nautilus-model 0.55.0

Domain model for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Pool profiling utilities for analyzing DeFi pool event data.

use ahash::AHashMap;
use alloy_primitives::{Address, I256, U160, U256};

use crate::defi::{
    PoolLiquidityUpdate, PoolSwap, SharedPool,
    data::{
        DexPoolData, PoolFeeCollect, PoolLiquidityUpdateType, block::BlockPosition,
        flash::PoolFlash,
    },
    pool_analysis::{
        position::PoolPosition,
        quote::SwapQuote,
        size_estimator,
        snapshot::{PoolAnalytics, PoolSnapshot, PoolState},
        swap_math::compute_swap_step,
    },
    reporting::{BlockchainSyncReportItems, BlockchainSyncReporter},
    tick_map::{
        TickMap,
        full_math::{FullMath, Q128},
        liquidity_math::liquidity_math_add,
        sqrt_price_math::{get_amount0_delta, get_amount1_delta, get_amounts_for_liquidity},
        tick::{CrossedTick, PoolTick},
        tick_math::{
            MAX_SQRT_RATIO, MIN_SQRT_RATIO, get_sqrt_ratio_at_tick, get_tick_at_sqrt_ratio,
        },
    },
};

/// A DeFi pool state tracker and event processor for UniswapV3-style AMM pools.
///
/// The `PoolProfiler` provides complete pool state management including:
/// - Liquidity position tracking and management.
/// - Tick crossing and price movement simulation.
/// - Fee accumulation and distribution tracking.
/// - Protocol fee calculation.
/// - Pool state validation and maintenance.
///
/// This profiler can both process historical events and execute new operations,
/// making it suitable for both backtesting and simulation scenarios.
///
/// # Usage
///
/// Create a new profiler with a pool definition, initialize it with a starting price,
/// then either process historical events or execute new pool operations to simulate
/// trading activity and analyze pool behavior.
#[derive(Debug, Clone)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
)]
pub struct PoolProfiler {
    /// Pool definition.
    pub pool: SharedPool,
    /// Position tracking by position key (owner:tick_lower:tick_upper).
    positions: AHashMap<String, PoolPosition>,
    /// Tick map managing liquidity distribution across price ranges.
    pub tick_map: TickMap,
    /// Global pool state including current price, tick, and cumulative flows with fees.
    pub state: PoolState,
    /// Analytics counters tracking pool operations and performance metrics.
    pub analytics: PoolAnalytics,
    /// The block position of the last processed event.
    pub last_processed_event: Option<BlockPosition>,
    /// Flag indicating whether the pool has been initialized with a starting price.
    pub is_initialized: bool,
    /// Optional progress reporter for tracking event processing.
    reporter: Option<BlockchainSyncReporter>,
    /// The last block number that was reported (used for progress tracking).
    last_reported_block: u64,
}

impl PoolProfiler {
    /// Creates a new [`PoolProfiler`] instance for tracking pool state and events.
    ///
    /// # Panics
    ///
    /// Panics if the pool's tick spacing is not set.
    #[must_use]
    pub fn new(pool: SharedPool) -> Self {
        let tick_spacing = pool.tick_spacing.expect("Pool tick spacing must be set");
        Self {
            pool,
            positions: AHashMap::new(),
            tick_map: TickMap::new(tick_spacing),
            state: PoolState::default(),
            analytics: PoolAnalytics::default(),
            last_processed_event: None,
            is_initialized: false,
            reporter: None,
            last_reported_block: 0,
        }
    }

    /// Initializes the pool with a starting price and activates the profiler.
    ///
    /// # Panics
    ///
    /// This function panics if:
    /// - Pool is already initialized (checked via `is_initialized` flag)
    /// - Calculated tick from price doesn't match pool's `initial_tick` (if set)
    pub fn initialize(&mut self, price_sqrt_ratio_x96: U160) {
        assert!(!self.is_initialized, "Pool already initialized");

        let calculated_tick = get_tick_at_sqrt_ratio(price_sqrt_ratio_x96);

        if let Some(initial_tick) = self.pool.initial_tick {
            assert_eq!(
                initial_tick, calculated_tick,
                "Calculated tick does not match pool initial tick"
            );
        }

        log::info!(
            "Initializing pool profiler with tick {calculated_tick} and price sqrt ratio {price_sqrt_ratio_x96}"
        );

        self.state.current_tick = calculated_tick;
        self.state.price_sqrt_ratio_x96 = price_sqrt_ratio_x96;
        self.is_initialized = true;
    }

    /// Verifies that the pool has been initialized.
    ///
    /// # Panics
    ///
    /// Panics if the pool hasn't been initialized with a starting price via [`initialize()`](Self::initialize).
    pub fn check_if_initialized(&self) {
        assert!(self.is_initialized, "Pool is not initialized");
    }

    /// Processes a historical pool event and updates internal state.
    ///
    /// Handles all types of pool events (swaps, mints, burns, fee collections),
    /// and updates the profiler's internal state accordingly. This is the main
    /// entry point for processing historical blockchain events.
    ///
    /// # Errors
    ///
    /// This function returns an error if:
    /// - Pool is not initialized.
    /// - Event contains invalid data (tick ranges, amounts).
    /// - Mathematical operations overflow.
    pub fn process(&mut self, event: &DexPoolData) -> anyhow::Result<()> {
        if self.check_if_already_processed(
            event.block_number(),
            event.transaction_index(),
            event.log_index(),
        ) {
            return Ok(());
        }

        match event {
            DexPoolData::Swap(swap) => self.process_swap(swap)?,
            DexPoolData::LiquidityUpdate(update) => match update.kind {
                PoolLiquidityUpdateType::Mint => self.process_mint(update)?,
                PoolLiquidityUpdateType::Burn => self.process_burn(update)?,
            },
            DexPoolData::FeeCollect(collect) => self.process_collect(collect)?,
            DexPoolData::Flash(flash) => self.process_flash(flash)?,
        }
        self.update_reporter_if_enabled(event.block_number());

        Ok(())
    }

    // Checks if we need to skip events at or before the last processed event to prevent double-processing.
    fn check_if_already_processed(&self, block: u64, tx_idx: u32, log_idx: u32) -> bool {
        if let Some(last_event) = &self.last_processed_event {
            let should_skip = block < last_event.number
                || (block == last_event.number && tx_idx < last_event.transaction_index)
                || (block == last_event.number
                    && tx_idx == last_event.transaction_index
                    && log_idx <= last_event.log_index);

            if should_skip {
                log::debug!(
                    "Skipping already processed event at block {block} tx {tx_idx} log {log_idx}"
                );
            }
            return should_skip;
        }

        false
    }

    /// Auto-updates reporter if it's enabled.
    fn update_reporter_if_enabled(&mut self, current_block: u64) {
        // Auto-update reporter if enabled
        if let Some(reporter) = &mut self.reporter {
            let blocks_processed = current_block.saturating_sub(self.last_reported_block);

            if blocks_processed > 0 {
                reporter.update(blocks_processed as usize);
                self.last_reported_block = current_block;

                if reporter.should_log_progress(current_block, current_block) {
                    reporter.log_progress(current_block);
                }
            }
        }
    }

