A Python library for interacting with Ethereum blockchain
Overall
score
88%
Evaluation — 88%
↑ 1.01xAgent success when using this tile
Core utility functions for data conversion, encoding, validation, and Ethereum-specific operations including Wei conversions, address validation, hash functions, and data formatting.
Functions for converting between different Ethereum units.
def to_wei(number: Union[int, float, str, decimal.Decimal], unit: str) -> Wei:
"""
Convert number to Wei (smallest Ethereum unit).
Parameters:
- number: Number to convert
- unit: Source unit ('ether', 'gwei', 'finney', etc.)
Returns:
Amount in Wei
Examples:
to_wei(1, 'ether') -> 1000000000000000000
to_wei(20, 'gwei') -> 20000000000
"""
def from_wei(number: Wei, unit: str) -> decimal.Decimal:
"""
Convert Wei to specified unit.
Parameters:
- number: Amount in Wei
- unit: Target unit ('ether', 'gwei', 'finney', etc.)
Returns:
Amount in specified unit as Decimal for precision
Examples:
from_wei(1000000000000000000, 'ether') -> Decimal('1')
from_wei(20000000000, 'gwei') -> Decimal('20')
"""Functions for address validation and formatting.
def to_checksum_address(value: AnyAddress) -> ChecksumAddress:
"""
Convert address to EIP-55 checksum format.
Parameters:
- value: Address in any format
Returns:
Checksummed address
Examples:
to_checksum_address('0xd8da6bf26964af9d7eed9e03e53415d37aa96045')
-> '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
"""
def is_address(value: Any) -> bool:
"""
Check if value is valid Ethereum address.
Parameters:
- value: Value to check
Returns:
True if valid address format
"""
def is_checksum_address(value: Any) -> bool:
"""
Check if address is in valid checksum format.
Parameters:
- value: Address to check
Returns:
True if valid checksum address
"""
def is_same_address(address1: AnyAddress, address2: AnyAddress) -> bool:
"""
Compare two addresses for equality (case-insensitive).
Parameters:
- address1: First address
- address2: Second address
Returns:
True if addresses are the same
"""Cryptographic hash functions for Ethereum operations.
def keccak(
primitive: Optional[Primitives] = None,
text: Optional[str] = None,
hexstr: Optional[HexStr] = None
) -> HexBytes:
"""
Compute Keccak-256 hash.
Parameters:
- primitive: Raw bytes to hash
- text: Text string to hash (UTF-8 encoded)
- hexstr: Hex string to hash
Returns:
32-byte hash as HexBytes
Examples:
keccak(text='hello') -> HexBytes('0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8')
"""
def solidityKeccak(abi_types: List[str], values: List[Any]) -> HexBytes:
"""
Compute Solidity-compatible packed hash.
Parameters:
- abi_types: List of Solidity types
- values: List of values matching types
Returns:
Packed hash as HexBytes
Examples:
solidityKeccak(['uint256', 'string'], [123, 'hello'])
"""
def sha3(
primitive: Optional[Primitives] = None,
text: Optional[str] = None,
hexstr: Optional[HexStr] = None
) -> HexBytes:
"""
Alias for keccak function (deprecated, use keccak).
"""Functions for encoding and converting data types.
def to_bytes(
primitive: Union[bool, int, str, bytes] = None,
hexstr: Optional[HexStr] = None,
text: Optional[str] = None
) -> bytes:
"""
Convert various types to bytes.
Parameters:
- primitive: Value to convert
- hexstr: Hex string to convert
- text: Text string to convert (UTF-8)
Returns:
Converted bytes
"""
def to_int(
primitive: Union[bytes, int, str] = None,
hexstr: Optional[HexStr] = None,
text: Optional[str] = None
) -> int:
"""
Convert various types to integer.
Parameters:
- primitive: Value to convert
- hexstr: Hex string to convert
- text: Text string to convert
Returns:
Converted integer
"""
def to_hex(
primitive: Union[bytes, int, str, bool] = None,
hexstr: Optional[HexStr] = None,
text: Optional[str] = None
) -> HexStr:
"""
Convert various types to hex string.
Parameters:
- primitive: Value to convert
- hexstr: Pass-through hex string
- text: Text string to convert (UTF-8)
Returns:
Hex string with 0x prefix
"""
def to_text(
primitive: Union[bytes, int, str] = None,
hexstr: Optional[HexStr] = None,
text: Optional[str] = None,
encoding: str = 'utf-8'
) -> str:
"""
Convert various types to text string.
Parameters:
- primitive: Value to convert
- hexstr: Hex string to convert
- text: Pass-through text string
- encoding: Text encoding (default UTF-8)
Returns:
Decoded text string
"""Functions for JSON encoding and data formatting.
def to_json(obj: Any) -> str:
"""
Convert object to JSON string with Ethereum-specific formatting.
Parameters:
- obj: Object to serialize
Returns:
JSON string
"""
def attributedict_to_dict(obj: Any) -> Any:
"""
Convert AttributeDict objects to regular dictionaries recursively.
Parameters:
- obj: Object to convert
Returns:
Converted object with regular dicts
"""
def remove_0x_prefix(value: str) -> str:
"""
Remove 0x prefix from hex string.
Parameters:
- value: Hex string potentially with 0x prefix
Returns:
Hex string without 0x prefix
"""
def add_0x_prefix(value: str) -> HexStr:
"""
Add 0x prefix to hex string if not present.
Parameters:
- value: Hex string
Returns:
Hex string with 0x prefix
"""Functions for working with ABI encoding and decoding.
def encode_abi(types: List[str], args: List[Any]) -> HexBytes:
"""
Encode data according to ABI specification.
Parameters:
- types: List of ABI types
- args: List of values matching types
Returns:
ABI-encoded data
"""
def decode_abi(types: List[str], data: HexBytes) -> List[Any]:
"""
Decode ABI-encoded data.
Parameters:
- types: List of expected ABI types
- data: ABI-encoded data
Returns:
List of decoded values
"""
def function_abi_to_4byte_selector(function_abi: Dict[str, Any]) -> HexBytes:
"""
Generate 4-byte function selector from ABI.
Parameters:
- function_abi: Function ABI definition
Returns:
4-byte function selector
"""
def event_abi_to_log_topic(event_abi: Dict[str, Any]) -> HexBytes:
"""
Generate log topic from event ABI.
Parameters:
- event_abi: Event ABI definition
Returns:
Event topic hash
"""Functions for contract-related operations.
def get_create_address(address: AnyAddress, nonce: int) -> ChecksumAddress:
"""
Calculate contract address from deployer address and nonce.
Parameters:
- address: Deployer address
- nonce: Transaction nonce
Returns:
Contract address
"""
def get_create2_address(
address: AnyAddress,
salt: Union[bytes, int, str],
init_code: bytes
) -> ChecksumAddress:
"""
Calculate CREATE2 contract address.
Parameters:
- address: Factory contract address
- salt: Salt value for deterministic address
- init_code: Contract initialization code
Returns:
Deterministic contract address
"""Functions for validating Ethereum data formats.
def is_hex(value: Any) -> bool:
"""
Check if value is valid hex string.
Parameters:
- value: Value to check
Returns:
True if valid hex format
"""
def is_0x_prefixed(value: str) -> bool:
"""
Check if string has 0x prefix.
Parameters:
- value: String to check
Returns:
True if has 0x prefix
"""
def is_bytes(value: Any) -> bool:
"""
Check if value is bytes type.
Parameters:
- value: Value to check
Returns:
True if bytes type
"""
def is_string(value: Any) -> bool:
"""
Check if value is string type.
Parameters:
- value: Value to check
Returns:
True if string type
"""Utility-related type definitions.
Wei = NewType('Wei', int)
HexStr = NewType('HexStr', str)
HexBytes = NewType('HexBytes', bytes)
Primitives = Union[bytes, int, bool]
AnyAddress = Union[str, bytes, ChecksumAddress]
# Unit conversion mappings
UNITS = {
'wei': 1,
'kwei': 10**3,
'mwei': 10**6,
'gwei': 10**9,
'szabo': 10**12,
'finney': 10**15,
'ether': 10**18,
}from web3 import Web3
w3 = Web3()
# Convert to Wei
eth_amount = 1.5
wei_amount = w3.to_wei(eth_amount, 'ether')
print(f"{eth_amount} ETH = {wei_amount} Wei")
gwei_amount = 20
wei_from_gwei = w3.to_wei(gwei_amount, 'gwei')
print(f"{gwei_amount} Gwei = {wei_from_gwei} Wei")
# Convert from Wei
large_wei = 1500000000000000000
eth_converted = w3.from_wei(large_wei, 'ether')
gwei_converted = w3.from_wei(large_wei, 'gwei')
print(f"{large_wei} Wei = {eth_converted} ETH")
print(f"{large_wei} Wei = {gwei_converted} Gwei")from web3 import Web3
w3 = Web3()
# Convert to checksum address
address = '0xd8da6bf26964af9d7eed9e03e53415d37aa96045'
checksum_addr = w3.to_checksum_address(address)
print(f"Checksum address: {checksum_addr}")
# Validate addresses
print(f"Is valid address: {w3.is_address(address)}")
print(f"Is checksum address: {w3.is_checksum_address(checksum_addr)}")
# Compare addresses
addr1 = '0xd8da6bf26964af9d7eed9e03e53415d37aa96045'
addr2 = '0xD8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
print(f"Addresses are same: {w3.is_same_address(addr1, addr2)}")from web3 import Web3
w3 = Web3()
# Keccak hash of string
message = "Hello, Ethereum!"
hash_result = w3.keccak(text=message)
print(f"Keccak hash: {hash_result.hex()}")
# Hash of bytes
data = b"binary data"
hash_bytes = w3.keccak(primitive=data)
print(f"Hash of bytes: {hash_bytes.hex()}")
# Solidity-style packed hash
types = ['uint256', 'string', 'address']
values = [12345, 'test', '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045']
packed_hash = w3.solidityKeccak(types, values)
print(f"Packed hash: {packed_hash.hex()}")from web3 import Web3
w3 = Web3()
# Convert text to bytes
text = "Hello World"
text_bytes = w3.to_bytes(text=text)
print(f"Text as bytes: {text_bytes}")
# Convert hex to integer
hex_value = "0xff"
int_value = w3.to_int(hexstr=hex_value)
print(f"Hex {hex_value} as int: {int_value}")
# Convert integer to hex
number = 255
hex_result = w3.to_hex(primitive=number)
print(f"Int {number} as hex: {hex_result}")
# Convert bytes back to text
message_bytes = b'Hello World'
decoded_text = w3.to_text(primitive=message_bytes)
print(f"Bytes as text: {decoded_text}")from web3 import Web3
w3 = Web3()
# Encode data for contract call
types = ['uint256', 'string', 'bool']
values = [42, 'hello', True]
encoded = w3.encode_abi(types, values)
print(f"Encoded data: {encoded.hex()}")
# Decode ABI data
decoded = w3.decode_abi(types, encoded)
print(f"Decoded values: {decoded}")
# Function selector
function_abi = {
'name': 'transfer',
'type': 'function',
'inputs': [
{'name': 'to', 'type': 'address'},
{'name': 'value', 'type': 'uint256'}
]
}
selector = w3.function_abi_to_4byte_selector(function_abi)
print(f"Transfer function selector: {selector.hex()}")from web3 import Web3
w3 = Web3()
# Calculate contract address from deployer
deployer = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
nonce = 42
contract_addr = w3.get_create_address(deployer, nonce)
print(f"Contract address: {contract_addr}")
# Calculate CREATE2 address
factory = '0x742d35Cc6635C0532925a3b8D5c0d9E3C4B3c8'
salt = w3.keccak(text="my-salt")
init_code = b'\x60\x80\x60\x40...' # Contract bytecode
create2_addr = w3.get_create2_address(factory, salt, init_code)
print(f"CREATE2 address: {create2_addr}")from web3 import Web3
w3 = Web3()
# Validate data formats
values_to_check = [
"0x1234", # hex string
"1234", # non-hex string
b"binary", # bytes
123, # integer
"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" # address
]
for value in values_to_check:
print(f"Value: {value}")
print(f" Is hex: {w3.is_hex(value)}")
print(f" Is bytes: {w3.is_bytes(value)}")
print(f" Is string: {w3.is_string(value)}")
print(f" Is address: {w3.is_address(value)}")
if isinstance(value, str):
print(f" Has 0x prefix: {w3.is_0x_prefixed(value)}")
print()from web3 import Web3
import json
w3 = Web3()
# Create complex data structure
data = {
'address': w3.to_checksum_address('0xd8da6bf26964af9d7eed9e03e53415d37aa96045'),
'balance': w3.to_wei(1.5, 'ether'),
'hash': w3.keccak(text='test'),
'number': 12345
}
# Convert to JSON with proper formatting
json_str = w3.to_json(data)
print("Formatted JSON:")
print(json.dumps(json.loads(json_str), indent=2))from web3 import Web3
w3 = Web3()
# Process multiple addresses
addresses = [
'0xd8da6bf26964af9d7eed9e03e53415d37aa96045',
'0x742d35cc6635c0532925a3b8d5c0d9e3c4b3c8',
'invalid-address'
]
checksum_addresses = []
for addr in addresses:
if w3.is_address(addr):
checksum_addr = w3.to_checksum_address(addr)
checksum_addresses.append(checksum_addr)
print(f"✓ {addr} -> {checksum_addr}")
else:
print(f"✗ Invalid address: {addr}")
print(f"Processed {len(checksum_addresses)} valid addresses")Install with Tessl CLI
npx tessl i tessl/pypi-web3docs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10