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