Skip to content

Commit

Permalink
upd 03.12.2024
Browse files Browse the repository at this point in the history
  • Loading branch information
kate-aleksseeva committed Dec 3, 2024
1 parent f73f89a commit 12a58e8
Show file tree
Hide file tree
Showing 4 changed files with 141 additions and 66 deletions.
55 changes: 35 additions & 20 deletions scripts/comp_file.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import csv, os
from datetime import datetime
from pathlib import Path

from brownie import *
Expand All @@ -9,36 +10,50 @@
from utils.comp_print import *

def main():
print('Script execution started...')
print('Script execution has been started.')
print()

AccountingOracle_HashConsensus = "0xD624B08C83bAECF0807Dd2c6880C3154a5F0B288"
oracle = Contract(AccountingOracle_HashConsensus)
# I. Set values for variables
threshold_balance = "1 ether" # the Ether threshold value that triggers a decision to charge the user
target_balance = "1 ether" # the Ether amount up to which the accrual will be made
target_accrual = "1 ether" # the Ether amount for which the accrual will be made

target_balance = "1 ether"
filename = 'accrual_data.csv' # + тек дата время
accounting_oracle_hash_consensus_expected = "0xD624B08C83bAECF0807Dd2c6880C3154a5F0B288"

members_list = get_members_list(oracle)
members_info = get_members_info(members_list, target_balance)
accounting_oracle_proxy = Contract("0x852deD011285fe67063a08005c71a85690503Cee")
accounting_oracle_hash_consensus = Contract(accounting_oracle_proxy.getConsensusContract())

if accounting_oracle_hash_consensus!=accounting_oracle_hash_consensus_expected:
print('AccountingOracle HashConsensus address has changed since the last script execution.')
print('Please, make sure that the correct addresses are used.')

# II. Collect members info
print('Members info will be collected using')
print('accounting_oracle_proxy:', accounting_oracle_proxy)
print('accounting_oracle_hash_consensus:', accounting_oracle_hash_consensus)

members_list = get_oracle_members_list(accounting_oracle_hash_consensus)
members_info = get_oracle_members_info(members_list, threshold_balance=threshold_balance, target_accrual=target_accrual)
print_members_info(members_info, 'All members')

members_info_filtered = filter_members_info(members_info)

# III. Сheck the need for a transfer
if len(members_info_filtered) != 0:
print_members_info(members_info_filtered, 'Filtered members')
print('Write to file?')
answer = input('Enter "yes" or "no": ').strip().lower()
if answer == 'yes':
write_to_file_accruals(filename, members_info_filtered)
elif answer == 'no':
print()
else:
print('Incorrect input')
else:
print('There are no users requiring fund accrual.')
print('Script execution has been completed.')
return 0

# IV. Write info to file
print('Write to file?')
answer = input('Enter "yes" or "no": ').strip().lower()
if answer == 'yes':
write_to_file_accruals(members_info_filtered)
elif answer == 'no':
print()
else:
print('Incorrect input')

print('Script execution completed...')

# todo - посмотреть есть ли адрес hash consensus в proxy accounting oracle, поменять, если можно получить
# сделать выравнивание баланса по правому краю или точке (для эфиров)
# начислять по одному эфиру
print('Script execution has been completed.')
83 changes: 51 additions & 32 deletions scripts/comp_transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,60 +11,79 @@
from utils.comp_print import *

def main():

print('Script execution started...')
print('Script execution has been started.')
print()

AccountingOracle_HashConsensus = "0xD624B08C83bAECF0807Dd2c6880C3154a5F0B288"
# получать адрес из метода getConsensusContract
# https: // etherscan.io / address / 0x852deD011285fe67063a08005c71a85690503Cee # readProxyContract#F14
oracle = Contract(AccountingOracle_HashConsensus)
# I. Set values for variables
wallet_address = "0x12a43b049A7D330cB8aEAB5113032D18AE9a9030"
wallet_safe = BrownieSafe('0x12a43b049A7D330cB8aEAB5113032D18AE9a9030')

