def initialize_db(): is_connected = w3.isConnected() if not is_connected: raise ConnectionError("W3 not connected") block_number = w3.eth.blockNumber # pdb.set_trace() # Query Get block 12000 times and populate the db for i in range(12000): block = w3.eth.getBlock(block_number - i, True) transactions = block.transactions for j in range(len(transactions)): t = transactions[j] data = { "block_number": t["blockNumber"], "to_user": t["to"], "from_user": t["from"], "hash": t["hash"].hex() } # pdb.set_trace() doc = Transactions.objects.create(**data) doc.save()
def start(self): """ Start the blockchain client using the configured blockchain gateway. """ assert self._w3 is None if self._gateway: w3 = web3.Web3(web3.Web3.HTTPProvider(self._gateway)) else: # using automatic provider detection: from web3.auto import w3 # check we are connected, and check network ID if not w3.isConnected(): emsg = 'could not connect to Web3/Ethereum at: {}'.format( self._gateway or 'auto') self.log.warn(emsg) raise RuntimeError(emsg) else: print('connected to network {} at provider "{}"'.format( w3.version.network, self._gateway or 'auto')) self._w3 = w3 # set new provider on XBR library xbr.setProvider(self._w3)
def __init__(self): assert w3.isConnected(), "Couldn't connect to node" self.endpoint = "http://127.0.0.1:8545" self.w3 = w3 networkId = w3.net.version #loading deployed contract address and json file path with open('../deployments/localhost/MMInstantiator.json') as json_file: mm_data = json.load(json_file) self.mm = w3.eth.contract(address=mm_data['address'], abi=mm_data['abi']) with open('../deployments/localhost/PartitionInstantiator.json') as json_file: partition_data = json.load(json_file) self.partition = w3.eth.contract(address=partition_data['address'], abi=partition_data['abi']) with open('../deployments/localhost/VGInstantiator.json') as json_file: vg_data = json.load(json_file) self.vg = w3.eth.contract(address=vg_data['address'], abi=vg_data['abi']) self.vg_address = vg_data['address'] with open('../deployments/localhost/ComputeInstantiator.json') as json_file: compute_data = json.load(json_file) self.compute = w3.eth.contract(address=compute_data['address'], abi=compute_data['abi']) with open('../deployments/localhost/MMInstantiatorTestAux.json') as json_file: mm_testaux_data = json.load(json_file) self.mm_testaux = w3.eth.contract(address=mm_testaux_data['address'], abi=mm_testaux_data['abi']) with open('../deployments/localhost/PartitionTestAux.json') as json_file: partition_testaux_data = json.load(json_file) self.partition_testaux = w3.eth.contract(address=partition_testaux_data['address'], abi=partition_testaux_data['abi'])
def _get_auto_provider(provider_uri) -> BaseProvider: from web3.auto import w3 # how-automated-detection-works: https://web3py.readthedocs.io/en/latest/providers.html connected = w3.isConnected() if not connected: raise ProviderError('Cannot auto-detect node. Provide a full URI instead.') return w3.provider
def connect(): global w3 global contract provider = Web3.HTTPProvider(HOSTNAME) w3 = Web3(provider) if w3.isConnected(): print("Connected to provider {0}".format(HOSTNAME)) else: return contract = w3.eth.contract(address = CONTRACT_ADDRESS, abi = ABI)
def connect(network, account='user'): if network == 'local': from web3 import Web3 w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545")) try: w3.eth.defaultAccount = w3.eth.accounts[0] admin = w3.eth.accounts[0] except: raise Exception("Ensure ganache-cli is connected") elif network == 'bsc-testnet': config = read_config() os.environ[ 'WEB3_PROVIDER_URI'] = 'https://data-seed-prebsc-1-s1.binance.org:8545/' os.environ['WEB3_CHAIN_ID'] = '97' from web3.middleware import construct_sign_and_send_raw_middleware from web3.middleware import geth_poa_middleware from web3.auto import w3 admin = w3.eth.account.from_key(config[account]['key']) w3.eth.defaultAccount = admin.address w3.middleware_onion.inject(geth_poa_middleware, layer=0) w3.middleware_onion.add(construct_sign_and_send_raw_middleware(admin)) elif network == 'bsc-mainnet': config = read_config() os.environ['WEB3_PROVIDER_URI'] = 'https://bsc-dataseed.binance.org/' os.environ['WEB3_CHAIN_ID'] = '56' from web3.middleware import construct_sign_and_send_raw_middleware from web3.middleware import geth_poa_middleware from web3.auto import w3 admin = w3.eth.account.from_key(config[account]['key']) w3.eth.defaultAccount = admin.address w3.middleware_onion.inject(geth_poa_middleware, layer=0) w3.middleware_onion.add(construct_sign_and_send_raw_middleware(admin)) elif network == 'kovan': config = read_config() os.environ['WEB3_INFURA_PROJECT_ID'] = config['infura']['project_id'] os.environ['WEB3_INFURA_API_SECRET'] = config['infura']['secret'] from web3.middleware import construct_sign_and_send_raw_middleware from web3.auto.infura.kovan import w3 admin = w3.eth.account.from_key(config[account]['key']) w3.eth.defaultAccount = admin.address w3.middleware_onion.add(construct_sign_and_send_raw_middleware(admin)) else: raise ValueError(f'Unknown network {network}') assert w3.isConnected() return w3, admin
def main(): try: w3.isConnected() except: print("Not connected. Exiting.") sys.exit() iterations = 1000000 # Number of keys we'll try before stopping total_found = 0 # Amount of ETH found so far wallets_with_eth = [] # List to contain the wallets with ETH try_count = 0 # The number of private keys tried so far hash = random.getrandbits(256) # Generate a private key try: while iterations > 0: print("----------") private_key = hex(hash) print("private_key: %s" % private_key) #private_key_example = '89cc3093f4f11d868a61bca31193117681c2955deca1be821067a9e8949841fa' balance = check_balance(private_key) print("balance: %s" % balance) if float(balance) > 0: wallets_with_eth.append(private_key) total_found += balance print("Total found: %s ETH Wallets checked: %s/%s" % (total_found, try_count, iterations)) hash += 1 try_count += 1 iterations -= 1 print("\nFinal stats: %s ETH found." % total_found) print("Exiting...")
def __init__(self): if (w3.isConnected()): print("Connected to node\n") else: print("Couldn't connect to node, exiting") sys.exit(1) self.endpoint = "http://127.0.0.1:8545" self.w3 = w3 networkId = w3.net.version #loading deployed contract address and json file path with open('../build/contracts/Descartes.json') as json_file: descartes_data = json.load(json_file) self.descartes = w3.eth.contract( address=descartes_data['networks'][networkId]['address'], abi=descartes_data['abi'])
else: result = xbr.xbrToken.functions.approve(xbr.xbrNetwork.address, actor['security']).transact({'from': actor['addr'], 'gas': 1000000}) if not result: print('Failed to allow transfer of tokens for market security!', result) else: print('Allowed transfer of {} XBR from {} to {} as security for joining market'.format(actor['security'], actor['addr'], xbr.xbrNetwork.address)) security = xbr.xbrNetwork.functions.joinMarket(market['id'], actor['type']).transact({'from': actor['addr'], 'gas': 1000000}) print('Actor {} joined market {} as actor type {} with security {}!'.format(hl(actor['addr']), market['id'], hl(actor['type']), security)) if __name__ == '__main__': print('using web3.py v{}'.format(web3.__version__)) # using automatic provider detection: from web3.auto import w3 # check we are connected, and check network ID if not w3.isConnected(): print('could not connect to Web3/Ethereum') sys.exit(1) else: print('connected to network {}'.format(w3.version.network)) # set new provider on XBR library xbr.setProvider(w3) # now enter main .. main(w3.eth.accounts)
def main(): abi = abi_heimdall() bytecode = bytecode_heimdall() print("connected:", w3.isConnected()) print("loading...") accounts = w3.eth.accounts w3.eth.defaultAccount = accounts[0] heimdall_contract = w3.eth.contract(abi=abi, bytecode=bytecode) with open("log.txt", "r") as f: if f.read() == "new deploy": tx_hash_heimdall_deployment = heimdall_contract.constructor( ).transact() tx_receipt_heimdall_deployment = w3.eth.waitForTransactionReceipt( tx_hash_heimdall_deployment) heimdall_contract_address = tx_receipt_heimdall_deployment.contractAddress with open("log.txt", "w") as fw: fw.write(heimdall_contract_address + "\n") else: f.seek(0) heimdall_contract_address = f.read(42) # load log data f.seek(0) for line in f.readlines()[1:]: clean_line = line.strip("\n") line_parts = line.split(" | ") line_parts[1] = literal_eval(line_parts[1]) handle_log_line(line_parts, state_vars) print("deployment account:", w3.eth.defaultAccount) print("contract deployed to:", heimdall_contract_address) heimdall_contract = w3.eth.contract(address=heimdall_contract_address, abi=abi, bytecode=bytecode) # create event filters toggle_contract_open_event_hash = w3.sha3( text="ToggleContractOpenEvent(address,bool,bool)").hex() toggle_contract_open_event_filter = w3.eth.filter( filter_params={ "address": heimdall_contract_address, "topics": [toggle_contract_open_event_hash] }) deposit_event_hash = w3.sha3( text="DepositEvent(address,address,uint256,uint256,uint256)").hex() deposit_event_filter = w3.eth.filter(filter_params={ "address": heimdall_contract_address, "topics": [deposit_event_hash] }) start_withdrawal_event_hash = w3.sha3( text="StartWithdrawalEvent(address,address,uint256,uint256)").hex() start_withdrawal_event_filter = w3.eth.filter( filter_params={ "address": heimdall_contract_address, "topics": [start_withdrawal_event_hash] }) approve_withdrawal_event_hash = w3.sha3( text="ApproveWithdrawalEvent(address,address,uint256,uint256)").hex() approve_withdrawal_event_filter = w3.eth.filter( filter_params={ "address": heimdall_contract_address, "topics": [approve_withdrawal_event_hash] }) deny_withdrawal_event_hash = w3.sha3( text="DenyWithdrawalEvent(address,address,uint256,uint256)").hex() deny_withdrawal_event_filter = w3.eth.filter( filter_params={ "address": heimdall_contract_address, "topics": [deny_withdrawal_event_hash] }) set_deposit_fee_event_hash = w3.sha3( text="SetDepositFeeEvent(address,uint256,uint256)").hex() set_deposit_fee_event_filter = w3.eth.filter( filter_params={ "address": heimdall_contract_address, "topics": [set_deposit_fee_event_hash] }) set_withdrawal_fee_event_hash = w3.sha3( text="SetWithdrawalFeeEvent(address,uint256,uint256)").hex() set_withdrawal_fee_event_filter = w3.eth.filter( filter_params={ "address": heimdall_contract_address, "topics": [set_withdrawal_fee_event_hash] }) try: while True: print("\t--") heimdall_contract.functions.toggleContractOpen().transact() heimdall_contract.functions.setWithdrawalFee(50).transact() for event in toggle_contract_open_event_filter.get_new_entries(): handle_toggle_contract_open_event(event["data"], state_vars) print("toggled", event) for event in deposit_event_filter.get_new_entries(): handle_deposit_event(event["data"], state_vars) for event in start_withdrawal_event_filter.get_new_entries(): handle_start_withdrawal_event(event["data"], heimdall_contract, state_vars) for event in approve_withdrawal_event_filter.get_new_entries(): handle_approve_withdrawal_event(event["data"], state_vars) for event in deny_withdrawal_event_filter.get_new_entries(): handle_deny_withdrawal_event(event["data"], state_vars) for event in set_deposit_fee_event_filter.get_new_entries(): handle_set_deposit_fee_event(event["data"], state_vars) for event in set_withdrawal_fee_event_filter.get_new_entries(): handle_set_withdrawal_fee_event(event["data"], state_vars) # update topl data time.sleep(2) except: if state_vars["contract_open"]: tx_toggle_contract_open(heimdall_contract)
# from web3.auto.infura.rinkeby import w3 from web3.auto import w3 #测试节点是否可连接 connected = w3.isConnected() print("connected:", connected)
def _check_connection(): if not w3.isConnected(): raise Exception("Could not connect to the node", '')
pd.options.mode.chained_assignment = None ##################### ## connect to node ## ##################### class EmptyProvider(Exception): # pylint: disable=C0115 pass if "WEB3_PROVIDER_URI" not in os.environ: raise EmptyProvider("Environment variable WEB3_PROVIDER_URI is not set.") assert w3.isConnected(), "problem connecting to node" ###################### ## initialize cache ## ###################### def _init_cache(): def _should_cache(method, params, response): if 'error' in response: return False if 'result' not in response: return False if response['result'] is None: return False return True
def allocate_drop(): global rando # load traits traits = load_traits() # load sales abi with open('sales_abi.json') as json_file: sales_abi = json.load(json_file) # load rando abi with open('rando_abi.json') as json_file: rando_abi = json.load(json_file) #print(abi) # making sure we are connected print(w3.isConnected()) # initialize contract ec = w3.eth.contract(address='0x97CA7FE0b0288f5EB85F386FeD876618FB9b8Ab8', abi=sales_abi) rando = w3.eth.contract( address='0xdc21eB6f0dacFba4dE360f3C6548A9c4B708c123', abi=rando_abi) # create records folder if necessary if not os.path.exists(results_folder): os.makedirs(results_folder) # loop through the 10k tokens # and merge the new traits with the metadata for i in range(10, 10000): print("card", i) print("") # load existing metadata metadata_url = ec.functions.tokenURI(i).call() metadata = json.loads(requests.get(metadata_url).text) # add accepted for j in range(len(metadata["traits"])): metadata["traits"][j]["accepted"] = "true" # load new traits print("new traits:") nt = load_new_traits(i) new_traits = nt["traits"] # loop through new traits and find descriptions for t in new_traits: print("trait name:", t) n = {} n["name"] = traits[t]["name"] n["description"] = traits[t]["description"] n["id"] = traits[t]["id"] n["icon"] = traits[t]["filename"] + ".png" n["accepted"] = "false" metadata["traits"].append(n) # save merged metadata # create subfolder if needed subfolder = os.path.join(results_folder, (str(i % 100))) if not os.path.exists(subfolder): os.makedirs(subfolder) filename = os.path.join(subfolder, (str(i) + ".json")) with open(filename, "w") as write_file: json.dump(metadata, write_file, indent=4) print("written", filename) print("==================================")
#!/usr/bin/env python3 import traceback from web3.auto import w3 assert w3.isConnected() # personal.unlockAccount('0xdF3097865fF3EA3EEC483Bb229322c255332A695') print(w3.eth.coinbase) ss = eval(input()) for k, v in ss.items(): print("payout", k, v) try: ret = w3.eth.sendTransaction({ 'to': w3.toChecksumAddress(k.decode('utf-8')), 'from': w3.eth.coinbase, 'value': v * 10**18, 'gasPrice': 1 }) print(ret) except Exception: print("PAYOUT FAILED") traceback.print_exc()