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 mev_capture_v21::MevCaptureV21Pool, stableswap::StableswapPool,
39 },
40 },
41 u256_num::u256_to_f64,
42 },
43 utils::decimals_exponent,
44};
45
46const 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 MevCaptureV21(MevCaptureV21Pool),
64 BoostedFees(BoostedFeesPool),
65 Ve33(Ve33Pool),
66}
67
68fn sqrt_price_q128_to_f64(
69 x: U256,
70 (token0_decimals, token1_decimals): (u32, u32),
71) -> Result<f64, SimulationError> {
72 let token_correction = 10f64.powi(decimals_exponent(token0_decimals, token1_decimals)?);
73
74 let price = u256_to_f64(x)? / 2.0f64.powi(128);
75 Ok(price.powi(2) * token_correction)
76}
77
78impl EkuboV3State {
79 fn forward_overhead_gas(&self) -> u64 {
85 let extension = self.key().config.extension;
86 if SIGNED_EXCLUSIVE_SWAP_DEPLOYMENTS
87 .iter()
88 .any(|(_, deployment)| *deployment == extension)
89 {
90 SIGNED_EXCLUSIVE_SWAP_GAS
91 } else {
92 0
93 }
94 }
95}
96
97impl EkuboSwapToPrice for EkuboV3State {
98 type SqrtRatio = U256;
99
100 fn sqrt_ratio_in_range(sqrt_ratio: &BigUint) -> Option<U256> {
101 let sqrt_ratio = U256::try_from_be_slice(&sqrt_ratio.to_bytes_be())?;
102 (EVM_MIN_SQRT_RATIO..=EVM_MAX_SQRT_RATIO)
103 .contains(&sqrt_ratio)
104 .then_some(sqrt_ratio)
105 }
106
107 fn current_sqrt_ratio(&self) -> U256 {
108 self.sqrt_ratio()
109 }
110
111 fn quote_to_limit(
112 &self,
113 token_in: &Token,
114 amount: i128,
115 sqrt_ratio_limit: Option<U256>,
116 ) -> Result<(i128, u128, Self), SimulationError> {
117 let token = Address::try_from(&token_in.address[..]).map_err(|err| {
118 SimulationError::InvalidInput(format!("token_in invalid: {err}"), None)
119 })?;
120 let quote = self.quote(EvmTokenAmount { token, amount }, sqrt_ratio_limit)?;
121 Ok((quote.consumed_amount, quote.calculated_amount, quote.new_state))
122 }
123}
124
125#[typetag::serde]
126impl ProtocolSim for EkuboV3State {
127 fn fee(&self) -> f64 {
128 let fee = match self {
129 Self::Ve33(pool) => pool.swap_fee(),
130 Self::Concentrated(_) |
131 Self::FullRange(_) |
132 Self::Stableswap(_) |
133 Self::Oracle(_) |
134 Self::Twamm(_) |
135 Self::MevCapture(_) |
136 Self::MevCaptureV21(_) |
137 Self::BoostedFees(_) => self.key().config.fee,
138 };
139 fee as f64 / (2f64.powi(64))
140 }
141
142 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
143 let sqrt_ratio = self.sqrt_ratio();
144 let (base_decimals, quote_decimals) = (base.decimals, quote.decimals);
145
146 if base < quote {
147 sqrt_price_q128_to_f64(sqrt_ratio, (base_decimals, quote_decimals))
148 } else {
149 sqrt_price_q128_to_f64(sqrt_ratio, (quote_decimals, base_decimals))
150 .map(|price| 1.0f64 / price)
151 }
152 }
153
154 fn get_amount_out(
155 &self,
156 amount_in: BigUint,
157 token_in: &Token,
158 _token_out: &Token,
159 ) -> Result<GetAmountOutResult, SimulationError> {
160 let token_amount = EvmTokenAmount {
161 token: Address::try_from(&token_in.address[..]).map_err(|err| {
162 SimulationError::InvalidInput(format!("token_in invalid: {err}"), None)
163 })?,
164 amount: amount_in
165 .try_into()
166 .map_err(|_out_of_range| {
167 SimulationError::InvalidInput(
168 "amount in must fit into a i128".to_string(),
169 None,
170 )
171 })?,
172 };
173
174 let quote = self.quote(token_amount, None)?;
175
176 if quote.calculated_amount > i128::MAX as u128 {
177 return Err(SimulationError::RecoverableError(
178 "calculated amount exceeds i128::MAX".to_string(),
179 ));
180 }
181
182 let res = GetAmountOutResult {
183 amount: BigUint::from(quote.calculated_amount),
184 gas: BigUint::from(quote.gas) + BigUint::from(self.forward_overhead_gas()),
185 new_state: Box::new(quote.new_state),
186 };
187
188 if quote.consumed_amount != token_amount.amount {
189 return Err(SimulationError::InvalidInput(
190 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),
191 Some(res),
192 ));
193 }
194
195 Ok(res)
196 }
197
198 fn delta_transition(
199 &mut self,
200 delta: ProtocolStateDelta,
201 _tokens: &HashMap<Bytes, Token>,
202 _balances: &Balances,
203 ) -> Result<(), TransitionError> {
204 if let Some(liquidity) = delta
205 .updated_attributes
206 .get("liquidity")
207 {
208 self.set_liquidity(liquidity.clone().try_into()?);
209 }
210
211 if let Some(sqrt_price) = delta
212 .updated_attributes
213 .get("sqrt_ratio")
214 {
215 self.set_sqrt_ratio(U256::try_from_be_slice(sqrt_price).ok_or_else(|| {
216 TransitionError::DecodeError("failed to parse updated pool price".to_string())
217 })?);
218 }
219
220 self.finish_transition(delta.updated_attributes, delta.deleted_attributes)
221 }
222
223 fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
226 match params.swap_constraint() {
227 SwapConstraint::TradeLimitPrice { .. } => {
228 crate::evm::query_pool_swap::query_pool_swap(self, params)
229 }
230 SwapConstraint::PoolTargetPrice { target, .. } => {
231 swap_to_target_price(self, params, target, 0)
233 }
234 }
235 }
236
237 fn clone_box(&self) -> Box<dyn ProtocolSim> {
238 Box::new(self.clone())
239 }
240
241 fn as_any(&self) -> &dyn Any {
242 self
243 }
244
245 fn as_any_mut(&mut self) -> &mut dyn Any {
246 self
247 }
248
249 fn eq(&self, other: &dyn ProtocolSim) -> bool {
250 other
251 .as_any()
252 .downcast_ref::<EkuboV3State>()
253 .is_some_and(|other_state| self == other_state)
254 }
255
256 fn get_limits(
257 &self,
258 sell_token: Bytes,
259 _buy_token: Bytes,
260 ) -> Result<(BigUint, BigUint), SimulationError> {
261 let consumed_amount =
262 self.get_limit(Address::try_from(&sell_token[..]).map_err(|err| {
263 SimulationError::InvalidInput(format!("sell_token invalid: {err}"), None)
264 })?)?;
265
266 Ok((
268 BigUint::try_from(consumed_amount).map_err(|_out_of_range| {
269 SimulationError::FatalError(format!(
270 "Failed to convert consumed amount `{consumed_amount}` into BigUint"
271 ))
272 })?,
273 BigUint::ZERO,
274 ))
275 }
276}
277
278#[cfg(test)]
279mod tests {
280 use rstest::*;
281 use rstest_reuse::apply;
282
283 use super::*;
284 use crate::evm::protocol::{ekubo_common::test_helpers::*, ekubo_v3::test_cases::*};
285
286 #[rstest]
288 fn test_signed_exclusive_swap_gas_includes_the_forward_overhead() {
289 let signed = signed_exclusive_swap();
290 let (token0, token1) = (signed.token0(), signed.token1());
291 let (amount_in, _) = signed.swap_token0.clone();
292
293 let signed_gas = signed
294 .state_after_transition
295 .get_amount_out(amount_in.clone(), &token0, &token1)
296 .expect("signed pool quotes")
297 .gas;
298
299 let plain = concentrated();
300 let plain_gas = plain
301 .state_after_transition
302 .get_amount_out(amount_in, &plain.token0(), &plain.token1())
303 .expect("plain pool quotes")
304 .gas;
305
306 assert_eq!(
307 signed_gas - plain_gas,
308 BigUint::from(SIGNED_EXCLUSIVE_SWAP_GAS),
309 "the signed pool must carry exactly the forward overhead over an equivalent plain pool"
310 );
311 }
312
313 #[rstest]
315 fn test_other_pools_carry_no_forward_overhead() {
316 for case in [concentrated(), full_range(), mev_capture(), mev_capture_v21()] {
317 assert_eq!(
318 case.state_after_transition
319 .forward_overhead_gas(),
320 0,
321 "only a signed-exclusive pool is surcharged"
322 );
323 }
324 }
325
326 #[apply(all_cases)]
327 fn test_delta_transition(case: TestCase) {
328 let mut state = case.state_before_transition;
329
330 state
331 .delta_transition(
332 ProtocolStateDelta {
333 updated_attributes: case.transition_attributes,
334 ..Default::default()
335 },
336 &HashMap::default(),
337 &Balances::default(),
338 )
339 .expect("executing transition");
340
341 assert_eq!(state, case.state_after_transition);
342 }
343
344 #[apply(all_cases)]
345 fn test_get_amount_out(case: TestCase) {
346 let (token0, token1) = (case.token0(), case.token1());
347 let (amount_in, expected_out) = case.swap_token0;
348
349 let res = case
350 .state_after_transition
351 .get_amount_out(amount_in, &token0, &token1)
352 .expect("computing quote");
353
354 assert_eq!(res.amount, expected_out);
355 }
356
357 #[apply(all_cases)]
358 fn test_get_limits(case: TestCase) {
359 use std::ops::Deref;
360
361 let (token0, token1) = (case.token0(), case.token1());
362 let state = case.state_after_transition;
363
364 let max_amount_in = state
365 .get_limits(token0.address.deref().into(), token1.address.deref().into())
366 .expect("computing limits for token0")
367 .0;
368
369 assert_eq!(max_amount_in, case.expected_limit_token0);
370
371 state
372 .get_amount_out(max_amount_in, &token0, &token1)
373 .expect("quoting with limit");
374 }
375
376 #[rstest]
377 #[case::full_range(full_range(), 0.95)]
378 #[case::mev_capture_with_fee(mev_capture(), 0.999_995)]
379 #[case::stableswap(stableswap(), 0.99)]
380 #[case::twamm(twamm(), 0.99)]
381 fn test_query_pool_swap_target_price_lands_in_band(
382 #[case] case: TestCase,
383 #[case] multiplier: f64,
384 ) {
385 assert_lands_in_band(
386 &case.state_after_transition,
387 &case.token0(),
388 &case.token1(),
389 multiplier,
390 );
391 }
392
393 #[rstest]
394 fn test_query_pool_swap_target_price_above_spot(full_range: TestCase) {
395 let state = &full_range.state_after_transition;
396 assert_target_above_spot_rejected(state, &full_range.token0(), &full_range.token1());
397 }
398
399 #[rstest]
400 fn test_query_pool_swap_target_price_at_spot(full_range: TestCase) {
401 let state = &full_range.state_after_transition;
402 assert_target_at_spot_gives_zero_swap(state, &full_range.token0(), &full_range.token1());
403 }
404
405 #[rstest]
406 fn test_query_pool_swap_target_price_out_of_range(full_range: TestCase) {
407 let state = &full_range.state_after_transition;
408 assert_out_of_range_falls_back(state, &full_range.token0(), &full_range.token1());
409 }
410
411 #[rstest]
412 fn test_query_pool_swap_target_price_empty_pool(full_range: TestCase) {
413 let state = empty_full_range_state();
414 assert_missed_limit_falls_back(&state, &full_range.token0(), &full_range.token1());
415 }
416
417 #[test]
418 fn test_query_pool_swap_target_price_virtual_orders_past_target() {
419 let case = twamm();
420 let state = &case.state_after_transition;
421 assert_virtual_orders_applied_before_direction_check(state, &case.token0(), &case.token1());
422 }
423}