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

use alloy::primitives::{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,
            SwapConstraint,
        },
    },
    Bytes,
};

use crate::{
    book::{
        component::PairState,
        sim::{self, SwapDirection},
    },
    evm::{
        protocol::{
            safe_math::{safe_add_u256, safe_mul_u256, safe_sub_u256},
            u256_num::{biguint_to_uint, u256_to_biguint, u256_to_f64},
        },
        query_pool_swap::{calculate_trade_price, price_to_f64_with_decimals},
    },
    pamm::protocols::hanji::market::FillGas,
};

/// The denominator of Hanji's commission rates: `getConfig()` reports them per 1e18 of the
/// executed value.
const RATE_DENOMINATOR: u64 = 1_000_000_000_000_000_000;

/// One price level of a Hanji book, in the market's scaled units.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(super) struct Level {
    /// Token Y units per share.
    pub price: U256,
    /// Shares of token X resting at the price.
    pub shares: U256,
}

/// One Hanji market as one of its quoters reported it at one block: both sides of the book the
/// proxy fills the feed's taker against, the market's scaling and its taker rate.
///
/// Prices exact-input swaps wei for wei as the proxy orderbook fills them at that block (see the
/// module docs for the rules), including the input left unused below one share or one share's
/// cost, which the quote does not count as spent and which stays with the caller. Every state,
/// deserialized ones included, passes the state's validation checks, and its arithmetic
/// is checked, so a book no contract would report fails its quotes instead of wrapping.
#[derive(Clone, derive_more::Debug, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "UncheckedHanjiState")]
pub struct HanjiState {
    /// The proxy orderbook the market is quoted and traded through.
    pub(super) orderbook: Address,
    /// Token X, or the native token where X is.
    pub(super) base_token: Token,
    /// Token Y, or the native token where Y is.
    pub(super) quote_token: Token,
    /// Atoms of token X per share.
    pub(super) scaling_x: U256,
    /// Atoms of token Y per unit of price and value.
    pub(super) scaling_y: U256,
    /// The taker's fee per 1e18 of the executed value: `totalAggressiveCommissionRate` plus
    /// `passiveOrderPayoutRate`.
    pub(super) fee_rate: u64,
    /// The proxy's gas for a fill: the market's measured figures.
    pub(super) gas: FillGas,
    /// Best (lowest price) first.
    #[debug("{} levels", asks.len())]
    pub(super) asks: Vec<Level>,
    /// Best (highest price) first.
    #[debug("{} levels", bids.len())]
    pub(super) bids: Vec<Level>,
}

/// A [`HanjiState`] as serialized, before [`HanjiState::validated`] checks it.
#[derive(Deserialize)]
struct UncheckedHanjiState {
    orderbook: Address,
    base_token: Token,
    quote_token: Token,
    scaling_x: U256,
    scaling_y: U256,
    fee_rate: u64,
    gas: FillGas,
    asks: Vec<Level>,
    bids: Vec<Level>,
}

impl TryFrom<UncheckedHanjiState> for HanjiState {
    type Error = SimulationError;

    fn try_from(state: UncheckedHanjiState) -> Result<Self, SimulationError> {
        let UncheckedHanjiState {
            orderbook,
            base_token,
            quote_token,
            scaling_x,
            scaling_y,
            fee_rate,
            gas,
            asks,
            bids,
        } = state;
        HanjiState {
            orderbook,
            base_token,
            quote_token,
            scaling_x,
            scaling_y,
            fee_rate,
            gas,
            asks,
            bids,
        }
        .validated()
    }
}

/// What filling one side of the book against an input amounts to.
struct Fill {
    shares: U256,
    value: U256,
    /// Levels the fill touched, the last one possibly in part.
    levels: usize,
}

fn invalid(message: impl Into<String>) -> SimulationError {
    SimulationError::InvalidInput(message.into(), None)
}

/// The refusal of a swap in `direction` when the side it walks holds no level.
fn no_levels(direction: SwapDirection) -> SimulationError {
    invalid(match direction {
        SwapDirection::BaseToQuote => "the book has no bids",
        SwapDirection::QuoteToBase => "the book has no asks",
    })
}

impl HanjiState {
    /// The state, or an error for a market or book the contracts would never report: a zero
    /// scaling factor, a fee of the whole value or more, an empty level, or a side out of price
    /// order.
    pub(super) fn validated(self) -> Result<Self, SimulationError> {
        if self.scaling_x.is_zero() || self.scaling_y.is_zero() {
            return Err(invalid("market has a zero scaling factor"));
        }
        if self.fee_rate >= RATE_DENOMINATOR {
            return Err(invalid(format!("fee rate {} takes the whole value", self.fee_rate)));
        }
        for (name, side) in [("ask", &self.asks), ("bid", &self.bids)] {
            if side
                .iter()
                .any(|level| level.price.is_zero() || level.shares.is_zero())
            {
                return Err(invalid(format!("{name} side holds an empty level")));
            }
        }
        if self
            .asks
            .windows(2)
            .any(|pair| pair[1].price < pair[0].price)
        {
            return Err(invalid("ask side is not ordered lowest price first"));
        }
        if self
            .bids
            .windows(2)
            .any(|pair| pair[1].price > pair[0].price)
        {
            return Err(invalid("bid side is not ordered highest price first"));
        }
        Ok(self)
    }

