A Python library for interacting with Ethereum blockchain
npx @tessl/cli install tessl/pypi-web3@7.13.00
# Web3.py
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: web3
7
- **Language**: Python
8
- **Installation**: `pip install web3`
9
- **Version**: 7.13.0
10
11
## Core Imports
12
13
```python
14
from web3 import Web3
15
```
16
17
For ENS functionality:
18
19
```python
20
from ens import ENS
21
```
22
23
Provider classes:
24
25
```python
26
from web3 import HTTPProvider, WebSocketProvider, IPCProvider
27
```
28
29
Account management:
30
31
```python
32
from web3 import Account
33
```
34
35
## Basic Usage
36
37
```python
38
from web3 import Web3
39
40
# Connect to Ethereum node
41
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))
42
43
# Check connection
44
if w3.is_connected():
45
print("Connected to Ethereum")
46
47
# Get latest block number
48
block_number = w3.eth.block_number
49
print(f"Latest block: {block_number}")
50
51
# Get account balance
52
balance = w3.eth.get_balance('0x742d35Cc6635C0532925a3b8D5c0d9E3C4B3c8')
53
balance_ether = w3.from_wei(balance, 'ether')
54
print(f"Balance: {balance_ether} ETH")
55
56
# Smart contract interaction
57
contract_address = '0x...'
58
contract_abi = [...] # Contract ABI
59
contract = w3.eth.contract(address=contract_address, abi=contract_abi)
60
result = contract.functions.someMethod().call()
61
```
62
63
## Architecture
64
65
Web3.py follows a modular architecture organized around key blockchain interaction patterns:
66
67
- **Web3 Client**: Main entry point providing connection management and module coordination
68
- **Providers**: Connection adapters for different Ethereum client interfaces (HTTP, WebSocket, IPC)
69
- **Modules**: Domain-specific functionality (eth, net, geth) attached to the Web3 instance
70
- **Middleware**: Request/response processing pipeline for customizing behavior
71
- **Contracts**: High-level interface for smart contract interaction with ABI support
72
- **ENS**: Ethereum Name Service integration for human-readable addresses
73
74
This design enables flexible blockchain integration while providing both low-level access and high-level convenience methods.
75
76
## Capabilities
77
78
### Web3 Client
79
80
Main client classes for connecting to Ethereum nodes with comprehensive blockchain interaction capabilities including transaction management, block queries, and smart contract operations.
81
82
```python { .api }
83
class Web3:
84
def __init__(self, provider=None, modules=None, middleware=None): ...
85
def is_connected(self) -> bool: ...
86
@property
87
def eth(self) -> Eth: ...
88
@property
89
def net(self) -> Net: ...
90
@property
91
def geth(self) -> Geth: ...
92
93
class AsyncWeb3:
94
def __init__(self, provider=None, modules=None, middleware=None): ...
95
async def is_connected(self) -> bool: ...
96
@property
97
def eth(self) -> AsyncEth: ...
98
@property
99
def net(self) -> AsyncNet: ...
100
@property
101
def geth(self) -> AsyncGeth: ...
102
```
103
104
[Web3 Client](./web3-client.md)
105
106
### Providers
107
108
Connection providers for different Ethereum client interfaces supporting HTTP, WebSocket, IPC, and testing environments with automatic provider detection and persistent connection management.
109
110
```python { .api }
111
class HTTPProvider:
112
def __init__(self, endpoint_uri=None, request_kwargs=None): ...
113
114
class AsyncHTTPProvider:
115
def __init__(self, endpoint_uri=None, request_kwargs=None): ...
116
117
class WebSocketProvider:
118
def __init__(self, endpoint_uri=None): ...
119
120
class IPCProvider:
121
def __init__(self, ipc_path=None): ...
122
123
class AutoProvider:
124
@staticmethod
125
def from_auto() -> BaseProvider: ...
126
```
127
128
[Providers](./providers.md)
129
130
### Ethereum Operations
131
132
Core Ethereum blockchain operations including transaction management, block and account queries, smart contract deployment and interaction, event filtering, and gas management.
133
134
```python { .api }
135
class Eth:
136
@property
137
def accounts(self) -> List[ChecksumAddress]: ...
138
@property
139
def block_number(self) -> BlockNumber: ...
140
def get_balance(self, account: AnyAddress, block_identifier: BlockIdentifier = "latest") -> Wei: ...
141
def send_transaction(self, transaction: TxParams) -> HexBytes: ...
142
def get_transaction(self, transaction_hash: Hash32) -> TxData: ...
143
def contract(self, address: AnyAddress = None, abi: ABI = None) -> Contract: ...
144
def get_logs(self, filter_params: FilterParams) -> List[LogReceipt]: ...
145
```
146
147
[Ethereum Operations](./ethereum-operations.md)
148
149
### Smart Contracts
150
151
Smart contract deployment, interaction, and management with ABI-based function calls, event filtering, transaction handling, and comprehensive type support for contract development.
152
153
```python { .api }
154
class Contract:
155
def __init__(self, address: AnyAddress = None, abi: ABI = None): ...
156
@property
157
def functions(self) -> ContractFunctions: ...
158
@property
159
def events(self) -> ContractEvents: ...
160
@classmethod
161
def constructor(cls, **kwargs) -> ContractConstructor: ...
162
163
class AsyncContract:
164
def __init__(self, address: AnyAddress = None, abi: ABI = None): ...
165
@property
166
def functions(self) -> AsyncContractFunctions: ...
167
@property
168
def events(self) -> AsyncContractEvents: ...
169
```
170
171
[Smart Contracts](./smart-contracts.md)
172
173
### ENS (Ethereum Name Service)
174
175
Ethereum Name Service integration for human-readable address resolution, reverse lookups, domain management, and decentralized naming system interactions.
176
177
```python { .api }
178
class ENS:
179
def __init__(self, provider=None): ...
180
def address(self, name: str) -> ChecksumAddress: ...
181
def name(self, address: AnyAddress) -> str: ...
182
def resolver(self, name: str) -> ChecksumAddress: ...
183
def owner(self, name: str) -> ChecksumAddress: ...
184
185
class AsyncENS:
186
def __init__(self, provider=None): ...
187
async def address(self, name: str) -> ChecksumAddress: ...
188
async def name(self, address: AnyAddress) -> str: ...
189
```
190
191
[ENS Operations](./ens-operations.md)
192
193
### Middleware
194
195
Request and response processing middleware for customizing Web3 behavior including validation, formatting, signing, filtering, and gas price strategies with composable middleware stack management.
196
197
```python { .api }
198
class Web3Middleware:
199
def __init__(self, w3: Web3): ...
200
def wrap_make_request(self, make_request: MakeRequestFn) -> MakeRequestFn: ...
201
202
def combine_middleware(
203
middleware: Sequence[Middleware],
204
w3: Web3,
205
provider_request_fn: MakeRequestFn
206
) -> Callable[..., RPCResponse]: ...
207
```
208
209
[Middleware](./middleware.md)
210
211
### Account Management
212
213
Cryptographic account operations including key generation, transaction signing, message signing, account recovery, and secure key management with support for various key formats.
214
215
```python { .api }
216
class Account:
217
@staticmethod
218
def create(extra_entropy: str = '') -> LocalAccount: ...
219
@staticmethod
220
def from_key(private_key: PrivateKey) -> LocalAccount: ...
221
@staticmethod
222
def encrypt(private_key: PrivateKey, password: str) -> dict: ...
223
@staticmethod
224
def decrypt(keyfile_json: dict, password: str) -> PrivateKey: ...
225
@staticmethod
226
def sign_transaction(transaction_dict: dict, private_key: PrivateKey) -> SignedTransaction: ...
227
```
228
229
[Account Management](./account-management.md)
230
231
### Utilities
232
233
Core utility functions for data conversion, encoding, validation, and Ethereum-specific operations including Wei conversions, address validation, hash functions, and data formatting.
234
235
```python { .api }
236
def to_wei(number: Union[int, float, str, decimal.Decimal], unit: str) -> Wei: ...
237
def from_wei(number: Wei, unit: str) -> decimal.Decimal: ...
238
def to_checksum_address(value: AnyAddress) -> ChecksumAddress: ...
239
def is_address(value: Any) -> bool: ...
240
def is_checksum_address(value: Any) -> bool: ...
241
def keccak(primitive: Primitives = None, text: str = None, hexstr: HexStr = None) -> HexBytes: ...
242
```
243
244
[Utilities](./utilities.md)
245
246
## Types
247
248
Core type definitions used throughout the Web3.py API.
249
250
### Basic Types
251
252
```python { .api }
253
Wei = NewType('Wei', int)
254
BlockNumber = NewType('BlockNumber', int)
255
ChecksumAddress = NewType('ChecksumAddress', str)
256
HexStr = NewType('HexStr', str)
257
Hash32 = NewType('Hash32', bytes)
258
```
259
260
### Transaction Types
261
262
```python { .api }
263
class TxParams(TypedDict):
264
from_: NotRequired[ChecksumAddress]
265
to: NotRequired[ChecksumAddress]
266
value: NotRequired[Wei]
267
gas: NotRequired[int]
268
gasPrice: NotRequired[Wei]
269
data: NotRequired[HexStr]
270
nonce: NotRequired[int]
271
272
class TxData(TypedDict):
273
hash: Hash32
274
blockHash: Hash32
275
blockNumber: BlockNumber
276
transactionIndex: int
277
from_: ChecksumAddress
278
to: ChecksumAddress
279
value: Wei
280
gas: int
281
gasPrice: Wei
282
input: HexStr
283
```
284
285
### Block Types
286
287
```python { .api }
288
class BlockData(TypedDict):
289
number: BlockNumber
290
hash: Hash32
291
parentHash: Hash32
292
timestamp: int
293
size: int
294
gasLimit: int
295
gasUsed: int
296
transactions: List[Union[Hash32, TxData]]
297
298
class BlockReceipts(TypedDict):
299
receipts: List[TxReceipt]
300
```
301
302
### Filter Types
303
304
```python { .api }
305
class FilterParams(TypedDict):
306
fromBlock: NotRequired[BlockIdentifier]
307
toBlock: NotRequired[BlockIdentifier]
308
address: NotRequired[Union[ChecksumAddress, List[ChecksumAddress]]]
309
topics: NotRequired[List[Optional[Union[HexStr, List[HexStr]]]]]
310
311
class LogReceipt(TypedDict):
312
address: ChecksumAddress
313
topics: List[HexStr]
314
data: HexStr
315
blockNumber: BlockNumber
316
transactionHash: Hash32
317
transactionIndex: int
318
blockHash: Hash32
319
logIndex: int
320
removed: bool
321
```
322
323
### Response Types
324
325
```python { .api }
326
class CreateAccessListResponse(TypedDict):
327
accessList: List[AccessListEntry]
328
gasUsed: int
329
330
class AccessListEntry(TypedDict):
331
address: ChecksumAddress
332
storageKeys: List[HexStr]
333
334
class FeeHistory(TypedDict):
335
baseFeePerGas: List[Wei]
336
gasUsedRatio: List[float]
337
oldestBlock: BlockNumber
338
reward: List[List[Wei]]
339
340
class MerkleProof(TypedDict):
341
address: ChecksumAddress
342
accountProof: List[HexStr]
343
balance: Wei
344
codeHash: Hash32
345
nonce: int
346
storageHash: Hash32
347
storageProof: List[StorageProof]
348
349
class StorageProof(TypedDict):
350
key: HexStr
351
value: HexStr
352
proof: List[HexStr]
353
354
class SyncStatus(TypedDict):
355
startingBlock: BlockNumber
356
currentBlock: BlockNumber
357
highestBlock: BlockNumber
358
```
359
360
### Contract Types
361
362
```python { .api }
363
ABI = List[Dict[str, Any]]
364
365
class Contract:
366
address: ChecksumAddress
367
abi: ABI
368
functions: ContractFunctions
369
events: ContractEvents
370
371
class ContractFunctions:
372
pass
373
374
class ContractEvents:
375
pass
376
```
377
378
### State Override Types
379
380
```python { .api }
381
StateOverride = Dict[ChecksumAddress, StateOverrideEntry]
382
383
class StateOverrideEntry(TypedDict):
384
balance: NotRequired[Wei]
385
nonce: NotRequired[int]
386
code: NotRequired[HexStr]
387
state: NotRequired[Dict[HexStr, HexStr]]
388
stateDiff: NotRequired[Dict[HexStr, HexStr]]
389
```
390
391
### Simulation Types
392
393
```python { .api }
394
class SimulateV1Payload(TypedDict):
395
blockStateOverrides: NotRequired[StateOverride]
396
calls: List[SimulateCall]
397
398
class SimulateCall(TypedDict):
399
from_: NotRequired[ChecksumAddress]
400
to: ChecksumAddress
401
value: NotRequired[Wei]
402
data: NotRequired[HexStr]
403
404
class SimulateV1Result(TypedDict):
405
result: HexStr
406
logs: List[LogReceipt]
407
```
408
409
### Subscription Types
410
411
```python { .api }
412
SubscriptionType = Union[Literal["newHeads"], Literal["logs"], Literal["newPendingTransactions"], Literal["syncing"]]
413
414
class LogsSubscriptionArg(TypedDict):
415
address: NotRequired[Union[ChecksumAddress, List[ChecksumAddress]]]
416
topics: NotRequired[List[Optional[Union[HexStr, List[HexStr]]]]]
417
418
EthSubscriptionHandler = Callable[[Dict[str, Any]], None]
419
```
420
421
### Signed Transaction Types
422
423
```python { .api }
424
class SignedTx(TypedDict):
425
rawTransaction: HexBytes
426
hash: Hash32
427
r: int
428
s: int
429
v: int
430
```