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_slot, 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 the module reads the oracle (`observed_twap`, whatever the scaling factor), fee() does a
69// TWAP binary search on the observation ring buffer (~77k–91k gas) instead of a simple slot read
70// (~18k–27k gas). This extra cost is 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    /// The oracle observations. The ring is shared by this state, its clones and the states its
116    /// swaps return; a swap records its observation in the state's own overlay (see
117    /// [`Observations`]), so a quote copies no ring.
118    observations: Observations,
119    dfc: DynamicFeeConfig,
120    /// Fee settings of an AERO v1.1 pool, whose swap hook sets the fee instead of a fee module.
121    /// When set, `dfc` is unused.
122    #[serde(default)]
123    aero_hook: Option<AeroHookFee>,
124    /// What quotes may assume about the swap's position within its execution block; see
125    /// [`BlockPositionAssumption`].
126    position_assumption: BlockPositionAssumption,
127}
128
129impl AerodromeSlipstreamsState {
130    /// Creates a new instance of `AerodromeSlipstreamsState`.
131    ///
132    /// # Arguments
133    /// - `id`: The id of the protocol component.
134    /// - `execution_block_timestamp`: Timestamp of the block a quote is expected to execute in.
135    /// - `liquidity`: The initial liquidity of the pool.
136    /// - `sqrt_price`: The square root of the current price.
137    /// - `observation_index`: The index of the current observation.
138    /// - `observation_cardinality`: The cardinality of the observation.
139    /// - `default_fee`: The default fee for the pool.
140    /// - `tick_spacing`: The tick spacing for the pool.
141    /// - `tick`: The current tick of the pool.
142    /// - `ticks`: A vector of `TickInfo` representing the tick information for the pool.
143    /// - `observations`: A vector of `Observation` representing the observation information for the
144    ///   pool.
145    /// - `dfc`: The dynamic fee configuration for the pool.
146    #[expect(
147        clippy::too_many_arguments,
148        reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
149    )]
150    pub fn new(
151        id: String,
152        execution_block_timestamp: u64,
153        liquidity: u128,
154        sqrt_price: U256,
155        observation_index: u16,
156        observation_cardinality: u16,
157        default_fee: u32,
158        tick_spacing: i32,
159        tick: i32,
160        ticks: Vec<TickInfo>,
161        observations: Vec<Observation>,
162        dfc: DynamicFeeConfig,
163    ) -> Result<Self, SimulationError> {
164        let tick_list_spacing = u16::try_from(tick_spacing).map_err(|e| {
165            SimulationError::InvalidInput(format!("Invalid tick spacing {tick_spacing}: {e}"), None)
166        })?;
167        let tick_list = TickList::from(tick_list_spacing, ticks)?;
168        Ok(AerodromeSlipstreamsState {
169            id,
170            execution_block_timestamp,
171            execution_block_number: 0,
172            liquidity,
173            sqrt_price,
174            observation_index,
175            observation_cardinality,
176            default_fee,
177            tick_spacing,
178            tick,
179            ticks: Arc::new(tick_list),
180            step_cache: SwapStepCache::default(),
181            observations: Observations::new(observations),
182            dfc,
183            aero_hook: None,
184            position_assumption: BlockPositionAssumption::default(),
185        })
186    }
187
188    /// Prices swaps with an AERO v1.1 swap hook instead of the dynamic fee module.
189    pub fn with_aero_hook(mut self, hook: AeroHookFee) -> Self {
190        self.aero_hook = Some(hook);
191        self
192    }
193
194    /// Sets what quotes assume about the swap's position within its execution block.
195    ///
196    /// A consumer-side preference, independent of the pool's on-chain state.
197    pub fn with_position_assumption(mut self, assumption: BlockPositionAssumption) -> Self {
198        self.position_assumption = assumption;
199        self
200    }
201
202    fn get_fee(&self) -> Result<ResolvedFee, SimulationError> {
203        if let Some(hook) = &self.aero_hook {
204            let fee = self.hook_fee(hook)?;
205            return Ok(ResolvedFee { fee: fee.fee, observed_twap: fee.observed_twap });
206        }
207        get_dynamic_fee(
208            &self.dfc,
209            self.default_fee,
210            self.tick,
211            self.liquidity,
212            self.observation_index,
213            self.observation_cardinality,
214            &self.observations,
215            oracle_timestamp(self.execution_block_timestamp),
216            self.position_assumption == BlockPositionAssumption::First,
217        )
218    }
219
220    fn hook_fee(&self, hook: &AeroHookFee) -> Result<HookFee, SimulationError> {
221        hook.resolve(
222            &PoolOracle {
223                tick: self.tick,
224                liquidity: self.liquidity,
225                observation_index: self.observation_index,
226                observation_cardinality: self.observation_cardinality,
227                observations: &self.observations,
228            },
229            self.default_fee,
230            Execution {
231                block: self.execution_block_number,
232                timestamp: oracle_timestamp(self.execution_block_timestamp),
233                first_in_block: self.position_assumption == BlockPositionAssumption::First,
234            },
235        )
236    }
237
238    /// Records the observation the pool would write for a swap that moved the tick from
239    /// `self.tick` to `post_swap_tick`, so that a second swap chained onto this state in the same
240    /// block resolves the dynamic fee instead of the initial fee.
241    ///
242    /// Mirrors `CLPool.swap`, which writes only when the tick moved and passes the pre-swap tick
243    /// and liquidity. Must be called before the caller overwrites `tick`/`liquidity`.
244    fn record_observation(&mut self, post_swap_tick: i32) -> Result<(), SimulationError> {
245        if post_swap_tick == self.tick {
246            return Ok(());
247        }
248        self.observation_index = self.observations.write(
249            self.observation_index,
250            oracle_timestamp(self.execution_block_timestamp),
251            self.tick,
252            self.liquidity,
253            self.observation_cardinality,
254        )?;
255        Ok(())
256    }
257
258    /// Swaps token_in until `spot_price(token_in, token_out)` reaches the middle of the band
259    /// `[target, target * (1 + tolerance)]`. Falls back to numerical search if recording the
260    /// observation changes the fee enough to move the final price outside the band.
261    fn swap_to_target_price(
262        &self,
263        params: &QueryPoolSwapParams,
264        target: &Price,
265        tolerance: f64,
266    ) -> Result<PoolSwap, SimulationError> {
267        let token_in = params.token_in();
268        let token_out = params.token_out();
269        let target_f64 = price_to_f64_with_decimals(target, token_in.decimals, token_out.decimals)?;
270        if target_f64 == self.spot_price(token_in, token_out)? {
271            return Ok(PoolSwap::new(BigUint::ZERO, BigUint::ZERO, Box::new(self.clone()), None));
272        }
273        let Some(limit) = raw_target_price(target, tolerance, self.get_fee()?.fee) else {
274            return crate::evm::query_pool_swap::query_pool_swap(self, params);
275        };
276        // `limit` already strips the fee that `spot_price` adds, so the swap uses fee 0.
277        let Ok((amount_in, amount_out, result)) = clmm_swap_to_price(
278            self.sqrt_price,
279            &token_in.address,
280            &token_out.address,
281            &limit,
282            0,
283            Sign::Positive,
284            |zero_for_one, amount_specified, sqrt_price_limit| {
285                self.swap(zero_for_one, amount_specified, Some(sqrt_price_limit))
286            },
287        ) else {
288            return crate::evm::query_pool_swap::query_pool_swap(self, params);
289        };
290
291        let new_state = if amount_in.is_zero() {
292            self.clone()
293        } else {
294            let (state, observation) =
295                self.clone_post_swap(result.sqrt_price, result.tick.value(), result.liquidity);
296            observation?;
297            state
298        };
299        let final_spot = new_state.spot_price(token_in, token_out)?;
300        if final_spot < target_f64 || final_spot > target_f64 * (1.0 + tolerance) {
301            return crate::evm::query_pool_swap::query_pool_swap(self, params);
302        }
303        Ok(PoolSwap::new(amount_in, amount_out, Box::new(new_state), None))
304    }
305
306    /// A clone of this state with the final price, tick and liquidity of a swap, an empty step
307    /// cache, and the price observation the swap writes. Returns the result of the observation
308    /// write beside the state, so a caller can decide whether a failed write is an error.
309    fn clone_post_swap(
310        &self,
311        sqrt_price: U256,
312        tick: i32,
313        liquidity: u128,
314    ) -> (Self, Result<(), SimulationError>) {
315        let mut state = self.clone();
316        state.step_cache = SwapStepCache::default();
317        // The block's first swap stores the block fee every later swap in the block pays.
318        if let (Some(hook), Some(state_hook)) = (&self.aero_hook, state.aero_hook.as_mut()) {
319            match self.hook_fee(hook) {
320                Ok(HookFee { block_fee_to_store: Some(fee), .. }) => {
321                    state_hook.store_block_fee(self.execution_block_number, fee)
322                }
323                Ok(_) => {}
324                Err(err) => return (state, Err(err)),
325            }
326        }
327        let observation = state.record_observation(tick);
328        state.liquidity = liquidity;
329        state.tick = tick;
330        state.sqrt_price = sqrt_price;
331        (state, observation)
332    }
333
334    fn swap(
335        &self,
336        zero_for_one: bool,
337        amount_specified: I256,
338        sqrt_price_limit: Option<U256>,
339    ) -> Result<SwapResults, SimulationError> {
340        if self.liquidity == 0 {
341            return Err(SimulationError::RecoverableError("No liquidity".to_string()));
342        }
343        let price_limit = if let Some(limit) = sqrt_price_limit {
344            limit
345        } else if zero_for_one {
346            safe_add_u256(MIN_SQRT_RATIO, U256::from(1u64))?
347        } else {
348            safe_sub_u256(MAX_SQRT_RATIO, U256::from(1u64))?
349        };
350
351        let price_limit_valid = if zero_for_one {
352            price_limit > MIN_SQRT_RATIO && price_limit < self.sqrt_price
353        } else {
354            price_limit < MAX_SQRT_RATIO && price_limit > self.sqrt_price
355        };
356        if !price_limit_valid {
357            return Err(SimulationError::InvalidInput("Price limit out of range".into(), None));
358        }
359
360        let exact_input = amount_specified > I256::from_raw(U256::from(0u64));
361
362        let mut state = SwapState {
363            amount_remaining: amount_specified,
364            amount_calculated: I256::from_raw(U256::from(0u64)),
365            sqrt_price: self.sqrt_price,
366            tick: self.tick.into(),
367            liquidity: self.liquidity,
368        };
369        let resolved_fee = self.get_fee()?;
370        let twap_overhead = if self.aero_hook.is_some() {
371            AERO_HOOK_GAS
372        } else if resolved_fee.observed_twap {
373            TWAP_FEE_OVERHEAD
374        } else {
375            0
376        };
377        let mut gas_used = U256::from(SWAP_BASE_GAS + twap_overhead);
378        let mut n_loops = 0;
379
380        let fee = resolved_fee.fee;
381        // Only exact-input swaps with no price limit use the step cache. The cache finds a step by
382        // its input, which an exact-output swap does not know. A cached step can also lie past a
383        // price limit.
384        let cache_key = if exact_input && sqrt_price_limit.is_none() {
385            StepCacheKey::new(self.sqrt_price, state.tick.value(), self.liquidity, fee, gas_used)
386        } else {
387            None
388        };
389        let mut cache_run = StepCacheRun::new(
390            &self.step_cache,
391            zero_for_one,
392            cache_key,
393            amount_specified.unsigned_abs(),
394        );
395        if let Some(progress) = cache_run.apply_cached_progress(&mut state) {
396            gas_used = progress.gas;
397            // The first loop's overhead is in the cached gas already.
398            n_loops = progress.steps_taken;
399        }
400        while state.amount_remaining != I256::from_raw(U256::from(0u64)) &&
401            state.sqrt_price != price_limit
402        {
403            let (mut next_tick, next_tick_info) = match self
404                .ticks
405                .next_initialized_tick_within_one_word(state.tick.value(), zero_for_one)
406            {
407                Ok((tick, info)) => (tick, info),
408                Err(tick_err) => match tick_err.kind {
409                    TickListErrorKind::TicksExeeded => {
410                        let (new_state, observation) = self.clone_post_swap(
411                            state.sqrt_price,
412                            state.tick.value(),
413                            state.liquidity,
414                        );
415                        // Best effort in an error path: a failed write only degrades the fee of
416                        // a chained simulation on this partial result, and must not mask the
417                        // more informative TicksExceeded error below.
418                        if let Err(record_err) = observation {
419                            trace!(%record_err, "skipping observation write on partial result");
420                        }
421                        return Err(SimulationError::InvalidInput(
422                            "Ticks exceeded".into(),
423                            Some(GetAmountOutResult::new(
424                                u256_to_biguint(state.amount_calculated.abs().into_raw()),
425                                u256_to_biguint(gas_used),
426                                Box::new(new_state),
427                            )),
428                        ));
429                    }
430                    TickListErrorKind::BelowSmallest | TickListErrorKind::AtOrAboveLargest => {
431                        return Err(SimulationError::FatalError("Unknown error".to_string()))
432                    }
433                },
434            };
435
436            next_tick = next_tick.clamp(MIN_TICK, MAX_TICK);
437
438            let sqrt_price_start = state.sqrt_price;
439            let sqrt_price_next = match next_tick_info {
440                Some(info) => info.sqrt_price,
441                None => get_sqrt_ratio_at_tick_cached(next_tick)?,
442            };
443            let SwapStepResult { sqrt_price, amount_in_with_fee, amount_out } =
444                swap_math::compute_swap_step(
445                    state.sqrt_price,
446                    AerodromeSlipstreamsState::get_sqrt_ratio_target(
447                        sqrt_price_next,
448                        price_limit,
449                        zero_for_one,
450                    ),
451                    state.liquidity,
452                    state.amount_remaining,
453                    fee,
454                )?;
455            state.sqrt_price = sqrt_price;
456
457            let step = StepComputation {
458                sqrt_price_start,
459                tick_next: next_tick,
460                sqrt_price_next,
461                amount_in_with_fee,
462                amount_out,
463            };
464            if exact_input {
465                state.amount_remaining -=
466                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
467                        .unwrap();
468                state.amount_calculated -=
469                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
470            } else {
471                state.amount_remaining +=
472                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
473                state.amount_calculated +=
474                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
475                        .unwrap();
476            }
477            if state.sqrt_price == step.sqrt_price_next {
478                if let Some(info) = next_tick_info {
479                    let liquidity_raw = info.net_liquidity;
480                    let liquidity_net = if zero_for_one { -liquidity_raw } else { liquidity_raw };
481                    state.liquidity =
482                        liquidity_math::add_liquidity_delta(state.liquidity, liquidity_net)?;
483                    gas_used = safe_add_u256(gas_used, U256::from(TICK_CROSSING_GAS_COST))?;
484                }
485                state.tick =
486                    PoolTick::from(if zero_for_one { step.tick_next - 1 } else { step.tick_next });
487            } else if state.sqrt_price != step.sqrt_price_start {
488                state.tick = PoolTick::at_sqrt_price(state.sqrt_price)?;
489            }
490            gas_used = safe_add_u256(gas_used, U256::from(LOOP_GAS_COST))?;
491            if n_loops == 0 {
492                gas_used = safe_add_u256(gas_used, U256::from(FIRST_LOOP_OVERHEAD))?;
493            }
494            n_loops += 1;
495            cache_run.cache_progress(&step, &state, gas_used);
496        }
497        Ok(SwapResults {
498            amount_calculated: state.amount_calculated,
499            amount_specified,
500            amount_remaining: state.amount_remaining,
501            sqrt_price: state.sqrt_price,
502            liquidity: state.liquidity,
503            tick: state.tick,
504            gas_used,
505        })
506    }
507
508    fn get_sqrt_ratio_target(
509        sqrt_price_next: U256,
510        sqrt_price_limit: U256,
511        zero_for_one: bool,
512    ) -> U256 {
513        let cond1 = if zero_for_one {
514            sqrt_price_next < sqrt_price_limit
515        } else {
516            sqrt_price_next > sqrt_price_limit
517        };
518
519        if cond1 {
520            sqrt_price_limit
521        } else {
522            sqrt_price_next
523        }
524    }
525}
526
527#[typetag::serde]
528impl ProtocolSim for AerodromeSlipstreamsState {
529    fn fee(&self) -> f64 {
530        match self.get_fee() {
531            Ok(resolved) => resolved.fee as f64 / 1_000_000.0,
532            Err(err) => {
533                error!(
534                    pool = %self.id,
535                    execution_block_timestamp = self.execution_block_timestamp,
536                    %err,
537                    "Error while calculating dynamic fee"
538                );
539                f64::MAX / 1_000_000.0
540            }
541        }
542    }
543
544    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
545        let price = if base < quote {
546            sqrt_price_q96_to_f64(self.sqrt_price, base.decimals, quote.decimals)?
547        } else {
548            1.0f64 / sqrt_price_q96_to_f64(self.sqrt_price, quote.decimals, base.decimals)?
549        };
550        Ok(add_fee_markup(price, self.get_fee()?.fee as f64 / 1_000_000.0))
551    }
552
553    fn get_amount_out(
554        &self,
555        amount_in: BigUint,
556        token_in: &Token,
557        token_out: &Token,
558    ) -> Result<GetAmountOutResult, SimulationError> {
559        let zero_for_one = token_in < token_out;
560        let amount_specified = I256::checked_from_sign_and_abs(
561            Sign::Positive,
562            U256::from_be_slice(&amount_in.to_bytes_be()),
563        )
564        .ok_or_else(|| {
565            SimulationError::InvalidInput("I256 overflow: amount_in".to_string(), None)
566        })?;
567
568        let result = self.swap(zero_for_one, amount_specified, None)?;
569
570        trace!(?amount_in, ?token_in, ?token_out, ?zero_for_one, ?result, "SLIPSTREAMS SWAP");
571        let (new_state, observation) =
572            self.clone_post_swap(result.sqrt_price, result.tick.value(), result.liquidity);
573        observation?;
574
575        Ok(GetAmountOutResult::new(
576            u256_to_biguint(
577                result
578                    .amount_calculated
579                    .abs()
580                    .into_raw(),
581            ),
582            u256_to_biguint(result.gas_used),
583            Box::new(new_state),
584        ))
585    }
586
587    fn get_limits(
588        &self,
589        sell_token: Bytes,
590        buy_token: Bytes,
591    ) -> Result<(BigUint, BigUint), SimulationError> {
592        // If the pool has no liquidity, return zeros for both limits
593        if self.liquidity == 0 {
594            return Ok((BigUint::zero(), BigUint::zero()));
595        }
596        // The limits do not depend on the fee, but a quote does: a pool whose fee cannot be
597        // resolved fails every quote, so it reports no limits to size one from.
598        self.get_fee()?;
599
600        let zero_for_one = sell_token < buy_token;
601        let mut current_tick = self.tick;
602        let mut current_sqrt_price = self.sqrt_price;
603        let mut current_liquidity = self.liquidity;
604        let mut total_amount_in = U256::from(0u64);
605        let mut total_amount_out = U256::from(0u64);
606
607        // Iterate through all ticks in the direction of the swap
608        // Continues until there is no more liquidity in the pool or no more ticks to process
609        let mut ticks_crossed: u64 = 0;
610        while let Ok((tick, next_tick_info)) = self
611            .ticks
612            .next_initialized_tick_within_one_word(current_tick, zero_for_one)
613        {
614            if ticks_crossed >= MAX_TICKS_CROSSED {
615                break;
616            }
617            ticks_crossed += 1;
618            // Clamp the tick value to ensure it's within valid range
619            let next_tick = tick.clamp(MIN_TICK, MAX_TICK);
620
621            let sqrt_price_next = match next_tick_info {
622                Some(info) => info.sqrt_price,
623                None => get_sqrt_ratio_at_tick_cached(next_tick)?,
624            };
625
626            // Calculate the amount of tokens swapped when moving from current_sqrt_price to
627            // sqrt_price_next. Direction determines which token is being swapped in vs out
628            let (amount_in, amount_out) = if zero_for_one {
629                let amount0 = get_amount0_delta(
630                    sqrt_price_next,
631                    current_sqrt_price,
632                    current_liquidity,
633                    true,
634                )?;
635                let amount1 = get_amount1_delta(
636                    sqrt_price_next,
637                    current_sqrt_price,
638                    current_liquidity,
639                    false,
640                )?;
641                (amount0, amount1)
642            } else {
643                let amount0 = get_amount0_delta(
644                    sqrt_price_next,
645                    current_sqrt_price,
646                    current_liquidity,
647                    false,
648                )?;
649                let amount1 = get_amount1_delta(
650                    sqrt_price_next,
651                    current_sqrt_price,
652                    current_liquidity,
653                    true,
654                )?;
655                (amount1, amount0)
656            };
657
658            // Accumulate total amounts for this tick range
659            total_amount_in = safe_add_u256(total_amount_in, amount_in)?;
660            total_amount_out = safe_add_u256(total_amount_out, amount_out)?;
661
662            // If this tick is "initialized" (meaning its someone's position boundary), update the
663            // liquidity when crossing it
664            // For zero_for_one, liquidity is removed when crossing a tick
665            // For one_for_zero, liquidity is added when crossing a tick
666            if let Some(info) = next_tick_info {
667                let liquidity_raw = info.net_liquidity;
668                let liquidity_delta = if zero_for_one { -liquidity_raw } else { liquidity_raw };
669                current_liquidity =
670                    liquidity_math::add_liquidity_delta(current_liquidity, liquidity_delta)?;
671            }
672
673            // Move to the next tick position
674            current_tick = if zero_for_one { next_tick - 1 } else { next_tick };
675            current_sqrt_price = sqrt_price_next;
676        }
677
678        Ok((u256_to_biguint(total_amount_in), u256_to_biguint(total_amount_out)))
679    }
680
681    fn delta_transition(
682        &mut self,
683        delta: ProtocolStateDelta,
684        _tokens: &HashMap<Bytes, Token>,
685        _balances: &Balances,
686    ) -> Result<(), TransitionError> {
687        // Swap steps taken from the old state do not hold for the new one.
688        self.step_cache = SwapStepCache::default();
689        // apply attribute changes
690        if let Some(liquidity) = delta
691            .updated_attributes
692            .get("liquidity")
693        {
694            // This is a hotfix because if the liquidity has never been updated after creation, it's
695            // currently encoded as H256::zero(), therefore, we can't decode this as u128.
696            // We can remove this once it has been fixed on the tycho side.
697            let liq_16_bytes = if liquidity.len() == 32 {
698                // Make sure it only happens for 0 values, otherwise error.
699                if liquidity == &Bytes::zero(32) {
700                    Bytes::from([0; 16])
701                } else {
702                    return Err(TransitionError::DecodeError(format!(
703                        "Liquidity bytes too long for {liquidity}, expected 16",
704                    )));
705                }
706            } else {
707                liquidity.clone()
708            };
709
710            self.liquidity = u128::try_from(liq_16_bytes)?;
711        }
712        if let Some(sqrt_price) = delta
713            .updated_attributes
714            .get("sqrt_price_x96")
715        {
716            self.sqrt_price = U256::from_be_slice(sqrt_price);
717        }
718        if let Some(observation_index) = delta
719            .updated_attributes
720            .get("observationIndex")
721        {
722            self.observation_index = u16::try_from(observation_index.clone())?;
723        }
724        if let Some(observation_cardinality) = delta
725            .updated_attributes
726            .get("observationCardinality")
727        {
728            self.observation_cardinality = u16::try_from(observation_cardinality.clone())?;
729        }
730        if let Some(default_fee) = delta
731            .updated_attributes
732            .get("default_fee")
733        {
734            self.default_fee = u32::try_from(default_fee.clone())?;
735        }
736        if let Some(hook) = self.aero_hook.as_mut() {
737            hook.update_from_attributes(&delta.updated_attributes)
738                .map_err(TransitionError::DecodeError)?;
739        } else {
740            self.dfc
741                .update_from_attributes(&delta.updated_attributes)
742                .map_err(|err| {
743                    TransitionError::DecodeError(format!(
744                        "Failed to update dynamic fee module config: {err}"
745                    ))
746                })?;
747        }
748        if let Some(tick) = delta.updated_attributes.get("tick") {
749            // This is a hotfix because if the tick has never been updated after creation, it's
750            // currently encoded as H256::zero(), therefore, we can't decode this as i32.
751            // We can remove this once it has been fixed on the tycho side.
752            let ticks_4_bytes = if tick.len() == 32 {
753                // Make sure it only happens for 0 values, otherwise error.
754                if tick == &Bytes::zero(32) {
755                    Bytes::from([0; 4])
756                } else {
757                    return Err(TransitionError::DecodeError(format!(
758                        "Tick bytes too long for {tick}, expected 4"
759                    )));
760                }
761            } else {
762                tick.clone()
763            };
764            self.tick = i24_be_bytes_to_i32(&ticks_4_bytes);
765        }
766
767        // apply tick & observations changes
768        for (key, value) in delta.updated_attributes.iter() {
769            // tick liquidity keys are in the format "ticks/{tick_index}/net_liquidity"
770            if key.starts_with("ticks/") {
771                let parts: Vec<&str> = key.split('/').collect();
772                Arc::make_mut(&mut self.ticks)
773                    .set_tick_liquidity(
774                        parts[1]
775                            .parse::<i32>()
776                            .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
777                        i128::try_from(value.clone())?,
778                    )
779                    .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
780            }
781
782            if let Some(slot) = observation_slot(key) {
783                let slot = slot.map_err(TransitionError::DecodeError)?;
784                self.observations
785                    .upsert_observation(slot, value)
786                    .map_err(|err| TransitionError::DecodeError(format!("{key}: {err}")))?;
787            }
788        }
789        // delete ticks - ignores deletes for attributes other than tick liquidity
790        for key in delta.deleted_attributes.iter() {
791            // tick liquidity keys are in the format "ticks/{tick_index}/net_liquidity"
792            if key.starts_with("ticks/") {
793                let parts: Vec<&str> = key.split('/').collect();
794                Arc::make_mut(&mut self.ticks)
795                    .set_tick_liquidity(
796                        parts[1]
797                            .parse::<i32>()
798                            .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
799                        0,
800                    )
801                    .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
802            }
803
804            if let Some(slot) = observation_slot(key) {
805                let slot = slot.map_err(TransitionError::DecodeError)?;
806                self.observations
807                    .upsert_observation(slot, &[])
808                    .map_err(|err| TransitionError::DecodeError(format!("{key}: {err}")))?;
809            }
810        }
811        Ok(())
812    }
813
814    /// Re-emits only when the resolved fee actually changed: idle pools whose initial-vs-dynamic
815    /// branch stays put return `false` indefinitely, and same-block flashblocks short-circuit on
816    /// the unchanged timestamp.
817    fn apply_block(&mut self, block: &BlockContext) -> bool {
818        let timestamp = block.timestamp();
819        if timestamp == self.execution_block_timestamp &&
820            block.number() == self.execution_block_number
821        {
822            return false;
823        }
824        let fee_before = self.get_fee().ok();
825        self.execution_block_timestamp = timestamp;
826        self.execution_block_number = block.number();
827        fee_before != self.get_fee().ok()
828    }
829
830    fn clone_box(&self) -> Box<dyn ProtocolSim> {
831        Box::new(self.clone())
832    }
833
834    fn as_any(&self) -> &dyn Any {
835        self
836    }
837
838    fn as_any_mut(&mut self) -> &mut dyn Any {
839        self
840    }
841
842    fn eq(&self, other: &dyn ProtocolSim) -> bool {
843        if let Some(other_state) = other
844            .as_any()
845            .downcast_ref::<AerodromeSlipstreamsState>()
846        {
847            let Ok(self_fee) = self.get_fee() else { return false };
848            let Ok(other_fee) = other_state.get_fee() else { return false };
849
850            self.liquidity == other_state.liquidity &&
851                self.sqrt_price == other_state.sqrt_price &&
852                self_fee == other_fee &&
853                self.tick == other_state.tick &&
854                self.ticks == other_state.ticks
855        } else {
856            false
857        }
858    }
859
860    /// Answers [`SwapConstraint::PoolTargetPrice`] with one native swap and no `price_points`.
861    /// [`SwapConstraint::TradeLimitPrice`] uses the numerical search.
862    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
863        match params.swap_constraint() {
864            SwapConstraint::TradeLimitPrice { .. } => {
865                crate::evm::query_pool_swap::query_pool_swap(self, params)
866            }
867            SwapConstraint::PoolTargetPrice {
868                target,
869                tolerance,
870                min_amount_in: _,
871                max_amount_in: _,
872            } => {
873                let swap = self.swap_to_target_price(params, target, *tolerance)?;
874                let target = price_to_f64_with_decimals(
875                    target,
876                    params.token_in().decimals,
877                    params.token_out().decimals,
878                )?;
879                let spot = swap
880                    .new_state()
881                    .spot_price(params.token_in(), params.token_out())?;
882                if !tolerance.is_finite() ||
883                    *tolerance < 0.0 ||
884                    !(spot >= target && spot <= target * (1.0 + tolerance))
885                {
886                    return Err(SimulationError::RecoverableError(
887                        "Aerodrome target-price search ended outside the requested tolerance"
888                            .into(),
889                    ));
890                }
891                Ok(swap)
892            }
893        }
894    }
895}
896
897#[cfg(test)]
898#[path = "aero_cl_replay_tests.rs"]
899mod aero_cl_replay_tests;
900
901#[cfg(test)]
902mod tests {
903    use std::str::FromStr;
904
905    use alloy::primitives::{Sign, I256, U256};
906    use rstest::rstest;
907    use tycho_common::{models::Chain, simulation::errors::SimulationError};
908
909    use super::*;
910    use crate::evm::{
911        protocol::utils::{
912            slipstreams::{
913                dynamic_fee_module::{DynamicFeeConfig, ZERO_FEE_INDICATOR},
914                observations::Observation,
915            },
916            uniswap::{
917                tick_list::TickInfo,
918                tick_math::{
919                    get_sqrt_ratio_at_tick, get_tick_at_sqrt_ratio, MAX_SQRT_RATIO, MIN_SQRT_RATIO,
920                    MIN_TICK,
921                },
922            },
923        },
924        query_pool_swap::test_helpers::{target_price_params, to_price},
925    };
926
927    fn create_basic_test_pool() -> AerodromeSlipstreamsState {
928        let sqrt_price = get_sqrt_ratio_at_tick(0).expect("Failed to calculate sqrt price");
929        let ticks = vec![TickInfo::new(-120, 0).unwrap(), TickInfo::new(120, 0).unwrap()];
930        AerodromeSlipstreamsState::new(
931            "test-pool".to_string(),
932            1_000_000,
933            100_000_000_000_000_000_000u128,
934            sqrt_price,
935            0,
936            1,
937            3000,
938            1,
939            0,
940            ticks,
941            vec![Observation::default()],
942            DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
943        )
944        .expect("Failed to create pool")
945    }
946
947    fn dynamic_fee_delta(dynamic_fee_module: [u8; 20]) -> ProtocolStateDelta {
948        ProtocolStateDelta {
949            component_id: "test-pool".to_string(),
950            updated_attributes: HashMap::from([
951                ("dynamic_fee_module".to_string(), Bytes::from(dynamic_fee_module)),
952                ("dfc_baseFee".to_string(), Bytes::from(500_u32.to_be_bytes())),
953                ("dfc_scalingFactor".to_string(), Bytes::from(0_u64.to_be_bytes())),
954                ("dfc_feeCap".to_string(), Bytes::from(700_u32.to_be_bytes())),
955                ("dfc_initialFeeEnabled".to_string(), Bytes::from([0_u8])),
956                ("dfc_initialFee".to_string(), Bytes::from(0_u32.to_be_bytes())),
957            ]),
958            ..Default::default()
959        }
960    }
961
962    /// Pool whose last swap wrote an observation at `last_observation_ts`, with the initial fee
963    /// enabled (750 pips) and a dynamic component on top of a 2700 pip base.
964    ///
965    /// Built with the first-in-block assumption on: most tests here exercise the optimistic
966    /// path. The worst-case-default tests switch it back to `BlockPositionAssumption::WorstCase`.
967    fn initial_fee_pool(last_observation_ts: u32) -> AerodromeSlipstreamsState {
968        let mut pool = create_basic_test_pool();
969        pool.dfc = DynamicFeeConfig::new(2700, 30_000, 0, true, 750);
970        pool.position_assumption = BlockPositionAssumption::First;
971        pool.observations = Observations::new(vec![Observation {
972            block_timestamp: last_observation_ts,
973            initialized: true,
974            ..Default::default()
975        }]);
976        pool
977    }
978
979    /// Replays Base block 50166683 on pool 0xdFe5F275020def30993f042174Fc2D335678b626
980    /// (AERO/cbBTC), the pair of swaps from the original report:
981    ///
982    /// - tx 0x3b0a96e9bb376d74b4b99d651336c790b2b2b65a660491c28cae3df1a5d69def (index 67), the
983    ///   block's first tick-moving swap, paid the 750 pip initial fee;
984    /// - tx 0xe934500efe7f9ef56370daf4859c21c3a439d998a80b5bd2e5a117e3045021e1 (index 154) paid the
985    ///   2700 pip dynamic fee.
986    ///
987    /// Pool state is reconstructed from archive RPC at the parent block 50166682 (slot0,
988    /// liquidity, observations[213], DynamicSwapFeeModule config); swap amounts come from the
989    /// on-chain Swap events. Both outputs must match wei-exact, and the end-of-block oracle
990    /// index must match the chain (213 -> 214: exactly one observation written).
991    #[test]
992    fn replays_base_block_50166683_swap_pair_wei_exact() {
993        // The fixture carries only the newest slot: at a zero scaling factor the module's fee does
994        // not depend on the oracle, and the swap's `write` reads only the current slot.
995        let mut observations = vec![Observation::default(); 213];
996        observations.push(Observation {
997            block_timestamp: 1_787_122_711, // == parent block ts: the pool traded in that block
998            tick_cumulative: -18_995_710_863_218,
999            seconds_per_liquidity_cumulative_x128: U256::from_str(
1000                "42501948193164408449462610706599523891176959",
1001            )
1002            .unwrap(),
1003            initialized: true,
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 ring_that_cannot_answer_observe_fails_limits_like_quotes() {
1103        // A non-zero scaling factor, with the slots around the 600 s target missing from this
1104        // copy of the ring: the fee is unknown, so no quote can be given and no limit either.
1105        let mut pool = create_basic_test_pool();
1106        pool.dfc = DynamicFeeConfig::new(0, 10_000, 1_000_000, false, 0);
1107        pool.observation_index = 5;
1108        pool.observation_cardinality = 300;
1109        let mut slots = vec![Observation::default(); 7];
1110        slots[5] =
1111            Observation { block_timestamp: 999_990, initialized: true, ..Default::default() };
1112        slots[6] =
1113            Observation { block_timestamp: 999_000, initialized: true, ..Default::default() };
1114        pool.observations = Observations::new(slots);
1115        let token_a =
1116            Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
1117        let token_b =
1118            Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);
1119
1120        assert!(pool.get_fee().is_err());
1121        assert!(pool
1122            .spot_price(&token_a, &token_b)
1123            .is_err());
1124        assert!(pool
1125            .get_amount_out(BigUint::from(1_000u32), &token_a, &token_b)
1126            .is_err());
1127        assert!(pool
1128            .get_limits(token_a.address, token_b.address)
1129            .is_err());
1130    }
1131
1132    #[test]
1133    fn default_quotes_the_worse_fee_when_position_is_unknown() {
1134        // Without the first-in-block assumption the quote must never over-state the output:
1135        // before the pool is touched in the execution block, the worse of the two branches
1136        // (here the 2700 dynamic fee) applies — which is also the pre-fix behavior.
1137        let mut pool = initial_fee_pool(1_000);
1138        pool.position_assumption = BlockPositionAssumption::WorstCase;
1139        pool.apply_block(&BlockContext::new(101, 1_002));
1140
1141        assert_eq!(
1142            pool.get_fee()
1143                .expect("fee should be computable")
1144                .fee,
1145            2700
1146        );
1147    }
1148
1149    #[test]
1150    fn worst_case_picks_the_initial_fee_when_it_is_the_higher_one() {
1151        // Nothing stops a pool from configuring initialFee above its dynamic fee, so the worst
1152        // case is max(initial, dynamic).
1153        let mut pool = initial_fee_pool(1_000);
1154        pool.dfc = DynamicFeeConfig::new(500, 30_000, 0, true, 4_000);
1155        pool.position_assumption = BlockPositionAssumption::WorstCase;
1156        pool.apply_block(&BlockContext::new(101, 1_002));
1157
1158        assert_eq!(
1159            pool.get_fee()
1160                .expect("fee should be computable")
1161                .fee,
1162            4_000
1163        );
1164    }
1165
1166    #[test]
1167    fn worst_case_keeps_a_flat_fee_pool_quiet_across_blocks() {
1168        // With scaling 0 the worst-case fee is constant, so apply_block must never request a
1169        // re-emission: the default mode adds no per-block load for such pools.
1170        let mut pool = initial_fee_pool(1_000);
1171        pool.position_assumption = BlockPositionAssumption::WorstCase;
1172        pool.apply_block(&BlockContext::new(100, 1_000));
1173
1174        assert!(!pool.apply_block(&BlockContext::new(101, 1_002)));
1175        assert!(!pool.apply_block(&BlockContext::new(102, 1_004)));
1176    }
1177
1178    #[test]
1179    fn apply_block_reports_a_fee_flip_and_is_idempotent() {
1180        // Pool traded in block 100 (ts 1_000): decoded with execution block == that block, so the
1181        // dynamic fee applies. Crossing to the next block flips the branch to the initial fee.
1182        let mut pool = initial_fee_pool(1_000);
1183        pool.apply_block(&BlockContext::new(100, 1_000));
1184
1185        assert!(pool.apply_block(&BlockContext::new(101, 1_002)), "branch flip must re-emit");
1186        assert!(!pool.apply_block(&BlockContext::new(101, 1_002)), "repeat block is a no-op");
1187    }
1188
1189    #[test]
1190    fn apply_block_stays_quiet_while_the_fee_does_not_move() {
1191        // Idle pool: the initial fee already applies and keeps applying as blocks pass, so
1192        // consumers must not be told anything changed.
1193        let mut pool = initial_fee_pool(1_000);
1194        pool.apply_block(&BlockContext::new(101, 1_002));
1195
1196        assert!(!pool.apply_block(&BlockContext::new(102, 1_004)));
1197        assert!(!pool.apply_block(&BlockContext::new(103, 1_006)));
1198    }
1199
1200    #[test]
1201    fn quotes_initial_fee_for_the_next_block_after_the_pool_traded() {
1202        // The pool wrote its observation in the block we decoded. A quote lands in the *next*
1203        // block, where no observation exists yet — under the first-in-block assumption it pays
1204        // the initial fee.
1205        let mut pool = initial_fee_pool(1_000);
1206        pool.apply_block(&BlockContext::new(101, 1_002));
1207
1208        assert_eq!(
1209            pool.get_fee()
1210                .expect("fee should be computable")
1211                .fee,
1212            750
1213        );
1214    }
1215
1216    #[test]
1217    fn quotes_dynamic_fee_when_targeting_a_block_the_pool_already_traded_in() {
1218        // Flashblock consumer: the block is still open and the pool traded in an earlier
1219        // flashblock, so a quote landing later in the same block pays the dynamic fee.
1220        let mut pool = initial_fee_pool(1_000);
1221        pool.apply_block(&BlockContext::new(100, 1_000));
1222
1223        assert_eq!(
1224            pool.get_fee()
1225                .expect("fee should be computable")
1226                .fee,
1227            2700
1228        );
1229    }
1230
1231    #[test]
1232    fn chained_swap_in_the_same_block_pays_the_dynamic_fee() {
1233        let mut pool = initial_fee_pool(1_000);
1234        pool.apply_block(&BlockContext::new(101, 1_002));
1235        let token_a =
1236            Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
1237        let token_b =
1238            Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);
1239
1240        assert_eq!(pool.fee(), 750.0 / 1_000_000.0);
1241
1242        let result = pool
1243            .get_amount_out(BigUint::from(100_000_000_000_000_000u128), &token_a, &token_b)
1244            .expect("first swap should succeed");
1245
1246        // The first swap moved the tick, so it wrote an observation at the execution timestamp;
1247        // the pool state it hands back prices the next swap in that block as a follow-up.
1248        assert_eq!(result.new_state.fee(), 2700.0 / 1_000_000.0);
1249    }
1250
1251    #[test]
1252    fn swap_that_does_not_move_the_tick_leaves_the_initial_fee_available() {
1253        // `CLPool.swap` only writes an observation when the tick changed, so a swap that stays
1254        // inside the tick leaves the next swap in the block on the initial fee.
1255        let mut pool = initial_fee_pool(1_000);
1256        pool.apply_block(&BlockContext::new(101, 1_002));
1257
1258        pool.record_observation(pool.tick)
1259            .expect("no-op write should succeed");
1260
1261        assert_eq!(
1262            pool.get_fee()
1263                .expect("fee should be computable")
1264                .fee,
1265            750
1266        );
1267    }
1268
1269    #[test]
1270    fn initial_fee_branch_does_not_charge_the_twap_gas_overhead() {
1271        let mut pool = initial_fee_pool(1_000);
1272        pool.dfc = DynamicFeeConfig::new(2700, 30_000, 6_000_000, true, 750);
1273        pool.apply_block(&BlockContext::new(101, 1_002));
1274
1275        let resolved = pool
1276            .get_fee()
1277            .expect("fee should be computable");
1278
1279        assert_eq!(resolved, ResolvedFee { fee: 750, observed_twap: false });
1280    }
1281
1282    #[test]
1283    fn dynamic_fee_update_applies_for_supported_module() {
1284        let mut pool = create_basic_test_pool();
1285        pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
1286        let delta =
1287            dynamic_fee_delta(hex_literal::hex!("090b2A6bb475c00e2256e2095A60887cD710803b"));
1288
1289        pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1290            .expect("dynamic fee update should be valid");
1291
1292        assert_eq!(
1293            pool.get_fee()
1294                .expect("fee should be computable")
1295                .fee,
1296            500
1297        );
1298    }
1299
1300    #[test]
1301    fn dynamic_fee_update_falls_back_to_default_for_unsupported_module() {
1302        // An unsupported-module delta resets to default rather than erroring; pool keeps
1303        // default_fee.
1304        let mut pool = create_basic_test_pool();
1305        pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
1306        let delta =
1307            dynamic_fee_delta(hex_literal::hex!("DB45818A6db280ecfeB33cbeBd445423d0216b5D"));
1308
1309        pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1310            .expect("unsupported module delta should decode to the default config");
1311
1312        assert_eq!(pool.dfc, DynamicFeeConfig::default());
1313        assert_eq!(
1314            pool.get_fee()
1315                .expect("fee should be computable")
1316                .fee,
1317            3000
1318        );
1319    }
1320
1321    #[test]
1322    fn applies_partial_dynamic_fee_updates_after_module_initialization() {
1323        let mut pool = create_basic_test_pool();
1324        pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
1325        let delta = ProtocolStateDelta {
1326            component_id: "test-pool".to_string(),
1327            updated_attributes: HashMap::from([(
1328                "dfc_baseFee".to_string(),
1329                Bytes::from(500_u32.to_be_bytes()),
1330            )]),
1331            ..Default::default()
1332        };
1333
1334        pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1335            .expect("partial dynamic fee update should be valid");
1336
1337        assert_eq!(pool.dfc, DynamicFeeConfig::new(500, 10_000, 1, false, 0));
1338    }
1339
1340    #[test]
1341    fn applies_a_cardinality_increase() {
1342        // `increaseObservationCardinalityNext(4)` prefills slots 1-3 with timestamp 1, which the
1343        // stream sends as the single byte 0x01. Lookups read them as uninitialized whether stored
1344        // or not, so the ring is left as it was.
1345        let mut pool = create_basic_test_pool();
1346        let ring = Observations::new(vec![Observation {
1347            block_timestamp: 999_990,
1348            initialized: true,
1349            ..Default::default()
1350        }]);
1351        pool.observations = ring.clone();
1352        let delta = ProtocolStateDelta {
1353            component_id: "test-pool".to_string(),
1354            updated_attributes: (1..4)
1355                .map(|index| (format!("observations/{index}"), Bytes::from([0x01_u8])))
1356                .collect(),
1357            ..Default::default()
1358        };
1359
1360        pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1361            .expect("prefilled observation slots should be valid");
1362
1363        assert_eq!(pool.observations, ring);
1364    }
1365
1366    #[rstest]
1367    #[case::not_a_number("observations/next")]
1368    #[case::past_the_ring("observations/65535")]
1369    fn malformed_observation_key_fails_the_transition(#[case] key: &str) {
1370        let mut pool = create_basic_test_pool();
1371        let delta = ProtocolStateDelta {
1372            component_id: "test-pool".to_string(),
1373            updated_attributes: HashMap::from([(key.to_string(), Bytes::from([0x01_u8]))]),
1374            ..Default::default()
1375        };
1376
1377        let result = pool.delta_transition(delta, &HashMap::new(), &Balances::default());
1378
1379        let Err(TransitionError::DecodeError(message)) = result else {
1380            panic!("expected a DecodeError, got {result:?}");
1381        };
1382        assert!(message.starts_with(key), "{message}");
1383    }
1384
1385    #[test]
1386    fn test_partial_step_updates_tick_when_price_moves_without_crossing_initialized_tick() {
1387        let pool = create_basic_test_pool();
1388        let amount =
1389            I256::checked_from_sign_and_abs(Sign::Positive, U256::from(100_000_000_000_000_000u64))
1390                .unwrap();
1391
1392        let result = pool
1393            .swap(true, amount, None)
1394            .expect("swap should stay within the current liquidity range");
1395        let expected_tick =
1396            get_tick_at_sqrt_ratio(result.sqrt_price).expect("new sqrt price should map to a tick");
1397
1398        assert_ne!(result.sqrt_price, pool.sqrt_price);
1399        assert_ne!(result.sqrt_price, get_sqrt_ratio_at_tick(-120).unwrap());
1400        assert_ne!(expected_tick, pool.tick);
1401        assert_eq!(result.tick.value(), expected_tick);
1402    }
1403
1404    #[test]
1405    fn test_swap_keeps_boundary_tick_when_price_does_not_move() {
1406        let mut pool = create_basic_test_pool();
1407        pool.tick = -1;
1408        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1u64)).unwrap();
1409
1410        let result = pool
1411            .swap(true, amount, None)
1412            .expect("swap should consume the input as fee without moving price");
1413
1414        assert_eq!(result.sqrt_price, pool.sqrt_price);
1415        assert_eq!(get_tick_at_sqrt_ratio(result.sqrt_price).unwrap(), 0);
1416        assert_eq!(result.tick.value(), pool.tick);
1417    }
1418
1419    #[test]
1420    fn test_swap_price_limit_out_of_range_returns_error() {
1421        let pool = create_basic_test_pool();
1422        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
1423
1424        let result = pool.swap(true, amount, Some(pool.sqrt_price));
1425        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1426
1427        let result = pool.swap(true, amount, Some(MIN_SQRT_RATIO));
1428        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1429
1430        let result = pool.swap(false, amount, Some(pool.sqrt_price));
1431        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1432
1433        let result = pool.swap(false, amount, Some(MAX_SQRT_RATIO));
1434        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1435    }
1436
1437    #[test]
1438    fn test_swap_at_extreme_price_returns_error() {
1439        let sqrt_price = MIN_SQRT_RATIO + U256::from(1u64);
1440        let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
1441        let ticks =
1442            vec![TickInfo::new(MIN_TICK, 0).unwrap(), TickInfo::new(MIN_TICK + 1, 0).unwrap()];
1443        let pool = AerodromeSlipstreamsState::new(
1444            "test-pool".to_string(),
1445            1_000_000,
1446            100_000_000_000_000_000_000u128,
1447            sqrt_price,
1448            0,
1449            1,
1450            3000,
1451            1,
1452            tick,
1453            ticks,
1454            vec![Observation::default()],
1455            DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
1456        )
1457        .expect("Failed to create pool");
1458
1459        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
1460        let result = pool.swap(true, amount, None);
1461        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1462    }
1463
1464    fn token_pair() -> (Token, Token) {
1465        let token_a =
1466            Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
1467        let token_b =
1468            Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);
1469        (token_a, token_b)
1470    }
1471
1472    #[rstest]
1473    fn test_query_pool_swap_target_price_lands_in_band(#[values(true, false)] sell_a: bool) {
1474        let mut pool = create_basic_test_pool();
1475        pool.dfc = DynamicFeeConfig::new(3000, 10_000, 0, false, 0);
1476        let (token_a, token_b) = token_pair();
1477        let (token_in, token_out) =
1478            if sell_a { (&token_a, &token_b) } else { (&token_b, &token_a) };
1479        let target = pool
1480            .spot_price(token_in, token_out)
1481            .unwrap() *
1482            0.99;
1483        let tolerance = 1e-4;
1484        let params = target_price_params(
1485            token_in,
1486            token_out,
1487            to_price(target, token_in, token_out),
1488            tolerance,
1489        );
1490
1491        let swap = pool.query_pool_swap(&params).unwrap();
1492
1493        let new_spot = swap
1494            .new_state()
1495            .spot_price(token_in, token_out)
1496            .unwrap();
1497        assert!(new_spot >= target && new_spot <= target * (1.0 + tolerance), "spot {new_spot}");
1498        assert!(swap.price_points().is_none(), "the native path returns no price points");
1499        let quote = pool
1500            .get_amount_out(swap.amount_in().clone(), token_in, token_out)
1501            .unwrap();
1502        assert_eq!(&quote.amount, swap.amount_out());
1503    }
1504
1505    #[test]
1506    fn target_price_revalidates_after_initial_fee_changes() {
1507        let mut pool = initial_fee_pool(999_999);
1508        pool.ticks = Arc::new(
1509            TickList::from(
1510                1,
1511                vec![TickInfo::new(-1200, 0).unwrap(), TickInfo::new(1200, 0).unwrap()],
1512            )
1513            .unwrap(),
1514        );
1515        let (token_in, token_out) = token_pair();
1516        let target = 0.99;
1517        let tolerance = 1e-4;
1518        let params = target_price_params(
1519            &token_in,
1520            &token_out,
1521            to_price(target, &token_in, &token_out),
1522            tolerance,
1523        );
1524        let swap = pool
1525            .query_pool_swap(&params)
1526            .expect("search reaches the target using the final fee");
1527        let spot = swap
1528            .new_state()
1529            .spot_price(&token_in, &token_out)
1530            .unwrap();
1531        assert!(spot >= target && spot <= target * (1.0 + tolerance), "final spot {spot}");
1532        assert!(swap.price_points().is_some(), "fee change should trigger numerical search");
1533    }
1534
1535    /// A target less than half the tolerance below spot puts the swap limit above spot.
1536    #[test]
1537    fn test_query_pool_swap_target_price_falls_back_to_search() {
1538        let pool = create_basic_test_pool();
1539        let (token_a, token_b) = token_pair();
1540        let spot = pool
1541            .spot_price(&token_a, &token_b)
1542            .unwrap();
1543        let params = target_price_params(
1544            &token_a,
1545            &token_b,
1546            to_price(spot * (1.0 - 1e-5), &token_a, &token_b),
1547            1e-4,
1548        );
1549
1550        let swap = pool.query_pool_swap(&params).unwrap();
1551
1552        assert!(swap.price_points().is_some(), "the numerical search returns price points");
1553    }
1554
1555    #[test]
1556    fn test_query_pool_swap_target_price_at_spot() {
1557        let mut pool = create_basic_test_pool();
1558        pool.dfc = DynamicFeeConfig::new(ZERO_FEE_INDICATOR, 10_000, 0, false, 0);
1559        let (token_a, token_b) = token_pair();
1560        let params = target_price_params(
1561            &token_a,
1562            &token_b,
1563            Price::new(BigUint::from(1u64), BigUint::from(1u64)),
1564            1e-4,
1565        );
1566
1567        let swap = pool.query_pool_swap(&params).unwrap();
1568
1569        assert!(swap.amount_in().is_zero());
1570        assert!(swap.amount_out().is_zero());
1571        assert!(swap.new_state().eq(&pool));
1572    }
1573
1574    #[test]
1575    fn test_query_pool_swap_target_price_above_spot() {
1576        let pool = create_basic_test_pool();
1577        let (token_a, token_b) = token_pair();
1578        let spot = pool
1579            .spot_price(&token_a, &token_b)
1580            .unwrap();
1581        let params = target_price_params(
1582            &token_a,
1583            &token_b,
1584            to_price(spot * 1.01, &token_a, &token_b),
1585            1e-4,
1586        );
1587
1588        let result = pool.query_pool_swap(&params);
1589
1590        assert!(matches!(result, Err(SimulationError::InvalidInput(..))), "got {result:?}");
1591    }
1592}
1593
1594#[cfg(test)]
1595mod tick_list_sharing_tests {
1596    use std::collections::{HashMap, HashSet};
1597
1598    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
1599
1600    use super::*;
1601    use crate::evm::protocol::utils::uniswap::tick_math::get_sqrt_ratio_at_tick;
1602
1603    #[test]
1604    fn test_delta_transition_leaves_clones_ticks_unchanged() {
1605        let original = AerodromeSlipstreamsState::new(
1606            "test-pool".to_string(),
1607            1_000_000,
1608            100_000_000_000_000_000_000u128,
1609            get_sqrt_ratio_at_tick(0).unwrap(),
1610            0,
1611            1,
1612            3000,
1613            1,
1614            0,
1615            vec![TickInfo::new(-120, 10000).unwrap(), TickInfo::new(120, -10000).unwrap()],
1616            vec![Observation::default()],
1617            DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
1618        )
1619        .unwrap();
1620        let mut updated = original.clone();
1621        let delta = ProtocolStateDelta {
1622            component_id: "State1".to_owned(),
1623            updated_attributes: HashMap::from([(
1624                "ticks/-120/net_liquidity".to_string(),
1625                Bytes::from(20000_i128.to_be_bytes().to_vec()),
1626            )]),
1627            deleted_attributes: HashSet::new(),
1628        };
1629
1630        updated
1631            .delta_transition(delta, &HashMap::new(), &Balances::default())
1632            .unwrap();
1633
1634        assert_eq!(
1635            updated
1636                .ticks
1637                .get_tick(-120)
1638                .unwrap()
1639                .net_liquidity,
1640            20000
1641        );
1642        assert_eq!(
1643            original
1644                .ticks
1645                .get_tick(-120)
1646                .unwrap()
1647                .net_liquidity,
1648            10000
1649        );
1650    }
1651}
1652
1653#[cfg(test)]
1654mod observation_sharing_tests {
1655    use std::collections::{HashMap, HashSet};
1656
1657    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
1658
1659    use super::*;
1660    use crate::evm::protocol::utils::uniswap::tick_math::get_sqrt_ratio_at_tick;
1661
1662    fn pool_with_observations() -> AerodromeSlipstreamsState {
1663        let observations = (0..3)
1664            .map(|index| Observation {
1665                block_timestamp: 1_000 + u32::try_from(index).unwrap(),
1666                tick_cumulative: 10 * i64::from(index),
1667                initialized: true,
1668                ..Default::default()
1669            })
1670            .collect();
1671        let mut pool = AerodromeSlipstreamsState::new(
1672            "test-pool".to_string(),
1673            1_000_000,
1674            100_000_000_000_000_000_000u128,
1675            get_sqrt_ratio_at_tick(0).unwrap(),
1676            0,
1677            3,
1678            3000,
1679            1,
1680            0,
1681            vec![TickInfo::new(-120, 10000).unwrap(), TickInfo::new(120, -10000).unwrap()],
1682            observations,
1683            DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
1684        )
1685        .unwrap();
1686        pool.execution_block_timestamp = 2_000;
1687        pool
1688    }
1689
1690    /// The state after a swap at `timestamp` that moved the tick to `tick`.
1691    fn swapped(
1692        pool: &AerodromeSlipstreamsState,
1693        timestamp: u64,
1694        tick: i32,
1695    ) -> AerodromeSlipstreamsState {
1696        let mut source = pool.clone();
1697        source.execution_block_timestamp = timestamp;
1698        let (state, written) =
1699            source.clone_post_swap(get_sqrt_ratio_at_tick(tick).unwrap(), tick, 1);
1700        written.unwrap();
1701        state
1702    }
1703
1704    fn observation_bytes(timestamp: u32) -> Bytes {
1705        // Packed as on chain: timestamp in the low 32 bits, `initialized` at bit 248.
1706        let mut packed = [0u8; 32];
1707        packed[28..].copy_from_slice(&timestamp.to_be_bytes());
1708        packed[0] = 1;
1709        Bytes::from(packed.to_vec())
1710    }
1711
1712    fn observation_delta(timestamp: u32) -> ProtocolStateDelta {
1713        ProtocolStateDelta {
1714            component_id: "State1".to_owned(),
1715            updated_attributes: HashMap::from([(
1716                "observations/1".to_string(),
1717                observation_bytes(timestamp),
1718            )]),
1719            deleted_attributes: HashSet::new(),
1720        }
1721    }
1722
1723    #[test]
1724    fn clone_shares_observations() {
1725        let original = pool_with_observations();
1726
1727        let copy = original.clone();
1728
1729        assert!(original
1730            .observations
1731            .shares_ring_with(&copy.observations));
1732    }
1733
1734    #[test]
1735    fn chain_of_tick_moving_swaps_never_copies_the_ring() {
1736        let original = pool_with_observations();
1737
1738        let first = swapped(&original, 2_000, 60);
1739        let second = swapped(&first, 2_010, -60);
1740        let third = swapped(&second, 2_020, 30);
1741
1742        for state in [&first, &second, &third] {
1743            assert!(original
1744                .observations
1745                .shares_ring_with(&state.observations));
1746        }
1747        assert_eq!(third.observation_index, 0);
1748        assert_eq!(
1749            third
1750                .observations
1751                .timestamp_at(0, 3)
1752                .unwrap(),
1753            2_020
1754        );
1755        assert_eq!(
1756            second
1757                .observations
1758                .timestamp_at(2, 3)
1759                .unwrap(),
1760            2_010
1761        );
1762        assert_eq!(
1763            first
1764                .observations
1765                .timestamp_at(1, 3)
1766                .unwrap(),
1767            2_000
1768        );
1769    }
1770
1771    #[test]
1772    fn swap_leaves_the_source_states_observations_unchanged() {
1773        let original = pool_with_observations();
1774
1775        let after_swap = swapped(&original, 2_000, 60);
1776
1777        assert_eq!(after_swap.observation_index, 1);
1778        assert_eq!(
1779            after_swap
1780                .observations
1781                .timestamp_at(1, 3)
1782                .unwrap(),
1783            2_000
1784        );
1785        assert_eq!(original.observation_index, 0);
1786        assert_eq!(
1787            original
1788                .observations
1789                .timestamp_at(1, 3)
1790                .unwrap(),
1791            1_001
1792        );
1793    }
1794
1795    #[test]
1796    fn second_swap_in_the_same_block_writes_nothing() {
1797        let original = pool_with_observations();
1798        let first = swapped(&original, 2_000, 60);
1799
1800        let second = swapped(&first, 2_000, -60);
1801
1802        assert_eq!(second.observation_index, first.observation_index);
1803        assert_eq!(second.observations, first.observations);
1804    }
1805
1806    #[test]
1807    fn swap_that_keeps_the_tick_writes_nothing() {
1808        let original = pool_with_observations();
1809
1810        let after_swap = swapped(&original, 2_000, original.tick);
1811
1812        assert_eq!(after_swap.observation_index, 0);
1813        assert_eq!(after_swap.observations, original.observations);
1814    }
1815
1816    #[test]
1817    fn fee_and_observations_match_a_state_rebuilt_from_the_merged_observations() {
1818        let original = pool_with_observations();
1819        let chained = swapped(&swapped(&original, 2_000, 60), 2_010, -60);
1820        let copied: AerodromeSlipstreamsState =
1821            serde_json::from_str(&serde_json::to_string(&chained).unwrap()).unwrap();
1822
1823        assert!(!chained
1824            .observations
1825            .shares_ring_with(&copied.observations));
1826        assert_eq!(chained.observations, copied.observations);
1827        assert_eq!(chained.get_fee().unwrap().fee, copied.get_fee().unwrap().fee);
1828        for seconds_ago in [0, 5, 10, 15] {
1829            assert_eq!(
1830                chained
1831                    .observations
1832                    .observe_single(2_020, seconds_ago, -60, 2, 1, 3)
1833                    .unwrap(),
1834                copied
1835                    .observations
1836                    .observe_single(2_020, seconds_ago, -60, 2, 1, 3)
1837                    .unwrap(),
1838            );
1839        }
1840    }
1841
1842    #[test]
1843    fn delta_transition_leaves_clones_observations_unchanged() {
1844        let original = pool_with_observations();
1845        let mut updated = original.clone();
1846
1847        updated
1848            .delta_transition(observation_delta(5_000), &HashMap::new(), &Balances::default())
1849            .unwrap();
1850
1851        assert_eq!(
1852            updated
1853                .observations
1854                .timestamp_at(1, 3)
1855                .unwrap(),
1856            5_000
1857        );
1858        assert_eq!(
1859            original
1860                .observations
1861                .timestamp_at(1, 3)
1862                .unwrap(),
1863            1_001
1864        );
1865        assert!(!original
1866            .observations
1867            .shares_ring_with(&updated.observations));
1868    }
1869
1870    #[test]
1871    fn delta_transition_after_simulated_writes_reads_the_chain_values() {
1872        let original = pool_with_observations();
1873        let mut simulated = swapped(&original, 2_000, 60);
1874
1875        simulated
1876            .delta_transition(observation_delta(5_000), &HashMap::new(), &Balances::default())
1877            .unwrap();
1878
1879        assert_eq!(
1880            simulated
1881                .observations
1882                .timestamp_at(1, 3)
1883                .unwrap(),
1884            5_000
1885        );
1886        assert_eq!(
1887            simulated
1888                .observations
1889                .timestamp_at(2, 3)
1890                .unwrap(),
1891            1_002
1892        );
1893        assert_eq!(
1894            original
1895                .observations
1896                .timestamp_at(1, 3)
1897                .unwrap(),
1898            1_001
1899        );
1900    }
1901
1902    #[test]
1903    fn delta_transition_keeps_simulated_writes_the_chain_did_not_touch() {
1904        let original = pool_with_observations();
1905        let mut simulated = swapped(&swapped(&original, 2_000, 60), 2_010, -60);
1906        let mut delta = observation_delta(5_000);
1907        delta.updated_attributes.clear();
1908        delta
1909            .deleted_attributes
1910            .insert("observations/0".to_string());
1911
1912        simulated
1913            .delta_transition(delta, &HashMap::new(), &Balances::default())
1914            .unwrap();
1915
1916        // Deleting slot 0 zeroes it; the simulated writes stay at slots 1 and 2.
1917        assert_eq!(simulated.observations.get(0), Some(Observation::default()));
1918        assert_eq!(
1919            simulated
1920                .observations
1921                .timestamp_at(1, 3)
1922                .unwrap(),
1923            2_000
1924        );
1925        assert_eq!(
1926            simulated
1927                .observations
1928                .timestamp_at(2, 3)
1929                .unwrap(),
1930            2_010
1931        );
1932    }
1933}
1934
1935#[cfg(test)]
1936mod step_cache_tests {
1937    use std::{
1938        collections::{HashMap, HashSet},
1939        str::FromStr,
1940    };
1941
1942    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
1943
1944    use super::*;
1945    use crate::evm::protocol::utils::uniswap::swap_step_cache::test_fixtures::{
1946        amount_orders, test_amounts, test_ticks, wbtc_weth, LIQUIDITY, SQRT_PRICE, TICK,
1947    };
1948
1949    fn test_pool() -> AerodromeSlipstreamsState {
1950        AerodromeSlipstreamsState::new(
1951            "test-pool".to_string(),
1952            1_000_000,
1953            LIQUIDITY,
1954            U256::from_str(SQRT_PRICE).unwrap(),
1955            0,
1956            1,
1957            500,
1958            10,
1959            TICK,
1960            test_ticks(),
1961            vec![Observation::default()],
1962            DynamicFeeConfig::new(500, 10_000, 1, false, 0),
1963        )
1964        .unwrap()
1965    }
1966
1967    /// A quote's amount, gas and new state, or its error, as text.
1968    fn format_quote_result(
1969        pool: &AerodromeSlipstreamsState,
1970        amount: &BigUint,
1971        sell: &Token,
1972        buy: &Token,
1973    ) -> String {
1974        match pool.get_amount_out(amount.clone(), sell, buy) {
1975            Ok(result) => {
1976                let state = result
1977                    .new_state
1978                    .as_any()
1979                    .downcast_ref::<AerodromeSlipstreamsState>()
1980                    .unwrap();
1981                format!(
1982                    "{} {} {} {} {}",
1983                    result.amount, result.gas, state.sqrt_price, state.tick, state.liquidity
1984                )
1985            }
1986            Err(error) => format!("error {error}"),
1987        }
1988    }
1989
1990    #[test]
1991    fn test_step_cache_quotes_match_a_fresh_state_in_any_order() {
1992        let (wbtc, weth) = wbtc_weth();
1993        for (sell, buy, smallest) in [(&wbtc, &weth, 1_000u64), (&weth, &wbtc, 1_000_000_000)] {
1994            for order in amount_orders(&test_amounts(smallest)) {
1995                let shared = test_pool();
1996                for amount in &order {
1997                    assert_eq!(
1998                        format_quote_result(&shared, amount, sell, buy),
1999                        format_quote_result(&test_pool(), amount, sell, buy),
2000                        "selling {amount} {}",
2001                        sell.symbol
2002                    );
2003                }
2004                let steps = shared
2005                    .step_cache
2006                    .min_inputs(sell < buy)
2007                    .len();
2008                assert!(steps > 2, "only {steps} steps cached");
2009            }
2010        }
2011    }
2012
2013    #[test]
2014    fn test_step_cache_quotes_match_a_fresh_state_at_each_cached_step() {
2015        let (wbtc, weth) = wbtc_weth();
2016        // Amounts that run past the last tick, so the cache covers the whole tick list. Selling
2017        // WETH needs a far larger amount to leave its first tick.
2018        for (sell, buy, doublings) in [(&wbtc, &weth, 30u32), (&weth, &wbtc, 70)] {
2019            let cached = test_pool();
2020            #[expect(
2021                clippy::let_underscore_must_use,
2022                reason = "the quote may run out of liquidity; only the step cache it fills is used"
2023            )]
2024            let _ = cached.get_amount_out(BigUint::from(10u32) << doublings, sell, buy);
2025            let boundaries = cached.step_cache.min_inputs(sell < buy);
2026            assert!(boundaries.len() > 2, "only {} steps cached", boundaries.len());
2027            for boundary in boundaries.into_iter().skip(1) {
2028                for amount in [boundary - U256::from(1u64), boundary, boundary + U256::from(1u64)] {
2029                    let amount = u256_to_biguint(amount);
2030                    assert_eq!(
2031                        format_quote_result(&cached, &amount, sell, buy),
2032                        format_quote_result(&test_pool(), &amount, sell, buy),
2033                        "selling {amount} {}",
2034                        sell.symbol
2035                    );
2036                }
2037            }
2038        }
2039    }
2040
2041    #[test]
2042    fn test_step_cache_of_a_swapped_state() {
2043        let (wbtc, weth) = wbtc_weth();
2044        let pool = test_pool();
2045        let swapped = pool
2046            .get_amount_out(BigUint::from(300_000_000u64), &wbtc, &weth)
2047            .unwrap()
2048            .new_state;
2049        let swapped = swapped
2050            .as_any()
2051            .downcast_ref::<AerodromeSlipstreamsState>()
2052            .unwrap();
2053        // A serde round trip gives the same state with an empty step cache.
2054        let fresh: AerodromeSlipstreamsState =
2055            serde_json::from_value(serde_json::to_value(swapped).unwrap()).unwrap();
2056
2057        for amount in test_amounts(1_000).iter().rev() {
2058            assert_eq!(
2059                format_quote_result(swapped, amount, &wbtc, &weth),
2060                format_quote_result(&fresh, amount, &wbtc, &weth),
2061                "selling {amount} WBTC"
2062            );
2063        }
2064    }
2065
2066    #[test]
2067    fn test_step_cache_restarts_after_delta_transition() {
2068        let (wbtc, weth) = wbtc_weth();
2069        let large = BigUint::from(3_000_000_000u64);
2070        // Only a crossed tick's liquidity changes, so the price, tick and liquidity the cache
2071        // starts from stay the same.
2072        let delta = || ProtocolStateDelta {
2073            component_id: "State1".to_owned(),
2074            updated_attributes: HashMap::from([(
2075                "ticks/255820/net_liquidity".to_string(),
2076                Bytes::from(
2077                    1_000_000_000_000_000i128
2078                        .to_be_bytes()
2079                        .to_vec(),
2080                ),
2081            )]),
2082            deleted_attributes: HashSet::new(),
2083        };
2084        let mut cached = test_pool();
2085        cached
2086            .get_amount_out(large.clone(), &wbtc, &weth)
2087            .unwrap();
2088        let mut fresh = test_pool();
2089
2090        cached
2091            .delta_transition(delta(), &HashMap::new(), &Balances::default())
2092            .unwrap();
2093        fresh
2094            .delta_transition(delta(), &HashMap::new(), &Balances::default())
2095            .unwrap();
2096
2097        assert_eq!(
2098            format_quote_result(&cached, &large, &wbtc, &weth),
2099            format_quote_result(&fresh, &large, &wbtc, &weth)
2100        );
2101    }
2102}