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
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::Modifier;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, List, ListItem, Paragraph, Tabs};

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

use crate::app::state::TxNavItem;
use crate::app::views::address_info::{RenderedRow, rendered_row};
use crate::app::{AddressTab, App};
use crate::data::types::{
    AddressTxSummary, ContractCallSummary, MetaTxIntenderSummary, TokenBalance, TokenTransfer,
};
use crate::registry::AddressRegistry;
use crate::ui::theme;
use crate::ui::widgets::address_color::known_or_palette_style;
use crate::ui::widgets::hex_display::{format_fri, format_strk_u128, short_address, tx_hash_cell};
use crate::ui::widgets::list_window::ListWindow;
use crate::ui::widgets::param_display::format_token_amount;
use crate::ui::widgets::price;
use crate::ui::widgets::{search_bar, status_bar};
use crate::utils::{felt_to_u64, felt_to_u128};

/// How confident are we in the tab's count?
///
/// The address-view revamp locks down two display states:
///
/// - [`CountBound::Exact`] — the tab's total is known exactly (e.g. the
///   on-chain nonce for Txs, a Dune probe total for Calls). Renders as
///   `"N / total"` while we're filling, or bare `"N"` once `shown == total`.
/// - [`CountBound::LowerBound`] — "at least N; more may exist". Always
///   renders with an explicit denominator — `"N / hint+"` if a hint is
///   available and exceeds `shown`, otherwise `"N / N+"` because we
///   know at least `shown` items exist. This is the default when no
///   authoritative probe has completed — every tab starts here on
///   first paint.
///
/// Keeping this enum the single input to [`count_fragment`] prevents
/// display divergence between tabs: no tab accidentally renders bare `"N"`
/// when it only has a lower bound (the historical bug was Events/Calls
/// hiding the `"+"` once a scan paused).
enum CountBound {
    Exact(u64),
    LowerBound { hint: Option<u64> },
}

/// Render the parens content for a tab count given its [`CountBound`].
///
/// The single source of truth for what goes inside the `(...)` on each
/// tab — shared by the compact `draw_tabs` row and each per-tab body
/// title. Previously every site recomputed a fragment independently, and
/// display nits (like the MetaTxs body title lagging the compact row's
/// `"+"`) crept in.
///
/// Format rules:
/// - `Exact(N)`, `shown == N` → `"N"` (full knowledge, no `+`)
/// - `Exact(N)`, `shown < N` → `"shown / N"` (filling toward a known total)
/// - `LowerBound` with hint `H > shown` → `"shown / H+"` (inexact hint)
/// - `LowerBound` otherwise → `"shown / shown+"` (no better hint; we
///   still always render a denominator so "0/0+" on a cold tab beats
///   a lonely "0+")
fn count_fragment(shown: u64, bound: CountBound) -> String {
    match bound {
        CountBound::Exact(total) if shown < total => format!("{shown} / {total}"),
        CountBound::Exact(_) => shown.to_string(),
        CountBound::LowerBound { hint: Some(h) } if h > shown => format!("{shown} / {h}+"),
        CountBound::LowerBound { .. } => format!("{shown} / {shown}+"),
    }
}

/// Count fragment for the Txs tab.
///
/// Authoritative total is the on-chain nonce (one invoke per sender nonce),
/// so once nonce is known the bound is [`CountBound::Exact`]. Dune's event
/// count over-counts on hybrid accounts (it counts emitted events, not
/// sender txs) — not suitable here.
///
/// The on-chain `nonce` is the *next* nonce to use, so the total tx count
/// equals `nonce`. DEPLOY_ACCOUNT (self-deploy) consumes nonce 0 and stays
/// in `txs.items`; UDC-deployed contracts have `nonce 0` start as their
/// first invoke. Either way, `nonce` is the count.
fn tx_count_fragment(app: &App) -> String {
    let count = app.address.txs.items.len() as u64;
    let bound = match app.address.info.as_ref().map(|i| felt_to_u64(&i.nonce)) {
        Some(nonce) => CountBound::Exact(nonce),
        None => CountBound::LowerBound { hint: None },
    };
    count_fragment(count, bound)
}

/// Count fragment for the Calls tab.
///
/// Only the Dune probe total counts as "exact" here — pf-query-only
/// backfill can't promise completeness (misses calls to contracts that
/// don't emit events). Until Dune returns, we're in `LowerBound`. The
/// `event_window.min_searched > 0` signal becomes the lower-bound hint's
/// "+" indicator, not a claim of exactness.
fn call_count_fragment(app: &App) -> String {
    let count = app.address.calls.items.len() as u64;
    let dune_total = app
        .address
        .activity_probe
        .as_ref()
        .map(|p| p.callee_call_count);
    let bound = match dune_total {
        Some(total) => CountBound::Exact(total),
        None => CountBound::LowerBound { hint: None },
    };
    count_fragment(count, bound)
}

/// Count fragment for the Events tab.
///
/// Events are all `from_address == ADDR` logs, sourced via the unkeyed
/// event-window scan. Per the plan we can only claim [`CountBound::Exact`]
/// when the backwards scan has reached deploy block; until then we stay
/// [`CountBound::LowerBound`]. Shares the same `event_window.min_searched`
/// signal as MetaTxs — technically imprecise because a keyed scan on a
/// hybrid address could satisfy the floor check here even if the unkeyed
/// scan hasn't, but that's the only signal the UI has today.
fn events_count_fragment(app: &App) -> String {
    let count = app.address.events.items.len() as u64;
    let reached_floor = match (
        app.address.event_window.as_ref().map(|w| w.min_searched),
        app.address.deployment.as_ref().map(|d| d.block_number),
    ) {
        (Some(m), Some(d)) if m > 0 => m <= d,
        _ => false,
    };
    let bound = if reached_floor {
        CountBound::Exact(count)
    } else {
        CountBound::LowerBound { hint: None }
    };
    count_fragment(count, bound)
}

/// Count fragment for the Transfers tab: exact once the scanned ranges run
/// contiguously from the deploy floor (no gap rows left), a lower bound before.
fn transfers_count_fragment(app: &App) -> String {
    let count = app.address.transfers.items.len() as u64;
    let bound = if app.address.transfers_fully_scanned() {
        CountBound::Exact(count)
    } else {
        CountBound::LowerBound { hint: None }
    };
    count_fragment(count, bound)
}

/// Count fragment for the MetaTxs tab.
///
/// Per the revamp spec we can only claim [`CountBound::Exact`] once the
/// backwards scan has reached (or crossed) the deploy block — only then
/// have we demonstrably seen every `execute_from_outside` targeting this
/// address. Until that holds we stay [`CountBound::LowerBound`], even if
/// `meta_tx_has_more` has flipped to false because the current fetch
/// returned no new rows: a dry page doesn't imply history exhausted.
///
/// The function now always returns a fragment — callers render the label
/// even on cold state so the tab doesn't silently hide behind a probe.
/// "0+" on first paint is strictly more informative than no count at all.
fn meta_tx_count_fragment(app: &App) -> String {
    let count = app.address.meta_txs.items.len() as u64;
    // Reached deploy-floor iff we know both values AND the scan has a
    // non-zero min_searched <= deploy_block. `min_searched == 0` is the
    // "never scanned" sentinel — never promote on that.
    let reached_floor = match (
        app.address.event_window.as_ref().map(|w| w.min_searched),
        app.address.deployment.as_ref().map(|d| d.block_number),
    ) {
        (Some(m), Some(d)) if m > 0 => m <= d,
        _ => false,
    };
    let bound = if reached_floor {
        CountBound::Exact(count)
    } else {
        CountBound::LowerBound { hint: None }
    };
    count_fragment(count, bound)
}

/// Title suffix describing any passive gap the event-window helper reported
/// on its last fetch. Shared between the Calls and MetaTxs tabs (Events tab
/// is intentionally excluded here — see task #13 for a follow-up review).
/// Returns an empty string when no gap is known, so callers can always
/// concatenate without a None-check.
fn event_window_gap_suffix(app: &App) -> String {
    let Some(hint) = app.address.event_window.as_ref() else {
        return String::new();
    };
    match hint.deferred_gap {
        Some((lo, hi)) => {
            let span = hi.saturating_sub(lo).saturating_add(1);
            format!(" — gap {lo}..{hi} ({span} blocks deferred) ")
        }
        None => String::new(),
    }
}