    // panics-doc-ok (transitive via check_if_initialized)
    /// Processes a historical swap event from blockchain data.
    ///
    /// Replays the swap by simulating it through [`Self::simulate_swap_through_ticks`],
    /// then verifies the simulation results against the actual event data. If mismatches
    /// are detected (tick or liquidity), the pool state is corrected to match the event
    /// values and warnings are logged.
    ///
    /// This self-healing approach ensures pool state stays synchronized with on-chain
    /// reality even if simulation logic differs slightly from actual contract behavior.
    ///
    /// # Use Case
    ///
    /// Historical event processing when rebuilding pool state from blockchain events.
    ///
    /// # Errors
    ///
    /// This function returns an error if:
    /// - Pool initialization checks fail.
    /// - Swap simulation fails (see [`Self::simulate_swap_through_ticks`] errors).
    ///
    /// # Panics
    ///
    /// Panics if the pool has not been initialized.
    pub fn process_swap(&mut self, swap: &PoolSwap) -> anyhow::Result<()> {
        self.check_if_initialized();

        if self.check_if_already_processed(swap.block, swap.transaction_index, swap.log_index) {
            return Ok(());
        }

        let zero_for_one = swap.amount0.is_positive();
        let amount_specified = if zero_for_one {
            swap.amount0
        } else {
            swap.amount1
        };
        // For price limit use the final sqrt price from swap, which is a
        // good proxy to price limit
        let sqrt_price_limit_x96 = swap.sqrt_price_x96;
        let swap_quote =
            self.simulate_swap_through_ticks(amount_specified, zero_for_one, sqrt_price_limit_x96)?;
        self.apply_swap_quote(&swap_quote);

        // Verify simulation against event data - correct with event values if mismatch detected
        if swap.tick != self.state.current_tick {
            log::error!(
                "Inconsistency in swap processing: Current tick mismatch: simulated {}, event {} on block {}",
                self.state.current_tick,
                swap.tick,
                swap.block
            );
            self.state.current_tick = swap.tick;
        }

        if swap.liquidity != self.tick_map.liquidity {
            log::error!(
                "Inconsistency in swap processing: Active liquidity mismatch: simulated {}, event {} on block {}",
                self.tick_map.liquidity,
                swap.liquidity,
                swap.block
            );
            self.tick_map.liquidity = swap.liquidity;
        }

        self.last_processed_event = Some(BlockPosition::new(
            swap.block,
            swap.transaction_hash.clone(),
            swap.transaction_index,
            swap.log_index,
        ));
        self.update_reporter_if_enabled(swap.block);
        self.update_liquidity_analytics();

        Ok(())
    }

    // panics-doc-ok (transitive via check_if_initialized)
    /// Executes a new simulated swap and returns the resulting event.
    ///
    /// This is the public API for forward simulation of swap operations. It delegates
    /// the core swap mathematics to [`Self::simulate_swap_through_ticks`], then wraps
    /// the results in a [`PoolSwap`] event structure with full metadata.
    ///
    /// # Errors
    ///
    /// Returns errors from [`Self::simulate_swap_through_ticks`]:
    /// - Pool metadata missing or invalid
    /// - Price limit violations
    /// - Arithmetic overflow in fee or liquidity calculations
    ///
    /// # Panics
    ///
    /// This function panics if:
    /// - Pool fee is not initialized
    /// - Pool is not initialized
    pub fn execute_swap(
        &mut self,
        sender: Address,
        recipient: Address,
        block: BlockPosition,
        zero_for_one: bool,
        amount_specified: I256,
        sqrt_price_limit_x96: U160,
    ) -> anyhow::Result<PoolSwap> {
        self.check_if_initialized();
        let swap_quote =
            self.simulate_swap_through_ticks(amount_specified, zero_for_one, sqrt_price_limit_x96)?;
        self.apply_swap_quote(&swap_quote);

        let swap_event = PoolSwap::new(
            self.pool.chain.clone(),
            self.pool.dex.clone(),
            self.pool.instrument_id,
            self.pool.pool_identifier,
            block.number,
            block.transaction_hash,
            block.transaction_index,
            block.log_index,
            None,
            sender,
            recipient,
            swap_quote.amount0,
            swap_quote.amount1,
            self.state.price_sqrt_ratio_x96,
            self.tick_map.liquidity,
            self.state.current_tick,
        );
        Ok(swap_event)
    }

