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::{biguint_to_uint, 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 =
369            I256::checked_from_sign_and_abs(Sign::Positive, biguint_to_uint(&amount_in)?)
370                .ok_or_else(|| {
371                    SimulationError::InvalidInput("I256 overflow: amount_in".to_string(), None)
372                })?;
373
374        let result = self.swap(zero_for_one, amount_specified, None)?;
375
376        trace!(?amount_in, ?token_in, ?token_out, ?zero_for_one, ?result, "SLIPSTREAMS SWAP");
377        let new_state = self.clone_post_swap(result.sqrt_price, result.tick, result.liquidity);
378
379        Ok(GetAmountOutResult::new(
380            u256_to_biguint(
381                result
382                    .amount_calculated
383                    .abs()
384                    .into_raw(),
385            ),
386            u256_to_biguint(result.gas_used),
387            Box::new(new_state),
388        ))
389    }
390
391    fn get_limits(
392        &self,
393        sell_token: Bytes,
394        buy_token: Bytes,
395    ) -> Result<(BigUint, BigUint), SimulationError> {
396        // If the pool has no liquidity, return zeros for both limits
397        if self.liquidity == 0 {
398            return Ok((BigUint::zero(), BigUint::zero()));
399        }
400
401        let zero_for_one = sell_token < buy_token;
402        let mut current_tick = self.tick.value();
403        let mut current_sqrt_price = self.sqrt_price;
404        let mut current_liquidity = self.liquidity;
405        let mut total_amount_in = U256::from(0u64);
406        let mut total_amount_out = U256::from(0u64);
407
408        // Iterate through all ticks in the direction of the swap
409        // Continues until there is no more liquidity in the pool or no more ticks to process
410        while let Ok((tick, next_tick_info)) = self
411            .ticks
412            .next_initialized_tick_within_one_word(current_tick, zero_for_one)
413        {
414            // Clamp the tick value to ensure it's within valid range
415            let next_tick = tick.clamp(MIN_TICK, MAX_TICK);
416
417            let sqrt_price_next = match next_tick_info {
418                Some(info) => info.sqrt_price,
419                None => get_sqrt_ratio_at_tick_cached(next_tick)?,
420            };
421
422            // Calculate the amount of tokens swapped when moving from current_sqrt_price to
423            // sqrt_price_next. Direction determines which token is being swapped in vs out
424            let (amount_in, amount_out) = if zero_for_one {
425                let amount0 = get_amount0_delta(
426                    sqrt_price_next,
427                    current_sqrt_price,
428                    current_liquidity,
429                    true,
430                )?;
431                let amount1 = get_amount1_delta(
432                    sqrt_price_next,
433                    current_sqrt_price,
434                    current_liquidity,
435                    false,
436                )?;
437                (amount0, amount1)
438            } else {
439                let amount0 = get_amount0_delta(
440                    sqrt_price_next,
441                    current_sqrt_price,
442                    current_liquidity,
443                    false,
444                )?;
445                let amount1 = get_amount1_delta(
446                    sqrt_price_next,
447                    current_sqrt_price,
448                    current_liquidity,
449                    true,
450                )?;
451                (amount1, amount0)
452            };
453
454            // Accumulate total amounts for this tick range
455            total_amount_in = safe_add_u256(total_amount_in, amount_in)?;
456            total_amount_out = safe_add_u256(total_amount_out, amount_out)?;
457
458            // If this tick is "initialized" (meaning its someone's position boundary), update the
459            // liquidity when crossing it
460            // For zero_for_one, liquidity is removed when crossing a tick
461            // For one_for_zero, liquidity is added when crossing a tick
462            if let Some(info) = next_tick_info {
463                let liquidity_raw = info.net_liquidity;
464                let liquidity_delta = if zero_for_one { -liquidity_raw } else { liquidity_raw };
465                current_liquidity =
466                    liquidity_math::add_liquidity_delta(current_liquidity, liquidity_delta)?;
467            }
468
469            // Move to the next tick position
470            current_tick = if zero_for_one { next_tick - 1 } else { next_tick };
471            current_sqrt_price = sqrt_price_next;
472        }
473
474        Ok((u256_to_biguint(total_amount_in), u256_to_biguint(total_amount_out)))
475    }
476
477    fn delta_transition(
478        &mut self,
479        delta: ProtocolStateDelta,
480        _tokens: &HashMap<Bytes, Token>,
481        _balances: &Balances,
482    ) -> Result<(), TransitionError> {
483        // Swap steps taken from the old state do not hold for the new one.
484        self.step_cache = SwapStepCache::default();
485        // apply attribute changes
486        if let Some(liquidity) = delta
487            .updated_attributes
488            .get("liquidity")
489        {
490            self.liquidity = u128::try_from(liquidity.clone())?;
491        }
492        if let Some(sqrt_price) = delta
493            .updated_attributes
494            .get("sqrt_price_x96")
495        {
496            self.sqrt_price = U256::from_be_slice(sqrt_price);
497        }
498        if let Some(default_fee) = delta
499            .updated_attributes
500            .get("default_fee")
501        {
502            self.default_fee = u32::try_from(default_fee.clone())?;
503        }
504        if let Some(custom_fee) = delta
505            .updated_attributes
506            .get("custom_fee")
507        {
508            self.custom_fee = u32::try_from(custom_fee.clone())?;
509        }
510        if let Some(tick) = delta.updated_attributes.get("tick") {
511            self.tick = i32::try_from(tick.clone())?.into();
512        }
513
514        // apply tick & observations changes
515        for (key, value) in delta.updated_attributes.iter() {
516            // tick liquidity keys are in the format "ticks/{tick_index}/net_liquidity"
517            if key.starts_with("ticks/") {
518                let parts: Vec<&str> = key.split('/').collect();
519                Arc::make_mut(&mut self.ticks)
520                    .set_tick_liquidity(
521                        parts[1]
522                            .parse::<i32>()
523                            .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
524                        i128::try_from(value.clone())?,
525                    )
526                    .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
527            }
528        }
529        // delete ticks - ignores deletes for attributes other than tick liquidity
530        for key in delta.deleted_attributes.iter() {
531            // tick liquidity keys are in the format "ticks/{tick_index}/net_liquidity"
532            if key.starts_with("ticks/") {
533                let parts: Vec<&str> = key.split('/').collect();
534                Arc::make_mut(&mut self.ticks)
535                    .set_tick_liquidity(
536                        parts[1]
537                            .parse::<i32>()
538                            .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
539                        0,
540                    )
541                    .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
542            }
543        }
544        Ok(())
545    }
546
547    /// Answers [`SwapConstraint::PoolTargetPrice`] with one native swap and no `price_points`.
548    /// [`SwapConstraint::TradeLimitPrice`] uses the numerical search.
549    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
550        match params.swap_constraint() {
551            SwapConstraint::TradeLimitPrice { .. } => {
552                crate::evm::query_pool_swap::query_pool_swap(self, params)
553            }
554            SwapConstraint::PoolTargetPrice {
555                target,
556                tolerance,
557                min_amount_in: _,
558                max_amount_in: _,
559            } => self.swap_to_target_price(params, target, *tolerance),
560        }
561    }
562
563    fn clone_box(&self) -> Box<dyn ProtocolSim> {
564        Box::new(self.clone())
565    }
566
567    fn as_any(&self) -> &dyn Any {
568        self
569    }
570
571    fn as_any_mut(&mut self) -> &mut dyn Any {
572        self
573    }
574
575    fn eq(&self, other: &dyn ProtocolSim) -> bool {
576        if let Some(other_state) = other
577            .as_any()
578            .downcast_ref::<VelodromeSlipstreamsState>()
579        {
580            self.liquidity == other_state.liquidity &&
581                self.sqrt_price == other_state.sqrt_price &&
582                self.get_fee() == other_state.get_fee() &&
583                self.tick == other_state.tick &&
584                self.ticks == other_state.ticks
585        } else {
586            false
587        }
588    }
589}
590
591#[cfg(test)]
592mod tests {
593    use alloy::primitives::{Sign, I256, U256};
594    use rstest::rstest;
595    use tycho_common::{models::Chain, simulation::errors::SimulationError};
596
597    use super::*;
598    use crate::evm::{
599        protocol::utils::uniswap::{
600            tick_list::TickInfo,
601            tick_math::{
602                get_sqrt_ratio_at_tick, get_tick_at_sqrt_ratio, MAX_SQRT_RATIO, MIN_SQRT_RATIO,
603                MIN_TICK,
604            },
605        },
606        query_pool_swap::test_helpers::{target_price_params, to_price},
607    };
608
609    fn create_basic_test_pool() -> VelodromeSlipstreamsState {
610        let sqrt_price = get_sqrt_ratio_at_tick(0).expect("Failed to calculate sqrt price");
611        let ticks = vec![TickInfo::new(-120, 0).unwrap(), TickInfo::new(120, 0).unwrap()];
612        VelodromeSlipstreamsState::new(
613            100_000_000_000_000_000_000u128,
614            sqrt_price,
615            3000,
616            0,
617            1,
618            0,
619            ticks,
620        )
621        .expect("Failed to create pool")
622    }
623
624    #[rstest]
625    #[case::no_custom_fee(0, 0.003)]
626    #[case::zero_fee_indicator(420, 0.0)]
627    #[case::custom_fee(500, 0.0005)]
628    fn test_fee_resolves_custom_fee(#[case] custom_fee: u32, #[case] expected: f64) {
629        let sqrt_price = get_sqrt_ratio_at_tick(0).unwrap();
630        let ticks = vec![TickInfo::new(-120, 0).unwrap(), TickInfo::new(120, 0).unwrap()];
631        let pool = VelodromeSlipstreamsState::new(
632            10u128.pow(20),
633            sqrt_price,
634            3000,
635            custom_fee,
636            1,
637            0,
638            ticks,
639        )
640        .unwrap();
641
642        assert_eq!(pool.fee(), expected);
643    }
644
645    #[test]
646    fn test_partial_step_updates_tick_when_price_moves_without_crossing_initialized_tick() {
647        let pool = create_basic_test_pool();
648        let amount =
649            I256::checked_from_sign_and_abs(Sign::Positive, U256::from(100_000_000_000_000_000u64))
650                .unwrap();
651
652        let result = pool
653            .swap(true, amount, None)
654            .expect("swap should stay within the current liquidity range");
655        let expected_tick =
656            get_tick_at_sqrt_ratio(result.sqrt_price).expect("new sqrt price should map to a tick");
657
658        assert_ne!(result.sqrt_price, pool.sqrt_price);
659        assert_ne!(result.sqrt_price, get_sqrt_ratio_at_tick(-120).unwrap());
660        assert_ne!(expected_tick, pool.tick.value());
661        assert_eq!(result.tick.value(), expected_tick);
662    }
663
664    #[test]
665    fn test_swap_keeps_boundary_tick_when_price_does_not_move() {
666        let mut pool = create_basic_test_pool();
667        pool.tick = PoolTick::from(-1);
668        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1u64)).unwrap();
669
670        let result = pool
671            .swap(true, amount, None)
672            .expect("swap should consume the input as fee without moving price");
673
674        assert_eq!(result.sqrt_price, pool.sqrt_price);
675        assert_eq!(get_tick_at_sqrt_ratio(result.sqrt_price).unwrap(), 0);
676        assert_eq!(result.tick, pool.tick);
677    }
678
679    #[test]
680    fn test_swap_price_limit_out_of_range_returns_error() {
681        let pool = create_basic_test_pool();
682        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
683
684        let result = pool.swap(true, amount, Some(pool.sqrt_price));
685        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
686
687        let result = pool.swap(true, amount, Some(MIN_SQRT_RATIO));
688        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
689
690        let result = pool.swap(false, amount, Some(pool.sqrt_price));
691        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
692
693        let result = pool.swap(false, amount, Some(MAX_SQRT_RATIO));
694        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
695    }
696
697    #[test]
698    fn test_swap_at_extreme_price_returns_error() {
699        let sqrt_price = MIN_SQRT_RATIO + U256::from(1u64);
700        let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
701        let ticks =
702            vec![TickInfo::new(MIN_TICK, 0).unwrap(), TickInfo::new(MIN_TICK + 1, 0).unwrap()];
703        let pool = VelodromeSlipstreamsState::new(
704            100_000_000_000_000_000_000u128,
705            sqrt_price,
706            3000,
707            0,
708            1,
709            tick,
710            ticks,
711        )
712        .expect("Failed to create pool");
713
714        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
715        let result = pool.swap(true, amount, None);
716        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
717    }
718
719    fn token_pair() -> (Token, Token) {
720        let token_x = Token::new(&Bytes::from([0x01; 20]), "X", 18, 0, &[], Chain::Ethereum, 100);
721        let token_y = Token::new(&Bytes::from([0x02; 20]), "Y", 18, 0, &[], Chain::Ethereum, 100);
722        (token_x, token_y)
723    }
724
725    #[rstest]
726    fn test_query_pool_swap_target_price_lands_in_band(#[values(true, false)] sell_x: bool) {
727        let pool = create_basic_test_pool();
728        let (token_x, token_y) = token_pair();
729        let (token_in, token_out) =
730            if sell_x { (&token_x, &token_y) } else { (&token_y, &token_x) };
731        let target = 0.995;
732        let tolerance = 1e-4;
733        let params = target_price_params(
734            token_in,
735            token_out,
736            to_price(target, token_in, token_out),
737            tolerance,
738        );
739
740        let swap = pool.query_pool_swap(&params).unwrap();
741
742        let new_spot = swap
743            .new_state()
744            .spot_price(token_in, token_out)
745            .unwrap();
746        assert!(new_spot >= target && new_spot <= target * (1.0 + tolerance), "spot {new_spot}");
747        assert!(swap.price_points().is_none(), "the native path returns no price points");
748        let quote = pool
749            .get_amount_out(swap.amount_in().clone(), token_in, token_out)
750            .unwrap();
751        assert_eq!(&quote.amount, swap.amount_out());
752    }
753
754    /// A target less than half the tolerance below spot puts the swap limit above spot.
755    #[test]
756    fn test_query_pool_swap_target_price_falls_back_to_search() {
757        let pool = create_basic_test_pool();
758        let (token_x, token_y) = token_pair();
759        let params =
760            target_price_params(&token_x, &token_y, to_price(1.0 - 1e-5, &token_x, &token_y), 1e-4);
761
762        let swap = pool.query_pool_swap(&params).unwrap();
763
764        assert!(swap.price_points().is_some(), "the numerical search returns price points");
765    }
766
767    /// With maximum liquidity, the native swap spends its whole input allowance far above a very
768    /// low target.
769    #[test]
770    fn test_query_pool_swap_target_price_out_of_reach_falls_back_to_search() {
771        let sqrt_price = get_sqrt_ratio_at_tick(0).unwrap();
772        let ticks = vec![TickInfo::new(MIN_TICK, 0).unwrap(), TickInfo::new(-MIN_TICK, 0).unwrap()];
773        let pool =
774            VelodromeSlipstreamsState::new(u128::MAX, sqrt_price, 3000, 0, 1, 0, ticks).unwrap();
775        let (token_x, token_y) = token_pair();
776        let target = Price::new(BigUint::from(1u8), BigUint::from(1u8) << 100usize);
777        let target_f64 = 2f64.powi(-100);
778        let tolerance = 1e-4;
779        let params = target_price_params(&token_x, &token_y, target, tolerance);
780
781        let swap = pool.query_pool_swap(&params).unwrap();
782
783        let new_spot = swap
784            .new_state()
785            .spot_price(&token_x, &token_y)
786            .unwrap();
787        assert!(
788            new_spot >= target_f64 && new_spot <= target_f64 * (1.0 + tolerance),
789            "spot {new_spot} is outside the band of target {target_f64}"
790        );
791        assert!(swap.price_points().is_some(), "the numerical search returns price points");
792    }
793
794    #[test]
795    fn test_query_pool_swap_target_price_at_spot() {
796        let pool = create_basic_test_pool();
797        let (token_x, token_y) = token_pair();
798        let params = target_price_params(
799            &token_x,
800            &token_y,
801            Price::new(BigUint::from(1u64), BigUint::from(1u64)),
802            1e-4,
803        );
804
805        let swap = pool.query_pool_swap(&params).unwrap();
806
807        assert!(swap.amount_in().is_zero());
808        assert!(swap.amount_out().is_zero());
809        assert!(swap.new_state().eq(&pool));
810    }
811
812    #[test]
813    fn test_query_pool_swap_target_price_above_spot() {
814        let pool = create_basic_test_pool();
815        let (token_x, token_y) = token_pair();
816        let params =
817            target_price_params(&token_x, &token_y, to_price(1.01, &token_x, &token_y), 1e-4);
818
819        let result = pool.query_pool_swap(&params);
820
821        assert!(matches!(result, Err(SimulationError::InvalidInput(..))), "got {result:?}");
822    }
823}
824
825#[cfg(test)]
826mod tick_list_sharing_tests {
827    use std::collections::{HashMap, HashSet};
828
829    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
830
831    use super::*;
832    use crate::evm::protocol::utils::uniswap::tick_math::get_sqrt_ratio_at_tick;
833
834    #[test]
835    fn test_delta_transition_leaves_clones_ticks_unchanged() {
836        let original = VelodromeSlipstreamsState::new(
837            100_000_000_000_000_000_000u128,
838            get_sqrt_ratio_at_tick(0).unwrap(),
839            3000,
840            0,
841            1,
842            0,
843            vec![TickInfo::new(-120, 10000).unwrap(), TickInfo::new(120, -10000).unwrap()],
844        )
845        .unwrap();
846        let mut updated = original.clone();
847        let delta = ProtocolStateDelta {
848            component_id: "State1".to_owned(),
849            updated_attributes: HashMap::from([(
850                "ticks/-120/net_liquidity".to_string(),
851                Bytes::from(20000_i128.to_be_bytes().to_vec()),
852            )]),
853            deleted_attributes: HashSet::new(),
854        };
855
856        updated
857            .delta_transition(delta, &HashMap::new(), &Balances::default())
858            .unwrap();
859
860        assert_eq!(
861            updated
862                .ticks
863                .get_tick(-120)
864                .unwrap()
865                .net_liquidity,
866            20000
867        );
868        assert_eq!(
869            original
870                .ticks
871                .get_tick(-120)
872                .unwrap()
873                .net_liquidity,
874            10000
875        );
876    }
877}
878
879#[cfg(test)]
880mod step_cache_tests {
881    use std::{
882        collections::{HashMap, HashSet},
883        str::FromStr,
884    };
885
886    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
887
888    use super::*;
889    use crate::evm::protocol::utils::uniswap::swap_step_cache::test_fixtures::{
890        amount_orders, test_amounts, test_ticks, wbtc_weth, LIQUIDITY, SQRT_PRICE, TICK,
891    };
892
893    fn test_pool() -> VelodromeSlipstreamsState {
894        VelodromeSlipstreamsState::new(
895            LIQUIDITY,
896            U256::from_str(SQRT_PRICE).unwrap(),
897            500,
898            0,
899            10,
900            TICK,
901            test_ticks(),
902        )
903        .unwrap()
904    }
905
906    /// A quote's amount, gas and new state, or its error, as text.
907    fn format_quote_result(
908        pool: &VelodromeSlipstreamsState,
909        amount: &BigUint,
910        sell: &Token,
911        buy: &Token,
912    ) -> String {
913        match pool.get_amount_out(amount.clone(), sell, buy) {
914            Ok(result) => {
915                let state = result
916                    .new_state
917                    .as_any()
918                    .downcast_ref::<VelodromeSlipstreamsState>()
919                    .unwrap();
920                format!(
921                    "{} {} {} {} {}",
922                    result.amount,
923                    result.gas,
924                    state.sqrt_price,
925                    state.tick.value(),
926                    state.liquidity
927                )
928            }
929            Err(error) => format!("error {error}"),
930        }
931    }
932
933    #[test]
934    fn test_step_cache_quotes_match_a_fresh_state_in_any_order() {
935        let (wbtc, weth) = wbtc_weth();
936        for (sell, buy, smallest) in [(&wbtc, &weth, 1_000u64), (&weth, &wbtc, 1_000_000_000)] {
937            for order in amount_orders(&test_amounts(smallest)) {
938                let shared = test_pool();
939                for amount in &order {
940                    assert_eq!(
941                        format_quote_result(&shared, amount, sell, buy),
942                        format_quote_result(&test_pool(), amount, sell, buy),
943                        "selling {amount} {}",
944                        sell.symbol
945                    );
946                }
947                let steps = shared
948                    .step_cache
949                    .min_inputs(sell < buy)
950                    .len();
951                assert!(steps > 2, "only {steps} steps cached");
952            }
953        }
954    }
955
956    #[test]
957    fn test_step_cache_quotes_match_a_fresh_state_at_each_cached_step() {
958        let (wbtc, weth) = wbtc_weth();
959        // Amounts that run past the last tick, so the cache covers the whole tick list. Selling
960        // WETH needs a far larger amount to leave its first tick.
961        for (sell, buy, doublings) in [(&wbtc, &weth, 30u32), (&weth, &wbtc, 70)] {
962            let cached = test_pool();
963            #[expect(
964                clippy::let_underscore_must_use,
965                reason = "the quote may run out of liquidity; only the step cache it fills is used"
966            )]
967            let _ = cached.get_amount_out(BigUint::from(10u32) << doublings, sell, buy);
968            let boundaries = cached.step_cache.min_inputs(sell < buy);
969            assert!(boundaries.len() > 2, "only {} steps cached", boundaries.len());
970            for boundary in boundaries.into_iter().skip(1) {
971                for amount in [boundary - U256::from(1u64), boundary, boundary + U256::from(1u64)] {
972                    let amount = u256_to_biguint(amount);
973                    assert_eq!(
974                        format_quote_result(&cached, &amount, sell, buy),
975                        format_quote_result(&test_pool(), &amount, sell, buy),
976                        "selling {amount} {}",
977                        sell.symbol
978                    );
979                }
980            }
981        }
982    }
983
984    #[test]
985    fn test_step_cache_of_a_swapped_state() {
986        let (wbtc, weth) = wbtc_weth();
987        let pool = test_pool();
988        let swapped = pool
989            .get_amount_out(BigUint::from(300_000_000u64), &wbtc, &weth)
990            .unwrap()
991            .new_state;
992        let swapped = swapped
993            .as_any()
994            .downcast_ref::<VelodromeSlipstreamsState>()
995            .unwrap();
996        // A serde round trip gives the same state with an empty step cache.
997        let fresh: VelodromeSlipstreamsState =
998            serde_json::from_value(serde_json::to_value(swapped).unwrap()).unwrap();
999
1000        for amount in test_amounts(1_000).iter().rev() {
1001            assert_eq!(
1002                format_quote_result(swapped, amount, &wbtc, &weth),
1003                format_quote_result(&fresh, amount, &wbtc, &weth),
1004                "selling {amount} WBTC"
1005            );
1006        }
1007    }
1008
1009    #[test]
1010    fn test_step_cache_restarts_after_delta_transition() {
1011        let (wbtc, weth) = wbtc_weth();
1012        let large = BigUint::from(3_000_000_000u64);
1013        // Only a crossed tick's liquidity changes, so the price, tick and liquidity the cache
1014        // starts from stay the same.
1015        let delta = || ProtocolStateDelta {
1016            component_id: "State1".to_owned(),
1017            updated_attributes: HashMap::from([(
1018                "ticks/255820/net_liquidity".to_string(),
1019                Bytes::from(
1020                    1_000_000_000_000_000i128
1021                        .to_be_bytes()
1022                        .to_vec(),
1023                ),
1024            )]),
1025            deleted_attributes: HashSet::new(),
1026        };
1027        let mut cached = test_pool();
1028        cached
1029            .get_amount_out(large.clone(), &wbtc, &weth)
1030            .unwrap();
1031        let mut fresh = test_pool();
1032
1033        cached
1034            .delta_transition(delta(), &HashMap::new(), &Balances::default())
1035            .unwrap();
1036        fresh
1037            .delta_transition(delta(), &HashMap::new(), &Balances::default())
1038            .unwrap();
1039
1040        assert_eq!(
1041            format_quote_result(&cached, &large, &wbtc, &weth),
1042            format_quote_result(&fresh, &large, &wbtc, &weth)
1043        );
1044    }
1045}