pub fn draw(f: &mut Frame, app: &mut App) {
    let has_deploy = app.address.deployment.is_some();
    let has_deployer = app
        .address
        .deployment
        .as_ref()
        .and_then(|d| d.sender)
        .is_some_and(|s| {
            app.address.info.as_ref().is_none_or(|i| s != i.address) && s != Felt::ZERO
        });
    // The red "not deployed" note (matches the gate in `draw_header`) adds
    // one line — reserve room for it so it isn't clipped.
    let has_not_deployed_note = app.address.not_deployed
        && app
            .address
            .info
            .as_ref()
            .is_some_and(|i| i.class_hash.is_none() && !i.token_balances.is_empty());
    // 2 borders + 2 base lines + 1 per deployment line (tx hash, deployer)
    // + 1 for the not-deployed note when shown.
    let header_height =
        4 + u16::from(has_deploy) + u16::from(has_deployer) + u16::from(has_not_deployed_note);
    let chunks = Layout::vertical([
        Constraint::Length(1),             // search bar
        Constraint::Length(header_height), // header
        Constraint::Length(1),             // tabs
        Constraint::Min(5),                // tab content
        Constraint::Length(1),             // status bar
    ])
    .split(f.area());

    search_bar::draw_input(f, app, chunks[0]);
    draw_header(f, app, chunks[1]);

    // Compute private holdings once per frame; reused by `draw_tabs`
    // (for the Balances `Prv (N)` tab fragment) and by
    // `draw_balances_tab` (which renders the per-token rows). Empty
    // when no labelled address / no notes yet.
    let private_holdings: Vec<(Felt, u128, usize)> = app
        .address
        .info
        .as_ref()
        .map(|i| compute_private_holdings(app, i.address))
        .unwrap_or_default();

    draw_tabs(f, app, chunks[2], &private_holdings);

    match app.address.tab {
        AddressTab::Transactions => draw_transactions_tab(f, app, chunks[3]),
        AddressTab::MetaTxs => draw_meta_txs_tab(f, app, chunks[3]),
        AddressTab::Calls => draw_calls_tab(f, app, chunks[3]),
        AddressTab::Balances => draw_balances_tab(f, app, chunks[3], &private_holdings),
        AddressTab::Transfers => draw_transfers_tab(f, app, chunks[3]),
        AddressTab::Events => draw_events_tab(f, app, chunks[3]),
        AddressTab::ClassHistory => draw_class_history_tab(f, app, chunks[3]),
    }

    status_bar::draw(f, app, chunks[4]);

    // Search dropdown overlay (last)
    search_bar::draw_dropdown(f, app, chunks[0]);
}

fn draw_header(f: &mut Frame, app: &App, area: Rect) {
    let info = match &app.address.info {
        Some(i) => i,
        None => {
            // Show the address we're loading, if known
            let addr_str = app
                .address
                .context
                .map(|a| format!(" Loading {:#x}...", a))
                .unwrap_or_else(|| " Loading address...".to_string());
            f.render_widget(Paragraph::new(addr_str).style(theme::STATUS_LOADING), area);
            return;
        }
    };

    let label = app.format_address_full(&info.address);
    let class_hash_str = info
        .class_hash
        .map(|c| format!("{:#x}", c))
        .unwrap_or_else(|| "N/A".into());

    // Current visual selection
    let selected: Option<&TxNavItem> = if app.address.visual_mode {
        app.address.nav_items.get(app.address.nav_cursor)
    } else {
        None
    };

    let mut lines = vec![Line::from(vec![
        Span::styled(" ", theme::NORMAL_STYLE),
        Span::styled(&label, theme::LABEL_STYLE),
        Span::styled(format!("  {:#x}", info.address), theme::BLOCK_HASH_STYLE),
    ])];

    // Class line — show full hash, highlight if selected
    {
        let ch_selected = info
            .class_hash
            .is_some_and(|ch| matches!(selected, Some(TxNavItem::ClassHash(c)) if *c == ch));
        let ch_style = if ch_selected {
            theme::VISUAL_SELECTED_STYLE
        } else {
            theme::TX_HASH_STYLE
        };
        let marker = if ch_selected { "►" } else { " " };

        let mut class_line = vec![
            Span::styled(
                marker,
                if ch_selected {
                    theme::VISUAL_SELECTED_STYLE
                } else {
                    theme::NORMAL_STYLE
                },
            ),
            Span::styled("Class: ", theme::NORMAL_STYLE),
            Span::styled(&class_hash_str, ch_style),
        ];
        if let Some(vl) = app.voyager_labels.get(&info.address)
            && let Some(ca) = &vl.class_alias
            && !ca.is_empty()
        {
            class_line.push(Span::styled(format!(" [{}]", ca), theme::LABEL_STYLE));
        }
        class_line.push(Span::styled(
            format!("  Nonce: {}", felt_to_u64(&info.nonce)),
            theme::NORMAL_STYLE,
        ));
        lines.push(Line::from(class_line));
    }

    if let Some(deploy) = &app.address.deployment {
        let has_tx = deploy.hash != Felt::ZERO;

        // Deploy block — navigable
        let blk_selected = deploy.block_number > 0
            && matches!(selected, Some(TxNavItem::Block(b)) if *b == deploy.block_number);
        let blk_style = if blk_selected {
            theme::VISUAL_SELECTED_STYLE
        } else {
            theme::BLOCK_NUMBER_STYLE
        };

        if has_tx {
            // Full deploy info: tx hash + block
            let tx_selected =
                matches!(selected, Some(TxNavItem::Transaction(h)) if *h == deploy.hash);
            let tx_style = if tx_selected {
                theme::VISUAL_SELECTED_STYLE
            } else {
                theme::TX_HASH_STYLE
            };
            let tx_marker = if tx_selected { "►" } else { " " };
            lines.push(Line::from(vec![
                Span::styled(
                    tx_marker,
                    if tx_selected {
                        theme::VISUAL_SELECTED_STYLE
                    } else {
                        theme::NORMAL_STYLE
                    },
                ),
                Span::styled("Deployed at: ", theme::NORMAL_STYLE),
                Span::styled(format!("{:#x}", deploy.hash), tx_style),
                Span::styled("  Block: ", theme::NORMAL_STYLE),
                Span::styled(format!("{}", deploy.block_number), blk_style),
            ]));
        } else {
            // Partial deploy info (from class_history): block only
            let blk_marker = if blk_selected { "►" } else { " " };
            lines.push(Line::from(vec![
                Span::styled(
                    blk_marker,
                    if blk_selected {
                        theme::VISUAL_SELECTED_STYLE
                    } else {
                        theme::NORMAL_STYLE
                    },
                ),
                Span::styled("Deployed at: ", theme::NORMAL_STYLE),
                Span::styled("Block: ", theme::NORMAL_STYLE),
                Span::styled(format!("{}", deploy.block_number), blk_style),
            ]));
        }

        // Show deployer on its own line when it's a different address
        if let Some(sender) = deploy.sender
            && sender != info.address
            && sender != Felt::ZERO
        {
            let addr_selected = matches!(selected, Some(TxNavItem::Address(a)) if *a == sender);
            let addr_style = if addr_selected {
                theme::VISUAL_SELECTED_STYLE
            } else {
                theme::LABEL_STYLE
            };
            let addr_marker = if addr_selected { "►" } else { " " };
            lines.push(Line::from(vec![
                Span::styled(
                    addr_marker,
                    if addr_selected {
                        theme::VISUAL_SELECTED_STYLE
                    } else {
                        theme::NORMAL_STYLE
                    },
                ),
                Span::styled("Deployed by: ", theme::NORMAL_STYLE),
                Span::styled(format!("{:#x}", sender), addr_style),
                {
                    let label = app.format_address_full(&sender);
                    if label.starts_with("0x") {
                        Span::raw("")
                    } else {
                        Span::styled(format!("  {}", label), theme::LABEL_STYLE)
                    }
                },
            ]));
        }
    }

    // Not-deployed note: the address holds token balances but has no class
    // at the latest block (funds sent to a counterfactual / not-yet-deployed
    // account). Gated on non-zero balances so a transient RPC error can't
    // trigger a false positive.
    if app.address.not_deployed && info.class_hash.is_none() && !info.token_balances.is_empty() {
        lines.push(Line::from(Span::styled(
            " ⚠ This contract is not deployed",
            theme::STATUS_ERROR.add_modifier(Modifier::BOLD),
        )));
    }

    let widget = Paragraph::new(lines).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(theme::BORDER_FOCUSED_STYLE)
            .title(Span::styled(" Address ", theme::TITLE_STYLE)),
    );
    f.render_widget(widget, area);
}

