1use std::sync::Arc;
19
20use ahash::AHashMap;
21use alloy_primitives::{Address, I256, U160, U256};
22use nautilus_core::UnixNanos;
23
24use crate::defi::{
25 DexType, PoolLiquidityUpdate, PoolSwap, SharedPool,
26 data::{
27 DexPoolData, PoolFeeCollect, PoolFeeProtocolCollect, PoolFeeProtocolUpdate,
28 PoolLiquidityUpdateType, block::BlockPosition, flash::PoolFlash,
29 },
30 pool_analysis::{
31 error::{
32 PoolEventKind, PoolEventLocation, PoolProfilerError, liquidity_error_with_location,
33 },
34 position::PoolPosition,
35 quote::SwapQuote,
36 size_estimator,
37 snapshot::{PROTOCOL_FEE_BASIS_POINTS_DENOMINATOR, PoolAnalytics, PoolSnapshot, PoolState},
38 swap_math::{SwapStepResult, compute_swap_step},
39 },
40 reporting::{BlockchainSyncReportItems, BlockchainSyncReporter},
41 tick_map::{
42 TickMap,
43 full_math::{FullMath, Q128},
44 liquidity_math::{liquidity_math_add, try_liquidity_math_add},
45 sqrt_price_math::{get_amount0_delta, get_amount1_delta, get_amounts_for_liquidity},
46 tick::{CrossedTick, PoolTick},
47 tick_math::{
48 MAX_SQRT_RATIO, MIN_SQRT_RATIO, get_sqrt_ratio_at_tick, get_tick_at_sqrt_ratio,
49 },
50 },
51};
52
53#[derive(Debug, Clone)]
71#[cfg_attr(
72 feature = "python",
73 pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
74)]
75#[cfg_attr(
76 feature = "python",
77 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
78)]
79pub struct PoolProfiler {
80 pub pool: SharedPool,
82 positions: AHashMap<String, PoolPosition>,
84 pub tick_map: TickMap,
86 pub state: PoolState,
88 pub analytics: PoolAnalytics,
90 pub last_processed_event: Option<BlockPosition>,
92 pub last_processed_ts: Option<UnixNanos>,
94 pub is_initialized: bool,
96 reporter: Option<BlockchainSyncReporter>,
98 last_reported_block: u64,
100}
101
102impl PoolProfiler {
103 #[must_use]
109 pub fn new(pool: SharedPool) -> Self {
110 let tick_spacing = pool.tick_spacing.expect("Pool tick spacing must be set");
111 let mut state = PoolState::default();
112
113 if let Some((fee_protocol0, fee_protocol1)) =
114 initial_protocol_fee_basis_points(pool.dex.name, pool.fee)
115 {
116 state.set_protocol_fee_basis_points(fee_protocol0, fee_protocol1);
117 }
118
119 Self {
120 pool,
121 positions: AHashMap::new(),
122 tick_map: TickMap::new(tick_spacing),
123 state,
124 analytics: PoolAnalytics::default(),
125 last_processed_event: None,
126 last_processed_ts: None,
127 is_initialized: false,
128 reporter: None,
129 last_reported_block: 0,
130 }
131 }
132
133 pub fn initialize(&mut self, price_sqrt_ratio_x96: U160) -> Result<(), PoolProfilerError> {
140 if self.is_initialized {
141 return Err(PoolProfilerError::AlreadyInitialized {
142 instrument_id: self.pool.instrument_id,
143 pool_identifier: self.pool.pool_identifier,
144 });
145 }
146
147 let calculated_tick = get_tick_at_sqrt_ratio(price_sqrt_ratio_x96);
148
149 if let Some(initial_tick) = self.pool.initial_tick
150 && initial_tick != calculated_tick
151 {
152 return Err(PoolProfilerError::InitialTickMismatch {
153 instrument_id: self.pool.instrument_id,
154 pool_identifier: self.pool.pool_identifier,
155 initial_tick,
156 calculated_tick,
157 });
158 }
159
160 log::info!(
161 "Initializing pool profiler with tick {calculated_tick} and price sqrt ratio {price_sqrt_ratio_x96}"
162 );
163
164 self.state.current_tick = calculated_tick;
165 self.state.price_sqrt_ratio_x96 = price_sqrt_ratio_x96;
166 self.is_initialized = true;
167 Ok(())
168 }
169
170 pub fn check_if_initialized(&self, event_kind: PoolEventKind) -> Result<(), PoolProfilerError> {
177 if !self.is_initialized {
178 return Err(PoolProfilerError::NotInitialized {
179 instrument_id: self.pool.instrument_id,
180 pool_identifier: self.pool.pool_identifier,
181 event_kind,
182 });
183 }
184 Ok(())
185 }
186
187 fn event_location(
188 &self,
189 event_kind: PoolEventKind,
190 block: u64,
191 transaction_index: u32,
192 log_index: u32,
193 ) -> PoolEventLocation {
194 PoolEventLocation {
195 instrument_id: self.pool.instrument_id,
196 pool_identifier: self.pool.pool_identifier,
197 block,
198 transaction_index,
199 log_index,
200 event_kind,
201 }
202 }
203
204 pub fn process(&mut self, event: &DexPoolData) -> anyhow::Result<()> {
218 if self.check_if_already_processed(
219 event.block_number(),
220 event.transaction_index(),
221 event.log_index(),
222 ) {
223 return Ok(());
224 }
225
226 match event {
227 DexPoolData::Swap(swap) => self.process_swap(swap)?,
228 DexPoolData::LiquidityUpdate(update) => match update.kind {
229 PoolLiquidityUpdateType::Mint => self.process_mint(update)?,
230 PoolLiquidityUpdateType::Burn => self.process_burn(update)?,
231 },
232 DexPoolData::FeeCollect(collect) => self.process_collect(collect)?,
233 DexPoolData::FeeProtocolUpdate(update) => self.process_fee_protocol_update(update)?,
234 DexPoolData::FeeProtocolCollect(collect) => {
235 self.process_fee_protocol_collect(collect)?;
236 }
237 DexPoolData::Flash(flash) => self.process_flash(flash)?,
238 }
239
240 self.update_reporter_if_enabled(event.block_number());
241
242 Ok(())
243 }
244
245 fn check_if_already_processed(&self, block: u64, tx_idx: u32, log_idx: u32) -> bool {
247 if let Some(last_event) = &self.last_processed_event {
248 let should_skip = block < last_event.number
249 || (block == last_event.number && tx_idx < last_event.transaction_index)
250 || (block == last_event.number
251 && tx_idx == last_event.transaction_index
252 && log_idx <= last_event.log_index);
253
254 if should_skip {
255 log::debug!(
256 "Skipping already processed event at block {block} tx {tx_idx} log {log_idx}"
257 );
258 }
259 return should_skip;
260 }
261
262 false
263 }
264
265 fn update_reporter_if_enabled(&mut self, current_block: u64) {
267 if let Some(reporter) = &mut self.reporter {
269 let blocks_processed = current_block.saturating_sub(self.last_reported_block);
270
271 if blocks_processed > 0 {
272 reporter.update(blocks_processed as usize);
273 self.last_reported_block = current_block;
274
275 if reporter.should_log_progress(current_block, current_block) {
276 reporter.log_progress(current_block);
277 }
278 }
279 }
280 }
281
282 pub fn process_swap(&mut self, swap: &PoolSwap) -> anyhow::Result<()> {
305 self.check_if_initialized(PoolEventKind::Swap)?;
306
307 if self.check_if_already_processed(swap.block, swap.transaction_index, swap.log_index) {
308 return Ok(());
309 }
310
311 let zero_for_one = if swap.amount0.is_zero() && swap.amount1.is_zero() {
312 swap.sqrt_price_x96 < self.state.price_sqrt_ratio_x96
313 } else {
314 swap.amount0.is_positive()
315 };
316
317 let amount_specified = if zero_for_one {
318 swap.amount0
319 } else {
320 swap.amount1
321 };
322
323 let sqrt_price_limit_x96 = swap.sqrt_price_x96;
326 let location = self.event_location(
327 PoolEventKind::Swap,
328 swap.block,
329 swap.transaction_index,
330 swap.log_index,
331 );
332 let swap_quote = self
333 .simulate_swap_through_ticks(amount_specified, zero_for_one, sqrt_price_limit_x96, true)
334 .map_err(|e| Self::wrap_liquidity_error(e, location.clone()))?;
335
336 self.validate_swap_replay(swap, &swap_quote, location)?;
337 self.apply_swap_event(swap, &swap_quote);
338 Ok(())
339 }
340
341 pub fn execute_swap(
356 &mut self,
357 sender: Address,
358 recipient: Address,
359 block: BlockPosition,
360 zero_for_one: bool,
361 amount_specified: I256,
362 sqrt_price_limit_x96: U160,
363 ) -> anyhow::Result<PoolSwap> {
364 self.check_if_initialized(PoolEventKind::Swap)?;
365
366 let swap_quote = self.simulate_swap_through_ticks(
367 amount_specified,
368 zero_for_one,
369 sqrt_price_limit_x96,
370 false,
371 )?;
372
373 self.apply_swap_quote(&swap_quote);
374
375 let swap_event = PoolSwap::new(
376 Arc::clone(&self.pool.chain),
377 Arc::clone(&self.pool.dex),
378 self.pool.instrument_id,
379 self.pool.pool_identifier,
380 block.number,
381 block.transaction_hash,
382 block.transaction_index,
383 block.log_index,
384 self.pool.ts_init, self.pool.ts_init, sender,
387 recipient,
388 swap_quote.amount0,
389 swap_quote.amount1,
390 self.state.price_sqrt_ratio_x96,
391 self.tick_map.liquidity,
392 self.state.current_tick,
393 );
394 Ok(swap_event)
395 }
396
397 pub fn simulate_swap_through_ticks(
436 &self,
437 amount_specified: I256,
438 zero_for_one: bool,
439 sqrt_price_limit_x96: U160,
440 traverse_empty_ranges: bool,
441 ) -> anyhow::Result<SwapQuote> {
442 self.validate_price_limit(sqrt_price_limit_x96, zero_for_one, true)?;
443
444 let simulation = SwapSimulation::new(
445 self,
446 amount_specified,
447 zero_for_one,
448 sqrt_price_limit_x96,
449 traverse_empty_ranges,
450 );
451
452 simulation.run()
453 }
454
455 pub fn apply_swap_quote(&mut self, swap_quote: &SwapQuote) {
463 self.state.current_tick = swap_quote.tick_after;
464 self.state.price_sqrt_ratio_x96 = swap_quote.sqrt_price_after_x96;
465
466 self.apply_swap_quote_fee_state(swap_quote);
467
468 for crossed in &swap_quote.crossed_ticks {
469 let liquidity_net =
470 self.tick_map
471 .cross_tick(crossed.tick, crossed.fee_growth_0, crossed.fee_growth_1);
472
473 self.tick_map.liquidity = if crossed.zero_for_one {
474 liquidity_math_add(self.tick_map.liquidity, -liquidity_net)
475 } else {
476 liquidity_math_add(self.tick_map.liquidity, liquidity_net)
477 };
478 }
479 self.analytics.total_swaps += 1;
480
481 debug_assert_eq!(
482 self.tick_map.liquidity, swap_quote.liquidity_after,
483 "Liquidity mismatch in apply_swap_quote: computed={}, quote={}",
484 self.tick_map.liquidity, swap_quote.liquidity_after
485 );
486 }
487
488 fn apply_swap_quote_fee_state(&mut self, swap_quote: &SwapQuote) {
489 if swap_quote.amount0.is_zero() && swap_quote.amount1.is_zero() {
490 return;
491 }
492
493 if swap_quote.zero_for_one() {
494 self.state.fee_growth_global_0 = swap_quote.fee_growth_global_after;
495 self.state.protocol_fees_token0 += swap_quote.protocol_fee;
496 } else {
497 self.state.fee_growth_global_1 = swap_quote.fee_growth_global_after;
498 self.state.protocol_fees_token1 += swap_quote.protocol_fee;
499 }
500 }
501
502 #[must_use]
506 pub fn wrap_liquidity_error(err: anyhow::Error, location: PoolEventLocation) -> anyhow::Error {
507 match err.downcast::<super::error::LiquidityMathError>() {
508 Ok(math_err) => anyhow::Error::from(liquidity_error_with_location(math_err, location)),
509 Err(other) => other,
510 }
511 }
512
513 pub fn quote_swap(
535 &self,
536 amount_specified: I256,
537 zero_for_one: bool,
538 sqrt_price_limit_x96: Option<U160>,
539 ) -> anyhow::Result<SwapQuote> {
540 self.check_if_initialized(PoolEventKind::Swap)?;
541
542 if amount_specified.is_zero() {
543 anyhow::bail!("Cannot quote swap with zero amount");
544 }
545
546 if let Some(price_limit) = sqrt_price_limit_x96 {
547 self.validate_price_limit(price_limit, zero_for_one, false)?;
548 }
549
550 let limit = sqrt_price_limit_x96.unwrap_or_else(|| {
551 if zero_for_one {
552 MIN_SQRT_RATIO + U160::from(1)
553 } else {
554 MAX_SQRT_RATIO - U160::from(1)
555 }
556 });
557
558 self.simulate_swap_through_ticks(amount_specified, zero_for_one, limit, false)
559 }
560
561 pub fn swap_exact_in(
566 &self,
567 amount_in: U256,
568 zero_for_one: bool,
569 sqrt_price_limit_x96: Option<U160>,
570 ) -> anyhow::Result<SwapQuote> {
571 let amount_specified = I256::from(amount_in);
573 let quote = self.quote_swap(amount_specified, zero_for_one, sqrt_price_limit_x96)?;
574
575 Ok(quote)
576 }
577
578 pub fn swap_exact_out(
584 &self,
585 amount_out: U256,
586 zero_for_one: bool,
587 sqrt_price_limit_x96: Option<U160>,
588 ) -> anyhow::Result<SwapQuote> {
589 let amount_specified = -I256::from(amount_out);
591 let quote = self.quote_swap(amount_specified, zero_for_one, sqrt_price_limit_x96)?;
592 quote.validate_exact_output(amount_out)?;
593
594 Ok(quote)
595 }
596
597 pub fn swap_to_lower_sqrt_price(
602 &self,
603 sqrt_price_limit_x96: U160,
604 ) -> anyhow::Result<SwapQuote> {
605 self.quote_swap(I256::MAX, true, Some(sqrt_price_limit_x96))
606 }
607
608 pub fn swap_to_higher_sqrt_price(
613 &self,
614 sqrt_price_limit_x96: U160,
615 ) -> anyhow::Result<SwapQuote> {
616 self.quote_swap(I256::MAX, false, Some(sqrt_price_limit_x96))
617 }
618
619 pub fn size_for_impact_bps(&self, impact_bps: u32, zero_for_one: bool) -> anyhow::Result<U256> {
634 let config = size_estimator::EstimationConfig::default();
635 size_estimator::size_for_impact_bps(self, impact_bps, zero_for_one, &config)
636 }
637
638 pub fn size_for_impact_bps_detailed(
652 &self,
653 impact_bps: u32,
654 zero_for_one: bool,
655 ) -> anyhow::Result<size_estimator::SizeForImpactResult> {
656 let config = size_estimator::EstimationConfig::default();
657 size_estimator::size_for_impact_bps_detailed(self, impact_bps, zero_for_one, &config)
658 }
659
660 fn validate_price_limit(
667 &self,
668 limit_price_sqrt: U160,
669 zero_for_one: bool,
670 allow_equal: bool,
671 ) -> anyhow::Result<()> {
672 if zero_for_one {
673 if limit_price_sqrt > self.state.price_sqrt_ratio_x96
675 || (!allow_equal && limit_price_sqrt == self.state.price_sqrt_ratio_x96)
676 {
677 anyhow::bail!("Price limit must be less than current price for zero_for_one swaps");
678 }
679
680 if limit_price_sqrt <= MIN_SQRT_RATIO {
681 anyhow::bail!(
682 "Price limit {limit_price_sqrt} must be greater than MIN_SQRT_RATIO {MIN_SQRT_RATIO}"
683 );
684 }
685 } else {
686 if limit_price_sqrt < self.state.price_sqrt_ratio_x96
688 || (!allow_equal && limit_price_sqrt == self.state.price_sqrt_ratio_x96)
689 {
690 anyhow::bail!(
691 "Price limit must be greater than current price for one_for_zero swaps"
692 );
693 }
694
695 if limit_price_sqrt >= MAX_SQRT_RATIO {
696 anyhow::bail!(
697 "Price limit {limit_price_sqrt} must be less than MAX_SQRT_RATIO {MAX_SQRT_RATIO}"
698 );
699 }
700 }
701
702 Ok(())
703 }
704
705 pub fn process_mint(&mut self, update: &PoolLiquidityUpdate) -> anyhow::Result<()> {
717 self.check_if_initialized(PoolEventKind::Mint)?;
718
719 if self.check_if_already_processed(update.block, update.transaction_index, update.log_index)
720 {
721 return Ok(());
722 }
723
724 self.validate_ticks(update.tick_lower, update.tick_upper)?;
725 let location = self.event_location(
726 PoolEventKind::Mint,
727 update.block,
728 update.transaction_index,
729 update.log_index,
730 );
731 self.add_liquidity(
732 &update.owner,
733 update.tick_lower,
734 update.tick_upper,
735 update.position_liquidity,
736 update.amount0,
737 update.amount1,
738 )
739 .map_err(|e| Self::wrap_liquidity_error(e, location))?;
740
741 self.analytics.total_mints += 1;
742 self.last_processed_event = Some(
743 BlockPosition::new(
744 update.block,
745 update.transaction_hash.clone(),
746 update.transaction_index,
747 update.log_index,
748 )
749 .with_block_hash(update.block_hash.clone()),
750 );
751 self.last_processed_ts = Some(update.ts_event);
752 self.update_reporter_if_enabled(update.block);
753 self.update_liquidity_analytics();
754
755 Ok(())
756 }
757
758 fn add_liquidity(
763 &mut self,
764 owner: &Address,
765 tick_lower: i32,
766 tick_upper: i32,
767 liquidity: u128,
768 amount0: U256,
769 amount1: U256,
770 ) -> anyhow::Result<()> {
771 let liquidity_delta = i128::try_from(liquidity)
772 .map_err(|_| anyhow::anyhow!("Liquidity {liquidity} exceeds i128::MAX"))?;
773 self.update_position(
774 owner,
775 tick_lower,
776 tick_upper,
777 liquidity_delta,
778 amount0,
779 amount1,
780 )?;
781
782 self.analytics.total_amount0_deposited += amount0;
784 self.analytics.total_amount1_deposited += amount1;
785
786 Ok(())
787 }
788
789 pub fn execute_mint(
804 &mut self,
805 recipient: Address,
806 block: BlockPosition,
807 tick_lower: i32,
808 tick_upper: i32,
809 liquidity: u128,
810 ) -> anyhow::Result<PoolLiquidityUpdate> {
811 self.check_if_initialized(PoolEventKind::Mint)?;
812
813 self.validate_ticks(tick_lower, tick_upper)?;
814 let (amount0, amount1) = get_amounts_for_liquidity(
815 self.state.price_sqrt_ratio_x96,
816 tick_lower,
817 tick_upper,
818 liquidity,
819 true,
820 );
821 self.add_liquidity(
822 &recipient, tick_lower, tick_upper, liquidity, amount0, amount1,
823 )?;
824
825 self.analytics.total_mints += 1;
826
827 let event = PoolLiquidityUpdate::new(
828 Arc::clone(&self.pool.chain),
829 Arc::clone(&self.pool.dex),
830 self.pool.instrument_id,
831 self.pool.pool_identifier,
832 PoolLiquidityUpdateType::Mint,
833 block.number,
834 block.transaction_hash,
835 block.transaction_index,
836 block.log_index,
837 None,
838 recipient,
839 liquidity,
840 amount0,
841 amount1,
842 tick_lower,
843 tick_upper,
844 self.pool.ts_init, self.pool.ts_init, );
847
848 Ok(event)
849 }
850
851 pub fn process_burn(&mut self, update: &PoolLiquidityUpdate) -> anyhow::Result<()> {
863 self.check_if_initialized(PoolEventKind::Burn)?;
864
865 if self.check_if_already_processed(update.block, update.transaction_index, update.log_index)
866 {
867 return Ok(());
868 }
869
870 self.validate_ticks(update.tick_lower, update.tick_upper)?;
871
872 let liquidity_delta = i128::try_from(update.position_liquidity).map_err(|_| {
874 anyhow::anyhow!("Liquidity {} exceeds i128::MAX", update.position_liquidity)
875 })?;
876 let location = self.event_location(
877 PoolEventKind::Burn,
878 update.block,
879 update.transaction_index,
880 update.log_index,
881 );
882
883 self.update_position(
884 &update.owner,
885 update.tick_lower,
886 update.tick_upper,
887 -liquidity_delta,
888 update.amount0,
889 update.amount1,
890 )
891 .map_err(|e| Self::wrap_liquidity_error(e, location))?;
892
893 self.analytics.total_burns += 1;
894 self.last_processed_event = Some(
895 BlockPosition::new(
896 update.block,
897 update.transaction_hash.clone(),
898 update.transaction_index,
899 update.log_index,
900 )
901 .with_block_hash(update.block_hash.clone()),
902 );
903 self.last_processed_ts = Some(update.ts_event);
904 self.update_reporter_if_enabled(update.block);
905 self.update_liquidity_analytics();
906
907 Ok(())
908 }
909
910 pub fn execute_burn(
923 &mut self,
924 recipient: Address,
925 block: BlockPosition,
926 tick_lower: i32,
927 tick_upper: i32,
928 liquidity: u128,
929 ) -> anyhow::Result<PoolLiquidityUpdate> {
930 self.check_if_initialized(PoolEventKind::Burn)?;
931
932 self.validate_ticks(tick_lower, tick_upper)?;
933 let (amount0, amount1) = get_amounts_for_liquidity(
934 self.state.price_sqrt_ratio_x96,
935 tick_lower,
936 tick_upper,
937 liquidity,
938 false,
939 );
940
941 let liquidity_delta = i128::try_from(liquidity)
943 .map_err(|_| anyhow::anyhow!("Liquidity {liquidity} exceeds i128::MAX"))?;
944 self.update_position(
945 &recipient,
946 tick_lower,
947 tick_upper,
948 -liquidity_delta,
949 amount0,
950 amount1,
951 )?;
952
953 self.analytics.total_burns += 1;
954
955 let event = PoolLiquidityUpdate::new(
956 Arc::clone(&self.pool.chain),
957 Arc::clone(&self.pool.dex),
958 self.pool.instrument_id,
959 self.pool.pool_identifier,
960 PoolLiquidityUpdateType::Burn,
961 block.number,
962 block.transaction_hash,
963 block.transaction_index,
964 block.log_index,
965 None,
966 recipient,
967 liquidity,
968 amount0,
969 amount1,
970 tick_lower,
971 tick_upper,
972 self.pool.ts_init, self.pool.ts_init, );
975
976 Ok(event)
977 }
978
979 pub fn process_collect(&mut self, collect: &PoolFeeCollect) -> anyhow::Result<()> {
992 self.check_if_initialized(PoolEventKind::Collect)?;
993
994 if self.check_if_already_processed(
995 collect.block,
996 collect.transaction_index,
997 collect.log_index,
998 ) {
999 return Ok(());
1000 }
1001 let position_key =
1002 PoolPosition::get_position_key(&collect.owner, collect.tick_lower, collect.tick_upper);
1003
1004 if let Some(position) = self.positions.get_mut(&position_key) {
1005 position.collect_fees(collect.amount0, collect.amount1);
1006 }
1007
1008 self.cleanup_position_if_empty(&position_key);
1010
1011 self.analytics.total_amount0_collected += U256::from(collect.amount0);
1012 self.analytics.total_amount1_collected += U256::from(collect.amount1);
1013
1014 self.analytics.total_fee_collects += 1;
1015 self.last_processed_event = Some(
1016 BlockPosition::new(
1017 collect.block,
1018 collect.transaction_hash.clone(),
1019 collect.transaction_index,
1020 collect.log_index,
1021 )
1022 .with_block_hash(collect.block_hash.clone()),
1023 );
1024 self.last_processed_ts = Some(collect.ts_event);
1025 self.update_reporter_if_enabled(collect.block);
1026 self.update_liquidity_analytics();
1027
1028 Ok(())
1029 }
1030
1031 pub fn process_fee_protocol_update(
1041 &mut self,
1042 update: &PoolFeeProtocolUpdate,
1043 ) -> anyhow::Result<()> {
1044 if self.check_if_already_processed(update.block, update.transaction_index, update.log_index)
1045 {
1046 return Ok(());
1047 }
1048
1049 if update.dex.name == DexType::PancakeSwapV3 {
1050 self.state
1051 .set_protocol_fee_basis_points(update.fee_protocol0_new, update.fee_protocol1_new);
1052 } else {
1053 let fee_protocol = update
1054 .uniswap_v3_packed()
1055 .ok_or_else(|| anyhow::anyhow!("invalid Uniswap V3 fee protocol update"))?;
1056 self.state.set_uniswap_v3_fee_protocol(fee_protocol);
1057 }
1058
1059 self.last_processed_event = Some(
1060 BlockPosition::new(
1061 update.block,
1062 update.transaction_hash.clone(),
1063 update.transaction_index,
1064 update.log_index,
1065 )
1066 .with_block_hash(update.block_hash.clone()),
1067 );
1068 self.last_processed_ts = Some(update.ts_event);
1069 self.update_reporter_if_enabled(update.block);
1070
1071 Ok(())
1072 }
1073
1074 #[allow(
1084 clippy::missing_errors_doc,
1085 reason = "protocol fee collection only updates in-memory state"
1086 )]
1087 pub fn process_fee_protocol_collect(
1088 &mut self,
1089 collect: &PoolFeeProtocolCollect,
1090 ) -> anyhow::Result<()> {
1091 if self.check_if_already_processed(
1092 collect.block,
1093 collect.transaction_index,
1094 collect.log_index,
1095 ) {
1096 return Ok(());
1097 }
1098
1099 self.state.protocol_fees_token0 = self
1100 .state
1101 .protocol_fees_token0
1102 .saturating_sub(U256::from(collect.amount0));
1103 self.state.protocol_fees_token1 = self
1104 .state
1105 .protocol_fees_token1
1106 .saturating_sub(U256::from(collect.amount1));
1107
1108 self.last_processed_event = Some(
1109 BlockPosition::new(
1110 collect.block,
1111 collect.transaction_hash.clone(),
1112 collect.transaction_index,
1113 collect.log_index,
1114 )
1115 .with_block_hash(collect.block_hash.clone()),
1116 );
1117 self.last_processed_ts = Some(collect.ts_event);
1118 self.update_reporter_if_enabled(collect.block);
1119
1120 Ok(())
1121 }
1122
1123 pub fn process_flash(&mut self, flash: &PoolFlash) -> anyhow::Result<()> {
1131 self.check_if_initialized(PoolEventKind::Flash)?;
1132
1133 if self.check_if_already_processed(flash.block, flash.transaction_index, flash.log_index) {
1134 return Ok(());
1135 }
1136
1137 self.update_flash_state(flash.paid0, flash.paid1)?;
1138
1139 self.analytics.total_flashes += 1;
1140 self.last_processed_event = Some(
1141 BlockPosition::new(
1142 flash.block,
1143 flash.transaction_hash.clone(),
1144 flash.transaction_index,
1145 flash.log_index,
1146 )
1147 .with_block_hash(flash.block_hash.clone()),
1148 );
1149 self.last_processed_ts = Some(flash.ts_event);
1150 self.update_reporter_if_enabled(flash.block);
1151 self.update_liquidity_analytics();
1152
1153 Ok(())
1154 }
1155
1156 pub fn execute_flash(
1169 &mut self,
1170 sender: Address,
1171 recipient: Address,
1172 block: BlockPosition,
1173 amount0: U256,
1174 amount1: U256,
1175 ) -> anyhow::Result<PoolFlash> {
1176 self.check_if_initialized(PoolEventKind::Flash)?;
1177
1178 let fee_tier = self.pool.fee.expect("Pool fee should be initialized");
1179
1180 let paid0 = if amount0 > U256::ZERO {
1182 FullMath::mul_div_rounding_up(amount0, U256::from(fee_tier), U256::from(1_000_000))?
1183 } else {
1184 U256::ZERO
1185 };
1186
1187 let paid1 = if amount1 > U256::ZERO {
1188 FullMath::mul_div_rounding_up(amount1, U256::from(fee_tier), U256::from(1_000_000))?
1189 } else {
1190 U256::ZERO
1191 };
1192
1193 self.update_flash_state(paid0, paid1)?;
1194 self.analytics.total_flashes += 1;
1195
1196 let flash_event = PoolFlash::new(
1197 Arc::clone(&self.pool.chain),
1198 Arc::clone(&self.pool.dex),
1199 self.pool.instrument_id,
1200 self.pool.pool_identifier,
1201 block.number,
1202 block.transaction_hash,
1203 block.transaction_index,
1204 block.log_index,
1205 self.pool.ts_init, self.pool.ts_init, sender,
1208 recipient,
1209 amount0,
1210 amount1,
1211 paid0,
1212 paid1,
1213 );
1214
1215 Ok(flash_event)
1216 }
1217
1218 fn update_flash_state(&mut self, paid0: U256, paid1: U256) -> anyhow::Result<()> {
1226 let liquidity = self.tick_map.liquidity;
1227 if liquidity == 0 {
1228 anyhow::bail!("No liquidity")
1229 }
1230
1231 let fee_protocol_0 = self.state.uniswap_v3_fee_protocol(true);
1232 let fee_protocol_1 = self.state.uniswap_v3_fee_protocol(false);
1233 let fee_protocol0_basis_points = self.state.fee_protocol_basis_points(true);
1234 let fee_protocol1_basis_points = self.state.fee_protocol_basis_points(false);
1235
1236 if paid0 > U256::ZERO {
1238 let protocol_fee_0 =
1239 Self::protocol_fee_delta(paid0, fee_protocol_0, fee_protocol0_basis_points)?;
1240
1241 if protocol_fee_0 > U256::ZERO {
1242 self.state.protocol_fees_token0 += protocol_fee_0;
1243 }
1244
1245 let lp_fee_0 = paid0 - protocol_fee_0;
1246 let delta = FullMath::mul_div(lp_fee_0, Q128, U256::from(liquidity))?;
1247 self.state.fee_growth_global_0 += delta;
1248 }
1249
1250 if paid1 > U256::ZERO {
1252 let protocol_fee_1 =
1253 Self::protocol_fee_delta(paid1, fee_protocol_1, fee_protocol1_basis_points)?;
1254
1255 if protocol_fee_1 > U256::ZERO {
1256 self.state.protocol_fees_token1 += protocol_fee_1;
1257 }
1258
1259 let lp_fee_1 = paid1 - protocol_fee_1;
1260 let delta = FullMath::mul_div(lp_fee_1, Q128, U256::from(liquidity))?;
1261 self.state.fee_growth_global_1 += delta;
1262 }
1263
1264 Ok(())
1265 }
1266
1267 fn protocol_fee_delta(
1268 fee_amount: U256,
1269 uniswap_v3_fee_protocol: u8,
1270 fee_protocol_basis_points: Option<u32>,
1271 ) -> anyhow::Result<U256> {
1272 if let Some(basis_points) = fee_protocol_basis_points {
1273 return FullMath::mul_div(
1274 fee_amount,
1275 U256::from(basis_points),
1276 U256::from(PROTOCOL_FEE_BASIS_POINTS_DENOMINATOR),
1277 );
1278 }
1279
1280 if uniswap_v3_fee_protocol > 0 {
1281 Ok(fee_amount / U256::from(uniswap_v3_fee_protocol))
1282 } else {
1283 Ok(U256::ZERO)
1284 }
1285 }
1286
1287 fn update_position(
1292 &mut self,
1293 owner: &Address,
1294 tick_lower: i32,
1295 tick_upper: i32,
1296 liquidity_delta: i128,
1297 amount0: U256,
1298 amount1: U256,
1299 ) -> anyhow::Result<()> {
1300 let current_tick = self.state.current_tick;
1301 let position_key = PoolPosition::get_position_key(owner, tick_lower, tick_upper);
1302
1303 let new_active_liquidity =
1304 self.validate_position_update(&position_key, tick_lower, tick_upper, liquidity_delta)?;
1305
1306 let position = self
1307 .positions
1308 .entry(position_key)
1309 .or_insert(PoolPosition::new(*owner, tick_lower, tick_upper, 0));
1310
1311 let flipped_lower = self.tick_map.update(
1313 tick_lower,
1314 current_tick,
1315 liquidity_delta,
1316 false,
1317 self.state.fee_growth_global_0,
1318 self.state.fee_growth_global_1,
1319 );
1320 let flipped_upper = self.tick_map.update(
1321 tick_upper,
1322 current_tick,
1323 liquidity_delta,
1324 true,
1325 self.state.fee_growth_global_0,
1326 self.state.fee_growth_global_1,
1327 );
1328
1329 let (fee_growth_inside_0, fee_growth_inside_1) = self.tick_map.get_fee_growth_inside(
1330 tick_lower,
1331 tick_upper,
1332 current_tick,
1333 self.state.fee_growth_global_0,
1334 self.state.fee_growth_global_1,
1335 );
1336 position.update_fees(fee_growth_inside_0, fee_growth_inside_1);
1337 position.update_liquidity(liquidity_delta);
1338 position.update_amounts(liquidity_delta, amount0, amount1);
1339
1340 if let Some(active_liquidity) = new_active_liquidity {
1341 self.tick_map.liquidity = active_liquidity;
1342 }
1343
1344 if liquidity_delta < 0 && flipped_lower {
1346 self.tick_map.clear(tick_lower);
1347 }
1348
1349 if liquidity_delta < 0 && flipped_upper {
1350 self.tick_map.clear(tick_upper);
1351 }
1352
1353 Ok(())
1354 }
1355
1356 fn cleanup_position_if_empty(&mut self, position_key: &str) {
1360 if let Some(position) = self.positions.get(position_key)
1361 && position.is_empty()
1362 {
1363 log::debug!(
1364 "CLEANING UP EMPTY POSITION: owner={}, ticks=[{}, {}]",
1365 position.owner,
1366 position.tick_lower,
1367 position.tick_upper,
1368 );
1369 self.positions.remove(position_key);
1370 }
1371 }
1372
1373 #[must_use]
1381 pub fn liquidity_utilization_rate(&self) -> f64 {
1382 const PRECISION: u32 = 1_000_000; let total_liquidity = self.get_total_liquidity();
1385 let active_liquidity = self.get_active_liquidity();
1386
1387 if total_liquidity == U256::ZERO {
1388 return 0.0;
1389 }
1390 let ratio = FullMath::mul_div(
1391 U256::from(active_liquidity),
1392 U256::from(PRECISION),
1393 total_liquidity,
1394 )
1395 .unwrap_or(U256::ZERO);
1396
1397 f64::from(ratio) / f64::from(PRECISION)
1398 }
1399
1400 fn validate_ticks(&self, tick_lower: i32, tick_upper: i32) -> anyhow::Result<()> {
1412 if tick_lower >= tick_upper {
1413 anyhow::bail!("Invalid tick range: {tick_lower} >= {tick_upper}")
1414 }
1415
1416 if tick_lower % self.pool.tick_spacing.unwrap() as i32 != 0
1417 || tick_upper % self.pool.tick_spacing.unwrap() as i32 != 0
1418 {
1419 anyhow::bail!(
1420 "Ticks {tick_lower} and {tick_upper} must be multiples of the tick spacing"
1421 )
1422 }
1423
1424 if tick_lower < PoolTick::MIN_TICK || tick_upper > PoolTick::MAX_TICK {
1425 anyhow::bail!("Invalid tick bounds for {tick_lower} and {tick_upper}");
1426 }
1427 Ok(())
1428 }
1429
1430 fn update_liquidity_analytics(&mut self) {
1432 self.analytics.liquidity_utilization_rate = self.liquidity_utilization_rate();
1433 }
1434
1435 #[must_use]
1444 pub fn get_active_liquidity(&self) -> u128 {
1445 self.tick_map.liquidity
1446 }
1447
1448 #[must_use]
1454 pub fn get_total_liquidity_from_active_positions(&self) -> u128 {
1455 self.positions
1456 .values()
1457 .filter(|position| {
1458 position.liquidity > 0
1459 && position.tick_lower <= self.state.current_tick
1460 && self.state.current_tick < position.tick_upper
1461 })
1462 .map(|position| position.liquidity)
1463 .sum()
1464 }
1465
1466 #[must_use]
1468 pub fn get_total_liquidity(&self) -> U256 {
1469 self.positions
1470 .values()
1471 .map(|position| U256::from(position.liquidity))
1472 .fold(U256::ZERO, |acc, liq| acc + liq)
1473 }
1474
1475 pub fn restore_from_snapshot(&mut self, snapshot: PoolSnapshot) -> anyhow::Result<()> {
1489 let liquidity = snapshot.state.liquidity;
1490
1491 self.state = snapshot.state;
1493
1494 self.analytics.total_amount0_deposited = snapshot.analytics.total_amount0_deposited;
1496 self.analytics.total_amount1_deposited = snapshot.analytics.total_amount1_deposited;
1497 self.analytics.total_amount0_collected = snapshot.analytics.total_amount0_collected;
1498 self.analytics.total_amount1_collected = snapshot.analytics.total_amount1_collected;
1499 self.analytics.total_swaps = snapshot.analytics.total_swaps;
1500 self.analytics.total_mints = snapshot.analytics.total_mints;
1501 self.analytics.total_burns = snapshot.analytics.total_burns;
1502 self.analytics.total_fee_collects = snapshot.analytics.total_fee_collects;
1503 self.analytics.total_flashes = snapshot.analytics.total_flashes;
1504
1505 self.positions.clear();
1507 for position in snapshot.positions {
1508 let key = PoolPosition::get_position_key(
1509 &position.owner,
1510 position.tick_lower,
1511 position.tick_upper,
1512 );
1513 self.positions.insert(key, position);
1514 }
1515
1516 self.tick_map = TickMap::new(
1518 self.pool
1519 .tick_spacing
1520 .expect("Pool tick spacing must be set"),
1521 );
1522
1523 for tick in snapshot.ticks {
1524 self.tick_map.restore_tick(tick);
1525 }
1526
1527 self.tick_map.liquidity = liquidity;
1529
1530 self.last_processed_event = Some(snapshot.block_position);
1532 self.last_processed_ts = Some(snapshot.ts_event);
1533
1534 self.is_initialized = true;
1536
1537 self.update_liquidity_analytics();
1539
1540 Ok(())
1541 }
1542
1543 #[must_use]
1548 pub fn get_active_tick_values(&self) -> Vec<i32> {
1549 self.tick_map
1550 .get_all_ticks()
1551 .iter()
1552 .filter(|(_, tick)| self.tick_map.is_tick_initialized(tick.value))
1553 .map(|(tick_value, _)| *tick_value)
1554 .collect()
1555 }
1556
1557 #[must_use]
1559 pub fn get_active_tick_count(&self) -> usize {
1560 self.tick_map.active_tick_count()
1561 }
1562
1563 #[must_use]
1568 pub fn get_tick(&self, tick: i32) -> Option<&PoolTick> {
1569 self.tick_map.get_tick(tick)
1570 }
1571
1572 #[must_use]
1577 pub fn get_current_tick(&self) -> i32 {
1578 self.state.current_tick
1579 }
1580
1581 #[must_use]
1589 pub fn get_total_tick_count(&self) -> usize {
1590 self.tick_map.total_tick_count()
1591 }
1592
1593 #[must_use]
1598 pub fn get_position(
1599 &self,
1600 owner: &Address,
1601 tick_lower: i32,
1602 tick_upper: i32,
1603 ) -> Option<&PoolPosition> {
1604 let position_key = PoolPosition::get_position_key(owner, tick_lower, tick_upper);
1605 self.positions.get(&position_key)
1606 }
1607
1608 #[must_use]
1618 pub fn get_active_positions(&self) -> Vec<&PoolPosition> {
1619 self.positions
1620 .values()
1621 .filter(|position| {
1622 let current_tick = self.get_current_tick();
1623 position.liquidity > 0
1624 && position.tick_lower <= current_tick
1625 && current_tick < position.tick_upper
1626 })
1627 .collect()
1628 }
1629
1630 #[must_use]
1639 pub fn get_all_positions(&self) -> Vec<&PoolPosition> {
1640 self.positions.values().collect()
1641 }
1642
1643 #[must_use]
1645 pub fn get_all_position_keys(&self) -> Vec<(Address, i32, i32)> {
1646 self.get_all_positions()
1647 .iter()
1648 .map(|position| (position.owner, position.tick_lower, position.tick_upper))
1649 .collect()
1650 }
1651
1652 pub fn extract_snapshot(&self) -> anyhow::Result<PoolSnapshot> {
1664 let positions: Vec<_> = self.positions.values().cloned().collect();
1665 let ticks: Vec<_> = self.tick_map.get_all_ticks().values().copied().collect();
1666
1667 let mut state = self.state.clone();
1668 state.liquidity = self.tick_map.liquidity;
1669
1670 let last_processed_event = self
1671 .last_processed_event
1672 .clone()
1673 .ok_or_else(|| anyhow::anyhow!("Cannot extract snapshot: no events processed yet"))?;
1674
1675 Ok(PoolSnapshot::new(
1676 self.pool.instrument_id,
1677 state,
1678 positions,
1679 ticks,
1680 self.analytics.clone(),
1681 last_processed_event,
1682 self.last_processed_ts.unwrap_or(self.pool.ts_init), self.last_processed_ts.unwrap_or(self.pool.ts_init), ))
1685 }
1686
1687 #[must_use]
1692 pub fn get_total_active_positions(&self) -> usize {
1693 self.positions
1694 .iter()
1695 .filter(|(_, position)| {
1696 let current_tick = self.get_current_tick();
1697 position.liquidity > 0
1698 && position.tick_lower <= current_tick
1699 && current_tick < position.tick_upper
1700 })
1701 .count()
1702 }
1703
1704 #[must_use]
1709 pub fn get_total_inactive_positions(&self) -> usize {
1710 self.positions.len() - self.get_total_active_positions()
1711 }
1712
1713 #[must_use]
1720 pub fn estimate_balance_of_token0(&self) -> U256 {
1721 let mut total_amount0 = U256::ZERO;
1722 let current_sqrt_price = self.state.price_sqrt_ratio_x96;
1723 let current_tick = self.state.current_tick;
1724
1725 for position in self.positions.values() {
1727 if position.liquidity == 0 || position.tick_upper <= current_tick {
1729 continue;
1730 }
1731
1732 if position.tick_lower > current_tick {
1733 let sqrt_ratio_a = get_sqrt_ratio_at_tick(position.tick_lower);
1735 let sqrt_ratio_b = get_sqrt_ratio_at_tick(position.tick_upper);
1736 let amount0 =
1737 get_amount0_delta(sqrt_ratio_a, sqrt_ratio_b, position.liquidity, true);
1738 total_amount0 += amount0;
1739 } else {
1740 let sqrt_ratio_upper = get_sqrt_ratio_at_tick(position.tick_upper);
1742 let amount0 = get_amount0_delta(
1743 current_sqrt_price,
1744 sqrt_ratio_upper,
1745 position.liquidity,
1746 true,
1747 );
1748 total_amount0 += amount0;
1749 }
1750 }
1751
1752 let fee_growth_0 = self.state.fee_growth_global_0;
1756 if fee_growth_0 > U256::ZERO {
1757 let active_liquidity = self.get_active_liquidity();
1760 if active_liquidity > 0 {
1761 if let Ok(total_fees_0) =
1764 FullMath::mul_div(fee_growth_0, U256::from(active_liquidity), Q128)
1765 {
1766 total_amount0 += total_fees_0;
1767 }
1768 }
1769 }
1770
1771 total_amount0 += self.state.protocol_fees_token0;
1773
1774 total_amount0
1775 }
1776
1777 #[must_use]
1784 pub fn estimate_balance_of_token1(&self) -> U256 {
1785 let mut total_amount1 = U256::ZERO;
1786 let current_sqrt_price = self.state.price_sqrt_ratio_x96;
1787 let current_tick = self.state.current_tick;
1788
1789 for position in self.positions.values() {
1791 if position.liquidity == 0 || position.tick_lower > current_tick {
1793 continue;
1794 }
1795
1796 if position.tick_upper <= current_tick {
1797 let sqrt_ratio_a = get_sqrt_ratio_at_tick(position.tick_lower);
1799 let sqrt_ratio_b = get_sqrt_ratio_at_tick(position.tick_upper);
1800 let amount1 =
1801 get_amount1_delta(sqrt_ratio_a, sqrt_ratio_b, position.liquidity, true);
1802 total_amount1 += amount1;
1803 } else {
1804 let sqrt_ratio_lower = get_sqrt_ratio_at_tick(position.tick_lower);
1806 let amount1 = get_amount1_delta(
1807 sqrt_ratio_lower,
1808 current_sqrt_price,
1809 position.liquidity,
1810 true,
1811 );
1812 total_amount1 += amount1;
1813 }
1814 }
1815
1816 let fee_growth_1 = self.state.fee_growth_global_1;
1818 if fee_growth_1 > U256::ZERO {
1819 let active_liquidity = self.get_active_liquidity();
1820 if active_liquidity > 0 {
1821 if let Ok(total_fees_1) =
1823 FullMath::mul_div(fee_growth_1, U256::from(active_liquidity), Q128)
1824 {
1825 total_amount1 += total_fees_1;
1826 }
1827 }
1828 }
1829
1830 total_amount1 += self.state.protocol_fees_token1;
1832
1833 total_amount1
1834 }
1835
1836 pub fn set_fee_growth_global(&mut self, fee_growth_global_0: U256, fee_growth_global_1: U256) {
1845 self.state.fee_growth_global_0 = fee_growth_global_0;
1846 self.state.fee_growth_global_1 = fee_growth_global_1;
1847 }
1848
1849 #[must_use]
1851 pub fn get_total_events(&self) -> u64 {
1852 self.analytics.total_swaps
1853 + self.analytics.total_mints
1854 + self.analytics.total_burns
1855 + self.analytics.total_fee_collects
1856 + self.analytics.total_flashes
1857 }
1858
1859 pub fn enable_reporting(&mut self, from_block: u64, total_blocks: u64, update_interval: u64) {
1864 self.reporter = Some(BlockchainSyncReporter::new(
1865 BlockchainSyncReportItems::PoolProfiling,
1866 from_block,
1867 total_blocks,
1868 update_interval,
1869 ));
1870 self.last_reported_block = from_block;
1871 }
1872
1873 pub fn finalize_reporting(&mut self) {
1878 if let Some(reporter) = &self.reporter {
1879 reporter.log_final_stats();
1880 }
1881 self.reporter = None;
1882 }
1883}
1884
1885impl PoolProfiler {
1886 fn validate_swap_replay(
1887 &self,
1888 swap: &PoolSwap,
1889 swap_quote: &SwapQuote,
1890 location: PoolEventLocation,
1891 ) -> anyhow::Result<()> {
1892 let tick_mismatch = swap.tick != swap_quote.tick_after;
1893 let liquidity_mismatch = swap.liquidity != swap_quote.liquidity_after;
1894 let structural_mismatch = tick_mismatch || liquidity_mismatch;
1895
1896 let anchoring_crossed_tick = if tick_mismatch {
1897 self.tick_map
1898 .get_all_ticks()
1899 .keys()
1900 .copied()
1901 .filter(|&tick| {
1902 self.tick_map.is_tick_initialized(tick)
1903 && (swap_quote.tick_after >= tick) != (swap.tick >= tick)
1904 })
1905 .min()
1906 } else {
1907 None
1908 };
1909
1910 if structural_mismatch
1911 && (!swap_quote.crossed_ticks.is_empty() || anchoring_crossed_tick.is_some())
1912 {
1913 return Err(PoolProfilerError::SwapReplayMismatch {
1914 location,
1915 simulated_tick: swap_quote.tick_after,
1916 event_tick: swap.tick,
1917 simulated_liquidity: swap_quote.liquidity_after,
1918 event_liquidity: swap.liquidity,
1919 simulated_crossed_tick_count: swap_quote.crossed_ticks.len(),
1920 anchoring_crossed_tick,
1921 }
1922 .into());
1923 }
1924
1925 Ok(())
1926 }
1927
1928 fn apply_swap_event(&mut self, swap: &PoolSwap, swap_quote: &SwapQuote) {
1929 let tick_mismatch = swap.tick != swap_quote.tick_after;
1930 let liquidity_mismatch = swap.liquidity != swap_quote.liquidity_after;
1931 let sqrt_mismatch = swap.sqrt_price_x96 != swap_quote.sqrt_price_after_x96;
1932 self.apply_swap_quote(swap_quote);
1933
1934 if tick_mismatch {
1936 log::warn!(
1937 "Inconsistency in swap processing: Current tick mismatch: simulated {}, event {} on block {}",
1938 swap_quote.tick_after,
1939 swap.tick,
1940 swap.block
1941 );
1942 }
1943
1944 if swap.tick != self.state.current_tick {
1945 self.state.current_tick = swap.tick;
1946 }
1947
1948 if liquidity_mismatch {
1949 log::warn!(
1950 "Inconsistency in swap processing: Active liquidity mismatch: simulated {}, event {} on block {}",
1951 swap_quote.liquidity_after,
1952 swap.liquidity,
1953 swap.block
1954 );
1955 }
1956
1957 if swap.liquidity != self.tick_map.liquidity {
1958 self.tick_map.liquidity = swap.liquidity;
1959 }
1960
1961 if sqrt_mismatch {
1962 log::warn!(
1963 "Inconsistency in swap processing: Sqrt price mismatch: simulated {}, event {} on block {}",
1964 swap_quote.sqrt_price_after_x96,
1965 swap.sqrt_price_x96,
1966 swap.block
1967 );
1968 }
1969
1970 if swap.sqrt_price_x96 != self.state.price_sqrt_ratio_x96 {
1971 self.state.price_sqrt_ratio_x96 = swap.sqrt_price_x96;
1972 }
1973
1974 self.last_processed_event = Some(
1975 BlockPosition::new(
1976 swap.block,
1977 swap.transaction_hash.clone(),
1978 swap.transaction_index,
1979 swap.log_index,
1980 )
1981 .with_block_hash(swap.block_hash.clone()),
1982 );
1983 self.last_processed_ts = Some(swap.ts_event);
1984 self.update_reporter_if_enabled(swap.block);
1985 self.update_liquidity_analytics();
1986 }
1987
1988 fn validate_position_update(
1989 &self,
1990 position_key: &str,
1991 tick_lower: i32,
1992 tick_upper: i32,
1993 liquidity_delta: i128,
1994 ) -> anyhow::Result<Option<u128>> {
1995 let current_tick = self.state.current_tick;
1996
1997 if liquidity_delta < 0 {
1999 let position_liquidity = self
2000 .positions
2001 .get(position_key)
2002 .map_or(0, |position| position.liquidity);
2003 let burn_amount = liquidity_delta.unsigned_abs();
2004 if position_liquidity < burn_amount {
2005 anyhow::bail!(
2006 "Position liquidity {position_liquidity} is less than the requested burn amount of {burn_amount}"
2007 );
2008 }
2009 }
2010
2011 let new_active_liquidity = if tick_lower <= current_tick && current_tick < tick_upper {
2014 Some(try_liquidity_math_add(
2015 self.tick_map.liquidity,
2016 liquidity_delta,
2017 )?)
2018 } else {
2019 None
2020 };
2021
2022 for tick_value in [tick_lower, tick_upper] {
2023 let liquidity_gross = self
2024 .tick_map
2025 .get_tick(tick_value)
2026 .map_or(0, |tick| tick.liquidity_gross);
2027 let liquidity_after = try_liquidity_math_add(liquidity_gross, liquidity_delta)?;
2028 if liquidity_after > self.tick_map.max_liquidity_per_tick {
2029 anyhow::bail!(
2030 "Liquidity {liquidity_after} exceeds maximum per tick {} at tick {tick_value}",
2031 self.tick_map.max_liquidity_per_tick,
2032 );
2033 }
2034 }
2035
2036 Ok(new_active_liquidity)
2037 }
2038}
2039
2040struct SwapSimulation<'a> {
2041 profiler: &'a PoolProfiler,
2042 amount_specified: I256,
2043 zero_for_one: bool,
2044 sqrt_price_limit_x96: U160,
2045 traverse_empty_ranges: bool,
2046 exact_input: bool,
2047 fee_tier: u32,
2048 fee_protocol: u8,
2049 fee_protocol_basis_points: Option<u32>,
2050 current_sqrt_price: U160,
2051 current_tick: i32,
2052 current_active_liquidity: u128,
2053 amount_specified_remaining: I256,
2054 amount_calculated: I256,
2055 protocol_fee: U256,
2056 lp_fee: U256,
2057 crossed_ticks: Vec<CrossedTick>,
2058 current_fee_growth_global: U256,
2059}
2060
2061impl<'a> SwapSimulation<'a> {
2062 fn new(
2063 profiler: &'a PoolProfiler,
2064 amount_specified: I256,
2065 zero_for_one: bool,
2066 sqrt_price_limit_x96: U160,
2067 traverse_empty_ranges: bool,
2068 ) -> Self {
2069 let exact_input = amount_specified.is_positive();
2070 let fee_tier = profiler.pool.fee.expect("Pool fee should be initialized");
2071 Self {
2072 profiler,
2073 amount_specified,
2074 zero_for_one,
2075 sqrt_price_limit_x96,
2076 traverse_empty_ranges,
2077 exact_input,
2078 fee_tier,
2079 fee_protocol: profiler.state.uniswap_v3_fee_protocol(zero_for_one),
2080 fee_protocol_basis_points: profiler.state.fee_protocol_basis_points(zero_for_one),
2081 current_sqrt_price: profiler.state.price_sqrt_ratio_x96,
2082 current_tick: profiler.state.current_tick,
2083 current_active_liquidity: profiler.tick_map.liquidity,
2084 amount_specified_remaining: amount_specified,
2085 amount_calculated: I256::ZERO,
2086 protocol_fee: U256::ZERO,
2087 lp_fee: U256::ZERO,
2088 crossed_ticks: Vec::new(),
2089 current_fee_growth_global: if zero_for_one {
2090 profiler.state.fee_growth_global_0
2091 } else {
2092 profiler.state.fee_growth_global_1
2093 },
2094 }
2095 }
2096
2097 fn run(mut self) -> anyhow::Result<SwapQuote> {
2098 while self.should_continue() {
2099 self.advance()?;
2100 }
2101
2102 Ok(self.into_quote())
2103 }
2104
2105 fn should_continue(&self) -> bool {
2106 (self.amount_specified_remaining != I256::ZERO
2108 || (self.traverse_empty_ranges && self.current_active_liquidity == 0))
2109 && (self.sqrt_price_limit_x96 != self.current_sqrt_price
2110 || (self.replays_exact_input() && self.amount_specified_remaining.is_positive()))
2111 }
2112
2113 fn replays_exact_input(&self) -> bool {
2116 self.traverse_empty_ranges && self.exact_input
2117 }
2118
2119 fn advance(&mut self) -> anyhow::Result<()> {
2120 let iteration_start = (
2121 self.current_sqrt_price,
2122 self.current_tick,
2123 self.amount_specified_remaining,
2124 );
2125
2126 let sqrt_price_start_x96 = self.current_sqrt_price;
2127
2128 let (mut tick_next, initialized) = self
2129 .profiler
2130 .tick_map
2131 .next_initialized_tick(self.current_tick, self.zero_for_one);
2132
2133 tick_next = tick_next.clamp(PoolTick::MIN_TICK, PoolTick::MAX_TICK);
2135
2136 let sqrt_price_next = get_sqrt_ratio_at_tick(tick_next);
2138
2139 let sqrt_price_target = if (self.zero_for_one
2141 && sqrt_price_next < self.sqrt_price_limit_x96)
2142 || (!self.zero_for_one && sqrt_price_next > self.sqrt_price_limit_x96)
2143 {
2144 self.sqrt_price_limit_x96
2145 } else {
2146 sqrt_price_next
2147 };
2148
2149 let mut swap_step_result = compute_swap_step(
2150 self.current_sqrt_price,
2151 sqrt_price_target,
2152 self.current_active_liquidity,
2153 self.amount_specified_remaining,
2154 self.fee_tier,
2155 )?;
2156
2157 if self.replays_exact_input()
2160 && swap_step_result.sqrt_ratio_next_x96 == self.sqrt_price_limit_x96
2161 && swap_step_result.sqrt_ratio_next_x96 != sqrt_price_next
2162 {
2163 swap_step_result.fee_amount =
2164 self.amount_specified_remaining.into_raw() - swap_step_result.amount_in;
2165 }
2166
2167 self.current_sqrt_price = swap_step_result.sqrt_ratio_next_x96;
2169
2170 self.update_amounts(&swap_step_result);
2171 self.accrue_fees(swap_step_result.fee_amount)?;
2173 self.advance_tick(
2174 tick_next,
2175 initialized,
2176 sqrt_price_next,
2177 sqrt_price_start_x96,
2178 )?;
2179
2180 if (
2181 self.current_sqrt_price,
2182 self.current_tick,
2183 self.amount_specified_remaining,
2184 ) == iteration_start
2185 {
2186 anyhow::bail!(
2187 "Swap simulation made no progress at tick {} with sqrt price \
2188 {} and remaining amount {}",
2189 self.current_tick,
2190 self.current_sqrt_price,
2191 self.amount_specified_remaining,
2192 );
2193 }
2194
2195 Ok(())
2196 }
2197
2198 fn update_amounts(&mut self, step: &SwapStepResult) {
2199 if self.exact_input {
2201 self.amount_specified_remaining -=
2203 FullMath::truncate_to_i256(step.amount_in + step.fee_amount);
2204 self.amount_calculated -= FullMath::truncate_to_i256(step.amount_out);
2205 } else {
2206 self.amount_specified_remaining += FullMath::truncate_to_i256(step.amount_out);
2208 self.amount_calculated += FullMath::truncate_to_i256(step.amount_in + step.fee_amount);
2209 }
2210 }
2211
2212 fn accrue_fees(&mut self, fee_amount: U256) -> anyhow::Result<()> {
2213 let mut step_fee_amount = fee_amount;
2215
2216 if self.fee_protocol > 0 || self.fee_protocol_basis_points.is_some() {
2217 let protocol_fee_delta = PoolProfiler::protocol_fee_delta(
2218 fee_amount,
2219 self.fee_protocol,
2220 self.fee_protocol_basis_points,
2221 )?;
2222 step_fee_amount -= protocol_fee_delta;
2223 self.protocol_fee += protocol_fee_delta;
2224 }
2225
2226 self.lp_fee += step_fee_amount;
2228
2229 if self.current_active_liquidity > 0 {
2231 let fee_growth_delta = FullMath::mul_div(
2232 step_fee_amount,
2233 Q128,
2234 U256::from(self.current_active_liquidity),
2235 )?;
2236 self.current_fee_growth_global += fee_growth_delta;
2237 }
2238
2239 Ok(())
2240 }
2241
2242 fn advance_tick(
2243 &mut self,
2244 tick_next: i32,
2245 initialized: bool,
2246 sqrt_price_next: U160,
2247 sqrt_price_start_x96: U160,
2248 ) -> anyhow::Result<()> {
2249 if self.current_sqrt_price == sqrt_price_next {
2251 if initialized {
2255 self.cross_tick(tick_next)?;
2256 }
2257
2258 self.current_tick = if self.zero_for_one {
2259 tick_next - 1
2260 } else {
2261 tick_next
2262 };
2263 } else if self.current_sqrt_price != sqrt_price_start_x96 {
2264 self.current_tick = get_tick_at_sqrt_ratio(self.current_sqrt_price);
2267 }
2268
2269 Ok(())
2270 }
2271
2272 fn cross_tick(&mut self, tick_next: i32) -> anyhow::Result<()> {
2273 self.crossed_ticks.push(CrossedTick::new(
2274 tick_next,
2275 self.zero_for_one,
2276 if self.zero_for_one {
2277 self.current_fee_growth_global
2278 } else {
2279 self.profiler.state.fee_growth_global_0
2280 },
2281 if self.zero_for_one {
2282 self.profiler.state.fee_growth_global_1
2283 } else {
2284 self.current_fee_growth_global
2285 },
2286 ));
2287
2288 if let Some(tick_data) = self.profiler.tick_map.get_tick(tick_next) {
2290 let liquidity_net = tick_data.liquidity_net;
2291 self.current_active_liquidity = if self.zero_for_one {
2292 try_liquidity_math_add(self.current_active_liquidity, -liquidity_net)?
2293 } else {
2294 try_liquidity_math_add(self.current_active_liquidity, liquidity_net)?
2295 };
2296 }
2297
2298 Ok(())
2299 }
2300
2301 fn into_quote(self) -> SwapQuote {
2302 let (amount0, amount1) = if self.zero_for_one == self.exact_input {
2304 (
2305 self.amount_specified - self.amount_specified_remaining,
2306 self.amount_calculated,
2307 )
2308 } else {
2309 (
2310 self.amount_calculated,
2311 self.amount_specified - self.amount_specified_remaining,
2312 )
2313 };
2314
2315 SwapQuote::new(
2316 self.profiler.pool.instrument_id,
2317 amount0,
2318 amount1,
2319 self.profiler.state.price_sqrt_ratio_x96,
2320 self.current_sqrt_price,
2321 self.profiler.state.current_tick,
2322 self.current_tick,
2323 self.current_active_liquidity,
2324 self.current_fee_growth_global,
2325 self.lp_fee,
2326 self.protocol_fee,
2327 self.crossed_ticks,
2328 )
2329 }
2330}
2331
2332fn initial_protocol_fee_basis_points(
2333 dex_type: DexType,
2334 pool_fee: Option<u32>,
2335) -> Option<(u32, u32)> {
2336 if dex_type != DexType::PancakeSwapV3 {
2337 return None;
2338 }
2339
2340 let fee_protocol = match pool_fee {
2341 Some(100) => 3_300,
2342 Some(500) => 3_400,
2343 _ => 3_200,
2344 };
2345
2346 Some((fee_protocol, fee_protocol))
2347}