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
#![allow(dead_code)]

mod app;
mod config;
mod data;
mod decode;
mod error;
mod network;
mod registry;
mod search;
mod ui;
mod utils;

use std::io;
use std::sync::Arc;
use std::time::Duration;

use clap::Parser;
use crossterm::event::{
    self, DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
    Event, EventStream, MouseEventKind,
};
use crossterm::execute;
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use tokio::sync::mpsc;
use tracing::{debug, info, warn};
use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt};

use app::App;
use app::actions::Action;
use config::AppConfig;
use data::cache::CachingDataSource;
use data::rpc::RpcDataSource;
use decode::AbiRegistry;
use decode::class_cache::ClassCache;
use registry::AddressRegistry;
use search::SearchEngine;

/// Initialize file-based logging. Returns a guard that must be held alive
/// for the duration of the program (dropping it flushes pending writes).
fn init_logging(config: &AppConfig) -> tracing_appender::non_blocking::WorkerGuard {
    let log_dir = config
        .log_dir
        .as_deref()
        .map(std::path::PathBuf::from)
        .unwrap_or_else(|| starktop_config_dir().join("logs"));

    std::fs::create_dir_all(&log_dir).expect("Failed to create log directory");

    let file_appender = tracing_appender::rolling::daily(&log_dir, "starktop.log");
    let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);

    let filter =
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&config.log_level));

    tracing_subscriber::registry()
        .with(filter)
        .with(
            fmt::layer()
                .with_ansi(false)
                .with_target(true)
                .with_thread_ids(false)
                .with_writer(non_blocking),
        )
        .init();

    guard
}

fn main() -> anyhow::Result<()> {
    let runtime = tokio::runtime::Runtime::new()?;
    let result = runtime.block_on(run());
    // Don't let a task stuck in synchronous work (a SQLite write, a large
    // cache load) hold the process open after the UI has exited.
    runtime.shutdown_timeout(Duration::from_secs(1));
    result
}

