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
//! State for the address info view (tx history, balances, calls, events, class history).

use std::collections::{HashMap, HashSet};

use starknet::core::types::Felt;

use crate::app::AddressTab;
use crate::app::actions::Source;
use crate::app::state::TxNavItem;
use crate::data::types::{
    AddressTxSummary, ContractCallSummary, MetaTxIntenderSummary, SnAddressInfo, TokenTransfer,
};
use crate::decode::events::DecodedEvent;
use crate::network::dune::AddressActivityProbe;
use crate::ui::widgets::address_color::AddressColorMap;
use crate::ui::widgets::stateful_list::StatefulList;

/// Maximum block span a nonce gap can cover before we stop auto-filling it
/// via RPC block scans. Gaps wider than this are deferred to on-demand Dune
/// queries (`run_nonce_gap_fill`). Shared between the detector
/// (`detect_unfilled_gaps`) and the filler (`fill_small_nonce_gaps_phase`) so
/// they stay aligned — drift between the two causes silent data loss.
pub const SMALL_GAP_SPAN_BLOCKS: u64 = 50;

/// Maximum number of txs an on-demand fill pulls per Enter press. Keeping
/// this small (matching the chronological pagination chunk in `app/mod.rs`)
/// makes large-gap fills lazy: each Enter shrinks the gap from its newer
/// edge, leaving a residual gap row that the user can fill again. Without
/// this cap, a 33k-tx gap would fire one giant Dune/Pathfinder query per
/// Enter, which is exactly the behavior we want to avoid.
pub const LARGE_GAP_FILL_CHUNK_TXS: u32 = 50;

/// Detected gaps with no more than this many missing nonces are filled
/// automatically (no Enter required). They still go through the deferred-fill
/// machinery — we just dispatch the fill on the user's behalf so a 1-tx hole
/// in a sparse account never surfaces as a "press Enter" row. Larger gaps
/// stay deferred so we don't burn Dune/Pathfinder queries on multi-thousand
/// tx ranges the user might not care about.
pub const AUTO_FILL_MAX_MISSING: u64 = 1;

/// Cap on the number of tiny gaps auto-dispatched per refresh. A very-active
/// address can have dozens of 1-nonce holes scattered across its history;
/// firing every one at once would saturate Pathfinder and (on the Dune
/// fallback) blow through quota. Remaining tiny gaps still appear as
/// deferred rows, and the next refresh picks them up after the dispatched
/// chunk lands.
pub const MAX_AUTO_FILLS_PER_REFRESH: usize = 5;

/// Passive UI hint derived from the event-window helper's last fetch.
/// Shared across the Calls / Events / MetaTxs tabs because all three
/// project from the same `address_events` + `address_search_progress`
/// cache. Surfaces whatever the helper already computed — no fill logic
/// is wired to it yet (see task #7 scope: passive-only port).
///
/// - `deferred_gap = Some((lo, hi))` ⇒ helper deliberately skipped that
///   block range because the TopDelta delta exceeded
///   `EVENT_LARGE_GAP_THRESHOLD_BLOCKS`. Surfaced as a title suffix so
///   users know the cached event set isn't contiguous.
/// - `min_searched > 0` ⇒ older history exists below the cached floor
///   (useful future signal for an interactive ExtendDown trigger).
#[derive(Clone, Debug, Default)]
pub struct EventWindowHint {
    /// Lowest block ever scanned for this address. `0` ⇒ reached genesis
    /// or never scanned.
    pub min_searched: u64,
    /// Highest block ever scanned. Anchors the "is there more tip to fetch"
    /// question on the next TopDelta.
    pub max_searched: u64,
    /// Deliberately skipped block range from the last TopDelta fetch.
    /// `Some((lo, hi))` where `lo..=hi` is unscanned.
    pub deferred_gap: Option<(u64, u64)>,
}

/// A detected, unfilled nonce gap in the tx list that has been deferred
/// for on-demand filling (issue #10). We do NOT auto-fill large gaps on
/// address load; instead we wait until the user scrolls toward the gap
/// boundary before burning RPC/Dune budget on it.
#[derive(Clone, Debug)]
pub struct UnfilledGap {
    /// Last known nonce below the gap.
    pub lo_nonce: u64,
    /// First known nonce above the gap.
    pub hi_nonce: u64,
    /// Block number of the lo_nonce tx (lower bound for the scan).
    pub lo_block: u64,
    /// Block number of the hi_nonce tx (upper bound for the scan).
    pub hi_block: u64,
    /// Number of missing nonces between lo and hi (exclusive).
    pub missing_count: u64,
    /// Whether the fill action has already been dispatched for this gap.
    pub fill_dispatched: bool,
}

/// Minimum block span between two consecutive contract calls before we treat
/// the hole as a fillable gap in the Calls tab. Unlike nonces (a missing nonce
/// *proves* a missing tx), a block-range hole between two calls does not prove
/// missing calls — a contract simply may not have been called for a while. So
/// this threshold is deliberately large: it surfaces the real "recent fetch vs
/// stale cache" hole (the Dune `CONTRACT_CALL_LIMIT`/event-window page caps
/// leave hundreds of thousands of blocks unscanned on revisit) without tripping
/// on ordinary quiet stretches. Tunable — ~10k blocks is a few hours on
/// mainnet. Filling a range that turns out empty is harmless: the gap just
/// closes once we've scanned it.
pub const CALL_GAP_SPAN_BLOCKS: u64 = 10_000;

/// A detected, unfilled block-range hole in the Calls list, deferred for
/// on-demand filling. The Calls analogue of [`UnfilledGap`] — keyed on block
/// numbers instead of nonces because incoming calls have no per-address
/// sequence. Each gap renders as its own row between the bordering calls; the
/// user presses Enter on it to dispatch a windowed backfill of `lo..=hi`.
#[derive(Clone, Debug)]
pub struct UnfilledCallGap {
    /// Block number of the call just *below* the gap (older edge, lower bound
    /// for the backfill scan). Also the gap's stable identity across
    /// re-detection passes.
    pub lo_block: u64,
    /// Block number of the call just *above* the gap (newer edge, upper bound
    /// for the backfill scan).
    pub hi_block: u64,
    /// Whether a fill has already been dispatched for this gap.
    pub fill_dispatched: bool,
}

/// Unscanned block range in the Transfers tab: the complement of the scanned
/// ranges, down to the deploy floor. Renders as a row; Enter dispatches a fill.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TransferGap {
    pub lo_block: u64,
    pub hi_block: u64,
    pub fill_dispatched: bool,
}

/// Gaps between `ranges` (sorted, disjoint) and below the lowest one down to
/// `floor`, oldest first. Nothing scanned yet ⇒ no gaps (the top-delta fetch
/// is still pending).
pub fn scanned_range_gaps(ranges: &[(u64, u64)], floor: u64) -> Vec<TransferGap> {
    let mut out = Vec::new();
    let Some(&(min_lo, _)) = ranges.first() else {
        return out;
    };
    if min_lo > floor {
        out.push(TransferGap {
            lo_block: floor,
            hi_block: min_lo - 1,
            fill_dispatched: false,
        });
    }
    for w in ranges.windows(2) {
        let (a_hi, b_lo) = (w[0].1, w[1].0);
        if b_lo > a_hi + 1 {
            out.push(TransferGap {
                lo_block: a_hi + 1,
                hi_block: b_lo - 1,
                fill_dispatched: false,
            });
        }
    }
    out
}

/// All state related to the address info view.
pub struct AddressInfoState {
    pub info: Option<SnAddressInfo>,
    pub events: StatefulList<DecodedEvent>,
    /// Enriched tx summaries for the Transactions tab.
    pub txs: StatefulList<AddressTxSummary>,
    /// The deploy tx that created this address. For self-deploys
    /// (DEPLOY_ACCOUNT, sender == address) the same tx also stays in `txs`
    /// since it consumed nonce 0; for UDC-style deploys it's only here.
    pub deployment: Option<AddressTxSummary>,
    /// Incoming calls to this contract (for the Calls tab).
    pub calls: StatefulList<ContractCallSummary>,
    /// tx hash → block of each row in `calls.items`: O(1) dedup, O(log n) row lookup.
    pub call_blocks: HashMap<Felt, u64>,
    /// Whether this address is a contract (nonce == 0) vs an account.
    pub is_contract: bool,
    /// The address has no class at the latest block (`get_class_hash`
    /// errored) — not deployed, exists only as a token-transfer recipient.
    /// Set once the live class fetch confirms absence; the header renders a
    /// red "not deployed" note (gated on non-zero balances).
    pub not_deployed: bool,
    /// Whether header is in visual (item-selection) mode.
    pub visual_mode: bool,
    /// Navigable items in the address header (class hash, deploy tx, deploy block, deployer).
    pub nav_items: Vec<TxNavItem>,
    /// Cursor index into nav_items.
    pub nav_cursor: usize,
    /// Class hash upgrade history for the current address.
    pub class_history: Vec<crate::data::pathfinder::ClassHashEntry>,
    /// Selected index in the class history list.
    pub class_history_scroll: usize,
    pub tab: AddressTab,
    /// Track which address we're viewing (for nonce-based cycling).
    pub context: Option<Felt>,
    /// Pagination flag (prevent duplicate fetches).
    pub fetching_more_txs: bool,
    /// Oldest block number in the current tx list (for pagination).
    pub oldest_event_block: Option<u64>,
    /// Tracks which data sources are still in-flight for the current address load.
    pub sources_pending: HashSet<Source>,
    /// Stored probe result — used for density-aware pagination window sizing.
    pub activity_probe: Option<AddressActivityProbe>,
    /// Dune-specific cursor: lowest block from last Dune result.
    pub dune_cursor_block: Option<u64>,
    /// RPC-specific cursor: lowest block from last RPC event fetch.
    pub rpc_cursor_block: Option<u64>,
    /// Whether Dune signaled more data is available (last query returned full batch).
    pub dune_has_more: bool,
    /// Whether RPC signaled more data is available.
    pub rpc_has_more: bool,
    /// Whether a WS subscription is currently active for this address.
    pub ws_subscribed: bool,
    /// Whether the post-display sanity check has already been dispatched.
    pub sanity_check_dispatched: bool,
    /// Detected large nonce gaps that have NOT been auto-filled (issue #10).
    /// Each gap renders as its own row between the bordering txs; the user
    /// presses Enter on a gap row to dispatch its fill.
    pub unfilled_gaps: Vec<UnfilledGap>,
    /// `Some(lo_nonce)` when the rendered gap row whose `lo_nonce` matches is
    /// currently selected. The gap row is a synthetic, standalone entry in the
    /// rendered list; the underlying `txs.state.selected()` does not move
    /// while this is set. Identifying by `lo_nonce` (instead of vec index)
    /// keeps the selection stable across re-detection passes that reorder the
    /// gap list.
    pub gap_selected: Option<u64>,
    /// ListState fed to ratatui for the Transactions tab. Indexed against the
    /// rendered list (txs + optional gap row), so it diverges from `txs.state`
    /// whenever a gap is showing. Persisted across frames to keep the viewport
    /// offset stable.
    pub txs_render_state: ratatui::widgets::ListState,
    /// Detected block-range holes in the Calls list that have NOT been filled.
    /// The Calls-tab analogue of `unfilled_gaps`; each renders as its own row
    /// between the bordering calls and the user presses Enter to backfill it.
    pub call_gaps: Vec<UnfilledCallGap>,
    /// `Some(lo_block)` when the rendered call-gap row whose `lo_block` matches
    /// is currently selected. Identified by `lo_block` (not vec index) so the
    /// selection survives re-detection passes — mirrors `gap_selected`.
    pub call_gap_selected: Option<u64>,
    /// ListState fed to ratatui for the Calls tab. Indexed against the rendered
    /// list (calls + optional gap rows), so it diverges from `calls.state`
    /// whenever a gap is showing. Mirrors `txs_render_state`.
    pub calls_render_state: ratatui::widgets::ListState,
    /// Block ranges `[lo, hi]` we have *fully* scanned for calls (Dune pages
    /// and on-demand gap fills). Unlike nonces, a block-range hole doesn't prove
    /// missing calls, so once we've scanned a range and found it sparse we must
    /// remember that — otherwise `detect_unfilled_call_gaps` would re-surface
    /// the same quiet stretch as a gap forever. Merged intervals, kept small.
    pub scanned_call_ranges: Vec<(u64, u64)>,
    /// Lowest block of the region Dune pages have been tracking. Above it,
    /// every block not in `scanned_call_ranges` is a gap, however short.
    pub call_tracked_from: Option<u64>,
    /// ERC-20 transfers touching this address (Transfers tab), newest-first.
    pub transfers: StatefulList<TokenTransfer>,
    /// `(tx_hash, event_index)` → block of each row: O(1) dedup on merge.
    pub transfer_keys: HashMap<(Felt, u64), u64>,
    /// Fully scanned `[lo, hi]` block ranges; gaps are their complement.
    pub transfer_scanned_ranges: Vec<(u64, u64)>,
    pub transfer_gaps: Vec<TransferGap>,
    /// `Some(lo_block)` when a transfer-gap row is the active selection.
    pub transfer_gap_selected: Option<u64>,
    /// ListState for the rendered (rows + gap rows) Transfers list.
    pub transfers_render_state: ratatui::widgets::ListState,
    /// The on-entry top-delta fetch has been dispatched for this address.
    pub transfers_dispatched: bool,
    pub fetching_transfers: bool,
    /// Counterparty color slots; the viewed address is pinned to the sender style.
    pub transfer_color_map: AddressColorMap,
    pub transfer_counts: HashMap<Felt, usize>,
    pub transfer_color_processed_len: usize,
    /// Meta-transactions (SNIP-9 outside executions) where this address is the intender.
    pub meta_txs: StatefulList<MetaTxIntenderSummary>,
    /// Pagination flag for MetaTxs tab (prevent duplicate fetches).
    pub fetching_meta_txs: bool,
    /// pf-query event cursor (oldest block - 1) for MetaTxs pagination.
    pub meta_tx_cursor_block: Option<u64>,
    /// Whether pf-query signaled more meta-tx data is available.
    pub meta_tx_has_more: bool,
    /// Whether the initial MetaTxs fetch has been dispatched for the current address.
    pub meta_txs_dispatched: bool,
    /// Lower bound for the MetaTxs bloom scan, preserved across pagination.
    /// Set to deploy block when known; bounds the scan range so pf-query
    /// doesn't time out walking chunks older than the account.
    pub meta_tx_from_block: u64,
    /// Last ExtendDown window size (blocks) used for this address's MetaTxs
    /// fetch. Adapted across pages: doubles on empty windows (sparse
    /// addresses), halves on full pages (dense addresses, bloom cap hit).
    /// Seeded with `EXTEND_DOWN_INITIAL_WINDOW` on tab entry.
    pub meta_tx_last_window: u64,
    /// Shared event-window hint for the event-backed tabs (Calls / Events /
    /// MetaTxs). Updated whenever `ensure_address_events_window` runs.
    /// `None` before any fetch completes.
    pub event_window: Option<EventWindowHint>,
    /// Per-sender occurrence counts across `calls.items`. Rebuilt only when
    /// the list length changes (i.e. on merge), so steady-state renders
    /// pay nothing.
    pub call_sender_counts: HashMap<Felt, usize>,
    /// Slot assignments for repeated, non-tagged senders in the Calls tab.
    /// Slots are sticky across rebuilds (HashMap insert is idempotent), so
    /// an address keeps its color once it crosses the 2-occurrence threshold.
    pub call_color_map: AddressColorMap,
    /// Cached `calls.items.len()` from the last color-map rebuild. When this
    /// matches the current length, the cache is up-to-date and renders skip
    /// the rescan entirely.
    pub call_color_processed_len: usize,
    /// Per-contract occurrence counts across `txs.items`'s `called_contracts`.
    /// Drives palette assignment in the Txs tab's Contracts column so repeated
    /// targets pop out, unlabeled one-offs stay neutral, and labeled or
    /// privacy contracts keep their tagged style.
    pub tx_contract_counts: HashMap<Felt, usize>,
    /// Slot assignments for repeated, non-tagged contracts called by this
    /// address's outbound txs. Same idempotent-slot guarantee as
    /// `call_color_map`.
    pub tx_color_map: AddressColorMap,
    /// Cached `txs.items.len()` from the last contract color-map rebuild.
    pub tx_color_processed_len: usize,
}

