evm-amm-state 0.2.0

EVM-backed AMM state loading, cache synchronization, and pool simulation models
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
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
//! Factory-backed pool discovery.
//!
//! Discovery is intentionally read-only: factory drivers produce
//! [`PoolRegistration`] values, and callers still decide when to cold-start and
//! register them.
//!
//! ## Concentrated-liquidity presets: on-chain-verified constants
//!
//! Every preset's storage constants are verified against a forked archive node
//! by the gated (`#[ignore]`) `discovery_cl_rpc` / `discovery_solidly_rpc` parity
//! tests — discovered via evm-fork-cache's trace-based slot probe, not guessed:
//!
//! - **Uniswap V3** ([`ClFactorySpec::uniswap_v3`]): `getPool` / `feeAmountTickSpacing`
//!   base slots 5 / 4, canonical fee tiers.
//! - **PancakeSwap V3** ([`ClFactorySpec::pancake_v3`]): `getPool` base slot **2**
//!   and `feeAmountTickSpacing` base slot **1** (verified — they differ from
//!   Uniswap's 5 / 4), plus the `PoolDeployer`, pool init-code hash, and
//!   `QuoterV2`. `verify_derivations` is ON (the mapping answer is cross-checked
//!   against the CREATE2 derivation on first use).
//! - **Slipstream / Aerodrome CL** ([`ClFactorySpec::slipstream`]): `getPool`
//!   base slot **6** (verified). Discovery-only: `quoter` is `None` because the
//!   Slipstream quoter takes a `tickSpacing`-keyed struct, not the Uniswap
//!   `(…, fee, …)` struct this crate encodes — so its sim rides the caller's
//!   Uniswap-compatible quoter (see the [`ClFactorySpec::slipstream`] docs).
//! - **Solidly V2 / Aerodrome** ([`SolidlyFactoryConfig::aerodrome`]): `getPool`
//!   base slot **5** + the pool storage layout (reserves @ 20/21, tokens @ 13/14),
//!   verified on-chain.
//!
//! ## Out of scope: integrator-supplied discovery
//!
//! Two AMM shapes ship no built-in discovery factory; supply their pools via
//! explicit registration or a custom [`PoolFactory`] added through
//! [`PoolDiscovery::with_factory`]:
//! - **Balancer V2** — no on-chain token→pool index, so discovery is an async
//!   log scan rather than a cache read.
//! - **Curve** — its MetaRegistry `find_pools_for_coins` view reverts against a
//!   live node, so ViewCall discovery is not built in. The Curve *adapter* still
//!   simulates explicitly-registered Curve pools.

use std::collections::HashMap;
use std::fmt;

#[cfg(any(feature = "uniswap-v2", feature = "uniswap-v3", feature = "solidly-v2"))]
use super::ProtocolMetadata;
#[cfg(feature = "solidly-v2")]
use super::SolidlyV2Metadata;
#[cfg(feature = "uniswap-v2")]
use super::UniswapV2Metadata;
#[cfg(feature = "uniswap-v3")]
use super::V3Metadata;
use super::{AdapterCache, AdapterRegistry, EventSource, PoolKey, PoolRegistration, ProtocolId};
#[cfg(feature = "solidly-v2")]
use crate::adapters::storage::SolidlyStorageLayout;
#[cfg(feature = "uniswap-v3")]
use crate::adapters::storage::V3StorageLayout;
#[cfg(any(feature = "uniswap-v2", feature = "uniswap-v3", feature = "solidly-v2"))]
use alloy_primitives::B256;
use alloy_primitives::{Address, Log, U256};
#[cfg(any(feature = "uniswap-v2", feature = "uniswap-v3", feature = "solidly-v2"))]
use alloy_sol_types::SolEvent;

/// Factory-level derivation helpers.
pub mod derive {
    use alloy_primitives::Address;
    #[cfg(any(feature = "uniswap-v2", feature = "uniswap-v3", feature = "solidly-v2"))]
    use alloy_primitives::{B256, U256, keccak256};

    /// Sort two token addresses into the canonical `(token0, token1)` order used
    /// by Uniswap-style factories.
    pub fn sort_tokens(a: Address, b: Address) -> (Address, Address) {
        if a.as_slice() <= b.as_slice() {
            (a, b)
        } else {
            (b, a)
        }
    }

    /// Every unordered token pair drawn from `tokens`, each normalized to
    /// `(token0, token1)` order and de-duplicated. For `n` distinct tokens this
    /// is the `C(n, 2)` combinations — the pair set a token-basket query
    /// expands into (see [`PoolQuery::basket`]).
    ///
    /// [`PoolQuery::basket`]: super::PoolQuery::basket
    pub fn pairs_among(tokens: &[Address]) -> Vec<(Address, Address)> {
        let mut pairs = Vec::new();
        for (i, &a) in tokens.iter().enumerate() {
            for &b in &tokens[i + 1..] {
                if a != b {
                    pairs.push(sort_tokens(a, b));
                }
            }
        }
        pairs.sort_unstable();
        pairs.dedup();
        pairs
    }

    /// Compute the storage key for `UniswapV2Factory.getPair[token0][token1]`.
    #[cfg(feature = "uniswap-v2")]
    pub fn v2_get_pair_slot(base_slot: U256, token0: Address, token1: Address) -> U256 {
        nested_address_mapping_slot(base_slot, token0, token1)
    }

    /// Compute the storage key for `UniswapV3Factory.getPool[token0][token1][fee]`.
    #[cfg(feature = "uniswap-v3")]
    pub fn v3_get_pool_slot(base_slot: U256, token0: Address, token1: Address, fee: u32) -> U256 {
        let first = mapping_slot_address(base_slot, token0);
        let second = mapping_slot_address(first, token1);
        mapping_slot_u256(second, U256::from(fee))
    }

    /// Compute the storage key for a tickSpacing-keyed
    /// `getPool[token0][token1][tickSpacing]` mapping (Slipstream / Aerodrome CL),
    /// where the innermost key is an `int24` tickSpacing.
    ///
    /// The tickSpacing is sign-extended to a full 256-bit word before hashing —
    /// the same two's-complement encoding Solidity uses for a signed mapping key —
    /// so a (non-negative in practice) spacing produces the exact storage slot the
    /// contract wrote. Mirrors [`v3_get_pool_slot`] but with a signed innermost
    /// key instead of a `uint24` fee.
    #[cfg(feature = "uniswap-v3")]
    pub fn v3_get_pool_slot_by_spacing(
        base_slot: U256,
        token0: Address,
        token1: Address,
        spacing: i32,
    ) -> U256 {
        let first = mapping_slot_address(base_slot, token0);
        let second = mapping_slot_address(first, token1);
        mapping_slot_u256(second, i24_to_word(spacing))
    }

    /// Compute the storage key for `UniswapV3Factory.feeAmountTickSpacing[fee]`.
    #[cfg(feature = "uniswap-v3")]
    pub fn v3_fee_amount_tick_spacing_slot(base_slot: U256, fee: u32) -> U256 {
        mapping_slot_u256(base_slot, U256::from(fee))
    }

    /// Compute a tick-spacing-keyed fee mapping slot.
    #[cfg(feature = "uniswap-v3")]
    pub fn v3_tick_spacing_fee_slot(base_slot: U256, spacing: i32) -> U256 {
        mapping_slot_u256(base_slot, i24_to_word(spacing))
    }

    /// Compute a Uniswap V2 pair address using the factory CREATE2 formula.
    #[cfg(feature = "uniswap-v2")]
    pub fn v2_pair_address(
        factory: Address,
        init_code_hash: B256,
        token0: Address,
        token1: Address,
    ) -> Address {
        let mut salt_preimage = [0u8; 40];
        salt_preimage[..20].copy_from_slice(token0.as_slice());
        salt_preimage[20..].copy_from_slice(token1.as_slice());
        create2_address(factory, keccak256(salt_preimage), init_code_hash)
    }

    /// Compute a Uniswap V3 pool address using the canonical `PoolAddress` salt.
    #[cfg(feature = "uniswap-v3")]
    pub fn v3_pool_address(
        deployer: Address,
        init_code_hash: B256,
        token0: Address,
        token1: Address,
        fee: u32,
    ) -> Address {
        let mut salt_preimage = [0u8; 96];
        salt_preimage[12..32].copy_from_slice(token0.as_slice());
        salt_preimage[44..64].copy_from_slice(token1.as_slice());
        salt_preimage[92..96].copy_from_slice(&fee.to_be_bytes());
        create2_address(deployer, keccak256(salt_preimage), init_code_hash)
    }

    /// Compute a tickSpacing-keyed CL pool address via the standard V3 `abi.encode
    /// (token0, token1, int24 spacing)` salt (Slipstream/Aerodrome shape).
    ///
    /// Note: some tickSpacing-keyed forks deploy pools as minimal-proxy clones
    /// with a different salt/creation-code scheme; treat this as the standard-V3
    /// derivation and verify a specific fork's formula before enabling its
    /// CREATE2 cross-check.
    #[cfg(feature = "uniswap-v3")]
    pub fn v3_pool_address_by_spacing(
        deployer: Address,
        init_code_hash: B256,
        token0: Address,
        token1: Address,
        spacing: i32,
    ) -> Address {
        let mut salt_preimage = [0u8; 96];
        salt_preimage[12..32].copy_from_slice(token0.as_slice());
        salt_preimage[44..64].copy_from_slice(token1.as_slice());
        // int24 spacing, sign-extended into the trailing 32-byte word.
        salt_preimage[64..96].copy_from_slice(&i24_to_word(spacing).to_be_bytes::<32>());
        create2_address(deployer, keccak256(salt_preimage), init_code_hash)
    }

    /// Compute the storage key for a Solidly V2 (Aerodrome / Velodrome V2)
    /// `PoolFactory.getPool[token0][token1][stable]` entry.
    ///
    /// The factory keys pools by a nested
    /// `mapping(address => mapping(address => mapping(bool => address)))`: the two
    /// address levels descend exactly like Uniswap V3's `getPool[t0][t1]`, and the
    /// innermost `bool` key is encoded as a 32-byte word (`1` for stable, `0` for
    /// volatile) — the same encoding Solidity uses for a `bool` mapping key.
    #[cfg(feature = "solidly-v2")]
    pub fn solidly_get_pool_slot(
        base_slot: U256,
        token0: Address,
        token1: Address,
        stable: bool,
    ) -> U256 {
        let first = mapping_slot_address(base_slot, token0);
        let second = mapping_slot_address(first, token1);
        mapping_slot_u256(second, U256::from(stable as u8))
    }

    /// Compute a Solidly V2 pool address via the factory CREATE2 formula.
    ///
    /// The salt is `keccak256(abi.encodePacked(token0, token1, stable))` — a
    /// tightly packed 41-byte preimage (20 + 20 + 1), matching Aerodrome's
    /// `PoolFactory.createPool`. Used as an optional discovery cross-check against
    /// the `getPool` mapping answer.
    #[cfg(feature = "solidly-v2")]
    pub fn solidly_pool_address(
        deployer: Address,
        init_code_hash: B256,
        token0: Address,
        token1: Address,
        stable: bool,
    ) -> Address {
        let mut salt_preimage = [0u8; 41];
        salt_preimage[..20].copy_from_slice(token0.as_slice());
        salt_preimage[20..40].copy_from_slice(token1.as_slice());
        salt_preimage[40] = stable as u8;
        create2_address(deployer, keccak256(salt_preimage), init_code_hash)
    }

    #[cfg(feature = "uniswap-v2")]
    fn nested_address_mapping_slot(base_slot: U256, outer: Address, inner: Address) -> U256 {
        let outer_slot = mapping_slot_address(base_slot, outer);
        mapping_slot_address(outer_slot, inner)
    }

    #[cfg(any(feature = "uniswap-v2", feature = "uniswap-v3", feature = "solidly-v2"))]
    fn mapping_slot_address(base_slot: U256, key: Address) -> U256 {
        let mut preimage = [0u8; 64];
        preimage[12..32].copy_from_slice(key.as_slice());
        preimage[32..64].copy_from_slice(&base_slot.to_be_bytes::<32>());
        keccak256(preimage).into()
    }

