starktop 0.8.1

A TUI block explorer for the Starknet blockchain
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
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::path::Path;
use std::pin::Pin;
use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use futures::FutureExt;
use futures::future::Shared;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::{TransactionBehavior, params};
use starknet::core::types::{ContractClass, Felt, TransactionTrace};
use tracing::{debug, info, trace, warn};

/// Alias so call sites read cleanly. r2d2 reuses the same `rusqlite::Connection`
/// type under the hood — `PooledConnection` derefs to `&Connection` (reads) and
/// `DerefMut` to `&mut Connection` (needed for `.transaction()`).
type DbPool = Pool<SqliteConnectionManager>;

#[allow(unused_imports)]
use super::types::*;
use super::{DataSource, FilterKind};
use crate::error::{Result, StarktopError};

/// A block/transaction finality status is final (immutable) once it reaches
/// L1. Anything else ("ACCEPTED_ON_L2", "PRE_CONFIRMED", or an empty status
/// from a pre-`status`-field cache row) is still subject to change and is
/// re-probed on the next view.
fn is_final_status(status: &str) -> bool {
    status == "ACCEPTED_ON_L1"
}

/// Shared future output: errors are stringified so the future is `Clone`-able
/// (StarktopError is not Clone due to `std::io::Error`).
type SharedTxFut =
    Shared<Pin<Box<dyn Future<Output = std::result::Result<SnTransaction, String>> + Send>>>;
type SharedRxFut =
    Shared<Pin<Box<dyn Future<Output = std::result::Result<SnReceipt, String>> + Send>>>;
type SharedTraceFut =
    Shared<Pin<Box<dyn Future<Output = std::result::Result<TransactionTrace, String>> + Send>>>;

/// Persistent cache backed by SQLite + in-memory LRU.
/// Wraps any DataSource: checks cache first, fetches from upstream on miss,
/// writes through to cache on fetch. Persists across restarts.
///
/// Also deduplicates concurrent in-flight `get_transaction` / `get_receipt` /
/// `get_trace` fetches so that N parallel callers for the same hash produce
/// one RPC round trip, not N. Prevents the user-click-races-background-
/// enrichment storm.
pub struct CachingDataSource {
    upstream: Arc<dyn DataSource>,
    db: DbPool,
    pending_txs: Mutex<HashMap<Felt, SharedTxFut>>,
    pending_receipts: Mutex<HashMap<Felt, SharedRxFut>>,
    pending_traces: Mutex<HashMap<Felt, SharedTraceFut>>,
    /// In-process chain head, fed by the WS new-heads stream. When set and
    /// fresh, `get_class_hash` uses this to check cache staleness instead of
    /// issuing a `starknet_blockNumber` RPC per call.
    head: Option<Arc<dyn crate::data::LatestBlockSource>>,
}

impl CachingDataSource {
    pub fn new(upstream: Arc<dyn DataSource>, cache_path: &Path) -> Result<Self> {
        // r2d2 pool over SqliteConnectionManager. Each connection is configured
        // the same way via `with_init`: WAL for concurrent readers + fast writer,
        // synchronous=NORMAL to skip WAL-checkpoint fsyncs (cache rows are
        // rebuildable from RPC, so a torn WAL on power-loss costs us re-fetches,
        // not integrity), and temp_store=MEMORY so sort/hash spill stays in RAM.
        let manager = SqliteConnectionManager::file(cache_path).with_init(|c| {
            c.execute_batch(
                "PRAGMA journal_mode = WAL; \
                 PRAGMA synchronous = NORMAL; \
                 PRAGMA temp_store = MEMORY; \
                 PRAGMA busy_timeout = 5000;",
            )
        });
        // 8 connections: enough for the observed concurrency (one UI-thread
        // reader + one WS writer + a handful of background enrichment tasks),
        // without pinning a ton of file handles on idle users.
        let pool = Pool::builder()
            .max_size(8)
            .build(manager)
            .map_err(|e| StarktopError::Config(format!("Failed to build cache db pool: {e}")))?;
        let db = pool
            .get()
            .map_err(|e| StarktopError::Config(format!("Failed to open cache db: {e}")))?;

        // Create tables
        db.execute_batch(
            "
            CREATE TABLE IF NOT EXISTS blocks (
                number INTEGER PRIMARY KEY,
                data TEXT NOT NULL
            );
            CREATE TABLE IF NOT EXISTS transactions (
                hash TEXT PRIMARY KEY,
                block_number INTEGER,
                data TEXT NOT NULL
            );
            CREATE TABLE IF NOT EXISTS receipts (
                tx_hash TEXT PRIMARY KEY,
                data TEXT NOT NULL
            );
            CREATE TABLE IF NOT EXISTS tx_traces (
                tx_hash TEXT PRIMARY KEY,
                data TEXT NOT NULL
            );
            CREATE TABLE IF NOT EXISTS block_transactions (
                block_number INTEGER,
                tx_index INTEGER,
                tx_hash TEXT NOT NULL,
                data TEXT NOT NULL,
                PRIMARY KEY (block_number, tx_index)
            );
            CREATE TABLE IF NOT EXISTS parsed_abis (
                class_hash TEXT PRIMARY KEY,
                data TEXT NOT NULL
            );
            CREATE TABLE IF NOT EXISTS address_events (
                address TEXT NOT NULL,
                block_number INTEGER NOT NULL,
                tx_hash TEXT NOT NULL,
                event_index INTEGER NOT NULL,
                data TEXT NOT NULL,
                PRIMARY KEY (address, block_number, tx_hash, event_index)
            );
            CREATE TABLE IF NOT EXISTS address_txs (
                address TEXT NOT NULL,
                tx_index INTEGER NOT NULL,
                data TEXT NOT NULL,
                PRIMARY KEY (address, tx_index)
            );
            CREATE INDEX IF NOT EXISTS idx_addr_txs ON address_txs(address);
            CREATE INDEX IF NOT EXISTS idx_tx_block ON transactions(block_number);
            CREATE INDEX IF NOT EXISTS idx_block_tx ON block_transactions(block_number);
            CREATE TABLE IF NOT EXISTS address_calls (
                address TEXT NOT NULL,
                tx_hash TEXT NOT NULL,
                block_number INTEGER NOT NULL,
                data TEXT NOT NULL,
                PRIMARY KEY (address, tx_hash)
            );
            CREATE TABLE IF NOT EXISTS address_call_scanned_ranges (
                address TEXT NOT NULL,
                lo_block INTEGER NOT NULL,
                hi_block INTEGER NOT NULL,
                PRIMARY KEY (address, lo_block)
            );
            CREATE INDEX IF NOT EXISTS idx_addr_call_scanned
                ON address_call_scanned_ranges(address);
            CREATE TABLE IF NOT EXISTS address_transfers (
                address TEXT NOT NULL,
                tx_hash TEXT NOT NULL,
                event_index INTEGER NOT NULL,
                block_number INTEGER NOT NULL,
                data TEXT NOT NULL,
                PRIMARY KEY (address, tx_hash, event_index)
            );
            CREATE INDEX IF NOT EXISTS idx_addr_transfers
                ON address_transfers(address, block_number);
            CREATE TABLE IF NOT EXISTS address_transfer_scanned_ranges (
                address TEXT NOT NULL,
                lo_block INTEGER NOT NULL,
                hi_block INTEGER NOT NULL,
                PRIMARY KEY (address, lo_block)
            );
            CREATE TABLE IF NOT EXISTS address_activity (
                address TEXT PRIMARY KEY,
                min_block INTEGER NOT NULL,
                max_block INTEGER NOT NULL,
                event_count INTEGER NOT NULL DEFAULT 0,
                updated_at INTEGER NOT NULL
            );
            CREATE TABLE IF NOT EXISTS class_hashes (
                address TEXT PRIMARY KEY,
                class_hash TEXT NOT NULL,
                fetched_at_block INTEGER NOT NULL
            );
            CREATE TABLE IF NOT EXISTS block_hash_index (
                hash TEXT PRIMARY KEY,
                number INTEGER NOT NULL
            );
            CREATE TABLE IF NOT EXISTS deploy_info (
                address TEXT PRIMARY KEY,
                deploy_tx_hash TEXT NOT NULL,
                deploy_block INTEGER NOT NULL,
                deployer TEXT
            );
            CREATE TABLE IF NOT EXISTS class_history (
                address TEXT NOT NULL,
                block_number INTEGER NOT NULL,
                class_hash TEXT NOT NULL,
                PRIMARY KEY (address, block_number)
            );
            CREATE INDEX IF NOT EXISTS idx_class_history_addr
                ON class_history(address, block_number DESC);
            CREATE TABLE IF NOT EXISTS class_history_meta (
                address TEXT PRIMARY KEY,
                last_known_block INTEGER NOT NULL
            );
            CREATE TABLE IF NOT EXISTS cached_nonces (
                address TEXT PRIMARY KEY,
                nonce TEXT NOT NULL,
                block_number INTEGER NOT NULL
            );
            CREATE TABLE IF NOT EXISTS address_search_progress (
                address TEXT NOT NULL,
                filter_kind TEXT NOT NULL DEFAULT 'unkeyed',
                max_searched_block INTEGER NOT NULL,
                min_searched_block INTEGER NOT NULL DEFAULT 0,
                PRIMARY KEY (address, filter_kind)
            );
            CREATE TABLE IF NOT EXISTS address_activity_total (
                address TEXT PRIMARY KEY,
                total_known INTEGER NOT NULL
            );
            CREATE TABLE IF NOT EXISTS contract_events (
                address TEXT NOT NULL,
                event_index INTEGER NOT NULL,
                data TEXT NOT NULL,
                PRIMARY KEY (address, event_index)
            );
            CREATE INDEX IF NOT EXISTS idx_contract_events ON contract_events(address);
            CREATE TABLE IF NOT EXISTS address_meta_txs (
                address TEXT NOT NULL,
                tx_hash TEXT NOT NULL,
                block_number INTEGER NOT NULL,
                data TEXT NOT NULL,
                PRIMARY KEY (address, tx_hash)
            );
            CREATE INDEX IF NOT EXISTS idx_addr_meta_txs
                ON address_meta_txs(address, block_number DESC);
            CREATE TABLE IF NOT EXISTS class_declarations (
                class_hash TEXT PRIMARY KEY,
                tx_hash TEXT NOT NULL,
                sender TEXT NOT NULL,
                block_number INTEGER NOT NULL,
                timestamp INTEGER NOT NULL DEFAULT 0
            );
            CREATE TABLE IF NOT EXISTS class_contracts (
                class_hash TEXT NOT NULL,
                contract_address TEXT NOT NULL,
                block_number INTEGER NOT NULL,
                PRIMARY KEY (class_hash, contract_address)
            );
            CREATE INDEX IF NOT EXISTS idx_class_contracts_class
                ON class_contracts(class_hash, block_number DESC);
            CREATE TABLE IF NOT EXISTS class_contracts_meta (
                class_hash TEXT PRIMARY KEY,
                fetched_at INTEGER NOT NULL
            );
            CREATE TABLE IF NOT EXISTS private_notes (
                note_id TEXT PRIMARY KEY,
                user TEXT NOT NULL,
                counterparty TEXT NOT NULL,
                direction TEXT NOT NULL,
                token TEXT NOT NULL,
                amount TEXT NOT NULL,
                channel_idx INTEGER NOT NULL,
                subchannel_idx INTEGER NOT NULL,
                note_idx INTEGER NOT NULL,
                spent INTEGER NOT NULL,
                block_number INTEGER NOT NULL
            );
            CREATE INDEX IF NOT EXISTS idx_private_notes_user
                ON private_notes(user);
            CREATE TABLE IF NOT EXISTS private_nullifiers (
                nullifier TEXT PRIMARY KEY,
                note_id TEXT NOT NULL,
                user TEXT NOT NULL
            );
            CREATE INDEX IF NOT EXISTS idx_private_nullifiers_user
                ON private_nullifiers(user);
            CREATE TABLE IF NOT EXISTS private_notes_sync (
                user TEXT PRIMARY KEY,
                last_synced_block INTEGER NOT NULL,
                synced_at INTEGER NOT NULL
            );
            CREATE TABLE IF NOT EXISTS token_metadata (
                address TEXT PRIMARY KEY,
                symbol TEXT NOT NULL,
                decimals INTEGER NOT NULL,
                fetched_at INTEGER NOT NULL
            );
            ",
        )
        .map_err(|e| StarktopError::Config(format!("Failed to init cache schema: {e}")))?;

        // --- Migrations (keyed on PRAGMA user_version) ---
        let version: i64 = db
            .query_row("PRAGMA user_version", [], |row| row.get(0))
            .unwrap_or(0);

        if version < 4 {
            // v4: DEPLOY_ACCOUNT txs had wrong contract_address. Clear all
            // tx/block/address caches so they are re-fetched with correct data.
            db.execute_batch(
                "DELETE FROM transactions;
                 DELETE FROM block_transactions;
                 DELETE FROM blocks;
                 DELETE FROM address_txs;
                 DELETE FROM deploy_info;
                 PRAGMA user_version = 4;",
            )
            .map_err(|e| StarktopError::Config(format!("Migration v4 failed: {e}")))?;
            debug!("Migration v4: cleared tx/block/address caches");
        }

        if version < 5 {
            // v5: introduce address_activity_total so we can persist the
            // upstream event-count total (e.g. Dune probe) and render
            // "(N / total)" labels across restarts. Kept in its own table so
            // that seeding a total does not create a bogus (0,0) scan range
            // on the address_search_progress row.
            // The CREATE TABLE IF NOT EXISTS above is the DDL; nothing else to
            // do for existing DBs — just bump the version.
            db.execute("PRAGMA user_version = 5", []).map_err(|e| {
                StarktopError::Config(format!("Migration v5 version bump failed: {e}"))
            })?;
            debug!("Migration v5: added address_activity_total table");
        }

        if version < 6 {
            // v6: split address_search_progress by filter_kind. Legacy rows
            // can't be attributed to a specific kind after the fact
            // (TASK C wrote either Account/keyed or Contract/unkeyed
            // scans here indiscriminately), so migrate them as `unkeyed`.
            // Consequence: accounts revisited post-upgrade will pay for
            // one keyed re-scan of the previously-covered range. Safe and
            // acceptably small.
            db.execute_batch(
                "CREATE TABLE address_search_progress_v6 (
                     address TEXT NOT NULL,
                     filter_kind TEXT NOT NULL DEFAULT 'unkeyed',
                     max_searched_block INTEGER NOT NULL,
                     min_searched_block INTEGER NOT NULL DEFAULT 0,
                     PRIMARY KEY (address, filter_kind)
                 );
                 INSERT INTO address_search_progress_v6
                     (address, filter_kind, max_searched_block, min_searched_block)
                     SELECT address, 'unkeyed', max_searched_block, min_searched_block
                     FROM address_search_progress;
                 DROP TABLE address_search_progress;
                 ALTER TABLE address_search_progress_v6
                     RENAME TO address_search_progress;
                 PRAGMA user_version = 6;",
            )
            .map_err(|e| StarktopError::Config(format!("Migration v6 failed: {e}")))?;
            debug!("Migration v6: split address_search_progress by filter_kind");
        }

