0
# Network Information
1
2
Ethereum network data including chain IDs, network names, and metadata for all major Ethereum networks and testnets.
3
4
## Capabilities
5
6
### Network Data Access
7
8
Retrieve network information by chain ID.
9
10
```python { .api }
11
def network_from_chain_id(chain_id: int) -> Network:
12
"""
13
Get complete network object from chain ID.
14
15
Args:
16
chain_id (int): Ethereum chain ID
17
18
Returns:
19
Network: Network object with chain_id, name, shortName, symbol
20
21
Raises:
22
KeyError: If chain ID is not found
23
"""
24
25
def name_from_chain_id(chain_id: int) -> str:
26
"""
27
Get network name from chain ID.
28
29
Args:
30
chain_id (int): Ethereum chain ID
31
32
Returns:
33
str: Network name
34
35
Raises:
36
KeyError: If chain ID is not found
37
"""
38
39
def short_name_from_chain_id(chain_id: int) -> str:
40
"""
41
Get network short name from chain ID.
42
43
Args:
44
chain_id (int): Ethereum chain ID
45
46
Returns:
47
str: Network short name
48
49
Raises:
50
KeyError: If chain ID is not found
51
"""
52
```
53
54
### Network Data Structures
55
56
Network information data classes and constants.
57
58
```python { .api }
59
class Network:
60
"""Ethereum network information dataclass."""
61
chain_id: int
62
name: str
63
shortName: str
64
symbol: str
65
66
# Network data constants
67
networks: List[Network] # List of all known networks
68
networks_by_id: Dict[int, Network] # Chain ID to Network mapping
69
network_names_by_id: Dict[int, str] # Chain ID to name mapping
70
network_short_names_by_id: Dict[int, str] # Chain ID to short name mapping
71
```
72
73
## Usage Examples
74
75
### Basic Network Lookup
76
77
```python
78
from eth_utils import network_from_chain_id, name_from_chain_id, short_name_from_chain_id
79
80
# Get complete network information
81
mainnet = network_from_chain_id(1)
82
print(f"Network: {mainnet.name}") # Ethereum Mainnet
83
print(f"Symbol: {mainnet.symbol}") # ETH
84
print(f"Short name: {mainnet.shortName}") # eth
85
86
# Get specific network properties
87
polygon_name = name_from_chain_id(137)
88
print(polygon_name) # Polygon Mainnet
89
90
arbitrum_short = short_name_from_chain_id(42161)
91
print(arbitrum_short) # arb1
92
```
93
94
### Network Validation
95
96
```python
97
from eth_utils import networks_by_id, network_from_chain_id
98
99
def is_supported_network(chain_id):
100
"""Check if chain ID is supported."""
101
return chain_id in networks_by_id
102
103
def get_network_info(chain_id):
104
"""Safely get network information."""
105
try:
106
return network_from_chain_id(chain_id)
107
except KeyError:
108
return None
109
110
def validate_chain_id(chain_id):
111
"""Validate and get chain information."""
112
if not isinstance(chain_id, int):
113
raise TypeError("Chain ID must be integer")
114
115
if chain_id <= 0:
116
raise ValueError("Chain ID must be positive")
117
118
if not is_supported_network(chain_id):
119
raise ValueError(f"Unsupported chain ID: {chain_id}")
120
121
return network_from_chain_id(chain_id)
122
123
# Examples
124
print(is_supported_network(1)) # True (Ethereum Mainnet)
125
print(is_supported_network(99999)) # False (Unknown network)
126
127
network = get_network_info(1)
128
if network:
129
print(f"Found network: {network.name}")
130
131
try:
132
validate_chain_id(1) # Success
133
validate_chain_id(99999) # Raises ValueError
134
except ValueError as e:
135
print(f"Validation error: {e}")
136
```
137
138
### Network-Specific Configuration
139
140
```python
141
from eth_utils import network_from_chain_id
142
143
class NetworkConfig:
144
"""Network-specific configuration."""
145
146
def __init__(self, chain_id):
147
self.network = network_from_chain_id(chain_id)
148
self.chain_id = chain_id
149
150
@property
151
def is_mainnet(self):
152
return self.chain_id == 1
153
154
@property
155
def is_testnet(self):
156
testnet_ids = {3, 4, 5, 42, 11155111} # Common testnets
157
return self.chain_id in testnet_ids
158
159
@property
160
def block_time(self):
161
"""Average block time in seconds."""
162
block_times = {
163
1: 12, # Ethereum Mainnet
164
137: 2, # Polygon
165
56: 3, # BSC
166
42161: 1, # Arbitrum One
167
}
168
return block_times.get(self.chain_id, 12) # Default to 12s
169
170
@property
171
def native_currency(self):
172
"""Get native currency symbol."""
173
return self.network.symbol
174
175
def get_explorer_url(self, tx_hash=None, address=None):
176
"""Get block explorer URL."""
177
explorers = {
178
1: "https://etherscan.io",
179
137: "https://polygonscan.com",
180
56: "https://bscscan.com",
181
42161: "https://arbiscan.io"
182
}
183
184
base_url = explorers.get(self.chain_id)
185
if not base_url:
186
return None
187
188
if tx_hash:
189
return f"{base_url}/tx/{tx_hash}"
190
elif address:
191
return f"{base_url}/address/{address}"
192
else:
193
return base_url
194
195
# Usage
196
config = NetworkConfig(1) # Ethereum Mainnet
197
print(f"Network: {config.network.name}")
198
print(f"Is mainnet: {config.is_mainnet}")
199
print(f"Block time: {config.block_time}s")
200
print(f"Currency: {config.native_currency}")
201
print(f"Explorer: {config.get_explorer_url()}")
202
```
203
204
### Multi-Chain Application Support
205
206
```python
207
from eth_utils import networks, network_from_chain_id
208
209
class MultiChainSupport:
210
"""Multi-chain application support."""
211
212
def __init__(self, supported_chains=None):
213
if supported_chains:
214
self.supported_networks = [
215
network_from_chain_id(chain_id)
216
for chain_id in supported_chains
217
]
218
else:
219
# Default to major networks
220
major_chains = [1, 137, 56, 42161, 10, 8453] # ETH, Polygon, BSC, Arbitrum, Optimism, Base
221
self.supported_networks = [
222
network_from_chain_id(chain_id)
223
for chain_id in major_chains
224
if chain_id in networks_by_id
225
]
226
227
def is_supported(self, chain_id):
228
"""Check if chain is supported."""
229
return any(network.chain_id == chain_id for network in self.supported_networks)
230
231
def get_supported_networks(self):
232
"""Get list of supported networks."""
233
return [(net.chain_id, net.name) for net in self.supported_networks]
234
235
def validate_network(self, chain_id):
236
"""Validate network is supported."""
237
if not self.is_supported(chain_id):
238
supported = [net.chain_id for net in self.supported_networks]
239
raise ValueError(f"Chain {chain_id} not supported. Supported: {supported}")
240
241
return network_from_chain_id(chain_id)
242
243
# Usage
244
multi_chain = MultiChainSupport()
245
print("Supported networks:")
246
for chain_id, name in multi_chain.get_supported_networks():
247
print(f" {chain_id}: {name}")
248
249
# Validate network
250
try:
251
network = multi_chain.validate_network(1) # Success
252
print(f"Using network: {network.name}")
253
except ValueError as e:
254
print(f"Network error: {e}")
255
```
256
257
### Network Utilities
258
259
```python
260
from eth_utils import networks, networks_by_id
261
262
def list_all_networks():
263
"""List all known networks."""
264
print("All known networks:")
265
for network in sorted(networks, key=lambda n: n.chain_id):
266
print(f" {network.chain_id:6d}: {network.name} ({network.shortName})")
267
268
def find_networks_by_name(search_term):
269
"""Find networks by name substring."""
270
matches = []
271
search_lower = search_term.lower()
272
273
for network in networks:
274
if (search_lower in network.name.lower() or
275
search_lower in network.shortName.lower()):
276
matches.append(network)
277
278
return matches
279
280
def get_testnet_networks():
281
"""Get all testnet networks."""
282
testnets = []
283
testnet_keywords = ['test', 'goerli', 'sepolia', 'ropsten', 'kovan', 'rinkeby']
284
285
for network in networks:
286
name_lower = network.name.lower()
287
if any(keyword in name_lower for keyword in testnet_keywords):
288
testnets.append(network)
289
290
return testnets
291
292
def get_layer2_networks():
293
"""Get Layer 2 networks."""
294
layer2_ids = {
295
137: "Polygon",
296
42161: "Arbitrum One",
297
10: "Optimism",
298
8453: "Base",
299
324: "zkSync Era"
300
}
301
302
layer2_networks = []
303
for chain_id, description in layer2_ids.items():
304
if chain_id in networks_by_id:
305
layer2_networks.append(networks_by_id[chain_id])
306
307
return layer2_networks
308
309
# Examples
310
list_all_networks()
311
312
ethereum_networks = find_networks_by_name("ethereum")
313
print(f"\nFound {len(ethereum_networks)} Ethereum networks")
314
315
testnets = get_testnet_networks()
316
print(f"Found {len(testnets)} testnet networks")
317
318
layer2_nets = get_layer2_networks()
319
print(f"Found {len(layer2_nets)} Layer 2 networks")
320
```
321
322
### RPC Configuration Helper
323
324
```python
325
from eth_utils import network_from_chain_id
326
327
class RPCConfig:
328
"""RPC configuration helper using network information."""
329
330
# Common RPC endpoints (example - use your own)
331
DEFAULT_RPCS = {
332
1: ["https://mainnet.infura.io/v3/YOUR-PROJECT-ID"],
333
137: ["https://polygon-rpc.com"],
334
56: ["https://bsc-dataseed.binance.org"],
335
42161: ["https://arb1.arbitrum.io/rpc"]
336
}
337
338
def __init__(self, chain_id, custom_rpc=None):
339
self.network = network_from_chain_id(chain_id)
340
self.chain_id = chain_id
341
self.custom_rpc = custom_rpc
342
343
def get_rpc_urls(self):
344
"""Get RPC URLs for this network."""
345
if self.custom_rpc:
346
return [self.custom_rpc]
347
348
return self.DEFAULT_RPCS.get(self.chain_id, [])
349
350
def get_chain_config(self):
351
"""Get complete chain configuration."""
352
return {
353
"chainId": self.chain_id,
354
"chainName": self.network.name,
355
"nativeCurrency": {
356
"name": self.network.symbol,
357
"symbol": self.network.symbol,
358
"decimals": 18
359
},
360
"rpcUrls": self.get_rpc_urls(),
361
"blockExplorerUrls": [self.get_explorer_url()] if self.get_explorer_url() else []
362
}
363
364
def get_explorer_url(self):
365
"""Get block explorer URL."""
366
explorers = {
367
1: "https://etherscan.io",
368
137: "https://polygonscan.com",
369
56: "https://bscscan.com",
370
42161: "https://arbiscan.io"
371
}
372
return explorers.get(self.chain_id)
373
374
# Usage
375
config = RPCConfig(1) # Ethereum Mainnet
376
chain_config = config.get_chain_config()
377
print(f"Chain config for {chain_config['chainName']}:")
378
print(f" Chain ID: {chain_config['chainId']}")
379
print(f" Currency: {chain_config['nativeCurrency']['symbol']}")
380
print(f" RPC URLs: {chain_config['rpcUrls']}")
381
```
382
383
## Supported Networks
384
385
The eth-utils package includes comprehensive network information for major Ethereum networks including:
386
387
### Mainnets
388
- Ethereum Mainnet (1)
389
- Polygon (137)
390
- Binance Smart Chain (56)
391
- Arbitrum One (42161)
392
- Optimism (10)
393
- Base (8453)
394
395
### Testnets
396
- Goerli (5)
397
- Sepolia (11155111)
398
- Polygon Mumbai (testnet)
399
- BSC Testnet
400
401
### Layer 2 Solutions
402
- Arbitrum networks
403
- Optimism networks
404
- Polygon networks
405
- zkSync networks
406
407
The complete list is available through the `networks` constant and can be explored programmatically.