async fn run() -> anyhow::Result<()> {
    // Load .env: try CWD first, then ~/.config/starktop/.env
    if dotenvy::dotenv().is_err() {
        let global_env = starktop_config_dir().join(".env");
        if global_env.exists() {
            dotenvy::from_path(&global_env).ok();
        }
    }

    let config = AppConfig::parse();
    let _log_guard = init_logging(&config);

    info!(rpc_url = %config.rpc_url, ws_url = ?config.ws_url, "starktop starting");

    // Startup checks
    startup_checks(&config)?;

    // Setup cache directory
    let cache_dir = starktop_config_dir();
    std::fs::create_dir_all(&cache_dir)?;
    let cache_db = cache_dir.join("cache.db");
    info!(cache_db = %cache_db.display(), "Using local cache");

    // Shared head-block tracker: WS writes the most recent block on every
    // `starknet_subscribeNewHeads` notification. Created up here (rather than
    // after the data source) so the cache layer can read chain head without
    // an RPC round-trip per class_hash staleness check. The WS subscriber and
    // head-keeper are spawned later — until they fire, `head.latest()`
    // returns `None` and the cache falls back to RPC, matching old behavior.
    let head_block = Arc::new(network::HeadTracker::new());

    // Create data source with persistent cache
    let rpc = RpcDataSource::new(&config.rpc_url);
    let cached = CachingDataSource::new(Arc::new(rpc) as Arc<dyn data::DataSource>, &cache_db)?
        .with_head_tracker(Arc::clone(&head_block) as Arc<dyn data::LatestBlockSource>);
    let data_source: Arc<dyn data::DataSource> = Arc::new(cached);

    // ABI registry with persistent class cache
    let class_cache_db = rusqlite::Connection::open(cache_dir.join("cache.db"))
        .map_err(|e| anyhow::anyhow!("Failed to open class cache db: {e}"))?;
    // Ensure the parsed_abis table exists (same DB as data cache)
    class_cache_db
        .execute_batch(
            "CREATE TABLE IF NOT EXISTS parsed_abis (
                class_hash TEXT PRIMARY KEY,
                data TEXT NOT NULL
            );",
        )
        .map_err(|e| anyhow::anyhow!("Failed to init class cache: {e}"))?;
    let class_cache = ClassCache::new(class_cache_db, 500);
    let abi_registry = Arc::new(AbiRegistry::new(Arc::clone(&data_source), class_cache));

    // Address registry — resolve labels and viewing-keys paths with XDG fallback.
    // viewing_keys.toml is a separate file because the keys it holds are
    // SECRETS that must not mix with shareable labels.
    let user_labels_path = resolve_config_file(&config.user_labels, "labels.toml");
    let viewing_keys_path = resolve_config_file(&config.viewing_keys, "viewing_keys.toml");
    let (registry_inner, registry_warnings) =
        AddressRegistry::load(&user_labels_path, &viewing_keys_path).unwrap_or_else(|e| {
            tracing::warn!(error = %e, "Failed to load address registry, using empty");
            AddressRegistry::load(
                std::path::Path::new("/dev/null"),
                std::path::Path::new("/dev/null"),
            )
            .unwrap()
        });
    let registry = Arc::new(registry_inner);
    let search_engine = Arc::new(SearchEngine::new(Arc::clone(&registry)));

    // Channels
    let (action_tx, action_rx) = mpsc::unbounded_channel::<Action>();
    let (response_tx, mut response_rx) = mpsc::unbounded_channel::<Action>();

    // Create app
    let mut app = App::new(action_tx.clone());
    app.search_engine = Some(Arc::clone(&search_engine));
    // Hydrate the on-chain ERC-20 metadata cache from SQLite so unknown
    // tokens render correctly on the very first frame of a cold start
    // (instead of falling back to raw u128 amounts until the live fetch
    // round-trips).
    app.fetched_token_metadata = data_source.load_token_metadata().into_iter().collect();
    // Hydrate forward-decrypted Privacy Pool notes from SQLite. The
    // in-session re-sync still fires on the first privacy-tx open (gated
    // by `private_notes_synced`, which we deliberately do NOT pre-seed),
    // but cached entries make the Privacy tab + Balances "Private
    // holdings" panel correct on the very first frame instead of waiting
    // a full storage walk.
    {
        let (cached_notes, cached_nullifiers) = data_source.load_private_notes();
        app.private_notes = cached_notes.into_iter().map(|n| (n.note_id, n)).collect();
        app.private_nullifiers = cached_nullifiers.into_iter().collect();
        if !app.private_notes.is_empty() || !app.private_nullifiers.is_empty() {
            info!(
                notes = app.private_notes.len(),
                nullifiers = app.private_nullifiers.len(),
                "Hydrated private notes from cache"
            );
        }
    }
    if !registry_warnings.is_empty() {
        app.error_message = Some(registry_warnings.join("\n"));
    }
    app.connection_status = app::state::ConnectionStatus::Connected {
        network: "mainnet".to_string(),
    };
    app.is_loading = true;

    // Create Dune client (optional — only if API key is set)
    let dune_client = config
        .dune_api_key
        .as_ref()
        .filter(|k| !k.is_empty())
        .map(|key| {
            info!(is_private = config.dune_private_queries, "Dune API enabled");
            // Persistent-query fast path: store reusable Dune query_ids
            // in the same cache.db so repeat probes skip the create +
            // archive round trips.
            Arc::new(
                network::dune::DuneClient::new(key.clone(), config.dune_private_queries)
                    .with_persistent_cache(&cache_db),
            )
        });

    // DefiLlama needs no API key, so the client is always created when the cache opens.
    let price_client: Option<Arc<network::prices::PriceClient>> =
        match network::prices::PriceClient::new(&cache_db) {
            Ok(client) => {
                info!("DefiLlama price client enabled");
                Some(Arc::new(client))
            }
            Err(e) => {
                warn!(error = %e, "Failed to initialize price client (USD prices disabled)");
                None
            }
        };
    app.price_client = price_client.clone();

    // Create Voyager client (optional — only if API key is set)
    let voyager_client: Option<Arc<network::voyager::VoyagerClient>> = config
        .voyager_api_key
        .as_ref()
        .filter(|k| !k.is_empty())
        .and_then(
            |key| match network::voyager::VoyagerClient::new(key.clone(), &cache_db) {
                Ok(client) => {
                    info!("Voyager API enabled");
                    Some(Arc::new(client))
                }
                Err(e) => {
                    warn!(error = %e, "Failed to initialize Voyager client");
                    None
                }
            },
        );

    // Starkscan client (optional — only if API key is set)
    let starkscan_client: Option<Arc<network::starkscan::StarkscanClient>> = config
        .starkscan_api_key
        .as_ref()
        .filter(|k| !k.is_empty())
        .map(|key| {
            info!("Starkscan API enabled");
            Arc::new(network::starkscan::StarkscanClient::new(
                key.clone(),
                config.starkscan_api_url.clone(),
            ))
        });

    // Seed the search index with cached Voyager labels so they're searchable immediately
    if let Some(vc) = &voyager_client {
        let cached = vc.load_all_cached_labels();
        if !cached.is_empty() {
            info!(
                count = cached.len(),
                "Seeding search index with cached Voyager labels"
            );
            for (address, name) in cached {
                registry.add_voyager_label(address, &name);
            }
        }
    }

    // Create Pathfinder query service client (optional — only if URL is set)
    let pf_client = config
        .pathfinder_service_url
        .as_ref()
        .filter(|u| !u.is_empty())
        .map(|url| {
            info!(url = %url, "Pathfinder query service enabled");
            Arc::new(data::pathfinder::PathfinderClient::new(url.clone()))
        });

    // Record which data sources are configured
    app.data_sources = app::state::DataSources {
        rpc: app::state::SourceStatus::Configured,
        dune: if dune_client.is_some() {
            app::state::SourceStatus::Configured
        } else {
            app::state::SourceStatus::Off
        },
        pathfinder: if pf_client.is_some() {
            app::state::SourceStatus::Configured
        } else {
            app::state::SourceStatus::Off
        },
        voyager: if voyager_client.is_some() {
            app::state::SourceStatus::Configured
        } else {
            app::state::SourceStatus::Off
        },
        starkscan: if starkscan_client.is_some() {
            app::state::SourceStatus::Configured
        } else {
            app::state::SourceStatus::Off
        },
        ws: app::state::SourceStatus::Off,
    };

    // Probe Voyager health in background, upgrade to Live if reachable
    if let Some(vc) = &voyager_client {
        let vc_c = Arc::clone(vc);
        let resp_tx_c = response_tx.clone();
        tokio::spawn(async move {
            match vc_c.health_check().await {
                Ok(()) => {
                    info!("Voyager API reachable");
                    let _ = resp_tx_c.send(app::actions::Action::SourceUpdate {
                        source: app::actions::Source::Voyager,
                        status: app::state::SourceStatus::Live,
                    });
                }
                Err(e) => {
                    warn!(error = %e, "Voyager API unreachable");
                    let _ = resp_tx_c.send(app::actions::Action::SourceUpdate {
                        source: app::actions::Source::Voyager,
                        status: app::state::SourceStatus::ConnectError(e),
                    });
                }
            }
        });
    }

    // Probe Starkscan in background, upgrade to Live if reachable
    if let Some(sc) = &starkscan_client {
        let sc_c = Arc::clone(sc);
        let resp_tx_c = response_tx.clone();
        tokio::spawn(async move {
            let status = match sc_c.health_check().await {
                Ok(()) => app::state::SourceStatus::Live,
                Err(e) => {
                    warn!(error = %e, "Starkscan API unreachable");
                    app::state::SourceStatus::ConnectError(e.to_string())
                }
            };
            let _ = resp_tx_c.send(app::actions::Action::SourceUpdate {
                source: app::actions::Source::Starkscan,
                status,
            });
        });
    }

    // Probe PF health in background, upgrade to Live if reachable
    if let Some(pf) = &pf_client {
        let pf_c = Arc::clone(pf);
        let resp_tx_c = response_tx.clone();
        tokio::spawn(async move {
            match pf_c.health().await {
                Ok(_) => {
                    let _ = resp_tx_c.send(app::actions::Action::SourceUpdate {
                        source: app::actions::Source::Pathfinder,
                        status: app::state::SourceStatus::Live,
                    });
                }
                Err(e) => {
                    tracing::warn!(error = %e, "Pathfinder service unreachable");
                    let _ = resp_tx_c.send(app::actions::Action::SourceUpdate {
                        source: app::actions::Source::Pathfinder,
                        status: app::state::SourceStatus::ConnectError(e.to_string()),
                    });
                }
            }
        });
    }

    // Probe Dune health in background, upgrade to Live if reachable
    if let Some(dune) = &dune_client {
        let dune_c = Arc::clone(dune);
        let resp_tx_c = response_tx.clone();
        tokio::spawn(async move {
            match dune_c.health().await {
                Ok(()) => {
                    let _ = resp_tx_c.send(app::actions::Action::SourceUpdate {
                        source: app::actions::Source::Dune,
                        status: app::state::SourceStatus::Live,
                    });
                }
                Err(e) => {
                    tracing::warn!(error = %e, "Dune API unreachable");
                    let _ = resp_tx_c.send(app::actions::Action::SourceUpdate {
                        source: app::actions::Source::Dune,
                        status: app::state::SourceStatus::ConnectError(e.to_string()),
                    });
                }
            }
        });
    }

    // Spawn network task
    let ds_clone = Arc::clone(&data_source);
    let abi_clone = Arc::clone(&abi_registry);
    let resp_tx_clone = response_tx.clone();
    let head_clone = Arc::clone(&head_block);
    tokio::spawn(async move {
        network::run_network_task(
            ds_clone,
            abi_clone,
            dune_client,
            pf_client,
            voyager_client,
            price_client,
            starkscan_client,
            head_clone,
            action_rx,
            resp_tx_clone,
        )
        .await;
    });

    // Spawn block update mechanism: prefer WebSocket, fall back to polling.
    // When WS is in use we also spawn a head-keeper as a backstop in case
    // WS disconnects — it keeps `head_block` fresh from a periodic RPC.
    // The HTTP polling path already calls `get_latest_block_number` every
    // 3 s and writes the tracker, so we don't double-spawn the keeper.
    let _block_updater: tokio::task::JoinHandle<()> = if let Some(ws_url) = &config.ws_url {
        info!(ws_url = %ws_url, "Using WebSocket for new block headers and address streaming");
        app.data_sources.ws = app::state::SourceStatus::Configured;
        let (handle, ws_manager) = network::ws::spawn_ws_subscriber(
            ws_url.clone(),
            Arc::clone(&data_source),
            response_tx.clone(),
            Arc::clone(&head_block),
        );
        app.ws_manager = Some(ws_manager);
        // WS feeds the tracker on every new head (~2 s on mainnet), so this
        // keeper exists purely as a backstop for WS-disconnect windows. 60 s
        // is plenty — we still recover well inside the 60 s freshness
        // threshold the cache layer applies to the tracker — and it saves
        // ~5 RPC round-trips per minute against a remote node.
        let _head_keeper: tokio::task::JoinHandle<()> = network::spawn_head_keeper(
            Arc::clone(&data_source),
            Arc::clone(&head_block),
            Duration::from_secs(60),
        );
        handle
    } else {
        info!("No WS URL configured, using HTTP polling (3s interval)");
        network::spawn_block_poller(
            Arc::clone(&data_source),
            response_tx.clone(),
            Duration::from_secs(3),
            Arc::clone(&head_block),
        )
    };

    // Periodic address-view refresh ticker: every 60s, nudge the reducer to
    // re-fetch the currently viewed address from RPC if WS isn't `Live`.
    // The reducer checks view/source/context guards before dispatching work,
    // so this timer is a cheap unconditional heartbeat.
    let resp_tx_poll = response_tx.clone();
    tokio::spawn(async move {
        let mut tick = tokio::time::interval(Duration::from_secs(60));
        // Burn the immediate first tick so we don't fire at t=0 before any
        // address view exists.
        tick.tick().await;
        loop {
            tick.tick().await;
            if resp_tx_poll.send(Action::PeriodicAddressPollTick).is_err() {
                break;
            }
        }
    });

    // Request initial data
    info!("Requesting initial block fetch");
    let _ = action_tx.send(Action::FetchRecentBlocks { count: 30 });

    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(
        stdout,
        EnterAlternateScreen,
        EnableMouseCapture,
        EnableBracketedPaste
    )?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    info!("TUI initialized, entering event loop");

    // TUI event loop
    let result = run_loop(&mut terminal, &mut app, &mut response_rx).await;

    // Restore terminal
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        DisableBracketedPaste,
        DisableMouseCapture,
        LeaveAlternateScreen
    )?;
    terminal.show_cursor()?;

    info!("starktop exiting");
    result
}

