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