Skip to main content

tycho_simulation/evm/protocol/uniswap_v4/
state.rs

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