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