fn draw_tabs(f: &mut Frame, app: &App, area: Rect, private_holdings: &[(Felt, u128, usize)]) {
    let bal_count = app
        .address
        .info
        .as_ref()
        .map(|i| i.token_balances.len())
        .unwrap_or(0);
    let class_count = app.address.class_history.len();

    let tx_label = format!(" Txs ({}) ", tx_count_fragment(app));
    let call_label = format!(" Calls ({}) ", call_count_fragment(app));
    // The fragment is always rendered — "0+" on cold state beats a bare
    // label that hides the tab's existence while the classifier spins up.
    let meta_label = format!(" MetaTxs ({}) ", meta_tx_count_fragment(app));

    // Per-token unspent-incoming count for the Balances tab. Suppressed
    // when the address has no viewing key (or no holdings yet) so the
    // tab label stays clean for the common non-privacy case.
    let prv_count = private_holdings.len();
    let balances_title: Line = if prv_count > 0 {
        Line::from(vec![
            Span::raw(format!(" Balances ({bal_count}) ")),
            Span::styled(format!("Prv ({prv_count}) "), theme::PRIVACY_STYLE),
        ])
    } else {
        Line::from(Span::raw(format!(" Balances ({bal_count}) ")))
    };

    let titles: Vec<Line> = vec![
        Line::from(Span::raw(tx_label)),
        Line::from(Span::raw(meta_label)),
        Line::from(Span::raw(call_label)),
        balances_title,
        Line::from(Span::raw(format!(
            " Transfers ({}) ",
            transfers_count_fragment(app)
        ))),
        Line::from(Span::raw(format!(
            " Events ({}) ",
            events_count_fragment(app)
        ))),
        Line::from(Span::raw(format!(" Class ({class_count}) "))),
    ];
    let selected = match app.address.tab {
        AddressTab::Transactions => 0,
        AddressTab::MetaTxs => 1,
        AddressTab::Calls => 2,
        AddressTab::Balances => 3,
        AddressTab::Transfers => 4,
        AddressTab::Events => 5,
        AddressTab::ClassHistory => 6,
    };
    let tabs = Tabs::new(titles)
        .select(selected)
        .highlight_style(theme::TITLE_STYLE.add_modifier(Modifier::UNDERLINED))
        .divider(Span::raw(" | "));
    f.render_widget(tabs, area);
}

fn list_block(title: String) -> Block<'static> {
    Block::default()
        .borders(Borders::ALL)
        .border_style(theme::BORDER_STYLE)
        .title(Span::styled(title, theme::TITLE_STYLE))
}

fn highlighted_list(items: Vec<ListItem<'static>>, block: Block<'static>) -> List<'static> {
    List::new(items)
        .block(block)
        .highlight_style(theme::SELECTED_STYLE.add_modifier(Modifier::BOLD))
        .highlight_symbol(">> ")
}

fn draw_transactions_tab(f: &mut Frame, app: &mut App, area: Rect) {
    // Column headers
    let header_area = Rect { height: 1, ..area };
    let list_area = Rect {
        y: area.y + 1,
        height: area.height.saturating_sub(1),
        ..area
    };
    let header = Paragraph::new(Line::from(vec![
        Span::styled("   Nonce     ", theme::SUGGESTION_STYLE),
        Span::styled("Type            ", theme::SUGGESTION_STYLE),
        Span::styled("Hash          ", theme::SUGGESTION_STYLE),
        Span::styled("Contracts                     ", theme::SUGGESTION_STYLE),
        Span::styled("Endpoint(s)                    ", theme::SUGGESTION_STYLE),
        Span::styled("Fee(STRK)        ", theme::SUGGESTION_STYLE),
        Span::styled("Tip              ", theme::SUGGESTION_STYLE),
        Span::styled("Block     ", theme::SUGGESTION_STYLE),
        Span::styled("St  ", theme::SUGGESTION_STYLE),
        Span::styled("Prv ", theme::SUGGESTION_STYLE),
        Span::styled("Age  ", theme::SUGGESTION_STYLE),
    ]));
    f.render_widget(header, header_area);

    if app.address.txs.items.is_empty() {
        let msg = if app.is_loading {
            " Loading transactions..."
        } else {
            " No transactions found"
        };
        f.render_widget(
            Paragraph::new(msg).style(theme::SUGGESTION_STYLE).block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(theme::BORDER_STYLE),
            ),
            area,
        );
        return;
    }

    // Refresh the per-contract count + color slot cache for the Contracts
    // column. No-op when the tx list hasn't grown since the last render.
    // Done before the gap closure below borrows `app.address` immutably.
    let registry = app.search_engine.as_ref().map(|e| e.registry());
    app.address
        .update_tx_color_map(|addr| registry.is_some_and(|r| r.is_known(addr)));

    let gap_suffix = if app.address.unfilled_gaps.is_empty() {
        String::new()
    } else {
        let total_missing: u64 = app
            .address
            .unfilled_gaps
            .iter()
            .map(|g| g.missing_count)
            .sum();
        let n = app.address.unfilled_gaps.len();
        let any_pending = app.address.unfilled_gaps.iter().any(|g| !g.fill_dispatched);
        if any_pending {
            format!(
                " — {n} gap{plural} ({total_missing} txs deferred, Enter on a gap row to load) ",
                plural = if n == 1 { "" } else { "s" }
            )
        } else {
            format!(
                " — {n} gap{plural} ({total_missing} txs, press r to retry) ",
                plural = if n == 1 { "" } else { "s" }
            )
        }
    };
    let count = tx_count_fragment(app);
    let title = if app.is_loading {
        format!(" Transactions ({count}) fetching...{gap_suffix} ")
    } else {
        format!(" Transactions ({count}){gap_suffix} ")
    };
    let block = list_block(title);

    // Build rows for the visible page only: the list can hold tens of
    // thousands of txs and every keystroke redraws the frame.
    let gaps = app.address.gap_render_positions();
    let window = ListWindow::new(
        app.address.txs.items.len() + gaps.len(),
        app.address.tx_list_rendered_selected_with(&gaps),
        app.address.txs_render_state.offset(),
        block.inner(list_area).height as usize,
    );
    let items: Vec<ListItem> = window
        .range()
        .map(|r| match rendered_row(r, &gaps) {
            RenderedRow::Gap(lo) => tx_gap_row(app, lo),
            RenderedRow::Item(idx) => tx_row(app, registry, &app.address.txs.items[idx]),
        })
        .collect();
    window.render(
        f,
        highlighted_list(items, block),
        list_area,
        &mut app.address.txs_render_state,
    );
}

fn tx_gap_row(app: &App, lo_nonce: u64) -> ListItem<'static> {
    let msg = match app
        .address
        .unfilled_gaps
        .iter()
        .find(|g| g.lo_nonce == lo_nonce)
    {
        Some(g) if g.fill_dispatched => {
            format!(
                " ── gap of {} txs — loading / press r to retry ──",
                g.missing_count
            )
        }
        Some(g) => format!(
            " ── {} txs hidden — press Enter to load ──",
            g.missing_count
        ),
        None => " ── gap ──".to_string(),
    };
    ListItem::new(Line::from(Span::styled(msg, theme::SUGGESTION_STYLE)))
}

fn tx_row(
    app: &App,
    registry: Option<&AddressRegistry>,
    tx: &AddressTxSummary,
) -> ListItem<'static> {
    let fee_str = format_strk_u128(tx.total_fee_fri)
        .trim_end_matches(" STRK")
        .to_string();
    let tip_str = if tx.tip > 0 {
        format_fri(tx.tip as u128)
    } else {
        "0".to_string()
    };
    let age = format_age(tx.timestamp);
    let endpoint = if tx.endpoint_names.chars().count() > 30 {
        let truncated: String = tx.endpoint_names.chars().take(29).collect();
        format!("{truncated}…")
    } else {
        tx.endpoint_names.clone()
    };
    let contract_spans = format_called_contracts_spans(app, &tx.called_contracts);
    // Privacy iff a top-level called contract is in the curated bundle. OE-
    // wrapped reaches only show once the tx itself is opened.
    let is_privacy_tx = registry.is_some_and(|reg| {
        tx.called_contracts
            .iter()
            .any(|c| reg.is_privacy_address(c))
    });

    let status_style = match tx.status.as_str() {
        "OK" => theme::STATUS_OK,
        "REV" => theme::STATUS_REVERTED,
        _ => theme::SUGGESTION_STYLE,
    };

    let type_style = match tx.tx_type.as_str() {
        "INVOKE" => theme::TX_TYPE_INVOKE,
        "DECLARE" => theme::TX_TYPE_DECLARE,
        "DEPLOY_ACCOUNT" | "DEPLOY" => theme::TX_TYPE_DEPLOY,
        "L1_HANDLER" => theme::TX_TYPE_L1HANDLER,
        _ => theme::NORMAL_STYLE,
    };

    let tx_label = app.resolve_tx(&tx.hash);
    let tx_hash_display = tx_hash_cell(tx_label, &tx.hash);
    let tx_hash_style = if tx_label.is_some() {
        theme::LABEL_STYLE
    } else {
        theme::TX_HASH_STYLE
    };

    let prv_marker_text = if is_privacy_tx { "🛡   " } else { "    " };
    let mut row_spans: Vec<Span<'static>> = vec![
        Span::styled(format!(" {:<8}", tx.nonce), theme::NORMAL_STYLE),
        Span::styled(format!("{:<15}", tx.tx_type), type_style),
        Span::styled(format!("{:<14}", tx_hash_display), tx_hash_style),
    ];
    row_spans.extend(contract_spans);
    row_spans.extend([
        Span::styled(format!("{:<31}", endpoint), theme::LABEL_STYLE),
        Span::styled(format!("{:<17}", fee_str), theme::TX_FEE_STYLE),
        Span::styled(format!("{:<17}", tip_str), theme::SUGGESTION_STYLE),
        Span::styled(
            format!("#{:<9}", tx.block_number),
            theme::BLOCK_NUMBER_STYLE,
        ),
        Span::styled(format!("{:<4}", tx.status), status_style),
        Span::styled(prv_marker_text, theme::PRIVACY_STYLE),
        Span::styled(age, theme::BLOCK_AGE_STYLE),
    ]);
    ListItem::new(Line::from(row_spans))
}