    #[cfg(any(feature = "uniswap-v3", feature = "solidly-v2"))]
    fn mapping_slot_u256(base_slot: U256, key: U256) -> U256 {
        let mut preimage = [0u8; 64];
        preimage[..32].copy_from_slice(&key.to_be_bytes::<32>());
        preimage[32..64].copy_from_slice(&base_slot.to_be_bytes::<32>());
        keccak256(preimage).into()
    }

    /// Sign-extend an `int24` value into a 256-bit word, matching how Solidity
    /// encodes a signed mapping key (a negative value fills the high bytes with
    /// `0xff`). Used to key tickSpacing-mapped `getPool` slots.
    #[cfg(feature = "uniswap-v3")]
    fn i24_to_word(value: i32) -> U256 {
        // A 24-bit signed value fits in an i64 losslessly; `as u64` then produces
        // the two's-complement 64-bit pattern, and `U256::from(u64)` zero-extends
        // — so re-apply the sign across the full 256 bits for negatives.
        if value < 0 {
            // (-1 as U256) is all-ones; mask in the low 64-bit two's-complement.
            let low = U256::from(value as i64 as u64);
            let high_ones = (U256::MAX >> 64) << 64;
            low | high_ones
        } else {
            U256::from(value as u64)
        }
    }

    #[cfg(any(feature = "uniswap-v2", feature = "uniswap-v3", feature = "solidly-v2"))]
    fn create2_address(deployer: Address, salt: B256, init_code_hash: B256) -> Address {
        let mut preimage = [0u8; 85];
        preimage[0] = 0xff;
        preimage[1..21].copy_from_slice(deployer.as_slice());
        preimage[21..53].copy_from_slice(salt.as_slice());
        preimage[53..85].copy_from_slice(init_code_hash.as_slice());
        let hash = keccak256(preimage);
        Address::from_slice(&hash.as_slice()[12..])
    }
}

#[cfg(feature = "uniswap-v2")]
const UNISWAP_V2_GET_PAIR_BASE_SLOT: U256 = U256::from_limbs([2, 0, 0, 0]);
#[cfg(feature = "uniswap-v3")]
const UNISWAP_V3_FEE_AMOUNT_TICK_SPACING_BASE_SLOT: U256 = U256::from_limbs([4, 0, 0, 0]);
#[cfg(feature = "uniswap-v3")]
const UNISWAP_V3_GET_POOL_BASE_SLOT: U256 = U256::from_limbs([5, 0, 0, 0]);
/// PancakeSwap V3 `getPool` + `feeAmountTickSpacing` mapping base slots —
/// VERIFIED on-chain (mainnet block 20_000_000) via evm-fork-cache trace-based
/// slot discovery. Pancake's factory storage layout differs from Uniswap's 5 / 4.
#[cfg(feature = "uniswap-v3")]
const PANCAKE_V3_GET_POOL_BASE_SLOT: U256 = U256::from_limbs([2, 0, 0, 0]);
#[cfg(feature = "uniswap-v3")]
const PANCAKE_V3_FEE_AMOUNT_TICK_SPACING_BASE_SLOT: U256 = U256::from_limbs([1, 0, 0, 0]);
/// Slipstream (Aerodrome CL) factory `getPool` mapping base slot — VERIFIED
/// on-chain (Base block 47_700_000) via trace-based slot discovery.
#[cfg(feature = "uniswap-v3")]
const SLIPSTREAM_GET_POOL_BASE_SLOT: U256 = U256::from_limbs([6, 0, 0, 0]);
#[cfg(feature = "uniswap-v3")]
const UNISWAP_V3_CANONICAL_FEE_TIERS: [u32; 4] = [100, 500, 3_000, 10_000];
/// PancakeSwap V3 fee tiers (hundredths of a bip): 0.01% / 0.05% / 0.25% / 1%.
#[cfg(feature = "uniswap-v3")]
const PANCAKE_V3_FEE_TIERS: [u32; 4] = [100, 500, 2_500, 10_000];
/// Aerodrome/Velodrome Slipstream tickSpacing tiers (int24). VERIFY against a
/// live CLFactory before relying on production discovery — see the gated parity
/// test. These are the commonly-deployed spacings but are not exhaustive.
#[cfg(feature = "uniswap-v3")]
const SLIPSTREAM_TICK_SPACINGS: [i32; 5] = [1, 50, 100, 200, 2_000];

// --- Real on-chain constants for the CL presets (Ethereum mainnet / Base). ---
// Verified against block-explorer / SDK sources; the storage-slot bases for
// forks whose factory layout was not confirmed on-chain are gated behind the
// `#[ignore]` RPC parity test rather than trusted blindly. See the module report.

/// PancakeSwap V3 `PancakeV3PoolDeployer` (the CREATE2 deployer; the factory is a
/// separate address). Same deterministic address across mainnet/BSC/Arbitrum.
#[cfg(feature = "uniswap-v3")]
const PANCAKE_V3_POOL_DEPLOYER: Address =
    alloy_primitives::address!("41ff9AA7e16B8B1a8a8dc4f0eFacd93D02d071c9");
/// PancakeSwap V3 pool init-code hash (CREATE2 salt cross-check). "Most chains"
/// value per the Pancake v3-sdk (mainnet included; zkSync differs).
#[cfg(feature = "uniswap-v3")]
const PANCAKE_V3_INIT_CODE_HASH: B256 =
    alloy_primitives::b256!("6ce8eb472fa82df5469c6ab6d485f17c3ad13c8cd7af59b3d4a8026c5ce0f7e2");
/// PancakeSwap V3 `QuoterV2` (Ethereum mainnet; deterministic across several EVM
/// chains). Uses the Uniswap-compatible `(…, fee, …)` quote struct.
#[cfg(feature = "uniswap-v3")]
const PANCAKE_V3_QUOTER_V2: Address =
    alloy_primitives::address!("B048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997");

// --- Solidly V2 (Aerodrome / Velodrome V2) preset constants. ---
//
// VERIFIED on-chain (Aerodrome PoolFactory, Base block 47_700_000) via
// evm-fork-cache trace-based slot discovery: the `_getPool[token0][token1][stable]`
// mapping lives at base slot 5. No CREATE2 init-code hash is pinned (Solidly's
// salt is a packed `keccak(t0‖t1‖stable)`), so `verify_derivations` stays OFF;
// the gated `discovery_solidly_rpc` parity test re-checks the slot on Base.
#[cfg(feature = "solidly-v2")]
const SOLIDLY_GET_POOL_BASE_SLOT: U256 = U256::from_limbs([5, 0, 0, 0]);

/// Uniswap V2 `PairCreated` factory event (crate-internal), wrapped like
/// [`solidly_events`] so the binding stays out of the public API.
#[cfg(feature = "uniswap-v2")]
mod v2_factory_events {
    alloy_sol_types::sol! {
        event PairCreated(address indexed token0, address indexed token1, address pair, uint256 allPairsLength);
    }
}
#[cfg(feature = "uniswap-v2")]
use v2_factory_events::PairCreated;

/// CL-family factory pool-creation events (crate-internal, not public API).
#[cfg(feature = "uniswap-v3")]
mod cl_factory_events {
    alloy_sol_types::sol! {
        /// Uniswap/Pancake-style fee-keyed pool-creation event.
        event PoolCreated(address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool);

        /// Slipstream/Aerodrome CL tickSpacing-keyed pool-creation event. The
        /// indexed key is `tickSpacing` (int24) rather than a fee; the pool address
        /// and (unindexed) fee follow in the data.
        event PoolCreatedTickSpacing(address indexed token0, address indexed token1, int24 indexed tickSpacing, address pool, uint24 fee);
    }
}
#[cfg(feature = "uniswap-v3")]
use cl_factory_events::{PoolCreated, PoolCreatedTickSpacing};

/// Solidly V2 (Aerodrome / Velodrome V2) pool-creation event, wrapped in its own
/// module so the generated struct keeps the on-chain name `PoolCreated` (whose
/// `SIGNATURE_HASH` is the real topic0) without colliding with the Uniswap/Pancake
/// [`PoolCreated`] already defined above. The indexed keys are `token0`, `token1`,
/// and the `bool stable` flag; the pool address and the (unindexed) all-pools
/// length follow in the data. Verbatim from Aerodrome's `IPoolFactory` (the
/// trailing `uint256` is unnamed on-chain; named `allPoolsLength` here so the
/// generated decoder has a field).
#[cfg(feature = "solidly-v2")]
mod solidly_events {
    alloy_sol_types::sol! {
        event PoolCreated(address indexed token0, address indexed token1, bool indexed stable, address pool, uint256 allPoolsLength);
    }
}
#[cfg(feature = "solidly-v2")]
use solidly_events::PoolCreated as SolidlyPoolCreated;

/// A declarative pool-discovery query: which token pairs to resolve, optionally
/// scoped to a single protocol.
///
/// Construct one with [`pair`](Self::pair), [`basket`](Self::basket), or
/// [`pairs`](Self::pairs) — each normalizes token order (via
/// [`derive::sort_tokens`]) and de-duplicates — then optionally narrow it with
/// [`on`](Self::on). An unscoped query (no protocol) spans every matching
/// factory in a single batched read; `.on(p)` restricts it to protocol `p` (and
/// [`PoolDiscovery::find`] errors [`DiscoveryError::MissingFactory`] if no
/// factory is registered for `p`).
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PoolQuery {
    /// Normalized, de-duplicated `(token0, token1)` pairs to resolve.
    pairs: Vec<(Address, Address)>,
    /// The protocol to scope discovery to; `None` spans all matching factories.
    protocol: Option<ProtocolId>,
}

impl PoolQuery {
    /// A single token pair, normalized to `(token0, token1)` order.
    pub fn pair(a: Address, b: Address) -> Self {
        Self {
            pairs: vec![derive::sort_tokens(a, b)],
            protocol: None,
        }
    }

    /// Every unordered pair drawn from a token basket — the `C(n, 2)`
    /// combinations, each normalized and de-duplicated (see
    /// [`derive::pairs_among`]).
    pub fn basket(tokens: impl IntoIterator<Item = Address>) -> Self {
        let tokens: Vec<Address> = tokens.into_iter().collect();
        Self {
            pairs: derive::pairs_among(&tokens),
            protocol: None,
        }
    }

    /// An explicit set of pairs, each normalized to `(token0, token1)` order,
    /// then sorted and de-duplicated.
    pub fn pairs(pairs: impl IntoIterator<Item = (Address, Address)>) -> Self {
        let mut pairs: Vec<(Address, Address)> = pairs
            .into_iter()
            .map(|(a, b)| derive::sort_tokens(a, b))
            .collect();
        pairs.sort_unstable();
        pairs.dedup();
        Self {
            pairs,
            protocol: None,
        }
    }

    /// Scope discovery to a single protocol. Without this, the query spans every
    /// registered factory whose protocol has a matching pool.
    pub fn on(mut self, protocol: ProtocolId) -> Self {
        self.protocol = Some(protocol);
        self
    }
}

/// Immutable connector-focused discovery request for one token.
///
/// Connectors are sorted, de-duplicated, and never include `token` itself. The
/// request deliberately contains no provider or runtime policy: it can be
/// converted into a [`PoolQuery`] and scheduled at any exact block pin.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TokenEdgeDiscoveryRequest {
    token: Address,
    connectors: Vec<Address>,
    protocol: Option<ProtocolId>,
}

impl TokenEdgeDiscoveryRequest {
    /// Discover pools joining `token` to each configured connector.
    pub fn new(token: Address, connectors: impl IntoIterator<Item = Address>) -> Self {
        let mut connectors: Vec<_> = connectors
            .into_iter()
            .filter(|connector| *connector != token)
            .collect();
        connectors.sort_unstable();
        connectors.dedup();
        Self {
            token,
            connectors,
            protocol: None,
        }
    }

    /// Restrict the connector query to one protocol.
    pub const fn with_protocol(mut self, protocol: ProtocolId) -> Self {
        self.protocol = Some(protocol);
        self
    }

    /// Token whose edges are being discovered.
    pub const fn token(&self) -> Address {
        self.token
    }

    /// Canonically ordered connector set.
    pub fn connectors(&self) -> &[Address] {
        &self.connectors
    }

    /// Optional protocol restriction.
    pub const fn protocol(&self) -> Option<ProtocolId> {
        self.protocol
    }

