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
//! Async network task: receives `Action` requests from the UI over an mpsc
//! channel, dispatches to the appropriate data source, and sends results back.
//!
//! Split into focused sub-modules:
//! - `block` — fetch block detail, resolve endpoint names
//! - `transaction` — fetch tx + receipt, decode events/calldata
//! - `address` — multi-source parallel address loading (PF/Dune/RPC)
//! - `class` — fetch class ABI, declaration info, deployed contracts
//! - `search` — resolve search queries (block number / address / tx hash / class hash)
//! - `helpers` — shared utilities (build_tx_summary, backfill_timestamps, etc.)
#![allow(clippy::too_many_arguments)]

mod address;
mod block;
mod class;
pub mod dune;
pub mod event_window;
pub mod helpers;
pub mod prices;
mod search;
pub mod starkscan;
mod transaction;
mod transfers;
pub mod voyager;
pub mod ws;

use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};

use crate::app::actions::Action;
use crate::data::DataSource;
use crate::decode::AbiRegistry;

/// Shared "latest block" tracker. Written by the WebSocket subscriber on
/// every `NewHeads` notification and by the head-keeper / block-poller
/// fallback. Read by the address pipeline (and any other path that wants
/// the chain tip) without issuing a `starknet_blockNumber` RPC.
///
/// Pairs the block number with the unix-second timestamp of the last
/// update so callers can tell when the value is stale (e.g. after a
/// WebSocket disconnect). A blank tracker reads as `(0, u64::MAX)` —
/// callers treat that as "always stale, force a refetch."
pub struct HeadTracker {
    block: AtomicU64,
    updated_at: AtomicU64,
}

impl HeadTracker {
    pub fn new() -> Self {
        Self {
            block: AtomicU64::new(0),
            updated_at: AtomicU64::new(0),
        }
    }

    /// Publish a freshly-seen block number. Monotonic on the block field
    /// (a reconnecting WS may briefly replay older heads). The timestamp
    /// is refreshed only when the block actually advances — otherwise a
    /// replayed old head would make a stale tracker look fresh and the
    /// address pipeline would skip its fallback RPC.
    pub fn update(&self, block: u64) {
        let prev = self.block.fetch_max(block, Ordering::Relaxed);
        if block <= prev {
            return;
        }
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        self.updated_at.store(now, Ordering::Relaxed);
    }

    /// Returns `(block, age_seconds)`. Age is `u64::MAX` if never written.
    pub fn read(&self) -> (u64, u64) {
        let block = self.block.load(Ordering::Relaxed);
        let updated = self.updated_at.load(Ordering::Relaxed);
        if updated == 0 {
            return (block, u64::MAX);
        }
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        (block, now.saturating_sub(updated))
    }
}

impl Default for HeadTracker {
    fn default() -> Self {
        Self::new()
    }
}

/// Age beyond which we don't trust the tracker for staleness checks.
/// Mainnet block time is ~2 s; WS feeds us every block and the head-keeper
/// backstops at 60 s. Setting the freshness threshold to 120 s gives one
/// full keeper-interval of slack: if a keeper tick fails or a WS reconnect
/// is in flight, the tracker is still considered fresh for the next
/// scheduled tick. ~60 blocks of slack is far below the 1000-block
/// class_hash staleness window, so a tracker on the edge of fresh still
/// can't cause a stale-cache hit.
const HEAD_TRACKER_FRESH_SECS: u64 = 120;

impl crate::data::LatestBlockSource for HeadTracker {
    fn latest(&self) -> Option<u64> {
        let (block, age) = self.read();
        if block > 0 && age <= HEAD_TRACKER_FRESH_SECS {
            Some(block)
        } else {
            None
        }
    }
}

/// Spawns a periodic head-keeper that calls `starknet_blockNumber` on a
/// timer and feeds the result into the shared `HeadTracker`. Runs
/// unconditionally as a backstop for cases where the WebSocket
/// disconnects or is never configured; when WS is healthy, the tracker
/// is always fresh and the RPC result here is a cheap no-op.
pub fn spawn_head_keeper(
    data_source: Arc<dyn DataSource>,
    head: Arc<HeadTracker>,
    interval: std::time::Duration,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        // `interval` fires its first tick immediately, which is exactly
        // what we want: prime the tracker before any address visit can
        // race a still-empty tracker into a fallback RPC.
        let mut tick = tokio::time::interval(interval);
        loop {
            tick.tick().await;
            match data_source.get_latest_block_number().await {
                Ok(n) => head.update(n),
                Err(e) => {
                    debug!(error = %e, "head-keeper: get_latest_block_number failed");
                }
            }
        }
    })
}

