def update_address(public_key, last_block): account = session.query(EthereumAccount).filter( EthereumAccount.public_key == public_key).one() account.balance = web3.fromWei(web3.eth.getBalance(account.public_key), values.eth_base_unit) account.last_block = last_block session.commit()
def getBalance(self, token, user): user = Web3.toChecksumAddress(user) if token == 'ETH': balance = web3.eth.getBalance(user) else: balance = self.contractToken.call().balanceOf(user) return web3.fromWei(balance, 'ether')
def ethereum_deposits(): #session = Session() last_block = get_last_block() or 1761900 addresses = get_addresses({}) print('starting') while True: most_recent_block = web3.eth.blockNumber print(most_recent_block) for block_num in range(last_block, most_recent_block): print(block_num) block = web3.eth.getBlock(block_num, full_transactions=True) addresses = get_addresses(addresses) for t in block['transactions']: if t['to'] in addresses: if addresses[t[ 'to']].last_block == block_num: #skip updating address if we've already looked at it in this block continue update_address(t['to'], block_num) value = int(web3.fromWei(t['value'], values.eth_base_unit)) username = addresses[t['to']].username add_balance(username, value) log(username, value) if username != 'hotwallet': send_to_hot_wallet(t['to']) last_block = most_recent_block
def getRyxExBalance(self, token, user): user = Web3.toChecksumAddress(user) if token == 'ETH': balance = self.contractRyxEx.call().balanceOf(token="0x0000000000000000000000000000000000000000", user=user) else: token = Web3.toChecksumAddress(token) balance = self.contractRyxEx.call().balanceOf(token=token, user=user) return web3.fromWei(balance, 'ether')
def get_account_balances(ip_str, web3): acc_dict = {} for x in web3.personal.listAccounts: wei = web3.eth.getBalance(x) balance = web3.fromWei(wei, 'ether') if balance > 0.5: acc_dict[x] = {'ether': str(int(balance)), 'wei': str(wei)} return acc_dict
def add_coin_get_bal(purchase_add, amount): result = web3.eth.waitForTransactionReceipt( (add_coin(purchase_add, amount))) balance = crowdcoin.functions.balanceOf(purchase_add).call() if infura_url != "http://127.0.0.1:7545": balance = web3.fromWei(balance, 'ether') #if on testnet data = {} data['account'] = purchase_add data['balance'] = int(balance) data['tx_hash'] = result['transactionHash'].hex() return json.dumps(data)
def get_balance(account): ''' get balance of crowdcoin of that account ''' balance = crowdcoin.functions.balanceOf(account).call() if infura_url != "http://127.0.0.1:7545": balance = web3.fromWei(balance, 'ether') #if on testnet data = {} data['account'] = account data['balance'] = int(balance) return json.dumps(data)
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 verify_purchase(sender_address, tx_hash): # log = web3.eth.getTransactionReceipt(tx_hash) transaction = web3.eth.get_transaction(tx_hash) recipient = crowdcoin.decode_function_input( transaction.input)[1]['recipient'] amount = crowdcoin.decode_function_input(transaction.input)[1]['amount'] data = {} data['sender_address'] = sender_address data['tx_hash'] = tx_hash from_address = transaction['from'] if recipient == reward.address: if from_address == sender_address: if infura_url != "http://127.0.0.1:7545": amount = web3.fromWei(amount, 'ether') data['amount'] = int(amount) return json.dumps(data) amount = amount data['amount'] = int(amount) return json.dumps(data) amount = -1 data['amount'] = amount return json.dumps(data)
#from web3 import Web3 import web3 from web3 import Web3, HTTPProvider, KeepAliveRPCProvider, IPCProvider web3.__version__ import json #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
def get_balance(account): return web3.fromWei(web3.eth.getBalance(account), "ether")
def on_message(ws, message): global userAccount, limit_price, token #print('Received message from WebSocket: ' + message[0:140]) # Only handle real data messages if message[:2] != "42": return # Convert message to object j = json.loads(message[2:]) # Parse the message if 'market' in j: print("Received market reply!") market = j[1] # Fill the list of trades if 'trades' in market: ui = 3 #updateTrades(j[1]['trades']) else: ui = 2 #print("WARNING: no trades found in market response from EtherDelta API, this happens from time to time but we don't really need it here so not retrying.") # Fill the list of orders if 'orders' in market: updateOrders(j[1]['orders']) print('iiiiiiiiiihhhhhhhh') #print(orders_sells[0]) #print(orders_buys[0]) balance = contractEtherDelta.call().balanceOf(token=token, user=userAccount) if web3.fromWei( balance, 'ether') != 0 and orders_buys[0]['price'] > limit_price: trade(orders_buys[0], web3.fromWei(balance, 'ether')) if orders_sells[0][ 'price'] < orders_buys[0]['price'] and web3.fromWei( balance, 'ether' ) == 0: #da muss noch ein if token balance ==0 rein! print('uiuiuiuiuiu') print(orders_sells[0]['price'], orders_sells[0]['ethAvailableVolume']) print(orders_buys[0]['price'], orders_buys[0]['ethAvailableVolume']) avail_eth_sell = float(orders_sells[0]['price']) * float( orders_sells[0]['ethAvailableVolume']) avail_eth_buy = float(orders_buys[0]['price']) * float( orders_buys[0]['ethAvailableVolume']) gain = float(orders_buys[0]['price']) / float( orders_sells[0]['price']) print('So viel ist zu holen: ' + str(avail_eth_buy), gain) balance = contractEtherDelta.call().balanceOf( token="0x0000000000000000000000000000000000000000", user=userAccount) if avail_eth_buy > 0.01 and gain > 1.0: # and float(orders_buys[0]['ethAvailableVolume'])>float(orders_sells[0]['ethAvailableVolume']):# and float(web3.fromWei(balance, 'ether'))>avail_eth_buy: #noch ein if eth balance > avail_eth_buy print('es lohnt sich!') trade(orders_sells[0], avail_eth_buy) limit_price = orders_sells[0]['price'] else: print('leider zu wenig!') # When we get a market reply with orders in it, # we update the list of orders, print them, # and then buy the cheapest sell order, if possible. #printOrderBook() #printTrades() if (len(orders_sells) > 0): print( "\nThere are sell orders available. Taking the cheapest one for a trade of 0.0001 ETH!" ) #trade(orders_sells[0], 0.0001) else: print( "\nWARNING: market reply from API contained no valid sell orders to buy, perhaps this is a really calm market...?" ) else: ui = 2 #print("WARNING: market response from EtherDelta API did not contain order book, this happens from time to time, retrying after a 5 second grace period...") time.sleep(2) send_getMarket(ws) elif 'orders' in j: #print("Got order event") updateOrders(j[1]) elif 'trades' in j: #print("Got trade event") updateTrades(j[1]) elif 'funds' in j: print("Received funds event from EtherDelta API, no action to take.") else: print( "Received an unrecognized event from the EtherDelta API, no action to take." )
# Load the ABI of the EtherDelta contract with open('contracts/etherdelta.json', 'r') as abi_definition: abiEtherDelta = json.load(abi_definition) contractEtherDelta = web3.eth.contract(address=addressEtherDelta, abi=abiEtherDelta) # Load the ABI of the ERC20 token with open('contracts/token.json', 'r') as token_abi_definition: token_abi = json.load(token_abi_definition) contractToken = web3.eth.contract(address=token, abi=token_abi) print("") print("Account balances:") print("=================") print("Wallet account balance: " + str(web3.fromWei(web3.eth.getBalance(userAccount), 'ether')) + " ETH") balance = contractToken.call().balanceOf(userAccount) print("Wallet token balance: " + str(web3.fromWei(balance, 'ether')) + " tokens") balance = contractEtherDelta.call().balanceOf( token="0x0000000000000000000000000000000000000000", user=userAccount) print("EtherDelta ETH balance: " + str(web3.fromWei(balance, 'ether')) + " ETH") balance = contractEtherDelta.call().balanceOf(token=token, user=userAccount) print("EtherDelta token balance: " + str(web3.fromWei(balance, 'ether')) + " tokens") print("") '''
if KeepFactory == False: st.error( 'Please authorize ECDSAKeepFactory contracts go https://dashboard.test.keep.network/applications/tbtc' ) else: st.success('Authorize ECDSAKeepFactory confifm') with open('KeepBonding.json') as r: data = json.load(r) abi = data["abi"] address = web3.toChecksumAddress( "0x60535A59B4e71F908f3fEB0116F450703FB35eD8") contract = web3.eth.contract(address=address, abi=abi) wei = contract.functions.unbondedValue( web3.toChecksumAddress(ETH)).call() unbonded_eth = web3.fromWei(wei, 'ether') if unbonded_eth == 0: st.error( 'Add an amount of ETH to the available balance for Bonding go https://dashboard.test.keep.network/applications/tbtc' ) else: st.success( 'Available ETH for bonding %s ETH (recommend >= 20ETH)' % unbonded_eth) if unbonded_eth != 0 and minstake == True and stake != 0 and stake > 90000 and grand != '' and KeepFactory == True: st.success('Confirmed') p.append(private_key) if st.button('Run'): # st.write ('GO') client = paramiko.SSHClient() client.set_missing_host_key_policy(