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
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::app::App;
use crate::app::actions::Action;
use crate::app::state::{Focus, InputMode, NavTarget, View};
use crate::utils::felt_to_u64;

/// Handle a key event and return an optional Action to dispatch to the network task.
pub fn handle_key(app: &mut App, key: KeyEvent) -> Option<Action> {
    // Ctrl+C always quits
    if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
        app.should_quit = true;
        return None;
    }

    match app.input_mode {
        InputMode::Normal => handle_normal_mode(app, key),
        InputMode::Search => handle_search_mode(app, key),
    }
}

fn handle_normal_mode(app: &mut App, key: KeyEvent) -> Option<Action> {
    // Intercept all keys when TxDetail visual mode is active
    if app.tx_detail.visual_mode && app.current_view() == View::TxDetail {
        return handle_tx_visual_mode(app, key);
    }

    // Intercept all keys when BlockDetail visual mode is active
    if app.block_detail.visual_mode && app.current_view() == View::BlockDetail {
        return handle_block_visual_mode(app, key);
    }

    // Intercept all keys when ClassInfo visual mode is active
    if app.class.visual_mode && app.current_view() == View::ClassInfo {
        return handle_class_visual_mode(app, key);
    }

    // Intercept all keys when AddressInfo visual mode is active
    if app.address.visual_mode && app.current_view() == View::AddressInfo {
        return handle_address_visual_mode(app, key);
    }

    match key.code {
        // q: jump to Blocks root (clearing forward history), or quit if already there
        KeyCode::Char('q') => {
            app.go_to_root_or_quit();
            None
        }

        // Search mode
        KeyCode::Char('/') => {
            app.input_mode = InputMode::Search;
            app.focus = Focus::SearchBar;
            app.search_input.clear();
            app.search_cursor = 0;
            app.search_suggestions.clear();
            app.search_selected = 0;
            None
        }

        // Navigation: down
        KeyCode::Char('j') | KeyCode::Down => {
            app.select_next();
            None
        }

        // Navigation: up
        KeyCode::Char('k') | KeyCode::Up => {
            app.select_previous();
            None
        }

        // Navigation: back one view (saves to forward history for Ctrl+i)
        KeyCode::Char('h') | KeyCode::Left => {
            app.pop_view_saving_forward();
            None
        }

        // Ctrl+o: back one view (vim-style jump back)
        KeyCode::Char('o') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            app.pop_view_saving_forward();
            None
        }

        // Navigation: forward / drill in
        KeyCode::Char('l') | KeyCode::Right | KeyCode::Enter => handle_enter(app),

        // Jump to top
        KeyCode::Char('g') => {
            app.select_first();
            None
        }

        // Jump to bottom
        KeyCode::Char('G') => {
            app.select_last();
            None
        }

        // Ctrl+U / PgUp: page-scroll the active list (in TxDetail: scroll
        // the active tab body up; Tab/Shift+Tab switches tabs).
        KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => handle_cycle(app, 1),
        KeyCode::PageUp => handle_cycle(app, 1),

        // Ctrl+D / PgDn: page-scroll the active list (in TxDetail: scroll
        // the active tab body down).
        KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            handle_cycle(app, -1)
        }
        KeyCode::PageDown => handle_cycle(app, -1),

        // Ctrl+P: scroll UP the primary axis. BlockDetail: block N+1.
        // TxDetail: higher tx idx, wrapping at the top to tx idx 0 of block N+1.
        KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::CONTROL) => handle_axis(app, -1),

        // Ctrl+N: scroll DOWN the primary axis. BlockDetail: block N-1.
        // TxDetail: lower tx idx, wrapping at the bottom (tx idx 0) to the
        // highest tx idx of block N-1.
        KeyCode::Char('n') if key.modifiers.contains(KeyModifiers::CONTROL) => handle_axis(app, 1),

        // Tab / Shift+Tab: cycle tabs forward/backward.
        KeyCode::Tab => {
            if app.current_view() == View::AddressInfo {
                app.address.tab = match app.address.tab {
                    crate::app::AddressTab::Transactions => crate::app::AddressTab::MetaTxs,
                    crate::app::AddressTab::MetaTxs => crate::app::AddressTab::Calls,
                    crate::app::AddressTab::Calls => crate::app::AddressTab::Balances,
                    crate::app::AddressTab::Balances => crate::app::AddressTab::Transfers,
                    crate::app::AddressTab::Transfers => crate::app::AddressTab::Events,
                    crate::app::AddressTab::Events => crate::app::AddressTab::ClassHistory,
                    crate::app::AddressTab::ClassHistory => crate::app::AddressTab::Transactions,
                };
                app.maybe_fetch_address_transfers();
                return maybe_dispatch_meta_txs_on_entry(app);
            }
            if app.current_view() == View::TxDetail {
                let has_privacy = tx_detail_has_privacy(app);
                app.tx_detail.active_tab = app.tx_detail.active_tab.next_visible(has_privacy);
            }
            None
        }
        KeyCode::BackTab => {
            if app.current_view() == View::AddressInfo {
                app.address.tab = match app.address.tab {
                    crate::app::AddressTab::Transactions => crate::app::AddressTab::ClassHistory,
                    crate::app::AddressTab::MetaTxs => crate::app::AddressTab::Transactions,
                    crate::app::AddressTab::Calls => crate::app::AddressTab::MetaTxs,
                    crate::app::AddressTab::Balances => crate::app::AddressTab::Calls,
                    crate::app::AddressTab::Transfers => crate::app::AddressTab::Balances,
                    crate::app::AddressTab::Events => crate::app::AddressTab::Transfers,
                    crate::app::AddressTab::ClassHistory => crate::app::AddressTab::Events,
                };
                app.maybe_fetch_address_transfers();
                return maybe_dispatch_meta_txs_on_entry(app);
            }
            if app.current_view() == View::TxDetail {
                let has_privacy = tx_detail_has_privacy(app);
                app.tx_detail.active_tab = app.tx_detail.active_tab.prev_visible(has_privacy);
            }
            None
        }

        // ]: jump forward in history (replaces Ctrl+i which terminals map to Tab)
        KeyCode::Char(']') => app.navigate_forward(),

        // n/N: nonce-based tx cycling (TxDetail; matches visual scroll
        // direction — n goes down to the older tx, N goes up to the newer).
        KeyCode::Char('n') => handle_nonce_cycle(app, -1),
        KeyCode::Char('N') => handle_nonce_cycle(app, 1),

        // Refresh
        KeyCode::Char('r') => match app.current_view() {
            View::AddressInfo => {
                if let Some(addr) = app.address.context {
                    app.is_loading = true;
                    Some(Action::FetchAddressInfo { address: addr })
                } else {
                    None
                }
            }
            View::ClassInfo => {
                if let Some(ch) = app.class.hash {
                    app.clear_class_info();
                    Some(Action::FetchClassInfo { class_hash: ch })
                } else {
                    None
                }
            }
            _ => Some(Action::FetchRecentBlocks { count: 50 }),
        },

        // Help toggle
        KeyCode::Char('?') => {
            app.show_help = !app.show_help;
            None
        }

        // Escape: back one view (saves forward history)
        KeyCode::Esc => {
            app.pop_view_saving_forward();
            None
        }

        // v: enter visual mode in TxDetail (cycle through navigable items
        // within the active tab + always-visible Header items)
        KeyCode::Char('v') if app.current_view() == View::TxDetail => {
            if !app.tx_detail.nav_items.is_empty() {
                app.tx_detail.visual_mode = true;
                app.tx_detail.reset_nav_cursor_for_active_tab();
            }
            None
        }

        // v: enter visual mode in AddressInfo: header items (class, deploy tx,
        // block, deployer) plus, on the Transfers tab, the selected row's items.
        KeyCode::Char('v') if app.current_view() == View::AddressInfo => {
            app.address.build_nav_items();
            if !app.address.nav_items.is_empty() {
                app.address.visual_mode = true;
            }
            None
        }

        // v: enter visual mode in ClassInfo (cycle through navigable items)
        KeyCode::Char('v') if app.current_view() == View::ClassInfo => {
            if !app.class.nav_items.is_empty() {
                app.class.visual_mode = true;
                app.class.nav_cursor = 0;
            }
            None
        }

        // v: enter visual mode in BlockDetail (cycle through tx senders)
        KeyCode::Char('v') if app.current_view() == View::BlockDetail => {
            if !app.block_detail.txs.items.is_empty() {
                app.block_detail.visual_mode = true;
                app.block_detail.nav_cursor = app.block_detail.txs.state.selected().unwrap_or(0);
            }
            None
        }

        // a: toggle ABI display in ClassInfo
        KeyCode::Char('a') if app.current_view() == View::ClassInfo => {
            app.class.show_abi = !app.class.show_abi;
            None
        }

        // c: toggle calldata display in TxDetail. The toggle only takes effect
        // in the Calls tab, so jump there if the user pressed it elsewhere.
        KeyCode::Char('c') if app.current_view() == View::TxDetail => {
            app.tx_detail.active_tab = crate::app::views::tx_detail::TxTab::Calls;
            app.tx_detail.show_calldata = !app.tx_detail.show_calldata;
            None
        }

        // d: toggle decoded calldata display in TxDetail (Calls tab).
        KeyCode::Char('d') if app.current_view() == View::TxDetail => {
            app.tx_detail.active_tab = crate::app::views::tx_detail::TxTab::Calls;
            app.tx_detail.show_decoded_calldata = !app.tx_detail.show_decoded_calldata;
            None
        }

        // o: toggle outside execution intent view in TxDetail (Calls tab).
        KeyCode::Char('o') if app.current_view() == View::TxDetail => {
            if !app.tx_detail.outside_executions.is_empty() {
                app.tx_detail.active_tab = crate::app::views::tx_detail::TxTab::Calls;
                app.tx_detail.show_outside_execution = !app.tx_detail.show_outside_execution;
                // OE inner-call rows appear/disappear with this toggle;
                // rebuild so visual mode doesn't park on a hidden row.
                app.build_tx_nav_items();
            }
            None
        }

        // e: toggle "expand everything" in TxDetail (Calls + Trace tabs).
        // Master switch — un-truncates hashes, expands structs/arrays inline,
        // and forces decoded-calldata + outside-exec intent on.
        KeyCode::Char('e') if app.current_view() == View::TxDetail => {
            app.tx_detail.expand_all = !app.tx_detail.expand_all;
            // Same reason as `o`: OE inner-call rows are gated on
            // `expand_all`, so the nav set has to follow.
            app.build_tx_nav_items();
            None
        }

        _ => None,
    }
}

