tycho-simulation 0.515.0

Provides tools for interacting with protocol states, calculating spot prices, and quoting token swaps.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
use std::{
    any::Any,
    collections::HashMap,
    sync::Arc,
    time::{Duration, Instant},
};

use num_bigint::BigUint;
use num_traits::{CheckedSub, ToPrimitive};
use serde::{Deserialize, Serialize};
use tycho_common::{
    dto::ProtocolStateDelta,
    models::token::Token,
    simulation::{
        errors::{SimulationError, TransitionError},
        protocol_sim::{Balances, GetAmountOutResult, ProtocolSim},
    },
    Bytes,
};

use super::{overrides::PammSimulationOverrides, telemetry};
use crate::utils::decimals_scale;

/// How long the quotes of one price level message stay quotable: one slot after the message's `ts`.
/// Titan prices the block it is building, so quotes older than one slot were priced for a block
/// already built. The guard is loose on purpose: the builder usually refreshes a venue before
/// inclusion, so a quote for the previous block often still fills, and the fallback router covers
/// the cases where it does not.
pub const QUOTE_TTL: Duration = super::SLOT;

/// The error of a query on the other direction once a swap filled this one.
const ALREADY_QUOTED: &str = "Price level stream already quoted in this route";

/// A single price level: the total `amount_out` a swap of exactly `amount_in` would deliver.
///
/// Levels are absolute quotes, not marginal order book sizes: each one already includes all
/// smaller levels' liquidity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PriceLevelStreamQuote {
    pub amount_in: BigUint,
    pub amount_out: BigUint,
}

impl PriceLevelStreamQuote {
    pub fn new(amount_in: BigUint, amount_out: BigUint) -> Self {
        Self { amount_in, amount_out }
    }
}

/// The merged swap an earlier swap on one direction has made so far, in atomic units.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct StreamFill {
    token_in: Bytes,
    token_out: Bytes,
    /// The input of the merged swap so far.
    amount_in: BigUint,
    /// The output the merged swap has paid so far.
    amount_out: BigUint,
}

/// State of a single pAMM pair fed from the price level stream.
///
/// Holds the latest complete quotes for both trade directions. Quotes are absolute
/// (`amount_in` → total `amount_out`), sorted ascending by `amount_in`; amounts between two
/// quotes are interpolated linearly, mirroring how Titan itself densifies the simulated levels.
/// Amounts outside the quoted range are not served.
///
/// A swap returns a state that records its fill. A later swap on the same direction continues
/// that fill: it pays the quotes' output for the merged input less the output so far, at zero
/// gas, and `get_limits` and `spot_price` answer for what is left. The other direction is refused
/// with an "already quoted" error, as the quotes are cumulative from the pre-fill venue and say
/// nothing about its price after a fill. So the caller merges all swaps on one direction into
/// one swap.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[expect(
    clippy::partial_pub_fields,
    reason = "public API; making every field public or private is a breaking change"
)]
pub struct PriceLevelStreamState {
    pub token0: Bytes,
    pub token1: Bytes,
    pub quotes_0_to_1: Vec<PriceLevelStreamQuote>,
    pub quotes_1_to_0: Vec<PriceLevelStreamQuote>,
    pub gas_cost: BigUint,
    /// What an earlier swap filled on this state. Older serialized states carry none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    fill: Option<StreamFill>,
    /// Monotonic instant from which this state refuses every query. `None` means the state never
    /// expires. The field is never serialized and deserializes as `None`, so a replayed
    /// recording always quotes. Only [`with_quotable_until`](Self::with_quotable_until) sets it,
    /// and equality ignores it: two states carrying the same quotes compare equal whichever
    /// messages they came from.
    #[serde(skip)]
    quotable_until: Option<Instant>,
    /// The account state Titan priced these quotes on, when the tracker matched a quote stream
    /// entry to them. An `Arc`, because every state a quote returns keeps it. Unlike
    /// `quotable_until` it is serialized, so a recording replays it;
    /// [`with_simulation_overrides`](Self::with_simulation_overrides) is the only setter.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    overrides: Option<Arc<PammSimulationOverrides>>,
}

impl PriceLevelStreamState {
    /// Creates the state for the pair `(token0, token1)`.
    ///
    /// Both quote lists are sorted ascending by `amount_in` and deduplicated on it, so callers
    /// may pass them in stream order.
    pub fn new(
        token0: Bytes,
        token1: Bytes,
        mut quotes_0_to_1: Vec<PriceLevelStreamQuote>,
        mut quotes_1_to_0: Vec<PriceLevelStreamQuote>,
        gas_cost: BigUint,
    ) -> Self {
        for quotes in [&mut quotes_0_to_1, &mut quotes_1_to_0] {
            quotes.sort_by(|a, b| a.amount_in.cmp(&b.amount_in));
            quotes.dedup_by(|a, b| a.amount_in == b.amount_in);
        }
        Self {
            token0,
            token1,
            quotes_0_to_1,
            quotes_1_to_0,
            gas_cost,
            fill: None,
            quotable_until: None,
            overrides: None,
        }
    }

    /// Sets the monotonic instant from which this state refuses every query.
    pub fn with_quotable_until(mut self, until: Instant) -> Self {
        self.quotable_until = Some(until);
        self
    }

    /// Attaches the account state Titan priced these quotes on.
    pub fn with_simulation_overrides(
        mut self,
        overrides: impl Into<Arc<PammSimulationOverrides>>,
    ) -> Self {
        self.overrides = Some(overrides.into());
        self
    }

    /// The account state Titan priced these quotes on, to convert and pass to `eth_call` as state
    /// overrides, or `None` when the stream matched no quote stream entry to this state's book, or
    /// runs without simulation overrides. Quoting never reads it.
    pub fn simulation_overrides(&self) -> Option<&PammSimulationOverrides> {
        self.overrides.as_deref()
    }

    /// The monotonic instant from which this state refuses every query, or `None` if it never
    /// expires.
    pub fn quotable_until(&self) -> Option<Instant> {
        self.quotable_until
    }