async fn run_loop(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut App,
    response_rx: &mut mpsc::UnboundedReceiver<Action>,
) -> anyhow::Result<()> {
    // EventStream is cancellation-safe: dropping its `.next()` future does NOT
    // consume buffered events. The previous `spawn_blocking(event::read)` form
    // was racy — when `tokio::select!` picked the network branch, the blocking
    // task could finish reading a key but its result would be dropped, silently
    // losing characters mid-paste under heavy background traffic.
    use futures::StreamExt;
    let mut event_stream = EventStream::new();

    loop {
        // Draw
        terminal.draw(|f| ui::draw(f, app))?;

        // Check for quit
        if app.should_quit {
            return Ok(());
        }

        tokio::select! {
            // Input first: a pending key must never queue behind a response burst.
            biased;
            maybe_event = event_stream.next() => {
                match maybe_event {
                    Some(Ok(event)) => {
                        handle_terminal_event(app, event);
                        drain_buffered_input(app)?;
                        // Responses still progress under a sustained input flood.
                        if let Ok(action) = response_rx.try_recv() {
                            log_action(&action);
                            app.handle_action(action);
                        }
                    }
                    Some(Err(e)) => {
                        // Terminal input errors are usually fatal (closed tty,
                        // broken pipe). Log and quit cleanly so the select! arm
                        // doesn't spin on persistent errors.
                        warn!(error = %e, "Terminal event stream error, quitting");
                        return Ok(());
                    }
                    None => {
                        // Stream end (terminal closed). Quit.
                        info!("Terminal event stream ended");
                        return Ok(());
                    }
                }
            }
            // Handle responses from network task. Drain a burst of pending
            // actions in one go so an enrichment storm (hundreds of
            // streamed tx summaries / decoded events / price updates)
            // doesn't trigger a full-frame redraw per action — the previous
            // form did exactly that, which is what made the UI feel sticky
            // when background work was heaviest.
            //
            // Cap the burst at MAX_DRAIN so input latency stays bounded:
            // even if the network task is firehosing, we still pump
            // EventStream and redraw at least every MAX_DRAIN actions.
            Some(action) = response_rx.recv() => {
                const MAX_DRAIN: usize = 64;
                log_action(&action);
                app.handle_action(action);
                for _ in 1..MAX_DRAIN {
                    match response_rx.try_recv() {
                        Ok(next) => {
                            log_action(&next);
                            app.handle_action(next);
                        }
                        Err(_) => break,
                    }
                }
            }
        }
    }
}

