Skip to main content

tycho_simulation/price_level_stream/
state.rs

1use std::{
2    any::Any,
3    collections::HashMap,
4    sync::Arc,
5    time::{Duration, Instant},
6};
7
8use num_bigint::BigUint;
9use num_traits::{CheckedSub, ToPrimitive};
10use serde::{Deserialize, Serialize};
11use tycho_common::{
12    dto::ProtocolStateDelta,
13    models::token::Token,
14    simulation::{
15        errors::{SimulationError, TransitionError},
16        protocol_sim::{Balances, GetAmountOutResult, ProtocolSim},
17    },
18    Bytes,
19};
20
21use super::{overrides::PammSimulationOverrides, telemetry};
22use crate::utils::decimals_scale;
23
24/// How long the quotes of one price level message stay quotable: one slot after the message's `ts`.
25/// Titan prices the block it is building, so quotes older than one slot were priced for a block
26/// already built. The guard is loose on purpose: the builder usually refreshes a venue before
27/// inclusion, so a quote for the previous block often still fills, and the fallback router covers
28/// the cases where it does not.
29pub const QUOTE_TTL: Duration = super::SLOT;
30
31/// The error of a query on the other direction once a swap filled this one.
32const ALREADY_QUOTED: &str = "Price level stream already quoted in this route";
33
34/// A single price level: the total `amount_out` a swap of exactly `amount_in` would deliver.
35///
36/// Levels are absolute quotes, not marginal order book sizes: each one already includes all
37/// smaller levels' liquidity.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct PriceLevelStreamQuote {
40    pub amount_in: BigUint,
41    pub amount_out: BigUint,
42}
43
44impl PriceLevelStreamQuote {
45    pub fn new(amount_in: BigUint, amount_out: BigUint) -> Self {
46        Self { amount_in, amount_out }
47    }
48}
49
50/// The merged swap an earlier swap on one direction has made so far, in atomic units.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52struct StreamFill {
53    token_in: Bytes,
54    token_out: Bytes,
55    /// The input of the merged swap so far.
56    amount_in: BigUint,
57    /// The output the merged swap has paid so far.
58    amount_out: BigUint,
59}
60
61/// State of a single pAMM pair fed from the price level stream.
62///
63/// Holds the latest complete quotes for both trade directions. Quotes are absolute
64/// (`amount_in` → total `amount_out`), sorted ascending by `amount_in`; amounts between two
65/// quotes are interpolated linearly, mirroring how Titan itself densifies the simulated levels.
66/// Amounts outside the quoted range are not served.
67///
68/// A swap returns a state that records its fill. A later swap on the same direction continues
69/// that fill: it pays the quotes' output for the merged input less the output so far, at zero
70/// gas, and `get_limits` and `spot_price` answer for what is left. The other direction is refused
71/// with an "already quoted" error, as the quotes are cumulative from the pre-fill venue and say
72/// nothing about its price after a fill. So the caller merges all swaps on one direction into
73/// one swap.
74#[derive(Debug, Clone, Serialize, Deserialize)]
75#[expect(
76    clippy::partial_pub_fields,
77    reason = "public API; making every field public or private is a breaking change"
78)]
79pub struct PriceLevelStreamState {
80    pub token0: Bytes,
81    pub token1: Bytes,
82    pub quotes_0_to_1: Vec<PriceLevelStreamQuote>,
83    pub quotes_1_to_0: Vec<PriceLevelStreamQuote>,
84    pub gas_cost: BigUint,
85    /// What an earlier swap filled on this state. Older serialized states carry none.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    fill: Option<StreamFill>,
88    /// Monotonic instant from which this state refuses every query. `None` means the state never
89    /// expires. The field is never serialized and deserializes as `None`, so a replayed
90    /// recording always quotes. Only [`with_quotable_until`](Self::with_quotable_until) sets it,
91    /// and equality ignores it: two states carrying the same quotes compare equal whichever
92    /// messages they came from.
93    #[serde(skip)]
94    quotable_until: Option<Instant>,
95    /// The account state Titan priced these quotes on, when the tracker matched a quote stream
96    /// entry to them. An `Arc`, because every state a quote returns keeps it. Unlike
97    /// `quotable_until` it is serialized, so a recording replays it;
98    /// [`with_simulation_overrides`](Self::with_simulation_overrides) is the only setter.
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    overrides: Option<Arc<PammSimulationOverrides>>,
101}
102
103impl PriceLevelStreamState {
104    /// Creates the state for the pair `(token0, token1)`.
105    ///
106    /// Both quote lists are sorted ascending by `amount_in` and deduplicated on it, so callers
107    /// may pass them in stream order.
108    pub fn new(
109        token0: Bytes,
110        token1: Bytes,
111        mut quotes_0_to_1: Vec<PriceLevelStreamQuote>,
112        mut quotes_1_to_0: Vec<PriceLevelStreamQuote>,
113        gas_cost: BigUint,
114    ) -> Self {
115        for quotes in [&mut quotes_0_to_1, &mut quotes_1_to_0] {
116            quotes.sort_by(|a, b| a.amount_in.cmp(&b.amount_in));
117            quotes.dedup_by(|a, b| a.amount_in == b.amount_in);
118        }
119        Self {
120            token0,
121            token1,
122            quotes_0_to_1,
123            quotes_1_to_0,
124            gas_cost,
125            fill: None,
126            quotable_until: None,
127            overrides: None,
128        }
129    }
130
131    /// Sets the monotonic instant from which this state refuses every query.
132    pub fn with_quotable_until(mut self, until: Instant) -> Self {
133        self.quotable_until = Some(until);
134        self
135    }
136
137    /// Attaches the account state Titan priced these quotes on.
138    pub fn with_simulation_overrides(
139        mut self,
140        overrides: impl Into<Arc<PammSimulationOverrides>>,
141    ) -> Self {
142        self.overrides = Some(overrides.into());
143        self
144    }
145
146    /// The account state Titan priced these quotes on, to convert and pass to `eth_call` as state
147    /// overrides, or `None` when the stream matched no quote stream entry to this state's book, or
148    /// runs without simulation overrides. Quoting never reads it.
149    pub fn simulation_overrides(&self) -> Option<&PammSimulationOverrides> {
150        self.overrides.as_deref()
151    }
152
153    /// The monotonic instant from which this state refuses every query, or `None` if it never
154    /// expires.
155    pub fn quotable_until(&self) -> Option<Instant> {
156        self.quotable_until
157    }
158
159    /// Returns a `RecoverableError` once `now` reaches `quotable_until`. A state without
160    /// `quotable_until` never errors.
161    fn ensure_quotable(&self, now: Instant) -> Result<(), SimulationError> {
162        match self.quotable_until {
163            Some(until) if now >= until => {
164                telemetry::record_quote_refused(telemetry::QuoteRefusedReason::PriceLevelsExpired);
165                Err(SimulationError::RecoverableError(format!(
166                    "price levels expired: the message that carried them is older than {} s (one \
167                     slot)",
168                    QUOTE_TTL.as_secs()
169                )))
170            }
171            Some(_) | None => Ok(()),
172        }
173    }
174
175    /// Returns the quotes selling `token_in` for `token_out`, or an error if the pair does
176    /// not match this state's tokens.
177    fn quotes(
178        &self,
179        token_in: &Bytes,
180        token_out: &Bytes,
181    ) -> Result<&[PriceLevelStreamQuote], SimulationError> {
182        if token_in == &self.token0 && token_out == &self.token1 {
183            Ok(&self.quotes_0_to_1)
184        } else if token_in == &self.token1 && token_out == &self.token0 {
185            Ok(&self.quotes_1_to_0)
186        } else {
187            telemetry::record_quote_refused(telemetry::QuoteRefusedReason::UnknownPair);
188            Err(SimulationError::RecoverableError(format!(
189                "Invalid token addresses for pair {}/{}: {token_in}, {token_out}",
190                self.token0, self.token1
191            )))
192        }
193    }
194
195    /// Computes the output amount for `amount_in` on the given quotes by linear interpolation
196    /// between the two enclosing quotes.
197    ///
198    /// Callers must ensure `amount_in` lies within the quoted range (smallest to largest
199    /// `amount_in`) — the quotes hold no information outside of it. Errors if the enclosing
200    /// quotes are not monotonically increasing in `amount_out`: such quotes are unreliable,
201    /// and a venue with corrupt data should not be quoted at any price.
202    fn interpolate(
203        &self,
204        quotes: &[PriceLevelStreamQuote],
205        amount_in: &BigUint,
206    ) -> Result<BigUint, SimulationError> {
207        // First quote with amount_in >= the requested amount; the caller-guaranteed range makes
208        // both it and (when needed) its predecessor exist.
209        let idx = quotes.partition_point(|quote| &quote.amount_in < amount_in);
210        let upper = &quotes[idx];
211        if &upper.amount_in == amount_in {
212            return Ok(upper.amount_out.clone());
213        }
214        let lower = &quotes[idx - 1];
215        let Some(out_span) = upper
216            .amount_out
217            .checked_sub(&lower.amount_out)
218        else {
219            // Recoverable: the next message replaces the quotes wholesale.
220            telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NotMonotonic);
221            return Err(SimulationError::RecoverableError(format!(
222                "Quotes {}/{} are not monotonically increasing in amount_out around the \
223                 requested amount {amount_in}: {} -> {}, but {} -> {}",
224                self.token0,
225                self.token1,
226                lower.amount_in,
227                lower.amount_out,
228                upper.amount_in,
229                upper.amount_out,
230            )));
231        };
232        let in_span = &upper.amount_in - &lower.amount_in;
233        let offset = amount_in - &lower.amount_in;
234        Ok(&lower.amount_out + out_span * offset / in_span)
235    }
236
237    /// The fill an earlier swap made on `token_in` into `token_out`, if any. Errors when the
238    /// state was filled on the other direction.
239    fn fill_on(
240        &self,
241        token_in: &Bytes,
242        token_out: &Bytes,
243    ) -> Result<Option<&StreamFill>, SimulationError> {
244        match &self.fill {
245            Some(fill) if &fill.token_in == token_in && &fill.token_out == token_out => {
246                Ok(Some(fill))
247            }
248            Some(_) => Err(SimulationError::RecoverableError(ALREADY_QUOTED.to_string())),
249            None => Ok(None),
250        }
251    }
252
253    /// This state with `fill` recorded. It keeps the quotes, `quotable_until` and the simulation
254    /// overrides: the overrides are the state the fill was priced on, and a consumer simulates
255    /// the swap after quoting it.
256    fn with_fill(&self, fill: StreamFill) -> Box<dyn ProtocolSim> {
257        Box::new(Self { fill: Some(fill), ..self.clone() })
258    }
259
260    /// The marginal price of the next input unit after `filled` went into `quotes`, in whole
261    /// tokens of `quote` per whole token of `base`. Below the smallest quote it is the price of
262    /// the first segment. Errors when `filled` reaches the largest quote, or when the segment it
263    /// falls in pays nothing or is not monotonically increasing in `amount_out`.
264    fn marginal_price(
265        &self,
266        quotes: &[PriceLevelStreamQuote],
267        filled: &BigUint,
268        base: &Token,
269        quote: &Token,
270    ) -> Result<f64, SimulationError> {
271        let no_liquidity = || {
272            telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NoLiquidity);
273            SimulationError::RecoverableError("No liquidity available".to_string())
274        };
275        let idx = quotes.partition_point(|level| &level.amount_in <= filled);
276        let upper = quotes
277            .get(idx)
278            .ok_or_else(no_liquidity)?;
279        let (lower_in, lower_out) = match idx
280            .checked_sub(1)
281            .and_then(|lower| quotes.get(lower))
282        {
283            Some(lower) => (&lower.amount_in, &lower.amount_out),
284            None => (&BigUint::ZERO, &BigUint::ZERO),
285        };
286        let Some(out_span) = upper.amount_out.checked_sub(lower_out) else {
287            telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NotMonotonic);
288            return Err(SimulationError::RecoverableError(format!(
289                "Quotes {}/{} are not monotonically increasing in amount_out around the filled \
290                 amount {filled}",
291                self.token0, self.token1
292            )));
293        };
294        if out_span == BigUint::ZERO {
295            return Err(no_liquidity());
296        }
297        whole_unit_price(&(&upper.amount_in - lower_in), &out_span, base, quote)
298    }
299
300    /// The output of a swap of `amount_in` on `quotes`, priced by the quotes alone: below the
301    /// smallest quote nothing is served, above the largest the result is partial.
302    fn priced_amount_out(
303        &self,
304        quotes: &[PriceLevelStreamQuote],
305        amount_in: &BigUint,
306    ) -> Result<PricedAmount, SimulationError> {
307        let (Some(first), Some(last)) = (quotes.first(), quotes.last()) else {
308            telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NoLiquidity);
309            return Err(SimulationError::RecoverableError("No liquidity available".to_string()));
310        };
311        // Below the smallest quote nothing is served. The venue itself could still fill —
312        // FermiSwap was observed quoting below the smallest streamed level — but if so, on its
313        // own price curve, which the quotes hold no information about: unlike interpolation
314        // between two quoted levels, whose result is bracketed by genuine samples on both
315        // sides, extrapolating linearly from (0, 0) like Titan's quote API does is an unbounded
316        // guess even off healthy quotes. (0, 0) is an assumption, not a sample, and the
317        // bottom of that line is not even fillable: FermiSwap reverts below a venue-side
318        // minimum (~$0.02 at the time of measurement) where the API keeps quoting. And
319        // malformed quotes turn the guess absurd: on FermiSwap's flat cbBTC-input books
320        // (18-decimals grid bug) the smallest quote is the venue's depth clamp, not a price
321        // sample, and the extrapolated quotes land ~3e6x below the venue's own (measured
322        // 2026-07). All the rejection gives up are trades smaller than the first level —
323        // ~$10-30 on healthy quotes, negligible for routing. Hence no partial result either.
324        if amount_in < &first.amount_in {
325            telemetry::record_quote_refused(telemetry::QuoteRefusedReason::BelowSmallestQuote);
326            return Err(SimulationError::InvalidInput(
327                format!(
328                    "Input amount is below the smallest quote. input amount: {amount_in}, minimum quoted amount: {}",
329                    first.amount_in
330                ),
331                None,
332            ));
333        }
334        // The requested amount exceeds the largest quote; report the output at the limit as a
335        // partial result, like other level-based protocols do.
336        if amount_in > &last.amount_in {
337            return Ok(PricedAmount::Partial {
338                amount: last.amount_out.clone(),
339                message: format!(
340                    "Not enough liquidity to support complete swap. input amount: {amount_in}, maximum quoted amount: {}",
341                    last.amount_in
342                ),
343            });
344        }
345        Ok(PricedAmount::Complete(self.interpolate(quotes, amount_in)?))
346    }
347}
348
349/// What the quotes alone pay for a swap.
350enum PricedAmount {
351    /// The quotes serve the whole input.
352    Complete(BigUint),
353    /// The input exceeds the largest quote: `amount` is the output at that quote, and `message`
354    /// says why the swap is partial.
355    Partial { amount: BigUint, message: String },
356}
357
358/// `amount_out` per `amount_in`, in whole tokens of `quote` per whole token of `base`.
359fn whole_unit_price(
360    amount_in: &BigUint,
361    amount_out: &BigUint,
362    base: &Token,
363    quote: &Token,
364) -> Result<f64, SimulationError> {
365    let amount_in = amount_in.to_f64().ok_or_else(|| {
366        SimulationError::RecoverableError("Can't convert amount in to f64".to_string())
367    })?;
368    let amount_out = amount_out.to_f64().ok_or_else(|| {
369        SimulationError::RecoverableError("Can't convert amount out to f64".to_string())
370    })?;
371    Ok((amount_out / decimals_scale(quote.decimals)) / (amount_in / decimals_scale(base.decimals)))
372}
373
374/// `amount` less `taken`, or zero when `taken` is larger.
375fn saturating_sub(amount: &BigUint, taken: &BigUint) -> BigUint {
376    amount
377        .checked_sub(taken)
378        .unwrap_or_default()
379}
380
381#[typetag::serde]
382impl ProtocolSim for PriceLevelStreamState {
383    fn fee(&self) -> f64 {
384        0.0
385    }
386
387    /// Before a fill, the price of the smallest quote. After a fill, the marginal price at the
388    /// filled amount, and a refusal for the other direction.
389    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
390        self.ensure_quotable(Instant::now())?;
391        let quotes = self.quotes(&base.address, &quote.address)?;
392        if let Some(fill) = self.fill_on(&base.address, &quote.address)? {
393            return self.marginal_price(quotes, &fill.amount_in, base, quote);
394        }
395        let best = quotes
396            .iter()
397            .find(|q| q.amount_in > BigUint::ZERO && q.amount_out > BigUint::ZERO)
398            .ok_or_else(|| {
399                telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NoLiquidity);
400                SimulationError::RecoverableError("No liquidity available".to_string())
401            })?;
402        whole_unit_price(&best.amount_in, &best.amount_out, base, quote)
403    }
404
405    /// Records the fill in the returned state. After a swap on the same direction it pays the
406    /// output of the merged input less the output so far, at zero gas. A swap on the other
407    /// direction fails: the venue already quoted. See [`PriceLevelStreamState`].
408    fn get_amount_out(
409        &self,
410        amount_in: BigUint,
411        token_in: &Token,
412        token_out: &Token,
413    ) -> Result<GetAmountOutResult, SimulationError> {
414        self.ensure_quotable(Instant::now())?;
415        let quotes = self.quotes(&token_in.address, &token_out.address)?;
416        let previous = self.fill_on(&token_in.address, &token_out.address)?;
417        let merged_in = match previous {
418            Some(previous) => &previous.amount_in + &amount_in,
419            None => amount_in,
420        };
421        let (merged_out, partial_message) = match self.priced_amount_out(quotes, &merged_in)? {
422            PricedAmount::Complete(amount) => (amount, None),
423            PricedAmount::Partial { amount, message } => (amount, Some(message)),
424        };
425        let (amount, gas) = match previous {
426            Some(previous) => (saturating_sub(&merged_out, &previous.amount_out), BigUint::ZERO),
427            None => (merged_out.clone(), self.gas_cost.clone()),
428        };
429        let new_state = self.with_fill(StreamFill {
430            token_in: token_in.address.clone(),
431            token_out: token_out.address.clone(),
432            amount_in: merged_in,
433            amount_out: merged_out,
434        });
435        let result = GetAmountOutResult { amount, gas, new_state };
436        match partial_message {
437            Some(message) => Err(SimulationError::InvalidInput(message, Some(result))),
438            None => Ok(result),
439        }
440    }
441
442    /// The largest quote, less the fill after a swap on the same direction. A swap on the other
443    /// direction fails: the venue already quoted.
444    fn get_limits(
445        &self,
446        sell_token: Bytes,
447        buy_token: Bytes,
448    ) -> Result<(BigUint, BigUint), SimulationError> {
449        self.ensure_quotable(Instant::now())?;
450        let quotes = self.quotes(&sell_token, &buy_token)?;
451        let fill = self.fill_on(&sell_token, &buy_token)?;
452        let (max_in, max_out) = match quotes.last() {
453            Some(largest) => (largest.amount_in.clone(), largest.amount_out.clone()),
454            None => (BigUint::ZERO, BigUint::ZERO),
455        };
456        Ok(match fill {
457            Some(fill) => (
458                saturating_sub(&max_in, &fill.amount_in),
459                saturating_sub(&max_out, &fill.amount_out),
460            ),
461            None => (max_in, max_out),
462        })
463    }
464
465    fn delta_transition(
466        &mut self,
467        _delta: ProtocolStateDelta,
468        _tokens: &HashMap<Bytes, Token>,
469        _balances: &Balances,
470    ) -> Result<(), TransitionError> {
471        Err(TransitionError::DecodeError("Not implemented".into()))
472    }
473
474    fn clone_box(&self) -> Box<dyn ProtocolSim> {
475        Box::new(self.clone())
476    }
477
478    fn as_any(&self) -> &dyn Any {
479        self
480    }
481
482    fn as_any_mut(&mut self) -> &mut dyn Any {
483        self
484    }
485
486    /// Equal when the pair, both quote lists, the gas cost and the fill match, and either neither
487    /// state carries simulation overrides, or both carry overrides of the same block over the
488    /// same account addresses. A state that gains or loses its overrides is a changed state.
489    ///
490    /// The overridden values are left out. Quoting never reads them, and Titan republishes a
491    /// venue's accounts several times a second while its prices stand still, so comparing them
492    /// would report a changed quote for an unchanged price.
493    ///
494    /// The block is compared because prices can be identical across a block boundary: without it,
495    /// a consumer that keeps the state it holds would simulate on the previous block's overrides.
496    /// The account addresses are compared because a merge can add or lose another quote address's
497    /// entry (see Metric); without them, a consumer would keep overrides missing an account the
498    /// swap reads.
499    ///
500    /// `quotable_until` is left out too: this process derives it and never serializes it. A
501    /// consumer that keeps the state it holds whenever `eq` says equal therefore keeps the earlier
502    /// deadline, and that state stops quoting one slot after its own message, even while newer
503    /// messages repeat the same quotes. Replace the held state on every update to always quote on
504    /// the newest deadline.
505    fn eq(&self, other: &dyn ProtocolSim) -> bool {
506        other
507            .as_any()
508            .downcast_ref::<PriceLevelStreamState>()
509            .is_some_and(|other| {
510                let Self {
511                    token0,
512                    token1,
513                    quotes_0_to_1,
514                    quotes_1_to_0,
515                    gas_cost,
516                    fill,
517                    quotable_until: _,
518                    overrides,
519                } = other;
520                let same_overrides = match (&self.overrides, overrides) {
521                    (Some(held), Some(arriving)) => {
522                        held.block_number == arriving.block_number &&
523                            held.accounts
524                                .keys()
525                                .eq(arriving.accounts.keys())
526                    }
527                    (None, None) => true,
528                    _ => false,
529                };
530                &self.token0 == token0 &&
531                    &self.token1 == token1 &&
532                    &self.quotes_0_to_1 == quotes_0_to_1 &&
533                    &self.quotes_1_to_0 == quotes_1_to_0 &&
534                    &self.gas_cost == gas_cost &&
535                    &self.fill == fill &&
536                    same_overrides
537            })
538    }
539}
540
541#[cfg(test)]
542mod tests {
543    use std::time::{Duration, Instant};
544
545    use rstest::rstest;
546
547    use super::{
548        super::{
549            convert::quotes_for_book,
550            telemetry::recorded::{counter_value, record_async},
551            test_support::{captured_book, test_overrides, token, tokens, USDC, WBTC, WETH},
552        },
553        *,
554    };
555
556    /// The tag typetag writes for this state, as it appears in a recording.
557    const TAG: &str = r#""PriceLevelStreamState""#;
558
559    /// A recording written before the state carried overrides, verbatim: it has no `overrides`
560    /// key at all, and its `BigUint` amounts are sequences of base-2^32 digits.
561    const LEGACY_STATE: &str = r#"{
562      "token0": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",
563      "token1": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
564      "quotes_0_to_1": [{"amount_in": [100000000], "amount_out": [1215752192, 23]}],
565      "quotes_1_to_0": [{"amount_in": [1215752192, 23], "amount_out": [99000000]}],
566      "gas_cost": [120000]
567    }"#;
568
569    /// A recording of an adjacently tagged state with the tag before the content, as typetag
570    /// itself writes it.
571    fn tag_first(tag: &str, state: &str) -> String {
572        format!(r#"{{"protocol":{tag},"state":{state}}}"#)
573    }
574
575    /// The same two fields the other way round: the order that makes typetag buffer the whole
576    /// state before it knows what to read it as.
577    fn content_first(tag: &str, state: &str) -> String {
578        format!(r#"{{"state":{state},"protocol":{tag}}}"#)
579    }
580
581    fn wbtc() -> Token {
582        token(WBTC, "WBTC", 8)
583    }
584
585    fn usdc() -> Token {
586        token(USDC, "USDC", 6)
587    }
588
589    fn weth() -> Token {
590        token(WETH, "WETH", 18)
591    }
592
593    fn quote(amount_in: u64, amount_out: u64) -> PriceLevelStreamQuote {
594        PriceLevelStreamQuote::new(BigUint::from(amount_in), BigUint::from(amount_out))
595    }
596
597    /// WBTC (token0) / USDC (token1) quotes: 1 WBTC -> 100k USDC flat, then the second level
598    /// fills at a worse marginal price.
599    fn state() -> PriceLevelStreamState {
600        PriceLevelStreamState::new(
601            wbtc().address,
602            usdc().address,
603            vec![quote(100_000_000, 100_000_000_000), quote(200_000_000, 190_000_000_000)],
604            vec![quote(100_000_000_000, 99_000_000), quote(200_000_000_000, 190_000_000)],
605            BigUint::from(120_000u64),
606        )
607    }
608
609    /// The Bebop WETH/USDC quotes of the captured live message, converted as the stream converts
610    /// them: the amounts Titan quoted.
611    fn captured_state() -> PriceLevelStreamState {
612        let tokens = tokens();
613        let book = captured_book("Bebop", "WETH", "USDC");
614        let weth = tokens
615            .get(&weth().address)
616            .expect("WETH is admitted");
617        let usdc = tokens
618            .get(&usdc().address)
619            .expect("USDC is admitted");
620        let (bids, asks) = quotes_for_book(&book, weth, usdc);
621        PriceLevelStreamState::new(
622            weth.address.clone(),
623            usdc.address.clone(),
624            bids.expect("the captured bids convert"),
625            asks.expect("the captured asks convert"),
626            BigUint::from(120_000u64),
627        )
628    }
629
630    #[test]
631    fn captured_state_carries_the_whole_captured_book() {
632        let state = captured_state();
633        assert_eq!(state.quotes_0_to_1.len(), 15);
634        assert_eq!(state.quotes_1_to_0.len(), 14);
635    }
636
637    #[test]
638    fn new_sorts_and_dedups_quotes() {
639        let state = PriceLevelStreamState::new(
640            wbtc().address,
641            usdc().address,
642            vec![quote(200, 380), quote(100, 200), quote(200, 999)],
643            vec![],
644            BigUint::ZERO,
645        );
646        assert_eq!(state.quotes_0_to_1, vec![quote(100, 200), quote(200, 380)]);
647    }
648
649    #[test]
650    fn get_amount_out_exact_level() {
651        let result = state()
652            .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
653            .unwrap();
654        assert_eq!(result.amount, BigUint::from(100_000_000_000u64));
655        assert_eq!(result.gas, BigUint::from(120_000u64));
656    }
657
658    #[test]
659    fn get_amount_out_interpolates_between_levels() {
660        // Halfway between the two levels: 100k + (190k - 100k) / 2 = 145k USDC.
661        let result = state()
662            .get_amount_out(BigUint::from(150_000_000u64), &wbtc(), &usdc())
663            .unwrap();
664        assert_eq!(result.amount, BigUint::from(145_000_000_000u64));
665    }
666
667    /// A WBTC/USDC state whose WBTC quotes are not monotonically increasing in amount_out, as
668    /// after a stream glitch.
669    fn glitched_state() -> PriceLevelStreamState {
670        PriceLevelStreamState::new(
671            wbtc().address,
672            usdc().address,
673            vec![quote(100, 200), quote(200, 150)],
674            vec![],
675            BigUint::ZERO,
676        )
677    }
678
679    /// A WBTC/USDC state with no quotes in either direction.
680    fn empty_state() -> PriceLevelStreamState {
681        PriceLevelStreamState::new(wbtc().address, usdc().address, vec![], vec![], BigUint::ZERO)
682    }
683
684    #[test]
685    fn get_amount_out_on_glitched_quotes_is_rejected() {
686        // The data is unreliable, so a quote landing in the glitched segment is refused instead
687        // of interpolated (or underflowing).
688        let state = glitched_state();
689        let result = state.get_amount_out(BigUint::from(150u64), &wbtc(), &usdc());
690        assert!(matches!(result, Err(SimulationError::RecoverableError(_))));
691
692        // Hitting a level exactly returns that genuine sample even on glitched quotes.
693        let result = state
694            .get_amount_out(BigUint::from(100u64), &wbtc(), &usdc())
695            .unwrap();
696        assert_eq!(result.amount, BigUint::from(200u64));
697    }
698
699    #[test]
700    fn get_amount_out_below_smallest_level_is_rejected() {
701        // The quotes hold no information below the smallest one, and there is no partial
702        // result to offer.
703        let result = state().get_amount_out(BigUint::from(50_000_000u64), &wbtc(), &usdc());
704        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
705    }
706
707    #[test]
708    fn get_amount_out_reverse_direction() {
709        let result = state()
710            .get_amount_out(BigUint::from(100_000_000_000u64), &usdc(), &wbtc())
711            .unwrap();
712        assert_eq!(result.amount, BigUint::from(99_000_000u64));
713    }
714
715    #[test]
716    fn get_amount_out_beyond_largest_level_is_partial() {
717        let result = state().get_amount_out(BigUint::from(300_000_000u64), &wbtc(), &usdc());
718        match result {
719            Err(SimulationError::InvalidInput(_, Some(partial))) => {
720                assert_eq!(partial.amount, BigUint::from(190_000_000_000u64));
721            }
722            other => panic!("expected partial InvalidInput, got {other:?}"),
723        }
724    }
725
726    fn successor(result: &GetAmountOutResult) -> &PriceLevelStreamState {
727        result
728            .new_state
729            .as_any()
730            .downcast_ref::<PriceLevelStreamState>()
731            .expect("price level state")
732    }
733
734    /// The state after a swap of 1 WBTC for USDC.
735    fn state_after_one_wbtc() -> PriceLevelStreamState {
736        let result = state()
737            .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
738            .unwrap();
739        successor(&result).clone()
740    }
741
742    fn wbtc_to_usdc_fill(amount_in: u64, amount_out: u64) -> StreamFill {
743        StreamFill {
744            token_in: wbtc().address,
745            token_out: usdc().address,
746            amount_in: BigUint::from(amount_in),
747            amount_out: BigUint::from(amount_out),
748        }
749    }
750
751    #[test]
752    fn get_amount_out_records_the_fill_and_keeps_the_quotes() {
753        let after = state_after_one_wbtc();
754        assert_eq!(after.fill, Some(wbtc_to_usdc_fill(100_000_000, 100_000_000_000)));
755        assert_eq!(after.quotes_0_to_1, state().quotes_0_to_1);
756        assert_eq!(after.quotes_1_to_0, state().quotes_1_to_0);
757    }
758
759    #[test]
760    fn two_chunks_pay_what_one_merged_swap_pays() {
761        let merged = state()
762            .get_amount_out(BigUint::from(150_000_000u64), &wbtc(), &usdc())
763            .unwrap();
764        let first = state()
765            .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
766            .unwrap();
767        let second = successor(&first)
768            .get_amount_out(BigUint::from(50_000_000u64), &wbtc(), &usdc())
769            .unwrap();
770        assert_eq!(first.amount + &second.amount, merged.amount);
771        assert_eq!(second.gas, BigUint::ZERO);
772        assert_eq!(successor(&second).fill, successor(&merged).fill);
773    }
774
775    #[test]
776    fn continued_chunk_beyond_largest_level_is_partial_and_carries_the_fill() {
777        let result =
778            state_after_one_wbtc().get_amount_out(BigUint::from(200_000_000u64), &wbtc(), &usdc());
779        let Err(SimulationError::InvalidInput(_, Some(partial))) = result else {
780            panic!("expected partial InvalidInput, got {result:?}");
781        };
782        // The largest quote pays 190k USDC, 100k of which the first chunk took.
783        assert_eq!(partial.amount, BigUint::from(90_000_000_000u64));
784        assert_eq!(partial.gas, BigUint::ZERO);
785        assert_eq!(successor(&partial).fill, Some(wbtc_to_usdc_fill(300_000_000, 190_000_000_000)));
786    }
787
788    /// After a fill on WBTC into USDC, every query on USDC into WBTC is refused.
789    #[test]
790    fn the_other_direction_after_a_fill_is_refused() {
791        let after = state_after_one_wbtc();
792        let refused = [
793            after
794                .get_amount_out(BigUint::from(100_000_000_000u64), &usdc(), &wbtc())
795                .map(|_| ()),
796            after
797                .get_limits(usdc().address, wbtc().address)
798                .map(|_| ()),
799            after
800                .spot_price(&usdc(), &wbtc())
801                .map(|_| ()),
802        ];
803        for result in refused {
804            assert!(matches!(
805                result,
806                Err(SimulationError::RecoverableError(message))
807                    if message == "Price level stream already quoted in this route"
808            ));
809        }
810    }
811
812    #[test]
813    fn get_amount_out_rejects_unknown_tokens() {
814        let result = state().get_amount_out(BigUint::from(1u64), &weth(), &usdc());
815        assert!(matches!(result, Err(SimulationError::RecoverableError(_))));
816    }
817
818    #[test]
819    fn get_amount_out_without_liquidity() {
820        let result = empty_state().get_amount_out(BigUint::from(1u64), &wbtc(), &usdc());
821        assert!(matches!(result, Err(SimulationError::RecoverableError(_))));
822    }
823
824    #[test]
825    fn spot_price_uses_smallest_quote() {
826        // 1 WBTC (1e8) -> 100_000 USDC (1e11 at 6 decimals).
827        let price = state()
828            .spot_price(&wbtc(), &usdc())
829            .unwrap();
830        assert!((price - 100_000.0).abs() < 1e-9);
831
832        let inverse = state()
833            .spot_price(&usdc(), &wbtc())
834            .unwrap();
835        // 100k USDC (1e11 at 6 decimals) -> 0.99 WBTC: 0.99 / 100_000 = 9.9e-6.
836        assert!((inverse - 9.9e-6).abs() < 1e-15);
837    }
838
839    #[test]
840    fn spot_price_skips_zero_amount_out_quotes() {
841        // A dust level rounding to zero output must not produce a spot price of 0 — consumers
842        // computing 1/spot_price would divide by zero.
843        let state = PriceLevelStreamState::new(
844            wbtc().address,
845            usdc().address,
846            vec![quote(1, 0), quote(100_000_000, 100_000_000_000)],
847            vec![],
848            BigUint::ZERO,
849        );
850        let price = state
851            .spot_price(&wbtc(), &usdc())
852            .unwrap();
853        assert!((price - 100_000.0).abs() < 1e-9);
854    }
855
856    #[test]
857    fn get_limits_returns_largest_quote() {
858        let (max_in, max_out) = state()
859            .get_limits(wbtc().address, usdc().address)
860            .unwrap();
861        assert_eq!(max_in, BigUint::from(200_000_000u64));
862        assert_eq!(max_out, BigUint::from(190_000_000_000u64));
863    }
864
865    #[test]
866    fn get_limits_after_a_fill_are_the_quote_limits_less_the_fill() {
867        let (max_in, max_out) = state_after_one_wbtc()
868            .get_limits(wbtc().address, usdc().address)
869            .unwrap();
870        assert_eq!(max_in, BigUint::from(100_000_000u64));
871        assert_eq!(max_out, BigUint::from(90_000_000_000u64));
872    }
873
874    #[test]
875    fn get_limits_after_a_fill_beyond_the_quotes_are_zero() {
876        let state = PriceLevelStreamState {
877            fill: Some(wbtc_to_usdc_fill(300_000_000, 190_000_000_000)),
878            ..state()
879        };
880        let limits = state
881            .get_limits(wbtc().address, usdc().address)
882            .unwrap();
883        assert_eq!(limits, (BigUint::ZERO, BigUint::ZERO));
884    }
885
886    #[test]
887    fn spot_price_after_a_fill_is_the_marginal_price_at_the_filled_amount() {
888        // Past 1 WBTC the quotes pay 90k USDC per WBTC, down from 100k.
889        let price = state_after_one_wbtc()
890            .spot_price(&wbtc(), &usdc())
891            .unwrap();
892        assert!((price - 90_000.0).abs() < 1e-9);
893    }
894
895    #[test]
896    fn spot_price_after_a_fill_to_the_largest_level_has_no_liquidity() {
897        let state = PriceLevelStreamState {
898            fill: Some(wbtc_to_usdc_fill(200_000_000, 190_000_000_000)),
899            ..state()
900        };
901        let result = state.spot_price(&wbtc(), &usdc());
902        assert!(matches!(
903            result,
904            Err(SimulationError::RecoverableError(message)) if message == "No liquidity available"
905        ));
906    }
907
908    #[test]
909    fn get_limits_without_liquidity() {
910        let state = PriceLevelStreamState::new(
911            wbtc().address,
912            usdc().address,
913            vec![],
914            vec![],
915            BigUint::ZERO,
916        );
917        let (max_in, max_out) = state
918            .get_limits(wbtc().address, usdc().address)
919            .unwrap();
920        assert_eq!(max_in, BigUint::ZERO);
921        assert_eq!(max_out, BigUint::ZERO);
922    }
923
924    #[test]
925    fn eq_compares_quotes() {
926        let a = state();
927        let mut b = state();
928        assert!(a.eq(&b as &dyn ProtocolSim));
929        b.quotes_0_to_1[0].amount_out += 1u32;
930        assert!(!a.eq(&b as &dyn ProtocolSim));
931    }
932
933    #[test]
934    fn eq_compares_fills() {
935        assert!(!state().eq(&state_after_one_wbtc() as &dyn ProtocolSim));
936        assert!(state_after_one_wbtc().eq(&state_after_one_wbtc() as &dyn ProtocolSim));
937    }
938
939    #[test]
940    fn a_state_serialized_without_a_fill_loads_with_none() {
941        let json = serde_json::to_value(state()).unwrap();
942        assert!(json
943            .as_object()
944            .unwrap()
945            .get("fill")
946            .is_none());
947        let loaded: PriceLevelStreamState = serde_json::from_value(json).unwrap();
948        assert_eq!(loaded.fill, None);
949    }
950
951    #[test]
952    fn a_fill_survives_a_serde_round_trip() {
953        let json = serde_json::to_value(state_after_one_wbtc()).unwrap();
954        let loaded: PriceLevelStreamState = serde_json::from_value(json).unwrap();
955        assert_eq!(loaded.fill, state_after_one_wbtc().fill);
956    }
957
958    #[rstest]
959    #[case::one_nanosecond_before(|until| until - Duration::from_nanos(1), true)]
960    #[case::at_quotable_until(|until| until, false)]
961    #[case::one_second_after(|until| until + Duration::from_secs(1), false)]
962    fn ensure_quotable_around_quotable_until(
963        #[case] now: fn(Instant) -> Instant,
964        #[case] quotable: bool,
965    ) {
966        let until = Instant::now() + Duration::from_secs(60);
967        let state = state().with_quotable_until(until);
968        assert_eq!(
969            state
970                .ensure_quotable(now(until))
971                .is_ok(),
972            quotable
973        );
974    }
975
976    /// Each refusal is counted under its own `reason`, once per refused call.
977    #[rstest]
978    #[case::price_levels_expired(
979        state().with_quotable_until(Instant::now()),
980        100_000_000,
981        wbtc(),
982        "price_levels_expired"
983    )]
984    #[case::unknown_pair(state(), 1, weth(), "unknown_pair")]
985    #[case::no_liquidity(empty_state(), 1, wbtc(), "no_liquidity")]
986    #[case::below_smallest_quote(state(), 50_000_000, wbtc(), "below_smallest_quote")]
987    #[case::not_monotonic(glitched_state(), 150, wbtc(), "not_monotonic")]
988    fn a_refused_quote_is_counted_under_its_reason(
989        #[case] state: PriceLevelStreamState,
990        #[case] amount_in: u64,
991        #[case] token_in: Token,
992        #[case] reason: &str,
993    ) {
994        let (result, snapshot) = record_async(async {
995            state.get_amount_out(BigUint::from(amount_in), &token_in, &usdc())
996        });
997
998        assert!(result.is_err());
999        assert_eq!(
1000            counter_value(
1001                &snapshot,
1002                "price_level_stream_quotes_refused_total",
1003                &[("reason", reason)]
1004            ),
1005            1
1006        );
1007    }
1008
1009    /// `spot_price` counts its own refusal, as `get_amount_out` does.
1010    #[test]
1011    fn a_refused_spot_price_is_counted() {
1012        let (result, snapshot) = record_async(async { empty_state().spot_price(&wbtc(), &usdc()) });
1013
1014        assert!(result.is_err());
1015        assert_eq!(
1016            counter_value(
1017                &snapshot,
1018                "price_level_stream_quotes_refused_total",
1019                &[("reason", "no_liquidity")]
1020            ),
1021            1
1022        );
1023    }
1024
1025    #[test]
1026    fn state_without_quotable_until_never_expires() {
1027        let far = Instant::now() + Duration::from_secs(1_000_000);
1028        assert!(state().ensure_quotable(far).is_ok());
1029    }
1030
1031    #[test]
1032    fn expired_state_refuses_every_query() {
1033        // `quotable_until` is set to `Instant::now()`, which has passed by the time the queries
1034        // run.
1035        let state = state().with_quotable_until(Instant::now());
1036        assert!(matches!(
1037            state.get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc()),
1038            Err(SimulationError::RecoverableError(_))
1039        ));
1040        assert!(matches!(
1041            state.spot_price(&wbtc(), &usdc()),
1042            Err(SimulationError::RecoverableError(_))
1043        ));
1044        assert!(matches!(
1045            state.get_limits(wbtc().address, usdc().address),
1046            Err(SimulationError::RecoverableError(_))
1047        ));
1048    }
1049
1050    #[test]
1051    fn fresh_state_answers_every_query() {
1052        let state = state().with_quotable_until(Instant::now() + Duration::from_secs(60));
1053        assert!(state
1054            .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
1055            .is_ok());
1056        assert!(state
1057            .spot_price(&wbtc(), &usdc())
1058            .is_ok());
1059        assert!(state
1060            .get_limits(wbtc().address, usdc().address)
1061            .is_ok());
1062    }
1063
1064    #[test]
1065    fn successor_state_keeps_quotable_until() {
1066        let until = Instant::now() + Duration::from_secs(60);
1067        let state = state().with_quotable_until(until);
1068        let result = state
1069            .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
1070            .expect("fresh state quotes");
1071        let successor = result
1072            .new_state
1073            .as_any()
1074            .downcast_ref::<PriceLevelStreamState>()
1075            .expect("price level state");
1076        assert_eq!(successor.quotable_until, Some(until));
1077    }
1078
1079    #[test]
1080    fn quotable_until_serde_round_trip() {
1081        let live = state().with_quotable_until(Instant::now());
1082        let json = serde_json::to_value(&live).unwrap();
1083        assert!(json
1084            .as_object()
1085            .unwrap()
1086            .get("quotable_until")
1087            .is_none());
1088        // A deserialized state has no `quotable_until`, so a recording replays without expiring.
1089        let replayed: PriceLevelStreamState = serde_json::from_value(json).unwrap();
1090        assert_eq!(replayed.quotable_until, None);
1091        assert!(replayed
1092            .spot_price(&wbtc(), &usdc())
1093            .is_ok());
1094    }
1095
1096    /// Two messages carrying the same quotes yield equal states, whatever their guards.
1097    #[test]
1098    fn eq_ignores_quotable_until() {
1099        let until = Instant::now() + Duration::from_secs(60);
1100        assert!(state().eq(&state().with_quotable_until(until)));
1101        assert!(state()
1102            .with_quotable_until(until)
1103            .eq(&state().with_quotable_until(until + Duration::from_secs(1))));
1104    }
1105
1106    #[test]
1107    fn with_simulation_overrides_sets_and_exposes_them() {
1108        assert_eq!(state().simulation_overrides(), None);
1109        assert_eq!(
1110            state()
1111                .with_simulation_overrides(test_overrides())
1112                .simulation_overrides(),
1113            Some(&test_overrides())
1114        );
1115    }
1116
1117    /// `eq` compares the block and the overridden account addresses of the simulation overrides,
1118    /// not the overridden values: see `eq`'s own documentation.
1119    #[rstest]
1120    #[case::the_same_overrides(Some(test_overrides()), true)]
1121    #[case::no_overrides(None, false)]
1122    #[case::rebuilt_with_other_values(Some(rebuilt_with_other_values()), true)]
1123    #[case::another_block(Some(in_another_block()), false)]
1124    #[case::fewer_accounts(Some(with_one_account_fewer()), false)]
1125    #[case::another_account(Some(with_another_account()), false)]
1126    fn eq_compares_the_block_and_the_accounts_not_the_values(
1127        #[case] other: Option<PammSimulationOverrides>,
1128        #[case] equal: bool,
1129    ) {
1130        let held = state().with_simulation_overrides(test_overrides());
1131        let other = match other {
1132            Some(overrides) => state().with_simulation_overrides(overrides),
1133            None => state(),
1134        };
1135
1136        assert_eq!(held.eq(&other), equal);
1137        assert_eq!(other.eq(&held), equal);
1138    }
1139
1140    /// [`test_overrides`] taken later in the same block: every overridden value and the build time
1141    /// differ, the account addresses and the block do not.
1142    fn rebuilt_with_other_values() -> PammSimulationOverrides {
1143        let mut rebuilt = test_overrides();
1144        rebuilt.built_at_ns += 1;
1145        for account in rebuilt.accounts.values_mut() {
1146            account.balance = Some(Bytes::from(vec![0x42]));
1147            account.nonce = account.nonce.map(|nonce| nonce + 1);
1148            account.state_diff.clear();
1149        }
1150        rebuilt
1151    }
1152
1153    /// [`test_overrides`] in the next block.
1154    fn in_another_block() -> PammSimulationOverrides {
1155        PammSimulationOverrides { block_number: Some(26_201_955), ..test_overrides() }
1156    }
1157
1158    /// [`test_overrides`] with as many accounts, one of them under another address, as when a merge
1159    /// swaps one quote address's entry for another's.
1160    fn with_another_account() -> PammSimulationOverrides {
1161        let mut swapped = test_overrides();
1162        let (_, account) = swapped
1163            .accounts
1164            .pop_first()
1165            .expect("an account");
1166        swapped
1167            .accounts
1168            .insert(Bytes::from(vec![0xab; 20]), account);
1169        swapped
1170    }
1171
1172    /// [`test_overrides`] without its first account, as when a merge loses another quote
1173    /// address's entry.
1174    fn with_one_account_fewer() -> PammSimulationOverrides {
1175        let mut fewer = test_overrides();
1176        fewer.accounts.pop_first();
1177        fewer
1178    }
1179
1180    /// The successor still carries the state the fill was priced on.
1181    #[test]
1182    fn successor_state_keeps_the_overrides() {
1183        let state = state().with_simulation_overrides(test_overrides());
1184        let result = state
1185            .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
1186            .expect("fresh state quotes");
1187        let successor = result
1188            .new_state
1189            .as_any()
1190            .downcast_ref::<PriceLevelStreamState>()
1191            .expect("price level state");
1192        assert_eq!(successor.simulation_overrides(), Some(&test_overrides()));
1193    }
1194
1195    /// A state built from captured quotes and carrying captured overrides survives both
1196    /// serde_json shapes. Nothing in the overrides is wider than `u64`, because a
1197    /// `serde_json::Value` cannot hold a wider integer.
1198    #[test]
1199    fn an_override_bearing_captured_state_round_trips_as_text_and_as_a_value() {
1200        let state = captured_state().with_simulation_overrides(test_overrides());
1201
1202        let text = serde_json::to_string(&state).expect("serializes");
1203        let value = serde_json::to_value(&state).expect("serializes into a Value");
1204        let from_text: PriceLevelStreamState =
1205            serde_json::from_str(&text).expect("reads back from text");
1206        let from_value: PriceLevelStreamState =
1207            serde_json::from_value(value).expect("reads back from a Value");
1208
1209        for read in [&from_text, &from_value] {
1210            assert_eq!(read.simulation_overrides(), Some(&test_overrides()));
1211            assert!(state.eq(read));
1212        }
1213    }
1214
1215    /// The same state through a boxed `dyn ProtocolSim`, in both orders typetag's adjacent tag
1216    /// can arrive in. The order decides the path: with the tag first typetag streams the state
1217    /// straight into its deserializer, while with the content first it buffers the whole state
1218    /// into its own `Content` enum and replays it — and that buffer, like a `serde_json::Value`,
1219    /// holds no integer wider than `u64`.
1220    #[rstest]
1221    #[case::tag_before_content(tag_first)]
1222    #[case::content_before_tag(content_first)]
1223    fn an_override_bearing_captured_state_round_trips_through_a_boxed_protocol_sim(
1224        #[case] recording: fn(&str, &str) -> String,
1225    ) {
1226        let state = captured_state().with_simulation_overrides(test_overrides());
1227        let text = recording(TAG, &serde_json::to_string(&state).expect("serializes"));
1228
1229        let boxed: Box<dyn ProtocolSim> = serde_json::from_str(&text).expect("reads back");
1230
1231        assert!(state.eq(boxed.as_ref()));
1232        let read = boxed
1233            .as_any()
1234            .downcast_ref::<PriceLevelStreamState>()
1235            .expect("price level state");
1236        assert_eq!(read.simulation_overrides(), Some(&test_overrides()));
1237    }
1238
1239    /// The tag the recordings in these tests carry is the one typetag itself writes.
1240    #[test]
1241    fn typetag_writes_the_tag_the_recordings_carry() {
1242        let text = serde_json::to_string(&state() as &dyn ProtocolSim).expect("serializes");
1243
1244        assert!(text.starts_with(&format!(r#"{{"protocol":{TAG},"#)), "{text}");
1245    }
1246
1247    /// The state serializes its overrides under the top-level key `overrides`, in the typed form
1248    /// and inside typetag's `state` content alike.
1249    ///
1250    /// A rename would break every recording without an error: the old key would be ignored as an
1251    /// unknown field and the state would read back without overrides, as recordings made before
1252    /// the field do (see `a_legacy_typed_recording_reads_back_without_overrides`). So this test
1253    /// pins the name.
1254    #[test]
1255    fn the_serialized_overrides_key_is_named_overrides() {
1256        let state = captured_state().with_simulation_overrides(test_overrides());
1257
1258        let text = serde_json::to_string(&state).expect("serializes");
1259        let typed = serde_json::to_value(&state).expect("serializes");
1260        let boxed = serde_json::to_value(&state as &dyn ProtocolSim).expect("serializes");
1261
1262        assert!(text.contains(r#""overrides":"#), "no `overrides` key in the state JSON");
1263        for json in [&typed, &boxed["state"]] {
1264            let overrides = json
1265                .as_object()
1266                .expect("an object")
1267                .get("overrides")
1268                .expect("the state object names them `overrides`");
1269            let read: PammSimulationOverrides =
1270                serde_json::from_value(overrides.clone()).expect("the overrides under that key");
1271            assert_eq!(read, test_overrides());
1272        }
1273    }
1274
1275    /// A recording made before the field existed reads back as a state without overrides, rather
1276    /// than failing on the missing key.
1277    #[test]
1278    fn a_legacy_typed_recording_reads_back_without_overrides() {
1279        let read: PriceLevelStreamState = serde_json::from_str(LEGACY_STATE).expect("reads back");
1280        assert_eq!(read.simulation_overrides(), None);
1281        assert_eq!(read.quotes_0_to_1, vec![quote(100_000_000, 100_000_000_000)]);
1282        assert_eq!(read.quotes_1_to_0, vec![quote(100_000_000_000, 99_000_000)]);
1283    }
1284
1285    /// The same legacy recording boxed, in both tag orders: the content-first path buffers the
1286    /// absent key as absent too.
1287    #[rstest]
1288    #[case::tag_before_content(tag_first)]
1289    #[case::content_before_tag(content_first)]
1290    fn a_legacy_boxed_recording_reads_back_without_overrides(
1291        #[case] recording: fn(&str, &str) -> String,
1292    ) {
1293        let boxed: Box<dyn ProtocolSim> =
1294            serde_json::from_str(&recording(TAG, LEGACY_STATE)).expect("reads back");
1295        let read = boxed
1296            .as_any()
1297            .downcast_ref::<PriceLevelStreamState>()
1298            .expect("price level state");
1299        assert_eq!(read.simulation_overrides(), None);
1300        assert_eq!(read.quotes_0_to_1, vec![quote(100_000_000, 100_000_000_000)]);
1301    }
1302
1303    /// A state without overrides writes the legacy shape, so a consumer built before the field
1304    /// existed can read a recording made now.
1305    #[test]
1306    fn a_state_without_overrides_serializes_without_the_key() {
1307        let typed = serde_json::to_value(state()).expect("serializes");
1308        let boxed = serde_json::to_value(&state() as &dyn ProtocolSim).expect("serializes");
1309
1310        for json in [&typed, &boxed["state"]] {
1311            assert!(json
1312                .as_object()
1313                .expect("an object")
1314                .get("overrides")
1315                .is_none());
1316        }
1317    }
1318}