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            // Base produces 200 ms blocks; same integer-second ceiling.
671            Chain::Base => 1,
672            Chain::Bsc => 1,
673            Chain::Unichain => 1,
674            Chain::Polygon => 2,
675            Chain::Plasma => 1,
676            Chain::Robinhood => 1,
677            // Arc produces sub-second blocks; integer-second APIs use the one-second ceiling.
678            Chain::Arc => 1,
679            // Elysium produces 100 ms blocks; same integer-second ceiling.
680            Chain::Elysium => 1,
681            Chain::Custom(id) => try_resolve_custom(id, chain_registry())?.block_time_secs,
682        })
683    }
684}
685
686#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash, Default)]
687pub struct ExtractorIdentity {
688    pub chain: Chain,
689    pub name: String,
690}
691
692impl ExtractorIdentity {
693    pub fn new(chain: Chain, name: &str) -> Self {
694        Self { chain, name: name.to_owned() }
695    }
696}
697
698impl std::fmt::Display for ExtractorIdentity {
699    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
700        write!(f, "{}:{}", self.chain, self.name)
701    }
702}
703
704impl From<ExtractorIdentity> for dto::ExtractorIdentity {
705    fn from(value: ExtractorIdentity) -> Self {
706        dto::ExtractorIdentity { chain: value.chain.into(), name: value.name }
707    }
708}
709
710impl From<dto::ExtractorIdentity> for ExtractorIdentity {
711    fn from(value: dto::ExtractorIdentity) -> Self {
712        Self { chain: value.chain.into(), name: value.name }
713    }
714}
715
716#[derive(Debug, PartialEq, Clone)]
717pub struct ExtractionState {
718    pub name: String,
719    pub chain: Chain,
720    pub attributes: serde_json::Value,
721    pub cursor: Vec<u8>,
722    pub block_hash: Bytes,
723}
724
725impl ExtractionState {
726    pub fn new(
727        name: String,
728        chain: Chain,
729        attributes: Option<serde_json::Value>,
730        cursor: &[u8],
731        block_hash: Bytes,
732    ) -> Self {
733        ExtractionState {
734            name,
735            chain,
736            attributes: attributes.unwrap_or_default(),
737            cursor: cursor.to_vec(),
738            block_hash,
739        }
740    }
741}
742
743#[derive(PartialEq, Debug, Clone, Default, Deserialize, Serialize)]
744pub enum ImplementationType {
745    #[default]
746    Vm,
747    Custom,
748}
749
750#[derive(PartialEq, Debug, Clone, Default, Deserialize, Serialize)]
751pub enum FinancialType {
752    #[default]
753    Swap,
754    Psm,
755    Debt,
756    Leverage,
757}
758
759#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
760pub struct ProtocolType {
761    pub name: String,
762    pub financial_type: FinancialType,
763    pub attribute_schema: Option<serde_json::Value>,
764    pub implementation: ImplementationType,
765}
766
767impl ProtocolType {
768    pub fn new(
769        name: String,
770        financial_type: FinancialType,
771        attribute_schema: Option<serde_json::Value>,
772        implementation: ImplementationType,
773    ) -> Self {
774        ProtocolType { name, financial_type, attribute_schema, implementation }
775    }
776}
777
778#[derive(Debug, PartialEq, Eq, Default, Copy, Clone, Deserialize, Serialize, DeepSizeOf)]
779pub enum ChangeType {
780    #[default]
781    Update,
782    Deletion,
783    Creation,
784}
785
786#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
787pub struct ContractId {
788    pub address: Address,
789    pub chain: Chain,
790}
791
792/// Uniquely identifies a contract on a specific chain.
793impl ContractId {
794    pub fn new(chain: Chain, address: Address) -> Self {
795        Self { address, chain }
796    }
797
798    pub fn address(&self) -> &Address {
799        &self.address
800    }
801}
802
803impl Display for ContractId {
804    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
805        write!(f, "{:?}: 0x{}", self.chain, hex::encode(&self.address))
806    }
807}
808
809#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
810pub struct PaginationParams {
811    pub page: i64,
812    pub page_size: i64,
813}
814
815impl PaginationParams {
816    pub fn new(page: i64, page_size: i64) -> Self {
817        Self { page, page_size }
818    }
819
820    pub fn offset(&self) -> i64 {
821        self.page * self.page_size
822    }
823}
824
825impl From<&dto::PaginationParams> for PaginationParams {
826    fn from(value: &dto::PaginationParams) -> Self {
827        PaginationParams { page: value.page, page_size: value.page_size }
828    }
829}
830
831#[derive(Error, Debug, PartialEq)]
832pub enum MergeError {
833    #[error("Can't merge {0} from differring idendities: Expected {1}, got {2}")]
834    IdMismatch(String, String, String),
835    #[error("Can't merge {0} from different blocks: 0x{1:x} != 0x{2:x}")]
836    BlockMismatch(String, Bytes, Bytes),
837    #[error("Can't merge {0} from the same transaction: 0x{1:x}")]
838    SameTransaction(String, Bytes),
839    #[error("Can't merge {0} with lower transaction index: {1} > {2}")]
840    TransactionOrderError(String, u64, u64),
841    #[error("Cannot merge: {0}")]
842    InvalidState(String),
843}
844
845// The custom-chain tests below install the process-wide chain registry, which is a set-once
846// `OnceLock`. They must run in isolated processes (we use nextest), so each test gets a fresh
847// registry; under a shared-process runner they would contend over the same global.
848#[cfg(test)]
849mod tests {
850    use arrayvec::ArrayString;
851
852    use super::{
853        chain_config::{
854            init_chain_registry, ChainAddress, ChainConfigError, ChainTokenConfig, TvlThresholds,
855        },
856        *,
857    };
858
859    fn test_config() -> CustomChainConfig {
860        CustomChainConfig::try_new(
861            "testchain",
862            9999,
863            5,
864            ChainTokenConfig::try_new("0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "TST", 18)
865                .unwrap(),
866            ChainTokenConfig::try_new("0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "WTST", 18)
867                .unwrap(),
868            TvlThresholds::new(50.0, 500.0),
869        )
870        .unwrap()
871    }
872
873    fn init_test_registry() {
874        init_chain_registry(ChainConfigRegistry::from_configs([test_config()]).unwrap())
875            .expect("chain registry already initialised; run tests under nextest");
876    }
877
878    #[test]
879    fn test_custom_chain_display() {
880        init_test_registry();
881        assert_eq!(
882            Chain::custom("testchain")
883                .unwrap()
884                .to_string(),
885            "testchain"
886        );
887    }
888
889    #[test]
890    fn test_from_str_custom_returns_err() {
891        assert!("custom".parse::<Chain>().is_err());
892        assert!("unknown".parse::<Chain>().is_err());
893    }
894
895    #[test]
896    fn test_custom_unregistered_returns_err() {
897        init_test_registry();
898        assert_eq!(Chain::custom("nope"), Err(ChainConfigError::UnknownChain("nope".to_owned())));
899    }
900
901    #[test]
902    fn test_from_dto_registered_custom_roundtrips() {
903        init_test_registry();
904        let dto_chain: dto::Chain = Chain::custom("testchain")
905            .unwrap()
906            .into();
907        let chain: Chain = dto_chain.into();
908        assert_eq!(chain.id(), 9999);
909    }
910
911    #[test]
912    #[should_panic(expected = "no registered config")]
913    fn test_from_dto_unregistered_custom_panics() {
914        let dto_chain = dto::Chain::Custom(ArrayString::from("nope").unwrap());
915        #[expect(
916            clippy::let_underscore_must_use,
917            reason = "the conversion panics before yielding a value"
918        )]
919        let _: Chain = dto_chain.into();
920    }
921
922    #[test]
923    fn test_try_accessors_ok_for_registered_custom() {
924        init_test_registry();
925        let chain = Chain::custom("testchain").unwrap();
926        assert_eq!(chain.try_id().unwrap(), 9999);
927        assert_eq!(chain.try_block_time_secs().unwrap(), 5);
928        assert_eq!(
929            chain
930                .try_default_tvl_threshold(TvlThresholdTier::Low)
931                .unwrap(),
932            50.0
933        );
934        assert_eq!(chain.try_native_token().unwrap().symbol, "TST");
935        assert_eq!(
936            chain
937                .try_wrapped_native_token()
938                .unwrap()
939                .expect("testchain should have a wrapper")
940                .symbol,
941            "WTST"
942        );
943    }
944
945    #[test]
946    fn test_try_accessors_err_for_unregistered_custom() {
947        // A `CustomChainId` that bypassed registry validation (only reachable via direct
948        // deserialization) surfaces as an error rather than a panic through the `try_*` accessors.
949        let ghost: Chain = serde_json::from_str(r#"{"custom":"ghostchain"}"#).unwrap();
950        assert_eq!(ghost.try_id(), Err(ChainConfigError::UnknownChain("ghostchain".to_owned())));
951        assert!(ghost.try_native_token().is_err());
952    }
953
954    #[test]
955    fn test_chain_stays_small() {
956        // Regression: Custom carries only a 32-char name, so Chain stays a small Copy enum rather
957        // than embedding the full config (~200 bytes) as it did when Custom held CustomChainConfig.
958        assert!(
959            std::mem::size_of::<Chain>() <= 40,
960            "Chain is {} bytes",
961            std::mem::size_of::<Chain>()
962        );
963    }
964
965    #[test]
966    fn test_custom_chain_id() {
967        init_test_registry();
968        let chain = Chain::custom("testchain").unwrap();
969        assert_eq!(chain.id(), 9999);
970    }
971
972    #[test]
973    fn test_custom_chain_tvl_thresholds() {
974        init_test_registry();
975        let chain = Chain::custom("testchain").unwrap();
976        assert_eq!(chain.default_tvl_threshold(TvlThresholdTier::Low), 50.0);
977        assert_eq!(chain.default_tvl_threshold(TvlThresholdTier::Medium), 500.0);
978    }
979
980    #[test]
981    fn test_custom_chain_native_token() {
982        init_test_registry();
983        let chain = Chain::custom("testchain").unwrap();
984        let token = chain.native_token();
985        assert_eq!(token.symbol, "TST");
986        assert_eq!(token.decimals, 18);
987        assert_eq!(token.chain, chain);
988        assert_eq!(token.address, Bytes::from(vec![0xAA; 20]));
989    }
990
991    #[test]
992    fn test_custom_chain_wrapped_native_token() {
993        init_test_registry();
994        let chain = Chain::custom("testchain").unwrap();
995        let token = chain
996            .wrapped_native_token()
997            .expect("testchain should have a wrapper");
998        assert_eq!(token.symbol, "WTST");
999        assert_eq!(token.chain, chain);
1000        assert_eq!(token.address, Bytes::from(vec![0xBB; 20]));
1001    }
1002
1003    #[test]
1004    fn test_custom_chain_with_same_native_and_wrapped_address_is_native_only() {
1005        let address = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
1006        let config = CustomChainConfig::try_new(
1007            "nativeonly",
1008            9998,
1009            5,
1010            ChainTokenConfig::try_new(address, "TST", 18).unwrap(),
1011            ChainTokenConfig::try_new(address, "WTST", 18).unwrap(),
1012            TvlThresholds::new(50.0, 500.0),
1013        )
1014        .unwrap();
1015        init_chain_registry(ChainConfigRegistry::from_configs([config]).unwrap())
1016            .expect("chain registry already initialised; run tests under nextest");
1017
1018        let chain = Chain::custom("nativeonly").unwrap();
1019        let asset = chain.native_asset();
1020
1021        assert!(asset.routable_token().is_none());
1022        assert!(chain.wrapped_native_token().is_none());
1023        assert_eq!(asset.representations().count(), 1);
1024    }
1025
1026    #[test]
1027    fn test_chain_address_new_rejects_oversized_input() {
1028        assert_eq!(ChainAddress::new(&[0u8; 33]), Err(ChainConfigError::AddressTooLong(33)));
1029    }
1030
1031    #[test]
1032    fn test_robinhood_chain_id() {
1033        assert_eq!(Chain::Robinhood.id(), 4663);
1034    }
1035
1036    #[test]
1037    fn test_robinhood_chain_display() {
1038        assert_eq!(Chain::Robinhood.to_string(), "robinhood");
1039    }
1040
1041    #[test]
1042    fn test_robinhood_chain_from_str() {
1043        assert_eq!("robinhood".parse::<Chain>().unwrap(), Chain::Robinhood);
1044    }
1045
1046    #[test]
1047    fn test_robinhood_native_token() {
1048        let token = Chain::Robinhood.native_token();
1049        assert_eq!(token.symbol, "ETH");
1050        assert_eq!(token.chain, Chain::Robinhood);
1051        assert_eq!(
1052            token.address,
1053            Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap()
1054        );
1055    }
1056
1057    #[test]
1058    fn test_robinhood_wrapped_native_token() {
1059        let token = Chain::Robinhood
1060            .wrapped_native_token()
1061            .expect("Robinhood should have a wrapper");
1062        assert_eq!(token.symbol, "WETH");
1063        assert_eq!(token.chain, Chain::Robinhood);
1064        assert_eq!(
1065            token.address,
1066            Bytes::from_str("0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73").unwrap()
1067        );
1068    }
1069
1070    #[test]
1071    fn test_robinhood_default_tvl_threshold() {
1072        assert_eq!(Chain::Robinhood.default_tvl_threshold(TvlThresholdTier::Low), 10.0);
1073        assert_eq!(Chain::Robinhood.default_tvl_threshold(TvlThresholdTier::Medium), 100.0);
1074    }
1075
1076    #[test]
1077    fn test_robinhood_block_time_secs() {
1078        assert_eq!(Chain::Robinhood.block_time_secs(), 1);
1079    }
1080
1081    #[test]
1082    fn test_base_block_time_secs() {
1083        assert_eq!(Chain::Base.block_time_secs(), 1);
1084    }
1085
1086    #[test]
1087    fn test_arc_chain_identity_and_dto_round_trip() {
1088        assert_eq!(Chain::Arc.id(), 5042);
1089        assert_eq!(Chain::Arc.to_string(), "arc");
1090        assert_eq!("arc".parse::<Chain>().unwrap(), Chain::Arc);
1091
1092        let dto_chain: dto::Chain = Chain::Arc.into();
1093        assert_eq!(dto_chain, dto::Chain::Arc);
1094        assert_eq!(Chain::from(dto_chain), Chain::Arc);
1095        assert_eq!(serde_json::to_string(&Chain::Arc).unwrap(), r#""arc""#);
1096        assert_eq!(serde_json::from_str::<Chain>(r#""arc""#).unwrap(), Chain::Arc);
1097
1098        let native = Chain::Arc.native_token();
1099        assert_eq!(native.symbol, "USDC");
1100        assert_eq!(native.decimals, 18);
1101        assert_eq!(native.address, Bytes::from([0u8; 20]));
1102
1103        assert!(Chain::Arc
1104            .wrapped_native_token()
1105            .is_none());
1106        let native_asset = Chain::Arc.native_asset();
1107        let routable = native_asset
1108            .routable_token()
1109            .expect("Arc should expose its routable USDC representation");
1110        assert_eq!(routable.symbol, "USDC");
1111        assert_eq!(routable.decimals, 6);
1112        assert_eq!(
1113            routable.address,
1114            Bytes::from_str("0x3600000000000000000000000000000000000000").unwrap()
1115        );
1116
1117        assert_eq!(Chain::Arc.block_time_secs(), 1);
1118        assert_eq!(Chain::Arc.default_tvl_threshold(TvlThresholdTier::Low), 20_000.0);
1119        assert_eq!(Chain::Arc.default_tvl_threshold(TvlThresholdTier::Medium), 200_000.0);
1120    }
1121
1122    #[test]
1123    fn test_arc_native_asset_uses_shared_balance_without_wrapper() {
1124        let asset = Chain::Arc.native_asset();
1125
1126        assert_eq!(asset.native_token(), &Chain::Arc.native_token());
1127        assert!(matches!(asset, NativeAsset::SharedBalance { .. }));
1128        assert!(asset.wrapper().is_none());
1129
1130        let representations: Vec<_> = asset
1131            .representations()
1132            .map(|token| (token.address.clone(), token.decimals))
1133            .collect();
1134        assert_eq!(
1135            representations,
1136            vec![
1137                (Bytes::from([0u8; 20]), 18),
1138                (Bytes::from_str("0x3600000000000000000000000000000000000000").unwrap(), 6,),
1139            ]
1140        );
1141    }
1142
1143    #[test]
1144    fn test_elysium_chain_identity_and_native_asset() {
1145        assert_eq!(Chain::Elysium.id(), 99901);
1146        assert_eq!(Chain::Elysium.to_string(), "elysium");
1147        assert_eq!("elysium".parse::<Chain>().unwrap(), Chain::Elysium);
1148
1149        let dto_chain: dto::Chain = Chain::Elysium.into();
1150        assert_eq!(dto_chain, dto::Chain::Elysium);
1151        assert_eq!(Chain::from(dto_chain), Chain::Elysium);
1152        assert_eq!(serde_json::to_string(&Chain::Elysium).unwrap(), r#""elysium""#);
1153        assert_eq!(serde_json::from_str::<Chain>(r#""elysium""#).unwrap(), Chain::Elysium);
1154
1155        let native = Chain::Elysium.native_token();
1156        assert_eq!(native.symbol, "HYPE");
1157        assert_eq!(native.decimals, 18);
1158        assert_eq!(native.address, Bytes::from([0u8; 20]));
1159
1160        let wrapper = Chain::Elysium
1161            .wrapped_native_token()
1162            .expect("Elysium should have a WHYPE wrapper");
1163        assert_eq!(wrapper.symbol, "WHYPE");
1164        assert_eq!(wrapper.chain, Chain::Elysium);
1165        assert_eq!(
1166            wrapper.address,
1167            Bytes::from_str("0xbA876237B0F021A6c6D852d6c26E107997cC5E81").unwrap()
1168        );
1169
1170        let asset = Chain::Elysium.native_asset();
1171        assert!(matches!(asset, NativeAsset::Wrapper { .. }));
1172        assert_eq!(asset.representations().count(), 2);
1173
1174        assert_eq!(Chain::Elysium.block_time_secs(), 1);
1175        assert_eq!(Chain::Elysium.default_tvl_threshold(TvlThresholdTier::Low), 250.0);
1176        assert_eq!(Chain::Elysium.default_tvl_threshold(TvlThresholdTier::Medium), 2_500.0);
1177    }
1178
1179    #[test]
1180    fn test_existing_native_asset_relationships_remain_compatible() {
1181        let ethereum = Chain::Ethereum.native_asset();
1182        assert!(matches!(ethereum, NativeAsset::Wrapper { .. }));
1183        assert_eq!(ethereum.wrapper(), ethereum.routable_token());
1184        assert_eq!(
1185            ethereum.routable_token(),
1186            Chain::Ethereum
1187                .wrapped_native_token()
1188                .as_ref()
1189        );
1190
1191        let starknet = Chain::Starknet.native_asset();
1192        assert!(matches!(starknet, NativeAsset::NativeOnly { .. }));
1193        assert!(starknet.wrapper().is_none());
1194        assert!(starknet.routable_token().is_none());
1195        assert!(Chain::Starknet
1196            .wrapped_native_token()
1197            .is_none());
1198        assert_eq!(starknet.representations().count(), 1);
1199    }
1200
1201    #[test]
1202    fn test_chain_address_as_bytes_returns_active_slice() {
1203        let addr = ChainAddress::new(&[0xAA; 20]).unwrap();
1204        assert_eq!(addr.as_bytes(), &[0xAA; 20]);
1205        assert_eq!(addr.as_bytes().len(), 20);
1206    }
1207}