    fn side(&self, direction: SwapDirection) -> &[Level] {
        match direction {
            SwapDirection::BaseToQuote => &self.bids,
            SwapDirection::QuoteToBase => &self.asks,
        }
    }

    /// The fee on `value`, which the proxy rounds up.
    fn fee_on(&self, value: U256) -> Result<U256, SimulationError> {
        Ok(safe_mul_u256(value, U256::from(self.fee_rate))?.div_ceil(U256::from(RATE_DENOMINATOR)))
    }

    /// `value` plus its fee: what buying shares worth `value` costs.
    fn cost(&self, value: U256) -> Result<U256, SimulationError> {
        safe_add_u256(value, self.fee_on(value)?)
    }

    /// The most value a buy with `target` can pay for, fee included: the largest `v` with
    /// `cost(v) <= target`, which is `floor(target * D / (D + rate))` exactly. `t - v` is an
    /// integer, so `v + ceil(v * rate / D) <= t` holds just when `v * rate / D <= t - v`, that is
    /// when `v * (D + rate) <= t * D`.
    fn affordable_value(&self, target: U256) -> Result<U256, SimulationError> {
        let denominator = U256::from(RATE_DENOMINATOR);
        Ok(safe_mul_u256(target, denominator)? / (denominator + U256::from(self.fee_rate)))
    }

    /// Sells `shares` into the bids, best first; the bids must hold at least that many.
    fn sell(&self, shares: U256) -> Result<Fill, SimulationError> {
        let mut fill = Fill { shares: U256::ZERO, value: U256::ZERO, levels: 0 };
        let mut left = shares;
        for level in &self.bids {
            if left.is_zero() {
                break;
            }
            let take = left.min(level.shares);
            fill.shares += take;
            fill.value = safe_add_u256(fill.value, safe_mul_u256(take, level.price)?)?;
            fill.levels += 1;
            left -= take;
        }
        Ok(fill)
    }

    /// Buys from the asks, best first, the most shares whose value and fee fit in `target`, which
    /// must not exceed what the whole side costs.
    fn buy(&self, target: U256) -> Result<Fill, SimulationError> {
        let budget = self.affordable_value(target)?;
        let mut fill = Fill { shares: U256::ZERO, value: U256::ZERO, levels: 0 };
        for level in &self.asks {
            let take = ((budget - fill.value) / level.price).min(level.shares);
            if take.is_zero() {
                break;
            }
            fill.shares += take;
            fill.value = safe_add_u256(fill.value, safe_mul_u256(take, level.price)?)?;
            fill.levels += 1;
        }
        Ok(fill)
    }

    /// What selling for `value` pays out: the value less its fee, in atoms of token Y.
    fn sale_proceeds(&self, value: U256) -> Result<U256, SimulationError> {
        safe_mul_u256(safe_sub_u256(value, self.fee_on(value)?)?, self.scaling_y)
    }

    /// The input that fills the whole side a swap in `direction` walks, and what it pays out;
    /// zero both ways for a side with no levels or whose whole fill pays out nothing. Every input
    /// up to it of at least one share fills, and none past it.
    fn limits(&self, direction: SwapDirection) -> Result<(U256, U256), SimulationError> {
        self.fill_of(direction, self.side(direction))
    }

    /// The input that fills exactly `levels`, the leading levels of the side a swap in
    /// `direction` walks, and what it pays out; zero both ways when that pays out nothing.
    fn fill_of(
        &self,
        direction: SwapDirection,
        levels: &[Level],
    ) -> Result<(U256, U256), SimulationError> {
        let mut value = U256::ZERO;
        let mut shares = U256::ZERO;
        for level in levels {
            value = safe_add_u256(value, safe_mul_u256(level.price, level.shares)?)?;
            shares = safe_add_u256(shares, level.shares)?;
        }
        let (input, output) = match direction {
            SwapDirection::BaseToQuote => {
                (safe_mul_u256(shares, self.scaling_x)?, self.sale_proceeds(value)?)
            }
            SwapDirection::QuoteToBase => (
                safe_mul_u256(self.cost(value)?, self.scaling_y)?,
                safe_mul_u256(shares, self.scaling_x)?,
            ),
        };
        if output.is_zero() {
            return Ok((U256::ZERO, U256::ZERO));
        }
        Ok((input, output))
    }
}

