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