    /// Convert this request into the existing declarative query vocabulary.
    pub fn query(&self) -> PoolQuery {
        let query = PoolQuery::pairs(
            self.connectors
                .iter()
                .copied()
                .map(|connector| (self.token, connector)),
        );
        match self.protocol {
            Some(protocol) => query.on(protocol),
            None => query,
        }
    }
}

/// Completed connector-focused discovery result.
#[derive(Clone, Debug)]
pub struct TokenEdgeDiscoveryReport {
    request: TokenEdgeDiscoveryRequest,
    discovered: Vec<DiscoveredPool>,
}

impl TokenEdgeDiscoveryReport {
    /// Pair one immutable request with its assembled discovered pools.
    pub fn new(request: TokenEdgeDiscoveryRequest, discovered: Vec<DiscoveredPool>) -> Self {
        Self {
            request,
            discovered,
        }
    }

    /// Request that produced this report.
    pub const fn request(&self) -> &TokenEdgeDiscoveryRequest {
        &self.request
    }

    /// De-duplicated pools found for the connector set.
    pub fn discovered(&self) -> &[DiscoveredPool] {
        &self.discovered
    }

    /// Consume the report into its request and pools.
    pub fn into_parts(self) -> (TokenEdgeDiscoveryRequest, Vec<DiscoveredPool>) {
        (self.request, self.discovered)
    }
}

/// Factory configuration. Defaults are intentionally empty; callers must opt in
/// to concrete factory addresses or explicit presets. Each protocol accepts
/// multiple factory configs (e.g. Uniswap plus a same-protocol fork), which are
/// resolved in insertion order.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FactoryConfig {
    /// Uniswap V2 factories (canonical plus same-protocol forks).
    #[cfg(feature = "uniswap-v2")]
    pub uniswap_v2: Vec<UniswapV2FactoryConfig>,
    /// Concentrated-liquidity forks (Uniswap V3, SushiSwap V3, PancakeSwap V3,
    /// Slipstream). Every UniV3-mechanics fork is one [`ClFactorySpec`]; the
    /// V3-family adapter emits a [`ConcentratedLiquidityFactory`] per spec whose
    /// protocol it serves.
    #[cfg(feature = "uniswap-v3")]
    pub concentrated_liquidity: Vec<ClFactorySpec>,
    /// Solidly V2 forks (Aerodrome / Velodrome V2). Every fork is one
    /// [`SolidlyFactoryConfig`]; the Solidly adapter emits a [`SolidlyFactory`]
    /// per config.
    #[cfg(feature = "solidly-v2")]
    pub solidly: Vec<SolidlyFactoryConfig>,
    /// Global switch for the CREATE2 cross-check: a spec's derivation
    /// verification runs only when both this and the spec opt in. Defaults `true`.
    pub verify_derivations: bool,
}

impl Default for FactoryConfig {
    fn default() -> Self {
        Self {
            #[cfg(feature = "uniswap-v2")]
            uniswap_v2: Vec::new(),
            #[cfg(feature = "uniswap-v3")]
            concentrated_liquidity: Vec::new(),
            #[cfg(feature = "solidly-v2")]
            solidly: Vec::new(),
            verify_derivations: true,
        }
    }
}

impl FactoryConfig {
    /// Add a Uniswap V2 factory by its [`UniswapV2FactoryConfig`].
    #[cfg(feature = "uniswap-v2")]
    pub fn with_uniswap_v2(mut self, config: UniswapV2FactoryConfig) -> Self {
        self.uniswap_v2.push(config);
        self
    }

    /// Add a canonical Uniswap V2 factory at `factory`.
    #[cfg(feature = "uniswap-v2")]
    pub fn with_uniswap_v2_factory(self, factory: Address) -> Self {
        self.with_uniswap_v2(UniswapV2FactoryConfig::uniswap_v2(factory))
    }

    /// Add a concentrated-liquidity fork by its [`ClFactorySpec`] — the general
    /// entry point behind the per-fork conveniences below.
    #[cfg(feature = "uniswap-v3")]
    pub fn with_concentrated_liquidity(mut self, spec: ClFactorySpec) -> Self {
        self.concentrated_liquidity.push(spec);
        self
    }

    /// Add a concentrated-liquidity fork by its [`ClFactorySpec`].
    ///
    /// Alias for [`with_concentrated_liquidity`](Self::with_concentrated_liquidity),
    /// kept so existing call sites that passed a V3 factory config keep reading
    /// naturally now that the config is a `ClFactorySpec`.
    #[cfg(feature = "uniswap-v3")]
    pub fn with_uniswap_v3(self, spec: ClFactorySpec) -> Self {
        self.with_concentrated_liquidity(spec)
    }

    /// Add a canonical Uniswap V3 factory at `factory`.
    #[cfg(feature = "uniswap-v3")]
    pub fn with_uniswap_v3_factory(self, factory: Address) -> Self {
        self.with_concentrated_liquidity(ClFactorySpec::uniswap_v3(factory))
    }

    /// Add a PancakeSwap V3 factory at `factory` (Pancake preset).
    #[cfg(feature = "uniswap-v3")]
    pub fn with_pancake_v3_factory(self, factory: Address) -> Self {
        self.with_concentrated_liquidity(ClFactorySpec::pancake_v3(factory))
    }

    /// Add a Slipstream / Aerodrome CL factory at `factory` (Slipstream preset).
    #[cfg(feature = "uniswap-v3")]
    pub fn with_slipstream_factory(self, factory: Address) -> Self {
        self.with_concentrated_liquidity(ClFactorySpec::slipstream(factory))
    }

    /// Add a Solidly V2 fork (Aerodrome / Velodrome V2) by its
    /// [`SolidlyFactoryConfig`].
    #[cfg(feature = "solidly-v2")]
    pub fn with_solidly(mut self, config: SolidlyFactoryConfig) -> Self {
        self.solidly.push(config);
        self
    }

    /// Add a Solidly V2 factory at `factory` using the Aerodrome preset.
    #[cfg(feature = "solidly-v2")]
    pub fn with_solidly_factory(self, factory: Address) -> Self {
        self.with_solidly(SolidlyFactoryConfig::aerodrome(factory))
    }

    /// Toggle the global CREATE2 derivation cross-check (default `true`).
    pub fn with_verify_derivations(mut self, verify_derivations: bool) -> Self {
        self.verify_derivations = verify_derivations;
        self
    }
}

/// Configuration for one Uniswap V2 (or V2-fork) factory.
#[cfg(feature = "uniswap-v2")]
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UniswapV2FactoryConfig {
    /// The factory contract address.
    pub factory: Address,
    /// Base storage slot of the factory's `getPair[t0][t1]` mapping.
    pub get_pair_base_slot: U256,
    /// Optional pair init-code hash for the CREATE2 cross-check.
    pub init_code_hash: Option<B256>,
    /// Optional swap fee (basis points) carried into discovered pool metadata.
    pub fee_bps: Option<u32>,
}

#[cfg(feature = "uniswap-v2")]
impl UniswapV2FactoryConfig {
    /// A canonical Uniswap V2 factory preset at `factory`.
    pub fn uniswap_v2(factory: Address) -> Self {
        Self {
            factory,
            get_pair_base_slot: UNISWAP_V2_GET_PAIR_BASE_SLOT,
            init_code_hash: None,
            fee_bps: None,
        }
    }

    /// Override the `getPair` mapping base slot (for a non-canonical fork).
    pub fn with_get_pair_base_slot(mut self, slot: U256) -> Self {
        self.get_pair_base_slot = slot;
        self
    }

    /// Set the pair init-code hash (enables the CREATE2 cross-check).
    pub fn with_init_code_hash(mut self, hash: B256) -> Self {
        self.init_code_hash = Some(hash);
        self
    }

    /// Set the swap fee (basis points) for discovered pools.
    pub fn with_fee_bps(mut self, fee_bps: u32) -> Self {
        self.fee_bps = Some(fee_bps);
        self
    }
}

/// How a concentrated-liquidity factory keys its `getPool` mapping and where the
/// per-pool tick spacing comes from.
///
/// Two shapes cover every UniV3-mechanics fork this crate serves:
/// - [`Fee`](Self::Fee): the innermost `getPool` key is the fee tier
///   (`getPool[t0][t1][fee]`), and the spacing is read from
///   `feeAmountTickSpacing[fee]` — Uniswap V3, SushiSwap V3, PancakeSwap V3.
/// - [`TickSpacing`](Self::TickSpacing): the innermost key *is* the tick spacing
///   (`getPool[t0][t1][tickSpacing]`); there is no `feeAmountTickSpacing` read —
///   Slipstream / Aerodrome CL.
#[cfg(feature = "uniswap-v3")]
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ClKeying {
    /// `getPool[t0][t1][fee]`; tick spacing comes from `feeAmountTickSpacing[fee]`.
    Fee {
        /// The fee tiers (hundredths of a bip) to probe per pair.
        tiers: Vec<u32>,
        /// Base slot of the `feeAmountTickSpacing` mapping.
        fee_amount_tick_spacing_base_slot: U256,
    },
    /// `getPool[t0][t1][tickSpacing]`; NO `feeAmountTickSpacing` read.
    TickSpacing {
        /// The int24 tick spacings to probe per pair.
        spacings: Vec<i32>,
    },
}

/// Where a discovered pool's swap `fee` (hundredths of a bip) is resolved from.
/// STATIC — resolved once at discovery time, never recomputed per-swap.
#[cfg(feature = "uniswap-v3")]
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FeeSource {
    /// The fee is the pool-key tier itself (only valid with [`ClKeying::Fee`]).
    Key,
    /// Read the fee from a factory mapping keyed by the pool key
    /// (`feeAmountTickSpacing`-style for fee keying, `tickSpacingToFee[spacing]`
    /// for tickSpacing keying) at `base_slot`.
    FactoryMapping {
        /// Base slot of the fee mapping.
        base_slot: U256,
    },
    /// A constant fee for every pool of this factory.
    Fixed(u32),
}

/// Optional CREATE2 cross-check for a concentrated-liquidity fork: when present
/// (and [`ClFactorySpec::verify_derivations`] is on), the factory re-derives the
/// pool address from the salt and compares it to the mapping answer, hard-failing
/// [`DiscoveryError::DerivationMismatch`] on disagreement — a guardrail against a
/// wrong init-code hash or base slot.
#[cfg(feature = "uniswap-v3")]
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ClCreate2 {
    /// The CREATE2 deployer. `None` means "the factory itself" (Uniswap V3);
    /// forks that deploy from a separate contract (PancakeSwap) set it explicitly.
    pub deployer: Option<Address>,
    /// The pool init-code hash.
    pub init_code_hash: B256,
}

/// Data-driven specification of a concentrated-liquidity (UniV3-mechanics) fork,
/// driving [`ConcentratedLiquidityFactory`]. Construct with the
/// [`fee_keyed`](Self::fee_keyed) / [`tick_spacing_keyed`](Self::tick_spacing_keyed)
/// constructors or a fork preset ([`uniswap_v3`](Self::uniswap_v3),
/// [`sushi_v3`](Self::sushi_v3), [`pancake_v3`](Self::pancake_v3),
/// [`slipstream`](Self::slipstream)), then refine with the `with_*` builders.
#[cfg(feature = "uniswap-v3")]
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ClFactorySpec {
    /// The protocol identity discovered pools register under (drives the
    /// [`PoolKey`]/[`ProtocolMetadata`] variant and storage-layout preset).
    pub protocol: ProtocolId,
    /// The factory contract address.
    pub factory: Address,
    /// Base slot of the `getPool` nested mapping.
    pub get_pool_base_slot: U256,
    /// How the `getPool` mapping is keyed and where tick spacing comes from.
    pub keying: ClKeying,
    /// Where a discovered pool's fee is resolved from.
    pub fee_source: FeeSource,
    /// Optional CREATE2 cross-check of the mapping answer.
    pub create2: Option<ClCreate2>,
    /// Per-fork swap-quote target. `None` => the caller's
    /// [`SimConfig::v3_quoter`](super::SimConfig::v3_quoter).
    pub quoter: Option<Address>,
    /// Push-discovery creation-event `topic0`. `None` => pull-only (no creation
    /// sources, `decode_creation` returns `Ok(None)`).
    pub creation_topic0: Option<B256>,
    /// Whether to run the CREATE2 cross-check (requires [`create2`](Self::create2)).
    pub verify_derivations: bool,
}

