tycho-simulation 0.529.1

Provides tools for interacting with protocol states, calculating spot prices, and quoting token swaps.
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
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
use std::{any::Any, collections::HashMap, sync::Arc};

use alloy::primitives::{Sign, I256, U256};
use num_bigint::BigUint;
use num_traits::Zero;
use serde::{Deserialize, Serialize};
use tracing::{error, trace};
use tycho_common::{
    dto::ProtocolStateDelta,
    models::token::Token,
    simulation::{
        errors::{SimulationError, TransitionError},
        protocol_sim::{
            Balances, BlockContext, GetAmountOutResult, PoolSwap, Price, ProtocolSim,
            QueryPoolSwapParams, SwapConstraint,
        },
    },
    Bytes,
};

use crate::{
    evm::{
        protocol::{
            clmm::clmm_swap_to_price,
            safe_math::{safe_add_u256, safe_sub_u256},
            u256_num::u256_to_biguint,
            utils::{
                add_fee_markup,
                slipstreams::{
                    aero_hook_fee::{AeroHookFee, Execution, HookFee, PoolOracle},
                    dynamic_fee_module::{get_dynamic_fee, DynamicFeeConfig, ResolvedFee},
                    observations::{observation_slot, Observation, Observations},
                    oracle_timestamp, raw_target_price,
                },
                uniswap::{
                    i24_be_bytes_to_i32, liquidity_math,
                    pool_tick::PoolTick,
                    sqrt_price_math::{
                        get_amount0_delta, get_amount1_delta, sqrt_price_q96_to_f64,
                    },
                    swap_math::{self, SwapStepResult},
                    swap_step_cache::{StepCacheKey, StepCacheRun, SwapStepCache},
                    tick_list::{TickInfo, TickList, TickListErrorKind},
                    tick_math::{
                        get_sqrt_ratio_at_tick_cached, MAX_SQRT_RATIO, MAX_TICK, MIN_SQRT_RATIO,
                        MIN_TICK,
                    },
                    StepComputation, SwapResults, SwapState,
                },
            },
        },
        query_pool_swap::price_to_f64_with_decimals,
    },
    protocol::models::BlockPositionAssumption,
};

// Cold-storage warmup on the first loop iteration:
// nextInitializedTickWithinOneWord first call (~3,000) vs warm (~1,060)
// calculateFees first call via cold getUnstakedFee STATICCALL (~19,050) vs warm (~6,055)
const FIRST_LOOP_OVERHEAD: u64 = 15_000;
// Steady-state per-loop: nextInitializedTickWithinOneWord (warm) + getSqrtRatioAtTick
// + computeSwapStep + calculateFees (warm) + toInt256x2 + EVM opcode overhead
const LOOP_GAS_COST: u64 = 12_500;
// cross(): updates tick fee growth and staked reward growth slots.
// Warm ticks (previously crossed, non-zero SSTORE slots) cost ~22k; cold ticks ~76k.
// We bias toward the cold end to prefer overestimation: 70k.
const TICK_CROSSING_GAS_COST: u64 = 70_000;
// When the module reads the oracle (`observed_twap`, whatever the scaling factor), fee() does a
// TWAP binary search on the observation ring buffer (~77k–91k gas) instead of a simple slot read
// (~18k–27k gas). This extra cost is added once per swap on top of the base.
const TWAP_FEE_OVERHEAD: u64 = 65_000;
// Pre/post loop overhead: fee(), slot0 reads, end-of-swap writes.
const SWAP_BASE_GAS: u64 = 125_000;
// AERO v1.1 pools call their swap hook, which runs the TWAP observe and stores the block fee,
// then record the swap on the pool tape and settle the gauge. Measured with eth_simulateV1 of
// single-step swaps on Base: ~312-317k for the pool's swap against ~140k for an Aerodrome
// Slipstreams pool. Replaces TWAP_FEE_OVERHEAD.
const AERO_HOOK_GAS: u64 = 160_000;
// Conservative max gas for a single swap. Used to cap get_limits iteration.
const MAX_SWAP_GAS: u64 = 16_700_000;
// Maximum initialized ticks that can be crossed within MAX_SWAP_GAS.
const MAX_TICKS_CROSSED: u64 = (MAX_SWAP_GAS - SWAP_BASE_GAS) / TICK_CROSSING_GAS_COST;

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AerodromeSlipstreamsState {
    id: String,
    /// Timestamp of the block a quote against this state is expected to execute in.
    ///
    /// Maintained by the stream decoder via [`ProtocolSim::apply_block`], not decoded from
    /// the pool: the fee module's initial-vs-dynamic branch keys on the *execution* block, which
    /// is the next block for a confirmed update and the still-open block for a flashblock
    /// update.
    execution_block_timestamp: u64,
    /// Number of the block a quote is expected to execute in; maintained like
    /// `execution_block_timestamp`. The AERO swap hook caches its fee per block number.
    #[serde(default)]
    execution_block_number: u64,
    liquidity: u128,
    sqrt_price: U256,
    observation_index: u16,
    observation_cardinality: u16,
    default_fee: u32,
    tick_spacing: i32,
    tick: i32,
    /// The tick list, shared by this state, its clones and the states its swaps return, so a quote
    /// does not copy it. Change it only through `Arc::make_mut`, which copies the list while
    /// another state shares it.
    ticks: Arc<TickList>,
    /// Swap steps already taken from this state, shared by its clones. The steps hold only for
    /// this state's price, tick, liquidity, fee and ticks. `delta_transition` and
    /// `clone_post_swap` replace the cache with an empty one, and any other code that changes
    /// those fields must do the same.
    #[serde(skip)]
    step_cache: SwapStepCache,
    /// The oracle observations. The ring is shared by this state, its clones and the states its
    /// swaps return; a swap records its observation in the state's own overlay (see
    /// [`Observations`]), so a quote copies no ring.
    observations: Observations,
    dfc: DynamicFeeConfig,
    /// Fee settings of an AERO v1.1 pool, whose swap hook sets the fee instead of a fee module.
    /// When set, `dfc` is unused.
    #[serde(default)]
    aero_hook: Option<AeroHookFee>,
    /// What quotes may assume about the swap's position within its execution block; see
    /// [`BlockPositionAssumption`].
    position_assumption: BlockPositionAssumption,
}

