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