Skip to main content

tycho_common/models/
mod.rs

1pub mod blockchain;
2pub mod chain_config;
3pub mod contract;
4pub mod error;
5pub mod protocol;
6pub mod token;
7
8use std::{collections::HashMap, fmt::Display, str::FromStr};
9
10pub use blockchain::{BlockChanges, TxWithContractChanges};
11use chain_config::{
12    chain_registry, ChainConfigError, ChainConfigRegistry, CustomChainConfig, CustomChainId,
13    TvlThresholdTier,
14};
15use deepsize::DeepSizeOf;
16use serde::{Deserialize, Serialize};
17use thiserror::Error;
18use token::Token;
19
20use crate::{dto, Bytes};
21
22/// Address hash literal type to uniquely identify contracts/accounts on a
23/// blockchain.
24pub type Address = Bytes;
25
26/// Block hash literal type to uniquely identify a block in the chain and
27/// likely across chains.
28pub type BlockHash = Bytes;
29
30/// Transaction hash literal type to uniquely identify a transaction in the
31/// chain and likely across chains.
32pub type TxHash = Bytes;
33
34/// Smart contract code is represented as a byte vector containing opcodes.
35pub type Code = Bytes;
36
37/// The hash of a contract's code is used to identify it.
38pub type CodeHash = Bytes;
39
40/// The balance of an account is a big endian serialised integer of variable size.
41pub type Balance = Bytes;
42
43/// Key literal type of the contract store.
44pub type StoreKey = Bytes;
45
46/// Key literal type of the attribute store.
47pub type AttrStoreKey = String;
48
49/// Value literal type of the contract store.
50pub type StoreVal = Bytes;
51
52/// A binary key-value store for an account.
53pub type ContractStore = HashMap<StoreKey, StoreVal>;
54pub type ContractStoreDeltas = HashMap<StoreKey, Option<StoreVal>>;
55pub type AccountToContractStoreDeltas = HashMap<Address, ContractStoreDeltas>;
56
57/// Component id literal type to uniquely identify a component.
58pub type ComponentId = String;
59
60/// Protocol system literal type to uniquely identify a protocol system.
61pub type ProtocolSystem = String;
62
63/// Entry point id literal type to uniquely identify an entry point.
64pub type EntryPointId = String;
65
66/// A blockchain Tycho indexes or simulates over.
67///
68/// Built-in chains are first-class variants: their config (id, native token, block time, TVL
69/// tiers) is compile-time and total, so they never fail to resolve. `Custom` is the escape hatch
70/// for a chain a self-hoster runs without upstreaming a variant — its config lives in the
71/// process-wide registry (see [`chain_config`]) rather than in the enum.
72///
73/// `Custom` wraps a [`CustomChainId`] whose inner name is private, so a `Chain::Custom` can only be
74/// built through the crate's registry-validating constructors ([`Chain::custom`],
75/// [`Chain::from_str`], `From<dto::Chain>`) — it cannot be fabricated directly. Because the
76/// registry is set-once, a validated `Chain::Custom` stays resolvable for its whole lifetime, so
77/// the config accessors only panic on an unreachable invariant; [`Chain::try_id`] and its siblings
78/// expose non-panicking variants. The one reachable failure is decoding wire data for a chain the
79/// local registry lacks (`From<dto::Chain>`), which panics at the decode boundary.
80///
81/// Prefer adding a first-class variant for any chain Tycho officially supports; reserve `Custom`
82/// for the self-host case. Full rationale in the custom-chain decision record.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
84#[serde(rename_all = "lowercase")]
85#[non_exhaustive]
86pub enum Chain {
87    #[default]
88    Ethereum,
89    Starknet,
90    ZkSync,
91    Arbitrum,
92    Base,
93    Bsc,
94    Unichain,
95    Polygon,
96    Plasma,
97    Robinhood,
98    Arc,
99    Elysium,
100    /// User-defined chain resolved via the [`chain_config`] registry; see the enum docs.
101    Custom(CustomChainId),
102}
103
104/// The native asset representations and economic relationship for a chain.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub enum NativeAsset {
107    /// Separate native and ERC-20 balances connected by a wrapper contract.
108    Wrapper { native: Token, wrapper: Token },
109    /// Separate token representations exposing the same underlying balance.
110    SharedBalance { native: Token, routable: Token },
111    /// A native balance without a routable token representation.
112    NativeOnly { native: Token },
113}
114
115impl NativeAsset {
116    pub fn native_token(&self) -> &Token {
117        match self {
118            NativeAsset::Wrapper { native, wrapper: _ } |
119            NativeAsset::SharedBalance { native, routable: _ } |
120            NativeAsset::NativeOnly { native } => native,
121        }
122    }
123
124    pub fn routable_token(&self) -> Option<&Token> {
125        match self {
126            NativeAsset::Wrapper { native: _, wrapper } => Some(wrapper),
127            NativeAsset::SharedBalance { native: _, routable } => Some(routable),
128            NativeAsset::NativeOnly { native: _ } => None,
129        }
130    }
131
132    /// Returns the routable token only when it is backed by a real wrapper contract.
133    pub fn wrapper(&self) -> Option<&Token> {
134        match self {
135            NativeAsset::Wrapper { native: _, wrapper } => Some(wrapper),
136            NativeAsset::SharedBalance { native: _, routable: _ } |
137            NativeAsset::NativeOnly { native: _ } => None,
138        }
139    }
140
141    /// Returns each token representation of this economic asset.
142    pub fn representations(&self) -> impl Iterator<Item = &Token> {
143        std::iter::once(self.native_token()).chain(self.routable_token())
144    }
145}
146
147impl DeepSizeOf for Chain {
148    fn deep_size_of_children(&self, _context: &mut deepsize::Context) -> usize {
149        0
150    }
151}
152
153impl Chain {
154    /// Parses only the built-in chains, ignoring any custom-chain registry.
155    pub fn builtin_from_str(s: &str) -> Option<Self> {
156        match s {
157            "ethereum" => Some(Chain::Ethereum),
158            "starknet" => Some(Chain::Starknet),
159            "zksync" => Some(Chain::ZkSync),
160            "arbitrum" => Some(Chain::Arbitrum),
161            "base" => Some(Chain::Base),
162            "bsc" => Some(Chain::Bsc),
163            "unichain" => Some(Chain::Unichain),
164            "polygon" => Some(Chain::Polygon),
165            "plasma" => Some(Chain::Plasma),
166            "robinhood" => Some(Chain::Robinhood),
167            "arc" => Some(Chain::Arc),
168            "elysium" => Some(Chain::Elysium),
169            _ => None,
170        }
171    }
172
173    /// Builds a custom-chain identity, validating that `name` has a config in the chain registry.
174    /// Returns [`ChainConfigError::UnknownChain`] when it is absent so typos never silently become
175    /// custom chains.
176    pub fn custom(name: &str) -> Result<Self, ChainConfigError> {
177        CustomChainId::checked(name, chain_registry()).map(Chain::Custom)
178    }
179}
180
181impl FromStr for Chain {
182    type Err = ChainConfigError;
183
184    /// Resolves a chain name. Built-in chains parse directly; any other name is accepted only if it
185    /// is registered in the global chain config registry, otherwise
186    /// [`ChainConfigError::UnknownChain`] is returned so typos never silently become custom chains.
187    fn from_str(s: &str) -> Result<Self, Self::Err> {
188        if let Some(chain) = Self::builtin_from_str(s) {
189            return Ok(chain);
190        }
191        Self::custom(s)
192    }
193}
194
195impl Display for Chain {
196    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197        match self {
198            Chain::Ethereum => f.write_str("ethereum"),
199            Chain::Starknet => f.write_str("starknet"),
200            Chain::ZkSync => f.write_str("zksync"),
201            Chain::Arbitrum => f.write_str("arbitrum"),
202            Chain::Base => f.write_str("base"),
203            Chain::Bsc => f.write_str("bsc"),
204            Chain::Unichain => f.write_str("unichain"),
205            Chain::Polygon => f.write_str("polygon"),
206            Chain::Plasma => f.write_str("plasma"),
207            Chain::Robinhood => f.write_str("robinhood"),
208            Chain::Arc => f.write_str("arc"),
209            Chain::Elysium => f.write_str("elysium"),
210            Chain::Custom(name) => f.write_str(name.as_str()),
211        }
212    }
213}
214
215impl From<dto::Chain> for Chain {
216    fn from(value: dto::Chain) -> Self {
217        match value {
218            dto::Chain::Ethereum => Chain::Ethereum,
219            dto::Chain::Starknet => Chain::Starknet,
220            dto::Chain::ZkSync => Chain::ZkSync,
221            dto::Chain::Arbitrum => Chain::Arbitrum,
222            dto::Chain::Base => Chain::Base,
223            dto::Chain::Bsc => Chain::Bsc,
224            dto::Chain::Unichain => Chain::Unichain,
225            dto::Chain::Polygon => Chain::Polygon,
226            dto::Chain::Plasma => Chain::Plasma,
227            dto::Chain::Robinhood => Chain::Robinhood,
228            dto::Chain::Arc => Chain::Arc,
229            dto::Chain::Elysium => Chain::Elysium,
230            dto::Chain::Custom(name) => Chain::custom(name.as_str()).unwrap_or_else(|e| {
231                panic!(
232                    "received custom chain '{name}' with no registered config: {e}; install it via \
233                     the chain config file (TYCHO_CHAINS_CONFIG, default ./chains.yaml) or \
234                     init_chain_registry before decoding wire data"
235                )
236            }),
237        }
238    }
239}
240
241impl From<dto::ChangeType> for ChangeType {
242    fn from(value: dto::ChangeType) -> Self {
243        match value {
244            dto::ChangeType::Update => ChangeType::Update,
245            dto::ChangeType::Creation => ChangeType::Creation,
246            dto::ChangeType::Deletion => ChangeType::Deletion,
247            dto::ChangeType::Unspecified => ChangeType::Update,
248        }
249    }
250}
251
252fn native_eth(chain: Chain) -> Token {
253    Token::new(
254        &Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
255        "ETH",
256        18,
257        0,
258        &[Some(2300)],
259        chain,
260        100,
261    )
262}
263
264fn native_bsc(chain: Chain) -> Token {
265    Token::new(
266        &Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
267        "BNB",
268        18,
269        0,
270        &[Some(2300)],
271        chain,
272        100,
273    )
274}
275
276fn wrapped_native_eth(chain: Chain, address: &str) -> Token {
277    Token::new(&Bytes::from_str(address).unwrap(), "WETH", 18, 0, &[Some(2300)], chain, 100)
278}
279
280fn native_pol(chain: Chain) -> Token {
281    Token::new(
282        &Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
283        "POL",
284        18,
285        0,
286        &[Some(2300)],
287        chain,
288        100,
289    )
290}
291
292fn native_xpl(chain: Chain) -> Token {
293    Token::new(
294        &Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
295        "XPL",
296        18,
297        0,
298        &[Some(2300)],
299        chain,
300        100,
301    )
302}
303
304fn native_arc_usdc(chain: Chain) -> Token {
305    Token::new(&Bytes::from([0u8; 20]), "USDC", 18, 0, &[Some(2300)], chain, 100)
306}
307
308fn native_hype(chain: Chain) -> Token {
309    Token::new(
310        &Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
311        "HYPE",
312        18,
313        0,
314        &[Some(2300)],
315        chain,
316        100,
317    )
318}
319
320fn wrapped_native_hype(chain: Chain, address: &str) -> Token {
321    Token::new(&Bytes::from_str(address).unwrap(), "WHYPE", 18, 0, &[Some(2300)], chain, 100)
322}
323
324/// Looks up a custom chain's config in the registry, returning [`ChainConfigError::UnknownChain`]
325/// when it is absent.
326fn try_resolve_custom<'a>(
327    id: &CustomChainId,
328    registry: &'a ChainConfigRegistry,
329) -> Result<&'a CustomChainConfig, ChainConfigError> {
330    registry
331        .get(id.as_str())
332        .ok_or_else(|| ChainConfigError::UnknownChain(id.as_str().to_owned()))
333}
334
335/// Unwraps a registry lookup that cannot fail for a validly-constructed `Chain::Custom`: a
336/// [`CustomChainId`] is only minted after registry validation and the registry is set-once, so a
337/// missing entry is an internal invariant violation rather than bad input.
338fn expect_registered<T>(result: Result<T, ChainConfigError>) -> T {
339    result.unwrap_or_else(|e| {
340        panic!(
341            "internal invariant violation resolving custom chain config: {e}; Chain::Custom is \
342             validated against the set-once chain registry at construction"
343        )
344    })
345}
346
347fn native_custom(chain: Chain, cfg: &CustomChainConfig) -> Token {
348    let addr = Bytes::from(cfg.native.address.as_bytes().to_vec());
349    Token::new(
350        &addr,
351        cfg.native.symbol.as_str(),
352        cfg.native.decimals as u32,
353        0,
354        &[Some(2300)],
355        chain,
356        100,
357    )
358}
359
360fn wrapped_native_bsc(chain: Chain, address: &str) -> Token {
361    Token::new(&Bytes::from_str(address).unwrap(), "WBNB", 18, 0, &[Some(2300)], chain, 100)
362}
363
364fn wrapped_native_pol(chain: Chain, address: &str) -> Token {
365    Token::new(&Bytes::from_str(address).unwrap(), "WMATIC", 18, 0, &[Some(2300)], chain, 100)
366}
367
368fn wrapped_native_xpl(chain: Chain, address: &str) -> Token {
369    Token::new(&Bytes::from_str(address).unwrap(), "WXPL", 18, 0, &[Some(2300)], chain, 100)
370}
371
372fn routable_arc_usdc(chain: Chain) -> Token {
373    Token::new(
374        &Bytes::from_str("0x3600000000000000000000000000000000000000").unwrap(),
375        "USDC",
376        6,
377        0,
378        &[Some(2300)],
379        chain,
380        100,
381    )
382}
383
384fn wrapped_native_custom(chain: Chain, cfg: &CustomChainConfig) -> Token {
385    let addr = Bytes::from(
386        cfg.wrapped_native
387            .address
388            .as_bytes()
389            .to_vec(),
390    );
391    Token::new(
392        &addr,
393        cfg.wrapped_native.symbol.as_str(),
394        cfg.wrapped_native.decimals as u32,
395        0,
396        &[Some(2300)],
397        chain,
398        100,
399    )
400}
401
402impl Chain {
403    /// Returns the numeric chain id. Panics if a custom chain has no registered config — an
404    /// unreachable invariant for a validly-constructed `Chain::Custom`; use [`Chain::try_id`] for a
405    /// non-panicking variant.
406    pub fn id(&self) -> u64 {
407        expect_registered(self.try_id())
408    }
409
410    /// Returns the numeric chain id, or [`ChainConfigError::UnknownChain`] when a custom chain has
411    /// no registered config.
412    pub fn try_id(&self) -> Result<u64, ChainConfigError> {
413        Ok(match self {
414            Chain::Ethereum => 1,
415            Chain::ZkSync => 324,
416            Chain::Arbitrum => 42161,
417            Chain::Starknet => 0,
418            Chain::Base => 8453,
419            Chain::Bsc => 56,
420            Chain::Unichain => 130,
421            Chain::Polygon => 137,
422            Chain::Plasma => 9745,
423            Chain::Robinhood => 4663,
424            Chain::Arc => 5042,
425            Chain::Elysium => 99901,
426            Chain::Custom(id) => try_resolve_custom(id, chain_registry())?.chain_id,
427        })
428    }
429
430    /// Returns a default TVL threshold in native token units for the given tier.
431    ///
432    /// Values are approximate and target a USD-equivalent range, not a precise conversion.
433    /// Native token prices used: ETH ~$2,000, POL ~$0.10, BNB ~$630.
434    /// These prices are volatile, and used as a reference. They should not be updated often,
435    /// unless big price movements occour, making an update necessary.
436    ///
437    /// Panics if a custom chain has no registered config; use [`Chain::try_default_tvl_threshold`]
438    /// for a non-panicking variant.
439    pub fn default_tvl_threshold(&self, tier: TvlThresholdTier) -> f64 {
440        expect_registered(self.try_default_tvl_threshold(tier))
441    }
442
443    /// Like [`Chain::default_tvl_threshold`] but returns [`ChainConfigError::UnknownChain`] when a
444    /// custom chain has no registered config.
445    pub fn try_default_tvl_threshold(
446        &self,
447        tier: TvlThresholdTier,
448    ) -> Result<f64, ChainConfigError> {
449        Ok(match (self, tier) {
450            // ETH-native chains: 10 ETH ≈ $20K, 100 ETH ≈ $200K.
451            // Starknet uses ETH-denominated TVL in Tycho (STRK tracked separately).
452            (
453                Chain::Ethereum |
454                Chain::Starknet |
455                Chain::ZkSync |
456                Chain::Arbitrum |
457                Chain::Base |
458                Chain::Unichain |
459                Chain::Robinhood,
460                TvlThresholdTier::Low,
461            ) => 10.0,
462            (
463                Chain::Ethereum |
464                Chain::Starknet |
465                Chain::ZkSync |
466                Chain::Arbitrum |
467                Chain::Base |
468                Chain::Unichain |
469                Chain::Robinhood,
470                TvlThresholdTier::Medium,
471            ) => 100.0,
472
473            // Polygon (POL ≈ $0.10): 200_000 POL ≈ $20K, 2_000_000 POL ≈ $200K
474            (Chain::Polygon, TvlThresholdTier::Low) => 200_000.0,
475            (Chain::Polygon, TvlThresholdTier::Medium) => 2_000_000.0,
476
477            // Plasma (XPL ≈ $0.10): 200_000 XPL ≈ $20K, 2_000_000 XPL ≈ $200K
478            (Chain::Plasma, TvlThresholdTier::Low) => 200_000.0,
479            (Chain::Plasma, TvlThresholdTier::Medium) => 2_000_000.0,
480
481            // BSC (BNB ≈ $630): 32 BNB ≈ $20K, 320 BNB ≈ $200K
482            (Chain::Bsc, TvlThresholdTier::Low) => 32.0,
483            (Chain::Bsc, TvlThresholdTier::Medium) => 320.0,
484
485            // Arc's native USDC is worth $1.
486            (Chain::Arc, TvlThresholdTier::Low) => 20_000.0,
487            (Chain::Arc, TvlThresholdTier::Medium) => 200_000.0,
488
489            // Elysium (HYPE ≈ $80): 250 HYPE ≈ $20K, 2_500 HYPE ≈ $200K.
490            (Chain::Elysium, TvlThresholdTier::Low) => 250.0,
491            (Chain::Elysium, TvlThresholdTier::Medium) => 2_500.0,
492
493            (Chain::Custom(id), TvlThresholdTier::Low) => {
494                try_resolve_custom(id, chain_registry())?
495                    .default_tvl_thresholds
496                    .low
497            }
498            (Chain::Custom(id), TvlThresholdTier::Medium) => {
499                try_resolve_custom(id, chain_registry())?
500                    .default_tvl_thresholds
501                    .medium
502            }
503        })
504    }
505
506    /// Returns the native token for the chain. Panics if a custom chain has no registered config;
507    /// use [`Chain::try_native_token`] for a non-panicking variant.
508    pub fn native_token(&self) -> Token {
509        expect_registered(self.try_native_token())
510    }
511
512    /// Like [`Chain::native_token`] but returns [`ChainConfigError::UnknownChain`] when a custom
513    /// chain has no registered config.
514    pub fn try_native_token(&self) -> Result<Token, ChainConfigError> {
515        Ok(match self {
516            Chain::Ethereum => native_eth(Chain::Ethereum),
517            // It was decided that STRK token will be tracked as a dedicated AccountBalance on
518            // Starknet accounts and ETH balances will be tracked as a native balance.
519            Chain::Starknet => native_eth(Chain::Starknet),
520            Chain::ZkSync => native_eth(Chain::ZkSync),
521            Chain::Arbitrum => native_eth(Chain::Arbitrum),
522            Chain::Base => native_eth(Chain::Base),
523            Chain::Bsc => native_bsc(Chain::Bsc),
524            Chain::Unichain => native_eth(Chain::Unichain),
525            Chain::Polygon => native_pol(Chain::Polygon),
526            Chain::Plasma => native_xpl(Chain::Plasma),
527            Chain::Robinhood => native_eth(Chain::Robinhood),
528            Chain::Arc => native_arc_usdc(Chain::Arc),
529            Chain::Elysium => native_hype(Chain::Elysium),
530            Chain::Custom(id) => native_custom(*self, try_resolve_custom(id, chain_registry())?),
531        })
532    }
533
534    /// Returns the wrapper contract token, if the chain has one. Panics if a custom chain has no
535    /// registered config; use [`Chain::try_wrapped_native_token`] for a non-panicking variant.
536    pub fn wrapped_native_token(&self) -> Option<Token> {
537        expect_registered(self.try_wrapped_native_token())
538    }
539
540    /// Like [`Chain::wrapped_native_token`] but returns [`ChainConfigError::UnknownChain`] when a
541    /// custom chain has no registered config.
542    pub fn try_wrapped_native_token(&self) -> Result<Option<Token>, ChainConfigError> {
543        Ok(self
544            .try_native_asset()?
545            .wrapper()
546            .cloned())
547    }
548
549    /// Returns the chain's native asset representations and their economic relationship.
550    /// Panics if a custom chain has no registered config; use [`Chain::try_native_asset`] for a
551    /// non-panicking variant.
552    pub fn native_asset(&self) -> NativeAsset {
553        expect_registered(self.try_native_asset())
554    }
555
556    /// Like [`Chain::native_asset`] but returns [`ChainConfigError::UnknownChain`] when a custom
557    /// chain has no registered config.
558    pub fn try_native_asset(&self) -> Result<NativeAsset, ChainConfigError> {
559        Ok(match self {
560            Chain::Ethereum => NativeAsset::Wrapper {
561                native: native_eth(Chain::Ethereum),
562                wrapper: wrapped_native_eth(
563                    Chain::Ethereum,
564                    "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
565                ),
566            },
567            // It was decided that STRK token will be tracked as a dedicated AccountBalance on
568            // Starknet accounts and ETH balances will be tracked as a native balance.
569            Chain::Starknet => NativeAsset::NativeOnly { native: native_eth(Chain::Starknet) },
570            Chain::ZkSync => NativeAsset::Wrapper {
571                native: native_eth(Chain::ZkSync),
572                wrapper: wrapped_native_eth(
573                    Chain::ZkSync,
574                    "0x5AEa5775959fBC2557Cc8789bC1bf90A239D9a91",
575                ),
576            },
577            Chain::Arbitrum => NativeAsset::Wrapper {
578                native: native_eth(Chain::Arbitrum),
579                wrapper: wrapped_native_eth(
580                    Chain::Arbitrum,
581                    "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
582                ),
583            },
584            Chain::Base => NativeAsset::Wrapper {
585                native: native_eth(Chain::Base),
586                wrapper: wrapped_native_eth(
587                    Chain::Base,
588                    "0x4200000000000000000000000000000000000006",
589                ),
590            },
591            Chain::Bsc => NativeAsset::Wrapper {
592                native: native_bsc(Chain::Bsc),
593                wrapper: wrapped_native_bsc(
594                    Chain::Bsc,
595                    "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",
596                ),
597            },
598            Chain::Unichain => NativeAsset::Wrapper {
599                native: native_eth(Chain::Unichain),
600                wrapper: wrapped_native_eth(
601                    Chain::Unichain,
602                    "0x4200000000000000000000000000000000000006",
603                ),
604            },
605            Chain::Polygon => NativeAsset::Wrapper {
606                native: native_pol(Chain::Polygon),
607                wrapper: wrapped_native_pol(
608                    Chain::Polygon,
609                    "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",
610                ),
611            },
612            Chain::Plasma => NativeAsset::Wrapper {
613                native: native_xpl(Chain::Plasma),
614                wrapper: wrapped_native_xpl(
615                    Chain::Plasma,
616                    "0x6100E367285b01F48D07953803A2d8dCA5D19873",
617                ),
618            },
619            Chain::Robinhood => NativeAsset::Wrapper {
620                native: native_eth(Chain::Robinhood),
621                // aeWETH is the Arbitrum bridge wrapper for native ETH and exposes WETH9.
622                wrapper: wrapped_native_eth(
623                    Chain::Robinhood,
624                    "0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73",
625                ),
626            },
627            Chain::Arc => NativeAsset::SharedBalance {
628                // Arc's native USDC pays gas; its ERC-20 interface shares that balance at 6
629                // decimals, so it has no wrapper. https://docs.arc.network/arc/concepts/stablecoin-native-model
630                native: native_arc_usdc(Chain::Arc),
631                routable: routable_arc_usdc(Chain::Arc),
632            },
633            Chain::Elysium => NativeAsset::Wrapper {
634                native: native_hype(Chain::Elysium),
635                // Canonical WHYPE on Elysium mainnet. Reported by Elysium ecosystem
636                // trackers and cross-checked on 5 Nov 2026; re-verify against the
637                // official contract list when Kinetiq publishes it at launch.
638                wrapper: wrapped_native_hype(
639                    Chain::Elysium,
640                    "0xbA876237B0F021A6c6D852d6c26E107997cC5E81",
641                ),
642            },
643            Chain::Custom(id) => {
644                let config = try_resolve_custom(id, chain_registry())?;
645                let native = native_custom(*self, config);
646                let wrapper = wrapped_native_custom(*self, config);
647                if native.address == wrapper.address {
648                    NativeAsset::NativeOnly { native }
649                } else {
650                    NativeAsset::Wrapper { native, wrapper }
651                }
652            }
653        })
654    }
655
656    /// Returns the expected block time in seconds for the chain. Panics if a custom chain has no
657    /// registered config; use [`Chain::try_block_time_secs`] for a non-panicking variant.
658    pub fn block_time_secs(&self) -> u64 {
659        expect_registered(self.try_block_time_secs())
660    }
661
662    /// Like [`Chain::block_time_secs`] but returns [`ChainConfigError::UnknownChain`] when a custom
663    /// chain has no registered config.
664    pub fn try_block_time_secs(&self) -> Result<u64, ChainConfigError> {
665        Ok(match self {
666            Chain::Ethereum => 12,
667            Chain::Starknet => 2,
668            Chain::ZkSync => 3,
669            Chain::Arbitrum => 1,
670            Chain::Base => 2,
671            Chain::Bsc => 1,
672            Chain::Unichain => 1,
673            Chain::Polygon => 2,
674            Chain::Plasma => 1,
675            Chain::Robinhood => 1,
676            // Arc produces sub-second blocks; integer-second APIs use the one-second ceiling.
677            Chain::Arc => 1,
678            // Elysium produces 100 ms blocks; same integer-second ceiling.
679            Chain::Elysium => 1,
680            Chain::Custom(id) => try_resolve_custom(id, chain_registry())?.block_time_secs,
681        })
682    }
683}
684
685#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash, Default)]
686pub struct ExtractorIdentity {
687    pub chain: Chain,
688    pub name: String,
689}
690
691impl ExtractorIdentity {
692    pub fn new(chain: Chain, name: &str) -> Self {
693        Self { chain, name: name.to_owned() }
694    }
695}
696
697impl std::fmt::Display for ExtractorIdentity {
698    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
699        write!(f, "{}:{}", self.chain, self.name)
700    }
701}
702
703impl From<ExtractorIdentity> for dto::ExtractorIdentity {
704    fn from(value: ExtractorIdentity) -> Self {
705        dto::ExtractorIdentity { chain: value.chain.into(), name: value.name }
706    }
707}
708
709impl From<dto::ExtractorIdentity> for ExtractorIdentity {
710    fn from(value: dto::ExtractorIdentity) -> Self {
711        Self { chain: value.chain.into(), name: value.name }
712    }
713}
714
715#[derive(Debug, PartialEq, Clone)]
716pub struct ExtractionState {
717    pub name: String,
718    pub chain: Chain,
719    pub attributes: serde_json::Value,
720    pub cursor: Vec<u8>,
721    pub block_hash: Bytes,
722}
723
724impl ExtractionState {
725    pub fn new(
726        name: String,
727        chain: Chain,
728        attributes: Option<serde_json::Value>,
729        cursor: &[u8],
730        block_hash: Bytes,
731    ) -> Self {
732        ExtractionState {
733            name,
734            chain,
735            attributes: attributes.unwrap_or_default(),
736            cursor: cursor.to_vec(),
737            block_hash,
738        }
739    }
740}
741
742#[derive(PartialEq, Debug, Clone, Default, Deserialize, Serialize)]
743pub enum ImplementationType {
744    #[default]
745    Vm,
746    Custom,
747}
748
749#[derive(PartialEq, Debug, Clone, Default, Deserialize, Serialize)]
750pub enum FinancialType {
751    #[default]
752    Swap,
753    Psm,
754    Debt,
755    Leverage,
756}
757
758#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
759pub struct ProtocolType {
760    pub name: String,
761    pub financial_type: FinancialType,
762    pub attribute_schema: Option<serde_json::Value>,
763    pub implementation: ImplementationType,
764}
765
766impl ProtocolType {
767    pub fn new(
768        name: String,
769        financial_type: FinancialType,
770        attribute_schema: Option<serde_json::Value>,
771        implementation: ImplementationType,
772    ) -> Self {
773        ProtocolType { name, financial_type, attribute_schema, implementation }
774    }
775}
776
777#[derive(Debug, PartialEq, Eq, Default, Copy, Clone, Deserialize, Serialize, DeepSizeOf)]
778pub enum ChangeType {
779    #[default]
780    Update,
781    Deletion,
782    Creation,
783}
784
785#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
786pub struct ContractId {
787    pub address: Address,
788    pub chain: Chain,
789}
790
791/// Uniquely identifies a contract on a specific chain.
792impl ContractId {
793    pub fn new(chain: Chain, address: Address) -> Self {
794        Self { address, chain }
795    }
796
797    pub fn address(&self) -> &Address {
798        &self.address
799    }
800}
801
802impl Display for ContractId {
803    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
804        write!(f, "{:?}: 0x{}", self.chain, hex::encode(&self.address))
805    }
806}
807
808#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
809pub struct PaginationParams {
810    pub page: i64,
811    pub page_size: i64,
812}
813
814impl PaginationParams {
815    pub fn new(page: i64, page_size: i64) -> Self {
816        Self { page, page_size }
817    }
818
819    pub fn offset(&self) -> i64 {
820        self.page * self.page_size
821    }
822}
823
824impl From<&dto::PaginationParams> for PaginationParams {
825    fn from(value: &dto::PaginationParams) -> Self {
826        PaginationParams { page: value.page, page_size: value.page_size }
827    }
828}
829
830#[derive(Error, Debug, PartialEq)]
831pub enum MergeError {
832    #[error("Can't merge {0} from differring idendities: Expected {1}, got {2}")]
833    IdMismatch(String, String, String),
834    #[error("Can't merge {0} from different blocks: 0x{1:x} != 0x{2:x}")]
835    BlockMismatch(String, Bytes, Bytes),
836    #[error("Can't merge {0} from the same transaction: 0x{1:x}")]
837    SameTransaction(String, Bytes),
838    #[error("Can't merge {0} with lower transaction index: {1} > {2}")]
839    TransactionOrderError(String, u64, u64),
840    #[error("Cannot merge: {0}")]
841    InvalidState(String),
842}
843
844// The custom-chain tests below install the process-wide chain registry, which is a set-once
845// `OnceLock`. They must run in isolated processes (we use nextest), so each test gets a fresh
846// registry; under a shared-process runner they would contend over the same global.
847#[cfg(test)]
848mod tests {
849    use arrayvec::ArrayString;
850
851    use super::{
852        chain_config::{
853            init_chain_registry, ChainAddress, ChainConfigError, ChainTokenConfig, TvlThresholds,
854        },
855        *,
856    };
857
858    fn test_config() -> CustomChainConfig {
859        CustomChainConfig::try_new(
860            "testchain",
861            9999,
862            5,
863            ChainTokenConfig::try_new("0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "TST", 18)
864                .unwrap(),
865            ChainTokenConfig::try_new("0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "WTST", 18)
866                .unwrap(),
867            TvlThresholds::new(50.0, 500.0),
868        )
869        .unwrap()
870    }
871
872    fn init_test_registry() {
873        init_chain_registry(ChainConfigRegistry::from_configs([test_config()]).unwrap())
874            .expect("chain registry already initialised; run tests under nextest");
875    }
876
877    #[test]
878    fn test_custom_chain_display() {
879        init_test_registry();
880        assert_eq!(
881            Chain::custom("testchain")
882                .unwrap()
883                .to_string(),
884            "testchain"
885        );
886    }
887
888    #[test]
889    fn test_from_str_custom_returns_err() {
890        assert!("custom".parse::<Chain>().is_err());
891        assert!("unknown".parse::<Chain>().is_err());
892    }
893
894    #[test]
895    fn test_custom_unregistered_returns_err() {
896        init_test_registry();
897        assert_eq!(Chain::custom("nope"), Err(ChainConfigError::UnknownChain("nope".to_owned())));
898    }
899
900    #[test]
901    fn test_from_dto_registered_custom_roundtrips() {
902        init_test_registry();
903        let dto_chain: dto::Chain = Chain::custom("testchain")
904            .unwrap()
905            .into();
906        let chain: Chain = dto_chain.into();
907        assert_eq!(chain.id(), 9999);
908    }
909
910    #[test]
911    #[should_panic(expected = "no registered config")]
912    fn test_from_dto_unregistered_custom_panics() {
913        let dto_chain = dto::Chain::Custom(ArrayString::from("nope").unwrap());
914        #[expect(
915            clippy::let_underscore_must_use,
916            reason = "the conversion panics before yielding a value"
917        )]
918        let _: Chain = dto_chain.into();
919    }
920
921    #[test]
922    fn test_try_accessors_ok_for_registered_custom() {
923        init_test_registry();
924        let chain = Chain::custom("testchain").unwrap();
925        assert_eq!(chain.try_id().unwrap(), 9999);
926        assert_eq!(chain.try_block_time_secs().unwrap(), 5);
927        assert_eq!(
928            chain
929                .try_default_tvl_threshold(TvlThresholdTier::Low)
930                .unwrap(),
931            50.0
932        );
933        assert_eq!(chain.try_native_token().unwrap().symbol, "TST");
934        assert_eq!(
935            chain
936                .try_wrapped_native_token()
937                .unwrap()
938                .expect("testchain should have a wrapper")
939                .symbol,
940            "WTST"
941        );
942    }
943
944    #[test]
945    fn test_try_accessors_err_for_unregistered_custom() {
946        // A `CustomChainId` that bypassed registry validation (only reachable via direct
947        // deserialization) surfaces as an error rather than a panic through the `try_*` accessors.
948        let ghost: Chain = serde_json::from_str(r#"{"custom":"ghostchain"}"#).unwrap();
949        assert_eq!(ghost.try_id(), Err(ChainConfigError::UnknownChain("ghostchain".to_owned())));
950        assert!(ghost.try_native_token().is_err());
951    }
952
953    #[test]
954    fn test_chain_stays_small() {
955        // Regression: Custom carries only a 32-char name, so Chain stays a small Copy enum rather
956        // than embedding the full config (~200 bytes) as it did when Custom held CustomChainConfig.
957        assert!(
958            std::mem::size_of::<Chain>() <= 40,
959            "Chain is {} bytes",
960            std::mem::size_of::<Chain>()
961        );
962    }
963
964    #[test]
965    fn test_custom_chain_id() {
966        init_test_registry();
967        let chain = Chain::custom("testchain").unwrap();
968        assert_eq!(chain.id(), 9999);
969    }
970
971    #[test]
972    fn test_custom_chain_tvl_thresholds() {
973        init_test_registry();
974        let chain = Chain::custom("testchain").unwrap();
975        assert_eq!(chain.default_tvl_threshold(TvlThresholdTier::Low), 50.0);
976        assert_eq!(chain.default_tvl_threshold(TvlThresholdTier::Medium), 500.0);
977    }
978
979    #[test]
980    fn test_custom_chain_native_token() {
981        init_test_registry();
982        let chain = Chain::custom("testchain").unwrap();
983        let token = chain.native_token();
984        assert_eq!(token.symbol, "TST");
985        assert_eq!(token.decimals, 18);
986        assert_eq!(token.chain, chain);
987        assert_eq!(token.address, Bytes::from(vec![0xAA; 20]));
988    }
989
990    #[test]
991    fn test_custom_chain_wrapped_native_token() {
992        init_test_registry();
993        let chain = Chain::custom("testchain").unwrap();
994        let token = chain
995            .wrapped_native_token()
996            .expect("testchain should have a wrapper");
997        assert_eq!(token.symbol, "WTST");
998        assert_eq!(token.chain, chain);
999        assert_eq!(token.address, Bytes::from(vec![0xBB; 20]));
1000    }
1001
1002    #[test]
1003    fn test_custom_chain_with_same_native_and_wrapped_address_is_native_only() {
1004        let address = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
1005        let config = CustomChainConfig::try_new(
1006            "nativeonly",
1007            9998,
1008            5,
1009            ChainTokenConfig::try_new(address, "TST", 18).unwrap(),
1010            ChainTokenConfig::try_new(address, "WTST", 18).unwrap(),
1011            TvlThresholds::new(50.0, 500.0),
1012        )
1013        .unwrap();
1014        init_chain_registry(ChainConfigRegistry::from_configs([config]).unwrap())
1015            .expect("chain registry already initialised; run tests under nextest");
1016
1017        let chain = Chain::custom("nativeonly").unwrap();
1018        let asset = chain.native_asset();
1019
1020        assert!(asset.routable_token().is_none());
1021        assert!(chain.wrapped_native_token().is_none());
1022        assert_eq!(asset.representations().count(), 1);
1023    }
1024
1025    #[test]
1026    fn test_chain_address_new_rejects_oversized_input() {
1027        assert_eq!(ChainAddress::new(&[0u8; 33]), Err(ChainConfigError::AddressTooLong(33)));
1028    }
1029
1030    #[test]
1031    fn test_robinhood_chain_id() {
1032        assert_eq!(Chain::Robinhood.id(), 4663);
1033    }
1034
1035    #[test]
1036    fn test_robinhood_chain_display() {
1037        assert_eq!(Chain::Robinhood.to_string(), "robinhood");
1038    }
1039
1040    #[test]
1041    fn test_robinhood_chain_from_str() {
1042        assert_eq!("robinhood".parse::<Chain>().unwrap(), Chain::Robinhood);
1043    }
1044
1045    #[test]
1046    fn test_robinhood_native_token() {
1047        let token = Chain::Robinhood.native_token();
1048        assert_eq!(token.symbol, "ETH");
1049        assert_eq!(token.chain, Chain::Robinhood);
1050        assert_eq!(
1051            token.address,
1052            Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap()
1053        );
1054    }
1055
1056    #[test]
1057    fn test_robinhood_wrapped_native_token() {
1058        let token = Chain::Robinhood
1059            .wrapped_native_token()
1060            .expect("Robinhood should have a wrapper");
1061        assert_eq!(token.symbol, "WETH");
1062        assert_eq!(token.chain, Chain::Robinhood);
1063        assert_eq!(
1064            token.address,
1065            Bytes::from_str("0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73").unwrap()
1066        );
1067    }
1068
1069    #[test]
1070    fn test_robinhood_default_tvl_threshold() {
1071        assert_eq!(Chain::Robinhood.default_tvl_threshold(TvlThresholdTier::Low), 10.0);
1072        assert_eq!(Chain::Robinhood.default_tvl_threshold(TvlThresholdTier::Medium), 100.0);
1073    }
1074
1075    #[test]
1076    fn test_robinhood_block_time_secs() {
1077        assert_eq!(Chain::Robinhood.block_time_secs(), 1);
1078    }
1079
1080    #[test]
1081    fn test_arc_chain_identity_and_dto_round_trip() {
1082        assert_eq!(Chain::Arc.id(), 5042);
1083        assert_eq!(Chain::Arc.to_string(), "arc");
1084        assert_eq!("arc".parse::<Chain>().unwrap(), Chain::Arc);
1085
1086        let dto_chain: dto::Chain = Chain::Arc.into();
1087        assert_eq!(dto_chain, dto::Chain::Arc);
1088        assert_eq!(Chain::from(dto_chain), Chain::Arc);
1089        assert_eq!(serde_json::to_string(&Chain::Arc).unwrap(), r#""arc""#);
1090        assert_eq!(serde_json::from_str::<Chain>(r#""arc""#).unwrap(), Chain::Arc);
1091
1092        let native = Chain::Arc.native_token();
1093        assert_eq!(native.symbol, "USDC");
1094        assert_eq!(native.decimals, 18);
1095        assert_eq!(native.address, Bytes::from([0u8; 20]));
1096
1097        assert!(Chain::Arc
1098            .wrapped_native_token()
1099            .is_none());
1100        let native_asset = Chain::Arc.native_asset();
1101        let routable = native_asset
1102            .routable_token()
1103            .expect("Arc should expose its routable USDC representation");
1104        assert_eq!(routable.symbol, "USDC");
1105        assert_eq!(routable.decimals, 6);
1106        assert_eq!(
1107            routable.address,
1108            Bytes::from_str("0x3600000000000000000000000000000000000000").unwrap()
1109        );
1110
1111        assert_eq!(Chain::Arc.block_time_secs(), 1);
1112        assert_eq!(Chain::Arc.default_tvl_threshold(TvlThresholdTier::Low), 20_000.0);
1113        assert_eq!(Chain::Arc.default_tvl_threshold(TvlThresholdTier::Medium), 200_000.0);
1114    }
1115
1116    #[test]
1117    fn test_arc_native_asset_uses_shared_balance_without_wrapper() {
1118        let asset = Chain::Arc.native_asset();
1119
1120        assert_eq!(asset.native_token(), &Chain::Arc.native_token());
1121        assert!(matches!(asset, NativeAsset::SharedBalance { .. }));
1122        assert!(asset.wrapper().is_none());
1123
1124        let representations: Vec<_> = asset
1125            .representations()
1126            .map(|token| (token.address.clone(), token.decimals))
1127            .collect();
1128        assert_eq!(
1129            representations,
1130            vec![
1131                (Bytes::from([0u8; 20]), 18),
1132                (Bytes::from_str("0x3600000000000000000000000000000000000000").unwrap(), 6,),
1133            ]
1134        );
1135    }
1136
1137    #[test]
1138    fn test_elysium_chain_identity_and_native_asset() {
1139        assert_eq!(Chain::Elysium.id(), 99901);
1140        assert_eq!(Chain::Elysium.to_string(), "elysium");
1141        assert_eq!("elysium".parse::<Chain>().unwrap(), Chain::Elysium);
1142
1143        let dto_chain: dto::Chain = Chain::Elysium.into();
1144        assert_eq!(dto_chain, dto::Chain::Elysium);
1145        assert_eq!(Chain::from(dto_chain), Chain::Elysium);
1146        assert_eq!(serde_json::to_string(&Chain::Elysium).unwrap(), r#""elysium""#);
1147        assert_eq!(serde_json::from_str::<Chain>(r#""elysium""#).unwrap(), Chain::Elysium);
1148
1149        let native = Chain::Elysium.native_token();
1150        assert_eq!(native.symbol, "HYPE");
1151        assert_eq!(native.decimals, 18);
1152        assert_eq!(native.address, Bytes::from([0u8; 20]));
1153
1154        let wrapper = Chain::Elysium
1155            .wrapped_native_token()
1156            .expect("Elysium should have a WHYPE wrapper");
1157        assert_eq!(wrapper.symbol, "WHYPE");
1158        assert_eq!(wrapper.chain, Chain::Elysium);
1159        assert_eq!(
1160            wrapper.address,
1161            Bytes::from_str("0xbA876237B0F021A6c6D852d6c26E107997cC5E81").unwrap()
1162        );
1163
1164        let asset = Chain::Elysium.native_asset();
1165        assert!(matches!(asset, NativeAsset::Wrapper { .. }));
1166        assert_eq!(asset.representations().count(), 2);
1167
1168        assert_eq!(Chain::Elysium.block_time_secs(), 1);
1169        assert_eq!(Chain::Elysium.default_tvl_threshold(TvlThresholdTier::Low), 250.0);
1170        assert_eq!(Chain::Elysium.default_tvl_threshold(TvlThresholdTier::Medium), 2_500.0);
1171    }
1172
1173    #[test]
1174    fn test_existing_native_asset_relationships_remain_compatible() {
1175        let ethereum = Chain::Ethereum.native_asset();
1176        assert!(matches!(ethereum, NativeAsset::Wrapper { .. }));
1177        assert_eq!(ethereum.wrapper(), ethereum.routable_token());
1178        assert_eq!(
1179            ethereum.routable_token(),
1180            Chain::Ethereum
1181                .wrapped_native_token()
1182                .as_ref()
1183        );
1184
1185        let starknet = Chain::Starknet.native_asset();
1186        assert!(matches!(starknet, NativeAsset::NativeOnly { .. }));
1187        assert!(starknet.wrapper().is_none());
1188        assert!(starknet.routable_token().is_none());
1189        assert!(Chain::Starknet
1190            .wrapped_native_token()
1191            .is_none());
1192        assert_eq!(starknet.representations().count(), 1);
1193    }
1194
1195    #[test]
1196    fn test_chain_address_as_bytes_returns_active_slice() {
1197        let addr = ChainAddress::new(&[0xAA; 20]).unwrap();
1198        assert_eq!(addr.as_bytes(), &[0xAA; 20]);
1199        assert_eq!(addr.as_bytes().len(), 20);
1200    }
1201}