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 => 2,
671 Chain::Bsc => 1,
672 Chain::Unichain => 1,
673 Chain::Polygon => 2,
674 Chain::Plasma => 1,
675 Chain::Robinhood => 1,
676 Chain::Arc => 1,
678 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
791impl 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#[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 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 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}