1use std::{any::Any, borrow::Cow, collections::HashMap, fmt, sync::Arc};
2
3use alloy::primitives::{Address, Sign, I256, U256};
4use num_bigint::BigUint;
5use num_traits::{CheckedSub, ToPrimitive, Zero};
6use revm::primitives::I128;
7use serde::{Deserialize, Serialize};
8use tracing::trace;
9use tycho_common::{
10 dto::ProtocolStateDelta,
11 models::token::Token,
12 simulation::{
13 errors::{SimulationError, TransitionError},
14 protocol_sim::{
15 Balances, BlockContext, GetAmountOutResult, PoolSwap, ProtocolSim, QueryPoolSwapParams,
16 SwapConstraint,
17 },
18 },
19 Bytes,
20};
21
22use super::hooks::utils::HookOptions;
23use crate::{
24 evm::{
25 protocol::{
26 clmm::clmm_swap_to_price,
27 safe_math::{safe_add_u256, safe_sub_u256},
28 u256_num::{biguint_to_uint, u256_to_biguint, u256_to_f64},
29 uniswap_v4::hooks::{
30 hook_handler::HookHandler,
31 models::{
32 AfterSwapParameters, BalanceDelta, BeforeSwapDelta, BeforeSwapParameters,
33 StateContext, SwapOutcome, SwapParams,
34 },
35 },
36 utils::{
37 add_fee_markup,
38 uniswap::{
39 i24_be_bytes_to_i32,
40 lp_fee::{self, is_dynamic},
41 pool_tick::PoolTick,
42 sqrt_price_math::{
43 get_amount0_delta, get_amount1_delta, sqrt_price_q96_to_f64,
44 },
45 swap_math::{self, SwapStepResult},
46 swap_step_cache::{StepCacheKey, StepCacheRun, SwapStepCache},
47 tick_list::{TickInfo, TickList, TickListErrorKind},
48 tick_math::{
49 get_sqrt_ratio_at_tick_cached, MAX_SQRT_RATIO, MAX_TICK, MIN_SQRT_RATIO,
50 MIN_TICK,
51 },
52 StepComputation, SwapResults, SwapState, FEE_PIPS_DENOMINATOR,
53 },
54 },
55 vm::constants::EXTERNAL_ACCOUNT,
56 },
57 simulation::PendingOverrides,
58 },
59 utils::decimals_exponent,
60};
61
62#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
66pub struct SwapGasCosts {
67 pub base: u64,
70 pub per_bitmap_lookup: u64,
72 pub per_tick: u64,
74 pub settlement: u64,
76}
77
78impl SwapGasCosts {
79 pub const UNISWAP_V4: Self =
84 Self { base: 150_000, per_bitmap_lookup: 3_500, per_tick: 29_000, settlement: 30_000 };
85
86 pub const PANCAKESWAP_INFINITY_CL: Self =
92 Self { base: 150_000, per_bitmap_lookup: 6_100, per_tick: 23_500, settlement: 30_000 };
93
94 fn max_ticks_crossed(&self) -> u64 {
96 (MAX_SWAP_GAS - self.base) / self.per_tick
97 }
98}
99
100fn uniswap_v4_gas_costs() -> SwapGasCosts {
101 SwapGasCosts::UNISWAP_V4
102}
103
104pub(crate) const PM_PER_HOOK_CALL_OVERHEAD: u64 = 25_000;
108const MAX_SWAP_GAS: u64 = 16_700_000;
110const HOOK_FEE_PROBE_EXP: u64 = 30;
115const PRICE_WALK_BUDGET: I256 = I256::from_raw(U256::from_limbs([0, 0, 0, 1 << 8]));
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub(crate) struct PriceWalk {
127 pub(crate) amount_in: U256,
129 pub(crate) liquidity: u128,
132 pub(crate) amount_out: U256,
134}
135
136#[derive(Clone, Deserialize)]
138#[serde(try_from = "UniswapV4StateData<'static>")]
139#[expect(
140 clippy::partial_pub_fields,
141 reason = "public API; making `hook` private or the rest public is a breaking change"
142)]
143pub struct UniswapV4State {
144 liquidity: u128,
145 sqrt_price: U256,
146 fees: UniswapV4Fees,
147 tick: PoolTick,
148 ticks: Arc<TickList>,
152 tick_spacing: i32,
153 gas_costs: SwapGasCosts,
154 pub hook: Option<Box<dyn HookHandler>>,
155 pending_overrides: Option<Arc<PendingOverrides>>,
158 step_cache: SwapStepCache,
163}
164
165#[derive(Serialize, Deserialize)]
166struct UniswapV4StateData<'a> {
167 liquidity: u128,
168 sqrt_price: U256,
169 fees: Cow<'a, UniswapV4Fees>,
170 tick: i32,
171 tick_spacing: i32,
172 ticks: Cow<'a, [TickInfo]>,
173 #[serde(default = "uniswap_v4_gas_costs")]
176 gas_costs: SwapGasCosts,
177}
178
179impl TryFrom<UniswapV4StateData<'_>> for UniswapV4State {
180 type Error = SimulationError;
181
182 fn try_from(data: UniswapV4StateData<'_>) -> Result<Self, Self::Error> {
183 let mut state = UniswapV4State::new(
184 data.liquidity,
185 data.sqrt_price,
186 data.fees.into_owned(),
187 data.tick,
188 data.tick_spacing,
189 data.ticks.into_owned(),
190 )?;
191 state.set_gas_costs(data.gas_costs);
192 Ok(state)
193 }
194}
195
196impl Serialize for UniswapV4State {
197 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
198 if self.hook.is_some() {
199 return Err(serde::ser::Error::custom(
200 "UniswapV4State with a hook cannot be serialized: HookHandler is a trait object",
201 ));
202 }
203 UniswapV4StateData {
204 liquidity: self.liquidity,
205 sqrt_price: self.sqrt_price,
206 fees: Cow::Borrowed(&self.fees),
207 tick: self.tick.value(),
208 tick_spacing: self.tick_spacing,
209 ticks: Cow::Borrowed(self.ticks.ticks()),
210 gas_costs: self.gas_costs,
211 }
212 .serialize(serializer)
213 }
214}
215
216impl fmt::Debug for UniswapV4State {
217 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218 f.debug_struct("UniswapV4State")
219 .field("liquidity", &self.liquidity)
220 .field("sqrt_price", &self.sqrt_price)
221 .field("fees", &self.fees)
222 .field("tick", &self.tick)
223 .field("tick_spacing", &self.tick_spacing)
224 .field("gas_costs", &self.gas_costs)
225 .field("pending_overrides", &self.pending_overrides.is_some())
226 .finish_non_exhaustive()
227 }
228}
229
230impl PartialEq for UniswapV4State {
231 fn eq(&self, other: &Self) -> bool {
232 match (&self.hook, &other.hook) {
233 (Some(a), Some(b)) => a.is_equal(&**b),
234 (None, None) => true,
235 _ => false,
236 }
237 }
238}
239
240impl Eq for UniswapV4State {}
241
242#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
243pub struct UniswapV4Fees {
244 pub zero_for_one: u32,
246 pub one_for_zero: u32,
248 pub lp_fee: u32,
250}
251
252impl UniswapV4Fees {
253 pub fn new(zero_for_one: u32, one_for_zero: u32, lp_fee: u32) -> Self {
254 Self { zero_for_one, one_for_zero, lp_fee }
255 }
256
257 fn calculate_swap_fees_pips(
258 &self,
259 zero_for_one: bool,
260 lp_fee_override: Option<u32>,
261 ) -> Result<u32, SimulationError> {
262 let protocol_fee = if zero_for_one { self.zero_for_one } else { self.one_for_zero };
263 let lp_fee = lp_fee_override.unwrap_or_else(|| {
264 if is_dynamic(self.lp_fee) {
266 0
267 } else {
268 self.lp_fee
269 }
270 });
271
272 let overlap = u64::from(protocol_fee) * u64::from(lp_fee) / 1_000_000;
277 u32::try_from(u64::from(protocol_fee) + u64::from(lp_fee) - overlap).map_err(|e| {
278 SimulationError::InvalidInput(
279 format!("swap fee for protocol fee {protocol_fee} and lp fee {lp_fee}: {e}"),
280 None,
281 )
282 })
283 }
284}
285
286impl UniswapV4State {
287 pub fn new(
289 liquidity: u128,
290 sqrt_price: U256,
291 fees: UniswapV4Fees,
292 tick: i32,
293 tick_spacing: i32,
294 ticks: Vec<TickInfo>,
295 ) -> Result<Self, SimulationError> {
296 let tick_spacing_u16 = tick_spacing
297 .try_into()
298 .map_err(|_out_of_range| {
299 SimulationError::FatalError(format!(
302 "tick_spacing {} must be positive (int24 -> u16 conversion failed)",
303 tick_spacing
304 ))
305 })?;
306 let tick_list = TickList::from(tick_spacing_u16, ticks)?;
307 Ok(UniswapV4State {
308 liquidity,
309 sqrt_price,
310 fees,
311 tick: tick.into(),
312 ticks: Arc::new(tick_list),
313 tick_spacing,
314 gas_costs: SwapGasCosts::UNISWAP_V4,
315 hook: None,
316 pending_overrides: None,
317 step_cache: SwapStepCache::default(),
318 })
319 }
320
321 pub(crate) fn price_and_tick(&self) -> (U256, i32) {
323 (self.sqrt_price, self.tick.value())
324 }
325
326 pub fn pending_overrides(&self) -> Option<&PendingOverrides> {
327 self.pending_overrides.as_deref()
328 }
329
330 pub fn set_gas_costs(&mut self, gas_costs: SwapGasCosts) {
332 self.gas_costs = gas_costs;
333 self.step_cache = SwapStepCache::default();
334 }
335
336 fn clone_post_swap(&self, sqrt_price: U256, tick: PoolTick, liquidity: u128) -> Self {
339 let mut state = self.clone();
340 state.sqrt_price = sqrt_price;
341 state.tick = tick;
342 state.liquidity = liquidity;
343 state.step_cache = SwapStepCache::default();
344 state
345 }
346
347 fn swap(
348 &self,
349 zero_for_one: bool,
350 amount_specified: I256,
351 sqrt_price_limit: Option<U256>,
352 lp_fee_override: Option<u32>,
353 ) -> Result<SwapResults, SimulationError> {
354 if amount_specified == I256::ZERO {
358 return Ok(SwapResults {
359 amount_calculated: I256::ZERO,
360 amount_specified: I256::ZERO,
361 amount_remaining: I256::ZERO,
362 sqrt_price: self.sqrt_price,
363 liquidity: self.liquidity,
364 tick: self.tick.clone(),
365 gas_used: U256::from(3_000), });
367 }
368
369 let hook_swaps_from_empty_range = self
375 .hook
376 .as_ref()
377 .is_some_and(|hook| hook.swaps_from_empty_range());
378 if self.liquidity == 0 && (!hook_swaps_from_empty_range || self.has_no_initialized_ticks())
379 {
380 return Err(SimulationError::RecoverableError("No liquidity".to_string()));
381 }
382 let price_limit = if let Some(limit) = sqrt_price_limit {
383 limit
384 } else if zero_for_one {
385 safe_add_u256(MIN_SQRT_RATIO, U256::from(1u64))?
386 } else {
387 safe_sub_u256(MAX_SQRT_RATIO, U256::from(1u64))?
388 };
389
390 let price_limit_valid = if zero_for_one {
391 price_limit > MIN_SQRT_RATIO && price_limit < self.sqrt_price
392 } else {
393 price_limit < MAX_SQRT_RATIO && price_limit > self.sqrt_price
394 };
395 if !price_limit_valid {
396 return Err(SimulationError::InvalidInput("Price limit out of range".into(), None));
397 }
398
399 let exact_input = amount_specified < I256::ZERO;
400
401 let mut state = SwapState {
402 amount_remaining: amount_specified,
403 amount_calculated: I256::ZERO,
404 sqrt_price: self.sqrt_price,
405 tick: self.tick.value().into(),
406 liquidity: self.liquidity,
407 };
408 let mut gas_used = U256::from(self.gas_costs.base);
409
410 let cache_key = if exact_input && sqrt_price_limit.is_none() && lp_fee_override.is_none() {
416 let fee_pips = self
417 .fees
418 .calculate_swap_fees_pips(zero_for_one, None)?;
419 StepCacheKey::new(
420 self.sqrt_price,
421 state.tick.value(),
422 self.liquidity,
423 fee_pips,
424 gas_used,
425 )
426 } else {
427 None
428 };
429 let mut cache_run = StepCacheRun::new(
430 &self.step_cache,
431 zero_for_one,
432 cache_key,
433 amount_specified.unsigned_abs(),
434 );
435 if let Some(progress) = cache_run.apply_cached_progress(&mut state) {
436 gas_used = progress.gas;
437 }
438
439 while state.amount_remaining != I256::ZERO && state.sqrt_price != price_limit {
440 let (mut next_tick, next_tick_info) = match self
441 .ticks
442 .next_initialized_tick_within_one_word(state.tick.value(), zero_for_one)
443 {
444 Ok((tick, info)) => {
445 gas_used =
446 safe_add_u256(gas_used, U256::from(self.gas_costs.per_bitmap_lookup))?;
447 (tick, info)
448 }
449 Err(tick_err) => match tick_err.kind {
450 TickListErrorKind::TicksExeeded if hook_swaps_from_empty_range => {
454 (if zero_for_one { MIN_TICK } else { MAX_TICK }, None)
455 }
456 TickListErrorKind::TicksExeeded => {
457 let new_state = self.clone_post_swap(
458 state.sqrt_price,
459 state.tick.clone(),
460 state.liquidity,
461 );
462 return Err(SimulationError::InvalidInput(
463 "Ticks exceeded".into(),
464 Some(GetAmountOutResult::new(
465 u256_to_biguint(state.amount_calculated.abs().into_raw()),
466 u256_to_biguint(gas_used),
467 Box::new(new_state),
468 )),
469 ));
470 }
471 TickListErrorKind::BelowSmallest | TickListErrorKind::AtOrAboveLargest => {
472 return Err(SimulationError::FatalError("Unknown error".to_string()))
473 }
474 },
475 };
476
477 next_tick = next_tick.clamp(MIN_TICK, MAX_TICK);
478
479 let sqrt_price_next = match next_tick_info {
480 Some(info) => info.sqrt_price,
481 None => get_sqrt_ratio_at_tick_cached(next_tick)?,
482 };
483 let fee_pips = self
484 .fees
485 .calculate_swap_fees_pips(zero_for_one, lp_fee_override)?;
486
487 let sqrt_price_start = state.sqrt_price;
488 let SwapStepResult { sqrt_price, amount_in_with_fee, amount_out } =
489 swap_math::compute_swap_step(
490 state.sqrt_price,
491 UniswapV4State::get_sqrt_ratio_target(
492 sqrt_price_next,
493 price_limit,
494 zero_for_one,
495 ),
496 state.liquidity,
497 -state.amount_remaining,
501 fee_pips,
502 )?;
503 state.sqrt_price = sqrt_price;
504
505 let step = StepComputation {
506 sqrt_price_start,
507 tick_next: next_tick,
508 sqrt_price_next,
509 amount_in_with_fee,
510 amount_out,
511 };
512 if exact_input {
513 state.amount_remaining +=
514 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
515 .unwrap();
516 state.amount_calculated -=
517 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
518 } else {
519 state.amount_remaining -=
520 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
521 state.amount_calculated +=
522 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
523 .unwrap();
524 }
525 if state.sqrt_price == step.sqrt_price_next {
526 if let Some(info) = next_tick_info {
527 state.liquidity =
528 info.liquidity_after_crossing(state.liquidity, zero_for_one)?;
529 gas_used = safe_add_u256(gas_used, U256::from(self.gas_costs.per_tick))?;
530 }
531 state.tick =
532 PoolTick::from(if zero_for_one { step.tick_next - 1 } else { step.tick_next });
533 } else if state.sqrt_price != step.sqrt_price_start {
534 state.tick = PoolTick::at_sqrt_price(state.sqrt_price)?;
535 }
536 cache_run.cache_progress(&step, &state, gas_used);
537 }
538
539 Ok(SwapResults {
540 amount_calculated: state.amount_calculated,
541 amount_specified,
542 amount_remaining: state.amount_remaining,
543 sqrt_price: state.sqrt_price,
544 liquidity: state.liquidity,
545 tick: state.tick,
546 gas_used: safe_add_u256(gas_used, U256::from(self.gas_costs.settlement))?,
547 })
548 }
549
550 pub fn set_hook_handler(&mut self, handler: Box<dyn HookHandler>) {
551 self.hook = Some(handler);
552 }
553
554 fn get_sqrt_ratio_target(
555 sqrt_price_next: U256,
556 sqrt_price_limit: U256,
557 zero_for_one: bool,
558 ) -> U256 {
559 let cond1 = if zero_for_one {
560 sqrt_price_next < sqrt_price_limit
561 } else {
562 sqrt_price_next > sqrt_price_limit
563 };
564
565 if cond1 {
566 sqrt_price_limit
567 } else {
568 sqrt_price_next
569 }
570 }
571
572 fn find_limits_experimentally(
573 &self,
574 token_in: &Bytes,
575 token_out: &Bytes,
576 ) -> (BigUint, BigUint) {
577 let (token_in_obj, token_out_obj) = limit_probe_tokens(token_in, token_out);
578 self.find_max_amount(&token_in_obj, &token_out_obj)
579 }
580
581 fn find_max_amount(&self, token_in: &Token, token_out: &Token) -> (BigUint, BigUint) {
594 let mut low = BigUint::from(1u64);
595
596 let mut high = BigUint::from(10u64).pow(18); let mut last_successful_amount_in = BigUint::from(1u64);
600 let mut last_successful_amount_out = BigUint::from(0u64);
601
602 while let Ok(result) = self.get_amount_out(high.clone(), token_in, token_out) {
605 low = last_successful_amount_in.clone();
608 last_successful_amount_in = high.clone();
609 last_successful_amount_out = result.amount;
610 high *= BigUint::from(10u64);
611
612 if high > BigUint::from(10u64).pow(75) {
614 return (last_successful_amount_in, last_successful_amount_out);
615 }
616 }
617
618 while &high - &low > BigUint::from(1u64) {
620 let mid = (&low + &high) / BigUint::from(2u64);
621
622 match self.get_amount_out(mid.clone(), token_in, token_out) {
623 Ok(result) => {
624 last_successful_amount_in = mid.clone();
625 last_successful_amount_out = result.amount;
626 low = mid;
627 }
628 Err(_) => {
629 high = mid;
630 }
631 }
632 }
633
634 (last_successful_amount_in, last_successful_amount_out)
635 }
636
637 pub(crate) fn swap_fee_pips(
642 &self,
643 zero_for_one: bool,
644 lp_fee_override: Option<u32>,
645 ) -> Result<u32, SimulationError> {
646 self.fees
647 .calculate_swap_fees_pips(zero_for_one, lp_fee_override)
648 }
649
650 pub(crate) fn amount_in_to_price(
666 &self,
667 zero_for_one: bool,
668 sqrt_price_target: U256,
669 lp_fee_override: Option<u32>,
670 ) -> Result<PriceWalk, SimulationError> {
671 let target_ahead = if zero_for_one {
672 sqrt_price_target < self.sqrt_price
673 } else {
674 sqrt_price_target > self.sqrt_price
675 };
676 if !target_ahead {
677 let liquidity = if self.sqrt_price == sqrt_price_target {
678 self.liquidity_leaving_price(zero_for_one)?
679 } else {
680 self.liquidity
681 };
682 return Ok(PriceWalk { amount_in: U256::ZERO, liquidity, amount_out: U256::ZERO });
683 }
684 let result =
685 self.swap(zero_for_one, -PRICE_WALK_BUDGET, Some(sqrt_price_target), lp_fee_override)?;
686 if result.sqrt_price != sqrt_price_target {
687 return Err(SimulationError::FatalError(format!(
688 "walking the price to {sqrt_price_target} used up the input budget at {}",
689 result.sqrt_price
690 )));
691 }
692 let consumed = PRICE_WALK_BUDGET + result.amount_remaining;
693 Ok(PriceWalk {
694 amount_in: consumed.into_raw(),
695 liquidity: result.liquidity,
696 amount_out: result.amount_calculated.unsigned_abs(),
698 })
699 }
700
701 fn liquidity_leaving_price(&self, zero_for_one: bool) -> Result<u128, SimulationError> {
707 if self.has_no_initialized_ticks() {
710 return Ok(self.liquidity);
711 }
712 match self
713 .ticks
714 .next_initialized_tick_within_one_word(self.tick.value(), zero_for_one)
715 {
716 Ok((_, Some(info))) if info.sqrt_price == self.sqrt_price => {
717 info.liquidity_after_crossing(self.liquidity, zero_for_one)
718 }
719 Ok(_) => Ok(self.liquidity),
720 Err(tick_err) => match tick_err.kind {
721 TickListErrorKind::TicksExeeded => Ok(self.liquidity),
722 TickListErrorKind::BelowSmallest | TickListErrorKind::AtOrAboveLargest => {
723 Err(SimulationError::FatalError(format!(
724 "no tick to search from {} in the tick list",
725 self.tick.value()
726 )))
727 }
728 },
729 }
730 }
731
732 fn has_no_initialized_ticks(&self) -> bool {
734 !self.ticks.has_initialized_ticks()
735 }
736
737 fn core_spot_price(
741 &self,
742 base: &Token,
743 quote: &Token,
744 lp_fee_override: Option<u32>,
745 ) -> Result<f64, SimulationError> {
746 let base_is_currency0 = base < quote;
747 let fee_pips = self
748 .fees
749 .calculate_swap_fees_pips(base_is_currency0, lp_fee_override)?;
750 let fee = fee_pips as f64 / 1_000_000.0;
751
752 let price = if base_is_currency0 {
753 sqrt_price_q96_to_f64(self.sqrt_price, base.decimals, quote.decimals)?
754 } else {
755 1.0f64 / sqrt_price_q96_to_f64(self.sqrt_price, quote.decimals, base.decimals)?
756 };
757
758 Ok(add_fee_markup(price, fee))
759 }
760
761 fn hook_fee_rate(&self, zero_for_one: bool) -> Result<Option<f64>, SimulationError> {
767 let Some(hook) = &self.hook else { return Ok(None) };
768
769 let probe = U256::from(10u64).pow(U256::from(HOOK_FEE_PROBE_EXP));
770 let Some(fee) = hook.unspecified_fee_amount(probe, zero_for_one)? else {
771 return Ok(None);
772 };
773
774 Ok(Some(u256_to_f64(fee)? / u256_to_f64(probe)?))
775 }
776}
777
778fn hook_call_error(stage: &str, error: SimulationError) -> SimulationError {
787 match error {
788 SimulationError::InvalidInput(..) => error,
789 e @ (SimulationError::FatalError(_) | SimulationError::RecoverableError(_)) => {
790 SimulationError::FatalError(format!("{stage} hook simulation failed: {e:?}"))
791 }
792 }
793}
794
795fn limit_probe_tokens(token_in: &Bytes, token_out: &Bytes) -> (Token, Token) {
798 (
799 Token::new(token_in, "TOKEN_IN", 18, 0, &[Some(10_000)], Default::default(), 100),
800 Token::new(token_out, "TOKEN_OUT", 18, 0, &[Some(10_000)], Default::default(), 100),
801 )
802}
803
804#[typetag::serde]
805impl ProtocolSim for UniswapV4State {
806 fn set_pending_overrides(
809 &mut self,
810 overrides: Arc<dyn Any + Send + Sync>,
811 ) -> Result<(), SimulationError> {
812 #[expect(
813 clippy::map_err_ignore,
814 reason = "the downcast error is the original `Arc<dyn Any>`, which has no message"
815 )]
816 let overrides = overrides
817 .downcast::<PendingOverrides>()
818 .map_err(|_| {
819 SimulationError::FatalError(
820 "Uniswap V4 pending overrides must be `PendingOverrides`".to_string(),
821 )
822 })?;
823 if let Some(hook) = &mut self.hook {
824 hook.set_pending_overrides(Arc::clone(&overrides));
825 }
826 self.pending_overrides = Some(overrides);
827 Ok(())
828 }
829
830 #[expect(
833 clippy::todo,
834 reason = "fee() returns no error and the trait documents the panic for asymmetric fees"
835 )]
836 fn fee(&self) -> f64 {
837 todo!()
838 }
839
840 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
841 if let Some(hook) = &self.hook {
842 let analytic = match hook.spot_fees(quote < base)? {
848 Some(fees) => Some((
849 fees.lp_fee_override,
850 f64::from(fees.hook_fee_pips) / f64::from(FEE_PIPS_DENOMINATOR),
851 )),
852 None => self
853 .hook_fee_rate(quote < base)?
854 .map(|rate| (None, rate)),
855 };
856 if let Some((lp_fee_override, rate)) = analytic {
857 if rate >= 1.0 {
858 return Err(SimulationError::FatalError(format!(
859 "Hook {} keeps {rate} of the swap, leaving no price to quote",
860 hook.address()
861 )));
862 }
863 let core = self.core_spot_price(base, quote, lp_fee_override)?;
864 return Ok(add_fee_markup(core, rate));
865 }
866
867 match hook.spot_price(base, quote) {
868 Ok(price) => return Ok(price),
869 Err(SimulationError::RecoverableError(_)) => {
870 let x1 = BigUint::from(10u64).pow(base.decimals) / BigUint::from(100u64); let x2 = &x1 + (&x1 / BigUint::from(100u64));
878
879 let y1 = self.get_amount_out(x1.clone(), base, quote)?;
881 let y2 = self.get_amount_out(x2.clone(), base, quote)?;
882
883 let num = y2
885 .amount
886 .checked_sub(&y1.amount)
887 .ok_or_else(|| {
888 SimulationError::FatalError(
889 "Cannot calculate spot price: y2 < y1".to_string(),
890 )
891 })?;
892 let den = x2.checked_sub(&x1).ok_or_else(|| {
893 SimulationError::FatalError(
894 "Cannot calculate spot price: x2 < x1".to_string(),
895 )
896 })?;
897
898 if den == BigUint::from(0u64) {
899 return Err(SimulationError::FatalError(
900 "Cannot calculate spot price: denominator is zero".to_string(),
901 ));
902 }
903
904 let num_f64 = num.to_f64().ok_or_else(|| {
906 SimulationError::FatalError(
907 "Failed to convert numerator to f64".to_string(),
908 )
909 })?;
910 let den_f64 = den.to_f64().ok_or_else(|| {
911 SimulationError::FatalError(
912 "Failed to convert denominator to f64".to_string(),
913 )
914 })?;
915
916 let token_correction =
917 10f64.powi(decimals_exponent(base.decimals, quote.decimals)?);
918
919 return Ok(num_f64 / den_f64 * token_correction);
920 }
921 Err(e) => return Err(e),
922 }
923 }
924
925 self.core_spot_price(base, quote, None)
926 }
927
928 fn get_amount_out(
929 &self,
930 amount_in: BigUint,
931 token_in: &Token,
932 token_out: &Token,
933 ) -> Result<GetAmountOutResult, SimulationError> {
934 let zero_for_one = token_in < token_out;
935 let amount_specified =
936 I256::checked_from_sign_and_abs(Sign::Negative, biguint_to_uint(&amount_in)?)
937 .ok_or_else(|| {
938 SimulationError::InvalidInput("I256 overflow: amount_in".to_string(), None)
939 })?;
940
941 let mut amount_to_swap = amount_specified;
942 let mut lp_fee_override: Option<u32> = None;
943 let mut before_swap_gas = 0u64;
944 let mut after_swap_gas = 0u64;
945 let mut before_swap_delta = BeforeSwapDelta(I256::ZERO);
946 let mut storage_overwrites = None;
947
948 let token_in_address = Address::from_slice(&token_in.address);
949 let token_out_address = Address::from_slice(&token_out.address);
950
951 let state_context = StateContext {
952 currency_0: if zero_for_one { token_in_address } else { token_out_address },
953 currency_1: if zero_for_one { token_out_address } else { token_in_address },
954 fees: self.fees.clone(),
955 tick_spacing: self.tick_spacing,
956 sqrt_price_x96: self.sqrt_price,
957 tick: self.tick.value(),
958 };
959
960 let sqrt_price_limit = if zero_for_one {
964 safe_add_u256(MIN_SQRT_RATIO, U256::from(1u64))?
965 } else {
966 safe_sub_u256(MAX_SQRT_RATIO, U256::from(1u64))?
967 };
968 let swap_params =
969 SwapParams { zero_for_one, amount_specified: amount_to_swap, sqrt_price_limit };
970
971 if let Some(ref hook) = self.hook {
973 if hook.has_permission(HookOptions::BeforeSwap) {
974 let before_swap_params = BeforeSwapParameters {
975 context: state_context.clone(),
976 sender: *EXTERNAL_ACCOUNT,
977 swap_params: swap_params.clone(),
978 hook_data: Bytes::new(),
979 };
980
981 let before_swap_result = hook
982 .before_swap(before_swap_params, None, None)
983 .map_err(|e| hook_call_error("BeforeSwap", e))?;
984
985 before_swap_gas = before_swap_result.gas_estimate;
986 before_swap_delta = before_swap_result.result.amount_delta;
987 storage_overwrites = Some(before_swap_result.result.overwrites);
988
989 if before_swap_delta.as_i256() != I256::ZERO {
992 amount_to_swap += I256::from(before_swap_delta.get_specified_delta());
993 if amount_to_swap > I256::ZERO {
994 return Err(SimulationError::FatalError(
995 "Hook delta exceeds swap amount".into(),
996 ));
997 }
998 }
999
1000 let hook_fee = before_swap_result
1005 .result
1006 .fee
1007 .to::<u32>();
1008 if hook_fee != 0 {
1009 let cleaned_fee = lp_fee::remove_override_flag(hook_fee);
1011
1012 if !lp_fee::is_valid(cleaned_fee) {
1014 return Err(SimulationError::FatalError(format!(
1015 "LP fee override {} exceeds maximum {} pips",
1016 cleaned_fee,
1017 lp_fee::MAX_LP_FEE
1018 )));
1019 }
1020
1021 lp_fee_override = Some(cleaned_fee);
1022 }
1023 }
1024 }
1025
1026 let result = self.swap(zero_for_one, amount_to_swap, None, lp_fee_override)?;
1028
1029 if let Some(hook) = &self.hook {
1030 hook.check_swap_outcome(
1031 zero_for_one,
1032 &SwapOutcome {
1033 sqrt_price_x96: result.sqrt_price,
1034 amount_unfilled: result.amount_remaining.unsigned_abs(),
1035 },
1036 )
1037 .map_err(|e| hook_call_error("CheckSwapOutcome", e))?;
1038 }
1039
1040 let next_hook = self
1045 .hook
1046 .as_ref()
1047 .map_or(Ok(None), |hook| hook.handler_after_swap(&state_context, &swap_params))
1048 .map_err(|e| hook_call_error("HandlerAfterSwap", e))?;
1049
1050 let mut swap_delta = BalanceDelta::from_swap_result(result.amount_calculated, zero_for_one);
1052
1053 let hook_delta_specified = before_swap_delta.get_specified_delta();
1056 let mut hook_delta_unspecified = before_swap_delta.get_unspecified_delta();
1057
1058 if let Some(ref hook) = self.hook {
1059 if hook.has_permission(HookOptions::AfterSwap) {
1060 let after_swap_params = AfterSwapParameters {
1061 context: state_context,
1062 sender: *EXTERNAL_ACCOUNT,
1063 swap_params,
1064 delta: swap_delta,
1065 hook_data: Bytes::new(),
1066 };
1067
1068 let after_swap_result = hook
1069 .after_swap(after_swap_params, storage_overwrites, None)
1070 .map_err(|e| hook_call_error("AfterSwap", e))?;
1071 after_swap_gas = after_swap_result.gas_estimate;
1072 if hook.has_permission(HookOptions::AfterSwapReturnsDelta) {
1077 hook_delta_unspecified += after_swap_result.result;
1078 }
1079 }
1080 }
1081
1082 if (hook_delta_specified != I128::ZERO) || (hook_delta_unspecified != I128::ZERO) {
1085 let hook_delta = if (amount_specified < I256::ZERO) == zero_for_one {
1086 BalanceDelta::new(hook_delta_specified, hook_delta_unspecified)
1087 } else {
1088 BalanceDelta::new(hook_delta_unspecified, hook_delta_specified)
1089 };
1090 swap_delta = swap_delta - hook_delta
1092 }
1093
1094 let amount_out = if (amount_specified < I256::ZERO) == zero_for_one {
1095 swap_delta.amount1()
1096 } else {
1097 swap_delta.amount0()
1098 };
1099
1100 trace!(?amount_in, ?token_in, ?token_out, ?zero_for_one, ?result, "V4 SWAP");
1101 let mut new_state = self.clone_post_swap(result.sqrt_price, result.tick, result.liquidity);
1102 if let Some(next_hook) = next_hook {
1103 new_state.hook = Some(next_hook);
1104 }
1105
1106 let mut hook_overhead = before_swap_gas + after_swap_gas;
1111 if let Some(hook) = &self.hook {
1112 let hook_calls = u64::from(before_swap_gas > 0) + u64::from(after_swap_gas > 0);
1113 hook_overhead += hook_calls * hook.pool_manager_call_overhead();
1114 }
1115 let total_gas_used = result.gas_used + U256::from(hook_overhead);
1116 Ok(GetAmountOutResult::new(
1117 u256_to_biguint(U256::from(amount_out.abs())),
1118 u256_to_biguint(total_gas_used),
1119 Box::new(new_state),
1120 ))
1121 }
1122
1123 fn get_limits(
1124 &self,
1125 sell_token: Bytes,
1126 buy_token: Bytes,
1127 ) -> Result<(BigUint, BigUint), SimulationError> {
1128 if let Some(hook) = &self.hook {
1129 if !hook.swaps_enabled() {
1130 return Ok((BigUint::zero(), BigUint::zero()));
1131 }
1132 if let Some(max_in) = hook.max_amount_in(self, sell_token < buy_token)? {
1135 if max_in.is_zero() {
1136 return Ok((BigUint::zero(), BigUint::zero()));
1137 }
1138 let max_in = u256_to_biguint(max_in);
1139 let (token_in, token_out) = limit_probe_tokens(&sell_token, &buy_token);
1140 let max_out = self
1141 .get_amount_out(max_in.clone(), &token_in, &token_out)?
1142 .amount;
1143 return Ok((max_in, max_out));
1144 }
1145 if hook.swaps_from_empty_range() {
1148 return Err(SimulationError::FatalError(format!(
1149 "hook {} swaps from an empty range but reports no max_amount_in",
1150 hook.address()
1151 )));
1152 }
1153 if self.liquidity == 0 && self.has_no_initialized_ticks() {
1155 match hook.get_amount_ranges(sell_token.clone(), buy_token.clone()) {
1157 Ok(amount_ranges) => {
1158 return Ok((
1159 u256_to_biguint(amount_ranges.amount_in_range.1),
1160 u256_to_biguint(amount_ranges.amount_out_range.1),
1161 ))
1162 }
1163 Err(SimulationError::RecoverableError(msg))
1166 if msg.contains("not implemented") || msg.contains("not set") =>
1167 {
1168 return Ok(self.find_limits_experimentally(&sell_token, &buy_token));
1171 }
1173 Err(e) => return Err(e),
1174 }
1175 }
1176 }
1177
1178 if self.liquidity == 0 {
1180 return Ok((BigUint::zero(), BigUint::zero()));
1181 }
1182
1183 let zero_for_one = sell_token < buy_token;
1184 let mut current_tick = self.tick.value();
1185 let mut current_sqrt_price = self.sqrt_price;
1186 let mut current_liquidity = self.liquidity;
1187 let mut total_amount_in = U256::ZERO;
1188 let mut total_amount_out = U256::ZERO;
1189 let mut ticks_crossed: u64 = 0;
1190 let max_ticks_crossed = self.gas_costs.max_ticks_crossed();
1191
1192 while let Ok((tick, next_tick_info)) = self
1195 .ticks
1196 .next_initialized_tick_within_one_word(current_tick, zero_for_one)
1197 {
1198 if ticks_crossed >= max_ticks_crossed {
1200 break;
1201 }
1202 ticks_crossed += 1;
1203
1204 let next_tick = tick.clamp(MIN_TICK, MAX_TICK);
1206
1207 let sqrt_price_next = match next_tick_info {
1208 Some(info) => info.sqrt_price,
1209 None => get_sqrt_ratio_at_tick_cached(next_tick)?,
1210 };
1211
1212 let (amount_in, amount_out) = if zero_for_one {
1215 let amount0 = get_amount0_delta(
1216 sqrt_price_next,
1217 current_sqrt_price,
1218 current_liquidity,
1219 true,
1220 )?;
1221 let amount1 = get_amount1_delta(
1222 sqrt_price_next,
1223 current_sqrt_price,
1224 current_liquidity,
1225 false,
1226 )?;
1227 (amount0, amount1)
1228 } else {
1229 let amount0 = get_amount0_delta(
1230 sqrt_price_next,
1231 current_sqrt_price,
1232 current_liquidity,
1233 false,
1234 )?;
1235 let amount1 = get_amount1_delta(
1236 sqrt_price_next,
1237 current_sqrt_price,
1238 current_liquidity,
1239 true,
1240 )?;
1241 (amount1, amount0)
1242 };
1243
1244 total_amount_in = safe_add_u256(total_amount_in, amount_in)?;
1246 total_amount_out = safe_add_u256(total_amount_out, amount_out)?;
1247
1248 if let Some(info) = next_tick_info {
1253 match info.liquidity_after_crossing(current_liquidity, zero_for_one) {
1256 Ok(new_liquidity) => {
1257 current_liquidity = new_liquidity;
1258 }
1259 Err(_) => {
1260 break;
1263 }
1264 }
1265 }
1266
1267 current_tick = if zero_for_one { next_tick - 1 } else { next_tick };
1269 current_sqrt_price = sqrt_price_next;
1270
1271 if current_liquidity == 0 {
1273 break;
1274 }
1275 }
1276
1277 if let Some(hook) = &self.hook {
1280 if let Some(fee) = hook.unspecified_fee_amount(total_amount_out, zero_for_one)? {
1281 total_amount_out = safe_sub_u256(total_amount_out, fee)?;
1282 }
1283 }
1284
1285 Ok((u256_to_biguint(total_amount_in), u256_to_biguint(total_amount_out)))
1286 }
1287
1288 fn delta_transition(
1289 &mut self,
1290 delta: ProtocolStateDelta,
1291 tokens: &HashMap<Bytes, Token>,
1292 balances: &Balances,
1293 ) -> Result<(), TransitionError> {
1294 self.step_cache = SwapStepCache::default();
1296 if let Some(mut hook) = self.hook.clone() {
1297 match hook.delta_transition(delta.clone(), tokens, balances) {
1298 Ok(()) => self.set_hook_handler(hook),
1299 Err(TransitionError::SimulationError(SimulationError::RecoverableError(msg)))
1300 if msg.contains("not implemented") =>
1301 {
1302 }
1304 Err(e) => return Err(e),
1305 }
1306 }
1307
1308 if let Some(liquidity) = delta
1310 .updated_attributes
1311 .get("liquidity")
1312 {
1313 self.liquidity = u128::try_from(liquidity.clone())?;
1314 }
1315 if let Some(sqrt_price) = delta
1316 .updated_attributes
1317 .get("sqrt_price_x96")
1318 {
1319 self.sqrt_price = U256::from_be_slice(sqrt_price);
1320 }
1321 if let Some(tick) = delta.updated_attributes.get("tick") {
1322 self.tick = i24_be_bytes_to_i32(tick).into();
1323 }
1324 if let Some(lp_fee) = delta.updated_attributes.get("fee") {
1325 self.fees.lp_fee = u32::try_from(lp_fee.clone())?;
1326 }
1327 if let Some(zero2one_protocol_fee) = delta
1328 .updated_attributes
1329 .get("protocol_fees/zero2one")
1330 {
1331 self.fees.zero_for_one = u32::try_from(zero2one_protocol_fee.clone())?;
1332 }
1333 if let Some(one2zero_protocol_fee) = delta
1334 .updated_attributes
1335 .get("protocol_fees/one2zero")
1336 {
1337 self.fees.one_for_zero = u32::try_from(one2zero_protocol_fee.clone())?;
1338 }
1339
1340 for (key, value) in delta.updated_attributes.iter() {
1342 if key.starts_with("ticks/") {
1344 let parts: Vec<&str> = key.split('/').collect();
1345 Arc::make_mut(&mut self.ticks)
1346 .set_tick_liquidity(
1347 parts[1]
1348 .parse::<i32>()
1349 .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
1350 i128::try_from(value.clone())?,
1351 )
1352 .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
1353 }
1354 }
1355 for key in delta.deleted_attributes.iter() {
1357 if key.starts_with("ticks/") {
1359 let parts: Vec<&str> = key.split('/').collect();
1360 Arc::make_mut(&mut self.ticks)
1361 .set_tick_liquidity(
1362 parts[1]
1363 .parse::<i32>()
1364 .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
1365 0,
1366 )
1367 .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
1368 }
1369 }
1370
1371 Ok(())
1372 }
1373
1374 fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
1387 let zero_for_one = params.token_in().address < params.token_out().address;
1388 if let Some(hook) = &self.hook {
1389 if !hook.swaps_enabled() {
1390 return Err(SimulationError::InvalidInput(
1391 format!("hook {} does not allow swaps in the execution block", hook.address()),
1392 None,
1393 ));
1394 }
1395 if hook.spot_fees(zero_for_one)?.is_some() {
1396 return Err(SimulationError::InvalidInput(
1397 format!(
1398 "hook {} sets the swap's fees, which query_pool_swap does not apply",
1399 hook.address()
1400 ),
1401 None,
1402 ));
1403 }
1404 }
1405 if self.liquidity == 0 {
1406 return Err(SimulationError::FatalError("No liquidity".to_string()));
1407 }
1408
1409 let fee_pips = self
1411 .fees
1412 .calculate_swap_fees_pips(zero_for_one, None)?;
1413
1414 match params.swap_constraint() {
1415 SwapConstraint::TradeLimitPrice { .. } => Err(SimulationError::InvalidInput(
1416 "Uniswap V4 does not support TradeLimitPrice constraint in query_pool_swap"
1417 .to_string(),
1418 None,
1419 )),
1420 SwapConstraint::PoolTargetPrice {
1421 target,
1422 tolerance: _,
1423 min_amount_in: _,
1424 max_amount_in: _,
1425 } => {
1426 if self.liquidity == 0 {
1427 return Err(SimulationError::FatalError("No liquidity".to_string()));
1428 }
1429
1430 let (amount_in, amount_out, swap_result) = clmm_swap_to_price(
1431 self.sqrt_price,
1432 ¶ms.token_in().address,
1433 ¶ms.token_out().address,
1434 target,
1435 fee_pips,
1436 Sign::Negative, |zero_for_one, amount_specified, sqrt_price_limit| {
1438 self.swap(zero_for_one, amount_specified, Some(sqrt_price_limit), None)
1439 },
1440 )?;
1441
1442 let new_state = self.clone_post_swap(
1443 swap_result.sqrt_price,
1444 swap_result.tick,
1445 swap_result.liquidity,
1446 );
1447
1448 Ok(PoolSwap::new(amount_in, amount_out, Box::new(new_state), None))
1449 }
1450 }
1451 }
1452
1453 fn apply_block(&mut self, block: &BlockContext) -> bool {
1456 self.hook
1457 .as_mut()
1458 .is_some_and(|hook| hook.apply_block(block))
1459 }
1460
1461 fn clone_box(&self) -> Box<dyn ProtocolSim> {
1462 Box::new(self.clone())
1463 }
1464
1465 fn as_any(&self) -> &dyn Any {
1466 self
1467 }
1468
1469 fn as_any_mut(&mut self) -> &mut dyn Any {
1470 self
1471 }
1472
1473 fn eq(&self, other: &dyn ProtocolSim) -> bool {
1474 if let Some(other_state) = other
1475 .as_any()
1476 .downcast_ref::<UniswapV4State>()
1477 {
1478 self.liquidity == other_state.liquidity &&
1479 self.sqrt_price == other_state.sqrt_price &&
1480 self.fees == other_state.fees &&
1481 self.tick == other_state.tick &&
1482 self.ticks == other_state.ticks
1483 } else {
1484 false
1485 }
1486 }
1487}
1488
1489#[cfg(test)]
1490mod tests {
1491 use std::{collections::HashSet, fs, path::Path, str::FromStr};
1492
1493 use alloy::primitives::{aliases::U24, U160};
1494 use num_traits::FromPrimitive;
1495 use rstest::rstest;
1496 use serde_json::Value;
1497 use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
1498 use tycho_common::{models::Chain, simulation::protocol_sim::Price};
1499
1500 use super::*;
1501 use crate::{
1502 evm::{
1503 engine_db::{
1504 create_engine,
1505 simulation_db::SimulationDB,
1506 utils::{get_client, get_runtime},
1507 },
1508 protocol::{
1509 u256_num::biguint_to_uint,
1510 uniswap_v4::hooks::{
1511 angstrom::hook_handler::{AngstromFees, AngstromHookHandler},
1512 generic_vm_hook_handler::GenericVMHookHandler,
1513 models::{
1514 AfterSwapDelta, AmountRanges, BeforeSwapOutput, HookSpotFees,
1515 WithGasEstimate,
1516 },
1517 pons_v2::hook_handler::{PonsV2HookHandler, PONS_V2_HOOK_ROBINHOOD},
1518 test_hook::{
1519 ExtensionTestHook, HandlerAfterSwapAnswer, OutcomeCheckAnswer,
1520 SpotFeesAnswer, WHOLE_INPUT_TEST_HOOK_GAS,
1521 },
1522 },
1523 utils::uniswap::{
1524 lp_fee,
1525 sqrt_price_math::get_sqrt_price_q96,
1526 tick_math::{get_sqrt_ratio_at_tick, get_tick_at_sqrt_ratio},
1527 },
1528 },
1529 },
1530 protocol::models::{DecoderContext, TryFromWithBlock},
1531 };
1532
1533 fn usdc() -> Token {
1535 Token::new(
1536 &Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap(),
1537 "USDC",
1538 6,
1539 0,
1540 &[Some(10_000)],
1541 Default::default(),
1542 100,
1543 )
1544 }
1545
1546 fn weth() -> Token {
1547 Token::new(
1548 &Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(),
1549 "WETH",
1550 18,
1551 0,
1552 &[Some(10_000)],
1553 Default::default(),
1554 100,
1555 )
1556 }
1557
1558 fn eth() -> Token {
1559 Token::new(
1560 &Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
1561 "ETH",
1562 18,
1563 0,
1564 &[Some(10_000)],
1565 Default::default(),
1566 100,
1567 )
1568 }
1569
1570 fn token_x() -> Token {
1571 Token::new(
1572 &Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap(),
1573 "X",
1574 18,
1575 0,
1576 &[Some(10_000)],
1577 Default::default(),
1578 100,
1579 )
1580 }
1581
1582 fn token_y() -> Token {
1583 Token::new(
1584 &Bytes::from_str("0x0000000000000000000000000000000000000002").unwrap(),
1585 "Y",
1586 18,
1587 0,
1588 &[Some(10_000)],
1589 Default::default(),
1590 100,
1591 )
1592 }
1593
1594 #[test]
1595 fn delta_with_oversized_liquidity_is_rejected_without_panicking() {
1596 let mut pool = UniswapV4State::new(
1597 1000,
1598 U256::from_str("1000").unwrap(),
1599 UniswapV4Fees { zero_for_one: 100, one_for_zero: 90, lp_fee: 700 },
1600 100,
1601 60,
1602 vec![TickInfo::new(120, 10000).unwrap(), TickInfo::new(180, -10000).unwrap()],
1603 )
1604 .unwrap();
1605 let address_sized = Bytes::from(vec![0x11_u8; 20]);
1606 let delta = ProtocolStateDelta {
1607 component_id: "State1".to_owned(),
1608 updated_attributes: HashMap::from([("liquidity".to_string(), address_sized.clone())]),
1609 deleted_attributes: HashSet::new(),
1610 };
1611
1612 let result = pool.delta_transition(delta, &HashMap::new(), &Balances::default());
1613
1614 let Err(TransitionError::DecodeError(message)) = result else {
1615 panic!("a 20-byte liquidity attribute must not apply");
1616 };
1617 assert!(message.contains(&address_sized.to_string()), "{message}");
1618 assert_eq!(pool.liquidity, 1000);
1619 }
1620
1621 #[rstest]
1628 #[case::down_from_the_tick(60, 7_000, true, 5_000)]
1629 #[case::up_from_the_tick(60, 7_000, false, 7_000)]
1630 #[case::up_from_just_below(59, 5_000, false, 7_000)]
1631 #[case::down_from_just_below(59, 5_000, true, 5_000)]
1632 fn test_amount_in_to_the_current_price_reports_the_liquidity_leaving_it(
1633 #[case] tick: i32,
1634 #[case] liquidity: u128,
1635 #[case] zero_for_one: bool,
1636 #[case] expected_liquidity: u128,
1637 ) {
1638 let sqrt_price = get_sqrt_ratio_at_tick(60).unwrap();
1639 let ticks = vec![
1640 TickInfo::new(-60, 5_000).unwrap(),
1641 TickInfo::new(60, 2_000).unwrap(),
1642 TickInfo::new(120, -7_000).unwrap(),
1643 ];
1644 let pool = UniswapV4State::new(
1645 liquidity,
1646 sqrt_price,
1647 UniswapV4Fees::new(0, 0, 0),
1648 tick,
1649 60,
1650 ticks,
1651 )
1652 .unwrap();
1653
1654 let walk = pool
1655 .amount_in_to_price(zero_for_one, sqrt_price, None)
1656 .unwrap();
1657
1658 assert_eq!((walk.amount_in, walk.liquidity), (U256::ZERO, expected_liquidity));
1659 }
1660
1661 #[rstest]
1662 #[case::down(true)]
1663 #[case::up(false)]
1664 fn test_amount_in_to_the_current_price_without_ticks_keeps_the_liquidity(
1665 #[case] zero_for_one: bool,
1666 ) {
1667 let sqrt_price = get_sqrt_ratio_at_tick(60).unwrap();
1668 let pool =
1669 UniswapV4State::new(5_000, sqrt_price, UniswapV4Fees::new(0, 0, 0), 60, 60, vec![])
1670 .unwrap();
1671
1672 let walk = pool
1673 .amount_in_to_price(zero_for_one, sqrt_price, None)
1674 .unwrap();
1675
1676 assert_eq!((walk.amount_in, walk.liquidity), (U256::ZERO, 5_000));
1677 }
1678
1679 #[rstest]
1691 #[case::no_fee_within_the_budget(None, true)]
1692 #[case::montra_cap_within_the_budget(Some(990_000), true)]
1693 #[case::fee_just_past_the_budget(Some(999_500), false)]
1694 #[case::fee_above_the_budget_bound(Some(999_900), false)]
1695 fn test_amount_in_to_price_against_the_input_budget(
1696 #[case] lp_fee_override: Option<u32>,
1697 #[case] reaches_target: bool,
1698 ) {
1699 let liquidity: u128 = 1 << 126;
1700 let net = i128::try_from(liquidity).unwrap();
1701 let ticks =
1702 vec![TickInfo::new(-887_220, net).unwrap(), TickInfo::new(887_220, -net).unwrap()];
1703 let pool = UniswapV4State::new(
1704 liquidity,
1705 get_sqrt_ratio_at_tick(0).unwrap(),
1706 UniswapV4Fees::new(0, 0, 0),
1707 0,
1708 60,
1709 ticks,
1710 )
1711 .unwrap();
1712 let target = get_sqrt_ratio_at_tick(880_000).unwrap();
1713
1714 let walk = pool.amount_in_to_price(false, target, lp_fee_override);
1715
1716 match (walk, reaches_target) {
1717 (Ok(_), true) if lp_fee_override.is_some() => {}
1719 (Ok(walk), true) => assert_eq!(
1720 (walk.amount_in, walk.amount_out, walk.liquidity),
1721 (
1722 U256::from_str("1090890785126545743432254324356798306370102991638442803200")
1723 .unwrap(),
1724 U256::from_str("85070591730234615859209618757650758722").unwrap(),
1725 liquidity
1726 )
1727 ),
1728 (Err(SimulationError::FatalError(message)), false) => {
1729 assert!(message.contains("used up the input budget"), "{message}")
1730 }
1731 (walk, _) => panic!("expected reaches_target = {reaches_target}, got {walk:?}"),
1732 }
1733 }
1734
1735 #[test]
1736 fn test_delta_transition() {
1737 let mut pool = UniswapV4State::new(
1738 1000,
1739 U256::from_str("1000").unwrap(),
1740 UniswapV4Fees { zero_for_one: 100, one_for_zero: 90, lp_fee: 700 },
1741 100,
1742 60,
1743 vec![TickInfo::new(120, 10000).unwrap(), TickInfo::new(180, -10000).unwrap()],
1744 )
1745 .unwrap();
1746
1747 let attributes: HashMap<String, Bytes> = [
1748 ("liquidity".to_string(), Bytes::from(2000_u64.to_be_bytes().to_vec())),
1749 ("sqrt_price_x96".to_string(), Bytes::from(1001_u64.to_be_bytes().to_vec())),
1750 ("tick".to_string(), Bytes::from(120_i32.to_be_bytes().to_vec())),
1751 ("protocol_fees/zero2one".to_string(), Bytes::from(50_u32.to_be_bytes().to_vec())),
1752 ("protocol_fees/one2zero".to_string(), Bytes::from(75_u32.to_be_bytes().to_vec())),
1753 ("fee".to_string(), Bytes::from(100_u32.to_be_bytes().to_vec())),
1754 ("ticks/-120/net_liquidity".to_string(), Bytes::from(10200_u64.to_be_bytes().to_vec())),
1755 ("ticks/120/net_liquidity".to_string(), Bytes::from(9800_u64.to_be_bytes().to_vec())),
1756 ("block_number".to_string(), Bytes::from(2000_u64.to_be_bytes().to_vec())),
1757 ("block_timestamp".to_string(), Bytes::from(1758201935_u64.to_be_bytes().to_vec())),
1758 ]
1759 .into_iter()
1760 .collect();
1761
1762 let delta = ProtocolStateDelta {
1763 component_id: "State1".to_owned(),
1764 updated_attributes: attributes,
1765 deleted_attributes: HashSet::new(),
1766 };
1767
1768 pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1769 .unwrap();
1770
1771 assert_eq!(pool.liquidity, 2000);
1772 assert_eq!(pool.sqrt_price, U256::from(1001));
1773 assert_eq!(pool.tick.value(), 120);
1774 assert_eq!(pool.fees.zero_for_one, 50);
1775 assert_eq!(pool.fees.one_for_zero, 75);
1776 assert_eq!(pool.fees.lp_fee, 100);
1777 assert_eq!(
1778 pool.ticks
1779 .get_tick(-120)
1780 .unwrap()
1781 .net_liquidity,
1782 10200
1783 );
1784 assert_eq!(
1785 pool.ticks
1786 .get_tick(120)
1787 .unwrap()
1788 .net_liquidity,
1789 9800
1790 );
1791 }
1792
1793 #[tokio::test]
1794 async fn test_swap_sim() {
1796 use tycho_client::feed::dto;
1797 let project_root = env!("CARGO_MANIFEST_DIR");
1798 let asset_path = Path::new(project_root)
1799 .join("tests/assets/decoder/uniswap_v4_snapshot_sepolia_block_7239119.json");
1800 let json_data = fs::read_to_string(asset_path).expect("Failed to read test asset");
1801 let data: Value = serde_json::from_str(&json_data).expect("Failed to parse JSON");
1802 let state: ComponentWithState = serde_json::from_value::<dto::ComponentWithState>(data)
1803 .expect("Expected json to match ComponentWithState structure")
1804 .into();
1805
1806 let block = BlockHeader {
1807 number: 7239119,
1808 hash: Bytes::from_str(
1809 "0x28d41d40f2ac275a4f5f621a636b9016b527d11d37d610a45ac3a821346ebf8c",
1810 )
1811 .expect("Invalid block hash"),
1812 parent_hash: Bytes::from(vec![0; 32]),
1813 ..Default::default()
1814 };
1815
1816 let t0 = Token::new(
1817 &Bytes::from_str("0x647e32181a64f4ffd4f0b0b4b052ec05b277729c").unwrap(),
1818 "T0",
1819 18,
1820 0,
1821 &[Some(10_000)],
1822 Chain::Ethereum,
1823 100,
1824 );
1825 let t1 = Token::new(
1826 &Bytes::from_str("0xe390a1c311b26f14ed0d55d3b0261c2320d15ca5").unwrap(),
1827 "T1",
1828 18,
1829 0,
1830 &[Some(10_000)],
1831 Chain::Ethereum,
1832 100,
1833 );
1834
1835 let all_tokens = [t0.clone(), t1.clone()]
1836 .iter()
1837 .map(|t| (t.address.clone(), t.clone()))
1838 .collect();
1839
1840 let usv4_state = UniswapV4State::try_from_with_header(
1841 state,
1842 block,
1843 &Default::default(),
1844 &all_tokens,
1845 &DecoderContext::new(),
1846 )
1847 .await
1848 .unwrap();
1849
1850 assert!(usv4_state.hook.is_none());
1853
1854 let res = usv4_state
1855 .get_amount_out(BigUint::from_u64(1000000000000000000).unwrap(), &t0, &t1)
1856 .unwrap();
1857
1858 let expected_amount = BigUint::from(9999909699895_u64);
1859 assert_eq!(res.amount, expected_amount);
1860 }
1861
1862 #[tokio::test]
1863 async fn test_get_limits() {
1864 use tycho_client::feed::dto;
1865 let block = BlockHeader {
1866 number: 22689129,
1867 hash: Bytes::from_str(
1868 "0x7763ea30d11aef68da729b65250c09a88ad00458c041064aad8c9a9dbf17adde",
1869 )
1870 .expect("Invalid block hash"),
1871 parent_hash: Bytes::from(vec![0; 32]),
1872 ..Default::default()
1873 };
1874
1875 let project_root = env!("CARGO_MANIFEST_DIR");
1876 let asset_path =
1877 Path::new(project_root).join("tests/assets/decoder/uniswap_v4_snapshot.json");
1878 let json_data = fs::read_to_string(asset_path).expect("Failed to read test asset");
1879 let data: Value = serde_json::from_str(&json_data).expect("Failed to parse JSON");
1880 let state: ComponentWithState = serde_json::from_value::<dto::ComponentWithState>(data)
1881 .expect("Expected json to match ComponentWithState structure")
1882 .into();
1883
1884 let t0 = Token::new(
1885 &Bytes::from_str("0x2260fac5e5542a773aa44fbcfedf7c193bc2c599").unwrap(),
1886 "WBTC",
1887 8,
1888 0,
1889 &[Some(10_000)],
1890 Chain::Ethereum,
1891 100,
1892 );
1893 let t1 = Token::new(
1894 &Bytes::from_str("0xdac17f958d2ee523a2206206994597c13d831ec7").unwrap(),
1895 "USDT",
1896 6,
1897 0,
1898 &[Some(10_000)],
1899 Chain::Ethereum,
1900 100,
1901 );
1902
1903 let all_tokens = [t0.clone(), t1.clone()]
1904 .iter()
1905 .map(|t| (t.address.clone(), t.clone()))
1906 .collect();
1907
1908 let usv4_state = UniswapV4State::try_from_with_header(
1909 state,
1910 block,
1911 &Default::default(),
1912 &all_tokens,
1913 &DecoderContext::new(),
1914 )
1915 .await
1916 .unwrap();
1917
1918 assert!(usv4_state.hook.is_none());
1921
1922 let res = usv4_state
1923 .get_limits(t0.address.clone(), t1.address.clone())
1924 .unwrap();
1925
1926 assert_eq!(&res.0, &BigUint::from_u128(71698353688830259750744466706).unwrap());
1927
1928 let out = usv4_state
1929 .get_amount_out(res.0, &t0, &t1)
1930 .expect("swap for limit in didn't work");
1931
1932 assert_eq!(&res.1, &out.amount);
1933 }
1934 type SeenCalls = Vec<(&'static str, Option<PendingOverrides>)>;
1936
1937 #[derive(Debug, Clone)]
1940 struct ConfigurableFeeHook {
1941 address: Address,
1942 pending_overrides: Option<Arc<PendingOverrides>>,
1943 seen: Arc<std::sync::Mutex<SeenCalls>>,
1944 }
1945
1946 impl ConfigurableFeeHook {
1947 fn new() -> Self {
1949 let mut address = [0u8; 20];
1950 address[19] = 0xC0;
1951 Self {
1952 address: Address::from_slice(&address),
1953 pending_overrides: None,
1954 seen: Arc::default(),
1955 }
1956 }
1957
1958 fn pending_fee(&self) -> U256 {
1959 self.pending_overrides
1960 .as_ref()
1961 .and_then(|p| p.storage.as_ref())
1962 .and_then(|storage| storage.get(&self.address))
1963 .and_then(|slots| slots.get(&U256::ZERO))
1964 .copied()
1965 .unwrap_or(U256::ZERO)
1966 }
1967 }
1968
1969 impl HookHandler for ConfigurableFeeHook {
1970 fn address(&self) -> Address {
1971 self.address
1972 }
1973
1974 #[expect(
1975 clippy::unwrap_in_result,
1976 reason = "test mock; a poisoned lock means a test already failed"
1977 )]
1978 fn before_swap(
1979 &self,
1980 _params: BeforeSwapParameters,
1981 _overwrites: Option<HashMap<Address, HashMap<U256, U256>>>,
1982 _transient_storage: Option<HashMap<Address, HashMap<U256, U256>>>,
1983 ) -> Result<WithGasEstimate<BeforeSwapOutput>, SimulationError> {
1984 self.seen.lock().unwrap().push((
1985 "before",
1986 self.pending_overrides
1987 .as_deref()
1988 .cloned(),
1989 ));
1990 Ok(WithGasEstimate {
1991 gas_estimate: 0,
1992 result: BeforeSwapOutput {
1993 amount_delta: BeforeSwapDelta(I256::ZERO),
1994 fee: U24::from(self.pending_fee()),
1995 overwrites: HashMap::new(),
1996 transient_storage: HashMap::new(),
1997 },
1998 })
1999 }
2000
2001 #[expect(
2002 clippy::unwrap_in_result,
2003 reason = "test mock; a poisoned lock means a test already failed"
2004 )]
2005 fn after_swap(
2006 &self,
2007 _params: AfterSwapParameters,
2008 _overwrites: Option<HashMap<Address, HashMap<U256, U256>>>,
2009 _transient_storage_params: Option<HashMap<Address, HashMap<U256, U256>>>,
2010 ) -> Result<WithGasEstimate<AfterSwapDelta>, SimulationError> {
2011 self.seen.lock().unwrap().push((
2012 "after",
2013 self.pending_overrides
2014 .as_deref()
2015 .cloned(),
2016 ));
2017 Ok(WithGasEstimate { gas_estimate: 0, result: I128::ZERO })
2018 }
2019
2020 fn fee(
2021 &self,
2022 _context: &UniswapV4State,
2023 _params: SwapParams,
2024 ) -> Result<f64, SimulationError> {
2025 Ok(0.0)
2026 }
2027
2028 fn spot_price(&self, _base: &Token, _quote: &Token) -> Result<f64, SimulationError> {
2029 Err(SimulationError::RecoverableError("not implemented".into()))
2030 }
2031
2032 fn get_amount_ranges(
2033 &self,
2034 _token_in: Bytes,
2035 _token_out: Bytes,
2036 ) -> Result<AmountRanges, SimulationError> {
2037 Err(SimulationError::RecoverableError("not implemented".into()))
2038 }
2039
2040 fn set_pending_overrides(&mut self, overrides: Arc<PendingOverrides>) {
2041 self.pending_overrides = Some(overrides);
2042 }
2043
2044 fn delta_transition(
2045 &mut self,
2046 _delta: ProtocolStateDelta,
2047 _tokens: &HashMap<Bytes, Token>,
2048 _balances: &Balances,
2049 ) -> Result<(), TransitionError> {
2050 Ok(())
2051 }
2052
2053 fn clone_box(&self) -> Box<dyn HookHandler> {
2054 Box::new(self.clone())
2055 }
2056
2057 fn as_any(&self) -> &dyn Any {
2058 self
2059 }
2060
2061 fn is_equal(&self, other: &dyn HookHandler) -> bool {
2062 other
2063 .as_any()
2064 .downcast_ref::<Self>()
2065 .is_some_and(|o| o.address == self.address)
2066 }
2067 }
2068
2069 fn hooked_pool(hook: &ConfigurableFeeHook) -> UniswapV4State {
2071 let liquidity = 1_000_000_000_000_000_000u128;
2072 let mut pool = UniswapV4State::new(
2073 liquidity,
2074 U256::from(1u8) << 96,
2075 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: lp_fee::DYNAMIC_FEE_FLAG },
2076 0,
2077 60,
2078 vec![
2079 TickInfo::new(-60, i128::try_from(liquidity).unwrap()).unwrap(),
2080 TickInfo::new(60, -(i128::try_from(liquidity).unwrap())).unwrap(),
2081 ],
2082 )
2083 .unwrap();
2084 pool.set_hook_handler(Box::new(hook.clone()));
2085 pool
2086 }
2087
2088 fn pending_fee_update(hook: &ConfigurableFeeHook, fee_pips: u64) -> PendingOverrides {
2089 PendingOverrides {
2090 storage: Some(HashMap::from([(
2091 hook.address,
2092 HashMap::from([(U256::ZERO, U256::from(fee_pips))]),
2093 )])),
2094 native_balances: None,
2095 block: None,
2096 }
2097 }
2098
2099 #[test]
2100 fn test_pending_overrides_reach_both_hook_calls_and_change_the_quote() {
2101 let hook = ConfigurableFeeHook::new();
2102 let amount_in = BigUint::from(1_000_000u64);
2103
2104 let confirmed = hooked_pool(&hook)
2105 .get_amount_out(amount_in.clone(), &token_x(), &token_y())
2106 .unwrap();
2107 let mut pool = hooked_pool(&hook);
2108 pool.set_pending_overrides(Arc::new(pending_fee_update(&hook, 100_000)))
2109 .unwrap();
2110 let pending = pool
2111 .get_amount_out(amount_in, &token_x(), &token_y())
2112 .unwrap();
2113
2114 assert!(
2115 pending.amount < confirmed.amount,
2116 "a 10% fee the pending block wrote must cut the output: {} vs {}",
2117 pending.amount,
2118 confirmed.amount
2119 );
2120 let seen = hook.seen.lock().unwrap();
2121 let calls: Vec<(&str, bool)> = seen
2122 .iter()
2123 .map(|(call, pending)| {
2124 (
2125 *call,
2126 pending
2127 .as_ref()
2128 .is_some_and(|p| p.storage.is_some()),
2129 )
2130 })
2131 .collect();
2132 assert_eq!(
2133 calls,
2134 vec![("before", false), ("after", false), ("before", true), ("after", true)],
2135 "the confirmed quote runs both calls without overrides, the pending one with them"
2136 );
2137 }
2138
2139 #[test]
2140 fn test_pending_overrides_survive_clone_box() {
2141 let hook = ConfigurableFeeHook::new();
2142 let mut pool = hooked_pool(&hook);
2143 pool.set_pending_overrides(Arc::new(pending_fee_update(&hook, 1)))
2144 .unwrap();
2145
2146 let cloned = pool.clone_box();
2147 let cloned = cloned
2148 .as_any()
2149 .downcast_ref::<UniswapV4State>()
2150 .unwrap();
2151
2152 assert!(cloned.pending_overrides().is_some(), "a clone quotes under the same overrides");
2153 }
2154
2155 #[test]
2156 fn test_set_pending_overrides_rejects_another_payload_type() {
2157 let hook = ConfigurableFeeHook::new();
2158 let mut pool = hooked_pool(&hook);
2159
2160 let result = pool.set_pending_overrides(Arc::new(0u8));
2161
2162 assert!(matches!(result, Err(SimulationError::FatalError(_))));
2163 assert!(pool.pending_overrides().is_none(), "a rejected payload sets nothing");
2164 assert!(hook.seen.lock().unwrap().is_empty());
2165 }
2166
2167 #[test]
2168 fn test_pending_overrides_are_not_part_of_equality() {
2169 let hook = ConfigurableFeeHook::new();
2170 let confirmed = hooked_pool(&hook);
2171 let mut pending = hooked_pool(&hook);
2172 pending
2173 .set_pending_overrides(Arc::new(pending_fee_update(&hook, 1)))
2174 .unwrap();
2175
2176 assert!(confirmed == pending, "PartialEq ignores the overrides");
2177 assert!(ProtocolSim::eq(&confirmed, &pending), "ProtocolSim::eq ignores the overrides");
2178 }
2179
2180 #[test]
2181 fn test_get_amount_out_no_hook() {
2182 let usv4_state = UniswapV4State::new(
2187 541501951282951892,
2188 U256::from_str("5362798333066270795901222").unwrap(), UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 100 },
2190 -192022,
2191 1,
2192 vec![
2194 TickInfo {
2195 index: -887272,
2196 net_liquidity: 460382969070005,
2197 sqrt_price: U256::from(4295128739_u64),
2198 },
2199 TickInfo {
2200 index: -207244,
2201 net_liquidity: 561268407024557,
2202 sqrt_price: U256::from_str("2505291706254206075074035").unwrap(),
2203 },
2204 TickInfo {
2205 index: -196411,
2206 net_liquidity: 825711941800452,
2207 sqrt_price: U256::from_str("4306080513146952705853399").unwrap(),
2208 },
2209 TickInfo {
2210 index: -196257,
2211 net_liquidity: 64844666874010,
2212 sqrt_price: U256::from_str("4339363644587371378270009").unwrap(),
2213 },
2214 TickInfo {
2215 index: -195611,
2216 net_liquidity: 2344045150766798,
2217 sqrt_price: U256::from_str("4481806029599743916020126").unwrap(),
2218 },
2219 TickInfo {
2220 index: -194715,
2221 net_liquidity: 391037380558274654,
2222 sqrt_price: U256::from_str("4687145946111116896040494").unwrap(),
2223 },
2224 TickInfo {
2225 index: -194599,
2226 net_liquidity: 89032603464508,
2227 sqrt_price: U256::from_str("4714409015946702405379370").unwrap(),
2228 },
2229 TickInfo {
2230 index: -194389,
2231 net_liquidity: 66635600426483168,
2232 sqrt_price: U256::from_str("4764168603367683402636621").unwrap(),
2233 },
2234 TickInfo {
2235 index: -194160,
2236 net_liquidity: 6123093436523361,
2237 sqrt_price: U256::from_str("4819029067726467394386780").unwrap(),
2238 },
2239 TickInfo {
2240 index: -194025,
2241 net_liquidity: 79940813798964,
2242 sqrt_price: U256::from_str("4851665907541490407930032").unwrap(),
2243 },
2244 TickInfo {
2245 index: -193922,
2246 net_liquidity: 415630967437234,
2247 sqrt_price: U256::from_str("4876715181040466809166531").unwrap(),
2248 },
2249 TickInfo {
2250 index: -193876,
2251 net_liquidity: 9664144015186047,
2252 sqrt_price: U256::from_str("4887943972687250473582419").unwrap(),
2253 },
2254 TickInfo {
2255 index: -193818,
2256 net_liquidity: 435344726052344,
2257 sqrt_price: U256::from_str("4902138873132735049121973").unwrap(),
2258 },
2259 TickInfo {
2260 index: -193804,
2261 net_liquidity: 221726179374067,
2262 sqrt_price: U256::from_str("4905571399964683340605904").unwrap(),
2263 },
2264 TickInfo {
2265 index: -193719,
2266 net_liquidity: 101340835774487,
2267 sqrt_price: U256::from_str("4926463397882393957462188").unwrap(),
2268 },
2269 TickInfo {
2270 index: -193690,
2271 net_liquidity: 193367475630077,
2272 sqrt_price: U256::from_str("4933611593595025190448924").unwrap(),
2273 },
2274 TickInfo {
2275 index: -193643,
2276 net_liquidity: 357016631583746,
2277 sqrt_price: U256::from_str("4945218633428068823432932").unwrap(),
2278 },
2279 TickInfo {
2280 index: -193520,
2281 net_liquidity: 917243184365178,
2282 sqrt_price: U256::from_str("4975723910367862081017120").unwrap(),
2283 },
2284 TickInfo {
2285 index: -193440,
2286 net_liquidity: 114125890211958292,
2287 sqrt_price: U256::from_str("4995665665861492533686137").unwrap(),
2288 },
2289 TickInfo {
2290 index: -193380,
2291 net_liquidity: -65980729148766579,
2292 sqrt_price: U256::from_str("5010674414300823856025303").unwrap(),
2293 },
2294 TickInfo {
2295 index: -192891,
2296 net_liquidity: 1687883551433195,
2297 sqrt_price: U256::from_str("5134689105039642314202223").unwrap(),
2298 },
2299 TickInfo {
2300 index: -192573,
2301 net_liquidity: 11108903221360975,
2302 sqrt_price: U256::from_str("5216979018647067786855495").unwrap(),
2303 },
2304 TickInfo {
2305 index: -192448,
2306 net_liquidity: 32888457482352,
2307 sqrt_price: U256::from_str("5249685603828944002327927").unwrap(),
2308 },
2309 TickInfo {
2310 index: -191525,
2311 net_liquidity: -221726179374067,
2312 sqrt_price: U256::from_str("5497623359964843320146512").unwrap(),
2313 },
2314 TickInfo {
2315 index: -191447,
2316 net_liquidity: -32888457482352,
2317 sqrt_price: U256::from_str("5519104878745833608097296").unwrap(),
2318 },
2319 TickInfo {
2320 index: -191444,
2321 net_liquidity: -114125890211958292,
2322 sqrt_price: U256::from_str("5519932765173943847315221").unwrap(),
2323 },
2324 TickInfo {
2325 index: -191417,
2326 net_liquidity: -101340835774487,
2327 sqrt_price: U256::from_str("5527389333636021285046380").unwrap(),
2328 },
2329 TickInfo {
2330 index: -191384,
2331 net_liquidity: -9664144015186047,
2332 sqrt_price: U256::from_str("5536516597603056457376182").unwrap(),
2333 },
2334 TickInfo {
2335 index: -191148,
2336 net_liquidity: -561268407024557,
2337 sqrt_price: U256::from_str("5602231161238705865493165").unwrap(),
2338 },
2339 TickInfo {
2340 index: -191147,
2341 net_liquidity: -1687883551433195,
2342 sqrt_price: U256::from_str("5602511265794328966803451").unwrap(),
2343 },
2344 TickInfo {
2345 index: -191091,
2346 net_liquidity: -89032603464508,
2347 sqrt_price: U256::from_str("5618219493196441347292357").unwrap(),
2348 },
2349 TickInfo {
2350 index: -190950,
2351 net_liquidity: -189177935487638,
2352 sqrt_price: U256::from_str("5657965894785859782969011").unwrap(),
2353 },
2354 TickInfo {
2355 index: -190756,
2356 net_liquidity: -6123093436523361,
2357 sqrt_price: U256::from_str("5713112435031881967192022").unwrap(),
2358 },
2359 TickInfo {
2360 index: -190548,
2361 net_liquidity: -193367475630077,
2362 sqrt_price: U256::from_str("5772835841671084402427710").unwrap(),
2363 },
2364 TickInfo {
2365 index: -190430,
2366 net_liquidity: -11108903221360975,
2367 sqrt_price: U256::from_str("5806994534290341208820930").unwrap(),
2368 },
2369 TickInfo {
2370 index: -190195,
2371 net_liquidity: -391583014714302569,
2372 sqrt_price: U256::from_str("5875625707132601785181387").unwrap(),
2373 },
2374 TickInfo {
2375 index: -190043,
2376 net_liquidity: -357016631583746,
2377 sqrt_price: U256::from_str("5920448331650864936739481").unwrap(),
2378 },
2379 TickInfo {
2380 index: -189779,
2381 net_liquidity: -917243184365178,
2382 sqrt_price: U256::from_str("5999112356918485175181346").unwrap(),
2383 },
2384 TickInfo {
2385 index: -189663,
2386 net_liquidity: -2344045150766798,
2387 sqrt_price: U256::from_str("6034006559279282606084981").unwrap(),
2388 },
2389 TickInfo {
2390 index: -189620,
2391 net_liquidity: -435344726052344,
2392 sqrt_price: U256::from_str("6046992979471024289177519").unwrap(),
2393 },
2394 TickInfo {
2395 index: -189409,
2396 net_liquidity: -825711941800452,
2397 sqrt_price: U256::from_str("6111123241285165242130911").unwrap(),
2398 },
2399 TickInfo {
2400 index: -189325,
2401 net_liquidity: -3947182209207,
2402 sqrt_price: U256::from_str("6136842645893819031257990").unwrap(),
2403 },
2404 TickInfo {
2405 index: -189324,
2406 net_liquidity: -415630967437234,
2407 sqrt_price: U256::from_str("6137149480355443943537284").unwrap(),
2408 },
2409 TickInfo {
2410 index: -115136,
2411 net_liquidity: 462452451821,
2412 sqrt_price: U256::from_str("250529060232794967902094762").unwrap(),
2413 },
2414 TickInfo {
2415 index: -92109,
2416 net_liquidity: -462452451821,
2417 sqrt_price: U256::from_str("792242363124136400178523925").unwrap(),
2418 },
2419 TickInfo {
2420 index: 887272,
2421 net_liquidity: -521280453734808,
2422 sqrt_price: U256::from_str("1461446703485210103287273052203988822378723970342")
2423 .unwrap(),
2424 },
2425 ],
2426 )
2427 .unwrap();
2428
2429 let t0 = usdc();
2430 let t1 = eth();
2431
2432 let out = usv4_state
2433 .get_amount_out(BigUint::from_u64(2000000).unwrap(), &t0, &t1)
2434 .unwrap();
2435
2436 assert_eq!(out.amount, BigUint::from_str("436478419853848").unwrap())
2437 }
2438
2439 #[test]
2440 fn test_get_amount_out_euler_hook() {
2441 let block = BlockHeader {
2457 number: 22689128,
2458 hash: Bytes::from_str(
2459 "0xfbfa716523d25d6d5248c18d001ca02b1caf10cabd1ab7321465e2262c41157b",
2460 )
2461 .expect("Invalid block hash"),
2462 timestamp: 1749739055,
2463 ..Default::default()
2464 };
2465
2466 let mut usv4_state = UniswapV4State::new(
2469 0,
2470 U256::from_str("4295128740").unwrap(),
2471 UniswapV4Fees { zero_for_one: 100, one_for_zero: 90, lp_fee: 500 },
2472 0,
2473 1,
2474 vec![],
2475 )
2476 .unwrap();
2477
2478 let hook_address: Address = Address::from_str("0x69058613588536167ba0aa94f0cc1fe420ef28a8")
2479 .expect("Invalid hook address");
2480
2481 let db = SimulationDB::new(
2482 get_client(None).expect("Failed to create client"),
2483 get_runtime().expect("Failed to get runtime"),
2484 Some(block),
2485 );
2486 let engine = create_engine(db, true).expect("Failed to create simulation engine");
2487 let pool_manager = Address::from_str("0x000000000004444c5dc75cb358380d2e3de08a90")
2488 .expect("Invalid pool manager address");
2489
2490 let hook_handler = GenericVMHookHandler::new(
2491 hook_address,
2492 engine,
2493 pool_manager,
2494 HashMap::new(),
2495 HashMap::new(),
2496 None,
2497 true, )
2499 .unwrap();
2500
2501 let t0 = usdc();
2502 let t1 = weth();
2503
2504 usv4_state.set_hook_handler(Box::new(hook_handler));
2505 let out = usv4_state
2506 .get_amount_out(BigUint::from_u64(7407000000).unwrap(), &t0, &t1)
2507 .unwrap();
2508
2509 assert_eq!(out.amount, BigUint::from_str("2681115183499232721").unwrap())
2510 }
2511
2512 #[test]
2513 fn test_get_amount_out_angstrom_hook() {
2514 let mut usv4_state = UniswapV4State::new(
2516 66319800403673162,
2518 U256::from_str("1314588940601923011323000261788004").unwrap(),
2519 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 8388608 },
2521 194343,
2522 10,
2523 vec![
2524 TickInfo::new(-887270, 198117767801).unwrap(),
2525 TickInfo::new(191990, 24561988698695).unwrap(),
2526 TickInfo::new(192280, 2839631428751224).unwrap(),
2527 TickInfo::new(193130, 318786492813931).unwrap(),
2528 TickInfo::new(194010, 26209207141081).unwrap(),
2529 TickInfo::new(194210, -26209207141081).unwrap(),
2530 TickInfo::new(194220, 63136622375641511).unwrap(),
2531 TickInfo::new(194420, -63136622375641511).unwrap(),
2532 TickInfo::new(195130, -318786492813931).unwrap(),
2533 TickInfo::new(196330, -2839631428751224).unwrap(),
2534 TickInfo::new(197100, -24561988698695).unwrap(),
2535 TickInfo::new(887270, -198117767801).unwrap(),
2536 ],
2537 )
2538 .unwrap();
2539
2540 let fees = AngstromFees {
2541 unlock: U24::from(338),
2548 protocol_unlock: U24::from(112),
2549 };
2550 let hook_handler = AngstromHookHandler::new(
2551 Address::from_str("0x0000000aa232009084bd71a5797d089aa4edfad4").unwrap(),
2552 Address::from_str("0x000000000004444c5dc75cb358380d2e3de08a90").unwrap(),
2553 fees,
2554 false,
2555 );
2556
2557 let t0 = usdc();
2558 let t1 = weth();
2559
2560 usv4_state.set_hook_handler(Box::new(hook_handler));
2561 let out = usv4_state
2562 .get_amount_out(
2563 BigUint::from_u64(
2564 6645198144, )
2566 .unwrap(),
2567 &t0, &t1, )
2570 .unwrap();
2571
2572 assert_eq!(out.amount, BigUint::from_str("1825627051870330472").unwrap())
2573 }
2574
2575 #[derive(Debug, Clone, PartialEq, Eq)]
2577 struct AfterSwapTestHook {
2578 address: Address,
2579 delta: I128,
2580 analytic_fee_bps: Option<u32>,
2583 spot_price_override: Option<u64>,
2586 after_swap_failure: Option<AfterSwapFailure>,
2588 }
2589
2590 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2592 enum AfterSwapFailure {
2593 Refuses,
2595 CannotSimulate,
2597 }
2598
2599 impl HookHandler for AfterSwapTestHook {
2600 fn address(&self) -> Address {
2601 self.address
2602 }
2603
2604 fn before_swap(
2605 &self,
2606 _: BeforeSwapParameters,
2607 _: Option<HashMap<Address, HashMap<U256, U256>>>,
2608 _: Option<HashMap<Address, HashMap<U256, U256>>>,
2609 ) -> Result<WithGasEstimate<BeforeSwapOutput>, SimulationError> {
2610 Err(SimulationError::RecoverableError("not implemented".into()))
2611 }
2612
2613 fn after_swap(
2614 &self,
2615 _: AfterSwapParameters,
2616 _: Option<HashMap<Address, HashMap<U256, U256>>>,
2617 _: Option<HashMap<Address, HashMap<U256, U256>>>,
2618 ) -> Result<WithGasEstimate<AfterSwapDelta>, SimulationError> {
2619 match self.after_swap_failure {
2620 Some(AfterSwapFailure::Refuses) => {
2621 Err(SimulationError::InvalidInput("refused by the hook".into(), None))
2622 }
2623 Some(AfterSwapFailure::CannotSimulate) => {
2624 Err(SimulationError::RecoverableError("the hook did not run".into()))
2625 }
2626 None => Ok(WithGasEstimate {
2627 gas_estimate: AFTER_SWAP_TEST_HOOK_GAS,
2628 result: self.delta,
2629 }),
2630 }
2631 }
2632
2633 fn fee(&self, _: &UniswapV4State, _: SwapParams) -> Result<f64, SimulationError> {
2634 Err(SimulationError::RecoverableError("not implemented".into()))
2635 }
2636
2637 fn spot_price(&self, _: &Token, _: &Token) -> Result<f64, SimulationError> {
2638 match self.spot_price_override {
2639 Some(price) => Ok(price as f64),
2640 None => Err(SimulationError::RecoverableError("not implemented".into())),
2641 }
2642 }
2643
2644 fn unspecified_fee_amount(
2645 &self,
2646 unspecified: U256,
2647 _: bool,
2648 ) -> Result<Option<U256>, SimulationError> {
2649 let Some(bps) = self.analytic_fee_bps else { return Ok(None) };
2650 Ok(Some(unspecified * U256::from(bps) / U256::from(10_000u64)))
2651 }
2652
2653 fn get_amount_ranges(&self, _: Bytes, _: Bytes) -> Result<AmountRanges, SimulationError> {
2654 Err(SimulationError::RecoverableError("not implemented".into()))
2655 }
2656
2657 fn delta_transition(
2658 &mut self,
2659 _: ProtocolStateDelta,
2660 _: &HashMap<Bytes, Token>,
2661 _: &Balances,
2662 ) -> Result<(), TransitionError> {
2663 Ok(())
2664 }
2665
2666 fn clone_box(&self) -> Box<dyn HookHandler> {
2667 Box::new(self.clone())
2668 }
2669
2670 fn as_any(&self) -> &dyn Any {
2671 self
2672 }
2673
2674 fn is_equal(&self, other: &dyn HookHandler) -> bool {
2675 other.as_any().downcast_ref::<Self>() == Some(self)
2676 }
2677 }
2678
2679 const AFTER_SWAP_TEST_HOOK_GAS: u64 = 1_000;
2682 const AFTER_SWAP_TEST_HOOK_DELTA: u64 = 777;
2683
2684 fn construct_hook_address(hook_options: &[HookOptions]) -> Address {
2685 let mut hook_flags = U160::ZERO;
2686 let one = U160::from_limbs([1, 0, 0]);
2687 for hook_option in hook_options {
2688 hook_flags |= one << (*hook_option as u8);
2689 }
2690 Address::from(hook_flags)
2691 }
2692
2693 fn after_swap_test_hook(hook_options: &[HookOptions]) -> Box<dyn HookHandler> {
2694 Box::new(AfterSwapTestHook {
2695 address: construct_hook_address(hook_options),
2696 delta: I128::unchecked_from(AFTER_SWAP_TEST_HOOK_DELTA),
2697 analytic_fee_bps: None,
2698 spot_price_override: None,
2699 after_swap_failure: None,
2700 })
2701 }
2702
2703 fn analytic_fee_test_hook(analytic_fee_bps: u32) -> Box<dyn HookHandler> {
2705 Box::new(AfterSwapTestHook {
2706 address: construct_hook_address(&[
2707 HookOptions::AfterSwap,
2708 HookOptions::AfterSwapReturnsDelta,
2709 ]),
2710 delta: I128::ZERO,
2711 analytic_fee_bps: Some(analytic_fee_bps),
2712 spot_price_override: None,
2713 after_swap_failure: None,
2714 })
2715 }
2716
2717 const TEST_HOOK_SPOT_PRICE: u64 = 1_000_000;
2720
2721 fn pricing_test_hook(analytic_fee_bps: Option<u32>) -> Box<dyn HookHandler> {
2724 Box::new(AfterSwapTestHook {
2725 address: construct_hook_address(&[
2726 HookOptions::AfterSwap,
2727 HookOptions::AfterSwapReturnsDelta,
2728 ]),
2729 delta: I128::ZERO,
2730 analytic_fee_bps,
2731 spot_price_override: Some(TEST_HOOK_SPOT_PRICE),
2732 after_swap_failure: None,
2733 })
2734 }
2735
2736 fn basic_v4_test_pool_tokens(zero_for_one: bool) -> (Token, Token) {
2737 if zero_for_one {
2738 (token_x(), token_y())
2739 } else {
2740 (token_y(), token_x())
2741 }
2742 }
2743
2744 #[rstest]
2747 #[case::zero_for_one(true)]
2748 #[case::one_for_zero(false)]
2749 fn test_after_swap_delta_ignored_without_returns_delta_permission(#[case] zero_for_one: bool) {
2750 let (token_in, token_out) = basic_v4_test_pool_tokens(zero_for_one);
2751 let amount_in = BigUint::from(1_000_000_000_000_000u64);
2752
2753 let hookless = create_basic_v4_test_pool()
2754 .get_amount_out(amount_in.clone(), &token_in, &token_out)
2755 .expect("hookless swap should succeed");
2756
2757 let mut pool = create_basic_v4_test_pool();
2758 pool.set_hook_handler(after_swap_test_hook(&[HookOptions::AfterSwap]));
2759 let gated = pool
2760 .get_amount_out(amount_in, &token_in, &token_out)
2761 .expect("gated swap should succeed");
2762
2763 assert_eq!(gated.amount, hookless.amount);
2764 assert_eq!(
2765 gated.gas,
2766 hookless.gas + BigUint::from(AFTER_SWAP_TEST_HOOK_GAS + PM_PER_HOOK_CALL_OVERHEAD)
2767 );
2768 }
2769
2770 #[rstest]
2773 #[case::zero_for_one(true)]
2774 #[case::one_for_zero(false)]
2775 fn test_after_swap_delta_applied_with_returns_delta_permission(#[case] zero_for_one: bool) {
2776 let (token_in, token_out) = basic_v4_test_pool_tokens(zero_for_one);
2777 let amount_in = BigUint::from(1_000_000_000_000_000u64);
2778
2779 let hookless = create_basic_v4_test_pool()
2780 .get_amount_out(amount_in.clone(), &token_in, &token_out)
2781 .expect("hookless swap should succeed");
2782
2783 let mut pool = create_basic_v4_test_pool();
2784 pool.set_hook_handler(after_swap_test_hook(&[
2785 HookOptions::AfterSwap,
2786 HookOptions::AfterSwapReturnsDelta,
2787 ]));
2788 let with_delta = pool
2789 .get_amount_out(amount_in, &token_in, &token_out)
2790 .expect("swap with hook delta should succeed");
2791
2792 assert_eq!(with_delta.amount, &hookless.amount - BigUint::from(AFTER_SWAP_TEST_HOOK_DELTA));
2793 assert_eq!(
2794 with_delta.gas,
2795 hookless.gas + BigUint::from(AFTER_SWAP_TEST_HOOK_GAS + PM_PER_HOOK_CALL_OVERHEAD)
2796 );
2797 }
2798
2799 #[rstest]
2802 #[case::refusal_passes_through(AfterSwapFailure::Refuses, true)]
2803 #[case::other_failure_is_fatal(AfterSwapFailure::CannotSimulate, false)]
2804 fn test_after_swap_failure_reaches_the_caller_by_kind(
2805 #[case] failure: AfterSwapFailure,
2806 #[case] expect_invalid_input: bool,
2807 ) {
2808 let (token_in, token_out) = basic_v4_test_pool_tokens(true);
2809 let mut pool = create_basic_v4_test_pool();
2810 pool.set_hook_handler(Box::new(AfterSwapTestHook {
2811 address: construct_hook_address(&[HookOptions::AfterSwap]),
2812 delta: I128::ZERO,
2813 analytic_fee_bps: None,
2814 spot_price_override: None,
2815 after_swap_failure: Some(failure),
2816 }));
2817
2818 let result =
2819 pool.get_amount_out(BigUint::from(1_000_000_000_000_000u64), &token_in, &token_out);
2820
2821 match result {
2822 Err(SimulationError::InvalidInput(msg, None)) if expect_invalid_input => {
2823 assert_eq!(msg, "refused by the hook");
2824 }
2825 Err(SimulationError::FatalError(msg)) if !expect_invalid_input => {
2826 assert!(msg.starts_with("AfterSwap hook simulation failed"), "{msg}");
2827 }
2828 other => panic!("expected the {failure:?} failure, got {other:?}"),
2829 }
2830 }
2831
2832 #[derive(Debug, Clone, PartialEq, Eq)]
2835 struct LimitOrderTestHook {
2836 fill_sqrt_price: U256,
2837 fill_in: u128,
2839 fill_out: u128,
2840 }
2841
2842 impl LimitOrderTestHook {
2843 fn fill_delta(&self) -> BeforeSwapDelta {
2844 let specified = U256::from(self.fill_in) << 128;
2845 let unspecified = U256::from(self.fill_out.wrapping_neg());
2848 BeforeSwapDelta(I256::from_raw(specified | unspecified))
2849 }
2850 }
2851
2852 impl HookHandler for LimitOrderTestHook {
2853 fn address(&self) -> Address {
2854 construct_hook_address(&[HookOptions::BeforeSwap, HookOptions::BeforeSwapReturnsDelta])
2855 }
2856
2857 fn before_swap(
2858 &self,
2859 params: BeforeSwapParameters,
2860 _: Option<HashMap<Address, HashMap<U256, U256>>>,
2861 _: Option<HashMap<Address, HashMap<U256, U256>>>,
2862 ) -> Result<WithGasEstimate<BeforeSwapOutput>, SimulationError> {
2863 let limit = params.swap_params.sqrt_price_limit;
2864 let limit_reaches_order = if params.swap_params.zero_for_one {
2865 limit <= self.fill_sqrt_price
2866 } else {
2867 limit >= self.fill_sqrt_price
2868 };
2869 let amount_delta =
2870 if limit_reaches_order { self.fill_delta() } else { BeforeSwapDelta(I256::ZERO) };
2871 Ok(WithGasEstimate {
2872 gas_estimate: 0,
2873 result: BeforeSwapOutput {
2874 amount_delta,
2875 fee: U24::ZERO,
2876 overwrites: HashMap::new(),
2877 transient_storage: HashMap::new(),
2878 },
2879 })
2880 }
2881
2882 fn after_swap(
2883 &self,
2884 _: AfterSwapParameters,
2885 _: Option<HashMap<Address, HashMap<U256, U256>>>,
2886 _: Option<HashMap<Address, HashMap<U256, U256>>>,
2887 ) -> Result<WithGasEstimate<AfterSwapDelta>, SimulationError> {
2888 Err(SimulationError::FatalError("hook has no afterSwap permission".into()))
2889 }
2890
2891 fn fee(&self, _: &UniswapV4State, _: SwapParams) -> Result<f64, SimulationError> {
2892 Err(SimulationError::RecoverableError("not implemented".into()))
2893 }
2894
2895 fn spot_price(&self, _: &Token, _: &Token) -> Result<f64, SimulationError> {
2896 Err(SimulationError::RecoverableError("not implemented".into()))
2897 }
2898
2899 fn get_amount_ranges(&self, _: Bytes, _: Bytes) -> Result<AmountRanges, SimulationError> {
2900 Err(SimulationError::RecoverableError("not implemented".into()))
2901 }
2902
2903 fn delta_transition(
2904 &mut self,
2905 _: ProtocolStateDelta,
2906 _: &HashMap<Bytes, Token>,
2907 _: &Balances,
2908 ) -> Result<(), TransitionError> {
2909 Ok(())
2910 }
2911
2912 fn clone_box(&self) -> Box<dyn HookHandler> {
2913 Box::new(self.clone())
2914 }
2915
2916 fn as_any(&self) -> &dyn Any {
2917 self
2918 }
2919
2920 fn is_equal(&self, other: &dyn HookHandler) -> bool {
2921 other.as_any().downcast_ref::<Self>() == Some(self)
2922 }
2923 }
2924
2925 #[rstest]
2928 #[case::zero_for_one(true)]
2929 #[case::one_for_zero(false)]
2930 fn test_before_swap_limit_order_fill(#[case] zero_for_one: bool) {
2931 let (token_in, token_out) = basic_v4_test_pool_tokens(zero_for_one);
2932 let amount_in = 1_000_000_000_000_000_000u128;
2933 let fill_in = amount_in / 2;
2934 let fill_out = 123_456_789u128;
2935
2936 let mut pool = create_basic_v4_test_pool();
2937 let fill_sqrt_price = if zero_for_one {
2939 pool.sqrt_price * U256::from(99u8) / U256::from(100u8)
2940 } else {
2941 pool.sqrt_price * U256::from(101u8) / U256::from(100u8)
2942 };
2943 let remainder = create_basic_v4_test_pool()
2944 .get_amount_out(BigUint::from(amount_in - fill_in), &token_in, &token_out)
2945 .expect("hookless swap of the remainder should succeed");
2946
2947 pool.set_hook_handler(Box::new(LimitOrderTestHook { fill_sqrt_price, fill_in, fill_out }));
2948 let quote = pool
2949 .get_amount_out(BigUint::from(amount_in), &token_in, &token_out)
2950 .expect("hooked swap should succeed");
2951
2952 assert_eq!(quote.amount, remainder.amount + BigUint::from(fill_out));
2953 }
2954
2955 const FEELESS_POOL_LIQUIDITY: u128 = 100_000_000_000_000_000_000; fn create_feeless_v4_test_pool(liquidity: u128) -> UniswapV4State {
2961 let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
2962 .expect("a price of two has a square root");
2963 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("the sqrt price maps to a tick");
2964 let position = i128::try_from(FEELESS_POOL_LIQUIDITY).unwrap();
2965
2966 UniswapV4State::new(
2967 liquidity,
2968 sqrt_price,
2969 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 0 },
2970 tick,
2971 60,
2972 vec![
2973 TickInfo::new(-46_080, position).unwrap(),
2974 TickInfo::new(46_080, -position).unwrap(),
2975 ],
2976 )
2977 .expect("the pool builds")
2978 }
2979
2980 fn pons_test_handler() -> PonsV2HookHandler {
2981 PonsV2HookHandler::new(PONS_V2_HOOK_ROBINHOOD, 100, 100)
2982 }
2983
2984 #[test]
2989 fn hookless_spot_price_is_the_documented_buy_price_with_lp_fee_markup() {
2990 const LP_FEE_PIPS: u32 = 3_000;
2991 const LP_FEE: f64 = LP_FEE_PIPS as f64 / 1_000_000.0;
2992 const LIQUIDITY: u128 = 100_000_000_000_000_000_000; const TOLERANCE: f64 = 1e-12;
2994
2995 let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
2996 .expect("a price of two has a square root");
2997 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("the sqrt price maps to a tick");
2998 let pool = UniswapV4State::new(
2999 LIQUIDITY,
3000 sqrt_price,
3001 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: LP_FEE_PIPS },
3002 tick,
3003 60,
3004 vec![
3005 TickInfo::new(-46_080, i128::try_from(LIQUIDITY).unwrap()).unwrap(),
3006 TickInfo::new(46_080, -(i128::try_from(LIQUIDITY).unwrap())).unwrap(),
3007 ],
3008 )
3009 .expect("the pool builds");
3010
3011 assert!(pool.hook.is_none(), "the pinned values only hold with no hook handler");
3012
3013 let (t0, t1) = (token_x(), token_y());
3014 let pre_fee = sqrt_price_q96_to_f64(sqrt_price, t0.decimals, t1.decimals)
3015 .expect("the sqrt price converts to a price");
3016
3017 let expected_buy_t0 = pre_fee / (1.0 - LP_FEE);
3018 let expected_buy_t1 = (1.0 / pre_fee) / (1.0 - LP_FEE);
3019
3020 let buy_t0 = pool
3021 .spot_price(&t0, &t1)
3022 .expect("a hookless pool always prices");
3023 let buy_t1 = pool
3024 .spot_price(&t1, &t0)
3025 .expect("a hookless pool always prices");
3026
3027 assert!(
3028 (buy_t0 / expected_buy_t0 - 1.0).abs() < TOLERANCE,
3029 "buying t0 quoted {buy_t0}, expected {expected_buy_t0}"
3030 );
3031 assert!(
3032 (buy_t1 / expected_buy_t1 - 1.0).abs() < TOLERANCE,
3033 "buying t1 quoted {buy_t1}, expected {expected_buy_t1}"
3034 );
3035 }
3036
3037 #[rstest]
3041 #[case::base_is_currency0(true)]
3042 #[case::base_is_currency1(false)]
3043 fn test_spot_price_marks_up_an_analytic_hook_fee(#[case] base_is_currency0: bool) {
3044 let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
3045 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3046 hooked.set_hook_handler(Box::new(pons_test_handler()));
3047
3048 let core = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
3049 .spot_price(&base, "e)
3050 .expect("a hookless pool always prices");
3051 let price = hooked
3052 .spot_price(&base, "e)
3053 .expect("the hook prices its own fee");
3054
3055 assert!(price > core, "hooked {price} is not above hookless {core}");
3056 let ratio = price / core;
3057 assert!((ratio * 0.98 - 1.0).abs() < 1e-9, "hooked/hookless is {ratio}, not 1/0.98");
3058 }
3059
3060 #[rstest]
3063 #[case::base_is_currency0(true)]
3064 #[case::base_is_currency1(false)]
3065 fn test_hooked_spot_price_matches_a_small_hooked_buy(#[case] base_is_currency0: bool) {
3066 let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
3067 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3068 hooked.set_hook_handler(Box::new(pons_test_handler()));
3069
3070 let quote_in = BigUint::from(100_000_000_000_000u64);
3071 let base_out = hooked
3072 .get_amount_out(quote_in.clone(), "e, &base)
3073 .expect("a tiny buy always fits the pool")
3074 .amount;
3075
3076 let executed = quote_in.to_f64().unwrap() / base_out.to_f64().unwrap();
3077 let spot = hooked
3078 .spot_price(&base, "e)
3079 .expect("the hook prices its own fee");
3080
3081 assert!((executed / spot - 1.0).abs() < 1e-4, "executed {executed}, quoted {spot}");
3082 }
3083
3084 #[rstest]
3088 #[case::base_is_currency0(true)]
3089 #[case::base_is_currency1(false)]
3090 fn test_spot_price_prefers_an_analytic_fee_over_the_hooks_own_price(
3091 #[case] base_is_currency0: bool,
3092 ) {
3093 let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
3094 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3095 hooked.set_hook_handler(pricing_test_hook(Some(200)));
3096
3097 let core = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
3098 .spot_price(&base, "e)
3099 .expect("a hookless pool always prices");
3100 let price = hooked
3101 .spot_price(&base, "e)
3102 .expect("the hook prices its own fee");
3103
3104 assert_ne!(
3105 price, TEST_HOOK_SPOT_PRICE as f64,
3106 "the pool asked the hook for a price instead of marking up its own"
3107 );
3108 let ratio = price / core;
3109 assert!((ratio * 0.98 - 1.0).abs() < 1e-9, "hooked/hookless is {ratio}, not 1/0.98");
3110 }
3111
3112 #[rstest]
3116 #[case::base_is_currency0(true)]
3117 #[case::base_is_currency1(false)]
3118 fn test_spot_price_uses_the_hooks_own_price_without_an_analytic_fee(
3119 #[case] base_is_currency0: bool,
3120 ) {
3121 let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
3122 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3123 hooked.set_hook_handler(pricing_test_hook(None));
3124
3125 let price = hooked
3126 .spot_price(&base, "e)
3127 .expect("the hook answers with a price");
3128
3129 assert_eq!(price, TEST_HOOK_SPOT_PRICE as f64);
3130 }
3131
3132 #[rstest]
3135 #[case::base_is_currency0(true)]
3136 #[case::base_is_currency1(false)]
3137 fn test_spot_price_falls_back_to_finite_difference_without_an_analytic_fee(
3138 #[case] base_is_currency0: bool,
3139 ) {
3140 let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
3141 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3142 hooked.set_hook_handler(after_swap_test_hook(&[
3143 HookOptions::AfterSwap,
3144 HookOptions::AfterSwapReturnsDelta,
3145 ]));
3146
3147 let x1 = BigUint::from(10u64).pow(base.decimals) / BigUint::from(100u64);
3148 let x2 = &x1 + (&x1 / BigUint::from(100u64));
3149 let y1 = hooked
3150 .get_amount_out(x1.clone(), &base, "e)
3151 .expect("the smaller probe swap fits")
3152 .amount;
3153 let y2 = hooked
3154 .get_amount_out(x2.clone(), &base, "e)
3155 .expect("the larger probe swap fits")
3156 .amount;
3157 let slope = (&y2 - &y1).to_f64().unwrap() / (&x2 - &x1).to_f64().unwrap();
3158
3159 let price = hooked
3160 .spot_price(&base, "e)
3161 .expect("the fallback always prices");
3162
3163 assert_eq!(price, slope);
3164 let core = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
3165 .spot_price(&base, "e)
3166 .expect("a hookless pool always prices");
3167 assert!((price / core - 1.0).abs() < 1e-3, "fallback {price} strayed from core {core}");
3168 }
3169
3170 #[rstest]
3173 #[case::zero_for_one(true)]
3174 #[case::one_for_zero(false)]
3175 fn test_get_limits_reports_the_output_net_of_an_analytic_hook_fee(#[case] zero_for_one: bool) {
3176 let (token_in, token_out) = basic_v4_test_pool_tokens(zero_for_one);
3177 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3178 hooked.set_hook_handler(Box::new(pons_test_handler()));
3179
3180 let (hookless_in, hookless_out) = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
3181 .get_limits(token_in.address.clone(), token_out.address.clone())
3182 .expect("a pool with liquidity has limits");
3183 let (limit_in, limit_out) = hooked
3184 .get_limits(token_in.address, token_out.address)
3185 .expect("a pool with liquidity has limits");
3186
3187 assert!(hookless_out > BigUint::zero(), "the reference pool must move some output");
3188 assert_eq!(limit_in, hookless_in);
3189 let taken = pons_test_handler()
3190 .fee_and_tax(biguint_to_uint(&hookless_out).unwrap())
3191 .expect("a pool sized output never overflows");
3192 assert_eq!(limit_out, &hookless_out - u256_to_biguint(taken));
3193 assert!(limit_out < hookless_out);
3194 }
3195
3196 #[rstest]
3199 #[case::zero_for_one(true)]
3200 #[case::one_for_zero(false)]
3201 fn test_get_limits_unchanged_without_an_analytic_hook_fee(#[case] zero_for_one: bool) {
3202 let (token_in, token_out) = basic_v4_test_pool_tokens(zero_for_one);
3203 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3204 hooked.set_hook_handler(after_swap_test_hook(&[
3205 HookOptions::AfterSwap,
3206 HookOptions::AfterSwapReturnsDelta,
3207 ]));
3208
3209 let hookless = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
3210 .get_limits(token_in.address.clone(), token_out.address.clone())
3211 .expect("a pool with liquidity has limits");
3212 let limits = hooked
3213 .get_limits(token_in.address, token_out.address)
3214 .expect("a pool with liquidity has limits");
3215
3216 assert_eq!(limits, hookless);
3217 }
3218
3219 #[test]
3222 fn test_get_limits_on_a_drained_pool_is_zero_with_an_analytic_hook() {
3223 let (token_in, token_out) = basic_v4_test_pool_tokens(true);
3224 let mut drained = create_feeless_v4_test_pool(0);
3225 drained.set_hook_handler(Box::new(pons_test_handler()));
3226
3227 let limits = drained
3228 .get_limits(token_in.address, token_out.address)
3229 .expect("a drained pool reports zero rather than failing");
3230
3231 assert_eq!(limits, (BigUint::zero(), BigUint::zero()));
3232 }
3233
3234 #[rstest]
3237 #[case::the_whole_output(10_000)]
3238 #[case::more_than_the_whole_output(20_000)]
3239 fn test_spot_price_rejects_a_hook_that_takes_the_whole_output(#[case] analytic_fee_bps: u32) {
3240 let mut pool = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3241 pool.set_hook_handler(analytic_fee_test_hook(analytic_fee_bps));
3242
3243 let error = pool
3244 .spot_price(&token_x(), &token_y())
3245 .expect_err("a rate of one or more is not a price");
3246
3247 assert!(matches!(error, SimulationError::FatalError(_)), "{error:?}");
3248 }
3249
3250 #[rstest]
3253 #[case::base_is_currency0(true)]
3254 #[case::base_is_currency1(false)]
3255 fn test_spot_price_marks_up_the_hooks_lp_fee_and_hook_fee(#[case] base_is_currency0: bool) {
3256 let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
3257 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3258 hooked.set_hook_handler(Box::new(ExtensionTestHook {
3259 spot_fees: SpotFeesAnswer::Fees(HookSpotFees {
3260 lp_fee_override: Some(10_000),
3261 hook_fee_pips: 20_000,
3262 }),
3263 ..Default::default()
3264 }));
3265
3266 let core = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
3267 .spot_price(&base, "e)
3268 .expect("a hookless pool always prices");
3269 let price = hooked
3270 .spot_price(&base, "e)
3271 .expect("the hook states its fees");
3272
3273 let ratio = price / core;
3274 assert!(
3275 (ratio * 0.99 * 0.98 - 1.0).abs() < 1e-9,
3276 "hooked/hookless is {ratio}, not 1/(0.99 * 0.98)"
3277 );
3278 }
3279
3280 #[test]
3282 fn test_spot_price_keeps_the_pool_lp_fee_without_an_override() {
3283 let mut hooked = create_basic_v4_test_pool();
3284 hooked.set_hook_handler(Box::new(ExtensionTestHook {
3285 spot_fees: SpotFeesAnswer::Fees(HookSpotFees {
3286 lp_fee_override: None,
3287 hook_fee_pips: 0,
3288 }),
3289 ..Default::default()
3290 }));
3291 let (base, quote) = basic_v4_test_pool_tokens(true);
3292
3293 let price = hooked
3294 .spot_price(&base, "e)
3295 .expect("the hook states its fees");
3296
3297 assert_eq!(
3298 price,
3299 create_basic_v4_test_pool()
3300 .spot_price(&base, "e)
3301 .expect("a hookless pool always prices")
3302 );
3303 }
3304
3305 #[test]
3306 fn test_spot_price_rejects_hook_fees_that_take_the_whole_swap() {
3307 let mut pool = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3308 pool.set_hook_handler(Box::new(ExtensionTestHook {
3309 spot_fees: SpotFeesAnswer::Fees(HookSpotFees {
3310 lp_fee_override: None,
3311 hook_fee_pips: 1_000_000,
3312 }),
3313 ..Default::default()
3314 }));
3315
3316 let error = pool
3317 .spot_price(&token_x(), &token_y())
3318 .expect_err("a rate of one is not a price");
3319
3320 assert!(matches!(error, SimulationError::FatalError(_)), "{error:?}");
3321 }
3322
3323 #[rstest]
3325 #[case::refusal(SpotFeesAnswer::Refuses, true)]
3326 #[case::failure(SpotFeesAnswer::Fails, false)]
3327 fn test_spot_price_reports_the_error_of_spot_fees(
3328 #[case] answer: SpotFeesAnswer,
3329 #[case] is_invalid_input: bool,
3330 ) {
3331 let mut pool = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3332 pool.set_hook_handler(Box::new(ExtensionTestHook {
3333 spot_fees: answer,
3334 ..Default::default()
3335 }));
3336
3337 let error = pool
3338 .spot_price(&token_x(), &token_y())
3339 .expect_err("the hook's error stops the pricing");
3340
3341 assert_eq!(
3342 matches!(error, SimulationError::InvalidInput(..)),
3343 is_invalid_input,
3344 "{error:?}"
3345 );
3346 }
3347
3348 #[test]
3350 fn test_get_limits_reports_the_hooks_max_amount_in() {
3351 let max_in = U256::from(1_000_000_000_000_000u64);
3352 let mut pool = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3353 pool.set_hook_handler(Box::new(ExtensionTestHook {
3354 max_amount_in: Some(max_in),
3355 ..Default::default()
3356 }));
3357 let (token_in, token_out) = basic_v4_test_pool_tokens(true);
3358
3359 let limits = pool
3360 .get_limits(token_in.address.clone(), token_out.address.clone())
3361 .expect("the hook bounds the limits");
3362
3363 let quote = pool
3364 .get_amount_out(u256_to_biguint(max_in), &token_in, &token_out)
3365 .expect("the bounded input swaps");
3366 assert_eq!(limits, (u256_to_biguint(max_in), quote.amount));
3367 }
3368
3369 #[test]
3370 fn test_get_limits_reports_zero_when_the_hook_allows_no_input() {
3371 let mut pool = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3372 pool.set_hook_handler(Box::new(ExtensionTestHook {
3373 max_amount_in: Some(U256::ZERO),
3374 ..Default::default()
3375 }));
3376 let (token_in, token_out) = basic_v4_test_pool_tokens(true);
3377
3378 let limits = pool
3379 .get_limits(token_in.address, token_out.address)
3380 .expect("a zero bound is a limit");
3381
3382 assert_eq!(limits, (BigUint::zero(), BigUint::zero()));
3383 }
3384
3385 #[rstest]
3387 #[case::ends_below_the_floor(U256::MAX, true)]
3388 #[case::ends_above_the_floor(U256::ZERO, false)]
3389 fn test_get_amount_out_refuses_a_swap_outcome_the_hook_rejects(
3390 #[case] floor: U256,
3391 #[case] refused: bool,
3392 ) {
3393 let mut pool = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3394 pool.set_hook_handler(Box::new(ExtensionTestHook {
3395 outcome_check: OutcomeCheckAnswer::RefusesBelow(floor),
3396 ..Default::default()
3397 }));
3398 let (token_in, token_out) = basic_v4_test_pool_tokens(true);
3399
3400 let result =
3401 pool.get_amount_out(BigUint::from(1_000_000_000_000_000u64), &token_in, &token_out);
3402
3403 match result {
3404 Err(SimulationError::InvalidInput(msg, None)) if refused => {
3405 assert_eq!(msg, "the swap ends below the floor");
3406 }
3407 Ok(_) if !refused => {}
3408 other => panic!("expected refused = {refused}, got {other:?}"),
3409 }
3410 }
3411
3412 #[test]
3416 fn test_get_amount_out_reports_a_failing_outcome_check_as_fatal() {
3417 let mut pool = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3418 pool.set_hook_handler(Box::new(ExtensionTestHook {
3419 outcome_check: OutcomeCheckAnswer::Fails,
3420 ..Default::default()
3421 }));
3422 let (token_in, token_out) = basic_v4_test_pool_tokens(true);
3423
3424 let result =
3425 pool.get_amount_out(BigUint::from(1_000_000_000_000_000u64), &token_in, &token_out);
3426
3427 assert!(
3428 matches!(&result, Err(SimulationError::FatalError(msg))
3429 if msg.starts_with("CheckSwapOutcome hook simulation failed")),
3430 "{result:?}"
3431 );
3432 }
3433
3434 fn hook_address_of(state: &dyn ProtocolSim) -> Address {
3436 state
3437 .as_any()
3438 .downcast_ref::<UniswapV4State>()
3439 .and_then(|state| state.hook.as_ref())
3440 .expect("a hooked pool")
3441 .address()
3442 }
3443
3444 #[test]
3447 fn test_get_amount_out_installs_the_hook_after_the_swap() {
3448 let installed = Address::repeat_byte(7);
3449 let (token_in, token_out) = basic_v4_test_pool_tokens(true);
3450 let amount_in = BigUint::from(1_000_000_000_000_000u64);
3451 let hookless = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
3452 .get_amount_out(amount_in.clone(), &token_in, &token_out)
3453 .expect("the hookless swap");
3454 let mut pool = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3455 pool.set_hook_handler(Box::new(ExtensionTestHook {
3456 handler_after_swap: HandlerAfterSwapAnswer::ReplaceWithAddress(installed),
3457 ..Default::default()
3458 }));
3459
3460 let quote = pool
3461 .get_amount_out(amount_in, &token_in, &token_out)
3462 .expect("the swap");
3463
3464 assert_eq!(hook_address_of(quote.new_state.as_ref()), installed);
3465 assert_eq!(hook_address_of(&pool), Address::ZERO);
3466 assert_eq!(quote.amount, hookless.amount);
3467 assert_eq!(quote.gas, hookless.gas);
3468 }
3469
3470 #[test]
3472 fn test_get_amount_out_keeps_the_hook_that_answers_none() {
3473 let (token_in, token_out) = basic_v4_test_pool_tokens(true);
3474 let mut pool = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3475 pool.set_hook_handler(Box::new(ExtensionTestHook {
3476 address: Address::repeat_byte(3),
3477 ..Default::default()
3478 }));
3479
3480 let quote = pool
3481 .get_amount_out(BigUint::from(1_000_000_000_000_000u64), &token_in, &token_out)
3482 .expect("the swap");
3483
3484 assert_eq!(hook_address_of(quote.new_state.as_ref()), Address::repeat_byte(3));
3485 }
3486
3487 #[test]
3491 fn test_get_amount_out_of_a_hook_taking_the_whole_input_charges_the_noop_swap() {
3492 let (token_in, token_out) = basic_v4_test_pool_tokens(true);
3493 let mut pool = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3494 pool.set_hook_handler(Box::new(ExtensionTestHook {
3495 takes_whole_input: Some(WHOLE_INPUT_TEST_HOOK_GAS),
3496 ..Default::default()
3497 }));
3498
3499 let quote = pool
3500 .get_amount_out(BigUint::from(1_000_000u64), &token_in, &token_out)
3501 .expect("the swap");
3502
3503 assert_eq!(quote.amount, BigUint::from(1_000_000u64));
3504 assert_eq!(
3505 quote.gas,
3506 BigUint::from(3_000 + WHOLE_INPUT_TEST_HOOK_GAS + PM_PER_HOOK_CALL_OVERHEAD)
3507 );
3508 }
3509
3510 #[rstest]
3513 #[case::refusal_passes_through(HandlerAfterSwapAnswer::Refuses, true)]
3514 #[case::other_failure_is_fatal(HandlerAfterSwapAnswer::Fails, false)]
3515 fn test_get_amount_out_maps_a_handler_after_swap_error_by_kind(
3516 #[case] answer: HandlerAfterSwapAnswer,
3517 #[case] expect_invalid_input: bool,
3518 ) {
3519 let (token_in, token_out) = basic_v4_test_pool_tokens(true);
3520 let mut pool = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
3521 pool.set_hook_handler(Box::new(ExtensionTestHook {
3522 handler_after_swap: answer,
3523 ..Default::default()
3524 }));
3525
3526 let result =
3527 pool.get_amount_out(BigUint::from(1_000_000_000_000_000u64), &token_in, &token_out);
3528
3529 match result {
3530 Err(SimulationError::InvalidInput(msg, None)) if expect_invalid_input => {
3531 assert_eq!(msg, "the hook refuses the swap");
3532 }
3533 Err(SimulationError::FatalError(msg)) if !expect_invalid_input => {
3534 assert!(msg.starts_with("HandlerAfterSwap hook simulation failed"), "{msg}");
3535 }
3536 other => panic!("expected the {answer:?} answer by kind, got {other:?}"),
3537 }
3538 }
3539
3540 fn pool_target_price_params() -> QueryPoolSwapParams {
3541 QueryPoolSwapParams::new(
3542 token_x(),
3543 token_y(),
3544 SwapConstraint::PoolTargetPrice {
3545 target: Price::new(BigUint::from(2_000_000u64), BigUint::from(1_010_000u64)),
3546 tolerance: 0f64,
3547 min_amount_in: None,
3548 max_amount_in: None,
3549 },
3550 )
3551 }
3552
3553 #[rstest]
3556 #[case::no_fees(SpotFeesAnswer::NoFees, "ok")]
3557 #[case::fees(
3558 SpotFeesAnswer::Fees(HookSpotFees { lp_fee_override: Some(500), hook_fee_pips: 100 }),
3559 "invalid_input"
3560 )]
3561 #[case::refusal(SpotFeesAnswer::Refuses, "invalid_input")]
3562 #[case::failure(SpotFeesAnswer::Fails, "fatal")]
3563 fn test_query_pool_swap_declines_a_direction_whose_fees_the_hook_sets(
3564 #[case] answer: SpotFeesAnswer,
3565 #[case] expected: &str,
3566 ) {
3567 let mut pool = create_basic_v4_test_pool();
3568 pool.set_hook_handler(Box::new(ExtensionTestHook {
3569 spot_fees: answer,
3570 ..Default::default()
3571 }));
3572
3573 let result = pool.query_pool_swap(&pool_target_price_params());
3574
3575 let outcome = match &result {
3576 Ok(_) => "ok",
3577 Err(SimulationError::InvalidInput(..)) => "invalid_input",
3578 Err(SimulationError::FatalError(_)) => "fatal",
3579 Err(_) => "other",
3580 };
3581 assert_eq!(outcome, expected, "{result:?}");
3582 }
3583
3584 #[test]
3585 fn test_spot_price_with_recoverable_error() {
3586 let usv4_state = UniswapV4State::new(
3590 1000000000000000000u128, U256::from_str("79228162514264337593543950336").unwrap(), UniswapV4Fees { zero_for_one: 100, one_for_zero: 100, lp_fee: 100 },
3593 0,
3594 60,
3595 vec![
3596 TickInfo::new(-600, 500000000000000000i128).unwrap(),
3597 TickInfo::new(600, -500000000000000000i128).unwrap(),
3598 ],
3599 )
3600 .unwrap();
3601
3602 let spot_price_result = usv4_state.spot_price(&usdc(), &weth());
3604 assert!(spot_price_result.is_ok());
3605
3606 let price = spot_price_result.unwrap();
3609 assert!(price > 0.0);
3610 }
3611
3612 #[test]
3613 fn test_get_limits_with_hook_managed_liquidity_no_ranges_entrypoint() {
3614 let block = BlockHeader {
3619 number: 22689128,
3620 hash: Bytes::from_str(
3621 "0xfbfa716523d25d6d5248c18d001ca02b1caf10cabd1ab7321465e2262c41157b",
3622 )
3623 .expect("Invalid block hash"),
3624 timestamp: 1749739055,
3625 ..Default::default()
3626 };
3627
3628 let hook_address: Address = Address::from_str("0x69058613588536167ba0aa94f0cc1fe420ef28a8")
3629 .expect("Invalid hook address");
3630
3631 let db = SimulationDB::new(
3632 get_client(None).expect("Failed to create client"),
3633 get_runtime().expect("Failed to get runtime"),
3634 Some(block),
3635 );
3636 let engine = create_engine(db, true).expect("Failed to create simulation engine");
3637 let pool_manager = Address::from_str("0x000000000004444c5dc75cb358380d2e3de08a90")
3638 .expect("Invalid pool manager address");
3639
3640 let hook_handler = GenericVMHookHandler::new(
3643 hook_address,
3644 engine,
3645 pool_manager,
3646 HashMap::new(),
3647 HashMap::new(),
3648 None,
3649 true, )
3651 .unwrap();
3652
3653 let mut usv4_state = UniswapV4State::new(
3655 0, U256::from_str("4295128740").unwrap(),
3657 UniswapV4Fees { zero_for_one: 100, one_for_zero: 90, lp_fee: 500 },
3658 0, 1, vec![], )
3662 .unwrap();
3663
3664 usv4_state.set_hook_handler(Box::new(hook_handler));
3665
3666 let token_in = usdc().address;
3667 let token_out = weth().address;
3668
3669 let (amount_in_limit, amount_out_limit) = usv4_state
3670 .get_limits(token_in, token_out)
3671 .expect("Should find limits through experimental swapping");
3672
3673 assert!(amount_in_limit > BigUint::from(10u64).pow(12));
3676 assert!(amount_in_limit < BigUint::from(10u64).pow(14));
3677
3678 assert!(amount_out_limit > BigUint::from(10u64).pow(20));
3680 assert!(amount_out_limit < BigUint::from(10u64).pow(22));
3681 }
3682
3683 #[rstest]
3684 #[case::high_liquidity(u128::MAX / 2)] #[case::medium_liquidity(10000000000000000000u128)] #[case::minimal_liquidity(1000u128)] fn test_find_max_amount(#[case] liquidity: u128) {
3688 let fees = UniswapV4Fees { zero_for_one: 100, one_for_zero: 100, lp_fee: 100 };
3690 let tick_spacing = 60;
3691 let ticks = vec![
3692 TickInfo::new(-600, i128::try_from(liquidity / 4).unwrap()).unwrap(),
3693 TickInfo::new(600, -(i128::try_from(liquidity / 4).unwrap())).unwrap(),
3694 ];
3695
3696 let usv4_state = UniswapV4State::new(
3697 liquidity,
3698 U256::from_str("79228162514264337593543950336").unwrap(),
3699 fees,
3700 0,
3701 tick_spacing,
3702 ticks,
3703 )
3704 .unwrap();
3705
3706 let token_in = usdc();
3707 let token_out = weth();
3708
3709 let (max_amount_in, _max_amount_out) = usv4_state.find_max_amount(&token_in, &token_out);
3710
3711 let success = usv4_state
3712 .get_amount_out(max_amount_in.clone(), &token_in, &token_out)
3713 .is_ok();
3714 assert!(success, "Should be able to swap the exact max amount.");
3715
3716 let one_more = &max_amount_in + BigUint::from(1u64);
3717 let should_fail = usv4_state
3718 .get_amount_out(one_more, &token_in, &token_out)
3719 .is_err();
3720 assert!(should_fail, "Swapping max_amount + 1 should fail.");
3721 }
3722
3723 #[test]
3724 fn test_calculate_swap_fees_with_override() {
3725 let fees = UniswapV4Fees::new(100, 90, 500);
3727
3728 let total_zero_for_one = fees
3731 .calculate_swap_fees_pips(true, None)
3732 .unwrap();
3733 assert_eq!(total_zero_for_one, 600);
3735
3736 let total_with_override = fees
3738 .calculate_swap_fees_pips(true, Some(1000))
3739 .unwrap();
3740 assert_eq!(total_with_override, 1100);
3742 }
3743
3744 #[test]
3745 fn test_max_combined_fees_stays_valid() {
3746 let fees = UniswapV4Fees::new(1000, 1000, 1000);
3748 let total = fees
3749 .calculate_swap_fees_pips(true, Some(lp_fee::MAX_LP_FEE))
3750 .unwrap();
3751
3752 assert_eq!(total, 1_000_000);
3755 }
3756
3757 #[test]
3758 fn test_get_limits_graceful_underflow() {
3759 let usv4_state = UniswapV4State::new(
3761 1000000,
3762 U256::from_str("79228162514264337593543950336").unwrap(), UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 },
3764 0,
3765 60,
3766 vec![
3767 TickInfo {
3770 index: -60,
3771 net_liquidity: 2000000, sqrt_price: U256::from_str("79051508376726796163471739988").unwrap(),
3773 },
3774 ],
3775 )
3776 .unwrap();
3777
3778 let usdc = usdc();
3779 let weth = weth();
3780
3781 let (limit_in, limit_out) = usv4_state
3782 .get_limits(usdc.address, weth.address)
3783 .unwrap();
3784
3785 assert!(limit_in > BigUint::zero());
3787 assert!(limit_out > BigUint::zero());
3788 }
3789
3790 const MAX_PROTOCOL_FEE: u32 = 1000;
3795
3796 #[rstest]
3797 #[case::max_protocol_and_max_lp(MAX_PROTOCOL_FEE, lp_fee::MAX_LP_FEE, lp_fee::MAX_LP_FEE)]
3798 #[case::max_protocol_with_3000_lp(MAX_PROTOCOL_FEE, 3000, 3997)]
3799 #[case::max_protocol_with_zero_lp(MAX_PROTOCOL_FEE, 0, MAX_PROTOCOL_FEE)]
3800 #[case::zero_protocol_zero_lp(0, 0, 0)]
3801 #[case::zero_protocol_with_1000_lp(0, 1000, 1000)]
3802 fn test_calculate_swap_fees_uniswap_test_cases(
3803 #[case] protocol_fee: u32,
3804 #[case] lp_fee: u32,
3805 #[case] expected: u32,
3806 ) {
3807 let fees = UniswapV4Fees::new(protocol_fee, protocol_fee, lp_fee);
3808 let result = fees
3809 .calculate_swap_fees_pips(true, None)
3810 .unwrap();
3811 assert_eq!(result, expected);
3812 }
3813
3814 #[test]
3815 fn test_calculate_swap_fees_with_dynamic_fee() {
3816 let fees = UniswapV4Fees::new(100, 90, lp_fee::DYNAMIC_FEE_FLAG);
3818
3819 let total_zero_for_one = fees
3821 .calculate_swap_fees_pips(true, None)
3822 .unwrap();
3823 assert_eq!(total_zero_for_one, 100);
3825
3826 let total_with_override = fees
3828 .calculate_swap_fees_pips(true, Some(500))
3829 .unwrap();
3830 assert_eq!(total_with_override, 600);
3832 }
3833
3834 #[test]
3835 fn test_calculate_swap_fees_direction_matters() {
3836 let fees = UniswapV4Fees::new(100, 200, 500);
3838
3839 let zero_for_one_fee = fees
3840 .calculate_swap_fees_pips(true, None)
3841 .unwrap();
3842 assert_eq!(zero_for_one_fee, 600);
3844
3845 let one_for_zero_fee = fees
3846 .calculate_swap_fees_pips(false, None)
3847 .unwrap();
3848 assert_eq!(one_for_zero_fee, 700);
3850 }
3851
3852 #[rstest]
3853 #[case::high_lp_fee(1000, 500_000, 500_500)] #[case::mid_fees(500, 500_000, 500_250)] #[case::low_fees(100, 100_000, 100_090)] fn test_calculate_swap_fees_formula_precision(
3857 #[case] protocol_fee: u32,
3858 #[case] lp_fee: u32,
3859 #[case] expected: u32,
3860 ) {
3861 let fees = UniswapV4Fees::new(protocol_fee, protocol_fee, lp_fee);
3864 let result = fees
3865 .calculate_swap_fees_pips(true, None)
3866 .unwrap();
3867 assert_eq!(result, expected, "Failed for protocol={}, lp={}", protocol_fee, lp_fee);
3868 }
3869
3870 #[test]
3871 fn test_calculate_swap_fees_override_takes_precedence() {
3872 let fees = UniswapV4Fees::new(100, 100, 3000);
3874
3875 let result = fees
3877 .calculate_swap_fees_pips(true, Some(5000))
3878 .unwrap();
3879 assert_eq!(result, 5100);
3881
3882 let result_no_override = fees
3884 .calculate_swap_fees_pips(true, None)
3885 .unwrap();
3886 assert_eq!(result_no_override, 3100);
3888 }
3889
3890 #[test]
3891 fn test_calculate_swap_fees_zero_protocol_fee() {
3892 let fees = UniswapV4Fees::new(0, 0, 3000);
3894 let result = fees
3895 .calculate_swap_fees_pips(true, None)
3896 .unwrap();
3897 assert_eq!(result, 3000);
3899 }
3900
3901 #[test]
3902 fn test_calculate_swap_fees_zero_lp_fee() {
3903 let fees = UniswapV4Fees::new(500, 500, 0);
3905 let result = fees
3906 .calculate_swap_fees_pips(true, None)
3907 .unwrap();
3908 assert_eq!(result, 500);
3910 }
3911
3912 fn create_basic_v4_test_pool() -> UniswapV4State {
3914 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))
3916 .expect("Failed to calculate sqrt price");
3917 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
3918
3919 let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
3920
3921 UniswapV4State::new(
3922 liquidity,
3923 sqrt_price,
3924 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 }, tick,
3926 60, ticks,
3928 )
3929 .expect("Failed to create pool")
3930 }
3931
3932 fn create_tick_boundary_v4_test_pool() -> UniswapV4State {
3933 let sqrt_price = get_sqrt_ratio_at_tick(0).expect("Failed to calculate sqrt price");
3934 let ticks = vec![TickInfo::new(-120, 0).unwrap(), TickInfo::new(120, 0).unwrap()];
3935
3936 UniswapV4State::new(
3937 100_000_000_000_000_000_000u128,
3938 sqrt_price,
3939 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 },
3940 0,
3941 60,
3942 ticks,
3943 )
3944 .expect("Failed to create pool")
3945 }
3946
3947 fn create_two_range_v4_test_pool() -> UniswapV4State {
3951 let (outer, inner) = (1_000_000_000_000_000_000_i128, 4_000_000_000_000_000_000_i128);
3952 let ticks = vec![
3953 TickInfo::new(-6000, outer).unwrap(),
3954 TickInfo::new(-60, inner).unwrap(),
3955 TickInfo::new(60, -inner).unwrap(),
3956 TickInfo::new(6000, -outer).unwrap(),
3957 ];
3958 UniswapV4State::new(
3959 u128::try_from(outer + inner).unwrap(),
3960 get_sqrt_ratio_at_tick(0).unwrap(),
3961 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 },
3962 0,
3963 60,
3964 ticks,
3965 )
3966 .expect("Failed to create pool")
3967 }
3968
3969 const TWO_RANGE_SWAP_AMOUNT: u64 = 100_000_000_000_000_000;
3970
3971 fn two_range_swap_gas(pool: &UniswapV4State) -> u64 {
3972 let amount = -I256::from_raw(U256::from(TWO_RANGE_SWAP_AMOUNT));
3973 pool.swap(true, amount, None, None)
3974 .expect("the swap ends inside the outer range")
3975 .gas_used
3976 .to::<u64>()
3977 }
3978
3979 #[rstest]
3980 #[case::uniswap_v4(SwapGasCosts::UNISWAP_V4)]
3981 #[case::infinity_cl(SwapGasCosts::PANCAKESWAP_INFINITY_CL)]
3982 fn test_swap_gas_follows_the_states_gas_costs(#[case] gas_costs: SwapGasCosts) {
3983 let mut pool = create_two_range_v4_test_pool();
3986 pool.set_gas_costs(SwapGasCosts {
3987 base: 0,
3988 per_bitmap_lookup: 1,
3989 per_tick: 1_000_000,
3990 settlement: 0,
3991 });
3992 let counted = two_range_swap_gas(&pool);
3993 let (ticks, lookups) = (counted / 1_000_000, counted % 1_000_000);
3994 assert_eq!(ticks, 1, "the swap crosses tick -60 only");
3995 assert!(lookups >= 2, "the swap walks past tick -60: {lookups} lookups");
3996
3997 pool.set_gas_costs(gas_costs);
3998
3999 assert_eq!(
4000 two_range_swap_gas(&pool),
4001 gas_costs.base +
4002 lookups * gas_costs.per_bitmap_lookup +
4003 ticks * gas_costs.per_tick +
4004 gas_costs.settlement
4005 );
4006 }
4007
4008 #[test]
4009 fn test_serde_roundtrip_keeps_gas_costs() {
4010 let mut pool = create_two_range_v4_test_pool();
4011 pool.set_gas_costs(SwapGasCosts::PANCAKESWAP_INFINITY_CL);
4012
4013 let json = serde_json::to_string(&pool).expect("hookless state should serialize");
4014 let deserialized: UniswapV4State =
4015 serde_json::from_str(&json).expect("state should deserialize");
4016
4017 assert_eq!(two_range_swap_gas(&deserialized), two_range_swap_gas(&pool));
4018 }
4019
4020 #[test]
4021 fn test_state_serialized_without_gas_costs_prices_as_uniswap_v4() {
4022 let mut pool = create_two_range_v4_test_pool();
4023 pool.set_gas_costs(SwapGasCosts::PANCAKESWAP_INFINITY_CL);
4024 let mut json = serde_json::to_value(&pool).expect("hookless state should serialize");
4025 json.as_object_mut()
4026 .expect("the state serializes to an object")
4027 .remove("gas_costs");
4028
4029 let deserialized: UniswapV4State =
4030 serde_json::from_value(json).expect("state should deserialize");
4031
4032 let uniswap_v4 = create_two_range_v4_test_pool();
4033 assert_eq!(two_range_swap_gas(&deserialized), two_range_swap_gas(&uniswap_v4));
4034 }
4035
4036 #[test]
4037 fn test_partial_step_updates_tick_when_price_moves_without_crossing_initialized_tick() {
4038 let pool = create_tick_boundary_v4_test_pool();
4039 let amount = -I256::from_raw(U256::from(100_000_000_000_000_000u64));
4040
4041 let result = pool
4042 .swap(true, amount, None, None)
4043 .expect("swap should stay within the current liquidity range");
4044 let expected_tick =
4045 get_tick_at_sqrt_ratio(result.sqrt_price).expect("new sqrt price should map to a tick");
4046
4047 assert_ne!(result.sqrt_price, pool.sqrt_price);
4048 assert_ne!(result.sqrt_price, get_sqrt_ratio_at_tick(-120).unwrap());
4049 assert_ne!(expected_tick, pool.tick.value());
4050 assert_eq!(result.tick.value(), expected_tick);
4051 }
4052
4053 fn empty_range_pool() -> UniswapV4State {
4056 let liquidity = 1_000_000_000_000_000_000i128;
4057 UniswapV4State::new(
4058 0,
4059 U256::from(1u64) << 96,
4060 UniswapV4Fees::new(0, 0, 3_000),
4061 0,
4062 60,
4063 vec![TickInfo::new(-600, liquidity).unwrap(), TickInfo::new(0, -liquidity).unwrap()],
4064 )
4065 .unwrap()
4066 }
4067
4068 #[test]
4071 fn test_a_pool_without_active_liquidity_refuses_and_reports_no_limits() {
4072 let pool = empty_range_pool();
4073
4074 let quote =
4075 pool.get_amount_out(BigUint::from(1_000_000_000_000_000u64), &token_x(), &token_y());
4076 assert!(
4077 matches!("e, Err(SimulationError::RecoverableError(msg)) if msg == "No liquidity"),
4078 "{quote:?}"
4079 );
4080 let limits = pool
4081 .get_limits(token_x().address, token_y().address)
4082 .expect("limits");
4083 assert_eq!(limits, (BigUint::ZERO, BigUint::ZERO));
4084 }
4085
4086 #[test]
4091 fn test_swap_from_the_upper_edge_inside_the_position() {
4092 let liquidity = 1_000_000_000_000_000_000i128;
4093 let pool = UniswapV4State::new(
4094 liquidity.cast_unsigned(),
4095 U256::from(1u64) << 96,
4096 UniswapV4Fees::new(0, 0, 3_000),
4097 -1,
4098 60,
4099 vec![TickInfo::new(-600, liquidity).unwrap(), TickInfo::new(0, -liquidity).unwrap()],
4100 )
4101 .unwrap();
4102
4103 let out = pool
4104 .get_amount_out(BigUint::from(1_000_000_000_000_000u64), &token_x(), &token_y())
4105 .expect("the swap reaches the position");
4106
4107 assert_eq!(out.amount, BigUint::from(996_006_981_039_903u64));
4108 let new_state = out
4109 .new_state
4110 .as_any()
4111 .downcast_ref::<UniswapV4State>()
4112 .unwrap();
4113 assert_eq!(new_state.liquidity, 1_000_000_000_000_000_000u128);
4114 assert_eq!(new_state.sqrt_price, U256::from_str("79149250711305166342700278159").unwrap());
4115 }
4116
4117 #[test]
4120 fn test_get_limits_refuses_empty_range_swaps_without_max_amount_in() {
4121 let (token_in, token_out) = basic_v4_test_pool_tokens(true);
4122 let mut pool = create_basic_v4_test_pool();
4123 pool.set_hook_handler(Box::new(ExtensionTestHook {
4124 swaps_from_empty_range: true,
4125 ..Default::default()
4126 }));
4127
4128 let limits = pool.get_limits(token_in.address, token_out.address);
4129
4130 assert!(
4131 matches!(&limits, Err(SimulationError::FatalError(m)) if m.contains("no max_amount_in")),
4132 "{limits:?}"
4133 );
4134 }
4135
4136 #[test]
4139 fn test_swap_from_an_empty_range_fills_in_the_liquidity_ahead_for_an_opted_in_hook() {
4140 let mut pool = empty_range_pool();
4141 pool.set_hook_handler(Box::new(ExtensionTestHook {
4142 swaps_from_empty_range: true,
4143 ..Default::default()
4144 }));
4145
4146 let out = pool
4147 .get_amount_out(BigUint::from(1_000_000_000_000_000u64), &token_x(), &token_y())
4148 .expect("the opted-in hook swaps from the empty range");
4149
4150 assert_eq!(out.amount, BigUint::from(996_006_981_039_903u64));
4151 }
4152
4153 #[rstest]
4156 #[case::hook_accepts_the_leftover(false)]
4157 #[case::hook_refuses_the_leftover(true)]
4158 fn test_swap_past_the_last_tick_reports_the_unfilled_input(#[case] refuse_unfilled: bool) {
4159 let liquidity = 1_000_000_000_000_000_000i128;
4160 let mut pool = UniswapV4State::new(
4161 liquidity.cast_unsigned(),
4162 U256::from(1u64) << 96,
4163 UniswapV4Fees::new(0, 0, 3_000),
4164 -1,
4165 60,
4166 vec![TickInfo::new(-600, liquidity).unwrap(), TickInfo::new(0, -liquidity).unwrap()],
4167 )
4168 .unwrap();
4169 pool.set_hook_handler(Box::new(ExtensionTestHook {
4170 swaps_from_empty_range: true,
4171 outcome_check: if refuse_unfilled {
4172 OutcomeCheckAnswer::RefusesUnfilledInput
4173 } else {
4174 OutcomeCheckAnswer::Accepts
4175 },
4176 ..Default::default()
4177 }));
4178 let amount_in = BigUint::from(1_000_000_000_000_000_000u64);
4180
4181 let result = pool.get_amount_out(amount_in, &token_x(), &token_y());
4182
4183 match result {
4184 Err(SimulationError::InvalidInput(msg, None)) if refuse_unfilled => {
4185 assert_eq!(msg, "part of the input is unfilled");
4186 }
4187 Ok(out) if !refuse_unfilled => assert!(out.amount > BigUint::zero()),
4188 other => panic!("expected refuse_unfilled = {refuse_unfilled}, got {other:?}"),
4189 }
4190 }
4191
4192 #[test]
4194 fn test_swap_past_the_last_tick_without_the_opt_in_is_refused() {
4195 let liquidity = 1_000_000_000_000_000_000i128;
4196 let pool = UniswapV4State::new(
4197 liquidity.cast_unsigned(),
4198 U256::from(1u64) << 96,
4199 UniswapV4Fees::new(0, 0, 3_000),
4200 -1,
4201 60,
4202 vec![TickInfo::new(-600, liquidity).unwrap(), TickInfo::new(0, -liquidity).unwrap()],
4203 )
4204 .unwrap();
4205
4206 let result = pool.get_amount_out(
4207 BigUint::from(1_000_000_000_000_000_000u64),
4208 &token_x(),
4209 &token_y(),
4210 );
4211
4212 assert!(
4213 matches!(&result, Err(SimulationError::InvalidInput(m, _)) if m == "Ticks exceeded"),
4214 "{result:?}"
4215 );
4216 }
4217
4218 #[test]
4219 fn test_swap_keeps_boundary_tick_when_price_does_not_move() {
4220 let mut pool = create_tick_boundary_v4_test_pool();
4221 pool.tick = PoolTick::from(-1);
4222 let amount = -I256::from_raw(U256::from(1u64));
4223
4224 let result = pool
4225 .swap(true, amount, None, None)
4226 .expect("swap should consume the input as fee without moving price");
4227
4228 assert_eq!(result.sqrt_price, pool.sqrt_price);
4229 assert_eq!(get_tick_at_sqrt_ratio(result.sqrt_price).unwrap(), 0);
4230 assert_eq!(result.tick, pool.tick);
4231 }
4232
4233 #[test]
4234 fn test_swap_to_price_price_too_high() {
4235 let pool = create_basic_v4_test_pool();
4236
4237 let token_x = token_x();
4238 let token_y = token_y();
4239
4240 let target_price = Price::new(BigUint::from(10_000_000u64), BigUint::from(1_000_000u64));
4242
4243 let result = pool.query_pool_swap(&QueryPoolSwapParams::new(
4244 token_x,
4245 token_y,
4246 SwapConstraint::PoolTargetPrice {
4247 target: target_price,
4248 tolerance: 0f64,
4249 min_amount_in: None,
4250 max_amount_in: None,
4251 },
4252 ));
4253 assert!(result.is_err(), "Should return error when target price is unreachable");
4254 }
4255
4256 #[test]
4257 fn test_swap_to_price_no_liquidity() {
4258 let pool = UniswapV4State::new(
4260 0, U256::from_str("79228162514264337593543950336").unwrap(),
4262 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 },
4263 0,
4264 60,
4265 vec![],
4266 )
4267 .unwrap();
4268
4269 let token_x = token_x();
4270 let token_y = token_y();
4271
4272 let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_000_000u64));
4273
4274 let pool_swap = pool.query_pool_swap(&QueryPoolSwapParams::new(
4275 token_x,
4276 token_y,
4277 SwapConstraint::PoolTargetPrice {
4278 target: target_price,
4279 tolerance: 0f64,
4280 min_amount_in: None,
4281 max_amount_in: None,
4282 },
4283 ));
4284
4285 assert!(pool_swap.is_err());
4286 }
4287
4288 #[test]
4289 fn test_swap_to_price_with_protocol_fees() {
4290 let liquidity = 100_000_000_000_000_000_000u128;
4291 let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
4292 .expect("Failed to calculate sqrt price");
4293 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
4294
4295 let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
4296
4297 let pool = UniswapV4State::new(
4299 liquidity,
4300 sqrt_price,
4301 UniswapV4Fees {
4302 zero_for_one: 1000, one_for_zero: 200, lp_fee: 3000, },
4306 tick,
4307 60,
4308 ticks,
4309 )
4310 .expect("Failed to create pool");
4311
4312 let token_x = token_x();
4313 let token_y = token_y();
4314
4315 let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_010_000u64));
4319 let pool_swap_forward = pool
4320 .query_pool_swap(&QueryPoolSwapParams::new(
4321 token_x.clone(),
4322 token_y.clone(),
4323 SwapConstraint::PoolTargetPrice {
4324 target: target_price,
4325 tolerance: 0f64,
4326 min_amount_in: None,
4327 max_amount_in: None,
4328 },
4329 ))
4330 .expect("swap_to_price failed");
4331
4332 let target_price_reverse =
4334 Price::new(BigUint::from(1_010_000u64), BigUint::from(2_040_000u64));
4335 let pool_swap_backward = pool
4336 .query_pool_swap(&QueryPoolSwapParams::new(
4337 token_y,
4338 token_x,
4339 SwapConstraint::PoolTargetPrice {
4340 target: target_price_reverse,
4341 tolerance: 0f64,
4342 min_amount_in: None,
4343 max_amount_in: None,
4344 },
4345 ))
4346 .expect("swap_to_price failed");
4347
4348 assert!(
4349 pool_swap_backward.amount_out().clone() > BigUint::ZERO,
4350 "One for zero swap should return non-zero output"
4351 );
4352
4353 assert!(
4356 pool_swap_forward.amount_out() < pool_swap_backward.amount_in(),
4357 "Backward fees should be lower therefore backward swap should be bigger"
4358 );
4359 assert!(
4360 pool_swap_forward.amount_in() < pool_swap_backward.amount_out(),
4361 "Backward fees should be lower therefore backward swap should be bigger"
4362 );
4363 }
4364
4365 #[test]
4366 fn test_swap_to_price_different_targets() {
4367 let pool = create_basic_v4_test_pool();
4369
4370 let token_x = token_x();
4371 let token_y = token_y();
4372
4373 let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_010_000u64));
4376 let pool_swap_close = pool
4377 .query_pool_swap(&QueryPoolSwapParams::new(
4378 token_x.clone(),
4379 token_y.clone(),
4380 SwapConstraint::PoolTargetPrice {
4381 target: target_price,
4382 tolerance: 0f64,
4383 min_amount_in: None,
4384 max_amount_in: None,
4385 },
4386 ))
4387 .expect("swap_to_price failed");
4388 assert!(
4389 *pool_swap_close.amount_out() > BigUint::ZERO,
4390 "Expected non-zero for 1.98 Y/X target"
4391 );
4392
4393 let target_price = Price::new(BigUint::from(1_900_000u64), BigUint::from(1_000_000u64));
4395 let pool_swap_below = pool
4396 .query_pool_swap(&QueryPoolSwapParams::new(
4397 token_x.clone(),
4398 token_y.clone(),
4399 SwapConstraint::PoolTargetPrice {
4400 target: target_price,
4401 tolerance: 0f64,
4402 min_amount_in: None,
4403 max_amount_in: None,
4404 },
4405 ))
4406 .expect("swap_to_price failed");
4407 assert!(
4408 pool_swap_below.amount_out().clone() > BigUint::ZERO,
4409 "Expected non-zero for 1.90 Y/X target"
4410 );
4411
4412 let target_price = Price::new(BigUint::from(1_500_000u64), BigUint::from(1_000_000u64));
4414 let pool_swap_far = pool
4415 .query_pool_swap(&QueryPoolSwapParams::new(
4416 token_x,
4417 token_y,
4418 SwapConstraint::PoolTargetPrice {
4419 target: target_price,
4420 tolerance: 0f64,
4421 min_amount_in: None,
4422 max_amount_in: None,
4423 },
4424 ))
4425 .expect("swap_to_price failed");
4426 assert!(
4427 pool_swap_far.amount_out().clone() > BigUint::ZERO,
4428 "Expected non-zero for 1.5 Y/X target"
4429 );
4430
4431 assert!(
4433 pool_swap_close.amount_out().clone() < pool_swap_below.amount_out().clone(),
4434 "Closer target (1.98 Y/X) should require less volume than medium target (1.90 Y/X). \
4435 Got close: {}, medium: {}",
4436 pool_swap_close.amount_out().clone(),
4437 pool_swap_below.amount_out().clone()
4438 );
4439 assert!(
4440 pool_swap_below.amount_out().clone() < pool_swap_far.amount_out().clone(),
4441 "Medium target (1.90 Y/X) should require less volume than far target (1.5 Y/X). \
4442 Got medium: {}, far: {}",
4443 pool_swap_below.amount_out().clone(),
4444 pool_swap_far.amount_out().clone()
4445 );
4446 }
4447
4448 #[test]
4449 fn test_swap_to_price_around_spot_price() {
4450 let liquidity = 10_000_000_000_000_000u128;
4451 let sqrt_price =
4452 get_sqrt_price_q96(U256::from(2_000_000_000u64), U256::from(1_000_000_000u64))
4453 .expect("Failed to calculate sqrt price");
4454 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
4455
4456 let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
4457
4458 let pool = UniswapV4State::new(
4460 liquidity,
4461 sqrt_price,
4462 UniswapV4Fees {
4463 zero_for_one: 0,
4464 one_for_zero: 0,
4465 lp_fee: 500, },
4467 tick,
4468 60,
4469 ticks,
4470 )
4471 .expect("Failed to create pool");
4472
4473 let token_x = token_x();
4474 let token_y = token_y();
4475
4476 let target_price = Price::new(BigUint::from(1_999_750u64), BigUint::from(1_000_250u64));
4478
4479 let result = pool.query_pool_swap(&QueryPoolSwapParams::new(
4480 token_x.clone(),
4481 token_y.clone(),
4482 SwapConstraint::PoolTargetPrice {
4483 target: target_price,
4484 tolerance: 0f64,
4485 min_amount_in: None,
4486 max_amount_in: None,
4487 },
4488 ));
4489 assert!(result.is_err(), "Should return error when target price is unreachable");
4490
4491 let target_price = Price::new(BigUint::from(1_999_000u64), BigUint::from(1_001_000u64));
4493
4494 let pool_swap = pool
4495 .query_pool_swap(&QueryPoolSwapParams::new(
4496 token_x,
4497 token_y,
4498 SwapConstraint::PoolTargetPrice {
4499 target: target_price,
4500 tolerance: 0f64,
4501 min_amount_in: None,
4502 max_amount_in: None,
4503 },
4504 ))
4505 .expect("swap_to_price failed");
4506
4507 let expected_amount_out =
4509 BigUint::from_str("7062236922008").expect("Failed to parse expected value");
4510 assert_eq!(
4511 pool_swap.amount_out().clone(),
4512 expected_amount_out,
4513 "V4 should match V3 output with same fees (0.05%)"
4514 );
4515 }
4516
4517 #[test]
4518 fn test_swap_to_price_matches_get_amount_out() {
4519 let pool = create_basic_v4_test_pool();
4520
4521 let token_x = token_x();
4522 let token_y = token_y();
4523
4524 let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_010_000u64));
4526 let pool_swap = pool
4527 .query_pool_swap(&QueryPoolSwapParams::new(
4528 token_x.clone(),
4529 token_y.clone(),
4530 SwapConstraint::PoolTargetPrice {
4531 target: target_price,
4532 tolerance: 0f64,
4533 min_amount_in: None,
4534 max_amount_in: None,
4535 },
4536 ))
4537 .expect("swap_to_price failed");
4538 assert!(*pool_swap.amount_in() > BigUint::ZERO, "Amount in should be positive");
4539
4540 let result = pool
4542 .get_amount_out(pool_swap.amount_in().clone(), &token_x, &token_y)
4543 .expect("get_amount_out failed");
4544
4545 assert!(result.amount > BigUint::ZERO);
4548 assert!(result.amount >= *pool_swap.amount_out());
4549 }
4550
4551 #[test]
4552 fn test_swap_to_price_basic() {
4553 let liquidity = 100_000_000_000_000_000_000u128;
4554 let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
4555 .expect("Failed to calculate sqrt price");
4556 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
4557
4558 let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
4559
4560 let pool = UniswapV4State::new(
4561 liquidity,
4562 sqrt_price,
4563 UniswapV4Fees {
4564 zero_for_one: 0,
4565 one_for_zero: 0,
4566 lp_fee: 3000, },
4568 tick,
4569 60,
4570 ticks,
4571 )
4572 .expect("Failed to create pool");
4573
4574 let token_x = token_x();
4575 let token_y = token_y();
4576
4577 let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_010_000u64));
4579
4580 let pool_swap = pool
4581 .query_pool_swap(&QueryPoolSwapParams::new(
4582 token_x,
4583 token_y,
4584 SwapConstraint::PoolTargetPrice {
4585 target: target_price,
4586 tolerance: 0f64,
4587 min_amount_in: None,
4588 max_amount_in: None,
4589 },
4590 ))
4591 .expect("swap_to_price failed");
4592
4593 let expected_amount_in = BigUint::from_str("246739021727519745").unwrap();
4595 let expected_amount_out = BigUint::from_str("490291909043340795").unwrap();
4596
4597 assert_eq!(
4598 *pool_swap.amount_in(),
4599 expected_amount_in,
4600 "amount_in should match expected value"
4601 );
4602 assert_eq!(
4603 *pool_swap.amount_out(),
4604 expected_amount_out,
4605 "amount_out should match expected value"
4606 );
4607 }
4608
4609 #[test]
4610 fn test_swap_price_limit_out_of_range_returns_error() {
4611 let pool = create_basic_v4_test_pool();
4612 let amount = -I256::from_raw(U256::from(1000u64)); let result = pool.swap(true, amount, Some(pool.sqrt_price), None);
4616 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
4617
4618 let result = pool.swap(true, amount, Some(MIN_SQRT_RATIO), None);
4620 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
4621
4622 let result = pool.swap(false, amount, Some(pool.sqrt_price), None);
4624 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
4625
4626 let result = pool.swap(false, amount, Some(MAX_SQRT_RATIO), None);
4628 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
4629 }
4630
4631 #[test]
4632 fn test_swap_at_extreme_price_returns_error() {
4633 let sqrt_price = MIN_SQRT_RATIO + U256::from(1u64);
4636 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
4637 let aligned_tick = (MIN_TICK / 60) * 60 + 60; let ticks = vec![
4640 TickInfo::new(aligned_tick, 0).unwrap(),
4641 TickInfo::new(aligned_tick + 60, 0).unwrap(),
4642 ];
4643 let pool = UniswapV4State::new(
4644 100_000_000_000_000_000_000u128,
4645 sqrt_price,
4646 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 },
4647 tick,
4648 60,
4649 ticks,
4650 )
4651 .unwrap();
4652
4653 let amount = -I256::from_raw(U256::from(1000u64));
4654 let result = pool.swap(true, amount, None, None);
4656 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
4657 }
4658
4659 #[test]
4660 fn test_serde_roundtrip_via_protocol_sim_typetag() {
4661 let pool = create_basic_v4_test_pool();
4662
4663 let json =
4664 serde_json::to_string(&pool as &dyn ProtocolSim).expect("state should serialize");
4665 let deserialized: Box<dyn ProtocolSim> =
4666 serde_json::from_str(&json).expect("state should deserialize");
4667
4668 assert!(deserialized.eq(&pool));
4669 }
4670
4671 #[test]
4672 fn test_serialize_with_hook() {
4673 let mut pool = create_basic_v4_test_pool();
4674 let handler = AngstromHookHandler::new(
4675 Address::from_str("0x0000000aa232009084bd71a5797d089aa4edfad4").unwrap(),
4676 Address::from_str("0x000000000004444c5dc75cb358380d2e3de08a90").unwrap(),
4677 AngstromFees { unlock: U24::from(238), protocol_unlock: U24::from(112) },
4678 false,
4679 );
4680 pool.set_hook_handler(Box::new(handler));
4681
4682 let result = serde_json::to_string(&pool);
4683 assert!(result
4684 .unwrap_err()
4685 .to_string()
4686 .contains("HookHandler is a trait object"));
4687 }
4688
4689 #[test]
4690 fn test_deserialize_negative_tick_spacing() {
4691 let pool = UniswapV4State::new(
4692 1_000,
4693 U256::from(1u64) << 96,
4694 UniswapV4Fees::new(0, 0, 3000),
4695 0,
4696 60,
4697 vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(60, 0).unwrap()],
4698 )
4699 .expect("valid state");
4700 let mut json = serde_json::to_value(&pool).expect("hookless state should serialize");
4701 json["tick_spacing"] = (-60).into();
4702
4703 let err = serde_json::from_value::<UniswapV4State>(json).unwrap_err();
4704
4705 assert!(
4706 err.to_string()
4707 .contains("must be positive"),
4708 "unexpected error: {err}"
4709 );
4710 }
4711}
4712
4713#[cfg(test)]
4714mod step_cache_tests {
4715 use std::{
4716 collections::{HashMap, HashSet},
4717 str::FromStr,
4718 };
4719
4720 use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
4721
4722 use super::*;
4723 use crate::evm::protocol::utils::uniswap::swap_step_cache::test_fixtures::{
4724 amount_orders, test_amounts, test_ticks, wbtc_weth, LIQUIDITY, SQRT_PRICE, TICK,
4725 };
4726
4727 fn test_pool_with_fees(fees: UniswapV4Fees) -> UniswapV4State {
4728 UniswapV4State::new(
4729 LIQUIDITY,
4730 U256::from_str(SQRT_PRICE).unwrap(),
4731 fees,
4732 TICK,
4733 10,
4734 test_ticks(),
4735 )
4736 .unwrap()
4737 }
4738
4739 fn test_pool() -> UniswapV4State {
4740 test_pool_with_fees(UniswapV4Fees::new(0, 0, 500))
4741 }
4742
4743 fn format_quote_result(
4745 pool: &UniswapV4State,
4746 amount: &BigUint,
4747 sell: &Token,
4748 buy: &Token,
4749 ) -> String {
4750 match pool.get_amount_out(amount.clone(), sell, buy) {
4751 Ok(result) => {
4752 let state = result
4753 .new_state
4754 .as_any()
4755 .downcast_ref::<UniswapV4State>()
4756 .unwrap();
4757 format!(
4758 "{} {} {} {} {}",
4759 result.amount,
4760 result.gas,
4761 state.sqrt_price,
4762 state.tick.value(),
4763 state.liquidity
4764 )
4765 }
4766 Err(error) => format!("error {error}"),
4767 }
4768 }
4769
4770 #[test]
4771 fn test_step_cache_quotes_match_a_fresh_state_in_any_order() {
4772 let (wbtc, weth) = wbtc_weth();
4773 for fees in [UniswapV4Fees::new(0, 0, 500), UniswapV4Fees::new(100, 90, 3000)] {
4775 for (sell, buy, smallest) in [(&wbtc, &weth, 1_000u64), (&weth, &wbtc, 1_000_000_000)] {
4776 for order in amount_orders(&test_amounts(smallest)) {
4777 let shared = test_pool_with_fees(fees.clone());
4778 for amount in &order {
4779 assert_eq!(
4780 format_quote_result(&shared, amount, sell, buy),
4781 format_quote_result(
4782 &test_pool_with_fees(fees.clone()),
4783 amount,
4784 sell,
4785 buy
4786 ),
4787 "selling {amount} {} with {fees:?}",
4788 sell.symbol
4789 );
4790 }
4791 let steps = shared
4792 .step_cache
4793 .min_inputs(sell < buy)
4794 .len();
4795 assert!(steps > 2, "only {steps} steps cached");
4796 }
4797 }
4798 }
4799 }
4800
4801 #[test]
4802 fn test_step_cache_quotes_match_a_fresh_state_at_each_cached_step() {
4803 let (wbtc, weth) = wbtc_weth();
4804 for (sell, buy, doublings) in [(&wbtc, &weth, 30u32), (&weth, &wbtc, 70)] {
4807 let cached = test_pool();
4808 #[expect(
4809 clippy::let_underscore_must_use,
4810 reason = "the quote may run out of liquidity; only the step cache it fills is used"
4811 )]
4812 let _ = cached.get_amount_out(BigUint::from(10u32) << doublings, sell, buy);
4813 let boundaries = cached.step_cache.min_inputs(sell < buy);
4814 assert!(boundaries.len() > 2, "only {} steps cached", boundaries.len());
4815 for boundary in boundaries.into_iter().skip(1) {
4816 for amount in [boundary - U256::from(1u64), boundary, boundary + U256::from(1u64)] {
4817 let amount = u256_to_biguint(amount);
4818 assert_eq!(
4819 format_quote_result(&cached, &amount, sell, buy),
4820 format_quote_result(&test_pool(), &amount, sell, buy),
4821 "selling {amount} {}",
4822 sell.symbol
4823 );
4824 }
4825 }
4826 }
4827 }
4828
4829 #[test]
4830 fn test_step_cache_restarts_after_delta_transition() {
4831 let (wbtc, weth) = wbtc_weth();
4832 let large = BigUint::from(3_000_000_000u64);
4833 let delta = || ProtocolStateDelta {
4836 component_id: "State1".to_owned(),
4837 updated_attributes: HashMap::from([(
4838 "ticks/255820/net_liquidity".to_string(),
4839 Bytes::from(
4840 1_000_000_000_000_000i128
4841 .to_be_bytes()
4842 .to_vec(),
4843 ),
4844 )]),
4845 deleted_attributes: HashSet::new(),
4846 };
4847 let mut cached = test_pool();
4848 cached
4849 .get_amount_out(large.clone(), &wbtc, &weth)
4850 .unwrap();
4851 let mut fresh = test_pool();
4852
4853 cached
4854 .delta_transition(delta(), &HashMap::new(), &Balances::default())
4855 .unwrap();
4856 fresh
4857 .delta_transition(delta(), &HashMap::new(), &Balances::default())
4858 .unwrap();
4859
4860 assert_eq!(
4861 format_quote_result(&cached, &large, &wbtc, &weth),
4862 format_quote_result(&fresh, &large, &wbtc, &weth)
4863 );
4864 }
4865}