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::{u256_to_biguint, u256_to_f64},
29 uniswap_v4::hooks::{
30 hook_handler::HookHandler,
31 models::{
32 AfterSwapParameters, BalanceDelta, BeforeSwapDelta, BeforeSwapParameters,
33 StateContext, SwapParams,
34 },
35 },
36 utils::{
37 add_fee_markup,
38 uniswap::{
39 i24_be_bytes_to_i32, liquidity_math,
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,
53 },
54 },
55 vm::constants::EXTERNAL_ACCOUNT,
56 },
57 simulation::PendingOverrides,
58 },
59 utils::decimals_exponent,
60};
61
62const SWAP_BASE_GAS: u64 = 185_000;
65const GAS_PER_BITMAP_LOOKUP: u64 = 3_500;
68const GAS_PER_TICK: u64 = 29_000;
72const V4_CALLBACK_SETTLEMENT_GAS: u64 = 30_000;
74pub(crate) const PM_PER_HOOK_CALL_OVERHEAD: u64 = 25_000;
78const MAX_SWAP_GAS: u64 = 16_700_000;
80const MAX_TICKS_CROSSED: u64 = (MAX_SWAP_GAS - SWAP_BASE_GAS) / GAS_PER_TICK;
81const HOOK_FEE_PROBE_EXP: u64 = 30;
86
87#[derive(Clone, Deserialize)]
89#[serde(try_from = "UniswapV4StateData<'static>")]
90#[expect(
91 clippy::partial_pub_fields,
92 reason = "public API; making `hook` private or the rest public is a breaking change"
93)]
94pub struct UniswapV4State {
95 liquidity: u128,
96 sqrt_price: U256,
97 fees: UniswapV4Fees,
98 tick: PoolTick,
99 ticks: Arc<TickList>,
103 tick_spacing: i32,
104 pub hook: Option<Box<dyn HookHandler>>,
105 pending_overrides: Option<Arc<PendingOverrides>>,
108 step_cache: SwapStepCache,
113}
114
115#[derive(Serialize, Deserialize)]
116struct UniswapV4StateData<'a> {
117 liquidity: u128,
118 sqrt_price: U256,
119 fees: Cow<'a, UniswapV4Fees>,
120 tick: i32,
121 tick_spacing: i32,
122 ticks: Cow<'a, [TickInfo]>,
123}
124
125impl TryFrom<UniswapV4StateData<'_>> for UniswapV4State {
126 type Error = SimulationError;
127
128 fn try_from(data: UniswapV4StateData<'_>) -> Result<Self, Self::Error> {
129 UniswapV4State::new(
130 data.liquidity,
131 data.sqrt_price,
132 data.fees.into_owned(),
133 data.tick,
134 data.tick_spacing,
135 data.ticks.into_owned(),
136 )
137 }
138}
139
140impl Serialize for UniswapV4State {
141 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
142 if self.hook.is_some() {
143 return Err(serde::ser::Error::custom(
144 "UniswapV4State with a hook cannot be serialized: HookHandler is a trait object",
145 ));
146 }
147 UniswapV4StateData {
148 liquidity: self.liquidity,
149 sqrt_price: self.sqrt_price,
150 fees: Cow::Borrowed(&self.fees),
151 tick: self.tick.value(),
152 tick_spacing: self.tick_spacing,
153 ticks: Cow::Borrowed(self.ticks.ticks()),
154 }
155 .serialize(serializer)
156 }
157}
158
159impl fmt::Debug for UniswapV4State {
160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161 f.debug_struct("UniswapV4State")
162 .field("liquidity", &self.liquidity)
163 .field("sqrt_price", &self.sqrt_price)
164 .field("fees", &self.fees)
165 .field("tick", &self.tick)
166 .field("tick_spacing", &self.tick_spacing)
167 .field("pending_overrides", &self.pending_overrides.is_some())
168 .finish_non_exhaustive()
169 }
170}
171
172impl PartialEq for UniswapV4State {
173 fn eq(&self, other: &Self) -> bool {
174 match (&self.hook, &other.hook) {
175 (Some(a), Some(b)) => a.is_equal(&**b),
176 (None, None) => true,
177 _ => false,
178 }
179 }
180}
181
182impl Eq for UniswapV4State {}
183
184#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
185pub struct UniswapV4Fees {
186 pub zero_for_one: u32,
188 pub one_for_zero: u32,
190 pub lp_fee: u32,
192}
193
194impl UniswapV4Fees {
195 pub fn new(zero_for_one: u32, one_for_zero: u32, lp_fee: u32) -> Self {
196 Self { zero_for_one, one_for_zero, lp_fee }
197 }
198
199 fn calculate_swap_fees_pips(
200 &self,
201 zero_for_one: bool,
202 lp_fee_override: Option<u32>,
203 ) -> Result<u32, SimulationError> {
204 let protocol_fee = if zero_for_one { self.zero_for_one } else { self.one_for_zero };
205 let lp_fee = lp_fee_override.unwrap_or_else(|| {
206 if is_dynamic(self.lp_fee) {
208 0
209 } else {
210 self.lp_fee
211 }
212 });
213
214 let overlap = u64::from(protocol_fee) * u64::from(lp_fee) / 1_000_000;
219 u32::try_from(u64::from(protocol_fee) + u64::from(lp_fee) - overlap).map_err(|e| {
220 SimulationError::InvalidInput(
221 format!("swap fee for protocol fee {protocol_fee} and lp fee {lp_fee}: {e}"),
222 None,
223 )
224 })
225 }
226}
227
228impl UniswapV4State {
229 pub fn new(
231 liquidity: u128,
232 sqrt_price: U256,
233 fees: UniswapV4Fees,
234 tick: i32,
235 tick_spacing: i32,
236 ticks: Vec<TickInfo>,
237 ) -> Result<Self, SimulationError> {
238 let tick_spacing_u16 = tick_spacing
239 .try_into()
240 .map_err(|_out_of_range| {
241 SimulationError::FatalError(format!(
244 "tick_spacing {} must be positive (int24 -> u16 conversion failed)",
245 tick_spacing
246 ))
247 })?;
248 let tick_list = TickList::from(tick_spacing_u16, ticks)?;
249 Ok(UniswapV4State {
250 liquidity,
251 sqrt_price,
252 fees,
253 tick: tick.into(),
254 ticks: Arc::new(tick_list),
255 tick_spacing,
256 hook: None,
257 pending_overrides: None,
258 step_cache: SwapStepCache::default(),
259 })
260 }
261
262 pub fn pending_overrides(&self) -> Option<&PendingOverrides> {
263 self.pending_overrides.as_deref()
264 }
265
266 fn clone_post_swap(&self, sqrt_price: U256, tick: PoolTick, liquidity: u128) -> Self {
269 let mut state = self.clone();
270 state.sqrt_price = sqrt_price;
271 state.tick = tick;
272 state.liquidity = liquidity;
273 state.step_cache = SwapStepCache::default();
274 state
275 }
276
277 fn swap(
278 &self,
279 zero_for_one: bool,
280 amount_specified: I256,
281 sqrt_price_limit: Option<U256>,
282 lp_fee_override: Option<u32>,
283 ) -> Result<SwapResults, SimulationError> {
284 if amount_specified == I256::ZERO {
285 return Ok(SwapResults {
286 amount_calculated: I256::ZERO,
287 amount_specified: I256::ZERO,
288 amount_remaining: I256::ZERO,
289 sqrt_price: self.sqrt_price,
290 liquidity: self.liquidity,
291 tick: self.tick.clone(),
292 gas_used: U256::from(3_000), });
294 }
295
296 if self.liquidity == 0 {
297 return Err(SimulationError::RecoverableError("No liquidity".to_string()));
298 }
299 let price_limit = if let Some(limit) = sqrt_price_limit {
300 limit
301 } else if zero_for_one {
302 safe_add_u256(MIN_SQRT_RATIO, U256::from(1u64))?
303 } else {
304 safe_sub_u256(MAX_SQRT_RATIO, U256::from(1u64))?
305 };
306
307 let price_limit_valid = if zero_for_one {
308 price_limit > MIN_SQRT_RATIO && price_limit < self.sqrt_price
309 } else {
310 price_limit < MAX_SQRT_RATIO && price_limit > self.sqrt_price
311 };
312 if !price_limit_valid {
313 return Err(SimulationError::InvalidInput("Price limit out of range".into(), None));
314 }
315
316 let exact_input = amount_specified < I256::ZERO;
317
318 let mut state = SwapState {
319 amount_remaining: amount_specified,
320 amount_calculated: I256::ZERO,
321 sqrt_price: self.sqrt_price,
322 tick: self.tick.value().into(),
323 liquidity: self.liquidity,
324 };
325 let mut gas_used = U256::from(SWAP_BASE_GAS);
326
327 let cache_key = if exact_input && sqrt_price_limit.is_none() && lp_fee_override.is_none() {
333 let fee_pips = self
334 .fees
335 .calculate_swap_fees_pips(zero_for_one, None)?;
336 StepCacheKey::new(
337 self.sqrt_price,
338 state.tick.value(),
339 self.liquidity,
340 fee_pips,
341 gas_used,
342 )
343 } else {
344 None
345 };
346 let mut cache_run = StepCacheRun::new(
347 &self.step_cache,
348 zero_for_one,
349 cache_key,
350 amount_specified.unsigned_abs(),
351 );
352 if let Some(progress) = cache_run.apply_cached_progress(&mut state) {
353 gas_used = progress.gas;
354 }
355
356 while state.amount_remaining != I256::ZERO && state.sqrt_price != price_limit {
357 let (mut next_tick, next_tick_info) = match self
358 .ticks
359 .next_initialized_tick_within_one_word(state.tick.value(), zero_for_one)
360 {
361 Ok((tick, info)) => {
362 gas_used = safe_add_u256(gas_used, U256::from(GAS_PER_BITMAP_LOOKUP))?;
363 (tick, info)
364 }
365 Err(tick_err) => match tick_err.kind {
366 TickListErrorKind::TicksExeeded => {
367 let new_state = self.clone_post_swap(
368 state.sqrt_price,
369 state.tick.clone(),
370 state.liquidity,
371 );
372 return Err(SimulationError::InvalidInput(
373 "Ticks exceeded".into(),
374 Some(GetAmountOutResult::new(
375 u256_to_biguint(state.amount_calculated.abs().into_raw()),
376 u256_to_biguint(gas_used),
377 Box::new(new_state),
378 )),
379 ));
380 }
381 TickListErrorKind::BelowSmallest | TickListErrorKind::AtOrAboveLargest => {
382 return Err(SimulationError::FatalError("Unknown error".to_string()))
383 }
384 },
385 };
386
387 next_tick = next_tick.clamp(MIN_TICK, MAX_TICK);
388
389 let sqrt_price_next = match next_tick_info {
390 Some(info) => info.sqrt_price,
391 None => get_sqrt_ratio_at_tick_cached(next_tick)?,
392 };
393 let fee_pips = self
394 .fees
395 .calculate_swap_fees_pips(zero_for_one, lp_fee_override)?;
396
397 let sqrt_price_start = state.sqrt_price;
398 let SwapStepResult { sqrt_price, amount_in_with_fee, amount_out } =
399 swap_math::compute_swap_step(
400 state.sqrt_price,
401 UniswapV4State::get_sqrt_ratio_target(
402 sqrt_price_next,
403 price_limit,
404 zero_for_one,
405 ),
406 state.liquidity,
407 -state.amount_remaining,
411 fee_pips,
412 )?;
413 state.sqrt_price = sqrt_price;
414
415 let step = StepComputation {
416 sqrt_price_start,
417 tick_next: next_tick,
418 sqrt_price_next,
419 amount_in_with_fee,
420 amount_out,
421 };
422 if exact_input {
423 state.amount_remaining +=
424 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
425 .unwrap();
426 state.amount_calculated -=
427 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
428 } else {
429 state.amount_remaining -=
430 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
431 state.amount_calculated +=
432 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
433 .unwrap();
434 }
435 if state.sqrt_price == step.sqrt_price_next {
436 if let Some(info) = next_tick_info {
437 let liquidity_raw = info.net_liquidity;
438 let liquidity_net = if zero_for_one { -liquidity_raw } else { liquidity_raw };
439 state.liquidity =
440 liquidity_math::add_liquidity_delta(state.liquidity, liquidity_net)?;
441 gas_used = safe_add_u256(gas_used, U256::from(GAS_PER_TICK))?;
442 }
443 state.tick =
444 PoolTick::from(if zero_for_one { step.tick_next - 1 } else { step.tick_next });
445 } else if state.sqrt_price != step.sqrt_price_start {
446 state.tick = PoolTick::at_sqrt_price(state.sqrt_price)?;
447 }
448 cache_run.cache_progress(&step, &state, gas_used);
449 }
450
451 Ok(SwapResults {
452 amount_calculated: state.amount_calculated,
453 amount_specified,
454 amount_remaining: state.amount_remaining,
455 sqrt_price: state.sqrt_price,
456 liquidity: state.liquidity,
457 tick: state.tick,
458 gas_used: safe_add_u256(gas_used, U256::from(V4_CALLBACK_SETTLEMENT_GAS))?,
459 })
460 }
461
462 pub fn set_hook_handler(&mut self, handler: Box<dyn HookHandler>) {
463 self.hook = Some(handler);
464 }
465
466 fn get_sqrt_ratio_target(
467 sqrt_price_next: U256,
468 sqrt_price_limit: U256,
469 zero_for_one: bool,
470 ) -> U256 {
471 let cond1 = if zero_for_one {
472 sqrt_price_next < sqrt_price_limit
473 } else {
474 sqrt_price_next > sqrt_price_limit
475 };
476
477 if cond1 {
478 sqrt_price_limit
479 } else {
480 sqrt_price_next
481 }
482 }
483
484 fn find_limits_experimentally(
485 &self,
486 token_in: &Bytes,
487 token_out: &Bytes,
488 ) -> (BigUint, BigUint) {
489 let token_in_obj =
492 Token::new(token_in, "TOKEN_IN", 18, 0, &[Some(10_000)], Default::default(), 100);
493 let token_out_obj =
494 Token::new(token_out, "TOKEN_OUT", 18, 0, &[Some(10_000)], Default::default(), 100);
495
496 self.find_max_amount(&token_in_obj, &token_out_obj)
497 }
498
499 fn find_max_amount(&self, token_in: &Token, token_out: &Token) -> (BigUint, BigUint) {
512 let mut low = BigUint::from(1u64);
513
514 let mut high = BigUint::from(10u64).pow(18); let mut last_successful_amount_in = BigUint::from(1u64);
518 let mut last_successful_amount_out = BigUint::from(0u64);
519
520 while let Ok(result) = self.get_amount_out(high.clone(), token_in, token_out) {
523 low = last_successful_amount_in.clone();
526 last_successful_amount_in = high.clone();
527 last_successful_amount_out = result.amount;
528 high *= BigUint::from(10u64);
529
530 if high > BigUint::from(10u64).pow(75) {
532 return (last_successful_amount_in, last_successful_amount_out);
533 }
534 }
535
536 while &high - &low > BigUint::from(1u64) {
538 let mid = (&low + &high) / BigUint::from(2u64);
539
540 match self.get_amount_out(mid.clone(), token_in, token_out) {
541 Ok(result) => {
542 last_successful_amount_in = mid.clone();
543 last_successful_amount_out = result.amount;
544 low = mid;
545 }
546 Err(_) => {
547 high = mid;
548 }
549 }
550 }
551
552 (last_successful_amount_in, last_successful_amount_out)
553 }
554
555 fn has_no_initialized_ticks(&self) -> bool {
557 !self.ticks.has_initialized_ticks()
558 }
559
560 fn core_spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
563 let base_is_currency0 = base < quote;
564 let fee_pips = self
565 .fees
566 .calculate_swap_fees_pips(base_is_currency0, None)?;
567 let fee = fee_pips as f64 / 1_000_000.0;
568
569 let price = if base_is_currency0 {
570 sqrt_price_q96_to_f64(self.sqrt_price, base.decimals, quote.decimals)?
571 } else {
572 1.0f64 / sqrt_price_q96_to_f64(self.sqrt_price, quote.decimals, base.decimals)?
573 };
574
575 Ok(add_fee_markup(price, fee))
576 }
577
578 fn hook_fee_rate(&self, zero_for_one: bool) -> Result<Option<f64>, SimulationError> {
585 let Some(hook) = &self.hook else { return Ok(None) };
586
587 let probe = U256::from(10u64).pow(U256::from(HOOK_FEE_PROBE_EXP));
588 let Some(fee) = hook.unspecified_fee_amount(probe, zero_for_one)? else {
589 return Ok(None);
590 };
591
592 let rate = u256_to_f64(fee)? / u256_to_f64(probe)?;
593 if rate >= 1.0 {
594 return Err(SimulationError::FatalError(format!(
595 "Hook {} keeps {rate} of the output, leaving no price to quote",
596 hook.address()
597 )));
598 }
599
600 Ok(Some(rate))
601 }
602}
603
604#[typetag::serde]
605impl ProtocolSim for UniswapV4State {
606 fn set_pending_overrides(
609 &mut self,
610 overrides: Arc<dyn Any + Send + Sync>,
611 ) -> Result<(), SimulationError> {
612 #[expect(
613 clippy::map_err_ignore,
614 reason = "the downcast error is the original `Arc<dyn Any>`, which has no message"
615 )]
616 let overrides = overrides
617 .downcast::<PendingOverrides>()
618 .map_err(|_| {
619 SimulationError::FatalError(
620 "Uniswap V4 pending overrides must be `PendingOverrides`".to_string(),
621 )
622 })?;
623 if let Some(hook) = &mut self.hook {
624 hook.set_pending_overrides(Arc::clone(&overrides));
625 }
626 self.pending_overrides = Some(overrides);
627 Ok(())
628 }
629
630 #[expect(
633 clippy::todo,
634 reason = "fee() returns no error and the trait documents the panic for asymmetric fees"
635 )]
636 fn fee(&self) -> f64 {
637 todo!()
638 }
639
640 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
641 if let Some(hook) = &self.hook {
642 if let Some(rate) = self.hook_fee_rate(quote < base)? {
647 return Ok(add_fee_markup(self.core_spot_price(base, quote)?, rate));
648 }
649
650 match hook.spot_price(base, quote) {
651 Ok(price) => return Ok(price),
652 Err(SimulationError::RecoverableError(_)) => {
653 let x1 = BigUint::from(10u64).pow(base.decimals) / BigUint::from(100u64); let x2 = &x1 + (&x1 / BigUint::from(100u64));
661
662 let y1 = self.get_amount_out(x1.clone(), base, quote)?;
664 let y2 = self.get_amount_out(x2.clone(), base, quote)?;
665
666 let num = y2
668 .amount
669 .checked_sub(&y1.amount)
670 .ok_or_else(|| {
671 SimulationError::FatalError(
672 "Cannot calculate spot price: y2 < y1".to_string(),
673 )
674 })?;
675 let den = x2.checked_sub(&x1).ok_or_else(|| {
676 SimulationError::FatalError(
677 "Cannot calculate spot price: x2 < x1".to_string(),
678 )
679 })?;
680
681 if den == BigUint::from(0u64) {
682 return Err(SimulationError::FatalError(
683 "Cannot calculate spot price: denominator is zero".to_string(),
684 ));
685 }
686
687 let num_f64 = num.to_f64().ok_or_else(|| {
689 SimulationError::FatalError(
690 "Failed to convert numerator to f64".to_string(),
691 )
692 })?;
693 let den_f64 = den.to_f64().ok_or_else(|| {
694 SimulationError::FatalError(
695 "Failed to convert denominator to f64".to_string(),
696 )
697 })?;
698
699 let token_correction =
700 10f64.powi(decimals_exponent(base.decimals, quote.decimals)?);
701
702 return Ok(num_f64 / den_f64 * token_correction);
703 }
704 Err(e) => return Err(e),
705 }
706 }
707
708 self.core_spot_price(base, quote)
709 }
710
711 fn get_amount_out(
712 &self,
713 amount_in: BigUint,
714 token_in: &Token,
715 token_out: &Token,
716 ) -> Result<GetAmountOutResult, SimulationError> {
717 let zero_for_one = token_in < token_out;
718 let amount_specified = I256::checked_from_sign_and_abs(
719 Sign::Negative,
720 U256::from_be_slice(&amount_in.to_bytes_be()),
721 )
722 .ok_or_else(|| {
723 SimulationError::InvalidInput("I256 overflow: amount_in".to_string(), None)
724 })?;
725
726 let mut amount_to_swap = amount_specified;
727 let mut lp_fee_override: Option<u32> = None;
728 let mut before_swap_gas = 0u64;
729 let mut after_swap_gas = 0u64;
730 let mut before_swap_delta = BeforeSwapDelta(I256::ZERO);
731 let mut storage_overwrites = None;
732
733 let token_in_address = Address::from_slice(&token_in.address);
734 let token_out_address = Address::from_slice(&token_out.address);
735
736 let state_context = StateContext {
737 currency_0: if zero_for_one { token_in_address } else { token_out_address },
738 currency_1: if zero_for_one { token_out_address } else { token_in_address },
739 fees: self.fees.clone(),
740 tick_spacing: self.tick_spacing,
741 };
742
743 let swap_params = SwapParams {
744 zero_for_one,
745 amount_specified: amount_to_swap,
746 sqrt_price_limit: self.sqrt_price,
747 };
748
749 if let Some(ref hook) = self.hook {
751 if hook.has_permission(HookOptions::BeforeSwap) {
752 let before_swap_params = BeforeSwapParameters {
753 context: state_context.clone(),
754 sender: *EXTERNAL_ACCOUNT,
755 swap_params: swap_params.clone(),
756 hook_data: Bytes::new(),
757 };
758
759 let before_swap_result = hook
762 .before_swap(before_swap_params, None, None)
763 .map_err(|e| match e {
764 SimulationError::InvalidInput(..) => e,
765 e @ (SimulationError::FatalError(_) |
766 SimulationError::RecoverableError(_)) => SimulationError::FatalError(
767 format!("BeforeSwap hook simulation failed: {e:?}"),
768 ),
769 })?;
770
771 before_swap_gas = before_swap_result.gas_estimate;
772 before_swap_delta = before_swap_result.result.amount_delta;
773 storage_overwrites = Some(before_swap_result.result.overwrites);
774
775 if before_swap_delta.as_i256() != I256::ZERO {
778 amount_to_swap += I256::from(before_swap_delta.get_specified_delta());
779 if amount_to_swap > I256::ZERO {
780 return Err(SimulationError::FatalError(
781 "Hook delta exceeds swap amount".into(),
782 ));
783 }
784 }
785
786 let hook_fee = before_swap_result
791 .result
792 .fee
793 .to::<u32>();
794 if hook_fee != 0 {
795 let cleaned_fee = lp_fee::remove_override_flag(hook_fee);
797
798 if !lp_fee::is_valid(cleaned_fee) {
800 return Err(SimulationError::FatalError(format!(
801 "LP fee override {} exceeds maximum {} pips",
802 cleaned_fee,
803 lp_fee::MAX_LP_FEE
804 )));
805 }
806
807 lp_fee_override = Some(cleaned_fee);
808 }
809 }
810 }
811
812 let result = self.swap(zero_for_one, amount_to_swap, None, lp_fee_override)?;
814
815 let mut swap_delta = BalanceDelta::from_swap_result(result.amount_calculated, zero_for_one);
817
818 let hook_delta_specified = before_swap_delta.get_specified_delta();
821 let mut hook_delta_unspecified = before_swap_delta.get_unspecified_delta();
822
823 if let Some(ref hook) = self.hook {
824 if hook.has_permission(HookOptions::AfterSwap) {
825 let after_swap_params = AfterSwapParameters {
826 context: state_context,
827 sender: *EXTERNAL_ACCOUNT,
828 swap_params,
829 delta: swap_delta,
830 hook_data: Bytes::new(),
831 };
832
833 let after_swap_result = hook
834 .after_swap(after_swap_params, storage_overwrites, None)
835 .map_err(|e| {
836 SimulationError::FatalError(format!(
837 "AfterSwap hook simulation failed: {e:?}"
838 ))
839 })?;
840 after_swap_gas = after_swap_result.gas_estimate;
841 if hook.has_permission(HookOptions::AfterSwapReturnsDelta) {
846 hook_delta_unspecified += after_swap_result.result;
847 }
848 }
849 }
850
851 if (hook_delta_specified != I128::ZERO) || (hook_delta_unspecified != I128::ZERO) {
854 let hook_delta = if (amount_specified < I256::ZERO) == zero_for_one {
855 BalanceDelta::new(hook_delta_specified, hook_delta_unspecified)
856 } else {
857 BalanceDelta::new(hook_delta_unspecified, hook_delta_specified)
858 };
859 swap_delta = swap_delta - hook_delta
861 }
862
863 let amount_out = if (amount_specified < I256::ZERO) == zero_for_one {
864 swap_delta.amount1()
865 } else {
866 swap_delta.amount0()
867 };
868
869 trace!(?amount_in, ?token_in, ?token_out, ?zero_for_one, ?result, "V4 SWAP");
870 let new_state = self.clone_post_swap(result.sqrt_price, result.tick, result.liquidity);
871
872 let mut hook_overhead = before_swap_gas + after_swap_gas;
878 if let Some(hook) = &self.hook {
879 let hook_calls = u64::from(before_swap_gas > 0) + u64::from(after_swap_gas > 0);
880 hook_overhead += hook_calls * hook.pool_manager_call_overhead();
881 }
882 let total_gas_used = result.gas_used + U256::from(hook_overhead);
883 Ok(GetAmountOutResult::new(
884 u256_to_biguint(U256::from(amount_out.abs())),
885 u256_to_biguint(total_gas_used),
886 Box::new(new_state),
887 ))
888 }
889
890 fn get_limits(
891 &self,
892 sell_token: Bytes,
893 buy_token: Bytes,
894 ) -> Result<(BigUint, BigUint), SimulationError> {
895 if let Some(hook) = &self.hook {
896 if !hook.swaps_enabled() {
897 return Ok((BigUint::zero(), BigUint::zero()));
898 }
899 if self.liquidity == 0 && self.has_no_initialized_ticks() {
901 match hook.get_amount_ranges(sell_token.clone(), buy_token.clone()) {
903 Ok(amount_ranges) => {
904 return Ok((
905 u256_to_biguint(amount_ranges.amount_in_range.1),
906 u256_to_biguint(amount_ranges.amount_out_range.1),
907 ))
908 }
909 Err(SimulationError::RecoverableError(msg))
912 if msg.contains("not implemented") || msg.contains("not set") =>
913 {
914 return Ok(self.find_limits_experimentally(&sell_token, &buy_token));
917 }
919 Err(e) => return Err(e),
920 }
921 }
922 }
923
924 if self.liquidity == 0 {
926 return Ok((BigUint::zero(), BigUint::zero()));
927 }
928
929 let zero_for_one = sell_token < buy_token;
930 let mut current_tick = self.tick.value();
931 let mut current_sqrt_price = self.sqrt_price;
932 let mut current_liquidity = self.liquidity;
933 let mut total_amount_in = U256::ZERO;
934 let mut total_amount_out = U256::ZERO;
935 let mut ticks_crossed: u64 = 0;
936
937 while let Ok((tick, next_tick_info)) = self
940 .ticks
941 .next_initialized_tick_within_one_word(current_tick, zero_for_one)
942 {
943 if ticks_crossed >= MAX_TICKS_CROSSED {
945 break;
946 }
947 ticks_crossed += 1;
948
949 let next_tick = tick.clamp(MIN_TICK, MAX_TICK);
951
952 let sqrt_price_next = match next_tick_info {
953 Some(info) => info.sqrt_price,
954 None => get_sqrt_ratio_at_tick_cached(next_tick)?,
955 };
956
957 let (amount_in, amount_out) = if zero_for_one {
960 let amount0 = get_amount0_delta(
961 sqrt_price_next,
962 current_sqrt_price,
963 current_liquidity,
964 true,
965 )?;
966 let amount1 = get_amount1_delta(
967 sqrt_price_next,
968 current_sqrt_price,
969 current_liquidity,
970 false,
971 )?;
972 (amount0, amount1)
973 } else {
974 let amount0 = get_amount0_delta(
975 sqrt_price_next,
976 current_sqrt_price,
977 current_liquidity,
978 false,
979 )?;
980 let amount1 = get_amount1_delta(
981 sqrt_price_next,
982 current_sqrt_price,
983 current_liquidity,
984 true,
985 )?;
986 (amount1, amount0)
987 };
988
989 total_amount_in = safe_add_u256(total_amount_in, amount_in)?;
991 total_amount_out = safe_add_u256(total_amount_out, amount_out)?;
992
993 if let Some(info) = next_tick_info {
998 let liquidity_raw = info.net_liquidity;
999 let liquidity_delta = if zero_for_one { -liquidity_raw } else { liquidity_raw };
1000
1001 match liquidity_math::add_liquidity_delta(current_liquidity, liquidity_delta) {
1004 Ok(new_liquidity) => {
1005 current_liquidity = new_liquidity;
1006 }
1007 Err(_) => {
1008 break;
1011 }
1012 }
1013 }
1014
1015 current_tick = if zero_for_one { next_tick - 1 } else { next_tick };
1017 current_sqrt_price = sqrt_price_next;
1018
1019 if current_liquidity == 0 {
1021 break;
1022 }
1023 }
1024
1025 if let Some(hook) = &self.hook {
1028 if let Some(fee) = hook.unspecified_fee_amount(total_amount_out, zero_for_one)? {
1029 total_amount_out = safe_sub_u256(total_amount_out, fee)?;
1030 }
1031 }
1032
1033 Ok((u256_to_biguint(total_amount_in), u256_to_biguint(total_amount_out)))
1034 }
1035
1036 fn delta_transition(
1037 &mut self,
1038 delta: ProtocolStateDelta,
1039 tokens: &HashMap<Bytes, Token>,
1040 balances: &Balances,
1041 ) -> Result<(), TransitionError> {
1042 self.step_cache = SwapStepCache::default();
1044 if let Some(mut hook) = self.hook.clone() {
1045 match hook.delta_transition(delta.clone(), tokens, balances) {
1046 Ok(()) => self.set_hook_handler(hook),
1047 Err(TransitionError::SimulationError(SimulationError::RecoverableError(msg)))
1048 if msg.contains("not implemented") =>
1049 {
1050 }
1052 Err(e) => return Err(e),
1053 }
1054 }
1055
1056 if let Some(liquidity) = delta
1058 .updated_attributes
1059 .get("liquidity")
1060 {
1061 self.liquidity = u128::try_from(liquidity.clone())?;
1062 }
1063 if let Some(sqrt_price) = delta
1064 .updated_attributes
1065 .get("sqrt_price_x96")
1066 {
1067 self.sqrt_price = U256::from_be_slice(sqrt_price);
1068 }
1069 if let Some(tick) = delta.updated_attributes.get("tick") {
1070 self.tick = i24_be_bytes_to_i32(tick).into();
1071 }
1072 if let Some(lp_fee) = delta.updated_attributes.get("fee") {
1073 self.fees.lp_fee = u32::try_from(lp_fee.clone())?;
1074 }
1075 if let Some(zero2one_protocol_fee) = delta
1076 .updated_attributes
1077 .get("protocol_fees/zero2one")
1078 {
1079 self.fees.zero_for_one = u32::try_from(zero2one_protocol_fee.clone())?;
1080 }
1081 if let Some(one2zero_protocol_fee) = delta
1082 .updated_attributes
1083 .get("protocol_fees/one2zero")
1084 {
1085 self.fees.one_for_zero = u32::try_from(one2zero_protocol_fee.clone())?;
1086 }
1087
1088 for (key, value) in delta.updated_attributes.iter() {
1090 if key.starts_with("ticks/") {
1092 let parts: Vec<&str> = key.split('/').collect();
1093 Arc::make_mut(&mut self.ticks)
1094 .set_tick_liquidity(
1095 parts[1]
1096 .parse::<i32>()
1097 .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
1098 i128::try_from(value.clone())?,
1099 )
1100 .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
1101 }
1102 }
1103 for key in delta.deleted_attributes.iter() {
1105 if key.starts_with("ticks/") {
1107 let parts: Vec<&str> = key.split('/').collect();
1108 Arc::make_mut(&mut self.ticks)
1109 .set_tick_liquidity(
1110 parts[1]
1111 .parse::<i32>()
1112 .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
1113 0,
1114 )
1115 .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
1116 }
1117 }
1118
1119 Ok(())
1120 }
1121
1122 fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
1132 if let Some(hook) = &self.hook {
1133 if !hook.swaps_enabled() {
1134 return Err(SimulationError::InvalidInput(
1135 format!("hook {} does not allow swaps in the execution block", hook.address()),
1136 None,
1137 ));
1138 }
1139 }
1140 if self.liquidity == 0 {
1141 return Err(SimulationError::FatalError("No liquidity".to_string()));
1142 }
1143
1144 let zero_for_one = params.token_in().address < params.token_out().address;
1146 let fee_pips = self
1147 .fees
1148 .calculate_swap_fees_pips(zero_for_one, None)?;
1149
1150 match params.swap_constraint() {
1151 SwapConstraint::TradeLimitPrice { .. } => Err(SimulationError::InvalidInput(
1152 "Uniswap V4 does not support TradeLimitPrice constraint in query_pool_swap"
1153 .to_string(),
1154 None,
1155 )),
1156 SwapConstraint::PoolTargetPrice {
1157 target,
1158 tolerance: _,
1159 min_amount_in: _,
1160 max_amount_in: _,
1161 } => {
1162 if self.liquidity == 0 {
1163 return Err(SimulationError::FatalError("No liquidity".to_string()));
1164 }
1165
1166 let (amount_in, amount_out, swap_result) = clmm_swap_to_price(
1167 self.sqrt_price,
1168 ¶ms.token_in().address,
1169 ¶ms.token_out().address,
1170 target,
1171 fee_pips,
1172 Sign::Negative, |zero_for_one, amount_specified, sqrt_price_limit| {
1174 self.swap(zero_for_one, amount_specified, Some(sqrt_price_limit), None)
1175 },
1176 )?;
1177
1178 let new_state = self.clone_post_swap(
1179 swap_result.sqrt_price,
1180 swap_result.tick,
1181 swap_result.liquidity,
1182 );
1183
1184 Ok(PoolSwap::new(amount_in, amount_out, Box::new(new_state), None))
1185 }
1186 }
1187 }
1188
1189 fn apply_block(&mut self, block: &BlockContext) -> bool {
1192 self.hook
1193 .as_mut()
1194 .is_some_and(|hook| hook.apply_block(block))
1195 }
1196
1197 fn clone_box(&self) -> Box<dyn ProtocolSim> {
1198 Box::new(self.clone())
1199 }
1200
1201 fn as_any(&self) -> &dyn Any {
1202 self
1203 }
1204
1205 fn as_any_mut(&mut self) -> &mut dyn Any {
1206 self
1207 }
1208
1209 fn eq(&self, other: &dyn ProtocolSim) -> bool {
1210 if let Some(other_state) = other
1211 .as_any()
1212 .downcast_ref::<UniswapV4State>()
1213 {
1214 self.liquidity == other_state.liquidity &&
1215 self.sqrt_price == other_state.sqrt_price &&
1216 self.fees == other_state.fees &&
1217 self.tick == other_state.tick &&
1218 self.ticks == other_state.ticks
1219 } else {
1220 false
1221 }
1222 }
1223}
1224
1225#[cfg(test)]
1226mod tests {
1227 use std::{collections::HashSet, fs, path::Path, str::FromStr};
1228
1229 use alloy::primitives::{aliases::U24, U160};
1230 use num_traits::FromPrimitive;
1231 use rstest::rstest;
1232 use serde_json::Value;
1233 use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
1234 use tycho_common::{models::Chain, simulation::protocol_sim::Price};
1235
1236 use super::*;
1237 use crate::{
1238 evm::{
1239 engine_db::{
1240 create_engine,
1241 simulation_db::SimulationDB,
1242 utils::{get_client, get_runtime},
1243 },
1244 protocol::{
1245 u256_num::biguint_to_u256,
1246 uniswap_v4::hooks::{
1247 angstrom::hook_handler::{AngstromFees, AngstromHookHandler},
1248 generic_vm_hook_handler::GenericVMHookHandler,
1249 models::{AfterSwapDelta, AmountRanges, BeforeSwapOutput, WithGasEstimate},
1250 pons_v2::hook_handler::{PonsV2HookHandler, PONS_V2_HOOK_ROBINHOOD},
1251 },
1252 utils::uniswap::{
1253 lp_fee,
1254 sqrt_price_math::get_sqrt_price_q96,
1255 tick_math::{get_sqrt_ratio_at_tick, get_tick_at_sqrt_ratio},
1256 },
1257 },
1258 },
1259 protocol::models::{DecoderContext, TryFromWithBlock},
1260 };
1261
1262 fn usdc() -> Token {
1264 Token::new(
1265 &Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap(),
1266 "USDC",
1267 6,
1268 0,
1269 &[Some(10_000)],
1270 Default::default(),
1271 100,
1272 )
1273 }
1274
1275 fn weth() -> Token {
1276 Token::new(
1277 &Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(),
1278 "WETH",
1279 18,
1280 0,
1281 &[Some(10_000)],
1282 Default::default(),
1283 100,
1284 )
1285 }
1286
1287 fn eth() -> Token {
1288 Token::new(
1289 &Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(),
1290 "ETH",
1291 18,
1292 0,
1293 &[Some(10_000)],
1294 Default::default(),
1295 100,
1296 )
1297 }
1298
1299 fn token_x() -> Token {
1300 Token::new(
1301 &Bytes::from_str("0x0000000000000000000000000000000000000001").unwrap(),
1302 "X",
1303 18,
1304 0,
1305 &[Some(10_000)],
1306 Default::default(),
1307 100,
1308 )
1309 }
1310
1311 fn token_y() -> Token {
1312 Token::new(
1313 &Bytes::from_str("0x0000000000000000000000000000000000000002").unwrap(),
1314 "Y",
1315 18,
1316 0,
1317 &[Some(10_000)],
1318 Default::default(),
1319 100,
1320 )
1321 }
1322
1323 #[test]
1324 fn delta_with_oversized_liquidity_is_rejected_without_panicking() {
1325 let mut pool = UniswapV4State::new(
1326 1000,
1327 U256::from_str("1000").unwrap(),
1328 UniswapV4Fees { zero_for_one: 100, one_for_zero: 90, lp_fee: 700 },
1329 100,
1330 60,
1331 vec![TickInfo::new(120, 10000).unwrap(), TickInfo::new(180, -10000).unwrap()],
1332 )
1333 .unwrap();
1334 let address_sized = Bytes::from(vec![0x11_u8; 20]);
1335 let delta = ProtocolStateDelta {
1336 component_id: "State1".to_owned(),
1337 updated_attributes: HashMap::from([("liquidity".to_string(), address_sized.clone())]),
1338 deleted_attributes: HashSet::new(),
1339 };
1340
1341 let result = pool.delta_transition(delta, &HashMap::new(), &Balances::default());
1342
1343 let Err(TransitionError::DecodeError(message)) = result else {
1344 panic!("a 20-byte liquidity attribute must not apply");
1345 };
1346 assert!(message.contains(&address_sized.to_string()), "{message}");
1347 assert_eq!(pool.liquidity, 1000);
1348 }
1349
1350 #[test]
1351 fn test_delta_transition() {
1352 let mut pool = UniswapV4State::new(
1353 1000,
1354 U256::from_str("1000").unwrap(),
1355 UniswapV4Fees { zero_for_one: 100, one_for_zero: 90, lp_fee: 700 },
1356 100,
1357 60,
1358 vec![TickInfo::new(120, 10000).unwrap(), TickInfo::new(180, -10000).unwrap()],
1359 )
1360 .unwrap();
1361
1362 let attributes: HashMap<String, Bytes> = [
1363 ("liquidity".to_string(), Bytes::from(2000_u64.to_be_bytes().to_vec())),
1364 ("sqrt_price_x96".to_string(), Bytes::from(1001_u64.to_be_bytes().to_vec())),
1365 ("tick".to_string(), Bytes::from(120_i32.to_be_bytes().to_vec())),
1366 ("protocol_fees/zero2one".to_string(), Bytes::from(50_u32.to_be_bytes().to_vec())),
1367 ("protocol_fees/one2zero".to_string(), Bytes::from(75_u32.to_be_bytes().to_vec())),
1368 ("fee".to_string(), Bytes::from(100_u32.to_be_bytes().to_vec())),
1369 ("ticks/-120/net_liquidity".to_string(), Bytes::from(10200_u64.to_be_bytes().to_vec())),
1370 ("ticks/120/net_liquidity".to_string(), Bytes::from(9800_u64.to_be_bytes().to_vec())),
1371 ("block_number".to_string(), Bytes::from(2000_u64.to_be_bytes().to_vec())),
1372 ("block_timestamp".to_string(), Bytes::from(1758201935_u64.to_be_bytes().to_vec())),
1373 ]
1374 .into_iter()
1375 .collect();
1376
1377 let delta = ProtocolStateDelta {
1378 component_id: "State1".to_owned(),
1379 updated_attributes: attributes,
1380 deleted_attributes: HashSet::new(),
1381 };
1382
1383 pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1384 .unwrap();
1385
1386 assert_eq!(pool.liquidity, 2000);
1387 assert_eq!(pool.sqrt_price, U256::from(1001));
1388 assert_eq!(pool.tick.value(), 120);
1389 assert_eq!(pool.fees.zero_for_one, 50);
1390 assert_eq!(pool.fees.one_for_zero, 75);
1391 assert_eq!(pool.fees.lp_fee, 100);
1392 assert_eq!(
1393 pool.ticks
1394 .get_tick(-120)
1395 .unwrap()
1396 .net_liquidity,
1397 10200
1398 );
1399 assert_eq!(
1400 pool.ticks
1401 .get_tick(120)
1402 .unwrap()
1403 .net_liquidity,
1404 9800
1405 );
1406 }
1407
1408 #[tokio::test]
1409 async fn test_swap_sim() {
1411 use tycho_client::feed::dto;
1412 let project_root = env!("CARGO_MANIFEST_DIR");
1413 let asset_path = Path::new(project_root)
1414 .join("tests/assets/decoder/uniswap_v4_snapshot_sepolia_block_7239119.json");
1415 let json_data = fs::read_to_string(asset_path).expect("Failed to read test asset");
1416 let data: Value = serde_json::from_str(&json_data).expect("Failed to parse JSON");
1417 let state: ComponentWithState = serde_json::from_value::<dto::ComponentWithState>(data)
1418 .expect("Expected json to match ComponentWithState structure")
1419 .into();
1420
1421 let block = BlockHeader {
1422 number: 7239119,
1423 hash: Bytes::from_str(
1424 "0x28d41d40f2ac275a4f5f621a636b9016b527d11d37d610a45ac3a821346ebf8c",
1425 )
1426 .expect("Invalid block hash"),
1427 parent_hash: Bytes::from(vec![0; 32]),
1428 ..Default::default()
1429 };
1430
1431 let t0 = Token::new(
1432 &Bytes::from_str("0x647e32181a64f4ffd4f0b0b4b052ec05b277729c").unwrap(),
1433 "T0",
1434 18,
1435 0,
1436 &[Some(10_000)],
1437 Chain::Ethereum,
1438 100,
1439 );
1440 let t1 = Token::new(
1441 &Bytes::from_str("0xe390a1c311b26f14ed0d55d3b0261c2320d15ca5").unwrap(),
1442 "T1",
1443 18,
1444 0,
1445 &[Some(10_000)],
1446 Chain::Ethereum,
1447 100,
1448 );
1449
1450 let all_tokens = [t0.clone(), t1.clone()]
1451 .iter()
1452 .map(|t| (t.address.clone(), t.clone()))
1453 .collect();
1454
1455 let usv4_state = UniswapV4State::try_from_with_header(
1456 state,
1457 block,
1458 &Default::default(),
1459 &all_tokens,
1460 &DecoderContext::new(),
1461 )
1462 .await
1463 .unwrap();
1464
1465 assert!(usv4_state.hook.is_none());
1468
1469 let res = usv4_state
1470 .get_amount_out(BigUint::from_u64(1000000000000000000).unwrap(), &t0, &t1)
1471 .unwrap();
1472
1473 let expected_amount = BigUint::from(9999909699895_u64);
1474 assert_eq!(res.amount, expected_amount);
1475 }
1476
1477 #[tokio::test]
1478 async fn test_get_limits() {
1479 use tycho_client::feed::dto;
1480 let block = BlockHeader {
1481 number: 22689129,
1482 hash: Bytes::from_str(
1483 "0x7763ea30d11aef68da729b65250c09a88ad00458c041064aad8c9a9dbf17adde",
1484 )
1485 .expect("Invalid block hash"),
1486 parent_hash: Bytes::from(vec![0; 32]),
1487 ..Default::default()
1488 };
1489
1490 let project_root = env!("CARGO_MANIFEST_DIR");
1491 let asset_path =
1492 Path::new(project_root).join("tests/assets/decoder/uniswap_v4_snapshot.json");
1493 let json_data = fs::read_to_string(asset_path).expect("Failed to read test asset");
1494 let data: Value = serde_json::from_str(&json_data).expect("Failed to parse JSON");
1495 let state: ComponentWithState = serde_json::from_value::<dto::ComponentWithState>(data)
1496 .expect("Expected json to match ComponentWithState structure")
1497 .into();
1498
1499 let t0 = Token::new(
1500 &Bytes::from_str("0x2260fac5e5542a773aa44fbcfedf7c193bc2c599").unwrap(),
1501 "WBTC",
1502 8,
1503 0,
1504 &[Some(10_000)],
1505 Chain::Ethereum,
1506 100,
1507 );
1508 let t1 = Token::new(
1509 &Bytes::from_str("0xdac17f958d2ee523a2206206994597c13d831ec7").unwrap(),
1510 "USDT",
1511 6,
1512 0,
1513 &[Some(10_000)],
1514 Chain::Ethereum,
1515 100,
1516 );
1517
1518 let all_tokens = [t0.clone(), t1.clone()]
1519 .iter()
1520 .map(|t| (t.address.clone(), t.clone()))
1521 .collect();
1522
1523 let usv4_state = UniswapV4State::try_from_with_header(
1524 state,
1525 block,
1526 &Default::default(),
1527 &all_tokens,
1528 &DecoderContext::new(),
1529 )
1530 .await
1531 .unwrap();
1532
1533 assert!(usv4_state.hook.is_none());
1536
1537 let res = usv4_state
1538 .get_limits(t0.address.clone(), t1.address.clone())
1539 .unwrap();
1540
1541 assert_eq!(&res.0, &BigUint::from_u128(71698353688830259750744466706).unwrap());
1542
1543 let out = usv4_state
1544 .get_amount_out(res.0, &t0, &t1)
1545 .expect("swap for limit in didn't work");
1546
1547 assert_eq!(&res.1, &out.amount);
1548 }
1549 type SeenCalls = Vec<(&'static str, Option<PendingOverrides>)>;
1551
1552 #[derive(Debug, Clone)]
1555 struct ConfigurableFeeHook {
1556 address: Address,
1557 pending_overrides: Option<Arc<PendingOverrides>>,
1558 seen: Arc<std::sync::Mutex<SeenCalls>>,
1559 }
1560
1561 impl ConfigurableFeeHook {
1562 fn new() -> Self {
1564 let mut address = [0u8; 20];
1565 address[19] = 0xC0;
1566 Self {
1567 address: Address::from_slice(&address),
1568 pending_overrides: None,
1569 seen: Arc::default(),
1570 }
1571 }
1572
1573 fn pending_fee(&self) -> U256 {
1574 self.pending_overrides
1575 .as_ref()
1576 .and_then(|p| p.storage.as_ref())
1577 .and_then(|storage| storage.get(&self.address))
1578 .and_then(|slots| slots.get(&U256::ZERO))
1579 .copied()
1580 .unwrap_or(U256::ZERO)
1581 }
1582 }
1583
1584 impl HookHandler for ConfigurableFeeHook {
1585 fn address(&self) -> Address {
1586 self.address
1587 }
1588
1589 #[expect(
1590 clippy::unwrap_in_result,
1591 reason = "test mock; a poisoned lock means a test already failed"
1592 )]
1593 fn before_swap(
1594 &self,
1595 _params: BeforeSwapParameters,
1596 _overwrites: Option<HashMap<Address, HashMap<U256, U256>>>,
1597 _transient_storage: Option<HashMap<Address, HashMap<U256, U256>>>,
1598 ) -> Result<WithGasEstimate<BeforeSwapOutput>, SimulationError> {
1599 self.seen.lock().unwrap().push((
1600 "before",
1601 self.pending_overrides
1602 .as_deref()
1603 .cloned(),
1604 ));
1605 Ok(WithGasEstimate {
1606 gas_estimate: 0,
1607 result: BeforeSwapOutput {
1608 amount_delta: BeforeSwapDelta(I256::ZERO),
1609 fee: U24::from(self.pending_fee()),
1610 overwrites: HashMap::new(),
1611 transient_storage: HashMap::new(),
1612 },
1613 })
1614 }
1615
1616 #[expect(
1617 clippy::unwrap_in_result,
1618 reason = "test mock; a poisoned lock means a test already failed"
1619 )]
1620 fn after_swap(
1621 &self,
1622 _params: AfterSwapParameters,
1623 _overwrites: Option<HashMap<Address, HashMap<U256, U256>>>,
1624 _transient_storage_params: Option<HashMap<Address, HashMap<U256, U256>>>,
1625 ) -> Result<WithGasEstimate<AfterSwapDelta>, SimulationError> {
1626 self.seen.lock().unwrap().push((
1627 "after",
1628 self.pending_overrides
1629 .as_deref()
1630 .cloned(),
1631 ));
1632 Ok(WithGasEstimate { gas_estimate: 0, result: I128::ZERO })
1633 }
1634
1635 fn fee(
1636 &self,
1637 _context: &UniswapV4State,
1638 _params: SwapParams,
1639 ) -> Result<f64, SimulationError> {
1640 Ok(0.0)
1641 }
1642
1643 fn spot_price(&self, _base: &Token, _quote: &Token) -> Result<f64, SimulationError> {
1644 Err(SimulationError::RecoverableError("not implemented".into()))
1645 }
1646
1647 fn get_amount_ranges(
1648 &self,
1649 _token_in: Bytes,
1650 _token_out: Bytes,
1651 ) -> Result<AmountRanges, SimulationError> {
1652 Err(SimulationError::RecoverableError("not implemented".into()))
1653 }
1654
1655 fn set_pending_overrides(&mut self, overrides: Arc<PendingOverrides>) {
1656 self.pending_overrides = Some(overrides);
1657 }
1658
1659 fn delta_transition(
1660 &mut self,
1661 _delta: ProtocolStateDelta,
1662 _tokens: &HashMap<Bytes, Token>,
1663 _balances: &Balances,
1664 ) -> Result<(), TransitionError> {
1665 Ok(())
1666 }
1667
1668 fn clone_box(&self) -> Box<dyn HookHandler> {
1669 Box::new(self.clone())
1670 }
1671
1672 fn as_any(&self) -> &dyn Any {
1673 self
1674 }
1675
1676 fn is_equal(&self, other: &dyn HookHandler) -> bool {
1677 other
1678 .as_any()
1679 .downcast_ref::<Self>()
1680 .is_some_and(|o| o.address == self.address)
1681 }
1682 }
1683
1684 fn hooked_pool(hook: &ConfigurableFeeHook) -> UniswapV4State {
1686 let liquidity = 1_000_000_000_000_000_000u128;
1687 let mut pool = UniswapV4State::new(
1688 liquidity,
1689 U256::from(1u8) << 96,
1690 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: lp_fee::DYNAMIC_FEE_FLAG },
1691 0,
1692 60,
1693 vec![
1694 TickInfo::new(-60, i128::try_from(liquidity).unwrap()).unwrap(),
1695 TickInfo::new(60, -(i128::try_from(liquidity).unwrap())).unwrap(),
1696 ],
1697 )
1698 .unwrap();
1699 pool.set_hook_handler(Box::new(hook.clone()));
1700 pool
1701 }
1702
1703 fn pending_fee_update(hook: &ConfigurableFeeHook, fee_pips: u64) -> PendingOverrides {
1704 PendingOverrides {
1705 storage: Some(HashMap::from([(
1706 hook.address,
1707 HashMap::from([(U256::ZERO, U256::from(fee_pips))]),
1708 )])),
1709 native_balances: None,
1710 block: None,
1711 }
1712 }
1713
1714 #[test]
1715 fn test_pending_overrides_reach_both_hook_calls_and_change_the_quote() {
1716 let hook = ConfigurableFeeHook::new();
1717 let amount_in = BigUint::from(1_000_000u64);
1718
1719 let confirmed = hooked_pool(&hook)
1720 .get_amount_out(amount_in.clone(), &token_x(), &token_y())
1721 .unwrap();
1722 let mut pool = hooked_pool(&hook);
1723 pool.set_pending_overrides(Arc::new(pending_fee_update(&hook, 100_000)))
1724 .unwrap();
1725 let pending = pool
1726 .get_amount_out(amount_in, &token_x(), &token_y())
1727 .unwrap();
1728
1729 assert!(
1730 pending.amount < confirmed.amount,
1731 "a 10% fee the pending block wrote must cut the output: {} vs {}",
1732 pending.amount,
1733 confirmed.amount
1734 );
1735 let seen = hook.seen.lock().unwrap();
1736 let calls: Vec<(&str, bool)> = seen
1737 .iter()
1738 .map(|(call, pending)| {
1739 (
1740 *call,
1741 pending
1742 .as_ref()
1743 .is_some_and(|p| p.storage.is_some()),
1744 )
1745 })
1746 .collect();
1747 assert_eq!(
1748 calls,
1749 vec![("before", false), ("after", false), ("before", true), ("after", true)],
1750 "the confirmed quote runs both calls without overrides, the pending one with them"
1751 );
1752 }
1753
1754 #[test]
1755 fn test_pending_overrides_survive_clone_box() {
1756 let hook = ConfigurableFeeHook::new();
1757 let mut pool = hooked_pool(&hook);
1758 pool.set_pending_overrides(Arc::new(pending_fee_update(&hook, 1)))
1759 .unwrap();
1760
1761 let cloned = pool.clone_box();
1762 let cloned = cloned
1763 .as_any()
1764 .downcast_ref::<UniswapV4State>()
1765 .unwrap();
1766
1767 assert!(cloned.pending_overrides().is_some(), "a clone quotes under the same overrides");
1768 }
1769
1770 #[test]
1771 fn test_set_pending_overrides_rejects_another_payload_type() {
1772 let hook = ConfigurableFeeHook::new();
1773 let mut pool = hooked_pool(&hook);
1774
1775 let result = pool.set_pending_overrides(Arc::new(0u8));
1776
1777 assert!(matches!(result, Err(SimulationError::FatalError(_))));
1778 assert!(pool.pending_overrides().is_none(), "a rejected payload sets nothing");
1779 assert!(hook.seen.lock().unwrap().is_empty());
1780 }
1781
1782 #[test]
1783 fn test_pending_overrides_are_not_part_of_equality() {
1784 let hook = ConfigurableFeeHook::new();
1785 let confirmed = hooked_pool(&hook);
1786 let mut pending = hooked_pool(&hook);
1787 pending
1788 .set_pending_overrides(Arc::new(pending_fee_update(&hook, 1)))
1789 .unwrap();
1790
1791 assert!(confirmed == pending, "PartialEq ignores the overrides");
1792 assert!(ProtocolSim::eq(&confirmed, &pending), "ProtocolSim::eq ignores the overrides");
1793 }
1794
1795 #[test]
1796 fn test_get_amount_out_no_hook() {
1797 let usv4_state = UniswapV4State::new(
1802 541501951282951892,
1803 U256::from_str("5362798333066270795901222").unwrap(), UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 100 },
1805 -192022,
1806 1,
1807 vec![
1809 TickInfo {
1810 index: -887272,
1811 net_liquidity: 460382969070005,
1812 sqrt_price: U256::from(4295128739_u64),
1813 },
1814 TickInfo {
1815 index: -207244,
1816 net_liquidity: 561268407024557,
1817 sqrt_price: U256::from_str("2505291706254206075074035").unwrap(),
1818 },
1819 TickInfo {
1820 index: -196411,
1821 net_liquidity: 825711941800452,
1822 sqrt_price: U256::from_str("4306080513146952705853399").unwrap(),
1823 },
1824 TickInfo {
1825 index: -196257,
1826 net_liquidity: 64844666874010,
1827 sqrt_price: U256::from_str("4339363644587371378270009").unwrap(),
1828 },
1829 TickInfo {
1830 index: -195611,
1831 net_liquidity: 2344045150766798,
1832 sqrt_price: U256::from_str("4481806029599743916020126").unwrap(),
1833 },
1834 TickInfo {
1835 index: -194715,
1836 net_liquidity: 391037380558274654,
1837 sqrt_price: U256::from_str("4687145946111116896040494").unwrap(),
1838 },
1839 TickInfo {
1840 index: -194599,
1841 net_liquidity: 89032603464508,
1842 sqrt_price: U256::from_str("4714409015946702405379370").unwrap(),
1843 },
1844 TickInfo {
1845 index: -194389,
1846 net_liquidity: 66635600426483168,
1847 sqrt_price: U256::from_str("4764168603367683402636621").unwrap(),
1848 },
1849 TickInfo {
1850 index: -194160,
1851 net_liquidity: 6123093436523361,
1852 sqrt_price: U256::from_str("4819029067726467394386780").unwrap(),
1853 },
1854 TickInfo {
1855 index: -194025,
1856 net_liquidity: 79940813798964,
1857 sqrt_price: U256::from_str("4851665907541490407930032").unwrap(),
1858 },
1859 TickInfo {
1860 index: -193922,
1861 net_liquidity: 415630967437234,
1862 sqrt_price: U256::from_str("4876715181040466809166531").unwrap(),
1863 },
1864 TickInfo {
1865 index: -193876,
1866 net_liquidity: 9664144015186047,
1867 sqrt_price: U256::from_str("4887943972687250473582419").unwrap(),
1868 },
1869 TickInfo {
1870 index: -193818,
1871 net_liquidity: 435344726052344,
1872 sqrt_price: U256::from_str("4902138873132735049121973").unwrap(),
1873 },
1874 TickInfo {
1875 index: -193804,
1876 net_liquidity: 221726179374067,
1877 sqrt_price: U256::from_str("4905571399964683340605904").unwrap(),
1878 },
1879 TickInfo {
1880 index: -193719,
1881 net_liquidity: 101340835774487,
1882 sqrt_price: U256::from_str("4926463397882393957462188").unwrap(),
1883 },
1884 TickInfo {
1885 index: -193690,
1886 net_liquidity: 193367475630077,
1887 sqrt_price: U256::from_str("4933611593595025190448924").unwrap(),
1888 },
1889 TickInfo {
1890 index: -193643,
1891 net_liquidity: 357016631583746,
1892 sqrt_price: U256::from_str("4945218633428068823432932").unwrap(),
1893 },
1894 TickInfo {
1895 index: -193520,
1896 net_liquidity: 917243184365178,
1897 sqrt_price: U256::from_str("4975723910367862081017120").unwrap(),
1898 },
1899 TickInfo {
1900 index: -193440,
1901 net_liquidity: 114125890211958292,
1902 sqrt_price: U256::from_str("4995665665861492533686137").unwrap(),
1903 },
1904 TickInfo {
1905 index: -193380,
1906 net_liquidity: -65980729148766579,
1907 sqrt_price: U256::from_str("5010674414300823856025303").unwrap(),
1908 },
1909 TickInfo {
1910 index: -192891,
1911 net_liquidity: 1687883551433195,
1912 sqrt_price: U256::from_str("5134689105039642314202223").unwrap(),
1913 },
1914 TickInfo {
1915 index: -192573,
1916 net_liquidity: 11108903221360975,
1917 sqrt_price: U256::from_str("5216979018647067786855495").unwrap(),
1918 },
1919 TickInfo {
1920 index: -192448,
1921 net_liquidity: 32888457482352,
1922 sqrt_price: U256::from_str("5249685603828944002327927").unwrap(),
1923 },
1924 TickInfo {
1925 index: -191525,
1926 net_liquidity: -221726179374067,
1927 sqrt_price: U256::from_str("5497623359964843320146512").unwrap(),
1928 },
1929 TickInfo {
1930 index: -191447,
1931 net_liquidity: -32888457482352,
1932 sqrt_price: U256::from_str("5519104878745833608097296").unwrap(),
1933 },
1934 TickInfo {
1935 index: -191444,
1936 net_liquidity: -114125890211958292,
1937 sqrt_price: U256::from_str("5519932765173943847315221").unwrap(),
1938 },
1939 TickInfo {
1940 index: -191417,
1941 net_liquidity: -101340835774487,
1942 sqrt_price: U256::from_str("5527389333636021285046380").unwrap(),
1943 },
1944 TickInfo {
1945 index: -191384,
1946 net_liquidity: -9664144015186047,
1947 sqrt_price: U256::from_str("5536516597603056457376182").unwrap(),
1948 },
1949 TickInfo {
1950 index: -191148,
1951 net_liquidity: -561268407024557,
1952 sqrt_price: U256::from_str("5602231161238705865493165").unwrap(),
1953 },
1954 TickInfo {
1955 index: -191147,
1956 net_liquidity: -1687883551433195,
1957 sqrt_price: U256::from_str("5602511265794328966803451").unwrap(),
1958 },
1959 TickInfo {
1960 index: -191091,
1961 net_liquidity: -89032603464508,
1962 sqrt_price: U256::from_str("5618219493196441347292357").unwrap(),
1963 },
1964 TickInfo {
1965 index: -190950,
1966 net_liquidity: -189177935487638,
1967 sqrt_price: U256::from_str("5657965894785859782969011").unwrap(),
1968 },
1969 TickInfo {
1970 index: -190756,
1971 net_liquidity: -6123093436523361,
1972 sqrt_price: U256::from_str("5713112435031881967192022").unwrap(),
1973 },
1974 TickInfo {
1975 index: -190548,
1976 net_liquidity: -193367475630077,
1977 sqrt_price: U256::from_str("5772835841671084402427710").unwrap(),
1978 },
1979 TickInfo {
1980 index: -190430,
1981 net_liquidity: -11108903221360975,
1982 sqrt_price: U256::from_str("5806994534290341208820930").unwrap(),
1983 },
1984 TickInfo {
1985 index: -190195,
1986 net_liquidity: -391583014714302569,
1987 sqrt_price: U256::from_str("5875625707132601785181387").unwrap(),
1988 },
1989 TickInfo {
1990 index: -190043,
1991 net_liquidity: -357016631583746,
1992 sqrt_price: U256::from_str("5920448331650864936739481").unwrap(),
1993 },
1994 TickInfo {
1995 index: -189779,
1996 net_liquidity: -917243184365178,
1997 sqrt_price: U256::from_str("5999112356918485175181346").unwrap(),
1998 },
1999 TickInfo {
2000 index: -189663,
2001 net_liquidity: -2344045150766798,
2002 sqrt_price: U256::from_str("6034006559279282606084981").unwrap(),
2003 },
2004 TickInfo {
2005 index: -189620,
2006 net_liquidity: -435344726052344,
2007 sqrt_price: U256::from_str("6046992979471024289177519").unwrap(),
2008 },
2009 TickInfo {
2010 index: -189409,
2011 net_liquidity: -825711941800452,
2012 sqrt_price: U256::from_str("6111123241285165242130911").unwrap(),
2013 },
2014 TickInfo {
2015 index: -189325,
2016 net_liquidity: -3947182209207,
2017 sqrt_price: U256::from_str("6136842645893819031257990").unwrap(),
2018 },
2019 TickInfo {
2020 index: -189324,
2021 net_liquidity: -415630967437234,
2022 sqrt_price: U256::from_str("6137149480355443943537284").unwrap(),
2023 },
2024 TickInfo {
2025 index: -115136,
2026 net_liquidity: 462452451821,
2027 sqrt_price: U256::from_str("250529060232794967902094762").unwrap(),
2028 },
2029 TickInfo {
2030 index: -92109,
2031 net_liquidity: -462452451821,
2032 sqrt_price: U256::from_str("792242363124136400178523925").unwrap(),
2033 },
2034 TickInfo {
2035 index: 887272,
2036 net_liquidity: -521280453734808,
2037 sqrt_price: U256::from_str("1461446703485210103287273052203988822378723970342")
2038 .unwrap(),
2039 },
2040 ],
2041 )
2042 .unwrap();
2043
2044 let t0 = usdc();
2045 let t1 = eth();
2046
2047 let out = usv4_state
2048 .get_amount_out(BigUint::from_u64(2000000).unwrap(), &t0, &t1)
2049 .unwrap();
2050
2051 assert_eq!(out.amount, BigUint::from_str("436478419853848").unwrap())
2052 }
2053
2054 #[test]
2055 fn test_get_amount_out_euler_hook() {
2056 let block = BlockHeader {
2072 number: 22689128,
2073 hash: Bytes::from_str(
2074 "0xfbfa716523d25d6d5248c18d001ca02b1caf10cabd1ab7321465e2262c41157b",
2075 )
2076 .expect("Invalid block hash"),
2077 timestamp: 1749739055,
2078 ..Default::default()
2079 };
2080
2081 let mut usv4_state = UniswapV4State::new(
2084 0,
2085 U256::from_str("4295128740").unwrap(),
2086 UniswapV4Fees { zero_for_one: 100, one_for_zero: 90, lp_fee: 500 },
2087 0,
2088 1,
2089 vec![],
2090 )
2091 .unwrap();
2092
2093 let hook_address: Address = Address::from_str("0x69058613588536167ba0aa94f0cc1fe420ef28a8")
2094 .expect("Invalid hook address");
2095
2096 let db = SimulationDB::new(
2097 get_client(None).expect("Failed to create client"),
2098 get_runtime().expect("Failed to get runtime"),
2099 Some(block),
2100 );
2101 let engine = create_engine(db, true).expect("Failed to create simulation engine");
2102 let pool_manager = Address::from_str("0x000000000004444c5dc75cb358380d2e3de08a90")
2103 .expect("Invalid pool manager address");
2104
2105 let hook_handler = GenericVMHookHandler::new(
2106 hook_address,
2107 engine,
2108 pool_manager,
2109 HashMap::new(),
2110 HashMap::new(),
2111 None,
2112 true, )
2114 .unwrap();
2115
2116 let t0 = usdc();
2117 let t1 = weth();
2118
2119 usv4_state.set_hook_handler(Box::new(hook_handler));
2120 let out = usv4_state
2121 .get_amount_out(BigUint::from_u64(7407000000).unwrap(), &t0, &t1)
2122 .unwrap();
2123
2124 assert_eq!(out.amount, BigUint::from_str("2681115183499232721").unwrap())
2125 }
2126
2127 #[test]
2128 fn test_get_amount_out_angstrom_hook() {
2129 let mut usv4_state = UniswapV4State::new(
2131 66319800403673162,
2133 U256::from_str("1314588940601923011323000261788004").unwrap(),
2134 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 8388608 },
2136 194343,
2137 10,
2138 vec![
2139 TickInfo::new(-887270, 198117767801).unwrap(),
2140 TickInfo::new(191990, 24561988698695).unwrap(),
2141 TickInfo::new(192280, 2839631428751224).unwrap(),
2142 TickInfo::new(193130, 318786492813931).unwrap(),
2143 TickInfo::new(194010, 26209207141081).unwrap(),
2144 TickInfo::new(194210, -26209207141081).unwrap(),
2145 TickInfo::new(194220, 63136622375641511).unwrap(),
2146 TickInfo::new(194420, -63136622375641511).unwrap(),
2147 TickInfo::new(195130, -318786492813931).unwrap(),
2148 TickInfo::new(196330, -2839631428751224).unwrap(),
2149 TickInfo::new(197100, -24561988698695).unwrap(),
2150 TickInfo::new(887270, -198117767801).unwrap(),
2151 ],
2152 )
2153 .unwrap();
2154
2155 let fees = AngstromFees {
2156 unlock: U24::from(338),
2163 protocol_unlock: U24::from(112),
2164 };
2165 let hook_handler = AngstromHookHandler::new(
2166 Address::from_str("0x0000000aa232009084bd71a5797d089aa4edfad4").unwrap(),
2167 Address::from_str("0x000000000004444c5dc75cb358380d2e3de08a90").unwrap(),
2168 fees,
2169 false,
2170 );
2171
2172 let t0 = usdc();
2173 let t1 = weth();
2174
2175 usv4_state.set_hook_handler(Box::new(hook_handler));
2176 let out = usv4_state
2177 .get_amount_out(
2178 BigUint::from_u64(
2179 6645198144, )
2181 .unwrap(),
2182 &t0, &t1, )
2185 .unwrap();
2186
2187 assert_eq!(out.amount, BigUint::from_str("1825627051870330472").unwrap())
2188 }
2189
2190 #[derive(Debug, Clone, PartialEq, Eq)]
2192 struct AfterSwapTestHook {
2193 address: Address,
2194 delta: I128,
2195 analytic_fee_bps: Option<u32>,
2198 spot_price_override: Option<u64>,
2201 }
2202
2203 impl HookHandler for AfterSwapTestHook {
2204 fn address(&self) -> Address {
2205 self.address
2206 }
2207
2208 fn before_swap(
2209 &self,
2210 _: BeforeSwapParameters,
2211 _: Option<HashMap<Address, HashMap<U256, U256>>>,
2212 _: Option<HashMap<Address, HashMap<U256, U256>>>,
2213 ) -> Result<WithGasEstimate<BeforeSwapOutput>, SimulationError> {
2214 Err(SimulationError::RecoverableError("not implemented".into()))
2215 }
2216
2217 fn after_swap(
2218 &self,
2219 _: AfterSwapParameters,
2220 _: Option<HashMap<Address, HashMap<U256, U256>>>,
2221 _: Option<HashMap<Address, HashMap<U256, U256>>>,
2222 ) -> Result<WithGasEstimate<AfterSwapDelta>, SimulationError> {
2223 Ok(WithGasEstimate { gas_estimate: AFTER_SWAP_TEST_HOOK_GAS, result: self.delta })
2224 }
2225
2226 fn fee(&self, _: &UniswapV4State, _: SwapParams) -> Result<f64, SimulationError> {
2227 Err(SimulationError::RecoverableError("not implemented".into()))
2228 }
2229
2230 fn spot_price(&self, _: &Token, _: &Token) -> Result<f64, SimulationError> {
2231 match self.spot_price_override {
2232 Some(price) => Ok(price as f64),
2233 None => Err(SimulationError::RecoverableError("not implemented".into())),
2234 }
2235 }
2236
2237 fn unspecified_fee_amount(
2238 &self,
2239 unspecified: U256,
2240 _: bool,
2241 ) -> Result<Option<U256>, SimulationError> {
2242 let Some(bps) = self.analytic_fee_bps else { return Ok(None) };
2243 Ok(Some(unspecified * U256::from(bps) / U256::from(10_000u64)))
2244 }
2245
2246 fn get_amount_ranges(&self, _: Bytes, _: Bytes) -> Result<AmountRanges, SimulationError> {
2247 Err(SimulationError::RecoverableError("not implemented".into()))
2248 }
2249
2250 fn delta_transition(
2251 &mut self,
2252 _: ProtocolStateDelta,
2253 _: &HashMap<Bytes, Token>,
2254 _: &Balances,
2255 ) -> Result<(), TransitionError> {
2256 Ok(())
2257 }
2258
2259 fn clone_box(&self) -> Box<dyn HookHandler> {
2260 Box::new(self.clone())
2261 }
2262
2263 fn as_any(&self) -> &dyn Any {
2264 self
2265 }
2266
2267 fn is_equal(&self, other: &dyn HookHandler) -> bool {
2268 other.as_any().downcast_ref::<Self>() == Some(self)
2269 }
2270 }
2271
2272 const AFTER_SWAP_TEST_HOOK_GAS: u64 = 1_000;
2275 const AFTER_SWAP_TEST_HOOK_DELTA: u64 = 777;
2276
2277 fn construct_hook_address(hook_options: &[HookOptions]) -> Address {
2278 let mut hook_flags = U160::ZERO;
2279 let one = U160::from_limbs([1, 0, 0]);
2280 for hook_option in hook_options {
2281 hook_flags |= one << (*hook_option as u8);
2282 }
2283 Address::from(hook_flags)
2284 }
2285
2286 fn after_swap_test_hook(hook_options: &[HookOptions]) -> Box<dyn HookHandler> {
2287 Box::new(AfterSwapTestHook {
2288 address: construct_hook_address(hook_options),
2289 delta: I128::unchecked_from(AFTER_SWAP_TEST_HOOK_DELTA),
2290 analytic_fee_bps: None,
2291 spot_price_override: None,
2292 })
2293 }
2294
2295 fn analytic_fee_test_hook(analytic_fee_bps: u32) -> Box<dyn HookHandler> {
2297 Box::new(AfterSwapTestHook {
2298 address: construct_hook_address(&[
2299 HookOptions::AfterSwap,
2300 HookOptions::AfterSwapReturnsDelta,
2301 ]),
2302 delta: I128::ZERO,
2303 analytic_fee_bps: Some(analytic_fee_bps),
2304 spot_price_override: None,
2305 })
2306 }
2307
2308 const TEST_HOOK_SPOT_PRICE: u64 = 1_000_000;
2311
2312 fn pricing_test_hook(analytic_fee_bps: Option<u32>) -> Box<dyn HookHandler> {
2315 Box::new(AfterSwapTestHook {
2316 address: construct_hook_address(&[
2317 HookOptions::AfterSwap,
2318 HookOptions::AfterSwapReturnsDelta,
2319 ]),
2320 delta: I128::ZERO,
2321 analytic_fee_bps,
2322 spot_price_override: Some(TEST_HOOK_SPOT_PRICE),
2323 })
2324 }
2325
2326 fn basic_v4_test_pool_tokens(zero_for_one: bool) -> (Token, Token) {
2327 if zero_for_one {
2328 (token_x(), token_y())
2329 } else {
2330 (token_y(), token_x())
2331 }
2332 }
2333
2334 #[rstest]
2337 #[case::zero_for_one(true)]
2338 #[case::one_for_zero(false)]
2339 fn test_after_swap_delta_ignored_without_returns_delta_permission(#[case] zero_for_one: bool) {
2340 let (token_in, token_out) = basic_v4_test_pool_tokens(zero_for_one);
2341 let amount_in = BigUint::from(1_000_000_000_000_000u64);
2342
2343 let hookless = create_basic_v4_test_pool()
2344 .get_amount_out(amount_in.clone(), &token_in, &token_out)
2345 .expect("hookless swap should succeed");
2346
2347 let mut pool = create_basic_v4_test_pool();
2348 pool.set_hook_handler(after_swap_test_hook(&[HookOptions::AfterSwap]));
2349 let gated = pool
2350 .get_amount_out(amount_in, &token_in, &token_out)
2351 .expect("gated swap should succeed");
2352
2353 assert_eq!(gated.amount, hookless.amount);
2354 assert_eq!(
2355 gated.gas,
2356 hookless.gas + BigUint::from(AFTER_SWAP_TEST_HOOK_GAS + PM_PER_HOOK_CALL_OVERHEAD)
2357 );
2358 }
2359
2360 #[rstest]
2363 #[case::zero_for_one(true)]
2364 #[case::one_for_zero(false)]
2365 fn test_after_swap_delta_applied_with_returns_delta_permission(#[case] zero_for_one: bool) {
2366 let (token_in, token_out) = basic_v4_test_pool_tokens(zero_for_one);
2367 let amount_in = BigUint::from(1_000_000_000_000_000u64);
2368
2369 let hookless = create_basic_v4_test_pool()
2370 .get_amount_out(amount_in.clone(), &token_in, &token_out)
2371 .expect("hookless swap should succeed");
2372
2373 let mut pool = create_basic_v4_test_pool();
2374 pool.set_hook_handler(after_swap_test_hook(&[
2375 HookOptions::AfterSwap,
2376 HookOptions::AfterSwapReturnsDelta,
2377 ]));
2378 let with_delta = pool
2379 .get_amount_out(amount_in, &token_in, &token_out)
2380 .expect("swap with hook delta should succeed");
2381
2382 assert_eq!(with_delta.amount, &hookless.amount - BigUint::from(AFTER_SWAP_TEST_HOOK_DELTA));
2383 assert_eq!(
2384 with_delta.gas,
2385 hookless.gas + BigUint::from(AFTER_SWAP_TEST_HOOK_GAS + PM_PER_HOOK_CALL_OVERHEAD)
2386 );
2387 }
2388
2389 const FEELESS_POOL_LIQUIDITY: u128 = 100_000_000_000_000_000_000; fn create_feeless_v4_test_pool(liquidity: u128) -> UniswapV4State {
2395 let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
2396 .expect("a price of two has a square root");
2397 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("the sqrt price maps to a tick");
2398 let position = i128::try_from(FEELESS_POOL_LIQUIDITY).unwrap();
2399
2400 UniswapV4State::new(
2401 liquidity,
2402 sqrt_price,
2403 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 0 },
2404 tick,
2405 60,
2406 vec![
2407 TickInfo::new(-46_080, position).unwrap(),
2408 TickInfo::new(46_080, -position).unwrap(),
2409 ],
2410 )
2411 .expect("the pool builds")
2412 }
2413
2414 fn pons_test_handler() -> PonsV2HookHandler {
2415 PonsV2HookHandler::new(PONS_V2_HOOK_ROBINHOOD, 100, 100)
2416 }
2417
2418 #[test]
2423 fn hookless_spot_price_is_the_documented_buy_price_with_lp_fee_markup() {
2424 const LP_FEE_PIPS: u32 = 3_000;
2425 const LP_FEE: f64 = LP_FEE_PIPS as f64 / 1_000_000.0;
2426 const LIQUIDITY: u128 = 100_000_000_000_000_000_000; const TOLERANCE: f64 = 1e-12;
2428
2429 let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
2430 .expect("a price of two has a square root");
2431 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("the sqrt price maps to a tick");
2432 let pool = UniswapV4State::new(
2433 LIQUIDITY,
2434 sqrt_price,
2435 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: LP_FEE_PIPS },
2436 tick,
2437 60,
2438 vec![
2439 TickInfo::new(-46_080, i128::try_from(LIQUIDITY).unwrap()).unwrap(),
2440 TickInfo::new(46_080, -(i128::try_from(LIQUIDITY).unwrap())).unwrap(),
2441 ],
2442 )
2443 .expect("the pool builds");
2444
2445 assert!(pool.hook.is_none(), "the pinned values only hold with no hook handler");
2446
2447 let (t0, t1) = (token_x(), token_y());
2448 let pre_fee = sqrt_price_q96_to_f64(sqrt_price, t0.decimals, t1.decimals)
2449 .expect("the sqrt price converts to a price");
2450
2451 let expected_buy_t0 = pre_fee / (1.0 - LP_FEE);
2452 let expected_buy_t1 = (1.0 / pre_fee) / (1.0 - LP_FEE);
2453
2454 let buy_t0 = pool
2455 .spot_price(&t0, &t1)
2456 .expect("a hookless pool always prices");
2457 let buy_t1 = pool
2458 .spot_price(&t1, &t0)
2459 .expect("a hookless pool always prices");
2460
2461 assert!(
2462 (buy_t0 / expected_buy_t0 - 1.0).abs() < TOLERANCE,
2463 "buying t0 quoted {buy_t0}, expected {expected_buy_t0}"
2464 );
2465 assert!(
2466 (buy_t1 / expected_buy_t1 - 1.0).abs() < TOLERANCE,
2467 "buying t1 quoted {buy_t1}, expected {expected_buy_t1}"
2468 );
2469 }
2470
2471 #[rstest]
2475 #[case::base_is_currency0(true)]
2476 #[case::base_is_currency1(false)]
2477 fn test_spot_price_marks_up_an_analytic_hook_fee(#[case] base_is_currency0: bool) {
2478 let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
2479 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2480 hooked.set_hook_handler(Box::new(pons_test_handler()));
2481
2482 let core = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
2483 .spot_price(&base, "e)
2484 .expect("a hookless pool always prices");
2485 let price = hooked
2486 .spot_price(&base, "e)
2487 .expect("the hook prices its own fee");
2488
2489 assert!(price > core, "hooked {price} is not above hookless {core}");
2490 let ratio = price / core;
2491 assert!((ratio * 0.98 - 1.0).abs() < 1e-9, "hooked/hookless is {ratio}, not 1/0.98");
2492 }
2493
2494 #[rstest]
2497 #[case::base_is_currency0(true)]
2498 #[case::base_is_currency1(false)]
2499 fn test_hooked_spot_price_matches_a_small_hooked_buy(#[case] base_is_currency0: bool) {
2500 let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
2501 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2502 hooked.set_hook_handler(Box::new(pons_test_handler()));
2503
2504 let quote_in = BigUint::from(100_000_000_000_000u64);
2505 let base_out = hooked
2506 .get_amount_out(quote_in.clone(), "e, &base)
2507 .expect("a tiny buy always fits the pool")
2508 .amount;
2509
2510 let executed = quote_in.to_f64().unwrap() / base_out.to_f64().unwrap();
2511 let spot = hooked
2512 .spot_price(&base, "e)
2513 .expect("the hook prices its own fee");
2514
2515 assert!((executed / spot - 1.0).abs() < 1e-4, "executed {executed}, quoted {spot}");
2516 }
2517
2518 #[rstest]
2522 #[case::base_is_currency0(true)]
2523 #[case::base_is_currency1(false)]
2524 fn test_spot_price_prefers_an_analytic_fee_over_the_hooks_own_price(
2525 #[case] base_is_currency0: bool,
2526 ) {
2527 let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
2528 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2529 hooked.set_hook_handler(pricing_test_hook(Some(200)));
2530
2531 let core = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
2532 .spot_price(&base, "e)
2533 .expect("a hookless pool always prices");
2534 let price = hooked
2535 .spot_price(&base, "e)
2536 .expect("the hook prices its own fee");
2537
2538 assert_ne!(
2539 price, TEST_HOOK_SPOT_PRICE as f64,
2540 "the pool asked the hook for a price instead of marking up its own"
2541 );
2542 let ratio = price / core;
2543 assert!((ratio * 0.98 - 1.0).abs() < 1e-9, "hooked/hookless is {ratio}, not 1/0.98");
2544 }
2545
2546 #[rstest]
2550 #[case::base_is_currency0(true)]
2551 #[case::base_is_currency1(false)]
2552 fn test_spot_price_uses_the_hooks_own_price_without_an_analytic_fee(
2553 #[case] base_is_currency0: bool,
2554 ) {
2555 let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
2556 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2557 hooked.set_hook_handler(pricing_test_hook(None));
2558
2559 let price = hooked
2560 .spot_price(&base, "e)
2561 .expect("the hook answers with a price");
2562
2563 assert_eq!(price, TEST_HOOK_SPOT_PRICE as f64);
2564 }
2565
2566 #[rstest]
2569 #[case::base_is_currency0(true)]
2570 #[case::base_is_currency1(false)]
2571 fn test_spot_price_falls_back_to_finite_difference_without_an_analytic_fee(
2572 #[case] base_is_currency0: bool,
2573 ) {
2574 let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
2575 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2576 hooked.set_hook_handler(after_swap_test_hook(&[
2577 HookOptions::AfterSwap,
2578 HookOptions::AfterSwapReturnsDelta,
2579 ]));
2580
2581 let x1 = BigUint::from(10u64).pow(base.decimals) / BigUint::from(100u64);
2582 let x2 = &x1 + (&x1 / BigUint::from(100u64));
2583 let y1 = hooked
2584 .get_amount_out(x1.clone(), &base, "e)
2585 .expect("the smaller probe swap fits")
2586 .amount;
2587 let y2 = hooked
2588 .get_amount_out(x2.clone(), &base, "e)
2589 .expect("the larger probe swap fits")
2590 .amount;
2591 let slope = (&y2 - &y1).to_f64().unwrap() / (&x2 - &x1).to_f64().unwrap();
2592
2593 let price = hooked
2594 .spot_price(&base, "e)
2595 .expect("the fallback always prices");
2596
2597 assert_eq!(price, slope);
2598 let core = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
2599 .spot_price(&base, "e)
2600 .expect("a hookless pool always prices");
2601 assert!((price / core - 1.0).abs() < 1e-3, "fallback {price} strayed from core {core}");
2602 }
2603
2604 #[rstest]
2607 #[case::zero_for_one(true)]
2608 #[case::one_for_zero(false)]
2609 fn test_get_limits_reports_the_output_net_of_an_analytic_hook_fee(#[case] zero_for_one: bool) {
2610 let (token_in, token_out) = basic_v4_test_pool_tokens(zero_for_one);
2611 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2612 hooked.set_hook_handler(Box::new(pons_test_handler()));
2613
2614 let (hookless_in, hookless_out) = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
2615 .get_limits(token_in.address.clone(), token_out.address.clone())
2616 .expect("a pool with liquidity has limits");
2617 let (limit_in, limit_out) = hooked
2618 .get_limits(token_in.address, token_out.address)
2619 .expect("a pool with liquidity has limits");
2620
2621 assert!(hookless_out > BigUint::zero(), "the reference pool must move some output");
2622 assert_eq!(limit_in, hookless_in);
2623 let taken = pons_test_handler()
2624 .fee_and_tax(biguint_to_u256(&hookless_out))
2625 .expect("a pool sized output never overflows");
2626 assert_eq!(limit_out, &hookless_out - u256_to_biguint(taken));
2627 assert!(limit_out < hookless_out);
2628 }
2629
2630 #[rstest]
2633 #[case::zero_for_one(true)]
2634 #[case::one_for_zero(false)]
2635 fn test_get_limits_unchanged_without_an_analytic_hook_fee(#[case] zero_for_one: bool) {
2636 let (token_in, token_out) = basic_v4_test_pool_tokens(zero_for_one);
2637 let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2638 hooked.set_hook_handler(after_swap_test_hook(&[
2639 HookOptions::AfterSwap,
2640 HookOptions::AfterSwapReturnsDelta,
2641 ]));
2642
2643 let hookless = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
2644 .get_limits(token_in.address.clone(), token_out.address.clone())
2645 .expect("a pool with liquidity has limits");
2646 let limits = hooked
2647 .get_limits(token_in.address, token_out.address)
2648 .expect("a pool with liquidity has limits");
2649
2650 assert_eq!(limits, hookless);
2651 }
2652
2653 #[test]
2656 fn test_get_limits_on_a_drained_pool_is_zero_with_an_analytic_hook() {
2657 let (token_in, token_out) = basic_v4_test_pool_tokens(true);
2658 let mut drained = create_feeless_v4_test_pool(0);
2659 drained.set_hook_handler(Box::new(pons_test_handler()));
2660
2661 let limits = drained
2662 .get_limits(token_in.address, token_out.address)
2663 .expect("a drained pool reports zero rather than failing");
2664
2665 assert_eq!(limits, (BigUint::zero(), BigUint::zero()));
2666 }
2667
2668 #[rstest]
2671 #[case::the_whole_output(10_000)]
2672 #[case::more_than_the_whole_output(20_000)]
2673 fn test_spot_price_rejects_a_hook_that_takes_the_whole_output(#[case] analytic_fee_bps: u32) {
2674 let mut pool = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2675 pool.set_hook_handler(analytic_fee_test_hook(analytic_fee_bps));
2676
2677 let error = pool
2678 .spot_price(&token_x(), &token_y())
2679 .expect_err("a rate of one or more is not a price");
2680
2681 assert!(matches!(error, SimulationError::FatalError(_)), "{error:?}");
2682 }
2683
2684 #[test]
2685 fn test_spot_price_with_recoverable_error() {
2686 let usv4_state = UniswapV4State::new(
2690 1000000000000000000u128, U256::from_str("79228162514264337593543950336").unwrap(), UniswapV4Fees { zero_for_one: 100, one_for_zero: 100, lp_fee: 100 },
2693 0,
2694 60,
2695 vec![
2696 TickInfo::new(-600, 500000000000000000i128).unwrap(),
2697 TickInfo::new(600, -500000000000000000i128).unwrap(),
2698 ],
2699 )
2700 .unwrap();
2701
2702 let spot_price_result = usv4_state.spot_price(&usdc(), &weth());
2704 assert!(spot_price_result.is_ok());
2705
2706 let price = spot_price_result.unwrap();
2709 assert!(price > 0.0);
2710 }
2711
2712 #[test]
2713 fn test_get_limits_with_hook_managed_liquidity_no_ranges_entrypoint() {
2714 let block = BlockHeader {
2719 number: 22689128,
2720 hash: Bytes::from_str(
2721 "0xfbfa716523d25d6d5248c18d001ca02b1caf10cabd1ab7321465e2262c41157b",
2722 )
2723 .expect("Invalid block hash"),
2724 timestamp: 1749739055,
2725 ..Default::default()
2726 };
2727
2728 let hook_address: Address = Address::from_str("0x69058613588536167ba0aa94f0cc1fe420ef28a8")
2729 .expect("Invalid hook address");
2730
2731 let db = SimulationDB::new(
2732 get_client(None).expect("Failed to create client"),
2733 get_runtime().expect("Failed to get runtime"),
2734 Some(block),
2735 );
2736 let engine = create_engine(db, true).expect("Failed to create simulation engine");
2737 let pool_manager = Address::from_str("0x000000000004444c5dc75cb358380d2e3de08a90")
2738 .expect("Invalid pool manager address");
2739
2740 let hook_handler = GenericVMHookHandler::new(
2743 hook_address,
2744 engine,
2745 pool_manager,
2746 HashMap::new(),
2747 HashMap::new(),
2748 None,
2749 true, )
2751 .unwrap();
2752
2753 let mut usv4_state = UniswapV4State::new(
2755 0, U256::from_str("4295128740").unwrap(),
2757 UniswapV4Fees { zero_for_one: 100, one_for_zero: 90, lp_fee: 500 },
2758 0, 1, vec![], )
2762 .unwrap();
2763
2764 usv4_state.set_hook_handler(Box::new(hook_handler));
2765
2766 let token_in = usdc().address;
2767 let token_out = weth().address;
2768
2769 let (amount_in_limit, amount_out_limit) = usv4_state
2770 .get_limits(token_in, token_out)
2771 .expect("Should find limits through experimental swapping");
2772
2773 assert!(amount_in_limit > BigUint::from(10u64).pow(12));
2776 assert!(amount_in_limit < BigUint::from(10u64).pow(14));
2777
2778 assert!(amount_out_limit > BigUint::from(10u64).pow(20));
2780 assert!(amount_out_limit < BigUint::from(10u64).pow(22));
2781 }
2782
2783 #[rstest]
2784 #[case::high_liquidity(u128::MAX / 2)] #[case::medium_liquidity(10000000000000000000u128)] #[case::minimal_liquidity(1000u128)] fn test_find_max_amount(#[case] liquidity: u128) {
2788 let fees = UniswapV4Fees { zero_for_one: 100, one_for_zero: 100, lp_fee: 100 };
2790 let tick_spacing = 60;
2791 let ticks = vec![
2792 TickInfo::new(-600, i128::try_from(liquidity / 4).unwrap()).unwrap(),
2793 TickInfo::new(600, -(i128::try_from(liquidity / 4).unwrap())).unwrap(),
2794 ];
2795
2796 let usv4_state = UniswapV4State::new(
2797 liquidity,
2798 U256::from_str("79228162514264337593543950336").unwrap(),
2799 fees,
2800 0,
2801 tick_spacing,
2802 ticks,
2803 )
2804 .unwrap();
2805
2806 let token_in = usdc();
2807 let token_out = weth();
2808
2809 let (max_amount_in, _max_amount_out) = usv4_state.find_max_amount(&token_in, &token_out);
2810
2811 let success = usv4_state
2812 .get_amount_out(max_amount_in.clone(), &token_in, &token_out)
2813 .is_ok();
2814 assert!(success, "Should be able to swap the exact max amount.");
2815
2816 let one_more = &max_amount_in + BigUint::from(1u64);
2817 let should_fail = usv4_state
2818 .get_amount_out(one_more, &token_in, &token_out)
2819 .is_err();
2820 assert!(should_fail, "Swapping max_amount + 1 should fail.");
2821 }
2822
2823 #[test]
2824 fn test_calculate_swap_fees_with_override() {
2825 let fees = UniswapV4Fees::new(100, 90, 500);
2827
2828 let total_zero_for_one = fees
2831 .calculate_swap_fees_pips(true, None)
2832 .unwrap();
2833 assert_eq!(total_zero_for_one, 600);
2835
2836 let total_with_override = fees
2838 .calculate_swap_fees_pips(true, Some(1000))
2839 .unwrap();
2840 assert_eq!(total_with_override, 1100);
2842 }
2843
2844 #[test]
2845 fn test_max_combined_fees_stays_valid() {
2846 let fees = UniswapV4Fees::new(1000, 1000, 1000);
2848 let total = fees
2849 .calculate_swap_fees_pips(true, Some(lp_fee::MAX_LP_FEE))
2850 .unwrap();
2851
2852 assert_eq!(total, 1_000_000);
2855 }
2856
2857 #[test]
2858 fn test_get_limits_graceful_underflow() {
2859 let usv4_state = UniswapV4State::new(
2861 1000000,
2862 U256::from_str("79228162514264337593543950336").unwrap(), UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 },
2864 0,
2865 60,
2866 vec![
2867 TickInfo {
2870 index: -60,
2871 net_liquidity: 2000000, sqrt_price: U256::from_str("79051508376726796163471739988").unwrap(),
2873 },
2874 ],
2875 )
2876 .unwrap();
2877
2878 let usdc = usdc();
2879 let weth = weth();
2880
2881 let (limit_in, limit_out) = usv4_state
2882 .get_limits(usdc.address, weth.address)
2883 .unwrap();
2884
2885 assert!(limit_in > BigUint::zero());
2887 assert!(limit_out > BigUint::zero());
2888 }
2889
2890 const MAX_PROTOCOL_FEE: u32 = 1000;
2895
2896 #[rstest]
2897 #[case::max_protocol_and_max_lp(MAX_PROTOCOL_FEE, lp_fee::MAX_LP_FEE, lp_fee::MAX_LP_FEE)]
2898 #[case::max_protocol_with_3000_lp(MAX_PROTOCOL_FEE, 3000, 3997)]
2899 #[case::max_protocol_with_zero_lp(MAX_PROTOCOL_FEE, 0, MAX_PROTOCOL_FEE)]
2900 #[case::zero_protocol_zero_lp(0, 0, 0)]
2901 #[case::zero_protocol_with_1000_lp(0, 1000, 1000)]
2902 fn test_calculate_swap_fees_uniswap_test_cases(
2903 #[case] protocol_fee: u32,
2904 #[case] lp_fee: u32,
2905 #[case] expected: u32,
2906 ) {
2907 let fees = UniswapV4Fees::new(protocol_fee, protocol_fee, lp_fee);
2908 let result = fees
2909 .calculate_swap_fees_pips(true, None)
2910 .unwrap();
2911 assert_eq!(result, expected);
2912 }
2913
2914 #[test]
2915 fn test_calculate_swap_fees_with_dynamic_fee() {
2916 let fees = UniswapV4Fees::new(100, 90, lp_fee::DYNAMIC_FEE_FLAG);
2918
2919 let total_zero_for_one = fees
2921 .calculate_swap_fees_pips(true, None)
2922 .unwrap();
2923 assert_eq!(total_zero_for_one, 100);
2925
2926 let total_with_override = fees
2928 .calculate_swap_fees_pips(true, Some(500))
2929 .unwrap();
2930 assert_eq!(total_with_override, 600);
2932 }
2933
2934 #[test]
2935 fn test_calculate_swap_fees_direction_matters() {
2936 let fees = UniswapV4Fees::new(100, 200, 500);
2938
2939 let zero_for_one_fee = fees
2940 .calculate_swap_fees_pips(true, None)
2941 .unwrap();
2942 assert_eq!(zero_for_one_fee, 600);
2944
2945 let one_for_zero_fee = fees
2946 .calculate_swap_fees_pips(false, None)
2947 .unwrap();
2948 assert_eq!(one_for_zero_fee, 700);
2950 }
2951
2952 #[rstest]
2953 #[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(
2957 #[case] protocol_fee: u32,
2958 #[case] lp_fee: u32,
2959 #[case] expected: u32,
2960 ) {
2961 let fees = UniswapV4Fees::new(protocol_fee, protocol_fee, lp_fee);
2964 let result = fees
2965 .calculate_swap_fees_pips(true, None)
2966 .unwrap();
2967 assert_eq!(result, expected, "Failed for protocol={}, lp={}", protocol_fee, lp_fee);
2968 }
2969
2970 #[test]
2971 fn test_calculate_swap_fees_override_takes_precedence() {
2972 let fees = UniswapV4Fees::new(100, 100, 3000);
2974
2975 let result = fees
2977 .calculate_swap_fees_pips(true, Some(5000))
2978 .unwrap();
2979 assert_eq!(result, 5100);
2981
2982 let result_no_override = fees
2984 .calculate_swap_fees_pips(true, None)
2985 .unwrap();
2986 assert_eq!(result_no_override, 3100);
2988 }
2989
2990 #[test]
2991 fn test_calculate_swap_fees_zero_protocol_fee() {
2992 let fees = UniswapV4Fees::new(0, 0, 3000);
2994 let result = fees
2995 .calculate_swap_fees_pips(true, None)
2996 .unwrap();
2997 assert_eq!(result, 3000);
2999 }
3000
3001 #[test]
3002 fn test_calculate_swap_fees_zero_lp_fee() {
3003 let fees = UniswapV4Fees::new(500, 500, 0);
3005 let result = fees
3006 .calculate_swap_fees_pips(true, None)
3007 .unwrap();
3008 assert_eq!(result, 500);
3010 }
3011
3012 fn create_basic_v4_test_pool() -> UniswapV4State {
3014 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))
3016 .expect("Failed to calculate sqrt price");
3017 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
3018
3019 let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
3020
3021 UniswapV4State::new(
3022 liquidity,
3023 sqrt_price,
3024 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 }, tick,
3026 60, ticks,
3028 )
3029 .expect("Failed to create pool")
3030 }
3031
3032 fn create_tick_boundary_v4_test_pool() -> UniswapV4State {
3033 let sqrt_price = get_sqrt_ratio_at_tick(0).expect("Failed to calculate sqrt price");
3034 let ticks = vec![TickInfo::new(-120, 0).unwrap(), TickInfo::new(120, 0).unwrap()];
3035
3036 UniswapV4State::new(
3037 100_000_000_000_000_000_000u128,
3038 sqrt_price,
3039 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 },
3040 0,
3041 60,
3042 ticks,
3043 )
3044 .expect("Failed to create pool")
3045 }
3046
3047 #[test]
3048 fn test_partial_step_updates_tick_when_price_moves_without_crossing_initialized_tick() {
3049 let pool = create_tick_boundary_v4_test_pool();
3050 let amount = -I256::from_raw(U256::from(100_000_000_000_000_000u64));
3051
3052 let result = pool
3053 .swap(true, amount, None, None)
3054 .expect("swap should stay within the current liquidity range");
3055 let expected_tick =
3056 get_tick_at_sqrt_ratio(result.sqrt_price).expect("new sqrt price should map to a tick");
3057
3058 assert_ne!(result.sqrt_price, pool.sqrt_price);
3059 assert_ne!(result.sqrt_price, get_sqrt_ratio_at_tick(-120).unwrap());
3060 assert_ne!(expected_tick, pool.tick.value());
3061 assert_eq!(result.tick.value(), expected_tick);
3062 }
3063
3064 #[test]
3065 fn test_swap_keeps_boundary_tick_when_price_does_not_move() {
3066 let mut pool = create_tick_boundary_v4_test_pool();
3067 pool.tick = PoolTick::from(-1);
3068 let amount = -I256::from_raw(U256::from(1u64));
3069
3070 let result = pool
3071 .swap(true, amount, None, None)
3072 .expect("swap should consume the input as fee without moving price");
3073
3074 assert_eq!(result.sqrt_price, pool.sqrt_price);
3075 assert_eq!(get_tick_at_sqrt_ratio(result.sqrt_price).unwrap(), 0);
3076 assert_eq!(result.tick, pool.tick);
3077 }
3078
3079 #[test]
3080 fn test_swap_to_price_price_too_high() {
3081 let pool = create_basic_v4_test_pool();
3082
3083 let token_x = token_x();
3084 let token_y = token_y();
3085
3086 let target_price = Price::new(BigUint::from(10_000_000u64), BigUint::from(1_000_000u64));
3088
3089 let result = pool.query_pool_swap(&QueryPoolSwapParams::new(
3090 token_x,
3091 token_y,
3092 SwapConstraint::PoolTargetPrice {
3093 target: target_price,
3094 tolerance: 0f64,
3095 min_amount_in: None,
3096 max_amount_in: None,
3097 },
3098 ));
3099 assert!(result.is_err(), "Should return error when target price is unreachable");
3100 }
3101
3102 #[test]
3103 fn test_swap_to_price_no_liquidity() {
3104 let pool = UniswapV4State::new(
3106 0, U256::from_str("79228162514264337593543950336").unwrap(),
3108 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 },
3109 0,
3110 60,
3111 vec![],
3112 )
3113 .unwrap();
3114
3115 let token_x = token_x();
3116 let token_y = token_y();
3117
3118 let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_000_000u64));
3119
3120 let pool_swap = pool.query_pool_swap(&QueryPoolSwapParams::new(
3121 token_x,
3122 token_y,
3123 SwapConstraint::PoolTargetPrice {
3124 target: target_price,
3125 tolerance: 0f64,
3126 min_amount_in: None,
3127 max_amount_in: None,
3128 },
3129 ));
3130
3131 assert!(pool_swap.is_err());
3132 }
3133
3134 #[test]
3135 fn test_swap_to_price_with_protocol_fees() {
3136 let liquidity = 100_000_000_000_000_000_000u128;
3137 let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
3138 .expect("Failed to calculate sqrt price");
3139 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
3140
3141 let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
3142
3143 let pool = UniswapV4State::new(
3145 liquidity,
3146 sqrt_price,
3147 UniswapV4Fees {
3148 zero_for_one: 1000, one_for_zero: 200, lp_fee: 3000, },
3152 tick,
3153 60,
3154 ticks,
3155 )
3156 .expect("Failed to create pool");
3157
3158 let token_x = token_x();
3159 let token_y = token_y();
3160
3161 let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_010_000u64));
3165 let pool_swap_forward = pool
3166 .query_pool_swap(&QueryPoolSwapParams::new(
3167 token_x.clone(),
3168 token_y.clone(),
3169 SwapConstraint::PoolTargetPrice {
3170 target: target_price,
3171 tolerance: 0f64,
3172 min_amount_in: None,
3173 max_amount_in: None,
3174 },
3175 ))
3176 .expect("swap_to_price failed");
3177
3178 let target_price_reverse =
3180 Price::new(BigUint::from(1_010_000u64), BigUint::from(2_040_000u64));
3181 let pool_swap_backward = pool
3182 .query_pool_swap(&QueryPoolSwapParams::new(
3183 token_y,
3184 token_x,
3185 SwapConstraint::PoolTargetPrice {
3186 target: target_price_reverse,
3187 tolerance: 0f64,
3188 min_amount_in: None,
3189 max_amount_in: None,
3190 },
3191 ))
3192 .expect("swap_to_price failed");
3193
3194 assert!(
3195 pool_swap_backward.amount_out().clone() > BigUint::ZERO,
3196 "One for zero swap should return non-zero output"
3197 );
3198
3199 assert!(
3202 pool_swap_forward.amount_out() < pool_swap_backward.amount_in(),
3203 "Backward fees should be lower therefore backward swap should be bigger"
3204 );
3205 assert!(
3206 pool_swap_forward.amount_in() < pool_swap_backward.amount_out(),
3207 "Backward fees should be lower therefore backward swap should be bigger"
3208 );
3209 }
3210
3211 #[test]
3212 fn test_swap_to_price_different_targets() {
3213 let pool = create_basic_v4_test_pool();
3215
3216 let token_x = token_x();
3217 let token_y = token_y();
3218
3219 let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_010_000u64));
3222 let pool_swap_close = pool
3223 .query_pool_swap(&QueryPoolSwapParams::new(
3224 token_x.clone(),
3225 token_y.clone(),
3226 SwapConstraint::PoolTargetPrice {
3227 target: target_price,
3228 tolerance: 0f64,
3229 min_amount_in: None,
3230 max_amount_in: None,
3231 },
3232 ))
3233 .expect("swap_to_price failed");
3234 assert!(
3235 *pool_swap_close.amount_out() > BigUint::ZERO,
3236 "Expected non-zero for 1.98 Y/X target"
3237 );
3238
3239 let target_price = Price::new(BigUint::from(1_900_000u64), BigUint::from(1_000_000u64));
3241 let pool_swap_below = pool
3242 .query_pool_swap(&QueryPoolSwapParams::new(
3243 token_x.clone(),
3244 token_y.clone(),
3245 SwapConstraint::PoolTargetPrice {
3246 target: target_price,
3247 tolerance: 0f64,
3248 min_amount_in: None,
3249 max_amount_in: None,
3250 },
3251 ))
3252 .expect("swap_to_price failed");
3253 assert!(
3254 pool_swap_below.amount_out().clone() > BigUint::ZERO,
3255 "Expected non-zero for 1.90 Y/X target"
3256 );
3257
3258 let target_price = Price::new(BigUint::from(1_500_000u64), BigUint::from(1_000_000u64));
3260 let pool_swap_far = pool
3261 .query_pool_swap(&QueryPoolSwapParams::new(
3262 token_x,
3263 token_y,
3264 SwapConstraint::PoolTargetPrice {
3265 target: target_price,
3266 tolerance: 0f64,
3267 min_amount_in: None,
3268 max_amount_in: None,
3269 },
3270 ))
3271 .expect("swap_to_price failed");
3272 assert!(
3273 pool_swap_far.amount_out().clone() > BigUint::ZERO,
3274 "Expected non-zero for 1.5 Y/X target"
3275 );
3276
3277 assert!(
3279 pool_swap_close.amount_out().clone() < pool_swap_below.amount_out().clone(),
3280 "Closer target (1.98 Y/X) should require less volume than medium target (1.90 Y/X). \
3281 Got close: {}, medium: {}",
3282 pool_swap_close.amount_out().clone(),
3283 pool_swap_below.amount_out().clone()
3284 );
3285 assert!(
3286 pool_swap_below.amount_out().clone() < pool_swap_far.amount_out().clone(),
3287 "Medium target (1.90 Y/X) should require less volume than far target (1.5 Y/X). \
3288 Got medium: {}, far: {}",
3289 pool_swap_below.amount_out().clone(),
3290 pool_swap_far.amount_out().clone()
3291 );
3292 }
3293
3294 #[test]
3295 fn test_swap_to_price_around_spot_price() {
3296 let liquidity = 10_000_000_000_000_000u128;
3297 let sqrt_price =
3298 get_sqrt_price_q96(U256::from(2_000_000_000u64), U256::from(1_000_000_000u64))
3299 .expect("Failed to calculate sqrt price");
3300 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
3301
3302 let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
3303
3304 let pool = UniswapV4State::new(
3306 liquidity,
3307 sqrt_price,
3308 UniswapV4Fees {
3309 zero_for_one: 0,
3310 one_for_zero: 0,
3311 lp_fee: 500, },
3313 tick,
3314 60,
3315 ticks,
3316 )
3317 .expect("Failed to create pool");
3318
3319 let token_x = token_x();
3320 let token_y = token_y();
3321
3322 let target_price = Price::new(BigUint::from(1_999_750u64), BigUint::from(1_000_250u64));
3324
3325 let result = pool.query_pool_swap(&QueryPoolSwapParams::new(
3326 token_x.clone(),
3327 token_y.clone(),
3328 SwapConstraint::PoolTargetPrice {
3329 target: target_price,
3330 tolerance: 0f64,
3331 min_amount_in: None,
3332 max_amount_in: None,
3333 },
3334 ));
3335 assert!(result.is_err(), "Should return error when target price is unreachable");
3336
3337 let target_price = Price::new(BigUint::from(1_999_000u64), BigUint::from(1_001_000u64));
3339
3340 let pool_swap = pool
3341 .query_pool_swap(&QueryPoolSwapParams::new(
3342 token_x,
3343 token_y,
3344 SwapConstraint::PoolTargetPrice {
3345 target: target_price,
3346 tolerance: 0f64,
3347 min_amount_in: None,
3348 max_amount_in: None,
3349 },
3350 ))
3351 .expect("swap_to_price failed");
3352
3353 let expected_amount_out =
3355 BigUint::from_str("7062236922008").expect("Failed to parse expected value");
3356 assert_eq!(
3357 pool_swap.amount_out().clone(),
3358 expected_amount_out,
3359 "V4 should match V3 output with same fees (0.05%)"
3360 );
3361 }
3362
3363 #[test]
3364 fn test_swap_to_price_matches_get_amount_out() {
3365 let pool = create_basic_v4_test_pool();
3366
3367 let token_x = token_x();
3368 let token_y = token_y();
3369
3370 let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_010_000u64));
3372 let pool_swap = pool
3373 .query_pool_swap(&QueryPoolSwapParams::new(
3374 token_x.clone(),
3375 token_y.clone(),
3376 SwapConstraint::PoolTargetPrice {
3377 target: target_price,
3378 tolerance: 0f64,
3379 min_amount_in: None,
3380 max_amount_in: None,
3381 },
3382 ))
3383 .expect("swap_to_price failed");
3384 assert!(*pool_swap.amount_in() > BigUint::ZERO, "Amount in should be positive");
3385
3386 let result = pool
3388 .get_amount_out(pool_swap.amount_in().clone(), &token_x, &token_y)
3389 .expect("get_amount_out failed");
3390
3391 assert!(result.amount > BigUint::ZERO);
3394 assert!(result.amount >= *pool_swap.amount_out());
3395 }
3396
3397 #[test]
3398 fn test_swap_to_price_basic() {
3399 let liquidity = 100_000_000_000_000_000_000u128;
3400 let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
3401 .expect("Failed to calculate sqrt price");
3402 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
3403
3404 let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
3405
3406 let pool = UniswapV4State::new(
3407 liquidity,
3408 sqrt_price,
3409 UniswapV4Fees {
3410 zero_for_one: 0,
3411 one_for_zero: 0,
3412 lp_fee: 3000, },
3414 tick,
3415 60,
3416 ticks,
3417 )
3418 .expect("Failed to create pool");
3419
3420 let token_x = token_x();
3421 let token_y = token_y();
3422
3423 let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_010_000u64));
3425
3426 let pool_swap = pool
3427 .query_pool_swap(&QueryPoolSwapParams::new(
3428 token_x,
3429 token_y,
3430 SwapConstraint::PoolTargetPrice {
3431 target: target_price,
3432 tolerance: 0f64,
3433 min_amount_in: None,
3434 max_amount_in: None,
3435 },
3436 ))
3437 .expect("swap_to_price failed");
3438
3439 let expected_amount_in = BigUint::from_str("246739021727519745").unwrap();
3441 let expected_amount_out = BigUint::from_str("490291909043340795").unwrap();
3442
3443 assert_eq!(
3444 *pool_swap.amount_in(),
3445 expected_amount_in,
3446 "amount_in should match expected value"
3447 );
3448 assert_eq!(
3449 *pool_swap.amount_out(),
3450 expected_amount_out,
3451 "amount_out should match expected value"
3452 );
3453 }
3454
3455 #[test]
3456 fn test_swap_price_limit_out_of_range_returns_error() {
3457 let pool = create_basic_v4_test_pool();
3458 let amount = -I256::from_raw(U256::from(1000u64)); let result = pool.swap(true, amount, Some(pool.sqrt_price), None);
3462 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
3463
3464 let result = pool.swap(true, amount, Some(MIN_SQRT_RATIO), None);
3466 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
3467
3468 let result = pool.swap(false, amount, Some(pool.sqrt_price), None);
3470 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
3471
3472 let result = pool.swap(false, amount, Some(MAX_SQRT_RATIO), None);
3474 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
3475 }
3476
3477 #[test]
3478 fn test_swap_at_extreme_price_returns_error() {
3479 let sqrt_price = MIN_SQRT_RATIO + U256::from(1u64);
3482 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
3483 let aligned_tick = (MIN_TICK / 60) * 60 + 60; let ticks = vec![
3486 TickInfo::new(aligned_tick, 0).unwrap(),
3487 TickInfo::new(aligned_tick + 60, 0).unwrap(),
3488 ];
3489 let pool = UniswapV4State::new(
3490 100_000_000_000_000_000_000u128,
3491 sqrt_price,
3492 UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 },
3493 tick,
3494 60,
3495 ticks,
3496 )
3497 .unwrap();
3498
3499 let amount = -I256::from_raw(U256::from(1000u64));
3500 let result = pool.swap(true, amount, None, None);
3502 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
3503 }
3504
3505 #[test]
3506 fn test_serde_roundtrip_via_protocol_sim_typetag() {
3507 let pool = create_basic_v4_test_pool();
3508
3509 let json =
3510 serde_json::to_string(&pool as &dyn ProtocolSim).expect("state should serialize");
3511 let deserialized: Box<dyn ProtocolSim> =
3512 serde_json::from_str(&json).expect("state should deserialize");
3513
3514 assert!(deserialized.eq(&pool));
3515 }
3516
3517 #[test]
3518 fn test_serialize_with_hook() {
3519 let mut pool = create_basic_v4_test_pool();
3520 let handler = AngstromHookHandler::new(
3521 Address::from_str("0x0000000aa232009084bd71a5797d089aa4edfad4").unwrap(),
3522 Address::from_str("0x000000000004444c5dc75cb358380d2e3de08a90").unwrap(),
3523 AngstromFees { unlock: U24::from(238), protocol_unlock: U24::from(112) },
3524 false,
3525 );
3526 pool.set_hook_handler(Box::new(handler));
3527
3528 let result = serde_json::to_string(&pool);
3529 assert!(result
3530 .unwrap_err()
3531 .to_string()
3532 .contains("HookHandler is a trait object"));
3533 }
3534
3535 #[test]
3536 fn test_deserialize_negative_tick_spacing() {
3537 let pool = UniswapV4State::new(
3538 1_000,
3539 U256::from(1u64) << 96,
3540 UniswapV4Fees::new(0, 0, 3000),
3541 0,
3542 60,
3543 vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(60, 0).unwrap()],
3544 )
3545 .expect("valid state");
3546 let mut json = serde_json::to_value(&pool).expect("hookless state should serialize");
3547 json["tick_spacing"] = (-60).into();
3548
3549 let err = serde_json::from_value::<UniswapV4State>(json).unwrap_err();
3550
3551 assert!(
3552 err.to_string()
3553 .contains("must be positive"),
3554 "unexpected error: {err}"
3555 );
3556 }
3557}
3558
3559#[cfg(test)]
3560mod step_cache_tests {
3561 use std::{
3562 collections::{HashMap, HashSet},
3563 str::FromStr,
3564 };
3565
3566 use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
3567
3568 use super::*;
3569 use crate::evm::protocol::utils::uniswap::swap_step_cache::test_fixtures::{
3570 amount_orders, test_amounts, test_ticks, wbtc_weth, LIQUIDITY, SQRT_PRICE, TICK,
3571 };
3572
3573 fn test_pool_with_fees(fees: UniswapV4Fees) -> UniswapV4State {
3574 UniswapV4State::new(
3575 LIQUIDITY,
3576 U256::from_str(SQRT_PRICE).unwrap(),
3577 fees,
3578 TICK,
3579 10,
3580 test_ticks(),
3581 )
3582 .unwrap()
3583 }
3584
3585 fn test_pool() -> UniswapV4State {
3586 test_pool_with_fees(UniswapV4Fees::new(0, 0, 500))
3587 }
3588
3589 fn format_quote_result(
3591 pool: &UniswapV4State,
3592 amount: &BigUint,
3593 sell: &Token,
3594 buy: &Token,
3595 ) -> String {
3596 match pool.get_amount_out(amount.clone(), sell, buy) {
3597 Ok(result) => {
3598 let state = result
3599 .new_state
3600 .as_any()
3601 .downcast_ref::<UniswapV4State>()
3602 .unwrap();
3603 format!(
3604 "{} {} {} {} {}",
3605 result.amount,
3606 result.gas,
3607 state.sqrt_price,
3608 state.tick.value(),
3609 state.liquidity
3610 )
3611 }
3612 Err(error) => format!("error {error}"),
3613 }
3614 }
3615
3616 #[test]
3617 fn test_step_cache_quotes_match_a_fresh_state_in_any_order() {
3618 let (wbtc, weth) = wbtc_weth();
3619 for fees in [UniswapV4Fees::new(0, 0, 500), UniswapV4Fees::new(100, 90, 3000)] {
3621 for (sell, buy, smallest) in [(&wbtc, &weth, 1_000u64), (&weth, &wbtc, 1_000_000_000)] {
3622 for order in amount_orders(&test_amounts(smallest)) {
3623 let shared = test_pool_with_fees(fees.clone());
3624 for amount in &order {
3625 assert_eq!(
3626 format_quote_result(&shared, amount, sell, buy),
3627 format_quote_result(
3628 &test_pool_with_fees(fees.clone()),
3629 amount,
3630 sell,
3631 buy
3632 ),
3633 "selling {amount} {} with {fees:?}",
3634 sell.symbol
3635 );
3636 }
3637 let steps = shared
3638 .step_cache
3639 .min_inputs(sell < buy)
3640 .len();
3641 assert!(steps > 2, "only {steps} steps cached");
3642 }
3643 }
3644 }
3645 }
3646
3647 #[test]
3648 fn test_step_cache_quotes_match_a_fresh_state_at_each_cached_step() {
3649 let (wbtc, weth) = wbtc_weth();
3650 for (sell, buy, doublings) in [(&wbtc, &weth, 30u32), (&weth, &wbtc, 70)] {
3653 let cached = test_pool();
3654 #[expect(
3655 clippy::let_underscore_must_use,
3656 reason = "the quote may run out of liquidity; only the step cache it fills is used"
3657 )]
3658 let _ = cached.get_amount_out(BigUint::from(10u32) << doublings, sell, buy);
3659 let boundaries = cached.step_cache.min_inputs(sell < buy);
3660 assert!(boundaries.len() > 2, "only {} steps cached", boundaries.len());
3661 for boundary in boundaries.into_iter().skip(1) {
3662 for amount in [boundary - U256::from(1u64), boundary, boundary + U256::from(1u64)] {
3663 let amount = u256_to_biguint(amount);
3664 assert_eq!(
3665 format_quote_result(&cached, &amount, sell, buy),
3666 format_quote_result(&test_pool(), &amount, sell, buy),
3667 "selling {amount} {}",
3668 sell.symbol
3669 );
3670 }
3671 }
3672 }
3673 }
3674
3675 #[test]
3676 fn test_step_cache_restarts_after_delta_transition() {
3677 let (wbtc, weth) = wbtc_weth();
3678 let large = BigUint::from(3_000_000_000u64);
3679 let delta = || ProtocolStateDelta {
3682 component_id: "State1".to_owned(),
3683 updated_attributes: HashMap::from([(
3684 "ticks/255820/net_liquidity".to_string(),
3685 Bytes::from(
3686 1_000_000_000_000_000i128
3687 .to_be_bytes()
3688 .to_vec(),
3689 ),
3690 )]),
3691 deleted_attributes: HashSet::new(),
3692 };
3693 let mut cached = test_pool();
3694 cached
3695 .get_amount_out(large.clone(), &wbtc, &weth)
3696 .unwrap();
3697 let mut fresh = test_pool();
3698
3699 cached
3700 .delta_transition(delta(), &HashMap::new(), &Balances::default())
3701 .unwrap();
3702 fresh
3703 .delta_transition(delta(), &HashMap::new(), &Balances::default())
3704 .unwrap();
3705
3706 assert_eq!(
3707 format_quote_result(&cached, &large, &wbtc, &weth),
3708 format_quote_result(&fresh, &large, &wbtc, &weth)
3709 );
3710 }
3711}