odos_sdk/types/
chain.rs

1// SPDX-FileCopyrightText: 2025 Semiotic AI, Inc.
2//
3// SPDX-License-Identifier: Apache-2.0
4
5use std::fmt;
6
7use alloy_chains::NamedChain;
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9
10use crate::{OdosChain, OdosChainError, OdosChainResult};
11
12/// Type-safe chain identifier with convenient constructors
13///
14/// Provides ergonomic helpers for accessing supported chains while
15/// maintaining full compatibility with `alloy_chains::NamedChain`.
16///
17/// # Examples
18///
19/// ```rust
20/// use odos_sdk::{Chain, OdosChain};
21///
22/// // Convenient constructors
23/// let chain = Chain::ethereum();
24/// let chain = Chain::arbitrum();
25/// let chain = Chain::base();
26///
27/// // From chain ID
28/// let chain = Chain::from_chain_id(1)?;  // Ethereum
29/// let chain = Chain::from_chain_id(42161)?;  // Arbitrum
30///
31/// // Access inner NamedChain
32/// let named = chain.inner();
33///
34/// // Use OdosChain trait methods
35/// let router = chain.v3_router_address()?;
36/// # Ok::<(), Box<dyn std::error::Error>>(())
37/// ```
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
39pub struct Chain(NamedChain);
40
41impl Chain {
42    /// Ethereum Mainnet (Chain ID: 1)
43    ///
44    /// # Examples
45    ///
46    /// ```rust
47    /// use odos_sdk::Chain;
48    ///
49    /// let chain = Chain::ethereum();
50    /// assert_eq!(chain.id(), 1);
51    /// ```
52    pub const fn ethereum() -> Self {
53        Self(NamedChain::Mainnet)
54    }
55
56    /// Arbitrum One (Chain ID: 42161)
57    ///
58    /// # Examples
59    ///
60    /// ```rust
61    /// use odos_sdk::Chain;
62    ///
63    /// let chain = Chain::arbitrum();
64    /// assert_eq!(chain.id(), 42161);
65    /// ```
66    pub const fn arbitrum() -> Self {
67        Self(NamedChain::Arbitrum)
68    }
69
70    /// Optimism (Chain ID: 10)
71    ///
72    /// # Examples
73    ///
74    /// ```rust
75    /// use odos_sdk::Chain;
76    ///
77    /// let chain = Chain::optimism();
78    /// assert_eq!(chain.id(), 10);
79    /// ```
80    pub const fn optimism() -> Self {
81        Self(NamedChain::Optimism)
82    }
83
84    /// Polygon (Chain ID: 137)
85    ///
86    /// # Examples
87    ///
88    /// ```rust
89    /// use odos_sdk::Chain;
90    ///
91    /// let chain = Chain::polygon();
92    /// assert_eq!(chain.id(), 137);
93    /// ```
94    pub const fn polygon() -> Self {
95        Self(NamedChain::Polygon)
96    }
97
98    /// Base (Chain ID: 8453)
99    ///
100    /// # Examples
101    ///
102    /// ```rust
103    /// use odos_sdk::Chain;
104    ///
105    /// let chain = Chain::base();
106    /// assert_eq!(chain.id(), 8453);
107    /// ```
108    pub const fn base() -> Self {
109        Self(NamedChain::Base)
110    }
111
112    /// BNB Smart Chain (Chain ID: 56)
113    ///
114    /// # Examples
115    ///
116    /// ```rust
117    /// use odos_sdk::Chain;
118    ///
119    /// let chain = Chain::bsc();
120    /// assert_eq!(chain.id(), 56);
121    /// ```
122    pub const fn bsc() -> Self {
123        Self(NamedChain::BinanceSmartChain)
124    }
125
126    /// Avalanche C-Chain (Chain ID: 43114)
127    ///
128    /// # Examples
129    ///
130    /// ```rust
131    /// use odos_sdk::Chain;
132    ///
133    /// let chain = Chain::avalanche();
134    /// assert_eq!(chain.id(), 43114);
135    /// ```
136    pub const fn avalanche() -> Self {
137        Self(NamedChain::Avalanche)
138    }
139
140    /// Linea (Chain ID: 59144)
141    ///
142    /// # Examples
143    ///
144    /// ```rust
145    /// use odos_sdk::Chain;
146    ///
147    /// let chain = Chain::linea();
148    /// assert_eq!(chain.id(), 59144);
149    /// ```
150    pub const fn linea() -> Self {
151        Self(NamedChain::Linea)
152    }
153
154    /// Scroll (Chain ID: 534352)
155    ///
156    /// # Examples
157    ///
158    /// ```rust
159    /// use odos_sdk::Chain;
160    ///
161    /// let chain = Chain::scroll();
162    /// assert_eq!(chain.id(), 534352);
163    /// ```
164    pub const fn scroll() -> Self {
165        Self(NamedChain::Scroll)
166    }
167
168    /// ZkSync Era (Chain ID: 324)
169    ///
170    /// # Examples
171    ///
172    /// ```rust
173    /// use odos_sdk::Chain;
174    ///
175    /// let chain = Chain::zksync();
176    /// assert_eq!(chain.id(), 324);
177    /// ```
178    pub const fn zksync() -> Self {
179        Self(NamedChain::ZkSync)
180    }
181
182    /// Mantle (Chain ID: 5000)
183    ///
184    /// # Examples
185    ///
186    /// ```rust
187    /// use odos_sdk::Chain;
188    ///
189    /// let chain = Chain::mantle();
190    /// assert_eq!(chain.id(), 5000);
191    /// ```
192    pub const fn mantle() -> Self {
193        Self(NamedChain::Mantle)
194    }
195
196    /// Mode (Chain ID: 34443)
197    ///
198    /// # Examples
199    ///
200    /// ```rust
201    /// use odos_sdk::Chain;
202    ///
203    /// let chain = Chain::mode();
204    /// assert_eq!(chain.id(), 34443);
205    /// ```
206    pub const fn mode() -> Self {
207        Self(NamedChain::Mode)
208    }
209
210    /// Fraxtal (Chain ID: 252)
211    ///
212    /// # Examples
213    ///
214    /// ```rust
215    /// use odos_sdk::Chain;
216    ///
217    /// let chain = Chain::fraxtal();
218    /// assert_eq!(chain.id(), 252);
219    /// ```
220    pub const fn fraxtal() -> Self {
221        Self(NamedChain::Fraxtal)
222    }
223
224    /// Sonic (Chain ID: 146)
225    ///
226    /// # Examples
227    ///
228    /// ```rust
229    /// use odos_sdk::Chain;
230    ///
231    /// let chain = Chain::sonic();
232    /// assert_eq!(chain.id(), 146);
233    /// ```
234    pub const fn sonic() -> Self {
235        Self(NamedChain::Sonic)
236    }
237
238    /// Unichain (Chain ID: 130)
239    ///
240    /// # Examples
241    ///
242    /// ```rust
243    /// use odos_sdk::Chain;
244    ///
245    /// let chain = Chain::unichain();
246    /// assert_eq!(chain.id(), 130);
247    /// ```
248    pub const fn unichain() -> Self {
249        Self(NamedChain::Unichain)
250    }
251
252    /// Create a chain from a chain ID
253    ///
254    /// # Arguments
255    ///
256    /// * `id` - The EVM chain ID
257    ///
258    /// # Returns
259    ///
260    /// * `Ok(Chain)` - If the chain ID is recognized
261    /// * `Err(OdosChainError)` - If the chain ID is not supported
262    ///
263    /// # Examples
264    ///
265    /// ```rust
266    /// use odos_sdk::Chain;
267    ///
268    /// let chain = Chain::from_chain_id(1)?;      // Ethereum
269    /// let chain = Chain::from_chain_id(42161)?;  // Arbitrum
270    /// let chain = Chain::from_chain_id(8453)?;   // Base
271    ///
272    /// // Unsupported chain
273    /// assert!(Chain::from_chain_id(999999).is_err());
274    /// # Ok::<(), Box<dyn std::error::Error>>(())
275    /// ```
276    pub fn from_chain_id(id: u64) -> OdosChainResult<Self> {
277        NamedChain::try_from(id)
278            .map(Self)
279            .map_err(|_| OdosChainError::UnsupportedChain {
280                chain: format!("Chain ID {id}"),
281            })
282    }
283
284    /// Get the chain ID
285    ///
286    /// # Examples
287    ///
288    /// ```rust
289    /// use odos_sdk::Chain;
290    ///
291    /// assert_eq!(Chain::ethereum().id(), 1);
292    /// assert_eq!(Chain::arbitrum().id(), 42161);
293    /// assert_eq!(Chain::base().id(), 8453);
294    /// ```
295    pub fn id(&self) -> u64 {
296        self.0.into()
297    }
298
299    /// Get the inner `NamedChain`
300    ///
301    /// # Examples
302    ///
303    /// ```rust
304    /// use odos_sdk::Chain;
305    /// use alloy_chains::NamedChain;
306    ///
307    /// let chain = Chain::ethereum();
308    /// assert_eq!(chain.inner(), NamedChain::Mainnet);
309    /// ```
310    pub const fn inner(&self) -> NamedChain {
311        self.0
312    }
313}
314
315impl fmt::Display for Chain {
316    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317        write!(f, "{}", self.0)
318    }
319}
320
321impl From<NamedChain> for Chain {
322    fn from(chain: NamedChain) -> Self {
323        Self(chain)
324    }
325}
326
327impl From<Chain> for NamedChain {
328    fn from(chain: Chain) -> Self {
329        chain.0
330    }
331}
332
333impl From<Chain> for u64 {
334    fn from(chain: Chain) -> Self {
335        chain.0.into()
336    }
337}
338
339// Custom serialization using chain ID
340impl Serialize for Chain {
341    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
342    where
343        S: Serializer,
344    {
345        let chain_id: u64 = self.0.into();
346        chain_id.serialize(serializer)
347    }
348}
349
350impl<'de> Deserialize<'de> for Chain {
351    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
352    where
353        D: Deserializer<'de>,
354    {
355        let chain_id = u64::deserialize(deserializer)?;
356        NamedChain::try_from(chain_id)
357            .map(Self)
358            .map_err(serde::de::Error::custom)
359    }
360}
361
362// Implement OdosChain trait by delegating to inner NamedChain
363impl OdosChain for Chain {
364    fn lo_router_address(&self) -> OdosChainResult<alloy_primitives::Address> {
365        self.0.lo_router_address()
366    }
367
368    fn v2_router_address(&self) -> OdosChainResult<alloy_primitives::Address> {
369        self.0.v2_router_address()
370    }
371
372    fn v3_router_address(&self) -> OdosChainResult<alloy_primitives::Address> {
373        self.0.v3_router_address()
374    }
375
376    fn supports_odos(&self) -> bool {
377        self.0.supports_odos()
378    }
379
380    fn supports_lo(&self) -> bool {
381        self.0.supports_lo()
382    }
383
384    fn supports_v2(&self) -> bool {
385        self.0.supports_v2()
386    }
387
388    fn supports_v3(&self) -> bool {
389        self.0.supports_v3()
390    }
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396
397    #[test]
398    fn test_chain_constructors() {
399        assert_eq!(Chain::ethereum().id(), 1);
400        assert_eq!(Chain::arbitrum().id(), 42161);
401        assert_eq!(Chain::optimism().id(), 10);
402        assert_eq!(Chain::polygon().id(), 137);
403        assert_eq!(Chain::base().id(), 8453);
404        assert_eq!(Chain::bsc().id(), 56);
405        assert_eq!(Chain::avalanche().id(), 43114);
406        assert_eq!(Chain::linea().id(), 59144);
407        assert_eq!(Chain::scroll().id(), 534352);
408        assert_eq!(Chain::zksync().id(), 324);
409        assert_eq!(Chain::mantle().id(), 5000);
410        assert_eq!(Chain::mode().id(), 34443);
411        assert_eq!(Chain::fraxtal().id(), 252);
412        assert_eq!(Chain::sonic().id(), 146);
413        assert_eq!(Chain::unichain().id(), 130);
414    }
415
416    #[test]
417    fn test_from_chain_id() {
418        assert_eq!(Chain::from_chain_id(1).unwrap().id(), 1);
419        assert_eq!(Chain::from_chain_id(42161).unwrap().id(), 42161);
420        assert_eq!(Chain::from_chain_id(8453).unwrap().id(), 8453);
421
422        // Unsupported chain
423        assert!(Chain::from_chain_id(999999).is_err());
424    }
425
426    #[test]
427    fn test_inner() {
428        assert_eq!(Chain::ethereum().inner(), NamedChain::Mainnet);
429        assert_eq!(Chain::arbitrum().inner(), NamedChain::Arbitrum);
430        assert_eq!(Chain::base().inner(), NamedChain::Base);
431    }
432
433    #[test]
434    fn test_display() {
435        assert_eq!(format!("{}", Chain::ethereum()), "mainnet");
436        assert_eq!(format!("{}", Chain::arbitrum()), "arbitrum");
437        assert_eq!(format!("{}", Chain::base()), "base");
438    }
439
440    #[test]
441    fn test_conversions() {
442        // From NamedChain
443        let chain: Chain = NamedChain::Mainnet.into();
444        assert_eq!(chain.id(), 1);
445
446        // To NamedChain
447        let named: NamedChain = Chain::ethereum().into();
448        assert_eq!(named, NamedChain::Mainnet);
449
450        // To u64
451        let id: u64 = Chain::ethereum().into();
452        assert_eq!(id, 1);
453    }
454
455    #[test]
456    fn test_odos_chain_trait() {
457        let chain = Chain::ethereum();
458
459        // Test trait methods work
460        assert!(chain.supports_odos());
461        assert!(chain.supports_v2());
462        assert!(chain.supports_v3());
463        assert!(chain.v2_router_address().is_ok());
464        assert!(chain.v3_router_address().is_ok());
465    }
466
467    #[test]
468    fn test_equality() {
469        assert_eq!(Chain::ethereum(), Chain::ethereum());
470        assert_ne!(Chain::ethereum(), Chain::arbitrum());
471    }
472
473    #[test]
474    fn test_serialization() {
475        let chain = Chain::ethereum();
476
477        // Serialize (as chain ID)
478        let json = serde_json::to_string(&chain).unwrap();
479        assert_eq!(json, "1"); // Ethereum chain ID
480
481        // Deserialize
482        let deserialized: Chain = serde_json::from_str(&json).unwrap();
483        assert_eq!(deserialized, chain);
484
485        // Test other chains
486        assert_eq!(serde_json::to_string(&Chain::arbitrum()).unwrap(), "42161");
487        assert_eq!(serde_json::to_string(&Chain::base()).unwrap(), "8453");
488    }
489}