diff --git a/nucypher/blockchain/eth/interfaces.py b/nucypher/blockchain/eth/interfaces.py index 0cf02341a..a530f22f6 100644 --- a/nucypher/blockchain/eth/interfaces.py +++ b/nucypher/blockchain/eth/interfaces.py @@ -59,6 +59,8 @@ from nucypher.blockchain.eth.providers import ( ) from nucypher.blockchain.eth.registry import BaseContractRegistry from nucypher.blockchain.eth.sol.compile import SolidityCompiler +from nucypher.blockchain.eth.utils import prettify_eth_amount + Web3Providers = Union[IPCProvider, WebsocketProvider, HTTPProvider, EthereumTester] @@ -372,6 +374,7 @@ class BlockchainInterface: payload_pprint = dict(payload) payload_pprint['from'] = to_checksum_address(payload['from']) + payload_pprint.update({f: prettify_eth_amount(v) for f, v in payload.items() if f in ('gasPrice', 'value')}) payload_pprint = ', '.join("{}: {}".format(k, v) for k, v in payload_pprint.items()) self.log.debug(f"[TX-{transaction_name}] | {payload_pprint}") diff --git a/nucypher/blockchain/eth/utils.py b/nucypher/blockchain/eth/utils.py index 9694238d5..52673e2d9 100644 --- a/nucypher/blockchain/eth/utils.py +++ b/nucypher/blockchain/eth/utils.py @@ -15,9 +15,12 @@ You should have received a copy of the GNU Affero General Public License along with nucypher. If not, see . """ +from decimal import Decimal + import maya from constant_sorrow.constants import UNKNOWN_DEVELOPMENT_CHAIN_ID from eth_utils import is_address, to_checksum_address, is_hex +from web3 import Web3 def epoch_to_period(epoch: int, seconds_per_period: int) -> int: @@ -85,3 +88,32 @@ def etherscan_url(item, network: str, is_token=False) -> str: url = f"{domain}/{item_type}/{item}" return url + + +def prettify_eth_amount(amount, original_denomination: str = 'wei') -> str: + """ + Converts any ether `amount` in `original_denomination` and finds a suitable representation based on its length. + The options in consideration are representing the amount in wei, gwei or ETH. + :param amount: Input amount to prettify + :param original_denomination: Denomination used by `amount` (by default, wei is assumed) + :return: Shortest representation for `amount`, considering wei, gwei and ETH. + """ + try: + # First obtain canonical representation in wei. Works for int, float, Decimal and str amounts + amount_in_wei = Web3.toWei(Decimal(amount), original_denomination) + + common_denominations = ('wei', 'gwei', 'ether') + + options = [str(Web3.fromWei(amount_in_wei, d)) for d in common_denominations] + + best_option = min(zip(map(len, options), options, common_denominations)) + _length, pretty_amount, denomination = best_option + + if denomination == 'ether': + denomination = 'ETH' + pretty_amount += " " + denomination + + except Exception: # Worst case scenario, we just print the str representation of amount + pretty_amount = str(amount) + + return pretty_amount