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/// flashblock) 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 flashblocks 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/// ProtocolSim trait
284/// This trait defines the methods that a protocol state must implement in order to be used
285/// in the trade simulation.
286#[typetag::serde(tag = "protocol", content = "state")]
287pub trait ProtocolSim: fmt::Debug + Send + Sync + 'static {
288    /// Returns the fee of the protocol as ratio
289    ///
290    /// E.g. if the fee is 1%, the value returned would be 0.01.
291    ///
292    /// # Panics
293    ///
294    /// Currently panic for protocols with asymmetric fees (e.g. Rocketpool, Uniswap V4),
295    /// where a single fee value cannot represent the protocol's fee structure.
296    fn fee(&self) -> f64;
297
298    /// Returns the protocol's current spot buy price for `base` in units of `quote`.
299    ///
300    /// The returned price is the amount of `quote` required to buy exactly 1 unit of `base`,
301    /// accounting for the protocol fee (i.e. `price = pre_fee_price / (1.0 - fee)`)
302    /// and assuming zero slippage (i.e., a negligibly small trade size).
303    ///
304    /// # Arguments
305    /// * `base` - the token being priced (what you buy). For BTC/USDT, BTC is the base token.
306    /// * `quote` - the token used to price (pay) for `base`. For BTC/USDT, USDT is the quote token.
307    ///
308    /// # Examples
309    /// If the BTC/USDT is trading at 1000 with a 20% fee, this returns `1000 / (1.0 - 0.20) = 1250`
310    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError>;
311
312    /// Returns the amount out given an amount in and input/output tokens.
313    ///
314    /// # Arguments
315    ///
316    /// * `amount_in` - The amount in of the input token.
317    /// * `token_in` - The input token ERC20 token.
318    /// * `token_out` - The output token ERC20 token.
319    ///
320    /// # Returns
321    ///
322    /// A `Result` containing a `GetAmountOutResult` struct on success or a
323    ///  `SimulationError` on failure.
324    fn get_amount_out(
325        &self,
326        amount_in: BigUint,
327        token_in: &Token,
328        token_out: &Token,
329    ) -> Result<GetAmountOutResult, SimulationError>;
330
331    /// Computes the maximum amount that can be traded between two tokens.
332    ///
333    /// This function calculates the maximum possible trade amount between two tokens,
334    /// taking into account the protocol's specific constraints and mechanics.
335    /// The implementation details vary by protocol - for example:
336    /// - For constant product AMMs (like Uniswap V2), this is based on available reserves
337    /// - For concentrated liquidity AMMs (like Uniswap V3), this considers liquidity across tick
338    ///   ranges
339    ///
340    /// Note: if there are no limits, the returned amount will be a "soft" limit,
341    ///       meaning that the actual amount traded could be higher but it's advised to not
342    ///       exceed it.
343    ///
344    /// # Arguments
345    /// * `sell_token` - The address of the token being sold
346    /// * `buy_token` - The address of the token being bought
347    ///
348    /// # Returns
349    /// * `Ok((BigUint, BigUint))` - A tuple containing:
350    ///   - First element: The maximum input amount (sell_token)
351    ///   - Second element: The maximum output amount (buy_token)
352    ///
353    /// For `let res = get_limits(...)`, the valid input domain for `get_amount_out` is `[0,
354    /// res.0]`.
355    ///
356    /// * `Err(SimulationError)` - If any unexpected error occurs
357    fn get_limits(
358        &self,
359        sell_token: Bytes,
360        buy_token: Bytes,
361    ) -> Result<(BigUint, BigUint), SimulationError>;
362
363    /// Decodes and applies a protocol state delta to the state
364    ///
365    /// Will error if the provided delta is missing any required attributes or if any of the
366    /// attribute values cannot be decoded.
367    ///
368    /// # Arguments
369    ///
370    /// * `delta` - A `ProtocolStateDelta` from the tycho indexer
371    ///
372    /// # Returns
373    ///
374    /// * `Result<(), TransitionError<String>>` - A `Result` containing `()` on success or a
375    ///   `TransitionError` on failure.
376    fn delta_transition(
377        &mut self,
378        delta: ProtocolStateDelta,
379        tokens: &HashMap<Bytes, Token>,
380        balances: &Balances,
381    ) -> Result<(), TransitionError>;
382
383    /// Calculates the swap volume required to achieve the provided goal when trading against this
384    /// pool.
385    ///
386    /// This method will branch towards different behaviors based on [SwapConstraint] enum. Please
387    /// refer to its documentation for further details on each behavior.
388    ///
389    /// In short, the current two options are:
390    /// - Maximize your trade while respecting a trade limit price:
391    ///   [SwapConstraint::TradeLimitPrice]
392    /// - Move the pool price to a target price: [SwapConstraint::PoolTargetPrice]
393    ///
394    /// # Arguments
395    ///
396    /// * `params` - A [QueryPoolSwapParams] struct containing the inputs for this method.
397    ///
398    /// # Returns
399    ///
400    /// * `Ok(PoolSwap)` - A `PoolSwap` struct containing the amounts to be traded and the state of
401    ///   the pool after trading.
402    /// * `Err(SimulationError)` - If:
403    ///   - The calculation encounters numerical issues
404    ///   - The method is not implemented for this protocol
405    fn query_pool_swap(&self, _params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
406        Err(SimulationError::FatalError("query_pool_swap not implemented".into()))
407    }
408
409    /// Clones the protocol state as a trait object.
410    /// This allows the state to be cloned when it is being used as a `Box<dyn ProtocolSim>`.
411    fn clone_box(&self) -> Box<dyn ProtocolSim>;
412
413    /// Allows downcasting of the trait object to its underlying type.
414    fn as_any(&self) -> &dyn Any;
415
416    /// Allows downcasting of the trait object to its mutable underlying type.
417    fn as_any_mut(&mut self) -> &mut dyn Any;
418
419    /// Compares two protocol states for equality.
420    /// This method must be implemented to define how two protocol states are considered equal
421    /// (used for tests).
422    fn eq(&self, other: &dyn ProtocolSim) -> bool;
423
424    /// Cast as IndicativelyPriced. This is necessary for RFQ protocols
425    fn as_indicatively_priced(&self) -> Result<&dyn IndicativelyPriced, SimulationError> {
426        Err(SimulationError::FatalError("Pool State does not implement IndicativelyPriced".into()))
427    }
428
429    /// Advances the state to the block a quote is expected to execute in.
430    ///
431    /// Returns `true` when quoting behavior changed and the state must be re-emitted to
432    /// consumers. The stream decoder calls this on every message — including messages in which
433    /// the pool itself did not change, since without that a state's notion of the execution
434    /// block would freeze at the pool's last update. Implementations must be idempotent for a
435    /// repeated block and must not use the value as a substitute for the block they were decoded
436    /// from: it describes the future, not the observed past.
437    fn apply_block(&mut self, _block: &BlockContext) -> bool {
438        false
439    }
440
441    /// Runs every later quote from this state under a pending block's state, held in
442    /// `overrides`.
443    ///
444    /// The payload type belongs to the simulation crate that builds it. The default ignores it,
445    /// for protocols that do not simulate pending state.
446    ///
447    /// # Errors
448    /// Returns an error when the protocol simulates pending state but `overrides` is not the
449    /// type it expects.
450    fn set_pending_overrides(
451        &mut self,
452        _overrides: Arc<dyn Any + Send + Sync>,
453    ) -> Result<(), SimulationError> {
454        Ok(())
455    }
456}
457
458impl Clone for Box<dyn ProtocolSim> {
459    fn clone(&self) -> Box<dyn ProtocolSim> {
460        self.clone_box()
461    }
462}
463
464impl<T> ProtocolSim for T
465where
466    T: SwapQuoter + Clone + Send + Sync + Eq + 'static,
467{
468    fn fee(&self) -> f64 {
469        self.quotable_pairs()
470            .iter()
471            .map(|(t0, t1)| {
472                let amount = BigUint::from(10u32).pow(t0.decimals);
473                if let Ok(params) = QuoteParams::fixed_in(&t0.address, &t1.address, amount) {
474                    self.fee(params)
475                        .map(|f| f.fee())
476                        .unwrap_or(f64::MAX)
477                } else {
478                    f64::MAX
479                }
480            })
481            .reduce(f64::min)
482            .unwrap_or(f64::MAX)
483    }
484
485    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
486        self.marginal_price(MarginalPriceParams::new(&base.address, &quote.address))
487            .map(|r| r.price())
488    }
489
490    fn get_amount_out(
491        &self,
492        amount_in: BigUint,
493        token_in: &Token,
494        token_out: &Token,
495    ) -> Result<GetAmountOutResult, SimulationError> {
496        #[expect(deprecated, reason = "implements the deprecated get_amount_out on top of quote")]
497        self.quote(
498            QuoteParams::fixed_in(&token_in.address, &token_out.address, amount_in)?
499                .with_new_state(),
500        )
501        .map(|r| {
502            GetAmountOutResult::new(
503                r.amount_out().clone(),
504                r.gas().clone(),
505                r.new_state()
506                    .expect("quote includes new state")
507                    .to_protocol_sim(),
508            )
509        })
510    }
511
512    fn get_limits(
513        &self,
514        sell_token: Bytes,
515        buy_token: Bytes,
516    ) -> Result<(BigUint, BigUint), SimulationError> {
517        self.swap_limits(LimitsParams::new(&sell_token, &buy_token))
518            .map(|r| (r.range_in().upper().clone(), r.range_out().upper().clone()))
519    }
520
521    fn delta_transition(
522        &mut self,
523        delta: ProtocolStateDelta,
524        tokens: &HashMap<Bytes, Token>,
525        balances: &Balances,
526    ) -> Result<(), TransitionError> {
527        self.delta_transition(TransitionParams::new(delta, tokens, balances))
528            .map(|_| ())
529    }
530
531    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
532        let constraint = match params.swap_constraint.clone() {
533            SwapConstraint::TradeLimitPrice { limit, tolerance, min_amount_in, max_amount_in } => {
534                swap::SwapConstraint::TradeLimitPrice {
535                    limit,
536                    tolerance,
537                    min_amount_in,
538                    max_amount_in,
539                }
540            }
541            SwapConstraint::PoolTargetPrice { target, tolerance, min_amount_in, max_amount_in } => {
542                swap::SwapConstraint::PoolTargetPrice {
543                    target,
544                    tolerance,
545                    min_amount_in,
546                    max_amount_in,
547                }
548            }
549        };
550        #[expect(
551            deprecated,
552            reason = "implements the deprecated query_pool_swap on top of query_swap"
553        )]
554        self.query_swap(swap::QuerySwapParams::new(
555            &params.token_in.address,
556            &params.token_out.address,
557            constraint,
558        ))
559        .map(|r| {
560            PoolSwap::new(
561                r.amount_in().clone(),
562                r.amount_out().clone(),
563                r.new_state().unwrap().to_protocol_sim(),
564                r.price_points().as_ref().map(|points| {
565                    points
566                        .iter()
567                        .map(|p| {
568                            PricePoint::new(
569                                p.amount_in().clone(),
570                                p.amount_out().clone(),
571                                p.price(),
572                            )
573                        })
574                        .collect()
575                }),
576            )
577        })
578    }
579
580    fn clone_box(&self) -> Box<dyn ProtocolSim> {
581        #[expect(
582            deprecated,
583            reason = "to_protocol_sim is deprecated for consumers but is the clone implementation here"
584        )]
585        self.to_protocol_sim()
586    }
587
588    fn as_any(&self) -> &dyn Any {
589        self
590    }
591
592    fn as_any_mut(&mut self) -> &mut dyn Any {
593        self
594    }
595
596    fn eq(&self, other: &dyn ProtocolSim) -> bool {
597        if let Some(other) = other.as_any().downcast_ref::<T>() {
598            self == other
599        } else {
600            false
601        }
602    }
603
604    fn typetag_name(&self) -> &'static str {
605        self.typetag_name()
606    }
607
608    fn typetag_deserialize(&self) {
609        self.typetag_deserialize()
610    }
611}
612
613#[cfg(test)]
614mod tests {
615
616    use super::*;
617
618    #[test]
619    fn serde() {
620        use serde::{Deserialize, Serialize};
621
622        #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
623        struct DummyProtocol {
624            reserve_0: u64,
625            reserve_1: u64,
626        }
627
628        #[typetag::serde]
629        #[expect(clippy::todo, reason = "test double: the test only serializes it")]
630        impl ProtocolSim for DummyProtocol {
631            fn clone_box(&self) -> Box<dyn ProtocolSim> {
632                todo!()
633            }
634
635            fn as_any(&self) -> &dyn Any {
636                self
637            }
638
639            fn as_any_mut(&mut self) -> &mut dyn Any {
640                todo!()
641            }
642
643            fn eq(&self, other: &dyn ProtocolSim) -> bool {
644                if let Some(other) = other.as_any().downcast_ref::<Self>() {
645                    self.reserve_0 == other.reserve_0 && self.reserve_1 == other.reserve_1
646                } else {
647                    false
648                }
649            }
650
651            fn fee(&self) -> f64 {
652                todo!()
653            }
654            fn spot_price(&self, _base: &Token, _quote: &Token) -> Result<f64, SimulationError> {
655                todo!()
656            }
657            fn get_amount_out(
658                &self,
659                _amount_in: BigUint,
660                _token_in: &Token,
661                _token_out: &Token,
662            ) -> Result<GetAmountOutResult, SimulationError> {
663                todo!()
664            }
665            fn get_limits(
666                &self,
667                _sell_token: Bytes,
668                _buy_token: Bytes,
669            ) -> Result<(BigUint, BigUint), SimulationError> {
670                todo!()
671            }
672            fn delta_transition(
673                &mut self,
674                _delta: ProtocolStateDelta,
675                _tokens: &HashMap<Bytes, Token>,
676                _balances: &Balances,
677            ) -> Result<(), TransitionError> {
678                todo!()
679            }
680        }
681
682        let state = DummyProtocol { reserve_0: 1, reserve_1: 2 };
683
684        assert_eq!(serde_json::to_string(&state).unwrap(), r#"{"reserve_0":1,"reserve_1":2}"#);
685        assert_eq!(
686            serde_json::to_string(&state as &dyn ProtocolSim).unwrap(),
687            r#"{"protocol":"DummyProtocol","state":{"reserve_0":1,"reserve_1":2}}"#
688        );
689
690        let deserialized: Box<dyn ProtocolSim> = serde_json::from_str(
691            r#"{"protocol":"DummyProtocol","state":{"reserve_0":1,"reserve_1":2}}"#,
692        )
693        .unwrap();
694
695        assert!(deserialized.eq(&state));
696    }
697}