alloy_chains/
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
use crate::NamedChain;
use core::{cmp::Ordering, fmt, str::FromStr, time::Duration};

#[allow(unused_imports)]
use alloc::string::String;

#[cfg(feature = "arbitrary")]
use proptest::{
    sample::Selector,
    strategy::{Map, TupleUnion, WA},
};
#[cfg(feature = "arbitrary")]
use strum::{EnumCount, IntoEnumIterator};

/// Either a known [`NamedChain`] or a EIP-155 chain ID.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Chain(ChainKind);

/// The kind of chain. Returned by [`Chain::kind`]. Prefer using [`Chain`] instead.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ChainKind {
    /// Known chain.
    Named(NamedChain),
    /// EIP-155 chain ID.
    Id(u64),
}

impl fmt::Debug for Chain {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Chain::")?;
        self.kind().fmt(f)
    }
}

impl Default for Chain {
    #[inline]
    fn default() -> Self {
        Self::from_named(NamedChain::default())
    }
}

impl From<NamedChain> for Chain {
    #[inline]
    fn from(id: NamedChain) -> Self {
        Self::from_named(id)
    }
}

impl From<u64> for Chain {
    #[inline]
    fn from(id: u64) -> Self {
        Self::from_id(id)
    }
}

impl From<Chain> for u64 {
    #[inline]
    fn from(chain: Chain) -> Self {
        chain.id()
    }
}

impl TryFrom<Chain> for NamedChain {
    type Error = <NamedChain as TryFrom<u64>>::Error;

    #[inline]
    fn try_from(chain: Chain) -> Result<Self, Self::Error> {
        match *chain.kind() {
            ChainKind::Named(chain) => Ok(chain),
            ChainKind::Id(id) => id.try_into(),
        }
    }
}

impl FromStr for Chain {
    type Err = core::num::ParseIntError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Ok(chain) = NamedChain::from_str(s) {
            Ok(Self::from_named(chain))
        } else {
            s.parse::<u64>().map(Self::from_id)
        }
    }
}

impl fmt::Display for Chain {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind() {
            ChainKind::Named(chain) => chain.fmt(f),
            ChainKind::Id(id) => id.fmt(f),
        }
    }
}

impl PartialEq<u64> for Chain {
    #[inline]
    fn eq(&self, other: &u64) -> bool {
        self.id().eq(other)
    }
}

impl PartialOrd<u64> for Chain {
    #[inline]
    fn partial_cmp(&self, other: &u64) -> Option<Ordering> {
        self.id().partial_cmp(other)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Chain {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self.kind() {
            ChainKind::Named(chain) => chain.serialize(serializer),
            ChainKind::Id(id) => id.serialize(serializer),
        }
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Chain {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct ChainVisitor;

        impl serde::de::Visitor<'_> for ChainVisitor {
            type Value = Chain;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("chain name or ID")
            }

            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<Self::Value, E> {
                if v.is_negative() {
                    Err(serde::de::Error::invalid_value(serde::de::Unexpected::Signed(v), &self))
                } else {
                    Ok(Chain::from_id(v as u64))
                }
            }

            fn visit_u64<E: serde::de::Error>(self, value: u64) -> Result<Self::Value, E> {
                Ok(Chain::from_id(value))
            }

            fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> {
                value.parse().map_err(serde::de::Error::custom)
            }
        }

        deserializer.deserialize_any(ChainVisitor)
    }
}

#[cfg(feature = "rlp")]
impl alloy_rlp::Encodable for Chain {
    #[inline]
    fn encode(&self, out: &mut dyn alloy_rlp::BufMut) {
        self.id().encode(out)
    }

    #[inline]
    fn length(&self) -> usize {
        self.id().length()
    }
}

#[cfg(feature = "rlp")]
impl alloy_rlp::Decodable for Chain {
    #[inline]
    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
        u64::decode(buf).map(Self::from)
    }
}

