1use std::{
2 any::Any,
3 collections::{HashMap, HashSet},
4 fmt::Debug,
5};
6
7use evm_ekubo_sdk::{
8 math::{
9 tick::{MAX_SQRT_RATIO, MIN_SQRT_RATIO},
10 uint::U256,
11 },
12 quoting::types::{NodeKey, TokenAmount},
13};
14use num_bigint::BigUint;
15use serde::{Deserialize, Serialize};
16use tycho_common::{
17 dto::ProtocolStateDelta,
18 models::token::Token,
19 simulation::{
20 errors::{SimulationError, TransitionError},
21 protocol_sim::{
22 Balances, GetAmountOutResult, PoolSwap, ProtocolSim, QueryPoolSwapParams,
23 SwapConstraint,
24 },
25 },
26 Bytes,
27};
28
29use super::pool::{
30 base::BasePool, full_range::FullRangePool, oracle::OraclePool, twamm::TwammPool, EkuboPool,
31};
32use crate::{
33 evm::protocol::{
34 ekubo::pool::mev_resist::MevResistPool,
35 ekubo_common::{swap_to_target_price, EkuboSwapToPrice},
36 u256_num::u256_to_f64,
37 utils::add_fee_markup,
38 },
39 utils::decimals_exponent,
40};
41
42#[enum_delegate::implement(EkuboPool)]
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub enum EkuboState {
45 Base(BasePool),
46 FullRange(FullRangePool),
47 Oracle(OraclePool),
48 Twamm(TwammPool),
49 MevResist(MevResistPool),
50}
51
52fn sqrt_price_q128_to_f64(
53 x: U256,
54 (token0_decimals, token1_decimals): (u32, u32),
55) -> Result<f64, SimulationError> {
56 let token_correction = 10f64.powi(decimals_exponent(token0_decimals, token1_decimals)?);
57
58 let price = u256_to_f64(alloy::primitives::U256::from_limbs(x.0))? / 2.0f64.powi(128);
59 Ok(price.powi(2) * token_correction)
60}
61
62impl EkuboSwapToPrice for EkuboState {
63 type SqrtRatio = U256;
64
65 fn sqrt_ratio_in_range(sqrt_ratio: &BigUint) -> Option<U256> {
66 if sqrt_ratio.bits() > 256 {
67 return None;
68 }
69 let sqrt_ratio = U256::from_big_endian(&sqrt_ratio.to_bytes_be());
70 (MIN_SQRT_RATIO..=MAX_SQRT_RATIO)
71 .contains(&sqrt_ratio)
72 .then_some(sqrt_ratio)
73 }
74
75 fn current_sqrt_ratio(&self) -> U256 {
76 self.sqrt_ratio()
77 }
78
79 fn quote_to_limit(
80 &self,
81 token_in: &Token,
82 amount: i128,
83 sqrt_ratio_limit: Option<U256>,
84 ) -> Result<(i128, u128, Self), SimulationError> {
85 let token_amount = TokenAmount { token: U256::from_big_endian(&token_in.address), amount };
86 let quote = self.quote(token_amount, sqrt_ratio_limit)?;
87 Ok((quote.consumed_amount, quote.calculated_amount, quote.new_state))
88 }
89}
90
91#[typetag::serde]
92impl ProtocolSim for EkuboState {
93 fn fee(&self) -> f64 {
94 self.key().config.fee as f64 / (2f64.powi(64))
95 }
96
97 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
98 let sqrt_ratio = self.sqrt_ratio();
99 let (base_decimals, quote_decimals) = (base.decimals, quote.decimals);
100
101 let price = if base < quote {
102 sqrt_price_q128_to_f64(sqrt_ratio, (base_decimals, quote_decimals))?
103 } else {
104 1.0f64 / sqrt_price_q128_to_f64(sqrt_ratio, (quote_decimals, base_decimals))?
105 };
106 Ok(add_fee_markup(price, self.fee()))
107 }
108
109 fn get_amount_out(
110 &self,
111 amount_in: BigUint,
112 token_in: &Token,
113 _token_out: &Token,
114 ) -> Result<GetAmountOutResult, SimulationError> {
115 let token_amount = TokenAmount {
116 token: U256::from_big_endian(&token_in.address),
117 amount: amount_in
118 .try_into()
119 .map_err(|_out_of_range| {
120 SimulationError::InvalidInput(
121 "amount in must fit into a i128".to_string(),
122 None,
123 )
124 })?,
125 };
126
127 let quote = self.quote(token_amount, None)?;
128
129 if quote.calculated_amount > i128::MAX as u128 {
130 return Err(SimulationError::RecoverableError(
131 "calculated amount exceeds i128::MAX".to_string(),
132 ));
133 }
134
135 let res = GetAmountOutResult {
136 amount: BigUint::from(quote.calculated_amount),
137 gas: quote.gas.into(),
138 new_state: Box::new(quote.new_state),
139 };
140
141 if quote.consumed_amount != token_amount.amount {
142 return Err(SimulationError::InvalidInput(
143 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),
144 Some(res),
145 ));
146 }
147
148 Ok(res)
149 }
150
151 fn delta_transition(
152 &mut self,
153 delta: ProtocolStateDelta,
154 _tokens: &HashMap<Bytes, Token>,
155 _balances: &Balances,
156 ) -> Result<(), TransitionError> {
157 if let Some(liquidity) = delta
158 .updated_attributes
159 .get("liquidity")
160 {
161 self.set_liquidity(liquidity.clone().try_into()?);
162 }
163
164 if let Some(sqrt_price) = delta
165 .updated_attributes
166 .get("sqrt_ratio")
167 {
168 self.set_sqrt_ratio(U256::from_big_endian(sqrt_price));
169 }
170
171 self.finish_transition(delta.updated_attributes, delta.deleted_attributes)
172 }
173
174 fn clone_box(&self) -> Box<dyn ProtocolSim> {
175 Box::new(self.clone())
176 }
177
178 fn as_any(&self) -> &dyn Any {
179 self
180 }
181
182 fn as_any_mut(&mut self) -> &mut dyn Any {
183 self
184 }
185
186 fn eq(&self, other: &dyn ProtocolSim) -> bool {
187 other
188 .as_any()
189 .downcast_ref::<EkuboState>()
190 .is_some_and(|other_state| self == other_state)
191 }
192
193 fn get_limits(
194 &self,
195 sell_token: Bytes,
196 _buy_token: Bytes,
197 ) -> Result<(BigUint, BigUint), SimulationError> {
198 let consumed_amount = self.get_limit(U256::from_big_endian(&sell_token))?;
199
200 Ok((
202 BigUint::try_from(consumed_amount).map_err(|_out_of_range| {
203 SimulationError::FatalError(format!(
204 "Failed to convert consumed amount `{consumed_amount}` into BigUint"
205 ))
206 })?,
207 BigUint::ZERO,
208 ))
209 }
210
211 fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
214 match params.swap_constraint() {
215 SwapConstraint::TradeLimitPrice { .. } => {
216 crate::evm::query_pool_swap::query_pool_swap(self, params)
217 }
218 SwapConstraint::PoolTargetPrice { target, .. } => {
219 swap_to_target_price(self, params, target, self.key().config.fee)
220 }
221 }
222 }
223}
224
225#[cfg(test)]
226mod tests {
227 use evm_ekubo_sdk::{
228 math::{tick::MIN_SQRT_RATIO, uint::U256},
229 quoting::types::{Config, NodeKey, Tick},
230 };
231 use rstest::*;
232 use rstest_reuse::apply;
233
234 use super::*;
235 use crate::evm::protocol::{
236 ekubo::{pool::base::BasePool, test_cases::*},
237 ekubo_common::test_helpers::*,
238 };
239
240 #[apply(all_cases)]
241 fn test_delta_transition(case: TestCase) {
242 let mut state = case.state_before_transition;
243
244 state
245 .delta_transition(
246 ProtocolStateDelta {
247 updated_attributes: case.transition_attributes,
248 ..Default::default()
249 },
250 &HashMap::default(),
251 &Balances::default(),
252 )
253 .expect("executing transition");
254
255 assert_eq!(state, case.state_after_transition);
256 }
257
258 #[apply(all_cases)]
259 fn test_get_amount_out(case: TestCase) {
260 let (token0, token1) = (case.token0(), case.token1());
261 let (amount_in, expected_out) = case.swap_token0;
262
263 let res = case
264 .state_after_transition
265 .get_amount_out(amount_in, &token0, &token1)
266 .expect("computing quote");
267
268 assert_eq!(res.amount, expected_out);
269 }
270
271 #[apply(all_cases)]
272 fn test_get_limits(case: TestCase) {
273 use std::ops::Deref;
274
275 let (token0, token1) = (case.token0(), case.token1());
276 let state = case.state_after_transition;
277
278 let max_amount_in = state
279 .get_limits(token0.address.deref().into(), token1.address.deref().into())
280 .expect("computing limits for token0")
281 .0;
282
283 assert_eq!(max_amount_in, case.expected_limit_token0);
284
285 state
286 .get_amount_out(max_amount_in, &token0, &token1)
287 .expect("quoting with limit");
288 }
289
290 #[test]
291 fn test_get_limits_negative_consumed_amount() {
292 let eth_address = U256::zero();
296 let usdt_address_bytes =
297 hex::decode("dac17f958d2ee523a2206206994597c13d831ec7").expect("valid hex");
298 let usdt_address = U256::from_big_endian(&usdt_address_bytes);
299
300 let pool_key = NodeKey {
301 token0: eth_address,
302 token1: usdt_address,
303 config: Config { fee: 0, tick_spacing: 1000, extension: U256::zero() },
304 };
305
306 let state = EkuboState::Base(
309 BasePool::new(
310 pool_key,
311 vec![
312 Tick { index: 1000, liquidity_delta: 1 },
313 Tick { index: 2000, liquidity_delta: -1 },
314 ],
315 MIN_SQRT_RATIO, 0, -887272, )
319 .unwrap(),
320 );
321
322 let (limit, _) = state
323 .get_limits(
324 pool_key.token0.to_big_endian().into(),
325 pool_key.token1.to_big_endian().into(),
326 )
327 .unwrap();
328
329 assert_eq!(limit, BigUint::ZERO);
331 }
332
333 #[rstest]
334 #[case::full_range(full_range(), 0.95)]
335 #[case::mev_resist_with_fee(mev_resist(), 0.999_995)]
336 #[case::oracle(oracle(), 0.99)]
337 #[case::twamm(twamm(), 0.99)]
338 fn test_query_pool_swap_target_price_lands_in_band(
339 #[case] case: TestCase,
340 #[case] multiplier: f64,
341 ) {
342 assert_lands_in_band(
343 &case.state_after_transition,
344 &case.token0(),
345 &case.token1(),
346 multiplier,
347 );
348 }
349
350 #[rstest]
351 fn test_query_pool_swap_target_price_above_spot(full_range: TestCase) {
352 let state = &full_range.state_after_transition;
353 assert_target_above_spot_rejected(state, &full_range.token0(), &full_range.token1());
354 }
355
356 #[rstest]
357 fn test_query_pool_swap_target_price_at_spot(full_range: TestCase) {
358 let state = &full_range.state_after_transition;
359 assert_target_at_spot_gives_zero_swap(state, &full_range.token0(), &full_range.token1());
360 }
361
362 #[rstest]
363 fn test_query_pool_swap_target_price_out_of_range(full_range: TestCase) {
364 let state = &full_range.state_after_transition;
365 assert_out_of_range_falls_back(state, &full_range.token0(), &full_range.token1());
366 }
367
368 #[rstest]
369 fn test_query_pool_swap_target_price_empty_pool(full_range: TestCase) {
370 let state = empty_full_range_state();
371 assert_missed_limit_falls_back(&state, &full_range.token0(), &full_range.token1());
372 }
373
374 #[test]
375 fn test_query_pool_swap_target_price_virtual_orders_past_target() {
376 let case = twamm();
377 let state = &case.state_after_transition;
378 assert_virtual_orders_applied_before_direction_check(state, &case.token0(), &case.token1());
379 }
380}