impl AerodromeSlipstreamsState {
    /// Creates a new instance of `AerodromeSlipstreamsState`.
    ///
    /// # Arguments
    /// - `id`: The id of the protocol component.
    /// - `execution_block_timestamp`: Timestamp of the block a quote is expected to execute in.
    /// - `liquidity`: The initial liquidity of the pool.
    /// - `sqrt_price`: The square root of the current price.
    /// - `observation_index`: The index of the current observation.
    /// - `observation_cardinality`: The cardinality of the observation.
    /// - `default_fee`: The default fee for the pool.
    /// - `tick_spacing`: The tick spacing for the pool.
    /// - `tick`: The current tick of the pool.
    /// - `ticks`: A vector of `TickInfo` representing the tick information for the pool.
    /// - `observations`: A vector of `Observation` representing the observation information for the
    ///   pool.
    /// - `dfc`: The dynamic fee configuration for the pool.
    #[expect(
        clippy::too_many_arguments,
        reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
    )]
    pub fn new(
        id: String,
        execution_block_timestamp: u64,
        liquidity: u128,
        sqrt_price: U256,
        observation_index: u16,
        observation_cardinality: u16,
        default_fee: u32,
        tick_spacing: i32,
        tick: i32,
        ticks: Vec<TickInfo>,
        observations: Vec<Observation>,
        dfc: DynamicFeeConfig,
    ) -> Result<Self, SimulationError> {
        let tick_list_spacing = u16::try_from(tick_spacing).map_err(|e| {
            SimulationError::InvalidInput(format!("Invalid tick spacing {tick_spacing}: {e}"), None)
        })?;
        let tick_list = TickList::from(tick_list_spacing, ticks)?;
        Ok(AerodromeSlipstreamsState {
            id,
            execution_block_timestamp,
            execution_block_number: 0,
            liquidity,
            sqrt_price,
            observation_index,
            observation_cardinality,
            default_fee,
            tick_spacing,
            tick,
            ticks: Arc::new(tick_list),
            step_cache: SwapStepCache::default(),
            observations: Observations::new(observations),
            dfc,
            aero_hook: None,
            position_assumption: BlockPositionAssumption::default(),
        })
    }

    /// Prices swaps with an AERO v1.1 swap hook instead of the dynamic fee module.
    pub fn with_aero_hook(mut self, hook: AeroHookFee) -> Self {
        self.aero_hook = Some(hook);
        self
    }

    /// Sets what quotes assume about the swap's position within its execution block.
    ///
    /// A consumer-side preference, independent of the pool's on-chain state.
    pub fn with_position_assumption(mut self, assumption: BlockPositionAssumption) -> Self {
        self.position_assumption = assumption;
        self
    }

    fn get_fee(&self) -> Result<ResolvedFee, SimulationError> {
        if let Some(hook) = &self.aero_hook {
            let fee = self.hook_fee(hook)?;
            return Ok(ResolvedFee { fee: fee.fee, observed_twap: fee.observed_twap });
        }
        get_dynamic_fee(
            &self.dfc,
            self.default_fee,
            self.tick,
            self.liquidity,
            self.observation_index,
            self.observation_cardinality,
            &self.observations,
            oracle_timestamp(self.execution_block_timestamp),
            self.position_assumption == BlockPositionAssumption::First,
        )
    }

    fn hook_fee(&self, hook: &AeroHookFee) -> Result<HookFee, SimulationError> {
        hook.resolve(
            &PoolOracle {
                tick: self.tick,
                liquidity: self.liquidity,
                observation_index: self.observation_index,
                observation_cardinality: self.observation_cardinality,
                observations: &self.observations,
            },
            self.default_fee,
            Execution {
                block: self.execution_block_number,
                timestamp: oracle_timestamp(self.execution_block_timestamp),
                first_in_block: self.position_assumption == BlockPositionAssumption::First,
            },
        )
    }

    /// Records the observation the pool would write for a swap that moved the tick from
    /// `self.tick` to `post_swap_tick`, so that a second swap chained onto this state in the same
    /// block resolves the dynamic fee instead of the initial fee.
    ///
    /// Mirrors `CLPool.swap`, which writes only when the tick moved and passes the pre-swap tick
    /// and liquidity. Must be called before the caller overwrites `tick`/`liquidity`.
    fn record_observation(&mut self, post_swap_tick: i32) -> Result<(), SimulationError> {
        if post_swap_tick == self.tick {
            return Ok(());
        }
        self.observation_index = self.observations.write(
            self.observation_index,
            oracle_timestamp(self.execution_block_timestamp),
            self.tick,
            self.liquidity,
            self.observation_cardinality,
        )?;
        Ok(())
    }

    /// Swaps token_in until `spot_price(token_in, token_out)` reaches the middle of the band
    /// `[target, target * (1 + tolerance)]`. Falls back to numerical search if recording the
    /// observation changes the fee enough to move the final price outside the band.
    fn swap_to_target_price(
        &self,
        params: &QueryPoolSwapParams,
        target: &Price,
        tolerance: f64,
    ) -> Result<PoolSwap, SimulationError> {
        let token_in = params.token_in();
        let token_out = params.token_out();
        let target_f64 = price_to_f64_with_decimals(target, token_in.decimals, token_out.decimals)?;
        if target_f64 == self.spot_price(token_in, token_out)? {
            return Ok(PoolSwap::new(BigUint::ZERO, BigUint::ZERO, Box::new(self.clone()), None));
        }
        let Some(limit) = raw_target_price(target, tolerance, self.get_fee()?.fee) else {
            return crate::evm::query_pool_swap::query_pool_swap(self, params);
        };
        // `limit` already strips the fee that `spot_price` adds, so the swap uses fee 0.
        let Ok((amount_in, amount_out, result)) = clmm_swap_to_price(
            self.sqrt_price,
            &token_in.address,
            &token_out.address,
            &limit,
            0,
            Sign::Positive,
            |zero_for_one, amount_specified, sqrt_price_limit| {
                self.swap(zero_for_one, amount_specified, Some(sqrt_price_limit))
            },
        ) else {
            return crate::evm::query_pool_swap::query_pool_swap(self, params);
        };

        let new_state = if amount_in.is_zero() {
            self.clone()
        } else {
            let (state, observation) =
                self.clone_post_swap(result.sqrt_price, result.tick.value(), result.liquidity);
            observation?;
            state
        };
        let final_spot = new_state.spot_price(token_in, token_out)?;
        if final_spot < target_f64 || final_spot > target_f64 * (1.0 + tolerance) {
            return crate::evm::query_pool_swap::query_pool_swap(self, params);
        }
        Ok(PoolSwap::new(amount_in, amount_out, Box::new(new_state), None))
    }

    /// A clone of this state with the final price, tick and liquidity of a swap, an empty step
    /// cache, and the price observation the swap writes. Returns the result of the observation
    /// write beside the state, so a caller can decide whether a failed write is an error.
    fn clone_post_swap(
        &self,
        sqrt_price: U256,
        tick: i32,
        liquidity: u128,
    ) -> (Self, Result<(), SimulationError>) {
        let mut state = self.clone();
        state.step_cache = SwapStepCache::default();
        // The block's first swap stores the block fee every later swap in the block pays.
        if let (Some(hook), Some(state_hook)) = (&self.aero_hook, state.aero_hook.as_mut()) {
            match self.hook_fee(hook) {
                Ok(HookFee { block_fee_to_store: Some(fee), .. }) => {
                    state_hook.store_block_fee(self.execution_block_number, fee)
                }
                Ok(_) => {}
                Err(err) => return (state, Err(err)),
            }
        }
        let observation = state.record_observation(tick);
        state.liquidity = liquidity;
        state.tick = tick;
        state.sqrt_price = sqrt_price;
        (state, observation)
    }

    fn swap(
        &self,
        zero_for_one: bool,
        amount_specified: I256,
        sqrt_price_limit: Option<U256>,
    ) -> Result<SwapResults, SimulationError> {
        if self.liquidity == 0 {
            return Err(SimulationError::RecoverableError("No liquidity".to_string()));
        }
        let price_limit = if let Some(limit) = sqrt_price_limit {
            limit
        } else if zero_for_one {
            safe_add_u256(MIN_SQRT_RATIO, U256::from(1u64))?
        } else {
            safe_sub_u256(MAX_SQRT_RATIO, U256::from(1u64))?
        };

        let price_limit_valid = if zero_for_one {
            price_limit > MIN_SQRT_RATIO && price_limit < self.sqrt_price
        } else {
            price_limit < MAX_SQRT_RATIO && price_limit > self.sqrt_price
        };
        if !price_limit_valid {
            return Err(SimulationError::InvalidInput("Price limit out of range".into(), None));
        }

        let exact_input = amount_specified > I256::from_raw(U256::from(0u64));

        let mut state = SwapState {
            amount_remaining: amount_specified,
            amount_calculated: I256::from_raw(U256::from(0u64)),
            sqrt_price: self.sqrt_price,
            tick: self.tick.into(),
            liquidity: self.liquidity,
        };
        let resolved_fee = self.get_fee()?;
        let twap_overhead = if self.aero_hook.is_some() {
            AERO_HOOK_GAS
        } else if resolved_fee.observed_twap {
            TWAP_FEE_OVERHEAD
        } else {
            0
        };
        let mut gas_used = U256::from(SWAP_BASE_GAS + twap_overhead);
        let mut n_loops = 0;

        let fee = resolved_fee.fee;
        // Only exact-input swaps with no price limit use the step cache. The cache finds a step by
        // its input, which an exact-output swap does not know. A cached step can also lie past a
        // price limit.
        let cache_key = if exact_input && sqrt_price_limit.is_none() {
            StepCacheKey::new(self.sqrt_price, state.tick.value(), self.liquidity, fee, gas_used)
        } else {
            None
        };
        let mut cache_run = StepCacheRun::new(
            &self.step_cache,
            zero_for_one,
            cache_key,
            amount_specified.unsigned_abs(),
        );
        if let Some(progress) = cache_run.apply_cached_progress(&mut state) {
            gas_used = progress.gas;
            // The first loop's overhead is in the cached gas already.
            n_loops = progress.steps_taken;
        }
        while state.amount_remaining != I256::from_raw(U256::from(0u64)) &&
            state.sqrt_price != price_limit
        {
            let (mut next_tick, next_tick_info) = match self
                .ticks
                .next_initialized_tick_within_one_word(state.tick.value(), zero_for_one)
            {
                Ok((tick, info)) => (tick, info),
                Err(tick_err) => match tick_err.kind {
                    TickListErrorKind::TicksExeeded => {
                        let (new_state, observation) = self.clone_post_swap(
                            state.sqrt_price,
                            state.tick.value(),
                            state.liquidity,
                        );
                        // Best effort in an error path: a failed write only degrades the fee of
                        // a chained simulation on this partial result, and must not mask the
                        // more informative TicksExceeded error below.
                        if let Err(record_err) = observation {
                            trace!(%record_err, "skipping observation write on partial result");
                        }
                        return Err(SimulationError::InvalidInput(
                            "Ticks exceeded".into(),
                            Some(GetAmountOutResult::new(
                                u256_to_biguint(state.amount_calculated.abs().into_raw()),
                                u256_to_biguint(gas_used),
                                Box::new(new_state),
                            )),
                        ));
                    }
                    TickListErrorKind::BelowSmallest | TickListErrorKind::AtOrAboveLargest => {
                        return Err(SimulationError::FatalError("Unknown error".to_string()))
                    }
                },
            };

            next_tick = next_tick.clamp(MIN_TICK, MAX_TICK);

            let sqrt_price_start = state.sqrt_price;
            let sqrt_price_next = match next_tick_info {
                Some(info) => info.sqrt_price,
                None => get_sqrt_ratio_at_tick_cached(next_tick)?,
            };
            let SwapStepResult { sqrt_price, amount_in_with_fee, amount_out } =
                swap_math::compute_swap_step(
                    state.sqrt_price,
                    AerodromeSlipstreamsState::get_sqrt_ratio_target(
                        sqrt_price_next,
                        price_limit,
                        zero_for_one,
                    ),
                    state.liquidity,
                    state.amount_remaining,
                    fee,
                )?;
            state.sqrt_price = sqrt_price;

            let step = StepComputation {
                sqrt_price_start,
                tick_next: next_tick,
                sqrt_price_next,
                amount_in_with_fee,
                amount_out,
            };
            if exact_input {
                state.amount_remaining -=
                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
                        .unwrap();
                state.amount_calculated -=
                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
            } else {
                state.amount_remaining +=
                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_out).unwrap();
                state.amount_calculated +=
                    I256::checked_from_sign_and_abs(Sign::Positive, step.amount_in_with_fee)
                        .unwrap();
            }
            if state.sqrt_price == step.sqrt_price_next {
                if let Some(info) = next_tick_info {
                    let liquidity_raw = info.net_liquidity;
                    let liquidity_net = if zero_for_one { -liquidity_raw } else { liquidity_raw };
                    state.liquidity =
                        liquidity_math::add_liquidity_delta(state.liquidity, liquidity_net)?;
                    gas_used = safe_add_u256(gas_used, U256::from(TICK_CROSSING_GAS_COST))?;
                }
                state.tick =
                    PoolTick::from(if zero_for_one { step.tick_next - 1 } else { step.tick_next });
            } else if state.sqrt_price != step.sqrt_price_start {
                state.tick = PoolTick::at_sqrt_price(state.sqrt_price)?;
            }
            gas_used = safe_add_u256(gas_used, U256::from(LOOP_GAS_COST))?;
            if n_loops == 0 {
                gas_used = safe_add_u256(gas_used, U256::from(FIRST_LOOP_OVERHEAD))?;
            }
            n_loops += 1;
            cache_run.cache_progress(&step, &state, gas_used);
        }
        Ok(SwapResults {
            amount_calculated: state.amount_calculated,
            amount_specified,
            amount_remaining: state.amount_remaining,
            sqrt_price: state.sqrt_price,
            liquidity: state.liquidity,
            tick: state.tick,
            gas_used,
        })
    }

    fn get_sqrt_ratio_target(
        sqrt_price_next: U256,
        sqrt_price_limit: U256,
        zero_for_one: bool,
    ) -> U256 {
        let cond1 = if zero_for_one {
            sqrt_price_next < sqrt_price_limit
        } else {
            sqrt_price_next > sqrt_price_limit
        };

        if cond1 {
            sqrt_price_limit
        } else {
            sqrt_price_next
        }
    }
}