        if version < 7 {
            // v7: introduce class_history. The DDL is in the CREATE block above;
            // existing DBs just need the version bump. On revisit without
            // pf-query the cached rows replay deployment + class-upgrade info
            // so the address view doesn't regress.
            db.execute("PRAGMA user_version = 7", []).map_err(|e| {
                StarktopError::Config(format!("Migration v7 version bump failed: {e}"))
            })?;
            debug!("Migration v7: added class_history table");
        }

        if version < 8 {
            // v8: introduce class_history_meta. Tracks the highest block at
            // which a pf-query response confirmed the cached class history was
            // complete. Only advanced on pf-validated reads — when pf is
            // unavailable we keep showing the cached list but leave the
            // watermark alone, so the next pf-enabled visit can detect (via
            // class-hash divergence) that gaps may exist and refetch.
            db.execute("PRAGMA user_version = 8", []).map_err(|e| {
                StarktopError::Config(format!("Migration v8 version bump failed: {e}"))
            })?;
            debug!("Migration v8: added class_history_meta table");
        }

        if version < 9 {
            // v9: introduce private_notes + private_notes_sync. Caches
            // forward-decrypted Privacy Pool incoming notes per labelled
            // user (note_id → amount/token/sender) so the Privacy tab can
            // annotate EncNoteCreated events without re-syncing storage on
            // every tx open. The CREATE TABLE IF NOT EXISTS lines above
            // handle DDL; nothing to migrate from older rows.
            db.execute("PRAGMA user_version = 9", []).map_err(|e| {
                StarktopError::Config(format!("Migration v9 version bump failed: {e}"))
            })?;
            debug!("Migration v9: added private_notes + private_notes_sync tables");
        }

        if version < 10 {
            // v10: introduce token_metadata. Caches on-chain ERC-20
            // (decimals, symbol) for tokens not in the static registry,
            // so the Privacy + Balances tabs can render unknown tokens
            // correctly across restarts without re-fetching every cold
            // start. CREATE TABLE IF NOT EXISTS above handles DDL.
            db.execute("PRAGMA user_version = 10", []).map_err(|e| {
                StarktopError::Config(format!("Migration v10 version bump failed: {e}"))
            })?;
            debug!("Migration v10: added token_metadata table");
        }

        if version < 11 {
            // v11: re-shape private_notes to match the actual DecryptedNote
            // (counterparty, direction, spent — the v9 columns
            // amount_low/high + salt_low/high + sender were never wired in)
            // and add private_nullifiers for nullifier→note_id persistence.
            // The v9 table was never written to, so dropping it is safe.
            db.execute_batch(
                "DROP TABLE IF EXISTS private_notes;
                 CREATE TABLE private_notes (
                     note_id TEXT PRIMARY KEY,
                     user TEXT NOT NULL,
                     counterparty TEXT NOT NULL,
                     direction TEXT NOT NULL,
                     token TEXT NOT NULL,
                     amount TEXT NOT NULL,
                     channel_idx INTEGER NOT NULL,
                     subchannel_idx INTEGER NOT NULL,
                     note_idx INTEGER NOT NULL,
                     spent INTEGER NOT NULL,
                     block_number INTEGER NOT NULL
                 );
                 CREATE INDEX IF NOT EXISTS idx_private_notes_user
                     ON private_notes(user);
                 CREATE TABLE IF NOT EXISTS private_nullifiers (
                     nullifier TEXT PRIMARY KEY,
                     note_id TEXT NOT NULL,
                     user TEXT NOT NULL
                 );
                 CREATE INDEX IF NOT EXISTS idx_private_nullifiers_user
                     ON private_nullifiers(user);
                 PRAGMA user_version = 11;",
            )
            .map_err(|e| StarktopError::Config(format!("Migration v11 failed: {e}")))?;
            debug!("Migration v11: reshaped private_notes + added private_nullifiers");
        }

        // address_calls was keyed by list position, forcing a full rewrite per
        // save; re-key by tx hash so saves upsert. Keyed on table shape rather
        // than user_version so it runs on any DB regardless of version bumps.
        let has_tx_hash: i64 = db
            .query_row(
                "SELECT count(*) FROM pragma_table_info('address_calls') WHERE name = 'tx_hash'",
                [],
                |r| r.get(0),
            )
            .map_err(|e| StarktopError::Config(format!("address_calls table_info: {e}")))?;
        if has_tx_hash == 0 {
            let t0 = std::time::Instant::now();
            db.execute_batch(
                "BEGIN;
                 CREATE TABLE address_calls_v2 (
                     address TEXT NOT NULL,
                     tx_hash TEXT NOT NULL,
                     block_number INTEGER NOT NULL,
                     data TEXT NOT NULL,
                     PRIMARY KEY (address, tx_hash)
                 );
                 INSERT OR REPLACE INTO address_calls_v2 (address, tx_hash, block_number, data)
                     SELECT address, json_extract(data, '$.tx_hash'),
                            COALESCE(json_extract(data, '$.block_number'), 0), data
                     FROM address_calls
                     WHERE json_valid(data) AND json_extract(data, '$.tx_hash') IS NOT NULL;
                 DROP TABLE address_calls;
                 ALTER TABLE address_calls_v2 RENAME TO address_calls;
                 COMMIT;",
            )
            .map_err(|e| StarktopError::Config(format!("address_calls re-key failed: {e}")))?;
            info!(
                elapsed_ms = t0.elapsed().as_millis(),
                "Re-keyed address_calls by tx hash"
            );
        }

        // address_events was keyed by list position, so every merge rewrote the
        // address's whole event list; re-key per event so merges upsert.
        let events_has_tx_hash: i64 = db
            .query_row(
                "SELECT count(*) FROM pragma_table_info('address_events') WHERE name = 'tx_hash'",
                [],
                |r| r.get(0),
            )
            .map_err(|e| StarktopError::Config(format!("address_events table_info: {e}")))?;
        if events_has_tx_hash == 0 {
            // Runs before the TUI starts; on a large cache it takes tens of seconds.
            eprintln!("starktop: upgrading the event cache (one-time)...");
            let t0 = std::time::Instant::now();
            db.execute_batch(
                "BEGIN;
                 CREATE TABLE address_events_v2 (
                     address TEXT NOT NULL,
                     block_number INTEGER NOT NULL,
                     tx_hash TEXT NOT NULL,
                     event_index INTEGER NOT NULL,
                     data TEXT NOT NULL,
                     PRIMARY KEY (address, block_number, tx_hash, event_index)
                 );
                 INSERT OR REPLACE INTO address_events_v2
                     (address, block_number, tx_hash, event_index, data)
                     SELECT address, json_extract(data, '$.block_number'),
                            json_extract(data, '$.transaction_hash'),
                            json_extract(data, '$.event_index'), data
                     FROM address_events
                     WHERE json_valid(data)
                       AND json_extract(data, '$.block_number') IS NOT NULL
                       AND json_extract(data, '$.transaction_hash') IS NOT NULL
                       AND json_extract(data, '$.event_index') IS NOT NULL
                     ORDER BY 1, 2, 3, 4;
                 DROP TABLE address_events;
                 ALTER TABLE address_events_v2 RENAME TO address_events;
                 COMMIT;",
            )
            .map_err(|e| StarktopError::Config(format!("address_events re-key failed: {e}")))?;
            info!(
                elapsed_ms = t0.elapsed().as_millis(),
                "Re-keyed address_events per event"
            );
        }