/// Auto-fill row target for the event-backed tabs (currently MetaTxs;
/// extends to Calls / Events as those tabs migrate to the shared pipeline).
///
/// Stop conditions for the background auto-continue loop are exactly:
///
///   1. The visible list reaches `AUTO_FILL_TARGET` rows — stop.
///   2. `has_more` drops (history exhausted: pf-query ran out of blocks
///      to scan) — stop. The final count stands, no retry.
///   3. The user navigates away — the session-token cancellation in the
///      network task tears down any in-flight page fetch.
///
/// There is no page-count cap: a sparse address with zero classified
/// meta-txs is allowed to walk back to its deploy block, because the
/// alternative ("give up early") silently under-reports. Scrolling near
/// the bottom re-arms auto-fill (see `maybe_fetch_more_meta_txs`), so
/// history-exhaustion and user-initiated continuation share one path.
pub const AUTO_FILL_TARGET: usize = 50;

impl Default for AddressInfoState {
    fn default() -> Self {
        Self {
            info: None,
            events: StatefulList::new(),
            txs: StatefulList::new(),
            deployment: None,
            calls: StatefulList::new(),
            call_blocks: HashMap::new(),
            is_contract: false,
            not_deployed: false,
            visual_mode: false,
            nav_items: Vec::new(),
            nav_cursor: 0,
            class_history: Vec::new(),
            class_history_scroll: 0,
            tab: AddressTab::Transactions,
            context: None,
            fetching_more_txs: false,
            oldest_event_block: None,
            sources_pending: HashSet::new(),
            activity_probe: None,
            dune_cursor_block: None,
            rpc_cursor_block: None,
            dune_has_more: false,
            rpc_has_more: false,
            ws_subscribed: false,
            sanity_check_dispatched: false,
            unfilled_gaps: Vec::new(),
            gap_selected: None,
            txs_render_state: ratatui::widgets::ListState::default(),
            call_gaps: Vec::new(),
            call_gap_selected: None,
            calls_render_state: ratatui::widgets::ListState::default(),
            scanned_call_ranges: Vec::new(),
            call_tracked_from: None,
            transfers: StatefulList::new(),
            transfer_keys: HashMap::new(),
            transfer_scanned_ranges: Vec::new(),
            transfer_gaps: Vec::new(),
            transfer_gap_selected: None,
            transfers_render_state: ratatui::widgets::ListState::default(),
            transfers_dispatched: false,
            fetching_transfers: false,
            transfer_color_map: AddressColorMap::new(),
            transfer_counts: HashMap::new(),
            transfer_color_processed_len: 0,
            meta_txs: StatefulList::new(),
            fetching_meta_txs: false,
            meta_tx_cursor_block: None,
            meta_tx_has_more: false,
            meta_txs_dispatched: false,
            meta_tx_from_block: 0,
            meta_tx_last_window: crate::network::event_window::EXTEND_DOWN_INITIAL_WINDOW,
            event_window: None,
            call_sender_counts: HashMap::new(),
            call_color_map: AddressColorMap::new(),
            call_color_processed_len: 0,
            tx_contract_counts: HashMap::new(),
            tx_color_map: AddressColorMap::new(),
            tx_color_processed_len: 0,
        }
    }
}

impl AddressInfoState {
    /// Clear all address info data. Called when navigating to a new address.
    pub fn clear(&mut self) {
        self.info = None;
        self.events = StatefulList::new();
        self.class_history.clear();
        self.class_history_scroll = 0;
        self.visual_mode = false;
        self.nav_items.clear();
        self.nav_cursor = 0;
        self.tab = AddressTab::Transactions;
        self.txs = StatefulList::new();
        self.deployment = None;
        self.calls = StatefulList::new();
        self.call_blocks.clear();
        self.not_deployed = false;
        self.fetching_more_txs = false;
        self.oldest_event_block = None;
        self.sources_pending.clear();
        self.activity_probe = None;
        self.dune_cursor_block = None;
        self.rpc_cursor_block = None;
        self.dune_has_more = false;
        self.rpc_has_more = false;
        self.ws_subscribed = false;
        self.sanity_check_dispatched = false;
        self.unfilled_gaps.clear();
        self.gap_selected = None;
        self.txs_render_state = ratatui::widgets::ListState::default();
        self.call_gaps.clear();
        self.call_gap_selected = None;
        self.calls_render_state = ratatui::widgets::ListState::default();
        self.scanned_call_ranges.clear();
        self.call_tracked_from = None;
        self.transfers = StatefulList::new();
        self.transfer_keys.clear();
        self.transfer_scanned_ranges.clear();
        self.transfer_gaps.clear();
        self.transfer_gap_selected = None;
        self.transfers_render_state = ratatui::widgets::ListState::default();
        self.transfers_dispatched = false;
        self.fetching_transfers = false;
        self.transfer_color_map = AddressColorMap::new();
        self.transfer_counts.clear();
        self.transfer_color_processed_len = 0;
        self.meta_txs = StatefulList::new();
        self.fetching_meta_txs = false;
        self.meta_tx_cursor_block = None;
        self.meta_tx_has_more = false;
        self.meta_txs_dispatched = false;
        self.meta_tx_from_block = 0;
        self.meta_tx_last_window = crate::network::event_window::EXTEND_DOWN_INITIAL_WINDOW;
        self.event_window = None;
        self.call_sender_counts.clear();
        self.call_color_map = AddressColorMap::new();
        self.call_color_processed_len = 0;
        self.tx_contract_counts.clear();
        self.tx_color_map = AddressColorMap::new();
        self.tx_color_processed_len = 0;
    }

    /// Drop the cached color map so the next render rebuilds it from scratch.
    /// Use this when a call's sender mutates in place (e.g. a `Felt::ZERO`
    /// stub being upgraded by enrichment) — `calls.items.len()` doesn't
    /// change in that case, so the length-keyed fast path in
    /// `update_call_color_map` would otherwise leave stale entries (a
    /// phantom `Felt::ZERO` slot lingering in the color map, real senders
    /// never counted).
    pub fn invalidate_call_color_cache(&mut self) {
        self.call_sender_counts.clear();
        self.call_color_map = AddressColorMap::new();
        self.call_color_processed_len = 0;
    }

    /// Drop the cached tx-color map. `merge_tx_summaries` calls this when
    /// an in-place upgrade fills `called_contracts` on an existing row —
    /// the length-keyed fast path wouldn't otherwise notice, so the
    /// Contracts column would stay in NORMAL_STYLE until the list grows.
    pub fn invalidate_tx_color_cache(&mut self) {
        self.tx_contract_counts.clear();
        self.tx_color_map = AddressColorMap::new();
        self.tx_color_processed_len = 0;
    }

    /// Refresh the per-sender count map and color slots for the Calls tab.
    ///
    /// Cheap fast path: when `calls.items.len()` matches the cached length,
    /// nothing has merged since the last rebuild and we return immediately.
    /// On a merge, we rescan the full list — sort interleaving makes index-
    /// based incremental work unsafe, but `AddressColorMap::register` is
    /// idempotent so existing senders keep their slots (and thus their
    /// colors) across rebuilds.
    ///
    /// `is_known` is the registry-tagged predicate; tagged addresses skip
    /// color registration so they keep their `LABEL_STYLE` rendering.
    pub fn update_call_color_map(&mut self, is_known: impl Fn(&Felt) -> bool) {
        if self.call_color_processed_len == self.calls.items.len() {
            return;
        }
        self.call_sender_counts.clear();
        for call in &self.calls.items {
            let count = self.call_sender_counts.entry(call.sender).or_insert(0);
            *count += 1;
            if *count == 2 && !is_known(&call.sender) {
                self.call_color_map.register(call.sender);
            }
        }
        self.call_color_processed_len = self.calls.items.len();
    }