#[typetag::serde]
impl ProtocolSim for AerodromeSlipstreamsState {
    fn fee(&self) -> f64 {
        match self.get_fee() {
            Ok(resolved) => resolved.fee as f64 / 1_000_000.0,
            Err(err) => {
                error!(
                    pool = %self.id,
                    execution_block_timestamp = self.execution_block_timestamp,
                    %err,
                    "Error while calculating dynamic fee"
                );
                f64::MAX / 1_000_000.0
            }
        }
    }

    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
        let price = if base < quote {
            sqrt_price_q96_to_f64(self.sqrt_price, base.decimals, quote.decimals)?
        } else {
            1.0f64 / sqrt_price_q96_to_f64(self.sqrt_price, quote.decimals, base.decimals)?
        };
        Ok(add_fee_markup(price, self.get_fee()?.fee as f64 / 1_000_000.0))
    }

    fn get_amount_out(
        &self,
        amount_in: BigUint,
        token_in: &Token,
        token_out: &Token,
    ) -> Result<GetAmountOutResult, SimulationError> {
        let zero_for_one = token_in < token_out;
        let amount_specified = I256::checked_from_sign_and_abs(
            Sign::Positive,
            U256::from_be_slice(&amount_in.to_bytes_be()),
        )
        .ok_or_else(|| {
            SimulationError::InvalidInput("I256 overflow: amount_in".to_string(), None)
        })?;

        let result = self.swap(zero_for_one, amount_specified, None)?;

        trace!(?amount_in, ?token_in, ?token_out, ?zero_for_one, ?result, "SLIPSTREAMS SWAP");
        let (new_state, observation) =
            self.clone_post_swap(result.sqrt_price, result.tick.value(), result.liquidity);
        observation?;

        Ok(GetAmountOutResult::new(
            u256_to_biguint(
                result
                    .amount_calculated
                    .abs()
                    .into_raw(),
            ),
            u256_to_biguint(result.gas_used),
            Box::new(new_state),
        ))
    }

    fn get_limits(
        &self,
        sell_token: Bytes,
        buy_token: Bytes,
    ) -> Result<(BigUint, BigUint), SimulationError> {
        // If the pool has no liquidity, return zeros for both limits
        if self.liquidity == 0 {
            return Ok((BigUint::zero(), BigUint::zero()));
        }
        // The limits do not depend on the fee, but a quote does: a pool whose fee cannot be
        // resolved fails every quote, so it reports no limits to size one from.
        self.get_fee()?;

        let zero_for_one = sell_token < buy_token;
        let mut current_tick = self.tick;
        let mut current_sqrt_price = self.sqrt_price;
        let mut current_liquidity = self.liquidity;
        let mut total_amount_in = U256::from(0u64);
        let mut total_amount_out = U256::from(0u64);

        // Iterate through all ticks in the direction of the swap
        // Continues until there is no more liquidity in the pool or no more ticks to process
        let mut ticks_crossed: u64 = 0;
        while let Ok((tick, next_tick_info)) = self
            .ticks
            .next_initialized_tick_within_one_word(current_tick, zero_for_one)
        {
            if ticks_crossed >= MAX_TICKS_CROSSED {
                break;
            }
            ticks_crossed += 1;
            // Clamp the tick value to ensure it's within valid range
            let next_tick = tick.clamp(MIN_TICK, MAX_TICK);

            let sqrt_price_next = match next_tick_info {
                Some(info) => info.sqrt_price,
                None => get_sqrt_ratio_at_tick_cached(next_tick)?,
            };

            // Calculate the amount of tokens swapped when moving from current_sqrt_price to
            // sqrt_price_next. Direction determines which token is being swapped in vs out
            let (amount_in, amount_out) = if zero_for_one {
                let amount0 = get_amount0_delta(
                    sqrt_price_next,
                    current_sqrt_price,
                    current_liquidity,
                    true,
                )?;
                let amount1 = get_amount1_delta(
                    sqrt_price_next,
                    current_sqrt_price,
                    current_liquidity,
                    false,
                )?;
                (amount0, amount1)
            } else {
                let amount0 = get_amount0_delta(
                    sqrt_price_next,
                    current_sqrt_price,
                    current_liquidity,
                    false,
                )?;
                let amount1 = get_amount1_delta(
                    sqrt_price_next,
                    current_sqrt_price,
                    current_liquidity,
                    true,
                )?;
                (amount1, amount0)
            };

            // Accumulate total amounts for this tick range
            total_amount_in = safe_add_u256(total_amount_in, amount_in)?;
            total_amount_out = safe_add_u256(total_amount_out, amount_out)?;

            // If this tick is "initialized" (meaning its someone's position boundary), update the
            // liquidity when crossing it
            // For zero_for_one, liquidity is removed when crossing a tick
            // For one_for_zero, liquidity is added when crossing a tick
            if let Some(info) = next_tick_info {
                let liquidity_raw = info.net_liquidity;
                let liquidity_delta = if zero_for_one { -liquidity_raw } else { liquidity_raw };
                current_liquidity =
                    liquidity_math::add_liquidity_delta(current_liquidity, liquidity_delta)?;
            }

            // Move to the next tick position
            current_tick = if zero_for_one { next_tick - 1 } else { next_tick };
            current_sqrt_price = sqrt_price_next;
        }

        Ok((u256_to_biguint(total_amount_in), u256_to_biguint(total_amount_out)))
    }

    fn delta_transition(
        &mut self,
        delta: ProtocolStateDelta,
        _tokens: &HashMap<Bytes, Token>,
        _balances: &Balances,
    ) -> Result<(), TransitionError> {
        // Swap steps taken from the old state do not hold for the new one.
        self.step_cache = SwapStepCache::default();
        // apply attribute changes
        if let Some(liquidity) = delta
            .updated_attributes
            .get("liquidity")
        {
            // This is a hotfix because if the liquidity has never been updated after creation, it's
            // currently encoded as H256::zero(), therefore, we can't decode this as u128.
            // We can remove this once it has been fixed on the tycho side.
            let liq_16_bytes = if liquidity.len() == 32 {
                // Make sure it only happens for 0 values, otherwise error.
                if liquidity == &Bytes::zero(32) {
                    Bytes::from([0; 16])
                } else {
                    return Err(TransitionError::DecodeError(format!(
                        "Liquidity bytes too long for {liquidity}, expected 16",
                    )));
                }
            } else {
                liquidity.clone()
            };

            self.liquidity = u128::try_from(liq_16_bytes)?;
        }
        if let Some(sqrt_price) = delta
            .updated_attributes
            .get("sqrt_price_x96")
        {
            self.sqrt_price = U256::from_be_slice(sqrt_price);
        }
        if let Some(observation_index) = delta
            .updated_attributes
            .get("observationIndex")
        {
            self.observation_index = u16::try_from(observation_index.clone())?;
        }
        if let Some(observation_cardinality) = delta
            .updated_attributes
            .get("observationCardinality")
        {
            self.observation_cardinality = u16::try_from(observation_cardinality.clone())?;
        }
        if let Some(default_fee) = delta
            .updated_attributes
            .get("default_fee")
        {
            self.default_fee = u32::try_from(default_fee.clone())?;
        }
        if let Some(hook) = self.aero_hook.as_mut() {
            hook.update_from_attributes(&delta.updated_attributes)
                .map_err(TransitionError::DecodeError)?;
        } else {
            self.dfc
                .update_from_attributes(&delta.updated_attributes)
                .map_err(|err| {
                    TransitionError::DecodeError(format!(
                        "Failed to update dynamic fee module config: {err}"
                    ))
                })?;
        }
        if let Some(tick) = delta.updated_attributes.get("tick") {
            // This is a hotfix because if the tick has never been updated after creation, it's
            // currently encoded as H256::zero(), therefore, we can't decode this as i32.
            // We can remove this once it has been fixed on the tycho side.
            let ticks_4_bytes = if tick.len() == 32 {
                // Make sure it only happens for 0 values, otherwise error.
                if tick == &Bytes::zero(32) {
                    Bytes::from([0; 4])
                } else {
                    return Err(TransitionError::DecodeError(format!(
                        "Tick bytes too long for {tick}, expected 4"
                    )));
                }
            } else {
                tick.clone()
            };
            self.tick = i24_be_bytes_to_i32(&ticks_4_bytes);
        }

        // apply tick & observations changes
        for (key, value) in delta.updated_attributes.iter() {
            // tick liquidity keys are in the format "ticks/{tick_index}/net_liquidity"
            if key.starts_with("ticks/") {
                let parts: Vec<&str> = key.split('/').collect();
                Arc::make_mut(&mut self.ticks)
                    .set_tick_liquidity(
                        parts[1]
                            .parse::<i32>()
                            .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
                        i128::try_from(value.clone())?,
                    )
                    .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
            }

            if let Some(slot) = observation_slot(key) {
                let slot = slot.map_err(TransitionError::DecodeError)?;
                self.observations
                    .upsert_observation(slot, value)
                    .map_err(|err| TransitionError::DecodeError(format!("{key}: {err}")))?;
            }
        }
        // delete ticks - ignores deletes for attributes other than tick liquidity
        for key in delta.deleted_attributes.iter() {
            // tick liquidity keys are in the format "ticks/{tick_index}/net_liquidity"
            if key.starts_with("ticks/") {
                let parts: Vec<&str> = key.split('/').collect();
                Arc::make_mut(&mut self.ticks)
                    .set_tick_liquidity(
                        parts[1]
                            .parse::<i32>()
                            .map_err(|err| TransitionError::DecodeError(err.to_string()))?,
                        0,
                    )
                    .map_err(|err| TransitionError::DecodeError(err.to_string()))?;
            }

            if let Some(slot) = observation_slot(key) {
                let slot = slot.map_err(TransitionError::DecodeError)?;
                self.observations
                    .upsert_observation(slot, &[])
                    .map_err(|err| TransitionError::DecodeError(format!("{key}: {err}")))?;
            }
        }
        Ok(())
    }

    /// Re-emits only when the resolved fee actually changed: idle pools whose initial-vs-dynamic
    /// branch stays put return `false` indefinitely, and same-block flashblocks short-circuit on
    /// the unchanged timestamp.
    fn apply_block(&mut self, block: &BlockContext) -> bool {
        let timestamp = block.timestamp();
        if timestamp == self.execution_block_timestamp &&
            block.number() == self.execution_block_number
        {
            return false;
        }
        let fee_before = self.get_fee().ok();
        self.execution_block_timestamp = timestamp;
        self.execution_block_number = block.number();
        fee_before != self.get_fee().ok()
    }

    fn clone_box(&self) -> Box<dyn ProtocolSim> {
        Box::new(self.clone())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn eq(&self, other: &dyn ProtocolSim) -> bool {
        if let Some(other_state) = other
            .as_any()
            .downcast_ref::<AerodromeSlipstreamsState>()
        {
            let Ok(self_fee) = self.get_fee() else { return false };
            let Ok(other_fee) = other_state.get_fee() else { return false };

            self.liquidity == other_state.liquidity &&
                self.sqrt_price == other_state.sqrt_price &&
                self_fee == other_fee &&
                self.tick == other_state.tick &&
                self.ticks == other_state.ticks
        } else {
            false
        }
    }

    /// Answers [`SwapConstraint::PoolTargetPrice`] with one native swap and no `price_points`.
    /// [`SwapConstraint::TradeLimitPrice`] uses the numerical search.
    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
        match params.swap_constraint() {
            SwapConstraint::TradeLimitPrice { .. } => {
                crate::evm::query_pool_swap::query_pool_swap(self, params)
            }
            SwapConstraint::PoolTargetPrice {
                target,
                tolerance,
                min_amount_in: _,
                max_amount_in: _,
            } => {
                let swap = self.swap_to_target_price(params, target, *tolerance)?;
                let target = price_to_f64_with_decimals(
                    target,
                    params.token_in().decimals,
                    params.token_out().decimals,
                )?;
                let spot = swap
                    .new_state()
                    .spot_price(params.token_in(), params.token_out())?;
                if !tolerance.is_finite() ||
                    *tolerance < 0.0 ||
                    !(spot >= target && spot <= target * (1.0 + tolerance))
                {
                    return Err(SimulationError::RecoverableError(
                        "Aerodrome target-price search ended outside the requested tolerance"
                            .into(),
                    ));
                }
                Ok(swap)
            }
        }
    }
}