/// Render the contracts-called column: up to the first two contract labels
/// (registry/Voyager-resolved or short hex), followed by ` +N` for any
/// remaining. Each label is truncated to share the 29-char content budget;
/// any slack left by a short first label spills over to the second.
///
/// Returns a sequence of styled spans so each contract gets its own theme:
/// privacy contracts render in `PRIVACY_STYLE`, registry-labeled contracts
/// in `LABEL_STYLE`, repeats in their palette slot, one-offs in `NORMAL_STYLE`.
/// Separator and `+N` overflow stay in `SUGGESTION_STYLE`. The returned
/// vector always totals exactly 30 visible chars (one trailing pad column).
fn format_called_contracts_spans(app: &App, contracts: &[Felt]) -> Vec<Span<'static>> {
    const CONTENT_BUDGET: usize = 29;
    const COLUMN_WIDTH: usize = 30;
    if contracts.is_empty() {
        return vec![Span::raw(" ".repeat(COLUMN_WIDTH))];
    }
    let registry = app.search_engine.as_ref().map(|e| e.registry());
    let color_map = &app.address.tx_color_map;
    let labels: Vec<String> = contracts.iter().map(|c| app.format_address(c)).collect();

    let mut spans: Vec<Span<'static>> = Vec::new();
    let used_chars;

    if labels.len() == 1 {
        let label = truncate_to(&labels[0], CONTENT_BUDGET);
        let style = known_or_palette_style(&contracts[0], registry, color_map);
        used_chars = label.chars().count();
        spans.push(Span::styled(label, style));
    } else {
        let extra = labels.len().saturating_sub(2);
        let suffix = if extra > 0 {
            format!(" +{extra}")
        } else {
            String::new()
        };
        const SEP: &str = ", ";
        let inner_budget = CONTENT_BUDGET.saturating_sub(suffix.chars().count() + SEP.len());
        let a_budget = inner_budget / 2;
        let a = truncate_to(&labels[0], a_budget);
        let b_budget = inner_budget.saturating_sub(a.chars().count());
        let b = truncate_to(&labels[1], b_budget);

        let style_a = known_or_palette_style(&contracts[0], registry, color_map);
        let style_b = known_or_palette_style(&contracts[1], registry, color_map);

        used_chars = a.chars().count() + SEP.len() + b.chars().count() + suffix.chars().count();
        spans.push(Span::styled(a, style_a));
        spans.push(Span::styled(SEP, theme::SUGGESTION_STYLE));
        spans.push(Span::styled(b, style_b));
        if !suffix.is_empty() {
            spans.push(Span::styled(suffix, theme::SUGGESTION_STYLE));
        }
    }

    let pad = COLUMN_WIDTH.saturating_sub(used_chars);
    if pad > 0 {
        spans.push(Span::raw(" ".repeat(pad)));
    }
    spans
}

/// Truncate a label to fit `max` chars, appending `…` when shortened. Returns
/// an empty string if `max` is 0 (caller is responsible for not asking for
/// space it doesn't have).
fn truncate_to(label: &str, max: usize) -> String {
    if max == 0 {
        return String::new();
    }
    if label.chars().count() <= max {
        return label.to_string();
    }
    let head: String = label.chars().take(max - 1).collect();
    format!("{head}…")
}

use crate::ui::widgets::hex_display::format_age_short as format_age;

fn draw_calls_tab(f: &mut Frame, app: &mut App, area: Rect) {
    // Column headers
    let header_area = Rect { height: 1, ..area };
    let list_area = Rect {
        y: area.y + 1,
        height: area.height.saturating_sub(1),
        ..area
    };
    let header = Paragraph::new(Line::from(vec![
        Span::styled("    Sender                   ", theme::SUGGESTION_STYLE),
        Span::styled("Endpoint(s)                    ", theme::SUGGESTION_STYLE),
        Span::styled("Hash          ", theme::SUGGESTION_STYLE),
        Span::styled("Nonce     ", theme::SUGGESTION_STYLE),
        Span::styled("Fee(STRK)        ", theme::SUGGESTION_STYLE),
        Span::styled("Tip              ", theme::SUGGESTION_STYLE),
        Span::styled("Block     ", theme::SUGGESTION_STYLE),
        Span::styled("St  ", theme::SUGGESTION_STYLE),
        Span::styled("Prv ", theme::SUGGESTION_STYLE),
        Span::styled("Age  ", theme::SUGGESTION_STYLE),
    ]));
    f.render_widget(header, header_area);

    if app.address.calls.items.is_empty() {
        let msg = if app.is_loading {
            " Loading contract calls..."
        } else {
            " No calls found"
        };
        f.render_widget(
            Paragraph::new(msg).style(theme::SUGGESTION_STYLE).block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(theme::BORDER_STYLE),
            ),
            list_area,
        );
        return;
    }

    // Refresh the per-sender count + color slot cache. No-op when the calls
    // list hasn't grown since the last render.
    let registry = app.search_engine.as_ref().map(|e| e.registry());
    app.address
        .update_call_color_map(|addr| registry.is_some_and(|r| r.is_known(addr)));

    // If the viewed contract is itself a privacy address, every incoming
    // call in this tab is by definition a privacy interaction — no need to
    // look at `inner_targets` (which would only fire for OE-wrapped flows
    // when viewing a non-privacy contract).
    let viewed_is_privacy = registry
        .zip(app.address.info.as_ref())
        .map(|(reg, info)| reg.is_privacy_address(&info.address))
        .unwrap_or(false);

    let gap_suffix = if app.address.call_gaps.is_empty() {
        event_window_gap_suffix(app)
    } else {
        let n = app.address.call_gaps.len();
        let plural = if n == 1 { "" } else { "s" };
        let any_pending = app.address.call_gaps.iter().any(|g| !g.fill_dispatched);
        if any_pending {
            format!(" — {n} gap{plural} (Enter on a gap row to load) ")
        } else {
            format!(" — {n} gap{plural} (loading…) ")
        }
    };
    let count = call_count_fragment(app);
    let title = if app.is_loading {
        format!(" Calls ({count}) fetching...{gap_suffix} ")
    } else {
        format!(" Calls ({count}){gap_suffix} ")
    };
    let block = list_block(title);

    let gaps = app.address.call_gap_render_positions();
    let window = ListWindow::new(
        app.address.calls.items.len() + gaps.len(),
        app.address.call_list_rendered_selected_with(&gaps),
        app.address.calls_render_state.offset(),
        block.inner(list_area).height as usize,
    );
    let items: Vec<ListItem> = window
        .range()
        .map(|r| match rendered_row(r, &gaps) {
            RenderedRow::Gap(lo) => call_gap_row(app, lo),
            RenderedRow::Item(idx) => call_row(
                app,
                registry,
                viewed_is_privacy,
                &app.address.calls.items[idx],
            ),
        })
        .collect();
    window.render(
        f,
        highlighted_list(items, block),
        list_area,
        &mut app.address.calls_render_state,
    );
}