    /// Core **read-only** swap simulation engine implementing UniswapV3 mathematics.
    ///
    /// This method performs a complete swap simulation without modifying pool state,
    /// working entirely on stack-allocated local copies of state variables. It returns
    /// a [`SwapQuote`] containing all swap results and profiling data,
    /// including a complete audit trail of crossed ticks.
    ///
    ///
    /// # Algorithm Overview
    ///
    /// 1. **Iterative price curve traversal**: Walks through liquidity ranges until
    ///    the input/output amount is exhausted or the price limit is reached
    /// 2. **Tick crossing tracking**: When crossing initialized tick boundaries, records
    ///    the crossing in `crossed_ticks` vector with complete state snapshot (tick, direction, fee growth)
    /// 3. **Local liquidity updates**: Tracks liquidity changes in local variables by reading
    ///    `liquidity_net` from tick map (read-only, no mutations)
    /// 4. **Fee calculation**: Splits fees between LPs and protocol, accumulates in local variables
    /// 5. **Quote assembly**: Returns [`SwapQuote`] with amounts, prices, fees, and crossed tick data
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Pool fee is not configured
    /// - Fee growth arithmetic overflows when scaling by liquidity
    /// - Swap step calculations fail
    ///
    /// # Panics
    ///
    /// Panics if pool is not initialized
    pub fn simulate_swap_through_ticks(
        &self,
        amount_specified: I256,
        zero_for_one: bool,
        sqrt_price_limit_x96: U160,
    ) -> anyhow::Result<SwapQuote> {
        let mut current_sqrt_price = self.state.price_sqrt_ratio_x96;
        let mut current_tick = self.state.current_tick;
        let mut current_active_liquidity = self.tick_map.liquidity;
        let exact_input = amount_specified.is_positive();
        let mut amount_specified_remaining = amount_specified;
        let mut amount_calculated = I256::ZERO;
        let mut protocol_fee = U256::ZERO;
        let mut lp_fee = U256::ZERO;
        let mut crossed_ticks = Vec::new();
        let fee_tier = self.pool.fee.expect("Pool fee should be initialized");
        // Swapping cache variables
        let fee_protocol = if zero_for_one {
            // Extract lower 4 bits for token0 protocol fee
            self.state.fee_protocol % 16
        } else {
            // Extract upper 4 bits for token1 protocol fee
            self.state.fee_protocol >> 4
        };

        // Track current fee growth during swap
        let mut current_fee_growth_global = if zero_for_one {
            self.state.fee_growth_global_0
        } else {
            self.state.fee_growth_global_1
        };

        // Continue swapping as long as we haven't used the entire input/output or haven't reached the price limit
        while amount_specified_remaining != I256::ZERO && sqrt_price_limit_x96 != current_sqrt_price
        {
            let sqrt_price_start_x96 = current_sqrt_price;

            let (mut tick_next, initialized) = self
                .tick_map
                .next_initialized_tick(current_tick, zero_for_one);

            // Make sure we do not overshoot MIN/MAX tick
            tick_next = tick_next.clamp(PoolTick::MIN_TICK, PoolTick::MAX_TICK);

            // Get the price for the next tick
            let sqrt_price_next = get_sqrt_ratio_at_tick(tick_next);

            // Compute values to swap to the target tick, price limit, or point where input/output amount is exhausted
            let sqrt_price_target = if (zero_for_one && sqrt_price_next < sqrt_price_limit_x96)
                || (!zero_for_one && sqrt_price_next > sqrt_price_limit_x96)
            {
                sqrt_price_limit_x96
            } else {
                sqrt_price_next
            };
            let swap_step_result = compute_swap_step(
                current_sqrt_price,
                sqrt_price_target,
                current_active_liquidity,
                amount_specified_remaining,
                fee_tier,
            )?;

            // Update current price to the new price after this swap step (BEFORE amount updates, matching Solidity)
            current_sqrt_price = swap_step_result.sqrt_ratio_next_x96;

            // Update amounts based on swap direction and type
            if exact_input {
                // For exact input swaps: subtract input amount and fees from remaining, subtract output from calculated
                amount_specified_remaining -= FullMath::truncate_to_i256(
                    swap_step_result.amount_in + swap_step_result.fee_amount,
                );
                amount_calculated -= FullMath::truncate_to_i256(swap_step_result.amount_out);
            } else {
                // For exact output swaps: add output to remaining, add input and fees to calculated
                amount_specified_remaining +=
                    FullMath::truncate_to_i256(swap_step_result.amount_out);
                amount_calculated += FullMath::truncate_to_i256(
                    swap_step_result.amount_in + swap_step_result.fee_amount,
                );
            }

            // Calculate protocol fee if enabled
            let mut step_fee_amount = swap_step_result.fee_amount;

            if fee_protocol > 0 {
                let protocol_fee_delta = swap_step_result.fee_amount / U256::from(fee_protocol);
                step_fee_amount -= protocol_fee_delta;
                protocol_fee += protocol_fee_delta;
            }

            // Accumulate LP fee (protocol fee is already deducted if it exists).
            lp_fee += step_fee_amount;

            // Update global fee tracker
            if current_active_liquidity > 0 {
                let fee_growth_delta =
                    FullMath::mul_div(step_fee_amount, Q128, U256::from(current_active_liquidity))?;
                current_fee_growth_global += fee_growth_delta;
            }

            // Shift tick if we reached the next price
            if swap_step_result.sqrt_ratio_next_x96 == sqrt_price_next {
                // We have swapped all the way to the boundary of the next tick.
                // Time to handle crossing into the next tick, which may change liquidity.
                // If the tick is initialized, run the tick transition logic (liquidity changes, fee accumulators, etc.).
                if initialized {
                    crossed_ticks.push(CrossedTick::new(
                        tick_next,
                        zero_for_one,
                        if zero_for_one {
                            current_fee_growth_global
                        } else {
                            self.state.fee_growth_global_0
                        },
                        if zero_for_one {
                            self.state.fee_growth_global_1
                        } else {
                            current_fee_growth_global
                        },
                    ));

                    // Update local liquidity tracking when crossing ticks
                    if let Some(tick_data) = self.tick_map.get_tick(tick_next) {
                        let liquidity_net = tick_data.liquidity_net;
                        current_active_liquidity = if zero_for_one {
                            liquidity_math_add(current_active_liquidity, -liquidity_net)
                        } else {
                            liquidity_math_add(current_active_liquidity, liquidity_net)
                        };
                    }
                }

                current_tick = if zero_for_one {
                    tick_next - 1
                } else {
                    tick_next
                };
            } else if swap_step_result.sqrt_ratio_next_x96 != sqrt_price_start_x96 {
                // The price moved during this swap step, but didn't reach a tick boundary.
                // So, update the tick to match the new price.
                current_tick = get_tick_at_sqrt_ratio(current_sqrt_price);
            }
        }

        // Calculate final amounts
        let (amount0, amount1) = if zero_for_one == exact_input {
            (
                amount_specified - amount_specified_remaining,
                amount_calculated,
            )
        } else {
            (
                amount_calculated,
                amount_specified - amount_specified_remaining,
            )
        };

        let quote = SwapQuote::new(
            self.pool.instrument_id,
            amount0,
            amount1,
            self.state.price_sqrt_ratio_x96,
            current_sqrt_price,
            self.state.current_tick,
            current_tick,
            current_active_liquidity,
            current_fee_growth_global,
            lp_fee,
            protocol_fee,
            crossed_ticks,
        );
        Ok(quote)
    }

    /// Applies a swap quote to the pool state (mutations only, no simulation).
    ///
    /// This private method takes a [`SwapQuote`] generated by [`Self::simulate_swap_through_ticks`]
    /// and applies its state changes to the pool, including:
    /// - Price and tick updates
    /// - Fee growth and protocol fee accumulation
    /// - Tick crossing mutations (updating tick fee accumulators and active liquidity)
    pub fn apply_swap_quote(&mut self, swap_quote: &SwapQuote) {
        // Update price and tick.
        self.state.current_tick = swap_quote.tick_after;
        self.state.price_sqrt_ratio_x96 = swap_quote.sqrt_price_after_x96;

        // Update fee growth and protocol fees based on swap direction.
        if swap_quote.zero_for_one() {
            self.state.fee_growth_global_0 = swap_quote.fee_growth_global_after;
            self.state.protocol_fees_token0 += swap_quote.protocol_fee;
        } else {
            self.state.fee_growth_global_1 = swap_quote.fee_growth_global_after;
            self.state.protocol_fees_token1 += swap_quote.protocol_fee;
        }

        // Apply tick crossings efficiently - only update crossed ticks
        for crossed in &swap_quote.crossed_ticks {
            let liquidity_net =
                self.tick_map
                    .cross_tick(crossed.tick, crossed.fee_growth_0, crossed.fee_growth_1);

            // Update active liquidity based on crossing direction
            self.tick_map.liquidity = if crossed.zero_for_one {
                liquidity_math_add(self.tick_map.liquidity, -liquidity_net)
            } else {
                liquidity_math_add(self.tick_map.liquidity, liquidity_net)
            };
        }
        self.analytics.total_swaps += 1;

        debug_assert_eq!(
            self.tick_map.liquidity, swap_quote.liquidity_after,
            "Liquidity mismatch in apply_swap_quote: computed={}, quote={}",
            self.tick_map.liquidity, swap_quote.liquidity_after
        );
    }

    // panics-doc-ok (transitive via check_if_initialized)
    /// Returns a swap quote without modifying pool state.
    ///
    /// This method simulates a swap and provides detailed profiling metrics including:
    /// - Amounts of tokens that would be exchanged
    /// - Price before and after the swap
    /// - Fee breakdown (LP fees and protocol fees)
    /// - List of crossed ticks with state snapshots
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Pool fee is not configured
    /// - Fee growth arithmetic overflows when scaling by liquidity
    /// - Swap step calculations fail
    ///
    /// # Panics
    ///
    /// Panics if pool is not initialized.
    pub fn quote_swap(
        &self,
        amount_specified: I256,
        zero_for_one: bool,
        sqrt_price_limit_x96: Option<U160>,
    ) -> anyhow::Result<SwapQuote> {
        self.check_if_initialized();

        if amount_specified.is_zero() {
            anyhow::bail!("Cannot quote swap with zero amount");
        }

        if let Some(price_limit) = sqrt_price_limit_x96 {
            self.validate_price_limit(price_limit, zero_for_one)?;
        }

        let limit = sqrt_price_limit_x96.unwrap_or_else(|| {
            if zero_for_one {
                MIN_SQRT_RATIO + U160::from(1)
            } else {
                MAX_SQRT_RATIO - U160::from(1)
            }
        });

        self.simulate_swap_through_ticks(amount_specified, zero_for_one, limit)
    }

    /// Simulates an exact input swap (know input amount, calculate output amount).
    ///
    /// # Errors
    /// Returns error if pool is not initialized, input is zero, or price limit is invalid
    pub fn swap_exact_in(
        &self,
        amount_in: U256,
        zero_for_one: bool,
        sqrt_price_limit_x96: Option<U160>,
    ) -> anyhow::Result<SwapQuote> {
        // Positive = exact input.
        let amount_specified = I256::from(amount_in);
        let quote = self.quote_swap(amount_specified, zero_for_one, sqrt_price_limit_x96)?;

        Ok(quote)
    }