#[cfg(feature = "uniswap-v3")]
impl ClFactorySpec {
    /// A fee-keyed CL fork (Uniswap/Sushi/Pancake shape): `getPool[t0][t1][fee]`
    /// with tick spacing from `feeAmountTickSpacing[fee]`, `fee_source: Key`.
    pub fn fee_keyed(
        protocol: ProtocolId,
        factory: Address,
        get_pool_base_slot: U256,
        fee_amount_tick_spacing_base_slot: U256,
        tiers: impl IntoIterator<Item = u32>,
    ) -> Self {
        Self {
            protocol,
            factory,
            get_pool_base_slot,
            keying: ClKeying::Fee {
                tiers: tiers.into_iter().collect(),
                fee_amount_tick_spacing_base_slot,
            },
            fee_source: FeeSource::Key,
            create2: None,
            quoter: None,
            creation_topic0: None,
            verify_derivations: false,
        }
    }

    /// A tickSpacing-keyed CL fork (Slipstream shape): `getPool[t0][t1][spacing]`
    /// only — no `feeAmountTickSpacing` read. Fee defaults to `Fixed(0)`, the
    /// "no fee mapping" sentinel: discovered registrations leave `V3Metadata.fee`
    /// **unset** (so `simulate_swap` returns `MissingMetadata("V3 fee")` rather
    /// than quoting at fee 0 — these forks are discovery-only for quoting unless
    /// the caller supplies a compatible quoter). Set a real
    /// [`fee_source`](Self::with_fee_source) if the fork exposes one on-chain.
    pub fn tick_spacing_keyed(
        protocol: ProtocolId,
        factory: Address,
        get_pool_base_slot: U256,
        spacings: impl IntoIterator<Item = i32>,
    ) -> Self {
        Self {
            protocol,
            factory,
            get_pool_base_slot,
            keying: ClKeying::TickSpacing {
                spacings: spacings.into_iter().collect(),
            },
            fee_source: FeeSource::Fixed(0),
            create2: None,
            quoter: None,
            creation_topic0: None,
            verify_derivations: false,
        }
    }

    /// Set the per-fork swap-quote target (a fork's own QuoterV2).
    pub fn with_quoter(mut self, quoter: Address) -> Self {
        self.quoter = Some(quoter);
        self
    }

    /// Set the CREATE2 cross-check (`deployer: None` => the factory itself).
    pub fn with_create2(mut self, deployer: Option<Address>, init_code_hash: B256) -> Self {
        self.create2 = Some(ClCreate2 {
            deployer,
            init_code_hash,
        });
        self
    }

    /// Toggle the CREATE2 derivation cross-check (needs [`with_create2`](Self::with_create2)).
    pub fn with_verify_derivations(mut self, verify: bool) -> Self {
        self.verify_derivations = verify;
        self
    }

    /// Set the push-discovery creation-event `topic0`.
    pub fn with_creation_topic0(mut self, topic0: B256) -> Self {
        self.creation_topic0 = Some(topic0);
        self
    }

    /// Set where a discovered pool's fee is resolved from.
    pub fn with_fee_source(mut self, fee_source: FeeSource) -> Self {
        self.fee_source = fee_source;
        self
    }

    /// Replace the probed fee tiers (fee keying) — no-op under tickSpacing keying.
    pub fn with_fee_tiers(mut self, fee_tiers: impl IntoIterator<Item = u32>) -> Self {
        if let ClKeying::Fee { tiers, .. } = &mut self.keying {
            *tiers = fee_tiers.into_iter().collect();
        }
        self
    }

    /// Replace the probed tick spacings (tickSpacing keying) — no-op under fee keying.
    pub fn with_tick_spacings(mut self, spacings: impl IntoIterator<Item = i32>) -> Self {
        if let ClKeying::TickSpacing { spacings: s } = &mut self.keying {
            *s = spacings.into_iter().collect();
        }
        self
    }

    /// The `feeAmountTickSpacing` mapping base slot for a fee-keyed spec; `None`
    /// for a tickSpacing-keyed spec (which has no such mapping).
    pub fn fee_amount_tick_spacing_base_slot(&self) -> Option<U256> {
        match &self.keying {
            ClKeying::Fee {
                fee_amount_tick_spacing_base_slot,
                ..
            } => Some(*fee_amount_tick_spacing_base_slot),
            ClKeying::TickSpacing { .. } => None,
        }
    }

    /// The fee tiers probed per pair under fee keying; empty under tickSpacing
    /// keying (which probes spacings, not fees — see [`tick_spacings`](Self::tick_spacings)).
    pub fn fee_tiers(&self) -> &[u32] {
        match &self.keying {
            ClKeying::Fee { tiers, .. } => tiers,
            ClKeying::TickSpacing { .. } => &[],
        }
    }

    /// The tick spacings probed per pair under tickSpacing keying; empty under
    /// fee keying.
    pub fn tick_spacings(&self) -> &[i32] {
        match &self.keying {
            ClKeying::TickSpacing { spacings } => spacings,
            ClKeying::Fee { .. } => &[],
        }
    }

    // --- Fork presets ---

    /// Canonical Uniswap V3 factory: base slot 5, fee tiers `[100, 500, 3000,
    /// 10000]` with `feeAmountTickSpacing` at slot 4, canonical `PoolCreated`
    /// push topic. No CREATE2 hash by default (add one with
    /// [`with_create2`](Self::with_create2) to enable the cross-check); quoter
    /// left to the caller.
    pub fn uniswap_v3(factory: Address) -> Self {
        Self::fee_keyed(
            ProtocolId::UniswapV3,
            factory,
            UNISWAP_V3_GET_POOL_BASE_SLOT,
            UNISWAP_V3_FEE_AMOUNT_TICK_SPACING_BASE_SLOT,
            UNISWAP_V3_CANONICAL_FEE_TIERS,
        )
        .with_creation_topic0(PoolCreated::SIGNATURE_HASH)
    }

    /// SushiSwap V3 — byte-identical Uniswap V3 fork. Registers as
    /// [`ProtocolId::UniswapV3`] (same PoolKey/adapter); differs only by factory
    /// address and (optionally) quoter. Its init-code hash is left unset (pin it
    /// with [`with_create2`](Self::with_create2); the gated parity test verifies).
    pub fn sushi_v3(factory: Address) -> Self {
        // Same shape as Uniswap V3 (Sushi V3 pools register as UniswapV3).
        Self::uniswap_v3(factory)
    }

    /// PancakeSwap V3 factory. Protocol [`ProtocolId::PancakeV3`], fee tiers
    /// `[100, 500, 2500, 10000]`, CREATE2 via the Pancake `PoolDeployer` +
    /// init-code hash, and the Pancake `QuoterV2` (Uniswap-compatible quote ABI).
    ///
    /// The `getPool` (slot 2) and `feeAmountTickSpacing` (slot 1) base slots are
    /// VERIFIED on-chain — they differ from Uniswap's 5 / 4 — and the CREATE2
    /// deployer + init-code hash reproduce the getter's pool, so
    /// `verify_derivations` is ON (the mapping answer is cross-checked against the
    /// CREATE2 derivation on first use).
    pub fn pancake_v3(factory: Address) -> Self {
        Self::fee_keyed(
            ProtocolId::PancakeV3,
            factory,
            PANCAKE_V3_GET_POOL_BASE_SLOT,
            PANCAKE_V3_FEE_AMOUNT_TICK_SPACING_BASE_SLOT,
            PANCAKE_V3_FEE_TIERS,
        )
        .with_create2(Some(PANCAKE_V3_POOL_DEPLOYER), PANCAKE_V3_INIT_CODE_HASH)
        .with_quoter(PANCAKE_V3_QUOTER_V2)
        .with_creation_topic0(PoolCreated::SIGNATURE_HASH)
        .with_verify_derivations(true)
    }

    /// Slipstream / Aerodrome CL factory. Protocol [`ProtocolId::Slipstream`],
    /// tickSpacing-keyed, spacings `[1, 50, 100, 200, 2000]`.
    ///
    /// The `getPool` base slot is VERIFIED on-chain (Base CLFactory). `create2`
    /// and `quoter` are left `None` on purpose:
    /// - the pool init-code hash + full spacing table are not pinned here (the
    ///   gated parity test covers the base slot);
    /// - the Slipstream quoter takes a `tickSpacing`-keyed struct, NOT the
    ///   Uniswap `(…, fee, …)` struct this crate encodes, so wiring it as the V3
    ///   quote target would send malformed calldata. Slipstream is therefore
    ///   discovery-only for quoting: its discovered `fee` is left unset, so
    ///   `simulate_swap` returns `MissingMetadata("V3 fee")` unless the caller
    ///   supplies a Slipstream-compatible quoter and fee.
    pub fn slipstream(factory: Address) -> Self {
        Self::tick_spacing_keyed(
            ProtocolId::Slipstream,
            factory,
            SLIPSTREAM_GET_POOL_BASE_SLOT,
            SLIPSTREAM_TICK_SPACINGS,
        )
        .with_creation_topic0(PoolCreatedTickSpacing::SIGNATURE_HASH)
    }
}

/// Backwards-compatible name for the canonical V3-family factory spec.
///
/// Existing call sites can keep using `UniswapV3FactoryConfig::uniswap_v3(...)`
/// while the implementation handles broader concentrated-liquidity forks via
/// [`ClFactorySpec`].
#[cfg(feature = "uniswap-v3")]
pub type UniswapV3FactoryConfig = ClFactorySpec;

/// Aerodrome / Velodrome V2 pool storage layout used by the `aerodrome`/
/// `velodrome` presets — VERIFIED on-chain (Aerodrome WETH/USDC pool, Base block
/// 47_700_000): reserve0 @ 20, reserve1 @ 21, token0 @ 13, token1 @ 14. Velodrome
/// V2 shares Aerodrome's contract, so the same layout applies. `new(..)` callers
/// supply their own layout for other forks.
#[cfg(feature = "solidly-v2")]
const SOLIDLY_AERODROME_LAYOUT: SolidlyStorageLayout = SolidlyStorageLayout::new(
    U256::from_limbs([20, 0, 0, 0]),
    U256::from_limbs([21, 0, 0, 0]),
    U256::from_limbs([13, 0, 0, 0]),
    U256::from_limbs([14, 0, 0, 0]),
);

/// Declarative configuration for a Solidly V2 (Aerodrome / Velodrome V2) factory.
///
/// Solidly pools are discovered by a [`DerivedSlot`] read of the factory's
/// `getPool[token0][token1][bool stable]` nested mapping (see
/// [`derive::solidly_get_pool_slot`]) — each pair yields up to TWO pools, a
/// stable and a volatile one. Discovery does NOT resolve the swap fee (Solidly
/// pools self-quote via `getAmountOut`, and the fee is a factory `getFee` read at
/// sim time), so there is no quoter to wire.
///
/// Construct with [`new`](Self::new) or a fork preset ([`aerodrome`](Self::aerodrome),
/// [`velodrome`](Self::velodrome)), then refine with the `with_*` builders.
///
/// [`DerivedSlot`]: crate::adapters::factory
#[cfg(feature = "solidly-v2")]
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SolidlyFactoryConfig {
    /// The `PoolFactory` contract address.
    pub factory: Address,
    /// Base slot of the `getPool[t0][t1][stable]` nested mapping.
    pub get_pool_base_slot: U256,
    /// The fork's reserve/token storage layout, attached to every discovered
    /// pool so cold-start can warm the right slots.
    pub storage_layout: SolidlyStorageLayout,
    /// Optional CREATE2 cross-check of the mapping answer. Reuses [`ClCreate2`]
    /// (`deployer` + `init_code_hash`); the salt scheme is Solidly-specific (see
    /// [`derive::solidly_pool_address`]).
    #[cfg(feature = "uniswap-v3")]
    pub create2: Option<ClCreate2>,
    /// Optional CREATE2 cross-check of the mapping answer (deployer +
    /// init-code hash); the salt scheme is Solidly-specific (see
    /// [`derive::solidly_pool_address`]).
    ///
    /// Mirrors the `uniswap-v3`-gated [`ClCreate2`] shape so the Solidly cfg
    /// compiles in isolation (without `uniswap-v3`).
    #[cfg(not(feature = "uniswap-v3"))]
    pub create2: Option<SolidlyCreate2>,
    /// Push-discovery creation-event `topic0`. `None` => pull-only (no creation
    /// sources, `decode_creation` returns `Ok(None)`).
    pub creation_topic0: Option<B256>,
    /// Whether to run the CREATE2 cross-check (requires [`create2`](Self::create2)).
    pub verify_derivations: bool,
}

