Skip to main content

tycho_simulation/evm/protocol/velodrome_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::trace;
8use tycho_common::{
9    dto::ProtocolStateDelta,
10    models::token::Token,
11    simulation::{
12        errors::{SimulationError, TransitionError},
13        protocol_sim::{
14            Balances, GetAmountOutResult, PoolSwap, Price, ProtocolSim, QueryPoolSwapParams,
15            SwapConstraint,
16        },
17    },
18    Bytes,
19};
20
21use crate::evm::{
22    protocol::{
23        clmm::clmm_swap_to_price,
24        safe_math::{safe_add_u256, safe_sub_u256},
25        u256_num::u256_to_biguint,
26        utils::{
27            slipstreams::{dynamic_fee_module::ZERO_FEE_INDICATOR, raw_target_price},
28            uniswap::{
29                liquidity_math,
30                pool_tick::PoolTick,
31                sqrt_price_math::{get_amount0_delta, get_amount1_delta, sqrt_price_q96_to_f64},
32                swap_math::{self, SwapStepResult},
33                swap_step_cache::{StepCacheKey, StepCacheRun, SwapStepCache},
34                tick_list::{TickInfo, TickList, TickListErrorKind},
35                tick_math::{
36                    get_sqrt_ratio_at_tick_cached, MAX_SQRT_RATIO, MAX_TICK, MIN_SQRT_RATIO,
37                    MIN_TICK,
38                },
39                StepComputation, SwapResults, SwapState,
40            },
41        },
42    },
43    query_pool_swap::price_to_f64_with_decimals,
44};
45
46// The names of the constants reflect the exact method from the tenderly log.
47const GAS_PER_TICK: u64 = 25_000;
48// nextInitializedTickWithinOneWord +  computeSwapStep + calculateFees
49const GAS_PER_LOOP: u64 = 10_000;
50
51#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
52pub struct VelodromeSlipstreamsState {
53    liquidity: u128,
54    sqrt_price: U256,
55    default_fee: u32,
56    custom_fee: u32,
57    tick_spacing: i32,
58    tick: PoolTick,
59    /// The tick list, shared by this state, its clones and the states its swaps return, so a quote
60    /// does not copy it. Change it only through `Arc::make_mut`, which copies the list while
61    /// another state shares it.
62    ticks: Arc<TickList>,
63    /// Swap steps already taken from this state, shared by its clones. The steps hold only for
64    /// this state's price, tick, liquidity, fee and ticks. `delta_transition` and
65    /// `clone_post_swap` replace the cache with an empty one, and any other code that changes
66    /// those fields must do the same.
67    #[serde(skip)]
68    step_cache: SwapStepCache,
69}
70
71impl VelodromeSlipstreamsState {
72    /// Creates a new instance of `AerodromeSlipstreamsState`.
73    ///
74    /// # Arguments
75    /// - `liquidity`: The initial liquidity of the pool.
76    /// - `sqrt_price`: The square root of the current price.
77    /// - `default_fee`: The default fee for the pool.
78    /// - `custom_fee`: The custom fee for the pool.
79    /// - `tick_spacing`: The tick spacing for the pool.
80    /// - `tick`: The current tick of the pool.
81    /// - `ticks`: A vector of `TickInfo` representing the tick information for the pool.
82    pub fn new(
83        liquidity: u128,
84        sqrt_price: U256,
85        default_fee: u32,
86        custom_fee: u32,
87        tick_spacing: i32,
88        tick: i32,
89        ticks: Vec<TickInfo>,
90    ) -> Result<Self, SimulationError> {
91        let tick_list_spacing = u16::try_from(tick_spacing).map_err(|e| {
92            SimulationError::InvalidInput(format!("Invalid tick spacing {tick_spacing}: {e}"), None)
93        })?;
94        let tick_list = TickList::from(tick_list_spacing, ticks)?;
95        Ok(VelodromeSlipstreamsState {
96            liquidity,
97            sqrt_price,
98            default_fee,
99            custom_fee,
100            tick_spacing,
101            tick: tick.into(),
102            ticks: Arc::new(tick_list),
103            step_cache: SwapStepCache::default(),
104        })
105    }
106
107    /// Returns the swap fee in pips. A custom fee of zero means that none is set, and
108    /// [`ZERO_FEE_INDICATOR`] is the value the fee module stores for an explicit zero fee.
109    fn get_fee(&self) -> u32 {
110        match self.custom_fee {
111            0 => self.default_fee,
112            ZERO_FEE_INDICATOR => 0,
113            custom_fee => custom_fee,
114        }
115    }
116
117    /// Swaps token_in until `spot_price(token_in, token_out)` reaches the middle of the band
118    /// `[target, target * (1 + tolerance)]`. Falls back to the numerical search on errors, and
119    /// when the native swap stops outside the band.
120    fn swap_to_target_price(
121        &self,
122        params: &QueryPoolSwapParams,
123        target: &Price,
124        tolerance: f64,
125    ) -> Result<PoolSwap, SimulationError> {
126        let token_in = params.token_in();
127        let token_out = params.token_out();
128        let target_f64 = price_to_f64_with_decimals(target, token_in.decimals, token_out.decimals)?;
129        if target_f64 == self.spot_price(token_in, token_out)? {
130            return Ok(PoolSwap::new(BigUint::ZERO, BigUint::ZERO, Box::new(self.clone()), None));
131        }
132        // `spot_price` has no fee markup, so the limit and the swap both use fee 0.
133        let Some(limit) = raw_target_price(target, tolerance, 0) else {
134            return crate::evm::query_pool_swap::query_pool_swap(self, params);
135        };
136        let Ok((amount_in, amount_out, result)) = clmm_swap_to_price(
137            self.sqrt_price,
138            &token_in.address,
139            &token_out.address,
140            &limit,
141            0,
142            Sign::Positive,
143            |zero_for_one, amount_specified, sqrt_price_limit| {
144                self.swap(zero_for_one, amount_specified, Some(sqrt_price_limit))
145            },
146        ) else {
147            return crate::evm::query_pool_swap::query_pool_swap(self, params);
148        };
149
150        let new_state = if amount_in.is_zero() {
151            self.clone()
152        } else {
153            self.clone_post_swap(result.sqrt_price, result.tick, result.liquidity)
154        };
155        // The native swap can spend its whole input allowance before it reaches the limit.
156        let final_spot = new_state.spot_price(token_in, token_out)?;
157        if final_spot < target_f64 || final_spot > target_f64 * (1.0 + tolerance) {
158            return crate::evm::query_pool_swap::query_pool_swap(self, params);
159        }
160        Ok(PoolSwap::new(amount_in, amount_out, Box::new(new_state), None))
161    }
162
163    /// A clone of this state with the final price, tick and liquidity of a swap, and an empty
164    /// step cache.
165    fn clone_post_swap(&self, sqrt_price: U256, tick: PoolTick, liquidity: u128) -> Self {
166        let mut state = self.clone();
167        state.sqrt_price = sqrt_price;
168        state.tick = tick;
169        state.liquidity = liquidity;
170        state.step_cache = SwapStepCache::default();
171        state
172    }
173
174    fn swap(
175        &self,
176        zero_for_one: bool,
177        amount_specified: I256,
178        sqrt_price_limit: Option<U256>,
179    ) -> Result<SwapResults, SimulationError> {
180        if self.liquidity == 0 {
181            return Err(SimulationError::RecoverableError("No liquidity".to_string()));
182        }
183        let price_limit = if let Some(limit) = sqrt_price_limit {
184            limit
185        } else if zero_for_one {
186            safe_add_u256(MIN_SQRT_RATIO, U256::from(1u64))?
187        } else {
188            safe_sub_u256(MAX_SQRT_RATIO, U256::from(1u64))?
189        };
190
191        let price_limit_valid = if zero_for_one {
192            price_limit > MIN_SQRT_RATIO && price_limit < self.sqrt_price
193        } else {
194            price_limit < MAX_SQRT_RATIO && price_limit > self.sqrt_price
195        };
196        if !price_limit_valid {
197            return Err(SimulationError::InvalidInput("Price limit out of range".into(), None));
198        }
199
200        let exact_input = amount_specified > I256::from_raw(U256::from(0u64));
201
202        let mut state = SwapState {
203            amount_remaining: amount_specified,
204            amount_calculated: I256::from_raw(U256::from(0u64)),
205            sqrt_price: self.sqrt_price,
206            tick: self.tick.value().into(),
207            liquidity: self.liquidity,
208        };
209        let mut gas_used = U256::from(130_000);
210
211        let fee = self.get_fee();
212        // Only exact-input swaps with no price limit use the step cache. The cache finds a step by
213        // its input, which an exact-output swap does not know. A cached step can also lie past a
214        // price limit.
215        let cache_key = if exact_input && sqrt_price_limit.is_none() {
216            StepCacheKey::new(self.sqrt_price, state.tick.value(), self.liquidity, fee, gas_used)
217        } else {
218            None
219        };
220        let mut cache_run = StepCacheRun::new(
221            &self.step_cache,
222            zero_for_one,
223            cache_key,
224            amount_specified.unsigned_abs(),
225        );
226        if let Some(progress) = cache_run.apply_cached_progress(&mut state) {
227            gas_used = progress.gas;
228        }
229        while state.amount_remaining != I256::from_raw(U256::from(0u64)) &&
230            state.sqrt_price != price_limit
231        {
232            let (mut next_tick, next_tick_info) = match self
233                .ticks
234                .next_initialized_tick_within_one_word(state.tick.value(), zero_for_one)
235            {
236                Ok((tick, info)) => (tick, info),
237                Err(tick_err) => match tick_err.kind {
238                    TickListErrorKind::TicksExeeded => {
239                        let new_state = self.clone_post_swap(
240                            state.sqrt_price,
241                            state.tick.clone(),
242                            state.liquidity,
243                        );
244                        return Err(SimulationError::InvalidInput(
245                            "Ticks exceeded".into(),
246                            Some(GetAmountOutResult::new(
247                                u256_to_biguint(state.amount_calculated.abs().into_raw()),
248                                u256_to_biguint(gas_used),
249                                Box::new(new_state),
250                            )),
251                        ));
252                    }
253                    TickListErrorKind::BelowSmallest | TickListErrorKind::AtOrAboveLargest => {
254                        return Err(SimulationError::FatalError("Unknown error".to_string()))
255                    }
256                },
257            };
258
259            next_tick = next_tick.clamp(MIN_TICK, MAX_TICK);
260
261            let sqrt_price_start = state.sqrt_price;
262            let sqrt_price_next = match next_tick_info {
263                Some(info) => info.sqrt_price,
264                None => get_sqrt_ratio_at_tick_cached(next_tick)?,
265            };
266            let SwapStepResult { sqrt_price, amount_in_with_fee, amount_out } =
267                swap_math::compute_swap_step(
268                    state.sqrt_price,
269                    VelodromeSlipstreamsState::get_sqrt_ratio_target(
270                        sqrt_price_next,
271                        price_limit,
272                        zero_for_one,
273                    ),
274                    state.liquidity,
275                    state.amount_remaining,
276                    fee,
277                )?;
278            state.sqrt_price = sqrt_price;
279
280            let step = StepComputation {
281                sqrt_price_start,
282                tick_next: next_tick,
283                sqrt_price_next,
284                amount_in_with_fee,
285                amount_out,
286            };
287            if exact_input {
288                state.amount_remaining -=
289                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
290                        .unwrap();
291                state.amount_calculated -=
292                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
293            } else {
294                state.amount_remaining +=
295                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
296                state.amount_calculated +=
297                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
298                        .unwrap();
299            }
300            if state.sqrt_price == step.sqrt_price_next {
301                if let Some(info) = next_tick_info {
302                    let liquidity_raw = info.net_liquidity;
303                    let liquidity_net = if zero_for_one { -liquidity_raw } else { liquidity_raw };
304                    state.liquidity =
305                        liquidity_math::add_liquidity_delta(state.liquidity, liquidity_net)?;
306                    gas_used = safe_add_u256(gas_used, U256::from(GAS_PER_TICK))?;
307                }
308                state.tick =
309                    PoolTick::from(if zero_for_one { step.tick_next - 1 } else { step.tick_next });
310            } else if state.sqrt_price != step.sqrt_price_start {
311                state.tick = PoolTick::at_sqrt_price(state.sqrt_price)?;
312            }
313            gas_used = safe_add_u256(gas_used, U256::from(GAS_PER_LOOP))?;
314            cache_run.cache_progress(&step, &state, gas_used);
315        }
316        Ok(SwapResults {
317            amount_calculated: state.amount_calculated,
318            amount_specified,
319            amount_remaining: state.amount_remaining,
320            sqrt_price: state.sqrt_price,
321            liquidity: state.liquidity,
322            tick: state.tick,
323            gas_used,
324        })
325    }
326
327    fn get_sqrt_ratio_target(
328        sqrt_price_next: U256,
329        sqrt_price_limit: U256,
330        zero_for_one: bool,
331    ) -> U256 {
332        let cond1 = if zero_for_one {
333            sqrt_price_next < sqrt_price_limit
334        } else {
335            sqrt_price_next > sqrt_price_limit
336        };
337
338        if cond1 {
339            sqrt_price_limit
340        } else {
341            sqrt_price_next
342        }
343    }
344}
345
346#[typetag::serde]
347impl ProtocolSim for VelodromeSlipstreamsState {
348    fn fee(&self) -> f64 {
349        self.get_fee() as f64 / 1_000_000.0
350    }
351
352    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
353        if base < quote {
354            sqrt_price_q96_to_f64(self.sqrt_price, base.decimals, quote.decimals)
355        } else {
356            sqrt_price_q96_to_f64(self.sqrt_price, quote.decimals, base.decimals)
357                .map(|price| 1.0f64 / price)
358        }
359    }
360
361    fn get_amount_out(
362        &self,
363        amount_in: BigUint,
364        token_in: &Token,
365        token_out: &Token,
366    ) -> Result<GetAmountOutResult, SimulationError> {
367        let zero_for_one = token_in < token_out;
368        let amount_specified = I256::checked_from_sign_and_abs(
369            Sign::Positive,
370            U256::from_be_slice(&amount_in.to_bytes_be()),
371        )
372        .ok_or_else(|| {
373            SimulationError::InvalidInput("I256 overflow: amount_in".to_string(), None)
374        })?;
375
376        let result = self.swap(zero_for_one, amount_specified, None)?;
377
378        trace!(?amount_in, ?token_in, ?token_out, ?zero_for_one, ?result, "SLIPSTREAMS SWAP");
379        let new_state = self.clone_post_swap(result.sqrt_price, result.tick, result.liquidity);
380
381        Ok(GetAmountOutResult::new(
382            u256_to_biguint(
383                result
384                    .amount_calculated
385                    .abs()
386                    .into_raw(),
387            ),
388            u256_to_biguint(result.gas_used),
389            Box::new(new_state),
390        ))
391    }
392
393    fn get_limits(
394        &self,
395        sell_token: Bytes,
396        buy_token: Bytes,
397    ) -> Result<(BigUint, BigUint), SimulationError> {
398        // If the pool has no liquidity, return zeros for both limits
399        if self.liquidity == 0 {
400            return Ok((BigUint::zero(), BigUint::zero()));
401        }
402
403        let zero_for_one = sell_token < buy_token;
404        let mut current_tick = self.tick.value();
405        let mut current_sqrt_price = self.sqrt_price;
406        let mut current_liquidity = self.liquidity;
407        let mut total_amount_in = U256::from(0u64);
408        let mut total_amount_out = U256::from(0u64);
409
410        // Iterate through all ticks in the direction of the swap
411        // Continues until there is no more liquidity in the pool or no more ticks to process
412        while let Ok((tick, next_tick_info)) = self
413            .ticks
414            .next_initialized_tick_within_one_word(current_tick, zero_for_one)
415        {
416            // Clamp the tick value to ensure it's within valid range
417            let next_tick = tick.clamp(MIN_TICK, MAX_TICK);
418
419            let sqrt_price_next = match next_tick_info {
420                Some(info) => info.sqrt_price,
421                None => get_sqrt_ratio_at_tick_cached(next_tick)?,
422            };
423
424            // Calculate the amount of tokens swapped when moving from current_sqrt_price to
425            // sqrt_price_next. Direction determines which token is being swapped in vs out
426            let (amount_in, amount_out) = if zero_for_one {
427                let amount0 = get_amount0_delta(
428                    sqrt_price_next,
429                    current_sqrt_price,
430                    current_liquidity,
431                    true,
432                )?;
433                let amount1 = get_amount1_delta(
434                    sqrt_price_next,
435                    current_sqrt_price,
436                    current_liquidity,
437                    false,
438                )?;
439                (amount0, amount1)
440            } else {
441                let amount0 = get_amount0_delta(
442                    sqrt_price_next,
443                    current_sqrt_price,
444                    current_liquidity,
445                    false,
446                )?;
447                let amount1 = get_amount1_delta(
448                    sqrt_price_next,
449                    current_sqrt_price,
450                    current_liquidity,
451                    true,
452                )?;
453                (amount1, amount0)
454            };
455
456            // Accumulate total amounts for this tick range
457            total_amount_in = safe_add_u256(total_amount_in, amount_in)?;
458            total_amount_out = safe_add_u256(total_amount_out, amount_out)?;
459
460            // If this tick is "initialized" (meaning its someone's position boundary), update the
461            // liquidity when crossing it
462            // For zero_for_one, liquidity is removed when crossing a tick
463            // For one_for_zero, liquidity is added when crossing a tick
464            if let Some(info) = next_tick_info {
465                let liquidity_raw = info.net_liquidity;
466                let liquidity_delta = if zero_for_one { -liquidity_raw } else { liquidity_raw };
467                current_liquidity =
468                    liquidity_math::add_liquidity_delta(current_liquidity, liquidity_delta)?;
469            }
470
471            // Move to the next tick position
472            current_tick = if zero_for_one { next_tick - 1 } else { next_tick };
473            current_sqrt_price = sqrt_price_next;
474        }
475
476        Ok((u256_to_biguint(total_amount_in), u256_to_biguint(total_amount_out)))
477    }
478
479    fn delta_transition(
480        &mut self,
481        delta: ProtocolStateDelta,
482        _tokens: &HashMap<Bytes, Token>,
483        _balances: &Balances,
484    ) -> Result<(), TransitionError> {
485        // Swap steps taken from the old state do not hold for the new one.
486        self.step_cache = SwapStepCache::default();
487        // apply attribute changes
488        if let Some(liquidity) = delta
489            .updated_attributes
490            .get("liquidity")
491        {
492            self.liquidity = u128::try_from(liquidity.clone())?;
493        }
494        if let Some(sqrt_price) = delta
495            .updated_attributes
496            .get("sqrt_price_x96")
497        {
498            self.sqrt_price = U256::from_be_slice(sqrt_price);
499        }
500        if let Some(default_fee) = delta
501            .updated_attributes
502            .get("default_fee")
503        {
504            self.default_fee = u32::try_from(default_fee.clone())?;
505        }
506        if let Some(custom_fee) = delta
507            .updated_attributes
508            .get("custom_fee")
509        {
510            self.custom_fee = u32::try_from(custom_fee.clone())?;
511        }
512        if let Some(tick) = delta.updated_attributes.get("tick") {
513            self.tick = i32::try_from(tick.clone())?.into();
514        }
515
516        // apply tick & observations changes
517        for (key, value) in delta.updated_attributes.iter() {
518            // tick liquidity keys are in the format "ticks/{tick_index}/net_liquidity"
519            if key.starts_with("ticks/") {
520                let parts: Vec<&str> = key.split('/').collect();
521                Arc::make_mut(&mut self.ticks)
522                    .set_tick_liquidity(
523                        parts[1]
524                            .parse::<i32>()
525                            .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
526                        i128::try_from(value.clone())?,
527                    )
528                    .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
529            }
530        }
531        // delete ticks - ignores deletes for attributes other than tick liquidity
532        for key in delta.deleted_attributes.iter() {
533            // tick liquidity keys are in the format "ticks/{tick_index}/net_liquidity"
534            if key.starts_with("ticks/") {
535                let parts: Vec<&str> = key.split('/').collect();
536                Arc::make_mut(&mut self.ticks)
537                    .set_tick_liquidity(
538                        parts[1]
539                            .parse::<i32>()
540                            .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
541                        0,
542                    )
543                    .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
544            }
545        }
546        Ok(())
547    }
548
549    /// Answers [`SwapConstraint::PoolTargetPrice`] with one native swap and no `price_points`.
550    /// [`SwapConstraint::TradeLimitPrice`] uses the numerical search.
551    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
552        match params.swap_constraint() {
553            SwapConstraint::TradeLimitPrice { .. } => {
554                crate::evm::query_pool_swap::query_pool_swap(self, params)
555            }
556            SwapConstraint::PoolTargetPrice {
557                target,
558                tolerance,
559                min_amount_in: _,
560                max_amount_in: _,
561            } => self.swap_to_target_price(params, target, *tolerance),
562        }
563    }
564
565    fn clone_box(&self) -> Box<dyn ProtocolSim> {
566        Box::new(self.clone())
567    }
568
569    fn as_any(&self) -> &dyn Any {
570        self
571    }
572
573    fn as_any_mut(&mut self) -> &mut dyn Any {
574        self
575    }
576
577    fn eq(&self, other: &dyn ProtocolSim) -> bool {
578        if let Some(other_state) = other
579            .as_any()
580            .downcast_ref::<VelodromeSlipstreamsState>()
581        {
582            self.liquidity == other_state.liquidity &&
583                self.sqrt_price == other_state.sqrt_price &&
584                self.get_fee() == other_state.get_fee() &&
585                self.tick == other_state.tick &&
586                self.ticks == other_state.ticks
587        } else {
588            false
589        }
590    }
591}
592
593#[cfg(test)]
594mod tests {
595    use alloy::primitives::{Sign, I256, U256};
596    use rstest::rstest;
597    use tycho_common::{models::Chain, simulation::errors::SimulationError};
598
599    use super::*;
600    use crate::evm::{
601        protocol::utils::uniswap::{
602            tick_list::TickInfo,
603            tick_math::{
604                get_sqrt_ratio_at_tick, get_tick_at_sqrt_ratio, MAX_SQRT_RATIO, MIN_SQRT_RATIO,
605                MIN_TICK,
606            },
607        },
608        query_pool_swap::test_helpers::{target_price_params, to_price},
609    };
610
611    fn create_basic_test_pool() -> VelodromeSlipstreamsState {
612        let sqrt_price = get_sqrt_ratio_at_tick(0).expect("Failed to calculate sqrt price");
613        let ticks = vec![TickInfo::new(-120, 0).unwrap(), TickInfo::new(120, 0).unwrap()];
614        VelodromeSlipstreamsState::new(
615            100_000_000_000_000_000_000u128,
616            sqrt_price,
617            3000,
618            0,
619            1,
620            0,
621            ticks,
622        )
623        .expect("Failed to create pool")
624    }
625
626    #[rstest]
627    #[case::no_custom_fee(0, 0.003)]
628    #[case::zero_fee_indicator(420, 0.0)]
629    #[case::custom_fee(500, 0.0005)]
630    fn test_fee_resolves_custom_fee(#[case] custom_fee: u32, #[case] expected: f64) {
631        let sqrt_price = get_sqrt_ratio_at_tick(0).unwrap();
632        let ticks = vec![TickInfo::new(-120, 0).unwrap(), TickInfo::new(120, 0).unwrap()];
633        let pool = VelodromeSlipstreamsState::new(
634            10u128.pow(20),
635            sqrt_price,
636            3000,
637            custom_fee,
638            1,
639            0,
640            ticks,
641        )
642        .unwrap();
643
644        assert_eq!(pool.fee(), expected);
645    }
646
647    #[test]
648    fn test_partial_step_updates_tick_when_price_moves_without_crossing_initialized_tick() {
649        let pool = create_basic_test_pool();
650        let amount =
651            I256::checked_from_sign_and_abs(Sign::Positive, U256::from(100_000_000_000_000_000u64))
652                .unwrap();
653
654        let result = pool
655            .swap(true, amount, None)
656            .expect("swap should stay within the current liquidity range");
657        let expected_tick =
658            get_tick_at_sqrt_ratio(result.sqrt_price).expect("new sqrt price should map to a tick");
659
660        assert_ne!(result.sqrt_price, pool.sqrt_price);
661        assert_ne!(result.sqrt_price, get_sqrt_ratio_at_tick(-120).unwrap());
662        assert_ne!(expected_tick, pool.tick.value());
663        assert_eq!(result.tick.value(), expected_tick);
664    }
665
666    #[test]
667    fn test_swap_keeps_boundary_tick_when_price_does_not_move() {
668        let mut pool = create_basic_test_pool();
669        pool.tick = PoolTick::from(-1);
670        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1u64)).unwrap();
671
672        let result = pool
673            .swap(true, amount, None)
674            .expect("swap should consume the input as fee without moving price");
675
676        assert_eq!(result.sqrt_price, pool.sqrt_price);
677        assert_eq!(get_tick_at_sqrt_ratio(result.sqrt_price).unwrap(), 0);
678        assert_eq!(result.tick, pool.tick);
679    }
680
681    #[test]
682    fn test_swap_price_limit_out_of_range_returns_error() {
683        let pool = create_basic_test_pool();
684        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
685
686        let result = pool.swap(true, amount, Some(pool.sqrt_price));
687        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
688
689        let result = pool.swap(true, amount, Some(MIN_SQRT_RATIO));
690        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
691
692        let result = pool.swap(false, amount, Some(pool.sqrt_price));
693        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
694
695        let result = pool.swap(false, amount, Some(MAX_SQRT_RATIO));
696        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
697    }
698
699    #[test]
700    fn test_swap_at_extreme_price_returns_error() {
701        let sqrt_price = MIN_SQRT_RATIO + U256::from(1u64);
702        let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
703        let ticks =
704            vec![TickInfo::new(MIN_TICK, 0).unwrap(), TickInfo::new(MIN_TICK + 1, 0).unwrap()];
705        let pool = VelodromeSlipstreamsState::new(
706            100_000_000_000_000_000_000u128,
707            sqrt_price,
708            3000,
709            0,
710            1,
711            tick,
712            ticks,
713        )
714        .expect("Failed to create pool");
715
716        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
717        let result = pool.swap(true, amount, None);
718        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
719    }
720
721    fn token_pair() -> (Token, Token) {
722        let token_x = Token::new(&Bytes::from([0x01; 20]), "X", 18, 0, &[], Chain::Ethereum, 100);
723        let token_y = Token::new(&Bytes::from([0x02; 20]), "Y", 18, 0, &[], Chain::Ethereum, 100);
724        (token_x, token_y)
725    }
726
727    #[rstest]
728    fn test_query_pool_swap_target_price_lands_in_band(#[values(true, false)] sell_x: bool) {
729        let pool = create_basic_test_pool();
730        let (token_x, token_y) = token_pair();
731        let (token_in, token_out) =
732            if sell_x { (&token_x, &token_y) } else { (&token_y, &token_x) };
733        let target = 0.995;
734        let tolerance = 1e-4;
735        let params = target_price_params(
736            token_in,
737            token_out,
738            to_price(target, token_in, token_out),
739            tolerance,
740        );
741
742        let swap = pool.query_pool_swap(&params).unwrap();
743
744        let new_spot = swap
745            .new_state()
746            .spot_price(token_in, token_out)
747            .unwrap();
748        assert!(new_spot >= target && new_spot <= target * (1.0 + tolerance), "spot {new_spot}");
749        assert!(swap.price_points().is_none(), "the native path returns no price points");
750        let quote = pool
751            .get_amount_out(swap.amount_in().clone(), token_in, token_out)
752            .unwrap();
753        assert_eq!(&quote.amount, swap.amount_out());
754    }
755
756    /// A target less than half the tolerance below spot puts the swap limit above spot.
757    #[test]
758    fn test_query_pool_swap_target_price_falls_back_to_search() {
759        let pool = create_basic_test_pool();
760        let (token_x, token_y) = token_pair();
761        let params =
762            target_price_params(&token_x, &token_y, to_price(1.0 - 1e-5, &token_x, &token_y), 1e-4);
763
764        let swap = pool.query_pool_swap(&params).unwrap();
765
766        assert!(swap.price_points().is_some(), "the numerical search returns price points");
767    }
768
769    /// With maximum liquidity, the native swap spends its whole input allowance far above a very
770    /// low target.
771    #[test]
772    fn test_query_pool_swap_target_price_out_of_reach_falls_back_to_search() {
773        let sqrt_price = get_sqrt_ratio_at_tick(0).unwrap();
774        let ticks = vec![TickInfo::new(MIN_TICK, 0).unwrap(), TickInfo::new(-MIN_TICK, 0).unwrap()];
775        let pool =
776            VelodromeSlipstreamsState::new(u128::MAX, sqrt_price, 3000, 0, 1, 0, ticks).unwrap();
777        let (token_x, token_y) = token_pair();
778        let target = Price::new(BigUint::from(1u8), BigUint::from(1u8) << 100usize);
779        let target_f64 = 2f64.powi(-100);
780        let tolerance = 1e-4;
781        let params = target_price_params(&token_x, &token_y, target, tolerance);
782
783        let swap = pool.query_pool_swap(&params).unwrap();
784
785        let new_spot = swap
786            .new_state()
787            .spot_price(&token_x, &token_y)
788            .unwrap();
789        assert!(
790            new_spot >= target_f64 && new_spot <= target_f64 * (1.0 + tolerance),
791            "spot {new_spot} is outside the band of target {target_f64}"
792        );
793        assert!(swap.price_points().is_some(), "the numerical search returns price points");
794    }
795
796    #[test]
797    fn test_query_pool_swap_target_price_at_spot() {
798        let pool = create_basic_test_pool();
799        let (token_x, token_y) = token_pair();
800        let params = target_price_params(
801            &token_x,
802            &token_y,
803            Price::new(BigUint::from(1u64), BigUint::from(1u64)),
804            1e-4,
805        );
806
807        let swap = pool.query_pool_swap(&params).unwrap();
808
809        assert!(swap.amount_in().is_zero());
810        assert!(swap.amount_out().is_zero());
811        assert!(swap.new_state().eq(&pool));
812    }
813
814    #[test]
815    fn test_query_pool_swap_target_price_above_spot() {
816        let pool = create_basic_test_pool();
817        let (token_x, token_y) = token_pair();
818        let params =
819            target_price_params(&token_x, &token_y, to_price(1.01, &token_x, &token_y), 1e-4);
820
821        let result = pool.query_pool_swap(&params);
822
823        assert!(matches!(result, Err(SimulationError::InvalidInput(..))), "got {result:?}");
824    }
825}
826
827#[cfg(test)]
828mod tick_list_sharing_tests {
829    use std::collections::{HashMap, HashSet};
830
831    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
832
833    use super::*;
834    use crate::evm::protocol::utils::uniswap::tick_math::get_sqrt_ratio_at_tick;
835
836    #[test]
837    fn test_delta_transition_leaves_clones_ticks_unchanged() {
838        let original = VelodromeSlipstreamsState::new(
839            100_000_000_000_000_000_000u128,
840            get_sqrt_ratio_at_tick(0).unwrap(),
841            3000,
842            0,
843            1,
844            0,
845            vec![TickInfo::new(-120, 10000).unwrap(), TickInfo::new(120, -10000).unwrap()],
846        )
847        .unwrap();
848        let mut updated = original.clone();
849        let delta = ProtocolStateDelta {
850            component_id: "State1".to_owned(),
851            updated_attributes: HashMap::from([(
852                "ticks/-120/net_liquidity".to_string(),
853                Bytes::from(20000_i128.to_be_bytes().to_vec()),
854            )]),
855            deleted_attributes: HashSet::new(),
856        };
857
858        updated
859            .delta_transition(delta, &HashMap::new(), &Balances::default())
860            .unwrap();
861
862        assert_eq!(
863            updated
864                .ticks
865                .get_tick(-120)
866                .unwrap()
867                .net_liquidity,
868            20000
869        );
870        assert_eq!(
871            original
872                .ticks
873                .get_tick(-120)
874                .unwrap()
875                .net_liquidity,
876            10000
877        );
878    }
879}
880
881#[cfg(test)]
882mod step_cache_tests {
883    use std::{
884        collections::{HashMap, HashSet},
885        str::FromStr,
886    };
887
888    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
889
890    use super::*;
891    use crate::evm::protocol::utils::uniswap::swap_step_cache::test_fixtures::{
892        amount_orders, test_amounts, test_ticks, wbtc_weth, LIQUIDITY, SQRT_PRICE, TICK,
893    };
894
895    fn test_pool() -> VelodromeSlipstreamsState {
896        VelodromeSlipstreamsState::new(
897            LIQUIDITY,
898            U256::from_str(SQRT_PRICE).unwrap(),
899            500,
900            0,
901            10,
902            TICK,
903            test_ticks(),
904        )
905        .unwrap()
906    }
907
908    /// A quote's amount, gas and new state, or its error, as text.
909    fn format_quote_result(
910        pool: &VelodromeSlipstreamsState,
911        amount: &BigUint,
912        sell: &Token,
913        buy: &Token,
914    ) -> String {
915        match pool.get_amount_out(amount.clone(), sell, buy) {
916            Ok(result) => {
917                let state = result
918                    .new_state
919                    .as_any()
920                    .downcast_ref::<VelodromeSlipstreamsState>()
921                    .unwrap();
922                format!(
923                    "{} {} {} {} {}",
924                    result.amount,
925                    result.gas,
926                    state.sqrt_price,
927                    state.tick.value(),
928                    state.liquidity
929                )
930            }
931            Err(error) => format!("error {error}"),
932        }
933    }
934
935    #[test]
936    fn test_step_cache_quotes_match_a_fresh_state_in_any_order() {
937        let (wbtc, weth) = wbtc_weth();
938        for (sell, buy, smallest) in [(&wbtc, &weth, 1_000u64), (&weth, &wbtc, 1_000_000_000)] {
939            for order in amount_orders(&test_amounts(smallest)) {
940                let shared = test_pool();
941                for amount in &order {
942                    assert_eq!(
943                        format_quote_result(&shared, amount, sell, buy),
944                        format_quote_result(&test_pool(), amount, sell, buy),
945                        "selling {amount} {}",
946                        sell.symbol
947                    );
948                }
949                let steps = shared
950                    .step_cache
951                    .min_inputs(sell < buy)
952                    .len();
953                assert!(steps > 2, "only {steps} steps cached");
954            }
955        }
956    }
957
958    #[test]
959    fn test_step_cache_quotes_match_a_fresh_state_at_each_cached_step() {
960        let (wbtc, weth) = wbtc_weth();
961        // Amounts that run past the last tick, so the cache covers the whole tick list. Selling
962        // WETH needs a far larger amount to leave its first tick.
963        for (sell, buy, doublings) in [(&wbtc, &weth, 30u32), (&weth, &wbtc, 70)] {
964            let cached = test_pool();
965            #[expect(
966                clippy::let_underscore_must_use,
967                reason = "the quote may run out of liquidity; only the step cache it fills is used"
968            )]
969            let _ = cached.get_amount_out(BigUint::from(10u32) << doublings, sell, buy);
970            let boundaries = cached.step_cache.min_inputs(sell < buy);
971            assert!(boundaries.len() > 2, "only {} steps cached", boundaries.len());
972            for boundary in boundaries.into_iter().skip(1) {
973                for amount in [boundary - U256::from(1u64), boundary, boundary + U256::from(1u64)] {
974                    let amount = u256_to_biguint(amount);
975                    assert_eq!(
976                        format_quote_result(&cached, &amount, sell, buy),
977                        format_quote_result(&test_pool(), &amount, sell, buy),
978                        "selling {amount} {}",
979                        sell.symbol
980                    );
981                }
982            }
983        }
984    }
985
986    #[test]
987    fn test_step_cache_of_a_swapped_state() {
988        let (wbtc, weth) = wbtc_weth();
989        let pool = test_pool();
990        let swapped = pool
991            .get_amount_out(BigUint::from(300_000_000u64), &wbtc, &weth)
992            .unwrap()
993            .new_state;
994        let swapped = swapped
995            .as_any()
996            .downcast_ref::<VelodromeSlipstreamsState>()
997            .unwrap();
998        // A serde round trip gives the same state with an empty step cache.
999        let fresh: VelodromeSlipstreamsState =
1000            serde_json::from_value(serde_json::to_value(swapped).unwrap()).unwrap();
1001
1002        for amount in test_amounts(1_000).iter().rev() {
1003            assert_eq!(
1004                format_quote_result(swapped, amount, &wbtc, &weth),
1005                format_quote_result(&fresh, amount, &wbtc, &weth),
1006                "selling {amount} WBTC"
1007            );
1008        }
1009    }
1010
1011    #[test]
1012    fn test_step_cache_restarts_after_delta_transition() {
1013        let (wbtc, weth) = wbtc_weth();
1014        let large = BigUint::from(3_000_000_000u64);
1015        // Only a crossed tick's liquidity changes, so the price, tick and liquidity the cache
1016        // starts from stay the same.
1017        let delta = || ProtocolStateDelta {
1018            component_id: "State1".to_owned(),
1019            updated_attributes: HashMap::from([(
1020                "ticks/255820/net_liquidity".to_string(),
1021                Bytes::from(
1022                    1_000_000_000_000_000i128
1023                        .to_be_bytes()
1024                        .to_vec(),
1025                ),
1026            )]),
1027            deleted_attributes: HashSet::new(),
1028        };
1029        let mut cached = test_pool();
1030        cached
1031            .get_amount_out(large.clone(), &wbtc, &weth)
1032            .unwrap();
1033        let mut fresh = test_pool();
1034
1035        cached
1036            .delta_transition(delta(), &HashMap::new(), &Balances::default())
1037            .unwrap();
1038        fresh
1039            .delta_transition(delta(), &HashMap::new(), &Balances::default())
1040            .unwrap();
1041
1042        assert_eq!(
1043            format_quote_result(&cached, &large, &wbtc, &weth),
1044            format_quote_result(&fresh, &large, &wbtc, &weth)
1045        );
1046    }
1047}