    /// Refresh the per-contract count map and color slots for the Txs tab's
    /// Contracts column. Mirrors `update_call_color_map`: counts occurrences
    /// across every tx's `called_contracts`, and assigns palette slots only
    /// to repeats that aren't already registry-known (labeled contracts keep
    /// their `LABEL_STYLE`; privacy contracts keep `PRIVACY_STYLE`).
    pub fn update_tx_color_map(&mut self, is_known: impl Fn(&Felt) -> bool) {
        if self.tx_color_processed_len == self.txs.items.len() {
            return;
        }
        self.tx_contract_counts.clear();
        for tx in &self.txs.items {
            for contract in &tx.called_contracts {
                let count = self.tx_contract_counts.entry(*contract).or_insert(0);
                *count += 1;
                if *count == 2 && !is_known(contract) {
                    self.tx_color_map.register(*contract);
                }
            }
        }
        self.tx_color_processed_len = self.txs.items.len();
    }

    /// Whether any source thinks there is more data to fetch.
    pub fn has_more_data(&self) -> bool {
        self.dune_has_more || self.rpc_has_more
    }

    /// The pagination cursor: the minimum block across all source cursors.
    pub fn pagination_cursor(&self) -> Option<u64> {
        [
            self.dune_cursor_block,
            self.rpc_cursor_block,
            self.oldest_event_block,
        ]
        .into_iter()
        .flatten()
        .min()
    }

    /// Build the list of navigable items for the AddressInfo header.
    pub fn build_nav_items(&mut self) {
        let mut items: Vec<TxNavItem> = Vec::new();

        // Class hash -> ClassInfo view
        if let Some(info) = &self.info
            && let Some(ch) = info.class_hash
        {
            items.push(TxNavItem::ClassHash(ch));
        }

        // Deployment info
        if let Some(deploy) = &self.deployment {
            // Deploy tx (skip if unknown/zero)
            if deploy.hash != Felt::ZERO {
                items.push(TxNavItem::Transaction(deploy.hash));
            }
            // Deploy block
            if deploy.block_number > 0 {
                items.push(TxNavItem::Block(deploy.block_number));
            }
            // Deployer address
            if let Some(sender) = deploy.sender
                && let Some(info) = &self.info
                && sender != info.address
                && sender != Felt::ZERO
            {
                items.push(TxNavItem::Address(sender));
            }
        }

        // Transfers tab: the selected row's tx, block, counterparties and
        // token join the header items; the cursor starts on the row.
        let header_len = items.len();
        if self.tab == AddressTab::Transfers
            && let Some(row) = self.transfers.selected_item()
        {
            for item in [
                TxNavItem::Transaction(row.tx_hash),
                TxNavItem::Block(row.block_number),
                TxNavItem::Address(row.from),
                TxNavItem::Address(row.to),
                TxNavItem::Address(row.token),
            ] {
                let skip = match &item {
                    TxNavItem::Address(a) => Some(*a) == self.context || *a == Felt::ZERO,
                    TxNavItem::Block(b) => *b == 0,
                    _ => false,
                };
                if !skip && !items.contains(&item) {
                    items.push(item);
                }
            }
        }

        self.nav_cursor = if items.len() > header_len {
            header_len
        } else {
            0
        };
        self.nav_items = items;
    }

    /// Step the visual-mode cursor by `delta` (wrapping).
    pub fn nav_step(&mut self, delta: i64) {
        if self.nav_items.is_empty() {
            return;
        }
        let len = self.nav_items.len() as i64;
        let next = (self.nav_cursor as i64 + delta).rem_euclid(len) as usize;
        self.nav_cursor = next;
    }

    /// Split `txs` into regular txs and deployment tx.
    ///
    /// DEPLOY_ACCOUNT txs (where the new account paid for its own deploy,
    /// `sender == address`) consume nonce 0 and are part of the account's
    /// history, so they populate `self.deployment` *and* stay in the regular
    /// list. UDC-style deploys (`sender != address`) are the deployer's tx,
    /// not the deployed contract's, so they're pulled out entirely.
    pub fn filter_deployment_txs(
        &mut self,
        address: Felt,
        txs: Vec<AddressTxSummary>,
    ) -> Vec<AddressTxSummary> {
        let mut regular = Vec::with_capacity(txs.len());
        for tx in txs {
            let self_deploy =
                tx.tx_type == "DEPLOY_ACCOUNT" && tx.sender.is_none_or(|s| s == address);
            let foreign_deploy =
                tx.tx_type.starts_with("DEPLOY") || tx.sender.is_some_and(|s| s != address);
            if self_deploy || foreign_deploy {
                let should_set = self.deployment.is_none()
                    || self
                        .deployment
                        .as_ref()
                        .is_some_and(|d| d.hash == Felt::ZERO);
                if should_set {
                    self.deployment = Some(tx.clone());
                }
                if self_deploy {
                    regular.push(tx);
                }
            } else {
                regular.push(tx);
            }
        }
        regular
    }

    /// Merge incoming tx summaries into the existing list.
    /// - Upgrades existing entries with better data (status, fee, timestamp, endpoint)
    /// - Appends new entries not yet seen
    /// - Re-sorts by nonce descending
    /// - Preserves the current selection index
    pub fn merge_tx_summaries(&mut self, incoming: Vec<AddressTxSummary>) {
        if incoming.is_empty() {
            return;
        }
        // `seen_hashes` tracks both pre-existing and newly added hashes so that
        // duplicates within the same incoming batch are also collapsed.
        let mut seen_hashes: HashSet<Felt> = self.txs.items.iter().map(|t| t.hash).collect();
        let had_selection = self.txs.state.selected();

        let mut called_contracts_upgraded = false;
        for item in incoming {
            if seen_hashes.contains(&item.hash) {
                if let Some(existing) = self.txs.items.iter_mut().find(|t| t.hash == item.hash) {
                    called_contracts_upgraded |= upgrade_tx_summary(existing, &item);
                }
            } else {
                seen_hashes.insert(item.hash);
                self.txs.items.push(item);
            }
        }
        // In-place called_contracts fill doesn't move items.len(), so the
        // tx-color cache's length-keyed fast path would miss it. Force a
        // rebuild now so the Contracts column reflects the enriched rows.
        if called_contracts_upgraded {
            self.invalidate_tx_color_cache();
        }

        self.txs.items.sort_by(|a, b| b.nonce.cmp(&a.nonce));

        // Preserve selection
        if let Some(sel) = had_selection {
            if sel < self.txs.items.len() {
                self.txs.state.select(Some(sel));
            }
        } else if !self.txs.items.is_empty() {
            self.txs.select_first();
        }

        // Update oldest block for pagination
        if let Some(oldest) = self
            .txs
            .items
            .iter()
            .filter(|t| t.block_number > 0)
            .map(|t| t.block_number)
            .min()
        {
            self.oldest_event_block = Some(oldest);
        }
    }

    /// Merge incoming contract calls into the existing list and sort by block
    /// number descending. `deduplicate_contract_calls` does the field-level
    /// merge so a later-arriving Dune row can still contribute richer
    /// function_name/fee data to a pf-query row with the same tx_hash (and
    /// vice-versa). Callers are responsible for follow-up work (selection,
    /// cursor updates, persistence).
    pub fn merge_calls(&mut self, incoming: Vec<ContractCallSummary>) {
        if incoming.is_empty() {
            return;
        }
        let mut merged = std::mem::take(&mut self.calls.items);
        merged.extend(incoming);
        self.calls.items = crate::data::types::deduplicate_contract_calls(merged);
        self.calls
            .items
            .sort_by(|a, b| b.block_number.cmp(&a.block_number));
        self.call_blocks = self
            .calls
            .items
            .iter()
            .map(|c| (c.tx_hash, c.block_number))
            .collect();
    }

    /// Insert one call keeping block-descending order (after same-block rows,
    /// like a stable sort of a push). Returns `false` if the tx hash is listed.
    pub fn insert_call(&mut self, call: ContractCallSummary) -> bool {
        if self.call_blocks.contains_key(&call.tx_hash) {
            return false;
        }
        let idx = self
            .calls
            .items
            .partition_point(|c| c.block_number >= call.block_number);
        self.call_blocks.insert(call.tx_hash, call.block_number);
        self.calls.items.insert(idx, call);
        true
    }

    /// Index of the call with this tx hash: its block from the index, then a
    /// binary search to that block's few rows.
    pub fn call_position(&self, tx_hash: Felt) -> Option<usize> {
        let block = *self.call_blocks.get(&tx_hash)?;
        let start = Self::first_index_with_key(&self.calls.items, |c| c.block_number, block)?;
        self.calls.items[start..]
            .iter()
            .take_while(|c| c.block_number == block)
            .position(|c| c.tx_hash == tx_hash)
            .map(|i| start + i)
    }

    pub fn find_call_mut(&mut self, tx_hash: Felt) -> Option<&mut ContractCallSummary> {
        let i = self.call_position(tx_hash)?;
        Some(&mut self.calls.items[i])
    }

