Common utility functions for python code that interacts with Ethereum
—
Ethereum currency conversions between wei and various denominations with precise decimal handling and comprehensive denomination constants. Essential for handling Ether amounts in applications.
Convert between wei (smallest unit) and named denominations.
def to_wei(number, unit: str) -> int:
"""
Convert from specified unit to wei.
Args:
number: Amount in the specified unit (int, float, Decimal, or string)
unit (str): Unit name ('ether', 'gwei', 'finney', etc.)
Returns:
int: Amount in wei
Raises:
ValidationError: If unit is unknown or number is invalid
"""
def from_wei(number: int, unit: str) -> Union[int, Decimal]:
"""
Convert wei to specified unit.
Args:
number (int): Amount in wei
unit (str): Target unit name ('ether', 'gwei', 'finney', etc.)
Returns:
Union[int, Decimal]: Amount in specified unit (int if whole number, Decimal otherwise)
Raises:
ValidationError: If unit is unknown or number is invalid
"""Convert using custom decimal places for precision control.
def to_wei_decimals(number, decimals: int) -> int:
"""
Convert to wei using specified decimal places.
Args:
number: Amount to convert
decimals (int): Number of decimal places (e.g., 18 for ether, 9 for gwei)
Returns:
int: Amount in wei
"""
def from_wei_decimals(number: int, decimals: int) -> Union[int, Decimal]:
"""
Convert wei using specified decimal places.
Args:
number (int): Amount in wei
decimals (int): Number of decimal places for target unit
Returns:
Union[int, Decimal]: Converted amount
"""Access denomination values and limits.
class denoms:
"""Ethereum denomination constants."""
# Smallest units
wei = 1
kwei = 1000
babbage = 1000
femtoether = 1000
# Common units
mwei = 1000000
lovelace = 1000000
picoether = 1000000
gwei = 1000000000
shannon = 1000000000
nanoether = 1000000000
nano = 1000000000
# Larger units
szabo = 1000000000000
microether = 1000000000000
micro = 1000000000000
finney = 1000000000000000
milliether = 1000000000000000
milli = 1000000000000000
# Standard unit
ether = 1000000000000000000
# Large units
kether = 1000000000000000000000
grand = 1000000000000000000000
mether = 1000000000000000000000000
gether = 1000000000000000000000000000
tether = 1000000000000000000000000000000
# Wei limits
MIN_WEI = 0
MAX_WEI = 2**256 - 1from eth_utils import to_wei, from_wei, denoms
# Convert ether to wei
eth_amount = 1.5
wei_amount = to_wei(eth_amount, 'ether')
print(wei_amount) # 1500000000000000000
# Convert wei back to ether
ether_amount = from_wei(wei_amount, 'ether')
print(ether_amount) # 1.5
# Working with gwei (common for gas prices)
gas_price_gwei = 20
gas_price_wei = to_wei(gas_price_gwei, 'gwei')
print(gas_price_wei) # 20000000000
# Convert large wei amount to readable ether
large_wei = 1234567890123456789012
readable_ether = from_wei(large_wei, 'ether')
print(readable_ether) # 1234.567890123456789012from eth_utils import to_wei, from_wei
# Gas calculation example
gas_limit = 21000
gas_price_gwei = 30
# Calculate total gas cost in wei
gas_price_wei = to_wei(gas_price_gwei, 'gwei')
total_gas_wei = gas_limit * gas_price_wei
print(f"Gas cost in wei: {total_gas_wei}") # 630000000000000
# Convert to readable ether amount
gas_cost_ether = from_wei(total_gas_wei, 'ether')
print(f"Gas cost in ether: {gas_cost_ether}") # 0.00063from eth_utils import denoms, from_wei
# Access denomination values directly
print(f"1 ether = {denoms.ether} wei")
print(f"1 gwei = {denoms.gwei} wei")
print(f"1 finney = {denoms.finney} wei")
# Calculate amounts using constants
amount_wei = 5 * denoms.ether + 250 * denoms.gwei
print(f"Total: {amount_wei} wei")
# Convert to readable format
readable = from_wei(amount_wei, 'ether')
print(f"Readable: {readable} ETH")from eth_utils import to_wei_decimals, from_wei_decimals
from decimal import Decimal
# Work with custom token (18 decimals like ether)
token_amount = Decimal('123.456789012345678901')
token_wei = to_wei_decimals(token_amount, 18)
print(token_wei) # 123456789012345678901
# Convert back maintaining precision
original_amount = from_wei_decimals(token_wei, 18)
print(original_amount) # 123.456789012345678901
# Work with USDC (6 decimals)
usdc_amount = 1000.50
usdc_base_units = to_wei_decimals(usdc_amount, 6)
print(usdc_base_units) # 1000500000
usdc_readable = from_wei_decimals(usdc_base_units, 6)
print(usdc_readable) # 1000.5from eth_utils import to_wei, from_wei, ValidationError
def safe_convert_to_wei(amount, unit):
"""Safely convert amount to wei with error handling."""
try:
return to_wei(amount, unit)
except ValidationError as e:
print(f"Invalid conversion: {e}")
return None
def format_ether_amount(wei_amount):
"""Format wei amount as readable ether."""
if wei_amount == 0:
return "0 ETH"
ether_amount = from_wei(wei_amount, 'ether')
return f"{ether_amount} ETH"
# Usage examples
wei1 = safe_convert_to_wei(1.5, 'ether') # Valid
wei2 = safe_convert_to_wei(1.5, 'invalid_unit') # None (invalid unit)
if wei1:
print(format_ether_amount(wei1)) # 1.5 ETHfrom eth_utils import to_wei, from_wei
def process_transaction_amounts(transactions):
"""Process list of transaction amounts."""
processed = []
for tx in transactions:
# Convert input amounts to wei for processing
if tx['unit'] != 'wei':
tx['amount_wei'] = to_wei(tx['amount'], tx['unit'])
else:
tx['amount_wei'] = tx['amount']
# Add readable ether amount
tx['amount_eth'] = from_wei(tx['amount_wei'], 'ether')
processed.append(tx)
return processed
# Example usage
transactions = [
{'amount': 1.5, 'unit': 'ether'},
{'amount': 500, 'unit': 'gwei'},
{'amount': 1000000000000000000, 'unit': 'wei'}
]
processed_txs = process_transaction_amounts(transactions)
for tx in processed_txs:
print(f"{tx['amount_eth']} ETH ({tx['amount_wei']} wei)")The following unit names are supported for conversions:
wei - Base unit (1 wei)gwei - Gigawei (10^9 wei) - commonly used for gas pricesether - Standard unit (10^18 wei)wei, kwei, babbage, femtoethermwei, lovelace, picoethergwei, shannon, nanoether, nanoszabo, microether, microfinney, milliether, millietherkether, grandmether, gether, tetherDecimal typeint (no fractional wei)int when result is whole number, Decimal otherwiseDecimal inputs for maximum precision in calculations