fn handle_terminal_event(app: &mut App, event: Event) {
    match event {
        Event::Key(key) => {
            // Clear error on any keypress
            app.error_message = None;
            if let Some(action) = app::input::handle_key(app, key) {
                debug!(?action, "Dispatching action from input");
                app.is_loading = true;
                let _ = app.action_tx.send(action);
            }
        }
        Event::Paste(text) => {
            debug!(len = text.len(), "Applying paste");
            app::input::handle_paste(app, &text);
        }
        Event::Mouse(mouse) => match mouse.kind {
            MouseEventKind::ScrollUp => app.select_previous(),
            MouseEventKind::ScrollDown => app.select_next(),
            _ => {} // ignore clicks/motion — text selection works via Shift+drag
        },
        _ => {} // resize, focus — ignored
    }
}

/// Apply already-buffered input before redrawing so a paste or key-repeat burst
/// costs one frame. Sync poll on purpose: a throwaway stream poll would register a dead waker.
fn drain_buffered_input(app: &mut App) -> io::Result<()> {
    const MAX_INPUT_DRAIN: usize = 256;
    for _ in 0..MAX_INPUT_DRAIN {
        if app.should_quit || !event::poll(Duration::ZERO)? {
            break;
        }
        handle_terminal_event(app, event::read()?);
    }
    Ok(())
}