    /// Simulates an exact output swap (know output amount, calculate required input amount).
    ///
    /// # Errors
    /// Returns error if pool is not initialized, output is zero, price limit is invalid,
    /// or insufficient liquidity exists to fulfill the exact output amount
    pub fn swap_exact_out(
        &self,
        amount_out: U256,
        zero_for_one: bool,
        sqrt_price_limit_x96: Option<U160>,
    ) -> anyhow::Result<SwapQuote> {
        // Negative = exact output.
        let amount_specified = -I256::from(amount_out);
        let quote = self.quote_swap(amount_specified, zero_for_one, sqrt_price_limit_x96)?;
        quote.validate_exact_output(amount_out)?;

        Ok(quote)
    }

    /// Simulates a swap to move the pool price down to a target price.
    ///
    /// # Errors
    /// Returns error if pool is not initialized or price limit is invalid.
    pub fn swap_to_lower_sqrt_price(
        &self,
        sqrt_price_limit_x96: U160,
    ) -> anyhow::Result<SwapQuote> {
        self.quote_swap(I256::MAX, true, Some(sqrt_price_limit_x96))
    }

    /// Simulates a swap to move the pool price up to a target price.
    ///
    /// # Errors
    /// Returns error if pool is not initialized or price limit is invalid.
    pub fn swap_to_higher_sqrt_price(
        &self,
        sqrt_price_limit_x96: U160,
    ) -> anyhow::Result<SwapQuote> {
        self.quote_swap(I256::MAX, false, Some(sqrt_price_limit_x96))
    }

    // panics-doc-ok (transitive via check_if_initialized)
    /// Finds the maximum trade size that produces a target slippage (including fees).
    ///
    /// Uses binary search to find the largest trade size that results in slippage
    /// at or below the target. The method iteratively simulates swaps at different
    /// sizes until it converges to the optimal size within the specified tolerance.
    ///
    /// # Returns
    /// The maximum trade size (U256) that produces the target slippage
    ///
    /// # Errors
    /// Returns error if:
    /// - Impact is zero or exceeds 100% (10000 bps)
    /// - Pool is not initialized
    /// - Swap simulations fail
    ///
    /// # Panics
    ///
    /// Panics if pool is not initialized.
    pub fn size_for_impact_bps(&self, impact_bps: u32, zero_for_one: bool) -> anyhow::Result<U256> {
        let config = size_estimator::EstimationConfig::default();
        size_estimator::size_for_impact_bps(self, impact_bps, zero_for_one, &config)
    }

    /// Finds the maximum trade size with search diagnostics.
    /// This is the detailed version of [`Self::size_for_impact_bps`] that returns
    /// extensive information about the search process.It is useful for debugging,
    /// monitoring, and analyzing search behavior in production.
    ///
    /// # Returns
    /// Detailed result with size and search diagnostics
    ///
    /// # Errors
    /// Returns error if:
    /// - Impact is zero or exceeds 100% (10000 bps)
    /// - Pool is not initialized
    /// - Swap simulations fail
    pub fn size_for_impact_bps_detailed(
        &self,
        impact_bps: u32,
        zero_for_one: bool,
    ) -> anyhow::Result<size_estimator::SizeForImpactResult> {
        let config = size_estimator::EstimationConfig::default();
        size_estimator::size_for_impact_bps_detailed(self, impact_bps, zero_for_one, &config)
    }

    /// Validates that the price limit is in the correct direction for the swap.
    ///
    /// # Errors
    /// Returns error if price limit violates swap direction constraints.
    fn validate_price_limit(
        &self,
        limit_price_sqrt: U160,
        zero_for_one: bool,
    ) -> anyhow::Result<()> {
        if zero_for_one {
            // Swapping token0 for token1: price must decrease
            if limit_price_sqrt >= self.state.price_sqrt_ratio_x96 {
                anyhow::bail!("Price limit must be less than current price for zero_for_one swaps");
            }
        } else {
            // Swapping token1 for token0: price must increase
            if limit_price_sqrt <= self.state.price_sqrt_ratio_x96 {
                anyhow::bail!(
                    "Price limit must be greater than current price for one_for_zero swaps"
                );
            }
        }

        Ok(())
    }

    /// Processes a mint (liquidity add) event from historical data.
    ///
    /// Updates pool state when liquidity is added to a position, validates ticks,
    /// and delegates to internal liquidity management methods.
    ///
    /// # Errors
    ///
    /// This function returns an error if:
    /// - Pool is not initialized.
    /// - Tick range is invalid or not properly spaced.
    /// - Position updates fail.
    pub fn process_mint(&mut self, update: &PoolLiquidityUpdate) -> anyhow::Result<()> {
        self.check_if_initialized();

        if self.check_if_already_processed(update.block, update.transaction_index, update.log_index)
        {
            return Ok(());
        }

        self.validate_ticks(update.tick_lower, update.tick_upper)?;
        self.add_liquidity(
            &update.owner,
            update.tick_lower,
            update.tick_upper,
            update.position_liquidity,
            update.amount0,
            update.amount1,
        )?;

        self.analytics.total_mints += 1;
        self.last_processed_event = Some(BlockPosition::new(
            update.block,
            update.transaction_hash.clone(),
            update.transaction_index,
            update.log_index,
        ));
        self.update_reporter_if_enabled(update.block);
        self.update_liquidity_analytics();

        Ok(())
    }

    /// Internal helper to add liquidity to a position.
    ///
    /// Updates position state, tracks deposited amounts, and manages tick maps.
    /// Called by both historical event processing and simulated operations.
    fn add_liquidity(
        &mut self,
        owner: &Address,
        tick_lower: i32,
        tick_upper: i32,
        liquidity: u128,
        amount0: U256,
        amount1: U256,
    ) -> anyhow::Result<()> {
        let liquidity_delta = i128::try_from(liquidity)
            .map_err(|_| anyhow::anyhow!("Liquidity {liquidity} exceeds i128::MAX"))?;
        self.update_position(
            owner,
            tick_lower,
            tick_upper,
            liquidity_delta,
            amount0,
            amount1,
        )?;

        // Track deposited amounts
        self.analytics.total_amount0_deposited += amount0;
        self.analytics.total_amount1_deposited += amount1;

        Ok(())
    }

    // panics-doc-ok (transitive via check_if_initialized)
    /// Executes a simulated mint (liquidity addition) operation.
    ///
    /// Calculates required token amounts for the specified liquidity amount,
    /// updates pool state, and returns the resulting mint event.
    ///
    /// # Errors
    ///
    /// This function returns an error if:
    /// - Pool is not initialized.
    /// - Tick range is invalid.
    /// - Amount calculations fail.
    ///
    /// # Panics
    ///
    /// Panics if the current sqrt price has not been initialized.
    pub fn execute_mint(
        &mut self,
        recipient: Address,
        block: BlockPosition,
        tick_lower: i32,
        tick_upper: i32,
        liquidity: u128,
    ) -> anyhow::Result<PoolLiquidityUpdate> {
        self.check_if_initialized();
        self.validate_ticks(tick_lower, tick_upper)?;
        let (amount0, amount1) = get_amounts_for_liquidity(
            self.state.price_sqrt_ratio_x96,
            tick_lower,
            tick_upper,
            liquidity,
            true,
        );
        self.add_liquidity(
            &recipient, tick_lower, tick_upper, liquidity, amount0, amount1,
        )?;

        self.analytics.total_mints += 1;
        let event = PoolLiquidityUpdate::new(
            self.pool.chain.clone(),
            self.pool.dex.clone(),
            self.pool.instrument_id,
            self.pool.pool_identifier,
            PoolLiquidityUpdateType::Mint,
            block.number,
            block.transaction_hash,
            block.transaction_index,
            block.log_index,
            None,
            recipient,
            liquidity,
            amount0,
            amount1,
            tick_lower,
            tick_upper,
            None,
        );

        Ok(event)
    }

