Skip to main content

nautilus_model/defi/
dex.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::{borrow::Cow, fmt::Display, str::FromStr, sync::Arc};
17
18use alloy_primitives::{Address, keccak256};
19use nautilus_core::{
20    correctness::{CorrectnessError, CorrectnessResultExt, FAILED},
21    hex,
22};
23use serde::{Deserialize, Serialize};
24use strum::{Display, EnumIter, EnumString};
25
26use crate::{
27    defi::{amm::Pool, chain::Chain, validation::validate_address},
28    instruments::{Instrument, any::InstrumentAny, currency_pair::CurrencyPair},
29    types::{fixed::FIXED_PRECISION, price::Price, quantity::Quantity},
30};
31
32/// Represents different types of Automated Market Makers (AMMs) in DeFi protocols.
33#[derive(
34    Debug,
35    Clone,
36    Copy,
37    Hash,
38    PartialEq,
39    Eq,
40    Serialize,
41    Deserialize,
42    strum::EnumString,
43    strum::Display,
44    strum::EnumIter,
45)]
46#[cfg_attr(
47    feature = "python",
48    pyo3::pyclass(
49        frozen,
50        eq,
51        eq_int,
52        module = "nautilus_trader.model",
53        from_py_object,
54        rename_all = "SCREAMING_SNAKE_CASE",
55    )
56)]
57#[cfg_attr(feature = "python", pyo3_stub_gen::derive::gen_stub_pyclass_enum)]
58#[non_exhaustive]
59pub enum AmmType {
60    /// Constant Product Automated Market Maker.
61    CPAMM,
62    /// Concentrated Liquidity Automated Market Maker.
63    CLAMM,
64    /// Concentrated liquidity AMM **with hooks** (e.g. upcoming Uniswap v4).
65    CLAMEnhanced,
66    /// Specialized Constant-Sum AMM for low-volatility assets (Curve-style "`StableSwap`").
67    StableSwap,
68    /// AMM with customizable token weights (e.g., Balancer style).
69    WeightedPool,
70    /// Advanced pool type that can nest other pools (Balancer V3).
71    ComposablePool,
72}
73
74/// Represents different types of decentralized exchanges (DEXes) supported by Nautilus.
75#[derive(
76    Debug,
77    Clone,
78    Copy,
79    Hash,
80    PartialOrd,
81    PartialEq,
82    Ord,
83    Eq,
84    Display,
85    EnumIter,
86    EnumString,
87    Serialize,
88    Deserialize,
89)]
90#[cfg_attr(
91    feature = "python",
92    pyo3::pyclass(
93        frozen,
94        eq,
95        eq_int,
96        module = "nautilus_trader.model",
97        from_py_object,
98        rename_all = "SCREAMING_SNAKE_CASE",
99    )
100)]
101#[cfg_attr(feature = "python", pyo3_stub_gen::derive::gen_stub_pyclass_enum)]
102pub enum DexType {
103    AerodromeSlipstream,
104    AerodromeV1,
105    BalancerV2,
106    BalancerV3,
107    BaseSwapV2,
108    BaseX,
109    CamelotV3,
110    CurveFinance,
111    FluidDEX,
112    MaverickV1,
113    MaverickV2,
114    PancakeSwapV3,
115    SushiSwapV2,
116    SushiSwapV3,
117    UniswapV2,
118    UniswapV3,
119    UniswapV4,
120}
121
122impl DexType {
123    /// Returns a reference to the `DexType` corresponding to the given dex name, or `None` if it is not found.
124    #[must_use]
125    pub fn from_dex_name(dex_name: &str) -> Option<Self> {
126        Self::from_str(dex_name).ok()
127    }
128}
129
130/// Represents a decentralized exchange (DEX) in a blockchain ecosystem.
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
132#[cfg_attr(
133    feature = "python",
134    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
135)]
136#[cfg_attr(feature = "python", pyo3_stub_gen::derive::gen_stub_pyclass)]
137pub struct Dex {
138    /// The blockchain network where this DEX operates.
139    pub chain: Chain,
140    /// The variant of the DEX protocol.
141    pub name: DexType,
142    /// The blockchain address of the DEX factory contract.
143    pub factory: Address,
144    /// The block number at which the DEX factory contract was deployed.
145    pub factory_creation_block: u64,
146    /// The event signature or identifier used to detect pool creation events.
147    pub pool_created_event: Cow<'static, str>,
148    // Optional Initialize event signature emitted when pool is initialized.
149    pub initialize_event: Option<Cow<'static, str>>,
150    /// The event signature or identifier used to detect swap events.
151    pub swap_created_event: Cow<'static, str>,
152    /// The event signature or identifier used to detect mint events.
153    pub mint_created_event: Cow<'static, str>,
154    /// The event signature or identifier used to detect burn events.
155    pub burn_created_event: Cow<'static, str>,
156    /// The event signature or identifier used to detect collect fee events.
157    pub collect_created_event: Cow<'static, str>,
158    // Optional Flash event signature emitted when flash loan occurs.
159    pub flash_created_event: Option<Cow<'static, str>>,
160    // Optional SetFeeProtocol event signature emitted when the protocol-fee config changes.
161    pub fee_protocol_update_event: Option<Cow<'static, str>>,
162    // Optional CollectProtocol event signature emitted when protocol fees are withdrawn.
163    pub fee_protocol_collect_event: Option<Cow<'static, str>>,
164    /// The type of automated market maker (AMM) algorithm used by this DEX.
165    pub amm_type: AmmType,
166    /// Collection of liquidity pools managed by this DEX.
167    #[allow(dead_code)]
168    pairs: Vec<Pool>,
169}
170
171/// A thread-safe shared pointer to a `Dex`, enabling efficient reuse across multiple components.
172pub type SharedDex = Arc<Dex>;
173
174impl Dex {
175    /// Creates a new [`Dex`] instance with the specified properties.
176    ///
177    /// # Panics
178    ///
179    /// Panics if the provided factory address is invalid.
180    #[must_use]
181    #[expect(clippy::too_many_arguments)]
182    pub fn new(
183        chain: Chain,
184        name: DexType,
185        factory: &str,
186        factory_creation_block: u64,
187        amm_type: AmmType,
188        pool_created_event: &str,
189        swap_event: &str,
190        mint_event: &str,
191        burn_event: &str,
192        collect_event: &str,
193    ) -> Self {
194        let encoded_pool_created_event =
195            hex::encode_prefixed(keccak256(pool_created_event.as_bytes()));
196        let encoded_swap_event = hex::encode_prefixed(keccak256(swap_event.as_bytes()));
197        let encoded_mint_event = hex::encode_prefixed(keccak256(mint_event.as_bytes()));
198        let encoded_burn_event = hex::encode_prefixed(keccak256(burn_event.as_bytes()));
199        let encoded_collect_event = hex::encode_prefixed(keccak256(collect_event.as_bytes()));
200        let factory_address = match validate_address(factory) {
201            Ok(address) => address,
202            Err(e) => panic!(
203                "Invalid factory address for DEX {name} on chain {chain} for factory address {factory}: {e}"
204            ),
205        };
206        Self {
207            chain,
208            name,
209            factory: factory_address,
210            factory_creation_block,
211            pool_created_event: encoded_pool_created_event.into(),
212            initialize_event: None,
213            swap_created_event: encoded_swap_event.into(),
214            mint_created_event: encoded_mint_event.into(),
215            burn_created_event: encoded_burn_event.into(),
216            collect_created_event: encoded_collect_event.into(),
217            flash_created_event: None,
218            fee_protocol_update_event: None,
219            fee_protocol_collect_event: None,
220            amm_type,
221            pairs: vec![],
222        }
223    }
224
225    /// Returns a unique identifier for this DEX, combining chain and protocol name.
226    #[must_use]
227    pub fn id(&self) -> String {
228        format!("{}:{}", self.chain.name, self.name)
229    }
230
231    /// Sets the pool initialization event signature by hashing and encoding the provided event string.
232    pub fn set_initialize_event(&mut self, event: &str) {
233        self.initialize_event = Some(hex::encode_prefixed(keccak256(event.as_bytes())).into());
234    }
235
236    /// Sets the flash loan event signature by hashing and encoding the provided event string.
237    pub fn set_flash_event(&mut self, event: &str) {
238        self.flash_created_event = Some(hex::encode_prefixed(keccak256(event.as_bytes())).into());
239    }
240
241    /// Sets the protocol-fee change event signature by hashing and encoding the provided event string.
242    pub fn set_fee_protocol_update_event(&mut self, event: &str) {
243        self.fee_protocol_update_event =
244            Some(hex::encode_prefixed(keccak256(event.as_bytes())).into());
245    }
246
247    /// Sets the protocol-fee withdrawal event signature by hashing and encoding the provided event string.
248    pub fn set_fee_protocol_collect_event(&mut self, event: &str) {
249        self.fee_protocol_collect_event =
250            Some(hex::encode_prefixed(keccak256(event.as_bytes())).into());
251    }
252}
253
254impl Display for Dex {
255    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
256        write!(f, "Dex(chain={}, name={})", self.chain, self.name)
257    }
258}
259
260impl TryFrom<&Pool> for CurrencyPair {
261    type Error = CorrectnessError;
262
263    fn try_from(p: &Pool) -> Result<Self, Self::Error> {
264        let base_token = p.get_base_token();
265        let quote_token = p.get_quote_token();
266        let size_precision = base_token.decimals.min(FIXED_PRECISION);
267        let price_precision = quote_token.decimals.min(FIXED_PRECISION);
268
269        let price_increment =
270            Price::from_mantissa_exponent(1, -price_precision.cast_signed(), price_precision);
271        let size_increment =
272            Quantity::from_mantissa_exponent(1, -size_precision.cast_signed(), size_precision);
273        let base_currency = base_token.currency()?;
274        let quote_currency = quote_token.currency()?;
275        let pair = Self::builder()
276            .instrument_id(p.instrument_id)
277            .raw_symbol(p.instrument_id.symbol)
278            .base_currency(base_currency)
279            .quote_currency(quote_currency)
280            .price_precision(price_precision)
281            .size_precision(size_precision)
282            .price_increment(price_increment)
283            .size_increment(size_increment)
284            .ts_event(p.ts_event)
285            .ts_init(p.ts_init)
286            .build()?;
287
288        Ok(pair)
289    }
290}
291
292impl From<Pool> for CurrencyPair {
293    fn from(p: Pool) -> Self {
294        Self::try_from(&p).expect_display(FAILED)
295    }
296}
297
298impl From<Pool> for InstrumentAny {
299    fn from(p: Pool) -> Self {
300        CurrencyPair::from(p).into_any()
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use std::sync::atomic::{AtomicU32, Ordering};
307
308    use alloy_primitives::Address;
309    use nautilus_core::correctness::CorrectnessError;
310    use rstest::{fixture, rstest};
311
312    use super::{CurrencyPair, DexType};
313    use crate::{
314        defi::{Pool, SharedPool, stubs::rain_pool},
315        enums::CurrencyType,
316        types::{Price, Quantity, currency::Currency, fixed::FIXED_PRECISION},
317    };
318
319    #[fixture]
320    fn currency_pool(rain_pool: SharedPool) -> Pool {
321        static NEXT_ADDRESS: AtomicU32 = AtomicU32::new(1);
322        let mut pool = (*rain_pool).clone();
323        for token in [&mut pool.token0, &mut pool.token1] {
324            let mut address = [0xfa; 20];
325            address[16..]
326                .copy_from_slice(&NEXT_ADDRESS.fetch_add(1, Ordering::Relaxed).to_be_bytes());
327            token.address = Address::from(address);
328        }
329
330        pool
331    }
332
333    #[rstest]
334    fn test_dex_type_from_dex_name_valid() {
335        // Test some known DEX names
336        assert!(DexType::from_dex_name("UniswapV3").is_some());
337        assert!(DexType::from_dex_name("SushiSwapV2").is_some());
338        assert!(DexType::from_dex_name("BalancerV2").is_some());
339        assert!(DexType::from_dex_name("CamelotV3").is_some());
340
341        // Verify specific DEX type
342        let uniswap_v3 = DexType::from_dex_name("UniswapV3").unwrap();
343        assert_eq!(uniswap_v3, DexType::UniswapV3);
344
345        // Verify compound names
346        let aerodrome_slipstream = DexType::from_dex_name("AerodromeSlipstream").unwrap();
347        assert_eq!(aerodrome_slipstream, DexType::AerodromeSlipstream);
348
349        // Verify specialized names
350        let fluid_dex = DexType::from_dex_name("FluidDEX").unwrap();
351        assert_eq!(fluid_dex, DexType::FluidDEX);
352    }
353
354    #[rstest]
355    fn test_dex_type_from_dex_name_invalid() {
356        // Test unknown DEX names
357        assert!(DexType::from_dex_name("InvalidDEX").is_none());
358        assert!(DexType::from_dex_name("").is_none());
359        assert!(DexType::from_dex_name("NonExistentDEX").is_none());
360    }
361
362    #[rstest]
363    fn test_dex_type_from_dex_name_case_sensitive() {
364        // Test case sensitivity - should be case sensitive
365        assert!(DexType::from_dex_name("UniswapV3").is_some());
366        assert!(DexType::from_dex_name("uniswapv3").is_none()); // lowercase
367        assert!(DexType::from_dex_name("UNISWAPV3").is_none()); // uppercase
368        assert!(DexType::from_dex_name("UniSwapV3").is_none()); // mixed case
369
370        assert!(DexType::from_dex_name("SushiSwapV2").is_some());
371        assert!(DexType::from_dex_name("sushiswapv2").is_none()); // lowercase
372    }
373
374    #[rstest]
375    fn test_dex_type_all_variants_mappable() {
376        // Test that all DEX variants can be mapped from their string representation
377        let all_dex_names = vec![
378            "AerodromeSlipstream",
379            "AerodromeV1",
380            "BalancerV2",
381            "BalancerV3",
382            "BaseSwapV2",
383            "BaseX",
384            "CamelotV3",
385            "CurveFinance",
386            "FluidDEX",
387            "MaverickV1",
388            "MaverickV2",
389            "PancakeSwapV3",
390            "SushiSwapV2",
391            "SushiSwapV3",
392            "UniswapV2",
393            "UniswapV3",
394            "UniswapV4",
395        ];
396
397        for dex_name in all_dex_names {
398            assert!(
399                DexType::from_dex_name(dex_name).is_some(),
400                "DEX name '{dex_name}' should be valid but was not found",
401            );
402        }
403    }
404
405    #[rstest]
406    fn test_dex_type_display() {
407        // Test that DexType variants display correctly (using strum::Display)
408        assert_eq!(DexType::UniswapV3.to_string(), "UniswapV3");
409        assert_eq!(DexType::SushiSwapV2.to_string(), "SushiSwapV2");
410        assert_eq!(
411            DexType::AerodromeSlipstream.to_string(),
412            "AerodromeSlipstream"
413        );
414        assert_eq!(DexType::FluidDEX.to_string(), "FluidDEX");
415    }
416
417    #[rstest]
418    #[case(0, 6, 0, 6)]
419    #[case(6, FIXED_PRECISION, 6, FIXED_PRECISION)]
420    #[case(FIXED_PRECISION, 0, FIXED_PRECISION, 0)]
421    #[case(
422        FIXED_PRECISION + 1,
423        FIXED_PRECISION + 2,
424        FIXED_PRECISION,
425        FIXED_PRECISION
426    )]
427    fn test_pool_to_currency_pair_constructs_exact_increments(
428        #[case] size_precision: u8,
429        #[case] price_precision: u8,
430        #[case] expected_size_precision: u8,
431        #[case] expected_price_precision: u8,
432        currency_pool: Pool,
433    ) {
434        let mut pool = currency_pool;
435        pool.token0.symbol = format!("BASE{size_precision}");
436        pool.token1.symbol = format!("QUOTE{price_precision}");
437        pool.token0.decimals = size_precision;
438        pool.token1.decimals = price_precision;
439
440        let expected_id = pool.instrument_id;
441        let expected_ts_event = pool.ts_event;
442        let expected_ts_init = pool.ts_init;
443        let expected_base_code = format!(
444            "{}@{}",
445            pool.get_base_token().symbol,
446            pool.get_base_token().chain.name.to_string().to_uppercase()
447        );
448        let expected_quote_code = format!(
449            "{}@{}",
450            pool.get_quote_token().symbol,
451            pool.get_quote_token().chain.name.to_string().to_uppercase()
452        );
453        let pair = CurrencyPair::from(pool);
454        let price_scale_exponent = u32::from(FIXED_PRECISION - expected_price_precision);
455        let size_scale_exponent = u32::from(FIXED_PRECISION - expected_size_precision);
456
457        assert_eq!(pair.id, expected_id);
458        assert_eq!(pair.raw_symbol, expected_id.symbol);
459        assert_eq!(pair.base_currency.code, expected_base_code);
460        assert_eq!(pair.base_currency.precision, size_precision);
461        assert_eq!(pair.quote_currency.code, expected_quote_code);
462        assert_eq!(pair.quote_currency.precision, price_precision);
463        assert_eq!(pair.price_precision, expected_price_precision);
464        assert_eq!(pair.size_precision, expected_size_precision);
465        assert_eq!(
466            pair.price_increment.raw(),
467            10_i128.pow(price_scale_exponent)
468        );
469        assert_eq!(pair.price_increment.precision, expected_price_precision);
470        assert_eq!(pair.size_increment.raw(), 10_u128.pow(size_scale_exponent));
471        assert_eq!(pair.size_increment.precision, expected_size_precision);
472        assert_eq!(pair.ts_event, expected_ts_event);
473        assert_eq!(pair.ts_init, expected_ts_init);
474    }
475
476    #[rstest]
477    fn test_pool_to_currency_pair_orients_inverted_pool_by_token_priority(currency_pool: Pool) {
478        let mut pool = currency_pool;
479
480        let chain = std::sync::Arc::new(crate::defi::Chain::new(
481            crate::defi::Blockchain::GaladrielDevnet,
482            812_330,
483        ));
484        pool.token0.chain = std::sync::Arc::clone(&chain);
485        pool.token1.chain = chain;
486        pool.token0.symbol = "USDC".to_string();
487        pool.token0.name = "USD Coin".to_string();
488        pool.token0.decimals = 6;
489        pool.token1.symbol = "WETH".to_string();
490        pool.token1.name = "Wrapped Ether".to_string();
491        pool.token1.decimals = 8;
492        assert!(pool.is_base_quote_inverted());
493
494        let expected_base_code = format!(
495            "{}@{}",
496            pool.get_base_token().symbol,
497            pool.get_base_token().chain.name.to_string().to_uppercase()
498        );
499        let expected_quote_code = format!(
500            "{}@{}",
501            pool.get_quote_token().symbol,
502            pool.get_quote_token().chain.name.to_string().to_uppercase()
503        );
504        let pair = CurrencyPair::from(pool);
505
506        assert_eq!(pair.base_currency.code, expected_base_code);
507        assert_eq!(pair.base_currency.name, "Wrapped Ether");
508        assert_eq!(pair.base_currency.precision, 8);
509        assert_eq!(pair.quote_currency.code, expected_quote_code);
510        assert_eq!(pair.quote_currency.name, "USD Coin");
511        assert_eq!(pair.quote_currency.precision, 6);
512        assert_eq!(pair.size_precision, 8);
513        assert_eq!(pair.price_precision, 6);
514        assert_eq!(pair.size_increment, Quantity::from("0.00000001"));
515        assert_eq!(pair.price_increment, Price::from("0.000001"));
516    }
517
518    #[rstest]
519    fn test_pool_to_currency_pair_registers_token_currencies(currency_pool: Pool) {
520        let mut pool = currency_pool;
521        pool.token0.symbol = "ENG444BASE".to_string();
522        pool.token0.name = "ENG-444 Base Token".to_string();
523        pool.token0.decimals = 8;
524        pool.token1.symbol = "ENG444QUOTE".to_string();
525        pool.token1.name = "ENG-444 Quote Token".to_string();
526        pool.token1.decimals = 6;
527
528        let base_code = format!(
529            "{}@{}",
530            pool.token0.symbol,
531            pool.token0.chain.name.to_string().to_uppercase()
532        );
533        let quote_code = format!(
534            "{}@{}",
535            pool.token1.symbol,
536            pool.token1.chain.name.to_string().to_uppercase()
537        );
538        let _ = CurrencyPair::from(pool);
539
540        let base = Currency::try_from_str(&base_code).unwrap();
541        let quote = Currency::try_from_str(&quote_code).unwrap();
542        assert_eq!(base.code, base_code);
543        assert_eq!(base.precision, 8);
544        assert_eq!(base.iso4217, 0);
545        assert_eq!(base.name, "ENG-444 Base Token");
546        assert_eq!(base.currency_type, CurrencyType::Crypto);
547        assert_eq!(quote.code, quote_code);
548        assert_eq!(quote.precision, 6);
549        assert_eq!(quote.iso4217, 0);
550        assert_eq!(quote.name, "ENG-444 Quote Token");
551        assert_eq!(quote.currency_type, CurrencyType::Crypto);
552    }
553
554    #[rstest]
555    fn test_pool_to_currency_pair_rejects_invalid_token_metadata(rain_pool: SharedPool) {
556        let mut missing_symbol = (*rain_pool).clone();
557        missing_symbol.token0.symbol.clear();
558        let mut blank_symbol = (*rain_pool).clone();
559        blank_symbol.token0.symbol = "  ".to_string();
560        let mut missing_name = (*rain_pool).clone();
561        missing_name.token0.name.clear();
562
563        let missing_symbol_result = CurrencyPair::try_from(&missing_symbol);
564        let blank_symbol_result = CurrencyPair::try_from(&blank_symbol);
565        let missing_name_result = CurrencyPair::try_from(&missing_name);
566
567        assert_eq!(
568            missing_symbol_result.unwrap_err(),
569            CorrectnessError::EmptyString {
570                param: "symbol".to_string(),
571            }
572        );
573        assert_eq!(
574            blank_symbol_result.unwrap_err(),
575            CorrectnessError::WhitespaceString {
576                param: "symbol".to_string(),
577            }
578        );
579        assert_eq!(
580            missing_name_result.unwrap_err(),
581            CorrectnessError::EmptyString {
582                param: "name".to_string(),
583            }
584        );
585    }
586}