#[cfg(test)]
#[path = "aero_cl_replay_tests.rs"]
mod aero_cl_replay_tests;

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use alloy::primitives::{Sign, I256, U256};
    use rstest::rstest;
    use tycho_common::{models::Chain, simulation::errors::SimulationError};

    use super::*;
    use crate::evm::{
        protocol::utils::{
            slipstreams::{
                dynamic_fee_module::{DynamicFeeConfig, ZERO_FEE_INDICATOR},
                observations::Observation,
            },
            uniswap::{
                tick_list::TickInfo,
                tick_math::{
                    get_sqrt_ratio_at_tick, get_tick_at_sqrt_ratio, MAX_SQRT_RATIO, MIN_SQRT_RATIO,
                    MIN_TICK,
                },
            },
        },
        query_pool_swap::test_helpers::{target_price_params, to_price},
    };

    fn create_basic_test_pool() -> AerodromeSlipstreamsState {
        let sqrt_price = get_sqrt_ratio_at_tick(0).expect("Failed to calculate sqrt price");
        let ticks = vec![TickInfo::new(-120, 0).unwrap(), TickInfo::new(120, 0).unwrap()];
        AerodromeSlipstreamsState::new(
            "test-pool".to_string(),
            1_000_000,
            100_000_000_000_000_000_000u128,
            sqrt_price,
            0,
            1,
            3000,
            1,
            0,
            ticks,
            vec![Observation::default()],
            DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
        )
        .expect("Failed to create pool")
    }

    fn dynamic_fee_delta(dynamic_fee_module: [u8; 20]) -> ProtocolStateDelta {
        ProtocolStateDelta {
            component_id: "test-pool".to_string(),
            updated_attributes: HashMap::from([
                ("dynamic_fee_module".to_string(), Bytes::from(dynamic_fee_module)),
                ("dfc_baseFee".to_string(), Bytes::from(500_u32.to_be_bytes())),
                ("dfc_scalingFactor".to_string(), Bytes::from(0_u64.to_be_bytes())),
                ("dfc_feeCap".to_string(), Bytes::from(700_u32.to_be_bytes())),
                ("dfc_initialFeeEnabled".to_string(), Bytes::from([0_u8])),
                ("dfc_initialFee".to_string(), Bytes::from(0_u32.to_be_bytes())),
            ]),
            ..Default::default()
        }
    }

    /// Pool whose last swap wrote an observation at `last_observation_ts`, with the initial fee
    /// enabled (750 pips) and a dynamic component on top of a 2700 pip base.
    ///
    /// Built with the first-in-block assumption on: most tests here exercise the optimistic
    /// path. The worst-case-default tests switch it back to `BlockPositionAssumption::WorstCase`.
    fn initial_fee_pool(last_observation_ts: u32) -> AerodromeSlipstreamsState {
        let mut pool = create_basic_test_pool();
        pool.dfc = DynamicFeeConfig::new(2700, 30_000, 0, true, 750);
        pool.position_assumption = BlockPositionAssumption::First;
        pool.observations = Observations::new(vec![Observation {
            block_timestamp: last_observation_ts,
            initialized: true,
            ..Default::default()
        }]);
        pool
    }

    /// Replays Base block 50166683 on pool 0xdFe5F275020def30993f042174Fc2D335678b626
    /// (AERO/cbBTC), the pair of swaps from the original report:
    ///
    /// - tx 0x3b0a96e9bb376d74b4b99d651336c790b2b2b65a660491c28cae3df1a5d69def (index 67), the
    ///   block's first tick-moving swap, paid the 750 pip initial fee;
    /// - tx 0xe934500efe7f9ef56370daf4859c21c3a439d998a80b5bd2e5a117e3045021e1 (index 154) paid the
    ///   2700 pip dynamic fee.
    ///
    /// Pool state is reconstructed from archive RPC at the parent block 50166682 (slot0,
    /// liquidity, observations[213], DynamicSwapFeeModule config); swap amounts come from the
    /// on-chain Swap events. Both outputs must match wei-exact, and the end-of-block oracle
    /// index must match the chain (213 -> 214: exactly one observation written).
    #[test]
    fn replays_base_block_50166683_swap_pair_wei_exact() {
        // The fixture carries only the newest slot: at a zero scaling factor the module's fee does
        // not depend on the oracle, and the swap's `write` reads only the current slot.
        let mut observations = vec![Observation::default(); 213];
        observations.push(Observation {
            block_timestamp: 1_787_122_711, // == parent block ts: the pool traded in that block
            tick_cumulative: -18_995_710_863_218,
            seconds_per_liquidity_cumulative_x128: U256::from_str(
                "42501948193164408449462610706599523891176959",
            )
            .unwrap(),
            initialized: true,
        });

        let mut pool = AerodromeSlipstreamsState::new(
            "0xdFe5F275020def30993f042174Fc2D335678b626".to_string(),
            1_787_122_711, // seed: decoded at the parent block
            1_128_781_556_759_264_064u128,
            U256::from_str("1979649713595747421731").unwrap(),
            213,
            360,
            2700, // tickSpacingToFee(200)
            200,
            -350_116,
            // No initialized tick is crossed (liquidity is unchanged across both swaps);
            // zero-net bounds outside the traversed range stand in for the full tick map.
            vec![TickInfo::new(-351_000, 0).unwrap(), TickInfo::new(-349_000, 0).unwrap()],
            observations,
            DynamicFeeConfig::new(2700, 0, 0, true, 750),
        )
        .expect("state should build")
        // The replayed swap was in fact the block's first: the optimistic mode reproduces it.
        .with_position_assumption(BlockPositionAssumption::First);

        // The quotes execute in block 50166683 (ts 1_787_122_713).
        assert!(pool.apply_block(&BlockContext::new(50_166_683, 1_787_122_713)));

        let aero = Token::new(
            &Bytes::from_str("0x940181a94A35A4569E4529A3CDfB74e38FD98631").unwrap(),
            "AERO",
            18,
            0,
            &[Some(10_000)],
            Chain::Base,
            100,
        );
        let cbbtc = Token::new(
            &Bytes::from_str("0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf").unwrap(),
            "cbBTC",
            8,
            0,
            &[Some(10_000)],
            Chain::Base,
            100,
        );

        assert_eq!(pool.fee(), 750.0 / 1_000_000.0);
        let first = pool
            .get_amount_out(BigUint::from(1_688_626u32), &cbbtc, &aero)
            .expect("first swap should succeed");
        assert_eq!(first.amount, BigUint::from(2_702_489_253_591_513_843_346u128));

        assert_eq!(first.new_state.fee(), 2700.0 / 1_000_000.0);
        let second = first
            .new_state
            .get_amount_out(BigUint::from(450_733u32), &cbbtc, &aero)
            .expect("second swap should succeed");
        assert_eq!(second.amount, BigUint::from(719_894_300_964_297_656_776u128));

        let replayed = first
            .new_state
            .as_any()
            .downcast_ref::<AerodromeSlipstreamsState>()
            .expect("state type");
        assert_eq!(replayed.observation_index, 214, "chain slot0 shows 214 after the block");
        assert_eq!(
            replayed
                .observations
                .timestamp_at(214, 360)
                .unwrap(),
            1_787_122_713
        );
    }

    #[test]
    fn ticks_exceeded_partial_result_still_records_the_observation() {
        // The partial result carried inside the TicksExceeded error must price a chained swap
        // with the dynamic fee, exactly like a successful swap's new_state.
        let mut pool = initial_fee_pool(1_000);
        pool.apply_block(&BlockContext::new(101, 1_002));
        let token_a =
            Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
        let token_b =
            Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);

        let err = pool
            .get_amount_out(
                BigUint::from(1_000_000_000_000_000_000_000_000u128),
                &token_a,
                &token_b,
            )
            .expect_err("swap must exhaust the tick list");
        let SimulationError::InvalidInput(_, Some(partial)) = err else {
            panic!("expected a partial result, got {err:?}");
        };

        assert_eq!(partial.new_state.fee(), 2700.0 / 1_000_000.0);
    }

    #[test]
    fn ring_that_cannot_answer_observe_fails_limits_like_quotes() {
        // A non-zero scaling factor, with the slots around the 600 s target missing from this
        // copy of the ring: the fee is unknown, so no quote can be given and no limit either.
        let mut pool = create_basic_test_pool();
        pool.dfc = DynamicFeeConfig::new(0, 10_000, 1_000_000, false, 0);
        pool.observation_index = 5;
        pool.observation_cardinality = 300;
        let mut slots = vec![Observation::default(); 7];
        slots[5] =
            Observation { block_timestamp: 999_990, initialized: true, ..Default::default() };
        slots[6] =
            Observation { block_timestamp: 999_000, initialized: true, ..Default::default() };
        pool.observations = Observations::new(slots);
        let token_a =
            Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
        let token_b =
            Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);

        assert!(pool.get_fee().is_err());
        assert!(pool
            .spot_price(&token_a, &token_b)
            .is_err());
        assert!(pool
            .get_amount_out(BigUint::from(1_000u32), &token_a, &token_b)
            .is_err());
        assert!(pool
            .get_limits(token_a.address, token_b.address)
            .is_err());
    }

    #[test]
    fn default_quotes_the_worse_fee_when_position_is_unknown() {
        // Without the first-in-block assumption the quote must never over-state the output:
        // before the pool is touched in the execution block, the worse of the two branches
        // (here the 2700 dynamic fee) applies — which is also the pre-fix behavior.
        let mut pool = initial_fee_pool(1_000);
        pool.position_assumption = BlockPositionAssumption::WorstCase;
        pool.apply_block(&BlockContext::new(101, 1_002));

        assert_eq!(
            pool.get_fee()
                .expect("fee should be computable")
                .fee,
            2700
        );
    }

    #[test]
    fn worst_case_picks_the_initial_fee_when_it_is_the_higher_one() {
        // Nothing stops a pool from configuring initialFee above its dynamic fee, so the worst
        // case is max(initial, dynamic).
        let mut pool = initial_fee_pool(1_000);
        pool.dfc = DynamicFeeConfig::new(500, 30_000, 0, true, 4_000);
        pool.position_assumption = BlockPositionAssumption::WorstCase;
        pool.apply_block(&BlockContext::new(101, 1_002));

        assert_eq!(
            pool.get_fee()
                .expect("fee should be computable")
                .fee,
            4_000
        );
    }

    #[test]
    fn worst_case_keeps_a_flat_fee_pool_quiet_across_blocks() {
        // With scaling 0 the worst-case fee is constant, so apply_block must never request a
        // re-emission: the default mode adds no per-block load for such pools.
        let mut pool = initial_fee_pool(1_000);
        pool.position_assumption = BlockPositionAssumption::WorstCase;
        pool.apply_block(&BlockContext::new(100, 1_000));

        assert!(!pool.apply_block(&BlockContext::new(101, 1_002)));
        assert!(!pool.apply_block(&BlockContext::new(102, 1_004)));
    }

    #[test]
    fn apply_block_reports_a_fee_flip_and_is_idempotent() {
        // Pool traded in block 100 (ts 1_000): decoded with execution block == that block, so the
        // dynamic fee applies. Crossing to the next block flips the branch to the initial fee.
        let mut pool = initial_fee_pool(1_000);
        pool.apply_block(&BlockContext::new(100, 1_000));

        assert!(pool.apply_block(&BlockContext::new(101, 1_002)), "branch flip must re-emit");
        assert!(!pool.apply_block(&BlockContext::new(101, 1_002)), "repeat block is a no-op");
    }

    #[test]
    fn apply_block_stays_quiet_while_the_fee_does_not_move() {
        // Idle pool: the initial fee already applies and keeps applying as blocks pass, so
        // consumers must not be told anything changed.
        let mut pool = initial_fee_pool(1_000);
        pool.apply_block(&BlockContext::new(101, 1_002));

        assert!(!pool.apply_block(&BlockContext::new(102, 1_004)));
        assert!(!pool.apply_block(&BlockContext::new(103, 1_006)));
    }

    #[test]
    fn quotes_initial_fee_for_the_next_block_after_the_pool_traded() {
        // The pool wrote its observation in the block we decoded. A quote lands in the *next*
        // block, where no observation exists yet — under the first-in-block assumption it pays
        // the initial fee.
        let mut pool = initial_fee_pool(1_000);
        pool.apply_block(&BlockContext::new(101, 1_002));

        assert_eq!(
            pool.get_fee()
                .expect("fee should be computable")
                .fee,
            750
        );
    }

    #[test]
    fn quotes_dynamic_fee_when_targeting_a_block_the_pool_already_traded_in() {
        // Flashblock consumer: the block is still open and the pool traded in an earlier
        // flashblock, so a quote landing later in the same block pays the dynamic fee.
        let mut pool = initial_fee_pool(1_000);
        pool.apply_block(&BlockContext::new(100, 1_000));

        assert_eq!(
            pool.get_fee()
                .expect("fee should be computable")
                .fee,
            2700
        );
    }

    #[test]
    fn chained_swap_in_the_same_block_pays_the_dynamic_fee() {
        let mut pool = initial_fee_pool(1_000);
        pool.apply_block(&BlockContext::new(101, 1_002));
        let token_a =
            Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
        let token_b =
            Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);

        assert_eq!(pool.fee(), 750.0 / 1_000_000.0);

        let result = pool
            .get_amount_out(BigUint::from(100_000_000_000_000_000u128), &token_a, &token_b)
            .expect("first swap should succeed");

        // The first swap moved the tick, so it wrote an observation at the execution timestamp;
        // the pool state it hands back prices the next swap in that block as a follow-up.
        assert_eq!(result.new_state.fee(), 2700.0 / 1_000_000.0);
    }

    #[test]
    fn swap_that_does_not_move_the_tick_leaves_the_initial_fee_available() {
        // `CLPool.swap` only writes an observation when the tick changed, so a swap that stays
        // inside the tick leaves the next swap in the block on the initial fee.
        let mut pool = initial_fee_pool(1_000);
        pool.apply_block(&BlockContext::new(101, 1_002));

        pool.record_observation(pool.tick)
            .expect("no-op write should succeed");

        assert_eq!(
            pool.get_fee()
                .expect("fee should be computable")
                .fee,
            750
        );
    }

    #[test]
    fn initial_fee_branch_does_not_charge_the_twap_gas_overhead() {
        let mut pool = initial_fee_pool(1_000);
        pool.dfc = DynamicFeeConfig::new(2700, 30_000, 6_000_000, true, 750);
        pool.apply_block(&BlockContext::new(101, 1_002));

        let resolved = pool
            .get_fee()
            .expect("fee should be computable");

        assert_eq!(resolved, ResolvedFee { fee: 750, observed_twap: false });
    }

    #[test]
    fn dynamic_fee_update_applies_for_supported_module() {
        let mut pool = create_basic_test_pool();
        pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
        let delta =
            dynamic_fee_delta(hex_literal::hex!("090b2A6bb475c00e2256e2095A60887cD710803b"));

        pool.delta_transition(delta, &HashMap::new(), &Balances::default())
            .expect("dynamic fee update should be valid");

        assert_eq!(
            pool.get_fee()
                .expect("fee should be computable")
                .fee,
            500
        );
    }

    #[test]
    fn dynamic_fee_update_falls_back_to_default_for_unsupported_module() {
        // An unsupported-module delta resets to default rather than erroring; pool keeps
        // default_fee.
        let mut pool = create_basic_test_pool();
        pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
        let delta =
            dynamic_fee_delta(hex_literal::hex!("DB45818A6db280ecfeB33cbeBd445423d0216b5D"));

        pool.delta_transition(delta, &HashMap::new(), &Balances::default())
            .expect("unsupported module delta should decode to the default config");

        assert_eq!(pool.dfc, DynamicFeeConfig::default());
        assert_eq!(
            pool.get_fee()
                .expect("fee should be computable")
                .fee,
            3000
        );
    }

    #[test]
    fn applies_partial_dynamic_fee_updates_after_module_initialization() {
        let mut pool = create_basic_test_pool();
        pool.dfc = DynamicFeeConfig::new(4500, 10_000, 1, false, 0);
        let delta = ProtocolStateDelta {
            component_id: "test-pool".to_string(),
            updated_attributes: HashMap::from([(
                "dfc_baseFee".to_string(),
                Bytes::from(500_u32.to_be_bytes()),
            )]),
            ..Default::default()
        };

        pool.delta_transition(delta, &HashMap::new(), &Balances::default())
            .expect("partial dynamic fee update should be valid");

        assert_eq!(pool.dfc, DynamicFeeConfig::new(500, 10_000, 1, false, 0));
    }

    #[test]
    fn applies_a_cardinality_increase() {
        // `increaseObservationCardinalityNext(4)` prefills slots 1-3 with timestamp 1, which the
        // stream sends as the single byte 0x01. Lookups read them as uninitialized whether stored
        // or not, so the ring is left as it was.
        let mut pool = create_basic_test_pool();
        let ring = Observations::new(vec![Observation {
            block_timestamp: 999_990,
            initialized: true,
            ..Default::default()
        }]);
        pool.observations = ring.clone();
        let delta = ProtocolStateDelta {
            component_id: "test-pool".to_string(),
            updated_attributes: (1..4)
                .map(|index| (format!("observations/{index}"), Bytes::from([0x01_u8])))
                .collect(),
            ..Default::default()
        };

        pool.delta_transition(delta, &HashMap::new(), &Balances::default())
            .expect("prefilled observation slots should be valid");

        assert_eq!(pool.observations, ring);
    }

    #[rstest]
    #[case::not_a_number("observations/next")]
    #[case::past_the_ring("observations/65535")]
    fn malformed_observation_key_fails_the_transition(#[case] key: &str) {
        let mut pool = create_basic_test_pool();
        let delta = ProtocolStateDelta {
            component_id: "test-pool".to_string(),
            updated_attributes: HashMap::from([(key.to_string(), Bytes::from([0x01_u8]))]),
            ..Default::default()
        };

        let result = pool.delta_transition(delta, &HashMap::new(), &Balances::default());

        let Err(TransitionError::DecodeError(message)) = result else {
            panic!("expected a DecodeError, got {result:?}");
        };
        assert!(message.starts_with(key), "{message}");
    }

    #[test]
    fn test_partial_step_updates_tick_when_price_moves_without_crossing_initialized_tick() {
        let pool = create_basic_test_pool();
        let amount =
            I256::checked_from_sign_and_abs(Sign::Positive, U256::from(100_000_000_000_000_000u64))
                .unwrap();

        let result = pool
            .swap(true, amount, None)
            .expect("swap should stay within the current liquidity range");
        let expected_tick =
            get_tick_at_sqrt_ratio(result.sqrt_price).expect("new sqrt price should map to a tick");

        assert_ne!(result.sqrt_price, pool.sqrt_price);
        assert_ne!(result.sqrt_price, get_sqrt_ratio_at_tick(-120).unwrap());
        assert_ne!(expected_tick, pool.tick);
        assert_eq!(result.tick.value(), expected_tick);
    }

    #[test]
    fn test_swap_keeps_boundary_tick_when_price_does_not_move() {
        let mut pool = create_basic_test_pool();
        pool.tick = -1;
        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1u64)).unwrap();

        let result = pool
            .swap(true, amount, None)
            .expect("swap should consume the input as fee without moving price");

        assert_eq!(result.sqrt_price, pool.sqrt_price);
        assert_eq!(get_tick_at_sqrt_ratio(result.sqrt_price).unwrap(), 0);
        assert_eq!(result.tick.value(), pool.tick);
    }

    #[test]
    fn test_swap_price_limit_out_of_range_returns_error() {
        let pool = create_basic_test_pool();
        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();

        let result = pool.swap(true, amount, Some(pool.sqrt_price));
        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));

        let result = pool.swap(true, amount, Some(MIN_SQRT_RATIO));
        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));

        let result = pool.swap(false, amount, Some(pool.sqrt_price));
        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));

        let result = pool.swap(false, amount, Some(MAX_SQRT_RATIO));
        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
    }

    #[test]
    fn test_swap_at_extreme_price_returns_error() {
        let sqrt_price = MIN_SQRT_RATIO + U256::from(1u64);
        let tick = get_tick_at_sqrt_ratio(sqrt_price).expect("Failed to calculate tick");
        let ticks =
            vec![TickInfo::new(MIN_TICK, 0).unwrap(), TickInfo::new(MIN_TICK + 1, 0).unwrap()];
        let pool = AerodromeSlipstreamsState::new(
            "test-pool".to_string(),
            1_000_000,
            100_000_000_000_000_000_000u128,
            sqrt_price,
            0,
            1,
            3000,
            1,
            tick,
            ticks,
            vec![Observation::default()],
            DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
        )
        .expect("Failed to create pool");

        let amount = I256::checked_from_sign_and_abs(Sign::Positive, U256::from(1000u64)).unwrap();
        let result = pool.swap(true, amount, None);
        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
    }

    fn token_pair() -> (Token, Token) {
        let token_a =
            Token::new(&Bytes::from([0x11; 20]), "A", 18, 0, &[Some(10_000)], Chain::Base, 100);
        let token_b =
            Token::new(&Bytes::from([0x22; 20]), "B", 18, 0, &[Some(10_000)], Chain::Base, 100);
        (token_a, token_b)
    }

    #[rstest]
    fn test_query_pool_swap_target_price_lands_in_band(#[values(true, false)] sell_a: bool) {
        let mut pool = create_basic_test_pool();
        pool.dfc = DynamicFeeConfig::new(3000, 10_000, 0, false, 0);
        let (token_a, token_b) = token_pair();
        let (token_in, token_out) =
            if sell_a { (&token_a, &token_b) } else { (&token_b, &token_a) };
        let target = pool
            .spot_price(token_in, token_out)
            .unwrap() *
            0.99;
        let tolerance = 1e-4;
        let params = target_price_params(
            token_in,
            token_out,
            to_price(target, token_in, token_out),
            tolerance,
        );

        let swap = pool.query_pool_swap(&params).unwrap();

        let new_spot = swap
            .new_state()
            .spot_price(token_in, token_out)
            .unwrap();
        assert!(new_spot >= target && new_spot <= target * (1.0 + tolerance), "spot {new_spot}");
        assert!(swap.price_points().is_none(), "the native path returns no price points");
        let quote = pool
            .get_amount_out(swap.amount_in().clone(), token_in, token_out)
            .unwrap();
        assert_eq!(&quote.amount, swap.amount_out());
    }

    #[test]
    fn target_price_revalidates_after_initial_fee_changes() {
        let mut pool = initial_fee_pool(999_999);
        pool.ticks = Arc::new(
            TickList::from(
                1,
                vec![TickInfo::new(-1200, 0).unwrap(), TickInfo::new(1200, 0).unwrap()],
            )
            .unwrap(),
        );
        let (token_in, token_out) = token_pair();
        let target = 0.99;
        let tolerance = 1e-4;
        let params = target_price_params(
            &token_in,
            &token_out,
            to_price(target, &token_in, &token_out),
            tolerance,
        );
        let swap = pool
            .query_pool_swap(&params)
            .expect("search reaches the target using the final fee");
        let spot = swap
            .new_state()
            .spot_price(&token_in, &token_out)
            .unwrap();
        assert!(spot >= target && spot <= target * (1.0 + tolerance), "final spot {spot}");
        assert!(swap.price_points().is_some(), "fee change should trigger numerical search");
    }

    /// A target less than half the tolerance below spot puts the swap limit above spot.
    #[test]
    fn test_query_pool_swap_target_price_falls_back_to_search() {
        let pool = create_basic_test_pool();
        let (token_a, token_b) = token_pair();
        let spot = pool
            .spot_price(&token_a, &token_b)
            .unwrap();
        let params = target_price_params(
            &token_a,
            &token_b,
            to_price(spot * (1.0 - 1e-5), &token_a, &token_b),
            1e-4,
        );

        let swap = pool.query_pool_swap(&params).unwrap();

        assert!(swap.price_points().is_some(), "the numerical search returns price points");
    }

    #[test]
    fn test_query_pool_swap_target_price_at_spot() {
        let mut pool = create_basic_test_pool();
        pool.dfc = DynamicFeeConfig::new(ZERO_FEE_INDICATOR, 10_000, 0, false, 0);
        let (token_a, token_b) = token_pair();
        let params = target_price_params(
            &token_a,
            &token_b,
            Price::new(BigUint::from(1u64), BigUint::from(1u64)),
            1e-4,
        );

        let swap = pool.query_pool_swap(&params).unwrap();

        assert!(swap.amount_in().is_zero());
        assert!(swap.amount_out().is_zero());
        assert!(swap.new_state().eq(&pool));
    }

    #[test]
    fn test_query_pool_swap_target_price_above_spot() {
        let pool = create_basic_test_pool();
        let (token_a, token_b) = token_pair();
        let spot = pool
            .spot_price(&token_a, &token_b)
            .unwrap();
        let params = target_price_params(
            &token_a,
            &token_b,
            to_price(spot * 1.01, &token_a, &token_b),
            1e-4,
        );

        let result = pool.query_pool_swap(&params);

        assert!(matches!(result, Err(SimulationError::InvalidInput(..))), "got {result:?}");
    }
}

