def tx_xfr_info(tx, addr, **kwargs): addr = Web3.toChecksumAddress(addr) info = [] if 'value' in tx and int(tx['value']) > 0: v = Web3.fromWei(int(tx['value']), 'ether') if addr == Web3.toChecksumAddress(tx['from']): info.append(['ETH', 0-v, tx['to']]) elif addr == Web3.toChecksumAddress(tx['to']): info.append(['ETH', v, tx['from']]) # ERC20 events for e in tx.get('_erc20_events') or []: v = int(e['value']) / (10**int(e['tokenDecimal'])) if addr == Web3.toChecksumAddress(e['from']): info.append([e['tokenSymbol'], 0-v, e['to']]) elif addr == Web3.toChecksumAddress(e['to']): info.append([e['tokenSymbol'], v, e['from']]) # Internal transactions for e in tx.get('_internal_txs') or []: v = Web3.fromWei(int(e['value']), 'ether') if addr == Web3.toChecksumAddress(e['from']): info.append(['ETH', 0-v, e['to']]) elif addr == Web3.toChecksumAddress(e['to']): info.append(['ETH', v, e['from']]) # Filter by mode. if kwargs.get('mode') == 'peer': if tx.get('input') == '0x': # ETH xfr only. return info if len(info) != 1: return [] if contract_info(info[0][2]) is not None: return [] # Skip when receiver is a contract. return info return info
def bid(self, label, amount, secret, **modifier_dict): """ @param label to bid on @param amount (in wei) to bid @param secret - as bytes, str, or int. You MUST keep a copy of this to avoid burning your entire deposit! """ if not modifier_dict: modifier_dict = {'transact': {}} if 'transact' in modifier_dict: transact = modifier_dict['transact'] self.__default_gas(transact, 'bid') if 'value' not in transact: transact['value'] = amount elif transact['value'] < amount: raise UnderfundedBid( "Bid of %s ETH was only funded with %s ETH" % (Web3.fromWei(amount, 'ether'), Web3.fromWei(transact['value'], 'ether'))) label = self._to_label(label) sender = self.__require_sender(modifier_dict) if amount < MIN_BID: raise BidTooLow("You must bid at least %s ether" % Web3.fromWei(MIN_BID, 'ether')) bid_hash = self._bid_hash(label, sender, amount, secret) return self.core.newBid(bid_hash, **modifier_dict)
def kitty_sale_callback(event): kittyId = event['args']['tokenId'] startPrice = Web3.fromWei(event['args']['startingPrice'], unit='ether') endPrice = Web3.fromWei(event['args']['endingPrice'], unit='ether') duration = int(event['args']['duration'] / 3600) print("Kitty #{0} for sale: E{1} - E{2}, Duration: {3}h".format( kittyId, startPrice, endPrice, duration))
def get_user_balance(user, filter_ticker=None, human=False): data = {} for ticker, contracts in atokens.items(): if not contracts.get("aave"): continue if filter_ticker and ticker != filter_ticker: continue reserveData = settings.CONTRACT_LP.functions.getUserReserveData( contracts["regular"], user).call() aBalance = reserveData[0] liquidityRate = reserveData[5] if ticker == "ETH": balance = settings.ENDPOINT.eth.getBalance(user) else: contract = settings.ENDPOINT.eth.contract( address=contracts["regular"], abi=aTokenAbi) balance = contract.functions.balanceOf(user).call() if human: aBalance = round(float(Web3.fromWei(aBalance, "ether")), 2) balance = round(float(Web3.fromWei(balance, "ether")), 2) liquidityRate = round( float(liquidityRate / 10000000000000000000000000), 2) data[ticker] = { "balance": balance, "aBalance": aBalance, "APY": liquidityRate } return data
def get_loan_health(self, position_index): health = 0 self.errors = [] if position_index < 0: self.errors.append({ 'label': 'invalid_position_index', 'message': 'Loan position index cannot be negative' }) # get the position position_hash = self.protocol_contract().functions.position_index( Web3.toInt(text=position_index)).call() position = self.protocol_contract().functions.position( position_hash).call() borrow_currency_address = Web3.toChecksumAddress(position[9]) lend_currency_address = Web3.toChecksumAddress(position[10]) initial_collateral_amount = float( Web3.fromWei(float(position[11]), 'ether')) lend_currency_filled = float(Web3.fromWei(float(position[13]), 'ether')) lend_currency_current_rate_per_borrow_currency = cryptocompare_rate( self.supported_addresses[borrow_currency_address], self.supported_addresses[lend_currency_address]) health = initial_collateral_amount * lend_currency_current_rate_per_borrow_currency * 100 / self.initial_margin / lend_currency_filled return health, self.errors
def getTransactionByHash(tx): r = call_api("eth_getTransactionByHash", [tx]) result = r['result'] result['blockNumber'] = Web3.toInt(hexstr=result['blockNumber']) if result['blockNumber'] is not None else 0 result['gas'] = Web3.fromWei(Web3.toInt(hexstr=result['gas']), "Gwei") result['gasPrice'] = Web3.fromWei(Web3.toInt(hexstr=result['gasPrice']), "Gwei") result['value'] = Web3.fromWei(Web3.toInt(hexstr=result['value']), "ether") return result
def formatted(self): d_event = dict() d_event['blockNumber'] = self.blockNumber d_event['timestamp'] = self.timestamp d_event['redeemer'] = self.redeemer d_event['commission'] = Web3.fromWei(self.commission, 'ether') d_event['amount'] = Web3.fromWei(self.amount, 'ether') return d_event
def formatted(self): d_event = dict() d_event['blockNumber'] = self.blockNumber d_event['timestamp'] = self.timestamp d_event['value'] = Web3.fromWei(self.value, 'ether') d_event['e_from'] = Web3.fromWei(self.e_from, 'ether') d_event['e_to'] = Web3.fromWei(self.e_to, 'ether') return d_event
def __init__(self, connection_manager, event): self.blockNumber = event['blockNumber'] ts = connection_manager.block_timestamp(self.blockNumber) dt = ts - datetime.timedelta(hours=self.hours_delta) self.timestamp = dt.strftime("%Y-%m-%d %H:%M:%S") self.riskProTecPrice = Web3.fromWei(event['args']['riskProTecPrice'], 'ether') self.riskProDiscountPrice = Web3.fromWei( event['args']['riskProDiscountPrice'], 'ether') self.amount = Web3.fromWei(event['args']['amount'], 'ether')
def formatted(self): d_event = dict() d_event['blockNumber'] = self.blockNumber d_event['timestamp'] = self.timestamp d_event['leverage'] = Web3.fromWei(self.leverage, 'ether') d_event['riskProxPrice'] = Web3.fromWei(self.riskProxPrice, 'ether') d_event['reservePrice'] = Web3.fromWei(self.reservePrice, 'ether') d_event['startBlockNumber'] = self.startBlockNumber return d_event
def formatted(self): d_event = dict() d_event['blockNumber'] = self.blockNumber d_event['timestamp'] = self.timestamp d_event['stableTokenRedeemCount'] = self.stableTokenRedeemCount d_event['deleveragingCount'] = self.deleveragingCount d_event['riskProxPrice'] = Web3.fromWei(self.riskProxPrice, 'ether') d_event['reservePrice'] = Web3.fromWei(self.reservePrice, 'ether') return d_event
def formatted(self): d_event = dict() d_event['blockNumber'] = self.blockNumber d_event['timestamp'] = self.timestamp d_event['queueSize'] = self.queueSize d_event['accumCommissions'] = Web3.fromWei(self.accumCommissions, 'ether') d_event['reservePrice'] = Web3.fromWei(self.reservePrice, 'ether') return d_event
def escrow(general_config: GroupGeneralConfig, worklock_options: WorkLockOptions, force: bool, hw_wallet: bool, value: Decimal): """Create an ETH escrow, or increase an existing escrow""" emitter, registry, blockchain = worklock_options.setup(general_config=general_config) worklock_agent = ContractAgency.get_agent(WorkLockAgent, registry=registry) # type: WorkLockAgent now = maya.now().epoch if not worklock_agent.start_bidding_date <= now <= worklock_agent.end_bidding_date: emitter.echo(BIDDING_WINDOW_CLOSED, color='red') raise click.Abort() _bidder_address = worklock_options.get_bidder_address(emitter, registry) bidder = worklock_options.create_bidder(registry=registry, hw_wallet=hw_wallet) existing_bid_amount = bidder.get_deposited_eth if not value: if force: raise click.MissingParameter("Missing --value.") if not existing_bid_amount: # It's the first bid minimum_bid = bidder.worklock_agent.minimum_allowed_bid minimum_bid_in_eth = Web3.fromWei(minimum_bid, 'ether') prompt = BID_AMOUNT_PROMPT_WITH_MIN_BID.format(minimum_bid_in_eth=minimum_bid_in_eth) else: # There's an existing bid and the bidder is increasing the amount emitter.message(EXISTING_BID_AMOUNT_NOTICE.format(eth_amount=Web3.fromWei(existing_bid_amount, 'ether'))) minimum_bid_in_eth = Web3.fromWei(1, 'ether') prompt = BID_INCREASE_AMOUNT_PROMPT value = click.prompt(prompt, type=DecimalRange(min=minimum_bid_in_eth)) value = int(Web3.toWei(Decimal(value), 'ether')) if not force: if not existing_bid_amount: paint_bidding_notice(emitter=emitter, bidder=bidder) click.confirm(f"Place WorkLock escrow of {prettify_eth_amount(value)}?", abort=True) else: click.confirm(f"Increase current escrow ({prettify_eth_amount(existing_bid_amount)}) " f"by {prettify_eth_amount(value)}?", abort=True) receipt = bidder.place_bid(value=value) emitter.message("Publishing WorkLock Escrow...") maximum = NU.from_nunits(bidder.economics.maximum_allowed_locked) available_claim = NU.from_nunits(bidder.available_claim) message = f'\nCurrent escrow: {prettify_eth_amount(bidder.get_deposited_eth)} | Allocation: {available_claim}\n' if available_claim > maximum: message += f"\nThis allocation is currently above the allowed max ({maximum}), " \ f"so the escrow may be partially refunded.\n" message += f'Note that the available allocation value may fluctuate until the escrow period closes and ' \ f'allocations are finalized.\n' emitter.echo(message, color='yellow') paint_receipt_summary(receipt=receipt, emitter=emitter, chain_name=bidder.staking_agent.blockchain.client.chain_name)
def formatted(self): d_event = dict() d_event['blockNumber'] = self.blockNumber d_event['timestamp'] = self.timestamp d_event['account'] = self.account d_event['amount'] = Web3.fromWei(self.amount, 'ether') d_event['reserveTotal'] = Web3.fromWei(self.reserveTotal, 'ether') d_event['commission'] = Web3.fromWei(self.commission, 'ether') d_event['reservePrice'] = Web3.fromWei(self.reservePrice, 'ether') return d_event
def bid(general_config, worklock_options, registry_options, force, hw_wallet, value): """Place a bid, or increase an existing bid""" emitter = _setup_emitter(general_config) registry = registry_options.get_registry(emitter, general_config.debug) worklock_agent = ContractAgency.get_agent(WorkLockAgent, registry=registry) # type: WorkLockAgent now = maya.now().epoch if not worklock_agent.start_bidding_date <= now <= worklock_agent.end_bidding_date: raise click.Abort(f"You can't bid, the bidding window is closed.") if not worklock_options.bidder_address: worklock_options.bidder_address = select_client_account(emitter=emitter, provider_uri=registry_options.provider_uri, poa=registry_options.poa, network=registry_options.network, registry=registry, show_balances=True) bidder = worklock_options.create_bidder(registry=registry, hw_wallet=hw_wallet) if not value: if force: raise click.MissingParameter("Missing --value.") existing_bid_amount = bidder.get_deposited_eth if not existing_bid_amount: # It's the first bid minimum_bid = bidder.worklock_agent.minimum_allowed_bid minimum_bid_in_eth = Web3.fromWei(minimum_bid, 'ether') prompt = f"Enter bid amount in ETH (at least {minimum_bid_in_eth} ETH)" else: # There's an existing bid and the bidder is increasing the amount emitter.message(f"You have an existing bid of {Web3.fromWei(existing_bid_amount, 'ether')} ETH") minimum_bid_in_eth = Web3.fromWei(1, 'ether') prompt = f"Enter the amount in ETH that you want to increase your bid" value = click.prompt(prompt, type=DecimalRange(min=minimum_bid_in_eth)) value = int(Web3.toWei(Decimal(value), 'ether')) if not force: paint_bidding_notice(emitter=emitter, bidder=bidder) click.confirm(f"Place WorkLock bid of {prettify_eth_amount(value)}?", abort=True) receipt = bidder.place_bid(value=value) emitter.message("Publishing WorkLock Bid...") maximum = NU.from_nunits(bidder.economics.maximum_allowed_locked) available_claim = NU.from_nunits(bidder.available_claim) message = f'Current bid: {prettify_eth_amount(bidder.get_deposited_eth)} | Claim: {available_claim}\n' if available_claim > maximum: message += f"This claim is currently above the allowed max ({maximum}), so the bid may be partially refunded.\n" message += f'Note that available claim value may fluctuate until bidding closes and claims are finalized.\n' emitter.echo(message, color='yellow') paint_receipt_summary(receipt=receipt, emitter=emitter, chain_name=bidder.staking_agent.blockchain.client.chain_name) return # Exit
def formatted(self): d_event = dict() d_event['blockNumber'] = self.blockNumber d_event['timestamp'] = self.timestamp d_event['riskProTecPrice'] = Web3.fromWei(self.riskProTecPrice, 'ether') d_event['riskProDiscountPrice'] = Web3.fromWei( self.riskProDiscountPrice, 'ether') d_event['amount'] = Web3.fromWei(self.amount, 'ether') return d_event
def classify_pool_share_transfers(transfers: []) -> (str, str): pool_share_burnt = list( filter(lambda x: x['dst'] == ZERO_ADDRESS, transfers)) if len(pool_share_burnt) > 0: return 'pool_amount_in', str( Web3.fromWei(int(pool_share_burnt[0]['amt']), 'ether')) pool_share_minted = list( filter(lambda x: x['src'] == ZERO_ADDRESS, transfers)) if len(pool_share_minted) > 0: return 'pool_amount_out', str( Web3.fromWei(int(pool_share_minted[0]['amt']), 'ether')) raise Exception('not pool share mint or burn', transfers)
def formatted(self): d_event = dict() d_event['blockNumber'] = self.blockNumber if self.timestamp: d_event['timestamp'] = self.timestamp.strftime("%Y-%m-%d %H:%M:%S") else: d_event['timestamp'] = '' d_event['redeemer'] = self.redeemer d_event['commission'] = Web3.fromWei(self.commission, 'ether') d_event['amount'] = Web3.fromWei(self.amount, 'ether') return d_event
def formatted(self): d_event = dict() d_event['blockNumber'] = self.blockNumber if self.timestamp: d_event['timestamp'] = self.timestamp.strftime("%Y-%m-%d %H:%M:%S") else: d_event['timestamp'] = '' d_event['value'] = Web3.fromWei(self.value, 'ether') d_event['e_from'] = Web3.fromWei(self.e_from, 'ether') d_event['e_to'] = Web3.fromWei(self.e_to, 'ether') return d_event
def __init__(self, connection_manager, event): self.blockNumber = event['blockNumber'] try: ts = connection_manager.block_timestamp(self.blockNumber) dt = ts - datetime.timedelta(hours=self.hours_delta) self.timestamp = dt.strftime("%Y-%m-%d %H:%M:%S") except BlockNotFound: self.timestamp = '' self.redeemer = event['args']['redeemer'] self.commission = Web3.fromWei(event['args']['commission'], 'ether') self.amount = Web3.fromWei(event['args']['amount'], 'ether')
def formatted(self): d_event = dict() d_event['blockNumber'] = self.blockNumber if self.timestamp: d_event['timestamp'] = self.timestamp.strftime("%Y-%m-%d %H:%M:%S") else: d_event['timestamp'] = '' d_event['amount'] = Web3.fromWei(self.amount, 'ether') d_event['nReserveBucketC0BeforePay'] = Web3.fromWei( self.nReserveBucketC0BeforePay, 'ether') return d_event
def quotePrice(self, disabledExchanges=None): """ Quote Price function, returns a json with: Returns within json: #################################################################### fromToken: from Token with {"symbol", "name", "decimals", "address"} toToken: to Token with {"symbol", "name", "decimals", "address"} toTokenAmount: How much of toToken you get {amount} fromTokenAmount: Amount of tojens for swap {amount} exchanges: Name and percentage of exchange used {{"name":XXX}, {"part":percentage}} #################################################################### """ # Set the endpoint endpoint = f"https://api.1inch.exchange/v1.1/"\ f"quote?fromTokenSymbol={self.fromToken}"\ f"&toTokenSymbol={self.toToken}&amount={self.amount_wei}" # If ignoring some exchanges if disabledExchanges is not None: endpoint += "&disabledExchangesList=" for exchange in disabledExchanges: endpoint += f"{exchange}," # Generate the request and check that it passed with 200 req = requests.get(endpoint) if req.status_code != 200: raise ValueError(f"Bad Http response {req.status_code}") # Response object jsonResponse = req.json() self.objective_amount_wei = jsonResponse["toTokenAmount"] print(Web3.fromWei(float(self.objective_amount_wei), "ether")) self.objective_amount = float( Web3.fromWei(float(self.objective_amount_wei), "ether")) # Pick out the exchange which uses 100 % _exchangeAllocations = jsonResponse["exchanges"] # Requires 100 % of the trade in one exchange usedExchanges = next( (sub for sub in _exchangeAllocations if sub['part'] == 100), None) try: self.exchange = usedExchanges["name"] except KeyError: raise KeyError("Unable to find an exchange with"\ f"100% liquidity available. Check list {_exchangeAllocations}") return (self.exchange, self.objective_amount)
def formatted(self): d_event = dict() d_event['blockNumber'] = self.blockNumber if self.timestamp: d_event['timestamp'] = self.timestamp.strftime("%Y-%m-%d %H:%M:%S") else: d_event['timestamp'] = '' d_event['queueSize'] = self.queueSize d_event['accumCommissions'] = Web3.fromWei(self.accumCommissions, 'ether') d_event['reservePrice'] = Web3.fromWei(self.reservePrice, 'ether') return d_event
def formatted(self): d_event = dict() d_event['blockNumber'] = self.blockNumber if self.timestamp: d_event['timestamp'] = self.timestamp.strftime("%Y-%m-%d %H:%M:%S") else: d_event['timestamp'] = '' d_event['leverage'] = Web3.fromWei(self.leverage, 'ether') d_event['riskProxPrice'] = Web3.fromWei(self.riskProxPrice, 'ether') d_event['reservePrice'] = Web3.fromWei(self.reservePrice, 'ether') d_event['startBlockNumber'] = self.startBlockNumber return d_event
def formatted(self): d_event = dict() d_event['blockNumber'] = self.blockNumber if self.timestamp: d_event['timestamp'] = self.timestamp.strftime("%Y-%m-%d %H:%M:%S") else: d_event['timestamp'] = '' d_event['stableTokenRedeemCount'] = self.stableTokenRedeemCount d_event['deleveragingCount'] = self.deleveragingCount d_event['riskProxPrice'] = Web3.fromWei(self.riskProxPrice, 'ether') d_event['reservePrice'] = Web3.fromWei(self.reservePrice, 'ether') return d_event
def _store_internal_transaction(tx, transaction, attacker, labeled_accounts, direction): if transaction["from"] == attacker: from_account_type = "Attacker" elif transaction["from"] in labeled_accounts: from_account_type = "Labeled_Account" else: from_account_type = "Account" if transaction["to"] == attacker: to_account_type = "Attacker" elif transaction["to"] in labeled_accounts: to_account_type = "Labeled_Account" else: to_account_type = "Account" account_info_from = "{address:'" + transaction["from"] + "'" if from_account_type == "Labeled_Account": account_info_from += ",label:'" + labeled_accounts[ transaction["from"]]["labels"][0] + "'" account_info_from += ",category:'" + labeled_accounts[ transaction["from"]]["category"] + "'" account_info_from += "}" account_info_to = "{address:'" + transaction["to"] + "'" if to_account_type == "Labeled_Account": account_info_to += ",label:'" + labeled_accounts[ transaction["to"]]["labels"][0] + "'" account_info_to += ",category:'" + labeled_accounts[ transaction["to"]]["category"] + "'" account_info_to += "}" if direction == "forwards": value = str(int(Web3.fromWei(int(transaction["value"]), 'ether'))) else: value = str(Web3.fromWei(int(transaction["value"]), 'ether')) tx.run("""MERGE (from:""" + from_account_type + """ """ + account_info_from + """) MERGE (to:""" + to_account_type + """ """ + account_info_to + """) MERGE (from)-[:INTERNAL_TRANSACTION { value:$value, hash:$hash, block:$block, timestamp:$timestamp }]->(to)""", value=value, hash=transaction["hash"], block=transaction["blockNumber"], timestamp=datetime.fromtimestamp(int(transaction["timeStamp"])))
def test_interactive_new_bid(click_runner, mocker, mock_worklock_agent, token_economics, test_registry_source_manager, surrogate_bidder, mock_testerchain): now = mock_testerchain.get_blocktime() sometime_later = now + 100 mocker.patch.object(BlockchainInterface, 'get_blocktime', return_value=sometime_later) minimum = token_economics.worklock_min_allowed_bid bid_value = random.randint(minimum, minimum * 100) bid_value_in_eth = Web3.fromWei(bid_value, 'ether') wrong_bid = random.randint(1, minimum - 1) wrong_bid_in_eth = Web3.fromWei(wrong_bid, 'ether') # Spy on the corresponding CLI function we are testing mock_place_bid = mocker.spy(Bidder, 'place_bid') # Patch Bidder.get_deposited_eth so it returns what we expect, in the correct sequence deposited_eth_sequence = ( 0, # When deciding if it's a new bid or increasing the new one (in this case, a new bid) 0, # When placing the bid, inside Bidder.place_bid bid_value, # When printing the CLI result, after the bid is placed .. bid_value, # .. we use it twice ) mocker.patch.object(Bidder, 'get_deposited_eth', new_callable=PropertyMock, side_effect=deposited_eth_sequence) command = ('escrow', '--participant-address', surrogate_bidder.checksum_address, '--provider', MOCK_PROVIDER_URI, '--signer', MOCK_PROVIDER_URI, '--network', TEMPORARY_DOMAIN,) user_input = "\n".join((INSECURE_DEVELOPMENT_PASSWORD, str(wrong_bid_in_eth), str(bid_value_in_eth), YES)) result = click_runner.invoke(worklock, command, catch_exceptions=False, input=user_input) assert result.exit_code == 0 # OK - Let's see what happened # Bidder mock_place_bid.assert_called_once() # Output minimum_in_eth = Web3.fromWei(minimum, 'ether') expected_error = f"Error: {wrong_bid_in_eth} is smaller than the minimum valid value {minimum_in_eth}" assert expected_error in result.output expected_prompt = BID_AMOUNT_PROMPT_WITH_MIN_BID.format(minimum_bid_in_eth=Web3.fromWei(minimum, 'ether')) assert 2 == result.output.count(expected_prompt)
def formatted(self): d_event = dict() d_event['blockNumber'] = self.blockNumber if self.timestamp: d_event['timestamp'] = self.timestamp.strftime("%Y-%m-%d %H:%M:%S") else: d_event['timestamp'] = '' d_event['riskProTecPrice'] = Web3.fromWei(self.riskProTecPrice, 'ether') d_event['riskProDiscountPrice'] = Web3.fromWei( self.riskProDiscountPrice, 'ether') d_event['amount'] = Web3.fromWei(self.amount, 'ether') return d_event
def readable_str(self): output_str = "" output_str += "input_utxos:\n" output_str += "\tutxo1 - blknum: %d\ttxindex: %d\toindex: %d\n" % ( self.blknum1, self.txindex1, self.oindex1) if self.blknum1 else "" output_str += "\tutxo2 - blknum: %d\ttxindex: %d\toindex: %d\n" % ( self.blknum2, self.txindex2, self.oindex2) if self.blknum2 else "" output_str += "output_utxos:\n" output_str += "\tutxo1 - utxotype: %s\tnewowner: %s\tamount: %f\ttokenprice: %f\ttoken address: %s\n" % ( self.UTXOType(self.utxotype1).name, self.newowner1.hex(), Web3.fromWei(self.amount1, 'ether'), Web3.fromWei(self.tokenprice1, 'ether'), self.cur1.hex()) if self.utxotype1 else "" output_str += "\tutxo2 - utxotype: %s\tnewowner: %s\tamount: %f\ttokenprice: %f\ttoken address: %s\n" % ( self.UTXOType(self.utxotype2).name, self.newowner2.hex(), Web3.fromWei(self.amount2, 'ether'), Web3.fromWei(self.tokenprice2, 'ether'), self.cur2.hex()) if self.utxotype2 else "" output_str += "\tutxo3 - utxotype: %s\tnewowner: %s\tamount: %f\ttokenprice: %f\ttoken address: %s\n" % ( self.UTXOType(self.utxotype3).name, self.newowner3.hex(), Web3.fromWei(self.amount3, 'ether'), Web3.fromWei(self.tokenprice3, 'ether'), self.cur3.hex()) if self.utxotype3 else "" output_str += "\tutxo4 - utxotype: %s\tnewowner: %s\tamount: %f\ttokenprice: %f\ttoken address: %s\n" % ( self.UTXOType(self.utxotype4).name, self.newowner4.hex(), Web3.fromWei(self.amount4, 'ether'), Web3.fromWei(self.tokenprice4, 'ether'), self.cur4.hex()) if self.utxotype4 else "" return Web3.toHex(text=output_str)
def __init__(self, connection_manager, event): self.blockNumber = event['blockNumber'] try: ts = connection_manager.block_timestamp(self.blockNumber) dt = ts - datetime.timedelta(hours=self.hours_delta) self.timestamp = dt.strftime("%Y-%m-%d %H:%M:%S") except BlockNotFound: self.timestamp = '' self.queueSize = event['args']['queueSize'] self.accumCommissions = Web3.fromWei(event['args']['accumCommissions'], 'ether') self.reservePrice = Web3.fromWei(event['args']['reservePrice'], 'ether')
def check_gas_reserve(raiden): """ Check periodically for gas reserve in the account """ while True: has_enough_balance, estimated_required_balance = gas_reserve.has_enough_gas_reserve( raiden, channels_to_open=0, ) estimated_required_balance_eth = Web3.fromWei(estimated_required_balance, 'ether') if not has_enough_balance: log.info('Missing gas reserve', required_wei=estimated_required_balance) click.secho( ( 'WARNING\n' "Your account's balance is below the estimated gas reserve of " f'{estimated_required_balance_eth} eth. This may lead to a loss of ' 'of funds because your account will be unable to perform on-chain ' 'transactions. Please add funds to your account as soon as possible.' ), fg='red', ) gevent.sleep(CHECK_GAS_RESERVE_INTERVAL)
def getBalance(self): wei_balance = self.web3.eth.getBalance(self.address) ether_balance = Web3.fromWei(wei_balance, unit='ether') return ether_balance