        drop(db);
        Ok(Self {
            upstream,
            db: pool,
            pending_txs: Mutex::new(HashMap::new()),
            pending_receipts: Mutex::new(HashMap::new()),
            pending_traces: Mutex::new(HashMap::new()),
            head: None,
        })
    }

    /// Plug in a chain-head source (typically a WS-fed `HeadTracker`) so cache
    /// staleness checks don't pay an RPC round-trip per call. Builder-style:
    /// call this on the freshly-constructed source before wrapping in `Arc`.
    pub fn with_head_tracker(mut self, head: Arc<dyn crate::data::LatestBlockSource>) -> Self {
        self.head = Some(head);
        self
    }

    /// Dispatch a heavy SQLite write off the async worker thread.
    ///
    /// Trait writes are sync, but several do DELETE + N×INSERT in a
    /// transaction (`save_address_txs`, `save_address_events`,
    /// `cache_block_with_txs`, ...). Run inline they pin a tokio worker
    /// for the whole transaction — under WAL write contention that means
    /// `pool.get()` (default 30s) and `busy_timeout` (5s) can stall the
    /// worker for seconds, delaying every other async task scheduled on
    /// it. Hand the closure to `spawn_blocking` instead.
    ///
    /// Fire-and-forget — these writes are idempotent caches and callers
    /// never use the return value. If no tokio runtime is in scope
    /// (e.g. from a sync unit test), fall back to running inline so
    /// existing tests still observe the write before they read back.
    fn dispatch_write<F>(f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        match tokio::runtime::Handle::try_current() {
            Ok(handle) => {
                handle.spawn_blocking(f);
            }
            Err(_) => f(),
        }
    }

    fn get_cached_block(&self, number: u64) -> Option<SnBlock> {
        let db = self.db.get().ok()?;
        let mut stmt = db
            .prepare("SELECT data FROM blocks WHERE number = ?1")
            .ok()?;
        let json: String = stmt.query_row(params![number], |row| row.get(0)).ok()?;
        serde_json::from_str(&json).ok()
    }

    fn cache_block(&self, block: &SnBlock) {
        if let Ok(json) = serde_json::to_string(block)
            && let Ok(db) = self.db.get()
        {
            let _ = db.execute(
                "INSERT OR REPLACE INTO blocks (number, data) VALUES (?1, ?2)",
                params![block.number, json],
            );
            // Also index hash→number for get_block_by_hash cache
            if block.hash != Felt::ZERO {
                let hash_hex = format!("{:#x}", block.hash);
                let _ = db.execute(
                    "INSERT OR REPLACE INTO block_hash_index (hash, number) VALUES (?1, ?2)",
                    params![hash_hex, block.number as i64],
                );
            }
        }
    }

    fn get_cached_block_with_txs(&self, number: u64) -> Option<(SnBlock, Vec<SnTransaction>)> {
        let block = self.get_cached_block(number)?;
        let db = self.db.get().ok()?;
        let mut stmt = db
            .prepare(
                "SELECT data FROM block_transactions WHERE block_number = ?1 ORDER BY tx_index",
            )
            .ok()?;
        let txs: Vec<SnTransaction> = stmt
            .query_map(params![number], |row| {
                let json: String = row.get(0)?;
                Ok(json)
            })
            .ok()?
            .filter_map(|r| r.ok())
            .filter_map(|json| serde_json::from_str(&json).ok())
            .collect();

        if txs.is_empty() {
            return None;
        }
        Some((block, txs))
    }

    /// Atomically write the block row, its hash index, and the full tx list
    /// so readers never observe a half-populated state. With the r2d2 pool, a
    /// prior split (block inserted on conn A, tx list on conn B) let readers
    /// hitting `get_cached_block_with_txs` between the two commits see the
    /// block but an empty tx list and return `None` at the `txs.is_empty()`
    /// guard — a false miss that caused upstream re-fetches. Everything now
    /// runs inside one transaction on a single pooled connection.
    fn cache_block_with_txs(&self, block: &SnBlock, txs: &[SnTransaction]) {
        // Serialize on the caller thread so the spawn_blocking closure only
        // does I/O. block_hash and tx hashes captured outside the closure.
        let block_json = match serde_json::to_string(block) {
            Ok(s) => s,
            Err(_) => return,
        };
        let block_number = block.number;
        let block_hash_hex = if block.hash != Felt::ZERO {
            Some(format!("{:#x}", block.hash))
        } else {
            None
        };
        let tx_rows: Vec<(i64, String, String)> = txs
            .iter()
            .enumerate()
            .filter_map(|(i, tx)| {
                let json = serde_json::to_string(tx).ok()?;
                Some((i as i64, format!("{:#x}", tx.hash()), json))
            })
            .collect();
        let pool = self.db.clone();
        Self::dispatch_write(move || {
            let mut db = match pool.get() {
                Ok(c) => c,
                Err(e) => {
                    warn!(error = %e, "cache_block_with_txs: pool get failed");
                    return;
                }
            };
            let tx_db = match db.transaction() {
                Ok(t) => t,
                Err(e) => {
                    warn!(error = %e, "cache_block_with_txs: begin transaction failed");
                    return;
                }
            };
            let _ = tx_db.execute(
                "INSERT OR REPLACE INTO blocks (number, data) VALUES (?1, ?2)",
                params![block_number, block_json],
            );
            if let Some(hash_hex) = &block_hash_hex {
                let _ = tx_db.execute(
                    "INSERT OR REPLACE INTO block_hash_index (hash, number) VALUES (?1, ?2)",
                    params![hash_hex, block_number as i64],
                );
            }
            for (i, hash_hex, json) in &tx_rows {
                let _ = tx_db.execute(
                    "INSERT OR REPLACE INTO block_transactions (block_number, tx_index, tx_hash, data) VALUES (?1, ?2, ?3, ?4)",
                    params![block_number, i, hash_hex, json],
                );
                let _ = tx_db.execute(
                    "INSERT OR REPLACE INTO transactions (hash, block_number, data) VALUES (?1, ?2, ?3)",
                    params![hash_hex, block_number, json],
                );
            }
            if let Err(e) = tx_db.commit() {
                warn!(error = %e, "cache_block_with_txs: commit failed");
            }
        });
    }

    fn get_cached_transaction(&self, hash: Felt) -> Option<SnTransaction> {
        let db = self.db.get().ok()?;
        let hash_hex = format!("{:#x}", hash);
        let mut stmt = db
            .prepare("SELECT data FROM transactions WHERE hash = ?1")
            .ok()?;
        let json: String = stmt.query_row(params![hash_hex], |row| row.get(0)).ok()?;
        serde_json::from_str(&json).ok()
    }

    fn cache_transaction(&self, tx: &SnTransaction) {
        if let Ok(json) = serde_json::to_string(tx)
            && let Ok(db) = self.db.get()
        {
            let hash_hex = format!("{:#x}", tx.hash());
            let _ = db.execute(
                    "INSERT OR REPLACE INTO transactions (hash, block_number, data) VALUES (?1, ?2, ?3)",
                    params![hash_hex, 0i64, json],
                );
        }
    }

    fn get_cached_address_events(&self, address: &Felt) -> Vec<SnEvent> {
        let db = match self.db.get() {
            Ok(db) => db,
            Err(_) => return Vec::new(),
        };
        let addr_hex = format!("{:#x}", address);
        let mut stmt = match db.prepare(
            "SELECT data FROM address_events WHERE address = ?1 \
             ORDER BY block_number DESC, tx_hash, event_index DESC",
        ) {
            Ok(s) => s,
            Err(_) => return Vec::new(),
        };
        let rows = match stmt.query_map(params![addr_hex], |row| row.get::<_, String>(0)) {
            Ok(r) => r,
            Err(_) => return Vec::new(),
        };
        rows.filter_map(|r| r.ok())
            .filter_map(|json| serde_json::from_str(&json).ok())
            .collect()
    }

    /// `(block_number, tx_hash, event_index, json)` rows for an `address_events` upsert.
    fn event_rows(events: &[SnEvent]) -> Vec<(i64, String, i64, String)> {
        events
            .iter()
            .filter_map(|e| {
                let json = serde_json::to_string(e).ok()?;
                Some((
                    e.block_number as i64,
                    format!("{:#x}", e.transaction_hash),
                    e.event_index as i64,
                    json,
                ))
            })
            .collect()
    }

    fn upsert_event_rows(
        db: &mut rusqlite::Connection,
        addr_hex: &str,
        rows: &[(i64, String, i64, String)],
    ) {
        Self::retry_locked("address_events", || {
            let tx = db.transaction()?;
            {
                let mut stmt = tx.prepare_cached(
                    "INSERT OR REPLACE INTO address_events \
                     (address, block_number, tx_hash, event_index, data) \
                     VALUES (?1, ?2, ?3, ?4, ?5)",
                )?;
                for (block, hash, idx, json) in rows {
                    stmt.execute(params![addr_hex, block, hash, idx, json])?;
                }
            }
            tx.commit()
        });
    }

    /// Fire-and-forget upsert of `events`, off the async worker.
    fn append_address_events_impl(&self, address: &Felt, events: &[SnEvent]) {
        if events.is_empty() {
            return;
        }
        let pool = self.db.clone();
        let addr_hex = format!("{:#x}", address);
        let rows = Self::event_rows(events);
        Self::dispatch_write(move || {
            let Ok(mut db) = pool.get() else {
                warn!("append_address_events: pool get failed");
                return;
            };
            Self::upsert_event_rows(&mut db, &addr_hex, &rows);
        });
    }

    /// Merge `cached` into `fresh` newest-first, deduping by
    /// `(tx_hash, block_number, event_index)`.
    fn merge_events_dedup(mut fresh: Vec<SnEvent>, cached: Vec<SnEvent>) -> Vec<SnEvent> {
        let mut seen: HashSet<(Felt, u64, u64)> =
            HashSet::with_capacity(fresh.len() + cached.len());
        fresh.retain(|e| seen.insert((e.transaction_hash, e.block_number, e.event_index)));
        for e in cached {
            if seen.insert((e.transaction_hash, e.block_number, e.event_index)) {
                fresh.push(e);
            }
        }
        fresh
    }

    /// Upsert `new_events`, then return the address's whole cached list newest-first.
    fn merge_address_events_impl(&self, address: &Felt, new_events: &[SnEvent]) -> Vec<SnEvent> {
        if !new_events.is_empty() {
            let addr_hex = format!("{:#x}", address);
            match self.db.get() {
                Ok(mut db) => {
                    Self::upsert_event_rows(&mut db, &addr_hex, &Self::event_rows(new_events))
                }
                Err(e) => warn!(error = %e, "merge_address_events: pool get failed"),
            }
        }
        let merged = self.get_cached_address_events(address);
        if merged.is_empty() {
            return new_events.to_vec();
        }
        merged
    }

    fn get_cached_receipt(&self, hash: Felt) -> Option<SnReceipt> {
        let db = self.db.get().ok()?;
        let hash_hex = format!("{:#x}", hash);
        let mut stmt = db
            .prepare("SELECT data FROM receipts WHERE tx_hash = ?1")
            .ok()?;
        let json: String = stmt.query_row(params![hash_hex], |row| row.get(0)).ok()?;
        serde_json::from_str(&json).ok()
    }

    fn cache_receipt(&self, receipt: &SnReceipt) {
        if let Ok(json) = serde_json::to_string(receipt)
            && let Ok(db) = self.db.get()
        {
            let hash_hex = format!("{:#x}", receipt.transaction_hash);
            let _ = db.execute(
                "INSERT OR REPLACE INTO receipts (tx_hash, data) VALUES (?1, ?2)",
                params![hash_hex, json],
            );
        }
    }

    // --- tx_trace cache ---
    // Traces are deterministic for finalized txs and the RPC call is expensive
    // (recursive call tree, hundreds of ms). Stash the JSON-serialized trace
    // keyed by tx hash so revisits are instant.
    fn get_cached_trace(&self, hash: Felt) -> Option<TransactionTrace> {
        let db = self.db.get().ok()?;
        let hash_hex = format!("{:#x}", hash);
        let mut stmt = db
            .prepare("SELECT data FROM tx_traces WHERE tx_hash = ?1")
            .ok()?;
        let json: String = stmt.query_row(params![hash_hex], |row| row.get(0)).ok()?;
        serde_json::from_str(&json).ok()
    }

    fn cache_trace(&self, hash: Felt, trace: &TransactionTrace) {
        if let Ok(json) = serde_json::to_string(trace)
            && let Ok(db) = self.db.get()
        {
            let hash_hex = format!("{:#x}", hash);
            let _ = db.execute(
                "INSERT OR REPLACE INTO tx_traces (tx_hash, data) VALUES (?1, ?2)",
                params![hash_hex, json],
            );
        }
    }

    // --- class_hash cache ---

    fn get_cached_class_hash(&self, address: &Felt) -> Option<(Felt, u64)> {
        let db = self.db.get().ok()?;
        let addr_hex = format!("{:#x}", address);
        let mut stmt = db
            .prepare("SELECT class_hash, fetched_at_block FROM class_hashes WHERE address = ?1")
            .ok()?;
        stmt.query_row(params![addr_hex], |row| {
            let ch_hex: String = row.get(0)?;
            let block: i64 = row.get(1)?;
            Ok((ch_hex, block as u64))
        })
        .ok()
        .and_then(|(ch_hex, block)| Felt::from_hex(&ch_hex).ok().map(|f| (f, block)))
    }

    fn cache_class_hash(&self, address: &Felt, class_hash: &Felt, block: u64) {
        if let Ok(db) = self.db.get() {
            let addr_hex = format!("{:#x}", address);
            let ch_hex = format!("{:#x}", class_hash);
            let _ = db.execute(
                "INSERT OR REPLACE INTO class_hashes (address, class_hash, fetched_at_block) VALUES (?1, ?2, ?3)",
                params![addr_hex, ch_hex, block as i64],
            );
        }
    }

    // --- block_by_hash cache ---

    fn get_cached_block_number_by_hash(&self, hash: &Felt) -> Option<u64> {
        let db = self.db.get().ok()?;
        let hash_hex = format!("{:#x}", hash);
        let mut stmt = db
            .prepare("SELECT number FROM block_hash_index WHERE hash = ?1")
            .ok()?;
        stmt.query_row(params![hash_hex], |row| {
            let n: i64 = row.get(0)?;
            Ok(n as u64)
        })
        .ok()
    }

    fn cache_block_hash(&self, hash: &Felt, number: u64) {
        if let Ok(db) = self.db.get() {
            let hash_hex = format!("{:#x}", hash);
            let _ = db.execute(
                "INSERT OR REPLACE INTO block_hash_index (hash, number) VALUES (?1, ?2)",
                params![hash_hex, number as i64],
            );
        }
    }

    // --- deploy info cache ---

    fn get_cached_deploy_info(&self, address: &Felt) -> Option<(Felt, u64, Option<Felt>)> {
        let db = self.db.get().ok()?;
        let addr_hex = format!("{:#x}", address);
        let mut stmt = db
            .prepare(
                "SELECT deploy_tx_hash, deploy_block, deployer FROM deploy_info WHERE address = ?1",
            )
            .ok()?;
        stmt.query_row(params![addr_hex], |row| {
            let tx_hex: String = row.get(0)?;
            let block: i64 = row.get(1)?;
            let deployer_hex: Option<String> = row.get(2)?;
            Ok((tx_hex, block as u64, deployer_hex))
        })
        .ok()
        .and_then(|(tx_hex, block, deployer_hex)| {
            let tx_hash = Felt::from_hex(&tx_hex).ok()?;
            let deployer = deployer_hex.and_then(|h| Felt::from_hex(&h).ok());
            Some((tx_hash, block, deployer))
        })
    }

    fn cache_deploy_info(
        &self,
        address: &Felt,
        tx_hash: &Felt,
        block: u64,
        deployer: Option<&Felt>,
    ) {
        if let Ok(db) = self.db.get() {
            let addr_hex = format!("{:#x}", address);
            let tx_hex = format!("{:#x}", tx_hash);
            let deployer_hex = deployer.map(|d| format!("{:#x}", d));
            let _ = db.execute(
                "INSERT OR REPLACE INTO deploy_info (address, deploy_tx_hash, deploy_block, deployer) VALUES (?1, ?2, ?3, ?4)",
                params![addr_hex, tx_hex, block as i64, deployer_hex],
            );
        }
    }

    // --- class history cache ---

    fn get_cached_class_history(
        &self,
        address: &Felt,
    ) -> Vec<crate::data::pathfinder::ClassHashEntry> {
        let db = match self.db.get() {
            Ok(d) => d,
            Err(_) => return Vec::new(),
        };
        let addr_hex = format!("{:#x}", address);
        let mut stmt = match db.prepare(
            "SELECT block_number, class_hash FROM class_history \
             WHERE address = ?1 ORDER BY block_number DESC",
        ) {
            Ok(s) => s,
            Err(_) => return Vec::new(),
        };
        let rows = stmt.query_map(params![addr_hex], |row| {
            let block: i64 = row.get(0)?;
            let class_hash: String = row.get(1)?;
            Ok(crate::data::pathfinder::ClassHashEntry {
                block_number: block as u64,
                class_hash,
            })
        });
        match rows {
            Ok(iter) => iter.filter_map(|r| r.ok()).collect(),
            Err(_) => Vec::new(),
        }
    }

    fn cache_class_history(
        &self,
        address: &Felt,
        entries: &[crate::data::pathfinder::ClassHashEntry],
    ) {
        let mut db = match self.db.get() {
            Ok(d) => d,
            Err(_) => return,
        };
        let addr_hex = format!("{:#x}", address);
        let tx = match db.transaction_with_behavior(TransactionBehavior::Immediate) {
            Ok(t) => t,
            Err(_) => return,
        };
        if tx
            .execute(
                "DELETE FROM class_history WHERE address = ?1",
                params![addr_hex],
            )
            .is_err()
        {
            return;
        }
        for entry in entries {
            if tx
                .execute(
                    "INSERT OR REPLACE INTO class_history (address, block_number, class_hash) \
                     VALUES (?1, ?2, ?3)",
                    params![addr_hex, entry.block_number as i64, entry.class_hash],
                )
                .is_err()
            {
                return;
            }
        }
        let _ = tx.commit();
    }

    fn get_cached_class_history_max_block(&self, address: &Felt) -> Option<u64> {
        let db = self.db.get().ok()?;
        let addr_hex = format!("{:#x}", address);
        let mut stmt = db
            .prepare("SELECT last_known_block FROM class_history_meta WHERE address = ?1")
            .ok()?;
        stmt.query_row(params![addr_hex], |row| {
            let block: i64 = row.get(0)?;
            Ok(block as u64)
        })
        .ok()
    }

    fn cache_class_history_max_block(&self, address: &Felt, block: u64) {
        if let Ok(db) = self.db.get() {
            let addr_hex = format!("{:#x}", address);
            let _ = db.execute(
                "INSERT OR REPLACE INTO class_history_meta (address, last_known_block) \
                 VALUES (?1, ?2)",
                params![addr_hex, block as i64],
            );
        }
    }

    // --- nonce cache ---

    fn get_cached_nonce_info(&self, address: &Felt) -> Option<(Felt, u64)> {
        let db = self.db.get().ok()?;
        let addr_hex = format!("{:#x}", address);
        let mut stmt = db
            .prepare("SELECT nonce, block_number FROM cached_nonces WHERE address = ?1")
            .ok()?;
        stmt.query_row(params![addr_hex], |row| {
            let nonce_hex: String = row.get(0)?;
            let block: i64 = row.get(1)?;
            Ok((nonce_hex, block as u64))
        })
        .ok()
        .and_then(|(nonce_hex, block)| Felt::from_hex(&nonce_hex).ok().map(|f| (f, block)))
    }

    fn cache_nonce_info(&self, address: &Felt, nonce: &Felt, block: u64) {
        if let Ok(db) = self.db.get() {
            let addr_hex = format!("{:#x}", address);
            let nonce_hex = format!("{:#x}", nonce);
            let _ = db.execute(
                "INSERT OR REPLACE INTO cached_nonces (address, nonce, block_number) VALUES (?1, ?2, ?3)",
                params![addr_hex, nonce_hex, block as i64],
            );
        }
    }

    // --- search progress cache ---

    fn get_cached_search_progress(
        &self,
        address: &Felt,
        filter_kind: FilterKind,
    ) -> Option<(u64, u64)> {
        let db = self.db.get().ok()?;
        let addr_hex = format!("{:#x}", address);
        let mut stmt = db
            .prepare(
                "SELECT min_searched_block, max_searched_block FROM address_search_progress \
                 WHERE address = ?1 AND filter_kind = ?2",
            )
            .ok()?;
        stmt.query_row(params![addr_hex, filter_kind.as_str()], |row| {
            let min: i64 = row.get(0)?;
            let max: i64 = row.get(1)?;
            Ok((min as u64, max as u64))
        })
        .ok()
    }

    fn cache_search_progress(
        &self,
        address: &Felt,
        filter_kind: FilterKind,
        min_block: u64,
        max_block: u64,
    ) {
        if let Ok(db) = self.db.get() {
            let addr_hex = format!("{:#x}", address);
            // Merge: expand existing range for this (address, filter_kind) row.
            let existing = db
                .prepare(
                    "SELECT min_searched_block, max_searched_block FROM address_search_progress \
                     WHERE address = ?1 AND filter_kind = ?2",
                )
                .ok()
                .and_then(|mut s| {
                    s.query_row(params![addr_hex, filter_kind.as_str()], |row| {
                        let min: i64 = row.get(0)?;
                        let max: i64 = row.get(1)?;
                        Ok((min as u64, max as u64))
                    })
                    .ok()
                });
            let (final_min, final_max) = if let Some((old_min, old_max)) = existing {
                (old_min.min(min_block), old_max.max(max_block))
            } else {
                (min_block, max_block)
            };
            let _ = db.execute(
                "INSERT OR REPLACE INTO address_search_progress \
                 (address, filter_kind, min_searched_block, max_searched_block) \
                 VALUES (?1, ?2, ?3, ?4)",
                params![
                    addr_hex,
                    filter_kind.as_str(),
                    final_min as i64,
                    final_max as i64
                ],
            );
        }
    }

    fn get_cached_activity_total(&self, address: &Felt) -> Option<u64> {
        let db = self.db.get().ok()?;
        let addr_hex = format!("{:#x}", address);
        let mut stmt = db
            .prepare("SELECT total_known FROM address_activity_total WHERE address = ?1")
            .ok()?;
        stmt.query_row(params![addr_hex], |row| row.get::<_, i64>(0))
            .ok()
            .map(|v| v as u64)
    }

    fn cache_activity_total(&self, address: &Felt, total: u64) {
        if let Ok(db) = self.db.get() {
            let addr_hex = format!("{:#x}", address);
            let _ = db.execute(
                "INSERT OR REPLACE INTO address_activity_total (address, total_known) VALUES (?1, ?2)",
                params![addr_hex, total as i64],
            );
        }
    }

    // --- contract events cache ---

    fn load_contract_events(&self, address: &Felt) -> Vec<SnEvent> {
        let db = match self.db.get() {
            Ok(db) => db,
            Err(_) => return Vec::new(),
        };
        let addr_hex = format!("{:#x}", address);
        let mut stmt = match db
            .prepare("SELECT data FROM contract_events WHERE address = ?1 ORDER BY event_index")
        {
            Ok(s) => s,
            Err(_) => return Vec::new(),
        };
        let rows = match stmt.query_map(params![addr_hex], |row| row.get::<_, String>(0)) {
            Ok(r) => r,
            Err(_) => return Vec::new(),
        };
        rows.filter_map(|r| r.ok())
            .filter_map(|json| serde_json::from_str(&json).ok())
            .collect()
    }

    fn save_contract_events(&self, address: &Felt, events: &[SnEvent]) {
        let pool = self.db.clone();
        let addr_hex = format!("{:#x}", address);
        let rows: Vec<(i64, String)> = events
            .iter()
            .enumerate()
            .filter_map(|(i, e)| serde_json::to_string(e).ok().map(|j| (i as i64, j)))
            .collect();
        Self::dispatch_write(move || {
            if let Ok(mut db) = pool.get() {
                let tx = match db.transaction() {
                    Ok(t) => t,
                    Err(e) => {
                        warn!(error = %e, "save_contract_events: begin transaction failed");
                        return;
                    }
                };
                let _ = tx.execute(
                    "DELETE FROM contract_events WHERE address = ?1",
                    params![&addr_hex],
                );
                for (i, json) in &rows {
                    let _ = tx.execute(
                        "INSERT OR REPLACE INTO contract_events (address, event_index, data) VALUES (?1, ?2, ?3)",
                        params![&addr_hex, i, json],
                    );
                }
                if let Err(e) = tx.commit() {
                    warn!(error = %e, "save_contract_events: commit failed");
                }
            }
        });
    }
}