/// Handle key events when TxDetail visual mode is active.
fn handle_tx_visual_mode(app: &mut App, key: KeyEvent) -> Option<Action> {
    match key.code {
        KeyCode::Char('j') | KeyCode::Down => {
            app.tx_nav_step(1);
            None
        }
        KeyCode::Char('k') | KeyCode::Up => {
            app.tx_nav_step(-1);
            None
        }
        // Tab / Shift+Tab inside visual mode: switch tabs without leaving
        // visual mode, and snap the cursor to the first item visible from
        // the new tab so the highlight stays valid.
        KeyCode::Tab => {
            let has_privacy = tx_detail_has_privacy(app);
            app.tx_detail.active_tab = app.tx_detail.active_tab.next_visible(has_privacy);
            app.tx_detail.reset_nav_cursor_for_active_tab();
            None
        }
        KeyCode::BackTab => {
            let has_privacy = tx_detail_has_privacy(app);
            app.tx_detail.active_tab = app.tx_detail.active_tab.prev_visible(has_privacy);
            app.tx_detail.reset_nav_cursor_for_active_tab();
            None
        }
        KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => {
            let item = app
                .tx_detail
                .nav_items
                .get(app.tx_detail.nav_cursor)
                .cloned();
            item.and_then(|i| app.navigate_to(NavTarget::from_nav_item(&i)))
        }
        KeyCode::Char('c') => {
            app.tx_detail.show_calldata = !app.tx_detail.show_calldata;
            None
        }
        KeyCode::Char('d') => {
            app.tx_detail.show_decoded_calldata = !app.tx_detail.show_decoded_calldata;
            None
        }
        KeyCode::Char('o') => {
            if !app.tx_detail.outside_executions.is_empty() {
                app.tx_detail.show_outside_execution = !app.tx_detail.show_outside_execution;
                app.build_tx_nav_items();
                app.tx_detail.reset_nav_cursor_for_active_tab();
            }
            None
        }
        KeyCode::Esc => {
            app.tx_detail.visual_mode = false;
            None
        }
        _ => None,
    }
}