#[cfg(test)]
mod tick_list_sharing_tests {
    use std::collections::{HashMap, HashSet};

    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};

    use super::*;
    use crate::evm::protocol::utils::uniswap::tick_math::get_sqrt_ratio_at_tick;

    #[test]
    fn test_delta_transition_leaves_clones_ticks_unchanged() {
        let original = AerodromeSlipstreamsState::new(
            "test-pool".to_string(),
            1_000_000,
            100_000_000_000_000_000_000u128,
            get_sqrt_ratio_at_tick(0).unwrap(),
            0,
            1,
            3000,
            1,
            0,
            vec![TickInfo::new(-120, 10000).unwrap(), TickInfo::new(120, -10000).unwrap()],
            vec![Observation::default()],
            DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
        )
        .unwrap();
        let mut updated = original.clone();
        let delta = ProtocolStateDelta {
            component_id: "State1".to_owned(),
            updated_attributes: HashMap::from([(
                "ticks/-120/net_liquidity".to_string(),
                Bytes::from(20000_i128.to_be_bytes().to_vec()),
            )]),
            deleted_attributes: HashSet::new(),
        };

        updated
            .delta_transition(delta, &HashMap::new(), &Balances::default())
            .unwrap();

        assert_eq!(
            updated
                .ticks
                .get_tick(-120)
                .unwrap()
                .net_liquidity,
            20000
        );
        assert_eq!(
            original
                .ticks
                .get_tick(-120)
                .unwrap()
                .net_liquidity,
            10000
        );
    }
}