threshold_balance = "1 ether" # the Ether threshold value that triggers a decision to charge the user
target_balance = "1 ether" # the Ether amount up to which the accrual will be made
target_accrual = "1 ether" # the Ether amount for which the accrual will be made

accounting_oracle_hash_consensus_expected = "0xD624B08C83bAECF0807Dd2c6880C3154a5F0B288"

accounting_oracle_proxy = Contract("0x852deD011285fe67063a08005c71a85690503Cee")
accounting_oracle_hash_consensus = Contract(accounting_oracle_proxy.getConsensusContract())

if accounting_oracle_hash_consensus != accounting_oracle_hash_consensus_expected:
print('AccountingOracle HashConsensus address has changed since the last script execution.')
print('Please, make sure that the correct addresses are used.')

target_balance = "1 ether"
filename = 'accrual_data.csv'
# II. Collect members info
print('Members info will be collected using')
print('accounting_oracle_proxy:', accounting_oracle_proxy)
print('accounting_oracle_hash_consensus:', accounting_oracle_hash_consensus)

members_list = get_members_list(oracle)
members_info = get_members_info(members_list, target_balance)
members_list = get_oracle_members_list(accounting_oracle_hash_consensus)
members_info = get_oracle_members_info(members_list, threshold_balance=threshold_balance, target_accrual=target_accrual)
print_members_info(members_info, 'All members')

members_info_filtered = filter_members_info(members_info)

# network.connect('mainnet')
# safe = BrownieSafe('ychad.eth') # ENS or Safe address

wallet_address = "0x12a43b049A7D330cB8aEAB5113032D18AE9a9030"
wallet_acc = accounts.at(wallet_address, force=True) # из тестов
# III. Сheck the need for a transfer
if len(members_info_filtered) != 0:
print_members_info(members_info_filtered, 'Filtered members')
else:
print('There are no users requiring fund accrual.')
print('Script execution has been completed.')
return 0

# IV. Collect wallet info
wallet_info = get_wallet_info(wallet_address)
print_wallet_info(wallet_info)
# wallet_account = accounts.at(wallet_address, force=True)

total_accrual_wei, total_accrual_eth = get_total_accrual(members_info_filtered)
print_total_accrual(total_accrual_wei, total_accrual_eth)

total_accrual_wei = 28910251107265401 # for tests

# V. Check wallet balance
try:
if total_accrual_wei > wallet_info['wallet_balance_wei']:
raise Exception(
f"Insufficient funds for accrual, wallet balance - {wallet_info['wallet_balance_eth']}, needed - {total_accrual_eth}.")

except Exception as e:
print(f"Error massage: {e}")

# VI. Create and send transactions
txns = create_transactions(members_info_filtered)
print_txns(txns)

print('Send transactions?')
answer = input('Enter "yes" or "no": ').strip().lower()
if answer == 'yes':
print("Sending transactions...")
send_transactions(txns)
print("Multicall transaction sent to fund accounts.")
elif answer == 'no':
print("Sending transactions has been canceled.")
print('Script execution was interrupted .')
return 0
else:
txns = create_transactions(members_info_filtered)
print_txns(txns)

print('Send transactions?')
answer = input('Enter "yes" or "no": ').strip().lower()

if answer == "yes":
print("Sending transactions...")
send_transactions(txns)
print("Multicall transaction sent to fund accounts.")
print('Script execution complete.')
elif answer == "no":
print("Sending transactions has been canceled.")
print('Script execution was interrupted .')
else:
print("Incorrect input.")
print('Incorrect input')
return 0

print('Script execution has been completed.')
50 changes: 38 additions & 12 deletions utils/comp_helpers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import csv, os
from datetime import datetime
from pathlib import Path

from brownie import *
Expand All @@ -7,21 +8,33 @@

from utils.comp_print import *

def get_members_list(address): # изменить название на get oracle members, либо hash consensus members
# внутри метода сделать получиние данных из прокси возможно
def get_oracle_members_list(address):
members_list = address.getMembers()[0]
return members_list

