Skip to main content

nautilus_model/defi/
token.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
16use std::{fmt::Display, sync::Arc};
17
18use alloy_primitives::Address;
19use nautilus_core::correctness::{CorrectnessResult, check_valid_string_utf8};
20use serde::{Deserialize, Serialize};
21
22use crate::{
23    defi::{
24        chain::SharedChain,
25        currency::{self, TokenCurrency},
26    },
27    enums::CurrencyType,
28    types::Currency,
29};
30
31/// Represents a cryptocurrency token on a blockchain network.
32#[cfg_attr(
33    feature = "python",
34    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
35)]
36#[cfg_attr(
37    feature = "python",
38    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
39)]
40#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
41pub struct Token {
42    /// The blockchain network where this token exists.
43    pub chain: SharedChain,
44    /// The blockchain address of the token contract.
45    pub address: Address,
46    /// The full name of the token.
47    pub name: String,
48    /// The token's ticker symbol.
49    pub symbol: String,
50    /// The number of decimal places used to represent fractional token amounts.
51    pub decimals: u8,
52}
53
54/// A thread-safe shared pointer to a `Token`, enabling efficient reuse across multiple components.
55pub type SharedToken = Arc<Token>;
56
57impl Token {
58    /// Creates a new [`Token`] instance with the specified properties.
59    #[must_use]
60    pub fn new(
61        chain: SharedChain,
62        address: Address,
63        name: String,
64        symbol: String,
65        decimals: u8,
66    ) -> Self {
67        Self {
68            chain,
69            address,
70            name,
71            symbol,
72            decimals,
73        }
74    }
75
76    /// Returns and registers the contract currency with the token's actual decimal precision.
77    ///
78    /// # Errors
79    ///
80    /// Returns an error if metadata is invalid, precision is unsupported, or a definition conflicts.
81    pub fn currency(&self) -> CorrectnessResult<Currency> {
82        check_valid_string_utf8(&self.symbol, "symbol")?;
83        let metadata = TokenCurrency::from(self);
84        let code = metadata.code();
85        let currency = Currency::new_checked(
86            code.as_str(),
87            self.decimals,
88            0,
89            self.name.as_str(),
90            CurrencyType::Crypto,
91        )?;
92        currency::register(currency, metadata)
93    }
94
95    /// Returns true if this token is a stablecoin.
96    ///
97    /// Checks against common stablecoin symbols including USD-pegged tokens,
98    /// Euro-pegged tokens, and other algorithmic/collateralized stablecoins.
99    #[must_use]
100    pub fn is_stablecoin(&self) -> bool {
101        matches!(
102            self.symbol.as_str(),
103            "USDC"
104                | "USDT"
105                | "DAI"
106                | "BUSD"
107                | "FRAX"
108                | "LUSD"
109                | "TUSD"
110                | "USDP"
111                | "GUSD"
112                | "SUSD"
113                | "UST"
114                | "USDD"
115                | "CUSD"
116                | "EUROC"
117                | "EURT"
118                | "EURS"
119                | "AGEUR"
120                | "MIM"
121                | "FEI"
122                | "OUSD"
123                | "USDB"
124        )
125    }
126
127    /// Returns true if this token is a native blockchain currency wrapper.
128    ///
129    /// Identifies wrapped versions of native currencies like WETH (Wrapped ETH),
130    /// WMATIC (Wrapped MATIC), WBNB (Wrapped BNB), etc.
131    #[must_use]
132    pub fn is_native_currency(&self) -> bool {
133        matches!(
134            self.symbol.as_str(),
135            "WETH"
136                | "ETH"
137                | "WMATIC"
138                | "MATIC"
139                | "WBNB"
140                | "BNB"
141                | "WAVAX"
142                | "AVAX"
143                | "WFTM"
144                | "FTM"
145        )
146    }
147
148    /// Returns the priority of this token for base/quote determination.
149    ///
150    /// Lower numbers indicate higher priority to become the quote token (pricing currency).
151    /// This follows market conventions where trades are quoted in the most liquid/stable assets.
152    ///
153    /// # Priority Levels
154    /// - **1**: Stablecoins (USDC, USDT, DAI, etc.) - Highest priority to be quote
155    /// - **2**: Native currencies (WETH, WMATIC, WBNB, etc.) - Medium priority
156    /// - **3**: Other tokens - Lowest priority (typically become base tokens)
157    #[must_use]
158    pub fn get_token_priority(&self) -> u8 {
159        if self.is_stablecoin() {
160            1
161        } else if self.is_native_currency() {
162            2
163        } else {
164            3
165        }
166    }
167}
168
169impl Display for Token {
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        let label = TokenCurrency::from(self).code();
172        write!(f, "Token(symbol={label}, name={})", self.name)
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use std::sync::Arc;
179
180    use rstest::rstest;
181
182    use super::*;
183    use crate::defi::{chain::chains, stubs::weth};
184
185    #[rstest]
186    fn test_token_constructor(weth: Token) {
187        assert_eq!(weth.chain.chain_id, chains::ARBITRUM.chain_id);
188        assert_eq!(weth.name, "Wrapped Ether");
189        assert_eq!(weth.symbol, "WETH");
190        assert_eq!(weth.decimals, 18);
191        assert!(weth.is_native_currency());
192    }
193
194    #[rstest]
195    fn test_token_display_with_special_characters() {
196        // Test edge case where token names/symbols contain formatting characters
197        let chain = Arc::new(chains::ETHEREUM.clone());
198        let token = Token::new(
199            chain,
200            "0xA0b86a33E6441b936662bb6B5d1F8Fb0E2b57A5D"
201                .parse()
202                .unwrap(),
203            "Test Token (with parentheses)".to_string(),
204            "TEST-1".to_string(),
205            18,
206        );
207
208        let display = token.to_string();
209        assert_eq!(
210            display,
211            "Token(symbol=TEST-1@ETHEREUM, name=Test Token (with parentheses))"
212        );
213        assert!(!token.is_native_currency());
214        assert!(!token.is_stablecoin());
215        assert_eq!(token.get_token_priority(), 3);
216    }
217}