tycho-simulation 0.527.4

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
use std::{any::Any, collections::HashMap};

use alloy::primitives::{address, Address, U256};
use num_bigint::BigUint;
use serde::{Deserialize, Serialize};
use tycho_common::{
    dto::ProtocolStateDelta,
    models::token::Token,
    simulation::{
        errors::{SimulationError, TransitionError},
        protocol_sim::{Balances, GetAmountOutResult, PoolSwap, ProtocolSim, QueryPoolSwapParams},
    },
    Bytes,
};

use crate::{
    book::{
        component::PairState,
        sim::{self, SwapDirection},
    },
    evm::protocol::{
        u256_num::{biguint_to_u256, u256_to_biguint},
        utils::solidity_math::mul_div,
    },
    pamm::protocols::baibai::math::{invalid, Curve, Side},
};

/// Gas of the executor's swap: a base cost, a cost per knot below the side's cursor after the swap
/// (behind its previous fill or passed by this swap), and, buying base, a further cost per knot
/// the swap itself passes. Measured cold on Base forks against WETH's five-knot sides: a base of
/// 110,963 buying and 111,330 selling at block 53,234,728, which the Entrypoint upgrade at
/// 53,492,231 raised by 3,379 both ways, to 114,342 and 114,709; the constant rounds the larger
/// up, with a margin of about 700. Each knot passed adds 1,527 selling and 2,908 buying,
/// unchanged by the upgrade: a knot below the cursor costs 1,550 (1,527 rounded up) and a knot
/// bought through a further 1,360 (2,908 less 1,550, rounded up). Curves with more knots were not
/// available to measure. The router's own transfers and approval are added on top by
/// tycho-execution's gas estimator.
const BASE_SWAP_GAS: u64 = 115_400;
const GAS_PER_KNOT_BELOW_CURSOR: u64 = 1_550;
const GAS_PER_KNOT_BOUGHT_THROUGH: u64 = 1_360;

/// Gas a base token's own transfers inside the swap add over WETH's, selling base then buying it:
/// cbBTC's go through its proxy. Measured at Base block 53,545,000 as the difference between
/// entrypoint swaps of each base within its first segment, +17,079 selling and +15,352 buying,
/// rounded up. A base not listed here, such as one served through
/// [`BaibaiFeedBuilder::bases`](super::BaibaiFeedBuilder::bases), is priced as WETH.
const BASE_TRANSFER_GAS: [(Address, u64, u64); 1] =
    [(address!("cbB7C0000aB88B473b1f5aFd9ef808440eed33Bf"), 17_100, 15_400)];

/// The entrypoint's fee denominator: fees are set in millionths of the gross output.
const FEE_DENOMINATOR: u32 = 1_000_000;

/// One BaiBai pair as the chain held it at one block: the curve's two sides, the custody each
/// payout draws on, and the fee the entrypoint charges the taker the feed was built for.
///
/// Prices exact-input swaps wei for wei as `Entrypoint.quoteFor(base, tokenIn, amountIn, taker)`
/// does at that block, except that it refuses inputs past a bid segment that exactly breaks even,
/// which the contract fills (see `Curve::capacity`). It does not price the entrypoint's priority
/// surcharge, up to 50 bps withheld from a swap sent with a priority fee above 0.002 gwei: see the
/// module docs.
#[derive(Clone, derive_more::Debug, PartialEq, Serialize, Deserialize)]
pub struct BaibaiState {
    pub(super) base_token: Token,
    pub(super) quote_token: Token,
    /// Quote atoms per 10^18 base atoms, before each side's spread.
    pub(super) mid: U256,
    pub(super) q_unit: U256,
    pub(super) c_unit: U256,
    #[debug("{{ filled: {}, {} knots }}", ask.filled, ask.knots.len())]
    pub(super) ask: Side,
    #[debug("{{ filled: {}, {} knots }}", bid.filled, bid.knots.len())]
    pub(super) bid: Side,
    /// What the custodian can pay out, base then quote: its balance less pending withdrawals.
    pub(super) available: [U256; 2],
    pub(super) fee_pips: u32,
}

