1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
//! Application state machine: view stack, navigation, and action dispatch.
//!
//! The `App` struct holds all UI state. Views are stacked (`view_stack`) and
//! navigated with `navigate_to(NavTarget)` — the single entry point for all
//! view transitions regardless of origin (search, visual mode, Enter, forward
//! history, etc.).
//!
//! Network responses arrive as `Action` variants and are handled by
//! `handle_action()`, which updates the appropriate view state struct.
pub mod actions;
pub mod input;
pub mod state;
pub mod views;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::mpsc;
use tracing::debug;
use crate::data::types::{AddressTxSummary, SnBlock, VoyagerLabelInfo};
use crate::network::prices::PriceClient;
use crate::network::ws::WsSubscriptionManager;
use crate::registry::SearchResult;
use crate::search::SearchEngine;
use crate::ui::widgets::stateful_list::StatefulList;
use actions::{Action, Source};
use starknet::core::types::Felt;
use state::{
ActiveQueries, ConnectionStatus, DataSources, Focus, InputMode, NavTarget, SourceStatus, View,
};
use views::{AddressInfoState, BlockDetailState, ClassInfoState, TxDetailState};
/// Maximum number of blocks retained in the main blocks list.
/// Applied consistently to both prepends (new blocks) and appends (older
/// blocks paginated in) to keep the list stable while the user navigates.
const MAX_BLOCKS: usize = 500;
/// A saved navigation location for the forward/back jump list (Ctrl+o / Ctrl+i).
#[derive(Debug, Clone)]
pub enum NavEntry {
Block(u64),
Transaction(starknet::core::types::Felt),
Address(starknet::core::types::Felt),
ClassHash(starknet::core::types::Felt),
}
/// Pending follow-up after a `BlockDetailLoaded` lands: jump to the first or
/// last tx of the freshly fetched block. Used by Ctrl+P / Ctrl+N in TxDetail
/// to wrap across block boundaries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TxBoundary {
First,
Last,
}
/// Tabs in the address info view.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AddressTab {
Transactions,
/// SNIP-9 outside executions where this address is the intender (issue #11).
MetaTxs,
Calls, // Incoming calls to this contract (for non-account contracts)
Balances,
/// ERC-20 transfers where this address is `from` or `to`.
Transfers,
Events,
ClassHistory, // Class hash upgrades over time
}
pub struct App {
// Navigation
pub view_stack: Vec<View>,
pub focus: Focus,
pub input_mode: InputMode,
pub should_quit: bool,
// Block list (home view)
pub blocks: StatefulList<SnBlock>,
pub latest_block_number: u64,
// View-specific state
pub block_detail: BlockDetailState,
pub tx_detail: TxDetailState,
pub address: AddressInfoState,
pub class: ClassInfoState,
// Search
pub search_input: String,
pub search_cursor: usize,
pub search_suggestions: Vec<SearchResult>,
pub search_selected: usize,
pub search_engine: Option<Arc<SearchEngine>>,
// Status
pub show_help: bool,
pub is_loading: bool,
pub loading_detail: Option<String>,
pub connection_status: ConnectionStatus,
pub error_message: Option<String>,
pub data_sources: DataSources,
pub active_queries: ActiveQueries,
// Pagination flags (prevent duplicate fetches)
pub fetching_older_blocks: bool,
/// Set when `G` on the blocks view triggers an older-blocks fetch, so
/// that once the fetch lands we re-snap the selection to the new last
/// item (without this, `G` stops 30 blocks short of the true bottom).
pub pending_bottom_jump: bool,
/// Set when Ctrl+P/Ctrl+N at a block boundary in TxDetail triggers a
/// neighbor-block fetch. Once the BlockDetail data lands, we honor this
/// by dispatching a follow-up FetchTransaction for that block's first or
/// last tx and staying in TxDetail.
pub pending_tx_boundary: Option<TxBoundary>,
/// Labels fetched from Voyager API at runtime (address → label info).
/// Used as a fallback when neither user labels nor known addresses have an entry.
pub voyager_labels: HashMap<starknet::core::types::Felt, VoyagerLabelInfo>,
/// Forward-decrypted Privacy Pool notes, keyed by `note_id`. Populated
/// by `Action::PrivateNotesIndexed` for users we hold a viewing key
/// for; consumed by the Privacy tab to annotate `EncNoteCreated`
/// events with decrypted amount/token/sender.
pub private_notes:
HashMap<starknet::core::types::Felt, crate::decode::privacy_sync::DecryptedNote>,
/// `nullifier → note_id` for incoming notes the user can spend.
/// Lets the Privacy tab label `NoteUsed` events as "user spent note
/// X" and link them back to the originating sender + amount.
pub private_nullifiers: HashMap<starknet::core::types::Felt, starknet::core::types::Felt>,
/// Set of users we've already kicked off a sync for in this session,
/// so we don't re-trigger on every tx open. Cleared on app restart;
/// the persisted SQLite cache provides cross-session memory.
pub private_notes_synced: std::collections::HashSet<starknet::core::types::Felt>,
/// On-chain ERC-20 metadata fetched for tokens not in the static
/// registry. Hydrated from SQLite on boot, extended at runtime when
/// the Privacy / Balances tab encounters a new token.
pub fetched_token_metadata:
HashMap<starknet::core::types::Felt, crate::data::token_metadata::TokenMeta>,
/// Tokens we've already dispatched a metadata fetch for this
/// session. Prevents N redundant `FetchTokenMetadata` actions when
/// the user opens many txs that share the same unknown token.
pub token_metadata_dispatched: std::collections::HashSet<starknet::core::types::Felt>,
// Channel to network task
pub action_tx: mpsc::UnboundedSender<Action>,
// Navigation history
/// Locations to revisit with Ctrl+i (populated by Ctrl+o / back navigation).
pub forward_history: Vec<NavEntry>,
/// Optional WebSocket subscription manager (present when APP_WS_URL is configured).
pub ws_manager: Option<WsSubscriptionManager>,
pub price_client: Option<Arc<PriceClient>>,
}
impl App {
pub fn new(action_tx: mpsc::UnboundedSender<Action>) -> Self {
Self {
view_stack: vec![View::Blocks],
focus: Focus::BlockList,
input_mode: InputMode::Normal,
should_quit: false,
blocks: StatefulList::new(),
latest_block_number: 0,
block_detail: BlockDetailState::default(),
tx_detail: TxDetailState::default(),
address: AddressInfoState::default(),
class: ClassInfoState::default(),
search_input: String::new(),
search_cursor: 0,
search_suggestions: Vec::new(),
search_selected: 0,
search_engine: None,
show_help: false,
is_loading: false,
loading_detail: None,
connection_status: ConnectionStatus::default(),
error_message: None,
data_sources: DataSources::default(),
active_queries: ActiveQueries::default(),
fetching_older_blocks: false,
pending_bottom_jump: false,
pending_tx_boundary: None,
voyager_labels: HashMap::new(),
private_notes: HashMap::new(),
private_nullifiers: HashMap::new(),
private_notes_synced: std::collections::HashSet::new(),
fetched_token_metadata: HashMap::new(),
token_metadata_dispatched: std::collections::HashSet::new(),
action_tx,
forward_history: Vec::new(),
ws_manager: None,
price_client: None,
}
}
fn filter_deployment_txs(
&mut self,
address: starknet::core::types::Felt,
txs: Vec<AddressTxSummary>,
) -> Vec<AddressTxSummary> {
self.address.filter_deployment_txs(address, txs)
}
fn dispatch_balance_price_fetch(&self) {
if self.price_client.is_none() {
return;
}
let tokens = crate::network::prices::TRACKED_TOKENS.clone();
if tokens.is_empty() {
return;
}
let _ = self
.action_tx
.send(Action::FetchTokenPricesToday { tokens });
}
/// On a freshly-loaded tx, kick off privacy-pool note sync for any
/// labelled user (one with a `viewing_keys.toml` entry) whose decrypted
/// notes might be referenced by `EncNoteCreated` events in this tx.
/// Idempotent per session — already-synced users are skipped (the
/// merged `private_notes` index stays in memory until the user quits).
fn dispatch_private_notes_sync(&mut self) {
let Some(engine) = &self.search_engine else {
return;
};
let registry = engine.registry();
// Cheap signal: only sync when the tx contains pool events. This
// catches the obvious cases (deposits, sends, joins, withdrawals).
// We could also sync on every privacy-tx open regardless, but
// syncing on a tx the user just looks at is the responsive
// moment.
let pool = *crate::decode::privacy::POOL_ADDRESS;
let touches_pool = self
.tx_detail
.decoded_events
.iter()
.any(|e| e.contract_address == pool);
if !touches_pool {
return;
}
let users: Vec<(starknet::core::types::Felt, starknet::core::types::Felt)> = registry
.iter_viewing_keys()
.filter(|(u, _)| !self.private_notes_synced.contains(u))
.map(|(u, k)| (u, **k))
.collect();
for (user, viewing_key) in users {
self.private_notes_synced.insert(user);
let _ = self
.action_tx
.send(Action::FetchPrivateNotes { user, viewing_key });
}
}
/// For every token in `tokens` that we don't already know
/// (registry-static or runtime-fetched) and haven't already
/// dispatched a fetch for this session, send
/// `Action::FetchTokenMetadata`. The network task replies with
/// `Action::TokenMetadataLoaded` and the result lands in
/// `fetched_token_metadata` for the next render.
fn dispatch_token_metadata_for_unknown_tokens<I>(&mut self, tokens: I)
where
I: IntoIterator<Item = starknet::core::types::Felt>,
{
let registry_known = |felt: &starknet::core::types::Felt| -> bool {
self.search_engine
.as_ref()
.map(|e| e.registry().get_decimals(felt).is_some())
.unwrap_or(false)
};
let mut seen = std::collections::HashSet::new();
for token in tokens {
if !seen.insert(token) {
continue;
}
if self.fetched_token_metadata.contains_key(&token) {
continue;
}
if registry_known(&token) {
continue;
}
if !self.token_metadata_dispatched.insert(token) {
continue;
}
let _ = self.action_tx.send(Action::FetchTokenMetadata { token });
}
}
/// Targeted version of `dispatch_private_notes_sync`: fires for the
/// specific address being opened, and only if we hold a viewing key
/// for it. Used by the address-info reducer so the Balances tab can
/// render private holdings the moment the address loads, without
/// the user having to drill into a tx first.
fn dispatch_private_notes_sync_for_address(&mut self, address: starknet::core::types::Felt) {
if self.private_notes_synced.contains(&address) {
return;
}
let Some(engine) = &self.search_engine else {
return;
};
let Some(vk) = engine.registry().viewing_key(&address) else {
return;
};
let viewing_key = **vk;
self.private_notes_synced.insert(address);
let _ = self.action_tx.send(Action::FetchPrivateNotes {
user: address,
viewing_key,
});
}
fn dispatch_tx_price_fetch(&self) {
if self.price_client.is_none() {
return;
}
let mut event_tokens: Vec<starknet::core::types::Felt> = self
.tx_detail
.decoded_events
.iter()
.map(|e| e.contract_address)
.filter(crate::network::prices::is_tracked)
.collect();
event_tokens.sort();
event_tokens.dedup();
if event_tokens.is_empty() {
return;
}
let _ = self.action_tx.send(Action::FetchTokenPricesToday {
tokens: event_tokens.clone(),
});
if let Some(ts) = self.tx_detail.block_timestamp {
let requests: Vec<_> = event_tokens.into_iter().map(|t| (t, ts)).collect();
let _ = self
.action_tx
.send(Action::FetchTokenPricesHistoric { requests });
}
}
pub fn current_view(&self) -> View {
*self.view_stack.last().unwrap_or(&View::Blocks)
}
pub fn push_view(&mut self, view: View) {
self.view_stack.push(view);
// Set focus based on view
match view {
View::Blocks => self.focus = Focus::BlockList,
View::BlockDetail => {
self.block_detail.txs.select_first();
self.focus = Focus::TxList;
}
View::TxDetail => self.focus = Focus::TxDetail,
View::AddressInfo => self.focus = Focus::AddressHistory,
View::ClassInfo => self.focus = Focus::ClassDetail,
}
}
pub fn pop_view(&mut self) {
if self.view_stack.len() > 1 {
// Unsubscribe from WS address subscriptions when leaving address view
if self.current_view() == View::AddressInfo {
self.unsubscribe_current_address();
}
self.view_stack.pop();
// Restore focus
match self.current_view() {
View::Blocks => self.focus = Focus::BlockList,
View::BlockDetail => self.focus = Focus::TxList,
View::TxDetail => self.focus = Focus::TxDetail,
View::AddressInfo => self.focus = Focus::AddressHistory,
View::ClassInfo => self.focus = Focus::ClassDetail,
}
}
}
/// Pop one view, saving the current location to the forward history (Ctrl+i can revisit it).
pub fn pop_view_saving_forward(&mut self) {
if self.view_stack.len() <= 1 {
return;
}
if let Some(entry) = self.current_nav_entry() {
self.forward_history.push(entry);
}
self.pop_view();
}
/// Unsubscribe WS for the currently viewed address, if any.
fn unsubscribe_current_address(&mut self) {
if let (Some(addr), Some(mgr)) = (self.address.context, &self.ws_manager)
&& self.address.ws_subscribed
{
mgr.unsubscribe_address(addr);
self.address.ws_subscribed = false;
}
}
/// Go to the Blocks root view, clearing all history. Quits if already at root.
pub fn go_to_root_or_quit(&mut self) {
if self.view_stack.len() > 1 {
// Unsubscribe from any active address WS subscription
if self.view_stack.contains(&View::AddressInfo) {
self.unsubscribe_current_address();
}
self.view_stack.truncate(1);
self.forward_history.clear();
self.focus = Focus::BlockList;
} else {
self.should_quit = true;
}
}
/// Dispatch the next forward-history entry. Returns the Action to fetch it.
pub fn navigate_forward(&mut self) -> Option<Action> {
let entry = self.forward_history.pop()?;
let target = match entry {
NavEntry::Block(n) => NavTarget::Block(n),
NavEntry::Transaction(h) => NavTarget::Transaction(h),
NavEntry::Address(a) => NavTarget::Address(a),
NavEntry::ClassHash(c) => NavTarget::ClassHash(c),
};
self.navigate_to(target)
}
/// Single entry point for all view navigation.
///
/// Clears any active visual mode, clears stale view state, pushes the
/// target view, sets loading state, and returns the fetch Action.
/// All navigation paths (search, visual mode, Enter, forward history,
/// nonce cycling, etc.) should go through this method.
pub fn navigate_to(&mut self, target: NavTarget) -> Option<Action> {
// Clear any active visual mode
self.tx_detail.visual_mode = false;
self.block_detail.visual_mode = false;
self.class.visual_mode = false;
self.address.visual_mode = false;
// Any explicit nav cancels a pending wrap-to-boundary.
self.pending_tx_boundary = None;
self.is_loading = true;
match target {
NavTarget::Block(n) => {
self.clear_block_detail();
self.push_view(View::BlockDetail);
Some(Action::FetchBlockDetail { number: n })
}
NavTarget::Transaction(h) => {
self.clear_tx_detail();
self.push_view(View::TxDetail);
Some(Action::FetchTransaction { hash: h })
}
NavTarget::Address(a) => {
// FetchAddressInfo handler sends NavigateToAddress internally,
// which does the view push + state clear in handle_action.
Some(Action::FetchAddressInfo { address: a })
}
NavTarget::ClassHash(c) => {
self.clear_class_info();
// FetchClassInfo handler sends NavigateToClassInfo internally.
Some(Action::FetchClassInfo { class_hash: c })
}
}
}
fn current_nav_entry(&self) -> Option<NavEntry> {
match self.current_view() {
View::BlockDetail => self
.block_detail
.block
.as_ref()
.map(|b| NavEntry::Block(b.number)),
View::TxDetail => self
.tx_detail
.transaction
.as_ref()
.map(|tx| NavEntry::Transaction(tx.hash())),
View::AddressInfo => self.address.context.map(NavEntry::Address),
View::ClassInfo => self.class.hash.map(NavEntry::ClassHash),
View::Blocks => None,
}
}
/// Send an `EnrichAddressTxs` for the rows currently visible in the
/// address Transactions tab that are missing endpoint names or timestamps.
///
/// Idempotent: the cache layer dedups in-flight requests and
/// `enrich_address_txs` itself drops hashes that already have data.
/// Safe to call on every scroll keystroke.
pub fn maybe_enrich_visible_address_txs(&self) {
if self.current_view() != View::AddressInfo {
return;
}
if !matches!(self.address.tab, AddressTab::Transactions) {
return;
}
let Some(address) = self.address.context else {
return;
};
let offset = self.address.txs_render_state.offset();
let hashes: Vec<_> = self
.address
.txs
.items
.iter()
.skip(offset)
.take(50)
.filter(|t| t.needs_enrichment())
.map(|t| t.hash)
.collect();
if !hashes.is_empty() {
let _ = self
.action_tx
.send(Action::EnrichAddressTxs { address, hashes });
}
}
/// Scroll the active address list by a delta and trigger viewport
/// enrichment for any rows newly exposed. Also re-arms older-tx
/// pagination, so Ctrl+D landing near the tail behaves like `j`/`G`
/// did when the same row gets selected via single-step or jump-to-end.
pub fn address_list_scroll_by(&mut self, delta: i64) {
match self.address.tab {
AddressTab::Transactions => {
self.address.tx_list_scroll_by(delta);
self.maybe_fetch_more_address_txs();
self.maybe_enrich_visible_address_txs();
}
AddressTab::Calls => {
self.address.call_list_scroll_by(delta);
self.maybe_fetch_more_address_txs();
}
AddressTab::MetaTxs => {
self.address.meta_txs.scroll_by(delta);
self.maybe_fetch_more_meta_txs();
}
AddressTab::Transfers => self.address.transfer_list_scroll_by(delta),
_ => {}
}
}
/// Scroll the tx list inside the BlockDetail view by a delta. Mirrors
/// `address_list_scroll_by` but for the per-block tx list — used by
/// Ctrl+U / Ctrl+D on the BlockDetail view.
pub fn block_detail_txs_scroll_by(&mut self, delta: i64) {
if self.block_detail.txs.items.is_empty() {
return;
}
self.block_detail.txs.scroll_by(delta);
}
/// Scroll the main blocks list by a delta, triggering older-block
/// pagination when the new selection nears the tail. Used by Ctrl+D /
/// Ctrl+U on the Blocks view.
pub fn blocks_scroll_by(&mut self, delta: i64) {
if self.blocks.items.is_empty() {
return;
}
self.blocks.scroll_by(delta);
self.maybe_fetch_older_blocks();
}
/// Dispatch the next MetaTxs page when the selection nears the end of the
/// list and pf-query signaled more data. Idempotent: guarded by
/// `fetching_meta_txs`.
pub fn maybe_fetch_more_meta_txs(&mut self) {
if !matches!(self.address.tab, AddressTab::MetaTxs) {
return;
}
if self.address.fetching_meta_txs || !self.address.meta_tx_has_more {
return;
}
if !self.address.meta_txs.is_near_bottom(5) {
return;
}
let Some(addr) = self.address.context else {
return;
};
let token = self.address.meta_tx_cursor_block;
let from_block = self.address.meta_tx_from_block;
let window_size = self.address.meta_tx_last_window;
self.address.fetching_meta_txs = true;
let _ = self.action_tx.send(Action::FetchAddressMetaTxs {
address: addr,
from_block,
continuation_token: token,
window_size,
limit: 50,
});
}
pub fn select_next(&mut self) {
match self.current_view() {
View::Blocks => {
self.blocks.next();
self.maybe_fetch_older_blocks();
}
View::BlockDetail => self.block_detail.txs.next(),
View::TxDetail => {
let s = self.tx_detail.active_scroll_mut();
*s = s.saturating_add(1);
}
View::ClassInfo => {
self.class.scroll = self.class.scroll.saturating_add(1);
}
View::AddressInfo => match self.address.tab {
AddressTab::Transactions => {
self.address.tx_list_next();
self.maybe_fetch_more_address_txs();
self.maybe_enrich_visible_address_txs();
}
AddressTab::Calls => {
self.address.call_list_next();
self.maybe_fetch_more_address_txs();
}
AddressTab::MetaTxs => {
self.address.meta_txs.next();
self.maybe_fetch_more_meta_txs();
}
AddressTab::Transfers => self.address.transfer_list_next(),
AddressTab::Events => self.address.events.next(),
AddressTab::ClassHistory => {
self.address.class_history_scroll = self
.address
.class_history_scroll
.saturating_add(1)
.min(self.address.class_history.len().saturating_sub(1));
}
AddressTab::Balances => {}
},
}
}
pub fn select_previous(&mut self) {
match self.current_view() {
View::Blocks => self.blocks.previous(),
View::BlockDetail => self.block_detail.txs.previous(),
View::TxDetail => {
let s = self.tx_detail.active_scroll_mut();
*s = s.saturating_sub(1);
}
View::ClassInfo => {
self.class.scroll = self.class.scroll.saturating_sub(1);
}
View::AddressInfo => match self.address.tab {
AddressTab::Transactions => {
self.address.tx_list_previous();
self.maybe_enrich_visible_address_txs();
}
AddressTab::Calls => self.address.call_list_previous(),
AddressTab::MetaTxs => self.address.meta_txs.previous(),
AddressTab::Transfers => self.address.transfer_list_previous(),
AddressTab::Events => self.address.events.previous(),
AddressTab::ClassHistory => {
self.address.class_history_scroll =
self.address.class_history_scroll.saturating_sub(1);
}
AddressTab::Balances => {}
},
}
}
pub fn select_first(&mut self) {
match self.current_view() {
View::Blocks => self.blocks.select_first(),
View::BlockDetail => self.block_detail.txs.select_first(),
View::TxDetail => {
*self.tx_detail.active_scroll_mut() = 0;
}
View::ClassInfo => {
self.class.scroll = 0;
}
View::AddressInfo => match self.address.tab {
AddressTab::Transactions => {
self.address.tx_list_select_first();
self.maybe_enrich_visible_address_txs();
}
AddressTab::Calls => self.address.call_list_select_first(),
AddressTab::MetaTxs => self.address.meta_txs.select_first(),
AddressTab::Transfers => self.address.transfer_list_select_first(),
AddressTab::Events => self.address.events.select_first(),
AddressTab::ClassHistory => {
self.address.class_history_scroll = 0;
}
AddressTab::Balances => {}
},
}
}
pub fn select_last(&mut self) {
match self.current_view() {
View::Blocks => {
self.blocks.select_last();
let was_fetching = self.fetching_older_blocks;
self.maybe_fetch_older_blocks();
// If G just kicked off an older-blocks fetch, remember that
// the user wanted the true bottom so we can re-snap once
// the paginated batch lands.
if !was_fetching && self.fetching_older_blocks {
self.pending_bottom_jump = true;
}
}
View::BlockDetail => self.block_detail.txs.select_last(),
View::TxDetail => {
*self.tx_detail.active_scroll_mut() = 999;
} // will be clamped by Paragraph
View::ClassInfo => {
self.class.scroll = 999;
}
View::AddressInfo => match self.address.tab {
AddressTab::Transactions => {
self.address.tx_list_select_last();
self.maybe_fetch_more_address_txs();
self.maybe_enrich_visible_address_txs();
}
AddressTab::Calls => {
self.address.call_list_select_last();
self.maybe_fetch_more_address_txs();
}
AddressTab::MetaTxs => {
self.address.meta_txs.select_last();
self.maybe_fetch_more_meta_txs();
}
AddressTab::Transfers => self.address.transfer_list_select_last(),
AddressTab::Events => self.address.events.select_last(),
AddressTab::ClassHistory => {
self.address.class_history_scroll =
self.address.class_history.len().saturating_sub(1);
}
AddressTab::Balances => {}
},
}
}
/// If the selection is near the bottom of the block list, fetch the next batch of older blocks.
fn maybe_fetch_older_blocks(&mut self) {
if self.fetching_older_blocks || self.blocks.items.is_empty() {
return;
}
// Trigger when within 5 items of the end
if self.blocks.is_near_bottom(5)
&& let Some(oldest) = self.blocks.items.last()
{
let before = oldest.number;
if before > 0 {
self.fetching_older_blocks = true;
let _ = self
.action_tx
.send(Action::FetchOlderBlocks { before, count: 30 });
}
}
}
/// If the selection is near the bottom of the address tx or calls list, fetch more.
fn maybe_fetch_more_address_txs(&mut self) {
if self.address.fetching_more_txs {
return;
}
let near_bottom = match self.address.tab {
AddressTab::Transactions => self.address.txs.is_near_bottom(5),
AddressTab::Calls => self.address.calls.is_near_bottom(5),
_ => false,
};
if !near_bottom {
return;
}
// Chronological pagination (older than oldest known block). Note: large
// nonce gaps (issue #10) are NOT auto-filled here — the user must press
// Enter on the gap row in the Transactions tab to dispatch the fill.
// Don't fetch if no source thinks there's more data.
if !self.address.has_more_data()
&& self.address.oldest_event_block.is_some()
&& self.address.sources_pending.is_empty()
{
return;
}
let cursor = self.address.pagination_cursor();
if let (Some(address), Some(before_block)) = (self.address.context, cursor)
&& before_block > 0
{
self.address.fetching_more_txs = true;
let _ = self.action_tx.send(Action::FetchMoreAddressTxs {
address,
before_block,
is_contract: self.address.is_contract,
});
}
}
/// Dispatch an on-demand nonce-gap fill for the currently selected gap row
/// in the address Transactions tab. Returns `true` if a fill was sent.
/// No-op if no gap is selected, no fill is in flight already, or there
/// is no current address.
pub fn dispatch_address_gap_fill(&mut self) -> bool {
let Some(address) = self.address.context else {
return false;
};
let Some(sel_lo) = self.address.gap_selected else {
return false;
};
let Some(gap) = self
.address
.unfilled_gaps
.iter_mut()
.find(|g| g.lo_nonce == sel_lo)
else {
return false;
};
if gap.fill_dispatched {
return false;
}
let gap_clone = gap.clone();
gap.fill_dispatched = true;
self.address.fetching_more_txs = true;
let _ = self.action_tx.send(Action::FillAddressNonceGaps {
address,
known_txs: self.address.txs.items.clone(),
gap: gap_clone,
});
true
}
/// Dispatch an on-demand backfill for the currently selected call-gap row
/// in the address Calls tab. Returns `true` if a fill was sent. No-op if no
/// call gap is selected, its fill is already in flight, or there is no
/// current address. Mirrors `dispatch_address_gap_fill`.
pub fn dispatch_address_call_gap_fill(&mut self) -> bool {
let Some(address) = self.address.context else {
return false;
};
let Some(sel_lo) = self.address.call_gap_selected else {
return false;
};
let Some(gap) = self
.address
.call_gaps
.iter_mut()
.find(|g| g.lo_block == sel_lo)
else {
return false;
};
if gap.fill_dispatched {
return false;
}
let gap_clone = gap.clone();
gap.fill_dispatched = true;
let _ = self.action_tx.send(Action::FillAddressCallGap {
address,
gap: gap_clone,
is_contract: self.address.is_contract,
});
true
}
/// Enter on a Transfers-tab gap row: backfill that block range. Returns
/// `true` if a fill was sent.
pub fn dispatch_address_transfer_gap_fill(&mut self) -> bool {
let Some(address) = self.address.context else {
return false;
};
let Some(sel_lo) = self.address.transfer_gap_selected else {
return false;
};
let Some(gap) = self
.address
.transfer_gaps
.iter_mut()
.find(|g| g.lo_block == sel_lo)
else {
return false;
};
if gap.fill_dispatched {
return false;
}
gap.fill_dispatched = true;
let (lo_block, hi_block) = (gap.lo_block, gap.hi_block);
self.address.fetching_transfers = true;
let _ = self.action_tx.send(Action::FillAddressTransferGap {
address,
lo_block,
hi_block,
});
true
}
/// On Transfers-tab entry (and on the poll tick when WS is down): scan
/// from the top scanned block to head. Idempotent per address visit via
/// `transfers_dispatched`.
pub fn maybe_fetch_address_transfers(&mut self) {
if self.address.tab != AddressTab::Transfers
|| self.address.transfers_dispatched
|| self.address.fetching_transfers
{
return;
}
let Some(address) = self.address.context else {
return;
};
self.address.transfers_dispatched = true;
self.address.fetching_transfers = true;
let _ = self.action_tx.send(Action::FetchAddressTransfers {
address,
floor_block: self.address.transfer_floor(),
});
}
/// Merge transfer rows into the tab, re-derive gaps, and fetch metadata
/// for any token the registry doesn't know.
fn merge_address_transfers(&mut self, rows: Vec<crate::data::types::TokenTransfer>) -> usize {
let tokens: Vec<Felt> = rows.iter().map(|r| r.token).collect();
// Rows the indexer left unpriced fall back to DefiLlama's day price;
// the client skips (token, day) pairs already cached.
let mut price_requests: Vec<(Felt, u64)> = rows
.iter()
.filter(|r| {
r.value_usd.is_none()
&& r.timestamp > 0
&& crate::network::prices::is_tracked(&r.token)
})
.map(|r| (r.token, r.timestamp))
.collect();
let added = self.address.merge_transfers(rows);
if added > 0 {
self.dispatch_token_metadata_for_unknown_tokens(tokens);
if self.price_client.is_some() && !price_requests.is_empty() {
price_requests.sort_unstable();
price_requests.dedup();
let _ = self.action_tx.send(Action::FetchTokenPricesHistoric {
requests: price_requests,
});
}
}
self.address.refresh_transfer_gaps();
self.address.ensure_transfer_selection();
added
}
/// Re-detect Calls-tab block-range gaps after a calls merge. Unlike the
/// nonce path there is no auto-fill — a block-range hole doesn't prove
/// missing calls, so every call gap waits for an explicit Enter.
fn refresh_address_call_gaps(&mut self) {
self.address.refresh_unfilled_call_gaps();
}
/// Refresh the address's nonce-gap list, then auto-dispatch fills for any
/// "tiny" gaps (≤ `AUTO_FILL_MAX_MISSING` missing nonces). Tiny gaps
/// shouldn't require user action — a 1-nonce hole in a sparse account is
/// trivial to fill and surfacing it as a "press Enter" row would just be
/// noise. Capped at `MAX_AUTO_FILLS_PER_REFRESH` per call to avoid
/// flooding the backends on accounts with many scattered holes;
/// remaining tiny gaps fire on the next refresh.
fn refresh_address_gaps_and_auto_fill(&mut self) {
use crate::app::views::address_info::{AUTO_FILL_MAX_MISSING, MAX_AUTO_FILLS_PER_REFRESH};
self.address.refresh_unfilled_gaps();
let Some(address) = self.address.context else {
return;
};
let to_fill: Vec<_> = self
.address
.unfilled_gaps
.iter()
.filter(|g| !g.fill_dispatched && g.missing_count <= AUTO_FILL_MAX_MISSING)
.take(MAX_AUTO_FILLS_PER_REFRESH)
.cloned()
.collect();
if to_fill.is_empty() {
return;
}
let known_txs = self.address.txs.items.clone();
for gap in to_fill {
if let Some(g) = self
.address
.unfilled_gaps
.iter_mut()
.find(|g| g.lo_nonce == gap.lo_nonce)
{
g.fill_dispatched = true;
}
self.address.fetching_more_txs = true;
let _ = self.action_tx.send(Action::FillAddressNonceGaps {
address,
known_txs: known_txs.clone(),
gap,
});
}
}
pub fn clear_block_detail(&mut self) {
self.block_detail.clear();
}
pub fn clear_tx_detail(&mut self) {
self.tx_detail.clear();
}
pub fn build_tx_nav_items(&mut self) {
let registry = self.search_engine.as_ref().map(|e| e.registry());
self.tx_detail.build_nav_items(
|felt| registry.as_ref().is_some_and(|r| r.resolve(felt).is_some()),
&self.private_notes,
&self.private_nullifiers,
);
}
pub fn tx_nav_step(&mut self, delta: i64) {
self.tx_detail.nav_step(delta);
}
pub fn clear_class_info(&mut self) {
self.class.clear();
}
pub fn build_class_nav_items(&mut self) {
self.class.build_nav_items();
}
pub fn class_nav_step(&mut self, delta: i64) {
self.class.nav_step(delta);
}
pub fn build_address_nav_items(&mut self) {
self.address.build_nav_items();
// Header changes include a newly-learned deploy block, which is the
// Transfers-tab gap floor.
self.address.refresh_transfer_gaps();
}
pub fn address_nav_step(&mut self, delta: i64) {
self.address.nav_step(delta);
}
/// Get the currently selected block (in blocks list view).
pub fn selected_block(&self) -> Option<&SnBlock> {
self.blocks.selected_item()
}
/// Get the currently selected transaction (in block detail view).
pub fn selected_transaction(&self) -> Option<&crate::data::types::SnTransaction> {
self.block_detail.txs.selected_item()
}
/// Update autocomplete suggestions based on current search input.
pub fn update_suggestions(&mut self) {
if let Some(engine) = &self.search_engine {
self.search_suggestions = engine.suggest(&self.search_input);
self.search_selected = 0;
}
}
/// Format an address using the registry (label if known, short hex otherwise).
/// Falls back to a Voyager-sourced label when the registry has no entry.
pub fn format_address(&self, address: &starknet::core::types::Felt) -> String {
if let Some(engine) = &self.search_engine {
let registry = engine.registry();
if registry.resolve(address).is_some() {
return registry.format_address(address);
}
}
// Voyager fallback
if let Some(label) = self.voyager_labels.get(address)
&& let Some(name) = &label.name
{
return format!("[{}] \u{2B21}", name); // ⬡ = Voyager-sourced
}
// Runtime-fetched ERC-20 metadata fallback. Uses a different
// marker (◇) so the user can tell the symbol came from an
// on-chain `symbol()` lookup rather than a curated label.
if let Some(meta) = self.fetched_token_metadata.get(address) {
return format!("[{}] \u{25C7}", meta.symbol);
}
if let Some(engine) = &self.search_engine {
engine.registry().format_address(address)
} else {
crate::ui::widgets::hex_display::short_address(address)
}
}
/// Decimals for a token, preferring the static registry over
/// runtime-fetched metadata. Used by amount formatters so unknown
/// tokens render with decimals as soon as the on-chain
/// `decimals()` call lands.
pub fn token_decimals(&self, token: &starknet::core::types::Felt) -> Option<u8> {
if let Some(engine) = &self.search_engine
&& let Some(d) = engine.registry().get_decimals(token)
{
return Some(d);
}
self.fetched_token_metadata.get(token).map(|m| m.decimals)
}
/// Bare token symbol (e.g. `"STRK"`, `"USDS"`) — registry first, then
/// runtime-fetched. Different from `format_address` which wraps the
/// label in brackets and adds source markers; this returns the
/// ticker plain so the Balances tab can render it in a fixed
/// table-style column.
pub fn token_symbol(&self, token: &starknet::core::types::Felt) -> Option<String> {
if let Some(engine) = &self.search_engine
&& let Some(name) = engine.registry().resolve(token)
{
return Some(name.to_string());
}
self.fetched_token_metadata
.get(token)
.map(|m| m.symbol.clone())
}
/// Resolve a tx hash to its user label, if any. Single registry lookup —
/// callers can derive both the displayed string and a style from the result.
pub fn resolve_tx(&self, hash: &starknet::core::types::Felt) -> Option<&str> {
self.search_engine.as_ref()?.registry().resolve_tx(hash)
}
/// Format an address showing both user and global labels (for detail views).
/// Falls back to a Voyager-sourced label when the registry has no entry.
pub fn format_address_full(&self, address: &starknet::core::types::Felt) -> String {
if let Some(engine) = &self.search_engine {
let registry = engine.registry();
if registry.resolve(address).is_some() {
return registry.format_address_full(address);
}
}
// Voyager fallback
if let Some(label) = self.voyager_labels.get(address)
&& let Some(name) = &label.name
{
return format!("[{}] \u{2B21}", name); // ⬡ = Voyager-sourced
}
// Runtime-fetched ERC-20 metadata fallback (mirrors format_address).
if let Some(meta) = self.fetched_token_metadata.get(address) {
return format!("[{}] \u{25C7}", meta.symbol);
}
if let Some(engine) = &self.search_engine {
engine.registry().format_address_full(address)
} else {
crate::ui::widgets::hex_display::short_address(address)
}
}
/// Handle a response action from the network task.
pub fn handle_action(&mut self, action: Action) {
match action {
Action::BlocksLoaded(blocks) => {
if let Some(first) = blocks.first() {
self.latest_block_number = first.number;
}
self.blocks = StatefulList::with_items(blocks);
if !self.blocks.items.is_empty() {
self.blocks.select_first();
}
self.is_loading = false;
self.fetching_older_blocks = false;
self.pending_bottom_jump = false;
}
Action::OlderBlocksLoaded(blocks) => {
// Preserve selection by block NUMBER across the append +
// truncate — index-based tracking silently drifts the user
// onto a different block when the list grows or shrinks.
let selected_number = self.blocks.selected_item().map(|b| b.number);
self.blocks.items.extend(blocks);
if self.blocks.items.len() > MAX_BLOCKS {
self.blocks.items.truncate(MAX_BLOCKS);
}
self.fetching_older_blocks = false;
if self.pending_bottom_jump {
// `G` asked for the true bottom; snap to the new last
// item now that pagination has landed.
self.blocks.select_last();
self.pending_bottom_jump = false;
} else if let Some(num) = selected_number
&& let Some(idx) = self.blocks.items.iter().position(|b| b.number == num)
{
self.blocks.state.select(Some(idx));
}
}
Action::NewBlock(block) => {
self.latest_block_number = block.number;
// Remember where the user was *before* mutating the list so
// we can either follow the tip (sel==0) or pin to the same
// block number (sel>0), robust against tail truncation.
let prior_sel = self.blocks.state.selected();
let selected_number = self.blocks.selected_item().map(|b| b.number);
// Deduplicate: if the head already has this block number
// (e.g. WS replay on reconnect), overwrite rather than
// insert a duplicate row.
if self.blocks.items.first().map(|b| b.number) == Some(block.number) {
self.blocks.items[0] = block;
} else {
self.blocks.items.insert(0, block);
}
if self.blocks.items.len() > MAX_BLOCKS {
self.blocks.items.truncate(MAX_BLOCKS);
}
match prior_sel {
// Follow the tip when unselected or already at the top.
None | Some(0) => {
if !self.blocks.items.is_empty() {
self.blocks.state.select(Some(0));
}
}
// Otherwise pin to the same block number so the user's
// highlighted row does not silently change under them.
Some(_) => {
if let Some(num) = selected_number {
if let Some(idx) =
self.blocks.items.iter().position(|b| b.number == num)
{
self.blocks.state.select(Some(idx));
} else {
// Block fell off the tail during truncation;
// clamp to the new last item.
self.blocks.select_last();
}
}
}
}
}
Action::BlockDetailLoaded {
block,
mut transactions,
mut endpoint_names,
mut tx_statuses,
mut meta_tx_info,
mut is_privacy_tx,
} => {
self.block_detail.block = Some(block);
// Reverse to show highest index first (descending order)
transactions.reverse();
endpoint_names.reverse();
tx_statuses.reverse();
meta_tx_info.reverse();
is_privacy_tx.reverse();
self.block_detail.txs = StatefulList::with_items(transactions);
self.block_detail.endpoint_names = endpoint_names;
self.block_detail.tx_statuses = tx_statuses;
self.block_detail.meta_tx_info = meta_tx_info;
self.block_detail.is_privacy_tx = is_privacy_tx;
// If a wrap-to-boundary is pending (Ctrl+P/N at the first/last
// tx of the prior block), pick the corresponding tx and stay
// in TxDetail by dispatching a follow-up FetchTransaction
// instead of pushing BlockDetail.
//
// Only honor the pending flag when the user is still in
// TxDetail. If they navigated away (Esc / h / q) while the
// neighbor block was loading, drop the flag and fall through
// to normal BlockDetail handling — otherwise we'd bounce them
// into an unexpected new tx.
if self.current_view() == View::TxDetail
&& let Some(boundary) = self.pending_tx_boundary.take()
{
let hash = match boundary {
TxBoundary::First => {
if !self.block_detail.txs.items.is_empty() {
self.block_detail.txs.select_first();
}
self.block_detail.txs.items.first().map(|t| t.hash())
}
TxBoundary::Last => {
if !self.block_detail.txs.items.is_empty() {
self.block_detail.txs.select_last();
}
self.block_detail.txs.items.last().map(|t| t.hash())
}
};
if let Some(hash) = hash {
// Keep is_loading true — the tx fetch will clear it.
let _ = self.action_tx.send(Action::FetchTransaction { hash });
return;
}
// Empty block on the other side — fall through to the
// normal BlockDetail push so the user lands on a sensible
// empty BlockDetail view rather than a stuck TxDetail.
}
// Drop any stale pending flag that wasn't consumed above.
self.pending_tx_boundary = None;
if !self.block_detail.txs.items.is_empty() {
self.block_detail.txs.select_first();
}
self.is_loading = false;
self.loading_detail = None;
// Push view if not already there (e.g., from search)
if self.current_view() != View::BlockDetail {
self.push_view(View::BlockDetail);
}
}
Action::TransactionLoaded {
transaction,
receipt,
decoded_events,
decoded_calls,
outside_executions,
block_timestamp,
block_gas_prices_fri,
block_status,
} => {
self.tx_detail.transaction = Some(transaction);
self.tx_detail.receipt = Some(receipt);
self.tx_detail.decoded_events = decoded_events;
self.tx_detail.decoded_calls = decoded_calls;
self.tx_detail.outside_executions = outside_executions;
self.tx_detail.block_timestamp = block_timestamp;
self.tx_detail.block_gas_prices_fri = block_gas_prices_fri;
self.tx_detail.block_status = block_status;
self.tx_detail.events_scroll = 0;
self.tx_detail.calls_scroll = 0;
self.tx_detail.trace_scroll = 0;
self.tx_detail.active_tab = crate::app::views::tx_detail::TxTab::default();
self.tx_detail.trace = None;
self.tx_detail.trace_loading = true;
self.tx_detail.visual_mode = false;
self.build_tx_nav_items();
self.is_loading = false;
self.loading_detail = None;
if self.current_view() != View::TxDetail {
self.push_view(View::TxDetail);
}
self.dispatch_tx_price_fetch();
self.dispatch_private_notes_sync();
}
Action::TransactionTraceLoaded { tx_hash, trace } => {
// Drop late-arriving traces for a tx the user has navigated
// away from (or replaced via a re-fetch).
let current_hash = self.tx_detail.transaction.as_ref().map(|t| t.hash());
if current_hash == Some(tx_hash) {
self.tx_detail.trace = trace;
// Always clear the loading flag, even on failure (None) —
// otherwise the Trace tab gets stuck on "loading…".
self.tx_detail.trace_loading = false;
// Rebuild nav so trace addresses become reachable in `v` mode.
self.build_tx_nav_items();
}
}
Action::TokenMetadataLoaded {
token,
meta: Some(m),
} => {
tracing::debug!(
token = %format!("{:#x}", token),
symbol = %m.symbol,
decimals = m.decimals,
"Token metadata indexed"
);
self.fetched_token_metadata.insert(token, m);
}
Action::TokenMetadataLoaded { meta: None, .. } => {
// Failed lookup is recorded only via `token_metadata_dispatched`
// (set at dispatch time) so we don't re-fire this session.
}
Action::PrivateNotesIndexed {
user,
notes,
nullifiers,
} => {
// Merge the labelled user's freshly-decrypted notes into
// the global note_id → DecryptedNote index. Late arrivals
// are fine to merge whether or not the user is still
// viewing the originating tx — they cost nothing if the
// active view doesn't reference the matching note_ids.
tracing::info!(
user = %format!("{:#x}", user),
count = notes.len(),
nullifiers = nullifiers.len(),
"Privacy notes indexed"
);
let new_tokens: Vec<starknet::core::types::Felt> =
notes.iter().map(|n| n.token).collect();
for n in notes {
self.private_notes.insert(n.note_id, n);
}
for (nul, nid) in nullifiers {
self.private_nullifiers.insert(nul, nid);
}
// Kick off on-chain decimals + symbol lookup for any
// token in the synced notes that we don't know about
// yet — without this, unknown tokens render as raw u128.
self.dispatch_token_metadata_for_unknown_tokens(new_tokens);
// Rebuild tx-detail nav items so decrypted/spent-note
// participants (counterparty/user/token rendered in the
// Privacy tab) become selectable via `v` once the sync
// lands. Only relevant if we're currently looking at a tx.
if self.tx_detail.transaction.is_some() {
self.build_tx_nav_items();
}
}
Action::NavigateToAddress { address } => {
// Push view immediately — show cached data while fresh data loads
self.address.clear();
self.address.context = Some(address);
self.is_loading = true;
self.loading_detail = Some("Fetching address info...".into());
if self.current_view() != View::AddressInfo {
self.push_view(View::AddressInfo);
}
// Start streaming new txs/events via WS if available
if let Some(mgr) = &self.ws_manager {
mgr.subscribe_address(address);
self.address.ws_subscribed = true;
}
}
Action::AddressInfoLoaded {
info,
decoded_events,
tx_summaries,
contract_calls,
} => {
// Guard: ignore stale results from a previously navigated address.
if let Some(ctx) = self.address.context
&& ctx != info.address
{
return; // stale result for a different address — discard
}
let address = info.address;
self.address.context = Some(address);
// Kick off privacy-pool sync for this address if we hold
// a viewing key for it. Drives the Balances tab's
// "Private holdings" section without needing the user
// to drill into a tx first.
self.dispatch_private_notes_sync_for_address(address);
// Detect contract vs account
let is_contract =
info.nonce == starknet::core::types::Felt::ZERO && info.class_hash.is_some();
self.address.is_contract = is_contract;
// A real class hash proves the address is deployed — clear any
// "not deployed" note a prior (class-less) emit may have set.
if info.class_hash.is_some() {
self.address.not_deployed = false;
}
// Preserve any balances that may have already arrived — the
// balance task runs in parallel with the nonce/class_hash
// fetch and can land first, and every callsite constructs
// `SnAddressInfo` with an empty `token_balances` by default.
let preserved_balances = self
.address
.info
.as_ref()
.map(|i| i.token_balances.clone())
.unwrap_or_default();
// Only update info if it has real data
let mut info = info;
if info.token_balances.is_empty() && !preserved_balances.is_empty() {
info.token_balances = preserved_balances;
}
// Clamp the incoming nonce against whatever we've already
// observed — a WS `AddressTxsStreamed` can arrive before
// this initial RPC-loaded info and bump the header nonce
// past the (now slightly stale) RPC read. Without this
// clamp, the RPC value would overwrite the more-recent
// streamed value and the header would regress.
if let Some(existing) = self.address.info.as_ref()
&& crate::utils::felt_to_u64(&existing.nonce)
> crate::utils::felt_to_u64(&info.nonce)
{
info.nonce = existing.nonce;
}
let balance_tokens: Vec<starknet::core::types::Felt> = info
.token_balances
.iter()
.map(|b| b.token_address)
.collect();
if info.nonce != starknet::core::types::Felt::ZERO
|| !info.token_balances.is_empty()
|| info.class_hash.is_some()
|| self.address.info.is_none()
{
self.address.info = Some(info);
}
// Kick off metadata lookup for any token in this
// address's balances that the static registry doesn't
// know about. Cheap (1-2 round-trips per token, deduped
// via `token_metadata_dispatched`), and makes the
// Balances tab render unknown ERC-20s with proper
// decimals + symbol on the next frame.
self.dispatch_token_metadata_for_unknown_tokens(balance_tokens);
if !decoded_events.is_empty() {
let had_selection = self.address.events.state.selected().is_some();
self.address.events.items = decoded_events;
if !had_selection {
self.address.events.select_first();
}
}
// Merge txs (dedup + upgrade existing entries with better data)
let tx_summaries = self.filter_deployment_txs(address, tx_summaries);
self.address.merge_tx_summaries(tx_summaries);
// Track oldest block for pagination (from both txs and calls)
let oldest_from_txs = self
.address
.txs
.items
.iter()
.filter(|t| t.block_number > 0)
.map(|t| t.block_number)
.min();
let oldest_from_calls = self
.address
.calls
.items
.iter()
.filter(|c| c.block_number > 0)
.map(|c| c.block_number)
.min();
if let Some(oldest) = oldest_from_txs.into_iter().chain(oldest_from_calls).min() {
self.address.oldest_event_block = Some(
self.address
.oldest_event_block
.map_or(oldest, |old| old.min(oldest)),
);
}
// Update contract calls (merge across sources, not replace).
//
// Calls can arrive from two paths for the same tx_hash:
// - Dune `starknet.calls` — authoritative and richer (resolved
// function_name, accurate fee).
// - pf-query shared window scan — supplementary, may arrive
// first if Dune is slow/unavailable.
//
// Previously the reducer skipped any new row whose tx_hash was
// already present, which silently dropped Dune's richer data
// when pf-query arrived first. Route both sources through
// `deduplicate_contract_calls` which merges function_name
// (joined), fills missing fee/timestamp, and preserves the
// superset — so neither source can hide the other's data.
if !contract_calls.is_empty() {
self.address.merge_calls(contract_calls);
if self.address.calls.state.selected().is_none()
&& !self.address.calls.items.is_empty()
{
self.address.calls.select_first();
}
// Update cursor from calls for contracts
if let Some(min_b) = self
.address
.calls
.items
.iter()
.filter(|c| c.block_number > 0)
.map(|c| c.block_number)
.min()
{
self.address.oldest_event_block = Some(
self.address
.oldest_event_block
.map_or(min_b, |old| old.min(min_b)),
);
self.address.dune_has_more = true;
self.address.rpc_has_more = true;
}
// Surface any block-range hole between the freshly-fetched
// recent window and older cached calls as a fillable gap.
self.refresh_address_call_gaps();
}
// Set default tab based on contract type
if self.address.tab == AddressTab::Transactions
&& is_contract
&& self.address.txs.items.is_empty()
{
self.address.tab = AddressTab::Calls;
}
// Don't clear loading here — let AddressTxsStreamed source
// completion tracking handle it for the parallel flow.
// Only clear if no sources are pending (e.g. cache-only load).
if self.address.sources_pending.is_empty() {
self.is_loading = false;
self.loading_detail = None;
}
if self.current_view() != View::AddressInfo {
self.push_view(View::AddressInfo);
}
self.build_address_nav_items();
// Lazily enrich visible txs that are missing endpoint/timestamp data
if let Some(address) = self.address.context {
let offset = self.address.txs_render_state.offset();
let hashes: Vec<_> = self
.address
.txs
.items
.iter()
.skip(offset)
.take(50)
.filter(|t| t.needs_enrichment())
.map(|t| t.hash)
.collect();
if !hashes.is_empty() {
let _ = self
.action_tx
.send(Action::EnrichAddressTxs { address, hashes });
}
// Detect any large nonce gaps in cached data and defer
// them to on-demand fill (issue #10). Endpoint enrichment
// + small gap fill still run immediately from cache.
if !self.address.is_contract
&& !self.address.txs.items.is_empty()
&& !self.address.sanity_check_dispatched
&& let Some(info) = &self.address.info
{
let current_nonce = crate::utils::felt_to_u64(&info.nonce);
if current_nonce > 0 {
self.refresh_address_gaps_and_auto_fill();
self.address.sanity_check_dispatched = true;
let _ = self.action_tx.send(Action::EnrichAddressEndpoints {
address,
current_nonce,
known_txs: self.address.txs.items.clone(),
});
}
}
}
}
Action::MoreAddressTxsLoaded {
address,
tx_summaries,
contract_calls,
oldest_block,
has_more,
} => {
if self.address.context == Some(address) {
let tx_summaries = self.filter_deployment_txs(address, tx_summaries);
self.address.merge_tx_summaries(tx_summaries);
// Merge contract calls across sources (Dune + pf-query) —
// see `merge_calls` for why this is a field-level merge
// rather than a hash-based replace.
self.address.merge_calls(contract_calls);
self.address.oldest_event_block = Some(oldest_block);
self.address.dune_cursor_block = Some(oldest_block);
self.address.rpc_cursor_block = Some(oldest_block);
self.address.dune_has_more = has_more;
self.address.rpc_has_more = has_more;
self.refresh_address_call_gaps();
}
self.address.fetching_more_txs = false;
}
Action::AddressMetaTxsLoaded {
address,
summaries,
next_token,
next_window_size,
} => {
if self.address.context == Some(address) {
// Merge by hash to avoid dupes across pages.
let mut seen: std::collections::HashSet<_> =
self.address.meta_txs.items.iter().map(|m| m.hash).collect();
for s in summaries {
if seen.insert(s.hash) {
self.address.meta_txs.items.push(s);
}
}
self.address.meta_txs.items.sort_by(|a, b| {
b.block_number
.cmp(&a.block_number)
.then(b.tx_index.cmp(&a.tx_index))
});
if !self.address.meta_txs.items.is_empty()
&& self.address.meta_txs.state.selected().is_none()
{
self.address.meta_txs.select_first();
}
self.address.meta_tx_cursor_block = next_token;
self.address.meta_tx_has_more = next_token.is_some();
// Persist adapted window size so the next ExtendDown
// dispatch (auto-page or user-scroll) picks up where this
// page left off.
if let Some(w) = next_window_size {
self.address.meta_tx_last_window = w;
}
}
self.address.fetching_meta_txs = false;
// Progressive fill: keep paging until the visible list has
// `AUTO_FILL_TARGET` rows, or pf-query runs out of blocks to
// scan (`meta_tx_has_more == false`), or the user navigates
// away (session-token cancellation tears down the in-flight
// fetch). No page-count cap — a sparse address with zero
// classified meta-txs will walk back to deploy block rather
// than silently under-report. Once auto-fill stops, further
// pagination is strictly on-demand via
// `maybe_fetch_more_meta_txs` on scroll-near-bottom, so the
// history-exhausted and user-continuation paths converge.
use crate::app::views::address_info::AUTO_FILL_TARGET;
if self.address.context == Some(address)
&& self.address.meta_tx_has_more
&& self.address.meta_txs.items.len() < AUTO_FILL_TARGET
{
let next = self.address.meta_tx_cursor_block;
let from_block = self.address.meta_tx_from_block;
let window_size = self.address.meta_tx_last_window;
self.address.fetching_meta_txs = true;
let _ = self.action_tx.send(Action::FetchAddressMetaTxs {
address,
from_block,
continuation_token: next,
window_size,
limit: 50,
});
}
}
Action::AddressMetaTxsCacheLoaded { address, summaries } => {
if self.address.context == Some(address) {
let mut seen: std::collections::HashSet<_> =
self.address.meta_txs.items.iter().map(|m| m.hash).collect();
for s in &summaries {
if seen.insert(s.hash) {
self.address.meta_txs.items.push(s.clone());
}
}
self.address.meta_txs.items.sort_by(|a, b| {
b.block_number
.cmp(&a.block_number)
.then(b.tx_index.cmp(&a.tx_index))
});
if !self.address.meta_txs.items.is_empty()
&& self.address.meta_txs.state.selected().is_none()
{
self.address.meta_txs.select_first();
}
// Keep fetching_meta_txs / cursor as-is: a live fetch may
// still be in-flight behind this cache delivery.
// Plan §2 invariant: every cached MetaTx is also a Call on
// this address. The live meta-tx scan already emits
// `AddressCallsMerged` for freshly-seen pages, but on
// re-entry the cached rows never pass through that path —
// promote them here so the Calls list reflects the
// MetaTxs ⊆ Calls invariant immediately from cache.
let promoted: Vec<crate::data::types::ContractCallSummary> = summaries
.into_iter()
.map(|m| crate::data::types::ContractCallSummary {
tx_hash: m.hash,
sender: m.paymaster,
function_name: String::new(),
block_number: m.block_number,
timestamp: m.timestamp,
total_fee_fri: m.total_fee_fri,
status: m.status,
nonce: None,
tip: 0,
inner_targets: m.inner_targets,
})
.collect();
if !promoted.is_empty() {
let _ = self.action_tx.send(Action::AddressCallsMerged {
address,
calls: promoted,
});
}
}
}
Action::AddressMetaTxsStreamed { address, summaries } => {
if self.address.context == Some(address) && !summaries.is_empty() {
let mut seen: std::collections::HashSet<_> =
self.address.meta_txs.items.iter().map(|m| m.hash).collect();
for s in summaries {
if seen.insert(s.hash) {
self.address.meta_txs.items.push(s);
}
}
self.address.meta_txs.items.sort_by(|a, b| {
b.block_number
.cmp(&a.block_number)
.then(b.tx_index.cmp(&a.tx_index))
});
if self.address.meta_txs.state.selected().is_none() {
self.address.meta_txs.select_first();
}
// Persistence of streamed rows happens in the network
// dispatcher (it holds the DataSource Arc). We never touch
// fetching_meta_txs / cursor / has_more / meta_txs_dispatched
// here: streaming merges run in parallel with bulk
// pagination and must not change the user's view or
// short-circuit in-flight fetches.
}
}
Action::AddressProbeLoaded { address, probe } => {
if self.address.context == Some(address) {
self.address.activity_probe = Some(probe);
}
}
Action::ClassHistoryLoaded { address, entries } => {
if self.address.context == Some(address) {
// Fallback: if no deploy info yet, use earliest class_history block
if self.address.deployment.is_none()
&& let Some(first) = entries.last()
{
self.address.deployment = Some(AddressTxSummary {
hash: starknet::core::types::Felt::ZERO,
nonce: 0,
block_number: first.block_number,
timestamp: 0,
endpoint_names: String::new(),
total_fee_fri: 0,
tip: 0,
tx_type: "DEPLOY".into(),
status: "OK".into(),
sender: None,
called_contracts: Vec::new(),
});
self.build_address_nav_items();
}
self.address.class_history = entries;
self.address.class_history_scroll = 0;
}
}
Action::AddressTxsEnriched { address, updates } => {
if self.address.context != Some(address) {
return;
}
let any_gap_fill_inflight =
self.address.unfilled_gaps.iter().any(|g| g.fill_dispatched);
self.address.merge_tx_summaries(updates);
// Re-run detection so newly-arrived txs can both close existing
// gaps and surface new ones (e.g. when a fresh top-of-list
// batch lands above the cached set). `refresh_unfilled_gaps`
// preserves `fill_dispatched` per `lo_nonce`, so any in-flight
// fill keeps its state.
self.refresh_address_gaps_and_auto_fill();
if any_gap_fill_inflight {
self.address.fetching_more_txs = false;
}
// Persist enriched txs to cache so they survive restarts
if !self.address.txs.items.is_empty() {
let _ = self.action_tx.send(Action::PersistAddressTxs {
address,
txs: self.address.txs.items.clone(),
});
}
}
Action::AddressSourcesPending { address, sources } => {
if self.address.context == Some(address) {
self.address.sources_pending = sources.into_iter().collect();
}
}
Action::AddressEventWindowUpdated {
address,
min_searched,
max_searched,
deferred_gap,
} => {
if self.address.context == Some(address) {
self.address.event_window =
Some(crate::app::views::address_info::EventWindowHint {
min_searched,
max_searched,
deferred_gap,
});
}
}
Action::AddressTxsStreamed {
address,
source,
tx_summaries,
complete,
} => {
if self.address.context != Some(address) {
debug!(
address = %format!("{:#x}", address),
source = ?source,
tx_summaries = tx_summaries.len(),
complete,
current_context = ?self.address.context.map(|c| format!("{:#x}", c)),
"AddressTxsStreamed dropped: stale context"
);
return;
}
let old_deploy_hash = self.address.deployment.as_ref().map(|d| d.hash);
let tx_summaries = self.filter_deployment_txs(address, tx_summaries);
let new_deploy_hash = self.address.deployment.as_ref().map(|d| d.hash);
// Rebuild nav items if deployment info arrived or hash was upgraded
if old_deploy_hash != new_deploy_hash {
self.build_address_nav_items();
}
// Derive an up-to-date account nonce from the incoming
// (post-deployment-filter) txs. After a tx with nonce N lands,
// the account's next nonce is N+1. This keeps the header
// `Nonce:` field in sync with newly streamed txs (WS today,
// RPC fallback poll in the future) instead of drifting behind
// the initial RPC load value.
let max_incoming_nonce = if self.address.is_contract {
None
} else {
tx_summaries.iter().map(|t| t.nonce).max()
};
self.address.merge_tx_summaries(tx_summaries);
if let Some(max_n) = max_incoming_nonce {
// Seed a minimal info if the WS tx beat `AddressInfoLoaded`
// here — otherwise the bump would be skipped and the
// later-arriving initial RPC nonce would overwrite
// unconditionally, leaving the header stale until the
// next tx. `AddressInfoLoaded` below clamps its incoming
// nonce against `existing.nonce` to preserve this bump.
let info = self.address.info.get_or_insert_with(|| {
crate::data::types::SnAddressInfo {
address,
nonce: Felt::ZERO,
class_hash: None,
recent_events: Vec::new(),
token_balances: Vec::new(),
}
});
let new_nonce = max_n.saturating_add(1);
if new_nonce > crate::utils::felt_to_u64(&info.nonce) {
info.nonce = Felt::from(new_nonce);
}
}
// Trigger enrichment for visible window
if !self.address.txs.items.is_empty() {
let offset = self.address.txs_render_state.offset();
let hashes: Vec<_> = self
.address
.txs
.items
.iter()
.skip(offset)
.take(50)
.filter(|t| t.needs_enrichment())
.map(|t| t.hash)
.collect();
if !hashes.is_empty() {
let _ = self
.action_tx
.send(Action::EnrichAddressTxs { address, hashes });
}
}
// Update per-source cursors from streamed data
if !self.address.txs.items.is_empty() {
let min_block = self
.address
.txs
.items
.iter()
.filter(|t| t.block_number > 0)
.map(|t| t.block_number)
.min();
if let Some(min_b) = min_block {
self.address.oldest_event_block = Some(
self.address
.oldest_event_block
.map_or(min_b, |old| old.min(min_b)),
);
match source {
Source::Dune => {
self.address.dune_cursor_block = Some(min_b);
self.address.dune_has_more = true; // Assume more until proven otherwise
}
Source::Rpc => {
self.address.rpc_cursor_block = Some(min_b);
self.address.rpc_has_more = true;
}
_ => {}
}
}
}
// Track source completion
if complete {
self.address.sources_pending.remove(&source);
debug!(
address = %format!("{:#x}", address),
source = ?source,
sources_pending = ?self.address.sources_pending,
"AddressTxsStreamed source completed"
);
if self.address.sources_pending.is_empty() {
self.is_loading = false;
self.loading_detail = None;
// Post-display: detect any large nonce gaps and defer
// them for on-demand fill (issue #10). Small gaps +
// endpoint enrichment still run automatically.
if !self.address.is_contract
&& let Some(info) = &self.address.info
{
let current_nonce = crate::utils::felt_to_u64(&info.nonce);
self.refresh_address_gaps_and_auto_fill();
self.address.sanity_check_dispatched = true;
let _ = self.action_tx.send(Action::EnrichAddressEndpoints {
address,
current_nonce,
known_txs: self.address.txs.items.clone(),
});
}
}
}
// Save to cache after each source completes
if complete && !self.address.txs.items.is_empty() {
let _ = self.action_tx.send(Action::LoadingStatus(format!(
"Loaded {} txs",
self.address.txs.items.len()
)));
}
}
Action::AddressWsEvent { address, event } => {
// Fan-out hub for WS-received events. The event has already
// been persisted to the per-address event cache in ws.rs; this
// reducer is purely about updating in-memory tab state and
// dispatching enrichment / classification follow-ups.
if self.address.context != Some(address) {
return;
}
// --- Events tab: delegate decode to the network task (which
// owns the async ABI registry); the resulting
// `AddressEventStreamed` arm below merges the decoded row.
let _ = self.action_tx.send(Action::DecodeAddressWsEvent {
address,
event: event.clone(),
});
// --- Calls tab: derive a stub summary and merge (dedupe by tx_hash).
let tx_hash = event.transaction_hash;
let block_number = event.block_number;
let stub = crate::data::types::ContractCallSummary {
tx_hash,
sender: Felt::ZERO, // filled in by EnrichAddressCalls
function_name: String::new(),
block_number,
timestamp: 0,
total_fee_fri: 0,
status: "OK".to_string(), // events only fire for successful txs
nonce: None, // filled in by EnrichAddressCalls
tip: 0,
inner_targets: Vec::new(), // filled in by EnrichAddressCalls
};
if self.address.insert_call(stub) {
let _ = self.action_tx.send(Action::EnrichAddressCalls {
address,
hashes_with_blocks: vec![(tx_hash, block_number)],
});
// Persist the stub too: a failed enrichment then still leaves
// a row for the load-time repair pass instead of losing the tx.
let _ = self.action_tx.send(Action::PersistAddressCalls {
address,
calls: self.address.calls_by_hash(&[tx_hash]),
});
if self.address.calls.state.selected().is_none() {
self.address.calls.select_first();
}
// Auto-switch to Calls only if the user is still on the
// default Transactions tab. Never yank them away from a
// tab they deliberately navigated to.
if self.address.tab == AddressTab::Transactions
&& self.address.txs.items.is_empty()
{
self.address.tab = AddressTab::Calls;
}
}
// --- Transfers tab: a keyed Transfer leg naming this address.
if let Some(t) = crate::data::types::TokenTransfer::from_event(&event, 0)
&& (t.from == address || t.to == address)
{
let rows = vec![t];
if self.merge_address_transfers(rows.clone()) > 0 {
let _ = self
.action_tx
.send(Action::PersistAddressTransfers { address, rows });
}
}
// --- MetaTxs: for viewed accounts, any TRANSACTION_EXECUTED
// event might be an execute_from_outside. Dispatch the
// classifier to check and populate the MetaTxs tab live.
if event
.keys
.first()
.map(|k| *k == crate::network::ws::tx_executed_selector())
.unwrap_or(false)
{
let _ = self
.action_tx
.send(Action::ClassifyPotentialMetaTx { address, tx_hash });
}
}
Action::AddressEventStreamed {
address,
decoded_event,
} => {
// Response arm for DecodeAddressWsEvent. Merge the decoded
// event into the Events tab list newest-first, dedup by
// `(tx_hash, event_index)` — the same key the cache uses. The
// event is already persisted (the WS handler called
// `merge_address_events` before broadcasting), so this is
// purely an in-memory refresh; a future cache reload will
// produce the same list via the cache path.
if self.address.context != Some(address) {
return;
}
let key = (
decoded_event.raw.transaction_hash,
decoded_event.raw.event_index,
);
let already_present = self
.address
.events
.items
.iter()
.any(|e| (e.raw.transaction_hash, e.raw.event_index) == key);
if already_present {
return;
}
self.address.events.items.insert(0, decoded_event);
// `insert(0, …)` preserves newest-first ordering as long as
// WS events arrive in block order, which they do. No sort.
if self.address.events.state.selected().is_none() {
self.address.events.select_first();
}
}
Action::AddressEventsCacheLoaded {
address,
decoded_events,
} => {
// Deferred decode pass for the events cached at entry time.
// `fetch_and_send_address_info` now sends `AddressInfoLoaded`
// immediately with empty `decoded_events` so the TUI can drop
// the "Fetching address info…" spinner while this expensive
// per-event ABI decode runs in a background task.
if self.address.context != Some(address) {
return; // stale — user navigated away
}
if decoded_events.is_empty() {
return;
}
let had_selection = self.address.events.state.selected().is_some();
self.address.events.items = decoded_events;
if !had_selection {
self.address.events.select_first();
}
}
Action::AddressCallsEnriched { address, calls } => {
if self.address.context != Some(address) {
return;
}
let mut sender_changed = false;
let mut touched = Vec::new();
for enriched in calls {
let Some(existing) = self.address.find_call_mut(enriched.tx_hash) else {
continue;
};
let prev_sender = existing.sender;
if crate::data::types::merge_call_into(existing, enriched) {
sender_changed |= existing.sender != prev_sender;
touched.push(existing.clone());
}
}
// Sender mutation doesn't change `calls.items.len()`, so the
// length-keyed color-map cache wouldn't otherwise rebuild.
// Drop it fully so phantom `Felt::ZERO` slots from stub rows
// don't take palette colors away from real senders.
if sender_changed {
self.address.invalidate_call_color_cache();
}
// Saves upsert by tx hash: only the rows that changed go to SQLite.
if !touched.is_empty() {
let _ = self.action_tx.send(Action::PersistAddressCalls {
address,
calls: touched,
});
}
}
Action::AddressCallsMerged { address, calls } => {
// Plan §2: pf-query tx_rows supplement Dune's capped Calls set.
// Dune's `starknet.calls` query is LIMIT 500 which collapses to
// far fewer unique tx_hashes after dedup for addresses with
// many multi-call txs (e.g. meta-tx-heavy accounts). The
// meta-tx scan already walks the right tx_rows — merge those
// rows so MetaTxs ⊆ Calls stays visible.
if self.address.context != Some(address) || calls.is_empty() {
return;
}
let touched: std::collections::HashSet<Felt> =
calls.iter().map(|c| c.tx_hash).collect();
self.address.merge_calls(calls);
if self.address.calls.state.selected().is_none()
&& !self.address.calls.items.is_empty()
{
self.address.calls.select_first();
}
// A merge can both close gaps (new calls bridge a hole) and
// surface new ones (a fresh top-of-list batch lands above the
// cached set). `refresh_unfilled_call_gaps` preserves any
// in-flight `fill_dispatched` whose range is unchanged.
self.refresh_address_call_gaps();
// Only the rows this batch created or enriched; saves upsert by tx hash.
let _ = self.action_tx.send(Action::PersistAddressCalls {
address,
calls: self.address.calls_by_hash(&touched),
});
}
Action::AddressCallRangeScanned {
address,
lo_block,
hi_block,
tracked_from,
} => {
if self.address.context == Some(address) {
// Record the scanned range so a genuinely-sparse hole inside
// it stops resurfacing, then re-detect (this pass is the one
// that drops or shrinks the gap).
self.address.note_scanned_call_range(lo_block, hi_block);
if let Some(t) = tracked_from {
self.address.note_call_tracked_from(t);
}
self.refresh_address_call_gaps();
}
}
Action::AddressCallGapFillFinished { address, lo_block } => {
// The fill task ended (success, no-op, or error). Clear the
// in-flight flag so the row stops showing "loading" and Enter
// can re-dispatch. On a successful fill the gap may have already
// shrunk/closed via the merge above, in which case this is a
// harmless no-op.
if self.address.context == Some(address)
&& let Some(gap) = self
.address
.call_gaps
.iter_mut()
.find(|g| g.lo_block == lo_block)
{
gap.fill_dispatched = false;
}
}
Action::AddressCallScannedRangesLoaded {
address,
ranges,
tracked_from,
} => {
if self.address.context == Some(address) {
// Merge the persisted closed ranges into whatever's in
// memory (empty on fresh entry; superset-safe on refresh),
// then re-detect so any hole we already scanned-and-found-
// sparse stays suppressed from first paint.
for (lo, hi) in ranges {
self.address.note_scanned_call_range(lo, hi);
}
if let Some(t) = tracked_from {
self.address.note_call_tracked_from(t);
}
self.refresh_address_call_gaps();
}
}
Action::AddressTransfersLoaded {
address,
rows,
scanned,
} => {
if self.address.context == Some(address) {
if let Some((lo, hi)) = scanned {
self.address.note_transfer_scanned_range(lo, hi);
}
self.merge_address_transfers(rows);
}
}
Action::AddressTransferScannedRangesLoaded { address, ranges } => {
if self.address.context == Some(address) {
for (lo, hi) in ranges {
self.address.note_transfer_scanned_range(lo, hi);
}
self.address.refresh_transfer_gaps();
self.address.ensure_transfer_selection();
}
}
Action::AddressTransferFillFinished { address, lo_block } => {
if self.address.context == Some(address) {
self.address.fetching_transfers = false;
if let Some(lo) = lo_block
&& let Some(gap) = self
.address
.transfer_gaps
.iter_mut()
.find(|g| g.lo_block == lo)
{
gap.fill_dispatched = false;
}
}
}
Action::AddressBalancesLoaded { address, balances } => {
if self.address.context == Some(address) {
// Balances can beat the nonce/class_hash fetch to the UI —
// seed a minimal info so the result isn't dropped while
// `info` is still `None` waiting on `AddressInfoLoaded`.
if self.address.info.is_none() {
self.address.info = Some(crate::data::types::SnAddressInfo {
address,
nonce: starknet::core::types::Felt::ZERO,
class_hash: None,
recent_events: Vec::new(),
token_balances: Vec::new(),
});
}
if let Some(info) = &mut self.address.info {
info.token_balances = balances;
}
self.dispatch_balance_price_fetch();
}
}
Action::AddressNotDeployed { address } => {
if self.address.context == Some(address) {
self.address.not_deployed = true;
// Seed a minimal info so the header renders even if the
// balance task hasn't landed yet; `AddressBalancesLoaded`
// fills token_balances in-place when it arrives.
if self.address.info.is_none() {
self.address.info = Some(crate::data::types::SnAddressInfo {
address,
nonce: starknet::core::types::Felt::ZERO,
class_hash: None,
recent_events: Vec::new(),
token_balances: Vec::new(),
});
}
// Loading is complete — an undeployed address has nothing
// left to fetch. Clear the spinner and any pending source
// so the view doesn't show a perpetual loader.
self.address.sources_pending.clear();
self.is_loading = false;
self.loading_detail = None;
}
}
Action::PricesUpdated => {
// Cache reads happen on next draw; no app state to update.
}
Action::VoyagerLabelLoaded { address, label } => {
// Add to search index so Voyager labels are searchable
if let Some(name) = &label.name
&& let Some(engine) = &self.search_engine
{
engine.registry().add_voyager_label(address, name);
}
self.voyager_labels.insert(address, label);
}
Action::LoadingStatus(msg) => {
self.is_loading = true;
self.loading_detail = Some(msg);
}
Action::SetActiveQuery { key, label } => match label {
Some(l) => self.active_queries.set(&key, l),
None => self.active_queries.clear(&key),
},
Action::SourceUpdate { source, status } => {
use crate::app::actions::Source;
let target = match source {
Source::Rpc => &mut self.data_sources.rpc,
Source::Ws => &mut self.data_sources.ws,
Source::Pathfinder => &mut self.data_sources.pathfinder,
Source::Dune => &mut self.data_sources.dune,
Source::Voyager => &mut self.data_sources.voyager,
Source::Starkscan => &mut self.data_sources.starkscan,
};
*target = status;
}
Action::LatestBlockNumber(n) => {
self.latest_block_number = n;
}
Action::NavigateToClassInfo { class_hash } => {
self.clear_class_info();
self.class.hash = Some(class_hash);
self.is_loading = true;
self.loading_detail = Some("Fetching class info...".into());
if self.current_view() != View::ClassInfo {
self.push_view(View::ClassInfo);
}
}
Action::ClassAbiLoaded { class_hash, abi } => {
if self.class.hash == Some(class_hash) {
self.class.abi = abi;
self.class.abi_loaded = true;
self.build_class_nav_items();
// If declare+contracts already arrived, clear loading
if self.class.declare.is_some() || self.class.decl_block.is_some() {
self.is_loading = false;
self.loading_detail = None;
}
}
}
Action::ClassDeclareLoaded {
class_hash,
declare_info,
} => {
if self.class.hash == Some(class_hash) {
self.class.declare = declare_info;
self.build_class_nav_items();
// If all data has arrived, clear loading
if self.class.abi_loaded {
self.is_loading = false;
self.loading_detail = None;
}
}
}
Action::ClassContractsLoaded {
class_hash,
contracts,
declaration_block,
} => {
if self.class.hash == Some(class_hash) {
self.class.contracts = contracts;
self.class.decl_block = declaration_block;
self.build_class_nav_items();
// If all data has arrived, clear loading
if self.class.abi_loaded {
self.is_loading = false;
self.loading_detail = None;
}
}
}
Action::Error(msg) => {
self.error_message = Some(msg);
self.is_loading = false;
}
Action::PeriodicAddressPollTick => {
// Only refresh when the user is actually sitting on an address
// view, WS isn't live (otherwise the WS stream covers this),
// and the context is an account (contracts don't have a
// meaningful account nonce and are topped up via other paths).
if self.current_view() == View::AddressInfo
&& self.data_sources.ws != SourceStatus::Live
&& !self.address.is_contract
&& let Some(address) = self.address.context
{
let _ = self.action_tx.send(Action::RefreshAddressRpc { address });
}
// Transfers tab has no WS fallback of its own: re-run the
// top-delta scan so new blocks show up while the user sits there.
if self.current_view() == View::AddressInfo
&& self.data_sources.ws != SourceStatus::Live
&& self.address.tab == AddressTab::Transfers
{
self.address.transfers_dispatched = false;
self.maybe_fetch_address_transfers();
}
}
// Request actions are not handled here (they go to the network task)
_ => {}
}
}
}