Skip to main content

tycho_simulation/evm/protocol/pancakeswap_v2/
state.rs

1use std::{any::Any, collections::HashMap};
2
3use alloy::primitives::U256;
4use num_bigint::BigUint;
5use num_traits::Zero;
6use serde::{Deserialize, Serialize};
7use tycho_common::{
8    dto::ProtocolStateDelta,
9    models::token::Token,
10    simulation::{
11        errors::{SimulationError, TransitionError},
12        protocol_sim::{
13            Balances, GetAmountOutResult, PoolSwap, ProtocolSim, QueryPoolSwapParams,
14            SwapConstraint,
15        },
16    },
17    Bytes,
18};
19
20use crate::evm::protocol::{
21    cpmm::protocol::{
22        cpmm_delta_transition, cpmm_fee, cpmm_get_amount_out, cpmm_get_limits, cpmm_spot_price,
23        cpmm_swap_to_price, ProtocolFee,
24    },
25    safe_math::{safe_add_u256, safe_sub_u256},
26    u256_num::{biguint_to_uint, u256_to_biguint},
27    utils::add_fee_markup,
28};
29
30const SWAP_BASE_GAS: u64 = 90_000;
31const PANCAKESWAP_V2_FEE: u32 = 25; // 0.25% fee
32const FEE_PRECISION: U256 = U256::from_limbs([10000, 0, 0, 0]);
33const FEE_NUMERATOR: U256 = U256::from_limbs([9975, 0, 0, 0]);
34
35#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
36pub struct PancakeswapV2State {
37    pub reserve0: U256,
38    pub reserve1: U256,
39}
40
41impl PancakeswapV2State {
42    /// Creates a new instance of `PancakeswapV2State` with the given reserves.
43    ///
44    /// # Arguments
45    ///
46    /// * `reserve0` - Reserve of token 0.
47    /// * `reserve1` - Reserve of token 1.
48    pub fn new(reserve0: U256, reserve1: U256) -> Self {
49        PancakeswapV2State { reserve0, reserve1 }
50    }
51}
52
53#[typetag::serde]
54impl ProtocolSim for PancakeswapV2State {
55    fn fee(&self) -> f64 {
56        cpmm_fee(PANCAKESWAP_V2_FEE)
57    }
58
59    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
60        let price = cpmm_spot_price(base, quote, self.reserve0, self.reserve1)?;
61        Ok(add_fee_markup(price, self.fee()))
62    }
63
64    fn get_amount_out(
65        &self,
66        amount_in: BigUint,
67        token_in: &Token,
68        token_out: &Token,
69    ) -> Result<GetAmountOutResult, SimulationError> {
70        let amount_in = biguint_to_uint(&amount_in)?;
71        let zero2one = token_in.address < token_out.address;
72        let (reserve_in, reserve_out) =
73            if zero2one { (self.reserve0, self.reserve1) } else { (self.reserve1, self.reserve0) };
74        let fee = ProtocolFee::new(FEE_NUMERATOR, FEE_PRECISION);
75        let amount_out = cpmm_get_amount_out(amount_in, reserve_in, reserve_out, fee)?;
76        let mut new_state = self.clone();
77        let (reserve0_mut, reserve1_mut) = (&mut new_state.reserve0, &mut new_state.reserve1);
78        if zero2one {
79            *reserve0_mut = safe_add_u256(self.reserve0, amount_in)?;
80            *reserve1_mut = safe_sub_u256(self.reserve1, amount_out)?;
81        } else {
82            *reserve0_mut = safe_sub_u256(self.reserve0, amount_out)?;
83            *reserve1_mut = safe_add_u256(self.reserve1, amount_in)?;
84        };
85        Ok(GetAmountOutResult::new(
86            u256_to_biguint(amount_out),
87            BigUint::from(SWAP_BASE_GAS),
88            Box::new(new_state),
89        ))
90    }
91
92    fn get_limits(
93        &self,
94        sell_token: Bytes,
95        buy_token: Bytes,
96    ) -> Result<(BigUint, BigUint), SimulationError> {
97        cpmm_get_limits(&sell_token, &buy_token, self.reserve0, self.reserve1, PANCAKESWAP_V2_FEE)
98    }
99
100    fn delta_transition(
101        &mut self,
102        delta: ProtocolStateDelta,
103        _tokens: &HashMap<Bytes, Token>,
104        _balances: &Balances,
105    ) -> Result<(), TransitionError> {
106        let (reserve0_mut, reserve1_mut) = (&mut self.reserve0, &mut self.reserve1);
107        cpmm_delta_transition(&delta, reserve0_mut, reserve1_mut)
108    }
109
110    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
111        match params.swap_constraint() {
112            SwapConstraint::PoolTargetPrice {
113                target: price,
114                tolerance: _,
115                min_amount_in: _,
116                max_amount_in: _,
117            } => {
118                let zero2one = params.token_in().address < params.token_out().address;
119                let (reserve_in, reserve_out) = if zero2one {
120                    (self.reserve0, self.reserve1)
121                } else {
122                    (self.reserve1, self.reserve0)
123                };
124
125                let fee = ProtocolFee::new(FEE_NUMERATOR, FEE_PRECISION);
126                let (amount_in, _) = cpmm_swap_to_price(reserve_in, reserve_out, price, fee)?;
127                if amount_in.is_zero() {
128                    return Ok(PoolSwap::new(
129                        BigUint::ZERO,
130                        BigUint::ZERO,
131                        Box::new(self.clone()),
132                        None,
133                    ));
134                }
135
136                let res =
137                    self.get_amount_out(amount_in.clone(), params.token_in(), params.token_out())?;
138                Ok(PoolSwap::new(amount_in, res.amount, res.new_state, None))
139            }
140            SwapConstraint::TradeLimitPrice { .. } => Err(SimulationError::InvalidInput(
141                "PancakeSwapV2State does not support TradeLimitPrice constraint in query_pool_swap"
142                    .to_string(),
143                None,
144            )),
145        }
146    }
147
148    fn clone_box(&self) -> Box<dyn ProtocolSim> {
149        Box::new(self.clone())
150    }
151
152    fn as_any(&self) -> &dyn Any {
153        self
154    }
155
156    fn as_any_mut(&mut self) -> &mut dyn Any {
157        self
158    }
159
160    fn eq(&self, other: &dyn ProtocolSim) -> bool {
161        if let Some(other_state) = other.as_any().downcast_ref::<Self>() {
162            let (self_reserve0, self_reserve1) = (self.reserve0, self.reserve1);
163            let (other_reserve0, other_reserve1) = (other_state.reserve0, other_state.reserve1);
164            self_reserve0 == other_reserve0 &&
165                self_reserve1 == other_reserve1 &&
166                self.fee() == other_state.fee()
167        } else {
168            false
169        }
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use std::{
176        collections::{HashMap, HashSet},
177        str::FromStr,
178    };
179
180    use approx::assert_ulps_eq;
181    use num_bigint::BigUint;
182    use num_traits::One;
183    use rstest::rstest;
184    use tycho_common::{
185        dto::ProtocolStateDelta,
186        hex_bytes::Bytes,
187        models::{token::Token, Chain},
188        simulation::{
189            errors::{SimulationError, TransitionError},
190            protocol_sim::{Balances, Price, ProtocolSim},
191        },
192    };
193
194    use super::*;
195    use crate::evm::protocol::u256_num::biguint_to_uint;
196
197    fn token_0() -> Token {
198        Token::new(
199            &Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
200            "T0",
201            18,
202            0,
203            &[Some(100_000)],
204            Chain::Ethereum,
205            100,
206        )
207    }
208
209    fn token_1() -> Token {
210        Token::new(
211            &Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap(),
212            "T1",
213            18,
214            0,
215            &[Some(10_000)],
216            Chain::Ethereum,
217            100,
218        )
219    }
220    #[test]
221    fn test_get_amount_out() {
222        // Values based on mainnet WETH/USDC pool swap at transaction
223        // 0x6b3193b0ce348cf45d2c70a6481d8088f58ee22ba41502b611a2b045f4464c9f
224        let t0 = Token::new(
225            &Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
226            "WETH",
227            18,
228            0,
229            &[Some(100_000)],
230            Chain::Ethereum,
231            100,
232        );
233
234        let t1 = Token::new(
235            &Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap(),
236            "USDC",
237            6,
238            0,
239            &[Some(10_000)],
240            Chain::Ethereum,
241            100,
242        );
243        let reserve0 = U256::from_str("114293490733").unwrap();
244        let reserve1 = U256::from_str("69592908201923870949").unwrap();
245        let state = PancakeswapV2State::new(reserve0, reserve1);
246        let amount_in = BigUint::from_str("13088600769481610").unwrap();
247
248        let res = state
249            .get_amount_out(amount_in, &t1, &t0)
250            .unwrap();
251
252        let exp = BigUint::from_str("21437847").unwrap();
253        assert_eq!(res.amount, exp);
254        let new_state = res
255            .new_state
256            .as_any()
257            .downcast_ref::<PancakeswapV2State>()
258            .unwrap();
259        assert_eq!(new_state.reserve0, U256::from_str("114272052886").unwrap());
260        assert_eq!(new_state.reserve1, U256::from_str("69605996802693352559").unwrap());
261        // Assert that the old state is unchanged
262        assert_eq!(state.reserve0, reserve0);
263        assert_eq!(state.reserve1, reserve1);
264    }
265
266    #[test]
267    fn test_get_amount_out_overflow() {
268        let r0 = U256::from_str("33372357002392258830279").unwrap();
269        let r1 = U256::from_str("43356945776493").unwrap();
270        let amount_in = (BigUint::one() << 256) - BigUint::one(); // U256 max value
271        let t0d = 18;
272        let t1d = 16;
273        let t0 = Token::new(
274            &Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
275            "T0",
276            t0d,
277            0,
278            &[Some(10_000)],
279            Chain::Ethereum,
280            100,
281        );
282        let t1 = Token::new(
283            &Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap(),
284            "T0",
285            t1d,
286            0,
287            &[Some(10_000)],
288            Chain::Ethereum,
289            100,
290        );
291        let state = PancakeswapV2State::new(r0, r1);
292
293        let res = state.get_amount_out(amount_in, &t0, &t1);
294        assert!(res.is_err());
295        let err = res.err().unwrap();
296        assert!(matches!(err, SimulationError::FatalError(_)));
297    }
298
299    #[rstest]
300    #[case(true, 0.0008230295686841545)] // 0.0008209719947624441 / 0.9975
301    #[case(false, 1221.12114914985)] // 1218.0683462769755 / 0.9975
302    fn test_spot_price(#[case] zero_to_one: bool, #[case] exp: f64) {
303        let state = PancakeswapV2State::new(
304            U256::from_str("36925554990922").unwrap(),
305            U256::from_str("30314846538607556521556").unwrap(),
306        );
307        let usdc = Token::new(
308            &Bytes::from_str("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap(),
309            "USDC",
310            6,
311            0,
312            &[Some(10_000)],
313            Chain::Ethereum,
314            100,
315        );
316        let weth = Token::new(
317            &Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap(),
318            "WETH",
319            18,
320            0,
321            &[Some(10_000)],
322            Chain::Ethereum,
323            100,
324        );
325
326        let res = if zero_to_one {
327            state.spot_price(&usdc, &weth).unwrap()
328        } else {
329            state.spot_price(&weth, &usdc).unwrap()
330        };
331
332        assert_ulps_eq!(res, exp);
333    }
334
335    #[test]
336    fn test_fee() {
337        let state = PancakeswapV2State::new(
338            U256::from_str("36925554990922").unwrap(),
339            U256::from_str("30314846538607556521556").unwrap(),
340        );
341
342        let res = state.fee();
343
344        assert_ulps_eq!(res, 0.0025); // 0.25% fee
345    }
346
347    #[test]
348    fn test_delta_transition() {
349        let mut state = PancakeswapV2State::new(
350            U256::from_str("1000").unwrap(),
351            U256::from_str("1000").unwrap(),
352        );
353        let attributes: HashMap<String, Bytes> = vec![
354            ("reserve0".to_string(), Bytes::from(1500_u64.to_be_bytes().to_vec())),
355            ("reserve1".to_string(), Bytes::from(2000_u64.to_be_bytes().to_vec())),
356        ]
357        .into_iter()
358        .collect();
359        let delta = ProtocolStateDelta {
360            component_id: "State1".to_owned(),
361            updated_attributes: attributes,
362            deleted_attributes: HashSet::new(),
363        };
364
365        let res = state.delta_transition(delta, &HashMap::new(), &Balances::default());
366
367        assert!(res.is_ok());
368        assert_eq!(state.reserve0, U256::from_str("1500").unwrap());
369        assert_eq!(state.reserve1, U256::from_str("2000").unwrap());
370    }
371
372    #[test]
373    fn test_delta_transition_missing_attribute() {
374        let mut state = PancakeswapV2State::new(
375            U256::from_str("1000").unwrap(),
376            U256::from_str("1000").unwrap(),
377        );
378        let attributes: HashMap<String, Bytes> =
379            vec![("reserve0".to_string(), Bytes::from(1500_u64.to_be_bytes().to_vec()))]
380                .into_iter()
381                .collect();
382        let delta = ProtocolStateDelta {
383            component_id: "State1".to_owned(),
384            updated_attributes: attributes,
385            deleted_attributes: HashSet::new(),
386        };
387
388        let res = state.delta_transition(delta, &HashMap::new(), &Balances::default());
389
390        assert!(res.is_err());
391        match res {
392            Err(e) => {
393                assert!(matches!(e, TransitionError::MissingAttribute(ref x) if x=="reserve1"))
394            }
395            _ => panic!("Test failed: was expecting an Err value"),
396        };
397    }
398
399    #[test]
400    fn test_get_limits_price_impact() {
401        let state = PancakeswapV2State::new(
402            U256::from_str("1000").unwrap(),
403            U256::from_str("100000").unwrap(),
404        );
405
406        let (amount_in, _) = state
407            .get_limits(
408                Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
409                Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap(),
410            )
411            .unwrap();
412
413        let token_0 = token_0();
414        let token_1 = token_1();
415
416        let result = state
417            .get_amount_out(amount_in, &token_0, &token_1)
418            .unwrap();
419        let new_state = result.new_state;
420
421        let initial_price = state
422            .spot_price(&token_0, &token_1)
423            .unwrap();
424        let new_price = new_state
425            .spot_price(&token_0, &token_1)
426            .unwrap();
427
428        // Price impact should be approximately 90% (new_price ≈ initial_price / 10)
429        // Due to fees being added to pool liquidity, actual impact is slightly less than 90%
430        // (see cpmm_get_limits documentation for details)
431        let price_impact = 1.0 - new_price / initial_price;
432        assert!(
433            (0.899..=0.90).contains(&price_impact),
434            "Price impact should be approximately 90%. Actual impact: {:.2}%",
435            price_impact * 100.0
436        );
437    }
438
439    #[test]
440    fn test_swap_to_price_below_spot() {
441        // Pool with reserve0=2000000, reserve1=1000000
442        // Current price: reserve1/reserve0 = 1000000/2000000 = 0.5 token_out per token_in
443        let state = PancakeswapV2State::new(U256::from(2_000_000u32), U256::from(1_000_000u32));
444
445        let token_in = token_0();
446        let token_out = token_1();
447
448        // Target price: 2/5 = 0.4 token_out per token_in (lower than current 0.5)
449        // Selling token_in decreases price from 0.5 down to 0.4
450        let target_price = Price::new(BigUint::from(2u32), BigUint::from(5u32));
451
452        let params = QueryPoolSwapParams::new(
453            token_in,
454            token_out,
455            SwapConstraint::PoolTargetPrice {
456                target: target_price,
457                tolerance: 0f64,
458                min_amount_in: None,
459                max_amount_in: None,
460            },
461        );
462
463        let pool_swap = state.query_pool_swap(&params).unwrap();
464
465        assert_eq!(
466            *pool_swap.amount_in(),
467            BigUint::from(233271u32),
468            "Should require some input amount"
469        );
470        assert_eq!(*pool_swap.amount_out(), BigUint::from(104218u32));
471
472        // Verify that swapping this amount brings us close to the target price
473        let new_state = pool_swap
474            .new_state()
475            .as_any()
476            .downcast_ref::<PancakeswapV2State>()
477            .unwrap();
478
479        // The new reserves should reflect the target price
480        // Price = reserve1/reserve0, so if price = 0.4, then reserve0/reserve1 = 2.5
481        let new_reserve_ratio =
482            new_state.reserve0.to::<u128>() as f64 / new_state.reserve1.to::<u128>() as f64;
483        let expected_ratio = 2.5;
484
485        // Allow for some difference due to fees and rounding
486        assert!(
487            (new_reserve_ratio - expected_ratio).abs() < 0.01,
488            "New reserve ratio {new_reserve_ratio} should be close to expected {expected_ratio}"
489        );
490    }
491
492    #[test]
493    fn test_swap_to_price_unreachable() {
494        // Pool with 2:1 ratio
495        let state = PancakeswapV2State::new(U256::from(2_000_000u32), U256::from(1_000_000u32));
496
497        let token_in = token_0();
498        let token_out = token_1();
499
500        // Target price is unreachable (should return error)
501        // Current pool price: reserve_out/reserve_in = 1000000/2000000 = 0.5 token_out per
502        // token_in Target: 1/1 = 1.0 token_out per token_in
503        // Selling token_in decreases pool price, so we can't reach 1.0 from 0.5
504        let target_price = Price::new(BigUint::from(1u32), BigUint::from(1u32));
505
506        let result = state.query_pool_swap(&QueryPoolSwapParams::new(
507            token_in,
508            token_out,
509            SwapConstraint::PoolTargetPrice {
510                target: target_price,
511                tolerance: 0f64,
512                min_amount_in: None,
513                max_amount_in: None,
514            },
515        ));
516
517        assert!(result.is_err(), "Should return error when target price is unreachable");
518    }
519
520    #[test]
521    fn test_swap_to_price_at_spot_price() {
522        let state = PancakeswapV2State::new(U256::from(2_000_000u32), U256::from(1_000_000u32));
523
524        let token_in = token_0();
525        let token_out = token_1();
526
527        // Calculate spot price with fee (token_out/token_in):
528        // Marginal price = (FEE_NUMERATOR * reserve_out) / (FEE_PRECISION * reserve_in)
529        let spot_price_num = U256::from(1_000_000u32) * FEE_NUMERATOR;
530        let spot_price_den = U256::from(2_000_000u32) * FEE_PRECISION;
531
532        let target_price =
533            Price::new(u256_to_biguint(spot_price_num), u256_to_biguint(spot_price_den));
534
535        let pool_swap = state
536            .query_pool_swap(&QueryPoolSwapParams::new(
537                token_in,
538                token_out,
539                SwapConstraint::PoolTargetPrice {
540                    target: target_price,
541                    tolerance: 0f64,
542                    min_amount_in: None,
543                    max_amount_in: None,
544                },
545            ))
546            .unwrap();
547
548        // At exact spot price, we should return zero amount
549        assert_eq!(
550            *pool_swap.amount_in(),
551            BigUint::ZERO,
552            "At spot price should require zero input amount"
553        );
554        assert_eq!(
555            *pool_swap.amount_out(),
556            BigUint::ZERO,
557            "At spot price should return zero output amount"
558        );
559    }
560
561    #[test]
562    fn test_swap_to_price_slightly_below_spot() {
563        let state = PancakeswapV2State::new(U256::from(2_000_000u32), U256::from(1_000_000u32));
564
565        let token_in = token_0();
566        let token_out = token_1();
567
568        // Calculate spot price with fee and subtract small amount to move slightly below
569        // Current spot (token_out/token_in with fees): (FEE_NUMERATOR * reserve_out) /
570        // (FEE_PRECISION * reserve_in) Target: slightly below current spot (multiply numerator by
571        // 99999/100000)
572        let spot_price_num = U256::from(1_000_000u32) * FEE_NUMERATOR * U256::from(99_999u32);
573        let spot_price_den = U256::from(2_000_000u32) * FEE_PRECISION * U256::from(100_000u32);
574
575        let target_price =
576            Price::new(u256_to_biguint(spot_price_num), u256_to_biguint(spot_price_den));
577
578        let pool_swap = state
579            .query_pool_swap(&QueryPoolSwapParams::new(
580                token_in,
581                token_out,
582                SwapConstraint::PoolTargetPrice {
583                    target: target_price,
584                    tolerance: 0f64,
585                    min_amount_in: None,
586                    max_amount_in: None,
587                },
588            ))
589            .unwrap();
590
591        assert!(
592            *pool_swap.amount_in() > BigUint::ZERO,
593            "Should return non-zero amount for target slightly below spot"
594        );
595    }
596
597    #[test]
598    fn test_swap_to_price_large_pool() {
599        // Test with realistic large reserves
600        let state = PancakeswapV2State::new(
601            U256::from_str("6770398782322527849696614").unwrap(),
602            U256::from_str("5124813135806900540214").unwrap(),
603        );
604
605        let token_in = token_0();
606        let token_out = token_1();
607
608        // Current price (token_out/token_in) = reserve1/reserve0
609        // To target a slightly lower price (move price down 10%), we can use:
610        // target_price = (reserve1 * 9) / (reserve0 * 10)
611        // This avoids floating point precision issues with large numbers
612        let price_numerator = u256_to_biguint(state.reserve1) * BigUint::from(9u32);
613        let price_denominator = u256_to_biguint(state.reserve0) * BigUint::from(10u32);
614
615        let target_price = Price::new(price_numerator, price_denominator);
616
617        let pool_swap = state
618            .query_pool_swap(&QueryPoolSwapParams::new(
619                token_in,
620                token_out,
621                SwapConstraint::PoolTargetPrice {
622                    target: target_price,
623                    tolerance: 0f64,
624                    min_amount_in: None,
625                    max_amount_in: None,
626                },
627            ))
628            .unwrap();
629
630        assert!(*pool_swap.amount_in() > BigUint::ZERO, "Should require some input amount");
631        assert!(*pool_swap.amount_out() > BigUint::ZERO, "Should get some output");
632    }
633
634    #[test]
635    fn test_swap_to_price_basic() {
636        let state = PancakeswapV2State::new(U256::from(1_000_000u32), U256::from(2_000_000u32));
637
638        let token_in = token_0();
639        let token_out = token_1();
640
641        let target_price = Price::new(BigUint::from(2u32), BigUint::from(3u32));
642
643        let pool_swap = state
644            .query_pool_swap(&QueryPoolSwapParams::new(
645                token_in,
646                token_out,
647                SwapConstraint::PoolTargetPrice {
648                    target: target_price,
649                    tolerance: 0f64,
650                    min_amount_in: None,
651                    max_amount_in: None,
652                },
653            ))
654            .unwrap();
655        assert!(*pool_swap.amount_in() > BigUint::ZERO, "Amount in should be non-zero");
656        assert!(*pool_swap.amount_out() > BigUint::ZERO, "Amount out should be non-zero");
657    }
658
659    #[test]
660    fn test_swap_to_price_validates_actual_output() {
661        // Test that query_supply validates actual_output >= expected_output
662        let state = PancakeswapV2State::new(
663            U256::from(1_000_000u128) * U256::from(1_000_000_000_000_000_000u128),
664            U256::from(2_000_000u128) * U256::from(1_000_000_000_000_000_000u128),
665        );
666
667        let token_in = token_0();
668        let token_out = token_1();
669
670        // Current pool price: 2M/1M = 2.0 token_out per token_in
671        // Target: slightly lower (e.g., 1.95:1 = 1_950_000/1_000_000)
672        // This is reachable by selling token_in
673        let target_price = Price::new(BigUint::from(1_950_000u128), BigUint::from(1_000_000u128));
674
675        let pool_swap = state
676            .query_pool_swap(&QueryPoolSwapParams::new(
677                token_in,
678                token_out,
679                SwapConstraint::PoolTargetPrice {
680                    target: target_price,
681                    tolerance: 0f64,
682                    min_amount_in: None,
683                    max_amount_in: None,
684                },
685            ))
686            .unwrap();
687        assert!(
688            *pool_swap.amount_out() > BigUint::ZERO,
689            "Should return amount out for valid price"
690        );
691        assert!(*pool_swap.amount_in() > BigUint::ZERO, "Should return amount in for valid price");
692    }
693
694    #[test]
695    fn test_swap_around_spot_price() {
696        let usdc = Token::new(
697            &Bytes::from_str("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap(),
698            "USDC",
699            6,
700            0,
701            &[Some(10_000)],
702            Chain::Ethereum,
703            100,
704        );
705        let dai = Token::new(
706            &Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap(),
707            "DAI",
708            18,
709            0,
710            &[Some(10_000)],
711            Chain::Ethereum,
712            100,
713        );
714
715        let reserve_0 = U256::from_str("735952457913070155214197").unwrap();
716        let reserve_1 = U256::from_str("735997725943000000000000").unwrap();
717
718        let pool = PancakeswapV2State::new(reserve_0, reserve_1);
719
720        // Reserves: reserve_0 = DAI, reserve_1 = USDC (DAI address < USDC address)
721        let reserve_usdc = reserve_1;
722        let reserve_dai = reserve_0;
723
724        // Calculate spot price (USDC/DAI with fee)
725        let spot_price_dai_per_usdc_num = reserve_dai
726            .checked_mul(U256::from(10000u32))
727            .unwrap();
728        let spot_price_dai_per_usdc_den = reserve_usdc
729            .checked_mul(U256::from(10025u32))
730            .unwrap();
731
732        // Test 1: Price above reachable limit (more DAI per USDC than pool can provide) -should
733        // return error Multiply by 1001/1000 to go above reachable limit
734        let above_limit_num = spot_price_dai_per_usdc_num
735            .checked_mul(U256::from(1001u32))
736            .unwrap();
737        let above_limit_den = spot_price_dai_per_usdc_den
738            .checked_mul(U256::from(1000u32))
739            .unwrap();
740        let target_price =
741            Price::new(u256_to_biguint(above_limit_num), u256_to_biguint(above_limit_den));
742
743        let result_above_limit = pool.query_pool_swap(&QueryPoolSwapParams::new(
744            usdc.clone(),
745            dai.clone(),
746            SwapConstraint::PoolTargetPrice {
747                target: target_price,
748                tolerance: 0f64,
749                min_amount_in: None,
750                max_amount_in: None,
751            },
752        ));
753        assert!(result_above_limit.is_err(), "Should return error for price above reachable limit");
754
755        // Test 2: Price just below reachable limit - should return non-zero
756        // Multiply by 100_000/100_001 to go slightly below (more reachable)
757        let below_limit_num = spot_price_dai_per_usdc_num
758            .checked_mul(U256::from(100_000u32))
759            .unwrap();
760        let below_limit_den = spot_price_dai_per_usdc_den
761            .checked_mul(U256::from(100_001u32))
762            .unwrap();
763        let target_price =
764            Price::new(u256_to_biguint(below_limit_num), u256_to_biguint(below_limit_den));
765
766        let swap_below_limit = pool
767            .query_pool_swap(&QueryPoolSwapParams::new(
768                usdc.clone(),
769                dai.clone(),
770                SwapConstraint::PoolTargetPrice {
771                    target: target_price,
772                    tolerance: 0f64,
773                    min_amount_in: None,
774                    max_amount_in: None,
775                },
776            ))
777            .unwrap();
778
779        assert!(
780            swap_below_limit.amount_out().clone() > BigUint::ZERO,
781            "Should return non-zero for reachable price"
782        );
783
784        // Verify with actual swap
785        let actual_result = pool
786            .get_amount_out(swap_below_limit.amount_in().clone(), &usdc, &dai)
787            .unwrap();
788
789        assert_eq!(
790            biguint_to_uint(&actual_result.amount).unwrap(),
791            U256::from(1376434275718772760u128),
792            "Should return non-zero amount"
793        );
794        assert!(
795            actual_result.amount >= swap_below_limit.amount_out().clone(),
796            "Actual swap should give at least predicted amount"
797        );
798    }
799}