/// Optional CREATE2 cross-check parameters for a Solidly V2 factory when the
/// `uniswap-v3` feature (which owns [`ClCreate2`]) is not enabled.
///
/// Field-identical to [`ClCreate2`]; exists only so the Solidly discovery path
/// compiles in isolation. When `uniswap-v3` is on, [`SolidlyFactoryConfig`]
/// reuses [`ClCreate2`] directly as the spec requires.
#[cfg(all(feature = "solidly-v2", not(feature = "uniswap-v3")))]
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SolidlyCreate2 {
    /// The CREATE2 deployer. `None` means "the factory itself".
    pub deployer: Option<Address>,
    /// The pool init-code hash.
    pub init_code_hash: B256,
}

/// The CREATE2 cross-check type [`SolidlyFactoryConfig`] carries: [`ClCreate2`]
/// when `uniswap-v3` is enabled (as the spec requires), else the standalone
/// [`SolidlyCreate2`] mirror so the Solidly cfg builds in isolation.
#[cfg(all(feature = "solidly-v2", feature = "uniswap-v3"))]
type SolidlyCreate2Params = ClCreate2;
#[cfg(all(feature = "solidly-v2", not(feature = "uniswap-v3")))]
type SolidlyCreate2Params = SolidlyCreate2;

#[cfg(feature = "solidly-v2")]
impl SolidlyFactoryConfig {
    /// A Solidly V2 factory with an explicit `getPool` base slot and storage
    /// layout. `create2` is `None` and `verify_derivations` is off; add a
    /// cross-check with [`with_create2`](Self::with_create2).
    pub fn new(
        factory: Address,
        get_pool_base_slot: U256,
        storage_layout: SolidlyStorageLayout,
    ) -> Self {
        Self {
            factory,
            get_pool_base_slot,
            storage_layout,
            create2: None,
            creation_topic0: None,
            verify_derivations: false,
        }
    }

    /// Aerodrome (Base) preset.
    ///
    /// The `getPool` base slot (5) and pool storage layout are VERIFIED on-chain
    /// (Base) via trace-based slot discovery; the gated `discovery_solidly_rpc`
    /// parity test re-checks them against the live factory. No CREATE2 init-code
    /// hash is pinned (Solidly's salt is packed), so `verify_derivations` stays OFF.
    pub fn aerodrome(factory: Address) -> Self {
        Self::new(
            factory,
            SOLIDLY_GET_POOL_BASE_SLOT,
            SOLIDLY_AERODROME_LAYOUT,
        )
        .with_creation_topic0(SolidlyPoolCreated::SIGNATURE_HASH)
    }

    /// Velodrome (Optimism) preset. Byte-identical Solidly-V2 shape to Aerodrome;
    /// it reuses Aerodrome's base slot + layout and `PoolCreated` push topic.
    /// Those constants are confirmed on Base for Aerodrome but are NOT yet
    /// verified for Velodrome on Optimism — treat them as provisional and run the
    /// gated parity check against an Optimism endpoint before relying on this
    /// preset in production.
    pub fn velodrome(factory: Address) -> Self {
        Self::aerodrome(factory)
    }

    /// Set the CREATE2 cross-check (`deployer: None` => the factory itself).
    pub fn with_create2(mut self, deployer: Option<Address>, init_code_hash: B256) -> Self {
        self.create2 = Some(SolidlyCreate2Params {
            deployer,
            init_code_hash,
        });
        self
    }

    /// Toggle the CREATE2 derivation cross-check (needs [`with_create2`](Self::with_create2)).
    pub fn with_verify_derivations(mut self, verify: bool) -> Self {
        self.verify_derivations = verify;
        self
    }

    /// Set the push-discovery creation-event `topic0`.
    pub fn with_creation_topic0(mut self, topic0: B256) -> Self {
        self.creation_topic0 = Some(topic0);
        self
    }
}

/// Source of a discovered pool.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DiscoverySource {
    /// Resolved by a factory-storage / view query (a [`PoolQuery`]).
    Query,
    /// Decoded from a factory creation log.
    CreationEvent {
        /// The creation log's block number, if known.
        block_number: Option<u64>,
        /// The creation log's index within the block, if known.
        log_index: Option<u64>,
    },
}

/// Context supplied alongside a factory creation log.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CreationLogContext {
    /// The log's block number, if known.
    pub block_number: Option<u64>,
    /// The log's index within the block, if known.
    pub log_index: Option<u64>,
}

impl CreationLogContext {
    /// A context from an optional block number and log index.
    pub const fn new(block_number: Option<u64>, log_index: Option<u64>) -> Self {
        Self {
            block_number,
            log_index,
        }
    }
}

/// A pool located by factory query or creation log.
///
/// `#[non_exhaustive]` (matching the rest of the discovery vocabulary): external
/// [`PoolFactory`] implementations construct this via [`DiscoveredPool::new`]
/// (the open-channel `with_factory` path), so new fields can be added without a
/// breaking change.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct DiscoveredPool {
    /// The discovered pool's key.
    pub key: PoolKey,
    /// A cold-start-ready registration for the pool.
    pub registration: PoolRegistration,
    /// How the pool was discovered.
    pub source: DiscoverySource,
}

impl DiscoveredPool {
    /// Assemble a discovered pool from its key, registration, and provenance.
    pub fn new(key: PoolKey, registration: PoolRegistration, source: DiscoverySource) -> Self {
        Self {
            key,
            registration,
            source,
        }
    }
}

/// Errors produced by factory-backed discovery.
#[derive(Debug)]
#[non_exhaustive]
pub enum DiscoveryError {
    /// A `.on(protocol)`-scoped query named a protocol with no configured factory.
    MissingFactory(ProtocolId),
    /// The factory query (storage read / view call) failed.
    Factory(Box<dyn std::error::Error + Send + Sync + 'static>),
    /// A factory response could not be decoded.
    Malformed(&'static str),
    /// The factory mapping answer disagrees with the CREATE2 derivation.
    DerivationMismatch {
        /// The pool address the factory mapping returned.
        mapping: Address,
        /// The pool address derived from CREATE2 (init-code hash + salt).
        derived: Address,
    },
    /// Provider-neutral prepared mode cannot execute a legacy factory whose
    /// only query path requires a mutable [`AdapterCache`].
    PreparedModeUnsupported {
        /// Protocol served by the legacy factory.
        protocol: ProtocolId,
        /// Address identifying the legacy factory.
        factory: Address,
    },
    /// A worker omitted one exact candidate value requested by its prepared plan.
    MissingPreparedValue {
        /// Contract whose storage was requested.
        address: Address,
        /// Requested storage slot.
        slot: U256,
    },
    /// A worker supplied the same prepared value more than once.
    DuplicatePreparedValue {
        /// Contract whose storage value was duplicated.
        address: Address,
        /// Duplicated storage slot.
        slot: U256,
    },
    /// A prepared plan was assembled against a different discovery registry.
    PreparedFactoryMismatch {
        /// Factory protocol recorded by the prepared plan.
        protocol: ProtocolId,
        /// Factory address recorded by the prepared plan.
        factory: Address,
    },
}

impl fmt::Display for DiscoveryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingFactory(protocol) => write!(f, "missing factory for {protocol:?}"),
            Self::Factory(err) => write!(f, "factory query failed: {err}"),
            Self::Malformed(message) => write!(f, "malformed factory response: {message}"),
            Self::DerivationMismatch { mapping, derived } => write!(
                f,
                "factory mapping answer {mapping:?} disagrees with CREATE2 derivation {derived:?}"
            ),
            Self::PreparedModeUnsupported { protocol, factory } => write!(
                f,
                "factory {factory:?} for {protocol:?} requires mutable-cache discovery and cannot run in prepared mode"
            ),
            Self::MissingPreparedValue { address, slot } => write!(
                f,
                "prepared discovery omitted storage value {address:?}[{slot}]"
            ),
            Self::DuplicatePreparedValue { address, slot } => write!(
                f,
                "prepared discovery supplied storage value {address:?}[{slot}] more than once"
            ),
            Self::PreparedFactoryMismatch { protocol, factory } => write!(
                f,
                "prepared discovery factory {protocol:?}@{factory:?} is absent or moved"
            ),
        }
    }
}

impl std::error::Error for DiscoveryError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Factory(err) => Some(&**err as &(dyn std::error::Error + 'static)),
            _ => None,
        }
    }
}

impl From<super::CacheError> for DiscoveryError {
    fn from(err: super::CacheError) -> Self {
        Self::Factory(Box::new(err))
    }
}

/// Per-protocol factory driver.
pub trait PoolFactory: Send + Sync {
    /// The protocol whose pools this factory resolves.
    fn protocol(&self) -> ProtocolId;

    /// Address of the factory contract this driver resolves against. Used
    /// together with [`PoolFactory::protocol`] as the identity for
    /// de-duplication, so distinct addresses of the same protocol are all kept.
    fn factory_address(&self) -> Address;

    /// Resolve a single normalized `(token0, token1)` pair to its pool(s).
    ///
    /// The default derives from the batched
    /// [`candidate_reads`](Self::candidate_reads) /
    /// [`assemble_pairs`](Self::assemble_pairs) pair — so a factory that
    /// implements those participates in single-pair discovery for free.
    /// [`PoolDiscovery::find`] calls this only as a per-pair fallback for
    /// factories that opt out of batching (empty `candidate_reads`); such
    /// external factories override it directly.
    fn find_pools(
        &self,
        cache: &mut dyn AdapterCache,
        pair: (Address, Address),
    ) -> Result<Vec<DiscoveredPool>, DiscoveryError> {
        let slots = self.candidate_reads(&[pair]);
        if slots.is_empty() {
            return Ok(Vec::new());
        }
        let values = cache.read_storage_slots(&slots)?;
        let resolved = slots.into_iter().zip(values).collect();
        self.assemble_pairs(&[pair], &resolved)
    }

    /// The storage reads (`(factory_address, slot)`) this factory needs to
    /// resolve every pair in `pairs`. Returning them instead of executing lets
    /// [`PoolDiscovery::find`] gather the candidate slots of *all* pairs across
    /// *all* factories and resolve them in a single batched
    /// [`AdapterCache::read_storage_slots`] call.
    ///
    /// Defaults to none: a factory that does not implement batched multi-pair
    /// discovery simply contributes no pools to a batched query (and its
    /// [`find_pools`](Self::find_pools) override runs per pair instead).
    fn candidate_reads(&self, pairs: &[(Address, Address)]) -> Vec<(Address, U256)> {
        let _ = pairs;
        Vec::new()
    }

    /// Assemble discovered pools from already-resolved candidate reads
    /// (`values`, keyed by `(factory_address, slot)`) — the batched counterpart
    /// to [`find_pools`](Self::find_pools). Must read only slots this factory
    /// previously returned from [`candidate_reads`](Self::candidate_reads).
    fn assemble_pairs(
        &self,
        pairs: &[(Address, Address)],
        values: &HashMap<(Address, U256), U256>,
    ) -> Result<Vec<DiscoveredPool>, DiscoveryError> {
        let _ = (pairs, values);
        Ok(Vec::new())
    }

    /// The log sources (factory address + creation topic) to subscribe for
    /// live pool-creation discovery.
    fn creation_sources(&self) -> Vec<EventSource>;

    /// Decode a factory creation log into a discovered pool, or `None` if the
    /// log is not a creation event this factory handles.
    fn decode_creation(
        &self,
        log: &Log,
        context: CreationLogContext,
    ) -> Result<Option<DiscoveredPool>, DiscoveryError>;
}

#[derive(Clone, Debug)]
struct PreparedFactoryQuery {
    factory_index: usize,
    protocol: ProtocolId,
    factory: Address,
    pairs: Vec<(Address, Address)>,
    reads: Vec<(Address, U256)>,
    legacy: bool,
}