#[cfg(test)]
mod observation_sharing_tests {
    use std::collections::{HashMap, HashSet};

    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};

    use super::*;
    use crate::evm::protocol::utils::uniswap::tick_math::get_sqrt_ratio_at_tick;

    fn pool_with_observations() -> AerodromeSlipstreamsState {
        let observations = (0..3)
            .map(|index| Observation {
                block_timestamp: 1_000 + u32::try_from(index).unwrap(),
                tick_cumulative: 10 * i64::from(index),
                initialized: true,
                ..Default::default()
            })
            .collect();
        let mut pool = AerodromeSlipstreamsState::new(
            "test-pool".to_string(),
            1_000_000,
            100_000_000_000_000_000_000u128,
            get_sqrt_ratio_at_tick(0).unwrap(),
            0,
            3,
            3000,
            1,
            0,
            vec![TickInfo::new(-120, 10000).unwrap(), TickInfo::new(120, -10000).unwrap()],
            observations,
            DynamicFeeConfig::new(3000, 10_000, 1, false, 0),
        )
        .unwrap();
        pool.execution_block_timestamp = 2_000;
        pool
    }

    /// The state after a swap at `timestamp` that moved the tick to `tick`.
    fn swapped(
        pool: &AerodromeSlipstreamsState,
        timestamp: u64,
        tick: i32,
    ) -> AerodromeSlipstreamsState {
        let mut source = pool.clone();
        source.execution_block_timestamp = timestamp;
        let (state, written) =
            source.clone_post_swap(get_sqrt_ratio_at_tick(tick).unwrap(), tick, 1);
        written.unwrap();
        state
    }

    fn observation_bytes(timestamp: u32) -> Bytes {
        // Packed as on chain: timestamp in the low 32 bits, `initialized` at bit 248.
        let mut packed = [0u8; 32];
        packed[28..].copy_from_slice(&timestamp.to_be_bytes());
        packed[0] = 1;
        Bytes::from(packed.to_vec())
    }

    fn observation_delta(timestamp: u32) -> ProtocolStateDelta {
        ProtocolStateDelta {
            component_id: "State1".to_owned(),
            updated_attributes: HashMap::from([(
                "observations/1".to_string(),
                observation_bytes(timestamp),
            )]),
            deleted_attributes: HashSet::new(),
        }
    }

    #[test]
    fn clone_shares_observations() {
        let original = pool_with_observations();

        let copy = original.clone();

        assert!(original
            .observations
            .shares_ring_with(&copy.observations));
    }

    #[test]
    fn chain_of_tick_moving_swaps_never_copies_the_ring() {
        let original = pool_with_observations();

        let first = swapped(&original, 2_000, 60);
        let second = swapped(&first, 2_010, -60);
        let third = swapped(&second, 2_020, 30);

        for state in [&first, &second, &third] {
            assert!(original
                .observations
                .shares_ring_with(&state.observations));
        }
        assert_eq!(third.observation_index, 0);
        assert_eq!(
            third
                .observations
                .timestamp_at(0, 3)
                .unwrap(),
            2_020
        );
        assert_eq!(
            second
                .observations
                .timestamp_at(2, 3)
                .unwrap(),
            2_010
        );
        assert_eq!(
            first
                .observations
                .timestamp_at(1, 3)
                .unwrap(),
            2_000
        );
    }

    #[test]
    fn swap_leaves_the_source_states_observations_unchanged() {
        let original = pool_with_observations();

        let after_swap = swapped(&original, 2_000, 60);

        assert_eq!(after_swap.observation_index, 1);
        assert_eq!(
            after_swap
                .observations
                .timestamp_at(1, 3)
                .unwrap(),
            2_000
        );
        assert_eq!(original.observation_index, 0);
        assert_eq!(
            original
                .observations
                .timestamp_at(1, 3)
                .unwrap(),
            1_001
        );
    }

    #[test]
    fn second_swap_in_the_same_block_writes_nothing() {
        let original = pool_with_observations();
        let first = swapped(&original, 2_000, 60);

        let second = swapped(&first, 2_000, -60);

        assert_eq!(second.observation_index, first.observation_index);
        assert_eq!(second.observations, first.observations);
    }

    #[test]
    fn swap_that_keeps_the_tick_writes_nothing() {
        let original = pool_with_observations();

        let after_swap = swapped(&original, 2_000, original.tick);

        assert_eq!(after_swap.observation_index, 0);
        assert_eq!(after_swap.observations, original.observations);
    }

    #[test]
    fn fee_and_observations_match_a_state_rebuilt_from_the_merged_observations() {
        let original = pool_with_observations();
        let chained = swapped(&swapped(&original, 2_000, 60), 2_010, -60);
        let copied: AerodromeSlipstreamsState =
            serde_json::from_str(&serde_json::to_string(&chained).unwrap()).unwrap();

        assert!(!chained
            .observations
            .shares_ring_with(&copied.observations));
        assert_eq!(chained.observations, copied.observations);
        assert_eq!(chained.get_fee().unwrap().fee, copied.get_fee().unwrap().fee);
        for seconds_ago in [0, 5, 10, 15] {
            assert_eq!(
                chained
                    .observations
                    .observe_single(2_020, seconds_ago, -60, 2, 1, 3)
                    .unwrap(),
                copied
                    .observations
                    .observe_single(2_020, seconds_ago, -60, 2, 1, 3)
                    .unwrap(),
            );
        }
    }

    #[test]
    fn delta_transition_leaves_clones_observations_unchanged() {
        let original = pool_with_observations();
        let mut updated = original.clone();

        updated
            .delta_transition(observation_delta(5_000), &HashMap::new(), &Balances::default())
            .unwrap();

        assert_eq!(
            updated
                .observations
                .timestamp_at(1, 3)
                .unwrap(),
            5_000
        );
        assert_eq!(
            original
                .observations
                .timestamp_at(1, 3)
                .unwrap(),
            1_001
        );
        assert!(!original
            .observations
            .shares_ring_with(&updated.observations));
    }

    #[test]
    fn delta_transition_after_simulated_writes_reads_the_chain_values() {
        let original = pool_with_observations();
        let mut simulated = swapped(&original, 2_000, 60);

        simulated
            .delta_transition(observation_delta(5_000), &HashMap::new(), &Balances::default())
            .unwrap();

        assert_eq!(
            simulated
                .observations
                .timestamp_at(1, 3)
                .unwrap(),
            5_000
        );
        assert_eq!(
            simulated
                .observations
                .timestamp_at(2, 3)
                .unwrap(),
            1_002
        );
        assert_eq!(
            original
                .observations
                .timestamp_at(1, 3)
                .unwrap(),
            1_001
        );
    }

    #[test]
    fn delta_transition_keeps_simulated_writes_the_chain_did_not_touch() {
        let original = pool_with_observations();
        let mut simulated = swapped(&swapped(&original, 2_000, 60), 2_010, -60);
        let mut delta = observation_delta(5_000);
        delta.updated_attributes.clear();
        delta
            .deleted_attributes
            .insert("observations/0".to_string());

        simulated
            .delta_transition(delta, &HashMap::new(), &Balances::default())
            .unwrap();

        // Deleting slot 0 zeroes it; the simulated writes stay at slots 1 and 2.
        assert_eq!(simulated.observations.get(0), Some(Observation::default()));
        assert_eq!(
            simulated
                .observations
                .timestamp_at(1, 3)
                .unwrap(),
            2_000
        );
        assert_eq!(
            simulated
                .observations
                .timestamp_at(2, 3)
                .unwrap(),
            2_010
        );
    }
}

