Skip to main content

nautilus_model/defi/
chain.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Blockchain network identities and optional connection endpoints.
17//!
18//! Presets use EIP-155 chain IDs. A network without a verified HyperSync endpoint has no default
19//! HyperSync URL; callers can configure one without changing the network identity.
20
21use std::{fmt::Display, str::FromStr, sync::Arc};
22
23use serde::{Deserialize, Serialize};
24use strum::{Display, EnumIter, EnumString};
25
26use crate::types::Currency;
27
28/// Represents different blockchain networks.
29#[derive(
30    Debug,
31    Clone,
32    Copy,
33    Hash,
34    PartialOrd,
35    PartialEq,
36    Ord,
37    Eq,
38    Display,
39    EnumIter,
40    EnumString,
41    Serialize,
42    Deserialize,
43)]
44#[non_exhaustive]
45#[strum(ascii_case_insensitive)]
46#[cfg_attr(
47    feature = "python",
48    pyo3::pyclass(
49        frozen,
50        eq,
51        eq_int,
52        module = "nautilus_trader.model",
53        from_py_object,
54        rename_all = "SCREAMING_SNAKE_CASE",
55    )
56)]
57#[cfg_attr(feature = "python", pyo3_stub_gen::derive::gen_stub_pyclass_enum)]
58pub enum Blockchain {
59    Abstract,
60    Arbitrum,
61    ArbitrumNova,
62    ArbitrumSepolia,
63    Aurora,
64    Avalanche,
65    Base,
66    BaseSepolia,
67    Berachain,
68    BerachainBartio,
69    Blast,
70    BlastSepolia,
71    Boba,
72    Bsc,
73    BscTestnet,
74    Celo,
75    Chiliz,
76    CitreaTestnet,
77    Curtis,
78    Cyber,
79    Darwinia,
80    Ethereum,
81    Fantom,
82    Flare,
83    Fraxtal,
84    Fuji,
85    GaladrielDevnet,
86    Gnosis,
87    GnosisChiado,
88    HarmonyShard0,
89    Holesky,
90    Hyperliquid,
91    Ink,
92    Kroma,
93    Linea,
94    Lisk,
95    Lukso,
96    LuksoTestnet,
97    Manta,
98    Mantle,
99    MegaethTestnet,
100    Merlin,
101    Metall2,
102    Metis,
103    Mode,
104    MonadTestnet,
105    MoonbaseAlpha,
106    Moonbeam,
107    Morph,
108    MorphHolesky,
109    Opbnb,
110    Optimism,
111    OptimismSepolia,
112    Polygon,
113    PolygonAmoy,
114    PolygonZkEvm,
115    Rootstock,
116    Saakuru,
117    Scroll,
118    Sepolia,
119    ShimmerEvm,
120    Soneium,
121    Sophon,
122    SophonTestnet,
123    Superseed,
124    Unichain,
125    UnichainSepolia,
126    Xdc,
127    XdcTestnet,
128    Zeta,
129    Zircuit,
130    ZKsync,
131    Zora,
132}
133
134/// Defines a blockchain with its unique identifiers and connection details for network interaction.
135#[cfg_attr(
136    feature = "python",
137    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
138)]
139#[cfg_attr(feature = "python", pyo3_stub_gen::derive::gen_stub_pyclass)]
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub struct Chain {
142    /// The blockchain network type.
143    pub name: Blockchain,
144    /// The unique identifier for this blockchain.
145    pub chain_id: u32,
146    /// HyperSync endpoint, if one is configured for this network.
147    pub hypersync_url: Option<String>,
148    /// URL endpoint for the default RPC connection.
149    pub rpc_url: Option<String>,
150    /// The number of decimals for the native currency.
151    pub native_currency_decimals: u8,
152}
153
154/// A thread-safe shared pointer to a `Chain`, enabling efficient reuse across multiple components.
155pub type SharedChain = Arc<Chain>;
156
157impl Chain {
158    /// Creates a [`Chain`] with no RPC or HyperSync endpoint configured.
159    #[must_use]
160    pub fn new(name: Blockchain, chain_id: u32) -> Self {
161        Self {
162            chain_id,
163            name,
164            hypersync_url: None,
165            rpc_url: None,
166            native_currency_decimals: 18, // Default to 18 for EVM chains
167        }
168    }
169
170    /// Sets the RPC URL endpoint.
171    pub fn set_rpc_url(&mut self, rpc: String) {
172        self.rpc_url = Some(rpc);
173    }
174
175    /// Returns the native currency for this blockchain.
176    ///
177    /// Native currencies are the base tokens used to pay gas fees on each chain.
178    ///
179    /// # Panics
180    ///
181    /// Panics if the native currency has not been defined for this blockchain.
182    #[must_use]
183    pub fn native_currency(&self) -> Currency {
184        use crate::enums::CurrencyType;
185
186        let (code, name) = match self.name {
187            // Ethereum and Ethereum testnets
188            Blockchain::Ethereum | Blockchain::Sepolia | Blockchain::Holesky => ("ETH", "Ethereum"),
189
190            // Ethereum L2s that use ETH
191            Blockchain::Arbitrum
192            | Blockchain::ArbitrumNova
193            | Blockchain::ArbitrumSepolia
194            | Blockchain::Base
195            | Blockchain::BaseSepolia
196            | Blockchain::Optimism
197            | Blockchain::OptimismSepolia
198            | Blockchain::Blast
199            | Blockchain::BlastSepolia
200            | Blockchain::Scroll
201            | Blockchain::Linea => ("ETH", "Ethereum"),
202            Blockchain::Polygon | Blockchain::PolygonAmoy => ("POL", "Polygon"),
203            Blockchain::Avalanche | Blockchain::Fuji => ("AVAX", "Avalanche"),
204            Blockchain::Bsc | Blockchain::BscTestnet => ("BNB", "Binance Coin"),
205            _ => panic!("Native currency not specified for chain {}", self.name),
206        };
207
208        Currency::new(
209            code,
210            self.native_currency_decimals,
211            0,
212            name,
213            CurrencyType::Crypto,
214        )
215    }
216
217    /// Returns a reference to the `Chain` corresponding to the given `chain_id`, or `None` if it is not found.
218    #[must_use]
219    pub fn from_chain_id(chain_id: u32) -> Option<&'static Self> {
220        match chain_id {
221            2741 => Some(&chains::ABSTRACT),
222            42161 => Some(&chains::ARBITRUM),
223            42170 => Some(&chains::ARBITRUM_NOVA),
224            421_614 => Some(&chains::ARBITRUM_SEPOLIA),
225            1_313_161_554 => Some(&chains::AURORA),
226            43114 => Some(&chains::AVALANCHE),
227            8453 => Some(&chains::BASE),
228            84532 => Some(&chains::BASE_SEPOLIA),
229            80094 => Some(&chains::BERACHAIN),
230            80084 => Some(&chains::BERACHAIN_BARTIO),
231            81457 => Some(&chains::BLAST),
232            168_587_773 => Some(&chains::BLAST_SEPOLIA),
233            288 => Some(&chains::BOBA),
234            56 => Some(&chains::BSC),
235            97 => Some(&chains::BSC_TESTNET),
236            42220 => Some(&chains::CELO),
237            88888 => Some(&chains::CHILIZ),
238            5115 => Some(&chains::CITREA_TESTNET),
239            33111 => Some(&chains::CURTIS),
240            7560 => Some(&chains::CYBER),
241            46 => Some(&chains::DARWINIA),
242            1 => Some(&chains::ETHEREUM),
243            250 => Some(&chains::FANTOM),
244            14 => Some(&chains::FLARE),
245            252 => Some(&chains::FRAXTAL),
246            43113 => Some(&chains::FUJI),
247            696_969 => Some(&chains::GALADRIEL_DEVNET),
248            100 => Some(&chains::GNOSIS),
249            10200 => Some(&chains::GNOSIS_CHIADO),
250            1_666_600_000 => Some(&chains::HARMONY_SHARD_0),
251            17000 => Some(&chains::HOLESKY),
252            999 => Some(&chains::HYPERLIQUID),
253            57073 => Some(&chains::INK),
254            255 => Some(&chains::KROMA),
255            59144 => Some(&chains::LINEA),
256            1135 => Some(&chains::LISK),
257            42 => Some(&chains::LUKSO),
258            4201 => Some(&chains::LUKSO_TESTNET),
259            169 => Some(&chains::MANTA),
260            5000 => Some(&chains::MANTLE),
261            6343 => Some(&chains::MEGAETH_TESTNET),
262            4200 => Some(&chains::MERLIN),
263            1750 => Some(&chains::METALL2),
264            1088 => Some(&chains::METIS),
265            34443 => Some(&chains::MODE),
266            10143 => Some(&chains::MONAD_TESTNET),
267            1287 => Some(&chains::MOONBASE_ALPHA),
268            1284 => Some(&chains::MOONBEAM),
269            2818 => Some(&chains::MORPH),
270            2810 => Some(&chains::MORPH_HOLESKY),
271            204 => Some(&chains::OPBNB),
272            10 => Some(&chains::OPTIMISM),
273            11_155_420 => Some(&chains::OPTIMISM_SEPOLIA),
274            137 => Some(&chains::POLYGON),
275            80002 => Some(&chains::POLYGON_AMOY),
276            1101 => Some(&chains::POLYGON_ZKEVM),
277            30 => Some(&chains::ROOTSTOCK),
278            7_225_878 => Some(&chains::SAAKURU),
279            534_352 => Some(&chains::SCROLL),
280            11_155_111 => Some(&chains::SEPOLIA),
281            148 => Some(&chains::SHIMMER_EVM),
282            1868 => Some(&chains::SONEIUM),
283            50104 => Some(&chains::SOPHON),
284            531_050_104 => Some(&chains::SOPHON_TESTNET),
285            5330 => Some(&chains::SUPERSEDE),
286            130 => Some(&chains::UNICHAIN),
287            1301 => Some(&chains::UNICHAIN_SEPOLIA),
288            50 => Some(&chains::XDC),
289            51 => Some(&chains::XDC_TESTNET),
290            7000 => Some(&chains::ZETA),
291            48900 => Some(&chains::ZIRCUIT),
292            324 => Some(&chains::ZKSYNC),
293            7_777_777 => Some(&chains::ZORA),
294            _ => None,
295        }
296    }
297
298    /// Returns a reference to the `Chain` corresponding to the given chain name, or `None` if it is not found.
299    ///
300    /// String matching is case-insensitive.
301    #[must_use]
302    pub fn from_chain_name(chain_name: &str) -> Option<&'static Self> {
303        let blockchain = Blockchain::from_str(chain_name).ok()?;
304
305        match blockchain {
306            Blockchain::Abstract => Some(&chains::ABSTRACT),
307            Blockchain::Arbitrum => Some(&chains::ARBITRUM),
308            Blockchain::ArbitrumNova => Some(&chains::ARBITRUM_NOVA),
309            Blockchain::ArbitrumSepolia => Some(&chains::ARBITRUM_SEPOLIA),
310            Blockchain::Aurora => Some(&chains::AURORA),
311            Blockchain::Avalanche => Some(&chains::AVALANCHE),
312            Blockchain::Base => Some(&chains::BASE),
313            Blockchain::BaseSepolia => Some(&chains::BASE_SEPOLIA),
314            Blockchain::Berachain => Some(&chains::BERACHAIN),
315            Blockchain::BerachainBartio => Some(&chains::BERACHAIN_BARTIO),
316            Blockchain::Blast => Some(&chains::BLAST),
317            Blockchain::BlastSepolia => Some(&chains::BLAST_SEPOLIA),
318            Blockchain::Boba => Some(&chains::BOBA),
319            Blockchain::Bsc => Some(&chains::BSC),
320            Blockchain::BscTestnet => Some(&chains::BSC_TESTNET),
321            Blockchain::Celo => Some(&chains::CELO),
322            Blockchain::Chiliz => Some(&chains::CHILIZ),
323            Blockchain::CitreaTestnet => Some(&chains::CITREA_TESTNET),
324            Blockchain::Curtis => Some(&chains::CURTIS),
325            Blockchain::Cyber => Some(&chains::CYBER),
326            Blockchain::Darwinia => Some(&chains::DARWINIA),
327            Blockchain::Ethereum => Some(&chains::ETHEREUM),
328            Blockchain::Fantom => Some(&chains::FANTOM),
329            Blockchain::Flare => Some(&chains::FLARE),
330            Blockchain::Fraxtal => Some(&chains::FRAXTAL),
331            Blockchain::Fuji => Some(&chains::FUJI),
332            Blockchain::GaladrielDevnet => Some(&chains::GALADRIEL_DEVNET),
333            Blockchain::Gnosis => Some(&chains::GNOSIS),
334            Blockchain::GnosisChiado => Some(&chains::GNOSIS_CHIADO),
335            Blockchain::HarmonyShard0 => Some(&chains::HARMONY_SHARD_0),
336            Blockchain::Holesky => Some(&chains::HOLESKY),
337            Blockchain::Hyperliquid => Some(&chains::HYPERLIQUID),
338            Blockchain::Ink => Some(&chains::INK),
339            Blockchain::Kroma => Some(&chains::KROMA),
340            Blockchain::Linea => Some(&chains::LINEA),
341            Blockchain::Lisk => Some(&chains::LISK),
342            Blockchain::Lukso => Some(&chains::LUKSO),
343            Blockchain::LuksoTestnet => Some(&chains::LUKSO_TESTNET),
344            Blockchain::Manta => Some(&chains::MANTA),
345            Blockchain::Mantle => Some(&chains::MANTLE),
346            Blockchain::MegaethTestnet => Some(&chains::MEGAETH_TESTNET),
347            Blockchain::Merlin => Some(&chains::MERLIN),
348            Blockchain::Metall2 => Some(&chains::METALL2),
349            Blockchain::Metis => Some(&chains::METIS),
350            Blockchain::Mode => Some(&chains::MODE),
351            Blockchain::MonadTestnet => Some(&chains::MONAD_TESTNET),
352            Blockchain::MoonbaseAlpha => Some(&chains::MOONBASE_ALPHA),
353            Blockchain::Moonbeam => Some(&chains::MOONBEAM),
354            Blockchain::Morph => Some(&chains::MORPH),
355            Blockchain::MorphHolesky => Some(&chains::MORPH_HOLESKY),
356            Blockchain::Opbnb => Some(&chains::OPBNB),
357            Blockchain::Optimism => Some(&chains::OPTIMISM),
358            Blockchain::OptimismSepolia => Some(&chains::OPTIMISM_SEPOLIA),
359            Blockchain::Polygon => Some(&chains::POLYGON),
360            Blockchain::PolygonAmoy => Some(&chains::POLYGON_AMOY),
361            Blockchain::PolygonZkEvm => Some(&chains::POLYGON_ZKEVM),
362            Blockchain::Rootstock => Some(&chains::ROOTSTOCK),
363            Blockchain::Saakuru => Some(&chains::SAAKURU),
364            Blockchain::Scroll => Some(&chains::SCROLL),
365            Blockchain::Sepolia => Some(&chains::SEPOLIA),
366            Blockchain::ShimmerEvm => Some(&chains::SHIMMER_EVM),
367            Blockchain::Soneium => Some(&chains::SONEIUM),
368            Blockchain::Sophon => Some(&chains::SOPHON),
369            Blockchain::SophonTestnet => Some(&chains::SOPHON_TESTNET),
370            Blockchain::Superseed => Some(&chains::SUPERSEDE),
371            Blockchain::Unichain => Some(&chains::UNICHAIN),
372            Blockchain::UnichainSepolia => Some(&chains::UNICHAIN_SEPOLIA),
373            Blockchain::Xdc => Some(&chains::XDC),
374            Blockchain::XdcTestnet => Some(&chains::XDC_TESTNET),
375            Blockchain::Zeta => Some(&chains::ZETA),
376            Blockchain::Zircuit => Some(&chains::ZIRCUIT),
377            Blockchain::ZKsync => Some(&chains::ZKSYNC),
378            Blockchain::Zora => Some(&chains::ZORA),
379        }
380    }
381}
382
383impl Display for Chain {
384    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
385        write!(f, "Chain(name={}, id={})", self.name, self.chain_id)
386    }
387}
388
389// Define a module to contain all the chain definitions.
390pub mod chains {
391    use std::sync::LazyLock;
392
393    use crate::defi::chain::{Blockchain, Chain};
394
395    pub static ABSTRACT: LazyLock<Chain> =
396        LazyLock::new(|| hypersync_chain(Blockchain::Abstract, 2741));
397    pub static ARBITRUM: LazyLock<Chain> =
398        LazyLock::new(|| hypersync_chain(Blockchain::Arbitrum, 42161));
399    pub static ARBITRUM_NOVA: LazyLock<Chain> =
400        LazyLock::new(|| hypersync_chain(Blockchain::ArbitrumNova, 42170));
401    pub static ARBITRUM_SEPOLIA: LazyLock<Chain> =
402        LazyLock::new(|| hypersync_chain(Blockchain::ArbitrumSepolia, 421_614));
403    pub static AURORA: LazyLock<Chain> =
404        LazyLock::new(|| hypersync_chain(Blockchain::Aurora, 1_313_161_554));
405    pub static AVALANCHE: LazyLock<Chain> =
406        LazyLock::new(|| hypersync_chain(Blockchain::Avalanche, 43114));
407    pub static BASE: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Base, 8453));
408    pub static BASE_SEPOLIA: LazyLock<Chain> =
409        LazyLock::new(|| hypersync_chain(Blockchain::BaseSepolia, 84532));
410    pub static BERACHAIN: LazyLock<Chain> =
411        LazyLock::new(|| hypersync_chain(Blockchain::Berachain, 80094));
412    pub static BERACHAIN_BARTIO: LazyLock<Chain> =
413        LazyLock::new(|| Chain::new(Blockchain::BerachainBartio, 80084));
414    pub static BLAST: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Blast, 81457));
415    pub static BLAST_SEPOLIA: LazyLock<Chain> =
416        LazyLock::new(|| Chain::new(Blockchain::BlastSepolia, 168_587_773));
417    pub static BOBA: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Boba, 288));
418    pub static BSC: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Bsc, 56));
419    pub static BSC_TESTNET: LazyLock<Chain> =
420        LazyLock::new(|| hypersync_chain(Blockchain::BscTestnet, 97));
421    pub static CELO: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Celo, 42220));
422    pub static CHILIZ: LazyLock<Chain> =
423        LazyLock::new(|| hypersync_chain(Blockchain::Chiliz, 88888));
424    pub static CITREA_TESTNET: LazyLock<Chain> =
425        LazyLock::new(|| hypersync_chain(Blockchain::CitreaTestnet, 5115));
426    pub static CURTIS: LazyLock<Chain> =
427        LazyLock::new(|| hypersync_chain(Blockchain::Curtis, 33111));
428    pub static CYBER: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Cyber, 7560));
429    pub static DARWINIA: LazyLock<Chain> = LazyLock::new(|| Chain::new(Blockchain::Darwinia, 46));
430    pub static ETHEREUM: LazyLock<Chain> =
431        LazyLock::new(|| hypersync_chain(Blockchain::Ethereum, 1));
432    pub static FANTOM: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Fantom, 250));
433    pub static FLARE: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Flare, 14));
434    pub static FRAXTAL: LazyLock<Chain> =
435        LazyLock::new(|| hypersync_chain(Blockchain::Fraxtal, 252));
436    pub static FUJI: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Fuji, 43113));
437    pub static GALADRIEL_DEVNET: LazyLock<Chain> =
438        LazyLock::new(|| Chain::new(Blockchain::GaladrielDevnet, 696_969));
439    pub static GNOSIS: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Gnosis, 100));
440    pub static GNOSIS_CHIADO: LazyLock<Chain> =
441        LazyLock::new(|| hypersync_chain(Blockchain::GnosisChiado, 10200));
442    pub static HARMONY_SHARD_0: LazyLock<Chain> =
443        LazyLock::new(|| hypersync_chain(Blockchain::HarmonyShard0, 1_666_600_000));
444    pub static HOLESKY: LazyLock<Chain> = LazyLock::new(|| Chain::new(Blockchain::Holesky, 17000));
445    pub static HYPERLIQUID: LazyLock<Chain> =
446        LazyLock::new(|| hypersync_chain(Blockchain::Hyperliquid, 999));
447    pub static INK: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Ink, 57073));
448    pub static KROMA: LazyLock<Chain> = LazyLock::new(|| Chain::new(Blockchain::Kroma, 255));
449    pub static LINEA: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Linea, 59144));
450    pub static LISK: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Lisk, 1135));
451    pub static LUKSO: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Lukso, 42));
452    pub static LUKSO_TESTNET: LazyLock<Chain> =
453        LazyLock::new(|| hypersync_chain(Blockchain::LuksoTestnet, 4201));
454    pub static MANTA: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Manta, 169));
455    pub static MANTLE: LazyLock<Chain> =
456        LazyLock::new(|| hypersync_chain(Blockchain::Mantle, 5000));
457    pub static MEGAETH_TESTNET: LazyLock<Chain> =
458        LazyLock::new(|| hypersync_chain(Blockchain::MegaethTestnet, 6343));
459    pub static MERLIN: LazyLock<Chain> =
460        LazyLock::new(|| hypersync_chain(Blockchain::Merlin, 4200));
461    pub static METALL2: LazyLock<Chain> =
462        LazyLock::new(|| hypersync_chain(Blockchain::Metall2, 1750));
463    pub static METIS: LazyLock<Chain> = LazyLock::new(|| Chain::new(Blockchain::Metis, 1088));
464    pub static MODE: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Mode, 34443));
465    pub static MONAD_TESTNET: LazyLock<Chain> =
466        LazyLock::new(|| hypersync_chain(Blockchain::MonadTestnet, 10143));
467    pub static MOONBASE_ALPHA: LazyLock<Chain> =
468        LazyLock::new(|| Chain::new(Blockchain::MoonbaseAlpha, 1287));
469    pub static MOONBEAM: LazyLock<Chain> =
470        LazyLock::new(|| hypersync_chain(Blockchain::Moonbeam, 1284));
471    pub static MORPH: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Morph, 2818));
472    pub static MORPH_HOLESKY: LazyLock<Chain> =
473        LazyLock::new(|| Chain::new(Blockchain::MorphHolesky, 2810));
474    pub static OPBNB: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Opbnb, 204));
475    pub static OPTIMISM: LazyLock<Chain> =
476        LazyLock::new(|| hypersync_chain(Blockchain::Optimism, 10));
477    pub static OPTIMISM_SEPOLIA: LazyLock<Chain> =
478        LazyLock::new(|| hypersync_chain(Blockchain::OptimismSepolia, 11_155_420));
479    pub static POLYGON: LazyLock<Chain> =
480        LazyLock::new(|| hypersync_chain(Blockchain::Polygon, 137));
481    pub static POLYGON_AMOY: LazyLock<Chain> =
482        LazyLock::new(|| hypersync_chain(Blockchain::PolygonAmoy, 80002));
483    pub static POLYGON_ZKEVM: LazyLock<Chain> =
484        LazyLock::new(|| hypersync_chain(Blockchain::PolygonZkEvm, 1101));
485    pub static ROOTSTOCK: LazyLock<Chain> =
486        LazyLock::new(|| hypersync_chain(Blockchain::Rootstock, 30));
487    pub static SAAKURU: LazyLock<Chain> =
488        LazyLock::new(|| Chain::new(Blockchain::Saakuru, 7_225_878));
489    pub static SCROLL: LazyLock<Chain> =
490        LazyLock::new(|| hypersync_chain(Blockchain::Scroll, 534_352));
491    pub static SEPOLIA: LazyLock<Chain> =
492        LazyLock::new(|| hypersync_chain(Blockchain::Sepolia, 11_155_111));
493    pub static SHIMMER_EVM: LazyLock<Chain> =
494        LazyLock::new(|| hypersync_chain(Blockchain::ShimmerEvm, 148));
495    pub static SONEIUM: LazyLock<Chain> =
496        LazyLock::new(|| hypersync_chain(Blockchain::Soneium, 1868));
497    pub static SOPHON: LazyLock<Chain> =
498        LazyLock::new(|| hypersync_chain(Blockchain::Sophon, 50104));
499    pub static SOPHON_TESTNET: LazyLock<Chain> =
500        LazyLock::new(|| Chain::new(Blockchain::SophonTestnet, 531_050_104));
501    pub static SUPERSEDE: LazyLock<Chain> =
502        LazyLock::new(|| hypersync_chain(Blockchain::Superseed, 5330));
503    pub static UNICHAIN: LazyLock<Chain> =
504        LazyLock::new(|| hypersync_chain(Blockchain::Unichain, 130));
505    pub static UNICHAIN_SEPOLIA: LazyLock<Chain> =
506        LazyLock::new(|| Chain::new(Blockchain::UnichainSepolia, 1301));
507    pub static XDC: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Xdc, 50));
508    pub static XDC_TESTNET: LazyLock<Chain> =
509        LazyLock::new(|| hypersync_chain(Blockchain::XdcTestnet, 51));
510    pub static ZETA: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::Zeta, 7000));
511    pub static ZIRCUIT: LazyLock<Chain> =
512        LazyLock::new(|| hypersync_chain(Blockchain::Zircuit, 48900));
513    pub static ZKSYNC: LazyLock<Chain> = LazyLock::new(|| hypersync_chain(Blockchain::ZKsync, 324));
514    pub static ZORA: LazyLock<Chain> =
515        LazyLock::new(|| hypersync_chain(Blockchain::Zora, 7_777_777));
516
517    fn hypersync_chain(name: Blockchain, chain_id: u32) -> Chain {
518        let mut chain = Chain::new(name, chain_id);
519        chain.hypersync_url = Some(format!("https://{chain_id}.hypersync.xyz"));
520        chain
521    }
522}
523
524#[cfg(test)]
525mod tests {
526    use ahash::AHashSet;
527    use rstest::rstest;
528    use strum::IntoEnumIterator;
529
530    use super::*;
531
532    #[rstest]
533    fn test_ethereum_chain() {
534        let eth_chain = chains::ETHEREUM.clone();
535        assert_eq!(eth_chain.to_string(), "Chain(name=Ethereum, id=1)");
536        assert_eq!(eth_chain.name, Blockchain::Ethereum);
537        assert_eq!(eth_chain.chain_id, 1);
538        assert_eq!(
539            eth_chain.hypersync_url.as_deref(),
540            Some("https://1.hypersync.xyz")
541        );
542
543        // Test native currency
544        let currency = eth_chain.native_currency();
545        assert_eq!(currency.code, "ETH");
546        assert_eq!(currency.precision, 18);
547        assert_eq!(currency.name, "Ethereum");
548    }
549
550    #[rstest]
551    fn test_arbitrum_chain() {
552        let arbitrum_chain = chains::ARBITRUM.clone();
553        assert_eq!(arbitrum_chain.to_string(), "Chain(name=Arbitrum, id=42161)");
554        assert_eq!(arbitrum_chain.name, Blockchain::Arbitrum);
555        assert_eq!(arbitrum_chain.chain_id, 42161);
556        assert_eq!(
557            arbitrum_chain.hypersync_url.as_deref(),
558            Some("https://42161.hypersync.xyz")
559        );
560
561        // Test native currency (Arbitrum uses ETH)
562        let currency = arbitrum_chain.native_currency();
563        assert_eq!(currency.code, "ETH");
564        assert_eq!(currency.precision, 18);
565        assert_eq!(currency.name, "Ethereum");
566    }
567
568    #[rstest]
569    fn test_chain_constructor() {
570        let chain = Chain::new(Blockchain::Polygon, 137);
571
572        assert_eq!(chain.name, Blockchain::Polygon);
573        assert_eq!(chain.chain_id, 137);
574        assert_eq!(chain.hypersync_url, None);
575        assert!(chain.rpc_url.is_none());
576        assert_eq!(chain.native_currency_decimals, 18);
577    }
578
579    #[rstest]
580    fn test_chain_set_rpc_url() {
581        let mut chain = Chain::new(Blockchain::Ethereum, 1);
582        assert!(chain.rpc_url.is_none());
583
584        let rpc_url = "https://mainnet.infura.io/v3/YOUR-PROJECT-ID".to_string();
585        chain.set_rpc_url(rpc_url.clone());
586
587        assert_eq!(chain.rpc_url, Some(rpc_url));
588    }
589
590    #[rstest]
591    fn test_chain_from_chain_id_valid() {
592        // Test some known chain IDs
593        assert!(Chain::from_chain_id(1).is_some()); // Ethereum
594        assert!(Chain::from_chain_id(137).is_some()); // Polygon
595        assert!(Chain::from_chain_id(42161).is_some()); // Arbitrum
596        assert!(Chain::from_chain_id(8453).is_some()); // Base
597
598        // Verify specific chain
599        let eth_chain = Chain::from_chain_id(1).unwrap();
600        assert_eq!(eth_chain.name, Blockchain::Ethereum);
601        assert_eq!(eth_chain.chain_id, 1);
602    }
603
604    // Sources: https://chainid.network/chains.json and
605    // https://docs.envio.dev/docs/HyperSync/hypersync-supported-networks
606    #[rstest]
607    #[case(Blockchain::BerachainBartio, 80084, false)]
608    #[case(Blockchain::BlastSepolia, 168_587_773, false)]
609    #[case(Blockchain::Chiliz, 88888, true)]
610    #[case(Blockchain::CitreaTestnet, 5115, true)]
611    #[case(Blockchain::Darwinia, 46, false)]
612    #[case(Blockchain::GaladrielDevnet, 696_969, false)]
613    #[case(Blockchain::Gnosis, 100, true)]
614    #[case(Blockchain::Holesky, 17000, false)]
615    #[case(Blockchain::Hyperliquid, 999, true)]
616    #[case(Blockchain::Ink, 57073, true)]
617    #[case(Blockchain::Kroma, 255, false)]
618    #[case(Blockchain::Lisk, 1135, true)]
619    #[case(Blockchain::MegaethTestnet, 6343, true)]
620    #[case(Blockchain::Metall2, 1750, true)]
621    #[case(Blockchain::Metis, 1088, false)]
622    #[case(Blockchain::MonadTestnet, 10143, true)]
623    #[case(Blockchain::MoonbaseAlpha, 1287, false)]
624    #[case(Blockchain::Morph, 2818, true)]
625    #[case(Blockchain::MorphHolesky, 2810, false)]
626    #[case(Blockchain::Saakuru, 7_225_878, false)]
627    #[case(Blockchain::Soneium, 1868, true)]
628    #[case(Blockchain::Sophon, 50104, true)]
629    #[case(Blockchain::SophonTestnet, 531_050_104, false)]
630    #[case(Blockchain::Superseed, 5330, true)]
631    #[case(Blockchain::Unichain, 130, true)]
632    #[case(Blockchain::UnichainSepolia, 1301, false)]
633    #[case(Blockchain::Xdc, 50, true)]
634    #[case(Blockchain::XdcTestnet, 51, true)]
635    #[case(Blockchain::Zircuit, 48900, true)]
636    fn test_chain_ids_match_network_chain_ids(
637        #[case] blockchain: Blockchain,
638        #[case] id: u32,
639        #[case] has_hypersync: bool,
640    ) {
641        let chain_by_name = Chain::from_chain_name(&blockchain.to_string()).unwrap();
642        let chain_by_id = Chain::from_chain_id(id).unwrap();
643        let hypersync_url = has_hypersync.then(|| format!("https://{id}.hypersync.xyz"));
644
645        assert_eq!(chain_by_name.name, blockchain);
646        assert_eq!(chain_by_name.chain_id, id);
647        assert_eq!(chain_by_name.hypersync_url, hypersync_url);
648        assert_eq!(chain_by_name.rpc_url, None);
649        assert_eq!(chain_by_name.native_currency_decimals, 18);
650        assert_eq!(chain_by_id, chain_by_name);
651    }
652
653    #[rstest]
654    #[case(80085)]
655    #[case(10300)]
656    #[case(17001)]
657    #[case(7978)]
658    #[case(13337)]
659    #[case(777)]
660    #[case(11)]
661    #[case(2358)]
662    #[case(2_710_111)]
663    #[case(1337)]
664    #[case(1204)]
665    #[case(139)]
666    #[case(9997)]
667    #[case(78600)]
668    fn test_unverified_chain_ids_are_not_recognized(#[case] id: u32) {
669        assert_eq!(Chain::from_chain_id(id), None);
670    }
671
672    #[rstest]
673    #[case("GnosisTraces")]
674    #[case("HyperliquidTemp")]
675    #[case("HoleskyTokenTest")]
676    #[case("InternalTestChain")]
677    #[case("MonadTestnetBackup")]
678    #[case("MevCommit")]
679    #[case("PharosDevnet")]
680    fn test_unverified_chain_names_are_not_recognized(#[case] name: &str) {
681        assert_eq!(Chain::from_chain_name(name), None);
682        assert!(Blockchain::from_str(name).is_err());
683    }
684
685    #[rstest]
686    fn test_chain_presets_have_unique_ids_and_round_trip() {
687        let mut ids = AHashSet::new();
688
689        for blockchain in Blockchain::iter() {
690            let chain = Chain::from_chain_name(&blockchain.to_string()).unwrap();
691
692            assert!(
693                ids.insert(chain.chain_id),
694                "duplicate chain ID for {blockchain}"
695            );
696            assert_eq!(chain.name, blockchain);
697            assert_eq!(Chain::from_chain_id(chain.chain_id), Some(chain));
698        }
699    }
700
701    #[rstest]
702    fn test_chain_from_chain_id_invalid() {
703        // Test unknown chain ID
704        assert!(Chain::from_chain_id(999_999).is_none());
705        assert!(Chain::from_chain_id(0).is_none());
706    }
707
708    #[rstest]
709    fn test_chain_from_chain_name_valid() {
710        // Test some known chain names
711        assert!(Chain::from_chain_name("Ethereum").is_some());
712        assert!(Chain::from_chain_name("Polygon").is_some());
713        assert!(Chain::from_chain_name("Arbitrum").is_some());
714        assert!(Chain::from_chain_name("Base").is_some());
715
716        // Verify specific chain
717        let eth_chain = Chain::from_chain_name("Ethereum").unwrap();
718        assert_eq!(eth_chain.name, Blockchain::Ethereum);
719        assert_eq!(eth_chain.chain_id, 1);
720
721        // Verify ArbitrumNova (compound name)
722        let arbitrum_nova_chain = Chain::from_chain_name("ArbitrumNova").unwrap();
723        assert_eq!(arbitrum_nova_chain.name, Blockchain::ArbitrumNova);
724        assert_eq!(arbitrum_nova_chain.chain_id, 42170);
725
726        // Verify BSC (abbreviated name)
727        let bsc_chain = Chain::from_chain_name("Bsc").unwrap();
728        assert_eq!(bsc_chain.name, Blockchain::Bsc);
729        assert_eq!(bsc_chain.chain_id, 56);
730    }
731
732    #[rstest]
733    fn test_chain_from_chain_name_invalid() {
734        // Test unknown chain names
735        assert!(Chain::from_chain_name("InvalidChain").is_none());
736        assert!(Chain::from_chain_name("").is_none());
737        assert!(Chain::from_chain_name("NonExistentNetwork").is_none());
738    }
739
740    #[rstest]
741    fn test_chain_from_chain_name_case_sensitive() {
742        // Test case sensitivity - should be case insensitive
743        assert!(Chain::from_chain_name("Ethereum").is_some());
744        assert!(Chain::from_chain_name("ethereum").is_some()); // lowercase
745        assert!(Chain::from_chain_name("ETHEREUM").is_some()); // uppercase
746        assert!(Chain::from_chain_name("EtHeReUm").is_some()); // mixed case
747
748        assert!(Chain::from_chain_name("Arbitrum").is_some());
749        assert!(Chain::from_chain_name("arbitrum").is_some()); // lowercase
750    }
751
752    #[rstest]
753    fn test_chain_from_chain_name_consistency_with_id() {
754        // Test that from_chain_name and from_chain_id return the same chain instances
755        let chains_to_test = [
756            ("Ethereum", 1),
757            ("Polygon", 137),
758            ("Arbitrum", 42161),
759            ("Base", 8453),
760            ("Optimism", 10),
761            ("Avalanche", 43114),
762            ("Fantom", 250),
763            ("Bsc", 56),
764        ];
765
766        for (name, id) in chains_to_test {
767            let chain_by_name =
768                Chain::from_chain_name(name).unwrap_or_else(|| panic!("Chain {name} should exist"));
769            let chain_by_id =
770                Chain::from_chain_id(id).unwrap_or_else(|| panic!("Chain {name} should exist"));
771
772            // Should return the same chain instance
773            assert_eq!(chain_by_name.name, chain_by_id.name);
774            assert_eq!(chain_by_name.chain_id, chain_by_id.chain_id);
775            assert_eq!(chain_by_name.hypersync_url, chain_by_id.hypersync_url);
776        }
777    }
778}