/// Per-action logging extracted so `run_loop` can apply it both to the
/// first action drained from the channel and to follow-on actions pulled
/// via `try_recv` in the same burst.
fn log_action(action: &Action) {
    match action {
        Action::BlocksLoaded(blocks) => {
            info!(count = blocks.len(), "Blocks loaded");
        }
        Action::NewBlock(block) => {
            debug!(number = block.number, "New block received");
        }
        Action::BlockDetailLoaded {
            block,
            transactions,
            endpoint_names,
            ..
        } => {
            let resolved = endpoint_names.iter().filter(|n| n.is_some()).count();
            info!(
                block = block.number,
                tx_count = transactions.len(),
                resolved_endpoints = resolved,
                "Block detail loaded"
            );
        }
        Action::TransactionLoaded {
            transaction,
            receipt,
            decoded_events,
            ..
        } => {
            let decoded_count = decoded_events
                .iter()
                .filter(|e| e.event_name.is_some())
                .count();
            info!(
                tx = %format!("{:#x}", transaction.hash()),
                events = receipt.events.len(),
                decoded = decoded_count,
                "Transaction loaded"
            );
        }
        Action::AddressInfoLoaded {
            info,
            decoded_events,
            tx_summaries,
            ..
        } => {
            info!(
                address = %format!("{:#x}", info.address),
                events = decoded_events.len(),
                txs = tx_summaries.len(),
                balances = info.token_balances.len(),
                "Address info loaded"
            );
        }
        Action::Error(msg) => {
            warn!(error = %msg, "Network error");
        }
        _ => {}
    }
}

