import os, sys, time _PATH = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) sys.path.append(_PATH) from web3 import Web3 from util import extract_key_from_keyfile, compile_contract, get_contract from account import account from Coin import mint, send, get_balance # w3 = Web3(Web3.IPCProvider("./blockchain/geth.ipc")) w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545')) account_list = [] password = ['coinbase', 'n1', 'n2'] address = [ '0x2C749426ff936a1B522fFdc8dcBf9eb8d78b3D00', '0x0697875dc0ae871809f049211d85b939b7B75A75', '0xdB66F629495c5B1d17d28A35ccEd5ECB6F494BD3' ] contract_address = "0x9066fb184a051382a4773B15416C39AD41E35E27" for i in range(len(password)): privKey = extract_key_from_keyfile( _PATH + '/keyFile/' + password[i] + '.json', password[i].encode()) account_list.append(account(privKey, address[i])) w3.geth.miner.setEtherbase(account_list[0].address) w3.geth.miner.start(1) contract_interface = compile_contract('../smartContract/Coin.sol', "Coin") contract = get_contract(w3, contract_address, contract_interface['abi'])
class Token: ABI: str = None address: str = None name: str = None symbol: str = None decimals = None total_supply = None class Wallet: address: str = None private_key = None balance = None w3 = Web3(Web3.HTTPProvider("https://ropsten.infura.io/v3/address")) new_account = Account.create("account") token = Token() with open("ABI.json", "r") as data: token.ABI = json.load(data) token.address = "token.address" contract = w3.eth.contract(token.address, abi=token.ABI) token.name = contract.functions.name().call() token.symbol = contract.functions.symbol().call() token.decimals = contract.functions.decimals().call() token.total_supply = contract.functions.totalSupply().call() print(token.address, token.name, token.symbol, token.decimals,
def main(number_of_drones, number_of_voters, simulation_ratio, number_of_cycles, k, theta): web3 = Web3(Web3.HTTPProvider(truffle_url)) accounts = web3.eth.accounts compiled_custodian_path = 'build/contracts/Custodian.json' compiled_vehicle_path = 'build/contracts/VehicleOracle.json' compiled_request_path = 'build/contracts/RequestOracle.json' with open(compiled_custodian_path) as file: custodian_json = json.load(file) custodian_abi = custodian_json['abi'] custodian_byte = custodian_json['bytecode'] with open(compiled_vehicle_path) as file: vehicle_json = json.load(file) vehicle_abi = vehicle_json['abi'] vehicle_byte = vehicle_json['bytecode'] with open(compiled_request_path) as file: request_json = json.load(file) request_abi = request_json['abi'] request_byte = request_json['bytecode'] Custodian = web3.eth.contract(abi=custodian_abi,bytecode=custodian_byte) Vehicle = web3.eth.contract(abi=vehicle_abi,bytecode=vehicle_byte) Request = web3.eth.contract(abi=request_abi,bytecode=request_byte) tx_hash = Custodian.constructor().transact({'from':web3.eth.accounts[0]}) # wait for mining trans_receipt = web3.eth.getTransactionReceipt(tx_hash) # get the contract address custodian_address = trans_receipt['contractAddress'] # now we can instantiate the contract factory to get an instance of the contract. custodian = Custodian(custodian_address) tx_hash = Vehicle.constructor(custodian_address).transact({'from':web3.eth.accounts[0]}) # wait for mining trans_receipt = web3.eth.getTransactionReceipt(tx_hash) # get the contract address vehicle_address = trans_receipt['contractAddress'] # now we can instantiate the contract factory to get an instance of the contract. vehicle = Vehicle(vehicle_address) tx_hash = Request.constructor(custodian_address).transact({'from':web3.eth.accounts[0]}) # wait for mining trans_receipt = web3.eth.getTransactionReceipt(tx_hash) # get the contract address request_address = trans_receipt['contractAddress'] # now we can instantiate the contract factory to get an instance of the contract. request = Request(request_address) # Custodian interfaces tx_hash = custodian.functions.setReqCon(request_address).transact({'from':accounts[0]}) web3.eth.waitForTransactionReceipt(tx_hash) tx_hash = custodian.functions.setVehCon(vehicle_address).transact({'from':accounts[0]}) web3.eth.waitForTransactionReceipt(tx_hash) # VEHICLES INITIALIZATION drones_accounts = accounts[1:number_of_drones+1] positions = [Position(np.random.randint(map_size[0],map_size[1]),np.random.randint(map_size[2],map_size[3])) for _ in range(number_of_drones)] max_volume = Volume(10,10,10) drones = [] t_drones = [] for i in range(number_of_drones): drones.append(Drone(positions[i], 10, max_volume, int(1e9), 15, 45, 30, drones_accounts[i], vehicle, request, custodian)) # Add vehicle vehicle.functions.addKnownVehicle(drones_accounts[i]).transact({'from':accounts[0]}) t_drones.append(threading.Thread(target=move, args=(drones[i], web3, simulation_ratio, number_of_cycles))) for t in t_drones: t.daemon = True t.start() # SOURCE INITIALIZATION tx_hash = request.functions.setNewSource(accounts[number_of_drones + 1]).transact({'from':accounts[0]}) web3.eth.waitForTransactionReceipt(tx_hash) t_source = threading.Thread(target=source, args=(accounts[number_of_drones + 1], map_size, request, web3, simulation_ratio, number_of_cycles, k, theta)) t_source.daemon = True t_source.start() # VOTERS INITIALIZATION cycle = 45 * 60 # The voter have a 45 minutes cycle value = custodian.functions.getInitial_Deposit().call() voters_accounts = accounts[number_of_drones+2 : number_of_drones+number_of_voters+3] t_voters = [] for i in range(number_of_voters): # Add voter tx_hash = custodian.functions.addVoter(voters_accounts[i]).transact({'from':accounts[0]}) web3.eth.waitForTransactionReceipt(tx_hash) # Enable voter tx_hash = custodian.functions.enableVoter().transact({'from':voters_accounts[i], 'value':value}) web3.eth.waitForTransactionReceipt(tx_hash) t_voters.append(threading.Thread(target=vote, args=(voters_accounts[i], map_size, custodian, request, vehicle, cycle, 30, 6, web3, simulation_ratio, number_of_cycles))) for t in t_voters: t.daemon = True t.start() balance = computeFullBalance(web3, accounts, vehicle_address, request_address, custodian_address) sleep(k*theta/simulation_ratio * 4) # waits on average for 4 requests custodian.functions.unsafeFirstCycle().transact({'from':accounts[0]}) # PRINT THE BLOCKCHAIN EVENTS' EVOLUTION counter_VoteCampFinished = 0 counter_disputeRaised = 0 counter_disputeEnded = 0 filter_VoteCampFinished=custodian.events.VoteCampFinished.createFilter(fromBlock=0, toBlock='latest') filter_disputeRaised=custodian.events.DisputeRaised.createFilter(fromBlock=0, toBlock='latest') filter_disputeEnded=custodian.events.DisputeEnded.createFilter(fromBlock=0, toBlock='latest') eth_spent = 0 while True: event_VoteCampFinished = filter_VoteCampFinished.get_all_entries() if len(event_VoteCampFinished) > counter_VoteCampFinished: print('-----------WINNER------------') for i in range(counter_VoteCampFinished, len(event_VoteCampFinished)): print(event_VoteCampFinished[i]['args']) counter_VoteCampFinished = len(event_VoteCampFinished) event_disputeRaised = filter_disputeRaised.get_all_entries() if len(event_disputeRaised) > counter_disputeRaised: print('-----------DISPUTE------------') for i in range(counter_disputeRaised, len(event_disputeRaised)): print(event_disputeRaised[i]['args']) counter_disputeRaised = len(event_disputeRaised) event_disputeEnded = filter_disputeEnded.get_all_entries() if len(event_disputeEnded) > counter_disputeEnded: print('-----------DISPUTE SOLVED------------') for i in range(counter_disputeEnded, len(event_disputeEnded)): print(event_disputeEnded[i]['args']) counter_disputeEnded = len(event_disputeEnded) new_balance = computeFullBalance(web3, accounts, vehicle_address, request_address, custodian_address) cost = (balance - new_balance) / 10**18 eth_spent += cost print(cost,'ether were spent') balance = new_balance sleep(10) if len(event_VoteCampFinished) > 0 and event_VoteCampFinished[-1]['args']['seq'] >= number_of_cycles: break print('An average of ',eth_spent/number_of_cycles,'where spent')
def __init__(self, node_url): self.node_url = node_url self.web3 = Web3(Web3.HTTPProvider(self.node_url)) self.abi = None
from web3 import Web3 from eth_utils.curried import keccak from eth_abi import (encode_abi, decode_single) from hexbytes import HexBytes from web3.utils.encoding import to_hex import json, sys w3 = Web3(Web3.HTTPProvider('http://localhost:8545')) accounts = w3.eth.accounts artifact = 'EzToken' fn_abi = './contract/build/{0}.abi'.format(artifact) fn_addr = './contract/build/{0}.addr'.format(artifact) with open(fn_abi, 'r') as f: abi = json.load(f) with open(fn_addr, 'r') as f: addr = f.read() def rpc_balanceOf(address): func_hash = keccak(text='balanceOf(address)') selector = func_hash[:4] encoded_params = encode_abi(['address'], [address]) tx_data = to_hex(HexBytes(selector) + encoded_params) payload = {'to': addr, 'data': tx_data} ret = w3.eth.call(payload)
def setup(self): self.w3 = Web3( Web3.HTTPProvider(self.provider, request_kwargs={"timeout": 60}))
from web3 import Web3 web3 = Web3(Web3.HTTPProvider("https://ropsten.infura.io")) class Net: def Main(): return { "mongo": "mongodb://192.168.51.202:27017", #"net":"http://192.168.51.203:9999", #"net":"http://127.0.0.1:9999", "net": "http://192.168.51.203:19999", "contract": Web3.toChecksumAddress( "0xfB05FF4F0cA7940ED801AA164af81D40cB567a7F") } def Ropsten(): return { "net": "https://ropsten.infura.io/", #"contract": Web3.toChecksumAddress("0x103d7643540dd48800d97a29048a7058542680dbc6b105c98f469d5f3862c3ec") "contract": Web3.toChecksumAddress( "0xfB05FF4F0cA7940ED801AA164af81D40cB567a7F") } def Testrpc(): return { "net":
import os import json import time import pprint import sqlite3 import secrets import threading from web3 import Web3 from web3.middleware import geth_poa_middleware from web3.providers.eth_tester import EthereumTesterProvider # link to quorum quorum_url = "http://127.0.0.1:7545" web3 = Web3(Web3.HTTPProvider(quorum_url)) # web3.middleware_onion.inject(geth_poa_middleware, layer=0) # web3.eth.defaultAccount = web3.eth.accounts[1] # web3.parity.personal.unlock_account(web3.eth.accounts[0], "123", 15000) gov_acct = web3.eth.accounts[2] """EO之一: - 2個listener: 聽whitelist 生成 event、聽exchange_result event - 負責matching - matching完把結果丟到白名單合約 """ def db_link(): # link to DB db_url = r'/Users/ariel/Documents/sqlite/quorum.db' db_conn = sqlite3.connect(db_url)
from web3 import Web3 import sys provider = Web3.HTTPProvider("http://parity:8545", request_kwargs={'timeout': 60}) myweb3 = Web3(provider) #print(sys.argv[1]) #acct = myweb3.eth.account.create() #to_write = open(str(sys.argv[1]), "w") #to_write.write(str(acct.privateKey)) keyfile = open("dev.key", "r") key = keyfile.read() account = myweb3.eth.account.privateKeyToAccount(key) print("address: " + str(account.address)) print(myweb3.eth.getBalance(account.address)) #account = myweb3.eth.account.privateKeyToAccount(hex(key))
def w3_with_gas_strategy(web3_server): w3 = Web3(Web3.HTTPProvider(web3_server)) setup_gas_strategy(w3, 60) return w3
import secrets import sys try: # Open current round details f = open("roundDetails.txt", "r") rawDigits = f.readline() roundKey = f.readline() concatCode = f.readline() concatEncrypt = f.readline() f.close() except IOError: print('Previous round details are not accessible') # Setup Infura parameters infura_provider = Web3.HTTPProvider('INFURA_DETAILS_HERE') w3 = Web3(infura_provider) # Setup contract/Whitelist parameters contract_address = "DEPLOYED_CONTRACT_HERE" resolver_address = 'LOCAL_ETH_ADDRESS_HERE' resolver_pk = 'LOCAL_ETH_ACCOUNT_PK_HERE' # Contract ABI and setup my_abi = [{ "constant": 'false', "inputs": [{ "name": "_A", "type": "uint256" }, {
def w3(web3_server): return Web3(Web3.HTTPProvider(web3_server))
SPDX-License-Identifier: Apache-2.0 """ from eth_utils import to_checksum_address from web3 import Web3 from web3.middleware import geth_poa_middleware from app.model import Listing from app import config from app.contracts import Contract from .account_config import eth_account from .contract_modules import (issue_share_token, register_share_list, register_share_reference_url, invalidate_share_token) web3 = Web3(Web3.HTTPProvider(config.WEB3_HTTP_PROVIDER)) web3.middleware_onion.inject(geth_poa_middleware, layer=0) class TestV2TokenShareTokenDetails: """ Test Case for v2.token.ShareTokenDetails """ # テスト対象API apiurl_base = '/v2/Token/Share/' # {contract_address} @staticmethod def share_token_attribute(exchange_address, personal_info_address): attribute = { 'name': 'テスト株式',
import json import requests import time import os import warnings #source: https://paohuee.medium.com/interact-binance-smart-chain-using-python-4f8d745fe7b7 from web3 import Web3 warnings.filterwarnings("ignore", message="divide by zero encountered in divide") web3 = Web3(Web3.HTTPProvider("https://bsc-dataseed.binance.org/")) print(web3.isConnected()) pair_abi = "" pancakeSwapAbi = '[{"inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_WETH","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"WETH","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenA","type":"address"},{"internalType":"address","name":"tokenB","type":"address"},{"internalType":"uint256","name":"amountADesired","type":"uint256"},{"internalType":"uint256","name":"amountBDesired","type":"uint256"},{"internalType":"uint256","name":"amountAMin","type":"uint256"},{"internalType":"uint256","name":"amountBMin","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"addLiquidity","outputs":[{"internalType":"uint256","name":"amountA","type":"uint256"},{"internalType":"uint256","name":"amountB","type":"uint256"},{"internalType":"uint256","name":"liquidity","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountTokenDesired","type":"uint256"},{"internalType":"uint256","name":"amountTokenMin","type":"uint256"},{"internalType":"uint256","name":"amountETHMin","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"addLiquidityETH","outputs":[{"internalType":"uint256","name":"amountToken","type":"uint256"},{"internalType":"uint256","name":"amountETH","type":"uint256"},{"internalType":"uint256","name":"liquidity","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"reserveIn","type":"uint256"},{"internalType":"uint256","name":"reserveOut","type":"uint256"}],"name":"getAmountIn","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"reserveIn","type":"uint256"},{"internalType":"uint256","name":"reserveOut","type":"uint256"}],"name":"getAmountOut","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"}],"name":"getAmountsIn","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"}],"name":"getAmountsOut","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountA","type":"uint256"},{"internalType":"uint256","name":"reserveA","type":"uint256"},{"internalType":"uint256","name":"reserveB","type":"uint256"}],"name":"quote","outputs":[{"internalType":"uint256","name":"amountB","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"tokenA","type":"address"},{"internalType":"address","name":"tokenB","type":"address"},{"internalType":"uint256","name":"liquidity","type":"uint256"},{"internalType":"uint256","name":"amountAMin","type":"uint256"},{"internalType":"uint256","name":"amountBMin","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"removeLiquidity","outputs":[{"internalType":"uint256","name":"amountA","type":"uint256"},{"internalType":"uint256","name":"amountB","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"liquidity","type":"uint256"},{"internalType":"uint256","name":"amountTokenMin","type":"uint256"},{"internalType":"uint256","name":"amountETHMin","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"removeLiquidityETH","outputs":[{"internalType":"uint256","name":"amountToken","type":"uint256"},{"internalType":"uint256","name":"amountETH","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"liquidity","type":"uint256"},{"internalType":"uint256","name":"amountTokenMin","type":"uint256"},{"internalType":"uint256","name":"amountETHMin","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"removeLiquidityETHSupportingFeeOnTransferTokens","outputs":[{"internalType":"uint256","name":"amountETH","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"liquidity","type":"uint256"},{"internalType":"uint256","name":"amountTokenMin","type":"uint256"},{"internalType":"uint256","name":"amountETHMin","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bool","name":"approveMax","type":"bool"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"removeLiquidityETHWithPermit","outputs":[{"internalType":"uint256","name":"amountToken","type":"uint256"},{"internalType":"uint256","name":"amountETH","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"liquidity","type":"uint256"},{"internalType":"uint256","name":"amountTokenMin","type":"uint256"},{"internalType":"uint256","name":"amountETHMin","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bool","name":"approveMax","type":"bool"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"removeLiquidityETHWithPermitSupportingFeeOnTransferTokens","outputs":[{"internalType":"uint256","name":"amountETH","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenA","type":"address"},{"internalType":"address","name":"tokenB","type":"address"},{"internalType":"uint256","name":"liquidity","type":"uint256"},{"internalType":"uint256","name":"amountAMin","type":"uint256"},{"internalType":"uint256","name":"amountBMin","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bool","name":"approveMax","type":"bool"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"removeLiquidityWithPermit","outputs":[{"internalType":"uint256","name":"amountA","type":"uint256"},{"internalType":"uint256","name":"amountB","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapETHForExactTokens","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactETHForTokens","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactETHForTokensSupportingFeeOnTransferTokens","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForETH","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForETHSupportingFeeOnTransferTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForTokens","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForTokensSupportingFeeOnTransferTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"amountInMax","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapTokensForExactETH","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"amountInMax","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapTokensForExactTokens","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]' tokenAbi = '[{"inputs":[{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"internalType":"uint256","name":"_decimals","type":"uint256"},{"internalType":"uint256","name":"_supply","type":"uint256"},{"internalType":"uint256","name":"_txFee","type":"uint256"},{"internalType":"uint256","name":"_burnFee","type":"uint256"},{"internalType":"uint256","name":"_charityFee","type":"uint256"},{"internalType":"address","name":"_FeeAddress","type":"address"},{"internalType":"address","name":"tokenOwner","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"FeeAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_BURN_FEE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_CHARITY_FEE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_TAX_FEE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tAmount","type":"uint256"}],"name":"deliver","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"excludeAccount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"includeAccount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"isCharity","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"isExcluded","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tAmount","type":"uint256"},{"internalType":"bool","name":"deductTransferFee","type":"bool"}],"name":"reflectionFromToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"setAsCharityAccount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"rAmount","type":"uint256"}],"name":"tokenFromReflection","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalBurn","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalCharity","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalFees","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_txFee","type":"uint256"},{"internalType":"uint256","name":"_burnFee","type":"uint256"},{"internalType":"uint256","name":"_charityFee","type":"uint256"}],"name":"updateFee","outputs":[],"stateMutability":"nonpayable","type":"function"}]' def printDetails(addr, abi): print("Getting details for: ", addr) url_eth = "https://api.bscscan.com/api" contract_address = web3.toChecksumAddress(addr) API_ENDPOINT = url_eth + "?module=contract&action=getabi&address=" + str( contract_address) API_ENDPOINT += "&apikey=<APIKEY>" # r = requests.get(url = API_ENDPOINT) # response = r.json() # print(response)
import csv import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from datetime import datetime from datetime import timezone from web3 import Web3 import json import requests web3 = Web3(Web3.HTTPProvider('http://192.168.0.24:8545')) start_block_num = 8125000 end_block_num = 8169663 ETH_SCALE = 1000000000000000000 DUST_LIMIT = 10.5 INNER_LIQUID_LINE = 2000 OUTER_LIQUID_LINE = 20000 OASIS0X = '0x39755357759cE0d7f32dC8dC45414CCa409AE24e' WETH0X = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2' DAI0X = '0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359' OASIS_ABI = '[{"constant":true,"inputs":[],"name":"matchingEnabled","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"sell_gem","type":"address"},{"name":"buy_gem","type":"address"}],"name":"getBestOffer","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"pay_gem","type":"address"},{"name":"pay_amt","type":"uint256"},{"name":"buy_gem","type":"address"},{"name":"min_fill_amount","type":"uint256"}],"name":"sellAllAmount","outputs":[{"name":"fill_amt","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"stop","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"pay_gem","type":"address"},{"name":"buy_gem","type":"address"},{"name":"pay_amt","type":"uint128"},{"name":"buy_amt","type":"uint128"}],"name":"make","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"owner_","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"buy_gem","type":"address"},{"name":"pay_gem","type":"address"},{"name":"pay_amt","type":"uint256"}],"name":"getBuyAmount","outputs":[{"name":"fill_amt","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"pay_amt","type":"uint256"},{"name":"pay_gem","type":"address"},{"name":"buy_amt","type":"uint256"},{"name":"buy_gem","type":"address"},{"name":"pos","type":"uint256"}],"name":"offer","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"id","type":"uint256"},{"name":"pos","type":"uint256"}],"name":"insert","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"last_offer_id","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"matchingEnabled_","type":"bool"}],"name":"setMatchingEnabled","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"id","type":"uint256"}],"name":"cancel","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"id","type":"uint256"}],"name":"getOffer","outputs":[{"name":"","type":"uint256"},{"name":"","type":"address"},{"name":"","type":"uint256"},{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"id","type":"uint256"}],"name":"del_rank","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"id","type":"bytes32"},{"name":"maxTakeAmount","type":"uint128"}],"name":"take","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"pay_gem","type":"address"}],"name":"getMinSell","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getTime","outputs":[{"name":"","type":"uint64"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"dustId","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"id","type":"uint256"}],"name":"getNextUnsortedOffer","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"close_time","outputs":[{"name":"","type":"uint64"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"_span","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"_best","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"stopped","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"id_","type":"bytes32"}],"name":"bump","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"authority_","type":"address"}],"name":"setAuthority","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"sell_gem","type":"address"},{"name":"buy_gem","type":"address"}],"name":"getOfferCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"buy_gem","type":"address"},{"name":"buy_amt","type":"uint256"},{"name":"pay_gem","type":"address"},{"name":"max_fill_amount","type":"uint256"}],"name":"buyAllAmount","outputs":[{"name":"fill_amt","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"id","type":"uint256"}],"name":"isActive","outputs":[{"name":"active","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"offers","outputs":[{"name":"pay_amt","type":"uint256"},{"name":"pay_gem","type":"address"},{"name":"buy_amt","type":"uint256"},{"name":"buy_gem","type":"address"},{"name":"owner","type":"address"},{"name":"timestamp","type":"uint64"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getFirstUnsortedOffer","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"id","type":"uint256"}],"name":"getBetterOffer","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"_dust","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"id","type":"uint256"}],"name":"getWorseOffer","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"_near","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"id","type":"bytes32"}],"name":"kill","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"pay_gem","type":"address"},{"name":"dust","type":"uint256"}],"name":"setMinSell","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"authority","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"name":"closed","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"_rank","outputs":[{"name":"next","type":"uint256"},{"name":"prev","type":"uint256"},{"name":"delb","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"id","type":"uint256"}],"name":"getOwner","outputs":[{"name":"owner","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"id","type":"uint256"}],"name":"isOfferSorted","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"buyEnabled_","type":"bool"}],"name":"setBuyEnabled","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"id","type":"uint256"},{"name":"amount","type":"uint256"}],"name":"buy","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"pay_amt","type":"uint256"},{"name":"pay_gem","type":"address"},{"name":"buy_amt","type":"uint256"},{"name":"buy_gem","type":"address"},{"name":"pos","type":"uint256"},{"name":"rounding","type":"bool"}],"name":"offer","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"pay_amt","type":"uint256"},{"name":"pay_gem","type":"address"},{"name":"buy_amt","type":"uint256"},{"name":"buy_gem","type":"address"}],"name":"offer","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"buyEnabled","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"pay_gem","type":"address"},{"name":"buy_gem","type":"address"},{"name":"buy_amt","type":"uint256"}],"name":"getPayAmount","outputs":[{"name":"fill_amt","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"close_time","type":"uint64"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":true,"inputs":[{"indexed":true,"name":"sig","type":"bytes4"},{"indexed":true,"name":"guy","type":"address"},{"indexed":true,"name":"foo","type":"bytes32"},{"indexed":true,"name":"bar","type":"bytes32"},{"indexed":false,"name":"wad","type":"uint256"},{"indexed":false,"name":"fax","type":"bytes"}],"name":"LogNote","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"id","type":"uint256"}],"name":"LogItemUpdate","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"pay_amt","type":"uint256"},{"indexed":true,"name":"pay_gem","type":"address"},{"indexed":false,"name":"buy_amt","type":"uint256"},{"indexed":true,"name":"buy_gem","type":"address"}],"name":"LogTrade","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"id","type":"bytes32"},{"indexed":true,"name":"pair","type":"bytes32"},{"indexed":true,"name":"maker","type":"address"},{"indexed":false,"name":"pay_gem","type":"address"},{"indexed":false,"name":"buy_gem","type":"address"},{"indexed":false,"name":"pay_amt","type":"uint128"},{"indexed":false,"name":"buy_amt","type":"uint128"},{"indexed":false,"name":"timestamp","type":"uint64"}],"name":"LogMake","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"id","type":"bytes32"},{"indexed":true,"name":"pair","type":"bytes32"},{"indexed":true,"name":"maker","type":"address"},{"indexed":false,"name":"pay_gem","type":"address"},{"indexed":false,"name":"buy_gem","type":"address"},{"indexed":false,"name":"pay_amt","type":"uint128"},{"indexed":false,"name":"buy_amt","type":"uint128"},{"indexed":false,"name":"timestamp","type":"uint64"}],"name":"LogBump","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"id","type":"bytes32"},{"indexed":true,"name":"pair","type":"bytes32"},{"indexed":true,"name":"maker","type":"address"},{"indexed":false,"name":"pay_gem","type":"address"},{"indexed":false,"name":"buy_gem","type":"address"},{"indexed":true,"name":"taker","type":"address"},{"indexed":false,"name":"take_amt","type":"uint128"},{"indexed":false,"name":"give_amt","type":"uint128"},{"indexed":false,"name":"timestamp","type":"uint64"}],"name":"LogTake","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"id","type":"bytes32"},{"indexed":true,"name":"pair","type":"bytes32"},{"indexed":true,"name":"maker","type":"address"},{"indexed":false,"name":"pay_gem","type":"address"},{"indexed":false,"name":"buy_gem","type":"address"},{"indexed":false,"name":"pay_amt","type":"uint128"},{"indexed":false,"name":"buy_amt","type":"uint128"},{"indexed":false,"name":"timestamp","type":"uint64"}],"name":"LogKill","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"authority","type":"address"}],"name":"LogSetAuthority","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"}],"name":"LogSetOwner","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"isEnabled","type":"bool"}],"name":"LogBuyEnabled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"pay_gem","type":"address"},{"indexed":false,"name":"min_amount","type":"uint256"}],"name":"LogMinSell","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"isEnabled","type":"bool"}],"name":"LogMatchingEnabled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"id","type":"uint256"}],"name":"LogUnsortedOffer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"id","type":"uint256"}],"name":"LogSortedOffer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"keeper","type":"address"},{"indexed":false,"name":"id","type":"uint256"}],"name":"LogInsert","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"keeper","type":"address"},{"indexed":false,"name":"id","type":"uint256"}],"name":"LogDelete","type":"event"}]' WETH_ABI = json.loads( '[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"guy","type":"address"},{"name":"wad","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"src","type":"address"},{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"wad","type":"uint256"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"deposit","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},{"indexed":true,"name":"guy","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},{"indexed":true,"name":"dst","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"dst","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Withdrawal","type":"event"}]' ) DAI_ABI = json.loads( '[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"stop","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"guy","type":"address"},{"name":"wad","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"owner_","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"src","type":"address"},{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"guy","type":"address"},{"name":"wad","type":"uint256"}],"name":"mint","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"wad","type":"uint256"}],"name":"burn","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"name_","type":"bytes32"}],"name":"setName","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"src","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"stopped","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"authority_","type":"address"}],"name":"setAuthority","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"guy","type":"address"},{"name":"wad","type":"uint256"}],"name":"burn","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"wad","type":"uint256"}],"name":"mint","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}],"name":"push","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"src","type":"address"},{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}],"name":"move","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"start","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"authority","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"guy","type":"address"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"src","type":"address"},{"name":"guy","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"src","type":"address"},{"name":"wad","type":"uint256"}],"name":"pull","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"symbol_","type":"bytes32"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"guy","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"guy","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"authority","type":"address"}],"name":"LogSetAuthority","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"}],"name":"LogSetOwner","type":"event"},{"anonymous":true,"inputs":[{"indexed":true,"name":"sig","type":"bytes4"},{"indexed":true,"name":"guy","type":"address"},{"indexed":true,"name":"foo","type":"bytes32"},{"indexed":true,"name":"bar","type":"bytes32"},{"indexed":false,"name":"wad","type":"uint256"},{"indexed":false,"name":"fax","type":"bytes"}],"name":"LogNote","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},{"indexed":true,"name":"guy","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},{"indexed":true,"name":"dst","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Transfer","type":"event"}]' )
from eth_account import Account from web3 import Web3 from web3.middleware import geth_poa_middleware node_url = 'https://rinkeby.infura.io/v3/646f232797a44ce58c336cf4e852905d' w3 = Web3(Web3.HTTPProvider(node_url)) w3.middleware_onion.inject(geth_poa_middleware, layer=0) ###############################Customize these values################### keyfile = 'account.silke.json' password = '' receiver_addresses = ['0x2418B7e00C5B8590d6FeB89f1e70f9A13A4181f7'] value = 0.2 ######################################################################## transaction_template = { 'to': None, 'value': None, 'gas': 2000000, 'gasPrice': None, 'nonce': None, 'chainId': 4 } def import_keyfile(keyfile: str): with open(keyfile, "r") as keyfile: account_json = keyfile.read() private_key = Account.decrypt(account_json, password) return Account.privateKeyToAccount(private_key)
class Connection: RINKEBY_URL = 'https://rinkeby.infura.io/v3/328d6f459b0341afb9d3f8b43f758234' CONNECTION = Web3(Web3.HTTPProvider(RINKEBY_URL))
def execute(): config_file = Path('config.ini') with open(str(config_file.absolute()), mode='r') as f: config_data = f.read() config = configparser.ConfigParser() config.read_string(config_data) logging_config = Path('logging.conf') if logging_config.exists(): fileConfig(str(logging_config.absolute())) else: dictConfig(dict( version=1, formatters={ 'f': {'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'} }, handlers={ 'h': {'class': 'logging.StreamHandler', 'formatter': 'f', 'level': logging.DEBUG} }, root={ 'handlers': ['h'], 'level': logging.DEBUG, } )) logger = logging.getLogger('WATCHER') eth_bridge_address = config['monitor']['eth_bridge_address'] ava_bridge_address = config['monitor']['ava_bridge_address'] eth_rpc_url = config['monitor']['eth_rpc_url'] ava_rpc_url = config['monitor']['ava_rpc_url'] sleep_time = int(config['monitor']['sleep_time']) eth_chain_id = int(config['monitor']['eth_chain_id']) ava_chain_id = int(config['monitor']['ava_chain_id']) eth_handler = config['monitor']['eth_handler'] ava_handler = config['monitor']['ava_handler'] ava_session = requests.Session() logger.debug('Connecting to ETH Web3') eth_web3 = Web3(Web3.HTTPProvider(eth_rpc_url)) logger.debug('Connecting to AVA Web3') ava_web3 = Web3(Web3.HTTPProvider(ava_rpc_url, session=ava_session)) logger.debug('Building contract instances') eth_bridge_contract = eth_web3.eth.contract(address=eth_bridge_address, abi=bridge_abi) ava_bridge_contract = ava_web3.eth.contract(address=ava_bridge_address, abi=bridge_abi) logger.debug("Building ETH Bridge Data") eth_bridge = Bridge(contract=eth_bridge_contract, chain_id=eth_chain_id, handler=eth_handler) logger.debug("Building AVA Bridge Data") ava_bridge = Bridge(contract=ava_bridge_contract, chain_id=ava_chain_id, handler=ava_handler) monitor_state = load_or_new_state() state = State(monitor=monitor_state, eth_bridge=eth_bridge, ava_bridge=ava_bridge, config=config) eth_fromBlock = 'latest' ava_fromBlock = 'latest' while True: try: logger.debug("Setting up Proposal Voted Event filter on Ethereum") eth_vote_events = eth_bridge.contract.events.ProposalVote.getLogs(fromBlock=eth_fromBlock, toBlock='latest') ava_vote_events = ava_bridge.contract.events.ProposalVote.getLogs(fromBlock=ava_fromBlock, toBlock='latest') try: logger.debug("Checking Ethereum ProposalVote event filters") check_vote_event(state, eth_vote_events) except Exception as e: logger.error("Failed to grab Ethereum ProposalVote event filters") logger.exception(e) try: logger.debug("Checking Avalanche ProposalVote event filters") check_vote_event(state, ava_vote_events) except Exception as e: logger.error("Failed to grab Avalanche ProposalVote event filters") logger.exception(e) eth_fromBlock = eth_web3.eth.block_number ava_fromBlock = ava_web3.eth.block_number logger.debug("Scanning for new proposals") new_proposals = find_all_new_proposals(state) logger.debug(f"Got {len(new_proposals['1'])} new Ethereum proposals and {len(new_proposals['2'])} new Avalanche proposals") logger.debug("Checking for imbalances") check_for_imbalances(state) logger.debug("Looking for expired proposals") expired_proposals(state, new_proposals) logger.debug("Looking for new active proposals") watch_active_proposals(state, new_proposals) logger.debug("Looking for new passed proposals") watch_passed_proposals(state, new_proposals) logger.debug("Checking active proposals") check_active_proposals(state) logger.debug("Checking passed proposals") check_passed_proposals(state) logger.debug("Saving current state") state.monitor.save() logger.debug(f"Restarting loop in {sleep_time} seconds") time.sleep(sleep_time) except KeyboardInterrupt: break except Exception as e: logger.error(e) logger.error(f"Swallowing exception, sleeping for {sleep_time} seconds before trying again") time.sleep(sleep_time) continue state.monitor.save()
def _create_w3_instance(self) -> Web3: assert cfg.blockchain_node_uri is None or isinstance(cfg.blockchain_node_uri, str) return Web3(Web3.HTTPProvider(cfg.blockchain_node_uri))
import time import datetime import os import hashlib import random import json from web3 import Web3 from web3.gas_strategies.time_based import medium_gas_price_strategy w3 = Web3( Web3.HTTPProvider( 'https://ropsten.infura.io/v3/8f283916dfab4e8e8fc2adf4c4a94127')) w3.eth.setGasPriceStrategy(medium_gas_price_strategy) if not os.path.exists('logs'): os.makedirs('logs') class Deamon(): def __init__(self): self.configurationFile = 'gianoConfiguration.json' self.pid = os.getpid() self.paths = self.readJson()['paths'] self.logsPath = self.readJson()['logsPath'] self.address = self.readJson()['address'] self.privateKey = self.readJson()['privateKey'] self.latestLogHash = None self.latestLogTx = None self.nonce = w3.eth.getTransactionCount(self.address) self.delay = self.readJson()['delay'] self.counter = 1
def __init__(self, private_key: Any, jsonrpc_url: str, erc20_token_addresses: List[str], chain: EthereumChain = EthereumChain.ROPSTEN): super().__init__() # Initialize Web3, accounts and contracts. self._w3: Web3 = Web3(Web3.HTTPProvider(jsonrpc_url)) self._chain: EthereumChain = chain self._account: LocalAccount = Account.privateKeyToAccount(private_key) # Get information about the ERC20 tokens. self._erc20_token_list: List[ERC20Token] = [] for erc20_token_address in erc20_token_addresses: self._erc20_token_list.append( ERC20Token(self._w3, erc20_token_address, self._chain)) self._erc20_tokens: OrderedDict[str, ERC20Token] = { erc20_token.symbol: erc20_token for erc20_token in self._erc20_token_list } self._weth_token = self._erc20_tokens[ "WETH"] if "WETH" in self._erc20_tokens else None self._asset_decimals: Dict[str, int] = { asset_name: erc20_token.decimals for asset_name, erc20_token in self._erc20_tokens.items() } self._asset_decimals["ETH"] = 18 # Create event watchers. self._new_blocks_watcher: NewBlocksWatcher = NewBlocksWatcher(self._w3) self._account_balance_watcher: AccountBalanceWatcher = AccountBalanceWatcher( self._w3, self._new_blocks_watcher, self._account.address, [ erc20_token.address for erc20_token in self._erc20_tokens.values() ], [token.abi for token in self._erc20_tokens.values()]) self._erc20_events_watcher: ERC20EventsWatcher = ERC20EventsWatcher( self._w3, self._new_blocks_watcher, [token.address for token in self._erc20_tokens.values()], [token.abi for token in self._erc20_tokens.values()], [self._account.address]) if self._weth_token is not None: self._weth_watcher: Optional[WethWatcher] = WethWatcher( self._w3, self._weth_token, self._new_blocks_watcher, [self._account.address]) else: self._weth_watcher: Optional[WethWatcher] = None self._incoming_eth_watcher: IncomingEthWatcher = IncomingEthWatcher( self._w3, self._new_blocks_watcher, [self._account.address]) # Create the outgoing transactions loop and local nonce. self._local_nonce: int = self._w3.eth.getTransactionCount( self.address, block_identifier="pending") self._outgoing_transactions_queue: asyncio.Queue = asyncio.Queue() self._outgoing_transactions_task: Optional[asyncio.Task] = None self._check_transaction_receipts_task: Optional[asyncio.Task] = None self._pending_tx_dict: Dict[str, int] = {} # Create a local cache for wallet states. self._current_block_number: int = self._w3.eth.blockNumber # Initialize event forwarders self._received_asset_event_forwarder: EventForwarder = EventForwarder( self._received_asset_event_listener) self._approved_token_event_forwarder: EventForwarder = EventForwarder( self._token_approved_event_listener) self._wrapped_eth_event_forwarder: EventForwarder = EventForwarder( self._eth_wrapped_event_listener) self._unwrapped_eth_event_forwarder: EventForwarder = EventForwarder( self._eth_unwrapped_event_listener) self._erc20_events_watcher.add_listener( ERC20WatcherEvent.ReceivedToken, self._received_asset_event_forwarder) self._erc20_events_watcher.add_listener( ERC20WatcherEvent.ApprovedToken, self._approved_token_event_forwarder) if self._weth_watcher is not None: self._weth_watcher.add_listener(WalletEvent.WrappedEth, self._wrapped_eth_event_forwarder) self._weth_watcher.add_listener( WalletEvent.UnwrappedEth, self._unwrapped_eth_event_forwarder) self._incoming_eth_watcher.add_listener( IncomingEthWatcherEvent.ReceivedEther, self._received_asset_event_forwarder)
def block_chain_connect(self): w3 = Web3(Web3.HTTPProvider(self.node_url)) w3.middleware_stack.inject(geth_poa_middleware, layer=0) return w3
from web3 import Web3 import json gananche_url="http://127.0.0.1:7545" w3 = Web3(Web3.HTTPProvider(gananche_url)) print(w3.isConnected())
if STAGING or PRODUCTION else "https://test.crossref.org/servlet/deposit") # Async Service API Key ASYNC_SERVICE_API_KEY = os.environ.get( "ASYNC_SERVICE_API_KEY", keys.ASYNC_SERVICE_API_KEY or "testapikeyservice") WEB3_NETWORK = os.environ.get("WEB3_NETWORK", "rinkeby") PROVIDER_URL = os.environ.get("PROVIDER_URL", keys.PROVIDER_URL) WEB3_KEYSTORE_BUCKET = os.environ.get("WEB3_KEYSTORE_BUCKET", keys.WEB3_KEYSTORE_BUCKET) WEB3_KEYSTORE_FILE = os.environ.get("WEB3_KEYSTORE_FILE", keys.WEB3_KEYSTORE_FILE) WEB3_KEYSTORE_PASSWORD = os.environ.get("WEB3_KEYSTORE_PASSWORD", keys.WEB3_KEYSTORE_PASSWORD) WEB3_KEYSTORE_ADDRESS = os.environ.get("", keys.WEB3_KEYSTORE_ADDRESS) try: w3 = Web3(Web3.HTTPProvider(PROVIDER_URL)) if WEB3_NETWORK == "rinkeby": from web3.middleware import geth_poa_middleware w3.middleware_onion.inject(geth_poa_middleware, layer=0) except Exception as e: log_error(e) print(e) # API Key Settings API_KEY_CUSTOM_HEADER = "HTTP_RH_API_KEY"
def connect_to_web3(url=None): if url is None: url = os.environ['URL'] return Web3(Web3.HTTPProvider(url))
import sys from web3 import Web3 # read in and store terminal arguments contract_address = sys.argv[1] infura_url = sys.argv[3] web3 = Web3(Web3.HTTPProvider(infura_url)) low = 0 high = web3.eth.blockNumber # set high to latest block number mid = high // 2 while (low < high - 1): # using high - 1 to avoid infinite loop bytecode = web3.eth.getCode(account=contract_address, block_identifier=mid).hex() # using binary approach to find first instance of contract if len(bytecode) == 2: # contract doesn't exist yet at this block low = mid mid = (low + high) // 2 else: # contract exists at this block high = mid mid = (low + high) // 2 # check needed in rare case that first checked block was the one needed if len(web3.eth.getCode(account=contract_address, block_identifier=mid).hex()) == 2: mid += 1
def main(): execution_begin = time.time() connection = None try: global args print('') print(' d8888 8888888888 .d8888b. 8888888 .d8888b. ') print(' d88888 888 d88P Y88b 888 d88P Y88b') print(' d88P888 888 888 888 888 Y88b. ') print(' d88P 888 8888888 888 888 "Y888b. ') print(' d88P 888 888 888 88888 888 "Y88b.') print(' d88P 888 888 888 888 888 "888') print(' d8888888888 888 Y88b d88P 888 Y88b d88P') print('d88P 888 8888888888 "Y8888P88 8888888 "Y8888P" ') print('') parser = argparse.ArgumentParser() group_1 = parser.add_mutually_exclusive_group(required=True) group_1.add_argument( "-t", "--transaction", type=str, help="transaction hash to be analyzed") group_1.add_argument( "-b", "--block", type=int, help="block number to be analyzed") group_1.add_argument( "-c", "--contract", type=str, help="contract address to be analyzed") group_2 = parser.add_mutually_exclusive_group(required=False) group_2.add_argument( "-l", "--load", type=str, help="load execution information from file") group_2.add_argument( "-s", "--save", type=str, help="save execution information to file") parser.add_argument( "-p", "--patterns", type=str, help="file containing patterns to be analyzed (default: '"+settings.PATTERNS_FILE+"')") parser.add_argument( "-r", "--results", type=str, help="folder where results should be stored") parser.add_argument( "--cfg", type=str, help="save control flow graph to a file") parser.add_argument( "--debug", action="store_true", help="print debug information to the console") parser.add_argument( "--host", type=str, help="HTTP-RPC server listening interface (default: '"+settings.RPC_HOST+"')") parser.add_argument( "--port", type=int, help="HTTP-RPC server listening port (default: '"+str(settings.RPC_PORT)+"')") parser.add_argument( "-v", "--version", action="version", version="AEGIS version 0.0.1 - 'Apollo'") args = parser.parse_args() if args.debug: settings.DEBUG_MODE = args.debug if args.patterns: settings.PATTERNS_FILE = args.patterns else: settings.PATTERNS_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)), settings.PATTERNS_FILE) if args.host: settings.RPC_HOST = args.host if args.port: settings.RPC_PORT = args.port network = "" tries = 0 while not (settings.W3 and connection) and tries < 10: try: tries += 1 if not args.load: settings.W3 = Web3(Web3.HTTPProvider("http://"+settings.RPC_HOST+":"+str(settings.RPC_PORT))) if settings.W3.isConnected(): network = "" if settings.W3.net.version == "1": network = "mainnet" elif settings.W3.net.version == "2": network = "morden" elif settings.W3.net.version == "3": network = "ropsten" else: network = "unknown" print("Connected to "+str(settings.W3.version.node)+" ("+network+")") else: print("Error: Could not connect to Ethereum client. Please make sure the client is running and settings are correct.") if not settings.W3.eth.syncing: print("Blockchain is in sync (latest block: "+str(settings.W3.eth.blockNumber)+").") print("") else: print("Blockchain is syncing... (synced at %.2f%% - latest block: %d)" % (settings.W3.eth.syncing.currentBlock/settings.W3.eth.syncing.highestBlock*100.0, settings.W3.eth.syncing.currentBlock)) print("") connection = http.client.HTTPConnection(settings.RPC_HOST, settings.RPC_PORT) except Exception as e: if tries < 10: print("Retrying to connect to http://"+settings.RPC_HOST+":"+str(settings.RPC_PORT)) time.sleep(30) else: print(e) return if args.results: settings.RESULTS_FOLDER = args.results if args.cfg: settings.SAVE_CFG = args.cfg if args.load or args.save: global execution_trace if args.load: with open(args.load) as file: execution_trace = json.load(file) if args.save: execution_trace = {"transactions": [], "traces": {}} if args.transaction: if not os.path.isfile(settings.RESULTS_FOLDER+'/'+args.transaction+'.json'): transactions = [] if args.load: transactions = execution_trace["transactions"] else: try: transaction = format_transaction(settings.W3.eth.getTransaction(args.transaction)) if transaction["to"] and transaction["gas"] > 21000: transactions.append(transaction) except Exception as e: print("Error: Blockchain is not in sync with transaction: "+args.transaction) results = analyze_transactions(connection, transactions) if settings.RESULTS_FOLDER: with open(settings.RESULTS_FOLDER+'/'+args.transaction+'.json', 'w') as file: json.dump(results, file) if args.save: with open(args.save+'/'+args.transaction+'.trace', 'w') as file: json.dump(execution_trace, file) if args.block: if not os.path.isfile(settings.RESULTS_FOLDER+'/'+str(args.block)+'.json'): transactions = [] if args.load: transactions = execution_trace["transactions"] else: try: block = settings.W3.eth.getBlock(args.block) for i in block["transactions"]: transaction = format_transaction(settings.W3.eth.getTransaction(i)) if transaction["to"] and transaction["gas"] > 21000: transactions.append(transaction) except: print("Error: Blockchain is not in sync with block number: "+args.block[0]) print("Analyzing block "+str(args.block)+" with "+str(len(transactions))+" transaction(s).\n") results = analyze_transactions(connection, transactions) if settings.RESULTS_FOLDER: with open(settings.RESULTS_FOLDER+'/'+str(args.block)+'.json', 'w') as file: json.dump(results, file) if args.save: with open(args.save+'/'+str(args.block)+'.trace', 'w') as file: json.dump(execution_trace, file) if args.contract: if not os.path.isfile(settings.RESULTS_FOLDER+'/'+args.contract+'.json'): transactions = [] if args.load: transactions = execution_trace["transactions"] else: api_network = "api" if network == "mainnet" else "api-"+network tries = 0 while tries < 10: try: tries += 1 etherscan_api_token = random.choice(settings.ETHERSCAN_API_TOKENS) api_response = requests.get("https://"+api_network+".etherscan.io/api?module=account&action=txlist&address="+args.contract+"&startblock=0&endblock="+str(settings.MAX_BLOCK_HEIGHT)+"&sort=asc&apikey="+etherscan_api_token).json() #print("https://"+api_network+".etherscan.io/api?module=account&action=txlist&address="+args.contract+"&startblock=0&endblock="+str(settings.MAX_BLOCK_HEIGHT)+"&sort=asc&apikey="+etherscan_api_token) #print("https://"+api_network+".etherscan.io/api?module=account&action=txlistinternal&address="+args.contract+"&startblock=0&endblock="+str(settings.MAX_BLOCK_HEIGHT)+"&sort=asc&apikey="+etherscan_api_token) if not api_response or "error" in api_response or not "result" in api_response: if "error" in api_response: print("An error occured in retrieving the list of transactions: "+str(api_response["error"])) else: print("An unknown error ocurred in retrieving the list of transactions!") else: for transaction in api_response["result"]: if transaction["to"] and int(transaction["gasUsed"]) > 21000: if not is_block_within_ranges(int(transaction["blockNumber"]), settings.DOS_ATTACK_BLOCK_RANGES): if not transaction in transactions: transactions.append(transaction) break except Exception as e: if tries < 10: print("Retrying to retrieve the list of transactions from etherscan in 1 min.") time.sleep(60) else: raise(e) """# Get the list of "normal" transactions for the given contract address page = 1 while True: api_response = requests.get("https://"+api_network+".etherscan.io/api?module=account&action=txlist&address="+args.contract+"&startblock=0&endblock="+str(settings.MAX_BLOCK_HEIGHT)+"&page="+str(page)+"&offset=10000&sort=asc&apikey="+etherscan_api_token).json() if not api_response or "error" in api_response: if "error" in api_response: print("An error occured in retrieving the list of transactions: "+str(api_response["error"])) else: print("An unknown error ocurred in retrieving the list of transactions!") elif "result" in api_response: if not api_response["result"] or len(api_response["result"]) == 0: break else: page += 1 for result in api_response["result"]: transaction = format_transaction(settings.W3.eth.getTransaction(result["hash"])) if transaction["to"] and transaction["gas"] > 21000: if not is_block_within_ranges(transaction["blockNumber"], settings.DOS_ATTACK_BLOCK_RANGES): if not transaction in transactions: transactions.append(transaction) else: break # Get the list of "internal" transactions for the given contract address page = 1 while True: api_response = requests.get("https://"+api_network+".etherscan.io/api?module=account&action=txlistinternal&address="+args.contract+"&startblock=0&endblock="+str(settings.MAX_BLOCK_HEIGHT)+"&page="+str(page)+"&offset=10000&sort=asc&apikey="+etherscan_api_token).json() if not api_response or "error" in api_response: if "error" in api_response: print("An error occured in retrieving the list of transactions: "+str(api_response["error"])) else: print("An unknown error ocurred in retrieving the list of transactions!") elif "result" in api_response: if len(api_response["result"]) == 0: break else: page += 1 for result in api_response["result"]: transaction = format_transaction(settings.W3.eth.getTransaction(result["hash"])) if transaction["to"] and transaction["gas"] > 21000: if not is_block_within_ranges(transaction["blockNumber"], settings.DOS_ATTACK_BLOCK_RANGES): if not transaction in transactions: transactions.append(transaction) else: break # Sort the list of transactions from operator import itemgetter transactions = sorted(transactions, key=itemgetter('blockNumber', 'transactionIndex'))""" print("Analyzing contract "+str(args.contract)+" with "+str(len(transactions))+" transaction(s).\n") results = analyze_transactions(connection, transactions) if settings.RESULTS_FOLDER: with open(settings.RESULTS_FOLDER+'/'+args.contract+'.json', 'w') as file: json.dump(results, file) if args.save: with open(args.save+'/'+args.contract+'.trace', 'w') as file: json.dump(execution_trace, file) except argparse.ArgumentTypeError as e: print(e) except Exception: traceback.print_exc() if args.transaction: print("Transaction: "+args.transaction) if args.block: print("Block: "+str(args.block)) if args.contract: print("Contract: "+args.contract) finally: if connection: connection.close() print("Connection closed.") execution_end = time.time() execution_delta = execution_end - execution_begin print("") print("Overall execution took %.2f second(s)." % execution_delta)
import json from web3 import Web3 url = "http://127.0.0.1:7545" w3 = Web3(Web3.HTTPProvider(url)) abi = [{ "inputs": [{ "internalType": "string", "name": "_firstName", "type": "string" }, { "internalType": "string", "name": "_lastName", "type": "string" }], "name": "addPerson", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "getPeopleCount", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
from constants import * from web3 import Web3, middleware, Account from web3.gas_strategies.time_based import medium_gas_price_strategy from web3.middleware import geth_poa_middleware import subprocess import json import os from dotenv import load_dotenv w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545")) w3.middleware_onion.inject(geth_poa_middleware, layer=0) s3.eth.setGasPriceStrategy(medium_gas_price_strategy) load_dotenv('homework.env') private_key = os.getenv('mnemonic') print(type(private_key)) ./derive -g --mnemonic="oil traffic blind stumble quote weekend wise tank clay layer slot cash" --cols=path,address,privkey,pubkey --coin="BTC" --numderive=3 --format=json def derive_wallet(coin=BTC, mnemonic=private_key, depth=3): command = f'./derive -g --mnemonic={mnemonic} --cols=path,address,privkey,pubkey --coin={coin} --numderive={depth} --format=json' p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) output, err = p.communicate() p_status = p.wait() return json.loads(output) derive_wallet()
import pymysql.cursors import requests from web3 import Web3 from datetime import datetime conn = pymysql.connect(host="127.0.0.1", user="******", password="", database="flashbots", cursorclass=pymysql.cursors.DictCursor, port=3306) w3 = Web3( Web3.HTTPProvider( 'https://mainnet.infura.io/v3/63c6341ccc124ac39ce4472f3133154b')) blocks_schema = [ 'block_number', 'miner', 'miner_reward', 'coinbase_transfers', 'gas_used', 'gas_price', 'timestamp' ] transactions_schema = [ 'transaction_hash', 'tx_index', 'bundle_type', 'bundle_index', 'block_number', 'eoa_address', 'to_address', 'gas_used', 'gas_price', 'coinbase_transfer', 'total_miner_reward' ] def turn_off_autocommit(): with conn.cursor() as cur: cur.execute("SET autocommit = 0") cur.fetchone() conn.commit()