impl CachingDataSource {
    /// Run an idempotent write, retrying while SQLite reports busy/locked.
    /// Bulk upserts from other tabs hold the WAL write lock past
    /// `busy_timeout`, and `BEGIN IMMEDIATE` then fails without waiting.
    fn retry_locked(label: &str, mut f: impl FnMut() -> rusqlite::Result<()>) {
        const ATTEMPTS: u32 = 40;
        for attempt in 1..=ATTEMPTS {
            match f() {
                Ok(()) => return,
                Err(e) if attempt < ATTEMPTS && Self::is_locked(&e) => {
                    std::thread::sleep(std::time::Duration::from_millis(250));
                }
                Err(e) => {
                    warn!(error = %e, label, attempt, "cache write failed");
                    return;
                }
            }
        }
    }

    fn is_locked(e: &rusqlite::Error) -> bool {
        matches!(
            e,
            rusqlite::Error::SqliteFailure(f, _)
                if matches!(
                    f.code,
                    rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked
                )
        )
    }

    /// Persisted fully-scanned `[lo, hi]` block ranges for one address (sorted).
    fn load_scanned_ranges(&self, table: &str, address: &Felt) -> Vec<(u64, u64)> {
        let db = match self.db.get() {
            Ok(db) => db,
            Err(_) => return Vec::new(),
        };
        let addr_hex = format!("{:#x}", address);
        let sql =
            format!("SELECT lo_block, hi_block FROM {table} WHERE address = ?1 ORDER BY lo_block");
        let mut stmt = match db.prepare(&sql) {
            Ok(s) => s,
            Err(_) => return Vec::new(),
        };
        let rows = match stmt.query_map(params![addr_hex], |row| {
            Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?))
        }) {
            Ok(r) => r,
            Err(_) => return Vec::new(),
        };
        rows.filter_map(|r| r.ok())
            .map(|(lo, hi)| (lo as u64, hi as u64))
            .collect()
    }

    /// Coalesce `[lo, hi]` into the persisted range set and rewrite it, so the
    /// stored set stays sorted and minimal like the in-memory one.
    fn add_scanned_range(&self, table: &'static str, address: &Felt, lo: u64, hi: u64) {
        let pool = self.db.clone();
        let addr_hex = format!("{:#x}", address);
        Self::dispatch_write(move || {
            let Ok(mut db) = pool.get() else {
                warn!(table, "add_scanned_range: pool get failed");
                return;
            };
            Self::retry_locked(table, || {
                // Read-then-rewrite must hold the write lock from the start: a
                // deferred tx whose snapshot goes stale fails with BUSY_SNAPSHOT.
                let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
                let mut ranges: Vec<(u64, u64)> = tx
                    .prepare(&format!(
                        "SELECT lo_block, hi_block FROM {table} WHERE address = ?1"
                    ))?
                    .query_map(params![&addr_hex], |row| {
                        Ok((row.get::<_, i64>(0)? as u64, row.get::<_, i64>(1)? as u64))
                    })?
                    .collect::<rusqlite::Result<Vec<_>>>()?;
                crate::utils::merge_block_interval(&mut ranges, lo, hi);
                tx.execute(
                    &format!("DELETE FROM {table} WHERE address = ?1"),
                    params![&addr_hex],
                )?;
                for (rlo, rhi) in &ranges {
                    tx.execute(
                        &format!(
                            "INSERT OR REPLACE INTO {table} (address, lo_block, hi_block) VALUES (?1, ?2, ?3)"
                        ),
                        params![&addr_hex, *rlo as i64, *rhi as i64],
                    )?;
                }
                tx.commit()
            });
        });
    }
}

#[async_trait]
impl DataSource for CachingDataSource {
    async fn get_latest_block_number(&self) -> Result<u64> {
        // Always go to upstream for latest block number (it changes constantly)
        self.upstream.get_latest_block_number().await
    }

    async fn latest_block_hint(&self) -> Option<u64> {
        // Prefer the in-process tracker — typically WS-fed, sub-second fresh —
        // so window/anchor math doesn't pay an RPC round trip per call. The
        // tracker reports `None` when empty (cold start) or stale (WS dropped
        // and the head-keeper hasn't ticked); in those cases the upstream RPC
        // is the only honest answer. Mirror the trait default's logging so
        // operators can tell a transient RPC outage from a missing tracker.
        if let Some(head) = &self.head
            && let Some(block) = head.latest()
        {
            return Some(block);
        }
        match self.upstream.get_latest_block_number().await {
            Ok(n) => Some(n),
            Err(e) => {
                debug!(error = %e, "latest_block_hint: upstream get_latest_block_number failed");
                None
            }
        }
    }

    async fn get_block(&self, number: u64) -> Result<SnBlock> {
        if let Some(mut block) = self.get_cached_block(number) {
            // Finality can advance ACCEPTED_ON_L2 -> ACCEPTED_ON_L1 (and is
            // immutable thereafter). Serve final blocks straight from cache;
            // re-probe anything not yet final and patch the cached status.
            if is_final_status(&block.status) {
                trace!(number, "cache hit: block (final)");
                return Ok(block);
            }
            match self.upstream.get_block_status(number).await {
                Ok(status) => {
                    if status != block.status {
                        debug!(number, %status, "block status advanced, updating cache");
                        block.status = status;
                        self.cache_block(&block);
                    }
                    return Ok(block);
                }
                // Probe failed — fall back to the cached (stale) block rather
                // than forcing a full refetch or erroring the view.
                Err(e) => {
                    debug!(number, error = %e, "block status probe failed, serving cached");
                    return Ok(block);
                }
            }
        }
        debug!(number, "cache miss: block, fetching from RPC");
        let block = self.upstream.get_block(number).await?;
        self.cache_block(&block);
        Ok(block)
    }

    async fn get_block_by_hash(&self, hash: Felt) -> Result<u64> {
        if let Some(number) = self.get_cached_block_number_by_hash(&hash) {
            trace!(hash = %format!("{:#x}", hash), "cache hit: block_by_hash");
            return Ok(number);
        }
        let number = self.upstream.get_block_by_hash(hash).await?;
        self.cache_block_hash(&hash, number);
        Ok(number)
    }

    async fn get_block_with_txs(&self, number: u64) -> Result<(SnBlock, Vec<SnTransaction>)> {
        if let Some((mut block, txs)) = self.get_cached_block_with_txs(number) {
            // Transactions are immutable once mined; only the block's finality
            // can advance. When not yet final, re-probe the status alone (a
            // light header call) and patch the cached block row — the cached
            // tx bodies are never re-downloaded.
            if is_final_status(&block.status) {
                trace!(number, tx_count = txs.len(), "cache hit: block+txs (final)");
                return Ok((block, txs));
            }
            match self.upstream.get_block_status(number).await {
                Ok(status) => {
                    if status != block.status {
                        debug!(number, %status, "block status advanced, updating cache");
                        block.status = status;
                        self.cache_block(&block);
                    }
                }
                Err(e) => {
                    debug!(number, error = %e, "block status probe failed, serving cached");
                }
            }
            return Ok((block, txs));
        }
        debug!(number, "cache miss: block+txs, fetching from RPC");
        let (block, txs) = self.upstream.get_block_with_txs(number).await?;
        self.cache_block_with_txs(&block, &txs);
        Ok((block, txs))
    }

    async fn get_transaction(&self, hash: Felt) -> Result<SnTransaction> {
        if let Some(tx) = self.get_cached_transaction(hash) {
            trace!(tx_hash = %format!("{:#x}", hash), "cache hit: transaction");
            return Ok(tx);
        }

        // In-flight dedup: if another caller is already fetching this hash,
        // await their future instead of firing a second RPC.
        let fut = {
            let mut pending = self.pending_txs.lock().unwrap();
            if let Some(existing) = pending.get(&hash) {
                trace!(tx_hash = %format!("{:#x}", hash), "dedup: joining in-flight transaction fetch");
                existing.clone()
            } else {
                debug!(tx_hash = %format!("{:#x}", hash), "cache miss: transaction, fetching from RPC");
                let upstream = Arc::clone(&self.upstream);
                let fut: Pin<
                    Box<dyn Future<Output = std::result::Result<SnTransaction, String>> + Send>,
                > = Box::pin(async move {
                    upstream
                        .get_transaction(hash)
                        .await
                        .map_err(|e| e.to_string())
                });
                let shared = fut.shared();
                pending.insert(hash, shared.clone());
                shared
            }
        };

        let result = fut.await;

        // Leader cleanup: whichever task observes it first removes the entry
        // so a later miss can start a fresh fetch.
        {
            let mut pending = self.pending_txs.lock().unwrap();
            pending.remove(&hash);
        }

        match result {
            Ok(tx) => {
                self.cache_transaction(&tx);
                Ok(tx)
            }
            Err(e) => Err(StarktopError::Rpc(e)),
        }
    }

    async fn get_receipt(&self, hash: Felt) -> Result<SnReceipt> {
        if let Some(receipt) = self.get_cached_receipt(hash) {
            trace!(tx_hash = %format!("{:#x}", hash), "cache hit: receipt");
            return Ok(receipt);
        }

        let fut = {
            let mut pending = self.pending_receipts.lock().unwrap();
            if let Some(existing) = pending.get(&hash) {
                trace!(tx_hash = %format!("{:#x}", hash), "dedup: joining in-flight receipt fetch");
                existing.clone()
            } else {
                debug!(tx_hash = %format!("{:#x}", hash), "cache miss: receipt, fetching from RPC");
                let upstream = Arc::clone(&self.upstream);
                let fut: Pin<
                    Box<dyn Future<Output = std::result::Result<SnReceipt, String>> + Send>,
                > = Box::pin(
                    async move { upstream.get_receipt(hash).await.map_err(|e| e.to_string()) },
                );
                let shared = fut.shared();
                pending.insert(hash, shared.clone());
                shared
            }
        };

        let result = fut.await;

        {
            let mut pending = self.pending_receipts.lock().unwrap();
            pending.remove(&hash);
        }

        match result {
            Ok(receipt) => {
                self.cache_receipt(&receipt);
                Ok(receipt)
            }
            Err(e) => Err(StarktopError::Rpc(e)),
        }
    }