    /// Clones of the rows for `hashes`; unknown hashes are skipped.
    pub fn calls_by_hash<'a>(
        &self,
        hashes: impl IntoIterator<Item = &'a Felt>,
    ) -> Vec<ContractCallSummary> {
        hashes
            .into_iter()
            .filter_map(|h| self.call_position(*h))
            .map(|i| self.calls.items[i].clone())
            .collect()
    }

    /// First index whose key equals `target` in a list sorted by `key` descending.
    fn first_index_with_key<T>(items: &[T], key: impl Fn(&T) -> u64, target: u64) -> Option<usize> {
        let p = items.partition_point(|x| key(x) > target);
        (p < items.len() && key(&items[p]) == target).then_some(p)
    }

    /// Scan the current tx list for *all* large nonce gaps that should be
    /// deferred until the user asks for them.
    ///
    /// Each returned gap has at least one missing nonce *and* a block span
    /// wider than `SMALL_GAP_SPAN_BLOCKS` (the RPC small-gap path's reach —
    /// narrower gaps stay on the auto-fill path). Sorted by `lo_nonce`
    /// ascending so renderers/tests have a stable order.
    pub fn detect_unfilled_gaps(&self) -> Vec<UnfilledGap> {
        if self.is_contract {
            return Vec::new();
        }
        let mut pairs: Vec<(u64, u64)> = self
            .txs
            .items
            .iter()
            .filter(|t| t.block_number > 0)
            .map(|t| (t.nonce, t.block_number))
            .collect();
        if pairs.len() < 2 {
            return Vec::new();
        }
        pairs.sort_by_key(|(n, _)| *n);

        let mut out = Vec::new();
        for w in pairs.windows(2) {
            let (lo_nonce, lo_block) = w[0];
            let (hi_nonce, hi_block) = w[1];
            let missing = hi_nonce.saturating_sub(lo_nonce).saturating_sub(1);
            if missing == 0 {
                continue;
            }
            // `fill_small_nonce_gaps_phase` only covers spans ≤ SMALL_GAP_SPAN_BLOCKS
            // via RPC scans; anything wider must be filled via Dune on demand
            // or it would be silently dropped.
            let span = hi_block.saturating_sub(lo_block);
            if span <= SMALL_GAP_SPAN_BLOCKS {
                continue;
            }
            out.push(UnfilledGap {
                lo_nonce,
                hi_nonce,
                lo_block,
                hi_block,
                missing_count: missing,
                fill_dispatched: false,
            });
        }
        out
    }

    /// Re-detect gaps and store them. `fill_dispatched` is preserved only for
    /// gaps whose `(lo_nonce, hi_nonce)` is unchanged from the previous list —
    /// a shifted `hi_nonce` is evidence the fill response just landed
    /// (lazy fills always shrink the gap from the newer edge), so we clear
    /// the flag and let the user press Enter again for the next chunk.
    /// Drops the gap selection if the previously-selected gap no longer exists.
    pub fn refresh_unfilled_gaps(&mut self) {
        let prev_inflight: std::collections::HashMap<u64, u64> = self
            .unfilled_gaps
            .iter()
            .filter(|g| g.fill_dispatched)
            .map(|g| (g.lo_nonce, g.hi_nonce))
            .collect();
        let mut next = self.detect_unfilled_gaps();
        for g in next.iter_mut() {
            if let Some(prev_hi) = prev_inflight.get(&g.lo_nonce)
                && *prev_hi == g.hi_nonce
            {
                g.fill_dispatched = true;
            }
        }
        self.unfilled_gaps = next;
        if let Some(sel) = self.gap_selected
            && !self.unfilled_gaps.iter().any(|g| g.lo_nonce == sel)
        {
            self.gap_selected = None;
        }
    }

    /// Render-order positions for the gap rows: pairs of `(tx_idx, lo_nonce)`
    /// sorted by `tx_idx` ascending. Each gap renders immediately above the
    /// tx whose nonce equals `lo_nonce`. Gaps whose `lo_nonce` tx isn't in
    /// `txs.items` are filtered out (defensive — usually all match).
    pub fn gap_render_positions(&self) -> Vec<(usize, u64)> {
        let mut out: Vec<(usize, u64)> = self
            .unfilled_gaps
            .iter()
            .filter_map(|g| {
                Self::first_index_with_key(&self.txs.items, |t| t.nonce, g.lo_nonce)
                    .map(|p| (p, g.lo_nonce))
            })
            .collect();
        out.sort_by_key(|(p, _)| *p);
        out
    }

    fn rendered_len(&self, gaps: &[(usize, u64)]) -> usize {
        self.txs.items.len() + gaps.len()
    }

    fn tx_pos_to_rendered(tx_pos: usize, gaps: &[(usize, u64)]) -> usize {
        tx_pos + gaps.iter().filter(|(p, _)| *p <= tx_pos).count()
    }

    fn gap_rendered_idx(gaps: &[(usize, u64)], idx_in_gaps: usize) -> usize {
        gaps[idx_in_gaps].0 + idx_in_gaps
    }

    /// Rendered (gap-aware) selection index for the Transactions list.
    pub fn tx_list_rendered_selected(&self) -> Option<usize> {
        self.tx_list_rendered_selected_with(&self.gap_render_positions())
    }

    /// Same, for callers that already hold `gap_render_positions()`.
    pub fn tx_list_rendered_selected_with(&self, gaps: &[(usize, u64)]) -> Option<usize> {
        if let Some(sel_lo) = self.gap_selected
            && let Some(g_idx) = gaps.iter().position(|(_, lo)| *lo == sel_lo)
        {
            return Some(Self::gap_rendered_idx(gaps, g_idx));
        }
        let tx_idx = self.txs.state.selected()?;
        Some(Self::tx_pos_to_rendered(tx_idx, gaps))
    }

    /// Currently-selected gap, if the gap row is the active selection.
    pub fn selected_gap(&self) -> Option<&UnfilledGap> {
        let lo = self.gap_selected?;
        self.unfilled_gaps.iter().find(|g| g.lo_nonce == lo)
    }

    fn current_rendered(&self, gaps: &[(usize, u64)]) -> usize {
        if let Some(sel_lo) = self.gap_selected
            && let Some(g_idx) = gaps.iter().position(|(_, lo)| *lo == sel_lo)
        {
            return Self::gap_rendered_idx(gaps, g_idx);
        }
        let t = self.txs.state.selected().unwrap_or(0);
        Self::tx_pos_to_rendered(t, gaps)
    }

    /// First gap rendered idx that lies strictly between `cur` and `target`
    /// (target inclusive). Returns `None` if no gap is crossed.
    fn first_gap_crossed(gaps: &[(usize, u64)], cur: usize, target: usize) -> Option<usize> {
        if cur == target {
            return None;
        }
        if target > cur {
            gaps.iter().enumerate().find_map(|(g_idx, (p, _))| {
                let r = p + g_idx;
                (r > cur && r <= target).then_some(r)
            })
        } else {
            gaps.iter().enumerate().rev().find_map(|(g_idx, (p, _))| {
                let r = p + g_idx;
                (r < cur && r >= target).then_some(r)
            })
        }
    }

    /// Apply a target rendered index to state — selects the gap row when the
    /// index lands on one, otherwise selects the corresponding tx.
    fn apply_rendered(&mut self, r: usize, gaps: &[(usize, u64)]) {
        match rendered_row(r, gaps) {
            RenderedRow::Gap(lo) => self.gap_selected = Some(lo),
            RenderedRow::Item(t) => {
                self.gap_selected = None;
                self.txs.state.select(Some(t));
            }
        }
    }

    /// Move selection by `delta` rows in the rendered list, clamping on the
    /// first gap row crossed.
    fn tx_list_step(&mut self, delta: i64) {
        if self.txs.items.is_empty() || delta == 0 {
            return;
        }
        let gaps = self.gap_render_positions();
        let rendered_max = self.rendered_len(&gaps).saturating_sub(1);
        let cur = self.current_rendered(&gaps);
        let target = ((cur as i64) + delta).clamp(0, rendered_max as i64) as usize;
        let final_r = Self::first_gap_crossed(&gaps, cur, target).unwrap_or(target);
        self.apply_rendered(final_r, &gaps);
    }

    pub fn tx_list_next(&mut self) {
        self.tx_list_step(1);
    }

    pub fn tx_list_previous(&mut self) {
        self.tx_list_step(-1);
    }

    /// Jump toward the first row, clamping on the first gap row crossed.
    pub fn tx_list_select_first(&mut self) {
        if self.txs.items.is_empty() {
            return;
        }
        let gaps = self.gap_render_positions();
        let cur = self.current_rendered(&gaps);
        let final_r = Self::first_gap_crossed(&gaps, cur, 0).unwrap_or(0);
        self.apply_rendered(final_r, &gaps);
    }

    /// Jump toward the last row, clamping on the first gap row crossed.
    pub fn tx_list_select_last(&mut self) {
        if self.txs.items.is_empty() {
            return;
        }
        let gaps = self.gap_render_positions();
        let rendered_max = self.rendered_len(&gaps).saturating_sub(1);
        let cur = self.current_rendered(&gaps);
        let final_r = Self::first_gap_crossed(&gaps, cur, rendered_max).unwrap_or(rendered_max);
        self.apply_rendered(final_r, &gaps);
    }

    pub fn tx_list_scroll_by(&mut self, delta: i64) {
        self.tx_list_step(delta);
    }

    // ---- Calls-tab block-range gaps (mirror the nonce-gap machinery) ----

    /// Calls-tab block-range holes, sorted by `lo_block`. A gap's bounds are
    /// the blocks bordering the hole; a fill rescans `[lo_block, hi_block]`.
    ///
    /// Inside the Dune-tracked region (from `call_tracked_from` up) every block
    /// missing from `scanned_call_ranges` is a gap. Below it only holes between
    /// calls wider than [`CALL_GAP_SPAN_BLOCKS`] are: a quiet stretch doesn't
    /// prove a call is missing.
    pub fn detect_unfilled_call_gaps(&self) -> Vec<UnfilledCallGap> {
        let gap = |lo_block, hi_block| UnfilledCallGap {
            lo_block,
            hi_block,
            fill_dispatched: false,
        };
        let tracked_from = self.call_tracked_from.unwrap_or(u64::MAX);
        let mut out = Vec::new();

        // `calls.items` is block-descending, so walk it oldest-first.
        let mut prev: Option<u64> = None;
        for b in self.calls.items.iter().rev().map(|c| c.block_number) {
            if b == 0 || prev == Some(b) {
                continue;
            }
            if let Some(lo_block) = prev
                && b <= tracked_from
                && b - lo_block > CALL_GAP_SPAN_BLOCKS
                && !self
                    .scanned_call_ranges
                    .iter()
                    .any(|(rlo, rhi)| *rlo <= lo_block && b <= *rhi)
            {
                out.push(gap(lo_block, b));
            }
            prev = Some(b);
        }

        if let Some(t) = self.call_tracked_from {
            // First block of the tracked region not yet known to be scanned.
            let mut cursor = t;
            for &(rlo, rhi) in &self.scanned_call_ranges {
                if rhi < cursor {
                    continue;
                }
                if rlo > cursor {
                    out.push(gap(cursor.saturating_sub(1), rlo));
                }
                cursor = cursor.max(rhi.saturating_add(1));
            }
        }
        out.sort_by_key(|g| g.lo_block);
        out
    }

    /// Lower the Dune-tracked region's floor to `from`.
    pub fn note_call_tracked_from(&mut self, from: u64) {
        self.call_tracked_from = Some(self.call_tracked_from.map_or(from, |t| t.min(from)));
    }

    /// Record a `[lo, hi]` block range as fully scanned for calls, merging it
    /// into `scanned_call_ranges` (coalescing overlapping/adjacent intervals so
    /// the list stays small). Called when an on-demand fill covered the whole
    /// range (returned below its query limit).
    pub fn note_scanned_call_range(&mut self, lo: u64, hi: u64) {
        crate::utils::merge_block_interval(&mut self.scanned_call_ranges, lo, hi);
    }

    /// Re-detect call gaps and store them. Mirrors `refresh_unfilled_gaps`:
    /// `fill_dispatched` is preserved only for gaps whose `(lo_block, hi_block)`
    /// is unchanged — a shifted `hi_block` is evidence the lazy fill landed (it
    /// always shrinks the gap from the newer edge), so we clear the flag and let
    /// the user press Enter again for the next chunk. Drops a stale selection.
    pub fn refresh_unfilled_call_gaps(&mut self) {
        let prev_inflight: HashMap<u64, u64> = self
            .call_gaps
            .iter()
            .filter(|g| g.fill_dispatched)
            .map(|g| (g.lo_block, g.hi_block))
            .collect();
        let mut next = self.detect_unfilled_call_gaps();
        for g in next.iter_mut() {
            if let Some(prev_hi) = prev_inflight.get(&g.lo_block)
                && *prev_hi == g.hi_block
            {
                g.fill_dispatched = true;
            }
        }
        self.call_gaps = next;
        if let Some(sel) = self.call_gap_selected
            && !self.call_gaps.iter().any(|g| g.lo_block == sel)
        {
            self.call_gap_selected = None;
        }
    }

    /// Render-order positions for the call-gap rows: `(call_idx, lo_block)`
    /// sorted by `call_idx` ascending. The calls list is block-descending, so
    /// each gap renders just below the calls at or above its `hi_block`.
    pub fn call_gap_render_positions(&self) -> Vec<(usize, u64)> {
        let mut out: Vec<(usize, u64)> = self
            .call_gaps
            .iter()
            .map(|g| {
                let p = self
                    .calls
                    .items
                    .partition_point(|c| c.block_number >= g.hi_block);
                (p, g.lo_block)
            })
            .collect();
        out.sort_by_key(|(p, lo)| (*p, std::cmp::Reverse(*lo)));
        out
    }

    /// Currently-selected call gap, if a gap row is the active selection.
    pub fn selected_call_gap(&self) -> Option<&UnfilledCallGap> {
        let lo = self.call_gap_selected?;
        self.call_gaps.iter().find(|g| g.lo_block == lo)
    }

    fn call_rendered_len(&self, gaps: &[(usize, u64)]) -> usize {
        self.calls.items.len() + gaps.len()
    }

    fn call_current_rendered(&self, gaps: &[(usize, u64)]) -> usize {
        if let Some(sel_lo) = self.call_gap_selected
            && let Some(g_idx) = gaps.iter().position(|(_, lo)| *lo == sel_lo)
        {
            return Self::gap_rendered_idx(gaps, g_idx);
        }
        let c = self.calls.state.selected().unwrap_or(0);
        Self::tx_pos_to_rendered(c, gaps)
    }

    fn apply_call_rendered(&mut self, r: usize, gaps: &[(usize, u64)]) {
        match rendered_row(r, gaps) {
            RenderedRow::Gap(lo) => self.call_gap_selected = Some(lo),
            RenderedRow::Item(c) => {
                self.call_gap_selected = None;
                self.calls.state.select(Some(c));
            }
        }
    }

    /// Move selection by `delta` rows in the rendered calls list, clamping on
    /// the first gap row crossed. Mirrors `tx_list_step`.
    fn call_list_step(&mut self, delta: i64) {
        if self.calls.items.is_empty() || delta == 0 {
            return;
        }
        let gaps = self.call_gap_render_positions();
        let rendered_max = self.call_rendered_len(&gaps).saturating_sub(1);
        let cur = self.call_current_rendered(&gaps);
        let target = ((cur as i64) + delta).clamp(0, rendered_max as i64) as usize;
        let final_r = Self::first_gap_crossed(&gaps, cur, target).unwrap_or(target);
        self.apply_call_rendered(final_r, &gaps);
    }

    pub fn call_list_next(&mut self) {
        self.call_list_step(1);
    }

    pub fn call_list_previous(&mut self) {
        self.call_list_step(-1);
    }

    pub fn call_list_scroll_by(&mut self, delta: i64) {
        self.call_list_step(delta);
    }

    /// Jump toward the first row, clamping on the first gap row crossed.
    pub fn call_list_select_first(&mut self) {
        if self.calls.items.is_empty() {
            return;
        }
        let gaps = self.call_gap_render_positions();
        let cur = self.call_current_rendered(&gaps);
        let final_r = Self::first_gap_crossed(&gaps, cur, 0).unwrap_or(0);
        self.apply_call_rendered(final_r, &gaps);
    }

    /// Jump toward the last row, clamping on the first gap row crossed.
    pub fn call_list_select_last(&mut self) {
        if self.calls.items.is_empty() {
            return;
        }
        let gaps = self.call_gap_render_positions();
        let rendered_max = self.call_rendered_len(&gaps).saturating_sub(1);
        let cur = self.call_current_rendered(&gaps);
        let final_r = Self::first_gap_crossed(&gaps, cur, rendered_max).unwrap_or(rendered_max);
        self.apply_call_rendered(final_r, &gaps);
    }

    /// Rendered (gap-aware) selection index for the Calls list. Mirrors
    /// `tx_list_rendered_selected`.
    pub fn call_list_rendered_selected(&self) -> Option<usize> {
        self.call_list_rendered_selected_with(&self.call_gap_render_positions())
    }

    /// Same, for callers that already hold `call_gap_render_positions()`.
    pub fn call_list_rendered_selected_with(&self, gaps: &[(usize, u64)]) -> Option<usize> {
        if let Some(sel_lo) = self.call_gap_selected
            && let Some(g_idx) = gaps.iter().position(|(_, lo)| *lo == sel_lo)
        {
            return Some(Self::gap_rendered_idx(gaps, g_idx));
        }
        let c = self.calls.state.selected()?;
        Some(Self::tx_pos_to_rendered(c, gaps))
    }
}

