Skip to main content

tycho_simulation/evm/protocol/uniswap_v2/
state.rs

1use std::{any::Any, collections::HashMap};
2
3use alloy::primitives::{aliases::U112, U256};
4use num_bigint::BigUint;
5use num_traits::Zero;
6use ruint::UintTryFrom;
7use serde::{Deserialize, Serialize};
8use tycho_common::{
9    dto::ProtocolStateDelta,
10    models::token::Token,
11    simulation::{
12        errors::{SimulationError, TransitionError},
13        protocol_sim::{
14            Balances, GetAmountOutResult, PoolSwap, ProtocolSim, QueryPoolSwapParams,
15            SwapConstraint,
16        },
17    },
18    Bytes,
19};
20
21#[cfg(feature = "proptest")]
22use crate::evm::protocol::checkable::generator::{
23    AnyTokens, AnyUint, Case, Domain, DomainExt, StateCases,
24};
25use crate::evm::protocol::{
26    checkable::{CheckableState, LimitKind},
27    cpmm::protocol::{
28        cpmm_fee, cpmm_get_amount_out, cpmm_spot_price, cpmm_swap_to_price, ProtocolFee,
29    },
30    u256_num::{biguint_to_uint, u256_to_biguint},
31    utils::add_fee_markup,
32};
33
34const SWAP_BASE_GAS: u64 = 90_000;
35const UNISWAP_V2_FEE_BPS: u32 = 30; // 0.3% fee
36const FEE_PRECISION: U256 = U256::from_limbs([10000, 0, 0, 0]);
37const FEE_NUMERATOR: U256 = U256::from_limbs([9970, 0, 0, 0]);
38
39#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
40pub struct UniswapV2State {
41    pub reserve0: U112,
42    pub reserve1: U112,
43}
44
45impl UniswapV2State {
46    /// Creates a new instance of `UniswapV2State` with the given reserves.
47    ///
48    /// # Arguments
49    ///
50    /// * `reserve0` - Reserve of token 0.
51    /// * `reserve1` - Reserve of token 1.
52    pub fn new(reserve0: U112, reserve1: U112) -> Self {
53        UniswapV2State { reserve0, reserve1 }
54    }
55
56    fn reserves(&self, zero_for_one: bool) -> (U112, U112) {
57        if zero_for_one {
58            (self.reserve0, self.reserve1)
59        } else {
60            (self.reserve1, self.reserve0)
61        }
62    }
63}
64
65/// Reads a reserve attribute, refusing one wider than the pair's `uint112`. The package writes
66/// it as `BigInt::to_signed_bytes_be`, which prefixes a zero sign byte to a reserve whose top
67/// bit is set, so leading zeros are skipped.
68pub(super) fn decode_reserve(name: &str, value: &Bytes) -> Result<U112, String> {
69    let magnitude = &value[value
70        .iter()
71        .take_while(|byte| **byte == 0)
72        .count()..];
73    U112::try_from_be_slice(magnitude)
74        .ok_or_else(|| format!("{name} {value} does not fit the pair's uint112 reserve"))
75}
76
77/// What the pair pays for `amount_in`, after its 0.3% fee.
78fn amount_out(
79    amount_in: U256,
80    reserve_in: U256,
81    reserve_out: U256,
82) -> Result<U256, SimulationError> {
83    cpmm_get_amount_out(
84        amount_in,
85        reserve_in,
86        reserve_out,
87        ProtocolFee::new(FEE_NUMERATOR, FEE_PRECISION),
88    )
89}
90
91#[typetag::serde]
92impl ProtocolSim for UniswapV2State {
93    fn fee(&self) -> f64 {
94        cpmm_fee(UNISWAP_V2_FEE_BPS)
95    }
96
97    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
98        let price =
99            cpmm_spot_price(base, quote, U256::from(self.reserve0), U256::from(self.reserve1))?;
100        Ok(add_fee_markup(price, self.fee()))
101    }
102
103    fn get_amount_out(
104        &self,
105        amount_in: BigUint,
106        token_in: &Token,
107        token_out: &Token,
108    ) -> Result<GetAmountOutResult, SimulationError> {
109        let amount_in: U112 = biguint_to_uint(&amount_in)?;
110        let zero2one = token_in.address < token_out.address;
111        let (reserve_in, reserve_out) = self.reserves(zero2one);
112        let new_reserve_in = reserve_in
113            .checked_add(amount_in)
114            .ok_or_else(|| {
115                SimulationError::InvalidInput(
116                    format!(
117                        "Amount in {amount_in} takes reserve {reserve_in} past uint112, where \
118                         the pair reverts"
119                    ),
120                    None,
121                )
122            })?;
123        let amount_out =
124            amount_out(U256::from(amount_in), U256::from(reserve_in), U256::from(reserve_out))?;
125        if amount_out.is_zero() {
126            // The pair's swap requires a non-zero output: 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT'.
127            return Err(SimulationError::InvalidInput(
128                format!("Amount in {amount_in} is too small to buy any output"),
129                None,
130            ));
131        }
132        // The constant-product output is below `reserve_out`, so it fits and the subtraction
133        // cannot underflow.
134        let new_reserve_out = U112::uint_try_from(amount_out)
135            .ok()
136            .and_then(|amount_out| reserve_out.checked_sub(amount_out))
137            .ok_or_else(|| {
138                SimulationError::FatalError(format!(
139                    "Amount out {amount_out} exceeds reserve {reserve_out}"
140                ))
141            })?;
142        let mut new_state = self.clone();
143        if zero2one {
144            new_state.reserve0 = new_reserve_in;
145            new_state.reserve1 = new_reserve_out;
146        } else {
147            new_state.reserve0 = new_reserve_out;
148            new_state.reserve1 = new_reserve_in;
149        };
150        Ok(GetAmountOutResult::new(
151            u256_to_biguint(amount_out),
152            BigUint::from(SWAP_BASE_GAS),
153            Box::new(new_state),
154        ))
155    }
156
157    fn get_limits(
158        &self,
159        sell_token: Bytes,
160        buy_token: Bytes,
161    ) -> Result<(BigUint, BigUint), SimulationError> {
162        // The pair takes any input until the input reserve would pass uint112, so the limit is the
163        // room left below it. A limit that buys no output is zero: output grows with input, so no
164        // smaller amount buys any either.
165        let (reserve_in, reserve_out) = self.reserves(sell_token < buy_token);
166        // FIXME: the pair checks its token balances against uint112, not its reserves, so tokens
167        // sent to it without a `sync` take up part of this room. The state holds only the reserves
168        // (the package indexes `Sync` events), so with such an excess the limit is too high by it,
169        // and `get_amount_out` accepts amounts the pair refuses with `UniswapV2: OVERFLOW`.
170        let room = U112::MAX - reserve_in;
171        if reserve_in.is_zero() || reserve_out.is_zero() || room.is_zero() {
172            return Ok((BigUint::ZERO, BigUint::ZERO));
173        }
174        let room = U256::from(room);
175        let max_out = amount_out(room, U256::from(reserve_in), U256::from(reserve_out))?;
176        if max_out.is_zero() {
177            return Ok((BigUint::ZERO, BigUint::ZERO));
178        }
179        Ok((u256_to_biguint(room), u256_to_biguint(max_out)))
180    }
181
182    fn delta_transition(
183        &mut self,
184        delta: ProtocolStateDelta,
185        _tokens: &HashMap<Bytes, Token>,
186        _balances: &Balances,
187    ) -> Result<(), TransitionError> {
188        // Both reserves are in every delta the package emits.
189        let reserve = |name: &str| {
190            let value = delta
191                .updated_attributes
192                .get(name)
193                .ok_or_else(|| TransitionError::MissingAttribute(name.to_string()))?;
194            decode_reserve(name, value).map_err(TransitionError::DecodeError)
195        };
196        let (reserve0, reserve1) = (reserve("reserve0")?, reserve("reserve1")?);
197        self.reserve0 = reserve0;
198        self.reserve1 = reserve1;
199        Ok(())
200    }
201
202    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
203        match params.swap_constraint() {
204            SwapConstraint::PoolTargetPrice {
205                target: price,
206                tolerance: _,
207                min_amount_in: _,
208                max_amount_in: _,
209            } => {
210                let zero2one = params.token_in().address < params.token_out().address;
211                let (reserve_in, reserve_out) = self.reserves(zero2one);
212                let (reserve_in, reserve_out) = (U256::from(reserve_in), U256::from(reserve_out));
213
214                let fee = ProtocolFee::new(FEE_NUMERATOR, FEE_PRECISION);
215                let (amount_in, _) = cpmm_swap_to_price(reserve_in, reserve_out, price, fee)?;
216                if amount_in.is_zero() {
217                    return Ok(PoolSwap::new(
218                        BigUint::ZERO,
219                        BigUint::ZERO,
220                        Box::new(self.clone()),
221                        None,
222                    ));
223                }
224
225                let res =
226                    self.get_amount_out(amount_in.clone(), params.token_in(), params.token_out())?;
227                Ok(PoolSwap::new(amount_in, res.amount, res.new_state, None))
228            }
229            SwapConstraint::TradeLimitPrice { .. } => Err(SimulationError::InvalidInput(
230                "UniswapV2State does not support TradeLimitPrice constraint in query_pool_swap"
231                    .to_string(),
232                None,
233            )),
234        }
235    }
236
237    fn clone_box(&self) -> Box<dyn ProtocolSim> {
238        Box::new(self.clone())
239    }
240
241    fn as_any(&self) -> &dyn Any {
242        self
243    }
244
245    fn as_any_mut(&mut self) -> &mut dyn Any {
246        self
247    }
248
249    fn eq(&self, other: &dyn ProtocolSim) -> bool {
250        if let Some(other_state) = other.as_any().downcast_ref::<Self>() {
251            let (self_reserve0, self_reserve1) = (self.reserve0, self.reserve1);
252            let (other_reserve0, other_reserve1) = (other_state.reserve0, other_state.reserve1);
253            self_reserve0 == other_reserve0 &&
254                self_reserve1 == other_reserve1 &&
255                self.fee() == other_state.fee()
256        } else {
257            false
258        }
259    }
260}
261
262impl CheckableState for UniswapV2State {
263    /// The limit is the room left below uint112, and one unit more overflows the pair.
264    fn limit_kind(&self, _sell_token: &Bytes, _buy_token: &Bytes) -> LimitKind {
265        LimitKind::Hard
266    }
267
268    /// Always valid: `sync` writes the pair's token balances into its reserves whenever both fit
269    /// `uint112`, and before the first mint anyone can send the pair any amounts and call it.
270    fn check_valid(&self) -> Result<(), String> {
271        Ok(())
272    }
273
274    /// The smallest input that buys any output, and one unit around it, where quoting turns from
275    /// an error into a quote of 1. For an input `a`, reserves `R_in` and `R_out`, and the fee
276    /// `F / P` (`FEE_NUMERATOR / FEE_PRECISION`), the pair pays
277    /// `floor(F a R_out / (P R_in + F a))`. That is at least 1 exactly when
278    /// `F a (R_out - 1) >= P R_in`, so with `R_out <= 1` no input buys any output.
279    fn amounts(&self, sell_token: &Bytes, buy_token: &Bytes) -> Vec<BigUint> {
280        let (reserve_in, reserve_out) = self.reserves(sell_token < buy_token);
281        let (reserve_in, reserve_out) = (U256::from(reserve_in), U256::from(reserve_out));
282        if reserve_out <= U256::ONE {
283            return Vec::new();
284        }
285        // Both products fit a `U256`: the reserves are `uint112`, and `F` and `P` are below `2^14`.
286        let smallest =
287            (reserve_in * FEE_PRECISION).div_ceil((reserve_out - U256::ONE) * FEE_NUMERATOR);
288        let mut amounts = vec![smallest + U256::ONE, smallest];
289        if !smallest.is_zero() {
290            amounts.push(smallest - U256::ONE);
291        }
292        amounts
293            .into_iter()
294            .map(u256_to_biguint)
295            .collect()
296    }
297}
298
299#[cfg(feature = "proptest")]
300impl StateCases for UniswapV2State {
301    type Tokens = [Token; 2];
302
303    /// Reserves anywhere in uint112, either of them possibly 0.
304    fn cases() -> impl Domain<Value = Case<Self, Self::Tokens>> {
305        (AnyUint, AnyUint, AnyTokens).map(|(reserve0, reserve1, tokens)| Case {
306            state: Self::new(reserve0, reserve1),
307            tokens,
308        })
309    }
310}
311
312#[cfg(test)]
313mod tests {
314    use std::{
315        collections::{HashMap, HashSet},
316        str::FromStr,
317    };
318
319    use approx::assert_ulps_eq;
320    use num_bigint::BigUint;
321    use num_traits::One;
322    use rstest::rstest;
323    use tycho_common::{
324        dto::ProtocolStateDelta,
325        hex_bytes::Bytes,
326        models::{token::Token, Chain},
327        simulation::{
328            errors::{SimulationError, TransitionError},
329            protocol_sim::{Balances, Price, ProtocolSim},
330        },
331    };
332
333    use super::*;
334    use crate::evm::protocol::u256_num::biguint_to_uint;
335
336    fn token_0() -> Token {
337        Token::new(
338            &Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
339            "T0",
340            18,
341            0,
342            &[Some(10_000)],
343            Chain::Ethereum,
344            100,
345        )
346    }
347
348    fn token_1() -> Token {
349        Token::new(
350            &Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap(),
351            "T1",
352            18,
353            0,
354            &[Some(10_000)],
355            Chain::Ethereum,
356            100,
357        )
358    }
359
360    #[rstest]
361    #[case::same_dec(
362        U112::from_str("6770398782322527849696614").unwrap(),
363        U112::from_str("5124813135806900540214").unwrap(),
364        18,
365        18,
366    BigUint::from_str("10000000000000000000000").unwrap(),
367    BigUint::from_str("7535635391574243447").unwrap()
368    )]
369    #[case::diff_dec(
370        U112::from_str("33372357002392258830279").unwrap(),
371        U112::from_str("43356945776493").unwrap(),
372        18,
373        6,
374    BigUint::from_str("10000000000000000000").unwrap(),
375    BigUint::from_str("12949029867").unwrap()
376    )]
377    fn test_get_amount_out(
378        #[case] r0: U112,
379        #[case] r1: U112,
380        #[case] token_0_decimals: u32,
381        #[case] token_1_decimals: u32,
382        #[case] amount_in: BigUint,
383        #[case] exp: BigUint,
384    ) {
385        let t0 = Token::new(
386            &Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
387            "T0",
388            token_0_decimals,
389            0,
390            &[Some(10_000)],
391            Chain::Ethereum,
392            100,
393        );
394        let t1 = Token::new(
395            &Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap(),
396            "T0",
397            token_1_decimals,
398            0,
399            &[Some(10_000)],
400            Chain::Ethereum,
401            100,
402        );
403        let state = UniswapV2State::new(r0, r1);
404
405        let res = state
406            .get_amount_out(amount_in.clone(), &t0, &t1)
407            .unwrap();
408
409        assert_eq!(res.amount, exp);
410        let new_state = res
411            .new_state
412            .as_any()
413            .downcast_ref::<UniswapV2State>()
414            .unwrap();
415        assert_eq!(new_state.reserve0, r0 + biguint_to_uint(&amount_in).unwrap());
416        assert_eq!(new_state.reserve1, r1 - biguint_to_uint(&exp).unwrap());
417        // Assert that the old state is unchanged
418        assert_eq!(state.reserve0, r0);
419        assert_eq!(state.reserve1, r1);
420    }
421
422    #[rstest]
423    #[case(true, 0.000823442321727627)] // 0.0008209719947624441 / 0.997
424    #[case(false, 1221.7335469177287)] // 1218.0683462769755 / 0.997
425    fn test_spot_price(#[case] zero_to_one: bool, #[case] exp: f64) {
426        let state = UniswapV2State::new(
427            U112::from_str("36925554990922").unwrap(),
428            U112::from_str("30314846538607556521556").unwrap(),
429        );
430        let usdc = Token::new(
431            &Bytes::from_str("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap(),
432            "USDC",
433            6,
434            0,
435            &[Some(10_000)],
436            Chain::Ethereum,
437            100,
438        );
439        let weth = Token::new(
440            &Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap(),
441            "WETH",
442            18,
443            0,
444            &[Some(10_000)],
445            Chain::Ethereum,
446            100,
447        );
448
449        let res = if zero_to_one {
450            state.spot_price(&usdc, &weth).unwrap()
451        } else {
452            state.spot_price(&weth, &usdc).unwrap()
453        };
454
455        assert_ulps_eq!(res, exp);
456    }
457
458    #[test]
459    fn test_fee() {
460        let state = UniswapV2State::new(
461            U112::from_str("36925554990922").unwrap(),
462            U112::from_str("30314846538607556521556").unwrap(),
463        );
464
465        let res = state.fee();
466
467        assert_ulps_eq!(res, 0.003);
468    }
469
470    #[test]
471    fn test_delta_transition() {
472        let mut state =
473            UniswapV2State::new(U112::from_str("1000").unwrap(), U112::from_str("1000").unwrap());
474        let attributes: HashMap<String, Bytes> = vec![
475            ("reserve0".to_string(), Bytes::from(1500_u64.to_be_bytes().to_vec())),
476            ("reserve1".to_string(), Bytes::from(2000_u64.to_be_bytes().to_vec())),
477        ]
478        .into_iter()
479        .collect();
480        let delta = ProtocolStateDelta {
481            component_id: "State1".to_owned(),
482            updated_attributes: attributes,
483            deleted_attributes: HashSet::new(), // usv2 doesn't have any deletable attributes
484        };
485
486        let res = state.delta_transition(delta, &HashMap::new(), &Balances::default());
487
488        assert!(res.is_ok());
489        assert_eq!(state.reserve0, U112::from_str("1500").unwrap());
490        assert_eq!(state.reserve1, U112::from_str("2000").unwrap());
491    }
492
493    #[test]
494    fn test_delta_transition_missing_attribute() {
495        let mut state =
496            UniswapV2State::new(U112::from_str("1000").unwrap(), U112::from_str("1000").unwrap());
497        let attributes: HashMap<String, Bytes> =
498            vec![("reserve0".to_string(), Bytes::from(1500_u64.to_be_bytes().to_vec()))]
499                .into_iter()
500                .collect();
501        let delta = ProtocolStateDelta {
502            component_id: "State1".to_owned(),
503            updated_attributes: attributes,
504            deleted_attributes: HashSet::new(),
505        };
506
507        let res = state.delta_transition(delta, &HashMap::new(), &Balances::default());
508
509        assert!(res.is_err());
510        // assert it errors for the missing reserve1 attribute delta
511        match res {
512            Err(e) => {
513                assert!(matches!(e, TransitionError::MissingAttribute(ref x) if x=="reserve1"))
514            }
515            _ => panic!("Test failed: was expecting an Err value"),
516        };
517    }
518
519    #[rstest]
520    // The smallest amount wider than uint112, which no reserve has room for.
521    #[case::two_pow_112(BigUint::one() << 112)]
522    #[case::two_pow_256(BigUint::one() << 256)]
523    fn test_get_amount_out_refuses_amount_wider_than_uint112(#[case] amount_in: BigUint) {
524        let state = UniswapV2State::new(U112::ZERO, U112::from(2000u32));
525
526        let res = state.get_amount_out(amount_in, &token_0(), &token_1());
527
528        assert!(matches!(res, Err(SimulationError::InvalidInput(..))));
529    }
530
531    #[test]
532    fn test_get_amount_out_refuses_reserve_past_uint112() {
533        // uint112 max is 5192296858534827628530496329220095; 1000 units of room are left.
534        let state = UniswapV2State::new(
535            U112::from_str("5192296858534827628530496329219095").unwrap(),
536            U112::from_str("2596148429267413814265248164610048").unwrap(),
537        );
538
539        // floor(1000 * 9970 * 2^111 / (reserve0 * 10000 + 1000 * 9970))
540        //   = floor(25883599839796115728224524201162178560000
541        //           / 51922968585348276285304963292200920000) = 498
542        let at_room = state
543            .get_amount_out(BigUint::from(1000u32), &token_0(), &token_1())
544            .unwrap();
545        assert_eq!(at_room.amount, BigUint::from(498u32));
546
547        let past_room = state.get_amount_out(BigUint::from(1001u32), &token_0(), &token_1());
548        assert!(matches!(past_room, Err(SimulationError::InvalidInput(..))));
549    }
550
551    #[test]
552    fn test_get_limits_is_room_below_uint112() {
553        let state = UniswapV2State::new(U112::from(1000u32), U112::from(2000u32));
554
555        // uint112 max is 5192296858534827628530496329220095.
556        // token 0 -> token 1, reserve_in = 1000, reserve_out = 2000:
557        // max_in = uint112 max - 1000 = 5192296858534827628530496329219095
558        // max_out = floor(max_in * 9970 * 2000 / (1000 * 10000 + max_in * 9970))
559        //         = floor(103534399359184462912898096804628754300000
560        //                 / 51767199679592231456449048402324377150) = 1999
561        let max_in = BigUint::from_str("5192296858534827628530496329219095").unwrap();
562        let limits = state
563            .get_limits(token_0().address, token_1().address)
564            .unwrap();
565        assert_eq!(limits, (max_in.clone(), BigUint::from(1999u32)));
566        let quote = state
567            .get_amount_out(max_in.clone(), &token_0(), &token_1())
568            .unwrap();
569        assert_eq!(quote.amount, BigUint::from(1999u32));
570        let past = state.get_amount_out(max_in + 1u32, &token_0(), &token_1());
571        assert!(matches!(past, Err(SimulationError::InvalidInput(..))));
572
573        // token 1 -> token 0, reserve_in = 2000, reserve_out = 1000:
574        // max_in = uint112 max - 2000 = 5192296858534827628530496329218095
575        // max_out = floor(max_in * 9970 * 1000 / (2000 * 10000 + max_in * 9970))
576        //         = floor(51767199679592231456449048402304407150000
577        //                 / 51767199679592231456449048402324407150) = 999
578        let max_in = BigUint::from_str("5192296858534827628530496329218095").unwrap();
579        let limits = state
580            .get_limits(token_1().address, token_0().address)
581            .unwrap();
582        assert_eq!(limits, (max_in.clone(), BigUint::from(999u32)));
583        let past = state.get_amount_out(max_in + 1u32, &token_1(), &token_0());
584        assert!(matches!(past, Err(SimulationError::InvalidInput(..))));
585    }
586
587    #[test]
588    fn test_get_limits_is_zero_when_a_reserve_is_empty_or_full() {
589        let max = U112::from_str("5192296858534827628530496329220095").unwrap();
590        for (reserve0, reserve1) in [(U112::ZERO, U112::from(2000u32)), (max, U112::from(2000u32))]
591        {
592            let limits = UniswapV2State::new(reserve0, reserve1)
593                .get_limits(token_0().address, token_1().address)
594                .unwrap();
595            assert_eq!(limits, (BigUint::ZERO, BigUint::ZERO), "{reserve0} / {reserve1}");
596        }
597    }
598
599    #[test]
600    fn test_get_amount_out_refuses_amount_that_buys_no_output() {
601        let state = UniswapV2State::new(U112::from(1_000_000u32), U112::from(1000u32));
602
603        // floor(1004 * 997 * 1000 / (1_000_000 * 1000 + 1004 * 997))
604        //   = floor(1_000_988_000 / 1_001_000_988) = 0
605        let dust = state.get_amount_out(BigUint::from(1004u32), &token_0(), &token_1());
606        assert!(matches!(dust, Err(SimulationError::InvalidInput(..))));
607
608        // floor(1005 * 997 * 1000 / (1_000_000 * 1000 + 1005 * 997))
609        //   = floor(1_001_985_000 / 1_001_001_985) = 1
610        let smallest = state
611            .get_amount_out(BigUint::from(1005u32), &token_0(), &token_1())
612            .unwrap();
613        assert_eq!(smallest.amount, BigUint::from(1u32));
614    }
615
616    #[test]
617    fn test_get_limits_is_zero_when_no_amount_buys_output() {
618        // An output of reserve_out = 1 or more needs the whole reserve, and the pair pays less
619        // than its reserve, so nothing can be bought.
620        let state = UniswapV2State::new(U112::from(1000u32), U112::from(1u32));
621
622        let limits = state
623            .get_limits(token_0().address, token_1().address)
624            .unwrap();
625
626        assert_eq!(limits, (BigUint::ZERO, BigUint::ZERO));
627    }
628
629    #[test]
630    fn test_swap_to_price_below_spot() {
631        // Pool with reserve0=2000000, reserve1=1000000
632        // Current price: reserve1/reserve0 = 1000000/2000000 = 0.5 token_out per token_in
633        let state = UniswapV2State::new(U112::from(2_000_000u32), U112::from(1_000_000u32));
634
635        let token_in = token_0();
636        let token_out = token_1();
637
638        // Target price: 2/5 = 0.4 token_out per token_in (lower than current 0.5)
639        // Selling token_in decreases price from 0.5 down to 0.4
640        let target_price = Price::new(BigUint::from(2u32), BigUint::from(5u32));
641        let params = &QueryPoolSwapParams::new(
642            token_in,
643            token_out,
644            SwapConstraint::PoolTargetPrice {
645                target: target_price,
646                tolerance: 0f64,
647                min_amount_in: None,
648                max_amount_in: None,
649            },
650        );
651        let pool_swap = state.query_pool_swap(params).unwrap();
652
653        assert_eq!(
654            *pool_swap.amount_in(),
655            BigUint::from(232711u32),
656            "Should require some input amount"
657        );
658        assert_eq!(*pool_swap.amount_out(), BigUint::from(103947u32));
659
660        // Verify that swapping this amount brings us close to the target price
661        let new_state = pool_swap
662            .new_state()
663            .as_any()
664            .downcast_ref::<UniswapV2State>()
665            .unwrap();
666
667        // The new reserves should reflect the target price
668        // Price = reserve1/reserve0, so if price = 0.4, then reserve0/reserve1 = 2.5
669        let new_reserve_ratio =
670            new_state.reserve0.to::<u128>() as f64 / new_state.reserve1.to::<u128>() as f64;
671        let expected_ratio = 2.5;
672
673        // Allow for some difference due to fees and rounding
674        assert!(
675            (new_reserve_ratio - expected_ratio).abs() < 0.01,
676            "New reserve ratio {new_reserve_ratio} should be close to expected {expected_ratio}"
677        );
678    }
679
680    #[test]
681    fn test_swap_to_price_unreachable() {
682        // Pool with 2:1 ratio
683        let state = UniswapV2State::new(U112::from(2_000_000u32), U112::from(1_000_000u32));
684
685        let token_in = token_0();
686        let token_out = token_1();
687        // Target price is unreachable (should return error)
688        // Current pool price: reserve_out/reserve_in = 1000000/2000000 = 0.5 token_out per
689        // token_in Target: 1/1 = 1.0 token_out per token_in
690        // Selling token_in decreases pool price, so we can't reach 1.0 from 0.5
691        let target_price = Price::new(BigUint::from(1u32), BigUint::from(1u32));
692
693        let result = state.query_pool_swap(&QueryPoolSwapParams::new(
694            token_in,
695            token_out,
696            SwapConstraint::PoolTargetPrice {
697                target: target_price,
698                tolerance: 0f64,
699                min_amount_in: None,
700                max_amount_in: None,
701            },
702        ));
703
704        assert!(result.is_err(), "Should return error when target price is unreachable");
705    }
706
707    #[test]
708    fn test_swap_to_price_at_spot_price() {
709        let state = UniswapV2State::new(U112::from(2_000_000u32), U112::from(1_000_000u32));
710
711        let token_in = token_0();
712        let token_out = token_1();
713
714        // Calculate spot price with fee (token_out/token_in):
715        // Marginal price = (FEE_NUMERATOR * reserve_out) / (FEE_PRECISION * reserve_in)
716        let spot_price_num = U256::from(1_000_000u32) * FEE_NUMERATOR;
717        let spot_price_den = U256::from(2_000_000u32) * FEE_PRECISION;
718
719        let target_price =
720            Price::new(u256_to_biguint(spot_price_num), u256_to_biguint(spot_price_den));
721
722        let pool_swap = state
723            .query_pool_swap(&QueryPoolSwapParams::new(
724                token_in,
725                token_out,
726                SwapConstraint::PoolTargetPrice {
727                    target: target_price,
728                    tolerance: 0f64,
729                    min_amount_in: None,
730                    max_amount_in: None,
731                },
732            ))
733            .unwrap();
734
735        // At exact spot price, we should return zero amount
736        assert_eq!(
737            *pool_swap.amount_in(),
738            BigUint::ZERO,
739            "At spot price should require zero input amount"
740        );
741        assert_eq!(
742            *pool_swap.amount_out(),
743            BigUint::ZERO,
744            "At spot price should return zero output amount"
745        );
746    }
747
748    #[test]
749    fn test_swap_to_price_slightly_below_spot() {
750        let state = UniswapV2State::new(U112::from(2_000_000u32), U112::from(1_000_000u32));
751
752        let token_in = token_0();
753        let token_out = token_1();
754
755        // Calculate spot price with fee and subtract small amount to move slightly below
756        // Current spot (token_out/token_in with fees): (FEE_NUMERATOR * reserve_out) /
757        // (FEE_PRECISION * reserve_in) Target: slightly below current spot (multiply numerator by
758        // 99999/100000)
759        let spot_price_num = U256::from(1_000_000u32) * FEE_NUMERATOR * U256::from(99_999u32);
760        let spot_price_den = U256::from(2_000_000u32) * FEE_PRECISION * U256::from(100_000u32);
761
762        let target_price =
763            Price::new(u256_to_biguint(spot_price_num), u256_to_biguint(spot_price_den));
764
765        let pool_swap = state
766            .query_pool_swap(&QueryPoolSwapParams::new(
767                token_in,
768                token_out,
769                SwapConstraint::PoolTargetPrice {
770                    target: target_price,
771                    tolerance: 0f64,
772                    min_amount_in: None,
773                    max_amount_in: None,
774                },
775            ))
776            .unwrap();
777
778        assert!(
779            *pool_swap.amount_in() > BigUint::ZERO,
780            "Should return non-zero amount for target slightly below spot"
781        );
782    }
783
784    #[test]
785    fn test_swap_to_price_large_pool() {
786        // Test with realistic large reserves
787        let state = UniswapV2State::new(
788            U112::from_str("6770398782322527849696614").unwrap(),
789            U112::from_str("5124813135806900540214").unwrap(),
790        );
791
792        let token_in = token_0();
793        let token_out = token_1();
794
795        // Current price (token_out/token_in) = reserve1/reserve0
796        // To target a slightly lower price (move price down 10%), we can use:
797        // target_price = (reserve1 * 9) / (reserve0 * 10)
798        // This avoids floating point precision issues with large numbers
799        let price_numerator = BigUint::from(state.reserve1) * BigUint::from(9u32);
800        let price_denominator = BigUint::from(state.reserve0) * BigUint::from(10u32);
801
802        let target_price = Price::new(price_numerator, price_denominator);
803
804        let pool_swap = state
805            .query_pool_swap(&QueryPoolSwapParams::new(
806                token_in,
807                token_out,
808                SwapConstraint::PoolTargetPrice {
809                    target: target_price,
810                    tolerance: 0f64,
811                    min_amount_in: None,
812                    max_amount_in: None,
813                },
814            ))
815            .unwrap();
816
817        assert!(pool_swap.amount_in().clone() > BigUint::ZERO, "Should require some input amount");
818        assert!(pool_swap.amount_out().clone() > BigUint::ZERO, "Should get some output");
819    }
820
821    #[test]
822    fn test_swap_to_price_basic() {
823        let state = UniswapV2State::new(U112::from(1_000_000u32), U112::from(2_000_000u32));
824
825        let token_in = token_0();
826        let token_out = token_1();
827
828        let target_price = Price::new(BigUint::from(2u32), BigUint::from(3u32));
829
830        let pool_swap = state
831            .query_pool_swap(&QueryPoolSwapParams::new(
832                token_in,
833                token_out,
834                SwapConstraint::PoolTargetPrice {
835                    target: target_price,
836                    tolerance: 0f64,
837                    min_amount_in: None,
838                    max_amount_in: None,
839                },
840            ))
841            .unwrap();
842        assert!(*pool_swap.amount_in() > BigUint::ZERO, "Amount in should be non-zero");
843        assert!(*pool_swap.amount_out() > BigUint::ZERO, "Amount out should be non-zero");
844    }
845
846    #[test]
847    fn test_swap_to_price_validates_actual_output() {
848        // Test that query_supply validates actual_output >= expected_output
849        let state = UniswapV2State::new(
850            U112::from(1_000_000u128) * U112::from(1_000_000_000_000_000_000u128),
851            U112::from(2_000_000u128) * U112::from(1_000_000_000_000_000_000u128),
852        );
853
854        let token_in = token_0();
855        let token_out = token_1();
856
857        // Current pool price: 2M/1M = 2.0 token_out per token_in
858        // Target: slightly lower (e.g., 1.95:1 = 1_950_000/1_000_000)
859        // This is reachable by selling token_in
860        let target_price = Price::new(BigUint::from(1_950_000u128), BigUint::from(1_000_000u128));
861
862        let pool_swap = state
863            .query_pool_swap(&QueryPoolSwapParams::new(
864                token_in,
865                token_out,
866                SwapConstraint::PoolTargetPrice {
867                    target: target_price,
868                    tolerance: 0f64,
869                    min_amount_in: None,
870                    max_amount_in: None,
871                },
872            ))
873            .unwrap();
874        assert!(
875            *pool_swap.amount_out() > BigUint::ZERO,
876            "Should return amount out for valid price"
877        );
878        assert!(*pool_swap.amount_in() > BigUint::ZERO, "Should return amount in for valid price");
879    }
880
881    #[test]
882    fn test_swap_around_spot_price() {
883        let usdc = Token::new(
884            &Bytes::from_str("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap(),
885            "USDC",
886            6,
887            0,
888            &[Some(10_000)],
889            Chain::Ethereum,
890            100,
891        );
892        let dai = Token::new(
893            &Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap(),
894            "DAI",
895            18,
896            0,
897            &[Some(10_000)],
898            Chain::Ethereum,
899            100,
900        );
901
902        let reserve_0 = U112::from_str("735952457913070155214197").unwrap();
903        let reserve_1 = U112::from_str("735997725943000000000000").unwrap();
904
905        let pool = UniswapV2State::new(reserve_0, reserve_1);
906
907        // Reserves: reserve_0 = DAI, reserve_1 = USDC (DAI address < USDC address)
908        let reserve_usdc = reserve_1;
909        let reserve_dai = reserve_0;
910
911        // Calculate spot price (USDC/DAI with fee)
912        let spot_price_dai_per_usdc_num = reserve_dai
913            .checked_mul(U112::from(1000u32))
914            .unwrap();
915        let spot_price_dai_per_usdc_den = reserve_usdc
916            .checked_mul(U112::from(1003u32))
917            .unwrap();
918
919        // Test 1: Price above reachable limit (more DAI per USDC than pool can provide) -should
920        // return error Multiply by 1001/1000 to go above reachable limit
921        let above_limit_num = spot_price_dai_per_usdc_num
922            .checked_mul(U112::from(1001u32))
923            .unwrap();
924        let above_limit_den = spot_price_dai_per_usdc_den
925            .checked_mul(U112::from(1000u32))
926            .unwrap();
927        let target_price =
928            Price::new(BigUint::from(above_limit_num), BigUint::from(above_limit_den));
929
930        let swap_above_limit = pool.query_pool_swap(&QueryPoolSwapParams::new(
931            usdc.clone(),
932            dai.clone(),
933            SwapConstraint::PoolTargetPrice {
934                target: target_price,
935                tolerance: 0f64,
936                min_amount_in: None,
937                max_amount_in: None,
938            },
939        ));
940        assert!(swap_above_limit.is_err(), "Should return error for price above reachable limit");
941
942        // Test 2: Price just below reachable limit - should return non-zero
943        // Multiply by 100_000/100_001 to go slightly below (more reachable)
944        let below_limit_num = spot_price_dai_per_usdc_num
945            .checked_mul(U112::from(100_000u32))
946            .unwrap();
947        let below_limit_den = spot_price_dai_per_usdc_den
948            .checked_mul(U112::from(100_001u32))
949            .unwrap();
950        let target_price =
951            Price::new(BigUint::from(below_limit_num), BigUint::from(below_limit_den));
952
953        let swap_below_limit = pool
954            .query_pool_swap(&QueryPoolSwapParams::new(
955                usdc.clone(),
956                dai.clone(),
957                SwapConstraint::PoolTargetPrice {
958                    target: target_price,
959                    tolerance: 0f64,
960                    min_amount_in: None,
961                    max_amount_in: None,
962                },
963            ))
964            .unwrap();
965
966        assert!(
967            swap_below_limit.amount_out().clone() > BigUint::ZERO,
968            "Should return non-zero for reachable price"
969        );
970
971        // Verify with actual swap
972        let actual_result = pool
973            .get_amount_out(swap_below_limit.amount_in().clone(), &usdc, &dai)
974            .unwrap();
975
976        assert_eq!(
977            biguint_to_uint(&actual_result.amount).unwrap(),
978            U112::from(366839007208379339u128),
979            "Should return non-zero amount"
980        );
981        assert!(
982            actual_result.amount >= swap_below_limit.amount_out().clone(),
983            "Actual swap should give at least predicted amount"
984        );
985    }
986}