Skip to main content

ows_core/
chain.rs

1use serde::{Deserialize, Serialize};
2use std::fmt;
3use std::str::FromStr;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
6#[serde(rename_all = "lowercase")]
7pub enum ChainType {
8    Evm,
9    Solana,
10    Cosmos,
11    Bitcoin,
12    Tron,
13    Ton,
14    Spark,
15    Filecoin,
16    Sui,
17}
18
19/// All supported chain families, used for universal wallet derivation.
20pub const ALL_CHAIN_TYPES: [ChainType; 8] = [
21    ChainType::Evm,
22    ChainType::Solana,
23    ChainType::Bitcoin,
24    ChainType::Cosmos,
25    ChainType::Tron,
26    ChainType::Ton,
27    ChainType::Filecoin,
28    ChainType::Sui,
29];
30
31/// A specific chain (e.g. "ethereum", "arbitrum") with its family type and CAIP-2 ID.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct Chain {
34    pub name: &'static str,
35    pub chain_type: ChainType,
36    pub chain_id: &'static str,
37}
38
39/// Known chains registry.
40pub const KNOWN_CHAINS: &[Chain] = &[
41    Chain {
42        name: "ethereum",
43        chain_type: ChainType::Evm,
44        chain_id: "eip155:1",
45    },
46    Chain {
47        name: "polygon",
48        chain_type: ChainType::Evm,
49        chain_id: "eip155:137",
50    },
51    Chain {
52        name: "arbitrum",
53        chain_type: ChainType::Evm,
54        chain_id: "eip155:42161",
55    },
56    Chain {
57        name: "optimism",
58        chain_type: ChainType::Evm,
59        chain_id: "eip155:10",
60    },
61    Chain {
62        name: "base",
63        chain_type: ChainType::Evm,
64        chain_id: "eip155:8453",
65    },
66    Chain {
67        name: "bsc",
68        chain_type: ChainType::Evm,
69        chain_id: "eip155:56",
70    },
71    Chain {
72        name: "avalanche",
73        chain_type: ChainType::Evm,
74        chain_id: "eip155:43114",
75    },
76    Chain {
77        name: "solana",
78        chain_type: ChainType::Solana,
79        chain_id: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
80    },
81    Chain {
82        name: "bitcoin",
83        chain_type: ChainType::Bitcoin,
84        chain_id: "bip122:000000000019d6689c085ae165831e93",
85    },
86    Chain {
87        name: "cosmos",
88        chain_type: ChainType::Cosmos,
89        chain_id: "cosmos:cosmoshub-4",
90    },
91    Chain {
92        name: "tron",
93        chain_type: ChainType::Tron,
94        chain_id: "tron:mainnet",
95    },
96    Chain {
97        name: "ton",
98        chain_type: ChainType::Ton,
99        chain_id: "ton:mainnet",
100    },
101    Chain {
102        name: "spark",
103        chain_type: ChainType::Spark,
104        chain_id: "spark:mainnet",
105    },
106    Chain {
107        name: "filecoin",
108        chain_type: ChainType::Filecoin,
109        chain_id: "fil:mainnet",
110    },
111    Chain {
112        name: "sui",
113        chain_type: ChainType::Sui,
114        chain_id: "sui:mainnet",
115    },
116];
117
118/// Parse a chain string into a `Chain`. Accepts:
119/// - Friendly names: "ethereum", "arbitrum", "solana", etc.
120/// - CAIP-2 chain IDs: "eip155:1", "eip155:42161", etc.
121/// - Legacy family names for backward compat: "evm" → resolves to ethereum
122pub fn parse_chain(s: &str) -> Result<Chain, String> {
123    let lower = s.to_lowercase();
124
125    // Legacy family name backward compat
126    let lookup = match lower.as_str() {
127        "evm" => "ethereum",
128        _ => &lower,
129    };
130
131    // Try friendly name match
132    if let Some(chain) = KNOWN_CHAINS.iter().find(|c| c.name == lookup) {
133        return Ok(*chain);
134    }
135
136    // Try CAIP-2 chain ID match
137    if let Some(chain) = KNOWN_CHAINS.iter().find(|c| c.chain_id == s) {
138        return Ok(*chain);
139    }
140
141    // Try namespace match for unknown CAIP-2 IDs (e.g. eip155:4217, eip155:84532).
142    // Uses the same signer as the namespace's default chain. The chain_id string is
143    // leaked to satisfy the 'static lifetime — acceptable since parse_chain is called
144    // with a small, bounded set of user-supplied chain identifiers.
145    if let Some((namespace, _reference)) = s.split_once(':') {
146        if let Some(ct) = ChainType::from_namespace(namespace) {
147            let leaked: &'static str = Box::leak(s.to_string().into_boxed_str());
148            return Ok(Chain {
149                name: leaked,
150                chain_type: ct,
151                chain_id: leaked,
152            });
153        }
154    }
155
156    Err(format!(
157        "unknown chain: '{}'. Use a chain name (ethereum, solana, bitcoin, ...) or CAIP-2 ID (eip155:1, ...)",
158        s
159    ))
160}
161
162/// Returns the default `Chain` for a given `ChainType` (first match in registry).
163pub fn default_chain_for_type(ct: ChainType) -> Chain {
164    *KNOWN_CHAINS.iter().find(|c| c.chain_type == ct).unwrap()
165}
166
167impl ChainType {
168    /// Returns the CAIP-2 namespace for this chain type.
169    pub fn namespace(&self) -> &'static str {
170        match self {
171            ChainType::Evm => "eip155",
172            ChainType::Solana => "solana",
173            ChainType::Cosmos => "cosmos",
174            ChainType::Bitcoin => "bip122",
175            ChainType::Tron => "tron",
176            ChainType::Ton => "ton",
177            ChainType::Spark => "spark",
178            ChainType::Filecoin => "fil",
179            ChainType::Sui => "sui",
180        }
181    }
182
183    /// Returns the BIP-44 coin type for this chain type.
184    pub fn default_coin_type(&self) -> u32 {
185        match self {
186            ChainType::Evm => 60,
187            ChainType::Solana => 501,
188            ChainType::Cosmos => 118,
189            ChainType::Bitcoin => 0,
190            ChainType::Tron => 195,
191            ChainType::Ton => 607,
192            ChainType::Spark => 8797555,
193            ChainType::Filecoin => 461,
194            ChainType::Sui => 784,
195        }
196    }
197
198    /// Returns the ChainType for a given CAIP-2 namespace.
199    pub fn from_namespace(ns: &str) -> Option<ChainType> {
200        match ns {
201            "eip155" => Some(ChainType::Evm),
202            "solana" => Some(ChainType::Solana),
203            "cosmos" => Some(ChainType::Cosmos),
204            "bip122" => Some(ChainType::Bitcoin),
205            "tron" => Some(ChainType::Tron),
206            "ton" => Some(ChainType::Ton),
207            "spark" => Some(ChainType::Spark),
208            "fil" => Some(ChainType::Filecoin),
209            "sui" => Some(ChainType::Sui),
210            _ => None,
211        }
212    }
213}
214
215impl fmt::Display for ChainType {
216    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217        let s = match self {
218            ChainType::Evm => "evm",
219            ChainType::Solana => "solana",
220            ChainType::Cosmos => "cosmos",
221            ChainType::Bitcoin => "bitcoin",
222            ChainType::Tron => "tron",
223            ChainType::Ton => "ton",
224            ChainType::Spark => "spark",
225            ChainType::Filecoin => "filecoin",
226            ChainType::Sui => "sui",
227        };
228        write!(f, "{}", s)
229    }
230}
231
232impl FromStr for ChainType {
233    type Err = String;
234
235    fn from_str(s: &str) -> Result<Self, Self::Err> {
236        match s.to_lowercase().as_str() {
237            "evm" => Ok(ChainType::Evm),
238            "solana" => Ok(ChainType::Solana),
239            "cosmos" => Ok(ChainType::Cosmos),
240            "bitcoin" => Ok(ChainType::Bitcoin),
241            "tron" => Ok(ChainType::Tron),
242            "ton" => Ok(ChainType::Ton),
243            "spark" => Ok(ChainType::Spark),
244            "filecoin" => Ok(ChainType::Filecoin),
245            "sui" => Ok(ChainType::Sui),
246            _ => Err(format!("unknown chain type: {}", s)),
247        }
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn test_serde_roundtrip() {
257        let chain = ChainType::Evm;
258        let json = serde_json::to_string(&chain).unwrap();
259        assert_eq!(json, "\"evm\"");
260        let chain2: ChainType = serde_json::from_str(&json).unwrap();
261        assert_eq!(chain, chain2);
262    }
263
264    #[test]
265    fn test_serde_all_variants() {
266        for (chain, expected) in [
267            (ChainType::Evm, "\"evm\""),
268            (ChainType::Solana, "\"solana\""),
269            (ChainType::Cosmos, "\"cosmos\""),
270            (ChainType::Bitcoin, "\"bitcoin\""),
271            (ChainType::Tron, "\"tron\""),
272            (ChainType::Ton, "\"ton\""),
273            (ChainType::Spark, "\"spark\""),
274            (ChainType::Filecoin, "\"filecoin\""),
275            (ChainType::Sui, "\"sui\""),
276        ] {
277            let json = serde_json::to_string(&chain).unwrap();
278            assert_eq!(json, expected);
279            let deserialized: ChainType = serde_json::from_str(&json).unwrap();
280            assert_eq!(chain, deserialized);
281        }
282    }
283
284    #[test]
285    fn test_namespace_mapping() {
286        assert_eq!(ChainType::Evm.namespace(), "eip155");
287        assert_eq!(ChainType::Solana.namespace(), "solana");
288        assert_eq!(ChainType::Cosmos.namespace(), "cosmos");
289        assert_eq!(ChainType::Bitcoin.namespace(), "bip122");
290        assert_eq!(ChainType::Tron.namespace(), "tron");
291        assert_eq!(ChainType::Ton.namespace(), "ton");
292        assert_eq!(ChainType::Spark.namespace(), "spark");
293        assert_eq!(ChainType::Filecoin.namespace(), "fil");
294        assert_eq!(ChainType::Sui.namespace(), "sui");
295    }
296
297    #[test]
298    fn test_coin_type_mapping() {
299        assert_eq!(ChainType::Evm.default_coin_type(), 60);
300        assert_eq!(ChainType::Solana.default_coin_type(), 501);
301        assert_eq!(ChainType::Cosmos.default_coin_type(), 118);
302        assert_eq!(ChainType::Bitcoin.default_coin_type(), 0);
303        assert_eq!(ChainType::Tron.default_coin_type(), 195);
304        assert_eq!(ChainType::Ton.default_coin_type(), 607);
305        assert_eq!(ChainType::Spark.default_coin_type(), 8797555);
306        assert_eq!(ChainType::Filecoin.default_coin_type(), 461);
307        assert_eq!(ChainType::Sui.default_coin_type(), 784);
308    }
309
310    #[test]
311    fn test_from_namespace() {
312        assert_eq!(ChainType::from_namespace("eip155"), Some(ChainType::Evm));
313        assert_eq!(ChainType::from_namespace("solana"), Some(ChainType::Solana));
314        assert_eq!(ChainType::from_namespace("cosmos"), Some(ChainType::Cosmos));
315        assert_eq!(
316            ChainType::from_namespace("bip122"),
317            Some(ChainType::Bitcoin)
318        );
319        assert_eq!(ChainType::from_namespace("tron"), Some(ChainType::Tron));
320        assert_eq!(ChainType::from_namespace("ton"), Some(ChainType::Ton));
321        assert_eq!(ChainType::from_namespace("spark"), Some(ChainType::Spark));
322        assert_eq!(ChainType::from_namespace("fil"), Some(ChainType::Filecoin));
323        assert_eq!(ChainType::from_namespace("sui"), Some(ChainType::Sui));
324        assert_eq!(ChainType::from_namespace("unknown"), None);
325    }
326
327    #[test]
328    fn test_from_str() {
329        assert_eq!("evm".parse::<ChainType>().unwrap(), ChainType::Evm);
330        assert_eq!("Solana".parse::<ChainType>().unwrap(), ChainType::Solana);
331        assert!("unknown".parse::<ChainType>().is_err());
332    }
333
334    #[test]
335    fn test_display() {
336        assert_eq!(ChainType::Evm.to_string(), "evm");
337        assert_eq!(ChainType::Bitcoin.to_string(), "bitcoin");
338    }
339
340    #[test]
341    fn test_parse_chain_friendly_name() {
342        let chain = parse_chain("ethereum").unwrap();
343        assert_eq!(chain.name, "ethereum");
344        assert_eq!(chain.chain_type, ChainType::Evm);
345        assert_eq!(chain.chain_id, "eip155:1");
346    }
347
348    #[test]
349    fn test_parse_chain_caip2() {
350        let chain = parse_chain("eip155:42161").unwrap();
351        assert_eq!(chain.name, "arbitrum");
352        assert_eq!(chain.chain_type, ChainType::Evm);
353    }
354
355    #[test]
356    fn test_parse_chain_legacy_evm() {
357        let chain = parse_chain("evm").unwrap();
358        assert_eq!(chain.name, "ethereum");
359        assert_eq!(chain.chain_type, ChainType::Evm);
360    }
361
362    #[test]
363    fn test_parse_chain_solana() {
364        let chain = parse_chain("solana").unwrap();
365        assert_eq!(chain.chain_type, ChainType::Solana);
366    }
367
368    #[test]
369    fn test_parse_chain_unknown() {
370        assert!(parse_chain("unknown_chain").is_err());
371    }
372
373    #[test]
374    fn test_all_chain_types() {
375        assert_eq!(ALL_CHAIN_TYPES.len(), 8);
376    }
377
378    #[test]
379    fn test_default_chain_for_type() {
380        let chain = default_chain_for_type(ChainType::Evm);
381        assert_eq!(chain.name, "ethereum");
382        assert_eq!(chain.chain_id, "eip155:1");
383    }
384}