/// Runs the network task: receives actions from the UI, dispatches to data source,
/// sends results back.
pub async fn run_network_task(
    data_source: Arc<dyn DataSource>,
    abi_registry: Arc<AbiRegistry>,
    dune_client: Option<Arc<dune::DuneClient>>,
    pf_client: Option<Arc<crate::data::pathfinder::PathfinderClient>>,
    voyager_client: Option<Arc<voyager::VoyagerClient>>,
    price_client: Option<Arc<prices::PriceClient>>,
    starkscan_client: Option<Arc<starkscan::StarkscanClient>>,
    head_block: Arc<HeadTracker>,
    mut action_rx: mpsc::UnboundedReceiver<Action>,
    response_tx: mpsc::UnboundedSender<Action>,
) {
    info!("Network task started");

    // Per-session cancellation: foreground navigation (opening a new address,
    // block, tx, class, or submitting a search) cancels this token so stale
    // background enrichment/pagination work for the previous view stops piling
    // up on pf-query. New work spawned after navigation captures the fresh
    // token. See `action_is_cancellable` / `action_is_fg_nav` below.
    let mut session_token = CancellationToken::new();

    while let Some(action) = action_rx.recv().await {
        // Rotate the session token on any foreground navigation. The old token
        // is cancelled, signalling in-flight bg tasks to unwind.
        if action_is_fg_nav(&action) {
            session_token.cancel();
            session_token = CancellationToken::new();
        }

        let ds = Arc::clone(&data_source);
        let abi_reg = Arc::clone(&abi_registry);
        let dune = dune_client.clone();
        let pf = pf_client.clone();
        let voyager = voyager_client.clone();
        let prices = price_client.clone();
        let starkscan = starkscan_client.clone();
        let head = Arc::clone(&head_block);
        let tx = response_tx.clone();
        let cancel = session_token.clone();
        let cancellable = action_is_cancellable(&action);

        // Spawn each request as a separate task for concurrency
        tokio::spawn(async move {
            let cancel_inner = cancel.clone();
            let task = async move {
                let cancel = cancel_inner;
                match action {
                    Action::FetchRecentBlocks { count } => {
                        let start = std::time::Instant::now();
                        debug!(count, "Fetching recent blocks");
                        match ds.get_recent_blocks(count).await {
                            Ok(blocks) => {
                                info!(
                                    count = blocks.len(),
                                    elapsed_ms = start.elapsed().as_millis(),
                                    "Recent blocks fetched"
                                );
                                let _ = tx
                                    .send(rpc_source_update(crate::app::state::SourceStatus::Live));
                                let _ = tx.send(Action::BlocksLoaded(blocks));
                            }
                            Err(e) => {
                                error!(elapsed_ms = start.elapsed().as_millis(), error = %e, "Failed to fetch recent blocks");
                                let _ = tx.send(rpc_source_update(
                                    crate::app::state::SourceStatus::ConnectError(e.to_string()),
                                ));
                                let _ = tx.send(Action::Error(format!("Fetch blocks: {e}")));
                            }
                        }
                    }
                    Action::FetchOlderBlocks { before, count } => {
                        debug!(before, count, "Fetching older blocks");
                        let end = before.saturating_sub(1);
                        let start = end.saturating_sub(count as u64 - 1);
                        let futs: Vec<_> = (start..=end)
                            .map(|num| {
                                let ds_c = Arc::clone(&ds);
                                async move { (num, ds_c.get_block(num).await) }
                            })
                            .collect();
                        let results = futures::future::join_all(futs).await;
                        let mut blocks: Vec<_> = results
                            .into_iter()
                            .filter_map(|(num, r)| match r {
                                Ok(block) => Some(block),
                                Err(e) => {
                                    warn!(block = num, error = %e, "Failed to fetch older block");
                                    None
                                }
                            })
                            .collect();
                        // Sort descending (newest first) to match the list order
                        blocks.sort_by(|a, b| b.number.cmp(&a.number));
                        let _ = tx.send(Action::OlderBlocksLoaded(blocks));
                    }
                    Action::FetchBlockDetail { number } => {
                        block::fetch_and_send_block_detail(number, &ds, &abi_reg, &voyager, &tx)
                            .await;
                    }
                    Action::FetchTransaction { hash } => {
                        transaction::fetch_and_send_transaction(
                            hash,
                            &ds,
                            pf.as_ref(),
                            &abi_reg,
                            &tx,
                        )
                        .await;
                    }
                    Action::FetchAddressInfo { address } => {
                        let _ = tx.send(Action::NavigateToAddress { address });
                        address::fetch_and_send_address_info(
                            address, &ds, &abi_reg, &dune, &pf, &voyager, &head, &tx, &cancel,
                        )
                        .await;
                    }
                    Action::RefreshAddressRpc { address } => {
                        address::refresh_address_rpc(address, &ds, &pf, &abi_reg, &tx).await;
                    }
                    Action::FetchTxByNonce {
                        sender,
                        current_nonce,
                        direction,
                    } => {
                        // Find the tx with the target nonce by scanning events for the sender.
                        // We look at the sender's events to find tx hashes, then check their nonces.
                        let target_nonce = (current_nonce as i64 + direction).max(0) as u64;
                        debug!(sender = %format!("{:#x}", sender), current_nonce, target_nonce, "Searching for tx by nonce");

                        // Strategy: fetch events for the sender, find tx with target nonce
                        match ds.get_events_for_address(sender, None, None, 200).await {
                            Ok(events) => {
                                // Collect unique tx hashes
                                let mut seen = std::collections::HashSet::new();
                                let tx_hashes: Vec<_> = events
                                    .iter()
                                    .filter_map(|e| {
                                        let h = e.transaction_hash;
                                        if h != starknet::core::types::Felt::ZERO && seen.insert(h)
                                        {
                                            Some(h)
                                        } else {
                                            None
                                        }
                                    })
                                    .collect();

                                // Find the tx with the target nonce. Fetch candidates in
                                // parallel (buffer_unordered) so worst-case latency is ~1
                                // RTT instead of N. Nonces are unique per sender on a
                                // healthy chain, so unordered traversal cannot pick a
                                // different "winner".
                                //
                                // We drain the stream to completion even after finding a
                                // match: the underlying `CachingDataSource::get_transaction`
                                // uses `Shared`-future dedup and removes its `pending_txs`
                                // entry only after the future is awaited to completion.
                                // Dropping the stream early would leave those entries in
                                // the pending map until some later caller observes them,
                                // so we let in-flight fetches finish (their results are
                                // cached for free) and just keep the first match.
                                use futures::stream::StreamExt;
                                let target_felt = starknet::core::types::Felt::from(target_nonce);
                                let ds_for_stream = ds.clone();
                                let stream = futures::stream::iter(tx_hashes.into_iter())
                                    .map(|h| {
                                        let ds = ds_for_stream.clone();
                                        async move { (h, ds.get_transaction(h).await) }
                                    })
                                    .buffer_unordered(8);

                                let mut found: Option<(
                                    starknet::core::types::Felt,
                                    crate::data::types::SnTransaction,
                                )> = None;
                                {
                                    tokio::pin!(stream);
                                    while let Some((hash, res)) = stream.next().await {
                                        if found.is_some() {
                                            continue;
                                        }
                                        if let Ok(fetched_tx) = res
                                            && let crate::data::types::SnTransaction::Invoke(
                                                ref inv,
                                            ) = fetched_tx
                                            && inv.nonce == Some(target_felt)
                                            && inv.sender_address == sender
                                        {
                                            found = Some((hash, fetched_tx));
                                        }
                                    }
                                }

                                if let Some((hash, fetched_tx)) = found {
                                    match ds.get_receipt(hash).await {
                                        Ok(receipt) => {
                                            transaction::decode_and_send_transaction(
                                                fetched_tx,
                                                receipt,
                                                &ds,
                                                pf.as_ref(),
                                                &abi_reg,
                                                &tx,
                                            )
                                            .await;
                                        }
                                        Err(e) => {
                                            let _ = tx
                                                .send(Action::Error(format!("Fetch receipt: {e}")));
                                        }
                                    }
                                    return;
                                }
                                let _ = tx.send(Action::Error(format!(
                                    "No tx found with nonce {target_nonce} for this sender"
                                )));
                            }
                            Err(e) => {
                                let _ = tx
                                    .send(Action::Error(format!("Failed to search by nonce: {e}")));
                            }
                        }
                    }
                    Action::ResolveSearch { query } => {
                        search::resolve_search(
                            query, &ds, &abi_reg, &dune, &pf, &voyager, &head, &tx, &cancel,
                        )
                        .await;
                    }
                    Action::EnrichAddressTxs { address, hashes } => {
                        address::enrich_address_txs(
                            address,
                            hashes,
                            &ds,
                            pf.as_ref(),
                            &abi_reg,
                            &tx,
                        )
                        .await;
                    }
                    Action::EnrichAddressEndpoints {
                        address,
                        current_nonce,
                        known_txs,
                    } => {
                        address::run_endpoint_enrichment(
                            address,
                            current_nonce,
                            known_txs,
                            &ds,
                            &dune,
                            &pf,
                            &abi_reg,
                            &tx,
                        )
                        .await;
                    }
                    Action::FillAddressNonceGaps {
                        address,
                        known_txs,
                        gap,
                    } => {
                        address::run_nonce_gap_fill(
                            address, known_txs, gap, &ds, &dune, &pf, &abi_reg, &tx,
                        )
                        .await;
                    }
                    Action::FillAddressCallGap {
                        address,
                        gap,
                        is_contract,
                    } => {
                        address::run_call_gap_fill(
                            address,
                            gap,
                            is_contract,
                            &ds,
                            &dune,
                            &pf,
                            &abi_reg,
                            &tx,
                        )
                        .await;
                    }
                    Action::FetchAddressTransfers {
                        address,
                        floor_block,
                    } => {
                        transfers::fetch_top_delta(
                            address,
                            floor_block,
                            &head,
                            transfers::TransferBackends {
                                ds: &ds,
                                starkscan: starkscan.as_ref(),
                                pf: pf.as_ref(),
                                tx: &tx,
                            },
                        )
                        .await;
                    }
                    Action::FillAddressTransferGap {
                        address,
                        lo_block,
                        hi_block,
                    } => {
                        transfers::fill_gap(
                            address,
                            lo_block,
                            hi_block,
                            transfers::TransferBackends {
                                ds: &ds,
                                starkscan: starkscan.as_ref(),
                                pf: pf.as_ref(),
                                tx: &tx,
                            },
                        )
                        .await;
                    }
                    Action::PersistAddressTransfers { address, rows } => {
                        ds.save_transfers(&address, &rows);
                    }
                    Action::EnrichAddressCalls {
                        address,
                        hashes_with_blocks,
                    } => {
                        let calls = address::build_contract_calls_from_hashes(
                            address,
                            &hashes_with_blocks,
                            &ds,
                            pf.as_ref(),
                            &abi_reg,
                        )
                        .await;
                        if !calls.is_empty() {
                            let _ = tx.send(Action::AddressCallsEnriched { address, calls });
                        }
                    }
                    Action::FetchMoreAddressTxs {
                        address,
                        before_block,
                        is_contract,
                    } => {
                        address::fetch_more_address_txs(
                            address,
                            before_block,
                            is_contract,
                            &ds,
                            &dune,
                            &pf,
                            &abi_reg,
                            &tx,
                        )
                        .await;
                    }
                    Action::FetchAddressMetaTxs {
                        address,
                        from_block,
                        continuation_token,
                        window_size,
                        limit,
                    } => {
                        // On first page, emit cached rows immediately so the UI
                        // renders instantly. Uses a separate CacheLoaded action so
                        // it merges without clearing the in-flight loading flag.
                        if continuation_token.is_none() {
                            let cached = ds.load_cached_meta_txs(&address);
                            if !cached.is_empty() {
                                let _ = tx.send(Action::AddressMetaTxsCacheLoaded {
                                    address,
                                    summaries: cached,
                                });
                            }
                        }
                        if let Some(pf) = pf.as_ref() {
                            address::fetch_address_meta_txs(
                                address,
                                from_block,
                                continuation_token,
                                window_size,
                                limit,
                                &ds,
                                dune.as_ref(),
                                pf,
                                &abi_reg,
                                &tx,
                                cancel.clone(),
                            )
                            .await;
                        } else {
                            // pf-query required for this feature. Send empty result so
                            // the UI clears its loading state instead of hanging.
                            let _ = tx.send(Action::AddressMetaTxsLoaded {
                                address,
                                summaries: Vec::new(),
                                next_token: None,
                                next_window_size: None,
                            });
                        }
                    }
                    Action::ClassifyPotentialMetaTx { address, tx_hash } => {
                        // Streaming path from WS: a TRANSACTION_EXECUTED event for
                        // `address` arrived. Fetch the single tx via pf-query, run
                        // it through the shared classifier, and — if it's actually
                        // a meta-tx where `address` is the intender — emit it to
                        // merge into the MetaTxs tab. Silent no-op otherwise
                        // (including when pf-query is unavailable).
                        let Some(pf) = pf.as_ref() else {
                            return;
                        };
                        match pf.get_txs_by_hash(&[tx_hash]).await {
                            Ok(rows) => {
                                let Some(row) = rows.first() else {
                                    return;
                                };
                                if let Some(summary) =
                                    address::classify_meta_tx_candidate(address, row, &abi_reg)
                                        .await
                                {
                                    // Persist immediately so the row survives
                                    // restart even if the user never scrolls past
                                    // the bulk fetch range. INSERT OR REPLACE
                                    // handles dedup at the DB layer.
                                    ds.save_meta_txs(&address, std::slice::from_ref(&summary));
                                    let _ = tx.send(Action::AddressMetaTxsStreamed {
                                        address,
                                        summaries: vec![summary],
                                    });
                                }
                            }
                            Err(e) => {
                                debug!(tx = %format!("{:#x}", tx_hash), error = %e, "WS meta-tx classify: get_txs_by_hash failed");
                            }
                        }
                    }
                    Action::DecodeAddressWsEvent { address, event } => {
                        // Streaming path from WS: a raw event for the
                        // currently-viewed `address` arrived. Resolve its
                        // emitter ABI, decode, and forward so the Events tab
                        // merges the decoded row in real time. ABI miss falls
                        // back to an undecoded `DecodedEvent` (raw keys/data
                        // preserved) — the user still sees live activity, it
                        // just renders without names.
                        let abi = abi_reg.get_abi_for_address(&event.from_address).await;
                        let decoded = crate::decode::events::decode_event(&event, abi.as_deref());
                        let _ = tx.send(Action::AddressEventStreamed {
                            address,
                            decoded_event: decoded,
                        });
                    }
                    Action::FetchClassInfo { class_hash } => {
                        class::fetch_class_info(class_hash, &ds, &abi_reg, &dune, &pf, &tx).await;
                    }
                    Action::PersistAddressTxs { address, txs } => {
                        ds.save_address_txs(&address, &txs);
                    }
                    Action::PersistAddressCalls { address, calls } => {
                        ds.save_address_calls(&address, &calls);
                    }
                    Action::FetchTokenPricesToday { tokens } => {
                        if let Some(pc) = &prices
                            && pc.ensure_today(&tokens).await
                        {
                            let _ = tx.send(Action::PricesUpdated);
                        }
                    }
                    Action::FetchTokenPricesHistoric { requests } => {
                        if let Some(pc) = &prices
                            && pc.ensure_historic(&requests).await
                        {
                            let _ = tx.send(Action::PricesUpdated);
                        }
                    }
                    Action::FetchTokenMetadata { token } => {
                        let meta =
                            crate::data::token_metadata::fetch_token_metadata(token, &*ds).await;
                        if let Some(m) = &meta {
                            ds.save_token_metadata(&token, m);
                            tracing::debug!(
                                token = %format!("{:#x}", token),
                                symbol = %m.symbol,
                                decimals = m.decimals,
                                "Token metadata fetched"
                            );
                        } else {
                            tracing::debug!(
                                token = %format!("{:#x}", token),
                                "Token metadata fetch failed (not ERC-20-shaped or RPC error)"
                            );
                        }
                        let _ = tx.send(Action::TokenMetadataLoaded { token, meta });
                    }
                    Action::FetchPrivateNotes { user, viewing_key } => {
                        // Re-wrap the raw felt as a SecretFelt so it gets
                        // zeroize-on-drop after the sync completes. The
                        // value already passed through the channel as a
                        // bare Felt — the wrapper is just for in-memory
                        // hygiene, not for cryptographic confidentiality
                        // beyond what the channel already provides.
                        let key =
                            crate::decode::privacy_crypto::types::SecretFelt::new(viewing_key);
                        let backend = crate::decode::privacy_sync::StorageBackend::new(
                            pf.clone(),
                            Arc::clone(&ds),
                        );
                        // Build a SyncResume from the cached state for this
                        // user, so the walk can skip already-enumerated
                        // channels/subchannels and only probe for new content.
                        let (cached_notes, cached_nullifiers) =
                            ds.load_private_notes_for_user(&user);
                        let mut resume = crate::decode::privacy_sync::SyncResume::default();
                        for n in cached_notes {
                            resume.notes.insert(n.note_id, n);
                        }
                        for (nul, nid) in cached_nullifiers {
                            resume.by_nullifier.insert(nul, nid);
                        }
                        match crate::decode::privacy_sync::sync_user_notes(
                            user, &key, &backend, resume,
                        )
                        .await
                        {
                            Ok((index, block_number)) => {
                                let nullifiers: Vec<_> =
                                    index.by_nullifier.iter().map(|(n, id)| (*n, *id)).collect();
                                let notes: Vec<_> = index.notes.into_values().collect();
                                // Persist before notifying the UI so a crash mid-render
                                // can't drop the work we just did. Idempotent per user
                                // — overwrites prior rows.
                                ds.save_private_notes_for_user(
                                    &user,
                                    &notes,
                                    &nullifiers,
                                    block_number,
                                );
                                let _ = tx.send(Action::PrivateNotesIndexed {
                                    user,
                                    notes,
                                    nullifiers,
                                });
                            }
                            Err(e) => {
                                tracing::warn!(
                                    user = %format!("{:#x}", user),
                                    error = %e,
                                    "Privacy sync failed"
                                );
                            }
                        }
                    }
                    // Response actions are not handled here
                    _ => {}
                }
            };

            if cancellable {
                tokio::select! {
                    _ = task => {}
                    _ = cancel.cancelled() => {
                        debug!("Background task cancelled on navigation");
                    }
                }
            } else {
                task.await;
            }
        });
    }

    info!("Network task ended");
}