#[cfg(test)]
mod step_cache_tests {
    use std::{
        collections::{HashMap, HashSet},
        str::FromStr,
    };

    use tycho_common::{dto::ProtocolStateDelta, hex_bytes::Bytes};

    use super::*;
    use crate::evm::protocol::utils::uniswap::swap_step_cache::test_fixtures::{
        amount_orders, test_amounts, test_ticks, wbtc_weth, LIQUIDITY, SQRT_PRICE, TICK,
    };

    fn test_pool() -> AerodromeSlipstreamsState {
        AerodromeSlipstreamsState::new(
            "test-pool".to_string(),
            1_000_000,
            LIQUIDITY,
            U256::from_str(SQRT_PRICE).unwrap(),
            0,
            1,
            500,
            10,
            TICK,
            test_ticks(),
            vec![Observation::default()],
            DynamicFeeConfig::new(500, 10_000, 1, false, 0),
        )
        .unwrap()
    }

    /// A quote's amount, gas and new state, or its error, as text.
    fn format_quote_result(
        pool: &AerodromeSlipstreamsState,
        amount: &BigUint,
        sell: &Token,
        buy: &Token,
    ) -> String {
        match pool.get_amount_out(amount.clone(), sell, buy) {
            Ok(result) => {
                let state = result
                    .new_state
                    .as_any()
                    .downcast_ref::<AerodromeSlipstreamsState>()
                    .unwrap();
                format!(
                    "{} {} {} {} {}",
                    result.amount, result.gas, state.sqrt_price, state.tick, state.liquidity
                )
            }
            Err(error) => format!("error {error}"),
        }
    }

