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