/// Handle key events when BlockDetail visual mode is active.
fn handle_block_visual_mode(app: &mut App, key: KeyEvent) -> Option<Action> {
    match key.code {
        KeyCode::Char('j') | KeyCode::Down => {
            let max = app.block_detail.txs.items.len().saturating_sub(1);
            app.block_detail.nav_cursor = (app.block_detail.nav_cursor + 1).min(max);
            app.block_detail
                .txs
                .state
                .select(Some(app.block_detail.nav_cursor));
            None
        }
        KeyCode::Char('k') | KeyCode::Up => {
            app.block_detail.nav_cursor = app.block_detail.nav_cursor.saturating_sub(1);
            app.block_detail
                .txs
                .state
                .select(Some(app.block_detail.nav_cursor));
            None
        }
        KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => {
            let addr = app
                .block_detail
                .txs
                .items
                .get(app.block_detail.nav_cursor)
                .map(|tx| tx.sender());
            addr.and_then(|a| app.navigate_to(NavTarget::Address(a)))
        }
        KeyCode::Esc => {
            app.block_detail.visual_mode = false;
            None
        }
        _ => None,
    }
}

/// Handle key events when ClassInfo visual mode is active.
fn handle_class_visual_mode(app: &mut App, key: KeyEvent) -> Option<Action> {
    match key.code {
        KeyCode::Char('j') | KeyCode::Down => {
            app.class_nav_step(1);
            None
        }
        KeyCode::Char('k') | KeyCode::Up => {
            app.class_nav_step(-1);
            None
        }
        KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => {
            let item = app.class.nav_items.get(app.class.nav_cursor).cloned();
            item.and_then(|i| app.navigate_to(NavTarget::from_nav_item(&i)))
        }
        KeyCode::Esc => {
            app.class.visual_mode = false;
            None
        }
        _ => None,
    }
}