fn call_gap_row(app: &App, lo_block: u64) -> ListItem<'static> {
    let msg = match app
        .address
        .call_gaps
        .iter()
        .find(|g| g.lo_block == lo_block)
    {
        Some(g) if g.fill_dispatched => {
            format!(
                " ── calls gap (blocks {lo_block}..{}) — loading… ──",
                g.hi_block
            )
        }
        Some(g) => format!(
            " ── calls gap (blocks {lo_block}..{}) — press Enter to load ──",
            g.hi_block
        ),
        None => " ── calls gap ──".to_string(),
    };
    ListItem::new(Line::from(Span::styled(msg, theme::SUGGESTION_STYLE)))
}

fn call_row(
    app: &App,
    registry: Option<&AddressRegistry>,
    viewed_is_privacy: bool,
    call: &ContractCallSummary,
) -> ListItem<'static> {
    let sender_style = known_or_palette_style(&call.sender, registry, &app.address.call_color_map);
    let sender_label = app.format_address(&call.sender);
    let sender_display = if sender_label.chars().count() > 25 {
        let truncated: String = sender_label.chars().take(24).collect();
        format!("{truncated}…")
    } else {
        sender_label
    };
    let func = if call.function_name.chars().count() > 30 {
        let truncated: String = call.function_name.chars().take(29).collect();
        format!("{truncated}…")
    } else {
        call.function_name.clone()
    };
    let fee_str = format_strk_u128(call.total_fee_fri)
        .trim_end_matches(" STRK")
        .to_string();
    let nonce_str = match call.nonce {
        Some(n) => n.to_string(),
        None => "—".to_string(),
    };
    let tip_str = if call.tip > 0 {
        format_fri(call.tip as u128)
    } else {
        "0".to_string()
    };
    let status_style = match call.status.as_str() {
        "OK" => theme::STATUS_OK,
        "REV" => theme::STATUS_REVERTED,
        _ => theme::SUGGESTION_STYLE,
    };

    let tx_label = app.resolve_tx(&call.tx_hash);
    let tx_hash_display = tx_hash_cell(tx_label, &call.tx_hash);
    let tx_hash_style = if tx_label.is_some() {
        theme::LABEL_STYLE
    } else {
        theme::TX_HASH_STYLE
    };

    // Privacy iff the viewed contract is itself a privacy address OR an OE
    // inner target is in the curated bundle (non-privacy forwarder pages).
    let is_privacy_call = viewed_is_privacy
        || registry.is_some_and(|reg| call.inner_targets.iter().any(|t| reg.is_privacy_address(t)));
    let prv_marker_text = if is_privacy_call { "🛡   " } else { "    " };

    ListItem::new(Line::from(vec![
        Span::styled(format!(" {:<25} ", sender_display), sender_style),
        Span::styled(format!("{:<31}", func), theme::LABEL_STYLE),
        Span::styled(format!("{:<14}", tx_hash_display), tx_hash_style),
        Span::styled(format!("{:<10}", nonce_str), theme::NORMAL_STYLE),
        Span::styled(format!("{:<17}", fee_str), theme::TX_FEE_STYLE),
        Span::styled(format!("{:<17}", tip_str), theme::SUGGESTION_STYLE),
        Span::styled(
            format!("#{:<9}", call.block_number),
            theme::BLOCK_NUMBER_STYLE,
        ),
        Span::styled(format!("{:<4}", call.status), status_style),
        Span::styled(prv_marker_text, theme::PRIVACY_STYLE),
        Span::styled(format_age(call.timestamp), theme::BLOCK_AGE_STYLE),
    ]))
}

fn draw_meta_txs_tab(f: &mut Frame, app: &mut App, area: Rect) {
    let header_area = Rect { height: 1, ..area };
    let list_area = Rect {
        y: area.y + 1,
        height: area.height.saturating_sub(1),
        ..area
    };
    // 3 leading spaces match the ">> " highlight_symbol on the list rows.
    let header = Paragraph::new(Line::from(vec![
        Span::styled("   Age   ", theme::SUGGESTION_STYLE),
        Span::styled("Hash          ", theme::SUGGESTION_STYLE),
        Span::styled("Block      ", theme::SUGGESTION_STYLE),
        Span::styled("Paymaster            ", theme::SUGGESTION_STYLE),
        Span::styled("Ver   ", theme::SUGGESTION_STYLE),
        Span::styled("Protocol(s)          ", theme::SUGGESTION_STYLE),
        Span::styled(
            "Endpoint(s)                        ",
            theme::SUGGESTION_STYLE,
        ),
        Span::styled("Fee(STRK)      ", theme::SUGGESTION_STYLE),
        Span::styled("St  ", theme::SUGGESTION_STYLE),
        Span::styled("Prv ", theme::SUGGESTION_STYLE),
    ]));
    f.render_widget(header, header_area);

    if app.address.meta_txs.items.is_empty() {
        let msg = if app.address.fetching_meta_txs || !app.address.meta_txs_dispatched {
            " Scanning for meta-transactions..."
        } else {
            " No meta-transactions found (requires pf-query; only Argent/Braavos accounts)"
        };
        f.render_widget(
            Paragraph::new(msg).style(theme::SUGGESTION_STYLE).block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(theme::BORDER_STYLE),
            ),
            list_area,
        );
        return;
    }

    let gap_suffix = event_window_gap_suffix(app);
    // The body title shares the same fragment helper as the compact tab row.
    let count = meta_tx_count_fragment(app);
    // While an adaptive walk is in flight, surface how far back we've
    // scanned — helpful signal for sparse addresses where the first few
    // windows return nothing and the list appears to hang.
    let scan_suffix = match app.address.event_window.as_ref() {
        Some(hint) if hint.min_searched > 0 && app.address.fetching_meta_txs => {
            format!(" scanned to block {}", hint.min_searched)
        }
        _ => String::new(),
    };
    let title = if app.address.fetching_meta_txs {
        format!(" MetaTxs ({count}) fetching...{scan_suffix}{gap_suffix} ")
    } else {
        format!(" MetaTxs ({count}){gap_suffix} ")
    };
    let block = list_block(title);

    let window = ListWindow::new(
        app.address.meta_txs.items.len(),
        app.address.meta_txs.state.selected(),
        app.address.meta_txs.state.offset(),
        block.inner(list_area).height as usize,
    );
    let items: Vec<ListItem> = app.address.meta_txs.items[window.range()]
        .iter()
        .map(|m| meta_tx_row(app, m))
        .collect();
    window.render(
        f,
        highlighted_list(items, block),
        list_area,
        &mut app.address.meta_txs.state,
    );
}

fn meta_tx_row(app: &App, m: &MetaTxIntenderSummary) -> ListItem<'static> {
    let age = format_age(m.timestamp);
    let paymaster_label = app.format_address(&m.paymaster);
    let paymaster_display = if paymaster_label.chars().count() > 20 {
        let truncated: String = paymaster_label.chars().take(19).collect();
        format!("{truncated}…")
    } else {
        paymaster_label
    };

    // Protocol column: first inner target (labeled) + " +N" if more.
    let protocol = match m.inner_targets.first() {
        Some(t) => {
            let base = app.format_address(t);
            let trimmed: String = if base.chars().count() > 16 {
                let t: String = base.chars().take(15).collect();
                format!("{t}…")
            } else {
                base
            };
            let extra = m.inner_targets.len().saturating_sub(1);
            if extra > 0 {
                format!("{trimmed} +{extra}")
            } else {
                trimmed
            }
        }
        None => "-".to_string(),
    };
    let protocol_display = if protocol.chars().count() > 20 {
        let truncated: String = protocol.chars().take(19).collect();
        format!("{truncated}…")
    } else {
        protocol
    };
    // Privacy detection uses the inner-call targets: that is where an
    // OE-wrapped sponsored tx reaches the pool (the on-chain sender is a relayer).
    let is_privacy_meta = app
        .search_engine
        .as_ref()
        .map(|e| {
            let reg = e.registry();
            m.inner_targets.iter().any(|t| reg.is_privacy_address(t))
        })
        .unwrap_or(false);
    let protocol_style = if is_privacy_meta {
        theme::PRIVACY_STYLE
    } else {
        theme::LABEL_STYLE
    };

    let endpoint = if m.inner_endpoints.chars().count() > 34 {
        let truncated: String = m.inner_endpoints.chars().take(33).collect();
        format!("{truncated}…")
    } else {
        m.inner_endpoints.clone()
    };

    let fee_str = format_strk_u128(m.total_fee_fri)
        .trim_end_matches(" STRK")
        .to_string();

    let status_style = match m.status.as_str() {
        "OK" => theme::STATUS_OK,
        "REV" => theme::STATUS_REVERTED,
        _ => theme::SUGGESTION_STYLE,
    };

    let tx_label = app.resolve_tx(&m.hash);
    let tx_hash_display = tx_hash_cell(tx_label, &m.hash);
    let tx_hash_style = if tx_label.is_some() {
        theme::LABEL_STYLE
    } else {
        theme::TX_HASH_STYLE
    };

    let prv_marker_text = if is_privacy_meta { "🛡   " } else { "    " };
    ListItem::new(Line::from(vec![
        Span::styled(format!(" {:<5}", age), theme::BLOCK_AGE_STYLE),
        Span::styled(format!("{:<14}", tx_hash_display), tx_hash_style),
        Span::styled(
            format!("#{:<10}", m.block_number),
            theme::BLOCK_NUMBER_STYLE,
        ),
        Span::styled(format!("{:<21}", paymaster_display), theme::LABEL_STYLE),
        Span::styled(format!("{:<6}", m.version), theme::SUGGESTION_STYLE),
        Span::styled(format!("{:<21}", protocol_display), protocol_style),
        Span::styled(format!("{:<35}", endpoint), theme::LABEL_STYLE),
        Span::styled(format!("{:<15}", fee_str), theme::TX_FEE_STYLE),
        Span::styled(format!("{:<4}", m.status), status_style),
        Span::styled(prv_marker_text, theme::PRIVACY_STYLE),
    ]))
}