/// Actions that represent foreground navigation. Receiving one of these
/// cancels the current session token, which in turn stops any in-flight
/// cancellable background work (enrichment, MetaTx pagination, etc.) for the
/// previous view.
fn action_is_fg_nav(action: &Action) -> bool {
    matches!(
        action,
        Action::FetchAddressInfo { .. }
            | Action::ResolveSearch { .. }
            | Action::FetchBlockDetail { .. }
            | Action::FetchTransaction { .. }
            | Action::FetchClassInfo { .. }
            | Action::FetchTxByNonce { .. }
    )
}

/// Actions that should abort when the session token is cancelled. These are
/// address-view-scoped background operations — stale ones just waste
/// pf-query / RPC cycles and delay the new view. Foreground fetches (block,
/// tx, class detail, the initial address info) are intentionally excluded:
/// aborting them leaves the UI half-loaded.
fn action_is_cancellable(action: &Action) -> bool {
    matches!(
        action,
        Action::EnrichAddressTxs { .. }
            | Action::EnrichAddressEndpoints { .. }
            | Action::FillAddressNonceGaps { .. }
            | Action::FillAddressCallGap { .. }
            | Action::FetchAddressTransfers { .. }
            | Action::FillAddressTransferGap { .. }
            | Action::EnrichAddressCalls { .. }
            | Action::FetchAddressMetaTxs { .. }
            | Action::ClassifyPotentialMetaTx { .. }
            | Action::DecodeAddressWsEvent { .. }
            | Action::FetchMoreAddressTxs { .. }
            | Action::RefreshAddressRpc { .. }
    )
}