impl HanjiState {
    /// The rate of a swap in `direction`, selling `token_in` for `token_out`, at `level`: out per
    /// in, decimal adjusted, fee included.
    fn rate_at(
        &self,
        direction: SwapDirection,
        level: &Level,
        token_in: &Token,
        token_out: &Token,
    ) -> Result<f64, SimulationError> {
        // Quote atoms per base atom at the level, before the fee.
        let atomic =
            u256_to_f64(level.price)? * u256_to_f64(self.scaling_y)? / u256_to_f64(self.scaling_x)?;
        let rate = ProtocolSim::fee(self);
        let decimals = 10f64.powf(f64::from(token_in.decimals) - f64::from(token_out.decimals));
        Ok(match direction {
            SwapDirection::BaseToQuote => atomic * decimals * (1.0 - rate),
            SwapDirection::QuoteToBase => decimals / (atomic * (1.0 + rate)),
        })
    }

    /// The largest swap whose rate, out per in, decimal adjusted and fee included, is `limit` or
    /// better; a zero swap when even the smallest fill is worse. The rate falls as a fill walks
    /// the book, so the swap takes whole levels while they clear `limit`, then the most shares of
    /// the next level that still do, found by bisection with the arithmetic `get_amount_out` uses.
    fn trade_limit_swap(
        &self,
        limit: f64,
        token_in: &Token,
        token_out: &Token,
    ) -> Result<PoolSwap, SimulationError> {
        let direction = SwapDirection::require(
            &self.base_token,
            &self.quote_token,
            &token_in.address,
            &token_out.address,
        )?;
        let clears = |levels: &[Level]| -> Result<bool, SimulationError> {
            let (input, output) = self.fill_of(direction, levels)?;
            if input.is_zero() {
                return Ok(false);
            }
            let rate = calculate_trade_price(
                u256_to_f64(input)?,
                u256_to_f64(output)?,
                token_in.decimals,
                token_out.decimals,
            );
            Ok(rate >= limit)
        };
        let side = self.side(direction);
        let mut whole = 0;
        while whole < side.len() && clears(&side[..=whole])? {
            whole += 1;
        }
        let mut levels = side[..whole].to_vec();
        if let Some(next) = side.get(whole) {
            // `low` shares of `next` clear the limit (none trivially), `high` do not.
            let (mut low, mut high) = (U256::ZERO, next.shares);
            while high - low > U256::from(1) {
                let middle = low + (high - low) / U256::from(2);
                let mut probe = levels.clone();
                probe.push(Level { price: next.price, shares: middle });
                if clears(&probe)? {
                    low = middle;
                } else {
                    high = middle;
                }
            }
            if !low.is_zero() {
                levels.push(Level { price: next.price, shares: low });
            }
        }
        self.swap_filling(direction, &levels, token_in, token_out)
    }

    /// The swap that fills exactly `levels` of the side a swap in `direction` walks; a zero swap,
    /// leaving the state as it is, when they pay out nothing.
    fn swap_filling(
        &self,
        direction: SwapDirection,
        levels: &[Level],
        token_in: &Token,
        token_out: &Token,
    ) -> Result<PoolSwap, SimulationError> {
        let (input, _) = self.fill_of(direction, levels)?;
        if input.is_zero() {
            return Ok(PoolSwap::new(BigUint::ZERO, BigUint::ZERO, self.clone_box(), None));
        }
        let amount_in = u256_to_biguint(input);
        let result = self.get_amount_out(amount_in.clone(), token_in, token_out)?;
        Ok(PoolSwap::new(amount_in, result.amount, result.new_state, None))
    }

    /// The swap that walks the book down to `target` (out per in, decimal adjusted): it fills
    /// whole levels, best first, while the level after them is still at `target` or better, so
    /// that the book's marginal rate after it, the next level's, is the closest to `target` from
    /// above that whole levels reach; a zero swap when that is the best level. A target above the
    /// best level, or below the last one, past which the side is empty, is refused. The state it
    /// returns has the walked side emptied, as after any swap (see
    /// [`ProtocolSim::get_amount_out`]).
    fn target_price_swap(
        &self,
        target: f64,
        token_in: &Token,
        token_out: &Token,
    ) -> Result<PoolSwap, SimulationError> {
        let direction = SwapDirection::require(
            &self.base_token,
            &self.quote_token,
            &token_in.address,
            &token_out.address,
        )?;
        let side = self.side(direction);
        let mut rates = Vec::with_capacity(side.len());
        for level in side {
            rates.push(self.rate_at(direction, level, token_in, token_out)?);
        }
        let (Some(best), Some(last)) = (rates.first(), rates.last()) else {
            return Err(no_levels(direction));
        };
        if target > *best {
            return Err(invalid(format!("target {target} is above the best level's {best}")));
        }
        if target < *last {
            return Err(invalid(format!(
                "target {target} is below the last level's {last}, past which the book is empty"
            )));
        }
        // Rates fall level by level and the last one is at `target` or below, so this is the
        // last level at `target` or better: the one the swap stops before.
        let stop = rates
            .iter()
            .rposition(|rate| *rate >= target)
            .unwrap_or(0);
        self.swap_filling(direction, &side[..stop], token_in, token_out)
    }
}