    /// Returns a `RecoverableError` once `now` reaches `quotable_until`. A state without
    /// `quotable_until` never errors.
    fn ensure_quotable(&self, now: Instant) -> Result<(), SimulationError> {
        match self.quotable_until {
            Some(until) if now >= until => {
                telemetry::record_quote_refused(telemetry::QuoteRefusedReason::PriceLevelsExpired);
                Err(SimulationError::RecoverableError(format!(
                    "price levels expired: the message that carried them is older than {} s (one \
                     slot)",
                    QUOTE_TTL.as_secs()
                )))
            }
            Some(_) | None => Ok(()),
        }
    }

    /// Returns the quotes selling `token_in` for `token_out`, or an error if the pair does
    /// not match this state's tokens.
    fn quotes(
        &self,
        token_in: &Bytes,
        token_out: &Bytes,
    ) -> Result<&[PriceLevelStreamQuote], SimulationError> {
        if token_in == &self.token0 && token_out == &self.token1 {
            Ok(&self.quotes_0_to_1)
        } else if token_in == &self.token1 && token_out == &self.token0 {
            Ok(&self.quotes_1_to_0)
        } else {
            telemetry::record_quote_refused(telemetry::QuoteRefusedReason::UnknownPair);
            Err(SimulationError::RecoverableError(format!(
                "Invalid token addresses for pair {}/{}: {token_in}, {token_out}",
                self.token0, self.token1
            )))
        }
    }

    /// Computes the output amount for `amount_in` on the given quotes by linear interpolation
    /// between the two enclosing quotes.
    ///
    /// Callers must ensure `amount_in` lies within the quoted range (smallest to largest
    /// `amount_in`) — the quotes hold no information outside of it. Errors if the enclosing
    /// quotes are not monotonically increasing in `amount_out`: such quotes are unreliable,
    /// and a venue with corrupt data should not be quoted at any price.
    fn interpolate(
        &self,
        quotes: &[PriceLevelStreamQuote],
        amount_in: &BigUint,
    ) -> Result<BigUint, SimulationError> {
        // First quote with amount_in >= the requested amount; the caller-guaranteed range makes
        // both it and (when needed) its predecessor exist.
        let idx = quotes.partition_point(|quote| &quote.amount_in < amount_in);
        let upper = &quotes[idx];
        if &upper.amount_in == amount_in {
            return Ok(upper.amount_out.clone());
        }
        let lower = &quotes[idx - 1];
        let Some(out_span) = upper
            .amount_out
            .checked_sub(&lower.amount_out)
        else {
            // Recoverable: the next message replaces the quotes wholesale.
            telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NotMonotonic);
            return Err(SimulationError::RecoverableError(format!(
                "Quotes {}/{} are not monotonically increasing in amount_out around the \
                 requested amount {amount_in}: {} -> {}, but {} -> {}",
                self.token0,
                self.token1,
                lower.amount_in,
                lower.amount_out,
                upper.amount_in,
                upper.amount_out,
            )));
        };
        let in_span = &upper.amount_in - &lower.amount_in;
        let offset = amount_in - &lower.amount_in;
        Ok(&lower.amount_out + out_span * offset / in_span)
    }

    /// The fill an earlier swap made on `token_in` into `token_out`, if any. Errors when the
    /// state was filled on the other direction.
    fn fill_on(
        &self,
        token_in: &Bytes,
        token_out: &Bytes,
    ) -> Result<Option<&StreamFill>, SimulationError> {
        match &self.fill {
            Some(fill) if &fill.token_in == token_in && &fill.token_out == token_out => {
                Ok(Some(fill))
            }
            Some(_) => Err(SimulationError::RecoverableError(ALREADY_QUOTED.to_string())),
            None => Ok(None),
        }
    }

    /// This state with `fill` recorded. It keeps the quotes, `quotable_until` and the simulation
    /// overrides: the overrides are the state the fill was priced on, and a consumer simulates
    /// the swap after quoting it.
    fn with_fill(&self, fill: StreamFill) -> Box<dyn ProtocolSim> {
        Box::new(Self { fill: Some(fill), ..self.clone() })
    }

    /// The marginal price of the next input unit after `filled` went into `quotes`, in whole
    /// tokens of `quote` per whole token of `base`. Below the smallest quote it is the price of
    /// the first segment. Errors when `filled` reaches the largest quote, or when the segment it
    /// falls in pays nothing or is not monotonically increasing in `amount_out`.
    fn marginal_price(
        &self,
        quotes: &[PriceLevelStreamQuote],
        filled: &BigUint,
        base: &Token,
        quote: &Token,
    ) -> Result<f64, SimulationError> {
        let no_liquidity = || {
            telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NoLiquidity);
            SimulationError::RecoverableError("No liquidity available".to_string())
        };
        let idx = quotes.partition_point(|level| &level.amount_in <= filled);
        let upper = quotes
            .get(idx)
            .ok_or_else(no_liquidity)?;
        let (lower_in, lower_out) = match idx
            .checked_sub(1)
            .and_then(|lower| quotes.get(lower))
        {
            Some(lower) => (&lower.amount_in, &lower.amount_out),
            None => (&BigUint::ZERO, &BigUint::ZERO),
        };
        let Some(out_span) = upper.amount_out.checked_sub(lower_out) else {
            telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NotMonotonic);
            return Err(SimulationError::RecoverableError(format!(
                "Quotes {}/{} are not monotonically increasing in amount_out around the filled \
                 amount {filled}",
                self.token0, self.token1
            )));
        };
        if out_span == BigUint::ZERO {
            return Err(no_liquidity());
        }
        whole_unit_price(&(&upper.amount_in - lower_in), &out_span, base, quote)
    }

    /// The output of a swap of `amount_in` on `quotes`, priced by the quotes alone: below the
    /// smallest quote nothing is served, above the largest the result is partial.
    fn priced_amount_out(
        &self,
        quotes: &[PriceLevelStreamQuote],
        amount_in: &BigUint,
    ) -> Result<PricedAmount, SimulationError> {
        let (Some(first), Some(last)) = (quotes.first(), quotes.last()) else {
            telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NoLiquidity);
            return Err(SimulationError::RecoverableError("No liquidity available".to_string()));
        };
        // Below the smallest quote nothing is served. The venue itself could still fill —
        // FermiSwap was observed quoting below the smallest streamed level — but if so, on its
        // own price curve, which the quotes hold no information about: unlike interpolation
        // between two quoted levels, whose result is bracketed by genuine samples on both
        // sides, extrapolating linearly from (0, 0) like Titan's quote API does is an unbounded
        // guess even off healthy quotes. (0, 0) is an assumption, not a sample, and the
        // bottom of that line is not even fillable: FermiSwap reverts below a venue-side
        // minimum (~$0.02 at the time of measurement) where the API keeps quoting. And
        // malformed quotes turn the guess absurd: on FermiSwap's flat cbBTC-input books
        // (18-decimals grid bug) the smallest quote is the venue's depth clamp, not a price
        // sample, and the extrapolated quotes land ~3e6x below the venue's own (measured
        // 2026-07). All the rejection gives up are trades smaller than the first level —
        // ~$10-30 on healthy quotes, negligible for routing. Hence no partial result either.
        if amount_in < &first.amount_in {
            telemetry::record_quote_refused(telemetry::QuoteRefusedReason::BelowSmallestQuote);
            return Err(SimulationError::InvalidInput(
                format!(
                    "Input amount is below the smallest quote. input amount: {amount_in}, minimum quoted amount: {}",
                    first.amount_in
                ),
                None,
            ));
        }
        // The requested amount exceeds the largest quote; report the output at the limit as a
        // partial result, like other level-based protocols do.
        if amount_in > &last.amount_in {
            return Ok(PricedAmount::Partial {
                amount: last.amount_out.clone(),
                message: format!(
                    "Not enough liquidity to support complete swap. input amount: {amount_in}, maximum quoted amount: {}",
                    last.amount_in
                ),
            });
        }
        Ok(PricedAmount::Complete(self.interpolate(quotes, amount_in)?))
    }
}