#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for Chain {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        if u.ratio(1, 2)? {
            let chain = u.int_in_range(0..=(NamedChain::COUNT - 1))?;

            return Ok(Self::from_named(NamedChain::iter().nth(chain).expect("in range")));
        }

        Ok(Self::from_id(u64::arbitrary(u)?))
    }
}

#[cfg(feature = "arbitrary")]
impl proptest::arbitrary::Arbitrary for Chain {
    type Parameters = ();
    type Strategy = TupleUnion<(
        WA<Map<proptest::sample::SelectorStrategy, fn(proptest::sample::Selector) -> Chain>>,
        WA<Map<proptest::num::u64::Any, fn(u64) -> Chain>>,
    )>;

    fn arbitrary_with((): ()) -> Self::Strategy {
        use proptest::prelude::*;
        prop_oneof![
            any::<Selector>().prop_map(move |sel| Self::from_named(sel.select(NamedChain::iter()))),
            any::<u64>().prop_map(Self::from_id),
        ]
    }
}

impl Chain {
    #[allow(non_snake_case)]
    #[doc(hidden)]
    #[deprecated(since = "0.1.0", note = "use `Self::from_named()` instead")]
    #[inline]
    pub const fn Named(named: NamedChain) -> Self {
        Self::from_named(named)
    }

    #[allow(non_snake_case)]
    #[doc(hidden)]
    #[deprecated(since = "0.1.0", note = "use `Self::from_id()` instead")]
    #[inline]
    pub const fn Id(id: u64) -> Self {
        Self::from_id_unchecked(id)
    }

    /// Creates a new [`Chain`] by wrapping a [`NamedChain`].
    #[inline]
    pub const fn from_named(named: NamedChain) -> Self {
        Self(ChainKind::Named(named))
    }

    /// Creates a new [`Chain`] by wrapping a [`NamedChain`].
    #[inline]
    pub fn from_id(id: u64) -> Self {
        if let Ok(named) = NamedChain::try_from(id) {
            Self::from_named(named)
        } else {
            Self::from_id_unchecked(id)
        }
    }

    /// Creates a new [`Chain`] from the given ID, without checking if an associated [`NamedChain`]
    /// exists.
    ///
    /// This is discouraged, as other methods assume that the chain ID is not known, but it is not
    /// unsafe.
    #[inline]
    pub const fn from_id_unchecked(id: u64) -> Self {
        Self(ChainKind::Id(id))
    }

    /// Returns the mainnet chain.
    #[inline]
    pub const fn mainnet() -> Self {
        Self::from_named(NamedChain::Mainnet)
    }

    /// Returns the goerli chain.
    #[inline]
    pub const fn goerli() -> Self {
        Self::from_named(NamedChain::Goerli)
    }

    /// Returns the holesky chain.
    #[inline]
    pub const fn holesky() -> Self {
        Self::from_named(NamedChain::Holesky)
    }

    /// Returns the sepolia chain.
    #[inline]
    pub const fn sepolia() -> Self {
        Self::from_named(NamedChain::Sepolia)
    }

    /// Returns the optimism mainnet chain.
    #[inline]
    pub const fn optimism_mainnet() -> Self {
        Self::from_named(NamedChain::Optimism)
    }

    /// Returns the optimism goerli chain.
    #[inline]
    pub const fn optimism_goerli() -> Self {
        Self::from_named(NamedChain::OptimismGoerli)
    }

    /// Returns the optimism sepolia chain.
    #[inline]
    pub const fn optimism_sepolia() -> Self {
        Self::from_named(NamedChain::OptimismSepolia)
    }

    /// Returns the base mainnet chain.
    #[inline]
    pub const fn base_mainnet() -> Self {
        Self::from_named(NamedChain::Base)
    }

    /// Returns the base goerli chain.
    #[inline]
    pub const fn base_goerli() -> Self {
        Self::from_named(NamedChain::BaseGoerli)
    }

    /// Returns the base sepolia chain.
    #[inline]
    pub const fn base_sepolia() -> Self {
        Self::from_named(NamedChain::BaseSepolia)
    }

