Common utility functions for python code that interacts with Ethereum
—
Flexible type conversion utilities supporting multiple input formats with consistent output types. Core functionality for data transformation pipelines in Ethereum applications.
Convert between bytes, hex strings, integers, and text with flexible input handling.
def to_bytes(primitive=None, hexstr=None, text=None) -> bytes:
"""
Convert various formats to bytes.
Args:
primitive: Integer, bytes, or other primitive value
hexstr (str): Hex string (with or without 0x prefix)
text (str): UTF-8 text string
Returns:
bytes: Converted byte data
Raises:
ValidationError: If no input provided or invalid format
TypeError: If multiple inputs provided
"""
def to_hex(primitive=None, hexstr=None, text=None) -> str:
"""
Convert various formats to 0x-prefixed hex string.
Args:
primitive: Integer, bytes, or other primitive value
hexstr (str): Hex string (normalized to 0x prefix)
text (str): UTF-8 text string
Returns:
str: 0x-prefixed hex string
Raises:
ValidationError: If no input provided or invalid format
TypeError: If multiple inputs provided
"""
def to_int(primitive=None, hexstr=None, text=None) -> int:
"""
Convert various formats to integer.
Args:
primitive: Integer, bytes, or other primitive value
hexstr (str): Hex string (with or without 0x prefix)
text (str): UTF-8 text string (must be numeric)
Returns:
int: Converted integer value
Raises:
ValidationError: If no input provided or invalid format
TypeError: If multiple inputs provided
"""
def to_text(primitive=None, hexstr=None, text=None) -> str:
"""
Convert various formats to UTF-8 text string.
Args:
primitive: Integer, bytes, or other primitive value
hexstr (str): Hex string (decoded as UTF-8)
text (str): Text string (returned as-is)
Returns:
str: UTF-8 text string
Raises:
ValidationError: If no input provided or invalid format
TypeError: If multiple inputs provided
UnicodeDecodeError: If bytes cannot be decoded as UTF-8
"""Convert values while treating strings as specific types.
def hexstr_if_str(to_type, hexstr_or_primitive):
"""
Convert value to specified type, treating strings as hex strings.
Args:
to_type: Target conversion function (to_bytes, to_int, etc.)
hexstr_or_primitive: Value to convert
Returns:
Converted value of target type
"""
def text_if_str(to_type, text_or_primitive):
"""
Convert value to specified type, treating strings as text.
Args:
to_type: Target conversion function (to_bytes, to_int, etc.)
text_or_primitive: Value to convert
Returns:
Converted value of target type
"""from eth_utils import to_bytes, to_hex, to_int, to_text
# Convert integer to different formats
number = 12345
print(to_hex(primitive=number)) # 0x3039
print(to_bytes(primitive=number)) # b'09'
print(to_text(primitive=number)) # '12345'
# Convert hex string to other formats
hex_str = "0x48656c6c6f"
print(to_bytes(hexstr=hex_str)) # b'Hello'
print(to_int(hexstr=hex_str)) # 310939249775
print(to_text(hexstr=hex_str)) # 'Hello'
# Convert text to other formats
text = "Hello"
print(to_bytes(text=text)) # b'Hello'
print(to_hex(text=text)) # 0x48656c6c6f
print(to_int(text=text)) # Raises ValidationError (not numeric)from eth_utils import to_bytes, to_hex, to_int
# Transaction hash from different sources
tx_hash_hex = "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
tx_hash_bytes = bytes.fromhex("1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef")
# Normalize to hex format
normalized_hash = to_hex(primitive=tx_hash_bytes)
print(normalized_hash) # 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
# Convert block number from hex
block_hex = "0x1b4" # Block 436 in hex
block_number = to_int(hexstr=block_hex)
print(block_number) # 436from eth_utils import to_bytes, to_hex, to_text
# Process contract call return data
return_data = "0x48656c6c6f20576f726c64" # "Hello World" in hex
# Convert to readable text
message = to_text(hexstr=return_data)
print(message) # "Hello World"
# Convert to bytes for further processing
data_bytes = to_bytes(hexstr=return_data)
print(len(data_bytes)) # 11 bytes
# Ensure hex format for transmission
hex_data = to_hex(primitive=data_bytes)
print(hex_data) # 0x48656c6c6f20576f726c64from eth_utils import hexstr_if_str, text_if_str, to_bytes, to_int
def process_hex_input(value):
"""Process input that might be hex string or bytes."""
return hexstr_if_str(to_bytes, value)
def process_text_input(value):
"""Process input that might be text string or bytes."""
return text_if_str(to_bytes, value)
# Hex string input
hex_input = "0x48656c6c6f"
result1 = process_hex_input(hex_input)
print(result1) # b'Hello'
# Text string input
text_input = "Hello"
result2 = process_text_input(text_input)
print(result2) # b'Hello'
# Bytes input works with both
bytes_input = b'Hello'
result3 = process_hex_input(bytes_input) # b'Hello'
result4 = process_text_input(bytes_input) # b'Hello'from eth_utils import to_hex, to_bytes, to_text
def encode_string_to_hex(text_string):
"""Encode a text string to hex for storage/transmission."""
return to_hex(text=text_string)
def decode_hex_to_string(hex_string):
"""Decode hex data back to text string."""
return to_text(hexstr=hex_string)
# Encode message
message = "Hello, Ethereum!"
encoded = encode_string_to_hex(message)
print(encoded) # 0x48656c6c6f2c20457468657265756d21
# Decode message
decoded = decode_hex_to_string(encoded)
print(decoded) # "Hello, Ethereum!"The conversion functions enforce strict input validation:
primitive, hexstr, or textfrom eth_utils import to_bytes, ValidationError
# Multiple inputs - raises TypeError
try:
to_bytes(primitive=123, hexstr="0x123")
except TypeError as e:
print("Cannot provide multiple inputs")
# No inputs - raises ValidationError
try:
to_bytes()
except ValidationError as e:
print("Must provide exactly one input")
# Invalid hex - raises ValidationError
try:
to_bytes(hexstr="0xGGG")
except ValidationError as e:
print("Invalid hex characters")