fn draw_balances_tab(
    f: &mut Frame,
    app: &App,
    area: Rect,
    private_by_token: &[(Felt, u128, usize)],
) {
    let info = match &app.address.info {
        Some(i) => i,
        None => return,
    };

    let nonzero: Vec<&TokenBalance> = info
        .token_balances
        .iter()
        .filter(|b| felt_to_u128(&b.balance_raw) > 0)
        .collect();

    // `private_by_token` is computed once per frame in `draw()` and
    // shared with `draw_tabs` so the Balances `Prv (N)` fragment and
    // these rows always agree without scanning `app.private_notes` twice.

    // Layout: when there are private holdings, stack both panels at
    // their natural heights and absorb any leftover space below.
    // Otherwise keep the historical full-area Token Balances widget.
    if private_by_token.is_empty() {
        draw_token_balances(f, app, area, &nonzero);
        return;
    }
    // +2 = border rows (top + bottom). The "+ 1" floor keeps an empty
    // panel from collapsing below "Title" + 1 row.
    let token_rows = nonzero.len().max(1) as u16;
    let token_height = (token_rows + 2).clamp(3, 12);
    let holdings_rows = private_by_token.len() as u16;
    let holdings_height = (holdings_rows + 2).clamp(3, 12);
    let chunks = Layout::default()
        .direction(ratatui::layout::Direction::Vertical)
        .constraints([
            Constraint::Length(token_height),
            Constraint::Length(holdings_height),
            Constraint::Min(0),
        ])
        .split(area);
    draw_token_balances(f, app, chunks[0], &nonzero);
    draw_private_holdings(f, app, chunks[1], private_by_token);
}

/// Pad-or-truncate a token label to a fixed display width so amount
/// columns line up across rows whose token names vary in length (e.g.
/// "STRK" vs. an unknown `0x6d6d…6854`). Truncation marks with `…` so
/// the row stays readable.
fn fmt_token_name(name: &str, width: usize) -> String {
    fmt_fixed_width(name, width)
}

/// Pad-with-spaces or truncate-with-`…` to exactly `width` columns.
/// Used to keep every column in the Balances tab at a fixed character
/// budget so the `·` separator aligns regardless of value length —
/// otherwise an unknown-decimals raw u128 amount (~20 digits) bumps
/// the suffix off-grid.
fn fmt_fixed_width(s: &str, width: usize) -> String {
    let len = s.chars().count();
    if len <= width {
        let pad = " ".repeat(width - len);
        format!("{s}{pad}")
    } else if width == 0 {
        String::new()
    } else {
        let truncated: String = s.chars().take(width.saturating_sub(1)).collect();
        format!("{truncated}…")
    }
}

fn draw_token_balances(f: &mut Frame, app: &App, area: Rect, nonzero: &[&TokenBalance]) {
    if nonzero.is_empty() {
        f.render_widget(
            Paragraph::new(" No token balances found")
                .style(theme::SUGGESTION_STYLE)
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_style(theme::BORDER_STYLE)
                        .title(Span::styled(" Token Balances ", theme::TITLE_STYLE)),
                ),
            area,
        );
        return;
    }

    let items: Vec<ListItem> = nonzero
        .iter()
        .map(|bal| {
            let formatted = format_token_balance(bal);
            let usd_str = balance_usd_value(app, bal)
                .map(price::format_usd)
                .unwrap_or_default();
            let spans = vec![
                Span::styled(
                    format!(" {}  ", fmt_token_name(&bal.token_name, 10)),
                    theme::LABEL_STYLE,
                ),
                Span::styled(fmt_fixed_width(&formatted, 18), theme::NORMAL_STYLE),
                Span::styled(format!("  {usd_str}"), theme::SUGGESTION_STYLE),
            ];
            ListItem::new(Line::from(spans))
        })
        .collect();

    let list = List::new(items).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(theme::BORDER_STYLE)
            .title(Span::styled(" Token Balances ", theme::TITLE_STYLE)),
    );
    f.render_widget(list, area);
}

/// Sum unspent incoming decrypted-note amounts for `address`, grouped by
/// token. Returns `(token, amount, n_unspent_notes)` rows sorted by
/// amount descending. Empty when the address has no viewing key, no
/// notes synced yet, or every note is spent.
fn compute_private_holdings(app: &App, address: Felt) -> Vec<(Felt, u128, usize)> {
    use crate::decode::privacy_sync::NoteDirection;
    let mut by_token: std::collections::HashMap<Felt, (u128, usize)> =
        std::collections::HashMap::new();
    for note in app.private_notes.values() {
        if note.user != address {
            continue;
        }
        if note.spent {
            continue;
        }
        if note.direction != NoteDirection::Incoming {
            continue;
        }
        let entry = by_token.entry(note.token).or_insert((0u128, 0usize));
        entry.0 = entry.0.saturating_add(note.amount);
        entry.1 += 1;
    }
    let mut rows: Vec<(Felt, u128, usize)> =
        by_token.into_iter().map(|(t, (a, n))| (t, a, n)).collect();
    rows.sort_by(|a, b| b.1.cmp(&a.1));
    rows
}

fn draw_private_holdings(f: &mut Frame, app: &App, area: Rect, rows: &[(Felt, u128, usize)]) {
    let items: Vec<ListItem> = rows
        .iter()
        .map(|(token, amount, n_unspent)| {
            // Prefer the registry/runtime-fetched ticker over the
            // truncated address. `App::token_symbol` consults the
            // static registry first, then `fetched_token_metadata`, so
            // tokens whose `symbol()` was just fetched render the
            // ticker (e.g. `USDS`) instead of `0x6d6d…68…`.
            let token_name = app.token_symbol(token).unwrap_or_else(|| short_addr(token));
            let amount_str =
                crate::ui::views::tx_detail::format_amount_for_token(app, token, *amount);
            let suffix = if *n_unspent == 1 {
                "1 unspent note".to_string()
            } else {
                format!("{} unspent notes", n_unspent)
            };
            let usd_str = private_holding_usd(app, token, *amount)
                .map(price::format_usd)
                .unwrap_or_default();
            let spans = vec![
                Span::styled(
                    format!(" {}  ", fmt_token_name(&token_name, 10)),
                    theme::LABEL_STYLE,
                ),
                Span::styled(fmt_fixed_width(&amount_str, 18), theme::NORMAL_STYLE),
                Span::styled(
                    format!("  {}", fmt_fixed_width(&usd_str, 8)),
                    theme::SUGGESTION_STYLE,
                ),
                Span::styled(format!("  · {}", suffix), theme::SUGGESTION_STYLE),
            ];
            ListItem::new(Line::from(spans))
        })
        .collect();

    let list = List::new(items).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(theme::BORDER_STYLE)
            .title(Span::styled(
                " Private holdings (viewing key) ",
                theme::PRIVACY_STYLE,
            )),
    );
    f.render_widget(list, area);
}

fn short_addr(felt: &Felt) -> String {
    let s = format!("{:#x}", felt);
    if s.len() <= 10 {
        s
    } else {
        format!("{}…{}", &s[..6], &s[s.len() - 4..])
    }
}

