1use std::{any::Any, collections::HashMap, sync::Arc};
2
3use alloy::primitives::{Sign, I256, U256};
4use num_bigint::BigUint;
5use num_traits::Zero;
6use serde::{Deserialize, Serialize};
7use tracing::trace;
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
21use super::fee_tier::{fee_serde, FeeTier};
22use crate::evm::protocol::{
23 clmm::clmm_swap_to_price,
24 safe_math::{safe_add_u256, safe_sub_u256},
25 u256_num::{biguint_to_uint, u256_to_biguint},
26 utils::{
27 add_fee_markup,
28 uniswap::{
29 i24_be_bytes_to_i32, liquidity_math,
30 pool_tick::PoolTick,
31 sqrt_price_math::{get_amount0_delta, get_amount1_delta, sqrt_price_q96_to_f64},
32 swap_math::{self, SwapStepResult},
33 swap_step_cache::{StepCacheKey, StepCacheRun, SwapStepCache},
34 tick_list::{TickInfo, TickList, TickListErrorKind},
35 tick_math::{
36 get_sqrt_ratio_at_tick_cached, MAX_SQRT_RATIO, MAX_TICK, MIN_SQRT_RATIO, MIN_TICK,
37 },
38 StepComputation, SwapResults, SwapState,
39 },
40 },
41};
42
43const SWAP_BASE_GAS: u64 = 70_000;
46const GAS_PER_BITMAP_WORD: u64 = 2_100;
48const GAS_PER_SWAP_MATH_STEP: u64 = 5_400;
50const GAS_PER_INITIALIZED_TICK_CROSS: u64 = 24_000;
53const V3_CALLBACK_SETTLEMENT_GAS: u64 = 70_000;
55const MAX_SWAP_GAS: u64 = 16_700_000;
57const MAX_TICKS_CROSSED: u64 = (MAX_SWAP_GAS - SWAP_BASE_GAS) / GAS_PER_INITIALIZED_TICK_CROSS;
58
59#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
60pub struct UniswapV3State {
61 liquidity: u128,
62 sqrt_price: U256,
63 #[serde(with = "fee_serde")]
64 fee: u32,
65 tick: PoolTick,
66 ticks: Arc<TickList>,
70 #[serde(skip)]
75 step_cache: SwapStepCache,
76}
77
78impl UniswapV3State {
79 pub fn new(
92 liquidity: u128,
93 sqrt_price: U256,
94 fee: impl Into<FeeTier>,
95 tick: i32,
96 ticks: Vec<TickInfo>,
97 ) -> Result<Self, SimulationError> {
98 let fee = fee.into();
99 let tick_list = TickList::from(fee.tick_spacing(), ticks)?;
100 Ok(UniswapV3State {
101 liquidity,
102 sqrt_price,
103 fee: fee.fee(),
104 tick: tick.into(),
105 ticks: Arc::new(tick_list),
106 step_cache: SwapStepCache::default(),
107 })
108 }
109
110 fn clone_post_swap(&self, sqrt_price: U256, tick: PoolTick, liquidity: u128) -> Self {
113 let mut state = self.clone();
114 state.sqrt_price = sqrt_price;
115 state.tick = tick;
116 state.liquidity = liquidity;
117 state.step_cache = SwapStepCache::default();
118 state
119 }
120
121 fn swap(
122 &self,
123 zero_for_one: bool,
124 amount_specified: I256,
125 sqrt_price_limit: Option<U256>,
126 ) -> Result<SwapResults, SimulationError> {
127 if self.liquidity == 0 {
128 return Err(SimulationError::RecoverableError("No liquidity".to_string()));
129 }
130 let price_limit = if let Some(limit) = sqrt_price_limit {
131 limit
132 } else if zero_for_one {
133 safe_add_u256(MIN_SQRT_RATIO, U256::from(1u64))?
134 } else {
135 safe_sub_u256(MAX_SQRT_RATIO, U256::from(1u64))?
136 };
137
138 let price_limit_valid = if zero_for_one {
139 price_limit > MIN_SQRT_RATIO && price_limit < self.sqrt_price
140 } else {
141 price_limit < MAX_SQRT_RATIO && price_limit > self.sqrt_price
142 };
143 if !price_limit_valid {
144 return Err(SimulationError::InvalidInput("Price limit out of range".into(), None));
145 }
146
147 let exact_input = amount_specified > I256::from_raw(U256::from(0u64));
148
149 let mut state = SwapState {
150 amount_remaining: amount_specified,
151 amount_calculated: I256::from_raw(U256::from(0u64)),
152 sqrt_price: self.sqrt_price,
153 tick: self.tick.value().into(),
154 liquidity: self.liquidity,
155 };
156 let mut gas_used = U256::from(SWAP_BASE_GAS);
157
158 let cache_key = if exact_input && sqrt_price_limit.is_none() {
162 StepCacheKey::new(
163 self.sqrt_price,
164 state.tick.value(),
165 self.liquidity,
166 self.fee,
167 gas_used,
168 )
169 } else {
170 None
171 };
172 let mut cache_run = StepCacheRun::new(
173 &self.step_cache,
174 zero_for_one,
175 cache_key,
176 amount_specified.unsigned_abs(),
177 );
178 if let Some(progress) = cache_run.apply_cached_progress(&mut state) {
179 gas_used = progress.gas;
180 }
181
182 while state.amount_remaining != I256::from_raw(U256::from(0u64)) &&
183 state.sqrt_price != price_limit
184 {
185 let (mut next_tick, next_tick_info) = match self
186 .ticks
187 .next_initialized_tick_within_one_word(state.tick.value(), zero_for_one)
188 {
189 Ok((tick, info)) => {
190 gas_used = safe_add_u256(gas_used, U256::from(GAS_PER_BITMAP_WORD))?;
191 (tick, info)
192 }
193 Err(tick_err) => match tick_err.kind {
194 TickListErrorKind::TicksExeeded => {
195 let new_state = self.clone_post_swap(
196 state.sqrt_price,
197 state.tick.clone(),
198 state.liquidity,
199 );
200 return Err(SimulationError::InvalidInput(
201 "Ticks exceeded".into(),
202 Some(GetAmountOutResult::new(
203 u256_to_biguint(state.amount_calculated.abs().into_raw()),
204 u256_to_biguint(gas_used),
205 Box::new(new_state),
206 )),
207 ));
208 }
209 TickListErrorKind::BelowSmallest | TickListErrorKind::AtOrAboveLargest => {
210 return Err(SimulationError::FatalError("Unknown error".to_string()))
211 }
212 },
213 };
214
215 next_tick = next_tick.clamp(MIN_TICK, MAX_TICK);
216
217 let sqrt_price_start = state.sqrt_price;
218 let sqrt_price_next = match next_tick_info {
219 Some(info) => info.sqrt_price,
220 None => get_sqrt_ratio_at_tick_cached(next_tick)?,
221 };
222 let SwapStepResult { sqrt_price, amount_in_with_fee, amount_out } =
223 swap_math::compute_swap_step(
224 state.sqrt_price,
225 UniswapV3State::get_sqrt_ratio_target(
226 sqrt_price_next,
227 price_limit,
228 zero_for_one,
229 ),
230 state.liquidity,
231 state.amount_remaining,
232 self.fee,
233 )?;
234 state.sqrt_price = sqrt_price;
235
236 let step = StepComputation {
237 sqrt_price_start,
238 tick_next: next_tick,
239 sqrt_price_next,
240 amount_in_with_fee,
241 amount_out,
242 };
243
244 gas_used = safe_add_u256(gas_used, U256::from(GAS_PER_SWAP_MATH_STEP))?;
245
246 if exact_input {
247 state.amount_remaining -=
248 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
249 .unwrap();
250 state.amount_calculated -=
251 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
252 } else {
253 state.amount_remaining +=
254 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
255 state.amount_calculated +=
256 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
257 .unwrap();
258 }
259 if state.sqrt_price == step.sqrt_price_next {
260 if let Some(info) = next_tick_info {
261 let liquidity_raw = info.net_liquidity;
262 let liquidity_net = if zero_for_one { -liquidity_raw } else { liquidity_raw };
263 state.liquidity =
264 liquidity_math::add_liquidity_delta(state.liquidity, liquidity_net)?;
265 gas_used = safe_add_u256(gas_used, U256::from(GAS_PER_INITIALIZED_TICK_CROSS))?;
266 }
267 state.tick =
268 PoolTick::from(if zero_for_one { step.tick_next - 1 } else { step.tick_next });
269 } else if state.sqrt_price != step.sqrt_price_start {
270 state.tick = PoolTick::at_sqrt_price(state.sqrt_price)?;
271 }
272 cache_run.cache_progress(&step, &state, gas_used);
273 }
274 Ok(SwapResults {
275 amount_calculated: state.amount_calculated,
276 amount_specified,
277 amount_remaining: state.amount_remaining,
278 sqrt_price: state.sqrt_price,
279 liquidity: state.liquidity,
280 tick: state.tick,
281 gas_used: safe_add_u256(gas_used, U256::from(V3_CALLBACK_SETTLEMENT_GAS))?,
282 })
283 }
284
285 fn get_sqrt_ratio_target(
286 sqrt_price_next: U256,
287 sqrt_price_limit: U256,
288 zero_for_one: bool,
289 ) -> U256 {
290 let cond1 = if zero_for_one {
291 sqrt_price_next < sqrt_price_limit
292 } else {
293 sqrt_price_next > sqrt_price_limit
294 };
295
296 if cond1 {
297 sqrt_price_limit
298 } else {
299 sqrt_price_next
300 }
301 }
302}
303
304#[typetag::serde]
305impl ProtocolSim for UniswapV3State {
306 fn fee(&self) -> f64 {
307 self.fee as f64 / 1_000_000.0
308 }
309
310 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
311 let price = if base < quote {
312 sqrt_price_q96_to_f64(self.sqrt_price, base.decimals, quote.decimals)?
313 } else {
314 1.0f64 / sqrt_price_q96_to_f64(self.sqrt_price, quote.decimals, base.decimals)?
315 };
316 Ok(add_fee_markup(price, self.fee()))
317 }
318
319 fn get_amount_out(
320 &self,
321 amount_in: BigUint,
322 token_in: &Token,
323 token_out: &Token,
324 ) -> Result<GetAmountOutResult, SimulationError> {
325 let zero_for_one = token_in < token_out;
326 let amount_specified =
327 I256::checked_from_sign_and_abs(Sign::Positive, biguint_to_uint(&amount_in)?)
328 .ok_or_else(|| {
329 SimulationError::InvalidInput("I256 overflow: amount_in".to_string(), None)
330 })?;
331
332 let result = self.swap(zero_for_one, amount_specified, None)?;
333
334 trace!(?amount_in, ?token_in, ?token_out, ?zero_for_one, ?result, "V3 SWAP");
335 let new_state = self.clone_post_swap(result.sqrt_price, result.tick, result.liquidity);
336
337 Ok(GetAmountOutResult::new(
338 u256_to_biguint(
339 result
340 .amount_calculated
341 .abs()
342 .into_raw(),
343 ),
344 u256_to_biguint(result.gas_used),
345 Box::new(new_state),
346 ))
347 }
348
349 fn get_limits(
350 &self,
351 sell_token: Bytes,
352 buy_token: Bytes,
353 ) -> Result<(BigUint, BigUint), SimulationError> {
354 if self.liquidity == 0 {
356 return Ok((BigUint::zero(), BigUint::zero()));
357 }
358
359 let zero_for_one = sell_token < buy_token;
360 let mut current_tick = self.tick.value();
361 let mut current_sqrt_price = self.sqrt_price;
362 let mut current_liquidity = self.liquidity;
363 let mut total_amount_in = U256::from(0u64);
364 let mut total_amount_out = U256::from(0u64);
365 let mut ticks_crossed: u64 = 0;
366
367 while let Ok((tick, next_tick_info)) = self
370 .ticks
371 .next_initialized_tick_within_one_word(current_tick, zero_for_one)
372 {
373 if ticks_crossed >= MAX_TICKS_CROSSED {
375 break;
376 }
377 ticks_crossed += 1;
378
379 let next_tick = tick.clamp(MIN_TICK, MAX_TICK);
381
382 let sqrt_price_next = match next_tick_info {
383 Some(info) => info.sqrt_price,
384 None => get_sqrt_ratio_at_tick_cached(next_tick)?,
385 };
386
387 let (amount_in, amount_out) = if zero_for_one {
390 let amount0 = get_amount0_delta(
391 sqrt_price_next,
392 current_sqrt_price,
393 current_liquidity,
394 true,
395 )?;
396 let amount1 = get_amount1_delta(
397 sqrt_price_next,
398 current_sqrt_price,
399 current_liquidity,
400 false,
401 )?;
402 (amount0, amount1)
403 } else {
404 let amount0 = get_amount0_delta(
405 sqrt_price_next,
406 current_sqrt_price,
407 current_liquidity,
408 false,
409 )?;
410 let amount1 = get_amount1_delta(
411 sqrt_price_next,
412 current_sqrt_price,
413 current_liquidity,
414 true,
415 )?;
416 (amount1, amount0)
417 };
418
419 total_amount_in = safe_add_u256(total_amount_in, amount_in)?;
421 total_amount_out = safe_add_u256(total_amount_out, amount_out)?;
422
423 if let Some(info) = next_tick_info {
428 let liquidity_raw = info.net_liquidity;
429 let liquidity_delta = if zero_for_one { -liquidity_raw } else { liquidity_raw };
430
431 match liquidity_math::add_liquidity_delta(current_liquidity, liquidity_delta) {
434 Ok(new_liquidity) => {
435 current_liquidity = new_liquidity;
436 }
437 Err(_) => {
438 break;
441 }
442 }
443 }
444
445 current_tick = if zero_for_one { next_tick - 1 } else { next_tick };
447 current_sqrt_price = sqrt_price_next;
448 }
449
450 Ok((u256_to_biguint(total_amount_in), u256_to_biguint(total_amount_out)))
451 }
452
453 fn delta_transition(
454 &mut self,
455 delta: ProtocolStateDelta,
456 _tokens: &HashMap<Bytes, Token>,
457 _balances: &Balances,
458 ) -> Result<(), TransitionError> {
459 self.step_cache = SwapStepCache::default();
461 if let Some(liquidity) = delta
463 .updated_attributes
464 .get("liquidity")
465 {
466 let liq_16_bytes = if liquidity.len() == 32 {
470 if liquidity == &Bytes::zero(32) {
472 Bytes::from([0; 16])
473 } else {
474 return Err(TransitionError::DecodeError(format!(
475 "Liquidity bytes too long for {liquidity}, expected 16",
476 )));
477 }
478 } else {
479 liquidity.clone()
480 };
481
482 self.liquidity = u128::try_from(liq_16_bytes)?;
483 }
484 if let Some(sqrt_price) = delta
485 .updated_attributes
486 .get("sqrt_price_x96")
487 {
488 self.sqrt_price = U256::from_be_slice(sqrt_price);
489 }
490 if let Some(tick) = delta.updated_attributes.get("tick") {
491 let ticks_4_bytes = if tick.len() == 32 {
495 if tick == &Bytes::zero(32) {
497 Bytes::from([0; 4])
498 } else {
499 return Err(TransitionError::DecodeError(format!(
500 "Tick bytes too long for {tick}, expected 4"
501 )));
502 }
503 } else {
504 tick.clone()
505 };
506 self.tick = i24_be_bytes_to_i32(&ticks_4_bytes).into();
507 }
508
509 for (key, value) in delta.updated_attributes.iter() {
511 if key.starts_with("ticks/") {
513 let parts: Vec<&str> = key.split('/').collect();
514 Arc::make_mut(&mut self.ticks)
515 .set_tick_liquidity(
516 parts[1]
517 .parse::<i32>()
518 .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
519 i128::try_from(value.clone())?,
520 )
521 .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
522 }
523 }
524 for key in delta.deleted_attributes.iter() {
526 if key.starts_with("ticks/") {
528 let parts: Vec<&str> = key.split('/').collect();
529 Arc::make_mut(&mut self.ticks)
530 .set_tick_liquidity(
531 parts[1]
532 .parse::<i32>()
533 .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
534 0,
535 )
536 .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
537 }
538 }
539 Ok(())
540 }
541
542 fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
547 if self.liquidity == 0 {
548 return Err(SimulationError::FatalError("No liquidity".to_string()));
549 }
550
551 match params.swap_constraint() {
552 SwapConstraint::TradeLimitPrice { .. } => Err(SimulationError::InvalidInput(
553 "Uniswap V3 does not support TradeLimitPrice constraint in query_pool_swap"
554 .to_string(),
555 None,
556 )),
557 SwapConstraint::PoolTargetPrice {
558 target,
559 tolerance: _,
560 min_amount_in: _,
561 max_amount_in: _,
562 } => {
563 let (amount_in, amount_out, swap_result) = clmm_swap_to_price(
564 self.sqrt_price,
565 ¶ms.token_in().address,
566 ¶ms.token_out().address,
567 target,
568 self.fee,
569 Sign::Positive,
570 |zero_for_one, amount_specified, sqrt_price_limit| {
571 self.swap(zero_for_one, amount_specified, Some(sqrt_price_limit))
572 },
573 )?;
574
575 let new_state = self.clone_post_swap(
576 swap_result.sqrt_price,
577 swap_result.tick,
578 swap_result.liquidity,
579 );
580
581 Ok(PoolSwap::new(amount_in, amount_out, Box::new(new_state), None))
582 }
583 }
584 }
585
586 fn clone_box(&self) -> Box<dyn ProtocolSim> {
587 Box::new(self.clone())
588 }
589
590 fn as_any(&self) -> &dyn Any {
591 self
592 }
593
594 fn as_any_mut(&mut self) -> &mut dyn Any {
595 self
596 }
597
598 fn eq(&self, other: &dyn ProtocolSim) -> bool {
599 if let Some(other_state) = other
600 .as_any()
601 .downcast_ref::<UniswapV3State>()
602 {
603 self.liquidity == other_state.liquidity &&
604 self.sqrt_price == other_state.sqrt_price &&
605 self.fee == other_state.fee &&
606 self.tick == other_state.tick &&
607 self.ticks == other_state.ticks
608 } else {
609 false
610 }
611 }
612}
613
614#[cfg(test)]
615mod tests {
616 use std::{
617 collections::{HashMap, HashSet},
618 fs,
619 path::Path,
620 str::FromStr,
621 };
622
623 use num_bigint::ToBigUint;
624 use num_traits::FromPrimitive;
625 use serde_json::Value;
626 use tycho_client::feed::synchronizer::ComponentWithState;
627 use tycho_common::{hex_bytes::Bytes, models::Chain, simulation::protocol_sim::Price};
628
629 use super::*;
630 use crate::{
631 evm::protocol::{
632 uniswap_v3::enums::FeeAmount,
633 utils::uniswap::{
634 sqrt_price_math::get_sqrt_price_q96,
635 tick_math::{get_sqrt_ratio_at_tick, get_tick_at_sqrt_ratio},
636 },
637 },
638 protocol::models::{DecoderContext, TryFromWithBlock},
639 };
640
641 fn serde_test_state(fee: impl Into<FeeTier>) -> UniswapV3State {
642 UniswapV3State::new(
643 1_000_000,
644 U256::from(79228162514264337593543950336u128),
645 fee,
646 0,
647 vec![TickInfo::new(-600, 1_000_000).unwrap(), TickInfo::new(600, -1_000_000).unwrap()],
648 )
649 .unwrap()
650 }
651
652 #[test]
653 fn test_serialize_fee_amount_fee_as_variant_name() {
654 let state = serde_test_state(FeeAmount::Medium);
655
656 let json = serde_json::to_value(&state).unwrap();
657
658 assert_eq!(json["fee"], Value::from("Medium"));
659 assert_eq!(serde_json::from_value::<UniswapV3State>(json).unwrap(), state);
660 }
661
662 #[test]
663 fn test_serialize_fee_outside_fee_amount_as_number() {
664 let state = serde_test_state(FeeTier::new(50, 10).unwrap());
665
666 let json = serde_json::to_value(&state).unwrap();
667
668 assert_eq!(json["fee"], Value::from(50));
669 assert_eq!(serde_json::from_value::<UniswapV3State>(json).unwrap(), state);
670 }
671
672 #[test]
673 fn test_deserialize_fee_as_number_for_fee_amount_fee() {
674 let state = serde_test_state(FeeAmount::Medium);
675 let mut json = serde_json::to_value(&state).unwrap();
676 json["fee"] = Value::from(3000);
677
678 assert_eq!(serde_json::from_value::<UniswapV3State>(json).unwrap(), state);
679 }
680
681 #[test]
682 fn test_deserialize_rejects_unknown_fee_name() {
683 let mut json = serde_json::to_value(serde_test_state(FeeAmount::Medium)).unwrap();
684 json["fee"] = Value::from("Unknown");
685
686 assert!(serde_json::from_value::<UniswapV3State>(json).is_err());
687 }
688
689 #[test]
690 fn test_get_amount_out_full_range_liquidity() {
691 let token_x = Token::new(
692 &Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap(),
693 "X",
694 18,
695 0,
696 &[Some(10_000)],
697 Chain::Ethereum,
698 100,
699 );
700 let token_y = Token::new(
701 &Bytes::from_str("0xf1ca9cb74685755965c7458528a36934df52a3ef").unwrap(),
702 "Y",
703 18,
704 0,
705 &[Some(10_000)],
706 Chain::Ethereum,
707 100,
708 );
709
710 let pool = UniswapV3State::new(
711 8330443394424070888454257,
712 U256::from_str("188562464004052255423565206602").unwrap(),
713 FeeAmount::Medium,
714 17342,
715 vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()],
716 )
717 .unwrap();
718 let sell_amount = BigUint::from_str("11_000_000000000000000000").unwrap();
719 let expected = BigUint::from_str("61927070842678722935941").unwrap();
720
721 let res = pool
722 .get_amount_out(sell_amount, &token_x, &token_y)
723 .unwrap();
724
725 assert_eq!(res.amount, expected);
726 }
727
728 #[test]
729 fn test_get_amount_out_refuses_amount_wider_than_uint256() {
730 let token_x = Token::new(
731 &Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap(),
732 "X",
733 18,
734 0,
735 &[Some(10_000)],
736 Chain::Ethereum,
737 100,
738 );
739 let token_y = Token::new(
740 &Bytes::from_str("0xf1ca9cb74685755965c7458528a36934df52a3ef").unwrap(),
741 "Y",
742 18,
743 0,
744 &[Some(10_000)],
745 Chain::Ethereum,
746 100,
747 );
748 let pool = UniswapV3State::new(
749 8330443394424070888454257,
750 U256::from_str("188562464004052255423565206602").unwrap(),
751 FeeAmount::Medium,
752 17342,
753 vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()],
754 )
755 .unwrap();
756
757 let res = pool.get_amount_out(BigUint::from(1u8) << 256, &token_x, &token_y);
758
759 assert!(matches!(res, Err(SimulationError::InvalidInput(..))));
760 }
761
762 struct SwapTestCase {
763 symbol: &'static str,
764 sell: BigUint,
765 exp: BigUint,
766 }
767
768 #[test]
769 fn test_get_amount_out() {
770 let wbtc = Token::new(
771 &Bytes::from_str("0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599").unwrap(),
772 "WBTC",
773 8,
774 0,
775 &[Some(10_000)],
776 Chain::Ethereum,
777 100,
778 );
779 let weth = Token::new(
780 &Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap(),
781 "WETH",
782 18,
783 0,
784 &[Some(10_000)],
785 Chain::Ethereum,
786 100,
787 );
788 let pool = UniswapV3State::new(
789 377952820878029838,
790 U256::from_str("28437325270877025820973479874632004").unwrap(),
791 FeeAmount::Low,
792 255830,
793 vec![
794 TickInfo::new(255760, 1759015528199933i128).unwrap(),
795 TickInfo::new(255770, 6393138051835308i128).unwrap(),
796 TickInfo::new(255780, 228206673808681i128).unwrap(),
797 TickInfo::new(255820, 1319490609195820i128).unwrap(),
798 TickInfo::new(255830, 678916926147901i128).unwrap(),
799 TickInfo::new(255840, 12208947683433103i128).unwrap(),
800 TickInfo::new(255850, 1177970713095301i128).unwrap(),
801 TickInfo::new(255860, 8752304680520407i128).unwrap(),
802 TickInfo::new(255880, 1486478248067104i128).unwrap(),
803 TickInfo::new(255890, 1878744276123248i128).unwrap(),
804 TickInfo::new(255900, 77340284046725227i128).unwrap(),
805 ],
806 )
807 .unwrap();
808 let cases = vec![
809 SwapTestCase {
810 symbol: "WBTC",
811 sell: 500000000.to_biguint().unwrap(),
812 exp: BigUint::from_str("64352395915550406461").unwrap(),
813 },
814 SwapTestCase {
815 symbol: "WBTC",
816 sell: 550000000.to_biguint().unwrap(),
817 exp: BigUint::from_str("70784271504035662865").unwrap(),
818 },
819 SwapTestCase {
820 symbol: "WBTC",
821 sell: 600000000.to_biguint().unwrap(),
822 exp: BigUint::from_str("77215534856185613494").unwrap(),
823 },
824 SwapTestCase {
825 symbol: "WBTC",
826 sell: BigUint::from_str("1000000000").unwrap(),
827 exp: BigUint::from_str("128643569649663616249").unwrap(),
828 },
829 SwapTestCase {
830 symbol: "WBTC",
831 sell: BigUint::from_str("3000000000").unwrap(),
832 exp: BigUint::from_str("385196519076234662939").unwrap(),
833 },
834 SwapTestCase {
835 symbol: "WETH",
836 sell: BigUint::from_str("64000000000000000000").unwrap(),
837 exp: BigUint::from_str("496294784").unwrap(),
838 },
839 SwapTestCase {
840 symbol: "WETH",
841 sell: BigUint::from_str("70000000000000000000").unwrap(),
842 exp: BigUint::from_str("542798479").unwrap(),
843 },
844 SwapTestCase {
845 symbol: "WETH",
846 sell: BigUint::from_str("77000000000000000000").unwrap(),
847 exp: BigUint::from_str("597047757").unwrap(),
848 },
849 SwapTestCase {
850 symbol: "WETH",
851 sell: BigUint::from_str("128000000000000000000").unwrap(),
852 exp: BigUint::from_str("992129037").unwrap(),
853 },
854 SwapTestCase {
855 symbol: "WETH",
856 sell: BigUint::from_str("385000000000000000000").unwrap(),
857 exp: BigUint::from_str("2978713582").unwrap(),
858 },
859 ];
860
861 for case in cases {
862 let (token_a, token_b) =
863 if case.symbol == "WBTC" { (&wbtc, &weth) } else { (&weth, &wbtc) };
864 let res = pool
865 .get_amount_out(case.sell, token_a, token_b)
866 .unwrap();
867
868 assert_eq!(res.amount, case.exp);
869 }
870 }
871
872 #[test]
873 fn test_err_with_partial_trade() {
874 let dai = Token::new(
875 &Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap(),
876 "DAI",
877 18,
878 0,
879 &[Some(10_000)],
880 Chain::Ethereum,
881 100,
882 );
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 pool = UniswapV3State::new(
893 73015811375239994,
894 U256::from_str("148273042406850898575413").unwrap(),
895 FeeAmount::High,
896 -263789,
897 vec![
898 TickInfo::new(-269600, 3612326326695492i128).unwrap(),
899 TickInfo::new(-268800, 1487613939516867i128).unwrap(),
900 TickInfo::new(-267800, 1557587121322546i128).unwrap(),
901 TickInfo::new(-267400, 424592076717375i128).unwrap(),
902 TickInfo::new(-267200, 11691597431643916i128).unwrap(),
903 TickInfo::new(-266800, -218742815100986i128).unwrap(),
904 TickInfo::new(-266600, 1118947532495477i128).unwrap(),
905 TickInfo::new(-266200, 1233064286622365i128).unwrap(),
906 TickInfo::new(-265000, 4252603063356107i128).unwrap(),
907 TickInfo::new(-263200, -351282010325232i128).unwrap(),
908 TickInfo::new(-262800, -2352011819117842i128).unwrap(),
909 TickInfo::new(-262600, -424592076717375i128).unwrap(),
910 TickInfo::new(-262200, -11923662433672566i128).unwrap(),
911 TickInfo::new(-261600, -2432911749667741i128).unwrap(),
912 TickInfo::new(-260200, -4032727022572273i128).unwrap(),
913 TickInfo::new(-260000, -22889492064625028i128).unwrap(),
914 TickInfo::new(-259400, -1557587121322546i128).unwrap(),
915 TickInfo::new(-259200, -1487613939516867i128).unwrap(),
916 TickInfo::new(-258400, -400137022888262i128).unwrap(),
917 ],
918 )
919 .unwrap();
920 let amount_in = BigUint::from_str("50000000000").unwrap();
921 let exp = BigUint::from_str("6820591625999718100883").unwrap();
922
923 let err = pool
924 .get_amount_out(amount_in, &usdc, &dai)
925 .unwrap_err();
926
927 match err {
928 SimulationError::InvalidInput(ref _err, ref amount_out_result) => {
929 match amount_out_result {
930 Some(amount_out_result) => {
931 assert_eq!(amount_out_result.amount, exp);
932 let new_state = amount_out_result
933 .new_state
934 .as_any()
935 .downcast_ref::<UniswapV3State>()
936 .unwrap();
937 assert_ne!(new_state.tick, pool.tick);
938 assert_ne!(new_state.liquidity, pool.liquidity);
939 }
940 _ => panic!("Partial amount out result is None. Expected partial result."),
941 }
942 }
943 SimulationError::FatalError(_) | SimulationError::RecoverableError(_) => {
944 panic!("Test failed: was expecting a SimulationError::InsufficientData")
945 }
946 }
947 }
948
949 #[test]
950 fn test_delta_transition_leaves_clones_ticks_unchanged() {
951 let original = UniswapV3State::new(
952 1000,
953 U256::from_str("1000").unwrap(),
954 FeeAmount::Low,
955 100,
956 vec![TickInfo::new(255760, 10000).unwrap(), TickInfo::new(255900, -10000).unwrap()],
957 )
958 .unwrap();
959 let mut updated = original.clone();
960 let delta = ProtocolStateDelta {
961 component_id: "State1".to_owned(),
962 updated_attributes: HashMap::from([(
963 "ticks/255760/net_liquidity".to_string(),
964 Bytes::from(20000_u64.to_be_bytes().to_vec()),
965 )]),
966 deleted_attributes: HashSet::new(),
967 };
968
969 updated
970 .delta_transition(delta, &HashMap::new(), &Balances::default())
971 .unwrap();
972
973 assert_eq!(
974 updated
975 .ticks
976 .get_tick(255760)
977 .unwrap()
978 .net_liquidity,
979 20000
980 );
981 assert_eq!(
982 original
983 .ticks
984 .get_tick(255760)
985 .unwrap()
986 .net_liquidity,
987 10000
988 );
989 }
990
991 #[test]
992 fn test_delta_transition() {
993 let mut pool = UniswapV3State::new(
994 1000,
995 U256::from_str("1000").unwrap(),
996 FeeAmount::Low,
997 100,
998 vec![TickInfo::new(255760, 10000).unwrap(), TickInfo::new(255900, -10000).unwrap()],
999 )
1000 .unwrap();
1001 let attributes: HashMap<String, Bytes> = [
1002 ("liquidity".to_string(), Bytes::from(2000_u64.to_be_bytes().to_vec())),
1003 ("sqrt_price_x96".to_string(), Bytes::from(1001_u64.to_be_bytes().to_vec())),
1004 ("tick".to_string(), Bytes::from(120_i32.to_be_bytes().to_vec())),
1005 (
1006 "ticks/-255760/net_liquidity".to_string(),
1007 Bytes::from(10200_u64.to_be_bytes().to_vec()),
1008 ),
1009 (
1010 "ticks/255900/net_liquidity".to_string(),
1011 Bytes::from(9800_u64.to_be_bytes().to_vec()),
1012 ),
1013 ]
1014 .into_iter()
1015 .collect();
1016 let delta = ProtocolStateDelta {
1017 component_id: "State1".to_owned(),
1018 updated_attributes: attributes,
1019 deleted_attributes: HashSet::new(),
1020 };
1021
1022 pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1023 .unwrap();
1024
1025 assert_eq!(pool.liquidity, 2000);
1026 assert_eq!(pool.sqrt_price, U256::from(1001));
1027 assert_eq!(pool.tick.value(), 120);
1028 assert_eq!(
1029 pool.ticks
1030 .get_tick(-255760)
1031 .unwrap()
1032 .net_liquidity,
1033 10200
1034 );
1035 assert_eq!(
1036 pool.ticks
1037 .get_tick(255900)
1038 .unwrap()
1039 .net_liquidity,
1040 9800
1041 );
1042 }
1043
1044 #[tokio::test]
1045 async fn test_get_limits() {
1046 use tycho_client::feed::dto;
1047 let project_root = env!("CARGO_MANIFEST_DIR");
1048 let asset_path =
1049 Path::new(project_root).join("tests/assets/decoder/uniswap_v3_snapshot.json");
1050 let json_data = fs::read_to_string(asset_path).expect("Failed to read test asset");
1051 let data: Value = serde_json::from_str(&json_data).expect("Failed to parse JSON");
1052 let state: ComponentWithState = serde_json::from_value::<dto::ComponentWithState>(data)
1053 .expect("Expected json to match ComponentWithState structure")
1054 .into();
1055
1056 let usv3_state = UniswapV3State::try_from_with_header(
1057 state,
1058 Default::default(),
1059 &Default::default(),
1060 &Default::default(),
1061 &DecoderContext::new(),
1062 )
1063 .await
1064 .unwrap();
1065
1066 let t0 = Token::new(
1067 &Bytes::from_str("0x2260fac5e5542a773aa44fbcfedf7c193bc2c599").unwrap(),
1068 "WBTC",
1069 8,
1070 0,
1071 &[Some(10_000)],
1072 Chain::Ethereum,
1073 100,
1074 );
1075 let t1 = Token::new(
1076 &Bytes::from_str("0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf").unwrap(),
1077 "cbBTC",
1078 8,
1079 0,
1080 &[Some(10_000)],
1081 Chain::Ethereum,
1082 100,
1083 );
1084
1085 let res = usv3_state
1086 .get_limits(t0.address.clone(), t1.address.clone())
1087 .unwrap();
1088
1089 assert_eq!(&res.0, &BigUint::from_u128(29160572556).unwrap());
1090
1091 let out = usv3_state
1092 .get_amount_out(res.0, &t0, &t1)
1093 .expect("swap for limit in didn't work");
1094
1095 let diff = if res.1 > out.amount { res.1 - out.amount } else { out.amount - res.1 };
1098 assert!(diff <= BigUint::from(1u64), "limit_out and amount_out differ by {diff}");
1099 }
1100
1101 fn create_basic_test_pool() -> UniswapV3State {
1103 let liquidity = 100_000_000_000_000_000_000u128; let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
1105 .expect("Failed to calculate sqrt price");
1106 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
1107
1108 let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
1109
1110 UniswapV3State::new(liquidity, sqrt_price, FeeAmount::Low, tick, ticks)
1111 .expect("Failed to create pool")
1112 }
1113
1114 fn create_tick_boundary_test_pool() -> UniswapV3State {
1115 let sqrt_price = get_sqrt_ratio_at_tick(0).expect("Failed to calculate sqrt price");
1116 let ticks = vec![TickInfo::new(-120, 0).unwrap(), TickInfo::new(120, 0).unwrap()];
1117
1118 UniswapV3State::new(100_000_000_000_000_000_000u128, sqrt_price, FeeAmount::Low, 0, ticks)
1119 .expect("Failed to create pool")
1120 }
1121
1122 #[test]
1123 fn test_partial_step_updates_tick_when_price_moves_without_crossing_initialized_tick() {
1124 let pool = create_tick_boundary_test_pool();
1125 let amount =
1126 I256::checked_from_sign_and_abs(Sign::Positive, U256::from(100_000_000_000_000_000u64))
1127 .unwrap();
1128
1129 let result = pool
1130 .swap(true, amount, None)
1131 .expect("swap should stay within the current liquidity range");
1132 let expected_tick =
1133 get_tick_at_sqrt_ratio(result.sqrt_price).expect("new sqrt price should map to a tick");
1134
1135 assert_ne!(result.sqrt_price, pool.sqrt_price);
1136 assert_ne!(result.sqrt_price, get_sqrt_ratio_at_tick(-120).unwrap());
1137 assert_ne!(expected_tick, pool.tick.value());
1138 assert_eq!(result.tick.value(), expected_tick);
1139 }
1140
1141 #[test]
1142 fn test_swap_keeps_boundary_tick_when_price_does_not_move() {
1143 let mut pool = create_tick_boundary_test_pool();
1144 pool.tick = PoolTick::from(-1);
1145 let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1u64)).unwrap();
1146
1147 let result = pool
1148 .swap(true, amount, None)
1149 .expect("swap should consume the input as fee without moving price");
1150
1151 assert_eq!(result.sqrt_price, pool.sqrt_price);
1152 assert_eq!(get_tick_at_sqrt_ratio(result.sqrt_price).unwrap(), 0);
1153 assert_eq!(result.tick, pool.tick);
1154 }
1155
1156 #[test]
1157 fn test_swap_basic() {
1158 let pool = create_basic_test_pool();
1159
1160 let amount_in =
1162 I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000000u64)).unwrap();
1163 let result = pool
1164 .swap(true, amount_in, None)
1165 .unwrap();
1166
1167 let expected_amount = U256::from(2000000u64);
1169 let actual_amount = result
1170 .amount_calculated
1171 .abs()
1172 .into_raw();
1173 assert_eq!(expected_amount - actual_amount, U256::from(1001u64));
1174 println!("Swap X->Y: amount_in={}, amount_out={}", amount_in, actual_amount);
1175 }
1176
1177 #[test]
1178 fn test_swap_to_price_basic() {
1179 let liquidity = 100_000_000_000_000_000_000u128;
1181 let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
1182 .expect("Failed to calculate sqrt price");
1183 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
1184 let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
1185
1186 let pool = UniswapV3State::new(liquidity, sqrt_price, FeeAmount::Medium, tick, ticks)
1187 .expect("Failed to create pool");
1188
1189 let token_x = Token::new(
1191 &Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap(),
1192 "X",
1193 18,
1194 0,
1195 &[Some(10_000)],
1196 Chain::Ethereum,
1197 100,
1198 );
1199 let token_y = Token::new(
1200 &Bytes::from_str("0x0000000000000000000000000000000000000002").unwrap(),
1201 "Y",
1202 18,
1203 0,
1204 &[Some(10_000)],
1205 Chain::Ethereum,
1206 100,
1207 );
1208
1209 let target_price =
1211 Price::new(2_000_000u64.to_biguint().unwrap(), 1_010_000u64.to_biguint().unwrap());
1212
1213 let trade = pool
1215 .query_pool_swap(&QueryPoolSwapParams::new(
1216 token_x,
1217 token_y,
1218 SwapConstraint::PoolTargetPrice {
1219 target: target_price,
1220 tolerance: 0f64,
1221 min_amount_in: None,
1222 max_amount_in: None,
1223 },
1224 ))
1225 .expect("swap_to_price failed");
1226
1227 let expected_amount_in =
1229 BigUint::from_str("246739021727519745").expect("Failed to parse expected amount_in");
1230 let expected_amount_out =
1231 BigUint::from_str("490291909043340795").expect("Failed to parse expected amount_out");
1232
1233 assert_eq!(
1234 trade.amount_in().clone(),
1235 expected_amount_in,
1236 "amount_in should match expected value"
1237 );
1238 assert_eq!(
1239 trade.amount_out().clone(),
1240 expected_amount_out,
1241 "amount_out should match expected value"
1242 );
1243 }
1244
1245 #[test]
1246 fn test_swap_to_price_price_too_high() {
1247 let pool = create_basic_test_pool();
1248
1249 let token_x = Token::new(
1250 &Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap(),
1251 "X",
1252 18,
1253 0,
1254 &[Some(10_000)],
1255 Chain::Ethereum,
1256 100,
1257 );
1258 let token_y = Token::new(
1259 &Bytes::from_str("0x0000000000000000000000000000000000000002").unwrap(),
1260 "Y",
1261 18,
1262 0,
1263 &[Some(10_000)],
1264 Chain::Ethereum,
1265 100,
1266 );
1267
1268 let target_price =
1270 Price::new(10_000_000u64.to_biguint().unwrap(), 1_000_000u64.to_biguint().unwrap());
1271
1272 let result = pool.query_pool_swap(&QueryPoolSwapParams::new(
1273 token_x,
1274 token_y,
1275 SwapConstraint::PoolTargetPrice {
1276 target: target_price,
1277 tolerance: 0f64,
1278 min_amount_in: None,
1279 max_amount_in: None,
1280 },
1281 ));
1282 assert!(result.is_err(), "Should return error when target price is unreachable");
1283 }
1284
1285 #[test]
1286 fn test_swap_parameterized() {
1287 let liquidity = 377_952_820_878_029_838u128;
1289 let sqrt_price = U256::from_str("28437325270877025820973479874632004")
1290 .expect("Failed to parse sqrt_price");
1291 let tick = 255830;
1292
1293 let ticks = vec![
1294 TickInfo::new(255760, 1_759_015_528_199_933).unwrap(),
1295 TickInfo::new(255770, 6_393_138_051_835_308).unwrap(),
1296 TickInfo::new(255780, 228_206_673_808_681).unwrap(),
1297 TickInfo::new(255820, 1_319_490_609_195_820).unwrap(),
1298 TickInfo::new(255830, 678_916_926_147_901).unwrap(),
1299 TickInfo::new(255840, 12_208_947_683_433_103).unwrap(),
1300 TickInfo::new(255850, 1_177_970_713_095_301).unwrap(),
1301 TickInfo::new(255860, 8_752_304_680_520_407).unwrap(),
1302 TickInfo::new(255880, 1_486_478_248_067_104).unwrap(),
1303 TickInfo::new(255890, 1_878_744_276_123_248).unwrap(),
1304 TickInfo::new(255900, 77_340_284_046_725_227).unwrap(),
1305 ];
1306
1307 let pool = UniswapV3State::new(liquidity, sqrt_price, FeeAmount::Low, tick, ticks)
1308 .expect("Failed to create pool");
1309
1310 let test_cases = vec![
1313 (true, "500000000", "64352395915550406461", "WBTC->WETH 500000000"),
1315 (true, "550000000", "70784271504035662865", "WBTC->WETH 550000000"),
1316 (true, "600000000", "77215534856185613494", "WBTC->WETH 600000000"),
1317 (true, "1000000000", "128643569649663616249", "WBTC->WETH 1000000000"),
1318 (true, "3000000000", "385196519076234662939", "WBTC->WETH 3000000000"),
1319 (false, "64000000000000000000", "496294784", "WETH->WBTC 64 ETH"),
1321 (false, "70000000000000000000", "542798479", "WETH->WBTC 70 ETH"),
1322 (false, "77000000000000000000", "597047757", "WETH->WBTC 77 ETH"),
1323 (false, "128000000000000000000", "992129037", "WETH->WBTC 128 ETH"),
1324 (false, "385000000000000000000", "2978713582", "WETH->WBTC 385 ETH"),
1325 ];
1326
1327 for (zero_for_one, amount_in_str, expected_amount_out_str, test_id) in test_cases {
1328 let amount_in = U256::from_str(amount_in_str).expect("Failed to parse amount_in");
1329 let amount_specified = I256::checked_from_sign_and_abs(Sign::Positive, amount_in)
1330 .unwrap_or_else(|| panic!("{} - Failed to convert amount to I256", test_id));
1331
1332 let result = pool
1333 .swap(zero_for_one, amount_specified, None)
1334 .unwrap_or_else(|e| panic!("{} - swap failed: {:?}", test_id, e));
1335
1336 let amount_out = result
1337 .amount_calculated
1338 .abs()
1339 .into_raw();
1340 let expected = U256::from_str(expected_amount_out_str)
1341 .expect("Failed to parse expected_amount_out");
1342
1343 assert_eq!(amount_out, expected, "{}", test_id);
1344 }
1345 }
1346
1347 #[test]
1348 fn test_swap_to_price_parameterized() {
1349 let wbtc = Token::new(
1351 &Bytes::from_str("0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599").unwrap(),
1352 "WBTC",
1353 8,
1354 0,
1355 &[Some(10_000)],
1356 Chain::Ethereum,
1357 100,
1358 );
1359 let weth = Token::new(
1360 &Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap(),
1361 "WETH",
1362 18,
1363 0,
1364 &[Some(10_000)],
1365 Chain::Ethereum,
1366 100,
1367 );
1368
1369 let liquidity = 377_952_820_878_029_838u128;
1370 let sqrt_price = get_sqrt_price_q96(U256::from(130_000_000u64), U256::from(10_000_000u64))
1371 .expect("Failed to calculate sqrt price");
1372 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
1373
1374 let ticks = vec![
1375 TickInfo::new(25560, 1759015528199933).unwrap(),
1376 TickInfo::new(25570, 6393138051835308).unwrap(),
1377 TickInfo::new(25580, 228206673808681).unwrap(),
1378 TickInfo::new(25620, 1319490609195820).unwrap(),
1379 TickInfo::new(25630, 678916926147901).unwrap(),
1380 TickInfo::new(25640, 12208947683433103).unwrap(),
1381 TickInfo::new(25660, 8752304680520407).unwrap(),
1382 TickInfo::new(25680, 1486478248067104).unwrap(),
1383 TickInfo::new(25690, 1878744276123248).unwrap(),
1384 TickInfo::new(25700, 77340284046725227).unwrap(),
1385 ];
1386
1387 let pool = UniswapV3State::new(liquidity, sqrt_price, FeeAmount::Low, tick, ticks)
1388 .expect("Failed to create pool");
1389
1390 let test_cases = vec![
1392 (&wbtc, 129u64, 10u64, "0", "WBTC sell_price=129, buy_price=10"),
1393 (&wbtc, 130u64, 10u64, "0", "WBTC sell_price=130, buy_price=10"),
1394 (&wbtc, 1305u64, 100u64, "163535995630461", "WBTC sell_price=1305, buy_price=100"),
1395 (&weth, 99u64, 1300u64, "0", "WETH sell_price=99, buy_price=1300"),
1396 (&weth, 100u64, 1300u64, "0", "WETH sell_price=100, buy_price=1300"),
1397 (&weth, 101u64, 1299u64, "524227092059180", "WETH sell_price=101, buy_price=1299"),
1398 ];
1399
1400 for (sell_token, sell_price, buy_price, expected_str, test_id) in test_cases {
1401 let buy_token = if sell_token == &wbtc { &weth } else { &wbtc };
1402
1403 let target_price =
1404 Price::new(buy_price.to_biguint().unwrap(), sell_price.to_biguint().unwrap());
1405
1406 if expected_str == "0" {
1407 let result = pool.query_pool_swap(&QueryPoolSwapParams::new(
1408 buy_token.clone(),
1409 sell_token.clone(),
1410 SwapConstraint::PoolTargetPrice {
1411 target: target_price,
1412 tolerance: 0f64,
1413 min_amount_in: None,
1414 max_amount_in: None,
1415 },
1416 ));
1417 assert!(result.is_err(), "Should return error when target price is unreachable");
1418 } else {
1419 let expected =
1420 BigUint::from_str(expected_str).expect("Failed to parse expected value");
1421
1422 let trade = pool
1423 .query_pool_swap(&QueryPoolSwapParams::new(
1424 buy_token.clone(),
1425 sell_token.clone(),
1426 SwapConstraint::PoolTargetPrice {
1427 target: target_price,
1428 tolerance: 0f64,
1429 min_amount_in: None,
1430 max_amount_in: None,
1431 },
1432 ))
1433 .unwrap_or_else(|e| panic!("{} - query_supply failed: {:?}", test_id, e));
1434 assert_eq!(trade.amount_out().clone(), expected, "{}", test_id);
1435 }
1436 }
1437 }
1438
1439 #[test]
1440 fn test_swap_to_price_around_spot_price() {
1441 let liquidity = 10_000_000_000_000_000u128;
1443 let sqrt_price =
1444 get_sqrt_price_q96(U256::from(2_000_000_000u64), U256::from(1_000_000_000u64))
1445 .expect("Failed to calculate sqrt price");
1446 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
1447
1448 let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
1449
1450 let pool = UniswapV3State::new(liquidity, sqrt_price, FeeAmount::Low, tick, ticks)
1451 .expect("Failed to create pool");
1452
1453 let token_x = Token::new(
1454 &Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap(),
1455 "X",
1456 18,
1457 0,
1458 &[Some(10_000)],
1459 Chain::Ethereum,
1460 100,
1461 );
1462 let token_y = Token::new(
1463 &Bytes::from_str("0x0000000000000000000000000000000000000002").unwrap(),
1464 "Y",
1465 18,
1466 0,
1467 &[Some(10_000)],
1468 Chain::Ethereum,
1469 100,
1470 );
1471
1472 let target_price =
1474 Price::new(1_999_750u64.to_biguint().unwrap(), 1_000_250u64.to_biguint().unwrap());
1475
1476 let result = pool.query_pool_swap(&QueryPoolSwapParams::new(
1477 token_x.clone(),
1478 token_y.clone(),
1479 SwapConstraint::PoolTargetPrice {
1480 target: target_price,
1481 tolerance: 0f64,
1482 min_amount_in: None,
1483 max_amount_in: None,
1484 },
1485 ));
1486 assert!(result.is_err(), "Should return error when target price is unreachable");
1487
1488 let target_price =
1490 Price::new(1_999_000u64.to_biguint().unwrap(), 1_001_000u64.to_biguint().unwrap());
1491
1492 let pool_swap = pool
1493 .query_pool_swap(&QueryPoolSwapParams::new(
1494 token_x,
1495 token_y,
1496 SwapConstraint::PoolTargetPrice {
1497 target: target_price,
1498 tolerance: 0f64,
1499 min_amount_in: None,
1500 max_amount_in: None,
1501 },
1502 ))
1503 .expect("swap_to_price failed");
1504
1505 let expected_amount_out =
1506 BigUint::from_str("7062236922008").expect("Failed to parse expected value");
1507 assert_eq!(
1508 pool_swap.amount_out().clone(),
1509 expected_amount_out,
1510 "Expected amount out when price covers fees"
1511 );
1512 }
1513
1514 #[test]
1515 fn test_swap_to_price_matches_get_amount_out() {
1516 let liquidity = 100_000_000_000_000_000_000u128;
1517 let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
1518 .expect("Failed to calculate sqrt price");
1519 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
1520
1521 let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
1522
1523 let pool = UniswapV3State::new(liquidity, sqrt_price, FeeAmount::Medium, tick, ticks)
1524 .expect("Failed to create pool");
1525
1526 let token_x_addr = Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap();
1527 let token_y_addr = Bytes::from_str("0x0000000000000000000000000000000000000002").unwrap();
1528
1529 let token_x = Token::new(&token_x_addr, "X", 18, 0, &[], Chain::Ethereum, 1);
1530 let token_y = Token::new(&token_y_addr, "Y", 18, 0, &[], Chain::Ethereum, 1);
1531
1532 let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_010_000u64));
1534 let pool_swap = pool
1535 .query_pool_swap(&QueryPoolSwapParams::new(
1536 token_x.clone(),
1537 token_y.clone(),
1538 SwapConstraint::PoolTargetPrice {
1539 target: target_price,
1540 tolerance: 0f64,
1541 min_amount_in: None,
1542 max_amount_in: None,
1543 },
1544 ))
1545 .expect("swap_to_price failed");
1546 assert!(pool_swap.amount_in().clone() > BigUint::ZERO, "Amount in should be positive");
1547
1548 let result = pool
1550 .get_amount_out(pool_swap.amount_in().clone(), &token_x, &token_y)
1551 .expect("get_amount_out failed");
1552
1553 assert!(result.amount > BigUint::ZERO);
1556 assert!(result.amount >= *pool_swap.amount_out());
1557 }
1558
1559 #[test]
1560 fn test_swap_price_limit_out_of_range_returns_error() {
1561 let pool = create_basic_test_pool();
1562 let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
1563
1564 let result = pool.swap(true, amount, Some(pool.sqrt_price));
1566 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1567
1568 let result = pool.swap(true, amount, Some(MIN_SQRT_RATIO));
1570 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1571
1572 let result = pool.swap(false, amount, Some(pool.sqrt_price));
1574 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1575
1576 let result = pool.swap(false, amount, Some(MAX_SQRT_RATIO));
1578 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1579 }
1580
1581 #[test]
1582 fn test_swap_at_extreme_price_returns_error() {
1583 let sqrt_price = MIN_SQRT_RATIO + U256::from(1u64);
1586 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
1587 let aligned_tick = (MIN_TICK / 10) * 10 + 10; let ticks = vec![
1590 TickInfo::new(aligned_tick, 0).unwrap(),
1591 TickInfo::new(aligned_tick + 10, 0).unwrap(),
1592 ];
1593 let pool = UniswapV3State::new(
1594 100_000_000_000_000_000_000u128,
1595 sqrt_price,
1596 FeeAmount::Low,
1597 tick,
1598 ticks,
1599 )
1600 .unwrap();
1601
1602 let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
1603 let result = pool.swap(true, amount, None);
1605 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1606 }
1607}
1608
1609#[cfg(test)]
1610mod tests_forks {
1611 use std::str::FromStr;
1612
1613 use tycho_client::feed::synchronizer::ComponentWithState;
1614 use tycho_common::{hex_bytes::Bytes, models::Chain};
1615
1616 use super::*;
1617 use crate::{
1618 evm::protocol::uniswap_v3::enums::FeeAmount,
1619 protocol::models::{DecoderContext, TryFromWithBlock},
1620 };
1621
1622 #[tokio::test]
1623 async fn test_pancakeswap_get_amount_out() {
1624 use std::{fs, path::Path};
1625
1626 use serde_json::Value;
1627 use tycho_client::feed::dto;
1628 let project_root = env!("CARGO_MANIFEST_DIR");
1629 let asset_path =
1630 Path::new(project_root).join("tests/assets/decoder/pancakeswap_v3_snapshot.json");
1631 let json_data = fs::read_to_string(asset_path).expect("Failed to read test asset");
1632 let data: Value = serde_json::from_str(&json_data).expect("Failed to parse JSON");
1633 let state: ComponentWithState = serde_json::from_value::<dto::ComponentWithState>(data)
1634 .expect("Expected json to match ComponentWithState structure")
1635 .into();
1636
1637 let pool_state = UniswapV3State::try_from_with_header(
1638 state,
1639 Default::default(),
1640 &Default::default(),
1641 &Default::default(),
1642 &DecoderContext::new(),
1643 )
1644 .await
1645 .unwrap();
1646
1647 let usdc = Token::new(
1648 &Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap(),
1649 "USDC",
1650 6,
1651 0,
1652 &[Some(10_000)],
1653 Chain::Ethereum,
1654 100,
1655 );
1656 let usdt = Token::new(
1657 &Bytes::from_str("0xdac17f958d2ee523a2206206994597c13d831ec7").unwrap(),
1658 "USDT",
1659 6,
1660 0,
1661 &[Some(10_000)],
1662 Chain::Ethereum,
1663 100,
1664 );
1665
1666 let res = pool_state
1667 .get_amount_out(BigUint::from_str("5976361609").unwrap(), &usdt, &usdc)
1668 .unwrap();
1669
1670 assert_eq!(res.amount, BigUint::from_str("5975901673").unwrap());
1671 }
1672
1673 #[test]
1674 fn test_get_limits_graceful_underflow() {
1675 let pool = UniswapV3State::new(
1677 1000000,
1678 U256::from_str("79228162514264337593543950336").unwrap(),
1679 FeeAmount::Medium,
1680 0,
1681 vec![
1682 TickInfo::new(-60, 2000000).unwrap(), ],
1686 )
1687 .unwrap();
1688
1689 let usdc = Token::new(
1690 &Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap(),
1691 "USDC",
1692 6,
1693 0,
1694 &[Some(10_000)],
1695 Chain::Ethereum,
1696 100,
1697 );
1698 let weth = Token::new(
1699 &Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(),
1700 "WETH",
1701 18,
1702 0,
1703 &[Some(10_000)],
1704 Chain::Ethereum,
1705 100,
1706 );
1707
1708 let (limit_in, limit_out) = pool
1709 .get_limits(usdc.address, weth.address)
1710 .unwrap();
1711
1712 assert!(limit_in > BigUint::zero());
1714 assert!(limit_out > BigUint::zero());
1715 }
1716}
1717
1718#[cfg(test)]
1719mod step_cache_tests {
1720 use std::{
1721 collections::{HashMap, HashSet},
1722 str::FromStr,
1723 };
1724
1725 use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
1726
1727 use super::*;
1728 use crate::evm::protocol::{
1729 uniswap_v3::enums::FeeAmount,
1730 utils::uniswap::swap_step_cache::test_fixtures::{
1731 amount_orders, test_amounts, test_ticks, wbtc_weth, LIQUIDITY, SQRT_PRICE, TICK,
1732 },
1733 };
1734
1735 fn test_pool() -> UniswapV3State {
1736 UniswapV3State::new(
1737 LIQUIDITY,
1738 U256::from_str(SQRT_PRICE).unwrap(),
1739 FeeAmount::Low,
1740 TICK,
1741 test_ticks(),
1742 )
1743 .unwrap()
1744 }
1745
1746 fn format_quote_result(
1748 pool: &UniswapV3State,
1749 amount: &BigUint,
1750 sell: &Token,
1751 buy: &Token,
1752 ) -> String {
1753 match pool.get_amount_out(amount.clone(), sell, buy) {
1754 Ok(result) => {
1755 let state = result
1756 .new_state
1757 .as_any()
1758 .downcast_ref::<UniswapV3State>()
1759 .unwrap();
1760 format!(
1761 "{} {} {} {} {}",
1762 result.amount,
1763 result.gas,
1764 state.sqrt_price,
1765 state.tick.value(),
1766 state.liquidity
1767 )
1768 }
1769 Err(error) => format!("error {error}"),
1770 }
1771 }
1772
1773 #[test]
1774 fn test_step_cache_quotes_match_a_fresh_state_in_any_order() {
1775 let (wbtc, weth) = wbtc_weth();
1776 for (sell, buy, smallest) in [(&wbtc, &weth, 1_000u64), (&weth, &wbtc, 1_000_000_000)] {
1777 for order in amount_orders(&test_amounts(smallest)) {
1778 let shared = test_pool();
1779 for amount in &order {
1780 assert_eq!(
1781 format_quote_result(&shared, amount, sell, buy),
1782 format_quote_result(&test_pool(), amount, sell, buy),
1783 "selling {amount} {}",
1784 sell.symbol
1785 );
1786 }
1787 let steps = shared
1788 .step_cache
1789 .min_inputs(sell < buy)
1790 .len();
1791 assert!(steps > 2, "only {steps} steps cached");
1792 }
1793 }
1794 }
1795
1796 #[test]
1797 fn test_step_cache_quotes_match_a_fresh_state_at_each_cached_step() {
1798 let (wbtc, weth) = wbtc_weth();
1799 for (sell, buy, doublings) in [(&wbtc, &weth, 30u32), (&weth, &wbtc, 70)] {
1802 let cached = test_pool();
1803 #[expect(
1804 clippy::let_underscore_must_use,
1805 reason = "the quote may run out of liquidity; only the step cache it fills is used"
1806 )]
1807 let _ = cached.get_amount_out(BigUint::from(10u32) << doublings, sell, buy);
1808 let boundaries = cached.step_cache.min_inputs(sell < buy);
1809 assert!(boundaries.len() > 2, "only {} steps cached", boundaries.len());
1810 for boundary in boundaries.into_iter().skip(1) {
1811 for amount in [boundary - U256::from(1u64), boundary, boundary + U256::from(1u64)] {
1812 let amount = u256_to_biguint(amount);
1813 assert_eq!(
1814 format_quote_result(&cached, &amount, sell, buy),
1815 format_quote_result(&test_pool(), &amount, sell, buy),
1816 "selling {amount} {}",
1817 sell.symbol
1818 );
1819 }
1820 }
1821 }
1822 }
1823
1824 #[test]
1825 fn test_step_cache_of_a_swapped_state() {
1826 let (wbtc, weth) = wbtc_weth();
1827 let pool = test_pool();
1828 let swapped = pool
1829 .get_amount_out(BigUint::from(300_000_000u64), &wbtc, &weth)
1830 .unwrap()
1831 .new_state;
1832 let swapped = swapped
1833 .as_any()
1834 .downcast_ref::<UniswapV3State>()
1835 .unwrap();
1836 let fresh: UniswapV3State =
1838 serde_json::from_value(serde_json::to_value(swapped).unwrap()).unwrap();
1839
1840 for amount in test_amounts(1_000).iter().rev() {
1841 assert_eq!(
1842 format_quote_result(swapped, amount, &wbtc, &weth),
1843 format_quote_result(&fresh, amount, &wbtc, &weth),
1844 "selling {amount} WBTC"
1845 );
1846 }
1847 }
1848
1849 #[test]
1850 fn test_step_cache_restarts_after_delta_transition() {
1851 let (wbtc, weth) = wbtc_weth();
1852 let large = BigUint::from(3_000_000_000u64);
1853 let delta = || ProtocolStateDelta {
1856 component_id: "State1".to_owned(),
1857 updated_attributes: HashMap::from([(
1858 "ticks/255820/net_liquidity".to_string(),
1859 Bytes::from(
1860 1_000_000_000_000_000i128
1861 .to_be_bytes()
1862 .to_vec(),
1863 ),
1864 )]),
1865 deleted_attributes: HashSet::new(),
1866 };
1867 let mut cached = test_pool();
1868 cached
1869 .get_amount_out(large.clone(), &wbtc, &weth)
1870 .unwrap();
1871 let mut fresh = test_pool();
1872
1873 cached
1874 .delta_transition(delta(), &HashMap::new(), &Balances::default())
1875 .unwrap();
1876 fresh
1877 .delta_transition(delta(), &HashMap::new(), &Balances::default())
1878 .unwrap();
1879
1880 assert_eq!(
1881 format_quote_result(&cached, &large, &wbtc, &weth),
1882 format_quote_result(&fresh, &large, &wbtc, &weth)
1883 );
1884 }
1885}