    /// Returns the syndr l3 mainnet chain.
    #[inline]
    pub const fn syndr() -> Self {
        Self::from_named(NamedChain::Syndr)
    }

    /// Returns the syndr sepolia chain.
    #[inline]
    pub const fn syndr_sepolia() -> Self {
        Self::from_named(NamedChain::SyndrSepolia)
    }

    /// Returns the fraxtal mainnet chain.
    #[inline]
    pub const fn fraxtal() -> Self {
        Self::from_named(NamedChain::Fraxtal)
    }

    /// Returns the fraxtal testnet chain.
    #[inline]
    pub const fn fraxtal_testnet() -> Self {
        Self::from_named(NamedChain::FraxtalTestnet)
    }

    /// Returns the blast chain.
    #[inline]
    pub const fn blast() -> Self {
        Self::from_named(NamedChain::Blast)
    }

    /// Returns the blast sepolia chain.
    #[inline]
    pub const fn blast_sepolia() -> Self {
        Self::from_named(NamedChain::BlastSepolia)
    }

    /// Returns the linea mainnet chain.
    #[inline]
    pub const fn linea() -> Self {
        Self::from_named(NamedChain::Linea)
    }

    /// Returns the linea goerli chain.
    #[inline]
    pub const fn linea_goerli() -> Self {
        Self::from_named(NamedChain::LineaGoerli)
    }

    /// Returns the linea sepolia chain.
    #[inline]
    pub const fn linea_sepolia() -> Self {
        Self::from_named(NamedChain::LineaSepolia)
    }

    /// Returns the mode mainnet chain.
    #[inline]
    pub const fn mode() -> Self {
        Self::from_named(NamedChain::Mode)
    }

    /// Returns the mode sepolia chain.
    #[inline]
    pub const fn mode_sepolia() -> Self {
        Self::from_named(NamedChain::ModeSepolia)
    }

    /// Returns the elastos mainnet chain.
    #[inline]
    pub const fn elastos() -> Self {
        Self::from_named(NamedChain::Elastos)
    }

    /// Returns the degen l3 mainnet chain.
    #[inline]
    pub const fn degen() -> Self {
        Self::from_named(NamedChain::Degen)
    }

    /// Returns the dev chain.
    #[inline]
    pub const fn dev() -> Self {
        Self::from_named(NamedChain::Dev)
    }

    /// Returns the bsc mainnet chain.
    #[inline]
    pub const fn bsc_mainnet() -> Self {
        Self::from_named(NamedChain::BinanceSmartChain)
    }

    /// Returns the bsc testnet chain.
    #[inline]
    pub const fn bsc_testnet() -> Self {
        Self::from_named(NamedChain::BinanceSmartChainTestnet)
    }

    /// Returns the opbnb mainnet chain.
    #[inline]
    pub const fn opbnb_mainnet() -> Self {
        Self::from_named(NamedChain::OpBNBMainnet)
    }

    /// Returns the opbnb testnet chain.
    #[inline]
    pub const fn opbnb_testnet() -> Self {
        Self::from_named(NamedChain::OpBNBTestnet)
    }

    /// Returns the ronin mainnet chain.
    #[inline]
    pub const fn ronin() -> Self {
        Self::from_named(NamedChain::Ronin)
    }

    /// Returns the taiko mainnet chain.
    #[inline]
    pub const fn taiko() -> Self {
        Self::from_named(NamedChain::Taiko)
    }

    /// Returns the taiko hekla chain.
    #[inline]
    pub const fn taiko_hekla() -> Self {
        Self::from_named(NamedChain::TaikoHekla)
    }

    /// Returns the shimmer testnet chain.
    #[inline]
    pub const fn shimmer() -> Self {
        Self::from_named(NamedChain::Shimmer)
    }

    /// Returns the flare mainnet chain.
    #[inline]
    pub const fn flare() -> Self {
        Self::from_named(NamedChain::Flare)
    }