    /// Processes a burn (liquidity removal) event from historical data.
    ///
    /// Updates pool state when liquidity is removed from a position. Uses negative
    /// liquidity delta to reduce the position size and tracks withdrawn amounts.
    ///
    /// # Errors
    ///
    /// This function returns an error if:
    /// - Pool is not initialized.
    /// - Tick range is invalid.
    /// - Position updates fail.
    pub fn process_burn(&mut self, update: &PoolLiquidityUpdate) -> anyhow::Result<()> {
        self.check_if_initialized();

        if self.check_if_already_processed(update.block, update.transaction_index, update.log_index)
        {
            return Ok(());
        }
        self.validate_ticks(update.tick_lower, update.tick_upper)?;

        // Update the position with a negative liquidity delta for the burn
        let liquidity_delta = i128::try_from(update.position_liquidity).map_err(|_| {
            anyhow::anyhow!("Liquidity {} exceeds i128::MAX", update.position_liquidity)
        })?;
        self.update_position(
            &update.owner,
            update.tick_lower,
            update.tick_upper,
            -liquidity_delta,
            update.amount0,
            update.amount1,
        )?;

        self.analytics.total_burns += 1;
        self.last_processed_event = Some(BlockPosition::new(
            update.block,
            update.transaction_hash.clone(),
            update.transaction_index,
            update.log_index,
        ));
        self.update_reporter_if_enabled(update.block);
        self.update_liquidity_analytics();

        Ok(())
    }

    // panics-doc-ok (transitive via check_if_initialized)
    /// Executes a simulated burn (liquidity removal) operation.
    ///
    /// Calculates token amounts that would be withdrawn for the specified liquidity,
    /// updates pool state, and returns the resulting burn event.
    ///
    /// # Errors
    ///
    /// This function returns an error if:
    /// - Pool is not initialized.
    /// - Tick range is invalid.
    /// - Amount calculations fail.
    /// - Insufficient liquidity in position.
    ///
    /// # Panics
    ///
    /// Panics if the current sqrt price has not been initialized.
    pub fn execute_burn(
        &mut self,
        recipient: Address,
        block: BlockPosition,
        tick_lower: i32,
        tick_upper: i32,
        liquidity: u128,
    ) -> anyhow::Result<PoolLiquidityUpdate> {
        self.check_if_initialized();
        self.validate_ticks(tick_lower, tick_upper)?;
        let (amount0, amount1) = get_amounts_for_liquidity(
            self.state.price_sqrt_ratio_x96,
            tick_lower,
            tick_upper,
            liquidity,
            false,
        );

        // Update the position with a negative liquidity delta for the burn
        let liquidity_delta = i128::try_from(liquidity)
            .map_err(|_| anyhow::anyhow!("Liquidity {liquidity} exceeds i128::MAX"))?;
        self.update_position(
            &recipient,
            tick_lower,
            tick_upper,
            -liquidity_delta,
            amount0,
            amount1,
        )?;

        self.analytics.total_burns += 1;
        let event = PoolLiquidityUpdate::new(
            self.pool.chain.clone(),
            self.pool.dex.clone(),
            self.pool.instrument_id,
            self.pool.pool_identifier,
            PoolLiquidityUpdateType::Burn,
            block.number,
            block.transaction_hash,
            block.transaction_index,
            block.log_index,
            None,
            recipient,
            liquidity,
            amount0,
            amount1,
            tick_lower,
            tick_upper,
            None,
        );

        Ok(event)
    }

    /// Processes a fee collect event from historical data.
    ///
    /// Updates position state when accumulated fees are collected. Finds the
    /// position and delegates fee collection to the position object.
    ///
    /// Note: Tick validation is intentionally skipped to match Uniswap V3 behavior.
    /// Invalid positions have no fees to collect, so they're silently ignored.
    ///
    /// # Errors
    ///
    /// This function returns an error if:
    /// - Pool is not initialized.
    pub fn process_collect(&mut self, collect: &PoolFeeCollect) -> anyhow::Result<()> {
        self.check_if_initialized();

        if self.check_if_already_processed(
            collect.block,
            collect.transaction_index,
            collect.log_index,
        ) {
            return Ok(());
        }
        let position_key =
            PoolPosition::get_position_key(&collect.owner, collect.tick_lower, collect.tick_upper);

        if let Some(position) = self.positions.get_mut(&position_key) {
            position.collect_fees(collect.amount0, collect.amount1);
        }

        // Cleanup position if it became empty after collecting all fees
        self.cleanup_position_if_empty(&position_key);

        self.analytics.total_amount0_collected += U256::from(collect.amount0);
        self.analytics.total_amount1_collected += U256::from(collect.amount1);

        self.analytics.total_fee_collects += 1;
        self.last_processed_event = Some(BlockPosition::new(
            collect.block,
            collect.transaction_hash.clone(),
            collect.transaction_index,
            collect.log_index,
        ));
        self.update_reporter_if_enabled(collect.block);
        self.update_liquidity_analytics();

        Ok(())
    }

    // panics-doc-ok (transitive via check_if_initialized)
    /// Processes a flash loan event from historical data.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Pool has no active liquidity.
    /// - Fee growth arithmetic overflows.
    ///
    /// # Panics
    ///
    /// Panics if the pool has not been initialized.
    pub fn process_flash(&mut self, flash: &PoolFlash) -> anyhow::Result<()> {
        self.check_if_initialized();

        if self.check_if_already_processed(flash.block, flash.transaction_index, flash.log_index) {
            return Ok(());
        }

        self.update_flash_state(flash.paid0, flash.paid1)?;

        self.analytics.total_flashes += 1;
        self.last_processed_event = Some(BlockPosition::new(
            flash.block,
            flash.transaction_hash.clone(),
            flash.transaction_index,
            flash.log_index,
        ));
        self.update_reporter_if_enabled(flash.block);
        self.update_liquidity_analytics();

        Ok(())
    }

    /// Executes a simulated flash loan operation and returns the resulting event.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Mathematical operations overflow when calculating fees.
    /// - Pool has no active liquidity.
    /// - Fee growth arithmetic overflows.
    ///
    /// # Panics
    ///
    /// Panics if:
    /// - Pool is not initialized
    /// - Pool fee is not set
    pub fn execute_flash(
        &mut self,
        sender: Address,
        recipient: Address,
        block: BlockPosition,
        amount0: U256,
        amount1: U256,
    ) -> anyhow::Result<PoolFlash> {
        self.check_if_initialized();
        let fee_tier = self.pool.fee.expect("Pool fee should be initialized");

        // Calculate fees or paid0/paid1
        let paid0 = if amount0 > U256::ZERO {
            FullMath::mul_div_rounding_up(amount0, U256::from(fee_tier), U256::from(1_000_000))?
        } else {
            U256::ZERO
        };

        let paid1 = if amount1 > U256::ZERO {
            FullMath::mul_div_rounding_up(amount1, U256::from(fee_tier), U256::from(1_000_000))?
        } else {
            U256::ZERO
        };

        self.update_flash_state(paid0, paid1)?;
        self.analytics.total_flashes += 1;

        let flash_event = PoolFlash::new(
            self.pool.chain.clone(),
            self.pool.dex.clone(),
            self.pool.instrument_id,
            self.pool.pool_identifier,
            block.number,
            block.transaction_hash,
            block.transaction_index,
            block.log_index,
            None,
            sender,
            recipient,
            amount0,
            amount1,
            paid0,
            paid1,
        );

        Ok(flash_event)
    }