impl AddressInfoState {
    // ---- Transfers tab ----

    /// Merge rows newest-first, deduping on `(tx_hash, event_index)`. A row
    /// already present is upgraded field-wise (WS rows arrive without
    /// tx_index / timestamp / token metadata). Returns the number of new rows.
    pub fn merge_transfers(&mut self, incoming: Vec<TokenTransfer>) -> usize {
        let mut added = 0;
        for t in incoming {
            if self.transfer_keys.contains_key(&t.key()) {
                if let Some(i) = self.transfer_position(&t)
                    && upgrade_transfer(&mut self.transfers.items[i], &t)
                {
                    // tx_index changed: re-slot so same-block order stays sorted.
                    let row = self.transfers.items.remove(i);
                    self.insert_transfer_sorted(row);
                }
                continue;
            }
            self.transfer_keys.insert(t.key(), t.block_number);
            self.insert_transfer_sorted(t);
            added += 1;
        }
        added
    }

    fn insert_transfer_sorted(&mut self, t: TokenTransfer) {
        let idx = self.transfers.items.partition_point(|x| {
            TokenTransfer::cmp_newest_first(x, &t) == std::cmp::Ordering::Less
        });
        self.transfers.items.insert(idx, t);
    }

    fn transfer_position(&self, t: &TokenTransfer) -> Option<usize> {
        let block = *self.transfer_keys.get(&t.key())?;
        let start = Self::first_index_with_key(&self.transfers.items, |r| r.block_number, block)?;
        self.transfers.items[start..]
            .iter()
            .take_while(|r| r.block_number == block)
            .position(|r| r.key() == t.key())
            .map(|i| start + i)
    }

    pub fn note_transfer_scanned_range(&mut self, lo: u64, hi: u64) {
        crate::utils::merge_block_interval(&mut self.transfer_scanned_ranges, lo, hi);
    }

    /// Lowest block a transfers scan needs to reach: the deploy block when
    /// known, else genesis.
    pub fn transfer_floor(&self) -> u64 {
        self.deployment
            .as_ref()
            .map(|d| d.block_number)
            .unwrap_or(0)
    }

    /// True once the scanned ranges run contiguously from the floor up: the
    /// row count is then exact for everything below the top scanned block.
    pub fn transfers_fully_scanned(&self) -> bool {
        !self.transfer_scanned_ranges.is_empty() && self.transfer_gaps.is_empty()
    }

    /// Re-derive gaps from the scanned ranges. `fill_dispatched` survives only
    /// for a gap whose bounds are unchanged (a shrunk gap means its fill landed
    /// and the user may press Enter again). Drops a stale selection.
    pub fn refresh_transfer_gaps(&mut self) {
        let inflight: HashMap<u64, u64> = self
            .transfer_gaps
            .iter()
            .filter(|g| g.fill_dispatched)
            .map(|g| (g.lo_block, g.hi_block))
            .collect();
        let mut next = scanned_range_gaps(&self.transfer_scanned_ranges, self.transfer_floor());
        for g in next.iter_mut() {
            g.fill_dispatched = inflight.get(&g.lo_block) == Some(&g.hi_block);
        }
        self.transfer_gaps = next;
        if let Some(sel) = self.transfer_gap_selected
            && !self.transfer_gaps.iter().any(|g| g.lo_block == sel)
        {
            self.transfer_gap_selected = None;
        }
    }

    /// Land the selection somewhere useful after the first data arrives: the
    /// top row, or the only gap row when nothing has been found yet.
    pub fn ensure_transfer_selection(&mut self) {
        if self.transfer_gap_selected.is_some() || self.transfers.state.selected().is_some() {
            return;
        }
        if !self.transfers.items.is_empty() {
            self.transfers.select_first();
        } else if let Some((_, lo)) = self.transfer_gap_render_positions().first() {
            self.transfer_gap_selected = Some(*lo);
        }
    }

    /// `(row_idx, lo_block)` per gap sorted by row index: a gap renders above
    /// the first row older than it (after the last row for the bottom gap).
    /// Gaps sharing a position render newest first.
    pub fn transfer_gap_render_positions(&self) -> Vec<(usize, u64)> {
        let mut out: Vec<(usize, u64)> = self
            .transfer_gaps
            .iter()
            .map(|g| {
                let p = self
                    .transfers
                    .items
                    .partition_point(|r| r.block_number > g.hi_block);
                (p, g.lo_block)
            })
            .collect();
        out.sort_by_key(|(p, lo)| (*p, std::cmp::Reverse(*lo)));
        out
    }

    pub fn selected_transfer_gap(&self) -> Option<&TransferGap> {
        let lo = self.transfer_gap_selected?;
        self.transfer_gaps.iter().find(|g| g.lo_block == lo)
    }

    pub fn transfer_list_rendered_selected_with(&self, gaps: &[(usize, u64)]) -> Option<usize> {
        if let Some(sel_lo) = self.transfer_gap_selected
            && let Some(g_idx) = gaps.iter().position(|(_, lo)| *lo == sel_lo)
        {
            return Some(Self::gap_rendered_idx(gaps, g_idx));
        }
        let i = self.transfers.state.selected()?;
        Some(Self::tx_pos_to_rendered(i, gaps))
    }

    fn transfer_current_rendered(&self, gaps: &[(usize, u64)]) -> usize {
        self.transfer_list_rendered_selected_with(gaps)
            .unwrap_or_else(|| Self::tx_pos_to_rendered(0, gaps))
    }

    fn apply_transfer_rendered(&mut self, r: usize, gaps: &[(usize, u64)]) {
        match rendered_row(r, gaps) {
            RenderedRow::Gap(lo) => self.transfer_gap_selected = Some(lo),
            RenderedRow::Item(i) => {
                self.transfer_gap_selected = None;
                self.transfers.state.select(Some(i));
            }
        }
    }

    /// Move by `delta` rendered rows, clamping on the first gap row crossed.
    /// Unlike the Calls list this works with zero rows: a lone gap row must
    /// still be selectable so Enter can start the first scan.
    fn transfer_list_step(&mut self, delta: i64) {
        let gaps = self.transfer_gap_render_positions();
        let len = self.transfers.items.len() + gaps.len();
        if len == 0 || delta == 0 {
            return;
        }
        let cur = self.transfer_current_rendered(&gaps);
        let target = ((cur as i64) + delta).clamp(0, len as i64 - 1) as usize;
        let final_r = Self::first_gap_crossed(&gaps, cur, target).unwrap_or(target);
        self.apply_transfer_rendered(final_r, &gaps);
    }

    pub fn transfer_list_next(&mut self) {
        self.transfer_list_step(1);
    }

    pub fn transfer_list_previous(&mut self) {
        self.transfer_list_step(-1);
    }

    pub fn transfer_list_scroll_by(&mut self, delta: i64) {
        self.transfer_list_step(delta);
    }

    pub fn transfer_list_select_first(&mut self) {
        let gaps = self.transfer_gap_render_positions();
        if self.transfers.items.len() + gaps.len() == 0 {
            return;
        }
        let cur = self.transfer_current_rendered(&gaps);
        let final_r = Self::first_gap_crossed(&gaps, cur, 0).unwrap_or(0);
        self.apply_transfer_rendered(final_r, &gaps);
    }

    pub fn transfer_list_select_last(&mut self) {
        let gaps = self.transfer_gap_render_positions();
        let len = self.transfers.items.len() + gaps.len();
        if len == 0 {
            return;
        }
        let cur = self.transfer_current_rendered(&gaps);
        let final_r = Self::first_gap_crossed(&gaps, cur, len - 1).unwrap_or(len - 1);
        self.apply_transfer_rendered(final_r, &gaps);
    }

    /// Palette slots for counterparties seen twice or more; the viewed address
    /// is pinned to the sender style so both columns mark it the same way.
    pub fn update_transfer_color_map(&mut self, is_known: impl Fn(&Felt) -> bool) {
        if self.transfer_color_processed_len == self.transfers.items.len() {
            return;
        }
        let Some(viewed) = self.context else {
            return;
        };
        self.transfer_color_map.set_sender(viewed);
        self.transfer_counts.clear();
        for t in &self.transfers.items {
            for a in [t.from, t.to] {
                if a == viewed {
                    continue;
                }
                let count = self.transfer_counts.entry(a).or_insert(0);
                *count += 1;
                if *count == 2 && !is_known(&a) {
                    self.transfer_color_map.register(a);
                }
            }
        }
        self.transfer_color_processed_len = self.transfers.items.len();
    }
}

/// Fill the zero/None fields of `existing` from `incoming`. Returns true when
/// `tx_index` changed (the row's sort position may have moved).
fn upgrade_transfer(existing: &mut TokenTransfer, incoming: &TokenTransfer) -> bool {
    let mut reslot = false;
    if existing.tx_index == 0 && incoming.tx_index != 0 {
        existing.tx_index = incoming.tx_index;
        reslot = true;
    }
    if existing.timestamp == 0 {
        existing.timestamp = incoming.timestamp;
    }
    if existing.symbol.is_none() {
        existing.symbol.clone_from(&incoming.symbol);
    }
    if existing.decimals.is_none() {
        existing.decimals = incoming.decimals;
    }
    if existing.value_usd.is_none() {
        existing.value_usd = incoming.value_usd;
    }
    reslot
}

/// What a gap-aware rendered index points at: a gap row (keyed by its `lo`
/// nonce/block) or a position in the underlying items list.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RenderedRow {
    Gap(u64),
    Item(usize),
}

/// Inverse of `tx_pos_to_rendered`. `gaps` is `(item_pos, lo)` sorted by
/// `item_pos`; each gap renders directly above its item.
pub fn rendered_row(r: usize, gaps: &[(usize, u64)]) -> RenderedRow {
    let mut gaps_before = 0;
    for (g_idx, (p, lo)) in gaps.iter().enumerate() {
        match (p + g_idx).cmp(&r) {
            std::cmp::Ordering::Equal => return RenderedRow::Gap(*lo),
            std::cmp::Ordering::Less => gaps_before += 1,
            std::cmp::Ordering::Greater => break,
        }
    }
    RenderedRow::Item(r - gaps_before)
}

