def _ether_transfer(address_to, value): # get saleLow price from Ethereum Gas Sation response = requests.get('https://ethgasstation.info/json/ethgasAPI.json') gas_price = int((int(response.json()['safeLow']) / 10)) print('gas price safeLow = ', gas_price, ' gwei') nonce = w3.eth.getTransactionCount(Talao_wallet_ethereum) transaction = { 'to': address_to, 'value': value, 'gas': 25000, 'gasPrice': w3.toWei(gas_price, 'gwei'), 'nonce': nonce, 'chainId': 1 } #sign transaction with TalaoGen wallet signed_txn = w3.eth.account.sign_transaction( transaction, Talao_wallet_ethereum_private_key) try: w3.eth.sendRawTransaction(signed_txn.rawTransaction) except: return None hash = w3.toHex(w3.keccak(signed_txn.rawTransaction)) print('ether transfer transaction = ', hash) receipt = w3.eth.waitForTransactionReceipt(hash, timeout=2000) if receipt['status'] == 0: return None return hash
def _createVaultAccess(address, private_key): # get saleLow price from Ethereum Gas Sation response = requests.get('https://ethgasstation.info/json/ethgasAPI.json') gas_price = int((int(response.json()['safeLow']) / 10)) print('gas price safeLow = ', gas_price, ' gwei') contract = w3.eth.contract(Talao_token_contract, abi=constante.Talao_Token_ABI) nonce = w3.eth.getTransactionCount(address) txn = contract.functions.createVaultAccess(0).buildTransaction({ 'chainId': 1, 'gas': 100000, 'gasPrice': w3.toWei(gas_price, 'gwei'), 'nonce': nonce, }) signed_txn = w3.eth.account.signTransaction(txn, private_key) w3.eth.sendRawTransaction(signed_txn.rawTransaction) hash = w3.toHex(w3.keccak(signed_txn.rawTransaction)) print('create vault access transaction = ', hash) receipt = w3.eth.waitForTransactionReceipt(hash, timeout=2000, poll_latency=1) if receipt['status'] == 0: return None return hash
def get_back_eth(address, private_key): # get saleLow price from Ethereum Gas Sation response = requests.get('https://ethgasstation.info/json/ethgasAPI.json') gas_price = int((int(response.json()['safeLow']) / 10)) print('gas price safeLow = ', gas_price, ' gwei') # get balance and sub transation fees balance = w3.eth.getBalance(address) print('Remaining balance (wei) ', balance) cost = w3.toWei(gas_price, 'gwei') * 21000 if cost > balance: print('Not enough Eth to get them back from ', address) return 0 eth_value = balance - cost print('Eth to transfer back (wei) : ', eth_value) nonce = w3.eth.getTransactionCount(address) transaction = { 'to': Talao_wallet_ethereum, 'value': eth_value, 'gas': 21000, 'gasPrice': w3.toWei(gas_price, 'gwei'), 'nonce': nonce, 'chainId': 1 } #sign transaction with address private key signed_txn = w3.eth.account.sign_transaction(transaction, private_key) w3.eth.sendRawTransaction(signed_txn.rawTransaction) hash = w3.toHex(w3.keccak(signed_txn.rawTransaction)) print('Get back ether transaction = ', hash) return hash
def swap(self, from_token, to_token, quantity): if not self.config_check(): return account = w3.eth.account.privateKeyToAccount(privateKey) quote = self.quote(from_token, to_token, quantity) min_return = quote[0] distribution = quote[1] disable_flags = 0 one_inch_join = w3.eth.contract(address=one_inch_split_contract, abi=one_inch_split_abi) nonce = w3.eth.getTransactionCount(self.get_public_key()) print("From Token Info: {}".format(self.get_token_info(from_token))) print("To Token Info: {}".format(self.get_token_info(to_token))) if from_token.lower() == "eth": value = quantity else: value = 0 data = one_inch_join.encodeABI(fn_name="swap", args=[ w3.toChecksumAddress(self.get_token_info(from_token)["address"]), w3.toChecksumAddress(self.get_token_info(to_token)["address"]), quantity, min_return, distribution, disable_flags]) tx = { 'nonce': nonce, 'to': one_inch_split_contract, 'value': value, 'gasPrice': w3.toWei(40, 'gwei'), 'from': self.get_public_key(), 'data': data } try: gas = w3.eth.estimateGas(tx) print("Gas Supplied: {}".format(gas)) tx["gas"] = gas except Exception as e: print(e) return print('transaction data: {0}'.format(tx)) try: signed_tx = w3.eth.account.signTransaction(tx, account.privateKey) except Exception as e: print(e) return False try: tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction) print("TXID: {0}".format(w3.toHex(tx_hash))) except Exception as e: print(e) return False
def verify_eth_get_proof(proof, root): trie_root = Binary.fixed_length(32, allow_empty=True) hash32 = Binary.fixed_length(32) class _Account(rlp.Serializable): fields = [('nonce', big_endian_int), ('balance', big_endian_int), ('storage', trie_root), ('code_hash', hash32)] acc = _Account(proof.nonce, proof.balance, w3.toBytes(hexstr=w3.toHex(proof.storageHash)), w3.toBytes(hexstr=w3.toHex(proof.codeHash))) rlp_account = rlp.encode(acc) trie_key = keccak(w3.toBytes(hexstr=proof.address)) trie_proof = format_proof_nodes(proof.accountProof) leaf = HexaryTrie.get_from_proof(root, trie_key, trie_proof) if acc == b'': print("Verify that the account does not exist") else: assert rlp_account == leaf, "Failed to verify account proof {}".format( proof.address) print("Succeed to verify account proof {}".format(proof.address)) return True
def approve_tokens(self, token, amount): if not self.config_check(): return token_address = w3.toChecksumAddress(self.get_token_info(token)["address"]) mcd_contract = w3.eth.contract(address=token_address, abi=mcd_abi) self.get_allowance(token) base_account = w3.eth.account.privateKeyToAccount(privateKey) nonce = w3.eth.getTransactionCount(base_account.address) data = mcd_contract.encodeABI(fn_name="approve", args=[one_inch_split_contract, amount]) tx = { 'nonce': nonce, 'to': token_address, 'value': 0, 'gasPrice': w3.toWei(40, 'gwei'), 'from': base_account.address, 'data': data } try: gas = w3.eth.estimateGas(tx) print("Gas Supplied: {}".format(gas)) tx["gas"] = gas except Exception as e: print(e) return try: signed_tx = w3.eth.account.signTransaction(tx, privateKey) except Exception as e: print(e) return try: tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction) print("TXID from 1 Inch: {0}".format(w3.toHex(tx_hash))) except Exception as e: print(e) return
('gas', big_endian_int), ('to', address), ('value', big_endian_int), ('data', binary), ('v', big_endian_int), ('r', big_endian_int), ('s', big_endian_int)] BLANK_ROOT_HASH = Hash32( b'V\xe8\x1f\x17\x1b\xccU\xa6\xff\x83E\xe6\x92\xc0\xf8n\x5bH\xe0\x1b\x99l\xad\xc0\x01b/\xb5\xe3c\xb4!' ) Transactions = Sequence[_Transaction] TrieRootAndData = Tuple[Hash32, Dict[Hash32, bytes]] block = w3.eth.getBlock(8290728) trie = HexaryTrie(db={}) assert trie.root_hash == BLANK_ROOT_HASH print(w3.toHex(trie.root_hash)) # Generate Merkle tree txs = [] B = len(block.transactions) print("The block has %d transactions" % B) for key in range(B): tx = w3.eth.getTransaction(block.transactions[key]) raw_tx = _Transaction(tx.nonce, tx.gasPrice, tx.gas, w3.toBytes(hexstr=tx.to), tx.value, w3.toBytes(hexstr=w3.toHex(hexstr=tx.input)), tx.v, w3.toInt(tx.r), w3.toInt(tx.s)) rlp_tx = rlp.encode(raw_tx) assert tx.hash == keccak(rlp_tx) txs.append(raw_tx) trie.set(rlp.encode(key), rlp_tx)
def _bridge(address, private_key): # Get private key for Talao Wallet global Talao_wallet_ethereum_private_key keys = json.load(open('./keys.json')) Talao_wallet_ethereum_private_key = keys['ethereum'][ 'talao_wallet_ethereum_private_key'] print('wallet private key = ', Talao_wallet_ethereum_private_key) # confirm that the connection succeeded if not w3.isConnected(): print('Blockchain non connectée') return False # get current vault deposit on TALAO token smart contract on Ethereum contract = w3.eth.contract(Talao_token_contract, abi=constante.Talao_Token_ABI) vault_deposit = contract.functions.vaultDeposit().call() """ # Get estimate of Eth to transfer response = requests.get('https://ethgasstation.info/json/ethgasAPI.json') gas_price = int((int(response.json()['safeLow'])/10)) print('gas price safeLow = ', gas_price, ' gwei') value = (115000 + 30000) * w3.toWei(gas_price, 'gwei') print('to be transfered to address (Ether) = ',w3.fromWei(value, 'ether')) # Transfert Eth to address to complete create workspace transaction if _ether_transfer(address, value) is None : print('pb transfer Eth') return False # Transfert Talao token to complete create workspace transaction if _token_transfer(address, vault_deposit) is None : print('pb trasnfer token') return False # Create Vault Access on Ethereum Talao Token smart contract if _createVaultAccess(address, private_key) is None : print('pb create vault access') return False # Get Eth back to Talao Wallet if get_back_eth(address, private_key) is None : print('pb get back ether') return False print('Ethereum Talao Token synchronization is over for ', address) """ # en attendant que les transaction fee baissent...on transfer les token du vault depsoit sur le token response = requests.get('https://ethgasstation.info/json/ethgasAPI.json') gas_price = int((int(response.json()['safeLow']) / 10)) print('Warning : gas price safeLow = ', gas_price, ' gwei') if gas_price > 40: gas_price = 40 address_to = Talao_token_contract value = vault_deposit contract = w3.eth.contract(Talao_token_contract, abi=constante.Talao_Token_ABI) nonce = w3.eth.getTransactionCount(Talao_wallet_ethereum) print('Warning : nonce =', nonce) txn = contract.functions.transfer(address_to, value).buildTransaction({ 'chainId': 1, 'gas': 100000, 'gasPrice': w3.toWei(gas_price, 'gwei'), 'nonce': nonce, }) signed_txn = w3.eth.account.signTransaction( txn, Talao_wallet_ethereum_private_key) try: w3.eth.sendRawTransaction(signed_txn.rawTransaction) hash = w3.toHex(w3.keccak(signed_txn.rawTransaction)) print('Warning : token transfer transaction brdge_ethereum.py= ', hash) #receipt = w3.eth.waitForTransactionReceipt( # hash, timeout=2000, poll_latency=1) #if receipt['status'] == 0: # print('transaction failed') # return None #print('Ethereum Talao Token synchronization is done for ', address) return hash except: print('transaction refused') return None
from web3.auto.infura import w3 from rlp.sedes import (Binary, big_endian_int, binary) import rlp from eth_utils import ( keccak, ) address = Binary.fixed_length(20, allow_empty=True) class _Transaction(rlp.Serializable): fields = [('nonce', big_endian_int), ('gas_price', big_endian_int), ('gas', big_endian_int), ('to', address), ('value', big_endian_int), ('data', binary), ('v', big_endian_int), ('r', big_endian_int), ('s', big_endian_int)] tx = w3.eth.getTransaction( 0x95604ade1cd64e12851e9626270fe1b61b3034293ae6d6d85fcf27b19d146c28) raw_tx = _Transaction(tx.nonce, tx.gasPrice, tx.gas, w3.toBytes(hexstr=tx.to), tx.value, w3.toBytes(hexstr=w3.toHex(hexstr=tx.input)), tx.v, w3.toInt(tx.r), w3.toInt(tx.s)) rlp_tx = rlp.encode(raw_tx) assert tx.hash == keccak(rlp_tx) print(True)
class _BlockHeader(rlp.Serializable): fields = [('parent_hash', hash32), ('uncles_hash', hash32), ('coinbase', address), ('state_root', trie_root), ('transaction_root', trie_root), ('receipt_root', trie_root), ('bloom', uint256), ('difficulty', big_endian_int), ('block_number', big_endian_int), ('gas_limit', big_endian_int), ('gas_used', big_endian_int), ('timestamp', big_endian_int), ('extra_data', binary), ('mix_hash', binary), ('nonce', Binary(8, allow_empty=True))] block = w3.eth.getBlock(8290728) raw_block = _BlockHeader(w3.toBytes(hexstr=w3.toHex(block.parentHash)), w3.toBytes(hexstr=w3.toHex(block.sha3Uncles)), w3.toBytes(hexstr=block.miner), w3.toBytes(hexstr=w3.toHex(block.stateRoot)), w3.toBytes(hexstr=w3.toHex(block.transactionsRoot)), w3.toBytes(hexstr=w3.toHex(block.receiptsRoot)), w3.toInt(block.logsBloom), block.difficulty, block.number, block.gasLimit, block.gasUsed, block.timestamp, block.extraData, block.mixHash, block.nonce) rlp_block = rlp.encode(raw_block) assert keccak(rlp_block) == block.hash print(True)
def format_proof_nodes(proof): trie_proof = [] for rlp_node in proof: trie_proof.append(rlp.decode(w3.toBytes(hexstr=w3.toHex(rlp_node)))) return trie_proof
('gas', big_endian_int), ('to', address), ('value', big_endian_int), ('data', binary), ('v', big_endian_int), ('r', big_endian_int), ('s', big_endian_int)] BLANK_ROOT_HASH = Hash32( b'V\xe8\x1f\x17\x1b\xccU\xa6\xff\x83E\xe6\x92\xc0\xf8n\x5bH\xe0\x1b\x99l\xad\xc0\x01b/\xb5\xe3c\xb4!' ) Transactions = Sequence[_Transaction] TrieRootAndData = Tuple[Hash32, Dict[Hash32, bytes]] block = w3.eth.getBlock(8290728) trie = HexaryTrie(db={}) assert trie.root_hash == BLANK_ROOT_HASH print(w3.toHex(trie.root_hash)) txs = [] B = len(block.transactions) for key in range(B): tx = w3.eth.getTransaction(block.transactions[key]) raw_tx = _Transaction(tx.nonce, tx.gasPrice, tx.gas, w3.toBytes(hexstr=tx.to), tx.value, w3.toBytes(hexstr=w3.toHex(hexstr=tx.input)), tx.v, w3.toInt(tx.r), w3.toInt(tx.s)) rlp_tx = rlp.encode(raw_tx) assert tx.hash == keccak(rlp_tx) txs.append(raw_tx) trie.set(rlp.encode(key), rlp_tx) assert block.transactionsRoot == trie.root_hash