tycho-simulation 0.537.3

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
//! [`CurveState`] — a hybrid Curve pool: pure-Rust quote math (`curve_math::Pool`) over state read
//! from the locally indexed VM storage.
use std::any::Any;

use alloy::primitives::{Address as AlloyAddress, U256};
use num_bigint::{BigUint, ToBigUint};
use serde::{Deserialize, Serialize};
use tracing::{debug, info};
use tycho_common::{
    dto::ProtocolStateDelta,
    models::token::Token,
    simulation::{
        errors::{SimulationError, TransitionError},
        protocol_sim::{
            Balances, GetAmountOutResult, PoolSwap, Price, ProtocolSim, QueryPoolSwapParams,
            SwapConstraint,
        },
    },
    Bytes,
};

use crate::{
    evm::{
        engine_db::{create_engine, SHARED_TYCHO_DB},
        protocol::{
            curve::{
                adapter::{build_pool, CurveVariant},
                math::Pool,
                policy::CurvePolicy,
                swap_to_price::{exchange, swap_to_price, SwapToPriceError},
                vm,
            },
            u256_num::{biguint_to_u256, u256_to_biguint, u256_to_f64},
        },
    },
    utils::decimals_exponent,
};

/// Curve fee denominator (`10^10`); both StableSwap `fee` and CryptoSwap `mid_fee` use it.
const FEE_DENOMINATOR: f64 = 1e10;
/// Representative gas cost of a StableSwap exchange.
const STABLESWAP_GAS: u64 = 150_000;
/// Representative gas cost of a CryptoSwap exchange (heavier math + price oracle update).
const CRYPTOSWAP_GAS: u64 = 350_000;
/// Policy version whose grant pricing [`CurveState::exclusive_view`] models.
const SUPPORTED_POLICY_VERSION: u64 = 1;
/// Gas a grant adds to a CryptoSwap exchange: the grant submission and the policy's fee hook.
const GRANT_GAS: u64 = 176_000;

/// A single Curve pool quoted via `curve_math`.
///
/// `tokens` and `decimals` are ordered to match the pool's coin indices, so a token address maps
/// directly to a `curve_math` coin index. State (`pool`) is rebuilt from the VM on every
/// `delta_transition`.
///
/// StableSwap exchanges update pricing balances net of admin fees and recompute `D` on the
/// next quote. CryptoSwap updates balances only, holding `D` and `price_scale` fixed: re-quoting
/// the same CryptoSwap pool is approximate because execution updates these via `tweak_price`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CurveState {
    /// Pool contract address (the Tycho component id).
    pool_address: Bytes,
    /// Coin addresses in pool index order.
    tokens: Vec<Bytes>,
    /// Coin decimals in pool index order.
    decimals: Vec<u8>,
    /// Resolved math variant.
    variant: CurveVariant,
    /// Constructed math pool used for quoting.
    pool: Pool,
    /// Admin share scaled by 1e10. Absent in old snapshots; legacy StableSwap must refresh.
    #[serde(default)]
    admin_fee: Option<U256>,
    /// The pool's policy contract.
    #[serde(default)]
    policy: CurvePolicy,
    /// How quotes price a swap.
    #[serde(default)]
    pricing: Pricing,
}

/// How a [`CurveState`] prices a swap.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
enum Pricing {
    /// At the pool's own fee.
    #[default]
    Public,
    /// At the policy's `min_fee`, with the gas of the grant, while the policy gives grants.
    /// At the pool's own fee otherwise.
    Exclusive,
}

impl CurveState {
    /// Construct a pool with its admin fee share (scaled by 1e10). Legacy StableSwap requires
    /// `Some(admin_fee)` to quote; NG uses its fixed 50% share and CryptoSwap ignores this field.
    pub fn new(
        pool_address: Bytes,
        tokens: Vec<Bytes>,
        decimals: Vec<u8>,
        variant: CurveVariant,
        pool: Pool,
        admin_fee: Option<U256>,
    ) -> Self {
        Self {
            pool_address,
            tokens,
            decimals,
            variant,
            pool,
            admin_fee,
            policy: CurvePolicy::default(),
            pricing: Pricing::Public,
        }
    }

    /// Sets the pool's policy contract.
    pub(super) fn with_policy(mut self, policy: CurvePolicy) -> Self {
        self.policy = policy;
        self
    }

    /// Returns a copy that quotes swaps with a grant from the pool's policy: at the policy's
    /// `min_fee`, with the gas of the grant. `None` for a StableSwap pool, an unsupported policy
    /// version, a killed policy or a zero `min_fee`. Ignores who signs the grants.
    ///
    /// While a later policy update stops the grants, the copy quotes at the pool's own fee.
    pub fn exclusive_view(&self) -> Option<Self> {
        if !self.can_grant() {
            return None;
        }
        let mut view = Self { pricing: Pricing::Exclusive, ..self.clone() };
        self.apply_grant(&mut view.pool)?;
        Some(view)
    }

    /// Whether quotes price a swap with a grant from the policy.
    pub fn is_exclusive_view(&self) -> bool {
        self.pricing == Pricing::Exclusive && self.can_grant()
    }

    /// Whether the policy gives grants this code can price.
    fn can_grant(&self) -> bool {
        self.policy.version() == U256::from(SUPPORTED_POLICY_VERSION) &&
            !self.policy.is_killed() &&
            !self.policy.min_fee().is_zero()
    }

    /// Sets the fee of every swap on `pool` to the policy's `min_fee`. `None` if the policy gives
    /// no grants or `pool` is a StableSwap pool.
    fn apply_grant(&self, pool: &mut Pool) -> Option<()> {
        if !self.can_grant() {
            return None;
        }
        set_fixed_fee(pool, self.policy.min_fee())
    }