impl PairState for HanjiState {
    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.bids.is_empty(),
            !self.asks.is_empty(),
        )
    }
}

#[typetag::serde]
impl ProtocolSim for HanjiState {
    fn fee(&self) -> f64 {
        self.fee_rate as f64 / RATE_DENOMINATOR as f64
    }

    /// The best level's 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 best = self
            .side(direction)
            .first()
            .ok_or_else(|| no_levels(direction))?;
        self.rate_at(direction, best, base, quote)
    }

    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,
        )?;
        let input = biguint_to_uint(&amount_in)?;
        if self.side(direction).is_empty() {
            return Err(no_levels(direction));
        }
        let (limit, _) = self.limits(direction)?;
        if input > limit {
            return Err(invalid(format!("input {input} exceeds the book's {limit}")));
        }
        let (fill, output) = match direction {
            SwapDirection::BaseToQuote => {
                let shares = input / self.scaling_x;
                if shares.is_zero() {
                    return Err(invalid("input is less than one share of the base token"));
                }
                let fill = self.sell(shares)?;
                let output = self.sale_proceeds(fill.value)?;
                (fill, output)
            }
            SwapDirection::QuoteToBase => {
                let fill = self.buy(input / self.scaling_y)?;
                let output = safe_mul_u256(fill.shares, self.scaling_x)?;
                (fill, output)
            }
        };
        if output.is_zero() {
            return Err(invalid("input buys less than one unit of output"));
        }
        let gas = self.gas.of(fill.levels);
        // The quoter places a new, worse book after every fill, which no state here knows, so the
        // side the swap walked is left empty: a second swap the same way is refused, not
        // over-quoted from the levels the first left (see the module docs).
        let mut next = self.clone();
        match direction {
            SwapDirection::BaseToQuote => next.bids.clear(),
            SwapDirection::QuoteToBase => next.asks.clear(),
        }
        Ok(GetAmountOutResult::new(u256_to_biguint(output), BigUint::from(gas), Box::new(next)))
    }

    /// The input that fills the whole side the swap walks and what it pays out. Zero both ways
    /// for a side with no levels.
    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 (input, output) = self.limits(direction)?;
        Ok((u256_to_biguint(input), u256_to_biguint(output)))
    }

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

    /// Both constraints are closed form over the book: the crate's generic search probes amounts
    /// below one share, which `get_amount_out` refuses, and reads the spot price of states whose
    /// walked side a swap has emptied. `TradeLimitPrice` is the largest swap whose rate clears the
    /// limit; `PoolTargetPrice` fills whole levels while the level after them is still at the
    /// target or better. `min_amount_in` and `max_amount_in` are ignored, as the generic search
    /// ignores them.
    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
        let (token_in, token_out) = (params.token_in(), params.token_out());
        match params.swap_constraint() {
            SwapConstraint::TradeLimitPrice { limit, .. } => {
                let limit =
                    price_to_f64_with_decimals(limit, token_in.decimals, token_out.decimals)?;
                self.trade_limit_swap(limit, token_in, token_out)
            }
            SwapConstraint::PoolTargetPrice { target, .. } => {
                let target =
                    price_to_f64_with_decimals(target, token_in.decimals, token_out.decimals)?;
                self.target_price_swap(target, token_in, token_out)
            }
        }
    }

    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 std::str::FromStr;

    use num_traits::{FromPrimitive, ToPrimitive};
    use rstest::rstest;
    use tycho_common::simulation::protocol_sim::Price;

    use super::*;
    use crate::pamm::protocols::hanji::test_support::{
        cbbtc, eth, fixture, state, usdc, Caller, CBBTC_ETH, CBBTC_USDC, ETH_USDC,
    };

    /// The state's tokens a swap in `direction` sells and buys.
    fn tokens(state: &HanjiState, direction: SwapDirection) -> (Token, Token) {
        match direction {
            SwapDirection::BaseToQuote => (state.base_token.clone(), state.quote_token.clone()),
            SwapDirection::QuoteToBase => (state.quote_token.clone(), state.base_token.clone()),
        }
    }

    fn quote(
        state: &HanjiState,
        amount_in: U256,
        direction: SwapDirection,
    ) -> Result<GetAmountOutResult, SimulationError> {
        let (token_in, token_out) = tokens(state, direction);
        state.get_amount_out(u256_to_biguint(amount_in), &token_in, &token_out)
    }

    fn limits(state: &HanjiState, direction: SwapDirection) -> (U256, U256) {
        let (token_in, token_out) = tokens(state, direction);
        let (input, output) = state
            .get_limits(token_in.address, token_out.address)
            .unwrap();
        (biguint_to_uint(&input).unwrap(), biguint_to_uint(&output).unwrap())
    }

    /// Every recorded fill on the three markets, both directions, for every kind of caller, Tycho's
    /// whitelisted router included, priced wei for wei from the book that caller gets against what
    /// the caller's balance gained; the recorded sizes past a side's depth, which the proxy fills
    /// in part, are refused, and what the proxy paid for them is the limit's output. The shares
    /// the proxy reported filled are the input's whole shares on a sell and the output's on a buy.
    #[test]
    fn test_quotes_match_recorded_fills() {
        let fixture = fixture();
        let (mut priced, mut refused) = (0, 0);
        for orderbook in [ETH_USDC, CBBTC_USDC, CBBTC_ETH] {
            for case in &fixture.market(orderbook).cases {
                let state = state(orderbook, case.caller);
                let amount_in = case.amount_in;
                let (limit, limit_out) = limits(&state, case.direction());
                let result = quote(&state, amount_in, case.direction());
                if amount_in > limit {
                    // The proxy fills such an input only up to its book, which pays out exactly
                    // what the limit says the whole side does.
                    assert!(result.is_err(), "{case:?} is past the book");
                    assert_eq!(limit_out, case.amount_out, "{case:?}");
                    refused += 1;
                    continue;
                }
                let shares = match case.direction() {
                    SwapDirection::BaseToQuote => amount_in / state.scaling_x,
                    SwapDirection::QuoteToBase => case.amount_out / state.scaling_x,
                };
                assert_eq!(shares, case.shares, "{case:?}");
                assert_eq!(
                    biguint_to_uint(&result.unwrap().amount).unwrap(),
                    case.amount_out,
                    "{case:?}"
                );
                priced += 1;
            }
        }
        assert_eq!((priced, refused), (90, 18));
    }

    /// The gas model covers what every recorded fill within the book costs a contract caller,
    /// whitelisted (Tycho's router) or not, once the refund is paid back, and overstates none by
    /// more than a quarter. Each refund is under a fifth of the call's gas, so the 20% of a
    /// transaction's gas that a refund may pay back never caps it.
    #[test]
    fn test_gas_covers_every_recorded_contract_fill() {
        let fixture = fixture();
        let mut checked = 0;
        for orderbook in [ETH_USDC, CBBTC_USDC, CBBTC_ETH] {
            for case in fixture
                .market(orderbook)
                .cases
                .iter()
                .filter(|case| case.caller != Caller::Direct)
            {
                let state = state(orderbook, case.caller);
                let (limit, _) = limits(&state, case.direction());
                if case.amount_in > limit {
                    continue;
                }
                let result = quote(&state, case.amount_in, case.direction()).unwrap();
                let gas = u64::try_from(result.gas).unwrap();
                assert!((case.gas - case.net_gas) * 5 < case.gas, "{case:?}: refund over a fifth");
                assert!(gas >= case.net_gas, "{case:?}: modelled {gas}");
                assert!(gas * 4 <= case.net_gas * 5, "{case:?}: modelled {gas}");
                checked += 1;
            }
        }
        assert_eq!(checked, 60, "the recording's contract fills within the book");
    }

    /// The limit is exactly what get_amount_out fills: the whole side at the limit, and an
    /// error one wei past it.
    #[rstest]
    fn test_limit_is_largest_fillable_input(
        #[values(ETH_USDC, CBBTC_USDC, CBBTC_ETH)] orderbook: Address,
        #[values(SwapDirection::BaseToQuote, SwapDirection::QuoteToBase)] direction: SwapDirection,
    ) {
        let state = state(orderbook, Caller::Contract);
        let (input, output) = limits(&state, direction);

        let at_limit = quote(&state, input, direction).unwrap();
        let past_limit = quote(&state, input + U256::from(1), direction);

        assert_eq!(biguint_to_uint::<256, 4>(&at_limit.amount).unwrap(), output);
        let next = at_limit
            .new_state
            .as_any()
            .downcast_ref::<HanjiState>()
            .unwrap();
        assert!(next.side(direction).is_empty());
        assert!(matches!(past_limit, Err(SimulationError::InvalidInput(..))));
    }

    #[test]
    fn test_input_below_one_share() {
        let state = state(ETH_USDC, Caller::Contract);

        let selling = quote(&state, state.scaling_x - U256::from(1), SwapDirection::BaseToQuote);
        let buying = quote(&state, U256::from(1000), SwapDirection::QuoteToBase);

        assert!(matches!(selling, Err(SimulationError::InvalidInput(..))));
        assert!(matches!(buying, Err(SimulationError::InvalidInput(..))));
    }

    #[test]
    fn test_zero_input_and_foreign_token() {
        let state = state(CBBTC_USDC, Caller::Contract);

        let zero = state.get_amount_out(BigUint::ZERO, &cbbtc(), &usdc());
        let foreign = state.get_amount_out(BigUint::from(1_000_000u64), &eth(), &usdc());

        assert!(matches!(zero, Err(SimulationError::InvalidInput(..))));
        assert!(matches!(foreign, Err(SimulationError::InvalidInput(..))));
    }

    /// A swap that fills part of the bids leaves none in the next state, which then refuses a
    /// second sell, and keeps the asks.
    #[test]
    fn test_swap_empties_walked_side() {
        let state = state(CBBTC_USDC, Caller::Contract);
        let amount = U256::from(10) * state.scaling_x;

        let result = quote(&state, amount, SwapDirection::BaseToQuote).unwrap();
        let next = result
            .new_state
            .as_any()
            .downcast_ref::<HanjiState>()
            .unwrap();

        assert!(next.bids.is_empty());
        assert_eq!(next.asks, state.asks);
        assert!(matches!(
            quote(next, amount, SwapDirection::BaseToQuote),
            Err(SimulationError::InvalidInput(..))
        ));
    }

    /// The fee on a value rounds up, as the proxy charges it: 1 bp of 12,345 is 1.2345, charged
    /// as 2.
    #[test]
    fn test_fee_rounds_up() {
        let state = state(CBBTC_USDC, Caller::Contract);

        assert_eq!(state.fee_rate, 100_000_000_000_000);
        assert_eq!(
            state
                .fee_on(U256::from(12_345))
                .unwrap(),
            U256::from(2)
        );
        assert_eq!(
            state
                .fee_on(U256::from(10_000))
                .unwrap(),
            U256::from(1)
        );
        assert_eq!(state.fee_on(U256::ZERO).unwrap(), U256::ZERO);
    }

    /// Buying spends the most value whose cost fits the target: at 1 bp, 10,000 costs 10,001 and
    /// 10,001 costs 10,003, so a target of 10,002 still buys 10,000.
    #[rstest]
    #[case::one_fee_step_short(10_000, 9_999)]
    #[case::exactly_one_fee_step(10_001, 10_000)]
    #[case::between_fee_steps(10_002, 10_000)]
    #[case::exactly_two_fee_steps(20_002, 20_000)]
    #[case::two_fee_steps_and_one_over(20_004, 20_001)]
    fn test_affordable_value(#[case] target: u64, #[case] value: u64) {
        let state = state(CBBTC_USDC, Caller::Contract);

        let affordable = state
            .affordable_value(U256::from(target))
            .unwrap();

        assert_eq!(affordable, U256::from(value));
        assert!(state.cost(affordable).unwrap() <= U256::from(target));
        assert!(
            state
                .cost(affordable + U256::from(1))
                .unwrap() >
                U256::from(target)
        );
    }

    /// The best bid of ETH/USDC, less the fee, in USDC per ETH, and its inverse on the ask
    /// side in ETH per USDC.
    #[test]
    fn test_spot_price() {
        let state = state(ETH_USDC, Caller::Contract);
        let best_bid = f64::from(u32::try_from(state.bids[0].price).unwrap()) / 100.0;
        let best_ask = f64::from(u32::try_from(state.asks[0].price).unwrap()) / 100.0;

        let selling = state
            .spot_price(&eth(), &usdc())
            .unwrap();
        let buying = state
            .spot_price(&usdc(), &eth())
            .unwrap();

        assert!((selling - best_bid * 0.9999).abs() < 1e-9 * best_bid);
        assert!((buying - 1.0 / (best_ask * 1.0001)).abs() < 1e-12);
    }

    #[test]
    fn test_one_sided_book() {
        let mut state = state(CBBTC_USDC, Caller::Contract);
        state.asks.clear();

        let directions = state.directions();
        let (input, output) = limits(&state, SwapDirection::QuoteToBase);
        let buying = quote(&state, U256::from(1_000_000), SwapDirection::QuoteToBase);

        assert_eq!(directions, vec![(cbbtc().address, usdc().address)]);
        assert_eq!((input, output), (U256::ZERO, U256::ZERO));
        assert!(matches!(buying, Err(SimulationError::InvalidInput(..))));
        assert!(state
            .spot_price(&usdc(), &cbbtc())
            .is_err());
    }

    #[rstest]
    #[case::zero_scaling(|state: &mut HanjiState| state.scaling_x = U256::ZERO)]
    #[case::whole_value_fee(|state: &mut HanjiState| state.fee_rate = RATE_DENOMINATOR)]
    #[case::empty_level(|state: &mut HanjiState| state.bids[1].shares = U256::ZERO)]
    #[case::asks_out_of_order(|state: &mut HanjiState| state.asks.swap(0, 1))]
    #[case::bids_out_of_order(|state: &mut HanjiState| state.bids.swap(0, 1))]
    fn test_malformed_book(#[case] break_it: fn(&mut HanjiState)) {
        let mut state = state(CBBTC_USDC, Caller::Contract);
        break_it(&mut state);

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

    /// Deserializing runs the same checks as building a state, so a recorded state no contract
    /// would report is refused instead of failing later inside a quote.
    #[test]
    fn test_malformed_serialized_state() {
        let mut state = state(CBBTC_ETH, Caller::Contract);
        state.asks[0].price = U256::ZERO;
        let json = serde_json::to_string(&state).unwrap();

        let restored = serde_json::from_str::<HanjiState>(&json);

        assert!(restored.is_err());
    }

    /// A book whose values overflow 256 bits fails its quotes and limits instead of wrapping.
    #[test]
    fn test_overflowing_book() {
        let mut state = state(CBBTC_USDC, Caller::Contract);
        state.scaling_y = U256::MAX;

        let selling = quote(&state, U256::from(1_000_000), SwapDirection::BaseToQuote);
        let limits = state.get_limits(cbbtc().address, usdc().address);

        assert!(selling.is_err());
        assert!(limits.is_err());
    }

    /// A one-share bid at price 1 is worth one unit, all of it fee (the fee rounds up), so selling
    /// into it pays nothing: the side offers no limit, as get_amount_out refuses it.
    #[test]
    fn test_side_worth_only_its_fee() {
        let mut state = state(CBBTC_USDC, Caller::Contract);
        state.bids = vec![Level { price: U256::from(1), shares: U256::from(1) }];

        let (input, output) = limits(&state, SwapDirection::BaseToQuote);
        let selling = quote(&state, state.scaling_x, SwapDirection::BaseToQuote);

        assert_eq!((input, output), (U256::ZERO, U256::ZERO));
        assert!(matches!(selling, Err(SimulationError::InvalidInput(..))));
    }

    /// A `Price` for `rate`, out per in and decimal adjusted, as `query_pool_swap` takes it.
    fn price_of(rate: f64, token_in: &Token, token_out: &Token) -> Price {
        let decimals = f64::from(token_out.decimals) - f64::from(token_in.decimals);
        let numerator = BigUint::from_f64(rate * 10f64.powf(decimals) * 1e30).unwrap();
        Price::new(numerator, BigUint::from(10u8).pow(30))
    }

    fn target_swap(
        state: &HanjiState,
        direction: SwapDirection,
        target: f64,
    ) -> Result<PoolSwap, SimulationError> {
        let (token_in, token_out) = tokens(state, direction);
        let target = price_of(target, &token_in, &token_out);
        let constraint = SwapConstraint::PoolTargetPrice {
            target,
            tolerance: 0.0,
            min_amount_in: None,
            max_amount_in: None,
        };
        state.query_pool_swap(&QueryPoolSwapParams::new(token_in, token_out, constraint))
    }

    /// Each level's rate on the side a swap walks, best first.
    fn rates(state: &HanjiState, direction: SwapDirection) -> Vec<f64> {
        let (token_in, token_out) = tokens(state, direction);
        let mut rates = Vec::new();
        for level in state.side(direction) {
            rates.push(
                state
                    .rate_at(direction, level, &token_in, &token_out)
                    .unwrap(),
            );
        }
        rates
    }

    /// A target between the second and third levels is reached by filling the first level whole:
    /// the book's marginal rate is then the second level's, the closest to the target from above.
    #[rstest]
    fn test_target_price_between_levels(
        #[values(SwapDirection::BaseToQuote, SwapDirection::QuoteToBase)] direction: SwapDirection,
    ) {
        let state = state(ETH_USDC, Caller::Direct);
        let rates = rates(&state, direction);
        assert!(rates.len() >= 3, "{rates:?}");
        let mut first_level_only = state.clone();
        match direction {
            SwapDirection::BaseToQuote => first_level_only.bids.truncate(1),
            SwapDirection::QuoteToBase => first_level_only.asks.truncate(1),
        }
        let (first_level_in, first_level_out) = limits(&first_level_only, direction);

        let swap = target_swap(&state, direction, (rates[1] + rates[2]) / 2.0).unwrap();

        assert_eq!(biguint_to_uint::<256, 4>(swap.amount_in()).unwrap(), first_level_in);
        assert_eq!(biguint_to_uint::<256, 4>(swap.amount_out()).unwrap(), first_level_out);
        let (token_in, token_out) = tokens(&state, direction);
        assert!(swap
            .new_state()
            .spot_price(&token_in, &token_out)
            .is_err());
    }

    /// A target the second level is already below cannot be reached without passing it, so the
    /// swap is empty and leaves the book as it is.
    #[rstest]
    fn test_target_price_above_second_level(
        #[values(SwapDirection::BaseToQuote, SwapDirection::QuoteToBase)] direction: SwapDirection,
    ) {
        let state = state(ETH_USDC, Caller::Direct);
        let rates = rates(&state, direction);

        let swap = target_swap(&state, direction, (rates[0] + rates[1]) / 2.0).unwrap();

        assert_eq!(swap.amount_in(), &BigUint::ZERO);
        assert!(swap.new_state().eq(&state));
    }

    #[rstest]
    #[case::above_the_best_level(|rates: &[f64]| rates[0] * 1.001)]
    #[case::below_the_last_level(|rates: &[f64]| rates[rates.len() - 1] * 0.999)]
    fn test_target_price_unreachable(
        #[values(SwapDirection::BaseToQuote, SwapDirection::QuoteToBase)] direction: SwapDirection,
        #[case] target: fn(&[f64]) -> f64,
    ) {
        let state = state(ETH_USDC, Caller::Direct);
        let target = target(&rates(&state, direction));

        let swap = target_swap(&state, direction, target);

        assert!(matches!(swap, Err(SimulationError::InvalidInput(..))), "{swap:?}");
    }

    fn trade_limit_swap(
        state: &HanjiState,
        direction: SwapDirection,
        limit: f64,
    ) -> Result<PoolSwap, SimulationError> {
        let (token_in, token_out) = tokens(state, direction);
        let constraint = SwapConstraint::TradeLimitPrice {
            limit: price_of(limit, &token_in, &token_out),
            tolerance: 0.0,
            min_amount_in: None,
            max_amount_in: None,
        };
        state.query_pool_swap(&QueryPoolSwapParams::new(token_in, token_out, constraint))
    }

    /// A limit at the last level's rate is cleared by the whole side, whose average rate is
    /// above it, so the answer is the whole side.
    #[rstest]
    fn test_trade_limit_cleared_by_whole_side(
        #[values(SwapDirection::BaseToQuote, SwapDirection::QuoteToBase)] direction: SwapDirection,
    ) {
        let state = state(ETH_USDC, Caller::Direct);
        let rates = rates(&state, direction);

        let swap = trade_limit_swap(&state, direction, rates[rates.len() - 1]).unwrap();

        let (limit_in, limit_out) = limits(&state, direction);
        assert_eq!(biguint_to_uint::<256, 4>(swap.amount_in()).unwrap(), limit_in);
        assert_eq!(biguint_to_uint::<256, 4>(swap.amount_out()).unwrap(), limit_out);
    }

    /// A limit inside the book is searched for, and the trade found clears it: the search prices
    /// its probes by their trades, not by the emptied state each swap leaves.
    #[rstest]
    fn test_trade_limit_inside_book(
        #[values(SwapDirection::BaseToQuote, SwapDirection::QuoteToBase)] direction: SwapDirection,
    ) {
        let state = state(ETH_USDC, Caller::Direct);
        let rates = rates(&state, direction);
        let limit = rates[1];

        let swap = trade_limit_swap(&state, direction, limit).unwrap();

        let (token_in, token_out) = tokens(&state, direction);
        let (limit_in, _) = limits(&state, direction);
        let amount_in = biguint_to_uint::<256, 4>(swap.amount_in()).unwrap();
        assert!(amount_in > U256::ZERO && amount_in < limit_in, "{amount_in}");
        let price = calculate_trade_price(
            swap.amount_in().to_f64().unwrap(),
            swap.amount_out().to_f64().unwrap(),
            token_in.decimals,
            token_out.decimals,
        );
        assert!(price >= limit, "{price} < {limit}");
        // The input that fills one share more no longer clears the limit.
        let shares = match direction {
            SwapDirection::BaseToQuote => amount_in / state.scaling_x,
            SwapDirection::QuoteToBase => {
                biguint_to_uint::<256, 4>(swap.amount_out()).unwrap() / state.scaling_x
            }
        };
        let (more_in, more_out) = fill_of_shares(&state, direction, shares + U256::from(1));
        let more_price = calculate_trade_price(
            u256_to_f64(more_in).unwrap(),
            u256_to_f64(more_out).unwrap(),
            token_in.decimals,
            token_out.decimals,
        );
        assert!(more_price < limit, "{more_price} >= {limit}");
    }

    /// What filling the first `shares` shares of the side a swap walks takes in and pays out.
    fn fill_of_shares(state: &HanjiState, direction: SwapDirection, shares: U256) -> (U256, U256) {
        let mut levels = Vec::new();
        let mut left = shares;
        for level in state.side(direction) {
            let take = left.min(level.shares);
            if take.is_zero() {
                break;
            }
            levels.push(Level { price: level.price, shares: take });
            left -= take;
        }
        state
            .fill_of(direction, &levels)
            .unwrap()
    }

    #[test]
    fn test_state_serialization_roundtrip() {
        let state = state(CBBTC_ETH, Caller::Contract);

        let json = serde_json::to_string(&state).unwrap();
        let restored: HanjiState = serde_json::from_str(&json).unwrap();

        assert_eq!(restored, state);
        assert_eq!(ProtocolSim::fee(&restored), f64::from_str("0.0001").unwrap());
    }
}