    /// Core flash loan state update logic.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - No active liquidity in pool
    /// - Fee growth arithmetic overflows
    fn update_flash_state(&mut self, paid0: U256, paid1: U256) -> anyhow::Result<()> {
        let liquidity = self.tick_map.liquidity;
        if liquidity == 0 {
            anyhow::bail!("No liquidity")
        }

        let fee_protocol_0 = self.state.fee_protocol % 16;
        let fee_protocol_1 = self.state.fee_protocol >> 4;

        // Process token0 fees
        if paid0 > U256::ZERO {
            let protocol_fee_0 = if fee_protocol_0 > 0 {
                paid0 / U256::from(fee_protocol_0)
            } else {
                U256::ZERO
            };

            if protocol_fee_0 > U256::ZERO {
                self.state.protocol_fees_token0 += protocol_fee_0;
            }

            let lp_fee_0 = paid0 - protocol_fee_0;
            let delta = FullMath::mul_div(lp_fee_0, Q128, U256::from(liquidity))?;
            self.state.fee_growth_global_0 += delta;
        }

        // Process token1 fees
        if paid1 > U256::ZERO {
            let protocol_fee_1 = if fee_protocol_1 > 0 {
                paid1 / U256::from(fee_protocol_1)
            } else {
                U256::ZERO
            };

            if protocol_fee_1 > U256::ZERO {
                self.state.protocol_fees_token1 += protocol_fee_1;
            }

            let lp_fee_1 = paid1 - protocol_fee_1;
            let delta = FullMath::mul_div(lp_fee_1, Q128, U256::from(liquidity))?;
            self.state.fee_growth_global_1 += delta;
        }

        Ok(())
    }

    /// Updates position state and tick maps when liquidity changes.
    ///
    /// Core internal method that handles position updates for both mints and burns.
    /// Updates tick maps, position tracking, fee growth, and active liquidity.
    fn update_position(
        &mut self,
        owner: &Address,
        tick_lower: i32,
        tick_upper: i32,
        liquidity_delta: i128,
        amount0: U256,
        amount1: U256,
    ) -> anyhow::Result<()> {
        let current_tick = self.state.current_tick;
        let position_key = PoolPosition::get_position_key(owner, tick_lower, tick_upper);
        let position = self
            .positions
            .entry(position_key)
            .or_insert(PoolPosition::new(*owner, tick_lower, tick_upper, 0));

        // Only validate when burning (negative liquidity_delta)
        if liquidity_delta < 0 {
            let burn_amount = liquidity_delta.unsigned_abs();
            if position.liquidity < burn_amount {
                anyhow::bail!(
                    "Position liquidity {} is less than the requested burn amount of {}",
                    position.liquidity,
                    burn_amount
                );
            }
        }

        // Update tickmaps.
        let flipped_lower = self.tick_map.update(
            tick_lower,
            current_tick,
            liquidity_delta,
            false,
            self.state.fee_growth_global_0,
            self.state.fee_growth_global_1,
        );
        let flipped_upper = self.tick_map.update(
            tick_upper,
            current_tick,
            liquidity_delta,
            true,
            self.state.fee_growth_global_0,
            self.state.fee_growth_global_1,
        );

        let (fee_growth_inside_0, fee_growth_inside_1) = self.tick_map.get_fee_growth_inside(
            tick_lower,
            tick_upper,
            current_tick,
            self.state.fee_growth_global_0,
            self.state.fee_growth_global_1,
        );
        position.update_liquidity(liquidity_delta);
        position.update_fees(fee_growth_inside_0, fee_growth_inside_1);
        position.update_amounts(liquidity_delta, amount0, amount1);

        // Update active liquidity if this position spans the current tick
        if tick_lower <= current_tick && current_tick < tick_upper {
            self.tick_map.liquidity = liquidity_math_add(self.tick_map.liquidity, liquidity_delta);
        }

        // Clear the ticks if they are flipped and burned
        if liquidity_delta < 0 && flipped_lower {
            self.tick_map.clear(tick_lower);
        }

        if liquidity_delta < 0 && flipped_upper {
            self.tick_map.clear(tick_upper);
        }

        Ok(())
    }

    /// Removes position from tracking if it's completely empty.
    ///
    /// This prevents accumulation of positions in the memory that are not used anymore.
    fn cleanup_position_if_empty(&mut self, position_key: &str) {
        if let Some(position) = self.positions.get(position_key)
            && position.is_empty()
        {
            log::debug!(
                "CLEANING UP EMPTY POSITION: owner={}, ticks=[{}, {}]",
                position.owner,
                position.tick_lower,
                position.tick_upper,
            );
            self.positions.remove(position_key);
        }
    }

    /// Calculates the liquidity utilization rate for the pool.
    ///
    /// The utilization rate measures what percentage of total deployed liquidity
    /// is currently active (in-range and earning fees) at the current price tick.
    pub fn liquidity_utilization_rate(&self) -> f64 {
        const PRECISION: u32 = 1_000_000; // 6 decimal places

        let total_liquidity = self.get_total_liquidity();
        let active_liquidity = self.get_active_liquidity();

        if total_liquidity == U256::ZERO {
            return 0.0;
        }
        let ratio = FullMath::mul_div(
            U256::from(active_liquidity),
            U256::from(PRECISION),
            total_liquidity,
        )
        .unwrap_or(U256::ZERO);

        // Safe to cast to u64: Since active_liquidity <= total_liquidity,
        // the ratio is guaranteed to be <= PRECISION (1_000_000), which fits in u64
        ratio.to::<u64>() as f64 / PRECISION as f64
    }

    /// Validates tick range for position operations.
    ///
    /// Ensures ticks are properly ordered, aligned to tick spacing, and within
    /// valid bounds. Used by all position-related operations.
    ///
    /// # Errors
    ///
    /// This function returns an error if:
    /// - `tick_lower >= tick_upper` (invalid range).
    /// - Ticks are not multiples of pool's tick spacing.
    /// - Ticks are outside MIN_TICK/MAX_TICK bounds.
    fn validate_ticks(&self, tick_lower: i32, tick_upper: i32) -> anyhow::Result<()> {
        if tick_lower >= tick_upper {
            anyhow::bail!("Invalid tick range: {tick_lower} >= {tick_upper}")
        }

        if tick_lower % self.pool.tick_spacing.unwrap() as i32 != 0
            || tick_upper % self.pool.tick_spacing.unwrap() as i32 != 0
        {
            anyhow::bail!(
                "Ticks {tick_lower} and {tick_upper} must be multiples of the tick spacing"
            )
        }

        if tick_lower < PoolTick::MIN_TICK || tick_upper > PoolTick::MAX_TICK {
            anyhow::bail!("Invalid tick bounds for {tick_lower} and {tick_upper}");
        }
        Ok(())
    }

    /// Updates all liquidity analytics.
    fn update_liquidity_analytics(&mut self) {
        self.analytics.liquidity_utilization_rate = self.liquidity_utilization_rate();
    }

