1use std::{borrow::Cow, collections::HashMap};
2
3use alloy::primitives::aliases::B32;
4use ekubo_sdk::{
5 chain::evm::{
6 EvmConcentratedPoolConfig, EvmConcentratedPoolKey, EvmConcentratedPoolState,
7 EvmFullRangePoolState, EvmOraclePoolKey, EvmPoolTypeConfig, EvmTwammPoolKey,
8 },
9 quoting::{
10 pools::{
11 full_range::{FullRangePoolKey, FullRangePoolState, FullRangePoolTypeConfig},
12 mev_capture_v21_main::MevCaptureV21MainPoolState,
13 stableswap::{StableswapPoolKey, StableswapPoolState},
14 twamm::TwammPoolState,
15 },
16 types::{PoolConfig, Tick, TimeRateDelta},
17 util::find_nearest_initialized_tick_index,
18 },
19 U256,
20};
21use itertools::Itertools;
22use revm::primitives::Address;
23use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
24use tycho_common::{
25 models::{token::Token, Chain},
26 Bytes,
27};
28
29use super::{
30 addresses::{
31 BOOSTED_FEES_CONCENTRATED_ADDRESS, MEV_CAPTURE_ADDRESS, MEV_CAPTURE_V21_ETHEREUM_ADDRESS,
32 ORACLE_ADDRESS, SIGNED_EXCLUSIVE_SWAP_DEPLOYMENTS, TWAMM_ADDRESS_V1, TWAMM_ADDRESS_V2,
33 VE33_ROBINHOOD_ADDRESS,
34 },
35 attributes::{rate_deltas_from_attributes, ticks_from_attributes},
36 pool::{
37 boosted_fees::BoostedFeesPool,
38 concentrated::ConcentratedPool,
39 full_range::FullRangePool,
40 mev_capture::MevCapturePool,
41 mev_capture_v21::{self, MevCaptureV21Pool},
42 oracle::OraclePool,
43 stableswap::StableswapPool,
44 twamm::TwammPool,
45 ve33::{Ve33Pool, Ve33UnderlyingPool},
46 },
47 state::EkuboV3State,
48};
49use crate::protocol::{
50 errors::InvalidSnapshotError,
51 models::{DecoderContext, TryFromWithBlock},
52};
53
54pub enum ExtensionType {
55 NoSwapCallPoints,
56 Oracle,
57 Twamm,
58 MevCapture,
59 MevCaptureV21,
60 BoostedFees,
61 SignedExclusiveSwap,
62 Ve33,
63}
64
65fn has_no_swap_call_points(extension: Address) -> bool {
66 extension[0] & 0b0110_0000 == 0
69}
70
71pub fn extension_type(extension: Address, chain: Chain) -> Option<ExtensionType> {
72 Some(if has_no_swap_call_points(extension) {
73 ExtensionType::NoSwapCallPoints
74 } else if extension == ORACLE_ADDRESS {
75 ExtensionType::Oracle
76 } else if [TWAMM_ADDRESS_V2, TWAMM_ADDRESS_V1].contains(&extension) {
77 ExtensionType::Twamm
78 } else if extension == MEV_CAPTURE_ADDRESS {
79 ExtensionType::MevCapture
80 } else if chain == Chain::Ethereum && extension == MEV_CAPTURE_V21_ETHEREUM_ADDRESS {
81 ExtensionType::MevCaptureV21
82 } else if extension == BOOSTED_FEES_CONCENTRATED_ADDRESS {
83 ExtensionType::BoostedFees
84 } else if SIGNED_EXCLUSIVE_SWAP_DEPLOYMENTS.contains(&(chain, extension)) {
85 ExtensionType::SignedExclusiveSwap
86 } else if chain == Chain::Robinhood && extension == VE33_ROBINHOOD_ADDRESS {
87 ExtensionType::Ve33
88 } else {
89 return None;
90 })
91}
92
93struct TimedStateDetails {
94 rate_token0: u128,
95 rate_token1: u128,
96 last_time: u64,
97 rate_deltas: Vec<TimeRateDelta>,
98}
99
100impl TryFromWithBlock<ComponentWithState, BlockHeader> for EkuboV3State {
101 type Error = InvalidSnapshotError;
102
103 async fn try_from_with_header(
104 snapshot: ComponentWithState,
105 _block: BlockHeader,
106 _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
107 _all_tokens: &HashMap<Bytes, Token>,
108 _decoder_context: &DecoderContext,
109 ) -> Result<Self, Self::Error> {
110 let chain = snapshot.component.chain;
111 let static_attrs = snapshot.component.static_attributes;
112 let state_attrs = snapshot.state.attributes;
113
114 let (token0, token1) = (
115 parse_address(attribute(&static_attrs, "token0")?, "token0")?,
116 parse_address(attribute(&static_attrs, "token1")?, "token1")?,
117 );
118
119 let fee = u64::from_be_bytes(
120 attribute(&static_attrs, "fee")?
121 .as_ref()
122 .try_into()
123 .map_err(|err| {
124 InvalidSnapshotError::ValueError(format!("fee length mismatch: {err:?}"))
125 })?,
126 );
127
128 let pool_type_config = EvmPoolTypeConfig::try_from(
129 B32::try_from(attribute(&static_attrs, "pool_type_config")?.as_ref()).map_err(
130 |err| {
131 InvalidSnapshotError::ValueError(format!(
132 "pool_type_config length mismatch: {err:?}"
133 ))
134 },
135 )?,
136 )
137 .map_err(|err| {
138 InvalidSnapshotError::ValueError(format!("parsing pool_type_config: {err}"))
139 })?;
140
141 let extension = parse_address(attribute(&static_attrs, "extension")?, "extension")?;
142
143 let liquidity = attribute(&state_attrs, "liquidity")?
144 .clone()
145 .try_into()?;
146
147 let sqrt_ratio = U256::try_from_be_slice(&attribute(&state_attrs, "sqrt_ratio")?[..])
148 .ok_or_else(|| InvalidSnapshotError::ValueError("invalid pool price".to_string()))?;
149
150 let concentrated_pool = |state_attrs,
151 pool_type_config|
152 -> Result<
153 (EvmConcentratedPoolKey, EvmConcentratedPoolState, i32, Vec<Tick>),
154 InvalidSnapshotError,
155 > {
156 let tick = attribute(state_attrs, "tick")?
157 .clone()
158 .try_into()?;
159
160 let mut ticks = ticks_from_attributes(
161 state_attrs
162 .iter()
163 .map(|(key, value)| (key.as_str(), Cow::Borrowed(value))),
164 )
165 .map_err(InvalidSnapshotError::ValueError)?;
166
167 ticks.sort_unstable_by_key(|tick| tick.index);
168
169 Ok((
170 EvmConcentratedPoolKey {
171 token0,
172 token1,
173 config: EvmConcentratedPoolConfig { extension, fee, pool_type_config },
174 },
175 EvmConcentratedPoolState {
176 sqrt_ratio,
177 liquidity,
178 active_tick_index: find_nearest_initialized_tick_index(&ticks, tick),
179 },
180 tick,
181 ticks,
182 ))
183 };
184
185 let ext_type = extension_type_from_attributes_or_address(&static_attrs, extension, chain)?;
186
187 Ok(match ext_type {
188 ExtensionType::NoSwapCallPoints => match pool_type_config {
189 EvmPoolTypeConfig::FullRange(pool_type_config) => {
190 Self::FullRange(FullRangePool::new(
191 FullRangePoolKey {
192 token0,
193 token1,
194 config: PoolConfig { extension, fee, pool_type_config },
195 },
196 FullRangePoolState { sqrt_ratio, liquidity },
197 )?)
198 }
199 EvmPoolTypeConfig::Stableswap(pool_type_config) => {
200 Self::Stableswap(StableswapPool::new(
201 StableswapPoolKey {
202 token0,
203 token1,
204 config: PoolConfig { extension, fee, pool_type_config },
205 },
206 StableswapPoolState { sqrt_ratio, liquidity },
207 )?)
208 }
209 EvmPoolTypeConfig::Concentrated(pool_type_config) => {
210 let (key, state, tick, ticks) =
211 concentrated_pool(&state_attrs, pool_type_config)?;
212
213 Self::Concentrated(ConcentratedPool::new(key, state, tick, ticks)?)
214 }
215 },
216 ExtensionType::Oracle => Self::Oracle(OraclePool::new(
217 EvmOraclePoolKey {
218 token0,
219 token1,
220 config: PoolConfig {
221 extension,
222 fee,
223 pool_type_config: FullRangePoolTypeConfig,
224 },
225 },
226 EvmFullRangePoolState { sqrt_ratio, liquidity },
227 )?),
228 ExtensionType::Twamm => {
229 let TimedStateDetails {
230 rate_token0: token0_sale_rate,
231 rate_token1: token1_sale_rate,
232 last_time: last_execution_time,
233 rate_deltas: virtual_order_deltas,
234 } = timed_state_details(state_attrs)?;
235
236 Self::Twamm(TwammPool::new(
237 EvmTwammPoolKey {
238 token0,
239 token1,
240 config: PoolConfig {
241 extension,
242 fee,
243 pool_type_config: FullRangePoolTypeConfig,
244 },
245 },
246 TwammPoolState {
247 full_range_pool_state: FullRangePoolState { sqrt_ratio, liquidity },
248 token0_sale_rate,
249 token1_sale_rate,
250 last_execution_time,
251 },
252 virtual_order_deltas,
253 )?)
254 }
255 ExtensionType::MevCapture => {
256 let EvmPoolTypeConfig::Concentrated(pool_type_config) = pool_type_config else {
257 return Err(InvalidSnapshotError::ValueError(
258 "expected concentrated pool type config for MEVCapture pool".to_string(),
259 ));
260 };
261
262 let (key, concentrated_state, tick, ticks) =
263 concentrated_pool(&state_attrs, pool_type_config)?;
264
265 Self::MevCapture(MevCapturePool::new(key, tick, concentrated_state, ticks)?)
266 }
267 ExtensionType::MevCaptureV21 => {
268 let EvmPoolTypeConfig::Concentrated(pool_type_config) = pool_type_config else {
269 return Err(InvalidSnapshotError::ValueError(
270 "expected concentrated pool type config for MEVCapture v2.1 pool"
271 .to_string(),
272 ));
273 };
274
275 let (key, _, tick, ticks) = concentrated_pool(&state_attrs, pool_type_config)?;
276 let anchor = mev_capture_v21::anchor_from_bytes(attribute(
277 &state_attrs,
278 mev_capture_v21::ANCHOR_STATE_ATTRIBUTE,
279 )?)
280 .map_err(InvalidSnapshotError::ValueError)?;
281
282 Self::MevCaptureV21(MevCaptureV21Pool::new(
283 key,
284 mev_capture_v21::config_from_attributes(&static_attrs)?,
285 MevCaptureV21MainPoolState {
286 core: mev_capture_v21::core_state(sqrt_ratio, tick, liquidity),
287 anchor,
288 },
289 ticks,
290 )?)
291 }
292 ExtensionType::SignedExclusiveSwap => {
293 let EvmPoolTypeConfig::Concentrated(pool_type_config) = pool_type_config else {
294 return Err(InvalidSnapshotError::ValueError(
295 "expected concentrated pool type config for SignedExclusiveSwap pool"
296 .to_string(),
297 ));
298 };
299
300 let (key, state, tick, ticks) = concentrated_pool(&state_attrs, pool_type_config)?;
301
302 Self::Concentrated(ConcentratedPool::new(key, state, tick, ticks)?)
303 }
304 ExtensionType::BoostedFees => {
305 let EvmPoolTypeConfig::Concentrated(pool_type_config) = pool_type_config else {
306 return Err(InvalidSnapshotError::ValueError(
307 "expected concentrated pool type config for BoostedFees pool".to_string(),
308 ));
309 };
310
311 let (key, concentrated_pool_state, tick, ticks) =
312 concentrated_pool(&state_attrs, pool_type_config)?;
313
314 let TimedStateDetails {
315 rate_token0: donate_rate0,
316 rate_token1: donate_rate1,
317 last_time: last_donate_time,
318 rate_deltas: donate_rate_deltas,
319 } = timed_state_details(state_attrs)?;
320
321 Self::BoostedFees(BoostedFeesPool::new(
322 key,
323 concentrated_pool_state,
324 donate_rate0,
325 donate_rate1,
326 last_donate_time,
327 donate_rate_deltas,
328 ticks,
329 tick,
330 )?)
331 }
332 ExtensionType::Ve33 => {
333 let underlying_pool = match pool_type_config {
334 EvmPoolTypeConfig::FullRange(pool_type_config) => {
335 Ve33UnderlyingPool::FullRange(FullRangePool::new(
336 FullRangePoolKey {
337 token0,
338 token1,
339 config: PoolConfig { extension, fee, pool_type_config },
340 },
341 FullRangePoolState { sqrt_ratio, liquidity },
342 )?)
343 }
344 EvmPoolTypeConfig::Stableswap(pool_type_config) => {
345 Ve33UnderlyingPool::Stableswap(StableswapPool::new(
346 StableswapPoolKey {
347 token0,
348 token1,
349 config: PoolConfig { extension, fee, pool_type_config },
350 },
351 StableswapPoolState { sqrt_ratio, liquidity },
352 )?)
353 }
354 EvmPoolTypeConfig::Concentrated(pool_type_config) => {
355 let (key, state, tick, ticks) =
356 concentrated_pool(&state_attrs, pool_type_config)?;
357 Ve33UnderlyingPool::Concentrated(ConcentratedPool::new(
358 key, state, tick, ticks,
359 )?)
360 }
361 };
362 let swap_fee = u64::from_be_bytes(
363 attribute(&state_attrs, "swap_fee")?
364 .as_ref()
365 .try_into()
366 .map_err(|err| {
367 InvalidSnapshotError::ValueError(format!(
368 "swap_fee length mismatch: {err:?}"
369 ))
370 })?,
371 );
372
373 Self::Ve33(Ve33Pool::new(underlying_pool, swap_fee)?)
374 }
375 })
376 }
377}
378
379fn extension_type_from_attributes_or_address(
382 static_attrs: &HashMap<String, Bytes>,
383 extension: Address,
384 chain: Chain,
385) -> Result<ExtensionType, InvalidSnapshotError> {
386 if let Some(extension_id) = static_attrs.get("extension_id") {
389 match i32::try_from(extension_id.clone())? {
390 0 => {}
391 1 => return Ok(ExtensionType::NoSwapCallPoints),
392 2 => return Ok(ExtensionType::Oracle),
393 3 => return Ok(ExtensionType::Twamm),
394 4 => return Ok(ExtensionType::MevCapture),
395 _ => {}
396 }
397 }
398
399 extension_type(extension, chain).ok_or_else(|| {
401 InvalidSnapshotError::ValueError(format!("unsupported extension {extension:x}"))
402 })
403}
404
405fn attribute<'a>(
406 map: &'a HashMap<String, Bytes>,
407 key: &str,
408) -> Result<&'a Bytes, InvalidSnapshotError> {
409 map.get(key)
410 .ok_or_else(|| InvalidSnapshotError::MissingAttribute(key.to_string()))
411}
412
413fn parse_address(bytes: &Bytes, attr_name: &str) -> Result<Address, InvalidSnapshotError> {
414 Address::try_from(&bytes[..])
415 .map_err(|err| InvalidSnapshotError::ValueError(format!("parsing {attr_name}: {err}")))
416}
417
418fn attribute_with_fallback<'a>(
420 map: &'a HashMap<String, Bytes>,
421 key: &str,
422 legacy_key: &str,
423) -> Result<&'a Bytes, InvalidSnapshotError> {
424 map.get(key)
425 .or_else(|| map.get(legacy_key))
426 .ok_or_else(|| InvalidSnapshotError::MissingAttribute(key.to_string()))
427}
428
429fn timed_state_details(
430 attrs: HashMap<String, Bytes>,
431) -> Result<TimedStateDetails, InvalidSnapshotError> {
432 let last_time = attribute_with_fallback(&attrs, "last_time", "last_execution_time")?
433 .clone()
434 .try_into()?;
435
436 Ok(TimedStateDetails {
437 rate_token0: attribute_with_fallback(&attrs, "rate_token0", "token0_sale_rate")?
438 .clone()
439 .try_into()?,
440 rate_token1: attribute_with_fallback(&attrs, "rate_token1", "token1_sale_rate")?
441 .clone()
442 .try_into()?,
443 last_time,
444 rate_deltas: rate_deltas_from_attributes(
445 attrs
446 .into_iter()
447 .map(|(key, value)| (key, Cow::Owned(value))),
448 last_time,
449 )
450 .map_err(InvalidSnapshotError::ValueError)?
451 .sorted_unstable_by_key(|delta| delta.time)
452 .collect(),
453 })
454}
455
456#[cfg(test)]
457mod tests {
458 use rstest::*;
459 use rstest_reuse::apply;
460 use tycho_common::models::protocol::ProtocolComponentState;
461
462 use super::*;
463 use crate::evm::protocol::{
464 ekubo_v3::test_cases::*, test_utils::try_decode_snapshot_with_defaults,
465 };
466
467 #[apply(all_cases)]
468 #[tokio::test]
469 async fn test_try_from_with_header(case: TestCase) {
470 let snapshot = ComponentWithState {
471 state: ProtocolComponentState {
472 component_id: String::new(),
473 attributes: case.state_attributes,
474 balances: HashMap::new(),
475 },
476 component: case.component,
477 component_tvl: None,
478 entrypoints: Vec::new(),
479 };
480
481 let result = try_decode_snapshot_with_defaults::<EkuboV3State>(snapshot)
482 .await
483 .expect("reconstructing state");
484
485 assert_eq!(result, case.state_before_transition);
486 }
487
488 #[apply(all_cases)]
495 #[tokio::test]
496 async fn test_try_from_legacy_format(case: TestCase) {
497 let extension_id: i32 = match &case.state_before_transition {
498 EkuboV3State::Concentrated(_) |
499 EkuboV3State::FullRange(_) |
500 EkuboV3State::Stableswap(_) => 1,
501 EkuboV3State::Oracle(_) => 2,
502 EkuboV3State::Twamm(_) => 3,
503 EkuboV3State::MevCapture(_) => 4,
504 EkuboV3State::BoostedFees(_) |
506 EkuboV3State::MevCaptureV21(_) |
507 EkuboV3State::Ve33(_) => return,
508 };
509
510 let mut component = case.component;
511 component
514 .static_attributes
515 .insert("extension_id".to_string(), extension_id.to_be_bytes().into());
516
517 let state_attributes = case
519 .state_attributes
520 .into_iter()
521 .map(|(key, value)| {
522 let key = key
523 .replace("tick/", "ticks/")
524 .replace("rate_delta/", "orders/");
525 let key = match key.as_str() {
526 "rate_token0" => "token0_sale_rate".to_string(),
527 "rate_token1" => "token1_sale_rate".to_string(),
528 "last_time" => "last_execution_time".to_string(),
529 _ => key,
530 };
531 (key, value)
532 })
533 .collect();
534
535 let snapshot = ComponentWithState {
536 state: ProtocolComponentState {
537 component_id: String::new(),
538 attributes: state_attributes,
539 balances: HashMap::new(),
540 },
541 component,
542 component_tvl: None,
543 entrypoints: Vec::new(),
544 };
545
546 let result = try_decode_snapshot_with_defaults::<EkuboV3State>(snapshot)
547 .await
548 .expect("reconstructing state from legacy format");
549
550 assert_eq!(result, case.state_before_transition);
551 }
552
553 #[apply(all_cases)]
554 #[tokio::test]
555 async fn test_try_from_invalid(case: TestCase) {
556 for missing_attribute in case.required_attributes {
557 let mut component = case.component.clone();
558 let mut attributes = case.state_attributes.clone();
559
560 component
561 .static_attributes
562 .remove(&missing_attribute);
563 attributes.remove(&missing_attribute);
564
565 let snapshot = ComponentWithState {
566 state: ProtocolComponentState {
567 attributes,
568 component_id: String::new(),
569 balances: HashMap::new(),
570 },
571 component,
572 component_tvl: None,
573 entrypoints: Vec::new(),
574 };
575
576 EkuboV3State::try_from_with_header(
577 snapshot,
578 BlockHeader::default(),
579 &HashMap::default(),
580 &HashMap::default(),
581 &DecoderContext::new(),
582 )
583 .await
584 .unwrap_err();
585 }
586 }
587
588 #[rstest]
589 #[case::concentrated(concentrated())]
590 #[case::full_range(full_range())]
591 #[case::stableswap(stableswap())]
592 #[tokio::test]
593 async fn test_decode_ve33_underlying_pool_types(#[case] mut case: TestCase) {
594 case.component.chain = Chain::Robinhood;
595 case.component.static_attributes.insert(
596 "extension".to_string(),
597 VE33_ROBINHOOD_ADDRESS
598 .into_array()
599 .into(),
600 );
601 case.state_attributes
602 .insert("swap_fee".to_string(), 1_u64.to_be_bytes().into());
603
604 let snapshot = ComponentWithState {
605 state: ProtocolComponentState {
606 component_id: String::new(),
607 attributes: case.state_attributes,
608 balances: HashMap::new(),
609 },
610 component: case.component,
611 component_tvl: None,
612 entrypoints: Vec::new(),
613 };
614
615 let result = try_decode_snapshot_with_defaults::<EkuboV3State>(snapshot)
616 .await
617 .expect("reconstructing Ve33 state");
618
619 assert!(matches!(result, EkuboV3State::Ve33(_)));
620 }
621}