/// Upgrade an existing tx summary with better data from an incoming one.
/// Returns `true` if `called_contracts` was filled in (was empty, is now
/// populated). Callers use this to invalidate the Txs-tab color cache,
/// whose length-keyed fast path would otherwise miss the in-place change.
pub fn upgrade_tx_summary(existing: &mut AddressTxSummary, incoming: &AddressTxSummary) -> bool {
    if existing.block_number == 0 && incoming.block_number > 0 {
        existing.block_number = incoming.block_number;
    }
    if existing.status == "?" && incoming.status != "?" {
        existing.status.clone_from(&incoming.status);
    }
    if existing.total_fee_fri == 0 && incoming.total_fee_fri > 0 {
        existing.total_fee_fri = incoming.total_fee_fri;
    }
    if existing.timestamp == 0 && incoming.timestamp > 0 {
        existing.timestamp = incoming.timestamp;
    }
    if existing.endpoint_names.is_empty() && !incoming.endpoint_names.is_empty() {
        existing.endpoint_names.clone_from(&incoming.endpoint_names);
    }
    let called_contracts_filled =
        existing.called_contracts.is_empty() && !incoming.called_contracts.is_empty();
    if called_contracts_filled {
        existing
            .called_contracts
            .clone_from(&incoming.called_contracts);
    }
    if existing.sender.is_none() && incoming.sender.is_some() {
        existing.sender = incoming.sender;
    }
    if existing.tip == 0 && incoming.tip > 0 {
        existing.tip = incoming.tip;
    }
    called_contracts_filled
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::types::AddressTxSummary;
    use starknet::core::types::Felt;

    fn transfer(block: u64, tx_index: u64, event_index: u64) -> TokenTransfer {
        TokenTransfer {
            token: Felt::from(7u64),
            from: Felt::from(1u64),
            to: Felt::from(2u64),
            amount_low: 1,
            amount_high: 0,
            tx_hash: Felt::from(block * 1000 + tx_index),
            block_number: block,
            tx_index,
            event_index,
            timestamp: 0,
            symbol: None,
            decimals: None,
            value_usd: None,
        }
    }

    #[test]
    fn scanned_range_gaps_cover_bottom_and_middle() {
        assert!(scanned_range_gaps(&[], 0).is_empty());
        let gaps = scanned_range_gaps(&[(100, 200), (301, 400)], 0);
        assert_eq!(
            gaps.iter()
                .map(|g| (g.lo_block, g.hi_block))
                .collect::<Vec<_>>(),
            vec![(0, 99), (201, 300)]
        );
        // Floor at/above the lowest scanned block: no bottom gap.
        let gaps = scanned_range_gaps(&[(100, 200)], 100);
        assert!(gaps.is_empty());
        let gaps = scanned_range_gaps(&[(100, 200)], 150);
        assert!(gaps.is_empty());
        // Adjacent ranges are not a gap.
        assert!(scanned_range_gaps(&[(0, 10), (11, 20)], 0).is_empty());
    }

    #[test]
    fn merge_transfers_dedups_sorts_and_upgrades() {
        let mut st = AddressInfoState::default();
        assert_eq!(
            st.merge_transfers(vec![transfer(10, 0, 1), transfer(12, 3, 0)]),
            2
        );
        // Duplicate key, but carrying tx_index: upgraded in place, no new row.
        let mut better = transfer(10, 0, 1);
        better.tx_index = 5;
        better.timestamp = 99;
        assert_eq!(st.merge_transfers(vec![better]), 0);
        assert_eq!(st.merge_transfers(vec![transfer(11, 0, 0)]), 1);
        let blocks: Vec<u64> = st.transfers.items.iter().map(|t| t.block_number).collect();
        assert_eq!(blocks, vec![12, 11, 10]);
        let row = &st.transfers.items[2];
        assert_eq!((row.tx_index, row.timestamp), (5, 99));
    }

    #[test]
    fn transfer_gap_rows_render_between_and_below_rows() {
        let mut st = AddressInfoState::default();
        st.merge_transfers(vec![transfer(500, 0, 0), transfer(150, 0, 0)]);
        st.note_transfer_scanned_range(100, 200);
        st.note_transfer_scanned_range(400, 600);
        st.refresh_transfer_gaps();
        // Bottom gap [0,99] renders after both rows; middle gap [201,399] between them.
        assert_eq!(st.transfer_gap_render_positions(), vec![(1, 201), (2, 0)]);
        assert_eq!(st.transfer_gaps.len(), 2);

        st.ensure_transfer_selection();
        assert_eq!(st.transfers.state.selected(), Some(0));
        st.transfer_list_next();
        assert_eq!(st.transfer_gap_selected, Some(201));
        st.transfer_list_next();
        assert_eq!(st.transfers.state.selected(), Some(1));
        assert_eq!(st.transfer_gap_selected, None);
        st.transfer_list_select_last();
        assert_eq!(st.transfer_gap_selected, Some(0));

        // A fill that closes the middle gap drops it and keeps the selection sane.
        st.transfer_gap_selected = Some(201);
        st.note_transfer_scanned_range(201, 399);
        st.refresh_transfer_gaps();
        assert_eq!(st.transfer_gaps.len(), 1);
        assert_eq!(st.transfer_gap_selected, None);
    }

    #[test]
    fn lone_gap_row_is_selectable_without_rows() {
        let mut st = AddressInfoState::default();
        st.note_transfer_scanned_range(900, 1000);
        st.refresh_transfer_gaps();
        st.ensure_transfer_selection();
        assert_eq!(st.transfer_gap_selected, Some(0));
        assert_eq!(
            st.transfer_list_rendered_selected_with(&st.transfer_gap_render_positions()),
            Some(0)
        );
    }

    fn summary(nonce: u64, block: u64) -> AddressTxSummary {
        AddressTxSummary {
            hash: Felt::from(nonce + 1),
            nonce,
            block_number: block,
            timestamp: 0,
            endpoint_names: String::new(),
            total_fee_fri: 0,
            tip: 0,
            tx_type: "INVOKE".into(),
            status: "OK".into(),
            sender: None,
            called_contracts: Vec::new(),
        }
    }

    fn state_with(txs: Vec<AddressTxSummary>) -> AddressInfoState {
        let mut s = AddressInfoState::default();
        s.txs.items = txs;
        s
    }

    #[test]
    fn no_gap_when_contiguous() {
        let state = state_with(vec![summary(10, 100), summary(11, 102), summary(12, 104)]);
        assert!(state.detect_unfilled_gaps().is_empty());
    }

    #[test]
    fn no_gap_for_small_span() {
        // Gap spans only 30 blocks — RPC small-gap path handles this.
        let state = state_with(vec![summary(10, 100), summary(16, 130)]);
        assert!(state.detect_unfilled_gaps().is_empty());
    }

    #[test]
    fn detects_wide_gap_even_with_few_missing() {
        // Only 2 missing nonces but span = 100 blocks > SMALL_GAP_SPAN_BLOCKS.
        // This is the medium-gap case that would otherwise be silently dropped.
        let state = state_with(vec![summary(10, 100), summary(13, 200)]);
        let gaps = state.detect_unfilled_gaps();
        assert_eq!(gaps.len(), 1);
        let g = &gaps[0];
        assert_eq!(g.lo_nonce, 10);
        assert_eq!(g.hi_nonce, 13);
        assert_eq!(g.missing_count, 2);
        assert!(!g.fill_dispatched);
    }

    #[test]
    fn detects_gap_by_block_span() {
        let state = state_with(vec![summary(10, 100), summary(21, 2000)]);
        let gaps = state.detect_unfilled_gaps();
        assert_eq!(gaps.len(), 1);
        assert_eq!(gaps[0].lo_nonce, 10);
        assert_eq!(gaps[0].hi_nonce, 21);
        assert_eq!(gaps[0].missing_count, 10);
    }

    #[test]
    fn gap_threshold_boundary() {
        // Exactly at the threshold: span == SMALL_GAP_SPAN_BLOCKS → not deferred.
        let state = state_with(vec![
            summary(10, 100),
            summary(12, 100 + SMALL_GAP_SPAN_BLOCKS),
        ]);
        assert!(state.detect_unfilled_gaps().is_empty());

        // One over → deferred.
        let state = state_with(vec![
            summary(10, 100),
            summary(12, 100 + SMALL_GAP_SPAN_BLOCKS + 1),
        ]);
        assert_eq!(state.detect_unfilled_gaps().len(), 1);
    }

    #[test]
    fn contract_addresses_never_report_gap() {
        let mut state = state_with(vec![summary(10, 100), summary(200, 500)]);
        state.is_contract = true;
        assert!(state.detect_unfilled_gaps().is_empty());
    }

    #[test]
    fn reset_clears_unfilled_gaps() {
        // Guards the 'r'-refresh path: `NavigateToAddress` calls `reset()`,
        // and the next load re-detects from scratch.
        let mut state = state_with(vec![summary(10, 100), summary(21, 2000)]);
        state.unfilled_gaps.push(UnfilledGap {
            lo_nonce: 10,
            hi_nonce: 21,
            lo_block: 100,
            hi_block: 2000,
            missing_count: 10,
            fill_dispatched: true,
        });
        state.sanity_check_dispatched = true;
        state.clear();
        assert!(state.unfilled_gaps.is_empty());
        assert!(!state.sanity_check_dispatched);
    }

    #[test]
    fn detects_every_qualifying_gap() {
        let state = state_with(vec![
            summary(10, 100),
            summary(20, 1100),  // 9 missing, span 1000 → deferred
            summary(22, 1110),  // 1 missing, span 10 → small (skipped)
            summary(200, 5000), // 177 missing, span 3890 → deferred
            summary(201, 5001),
        ]);
        let gaps = state.detect_unfilled_gaps();
        assert_eq!(gaps.len(), 2);
        let los: Vec<u64> = gaps.iter().map(|g| g.lo_nonce).collect();
        assert_eq!(los, vec![10, 22]);
    }

    #[test]
    fn refresh_preserves_dispatched_flag_when_gap_unchanged() {
        let mut state = state_with(vec![summary(10, 100), summary(21, 2000)]);
        state.unfilled_gaps = state.detect_unfilled_gaps();
        state.unfilled_gaps[0].fill_dispatched = true;
        state.refresh_unfilled_gaps();
        assert_eq!(state.unfilled_gaps.len(), 1);
        assert!(state.unfilled_gaps[0].fill_dispatched);
    }

    #[test]
    fn refresh_clears_dispatched_flag_when_gap_shrinks() {
        // Mimics a lazy fill landing: the chunk arrived from the top of the
        // gap (nonces just below `hi_nonce`), shrinking the gap from its
        // newer edge. Same `lo_nonce`, lower `hi_nonce` → flag should clear
        // so the user can Enter on the residual to load the next chunk.
        let mut state = state_with(vec![summary(10, 100), summary(21, 2000)]);
        state.unfilled_gaps = state.detect_unfilled_gaps();
        state.unfilled_gaps[0].fill_dispatched = true;

        // Add a contiguous chunk at the top of the gap (nonces 18, 19, 20).
        // Their blocks are close to 2000 (top edge) but the older boundary
        // gap (10..18) still has a wide block span → still deferred.
        state.txs.items.push(summary(18, 1980));
        state.txs.items.push(summary(19, 1990));
        state.txs.items.push(summary(20, 1995));
        state.refresh_unfilled_gaps();

        assert_eq!(state.unfilled_gaps.len(), 1);
        assert_eq!(state.unfilled_gaps[0].lo_nonce, 10);
        assert_eq!(state.unfilled_gaps[0].hi_nonce, 18);
        assert!(!state.unfilled_gaps[0].fill_dispatched);
    }

    #[test]
    fn refresh_drops_stale_gap_selection() {
        let mut state = state_with(vec![summary(10, 100), summary(21, 2000)]);
        state.unfilled_gaps = state.detect_unfilled_gaps();
        state.gap_selected = Some(10);
        // Replace tx data so the gap closes.
        state.txs.items = (10..=21).map(|n| summary(n, 100 + n)).collect();
        state.refresh_unfilled_gaps();
        assert!(state.unfilled_gaps.is_empty());
        assert!(state.gap_selected.is_none());
    }

    /// Build a state with a single deferred gap between hi/lo nonces. Tx list
    /// is sorted nonce-descending, matching the live-render layout.
    fn state_one_gap() -> AddressInfoState {
        // Nonces 100, 99, 30, 29 — gap between 30 and 99 (block span 4790).
        let mut state = state_with(vec![
            summary(100, 5000),
            summary(99, 4990),
            summary(30, 200),
            summary(29, 190),
        ]);
        state.refresh_unfilled_gaps();
        assert_eq!(state.unfilled_gaps.len(), 1);
        state.txs.state.select(Some(0));
        state
    }

    #[test]
    fn next_lands_on_gap_when_crossing_forward() {
        let mut state = state_one_gap();
        // Start at nonce 99 (tx idx 1), the tx just above the gap.
        state.txs.state.select(Some(1));
        state.tx_list_next();
        assert_eq!(state.gap_selected, Some(30));
        assert_eq!(state.txs.state.selected(), Some(1));
    }

    #[test]
    fn next_off_gap_lands_on_lo_nonce_tx_no_dispatch() {
        let mut state = state_one_gap();
        state.gap_selected = Some(30);
        state.tx_list_next();
        // Cleared gap selection, landed on the lo_nonce tx (nonce 30, idx 2).
        assert_eq!(state.gap_selected, None);
        assert_eq!(state.txs.state.selected(), Some(2));
        // Crucially, no fill_dispatched — Enter alone triggers fills.
        assert!(!state.unfilled_gaps[0].fill_dispatched);
    }

    #[test]
    fn previous_lands_on_gap_when_crossing_backward() {
        let mut state = state_one_gap();
        // Start at nonce 30 (tx idx 2), the tx just below the gap.
        state.txs.state.select(Some(2));
        state.tx_list_previous();
        assert_eq!(state.gap_selected, Some(30));
        assert_eq!(state.txs.state.selected(), Some(2));
    }

    #[test]
    fn previous_off_gap_lands_on_hi_nonce_tx() {
        let mut state = state_one_gap();
        state.gap_selected = Some(30);
        state.tx_list_previous();
        assert_eq!(state.gap_selected, None);
        assert_eq!(state.txs.state.selected(), Some(1));
    }

    #[test]
    fn scroll_by_clamps_on_gap_forward() {
        let mut state = state_one_gap();
        state.txs.state.select(Some(0));
        state.tx_list_scroll_by(10);
        // Should clamp on the gap row, not jump past it.
        assert_eq!(state.gap_selected, Some(30));
    }

    #[test]
    fn scroll_by_clamps_on_gap_backward() {
        let mut state = state_one_gap();
        state.txs.state.select(Some(3));
        state.tx_list_scroll_by(-10);
        assert_eq!(state.gap_selected, Some(30));
    }

    #[test]
    fn select_first_clamps_on_gap_from_below() {
        let mut state = state_one_gap();
        state.txs.state.select(Some(3));
        state.tx_list_select_first();
        assert_eq!(state.gap_selected, Some(30));
    }

    #[test]
    fn select_last_clamps_on_gap_from_above() {
        let mut state = state_one_gap();
        state.txs.state.select(Some(0));
        state.tx_list_select_last();
        assert_eq!(state.gap_selected, Some(30));
    }

    #[test]
    fn navigation_is_a_noop_with_no_gap() {
        let mut state = state_with(vec![summary(10, 100), summary(11, 102)]);
        state.refresh_unfilled_gaps();
        assert!(state.unfilled_gaps.is_empty());
        state.txs.state.select(Some(0));
        state.tx_list_next();
        assert_eq!(state.gap_selected, None);
        assert_eq!(state.txs.state.selected(), Some(1));
    }

    /// Two deferred gaps — single-step navigation should pause at each.
    fn state_two_gaps() -> AddressInfoState {
        // Nonces 200, 199, 100, 99, 30, 29 — gaps between 100..199 and 30..99.
        let mut state = state_with(vec![
            summary(200, 9010),
            summary(199, 9000),
            summary(100, 5000),
            summary(99, 4990),
            summary(30, 200),
            summary(29, 190),
        ]);
        state.refresh_unfilled_gaps();
        assert_eq!(state.unfilled_gaps.len(), 2);
        state.txs.state.select(Some(0));
        state
    }

    #[test]
    fn scroll_by_clamps_on_first_of_multiple_gaps_forward() {
        let mut state = state_two_gaps();
        state.tx_list_scroll_by(20);
        // First gap encountered going down from the top is the upper one.
        assert_eq!(state.gap_selected, Some(100));
    }

    #[test]
    fn scroll_by_from_first_gap_clamps_on_second() {
        let mut state = state_two_gaps();
        state.gap_selected = Some(100);
        state.tx_list_scroll_by(20);
        assert_eq!(state.gap_selected, Some(30));
    }

    #[test]
    fn step_walks_through_each_gap() {
        let mut state = state_two_gaps();
        // Start on the tx just above the upper gap (nonce 199, idx 1).
        state.txs.state.select(Some(1));
        state.tx_list_next(); // lands on upper gap
        assert_eq!(state.gap_selected, Some(100));
        state.tx_list_next(); // off gap → tx with nonce 100 (idx 2)
        assert_eq!(state.gap_selected, None);
        assert_eq!(state.txs.state.selected(), Some(2));
        state.tx_list_next(); // tx idx 3 (nonce 99) — just above lower gap
        assert_eq!(state.txs.state.selected(), Some(3));
        state.tx_list_next(); // lands on lower gap
        assert_eq!(state.gap_selected, Some(30));
    }

    #[test]
    fn rendered_selected_tracks_gap_and_tx_state() {
        let mut state = state_two_gaps();
        // Tx idx 0 (nonce 200) → rendered 0.
        state.txs.state.select(Some(0));
        assert_eq!(state.tx_list_rendered_selected(), Some(0));
        // Tx idx 3 (nonce 99) → rendered 4 (one upper-gap row in front of it).
        state.txs.state.select(Some(3));
        assert_eq!(state.tx_list_rendered_selected(), Some(4));
        // Selecting the upper gap → rendered 2.
        state.gap_selected = Some(100);
        assert_eq!(state.tx_list_rendered_selected(), Some(2));
        // Selecting the lower gap → rendered 5.
        state.gap_selected = Some(30);
        assert_eq!(state.tx_list_rendered_selected(), Some(5));
    }

    fn call_summary(sender: Felt, block: u64) -> ContractCallSummary {
        ContractCallSummary {
            tx_hash: Felt::from(block * 31 + 1),
            sender,
            function_name: String::new(),
            block_number: block,
            timestamp: 0,
            total_fee_fri: 0,
            status: "OK".into(),
            nonce: None,
            tip: 0,
            inner_targets: Vec::new(),
        }
    }

    fn call_at(block: u64) -> ContractCallSummary {
        call_summary(Felt::from(0xC0FFEE_u64), block)
    }

    fn call_state_with(calls: Vec<ContractCallSummary>) -> AddressInfoState {
        let mut s = AddressInfoState::default();
        // Live merge keeps calls block-descending; mirror that here.
        s.calls.items = calls;
        s.calls
            .items
            .sort_by(|a, b| b.block_number.cmp(&a.block_number));
        s
    }

    fn call_with_hash(hash: u64, block: u64) -> ContractCallSummary {
        ContractCallSummary {
            tx_hash: Felt::from(hash),
            ..call_at(block)
        }
    }

    #[test]
    fn insert_call_keeps_block_order_and_dedups() {
        let mut s = AddressInfoState::default();
        s.merge_calls(vec![call_at(100), call_at(300)]);
        assert!(s.insert_call(call_with_hash(7, 200)));
        // Same block as an existing row lands after it, like a stable sort of a push.
        assert!(s.insert_call(call_with_hash(8, 300)));
        assert!(!s.insert_call(call_with_hash(7, 999)));
        let blocks: Vec<u64> = s.calls.items.iter().map(|c| c.block_number).collect();
        assert_eq!(blocks, vec![300, 300, 200, 100]);
        assert_eq!(s.calls.items[1].tx_hash, Felt::from(8_u64));

        assert_eq!(s.call_position(Felt::from(8_u64)), Some(1));
        assert_eq!(s.call_position(Felt::from(7_u64)), Some(2));
        assert_eq!(s.call_position(call_at(100).tx_hash), Some(3));
        assert_eq!(s.call_position(Felt::from(9_u64)), None);

        s.find_call_mut(Felt::from(7_u64)).unwrap().tip = 5;
        let rows = s.calls_by_hash(&[Felt::from(7_u64), Felt::from(9_u64)]);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].tip, 5);
    }

    #[test]
    fn call_gap_positions_pick_first_row_of_the_block() {
        let mut s = AddressInfoState::default();
        let top = 1_000 + 2 * CALL_GAP_SPAN_BLOCKS;
        s.merge_calls(vec![call_at(1_000), call_with_hash(2, 1_000), call_at(top)]);
        s.call_gaps = vec![
            UnfilledCallGap {
                lo_block: 42, // below every row: renders last
                hi_block: 43,
                fill_dispatched: false,
            },
            UnfilledCallGap {
                lo_block: 1_000,
                hi_block: top,
                fill_dispatched: false,
            },
        ];
        assert_eq!(s.call_gap_render_positions(), vec![(1, 1_000), (3, 42)]);
    }

    #[test]
    fn tx_gap_positions_search_by_nonce() {
        let mut s = AddressInfoState::default();
        s.merge_tx_summaries(vec![
            summary(10, 100),
            summary(30, 3_000),
            summary(21, 2_000),
        ]);
        let gap = |lo: u64| UnfilledGap {
            lo_nonce: lo,
            hi_nonce: 21,
            lo_block: 100,
            hi_block: 2_000,
            missing_count: 1,
            fill_dispatched: false,
        };
        s.unfilled_gaps = vec![gap(10), gap(5)];
        assert_eq!(s.gap_render_positions(), vec![(2, 10)]);
    }

    /// `cargo test call_insert_and_lookup_timing -- --ignored --nocapture`
    #[test]
    #[ignore]
    fn call_insert_and_lookup_timing() {
        let n = 50_000u64;
        let mut s = AddressInfoState::default();
        s.merge_calls((0..n).map(|i| call_with_hash(i, i)).collect());

        let mut old = s.calls.items.clone();
        let t = std::time::Instant::now();
        for i in 0..100u64 {
            let c = call_with_hash(n + 10_000 + i, n - 1 - i * 37);
            if !old.iter().any(|x| x.tx_hash == c.tx_hash) {
                old.push(c);
                old.sort_by_key(|x| std::cmp::Reverse(x.block_number));
            }
        }
        let old_ins = t.elapsed() / 100;

        let t = std::time::Instant::now();
        for i in 0..1_000u64 {
            assert!(s.insert_call(call_with_hash(n + i, n - 1 - i * 37)));
        }
        let ins = t.elapsed() / 1_000;
        let t = std::time::Instant::now();
        for i in 0..1_000u64 {
            assert!(s.find_call_mut(Felt::from(n + i)).is_some());
        }
        let find = t.elapsed() / 1_000;
        eprintln!(
            "50k rows: push+sort {old_ins:?}/row → insert_call {ins:?}/row, find_call_mut {find:?}/row"
        );
    }

    #[test]
    fn no_call_gap_when_dense() {
        let state = call_state_with(vec![call_at(1000), call_at(1010), call_at(1020)]);
        assert!(state.detect_unfilled_call_gaps().is_empty());
    }

    #[test]
    fn no_call_gap_for_zero_block_stubs() {
        // WS stubs land with block 0 before enrichment — they must not anchor a
        // spurious "0..N" gap.
        let state = call_state_with(vec![call_at(0), call_at(1_000_000)]);
        assert!(state.detect_unfilled_call_gaps().is_empty());
    }

    #[test]
    fn detects_call_gap_by_block_span() {
        // Recent batch (~1.2M) vs stale cache (~1.0M): a ~195k-block hole.
        let state = call_state_with(vec![
            call_at(1_200_500),
            call_at(1_200_490),
            call_at(1_005_000),
            call_at(1_004_990),
        ]);
        let gaps = state.detect_unfilled_call_gaps();
        assert_eq!(gaps.len(), 1);
        assert_eq!(gaps[0].lo_block, 1_005_000);
        assert_eq!(gaps[0].hi_block, 1_200_490);
        assert!(!gaps[0].fill_dispatched);
    }

    #[test]
    fn call_gap_threshold_boundary() {
        // Exactly at the threshold → not a gap.
        let state = call_state_with(vec![call_at(1000), call_at(1000 + CALL_GAP_SPAN_BLOCKS)]);
        assert!(state.detect_unfilled_call_gaps().is_empty());
        // One block over → a gap.
        let state = call_state_with(vec![
            call_at(1000),
            call_at(1000 + CALL_GAP_SPAN_BLOCKS + 1),
        ]);
        assert_eq!(state.detect_unfilled_call_gaps().len(), 1);
    }

    #[test]
    fn tracked_region_flags_every_unscanned_range() {
        let mut state = call_state_with(vec![call_at(1_500), call_at(1_800), call_at(2_600)]);
        state.note_call_tracked_from(1_000);
        state.note_scanned_call_range(1_000, 2_000);
        state.note_scanned_call_range(2_500, 3_000);
        // A 500-block hole is far under the span threshold, but it's inside
        // the tracked region, so it's a gap bordered by the scanned blocks.
        let gaps = state.detect_unfilled_call_gaps();
        assert_eq!(gaps.len(), 1);
        assert_eq!((gaps[0].lo_block, gaps[0].hi_block), (2_000, 2_500));
        // It renders between the calls above and below the hole.
        state.call_gaps = gaps;
        assert_eq!(state.call_gap_render_positions(), vec![(1, 2_000)]);

        state.note_scanned_call_range(2_000, 2_500);
        assert!(state.detect_unfilled_call_gaps().is_empty());
    }

    #[test]
    fn tracked_region_floor_and_older_rows() {
        // Older cached rows below the tracked floor keep the span rule.
        let mut state = call_state_with(vec![call_at(100), call_at(900), call_at(2_000)]);
        state.note_call_tracked_from(1_000);
        state.note_scanned_call_range(1_500, 3_000);
        let gaps = state.detect_unfilled_call_gaps();
        assert_eq!(
            gaps.len(),
            1,
            "only the unscanned bottom of the tracked region"
        );
        assert_eq!((gaps[0].lo_block, gaps[0].hi_block), (999, 1_500));

        // The floor only moves down.
        state.note_call_tracked_from(5_000);
        assert_eq!(state.call_tracked_from, Some(1_000));
    }

    #[test]
    fn refresh_preserves_call_gap_dispatched_when_unchanged() {
        let mut state = call_state_with(vec![call_at(1_005_000), call_at(1_200_490)]);
        state.call_gaps = state.detect_unfilled_call_gaps();
        state.call_gaps[0].fill_dispatched = true;
        state.refresh_unfilled_call_gaps();
        assert_eq!(state.call_gaps.len(), 1);
        assert!(state.call_gaps[0].fill_dispatched);
    }

    #[test]
    fn refresh_clears_call_gap_dispatched_when_gap_shrinks() {
        // A lazy fill landed: the chunk arrived from the top of the gap,
        // shrinking it from the newer edge (same lo_block, lower hi_block).
        // The dispatched flag should clear so the residual row is fillable.
        let mut state = call_state_with(vec![call_at(1_005_000), call_at(1_200_490)]);
        state.call_gaps = state.detect_unfilled_call_gaps();
        state.call_gaps[0].fill_dispatched = true;
        // A row just below the old top edge (490 blocks down ≤ threshold), so
        // the upper sub-range stays contiguous and only the wide lower hole
        // remains — the gap shrank from its newer edge.
        state.calls.items.push(call_at(1_200_000));
        state
            .calls
            .items
            .sort_by(|a, b| b.block_number.cmp(&a.block_number));
        state.refresh_unfilled_call_gaps();
        assert_eq!(state.call_gaps.len(), 1);
        assert_eq!(state.call_gaps[0].lo_block, 1_005_000);
        assert_eq!(state.call_gaps[0].hi_block, 1_200_000);
        assert!(!state.call_gaps[0].fill_dispatched);
    }

    #[test]
    fn refresh_drops_stale_call_gap_selection() {
        let mut state = call_state_with(vec![call_at(1_005_000), call_at(1_200_490)]);
        state.refresh_unfilled_call_gaps();
        state.call_gap_selected = Some(1_005_000);
        // Backfill closes the gap with intervening blocks.
        state.calls.items = (0..=20)
            .map(|i| call_at(1_005_000 + i * (CALL_GAP_SPAN_BLOCKS / 2)))
            .collect();
        state
            .calls
            .items
            .sort_by(|a, b| b.block_number.cmp(&a.block_number));
        state.refresh_unfilled_call_gaps();
        assert!(state.call_gaps.is_empty());
        assert!(state.call_gap_selected.is_none());
    }

    #[test]
    fn scanned_range_suppresses_call_gap() {
        let mut state = call_state_with(vec![call_at(1_005_000), call_at(1_200_490)]);
        assert_eq!(state.detect_unfilled_call_gaps().len(), 1);
        // After fully scanning the range, the (genuinely sparse) hole must not
        // resurface as a gap.
        state.note_scanned_call_range(1_005_000, 1_200_490);
        assert!(state.detect_unfilled_call_gaps().is_empty());
    }

    #[test]
    fn note_scanned_call_range_merges_overlaps() {
        let mut state = AddressInfoState::default();
        state.note_scanned_call_range(100, 200);
        state.note_scanned_call_range(150, 300); // overlaps → merge
        state.note_scanned_call_range(301, 400); // adjacent → merge
        state.note_scanned_call_range(1000, 1100); // disjoint
        assert_eq!(state.scanned_call_ranges, vec![(100, 400), (1000, 1100)]);
    }

    /// Single deferred call gap; list is block-descending like the live render.
    fn call_state_one_gap() -> AddressInfoState {
        // Blocks 200000, 199000, 200, 190 — only the 200..199000 hole exceeds
        // CALL_GAP_SPAN_BLOCKS, so exactly one gap (lo_block 200).
        let mut state = call_state_with(vec![
            call_at(200_000),
            call_at(199_000),
            call_at(200),
            call_at(190),
        ]);
        state.refresh_unfilled_call_gaps();
        assert_eq!(state.call_gaps.len(), 1);
        assert_eq!(state.call_gaps[0].lo_block, 200);
        state.calls.state.select(Some(0));
        state
    }

    #[test]
    fn call_next_lands_on_gap_when_crossing_forward() {
        let mut state = call_state_one_gap();
        // Start at block 4990 (call idx 1), just above the gap.
        state.calls.state.select(Some(1));
        state.call_list_next();
        assert_eq!(state.call_gap_selected, Some(200));
        assert_eq!(state.calls.state.selected(), Some(1));
    }

    #[test]
    fn call_next_off_gap_lands_on_lo_block_call() {
        let mut state = call_state_one_gap();
        state.call_gap_selected = Some(200);
        state.call_list_next();
        assert_eq!(state.call_gap_selected, None);
        assert_eq!(state.calls.state.selected(), Some(2));
    }

    #[test]
    fn call_scroll_by_clamps_on_gap_forward() {
        let mut state = call_state_one_gap();
        state.calls.state.select(Some(0));
        state.call_list_scroll_by(10);
        assert_eq!(state.call_gap_selected, Some(200));
    }

    #[test]
    fn call_rendered_selected_tracks_gap_and_call_state() {
        let mut state = call_state_one_gap();
        // Call idx 0 (block 5000) → rendered 0.
        state.calls.state.select(Some(0));
        assert_eq!(state.call_list_rendered_selected(), Some(0));
        // Call idx 2 (block 200) → rendered 3 (one gap row in front of it).
        state.calls.state.select(Some(2));
        assert_eq!(state.call_list_rendered_selected(), Some(3));
        // Selecting the gap → rendered 2.
        state.call_gap_selected = Some(200);
        assert_eq!(state.call_list_rendered_selected(), Some(2));
    }

    #[test]
    fn call_nav_is_noop_with_no_gap() {
        let mut state = call_state_with(vec![call_at(1000), call_at(1010)]);
        state.refresh_unfilled_call_gaps();
        assert!(state.call_gaps.is_empty());
        state.calls.state.select(Some(0));
        state.call_list_next();
        assert_eq!(state.call_gap_selected, None);
        assert_eq!(state.calls.state.selected(), Some(1));
    }

    /// Builds a synthetic call list with `n` rows. ~30% of senders are unique
    /// one-shots; the remaining 70% are drawn from a pool of 50 repeating
    /// senders (the "hot" set the color map should pick up). Hot-pool indices
    /// step by a coprime stride so every slot gets used as `n` grows.
    fn build_call_corpus(n: usize) -> Vec<ContractCallSummary> {
        const POOL_SIZE: usize = 50;
        let hot_pool: Vec<Felt> = (0..POOL_SIZE)
            .map(|i| Felt::from(0x1000_u64 + i as u64))
            .collect();
        let mut hot_cursor: usize = 0;
        (0..n)
            .map(|i| {
                let sender = if i % 10 < 3 {
                    Felt::from(0x9000_0000_u64 + i as u64)
                } else {
                    let s = hot_pool[hot_cursor % POOL_SIZE];
                    // 7 is coprime to 50 → cycles through every slot.
                    hot_cursor = hot_cursor.wrapping_add(7);
                    s
                };
                call_summary(sender, (n - i) as u64)
            })
            .collect()
    }

    #[test]
    #[ignore = "release-mode microbenchmark; run with `cargo test --release bench_update_call_color_map -- --ignored --nocapture`"]
    fn bench_update_call_color_map() {
        // Marked `#[ignore]` so the default `cargo test` run (typically debug)
        // doesn't flake on the 100ms ceiling. Run explicitly in release with
        // `--ignored` to print timings.
        let sizes = [1_000usize, 5_000, 10_000, 25_000];
        for &n in &sizes {
            let corpus = build_call_corpus(n);

            // Cold rebuild: full rescan from scratch (worst case — every merge).
            let mut state = AddressInfoState::default();
            state.calls.items = corpus.clone();
            let t0 = std::time::Instant::now();
            state.update_call_color_map(|_| false);
            let cold = t0.elapsed();

            // Warm path: items unchanged, length-equal early-out.
            let t1 = std::time::Instant::now();
            for _ in 0..1_000 {
                state.update_call_color_map(|_| false);
            }
            let warm_avg = t1.elapsed() / 1_000;

            // Sanity: the hot pool of 50 repeated senders should all have
            // crossed the count==2 threshold and registered.
            let registered = state.call_color_map.slots_count();
            assert!(
                registered >= 50,
                "expected ≥50 registered (hot pool), got {} at n={}",
                registered,
                n
            );

            println!(
                "n={:>5} cold_rebuild={:>8.3?} warm_per_call={:>8.3?} registered={}",
                n, cold, warm_avg, registered
            );

            // Hard ceiling: even 25k items should rebuild well under 100 ms
            // on any modern machine. Anything above this means the design
            // has regressed.
            assert!(
                cold < std::time::Duration::from_millis(100),
                "cold rebuild for n={} took {:?}, exceeds 100 ms budget",
                n,
                cold
            );
        }
    }
}