/// Immutable provider-neutral plan for one or more discovery queries.
///
/// A background worker fetches [`reads`](Self::reads) at its exact block/hash
/// pin, then returns those values to [`PoolDiscovery::assemble_prepared`]. The
/// plan contains no cache or provider handle and is safe to retain alongside an
/// `Arc<PoolDiscovery>`.
#[derive(Clone, Debug)]
pub struct PreparedDiscoveryReads {
    reads: Vec<(Address, U256)>,
    factories: Vec<PreparedFactoryQuery>,
}

impl PreparedDiscoveryReads {
    /// Canonically sorted and de-duplicated `(address, slot)` values to fetch.
    pub fn reads(&self) -> &[(Address, U256)] {
        &self.reads
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LegacyFactoryMode {
    Allow,
    Reject,
}

/// Front-end that fans discovery across registered adapter factory drivers.
///
/// Factories are held in insertion order, so iteration (and thus the order of
/// concatenated results) is deterministic. Multiple factories may share a
/// [`ProtocolId`] — e.g. Uniswap and a same-protocol fork — and every matching
/// factory is consulted. Identity is `(protocol, factory_address)`; exact
/// duplicates are dropped (first wins) so a repeated factory does not run twice.
#[derive(Default)]
pub struct PoolDiscovery {
    factories: Vec<Box<dyn PoolFactory>>,
}

impl PoolDiscovery {
    /// A discovery front-end over an explicit set of factory drivers
    /// (de-duplicated by `(protocol, factory_address)`, insertion order kept).
    pub fn new(factories: impl IntoIterator<Item = Box<dyn PoolFactory>>) -> Self {
        let mut discovery = Self {
            factories: Vec::new(),
        };
        for factory in factories {
            discovery.push_unique(factory);
        }
        discovery
    }

    /// Build discovery by fanning `config` out to every registered adapter's
    /// `pool_factories`, collecting the resulting drivers.
    pub fn for_registry(registry: &AdapterRegistry, config: FactoryConfig) -> Self {
        let mut factories = Vec::new();
        let mut seen = Vec::new();
        for adapter in registry.adapters() {
            let ptr = std::sync::Arc::as_ptr(adapter);
            if seen.contains(&ptr) {
                continue;
            }
            seen.push(ptr);
            factories.extend(adapter.pool_factories(&config));
        }
        Self::new(factories)
    }

    /// Open channel for extending discovery with an externally-implemented
    /// [`PoolFactory`]. Appends the factory, applying the same
    /// `(protocol, factory_address)` de-duplication as [`PoolDiscovery::new`].
    pub fn with_factory(mut self, factory: Box<dyn PoolFactory>) -> Self {
        self.push_unique(factory);
        self
    }

    fn push_unique(&mut self, factory: Box<dyn PoolFactory>) {
        let identity = (factory.protocol(), factory.factory_address());
        if self
            .factories
            .iter()
            .any(|existing| (existing.protocol(), existing.factory_address()) == identity)
        {
            return;
        }
        self.factories.push(factory);
    }

    /// Prepare provider-neutral candidate reads for several queries.
    ///
    /// `candidate_reads` is evaluated exactly once for every matching
    /// `(query, factory)` pair. The returned read set is globally sorted and
    /// de-duplicated so a worker can fetch it in one exact-hash batch. Factories
    /// that only implement [`PoolFactory::find_pools`] are rejected explicitly:
    /// that legacy path requires a mutable [`AdapterCache`] and remains available
    /// through synchronous [`find`](Self::find) / [`find_many`](Self::find_many).
    pub fn prepare_reads(
        &self,
        queries: impl IntoIterator<Item = PoolQuery>,
    ) -> Result<PreparedDiscoveryReads, DiscoveryError> {
        self.prepare_reads_with_mode(queries, LegacyFactoryMode::Reject)
    }

    /// Assemble a prepared plan from externally fetched `(address, slot)` values.
    ///
    /// This method performs no cache or provider access. Every requested value
    /// must appear exactly once; the caller remains responsible for fetching all
    /// values at the block/hash pin associated with its work item.
    pub fn assemble_prepared(
        &self,
        prepared: &PreparedDiscoveryReads,
        values: impl IntoIterator<Item = ((Address, U256), U256)>,
    ) -> Result<Vec<DiscoveredPool>, DiscoveryError> {
        let mut resolved = HashMap::new();
        for ((address, slot), value) in values {
            if resolved.insert((address, slot), value).is_some() {
                return Err(DiscoveryError::DuplicatePreparedValue { address, slot });
            }
        }
        for &(address, slot) in prepared.reads() {
            if !resolved.contains_key(&(address, slot)) {
                return Err(DiscoveryError::MissingPreparedValue { address, slot });
            }
        }
        self.assemble_plan(prepared, &resolved, None)
    }

    fn prepare_reads_with_mode(
        &self,
        queries: impl IntoIterator<Item = PoolQuery>,
        legacy_mode: LegacyFactoryMode,
    ) -> Result<PreparedDiscoveryReads, DiscoveryError> {
        let queries: Vec<_> = queries.into_iter().collect();
        for query in &queries {
            if let Some(protocol) = query.protocol
                && !self
                    .factories
                    .iter()
                    .any(|factory| factory.protocol() == protocol)
            {
                return Err(DiscoveryError::MissingFactory(protocol));
            }
        }

        let mut reads = Vec::new();
        let mut factories = Vec::new();
        for query in queries {
            for (factory_index, factory) in
                self.factories.iter().enumerate().filter(|(_, factory)| {
                    query
                        .protocol
                        .is_none_or(|protocol| factory.protocol() == protocol)
                })
            {
                let mut factory_reads = factory.candidate_reads(&query.pairs);
                factory_reads.sort_unstable();
                factory_reads.dedup();
                let legacy = !query.pairs.is_empty() && factory_reads.is_empty();
                if legacy && legacy_mode == LegacyFactoryMode::Reject {
                    return Err(DiscoveryError::PreparedModeUnsupported {
                        protocol: factory.protocol(),
                        factory: factory.factory_address(),
                    });
                }
                reads.extend(factory_reads.iter().copied());
                factories.push(PreparedFactoryQuery {
                    factory_index,
                    protocol: factory.protocol(),
                    factory: factory.factory_address(),
                    pairs: query.pairs.clone(),
                    reads: factory_reads,
                    legacy,
                });
            }
        }
        reads.sort_unstable();
        reads.dedup();
        Ok(PreparedDiscoveryReads { reads, factories })
    }

    fn assemble_plan(
        &self,
        prepared: &PreparedDiscoveryReads,
        resolved: &HashMap<(Address, U256), U256>,
        mut cache: Option<&mut dyn AdapterCache>,
    ) -> Result<Vec<DiscoveredPool>, DiscoveryError> {
        let mut found = Vec::new();
        let mut seen = std::collections::HashSet::new();
        for plan in &prepared.factories {
            let factory = self.factories.get(plan.factory_index).ok_or(
                DiscoveryError::PreparedFactoryMismatch {
                    protocol: plan.protocol,
                    factory: plan.factory,
                },
            )?;
            if factory.protocol() != plan.protocol || factory.factory_address() != plan.factory {
                return Err(DiscoveryError::PreparedFactoryMismatch {
                    protocol: plan.protocol,
                    factory: plan.factory,
                });
            }
            debug_assert!(plan.reads.iter().all(|read| prepared.reads.contains(read)));
            let pools = if plan.legacy {
                let cache = cache
                    .as_deref_mut()
                    .expect("legacy plans are never exposed by prepare_reads");
                let mut pools = Vec::new();
                for pair in &plan.pairs {
                    pools.extend(factory.find_pools(cache, *pair)?);
                }
                pools
            } else {
                factory.assemble_pairs(&plan.pairs, resolved)?
            };
            for pool in pools {
                if seen.insert(pool.key.clone()) {
                    found.push(pool);
                }
            }
        }
        Ok(found)
    }

    /// Discover pools for several [`PoolQuery`]s at once, resolving the candidate
    /// slots of *all* of them in a single batched read and returning the
    /// de-duplicated union. This is the shared resolution core behind
    /// [`find`](Self::find).
    ///
    /// Each query is scoped independently, so one call can mix protocols across
    /// pairs — some pairs only on Uniswap V2, others only on V3 — without extra
    /// round-trips. *Batchable* factories (non-empty
    /// [`candidate_reads`](PoolFactory::candidate_reads); the built-in V2/V3)
    /// contribute their candidate mapping slots to ONE
    /// [`AdapterCache::read_storage_slots`] call — a single bulk `eth_call` on an
    /// `EvmCache`, regardless of factory or pair count — then each factory's
    /// [`assemble_pairs`](PoolFactory::assemble_pairs) builds its pools from the
    /// shared answers. External factories that only implement
    /// [`find_pools`](PoolFactory::find_pools) fall back per pair. A
    /// query scoped with [`PoolQuery::on`] to a protocol with no registered
    /// factory yields [`DiscoveryError::MissingFactory`]; an empty query list is
    /// `Ok(vec![])`.
    pub fn find_many(
        &self,
        cache: &mut dyn AdapterCache,
        queries: impl IntoIterator<Item = PoolQuery>,
    ) -> Result<Vec<DiscoveredPool>, DiscoveryError> {
        let prepared = self.prepare_reads_with_mode(queries, LegacyFactoryMode::Allow)?;
        let resolved: HashMap<(Address, U256), U256> = if prepared.reads.is_empty() {
            HashMap::new()
        } else {
            let values = cache.read_storage_slots(&prepared.reads)?;
            prepared.reads.iter().copied().zip(values).collect()
        };
        self.assemble_plan(&prepared, &resolved, Some(cache))
    }

    /// Resolve a [`PoolQuery`] into discovered pools in a single batched read.
    ///
    /// Every pair in the query — a single pair, a token basket's `C(n, 2)`
    /// combinations, or an explicit pair set — is resolved across all matching
    /// factories at once: batchable factories (the built-in Uniswap V2 and V3)
    /// contribute their candidate mapping slots to ONE
    /// [`AdapterCache::read_storage_slots`] call (a single bulk `eth_call` on an
    /// `EvmCache`), so request count scales with factory count, not with pairs,
    /// fee tiers, or basket size. External factories that only implement
    /// [`find_pools`](PoolFactory::find_pools) fall back to a per-pair call.
    ///
    /// An unscoped query spans every matching factory. If the query is scoped
    /// with [`PoolQuery::on`] to a protocol that has no registered factory, this
    /// returns [`DiscoveryError::MissingFactory`]; an unscoped query never errors
    /// on missing factories (empty pairs simply yield `Ok(vec![])`).
    pub fn find(
        &self,
        cache: &mut dyn AdapterCache,
        query: PoolQuery,
    ) -> Result<Vec<DiscoveredPool>, DiscoveryError> {
        self.find_many(cache, std::iter::once(query))
    }

    /// The union of every registered factory's creation-log sources, for live
    /// pool-creation discovery.
    pub fn creation_sources(&self) -> Vec<EventSource> {
        self.factories
            .iter()
            .flat_map(|factory| factory.creation_sources())
            .collect()
    }

    /// Decode a factory creation `log` into a discovered pool by trying each
    /// registered factory; `Ok(None)` if none handled it.
    pub fn decode_creation(
        &self,
        log: &Log,
        context: CreationLogContext,
    ) -> Result<Option<DiscoveredPool>, DiscoveryError> {
        for factory in &self.factories {
            if let Some(pool) = factory.decode_creation(log, context)? {
                return Ok(Some(pool));
            }
        }
        Ok(None)
    }
}

#[cfg(feature = "uniswap-v2")]
#[derive(Debug)]
pub(crate) struct UniswapV2Factory {
    config: UniswapV2FactoryConfig,
    verify_derivations: bool,
    derivation_verified: std::sync::OnceLock<()>,
}

#[cfg(feature = "uniswap-v2")]
impl UniswapV2Factory {
    pub(crate) fn new(config: UniswapV2FactoryConfig, verify_derivations: bool) -> Self {
        Self {
            config,
            verify_derivations,
            derivation_verified: std::sync::OnceLock::new(),
        }
    }

    fn registration(
        &self,
        pair: Address,
        token0: Address,
        token1: Address,
        source: DiscoverySource,
    ) -> DiscoveredPool {
        let mut metadata = UniswapV2Metadata::default()
            .with_token0(token0)
            .with_token1(token1);
        if let Some(fee_bps) = self.config.fee_bps {
            metadata = metadata.with_fee_bps(fee_bps);
        }
        let registration = PoolRegistration::new(PoolKey::UniswapV2(pair))
            .with_state_address(pair)
            .with_metadata(ProtocolMetadata::UniswapV2(metadata));
        let adapter = crate::adapters::UniswapV2Adapter::default();
        let sources = super::AmmAdapter::event_sources(&adapter, &registration);
        let registration = registration.with_event_sources(sources);
        DiscoveredPool {
            key: registration.key.clone(),
            registration,
            source,
        }
    }

    fn ensure_derivation_matches(
        &self,
        mapping: Address,
        token0: Address,
        token1: Address,
    ) -> Result<(), DiscoveryError> {
        if !self.verify_derivations || self.derivation_verified.get().is_some() {
            return Ok(());
        }
        let Some(init_code_hash) = self.config.init_code_hash else {
            return Ok(());
        };
        let derived = derive::v2_pair_address(self.config.factory, init_code_hash, token0, token1);
        if derived != mapping {
            return Err(DiscoveryError::DerivationMismatch { mapping, derived });
        }
        let _ = self.derivation_verified.set(());
        Ok(())
    }
}

#[cfg(feature = "uniswap-v2")]
impl PoolFactory for UniswapV2Factory {
    fn protocol(&self) -> ProtocolId {
        ProtocolId::UniswapV2
    }

    fn factory_address(&self) -> Address {
        self.config.factory
    }

    fn candidate_reads(&self, pairs: &[(Address, Address)]) -> Vec<(Address, U256)> {
        pairs
            .iter()
            .map(|(token0, token1)| {
                (
                    self.config.factory,
                    derive::v2_get_pair_slot(self.config.get_pair_base_slot, *token0, *token1),
                )
            })
            .collect()
    }

    fn assemble_pairs(
        &self,
        pairs: &[(Address, Address)],
        values: &HashMap<(Address, U256), U256>,
    ) -> Result<Vec<DiscoveredPool>, DiscoveryError> {
        let mut found = Vec::new();
        for (token0, token1) in pairs {
            let slot = derive::v2_get_pair_slot(self.config.get_pair_base_slot, *token0, *token1);
            let Some(&word) = values.get(&(self.config.factory, slot)) else {
                continue;
            };
            let pair = address_from_word(word)?;
            if pair == Address::ZERO {
                continue;
            }
            self.ensure_derivation_matches(pair, *token0, *token1)?;
            found.push(self.registration(pair, *token0, *token1, DiscoverySource::Query));
        }
        Ok(found)
    }

    fn creation_sources(&self) -> Vec<EventSource> {
        vec![EventSource::adapter_defined(
            self.config.factory,
            vec![PairCreated::SIGNATURE_HASH],
        )]
    }

    fn decode_creation(
        &self,
        log: &Log,
        context: CreationLogContext,
    ) -> Result<Option<DiscoveredPool>, DiscoveryError> {
        if log.address != self.config.factory
            || log.topics().first() != Some(&PairCreated::SIGNATURE_HASH)
        {
            return Ok(None);
        }
        let event = PairCreated::decode_log(log)
            .map_err(|_| DiscoveryError::Malformed("PairCreated failed to decode"))?
            .data;
        self.ensure_derivation_matches(event.pair, event.token0, event.token1)?;
        Ok(Some(self.registration(
            event.pair,
            event.token0,
            event.token1,
            DiscoverySource::CreationEvent {
                block_number: context.block_number,
                log_index: context.log_index,
            },
        )))
    }
}

/// Data-driven concentrated-liquidity (UniV3-mechanics) factory driver.
///
/// One [`ClFactorySpec`] configures the whole family: fee-keyed forks (Uniswap
/// V3 / SushiSwap V3 / PancakeSwap V3) and tickSpacing-keyed forks (Slipstream /
/// Aerodrome). Replaces the former Uniswap-V3-only factory.
#[cfg(feature = "uniswap-v3")]
#[derive(Debug)]
pub struct ConcentratedLiquidityFactory {
    spec: ClFactorySpec,
    derivation_verified: std::sync::OnceLock<()>,
}

/// The innermost `getPool` key for one probe: a fee tier (fee keying) or an int24
/// tick spacing (tickSpacing keying).
#[cfg(feature = "uniswap-v3")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ClLookupKey {
    Fee(u32),
    TickSpacing(i32),
}

#[cfg(feature = "uniswap-v3")]
impl ConcentratedLiquidityFactory {
    /// Build a driver from a fully-specified [`ClFactorySpec`].
    pub fn new(spec: ClFactorySpec) -> Self {
        Self {
            spec,
            derivation_verified: std::sync::OnceLock::new(),
        }
    }