/// Handle key events when AddressInfo visual mode is active (header navigation).
fn handle_address_visual_mode(app: &mut App, key: KeyEvent) -> Option<Action> {
    match key.code {
        KeyCode::Char('j') | KeyCode::Down => {
            app.address_nav_step(1);
            None
        }
        KeyCode::Char('k') | KeyCode::Up => {
            app.address_nav_step(-1);
            None
        }
        KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => {
            let item = app.address.nav_items.get(app.address.nav_cursor).cloned();
            item.and_then(|i| app.navigate_to(NavTarget::from_nav_item(&i)))
        }
        KeyCode::Esc => {
            app.address.visual_mode = false;
            None
        }
        _ => None,
    }
}

fn handle_search_mode(app: &mut App, key: KeyEvent) -> Option<Action> {
    // Arrow keys navigate dropdown when suggestions are visible
    if !app.search_suggestions.is_empty() {
        match key.code {
            KeyCode::Down => {
                app.search_selected =
                    (app.search_selected + 1).min(app.search_suggestions.len() - 1);
                return None;
            }
            KeyCode::Up => {
                app.search_selected = app.search_selected.saturating_sub(1);
                return None;
            }
            _ => {}
        }
    }

    match key.code {
        KeyCode::Esc => {
            app.input_mode = InputMode::Normal;
            app.focus = Focus::BlockList;
            app.search_input.clear();
            app.search_cursor = 0;
            app.search_suggestions.clear();
            app.search_selected = 0;
            None
        }

        KeyCode::Enter => {
            // If a suggestion is selected and dropdown is visible, use it
            let query = if !app.search_suggestions.is_empty()
                && app.search_selected < app.search_suggestions.len()
            {
                format!("{:#x}", app.search_suggestions[app.search_selected].felt)
            } else {
                app.search_input.clone()
            };
            app.input_mode = InputMode::Normal;
            app.focus = Focus::BlockList;
            app.search_suggestions.clear();
            app.search_selected = 0;
            if query.is_empty() {
                None
            } else {
                Some(Action::ResolveSearch { query })
            }
        }

        // Tab accepts the selected suggestion's NAME into the input field
        KeyCode::Tab => {
            if let Some(result) = app.search_suggestions.get(app.search_selected) {
                // Extract just the name part (before the " (0x..." suffix)
                let name = extract_name_from_display(&result.display);
                app.search_input = name;
                app.search_cursor = app.search_input.len();
                app.update_suggestions();
            }
            None
        }

        KeyCode::Char(c) => {
            search_insert(app, c.encode_utf8(&mut [0; 4]));
            None
        }

        KeyCode::Backspace => {
            if let Some(start) = prev_char_start(&app.search_input, app.search_cursor) {
                app.search_input.remove(start);
                app.search_cursor = start;
            }
            app.search_selected = 0;
            app.update_suggestions();
            None
        }

        KeyCode::Left => {
            if let Some(start) = prev_char_start(&app.search_input, app.search_cursor) {
                app.search_cursor = start;
            }
            None
        }

        KeyCode::Right => {
            if let Some(c) = app.search_input[app.search_cursor..].chars().next() {
                app.search_cursor += c.len_utf8();
            }
            None
        }

        // Up/Down — ignore when no suggestions (handled above when suggestions exist)
        KeyCode::Up | KeyCode::Down => None,

        _ => None,
    }
}

