Skip to main content

tycho_simulation/evm/protocol/ekubo_v3/
state.rs

1use std::{
2    any::Any,
3    collections::{HashMap, HashSet},
4    fmt::Debug,
5};
6
7use ekubo_sdk::{
8    chain::evm::{EvmPoolKey, EvmTokenAmount, EVM_MAX_SQRT_RATIO, EVM_MIN_SQRT_RATIO},
9    U256,
10};
11use num_bigint::BigUint;
12use revm::primitives::Address;
13use serde::{Deserialize, Serialize};
14use tycho_common::{
15    dto::ProtocolStateDelta,
16    models::token::Token,
17    simulation::{
18        errors::{SimulationError, TransitionError},
19        protocol_sim::{
20            Balances, GetAmountOutResult, PoolSwap, ProtocolSim, QueryPoolSwapParams,
21            SwapConstraint,
22        },
23    },
24    Bytes,
25};
26
27use super::pool::{
28    concentrated::ConcentratedPool, full_range::FullRangePool, oracle::OraclePool,
29    twamm::TwammPool, ve33::Ve33Pool, EkuboPool, EkuboPoolQuote,
30};
31use crate::{
32    evm::protocol::{
33        ekubo_common::{swap_to_target_price, EkuboSwapToPrice},
34        ekubo_v3::{
35            addresses::SIGNED_EXCLUSIVE_SWAP_DEPLOYMENTS,
36            pool::{
37                boosted_fees::BoostedFeesPool, mev_capture::MevCapturePool,
38                stableswap::StableswapPool,
39            },
40        },
41        u256_num::u256_to_f64,
42    },
43    utils::decimals_exponent,
44};
45
46/// Gas cost of `Core.forward`, the signature check and the signed-fee accounting, on top of the
47/// swap itself.
48///
49/// Measured against a plain-swap baseline in Ekubo's `SignedExclusiveSwap.t.sol`: `forward` plus
50/// the signature check costs 37,852 and charging the signed fee costs another 24,521. Fynd signs a
51/// fee above zero, so the constant is the sum of both.
52const SIGNED_EXCLUSIVE_SWAP_GAS: u64 = 62_373;
53
54#[enum_delegate::implement(EkuboPool)]
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub enum EkuboV3State {
57    Concentrated(ConcentratedPool),
58    FullRange(FullRangePool),
59    Stableswap(StableswapPool),
60    Oracle(OraclePool),
61    Twamm(TwammPool),
62    MevCapture(MevCapturePool),
63    BoostedFees(BoostedFeesPool),
64    Ve33(Ve33Pool),
65}
66
67fn sqrt_price_q128_to_f64(
68    x: U256,
69    (token0_decimals, token1_decimals): (u32, u32),
70) -> Result<f64, SimulationError> {
71    let token_correction = 10f64.powi(decimals_exponent(token0_decimals, token1_decimals)?);
72
73    let price = u256_to_f64(x)? / 2.0f64.powi(128);
74    Ok(price.powi(2) * token_correction)
75}
76
77impl EkuboV3State {
78    /// Zero unless the extension forces the swap through `Core.forward`.
79    ///
80    /// The pool key carries no chain, so a SignedExclusiveSwap address from any deployment counts.
81    fn forward_overhead_gas(&self) -> u64 {
82        let extension = self.key().config.extension;
83        if SIGNED_EXCLUSIVE_SWAP_DEPLOYMENTS
84            .iter()
85            .any(|(_, deployment)| *deployment == extension)
86        {
87            SIGNED_EXCLUSIVE_SWAP_GAS
88        } else {
89            0
90        }
91    }
92}
93
94impl EkuboSwapToPrice for EkuboV3State {
95    type SqrtRatio = U256;
96
97    fn sqrt_ratio_in_range(sqrt_ratio: &BigUint) -> Option<U256> {
98        let sqrt_ratio = U256::try_from_be_slice(&sqrt_ratio.to_bytes_be())?;
99        (EVM_MIN_SQRT_RATIO..=EVM_MAX_SQRT_RATIO)
100            .contains(&sqrt_ratio)
101            .then_some(sqrt_ratio)
102    }
103
104    fn current_sqrt_ratio(&self) -> U256 {
105        self.sqrt_ratio()
106    }
107
108    fn quote_to_limit(
109        &self,
110        token_in: &Token,
111        amount: i128,
112        sqrt_ratio_limit: Option<U256>,
113    ) -> Result<(i128, u128, Self), SimulationError> {
114        let token = Address::try_from(&token_in.address[..]).map_err(|err| {
115            SimulationError::InvalidInput(format!("token_in invalid: {err}"), None)
116        })?;
117        let quote = self.quote(EvmTokenAmount { token, amount }, sqrt_ratio_limit)?;
118        Ok((quote.consumed_amount, quote.calculated_amount, quote.new_state))
119    }
120}
121
122#[typetag::serde]
123impl ProtocolSim for EkuboV3State {
124    fn fee(&self) -> f64 {
125        let fee = match self {
126            Self::Ve33(pool) => pool.swap_fee(),
127            Self::Concentrated(_) |
128            Self::FullRange(_) |
129            Self::Stableswap(_) |
130            Self::Oracle(_) |
131            Self::Twamm(_) |
132            Self::MevCapture(_) |
133            Self::BoostedFees(_) => self.key().config.fee,
134        };
135        fee as f64 / (2f64.powi(64))
136    }
137
138    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
139        let sqrt_ratio = self.sqrt_ratio();
140        let (base_decimals, quote_decimals) = (base.decimals, quote.decimals);
141
142        if base < quote {
143            sqrt_price_q128_to_f64(sqrt_ratio, (base_decimals, quote_decimals))
144        } else {
145            sqrt_price_q128_to_f64(sqrt_ratio, (quote_decimals, base_decimals))
146                .map(|price| 1.0f64 / price)
147        }
148    }
149
150    fn get_amount_out(
151        &self,
152        amount_in: BigUint,
153        token_in: &Token,
154        _token_out: &Token,
155    ) -> Result<GetAmountOutResult, SimulationError> {
156        let token_amount = EvmTokenAmount {
157            token: Address::try_from(&token_in.address[..]).map_err(|err| {
158                SimulationError::InvalidInput(format!("token_in invalid: {err}"), None)
159            })?,
160            amount: amount_in
161                .try_into()
162                .map_err(|_out_of_range| {
163                    SimulationError::InvalidInput(
164                        "amount in must fit into a i128".to_string(),
165                        None,
166                    )
167                })?,
168        };
169
170        let quote = self.quote(token_amount, None)?;
171
172        if quote.calculated_amount > i128::MAX as u128 {
173            return Err(SimulationError::RecoverableError(
174                "calculated amount exceeds i128::MAX".to_string(),
175            ));
176        }
177
178        let res = GetAmountOutResult {
179            amount: BigUint::from(quote.calculated_amount),
180            gas: BigUint::from(quote.gas) + BigUint::from(self.forward_overhead_gas()),
181            new_state: Box::new(quote.new_state),
182        };
183
184        if quote.consumed_amount != token_amount.amount {
185            return Err(SimulationError::InvalidInput(
186                format!("pool does not have enough liquidity to support complete swap. input amount: {input_amount}, consumed amount: {consumed_amount}", input_amount = token_amount.amount, consumed_amount = quote.consumed_amount),
187                Some(res),
188            ));
189        }
190
191        Ok(res)
192    }
193
194    fn delta_transition(
195        &mut self,
196        delta: ProtocolStateDelta,
197        _tokens: &HashMap<Bytes, Token>,
198        _balances: &Balances,
199    ) -> Result<(), TransitionError> {
200        if let Some(liquidity) = delta
201            .updated_attributes
202            .get("liquidity")
203        {
204            self.set_liquidity(liquidity.clone().try_into()?);
205        }
206
207        if let Some(sqrt_price) = delta
208            .updated_attributes
209            .get("sqrt_ratio")
210        {
211            self.set_sqrt_ratio(U256::try_from_be_slice(sqrt_price).ok_or_else(|| {
212                TransitionError::DecodeError("failed to parse updated pool price".to_string())
213            })?);
214        }
215
216        self.finish_transition(delta.updated_attributes, delta.deleted_attributes)
217    }
218
219    /// Solves [`SwapConstraint::PoolTargetPrice`] natively with a sqrt ratio limit. This path
220    /// ignores `min_amount_in`, `max_amount_in` and `tolerance`, and returns no price points.
221    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
222        match params.swap_constraint() {
223            SwapConstraint::TradeLimitPrice { .. } => {
224                crate::evm::query_pool_swap::query_pool_swap(self, params)
225            }
226            SwapConstraint::PoolTargetPrice { target, .. } => {
227                // Ekubo v3 spot prices have no fee markup.
228                swap_to_target_price(self, params, target, 0)
229            }
230        }
231    }
232
233    fn clone_box(&self) -> Box<dyn ProtocolSim> {
234        Box::new(self.clone())
235    }
236
237    fn as_any(&self) -> &dyn Any {
238        self
239    }
240
241    fn as_any_mut(&mut self) -> &mut dyn Any {
242        self
243    }
244
245    fn eq(&self, other: &dyn ProtocolSim) -> bool {
246        other
247            .as_any()
248            .downcast_ref::<EkuboV3State>()
249            .is_some_and(|other_state| self == other_state)
250    }
251
252    fn get_limits(
253        &self,
254        sell_token: Bytes,
255        _buy_token: Bytes,
256    ) -> Result<(BigUint, BigUint), SimulationError> {
257        let consumed_amount =
258            self.get_limit(Address::try_from(&sell_token[..]).map_err(|err| {
259                SimulationError::InvalidInput(format!("sell_token invalid: {err}"), None)
260            })?)?;
261
262        // TODO Update once exact out is supported
263        Ok((
264            BigUint::try_from(consumed_amount).map_err(|_out_of_range| {
265                SimulationError::FatalError(format!(
266                    "Failed to convert consumed amount `{consumed_amount}` into BigUint"
267                ))
268            })?,
269            BigUint::ZERO,
270        ))
271    }
272}
273
274#[cfg(test)]
275mod tests {
276    use rstest::*;
277    use rstest_reuse::apply;
278
279    use super::*;
280    use crate::evm::protocol::{ekubo_common::test_helpers::*, ekubo_v3::test_cases::*};
281
282    /// Both pools price identically, so the gas gap is exactly the forward overhead.
283    #[rstest]
284    fn test_signed_exclusive_swap_gas_includes_the_forward_overhead() {
285        let signed = signed_exclusive_swap();
286        let (token0, token1) = (signed.token0(), signed.token1());
287        let (amount_in, _) = signed.swap_token0.clone();
288
289        let signed_gas = signed
290            .state_after_transition
291            .get_amount_out(amount_in.clone(), &token0, &token1)
292            .expect("signed pool quotes")
293            .gas;
294
295        let plain = concentrated();
296        let plain_gas = plain
297            .state_after_transition
298            .get_amount_out(amount_in, &plain.token0(), &plain.token1())
299            .expect("plain pool quotes")
300            .gas;
301
302        assert_eq!(
303            signed_gas - plain_gas,
304            BigUint::from(SIGNED_EXCLUSIVE_SWAP_GAS),
305            "the signed pool must carry exactly the forward overhead over an equivalent plain pool"
306        );
307    }
308
309    /// Only a pool that cannot be swapped without `Core.forward` is surcharged.
310    #[rstest]
311    fn test_other_pools_carry_no_forward_overhead() {
312        for case in [concentrated(), full_range(), mev_capture()] {
313            assert_eq!(
314                case.state_after_transition
315                    .forward_overhead_gas(),
316                0,
317                "only a signed-exclusive pool is surcharged"
318            );
319        }
320    }
321
322    #[apply(all_cases)]
323    fn test_delta_transition(case: TestCase) {
324        let mut state = case.state_before_transition;
325
326        state
327            .delta_transition(
328                ProtocolStateDelta {
329                    updated_attributes: case.transition_attributes,
330                    ..Default::default()
331                },
332                &HashMap::default(),
333                &Balances::default(),
334            )
335            .expect("executing transition");
336
337        assert_eq!(state, case.state_after_transition);
338    }
339
340    #[apply(all_cases)]
341    fn test_get_amount_out(case: TestCase) {
342        let (token0, token1) = (case.token0(), case.token1());
343        let (amount_in, expected_out) = case.swap_token0;
344
345        let res = case
346            .state_after_transition
347            .get_amount_out(amount_in, &token0, &token1)
348            .expect("computing quote");
349
350        assert_eq!(res.amount, expected_out);
351    }
352
353    #[apply(all_cases)]
354    fn test_get_limits(case: TestCase) {
355        use std::ops::Deref;
356
357        let (token0, token1) = (case.token0(), case.token1());
358        let state = case.state_after_transition;
359
360        let max_amount_in = state
361            .get_limits(token0.address.deref().into(), token1.address.deref().into())
362            .expect("computing limits for token0")
363            .0;
364
365        assert_eq!(max_amount_in, case.expected_limit_token0);
366
367        state
368            .get_amount_out(max_amount_in, &token0, &token1)
369            .expect("quoting with limit");
370    }
371
372    #[rstest]
373    #[case::full_range(full_range(), 0.95)]
374    #[case::mev_capture_with_fee(mev_capture(), 0.999_995)]
375    #[case::stableswap(stableswap(), 0.99)]
376    #[case::twamm(twamm(), 0.99)]
377    fn test_query_pool_swap_target_price_lands_in_band(
378        #[case] case: TestCase,
379        #[case] multiplier: f64,
380    ) {
381        assert_lands_in_band(
382            &case.state_after_transition,
383            &case.token0(),
384            &case.token1(),
385            multiplier,
386        );
387    }
388
389    #[rstest]
390    fn test_query_pool_swap_target_price_above_spot(full_range: TestCase) {
391        let state = &full_range.state_after_transition;
392        assert_target_above_spot_rejected(state, &full_range.token0(), &full_range.token1());
393    }
394
395    #[rstest]
396    fn test_query_pool_swap_target_price_at_spot(full_range: TestCase) {
397        let state = &full_range.state_after_transition;
398        assert_target_at_spot_gives_zero_swap(state, &full_range.token0(), &full_range.token1());
399    }
400
401    #[rstest]
402    fn test_query_pool_swap_target_price_out_of_range(full_range: TestCase) {
403        let state = &full_range.state_after_transition;
404        assert_out_of_range_falls_back(state, &full_range.token0(), &full_range.token1());
405    }
406
407    #[rstest]
408    fn test_query_pool_swap_target_price_empty_pool(full_range: TestCase) {
409        let state = empty_full_range_state();
410        assert_missed_limit_falls_back(&state, &full_range.token0(), &full_range.token1());
411    }
412
413    #[test]
414    fn test_query_pool_swap_target_price_virtual_orders_past_target() {
415        let case = twamm();
416        let state = &case.state_after_transition;
417        assert_virtual_orders_applied_before_direction_check(state, &case.token0(), &case.token1());
418    }
419}