A Python library for interacting with Ethereum blockchain
npx @tessl/cli install tessl/pypi-web3@7.13.0A comprehensive Python library for interacting with the Ethereum blockchain. Web3.py provides essential functionality for building decentralized applications, managing smart contracts, and handling blockchain operations with support for multiple connection types, middleware processing, and extensive utilities for Ethereum development.
pip install web3from web3 import Web3For ENS functionality:
from ens import ENSProvider classes:
from web3 import HTTPProvider, WebSocketProvider, IPCProviderAccount management:
from web3 import Accountfrom web3 import Web3
# Connect to Ethereum node
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))
# Check connection
if w3.is_connected():
print("Connected to Ethereum")
# Get latest block number
block_number = w3.eth.block_number
print(f"Latest block: {block_number}")
# Get account balance
balance = w3.eth.get_balance('0x742d35Cc6635C0532925a3b8D5c0d9E3C4B3c8')
balance_ether = w3.from_wei(balance, 'ether')
print(f"Balance: {balance_ether} ETH")
# Smart contract interaction
contract_address = '0x...'
contract_abi = [...] # Contract ABI
contract = w3.eth.contract(address=contract_address, abi=contract_abi)
result = contract.functions.someMethod().call()Web3.py follows a modular architecture organized around key blockchain interaction patterns:
This design enables flexible blockchain integration while providing both low-level access and high-level convenience methods.
Main client classes for connecting to Ethereum nodes with comprehensive blockchain interaction capabilities including transaction management, block queries, and smart contract operations.
class Web3:
def __init__(self, provider=None, modules=None, middleware=None): ...
def is_connected(self) -> bool: ...
@property
def eth(self) -> Eth: ...
@property
def net(self) -> Net: ...
@property
def geth(self) -> Geth: ...
class AsyncWeb3:
def __init__(self, provider=None, modules=None, middleware=None): ...
async def is_connected(self) -> bool: ...
@property
def eth(self) -> AsyncEth: ...
@property
def net(self) -> AsyncNet: ...
@property
def geth(self) -> AsyncGeth: ...Connection providers for different Ethereum client interfaces supporting HTTP, WebSocket, IPC, and testing environments with automatic provider detection and persistent connection management.
class HTTPProvider:
def __init__(self, endpoint_uri=None, request_kwargs=None): ...
class AsyncHTTPProvider:
def __init__(self, endpoint_uri=None, request_kwargs=None): ...
class WebSocketProvider:
def __init__(self, endpoint_uri=None): ...
class IPCProvider:
def __init__(self, ipc_path=None): ...
class AutoProvider:
@staticmethod
def from_auto() -> BaseProvider: ...Core Ethereum blockchain operations including transaction management, block and account queries, smart contract deployment and interaction, event filtering, and gas management.
class Eth:
@property
def accounts(self) -> List[ChecksumAddress]: ...
@property
def block_number(self) -> BlockNumber: ...
def get_balance(self, account: AnyAddress, block_identifier: BlockIdentifier = "latest") -> Wei: ...
def send_transaction(self, transaction: TxParams) -> HexBytes: ...
def get_transaction(self, transaction_hash: Hash32) -> TxData: ...
def contract(self, address: AnyAddress = None, abi: ABI = None) -> Contract: ...
def get_logs(self, filter_params: FilterParams) -> List[LogReceipt]: ...Smart contract deployment, interaction, and management with ABI-based function calls, event filtering, transaction handling, and comprehensive type support for contract development.
class Contract:
def __init__(self, address: AnyAddress = None, abi: ABI = None): ...
@property
def functions(self) -> ContractFunctions: ...
@property
def events(self) -> ContractEvents: ...
@classmethod
def constructor(cls, **kwargs) -> ContractConstructor: ...
class AsyncContract:
def __init__(self, address: AnyAddress = None, abi: ABI = None): ...
@property
def functions(self) -> AsyncContractFunctions: ...
@property
def events(self) -> AsyncContractEvents: ...Ethereum Name Service integration for human-readable address resolution, reverse lookups, domain management, and decentralized naming system interactions.
class ENS:
def __init__(self, provider=None): ...
def address(self, name: str) -> ChecksumAddress: ...
def name(self, address: AnyAddress) -> str: ...
def resolver(self, name: str) -> ChecksumAddress: ...
def owner(self, name: str) -> ChecksumAddress: ...
class AsyncENS:
def __init__(self, provider=None): ...
async def address(self, name: str) -> ChecksumAddress: ...
async def name(self, address: AnyAddress) -> str: ...Request and response processing middleware for customizing Web3 behavior including validation, formatting, signing, filtering, and gas price strategies with composable middleware stack management.
class Web3Middleware:
def __init__(self, w3: Web3): ...
def wrap_make_request(self, make_request: MakeRequestFn) -> MakeRequestFn: ...
def combine_middleware(
middleware: Sequence[Middleware],
w3: Web3,
provider_request_fn: MakeRequestFn
) -> Callable[..., RPCResponse]: ...Cryptographic account operations including key generation, transaction signing, message signing, account recovery, and secure key management with support for various key formats.
class Account:
@staticmethod
def create(extra_entropy: str = '') -> LocalAccount: ...
@staticmethod
def from_key(private_key: PrivateKey) -> LocalAccount: ...
@staticmethod
def encrypt(private_key: PrivateKey, password: str) -> dict: ...
@staticmethod
def decrypt(keyfile_json: dict, password: str) -> PrivateKey: ...
@staticmethod
def sign_transaction(transaction_dict: dict, private_key: PrivateKey) -> SignedTransaction: ...Core utility functions for data conversion, encoding, validation, and Ethereum-specific operations including Wei conversions, address validation, hash functions, and data formatting.
def to_wei(number: Union[int, float, str, decimal.Decimal], unit: str) -> Wei: ...
def from_wei(number: Wei, unit: str) -> decimal.Decimal: ...
def to_checksum_address(value: AnyAddress) -> ChecksumAddress: ...
def is_address(value: Any) -> bool: ...
def is_checksum_address(value: Any) -> bool: ...
def keccak(primitive: Primitives = None, text: str = None, hexstr: HexStr = None) -> HexBytes: ...Core type definitions used throughout the Web3.py API.
Wei = NewType('Wei', int)
BlockNumber = NewType('BlockNumber', int)
ChecksumAddress = NewType('ChecksumAddress', str)
HexStr = NewType('HexStr', str)
Hash32 = NewType('Hash32', bytes)class TxParams(TypedDict):
from_: NotRequired[ChecksumAddress]
to: NotRequired[ChecksumAddress]
value: NotRequired[Wei]
gas: NotRequired[int]
gasPrice: NotRequired[Wei]
data: NotRequired[HexStr]
nonce: NotRequired[int]
class TxData(TypedDict):
hash: Hash32
blockHash: Hash32
blockNumber: BlockNumber
transactionIndex: int
from_: ChecksumAddress
to: ChecksumAddress
value: Wei
gas: int
gasPrice: Wei
input: HexStrclass BlockData(TypedDict):
number: BlockNumber
hash: Hash32
parentHash: Hash32
timestamp: int
size: int
gasLimit: int
gasUsed: int
transactions: List[Union[Hash32, TxData]]
class BlockReceipts(TypedDict):
receipts: List[TxReceipt]class FilterParams(TypedDict):
fromBlock: NotRequired[BlockIdentifier]
toBlock: NotRequired[BlockIdentifier]
address: NotRequired[Union[ChecksumAddress, List[ChecksumAddress]]]
topics: NotRequired[List[Optional[Union[HexStr, List[HexStr]]]]]
class LogReceipt(TypedDict):
address: ChecksumAddress
topics: List[HexStr]
data: HexStr
blockNumber: BlockNumber
transactionHash: Hash32
transactionIndex: int
blockHash: Hash32
logIndex: int
removed: boolclass CreateAccessListResponse(TypedDict):
accessList: List[AccessListEntry]
gasUsed: int
class AccessListEntry(TypedDict):
address: ChecksumAddress
storageKeys: List[HexStr]
class FeeHistory(TypedDict):
baseFeePerGas: List[Wei]
gasUsedRatio: List[float]
oldestBlock: BlockNumber
reward: List[List[Wei]]
class MerkleProof(TypedDict):
address: ChecksumAddress
accountProof: List[HexStr]
balance: Wei
codeHash: Hash32
nonce: int
storageHash: Hash32
storageProof: List[StorageProof]
class StorageProof(TypedDict):
key: HexStr
value: HexStr
proof: List[HexStr]
class SyncStatus(TypedDict):
startingBlock: BlockNumber
currentBlock: BlockNumber
highestBlock: BlockNumberABI = List[Dict[str, Any]]
class Contract:
address: ChecksumAddress
abi: ABI
functions: ContractFunctions
events: ContractEvents
class ContractFunctions:
pass
class ContractEvents:
passStateOverride = Dict[ChecksumAddress, StateOverrideEntry]
class StateOverrideEntry(TypedDict):
balance: NotRequired[Wei]
nonce: NotRequired[int]
code: NotRequired[HexStr]
state: NotRequired[Dict[HexStr, HexStr]]
stateDiff: NotRequired[Dict[HexStr, HexStr]]class SimulateV1Payload(TypedDict):
blockStateOverrides: NotRequired[StateOverride]
calls: List[SimulateCall]
class SimulateCall(TypedDict):
from_: NotRequired[ChecksumAddress]
to: ChecksumAddress
value: NotRequired[Wei]
data: NotRequired[HexStr]
class SimulateV1Result(TypedDict):
result: HexStr
logs: List[LogReceipt]SubscriptionType = Union[Literal["newHeads"], Literal["logs"], Literal["newPendingTransactions"], Literal["syncing"]]
class LogsSubscriptionArg(TypedDict):
address: NotRequired[Union[ChecksumAddress, List[ChecksumAddress]]]
topics: NotRequired[List[Optional[Union[HexStr, List[HexStr]]]]]
EthSubscriptionHandler = Callable[[Dict[str, Any]], None]class SignedTx(TypedDict):
rawTransaction: HexBytes
hash: Hash32
r: int
s: int
v: int