/// Bracketed paste: the whole text lands in one insert, so one suggestion refresh and one frame.
pub fn handle_paste(app: &mut App, text: &str) {
    if app.input_mode != InputMode::Search {
        return;
    }
    // Copied lines carry a trailing newline; keep only printable text.
    let text: String = text.chars().filter(|c| !c.is_control()).collect();
    search_insert(app, &text);
}

/// `search_cursor` is a byte offset; step back to the start of the preceding char.
fn prev_char_start(s: &str, cursor: usize) -> Option<usize> {
    s[..cursor].char_indices().next_back().map(|(i, _)| i)
}

fn search_insert(app: &mut App, text: &str) {
    app.search_input.insert_str(app.search_cursor, text);
    app.search_cursor += text.len();
    app.search_selected = 0;
    app.update_suggestions();
}

/// Extract the name portion from a search result display string.
/// Display format: " ETH (0x49d..dc7)" or "*ETH (0x49d..dc7)"
/// Returns: "ETH"
fn extract_name_from_display(display: &str) -> String {
    let trimmed = display.trim().trim_start_matches('*').trim();
    if let Some(paren_pos) = trimmed.find(" (") {
        trimmed[..paren_pos].to_string()
    } else {
        trimmed.to_string()
    }
}

/// If the user just switched INTO the MetaTxs tab (via Tab/Shift+Tab), fire
/// the initial pf-query fetch. Idempotent: `meta_txs_dispatched` guards it.
fn maybe_dispatch_meta_txs_on_entry(app: &mut App) -> Option<Action> {
    if app.address.tab != crate::app::AddressTab::MetaTxs
        || app.address.meta_txs_dispatched
        || app.address.fetching_meta_txs
        // Undeployed addresses have no meta-txs to scan for — skip the
        // pf-query bloom walk entirely (it can only return empty).
        || app.address.not_deployed
    {
        return None;
    }
    let addr = app.address.context?;
    // Bound the bloom scan to the deploy block when known; without this
    // pf-query walks from genesis and times out on long-lived accounts.
    let from_block = app
        .address
        .deployment
        .as_ref()
        .map(|d| d.block_number)
        .unwrap_or(0);
    app.address.fetching_meta_txs = true;
    app.address.meta_txs_dispatched = true;
    app.address.meta_tx_from_block = from_block;
    let window_size = app.address.meta_tx_last_window;
    Some(Action::FetchAddressMetaTxs {
        address: addr,
        from_block,
        continuation_token: None,
        window_size,
        limit: 50,
    })
}