/// USD value of a (token, raw u128 amount) pair using today's price and
/// registry-known decimals. Same semantics as `balance_usd_value` but
/// for inputs that don't have a `TokenBalance` struct (e.g. summed
/// private-note amounts).
fn private_holding_usd(app: &App, token: &Felt, amount: u128) -> Option<f64> {
    let price = app.price_client.as_ref()?.get_today_price(token)?;
    let registry = app.search_engine.as_ref().map(|e| e.registry())?;
    let decimals = registry.get_decimals(token)? as i32;
    let raw = amount as f64;
    let scale = 10f64.powi(decimals);
    Some(raw / scale * price)
}

fn balance_usd_value(app: &App, bal: &TokenBalance) -> Option<f64> {
    let price = app
        .price_client
        .as_ref()?
        .get_today_price(&bal.token_address)?;
    let raw = felt_to_u128(&bal.balance_raw) as f64;
    let scale = 10f64.powi(bal.decimals as i32);
    Some(raw / scale * price)
}

fn draw_transfers_tab(f: &mut Frame, app: &mut App, area: Rect) {
    let header_area = Rect { height: 1, ..area };
    let list_area = Rect {
        y: area.y + 1,
        height: area.height.saturating_sub(1),
        ..area
    };
    let header = Paragraph::new(Line::from(vec![
        Span::styled("    Dir  ", theme::SUGGESTION_STYLE),
        Span::styled("Token       ", theme::SUGGESTION_STYLE),
        Span::styled("             Amount ", theme::SUGGESTION_STYLE),
        Span::styled("          USD ", theme::SUGGESTION_STYLE),
        Span::styled("From                    ", theme::SUGGESTION_STYLE),
        Span::styled("To                      ", theme::SUGGESTION_STYLE),
        Span::styled("Tx             ", theme::SUGGESTION_STYLE),
        Span::styled("Block      ", theme::SUGGESTION_STYLE),
        Span::styled("Age  ", theme::SUGGESTION_STYLE),
    ]));
    f.render_widget(header, header_area);

    let gaps = app.address.transfer_gap_render_positions();
    if app.address.transfers.items.is_empty() && gaps.is_empty() {
        let msg = if app.address.fetching_transfers {
            " Loading transfers..."
        } else if app.address.transfers_dispatched {
            " No transfers found"
        } else {
            " Press Tab to reach this tab; transfers load on entry"
        };
        f.render_widget(
            Paragraph::new(msg).style(theme::SUGGESTION_STYLE).block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(theme::BORDER_STYLE),
            ),
            list_area,
        );
        return;
    }

    let registry = app.search_engine.as_ref().map(|e| e.registry());
    app.address
        .update_transfer_color_map(|addr| registry.is_some_and(|r| r.is_known(addr)));

    let gap_suffix = if app.address.transfer_gaps.is_empty() {
        String::new()
    } else {
        let n = app.address.transfer_gaps.len();
        let plural = if n == 1 { "" } else { "s" };
        if app.address.transfer_gaps.iter().any(|g| !g.fill_dispatched) {
            format!(" — {n} gap{plural} (Enter on a gap row to load) ")
        } else {
            format!(" — {n} gap{plural} (loading…) ")
        }
    };
    let count = transfers_count_fragment(app);
    let title = if app.address.fetching_transfers {
        format!(" Transfers ({count}) fetching...{gap_suffix} ")
    } else {
        format!(" Transfers ({count}){gap_suffix} ")
    };
    let block = list_block(title);

    let viewed = app.address.context.unwrap_or(Felt::ZERO);
    let selected_nav: Option<&TxNavItem> = if app.address.visual_mode {
        app.address.nav_items.get(app.address.nav_cursor)
    } else {
        None
    };
    let window = ListWindow::new(
        app.address.transfers.items.len() + gaps.len(),
        app.address.transfer_list_rendered_selected_with(&gaps),
        app.address.transfers_render_state.offset(),
        block.inner(list_area).height as usize,
    );
    let items: Vec<ListItem> = window
        .range()
        .map(|r| match rendered_row(r, &gaps) {
            RenderedRow::Gap(lo) => transfer_gap_row(app, lo),
            RenderedRow::Item(idx) => transfer_row(
                app,
                registry,
                viewed,
                selected_nav,
                &app.address.transfers.items[idx],
            ),
        })
        .collect();
    window.render(
        f,
        highlighted_list(items, block),
        list_area,
        &mut app.address.transfers_render_state,
    );
}

fn transfer_gap_row(app: &App, lo_block: u64) -> ListItem<'static> {
    let Some(g) = app
        .address
        .transfer_gaps
        .iter()
        .find(|g| g.lo_block == lo_block)
    else {
        return ListItem::new(Line::from(Span::styled(
            " ── transfers gap ──",
            theme::SUGGESTION_STYLE,
        )));
    };
    let is_bottom = g.lo_block == app.address.transfer_floor();
    let span = g.hi_block.saturating_sub(g.lo_block).saturating_add(1);
    let what = if is_bottom {
        format!(
            "{span} older blocks unsearched (below block {})",
            g.hi_block + 1
        )
    } else {
        format!("transfers gap (blocks {}..{})", g.lo_block, g.hi_block)
    };
    let action = match (g.fill_dispatched, is_bottom) {
        (true, _) => "loading…",
        (false, true) => "press Enter to search further",
        (false, false) => "press Enter to load",
    };
    ListItem::new(Line::from(Span::styled(
        format!(" ── {what} — {action} ──"),
        theme::SUGGESTION_STYLE,
    )))
}

/// USD value at transfer time: the indexer's figure when it priced the row,
/// else amount × DefiLlama's day price for tracked tokens.
fn transfer_value_usd(app: &App, t: &TokenTransfer) -> Option<f64> {
    if let Some(v) = t.value_usd {
        return Some(v);
    }
    if t.amount_high != 0 || t.timestamp == 0 {
        return None;
    }
    let decimals = app.token_decimals(&t.token).or(t.decimals)?;
    let (_, historic) = price::token_prices(app, &t.token, Some(t.timestamp));
    Some(t.amount_low as f64 / 10f64.powi(decimals as i32) * historic?)
}

/// Address cell for the From/To columns: the viewed address always takes the
/// sender style so it is marked the same way in either column; the current
/// visual-mode item overrides everything.
fn transfer_party_style(
    app: &App,
    registry: Option<&AddressRegistry>,
    viewed: Felt,
    selected_nav: Option<&TxNavItem>,
    addr: &Felt,
) -> ratatui::style::Style {
    if matches!(selected_nav, Some(TxNavItem::Address(a)) if a == addr) {
        return theme::VISUAL_SELECTED_STYLE;
    }
    if *addr == viewed {
        return theme::TX_SENDER_STYLE;
    }
    known_or_palette_style(addr, registry, &app.address.transfer_color_map)
}

fn transfer_row(
    app: &App,
    registry: Option<&AddressRegistry>,
    viewed: Felt,
    selected_nav: Option<&TxNavItem>,
    t: &TokenTransfer,
) -> ListItem<'static> {
    let (dir, dir_style) = match (t.from == viewed, t.to == viewed) {
        (true, true) => ("SELF", theme::SUGGESTION_STYLE),
        (false, true) => ("IN", theme::STATUS_OK),
        (true, false) => ("OUT", theme::STATUS_REVERTED),
        (false, false) => ("?", theme::SUGGESTION_STYLE),
    };

    let token_label = app
        .token_symbol(&t.token)
        .or_else(|| t.symbol.clone())
        .unwrap_or_else(|| short_address(&t.token));
    let token_style = if matches!(selected_nav, Some(TxNavItem::Address(a)) if *a == t.token) {
        theme::VISUAL_SELECTED_STYLE
    } else if registry.is_some_and(|r| r.is_known(&t.token)) {
        theme::LABEL_STYLE
    } else {
        theme::NORMAL_STYLE
    };

    let amount = match app.token_decimals(&t.token).or(t.decimals) {
        Some(d) => format_token_amount(t.amount_low, t.amount_high, d),
        None if t.amount_high == 0 => t.amount_low.to_string(),
        None => format!("0x{:x}{:032x}", t.amount_high, t.amount_low),
    };

    let usd = transfer_value_usd(app, t)
        .map(price::format_usd)
        .unwrap_or_default();

    let from_style = transfer_party_style(app, registry, viewed, selected_nav, &t.from);
    let to_style = transfer_party_style(app, registry, viewed, selected_nav, &t.to);

    let tx_label = app.resolve_tx(&t.tx_hash);
    let tx_style = if matches!(selected_nav, Some(TxNavItem::Transaction(h)) if *h == t.tx_hash) {
        theme::VISUAL_SELECTED_STYLE
    } else if tx_label.is_some() {
        theme::LABEL_STYLE
    } else {
        theme::TX_HASH_STYLE
    };
    let block_style = if matches!(selected_nav, Some(TxNavItem::Block(b)) if *b == t.block_number) {
        theme::VISUAL_SELECTED_STYLE
    } else {
        theme::BLOCK_NUMBER_STYLE
    };

    ListItem::new(Line::from(vec![
        Span::styled(format!(" {dir:<4} "), dir_style),
        Span::styled(
            format!("{:<12}", truncate_to(&token_label, 11)),
            token_style,
        ),
        Span::styled(
            format!("{:>19} ", truncate_to(&amount, 19)),
            theme::TX_HASH_STYLE,
        ),
        Span::styled(
            format!("{:>13} ", truncate_to(&usd, 13)),
            theme::SUGGESTION_STYLE,
        ),
        Span::styled(
            format!("{:<24}", truncate_to(&app.format_address(&t.from), 23)),
            from_style,
        ),
        Span::styled(
            format!("{:<24}", truncate_to(&app.format_address(&t.to), 23)),
            to_style,
        ),
        Span::styled(
            format!("{:<15}", tx_hash_cell(tx_label, &t.tx_hash)),
            tx_style,
        ),
        Span::styled(format!("{:<11}", t.block_number), block_style),
        Span::styled(format_age(t.timestamp), theme::BLOCK_AGE_STYLE),
    ]))
}