    fn registration(
        &self,
        pool: Address,
        token0: Address,
        token1: Address,
        fee: u32,
        tick_spacing: i32,
        source: DiscoverySource,
    ) -> DiscoveredPool {
        let storage_layout = match self.spec.protocol {
            ProtocolId::UniswapV3 => V3StorageLayout::uniswap(tick_spacing),
            ProtocolId::PancakeV3 => V3StorageLayout::pancake(tick_spacing),
            ProtocolId::Slipstream => V3StorageLayout::slipstream(tick_spacing),
            _ => V3StorageLayout::uniswap(tick_spacing),
        };
        let mut metadata = V3Metadata::default()
            .with_token0(token0)
            .with_token1(token1)
            .with_tick_spacing(tick_spacing)
            .with_storage_layout(storage_layout)
            .with_factory(self.spec.factory);
        // A resolved fee of 0 is the tickSpacing-keyed "no fee mapping" sentinel
        // (Slipstream / Aerodrome CL have no on-chain fee→pool mapping and set
        // `FeeSource::Fixed(0)`): leave `fee` UNSET rather than record a bogus 0,
        // so `simulate_swap` surfaces `MissingMetadata("V3 fee")` — Slipstream is
        // discovery-only for quoting — instead of silently quoting at fee 0.
        // Fee-keyed forks always resolve a real, non-zero tier.
        if fee != 0 {
            metadata = metadata.with_fee(fee);
        }
        let metadata = if let Some(quoter) = self.spec.quoter {
            metadata.with_quoter(quoter)
        } else {
            metadata
        };
        let key = match self.spec.protocol {
            ProtocolId::PancakeV3 => PoolKey::PancakeV3(pool),
            ProtocolId::Slipstream => PoolKey::Slipstream(pool),
            _ => PoolKey::UniswapV3(pool),
        };
        let protocol_metadata = match self.spec.protocol {
            ProtocolId::PancakeV3 => ProtocolMetadata::PancakeV3(metadata),
            ProtocolId::Slipstream => ProtocolMetadata::Slipstream(metadata),
            _ => ProtocolMetadata::UniswapV3(metadata),
        };
        let registration = PoolRegistration::new(key)
            .with_state_address(pool)
            .with_metadata(protocol_metadata);
        let adapter = crate::adapters::ConcentratedLiquidityAdapter::default();
        let sources = super::AmmAdapter::event_sources(&adapter, &registration);
        let registration = registration.with_event_sources(sources);
        DiscoveredPool {
            key: registration.key.clone(),
            registration,
            source,
        }
    }

    fn ensure_derivation_matches(
        &self,
        mapping: Address,
        token0: Address,
        token1: Address,
        key: ClLookupKey,
    ) -> Result<(), DiscoveryError> {
        if !self.spec.verify_derivations || self.derivation_verified.get().is_some() {
            return Ok(());
        }
        let Some(create2) = self.spec.create2 else {
            return Ok(());
        };
        let deployer = create2.deployer.unwrap_or(self.spec.factory);
        let derived = match key {
            ClLookupKey::Fee(fee) => {
                derive::v3_pool_address(deployer, create2.init_code_hash, token0, token1, fee)
            }
            ClLookupKey::TickSpacing(spacing) => derive::v3_pool_address_by_spacing(
                deployer,
                create2.init_code_hash,
                token0,
                token1,
                spacing,
            ),
        };
        if derived != mapping {
            return Err(DiscoveryError::DerivationMismatch { mapping, derived });
        }
        let _ = self.derivation_verified.set(());
        Ok(())
    }

    fn fee_for_key(
        &self,
        key: ClLookupKey,
        values: &HashMap<(Address, U256), U256>,
    ) -> Result<u32, DiscoveryError> {
        match self.spec.fee_source {
            FeeSource::Key => match key {
                ClLookupKey::Fee(fee) => Ok(fee),
                ClLookupKey::TickSpacing(_) => Err(DiscoveryError::Malformed(
                    "fee source Key is not valid for tickSpacing-keyed factories",
                )),
            },
            FeeSource::Fixed(fee) => Ok(fee),
            FeeSource::FactoryMapping { base_slot } => {
                let slot = match key {
                    ClLookupKey::Fee(fee) => {
                        derive::v3_fee_amount_tick_spacing_slot(base_slot, fee)
                    }
                    ClLookupKey::TickSpacing(spacing) => {
                        derive::v3_tick_spacing_fee_slot(base_slot, spacing)
                    }
                };
                let word = values
                    .get(&(self.spec.factory, slot))
                    .copied()
                    .unwrap_or_default();
                Ok(u32_from_word(word))
            }
        }
    }
}

#[cfg(feature = "uniswap-v3")]
impl PoolFactory for ConcentratedLiquidityFactory {
    fn protocol(&self) -> ProtocolId {
        self.spec.protocol
    }

    fn factory_address(&self) -> Address {
        self.spec.factory
    }

    fn candidate_reads(&self, pairs: &[(Address, Address)]) -> Vec<(Address, U256)> {
        let mut slots = Vec::new();
        match &self.spec.keying {
            ClKeying::Fee {
                tiers,
                fee_amount_tick_spacing_base_slot,
            } => {
                // `feeAmountTickSpacing[fee]` is per-fee, not per-pair — read each once.
                for &fee in tiers {
                    slots.push((
                        self.spec.factory,
                        derive::v3_fee_amount_tick_spacing_slot(
                            *fee_amount_tick_spacing_base_slot,
                            fee,
                        ),
                    ));
                }
                for (token0, token1) in pairs {
                    for &fee in tiers {
                        slots.push((
                            self.spec.factory,
                            derive::v3_get_pool_slot(
                                self.spec.get_pool_base_slot,
                                *token0,
                                *token1,
                                fee,
                            ),
                        ));
                    }
                }
            }
            ClKeying::TickSpacing { spacings } => {
                for (token0, token1) in pairs {
                    for &spacing in spacings {
                        slots.push((
                            self.spec.factory,
                            derive::v3_get_pool_slot_by_spacing(
                                self.spec.get_pool_base_slot,
                                *token0,
                                *token1,
                                spacing,
                            ),
                        ));
                        if let FeeSource::FactoryMapping { base_slot } = self.spec.fee_source {
                            slots.push((
                                self.spec.factory,
                                derive::v3_tick_spacing_fee_slot(base_slot, spacing),
                            ));
                        }
                    }
                }
            }
        }
        slots
    }

