0
# Web3 Client
1
2
The main client classes for connecting to Ethereum nodes, providing comprehensive blockchain interaction capabilities and module management.
3
4
## Capabilities
5
6
### Web3 Class
7
8
Main synchronous client for Ethereum interaction with provider management, middleware support, and module attachment.
9
10
```python { .api }
11
class Web3:
12
def __init__(
13
self,
14
provider: BaseProvider = None,
15
modules: Dict[str, Union[Type[Module], Sequence[Any]]] = None,
16
middleware: Optional[List[Middleware]] = None
17
):
18
"""
19
Initialize Web3 instance.
20
21
Parameters:
22
- provider: Connection provider (HTTPProvider, WebSocketProvider, etc.)
23
- modules: Custom modules to attach
24
- middleware: Middleware stack for request/response processing
25
"""
26
27
def is_connected(self) -> bool:
28
"""Check if connected to Ethereum node."""
29
30
@property
31
def eth(self) -> Eth:
32
"""Access Ethereum operations module."""
33
34
@property
35
def net(self) -> Net:
36
"""Access network operations module."""
37
38
@property
39
def geth(self) -> Geth:
40
"""Access Geth-specific operations module."""
41
42
@property
43
def manager(self) -> RequestManager:
44
"""Access request manager for low-level operations."""
45
46
@property
47
def middleware_onion(self) -> MiddlewareOnion:
48
"""Access middleware management."""
49
50
@property
51
def provider(self) -> BaseProvider:
52
"""Access current provider."""
53
54
def enable_unstable_package_management_api(self) -> None:
55
"""Enable package management functionality."""
56
57
def to_wei(self, number: Union[int, float, str, decimal.Decimal], unit: str) -> Wei:
58
"""Convert number to Wei."""
59
60
def from_wei(self, number: Wei, unit: str) -> decimal.Decimal:
61
"""Convert Wei to specified unit."""
62
63
def to_checksum_address(self, value: AnyAddress) -> ChecksumAddress:
64
"""Convert address to checksum format."""
65
66
def is_address(self, value: Any) -> bool:
67
"""Check if value is valid Ethereum address."""
68
69
def is_checksum_address(self, value: Any) -> bool:
70
"""Check if address is in checksum format."""
71
72
def keccak(
73
self,
74
primitive: Primitives = None,
75
text: str = None,
76
hexstr: HexStr = None
77
) -> HexBytes:
78
"""Compute Keccak-256 hash."""
79
80
def solidity_keccak(self, abi_types: List[str], values: List[Any]) -> HexBytes:
81
"""Compute Solidity-compatible Keccak hash."""
82
83
def encode_abi(self, types: List[str], args: List[Any]) -> HexBytes:
84
"""Encode data according to ABI specification."""
85
86
def decode_abi(self, types: List[str], data: HexBytes) -> List[Any]:
87
"""Decode ABI-encoded data."""
88
89
def to_bytes(
90
self,
91
primitive: Primitives = None,
92
hexstr: HexStr = None,
93
text: str = None
94
) -> bytes:
95
"""Convert primitive to bytes."""
96
97
def to_int(
98
self,
99
primitive: Primitives = None,
100
hexstr: HexStr = None,
101
text: str = None
102
) -> int:
103
"""Convert primitive to integer."""
104
105
def to_hex(
106
self,
107
primitive: Primitives = None,
108
hexstr: HexStr = None,
109
text: str = None
110
) -> HexStr:
111
"""Convert primitive to hex string."""
112
113
def to_text(
114
self,
115
primitive: Primitives = None,
116
hexstr: HexStr = None,
117
text: str = None
118
) -> str:
119
"""Convert primitive to text string."""
120
121
def to_json(self, obj: Dict[Any, Any]) -> str:
122
"""Convert object to JSON string."""
123
124
def normalize_values(
125
self,
126
abi_types: List[str],
127
values: List[Any]
128
) -> List[Any]:
129
"""Normalize values according to ABI types."""
130
131
def is_encodable(self, _type: str, value: Any) -> bool:
132
"""Check if value is encodable for given type."""
133
134
def attach_modules(
135
self,
136
modules: Optional[Dict[str, Union[Type[Module], Sequence[Any]]]]
137
) -> None:
138
"""Attach modules to Web3 instance."""
139
140
def batch_requests(self) -> RequestBatcher:
141
"""Create batch request context manager."""
142
```
143
144
### AsyncWeb3 Class
145
146
Asynchronous client providing the same interface as Web3 with async/await support.
147
148
```python { .api }
149
class AsyncWeb3:
150
def __init__(
151
self,
152
provider: AsyncBaseProvider = None,
153
modules: Dict[str, Union[Type[Module], Sequence[Any]]] = None,
154
middleware: Optional[List[Middleware]] = None
155
):
156
"""
157
Initialize AsyncWeb3 instance.
158
159
Parameters:
160
- provider: Async connection provider
161
- modules: Custom modules to attach
162
- middleware: Middleware stack for request/response processing
163
"""
164
165
async def is_connected(self) -> bool:
166
"""Check if connected to Ethereum node."""
167
168
@property
169
def eth(self) -> AsyncEth:
170
"""Access async Ethereum operations module."""
171
172
@property
173
def net(self) -> AsyncNet:
174
"""Access async network operations module."""
175
176
@property
177
def geth(self) -> AsyncGeth:
178
"""Access async Geth-specific operations module."""
179
180
@property
181
def manager(self) -> RequestManager:
182
"""Access request manager for low-level operations."""
183
184
@property
185
def middleware_onion(self) -> MiddlewareOnion:
186
"""Access middleware management."""
187
188
@property
189
def provider(self) -> AsyncBaseProvider:
190
"""Access current async provider."""
191
192
def to_wei(self, number: Union[int, float, str, decimal.Decimal], unit: str) -> Wei:
193
"""Convert number to Wei."""
194
195
def from_wei(self, number: Wei, unit: str) -> decimal.Decimal:
196
"""Convert Wei to specified unit."""
197
198
def to_checksum_address(self, value: AnyAddress) -> ChecksumAddress:
199
"""Convert address to checksum format."""
200
201
def is_address(self, value: Any) -> bool:
202
"""Check if value is valid Ethereum address."""
203
204
def is_checksum_address(self, value: Any) -> bool:
205
"""Check if address is in checksum format."""
206
207
def keccak(
208
self,
209
primitive: Primitives = None,
210
text: str = None,
211
hexstr: HexStr = None
212
) -> HexBytes:
213
"""Compute Keccak-256 hash."""
214
215
def solidity_keccak(self, abi_types: List[str], values: List[Any]) -> HexBytes:
216
"""Compute Solidity-compatible Keccak hash."""
217
218
def encode_abi(self, types: List[str], args: List[Any]) -> HexBytes:
219
"""Encode data according to ABI specification."""
220
221
def decode_abi(self, types: List[str], data: HexBytes) -> List[Any]:
222
"""Decode ABI-encoded data."""
223
```
224
225
### Module Management
226
227
```python { .api }
228
def get_default_modules() -> Dict[str, Union[Type[Module], Sequence[Any]]]:
229
"""Get default modules attached to Web3 instance."""
230
231
def get_async_default_modules() -> Dict[str, Union[Type[Module], Sequence[Any]]]:
232
"""Get default modules attached to AsyncWeb3 instance."""
233
```
234
235
## Usage Examples
236
237
### Basic Connection
238
239
```python
240
from web3 import Web3
241
242
# HTTP connection
243
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))
244
245
# Check connection
246
if w3.is_connected():
247
print("Connected to Ethereum mainnet")
248
print(f"Latest block: {w3.eth.block_number}")
249
```
250
251
### Custom Middleware
252
253
```python
254
from web3 import Web3
255
from web3.middleware import geth_poa_middleware
256
257
w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
258
259
# Add Proof of Authority middleware for private networks
260
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
261
```
262
263
### Async Usage
264
265
```python
266
import asyncio
267
from web3 import AsyncWeb3
268
269
async def main():
270
w3 = AsyncWeb3(AsyncWeb3.AsyncHTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))
271
272
if await w3.is_connected():
273
block_number = await w3.eth.block_number
274
print(f"Latest block: {block_number}")
275
276
asyncio.run(main())
277
```