    fn admin_fee(&self) -> Result<U256, SimulationError> {
        if self.variant == CurveVariant::StableSwapNG {
            return Ok(U256::from(5_000_000_000u64));
        }
        self.admin_fee.ok_or_else(|| {
            SimulationError::RecoverableError(format!(
                "Missing Curve admin fee for {}; refresh the pool state",
                self.pool_address
            ))
        })
    }

    fn coin_index(&self, token: &Bytes) -> Result<usize, SimulationError> {
        self.tokens
            .iter()
            .position(|t| t == token)
            .ok_or_else(|| {
                SimulationError::InvalidInput(
                    format!("token {token} is not a coin of curve pool {}", self.pool_address),
                    None,
                )
            })
    }

    fn is_crypto(&self) -> bool {
        matches!(
            self.variant,
            CurveVariant::TwoCryptoV1 |
                CurveVariant::TwoCryptoNG |
                CurveVariant::TwoCryptoStable |
                CurveVariant::TriCryptoV1 |
                CurveVariant::TriCryptoNG
        )
    }

    fn gas_estimate(&self) -> u64 {
        let gas = if self.is_crypto() { CRYPTOSWAP_GAS } else { STABLESWAP_GAS };
        if self.is_exclusive_view() {
            gas + GRANT_GAS
        } else {
            gas
        }
    }

    /// Finds the swap to `target` with the native solver. Returns `None` when the target does not
    /// fit in U256 or the variant has no native solver. Also returns `None`, and logs the reason,
    /// when the solver's math fails.
    fn swap_to_target_price(
        &self,
        token_in: &Token,
        token_out: &Token,
        target: &Price,
        tolerance: f64,
    ) -> Result<Option<PoolSwap>, SimulationError> {
        let i = self.coin_index(&token_in.address)?;
        let j = self.coin_index(&token_out.address)?;
        if target.numerator.bits() > 256 || target.denominator.bits() > 256 {
            return Ok(None);
        }
        let target_num = biguint_to_u256(&target.numerator);
        let target_den = biguint_to_u256(&target.denominator);

        match swap_to_price(
            &self.pool,
            i,
            j,
            target_num,
            target_den,
            tolerance,
            if self.is_crypto() { U256::ZERO } else { self.admin_fee()? },
        ) {
            Ok(dx) => {
                if dx.is_zero() {
                    let swap = PoolSwap::new(BigUint::ZERO, BigUint::ZERO, self.clone_box(), None);
                    return Ok(Some(swap));
                }
                let result = self.get_amount_out(u256_to_biguint(dx), token_in, token_out)?;
                Ok(Some(PoolSwap::new(u256_to_biguint(dx), result.amount, result.new_state, None)))
            }
            Err(SwapToPriceError::TargetAboveSpot) => {
                let spot = self.spot_price(token_in, token_out)?;
                let decimal_adjustment =
                    10f64.powi(decimals_exponent(token_in.decimals, token_out.decimals)?);
                let target =
                    u256_to_f64(target_num)? / u256_to_f64(target_den)? * decimal_adjustment;
                Err(SimulationError::InvalidInput(
                    format!("Target price {target} is above spot price {spot}"),
                    None,
                ))
            }
            Err(SwapToPriceError::TargetBelowLimit) => Err(SimulationError::InvalidInput(
                format!(
                    "Target price below reachable limit for curve pool {pool}",
                    pool = self.pool_address
                ),
                None,
            )),
            Err(err @ SwapToPriceError::InvalidInput(_)) => Err(SimulationError::InvalidInput(
                format!("{err} for curve pool {pool}", pool = self.pool_address),
                None,
            )),
            Err(SwapToPriceError::UnsupportedVariant) => Ok(None),
            Err(err @ SwapToPriceError::MathFailed) => {
                debug!(
                    pool = %self.pool_address,
                    %err,
                    "Curve native swap-to-price failed; using the numerical search"
                );
                Ok(None)
            }
        }
    }
}

/// Sets the fee of every swap on a CryptoSwap pool, in units of 1e-10. `None` for a StableSwap
/// pool.
fn set_fixed_fee(pool: &mut Pool, fee: U256) -> Option<()> {
    match pool {
        Pool::TwoCryptoV1 { mid_fee, out_fee, .. } |
        Pool::TwoCryptoNG { mid_fee, out_fee, .. } |
        Pool::TwoCryptoStable { mid_fee, out_fee, .. } |
        Pool::TriCryptoV1 { mid_fee, out_fee, .. } |
        Pool::TriCryptoNG { mid_fee, out_fee, .. } => {
            *mid_fee = fee;
            *out_fee = fee;
            Some(())
        }
        Pool::StableSwapV0 { .. } |
        Pool::StableSwapV1 { .. } |
        Pool::StableSwapV2 { .. } |
        Pool::StableSwapSTETH { .. } |
        Pool::StableSwapALend { .. } |
        Pool::StableSwapNG { .. } |
        Pool::StableSwapMeta { .. } => None,
    }
}