/// Helper to build an RPC source update action.
fn rpc_source_update(status: crate::app::state::SourceStatus) -> Action {
    Action::SourceUpdate {
        source: crate::app::actions::Source::Rpc,
        status,
    }
}

/// Helper to build a Dune source update action.
fn dune_source_update(status: crate::app::state::SourceStatus) -> Action {
    Action::SourceUpdate {
        source: crate::app::actions::Source::Dune,
        status,
    }
}

/// Spawns a polling task that checks for new blocks periodically.
pub fn spawn_block_poller(
    data_source: Arc<dyn DataSource>,
    response_tx: mpsc::UnboundedSender<Action>,
    interval: std::time::Duration,
    head_block: Arc<HeadTracker>,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        let mut last_block = 0u64;
        loop {
            tokio::time::sleep(interval).await;

            match data_source.get_latest_block_number().await {
                Ok(latest) => {
                    head_block.update(latest);
                    if latest > last_block && last_block > 0 {
                        // Fetch new blocks
                        for num in (last_block + 1)..=latest {
                            match data_source.get_block(num).await {
                                Ok(block) => {
                                    let _ = response_tx.send(Action::NewBlock(block));
                                }
                                Err(e) => {
                                    tracing::warn!("Failed to fetch new block {num}: {e}");
                                }
                            }
                        }
                    }
                    last_block = latest;
                }
                Err(e) => {
                    tracing::warn!("Failed to poll latest block: {e}");
                }
            }
        }
    })
}