Skip to main content

tycho_simulation/evm/protocol/aerodrome_slipstreams/
state.rs

1use std::{any::Any, collections::HashMap, sync::Arc};
2
3use alloy::primitives::{Sign, I256, U256};
4use num_bigint::BigUint;
5use num_traits::Zero;
6use serde::{Deserialize, Serialize};
7use tracing::{error, trace};
8use tycho_common::{
9    dto::ProtocolStateDelta,
10    models::token::Token,
11    simulation::{
12        errors::{SimulationError, TransitionError},
13        protocol_sim::{
14            Balances, BlockContext, GetAmountOutResult, PoolSwap, Price, ProtocolSim,
15            QueryPoolSwapParams, SwapConstraint,
16        },
17    },
18    Bytes,
19};
20
21use crate::{
22    evm::{
23        protocol::{
24            clmm::clmm_swap_to_price,
25            safe_math::{safe_add_u256, safe_sub_u256},
26            u256_num::u256_to_biguint,
27            utils::{
28                add_fee_markup,
29                slipstreams::{
30                    aero_hook_fee::{AeroHookFee, Execution, HookFee, PoolOracle},
31                    dynamic_fee_module::{get_dynamic_fee, DynamicFeeConfig, ResolvedFee},
32                    observations::{Observation, Observations},
33                    oracle_timestamp, raw_target_price,
34                },
35                uniswap::{
36                    i24_be_bytes_to_i32, liquidity_math,
37                    pool_tick::PoolTick,
38                    sqrt_price_math::{
39                        get_amount0_delta, get_amount1_delta, sqrt_price_q96_to_f64,
40                    },
41                    swap_math::{self, SwapStepResult},
42                    swap_step_cache::{StepCacheKey, StepCacheRun, SwapStepCache},
43                    tick_list::{TickInfo, TickList, TickListErrorKind},
44                    tick_math::{
45                        get_sqrt_ratio_at_tick_cached, MAX_SQRT_RATIO, MAX_TICK, MIN_SQRT_RATIO,
46                        MIN_TICK,
47                    },
48                    StepComputation, SwapResults, SwapState,
49                },
50            },
51        },
52        query_pool_swap::price_to_f64_with_decimals,
53    },
54    protocol::models::BlockPositionAssumption,
55};
56
57// Cold-storage warmup on the first loop iteration:
58// nextInitializedTickWithinOneWord first call (~3,000) vs warm (~1,060)
59// calculateFees first call via cold getUnstakedFee STATICCALL (~19,050) vs warm (~6,055)
60const FIRST_LOOP_OVERHEAD: u64 = 15_000;
61// Steady-state per-loop: nextInitializedTickWithinOneWord (warm) + getSqrtRatioAtTick
62// + computeSwapStep + calculateFees (warm) + toInt256x2 + EVM opcode overhead
63const LOOP_GAS_COST: u64 = 12_500;
64// cross(): updates tick fee growth and staked reward growth slots.
65// Warm ticks (previously crossed, non-zero SSTORE slots) cost ~22k; cold ticks ~76k.
66// We bias toward the cold end to prefer overestimation: 70k.
67const TICK_CROSSING_GAS_COST: u64 = 70_000;
68// When dfc.scaling_factor != 0, fee() does a TWAP binary search on the observation ring
69// buffer (~77k–91k gas) instead of a simple slot read (~18k–27k gas). This extra cost is
70// added once per swap on top of the base.
71const TWAP_FEE_OVERHEAD: u64 = 65_000;
72// Pre/post loop overhead: fee(), slot0 reads, end-of-swap writes.
73const SWAP_BASE_GAS: u64 = 125_000;
74// AERO v1.1 pools call their swap hook, which runs the TWAP observe and stores the block fee,
75// then record the swap on the pool tape and settle the gauge. Measured with eth_simulateV1 of
76// single-step swaps on Base: ~312-317k for the pool's swap against ~140k for an Aerodrome
77// Slipstreams pool. Replaces TWAP_FEE_OVERHEAD.
78const AERO_HOOK_GAS: u64 = 160_000;
79// Conservative max gas for a single swap. Used to cap get_limits iteration.
80const MAX_SWAP_GAS: u64 = 16_700_000;
81// Maximum initialized ticks that can be crossed within MAX_SWAP_GAS.
82const MAX_TICKS_CROSSED: u64 = (MAX_SWAP_GAS - SWAP_BASE_GAS) / TICK_CROSSING_GAS_COST;
83
84#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
85pub struct AerodromeSlipstreamsState {
86    id: String,
87    /// Timestamp of the block a quote against this state is expected to execute in.
88    ///
89    /// Maintained by the stream decoder via [`ProtocolSim::apply_block`], not decoded from
90    /// the pool: the fee module's initial-vs-dynamic branch keys on the *execution* block, which
91    /// is the next block for a confirmed update and the still-open block for a flashblock
92    /// update.
93    execution_block_timestamp: u64,
94    /// Number of the block a quote is expected to execute in; maintained like
95    /// `execution_block_timestamp`. The AERO swap hook caches its fee per block number.
96    #[serde(default)]
97    execution_block_number: u64,
98    liquidity: u128,
99    sqrt_price: U256,
100    observation_index: u16,
101    observation_cardinality: u16,
102    default_fee: u32,
103    tick_spacing: i32,
104    tick: i32,
105    /// The tick list, shared by this state, its clones and the states its swaps return, so a quote
106    /// does not copy it. Change it only through `Arc::make_mut`, which copies the list while
107    /// another state shares it.
108    ticks: Arc<TickList>,
109    /// Swap steps already taken from this state, shared by its clones. The steps hold only for
110    /// this state's price, tick, liquidity, fee and ticks. `delta_transition` and
111    /// `clone_post_swap` replace the cache with an empty one, and any other code that changes
112    /// those fields must do the same.
113    #[serde(skip)]
114    step_cache: SwapStepCache,
115    observations: Observations,
116    dfc: DynamicFeeConfig,
117    /// Fee settings of an AERO v1.1 pool, whose swap hook sets the fee instead of a fee module.
118    /// When set, `dfc` is unused.
119    #[serde(default)]
120    aero_hook: Option<AeroHookFee>,
121    /// What quotes may assume about the swap's position within its execution block; see
122    /// [`BlockPositionAssumption`].
123    position_assumption: BlockPositionAssumption,
124}
125
126impl AerodromeSlipstreamsState {
127    /// Creates a new instance of `AerodromeSlipstreamsState`.
128    ///
129    /// # Arguments
130    /// - `id`: The id of the protocol component.
131    /// - `execution_block_timestamp`: Timestamp of the block a quote is expected to execute in.
132    /// - `liquidity`: The initial liquidity of the pool.
133    /// - `sqrt_price`: The square root of the current price.
134    /// - `observation_index`: The index of the current observation.
135    /// - `observation_cardinality`: The cardinality of the observation.
136    /// - `default_fee`: The default fee for the pool.
137    /// - `tick_spacing`: The tick spacing for the pool.
138    /// - `tick`: The current tick of the pool.
139    /// - `ticks`: A vector of `TickInfo` representing the tick information for the pool.
140    /// - `observations`: A vector of `Observation` representing the observation information for the
141    ///   pool.
142    /// - `dfc`: The dynamic fee configuration for the pool.
143    #[expect(
144        clippy::too_many_arguments,
145        reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
146    )]
147    pub fn new(
148        id: String,
149        execution_block_timestamp: u64,
150        liquidity: u128,
151        sqrt_price: U256,
152        observation_index: u16,
153        observation_cardinality: u16,
154        default_fee: u32,
155        tick_spacing: i32,
156        tick: i32,
157        ticks: Vec<TickInfo>,
158        observations: Vec<Observation>,
159        dfc: DynamicFeeConfig,
160    ) -> Result<Self, SimulationError> {
161        let tick_list_spacing = u16::try_from(tick_spacing).map_err(|e| {
162            SimulationError::InvalidInput(format!("Invalid tick spacing {tick_spacing}: {e}"), None)
163        })?;
164        let tick_list = TickList::from(tick_list_spacing, ticks)?;
165        Ok(AerodromeSlipstreamsState {
166            id,
167            execution_block_timestamp,
168            execution_block_number: 0,
169            liquidity,
170            sqrt_price,
171            observation_index,
172            observation_cardinality,
173            default_fee,
174            tick_spacing,
175            tick,
176            ticks: Arc::new(tick_list),
177            step_cache: SwapStepCache::default(),
178            observations: Observations::new(observations),
179            dfc,
180            aero_hook: None,
181            position_assumption: BlockPositionAssumption::default(),
182        })
183    }
184
185    /// Prices swaps with an AERO v1.1 swap hook instead of the dynamic fee module.
186    pub fn with_aero_hook(mut self, hook: AeroHookFee) -> Self {
187        self.aero_hook = Some(hook);
188        self
189    }
190
191    /// Sets what quotes assume about the swap's position within its execution block.
192    ///
193    /// A consumer-side preference, independent of the pool's on-chain state.
194    pub fn with_position_assumption(mut self, assumption: BlockPositionAssumption) -> Self {
195        self.position_assumption = assumption;
196        self
197    }
198
199    fn get_fee(&self) -> Result<ResolvedFee, SimulationError> {
200        if let Some(hook) = &self.aero_hook {
201            let fee = self.hook_fee(hook)?;
202            return Ok(ResolvedFee { fee: fee.fee, observed_twap: fee.observed_twap });
203        }
204        get_dynamic_fee(
205            &self.dfc,
206            self.default_fee,
207            self.tick,
208            self.liquidity,
209            self.observation_index,
210            self.observation_cardinality,
211            &self.observations,
212            oracle_timestamp(self.execution_block_timestamp),
213            self.position_assumption == BlockPositionAssumption::First,
214        )
215    }
216
217    fn hook_fee(&self, hook: &AeroHookFee) -> Result<HookFee, SimulationError> {
218        hook.resolve(
219            &PoolOracle {
220                tick: self.tick,
221                liquidity: self.liquidity,
222                observation_index: self.observation_index,
223                observation_cardinality: self.observation_cardinality,
224                observations: &self.observations,
225            },
226            self.default_fee,
227            Execution {
228                block: self.execution_block_number,
229                timestamp: oracle_timestamp(self.execution_block_timestamp),
230                first_in_block: self.position_assumption == BlockPositionAssumption::First,
231            },
232        )
233    }
234
235    /// Records the observation the pool would write for a swap that moved the tick from
236    /// `self.tick` to `post_swap_tick`, so that a second swap chained onto this state in the same
237    /// block resolves the dynamic fee instead of the initial fee.
238    ///
239    /// Mirrors `CLPool.swap`, which writes only when the tick moved and passes the pre-swap tick
240    /// and liquidity. Must be called before the caller overwrites `tick`/`liquidity`.
241    fn record_observation(&mut self, post_swap_tick: i32) -> Result<(), SimulationError> {
242        if post_swap_tick == self.tick {
243            return Ok(());
244        }
245        self.observation_index = self.observations.write(
246            self.observation_index,
247            oracle_timestamp(self.execution_block_timestamp),
248            self.tick,
249            self.liquidity,
250            self.observation_cardinality,
251        )?;
252        Ok(())
253    }
254
255    /// Swaps token_in until `spot_price(token_in, token_out)` reaches the middle of the band
256    /// `[target, target * (1 + tolerance)]`. Falls back to numerical search if recording the
257    /// observation changes the fee enough to move the final price outside the band.
258    fn swap_to_target_price(
259        &self,
260        params: &QueryPoolSwapParams,
261        target: &Price,
262        tolerance: f64,
263    ) -> Result<PoolSwap, SimulationError> {
264        let token_in = params.token_in();
265        let token_out = params.token_out();
266        let target_f64 = price_to_f64_with_decimals(target, token_in.decimals, token_out.decimals)?;
267        if target_f64 == self.spot_price(token_in, token_out)? {
268            return Ok(PoolSwap::new(BigUint::ZERO, BigUint::ZERO, Box::new(self.clone()), None));
269        }
270        let Some(limit) = raw_target_price(target, tolerance, self.get_fee()?.fee) else {
271            return crate::evm::query_pool_swap::query_pool_swap(self, params);
272        };
273        // `limit` already strips the fee that `spot_price` adds, so the swap uses fee 0.
274        let Ok((amount_in, amount_out, result)) = clmm_swap_to_price(
275            self.sqrt_price,
276            &token_in.address,
277            &token_out.address,
278            &limit,
279            0,
280            Sign::Positive,
281            |zero_for_one, amount_specified, sqrt_price_limit| {
282                self.swap(zero_for_one, amount_specified, Some(sqrt_price_limit))
283            },
284        ) else {
285            return crate::evm::query_pool_swap::query_pool_swap(self, params);
286        };
287
288        let new_state = if amount_in.is_zero() {
289            self.clone()
290        } else {
291            let (state, observation) =
292                self.clone_post_swap(result.sqrt_price, result.tick.value(), result.liquidity);
293            observation?;
294            state
295        };
296        let final_spot = new_state.spot_price(token_in, token_out)?;
297        if final_spot < target_f64 || final_spot > target_f64 * (1.0 + tolerance) {
298            return crate::evm::query_pool_swap::query_pool_swap(self, params);
299        }
300        Ok(PoolSwap::new(amount_in, amount_out, Box::new(new_state), None))
301    }
302
303    /// A clone of this state with the final price, tick and liquidity of a swap, an empty step
304    /// cache, and the price observation the swap writes. Returns the result of the observation
305    /// write beside the state, so a caller can decide whether a failed write is an error.
306    fn clone_post_swap(
307        &self,
308        sqrt_price: U256,
309        tick: i32,
310        liquidity: u128,
311    ) -> (Self, Result<(), SimulationError>) {
312        let mut state = self.clone();
313        state.step_cache = SwapStepCache::default();
314        // The block's first swap stores the block fee every later swap in the block pays.
315        if let (Some(hook), Some(state_hook)) = (&self.aero_hook, state.aero_hook.as_mut()) {
316            match self.hook_fee(hook) {
317                Ok(HookFee { block_fee_to_store: Some(fee), .. }) => {
318                    state_hook.store_block_fee(self.execution_block_number, fee)
319                }
320                Ok(_) => {}
321                Err(err) => return (state, Err(err)),
322            }
323        }
324        let observation = state.record_observation(tick);
325        state.liquidity = liquidity;
326        state.tick = tick;
327        state.sqrt_price = sqrt_price;
328        (state, observation)
329    }
330
331    fn swap(
332        &self,
333        zero_for_one: bool,
334        amount_specified: I256,
335        sqrt_price_limit: Option<U256>,
336    ) -> Result<SwapResults, SimulationError> {
337        if self.liquidity == 0 {
338            return Err(SimulationError::RecoverableError("No liquidity".to_string()));
339        }
340        let price_limit = if let Some(limit) = sqrt_price_limit {
341            limit
342        } else if zero_for_one {
343            safe_add_u256(MIN_SQRT_RATIO, U256::from(1u64))?
344        } else {
345            safe_sub_u256(MAX_SQRT_RATIO, U256::from(1u64))?
346        };
347
348        let price_limit_valid = if zero_for_one {
349            price_limit > MIN_SQRT_RATIO && price_limit < self.sqrt_price
350        } else {
351            price_limit < MAX_SQRT_RATIO && price_limit > self.sqrt_price
352        };
353        if !price_limit_valid {
354            return Err(SimulationError::InvalidInput("Price limit out of range".into(), None));
355        }
356
357        let exact_input = amount_specified > I256::from_raw(U256::from(0u64));
358
359        let mut state = SwapState {
360            amount_remaining: amount_specified,
361            amount_calculated: I256::from_raw(U256::from(0u64)),
362            sqrt_price: self.sqrt_price,
363            tick: self.tick.into(),
364            liquidity: self.liquidity,
365        };
366        let resolved_fee = self.get_fee()?;
367        let twap_overhead = if self.aero_hook.is_some() {
368            AERO_HOOK_GAS
369        } else if resolved_fee.observed_twap {
370            TWAP_FEE_OVERHEAD
371        } else {
372            0
373        };
374        let mut gas_used = U256::from(SWAP_BASE_GAS + twap_overhead);
375        let mut n_loops = 0;
376
377        let fee = resolved_fee.fee;
378        // Only exact-input swaps with no price limit use the step cache. The cache finds a step by
379        // its input, which an exact-output swap does not know. A cached step can also lie past a
380        // price limit.
381        let cache_key = if exact_input && sqrt_price_limit.is_none() {
382            StepCacheKey::new(self.sqrt_price, state.tick.value(), self.liquidity, fee, gas_used)
383        } else {
384            None
385        };
386        let mut cache_run = StepCacheRun::new(
387            &self.step_cache,
388            zero_for_one,
389            cache_key,
390            amount_specified.unsigned_abs(),
391        );
392        if let Some(progress) = cache_run.apply_cached_progress(&mut state) {
393            gas_used = progress.gas;
394            // The first loop's overhead is in the cached gas already.
395            n_loops = progress.steps_taken;
396        }
397        while state.amount_remaining != I256::from_raw(U256::from(0u64)) &&
398            state.sqrt_price != price_limit
399        {
400            let (mut next_tick, next_tick_info) = match self
401                .ticks
402                .next_initialized_tick_within_one_word(state.tick.value(), zero_for_one)
403            {
404                Ok((tick, info)) => (tick, info),
405                Err(tick_err) => match tick_err.kind {
406                    TickListErrorKind::TicksExeeded => {
407                        let (new_state, observation) = self.clone_post_swap(
408                            state.sqrt_price,
409                            state.tick.value(),
410                            state.liquidity,
411                        );
412                        // Best effort in an error path: a failed write only degrades the fee of
413                        // a chained simulation on this partial result, and must not mask the
414                        // more informative TicksExceeded error below.
415                        if let Err(record_err) = observation {
416                            trace!(%record_err, "skipping observation write on partial result");
417                        }
418                        return Err(SimulationError::InvalidInput(
419                            "Ticks exceeded".into(),
420                            Some(GetAmountOutResult::new(
421                                u256_to_biguint(state.amount_calculated.abs().into_raw()),
422                                u256_to_biguint(gas_used),
423                                Box::new(new_state),
424                            )),
425                        ));
426                    }
427                    TickListErrorKind::BelowSmallest | TickListErrorKind::AtOrAboveLargest => {
428                        return Err(SimulationError::FatalError("Unknown error".to_string()))
429                    }
430                },
431            };
432
433            next_tick = next_tick.clamp(MIN_TICK, MAX_TICK);
434
435            let sqrt_price_start = state.sqrt_price;
436            let sqrt_price_next = match next_tick_info {
437                Some(info) => info.sqrt_price,
438                None => get_sqrt_ratio_at_tick_cached(next_tick)?,
439            };
440            let SwapStepResult { sqrt_price, amount_in_with_fee, amount_out } =
441                swap_math::compute_swap_step(
442                    state.sqrt_price,
443                    AerodromeSlipstreamsState::get_sqrt_ratio_target(
444                        sqrt_price_next,
445                        price_limit,
446                        zero_for_one,
447                    ),
448                    state.liquidity,
449                    state.amount_remaining,
450                    fee,
451                )?;
452            state.sqrt_price = sqrt_price;
453
454            let step = StepComputation {
455                sqrt_price_start,
456                tick_next: next_tick,
457                sqrt_price_next,
458                amount_in_with_fee,
459                amount_out,
460            };
461            if exact_input {
462                state.amount_remaining -=
463                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
464                        .unwrap();
465                state.amount_calculated -=
466                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
467            } else {
468                state.amount_remaining +=
469                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
470                state.amount_calculated +=
471                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
472                        .unwrap();
473            }
474            if state.sqrt_price == step.sqrt_price_next {
475                if let Some(info) = next_tick_info {
476                    let liquidity_raw = info.net_liquidity;
477                    let liquidity_net = if zero_for_one { -liquidity_raw } else { liquidity_raw };
478                    state.liquidity =
479                        liquidity_math::add_liquidity_delta(state.liquidity, liquidity_net)?;
480                    gas_used = safe_add_u256(gas_used, U256::from(TICK_CROSSING_GAS_COST))?;
481                }
482                state.tick =
483                    PoolTick::from(if zero_for_one { step.tick_next - 1 } else { step.tick_next });
484            } else if state.sqrt_price != step.sqrt_price_start {
485                state.tick = PoolTick::at_sqrt_price(state.sqrt_price)?;
486            }
487            gas_used = safe_add_u256(gas_used, U256::from(LOOP_GAS_COST))?;
488            if n_loops == 0 {
489                gas_used = safe_add_u256(gas_used, U256::from(FIRST_LOOP_OVERHEAD))?;
490            }
491            n_loops += 1;
492            cache_run.cache_progress(&step, &state, gas_used);
493        }
494        Ok(SwapResults {
495            amount_calculated: state.amount_calculated,
496            amount_specified,
497            amount_remaining: state.amount_remaining,
498            sqrt_price: state.sqrt_price,
499            liquidity: state.liquidity,
500            tick: state.tick,
501            gas_used,
502        })
503    }
504
505    fn get_sqrt_ratio_target(
506        sqrt_price_next: U256,
507        sqrt_price_limit: U256,
508        zero_for_one: bool,
509    ) -> U256 {
510        let cond1 = if zero_for_one {
511            sqrt_price_next < sqrt_price_limit
512        } else {
513            sqrt_price_next > sqrt_price_limit
514        };
515
516        if cond1 {
517            sqrt_price_limit
518        } else {
519            sqrt_price_next
520        }
521    }
522}
523
524#[typetag::serde]
525impl ProtocolSim for AerodromeSlipstreamsState {
526    fn fee(&self) -> f64 {
527        match self.get_fee() {
528            Ok(resolved) => resolved.fee as f64 / 1_000_000.0,
529            Err(err) => {
530                error!(
531                    pool = %self.id,
532                    execution_block_timestamp = self.execution_block_timestamp,
533                    %err,
534                    "Error while calculating dynamic fee"
535                );
536                f64::MAX / 1_000_000.0
537            }
538        }
539    }
540
541    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
542        let price = if base < quote {
543            sqrt_price_q96_to_f64(self.sqrt_price, base.decimals, quote.decimals)?
544        } else {
545            1.0f64 / sqrt_price_q96_to_f64(self.sqrt_price, quote.decimals, base.decimals)?
546        };
547        Ok(add_fee_markup(price, self.get_fee()?.fee as f64 / 1_000_000.0))
548    }
549
550    fn get_amount_out(
551        &self,
552        amount_in: BigUint,
553        token_in: &Token,
554        token_out: &Token,
555    ) -> Result<GetAmountOutResult, SimulationError> {
556        let zero_for_one = token_in < token_out;
557        let amount_specified = I256::checked_from_sign_and_abs(
558            Sign::Positive,
559            U256::from_be_slice(&amount_in.to_bytes_be()),
560        )
561        .ok_or_else(|| {
562            SimulationError::InvalidInput("I256 overflow: amount_in".to_string(), None)
563        })?;
564
565        let result = self.swap(zero_for_one, amount_specified, None)?;
566
567        trace!(?amount_in, ?token_in, ?token_out, ?zero_for_one, ?result, "SLIPSTREAMS SWAP");
568        let (new_state, observation) =
569            self.clone_post_swap(result.sqrt_price, result.tick.value(), result.liquidity);
570        observation?;
571
572        Ok(GetAmountOutResult::new(
573            u256_to_biguint(
574                result
575                    .amount_calculated
576                    .abs()
577                    .into_raw(),
578            ),
579            u256_to_biguint(result.gas_used),
580            Box::new(new_state),
581        ))
582    }
583
584    fn get_limits(
585        &self,
586        sell_token: Bytes,
587        buy_token: Bytes,
588    ) -> Result<(BigUint, BigUint), SimulationError> {
589        // If the pool has no liquidity, return zeros for both limits
590        if self.liquidity == 0 {
591            return Ok((BigUint::zero(), BigUint::zero()));
592        }
593
594        let zero_for_one = sell_token < buy_token;
595        let mut current_tick = self.tick;
596        let mut current_sqrt_price = self.sqrt_price;
597        let mut current_liquidity = self.liquidity;
598        let mut total_amount_in = U256::from(0u64);
599        let mut total_amount_out = U256::from(0u64);
600
601        // Iterate through all ticks in the direction of the swap
602        // Continues until there is no more liquidity in the pool or no more ticks to process
603        let mut ticks_crossed: u64 = 0;
604        while let Ok((tick, next_tick_info)) = self
605            .ticks
606            .next_initialized_tick_within_one_word(current_tick, zero_for_one)
607        {
608            if ticks_crossed >= MAX_TICKS_CROSSED {
609                break;
610            }
611            ticks_crossed += 1;
612            // Clamp the tick value to ensure it's within valid range
613            let next_tick = tick.clamp(MIN_TICK, MAX_TICK);
614
615            let sqrt_price_next = match next_tick_info {
616                Some(info) => info.sqrt_price,
617                None => get_sqrt_ratio_at_tick_cached(next_tick)?,
618            };
619
620            // Calculate the amount of tokens swapped when moving from current_sqrt_price to
621            // sqrt_price_next. Direction determines which token is being swapped in vs out
622            let (amount_in, amount_out) = if zero_for_one {
623                let amount0 = get_amount0_delta(
624                    sqrt_price_next,
625                    current_sqrt_price,
626                    current_liquidity,
627                    true,
628                )?;
629                let amount1 = get_amount1_delta(
630                    sqrt_price_next,
631                    current_sqrt_price,
632                    current_liquidity,
633                    false,
634                )?;
635                (amount0, amount1)
636            } else {
637                let amount0 = get_amount0_delta(
638                    sqrt_price_next,
639                    current_sqrt_price,
640                    current_liquidity,
641                    false,
642                )?;
643                let amount1 = get_amount1_delta(
644                    sqrt_price_next,
645                    current_sqrt_price,
646                    current_liquidity,
647                    true,
648                )?;
649                (amount1, amount0)
650            };
651
652            // Accumulate total amounts for this tick range
653            total_amount_in = safe_add_u256(total_amount_in, amount_in)?;
654            total_amount_out = safe_add_u256(total_amount_out, amount_out)?;
655
656            // If this tick is "initialized" (meaning its someone's position boundary), update the
657            // liquidity when crossing it
658            // For zero_for_one, liquidity is removed when crossing a tick
659            // For one_for_zero, liquidity is added when crossing a tick
660            if let Some(info) = next_tick_info {
661                let liquidity_raw = info.net_liquidity;
662                let liquidity_delta = if zero_for_one { -liquidity_raw } else { liquidity_raw };
663                current_liquidity =
664                    liquidity_math::add_liquidity_delta(current_liquidity, liquidity_delta)?;
665            }
666
667            // Move to the next tick position
668            current_tick = if zero_for_one { next_tick - 1 } else { next_tick };
669            current_sqrt_price = sqrt_price_next;
670        }
671
672        Ok((u256_to_biguint(total_amount_in), u256_to_biguint(total_amount_out)))
673    }
674
675    fn delta_transition(
676        &mut self,
677        delta: ProtocolStateDelta,
678        _tokens: &HashMap<Bytes, Token>,
679        _balances: &Balances,
680    ) -> Result<(), TransitionError> {
681        // Swap steps taken from the old state do not hold for the new one.
682        self.step_cache = SwapStepCache::default();
683        // apply attribute changes
684        if let Some(liquidity) = delta
685            .updated_attributes
686            .get("liquidity")
687        {
688            // This is a hotfix because if the liquidity has never been updated after creation, it's
689            // currently encoded as H256::zero(), therefore, we can't decode this as u128.
690            // We can remove this once it has been fixed on the tycho side.
691            let liq_16_bytes = if liquidity.len() == 32 {
692                // Make sure it only happens for 0 values, otherwise error.
693                if liquidity == &Bytes::zero(32) {
694                    Bytes::from([0; 16])
695                } else {
696                    return Err(TransitionError::DecodeError(format!(
697                        "Liquidity bytes too long for {liquidity}, expected 16",
698                    )));
699                }
700            } else {
701                liquidity.clone()
702            };
703
704            self.liquidity = u128::try_from(liq_16_bytes)?;
705        }
706        if let Some(sqrt_price) = delta
707            .updated_attributes
708            .get("sqrt_price_x96")
709        {
710            self.sqrt_price = U256::from_be_slice(sqrt_price);
711        }
712        if let Some(observation_index) = delta
713            .updated_attributes
714            .get("observationIndex")
715        {
716            self.observation_index = u16::try_from(observation_index.clone())?;
717        }
718        if let Some(observation_cardinality) = delta
719            .updated_attributes
720            .get("observationCardinality")
721        {
722            self.observation_cardinality = u16::try_from(observation_cardinality.clone())?;
723        }
724        if let Some(default_fee) = delta
725            .updated_attributes
726            .get("default_fee")
727        {
728            self.default_fee = u32::try_from(default_fee.clone())?;
729        }
730        if let Some(hook) = self.aero_hook.as_mut() {
731            hook.update_from_attributes(&delta.updated_attributes)
732                .map_err(TransitionError::DecodeError)?;
733        } else {
734            self.dfc
735                .update_from_attributes(&delta.updated_attributes)
736                .map_err(|err| {
737                    TransitionError::DecodeError(format!(
738                        "Failed to update dynamic fee module config: {err}"
739                    ))
740                })?;
741        }
742        if let Some(tick) = delta.updated_attributes.get("tick") {
743            // This is a hotfix because if the tick has never been updated after creation, it's
744            // currently encoded as H256::zero(), therefore, we can't decode this as i32.
745            // We can remove this once it has been fixed on the tycho side.
746            let ticks_4_bytes = if tick.len() == 32 {
747                // Make sure it only happens for 0 values, otherwise error.
748                if tick == &Bytes::zero(32) {
749                    Bytes::from([0; 4])
750                } else {
751                    return Err(TransitionError::DecodeError(format!(
752                        "Tick bytes too long for {tick}, expected 4"
753                    )));
754                }
755            } else {
756                tick.clone()
757            };
758            self.tick = i24_be_bytes_to_i32(&ticks_4_bytes);
759        }
760
761        // apply tick & observations changes
762        for (key, value) in delta.updated_attributes.iter() {
763            // tick liquidity keys are in the format "ticks/{tick_index}/net_liquidity"
764            if key.starts_with("ticks/") {
765                let parts: Vec<&str> = key.split('/').collect();
766                Arc::make_mut(&mut self.ticks)
767                    .set_tick_liquidity(
768                        parts[1]
769                            .parse::<i32>()
770                            .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
771                        i128::try_from(value.clone())?,
772                    )
773                    .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
774            }
775
776            // observations keys are in the format "observations/{observation_index}"
777            if let Some(idx_str) = key.strip_prefix("observations/") {
778                if let Ok(idx) = idx_str.parse::<i32>() {
779                    self.observations
780                        .upsert_observation(idx, value)
781                        .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
782                }
783            }
784        }
785        // delete ticks - ignores deletes for attributes other than tick liquidity
786        for key in delta.deleted_attributes.iter() {
787            // tick liquidity keys are in the format "ticks/{tick_index}/net_liquidity"
788            if key.starts_with("ticks/") {
789                let parts: Vec<&str> = key.split('/').collect();
790                Arc::make_mut(&mut self.ticks)
791                    .set_tick_liquidity(
792                        parts[1]
793                            .parse::<i32>()
794                            .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
795                        0,
796                    )
797                    .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
798            }
799
800            // observations keys are in the format "observations/{observation_index}"
801            if let Some(idx_str) = key.strip_prefix("observations/") {
802                if let Ok(idx) = idx_str.parse::<i32>() {
803                    self.observations
804                        .upsert_observation(idx, &[])
805                        .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
806                }
807            }
808        }
809        Ok(())
810    }
811
812    /// Re-emits only when the resolved fee actually changed: idle pools whose initial-vs-dynamic
813    /// branch stays put return `false` indefinitely, and same-block flashblocks short-circuit on
814    /// the unchanged timestamp.
815    fn apply_block(&mut self, block: &BlockContext) -> bool {
816        let timestamp = block.timestamp();
817        if timestamp == self.execution_block_timestamp &&
818            block.number() == self.execution_block_number
819        {
820            return false;
821        }
822        let fee_before = self.get_fee().ok();
823        self.execution_block_timestamp = timestamp;
824        self.execution_block_number = block.number();
825        fee_before != self.get_fee().ok()
826    }
827
828    fn clone_box(&self) -> Box<dyn ProtocolSim> {
829        Box::new(self.clone())
830    }
831
832    fn as_any(&self) -> &dyn Any {
833        self
834    }
835
836    fn as_any_mut(&mut self) -> &mut dyn Any {
837        self
838    }
839
840    fn eq(&self, other: &dyn ProtocolSim) -> bool {
841        if let Some(other_state) = other
842            .as_any()
843            .downcast_ref::<AerodromeSlipstreamsState>()
844        {
845            let Ok(self_fee) = self.get_fee() else { return false };
846            let Ok(other_fee) = other_state.get_fee() else { return false };
847
848            self.liquidity == other_state.liquidity &&
849                self.sqrt_price == other_state.sqrt_price &&
850                self_fee == other_fee &&
851                self.tick == other_state.tick &&
852                self.ticks == other_state.ticks
853        } else {
854            false
855        }
856    }
857
858    /// Answers [`SwapConstraint::PoolTargetPrice`] with one native swap and no `price_points`.
859    /// [`SwapConstraint::TradeLimitPrice`] uses the numerical search.
860    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
861        match params.swap_constraint() {
862            SwapConstraint::TradeLimitPrice { .. } => {
863                crate::evm::query_pool_swap::query_pool_swap(self, params)
864            }
865            SwapConstraint::PoolTargetPrice {
866                target,
867                tolerance,
868                min_amount_in: _,
869                max_amount_in: _,
870            } => {
871                let swap = self.swap_to_target_price(params, target, *tolerance)?;
872                let target = price_to_f64_with_decimals(
873                    target,
874                    params.token_in().decimals,
875                    params.token_out().decimals,
876                )?;
877                let spot = swap
878                    .new_state()
879                    .spot_price(params.token_in(), params.token_out())?;
880                if !tolerance.is_finite() ||
881                    *tolerance < 0.0 ||
882                    !(spot >= target && spot <= target * (1.0 + tolerance))
883                {
884                    return Err(SimulationError::RecoverableError(
885                        "Aerodrome target-price search ended outside the requested tolerance"
886                            .into(),
887                    ));
888                }
889                Ok(swap)
890            }
891        }
892    }
893}
894
895#[cfg(test)]
896#[path = "aero_cl_replay_tests.rs"]
897mod aero_cl_replay_tests;
898
899#[cfg(test)]
900mod tests {
901    use std::str::FromStr;
902
903    use alloy::primitives::{Sign, I256, U256};
904    use rstest::rstest;
905    use tycho_common::{models::Chain, simulation::errors::SimulationError};
906
907    use super::*;
908    use crate::evm::{
909        protocol::utils::{
910            slipstreams::{
911                dynamic_fee_module::{DynamicFeeConfig, ZERO_FEE_INDICATOR},
912                observations::Observation,
913            },
914            uniswap::{
915                tick_list::TickInfo,
916                tick_math::{
917                    get_sqrt_ratio_at_tick, get_tick_at_sqrt_ratio, MAX_SQRT_RATIO, MIN_SQRT_RATIO,
918                    MIN_TICK,
919                },
920            },
921        },
922        query_pool_swap::test_helpers::{target_price_params, to_price},
923    };
924
925    fn create_basic_test_pool() -> AerodromeSlipstreamsState {
926        let sqrt_price = get_sqrt_ratio_at_tick(0).expect("Failed to calculate sqrt price");
927        let ticks = vec![TickInfo::new(-120, 0).unwrap(), TickInfo::new(120, 0).unwrap()];
928        AerodromeSlipstreamsState::new(
929            "test-pool".to_string(),
930            1_000_000,
931            100_000_000_000_000_000_000u128,
932            sqrt_price,
933            0,
934            1,
935            3000,
936            1,
937            0,
938            ticks,
939            vec![Observation::default()],
940            DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
941        )
942        .expect("Failed to create pool")
943    }
944
945    fn dynamic_fee_delta(dynamic_fee_module: [u8; 20]) -> ProtocolStateDelta {
946        ProtocolStateDelta {
947            component_id: "test-pool".to_string(),
948            updated_attributes: HashMap::from([
949                ("dynamic_fee_module".to_string(), Bytes::from(dynamic_fee_module)),
950                ("dfc_baseFee".to_string(), Bytes::from(500_u32.to_be_bytes())),
951                ("dfc_scalingFactor".to_string(), Bytes::from(0_u64.to_be_bytes())),
952                ("dfc_feeCap".to_string(), Bytes::from(700_u32.to_be_bytes())),
953                ("dfc_initialFeeEnabled".to_string(), Bytes::from([0_u8])),
954                ("dfc_initialFee".to_string(), Bytes::from(0_u32.to_be_bytes())),
955            ]),
956            ..Default::default()
957        }
958    }
959
960    /// Pool whose last swap wrote an observation at `last_observation_ts`, with the initial fee
961    /// enabled (750 pips) and a dynamic component on top of a 2700 pip base.
962    ///
963    /// Built with the first-in-block assumption on: most tests here exercise the optimistic
964    /// path. The worst-case-default tests switch it back to `BlockPositionAssumption::WorstCase`.
965    fn initial_fee_pool(last_observation_ts: u32) -> AerodromeSlipstreamsState {
966        let mut pool = create_basic_test_pool();
967        pool.dfc = DynamicFeeConfig::new(2700, 30_000, 0, true, 750);
968        pool.position_assumption = BlockPositionAssumption::First;
969        pool.observations = Observations::new(vec![Observation {
970            block_timestamp: last_observation_ts,
971            initialized: true,
972            index: 0,
973            ..Default::default()
974        }]);
975        pool
976    }
977
978    /// Replays Base block 50166683 on pool 0xdFe5F275020def30993f042174Fc2D335678b626
979    /// (AERO/cbBTC), the pair of swaps from the original report:
980    ///
981    /// - tx 0x3b0a96e9bb376d74b4b99d651336c790b2b2b65a660491c28cae3df1a5d69def (index 67), the
982    ///   block's first tick-moving swap, paid the 750 pip initial fee;
983    /// - tx 0xe934500efe7f9ef56370daf4859c21c3a439d998a80b5bd2e5a117e3045021e1 (index 154) paid the
984    ///   2700 pip dynamic fee.
985    ///
986    /// Pool state is reconstructed from archive RPC at the parent block 50166682 (slot0,
987    /// liquidity, observations[213], DynamicSwapFeeModule config); swap amounts come from the
988    /// on-chain Swap events. Both outputs must match wei-exact, and the end-of-block oracle
989    /// index must match the chain (213 -> 214: exactly one observation written).
990    #[test]
991    fn replays_base_block_50166683_swap_pair_wei_exact() {
992        let mut observations: Vec<Observation> = (0..213)
993            .map(|index| Observation { index, ..Default::default() })
994            .collect();
995        observations.push(Observation {
996            block_timestamp: 1_787_122_711, // == parent block ts: the pool traded in that block
997            tick_cumulative: -18_995_710_863_218,
998            seconds_per_liquidity_cumulative_x128: U256::from_str(
999                "42501948193164408449462610706599523891176959",
1000            )
1001            .unwrap(),
1002            initialized: true,
1003            index: 213,
1004        });
1005
1006        let mut pool = AerodromeSlipstreamsState::new(
1007            "0xdFe5F275020def30993f042174Fc2D335678b626".to_string(),
1008            1_787_122_711, // seed: decoded at the parent block
1009            1_128_781_556_759_264_064u128,
1010            U256::from_str("1979649713595747421731").unwrap(),
1011            213,
1012            360,
1013            2700, // tickSpacingToFee(200)
1014            200,
1015            -350_116,
1016            // No initialized tick is crossed (liquidity is unchanged across both swaps);
1017            // zero-net bounds outside the traversed range stand in for the full tick map.
1018            vec![TickInfo::new(-351_000, 0).unwrap(), TickInfo::new(-349_000, 0).unwrap()],
1019            observations,
1020            DynamicFeeConfig::new(2700, 0, 0, true, 750),
1021        )
1022        .expect("state should build")
1023        // The replayed swap was in fact the block's first: the optimistic mode reproduces it.
1024        .with_position_assumption(BlockPositionAssumption::First);
1025
1026        // The quotes execute in block 50166683 (ts 1_787_122_713).
1027        assert!(pool.apply_block(&BlockContext::new(50_166_683, 1_787_122_713)));
1028
1029        let aero = Token::new(
1030            &Bytes::from_str("0x940181a94A35A4569E4529A3CDfB74e38FD98631").unwrap(),
1031            "AERO",
1032            18,
1033            0,
1034            &[Some(10_000)],
1035            Chain::Base,
1036            100,
1037        );
1038        let cbbtc = Token::new(
1039            &Bytes::from_str("0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf").unwrap(),
1040            "cbBTC",
1041            8,
1042            0,
1043            &[Some(10_000)],
1044            Chain::Base,
1045            100,
1046        );
1047
1048        assert_eq!(pool.fee(), 750.0 / 1_000_000.0);
1049        let first = pool
1050            .get_amount_out(BigUint::from(1_688_626u32), &cbbtc, &aero)
1051            .expect("first swap should succeed");
1052        assert_eq!(first.amount, BigUint::from(2_702_489_253_591_513_843_346u128));
1053
1054        assert_eq!(first.new_state.fee(), 2700.0 / 1_000_000.0);
1055        let second = first
1056            .new_state
1057            .get_amount_out(BigUint::from(450_733u32), &cbbtc, &aero)
1058            .expect("second swap should succeed");
1059        assert_eq!(second.amount, BigUint::from(719_894_300_964_297_656_776u128));
1060
1061        let replayed = first
1062            .new_state
1063            .as_any()
1064            .downcast_ref::<AerodromeSlipstreamsState>()
1065            .expect("state type");
1066        assert_eq!(replayed.observation_index, 214, "chain slot0 shows 214 after the block");
1067        assert_eq!(
1068            replayed
1069                .observations
1070                .timestamp_at(214, 360)
1071                .unwrap(),
1072            1_787_122_713
1073        );
1074    }
1075
1076    #[test]
1077    fn ticks_exceeded_partial_result_still_records_the_observation() {
1078        // The partial result carried inside the TicksExceeded error must price a chained swap
1079        // with the dynamic fee, exactly like a successful swap's new_state.
1080        let mut pool = initial_fee_pool(1_000);
1081        pool.apply_block(&BlockContext::new(101, 1_002));
1082        let token_a =
1083            Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
1084        let token_b =
1085            Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);
1086
1087        let err = pool
1088            .get_amount_out(
1089                BigUint::from(1_000_000_000_000_000_000_000_000u128),
1090                &token_a,
1091                &token_b,
1092            )
1093            .expect_err("swap must exhaust the tick list");
1094        let SimulationError::InvalidInput(_, Some(partial)) = err else {
1095            panic!("expected a partial result, got {err:?}");
1096        };
1097
1098        assert_eq!(partial.new_state.fee(), 2700.0 / 1_000_000.0);
1099    }
1100
1101    #[test]
1102    fn default_quotes_the_worse_fee_when_position_is_unknown() {
1103        // Without the first-in-block assumption the quote must never over-state the output:
1104        // before the pool is touched in the execution block, the worse of the two branches
1105        // (here the 2700 dynamic fee) applies — which is also the pre-fix behavior.
1106        let mut pool = initial_fee_pool(1_000);
1107        pool.position_assumption = BlockPositionAssumption::WorstCase;
1108        pool.apply_block(&BlockContext::new(101, 1_002));
1109
1110        assert_eq!(
1111            pool.get_fee()
1112                .expect("fee should be computable")
1113                .fee,
1114            2700
1115        );
1116    }
1117
1118    #[test]
1119    fn worst_case_picks_the_initial_fee_when_it_is_the_higher_one() {
1120        // Nothing stops a pool from configuring initialFee above its dynamic fee, so the worst
1121        // case is max(initial, dynamic).
1122        let mut pool = initial_fee_pool(1_000);
1123        pool.dfc = DynamicFeeConfig::new(500, 30_000, 0, true, 4_000);
1124        pool.position_assumption = BlockPositionAssumption::WorstCase;
1125        pool.apply_block(&BlockContext::new(101, 1_002));
1126
1127        assert_eq!(
1128            pool.get_fee()
1129                .expect("fee should be computable")
1130                .fee,
1131            4_000
1132        );
1133    }
1134
1135    #[test]
1136    fn worst_case_keeps_a_flat_fee_pool_quiet_across_blocks() {
1137        // With scaling 0 the worst-case fee is constant, so apply_block must never request a
1138        // re-emission: the default mode adds no per-block load for such pools.
1139        let mut pool = initial_fee_pool(1_000);
1140        pool.position_assumption = BlockPositionAssumption::WorstCase;
1141        pool.apply_block(&BlockContext::new(100, 1_000));
1142
1143        assert!(!pool.apply_block(&BlockContext::new(101, 1_002)));
1144        assert!(!pool.apply_block(&BlockContext::new(102, 1_004)));
1145    }
1146
1147    #[test]
1148    fn apply_block_reports_a_fee_flip_and_is_idempotent() {
1149        // Pool traded in block 100 (ts 1_000): decoded with execution block == that block, so the
1150        // dynamic fee applies. Crossing to the next block flips the branch to the initial fee.
1151        let mut pool = initial_fee_pool(1_000);
1152        pool.apply_block(&BlockContext::new(100, 1_000));
1153
1154        assert!(pool.apply_block(&BlockContext::new(101, 1_002)), "branch flip must re-emit");
1155        assert!(!pool.apply_block(&BlockContext::new(101, 1_002)), "repeat block is a no-op");
1156    }
1157
1158    #[test]
1159    fn apply_block_stays_quiet_while_the_fee_does_not_move() {
1160        // Idle pool: the initial fee already applies and keeps applying as blocks pass, so
1161        // consumers must not be told anything changed.
1162        let mut pool = initial_fee_pool(1_000);
1163        pool.apply_block(&BlockContext::new(101, 1_002));
1164
1165        assert!(!pool.apply_block(&BlockContext::new(102, 1_004)));
1166        assert!(!pool.apply_block(&BlockContext::new(103, 1_006)));
1167    }
1168
1169    #[test]
1170    fn quotes_initial_fee_for_the_next_block_after_the_pool_traded() {
1171        // The pool wrote its observation in the block we decoded. A quote lands in the *next*
1172        // block, where no observation exists yet — under the first-in-block assumption it pays
1173        // the initial fee.
1174        let mut pool = initial_fee_pool(1_000);
1175        pool.apply_block(&BlockContext::new(101, 1_002));
1176
1177        assert_eq!(
1178            pool.get_fee()
1179                .expect("fee should be computable")
1180                .fee,
1181            750
1182        );
1183    }
1184
1185    #[test]
1186    fn quotes_dynamic_fee_when_targeting_a_block_the_pool_already_traded_in() {
1187        // Flashblock consumer: the block is still open and the pool traded in an earlier
1188        // flashblock, so a quote landing later in the same block pays the dynamic fee.
1189        let mut pool = initial_fee_pool(1_000);
1190        pool.apply_block(&BlockContext::new(100, 1_000));
1191
1192        assert_eq!(
1193            pool.get_fee()
1194                .expect("fee should be computable")
1195                .fee,
1196            2700
1197        );
1198    }
1199
1200    #[test]
1201    fn chained_swap_in_the_same_block_pays_the_dynamic_fee() {
1202        let mut pool = initial_fee_pool(1_000);
1203        pool.apply_block(&BlockContext::new(101, 1_002));
1204        let token_a =
1205            Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
1206        let token_b =
1207            Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);
1208
1209        assert_eq!(pool.fee(), 750.0 / 1_000_000.0);
1210
1211        let result = pool
1212            .get_amount_out(BigUint::from(100_000_000_000_000_000u128), &token_a, &token_b)
1213            .expect("first swap should succeed");
1214
1215        // The first swap moved the tick, so it wrote an observation at the execution timestamp;
1216        // the pool state it hands back prices the next swap in that block as a follow-up.
1217        assert_eq!(result.new_state.fee(), 2700.0 / 1_000_000.0);
1218    }
1219
1220    #[test]
1221    fn swap_that_does_not_move_the_tick_leaves_the_initial_fee_available() {
1222        // `CLPool.swap` only writes an observation when the tick changed, so a swap that stays
1223        // inside the tick leaves the next swap in the block on the initial fee.
1224        let mut pool = initial_fee_pool(1_000);
1225        pool.apply_block(&BlockContext::new(101, 1_002));
1226
1227        pool.record_observation(pool.tick)
1228            .expect("no-op write should succeed");
1229
1230        assert_eq!(
1231            pool.get_fee()
1232                .expect("fee should be computable")
1233                .fee,
1234            750
1235        );
1236    }
1237
1238    #[test]
1239    fn initial_fee_branch_does_not_charge_the_twap_gas_overhead() {
1240        let mut pool = initial_fee_pool(1_000);
1241        pool.dfc = DynamicFeeConfig::new(2700, 30_000, 6_000_000, true, 750);
1242        pool.apply_block(&BlockContext::new(101, 1_002));
1243
1244        let resolved = pool
1245            .get_fee()
1246            .expect("fee should be computable");
1247
1248        assert_eq!(resolved, ResolvedFee { fee: 750, observed_twap: false });
1249    }
1250
1251    #[test]
1252    fn dynamic_fee_update_applies_for_supported_module() {
1253        let mut pool = create_basic_test_pool();
1254        pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
1255        let delta =
1256            dynamic_fee_delta(hex_literal::hex!("090b2A6bb475c00e2256e2095A60887cD710803b"));
1257
1258        pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1259            .expect("dynamic fee update should be valid");
1260
1261        assert_eq!(
1262            pool.get_fee()
1263                .expect("fee should be computable")
1264                .fee,
1265            500
1266        );
1267    }
1268
1269    #[test]
1270    fn dynamic_fee_update_falls_back_to_default_for_unsupported_module() {
1271        // An unsupported-module delta resets to default rather than erroring; pool keeps
1272        // default_fee.
1273        let mut pool = create_basic_test_pool();
1274        pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
1275        let delta =
1276            dynamic_fee_delta(hex_literal::hex!("DB45818A6db280ecfeB33cbeBd445423d0216b5D"));
1277
1278        pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1279            .expect("unsupported module delta should decode to the default config");
1280
1281        assert_eq!(pool.dfc, DynamicFeeConfig::default());
1282        assert_eq!(
1283            pool.get_fee()
1284                .expect("fee should be computable")
1285                .fee,
1286            3000
1287        );
1288    }
1289
1290    #[test]
1291    fn applies_partial_dynamic_fee_updates_after_module_initialization() {
1292        let mut pool = create_basic_test_pool();
1293        pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
1294        let delta = ProtocolStateDelta {
1295            component_id: "test-pool".to_string(),
1296            updated_attributes: HashMap::from([(
1297                "dfc_baseFee".to_string(),
1298                Bytes::from(500_u32.to_be_bytes()),
1299            )]),
1300            ..Default::default()
1301        };
1302
1303        pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1304            .expect("partial dynamic fee update should be valid");
1305
1306        assert_eq!(pool.dfc, DynamicFeeConfig::new(500, 10_000, 1, false, 0));
1307    }
1308
1309    #[test]
1310    fn test_partial_step_updates_tick_when_price_moves_without_crossing_initialized_tick() {
1311        let pool = create_basic_test_pool();
1312        let amount =
1313            I256::checked_from_sign_and_abs(Sign::Positive, U256::from(100_000_000_000_000_000u64))
1314                .unwrap();
1315
1316        let result = pool
1317            .swap(true, amount, None)
1318            .expect("swap should stay within the current liquidity range");
1319        let expected_tick =
1320            get_tick_at_sqrt_ratio(result.sqrt_price).expect("new sqrt price should map to a tick");
1321
1322        assert_ne!(result.sqrt_price, pool.sqrt_price);
1323        assert_ne!(result.sqrt_price, get_sqrt_ratio_at_tick(-120).unwrap());
1324        assert_ne!(expected_tick, pool.tick);
1325        assert_eq!(result.tick.value(), expected_tick);
1326    }
1327
1328    #[test]
1329    fn test_swap_keeps_boundary_tick_when_price_does_not_move() {
1330        let mut pool = create_basic_test_pool();
1331        pool.tick = -1;
1332        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1u64)).unwrap();
1333
1334        let result = pool
1335            .swap(true, amount, None)
1336            .expect("swap should consume the input as fee without moving price");
1337
1338        assert_eq!(result.sqrt_price, pool.sqrt_price);
1339        assert_eq!(get_tick_at_sqrt_ratio(result.sqrt_price).unwrap(), 0);
1340        assert_eq!(result.tick.value(), pool.tick);
1341    }
1342
1343    #[test]
1344    fn test_swap_price_limit_out_of_range_returns_error() {
1345        let pool = create_basic_test_pool();
1346        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
1347
1348        let result = pool.swap(true, amount, Some(pool.sqrt_price));
1349        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1350
1351        let result = pool.swap(true, amount, Some(MIN_SQRT_RATIO));
1352        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1353
1354        let result = pool.swap(false, amount, Some(pool.sqrt_price));
1355        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1356
1357        let result = pool.swap(false, amount, Some(MAX_SQRT_RATIO));
1358        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1359    }
1360
1361    #[test]
1362    fn test_swap_at_extreme_price_returns_error() {
1363        let sqrt_price = MIN_SQRT_RATIO + U256::from(1u64);
1364        let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
1365        let ticks =
1366            vec![TickInfo::new(MIN_TICK, 0).unwrap(), TickInfo::new(MIN_TICK + 1, 0).unwrap()];
1367        let pool = AerodromeSlipstreamsState::new(
1368            "test-pool".to_string(),
1369            1_000_000,
1370            100_000_000_000_000_000_000u128,
1371            sqrt_price,
1372            0,
1373            1,
1374            3000,
1375            1,
1376            tick,
1377            ticks,
1378            vec![Observation::default()],
1379            DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
1380        )
1381        .expect("Failed to create pool");
1382
1383        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
1384        let result = pool.swap(true, amount, None);
1385        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1386    }
1387
1388    fn token_pair() -> (Token, Token) {
1389        let token_a =
1390            Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
1391        let token_b =
1392            Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);
1393        (token_a, token_b)
1394    }
1395
1396    #[rstest]
1397    fn test_query_pool_swap_target_price_lands_in_band(#[values(true, false)] sell_a: bool) {
1398        let mut pool = create_basic_test_pool();
1399        pool.dfc = DynamicFeeConfig::new(3000, 10_000, 0, false, 0);
1400        let (token_a, token_b) = token_pair();
1401        let (token_in, token_out) =
1402            if sell_a { (&token_a, &token_b) } else { (&token_b, &token_a) };
1403        let target = pool
1404            .spot_price(token_in, token_out)
1405            .unwrap() *
1406            0.99;
1407        let tolerance = 1e-4;
1408        let params = target_price_params(
1409            token_in,
1410            token_out,
1411            to_price(target, token_in, token_out),
1412            tolerance,
1413        );
1414
1415        let swap = pool.query_pool_swap(&params).unwrap();
1416
1417        let new_spot = swap
1418            .new_state()
1419            .spot_price(token_in, token_out)
1420            .unwrap();
1421        assert!(new_spot >= target && new_spot <= target * (1.0 + tolerance), "spot {new_spot}");
1422        assert!(swap.price_points().is_none(), "the native path returns no price points");
1423        let quote = pool
1424            .get_amount_out(swap.amount_in().clone(), token_in, token_out)
1425            .unwrap();
1426        assert_eq!(&quote.amount, swap.amount_out());
1427    }
1428
1429    #[test]
1430    fn target_price_revalidates_after_initial_fee_changes() {
1431        let mut pool = initial_fee_pool(999_999);
1432        pool.ticks = Arc::new(
1433            TickList::from(
1434                1,
1435                vec![TickInfo::new(-1200, 0).unwrap(), TickInfo::new(1200, 0).unwrap()],
1436            )
1437            .unwrap(),
1438        );
1439        let (token_in, token_out) = token_pair();
1440        let target = 0.99;
1441        let tolerance = 1e-4;
1442        let params = target_price_params(
1443            &token_in,
1444            &token_out,
1445            to_price(target, &token_in, &token_out),
1446            tolerance,
1447        );
1448        let swap = pool
1449            .query_pool_swap(&params)
1450            .expect("search reaches the target using the final fee");
1451        let spot = swap
1452            .new_state()
1453            .spot_price(&token_in, &token_out)
1454            .unwrap();
1455        assert!(spot >= target && spot <= target * (1.0 + tolerance), "final spot {spot}");
1456        assert!(swap.price_points().is_some(), "fee change should trigger numerical search");
1457    }
1458
1459    /// A target less than half the tolerance below spot puts the swap limit above spot.
1460    #[test]
1461    fn test_query_pool_swap_target_price_falls_back_to_search() {
1462        let pool = create_basic_test_pool();
1463        let (token_a, token_b) = token_pair();
1464        let spot = pool
1465            .spot_price(&token_a, &token_b)
1466            .unwrap();
1467        let params = target_price_params(
1468            &token_a,
1469            &token_b,
1470            to_price(spot * (1.0 - 1e-5), &token_a, &token_b),
1471            1e-4,
1472        );
1473
1474        let swap = pool.query_pool_swap(&params).unwrap();
1475
1476        assert!(swap.price_points().is_some(), "the numerical search returns price points");
1477    }
1478
1479    #[test]
1480    fn test_query_pool_swap_target_price_at_spot() {
1481        let mut pool = create_basic_test_pool();
1482        pool.dfc = DynamicFeeConfig::new(ZERO_FEE_INDICATOR, 10_000, 0, false, 0);
1483        let (token_a, token_b) = token_pair();
1484        let params = target_price_params(
1485            &token_a,
1486            &token_b,
1487            Price::new(BigUint::from(1u64), BigUint::from(1u64)),
1488            1e-4,
1489        );
1490
1491        let swap = pool.query_pool_swap(&params).unwrap();
1492
1493        assert!(swap.amount_in().is_zero());
1494        assert!(swap.amount_out().is_zero());
1495        assert!(swap.new_state().eq(&pool));
1496    }
1497
1498    #[test]
1499    fn test_query_pool_swap_target_price_above_spot() {
1500        let pool = create_basic_test_pool();
1501        let (token_a, token_b) = token_pair();
1502        let spot = pool
1503            .spot_price(&token_a, &token_b)
1504            .unwrap();
1505        let params = target_price_params(
1506            &token_a,
1507            &token_b,
1508            to_price(spot * 1.01, &token_a, &token_b),
1509            1e-4,
1510        );
1511
1512        let result = pool.query_pool_swap(&params);
1513
1514        assert!(matches!(result, Err(SimulationError::InvalidInput(..))), "got {result:?}");
1515    }
1516}
1517
1518#[cfg(test)]
1519mod tick_list_sharing_tests {
1520    use std::collections::{HashMap, HashSet};
1521
1522    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
1523
1524    use super::*;
1525    use crate::evm::protocol::utils::uniswap::tick_math::get_sqrt_ratio_at_tick;
1526
1527    #[test]
1528    fn test_delta_transition_leaves_clones_ticks_unchanged() {
1529        let original = AerodromeSlipstreamsState::new(
1530            "test-pool".to_string(),
1531            1_000_000,
1532            100_000_000_000_000_000_000u128,
1533            get_sqrt_ratio_at_tick(0).unwrap(),
1534            0,
1535            1,
1536            3000,
1537            1,
1538            0,
1539            vec![TickInfo::new(-120, 10000).unwrap(), TickInfo::new(120, -10000).unwrap()],
1540            vec![Observation::default()],
1541            DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
1542        )
1543        .unwrap();
1544        let mut updated = original.clone();
1545        let delta = ProtocolStateDelta {
1546            component_id: "State1".to_owned(),
1547            updated_attributes: HashMap::from([(
1548                "ticks/-120/net_liquidity".to_string(),
1549                Bytes::from(20000_i128.to_be_bytes().to_vec()),
1550            )]),
1551            deleted_attributes: HashSet::new(),
1552        };
1553
1554        updated
1555            .delta_transition(delta, &HashMap::new(), &Balances::default())
1556            .unwrap();
1557
1558        assert_eq!(
1559            updated
1560                .ticks
1561                .get_tick(-120)
1562                .unwrap()
1563                .net_liquidity,
1564            20000
1565        );
1566        assert_eq!(
1567            original
1568                .ticks
1569                .get_tick(-120)
1570                .unwrap()
1571                .net_liquidity,
1572            10000
1573        );
1574    }
1575}
1576
1577#[cfg(test)]
1578mod step_cache_tests {
1579    use std::{
1580        collections::{HashMap, HashSet},
1581        str::FromStr,
1582    };
1583
1584    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
1585
1586    use super::*;
1587    use crate::evm::protocol::utils::uniswap::swap_step_cache::test_fixtures::{
1588        amount_orders, test_amounts, test_ticks, wbtc_weth, LIQUIDITY, SQRT_PRICE, TICK,
1589    };
1590
1591    fn test_pool() -> AerodromeSlipstreamsState {
1592        AerodromeSlipstreamsState::new(
1593            "test-pool".to_string(),
1594            1_000_000,
1595            LIQUIDITY,
1596            U256::from_str(SQRT_PRICE).unwrap(),
1597            0,
1598            1,
1599            500,
1600            10,
1601            TICK,
1602            test_ticks(),
1603            vec![Observation::default()],
1604            DynamicFeeConfig::new(500, 10_000, 1, false, 0),
1605        )
1606        .unwrap()
1607    }
1608
1609    /// A quote's amount, gas and new state, or its error, as text.
1610    fn format_quote_result(
1611        pool: &AerodromeSlipstreamsState,
1612        amount: &BigUint,
1613        sell: &Token,
1614        buy: &Token,
1615    ) -> String {
1616        match pool.get_amount_out(amount.clone(), sell, buy) {
1617            Ok(result) => {
1618                let state = result
1619                    .new_state
1620                    .as_any()
1621                    .downcast_ref::<AerodromeSlipstreamsState>()
1622                    .unwrap();
1623                format!(
1624                    "{} {} {} {} {}",
1625                    result.amount, result.gas, state.sqrt_price, state.tick, state.liquidity
1626                )
1627            }
1628            Err(error) => format!("error {error}"),
1629        }
1630    }
1631
1632    #[test]
1633    fn test_step_cache_quotes_match_a_fresh_state_in_any_order() {
1634        let (wbtc, weth) = wbtc_weth();
1635        for (sell, buy, smallest) in [(&wbtc, &weth, 1_000u64), (&weth, &wbtc, 1_000_000_000)] {
1636            for order in amount_orders(&test_amounts(smallest)) {
1637                let shared = test_pool();
1638                for amount in &order {
1639                    assert_eq!(
1640                        format_quote_result(&shared, amount, sell, buy),
1641                        format_quote_result(&test_pool(), amount, sell, buy),
1642                        "selling {amount} {}",
1643                        sell.symbol
1644                    );
1645                }
1646                let steps = shared
1647                    .step_cache
1648                    .min_inputs(sell < buy)
1649                    .len();
1650                assert!(steps > 2, "only {steps} steps cached");
1651            }
1652        }
1653    }
1654
1655    #[test]
1656    fn test_step_cache_quotes_match_a_fresh_state_at_each_cached_step() {
1657        let (wbtc, weth) = wbtc_weth();
1658        // Amounts that run past the last tick, so the cache covers the whole tick list. Selling
1659        // WETH needs a far larger amount to leave its first tick.
1660        for (sell, buy, doublings) in [(&wbtc, &weth, 30u32), (&weth, &wbtc, 70)] {
1661            let cached = test_pool();
1662            #[expect(
1663                clippy::let_underscore_must_use,
1664                reason = "the quote may run out of liquidity; only the step cache it fills is used"
1665            )]
1666            let _ = cached.get_amount_out(BigUint::from(10u32) << doublings, sell, buy);
1667            let boundaries = cached.step_cache.min_inputs(sell < buy);
1668            assert!(boundaries.len() > 2, "only {} steps cached", boundaries.len());
1669            for boundary in boundaries.into_iter().skip(1) {
1670                for amount in [boundary - U256::from(1u64), boundary, boundary + U256::from(1u64)] {
1671                    let amount = u256_to_biguint(amount);
1672                    assert_eq!(
1673                        format_quote_result(&cached, &amount, sell, buy),
1674                        format_quote_result(&test_pool(), &amount, sell, buy),
1675                        "selling {amount} {}",
1676                        sell.symbol
1677                    );
1678                }
1679            }
1680        }
1681    }
1682
1683    #[test]
1684    fn test_step_cache_of_a_swapped_state() {
1685        let (wbtc, weth) = wbtc_weth();
1686        let pool = test_pool();
1687        let swapped = pool
1688            .get_amount_out(BigUint::from(300_000_000u64), &wbtc, &weth)
1689            .unwrap()
1690            .new_state;
1691        let swapped = swapped
1692            .as_any()
1693            .downcast_ref::<AerodromeSlipstreamsState>()
1694            .unwrap();
1695        // A serde round trip gives the same state with an empty step cache.
1696        let fresh: AerodromeSlipstreamsState =
1697            serde_json::from_value(serde_json::to_value(swapped).unwrap()).unwrap();
1698
1699        for amount in test_amounts(1_000).iter().rev() {
1700            assert_eq!(
1701                format_quote_result(swapped, amount, &wbtc, &weth),
1702                format_quote_result(&fresh, amount, &wbtc, &weth),
1703                "selling {amount} WBTC"
1704            );
1705        }
1706    }
1707
1708    #[test]
1709    fn test_step_cache_restarts_after_delta_transition() {
1710        let (wbtc, weth) = wbtc_weth();
1711        let large = BigUint::from(3_000_000_000u64);
1712        // Only a crossed tick's liquidity changes, so the price, tick and liquidity the cache
1713        // starts from stay the same.
1714        let delta = || ProtocolStateDelta {
1715            component_id: "State1".to_owned(),
1716            updated_attributes: HashMap::from([(
1717                "ticks/255820/net_liquidity".to_string(),
1718                Bytes::from(
1719                    1_000_000_000_000_000i128
1720                        .to_be_bytes()
1721                        .to_vec(),
1722                ),
1723            )]),
1724            deleted_attributes: HashSet::new(),
1725        };
1726        let mut cached = test_pool();
1727        cached
1728            .get_amount_out(large.clone(), &wbtc, &weth)
1729            .unwrap();
1730        let mut fresh = test_pool();
1731
1732        cached
1733            .delta_transition(delta(), &HashMap::new(), &Balances::default())
1734            .unwrap();
1735        fresh
1736            .delta_transition(delta(), &HashMap::new(), &Balances::default())
1737            .unwrap();
1738
1739        assert_eq!(
1740            format_quote_result(&cached, &large, &wbtc, &weth),
1741            format_quote_result(&fresh, &large, &wbtc, &weth)
1742        );
1743    }
1744}