impl BaibaiState {
    /// Fails for a curve the contract would never store or a fee it would never charge.
    pub(super) fn validated(self) -> Result<Self, SimulationError> {
        if self.mid == U256::ZERO || self.q_unit == U256::ZERO || self.c_unit == U256::ZERO {
            return Err(invalid("curve has no mid price or unit"));
        }
        self.kept_pips()?;
        self.curve(SwapDirection::BaseToQuote)?;
        self.curve(SwapDirection::QuoteToBase)?;
        Ok(self)
    }

    /// The side a swap in `direction` walks: selling base fills the bid, buying it the ask.
    fn curve(&self, direction: SwapDirection) -> Result<Curve, SimulationError> {
        let (side, asks) = match direction {
            SwapDirection::BaseToQuote => (&self.bid, false),
            SwapDirection::QuoteToBase => (&self.ask, true),
        };
        Curve::new(side, self.mid, self.q_unit, self.c_unit, asks)
    }

    /// Indices into `available` of the token a swap in `direction` pays in and the one it pays
    /// out.
    fn custody(direction: SwapDirection) -> (usize, usize) {
        match direction {
            SwapDirection::BaseToQuote => (0, 1),
            SwapDirection::QuoteToBase => (1, 0),
        }
    }

    /// The millionths of the gross output the taker keeps. Fails for a fee of the whole output or
    /// more, which the entrypoint never charges: [`Self::validated`] refuses it, and a
    /// deserialized state, which has not been through it, fails every quote and price for it and
    /// lists no direction.
    fn kept_pips(&self) -> Result<u32, SimulationError> {
        if self.fee_pips >= FEE_DENOMINATOR {
            return Err(invalid(format!("fee of {} pips takes the whole output", self.fee_pips)));
        }
        Ok(FEE_DENOMINATOR - self.fee_pips)
    }

    /// The gross output less the entrypoint's fee, which the contract rounds up.
    fn after_fee(&self, gross: U256) -> Result<U256, SimulationError> {
        let kept = self.kept_pips()?;
        mul_div(gross, U256::from(kept), U256::from(FEE_DENOMINATOR))
    }

    /// The executor's gas for a swap in `direction` that moves the side's cursor to `cursor`.
    fn gas(&self, curve: &Curve, direction: SwapDirection, cursor: U256) -> u64 {
        let below = curve.knots_below(cursor);
        let bought_through = match direction {
            SwapDirection::BaseToQuote => 0,
            SwapDirection::QuoteToBase => below - curve.knots_below(curve.filled),
        };
        let transfers = BASE_TRANSFER_GAS
            .iter()
            .find(|(base, _, _)| self.base_token.address.as_ref() == base.as_slice())
            .map_or(0, |(_, selling, buying)| match direction {
                SwapDirection::BaseToQuote => *selling,
                SwapDirection::QuoteToBase => *buying,
            });
        BASE_SWAP_GAS +
            transfers +
            GAS_PER_KNOT_BELOW_CURSOR * below +
            GAS_PER_KNOT_BOUGHT_THROUGH * bought_through
    }

    fn sells(&self, direction: SwapDirection) -> bool {
        let (_, out) = Self::custody(direction);
        self.kept_pips().is_ok() &&
            self.available[out] > U256::ZERO &&
            self.curve(direction)
                .and_then(|curve| curve.capacity())
                .is_ok_and(|capacity| capacity > U256::ZERO)
    }
}

impl PairState for BaibaiState {
    fn base_token(&self) -> &Token {
        &self.base_token
    }

    fn quote_token(&self) -> &Token {
        &self.quote_token
    }

    fn directions(&self) -> Vec<(Bytes, Bytes)> {
        sim::directions(
            &self.base_token,
            &self.quote_token,
            self.sells(SwapDirection::BaseToQuote),
            self.sells(SwapDirection::QuoteToBase),
        )
    }
}