/// What the quotes alone pay for a swap.
enum PricedAmount {
    /// The quotes serve the whole input.
    Complete(BigUint),
    /// The input exceeds the largest quote: `amount` is the output at that quote, and `message`
    /// says why the swap is partial.
    Partial { amount: BigUint, message: String },
}

/// `amount_out` per `amount_in`, in whole tokens of `quote` per whole token of `base`.
fn whole_unit_price(
    amount_in: &BigUint,
    amount_out: &BigUint,
    base: &Token,
    quote: &Token,
) -> Result<f64, SimulationError> {
    let amount_in = amount_in.to_f64().ok_or_else(|| {
        SimulationError::RecoverableError("Can't convert amount in to f64".to_string())
    })?;
    let amount_out = amount_out.to_f64().ok_or_else(|| {
        SimulationError::RecoverableError("Can't convert amount out to f64".to_string())
    })?;
    Ok((amount_out / decimals_scale(quote.decimals)) / (amount_in / decimals_scale(base.decimals)))
}

/// `amount` less `taken`, or zero when `taken` is larger.
fn saturating_sub(amount: &BigUint, taken: &BigUint) -> BigUint {
    amount
        .checked_sub(taken)
        .unwrap_or_default()
}

#[typetag::serde]
impl ProtocolSim for PriceLevelStreamState {
    fn fee(&self) -> f64 {
        0.0
    }

    /// Before a fill, the price of the smallest quote. After a fill, the marginal price at the
    /// filled amount, and a refusal for the other direction.
    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
        self.ensure_quotable(Instant::now())?;
        let quotes = self.quotes(&base.address, &quote.address)?;
        if let Some(fill) = self.fill_on(&base.address, &quote.address)? {
            return self.marginal_price(quotes, &fill.amount_in, base, quote);
        }
        let best = quotes
            .iter()
            .find(|q| q.amount_in > BigUint::ZERO && q.amount_out > BigUint::ZERO)
            .ok_or_else(|| {
                telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NoLiquidity);
                SimulationError::RecoverableError("No liquidity available".to_string())
            })?;
        whole_unit_price(&best.amount_in, &best.amount_out, base, quote)
    }

    /// Records the fill in the returned state. After a swap on the same direction it pays the
    /// output of the merged input less the output so far, at zero gas. A swap on the other
    /// direction fails: the venue already quoted. See [`PriceLevelStreamState`].
    fn get_amount_out(
        &self,
        amount_in: BigUint,
        token_in: &Token,
        token_out: &Token,
    ) -> Result<GetAmountOutResult, SimulationError> {
        self.ensure_quotable(Instant::now())?;
        let quotes = self.quotes(&token_in.address, &token_out.address)?;
        let previous = self.fill_on(&token_in.address, &token_out.address)?;
        let merged_in = match previous {
            Some(previous) => &previous.amount_in + &amount_in,
            None => amount_in,
        };
        let (merged_out, partial_message) = match self.priced_amount_out(quotes, &merged_in)? {
            PricedAmount::Complete(amount) => (amount, None),
            PricedAmount::Partial { amount, message } => (amount, Some(message)),
        };
        let (amount, gas) = match previous {
            Some(previous) => (saturating_sub(&merged_out, &previous.amount_out), BigUint::ZERO),
            None => (merged_out.clone(), self.gas_cost.clone()),
        };
        let new_state = self.with_fill(StreamFill {
            token_in: token_in.address.clone(),
            token_out: token_out.address.clone(),
            amount_in: merged_in,
            amount_out: merged_out,
        });
        let result = GetAmountOutResult { amount, gas, new_state };
        match partial_message {
            Some(message) => Err(SimulationError::InvalidInput(message, Some(result))),
            None => Ok(result),
        }
    }

    /// The largest quote, less the fill after a swap on the same direction. A swap on the other
    /// direction fails: the venue already quoted.
    fn get_limits(
        &self,
        sell_token: Bytes,
        buy_token: Bytes,
    ) -> Result<(BigUint, BigUint), SimulationError> {
        self.ensure_quotable(Instant::now())?;
        let quotes = self.quotes(&sell_token, &buy_token)?;
        let fill = self.fill_on(&sell_token, &buy_token)?;
        let (max_in, max_out) = match quotes.last() {
            Some(largest) => (largest.amount_in.clone(), largest.amount_out.clone()),
            None => (BigUint::ZERO, BigUint::ZERO),
        };
        Ok(match fill {
            Some(fill) => (
                saturating_sub(&max_in, &fill.amount_in),
                saturating_sub(&max_out, &fill.amount_out),
            ),
            None => (max_in, max_out),
        })
    }

    fn delta_transition(
        &mut self,
        _delta: ProtocolStateDelta,
        _tokens: &HashMap<Bytes, Token>,
        _balances: &Balances,
    ) -> Result<(), TransitionError> {
        Err(TransitionError::DecodeError("Not implemented".into()))
    }

    fn clone_box(&self) -> Box<dyn ProtocolSim> {
        Box::new(self.clone())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    /// Equal when the pair, both quote lists, the gas cost and the fill match, and either neither
    /// state carries simulation overrides, or both carry overrides of the same block over the
    /// same account addresses. A state that gains or loses its overrides is a changed state.
    ///
    /// The overridden values are left out. Quoting never reads them, and Titan republishes a
    /// venue's accounts several times a second while its prices stand still, so comparing them
    /// would report a changed quote for an unchanged price.
    ///
    /// The block is compared because prices can be identical across a block boundary: without it,
    /// a consumer that keeps the state it holds would simulate on the previous block's overrides.
    /// The account addresses are compared because a merge can add or lose another quote address's
    /// entry (see Metric); without them, a consumer would keep overrides missing an account the
    /// swap reads.
    ///
    /// `quotable_until` is left out too: this process derives it and never serializes it. A
    /// consumer that keeps the state it holds whenever `eq` says equal therefore keeps the earlier
    /// deadline, and that state stops quoting one slot after its own message, even while newer
    /// messages repeat the same quotes. Replace the held state on every update to always quote on
    /// the newest deadline.
    fn eq(&self, other: &dyn ProtocolSim) -> bool {
        other
            .as_any()
            .downcast_ref::<PriceLevelStreamState>()
            .is_some_and(|other| {
                let Self {
                    token0,
                    token1,
                    quotes_0_to_1,
                    quotes_1_to_0,
                    gas_cost,
                    fill,
                    quotable_until: _,
                    overrides,
                } = other;
                let same_overrides = match (&self.overrides, overrides) {
                    (Some(held), Some(arriving)) => {
                        held.block_number == arriving.block_number &&
                            held.accounts
                                .keys()
                                .eq(arriving.accounts.keys())
                    }
                    (None, None) => true,
                    _ => false,
                };
                &self.token0 == token0 &&
                    &self.token1 == token1 &&
                    &self.quotes_0_to_1 == quotes_0_to_1 &&
                    &self.quotes_1_to_0 == quotes_1_to_0 &&
                    &self.gas_cost == gas_cost &&
                    &self.fill == fill &&
                    same_overrides
            })
    }
}

