forked from gakonst/ethers-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain.rs
628 lines (533 loc) · 20.3 KB
/
chain.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
use super::{U128, U256, U512, U64};
use serde::{Deserialize, Serialize, Serializer};
use std::{
convert::{TryFrom, TryInto},
fmt,
time::Duration,
};
use strum::{AsRefStr, EnumCount, EnumIter, EnumString, EnumVariantNames};
// compatibility re-export
#[doc(hidden)]
pub use num_enum::{TryFromPrimitive, TryFromPrimitiveError};
#[doc(hidden)]
pub type ParseChainError = TryFromPrimitiveError<Chain>;
// When adding a new chain:
// 1. add new variant to the Chain enum;
// 2. add extra information in the last `impl` block (explorer URLs, block time) when applicable;
// 3. (optional) add aliases:
// - Strum (in kebab-case): `#[strum(to_string = "<main>", serialize = "<aliasX>", ...)]`
// `to_string = "<main>"` must be present and will be used in `Display`, `Serialize`
// and `FromStr`, while `serialize = "<aliasX>"` will be appended to `FromStr`.
// More info: <https://docs.rs/strum/latest/strum/additional_attributes/index.html#attributes-on-variants>
// - Serde (in snake_case): `#[serde(alias = "<aliasX>", ...)]`
// Aliases are appended to the `Deserialize` implementation.
// More info: <https://serde.rs/variant-attrs.html>
// - Add a test at the bottom of the file
// We don't derive Serialize because it is manually implemented using AsRef<str> and it would
// break a lot of things since Serialize is `kebab-case` vs Deserialize `snake_case`.
// This means that the Chain type is not "round-trippable", because the Serialize and Deserialize
// implementations do not use the same case style.
/// An Ethereum EIP-155 chain.
#[derive(
Clone,
Copy,
Debug,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
AsRefStr, // AsRef<str>, fmt::Display and serde::Serialize
EnumVariantNames, // Chain::VARIANTS
EnumString, // FromStr, TryFrom<&str>
EnumIter, // Chain::iter
EnumCount, // Chain::COUNT
TryFromPrimitive, // TryFrom<u64>
Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "kebab-case")]
#[repr(u64)]
pub enum Chain {
#[strum(to_string = "mainnet", serialize = "ethlive")]
#[serde(alias = "ethlive")]
Mainnet = 1,
Morden = 2,
Ropsten = 3,
Rinkeby = 4,
Goerli = 5,
Kovan = 42,
Sepolia = 11155111,
Optimism = 10,
OptimismKovan = 69,
OptimismGoerli = 420,
Arbitrum = 42161,
ArbitrumTestnet = 421611,
ArbitrumGoerli = 421613,
ArbitrumNova = 42170,
Cronos = 25,
CronosTestnet = 338,
Rsk = 30,
#[strum(to_string = "bsc", serialize = "binance-smart-chain")]
#[serde(alias = "bsc")]
BinanceSmartChain = 56,
#[strum(to_string = "bsc-testnet", serialize = "binance-smart-chain-testnet")]
#[serde(alias = "bsc_testnet")]
BinanceSmartChainTestnet = 97,
Poa = 99,
Sokol = 77,
#[strum(to_string = "xdai", serialize = "gnosis", serialize = "gnosis-chain")]
#[serde(alias = "xdai", alias = "gnosis", alias = "gnosis_chain")]
XDai = 100,
Polygon = 137,
#[strum(to_string = "mumbai", serialize = "polygon-mumbai")]
#[serde(alias = "mumbai")]
PolygonMumbai = 80001,
Fantom = 250,
FantomTestnet = 4002,
Moonbeam = 1284,
MoonbeamDev = 1281,
Moonriver = 1285,
Moonbase = 1287,
Dev = 1337,
#[strum(to_string = "anvil-hardhat", serialize = "anvil", serialize = "hardhat")]
#[serde(alias = "anvil", alias = "hardhat")]
AnvilHardhat = 31337,
Evmos = 9001,
EvmosTestnet = 9000,
Chiado = 10200,
Oasis = 26863,
Emerald = 42262,
EmeraldTestnet = 42261,
FilecoinMainnet = 314,
FilecoinHyperspaceTestnet = 3141,
Avalanche = 43114,
#[strum(to_string = "fuji", serialize = "avalanche-fuji")]
#[serde(alias = "fuji")]
AvalancheFuji = 43113,
Celo = 42220,
CeloAlfajores = 44787,
CeloBaklava = 62320,
Aurora = 1313161554,
AuroraTestnet = 1313161555,
Canto = 7700,
CantoTestnet = 740,
Boba = 288,
}
// === impl Chain ===
// This must be implemented manually so we avoid a conflict with `TryFromPrimitive` where it treats
// the `#[default]` attribute as its own `#[num_enum(default)]`
impl Default for Chain {
fn default() -> Self {
Self::Mainnet
}
}
macro_rules! impl_into_numeric {
($($ty:ty)+) => {$(
impl From<Chain> for $ty {
fn from(chain: Chain) -> Self {
u64::from(chain).into()
}
}
)+};
}
macro_rules! impl_try_from_numeric {
($($native:ty)+ ; $($primitive:ty)*) => {
$(
impl TryFrom<$native> for Chain {
type Error = ParseChainError;
fn try_from(value: $native) -> Result<Self, Self::Error> {
(value as u64).try_into()
}
}
)+
$(
impl TryFrom<$primitive> for Chain {
type Error = ParseChainError;
fn try_from(value: $primitive) -> Result<Self, Self::Error> {
if value.bits() > 64 {
// `TryFromPrimitiveError` only has a `number` field which has the same type
// as the `#[repr(_)]` attribute on the enum.
return Err(ParseChainError { number: value.low_u64() })
}
value.low_u64().try_into()
}
}
)*
};
}
impl From<Chain> for u64 {
fn from(chain: Chain) -> Self {
chain as u64
}
}
impl_into_numeric!(u128 U64 U128 U256 U512);
impl TryFrom<U64> for Chain {
type Error = ParseChainError;
fn try_from(value: U64) -> Result<Self, Self::Error> {
value.low_u64().try_into()
}
}
impl_try_from_numeric!(u8 u16 u32 usize; U128 U256 U512);
impl fmt::Display for Chain {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad(self.as_ref())
}
}
impl Serialize for Chain {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_str(self.as_ref())
}
}
// NB: all utility functions *should* be explicitly exhaustive (not use `_` matcher) so we don't
// forget to update them when adding a new `Chain` variant.
#[allow(clippy::match_like_matches_macro)]
impl Chain {
/// Returns the chain's average blocktime, if applicable.
///
/// It can be beneficial to know the average blocktime to adjust the polling of an HTTP provider
/// for example.
///
/// **Note:** this is not an accurate average, but is rather a sensible default derived from
/// blocktime charts such as [Etherscan's](https://etherscan.com/chart/blocktime)
/// or [Polygonscan's](https://polygonscan.com/chart/blocktime).
///
/// # Examples
///
/// ```
/// use ethers_core::types::Chain;
/// use std::time::Duration;
///
/// assert_eq!(
/// Chain::Mainnet.average_blocktime_hint(),
/// Some(Duration::from_millis(12_000)),
/// );
/// assert_eq!(Chain::Optimism.average_blocktime_hint(), None);
/// ```
pub const fn average_blocktime_hint(&self) -> Option<Duration> {
use Chain::*;
let ms = match self {
Mainnet => 12_000,
Arbitrum | ArbitrumTestnet | ArbitrumGoerli | ArbitrumNova => 1_300,
Polygon | PolygonMumbai => 2_100,
Moonbeam | Moonriver => 12_500,
BinanceSmartChain | BinanceSmartChainTestnet => 3_000,
Avalanche | AvalancheFuji => 2_000,
Fantom | FantomTestnet => 1_200,
Cronos | CronosTestnet | Canto | CantoTestnet => 5_700,
Evmos | EvmosTestnet => 1_900,
Aurora | AuroraTestnet => 1_100,
Oasis => 5_500,
Emerald => 6_000,
Dev | AnvilHardhat => 200,
Celo | CeloAlfajores | CeloBaklava => 5_000,
FilecoinHyperspaceTestnet | FilecoinMainnet => 30_000,
// Explicitly exhaustive. See NB above.
Morden | Ropsten | Rinkeby | Goerli | Kovan | XDai | Chiado | Sepolia | Moonbase |
MoonbeamDev | Optimism | OptimismGoerli | OptimismKovan | Poa | Sokol | Rsk |
EmeraldTestnet | Boba => return None,
};
Some(Duration::from_millis(ms))
}
/// Returns whether the chain implements EIP-1559 (with the type 2 EIP-2718 transaction type).
///
/// # Examples
///
/// ```
/// use ethers_core::types::Chain;
///
/// assert!(!Chain::Mainnet.is_legacy());
/// assert!(Chain::Celo.is_legacy());
/// ```
pub const fn is_legacy(&self) -> bool {
use Chain::*;
match self {
// Known legacy chains / non EIP-1559 compliant
Optimism |
OptimismGoerli |
OptimismKovan |
Fantom |
FantomTestnet |
BinanceSmartChain |
BinanceSmartChainTestnet |
Arbitrum |
ArbitrumTestnet |
ArbitrumGoerli |
ArbitrumNova |
Rsk |
Oasis |
Emerald |
EmeraldTestnet |
Celo |
CeloAlfajores |
CeloBaklava |
Boba => true,
// Known EIP-1559 chains
Mainnet |
Goerli |
Sepolia |
Polygon |
PolygonMumbai |
Avalanche |
AvalancheFuji |
FilecoinHyperspaceTestnet => false,
// Unknown / not applicable, default to false for backwards compatibility
Dev | AnvilHardhat | Morden | Ropsten | Rinkeby | Cronos | CronosTestnet | Kovan |
Sokol | Poa | XDai | Moonbeam | MoonbeamDev | Moonriver | Moonbase | Evmos |
EvmosTestnet | Chiado | Aurora | AuroraTestnet | Canto | CantoTestnet |
FilecoinMainnet => false,
}
}
/// Returns the chain's blockchain explorer and its API (Etherscan and Etherscan-like) URLs.
///
/// Returns `(API_URL, BASE_URL)`
///
/// # Examples
///
/// ```
/// use ethers_core::types::Chain;
///
/// assert_eq!(
/// Chain::Mainnet.etherscan_urls(),
/// Some(("https://api.etherscan.io/api", "https://etherscan.io"))
/// );
/// assert_eq!(
/// Chain::Avalanche.etherscan_urls(),
/// Some(("https://api.snowtrace.io/api", "https://snowtrace.io"))
/// );
/// assert_eq!(Chain::AnvilHardhat.etherscan_urls(), None);
/// ```
pub const fn etherscan_urls(&self) -> Option<(&'static str, &'static str)> {
use Chain::*;
let urls = match self {
Mainnet => ("https://api.etherscan.io/api", "https://etherscan.io"),
Ropsten => ("https://api-ropsten.etherscan.io/api", "https://ropsten.etherscan.io"),
Kovan => ("https://api-kovan.etherscan.io/api", "https://kovan.etherscan.io"),
Rinkeby => ("https://api-rinkeby.etherscan.io/api", "https://rinkeby.etherscan.io"),
Goerli => ("https://api-goerli.etherscan.io/api", "https://goerli.etherscan.io"),
Sepolia => ("https://api-sepolia.etherscan.io/api", "https://sepolia.etherscan.io"),
Polygon => ("https://api.polygonscan.com/api", "https://polygonscan.com"),
PolygonMumbai => {
("https://api-testnet.polygonscan.com/api", "https://mumbai.polygonscan.com")
}
Avalanche => ("https://api.snowtrace.io/api", "https://snowtrace.io"),
AvalancheFuji => {
("https://api-testnet.snowtrace.io/api", "https://testnet.snowtrace.io")
}
Optimism => {
("https://api-optimistic.etherscan.io/api", "https://optimistic.etherscan.io")
}
OptimismGoerli => (
"https://api-goerli-optimistic.etherscan.io/api",
"https://goerli-optimism.etherscan.io",
),
OptimismKovan => (
"https://api-kovan-optimistic.etherscan.io/api",
"https://kovan-optimistic.etherscan.io",
),
Fantom => ("https://api.ftmscan.com/api", "https://ftmscan.com"),
FantomTestnet => ("https://api-testnet.ftmscan.com/api", "https://testnet.ftmscan.com"),
BinanceSmartChain => ("https://api.bscscan.com/api", "https://bscscan.com"),
BinanceSmartChainTestnet => {
("https://api-testnet.bscscan.com/api", "https://testnet.bscscan.com")
}
Arbitrum => ("https://api.arbiscan.io/api", "https://arbiscan.io"),
ArbitrumTestnet => {
("https://api-testnet.arbiscan.io/api", "https://testnet.arbiscan.io")
}
ArbitrumGoerli => ("https://api-goerli.arbiscan.io/api", "https://goerli.arbiscan.io"),
ArbitrumNova => ("https://api-nova.arbiscan.io/api", "https://nova.arbiscan.io/"),
Cronos => ("https://api.cronoscan.com/api", "https://cronoscan.com"),
CronosTestnet => {
("https://api-testnet.cronoscan.com/api", "https://testnet.cronoscan.com")
}
Moonbeam => ("https://api-moonbeam.moonscan.io/api", "https://moonbeam.moonscan.io/"),
Moonbase => ("https://api-moonbase.moonscan.io/api", "https://moonbase.moonscan.io/"),
Moonriver => ("https://api-moonriver.moonscan.io/api", "https://moonriver.moonscan.io"),
// blockscout API is etherscan compatible
XDai => {
("https://blockscout.com/xdai/mainnet/api", "https://blockscout.com/xdai/mainnet")
}
Chiado => {
("https://blockscout.chiadochain.net/api", "https://blockscout.chiadochain.net")
}
FilecoinHyperspaceTestnet => {
("https://api.hyperspace.node.glif.io/rpc/v1", "https://hyperspace.filfox.info")
}
Sokol => ("https://blockscout.com/poa/sokol/api", "https://blockscout.com/poa/sokol"),
Poa => ("https://blockscout.com/poa/core/api", "https://blockscout.com/poa/core"),
Rsk => ("https://blockscout.com/rsk/mainnet/api", "https://blockscout.com/rsk/mainnet"),
Oasis => ("https://scan.oasischain.io/api", "https://scan.oasischain.io/"),
Emerald => {
("https://explorer.emerald.oasis.dev/api", "https://explorer.emerald.oasis.dev/")
}
EmeraldTestnet => (
"https://testnet.explorer.emerald.oasis.dev/api",
"https://testnet.explorer.emerald.oasis.dev/",
),
Aurora => ("https://api.aurorascan.dev/api", "https://aurorascan.dev"),
AuroraTestnet => {
("https://testnet.aurorascan.dev/api", "https://testnet.aurorascan.dev")
}
Evmos => ("https://evm.evmos.org/api", "https://evm.evmos.org/"),
EvmosTestnet => ("https://evm.evmos.dev/api", "https://evm.evmos.dev/"),
Celo => ("https://explorer.celo.org/mainnet/api", "https://explorer.celo.org/mainnet"),
CeloAlfajores => {
("https://explorer.celo.org/alfajores/api", "https://explorer.celo.org/alfajores")
}
CeloBaklava => {
("https://explorer.celo.org/baklava/api", "https://explorer.celo.org/baklava")
}
Canto => ("https://evm.explorer.canto.io/api", "https://evm.explorer.canto.io/"),
CantoTestnet => (
"https://testnet-explorer.canto.neobase.one/api",
"https://testnet-explorer.canto.neobase.one/",
),
Boba => ("https://api.bobascan.com/api", "https://bobascan.com"),
AnvilHardhat | Dev | Morden | MoonbeamDev | FilecoinMainnet => {
// this is explicitly exhaustive so we don't forget to add new urls when adding a
// new chain
return None
}
};
Some(urls)
}
/// Returns the chain's blockchain explorer's API key environment variable's default name.
///
/// # Examples
///
/// ```
/// use ethers_core::types::Chain;
///
/// assert_eq!(Chain::Mainnet.etherscan_api_key_name(), Some("ETHERSCAN_API_KEY"));
/// assert_eq!(Chain::AnvilHardhat.etherscan_api_key_name(), None);
/// ```
pub const fn etherscan_api_key_name(&self) -> Option<&'static str> {
use Chain::*;
let api_key_name = match self {
Mainnet |
Morden |
Ropsten |
Kovan |
Rinkeby |
Goerli |
Optimism |
OptimismGoerli |
OptimismKovan |
BinanceSmartChain |
BinanceSmartChainTestnet |
Arbitrum |
ArbitrumTestnet |
ArbitrumGoerli |
ArbitrumNova |
Cronos |
CronosTestnet |
Aurora |
AuroraTestnet |
Celo |
CeloAlfajores |
CeloBaklava => "ETHERSCAN_API_KEY",
Avalanche | AvalancheFuji => "SNOWTRACE_API_KEY",
Polygon | PolygonMumbai => "POLYGONSCAN_API_KEY",
Fantom | FantomTestnet => "FTMSCAN_API_KEY",
Moonbeam | Moonbase | MoonbeamDev | Moonriver => "MOONSCAN_API_KEY",
Canto | CantoTestnet => "BLOCKSCOUT_API_KEY",
Boba => "BOBASCAN_API_KEY",
// Explicitly exhaustive. See NB above.
XDai |
Chiado |
Sepolia |
Rsk |
Sokol |
Poa |
Oasis |
Emerald |
EmeraldTestnet |
Evmos |
EvmosTestnet |
AnvilHardhat |
Dev |
FilecoinMainnet |
FilecoinHyperspaceTestnet => return None,
};
Some(api_key_name)
}
/// Returns the chain's blockchain explorer's API key, from the environment variable with the
/// name specified in [`etherscan_api_key_name`](Chain::etherscan_api_key_name).
///
/// # Examples
///
/// ```
/// use ethers_core::types::Chain;
///
/// let chain = Chain::Mainnet;
/// std::env::set_var(chain.etherscan_api_key_name().unwrap(), "KEY");
/// assert_eq!(chain.etherscan_api_key().as_deref(), Some("KEY"));
/// ```
pub fn etherscan_api_key(&self) -> Option<String> {
self.etherscan_api_key_name().and_then(|name| std::env::var(name).ok())
}
}
#[cfg(test)]
mod tests {
use super::*;
use strum::IntoEnumIterator;
#[test]
fn default() {
assert_eq!(serde_json::to_string(&Chain::default()).unwrap(), "\"mainnet\"");
}
#[test]
fn enum_iter() {
assert_eq!(Chain::COUNT, Chain::iter().size_hint().0);
}
#[test]
fn roundtrip_string() {
for chain in Chain::iter() {
let chain_string = chain.to_string();
assert_eq!(chain_string, format!("{chain}"));
assert_eq!(chain_string.as_str(), chain.as_ref());
assert_eq!(serde_json::to_string(&chain).unwrap(), format!("\"{chain_string}\""));
assert_eq!(chain_string.parse::<Chain>().unwrap(), chain);
}
}
#[test]
fn roundtrip_serde() {
for chain in Chain::iter() {
let chain_string = serde_json::to_string(&chain).unwrap();
let chain_string = chain_string.replace('-', "_");
assert_eq!(serde_json::from_str::<'_, Chain>(&chain_string).unwrap(), chain);
}
}
#[test]
fn aliases() {
use Chain::*;
// kebab-case
const ALIASES: &[(Chain, &[&str])] = &[
(Mainnet, &["ethlive"]),
(BinanceSmartChain, &["bsc", "binance-smart-chain"]),
(BinanceSmartChainTestnet, &["bsc-testnet", "binance-smart-chain-testnet"]),
(XDai, &["xdai", "gnosis", "gnosis-chain"]),
(PolygonMumbai, &["mumbai"]),
(AnvilHardhat, &["anvil", "hardhat"]),
(AvalancheFuji, &["fuji"]),
];
for &(chain, aliases) in ALIASES {
for &alias in aliases {
assert_eq!(alias.parse::<Chain>().unwrap(), chain);
let s = alias.to_string().replace('-', "_");
assert_eq!(serde_json::from_str::<Chain>(&format!("\"{s}\"")).unwrap(), chain);
}
}
}
#[test]
fn serde_to_string_match() {
for chain in Chain::iter() {
let chain_serde = serde_json::to_string(&chain).unwrap();
let chain_string = format!("\"{}\"", chain.to_string());
assert_eq!(chain_serde, chain_string);
}
}
}