Skip to main content

tycho_common/models/
chain_config.rs

1//! Value types describing a blockchain's configuration: token metadata, TVL thresholds, and the
2//! full `CustomChainConfig` used to describe user-defined chains. Re-exported from `models`.
3
4use std::{collections::HashMap, sync::OnceLock};
5
6use arrayvec::ArrayString;
7use deepsize::DeepSizeOf;
8use serde::{Deserialize, Serialize};
9use thiserror::Error;
10use utoipa::ToSchema;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13pub struct ChainAddress {
14    bytes: [u8; 32],
15    len: u8,
16}
17
18impl ChainAddress {
19    pub fn new(bytes: &[u8]) -> Result<Self, ChainConfigError> {
20        let Some(len) = u8::try_from(bytes.len())
21            .ok()
22            .filter(|&len| len <= 32)
23        else {
24            return Err(ChainConfigError::AddressTooLong(bytes.len()));
25        };
26        let mut arr = [0u8; 32];
27        arr[..bytes.len()].copy_from_slice(bytes);
28        Ok(Self { bytes: arr, len })
29    }
30
31    pub fn as_bytes(&self) -> &[u8] {
32        &self.bytes[..self.len as usize]
33    }
34}
35
36/// Serialized as a `0x`-prefixed hex string so config files and wire payloads use the same
37/// representation a human writes (e.g. `"0x0000...0000"`).
38impl Serialize for ChainAddress {
39    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
40        serializer.serialize_str(&format!("0x{}", hex::encode(self.as_bytes())))
41    }
42}
43
44impl<'de> Deserialize<'de> for ChainAddress {
45    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
46        let s = String::deserialize(deserializer)?;
47        let raw = hex::decode(s.trim_start_matches("0x"))
48            .map_err(|e| serde::de::Error::custom(format!("invalid hex address '{s}': {e}")))?;
49        ChainAddress::new(&raw).map_err(serde::de::Error::custom)
50    }
51}
52
53#[derive(Error, Debug, PartialEq)]
54pub enum ChainConfigError {
55    #[error("invalid hex address '{0}': {1}")]
56    InvalidAddress(String, String),
57    #[error("address is {0} bytes, max is 32")]
58    AddressTooLong(usize),
59    #[error("symbol '{0}' too long (max 8 chars)")]
60    SymbolTooLong(String),
61    #[error("chain name '{0}' too long (max 32 chars)")]
62    NameTooLong(String),
63    #[error("unknown chain '{0}': not a built-in chain and no custom config registered")]
64    UnknownChain(String),
65    #[error("duplicate custom chain config for '{0}'")]
66    DuplicateChain(String),
67    #[error("failed to read chain config file: {0}")]
68    Io(String),
69    #[error("failed to parse chain config: {0}")]
70    Parse(String),
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
74pub struct ChainTokenConfig {
75    #[schema(value_type = String)]
76    pub(crate) address: ChainAddress,
77    #[schema(value_type = String)]
78    pub(crate) symbol: ArrayString<8>,
79    pub(crate) decimals: u8,
80}
81
82impl ChainTokenConfig {
83    pub fn try_new(
84        address_hex: &str,
85        symbol: &str,
86        decimals: u8,
87    ) -> Result<Self, ChainConfigError> {
88        let raw = hex::decode(address_hex.trim_start_matches("0x"))
89            .map_err(|e| ChainConfigError::InvalidAddress(address_hex.to_owned(), e.to_string()))?;
90        let address = ChainAddress::new(&raw)?;
91        let symbol = ArrayString::from(symbol)
92            .map_err(|e| ChainConfigError::SymbolTooLong(e.element().to_owned()))?;
93        Ok(Self { address, symbol, decimals })
94    }
95}
96
97#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema)]
98pub struct TvlThresholds {
99    pub(crate) low: f64,
100    pub(crate) medium: f64,
101}
102
103impl TvlThresholds {
104    pub fn new(low: f64, medium: f64) -> Self {
105        Self { low, medium }
106    }
107}
108
109impl PartialEq for TvlThresholds {
110    fn eq(&self, other: &Self) -> bool {
111        self.low.to_bits() == other.low.to_bits() && self.medium.to_bits() == other.medium.to_bits()
112    }
113}
114
115impl Eq for TvlThresholds {}
116
117impl std::hash::Hash for TvlThresholds {
118    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
119        self.low.to_bits().hash(state);
120        self.medium.to_bits().hash(state);
121    }
122}
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
125#[expect(
126    clippy::partial_pub_fields,
127    reason = "public API; the private fields are validated by `try_new`, and making `block_time_secs` private is a breaking change"
128)]
129pub struct CustomChainConfig {
130    #[schema(value_type = String)]
131    pub(crate) name: ArrayString<32>,
132    pub(crate) chain_id: u64,
133    pub block_time_secs: u64,
134    pub(crate) native: ChainTokenConfig,
135    pub(crate) wrapped_native: ChainTokenConfig,
136    pub(crate) default_tvl_thresholds: TvlThresholds,
137}
138
139impl CustomChainConfig {
140    pub fn try_new(
141        name: &str,
142        chain_id: u64,
143        block_time_secs: u64,
144        native: ChainTokenConfig,
145        wrapped_native: ChainTokenConfig,
146        default_tvl_thresholds: TvlThresholds,
147    ) -> Result<Self, ChainConfigError> {
148        let name = ArrayString::from(name)
149            .map_err(|e| ChainConfigError::NameTooLong(e.element().to_owned()))?;
150        Ok(Self { name, chain_id, block_time_secs, native, wrapped_native, default_tvl_thresholds })
151    }
152
153    pub fn name(&self) -> &str {
154        self.name.as_str()
155    }
156}
157
158impl DeepSizeOf for CustomChainConfig {
159    fn deep_size_of_children(&self, _context: &mut deepsize::Context) -> usize {
160        0
161    }
162}
163
164/// Name of a custom chain, guaranteed at construction time to have a matching config in the chain
165/// registry. The inner name is private, so a `CustomChainId` — and therefore a `Chain::Custom` —
166/// can only be minted through the crate's validating constructors (`Chain::custom`,
167/// `Chain::from_str`, `From<dto::Chain>`), never fabricated directly. Serializes transparently as
168/// the bare chain name.
169#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
170pub struct CustomChainId(ArrayString<32>);
171
172impl CustomChainId {
173    /// Builds an id after confirming `name` is registered, returning
174    /// [`ChainConfigError::UnknownChain`] when it is absent and [`ChainConfigError::NameTooLong`]
175    /// when it exceeds 32 bytes.
176    pub(crate) fn checked(
177        name: &str,
178        registry: &ChainConfigRegistry,
179    ) -> Result<Self, ChainConfigError> {
180        if !registry.contains(name) {
181            return Err(ChainConfigError::UnknownChain(name.to_owned()));
182        }
183        ArrayString::from(name)
184            .map(Self)
185            .map_err(|e| ChainConfigError::NameTooLong(e.element().to_owned()))
186    }
187
188    pub fn as_str(&self) -> &str {
189        self.0.as_str()
190    }
191}
192
193/// TVL threshold tiers for chain-aware filtering defaults.
194///
195/// TVL is denominated in each chain's native token. Since native tokens have different USD values,
196/// the same numeric threshold produces wildly different USD-equivalent filters across chains.
197/// These tiers provide sensible defaults targeting equivalent USD values.
198#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
199pub enum TvlThresholdTier {
200    /// Filters out dust pools (~$20K USD equivalent in native token).
201    Low,
202    /// Filters for pools with meaningful liquidity (~$200K USD equivalent in native token).
203    Medium,
204}
205
206/// Env var holding the path the registry reads custom-chain config from. Unset means "no custom
207/// chains"; there is no default path, so loading never depends on the current working directory.
208const TYCHO_CHAINS_CONFIG_ENV: &str = "TYCHO_CHAINS_CONFIG";
209
210/// On-disk shape of the custom-chain config file: a top-level `chains:` list. This is the format of
211/// the indexer's `chains.yaml` (its `--chain-config` file), so a consumer can point
212/// `TYCHO_CHAINS_CONFIG` at the same file the indexer uses.
213#[derive(Debug, Default, Deserialize)]
214struct ChainConfigFile {
215    #[serde(default)]
216    chains: Vec<CustomChainConfig>,
217}
218
219/// Resolves the full configuration of custom chains by name.
220///
221/// Built-in chains are resolved without this registry; it only holds user-defined chains loaded
222/// from a YAML source. Build it explicitly via [`ChainConfigRegistry::from_configs`],
223/// [`ChainConfigRegistry::from_yaml_file`], or [`ChainConfigRegistry::load_default`], then install
224/// it as the process-wide registry with [`init_chain_registry`].
225#[derive(Debug, Default, Clone)]
226pub struct ChainConfigRegistry {
227    custom: HashMap<String, CustomChainConfig>,
228}
229
230impl ChainConfigRegistry {
231    /// An empty registry — only built-in chains will resolve.
232    pub fn empty() -> Self {
233        Self { custom: HashMap::new() }
234    }
235
236    /// Builds a registry from custom chain configs, keyed by chain name. Rejects duplicate names
237    /// with [`ChainConfigError::DuplicateChain`] rather than silently overriding, so an ambiguous
238    /// config fails loudly at construction.
239    pub fn from_configs(
240        configs: impl IntoIterator<Item = CustomChainConfig>,
241    ) -> Result<Self, ChainConfigError> {
242        let mut custom = HashMap::new();
243        for cfg in configs {
244            let name = cfg.name().to_owned();
245            if custom
246                .insert(name.clone(), cfg)
247                .is_some()
248            {
249                return Err(ChainConfigError::DuplicateChain(name));
250            }
251        }
252        Ok(Self { custom })
253    }
254
255    /// Reads custom chain configs from the path in `TYCHO_CHAINS_CONFIG`.
256    ///
257    /// Returns an empty registry when the env var is unset, so runs on built-in chains need no
258    /// config. When it is set, the file is loaded as-is: a missing, unreadable, or malformed file
259    /// is an error (the operator asked for a config, so a broken one is a mistake, not "no custom
260    /// chains"), leaving the caller to decide how to react. Install the result with
261    /// [`init_chain_registry`] to make it the process-wide registry.
262    pub fn load_default() -> Result<Self, ChainConfigError> {
263        let Ok(path) = std::env::var(TYCHO_CHAINS_CONFIG_ENV) else {
264            return Ok(Self::empty());
265        };
266        Self::from_yaml_file(&path)
267    }
268
269    /// Like [`load_default`](Self::load_default) but never fails: a broken `TYCHO_CHAINS_CONFIG`
270    /// (missing, unreadable, or malformed file) is logged and degrades to an empty registry rather
271    /// than aborting. Used by [`chain_registry`] to lazily initialise the process-wide registry, so
272    /// a consumer only needs to set `TYCHO_CHAINS_CONFIG` — no explicit init call. Call
273    /// [`load_default`](Self::load_default) directly when you need to react to the error.
274    pub fn load_default_or_empty() -> Self {
275        Self::load_default().unwrap_or_else(|e| {
276            tracing::warn!(
277                error = %e,
278                "failed to load custom chain config from TYCHO_CHAINS_CONFIG; falling back to an \
279                 empty registry"
280            );
281            Self::empty()
282        })
283    }
284
285    /// Parses a registry from a YAML file with a top-level `chains:` list.
286    pub fn from_yaml_file(path: &str) -> Result<Self, ChainConfigError> {
287        let contents =
288            std::fs::read_to_string(path).map_err(|e| ChainConfigError::Io(e.to_string()))?;
289        Self::from_yaml_str(&contents)
290    }
291
292    /// Parses a registry from a YAML string with a top-level `chains:` list.
293    pub fn from_yaml_str(contents: &str) -> Result<Self, ChainConfigError> {
294        let file: ChainConfigFile =
295            serde_yaml::from_str(contents).map_err(|e| ChainConfigError::Parse(e.to_string()))?;
296        Self::from_configs(file.chains)
297    }
298
299    /// Returns the config for a custom chain by name, if registered.
300    pub fn get(&self, name: &str) -> Option<&CustomChainConfig> {
301        self.custom.get(name)
302    }
303
304    /// Whether a custom chain with this name is registered.
305    pub fn contains(&self, name: &str) -> bool {
306        self.custom.contains_key(name)
307    }
308}
309
310static CHAIN_REGISTRY: OnceLock<ChainConfigRegistry> = OnceLock::new();
311
312/// Returns the process-wide chain config registry.
313///
314/// On first access, lazily initialises itself from `TYCHO_CHAINS_CONFIG` via
315/// [`ChainConfigRegistry::load_default_or_empty`] — so a consumer that wants custom chains only
316/// needs to set that env var, no explicit init call. A run with the env var unset resolves
317/// built-in chains from an empty registry. Install a registry explicitly with
318/// [`init_chain_registry`] before first access to override the lazy load (e.g. the indexer
319/// building one from its own config).
320pub fn chain_registry() -> &'static ChainConfigRegistry {
321    CHAIN_REGISTRY.get_or_init(ChainConfigRegistry::load_default_or_empty)
322}
323
324/// Installs the process-wide chain config registry explicitly, before any call to
325/// [`chain_registry`]. Returns the passed registry back as `Err` if it was already initialised.
326pub fn init_chain_registry(registry: ChainConfigRegistry) -> Result<(), ChainConfigRegistry> {
327    CHAIN_REGISTRY.set(registry)
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333
334    const SAMPLE_YAML: &str = r#"
335chains:
336  - name: testchain
337    chain_id: 9999
338    block_time_secs: 5
339    native:
340      address: "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
341      symbol: TST
342      decimals: 18
343    wrapped_native:
344      address: "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
345      symbol: WTST
346      decimals: 18
347    default_tvl_thresholds:
348      low: 50.0
349      medium: 500.0
350"#;
351
352    #[test]
353    fn parses_yaml_and_resolves_by_name() {
354        let registry = ChainConfigRegistry::from_yaml_str(SAMPLE_YAML).unwrap();
355        assert!(registry.contains("testchain"));
356        let cfg = registry
357            .get("testchain")
358            .expect("testchain present");
359        assert_eq!(cfg.name(), "testchain");
360        assert_eq!(cfg.chain_id, 9999);
361        assert_eq!(cfg.block_time_secs, 5);
362    }
363
364    #[test]
365    fn unknown_chain_is_absent() {
366        let registry = ChainConfigRegistry::from_yaml_str(SAMPLE_YAML).unwrap();
367        assert!(!registry.contains("nope"));
368        assert!(registry.get("nope").is_none());
369    }
370
371    #[test]
372    fn empty_registry_has_no_custom_chains() {
373        assert!(!ChainConfigRegistry::empty().contains("testchain"));
374    }
375
376    #[test]
377    fn from_configs_keys_by_name() {
378        let cfg = CustomChainConfig::try_new(
379            "mychain",
380            42,
381            2,
382            ChainTokenConfig::try_new("0x00", "AAA", 18).unwrap(),
383            ChainTokenConfig::try_new("0x01", "WAAA", 18).unwrap(),
384            TvlThresholds::new(1.0, 2.0),
385        )
386        .unwrap();
387        let registry = ChainConfigRegistry::from_configs([cfg]).unwrap();
388        assert!(registry.contains("mychain"));
389        assert_eq!(
390            registry
391                .get("mychain")
392                .unwrap()
393                .chain_id,
394            42
395        );
396    }
397
398    #[test]
399    fn empty_chains_list_parses_to_empty_registry() {
400        let registry = ChainConfigRegistry::from_yaml_str("chains: []").unwrap();
401        assert!(!registry.contains("anything"));
402    }
403
404    // These tests mutate the process-global `TYCHO_CHAINS_CONFIG` env var; they rely on nextest
405    // running each test in its own process (repo convention). Under plain `cargo test` they would
406    // race on the shared env.
407    #[test]
408    fn load_default_returns_empty_when_env_unset() {
409        std::env::remove_var(TYCHO_CHAINS_CONFIG_ENV);
410        assert!(!ChainConfigRegistry::load_default()
411            .unwrap()
412            .contains("anything"));
413    }
414
415    #[test]
416    fn load_default_errors_when_env_points_at_missing_file() {
417        let missing = format!(
418            "{}/tycho-chain-config-missing-{}.yaml",
419            std::env::temp_dir().display(),
420            std::process::id()
421        );
422        std::env::set_var(TYCHO_CHAINS_CONFIG_ENV, &missing);
423        assert!(matches!(ChainConfigRegistry::load_default(), Err(ChainConfigError::Io(_))));
424    }
425
426    #[test]
427    fn chain_registry_lazy_loads_from_env() {
428        let path = format!(
429            "{}/tycho-lazy-chain-{}.yaml",
430            std::env::temp_dir().display(),
431            std::process::id()
432        );
433        std::fs::write(&path, SAMPLE_YAML).unwrap();
434        std::env::set_var(TYCHO_CHAINS_CONFIG_ENV, &path);
435        // No explicit init_chain_registry — first access lazily loads from the env path.
436        assert!(chain_registry().contains("testchain"));
437    }
438
439    #[test]
440    fn load_default_or_empty_degrades_to_empty_on_missing_file() {
441        let missing = format!(
442            "{}/tycho-chain-config-degrade-{}.yaml",
443            std::env::temp_dir().display(),
444            std::process::id()
445        );
446        std::env::set_var(TYCHO_CHAINS_CONFIG_ENV, &missing);
447        // A broken config must not panic here; it degrades to an empty registry.
448        assert!(!ChainConfigRegistry::load_default_or_empty().contains("anything"));
449    }
450
451    #[test]
452    fn from_configs_duplicate_name_errors() {
453        let first = CustomChainConfig::try_new(
454            "dup",
455            1,
456            2,
457            ChainTokenConfig::try_new("0x00", "AAA", 18).unwrap(),
458            ChainTokenConfig::try_new("0x01", "WAAA", 18).unwrap(),
459            TvlThresholds::new(1.0, 2.0),
460        )
461        .unwrap();
462        let second = CustomChainConfig::try_new(
463            "dup",
464            2,
465            2,
466            ChainTokenConfig::try_new("0x00", "AAA", 18).unwrap(),
467            ChainTokenConfig::try_new("0x01", "WAAA", 18).unwrap(),
468            TvlThresholds::new(1.0, 2.0),
469        )
470        .unwrap();
471        assert_eq!(
472            ChainConfigRegistry::from_configs([first, second]).unwrap_err(),
473            ChainConfigError::DuplicateChain("dup".to_owned())
474        );
475    }
476}