fn starktop_config_dir() -> std::path::PathBuf {
    if let Some(config_dir) = dirs::config_dir() {
        config_dir.join("starktop")
    } else {
        std::path::PathBuf::from(".starktop")
    }
}

/// Resolve a config file path: if the user set a custom value, use it as-is.
/// Otherwise (default), try CWD first, then fall back to ~/.config/starktop/.
fn resolve_config_file(configured: &str, default_name: &str) -> std::path::PathBuf {
    let path = std::path::PathBuf::from(configured);
    // User explicitly set a path (not the default) — use as-is
    if configured != default_name {
        return path;
    }
    // Default name: prefer CWD, fall back to config dir
    if path.exists() {
        path
    } else {
        let global = starktop_config_dir().join(default_name);
        if global.exists() { global } else { path }
    }
}

/// Validate prerequisites before starting the app.
fn startup_checks(config: &AppConfig) -> anyhow::Result<()> {
    let mut warnings = Vec::new();

    // Check RPC URL is set and looks valid
    if config.rpc_url.is_empty() {
        anyhow::bail!(
            "APP_RPC_URL is required. Set it in .env, ~/.config/starktop/.env, or pass --rpc-url"
        );
    }
    if !config.rpc_url.starts_with("http://") && !config.rpc_url.starts_with("https://") {
        anyhow::bail!(
            "APP_RPC_URL must start with http:// or https://. Got: {}",
            config.rpc_url
        );
    }

    // Validate WS URL if provided
    if let Some(ws_url) = &config.ws_url
        && !ws_url.starts_with("ws://")
        && !ws_url.starts_with("wss://")
    {
        anyhow::bail!(
            "APP_WS_URL must start with ws:// or wss://. Got: {}",
            ws_url
        );
    }

    // Check config directory is writable
    let config_dir = starktop_config_dir();
    if let Err(e) = std::fs::create_dir_all(&config_dir) {
        anyhow::bail!(
            "Cannot create config directory {}: {}",
            config_dir.display(),
            e
        );
    }

    // Check SQLite works (bundled, should always work)
    let test_db_path = config_dir.join(".startup_check.db");
    match rusqlite::Connection::open(&test_db_path) {
        Ok(db) => {
            let _ = db.execute_batch("CREATE TABLE IF NOT EXISTS _test (id INTEGER)");
            drop(db);
            let _ = std::fs::remove_file(&test_db_path);
        }
        Err(e) => {
            anyhow::bail!(
                "SQLite check failed: {}. Cache directory: {}",
                e,
                config_dir.display()
            );
        }
    }

    // Check optional API keys
    if config.dune_api_key.as_ref().is_none_or(|k| k.is_empty()) {
        warnings.push(
            "DUNE_API_KEY not set — account history and contract call discovery will be limited",
        );
    }
    if config.voyager_api_key.as_ref().is_none_or(|k| k.is_empty()) {
        warnings.push("VOYAGER_API_KEY not set — address metadata enrichment unavailable");
    }
    if config
        .starkscan_api_key
        .as_ref()
        .is_none_or(|k| k.is_empty())
    {
        warnings.push("STARKSCAN_API_KEY not set — token transfer history limited to RPC scans");
    }

    // Check labels file (with XDG fallback)
    let labels_path = resolve_config_file(&config.user_labels, "labels.toml");
    if !labels_path.exists() {
        warnings
            .push("User labels file not found — create labels.toml in CWD or ~/.config/starktop/");
    }

    // Log warnings
    for w in &warnings {
        info!("Startup: {}", w);
    }

    info!(
        rpc = %config.rpc_url,
        cache_dir = %config_dir.display(),
        dune = config.dune_api_key.as_ref().is_some_and(|k| !k.is_empty()),
        voyager = config.voyager_api_key.as_ref().is_some_and(|k| !k.is_empty()),
        labels = labels_path.exists(),
        "Startup checks passed"
    );

    Ok(())
}