#[typetag::serde]
impl ProtocolSim for CurveState {
    fn fee(&self) -> f64 {
        let fee = self.pool.fee().or_else(|| {
            self.pool
                .crypto_fees()
                .map(|(mid, _, _)| mid)
        });
        fee.and_then(|f| u256_to_f64(f).ok())
            .map(|f| f / FEE_DENOMINATOR)
            .unwrap_or(0.0)
    }

    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
        let i = self.coin_index(&base.address)?;
        let j = self.coin_index(&quote.address)?;
        let (numerator, denominator) = self
            .pool
            .spot_price(i, j)
            .ok_or_else(|| {
                SimulationError::RecoverableError(format!(
                    "curve spot price unavailable for {}",
                    self.pool_address
                ))
            })?;
        // curve_math returns dy/dx (quote per base) in native token units and fee-inclusive;
        // rescale to human units of quote per 1 base.
        let ratio = u256_to_f64(numerator)? / u256_to_f64(denominator)?;
        let decimal_adjustment = 10f64.powi(decimals_exponent(base.decimals, quote.decimals)?);
        Ok(ratio * decimal_adjustment)
    }

    fn get_amount_out(
        &self,
        amount_in: BigUint,
        token_in: &Token,
        token_out: &Token,
    ) -> Result<GetAmountOutResult, SimulationError> {
        let i = self.coin_index(&token_in.address)?;
        let j = self.coin_index(&token_out.address)?;
        let dx = biguint_to_u256(&amount_in);

        let mut new_pool = self.pool.clone();
        let dy = if self.is_crypto() {
            let dy = self
                .pool
                .get_amount_out(i, j, dx)
                .ok_or_else(|| {
                    SimulationError::RecoverableError(format!(
                        "curve get_amount_out failed for {}",
                        self.pool_address
                    ))
                })?;
            let balances = self.pool.balances();
            // CryptoSwap retains its existing balance-only approximation.
            new_pool
                .set_balance(i, balances[i] + dx)
                .map_err(|e| SimulationError::FatalError(e.to_string()))?;
            new_pool
                .set_balance(j, balances[j].saturating_sub(dy))
                .map_err(|e| SimulationError::FatalError(e.to_string()))?;
            dy
        } else {
            let result = exchange(&self.pool, i, j, dx, self.admin_fee()?).ok_or_else(|| {
                SimulationError::RecoverableError(format!(
                    "curve exchange accounting failed for {}",
                    self.pool_address
                ))
            })?;
            for (index, balance) in result.balances.into_iter().enumerate() {
                new_pool
                    .set_balance(index, balance)
                    .map_err(|e| SimulationError::FatalError(e.to_string()))?;
            }
            result.amount
        };

        let new_state = Self { pool: new_pool, ..self.clone() };
        Ok(GetAmountOutResult::new(
            u256_to_biguint(dy),
            self.gas_estimate()
                .to_biguint()
                .expect("u64 fits in BigUint"),
            Box::new(new_state),
        ))
    }

    fn get_limits(
        &self,
        sell_token: Bytes,
        buy_token: Bytes,
    ) -> Result<(BigUint, BigUint), SimulationError> {
        let i = self.coin_index(&sell_token)?;
        let j = self.coin_index(&buy_token)?;
        let (balance_in, balance_out) = {
            let balances = self.pool.balances();
            (balances[i], balances[j])
        };
        if balance_in.is_zero() || balance_out.is_zero() {
            return Ok((BigUint::ZERO, BigUint::ZERO));
        }
        // Soft limit: cap the input at the pool's own balance of the sell token. Beyond this the
        // solver math becomes unreliable and output approaches the available reserve.
        let max_out_reserve = balance_out.saturating_sub(U256::from(1));
        let max_out = self
            .pool
            .get_amount_out(i, j, balance_in)
            .ok_or_else(|| {
                SimulationError::RecoverableError(format!(
                    "curve get_limits: solver failed at max input for {}",
                    self.pool_address
                ))
            })?
            .min(max_out_reserve);
        Ok((u256_to_biguint(balance_in), u256_to_biguint(max_out)))
    }

    /// When `updated_attributes` carries [`vm::POOL_STATE_ADJUSTED`], the pool is rebuilt from
    /// those readings. Otherwise the view getters are read from the indexed VM storage.
    ///
    /// The attribute exists for pending blocks, whose state never reaches that storage: an
    /// indexer that has already read the pool under the pending block's overrides passes the
    /// readings through instead.
    fn delta_transition(
        &mut self,
        delta: ProtocolStateDelta,
        _tokens: &std::collections::HashMap<Bytes, Token>,
        _balances: &Balances,
    ) -> Result<(), TransitionError> {
        let mut policy = self.policy.clone();
        for (name, value) in &delta.updated_attributes {
            policy
                .update(name, value)
                .map_err(|error| TransitionError::DecodeError(error.to_string()))?;
        }
        for name in &delta.deleted_attributes {
            policy.delete(name);
        }
        let state = match delta
            .updated_attributes
            .get(vm::POOL_STATE_ADJUSTED)
        {
            Some(encoded) => {
                let state = vm::decode_raw_state(encoded)?;
                if state.variant != self.variant {
                    return Err(SimulationError::FatalError(format!(
                        "Variant mismatch: expected {}, got {}",
                        self.variant, state.variant
                    ))
                    .into())
                }
                if state.token_decimals != self.decimals {
                    return Err(SimulationError::FatalError(format!(
                        "Token decimals mismatch: expected {:?}, got {:?}",
                        self.decimals, state.token_decimals
                    ))
                    .into())
                }
                state
            }
            None => {
                let engine = create_engine(SHARED_TYCHO_DB.clone(), false)?;
                let pool_address = AlloyAddress::from_slice(self.pool_address.as_ref());
                vm::read_raw_pool_state(
                    &engine,
                    &pool_address,
                    self.variant,
                    &self.decimals,
                    &Default::default(),
                )?
            }
        };
        let mut pool = build_pool(&state)
            .map_err(|e| SimulationError::FatalError(format!("curve build_pool failed: {e}")))?;
        let was_granted = self.is_exclusive_view();
        self.policy = policy;
        if self.pricing == Pricing::Exclusive {
            let is_granted = self.apply_grant(&mut pool).is_some();
            if is_granted != was_granted {
                info!(
                    pool = %self.pool_address,
                    is_granted,
                    "curve exclusive view changes between grant and public pricing"
                );
            }
        }
        self.pool = pool;
        self.admin_fee = state.admin_fee;
        Ok(())
    }

    /// Answers [`SwapConstraint::PoolTargetPrice`] on StableSwap pools with the native solver,
    /// which ignores `min_amount_in` and `max_amount_in` and returns no `price_points`. All other
    /// cases use the numerical search.
    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
        match params.swap_constraint() {
            SwapConstraint::TradeLimitPrice { .. } => {
                crate::evm::query_pool_swap::query_pool_swap(self, params)
            }
            SwapConstraint::PoolTargetPrice { target, tolerance, .. } => {
                let native = self.swap_to_target_price(
                    params.token_in(),
                    params.token_out(),
                    target,
                    *tolerance,
                )?;
                match native {
                    Some(swap) => Ok(swap),
                    None => 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>()
            .is_some_and(|other| self == other)
    }
}

#[cfg(test)]
mod tests {
    use std::{collections::HashMap, str::FromStr};

    use num_traits::ToPrimitive;
    use rstest::rstest;
    use tycho_common::{
        models::Chain,
        simulation::protocol_sim::{QueryPoolSwapParams, SwapConstraint},
    };

    use super::*;
    use crate::evm::{
        protocol::curve::{
            adapter::RawPoolState,
            policy::{
                POLICY_ATTRIBUTE, POLICY_KILLED_ATTRIBUTE, POLICY_MIN_FEE_ATTRIBUTE,
                POLICY_VERSION_ATTRIBUTE,
            },
            vm::encode_raw_state,
        },
        query_pool_swap::test_helpers::{target_price_params, to_price},
    };

    const VARIANT: CurveVariant = CurveVariant::TriCryptoNG;
    const DECIMALS: [u8; 3] = [6, 8, 18];

    fn u(s: &str) -> U256 {
        s.parse().unwrap()
    }

    /// The TriCryptoNG USDC/WBTC/WETH pool (0x7f86bf…), balances aside.
    fn raw_pool_state(balances: Vec<U256>) -> RawPoolState {
        RawPoolState {
            variant: VARIANT,
            balances,
            token_decimals: DECIMALS.to_vec(),
            amp: u("1707629"),
            mid_fee: Some(u("3000000")),
            out_fee: Some(u("30000000")),
            fee_gamma: Some(u("500000000000000")),
            d: Some(u("7457948167729606869978625")),
            gamma: Some(u("11809167828997")),
            price_scale: Some(vec![u("59372627314351316239076"), u("1565715369034455123313")]),
            ..Default::default()
        }
    }

    fn state(balances: Vec<U256>) -> CurveState {
        let raw_state = raw_pool_state(balances);
        let pool = build_pool(&raw_state).expect("build");
        CurveState::new(
            Bytes::from([7u8; 20]),
            vec![Bytes::from([1u8; 20]), Bytes::from([2u8; 20]), Bytes::from([3u8; 20])],
            DECIMALS.to_vec(),
            VARIANT,
            pool,
            Some(U256::ZERO),
        )
    }

    fn delta(attributes: HashMap<String, Bytes>) -> ProtocolStateDelta {
        ProtocolStateDelta { updated_attributes: attributes, ..Default::default() }
    }

    #[test]
    fn test_delta_transition_rebuilds_from_attribute() {
        let confirmed = vec![u("2466241139205"), u("4200057336"), u("1595469030050811720465")];
        let pending = vec![u("2470000000000"), u("4190000000"), u("1600000000000000000000")];
        let mut curve = state(confirmed.clone());
        let attribute = encode_raw_state(&raw_pool_state(pending.clone())).expect("encode");

        curve
            .delta_transition(
                delta(HashMap::from([(vm::POOL_STATE_ADJUSTED.to_string(), attribute)])),
                &HashMap::new(),
                &Balances::default(),
            )
            .expect("delta transition from attribute failed");

        // The readings must come from the attribute. A VM read would fail here anyway: the
        // shared engine has no block set in this test.
        assert_eq!(
            curve.pool.balances()[..3],
            pending[..],
            "balances must come from the attribute"
        );
        assert_ne!(curve.pool.balances()[..3], confirmed[..]);
    }

    #[test]
    fn test_delta_transition_errors_on_variant_mismatch() {
        let mut curve = state(vec![u("1"), u("2"), u("3")]);
        let mut pending_state = raw_pool_state(curve.pool.balances().to_vec());
        pending_state.variant = CurveVariant::StableSwapMeta;
        let encoded = encode_raw_state(&pending_state).expect("encode");

        let result = curve.delta_transition(
            delta(HashMap::from([(vm::POOL_STATE_ADJUSTED.to_string(), encoded)])),
            &HashMap::new(),
            &Balances::default(),
        );

        assert!(matches!(result, Err(TransitionError::SimulationError(_))), "got {result:?}");
    }

    #[test]
    fn test_delta_transition_errors_on_decimals_mismatch() {
        let mut curve = state(vec![u("1"), u("2"), u("3")]);
        let mut pending_state = raw_pool_state(curve.pool.balances().to_vec());
        pending_state.token_decimals = vec![18, 18, 18];
        let encoded = encode_raw_state(&pending_state).expect("encode");

        let result = curve.delta_transition(
            delta(HashMap::from([(vm::POOL_STATE_ADJUSTED.to_string(), encoded)])),
            &HashMap::new(),
            &Balances::default(),
        );

        assert!(matches!(result, Err(TransitionError::SimulationError(_))), "got {result:?}");
    }

    #[test]
    fn test_delta_transition_rejects_malformed_attribute() {
        let mut curve = state(vec![u("1"), u("2"), u("3")]);

        let result = curve.delta_transition(
            delta(HashMap::from([(
                vm::POOL_STATE_ADJUSTED.to_string(),
                Bytes::from(b"not json".to_vec()),
            )])),
            &HashMap::new(),
            &Balances::default(),
        );

        // Falling back to the indexed VM state would silently price a pending block against
        // confirmed state, so a malformed attribute must fail instead.
        assert!(matches!(result, Err(TransitionError::SimulationError(_))), "got {result:?}");
    }

    fn policy(entries: &[(&str, Vec<u8>)]) -> CurvePolicy {
        let attributes = entries
            .iter()
            .map(|(name, value)| (name.to_string(), Bytes::from(value.clone())))
            .collect();
        CurvePolicy::from_attributes(&attributes).expect("decode policy")
    }

    #[rstest]
    #[case::set(Some(vec![7; 20]), false, Some(vec![7; 20]))]
    #[case::cleared(Some(vec![0; 20]), false, None)]
    #[case::deleted(None, true, None)]
    #[case::absent(None, false, Some(vec![9; 20]))]
    fn test_delta_transition_policy_attribute(
        #[case] updated: Option<Vec<u8>>,
        #[case] deleted: bool,
        #[case] expected: Option<Vec<u8>>,
    ) {
        let balances = vec![u("1"), u("2"), u("3")];
        let mut curve = state(balances.clone()).with_policy(policy(&[
            (POLICY_ATTRIBUTE, vec![9; 20]),
            (POLICY_MIN_FEE_ATTRIBUTE, vec![5]),
        ]));
        let mut attributes = HashMap::from([(
            vm::POOL_STATE_ADJUSTED.to_string(),
            encode_raw_state(&raw_pool_state(balances)).expect("encode"),
        )]);
        if let Some(value) = updated {
            attributes.insert(POLICY_ATTRIBUTE.to_string(), Bytes::from(value));
        }
        let mut delta = delta(attributes);
        if deleted {
            delta
                .deleted_attributes
                .insert(POLICY_ATTRIBUTE.to_string());
        }

        curve
            .delta_transition(delta, &HashMap::new(), &Balances::default())
            .expect("delta transition failed");

        let mut expected_entries = vec![(POLICY_MIN_FEE_ATTRIBUTE, vec![5])];
        if let Some(address) = expected {
            expected_entries.push((POLICY_ATTRIBUTE, address));
        }
        assert_eq!(curve.policy, policy(&expected_entries));
    }

    const WAD: u128 = 1_000_000_000_000_000_000;
    const RATE_6_DEC: u128 = 1_000_000_000_000_000_000_000_000_000_000;

    fn token(index: u8, decimals: u32) -> Token {
        let address =
            Bytes::from_str(&format!("0x00000000000000000000000000000000000000{index:02x}"))
                .expect("valid address");
        Token::new(
            &address,
            &format!("T{index}"),
            decimals,
            0,
            &[Some(10_000)],
            Chain::Ethereum,
            100,
        )
    }

    fn curve_state(pool: Pool, variant: CurveVariant, decimals: Vec<u8>) -> CurveState {
        let tokens: Vec<Bytes> = (0..decimals.len())
            .map(|k| token(u8::try_from(k).unwrap(), decimals[k] as u32).address)
            .collect();
        CurveState::new(
            Bytes::from_str("0x00000000000000000000000000000000000000ff").expect("valid address"),
            tokens,
            decimals,
            variant,
            pool,
            Some(U256::ZERO),
        )
    }

    fn v1_two_coin_state() -> (CurveState, Token, Token) {
        let pool = Pool::StableSwapV1 {
            balances: vec![U256::from(50_000_000u128 * WAD), U256::from(48_000_000u128 * WAD)],
            rates: vec![U256::from(WAD), U256::from(WAD)],
            amp: U256::from(2000u64),
            fee: U256::from(1_000_000u64),
        };
        (curve_state(pool, CurveVariant::StableSwapV1, vec![18, 18]), token(0, 18), token(1, 18))
    }

    fn v1_three_coin_mixed_state() -> (CurveState, Token, Token) {
        // 3pool state at block 24669924: DAI (18 dec) in, USDC (6 dec) out.
        let pool = Pool::StableSwapV1 {
            balances: vec![
                U256::from(63_975_337_809_806_329_031_583_135u128),
                U256::from(61_219_263_170_093u128),
                U256::from(37_832_425_459_809u128),
            ],
            rates: vec![U256::from(WAD), U256::from(RATE_6_DEC), U256::from(RATE_6_DEC)],
            amp: U256::from(4000u64),
            fee: U256::from(1_500_000u64),
        };
        (curve_state(pool, CurveVariant::StableSwapV1, vec![18, 6, 6]), token(0, 18), token(1, 6))
    }

    fn v1_three_coin_mixed_state_reverse() -> (CurveState, Token, Token) {
        let (state, token_out, token_in) = v1_three_coin_mixed_state();
        (state, token_in, token_out)
    }

    fn ng_dynamic_fee_state() -> (CurveState, Token, Token) {
        let pool = Pool::StableSwapNG {
            balances: vec![U256::from(1_500_000u128 * WAD), U256::from(700_000u128 * WAD)],
            rates: vec![U256::from(WAD), U256::from(WAD)],
            amp: U256::from(40_000u64),
            fee: U256::from(4_000_000u64),
            offpeg_fee_multiplier: U256::from(20_000_000_000u64),
        };
        (curve_state(pool, CurveVariant::StableSwapNG, vec![18, 18]), token(0, 18), token(1, 18))
    }

    fn meta_state() -> (CurveState, Token, Token) {
        let pool = Pool::StableSwapMeta {
            balances: vec![U256::from(500_000u128 * WAD), U256::from(480_000u128 * WAD)],
            rates: vec![U256::from(WAD), U256::from(1_030_000_000_000_000_000u128)],
            amp: U256::from(50_000u64),
            fee: U256::from(4_000_000u64),
        };
        (curve_state(pool, CurveVariant::StableSwapMeta, vec![18, 18]), token(0, 18), token(1, 18))
    }

    #[test]
    fn pending_state_preserves_admin_fee_for_exchange() {
        let (mut state, token_in, token_out) = v1_two_coin_state();
        let pool = state.pool.clone();
        #[expect(clippy::unreachable, reason = "v1_two_coin_state builds a StableSwapV1 pool")]
        let Pool::StableSwapV1 { balances, rates: _, amp, fee } = pool
        else {
            unreachable!()
        };
        let raw = RawPoolState {
            variant: CurveVariant::StableSwapV1,
            balances,
            amp,
            fee: Some(fee),
            token_decimals: vec![18, 18],
            admin_fee: Some(U256::from(5_000_000_000u64)),
            ..Default::default()
        };
        state
            .delta_transition(
                delta(HashMap::from([(
                    vm::POOL_STATE_ADJUSTED.into(),
                    encode_raw_state(&raw).unwrap(),
                )])),
                &HashMap::new(),
                &Balances::default(),
            )
            .unwrap();
        assert_eq!(state.admin_fee, raw.admin_fee);
        let mut without_admin = state.clone();
        without_admin.admin_fee = Some(U256::ZERO);
        let amount = BigUint::from(WAD);
        let with_fee = state
            .get_amount_out(amount.clone(), &token_in, &token_out)
            .unwrap();
        let no_fee = without_admin
            .get_amount_out(amount, &token_in, &token_out)
            .unwrap();
        assert_eq!(with_fee.amount, no_fee.amount);
        let balance = |result: &GetAmountOutResult| {
            result
                .new_state
                .as_any()
                .downcast_ref::<CurveState>()
                .unwrap()
                .pool
                .balances()[1]
        };
        assert!(balance(&with_fee) < balance(&no_fee));
    }

    fn granted_policy(min_fee: u64) -> CurvePolicy {
        policy(&[
            (POLICY_VERSION_ATTRIBUTE, vec![1]),
            (POLICY_MIN_FEE_ATTRIBUTE, min_fee.to_be_bytes().to_vec()),
        ])
    }

    #[test]
    fn test_exclusive_view_min_fee() {
        let (state, token_in, token_out) = two_crypto_ng_state();
        let amount_out = |state: &CurveState| {
            state
                .get_amount_out(BigUint::from(10u64).pow(18), &token_in, &token_out)
                .expect("amount out")
        };
        let exclusive = |min_fee: u64| {
            state
                .clone()
                .with_policy(granted_policy(min_fee))
                .exclusive_view()
                .expect("exclusive view")
        };
        let lowest = amount_out(&exclusive(100_000));
        let one_percent = amount_out(&exclusive(100_000_000));

        assert!(lowest.amount > amount_out(&state).amount);
        // Each output is the fee-free output times (1 - fee): 0.99999 and 0.99.
        let scaled_one_percent = &one_percent.amount * 99_999u64;
        let scaled_lowest = &lowest.amount * 99_000u64;
        let difference = if scaled_one_percent > scaled_lowest {
            scaled_one_percent - scaled_lowest
        } else {
            scaled_lowest - scaled_one_percent
        };
        assert!(difference <= BigUint::from(200_000u64), "difference {difference}");
        assert_eq!(one_percent.gas, BigUint::from(CRYPTOSWAP_GAS + GRANT_GAS));
    }

    #[rstest]
    #[case::no_policy(vec![0], vec![0], 100_000)]
    #[case::unknown_version(vec![2], vec![0], 100_000)]
    #[case::killed(vec![1], vec![1], 100_000)]
    #[case::zero_min_fee(vec![1], vec![0], 0)]
    fn test_exclusive_view_without_grants(
        #[case] version: Vec<u8>,
        #[case] killed: Vec<u8>,
        #[case] min_fee: u64,
    ) {
        let (state, _, _) = two_crypto_ng_state();
        let state = state.with_policy(policy(&[
            (POLICY_VERSION_ATTRIBUTE, version),
            (POLICY_KILLED_ATTRIBUTE, killed),
            (POLICY_MIN_FEE_ATTRIBUTE, min_fee.to_be_bytes().to_vec()),
        ]));

        assert!(state.exclusive_view().is_none());
    }

    #[test]
    fn test_exclusive_view_stableswap_pool() {
        let (state, _, _) = v1_two_coin_state();

        assert!(state
            .with_policy(granted_policy(100_000))
            .exclusive_view()
            .is_none());
    }

    /// Applies a delta that sets `name` to `value` on an exclusive view with a 0.001% `min_fee`.
    fn exclusive_view_after_delta(name: &str, value: Vec<u8>) -> CurveState {
        let balances = vec![u("2466241139205"), u("4200057336"), u("1595469030050811720465")];
        let mut view = state(balances.clone())
            .with_policy(granted_policy(100_000))
            .exclusive_view()
            .expect("exclusive view");
        let attributes = HashMap::from([
            (
                vm::POOL_STATE_ADJUSTED.to_string(),
                encode_raw_state(&raw_pool_state(balances)).expect("encode"),
            ),
            (name.to_string(), Bytes::from(value)),
        ]);
        view.delta_transition(delta(attributes), &HashMap::new(), &Balances::default())
            .expect("delta transition failed");
        view
    }

    #[test]
    fn test_exclusive_view_delta_transition_min_fee() {
        let view = exclusive_view_after_delta(
            POLICY_MIN_FEE_ATTRIBUTE,
            100_000_000u64.to_be_bytes().to_vec(),
        );

        assert!(view.is_exclusive_view());
        assert_eq!(view.fee(), 0.01);
    }

    #[test]
    fn test_exclusive_view_delta_transition_killed() {
        let view = exclusive_view_after_delta(POLICY_KILLED_ATTRIBUTE, vec![1]);

        assert!(!view.is_exclusive_view());
        assert_eq!(view.fee(), 0.0003);
    }

    #[test]
    fn test_exclusive_view_delta_transition_revived() {
        let mut view = exclusive_view_after_delta(POLICY_KILLED_ATTRIBUTE, vec![1]);
        let balances = vec![u("2466241139205"), u("4200057336"), u("1595469030050811720465")];
        let attributes = HashMap::from([
            (
                vm::POOL_STATE_ADJUSTED.to_string(),
                encode_raw_state(&raw_pool_state(balances)).expect("encode"),
            ),
            (POLICY_KILLED_ATTRIBUTE.to_string(), Bytes::from(vec![0])),
        ]);

        view.delta_transition(delta(attributes), &HashMap::new(), &Balances::default())
            .expect("delta transition failed");

        assert!(view.is_exclusive_view());
        assert_eq!(view.fee(), 0.00001);
    }

    #[test]
    fn test_delta_transition_malformed_policy_attribute() {
        let balances = vec![u("1"), u("2"), u("3")];
        let before = policy(&[(POLICY_ATTRIBUTE, vec![9; 20])]);
        let mut curve = state(balances.clone()).with_policy(before.clone());
        let attributes = HashMap::from([
            (
                vm::POOL_STATE_ADJUSTED.to_string(),
                encode_raw_state(&raw_pool_state(balances)).expect("encode"),
            ),
            (POLICY_ATTRIBUTE.to_string(), Bytes::from(vec![7; 19])),
        ]);

        let result =
            curve.delta_transition(delta(attributes), &HashMap::new(), &Balances::default());

        assert!(matches!(result, Err(TransitionError::DecodeError(_))), "got {result:?}");
        assert_eq!(curve.policy, before);
    }

    fn two_crypto_ng_state() -> (CurveState, Token, Token) {
        let wad = U256::from(WAD);
        let pool = Pool::TwoCryptoNG {
            balances: [U256::from(5000u64) * wad, U256::from(5000u64) * wad],
            precisions: [U256::from(1u64), U256::from(1u64)],
            price_scale: wad,
            d: U256::from(10000u64) * wad,
            ann: U256::from(540_000u64) * U256::from(10_000u64),
            gamma: U256::from(11_809_167_828_997u64),
            mid_fee: U256::from(3_000_000u64),
            out_fee: U256::from(30_000_000u64),
            fee_gamma: U256::from(230_000_000_000_000u64),
        };
        (curve_state(pool, CurveVariant::TwoCryptoNG, vec![18, 18]), token(0, 18), token(1, 18))
    }

    const TOLERANCE: f64 = 0.001;

    /// Builds `PoolTargetPrice` params for a target of `spot * multiplier`, and returns the
    /// target as f64.
    fn spot_target_params(
        state: &CurveState,
        token_in: &Token,
        token_out: &Token,
        multiplier: f64,
    ) -> (QueryPoolSwapParams, f64) {
        let spot = state
            .spot_price(token_in, token_out)
            .expect("spot price");
        let target_f64 = spot * multiplier;
        let target = to_price(target_f64, token_in, token_out);
        (target_price_params(token_in, token_out, target, TOLERANCE), target_f64)
    }

    #[rstest]
    #[case::v1_two_coin_shallow(v1_two_coin_state(), 0.9999)]
    #[case::v1_two_coin_mid(v1_two_coin_state(), 0.999)]
    #[case::v1_two_coin_deep(v1_two_coin_state(), 0.99)]
    #[case::v1_mixed_decimals_18_to_6(v1_three_coin_mixed_state(), 0.99)]
    #[case::v1_mixed_decimals_6_to_18(v1_three_coin_mixed_state_reverse(), 0.99)]
    #[case::ng_dynamic_fee(ng_dynamic_fee_state(), 0.99)]
    #[case::ng_dynamic_fee_mid(ng_dynamic_fee_state(), 0.999)]
    #[case::meta_virtual_price(meta_state(), 0.99)]
    #[case::meta_virtual_price_mid(meta_state(), 0.999)]
    fn test_query_pool_swap_native_amounts(
        #[case] setup: (CurveState, Token, Token),
        #[case] multiplier: f64,
    ) {
        let (state, token_in, token_out) = setup;
        let (params, target) = spot_target_params(&state, &token_in, &token_out, multiplier);

        let swap = state
            .query_pool_swap(&params)
            .expect("native query_pool_swap");

        let price = swap
            .new_state()
            .spot_price(&token_in, &token_out)
            .unwrap();
        assert!(price >= target && price <= target * (1.0 + TOLERANCE));
        let executed = state
            .get_amount_out(swap.amount_in().clone(), &token_in, &token_out)
            .unwrap();
        assert_eq!(swap.amount_out(), &executed.amount);
        assert!(ProtocolSim::eq(swap.new_state(), executed.new_state.as_ref()));
    }

    /// The native result must land in the lower half of the tolerance band, and the numerical
    /// result within five times the band.
    #[rstest]
    #[case::v1_two_coin_shallow(v1_two_coin_state(), 0.9999)]
    #[case::v1_two_coin_mid(v1_two_coin_state(), 0.999)]
    #[case::v1_two_coin_deep(v1_two_coin_state(), 0.99)]
    #[case::v1_mixed_decimals_18_to_6(v1_three_coin_mixed_state(), 0.99)]
    #[case::v1_mixed_decimals_6_to_18(v1_three_coin_mixed_state_reverse(), 0.99)]
    #[case::ng_dynamic_fee(ng_dynamic_fee_state(), 0.99)]
    #[case::ng_dynamic_fee_mid(ng_dynamic_fee_state(), 0.999)]
    #[case::meta_virtual_price(meta_state(), 0.99)]
    #[case::meta_virtual_price_mid(meta_state(), 0.999)]
    fn test_query_pool_swap_numerical_comparison(
        #[case] setup: (CurveState, Token, Token),
        #[case] multiplier: f64,
    ) {
        let (state, token_in, token_out) = setup;
        let (params, target_f64) = spot_target_params(&state, &token_in, &token_out, multiplier);

        let native = state
            .query_pool_swap(&params)
            .expect("native query_pool_swap");
        let numerical = crate::evm::query_pool_swap::query_pool_swap(&state, &params)
            .expect("numerical query_pool_swap");

        for (label, swap, band) in
            [("native", &native, TOLERANCE / 2.0), ("numerical", &numerical, 5.0 * TOLERANCE)]
        {
            assert!(swap.amount_in() > &BigUint::ZERO, "{label} amount_in should be > 0");
            let new_spot = swap
                .new_state()
                .spot_price(&token_in, &token_out)
                .expect("post-swap spot");
            let error = (new_spot - target_f64) / target_f64;
            assert!(
                error >= -1e-12,
                "{label} post-swap spot {new_spot} fell below target {target_f64}"
            );
            assert!(
                error <= band,
                "{label} post-swap spot {new_spot} outside band of target {target_f64}: {error}"
            );
        }
    }

    /// CryptoSwap pools delegate to the numerical search. That search rejects every target,
    /// because `get_amount_out` keeps the stored `D` (no `tweak_price` port).
    #[test]
    fn test_crypto_variant_delegates_to_numerical() {
        let (state, token_in, token_out) = two_crypto_ng_state();
        let (params, _) = spot_target_params(&state, &token_in, &token_out, 0.995);

        let result = state.query_pool_swap(&params);
        let Err(SimulationError::InvalidInput(msg, _)) = result else {
            panic!("crypto pools must delegate to the numerical search, got {result:?}");
        };
        assert!(msg.contains("< limit"), "expected the numerical search's limit error, got: {msg}");
    }

    #[test]
    fn test_query_pool_swap_target_wider_than_u256() {
        let (state, token_in, token_out) = v1_two_coin_state();
        let (params, target_f64) = spot_target_params(&state, &token_in, &token_out, 0.999);
        let SwapConstraint::PoolTargetPrice { target, .. } = params.swap_constraint() else {
            panic!("spot_target_params builds a PoolTargetPrice constraint");
        };
        let scale = BigUint::from(1u8) << 256;
        let wide_target = Price::new(&target.numerator * &scale, &target.denominator * &scale);
        let params = target_price_params(&token_in, &token_out, wide_target, TOLERANCE);

        let swap = state
            .query_pool_swap(&params)
            .expect("numerical query_pool_swap");

        assert!(swap.price_points().is_some(), "only the numerical search returns price points");
        let new_spot = swap
            .new_state()
            .spot_price(&token_in, &token_out)
            .expect("post-swap spot");
        let error = (new_spot - target_f64) / target_f64;
        assert!(
            (-1e-12..=5.0 * TOLERANCE).contains(&error),
            "post-swap spot {new_spot} missed {target_f64}"
        );
    }

    #[test]
    fn test_trade_limit_price_delegates_to_numerical() {
        let (state, token_in, token_out) = v1_two_coin_state();
        let spot = state
            .spot_price(&token_in, &token_out)
            .expect("spot price");
        let limit_f64 = spot * 0.999;
        let params = QueryPoolSwapParams::new(
            token_in.clone(),
            token_out.clone(),
            SwapConstraint::TradeLimitPrice {
                limit: to_price(limit_f64, &token_in, &token_out),
                tolerance: TOLERANCE,
                min_amount_in: None,
                max_amount_in: None,
            },
        );

        let swap = state
            .query_pool_swap(&params)
            .expect("trade limit query_pool_swap");
        assert!(swap.amount_in() > &BigUint::ZERO);
        assert!(swap.amount_out() > &BigUint::ZERO);
        let trade_price = swap
            .amount_out()
            .to_f64()
            .expect("failed to convert the output amount to f64") /
            swap.amount_in()
                .to_f64()
                .expect("failed to convert the input amount to f64");
        assert!(trade_price >= limit_f64, "trade price {trade_price} violates limit {limit_f64}");
    }

    #[rstest]
    #[case::above_spot(1.01, "is above spot price")]
    #[case::below_limit(1e-9, "below reachable limit for curve pool")]
    fn test_query_pool_swap_unreachable_target(#[case] multiplier: f64, #[case] expected: &str) {
        let (state, token_in, token_out) = v1_two_coin_state();
        let (params, _) = spot_target_params(&state, &token_in, &token_out, multiplier);

        let result = state.query_pool_swap(&params);
        let Err(SimulationError::InvalidInput(msg, _)) = result else {
            panic!("expected InvalidInput, got {result:?}");
        };
        assert!(msg.contains(expected), "unexpected message: {msg}");
    }

    #[test]
    fn test_query_pool_swap_target_equal_to_spot() {
        let (state, token_in, token_out) = v1_two_coin_state();
        let i = state
            .coin_index(&token_in.address)
            .expect("token_in index");
        let j = state
            .coin_index(&token_out.address)
            .expect("token_out index");
        let (num, den) = state
            .pool
            .spot_price(i, j)
            .expect("pool spot price");
        let target = Price::new(u256_to_biguint(num), u256_to_biguint(den));
        let params = target_price_params(&token_in, &token_out, target, TOLERANCE);

        let swap = state
            .query_pool_swap(&params)
            .expect("query_pool_swap at spot");
        assert_eq!(swap.amount_in(), &BigUint::ZERO);
        assert_eq!(swap.amount_out(), &BigUint::ZERO);
    }
}