#[cfg(test)]
mod rendered_row_tests {
    use super::*;

    #[test]
    fn no_gaps_is_identity() {
        assert_eq!(rendered_row(7, &[]), RenderedRow::Item(7));
    }

    #[test]
    fn gap_rows_and_items_interleave() {
        // Gaps above item 0 and item 5 render at rows 0 and 6.
        let gaps = [(0, 100), (5, 200)];
        assert_eq!(rendered_row(0, &gaps), RenderedRow::Gap(100));
        assert_eq!(rendered_row(1, &gaps), RenderedRow::Item(0));
        assert_eq!(rendered_row(5, &gaps), RenderedRow::Item(4));
        assert_eq!(rendered_row(6, &gaps), RenderedRow::Gap(200));
        assert_eq!(rendered_row(7, &gaps), RenderedRow::Item(5));
        assert_eq!(rendered_row(9, &gaps), RenderedRow::Item(7));
    }

    #[test]
    fn round_trips_with_tx_pos_to_rendered() {
        let gaps = [(2, 10), (2, 11), (9, 12)];
        for pos in 0..20 {
            let r = AddressInfoState::tx_pos_to_rendered(pos, &gaps);
            assert_eq!(rendered_row(r, &gaps), RenderedRow::Item(pos));
        }
    }
}