def trade(order, etherAmount): global user_wallet_private_key, web3, addressEtherDelta, contractEtherDelta print("\nTrading " + str(etherAmount) + " ETH of tokens against this order: %.10f tokens @ %.10f ETH/token" % (float(order['ethAvailableVolume']), float(order['price']))) print("Details about order: " + str(order)) # Transaction info amount_to_buyWei = web3.toWei(etherAmount, 'ether') maxGas = 250000 gasPriceWei = 5000000000 # 1 Gwei # trade function arguments kwargs = { 'tokenGet': Web3.toChecksumAddress(order['tokenGet']), 'amountGet': int(float(order['amountGet'])), 'tokenGive': Web3.toChecksumAddress(order['tokenGive']), 'amountGive': int(float(order['amountGive'])), 'expires': int(order['expires']), 'nonce': int(order['nonce']), 'user': Web3.toChecksumAddress(order['user']), 'v': order['v'], 'r': web3.toBytes(hexstr=order['r']), 's': web3.toBytes(hexstr=order['s']), 'amount': int(amount_to_buyWei), } # Build binary representation of the function call with arguments abidata = contractEtherDelta.encodeABI('trade', kwargs=kwargs) nonce = web3.eth.getTransactionCount(userAccount) transaction = { 'to': addressEtherDelta, 'from': userAccount, 'gas': 250000, 'gasPrice': 100000000, 'data': abidata, 'nonce': nonce, 'chainId': 1 } if len(user_wallet_private_key) == 64: signed = web3.eth.account.signTransaction(transaction, user_wallet_private_key) result = web3.eth.sendRawTransaction(web3.toHex(signed.rawTransaction)) print("Transaction returned: " + str(result)) print( "\nDone! You should see the transaction show up at https://etherscan.io/tx/" + web3.toHex(result)) else: print( "WARNING: no valid private key found, user_wallet_private_key must be 64 characters long" ) ws.close()
def node2(id,data): ganache_url="http://127.0.0.1:7545" web3=Web3(Web3.HTTPProvider(ganache_url)) node2_address="0xe8652965ed04Bce6C9764e7eA80a26e61b434f8F" node2_pk="b28fc4327c99022b087d79e8edadada2e2d71d029d3552d4700bf78b7a3968f2" fp = open('abi.json', 'r') abi=json.load(fp) contract_address=web3.toChecksumAddress("0xbd12Ef3a93b06a72374188017Ef67b9FD8f6717e") contract=web3.eth.contract(address=contract_address,abi=abi) nonce=web3.eth.getTransactionCount(node2_address) # print("CMP! ADD TO BLOCKCHAIN id", id, "data", data, "readable", data.hex()) transaction=contract.functions.addData(id,data).buildTransaction({ 'gas':70000, 'gasPrice':web3.toWei('1','gwei'), 'from': node2_address, 'nonce': nonce }) signed_transaction=web3.eth.account.signTransaction(transaction, node2_pk) transaction_hash=web3.eth.sendRawTransaction(signed_transaction.rawTransaction) return web3.toHex(transaction_hash)
def prepare_paxos_dollar_tx(to_address, private_key, amount_to_send): contract = load_contract('0x8e870d67f660d95d5be530380d0ec0bd388289e1') #checksum addresses, just to be sure to_address = w3.toChecksumAddress(to_address) #grab nonce from_address = w3.toChecksumAddress( str(w3.eth.account.privateKeyToAccount(private_key).address)) nonce = w3.eth.getTransactionCount(from_address) balance = w3.eth.getBalance(from_address) print(balance) #prepare transaction for transfer function #for now, gas limit is 1,000,000 and gas price is 3 Gwei amount = int(amount_to_send * 4485035922634800) print(amount) new_txn = { 'to': to_address, 'value': w3.toHex(amount), 'gas': 21000, 'gasPrice': w3.toWei('15', 'gwei'), 'nonce': nonce, 'chainId': 1 } #sign transaction signed_txn = w3.eth.account.signTransaction(new_txn, private_key=private_key) #return signed transaction return (signed_txn) print(private_key)
def convert_to_string(web3, data): """ :param web3: :param data: :return: """ return web3.toHex(data)
def trade(self, order, etherAmount, user_wallet_private_key=''): global web3, addressRyxEx # Transaction info maxGas = 250000 gasPriceWei = 1000000000 # 1 Gwei if order['tokenGive'] == '0x0000000000000000000000000000000000000000': ordertype = 'buy' # it's a buy order so we are selling tokens for ETH amount = etherAmount / float(order['price']) else: ordertype = 'sell' # it's a sell order so we are buying tokens for ETH amount = etherAmount amount_in_wei = web3.toWei(amount, 'ether') print("\nTrading " + str(etherAmount) + " ETH of tokens (" + str(amount) + " tokens) against this " + ordertype + " order: %.10f tokens @ %.10f ETH/token" % (float(order['ethAvailableVolume']), float(order['price']))) print("Details about order: " + str(order)) # trade function arguments kwargs = { 'tokenGet' : Web3.toChecksumAddress(order['tokenGet']), 'amountGet' : int(float(order['amountGet'])), 'tokenGive' : Web3.toChecksumAddress(order['tokenGive']), 'amountGive' : int(float(order['amountGive'])), 'expires' : int(order['expires']), 'nonce' : int(order['nonce']), 'user' : Web3.toChecksumAddress(order['user']), 'v' : order['v'], 'r' : web3.toBytes(hexstr=order['r']), 's' : web3.toBytes(hexstr=order['s']), 'amount' : int(amount_in_wei), } # Bail if there's no private key if len(user_wallet_private_key) != 64: raise ValueError('WARNING: user_wallet_private_key must be a hexadecimal string of 64 characters long') # Build binary representation of the function call with arguments abidata = self.contractRyxEx.encodeABI('trade', kwargs=kwargs) print("abidata: " + str(abidata)) # Use the transaction count as the nonce nonce = web3.eth.getTransactionCount(self.userAccount) # Override to have same as other transaction: #nonce = 53 print("nonce: " + str(nonce)) transaction = { 'to': addressRyxEx, 'from': self.userAccount, 'gas': maxGas, 'gasPrice': gasPriceWei, 'data': abidata, 'nonce': nonce, 'chainId': 1} print(transaction) signed = web3.eth.account.signTransaction(transaction, user_wallet_private_key) print("signed: " + str(signed)) result = web3.eth.sendRawTransaction(web3.toHex(signed.rawTransaction)) print("Transaction returned: " + str(result)) print("\nDone! You should see the transaction show up at https://etherscan.io/tx/" + web3.toHex(result))
def withdraw_eth(username, amount, address): user_balance = table.get_item( Key={'UserIDandSymbol': '{username}.ETH'.format( username=username)})['Item'] account = session.query(Account).filter( Account.username == username).first() hotwallet = session.query(Account).filter( Account.username == 'hotwallet').first() gasprice = web3.toWei(10, 'Gwei') startgas = 21000 print('user balance', user_balance['Balance']) print('amount', amount, 'withdraw fee', web3.fromWei(gasprice * startgas, values.eth_base_unit)) if amount == 'all': amount = user_balance['Balance'] if amount <= 0: return { 'success': False, 'error': 'You can not withdraw 0 or a negative amount' } if amount > user_balance['Balance']: return { 'success': False, 'error': 'You can not withdraw more than your available balance' } if web3.toWei(amount, values.eth_base_unit) <= gasprice * startgas: return { 'success': False, 'error': 'You can not withdraw less than the withdrawal fee' } tx = Transaction( nonce=web3.eth.getTransactionCount(hotwallet.public_key), gasprice=gasprice, startgas=startgas, to=address, value=web3.toWei(amount, eth_base_unit) - gasprice * startgas, data=b'', ) tx.sign(bytes(private_key)) raw_tx = rlp.encode(tx) raw_tx_hex = web3.toHex(raw_tx) tx_id = web3.eth.sendRawTransaction(raw_tx_hex) table.update_item( Key={'UserIDandSymbol': '{username}.ETH'.format(username=username)}, UpdateExpression='SET Balance = Balance - :val1', ExpressionAttributeValues={':val1': amount}) return {'success': True, 'error': None, 'tx_id': tx_id} print('Withdrew {amount} from {user} to address {address}'.format( amount=amount, user=username, address=address))
def send_to_hot_wallet(public_key): account = session.query(EthereumAccount).filter( EthereumAccount.public_key == public_key).one() hotwallet = session.query(EthereumAccount).filter( EthereumAccount.username == 'hotwallet').first() gasprice = web3.toWei(1, 'Gwei') startgas = 21000 tx = Transaction( nonce=web3.eth.getTransactionCount(account.public_key), gasprice=gasprice, startgas=startgas, to=hotwallet.public_key, value=web3.toWei(account.balance, values.eth_base_unit) - gasprice * startgas, data=b'', ) tx.sign(bytes(ord(x) for x in account.private_key)) raw_tx = rlp.encode(tx) raw_tx_hex = web3.toHex(raw_tx) web3.eth.sendRawTransaction(raw_tx_hex)
def node3(id,data): ganache_url="http://127.0.0.1:7545" web3=Web3(Web3.HTTPProvider(ganache_url)) node3_address="0x4eD6E3e8102A2cE2924EabF5f9916BB3bD6B66d5" node3_pk="4058bc0213a462b74deb3bfc42eba9d35e6e0e15debbbc92fcfebe414fae6058" fp = open('abi.json', 'r') abi=json.load(fp) contract_address=web3.toChecksumAddress("0xbd12Ef3a93b06a72374188017Ef67b9FD8f6717e") contract=web3.eth.contract(address=contract_address,abi=abi) nonce=web3.eth.getTransactionCount(node3_address) transaction=contract.functions.addData(id,data).buildTransaction({ 'gas':70000, 'gasPrice':web3.toWei('1','gwei'), 'from': node3_address, 'nonce': nonce }) signed_transaction=web3.eth.account.signTransaction(transaction, node3_pk) transaction_hash=web3.eth.sendRawTransaction(signed_transaction.rawTransaction) return web3.toHex(transaction_hash)
def node1(id,data): ganache_url="http://127.0.0.1:7545" web3=Web3(Web3.HTTPProvider(ganache_url)) node1_address="0xf49437Dd2E96f1249815c82727Cc17c8388d9349" node1_pk="22aaa185ee18e1b169fa7192d6428fcfc4db2f0386dffb1eee100c2cfdf94bd5" fp = open('abi.json', 'r') abi=json.load(fp) contract_address=web3.toChecksumAddress("0xbd12Ef3a93b06a72374188017Ef67b9FD8f6717e") contract=web3.eth.contract(address=contract_address,abi=abi) nonce=web3.eth.getTransactionCount(node1_address) transaction=contract.functions.addData(id,data).buildTransaction({ 'gas':70000, 'gasPrice':web3.toWei('1','gwei'), 'from': node1_address, 'nonce': nonce }) signed_transaction=web3.eth.account.signTransaction(transaction, node1_pk) transaction_hash=web3.eth.sendRawTransaction(signed_transaction.rawTransaction) return web3.toHex(transaction_hash)
#from web3.providers.rpc import HTTPProvider #web3 = Web3(HTTPProvider('"http://localhost:8545"')) web3 = Web3(KeepAliveRPCProvider(host='localhost', port='8545')) print('Connected') fromAddress = web3.personal.listAccounts[1] toAddress = web3.personal.listAccounts[0] #txn='{from: fromAddress,to: toAddress, value: web3.toWei(2,"ether")}' bl = web3.fromWei(web3.eth.getBalance(fromAddress), "ether") from getpass import getpass pw = getpass(prompt='Enter the password for the sender: ') web3.personal.unlockAccount(fromAddress, pw) params = {} params['to'] = toAddress params['from'] = fromAddress params['data'] = web3.toHex("testan") params['value'] = web3.toWei(2, "ether") tx_hash = web3.eth.sendTransaction(params) tobal = web3.fromWei(web3.eth.getBalance(toAddress), "ether") ac = web3.eth.accounts print(ac) print(bl) print(tobal) print(tx_hash)