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
22pub type Address = Bytes;
25
26pub type BlockHash = Bytes;
29
30pub type TxHash = Bytes;
33
34pub type Code = Bytes;
36
37pub type CodeHash = Bytes;
39
40pub type Balance = Bytes;
42
43pub type StoreKey = Bytes;
45
46pub type AttrStoreKey = String;
48
49pub type StoreVal = Bytes;
51
52pub type ContractStore = HashMap<StoreKey, StoreVal>;
54pub type ContractStoreDeltas = HashMap<StoreKey, Option<StoreVal>>;
55pub type AccountToContractStoreDeltas = HashMap<Address, ContractStoreDeltas>;
56
57pub type ComponentId = String;
59
60pub type ProtocolSystem = String;
62
63pub type EntryPointId = String;
65
66#[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 Custom(CustomChainId),
102}
103
104#[derive(Debug, Clone, PartialEq, Eq)]
106pub enum NativeAsset {
107 Wrapper { native: Token, wrapper: Token },
109 SharedBalance { native: Token, routable: Token },
111 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 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 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 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 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 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
324fn 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
335fn 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 pub fn id(&self) -> u64 {
407 expect_registered(self.try_id())
408 }
409
410 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 pub fn default_tvl_threshold(&self, tier: TvlThresholdTier) -> f64 {
440 expect_registered(self.try_default_tvl_threshold(tier))
441 }
442
443 pub fn try_default_tvl_threshold(
446 &self,
447 tier: TvlThresholdTier,
448 ) -> Result<f64, ChainConfigError> {
449 Ok(match (self, tier) {
450 (
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 (Chain::Polygon, TvlThresholdTier::Low) => 200_000.0,
475 (Chain::Polygon, TvlThresholdTier::Medium) => 2_000_000.0,
476
477 (Chain::Plasma, TvlThresholdTier::Low) => 200_000.0,
479 (Chain::Plasma, TvlThresholdTier::Medium) => 2_000_000.0,
480
481 (Chain::Bsc, TvlThresholdTier::Low) => 32.0,
483 (Chain::Bsc, TvlThresholdTier::Medium) => 320.0,
484
485 (Chain::Arc, TvlThresholdTier::Low) => 20_000.0,
487 (Chain::Arc, TvlThresholdTier::Medium) => 200_000.0,
488
489 (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 pub fn native_token(&self) -> Token {
509 expect_registered(self.try_native_token())
510 }
511
512 pub fn try_native_token(&self) -> Result<Token, ChainConfigError> {
515 Ok(match self {
516 Chain::Ethereum => native_eth(Chain::Ethereum),
517 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 pub fn wrapped_native_token(&self) -> Option<Token> {
537 expect_registered(self.try_wrapped_native_token())
538 }
539
540 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 pub fn native_asset(&self) -> NativeAsset {
553 expect_registered(self.try_native_asset())
554 }
555
556 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 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 wrapper: wrapped_native_eth(
623 Chain::Robinhood,
624 "0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73",
625 ),
626 },
627 Chain::Arc => NativeAsset::SharedBalance {
628 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 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 pub fn block_time_secs(&self) -> u64 {
659 expect_registered(self.try_block_time_secs())
660 }
661
662 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 => 1,
672 Chain::Bsc => 1,
673 Chain::Unichain => 1,
674 Chain::Polygon => 2,
675 Chain::Plasma => 1,
676 Chain::Robinhood => 1,
677 Chain::Arc => 1,
679 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
792impl 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#[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 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 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}