    #[test]
    fn test_step_cache_quotes_match_a_fresh_state_in_any_order() {
        let (wbtc, weth) = wbtc_weth();
        for (sell, buy, smallest) in [(&wbtc, &weth, 1_000u64), (&weth, &wbtc, 1_000_000_000)] {
            for order in amount_orders(&test_amounts(smallest)) {
                let shared = test_pool();
                for amount in &order {
                    assert_eq!(
                        format_quote_result(&shared, amount, sell, buy),
                        format_quote_result(&test_pool(), amount, sell, buy),
                        "selling {amount} {}",
                        sell.symbol
                    );
                }
                let steps = shared
                    .step_cache
                    .min_inputs(sell < buy)
                    .len();
                assert!(steps > 2, "only {steps} steps cached");
            }
        }
    }

    #[test]
    fn test_step_cache_quotes_match_a_fresh_state_at_each_cached_step() {
        let (wbtc, weth) = wbtc_weth();
        // Amounts that run past the last tick, so the cache covers the whole tick list. Selling
        // WETH needs a far larger amount to leave its first tick.
        for (sell, buy, doublings) in [(&wbtc, &weth, 30u32), (&weth, &wbtc, 70)] {
            let cached = test_pool();
            #[expect(
                clippy::let_underscore_must_use,
                reason = "the quote may run out of liquidity; only the step cache it fills is used"
            )]
            let _ = cached.get_amount_out(BigUint::from(10u32) << doublings, sell, buy);
            let boundaries = cached.step_cache.min_inputs(sell < buy);
            assert!(boundaries.len() > 2, "only {} steps cached", boundaries.len());
            for boundary in boundaries.into_iter().skip(1) {
                for amount in [boundary - U256::from(1u64), boundary, boundary + U256::from(1u64)] {
                    let amount = u256_to_biguint(amount);
                    assert_eq!(
                        format_quote_result(&cached, &amount, sell, buy),
                        format_quote_result(&test_pool(), &amount, sell, buy),
                        "selling {amount} {}",
                        sell.symbol
                    );
                }
            }
        }
    }

    #[test]
    fn test_step_cache_of_a_swapped_state() {
        let (wbtc, weth) = wbtc_weth();
        let pool = test_pool();
        let swapped = pool
            .get_amount_out(BigUint::from(300_000_000u64), &wbtc, &weth)
            .unwrap()
            .new_state;
        let swapped = swapped
            .as_any()
            .downcast_ref::<AerodromeSlipstreamsState>()
            .unwrap();
        // A serde round trip gives the same state with an empty step cache.
        let fresh: AerodromeSlipstreamsState =
            serde_json::from_value(serde_json::to_value(swapped).unwrap()).unwrap();

        for amount in test_amounts(1_000).iter().rev() {
            assert_eq!(
                format_quote_result(swapped, amount, &wbtc, &weth),
                format_quote_result(&fresh, amount, &wbtc, &weth),
                "selling {amount} WBTC"
            );
        }
    }

    #[test]
    fn test_step_cache_restarts_after_delta_transition() {
        let (wbtc, weth) = wbtc_weth();
        let large = BigUint::from(3_000_000_000u64);
        // Only a crossed tick's liquidity changes, so the price, tick and liquidity the cache
        // starts from stay the same.
        let delta = || ProtocolStateDelta {
            component_id: "State1".to_owned(),
            updated_attributes: HashMap::from([(
                "ticks/255820/net_liquidity".to_string(),
                Bytes::from(
                    1_000_000_000_000_000i128
                        .to_be_bytes()
                        .to_vec(),
                ),
            )]),
            deleted_attributes: HashSet::new(),
        };
        let mut cached = test_pool();
        cached
            .get_amount_out(large.clone(), &wbtc, &weth)
            .unwrap();
        let mut fresh = test_pool();

        cached
            .delta_transition(delta(), &HashMap::new(), &Balances::default())
            .unwrap();
        fresh
            .delta_transition(delta(), &HashMap::new(), &Balances::default())
            .unwrap();

        assert_eq!(
            format_quote_result(&cached, &large, &wbtc, &weth),
            format_quote_result(&fresh, &large, &wbtc, &weth)
        );
    }
}