    async fn get_nonce(&self, address: Felt) -> Result<Felt> {
        // Nonces change — always go upstream
        self.upstream.get_nonce(address).await
    }

    async fn get_class_hash(&self, address: Felt) -> Result<Felt> {
        // Class hash is mostly stable but CAN change via replace_class syscall.
        // Cache with the block at which we fetched it; refetch if stale (>1000 blocks).
        //
        // Head-hint failure handling:
        //  - Read side: a missing hint makes `0.saturating_sub(fetched_at) = 0`,
        //    so we treat the cached entry as fresh — "fail open" toward the
        //    warm value rather than hammering the upstream when we couldn't
        //    even read the head.
        //  - Write side: we skip persisting the anchor entirely when the head
        //    is unknown. Caching with `fetched_at = 0` would force every
        //    subsequent call (once the tracker recovers) to treat the entry
        //    as 1000+ blocks stale and refetch unnecessarily.
        const CLASS_HASH_STALE_BLOCKS: u64 = 1000;
        if let Some((class_hash, fetched_at)) = self.get_cached_class_hash(&address) {
            let latest = self.latest_block_hint().await.unwrap_or(0);
            let age = latest.saturating_sub(fetched_at);
            if age < CLASS_HASH_STALE_BLOCKS {
                trace!(address = %format!("{:#x}", address), "cache hit: class_hash");
                return Ok(class_hash);
            }
            debug!(address = %format!("{:#x}", address), age, "class_hash cache stale, refetching");
        }
        let class_hash = self.upstream.get_class_hash(address).await?;
        if let Some(block) = self.latest_block_hint().await {
            self.cache_class_hash(&address, &class_hash, block);
        }
        Ok(class_hash)
    }

    async fn get_class_hash_at(&self, address: Felt, block: u64) -> Result<Felt> {
        // The (address, block) → class_hash mapping is immutable, but the
        // class_history table already caches it at coarser granularity for
        // the addresses tx decoding cares about. Pass through here; the
        // helper that wraps this (`resolve_class_hash_at`) consults
        // class_history first and only hits this fallback when the cached
        // history is incomplete.
        self.upstream.get_class_hash_at(address, block).await
    }

    async fn get_class(&self, class_hash: Felt) -> Result<ContractClass> {
        // Classes are large — pass through to upstream.
        // Parsed ABIs are cached separately via the decode layer's class_cache.
        debug!(class_hash = %format!("{:#x}", class_hash), "Fetching class from RPC (not cached — parsed ABI cached separately)");
        self.upstream.get_class(class_hash).await
    }

    async fn get_trace(&self, hash: Felt) -> Result<TransactionTrace> {
        if let Some(cached) = self.get_cached_trace(hash) {
            trace!(tx_hash = %format!("{:#x}", hash), "cache hit: trace");
            return Ok(cached);
        }

        // Coalesce concurrent misses on the same hash into one RPC, mirroring
        // the get_transaction / get_receipt pattern. Trace fetches are
        // expensive (recursive call tree, hundreds of ms), so a re-fetch race
        // would otherwise issue several full traces before the first lands.
        let fut = {
            let mut pending = self.pending_traces.lock().unwrap();
            if let Some(existing) = pending.get(&hash) {
                trace!(tx_hash = %format!("{:#x}", hash), "dedup: joining in-flight trace fetch");
                existing.clone()
            } else {
                debug!(tx_hash = %format!("{:#x}", hash), "cache miss: trace, fetching from RPC");
                let upstream = Arc::clone(&self.upstream);
                let fut: Pin<
                    Box<dyn Future<Output = std::result::Result<TransactionTrace, String>> + Send>,
                > = Box::pin(
                    async move { upstream.get_trace(hash).await.map_err(|e| e.to_string()) },
                );
                let shared = fut.shared();
                pending.insert(hash, shared.clone());
                shared
            }
        };

        let result = fut.await;

        {
            let mut pending = self.pending_traces.lock().unwrap();
            pending.remove(&hash);
        }

        match result {
            Ok(fetched) => {
                self.cache_trace(hash, &fetched);
                Ok(fetched)
            }
            Err(e) => Err(StarktopError::Rpc(e)),
        }
    }

    async fn get_events_for_address(
        &self,
        address: Felt,
        from_block: Option<u64>,
        to_block: Option<u64>,
        limit: usize,
    ) -> Result<Vec<SnEvent>> {
        // Bounded (paginating into history) — bypass cache merge and pass through.
        // The cache only accelerates the "newest events" path; old-window fetches
        // shouldn't poison the cache with partial windows.
        if to_block.is_some() {
            return self
                .upstream
                .get_events_for_address(address, from_block, to_block, limit)
                .await;
        }

        // Load cached events
        let cached = self.get_cached_address_events(&address);

        // Incremental: fetch events newer than our newest cached event
        let fetch_from = if !cached.is_empty() && from_block.is_none() {
            // Start from the block AFTER our newest cached event to avoid duplicates
            let max_block = cached.iter().map(|e| e.block_number).max().unwrap_or(0);
            Some(max_block + 1)
        } else {
            from_block
        };

        // Fetch from upstream
        let new_events = self
            .upstream
            .get_events_for_address(address, fetch_from, None, limit)
            .await
            .unwrap_or_default();

        self.append_address_events_impl(&address, &new_events);

        // Merge: new + cached (new events are newest-first, cached are newest-first)
        let mut merged = Self::merge_events_dedup(new_events, cached);

        // Sort by block number descending (newest first)
        merged.sort_by(|a, b| b.block_number.cmp(&a.block_number));

        Ok(merged)
    }

    fn load_cached_address_txs(&self, address: &Felt) -> Vec<AddressTxSummary> {
        let db = match self.db.get() {
            Ok(db) => db,
            Err(_) => return Vec::new(),
        };
        let addr_hex = format!("{:#x}", address);
        let mut stmt =
            match db.prepare("SELECT data FROM address_txs WHERE address = ?1 ORDER BY tx_index") {
                Ok(s) => s,
                Err(_) => return Vec::new(),
            };
        let rows = match stmt.query_map(params![addr_hex], |row| row.get::<_, String>(0)) {
            Ok(r) => r,
            Err(_) => return Vec::new(),
        };
        rows.filter_map(|r| r.ok())
            .filter_map(|json| serde_json::from_str(&json).ok())
            .collect()
    }

    fn save_address_txs(&self, address: &Felt, txs: &[AddressTxSummary]) {
        let pool = self.db.clone();
        let addr_hex = format!("{:#x}", address);
        let rows: Vec<(i64, String)> = txs
            .iter()
            .enumerate()
            .filter_map(|(i, tx)| serde_json::to_string(tx).ok().map(|j| (i as i64, j)))
            .collect();
        Self::dispatch_write(move || {
            if let Ok(mut db) = pool.get() {
                let tx_db = match db.transaction() {
                    Ok(t) => t,
                    Err(e) => {
                        warn!(error = %e, "save_address_txs: begin transaction failed");
                        return;
                    }
                };
                let _ = tx_db.execute(
                    "DELETE FROM address_txs WHERE address = ?1",
                    params![&addr_hex],
                );
                for (i, json) in &rows {
                    let _ = tx_db.execute(
                        "INSERT OR REPLACE INTO address_txs (address, tx_index, data) VALUES (?1, ?2, ?3)",
                        params![&addr_hex, i, json],
                    );
                }
                if let Err(e) = tx_db.commit() {
                    warn!(error = %e, "save_address_txs: commit failed");
                }
            }
        });
    }

    fn load_cached_address_calls(&self, address: &Felt) -> Vec<ContractCallSummary> {
        let db = match self.db.get() {
            Ok(db) => db,
            Err(_) => return Vec::new(),
        };
        let addr_hex = format!("{:#x}", address);
        let mut stmt = match db
            .prepare("SELECT data FROM address_calls WHERE address = ?1 ORDER BY block_number DESC")
        {
            Ok(s) => s,
            Err(_) => return Vec::new(),
        };
        let rows = match stmt.query_map(params![addr_hex], |row| row.get::<_, String>(0)) {
            Ok(r) => r,
            Err(_) => return Vec::new(),
        };
        rows.filter_map(|r| r.ok())
            .filter_map(|json| serde_json::from_str(&json).ok())
            .collect()
    }

    fn save_address_calls(&self, address: &Felt, calls: &[ContractCallSummary]) {
        let pool = self.db.clone();
        let addr_hex = format!("{:#x}", address);
        let rows: Vec<(String, i64, String)> = calls
            .iter()
            .filter_map(|c| {
                serde_json::to_string(c)
                    .ok()
                    .map(|j| (format!("{:#x}", c.tx_hash), c.block_number as i64, j))
            })
            .collect();
        debug!(address = %addr_hex, rows = rows.len(), "save_address_calls: upsert");
        Self::dispatch_write(move || {
            if let Ok(mut db) = pool.get() {
                let tx = match db.transaction() {
                    Ok(t) => t,
                    Err(e) => {
                        warn!(error = %e, "save_address_calls: begin transaction failed");
                        return;
                    }
                };
                {
                    let mut stmt = match tx.prepare_cached(
                        "INSERT OR REPLACE INTO address_calls (address, tx_hash, block_number, data) VALUES (?1, ?2, ?3, ?4)",
                    ) {
                        Ok(s) => s,
                        Err(e) => {
                            warn!(error = %e, "save_address_calls: prepare failed");
                            return;
                        }
                    };
                    for (hash, block, json) in &rows {
                        let _ = stmt.execute(params![&addr_hex, hash, block, json]);
                    }
                }
                if let Err(e) = tx.commit() {
                    warn!(error = %e, "save_address_calls: commit failed");
                }
            }
        });
    }

    fn load_call_scanned_ranges(&self, address: &Felt) -> Vec<(u64, u64)> {
        self.load_scanned_ranges("address_call_scanned_ranges", address)
    }

    fn add_call_scanned_range(&self, address: &Felt, lo: u64, hi: u64) {
        self.add_scanned_range("address_call_scanned_ranges", address, lo, hi);
    }

    fn load_transfer_scanned_ranges(&self, address: &Felt) -> Vec<(u64, u64)> {
        self.load_scanned_ranges("address_transfer_scanned_ranges", address)
    }

    fn add_transfer_scanned_range(&self, address: &Felt, lo: u64, hi: u64) {
        self.add_scanned_range("address_transfer_scanned_ranges", address, lo, hi);
    }

    fn load_cached_transfers(&self, address: &Felt) -> Vec<TokenTransfer> {
        let db = match self.db.get() {
            Ok(db) => db,
            Err(_) => return Vec::new(),
        };
        let addr_hex = format!("{:#x}", address);
        let mut stmt = match db.prepare(
            "SELECT data FROM address_transfers WHERE address = ?1 ORDER BY block_number DESC",
        ) {
            Ok(s) => s,
            Err(_) => return Vec::new(),
        };
        let rows = match stmt.query_map(params![addr_hex], |row| row.get::<_, String>(0)) {
            Ok(r) => r,
            Err(_) => return Vec::new(),
        };
        let mut out: Vec<TokenTransfer> = rows
            .filter_map(|r| r.ok())
            .filter_map(|json| serde_json::from_str(&json).ok())
            .collect();
        out.sort_by(TokenTransfer::cmp_newest_first);
        out
    }

    fn save_transfers(&self, address: &Felt, rows: &[TokenTransfer]) {
        let pool = self.db.clone();
        let addr_hex = format!("{:#x}", address);
        let encoded: Vec<(String, i64, i64, String)> = rows
            .iter()
            .filter_map(|t| {
                serde_json::to_string(t).ok().map(|j| {
                    (
                        format!("{:#x}", t.tx_hash),
                        t.event_index as i64,
                        t.block_number as i64,
                        j,
                    )
                })
            })
            .collect();
        Self::dispatch_write(move || {
            let Ok(mut db) = pool.get() else {
                warn!("save_transfers: pool get failed");
                return;
            };
            Self::retry_locked("save_transfers", || {
                let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
                {
                    let mut stmt = tx.prepare_cached(
                        "INSERT OR REPLACE INTO address_transfers \
                         (address, tx_hash, event_index, block_number, data) VALUES (?1, ?2, ?3, ?4, ?5)",
                    )?;
                    for (hash, idx, block, json) in &encoded {
                        stmt.execute(params![&addr_hex, hash, idx, block, json])?;
                    }
                }
                tx.commit()
            });
        });
    }

    fn load_cached_meta_txs(&self, address: &Felt) -> Vec<MetaTxIntenderSummary> {
        let db = match self.db.get() {
            Ok(db) => db,
            Err(_) => return Vec::new(),
        };
        let addr_hex = format!("{:#x}", address);
        let mut stmt = match db.prepare(
            "SELECT data FROM address_meta_txs WHERE address = ?1 ORDER BY block_number DESC",
        ) {
            Ok(s) => s,
            Err(_) => return Vec::new(),
        };
        let rows = match stmt.query_map(params![addr_hex], |row| row.get::<_, String>(0)) {
            Ok(r) => r,
            Err(_) => return Vec::new(),
        };
        rows.filter_map(|r| r.ok())
            .filter_map(|json| serde_json::from_str(&json).ok())
            .collect()
    }

    fn save_meta_txs(&self, address: &Felt, txs: &[MetaTxIntenderSummary]) {
        if let Ok(mut db) = self.db.get() {
            let addr_hex = format!("{:#x}", address);
            let tx_db = match db.transaction() {
                Ok(t) => t,
                Err(e) => {
                    warn!(error = %e, "save_meta_txs: begin transaction failed");
                    return;
                }
            };
            for tx in txs {
                if let Ok(json) = serde_json::to_string(tx) {
                    let hash_hex = format!("{:#x}", tx.hash);
                    let _ = tx_db.execute(
                        "INSERT OR REPLACE INTO address_meta_txs \
                         (address, tx_hash, block_number, data) VALUES (?1, ?2, ?3, ?4)",
                        params![addr_hex, hash_hex, tx.block_number as i64, json],
                    );
                }
            }
            if let Err(e) = tx_db.commit() {
                warn!(error = %e, "save_meta_txs: commit failed");
            }
        }
    }

