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; const 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 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
66pub(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
78fn 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 return Err(SimulationError::InvalidInput(
129 format!("Amount in {amount_in} is too small to buy any output"),
130 None,
131 ));
132 }
133 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 let (reserve_in, reserve_out) = self.reserves(sell_token < buy_token);
167 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 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 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 fn limit_kind(&self, _sell_token: &Bytes, _buy_token: &Bytes) -> LimitKind {
297 LimitKind::Hard
298 }
299
300 fn check_valid(&self) -> Result<(), String> {
303 Ok(())
304 }
305
306 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 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 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_eq!(state.reserve0, r0);
451 assert_eq!(state.reserve1, r1);
452 }
453
454 #[rstest]
455 #[case(true, 0.000823442321727627)] #[case(false, 1221.7335469177287)] 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(), };
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 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 #[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 let state = UniswapV2State::new(
567 U112::from_str("5192296858534827628530496329219095").unwrap(),
568 U112::from_str("2596148429267413814265248164610048").unwrap(),
569 );
570
571 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 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 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 let dust = state.get_amount_out(BigUint::from(1004u32), &token_0(), &token_1());
638 assert!(matches!(dust, Err(SimulationError::InvalidInput(..))));
639
640 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 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 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 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 let new_state = pool_swap
694 .new_state()
695 .as_any()
696 .downcast_ref::<UniswapV2State>()
697 .unwrap();
698
699 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 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 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 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 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 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 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 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 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 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 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 let reserve_usdc = reserve_1;
941 let reserve_dai = reserve_0;
942
943 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 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 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 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}