fn draw_events_tab(f: &mut Frame, app: &mut App, area: Rect) {
    // Column headers
    let header_area = Rect { height: 1, ..area };
    let list_area = Rect {
        y: area.y + 1,
        height: area.height.saturating_sub(1),
        ..area
    };
    let header = Paragraph::new(Line::from(vec![
        Span::styled("    Event               ", theme::SUGGESTION_STYLE),
        Span::styled("Contract         ", theme::SUGGESTION_STYLE),
        Span::styled("Tx             ", theme::SUGGESTION_STYLE),
    ]));
    f.render_widget(header, header_area);

    if app.address.events.items.is_empty() {
        let msg = if app.is_loading {
            " Loading events..."
        } else {
            " No events found"
        };
        f.render_widget(
            Paragraph::new(msg).style(theme::SUGGESTION_STYLE).block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(theme::BORDER_STYLE),
            ),
            list_area,
        );
        return;
    }

    let count = events_count_fragment(app);
    let title = if app.is_loading {
        format!(" Events ({count}) fetching... ")
    } else {
        format!(" Events ({count}) ")
    };
    let block = list_block(title);

    let window = ListWindow::new(
        app.address.events.items.len(),
        app.address.events.state.selected(),
        app.address.events.state.offset(),
        block.inner(list_area).height as usize,
    );
    let items: Vec<ListItem> = app.address.events.items[window.range()]
        .iter()
        .map(|event| {
            let contract = app.format_address(&event.contract_address);
            let name = event.event_name.as_deref().unwrap_or("?");
            let tx_hash = event.raw.transaction_hash;
            let tx_label = app.resolve_tx(&tx_hash);
            let tx_display = tx_hash_cell(tx_label, &tx_hash);
            let tx_style = if tx_label.is_some() {
                theme::LABEL_STYLE
            } else {
                theme::TX_HASH_STYLE
            };
            ListItem::new(Line::from(vec![
                Span::styled(format!(" {:<20}", name), theme::LABEL_STYLE),
                Span::styled(format!("{:<17}", contract), theme::BLOCK_HASH_STYLE),
                Span::styled(tx_display, tx_style),
            ]))
        })
        .collect();
    window.render(
        f,
        highlighted_list(items, block),
        list_area,
        &mut app.address.events.state,
    );
}

fn format_token_balance(bal: &TokenBalance) -> String {
    let raw = felt_to_u128(&bal.balance_raw);
    if raw == 0 {
        return "0".to_string();
    }
    let divisor = 10u128.pow(bal.decimals as u32);
    let whole = raw / divisor;
    let frac = raw % divisor;
    let frac_digits = bal.decimals.min(6) as u32;
    let frac_divisor = 10u128.pow(bal.decimals as u32 - frac_digits);
    let frac_display = frac / frac_divisor;
    format!(
        "{}.{:0>width$}",
        whole,
        frac_display,
        width = frac_digits as usize
    )
}

fn draw_class_history_tab(f: &mut Frame, app: &App, area: Rect) {
    let header_area = Rect { height: 1, ..area };
    let list_area = Rect {
        y: area.y + 1,
        height: area.height.saturating_sub(1),
        ..area
    };
    let header = Paragraph::new(Line::from(vec![
        Span::styled("   Block          ", theme::SUGGESTION_STYLE),
        Span::styled(
            "Class Hash                                                              ",
            theme::SUGGESTION_STYLE,
        ),
    ]));
    f.render_widget(header, header_area);

    if app.address.class_history.is_empty() {
        let msg = if app.is_loading {
            " Loading class history..."
        } else {
            " No class history available (requires PF service)"
        };
        f.render_widget(
            Paragraph::new(msg).style(theme::SUGGESTION_STYLE).block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(theme::BORDER_STYLE),
            ),
            list_area,
        );
        return;
    }

    let items: Vec<ListItem> = app
        .address
        .class_history
        .iter()
        .enumerate()
        .map(|(i, entry)| {
            let hash_display = if entry.class_hash.len() > 66 {
                format!("{}…", &entry.class_hash[..65])
            } else {
                entry.class_hash.clone()
            };
            let is_selected = i == app.address.class_history_scroll;
            let hash_style = if is_selected {
                theme::VISUAL_SELECTED_STYLE
            } else {
                theme::TX_HASH_STYLE
            };
            let marker = if is_selected { "►" } else { " " };
            let line = Line::from(vec![
                Span::styled(
                    marker,
                    if is_selected {
                        theme::VISUAL_SELECTED_STYLE
                    } else {
                        theme::NORMAL_STYLE
                    },
                ),
                Span::styled(
                    format!("#{:<14}", entry.block_number),
                    theme::BLOCK_NUMBER_STYLE,
                ),
                Span::styled(format!("{:<68}", hash_display), hash_style),
            ]);
            ListItem::new(line)
        })
        .collect();

    let list = List::new(items).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(theme::BORDER_STYLE),
    );
    f.render_widget(list, list_area);
}

#[cfg(test)]
mod count_fragment_tests {
    //! The count-fragment helper is the single source of truth for what the
    //! four address-view tabs render inside `(...)`. These tests pin its
    //! five distinct display outputs so regressions show up here before
    //! they surface on screen.
    use super::{CountBound, count_fragment};

    #[test]
    fn exact_shown_less_than_total_renders_fraction() {
        assert_eq!(count_fragment(7, CountBound::Exact(20)), "7 / 20");
    }

    #[test]
    fn exact_shown_equal_total_renders_bare_count() {
        assert_eq!(count_fragment(20, CountBound::Exact(20)), "20");
    }

    #[test]
    fn exact_shown_greater_than_total_falls_back_to_bare_count() {
        // Stale probe: Dune total lags an active stream. Never render a
        // negative-looking "20 / 7" — fall back to the authoritative shown.
        assert_eq!(count_fragment(20, CountBound::Exact(7)), "20");
    }

    #[test]
    fn lower_bound_without_hint_renders_shown_over_shown_plus() {
        // No hint ⇒ denominator defaults to `shown` itself. We know at
        // least N items exist, so "N / N+" is both truthful and keeps
        // the Shown/Known format across every tab state.
        assert_eq!(
            count_fragment(7, CountBound::LowerBound { hint: None }),
            "7 / 7+"
        );
    }

    #[test]
    fn lower_bound_zero_renders_zero_over_zero_plus() {
        // The cold-state display the user wants on every tab — never a
        // bare "0" or an empty label while probes are still warming up.
        assert_eq!(
            count_fragment(0, CountBound::LowerBound { hint: None }),
            "0 / 0+"
        );
    }

    #[test]
    fn lower_bound_with_hint_above_shown_renders_fraction_plus() {
        assert_eq!(
            count_fragment(7, CountBound::LowerBound { hint: Some(100) }),
            "7 / 100+"
        );
    }

    #[test]
    fn lower_bound_with_hint_at_or_below_shown_falls_back_to_shown_denominator() {
        // Hint is stale or conservative; we still want the Shown/Known
        // format, so fall back to "shown / shown+" rather than a
        // misleading "7 / 3+".
        assert_eq!(
            count_fragment(7, CountBound::LowerBound { hint: Some(3) }),
            "7 / 7+"
        );
        assert_eq!(
            count_fragment(7, CountBound::LowerBound { hint: Some(7) }),
            "7 / 7+"
        );
    }
}