    fn load_cached_activity_range(&self, address: &Felt) -> Option<(u64, u64)> {
        self.load_cached_activity_range_with_count(address)
            .map(|(min, max, _count)| (min, max))
    }

    fn load_cached_activity_range_with_count(&self, address: &Felt) -> Option<(u64, u64, u64)> {
        let db = self.db.get().ok()?;
        let addr_hex = format!("{:#x}", address);
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .ok()?
            .as_secs() as i64;
        // Activity range is considered fresh for 1 hour
        let cutoff = now - 3600;
        let mut stmt = db
            .prepare(
                "SELECT min_block, max_block, event_count FROM address_activity \
                 WHERE address = ?1 AND updated_at > ?2",
            )
            .ok()?;
        stmt.query_row(params![addr_hex, cutoff], |row| {
            let min: i64 = row.get(0)?;
            let max: i64 = row.get(1)?;
            let count: i64 = row.get(2)?;
            Ok((min as u64, max as u64, count as u64))
        })
        .ok()
    }

    fn load_cached_activity_range_any_age(&self, address: &Felt) -> Option<(u64, u64, u64)> {
        let db = self.db.get().ok()?;
        let addr_hex = format!("{:#x}", address);
        let mut stmt = db
            .prepare(
                "SELECT min_block, max_block, event_count FROM address_activity \
                 WHERE address = ?1",
            )
            .ok()?;
        stmt.query_row(params![addr_hex], |row| {
            let min: i64 = row.get(0)?;
            let max: i64 = row.get(1)?;
            let count: i64 = row.get(2)?;
            Ok((min as u64, max as u64, count as u64))
        })
        .ok()
    }

    fn save_activity_range(&self, address: &Felt, min_block: u64, max_block: u64) {
        self.save_activity_range_with_count(address, min_block, max_block, 0);
    }

    fn save_activity_range_with_count(
        &self,
        address: &Felt,
        min_block: u64,
        max_block: u64,
        event_count: u64,
    ) {
        if let Ok(db) = self.db.get() {
            let addr_hex = format!("{:#x}", address);
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs() as i64;
            // Merge: expand existing range, keep max event count
            let existing = db
                .prepare(
                    "SELECT min_block, max_block, event_count FROM address_activity WHERE address = ?1",
                )
                .ok()
                .and_then(|mut s| {
                    s.query_row(params![addr_hex], |row| {
                        let min: i64 = row.get(0)?;
                        let max: i64 = row.get(1)?;
                        let count: i64 = row.get(2)?;
                        Ok((min as u64, max as u64, count as u64))
                    })
                    .ok()
                });
            let (final_min, final_max, final_count) =
                if let Some((old_min, old_max, old_count)) = existing {
                    (
                        old_min.min(min_block),
                        old_max.max(max_block),
                        old_count.max(event_count),
                    )
                } else {
                    (min_block, max_block, event_count)
                };
            let _ = db.execute(
                "INSERT OR REPLACE INTO address_activity (address, min_block, max_block, event_count, updated_at) \
                 VALUES (?1, ?2, ?3, ?4, ?5)",
                params![addr_hex, final_min as i64, final_max as i64, final_count as i64, now],
            );
        }
    }

    async fn call_contract(
        &self,
        contract_address: Felt,
        selector: Felt,
        calldata: Vec<Felt>,
    ) -> Result<Vec<Felt>> {
        // Contract calls are dynamic (balances change) — pass through
        self.upstream
            .call_contract(contract_address, selector, calldata)
            .await
    }

    async fn batch_call_contracts(
        &self,
        calls: Vec<(Felt, Felt, Vec<Felt>)>,
    ) -> Vec<Result<Vec<Felt>>> {
        // Pass through so the upstream's batched implementation is used —
        // the default trait impl would silently run each call serially.
        self.upstream.batch_call_contracts(calls).await
    }

    async fn get_storage_at(&self, contract: Felt, key: Felt, block: Option<u64>) -> Result<Felt> {
        // Pass through. Without this override the trait default returns a
        // "not implemented" error, which would silently break the privacy
        // sync's RPC fallback when the cached source is in front of RPC.
        self.upstream.get_storage_at(contract, key, block).await
    }

    async fn batch_get_storage_at(
        &self,
        contract: Felt,
        keys: &[Felt],
        block: Option<u64>,
    ) -> Vec<Result<Felt>> {
        // Pass through to the upstream's batched JSON-RPC implementation.
        self.upstream
            .batch_get_storage_at(contract, keys, block)
            .await
    }

    async fn get_transfer_events(
        &self,
        address: Felt,
        from_block: u64,
        to_block: u64,
    ) -> Result<Vec<TokenTransfer>> {
        // Windowed scans are persisted by the caller via `save_transfers`.
        self.upstream
            .get_transfer_events(address, from_block, to_block)
            .await
    }

    async fn get_contract_events(
        &self,
        address: Felt,
        from_block: Option<u64>,
        to_block: Option<u64>,
        limit: usize,
    ) -> Result<Vec<SnEvent>> {
        // Bounded pagination: skip cache merge (see `get_events_for_address`).
        if to_block.is_some() {
            return self
                .upstream
                .get_contract_events(address, from_block, to_block, limit)
                .await;
        }

        // Incremental caching for contract events (all events, no key filter)
        let cached = self.load_contract_events(&address);

        let fetch_from = if !cached.is_empty() && from_block.is_none() {
            let max_block = cached.iter().map(|e| e.block_number).max().unwrap_or(0);
            Some(max_block + 1)
        } else {
            from_block
        };

        let new_events = match self
            .upstream
            .get_contract_events(address, fetch_from, None, limit)
            .await
        {
            Ok(events) => events,
            Err(e) => {
                warn!(address = %format!("{:#x}", address), error = %e, "RPC error fetching events, using cache only");
                if cached.is_empty() {
                    return Err(e);
                }
                vec![]
            }
        };

        let mut merged = Self::merge_events_dedup(new_events, cached);

        merged.sort_by(|a, b| b.block_number.cmp(&a.block_number));
        self.save_contract_events(&address, &merged);
        merged.truncate(limit);

        Ok(merged)
    }

    fn load_cached_deploy_info(&self, address: &Felt) -> Option<(Felt, u64, Option<Felt>)> {
        self.get_cached_deploy_info(address)
    }

    fn save_deploy_info(
        &self,
        address: &Felt,
        tx_hash: &Felt,
        block: u64,
        deployer: Option<&Felt>,
    ) {
        self.cache_deploy_info(address, tx_hash, block, deployer);
    }

    fn load_cached_class_history(
        &self,
        address: &Felt,
    ) -> Vec<crate::data::pathfinder::ClassHashEntry> {
        self.get_cached_class_history(address)
    }

    fn save_class_history(
        &self,
        address: &Felt,
        entries: &[crate::data::pathfinder::ClassHashEntry],
    ) {
        self.cache_class_history(address, entries);
    }

    fn load_class_history_max_block(&self, address: &Felt) -> Option<u64> {
        self.get_cached_class_history_max_block(address)
    }

    fn save_class_history_max_block(&self, address: &Felt, block: u64) {
        self.cache_class_history_max_block(address, block);
    }

    fn load_cached_nonce(&self, address: &Felt) -> Option<(Felt, u64)> {
        self.get_cached_nonce_info(address)
    }

    fn save_cached_nonce(&self, address: &Felt, nonce: &Felt, block: u64) {
        self.cache_nonce_info(address, nonce, block);
    }

    fn load_cached_class_hash(&self, address: &Felt) -> Option<Felt> {
        self.get_cached_class_hash(address).map(|(ch, _)| ch)
    }

    fn load_search_progress(&self, address: &Felt, filter_kind: FilterKind) -> Option<(u64, u64)> {
        self.get_cached_search_progress(address, filter_kind)
    }

    fn save_search_progress(
        &self,
        address: &Felt,
        filter_kind: FilterKind,
        min_block: u64,
        max_block: u64,
    ) {
        self.cache_search_progress(address, filter_kind, min_block, max_block);
    }

    fn load_activity_total(&self, address: &Felt) -> Option<u64> {
        self.get_cached_activity_total(address)
    }

    fn save_activity_total(&self, address: &Felt, total: u64) {
        self.cache_activity_total(address, total);
    }

    fn load_address_events(&self, address: &Felt) -> Vec<SnEvent> {
        self.get_cached_address_events(address)
    }

    fn merge_address_events(&self, address: &Felt, new_events: &[SnEvent]) -> Vec<SnEvent> {
        self.merge_address_events_impl(address, new_events)
    }

    fn append_address_events(&self, address: &Felt, events: &[SnEvent]) {
        self.append_address_events_impl(address, events);
    }

    async fn get_recent_blocks(&self, count: usize) -> Result<Vec<SnBlock>> {
        // Fetch from upstream (recent blocks change)
        let blocks = self.upstream.get_recent_blocks(count).await?;
        // Cache each block
        for block in &blocks {
            self.cache_block(block);
        }
        Ok(blocks)
    }

    fn load_cached_class_declaration(&self, class_hash: &Felt) -> Option<ClassDeclareInfo> {
        let db = self.db.get().ok()?;
        let hash_hex = format!("{:#x}", class_hash);
        let mut stmt = db
            .prepare(
                "SELECT tx_hash, sender, block_number, timestamp \
                 FROM class_declarations WHERE class_hash = ?1",
            )
            .ok()?;
        stmt.query_row(params![hash_hex], |row| {
            let tx_hash_s: String = row.get(0)?;
            let sender_s: String = row.get(1)?;
            let block_number: i64 = row.get(2)?;
            let timestamp: i64 = row.get(3)?;
            Ok((tx_hash_s, sender_s, block_number as u64, timestamp as u64))
        })
        .ok()
        .and_then(|(tx_hash_s, sender_s, block_number, timestamp)| {
            let tx_hash = Felt::from_hex(&tx_hash_s).ok()?;
            let sender = Felt::from_hex(&sender_s).ok()?;
            Some(ClassDeclareInfo {
                tx_hash,
                sender,
                block_number,
                timestamp,
            })
        })
    }

    fn save_class_declaration(&self, class_hash: &Felt, info: &ClassDeclareInfo) {
        if let Ok(db) = self.db.get() {
            let hash_hex = format!("{:#x}", class_hash);
            let tx_hex = format!("{:#x}", info.tx_hash);
            let sender_hex = format!("{:#x}", info.sender);
            let _ = db.execute(
                "INSERT OR REPLACE INTO class_declarations \
                 (class_hash, tx_hash, sender, block_number, timestamp) \
                 VALUES (?1, ?2, ?3, ?4, ?5)",
                params![
                    hash_hex,
                    tx_hex,
                    sender_hex,
                    info.block_number as i64,
                    info.timestamp as i64,
                ],
            );
        }
    }

    fn load_cached_class_contracts(&self, class_hash: &Felt) -> Option<Vec<ClassContractEntry>> {
        let db = self.db.get().ok()?;
        let hash_hex = format!("{:#x}", class_hash);
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .ok()?
            .as_secs() as i64;
        // Contracts-by-class is fresh for 1 hour; stale entries return None so
        // the caller re-fetches. Without this TTL the list would miss new
        // deploys performed against the class after the first cache write.
        let cutoff = now - 3600;
        let fetched_at: i64 = db
            .prepare("SELECT fetched_at FROM class_contracts_meta WHERE class_hash = ?1")
            .ok()?
            .query_row(params![&hash_hex], |row| row.get(0))
            .ok()?;
        if fetched_at <= cutoff {
            return None;
        }
        let mut stmt = db
            .prepare(
                "SELECT contract_address, block_number FROM class_contracts \
                 WHERE class_hash = ?1 ORDER BY block_number DESC",
            )
            .ok()?;
        let rows = stmt
            .query_map(params![hash_hex], |row| {
                let addr_s: String = row.get(0)?;
                let block_number: i64 = row.get(1)?;
                Ok((addr_s, block_number as u64))
            })
            .ok()?;
        let mut out = Vec::new();
        for row in rows.flatten() {
            if let Ok(address) = Felt::from_hex(&row.0) {
                out.push(ClassContractEntry {
                    address,
                    block_number: row.1,
                });
            }
        }
        Some(out)
    }

    fn save_class_contracts(&self, class_hash: &Felt, contracts: &[ClassContractEntry]) {
        if let Ok(mut db) = self.db.get() {
            let hash_hex = format!("{:#x}", class_hash);
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs() as i64;
            let tx = match db.transaction() {
                Ok(t) => t,
                Err(e) => {
                    warn!(error = %e, "save_class_contracts: begin transaction failed");
                    return;
                }
            };
            // Replace: drop prior rows, insert the new list atomically.
            let _ = tx.execute(
                "DELETE FROM class_contracts WHERE class_hash = ?1",
                params![hash_hex],
            );
            for entry in contracts {
                let contract_hex = format!("{:#x}", entry.address);
                let _ = tx.execute(
                    "INSERT OR REPLACE INTO class_contracts \
                     (class_hash, contract_address, block_number) VALUES (?1, ?2, ?3)",
                    params![hash_hex, contract_hex, entry.block_number as i64],
                );
            }
            let _ = tx.execute(
                "INSERT OR REPLACE INTO class_contracts_meta (class_hash, fetched_at) \
                 VALUES (?1, ?2)",
                params![hash_hex, now],
            );
            if let Err(e) = tx.commit() {
                warn!(error = %e, "save_class_contracts: commit failed");
            }
        }
    }

