1use std::{any::Any, collections::HashMap, sync::Arc};
2
3use alloy::primitives::{Sign, I256, U256};
4use num_bigint::BigUint;
5use num_traits::Zero;
6use serde::{Deserialize, Serialize};
7use tracing::{error, trace};
8use tycho_common::{
9 dto::ProtocolStateDelta,
10 models::token::Token,
11 simulation::{
12 errors::{SimulationError, TransitionError},
13 protocol_sim::{
14 Balances, BlockContext, GetAmountOutResult, PoolSwap, Price, ProtocolSim,
15 QueryPoolSwapParams, SwapConstraint,
16 },
17 },
18 Bytes,
19};
20
21use crate::{
22 evm::{
23 protocol::{
24 clmm::clmm_swap_to_price,
25 safe_math::{safe_add_u256, safe_sub_u256},
26 u256_num::u256_to_biguint,
27 utils::{
28 add_fee_markup,
29 slipstreams::{
30 aero_hook_fee::{AeroHookFee, Execution, HookFee, PoolOracle},
31 dynamic_fee_module::{get_dynamic_fee, DynamicFeeConfig, ResolvedFee},
32 observations::{Observation, Observations},
33 oracle_timestamp, raw_target_price,
34 },
35 uniswap::{
36 i24_be_bytes_to_i32, liquidity_math,
37 pool_tick::PoolTick,
38 sqrt_price_math::{
39 get_amount0_delta, get_amount1_delta, sqrt_price_q96_to_f64,
40 },
41 swap_math::{self, SwapStepResult},
42 swap_step_cache::{StepCacheKey, StepCacheRun, SwapStepCache},
43 tick_list::{TickInfo, TickList, TickListErrorKind},
44 tick_math::{
45 get_sqrt_ratio_at_tick_cached, MAX_SQRT_RATIO, MAX_TICK, MIN_SQRT_RATIO,
46 MIN_TICK,
47 },
48 StepComputation, SwapResults, SwapState,
49 },
50 },
51 },
52 query_pool_swap::price_to_f64_with_decimals,
53 },
54 protocol::models::BlockPositionAssumption,
55};
56
57const FIRST_LOOP_OVERHEAD: u64 = 15_000;
61const LOOP_GAS_COST: u64 = 12_500;
64const TICK_CROSSING_GAS_COST: u64 = 70_000;
68const TWAP_FEE_OVERHEAD: u64 = 65_000;
72const SWAP_BASE_GAS: u64 = 125_000;
74const AERO_HOOK_GAS: u64 = 160_000;
79const MAX_SWAP_GAS: u64 = 16_700_000;
81const MAX_TICKS_CROSSED: u64 = (MAX_SWAP_GAS - SWAP_BASE_GAS) / TICK_CROSSING_GAS_COST;
83
84#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
85pub struct AerodromeSlipstreamsState {
86 id: String,
87 execution_block_timestamp: u64,
94 #[serde(default)]
97 execution_block_number: u64,
98 liquidity: u128,
99 sqrt_price: U256,
100 observation_index: u16,
101 observation_cardinality: u16,
102 default_fee: u32,
103 tick_spacing: i32,
104 tick: i32,
105 ticks: Arc<TickList>,
109 #[serde(skip)]
114 step_cache: SwapStepCache,
115 observations: Observations,
119 dfc: DynamicFeeConfig,
120 #[serde(default)]
123 aero_hook: Option<AeroHookFee>,
124 position_assumption: BlockPositionAssumption,
127}
128
129impl AerodromeSlipstreamsState {
130 #[expect(
147 clippy::too_many_arguments,
148 reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
149 )]
150 pub fn new(
151 id: String,
152 execution_block_timestamp: u64,
153 liquidity: u128,
154 sqrt_price: U256,
155 observation_index: u16,
156 observation_cardinality: u16,
157 default_fee: u32,
158 tick_spacing: i32,
159 tick: i32,
160 ticks: Vec<TickInfo>,
161 observations: Vec<Observation>,
162 dfc: DynamicFeeConfig,
163 ) -> Result<Self, SimulationError> {
164 let tick_list_spacing = u16::try_from(tick_spacing).map_err(|e| {
165 SimulationError::InvalidInput(format!("Invalid tick spacing {tick_spacing}: {e}"), None)
166 })?;
167 let tick_list = TickList::from(tick_list_spacing, ticks)?;
168 Ok(AerodromeSlipstreamsState {
169 id,
170 execution_block_timestamp,
171 execution_block_number: 0,
172 liquidity,
173 sqrt_price,
174 observation_index,
175 observation_cardinality,
176 default_fee,
177 tick_spacing,
178 tick,
179 ticks: Arc::new(tick_list),
180 step_cache: SwapStepCache::default(),
181 observations: Observations::new(observations),
182 dfc,
183 aero_hook: None,
184 position_assumption: BlockPositionAssumption::default(),
185 })
186 }
187
188 pub fn with_aero_hook(mut self, hook: AeroHookFee) -> Self {
190 self.aero_hook = Some(hook);
191 self
192 }
193
194 pub fn with_position_assumption(mut self, assumption: BlockPositionAssumption) -> Self {
198 self.position_assumption = assumption;
199 self
200 }
201
202 fn get_fee(&self) -> Result<ResolvedFee, SimulationError> {
203 if let Some(hook) = &self.aero_hook {
204 let fee = self.hook_fee(hook)?;
205 return Ok(ResolvedFee { fee: fee.fee, observed_twap: fee.observed_twap });
206 }
207 get_dynamic_fee(
208 &self.dfc,
209 self.default_fee,
210 self.tick,
211 self.liquidity,
212 self.observation_index,
213 self.observation_cardinality,
214 &self.observations,
215 oracle_timestamp(self.execution_block_timestamp),
216 self.position_assumption == BlockPositionAssumption::First,
217 )
218 }
219
220 fn hook_fee(&self, hook: &AeroHookFee) -> Result<HookFee, SimulationError> {
221 hook.resolve(
222 &PoolOracle {
223 tick: self.tick,
224 liquidity: self.liquidity,
225 observation_index: self.observation_index,
226 observation_cardinality: self.observation_cardinality,
227 observations: &self.observations,
228 },
229 self.default_fee,
230 Execution {
231 block: self.execution_block_number,
232 timestamp: oracle_timestamp(self.execution_block_timestamp),
233 first_in_block: self.position_assumption == BlockPositionAssumption::First,
234 },
235 )
236 }
237
238 fn record_observation(&mut self, post_swap_tick: i32) -> Result<(), SimulationError> {
245 if post_swap_tick == self.tick {
246 return Ok(());
247 }
248 self.observation_index = self.observations.write(
249 self.observation_index,
250 oracle_timestamp(self.execution_block_timestamp),
251 self.tick,
252 self.liquidity,
253 self.observation_cardinality,
254 )?;
255 Ok(())
256 }
257
258 fn swap_to_target_price(
262 &self,
263 params: &QueryPoolSwapParams,
264 target: &Price,
265 tolerance: f64,
266 ) -> Result<PoolSwap, SimulationError> {
267 let token_in = params.token_in();
268 let token_out = params.token_out();
269 let target_f64 = price_to_f64_with_decimals(target, token_in.decimals, token_out.decimals)?;
270 if target_f64 == self.spot_price(token_in, token_out)? {
271 return Ok(PoolSwap::new(BigUint::ZERO, BigUint::ZERO, Box::new(self.clone()), None));
272 }
273 let Some(limit) = raw_target_price(target, tolerance, self.get_fee()?.fee) else {
274 return crate::evm::query_pool_swap::query_pool_swap(self, params);
275 };
276 let Ok((amount_in, amount_out, result)) = clmm_swap_to_price(
278 self.sqrt_price,
279 &token_in.address,
280 &token_out.address,
281 &limit,
282 0,
283 Sign::Positive,
284 |zero_for_one, amount_specified, sqrt_price_limit| {
285 self.swap(zero_for_one, amount_specified, Some(sqrt_price_limit))
286 },
287 ) else {
288 return crate::evm::query_pool_swap::query_pool_swap(self, params);
289 };
290
291 let new_state = if amount_in.is_zero() {
292 self.clone()
293 } else {
294 let (state, observation) =
295 self.clone_post_swap(result.sqrt_price, result.tick.value(), result.liquidity);
296 observation?;
297 state
298 };
299 let final_spot = new_state.spot_price(token_in, token_out)?;
300 if final_spot < target_f64 || final_spot > target_f64 * (1.0 + tolerance) {
301 return crate::evm::query_pool_swap::query_pool_swap(self, params);
302 }
303 Ok(PoolSwap::new(amount_in, amount_out, Box::new(new_state), None))
304 }
305
306 fn clone_post_swap(
310 &self,
311 sqrt_price: U256,
312 tick: i32,
313 liquidity: u128,
314 ) -> (Self, Result<(), SimulationError>) {
315 let mut state = self.clone();
316 state.step_cache = SwapStepCache::default();
317 if let (Some(hook), Some(state_hook)) = (&self.aero_hook, state.aero_hook.as_mut()) {
319 match self.hook_fee(hook) {
320 Ok(HookFee { block_fee_to_store: Some(fee), .. }) => {
321 state_hook.store_block_fee(self.execution_block_number, fee)
322 }
323 Ok(_) => {}
324 Err(err) => return (state, Err(err)),
325 }
326 }
327 let observation = state.record_observation(tick);
328 state.liquidity = liquidity;
329 state.tick = tick;
330 state.sqrt_price = sqrt_price;
331 (state, observation)
332 }
333
334 fn swap(
335 &self,
336 zero_for_one: bool,
337 amount_specified: I256,
338 sqrt_price_limit: Option<U256>,
339 ) -> Result<SwapResults, SimulationError> {
340 if self.liquidity == 0 {
341 return Err(SimulationError::RecoverableError("No liquidity".to_string()));
342 }
343 let price_limit = if let Some(limit) = sqrt_price_limit {
344 limit
345 } else if zero_for_one {
346 safe_add_u256(MIN_SQRT_RATIO, U256::from(1u64))?
347 } else {
348 safe_sub_u256(MAX_SQRT_RATIO, U256::from(1u64))?
349 };
350
351 let price_limit_valid = if zero_for_one {
352 price_limit > MIN_SQRT_RATIO && price_limit < self.sqrt_price
353 } else {
354 price_limit < MAX_SQRT_RATIO && price_limit > self.sqrt_price
355 };
356 if !price_limit_valid {
357 return Err(SimulationError::InvalidInput("Price limit out of range".into(), None));
358 }
359
360 let exact_input = amount_specified > I256::from_raw(U256::from(0u64));
361
362 let mut state = SwapState {
363 amount_remaining: amount_specified,
364 amount_calculated: I256::from_raw(U256::from(0u64)),
365 sqrt_price: self.sqrt_price,
366 tick: self.tick.into(),
367 liquidity: self.liquidity,
368 };
369 let resolved_fee = self.get_fee()?;
370 let twap_overhead = if self.aero_hook.is_some() {
371 AERO_HOOK_GAS
372 } else if resolved_fee.observed_twap {
373 TWAP_FEE_OVERHEAD
374 } else {
375 0
376 };
377 let mut gas_used = U256::from(SWAP_BASE_GAS + twap_overhead);
378 let mut n_loops = 0;
379
380 let fee = resolved_fee.fee;
381 let cache_key = if exact_input && sqrt_price_limit.is_none() {
385 StepCacheKey::new(self.sqrt_price, state.tick.value(), self.liquidity, fee, gas_used)
386 } else {
387 None
388 };
389 let mut cache_run = StepCacheRun::new(
390 &self.step_cache,
391 zero_for_one,
392 cache_key,
393 amount_specified.unsigned_abs(),
394 );
395 if let Some(progress) = cache_run.apply_cached_progress(&mut state) {
396 gas_used = progress.gas;
397 n_loops = progress.steps_taken;
399 }
400 while state.amount_remaining != I256::from_raw(U256::from(0u64)) &&
401 state.sqrt_price != price_limit
402 {
403 let (mut next_tick, next_tick_info) = match self
404 .ticks
405 .next_initialized_tick_within_one_word(state.tick.value(), zero_for_one)
406 {
407 Ok((tick, info)) => (tick, info),
408 Err(tick_err) => match tick_err.kind {
409 TickListErrorKind::TicksExeeded => {
410 let (new_state, observation) = self.clone_post_swap(
411 state.sqrt_price,
412 state.tick.value(),
413 state.liquidity,
414 );
415 if let Err(record_err) = observation {
419 trace!(%record_err, "skipping observation write on partial result");
420 }
421 return Err(SimulationError::InvalidInput(
422 "Ticks exceeded".into(),
423 Some(GetAmountOutResult::new(
424 u256_to_biguint(state.amount_calculated.abs().into_raw()),
425 u256_to_biguint(gas_used),
426 Box::new(new_state),
427 )),
428 ));
429 }
430 TickListErrorKind::BelowSmallest | TickListErrorKind::AtOrAboveLargest => {
431 return Err(SimulationError::FatalError("Unknown error".to_string()))
432 }
433 },
434 };
435
436 next_tick = next_tick.clamp(MIN_TICK, MAX_TICK);
437
438 let sqrt_price_start = state.sqrt_price;
439 let sqrt_price_next = match next_tick_info {
440 Some(info) => info.sqrt_price,
441 None => get_sqrt_ratio_at_tick_cached(next_tick)?,
442 };
443 let SwapStepResult { sqrt_price, amount_in_with_fee, amount_out } =
444 swap_math::compute_swap_step(
445 state.sqrt_price,
446 AerodromeSlipstreamsState::get_sqrt_ratio_target(
447 sqrt_price_next,
448 price_limit,
449 zero_for_one,
450 ),
451 state.liquidity,
452 state.amount_remaining,
453 fee,
454 )?;
455 state.sqrt_price = sqrt_price;
456
457 let step = StepComputation {
458 sqrt_price_start,
459 tick_next: next_tick,
460 sqrt_price_next,
461 amount_in_with_fee,
462 amount_out,
463 };
464 if exact_input {
465 state.amount_remaining -=
466 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
467 .unwrap();
468 state.amount_calculated -=
469 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
470 } else {
471 state.amount_remaining +=
472 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
473 state.amount_calculated +=
474 I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
475 .unwrap();
476 }
477 if state.sqrt_price == step.sqrt_price_next {
478 if let Some(info) = next_tick_info {
479 let liquidity_raw = info.net_liquidity;
480 let liquidity_net = if zero_for_one { -liquidity_raw } else { liquidity_raw };
481 state.liquidity =
482 liquidity_math::add_liquidity_delta(state.liquidity, liquidity_net)?;
483 gas_used = safe_add_u256(gas_used, U256::from(TICK_CROSSING_GAS_COST))?;
484 }
485 state.tick =
486 PoolTick::from(if zero_for_one { step.tick_next - 1 } else { step.tick_next });
487 } else if state.sqrt_price != step.sqrt_price_start {
488 state.tick = PoolTick::at_sqrt_price(state.sqrt_price)?;
489 }
490 gas_used = safe_add_u256(gas_used, U256::from(LOOP_GAS_COST))?;
491 if n_loops == 0 {
492 gas_used = safe_add_u256(gas_used, U256::from(FIRST_LOOP_OVERHEAD))?;
493 }
494 n_loops += 1;
495 cache_run.cache_progress(&step, &state, gas_used);
496 }
497 Ok(SwapResults {
498 amount_calculated: state.amount_calculated,
499 amount_specified,
500 amount_remaining: state.amount_remaining,
501 sqrt_price: state.sqrt_price,
502 liquidity: state.liquidity,
503 tick: state.tick,
504 gas_used,
505 })
506 }
507
508 fn get_sqrt_ratio_target(
509 sqrt_price_next: U256,
510 sqrt_price_limit: U256,
511 zero_for_one: bool,
512 ) -> U256 {
513 let cond1 = if zero_for_one {
514 sqrt_price_next < sqrt_price_limit
515 } else {
516 sqrt_price_next > sqrt_price_limit
517 };
518
519 if cond1 {
520 sqrt_price_limit
521 } else {
522 sqrt_price_next
523 }
524 }
525}
526
527#[typetag::serde]
528impl ProtocolSim for AerodromeSlipstreamsState {
529 fn fee(&self) -> f64 {
530 match self.get_fee() {
531 Ok(resolved) => resolved.fee as f64 / 1_000_000.0,
532 Err(err) => {
533 error!(
534 pool = %self.id,
535 execution_block_timestamp = self.execution_block_timestamp,
536 %err,
537 "Error while calculating dynamic fee"
538 );
539 f64::MAX / 1_000_000.0
540 }
541 }
542 }
543
544 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
545 let price = if base < quote {
546 sqrt_price_q96_to_f64(self.sqrt_price, base.decimals, quote.decimals)?
547 } else {
548 1.0f64 / sqrt_price_q96_to_f64(self.sqrt_price, quote.decimals, base.decimals)?
549 };
550 Ok(add_fee_markup(price, self.get_fee()?.fee as f64 / 1_000_000.0))
551 }
552
553 fn get_amount_out(
554 &self,
555 amount_in: BigUint,
556 token_in: &Token,
557 token_out: &Token,
558 ) -> Result<GetAmountOutResult, SimulationError> {
559 let zero_for_one = token_in < token_out;
560 let amount_specified = I256::checked_from_sign_and_abs(
561 Sign::Positive,
562 U256::from_be_slice(&amount_in.to_bytes_be()),
563 )
564 .ok_or_else(|| {
565 SimulationError::InvalidInput("I256 overflow: amount_in".to_string(), None)
566 })?;
567
568 let result = self.swap(zero_for_one, amount_specified, None)?;
569
570 trace!(?amount_in, ?token_in, ?token_out, ?zero_for_one, ?result, "SLIPSTREAMS SWAP");
571 let (new_state, observation) =
572 self.clone_post_swap(result.sqrt_price, result.tick.value(), result.liquidity);
573 observation?;
574
575 Ok(GetAmountOutResult::new(
576 u256_to_biguint(
577 result
578 .amount_calculated
579 .abs()
580 .into_raw(),
581 ),
582 u256_to_biguint(result.gas_used),
583 Box::new(new_state),
584 ))
585 }
586
587 fn get_limits(
588 &self,
589 sell_token: Bytes,
590 buy_token: Bytes,
591 ) -> Result<(BigUint, BigUint), SimulationError> {
592 if self.liquidity == 0 {
594 return Ok((BigUint::zero(), BigUint::zero()));
595 }
596
597 let zero_for_one = sell_token < buy_token;
598 let mut current_tick = self.tick;
599 let mut current_sqrt_price = self.sqrt_price;
600 let mut current_liquidity = self.liquidity;
601 let mut total_amount_in = U256::from(0u64);
602 let mut total_amount_out = U256::from(0u64);
603
604 let mut ticks_crossed: u64 = 0;
607 while let Ok((tick, next_tick_info)) = self
608 .ticks
609 .next_initialized_tick_within_one_word(current_tick, zero_for_one)
610 {
611 if ticks_crossed >= MAX_TICKS_CROSSED {
612 break;
613 }
614 ticks_crossed += 1;
615 let next_tick = tick.clamp(MIN_TICK, MAX_TICK);
617
618 let sqrt_price_next = match next_tick_info {
619 Some(info) => info.sqrt_price,
620 None => get_sqrt_ratio_at_tick_cached(next_tick)?,
621 };
622
623 let (amount_in, amount_out) = if zero_for_one {
626 let amount0 = get_amount0_delta(
627 sqrt_price_next,
628 current_sqrt_price,
629 current_liquidity,
630 true,
631 )?;
632 let amount1 = get_amount1_delta(
633 sqrt_price_next,
634 current_sqrt_price,
635 current_liquidity,
636 false,
637 )?;
638 (amount0, amount1)
639 } else {
640 let amount0 = get_amount0_delta(
641 sqrt_price_next,
642 current_sqrt_price,
643 current_liquidity,
644 false,
645 )?;
646 let amount1 = get_amount1_delta(
647 sqrt_price_next,
648 current_sqrt_price,
649 current_liquidity,
650 true,
651 )?;
652 (amount1, amount0)
653 };
654
655 total_amount_in = safe_add_u256(total_amount_in, amount_in)?;
657 total_amount_out = safe_add_u256(total_amount_out, amount_out)?;
658
659 if let Some(info) = next_tick_info {
664 let liquidity_raw = info.net_liquidity;
665 let liquidity_delta = if zero_for_one { -liquidity_raw } else { liquidity_raw };
666 current_liquidity =
667 liquidity_math::add_liquidity_delta(current_liquidity, liquidity_delta)?;
668 }
669
670 current_tick = if zero_for_one { next_tick - 1 } else { next_tick };
672 current_sqrt_price = sqrt_price_next;
673 }
674
675 Ok((u256_to_biguint(total_amount_in), u256_to_biguint(total_amount_out)))
676 }
677
678 fn delta_transition(
679 &mut self,
680 delta: ProtocolStateDelta,
681 _tokens: &HashMap<Bytes, Token>,
682 _balances: &Balances,
683 ) -> Result<(), TransitionError> {
684 self.step_cache = SwapStepCache::default();
686 if let Some(liquidity) = delta
688 .updated_attributes
689 .get("liquidity")
690 {
691 let liq_16_bytes = if liquidity.len() == 32 {
695 if liquidity == &Bytes::zero(32) {
697 Bytes::from([0; 16])
698 } else {
699 return Err(TransitionError::DecodeError(format!(
700 "Liquidity bytes too long for {liquidity}, expected 16",
701 )));
702 }
703 } else {
704 liquidity.clone()
705 };
706
707 self.liquidity = u128::try_from(liq_16_bytes)?;
708 }
709 if let Some(sqrt_price) = delta
710 .updated_attributes
711 .get("sqrt_price_x96")
712 {
713 self.sqrt_price = U256::from_be_slice(sqrt_price);
714 }
715 if let Some(observation_index) = delta
716 .updated_attributes
717 .get("observationIndex")
718 {
719 self.observation_index = u16::try_from(observation_index.clone())?;
720 }
721 if let Some(observation_cardinality) = delta
722 .updated_attributes
723 .get("observationCardinality")
724 {
725 self.observation_cardinality = u16::try_from(observation_cardinality.clone())?;
726 }
727 if let Some(default_fee) = delta
728 .updated_attributes
729 .get("default_fee")
730 {
731 self.default_fee = u32::try_from(default_fee.clone())?;
732 }
733 if let Some(hook) = self.aero_hook.as_mut() {
734 hook.update_from_attributes(&delta.updated_attributes)
735 .map_err(TransitionError::DecodeError)?;
736 } else {
737 self.dfc
738 .update_from_attributes(&delta.updated_attributes)
739 .map_err(|err| {
740 TransitionError::DecodeError(format!(
741 "Failed to update dynamic fee module config: {err}"
742 ))
743 })?;
744 }
745 if let Some(tick) = delta.updated_attributes.get("tick") {
746 let ticks_4_bytes = if tick.len() == 32 {
750 if tick == &Bytes::zero(32) {
752 Bytes::from([0; 4])
753 } else {
754 return Err(TransitionError::DecodeError(format!(
755 "Tick bytes too long for {tick}, expected 4"
756 )));
757 }
758 } else {
759 tick.clone()
760 };
761 self.tick = i24_be_bytes_to_i32(&ticks_4_bytes);
762 }
763
764 for (key, value) in delta.updated_attributes.iter() {
766 if key.starts_with("ticks/") {
768 let parts: Vec<&str> = key.split('/').collect();
769 Arc::make_mut(&mut self.ticks)
770 .set_tick_liquidity(
771 parts[1]
772 .parse::<i32>()
773 .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
774 i128::try_from(value.clone())?,
775 )
776 .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
777 }
778
779 if let Some(idx_str) = key.strip_prefix("observations/") {
781 if let Ok(idx) = idx_str.parse::<i32>() {
782 self.observations
783 .upsert_observation(idx, value)
784 .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
785 }
786 }
787 }
788 for key in delta.deleted_attributes.iter() {
790 if key.starts_with("ticks/") {
792 let parts: Vec<&str> = key.split('/').collect();
793 Arc::make_mut(&mut self.ticks)
794 .set_tick_liquidity(
795 parts[1]
796 .parse::<i32>()
797 .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
798 0,
799 )
800 .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
801 }
802
803 if let Some(idx_str) = key.strip_prefix("observations/") {
805 if let Ok(idx) = idx_str.parse::<i32>() {
806 self.observations
807 .upsert_observation(idx, &[])
808 .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
809 }
810 }
811 }
812 Ok(())
813 }
814
815 fn apply_block(&mut self, block: &BlockContext) -> bool {
819 let timestamp = block.timestamp();
820 if timestamp == self.execution_block_timestamp &&
821 block.number() == self.execution_block_number
822 {
823 return false;
824 }
825 let fee_before = self.get_fee().ok();
826 self.execution_block_timestamp = timestamp;
827 self.execution_block_number = block.number();
828 fee_before != self.get_fee().ok()
829 }
830
831 fn clone_box(&self) -> Box<dyn ProtocolSim> {
832 Box::new(self.clone())
833 }
834
835 fn as_any(&self) -> &dyn Any {
836 self
837 }
838
839 fn as_any_mut(&mut self) -> &mut dyn Any {
840 self
841 }
842
843 fn eq(&self, other: &dyn ProtocolSim) -> bool {
844 if let Some(other_state) = other
845 .as_any()
846 .downcast_ref::<AerodromeSlipstreamsState>()
847 {
848 let Ok(self_fee) = self.get_fee() else { return false };
849 let Ok(other_fee) = other_state.get_fee() else { return false };
850
851 self.liquidity == other_state.liquidity &&
852 self.sqrt_price == other_state.sqrt_price &&
853 self_fee == other_fee &&
854 self.tick == other_state.tick &&
855 self.ticks == other_state.ticks
856 } else {
857 false
858 }
859 }
860
861 fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
864 match params.swap_constraint() {
865 SwapConstraint::TradeLimitPrice { .. } => {
866 crate::evm::query_pool_swap::query_pool_swap(self, params)
867 }
868 SwapConstraint::PoolTargetPrice {
869 target,
870 tolerance,
871 min_amount_in: _,
872 max_amount_in: _,
873 } => {
874 let swap = self.swap_to_target_price(params, target, *tolerance)?;
875 let target = price_to_f64_with_decimals(
876 target,
877 params.token_in().decimals,
878 params.token_out().decimals,
879 )?;
880 let spot = swap
881 .new_state()
882 .spot_price(params.token_in(), params.token_out())?;
883 if !tolerance.is_finite() ||
884 *tolerance < 0.0 ||
885 !(spot >= target && spot <= target * (1.0 + tolerance))
886 {
887 return Err(SimulationError::RecoverableError(
888 "Aerodrome target-price search ended outside the requested tolerance"
889 .into(),
890 ));
891 }
892 Ok(swap)
893 }
894 }
895 }
896}
897
898#[cfg(test)]
899#[path = "aero_cl_replay_tests.rs"]
900mod aero_cl_replay_tests;
901
902#[cfg(test)]
903mod tests {
904 use std::str::FromStr;
905
906 use alloy::primitives::{Sign, I256, U256};
907 use rstest::rstest;
908 use tycho_common::{models::Chain, simulation::errors::SimulationError};
909
910 use super::*;
911 use crate::evm::{
912 protocol::utils::{
913 slipstreams::{
914 dynamic_fee_module::{DynamicFeeConfig, ZERO_FEE_INDICATOR},
915 observations::Observation,
916 },
917 uniswap::{
918 tick_list::TickInfo,
919 tick_math::{
920 get_sqrt_ratio_at_tick, get_tick_at_sqrt_ratio, MAX_SQRT_RATIO, MIN_SQRT_RATIO,
921 MIN_TICK,
922 },
923 },
924 },
925 query_pool_swap::test_helpers::{target_price_params, to_price},
926 };
927
928 fn create_basic_test_pool() -> AerodromeSlipstreamsState {
929 let sqrt_price = get_sqrt_ratio_at_tick(0).expect("Failed to calculate sqrt price");
930 let ticks = vec![TickInfo::new(-120, 0).unwrap(), TickInfo::new(120, 0).unwrap()];
931 AerodromeSlipstreamsState::new(
932 "test-pool".to_string(),
933 1_000_000,
934 100_000_000_000_000_000_000u128,
935 sqrt_price,
936 0,
937 1,
938 3000,
939 1,
940 0,
941 ticks,
942 vec![Observation::default()],
943 DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
944 )
945 .expect("Failed to create pool")
946 }
947
948 fn dynamic_fee_delta(dynamic_fee_module: [u8; 20]) -> ProtocolStateDelta {
949 ProtocolStateDelta {
950 component_id: "test-pool".to_string(),
951 updated_attributes: HashMap::from([
952 ("dynamic_fee_module".to_string(), Bytes::from(dynamic_fee_module)),
953 ("dfc_baseFee".to_string(), Bytes::from(500_u32.to_be_bytes())),
954 ("dfc_scalingFactor".to_string(), Bytes::from(0_u64.to_be_bytes())),
955 ("dfc_feeCap".to_string(), Bytes::from(700_u32.to_be_bytes())),
956 ("dfc_initialFeeEnabled".to_string(), Bytes::from([0_u8])),
957 ("dfc_initialFee".to_string(), Bytes::from(0_u32.to_be_bytes())),
958 ]),
959 ..Default::default()
960 }
961 }
962
963 fn initial_fee_pool(last_observation_ts: u32) -> AerodromeSlipstreamsState {
969 let mut pool = create_basic_test_pool();
970 pool.dfc = DynamicFeeConfig::new(2700, 30_000, 0, true, 750);
971 pool.position_assumption = BlockPositionAssumption::First;
972 pool.observations = Observations::new(vec![Observation {
973 block_timestamp: last_observation_ts,
974 initialized: true,
975 index: 0,
976 ..Default::default()
977 }]);
978 pool
979 }
980
981 #[test]
994 fn replays_base_block_50166683_swap_pair_wei_exact() {
995 let mut observations: Vec<Observation> = (0..213)
996 .map(|index| Observation { index, ..Default::default() })
997 .collect();
998 observations.push(Observation {
999 block_timestamp: 1_787_122_711, tick_cumulative: -18_995_710_863_218,
1001 seconds_per_liquidity_cumulative_x128: U256::from_str(
1002 "42501948193164408449462610706599523891176959",
1003 )
1004 .unwrap(),
1005 initialized: true,
1006 index: 213,
1007 });
1008
1009 let mut pool = AerodromeSlipstreamsState::new(
1010 "0xdFe5F275020def30993f042174Fc2D335678b626".to_string(),
1011 1_787_122_711, 1_128_781_556_759_264_064u128,
1013 U256::from_str("1979649713595747421731").unwrap(),
1014 213,
1015 360,
1016 2700, 200,
1018 -350_116,
1019 vec![TickInfo::new(-351_000, 0).unwrap(), TickInfo::new(-349_000, 0).unwrap()],
1022 observations,
1023 DynamicFeeConfig::new(2700, 0, 0, true, 750),
1024 )
1025 .expect("state should build")
1026 .with_position_assumption(BlockPositionAssumption::First);
1028
1029 assert!(pool.apply_block(&BlockContext::new(50_166_683, 1_787_122_713)));
1031
1032 let aero = Token::new(
1033 &Bytes::from_str("0x940181a94A35A4569E4529A3CDfB74e38FD98631").unwrap(),
1034 "AERO",
1035 18,
1036 0,
1037 &[Some(10_000)],
1038 Chain::Base,
1039 100,
1040 );
1041 let cbbtc = Token::new(
1042 &Bytes::from_str("0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf").unwrap(),
1043 "cbBTC",
1044 8,
1045 0,
1046 &[Some(10_000)],
1047 Chain::Base,
1048 100,
1049 );
1050
1051 assert_eq!(pool.fee(), 750.0 / 1_000_000.0);
1052 let first = pool
1053 .get_amount_out(BigUint::from(1_688_626u32), &cbbtc, &aero)
1054 .expect("first swap should succeed");
1055 assert_eq!(first.amount, BigUint::from(2_702_489_253_591_513_843_346u128));
1056
1057 assert_eq!(first.new_state.fee(), 2700.0 / 1_000_000.0);
1058 let second = first
1059 .new_state
1060 .get_amount_out(BigUint::from(450_733u32), &cbbtc, &aero)
1061 .expect("second swap should succeed");
1062 assert_eq!(second.amount, BigUint::from(719_894_300_964_297_656_776u128));
1063
1064 let replayed = first
1065 .new_state
1066 .as_any()
1067 .downcast_ref::<AerodromeSlipstreamsState>()
1068 .expect("state type");
1069 assert_eq!(replayed.observation_index, 214, "chain slot0 shows 214 after the block");
1070 assert_eq!(
1071 replayed
1072 .observations
1073 .timestamp_at(214, 360)
1074 .unwrap(),
1075 1_787_122_713
1076 );
1077 }
1078
1079 #[test]
1080 fn ticks_exceeded_partial_result_still_records_the_observation() {
1081 let mut pool = initial_fee_pool(1_000);
1084 pool.apply_block(&BlockContext::new(101, 1_002));
1085 let token_a =
1086 Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
1087 let token_b =
1088 Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);
1089
1090 let err = pool
1091 .get_amount_out(
1092 BigUint::from(1_000_000_000_000_000_000_000_000u128),
1093 &token_a,
1094 &token_b,
1095 )
1096 .expect_err("swap must exhaust the tick list");
1097 let SimulationError::InvalidInput(_, Some(partial)) = err else {
1098 panic!("expected a partial result, got {err:?}");
1099 };
1100
1101 assert_eq!(partial.new_state.fee(), 2700.0 / 1_000_000.0);
1102 }
1103
1104 #[test]
1105 fn default_quotes_the_worse_fee_when_position_is_unknown() {
1106 let mut pool = initial_fee_pool(1_000);
1110 pool.position_assumption = BlockPositionAssumption::WorstCase;
1111 pool.apply_block(&BlockContext::new(101, 1_002));
1112
1113 assert_eq!(
1114 pool.get_fee()
1115 .expect("fee should be computable")
1116 .fee,
1117 2700
1118 );
1119 }
1120
1121 #[test]
1122 fn worst_case_picks_the_initial_fee_when_it_is_the_higher_one() {
1123 let mut pool = initial_fee_pool(1_000);
1126 pool.dfc = DynamicFeeConfig::new(500, 30_000, 0, true, 4_000);
1127 pool.position_assumption = BlockPositionAssumption::WorstCase;
1128 pool.apply_block(&BlockContext::new(101, 1_002));
1129
1130 assert_eq!(
1131 pool.get_fee()
1132 .expect("fee should be computable")
1133 .fee,
1134 4_000
1135 );
1136 }
1137
1138 #[test]
1139 fn worst_case_keeps_a_flat_fee_pool_quiet_across_blocks() {
1140 let mut pool = initial_fee_pool(1_000);
1143 pool.position_assumption = BlockPositionAssumption::WorstCase;
1144 pool.apply_block(&BlockContext::new(100, 1_000));
1145
1146 assert!(!pool.apply_block(&BlockContext::new(101, 1_002)));
1147 assert!(!pool.apply_block(&BlockContext::new(102, 1_004)));
1148 }
1149
1150 #[test]
1151 fn apply_block_reports_a_fee_flip_and_is_idempotent() {
1152 let mut pool = initial_fee_pool(1_000);
1155 pool.apply_block(&BlockContext::new(100, 1_000));
1156
1157 assert!(pool.apply_block(&BlockContext::new(101, 1_002)), "branch flip must re-emit");
1158 assert!(!pool.apply_block(&BlockContext::new(101, 1_002)), "repeat block is a no-op");
1159 }
1160
1161 #[test]
1162 fn apply_block_stays_quiet_while_the_fee_does_not_move() {
1163 let mut pool = initial_fee_pool(1_000);
1166 pool.apply_block(&BlockContext::new(101, 1_002));
1167
1168 assert!(!pool.apply_block(&BlockContext::new(102, 1_004)));
1169 assert!(!pool.apply_block(&BlockContext::new(103, 1_006)));
1170 }
1171
1172 #[test]
1173 fn quotes_initial_fee_for_the_next_block_after_the_pool_traded() {
1174 let mut pool = initial_fee_pool(1_000);
1178 pool.apply_block(&BlockContext::new(101, 1_002));
1179
1180 assert_eq!(
1181 pool.get_fee()
1182 .expect("fee should be computable")
1183 .fee,
1184 750
1185 );
1186 }
1187
1188 #[test]
1189 fn quotes_dynamic_fee_when_targeting_a_block_the_pool_already_traded_in() {
1190 let mut pool = initial_fee_pool(1_000);
1193 pool.apply_block(&BlockContext::new(100, 1_000));
1194
1195 assert_eq!(
1196 pool.get_fee()
1197 .expect("fee should be computable")
1198 .fee,
1199 2700
1200 );
1201 }
1202
1203 #[test]
1204 fn chained_swap_in_the_same_block_pays_the_dynamic_fee() {
1205 let mut pool = initial_fee_pool(1_000);
1206 pool.apply_block(&BlockContext::new(101, 1_002));
1207 let token_a =
1208 Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
1209 let token_b =
1210 Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);
1211
1212 assert_eq!(pool.fee(), 750.0 / 1_000_000.0);
1213
1214 let result = pool
1215 .get_amount_out(BigUint::from(100_000_000_000_000_000u128), &token_a, &token_b)
1216 .expect("first swap should succeed");
1217
1218 assert_eq!(result.new_state.fee(), 2700.0 / 1_000_000.0);
1221 }
1222
1223 #[test]
1224 fn swap_that_does_not_move_the_tick_leaves_the_initial_fee_available() {
1225 let mut pool = initial_fee_pool(1_000);
1228 pool.apply_block(&BlockContext::new(101, 1_002));
1229
1230 pool.record_observation(pool.tick)
1231 .expect("no-op write should succeed");
1232
1233 assert_eq!(
1234 pool.get_fee()
1235 .expect("fee should be computable")
1236 .fee,
1237 750
1238 );
1239 }
1240
1241 #[test]
1242 fn initial_fee_branch_does_not_charge_the_twap_gas_overhead() {
1243 let mut pool = initial_fee_pool(1_000);
1244 pool.dfc = DynamicFeeConfig::new(2700, 30_000, 6_000_000, true, 750);
1245 pool.apply_block(&BlockContext::new(101, 1_002));
1246
1247 let resolved = pool
1248 .get_fee()
1249 .expect("fee should be computable");
1250
1251 assert_eq!(resolved, ResolvedFee { fee: 750, observed_twap: false });
1252 }
1253
1254 #[test]
1255 fn dynamic_fee_update_applies_for_supported_module() {
1256 let mut pool = create_basic_test_pool();
1257 pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
1258 let delta =
1259 dynamic_fee_delta(hex_literal::hex!("090b2A6bb475c00e2256e2095A60887cD710803b"));
1260
1261 pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1262 .expect("dynamic fee update should be valid");
1263
1264 assert_eq!(
1265 pool.get_fee()
1266 .expect("fee should be computable")
1267 .fee,
1268 500
1269 );
1270 }
1271
1272 #[test]
1273 fn dynamic_fee_update_falls_back_to_default_for_unsupported_module() {
1274 let mut pool = create_basic_test_pool();
1277 pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
1278 let delta =
1279 dynamic_fee_delta(hex_literal::hex!("DB45818A6db280ecfeB33cbeBd445423d0216b5D"));
1280
1281 pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1282 .expect("unsupported module delta should decode to the default config");
1283
1284 assert_eq!(pool.dfc, DynamicFeeConfig::default());
1285 assert_eq!(
1286 pool.get_fee()
1287 .expect("fee should be computable")
1288 .fee,
1289 3000
1290 );
1291 }
1292
1293 #[test]
1294 fn applies_partial_dynamic_fee_updates_after_module_initialization() {
1295 let mut pool = create_basic_test_pool();
1296 pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
1297 let delta = ProtocolStateDelta {
1298 component_id: "test-pool".to_string(),
1299 updated_attributes: HashMap::from([(
1300 "dfc_baseFee".to_string(),
1301 Bytes::from(500_u32.to_be_bytes()),
1302 )]),
1303 ..Default::default()
1304 };
1305
1306 pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1307 .expect("partial dynamic fee update should be valid");
1308
1309 assert_eq!(pool.dfc, DynamicFeeConfig::new(500, 10_000, 1, false, 0));
1310 }
1311
1312 #[test]
1313 fn test_partial_step_updates_tick_when_price_moves_without_crossing_initialized_tick() {
1314 let pool = create_basic_test_pool();
1315 let amount =
1316 I256::checked_from_sign_and_abs(Sign::Positive, U256::from(100_000_000_000_000_000u64))
1317 .unwrap();
1318
1319 let result = pool
1320 .swap(true, amount, None)
1321 .expect("swap should stay within the current liquidity range");
1322 let expected_tick =
1323 get_tick_at_sqrt_ratio(result.sqrt_price).expect("new sqrt price should map to a tick");
1324
1325 assert_ne!(result.sqrt_price, pool.sqrt_price);
1326 assert_ne!(result.sqrt_price, get_sqrt_ratio_at_tick(-120).unwrap());
1327 assert_ne!(expected_tick, pool.tick);
1328 assert_eq!(result.tick.value(), expected_tick);
1329 }
1330
1331 #[test]
1332 fn test_swap_keeps_boundary_tick_when_price_does_not_move() {
1333 let mut pool = create_basic_test_pool();
1334 pool.tick = -1;
1335 let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1u64)).unwrap();
1336
1337 let result = pool
1338 .swap(true, amount, None)
1339 .expect("swap should consume the input as fee without moving price");
1340
1341 assert_eq!(result.sqrt_price, pool.sqrt_price);
1342 assert_eq!(get_tick_at_sqrt_ratio(result.sqrt_price).unwrap(), 0);
1343 assert_eq!(result.tick.value(), pool.tick);
1344 }
1345
1346 #[test]
1347 fn test_swap_price_limit_out_of_range_returns_error() {
1348 let pool = create_basic_test_pool();
1349 let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
1350
1351 let result = pool.swap(true, amount, Some(pool.sqrt_price));
1352 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1353
1354 let result = pool.swap(true, amount, Some(MIN_SQRT_RATIO));
1355 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1356
1357 let result = pool.swap(false, amount, Some(pool.sqrt_price));
1358 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1359
1360 let result = pool.swap(false, amount, Some(MAX_SQRT_RATIO));
1361 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1362 }
1363
1364 #[test]
1365 fn test_swap_at_extreme_price_returns_error() {
1366 let sqrt_price = MIN_SQRT_RATIO + U256::from(1u64);
1367 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
1368 let ticks =
1369 vec![TickInfo::new(MIN_TICK, 0).unwrap(), TickInfo::new(MIN_TICK + 1, 0).unwrap()];
1370 let pool = AerodromeSlipstreamsState::new(
1371 "test-pool".to_string(),
1372 1_000_000,
1373 100_000_000_000_000_000_000u128,
1374 sqrt_price,
1375 0,
1376 1,
1377 3000,
1378 1,
1379 tick,
1380 ticks,
1381 vec![Observation::default()],
1382 DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
1383 )
1384 .expect("Failed to create pool");
1385
1386 let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
1387 let result = pool.swap(true, amount, None);
1388 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1389 }
1390
1391 fn token_pair() -> (Token, Token) {
1392 let token_a =
1393 Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
1394 let token_b =
1395 Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);
1396 (token_a, token_b)
1397 }
1398
1399 #[rstest]
1400 fn test_query_pool_swap_target_price_lands_in_band(#[values(true, false)] sell_a: bool) {
1401 let mut pool = create_basic_test_pool();
1402 pool.dfc = DynamicFeeConfig::new(3000, 10_000, 0, false, 0);
1403 let (token_a, token_b) = token_pair();
1404 let (token_in, token_out) =
1405 if sell_a { (&token_a, &token_b) } else { (&token_b, &token_a) };
1406 let target = pool
1407 .spot_price(token_in, token_out)
1408 .unwrap() *
1409 0.99;
1410 let tolerance = 1e-4;
1411 let params = target_price_params(
1412 token_in,
1413 token_out,
1414 to_price(target, token_in, token_out),
1415 tolerance,
1416 );
1417
1418 let swap = pool.query_pool_swap(¶ms).unwrap();
1419
1420 let new_spot = swap
1421 .new_state()
1422 .spot_price(token_in, token_out)
1423 .unwrap();
1424 assert!(new_spot >= target && new_spot <= target * (1.0 + tolerance), "spot {new_spot}");
1425 assert!(swap.price_points().is_none(), "the native path returns no price points");
1426 let quote = pool
1427 .get_amount_out(swap.amount_in().clone(), token_in, token_out)
1428 .unwrap();
1429 assert_eq!("e.amount, swap.amount_out());
1430 }
1431
1432 #[test]
1433 fn target_price_revalidates_after_initial_fee_changes() {
1434 let mut pool = initial_fee_pool(999_999);
1435 pool.ticks = Arc::new(
1436 TickList::from(
1437 1,
1438 vec![TickInfo::new(-1200, 0).unwrap(), TickInfo::new(1200, 0).unwrap()],
1439 )
1440 .unwrap(),
1441 );
1442 let (token_in, token_out) = token_pair();
1443 let target = 0.99;
1444 let tolerance = 1e-4;
1445 let params = target_price_params(
1446 &token_in,
1447 &token_out,
1448 to_price(target, &token_in, &token_out),
1449 tolerance,
1450 );
1451 let swap = pool
1452 .query_pool_swap(¶ms)
1453 .expect("search reaches the target using the final fee");
1454 let spot = swap
1455 .new_state()
1456 .spot_price(&token_in, &token_out)
1457 .unwrap();
1458 assert!(spot >= target && spot <= target * (1.0 + tolerance), "final spot {spot}");
1459 assert!(swap.price_points().is_some(), "fee change should trigger numerical search");
1460 }
1461
1462 #[test]
1464 fn test_query_pool_swap_target_price_falls_back_to_search() {
1465 let pool = create_basic_test_pool();
1466 let (token_a, token_b) = token_pair();
1467 let spot = pool
1468 .spot_price(&token_a, &token_b)
1469 .unwrap();
1470 let params = target_price_params(
1471 &token_a,
1472 &token_b,
1473 to_price(spot * (1.0 - 1e-5), &token_a, &token_b),
1474 1e-4,
1475 );
1476
1477 let swap = pool.query_pool_swap(¶ms).unwrap();
1478
1479 assert!(swap.price_points().is_some(), "the numerical search returns price points");
1480 }
1481
1482 #[test]
1483 fn test_query_pool_swap_target_price_at_spot() {
1484 let mut pool = create_basic_test_pool();
1485 pool.dfc = DynamicFeeConfig::new(ZERO_FEE_INDICATOR, 10_000, 0, false, 0);
1486 let (token_a, token_b) = token_pair();
1487 let params = target_price_params(
1488 &token_a,
1489 &token_b,
1490 Price::new(BigUint::from(1u64), BigUint::from(1u64)),
1491 1e-4,
1492 );
1493
1494 let swap = pool.query_pool_swap(¶ms).unwrap();
1495
1496 assert!(swap.amount_in().is_zero());
1497 assert!(swap.amount_out().is_zero());
1498 assert!(swap.new_state().eq(&pool));
1499 }
1500
1501 #[test]
1502 fn test_query_pool_swap_target_price_above_spot() {
1503 let pool = create_basic_test_pool();
1504 let (token_a, token_b) = token_pair();
1505 let spot = pool
1506 .spot_price(&token_a, &token_b)
1507 .unwrap();
1508 let params = target_price_params(
1509 &token_a,
1510 &token_b,
1511 to_price(spot * 1.01, &token_a, &token_b),
1512 1e-4,
1513 );
1514
1515 let result = pool.query_pool_swap(¶ms);
1516
1517 assert!(matches!(result, Err(SimulationError::InvalidInput(..))), "got {result:?}");
1518 }
1519}
1520
1521#[cfg(test)]
1522mod tick_list_sharing_tests {
1523 use std::collections::{HashMap, HashSet};
1524
1525 use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
1526
1527 use super::*;
1528 use crate::evm::protocol::utils::uniswap::tick_math::get_sqrt_ratio_at_tick;
1529
1530 #[test]
1531 fn test_delta_transition_leaves_clones_ticks_unchanged() {
1532 let original = AerodromeSlipstreamsState::new(
1533 "test-pool".to_string(),
1534 1_000_000,
1535 100_000_000_000_000_000_000u128,
1536 get_sqrt_ratio_at_tick(0).unwrap(),
1537 0,
1538 1,
1539 3000,
1540 1,
1541 0,
1542 vec![TickInfo::new(-120, 10000).unwrap(), TickInfo::new(120, -10000).unwrap()],
1543 vec![Observation::default()],
1544 DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
1545 )
1546 .unwrap();
1547 let mut updated = original.clone();
1548 let delta = ProtocolStateDelta {
1549 component_id: "State1".to_owned(),
1550 updated_attributes: HashMap::from([(
1551 "ticks/-120/net_liquidity".to_string(),
1552 Bytes::from(20000_i128.to_be_bytes().to_vec()),
1553 )]),
1554 deleted_attributes: HashSet::new(),
1555 };
1556
1557 updated
1558 .delta_transition(delta, &HashMap::new(), &Balances::default())
1559 .unwrap();
1560
1561 assert_eq!(
1562 updated
1563 .ticks
1564 .get_tick(-120)
1565 .unwrap()
1566 .net_liquidity,
1567 20000
1568 );
1569 assert_eq!(
1570 original
1571 .ticks
1572 .get_tick(-120)
1573 .unwrap()
1574 .net_liquidity,
1575 10000
1576 );
1577 }
1578}
1579
1580#[cfg(test)]
1581mod observation_sharing_tests {
1582 use std::collections::{HashMap, HashSet};
1583
1584 use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
1585
1586 use super::*;
1587 use crate::evm::protocol::utils::uniswap::tick_math::get_sqrt_ratio_at_tick;
1588
1589 fn pool_with_observations() -> AerodromeSlipstreamsState {
1590 let observations = (0..3)
1591 .map(|index| Observation {
1592 block_timestamp: 1_000 + u32::try_from(index).unwrap(),
1593 tick_cumulative: 10 * i64::from(index),
1594 initialized: true,
1595 index,
1596 ..Default::default()
1597 })
1598 .collect();
1599 let mut pool = AerodromeSlipstreamsState::new(
1600 "test-pool".to_string(),
1601 1_000_000,
1602 100_000_000_000_000_000_000u128,
1603 get_sqrt_ratio_at_tick(0).unwrap(),
1604 0,
1605 3,
1606 3000,
1607 1,
1608 0,
1609 vec![TickInfo::new(-120, 10000).unwrap(), TickInfo::new(120, -10000).unwrap()],
1610 observations,
1611 DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
1612 )
1613 .unwrap();
1614 pool.execution_block_timestamp = 2_000;
1615 pool
1616 }
1617
1618 fn swapped(
1620 pool: &AerodromeSlipstreamsState,
1621 timestamp: u64,
1622 tick: i32,
1623 ) -> AerodromeSlipstreamsState {
1624 let mut source = pool.clone();
1625 source.execution_block_timestamp = timestamp;
1626 let (state, written) =
1627 source.clone_post_swap(get_sqrt_ratio_at_tick(tick).unwrap(), tick, 1);
1628 written.unwrap();
1629 state
1630 }
1631
1632 fn observation_bytes(timestamp: u32) -> Bytes {
1633 let mut packed = [0u8; 32];
1635 packed[28..].copy_from_slice(×tamp.to_be_bytes());
1636 packed[0] = 1;
1637 Bytes::from(packed.to_vec())
1638 }
1639
1640 fn observation_delta(timestamp: u32) -> ProtocolStateDelta {
1641 ProtocolStateDelta {
1642 component_id: "State1".to_owned(),
1643 updated_attributes: HashMap::from([(
1644 "observations/1".to_string(),
1645 observation_bytes(timestamp),
1646 )]),
1647 deleted_attributes: HashSet::new(),
1648 }
1649 }
1650
1651 #[test]
1652 fn clone_shares_observations() {
1653 let original = pool_with_observations();
1654
1655 let copy = original.clone();
1656
1657 assert!(original
1658 .observations
1659 .shares_ring_with(©.observations));
1660 }
1661
1662 #[test]
1663 fn chain_of_tick_moving_swaps_never_copies_the_ring() {
1664 let original = pool_with_observations();
1665
1666 let first = swapped(&original, 2_000, 60);
1667 let second = swapped(&first, 2_010, -60);
1668 let third = swapped(&second, 2_020, 30);
1669
1670 for state in [&first, &second, &third] {
1671 assert!(original
1672 .observations
1673 .shares_ring_with(&state.observations));
1674 }
1675 assert_eq!(third.observation_index, 0);
1676 assert_eq!(
1677 third
1678 .observations
1679 .timestamp_at(0, 3)
1680 .unwrap(),
1681 2_020
1682 );
1683 assert_eq!(
1684 second
1685 .observations
1686 .timestamp_at(2, 3)
1687 .unwrap(),
1688 2_010
1689 );
1690 assert_eq!(
1691 first
1692 .observations
1693 .timestamp_at(1, 3)
1694 .unwrap(),
1695 2_000
1696 );
1697 }
1698
1699 #[test]
1700 fn swap_leaves_the_source_states_observations_unchanged() {
1701 let original = pool_with_observations();
1702
1703 let after_swap = swapped(&original, 2_000, 60);
1704
1705 assert_eq!(after_swap.observation_index, 1);
1706 assert_eq!(
1707 after_swap
1708 .observations
1709 .timestamp_at(1, 3)
1710 .unwrap(),
1711 2_000
1712 );
1713 assert_eq!(original.observation_index, 0);
1714 assert_eq!(
1715 original
1716 .observations
1717 .timestamp_at(1, 3)
1718 .unwrap(),
1719 1_001
1720 );
1721 }
1722
1723 #[test]
1724 fn second_swap_in_the_same_block_writes_nothing() {
1725 let original = pool_with_observations();
1726 let first = swapped(&original, 2_000, 60);
1727
1728 let second = swapped(&first, 2_000, -60);
1729
1730 assert_eq!(second.observation_index, first.observation_index);
1731 assert_eq!(second.observations, first.observations);
1732 }
1733
1734 #[test]
1735 fn swap_that_keeps_the_tick_writes_nothing() {
1736 let original = pool_with_observations();
1737
1738 let after_swap = swapped(&original, 2_000, original.tick);
1739
1740 assert_eq!(after_swap.observation_index, 0);
1741 assert_eq!(after_swap.observations, original.observations);
1742 }
1743
1744 #[test]
1745 fn fee_and_observations_match_a_state_rebuilt_from_the_merged_observations() {
1746 let original = pool_with_observations();
1747 let chained = swapped(&swapped(&original, 2_000, 60), 2_010, -60);
1748 let copied: AerodromeSlipstreamsState =
1749 serde_json::from_str(&serde_json::to_string(&chained).unwrap()).unwrap();
1750
1751 assert!(!chained
1752 .observations
1753 .shares_ring_with(&copied.observations));
1754 assert_eq!(chained.observations, copied.observations);
1755 assert_eq!(chained.get_fee().unwrap().fee, copied.get_fee().unwrap().fee);
1756 for seconds_ago in [0, 5, 10, 15] {
1757 assert_eq!(
1758 chained
1759 .observations
1760 .observe_single(2_020, seconds_ago, -60, 2, 1, 3)
1761 .unwrap(),
1762 copied
1763 .observations
1764 .observe_single(2_020, seconds_ago, -60, 2, 1, 3)
1765 .unwrap(),
1766 );
1767 }
1768 }
1769
1770 #[test]
1771 fn delta_transition_leaves_clones_observations_unchanged() {
1772 let original = pool_with_observations();
1773 let mut updated = original.clone();
1774
1775 updated
1776 .delta_transition(observation_delta(5_000), &HashMap::new(), &Balances::default())
1777 .unwrap();
1778
1779 assert_eq!(
1780 updated
1781 .observations
1782 .timestamp_at(1, 3)
1783 .unwrap(),
1784 5_000
1785 );
1786 assert_eq!(
1787 original
1788 .observations
1789 .timestamp_at(1, 3)
1790 .unwrap(),
1791 1_001
1792 );
1793 assert!(!original
1794 .observations
1795 .shares_ring_with(&updated.observations));
1796 }
1797
1798 #[test]
1799 fn delta_transition_after_simulated_writes_reads_the_chain_values() {
1800 let original = pool_with_observations();
1801 let mut simulated = swapped(&original, 2_000, 60);
1802
1803 simulated
1804 .delta_transition(observation_delta(5_000), &HashMap::new(), &Balances::default())
1805 .unwrap();
1806
1807 assert_eq!(
1808 simulated
1809 .observations
1810 .timestamp_at(1, 3)
1811 .unwrap(),
1812 5_000
1813 );
1814 assert_eq!(
1815 simulated
1816 .observations
1817 .timestamp_at(2, 3)
1818 .unwrap(),
1819 1_002
1820 );
1821 assert_eq!(
1822 original
1823 .observations
1824 .timestamp_at(1, 3)
1825 .unwrap(),
1826 1_001
1827 );
1828 }
1829
1830 #[test]
1831 fn delta_transition_keeps_simulated_writes_the_chain_did_not_touch() {
1832 let original = pool_with_observations();
1833 let mut simulated = swapped(&swapped(&original, 2_000, 60), 2_010, -60);
1834 let mut delta = observation_delta(5_000);
1835 delta.updated_attributes.clear();
1836 delta
1837 .deleted_attributes
1838 .insert("observations/0".to_string());
1839
1840 simulated
1841 .delta_transition(delta, &HashMap::new(), &Balances::default())
1842 .unwrap();
1843
1844 assert_eq!(
1846 simulated
1847 .observations
1848 .timestamp_at(0, 3)
1849 .unwrap(),
1850 2_000
1851 );
1852 assert_eq!(
1853 simulated
1854 .observations
1855 .timestamp_at(1, 3)
1856 .unwrap(),
1857 2_010
1858 );
1859 }
1860}
1861
1862#[cfg(test)]
1863mod step_cache_tests {
1864 use std::{
1865 collections::{HashMap, HashSet},
1866 str::FromStr,
1867 };
1868
1869 use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
1870
1871 use super::*;
1872 use crate::evm::protocol::utils::uniswap::swap_step_cache::test_fixtures::{
1873 amount_orders, test_amounts, test_ticks, wbtc_weth, LIQUIDITY, SQRT_PRICE, TICK,
1874 };
1875
1876 fn test_pool() -> AerodromeSlipstreamsState {
1877 AerodromeSlipstreamsState::new(
1878 "test-pool".to_string(),
1879 1_000_000,
1880 LIQUIDITY,
1881 U256::from_str(SQRT_PRICE).unwrap(),
1882 0,
1883 1,
1884 500,
1885 10,
1886 TICK,
1887 test_ticks(),
1888 vec![Observation::default()],
1889 DynamicFeeConfig::new(500, 10_000, 1, false, 0),
1890 )
1891 .unwrap()
1892 }
1893
1894 fn format_quote_result(
1896 pool: &AerodromeSlipstreamsState,
1897 amount: &BigUint,
1898 sell: &Token,
1899 buy: &Token,
1900 ) -> String {
1901 match pool.get_amount_out(amount.clone(), sell, buy) {
1902 Ok(result) => {
1903 let state = result
1904 .new_state
1905 .as_any()
1906 .downcast_ref::<AerodromeSlipstreamsState>()
1907 .unwrap();
1908 format!(
1909 "{} {} {} {} {}",
1910 result.amount, result.gas, state.sqrt_price, state.tick, state.liquidity
1911 )
1912 }
1913 Err(error) => format!("error {error}"),
1914 }
1915 }
1916
1917 #[test]
1918 fn test_step_cache_quotes_match_a_fresh_state_in_any_order() {
1919 let (wbtc, weth) = wbtc_weth();
1920 for (sell, buy, smallest) in [(&wbtc, &weth, 1_000u64), (&weth, &wbtc, 1_000_000_000)] {
1921 for order in amount_orders(&test_amounts(smallest)) {
1922 let shared = test_pool();
1923 for amount in &order {
1924 assert_eq!(
1925 format_quote_result(&shared, amount, sell, buy),
1926 format_quote_result(&test_pool(), amount, sell, buy),
1927 "selling {amount} {}",
1928 sell.symbol
1929 );
1930 }
1931 let steps = shared
1932 .step_cache
1933 .min_inputs(sell < buy)
1934 .len();
1935 assert!(steps > 2, "only {steps} steps cached");
1936 }
1937 }
1938 }
1939
1940 #[test]
1941 fn test_step_cache_quotes_match_a_fresh_state_at_each_cached_step() {
1942 let (wbtc, weth) = wbtc_weth();
1943 for (sell, buy, doublings) in [(&wbtc, &weth, 30u32), (&weth, &wbtc, 70)] {
1946 let cached = test_pool();
1947 #[expect(
1948 clippy::let_underscore_must_use,
1949 reason = "the quote may run out of liquidity; only the step cache it fills is used"
1950 )]
1951 let _ = cached.get_amount_out(BigUint::from(10u32) << doublings, sell, buy);
1952 let boundaries = cached.step_cache.min_inputs(sell < buy);
1953 assert!(boundaries.len() > 2, "only {} steps cached", boundaries.len());
1954 for boundary in boundaries.into_iter().skip(1) {
1955 for amount in [boundary - U256::from(1u64), boundary, boundary + U256::from(1u64)] {
1956 let amount = u256_to_biguint(amount);
1957 assert_eq!(
1958 format_quote_result(&cached, &amount, sell, buy),
1959 format_quote_result(&test_pool(), &amount, sell, buy),
1960 "selling {amount} {}",
1961 sell.symbol
1962 );
1963 }
1964 }
1965 }
1966 }
1967
1968 #[test]
1969 fn test_step_cache_of_a_swapped_state() {
1970 let (wbtc, weth) = wbtc_weth();
1971 let pool = test_pool();
1972 let swapped = pool
1973 .get_amount_out(BigUint::from(300_000_000u64), &wbtc, &weth)
1974 .unwrap()
1975 .new_state;
1976 let swapped = swapped
1977 .as_any()
1978 .downcast_ref::<AerodromeSlipstreamsState>()
1979 .unwrap();
1980 let fresh: AerodromeSlipstreamsState =
1982 serde_json::from_value(serde_json::to_value(swapped).unwrap()).unwrap();
1983
1984 for amount in test_amounts(1_000).iter().rev() {
1985 assert_eq!(
1986 format_quote_result(swapped, amount, &wbtc, &weth),
1987 format_quote_result(&fresh, amount, &wbtc, &weth),
1988 "selling {amount} WBTC"
1989 );
1990 }
1991 }
1992
1993 #[test]
1994 fn test_step_cache_restarts_after_delta_transition() {
1995 let (wbtc, weth) = wbtc_weth();
1996 let large = BigUint::from(3_000_000_000u64);
1997 let delta = || ProtocolStateDelta {
2000 component_id: "State1".to_owned(),
2001 updated_attributes: HashMap::from([(
2002 "ticks/255820/net_liquidity".to_string(),
2003 Bytes::from(
2004 1_000_000_000_000_000i128
2005 .to_be_bytes()
2006 .to_vec(),
2007 ),
2008 )]),
2009 deleted_attributes: HashSet::new(),
2010 };
2011 let mut cached = test_pool();
2012 cached
2013 .get_amount_out(large.clone(), &wbtc, &weth)
2014 .unwrap();
2015 let mut fresh = test_pool();
2016
2017 cached
2018 .delta_transition(delta(), &HashMap::new(), &Balances::default())
2019 .unwrap();
2020 fresh
2021 .delta_transition(delta(), &HashMap::new(), &Balances::default())
2022 .unwrap();
2023
2024 assert_eq!(
2025 format_quote_result(&cached, &large, &wbtc, &weth),
2026 format_quote_result(&fresh, &large, &wbtc, &weth)
2027 );
2028 }
2029}