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