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