Skip to main content

nautilus_model/defi/pool_analysis/
compare.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 profiler state comparison utilities.
17
18use super::{position::PoolPosition, profiler::PoolProfiler};
19use crate::defi::pool_analysis::snapshot::PoolSnapshot;
20
21/// Result of comparing a replayed pool profiler against an on-chain snapshot.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum PoolProfilerComparison {
24    /// All compared fields match.
25    Match,
26    /// Only the sqrt price differs; structural pool state still matches.
27    SqrtPriceMismatch,
28    /// Only the fee protocol differs; structural pool state still matches.
29    FeeProtocolMismatch,
30    /// Only the accrued protocol-fee balances differ; structural pool state still matches.
31    ProtocolFeesMismatch,
32    /// One or more structural fields differ.
33    Mismatch,
34}
35
36impl PoolProfilerComparison {
37    /// Returns `true` when every compared field matches.
38    #[must_use]
39    pub const fn is_exact_match(self) -> bool {
40        matches!(self, Self::Match)
41    }
42
43    /// Returns `true` when the snapshot can seed the profiler cache.
44    #[must_use]
45    pub const fn is_valid_for_snapshot(self) -> bool {
46        matches!(
47            self,
48            Self::Match
49                | Self::SqrtPriceMismatch
50                | Self::FeeProtocolMismatch
51                | Self::ProtocolFeesMismatch
52        )
53    }
54}
55
56/// Compares a pool profiler's internal state with on-chain state to verify consistency.
57///
58/// This function validates that the profiler's tracked state matches the actual on-chain
59/// pool state by comparing global pool parameters, tick data, and position data.
60/// Structural mismatches are logged as errors, sqrt price mismatches are logged as warnings,
61/// and matches are logged as info.
62///
63/// # Arguments
64///
65/// - `profiler` - The pool profiler whose state should be compared
66/// - `snapshot` - The on-chain snapshot to compare against
67///
68/// # Panics
69///
70/// Panics if the profiler has not been initialized.
71///
72/// # Returns
73///
74/// Returns `true` if all compared values match, `false` if any mismatches are detected.
75#[must_use]
76pub fn compare_pool_profiler(profiler: &PoolProfiler, snapshot: &PoolSnapshot) -> bool {
77    compare_pool_profiler_detailed(profiler, snapshot).is_exact_match()
78}
79
80/// Compares a pool profiler's internal state with on-chain state and classifies mismatches.
81///
82/// Sqrt price can differ when replay is event-scoped but the RPC snapshot is block-scoped. Fee
83/// protocol can differ until `SetFeeProtocol` events are indexed and applied during replay, leaving
84/// the profiler value lagging the on-chain one. Accrued protocol-fee balances can differ when
85/// per-step rounding during replay accrual diverges from the on-chain accumulator. These mismatches
86/// are non-blocking when tick, liquidity, ticks, and positions all match.
87///
88/// # Panics
89///
90/// Panics if the profiler has not been initialized.
91#[must_use]
92pub fn compare_pool_profiler_detailed(
93    profiler: &PoolProfiler,
94    snapshot: &PoolSnapshot,
95) -> PoolProfilerComparison {
96    assert!(profiler.is_initialized, "Profiler is not initialized");
97
98    let comparison = compare_pool_state(profiler, snapshot);
99    let ticks_match = compare_ticks(profiler, snapshot);
100    let positions_match = compare_positions(profiler, snapshot);
101
102    if !ticks_match || !positions_match {
103        return PoolProfilerComparison::Mismatch;
104    }
105
106    match comparison {
107        PoolProfilerComparison::SqrtPriceMismatch => {
108            log::warn!("Pool profiler sqrt ratio differs, but all structural state matches");
109        }
110        PoolProfilerComparison::FeeProtocolMismatch => {
111            log::warn!("Pool profiler fee protocol differs, but all structural state matches");
112        }
113        PoolProfilerComparison::ProtocolFeesMismatch => {
114            log::warn!("Pool profiler protocol fees differ, but all structural state matches");
115        }
116        PoolProfilerComparison::Match | PoolProfilerComparison::Mismatch => {}
117    }
118
119    comparison
120}
121
122fn compare_pool_state(profiler: &PoolProfiler, snapshot: &PoolSnapshot) -> PoolProfilerComparison {
123    let mut structural_match = true;
124    let mut sqrt_price_matches = true;
125
126    if snapshot.state.current_tick == profiler.state.current_tick {
127        log::info!("✓ current_tick matches: {}", snapshot.state.current_tick);
128    } else {
129        log::error!(
130            "Tick mismatch: profiler={}, compared={}",
131            profiler.state.current_tick,
132            snapshot.state.current_tick
133        );
134        structural_match = false;
135    }
136
137    if snapshot.state.price_sqrt_ratio_x96 == profiler.state.price_sqrt_ratio_x96 {
138        log::info!(
139            "✓ sqrt_price_x96 matches: {}",
140            profiler.state.price_sqrt_ratio_x96,
141        );
142    } else {
143        log::warn!(
144            "Sqrt ratio mismatch: profiler={}, compared={}",
145            profiler.state.price_sqrt_ratio_x96,
146            snapshot.state.price_sqrt_ratio_x96
147        );
148        sqrt_price_matches = false;
149    }
150
151    let fee_protocol_matches = compare_fee_protocol(profiler, snapshot);
152
153    let protocol_fees_match = compare_protocol_fees(profiler, snapshot);
154
155    if snapshot.state.liquidity == profiler.tick_map.liquidity {
156        log::info!("✓ liquidity matches: {}", snapshot.state.liquidity);
157    } else {
158        log::error!(
159            "Liquidity mismatch: profiler={}, compared={}",
160            profiler.tick_map.liquidity,
161            snapshot.state.liquidity
162        );
163        structural_match = false;
164    }
165
166    // TODO add growth fee checking
167
168    if !structural_match {
169        PoolProfilerComparison::Mismatch
170    } else if !sqrt_price_matches {
171        PoolProfilerComparison::SqrtPriceMismatch
172    } else if !fee_protocol_matches {
173        PoolProfilerComparison::FeeProtocolMismatch
174    } else if !protocol_fees_match {
175        PoolProfilerComparison::ProtocolFeesMismatch
176    } else {
177        PoolProfilerComparison::Match
178    }
179}
180
181fn compare_fee_protocol(profiler: &PoolProfiler, snapshot: &PoolSnapshot) -> bool {
182    if snapshot.state.fee_protocol == profiler.state.fee_protocol
183        && snapshot.state.fee_protocol0_basis_points == profiler.state.fee_protocol0_basis_points
184        && snapshot.state.fee_protocol1_basis_points == profiler.state.fee_protocol1_basis_points
185    {
186        log::info!(
187            "✓ fee_protocol matches: packed={}, token0_bps={:?}, token1_bps={:?}",
188            snapshot.state.fee_protocol,
189            snapshot.state.fee_protocol0_basis_points,
190            snapshot.state.fee_protocol1_basis_points,
191        );
192        true
193    } else {
194        log::warn!(
195            "Fee protocol mismatch: profiler=(packed={}, token0_bps={:?}, token1_bps={:?}), compared=(packed={}, token0_bps={:?}, token1_bps={:?})",
196            profiler.state.fee_protocol,
197            profiler.state.fee_protocol0_basis_points,
198            profiler.state.fee_protocol1_basis_points,
199            snapshot.state.fee_protocol,
200            snapshot.state.fee_protocol0_basis_points,
201            snapshot.state.fee_protocol1_basis_points,
202        );
203        false
204    }
205}
206
207fn compare_protocol_fees(profiler: &PoolProfiler, snapshot: &PoolSnapshot) -> bool {
208    if snapshot.state.protocol_fees_token0 == profiler.state.protocol_fees_token0
209        && snapshot.state.protocol_fees_token1 == profiler.state.protocol_fees_token1
210    {
211        log::info!(
212            "✓ protocol_fees match: token0={}, token1={}",
213            snapshot.state.protocol_fees_token0,
214            snapshot.state.protocol_fees_token1
215        );
216        true
217    } else {
218        log::warn!(
219            "Protocol fees mismatch: profiler=(token0={}, token1={}), compared=(token0={}, token1={})",
220            profiler.state.protocol_fees_token0,
221            profiler.state.protocol_fees_token1,
222            snapshot.state.protocol_fees_token0,
223            snapshot.state.protocol_fees_token1
224        );
225        false
226    }
227}
228
229fn compare_ticks(profiler: &PoolProfiler, snapshot: &PoolSnapshot) -> bool {
230    let total_ticks = snapshot.ticks.len();
231    let mut ticks_match = true;
232    let mut tick_mismatches = 0;
233
234    for tick in &snapshot.ticks {
235        let Some(profiler_tick) = profiler.get_tick(tick.value) else {
236            log::error!(
237                "Tick {} not found in the profiler but provided in the compare mapping",
238                tick.value
239            );
240            ticks_match = false;
241            continue;
242        };
243
244        let mut all_tick_fields_matching = true;
245
246        if profiler_tick.liquidity_net != tick.liquidity_net {
247            log::error!(
248                "Tick {} mismatch on net liquidity: profiler={}, compared={}",
249                tick.value,
250                profiler_tick.liquidity_net,
251                tick.liquidity_net
252            );
253            all_tick_fields_matching = false;
254        }
255
256        if profiler_tick.liquidity_gross != tick.liquidity_gross {
257            log::error!(
258                "Tick {} mismatch on gross liquidity: profiler={}, compared={}",
259                tick.value,
260                profiler_tick.liquidity_gross,
261                tick.liquidity_gross
262            );
263            all_tick_fields_matching = false;
264        }
265        // TODO add fees checking per tick
266
267        if !all_tick_fields_matching {
268            tick_mismatches += 1;
269            ticks_match = false;
270        }
271    }
272
273    if tick_mismatches == 0 {
274        log::info!("✓ Provided {total_ticks} ticks with liquidity net and gross are matching");
275    }
276
277    ticks_match
278}
279
280fn compare_positions(profiler: &PoolProfiler, snapshot: &PoolSnapshot) -> bool {
281    let total_positions = snapshot.positions.len();
282    let mut positions_match = true;
283    let mut position_mismatches = 0;
284
285    for position in &snapshot.positions {
286        let Some(profiler_position) =
287            profiler.get_position(&position.owner, position.tick_lower, position.tick_upper)
288        else {
289            log::error!(
290                "Position {} not found in the profiler but provided in the compare mapping",
291                position.owner
292            );
293            positions_match = false;
294            continue;
295        };
296
297        let position_key = PoolPosition::get_position_key(
298            &position.owner,
299            position.tick_lower,
300            position.tick_upper,
301        );
302
303        if position.liquidity != profiler_position.liquidity {
304            log::error!(
305                "Position '{}' mismatch on liquidity: profiler={}, compared={}",
306                position_key,
307                profiler_position.liquidity,
308                position.liquidity
309            );
310            position_mismatches += 1;
311        }
312        // TODO add fees and tokens owned checking
313    }
314
315    if position_mismatches == 0 {
316        log::info!("✓ Provided {total_positions} active positions with liquidity are matching");
317    } else {
318        positions_match = false;
319    }
320
321    positions_match
322}