    /// Returns the pool's active liquidity tracked by the tick map.
    ///
    /// This represents the effective liquidity available for trading at the current price.
    /// The tick map maintains this value efficiently by updating it during tick crossings
    /// as the price moves through different ranges.
    ///
    /// # Returns
    /// The active liquidity (u128) at the current tick from the tick map
    #[must_use]
    pub fn get_active_liquidity(&self) -> u128 {
        self.tick_map.liquidity
    }

    /// Calculates total liquidity by summing all individual positions at the current tick.
    ///
    /// This computes liquidity by iterating through all positions and summing those that
    /// span the current tick. Unlike [`Self::get_active_liquidity`], which returns the maintained
    /// tick map value, this method performs a fresh calculation from position data.
    #[must_use]
    pub fn get_total_liquidity_from_active_positions(&self) -> u128 {
        self.positions
            .values()
            .filter(|position| {
                position.liquidity > 0
                    && position.tick_lower <= self.state.current_tick
                    && self.state.current_tick < position.tick_upper
            })
            .map(|position| position.liquidity)
            .sum()
    }

    /// Calculates total liquidity across all positions, regardless of range status.
    #[must_use]
    pub fn get_total_liquidity(&self) -> U256 {
        self.positions
            .values()
            .map(|position| U256::from(position.liquidity))
            .fold(U256::ZERO, |acc, liq| acc + liq)
    }

    /// Restores the profiler state from a saved snapshot.
    ///
    /// This method allows resuming profiling from a previously saved state,
    /// enabling incremental processing without reprocessing all historical events.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Tick insertion into the tick map fails.
    ///
    /// # Panics
    ///
    /// Panics if the pool's tick spacing is not set.
    pub fn restore_from_snapshot(&mut self, snapshot: PoolSnapshot) -> anyhow::Result<()> {
        let liquidity = snapshot.state.liquidity;

        // Restore state
        self.state = snapshot.state;

        // Restore analytics (skip duration fields as they're debug-only)
        self.analytics.total_amount0_deposited = snapshot.analytics.total_amount0_deposited;
        self.analytics.total_amount1_deposited = snapshot.analytics.total_amount1_deposited;
        self.analytics.total_amount0_collected = snapshot.analytics.total_amount0_collected;
        self.analytics.total_amount1_collected = snapshot.analytics.total_amount1_collected;
        self.analytics.total_swaps = snapshot.analytics.total_swaps;
        self.analytics.total_mints = snapshot.analytics.total_mints;
        self.analytics.total_burns = snapshot.analytics.total_burns;
        self.analytics.total_fee_collects = snapshot.analytics.total_fee_collects;
        self.analytics.total_flashes = snapshot.analytics.total_flashes;

        // Rebuild positions AHashMap
        self.positions.clear();
        for position in snapshot.positions {
            let key = PoolPosition::get_position_key(
                &position.owner,
                position.tick_lower,
                position.tick_upper,
            );
            self.positions.insert(key, position);
        }

        // Rebuild tick_map
        self.tick_map = TickMap::new(
            self.pool
                .tick_spacing
                .expect("Pool tick spacing must be set"),
        );
        for tick in snapshot.ticks {
            self.tick_map.restore_tick(tick);
        }

        // Restore active liquidity
        self.tick_map.liquidity = liquidity;

        // Set last processed event
        self.last_processed_event = Some(snapshot.block_position);

        // Mark as initialized
        self.is_initialized = true;

        // Recalculate analytics
        self.update_liquidity_analytics();

        Ok(())
    }

    /// Gets a list of all initialized tick values.
    ///
    /// Returns tick values that have been initialized (have liquidity positions).
    /// Useful for understanding the liquidity distribution across price ranges.
    pub fn get_active_tick_values(&self) -> Vec<i32> {
        self.tick_map
            .get_all_ticks()
            .iter()
            .filter(|(_, tick)| self.tick_map.is_tick_initialized(tick.value))
            .map(|(tick_value, _)| *tick_value)
            .collect()
    }

    /// Gets the number of active ticks.
    #[must_use]
    pub fn get_active_tick_count(&self) -> usize {
        self.tick_map.active_tick_count()
    }

    /// Gets tick information for a specific tick value.
    ///
    /// Returns the tick data structure containing liquidity and fee information
    /// for the specified tick, if it exists.
    pub fn get_tick(&self, tick: i32) -> Option<&PoolTick> {
        self.tick_map.get_tick(tick)
    }

    /// Gets the current tick position of the pool.
    ///
    /// Returns the tick that corresponds to the current pool price.
    /// The pool must be initialized before calling this method.
    pub fn get_current_tick(&self) -> i32 {
        self.state.current_tick
    }

    /// Gets the total number of ticks tracked by the tick map.
    ///
    /// Returns count of all ticks that have ever been initialized,
    /// including those that may no longer have active liquidity.
    ///
    /// # Returns
    /// Total tick count in the tick map
    pub fn get_total_tick_count(&self) -> usize {
        self.tick_map.total_tick_count()
    }

    /// Gets position information for a specific owner and tick range.
    ///
    /// Looks up a position by its unique key (owner + tick range) and returns
    /// the position data if it exists.
    pub fn get_position(
        &self,
        owner: &Address,
        tick_lower: i32,
        tick_upper: i32,
    ) -> Option<&PoolPosition> {
        let position_key = PoolPosition::get_position_key(owner, tick_lower, tick_upper);
        self.positions.get(&position_key)
    }

    /// Returns a list of all currently active positions.
    ///
    /// Active positions are those with liquidity > 0 whose tick range includes
    /// the current pool tick, meaning they have tokens actively deployed in the pool
    /// and are earning fees from trades at the current price.
    ///
    /// # Returns
    ///
    /// A vector of references to active [`PoolPosition`] objects.
    pub fn get_active_positions(&self) -> Vec<&PoolPosition> {
        self.positions
            .values()
            .filter(|position| {
                let current_tick = self.get_current_tick();
                position.liquidity > 0
                    && position.tick_lower <= current_tick
                    && current_tick < position.tick_upper
            })
            .collect()
    }

    /// Returns a list of all positions tracked by the profiler.
    ///
    /// This includes both active and inactive positions, regardless of their
    /// liquidity or tick range relative to the current pool tick.
    ///
    /// # Returns
    ///
    /// A vector of references to all [`PoolPosition`] objects.
    pub fn get_all_positions(&self) -> Vec<&PoolPosition> {
        self.positions.values().collect()
    }

    /// Returns position keys for all tracked positions.
    pub fn get_all_position_keys(&self) -> Vec<(Address, i32, i32)> {
        self.get_all_positions()
            .iter()
            .map(|position| (position.owner, position.tick_lower, position.tick_upper))
            .collect()
    }

    /// Extracts a complete snapshot of the current pool state.
    ///
    /// Extracts and bundles the complete pool state including global variables,
    /// all liquidity positions, and the full tick distribution into a portable
    /// [`PoolSnapshot`] structure. This snapshot can be serialized, persisted
    /// to database, or used to restore pool state later.
    ///
    /// # Panics
    ///
    /// Panics if no events have been processed yet.
    pub fn extract_snapshot(&self) -> PoolSnapshot {
        let positions: Vec<_> = self.positions.values().cloned().collect();
        let ticks: Vec<_> = self.tick_map.get_all_ticks().values().copied().collect();

        let mut state = self.state.clone();
        state.liquidity = self.tick_map.liquidity;

        PoolSnapshot::new(
            self.pool.instrument_id,
            state,
            positions,
            ticks,
            self.analytics.clone(),
            self.last_processed_event
                .clone()
                .expect("No events processed yet"),
        )
    }