/// Page-scroll the active list or pane. Ctrl+U / Ctrl+D / PageUp / PageDown
/// share this dispatcher. In TxDetail (which has no list under the cursor) it
/// page-scrolls the active tab's body; tab switching is on Tab / Shift+Tab.
/// Axis navigation (next/prev block, next/prev tx) lives in `handle_axis`
/// (Ctrl+P / Ctrl+N).
fn handle_cycle(app: &mut App, direction: i64) -> Option<Action> {
    match app.current_view() {
        View::Blocks => {
            // Half-page-ish scroll through the blocks list.
            // direction: +1 = Ctrl+U / PageUp (toward newest = lower index),
            //           -1 = Ctrl+D / PageDown (toward older = higher index).
            // Blocks are newest-first, so "up" = lower index.
            const CHUNK: i64 = 10;
            let delta = -direction * CHUNK;
            app.blocks_scroll_by(delta);
            None
        }
        View::BlockDetail => {
            // Page-scroll the per-block tx list (newest tx first, so direction
            // signs match Blocks above).
            const CHUNK: i64 = 20;
            let delta = -direction * CHUNK;
            app.block_detail_txs_scroll_by(delta);
            None
        }
        View::TxDetail => {
            // Page-scroll the active tab's body. Tab/Shift+Tab switch tabs.
            // direction: +1 = Ctrl+U / PageUp (up), -1 = Ctrl+D / PageDown (down).
            const CHUNK: u16 = 10;
            let s = app.tx_detail.active_scroll_mut();
            *s = if direction > 0 {
                s.saturating_sub(CHUNK)
            } else {
                s.saturating_add(CHUNK)
            };
            None
        }
        View::AddressInfo => {
            // Half-page-ish scroll inside the active address tab.
            // direction: +1 = Ctrl+U / PageUp (up), -1 = Ctrl+D / PageDown (down).
            // Address lists are newest-first, so "up" means lower index.
            const CHUNK: i64 = 20;
            let delta = -direction * CHUNK;
            app.address_list_scroll_by(delta);
            None
        }
        View::ClassInfo => {
            // Page-scroll the class info pane (mirrors j/k stepping by 1).
            const CHUNK: u16 = 10;
            app.class.scroll = if direction > 0 {
                app.class.scroll.saturating_sub(CHUNK)
            } else {
                app.class.scroll.saturating_add(CHUNK)
            };
            None
        }
    }
}

/// Axis navigation in display order.
///
/// `dir`: +1 = scroll DOWN visually (Ctrl+N), -1 = scroll UP visually (Ctrl+P).
///
/// Display order in the TUI:
/// - Blocks list shows newest first → block N+1 is above block N → scrolling
///   down visually means moving to a *lower* block number.
/// - Per-block tx list is reversed at load time (`transactions.reverse()` in
///   `BlockDetailLoaded`) so highest tx idx is at the top → scrolling down
///   visually means moving to a *lower* tx idx (i.e., a higher *position*
///   in the items list).
///
/// Wrapping in TxDetail:
/// - Down past tx idx 0 (bottom of current block) → highest tx idx of block
///   N-1 (top of the next block down). That's `TxBoundary::First` (position
///   0 in the items list of block N-1, which is the highest tx idx after
///   the load-time reverse).
/// - Up past the highest tx idx (top of current block) → tx idx 0 of block
///   N+1 (bottom of the previous block up). That's `TxBoundary::Last`
///   (last position in the items list = tx idx 0 after the reverse).
fn handle_axis(app: &mut App, dir: i64) -> Option<Action> {
    match app.current_view() {
        View::BlockDetail => {
            let current = app.block_detail.block.as_ref()?.number;
            // Higher block number = visually up, so target = current - dir.
            // Genesis is the lower bound; `latest_block_number` (last known
            // tip) is the upper bound — refusing to fetch past it avoids a
            // miss that would clear the view.
            let target = if dir > 0 {
                current.checked_sub(1)?
            } else {
                if current >= app.latest_block_number {
                    return None;
                }
                current + 1
            };
            // Stay in same view -- clear and refetch without pushing.
            app.is_loading = true;
            app.clear_block_detail();
            Some(Action::FetchBlockDetail { number: target })
        }
        View::TxDetail => {
            let current_hash = app.tx_detail.transaction.as_ref()?.hash();
            let len = app.block_detail.txs.items.len();
            let idx = app
                .block_detail
                .txs
                .items
                .iter()
                .position(|tx| tx.hash() == current_hash)?;
            // Higher position in items list = visually down (because the list
            // is reversed at load time), so new_position = current_position + dir.
            let new_idx = idx as i64 + dir;
            if new_idx >= 0 && (new_idx as usize) < len {
                // Within-block step.
                let new_idx = new_idx as usize;
                let hash = app.block_detail.txs.items[new_idx].hash();
                app.block_detail.txs.state.select(Some(new_idx));
                app.is_loading = true;
                app.clear_tx_detail();
                Some(Action::FetchTransaction { hash })
            } else {
                // Out of bounds — wrap to neighbor block.
                let current_block = app.block_detail.block.as_ref()?.number;
                let target_block = if dir > 0 {
                    // Down past tx idx 0 → next block (N-1) at its top
                    // (highest tx idx = position 0 in items = First).
                    current_block.checked_sub(1)?
                } else {
                    // Up past highest tx idx → prev block (N+1) at its bottom
                    // (tx idx 0 = last position in items = Last). Refuse to
                    // step past the known chain tip.
                    if current_block >= app.latest_block_number {
                        return None;
                    }
                    current_block + 1
                };
                let boundary = if dir > 0 {
                    crate::app::TxBoundary::First
                } else {
                    crate::app::TxBoundary::Last
                };
                app.pending_tx_boundary = Some(boundary);
                app.is_loading = true;
                app.clear_tx_detail();
                app.clear_block_detail();
                Some(Action::FetchBlockDetail {
                    number: target_block,
                })
            }
        }
        _ => None,
    }
}

