Skip to main content

tycho_simulation/evm/protocol/uniswap_v4/
state.rs

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
57// Fixed overhead per swap: covers router overhead, executor preamble (decode, sync,
58// unlock/callback pattern), and token transfer-in.
59const SWAP_BASE_GAS: u64 = 185_000;
60// Per loop: PoolManager.swap bitmap lookup + sqrt math + computeSwapStep.
61// V4's singleton PoolManager hits warmer storage than V3 standalone pools: ~3,500/loop.
62const GAS_PER_BITMAP_LOOKUP: u64 = 3_500;
63// Initialized tick crossing: _updateTick() updates feeGrowthOutside0/1 (2 SSTOREs).
64// Warm ≈ 10–17k, cold ≈ 40–52k. We use a blended estimate that
65// weights toward cold costs.
66const GAS_PER_TICK: u64 = 29_000;
67// Settlement overhead within swapExactInputSingle: _settle() + _getFullCredit() + misc.
68const V4_CALLBACK_SETTLEMENT_GAS: u64 = 30_000;
69// PoolManager Hooks.sol wrapper overhead per hook call: ABI encode params,
70// external CALL dispatch, decode return, validate selector, and process
71// the returned BeforeSwapDelta / AfterSwapDelta.
72pub(crate) const PM_PER_HOOK_CALL_OVERHEAD: u64 = 25_000;
73// Conservative max gas budget for a single swap (Ethereum transaction gas limit)
74const MAX_SWAP_GAS: u64 = 16_700_000;
75const MAX_TICKS_CROSSED: u64 = (MAX_SWAP_GAS - SWAP_BASE_GAS) / GAS_PER_TICK;
76// Decimal exponent of the output amount a hook is probed with to read off its fee rate.
77// Hooks floor each term of their fee, so the rate is only exact in the limit of a large amount;
78// 1e30 makes the rounding smaller than an f64 can hold and still leaves room under U256::MAX for
79// the hook's own intermediate products.
80const HOOK_FEE_PROBE_EXP: u64 = 30;
81
82/// Only hookless pools serialize. Deserializing sets `hook: None` and checks the tick list.
83#[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    /// The tick list, shared by this state, its clones and the states its swaps return, so a quote
91    /// does not copy it. Change it only through `Arc::make_mut`, which copies the list while
92    /// another state shares it.
93    ticks: Arc<TickList>,
94    tick_spacing: i32,
95    pub hook: Option<Box<dyn HookHandler>>,
96    /// Storage and block environment a pending quote runs the hook under. `None` on confirmed
97    /// state; set only on the clones `apply_deltas_ephemeral` hands out.
98    pending_overrides: Option<Arc<PendingOverrides>>,
99    /// Swap steps already taken from this state, shared by its clones. The steps hold only for
100    /// this state's price, tick, liquidity, fees and ticks. `delta_transition` and
101    /// `clone_post_swap` replace the cache with an empty one, and any other code that changes
102    /// those fields must do the same.
103    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    // Protocol fees in the zero for one direction
178    pub zero_for_one: u32,
179    // Protocol fees in the one for zero direction
180    pub one_for_zero: u32,
181    // Liquidity providers fees
182    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 a protocol has dynamic fees,
194            if is_dynamic(self.lp_fee) {
195                0
196            } else {
197                self.lp_fee
198            }
199        });
200
201        // UniswapV4 formula: protocolFee + lpFee - (protocolFee * lpFee / 1_000_000)
202        // Source: https://raw.githubusercontent.com/Uniswap/v4-core/main/src/libraries/ProtocolFeeLibrary.sol
203        // This accounts for the fact that protocol fee is taken first, then LP fee applies to
204        // remainder
205        protocol_fee + lp_fee - ((protocol_fee as u64 * lp_fee as u64 / 1_000_000) as u32)
206    }
207}
208
209impl UniswapV4State {
210    /// Creates a new `UniswapV4State` with specified values.
211    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            // even though it's given as int24, tick_spacing must be positive, see here:
221            // https://github.com/Uniswap/v4-core/blob/a22414e4d7c0d0b0765827fe0a6c20dfd7f96291/src/libraries/TickMath.sol#L25-L28
222            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    /// A clone of this state with the final price, tick and liquidity of a swap, and an empty
246    /// step cache.
247    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), // baseline gas cost for no-op swap
272            });
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        // A hook's fee override holds for one swap only, so those swaps neither use nor add to the
307        // step cache.
308        // Only exact-input swaps with no price limit use the step cache. The cache finds a step by
309        // its input, which an exact-output swap does not know. A cached step can also lie past a
310        // price limit.
311        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                    // The core univ4 swap logic assumes that if the amount is > 0 it's exact in,
385                    // and if it's < 0 it's exact out. The compute_swap_step
386                    // assumes the opposite (it's like that for univ3).
387                    -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        // Create dummy token objects with proper addresses. This is fine since `get_amount_out`
467        // only uses the token addresses.
468        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    /// Finds max amount by performing exponential search.
477    ///
478    /// Reasoning:
479    /// - get_amount_out(I256::MAX) will almost always fail, so this will waste time checking values
480    ///   unrealistically high.
481    /// - If you were to start binary search from 1 to 10^76, you'd need hundreds of iterations.
482    ///
483    /// More about exponential search: https://en.wikipedia.org/wiki/Exponential_search
484    ///
485    /// # Returns
486    ///
487    /// Returns a tuple containing the max amount in and max amount out respectively.
488    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        // The max you can swap on a USV4 is I256::MAX is 5.7e76, since input amount is I256.
496        // So start with something much smaller to search for a reasonable upper bound.
497        let mut high = BigUint::from(10u64).pow(18); // 1 ether in wei
498        let mut last_successful_amount_in = BigUint::from(1u64);
499        let mut last_successful_amount_out = BigUint::from(0u64);
500
501        // First, find an upper bound where the swap fails using exponential search.
502        // Save and return both the amount in and amount out.
503        while let Ok(result) = self.get_amount_out(high.clone(), token_in, token_out) {
504            // We haven't found the upper bound yet, increase the attempted upper bound
505            // by order of magnitude and store the last success as the lower bound.
506            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            // Stop if we're getting too large for I256 (about 10^75)
512            if high > BigUint::from(10u64).pow(75) {
513                return Ok((last_successful_amount_in, last_successful_amount_out));
514            }
515        }
516
517        // Use binary search to narrow down value between low and high
518        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    /// Helper method to check if there are no initialized ticks in either direction
537    fn has_no_initialized_ticks(&self) -> bool {
538        !self.ticks.has_initialized_ticks()
539    }
540
541    /// The pool's own spot buy price for `base` in units of `quote`: the amount of `quote` one
542    /// `base` costs at the current price, marked up by the pool's swap fee and ignoring any hook.
543    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    /// The share of a swap's output that the pool's hook keeps, as a fraction of one. `None`
560    /// when the pool has no hook, or when its hook does not model its fee analytically and has
561    /// to be simulated instead.
562    ///
563    /// Fails if the hook would keep the whole output or more, which is not a rate a price can be
564    /// marked up by.
565    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    /// Runs the hook of every quote and limit from this state under `overrides`, which must be
588    /// [`PendingOverrides`].
589    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    // Not possible to implement correctly with the current interface because we need to know the
608    // swap direction.
609    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            // Buying `base` means selling `quote` into the pool, so the hook sees a swap whose
616            // input is `quote` and whose output, the leg it charges, is `base`. A hook that
617            // prices that cut analytically needs no simulation: its price is the pool's own buy
618            // price marked up by the cut.
619            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                    // Calculate spot price by swapping two amounts and use the approximation
627                    // to get the derivative, following the pattern from vm/state.rs
628
629                    // Calculate the first sell amount (x1) as a small amount
630                    let x1 = BigUint::from(10u64).pow(base.decimals) / BigUint::from(100u64); // 0.01 token
631
632                    // Calculate the second sell amount (x2) as x1 + 1% of x1
633                    let x2 = &x1 + (&x1 / BigUint::from(100u64));
634
635                    // Perform swaps to get the received amounts
636                    let y1 = self.get_amount_out(x1.clone(), base, quote)?;
637                    let y2 = self.get_amount_out(x2.clone(), base, quote)?;
638
639                    // Calculate the marginal price
640                    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                    // Convert to f64 and adjust for decimals
661                    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        // Check if hook is set and has before_swap permissions
722        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                // A hook that refuses this swap, such as one gating trading on a start time,
732                // reports `InvalidInput`; only a failure to simulate the hook is fatal.
733                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                // Convert amountDelta to amountToSwap as per Uniswap V4 spec
747                // See: https://github.com/Uniswap/v4-core/blob/main/src/libraries/Hooks.sol#L270
748                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                // Set LP fee override if provided by hook
758                // The fee returned by beforeSwap may have the override flag (bit 22) set,
759                // which needs to be removed before using the fee value.
760                // See: https://github.com/Uniswap/v4-core/blob/main/src/libraries/LPFeeLibrary.sol
761                let hook_fee = before_swap_result
762                    .result
763                    .fee
764                    .to::<u32>();
765                if hook_fee != 0 {
766                    // Remove the override flag (bit 22) as per LPFeeLibrary.sol
767                    let cleaned_fee = lp_fee::remove_override_flag(hook_fee);
768
769                    // Validate the fee doesn't exceed MAX_LP_FEE (1,000,000 pips = 100%)
770                    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        // Perform the swap with potential hook modifications
784        let result = self.swap(zero_for_one, amount_to_swap, None, lp_fee_override)?;
785
786        // Create BalanceDelta from swap result using the proper constructor
787        let mut swap_delta = BalanceDelta::from_swap_result(result.amount_calculated, zero_for_one);
788
789        // Get deltas (change in the specified/given and unspecified/computed token balances after
790        // calling before swap)
791        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                // Hooks.sol calls afterSwap whenever AFTER_SWAP_FLAG is set, but only parses the
813                // returned delta when AFTER_SWAP_RETURNS_DELTA_FLAG is set too. Without that
814                // permission the PoolManager discards the return value, so the hook still costs
815                // gas but cannot move the swapper's balance.
816                if hook.has_permission(HookOptions::AfterSwapReturnsDelta) {
817                    hook_delta_unspecified += after_swap_result.result;
818                }
819            }
820        }
821
822        // Replicates the behaviour of the Hooks library wrapper of the afterSwap method:
823        // https://github.com/Uniswap/v4-core/blob/59d3ecf53afa9264a16bba0e38f4c5d2231f80bc/src/libraries/Hooks.sol
824        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            // This is a BalanceDelta subtraction
831            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        // Add hook gas costs to baseline swap cost.
844        // before_swap_gas / after_swap_gas capture the hook contract's internal
845        // logic. The hook's pool_manager_call_overhead accounts for the pool
846        // manager's dispatch wrapper that is not captured by either the native swap
847        // constants or the hook's own estimates.
848        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            // Check if pool has no liquidity & ticks -> hook manages liquidity
871            if self.liquidity == 0 && self.has_no_initialized_ticks() {
872                // If the hook has a get_amount_ranges entrypoint, call it and return (0, limits[1])
873                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                    // Check if hook get_amount_ranges is not implemented or the limits entrypoint
881                    // is not set for this hook
882                    Err(SimulationError::RecoverableError(msg))
883                        if msg.contains("not implemented") || msg.contains("not set") =>
884                    {
885                        // Hook manages liquidity but doesn't have get_amount_ranges
886                        // Use binary search to find limits by calling swap with increasing amounts
887                        return self.find_limits_experimentally(token_in, token_out);
888                        // Otherwise fall back to default implementation
889                    }
890                    Err(e) => return Err(e),
891                }
892            }
893        }
894
895        // If the pool has no liquidity, return zeros for both limits
896        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        // Iterate through ticks in the direction of the swap
909        // Stops when: no more liquidity, no more ticks, or gas limit would be exceeded
910        while let Ok((tick, next_tick_info)) = self
911            .ticks
912            .next_initialized_tick_within_one_word(current_tick, zero_for_one)
913        {
914            // Cap iteration to prevent exceeding Ethereum's gas limit
915            if ticks_crossed >= MAX_TICKS_CROSSED {
916                break;
917            }
918            ticks_crossed += 1;
919
920            // Clamp the tick value to ensure it's within valid range
921            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            // Calculate the amount of tokens swapped when moving from current_sqrt_price to
929            // sqrt_price_next. Direction determines which token is being swapped in vs out
930            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            // Accumulate total amounts for this tick range
961            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 this tick is "initialized" (meaning its someone's position boundary), update the
965            // liquidity when crossing it
966            // For zero_for_one, liquidity is removed when crossing a tick
967            // For one_for_zero, liquidity is added when crossing a tick
968            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                // Check if applying this liquidity delta would cause underflow
973                // If so, stop here rather than continuing with invalid state
974                match liquidity_math::add_liquidity_delta(current_liquidity, liquidity_delta) {
975                    Ok(new_liquidity) => {
976                        current_liquidity = new_liquidity;
977                    }
978                    Err(_) => {
979                        // Liquidity would underflow, stop iteration here
980                        // This represents the maximum liquidity we can actually use
981                        break;
982                    }
983                }
984            }
985
986            // Move to the next tick position
987            current_tick = if zero_for_one { next_tick - 1 } else { next_tick };
988            current_sqrt_price = sqrt_price_next;
989
990            // If we've consumed all liquidity, no point continuing the loop
991            if current_liquidity == 0 {
992                break;
993            }
994        }
995
996        // A hook that charges the output reduces what a swapper can actually receive, so the
997        // limit has to be reported net of its cut.
998        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        // Swap steps taken from the old state do not hold for the new one.
1014        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                    // Fall back to default implementation
1022                }
1023                Err(e) => return Err(e),
1024            }
1025        }
1026
1027        // Apply attribute changes
1028        if let Some(liquidity) = delta
1029            .updated_attributes
1030            .get("liquidity")
1031        {
1032            self.liquidity = u128::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::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::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::from(one2zero_protocol_fee.clone());
1057        }
1058
1059        // apply tick changes
1060        for (key, value) in delta.updated_attributes.iter() {
1061            // tick liquidity keys are in the format "ticks/{tick_index}/net_liquidity"
1062            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::from(value.clone()),
1070                    )
1071                    .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
1072            }
1073        }
1074        // delete ticks - ignores deletes for attributes other than tick liquidity
1075        for key in delta.deleted_attributes.iter() {
1076            // tick liquidity keys are in the format "ticks/{tick_index}/net_liquidity"
1077            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    /// See [`ProtocolSim::query_pool_swap`] for the trait documentation.
1094    ///
1095    /// This method uses Uniswap V4 internal swap logic by swapping an infinite amount of token_in
1096    /// until the target price is reached. Takes into account V4-specific features like protocol
1097    /// fees and dynamic LP fees.
1098    ///
1099    /// Note: This implementation does not invoke hooks, as it is a query-only operation meant to
1100    /// determine available liquidity at a given price without executing an actual swap. It only
1101    /// asks the hook whether swaps are enabled, and returns `InvalidInput` when they are not.
1102    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        // Calculate total fee (protocol + LP fee) for V4
1116        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                    &params.token_in().address,
1140                    &params.token_out().address,
1141                    target,
1142                    fee_pips,
1143                    Sign::Negative, // V4 uses negative for exact input
1144                    |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    /// Forwards the execution block to the pool's hook, the only part of a V4 pool whose quoting
1161    /// can depend on it. Re-emits the pool exactly when the hook says its behavior changed.
1162    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    // Helper methods to create commonly used tokens
1234    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 test_delta_transition() {
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
1306        let attributes: HashMap<String, Bytes> = [
1307            ("liquidity".to_string(), Bytes::from(2000_u64.to_be_bytes().to_vec())),
1308            ("sqrt_price_x96".to_string(), Bytes::from(1001_u64.to_be_bytes().to_vec())),
1309            ("tick".to_string(), Bytes::from(120_i32.to_be_bytes().to_vec())),
1310            ("protocol_fees/zero2one".to_string(), Bytes::from(50_u32.to_be_bytes().to_vec())),
1311            ("protocol_fees/one2zero".to_string(), Bytes::from(75_u32.to_be_bytes().to_vec())),
1312            ("fee".to_string(), Bytes::from(100_u32.to_be_bytes().to_vec())),
1313            ("ticks/-120/net_liquidity".to_string(), Bytes::from(10200_u64.to_be_bytes().to_vec())),
1314            ("ticks/120/net_liquidity".to_string(), Bytes::from(9800_u64.to_be_bytes().to_vec())),
1315            ("block_number".to_string(), Bytes::from(2000_u64.to_be_bytes().to_vec())),
1316            ("block_timestamp".to_string(), Bytes::from(1758201935_u64.to_be_bytes().to_vec())),
1317        ]
1318        .into_iter()
1319        .collect();
1320
1321        let delta = ProtocolStateDelta {
1322            component_id: "State1".to_owned(),
1323            updated_attributes: attributes,
1324            deleted_attributes: HashSet::new(),
1325        };
1326
1327        pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1328            .unwrap();
1329
1330        assert_eq!(pool.liquidity, 2000);
1331        assert_eq!(pool.sqrt_price, U256::from(1001));
1332        assert_eq!(pool.tick.value(), 120);
1333        assert_eq!(pool.fees.zero_for_one, 50);
1334        assert_eq!(pool.fees.one_for_zero, 75);
1335        assert_eq!(pool.fees.lp_fee, 100);
1336        assert_eq!(
1337            pool.ticks
1338                .get_tick(-120)
1339                .unwrap()
1340                .net_liquidity,
1341            10200
1342        );
1343        assert_eq!(
1344            pool.ticks
1345                .get_tick(120)
1346                .unwrap()
1347                .net_liquidity,
1348            9800
1349        );
1350    }
1351
1352    #[tokio::test]
1353    /// Compares a quote from the UniswapV4 Quoter contract on Sepolia with a simulation.
1354    async fn test_swap_sim() {
1355        use tycho_client::feed::dto;
1356        let project_root = env!("CARGO_MANIFEST_DIR");
1357        let asset_path = Path::new(project_root)
1358            .join("tests/assets/decoder/uniswap_v4_snapshot_sepolia_block_7239119.json");
1359        let json_data = fs::read_to_string(asset_path).expect("Failed to read test asset");
1360        let data: Value = serde_json::from_str(&json_data).expect("Failed to parse JSON");
1361        let state: ComponentWithState = serde_json::from_value::<dto::ComponentWithState>(data)
1362            .expect("Expected json to match ComponentWithState structure")
1363            .into();
1364
1365        let block = BlockHeader {
1366            number: 7239119,
1367            hash: Bytes::from_str(
1368                "0x28d41d40f2ac275a4f5f621a636b9016b527d11d37d610a45ac3a821346ebf8c",
1369            )
1370            .expect("Invalid block hash"),
1371            parent_hash: Bytes::from(vec![0; 32]),
1372            ..Default::default()
1373        };
1374
1375        let t0 = Token::new(
1376            &Bytes::from_str("0x647e32181a64f4ffd4f0b0b4b052ec05b277729c").unwrap(),
1377            "T0",
1378            18,
1379            0,
1380            &[Some(10_000)],
1381            Chain::Ethereum,
1382            100,
1383        );
1384        let t1 = Token::new(
1385            &Bytes::from_str("0xe390a1c311b26f14ed0d55d3b0261c2320d15ca5").unwrap(),
1386            "T1",
1387            18,
1388            0,
1389            &[Some(10_000)],
1390            Chain::Ethereum,
1391            100,
1392        );
1393
1394        let all_tokens = [t0.clone(), t1.clone()]
1395            .iter()
1396            .map(|t| (t.address.clone(), t.clone()))
1397            .collect();
1398
1399        let usv4_state = UniswapV4State::try_from_with_header(
1400            state,
1401            block,
1402            &Default::default(),
1403            &all_tokens,
1404            &DecoderContext::new(),
1405        )
1406        .await
1407        .unwrap();
1408
1409        // The fixture's `hooks` attribute is the zero address, so this is a plain V4 pool and
1410        // needs no chain to decode.
1411        assert!(usv4_state.hook.is_none());
1412
1413        let res = usv4_state
1414            .get_amount_out(BigUint::from_u64(1000000000000000000).unwrap(), &t0, &t1)
1415            .unwrap();
1416
1417        let expected_amount = BigUint::from(9999909699895_u64);
1418        assert_eq!(res.amount, expected_amount);
1419    }
1420
1421    #[tokio::test]
1422    async fn test_get_limits() {
1423        use tycho_client::feed::dto;
1424        let block = BlockHeader {
1425            number: 22689129,
1426            hash: Bytes::from_str(
1427                "0x7763ea30d11aef68da729b65250c09a88ad00458c041064aad8c9a9dbf17adde",
1428            )
1429            .expect("Invalid block hash"),
1430            parent_hash: Bytes::from(vec![0; 32]),
1431            ..Default::default()
1432        };
1433
1434        let project_root = env!("CARGO_MANIFEST_DIR");
1435        let asset_path =
1436            Path::new(project_root).join("tests/assets/decoder/uniswap_v4_snapshot.json");
1437        let json_data = fs::read_to_string(asset_path).expect("Failed to read test asset");
1438        let data: Value = serde_json::from_str(&json_data).expect("Failed to parse JSON");
1439        let state: ComponentWithState = serde_json::from_value::<dto::ComponentWithState>(data)
1440            .expect("Expected json to match ComponentWithState structure")
1441            .into();
1442
1443        let t0 = Token::new(
1444            &Bytes::from_str("0x2260fac5e5542a773aa44fbcfedf7c193bc2c599").unwrap(),
1445            "WBTC",
1446            8,
1447            0,
1448            &[Some(10_000)],
1449            Chain::Ethereum,
1450            100,
1451        );
1452        let t1 = Token::new(
1453            &Bytes::from_str("0xdac17f958d2ee523a2206206994597c13d831ec7").unwrap(),
1454            "USDT",
1455            6,
1456            0,
1457            &[Some(10_000)],
1458            Chain::Ethereum,
1459            100,
1460        );
1461
1462        let all_tokens = [t0.clone(), t1.clone()]
1463            .iter()
1464            .map(|t| (t.address.clone(), t.clone()))
1465            .collect();
1466
1467        let usv4_state = UniswapV4State::try_from_with_header(
1468            state,
1469            block,
1470            &Default::default(),
1471            &all_tokens,
1472            &DecoderContext::new(),
1473        )
1474        .await
1475        .unwrap();
1476
1477        // The fixture's `hooks` attribute is the zero address, so this is a plain V4 pool and
1478        // needs no chain to decode.
1479        assert!(usv4_state.hook.is_none());
1480
1481        let res = usv4_state
1482            .get_limits(t0.address.clone(), t1.address.clone())
1483            .unwrap();
1484
1485        assert_eq!(&res.0, &BigUint::from_u128(71698353688830259750744466706).unwrap());
1486
1487        let out = usv4_state
1488            .get_amount_out(res.0, &t0, &t1)
1489            .expect("swap for limit in didn't work");
1490
1491        assert_eq!(&res.1, &out.amount);
1492    }
1493    /// The hook calls a quote made, each with the overrides it ran under.
1494    type SeenCalls = Vec<(&'static str, Option<PendingOverrides>)>;
1495
1496    /// A hook whose beforeSwap fee is whatever the pending block wrote to its slot 0, and
1497    /// which records the overrides each call ran under.
1498    #[derive(Debug, Clone)]
1499    struct ConfigurableFeeHook {
1500        address: Address,
1501        pending_overrides: Option<Arc<PendingOverrides>>,
1502        seen: Arc<std::sync::Mutex<SeenCalls>>,
1503    }
1504
1505    impl ConfigurableFeeHook {
1506        /// Low address bits are the permission flags: bit 7 beforeSwap, bit 6 afterSwap.
1507        fn new() -> Self {
1508            let mut address = [0u8; 20];
1509            address[19] = 0xC0;
1510            Self {
1511                address: Address::from_slice(&address),
1512                pending_overrides: None,
1513                seen: Arc::default(),
1514            }
1515        }
1516
1517        fn pending_fee(&self) -> U256 {
1518            self.pending_overrides
1519                .as_ref()
1520                .and_then(|p| p.storage.as_ref())
1521                .and_then(|storage| storage.get(&self.address))
1522                .and_then(|slots| slots.get(&U256::ZERO))
1523                .copied()
1524                .unwrap_or(U256::ZERO)
1525        }
1526    }
1527
1528    impl HookHandler for ConfigurableFeeHook {
1529        fn address(&self) -> Address {
1530            self.address
1531        }
1532
1533        fn before_swap(
1534            &self,
1535            _params: BeforeSwapParameters,
1536            _overwrites: Option<HashMap<Address, HashMap<U256, U256>>>,
1537            _transient_storage: Option<HashMap<Address, HashMap<U256, U256>>>,
1538        ) -> Result<WithGasEstimate<BeforeSwapOutput>, SimulationError> {
1539            self.seen.lock().unwrap().push((
1540                "before",
1541                self.pending_overrides
1542                    .as_deref()
1543                    .cloned(),
1544            ));
1545            Ok(WithGasEstimate {
1546                gas_estimate: 0,
1547                result: BeforeSwapOutput {
1548                    amount_delta: BeforeSwapDelta(I256::ZERO),
1549                    fee: U24::from(self.pending_fee()),
1550                    overwrites: HashMap::new(),
1551                    transient_storage: HashMap::new(),
1552                },
1553            })
1554        }
1555
1556        fn after_swap(
1557            &self,
1558            _params: AfterSwapParameters,
1559            _overwrites: Option<HashMap<Address, HashMap<U256, U256>>>,
1560            _transient_storage_params: Option<HashMap<Address, HashMap<U256, U256>>>,
1561        ) -> Result<WithGasEstimate<AfterSwapDelta>, SimulationError> {
1562            self.seen.lock().unwrap().push((
1563                "after",
1564                self.pending_overrides
1565                    .as_deref()
1566                    .cloned(),
1567            ));
1568            Ok(WithGasEstimate { gas_estimate: 0, result: I128::ZERO })
1569        }
1570
1571        fn fee(
1572            &self,
1573            _context: &UniswapV4State,
1574            _params: SwapParams,
1575        ) -> Result<f64, SimulationError> {
1576            Ok(0.0)
1577        }
1578
1579        fn spot_price(&self, _base: &Token, _quote: &Token) -> Result<f64, SimulationError> {
1580            Err(SimulationError::RecoverableError("not implemented".into()))
1581        }
1582
1583        fn get_amount_ranges(
1584            &self,
1585            _token_in: Bytes,
1586            _token_out: Bytes,
1587        ) -> Result<AmountRanges, SimulationError> {
1588            Err(SimulationError::RecoverableError("not implemented".into()))
1589        }
1590
1591        fn set_pending_overrides(&mut self, overrides: Arc<PendingOverrides>) {
1592            self.pending_overrides = Some(overrides);
1593        }
1594
1595        fn delta_transition(
1596            &mut self,
1597            _delta: ProtocolStateDelta,
1598            _tokens: &HashMap<Bytes, Token>,
1599            _balances: &Balances,
1600        ) -> Result<(), TransitionError> {
1601            Ok(())
1602        }
1603
1604        fn clone_box(&self) -> Box<dyn HookHandler> {
1605            Box::new(self.clone())
1606        }
1607
1608        fn as_any(&self) -> &dyn Any {
1609            self
1610        }
1611
1612        fn is_equal(&self, other: &dyn HookHandler) -> bool {
1613            other
1614                .as_any()
1615                .downcast_ref::<Self>()
1616                .is_some_and(|o| o.address == self.address)
1617        }
1618    }
1619
1620    /// A pool at price one with liquidity on both sides of the current tick.
1621    fn hooked_pool(hook: &ConfigurableFeeHook) -> UniswapV4State {
1622        let liquidity = 1_000_000_000_000_000_000u128;
1623        let mut pool = UniswapV4State::new(
1624            liquidity,
1625            U256::from(1u8) << 96,
1626            UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: lp_fee::DYNAMIC_FEE_FLAG },
1627            0,
1628            60,
1629            vec![
1630                TickInfo::new(-60, liquidity as i128).unwrap(),
1631                TickInfo::new(60, -(liquidity as i128)).unwrap(),
1632            ],
1633        )
1634        .unwrap();
1635        pool.set_hook_handler(Box::new(hook.clone()));
1636        pool
1637    }
1638
1639    fn pending_fee_update(hook: &ConfigurableFeeHook, fee_pips: u64) -> PendingOverrides {
1640        PendingOverrides {
1641            storage: Some(HashMap::from([(
1642                hook.address,
1643                HashMap::from([(U256::ZERO, U256::from(fee_pips))]),
1644            )])),
1645            native_balances: None,
1646            block: None,
1647        }
1648    }
1649
1650    #[test]
1651    fn test_pending_overrides_reach_both_hook_calls_and_change_the_quote() {
1652        let hook = ConfigurableFeeHook::new();
1653        let amount_in = BigUint::from(1_000_000u64);
1654
1655        let confirmed = hooked_pool(&hook)
1656            .get_amount_out(amount_in.clone(), &token_x(), &token_y())
1657            .unwrap();
1658        let mut pool = hooked_pool(&hook);
1659        pool.set_pending_overrides(Arc::new(pending_fee_update(&hook, 100_000)))
1660            .unwrap();
1661        let pending = pool
1662            .get_amount_out(amount_in, &token_x(), &token_y())
1663            .unwrap();
1664
1665        assert!(
1666            pending.amount < confirmed.amount,
1667            "a 10% fee the pending block wrote must cut the output: {} vs {}",
1668            pending.amount,
1669            confirmed.amount
1670        );
1671        let seen = hook.seen.lock().unwrap();
1672        let calls: Vec<(&str, bool)> = seen
1673            .iter()
1674            .map(|(call, pending)| {
1675                (
1676                    *call,
1677                    pending
1678                        .as_ref()
1679                        .is_some_and(|p| p.storage.is_some()),
1680                )
1681            })
1682            .collect();
1683        assert_eq!(
1684            calls,
1685            vec![("before", false), ("after", false), ("before", true), ("after", true)],
1686            "the confirmed quote runs both calls without overrides, the pending one with them"
1687        );
1688    }
1689
1690    #[test]
1691    fn test_pending_overrides_survive_clone_box() {
1692        let hook = ConfigurableFeeHook::new();
1693        let mut pool = hooked_pool(&hook);
1694        pool.set_pending_overrides(Arc::new(pending_fee_update(&hook, 1)))
1695            .unwrap();
1696
1697        let cloned = pool.clone_box();
1698        let cloned = cloned
1699            .as_any()
1700            .downcast_ref::<UniswapV4State>()
1701            .unwrap();
1702
1703        assert!(cloned.pending_overrides().is_some(), "a clone quotes under the same overrides");
1704    }
1705
1706    #[test]
1707    fn test_set_pending_overrides_rejects_another_payload_type() {
1708        let hook = ConfigurableFeeHook::new();
1709        let mut pool = hooked_pool(&hook);
1710
1711        let result = pool.set_pending_overrides(Arc::new(0u8));
1712
1713        assert!(matches!(result, Err(SimulationError::FatalError(_))));
1714        assert!(pool.pending_overrides().is_none(), "a rejected payload sets nothing");
1715        assert!(hook.seen.lock().unwrap().is_empty());
1716    }
1717
1718    #[test]
1719    fn test_pending_overrides_are_not_part_of_equality() {
1720        let hook = ConfigurableFeeHook::new();
1721        let confirmed = hooked_pool(&hook);
1722        let mut pending = hooked_pool(&hook);
1723        pending
1724            .set_pending_overrides(Arc::new(pending_fee_update(&hook, 1)))
1725            .unwrap();
1726
1727        assert!(confirmed == pending, "PartialEq ignores the overrides");
1728        assert!(ProtocolSim::eq(&confirmed, &pending), "ProtocolSim::eq ignores the overrides");
1729    }
1730
1731    #[test]
1732    fn test_get_amount_out_no_hook() {
1733        // Test using transaction 0x78ea4bbb7d4405000f33fdf6f3fa08b5e557d50e5e7f826a79766d50bd643b6f
1734
1735        // Pool ID: 0x00b9edc1583bf6ef09ff3a09f6c23ecb57fd7d0bb75625717ec81eed181e22d7
1736        // Information taken from Tenderly simulation / event emitted on Etherscan
1737        let usv4_state = UniswapV4State::new(
1738            541501951282951892,
1739            U256::from_str("5362798333066270795901222").unwrap(), // Sqrt price
1740            UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 100 },
1741            -192022,
1742            1,
1743            // Ticks taken from indexer logs
1744            vec![
1745                TickInfo {
1746                    index: -887272,
1747                    net_liquidity: 460382969070005,
1748                    sqrt_price: U256::from(4295128739_u64),
1749                },
1750                TickInfo {
1751                    index: -207244,
1752                    net_liquidity: 561268407024557,
1753                    sqrt_price: U256::from_str("2505291706254206075074035").unwrap(),
1754                },
1755                TickInfo {
1756                    index: -196411,
1757                    net_liquidity: 825711941800452,
1758                    sqrt_price: U256::from_str("4306080513146952705853399").unwrap(),
1759                },
1760                TickInfo {
1761                    index: -196257,
1762                    net_liquidity: 64844666874010,
1763                    sqrt_price: U256::from_str("4339363644587371378270009").unwrap(),
1764                },
1765                TickInfo {
1766                    index: -195611,
1767                    net_liquidity: 2344045150766798,
1768                    sqrt_price: U256::from_str("4481806029599743916020126").unwrap(),
1769                },
1770                TickInfo {
1771                    index: -194715,
1772                    net_liquidity: 391037380558274654,
1773                    sqrt_price: U256::from_str("4687145946111116896040494").unwrap(),
1774                },
1775                TickInfo {
1776                    index: -194599,
1777                    net_liquidity: 89032603464508,
1778                    sqrt_price: U256::from_str("4714409015946702405379370").unwrap(),
1779                },
1780                TickInfo {
1781                    index: -194389,
1782                    net_liquidity: 66635600426483168,
1783                    sqrt_price: U256::from_str("4764168603367683402636621").unwrap(),
1784                },
1785                TickInfo {
1786                    index: -194160,
1787                    net_liquidity: 6123093436523361,
1788                    sqrt_price: U256::from_str("4819029067726467394386780").unwrap(),
1789                },
1790                TickInfo {
1791                    index: -194025,
1792                    net_liquidity: 79940813798964,
1793                    sqrt_price: U256::from_str("4851665907541490407930032").unwrap(),
1794                },
1795                TickInfo {
1796                    index: -193922,
1797                    net_liquidity: 415630967437234,
1798                    sqrt_price: U256::from_str("4876715181040466809166531").unwrap(),
1799                },
1800                TickInfo {
1801                    index: -193876,
1802                    net_liquidity: 9664144015186047,
1803                    sqrt_price: U256::from_str("4887943972687250473582419").unwrap(),
1804                },
1805                TickInfo {
1806                    index: -193818,
1807                    net_liquidity: 435344726052344,
1808                    sqrt_price: U256::from_str("4902138873132735049121973").unwrap(),
1809                },
1810                TickInfo {
1811                    index: -193804,
1812                    net_liquidity: 221726179374067,
1813                    sqrt_price: U256::from_str("4905571399964683340605904").unwrap(),
1814                },
1815                TickInfo {
1816                    index: -193719,
1817                    net_liquidity: 101340835774487,
1818                    sqrt_price: U256::from_str("4926463397882393957462188").unwrap(),
1819                },
1820                TickInfo {
1821                    index: -193690,
1822                    net_liquidity: 193367475630077,
1823                    sqrt_price: U256::from_str("4933611593595025190448924").unwrap(),
1824                },
1825                TickInfo {
1826                    index: -193643,
1827                    net_liquidity: 357016631583746,
1828                    sqrt_price: U256::from_str("4945218633428068823432932").unwrap(),
1829                },
1830                TickInfo {
1831                    index: -193520,
1832                    net_liquidity: 917243184365178,
1833                    sqrt_price: U256::from_str("4975723910367862081017120").unwrap(),
1834                },
1835                TickInfo {
1836                    index: -193440,
1837                    net_liquidity: 114125890211958292,
1838                    sqrt_price: U256::from_str("4995665665861492533686137").unwrap(),
1839                },
1840                TickInfo {
1841                    index: -193380,
1842                    net_liquidity: -65980729148766579,
1843                    sqrt_price: U256::from_str("5010674414300823856025303").unwrap(),
1844                },
1845                TickInfo {
1846                    index: -192891,
1847                    net_liquidity: 1687883551433195,
1848                    sqrt_price: U256::from_str("5134689105039642314202223").unwrap(),
1849                },
1850                TickInfo {
1851                    index: -192573,
1852                    net_liquidity: 11108903221360975,
1853                    sqrt_price: U256::from_str("5216979018647067786855495").unwrap(),
1854                },
1855                TickInfo {
1856                    index: -192448,
1857                    net_liquidity: 32888457482352,
1858                    sqrt_price: U256::from_str("5249685603828944002327927").unwrap(),
1859                },
1860                TickInfo {
1861                    index: -191525,
1862                    net_liquidity: -221726179374067,
1863                    sqrt_price: U256::from_str("5497623359964843320146512").unwrap(),
1864                },
1865                TickInfo {
1866                    index: -191447,
1867                    net_liquidity: -32888457482352,
1868                    sqrt_price: U256::from_str("5519104878745833608097296").unwrap(),
1869                },
1870                TickInfo {
1871                    index: -191444,
1872                    net_liquidity: -114125890211958292,
1873                    sqrt_price: U256::from_str("5519932765173943847315221").unwrap(),
1874                },
1875                TickInfo {
1876                    index: -191417,
1877                    net_liquidity: -101340835774487,
1878                    sqrt_price: U256::from_str("5527389333636021285046380").unwrap(),
1879                },
1880                TickInfo {
1881                    index: -191384,
1882                    net_liquidity: -9664144015186047,
1883                    sqrt_price: U256::from_str("5536516597603056457376182").unwrap(),
1884                },
1885                TickInfo {
1886                    index: -191148,
1887                    net_liquidity: -561268407024557,
1888                    sqrt_price: U256::from_str("5602231161238705865493165").unwrap(),
1889                },
1890                TickInfo {
1891                    index: -191147,
1892                    net_liquidity: -1687883551433195,
1893                    sqrt_price: U256::from_str("5602511265794328966803451").unwrap(),
1894                },
1895                TickInfo {
1896                    index: -191091,
1897                    net_liquidity: -89032603464508,
1898                    sqrt_price: U256::from_str("5618219493196441347292357").unwrap(),
1899                },
1900                TickInfo {
1901                    index: -190950,
1902                    net_liquidity: -189177935487638,
1903                    sqrt_price: U256::from_str("5657965894785859782969011").unwrap(),
1904                },
1905                TickInfo {
1906                    index: -190756,
1907                    net_liquidity: -6123093436523361,
1908                    sqrt_price: U256::from_str("5713112435031881967192022").unwrap(),
1909                },
1910                TickInfo {
1911                    index: -190548,
1912                    net_liquidity: -193367475630077,
1913                    sqrt_price: U256::from_str("5772835841671084402427710").unwrap(),
1914                },
1915                TickInfo {
1916                    index: -190430,
1917                    net_liquidity: -11108903221360975,
1918                    sqrt_price: U256::from_str("5806994534290341208820930").unwrap(),
1919                },
1920                TickInfo {
1921                    index: -190195,
1922                    net_liquidity: -391583014714302569,
1923                    sqrt_price: U256::from_str("5875625707132601785181387").unwrap(),
1924                },
1925                TickInfo {
1926                    index: -190043,
1927                    net_liquidity: -357016631583746,
1928                    sqrt_price: U256::from_str("5920448331650864936739481").unwrap(),
1929                },
1930                TickInfo {
1931                    index: -189779,
1932                    net_liquidity: -917243184365178,
1933                    sqrt_price: U256::from_str("5999112356918485175181346").unwrap(),
1934                },
1935                TickInfo {
1936                    index: -189663,
1937                    net_liquidity: -2344045150766798,
1938                    sqrt_price: U256::from_str("6034006559279282606084981").unwrap(),
1939                },
1940                TickInfo {
1941                    index: -189620,
1942                    net_liquidity: -435344726052344,
1943                    sqrt_price: U256::from_str("6046992979471024289177519").unwrap(),
1944                },
1945                TickInfo {
1946                    index: -189409,
1947                    net_liquidity: -825711941800452,
1948                    sqrt_price: U256::from_str("6111123241285165242130911").unwrap(),
1949                },
1950                TickInfo {
1951                    index: -189325,
1952                    net_liquidity: -3947182209207,
1953                    sqrt_price: U256::from_str("6136842645893819031257990").unwrap(),
1954                },
1955                TickInfo {
1956                    index: -189324,
1957                    net_liquidity: -415630967437234,
1958                    sqrt_price: U256::from_str("6137149480355443943537284").unwrap(),
1959                },
1960                TickInfo {
1961                    index: -115136,
1962                    net_liquidity: 462452451821,
1963                    sqrt_price: U256::from_str("250529060232794967902094762").unwrap(),
1964                },
1965                TickInfo {
1966                    index: -92109,
1967                    net_liquidity: -462452451821,
1968                    sqrt_price: U256::from_str("792242363124136400178523925").unwrap(),
1969                },
1970                TickInfo {
1971                    index: 887272,
1972                    net_liquidity: -521280453734808,
1973                    sqrt_price: U256::from_str("1461446703485210103287273052203988822378723970342")
1974                        .unwrap(),
1975                },
1976            ],
1977        )
1978        .unwrap();
1979
1980        let t0 = usdc();
1981        let t1 = eth();
1982
1983        let out = usv4_state
1984            .get_amount_out(BigUint::from_u64(2000000).unwrap(), &t0, &t1)
1985            .unwrap();
1986
1987        assert_eq!(out.amount, BigUint::from_str("436478419853848").unwrap())
1988    }
1989
1990    #[test]
1991    fn test_get_amount_out_euler_hook() {
1992        // Test using transaction 0xb372306a81c6e840f4ec55f006da6b0b097f435802a2e6fd216998dd12fb4aca
1993        //
1994        // Output of beforeSwap:
1995        // "output":{
1996        //      "amountToSwap":"0"
1997        //      "hookReturn":"2520471492123673565794154180707800634502860978735"
1998        //      "lpFeeOverride":"0"
1999        // }
2000        //
2001        // Output of entire swap, including hooks:
2002        // "swapDelta":"-2520471491783391198873215717244426027071092767279"
2003        //
2004        // Get amount out:
2005        // "amountOut":"2681115183499232721"
2006
2007        let block = BlockHeader {
2008            number: 22689128,
2009            hash: Bytes::from_str(
2010                "0xfbfa716523d25d6d5248c18d001ca02b1caf10cabd1ab7321465e2262c41157b",
2011            )
2012            .expect("Invalid block hash"),
2013            timestamp: 1749739055,
2014            ..Default::default()
2015        };
2016
2017        // Pool ID: 0xdd8dd509e58ec98631b800dd6ba86ee569c517ffbd615853ed5ab815bbc48ccb
2018        // Information taken from Tenderly simulation
2019        let mut usv4_state = UniswapV4State::new(
2020            0,
2021            U256::from_str("4295128740").unwrap(),
2022            UniswapV4Fees { zero_for_one: 100, one_for_zero: 90, lp_fee: 500 },
2023            0,
2024            1,
2025            vec![],
2026        )
2027        .unwrap();
2028
2029        let hook_address: Address = Address::from_str("0x69058613588536167ba0aa94f0cc1fe420ef28a8")
2030            .expect("Invalid hook address");
2031
2032        let db = SimulationDB::new(
2033            get_client(None).expect("Failed to create client"),
2034            get_runtime().expect("Failed to get runtime"),
2035            Some(block.clone()),
2036        );
2037        let engine = create_engine(db, true).expect("Failed to create simulation engine");
2038        let pool_manager = Address::from_str("0x000000000004444c5dc75cb358380d2e3de08a90")
2039            .expect("Invalid pool manager address");
2040
2041        let hook_handler = GenericVMHookHandler::new(
2042            hook_address,
2043            engine,
2044            pool_manager,
2045            HashMap::new(),
2046            HashMap::new(),
2047            None,
2048            true, // Euler hook
2049        )
2050        .unwrap();
2051
2052        let t0 = usdc();
2053        let t1 = weth();
2054
2055        usv4_state.set_hook_handler(Box::new(hook_handler));
2056        let out = usv4_state
2057            .get_amount_out(BigUint::from_u64(7407000000).unwrap(), &t0, &t1)
2058            .unwrap();
2059
2060        assert_eq!(out.amount, BigUint::from_str("2681115183499232721").unwrap())
2061    }
2062
2063    #[test]
2064    fn test_get_amount_out_angstrom_hook() {
2065        // Test using transaction 0x671b8e1d0966cee520dc2bb9628de8e22a17b036e70077504796d0a476932d21
2066        let mut usv4_state = UniswapV4State::new(
2067            // Liquidity and tick taken from tycho indexer for same block as transaction
2068            66319800403673162,
2069            U256::from_str("1314588940601923011323000261788004").unwrap(),
2070            // 8388608 (i.e. 0x800000) signifies a dynamic fee.
2071            UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 8388608 },
2072            194343,
2073            10,
2074            vec![
2075                TickInfo::new(-887270, 198117767801).unwrap(),
2076                TickInfo::new(191990, 24561988698695).unwrap(),
2077                TickInfo::new(192280, 2839631428751224).unwrap(),
2078                TickInfo::new(193130, 318786492813931).unwrap(),
2079                TickInfo::new(194010, 26209207141081).unwrap(),
2080                TickInfo::new(194210, -26209207141081).unwrap(),
2081                TickInfo::new(194220, 63136622375641511).unwrap(),
2082                TickInfo::new(194420, -63136622375641511).unwrap(),
2083                TickInfo::new(195130, -318786492813931).unwrap(),
2084                TickInfo::new(196330, -2839631428751224).unwrap(),
2085                TickInfo::new(197100, -24561988698695).unwrap(),
2086                TickInfo::new(887270, -198117767801).unwrap(),
2087            ],
2088        )
2089        .unwrap();
2090
2091        let fees = AngstromFees {
2092            // To get these values, enable storage access logs on tenderly,
2093            // and look at the hex value retrieved right after calling afterSwap
2094            //
2095            // The value (hex: 0x70000152) contains two packed uint24 values:
2096            // Lower 24 bits (unlockedFee):         0x152   = 338
2097            // Upper 24 bits (protocolUnlockedFee): 0x70    = 112
2098            unlock: U24::from(338),
2099            protocol_unlock: U24::from(112),
2100        };
2101        let hook_handler = AngstromHookHandler::new(
2102            Address::from_str("0x0000000aa232009084bd71a5797d089aa4edfad4").unwrap(),
2103            Address::from_str("0x000000000004444c5dc75cb358380d2e3de08a90").unwrap(),
2104            fees,
2105            false,
2106        );
2107
2108        let t0 = usdc();
2109        let t1 = weth();
2110
2111        usv4_state.set_hook_handler(Box::new(hook_handler));
2112        let out = usv4_state
2113            .get_amount_out(
2114                BigUint::from_u64(
2115                    6645198144, // usdc
2116                )
2117                .unwrap(),
2118                &t0, // usdc IN
2119                &t1, // weth OUT
2120            )
2121            .unwrap();
2122
2123        assert_eq!(out.amount, BigUint::from_str("1825627051870330472").unwrap())
2124    }
2125
2126    /// Hook that only answers `after_swap`, with a configurable address and returned delta.
2127    #[derive(Debug, Clone, PartialEq, Eq)]
2128    struct AfterSwapTestHook {
2129        address: Address,
2130        delta: I128,
2131        /// Share of the output the hook reports analytically, in basis points. `None` models a
2132        /// hook that cannot price its fee without a simulation.
2133        analytic_fee_bps: Option<u32>,
2134        /// Price the hook answers `spot_price` with. `None` models a hook that leaves the price
2135        /// to the pool by failing recoverably.
2136        spot_price_override: Option<u64>,
2137    }
2138
2139    impl HookHandler for AfterSwapTestHook {
2140        fn address(&self) -> Address {
2141            self.address
2142        }
2143
2144        fn before_swap(
2145            &self,
2146            _: BeforeSwapParameters,
2147            _: Option<HashMap<Address, HashMap<U256, U256>>>,
2148            _: Option<HashMap<Address, HashMap<U256, U256>>>,
2149        ) -> Result<WithGasEstimate<BeforeSwapOutput>, SimulationError> {
2150            Err(SimulationError::RecoverableError("not implemented".into()))
2151        }
2152
2153        fn after_swap(
2154            &self,
2155            _: AfterSwapParameters,
2156            _: Option<HashMap<Address, HashMap<U256, U256>>>,
2157            _: Option<HashMap<Address, HashMap<U256, U256>>>,
2158        ) -> Result<WithGasEstimate<AfterSwapDelta>, SimulationError> {
2159            Ok(WithGasEstimate { gas_estimate: AFTER_SWAP_TEST_HOOK_GAS, result: self.delta })
2160        }
2161
2162        fn fee(&self, _: &UniswapV4State, _: SwapParams) -> Result<f64, SimulationError> {
2163            Err(SimulationError::RecoverableError("not implemented".into()))
2164        }
2165
2166        fn spot_price(&self, _: &Token, _: &Token) -> Result<f64, SimulationError> {
2167            match self.spot_price_override {
2168                Some(price) => Ok(price as f64),
2169                None => Err(SimulationError::RecoverableError("not implemented".into())),
2170            }
2171        }
2172
2173        fn unspecified_fee_amount(
2174            &self,
2175            unspecified: U256,
2176            _: bool,
2177        ) -> Result<Option<U256>, SimulationError> {
2178            let Some(bps) = self.analytic_fee_bps else { return Ok(None) };
2179            Ok(Some(unspecified * U256::from(bps) / U256::from(10_000u64)))
2180        }
2181
2182        fn get_amount_ranges(&self, _: Bytes, _: Bytes) -> Result<AmountRanges, SimulationError> {
2183            Err(SimulationError::RecoverableError("not implemented".into()))
2184        }
2185
2186        fn delta_transition(
2187            &mut self,
2188            _: ProtocolStateDelta,
2189            _: &HashMap<Bytes, Token>,
2190            _: &Balances,
2191        ) -> Result<(), TransitionError> {
2192            Ok(())
2193        }
2194
2195        fn clone_box(&self) -> Box<dyn HookHandler> {
2196            Box::new(self.clone())
2197        }
2198
2199        fn as_any(&self) -> &dyn Any {
2200            self
2201        }
2202
2203        fn is_equal(&self, other: &dyn HookHandler) -> bool {
2204            other.as_any().downcast_ref::<Self>() == Some(self)
2205        }
2206    }
2207
2208    // Deliberately different values: the gate tests below assert on a gas delta and on an amount
2209    // delta, and equal constants would let a mix-up between the two pass.
2210    const AFTER_SWAP_TEST_HOOK_GAS: u64 = 1_000;
2211    const AFTER_SWAP_TEST_HOOK_DELTA: u64 = 777;
2212
2213    fn construct_hook_address(hook_options: &[HookOptions]) -> Address {
2214        let mut hook_flags = U160::ZERO;
2215        let one = U160::from_limbs([1, 0, 0]);
2216        for hook_option in hook_options {
2217            hook_flags |= one << (*hook_option as u8);
2218        }
2219        Address::from(hook_flags)
2220    }
2221
2222    fn after_swap_test_hook(hook_options: &[HookOptions]) -> Box<dyn HookHandler> {
2223        Box::new(AfterSwapTestHook {
2224            address: construct_hook_address(hook_options),
2225            delta: I128::unchecked_from(AFTER_SWAP_TEST_HOOK_DELTA),
2226            analytic_fee_bps: None,
2227            spot_price_override: None,
2228        })
2229    }
2230
2231    /// A hook that prices its fee analytically as `analytic_fee_bps` of the output.
2232    fn analytic_fee_test_hook(analytic_fee_bps: u32) -> Box<dyn HookHandler> {
2233        Box::new(AfterSwapTestHook {
2234            address: construct_hook_address(&[
2235                HookOptions::AfterSwap,
2236                HookOptions::AfterSwapReturnsDelta,
2237            ]),
2238            delta: I128::ZERO,
2239            analytic_fee_bps: Some(analytic_fee_bps),
2240            spot_price_override: None,
2241        })
2242    }
2243
2244    /// The price a test hook answers `spot_price` with when it is asked for one. Far from any
2245    /// price the test pool could quote, so a test cannot confuse the two.
2246    const TEST_HOOK_SPOT_PRICE: u64 = 1_000_000;
2247
2248    /// A hook that answers `spot_price` with [`TEST_HOOK_SPOT_PRICE`], and prices its fee
2249    /// analytically when `analytic_fee_bps` is `Some`.
2250    fn pricing_test_hook(analytic_fee_bps: Option<u32>) -> Box<dyn HookHandler> {
2251        Box::new(AfterSwapTestHook {
2252            address: construct_hook_address(&[
2253                HookOptions::AfterSwap,
2254                HookOptions::AfterSwapReturnsDelta,
2255            ]),
2256            delta: I128::ZERO,
2257            analytic_fee_bps,
2258            spot_price_override: Some(TEST_HOOK_SPOT_PRICE),
2259        })
2260    }
2261
2262    fn basic_v4_test_pool_tokens(zero_for_one: bool) -> (Token, Token) {
2263        if zero_for_one {
2264            (token_x(), token_y())
2265        } else {
2266            (token_y(), token_x())
2267        }
2268    }
2269
2270    /// An `afterSwap` delta must be discarded unless the hook also carries
2271    /// `AfterSwapReturnsDelta`, mirroring `Hooks.afterSwap` in v4-core.
2272    #[rstest]
2273    #[case::zero_for_one(true)]
2274    #[case::one_for_zero(false)]
2275    fn test_after_swap_delta_ignored_without_returns_delta_permission(#[case] zero_for_one: bool) {
2276        let (token_in, token_out) = basic_v4_test_pool_tokens(zero_for_one);
2277        let amount_in = BigUint::from(1_000_000_000_000_000u64);
2278
2279        let hookless = create_basic_v4_test_pool()
2280            .get_amount_out(amount_in.clone(), &token_in, &token_out)
2281            .expect("hookless swap should succeed");
2282
2283        let mut pool = create_basic_v4_test_pool();
2284        pool.set_hook_handler(after_swap_test_hook(&[HookOptions::AfterSwap]));
2285        let gated = pool
2286            .get_amount_out(amount_in, &token_in, &token_out)
2287            .expect("gated swap should succeed");
2288
2289        assert_eq!(gated.amount, hookless.amount);
2290        assert_eq!(
2291            gated.gas,
2292            hookless.gas + BigUint::from(AFTER_SWAP_TEST_HOOK_GAS + PM_PER_HOOK_CALL_OVERHEAD)
2293        );
2294    }
2295
2296    /// With `AfterSwapReturnsDelta` set, the returned delta is taken out of the unspecified
2297    /// (output) currency.
2298    #[rstest]
2299    #[case::zero_for_one(true)]
2300    #[case::one_for_zero(false)]
2301    fn test_after_swap_delta_applied_with_returns_delta_permission(#[case] zero_for_one: bool) {
2302        let (token_in, token_out) = basic_v4_test_pool_tokens(zero_for_one);
2303        let amount_in = BigUint::from(1_000_000_000_000_000u64);
2304
2305        let hookless = create_basic_v4_test_pool()
2306            .get_amount_out(amount_in.clone(), &token_in, &token_out)
2307            .expect("hookless swap should succeed");
2308
2309        let mut pool = create_basic_v4_test_pool();
2310        pool.set_hook_handler(after_swap_test_hook(&[
2311            HookOptions::AfterSwap,
2312            HookOptions::AfterSwapReturnsDelta,
2313        ]));
2314        let with_delta = pool
2315            .get_amount_out(amount_in, &token_in, &token_out)
2316            .expect("swap with hook delta should succeed");
2317
2318        assert_eq!(with_delta.amount, &hookless.amount - BigUint::from(AFTER_SWAP_TEST_HOOK_DELTA));
2319        assert_eq!(
2320            with_delta.gas,
2321            hookless.gas + BigUint::from(AFTER_SWAP_TEST_HOOK_GAS + PM_PER_HOOK_CALL_OVERHEAD)
2322        );
2323    }
2324
2325    const FEELESS_POOL_LIQUIDITY: u128 = 100_000_000_000_000_000_000; // 100e18
2326
2327    /// A pool with no LP fee and no protocol fee, holding a single position that spans the whole
2328    /// walkable tick range, so every difference between a hooked and a hookless answer is the
2329    /// hook's doing alone.
2330    fn create_feeless_v4_test_pool(liquidity: u128) -> UniswapV4State {
2331        let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
2332            .expect("a price of two has a square root");
2333        let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("the sqrt price maps to a tick");
2334        let position = FEELESS_POOL_LIQUIDITY as i128;
2335
2336        UniswapV4State::new(
2337            liquidity,
2338            sqrt_price,
2339            UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 0 },
2340            tick,
2341            60,
2342            vec![
2343                TickInfo::new(-46_080, position).unwrap(),
2344                TickInfo::new(46_080, -position).unwrap(),
2345            ],
2346        )
2347        .expect("the pool builds")
2348    }
2349
2350    fn pons_test_handler() -> PonsV2HookHandler {
2351        PonsV2HookHandler::new(PONS_V2_HOOK_ROBINHOOD, 100, 100)
2352    }
2353
2354    /// A pool whose `hooks` attribute is the zero address carries no handler, so it prices
2355    /// through `core_spot_price`: the documented `ProtocolSim::spot_price` contract, which is the
2356    /// buy price `P / (1 − f)` rather than the sell-side slope `P · (1 − f)` a finite-difference
2357    /// fallback would return. Pinned to a concrete number in both token orderings.
2358    #[test]
2359    fn hookless_spot_price_is_the_documented_buy_price_with_lp_fee_markup() {
2360        const LP_FEE_PIPS: u32 = 3_000;
2361        const LP_FEE: f64 = LP_FEE_PIPS as f64 / 1_000_000.0;
2362        const LIQUIDITY: u128 = 100_000_000_000_000_000_000; // 100e18
2363        const TOLERANCE: f64 = 1e-12;
2364
2365        let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
2366            .expect("a price of two has a square root");
2367        let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("the sqrt price maps to a tick");
2368        let pool = UniswapV4State::new(
2369            LIQUIDITY,
2370            sqrt_price,
2371            UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: LP_FEE_PIPS },
2372            tick,
2373            60,
2374            vec![
2375                TickInfo::new(-46_080, LIQUIDITY as i128).unwrap(),
2376                TickInfo::new(46_080, -(LIQUIDITY as i128)).unwrap(),
2377            ],
2378        )
2379        .expect("the pool builds");
2380
2381        assert!(pool.hook.is_none(), "the pinned values only hold with no hook handler");
2382
2383        let (t0, t1) = (token_x(), token_y());
2384        let pre_fee = sqrt_price_q96_to_f64(sqrt_price, t0.decimals, t1.decimals)
2385            .expect("the sqrt price converts to a price");
2386
2387        let expected_buy_t0 = pre_fee / (1.0 - LP_FEE);
2388        let expected_buy_t1 = (1.0 / pre_fee) / (1.0 - LP_FEE);
2389
2390        let buy_t0 = pool
2391            .spot_price(&t0, &t1)
2392            .expect("a hookless pool always prices");
2393        let buy_t1 = pool
2394            .spot_price(&t1, &t0)
2395            .expect("a hookless pool always prices");
2396
2397        assert!(
2398            (buy_t0 / expected_buy_t0 - 1.0).abs() < TOLERANCE,
2399            "buying t0 quoted {buy_t0}, expected {expected_buy_t0}"
2400        );
2401        assert!(
2402            (buy_t1 / expected_buy_t1 - 1.0).abs() < TOLERANCE,
2403            "buying t1 quoted {buy_t1}, expected {expected_buy_t1}"
2404        );
2405    }
2406
2407    /// Pons takes its cut out of the swap's output, so buying one `base` through it costs
2408    /// `core / (1 − rate)` of `quote`. At 100 + 100 bps that is `1 / 0.98` of the hookless
2409    /// price: above it, never below.
2410    #[rstest]
2411    #[case::base_is_currency0(true)]
2412    #[case::base_is_currency1(false)]
2413    fn test_spot_price_marks_up_an_analytic_hook_fee(#[case] base_is_currency0: bool) {
2414        let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
2415        let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2416        hooked.set_hook_handler(Box::new(pons_test_handler()));
2417
2418        let core = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
2419            .spot_price(&base, &quote)
2420            .expect("a hookless pool always prices");
2421        let price = hooked
2422            .spot_price(&base, &quote)
2423            .expect("the hook prices its own fee");
2424
2425        assert!(price > core, "hooked {price} is not above hookless {core}");
2426        let ratio = price / core;
2427        assert!((ratio * 0.98 - 1.0).abs() < 1e-9, "hooked/hookless is {ratio}, not 1/0.98");
2428    }
2429
2430    /// The marked-up spot price is the limit of the hooked quote as the trade shrinks: buying
2431    /// 1e-4 of a token out of 100e18 of liquidity executes within 1e-4 of it.
2432    #[rstest]
2433    #[case::base_is_currency0(true)]
2434    #[case::base_is_currency1(false)]
2435    fn test_hooked_spot_price_matches_a_small_hooked_buy(#[case] base_is_currency0: bool) {
2436        let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
2437        let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2438        hooked.set_hook_handler(Box::new(pons_test_handler()));
2439
2440        let quote_in = BigUint::from(100_000_000_000_000u64);
2441        let base_out = hooked
2442            .get_amount_out(quote_in.clone(), &quote, &base)
2443            .expect("a tiny buy always fits the pool")
2444            .amount;
2445
2446        let executed = quote_in.to_f64().unwrap() / base_out.to_f64().unwrap();
2447        let spot = hooked
2448            .spot_price(&base, &quote)
2449            .expect("the hook prices its own fee");
2450
2451        assert!((executed / spot - 1.0).abs() < 1e-4, "executed {executed}, quoted {spot}");
2452    }
2453
2454    /// A hook that prices its fee analytically is priced from the pool, not from whatever its
2455    /// own `spot_price` answers: the analytic rate is the whole of what it does to the price,
2456    /// and asking the handler would cost a simulation for no gain.
2457    #[rstest]
2458    #[case::base_is_currency0(true)]
2459    #[case::base_is_currency1(false)]
2460    fn test_spot_price_prefers_an_analytic_fee_over_the_hooks_own_price(
2461        #[case] base_is_currency0: bool,
2462    ) {
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(pricing_test_hook(Some(200)));
2466
2467        let core = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
2468            .spot_price(&base, &quote)
2469            .expect("a hookless pool always prices");
2470        let price = hooked
2471            .spot_price(&base, &quote)
2472            .expect("the hook prices its own fee");
2473
2474        assert_ne!(
2475            price, TEST_HOOK_SPOT_PRICE as f64,
2476            "the pool asked the hook for a price instead of marking up its own"
2477        );
2478        let ratio = price / core;
2479        assert!((ratio * 0.98 - 1.0).abs() < 1e-9, "hooked/hookless is {ratio}, not 1/0.98");
2480    }
2481
2482    /// The companion of the test above: the very same handler, with nothing but its analytic fee
2483    /// taken away, is asked for a price and its answer is passed through. That is what the pool
2484    /// would return for the hook above if it consulted the handler first.
2485    #[rstest]
2486    #[case::base_is_currency0(true)]
2487    #[case::base_is_currency1(false)]
2488    fn test_spot_price_uses_the_hooks_own_price_without_an_analytic_fee(
2489        #[case] base_is_currency0: bool,
2490    ) {
2491        let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
2492        let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2493        hooked.set_hook_handler(pricing_test_hook(None));
2494
2495        let price = hooked
2496            .spot_price(&base, &quote)
2497            .expect("the hook answers with a price");
2498
2499        assert_eq!(price, TEST_HOOK_SPOT_PRICE as f64);
2500    }
2501
2502    /// A handler that does not price its fee analytically keeps the finite-difference fallback,
2503    /// which reads the slope of two quotes and so cancels out a constant per-swap take.
2504    #[rstest]
2505    #[case::base_is_currency0(true)]
2506    #[case::base_is_currency1(false)]
2507    fn test_spot_price_falls_back_to_finite_difference_without_an_analytic_fee(
2508        #[case] base_is_currency0: bool,
2509    ) {
2510        let (base, quote) = basic_v4_test_pool_tokens(base_is_currency0);
2511        let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2512        hooked.set_hook_handler(after_swap_test_hook(&[
2513            HookOptions::AfterSwap,
2514            HookOptions::AfterSwapReturnsDelta,
2515        ]));
2516
2517        let x1 = BigUint::from(10u64).pow(base.decimals) / BigUint::from(100u64);
2518        let x2 = &x1 + (&x1 / BigUint::from(100u64));
2519        let y1 = hooked
2520            .get_amount_out(x1.clone(), &base, &quote)
2521            .expect("the smaller probe swap fits")
2522            .amount;
2523        let y2 = hooked
2524            .get_amount_out(x2.clone(), &base, &quote)
2525            .expect("the larger probe swap fits")
2526            .amount;
2527        let slope = (&y2 - &y1).to_f64().unwrap() / (&x2 - &x1).to_f64().unwrap();
2528
2529        let price = hooked
2530            .spot_price(&base, &quote)
2531            .expect("the fallback always prices");
2532
2533        assert_eq!(price, slope);
2534        let core = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
2535            .spot_price(&base, &quote)
2536            .expect("a hookless pool always prices");
2537        assert!((price / core - 1.0).abs() < 1e-3, "fallback {price} strayed from core {core}");
2538    }
2539
2540    /// `get_limits` reports what a swapper actually receives, so the hook's cut comes off the
2541    /// output. The input the pool can absorb is unchanged: the hook charges the other leg.
2542    #[rstest]
2543    #[case::zero_for_one(true)]
2544    #[case::one_for_zero(false)]
2545    fn test_get_limits_reports_the_output_net_of_an_analytic_hook_fee(#[case] zero_for_one: bool) {
2546        let (token_in, token_out) = basic_v4_test_pool_tokens(zero_for_one);
2547        let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2548        hooked.set_hook_handler(Box::new(pons_test_handler()));
2549
2550        let (hookless_in, hookless_out) = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
2551            .get_limits(token_in.address.clone(), token_out.address.clone())
2552            .expect("a pool with liquidity has limits");
2553        let (limit_in, limit_out) = hooked
2554            .get_limits(token_in.address.clone(), token_out.address.clone())
2555            .expect("a pool with liquidity has limits");
2556
2557        assert!(hookless_out > BigUint::zero(), "the reference pool must move some output");
2558        assert_eq!(limit_in, hookless_in);
2559        let taken = pons_test_handler()
2560            .fee_and_tax(biguint_to_u256(&hookless_out))
2561            .expect("a pool sized output never overflows");
2562        assert_eq!(limit_out, &hookless_out - u256_to_biguint(taken));
2563        assert!(limit_out < hookless_out);
2564    }
2565
2566    /// A handler with no analytic fee leaves the limits exactly where the pool's own liquidity
2567    /// puts them, so hooks that quote by simulation are unaffected.
2568    #[rstest]
2569    #[case::zero_for_one(true)]
2570    #[case::one_for_zero(false)]
2571    fn test_get_limits_unchanged_without_an_analytic_hook_fee(#[case] zero_for_one: bool) {
2572        let (token_in, token_out) = basic_v4_test_pool_tokens(zero_for_one);
2573        let mut hooked = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2574        hooked.set_hook_handler(after_swap_test_hook(&[
2575            HookOptions::AfterSwap,
2576            HookOptions::AfterSwapReturnsDelta,
2577        ]));
2578
2579        let hookless = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY)
2580            .get_limits(token_in.address.clone(), token_out.address.clone())
2581            .expect("a pool with liquidity has limits");
2582        let limits = hooked
2583            .get_limits(token_in.address.clone(), token_out.address.clone())
2584            .expect("a pool with liquidity has limits");
2585
2586        assert_eq!(limits, hookless);
2587    }
2588
2589    /// A pool with no liquidity of its own still reports no limits: the hook does not manage the
2590    /// liquidity here, so there is no output for it to take a cut of.
2591    #[test]
2592    fn test_get_limits_on_a_drained_pool_is_zero_with_an_analytic_hook() {
2593        let (token_in, token_out) = basic_v4_test_pool_tokens(true);
2594        let mut drained = create_feeless_v4_test_pool(0);
2595        drained.set_hook_handler(Box::new(pons_test_handler()));
2596
2597        let limits = drained
2598            .get_limits(token_in.address, token_out.address)
2599            .expect("a drained pool reports zero rather than failing");
2600
2601        assert_eq!(limits, (BigUint::zero(), BigUint::zero()));
2602    }
2603
2604    /// A hook that keeps the whole output leaves no price to quote. The markup would divide by
2605    /// zero or go negative, so the pool has to report the error instead.
2606    #[rstest]
2607    #[case::the_whole_output(10_000)]
2608    #[case::more_than_the_whole_output(20_000)]
2609    fn test_spot_price_rejects_a_hook_that_takes_the_whole_output(#[case] analytic_fee_bps: u32) {
2610        let mut pool = create_feeless_v4_test_pool(FEELESS_POOL_LIQUIDITY);
2611        pool.set_hook_handler(analytic_fee_test_hook(analytic_fee_bps));
2612
2613        let error = pool
2614            .spot_price(&token_x(), &token_y())
2615            .expect_err("a rate of one or more is not a price");
2616
2617        assert!(matches!(error, SimulationError::FatalError(_)), "{error:?}");
2618    }
2619
2620    #[test]
2621    fn test_spot_price_with_recoverable_error() {
2622        // Test that spot_price correctly falls back to swap-based calculation
2623        // when a RecoverableError (other than "not implemented") is returned
2624
2625        let usv4_state = UniswapV4State::new(
2626            1000000000000000000u128,                                  // 1e18 liquidity
2627            U256::from_str("79228162514264337593543950336").unwrap(), // 1:1 price
2628            UniswapV4Fees { zero_for_one: 100, one_for_zero: 100, lp_fee: 100 },
2629            0,
2630            60,
2631            vec![
2632                TickInfo::new(-600, 500000000000000000i128).unwrap(),
2633                TickInfo::new(600, -500000000000000000i128).unwrap(),
2634            ],
2635        )
2636        .unwrap();
2637
2638        // Test spot price calculation without a hook (should use default implementation)
2639        let spot_price_result = usv4_state.spot_price(&usdc(), &weth());
2640        assert!(spot_price_result.is_ok());
2641
2642        // The price should be approximately 1.0 (since we set sqrt_price for 1:1)
2643        // Adjusting for decimals difference (USDC has 6, WETH has 18)
2644        let price = spot_price_result.unwrap();
2645        assert!(price > 0.0);
2646    }
2647
2648    #[test]
2649    fn test_get_limits_with_hook_managed_liquidity_no_ranges_entrypoint() {
2650        // This test demonstrates the experimental limit finding logic for hooks that:
2651        // 1. Manage liquidity (pool has no liquidity & no ticks)
2652        // 2. Don't have get_amount_ranges entrypoint
2653
2654        let block = BlockHeader {
2655            number: 22689128,
2656            hash: Bytes::from_str(
2657                "0xfbfa716523d25d6d5248c18d001ca02b1caf10cabd1ab7321465e2262c41157b",
2658            )
2659            .expect("Invalid block hash"),
2660            timestamp: 1749739055,
2661            ..Default::default()
2662        };
2663
2664        let hook_address: Address = Address::from_str("0x69058613588536167ba0aa94f0cc1fe420ef28a8")
2665            .expect("Invalid hook address");
2666
2667        let db = SimulationDB::new(
2668            get_client(None).expect("Failed to create client"),
2669            get_runtime().expect("Failed to get runtime"),
2670            Some(block.clone()),
2671        );
2672        let engine = create_engine(db, true).expect("Failed to create simulation engine");
2673        let pool_manager = Address::from_str("0x000000000004444c5dc75cb358380d2e3de08a90")
2674            .expect("Invalid pool manager address");
2675
2676        // Create a GenericVMHookHandler without limits_entrypoint
2677        // This will trigger the "not set" error path and use experimental limit finding
2678        let hook_handler = GenericVMHookHandler::new(
2679            hook_address,
2680            engine,
2681            pool_manager,
2682            HashMap::new(),
2683            HashMap::new(),
2684            None,
2685            true, // Euler hook
2686        )
2687        .unwrap();
2688
2689        // Create a UniswapV4State with NO liquidity and NO ticks (hook manages all liquidity)
2690        let mut usv4_state = UniswapV4State::new(
2691            0, // no liquidity - hook provides it
2692            U256::from_str("4295128740").unwrap(),
2693            UniswapV4Fees { zero_for_one: 100, one_for_zero: 90, lp_fee: 500 },
2694            0,      // current tick
2695            1,      // tick spacing
2696            vec![], // no ticks - hook manages liquidity
2697        )
2698        .unwrap();
2699
2700        usv4_state.set_hook_handler(Box::new(hook_handler));
2701
2702        let token_in = usdc().address;
2703        let token_out = weth().address;
2704
2705        let (amount_in_limit, amount_out_limit) = usv4_state
2706            .get_limits(token_in, token_out)
2707            .expect("Should find limits through experimental swapping");
2708
2709        // Assuming pool supply doesn't change drastically at time of this test
2710        // At least 1 million USDC, not more than 100 million USDC
2711        assert!(amount_in_limit > BigUint::from(10u64).pow(12));
2712        assert!(amount_in_limit < BigUint::from(10u64).pow(14));
2713
2714        // At least 100 ETH, not more than 10 000 ETH
2715        assert!(amount_out_limit > BigUint::from(10u64).pow(20));
2716        assert!(amount_out_limit < BigUint::from(10u64).pow(22));
2717    }
2718
2719    #[rstest]
2720    #[case::high_liquidity(u128::MAX / 2)] // Very large liquidity
2721    #[case::medium_liquidity(10000000000000000000u128)] // Moderate liquidity: 10e18
2722    #[case::minimal_liquidity(1000u128)] // Very small liquidity
2723    fn test_find_max_amount(#[case] liquidity: u128) {
2724        // Use fixed configuration for all test cases
2725        let fees = UniswapV4Fees { zero_for_one: 100, one_for_zero: 100, lp_fee: 100 };
2726        let tick_spacing = 60;
2727        let ticks = vec![
2728            TickInfo::new(-600, (liquidity / 4) as i128).unwrap(),
2729            TickInfo::new(600, -((liquidity / 4) as i128)).unwrap(),
2730        ];
2731
2732        let usv4_state = UniswapV4State::new(
2733            liquidity,
2734            U256::from_str("79228162514264337593543950336").unwrap(),
2735            fees,
2736            0,
2737            tick_spacing,
2738            ticks,
2739        )
2740        .unwrap();
2741
2742        let token_in = usdc();
2743        let token_out = weth();
2744
2745        let (max_amount_in, _max_amount_out) = usv4_state
2746            .find_max_amount(&token_in, &token_out)
2747            .unwrap();
2748
2749        let success = usv4_state
2750            .get_amount_out(max_amount_in.clone(), &token_in, &token_out)
2751            .is_ok();
2752        assert!(success, "Should be able to swap the exact max amount.");
2753
2754        let one_more = &max_amount_in + BigUint::from(1u64);
2755        let should_fail = usv4_state
2756            .get_amount_out(one_more, &token_in, &token_out)
2757            .is_err();
2758        assert!(should_fail, "Swapping max_amount + 1 should fail.");
2759    }
2760
2761    #[test]
2762    fn test_calculate_swap_fees_with_override() {
2763        // Test that calculate_swap_fees_pips works correctly with overridden fees
2764        let fees = UniswapV4Fees::new(100, 90, 500);
2765
2766        // Without override, should use UniswapV4 formula: protocol + lp - (protocol * lp /
2767        // 1_000_000)
2768        let total_zero_for_one = fees.calculate_swap_fees_pips(true, None);
2769        // 100 + 500 - (100 * 500 / 1_000_000) = 600 - 0 = 600 (rounded down)
2770        assert_eq!(total_zero_for_one, 600);
2771
2772        // With override, should use override fee + protocol fee with same formula
2773        let total_with_override = fees.calculate_swap_fees_pips(true, Some(1000));
2774        // 100 + 1000 - (100 * 1000 / 1_000_000) = 1100 - 0 = 1100 (rounded down)
2775        assert_eq!(total_with_override, 1100);
2776    }
2777
2778    #[test]
2779    fn test_max_combined_fees_stays_valid() {
2780        // Test that even with max protocol + max LP fees, we stay under compute_swap_step limit
2781        let fees = UniswapV4Fees::new(1000, 1000, 1000);
2782        let total = fees.calculate_swap_fees_pips(true, Some(lp_fee::MAX_LP_FEE));
2783
2784        // Using UniswapV4 formula: 1000 + 1000000 - (1000 * 1000000 / 1_000_000)
2785        // = 1001000 - 1000 = 1000000
2786        assert_eq!(total, 1_000_000);
2787    }
2788
2789    #[test]
2790    fn test_get_limits_graceful_underflow() {
2791        // Verifies graceful handling of liquidity underflow in get_limits for V4
2792        let usv4_state = UniswapV4State::new(
2793            1000000,
2794            U256::from_str("79228162514264337593543950336").unwrap(), // 1:1 price
2795            UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 },
2796            0,
2797            60,
2798            vec![
2799                // A tick with net_liquidity > current_liquidity
2800                // When zero_for_one=true, this gets negated and would cause underflow
2801                TickInfo {
2802                    index: -60,
2803                    net_liquidity: 2000000, // 2x current liquidity
2804                    sqrt_price: U256::from_str("79051508376726796163471739988").unwrap(),
2805                },
2806            ],
2807        )
2808        .unwrap();
2809
2810        let usdc = usdc();
2811        let weth = weth();
2812
2813        let (limit_in, limit_out) = usv4_state
2814            .get_limits(usdc.address.clone(), weth.address.clone())
2815            .unwrap();
2816
2817        // Should return some conservative limits
2818        assert!(limit_in > BigUint::zero());
2819        assert!(limit_out > BigUint::zero());
2820    }
2821
2822    // Tests based on Uniswap V4's ProtocolFeeLibrary.t.sol
2823    // See: https://github.com/Uniswap/v4-core/blob/main/test/libraries/ProtocolFeeLibrary.t.sol
2824
2825    /// Maximum protocol fee in pips (1000 = 0.1%)
2826    const MAX_PROTOCOL_FEE: u32 = 1000;
2827
2828    #[rstest]
2829    #[case::max_protocol_and_max_lp(MAX_PROTOCOL_FEE, lp_fee::MAX_LP_FEE, lp_fee::MAX_LP_FEE)]
2830    #[case::max_protocol_with_3000_lp(MAX_PROTOCOL_FEE, 3000, 3997)]
2831    #[case::max_protocol_with_zero_lp(MAX_PROTOCOL_FEE, 0, MAX_PROTOCOL_FEE)]
2832    #[case::zero_protocol_zero_lp(0, 0, 0)]
2833    #[case::zero_protocol_with_1000_lp(0, 1000, 1000)]
2834    fn test_calculate_swap_fees_uniswap_test_cases(
2835        #[case] protocol_fee: u32,
2836        #[case] lp_fee: u32,
2837        #[case] expected: u32,
2838    ) {
2839        let fees = UniswapV4Fees::new(protocol_fee, protocol_fee, lp_fee);
2840        let result = fees.calculate_swap_fees_pips(true, None);
2841        assert_eq!(result, expected);
2842    }
2843
2844    #[test]
2845    fn test_calculate_swap_fees_with_dynamic_fee() {
2846        // Test that dynamic fees default to 0 when no override is provided
2847        let fees = UniswapV4Fees::new(100, 90, lp_fee::DYNAMIC_FEE_FLAG);
2848
2849        // Without override, dynamic fee should be treated as 0
2850        let total_zero_for_one = fees.calculate_swap_fees_pips(true, None);
2851        // 100 + 0 - (100 * 0 / 1_000_000) = 100
2852        assert_eq!(total_zero_for_one, 100);
2853
2854        // With override, should use the override value
2855        let total_with_override = fees.calculate_swap_fees_pips(true, Some(500));
2856        // 100 + 500 - (100 * 500 / 1_000_000) = 600 - 0 = 600
2857        assert_eq!(total_with_override, 600);
2858    }
2859
2860    #[test]
2861    fn test_calculate_swap_fees_direction_matters() {
2862        // Test that zero_for_one direction affects which protocol fee is used
2863        let fees = UniswapV4Fees::new(100, 200, 500);
2864
2865        let zero_for_one_fee = fees.calculate_swap_fees_pips(true, None);
2866        // 100 + 500 - (100 * 500 / 1_000_000) = 600 - 0 = 600
2867        assert_eq!(zero_for_one_fee, 600);
2868
2869        let one_for_zero_fee = fees.calculate_swap_fees_pips(false, None);
2870        // 200 + 500 - (200 * 500 / 1_000_000) = 700 - 0 = 700
2871        assert_eq!(one_for_zero_fee, 700);
2872    }
2873
2874    #[rstest]
2875    #[case::high_lp_fee(1000, 500_000, 500_500)] // 1000 + 500k - 500 = 500.5k
2876    #[case::mid_fees(500, 500_000, 500_250)] // 500 + 500k - 250 = 500.25k
2877    #[case::low_fees(100, 100_000, 100_090)] // 100 + 100k - 10 = 100.09k
2878    fn test_calculate_swap_fees_formula_precision(
2879        #[case] protocol_fee: u32,
2880        #[case] lp_fee: u32,
2881        #[case] expected: u32,
2882    ) {
2883        // Test cases where the subtraction term (protocol * lp / 1M) significantly affects the
2884        // result
2885        let fees = UniswapV4Fees::new(protocol_fee, protocol_fee, lp_fee);
2886        let result = fees.calculate_swap_fees_pips(true, None);
2887        assert_eq!(result, expected, "Failed for protocol={}, lp={}", protocol_fee, lp_fee);
2888    }
2889
2890    #[test]
2891    fn test_calculate_swap_fees_override_takes_precedence() {
2892        // Test that lp_fee_override completely replaces stored lp_fee
2893        let fees = UniswapV4Fees::new(100, 100, 3000);
2894
2895        // With override, stored lp_fee should be ignored
2896        let result = fees.calculate_swap_fees_pips(true, Some(5000));
2897        // 100 + 5000 - (100 * 5000 / 1_000_000) = 5100 - 0 = 5100
2898        assert_eq!(result, 5100);
2899
2900        // Without override, should use stored lp_fee
2901        let result_no_override = fees.calculate_swap_fees_pips(true, None);
2902        // 100 + 3000 - (100 * 3000 / 1_000_000) = 3100 - 0 = 3100
2903        assert_eq!(result_no_override, 3100);
2904    }
2905
2906    #[test]
2907    fn test_calculate_swap_fees_zero_protocol_fee() {
2908        // When protocol fee is 0, formula simplifies to just lpFee
2909        let fees = UniswapV4Fees::new(0, 0, 3000);
2910        let result = fees.calculate_swap_fees_pips(true, None);
2911        // 0 + 3000 - (0 * 3000 / 1_000_000) = 3000
2912        assert_eq!(result, 3000);
2913    }
2914
2915    #[test]
2916    fn test_calculate_swap_fees_zero_lp_fee() {
2917        // When lp fee is 0, formula simplifies to just protocolFee
2918        let fees = UniswapV4Fees::new(500, 500, 0);
2919        let result = fees.calculate_swap_fees_pips(true, None);
2920        // 500 + 0 - (500 * 0 / 1_000_000) = 500
2921        assert_eq!(result, 500);
2922    }
2923
2924    // Helper to create a basic test pool for swap_to_price tests
2925    fn create_basic_v4_test_pool() -> UniswapV4State {
2926        let liquidity = 100_000_000_000_000_000_000u128; // 100e18
2927        let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
2928            .expect("Failed to calculate sqrt price");
2929        let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
2930
2931        let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
2932
2933        UniswapV4State::new(
2934            liquidity,
2935            sqrt_price,
2936            UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 }, // 0.3% fee
2937            tick,
2938            60, // tick spacing
2939            ticks,
2940        )
2941        .expect("Failed to create pool")
2942    }
2943
2944    fn create_tick_boundary_v4_test_pool() -> UniswapV4State {
2945        let sqrt_price = get_sqrt_ratio_at_tick(0).expect("Failed to calculate sqrt price");
2946        let ticks = vec![TickInfo::new(-120, 0).unwrap(), TickInfo::new(120, 0).unwrap()];
2947
2948        UniswapV4State::new(
2949            100_000_000_000_000_000_000u128,
2950            sqrt_price,
2951            UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 },
2952            0,
2953            60,
2954            ticks,
2955        )
2956        .expect("Failed to create pool")
2957    }
2958
2959    #[test]
2960    fn test_partial_step_updates_tick_when_price_moves_without_crossing_initialized_tick() {
2961        let pool = create_tick_boundary_v4_test_pool();
2962        let amount = -I256::from_raw(U256::from(100_000_000_000_000_000u64));
2963
2964        let result = pool
2965            .swap(true, amount, None, None)
2966            .expect("swap should stay within the current liquidity range");
2967        let expected_tick =
2968            get_tick_at_sqrt_ratio(result.sqrt_price).expect("new sqrt price should map to a tick");
2969
2970        assert_ne!(result.sqrt_price, pool.sqrt_price);
2971        assert_ne!(result.sqrt_price, get_sqrt_ratio_at_tick(-120).unwrap());
2972        assert_ne!(expected_tick, pool.tick.value());
2973        assert_eq!(result.tick.value(), expected_tick);
2974    }
2975
2976    #[test]
2977    fn test_swap_keeps_boundary_tick_when_price_does_not_move() {
2978        let mut pool = create_tick_boundary_v4_test_pool();
2979        pool.tick = PoolTick::from(-1);
2980        let amount = -I256::from_raw(U256::from(1u64));
2981
2982        let result = pool
2983            .swap(true, amount, None, None)
2984            .expect("swap should consume the input as fee without moving price");
2985
2986        assert_eq!(result.sqrt_price, pool.sqrt_price);
2987        assert_eq!(get_tick_at_sqrt_ratio(result.sqrt_price).unwrap(), 0);
2988        assert_eq!(result.tick, pool.tick);
2989    }
2990
2991    #[test]
2992    fn test_swap_to_price_price_too_high() {
2993        let pool = create_basic_v4_test_pool();
2994
2995        let token_x = token_x();
2996        let token_y = token_y();
2997
2998        // Price far above pool price - should return zero
2999        let target_price = Price::new(BigUint::from(10_000_000u64), BigUint::from(1_000_000u64));
3000
3001        let result = pool.query_pool_swap(&QueryPoolSwapParams::new(
3002            token_x,
3003            token_y,
3004            SwapConstraint::PoolTargetPrice {
3005                target: target_price,
3006                tolerance: 0f64,
3007                min_amount_in: None,
3008                max_amount_in: None,
3009            },
3010        ));
3011        assert!(result.is_err(), "Should return error when target price is unreachable");
3012    }
3013
3014    #[test]
3015    fn test_swap_to_price_no_liquidity() {
3016        // Test that swap_to_price returns zero for pool with no liquidity
3017        let pool = UniswapV4State::new(
3018            0, // No liquidity
3019            U256::from_str("79228162514264337593543950336").unwrap(),
3020            UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 },
3021            0,
3022            60,
3023            vec![],
3024        )
3025        .unwrap();
3026
3027        let token_x = token_x();
3028        let token_y = token_y();
3029
3030        let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_000_000u64));
3031
3032        let pool_swap = pool.query_pool_swap(&QueryPoolSwapParams::new(
3033            token_x,
3034            token_y,
3035            SwapConstraint::PoolTargetPrice {
3036                target: target_price,
3037                tolerance: 0f64,
3038                min_amount_in: None,
3039                max_amount_in: None,
3040            },
3041        ));
3042
3043        assert!(pool_swap.is_err());
3044    }
3045
3046    #[test]
3047    fn test_swap_to_price_with_protocol_fees() {
3048        let liquidity = 100_000_000_000_000_000_000u128;
3049        let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
3050            .expect("Failed to calculate sqrt price");
3051        let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
3052
3053        let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
3054
3055        // Create pool with different protocol fees for each direction
3056        let pool = UniswapV4State::new(
3057            liquidity,
3058            sqrt_price,
3059            UniswapV4Fees {
3060                zero_for_one: 1000, // 0.1% protocol fee for zero_for_one
3061                one_for_zero: 200,  // 0.02% protocol fee for one_for_zero
3062                lp_fee: 3000,       // 0.3% LP fee
3063            },
3064            tick,
3065            60,
3066            ticks,
3067        )
3068        .expect("Failed to create pool");
3069
3070        let token_x = token_x();
3071        let token_y = token_y();
3072
3073        // Pool at 2.0 Y/X = 0.5 X/Y, swap_to_price moves price DOWN to target
3074
3075        // Test zero_for_one direction (X -> Y, uses zero_for_one fee)
3076        let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_010_000u64));
3077        let pool_swap_forward = pool
3078            .query_pool_swap(&QueryPoolSwapParams::new(
3079                token_x.clone(),
3080                token_y.clone(),
3081                SwapConstraint::PoolTargetPrice {
3082                    target: target_price,
3083                    tolerance: 0f64,
3084                    min_amount_in: None,
3085                    max_amount_in: None,
3086                },
3087            ))
3088            .expect("swap_to_price failed");
3089
3090        // Test one_for_zero direction (Y -> X, uses one_for_zero fee)
3091        let target_price_reverse =
3092            Price::new(BigUint::from(1_010_000u64), BigUint::from(2_040_000u64));
3093        let pool_swap_backward = pool
3094            .query_pool_swap(&QueryPoolSwapParams::new(
3095                token_y,
3096                token_x,
3097                SwapConstraint::PoolTargetPrice {
3098                    target: target_price_reverse,
3099                    tolerance: 0f64,
3100                    min_amount_in: None,
3101                    max_amount_in: None,
3102                },
3103            ))
3104            .expect("swap_to_price failed");
3105
3106        assert!(
3107            pool_swap_backward.amount_out().clone() > BigUint::ZERO,
3108            "One for zero swap should return non-zero output"
3109        );
3110
3111        // Higher fees require more volume to reach the same price target
3112        // trade_zfo has 0.1% protocol fee, trade_ofz has 0.02% protocol fee
3113        assert!(
3114            pool_swap_forward.amount_out() < pool_swap_backward.amount_in(),
3115            "Backward fees should be lower therefore backward swap should be bigger"
3116        );
3117        assert!(
3118            pool_swap_forward.amount_in() < pool_swap_backward.amount_out(),
3119            "Backward fees should be lower therefore backward swap should be bigger"
3120        );
3121    }
3122
3123    #[test]
3124    fn test_swap_to_price_different_targets() {
3125        // Test with various target prices using working format
3126        let pool = create_basic_v4_test_pool();
3127
3128        let token_x = token_x();
3129        let token_y = token_y();
3130
3131        // Pool at 2.0 Y/X (20M/10M)
3132        // Test 1: Target close to spot (1.98 Y/X)
3133        let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_010_000u64));
3134        let pool_swap_close = pool
3135            .query_pool_swap(&QueryPoolSwapParams::new(
3136                token_x.clone(),
3137                token_y.clone(),
3138                SwapConstraint::PoolTargetPrice {
3139                    target: target_price,
3140                    tolerance: 0f64,
3141                    min_amount_in: None,
3142                    max_amount_in: None,
3143                },
3144            ))
3145            .expect("swap_to_price failed");
3146        assert!(
3147            *pool_swap_close.amount_out() > BigUint::ZERO,
3148            "Expected non-zero for 1.98 Y/X target"
3149        );
3150
3151        // Test 2: Target further from spot (1.90 Y/X)
3152        let target_price = Price::new(BigUint::from(1_900_000u64), BigUint::from(1_000_000u64));
3153        let pool_swap_below = pool
3154            .query_pool_swap(&QueryPoolSwapParams::new(
3155                token_x.clone(),
3156                token_y.clone(),
3157                SwapConstraint::PoolTargetPrice {
3158                    target: target_price,
3159                    tolerance: 0f64,
3160                    min_amount_in: None,
3161                    max_amount_in: None,
3162                },
3163            ))
3164            .expect("swap_to_price failed");
3165        assert!(
3166            pool_swap_below.amount_out().clone() > BigUint::ZERO,
3167            "Expected non-zero for 1.90 Y/X target"
3168        );
3169
3170        // Test 3: Target far from spot (1.5 Y/X)
3171        let target_price = Price::new(BigUint::from(1_500_000u64), BigUint::from(1_000_000u64));
3172        let pool_swap_far = pool
3173            .query_pool_swap(&QueryPoolSwapParams::new(
3174                token_x,
3175                token_y,
3176                SwapConstraint::PoolTargetPrice {
3177                    target: target_price,
3178                    tolerance: 0f64,
3179                    min_amount_in: None,
3180                    max_amount_in: None,
3181                },
3182            ))
3183            .expect("swap_to_price failed");
3184        assert!(
3185            pool_swap_far.amount_out().clone() > BigUint::ZERO,
3186            "Expected non-zero for 1.5 Y/X target"
3187        );
3188
3189        // Verify that further targets require more volume
3190        assert!(
3191            pool_swap_close.amount_out().clone() < pool_swap_below.amount_out().clone(),
3192            "Closer target (1.98 Y/X) should require less volume than medium target (1.90 Y/X). \
3193             Got close: {}, medium: {}",
3194            pool_swap_close.amount_out().clone(),
3195            pool_swap_below.amount_out().clone()
3196        );
3197        assert!(
3198            pool_swap_below.amount_out().clone() < pool_swap_far.amount_out().clone(),
3199            "Medium target (1.90 Y/X) should require less volume than far target (1.5 Y/X). \
3200             Got medium: {}, far: {}",
3201            pool_swap_below.amount_out().clone(),
3202            pool_swap_far.amount_out().clone()
3203        );
3204    }
3205
3206    #[test]
3207    fn test_swap_to_price_around_spot_price() {
3208        let liquidity = 10_000_000_000_000_000u128;
3209        let sqrt_price =
3210            get_sqrt_price_q96(U256::from(2_000_000_000u64), U256::from(1_000_000_000u64))
3211                .expect("Failed to calculate sqrt price");
3212        let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
3213
3214        let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
3215
3216        // Use FeeAmount::Low equivalent (500 pips = 0.05%)
3217        let pool = UniswapV4State::new(
3218            liquidity,
3219            sqrt_price,
3220            UniswapV4Fees {
3221                zero_for_one: 0,
3222                one_for_zero: 0,
3223                lp_fee: 500, // 0.05% to match V3 FeeAmount::Low
3224            },
3225            tick,
3226            60,
3227            ticks,
3228        )
3229        .expect("Failed to create pool");
3230
3231        let token_x = token_x();
3232        let token_y = token_y();
3233
3234        // Test 1: Price just above spot price, too little to cover fees
3235        let target_price = Price::new(BigUint::from(1_999_750u64), BigUint::from(1_000_250u64));
3236
3237        let result = pool.query_pool_swap(&QueryPoolSwapParams::new(
3238            token_x.clone(),
3239            token_y.clone(),
3240            SwapConstraint::PoolTargetPrice {
3241                target: target_price,
3242                tolerance: 0f64,
3243                min_amount_in: None,
3244                max_amount_in: None,
3245            },
3246        ));
3247        assert!(result.is_err(), "Should return error when target price is unreachable");
3248
3249        // Test 2: Price far enough from spot prices to enable trading despite fees (0.1% lower)
3250        let target_price = Price::new(BigUint::from(1_999_000u64), BigUint::from(1_001_000u64));
3251
3252        let pool_swap = pool
3253            .query_pool_swap(&QueryPoolSwapParams::new(
3254                token_x,
3255                token_y,
3256                SwapConstraint::PoolTargetPrice {
3257                    target: target_price,
3258                    tolerance: 0f64,
3259                    min_amount_in: None,
3260                    max_amount_in: None,
3261                },
3262            ))
3263            .expect("swap_to_price failed");
3264
3265        // Should match V3 output exactly with same fees
3266        let expected_amount_out =
3267            BigUint::from_str("7062236922008").expect("Failed to parse expected value");
3268        assert_eq!(
3269            pool_swap.amount_out().clone(),
3270            expected_amount_out,
3271            "V4 should match V3 output with same fees (0.05%)"
3272        );
3273    }
3274
3275    #[test]
3276    fn test_swap_to_price_matches_get_amount_out() {
3277        let pool = create_basic_v4_test_pool();
3278
3279        let token_x = token_x();
3280        let token_y = token_y();
3281
3282        // Get the trade from swap_to_price
3283        let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_010_000u64));
3284        let pool_swap = pool
3285            .query_pool_swap(&QueryPoolSwapParams::new(
3286                token_x.clone(),
3287                token_y.clone(),
3288                SwapConstraint::PoolTargetPrice {
3289                    target: target_price,
3290                    tolerance: 0f64,
3291                    min_amount_in: None,
3292                    max_amount_in: None,
3293                },
3294            ))
3295            .expect("swap_to_price failed");
3296        assert!(*pool_swap.amount_in() > BigUint::ZERO, "Amount in should be positive");
3297
3298        // Use the amount_in from swap_to_price with get_amount_out
3299        let result = pool
3300            .get_amount_out(pool_swap.amount_in().clone(), &token_x, &token_y)
3301            .expect("get_amount_out failed");
3302
3303        // The amount_out from get_amount_out should be close to swap_to_price's amount_out
3304        // Allow for small rounding differences
3305        assert!(result.amount > BigUint::ZERO);
3306        assert!(result.amount >= *pool_swap.amount_out());
3307    }
3308
3309    #[test]
3310    fn test_swap_to_price_basic() {
3311        let liquidity = 100_000_000_000_000_000_000u128;
3312        let sqrt_price = get_sqrt_price_q96(U256::from(20_000_000u64), U256::from(10_000_000u64))
3313            .expect("Failed to calculate sqrt price");
3314        let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
3315
3316        let ticks = vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(46080, 0).unwrap()];
3317
3318        let pool = UniswapV4State::new(
3319            liquidity,
3320            sqrt_price,
3321            UniswapV4Fees {
3322                zero_for_one: 0,
3323                one_for_zero: 0,
3324                lp_fee: 3000, // 0.3% LP fee
3325            },
3326            tick,
3327            60,
3328            ticks,
3329        )
3330        .expect("Failed to create pool");
3331
3332        let token_x = token_x();
3333        let token_y = token_y();
3334
3335        // Target price: 2_000_000/1_010_000 ≈ 1.98 Y/X
3336        let target_price = Price::new(BigUint::from(2_000_000u64), BigUint::from(1_010_000u64));
3337
3338        let pool_swap = pool
3339            .query_pool_swap(&QueryPoolSwapParams::new(
3340                token_x,
3341                token_y,
3342                SwapConstraint::PoolTargetPrice {
3343                    target: target_price,
3344                    tolerance: 0f64,
3345                    min_amount_in: None,
3346                    max_amount_in: None,
3347                },
3348            ))
3349            .expect("swap_to_price failed");
3350
3351        // Should match V3's output exactly with same fees (0.3%)
3352        let expected_amount_in = BigUint::from_str("246739021727519745").unwrap();
3353        let expected_amount_out = BigUint::from_str("490291909043340795").unwrap();
3354
3355        assert_eq!(
3356            *pool_swap.amount_in(),
3357            expected_amount_in,
3358            "amount_in should match expected value"
3359        );
3360        assert_eq!(
3361            *pool_swap.amount_out(),
3362            expected_amount_out,
3363            "amount_out should match expected value"
3364        );
3365    }
3366
3367    #[test]
3368    fn test_swap_price_limit_out_of_range_returns_error() {
3369        let pool = create_basic_v4_test_pool();
3370        let amount = -I256::from_raw(U256::from(1000u64)); // V4 uses negative for exact input
3371
3372        // zero_for_one: price_limit equal to sqrt_price is invalid (must be strictly less)
3373        let result = pool.swap(true, amount, Some(pool.sqrt_price), None);
3374        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
3375
3376        // zero_for_one: price_limit at MIN_SQRT_RATIO is invalid (must be strictly greater)
3377        let result = pool.swap(true, amount, Some(MIN_SQRT_RATIO), None);
3378        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
3379
3380        // one_for_zero: price_limit equal to sqrt_price is invalid (must be strictly greater)
3381        let result = pool.swap(false, amount, Some(pool.sqrt_price), None);
3382        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
3383
3384        // one_for_zero: price_limit at MAX_SQRT_RATIO is invalid (must be strictly less)
3385        let result = pool.swap(false, amount, Some(MAX_SQRT_RATIO), None);
3386        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
3387    }
3388
3389    #[test]
3390    fn test_swap_at_extreme_price_returns_error() {
3391        // Simulates the depth calculation scenario: pool sqrt_price is at MIN_SQRT_RATIO + 1,
3392        // so the default price limit for zero_for_one equals sqrt_price and fails validation.
3393        let sqrt_price = MIN_SQRT_RATIO + U256::from(1u64);
3394        let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
3395        // tick_spacing 60; ticks must be aligned
3396        let aligned_tick = (MIN_TICK / 60) * 60 + 60; // first multiple of 60 above MIN_TICK
3397        let ticks = vec![
3398            TickInfo::new(aligned_tick, 0).unwrap(),
3399            TickInfo::new(aligned_tick + 60, 0).unwrap(),
3400        ];
3401        let pool = UniswapV4State::new(
3402            100_000_000_000_000_000_000u128,
3403            sqrt_price,
3404            UniswapV4Fees { zero_for_one: 0, one_for_zero: 0, lp_fee: 3000 },
3405            tick,
3406            60,
3407            ticks,
3408        )
3409        .unwrap();
3410
3411        let amount = -I256::from_raw(U256::from(1000u64));
3412        // Default price limit for zero_for_one is MIN_SQRT_RATIO + 1 == sqrt_price, so invalid
3413        let result = pool.swap(true, amount, None, None);
3414        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
3415    }
3416
3417    #[test]
3418    fn test_serde_roundtrip_via_protocol_sim_typetag() {
3419        let pool = create_basic_v4_test_pool();
3420
3421        let json =
3422            serde_json::to_string(&pool as &dyn ProtocolSim).expect("state should serialize");
3423        let deserialized: Box<dyn ProtocolSim> =
3424            serde_json::from_str(&json).expect("state should deserialize");
3425
3426        assert!(deserialized.eq(&pool));
3427    }
3428
3429    #[test]
3430    fn test_serialize_with_hook() {
3431        let mut pool = create_basic_v4_test_pool();
3432        let handler = AngstromHookHandler::new(
3433            Address::from_str("0x0000000aa232009084bd71a5797d089aa4edfad4").unwrap(),
3434            Address::from_str("0x000000000004444c5dc75cb358380d2e3de08a90").unwrap(),
3435            AngstromFees { unlock: U24::from(238), protocol_unlock: U24::from(112) },
3436            false,
3437        );
3438        pool.set_hook_handler(Box::new(handler));
3439
3440        let result = serde_json::to_string(&pool);
3441        assert!(result
3442            .unwrap_err()
3443            .to_string()
3444            .contains("HookHandler is a trait object"));
3445    }
3446
3447    #[test]
3448    fn test_deserialize_negative_tick_spacing() {
3449        let pool = UniswapV4State::new(
3450            1_000,
3451            U256::from(1u64) << 96,
3452            UniswapV4Fees::new(0, 0, 3000),
3453            0,
3454            60,
3455            vec![TickInfo::new(0, 0).unwrap(), TickInfo::new(60, 0).unwrap()],
3456        )
3457        .expect("valid state");
3458        let mut json = serde_json::to_value(&pool).expect("hookless state should serialize");
3459        json["tick_spacing"] = (-60).into();
3460
3461        let err = serde_json::from_value::<UniswapV4State>(json).unwrap_err();
3462
3463        assert!(
3464            err.to_string()
3465                .contains("must be positive"),
3466            "unexpected error: {err}"
3467        );
3468    }
3469}
3470
3471#[cfg(test)]
3472mod step_cache_tests {
3473    use std::{
3474        collections::{HashMap, HashSet},
3475        str::FromStr,
3476    };
3477
3478    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
3479
3480    use super::*;
3481    use crate::evm::protocol::utils::uniswap::swap_step_cache::test_fixtures::{
3482        amount_orders, test_amounts, test_ticks, wbtc_weth, LIQUIDITY, SQRT_PRICE, TICK,
3483    };
3484
3485    fn test_pool_with_fees(fees: UniswapV4Fees) -> UniswapV4State {
3486        UniswapV4State::new(
3487            LIQUIDITY,
3488            U256::from_str(SQRT_PRICE).unwrap(),
3489            fees,
3490            TICK,
3491            10,
3492            test_ticks(),
3493        )
3494        .unwrap()
3495    }
3496
3497    fn test_pool() -> UniswapV4State {
3498        test_pool_with_fees(UniswapV4Fees::new(0, 0, 500))
3499    }
3500
3501    /// A quote's amount, gas and new state, or its error, as text.
3502    fn format_quote_result(
3503        pool: &UniswapV4State,
3504        amount: &BigUint,
3505        sell: &Token,
3506        buy: &Token,
3507    ) -> String {
3508        match pool.get_amount_out(amount.clone(), sell, buy) {
3509            Ok(result) => {
3510                let state = result
3511                    .new_state
3512                    .as_any()
3513                    .downcast_ref::<UniswapV4State>()
3514                    .unwrap();
3515                format!(
3516                    "{} {} {} {} {}",
3517                    result.amount,
3518                    result.gas,
3519                    state.sqrt_price,
3520                    state.tick.value(),
3521                    state.liquidity
3522                )
3523            }
3524            Err(error) => format!("error {error}"),
3525        }
3526    }
3527
3528    #[test]
3529    fn test_step_cache_quotes_match_a_fresh_state_in_any_order() {
3530        let (wbtc, weth) = wbtc_weth();
3531        // No protocol fee, then a protocol fee that differs by direction.
3532        for fees in [UniswapV4Fees::new(0, 0, 500), UniswapV4Fees::new(100, 90, 3000)] {
3533            for (sell, buy, smallest) in [(&wbtc, &weth, 1_000u64), (&weth, &wbtc, 1_000_000_000)] {
3534                for order in amount_orders(&test_amounts(smallest)) {
3535                    let shared = test_pool_with_fees(fees.clone());
3536                    for amount in &order {
3537                        assert_eq!(
3538                            format_quote_result(&shared, amount, sell, buy),
3539                            format_quote_result(
3540                                &test_pool_with_fees(fees.clone()),
3541                                amount,
3542                                sell,
3543                                buy
3544                            ),
3545                            "selling {amount} {} with {fees:?}",
3546                            sell.symbol
3547                        );
3548                    }
3549                    let steps = shared
3550                        .step_cache
3551                        .min_inputs(sell < buy)
3552                        .len();
3553                    assert!(steps > 2, "only {steps} steps cached");
3554                }
3555            }
3556        }
3557    }
3558
3559    #[test]
3560    fn test_step_cache_quotes_match_a_fresh_state_at_each_cached_step() {
3561        let (wbtc, weth) = wbtc_weth();
3562        // Amounts that run past the last tick, so the cache covers the whole tick list. Selling
3563        // WETH needs a far larger amount to leave its first tick.
3564        for (sell, buy, doublings) in [(&wbtc, &weth, 30u32), (&weth, &wbtc, 70)] {
3565            let cached = test_pool();
3566            let _ = cached.get_amount_out(BigUint::from(10u32) << doublings, sell, buy);
3567            let boundaries = cached.step_cache.min_inputs(sell < buy);
3568            assert!(boundaries.len() > 2, "only {} steps cached", boundaries.len());
3569            for boundary in boundaries.into_iter().skip(1) {
3570                for amount in [boundary - U256::from(1u64), boundary, boundary + U256::from(1u64)] {
3571                    let amount = u256_to_biguint(amount);
3572                    assert_eq!(
3573                        format_quote_result(&cached, &amount, sell, buy),
3574                        format_quote_result(&test_pool(), &amount, sell, buy),
3575                        "selling {amount} {}",
3576                        sell.symbol
3577                    );
3578                }
3579            }
3580        }
3581    }
3582
3583    #[test]
3584    fn test_step_cache_restarts_after_delta_transition() {
3585        let (wbtc, weth) = wbtc_weth();
3586        let large = BigUint::from(3_000_000_000u64);
3587        // Only a crossed tick's liquidity changes, so the price, tick and liquidity the cache
3588        // starts from stay the same.
3589        let delta = || ProtocolStateDelta {
3590            component_id: "State1".to_owned(),
3591            updated_attributes: HashMap::from([(
3592                "ticks/255820/net_liquidity".to_string(),
3593                Bytes::from(
3594                    1_000_000_000_000_000i128
3595                        .to_be_bytes()
3596                        .to_vec(),
3597                ),
3598            )]),
3599            deleted_attributes: HashSet::new(),
3600        };
3601        let mut cached = test_pool();
3602        cached
3603            .get_amount_out(large.clone(), &wbtc, &weth)
3604            .unwrap();
3605        let mut fresh = test_pool();
3606
3607        cached
3608            .delta_transition(delta(), &HashMap::new(), &Balances::default())
3609            .unwrap();
3610        fresh
3611            .delta_transition(delta(), &HashMap::new(), &Balances::default())
3612            .unwrap();
3613
3614        assert_eq!(
3615            format_quote_result(&cached, &large, &wbtc, &weth),
3616            format_quote_result(&fresh, &large, &wbtc, &weth)
3617        );
3618    }
3619}