    fn assemble_pairs(
        &self,
        pairs: &[(Address, Address)],
        values: &HashMap<(Address, U256), U256>,
    ) -> Result<Vec<DiscoveredPool>, DiscoveryError> {
        let mut found = Vec::new();
        for (token0, token1) in pairs {
            match &self.spec.keying {
                ClKeying::Fee {
                    tiers,
                    fee_amount_tick_spacing_base_slot,
                } => {
                    for &fee in tiers {
                        let key = ClLookupKey::Fee(fee);
                        let pool_slot = derive::v3_get_pool_slot(
                            self.spec.get_pool_base_slot,
                            *token0,
                            *token1,
                            fee,
                        );
                        let Some(&word) = values.get(&(self.spec.factory, pool_slot)) else {
                            continue;
                        };
                        let pool = address_from_word(word)?;
                        if pool == Address::ZERO {
                            continue;
                        }
                        self.ensure_derivation_matches(pool, *token0, *token1, key)?;
                        let tick_slot = derive::v3_fee_amount_tick_spacing_slot(
                            *fee_amount_tick_spacing_base_slot,
                            fee,
                        );
                        let tick_spacing = i24_from_word(
                            values
                                .get(&(self.spec.factory, tick_slot))
                                .copied()
                                .unwrap_or_default(),
                        );
                        if tick_spacing <= 0 {
                            return Err(DiscoveryError::Malformed(
                                "V3 feeAmountTickSpacing returned a non-positive spacing",
                            ));
                        }
                        found.push(self.registration(
                            pool,
                            *token0,
                            *token1,
                            self.fee_for_key(key, values)?,
                            tick_spacing,
                            DiscoverySource::Query,
                        ));
                    }
                }
                ClKeying::TickSpacing { spacings } => {
                    for &spacing in spacings {
                        let key = ClLookupKey::TickSpacing(spacing);
                        let pool_slot = derive::v3_get_pool_slot_by_spacing(
                            self.spec.get_pool_base_slot,
                            *token0,
                            *token1,
                            spacing,
                        );
                        let Some(&word) = values.get(&(self.spec.factory, pool_slot)) else {
                            continue;
                        };
                        let pool = address_from_word(word)?;
                        if pool == Address::ZERO {
                            continue;
                        }
                        self.ensure_derivation_matches(pool, *token0, *token1, key)?;
                        found.push(self.registration(
                            pool,
                            *token0,
                            *token1,
                            self.fee_for_key(key, values)?,
                            spacing,
                            DiscoverySource::Query,
                        ));
                    }
                }
            }
        }
        Ok(found)
    }

    fn creation_sources(&self) -> Vec<EventSource> {
        self.spec
            .creation_topic0
            .map(|topic| EventSource::adapter_defined(self.spec.factory, vec![topic]))
            .into_iter()
            .collect()
    }

    fn decode_creation(
        &self,
        log: &Log,
        context: CreationLogContext,
    ) -> Result<Option<DiscoveredPool>, DiscoveryError> {
        let Some(topic0) = self.spec.creation_topic0 else {
            return Ok(None);
        };
        if log.address != self.spec.factory || log.topics().first() != Some(&topic0) {
            return Ok(None);
        }
        if topic0 == PoolCreated::SIGNATURE_HASH {
            let event = PoolCreated::decode_log(log)
                .map_err(|_| DiscoveryError::Malformed("PoolCreated failed to decode"))?
                .data;
            let fee: u32 = event.fee.to();
            let tick_spacing: i32 = event.tickSpacing.as_i32();
            self.ensure_derivation_matches(
                event.pool,
                event.token0,
                event.token1,
                ClLookupKey::Fee(fee),
            )?;
            return Ok(Some(self.registration(
                event.pool,
                event.token0,
                event.token1,
                fee,
                tick_spacing,
                DiscoverySource::CreationEvent {
                    block_number: context.block_number,
                    log_index: context.log_index,
                },
            )));
        }
        if topic0 == PoolCreatedTickSpacing::SIGNATURE_HASH {
            let event = PoolCreatedTickSpacing::decode_log(log)
                .map_err(|_| DiscoveryError::Malformed("PoolCreatedTickSpacing failed to decode"))?
                .data;
            let fee: u32 = event.fee.to();
            let tick_spacing: i32 = event.tickSpacing.as_i32();
            self.ensure_derivation_matches(
                event.pool,
                event.token0,
                event.token1,
                ClLookupKey::TickSpacing(tick_spacing),
            )?;
            return Ok(Some(self.registration(
                event.pool,
                event.token0,
                event.token1,
                fee,
                tick_spacing,
                DiscoverySource::CreationEvent {
                    block_number: context.block_number,
                    log_index: context.log_index,
                },
            )));
        }
        Ok(None)
    }
}

/// Solidly V2 (Aerodrome / Velodrome V2) factory driver.
///
/// Resolves pools by a batched [`DerivedSlot`] read of the factory's
/// `getPool[token0][token1][bool stable]` nested mapping: each pair contributes
/// two candidate slots (volatile + stable), and a non-zero mapping answer yields
/// a [`PoolKey::SolidlyV2`] pool carrying the fork's [`SolidlyStorageLayout`]. No
/// quoter is wired — Solidly pools self-quote (`getAmountOut`) and their fee is a
/// factory read at sim time — so discovery resolves only the pool set, not fees.
///
/// [`DerivedSlot`]: crate::adapters::factory
#[cfg(feature = "solidly-v2")]
#[derive(Debug)]
pub struct SolidlyFactory {
    config: SolidlyFactoryConfig,
    derivation_verified: std::sync::OnceLock<()>,
}

/// The two Solidly pool variants a pair can resolve to.
#[cfg(feature = "solidly-v2")]
const SOLIDLY_VARIANTS: [bool; 2] = [false, true];

#[cfg(feature = "solidly-v2")]
impl SolidlyFactory {
    /// Build a driver from a fully-specified [`SolidlyFactoryConfig`].
    pub fn new(config: SolidlyFactoryConfig) -> Self {
        Self {
            config,
            derivation_verified: std::sync::OnceLock::new(),
        }
    }

    fn registration(
        &self,
        pool: Address,
        token0: Address,
        token1: Address,
        stable: bool,
        source: DiscoverySource,
    ) -> DiscoveredPool {
        let metadata = SolidlyV2Metadata::default()
            .with_token0(token0)
            .with_token1(token1)
            .with_stable(stable)
            .with_storage_layout(self.config.storage_layout);
        let registration = PoolRegistration::new(PoolKey::SolidlyV2(pool))
            .with_state_address(pool)
            .with_metadata(ProtocolMetadata::SolidlyV2(metadata));
        let adapter = crate::adapters::SolidlyV2Adapter::default();
        let sources = super::AmmAdapter::event_sources(&adapter, &registration);
        let registration = registration.with_event_sources(sources);
        DiscoveredPool {
            key: registration.key.clone(),
            registration,
            source,
        }
    }

    fn ensure_derivation_matches(
        &self,
        mapping: Address,
        token0: Address,
        token1: Address,
        stable: bool,
    ) -> Result<(), DiscoveryError> {
        if !self.config.verify_derivations || self.derivation_verified.get().is_some() {
            return Ok(());
        }
        let Some(create2) = self.config.create2 else {
            return Ok(());
        };
        let deployer = create2.deployer.unwrap_or(self.config.factory);
        let derived =
            derive::solidly_pool_address(deployer, create2.init_code_hash, token0, token1, stable);
        if derived != mapping {
            return Err(DiscoveryError::DerivationMismatch { mapping, derived });
        }
        let _ = self.derivation_verified.set(());
        Ok(())
    }
}

#[cfg(feature = "solidly-v2")]
impl PoolFactory for SolidlyFactory {
    fn protocol(&self) -> ProtocolId {
        ProtocolId::SolidlyV2
    }

    fn factory_address(&self) -> Address {
        self.config.factory
    }

    fn candidate_reads(&self, pairs: &[(Address, Address)]) -> Vec<(Address, U256)> {
        let mut slots = Vec::with_capacity(pairs.len() * SOLIDLY_VARIANTS.len());
        for (token0, token1) in pairs {
            for stable in SOLIDLY_VARIANTS {
                slots.push((
                    self.config.factory,
                    derive::solidly_get_pool_slot(
                        self.config.get_pool_base_slot,
                        *token0,
                        *token1,
                        stable,
                    ),
                ));
            }
        }
        slots
    }

    fn assemble_pairs(
        &self,
        pairs: &[(Address, Address)],
        values: &HashMap<(Address, U256), U256>,
    ) -> Result<Vec<DiscoveredPool>, DiscoveryError> {
        let mut found = Vec::new();
        for (token0, token1) in pairs {
            for stable in SOLIDLY_VARIANTS {
                let slot = derive::solidly_get_pool_slot(
                    self.config.get_pool_base_slot,
                    *token0,
                    *token1,
                    stable,
                );
                let Some(&word) = values.get(&(self.config.factory, slot)) else {
                    continue;
                };
                let pool = address_from_word(word)?;
                if pool == Address::ZERO {
                    continue;
                }
                self.ensure_derivation_matches(pool, *token0, *token1, stable)?;
                found.push(self.registration(
                    pool,
                    *token0,
                    *token1,
                    stable,
                    DiscoverySource::Query,
                ));
            }
        }
        Ok(found)
    }

    fn creation_sources(&self) -> Vec<EventSource> {
        self.config
            .creation_topic0
            .map(|topic| EventSource::adapter_defined(self.config.factory, vec![topic]))
            .into_iter()
            .collect()
    }

    fn decode_creation(
        &self,
        log: &Log,
        context: CreationLogContext,
    ) -> Result<Option<DiscoveredPool>, DiscoveryError> {
        let Some(topic0) = self.config.creation_topic0 else {
            return Ok(None);
        };
        if log.address != self.config.factory || log.topics().first() != Some(&topic0) {
            return Ok(None);
        }
        if topic0 != SolidlyPoolCreated::SIGNATURE_HASH {
            return Ok(None);
        }
        let event = SolidlyPoolCreated::decode_log(log)
            .map_err(|_| DiscoveryError::Malformed("SolidlyPoolCreated failed to decode"))?
            .data;
        self.ensure_derivation_matches(event.pool, event.token0, event.token1, event.stable)?;
        Ok(Some(self.registration(
            event.pool,
            event.token0,
            event.token1,
            event.stable,
            DiscoverySource::CreationEvent {
                block_number: context.block_number,
                log_index: context.log_index,
            },
        )))
    }
}

#[cfg(feature = "uniswap-v3")]
fn u32_from_word(word: U256) -> u32 {
    let bytes = word.to_be_bytes::<32>();
    u32::from_be_bytes([bytes[28], bytes[29], bytes[30], bytes[31]])
}

#[cfg(any(feature = "uniswap-v2", feature = "uniswap-v3", feature = "solidly-v2"))]
fn address_from_word(word: U256) -> Result<Address, DiscoveryError> {
    let bytes = word.to_be_bytes::<32>();
    if bytes[..12].iter().any(|b| *b != 0) {
        return Err(DiscoveryError::Malformed(
            "factory address word has non-zero high bytes",
        ));
    }
    Ok(Address::from_slice(&bytes[12..]))
}

#[cfg(feature = "uniswap-v3")]
fn i24_from_word(word: U256) -> i32 {
    let bytes = word.to_be_bytes::<32>();
    let raw = u32::from_be_bytes([0, bytes[29], bytes[30], bytes[31]]);
    if (raw & 0x0080_0000) != 0 {
        (raw | 0xff00_0000) as i32
    } else {
        raw as i32
    }
}

#[cfg(all(test, feature = "solidly-v2"))]
mod solidly_tests {
    use super::*;
    use alloy_primitives::keccak256;

    /// The Solidly `PoolCreated` push topic0 must be the REAL on-chain event
    /// signature `keccak256("PoolCreated(address,address,bool,address,uint256)")`
    /// — NOT the Rust alias name. This guards the module-wrapping that keeps the
    /// generated struct named `PoolCreated` (renaming it silently produces the
    /// wrong topic0, so real creation logs would never match).
    #[test]
    fn solidly_pool_created_topic0_matches_onchain_signature() {
        let expected = keccak256(b"PoolCreated(address,address,bool,address,uint256)");
        assert_eq!(SolidlyPoolCreated::SIGNATURE_HASH, expected);
        assert_eq!(
            SolidlyPoolCreated::SIGNATURE,
            "PoolCreated(address,address,bool,address,uint256)"
        );
    }

    /// `solidly_get_pool_slot` descends the two address levels exactly like the
    /// V3 `getPool[t0][t1]` mapping, then keys the innermost `bool` as 0/1 — so
    /// the stable and volatile variants land on distinct, non-zero slots.
    #[test]
    fn solidly_get_pool_slot_distinguishes_stable_flag() {
        let base = U256::from(3);
        let t0 = Address::repeat_byte(0x0a);
        let t1 = Address::repeat_byte(0x0b);
        let volatile = derive::solidly_get_pool_slot(base, t0, t1, false);
        let stable = derive::solidly_get_pool_slot(base, t0, t1, true);
        assert_ne!(volatile, stable);
        assert_ne!(volatile, U256::ZERO);
        assert_ne!(stable, U256::ZERO);
    }
}