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