Skip to main content

tycho_simulation/evm/protocol/ramses_v3/
state.rs

1use std::{any::Any, collections::HashMap, sync::Arc};
2
3use alloy::primitives::{Sign, I256, U256};
4use num_bigint::BigUint;
5use serde::{Deserialize, Serialize};
6use tracing::trace;
7use tycho_common::{
8    dto::ProtocolStateDelta,
9    models::token::Token,
10    simulation::{
11        errors::{SimulationError, TransitionError},
12        protocol_sim::{
13            Balances, GetAmountOutResult, PoolSwap, ProtocolSim, QueryPoolSwapParams,
14            SwapConstraint,
15        },
16    },
17    Bytes,
18};
19
20use crate::evm::protocol::{
21    clmm::clmm_swap_to_price,
22    safe_math::{safe_add_u256, safe_sub_u256},
23    u256_num::u256_to_biguint,
24    utils::{
25        add_fee_markup,
26        uniswap::{
27            liquidity_math,
28            pool_tick::PoolTick,
29            sqrt_price_math::{get_amount0_delta, get_amount1_delta, sqrt_price_q96_to_f64},
30            swap_math::{self, SwapStepResult},
31            swap_step_cache::{StepCacheKey, StepCacheRun, SwapStepCache},
32            tick_list::{TickInfo, TickList, TickListErrorKind},
33            tick_math::{
34                get_sqrt_ratio_at_tick_cached, MAX_SQRT_RATIO, MAX_TICK, MIN_SQRT_RATIO, MIN_TICK,
35            },
36            StepComputation, SwapResults, SwapState,
37        },
38    },
39};
40
41// Gas model for a Ramses V3 swap. Constants start from the Uniswap V3 estimator and are nudged for
42// Ramses' extra gauge/period accounting (the second `grossFeeGrowthGlobal` accumulator, the
43// `advancePeriod` bookkeeping, and the richer `Tick.cross`). Calibrated against two on-chain
44// Polygon swaps on the USDC/USD.e pool:
45// - 0 tick crossings: ~141.5k gas total (~74k base, ~56k settlement, ~5k step)
46//   0x8fddae1260f40d7d22c0dc4b995ab1e84423adc523e71bbda503f735610db995
47// - 1 tick crossing:  ~184.1k gas total
48//   0xe884fa71e94c4c88d8e225fdc425e4df2321692343e51d06f8e5427729c34010
49// The ~42.5k delta = one extra math step + bitmap scan + the cross itself (its feeGrowthOutside /
50// gauge / period SSTOREs plus the oracle observation a tick change triggers).
51
52// Pre/post loop overhead: cold SLOADs (slot0, liquidity, feeGrowthGlobal) + cold SSTOREs (slot0,
53// liquidity) at end of swap. Uniswap V3 budgets ~70k here; Ramses adds the `grossFeeGrowthGlobal`
54// write and `advancePeriod` period bookkeeping (~+8k on-chain), hence ~78k.
55const SWAP_BASE_GAS: u64 = 78_000;
56// Bitmap word scan (cold SLOAD of tickBitmap word)
57const GAS_PER_BITMAP_WORD: u64 = 2_100;
58// swap math step: getSqrtRatioAtTick + computeSwapStep + amount accounting + getTickAtSqrtRatio
59const GAS_PER_SWAP_MATH_STEP: u64 = 5_400;
60// Initialized tick crossing: Ramses' cross() writes feeGrowthOutside plus gauge/period checkpoints
61// (seconds-per-liquidity, tickCumulative, period start tick) and triggers an oracle observation.
62// Measured at ~35k (the ~42.5k one-cross delta minus the extra math step + bitmap scan).
63const GAS_PER_INITIALIZED_TICK_CROSS: u64 = 35_000;
64// Output transfer + balanceBefore + callback + balanceAfter.
65const V3_CALLBACK_SETTLEMENT_GAS: u64 = 70_000;
66// Conservative max gas budget for a single swap (Ethereum transaction gas limit)
67const MAX_SWAP_GAS: u64 = 16_700_000;
68const MAX_TICKS_CROSSED: u64 = (MAX_SWAP_GAS - SWAP_BASE_GAS) / GAS_PER_INITIALIZED_TICK_CROSS;
69
70/// State of a Ramses V3 pool.
71///
72/// Mirrors `UniswapV3State` but, because the Ramses swap fee is governance-mutable and pools are
73/// keyed by tick spacing, `fee` is stored as a raw `u32` (hundredths of a bip) and `tick_spacing`
74/// is tracked explicitly rather than being derived from the fee tier.
75#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
76pub struct RamsesV3State {
77    liquidity: u128,
78    sqrt_price: U256,
79    fee: u32,
80    tick: PoolTick,
81    tick_spacing: u16,
82    /// The tick list, shared by this state, its clones and the states its swaps return, so a quote
83    /// does not copy it. Change it only through `Arc::make_mut`, which copies the list while
84    /// another state shares it.
85    ticks: Arc<TickList>,
86    /// Swap steps already taken from this state, shared by its clones. The steps hold only for
87    /// this state's price, tick, liquidity, fee and ticks. `delta_transition` and
88    /// `clone_post_swap` replace the cache with an empty one, and any other code that changes
89    /// those fields must do the same.
90    #[serde(skip)]
91    step_cache: SwapStepCache,
92}
93
94impl RamsesV3State {
95    /// Creates a new instance of `RamsesV3State`.
96    ///
97    /// # Arguments
98    /// - `liquidity`: The initial liquidity of the pool.
99    /// - `sqrt_price`: The square root of the current price.
100    /// - `fee`: The current swap fee, in hundredths of a bip (1_000_000 = 100%).
101    /// - `tick_spacing`: The tick spacing of the pool (its immutable key).
102    /// - `tick`: The current tick of the pool.
103    /// - `ticks`: A vector of `TickInfo` representing the tick information for the pool.
104    pub fn new(
105        liquidity: u128,
106        sqrt_price: U256,
107        fee: u32,
108        tick_spacing: u16,
109        tick: i32,
110        ticks: Vec<TickInfo>,
111    ) -> Result<Self, SimulationError> {
112        let tick_list = TickList::from(tick_spacing, ticks)?;
113        Ok(RamsesV3State {
114            liquidity,
115            sqrt_price,
116            fee,
117            tick: tick.into(),
118            tick_spacing,
119            ticks: Arc::new(tick_list),
120            step_cache: SwapStepCache::default(),
121        })
122    }
123
124    /// A clone of this state with the final price, tick and liquidity of a swap, and an empty
125    /// step cache.
126    fn clone_post_swap(&self, sqrt_price: U256, tick: PoolTick, liquidity: u128) -> Self {
127        let mut state = self.clone();
128        state.sqrt_price = sqrt_price;
129        state.tick = tick;
130        state.liquidity = liquidity;
131        state.step_cache = SwapStepCache::default();
132        state
133    }
134
135    fn swap(
136        &self,
137        zero_for_one: bool,
138        amount_specified: I256,
139        sqrt_price_limit: Option<U256>,
140    ) -> Result<SwapResults, SimulationError> {
141        if !self.ticks.has_initialized_ticks() {
142            return Err(SimulationError::RecoverableError("No liquidity".to_string()));
143        }
144        let price_limit = if let Some(limit) = sqrt_price_limit {
145            limit
146        } else if zero_for_one {
147            safe_add_u256(MIN_SQRT_RATIO, U256::ONE)?
148        } else {
149            safe_sub_u256(MAX_SQRT_RATIO, U256::ONE)?
150        };
151
152        let price_limit_valid = if zero_for_one {
153            price_limit > MIN_SQRT_RATIO && price_limit < self.sqrt_price
154        } else {
155            price_limit < MAX_SQRT_RATIO && price_limit > self.sqrt_price
156        };
157        if !price_limit_valid {
158            return Err(SimulationError::InvalidInput("Price limit out of range".into(), None));
159        }
160
161        let exact_input = amount_specified > I256::from_raw(U256::from(0u64));
162
163        let mut state = SwapState {
164            amount_remaining: amount_specified,
165            amount_calculated: I256::from_raw(U256::from(0u64)),
166            sqrt_price: self.sqrt_price,
167            tick: self.tick.value().into(),
168            liquidity: self.liquidity,
169        };
170        let mut gas_used = U256::from(SWAP_BASE_GAS);
171
172        // Only exact-input swaps with no price limit use the step cache. The cache finds a step by
173        // its input, which an exact-output swap does not know. A cached step can also lie past a
174        // price limit.
175        let cache_key = if exact_input && sqrt_price_limit.is_none() {
176            StepCacheKey::new(
177                self.sqrt_price,
178                state.tick.value(),
179                self.liquidity,
180                self.fee,
181                gas_used,
182            )
183        } else {
184            None
185        };
186        let mut cache_run = StepCacheRun::new(
187            &self.step_cache,
188            zero_for_one,
189            cache_key,
190            amount_specified.unsigned_abs(),
191        );
192        if let Some(progress) = cache_run.apply_cached_progress(&mut state) {
193            gas_used = progress.gas;
194        }
195        while state.amount_remaining != I256::from_raw(U256::from(0u64)) &&
196            state.sqrt_price != price_limit
197        {
198            let (mut next_tick, next_tick_info) = match self
199                .ticks
200                .next_initialized_tick_within_one_word(state.tick.value(), zero_for_one)
201            {
202                Ok((tick, info)) => {
203                    gas_used = safe_add_u256(gas_used, U256::from(GAS_PER_BITMAP_WORD))?;
204                    (tick, info)
205                }
206                Err(tick_err) => match tick_err.kind {
207                    TickListErrorKind::TicksExeeded => {
208                        let new_state = self.clone_post_swap(
209                            state.sqrt_price,
210                            state.tick.clone(),
211                            state.liquidity,
212                        );
213                        return Err(SimulationError::InvalidInput(
214                            "Ticks exceeded".into(),
215                            Some(GetAmountOutResult::new(
216                                u256_to_biguint(state.amount_calculated.abs().into_raw()),
217                                u256_to_biguint(gas_used),
218                                Box::new(new_state),
219                            )),
220                        ));
221                    }
222                    TickListErrorKind::BelowSmallest | TickListErrorKind::AtOrAboveLargest => {
223                        return Err(SimulationError::FatalError("Unknown error".to_string()))
224                    }
225                },
226            };
227
228            next_tick = next_tick.clamp(MIN_TICK, MAX_TICK);
229
230            let sqrt_price_start = state.sqrt_price;
231            let sqrt_price_next = match next_tick_info {
232                Some(info) => info.sqrt_price,
233                None => get_sqrt_ratio_at_tick_cached(next_tick)?,
234            };
235            let SwapStepResult { sqrt_price, amount_in_with_fee, amount_out } =
236                swap_math::compute_swap_step(
237                    state.sqrt_price,
238                    RamsesV3State::get_sqrt_ratio_target(
239                        sqrt_price_next,
240                        price_limit,
241                        zero_for_one,
242                    ),
243                    state.liquidity,
244                    state.amount_remaining,
245                    self.fee,
246                )?;
247            state.sqrt_price = sqrt_price;
248
249            let step = StepComputation {
250                sqrt_price_start,
251                tick_next: next_tick,
252                sqrt_price_next,
253                amount_in_with_fee,
254                amount_out,
255            };
256
257            gas_used = safe_add_u256(gas_used, U256::from(GAS_PER_SWAP_MATH_STEP))?;
258
259            if exact_input {
260                state.amount_remaining -=
261                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
262                        .unwrap();
263                state.amount_calculated -=
264                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
265            } else {
266                state.amount_remaining +=
267                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
268                state.amount_calculated +=
269                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
270                        .unwrap();
271            }
272            if state.sqrt_price == step.sqrt_price_next {
273                if let Some(info) = next_tick_info {
274                    let liquidity_raw = info.net_liquidity;
275                    let liquidity_net = if zero_for_one { -liquidity_raw } else { liquidity_raw };
276                    state.liquidity =
277                        liquidity_math::add_liquidity_delta(state.liquidity, liquidity_net)?;
278                    gas_used = safe_add_u256(gas_used, U256::from(GAS_PER_INITIALIZED_TICK_CROSS))?;
279                }
280                state.tick =
281                    PoolTick::from(if zero_for_one { step.tick_next - 1 } else { step.tick_next });
282            } else if state.sqrt_price != step.sqrt_price_start {
283                state.tick = PoolTick::at_sqrt_price(state.sqrt_price)?;
284            }
285            cache_run.cache_progress(&step, &state, gas_used);
286        }
287        Ok(SwapResults {
288            amount_calculated: state.amount_calculated,
289            amount_specified,
290            amount_remaining: state.amount_remaining,
291            sqrt_price: state.sqrt_price,
292            liquidity: state.liquidity,
293            tick: state.tick,
294            gas_used: safe_add_u256(gas_used, U256::from(V3_CALLBACK_SETTLEMENT_GAS))?,
295        })
296    }
297
298    fn get_sqrt_ratio_target(
299        sqrt_price_next: U256,
300        sqrt_price_limit: U256,
301        zero_for_one: bool,
302    ) -> U256 {
303        let cond1 = if zero_for_one {
304            sqrt_price_next < sqrt_price_limit
305        } else {
306            sqrt_price_next > sqrt_price_limit
307        };
308
309        if cond1 {
310            sqrt_price_limit
311        } else {
312            sqrt_price_next
313        }
314    }
315}
316
317#[typetag::serde]
318impl ProtocolSim for RamsesV3State {
319    fn fee(&self) -> f64 {
320        self.fee as f64 / 1_000_000.0
321    }
322
323    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
324        let price = if base < quote {
325            sqrt_price_q96_to_f64(self.sqrt_price, base.decimals, quote.decimals)?
326        } else {
327            1.0f64 / sqrt_price_q96_to_f64(self.sqrt_price, quote.decimals, base.decimals)?
328        };
329        Ok(add_fee_markup(price, self.fee()))
330    }
331
332    fn get_amount_out(
333        &self,
334        amount_in: BigUint,
335        token_in: &Token,
336        token_out: &Token,
337    ) -> Result<GetAmountOutResult, SimulationError> {
338        let zero_for_one = token_in < token_out;
339        let amount_specified = U256::try_from_be_slice(&amount_in.to_bytes_be())
340            .and_then(|unsigned_amount_in| {
341                I256::checked_from_sign_and_abs(Sign::Positive, unsigned_amount_in)
342            })
343            .ok_or_else(|| {
344                SimulationError::InvalidInput("I256 overflow: amount_in".to_string(), None)
345            })?;
346
347        let result = self.swap(zero_for_one, amount_specified, None)?;
348
349        trace!(?amount_in, ?token_in, ?token_out, ?zero_for_one, ?result, "RAMSES V3 SWAP");
350        let new_state = self.clone_post_swap(result.sqrt_price, result.tick, result.liquidity);
351
352        Ok(GetAmountOutResult::new(
353            u256_to_biguint(
354                result
355                    .amount_calculated
356                    .saturating_abs()
357                    .into_raw(),
358            ),
359            u256_to_biguint(result.gas_used),
360            Box::new(new_state),
361        ))
362    }
363
364    fn get_limits(
365        &self,
366        sell_token: Bytes,
367        buy_token: Bytes,
368    ) -> Result<(BigUint, BigUint), SimulationError> {
369        if !self.ticks.has_initialized_ticks() {
370            return Ok((BigUint::ZERO, BigUint::ZERO));
371        }
372
373        let zero_for_one = sell_token < buy_token;
374        let mut current_tick = self.tick.value();
375        let mut current_sqrt_price = self.sqrt_price;
376        let mut current_liquidity = self.liquidity;
377        let mut total_amount_in = U256::ZERO;
378        let mut total_amount_out = U256::ZERO;
379        let mut ticks_crossed: u64 = 0;
380
381        // Iterate through ticks in the direction of the swap
382        // Stops when: no more liquidity, no more ticks, or gas limit would be exceeded
383        while let Ok((tick, next_tick_info)) = self
384            .ticks
385            .next_initialized_tick_within_one_word(current_tick, zero_for_one)
386        {
387            // Cap iteration to prevent exceeding Ethereum's gas limit
388            if ticks_crossed == MAX_TICKS_CROSSED {
389                break;
390            }
391            ticks_crossed += 1;
392
393            // Clamp the tick value to ensure it's within valid range
394            let next_tick = tick.clamp(MIN_TICK, MAX_TICK);
395
396            let sqrt_price_next = match next_tick_info {
397                Some(info) => info.sqrt_price,
398                None => get_sqrt_ratio_at_tick_cached(next_tick)?,
399            };
400
401            // Calculate the amount of tokens swapped when moving from current_sqrt_price to
402            // sqrt_price_next. Direction determines which token is being swapped in vs out
403            let (amount_in, amount_out) = if zero_for_one {
404                let amount0 = get_amount0_delta(
405                    sqrt_price_next,
406                    current_sqrt_price,
407                    current_liquidity,
408                    true,
409                )?;
410                let amount1 = get_amount1_delta(
411                    sqrt_price_next,
412                    current_sqrt_price,
413                    current_liquidity,
414                    false,
415                )?;
416                (amount0, amount1)
417            } else {
418                let amount0 = get_amount0_delta(
419                    sqrt_price_next,
420                    current_sqrt_price,
421                    current_liquidity,
422                    false,
423                )?;
424                let amount1 = get_amount1_delta(
425                    sqrt_price_next,
426                    current_sqrt_price,
427                    current_liquidity,
428                    true,
429                )?;
430                (amount1, amount0)
431            };
432
433            // Accumulate total amounts for this tick range
434            total_amount_in = safe_add_u256(total_amount_in, amount_in)?;
435            total_amount_out = safe_add_u256(total_amount_out, amount_out)?;
436
437            // If this tick is "initialized" (meaning its someone's position boundary), update the
438            // liquidity when crossing it
439            // For zero_for_one, liquidity is removed when crossing a tick
440            // For one_for_zero, liquidity is added when crossing a tick
441            if let Some(info) = next_tick_info {
442                let liquidity_raw = info.net_liquidity;
443                let liquidity_delta = if zero_for_one { -liquidity_raw } else { liquidity_raw };
444
445                // Check if applying this liquidity delta would cause underflow
446                // If so, stop here rather than continuing with invalid state
447                match liquidity_math::add_liquidity_delta(current_liquidity, liquidity_delta) {
448                    Ok(new_liquidity) => {
449                        current_liquidity = new_liquidity;
450                    }
451                    Err(_) => {
452                        // Liquidity would underflow, stop iteration here
453                        // This represents the maximum liquidity we can actually use
454                        break;
455                    }
456                }
457            }
458
459            // Move to the next tick position
460            current_tick = if zero_for_one { next_tick - 1 } else { next_tick };
461            current_sqrt_price = sqrt_price_next;
462        }
463
464        Ok((u256_to_biguint(total_amount_in), u256_to_biguint(total_amount_out)))
465    }
466
467    fn delta_transition(
468        &mut self,
469        mut delta: ProtocolStateDelta,
470        _tokens: &HashMap<Bytes, Token>,
471        _balances: &Balances,
472    ) -> Result<(), TransitionError> {
473        // Swap steps taken from the old state do not hold for the new one.
474        self.step_cache = SwapStepCache::default();
475        // apply attribute changes
476        if let Some(liquidity) = delta
477            .updated_attributes
478            .remove("liquidity")
479        {
480            self.liquidity = liquidity.try_into()?;
481        }
482        if let Some(sqrt_price) = delta
483            .updated_attributes
484            .get("sqrt_price_x96")
485        {
486            self.sqrt_price = U256::from_be_slice(sqrt_price);
487        }
488        if let Some(tick) = delta.updated_attributes.remove("tick") {
489            self.tick = i32::try_from(tick)?.into();
490        }
491        // The Ramses swap fee is governance-mutable, so apply fee updates here.
492        if let Some(fee) = delta.updated_attributes.remove("fee") {
493            self.fee = fee.try_into()?;
494        }
495
496        // update ticks
497        for (key, value) in delta.updated_attributes {
498            let Some(tick) = key.strip_prefix("ticks/") else {
499                continue;
500            };
501
502            Arc::make_mut(&mut self.ticks)
503                .set_tick_liquidity(
504                    tick.parse::<i32>()
505                        .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
506                    i128::try_from(value)?,
507                )
508                .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
509        }
510        // delete ticks
511        for key in delta.deleted_attributes {
512            let Some(tick) = key.strip_prefix("ticks/") else {
513                continue;
514            };
515
516            Arc::make_mut(&mut self.ticks)
517                .set_tick_liquidity(
518                    tick.parse::<i32>()
519                        .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
520                    0,
521                )
522                .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
523        }
524        Ok(())
525    }
526
527    /// See [`ProtocolSim::query_pool_swap`] for the trait documentation.
528    ///
529    /// This method uses Ramses V3 internal swap logic by swapping an infinite amount of token_in
530    /// until the target price is reached.
531    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
532        if !self.ticks.has_initialized_ticks() {
533            return Err(SimulationError::RecoverableError("No liquidity".to_string()));
534        }
535
536        match params.swap_constraint() {
537            SwapConstraint::TradeLimitPrice { .. } => Err(SimulationError::InvalidInput(
538                "Ramses V3 does not support TradeLimitPrice constraint in query_pool_swap"
539                    .to_string(),
540                None,
541            )),
542            SwapConstraint::PoolTargetPrice {
543                target,
544                tolerance: _,
545                min_amount_in: _,
546                max_amount_in: _,
547            } => {
548                let (amount_in, amount_out, swap_result) = clmm_swap_to_price(
549                    self.sqrt_price,
550                    &params.token_in().address,
551                    &params.token_out().address,
552                    target,
553                    self.fee,
554                    Sign::Positive,
555                    |zero_for_one, amount_specified, sqrt_price_limit| {
556                        self.swap(zero_for_one, amount_specified, Some(sqrt_price_limit))
557                    },
558                )?;
559
560                let new_state = self.clone_post_swap(
561                    swap_result.sqrt_price,
562                    swap_result.tick,
563                    swap_result.liquidity,
564                );
565
566                Ok(PoolSwap::new(amount_in, amount_out, Box::new(new_state), None))
567            }
568        }
569    }
570
571    fn clone_box(&self) -> Box<dyn ProtocolSim> {
572        Box::new(self.clone())
573    }
574
575    fn as_any(&self) -> &dyn Any {
576        self
577    }
578
579    fn as_any_mut(&mut self) -> &mut dyn Any {
580        self
581    }
582
583    fn eq(&self, other: &dyn ProtocolSim) -> bool {
584        let Some(RamsesV3State {
585            liquidity,
586            sqrt_price,
587            fee,
588            tick,
589            tick_spacing,
590            ticks,
591            step_cache: _,
592        }) = other
593            .as_any()
594            .downcast_ref::<RamsesV3State>()
595        else {
596            return false;
597        };
598
599        &self.liquidity == liquidity &&
600            &self.sqrt_price == sqrt_price &&
601            &self.fee == fee &&
602            &self.tick == tick &&
603            &self.tick_spacing == tick_spacing &&
604            &self.ticks == ticks
605    }
606}
607
608#[cfg(test)]
609mod tests {
610    use std::{
611        collections::{HashMap, HashSet},
612        str::FromStr,
613    };
614
615    use num_bigint::ToBigUint;
616    use tycho_common::models::Chain;
617
618    use super::*;
619
620    // Real WBTC/WETH pool data (Uniswap V3, 0.05% fee, tick spacing 10). Because the Ramses swap
621    // math is identical to Uniswap V3, the same inputs must produce the same outputs — this test
622    // guards math parity with the upstream implementation.
623    #[test]
624    fn test_get_amount_out_math_parity() {
625        let wbtc = Token::new(
626            &Bytes::from_str("0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599").unwrap(),
627            "WBTC",
628            8,
629            0,
630            &[Some(10_000)],
631            Chain::Ethereum,
632            100,
633        );
634        let weth = Token::new(
635            &Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap(),
636            "WETH",
637            18,
638            0,
639            &[Some(10_000)],
640            Chain::Ethereum,
641            100,
642        );
643        let pool = RamsesV3State::new(
644            377952820878029838,
645            U256::from_str("28437325270877025820973479874632004").unwrap(),
646            500,
647            10,
648            255830,
649            vec![
650                TickInfo::new(255760, 1759015528199933i128).unwrap(),
651                TickInfo::new(255770, 6393138051835308i128).unwrap(),
652                TickInfo::new(255780, 228206673808681i128).unwrap(),
653                TickInfo::new(255820, 1319490609195820i128).unwrap(),
654                TickInfo::new(255830, 678916926147901i128).unwrap(),
655                TickInfo::new(255840, 12208947683433103i128).unwrap(),
656                TickInfo::new(255850, 1177970713095301i128).unwrap(),
657                TickInfo::new(255860, 8752304680520407i128).unwrap(),
658                TickInfo::new(255880, 1486478248067104i128).unwrap(),
659                TickInfo::new(255890, 1878744276123248i128).unwrap(),
660                TickInfo::new(255900, 77340284046725227i128).unwrap(),
661            ],
662        )
663        .unwrap();
664
665        let res = pool
666            .get_amount_out(500000000.to_biguint().unwrap(), &wbtc, &weth)
667            .unwrap();
668
669        assert_eq!(res.amount, BigUint::from_str("64352395915550406461").unwrap());
670    }
671
672    #[test]
673    fn test_delta_transition_updates_mutable_fee() {
674        let mut pool = RamsesV3State::new(
675            1000,
676            U256::from_str("1000").unwrap(),
677            500,
678            10,
679            100,
680            vec![TickInfo::new(255760, 10000).unwrap(), TickInfo::new(255900, -10000).unwrap()],
681        )
682        .unwrap();
683
684        let attributes: HashMap<String, Bytes> = [
685            ("liquidity".to_string(), Bytes::from(2000_u64.to_be_bytes().to_vec())),
686            // 3000 hundredths-of-a-bip, as emitted by the substreams (to_signed_bytes_be ->
687            // 0x0bb8)
688            ("fee".to_string(), Bytes::from(3000_u32.to_be_bytes().to_vec())),
689        ]
690        .into_iter()
691        .collect();
692        let delta = ProtocolStateDelta {
693            component_id: "State1".to_owned(),
694            updated_attributes: attributes,
695            deleted_attributes: HashSet::new(),
696        };
697
698        pool.delta_transition(delta, &HashMap::new(), &Balances::default())
699            .unwrap();
700
701        assert_eq!(pool.liquidity, 2000);
702        assert_eq!(pool.fee, 3000);
703        assert_eq!(pool.fee(), 0.003);
704    }
705}
706
707#[cfg(test)]
708mod tick_list_sharing_tests {
709    use std::collections::{HashMap, HashSet};
710
711    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
712
713    use super::*;
714
715    #[test]
716    fn test_delta_transition_leaves_clones_ticks_unchanged() {
717        let original = RamsesV3State::new(
718            1000,
719            U256::from(1000u64),
720            500,
721            10,
722            100,
723            vec![TickInfo::new(255760, 10000).unwrap(), TickInfo::new(255900, -10000).unwrap()],
724        )
725        .unwrap();
726        let mut updated = original.clone();
727        let delta = ProtocolStateDelta {
728            component_id: "State1".to_owned(),
729            updated_attributes: HashMap::from([(
730                "ticks/255760".to_string(),
731                Bytes::from(20000_i128.to_be_bytes().to_vec()),
732            )]),
733            deleted_attributes: HashSet::new(),
734        };
735
736        updated
737            .delta_transition(delta, &HashMap::new(), &Balances::default())
738            .unwrap();
739
740        assert_eq!(
741            updated
742                .ticks
743                .get_tick(255760)
744                .unwrap()
745                .net_liquidity,
746            20000
747        );
748        assert_eq!(
749            original
750                .ticks
751                .get_tick(255760)
752                .unwrap()
753                .net_liquidity,
754            10000
755        );
756    }
757}
758
759#[cfg(test)]
760mod step_cache_tests {
761    use std::{
762        collections::{HashMap, HashSet},
763        str::FromStr,
764    };
765
766    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
767
768    use super::*;
769    use crate::evm::protocol::utils::uniswap::swap_step_cache::test_fixtures::{
770        amount_orders, test_amounts, test_ticks, wbtc_weth, LIQUIDITY, SQRT_PRICE, TICK,
771    };
772
773    fn test_pool() -> RamsesV3State {
774        RamsesV3State::new(
775            LIQUIDITY,
776            U256::from_str(SQRT_PRICE).unwrap(),
777            500,
778            10,
779            TICK,
780            test_ticks(),
781        )
782        .unwrap()
783    }
784
785    /// A quote's amount, gas and new state, or its error, as text.
786    fn format_quote_result(
787        pool: &RamsesV3State,
788        amount: &BigUint,
789        sell: &Token,
790        buy: &Token,
791    ) -> String {
792        match pool.get_amount_out(amount.clone(), sell, buy) {
793            Ok(result) => {
794                let state = result
795                    .new_state
796                    .as_any()
797                    .downcast_ref::<RamsesV3State>()
798                    .unwrap();
799                format!(
800                    "{} {} {} {} {}",
801                    result.amount,
802                    result.gas,
803                    state.sqrt_price,
804                    state.tick.value(),
805                    state.liquidity
806                )
807            }
808            Err(error) => format!("error {error}"),
809        }
810    }
811
812    #[test]
813    fn test_step_cache_quotes_match_a_fresh_state_in_any_order() {
814        let (wbtc, weth) = wbtc_weth();
815        for (sell, buy, smallest) in [(&wbtc, &weth, 1_000u64), (&weth, &wbtc, 1_000_000_000)] {
816            for order in amount_orders(&test_amounts(smallest)) {
817                let shared = test_pool();
818                for amount in &order {
819                    assert_eq!(
820                        format_quote_result(&shared, amount, sell, buy),
821                        format_quote_result(&test_pool(), amount, sell, buy),
822                        "selling {amount} {}",
823                        sell.symbol
824                    );
825                }
826                let steps = shared
827                    .step_cache
828                    .min_inputs(sell < buy)
829                    .len();
830                assert!(steps > 2, "only {steps} steps cached");
831            }
832        }
833    }
834
835    #[test]
836    fn test_step_cache_quotes_match_a_fresh_state_at_each_cached_step() {
837        let (wbtc, weth) = wbtc_weth();
838        // Amounts that run past the last tick, so the cache covers the whole tick list. Selling
839        // WETH needs a far larger amount to leave its first tick.
840        for (sell, buy, doublings) in [(&wbtc, &weth, 30u32), (&weth, &wbtc, 70)] {
841            let cached = test_pool();
842            #[expect(
843                clippy::let_underscore_must_use,
844                reason = "the quote may run out of liquidity; only the step cache it fills is used"
845            )]
846            let _ = cached.get_amount_out(BigUint::from(10u32) << doublings, sell, buy);
847            let boundaries = cached.step_cache.min_inputs(sell < buy);
848            assert!(boundaries.len() > 2, "only {} steps cached", boundaries.len());
849            for boundary in boundaries.into_iter().skip(1) {
850                for amount in [boundary - U256::from(1u64), boundary, boundary + U256::from(1u64)] {
851                    let amount = u256_to_biguint(amount);
852                    assert_eq!(
853                        format_quote_result(&cached, &amount, sell, buy),
854                        format_quote_result(&test_pool(), &amount, sell, buy),
855                        "selling {amount} {}",
856                        sell.symbol
857                    );
858                }
859            }
860        }
861    }
862
863    #[test]
864    fn test_step_cache_of_a_swapped_state() {
865        let (wbtc, weth) = wbtc_weth();
866        let pool = test_pool();
867        let swapped = pool
868            .get_amount_out(BigUint::from(300_000_000u64), &wbtc, &weth)
869            .unwrap()
870            .new_state;
871        let swapped = swapped
872            .as_any()
873            .downcast_ref::<RamsesV3State>()
874            .unwrap();
875        // A serde round trip gives the same state with an empty step cache.
876        let fresh: RamsesV3State =
877            serde_json::from_value(serde_json::to_value(swapped).unwrap()).unwrap();
878
879        for amount in test_amounts(1_000).iter().rev() {
880            assert_eq!(
881                format_quote_result(swapped, amount, &wbtc, &weth),
882                format_quote_result(&fresh, amount, &wbtc, &weth),
883                "selling {amount} WBTC"
884            );
885        }
886    }
887
888    #[test]
889    fn test_step_cache_restarts_after_delta_transition() {
890        let (wbtc, weth) = wbtc_weth();
891        let large = BigUint::from(3_000_000_000u64);
892        // Only a crossed tick's liquidity changes, so the price, tick and liquidity the cache
893        // starts from stay the same.
894        let delta = || ProtocolStateDelta {
895            component_id: "State1".to_owned(),
896            updated_attributes: HashMap::from([(
897                "ticks/255820".to_string(),
898                Bytes::from(
899                    1_000_000_000_000_000i128
900                        .to_be_bytes()
901                        .to_vec(),
902                ),
903            )]),
904            deleted_attributes: HashSet::new(),
905        };
906        let mut cached = test_pool();
907        cached
908            .get_amount_out(large.clone(), &wbtc, &weth)
909            .unwrap();
910        let mut fresh = test_pool();
911
912        cached
913            .delta_transition(delta(), &HashMap::new(), &Balances::default())
914            .unwrap();
915        fresh
916            .delta_transition(delta(), &HashMap::new(), &Balances::default())
917            .unwrap();
918
919        assert_eq!(
920            format_quote_result(&cached, &large, &wbtc, &weth),
921            format_quote_result(&fresh, &large, &wbtc, &weth)
922        );
923    }
924}