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