def get_members_info(members_list, target_balance):
def get_oracle_members_info(members_list, threshold_balance, target_balance=None, target_accrual=None):

if target_balance is None and target_accrual is None:
raise ValueError("You must provide either 'target_balance' or 'target_accrual'.")

members_info = []
for item in members_list:

balance_wei = get_balance_in_wei(item)
balance_eth = wei_to_eth(balance_wei)
accrual_flag = balance_wei < target_balance
accrual_wei = 0 # упростить конструкцию, может в одну строку можно
if accrual_flag:
accrual_wei = Wei(target_balance) - balance_wei
accrual_eth = wei_to_eth(Wei(accrual_wei))

accrual_flag = balance_wei < Wei(threshold_balance)

accrual_wei = (
Wei(target_balance)-balance_wei if accrual_flag and target_balance is not None and balance_wei < target_balance
else Wei(target_accrual) if accrual_flag and target_accrual is not None
else 0
)
accrual_eth = (
wei_to_eth(Wei(accrual_wei)) if accrual_wei
else 0
)

members_info.append(
{
"address": item,
Expand All @@ -32,6 +45,7 @@ def get_members_info(members_list, target_balance):
"accrual_eth": accrual_eth,
}
)

return members_info

def filter_members_info(members_info):
Expand Down Expand Up @@ -83,9 +97,19 @@ def get_balance_in_wei(address):
balance = Wei(web3.eth.get_balance(address))
return balance

def write_to_file_accruals(filename, members_info):
field_names = ["token_type", "token_address", "receiver", "amount"]
def write_to_file_accruals(members_info):

current_date_iso_format = datetime.now().isoformat()
filename = "oracle_members_accrual_data_" + str(current_date_iso_format) + ".csv"

data = []

field_names = ["token_type",
"token_address",
"receiver",
"amount"
]

for item in members_info:
row = {
"token_type": "native",
Expand All @@ -94,16 +118,18 @@ def write_to_file_accruals(filename, members_info):
"amount": item['accrual_eth']
}
data.append(row)

with open(filename, mode='w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=field_names)
writer.writeheader()
writer.writerows(data)

print(f"A CSV-file has been created: '{filename}'")
file_path = Path(filename).resolve()
if not file_path.is_file():
print(f"File '{filename}' does not exist.")
return
file_link = f"file://{file_path}"
print(f"Absolute path: {file_path}")
print(f"Clickable link: {file_link}")
print(f"Path: {file_path}")
print(f"Link: {file_link}")
print()
19 changes: 17 additions & 2 deletions utils/comp_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,23 @@
from brownie import web3
from brownie import convert

import utils.comp_helpers
from utils.comp_helpers import *

def print_members_info(members_info, header):
column_names = ["#", "address", "balance_wei", "balance_eth", "accrual_flag", "accrual_wei", "accrual_eth"]
column_widths = {col: len(col) for col in column_names}

alignments = {
"#": "ljust",
"address": "ljust",
"balance_wei": "rjust",
"balance_eth": "rjust",
"accrual_flag": "ljust",
"accrual_wei": "rjust",
"accrual_eth": "rjust",
}

for idx, item in enumerate(members_info, start=1):
column_widths["#"] = max(column_widths["#"], len(str(idx)))
for col in column_names[1:]:
Expand All @@ -24,8 +35,12 @@ def print_members_info(members_info, header):
print(separator_row)

for idx, item in enumerate(members_info, start=1):
row = f"{str(idx).ljust(column_widths['#'])} | " + " | ".join(
f"{str(item[col]).ljust(column_widths[col])}" for col in column_names[1:]
row = (
f"{str(idx).ljust(column_widths['#'])} | " + " | ".join(
f"{str(item[col]).ljust(column_widths[col])}" if alignments[col] == "ljust"
else f"{str(item[col]).rjust(column_widths[col])}"
for col in column_names[1:]
)
)
print(row)

Expand Down

0 comments on commit 12a58e8

Please sign in to comment.