    /// Returns the flare testnet chain.
    #[inline]
    pub const fn flare_coston2() -> Self {
        Self::from_named(NamedChain::FlareCoston2)
    }

    /// Returns the darwinia mainnet chain.
    #[inline]
    pub const fn darwinia() -> Self {
        Self::from_named(NamedChain::Darwinia)
    }

    /// Returns the crab mainnet chain.
    #[inline]
    pub const fn crab() -> Self {
        Self::from_named(NamedChain::Crab)
    }

    /// Returns the koi testnet chain.
    #[inline]
    pub const fn koi() -> Self {
        Self::from_named(NamedChain::Koi)
    }

    /// Returns the Immutable zkEVM mainnet chain.
    #[inline]
    pub const fn immutable() -> Self {
        Self::from_named(NamedChain::Immutable)
    }

    /// Returns the Immutable zkEVM testnet chain.
    #[inline]
    pub const fn immutable_testnet() -> Self {
        Self::from_named(NamedChain::ImmutableTestnet)
    }

    /// Returns the koi testnet chain.
    #[inline]
    pub const fn ink_sepolia() -> Self {
        Self::from_named(NamedChain::InkSepolia)
    }

    /// Returns the kind of this chain.
    #[inline]
    pub const fn kind(&self) -> &ChainKind {
        &self.0
    }

    /// Returns the kind of this chain.
    #[inline]
    pub const fn into_kind(self) -> ChainKind {
        self.0
    }

    /// Returns `true` if this chain is Ethereum or an Ethereum testnet.
    #[inline]
    pub const fn is_ethereum(&self) -> bool {
        matches!(self.named(), Some(named) if named.is_ethereum())
    }

    /// Returns true if the chain contains Optimism configuration.
    #[inline]
    pub const fn is_optimism(self) -> bool {
        matches!(self.named(), Some(named) if named.is_optimism())
    }

    /// Returns true if the chain contains Arbitrum configuration.
    #[inline]
    pub const fn is_arbitrum(self) -> bool {
        matches!(self.named(), Some(named) if named.is_arbitrum())
    }

    /// Attempts to convert the chain into a named chain.
    #[inline]
    pub const fn named(self) -> Option<NamedChain> {
        match *self.kind() {
            ChainKind::Named(named) => Some(named),
            ChainKind::Id(_) => None,
        }
    }

    /// The ID of the chain.
    #[inline]
    pub const fn id(self) -> u64 {
        match *self.kind() {
            ChainKind::Named(named) => named as u64,
            ChainKind::Id(id) => id,
        }
    }
}

/// Methods delegated to `NamedChain`. Note that [`ChainKind::Id`] won't be converted because it was
/// already done at construction.
impl Chain {
    /// Returns the chain's average blocktime, if applicable.
    ///
    /// See [`NamedChain::average_blocktime_hint`] for more info.
    pub const fn average_blocktime_hint(self) -> Option<Duration> {
        match self.kind() {
            ChainKind::Named(named) => named.average_blocktime_hint(),
            ChainKind::Id(_) => None,
        }
    }

    /// Returns whether the chain implements EIP-1559 (with the type 2 EIP-2718 transaction type).
    ///
    /// See [`NamedChain::is_legacy`] for more info.
    pub const fn is_legacy(self) -> bool {
        match self.kind() {
            ChainKind::Named(named) => named.is_legacy(),
            ChainKind::Id(_) => false,
        }
    }

    /// Returns whether the chain supports the [Shanghai hardfork][ref].
    ///
    /// See [`NamedChain::supports_shanghai`] for more info.
    ///
    /// [ref]: https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/shanghai.md
    pub const fn supports_shanghai(self) -> bool {
        match self.kind() {
            ChainKind::Named(named) => named.supports_shanghai(),
            ChainKind::Id(_) => false,
        }
    }