/// Navigate to the next/prev tx by the same sender (nonce-based).
/// Uses the cached address tx list if available, falls back to RPC.
fn handle_nonce_cycle(app: &mut App, direction: i64) -> Option<Action> {
    if app.current_view() != View::TxDetail {
        return None;
    }
    let tx = app.tx_detail.transaction.as_ref()?;
    let current_nonce = match tx {
        crate::data::types::SnTransaction::Invoke(i) => {
            i.nonce.map(|n| felt_to_u64(&n)).unwrap_or(0)
        }
        _ => return None,
    };

    let target_nonce = (current_nonce as i64 + direction).max(0) as u64;

    // Try to find the tx in the cached address tx list first (instant, no RPC)
    if let Some(summary) = app
        .address
        .txs
        .items
        .iter()
        .find(|s| s.nonce == target_nonce)
    {
        let hash = summary.hash;
        // Stay in same view -- clear and refetch without pushing
        app.is_loading = true;
        app.clear_tx_detail();
        return Some(Action::FetchTransaction { hash });
    }

    // Fall back to RPC search
    let sender = tx.sender();
    app.is_loading = true;
    app.clear_tx_detail();
    Some(Action::FetchTxByNonce {
        sender,
        current_nonce,
        direction,
    })
}

fn handle_enter(app: &mut App) -> Option<Action> {
    match app.current_view() {
        View::Blocks => {
            let number = app.selected_block()?.number;
            app.navigate_to(NavTarget::Block(number))
        }
        View::BlockDetail => {
            let hash = app.selected_transaction()?.hash();
            app.navigate_to(NavTarget::Transaction(hash))
        }
        View::AddressInfo => {
            match app.address.tab {
                crate::app::AddressTab::Transactions => {
                    if app.address.gap_selected.is_some() {
                        app.dispatch_address_gap_fill();
                        return None;
                    }
                    let hash = app.address.txs.selected_item()?.hash;
                    return app.navigate_to(NavTarget::Transaction(hash));
                }
                crate::app::AddressTab::Calls => {
                    if app.address.call_gap_selected.is_some() {
                        app.dispatch_address_call_gap_fill();
                        return None;
                    }
                    let hash = app.address.calls.selected_item()?.tx_hash;
                    return app.navigate_to(NavTarget::Transaction(hash));
                }
                crate::app::AddressTab::Events => {
                    let hash = app.address.events.selected_item()?.raw.transaction_hash;
                    return app.navigate_to(NavTarget::Transaction(hash));
                }
                crate::app::AddressTab::Transfers => {
                    if app.address.transfer_gap_selected.is_some() {
                        app.dispatch_address_transfer_gap_fill();
                        return None;
                    }
                    let hash = app.address.transfers.selected_item()?.tx_hash;
                    return app.navigate_to(NavTarget::Transaction(hash));
                }
                crate::app::AddressTab::MetaTxs => {
                    let hash = app.address.meta_txs.selected_item()?.hash;
                    return app.navigate_to(NavTarget::Transaction(hash));
                }
                crate::app::AddressTab::ClassHistory => {
                    let felt = app
                        .address
                        .class_history
                        .get(app.address.class_history_scroll)
                        .and_then(|e| starknet::core::types::Felt::from_hex(&e.class_hash).ok())?;
                    return app.navigate_to(NavTarget::ClassHash(felt));
                }
                _ => {}
            }
            None
        }
        View::TxDetail => None,
        View::ClassInfo => None,
    }
}