#[typetag::serde]
impl ProtocolSim for BaibaiState {
    fn fee(&self) -> f64 {
        f64::from(self.fee_pips) / f64::from(FEE_DENOMINATOR)
    }

    /// The marginal rate of selling `base` for `quote`, fee included.
    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
        let direction = SwapDirection::require(
            &self.base_token,
            &self.quote_token,
            &base.address,
            &quote.address,
        )?;
        let (_, out) = Self::custody(direction);
        if self.available[out] == U256::ZERO {
            return Err(invalid("no custody to pay out"));
        }
        let atomic = self
            .curve(direction)?
            .marginal_price()?;
        let decimals = 10f64.powf(f64::from(base.decimals) - f64::from(quote.decimals));
        let kept = f64::from(self.kept_pips()?) / f64::from(FEE_DENOMINATOR);
        Ok(atomic * decimals * kept)
    }

    fn get_amount_out(
        &self,
        amount_in: BigUint,
        token_in: &Token,
        token_out: &Token,
    ) -> Result<GetAmountOutResult, SimulationError> {
        sim::require_positive_amount(&amount_in)?;
        let direction = SwapDirection::require(
            &self.base_token,
            &self.quote_token,
            &token_in.address,
            &token_out.address,
        )?;
        if amount_in.bits() > 256 {
            return Err(invalid("amount exceeds uint256"));
        }
        let input = biguint_to_u256(&amount_in);
        let curve = self.curve(direction)?;
        let (gross, cursor) = curve.quote(input)?;
        let output = self.after_fee(gross)?;
        if output == U256::ZERO {
            return Err(invalid("input below the curve's atomic precision"));
        }
        let (paid_in, paid_out) = Self::custody(direction);
        if output > self.available[paid_out] {
            return Err(invalid(format!(
                "output {output} exceeds the custodian's available {}",
                self.available[paid_out]
            )));
        }
        let mut next = self.clone();
        match direction {
            SwapDirection::BaseToQuote => next.bid.filled = cursor,
            SwapDirection::QuoteToBase => next.ask.filled = cursor,
        }
        next.available[paid_in] = next.available[paid_in].saturating_add(input);
        next.available[paid_out] -= output;
        Ok(GetAmountOutResult::new(
            u256_to_biguint(output),
            BigUint::from(self.gas(&curve, direction, cursor)),
            Box::new(next),
        ))
    }

    /// The largest input the curve fills and custody pays out, and its output. Zero both ways
    /// when nothing can be swapped in that direction.
    fn get_limits(
        &self,
        sell_token: Bytes,
        buy_token: Bytes,
    ) -> Result<(BigUint, BigUint), SimulationError> {
        let direction =
            SwapDirection::require(&self.base_token, &self.quote_token, &sell_token, &buy_token)?;
        let (paid_in, paid_out) = Self::custody(direction);
        let available = self.available[paid_out];
        if available == U256::ZERO {
            return Ok((BigUint::ZERO, BigUint::ZERO));
        }
        let curve = self.curve(direction)?;
        let mut high = curve
            .capacity()?
            .min(U256::MAX - self.available[paid_in]);
        let full_output = self.after_fee(curve.quote(high)?.0)?;
        if full_output == U256::ZERO {
            return Ok((BigUint::ZERO, BigUint::ZERO));
        }
        if self.after_fee(curve.output_bound(high)?)? <= available {
            return Ok((u256_to_biguint(high), u256_to_biguint(full_output)));
        }
        // Custody binds before the curve does: find the largest input whose output it covers.
        let mut low = U256::ZERO;
        while low < high {
            let mid = low + (high - low).div_ceil(U256::from(2));
            if self.after_fee(curve.output_bound(mid)?)? <= available {
                low = mid;
            } else {
                high = mid - U256::from(1);
            }
        }
        let output = self.after_fee(curve.quote(low)?.0)?;
        if output == U256::ZERO {
            return Ok((BigUint::ZERO, BigUint::ZERO));
        }
        Ok((u256_to_biguint(low), u256_to_biguint(output)))
    }

    fn delta_transition(
        &mut self,
        _delta: ProtocolStateDelta,
        _tokens: &HashMap<Bytes, Token>,
        _balances: &Balances,
    ) -> Result<(), TransitionError> {
        Err(TransitionError::DecodeError(
            "BaiBai state is read whole every poll and does not take deltas".into(),
        ))
    }

    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
        crate::evm::query_pool_swap::query_pool_swap(self, params)
    }

    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
    }

    fn eq(&self, other: &dyn ProtocolSim) -> bool {
        other.as_any().downcast_ref::<Self>() == Some(self)
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;
    use crate::pamm::protocols::baibai::{
        math::Knot,
        test_support::{fee_charging_fixture, fixture, fixtures, state, token, weth_state},
        BASE_DEPLOYMENT,
    };

    fn quote() -> Token {
        token(BASE_DEPLOYMENT.quote)
    }

    /// Every recorded `quoteFor` for Tycho's router, both pairs and both directions, at blocks
    /// before and after the router's whitelist and the Entrypoint upgrade, with every cursor at
    /// zero, the ask partly filled and the bid partly filled, priced wei for wei, including the
    /// sizes the entrypoint refused (recorded as zero output).
    #[test]
    fn quotes_match_the_entrypoint_wei_for_wei() {
        let mut priced = 0;
        for fixture in fixtures() {
            for pair in &fixture.pairs {
                let state = state(&fixture, pair);
                for case in &pair.cases {
                    let (token_in, token_out) = if case.sell_base {
                        (state.base_token.clone(), quote())
                    } else {
                        (quote(), state.base_token.clone())
                    };
                    let amount_in = u256_to_biguint(case.amount_in);
                    match state.get_amount_out(amount_in, &token_in, &token_out) {
                        Ok(result) => {
                            assert_eq!(result.amount, u256_to_biguint(case.amount_out), "{case:?}");
                            priced += 1;
                        }
                        Err(error) => {
                            assert_eq!(case.amount_out, U256::ZERO, "{case:?}: {error}")
                        }
                    }
                }
            }
        }
        assert_eq!(priced, 116, "the recordings' fillable cases");
    }

    /// The curve itself, without the fee, matches `CurveBook.quote` at every recorded block.
    #[test]
    fn a_feeless_state_matches_the_curve_book() {
        for fixture in fixtures() {
            for pair in &fixture.pairs {
                let mut state = state(&fixture, pair);
                state.fee_pips = 0;
                for case in pair
                    .cases
                    .iter()
                    .filter(|case| case.curve_out != U256::ZERO)
                {
                    let (token_in, token_out) = if case.sell_base {
                        (state.base_token.clone(), quote())
                    } else {
                        (quote(), state.base_token.clone())
                    };
                    let result = state
                        .get_amount_out(u256_to_biguint(case.amount_in), &token_in, &token_out)
                        .unwrap();
                    assert_eq!(result.amount, u256_to_biguint(case.curve_out), "{case:?}");
                }
            }
        }
    }

    /// The 53,234,728 recording's router fee, 50 millionths, before the whitelist.
    #[test]
    fn the_fee_is_in_millionths_of_the_output() {
        let fixture = fee_charging_fixture();

        assert_eq!(state(&fixture, &fixture.pairs[0]).fee(), 0.00005);
    }

    /// Since the router's whitelist, it is charged nothing: selling 1 WETH at block 53,545,000
    /// fetched exactly what `quoteFor` returned for the router there.
    #[test]
    fn the_router_pays_no_fee_since_its_whitelist() {
        let state = weth_state();

        let result = state
            .get_amount_out(BigUint::from(10u64).pow(18), &state.base_token.clone(), &quote())
            .unwrap();

        assert_eq!(state.fee(), 0.0);
        assert_eq!(result.amount, BigUint::from(2_416_825_836u64));
    }

    #[test]
    fn a_swap_advances_the_cursor_and_moves_custody() {
        let state = weth_state();
        let weth = state.base_token.clone();
        let amount = BigUint::from(10u64).pow(17);

        let result = state
            .get_amount_out(amount.clone(), &weth, &quote())
            .unwrap();

        let next = result
            .new_state
            .as_any()
            .downcast_ref::<BaibaiState>()
            .unwrap();
        assert_eq!(next.bid.filled, U256::from(10u64).pow(U256::from(17)));
        assert_eq!(next.ask.filled, state.ask.filled);
        assert_eq!(
            u256_to_biguint(next.available[0]),
            u256_to_biguint(state.available[0]) + amount
        );
        assert_eq!(
            u256_to_biguint(next.available[1]),
            u256_to_biguint(state.available[1]) - &result.amount
        );
        // The same size again walks further along the bid and pays no more.
        let again = next
            .get_amount_out(BigUint::from(10u64).pow(17), &weth, &quote())
            .unwrap();
        assert!(again.amount <= result.amount);
    }

    /// A swap costs a base amount plus a share per knot it walks past, and more per knot buying
    /// base. The 53,545,000 recording's WETH sides have five knots, the first three at about 0.41,
    /// 1.03 and 3.10 WETH; the fork at 53,234,728 measured 1,527 more gas per knot selling 2 WETH
    /// (two knots) than 0.2 WETH (none), and 2,908 more buying with 1,000 USDC (one knot, just:
    /// it buys 0.4137086 WETH against a knot at 0.4137) than with 500.
    #[rstest]
    #[case::selling_within_the_first_segment(true, 2u64 * 10u64.pow(17), 115_400)]
    #[case::selling_past_two_knots(true, 2u64 * 10u64.pow(18), 118_500)]
    #[case::buying_within_the_first_segment(false, 500_000_000, 115_400)]
    #[case::buying_past_one_knot(false, 1_000_000_000, 118_310)]
    fn gas_grows_with_the_knots_a_swap_passes(
        #[case] sell_base: bool,
        #[case] amount: u64,
        #[case] expected: u64,
    ) {
        let state = weth_state();
        let (token_in, token_out) = if sell_base {
            (state.base_token.clone(), quote())
        } else {
            (quote(), state.base_token.clone())
        };

        let gas = state
            .get_amount_out(BigUint::from(amount), &token_in, &token_out)
            .unwrap()
            .gas;

        assert_eq!(gas, BigUint::from(expected));
    }

    /// cbBTC's own transfers cost more than WETH's, each way, on top of the same curve walk.
    #[rstest]
    #[case::selling(true, 1_000_000, 115_400 + 17_100)]
    #[case::buying(false, 500_000_000, 115_400 + 15_400)]
    fn cbbtc_swaps_add_its_transfer_gas(
        #[case] sell_base: bool,
        #[case] amount: u64,
        #[case] expected: u64,
    ) {
        let fixture = fixture();
        let state = state(&fixture, &fixture.pairs[1]);
        assert_eq!(state.base_token.symbol, "cbBTC");
        let (token_in, token_out) = if sell_base {
            (state.base_token.clone(), quote())
        } else {
            (quote(), state.base_token.clone())
        };

        let gas = state
            .get_amount_out(BigUint::from(amount), &token_in, &token_out)
            .unwrap()
            .gas;

        assert_eq!(gas, BigUint::from(expected));
    }

    /// A knot behind the side's previous fill still costs its share, but no longer the extra a
    /// buy pays for walking through it.
    #[test]
    fn knots_behind_the_cursor_still_cost_gas() {
        let mut state = weth_state();
        state.ask.filled = U256::from(5u64) * U256::from(10u64).pow(U256::from(17));

        let gas = state
            .get_amount_out(BigUint::from(1_000_000u64), &quote(), &state.base_token.clone())
            .unwrap()
            .gas;

        assert_eq!(gas, BigUint::from(115_400u64 + 1_550));
    }

    /// Past a bid segment that loses money the contract reverts; the state refuses the same
    /// inputs, and `get_limits` stops before them.
    #[test]
    fn a_bid_past_its_paying_depth_is_refused() {
        let mut state = weth_state();
        state.bid.knots = vec![Knot { q: 1_000, extra: 0 }, Knot { q: 2_000, extra: 46_000_000 }];
        let weth = state.base_token.clone();

        let (max_in, max_out) = state
            .get_limits(weth.address.clone(), quote().address)
            .unwrap();

        let at_limit = state
            .get_amount_out(max_in.clone(), &weth, &quote())
            .unwrap();
        assert_eq!(at_limit.amount, max_out);
        let error = state
            .get_amount_out(max_in + 1u32, &weth, &quote())
            .unwrap_err();
        assert!(
            error
                .to_string()
                .contains("paying depth"),
            "{error}"
        );
    }

    /// A state deserialized from elsewhere has not been validated. A fee of the whole output or
    /// more fails its quotes and prices alike, and it lists no direction to trade.
    #[rstest]
    #[case::the_whole_output(1_000_000)]
    #[case::more_than_the_output(1_000_001)]
    fn a_fee_of_the_whole_output_trades_nothing(#[case] fee_pips: u32) {
        let mut state = weth_state();
        state.fee_pips = fee_pips;
        let weth = state.base_token.clone();

        let quoted = state
            .get_amount_out(BigUint::from(10u64).pow(16), &weth, &quote())
            .unwrap_err();
        let priced = state
            .spot_price(&weth, &quote())
            .unwrap_err();

        for error in [quoted, priced] {
            assert!(
                error
                    .to_string()
                    .contains("takes the whole output"),
                "{error}"
            );
        }
        assert!(state.directions().is_empty());
        assert!(state.validated().is_err());
    }

    #[test]
    fn output_beyond_custody_is_refused() {
        let mut state = weth_state();
        state.available[1] = U256::from(1_000_000);

        let error = state
            .get_amount_out(BigUint::from(10u64).pow(17), &state.base_token.clone(), &quote())
            .unwrap_err();

        assert!(error.to_string().contains("available"), "{error}");
    }

    #[rstest]
    #[case::zero_amount(0u64, true)]
    #[case::unrelated_tokens(1_000u64, false)]
    fn invalid_requests_are_refused(#[case] amount: u64, #[case] own_tokens: bool) {
        let state = weth_state();
        let token_in = if own_tokens {
            state.base_token.clone()
        } else {
            token(alloy::primitives::Address::repeat_byte(0x11))
        };

        let error = state
            .get_amount_out(BigUint::from(amount), &token_in, &quote())
            .unwrap_err();

        assert!(matches!(error, SimulationError::InvalidInput(..)), "{error}");
    }

    /// The limits are a swap the state fills, and the next atom past a curve-bound limit is not.
    #[rstest]
    #[case::sell_base(true)]
    #[case::buy_base(false)]
    fn the_limits_are_fillable_and_tight(#[case] sell_base: bool) {
        let state = weth_state();
        let (token_in, token_out) = if sell_base {
            (state.base_token.clone(), quote())
        } else {
            (quote(), state.base_token.clone())
        };

        let (max_in, max_out) = state
            .get_limits(token_in.address.clone(), token_out.address.clone())
            .unwrap();

        let at_limit = state
            .get_amount_out(max_in.clone(), &token_in, &token_out)
            .unwrap();
        assert_eq!(at_limit.amount, max_out);
        assert!(state
            .get_amount_out(max_in + 1u32, &token_in, &token_out)
            .is_err());
    }

    /// The base the bid buys before it stops paying, derived from the side's parameters rather
    /// than [`Curve::capacity`]: up to its depth, and short of the first segment past its cursor
    /// whose extra cost takes all the spread-adjusted mid pays for it.
    fn bid_paying_depth(state: &BaibaiState) -> U256 {
        let side = &state.bid;
        let wad = U256::from(10u64).pow(U256::from(18));
        let bps = U256::from(10_000u64);
        let scale = U256::from(u64::try_from(10_000 + i64::from(side.spread_bps)).unwrap());
        let price = state.mid * scale / bps;
        let last_q = side
            .knots
            .last()
            .map_or(U256::ZERO, |knot| U256::from(knot.q) * state.q_unit);
        let depth = last_q * U256::from(side.depth_bps) / bps;
        let mut reach = side.filled;
        let (mut prev_q, mut prev_c) = (U256::ZERO, U256::ZERO);
        for knot in &side.knots {
            let q = U256::from(knot.q) * state.q_unit;
            let c = U256::from(knot.extra) * state.c_unit;
            if q > side.filled && reach < depth {
                if price * (q - prev_q) <= (c - prev_c) * wad {
                    break;
                }
                reach = q.min(depth);
            }
            (prev_q, prev_c) = (q, c);
        }
        reach.saturating_sub(side.filled)
    }

    /// Checks that `state`'s limits in `direction` are a swap it fills at their stated output and
    /// that one atom more is refused with `refusal`, or, when `flat_allowed`, pays no more than
    /// the limit. Returns the limits.
    fn assert_tight_limits(
        state: &BaibaiState,
        direction: SwapDirection,
        refusal: &str,
        flat_allowed: bool,
        context: &str,
    ) -> (BigUint, BigUint) {
        let (token_in, token_out) = match direction {
            SwapDirection::BaseToQuote => (state.base_token.clone(), quote()),
            SwapDirection::QuoteToBase => (quote(), state.base_token.clone()),
        };
        let (max_in, max_out) = state
            .get_limits(token_in.address.clone(), token_out.address.clone())
            .unwrap();
        if max_in == BigUint::ZERO {
            return (max_in, max_out);
        }
        let at_limit = state
            .get_amount_out(max_in.clone(), &token_in, &token_out)
            .unwrap_or_else(|e| panic!("{context}: the limit {max_in} is refused: {e}"));
        assert_eq!(at_limit.amount, max_out, "{context}");
        match state.get_amount_out(max_in.clone() + 1u32, &token_in, &token_out) {
            Err(error) => assert!(error.to_string().contains(refusal), "{context}: {error}"),
            Ok(past) => assert!(
                flat_allowed && past.amount == max_out,
                "{context}: one atom past the limit {max_in} pays {}",
                past.amount
            ),
        }
        (max_in, max_out)
    }

    /// The limits hold beyond a trivial state: on every recorded pair, including partly filled
    /// sides, as recorded and with a fee, a spread or half the depth, in both directions.
    /// - With the custody as recorded, the curve binds: the bid's limit is the depth that still
    ///   pays, derived without [`Curve::capacity`], and one atom past either limit is refused as
    ///   beyond the curve.
    /// - With half the curve's output in custody, custody binds: the limit's output fits it, and
    ///   one atom more is refused as exceeding it or pays no more. The second happens on WETH's
    ///   bid, where many wei buy the same USDC atom and [`Curve::output_bound`], one atom above the
    ///   exact output there, stops the search short of the last such wei.
    #[rstest]
    #[case::as_recorded(|_: &mut BaibaiState| {})]
    #[case::with_a_fee(|s: &mut BaibaiState| s.fee_pips = 1_000)]
    #[case::with_spreads(|s: &mut BaibaiState| {
        s.ask.spread_bps = 25;
        s.bid.spread_bps = -25;
    })]
    #[case::at_half_depth(|s: &mut BaibaiState| {
        s.ask.depth_bps = 5_000;
        s.bid.depth_bps = 5_000;
    })]
    fn the_limits_hold_on_every_recording(#[case] vary: fn(&mut BaibaiState)) {
        let (mut curve_bound, mut custody_bound) = (0, 0);
        for fixture in fixtures() {
            for pair in &fixture.pairs {
                let mut state = state(&fixture, pair);
                vary(&mut state);
                let state = state.validated().unwrap();
                for (direction, beyond_curve) in [
                    (SwapDirection::BaseToQuote, "beyond the bid's paying depth"),
                    (SwapDirection::QuoteToBase, "beyond ask depth"),
                ] {
                    let context = format!("{direction:?} at block {}", fixture.block);
                    let (max_in, max_out) =
                        assert_tight_limits(&state, direction, beyond_curve, false, &context);
                    if direction == SwapDirection::BaseToQuote {
                        assert_eq!(biguint_to_u256(&max_in), bid_paying_depth(&state), "{context}");
                    }
                    if max_out < BigUint::from(2u32) {
                        continue;
                    }
                    curve_bound += 1;

                    let mut short = state.clone();
                    let available = biguint_to_u256(&max_out) / U256::from(2);
                    short.available[BaibaiState::custody(direction).1] = available;
                    let (short_in, short_out) = assert_tight_limits(
                        &short,
                        direction,
                        "exceeds the custodian's",
                        true,
                        &context,
                    );
                    assert!(short_out <= u256_to_biguint(available), "{context}");
                    assert!(short_in < max_in, "{context}");
                    custody_bound += 1;
                }
            }
        }
        assert!(curve_bound > 0, "no limit was bound by the curve");
        assert!(custody_bound > 0, "no limit was bound by custody");
    }

    #[test]
    fn an_empty_custody_trades_neither_way() {
        let mut state = weth_state();
        state.available = [U256::ZERO, U256::ZERO];

        assert!(state.directions().is_empty());
        let limits = state
            .get_limits(state.base_token.address.clone(), quote().address)
            .unwrap();
        assert_eq!(limits, (BigUint::ZERO, BigUint::ZERO));
        assert!(state
            .spot_price(&state.base_token.clone(), &quote())
            .is_err());
    }

    /// Selling base pays the bid, buying it costs the ask: the two spot prices bracket the mid.
    #[test]
    fn spot_prices_bracket_the_mid() {
        let state = weth_state();
        let weth = state.base_token.clone();
        let mid = 2_417.07;

        let bid = state
            .spot_price(&weth, &quote())
            .unwrap();
        let ask = 1.0 /
            state
                .spot_price(&quote(), &weth)
                .unwrap();

        assert!(bid < ask, "bid {bid} ask {ask}");
        assert!((bid - mid).abs() / mid < 0.01, "bid {bid}");
        assert!((ask - mid).abs() / mid < 0.01, "ask {ask}");
    }

    #[rstest]
    #[case::fee_takes_everything(|s: &mut BaibaiState| s.fee_pips = 1_000_000)]
    #[case::no_mid(|s: &mut BaibaiState| s.mid = U256::ZERO)]
    #[case::too_many_knots(|s: &mut BaibaiState| s.ask.knots = (1..=37).map(|i| Knot { q: i, extra: i }).collect())]
    #[case::falling_cost(|s: &mut BaibaiState| s.bid.knots = vec![Knot { q: 1, extra: 5 }, Knot { q: 2, extra: 4 }])]
    #[case::repeated_quantity(|s: &mut BaibaiState| s.bid.knots = vec![Knot { q: 1, extra: 0 }, Knot { q: 1, extra: 1 }])]
    #[case::depth_over_100_percent(|s: &mut BaibaiState| s.ask.depth_bps = 10_001)]
    #[case::spread_of_minus_100_percent(|s: &mut BaibaiState| s.bid.spread_bps = -10_000)]
    #[case::spread_below_minus_100_percent(|s: &mut BaibaiState| s.ask.spread_bps = i16::MIN)]
    fn malformed_states_are_rejected(#[case] corrupt: fn(&mut BaibaiState)) {
        let mut state = weth_state();
        corrupt(&mut state);

        assert!(state.validated().is_err());
    }

    #[test]
    fn a_state_round_trips_through_serde() {
        let state: Box<dyn ProtocolSim> = Box::new(weth_state());

        let json = serde_json::to_string(&state).unwrap();
        let back: Box<dyn ProtocolSim> = serde_json::from_str(&json).unwrap();

        assert!(back.eq(state.as_ref()));
    }
}