Skip to main content

nautilus_common/defi/
cache.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//! DeFi-specific cache functionality.
17
18use std::{cell::RefCell, fmt::Debug, sync::Arc};
19
20use ahash::{AHashMap, AHashSet};
21use nautilus_model::{
22    defi::{Pool, PoolProfiler, currency},
23    identifiers::{ClientId, InstrumentId, Venue},
24    instruments::{Instrument, InstrumentAny},
25    orders::Order,
26    types::Currency,
27};
28use ustr::Ustr;
29
30use crate::cache::Cache;
31
32/// Identifies a DeFi currency conflict that prevents dependent state from being published.
33#[derive(Debug, thiserror::Error)]
34#[error("DeFi currency integrity: {0}")]
35pub struct IntegrityError(pub String);
36
37/// DeFi-specific cache state.
38#[derive(Clone, Debug, Default)]
39pub(crate) struct DefiCache {
40    currencies: AHashSet<Ustr>,
41    execution_checks: RefCell<AHashMap<ClientId, ExecutionCheck>>,
42    pools: AHashMap<InstrumentId, Pool>,
43    pool_profilers: AHashMap<InstrumentId, PoolProfiler>,
44}
45
46#[derive(Clone)]
47struct ExecutionCheck {
48    chain_id: u32,
49    check: Arc<dyn Fn(InstrumentId) -> anyhow::Result<()> + Send + Sync>,
50}
51
52impl Debug for ExecutionCheck {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.debug_struct(stringify!(ExecutionCheck))
55            .field("chain_id", &self.chain_id)
56            .finish_non_exhaustive()
57    }
58}
59
60/// Checks the live state and authoritative intent stores before replacing a legacy instrument.
61///
62/// The cache creates this check for one instrument. Backends invoke it only for legacy replacement.
63#[derive(Clone)]
64pub struct InstrumentMigration {
65    check: Arc<dyn Fn() -> anyhow::Result<()> + Send + Sync>,
66}
67
68impl Debug for InstrumentMigration {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        f.write_str("InstrumentMigration")
71    }
72}
73
74impl InstrumentMigration {
75    /// Checks that replacement preserves live state and has no active swap intent.
76    ///
77    /// # Errors
78    ///
79    /// Returns an error if position history, nonterminal orders, or unavailable or active execution
80    /// state blocks replacement.
81    pub fn validate(&self) -> anyhow::Result<()> {
82        (self.check)()
83    }
84}
85
86impl Cache {
87    /// Registers the authoritative execution-store check for a blockchain client.
88    ///
89    /// The check covers active swap intents for an instrument, including when the cache uses another store.
90    pub fn register_defi_execution_check(
91        &self,
92        client_id: ClientId,
93        chain_id: u32,
94        check: impl Fn(InstrumentId) -> anyhow::Result<()> + Send + Sync + 'static,
95    ) {
96        self.defi.execution_checks.borrow_mut().insert(
97            client_id,
98            ExecutionCheck {
99                chain_id,
100                check: Arc::new(check),
101            },
102        );
103    }
104
105    pub(crate) fn check_instrument_migration(
106        &self,
107        instrument: &InstrumentAny,
108    ) -> anyhow::Result<Option<InstrumentMigration>> {
109        let id = instrument.id();
110        let previous = self.instrument(&id);
111
112        let changed = previous.is_some_and(|previous| {
113            previous.base_currency() != instrument.base_currency()
114                || previous.quote_currency() != instrument.quote_currency()
115                || previous.settlement_currency() != instrument.settlement_currency()
116        });
117
118        if let Some(previous) = previous
119            && changed
120            && !currency::instrument_codes(previous)?.is_empty()
121        {
122            return Err(IntegrityError(
123                "Cannot change a token instrument's currency identities".into(),
124            )
125            .into());
126        }
127
128        if currency::instrument_codes(instrument)?.is_empty() {
129            return Ok(None);
130        }
131
132        let migration = self.instrument_migration(instrument)?;
133        if changed
134            || (previous.is_none()
135                && (self.has_position_history(&id)? || self.has_nonterminal_orders(&id)))
136        {
137            migration.validate()?;
138        }
139
140        Ok(Some(migration))
141    }
142
143    pub(crate) fn instrument_migration(
144        &self,
145        instrument: &InstrumentAny,
146    ) -> anyhow::Result<InstrumentMigration> {
147        let id = instrument.id();
148        let history = self.has_position_history(&id)?;
149        let orders = self.has_nonterminal_orders(&id);
150        let mut chains = Vec::new();
151
152        for code in currency::instrument_codes(instrument)? {
153            let (_, metadata) = currency::lookup(Ustr::from(&code))
154                .ok_or_else(|| anyhow::anyhow!("Missing token definition for {code}"))?;
155            chains.push(metadata.chain_id);
156        }
157
158        chains.sort_unstable();
159        chains.dedup();
160        let checks = self
161            .defi
162            .execution_checks
163            .borrow()
164            .values()
165            .cloned()
166            .collect::<Vec<_>>();
167        Ok(InstrumentMigration {
168            check: Arc::new(move || {
169                anyhow::ensure!(
170                    !history,
171                    "Instrument {id} has position history; retain its legacy currencies"
172                );
173                anyhow::ensure!(!orders, "Instrument {id} has nonterminal orders");
174
175                for chain in &chains {
176                    let matching = checks
177                        .iter()
178                        .filter(|check| check.chain_id == *chain)
179                        .collect::<Vec<_>>();
180                    anyhow::ensure!(
181                        !matching.is_empty(),
182                        "No authoritative execution-store check for chain {chain}; cannot replace {id}"
183                    );
184
185                    for check in matching {
186                        (check.check)(id)?;
187                    }
188                }
189
190                Ok(())
191            }),
192        })
193    }
194
195    fn has_nonterminal_orders(&self, id: &InstrumentId) -> bool {
196        self.orders_refs(None, Some(id), None, None, None)
197            .iter()
198            .any(|order| !order.is_closed())
199    }
200
201    /// Adds a `Pool` to the cache.
202    ///
203    /// This function does not return errors; the result type matches the other add methods.
204    #[allow(
205        clippy::missing_errors_doc,
206        reason = "this method only inserts into the in-memory cache"
207    )]
208    pub fn add_pool(&mut self, pool: Pool) -> anyhow::Result<()> {
209        log::debug!("Adding `Pool` {}", pool.instrument_id);
210
211        self.defi.pools.insert(pool.instrument_id, pool);
212        Ok(())
213    }
214
215    /// Adds a `PoolProfiler` to the cache.
216    ///
217    /// This function does not return errors; the result type matches the other add methods.
218    #[allow(
219        clippy::missing_errors_doc,
220        reason = "this method only inserts into the in-memory cache"
221    )]
222    pub fn add_pool_profiler(&mut self, pool_profiler: PoolProfiler) -> anyhow::Result<()> {
223        let instrument_id = pool_profiler.pool.instrument_id;
224        log::debug!("Adding `PoolProfiler` {instrument_id}");
225
226        self.defi
227            .pool_profilers
228            .insert(instrument_id, pool_profiler);
229        Ok(())
230    }
231
232    /// Gets a reference to the pool for the `instrument_id`.
233    #[must_use]
234    pub fn pool(&self, instrument_id: &InstrumentId) -> Option<&Pool> {
235        self.defi.pools.get(instrument_id)
236    }
237
238    /// Gets a mutable reference to the pool for the `instrument_id`.
239    #[must_use]
240    pub fn pool_mut(&mut self, instrument_id: &InstrumentId) -> Option<&mut Pool> {
241        self.defi.pools.get_mut(instrument_id)
242    }
243
244    /// Returns the instrument IDs of all pools in the cache, optionally filtered by `venue`.
245    #[must_use]
246    pub fn pool_ids(&self, venue: Option<&Venue>) -> Vec<InstrumentId> {
247        match venue {
248            Some(v) => self
249                .defi
250                .pools
251                .keys()
252                .filter(|id| &id.venue == v)
253                .copied()
254                .collect(),
255            None => self.defi.pools.keys().copied().collect(),
256        }
257    }
258
259    /// Returns references to all pools in the cache, optionally filtered by `venue`.
260    #[must_use]
261    pub fn pools(&self, venue: Option<&Venue>) -> Vec<&Pool> {
262        match venue {
263            Some(v) => self
264                .defi
265                .pools
266                .values()
267                .filter(|p| &p.instrument_id.venue == v)
268                .collect(),
269            None => self.defi.pools.values().collect(),
270        }
271    }
272
273    /// Gets a reference to the pool profiler for the `instrument_id`.
274    #[must_use]
275    pub fn pool_profiler(&self, instrument_id: &InstrumentId) -> Option<&PoolProfiler> {
276        self.defi.pool_profilers.get(instrument_id)
277    }
278
279    /// Gets a mutable reference to the pool profiler for the `instrument_id`.
280    #[must_use]
281    pub fn pool_profiler_mut(&mut self, instrument_id: &InstrumentId) -> Option<&mut PoolProfiler> {
282        self.defi.pool_profilers.get_mut(instrument_id)
283    }
284
285    /// Returns the instrument IDs of all pool profilers in the cache, optionally filtered by `venue`.
286    #[must_use]
287    pub fn pool_profiler_ids(&self, venue: Option<&Venue>) -> Vec<InstrumentId> {
288        match venue {
289            Some(v) => self
290                .defi
291                .pool_profilers
292                .keys()
293                .filter(|id| &id.venue == v)
294                .copied()
295                .collect(),
296            None => self.defi.pool_profilers.keys().copied().collect(),
297        }
298    }
299
300    /// Returns references to all pool profilers in the cache, optionally filtered by `venue`.
301    #[must_use]
302    pub fn pool_profilers(&self, venue: Option<&Venue>) -> Vec<&PoolProfiler> {
303        match venue {
304            Some(v) => self
305                .defi
306                .pool_profilers
307                .values()
308                .filter(|p| &p.pool.instrument_id.venue == v)
309                .collect(),
310            None => self.defi.pool_profilers.values().collect(),
311        }
312    }
313}
314
315impl DefiCache {
316    pub(crate) fn restore_currencies(&mut self, currencies: &AHashMap<Ustr, Currency>) {
317        self.currencies = currencies
318            .values()
319            .filter(|currency| currency::lookup(currency.code).is_some())
320            .map(|currency| currency.code)
321            .collect();
322    }
323
324    pub(crate) fn contains_currency(&self, code: &Ustr) -> bool {
325        self.currencies.contains(code)
326    }
327
328    pub(crate) fn add_currency(&mut self, code: Ustr) {
329        self.currencies.insert(code);
330    }
331
332    pub(crate) fn clear_currencies(&mut self) {
333        self.currencies.clear();
334    }
335
336    pub(crate) fn remove_instrument(&mut self, instrument_id: &InstrumentId) {
337        self.pools.remove(instrument_id);
338        self.pool_profilers.remove(instrument_id);
339    }
340
341    pub(crate) fn clear_pools(&mut self) {
342        self.pools.clear();
343        self.pool_profilers.clear();
344    }
345}