    /// Gets the count of positions that are currently active.
    ///
    /// Active positions are those with liquidity > 0 and whose tick range
    /// includes the current pool tick (meaning they have tokens in the pool).
    pub fn get_total_active_positions(&self) -> usize {
        self.positions
            .iter()
            .filter(|(_, position)| {
                let current_tick = self.get_current_tick();
                position.liquidity > 0
                    && position.tick_lower <= current_tick
                    && current_tick < position.tick_upper
            })
            .count()
    }

    /// Gets the count of positions that are currently inactive.
    ///
    /// Inactive positions are those that exist but don't span the current tick,
    /// meaning their liquidity is entirely in one token or the other.
    pub fn get_total_inactive_positions(&self) -> usize {
        self.positions.len() - self.get_total_active_positions()
    }

    /// Estimates the total amount of token0 in the pool.
    ///
    /// Calculates token0 balance by summing:
    /// - Token0 amounts from all active liquidity positions
    /// - Accumulated trading fees (approximated from fee growth)
    /// - Protocol fees collected
    pub fn estimate_balance_of_token0(&self) -> U256 {
        let mut total_amount0 = U256::ZERO;
        let current_sqrt_price = self.state.price_sqrt_ratio_x96;
        let current_tick = self.state.current_tick;
        let mut total_fees_0_collected: u128 = 0;

        // 1. Calculate token0 from active liquidity positions
        for position in self.positions.values() {
            if position.liquidity > 0 {
                if position.tick_upper <= current_tick {
                    // Position is below current price - no token0
                    continue;
                } else if position.tick_lower > current_tick {
                    // Position is above current price - all token0
                    let sqrt_ratio_a = get_sqrt_ratio_at_tick(position.tick_lower);
                    let sqrt_ratio_b = get_sqrt_ratio_at_tick(position.tick_upper);
                    let amount0 =
                        get_amount0_delta(sqrt_ratio_a, sqrt_ratio_b, position.liquidity, true);
                    total_amount0 += amount0;
                } else {
                    // Position is active - token0 from current price to upper tick
                    let sqrt_ratio_upper = get_sqrt_ratio_at_tick(position.tick_upper);
                    let amount0 = get_amount0_delta(
                        current_sqrt_price,
                        sqrt_ratio_upper,
                        position.liquidity,
                        true,
                    );
                    total_amount0 += amount0;
                }
            }

            total_fees_0_collected += position.total_amount0_collected;
        }

        // 2. Add accumulated swap fees (fee_growth_global represents total fees accumulated)
        // Note: In a real pool, fees are distributed as liquidity, but for balance estimation
        // we can use a simplified approach by converting fee growth to token amounts
        let fee_growth_0 = self.state.fee_growth_global_0;
        if fee_growth_0 > U256::ZERO {
            // Convert fee growth to actual token amount using FullMath for precision
            // Fee growth is in Q128.128 format, so we need to scale it properly
            let active_liquidity = self.get_active_liquidity();
            if active_liquidity > 0 {
                // fee_growth_global is fees per unit of liquidity in Q128.128
                // To get total fees: mul_div(fee_growth, liquidity, 2^128)
                if let Ok(total_fees_0) =
                    FullMath::mul_div(fee_growth_0, U256::from(active_liquidity), Q128)
                {
                    total_amount0 += total_fees_0;
                }
            }
        }

        let total_fees_0_left = fee_growth_0 - U256::from(total_fees_0_collected);

        // 4. Add protocol fees
        total_amount0 += self.state.protocol_fees_token0;

        total_amount0 + total_fees_0_left
    }

    /// Estimates the total amount of token1 in the pool.
    ///
    /// Calculates token1 balance by summing:
    /// - Token1 amounts from all active liquidity positions
    /// - Accumulated trading fees (approximated from fee growth)
    /// - Protocol fees collected
    pub fn estimate_balance_of_token1(&self) -> U256 {
        let mut total_amount1 = U256::ZERO;
        let current_sqrt_price = self.state.price_sqrt_ratio_x96;
        let current_tick = self.state.current_tick;
        let mut total_fees_1_collected: u128 = 0;

        // 1. Calculate token1 from active liquidity positions
        for position in self.positions.values() {
            if position.liquidity > 0 {
                if position.tick_lower > current_tick {
                    // Position is above current price - no token1
                    continue;
                } else if position.tick_upper <= current_tick {
                    // Position is below current price - all token1
                    let sqrt_ratio_a = get_sqrt_ratio_at_tick(position.tick_lower);
                    let sqrt_ratio_b = get_sqrt_ratio_at_tick(position.tick_upper);
                    let amount1 =
                        get_amount1_delta(sqrt_ratio_a, sqrt_ratio_b, position.liquidity, true);
                    total_amount1 += amount1;
                } else {
                    // Position is active - token1 from lower tick to current price
                    let sqrt_ratio_lower = get_sqrt_ratio_at_tick(position.tick_lower);
                    let amount1 = get_amount1_delta(
                        sqrt_ratio_lower,
                        current_sqrt_price,
                        position.liquidity,
                        true,
                    );
                    total_amount1 += amount1;
                }
            }

            // Sum collected fees
            total_fees_1_collected += position.total_amount1_collected;
        }

        // 2. Add accumulated swap fees for token1
        let fee_growth_1 = self.state.fee_growth_global_1;
        if fee_growth_1 > U256::ZERO {
            let active_liquidity = self.get_active_liquidity();
            if active_liquidity > 0 {
                // Convert fee growth to actual token amount using FullMath
                if let Ok(total_fees_1) =
                    FullMath::mul_div(fee_growth_1, U256::from(active_liquidity), Q128)
                {
                    total_amount1 += total_fees_1;
                }
            }
        }

        let total_fees_1_left = fee_growth_1 - U256::from(total_fees_1_collected);

        // 4. Add protocol fees
        total_amount1 += self.state.protocol_fees_token1;

        total_amount1 + total_fees_1_left
    }

    /// Sets the global fee growth for both tokens.
    ///
    /// This is primarily used for testing to simulate specific fee growth scenarios.
    /// In production, fee growth is updated through swap operations.
    ///
    /// # Arguments
    /// * `fee_growth_global_0` - New global fee growth for token0
    /// * `fee_growth_global_1` - New global fee growth for token1
    pub fn set_fee_growth_global(&mut self, fee_growth_global_0: U256, fee_growth_global_1: U256) {
        self.state.fee_growth_global_0 = fee_growth_global_0;
        self.state.fee_growth_global_1 = fee_growth_global_1;
    }

    /// Returns the total number of events processed.
    pub fn get_total_events(&self) -> u64 {
        self.analytics.total_swaps
            + self.analytics.total_mints
            + self.analytics.total_burns
            + self.analytics.total_fee_collects
            + self.analytics.total_flashes
    }

    /// Enables progress reporting for pool profiler event processing.
    ///
    /// When enabled, the profiler will automatically track and log progress
    /// as events are processed through the `process()` method.
    pub fn enable_reporting(&mut self, from_block: u64, total_blocks: u64, update_interval: u64) {
        self.reporter = Some(BlockchainSyncReporter::new(
            BlockchainSyncReportItems::PoolProfiling,
            from_block,
            total_blocks,
            update_interval,
        ));
        self.last_reported_block = from_block;
    }

    /// Finalizes reporting and logs final statistics.
    ///
    /// Should be called after all events have been processed to output
    /// the final summary of the profiler bootstrap operation.
    pub fn finalize_reporting(&mut self) {
        if let Some(reporter) = &self.reporter {
            reporter.log_final_stats();
        }
        self.reporter = None;
    }
}