Skip to main content

tycho_common/simulation/
protocol_sim.rs

1use std::{any::Any, collections::HashMap, fmt, sync::Arc};
2
3use num_bigint::BigUint;
4
5use crate::{
6    dto::ProtocolStateDelta,
7    models::token::Token,
8    simulation::{
9        errors::{SimulationError, TransitionError},
10        indicatively_priced::IndicativelyPriced,
11        swap::{
12            self, LimitsParams, MarginalPriceParams, QuoteParams, SwapQuoter, TransitionParams,
13        },
14    },
15    Bytes,
16};
17
18/// The block a quote is expected to execute in.
19///
20/// This is **not** the block a state was decoded from: a quote produced against block `N` is
21/// normally submitted for block `N + 1`, and a quote produced against a still-open (partial)
22/// view of block `N` is submitted for block `N` itself. Protocols whose pricing
23/// depends on the execution block — Aerodrome Slipstream's initial-vs-dynamic fee branch, for
24/// instance — resolve it from this type rather than from the block they last observed.
25#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
26#[non_exhaustive]
27pub struct BlockContext {
28    number: u64,
29    timestamp: u64,
30}
31
32impl BlockContext {
33    pub fn new(number: u64, timestamp: u64) -> Self {
34        Self { number, timestamp }
35    }
36
37    /// Height of the block the quote is expected to execute in.
38    pub fn number(&self) -> u64 {
39        self.number
40    }
41
42    /// Unix timestamp of the block the quote is expected to execute in.
43    ///
44    /// All partial blocks of one block share this value, matching `block.timestamp` on chain.
45    pub fn timestamp(&self) -> u64 {
46        self.timestamp
47    }
48}
49
50#[derive(Default, Debug, Clone)]
51pub struct Balances {
52    pub component_balances: HashMap<String, HashMap<Bytes, Bytes>>,
53    pub account_balances: HashMap<Bytes, HashMap<Bytes, Bytes>>,
54}
55
56/// Represents the result of getting the amount out of a trading pair.
57#[derive(Debug, Clone)]
58pub struct GetAmountOutResult {
59    /// The output amount
60    pub amount: BigUint,
61    /// The gas cost
62    pub gas: BigUint,
63    /// The new state after the swap
64    pub new_state: Box<dyn ProtocolSim>,
65}
66
67impl GetAmountOutResult {
68    /// Constructs a new GetAmountOutResult struct with the given amount and gas
69    pub fn new(amount: BigUint, gas: BigUint, new_state: Box<dyn ProtocolSim>) -> Self {
70        GetAmountOutResult { amount, gas, new_state }
71    }
72
73    /// Aggregates the given GetAmountOutResult struct to the current one.
74    /// It updates the amount with the other's amount and adds the other's gas to the current one's
75    /// gas.
76    pub fn aggregate(&mut self, other: &Self) {
77        self.amount = other.amount.clone();
78        self.gas += &other.gas;
79    }
80}
81
82impl fmt::Display for GetAmountOutResult {
83    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84        write!(f, "amount = {}, gas = {}", self.amount, self.gas)
85    }
86}
87
88/// Represents a price as a fraction in the token_in -> token_out direction with units
89/// `[token_out/token_in]`.
90///
91/// A fraction struct is used for price to have flexibility in precision independent of the
92/// decimal precisions of the numerator and denominator tokens. This allows for:
93/// - Exact price representation without floating-point errors
94/// - Handling tokens with different decimal places without loss of precision
95///
96/// # Example
97/// If we want to represent that token A is worth 2.5 units of token B:
98///
99/// ```
100/// use num_bigint::BigUint;
101/// use tycho_common::simulation::protocol_sim::Price;
102///
103/// let numerator = BigUint::from(25u32); // Represents 25 units of token B
104/// let denominator = BigUint::from(10u32); // Represents 10 units of token A
105/// let price = Price::new(numerator, denominator);
106/// ```
107///
108/// If you want to define a limit price for a trade, where you expect to get at least 120 T1 for
109/// 50 T2:
110/// ```
111/// use num_bigint::BigUint;
112/// use tycho_common::simulation::protocol_sim::Price;
113///
114/// let min_amount_out = BigUint::from(120u32); // The minimum amount of T1 you expect
115/// let amount_in = BigUint::from(50u32); // The amount of T2 you are selling
116/// let limit_price = Price::new(min_amount_out, amount_in);
117/// ```
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub struct Price {
120    /// The amount of token_out (what you receive), including token decimals
121    pub numerator: BigUint,
122    /// The amount of token_in (what you pay), including token decimals
123    pub denominator: BigUint,
124}
125
126impl Price {
127    pub fn new(numerator: BigUint, denominator: BigUint) -> Self {
128        if denominator == BigUint::ZERO {
129            // Division by zero is not possible
130            panic!("Price denominator cannot be zero");
131        } else if numerator == BigUint::ZERO {
132            // Zero pool price is not valid in our context
133            panic!("Price numerator cannot be zero");
134        }
135        Self { numerator, denominator }
136    }
137}
138
139/// A point on the AMM price curve.
140///
141/// Collected during iterative numerical search algorithms.
142/// These points can be reused as bounds for subsequent searches, improving convergence speed.
143#[derive(Debug, Clone)]
144pub struct PricePoint {
145    /// The amount of token_in in atomic units (wei).
146    pub amount_in: BigUint,
147    /// The amount of token_out in atomic units (wei).
148    pub amount_out: BigUint,
149    /// The price in units of `[token_out/token_in]` scaled by decimals.
150    ///
151    /// Computed as `(amount_out / 10^token_out_decimals) / (amount_in / 10^token_in_decimals)`.
152    pub price: f64,
153}
154
155impl PricePoint {
156    pub fn new(amount_in: BigUint, amount_out: BigUint, price: f64) -> Self {
157        Self { amount_in, amount_out, price }
158    }
159}
160
161/// Represents a pool swap between two tokens at a given price on a pool.
162#[derive(Debug, Clone)]
163pub struct PoolSwap {
164    /// The amount of token_in sold to the pool
165    amount_in: BigUint,
166    /// The amount of token_out bought from the pool
167    amount_out: BigUint,
168    /// The new state of the pool after the swap
169    new_state: Box<dyn ProtocolSim>,
170    /// Optional price points that the pool was transitioned through while computing this swap.
171    /// Useful for providing good bounds for repeated calls.
172    price_points: Option<Vec<PricePoint>>,
173}
174
175impl PoolSwap {
176    pub fn new(
177        amount_in: BigUint,
178        amount_out: BigUint,
179        new_state: Box<dyn ProtocolSim>,
180        price_points: Option<Vec<PricePoint>>,
181    ) -> Self {
182        Self { amount_in, amount_out, new_state, price_points }
183    }
184
185    pub fn amount_in(&self) -> &BigUint {
186        &self.amount_in
187    }
188
189    pub fn amount_out(&self) -> &BigUint {
190        &self.amount_out
191    }
192
193    pub fn new_state(&self) -> &dyn ProtocolSim {
194        self.new_state.as_ref()
195    }
196
197    #[expect(
198        clippy::ref_option,
199        reason = "public API; changing the signature is a breaking change"
200    )]
201    pub fn price_points(&self) -> &Option<Vec<PricePoint>> {
202        &self.price_points
203    }
204}
205
206/// Options on how to constrain the pool swap query.
207///
208/// All prices use units `[token_out/token_in]` with amounts in atomic units (wei). When selling
209/// token_in into a pool, prices decrease due to slippage.
210#[derive(Debug, Clone, PartialEq)]
211pub enum SwapConstraint {
212    /// Calculates the maximum trade while respecting a minimum trade price.
213    TradeLimitPrice {
214        /// The minimum acceptable trade price. The resulting `amount_out / amount_in >= limit`.
215        limit: Price,
216        /// Fraction to raise the acceptance threshold above `limit`. Loosens the search criteria
217        /// but will never allow violating the trade limit price itself.
218        tolerance: f64,
219        /// The minimum amount of token_in that must be used for this trade.
220        min_amount_in: Option<BigUint>,
221        /// The maximum amount of token_in that can be used for this trade.
222        max_amount_in: Option<BigUint>,
223    },
224
225    /// Calculates the swap required to move the pool's marginal price down to a target.
226    ///
227    /// # Edge Cases and Limitations
228    ///
229    /// Computing the exact amount to move a pool's marginal price to a target has several
230    /// challenges:
231    /// - The definition of marginal price varies between protocols. It is usually not an attribute
232    ///   of the pool but a consequence of its liquidity distribution and current state.
233    /// - For protocols with concentrated liquidity, the marginal price is discrete, meaning we
234    ///   can't always find an exact trade amount to reach the target price.
235    /// - Not all protocols support analytical solutions for this problem, requiring numerical
236    ///   methods.
237    PoolTargetPrice {
238        /// The target marginal price for the pool after the trade. The pool's price decreases
239        /// toward this target as token_in is sold into it.
240        target: Price,
241        /// Fraction above `target` considered acceptable. After trading, the pool's marginal
242        /// price will be in `[target, target * (1 + tolerance)]`.
243        tolerance: f64,
244        /// The lower bound for searching algorithms.
245        min_amount_in: Option<BigUint>,
246        /// The upper bound for searching algorithms.
247        max_amount_in: Option<BigUint>,
248    },
249}
250
251/// Represents the parameters for [ProtocolSim::query_pool_swap].
252#[derive(Debug, Clone, PartialEq)]
253pub struct QueryPoolSwapParams {
254    /// The token being sold (swapped into the pool)
255    token_in: Token,
256    /// The token being bought (swapped out of the pool)
257    token_out: Token,
258    /// Type of price constraint to be applied. See [SwapConstraint].
259    swap_constraint: SwapConstraint,
260}
261
262impl QueryPoolSwapParams {
263    pub fn new(token_in: Token, token_out: Token, swap_constraint: SwapConstraint) -> Self {
264        Self { token_in, token_out, swap_constraint }
265    }
266
267    /// Returns a reference to the input token (token being sold into the pool)
268    pub fn token_in(&self) -> &Token {
269        &self.token_in
270    }
271
272    /// Returns a reference to the output token (token being bought out of the pool)
273    pub fn token_out(&self) -> &Token {
274        &self.token_out
275    }
276
277    /// Returns a reference to the price constraint
278    pub fn swap_constraint(&self) -> &SwapConstraint {
279        &self.swap_constraint
280    }
281}
282
283/// A `U256` as its four 64-bit limbs, least significant first.
284///
285/// [`ProtocolSim::query_supply_to_price`] takes and returns raw limbs so callers can pass
286/// prices and amounts without converting through `BigUint`.
287pub type U256Limbs = [u64; 4];
288
289/// ProtocolSim trait
290/// This trait defines the methods that a protocol state must implement in order to be used
291/// in the trade simulation.
292#[typetag::serde(tag = "protocol", content = "state")]
293pub trait ProtocolSim: fmt::Debug + Send + Sync + 'static {
294    /// Returns the fee of the protocol as ratio
295    ///
296    /// E.g. if the fee is 1%, the value returned would be 0.01.
297    ///
298    /// # Panics
299    ///
300    /// Currently panic for protocols with asymmetric fees (e.g. Rocketpool, Uniswap V4),
301    /// where a single fee value cannot represent the protocol's fee structure.
302    fn fee(&self) -> f64;
303
304    /// Returns the protocol's current spot buy price for `base` in units of `quote`.
305    ///
306    /// The returned price is the amount of `quote` required to buy exactly 1 unit of `base`,
307    /// accounting for the protocol fee (i.e. `price = pre_fee_price / (1.0 - fee)`)
308    /// and assuming zero slippage (i.e., a negligibly small trade size).
309    ///
310    /// # Arguments
311    /// * `base` - the token being priced (what you buy). For BTC/USDT, BTC is the base token.
312    /// * `quote` - the token used to price (pay) for `base`. For BTC/USDT, USDT is the quote token.
313    ///
314    /// # Examples
315    /// If the BTC/USDT is trading at 1000 with a 20% fee, this returns `1000 / (1.0 - 0.20) = 1250`
316    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError>;
317
318    /// Returns the amount out given an amount in and input/output tokens.
319    ///
320    /// # Arguments
321    ///
322    /// * `amount_in` - The amount in of the input token.
323    /// * `token_in` - The input token ERC20 token.
324    /// * `token_out` - The output token ERC20 token.
325    ///
326    /// # Returns
327    ///
328    /// A `Result` containing a `GetAmountOutResult` struct on success or a
329    ///  `SimulationError` on failure.
330    fn get_amount_out(
331        &self,
332        amount_in: BigUint,
333        token_in: &Token,
334        token_out: &Token,
335    ) -> Result<GetAmountOutResult, SimulationError>;
336
337    /// Computes the maximum amount that can be traded between two tokens.
338    ///
339    /// This function calculates the maximum possible trade amount between two tokens,
340    /// taking into account the protocol's specific constraints and mechanics.
341    /// The implementation details vary by protocol - for example:
342    /// - For constant product AMMs (like Uniswap V2), this is based on available reserves
343    /// - For concentrated liquidity AMMs (like Uniswap V3), this considers liquidity across tick
344    ///   ranges
345    ///
346    /// Note: if there are no limits, the returned amount will be a "soft" limit,
347    ///       meaning that the actual amount traded could be higher but it's advised to not
348    ///       exceed it.
349    ///
350    /// # Arguments
351    /// * `sell_token` - The address of the token being sold
352    /// * `buy_token` - The address of the token being bought
353    ///
354    /// # Returns
355    /// * `Ok((BigUint, BigUint))` - A tuple containing:
356    ///   - First element: The maximum input amount (sell_token)
357    ///   - Second element: The maximum output amount (buy_token)
358    ///
359    /// For `let res = get_limits(...)`, the valid input domain for `get_amount_out` is `[0,
360    /// res.0]`.
361    ///
362    /// * `Err(SimulationError)` - If any unexpected error occurs
363    fn get_limits(
364        &self,
365        sell_token: Bytes,
366        buy_token: Bytes,
367    ) -> Result<(BigUint, BigUint), SimulationError>;
368
369    /// Decodes and applies a protocol state delta to the state
370    ///
371    /// Will error if the provided delta is missing any required attributes or if any of the
372    /// attribute values cannot be decoded.
373    ///
374    /// # Arguments
375    ///
376    /// * `delta` - A `ProtocolStateDelta` from the tycho indexer
377    ///
378    /// # Returns
379    ///
380    /// * `Result<(), TransitionError<String>>` - A `Result` containing `()` on success or a
381    ///   `TransitionError` on failure.
382    fn delta_transition(
383        &mut self,
384        delta: ProtocolStateDelta,
385        tokens: &HashMap<Bytes, Token>,
386        balances: &Balances,
387    ) -> Result<(), TransitionError>;
388
389    /// Calculates the swap volume required to achieve the provided goal when trading against this
390    /// pool.
391    ///
392    /// This method will branch towards different behaviors based on [SwapConstraint] enum. Please
393    /// refer to its documentation for further details on each behavior.
394    ///
395    /// In short, the current two options are:
396    /// - Maximize your trade while respecting a trade limit price:
397    ///   [SwapConstraint::TradeLimitPrice]
398    /// - Move the pool price to a target price: [SwapConstraint::PoolTargetPrice]
399    ///
400    /// # Arguments
401    ///
402    /// * `params` - A [QueryPoolSwapParams] struct containing the inputs for this method.
403    ///
404    /// # Returns
405    ///
406    /// * `Ok(PoolSwap)` - A `PoolSwap` struct containing the amounts to be traded and the state of
407    ///   the pool after trading.
408    /// * `Err(SimulationError)` - If:
409    ///   - The calculation encounters numerical issues
410    ///   - The method is not implemented for this protocol
411    fn query_pool_swap(&self, _params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
412        Err(SimulationError::FatalError("query_pool_swap not implemented".into()))
413    }
414
415    /// Computes `(amount_in, amount_out)` required to move the pool's marginal price to
416    /// `target_num / target_den` (`token_out / token_in` in raw atomic units), without cloning
417    /// tokens or allocating a post-swap `Box<dyn ProtocolSim>`.
418    ///
419    /// Returns `Ok(None)` when the target price is unreachable or yields zero output.
420    fn query_supply_to_price(
421        &self,
422        token_in: &Token,
423        token_out: &Token,
424        target_num: U256Limbs,
425        target_den: U256Limbs,
426    ) -> Result<Option<(U256Limbs, U256Limbs)>, SimulationError> {
427        let mut num_bytes = [0u8; 32];
428        let mut den_bytes = [0u8; 32];
429        for i in 0..4 {
430            num_bytes[i * 8..(i + 1) * 8].copy_from_slice(&target_num[i].to_le_bytes());
431            den_bytes[i * 8..(i + 1) * 8].copy_from_slice(&target_den[i].to_le_bytes());
432        }
433        let price =
434            Price::new(BigUint::from_bytes_le(&num_bytes), BigUint::from_bytes_le(&den_bytes));
435        let params = QueryPoolSwapParams::new(
436            token_in.clone(),
437            token_out.clone(),
438            SwapConstraint::PoolTargetPrice {
439                target: price,
440                tolerance: 0.0,
441                min_amount_in: None,
442                max_amount_in: None,
443            },
444        );
445        match self.query_pool_swap(&params) {
446            Ok(swap) => {
447                let to_limbs = |v: &BigUint| -> [u64; 4] {
448                    let bytes = v.to_bytes_le();
449                    if bytes.len() > 32 {
450                        return [u64::MAX; 4];
451                    }
452                    let mut buf = [0u8; 32];
453                    buf[..bytes.len()].copy_from_slice(&bytes);
454                    [
455                        u64::from_le_bytes(buf[0..8].try_into().unwrap()),
456                        u64::from_le_bytes(buf[8..16].try_into().unwrap()),
457                        u64::from_le_bytes(buf[16..24].try_into().unwrap()),
458                        u64::from_le_bytes(buf[24..32].try_into().unwrap()),
459                    ]
460                };
461                Ok(Some((to_limbs(swap.amount_in()), to_limbs(swap.amount_out()))))
462            }
463            Err(SimulationError::InvalidInput(_, _)) => Ok(None),
464            Err(e) => Err(e),
465        }
466    }
467
468    /// Clones the protocol state as a trait object.
469    /// This allows the state to be cloned when it is being used as a `Box<dyn ProtocolSim>`.
470    fn clone_box(&self) -> Box<dyn ProtocolSim>;
471
472    /// Allows downcasting of the trait object to its underlying type.
473    fn as_any(&self) -> &dyn Any;
474
475    /// Allows downcasting of the trait object to its mutable underlying type.
476    fn as_any_mut(&mut self) -> &mut dyn Any;
477
478    /// Compares two protocol states for equality.
479    /// This method must be implemented to define how two protocol states are considered equal
480    /// (used for tests).
481    fn eq(&self, other: &dyn ProtocolSim) -> bool;
482
483    /// Cast as IndicativelyPriced. This is necessary for RFQ protocols
484    fn as_indicatively_priced(&self) -> Result<&dyn IndicativelyPriced, SimulationError> {
485        Err(SimulationError::FatalError("Pool State does not implement IndicativelyPriced".into()))
486    }
487
488    /// Advances the state to the block a quote is expected to execute in.
489    ///
490    /// Returns `true` when quoting behavior changed and the state must be re-emitted to
491    /// consumers. The stream decoder calls this on every message — including messages in which
492    /// the pool itself did not change, since without that a state's notion of the execution
493    /// block would freeze at the pool's last update. Implementations must be idempotent for a
494    /// repeated block and must not use the value as a substitute for the block they were decoded
495    /// from: it describes the future, not the observed past.
496    fn apply_block(&mut self, _block: &BlockContext) -> bool {
497        false
498    }
499
500    /// Runs every later quote from this state under a pending block's state, held in
501    /// `overrides`.
502    ///
503    /// The payload type belongs to the simulation crate that builds it. The default ignores it,
504    /// for protocols that do not simulate pending state.
505    ///
506    /// # Errors
507    /// Returns an error when the protocol simulates pending state but `overrides` is not the
508    /// type it expects.
509    fn set_pending_overrides(
510        &mut self,
511        _overrides: Arc<dyn Any + Send + Sync>,
512    ) -> Result<(), SimulationError> {
513        Ok(())
514    }
515}
516
517impl Clone for Box<dyn ProtocolSim> {
518    fn clone(&self) -> Box<dyn ProtocolSim> {
519        self.clone_box()
520    }
521}
522
523impl<T> ProtocolSim for T
524where
525    T: SwapQuoter + Clone + Send + Sync + Eq + 'static,
526{
527    fn fee(&self) -> f64 {
528        self.quotable_pairs()
529            .iter()
530            .map(|(t0, t1)| {
531                let amount = BigUint::from(10u32).pow(t0.decimals);
532                if let Ok(params) = QuoteParams::fixed_in(&t0.address, &t1.address, amount) {
533                    self.fee(params)
534                        .map(|f| f.fee())
535                        .unwrap_or(f64::MAX)
536                } else {
537                    f64::MAX
538                }
539            })
540            .reduce(f64::min)
541            .unwrap_or(f64::MAX)
542    }
543
544    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
545        self.marginal_price(MarginalPriceParams::new(&base.address, &quote.address))
546            .map(|r| r.price())
547    }
548
549    fn get_amount_out(
550        &self,
551        amount_in: BigUint,
552        token_in: &Token,
553        token_out: &Token,
554    ) -> Result<GetAmountOutResult, SimulationError> {
555        #[expect(deprecated, reason = "implements the deprecated get_amount_out on top of quote")]
556        self.quote(
557            QuoteParams::fixed_in(&token_in.address, &token_out.address, amount_in)?
558                .with_new_state(),
559        )
560        .map(|r| {
561            GetAmountOutResult::new(
562                r.amount_out().clone(),
563                r.gas().clone(),
564                r.new_state()
565                    .expect("quote includes new state")
566                    .to_protocol_sim(),
567            )
568        })
569    }
570
571    fn get_limits(
572        &self,
573        sell_token: Bytes,
574        buy_token: Bytes,
575    ) -> Result<(BigUint, BigUint), SimulationError> {
576        self.swap_limits(LimitsParams::new(&sell_token, &buy_token))
577            .map(|r| (r.range_in().upper().clone(), r.range_out().upper().clone()))
578    }
579
580    fn delta_transition(
581        &mut self,
582        delta: ProtocolStateDelta,
583        tokens: &HashMap<Bytes, Token>,
584        balances: &Balances,
585    ) -> Result<(), TransitionError> {
586        self.delta_transition(TransitionParams::new(delta, tokens, balances))
587            .map(|_| ())
588    }
589
590    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
591        let constraint = match params.swap_constraint.clone() {
592            SwapConstraint::TradeLimitPrice { limit, tolerance, min_amount_in, max_amount_in } => {
593                swap::SwapConstraint::TradeLimitPrice {
594                    limit,
595                    tolerance,
596                    min_amount_in,
597                    max_amount_in,
598                }
599            }
600            SwapConstraint::PoolTargetPrice { target, tolerance, min_amount_in, max_amount_in } => {
601                swap::SwapConstraint::PoolTargetPrice {
602                    target,
603                    tolerance,
604                    min_amount_in,
605                    max_amount_in,
606                }
607            }
608        };
609        #[expect(
610            deprecated,
611            reason = "implements the deprecated query_pool_swap on top of query_swap"
612        )]
613        self.query_swap(swap::QuerySwapParams::new(
614            &params.token_in.address,
615            &params.token_out.address,
616            constraint,
617        ))
618        .map(|r| {
619            PoolSwap::new(
620                r.amount_in().clone(),
621                r.amount_out().clone(),
622                r.new_state().unwrap().to_protocol_sim(),
623                r.price_points().as_ref().map(|points| {
624                    points
625                        .iter()
626                        .map(|p| {
627                            PricePoint::new(
628                                p.amount_in().clone(),
629                                p.amount_out().clone(),
630                                p.price(),
631                            )
632                        })
633                        .collect()
634                }),
635            )
636        })
637    }
638
639    fn clone_box(&self) -> Box<dyn ProtocolSim> {
640        #[expect(
641            deprecated,
642            reason = "to_protocol_sim is deprecated for consumers but is the clone implementation here"
643        )]
644        self.to_protocol_sim()
645    }
646
647    fn as_any(&self) -> &dyn Any {
648        self
649    }
650
651    fn as_any_mut(&mut self) -> &mut dyn Any {
652        self
653    }
654
655    fn eq(&self, other: &dyn ProtocolSim) -> bool {
656        if let Some(other) = other.as_any().downcast_ref::<T>() {
657            self == other
658        } else {
659            false
660        }
661    }
662
663    fn typetag_name(&self) -> &'static str {
664        self.typetag_name()
665    }
666
667    fn typetag_deserialize(&self) {
668        self.typetag_deserialize()
669    }
670}
671
672#[cfg(test)]
673mod tests {
674
675    use super::*;
676
677    #[test]
678    fn serde() {
679        use serde::{Deserialize, Serialize};
680
681        #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
682        struct DummyProtocol {
683            reserve_0: u64,
684            reserve_1: u64,
685        }
686
687        #[typetag::serde]
688        #[expect(clippy::todo, reason = "test double: the test only serializes it")]
689        impl ProtocolSim for DummyProtocol {
690            fn clone_box(&self) -> Box<dyn ProtocolSim> {
691                todo!()
692            }
693
694            fn as_any(&self) -> &dyn Any {
695                self
696            }
697
698            fn as_any_mut(&mut self) -> &mut dyn Any {
699                todo!()
700            }
701
702            fn eq(&self, other: &dyn ProtocolSim) -> bool {
703                if let Some(other) = other.as_any().downcast_ref::<Self>() {
704                    self.reserve_0 == other.reserve_0 && self.reserve_1 == other.reserve_1
705                } else {
706                    false
707                }
708            }
709
710            fn fee(&self) -> f64 {
711                todo!()
712            }
713            fn spot_price(&self, _base: &Token, _quote: &Token) -> Result<f64, SimulationError> {
714                todo!()
715            }
716            fn get_amount_out(
717                &self,
718                _amount_in: BigUint,
719                _token_in: &Token,
720                _token_out: &Token,
721            ) -> Result<GetAmountOutResult, SimulationError> {
722                todo!()
723            }
724            fn get_limits(
725                &self,
726                _sell_token: Bytes,
727                _buy_token: Bytes,
728            ) -> Result<(BigUint, BigUint), SimulationError> {
729                todo!()
730            }
731            fn delta_transition(
732                &mut self,
733                _delta: ProtocolStateDelta,
734                _tokens: &HashMap<Bytes, Token>,
735                _balances: &Balances,
736            ) -> Result<(), TransitionError> {
737                todo!()
738            }
739        }
740
741        let state = DummyProtocol { reserve_0: 1, reserve_1: 2 };
742
743        assert_eq!(serde_json::to_string(&state).unwrap(), r#"{"reserve_0":1,"reserve_1":2}"#);
744        assert_eq!(
745            serde_json::to_string(&state as &dyn ProtocolSim).unwrap(),
746            r#"{"protocol":"DummyProtocol","state":{"reserve_0":1,"reserve_1":2}}"#
747        );
748
749        let deserialized: Box<dyn ProtocolSim> = serde_json::from_str(
750            r#"{"protocol":"DummyProtocol","state":{"reserve_0":1,"reserve_1":2}}"#,
751        )
752        .unwrap();
753
754        assert!(deserialized.eq(&state));
755    }
756}