#[cfg(test)]
mod tests {
    use std::time::{Duration, Instant};

    use rstest::rstest;

    use super::{
        super::{
            convert::quotes_for_book,
            telemetry::recorded::{counter_value, record_async},
            test_support::{captured_book, test_overrides, token, tokens, USDC, WBTC, WETH},
        },
        *,
    };

    /// The tag typetag writes for this state, as it appears in a recording.
    const TAG: &str = r#""PriceLevelStreamState""#;

    /// A recording written before the state carried overrides, verbatim: it has no `overrides`
    /// key at all, and its `BigUint` amounts are sequences of base-2^32 digits.
    const LEGACY_STATE: &str = r#"{
      "token0": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",
      "token1": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
      "quotes_0_to_1": [{"amount_in": [100000000], "amount_out": [1215752192, 23]}],
      "quotes_1_to_0": [{"amount_in": [1215752192, 23], "amount_out": [99000000]}],
      "gas_cost": [120000]
    }"#;

    /// A recording of an adjacently tagged state with the tag before the content, as typetag
    /// itself writes it.
    fn tag_first(tag: &str, state: &str) -> String {
        format!(r#"{{"protocol":{tag},"state":{state}}}"#)
    }

    /// The same two fields the other way round: the order that makes typetag buffer the whole
    /// state before it knows what to read it as.
    fn content_first(tag: &str, state: &str) -> String {
        format!(r#"{{"state":{state},"protocol":{tag}}}"#)
    }

    fn wbtc() -> Token {
        token(WBTC, "WBTC", 8)
    }

    fn usdc() -> Token {
        token(USDC, "USDC", 6)
    }

    fn weth() -> Token {
        token(WETH, "WETH", 18)
    }

    fn quote(amount_in: u64, amount_out: u64) -> PriceLevelStreamQuote {
        PriceLevelStreamQuote::new(BigUint::from(amount_in), BigUint::from(amount_out))
    }

    /// WBTC (token0) / USDC (token1) quotes: 1 WBTC -> 100k USDC flat, then the second level
    /// fills at a worse marginal price.
    fn state() -> PriceLevelStreamState {
        PriceLevelStreamState::new(
            wbtc().address,
            usdc().address,
            vec![quote(100_000_000, 100_000_000_000), quote(200_000_000, 190_000_000_000)],
            vec![quote(100_000_000_000, 99_000_000), quote(200_000_000_000, 190_000_000)],
            BigUint::from(120_000u64),
        )
    }

    /// The Bebop WETH/USDC quotes of the captured live message, converted as the stream converts
    /// them: the amounts Titan quoted.
    fn captured_state() -> PriceLevelStreamState {
        let tokens = tokens();
        let book = captured_book("Bebop", "WETH", "USDC");
        let weth = tokens
            .get(&weth().address)
            .expect("WETH is admitted");
        let usdc = tokens
            .get(&usdc().address)
            .expect("USDC is admitted");
        let (bids, asks) = quotes_for_book(&book, weth, usdc);
        PriceLevelStreamState::new(
            weth.address.clone(),
            usdc.address.clone(),
            bids.expect("the captured bids convert"),
            asks.expect("the captured asks convert"),
            BigUint::from(120_000u64),
        )
    }

    #[test]
    fn captured_state_carries_the_whole_captured_book() {
        let state = captured_state();
        assert_eq!(state.quotes_0_to_1.len(), 15);
        assert_eq!(state.quotes_1_to_0.len(), 14);
    }

    #[test]
    fn new_sorts_and_dedups_quotes() {
        let state = PriceLevelStreamState::new(
            wbtc().address,
            usdc().address,
            vec![quote(200, 380), quote(100, 200), quote(200, 999)],
            vec![],
            BigUint::ZERO,
        );
        assert_eq!(state.quotes_0_to_1, vec![quote(100, 200), quote(200, 380)]);
    }

    #[test]
    fn get_amount_out_exact_level() {
        let result = state()
            .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
            .unwrap();
        assert_eq!(result.amount, BigUint::from(100_000_000_000u64));
        assert_eq!(result.gas, BigUint::from(120_000u64));
    }

    #[test]
    fn get_amount_out_interpolates_between_levels() {
        // Halfway between the two levels: 100k + (190k - 100k) / 2 = 145k USDC.
        let result = state()
            .get_amount_out(BigUint::from(150_000_000u64), &wbtc(), &usdc())
            .unwrap();
        assert_eq!(result.amount, BigUint::from(145_000_000_000u64));
    }

    /// A WBTC/USDC state whose WBTC quotes are not monotonically increasing in amount_out, as
    /// after a stream glitch.
    fn glitched_state() -> PriceLevelStreamState {
        PriceLevelStreamState::new(
            wbtc().address,
            usdc().address,
            vec![quote(100, 200), quote(200, 150)],
            vec![],
            BigUint::ZERO,
        )
    }

    /// A WBTC/USDC state with no quotes in either direction.
    fn empty_state() -> PriceLevelStreamState {
        PriceLevelStreamState::new(wbtc().address, usdc().address, vec![], vec![], BigUint::ZERO)
    }

    #[test]
    fn get_amount_out_on_glitched_quotes_is_rejected() {
        // The data is unreliable, so a quote landing in the glitched segment is refused instead
        // of interpolated (or underflowing).
        let state = glitched_state();
        let result = state.get_amount_out(BigUint::from(150u64), &wbtc(), &usdc());
        assert!(matches!(result, Err(SimulationError::RecoverableError(_))));

        // Hitting a level exactly returns that genuine sample even on glitched quotes.
        let result = state
            .get_amount_out(BigUint::from(100u64), &wbtc(), &usdc())
            .unwrap();
        assert_eq!(result.amount, BigUint::from(200u64));
    }

    #[test]
    fn get_amount_out_below_smallest_level_is_rejected() {
        // The quotes hold no information below the smallest one, and there is no partial
        // result to offer.
        let result = state().get_amount_out(BigUint::from(50_000_000u64), &wbtc(), &usdc());
        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
    }

    #[test]
    fn get_amount_out_reverse_direction() {
        let result = state()
            .get_amount_out(BigUint::from(100_000_000_000u64), &usdc(), &wbtc())
            .unwrap();
        assert_eq!(result.amount, BigUint::from(99_000_000u64));
    }

    #[test]
    fn get_amount_out_beyond_largest_level_is_partial() {
        let result = state().get_amount_out(BigUint::from(300_000_000u64), &wbtc(), &usdc());
        match result {
            Err(SimulationError::InvalidInput(_, Some(partial))) => {
                assert_eq!(partial.amount, BigUint::from(190_000_000_000u64));
            }
            other => panic!("expected partial InvalidInput, got {other:?}"),
        }
    }

    fn successor(result: &GetAmountOutResult) -> &PriceLevelStreamState {
        result
            .new_state
            .as_any()
            .downcast_ref::<PriceLevelStreamState>()
            .expect("price level state")
    }

    /// The state after a swap of 1 WBTC for USDC.
    fn state_after_one_wbtc() -> PriceLevelStreamState {
        let result = state()
            .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
            .unwrap();
        successor(&result).clone()
    }

    fn wbtc_to_usdc_fill(amount_in: u64, amount_out: u64) -> StreamFill {
        StreamFill {
            token_in: wbtc().address,
            token_out: usdc().address,
            amount_in: BigUint::from(amount_in),
            amount_out: BigUint::from(amount_out),
        }
    }

    #[test]
    fn get_amount_out_records_the_fill_and_keeps_the_quotes() {
        let after = state_after_one_wbtc();
        assert_eq!(after.fill, Some(wbtc_to_usdc_fill(100_000_000, 100_000_000_000)));
        assert_eq!(after.quotes_0_to_1, state().quotes_0_to_1);
        assert_eq!(after.quotes_1_to_0, state().quotes_1_to_0);
    }

    #[test]
    fn two_chunks_pay_what_one_merged_swap_pays() {
        let merged = state()
            .get_amount_out(BigUint::from(150_000_000u64), &wbtc(), &usdc())
            .unwrap();
        let first = state()
            .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
            .unwrap();
        let second = successor(&first)
            .get_amount_out(BigUint::from(50_000_000u64), &wbtc(), &usdc())
            .unwrap();
        assert_eq!(first.amount + &second.amount, merged.amount);
        assert_eq!(second.gas, BigUint::ZERO);
        assert_eq!(successor(&second).fill, successor(&merged).fill);
    }

    #[test]
    fn continued_chunk_beyond_largest_level_is_partial_and_carries_the_fill() {
        let result =
            state_after_one_wbtc().get_amount_out(BigUint::from(200_000_000u64), &wbtc(), &usdc());
        let Err(SimulationError::InvalidInput(_, Some(partial))) = result else {
            panic!("expected partial InvalidInput, got {result:?}");
        };
        // The largest quote pays 190k USDC, 100k of which the first chunk took.
        assert_eq!(partial.amount, BigUint::from(90_000_000_000u64));
        assert_eq!(partial.gas, BigUint::ZERO);
        assert_eq!(successor(&partial).fill, Some(wbtc_to_usdc_fill(300_000_000, 190_000_000_000)));
    }

    /// After a fill on WBTC into USDC, every query on USDC into WBTC is refused.
    #[test]
    fn the_other_direction_after_a_fill_is_refused() {
        let after = state_after_one_wbtc();
        let refused = [
            after
                .get_amount_out(BigUint::from(100_000_000_000u64), &usdc(), &wbtc())
                .map(|_| ()),
            after
                .get_limits(usdc().address, wbtc().address)
                .map(|_| ()),
            after
                .spot_price(&usdc(), &wbtc())
                .map(|_| ()),
        ];
        for result in refused {
            assert!(matches!(
                result,
                Err(SimulationError::RecoverableError(message))
                    if message == "Price level stream already quoted in this route"
            ));
        }
    }

    #[test]
    fn get_amount_out_rejects_unknown_tokens() {
        let result = state().get_amount_out(BigUint::from(1u64), &weth(), &usdc());
        assert!(matches!(result, Err(SimulationError::RecoverableError(_))));
    }

    #[test]
    fn get_amount_out_without_liquidity() {
        let result = empty_state().get_amount_out(BigUint::from(1u64), &wbtc(), &usdc());
        assert!(matches!(result, Err(SimulationError::RecoverableError(_))));
    }

    #[test]
    fn spot_price_uses_smallest_quote() {
        // 1 WBTC (1e8) -> 100_000 USDC (1e11 at 6 decimals).
        let price = state()
            .spot_price(&wbtc(), &usdc())
            .unwrap();
        assert!((price - 100_000.0).abs() < 1e-9);

        let inverse = state()
            .spot_price(&usdc(), &wbtc())
            .unwrap();
        // 100k USDC (1e11 at 6 decimals) -> 0.99 WBTC: 0.99 / 100_000 = 9.9e-6.
        assert!((inverse - 9.9e-6).abs() < 1e-15);
    }

    #[test]
    fn spot_price_skips_zero_amount_out_quotes() {
        // A dust level rounding to zero output must not produce a spot price of 0 — consumers
        // computing 1/spot_price would divide by zero.
        let state = PriceLevelStreamState::new(
            wbtc().address,
            usdc().address,
            vec![quote(1, 0), quote(100_000_000, 100_000_000_000)],
            vec![],
            BigUint::ZERO,
        );
        let price = state
            .spot_price(&wbtc(), &usdc())
            .unwrap();
        assert!((price - 100_000.0).abs() < 1e-9);
    }

    #[test]
    fn get_limits_returns_largest_quote() {
        let (max_in, max_out) = state()
            .get_limits(wbtc().address, usdc().address)
            .unwrap();
        assert_eq!(max_in, BigUint::from(200_000_000u64));
        assert_eq!(max_out, BigUint::from(190_000_000_000u64));
    }

    #[test]
    fn get_limits_after_a_fill_are_the_quote_limits_less_the_fill() {
        let (max_in, max_out) = state_after_one_wbtc()
            .get_limits(wbtc().address, usdc().address)
            .unwrap();
        assert_eq!(max_in, BigUint::from(100_000_000u64));
        assert_eq!(max_out, BigUint::from(90_000_000_000u64));
    }

    #[test]
    fn get_limits_after_a_fill_beyond_the_quotes_are_zero() {
        let state = PriceLevelStreamState {
            fill: Some(wbtc_to_usdc_fill(300_000_000, 190_000_000_000)),
            ..state()
        };
        let limits = state
            .get_limits(wbtc().address, usdc().address)
            .unwrap();
        assert_eq!(limits, (BigUint::ZERO, BigUint::ZERO));
    }

    #[test]
    fn spot_price_after_a_fill_is_the_marginal_price_at_the_filled_amount() {
        // Past 1 WBTC the quotes pay 90k USDC per WBTC, down from 100k.
        let price = state_after_one_wbtc()
            .spot_price(&wbtc(), &usdc())
            .unwrap();
        assert!((price - 90_000.0).abs() < 1e-9);
    }

    #[test]
    fn spot_price_after_a_fill_to_the_largest_level_has_no_liquidity() {
        let state = PriceLevelStreamState {
            fill: Some(wbtc_to_usdc_fill(200_000_000, 190_000_000_000)),
            ..state()
        };
        let result = state.spot_price(&wbtc(), &usdc());
        assert!(matches!(
            result,
            Err(SimulationError::RecoverableError(message)) if message == "No liquidity available"
        ));
    }

    #[test]
    fn get_limits_without_liquidity() {
        let state = PriceLevelStreamState::new(
            wbtc().address,
            usdc().address,
            vec![],
            vec![],
            BigUint::ZERO,
        );
        let (max_in, max_out) = state
            .get_limits(wbtc().address, usdc().address)
            .unwrap();
        assert_eq!(max_in, BigUint::ZERO);
        assert_eq!(max_out, BigUint::ZERO);
    }

    #[test]
    fn eq_compares_quotes() {
        let a = state();
        let mut b = state();
        assert!(a.eq(&b as &dyn ProtocolSim));
        b.quotes_0_to_1[0].amount_out += 1u32;
        assert!(!a.eq(&b as &dyn ProtocolSim));
    }

    #[test]
    fn eq_compares_fills() {
        assert!(!state().eq(&state_after_one_wbtc() as &dyn ProtocolSim));
        assert!(state_after_one_wbtc().eq(&state_after_one_wbtc() as &dyn ProtocolSim));
    }

    #[test]
    fn a_state_serialized_without_a_fill_loads_with_none() {
        let json = serde_json::to_value(state()).unwrap();
        assert!(json
            .as_object()
            .unwrap()
            .get("fill")
            .is_none());
        let loaded: PriceLevelStreamState = serde_json::from_value(json).unwrap();
        assert_eq!(loaded.fill, None);
    }

    #[test]
    fn a_fill_survives_a_serde_round_trip() {
        let json = serde_json::to_value(state_after_one_wbtc()).unwrap();
        let loaded: PriceLevelStreamState = serde_json::from_value(json).unwrap();
        assert_eq!(loaded.fill, state_after_one_wbtc().fill);
    }

    #[rstest]
    #[case::one_nanosecond_before(|until| until - Duration::from_nanos(1), true)]
    #[case::at_quotable_until(|until| until, false)]
    #[case::one_second_after(|until| until + Duration::from_secs(1), false)]
    fn ensure_quotable_around_quotable_until(
        #[case] now: fn(Instant) -> Instant,
        #[case] quotable: bool,
    ) {
        let until = Instant::now() + Duration::from_secs(60);
        let state = state().with_quotable_until(until);
        assert_eq!(
            state
                .ensure_quotable(now(until))
                .is_ok(),
            quotable
        );
    }

    /// Each refusal is counted under its own `reason`, once per refused call.
    #[rstest]
    #[case::price_levels_expired(
        state().with_quotable_until(Instant::now()),
        100_000_000,
        wbtc(),
        "price_levels_expired"
    )]
    #[case::unknown_pair(state(), 1, weth(), "unknown_pair")]
    #[case::no_liquidity(empty_state(), 1, wbtc(), "no_liquidity")]
    #[case::below_smallest_quote(state(), 50_000_000, wbtc(), "below_smallest_quote")]
    #[case::not_monotonic(glitched_state(), 150, wbtc(), "not_monotonic")]
    fn a_refused_quote_is_counted_under_its_reason(
        #[case] state: PriceLevelStreamState,
        #[case] amount_in: u64,
        #[case] token_in: Token,
        #[case] reason: &str,
    ) {
        let (result, snapshot) = record_async(async {
            state.get_amount_out(BigUint::from(amount_in), &token_in, &usdc())
        });

        assert!(result.is_err());
        assert_eq!(
            counter_value(
                &snapshot,
                "price_level_stream_quotes_refused_total",
                &[("reason", reason)]
            ),
            1
        );
    }

    /// `spot_price` counts its own refusal, as `get_amount_out` does.
    #[test]
    fn a_refused_spot_price_is_counted() {
        let (result, snapshot) = record_async(async { empty_state().spot_price(&wbtc(), &usdc()) });

        assert!(result.is_err());
        assert_eq!(
            counter_value(
                &snapshot,
                "price_level_stream_quotes_refused_total",
                &[("reason", "no_liquidity")]
            ),
            1
        );
    }

    #[test]
    fn state_without_quotable_until_never_expires() {
        let far = Instant::now() + Duration::from_secs(1_000_000);
        assert!(state().ensure_quotable(far).is_ok());
    }

    #[test]
    fn expired_state_refuses_every_query() {
        // `quotable_until` is set to `Instant::now()`, which has passed by the time the queries
        // run.
        let state = state().with_quotable_until(Instant::now());
        assert!(matches!(
            state.get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc()),
            Err(SimulationError::RecoverableError(_))
        ));
        assert!(matches!(
            state.spot_price(&wbtc(), &usdc()),
            Err(SimulationError::RecoverableError(_))
        ));
        assert!(matches!(
            state.get_limits(wbtc().address, usdc().address),
            Err(SimulationError::RecoverableError(_))
        ));
    }

    #[test]
    fn fresh_state_answers_every_query() {
        let state = state().with_quotable_until(Instant::now() + Duration::from_secs(60));
        assert!(state
            .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
            .is_ok());
        assert!(state
            .spot_price(&wbtc(), &usdc())
            .is_ok());
        assert!(state
            .get_limits(wbtc().address, usdc().address)
            .is_ok());
    }

    #[test]
    fn successor_state_keeps_quotable_until() {
        let until = Instant::now() + Duration::from_secs(60);
        let state = state().with_quotable_until(until);
        let result = state
            .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
            .expect("fresh state quotes");
        let successor = result
            .new_state
            .as_any()
            .downcast_ref::<PriceLevelStreamState>()
            .expect("price level state");
        assert_eq!(successor.quotable_until, Some(until));
    }

    #[test]
    fn quotable_until_serde_round_trip() {
        let live = state().with_quotable_until(Instant::now());
        let json = serde_json::to_value(&live).unwrap();
        assert!(json
            .as_object()
            .unwrap()
            .get("quotable_until")
            .is_none());
        // A deserialized state has no `quotable_until`, so a recording replays without expiring.
        let replayed: PriceLevelStreamState = serde_json::from_value(json).unwrap();
        assert_eq!(replayed.quotable_until, None);
        assert!(replayed
            .spot_price(&wbtc(), &usdc())
            .is_ok());
    }

    /// Two messages carrying the same quotes yield equal states, whatever their guards.
    #[test]
    fn eq_ignores_quotable_until() {
        let until = Instant::now() + Duration::from_secs(60);
        assert!(state().eq(&state().with_quotable_until(until)));
        assert!(state()
            .with_quotable_until(until)
            .eq(&state().with_quotable_until(until + Duration::from_secs(1))));
    }

    #[test]
    fn with_simulation_overrides_sets_and_exposes_them() {
        assert_eq!(state().simulation_overrides(), None);
        assert_eq!(
            state()
                .with_simulation_overrides(test_overrides())
                .simulation_overrides(),
            Some(&test_overrides())
        );
    }

    /// `eq` compares the block and the overridden account addresses of the simulation overrides,
    /// not the overridden values: see `eq`'s own documentation.
    #[rstest]
    #[case::the_same_overrides(Some(test_overrides()), true)]
    #[case::no_overrides(None, false)]
    #[case::rebuilt_with_other_values(Some(rebuilt_with_other_values()), true)]
    #[case::another_block(Some(in_another_block()), false)]
    #[case::fewer_accounts(Some(with_one_account_fewer()), false)]
    #[case::another_account(Some(with_another_account()), false)]
    fn eq_compares_the_block_and_the_accounts_not_the_values(
        #[case] other: Option<PammSimulationOverrides>,
        #[case] equal: bool,
    ) {
        let held = state().with_simulation_overrides(test_overrides());
        let other = match other {
            Some(overrides) => state().with_simulation_overrides(overrides),
            None => state(),
        };

        assert_eq!(held.eq(&other), equal);
        assert_eq!(other.eq(&held), equal);
    }

    /// [`test_overrides`] taken later in the same block: every overridden value and the build time
    /// differ, the account addresses and the block do not.
    fn rebuilt_with_other_values() -> PammSimulationOverrides {
        let mut rebuilt = test_overrides();
        rebuilt.built_at_ns += 1;
        for account in rebuilt.accounts.values_mut() {
            account.balance = Some(Bytes::from(vec![0x42]));
            account.nonce = account.nonce.map(|nonce| nonce + 1);
            account.state_diff.clear();
        }
        rebuilt
    }

    /// [`test_overrides`] in the next block.
    fn in_another_block() -> PammSimulationOverrides {
        PammSimulationOverrides { block_number: Some(26_201_955), ..test_overrides() }
    }

    /// [`test_overrides`] with as many accounts, one of them under another address, as when a merge
    /// swaps one quote address's entry for another's.
    fn with_another_account() -> PammSimulationOverrides {
        let mut swapped = test_overrides();
        let (_, account) = swapped
            .accounts
            .pop_first()
            .expect("an account");
        swapped
            .accounts
            .insert(Bytes::from(vec![0xab; 20]), account);
        swapped
    }

    /// [`test_overrides`] without its first account, as when a merge loses another quote
    /// address's entry.
    fn with_one_account_fewer() -> PammSimulationOverrides {
        let mut fewer = test_overrides();
        fewer.accounts.pop_first();
        fewer
    }

    /// The successor still carries the state the fill was priced on.
    #[test]
    fn successor_state_keeps_the_overrides() {
        let state = state().with_simulation_overrides(test_overrides());
        let result = state
            .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
            .expect("fresh state quotes");
        let successor = result
            .new_state
            .as_any()
            .downcast_ref::<PriceLevelStreamState>()
            .expect("price level state");
        assert_eq!(successor.simulation_overrides(), Some(&test_overrides()));
    }

    /// A state built from captured quotes and carrying captured overrides survives both
    /// serde_json shapes. Nothing in the overrides is wider than `u64`, because a
    /// `serde_json::Value` cannot hold a wider integer.
    #[test]
    fn an_override_bearing_captured_state_round_trips_as_text_and_as_a_value() {
        let state = captured_state().with_simulation_overrides(test_overrides());

        let text = serde_json::to_string(&state).expect("serializes");
        let value = serde_json::to_value(&state).expect("serializes into a Value");
        let from_text: PriceLevelStreamState =
            serde_json::from_str(&text).expect("reads back from text");
        let from_value: PriceLevelStreamState =
            serde_json::from_value(value).expect("reads back from a Value");

        for read in [&from_text, &from_value] {
            assert_eq!(read.simulation_overrides(), Some(&test_overrides()));
            assert!(state.eq(read));
        }
    }

    /// The same state through a boxed `dyn ProtocolSim`, in both orders typetag's adjacent tag
    /// can arrive in. The order decides the path: with the tag first typetag streams the state
    /// straight into its deserializer, while with the content first it buffers the whole state
    /// into its own `Content` enum and replays it — and that buffer, like a `serde_json::Value`,
    /// holds no integer wider than `u64`.
    #[rstest]
    #[case::tag_before_content(tag_first)]
    #[case::content_before_tag(content_first)]
    fn an_override_bearing_captured_state_round_trips_through_a_boxed_protocol_sim(
        #[case] recording: fn(&str, &str) -> String,
    ) {
        let state = captured_state().with_simulation_overrides(test_overrides());
        let text = recording(TAG, &serde_json::to_string(&state).expect("serializes"));

        let boxed: Box<dyn ProtocolSim> = serde_json::from_str(&text).expect("reads back");

        assert!(state.eq(boxed.as_ref()));
        let read = boxed
            .as_any()
            .downcast_ref::<PriceLevelStreamState>()
            .expect("price level state");
        assert_eq!(read.simulation_overrides(), Some(&test_overrides()));
    }

    /// The tag the recordings in these tests carry is the one typetag itself writes.
    #[test]
    fn typetag_writes_the_tag_the_recordings_carry() {
        let text = serde_json::to_string(&state() as &dyn ProtocolSim).expect("serializes");

        assert!(text.starts_with(&format!(r#"{{"protocol":{TAG},"#)), "{text}");
    }

    /// The state serializes its overrides under the top-level key `overrides`, in the typed form
    /// and inside typetag's `state` content alike.
    ///
    /// A rename would break every recording without an error: the old key would be ignored as an
    /// unknown field and the state would read back without overrides, as recordings made before
    /// the field do (see `a_legacy_typed_recording_reads_back_without_overrides`). So this test
    /// pins the name.
    #[test]
    fn the_serialized_overrides_key_is_named_overrides() {
        let state = captured_state().with_simulation_overrides(test_overrides());

        let text = serde_json::to_string(&state).expect("serializes");
        let typed = serde_json::to_value(&state).expect("serializes");
        let boxed = serde_json::to_value(&state as &dyn ProtocolSim).expect("serializes");

        assert!(text.contains(r#""overrides":"#), "no `overrides` key in the state JSON");
        for json in [&typed, &boxed["state"]] {
            let overrides = json
                .as_object()
                .expect("an object")
                .get("overrides")
                .expect("the state object names them `overrides`");
            let read: PammSimulationOverrides =
                serde_json::from_value(overrides.clone()).expect("the overrides under that key");
            assert_eq!(read, test_overrides());
        }
    }

    /// A recording made before the field existed reads back as a state without overrides, rather
    /// than failing on the missing key.
    #[test]
    fn a_legacy_typed_recording_reads_back_without_overrides() {
        let read: PriceLevelStreamState = serde_json::from_str(LEGACY_STATE).expect("reads back");
        assert_eq!(read.simulation_overrides(), None);
        assert_eq!(read.quotes_0_to_1, vec![quote(100_000_000, 100_000_000_000)]);
        assert_eq!(read.quotes_1_to_0, vec![quote(100_000_000_000, 99_000_000)]);
    }

    /// The same legacy recording boxed, in both tag orders: the content-first path buffers the
    /// absent key as absent too.
    #[rstest]
    #[case::tag_before_content(tag_first)]
    #[case::content_before_tag(content_first)]
    fn a_legacy_boxed_recording_reads_back_without_overrides(
        #[case] recording: fn(&str, &str) -> String,
    ) {
        let boxed: Box<dyn ProtocolSim> =
            serde_json::from_str(&recording(TAG, LEGACY_STATE)).expect("reads back");
        let read = boxed
            .as_any()
            .downcast_ref::<PriceLevelStreamState>()
            .expect("price level state");
        assert_eq!(read.simulation_overrides(), None);
        assert_eq!(read.quotes_0_to_1, vec![quote(100_000_000, 100_000_000_000)]);
    }

    /// A state without overrides writes the legacy shape, so a consumer built before the field
    /// existed can read a recording made now.
    #[test]
    fn a_state_without_overrides_serializes_without_the_key() {
        let typed = serde_json::to_value(state()).expect("serializes");
        let boxed = serde_json::to_value(&state() as &dyn ProtocolSim).expect("serializes");

        for json in [&typed, &boxed["state"]] {
            assert!(json
                .as_object()
                .expect("an object")
                .get("overrides")
                .is_none());
        }
    }
}