Skip to main content

nautilus_model/defi/pool_analysis/
profiler.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Pool profiling utilities for analyzing DeFi pool event data.
17
18use 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/// A DeFi pool state tracker and event processor for UniswapV3-style AMM pools.
54///
55/// The `PoolProfiler` provides complete pool state management including:
56/// - Liquidity position tracking and management.
57/// - Tick crossing and price movement simulation.
58/// - Fee accumulation and distribution tracking.
59/// - Protocol fee calculation.
60/// - Pool state validation and maintenance.
61///
62/// This profiler can both process historical events and execute new operations,
63/// making it suitable for both backtesting and simulation scenarios.
64///
65/// # Usage
66///
67/// Create a new profiler with a pool definition, initialize it with a starting price,
68/// then either process historical events or execute new pool operations to simulate
69/// trading activity and analyze pool behavior.
70#[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    /// Pool definition.
81    pub pool: SharedPool,
82    /// Position tracking by position key (`owner:tick_lower:tick_upper`).
83    positions: AHashMap<String, PoolPosition>,
84    /// Tick map managing liquidity distribution across price ranges.
85    pub tick_map: TickMap,
86    /// Global pool state including current price, tick, and cumulative flows with fees.
87    pub state: PoolState,
88    /// Analytics counters tracking pool operations and performance metrics.
89    pub analytics: PoolAnalytics,
90    /// The block position of the last processed event.
91    pub last_processed_event: Option<BlockPosition>,
92    /// The event timestamp of the last processed event.
93    pub last_processed_ts: Option<UnixNanos>,
94    /// Flag indicating whether the pool has been initialized with a starting price.
95    pub is_initialized: bool,
96    /// Optional progress reporter for tracking event processing.
97    reporter: Option<BlockchainSyncReporter>,
98    /// The last block number that was reported (used for progress tracking).
99    last_reported_block: u64,
100}
101
102impl PoolProfiler {
103    /// Creates a new [`PoolProfiler`] instance for tracking pool state and events.
104    ///
105    /// # Panics
106    ///
107    /// Panics if the pool's tick spacing is not set.
108    #[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    /// Initializes the pool with a starting price and activates the profiler.
134    ///
135    /// # Errors
136    ///
137    /// Returns an error if the profiler has already been initialized, or if the pool config carries
138    /// an `initial_tick` that disagrees with the tick derived from `price_sqrt_ratio_x96`.
139    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    /// Returns an error if the pool has not been initialized.
171    ///
172    /// # Errors
173    ///
174    /// Returns an error if [`Self::initialize`] or [`Self::restore_from_snapshot`] has not been
175    /// called yet.
176    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    /// Processes a historical pool event and updates internal state.
205    ///
206    /// Handles all types of pool events (swaps, mints, burns, fee collections),
207    /// and updates the profiler's internal state accordingly. This is the main
208    /// entry point for processing historical blockchain events.
209    ///
210    /// # Errors
211    ///
212    /// Returns an error if:
213    /// - Pool is not initialized.
214    /// - Event contains invalid data (tick ranges, amounts).
215    /// - Mathematical operations overflow.
216    /// - Swap replay cannot maintain the initialized tick partition.
217    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    // Checks if we need to skip events at or before the last processed event to prevent double-processing.
246    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    /// Auto-updates reporter if it's enabled.
266    fn update_reporter_if_enabled(&mut self, current_block: u64) {
267        // Auto-update reporter if enabled
268        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    /// Processes a historical swap event from blockchain data.
283    ///
284    /// Replays the swap by simulating it through [`Self::simulate_swap_through_ticks`],
285    /// then verifies the simulation results against the actual event data. Tick and
286    /// liquidity mismatches are corrected only when no simulated crossings occurred
287    /// and anchoring to the event tick preserves the initialized tick partition.
288    /// Otherwise, replay returns an error without changing the profiler. The event price
289    /// serves as the simulation limit, so wrong-side or out-of-bounds event prices also
290    /// return an error without changing the profiler. After a successful simulation, sqrt
291    /// price mismatches are corrected to match the event.
292    ///
293    /// # Use Case
294    ///
295    /// Historical event processing when rebuilding pool state from blockchain events.
296    ///
297    /// # Errors
298    ///
299    /// Returns an error if:
300    /// - Pool initialization checks fail.
301    /// - Swap simulation fails (see [`Self::simulate_swap_through_ticks`] errors).
302    /// - A structural mismatch involves simulated crossings or anchoring across an initialized
303    ///   tick.
304    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        // For price limit use the final sqrt price from swap, which is a
324        // good proxy to price limit
325        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    /// Executes a new simulated swap and returns the resulting event.
342    ///
343    /// This is the public API for forward simulation of swap operations. It delegates
344    /// the core swap mathematics to [`Self::simulate_swap_through_ticks`], then wraps
345    /// the results in a [`PoolSwap`] event structure with full metadata.
346    ///
347    /// # Errors
348    ///
349    /// Returns an error if:
350    /// - Pool metadata is missing or invalid.
351    /// - The price limit is violated.
352    /// - Fee or liquidity calculations overflow.
353    ///
354    /// Propagates failures from [`Self::simulate_swap_through_ticks`].
355    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, // ts_event (simulated; pool init time)
385            self.pool.ts_init, // ts_init
386            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    // panics-doc-ok (transitive via SwapSimulation::new)
398    /// Core **read-only** swap simulation engine implementing `UniswapV3` mathematics.
399    ///
400    /// This method performs a complete swap simulation without modifying pool state,
401    /// working entirely on stack-allocated local copies of state variables. It returns
402    /// a [`SwapQuote`] containing all swap results and profiling data,
403    /// including a complete audit trail of crossed ticks.
404    ///
405    /// # Algorithm Overview
406    ///
407    /// 1. **Iterative price curve traversal**: Walks through liquidity ranges until
408    ///    the input/output amount is exhausted or the price limit is reached
409    /// 2. **Tick crossing tracking**: When crossing initialized tick boundaries, records
410    ///    the crossing in `crossed_ticks` vector with complete state snapshot (tick, direction, fee growth)
411    /// 3. **Local liquidity updates**: Tracks liquidity changes in local variables by reading
412    ///    `liquidity_net` from tick map (read-only, no mutations)
413    /// 4. **Fee calculation**: Splits fees between LPs and protocol, accumulates in local variables
414    /// 5. **Quote assembly**: Returns [`SwapQuote`] with amounts, prices, fees, and crossed tick data
415    ///
416    /// When `traverse_empty_ranges` is set, the walk continues across zero-liquidity ranges
417    /// to `sqrt_price_limit_x96` even after the amount is exhausted. This reproduces a
418    /// historical swap whose recorded amount (the on-chain consumed amount) runs out at the
419    /// last liquid tick before an empty range to the boundary; forward simulation leaves it
420    /// unset so the swap stops where the amount is spent, matching `UniswapV3`. With an exact
421    /// input, it also charges any input left at `sqrt_price_limit_x96` as fee, because the chain
422    /// consumed the recorded amount in full.
423    ///
424    /// # Errors
425    ///
426    /// Returns an error if:
427    /// - The price limit violates the swap direction or protocol bounds.
428    /// - Fee growth arithmetic overflows when scaling by liquidity.
429    /// - Swap step calculations fail.
430    /// - A swap iteration makes no progress: price, tick, and remaining amount are all unchanged.
431    ///
432    /// # Panics
433    ///
434    /// Panics if the pool fee has not been initialized.
435    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    /// Applies a swap quote to the pool state (mutations only, no simulation).
456    ///
457    /// # Panics
458    ///
459    /// Panics if applying a tick-crossing liquidity delta overflows or underflows,
460    /// which indicates internal tick-map inconsistency rather than a recoverable
461    /// replay error.
462    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    /// Wraps a low-level [`LiquidityMathError`](super::error::LiquidityMathError) into a
503    /// [`PoolProfilerError`] carrying the supplied event location, leaving non-liquidity
504    /// errors untouched.
505    #[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    // panics-doc-ok (transitive via simulate_swap_through_ticks)
514    /// Returns a swap quote without modifying pool state.
515    ///
516    /// This method simulates a swap and provides detailed profiling metrics including:
517    /// - Amounts of tokens that would be exchanged
518    /// - Price before and after the swap
519    /// - Fee breakdown (LP fees and protocol fees)
520    /// - List of crossed ticks with state snapshots
521    ///
522    /// # Errors
523    ///
524    /// Returns an error if:
525    /// - The profiler is not initialized or the amount is zero.
526    /// - The price limit violates the swap direction or protocol bounds.
527    /// - Fee growth arithmetic overflows when scaling by liquidity.
528    /// - Swap step calculations fail.
529    /// - A swap iteration makes no progress.
530    ///
531    /// # Panics
532    ///
533    /// Panics if the pool fee has not been initialized.
534    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    /// Simulates an exact input swap (know input amount, calculate output amount).
562    ///
563    /// # Errors
564    /// Returns an error if pool is not initialized, input is zero, or price limit is invalid.
565    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        // Positive = exact input.
572        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    /// Simulates an exact output swap (know output amount, calculate required input amount).
579    ///
580    /// # Errors
581    /// Returns an error if pool is not initialized, output is zero, price limit is invalid, or
582    /// insufficient liquidity exists to fulfill the exact output amount.
583    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        // Negative = exact output.
590        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    /// Simulates a swap to move the pool price down to a target price.
598    ///
599    /// # Errors
600    /// Returns an error if pool is not initialized or price limit is invalid.
601    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    /// Simulates a swap to move the pool price up to a target price.
609    ///
610    /// # Errors
611    /// Returns an error if pool is not initialized or price limit is invalid.
612    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    /// Finds the maximum trade size that produces a target slippage (including fees).
620    ///
621    /// Uses binary search to find the largest trade size that results in slippage
622    /// at or below the target. The method iteratively simulates swaps at different
623    /// sizes until it converges to the optimal size within the specified tolerance.
624    ///
625    /// # Returns
626    /// The maximum trade size (U256) that produces the target slippage
627    ///
628    /// # Errors
629    /// Returns an error if:
630    /// - Impact is zero or exceeds 100% (10000 bps).
631    /// - Pool is not initialized.
632    /// - Swap simulations fail.
633    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    /// Finds the maximum trade size with search diagnostics.
639    /// This is the detailed version of [`Self::size_for_impact_bps`] that returns
640    /// extensive information about the search process.It is useful for debugging,
641    /// monitoring, and analyzing search behavior in production.
642    ///
643    /// # Returns
644    /// Detailed result with size and search diagnostics
645    ///
646    /// # Errors
647    /// Returns an error if:
648    /// - Impact is zero or exceeds 100% (10000 bps).
649    /// - Pool is not initialized.
650    /// - Swap simulations fail.
651    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    /// Validates that the price limit is in the swap direction and strictly inside the
661    /// `(MIN_SQRT_RATIO, MAX_SQRT_RATIO)` range. The current price is valid when `allow_equal` is
662    /// set for direct simulation or replay; otherwise the direction check matches Uniswap V3.
663    ///
664    /// # Errors
665    /// Returns an error if price limit violates swap direction or range constraints.
666    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            // Swapping token0 for token1: price must decrease
674            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            // Swapping token1 for token0: price must increase
687            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    /// Processes a mint (liquidity add) event from historical data.
706    ///
707    /// Updates pool state when liquidity is added to a position, validates ticks,
708    /// and delegates to internal liquidity management methods.
709    ///
710    /// # Errors
711    ///
712    /// Returns an error if:
713    /// - Pool is not initialized.
714    /// - Tick range is invalid or not properly spaced.
715    /// - Position updates fail.
716    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    /// Adds liquidity to a position.
759    ///
760    /// Updates position state, tracks deposited amounts, and manages tick maps.
761    /// Called by both historical event processing and simulated operations.
762    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        // Track deposited amounts
783        self.analytics.total_amount0_deposited += amount0;
784        self.analytics.total_amount1_deposited += amount1;
785
786        Ok(())
787    }
788
789    /// Executes a simulated mint (liquidity addition) operation.
790    ///
791    /// Calculates required token amounts for the specified liquidity amount,
792    /// updates pool state, and returns the resulting mint event.
793    /// Rejects the mint before changing pool state if the resulting gross liquidity at either
794    /// boundary tick exceeds the pool's maximum liquidity per tick.
795    ///
796    /// # Errors
797    ///
798    /// Returns an error if:
799    /// - Pool is not initialized.
800    /// - Tick range is invalid.
801    /// - Amount calculations fail.
802    /// - Resulting tick liquidity exceeds the per-tick limit, or a liquidity calculation overflows.
803    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, // ts_event (simulated; pool init time)
845            self.pool.ts_init, // ts_init
846        );
847
848        Ok(event)
849    }
850
851    /// Processes a burn (liquidity removal) event from historical data.
852    ///
853    /// Updates pool state when liquidity is removed from a position. Uses negative
854    /// liquidity delta to reduce the position size and tracks withdrawn amounts.
855    ///
856    /// # Errors
857    ///
858    /// Returns an error if:
859    /// - Pool is not initialized.
860    /// - Tick range is invalid.
861    /// - Position updates fail.
862    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        // Update the position with a negative liquidity delta for the burn
873        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    /// Executes a simulated burn (liquidity removal) operation.
911    ///
912    /// Calculates token amounts that would be withdrawn for the specified liquidity,
913    /// updates pool state, and returns the resulting burn event.
914    ///
915    /// # Errors
916    ///
917    /// Returns an error if:
918    /// - Pool is not initialized.
919    /// - Tick range is invalid.
920    /// - Amount calculations fail.
921    /// - Insufficient liquidity in position.
922    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        // Update the position with a negative liquidity delta for the burn
942        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, // ts_event (simulated; pool init time)
973            self.pool.ts_init, // ts_init
974        );
975
976        Ok(event)
977    }
978
979    /// Processes a fee collect event from historical data.
980    ///
981    /// Updates position state when accumulated fees are collected. Finds the
982    /// position and delegates fee collection to the position object.
983    ///
984    /// Note: Tick validation is intentionally skipped to match Uniswap V3 behavior.
985    /// Invalid positions have no fees to collect, so they're silently ignored.
986    ///
987    /// # Errors
988    ///
989    /// Returns an error if:
990    /// - Pool is not initialized.
991    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        // Cleanup position if it became empty after collecting all fees
1009        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    /// Applies a protocol-fee configuration change from a `SetFeeProtocol` event.
1032    ///
1033    /// Applies the DEX-specific protocol-fee representation so subsequent swap and flash fee
1034    /// splitting uses the correct setting. Not gated on pool initialization, since a protocol-fee
1035    /// change is independent of the pool's price/liquidity state.
1036    ///
1037    /// # Errors
1038    ///
1039    /// Returns an error if a Uniswap V3 fee protocol update cannot be packed into one byte.
1040    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    /// Applies a protocol-fee withdrawal from a `CollectProtocol` event.
1075    ///
1076    /// Decrements the accrued protocol-fee balances by the withdrawn amounts, leaving the on-chain
1077    /// remainder (Uniswap V3 keeps one wei in each slot to save gas). Saturating subtraction guards
1078    /// against replay accrual lagging behind the on-chain balance. Not gated on pool initialization,
1079    /// since the protocol-fee balances are independent of the pool's price/liquidity state.
1080    ///
1081    /// This function does not return an error; the `Result` keeps the signature uniform with the
1082    /// other `process_*` event handlers.
1083    #[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    /// Processes a flash loan event from historical data.
1124    ///
1125    /// # Errors
1126    ///
1127    /// Returns an error if:
1128    /// - Pool has no active liquidity.
1129    /// - Fee growth arithmetic overflows.
1130    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    /// Executes a simulated flash loan operation and returns the resulting event.
1157    ///
1158    /// # Errors
1159    ///
1160    /// Returns an error if:
1161    /// - Mathematical operations overflow when calculating fees.
1162    /// - Pool has no active liquidity.
1163    /// - Fee growth arithmetic overflows.
1164    ///
1165    /// # Panics
1166    ///
1167    /// Panics if the pool fee has not been set.
1168    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        // Calculate fees or paid0/paid1
1181        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, // ts_event (simulated; pool init time)
1206            self.pool.ts_init, // ts_init
1207            sender,
1208            recipient,
1209            amount0,
1210            amount1,
1211            paid0,
1212            paid1,
1213        );
1214
1215        Ok(flash_event)
1216    }
1217
1218    /// Core flash loan state update logic.
1219    ///
1220    /// # Errors
1221    ///
1222    /// Returns an error if:
1223    /// - No active liquidity in pool.
1224    /// - Fee growth arithmetic overflows.
1225    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        // Process token0 fees
1237        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        // Process token1 fees
1251        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    /// Updates position state and tick maps when liquidity changes.
1288    ///
1289    /// Core internal method that handles position updates for both mints and burns.
1290    /// Updates tick maps, position tracking, fee growth, and active liquidity.
1291    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        // Update tickmaps.
1312        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        // Clear the ticks if they are flipped and burned
1345        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    /// Removes position from tracking if it's completely empty.
1357    ///
1358    /// This prevents accumulation of positions in the memory that are not used anymore.
1359    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    /// Calculates the liquidity utilization rate for the pool.
1374    ///
1375    /// The utilization rate measures what fraction of total deployed liquidity
1376    /// is currently active (in-range and earning fees) at the current price tick.
1377    /// Returns zero when no position liquidity is tracked, otherwise truncates to six decimal places.
1378    /// Partial-history replay can produce values above one when active liquidity includes positions
1379    /// whose mint events were not replayed.
1380    #[must_use]
1381    pub fn liquidity_utilization_rate(&self) -> f64 {
1382        const PRECISION: u32 = 1_000_000; // 6 decimal places
1383
1384        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    /// Validates tick range for position operations.
1401    ///
1402    /// Ensures ticks are properly ordered, aligned to tick spacing, and within
1403    /// valid bounds. Used by all position-related operations.
1404    ///
1405    /// # Errors
1406    ///
1407    /// Returns an error if:
1408    /// - `tick_lower >= tick_upper` (invalid range).
1409    /// - Ticks are not multiples of pool's tick spacing.
1410    /// - Ticks are outside `MIN_TICK/MAX_TICK` bounds.
1411    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    /// Updates all liquidity analytics.
1431    fn update_liquidity_analytics(&mut self) {
1432        self.analytics.liquidity_utilization_rate = self.liquidity_utilization_rate();
1433    }
1434
1435    /// Returns the pool's active liquidity tracked by the tick map.
1436    ///
1437    /// This represents the effective liquidity available for trading at the current price.
1438    /// The tick map maintains this value efficiently by updating it during tick crossings
1439    /// as the price moves through different ranges.
1440    ///
1441    /// # Returns
1442    /// The active liquidity (u128) at the current tick from the tick map
1443    #[must_use]
1444    pub fn get_active_liquidity(&self) -> u128 {
1445        self.tick_map.liquidity
1446    }
1447
1448    /// Calculates total liquidity by summing all individual positions at the current tick.
1449    ///
1450    /// This computes liquidity by iterating through all positions and summing those that
1451    /// span the current tick. Unlike [`Self::get_active_liquidity`], which returns the maintained
1452    /// tick map value, this method performs a fresh calculation from position data.
1453    #[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    /// Calculates total liquidity across all positions, regardless of range status.
1467    #[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    /// Restores the profiler state from a saved snapshot.
1476    ///
1477    /// This method allows resuming profiling from a previously saved state,
1478    /// enabling incremental processing without reprocessing all historical events.
1479    ///
1480    /// # Errors
1481    ///
1482    /// Returns an error if:
1483    /// - Tick insertion into the tick map fails.
1484    ///
1485    /// # Panics
1486    ///
1487    /// Panics if the pool's tick spacing is not set.
1488    pub fn restore_from_snapshot(&mut self, snapshot: PoolSnapshot) -> anyhow::Result<()> {
1489        let liquidity = snapshot.state.liquidity;
1490
1491        // Restore state
1492        self.state = snapshot.state;
1493
1494        // Restore analytics (skip duration fields as they're debug-only)
1495        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        // Rebuild positions AHashMap
1506        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        // Rebuild tick_map
1517        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        // Restore active liquidity
1528        self.tick_map.liquidity = liquidity;
1529
1530        // Set last processed event
1531        self.last_processed_event = Some(snapshot.block_position);
1532        self.last_processed_ts = Some(snapshot.ts_event);
1533
1534        // Mark as initialized
1535        self.is_initialized = true;
1536
1537        // Recalculate analytics
1538        self.update_liquidity_analytics();
1539
1540        Ok(())
1541    }
1542
1543    /// Gets a list of all initialized tick values.
1544    ///
1545    /// Returns tick values that have been initialized (have liquidity positions).
1546    /// Useful for understanding the liquidity distribution across price ranges.
1547    #[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    /// Gets the number of active ticks.
1558    #[must_use]
1559    pub fn get_active_tick_count(&self) -> usize {
1560        self.tick_map.active_tick_count()
1561    }
1562
1563    /// Gets tick information for a specific tick value.
1564    ///
1565    /// Returns the tick data structure containing liquidity and fee information
1566    /// for the specified tick, if it exists.
1567    #[must_use]
1568    pub fn get_tick(&self, tick: i32) -> Option<&PoolTick> {
1569        self.tick_map.get_tick(tick)
1570    }
1571
1572    /// Gets the current tick position of the pool.
1573    ///
1574    /// Returns the tick that corresponds to the current pool price.
1575    /// The pool must be initialized before calling this method.
1576    #[must_use]
1577    pub fn get_current_tick(&self) -> i32 {
1578        self.state.current_tick
1579    }
1580
1581    /// Gets the total number of ticks tracked by the tick map.
1582    ///
1583    /// Returns count of all ticks that have ever been initialized,
1584    /// including those that may no longer have active liquidity.
1585    ///
1586    /// # Returns
1587    /// Total tick count in the tick map
1588    #[must_use]
1589    pub fn get_total_tick_count(&self) -> usize {
1590        self.tick_map.total_tick_count()
1591    }
1592
1593    /// Gets position information for a specific owner and tick range.
1594    ///
1595    /// Looks up a position by its unique key (owner + tick range) and returns
1596    /// the position data if it exists.
1597    #[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    /// Returns a list of all currently active positions.
1609    ///
1610    /// Active positions are those with liquidity > 0 whose tick range includes
1611    /// the current pool tick, meaning they have tokens actively deployed in the pool
1612    /// and are earning fees from trades at the current price.
1613    ///
1614    /// # Returns
1615    ///
1616    /// A vector of references to active [`PoolPosition`] objects.
1617    #[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    /// Returns a list of all positions tracked by the profiler.
1631    ///
1632    /// This includes both active and inactive positions, regardless of their
1633    /// liquidity or tick range relative to the current pool tick.
1634    ///
1635    /// # Returns
1636    ///
1637    /// A vector of references to all [`PoolPosition`] objects.
1638    #[must_use]
1639    pub fn get_all_positions(&self) -> Vec<&PoolPosition> {
1640        self.positions.values().collect()
1641    }
1642
1643    /// Returns position keys for all tracked positions.
1644    #[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    /// Extracts a complete snapshot of the current pool state.
1653    ///
1654    /// Extracts and bundles the complete pool state including global variables,
1655    /// all liquidity positions, and the full tick distribution into a portable
1656    /// [`PoolSnapshot`] structure. This snapshot can be serialized, persisted
1657    /// to database, or used to restore pool state later.
1658    ///
1659    /// # Errors
1660    ///
1661    /// Returns an error if no events have been processed yet, since there is no event watermark to
1662    /// anchor the snapshot to.
1663    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), // ts_event (last processed event)
1683            self.last_processed_ts.unwrap_or(self.pool.ts_init), // ts_init
1684        ))
1685    }
1686
1687    /// Gets the count of positions that are currently active.
1688    ///
1689    /// Active positions are those with liquidity > 0 and whose tick range
1690    /// includes the current pool tick (meaning they have tokens in the pool).
1691    #[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    /// Gets the count of positions that are currently inactive.
1705    ///
1706    /// Inactive positions are those that exist but don't span the current tick,
1707    /// meaning their liquidity is entirely in one token or the other.
1708    #[must_use]
1709    pub fn get_total_inactive_positions(&self) -> usize {
1710        self.positions.len() - self.get_total_active_positions()
1711    }
1712
1713    /// Estimates the total amount of token0 in the pool.
1714    ///
1715    /// Calculates token0 balance by summing:
1716    /// - Token0 amounts from all active liquidity positions
1717    /// - Accumulated trading fees (approximated from fee growth)
1718    /// - Protocol fees collected
1719    #[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        // 1. Calculate token0 from active liquidity positions
1726        for position in self.positions.values() {
1727            // Empty positions and positions below current price hold no token0
1728            if position.liquidity == 0 || position.tick_upper <= current_tick {
1729                continue;
1730            }
1731
1732            if position.tick_lower > current_tick {
1733                // Position is above current price - all token0
1734                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                // Position is active - token0 from current price to upper tick
1741                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        // 2. Add accumulated swap fees (fee_growth_global represents total fees accumulated)
1753        // Note: In a real pool, fees are distributed as liquidity, but for balance estimation
1754        // we can use a simplified approach by converting fee growth to token amounts
1755        let fee_growth_0 = self.state.fee_growth_global_0;
1756        if fee_growth_0 > U256::ZERO {
1757            // Convert fee growth to actual token amount using FullMath for precision
1758            // Fee growth is in Q128.128 format, so we need to scale it properly
1759            let active_liquidity = self.get_active_liquidity();
1760            if active_liquidity > 0 {
1761                // fee_growth_global is fees per unit of liquidity in Q128.128
1762                // To get total fees: mul_div(fee_growth, liquidity, 2^128)
1763                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        // 4. Add protocol fees
1772        total_amount0 += self.state.protocol_fees_token0;
1773
1774        total_amount0
1775    }
1776
1777    /// Estimates the total amount of token1 in the pool.
1778    ///
1779    /// Calculates token1 balance by summing:
1780    /// - Token1 amounts from all active liquidity positions
1781    /// - Accumulated trading fees (approximated from fee growth)
1782    /// - Protocol fees collected
1783    #[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        // 1. Calculate token1 from active liquidity positions
1790        for position in self.positions.values() {
1791            // Empty positions and positions above current price hold no token1
1792            if position.liquidity == 0 || position.tick_lower > current_tick {
1793                continue;
1794            }
1795
1796            if position.tick_upper <= current_tick {
1797                // Position is below current price - all token1
1798                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                // Position is active - token1 from lower tick to current price
1805                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        // 2. Add accumulated swap fees for token1
1817        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                // Convert fee growth to actual token amount using FullMath
1822                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        // 4. Add protocol fees
1831        total_amount1 += self.state.protocol_fees_token1;
1832
1833        total_amount1
1834    }
1835
1836    /// Sets the global fee growth for both tokens.
1837    ///
1838    /// This is primarily used for testing to simulate specific fee growth scenarios.
1839    /// In production, fee growth is updated through swap operations.
1840    ///
1841    /// # Arguments
1842    /// * `fee_growth_global_0` - New global fee growth for token0
1843    /// * `fee_growth_global_1` - New global fee growth for token1
1844    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    /// Returns the total number of events processed.
1850    #[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    /// Enables progress reporting for pool profiler event processing.
1860    ///
1861    /// When enabled, the profiler will automatically track and log progress
1862    /// as events are processed through the `process()` method.
1863    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    /// Finalizes reporting and logs final statistics.
1874    ///
1875    /// Should be called after all events have been processed to output
1876    /// the final summary of the profiler bootstrap operation.
1877    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        // Verify simulation against event data - correct with event values if mismatch detected
1935        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        // Only validate when burning (negative liquidity_delta)
1998        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        // Pre-validate so an over/underflow error returns before mutating tick map
2012        // or position state.
2013        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        // The replay clause keeps crossing empty ranges to the limit after the amount runs out
2107        (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    // A replayed swap's recorded input was consumed in full, so input left at the event
2114    // price is charged as fee even when that price equals the starting price.
2115    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        // Make sure we do not overshoot MIN/MAX tick
2134        tick_next = tick_next.clamp(PoolTick::MIN_TICK, PoolTick::MAX_TICK);
2135
2136        // Get the price for the next tick
2137        let sqrt_price_next = get_sqrt_ratio_at_tick(tick_next);
2138
2139        // Compute values to swap to the target tick, price limit, or point where input/output amount is exhausted
2140        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        // Matches the on-chain step that ran out of input before its target; a step ending on
2158        // a tick boundary keeps its fee because the chain crosses first.
2159        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        // Update current price to the new price after this swap step (BEFORE amount updates, matching Solidity)
2168        self.current_sqrt_price = swap_step_result.sqrt_ratio_next_x96;
2169
2170        self.update_amounts(&swap_step_result);
2171        // Accrue against pre-crossing liquidity; crossings record the updated fee growth
2172        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        // Update amounts based on swap direction and type
2200        if self.exact_input {
2201            // For exact input swaps: subtract input amount and fees from remaining, subtract output from calculated
2202            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            // For exact output swaps: add output to remaining, add input and fees to calculated
2207            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        // Calculate protocol fee if enabled
2214        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        // Accumulate LP fee (protocol fee is already deducted if it exists).
2227        self.lp_fee += step_fee_amount;
2228
2229        // Update global fee tracker
2230        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        // Shift tick if we reached the next price
2250        if self.current_sqrt_price == sqrt_price_next {
2251            // We have swapped all the way to the boundary of the next tick.
2252            // Time to handle crossing into the next tick, which may change liquidity.
2253            // If the tick is initialized, run the tick transition logic (liquidity changes, fee accumulators, etc.).
2254            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            // The price moved during this swap step, but didn't reach a tick boundary.
2265            // So, update the tick to match the new price.
2266            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        // Update local liquidity tracking when crossing ticks
2289        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        // Calculate final amounts
2303        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}