poolABI = json.load(poolFile) with open("util/ERC20.json") as erc20File: ERC20ABI = json.load(erc20File) AVAX_HOST = os.environ.get('AVAX_HOST', '') AVAX_PORT = os.environ.get('AVAX_PORT', '') AVAX_HOST_TYPE = os.environ.get('AVAX_HOST_TYPE', '') if AVAX_HOST_TYPE in ['http', 'https']: provider_avax = Web3( Web3.HTTPProvider( f'{AVAX_HOST_TYPE}://{AVAX_HOST}:{AVAX_PORT}/ext/bc/C/rpc')) provider_avax.middleware_onion.inject(geth_poa_middleware, layer=0) elif AVAX_HOST_TYPE in ['ws', 'wss']: provider_avax = Web3( Web3.WebsocketProvider( f'{AVAX_HOST_TYPE}://{AVAX_HOST}:{AVAX_PORT}/ext/bc/C/rpc')) provider_avax.middleware_onion.inject(geth_poa_middleware, layer=0) usdtContract_address = '0x9ee0a4e21bd333a6bb2ab298194320b8daa26516' aablockContract_address = '0xfFc53c9d889B4C0bfC1ba7B9E253C615300d9fFD' def get_price_aablock(): def price(reserveToken0, reserveToken1, token0Address, token1Address): token0 = provider_avax.eth.contract( address=provider_avax.toChecksumAddress(token0Address), abi=ERC20ABI) token1 = provider_avax.eth.contract( address=provider_avax.toChecksumAddress(token1Address), abi=ERC20ABI)
def web3(geth_process, endpoint_uri, event_loop): event_loop.run_until_complete(wait_for_ws(endpoint_uri, event_loop)) _web3 = Web3(Web3.WebsocketProvider(endpoint_uri)) return _web3
provider_url = "wss://rinkeby.infura.io/ws/v3/6a3397d0a8394382a35037cadddfcafe" privateKey = "0xbab478afa30c6777b38200c546aeebbe8489c39a3da1287efa7e9d7ed707352e" def readAbi(fileName): f = open(fileName, "r") abi = json.loads(f.read()) f.close() return abi heater_bytecode = "60806040526000600160146101000a81548160ff0219169083151502179055506000600160156101000a81548160ff02191690831515021790555034801561004657600080fd5b50336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555061009561009b60201b60201c565b506101f3565b6000600160159054906101000a900460ff1615610120576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600e8152602001807f456e64656420636f6e747261637400000000000000000000000000000000000081525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614156101805760009050610193565b61018e61019660201b60201c565b600190505b90565b600160149054906101000a900460ff166101f15760018060146101000a81548160ff0219169083151502179055507fb6b49146609ca7b82407ba2c0a14cf5a9e1bf0bee2f279aadf259fa97ad20dab60405160405180910390a15b565b610cc5806102026000396000f3fe608060405234801561001057600080fd5b50600436106100cf5760003560e01c8063a094a0311161008c578063bb40b22211610066578063bb40b2221461022e578063f2fde38b14610262578063f33218cf146102a6578063fa52edb0146102c6576100cf565b8063a094a031146101aa578063a4fd6f56146101ca578063a9623874146101ea576100cf565b806304fa03f7146100d45780631bfcc5cf14610104578063200d2ed214610134578063544736e6146101525780636e9288b81461017257806386ec6177146101a0575b600080fd5b610102600480360360208110156100ea57600080fd5b8101908080351515906020019092919050505061030a565b005b6101326004803603602081101561011a57600080fd5b81019080803515159060200190929190505050610441565b005b61013c610578565b6040518082815260200191505060405180910390f35b61015a61057e565b60405180821515815260200191505060405180910390f35b61019e6004803603602081101561018857600080fd5b8101908080359060200190929190505050610591565b005b6101a8610668565b005b6101b2610684565b60405180821515815260200191505060405180910390f35b6101d2610779565b60405180821515815260200191505060405180910390f35b6102166004803603602081101561020057600080fd5b810190808035906020019092919050505061078c565b60405180821515815260200191505060405180910390f35b6102366107ac565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6102a46004803603602081101561027857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506107d2565b005b6102ae610951565b60405180821515815260200191505060405180910390f35b610308600480360360208110156102dc57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610964565b005b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff168073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146103ce576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260138152602001807f41646472657373206e6f7420616c6c6f7765640000000000000000000000000081525060200191505060405180910390fd5b81600460006101000a81548160ff0219169083151502179055507f035a685ae71650e5d7cfbf064aecfe6a6f7acd74594cce6d8ff83207494f0778600460009054906101000a900460ff1660405180821515815260200191505060405180910390a161043d6307a9b4d2610a72565b5050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff168073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610505576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260138152602001807f41646472657373206e6f7420616c6c6f7765640000000000000000000000000081525060200191505060405180910390fd5b81600460006101000a81548160ff0219169083151502179055507f035a685ae71650e5d7cfbf064aecfe6a6f7acd74594cce6d8ff83207494f0778600460009054906101000a900460ff1660405180821515815260200191505060405180910390a16105746307a9b4d2610a72565b5050565b60035481565b600160149054906101000a900460ff1681565b61059e6307a9b4d2610ad8565b610610576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600b8152602001807f4e6f7420656e61626c656400000000000000000000000000000000000000000081525060200191505060405180910390fd5b61061d6307a9b4d2610b02565b806003819055507f46433c07253205c5fe01c35f94b7c25cb443ed57b1992106613ed6263542374f6003546040518082815260200191505060405180910390a1610665610b68565b50565b60018060156101000a81548160ff021916908315150217905550565b6000600160159054906101000a900460ff1615610709576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600e8152602001807f456e64656420636f6e747261637400000000000000000000000000000000000081525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614156107695760009050610776565b610771610bf9565b600190505b90565b600160159054906101000a900460ff1681565b60026020528060005260406000206000915054906101000a900460ff1681565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610893576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260118152602001807f41646472657373206e6f742076616c696400000000000000000000000000000081525060200191505060405180910390fd5b61089c81610c56565b61090e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260118152602001807f41646472657373206e6f742076616c696400000000000000000000000000000081525060200191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600460009054906101000a900460ff1681565b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610a25576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260118152602001807f41646472657373206e6f742076616c696400000000000000000000000000000081525060200191505060405180910390fd5b80600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550610a6e610684565b5050565b60016002600083815260200190815260200160002060006101000a81548160ff0219169083151502179055507f062e0861d5487e926f5f2570e58d44c81580def7044c232ee0d939c4d2ba2259816040518082815260200191505060405180910390a150565b60006002600083815260200190815260200160002060009054906101000a900460ff169050919050565b60006002600083815260200190815260200160002060006101000a81548160ff0219169083151502179055507f470d577b826466531919b2b313ba7a913f56d9b6adcb14a1a20864553505ac5d816040518082815260200191505060405180910390a150565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663cbd7d6b96003546040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b158015610bdf57600080fd5b505af1158015610bf3573d6000803e3d6000fd5b50505050565b600160149054906101000a900460ff16610c545760018060146101000a81548160ff0219169083151502179055507fb6b49146609ca7b82407ba2c0a14cf5a9e1bf0bee2f279aadf259fa97ad20dab60405160405180910390a15b565b60008073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415905091905056fea2646970667358221220a4cce1c36f2abb4e79c0f63e8a116bb4307fc404efb20791655fe20433a826e764736f6c634300060c0033" sensor_bytecode = "60806040526000600160146101000a81548160ff0219169083151502179055506000600160156101000a81548160ff02191690831515021790555034801561004657600080fd5b50336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555061009561009b60201b60201c565b506101f3565b6000600160159054906101000a900460ff1615610120576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600e8152602001807f456e64656420636f6e747261637400000000000000000000000000000000000081525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614156101805760009050610193565b61018e61019660201b60201c565b600190505b90565b600160149054906101000a900460ff166101f15760018060146101000a81548160ff0219169083151502179055507fb6b49146609ca7b82407ba2c0a14cf5a9e1bf0bee2f279aadf259fa97ad20dab60405160405180910390a15b565b610c8c806102026000396000f3fe608060405234801561001057600080fd5b50600436106100ea5760003560e01c8063a4fd6f561161008c578063d1e485be11610066578063d1e485be14610255578063ed6050e51461025f578063f2fde38b14610269578063fa52edb0146102ad576100ea565b8063a4fd6f56146101bd578063a9623874146101dd578063bb40b22214610221576100ea565b806386ec6177116100c857806386ec61771461015b5780638cb15c7c146101655780639c3b861c1461016f578063a094a0311461019d576100ea565b80631e6b1df4146100ef578063544736e61461011d578063673402e51461013d575b600080fd5b61011b6004803603602081101561010557600080fd5b81019080803590602001909291905050506102f1565b005b610125610408565b60405180821515815260200191505060405180910390f35b61014561041b565b6040518082815260200191505060405180910390f35b610163610421565b005b61016d61043d565b005b61019b6004803603602081101561018557600080fd5b8101908080359060200190929190505050610468565b005b6101a5610577565b60405180821515815260200191505060405180910390f35b6101c561066c565b60405180821515815260200191505060405180910390f35b610209600480360360208110156101f357600080fd5b810190808035906020019092919050505061067f565b60405180821515815260200191505060405180910390f35b61022961069f565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61025d6106c5565b005b6102676106f0565b005b6102ab6004803603602081101561027f57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061071b565b005b6102ef600480360360208110156102c357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061089a565b005b61031a7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffc82119796109a8565b61038c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600b8152602001807f4e6f7420656e61626c656400000000000000000000000000000000000000000081525060200191505060405180910390fd5b6103b57fffffffffffffffffffffffffffffffffffffffffffffffffffffffffc82119796109d2565b806003819055507f0b544df78d286e8b03fd9c67a0b16ae6f1b3b4292a0d44f73163dc6e49d0f1a96003546040518082815260200191505060405180910390a16103fd61043d565b610405610a38565b50565b600160149054906101000a900460ff1681565b60035481565b60018060156101000a81548160ff021916908315150217905550565b6104667fffffffffffffffffffffffffffffffffffffffffffffffffffffffffc82119796109d2565b565b6104917ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdf8905c6109a8565b610503576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600b8152602001807f4e6f7420656e61626c656400000000000000000000000000000000000000000081525060200191505060405180910390fd5b61052c7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdf8905c6109d2565b806003819055507f0b544df78d286e8b03fd9c67a0b16ae6f1b3b4292a0d44f73163dc6e49d0f1a96003546040518082815260200191505060405180910390a1610574610ac9565b50565b6000600160159054906101000a900460ff16156105fc576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600e8152602001807f456e64656420636f6e747261637400000000000000000000000000000000000081525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141561065c5760009050610669565b610664610b5a565b600190505b90565b600160159054906101000a900460ff1681565b60026020528060005260406000206000915054906101000a900460ff1681565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6106ee7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffc8211979610bb7565b565b6107197ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdf8905c610bb7565b565b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146107dc576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260118152602001807f41646472657373206e6f742076616c696400000000000000000000000000000081525060200191505060405180910390fd5b6107e581610c1d565b610857576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260118152602001807f41646472657373206e6f742076616c696400000000000000000000000000000081525060200191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161461095b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260118152602001807f41646472657373206e6f742076616c696400000000000000000000000000000081525060200191505060405180910390fd5b80600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506109a4610577565b5050565b60006002600083815260200190815260200160002060009054906101000a900460ff169050919050565b60006002600083815260200190815260200160002060006101000a81548160ff0219169083151502179055507f470d577b826466531919b2b313ba7a913f56d9b6adcb14a1a20864553505ac5d816040518082815260200191505060405180910390a150565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166376a83d2c6003546040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b158015610aaf57600080fd5b505af1158015610ac3573d6000803e3d6000fd5b50505050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a97d32c46003546040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b158015610b4057600080fd5b505af1158015610b54573d6000803e3d6000fd5b50505050565b600160149054906101000a900460ff16610bb55760018060146101000a81548160ff0219169083151502179055507fb6b49146609ca7b82407ba2c0a14cf5a9e1bf0bee2f279aadf259fa97ad20dab60405160405180910390a15b565b60016002600083815260200190815260200160002060006101000a81548160ff0219169083151502179055507f062e0861d5487e926f5f2570e58d44c81580def7044c232ee0d939c4d2ba2259816040518082815260200191505060405180910390a150565b60008073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415905091905056fea2646970667358221220512960251a0d6c83e9d1f77e9694e7f5927875c4f8aeeff2e3769d0052f2bd5664736f6c634300060c0033" w3 = Web3(HTTPProvider(node_url)) web3 = Web3(Web3.WebsocketProvider(provider_url)) acct = w3.eth.account.privateKeyToAccount(privateKey) def deployNewSensor(thermostatAddress): print("New sensor deploying...") contracts = w3.eth.contract(bytecode=sensor_bytecode, abi=readAbi("sensor.json")) return deploy(contracts, thermostatAddress) def deployNewHeater(thermostatAddress): print("New heater deploying...") contract = w3.eth.contract(bytecode=heater_bytecode, abi=readAbi("heater.json")) return deploy(contract, thermostatAddress) def deploy(contract, thermostatAddress): deploy_hash = contract.constructor().buildTransaction({ 'from': acct.address,
from web3 import Web3 w3 = Web3(Web3.WebsocketProvider("ws://127.0.0.1:8545")) w3.eth.defaultAccount = w3.eth.accounts[0] contract_address = "0xba51fF67b9089a3Fef592d44ffD4E93Cd209309F" contract_abi = [ { "inputs": [ { "internalType": "string", "name": "domainName", "type": "string", }, { "internalType": "string", "name": "ip", "type": "string", }, ], "name": "agregarRegistro", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ { "internalType": "address payable", "name": "admin",
def createQuestion(): # contract address after deploy myContractAddress = "0xea54A06F8e74B72DF67B77b9D76046833757c165" # get abi from Data.json, get data from output_new_without_body.csv, collect url that makes error in errorQuestion.txt with open("./build/contracts/Data.json") as f, open( './Dataset/output_with_answer.csv', 'r', encoding="utf-8", errors='ignore') as csv_file, open('errorQuestion.txt', 'a') as text_file: info_json = json.load(f) abi = info_json["abi"] csv_reader = csv.reader(csv_file) # start at 0 count = 0 start = count skip = 0 url = None questionUrlFromAnswer = None questionString = None answerAtring = None linkList = [] transact = None # set up web3 connection with Ganache w3 = Web3( Web3.WebsocketProvider("ws://127.0.0.1:8545", websocket_kwargs={'timeout': 10000})) # read smart contract myContract = w3.eth.contract(address=myContractAddress, abi=abi) # set up default account to be sender w3.eth.defaultAccount = w3.eth.accounts[0] # for loop reading data for row in csv_reader: # 11465 if (count > 11465): break if (skip < start): skip += 1 continue url = row[0] questionUrlFromAnswer = row[8] # collect question link in list, and snippet file will use this list to check answer linkList.append(questionUrlFromAnswer) question = None answer = None if row[2]: # collect question data question = ({ 'url': row[0], 'questionTitle': row[1], 'viewCount': row[2], 'questionAuthor': row[3], 'questionEditor': row[4], 'questionCreationDate': int(row[5]), 'questionLastActivity': int(row[6]), 'questionLastModified': int(row[7]), 'questionUrlFromAnswer': row[8] }) # collect answer data answer = ({ 'questionUrlFromAnswer': row[8], 'answerBody': row[9], 'answerAuthor': row[10], 'answerEditor': row[11], 'answerCreationDate': row[12], 'answerLastActivity': row[13], 'answerLastModified': row[14], }) # convert from dictionary to string questionString = json.dumps(question) answerString = json.dumps(answer) # call function to store data on blockchain try: # if questionUrlFromAnswer equal to "", it is a question if (questionUrlFromAnswer == ""): transact = myContract.functions.createNewQuestion( url, questionUrlFromAnswer, questionString).transact() else: # it is an answer transact = myContract.functions.createNewQuestion( url, questionUrlFromAnswer, answerString).transact() # waiting for transaction to be mined w3.eth.waitForTransactionReceipt(transact) except asyncio.TimeoutError: # when timeout error occured, url will be written in textfile text_file.write(url + "\n") print('timeout!') # txn_receipt = w3.eth.getTransactionReceipt(transact) # collect transaction number in array transactionNumber = [] transactionNumber.append(w3.toHex(transact)) # print(transactionNumber) # print(txn_receipt['transactionHash']) print("info") print(count) count += 1 return linkList
def init(self): infuraProvider = Web3.WebsocketProvider(self.infuraURL) self.web3 = Web3(infuraProvider) self.locker = self.web3.eth.contract(address=Web3.toChecksumAddress( self.contractAddr), abi=self.contractAPi)
######################################## ### Module initialize section #### ######################################## logging.basicConfig( format= '%(asctime)s->%(levelname)s:[in %(filename)s:%(lineno)d]:%(message)s', level=int(os.environ.get('EXO_LOGLEVEL', logging.DEBUG))) #web3 provider initializing if ('http:'.upper() in settings.WEB3_PROVIDER.upper() or 'https:'.upper() in settings.WEB3_PROVIDER.upper()): w3 = Web3(HTTPProvider(settings.WEB3_PROVIDER)) elif ('ws:'.upper() in settings.WEB3_PROVIDER.upper() or 'wss:'.upper() in settings.WEB3_PROVIDER.upper()): w3 = Web3(Web3.WebsocketProvider(settings.WEB3_PROVIDER)) else: w3 = Web3(IPCProvider(settings.WEB3_PROVIDER)) # # !!!!!TODO try/except # try: logging.info('w3.eth.blockNumber=' + str(w3.eth.blockNumber)) w3.eth.defaultAccount = settings.ADDRESS_OPERATOR except Exception as e: logging.info('!!!!! w3.eth.blockNumber ERROR') # #Need some injection on Rinkeby and -dev networks # if w3.admin.nodeInfo['protocols']['eth']['network'] == 4: # from web3.middleware import geth_poa_middleware # w3.middleware_stack.inject(geth_poa_middleware, layer=0)
import hashlib import base64 from abis import lottery_abi, token_abi from boto3.dynamodb.conditions import Key from datadog_lambda.metric import lambda_metric from decimal import Decimal from ecdsa import SigningKey, SECP256k1 from inapppy import AppStoreValidator, InAppPyValidationError from typing import Any, Dict, Optional, Tuple from utils import configure_logging, get_secret, get_token_decimals, get_token_name, get_token_symbol, is_true from web3 import Web3 from asn1crypto.cms import ContentInfo w3 = Web3(Web3.WebsocketProvider(os.environ['WEB3_WEBSOCKET'], websocket_timeout=900)) configure_logging() def get_usd_per_oxt() -> float: r = requests.get(url="https://api.coinbase.com/v2/prices/OXT-USD/spot") data = r.json() logging.debug(data) usd_per_oxt = float(data['data']['amount']) logging.debug(f"usd_per_oxt: {usd_per_oxt}") return usd_per_oxt def get_product_id_mapping(store: str = 'apple') -> dict: mapping = {} mapping['apple'] = {
import time import threading import datetime import random from eth_account import Account from web3 import Web3 from web3.middleware import geth_poa_middleware file_config = 'conf/config.ini' config = configparser.ConfigParser() config.read(file_config) eth_cfg = config['rinkeby'] provider = Web3.WebsocketProvider(eth_cfg['ws_provider']) w3 = Web3(provider) w3.middleware_onion.inject(geth_poa_middleware, layer=0) def load_contract(): print(os.path.abspath(os.getcwd())) with open( os.path.join(os.path.abspath(os.getcwd()), eth_cfg['contract_address'] + '.json'), 'r') as f: contract = json.load(f) contract_address = eth_cfg['contract_address'] print(contract_address) return contract_address, contract
def test_websocket_max_size_error(self, web3, endpoint_uri): w3 = Web3( Web3.WebsocketProvider(endpoint_uri=endpoint_uri, websocket_kwargs={'max_size': 1})) with pytest.raises((OSError, ConnectionClosed)): w3.eth.getBlock(0)
#!/usr/bin/env python3 import web3 import json import time import requests from threading import Timer from web3 import Web3 from setup import WS_GETH, WS_INFURA, MY_TELEGRAM_ID, send_message, BONDING_MANAGER_PROXY, BONDING_MANAGER_ABI w3 = Web3(Web3.WebsocketProvider(WS_GETH)) ### # Variables ### poll_interval = 60 ### # Contracts, Filters & Classes ### bonding_manager_proxy = w3.eth.contract(address=BONDING_MANAGER_PROXY, abi=json.loads(BONDING_MANAGER_ABI)) class Transcoder: # Class Attributes, defaults to true in case script crashes -> no invalid warnings rewardCalled = True isActive = True
from base64 import b64decode, b64encode from binascii import hexlify, unhexlify from collections import defaultdict from hashlib import sha1 import requests from ethereum import utils from solc import compile_source from web3 import Web3 from config import * my_ipc = Web3.WebsocketProvider('wss://ropsten.infura.io/ws/v3/{}'.format(INFURA_PROJECT_ID)) assert my_ipc.isConnected() w3 = Web3(my_ipc) flag = open(FLAG_PATH).read() source = open(SOURCE_PATH).read() session = defaultdict(lambda : 'No address for this token') start_block = w3.eth.blockNumber - 86400 compiled_contract = compile_source(source)['<stdin>:{}'.format(CONTRACT_NAME)] base_contract = w3.eth.contract(abi=compiled_contract['abi'], bytecode=compiled_contract['bin']) # random def random_prefix(): return hexlify(os.urandom(3)).decode('utf8')
import json import time from web3 import Web3 w3 = Web3(Web3.WebsocketProvider("ws://localhost:9545")) with open('../build/contracts/Ticketing.json') as json_file: abiJson = json.load(json_file) contractAddress = '0x2ba3fE77842EA424f694c84D642d5189B6Eb168d' contract = w3.eth.contract(address=contractAddress, abi=abiJson['abi']) def handle_event(event): receipt = w3.eth.waitForTransactionReceipt(event['transactionHash']) print(receipt) def log_loop(event_filter, poll_interval): while True: for event in event_filter.get_all_entries(): handle_event(event) time.sleep(poll_interval)
from web3 import Web3 import json import time import mysql.connector import os from hexbytes import HexBytes contractAddress = '0x52B31871eFF4479ea7a71A12ea087DEbd33B2b01' w3 = Web3(Web3.WebsocketProvider("wss://rinkeby.infura.io/ws/v3/6d7880a8f4b347ca8953d2715e164241")) with open("contracts/contract.abi") as abi_file: abi = json.load(abi_file) contract = w3.eth.contract(address=contractAddress, abi=abi) disconnected = True print("====== ENV =======") print("host: " + os.getenv("DATABASE_HOST", default = 'localhost')) print("user: "******"DATABASE_USERNAME", default = 'test')) print("passwd: " + os.getenv("DATABASE_PASSWORD", default = 'test123')) print("database: " + os.getenv("DATABASE_NAME", default = 'test123')) print("") def handle_event(event): global disconnected, w3 receipt = w3.eth.waitForTransactionReceipt(event['transactionHash']) result = contract.events.InsertedRoot().processReceipt(receipt) try:
import random import json from web3 import Web3 # import json MAIN_URL = "https://mainnet.infura.io/v3/bb055071bba745488eda95512a6d0035" URL = 'https://8cf41633363c49a584fbfb0b556a5927.ropsten.rpc.rivet.cloud/' URL = 'wss://ropsten.infura.io/ws/v3/bb055071bba745488eda95512a6d0035' w3 = Web3(Web3.WebsocketProvider(URL)) # w3 = Web3(Web3.HTTPProvider(URL)) def _checking(_addr): ''' ورودی تابع ک استرینگ است که چک میشمود ایا ادرس معبتری هست یا خیر false یا addrress درنهایت خارح میشود ''' if not isinstance(_addr, str): print("ادرس بد وارد کردی باید یک استرینگ باشه") return False try: if not w3.isConnected(): print("نت مشکل داره ") return False addr_ = Web3.toChecksumAddress(_addr) if not _addr: print("ادرس بدی وارد کردی شرمنده تم") return False return addr_
from web3 import Web3 import pymongo store_address = "0x9F0353A38c2CCB09d3440B6a7D85cb61d59e882E" w3 = Web3(Web3.WebsocketProvider("ws://127.0.0.1:9000")) mongoClient = pymongo.MongoClient( "mongodb+srv://dbUser:[email protected]/<dbname>?retryWrites=true&w=majority" )
def w3_websocket(self, uri=None): from web3 import Web3 return Web3(Web3.WebsocketProvider(uri))
def send(): with open('erc20.json') as abi_json: tokenABI = json.load(abi_json) with open('data.json') as data_json: data = json.load(data_json) with open('bad.json') as bad_json: bad = json.load(bad_json) # Your address and pk that hold all of the new MKR address = Web3.toChecksumAddress('<address>') pk = '<your private key for above address>' dev = Web3.toChecksumAddress('<address of the dev fund>') # This is only for testing. We pull in balances from mainnet and redistribute on Goerli # For a real deploy you would only need one web3 = Web3(Web3.WebsocketProvider("<testnet wss url>")) web3Mainnet = Web3(Web3.WebsocketProvider("<mainnet wss url>")) # TODO figure out why the web3py call for nonce is broken nonce = 3048 # The mainnet MKR address oldMKR = Web3.toChecksumAddress( '0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2') # Your testnet deployed MKR address newMKR = Web3.toChecksumAddress('<MKR address>') old = web3Mainnet.eth.contract(abi=tokenABI, address=oldMKR) new = web3.eth.contract(abi=tokenABI, address=newMKR) block = int(data["block"]) total = 0 # Send the tokens to all users # Keeps a running total so we can make sure it does not fail for guy in data["people"]: if guy in bad["people"]: continue amt = old.functions.balanceOf( Web3.toChecksumAddress(guy)).call(block_identifier=block) if amt != 0: txn = new.functions.transfer( Web3.toChecksumAddress(guy), amt, ).buildTransaction({ 'chainId': 5, 'gas': 70000, 'gasPrice': Web3.toWei('2', 'gwei'), 'nonce': nonce, }) sgn = web3.eth.account.signTransaction(txn, private_key=pk) web3.eth.sendRawTransaction(sgn.rawTransaction) total += amt print("Sent " + str(amt) + " MKR to " + Web3.toChecksumAddress(guy) + " || " + str(total) + " MKR Total") nonce += 1 # Handle any tokens that are being stripped of bad actors in the system # TODO some cool redistribute logic instead of just sending to the dev fund takenMKR = badGuysTokens(bad, old, block) if (bad["action"] == "redistribute"): txn = new.functions.transfer( Web3.toChecksumAddress(dev), takenMKR, ).buildTransaction({ 'chainId': 5, 'gas': 70000, 'gasPrice': Web3.toWei('2', 'gwei'), 'nonce': nonce, }) sgn = web3.eth.account.signTransaction(txn, private_key=pk) web3.eth.sendRawTransaction(sgn.rawTransaction) total += takenMKR print("Sent " + str(takenMKR) + " MKR to " + Web3.toChecksumAddress(dev) + " || " + str(total) + " MKR Total") if (bad["action"] == "burn"): txn = new.functions.burn(takenMKR, ).buildTransaction({ 'chainId': 5, 'gas': 70000, 'gasPrice': Web3.toWei('2', 'gwei'), 'nonce': nonce, }) sgn = web3.eth.account.signTransaction(txn, private_key=pk) web3.eth.sendRawTransaction(sgn.rawTransaction) total += takenMKR print("Burned " + str(takenMKR) + " MKR || " + str(total) + " MKR Total")
from web3 import Web3 from solc import compile_source from web3.contract import ConciseContract w3 = Web3(Web3.WebsocketProvider("wss://ropsten.infura.io/ws/v3/032b2cbaaefc4ad5b7fc1a875fbed094", websocket_kwargs={'timeout': 60})) from eth_account import Account
from fog05 import FIMAPI from fog05_sdk.interfaces.FDU import FDU import uuid import json import sys import os import time from web3 import Web3, HTTPProvider, IPCProvider from web3.contract import ConciseContract blockchain_ip = "163.117.140.69" blockchain_port = "7545" web3 = Web3( Web3.WebsocketProvider("ws://" + blockchain_ip + ":" + blockchain_port)) abi_path = "../../smart-contracts/build/contracts/" with open(abi_path + "Federation.json") as c_json: contract_json = json.load(c_json) contract_abi = contract_json["abi"] contract_address = Web3.toChecksumAddress( '0xc76d33f788a17fe014b9E8D00505FA51F9804f97') Federation_contract = web3.eth.contract(abi=contract_abi, address=contract_address) coinbase = web3.eth.coinbase eth_address = web3.eth.accounts block_address = "" service_id = "" ####### README ######
def connect_w3_websocket(self, uri=None, kwargs={}): self.cleanout_w3() from web3 import Web3 return Web3(Web3.WebsocketProvider(uri, websocket_kwargs=kwargs))
import time import traceback from web3 import Web3 from arango import ArangoClient from web3.middleware import geth_poa_middleware import config db = ArangoClient(hosts=config.ARANGO_SERVER).db('_system') w3 = Web3(Web3.WebsocketProvider(config.SEED_GROUPS_WS_URL)) if config.SEED_GROUPS_WS_URL.count('rinkeby') > 0 or config.SEED_GROUPS_WS_URL.count('idchain') > 0: w3.middleware_onion.inject(geth_poa_middleware, layer=0) voting = w3.eth.contract(address=config.VOTING_ADDRESS, abi=config.VOTING_ABI) def get_action(vote_id): text = voting.events.StartVote.createFilter( fromBlock="0x0", argument_filters={'voteId': vote_id} ).get_all_entries()[0].args.metadata sections = [s.strip() for s in text.split('|')] name = sections[0].lower() if len(sections) > 0 else None if name not in ['grant seed status', 'revoke seed status']: print('{} is an invalid action'.format(name)) return None if ((name == 'grant seed status' and len(sections) != 5) or (name == 'revoke seed status' and len(sections) != 3)): print('"{}" is invalid action'.format(text)) return None group = sections[1]
def __init__(self, infura_key): self.w3 = Web3( Web3.WebsocketProvider( 'wss://mainnet.infura.io/ws/v3/{}'.format(infura_key)))
import numpy as np import os, json from web3 import Web3 chemin = os.path.join("sponsoring-pool_2020-10-14.tsv") C = np.loadtxt(chemin, dtype=np.str, delimiter="\t", skiprows=1) Wallets = C[:,0] ProviderAddr = 'wss://mainnet.infura.io/ws/v3/aaaaaaaaaaaaaa' w3 = Web3(Web3.WebsocketProvider(ProviderAddr)) # contract listContractCheck = [] listContractCheck.append(w3.toChecksumAddress("0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d")) listContractCheck.append(w3.toChecksumAddress("0x6Ee0f7BB50a54AB5253dA0667B0Dc2ee526C30a8")) listContractCheck.append(w3.toChecksumAddress("0x9ba00d6856a4edf4665bca2c2309936572473b7e")) listContractCheck.append(w3.toChecksumAddress("0x71fc860F7D3A592A4a98740e39dB31d25db65ae8")) listContractCheck.append(w3.toChecksumAddress("0x4da9b813057d04baef4e5800e36083717b4a0341")) listContractCheck.append(w3.toChecksumAddress( "0x625ae63000f46200499120b906716420bd059240")) # redirect Addresse RedirectAddr = "0x5ae7E199EC6ACfe1D7ee28401637a0AE897818c1" with open("ABI/atoken.json") as json_file: abiContract = json.load(json_file) lockUSD = 0 for wallet in Wallets: print(wallet) wallet2 = w3.toChecksumAddress(wallet) for addrContract in listContractCheck:
import os import socket import time import json import binascii import copy from arango import ArangoClient from web3 import Web3 import config w3 = Web3(Web3.WebsocketProvider(config.INFURA_URL)) db = ArangoClient(hosts=config.ARANGO_SERVER).db('_system') def sendTransaction(data): nonce = w3.eth.getTransactionCount(config.ADDRESS, 'pending') tx = { 'to': config.TO_ADDRESS, 'value': 0, 'gas': config.GAS, 'gasPrice': config.GAS_PRICE, 'nonce': nonce, 'chainId': w3.eth.chainId, 'data': data } signed = w3.eth.account.sign_transaction(tx, config.PRIVATE_KEY) tx = w3.eth.sendRawTransaction(signed.rawTransaction).hex() return tx def main():
1: '0xdAE7e32ADc5d490a43cCba1f0c736033F2b4eFca', 137: '0x0F3e0c4218b7b0108a3643cFe9D3ec0d4F57c54e', 42161: '0x751A0bC0e3f75b38e01Cf25bFCE7fF36DE1C87DE' } ORCHARD_CONFIGS_URL = 'https://raw.githubusercontent.com/balancer-labs/frontend-v2/master/src/services/claim/MultiTokenClaim.json' ORCHARD_CONFIGS = load_json_from_url(ORCHARD_CONFIGS_URL) ORCHARD_ABI_PATH = 'abi/MerkleOrchard.json' ORCHARD_ABI = load_json_from_path(ORCHARD_ABI_PATH) MINING_CONFIGS_PATH = 'js/src/config/liquidityMiningConfig.json' MINING_CONFIGS = load_json_from_path(MINING_CONFIGS_PATH) WEB3_PROVIDERS = { 1: Web3(Web3.WebsocketProvider(os.environ['ENDPOINT_URL'])), 137: Web3( Web3.WebsocketProvider(os.environ['ENDPOINT_URL'].replace( 'mainnet', 'polygon-mainnet'))), 42161: Web3( Web3.WebsocketProvider(os.environ['ENDPOINT_URL'].replace( 'mainnet', 'arbitrum-mainnet'))) } def get_token_configs(_network, _token_address, _distribution_id): _network = str(_network) network_config = ORCHARD_CONFIGS[_network] result = []
def handle(self, *args, **options): # Parse inputs what = options['what'] network = options['network'] process_all = options['process_all'] valid_whats = ['finalize', 'payout_test', 'prepare_final_payout', 'verify', 'set_payouts_test', 'set_payouts'] if what not in valid_whats: raise Exception(f"Invalid value {what} for 'what' arg") if network not in ['rinkeby', 'mainnet']: raise Exception(f"Invalid value {network} for 'network' arg") if not options['clr_round'] or not options['clr_pks']: raise Exception('Must provide clr_round and clr_pks') # Define parameters that vary by network. The expected total DAI amount uses the value here # if one is not available in the database from_block = 11466409 if network == 'mainnet' else 7731622 # block contract was deployed at dai_address = '0x6B175474E89094C44Da98b954EedeAC495271d0F' if network == 'mainnet' else '0x2e055eEe18284513B993dB7568A592679aB13188' expected_total_dai_amount = 100_000 if network == 'mainnet' else 5000 # in dollars, not wei, e.g. 500 = 500e18 # Get contract instances PROVIDER = "wss://" + network + ".infura.io/ws/v3/" + settings.INFURA_V3_PROJECT_ID w3 = Web3(Web3.WebsocketProvider(PROVIDER)) match_payouts = w3.eth.contract(address=match_payouts_address, abi=match_payouts_abi) dai = w3.eth.contract(address=dai_address, abi=erc20_abi) # Setup clr_round = options['clr_round'] clr_pks = options['clr_pks'].split(',') KYC_THRESHOLD = settings.GRANTS_PAYOUT_CLR_KYC_THRESHOLD # Get data gclrs = GrantCLR.objects.filter(pk__in=clr_pks) pks = [] for gclr in gclrs: pks += gclr.grants.values_list('pk', flat=True) scheduled_matches = CLRMatch.objects.filter(round_number=clr_round) grants = Grant.objects.filter(active=True, network='mainnet', is_clr_eligible=True, link_to_new_grant__isnull=True, pk__in=pks) print(f"got {grants.count()} grants") # Finalize rankings ------------------------------------------------------------------------ if what == 'finalize': total_owed_grants = 0 for grant in grants: try: for gclr in grant.clr_calculations.filter(grantclr__in=gclrs, latest=True): total_owed_grants += gclr.clr_prediction_curve[0][1] except: pass total_owed_matches = sum(sm.amount for sm in scheduled_matches) print(f"there are {grants.count()} grants to finalize worth ${round(total_owed_grants,2)}") print(f"there are {scheduled_matches.count()} Match Payments already created worth ${round(total_owed_matches,2)}") print('------------------------------') user_input = input("continue? (y/n) ") if user_input != 'y': return for grant in grants: amount = sum(ele.clr_prediction_curve[0][1] for ele in grant.clr_calculations.filter(grantclr__in=gclrs, latest=True)) has_already_kyc = grant.clr_matches.filter(has_passed_kyc=True).exists() if not amount: continue already_exists = scheduled_matches.filter(grant=grant).exists() if already_exists: continue needs_kyc = amount > KYC_THRESHOLD and not has_already_kyc comments = "" if not needs_kyc else "Needs KYC" ready_for_test_payout = not needs_kyc match = CLRMatch.objects.create( round_number=clr_round, amount=amount, grant=grant, comments=comments, ready_for_test_payout=ready_for_test_payout, ) if needs_kyc: grant_match_distribution_kyc(match) # Payout rankings (round must be finalized first) ------------------------------------------ if what in ['prepare_final_payout']: payout_matches = scheduled_matches.filter(ready_for_payout=False) payout_matches_amount = sum(sm.amount for sm in payout_matches) print(f"there are {payout_matches.count()} UNPAID Match Payments already created worth ${round(payout_matches_amount,2)} {network} DAI") print('------------------------------') user_input = input("continue? (y/n) ") if user_input != 'y': return for match in payout_matches: match.ready_for_payout=True match.save() print('promoted') # Set payouts (round must be finalized first) ---------------------------------------------- if what in ['set_payouts_test', 'set_payouts']: is_real_payout = what == 'set_payouts' kwargs = {} token_name = 'DAI' key = 'ready_for_test_payout' if not is_real_payout else 'ready_for_payout' kwargs[key] = False not_ready_scheduled_matches = scheduled_matches.filter(**kwargs) kwargs[key] = True kwargs2 = {} key2 = 'test_payout_tx' if not is_real_payout else 'payout_tx' kwargs2[key2] = '' unpaid_scheduled_matches = scheduled_matches.filter(**kwargs).filter(**kwargs2) paid_scheduled_matches = scheduled_matches.filter(**kwargs).exclude(**kwargs2) total_not_ready_matches = sum(sm.amount for sm in not_ready_scheduled_matches) total_owed_matches = sum(sm.amount for sm in unpaid_scheduled_matches) total_paid_matches = sum(sm.amount for sm in paid_scheduled_matches) print(f"there are {not_ready_scheduled_matches.count()} NOT READY Match Payments already created worth ${round(total_not_ready_matches,2)} {network} {token_name}") print(f"there are {unpaid_scheduled_matches.count()} UNPAID Match Payments already created worth ${round(total_owed_matches,2)} {network} {token_name}") print(f"there are {paid_scheduled_matches.count()} PAID Match Payments already created worth ${round(total_paid_matches,2)} {network} {token_name}") print('------------------------------') target_matches = unpaid_scheduled_matches if not process_all else scheduled_matches user_input = input("continue? (y/n) ") if user_input != 'y': return print(f"continuing with {target_matches.count()} unpaid scheduled payouts") if is_real_payout: user_input = input(F"THIS IS A REAL PAYOUT FOR {network} {token_name}. ARE YOU DOUBLE SECRET SUPER SURE? (y/n) ") if user_input != 'y': return # Generate dict of payout mapping that we'll use to set the contract's payout mapping full_payouts_mapping_dict = {} for match in target_matches.order_by('amount'): try: # Amounts to set recipient = w3.toChecksumAddress(match.grant.admin_address) amount = Decimal(match.amount) * SCALE # convert to wei # This ensures that even when multiple grants have the same receiving address, # all match funds are accounted for if recipient in full_payouts_mapping_dict.keys(): full_payouts_mapping_dict[recipient] += amount else: full_payouts_mapping_dict[recipient] = amount except Exception as e: print(f"could not payout grant:{match.grant.pk} bc exceptoin{e}") # Convert dict to array to use it as inputs to the contract full_payouts_mapping = [] for key, value in full_payouts_mapping_dict.items(): full_payouts_mapping.append([key, str(int(value))]) total_amount = sum(int(ele[1]) for ele in full_payouts_mapping) # In tests, it took 68,080 gas to set 2 payout values. Let's be super conservative # and say it's 50k gas per payout mapping. If we are ok using 6M gas per transaction, # that means we can set 6M / 50k = 120 payouts per transaction. So we chunk the # payout mapping into sub-arrays with max length of 120 each # KO 12/21 - edited with Matt to make 2.1x that def chunks(lst, n): """Yield successive n-sized chunks from lst. https://stackoverflow.com/a/312464""" for i in range(0, len(lst), n): yield lst[i:i + n] chunk_size = 250 if not settings.DEBUG else 120 chunked_payouts_mapping = chunks(full_payouts_mapping, chunk_size) # Set payouts from_address = settings.GRANTS_PAYOUT_ADDRESS from_pk = settings.GRANTS_PAYOUT_PRIVATE_KEY for payout_mapping in chunked_payouts_mapping: #tx = match_payouts.functions.setPayouts(payout_mapping).buildTransaction(tx_args) print(f"#TODO: Send this txn view etherscan {match_payouts_address}") print(json.dumps(payout_mapping)) # Pause until the next one print("SLEEPING") #time.sleep(WAIT_TIME_BETWEEN_TXS) print("DONE SLEEPING") user_input = input("continue? (y/n) ") if user_input != 'y': return tx_id = input("enter a txid: ") # All payouts have been successfully set, so now we update the database for match in target_matches.order_by('amount'): # make save state to DB if is_real_payout: match.payout_tx = tx_id match.payout_tx_date = timezone.now() grant_match_distribution_final_txn(match, True) else: match.test_payout_tx = tx_id match.test_payout_tx_date = timezone.now() #grant_match_distribution_test_txn(match) match.save() # create payout obj artifacts profile = Profile.objects.get(handle__iexact='gitcoinbot') validator_comment = f"created by ingest payout_round_script" subscription = Subscription() subscription.is_postive_vote = True subscription.active = False subscription.error = True subscription.contributor_address = 'N/A' subscription.amount_per_period = match.amount subscription.real_period_seconds = 2592000 subscription.frequency = 30 subscription.frequency_unit = 'N/A' subscription.token_address = dai_address subscription.token_symbol = token_name subscription.gas_price = 0 subscription.new_approve_tx_id = '0x0' subscription.num_tx_approved = 1 subscription.network = network subscription.contributor_profile = profile subscription.grant = match.grant subscription.comments = validator_comment subscription.amount_per_period_usdt = match.amount if is_real_payout else 0 subscription.save() contrib = Contribution.objects.create( success=True, tx_cleared=True, tx_override=True, tx_id=tx_id, subscription=subscription, validator_passed=True, validator_comment=validator_comment, ) print(f"ingested {subscription.pk} / {contrib.pk}") if is_real_payout: match.payout_contribution = contrib else: match.test_payout_contribution = contrib match.save() metadata = { 'id': subscription.id, 'value_in_token': str(subscription.amount_per_period), 'value_in_usdt_now': str(round(subscription.amount_per_period_usdt,2)), 'token_name': subscription.token_symbol, 'title': subscription.grant.title, 'grant_url': subscription.grant.url, 'num_tx_approved': subscription.num_tx_approved, 'category': 'grant', } kwargs = { 'profile': profile, 'subscription': subscription, 'grant': subscription.grant, 'activity_type': 'new_grant_contribution', 'metadata': metadata, } activity = Activity.objects.create(**kwargs) if is_real_payout: comment = f"CLR Round {clr_round} Payout" comment = Comment.objects.create(profile=profile, activity=activity, comment=comment) # Verify contract is set properly ---------------------------------------------------------- if what == 'verify': # Get expected total match amount total_owed_grants = 0 for grant in grants: try: for gclr in grant.clr_calculations.filter(grantclr__in=gclrs, latest=True): total_owed_grants += gclr.clr_prediction_curve[0][1] except: pass expected_total_dai_amount = sum(sm.amount for sm in scheduled_matches) # Get PayoutAdded events payout_added_filter = match_payouts.events.PayoutAdded.createFilter(fromBlock=from_block) payout_added_logs = payout_added_filter.get_all_entries() # print these if you need to inspect them # Sort payout logs by ascending block number, this way if a recipient appears in multiple blocks # we use the value from the latest block sorted_payout_added_logs = sorted(payout_added_logs, key=lambda log:log['blockNumber'], reverse=False) # Get total required DAI balance based on PayoutAdded events. Events will be sorted chronologically, # so if a recipient is duplicated we only keep the latest entry. We do this by storing our own # mapping from recipients to match amount and overwriting it as needed just like the contract would. # We keep another dict that maps the recipient's addresses to the block it was found in. If we find # two entries for the same user in the same block, we throw, since we don't know which is the # correct one payment_dict = {} user_block_dict = {} for log in sorted_payout_added_logs: # Parse parameters from logs recipient = log['args']['recipient'] amount = Decimal(log['args']['amount']) block = log['blockNumber'] # Check if recipient's payout has already been set in this block if recipient in user_block_dict and user_block_dict[recipient] == block: raise Exception(f'Recipient {recipient} payout was set twice in block {block}, so unclear which to use') # Recipient not seen in this block, so save data payment_dict[recipient] = amount user_block_dict[recipient] = block # Sum up each entry to get the total required amount total_dai_required_wei = sum(payment_dict[recipient] for recipient in payment_dict.keys()) # Convert to human units total_dai_required = total_dai_required_wei / SCALE # Verify that total DAI required (from event logs) equals the expected amount if round(expected_total_dai_amount, 0) != round(total_dai_required, 0): print('\n* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *') print('Total DAI payout amount in the contract does not equal the expected value!') print(' Total expected amount: ', expected_total_dai_amount) print(' Total amount from logs: ', total_dai_required) print('* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n') raise Exception('Total payout amount in the contract does not equal the expected value!') print('Total payout amount in the contracts is the expected value') # Get contract DAI balance dai_balance = Decimal(dai.functions.balanceOf(match_payouts_address).call()) / SCALE # Verify that contract has sufficient DAI balance to cover all payouts print('\n* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *') if dai_balance == total_dai_required: print(f'Contract balance of {dai_balance} DAI is exactly equal to the required amount') elif dai_balance < total_dai_required: shortage = total_dai_required - dai_balance print('Contract DAI balance is insufficient') print(' Required balance: ', total_dai_required) print(' Current balance: ', dai_balance) print(' Extra DAI needed: ', shortage) print(f'\n Contract needs another {shortage} DAI') elif dai_balance > total_dai_required: excess = dai_balance - total_dai_required print('Contract has excess DAI balance') print(' Required balance: ', total_dai_required) print(' Current balance: ', dai_balance) print(' Excess DAI amount: ', excess) print(f'\n Contract has an excess of {excess} DAI') print('* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n')
def web3(): config = Config().load(CONFIG) web3 = Web3(Web3.WebsocketProvider(config.Worker.Blockchain.URI)) yield web3
# scrapper settings ethurl = "https://etherscan.io/tx/" user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' headers = {'User-Agent': user_agent} # ERC20 / ERC721 tokens # Transfer(address,address,uint256) # Deposit(address, uint256) # Approval(address,address, uint256) SEARCH_METHOD_TRANSFER = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' SEARCH_METHOD_DEPOSIT = '0xaef05ca429cf234724843763035496132d10808feeac94ee79441c83b6dd519a' SEARCH_METHOD_APPROVAL = '0x7c3bc83eb61feb549a19180bb8de62c55c110922b2a80e511547cf8deda5b25a' PROVIDER = "wss://mainnet.infura.io/ws/v3/" + settings.INFURA_V3_PROJECT_ID w3 = Web3(Web3.WebsocketProvider(PROVIDER)) check_transaction = lambda txid: w3.eth.getTransaction(txid) check_amount = lambda amount: int(amount[75:], 16) if len(amount) == 138 else print (f"{bcolors.FAIL}{bcolors.UNDERLINE} {index_transaction} txid: {transaction_tax[:10]} -> status: 0 False - amount was off by 0.001 {bcolors.ENDC}") check_token = lambda token_address: len(token_address) == 42 check_contract = lambda token_address, abi : w3.eth.contract(token_address, abi=abi) check_event_transfer = lambda contract_address, search, txid : w3.eth.filter({ "address": contract_address, "topics": [search, txid]}) get_decimals = lambda contract : int(contract.functions.decimals().call()) # scrapes etherscan to get the replaced tx def getReplacedTX(tx): response = requests.get(ethurl + tx, headers=headers) soup = BeautifulSoup(response.content, "html.parser") # look for span that contains the dropped&replaced msg p = soup.find("span", "u-label u-label--sm u-label--warning rounded") if not p:
def web3(geth_process, endpoint_uri): event_loop = asyncio.new_event_loop() event_loop.run_until_complete(wait_for_ws(endpoint_uri)) _web3 = Web3(Web3.WebsocketProvider(endpoint_uri, websocket_timeout=30)) return _web3