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::{biguint_to_uint, 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_slot, 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 =
561 I256::checked_from_sign_and_abs(Sign::Positive, biguint_to_uint(&amount_in)?)
562 .ok_or_else(|| {
563 SimulationError::InvalidInput("I256 overflow: amount_in".to_string(), None)
564 })?;
565
566 let result = self.swap(zero_for_one, amount_specified, None)?;
567
568 trace!(?amount_in, ?token_in, ?token_out, ?zero_for_one, ?result, "SLIPSTREAMS SWAP");
569 let (new_state, observation) =
570 self.clone_post_swap(result.sqrt_price, result.tick.value(), result.liquidity);
571 observation?;
572
573 Ok(GetAmountOutResult::new(
574 u256_to_biguint(
575 result
576 .amount_calculated
577 .abs()
578 .into_raw(),
579 ),
580 u256_to_biguint(result.gas_used),
581 Box::new(new_state),
582 ))
583 }
584
585 fn get_limits(
586 &self,
587 sell_token: Bytes,
588 buy_token: Bytes,
589 ) -> Result<(BigUint, BigUint), SimulationError> {
590 if self.liquidity == 0 {
592 return Ok((BigUint::zero(), BigUint::zero()));
593 }
594 self.get_fee()?;
597
598 let zero_for_one = sell_token < buy_token;
599 let mut current_tick = self.tick;
600 let mut current_sqrt_price = self.sqrt_price;
601 let mut current_liquidity = self.liquidity;
602 let mut total_amount_in = U256::from(0u64);
603 let mut total_amount_out = U256::from(0u64);
604
605 let mut ticks_crossed: u64 = 0;
608 while let Ok((tick, next_tick_info)) = self
609 .ticks
610 .next_initialized_tick_within_one_word(current_tick, zero_for_one)
611 {
612 if ticks_crossed >= MAX_TICKS_CROSSED {
613 break;
614 }
615 ticks_crossed += 1;
616 let next_tick = tick.clamp(MIN_TICK, MAX_TICK);
618
619 let sqrt_price_next = match next_tick_info {
620 Some(info) => info.sqrt_price,
621 None => get_sqrt_ratio_at_tick_cached(next_tick)?,
622 };
623
624 let (amount_in, amount_out) = if zero_for_one {
627 let amount0 = get_amount0_delta(
628 sqrt_price_next,
629 current_sqrt_price,
630 current_liquidity,
631 true,
632 )?;
633 let amount1 = get_amount1_delta(
634 sqrt_price_next,
635 current_sqrt_price,
636 current_liquidity,
637 false,
638 )?;
639 (amount0, amount1)
640 } else {
641 let amount0 = get_amount0_delta(
642 sqrt_price_next,
643 current_sqrt_price,
644 current_liquidity,
645 false,
646 )?;
647 let amount1 = get_amount1_delta(
648 sqrt_price_next,
649 current_sqrt_price,
650 current_liquidity,
651 true,
652 )?;
653 (amount1, amount0)
654 };
655
656 total_amount_in = safe_add_u256(total_amount_in, amount_in)?;
658 total_amount_out = safe_add_u256(total_amount_out, amount_out)?;
659
660 if let Some(info) = next_tick_info {
665 let liquidity_raw = info.net_liquidity;
666 let liquidity_delta = if zero_for_one { -liquidity_raw } else { liquidity_raw };
667 current_liquidity =
668 liquidity_math::add_liquidity_delta(current_liquidity, liquidity_delta)?;
669 }
670
671 current_tick = if zero_for_one { next_tick - 1 } else { next_tick };
673 current_sqrt_price = sqrt_price_next;
674 }
675
676 Ok((u256_to_biguint(total_amount_in), u256_to_biguint(total_amount_out)))
677 }
678
679 fn delta_transition(
680 &mut self,
681 delta: ProtocolStateDelta,
682 _tokens: &HashMap<Bytes, Token>,
683 _balances: &Balances,
684 ) -> Result<(), TransitionError> {
685 self.step_cache = SwapStepCache::default();
687 if let Some(liquidity) = delta
689 .updated_attributes
690 .get("liquidity")
691 {
692 let liq_16_bytes = if liquidity.len() == 32 {
696 if liquidity == &Bytes::zero(32) {
698 Bytes::from([0; 16])
699 } else {
700 return Err(TransitionError::DecodeError(format!(
701 "Liquidity bytes too long for {liquidity}, expected 16",
702 )));
703 }
704 } else {
705 liquidity.clone()
706 };
707
708 self.liquidity = u128::try_from(liq_16_bytes)?;
709 }
710 if let Some(sqrt_price) = delta
711 .updated_attributes
712 .get("sqrt_price_x96")
713 {
714 self.sqrt_price = U256::from_be_slice(sqrt_price);
715 }
716 if let Some(observation_index) = delta
717 .updated_attributes
718 .get("observationIndex")
719 {
720 self.observation_index = u16::try_from(observation_index.clone())?;
721 }
722 if let Some(observation_cardinality) = delta
723 .updated_attributes
724 .get("observationCardinality")
725 {
726 self.observation_cardinality = u16::try_from(observation_cardinality.clone())?;
727 }
728 if let Some(default_fee) = delta
729 .updated_attributes
730 .get("default_fee")
731 {
732 self.default_fee = u32::try_from(default_fee.clone())?;
733 }
734 if let Some(hook) = self.aero_hook.as_mut() {
735 hook.update_from_attributes(&delta.updated_attributes)
736 .map_err(TransitionError::DecodeError)?;
737 } else {
738 self.dfc
739 .update_from_attributes(&delta.updated_attributes)
740 .map_err(|err| {
741 TransitionError::DecodeError(format!(
742 "Failed to update dynamic fee module config: {err}"
743 ))
744 })?;
745 }
746 if let Some(tick) = delta.updated_attributes.get("tick") {
747 let ticks_4_bytes = if tick.len() == 32 {
751 if tick == &Bytes::zero(32) {
753 Bytes::from([0; 4])
754 } else {
755 return Err(TransitionError::DecodeError(format!(
756 "Tick bytes too long for {tick}, expected 4"
757 )));
758 }
759 } else {
760 tick.clone()
761 };
762 self.tick = i24_be_bytes_to_i32(&ticks_4_bytes);
763 }
764
765 for (key, value) in delta.updated_attributes.iter() {
767 if key.starts_with("ticks/") {
769 let parts: Vec<&str> = key.split('/').collect();
770 Arc::make_mut(&mut self.ticks)
771 .set_tick_liquidity(
772 parts[1]
773 .parse::<i32>()
774 .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
775 i128::try_from(value.clone())?,
776 )
777 .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
778 }
779
780 if let Some(slot) = observation_slot(key) {
781 let slot = slot.map_err(TransitionError::DecodeError)?;
782 self.observations
783 .upsert_observation(slot, value)
784 .map_err(|err| TransitionError::DecodeError(format!("{key}: {err}")))?;
785 }
786 }
787 for key in delta.deleted_attributes.iter() {
789 if key.starts_with("ticks/") {
791 let parts: Vec<&str> = key.split('/').collect();
792 Arc::make_mut(&mut self.ticks)
793 .set_tick_liquidity(
794 parts[1]
795 .parse::<i32>()
796 .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
797 0,
798 )
799 .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
800 }
801
802 if let Some(slot) = observation_slot(key) {
803 let slot = slot.map_err(TransitionError::DecodeError)?;
804 self.observations
805 .upsert_observation(slot, &[])
806 .map_err(|err| TransitionError::DecodeError(format!("{key}: {err}")))?;
807 }
808 }
809 Ok(())
810 }
811
812 fn apply_block(&mut self, block: &BlockContext) -> bool {
816 let timestamp = block.timestamp();
817 if timestamp == self.execution_block_timestamp &&
818 block.number() == self.execution_block_number
819 {
820 return false;
821 }
822 let fee_before = self.get_fee().ok();
823 self.execution_block_timestamp = timestamp;
824 self.execution_block_number = block.number();
825 fee_before != self.get_fee().ok()
826 }
827
828 fn clone_box(&self) -> Box<dyn ProtocolSim> {
829 Box::new(self.clone())
830 }
831
832 fn as_any(&self) -> &dyn Any {
833 self
834 }
835
836 fn as_any_mut(&mut self) -> &mut dyn Any {
837 self
838 }
839
840 fn eq(&self, other: &dyn ProtocolSim) -> bool {
841 if let Some(other_state) = other
842 .as_any()
843 .downcast_ref::<AerodromeSlipstreamsState>()
844 {
845 let Ok(self_fee) = self.get_fee() else { return false };
846 let Ok(other_fee) = other_state.get_fee() else { return false };
847
848 self.liquidity == other_state.liquidity &&
849 self.sqrt_price == other_state.sqrt_price &&
850 self_fee == other_fee &&
851 self.tick == other_state.tick &&
852 self.ticks == other_state.ticks
853 } else {
854 false
855 }
856 }
857
858 fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
861 match params.swap_constraint() {
862 SwapConstraint::TradeLimitPrice { .. } => {
863 crate::evm::query_pool_swap::query_pool_swap(self, params)
864 }
865 SwapConstraint::PoolTargetPrice {
866 target,
867 tolerance,
868 min_amount_in: _,
869 max_amount_in: _,
870 } => {
871 let swap = self.swap_to_target_price(params, target, *tolerance)?;
872 let target = price_to_f64_with_decimals(
873 target,
874 params.token_in().decimals,
875 params.token_out().decimals,
876 )?;
877 let spot = swap
878 .new_state()
879 .spot_price(params.token_in(), params.token_out())?;
880 if !tolerance.is_finite() ||
881 *tolerance < 0.0 ||
882 !(spot >= target && spot <= target * (1.0 + tolerance))
883 {
884 return Err(SimulationError::RecoverableError(
885 "Aerodrome target-price search ended outside the requested tolerance"
886 .into(),
887 ));
888 }
889 Ok(swap)
890 }
891 }
892 }
893}
894
895#[cfg(test)]
896#[path = "aero_cl_replay_tests.rs"]
897mod aero_cl_replay_tests;
898
899#[cfg(test)]
900mod tests {
901 use std::str::FromStr;
902
903 use alloy::primitives::{Sign, I256, U256};
904 use rstest::rstest;
905 use tycho_common::{models::Chain, simulation::errors::SimulationError};
906
907 use super::*;
908 use crate::evm::{
909 protocol::utils::{
910 slipstreams::{
911 dynamic_fee_module::{DynamicFeeConfig, ZERO_FEE_INDICATOR},
912 observations::Observation,
913 },
914 uniswap::{
915 tick_list::TickInfo,
916 tick_math::{
917 get_sqrt_ratio_at_tick, get_tick_at_sqrt_ratio, MAX_SQRT_RATIO, MIN_SQRT_RATIO,
918 MIN_TICK,
919 },
920 },
921 },
922 query_pool_swap::test_helpers::{target_price_params, to_price},
923 };
924
925 fn create_basic_test_pool() -> AerodromeSlipstreamsState {
926 let sqrt_price = get_sqrt_ratio_at_tick(0).expect("Failed to calculate sqrt price");
927 let ticks = vec![TickInfo::new(-120, 0).unwrap(), TickInfo::new(120, 0).unwrap()];
928 AerodromeSlipstreamsState::new(
929 "test-pool".to_string(),
930 1_000_000,
931 100_000_000_000_000_000_000u128,
932 sqrt_price,
933 0,
934 1,
935 3000,
936 1,
937 0,
938 ticks,
939 vec![Observation::default()],
940 DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
941 )
942 .expect("Failed to create pool")
943 }
944
945 fn dynamic_fee_delta(dynamic_fee_module: [u8; 20]) -> ProtocolStateDelta {
946 ProtocolStateDelta {
947 component_id: "test-pool".to_string(),
948 updated_attributes: HashMap::from([
949 ("dynamic_fee_module".to_string(), Bytes::from(dynamic_fee_module)),
950 ("dfc_baseFee".to_string(), Bytes::from(500_u32.to_be_bytes())),
951 ("dfc_scalingFactor".to_string(), Bytes::from(0_u64.to_be_bytes())),
952 ("dfc_feeCap".to_string(), Bytes::from(700_u32.to_be_bytes())),
953 ("dfc_initialFeeEnabled".to_string(), Bytes::from([0_u8])),
954 ("dfc_initialFee".to_string(), Bytes::from(0_u32.to_be_bytes())),
955 ]),
956 ..Default::default()
957 }
958 }
959
960 fn initial_fee_pool(last_observation_ts: u32) -> AerodromeSlipstreamsState {
966 let mut pool = create_basic_test_pool();
967 pool.dfc = DynamicFeeConfig::new(2700, 30_000, 0, true, 750);
968 pool.position_assumption = BlockPositionAssumption::First;
969 pool.observations = Observations::new(vec![Observation {
970 block_timestamp: last_observation_ts,
971 initialized: true,
972 ..Default::default()
973 }]);
974 pool
975 }
976
977 #[test]
990 fn replays_base_block_50166683_swap_pair_wei_exact() {
991 let mut observations = vec![Observation::default(); 213];
994 observations.push(Observation {
995 block_timestamp: 1_787_122_711, tick_cumulative: -18_995_710_863_218,
997 seconds_per_liquidity_cumulative_x128: U256::from_str(
998 "42501948193164408449462610706599523891176959",
999 )
1000 .unwrap(),
1001 initialized: true,
1002 });
1003
1004 let mut pool = AerodromeSlipstreamsState::new(
1005 "0xdFe5F275020def30993f042174Fc2D335678b626".to_string(),
1006 1_787_122_711, 1_128_781_556_759_264_064u128,
1008 U256::from_str("1979649713595747421731").unwrap(),
1009 213,
1010 360,
1011 2700, 200,
1013 -350_116,
1014 vec![TickInfo::new(-351_000, 0).unwrap(), TickInfo::new(-349_000, 0).unwrap()],
1017 observations,
1018 DynamicFeeConfig::new(2700, 0, 0, true, 750),
1019 )
1020 .expect("state should build")
1021 .with_position_assumption(BlockPositionAssumption::First);
1023
1024 assert!(pool.apply_block(&BlockContext::new(50_166_683, 1_787_122_713)));
1026
1027 let aero = Token::new(
1028 &Bytes::from_str("0x940181a94A35A4569E4529A3CDfB74e38FD98631").unwrap(),
1029 "AERO",
1030 18,
1031 0,
1032 &[Some(10_000)],
1033 Chain::Base,
1034 100,
1035 );
1036 let cbbtc = Token::new(
1037 &Bytes::from_str("0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf").unwrap(),
1038 "cbBTC",
1039 8,
1040 0,
1041 &[Some(10_000)],
1042 Chain::Base,
1043 100,
1044 );
1045
1046 assert_eq!(pool.fee(), 750.0 / 1_000_000.0);
1047 let first = pool
1048 .get_amount_out(BigUint::from(1_688_626u32), &cbbtc, &aero)
1049 .expect("first swap should succeed");
1050 assert_eq!(first.amount, BigUint::from(2_702_489_253_591_513_843_346u128));
1051
1052 assert_eq!(first.new_state.fee(), 2700.0 / 1_000_000.0);
1053 let second = first
1054 .new_state
1055 .get_amount_out(BigUint::from(450_733u32), &cbbtc, &aero)
1056 .expect("second swap should succeed");
1057 assert_eq!(second.amount, BigUint::from(719_894_300_964_297_656_776u128));
1058
1059 let replayed = first
1060 .new_state
1061 .as_any()
1062 .downcast_ref::<AerodromeSlipstreamsState>()
1063 .expect("state type");
1064 assert_eq!(replayed.observation_index, 214, "chain slot0 shows 214 after the block");
1065 assert_eq!(
1066 replayed
1067 .observations
1068 .timestamp_at(214, 360)
1069 .unwrap(),
1070 1_787_122_713
1071 );
1072 }
1073
1074 #[test]
1075 fn ticks_exceeded_partial_result_still_records_the_observation() {
1076 let mut pool = initial_fee_pool(1_000);
1079 pool.apply_block(&BlockContext::new(101, 1_002));
1080 let token_a =
1081 Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
1082 let token_b =
1083 Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);
1084
1085 let err = pool
1086 .get_amount_out(
1087 BigUint::from(1_000_000_000_000_000_000_000_000u128),
1088 &token_a,
1089 &token_b,
1090 )
1091 .expect_err("swap must exhaust the tick list");
1092 let SimulationError::InvalidInput(_, Some(partial)) = err else {
1093 panic!("expected a partial result, got {err:?}");
1094 };
1095
1096 assert_eq!(partial.new_state.fee(), 2700.0 / 1_000_000.0);
1097 }
1098
1099 #[test]
1100 fn ring_that_cannot_answer_observe_fails_limits_like_quotes() {
1101 let mut pool = create_basic_test_pool();
1104 pool.dfc = DynamicFeeConfig::new(0, 10_000, 1_000_000, false, 0);
1105 pool.observation_index = 5;
1106 pool.observation_cardinality = 300;
1107 let mut slots = vec![Observation::default(); 7];
1108 slots[5] =
1109 Observation { block_timestamp: 999_990, initialized: true, ..Default::default() };
1110 slots[6] =
1111 Observation { block_timestamp: 999_000, initialized: true, ..Default::default() };
1112 pool.observations = Observations::new(slots);
1113 let token_a =
1114 Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
1115 let token_b =
1116 Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);
1117
1118 assert!(pool.get_fee().is_err());
1119 assert!(pool
1120 .spot_price(&token_a, &token_b)
1121 .is_err());
1122 assert!(pool
1123 .get_amount_out(BigUint::from(1_000u32), &token_a, &token_b)
1124 .is_err());
1125 assert!(pool
1126 .get_limits(token_a.address, token_b.address)
1127 .is_err());
1128 }
1129
1130 #[test]
1131 fn default_quotes_the_worse_fee_when_position_is_unknown() {
1132 let mut pool = initial_fee_pool(1_000);
1136 pool.position_assumption = BlockPositionAssumption::WorstCase;
1137 pool.apply_block(&BlockContext::new(101, 1_002));
1138
1139 assert_eq!(
1140 pool.get_fee()
1141 .expect("fee should be computable")
1142 .fee,
1143 2700
1144 );
1145 }
1146
1147 #[test]
1148 fn worst_case_picks_the_initial_fee_when_it_is_the_higher_one() {
1149 let mut pool = initial_fee_pool(1_000);
1152 pool.dfc = DynamicFeeConfig::new(500, 30_000, 0, true, 4_000);
1153 pool.position_assumption = BlockPositionAssumption::WorstCase;
1154 pool.apply_block(&BlockContext::new(101, 1_002));
1155
1156 assert_eq!(
1157 pool.get_fee()
1158 .expect("fee should be computable")
1159 .fee,
1160 4_000
1161 );
1162 }
1163
1164 #[test]
1165 fn worst_case_keeps_a_flat_fee_pool_quiet_across_blocks() {
1166 let mut pool = initial_fee_pool(1_000);
1169 pool.position_assumption = BlockPositionAssumption::WorstCase;
1170 pool.apply_block(&BlockContext::new(100, 1_000));
1171
1172 assert!(!pool.apply_block(&BlockContext::new(101, 1_002)));
1173 assert!(!pool.apply_block(&BlockContext::new(102, 1_004)));
1174 }
1175
1176 #[test]
1177 fn apply_block_reports_a_fee_flip_and_is_idempotent() {
1178 let mut pool = initial_fee_pool(1_000);
1181 pool.apply_block(&BlockContext::new(100, 1_000));
1182
1183 assert!(pool.apply_block(&BlockContext::new(101, 1_002)), "branch flip must re-emit");
1184 assert!(!pool.apply_block(&BlockContext::new(101, 1_002)), "repeat block is a no-op");
1185 }
1186
1187 #[test]
1188 fn apply_block_stays_quiet_while_the_fee_does_not_move() {
1189 let mut pool = initial_fee_pool(1_000);
1192 pool.apply_block(&BlockContext::new(101, 1_002));
1193
1194 assert!(!pool.apply_block(&BlockContext::new(102, 1_004)));
1195 assert!(!pool.apply_block(&BlockContext::new(103, 1_006)));
1196 }
1197
1198 #[test]
1199 fn quotes_initial_fee_for_the_next_block_after_the_pool_traded() {
1200 let mut pool = initial_fee_pool(1_000);
1204 pool.apply_block(&BlockContext::new(101, 1_002));
1205
1206 assert_eq!(
1207 pool.get_fee()
1208 .expect("fee should be computable")
1209 .fee,
1210 750
1211 );
1212 }
1213
1214 #[test]
1215 fn quotes_dynamic_fee_when_targeting_a_block_the_pool_already_traded_in() {
1216 let mut pool = initial_fee_pool(1_000);
1219 pool.apply_block(&BlockContext::new(100, 1_000));
1220
1221 assert_eq!(
1222 pool.get_fee()
1223 .expect("fee should be computable")
1224 .fee,
1225 2700
1226 );
1227 }
1228
1229 #[test]
1230 fn chained_swap_in_the_same_block_pays_the_dynamic_fee() {
1231 let mut pool = initial_fee_pool(1_000);
1232 pool.apply_block(&BlockContext::new(101, 1_002));
1233 let token_a =
1234 Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
1235 let token_b =
1236 Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);
1237
1238 assert_eq!(pool.fee(), 750.0 / 1_000_000.0);
1239
1240 let result = pool
1241 .get_amount_out(BigUint::from(100_000_000_000_000_000u128), &token_a, &token_b)
1242 .expect("first swap should succeed");
1243
1244 assert_eq!(result.new_state.fee(), 2700.0 / 1_000_000.0);
1247 }
1248
1249 #[test]
1250 fn swap_that_does_not_move_the_tick_leaves_the_initial_fee_available() {
1251 let mut pool = initial_fee_pool(1_000);
1254 pool.apply_block(&BlockContext::new(101, 1_002));
1255
1256 pool.record_observation(pool.tick)
1257 .expect("no-op write should succeed");
1258
1259 assert_eq!(
1260 pool.get_fee()
1261 .expect("fee should be computable")
1262 .fee,
1263 750
1264 );
1265 }
1266
1267 #[test]
1268 fn initial_fee_branch_does_not_charge_the_twap_gas_overhead() {
1269 let mut pool = initial_fee_pool(1_000);
1270 pool.dfc = DynamicFeeConfig::new(2700, 30_000, 6_000_000, true, 750);
1271 pool.apply_block(&BlockContext::new(101, 1_002));
1272
1273 let resolved = pool
1274 .get_fee()
1275 .expect("fee should be computable");
1276
1277 assert_eq!(resolved, ResolvedFee { fee: 750, observed_twap: false });
1278 }
1279
1280 #[test]
1281 fn dynamic_fee_update_applies_for_supported_module() {
1282 let mut pool = create_basic_test_pool();
1283 pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
1284 let delta =
1285 dynamic_fee_delta(hex_literal::hex!("090b2A6bb475c00e2256e2095A60887cD710803b"));
1286
1287 pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1288 .expect("dynamic fee update should be valid");
1289
1290 assert_eq!(
1291 pool.get_fee()
1292 .expect("fee should be computable")
1293 .fee,
1294 500
1295 );
1296 }
1297
1298 #[test]
1299 fn dynamic_fee_update_falls_back_to_default_for_unsupported_module() {
1300 let mut pool = create_basic_test_pool();
1303 pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
1304 let delta =
1305 dynamic_fee_delta(hex_literal::hex!("DB45818A6db280ecfeB33cbeBd445423d0216b5D"));
1306
1307 pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1308 .expect("unsupported module delta should decode to the default config");
1309
1310 assert_eq!(pool.dfc, DynamicFeeConfig::default());
1311 assert_eq!(
1312 pool.get_fee()
1313 .expect("fee should be computable")
1314 .fee,
1315 3000
1316 );
1317 }
1318
1319 #[test]
1320 fn applies_partial_dynamic_fee_updates_after_module_initialization() {
1321 let mut pool = create_basic_test_pool();
1322 pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
1323 let delta = ProtocolStateDelta {
1324 component_id: "test-pool".to_string(),
1325 updated_attributes: HashMap::from([(
1326 "dfc_baseFee".to_string(),
1327 Bytes::from(500_u32.to_be_bytes()),
1328 )]),
1329 ..Default::default()
1330 };
1331
1332 pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1333 .expect("partial dynamic fee update should be valid");
1334
1335 assert_eq!(pool.dfc, DynamicFeeConfig::new(500, 10_000, 1, false, 0));
1336 }
1337
1338 #[test]
1339 fn applies_a_cardinality_increase() {
1340 let mut pool = create_basic_test_pool();
1344 let ring = Observations::new(vec![Observation {
1345 block_timestamp: 999_990,
1346 initialized: true,
1347 ..Default::default()
1348 }]);
1349 pool.observations = ring.clone();
1350 let delta = ProtocolStateDelta {
1351 component_id: "test-pool".to_string(),
1352 updated_attributes: (1..4)
1353 .map(|index| (format!("observations/{index}"), Bytes::from([0x01_u8])))
1354 .collect(),
1355 ..Default::default()
1356 };
1357
1358 pool.delta_transition(delta, &HashMap::new(), &Balances::default())
1359 .expect("prefilled observation slots should be valid");
1360
1361 assert_eq!(pool.observations, ring);
1362 }
1363
1364 #[rstest]
1365 #[case::not_a_number("observations/next")]
1366 #[case::past_the_ring("observations/65535")]
1367 fn malformed_observation_key_fails_the_transition(#[case] key: &str) {
1368 let mut pool = create_basic_test_pool();
1369 let delta = ProtocolStateDelta {
1370 component_id: "test-pool".to_string(),
1371 updated_attributes: HashMap::from([(key.to_string(), Bytes::from([0x01_u8]))]),
1372 ..Default::default()
1373 };
1374
1375 let result = pool.delta_transition(delta, &HashMap::new(), &Balances::default());
1376
1377 let Err(TransitionError::DecodeError(message)) = result else {
1378 panic!("expected a DecodeError, got {result:?}");
1379 };
1380 assert!(message.starts_with(key), "{message}");
1381 }
1382
1383 #[test]
1384 fn test_partial_step_updates_tick_when_price_moves_without_crossing_initialized_tick() {
1385 let pool = create_basic_test_pool();
1386 let amount =
1387 I256::checked_from_sign_and_abs(Sign::Positive, U256::from(100_000_000_000_000_000u64))
1388 .unwrap();
1389
1390 let result = pool
1391 .swap(true, amount, None)
1392 .expect("swap should stay within the current liquidity range");
1393 let expected_tick =
1394 get_tick_at_sqrt_ratio(result.sqrt_price).expect("new sqrt price should map to a tick");
1395
1396 assert_ne!(result.sqrt_price, pool.sqrt_price);
1397 assert_ne!(result.sqrt_price, get_sqrt_ratio_at_tick(-120).unwrap());
1398 assert_ne!(expected_tick, pool.tick);
1399 assert_eq!(result.tick.value(), expected_tick);
1400 }
1401
1402 #[test]
1403 fn test_swap_keeps_boundary_tick_when_price_does_not_move() {
1404 let mut pool = create_basic_test_pool();
1405 pool.tick = -1;
1406 let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1u64)).unwrap();
1407
1408 let result = pool
1409 .swap(true, amount, None)
1410 .expect("swap should consume the input as fee without moving price");
1411
1412 assert_eq!(result.sqrt_price, pool.sqrt_price);
1413 assert_eq!(get_tick_at_sqrt_ratio(result.sqrt_price).unwrap(), 0);
1414 assert_eq!(result.tick.value(), pool.tick);
1415 }
1416
1417 #[test]
1418 fn test_swap_price_limit_out_of_range_returns_error() {
1419 let pool = create_basic_test_pool();
1420 let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
1421
1422 let result = pool.swap(true, amount, Some(pool.sqrt_price));
1423 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1424
1425 let result = pool.swap(true, amount, Some(MIN_SQRT_RATIO));
1426 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1427
1428 let result = pool.swap(false, amount, Some(pool.sqrt_price));
1429 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1430
1431 let result = pool.swap(false, amount, Some(MAX_SQRT_RATIO));
1432 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1433 }
1434
1435 #[test]
1436 fn test_swap_at_extreme_price_returns_error() {
1437 let sqrt_price = MIN_SQRT_RATIO + U256::from(1u64);
1438 let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
1439 let ticks =
1440 vec![TickInfo::new(MIN_TICK, 0).unwrap(), TickInfo::new(MIN_TICK + 1, 0).unwrap()];
1441 let pool = AerodromeSlipstreamsState::new(
1442 "test-pool".to_string(),
1443 1_000_000,
1444 100_000_000_000_000_000_000u128,
1445 sqrt_price,
1446 0,
1447 1,
1448 3000,
1449 1,
1450 tick,
1451 ticks,
1452 vec![Observation::default()],
1453 DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
1454 )
1455 .expect("Failed to create pool");
1456
1457 let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
1458 let result = pool.swap(true, amount, None);
1459 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
1460 }
1461
1462 fn token_pair() -> (Token, Token) {
1463 let token_a =
1464 Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
1465 let token_b =
1466 Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);
1467 (token_a, token_b)
1468 }
1469
1470 #[rstest]
1471 fn test_query_pool_swap_target_price_lands_in_band(#[values(true, false)] sell_a: bool) {
1472 let mut pool = create_basic_test_pool();
1473 pool.dfc = DynamicFeeConfig::new(3000, 10_000, 0, false, 0);
1474 let (token_a, token_b) = token_pair();
1475 let (token_in, token_out) =
1476 if sell_a { (&token_a, &token_b) } else { (&token_b, &token_a) };
1477 let target = pool
1478 .spot_price(token_in, token_out)
1479 .unwrap() *
1480 0.99;
1481 let tolerance = 1e-4;
1482 let params = target_price_params(
1483 token_in,
1484 token_out,
1485 to_price(target, token_in, token_out),
1486 tolerance,
1487 );
1488
1489 let swap = pool.query_pool_swap(¶ms).unwrap();
1490
1491 let new_spot = swap
1492 .new_state()
1493 .spot_price(token_in, token_out)
1494 .unwrap();
1495 assert!(new_spot >= target && new_spot <= target * (1.0 + tolerance), "spot {new_spot}");
1496 assert!(swap.price_points().is_none(), "the native path returns no price points");
1497 let quote = pool
1498 .get_amount_out(swap.amount_in().clone(), token_in, token_out)
1499 .unwrap();
1500 assert_eq!("e.amount, swap.amount_out());
1501 }
1502
1503 #[test]
1504 fn target_price_revalidates_after_initial_fee_changes() {
1505 let mut pool = initial_fee_pool(999_999);
1506 pool.ticks = Arc::new(
1507 TickList::from(
1508 1,
1509 vec![TickInfo::new(-1200, 0).unwrap(), TickInfo::new(1200, 0).unwrap()],
1510 )
1511 .unwrap(),
1512 );
1513 let (token_in, token_out) = token_pair();
1514 let target = 0.99;
1515 let tolerance = 1e-4;
1516 let params = target_price_params(
1517 &token_in,
1518 &token_out,
1519 to_price(target, &token_in, &token_out),
1520 tolerance,
1521 );
1522 let swap = pool
1523 .query_pool_swap(¶ms)
1524 .expect("search reaches the target using the final fee");
1525 let spot = swap
1526 .new_state()
1527 .spot_price(&token_in, &token_out)
1528 .unwrap();
1529 assert!(spot >= target && spot <= target * (1.0 + tolerance), "final spot {spot}");
1530 assert!(swap.price_points().is_some(), "fee change should trigger numerical search");
1531 }
1532
1533 #[test]
1535 fn test_query_pool_swap_target_price_falls_back_to_search() {
1536 let pool = create_basic_test_pool();
1537 let (token_a, token_b) = token_pair();
1538 let spot = pool
1539 .spot_price(&token_a, &token_b)
1540 .unwrap();
1541 let params = target_price_params(
1542 &token_a,
1543 &token_b,
1544 to_price(spot * (1.0 - 1e-5), &token_a, &token_b),
1545 1e-4,
1546 );
1547
1548 let swap = pool.query_pool_swap(¶ms).unwrap();
1549
1550 assert!(swap.price_points().is_some(), "the numerical search returns price points");
1551 }
1552
1553 #[test]
1554 fn test_query_pool_swap_target_price_at_spot() {
1555 let mut pool = create_basic_test_pool();
1556 pool.dfc = DynamicFeeConfig::new(ZERO_FEE_INDICATOR, 10_000, 0, false, 0);
1557 let (token_a, token_b) = token_pair();
1558 let params = target_price_params(
1559 &token_a,
1560 &token_b,
1561 Price::new(BigUint::from(1u64), BigUint::from(1u64)),
1562 1e-4,
1563 );
1564
1565 let swap = pool.query_pool_swap(¶ms).unwrap();
1566
1567 assert!(swap.amount_in().is_zero());
1568 assert!(swap.amount_out().is_zero());
1569 assert!(swap.new_state().eq(&pool));
1570 }
1571
1572 #[test]
1573 fn test_query_pool_swap_target_price_above_spot() {
1574 let pool = create_basic_test_pool();
1575 let (token_a, token_b) = token_pair();
1576 let spot = pool
1577 .spot_price(&token_a, &token_b)
1578 .unwrap();
1579 let params = target_price_params(
1580 &token_a,
1581 &token_b,
1582 to_price(spot * 1.01, &token_a, &token_b),
1583 1e-4,
1584 );
1585
1586 let result = pool.query_pool_swap(¶ms);
1587
1588 assert!(matches!(result, Err(SimulationError::InvalidInput(..))), "got {result:?}");
1589 }
1590}
1591
1592#[cfg(test)]
1593mod tick_list_sharing_tests {
1594 use std::collections::{HashMap, HashSet};
1595
1596 use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
1597
1598 use super::*;
1599 use crate::evm::protocol::utils::uniswap::tick_math::get_sqrt_ratio_at_tick;
1600
1601 #[test]
1602 fn test_delta_transition_leaves_clones_ticks_unchanged() {
1603 let original = AerodromeSlipstreamsState::new(
1604 "test-pool".to_string(),
1605 1_000_000,
1606 100_000_000_000_000_000_000u128,
1607 get_sqrt_ratio_at_tick(0).unwrap(),
1608 0,
1609 1,
1610 3000,
1611 1,
1612 0,
1613 vec![TickInfo::new(-120, 10000).unwrap(), TickInfo::new(120, -10000).unwrap()],
1614 vec![Observation::default()],
1615 DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
1616 )
1617 .unwrap();
1618 let mut updated = original.clone();
1619 let delta = ProtocolStateDelta {
1620 component_id: "State1".to_owned(),
1621 updated_attributes: HashMap::from([(
1622 "ticks/-120/net_liquidity".to_string(),
1623 Bytes::from(20000_i128.to_be_bytes().to_vec()),
1624 )]),
1625 deleted_attributes: HashSet::new(),
1626 };
1627
1628 updated
1629 .delta_transition(delta, &HashMap::new(), &Balances::default())
1630 .unwrap();
1631
1632 assert_eq!(
1633 updated
1634 .ticks
1635 .get_tick(-120)
1636 .unwrap()
1637 .net_liquidity,
1638 20000
1639 );
1640 assert_eq!(
1641 original
1642 .ticks
1643 .get_tick(-120)
1644 .unwrap()
1645 .net_liquidity,
1646 10000
1647 );
1648 }
1649}
1650
1651#[cfg(test)]
1652mod observation_sharing_tests {
1653 use std::collections::{HashMap, HashSet};
1654
1655 use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
1656
1657 use super::*;
1658 use crate::evm::protocol::utils::uniswap::tick_math::get_sqrt_ratio_at_tick;
1659
1660 fn pool_with_observations() -> AerodromeSlipstreamsState {
1661 let observations = (0..3)
1662 .map(|index| Observation {
1663 block_timestamp: 1_000 + u32::try_from(index).unwrap(),
1664 tick_cumulative: 10 * i64::from(index),
1665 initialized: true,
1666 ..Default::default()
1667 })
1668 .collect();
1669 let mut pool = AerodromeSlipstreamsState::new(
1670 "test-pool".to_string(),
1671 1_000_000,
1672 100_000_000_000_000_000_000u128,
1673 get_sqrt_ratio_at_tick(0).unwrap(),
1674 0,
1675 3,
1676 3000,
1677 1,
1678 0,
1679 vec![TickInfo::new(-120, 10000).unwrap(), TickInfo::new(120, -10000).unwrap()],
1680 observations,
1681 DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
1682 )
1683 .unwrap();
1684 pool.execution_block_timestamp = 2_000;
1685 pool
1686 }
1687
1688 fn swapped(
1690 pool: &AerodromeSlipstreamsState,
1691 timestamp: u64,
1692 tick: i32,
1693 ) -> AerodromeSlipstreamsState {
1694 let mut source = pool.clone();
1695 source.execution_block_timestamp = timestamp;
1696 let (state, written) =
1697 source.clone_post_swap(get_sqrt_ratio_at_tick(tick).unwrap(), tick, 1);
1698 written.unwrap();
1699 state
1700 }
1701
1702 fn observation_bytes(timestamp: u32) -> Bytes {
1703 let mut packed = [0u8; 32];
1705 packed[28..].copy_from_slice(×tamp.to_be_bytes());
1706 packed[0] = 1;
1707 Bytes::from(packed.to_vec())
1708 }
1709
1710 fn observation_delta(timestamp: u32) -> ProtocolStateDelta {
1711 ProtocolStateDelta {
1712 component_id: "State1".to_owned(),
1713 updated_attributes: HashMap::from([(
1714 "observations/1".to_string(),
1715 observation_bytes(timestamp),
1716 )]),
1717 deleted_attributes: HashSet::new(),
1718 }
1719 }
1720
1721 #[test]
1722 fn clone_shares_observations() {
1723 let original = pool_with_observations();
1724
1725 let copy = original.clone();
1726
1727 assert!(original
1728 .observations
1729 .shares_ring_with(©.observations));
1730 }
1731
1732 #[test]
1733 fn chain_of_tick_moving_swaps_never_copies_the_ring() {
1734 let original = pool_with_observations();
1735
1736 let first = swapped(&original, 2_000, 60);
1737 let second = swapped(&first, 2_010, -60);
1738 let third = swapped(&second, 2_020, 30);
1739
1740 for state in [&first, &second, &third] {
1741 assert!(original
1742 .observations
1743 .shares_ring_with(&state.observations));
1744 }
1745 assert_eq!(third.observation_index, 0);
1746 assert_eq!(
1747 third
1748 .observations
1749 .timestamp_at(0, 3)
1750 .unwrap(),
1751 2_020
1752 );
1753 assert_eq!(
1754 second
1755 .observations
1756 .timestamp_at(2, 3)
1757 .unwrap(),
1758 2_010
1759 );
1760 assert_eq!(
1761 first
1762 .observations
1763 .timestamp_at(1, 3)
1764 .unwrap(),
1765 2_000
1766 );
1767 }
1768
1769 #[test]
1770 fn swap_leaves_the_source_states_observations_unchanged() {
1771 let original = pool_with_observations();
1772
1773 let after_swap = swapped(&original, 2_000, 60);
1774
1775 assert_eq!(after_swap.observation_index, 1);
1776 assert_eq!(
1777 after_swap
1778 .observations
1779 .timestamp_at(1, 3)
1780 .unwrap(),
1781 2_000
1782 );
1783 assert_eq!(original.observation_index, 0);
1784 assert_eq!(
1785 original
1786 .observations
1787 .timestamp_at(1, 3)
1788 .unwrap(),
1789 1_001
1790 );
1791 }
1792
1793 #[test]
1794 fn second_swap_in_the_same_block_writes_nothing() {
1795 let original = pool_with_observations();
1796 let first = swapped(&original, 2_000, 60);
1797
1798 let second = swapped(&first, 2_000, -60);
1799
1800 assert_eq!(second.observation_index, first.observation_index);
1801 assert_eq!(second.observations, first.observations);
1802 }
1803
1804 #[test]
1805 fn swap_that_keeps_the_tick_writes_nothing() {
1806 let original = pool_with_observations();
1807
1808 let after_swap = swapped(&original, 2_000, original.tick);
1809
1810 assert_eq!(after_swap.observation_index, 0);
1811 assert_eq!(after_swap.observations, original.observations);
1812 }
1813
1814 #[test]
1815 fn fee_and_observations_match_a_state_rebuilt_from_the_merged_observations() {
1816 let original = pool_with_observations();
1817 let chained = swapped(&swapped(&original, 2_000, 60), 2_010, -60);
1818 let copied: AerodromeSlipstreamsState =
1819 serde_json::from_str(&serde_json::to_string(&chained).unwrap()).unwrap();
1820
1821 assert!(!chained
1822 .observations
1823 .shares_ring_with(&copied.observations));
1824 assert_eq!(chained.observations, copied.observations);
1825 assert_eq!(chained.get_fee().unwrap().fee, copied.get_fee().unwrap().fee);
1826 for seconds_ago in [0, 5, 10, 15] {
1827 assert_eq!(
1828 chained
1829 .observations
1830 .observe_single(2_020, seconds_ago, -60, 2, 1, 3)
1831 .unwrap(),
1832 copied
1833 .observations
1834 .observe_single(2_020, seconds_ago, -60, 2, 1, 3)
1835 .unwrap(),
1836 );
1837 }
1838 }
1839
1840 #[test]
1841 fn delta_transition_leaves_clones_observations_unchanged() {
1842 let original = pool_with_observations();
1843 let mut updated = original.clone();
1844
1845 updated
1846 .delta_transition(observation_delta(5_000), &HashMap::new(), &Balances::default())
1847 .unwrap();
1848
1849 assert_eq!(
1850 updated
1851 .observations
1852 .timestamp_at(1, 3)
1853 .unwrap(),
1854 5_000
1855 );
1856 assert_eq!(
1857 original
1858 .observations
1859 .timestamp_at(1, 3)
1860 .unwrap(),
1861 1_001
1862 );
1863 assert!(!original
1864 .observations
1865 .shares_ring_with(&updated.observations));
1866 }
1867
1868 #[test]
1869 fn delta_transition_after_simulated_writes_reads_the_chain_values() {
1870 let original = pool_with_observations();
1871 let mut simulated = swapped(&original, 2_000, 60);
1872
1873 simulated
1874 .delta_transition(observation_delta(5_000), &HashMap::new(), &Balances::default())
1875 .unwrap();
1876
1877 assert_eq!(
1878 simulated
1879 .observations
1880 .timestamp_at(1, 3)
1881 .unwrap(),
1882 5_000
1883 );
1884 assert_eq!(
1885 simulated
1886 .observations
1887 .timestamp_at(2, 3)
1888 .unwrap(),
1889 1_002
1890 );
1891 assert_eq!(
1892 original
1893 .observations
1894 .timestamp_at(1, 3)
1895 .unwrap(),
1896 1_001
1897 );
1898 }
1899
1900 #[test]
1901 fn delta_transition_keeps_simulated_writes_the_chain_did_not_touch() {
1902 let original = pool_with_observations();
1903 let mut simulated = swapped(&swapped(&original, 2_000, 60), 2_010, -60);
1904 let mut delta = observation_delta(5_000);
1905 delta.updated_attributes.clear();
1906 delta
1907 .deleted_attributes
1908 .insert("observations/0".to_string());
1909
1910 simulated
1911 .delta_transition(delta, &HashMap::new(), &Balances::default())
1912 .unwrap();
1913
1914 assert_eq!(simulated.observations.get(0), Some(Observation::default()));
1916 assert_eq!(
1917 simulated
1918 .observations
1919 .timestamp_at(1, 3)
1920 .unwrap(),
1921 2_000
1922 );
1923 assert_eq!(
1924 simulated
1925 .observations
1926 .timestamp_at(2, 3)
1927 .unwrap(),
1928 2_010
1929 );
1930 }
1931}
1932
1933#[cfg(test)]
1934mod step_cache_tests {
1935 use std::{
1936 collections::{HashMap, HashSet},
1937 str::FromStr,
1938 };
1939
1940 use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};
1941
1942 use super::*;
1943 use crate::evm::protocol::utils::uniswap::swap_step_cache::test_fixtures::{
1944 amount_orders, test_amounts, test_ticks, wbtc_weth, LIQUIDITY, SQRT_PRICE, TICK,
1945 };
1946
1947 fn test_pool() -> AerodromeSlipstreamsState {
1948 AerodromeSlipstreamsState::new(
1949 "test-pool".to_string(),
1950 1_000_000,
1951 LIQUIDITY,
1952 U256::from_str(SQRT_PRICE).unwrap(),
1953 0,
1954 1,
1955 500,
1956 10,
1957 TICK,
1958 test_ticks(),
1959 vec![Observation::default()],
1960 DynamicFeeConfig::new(500, 10_000, 1, false, 0),
1961 )
1962 .unwrap()
1963 }
1964
1965 fn format_quote_result(
1967 pool: &AerodromeSlipstreamsState,
1968 amount: &BigUint,
1969 sell: &Token,
1970 buy: &Token,
1971 ) -> String {
1972 match pool.get_amount_out(amount.clone(), sell, buy) {
1973 Ok(result) => {
1974 let state = result
1975 .new_state
1976 .as_any()
1977 .downcast_ref::<AerodromeSlipstreamsState>()
1978 .unwrap();
1979 format!(
1980 "{} {} {} {} {}",
1981 result.amount, result.gas, state.sqrt_price, state.tick, state.liquidity
1982 )
1983 }
1984 Err(error) => format!("error {error}"),
1985 }
1986 }
1987
1988 #[test]
1989 fn test_step_cache_quotes_match_a_fresh_state_in_any_order() {
1990 let (wbtc, weth) = wbtc_weth();
1991 for (sell, buy, smallest) in [(&wbtc, &weth, 1_000u64), (&weth, &wbtc, 1_000_000_000)] {
1992 for order in amount_orders(&test_amounts(smallest)) {
1993 let shared = test_pool();
1994 for amount in &order {
1995 assert_eq!(
1996 format_quote_result(&shared, amount, sell, buy),
1997 format_quote_result(&test_pool(), amount, sell, buy),
1998 "selling {amount} {}",
1999 sell.symbol
2000 );
2001 }
2002 let steps = shared
2003 .step_cache
2004 .min_inputs(sell < buy)
2005 .len();
2006 assert!(steps > 2, "only {steps} steps cached");
2007 }
2008 }
2009 }
2010
2011 #[test]
2012 fn test_step_cache_quotes_match_a_fresh_state_at_each_cached_step() {
2013 let (wbtc, weth) = wbtc_weth();
2014 for (sell, buy, doublings) in [(&wbtc, &weth, 30u32), (&weth, &wbtc, 70)] {
2017 let cached = test_pool();
2018 #[expect(
2019 clippy::let_underscore_must_use,
2020 reason = "the quote may run out of liquidity; only the step cache it fills is used"
2021 )]
2022 let _ = cached.get_amount_out(BigUint::from(10u32) << doublings, sell, buy);
2023 let boundaries = cached.step_cache.min_inputs(sell < buy);
2024 assert!(boundaries.len() > 2, "only {} steps cached", boundaries.len());
2025 for boundary in boundaries.into_iter().skip(1) {
2026 for amount in [boundary - U256::from(1u64), boundary, boundary + U256::from(1u64)] {
2027 let amount = u256_to_biguint(amount);
2028 assert_eq!(
2029 format_quote_result(&cached, &amount, sell, buy),
2030 format_quote_result(&test_pool(), &amount, sell, buy),
2031 "selling {amount} {}",
2032 sell.symbol
2033 );
2034 }
2035 }
2036 }
2037 }
2038
2039 #[test]
2040 fn test_step_cache_of_a_swapped_state() {
2041 let (wbtc, weth) = wbtc_weth();
2042 let pool = test_pool();
2043 let swapped = pool
2044 .get_amount_out(BigUint::from(300_000_000u64), &wbtc, &weth)
2045 .unwrap()
2046 .new_state;
2047 let swapped = swapped
2048 .as_any()
2049 .downcast_ref::<AerodromeSlipstreamsState>()
2050 .unwrap();
2051 let fresh: AerodromeSlipstreamsState =
2053 serde_json::from_value(serde_json::to_value(swapped).unwrap()).unwrap();
2054
2055 for amount in test_amounts(1_000).iter().rev() {
2056 assert_eq!(
2057 format_quote_result(swapped, amount, &wbtc, &weth),
2058 format_quote_result(&fresh, amount, &wbtc, &weth),
2059 "selling {amount} WBTC"
2060 );
2061 }
2062 }
2063
2064 #[test]
2065 fn test_step_cache_restarts_after_delta_transition() {
2066 let (wbtc, weth) = wbtc_weth();
2067 let large = BigUint::from(3_000_000_000u64);
2068 let delta = || ProtocolStateDelta {
2071 component_id: "State1".to_owned(),
2072 updated_attributes: HashMap::from([(
2073 "ticks/255820/net_liquidity".to_string(),
2074 Bytes::from(
2075 1_000_000_000_000_000i128
2076 .to_be_bytes()
2077 .to_vec(),
2078 ),
2079 )]),
2080 deleted_attributes: HashSet::new(),
2081 };
2082 let mut cached = test_pool();
2083 cached
2084 .get_amount_out(large.clone(), &wbtc, &weth)
2085 .unwrap();
2086 let mut fresh = test_pool();
2087
2088 cached
2089 .delta_transition(delta(), &HashMap::new(), &Balances::default())
2090 .unwrap();
2091 fresh
2092 .delta_transition(delta(), &HashMap::new(), &Balances::default())
2093 .unwrap();
2094
2095 assert_eq!(
2096 format_quote_result(&cached, &large, &wbtc, &weth),
2097 format_quote_result(&fresh, &large, &wbtc, &weth)
2098 );
2099 }
2100}