/// Whether the current tx in `TxDetail` is a privacy-pool tx, controlling
/// whether `Tab`/`Shift+Tab` includes the Privacy tab in the cycle.
fn tx_detail_has_privacy(app: &App) -> bool {
    let Some(tx) = &app.tx_detail.transaction else {
        return false;
    };
    let oe: Vec<_> = app
        .tx_detail
        .outside_executions
        .iter()
        .map(|(_, info)| info.clone())
        .collect();
    crate::decode::privacy::summarize(
        tx,
        &app.tx_detail.decoded_calls,
        &app.tx_detail.decoded_events,
        &oe,
    )
    .is_some()
}

#[cfg(test)]
mod paste_tests {
    use super::*;
    use tokio::sync::mpsc;

    fn search_app() -> App {
        let (tx, _rx) = mpsc::unbounded_channel();
        let mut app = App::new(tx);
        app.input_mode = InputMode::Search;
        app
    }

    #[test]
    fn paste_inserts_whole_text_at_cursor() {
        let mut app = search_app();
        handle_paste(&mut app, "0x49d3");
        handle_key(&mut app, KeyEvent::from(KeyCode::Left));
        handle_key(&mut app, KeyEvent::from(KeyCode::Left));
        handle_paste(&mut app, "ab");
        assert_eq!(app.search_input, "0x49abd3");
        assert_eq!(app.search_cursor, 6);
    }

    #[test]
    fn paste_strips_control_characters() {
        let mut app = search_app();
        handle_paste(&mut app, "0x49d3\r\n");
        assert_eq!(app.search_input, "0x49d3");
        assert_eq!(app.search_cursor, 6);
    }

    #[test]
    fn paste_in_normal_mode_is_ignored() {
        let (tx, _rx) = mpsc::unbounded_channel();
        let mut app = App::new(tx);
        handle_paste(&mut app, "q");
        assert_eq!(app.input_mode, InputMode::Normal);
        assert!(app.search_input.is_empty());
        assert!(!app.should_quit);
    }

    #[test]
    fn non_ascii_input_keeps_cursor_on_char_boundaries() {
        let mut app = search_app();
        handle_paste(&mut app, "aé");
        handle_key(&mut app, KeyEvent::from(KeyCode::Left));
        handle_key(&mut app, KeyEvent::from(KeyCode::Char('ß')));
        assert_eq!(app.search_input, "aßé");
        handle_key(&mut app, KeyEvent::from(KeyCode::Right));
        handle_key(&mut app, KeyEvent::from(KeyCode::Backspace));
        assert_eq!((app.search_input.as_str(), app.search_cursor), ("aß", 3));
    }

    #[test]
    fn paste_matches_typing_the_same_chars() {
        let mut app = search_app();
        handle_key(&mut app, KeyEvent::from(KeyCode::Char('0')));
        handle_key(&mut app, KeyEvent::from(KeyCode::Char('x')));
        let typed = (app.search_input.clone(), app.search_cursor);
        let mut app = search_app();
        handle_paste(&mut app, "0x");
        assert_eq!((app.search_input, app.search_cursor), typed);
    }
}