    fn load_token_metadata(&self) -> Vec<(Felt, crate::data::token_metadata::TokenMeta)> {
        let db = match self.db.get() {
            Ok(db) => db,
            Err(_) => return Vec::new(),
        };
        let mut stmt = match db.prepare("SELECT address, symbol, decimals FROM token_metadata") {
            Ok(s) => s,
            Err(_) => return Vec::new(),
        };
        let rows = match stmt.query_map([], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, i64>(2)?,
            ))
        }) {
            Ok(r) => r,
            Err(_) => return Vec::new(),
        };
        rows.filter_map(|r| r.ok())
            .filter_map(|(addr, sym, dec)| {
                let felt = Felt::from_hex(&addr).ok()?;
                if !(0..=255).contains(&dec) {
                    return None;
                }
                Some((
                    felt,
                    crate::data::token_metadata::TokenMeta {
                        symbol: sym,
                        decimals: dec as u8,
                    },
                ))
            })
            .collect()
    }

    fn save_token_metadata(&self, address: &Felt, meta: &crate::data::token_metadata::TokenMeta) {
        if let Ok(db) = self.db.get() {
            let addr_hex = format!("{:#x}", address);
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs() as i64)
                .unwrap_or(0);
            if let Err(e) = db.execute(
                "INSERT OR REPLACE INTO token_metadata
                    (address, symbol, decimals, fetched_at)
                 VALUES (?1, ?2, ?3, ?4)",
                params![addr_hex, meta.symbol, meta.decimals as i64, now],
            ) {
                warn!(error = %e, "save_token_metadata failed");
            }
        }
    }

    fn load_private_notes(
        &self,
    ) -> (
        Vec<crate::decode::privacy_sync::DecryptedNote>,
        Vec<(Felt, Felt)>,
    ) {
        use crate::decode::privacy_sync::{DecryptedNote, NoteDirection};
        let db = match self.db.get() {
            Ok(db) => db,
            Err(_) => return (Vec::new(), Vec::new()),
        };

        let notes: Vec<DecryptedNote> = match db.prepare(
            "SELECT note_id, user, counterparty, direction, token, amount,
                    channel_idx, subchannel_idx, note_idx, spent, block_number
             FROM private_notes",
        ) {
            Ok(mut stmt) => match stmt.query_map([], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, String>(3)?,
                    row.get::<_, String>(4)?,
                    row.get::<_, String>(5)?,
                    row.get::<_, i64>(6)?,
                    row.get::<_, i64>(7)?,
                    row.get::<_, i64>(8)?,
                    row.get::<_, i64>(9)?,
                    row.get::<_, i64>(10)?,
                ))
            }) {
                Ok(rows) => rows
                    .filter_map(|r| r.ok())
                    .filter_map(|(nid, u, cp, dir, tok, amt, ch, sch, ni, sp, bn)| {
                        let direction = match dir.as_str() {
                            "incoming" => NoteDirection::Incoming,
                            "outgoing" => NoteDirection::Outgoing,
                            _ => return None,
                        };
                        Some(DecryptedNote {
                            note_id: Felt::from_hex(&nid).ok()?,
                            user: Felt::from_hex(&u).ok()?,
                            counterparty: Felt::from_hex(&cp).ok()?,
                            direction,
                            token: Felt::from_hex(&tok).ok()?,
                            amount: amt.parse::<u128>().ok()?,
                            channel_idx: ch.max(0) as u64,
                            subchannel_idx: sch.max(0) as u64,
                            note_idx: ni.max(0) as u64,
                            spent: sp != 0,
                            block_number: bn.max(0) as u64,
                        })
                    })
                    .collect(),
                Err(_) => Vec::new(),
            },
            Err(_) => Vec::new(),
        };

        let nullifiers: Vec<(Felt, Felt)> =
            match db.prepare("SELECT nullifier, note_id FROM private_nullifiers") {
                Ok(mut stmt) => match stmt.query_map([], |row| {
                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
                }) {
                    Ok(rows) => rows
                        .filter_map(|r| r.ok())
                        .filter_map(|(nul, nid)| {
                            Some((Felt::from_hex(&nul).ok()?, Felt::from_hex(&nid).ok()?))
                        })
                        .collect(),
                    Err(_) => Vec::new(),
                },
                Err(_) => Vec::new(),
            };

        (notes, nullifiers)
    }

    fn load_private_notes_for_user(
        &self,
        user: &Felt,
    ) -> (
        Vec<crate::decode::privacy_sync::DecryptedNote>,
        Vec<(Felt, Felt)>,
    ) {
        use crate::decode::privacy_sync::{DecryptedNote, NoteDirection};
        let db = match self.db.get() {
            Ok(db) => db,
            Err(_) => return (Vec::new(), Vec::new()),
        };
        let user_hex = format!("{:#x}", user);

        let notes: Vec<DecryptedNote> = match db.prepare(
            "SELECT note_id, user, counterparty, direction, token, amount,
                    channel_idx, subchannel_idx, note_idx, spent, block_number
             FROM private_notes WHERE user = ?1",
        ) {
            Ok(mut stmt) => match stmt.query_map(params![user_hex], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, String>(3)?,
                    row.get::<_, String>(4)?,
                    row.get::<_, String>(5)?,
                    row.get::<_, i64>(6)?,
                    row.get::<_, i64>(7)?,
                    row.get::<_, i64>(8)?,
                    row.get::<_, i64>(9)?,
                    row.get::<_, i64>(10)?,
                ))
            }) {
                Ok(rows) => rows
                    .filter_map(|r| r.ok())
                    .filter_map(|(nid, u, cp, dir, tok, amt, ch, sch, ni, sp, bn)| {
                        let direction = match dir.as_str() {
                            "incoming" => NoteDirection::Incoming,
                            "outgoing" => NoteDirection::Outgoing,
                            _ => return None,
                        };
                        Some(DecryptedNote {
                            note_id: Felt::from_hex(&nid).ok()?,
                            user: Felt::from_hex(&u).ok()?,
                            counterparty: Felt::from_hex(&cp).ok()?,
                            direction,
                            token: Felt::from_hex(&tok).ok()?,
                            amount: amt.parse::<u128>().ok()?,
                            channel_idx: ch.max(0) as u64,
                            subchannel_idx: sch.max(0) as u64,
                            note_idx: ni.max(0) as u64,
                            spent: sp != 0,
                            block_number: bn.max(0) as u64,
                        })
                    })
                    .collect(),
                Err(_) => Vec::new(),
            },
            Err(_) => Vec::new(),
        };

        let nullifiers: Vec<(Felt, Felt)> =
            match db.prepare("SELECT nullifier, note_id FROM private_nullifiers WHERE user = ?1") {
                Ok(mut stmt) => match stmt.query_map(params![user_hex], |row| {
                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
                }) {
                    Ok(rows) => rows
                        .filter_map(|r| r.ok())
                        .filter_map(|(nul, nid)| {
                            Some((Felt::from_hex(&nul).ok()?, Felt::from_hex(&nid).ok()?))
                        })
                        .collect(),
                    Err(_) => Vec::new(),
                },
                Err(_) => Vec::new(),
            };

        (notes, nullifiers)
    }

    fn save_private_notes_for_user(
        &self,
        user: &Felt,
        notes: &[crate::decode::privacy_sync::DecryptedNote],
        nullifiers: &[(Felt, Felt)],
        last_synced_block: u64,
    ) {
        use crate::decode::privacy_sync::NoteDirection;
        let mut db = match self.db.get() {
            Ok(db) => db,
            Err(e) => {
                warn!(error = %e, "save_private_notes_for_user: failed to get db connection");
                return;
            }
        };
        let user_hex = format!("{:#x}", user);
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0);
        // SQLite INTEGER is i64 — cap to keep us off the rusqlite u64 sentinel
        // bug (per project memory).
        let last_block_i64 = last_synced_block.min(i64::MAX as u64) as i64;

        let tx = match db.transaction_with_behavior(TransactionBehavior::Immediate) {
            Ok(t) => t,
            Err(e) => {
                warn!(error = %e, "save_private_notes_for_user: begin tx failed");
                return;
            }
        };

        if let Err(e) = tx.execute(
            "DELETE FROM private_notes WHERE user = ?1",
            params![user_hex],
        ) {
            warn!(error = %e, "save_private_notes_for_user: delete notes failed");
            return;
        }
        if let Err(e) = tx.execute(
            "DELETE FROM private_nullifiers WHERE user = ?1",
            params![user_hex],
        ) {
            warn!(error = %e, "save_private_notes_for_user: delete nullifiers failed");
            return;
        }

        for n in notes {
            let dir = match n.direction {
                NoteDirection::Incoming => "incoming",
                NoteDirection::Outgoing => "outgoing",
            };
            if let Err(e) = tx.execute(
                "INSERT OR REPLACE INTO private_notes
                    (note_id, user, counterparty, direction, token, amount,
                     channel_idx, subchannel_idx, note_idx, spent, block_number)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
                params![
                    format!("{:#x}", n.note_id),
                    format!("{:#x}", n.user),
                    format!("{:#x}", n.counterparty),
                    dir,
                    format!("{:#x}", n.token),
                    n.amount.to_string(),
                    n.channel_idx.min(i64::MAX as u64) as i64,
                    n.subchannel_idx.min(i64::MAX as u64) as i64,
                    n.note_idx.min(i64::MAX as u64) as i64,
                    if n.spent { 1_i64 } else { 0_i64 },
                    n.block_number.min(i64::MAX as u64) as i64,
                ],
            ) {
                warn!(error = %e, "save_private_notes_for_user: insert note failed");
                return;
            }
        }

        for (nul, nid) in nullifiers {
            if let Err(e) = tx.execute(
                "INSERT OR REPLACE INTO private_nullifiers
                    (nullifier, note_id, user)
                 VALUES (?1, ?2, ?3)",
                params![format!("{:#x}", nul), format!("{:#x}", nid), user_hex],
            ) {
                warn!(error = %e, "save_private_notes_for_user: insert nullifier failed");
                return;
            }
        }

        if let Err(e) = tx.execute(
            "INSERT OR REPLACE INTO private_notes_sync
                (user, last_synced_block, synced_at)
             VALUES (?1, ?2, ?3)",
            params![user_hex, last_block_i64, now],
        ) {
            warn!(error = %e, "save_private_notes_for_user: upsert sync row failed");
            return;
        }

        if let Err(e) = tx.commit() {
            warn!(error = %e, "save_private_notes_for_user: commit failed");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::DataSource;
    use starknet::core::types::{ContractClass, TransactionTrace};

    /// Minimal upstream stub — the search_progress / activity_total tests only
    /// touch sync cache-local SQL, so the async upstream methods never fire.
    struct NullUpstream;

    #[async_trait]
    impl DataSource for NullUpstream {
        async fn get_latest_block_number(&self) -> Result<u64> {
            unimplemented!()
        }
        async fn get_block(&self, _number: u64) -> Result<SnBlock> {
            unimplemented!()
        }
        async fn get_block_by_hash(&self, _hash: Felt) -> Result<u64> {
            unimplemented!()
        }
        async fn get_block_with_txs(&self, _number: u64) -> Result<(SnBlock, Vec<SnTransaction>)> {
            unimplemented!()
        }
        async fn get_transaction(&self, _hash: Felt) -> Result<SnTransaction> {
            unimplemented!()
        }
        async fn get_receipt(&self, _hash: Felt) -> Result<SnReceipt> {
            unimplemented!()
        }
        async fn get_nonce(&self, _address: Felt) -> Result<Felt> {
            unimplemented!()
        }
        async fn get_class_hash(&self, _address: Felt) -> Result<Felt> {
            unimplemented!()
        }
        async fn get_class(&self, _class_hash: Felt) -> Result<ContractClass> {
            unimplemented!()
        }
        async fn get_trace(&self, _hash: Felt) -> Result<TransactionTrace> {
            unimplemented!()
        }
        async fn get_recent_blocks(&self, _count: usize) -> Result<Vec<SnBlock>> {
            unimplemented!()
        }
        async fn get_events_for_address(
            &self,
            _address: Felt,
            _from_block: Option<u64>,
            _to_block: Option<u64>,
            _limit: usize,
        ) -> Result<Vec<SnEvent>> {
            unimplemented!()
        }
        async fn call_contract(
            &self,
            _contract_address: Felt,
            _selector: Felt,
            _calldata: Vec<Felt>,
        ) -> Result<Vec<Felt>> {
            unimplemented!()
        }
    }

    fn new_cache() -> (CachingDataSource, tempfile::TempDir) {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("cache.db");
        let ds = CachingDataSource::new(Arc::new(NullUpstream), &path).expect("open cache");
        (ds, dir)
    }

    #[test]
    fn activity_total_roundtrip() {
        let (ds, _d) = new_cache();
        let addr = Felt::from_hex("0x1234").unwrap();

        assert_eq!(ds.load_activity_total(&addr), None);

        ds.save_activity_total(&addr, 11400);
        assert_eq!(ds.load_activity_total(&addr), Some(11400));

        // Update is idempotent and overwrites.
        ds.save_activity_total(&addr, 11450);
        assert_eq!(ds.load_activity_total(&addr), Some(11450));
    }

    #[test]
    fn save_search_progress_preserves_total_known() {
        // Regression test: before this change, INSERT OR REPLACE in
        // cache_search_progress would null out total_known when a later event
        // scan extended the range. Now it must survive.
        let (ds, _d) = new_cache();
        let addr = Felt::from_hex("0xabcd").unwrap();

        ds.save_activity_total(&addr, 11400);
        // Seed an initial scanned range.
        ds.save_search_progress(&addr, FilterKind::Unkeyed, 3_000_000, 8_900_000);
        assert_eq!(ds.load_activity_total(&addr), Some(11400));

        // Extending the range (e.g. fetching newer events) must keep total_known.
        ds.save_search_progress(&addr, FilterKind::Unkeyed, 3_000_000, 8_941_000);
        assert_eq!(ds.load_activity_total(&addr), Some(11400));
        assert_eq!(
            ds.load_search_progress(&addr, FilterKind::Unkeyed),
            Some((3_000_000, 8_941_000))
        );
    }

    #[test]
    fn call_scanned_ranges_persist_and_coalesce() {
        let (ds, _d) = new_cache();
        let addr = Felt::from_hex("0xca115").unwrap();

        assert!(ds.load_call_scanned_ranges(&addr).is_empty());

        ds.add_call_scanned_range(&addr, 1_000_000, 1_100_000);
        assert_eq!(
            ds.load_call_scanned_ranges(&addr),
            vec![(1_000_000, 1_100_000)]
        );

        // Overlapping range coalesces into one interval.
        ds.add_call_scanned_range(&addr, 1_050_000, 1_200_000);
        assert_eq!(
            ds.load_call_scanned_ranges(&addr),
            vec![(1_000_000, 1_200_000)]
        );

        // Disjoint range stays separate, sorted ascending.
        ds.add_call_scanned_range(&addr, 2_000_000, 2_100_000);
        assert_eq!(
            ds.load_call_scanned_ranges(&addr),
            vec![(1_000_000, 1_200_000), (2_000_000, 2_100_000)]
        );

        // Other addresses are isolated.
        let other = Felt::from_hex("0xbeef").unwrap();
        assert!(ds.load_call_scanned_ranges(&other).is_empty());
    }

    #[test]
    fn search_progress_merges_ranges() {
        let (ds, _d) = new_cache();
        let addr = Felt::from_hex("0xbeef").unwrap();

        ds.save_search_progress(&addr, FilterKind::Unkeyed, 100, 200);
        ds.save_search_progress(&addr, FilterKind::Unkeyed, 50, 150);
        // Min shrinks, max doesn't regress.
        assert_eq!(
            ds.load_search_progress(&addr, FilterKind::Unkeyed),
            Some((50, 200))
        );

        ds.save_search_progress(&addr, FilterKind::Unkeyed, 300, 400);
        // Max extends, min doesn't grow past the remembered floor.
        assert_eq!(
            ds.load_search_progress(&addr, FilterKind::Unkeyed),
            Some((50, 400))
        );
    }

    #[test]
    fn search_progress_split_by_filter_kind() {
        // Regression test for v6 migration: keyed and unkeyed coverage are
        // tracked independently. A keyed scan must not appear to cover the
        // unkeyed region (which would be a lie — keyed scans miss non-
        // TRANSACTION_EXECUTED events).
        let (ds, _d) = new_cache();
        let addr = Felt::from_hex("0xface").unwrap();

        // Record a wide keyed scan.
        ds.save_search_progress(&addr, FilterKind::Keyed, 1_000_000, 9_000_000);
        assert_eq!(
            ds.load_search_progress(&addr, FilterKind::Keyed),
            Some((1_000_000, 9_000_000))
        );
        // Unkeyed is still unrecorded — not satisfied by the keyed scan.
        assert_eq!(ds.load_search_progress(&addr, FilterKind::Unkeyed), None);

        // Recording an unkeyed scan does not disturb the keyed row.
        ds.save_search_progress(&addr, FilterKind::Unkeyed, 8_000_000, 9_000_000);
        assert_eq!(
            ds.load_search_progress(&addr, FilterKind::Unkeyed),
            Some((8_000_000, 9_000_000))
        );
        assert_eq!(
            ds.load_search_progress(&addr, FilterKind::Keyed),
            Some((1_000_000, 9_000_000))
        );
    }

    #[test]
    fn merge_events_dedup_drops_duplicates_preserves_fresh_first_order() {
        // Helper to build a minimal SnEvent fixture keyed by (tx, block, idx).
        fn ev(tx: u64, block: u64, idx: u64) -> SnEvent {
            SnEvent {
                from_address: Felt::ZERO,
                keys: Vec::new(),
                data: Vec::new(),
                transaction_hash: Felt::from(tx),
                block_number: block,
                event_index: idx,
            }
        }

        // Two fresh events; cached has one overlap (block 100 idx 0) plus
        // one strictly older event. Expected merged order: fresh first
        // (callers sort newest-first after this), then the unique cached one.
        let fresh = vec![ev(1, 100, 0), ev(2, 101, 0)];
        let cached = vec![ev(1, 100, 0), ev(3, 99, 0)];
        let merged = CachingDataSource::merge_events_dedup(fresh, cached);
        let keys: Vec<_> = merged
            .iter()
            .map(|e| (e.transaction_hash, e.block_number, e.event_index))
            .collect();
        assert_eq!(
            keys,
            vec![
                (Felt::from(1u64), 100, 0),
                (Felt::from(2u64), 101, 0),
                (Felt::from(3u64), 99, 0),
            ]
        );

        // Duplicates within `fresh` itself are also collapsed (defensive —
        // upstream sometimes returns the same event in overlapping pages).
        let fresh = vec![ev(1, 100, 0), ev(1, 100, 0), ev(2, 101, 0)];
        let merged = CachingDataSource::merge_events_dedup(fresh, vec![]);
        assert_eq!(merged.len(), 2);
    }

    fn call_row(hash: u64, block: u64, name: &str) -> ContractCallSummary {
        ContractCallSummary {
            tx_hash: Felt::from(hash),
            sender: Felt::from(0xABC_u64),
            function_name: name.into(),
            block_number: block,
            timestamp: 0,
            total_fee_fri: 0,
            status: "OK".into(),
            nonce: None,
            tip: 0,
            inner_targets: Vec::new(),
        }
    }

    #[test]
    fn address_calls_rekey_migration_and_upsert() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("cache.db");
        let addr = Felt::from(0x49d_u64);
        let addr_hex = format!("{:#x}", addr);
        {
            // Pre-migration shape: rows keyed by list position.
            let db = rusqlite::Connection::open(&path).unwrap();
            db.execute_batch(
                "CREATE TABLE address_calls (
                     address TEXT NOT NULL, call_index INTEGER NOT NULL, data TEXT NOT NULL,
                     PRIMARY KEY (address, call_index));",
            )
            .unwrap();
            let old = [
                call_row(1, 500, "a"),
                call_row(2, 900, "b"),
                call_row(3, 700, "c"),
            ];
            for (i, c) in old.iter().enumerate() {
                db.execute(
                    "INSERT INTO address_calls VALUES (?1, ?2, ?3)",
                    params![&addr_hex, i as i64, serde_json::to_string(c).unwrap()],
                )
                .unwrap();
            }
            db.execute(
                "INSERT INTO address_calls VALUES ('0x1', 0, 'not json')",
                [],
            )
            .unwrap();
        }

        let ds = CachingDataSource::new(Arc::new(NullUpstream), &path).expect("open + migrate");
        let blocks: Vec<u64> = ds
            .load_cached_address_calls(&addr)
            .iter()
            .map(|c| c.block_number)
            .collect();
        assert_eq!(blocks, vec![900, 700, 500]);
        assert!(ds.load_cached_address_calls(&Felt::from(1_u64)).is_empty());

        // Upsert: the touched hash is replaced, a new one added, the rest kept.
        ds.save_address_calls(&addr, &[call_row(1, 500, "a, x"), call_row(4, 100, "d")]);
        let after = ds.load_cached_address_calls(&addr);
        let name = |h: u64| {
            after
                .iter()
                .find(|c| c.tx_hash == Felt::from(h))
                .map(|c| c.function_name.clone())
        };
        assert_eq!(after.len(), 4);
        assert_eq!(name(1).as_deref(), Some("a, x"));
        assert_eq!(name(2).as_deref(), Some("b"));
        assert_eq!(name(4).as_deref(), Some("d"));
    }

    fn event(tx: u64, block: u64, idx: u64) -> SnEvent {
        SnEvent {
            from_address: Felt::from(0x10_u64),
            keys: vec![Felt::from(idx)],
            data: Vec::new(),
            transaction_hash: Felt::from(tx),
            block_number: block,
            event_index: idx,
        }
    }

    fn event_ids(events: &[SnEvent]) -> Vec<(u64, u64, u64)> {
        events
            .iter()
            .map(|e| {
                (
                    e.block_number,
                    crate::utils::felt_to_u64(&e.transaction_hash),
                    e.event_index,
                )
            })
            .collect()
    }

    #[test]
    fn merge_address_events_upserts_newest_first() {
        let (ds, _d) = new_cache();
        let addr = Felt::from(0x49d_u64);

        ds.merge_address_events(&addr, &[event(1, 100, 0), event(2, 300, 0)]);
        // Re-sending a cached event is a no-op; a new one lands in block order.
        let merged = ds.merge_address_events(&addr, &[event(2, 300, 0), event(3, 200, 1)]);
        assert_eq!(
            event_ids(&merged),
            vec![(300, 2, 0), (200, 3, 1), (100, 1, 0)]
        );
        // Two legs of one tx are distinct rows.
        ds.merge_address_events(&addr, &[event(3, 200, 0)]);
        assert_eq!(ds.load_address_events(&addr).len(), 4);
    }

    #[test]
    fn address_events_rekey_migration() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("cache.db");
        let addr = Felt::from(0x49d_u64);
        let addr_hex = format!("{:#x}", addr);
        {
            // Pre-migration shape: rows keyed by list position.
            let db = rusqlite::Connection::open(&path).unwrap();
            db.execute_batch(
                "CREATE TABLE address_events (
                     address TEXT NOT NULL, event_index INTEGER NOT NULL, data TEXT NOT NULL,
                     PRIMARY KEY (address, event_index));",
            )
            .unwrap();
            for (i, e) in [event(1, 900, 1), event(1, 900, 0), event(2, 500, 0)]
                .iter()
                .enumerate()
            {
                db.execute(
                    "INSERT INTO address_events VALUES (?1, ?2, ?3)",
                    params![&addr_hex, i as i64, serde_json::to_string(e).unwrap()],
                )
                .unwrap();
            }
            db.execute(
                "INSERT INTO address_events VALUES ('0x1', 0, 'not json')",
                [],
            )
            .unwrap();
        }

        let ds = CachingDataSource::new(Arc::new(NullUpstream), &path).expect("open + migrate");
        assert_eq!(
            event_ids(&ds.load_address_events(&addr)),
            vec![(900, 1, 1), (900, 1, 0), (500, 2, 0)]
        );
        assert!(ds.load_address_events(&Felt::from(1_u64)).is_empty());
    }

    /// Opens an external cache.db snapshot via env var `STARKTOP_TEST_CACHE_DB`
    /// and runs the migration. Used to verify v11 against a real production
    /// snapshot. Ignored by default — set the env var to invoke it.
    #[test]
    #[ignore]
    fn external_cache_migration_smoke() {
        let path = std::env::var("STARKTOP_TEST_CACHE_DB")
            .expect("set STARKTOP_TEST_CACHE_DB to a snapshot path");
        let p = std::path::PathBuf::from(path);
        let _ds = CachingDataSource::new(Arc::new(NullUpstream), &p).expect("open + migrate");
    }

    #[test]
    fn private_notes_roundtrip() {
        use crate::decode::privacy_sync::{DecryptedNote, NoteDirection};
        let (ds, _d) = new_cache();

        let user_a = Felt::from_hex("0xa11ce").unwrap();
        let user_b = Felt::from_hex("0xb0b").unwrap();
        let token_usdc = Felt::from_hex("0x53c9151").unwrap();
        let cp1 = Felt::from_hex("0xc1").unwrap();
        let cp2 = Felt::from_hex("0xc2").unwrap();

        // Pick an amount that exceeds u64 to verify u128 → TEXT round-trips
        // intact (per the project rule against u64 sentinels for SQLite).
        let big_amount: u128 = (u64::MAX as u128) + 7;

        let notes = vec![
            DecryptedNote {
                note_id: Felt::from_hex("0x111").unwrap(),
                user: user_a,
                counterparty: cp1,
                direction: NoteDirection::Incoming,
                token: token_usdc,
                amount: 400_000,
                channel_idx: 0,
                subchannel_idx: 0,
                note_idx: 0,
                spent: false,
                block_number: 1_234_567,
            },
            DecryptedNote {
                note_id: Felt::from_hex("0x222").unwrap(),
                user: user_a,
                counterparty: cp2,
                direction: NoteDirection::Outgoing,
                token: token_usdc,
                amount: big_amount,
                channel_idx: 1,
                subchannel_idx: 2,
                note_idx: 3,
                spent: false,
                block_number: 1_234_700,
            },
        ];
        let nullifiers = vec![(
            Felt::from_hex("0xdead").unwrap(),
            Felt::from_hex("0x111").unwrap(),
        )];

        ds.save_private_notes_for_user(&user_a, &notes, &nullifiers, 1_234_700);

        let (loaded_notes, loaded_nullifiers) = ds.load_private_notes();
        assert_eq!(loaded_notes.len(), 2);
        assert_eq!(loaded_nullifiers.len(), 1);

        let n0 = loaded_notes
            .iter()
            .find(|n| n.note_id == Felt::from_hex("0x111").unwrap())
            .expect("note 0x111");
        assert_eq!(n0.user, user_a);
        assert_eq!(n0.counterparty, cp1);
        assert_eq!(n0.direction, NoteDirection::Incoming);
        assert_eq!(n0.token, token_usdc);
        assert_eq!(n0.amount, 400_000);
        assert!(!n0.spent);
        assert_eq!(n0.block_number, 1_234_567);

        let n1 = loaded_notes
            .iter()
            .find(|n| n.note_id == Felt::from_hex("0x222").unwrap())
            .expect("note 0x222");
        assert_eq!(n1.direction, NoteDirection::Outgoing);
        // u128 amount above u64::MAX must survive the TEXT round-trip.
        assert_eq!(n1.amount, big_amount);
        assert_eq!(n1.channel_idx, 1);
        assert_eq!(n1.subchannel_idx, 2);
        assert_eq!(n1.note_idx, 3);

        assert_eq!(
            loaded_nullifiers[0],
            (
                Felt::from_hex("0xdead").unwrap(),
                Felt::from_hex("0x111").unwrap(),
            )
        );

        // Re-saving for the same user must replace, not duplicate. Saving
        // a different user must coexist.
        let notes_b = vec![DecryptedNote {
            note_id: Felt::from_hex("0x333").unwrap(),
            user: user_b,
            counterparty: cp1,
            direction: NoteDirection::Incoming,
            token: token_usdc,
            amount: 1,
            channel_idx: 0,
            subchannel_idx: 0,
            note_idx: 0,
            spent: true,
            block_number: 1_234_800,
        }];
        ds.save_private_notes_for_user(&user_b, &notes_b, &[], 1_234_800);
        // Replace user_a with a single note.
        let notes_a2 = vec![DecryptedNote {
            note_id: Felt::from_hex("0x999").unwrap(),
            user: user_a,
            counterparty: cp1,
            direction: NoteDirection::Incoming,
            token: token_usdc,
            amount: 5,
            channel_idx: 0,
            subchannel_idx: 0,
            note_idx: 0,
            spent: false,
            block_number: 1_234_900,
        }];
        ds.save_private_notes_for_user(&user_a, &notes_a2, &[], 1_234_900);

        let (loaded2, loaded_nuls2) = ds.load_private_notes();
        // user_a's old notes (0x111, 0x222) gone, replaced by 0x999. user_b's 0x333 still there.
        let ids: std::collections::HashSet<Felt> = loaded2.iter().map(|n| n.note_id).collect();
        assert!(ids.contains(&Felt::from_hex("0x999").unwrap()));
        assert!(ids.contains(&Felt::from_hex("0x333").unwrap()));
        assert!(!ids.contains(&Felt::from_hex("0x111").unwrap()));
        assert!(!ids.contains(&Felt::from_hex("0x222").unwrap()));
        // user_a's nullifiers cleared on re-save.
        assert!(loaded_nuls2.is_empty());
    }
}