Skip to main content

nautilus_model/defi/
currency.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Contract currency definitions and their DeFi presentation metadata.
17
18use std::{str::FromStr, sync::LazyLock};
19
20use ahash::AHashMap;
21use alloy_primitives::Address;
22use nautilus_core::correctness::{CorrectnessError, CorrectnessResult, check_valid_string_utf8};
23use parking_lot::Mutex;
24use serde::{Deserialize, Serialize};
25use ustr::Ustr;
26
27use super::{Blockchain, Token};
28use crate::{
29    currencies::CURRENCY_MAP, enums::CurrencyType, instruments::Instrument, types::Currency,
30};
31
32static TOKEN_CURRENCIES: LazyLock<Mutex<AHashMap<Ustr, (Currency, TokenCurrency)>>> =
33    LazyLock::new(|| Mutex::new(AHashMap::new()));
34
35/// Binds a readable currency code to one token contract.
36///
37/// Precision and name belong to the associated [`Currency`]. Endpoint settings are not persisted.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct TokenCurrency {
40    pub chain_id: u32,
41    pub address: String,
42    pub symbol: String,
43    pub chain_name: Blockchain,
44}
45
46impl TokenCurrency {
47    /// Returns the currency code as `SYMBOL@CHAIN`.
48    #[must_use]
49    pub fn code(&self) -> String {
50        format!(
51            "{}@{}",
52            self.symbol,
53            self.chain_name.to_string().to_uppercase()
54        )
55    }
56
57    /// Checks the contract address and its associated currency definition.
58    ///
59    /// # Errors
60    ///
61    /// Returns an error if the address is noncanonical, the code mismatches, the symbol is invalid,
62    /// or the type is not a token.
63    pub fn validate(&self, currency: Currency) -> CorrectnessResult<()> {
64        let address = Address::from_str(&self.address).map_err(|_| conflict(currency.code))?;
65        if self.address != format!("{address:#x}")
66            || currency.code.as_str() != self.code()
67            || currency.iso4217 != 0
68            || currency.currency_type != CurrencyType::Crypto
69            || self.symbol.contains([':', '@'])
70            || self.symbol.chars().any(char::is_whitespace)
71        {
72            return Err(conflict(currency.code));
73        }
74
75        check_valid_string_utf8(&self.symbol, "symbol")
76    }
77}
78
79impl From<&Token> for TokenCurrency {
80    fn from(token: &Token) -> Self {
81        Self {
82            chain_id: token.chain.chain_id,
83            address: format!("{:#x}", token.address),
84            symbol: token.symbol.clone(),
85            chain_name: token.chain.name,
86        }
87    }
88}
89
90/// Registers a token code and its chain/contract binding, retaining the first name and symbol.
91///
92/// # Errors
93///
94/// Returns an error if metadata is invalid, a legacy code exists, or an amount definition conflicts.
95pub fn register(currency: Currency, metadata: TokenCurrency) -> CorrectnessResult<Currency> {
96    Currency::new_checked(
97        currency.code.as_str(),
98        currency.precision,
99        currency.iso4217,
100        currency.name.as_str(),
101        currency.currency_type,
102    )?;
103    metadata.validate(currency)?;
104    let mut currencies = CURRENCY_MAP.lock();
105    let mut tokens = TOKEN_CURRENCIES.lock();
106    if let Some((registered, existing)) = tokens.get(&currency.code) {
107        check_definition(*registered, currency)?;
108        if existing.chain_id != metadata.chain_id || existing.address != metadata.address {
109            return Err(conflict(currency.code));
110        }
111
112        if existing != &metadata || registered.name != currency.name {
113            log::warn!(
114                "Token {} display metadata differs from the registered definition; keeping the registered metadata",
115                currency.code,
116            );
117        }
118
119        return Ok(*registered);
120    }
121
122    if let Some((registered, _)) = tokens.values().find(|(_, existing)| {
123        existing.chain_id == metadata.chain_id && existing.address == metadata.address
124    }) {
125        check_definition(*registered, currency)?;
126        log::warn!(
127            "Token {} symbol differs from its registered definition; keeping the registered code {}",
128            currency.code,
129            registered.code
130        );
131        return Ok(*registered);
132    }
133
134    if currencies.contains_key(currency.code.as_str()) {
135        return Err(conflict(currency.code));
136    }
137
138    currencies.insert(currency.code.to_string(), currency);
139    tokens.insert(currency.code, (currency, metadata));
140    Ok(currency)
141}
142
143/// Returns a registered token definition, without inferring provenance from its code.
144#[must_use]
145pub fn lookup(code: Ustr) -> Option<(Currency, TokenCurrency)> {
146    if !code.contains('@') {
147        return None;
148    }
149
150    TOKEN_CURRENCIES.lock().get(&code).cloned()
151}
152
153/// Checks a currency against its registered token definition.
154///
155/// # Errors
156///
157/// Returns an error if a registered token has a conflicting amount definition.
158pub fn check(currency: Currency) -> CorrectnessResult<Option<TokenCurrency>> {
159    if !currency.code.contains('@') {
160        return Ok(None);
161    }
162
163    let tokens = TOKEN_CURRENCIES.lock();
164
165    let Some((registered, metadata)) = tokens.get(&currency.code) else {
166        return Ok(None);
167    };
168
169    check_definition(*registered, currency)?;
170    Ok(Some(metadata.clone()))
171}
172
173/// Returns the sorted, distinct token currency codes used by an instrument.
174///
175/// # Errors
176///
177/// Returns an error if an instrument carries a conflicting token definition.
178pub fn instrument_codes(instrument: &dyn Instrument) -> CorrectnessResult<Vec<String>> {
179    let mut codes = Vec::new();
180
181    for currency in instrument.base_currency().into_iter().chain([
182        instrument.quote_currency(),
183        instrument.settlement_currency(),
184    ]) {
185        if check(currency)?.is_some() {
186            codes.push(currency.code.to_string());
187        }
188    }
189
190    codes.sort_unstable();
191    codes.dedup();
192    Ok(codes)
193}
194
195pub(crate) fn check_registration(currency: Currency) -> CorrectnessResult<Option<Currency>> {
196    if !currency.code.contains('@') {
197        return Ok(None);
198    }
199
200    let tokens = TOKEN_CURRENCIES.lock();
201
202    let Some((registered, _)) = tokens.get(&currency.code) else {
203        return Ok(None);
204    };
205
206    check_definition(*registered, currency)?;
207    if registered.name != currency.name {
208        log::warn!(
209            "Token {} name differs from the registered definition; keeping the registered name",
210            currency.code,
211        );
212    }
213
214    Ok(Some(*registered))
215}
216
217fn check_definition(registered: Currency, currency: Currency) -> CorrectnessResult<()> {
218    if registered.precision != currency.precision
219        || registered.iso4217 != currency.iso4217
220        || registered.currency_type != currency.currency_type
221    {
222        return Err(conflict(currency.code));
223    }
224
225    Ok(())
226}
227
228fn conflict(code: Ustr) -> CorrectnessError {
229    CorrectnessError::PredicateViolation {
230        message: format!("Conflicting DeFi currency definition for {code}"),
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use std::{collections::HashSet, sync::Arc};
237
238    use alloy_primitives::{Address, U256};
239    use rstest::rstest;
240    use rust_decimal_macros::dec;
241
242    use super::*;
243    use crate::{defi::Chain, types::Money};
244
245    #[rstest]
246    fn test_contract_and_chain_identity() {
247        let first = Token::new(
248            Arc::new(Chain::new(Blockchain::Ethereum, 812_301)),
249            Address::from([11; 20]),
250            "First".into(),
251            "IDENTITY".into(),
252            18,
253        );
254        let mut conflicting = first.clone();
255        conflicting.address = Address::from([12; 20]);
256        let mut other_chain = first.clone();
257        other_chain.chain = Arc::new(Chain::new(Blockchain::Base, 812_302));
258
259        let first_currency = first.currency().unwrap();
260        let conflict = conflicting.currency().unwrap_err();
261        let third_currency = other_chain.currency().unwrap();
262        let codes = HashSet::from([first_currency, third_currency]);
263
264        assert_eq!(codes.len(), 2);
265        assert_eq!(first_currency.code, "IDENTITY@ETHEREUM");
266        assert_eq!(third_currency.code, "IDENTITY@BASE");
267        assert_eq!(conflict, super::conflict(first_currency.code));
268        assert_eq!(
269            lookup(first_currency.code).unwrap().1,
270            TokenCurrency {
271                chain_id: 812_301,
272                address: format!("{:#x}", first.address),
273                symbol: "IDENTITY".into(),
274                chain_name: Blockchain::Ethereum,
275            }
276        );
277        assert!(
278            std::panic::catch_unwind(
279                || Money::zero(first_currency).checked_add(Money::zero(third_currency))
280            )
281            .is_err()
282        );
283    }
284
285    #[rstest]
286    #[case(17, "0.00000000000000001")]
287    #[case(18, "0.000000000000000001")]
288    fn test_exact_token_amount(#[case] precision: u8, #[case] amount: &str) {
289        let token = Token::new(
290            Arc::new(Chain::new(Blockchain::Ethereum, 812_303)),
291            Address::from([precision; 20]),
292            "Exact".into(),
293            format!("EXACT{precision}"),
294            precision,
295        );
296        let currency = token.currency().unwrap();
297
298        let money = Money::from_u256(U256::from(1), currency).unwrap();
299        let encoded = serde_json::to_vec(&money).unwrap();
300        let restored: Money = serde_json::from_slice(&encoded).unwrap();
301
302        assert_eq!(money.raw(), 1);
303        assert_eq!(
304            money.as_decimal(),
305            amount.parse::<rust_decimal::Decimal>().unwrap()
306        );
307        assert_eq!(restored, money);
308        assert_eq!(restored.currency.precision, precision);
309        assert_eq!(restored.as_decimal(), money.as_decimal());
310    }
311
312    #[rstest]
313    #[case(812_312, [27; 20], [28; 20])]
314    #[case(812_313, [30; 20], [30; 20])]
315    fn test_code_rejects_conflicting_binding(
316        #[case] chain_id: u32,
317        #[case] original_address: [u8; 20],
318        #[case] address: [u8; 20],
319    ) {
320        let token = Token::new(
321            Arc::new(Chain::new(Blockchain::Ethereum, 812_312)),
322            Address::from(original_address),
323            "Binding".into(),
324            format!("BIND{chain_id}"),
325            6,
326        );
327        let registered = token.currency().unwrap();
328        let mut conflicting = token.clone();
329        conflicting.chain = Arc::new(Chain::new(Blockchain::Ethereum, chain_id));
330        conflicting.address = Address::from(address);
331
332        let error = conflicting.currency().unwrap_err();
333
334        assert_eq!(error, conflict(registered.code));
335        assert_eq!(
336            lookup(registered.code).unwrap().1,
337            TokenCurrency::from(&token)
338        );
339    }
340
341    #[rstest]
342    #[case("BAD@TOKEN")]
343    #[case("BAD:TOKEN")]
344    #[case("BAD TOKEN")]
345    #[case("BAD\nTOKEN")]
346    fn test_code_rejects_invalid_symbol(#[case] symbol: &str) {
347        let token = Token::new(
348            Arc::new(Chain::new(Blockchain::Ethereum, 812_314)),
349            Address::from([29; 20]),
350            "Invalid symbol".into(),
351            symbol.into(),
352            6,
353        );
354        let code = TokenCurrency::from(&token).code();
355
356        let error = token.currency().unwrap_err();
357
358        assert_eq!(error, conflict(Ustr::from(&code)));
359        assert_eq!(lookup(Ustr::from(&code)), None);
360    }
361
362    #[rstest]
363    fn test_token_rejects_unrepresentable_precision() {
364        let token = Token::new(
365            Arc::new(Chain::new(Blockchain::Ethereum, 812_315)),
366            Address::from([31; 20]),
367            "Unsupported precision".into(),
368            "DECIMALS19".into(),
369            19,
370        );
371        let code = Ustr::from(&TokenCurrency::from(&token).code());
372
373        let result = token.currency();
374
375        assert!(result.is_err());
376        assert_eq!(lookup(code), None);
377        assert_eq!(Currency::try_from_str(code.as_str()), None);
378    }
379
380    #[rstest]
381    #[case(false)]
382    #[case(true)]
383    fn test_registration_conflict_in_both_orders(#[case] reversed: bool) {
384        let chain_id = if reversed { 812_304 } else { 812_305 };
385
386        let token = Token::new(
387            Arc::new(Chain::new(Blockchain::Ethereum, chain_id)),
388            Address::from([21; 20]),
389            "Conflict".into(),
390            format!("CONFLICT{chain_id}"),
391            6,
392        );
393        let metadata = TokenCurrency::from(&token);
394        let code = metadata.code();
395
396        let first_precision = if reversed { 18 } else { 6 };
397        let second_precision = if reversed { 6 } else { 18 };
398        let first = Currency::new(&code, first_precision, 0, &token.name, CurrencyType::Crypto);
399
400        let second = Currency::new(
401            &code,
402            second_precision,
403            0,
404            &token.name,
405            CurrencyType::Crypto,
406        );
407
408        let registered = register(first, metadata.clone()).unwrap();
409        let conflict = register(second, metadata).unwrap_err();
410        let overwrite = Currency::register(second, true).unwrap_err();
411
412        assert_eq!(registered.precision, first_precision);
413        assert_eq!(conflict, overwrite);
414        assert_eq!(
415            Currency::try_from_str(&code).unwrap().precision,
416            first_precision
417        );
418    }
419
420    #[rstest]
421    fn test_display_changes_retain_first_definition() {
422        let mut token = Token::new(
423            Arc::new(Chain::new(Blockchain::Ethereum, 812_306)),
424            Address::from([22; 20]),
425            "Original".into(),
426            "OLD".into(),
427            8,
428        );
429        let original_metadata = TokenCurrency::from(&token);
430        let first = token.currency().unwrap();
431        token.name = "Renamed".into();
432        token.symbol = "NEW".into();
433
434        let renamed = token.currency().unwrap();
435        let (_, metadata) = lookup(first.code).unwrap();
436
437        assert_eq!(renamed.code, first.code);
438        assert_eq!(metadata, original_metadata);
439        assert_eq!(renamed.name, "Original");
440        assert_eq!(renamed.precision, 8);
441        assert_eq!(metadata.symbol, "OLD");
442        assert_eq!(metadata.code(), "OLD@ETHEREUM");
443        assert_eq!(
444            Money::from_decimal(dec!(0.12345678), renamed)
445                .unwrap()
446                .as_decimal(),
447            dec!(0.12345678)
448        );
449    }
450
451    #[rstest]
452    fn test_legacy_code_is_not_upgraded() {
453        let token = Token::new(
454            Arc::new(Chain::new(Blockchain::Ethereum, 812_307)),
455            Address::from([23; 20]),
456            "Legacy".into(),
457            "LEGACY".into(),
458            6,
459        );
460        let metadata = TokenCurrency::from(&token);
461        let code = metadata.code();
462        let legacy = Currency::new(&code, 6, 0, &token.name, CurrencyType::Crypto);
463        Currency::register(legacy, false).unwrap();
464
465        let result = token.currency();
466
467        assert!(result.is_err());
468        assert_eq!(lookup(legacy.code), None);
469        assert_eq!(Currency::try_from_str(&code).unwrap().name, "Legacy");
470    }
471
472    #[rstest]
473    #[case(19, "Valid")]
474    #[case(6, "")]
475    fn test_registration_rejects_invalid_public_fields(#[case] precision: u8, #[case] name: &str) {
476        let chain_id = if name.is_empty() { 812_309 } else { 812_308 };
477
478        let token = Token::new(
479            Arc::new(Chain::new(Blockchain::Ethereum, chain_id)),
480            Address::from([24; 20]),
481            "Valid".into(),
482            format!("INVALID{chain_id}"),
483            6,
484        );
485        let metadata = TokenCurrency::from(&token);
486        let code = metadata.code();
487        let mut currency = Currency::new(code.as_str(), 6, 0, "Valid", CurrencyType::Crypto);
488        currency.precision = precision;
489        currency.name = Ustr::from(name);
490
491        let result = register(currency, metadata);
492
493        assert!(result.is_err());
494        assert_eq!(lookup(currency.code), None);
495        assert_eq!(Currency::try_from_str(&code), None);
496    }
497
498    #[rstest]
499    fn test_get_or_create_uses_registered_token_definition() {
500        let token = Token::new(
501            Arc::new(Chain::new(Blockchain::Ethereum, 812_310)),
502            Address::from([25; 20]),
503            "Six decimals".into(),
504            "LOOKUP".into(),
505            6,
506        );
507        let currency = token.currency().unwrap();
508
509        let resolved = Currency::get_or_create_crypto(currency.code);
510
511        assert_eq!(resolved.code, currency.code);
512        assert_eq!(resolved.precision, 6);
513        assert_eq!(resolved.iso4217, 0);
514        assert_eq!(resolved.name, "Six decimals");
515        assert_eq!(resolved.currency_type, CurrencyType::Crypto);
516    }
517
518    #[cfg(feature = "ffi")]
519    #[rstest]
520    fn test_ffi_cannot_overwrite_token_precision() {
521        let token = Token::new(
522            Arc::new(Chain::new(Blockchain::Ethereum, 812_311)),
523            Address::from([26; 20]),
524            "Guarded".into(),
525            "FFIGUARD".into(),
526            6,
527        );
528        let original = token.currency().unwrap();
529        let mut conflicting = original;
530        conflicting.precision = 18;
531
532        crate::ffi::types::currency::currency_register(conflicting);
533
534        assert_eq!(
535            Currency::try_from_str(original.code.as_str())
536                .unwrap()
537                .precision,
538            6
539        );
540    }
541}