    #[doc(hidden)]
    #[deprecated(since = "0.1.3", note = "use `supports_shanghai` instead")]
    pub const fn supports_push0(self) -> bool {
        self.supports_shanghai()
    }

    /// Returns the chain's blockchain explorer and its API (Etherscan and Etherscan-like) URLs.
    ///
    /// See [`NamedChain::etherscan_urls`] for more info.
    pub const fn etherscan_urls(self) -> Option<(&'static str, &'static str)> {
        match self.kind() {
            ChainKind::Named(named) => named.etherscan_urls(),
            ChainKind::Id(_) => None,
        }
    }

    /// Returns the chain's blockchain explorer's API key environment variable's default name.
    ///
    /// See [`NamedChain::etherscan_api_key_name`] for more info.
    pub const fn etherscan_api_key_name(self) -> Option<&'static str> {
        match self.kind() {
            ChainKind::Named(named) => named.etherscan_api_key_name(),
            ChainKind::Id(_) => None,
        }
    }

    /// Returns the chain's blockchain explorer's API key, from the environment variable with the
    /// name specified in [`etherscan_api_key_name`](NamedChain::etherscan_api_key_name).
    ///
    /// See [`NamedChain::etherscan_api_key`] for more info.
    #[cfg(feature = "std")]
    pub fn etherscan_api_key(self) -> Option<String> {
        match self.kind() {
            ChainKind::Named(named) => named.etherscan_api_key(),
            ChainKind::Id(_) => None,
        }
    }

    /// Returns the address of the public DNS node list for the given chain.
    ///
    /// See [`NamedChain::public_dns_network_protocol`] for more info.
    pub fn public_dns_network_protocol(self) -> Option<String> {
        match self.kind() {
            ChainKind::Named(named) => named.public_dns_network_protocol(),
            ChainKind::Id(_) => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[allow(unused_imports)]
    use alloc::string::ToString;

    #[test]
    fn test_id() {
        assert_eq!(Chain::from_id(1234).id(), 1234);
    }

    #[test]
    fn test_named_id() {
        assert_eq!(Chain::from_named(NamedChain::Goerli).id(), 5);
    }

    #[test]
    fn test_display_named_chain() {
        assert_eq!(Chain::from_named(NamedChain::Mainnet).to_string(), "mainnet");
    }

    #[test]
    fn test_display_id_chain() {
        assert_eq!(Chain::from_id(1234).to_string(), "1234");
    }

    #[test]
    fn test_from_str_named_chain() {
        let result = Chain::from_str("mainnet");
        let expected = Chain::from_named(NamedChain::Mainnet);
        assert_eq!(result.unwrap(), expected);
    }

    #[test]
    fn test_from_str_named_chain_error() {
        let result = Chain::from_str("chain");
        assert!(result.is_err());
    }

    #[test]
    fn test_from_str_id_chain() {
        let result = Chain::from_str("1234");
        let expected = Chain::from_id(1234);
        assert_eq!(result.unwrap(), expected);
    }

    #[test]
    fn test_default() {
        let default = Chain::default();
        let expected = Chain::from_named(NamedChain::Mainnet);
        assert_eq!(default, expected);
    }

    #[cfg(feature = "rlp")]
    #[test]
    fn test_id_chain_encodable_length() {
        use alloy_rlp::Encodable;

        let chain = Chain::from_id(1234);
        assert_eq!(chain.length(), 3);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serde() {
        let chains = r#"["mainnet",1,80001,80002,"mumbai"]"#;
        let re = r#"["mainnet","mainnet","mumbai","amoy","mumbai"]"#;
        let expected = [
            Chain::mainnet(),
            Chain::mainnet(),
            Chain::from_named(NamedChain::PolygonMumbai),
            Chain::from_id(80002),
            Chain::from_named(NamedChain::PolygonMumbai),
        ];
        assert_eq!(serde_json::from_str::<alloc::vec::Vec<Chain>>(chains).unwrap(), expected);
        assert_eq!(serde_json::to_string(&expected).unwrap(), re);
    }
}