Skip to main content

nautilus_model/python/defi/
types.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//! Python bindings for DeFi types.
17
18use std::{
19    collections::hash_map::DefaultHasher,
20    hash::{Hash, Hasher},
21    str::FromStr,
22    sync::Arc,
23};
24
25use nautilus_core::python::{IntoPyObjectNautilusExt, to_pyvalue_err};
26use pyo3::{basic::CompareOp, prelude::*};
27
28use crate::{
29    defi::{
30        AmmType, Blockchain, Chain, Dex, DexType, Pool, Token, chain::chains,
31        validation::validate_address,
32    },
33    identifiers::InstrumentId,
34};
35
36#[pymethods]
37#[pyo3_stub_gen::derive::gen_stub_pymethods]
38impl Chain {
39    /// Defines a blockchain with its unique identifiers and connection details for network interaction.
40    #[new]
41    fn py_new(name: Blockchain, chain_id: u32) -> Self {
42        Self::new(name, chain_id)
43    }
44
45    fn __str__(&self) -> String {
46        self.to_string()
47    }
48
49    fn __repr__(&self) -> String {
50        format!("{self:?}")
51    }
52
53    fn __hash__(&self) -> u64 {
54        let mut hasher = DefaultHasher::new();
55        self.chain_id.hash(&mut hasher);
56        hasher.finish()
57    }
58
59    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
60        match op {
61            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
62            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
63            _ => py.NotImplemented(),
64        }
65    }
66
67    #[getter]
68    #[pyo3(name = "name")]
69    fn py_name(&self) -> Blockchain {
70        self.name
71    }
72
73    #[getter]
74    #[pyo3(name = "chain_id")]
75    fn py_chain_id(&self) -> u32 {
76        self.chain_id
77    }
78
79    #[getter]
80    #[pyo3(name = "hypersync_url")]
81    fn py_hypersync_url(&self) -> Option<&str> {
82        self.hypersync_url.as_deref()
83    }
84
85    /// Sets or clears the HyperSync endpoint.
86    #[pyo3(name = "set_hypersync_url", signature = (hypersync_url=None))]
87    fn py_set_hypersync_url(&mut self, hypersync_url: Option<String>) {
88        self.hypersync_url = hypersync_url;
89    }
90
91    #[getter]
92    #[pyo3(name = "rpc_url")]
93    fn py_rpc_url(&self) -> Option<&str> {
94        self.rpc_url.as_deref()
95    }
96
97    #[getter]
98    #[pyo3(name = "native_currency_decimals")]
99    fn py_native_currency_decimals(&self) -> u8 {
100        self.native_currency_decimals
101    }
102
103    /// Sets the RPC URL endpoint.
104    #[pyo3(name = "set_rpc_url")]
105    fn py_set_rpc_url(&mut self, rpc_url: String) {
106        self.set_rpc_url(rpc_url);
107    }
108
109    /// Returns a reference to the `Chain` corresponding to the given chain name, or `None` if it is not found.
110    ///
111    /// String matching is case-insensitive.
112    #[staticmethod]
113    #[pyo3(name = "from_chain_name")]
114    fn py_from_chain_name(chain_name: &str) -> PyResult<Self> {
115        Self::from_chain_name(chain_name)
116            .cloned()
117            .ok_or_else(|| to_pyvalue_err(format!("`chain_name` '{chain_name}' is not recognized")))
118    }
119
120    /// Returns a reference to the `Chain` corresponding to the given `chain_id`, or `None` if it is not found.
121    #[staticmethod]
122    #[pyo3(name = "from_chain_id")]
123    fn py_from_chain_id(chain_id: u32) -> Option<Self> {
124        Self::from_chain_id(chain_id).cloned()
125    }
126
127    #[staticmethod]
128    #[pyo3(name = "ARBITRUM")]
129    fn py_arbitrum_chain() -> Self {
130        chains::ARBITRUM.clone()
131    }
132}
133
134#[pymethods]
135#[pyo3_stub_gen::derive::gen_stub_pymethods]
136impl Token {
137    /// Represents a cryptocurrency token on a blockchain network.
138    #[new]
139    #[expect(clippy::needless_pass_by_value)]
140    fn py_new(
141        chain: Chain,
142        address: String,
143        name: String,
144        symbol: String,
145        decimals: u8,
146    ) -> PyResult<Self> {
147        let address = address.parse().map_err(to_pyvalue_err)?;
148        Ok(Self::new(Arc::new(chain), address, name, symbol, decimals))
149    }
150
151    fn __str__(&self) -> String {
152        self.to_string()
153    }
154
155    fn __repr__(&self) -> String {
156        format!("{self:?}")
157    }
158
159    fn __hash__(&self) -> u64 {
160        let mut hasher = DefaultHasher::new();
161        self.chain.chain_id.hash(&mut hasher);
162        self.address.hash(&mut hasher);
163        hasher.finish()
164    }
165
166    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
167        match op {
168            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
169            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
170            _ => py.NotImplemented(),
171        }
172    }
173
174    #[getter]
175    #[pyo3(name = "chain")]
176    fn py_chain(&self) -> Chain {
177        self.chain.as_ref().clone()
178    }
179
180    #[getter]
181    #[pyo3(name = "address")]
182    fn py_address(&self) -> String {
183        self.address.to_string()
184    }
185
186    #[getter]
187    #[pyo3(name = "name")]
188    fn py_name(&self) -> &str {
189        &self.name
190    }
191
192    #[getter]
193    #[pyo3(name = "symbol")]
194    fn py_symbol(&self) -> &str {
195        &self.symbol
196    }
197
198    #[getter]
199    #[pyo3(name = "decimals")]
200    fn py_decimals(&self) -> u8 {
201        self.decimals
202    }
203}
204
205#[pymethods]
206#[pyo3_stub_gen::derive::gen_stub_pymethods]
207impl Dex {
208    /// Represents a decentralized exchange (DEX) in a blockchain ecosystem.
209    #[new]
210    #[expect(clippy::too_many_arguments, clippy::needless_pass_by_value)]
211    fn py_new(
212        chain: Chain,
213        name: String,
214        factory: String,
215        factory_creation_block: u64,
216        amm_type: String,
217        pool_created_event: &str,
218        swap_event: &str,
219        mint_event: &str,
220        burn_event: &str,
221        collect_event: &str,
222    ) -> PyResult<Self> {
223        let amm_type = AmmType::from_str(&amm_type).map_err(to_pyvalue_err)?;
224        let dex_type = DexType::from_dex_name(&name)
225            .ok_or_else(|| to_pyvalue_err(format!("Invalid DEX name: {name}")))?;
226
227        validate_address(&factory).map_err(to_pyvalue_err)?;
228
229        Ok(Self::new(
230            chain,
231            dex_type,
232            &factory,
233            factory_creation_block,
234            amm_type,
235            pool_created_event,
236            swap_event,
237            mint_event,
238            burn_event,
239            collect_event,
240        ))
241    }
242
243    fn __str__(&self) -> String {
244        self.to_string()
245    }
246
247    fn __repr__(&self) -> String {
248        format!("{self:?}")
249    }
250
251    fn __hash__(&self) -> u64 {
252        let mut hasher = DefaultHasher::new();
253        self.chain.chain_id.hash(&mut hasher);
254        self.name.hash(&mut hasher);
255        self.factory.hash(&mut hasher);
256        hasher.finish()
257    }
258
259    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
260        match op {
261            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
262            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
263            _ => py.NotImplemented(),
264        }
265    }
266
267    #[getter]
268    #[pyo3(name = "chain")]
269    fn py_chain(&self) -> Chain {
270        self.chain.clone()
271    }
272
273    #[getter]
274    #[pyo3(name = "name")]
275    fn py_name(&self) -> DexType {
276        self.name
277    }
278
279    #[getter]
280    #[pyo3(name = "factory")]
281    fn py_factory(&self) -> String {
282        self.factory.to_string()
283    }
284
285    #[getter]
286    #[pyo3(name = "factory_creation_block")]
287    fn py_factory_creation_block(&self) -> u64 {
288        self.factory_creation_block
289    }
290
291    #[getter]
292    #[pyo3(name = "pool_created_event")]
293    fn py_pool_created_event(&self) -> &str {
294        &self.pool_created_event
295    }
296
297    #[getter]
298    #[pyo3(name = "swap_created_event")]
299    fn py_swap_created_event(&self) -> &str {
300        &self.swap_created_event
301    }
302
303    #[getter]
304    #[pyo3(name = "mint_created_event")]
305    fn py_mint_created_event(&self) -> &str {
306        &self.mint_created_event
307    }
308
309    #[getter]
310    #[pyo3(name = "burn_created_event")]
311    fn py_burn_created_event(&self) -> &str {
312        &self.burn_created_event
313    }
314
315    #[getter]
316    #[pyo3(name = "amm_type")]
317    fn py_amm_type(&self) -> AmmType {
318        self.amm_type
319    }
320}
321
322#[pymethods]
323#[pyo3_stub_gen::derive::gen_stub_pymethods]
324impl Pool {
325    /// Represents a liquidity pool in a decentralized exchange.
326    ///
327    /// ## Pool Identification Architecture
328    ///
329    /// Pools are identified differently depending on the DEX protocol version:
330    ///
331    /// **UniswapV2/V3**: Each pool has its own smart contract deployed at a unique address.
332    /// - `address` = pool contract address
333    /// - `pool_identifier` = same as address (hex string)
334    ///
335    /// **`UniswapV4`**: All pools share a singleton `PoolManager` contract. Pools are distinguished
336    /// by a unique Pool ID (keccak256 hash of currencies, fee, tick spacing, and hooks).
337    /// - `address` = `PoolManager` contract address (shared by all pools)
338    /// - `pool_identifier` = Pool ID (bytes32 as hex string)
339    ///
340    /// ## Instrument ID Format
341    ///
342    /// The instrument ID encodes with the following components:
343    /// - `symbol` - The pool identifier (address for V2/V3, Pool ID for V4)
344    /// - `venue`  - The chain name plus DEX ID
345    ///
346    /// String representation: `<POOL_IDENTIFIER>.<CHAIN_NAME>:<DEX_ID>`
347    ///
348    /// Example: `0x11b815efB8f581194ae79006d24E0d814B7697F6.Ethereum:UniswapV3`
349    #[new]
350    #[expect(clippy::too_many_arguments, clippy::needless_pass_by_value)]
351    fn py_new(
352        chain: Chain,
353        dex: Dex,
354        address: String,
355        pool_identifier: String,
356        creation_block: u64,
357        token0: Token,
358        token1: Token,
359        fee: Option<u32>,
360        tick_spacing: Option<u32>,
361        ts_init: u64,
362    ) -> PyResult<Self> {
363        let address = address.parse().map_err(to_pyvalue_err)?;
364        let pool_identifier = pool_identifier.parse().map_err(to_pyvalue_err)?;
365        Ok(Self::new(
366            Arc::new(chain),
367            Arc::new(dex),
368            address,
369            pool_identifier,
370            creation_block,
371            token0,
372            token1,
373            fee,
374            tick_spacing,
375            ts_init.into(),
376        ))
377    }
378
379    fn __str__(&self) -> String {
380        self.to_string()
381    }
382
383    fn __repr__(&self) -> String {
384        format!("{self:?}")
385    }
386
387    fn __hash__(&self) -> u64 {
388        let mut hasher = DefaultHasher::new();
389        self.chain.chain_id.hash(&mut hasher);
390        self.address.hash(&mut hasher);
391        hasher.finish()
392    }
393
394    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
395        match op {
396            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
397            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
398            _ => py.NotImplemented(),
399        }
400    }
401
402    #[getter]
403    #[pyo3(name = "chain")]
404    fn py_chain(&self) -> Chain {
405        self.chain.as_ref().clone()
406    }
407
408    #[getter]
409    #[pyo3(name = "dex")]
410    fn py_dex(&self) -> Dex {
411        self.dex.as_ref().clone()
412    }
413
414    #[getter]
415    #[pyo3(name = "instrument_id")]
416    fn py_instrument_id(&self) -> InstrumentId {
417        self.instrument_id
418    }
419
420    #[getter]
421    #[pyo3(name = "address")]
422    fn py_address(&self) -> String {
423        self.address.to_string()
424    }
425
426    #[getter]
427    #[pyo3(name = "creation_block")]
428    fn py_creation_block(&self) -> u64 {
429        self.creation_block
430    }
431
432    #[getter]
433    #[pyo3(name = "token0")]
434    fn py_token0(&self) -> Token {
435        self.token0.clone()
436    }
437
438    #[getter]
439    #[pyo3(name = "token1")]
440    fn py_token1(&self) -> Token {
441        self.token1.clone()
442    }
443
444    #[getter]
445    #[pyo3(name = "fee")]
446    fn py_fee(&self) -> Option<u32> {
447        self.fee
448    }
449
450    #[getter]
451    #[pyo3(name = "tick_spacing")]
452    fn py_tick_spacing(&self) -> Option<u32> {
453        self.tick_spacing
454    }
455
456    #[getter]
457    #[pyo3(name = "ts_event")]
458    fn py_ts_event(&self) -> u64 {
459        self.ts_event.as_u64()
460    }
461
462    #[getter]
463    #[pyo3(name = "ts_init")]
464    fn py_ts_init(&self) -> u64 {
465        self.ts_init.as_u64()
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    use rstest::rstest;
472
473    use super::*;
474
475    #[rstest]
476    fn test_chain_hypersync_endpoint() {
477        Python::initialize();
478
479        Python::attach(|py| {
480            let chain = Chain::new(Blockchain::Saakuru, 7_225_878);
481            let chain = Py::new(py, chain).unwrap();
482            let chain = chain.bind(py);
483            let endpoint = "https://indexer.example.com";
484            let unset = chain.getattr("hypersync_url").unwrap().is_none();
485
486            chain
487                .call_method1("set_hypersync_url", (endpoint,))
488                .unwrap();
489            let configured: String = chain.getattr("hypersync_url").unwrap().extract().unwrap();
490            chain.call_method0("set_hypersync_url").unwrap();
491            let cleared = chain.getattr("hypersync_url").unwrap().is_none();
492            let chain = chain.borrow();
493
494            assert!(unset);
495            assert_eq!(configured, endpoint);
496            assert!(cleared);
497            assert_eq!(chain.name, Blockchain::Saakuru);
498            assert_eq!(chain.chain_id, 7_225_878);
499            assert_eq!(chain.rpc_url, None);
500            assert_eq!(chain.native_currency_decimals, 18);
501        });
502    }
503}