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
pub mod cache;
pub mod pathfinder;
pub mod rpc;
pub mod token_metadata;
pub mod types;

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

use starknet::core::types::{ContractClass, TransactionTrace};

use crate::error::Result;
use types::{
    AddressTxSummary, ClassContractEntry, ClassDeclareInfo, ContractCallSummary,
    MetaTxIntenderSummary, SnBlock, SnEvent, SnReceipt, SnTransaction, TokenTransfer,
};

use pathfinder::ClassHashEntry;

/// What kind of event filter a scan applied. Used as a secondary key in
/// `address_search_progress` so that a narrower (keyed) scan doesn't
/// falsely mark the broader (unkeyed) region as "covered". Scans record
/// coverage under the kind they used; callers query the kind they need.
///
/// - [`FilterKind::Unkeyed`] — all events emitted by the address
///   (pf-query `from_address` filter, no key filter). Equivalent to the
///   Events-tab source. Strictly a superset of `Keyed` data over the
///   same block range, so an unkeyed-covered range satisfies keyed
///   queries too (though we don't currently exploit that — see §3 of
///   the address-view revamp plan).
/// - [`FilterKind::Keyed`] — events with a specific key filter
///   (currently only `TRANSACTION_EXECUTED`, used by the MetaTxs tab).
///   Narrower than `Unkeyed`.
/// - [`FilterKind::DuneCalls`] — not an event scan: the block span Dune
///   contract-calls pages have tracked for the Calls tab.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FilterKind {
    Unkeyed,
    Keyed,
    DuneCalls,
}

impl FilterKind {
    /// Stable string identifier persisted in the SQLite `filter_kind` column.
    pub fn as_str(self) -> &'static str {
        match self {
            FilterKind::Unkeyed => "unkeyed",
            FilterKind::Keyed => "keyed",
            FilterKind::DuneCalls => "dune_calls",
        }
    }
}

/// Cheap, in-process source of the chain's latest block height.
///
/// Implementors (typically a WS-fed `HeadTracker`) let cache layers check
/// staleness without paying an RPC round-trip on every hit. Returning `None`
/// means "I don't have a recent enough value" — callers fall back to
/// `DataSource::get_latest_block_number()`.
pub trait LatestBlockSource: Send + Sync {
    fn latest(&self) -> Option<u64>;
}

/// Abstraction over different Starknet data sources (RPC, Pathfinder DB).
#[async_trait]
pub trait DataSource: Send + Sync {
    async fn get_latest_block_number(&self) -> Result<u64>;
    /// Best-effort chain head for window/anchor math. Default falls back to a
    /// full RPC; `CachingDataSource` overrides to read an in-process tracker
    /// first (WS-fed, < 2 s old typically). Returns `None` when no usable
    /// answer is available — callers handle that as "give up" or
    /// "degrade gracefully" per their own semantics.
    ///
    /// Use this instead of `get_latest_block_number` whenever the result is
    /// only used to anchor a windowed scan or staleness check; reserve the
    /// authoritative call for paths that actually need to know the tip
    /// (e.g. the head-keeper that populates the tracker).
    ///
    /// The underlying RPC error (if any) is logged at debug level here, so
    /// callers can keep their failure branches concise without losing the
    /// upstream context (network, HTTP, deserialization, …).
    async fn latest_block_hint(&self) -> Option<u64> {
        match self.get_latest_block_number().await {
            Ok(n) => Some(n),
            Err(e) => {
                tracing::debug!(error = %e, "latest_block_hint: upstream get_latest_block_number failed");
                None
            }
        }
    }
    async fn get_block(&self, number: u64) -> Result<SnBlock>;
    async fn get_block_by_hash(&self, hash: Felt) -> Result<u64>;
    async fn get_block_with_txs(&self, number: u64) -> Result<(SnBlock, Vec<SnTransaction>)>;
    /// Lightweight finality probe for a single block. Returns the block's
    /// status string ("ACCEPTED_ON_L1" / "ACCEPTED_ON_L2" / "PRE_CONFIRMED").
    /// Used to refresh a cached block whose status is not yet final without
    /// re-downloading its full transaction bodies. The default implementation
    /// falls back to a full `get_block`; `RpcDataSource` overrides it with a
    /// cheaper `starknet_getBlockWithTxHashes` call.
    async fn get_block_status(&self, number: u64) -> Result<String> {
        self.get_block(number).await.map(|b| b.status)
    }
    async fn get_transaction(&self, hash: Felt) -> Result<SnTransaction>;
    async fn get_receipt(&self, hash: Felt) -> Result<SnReceipt>;
    async fn get_nonce(&self, address: Felt) -> Result<Felt>;
    async fn get_class_hash(&self, address: Felt) -> Result<Felt>;
    /// Class hash that was active for `address` at `block`. Used by tx
    /// decoding so old transactions render with the ABI that was deployed
    /// when they ran, not the current one. Default implementation falls
    /// back to `get_class_hash` (latest) — sources backed by RPC override
    /// to use `BlockId::Number(block)`.
    async fn get_class_hash_at(&self, address: Felt, _block: u64) -> Result<Felt> {
        self.get_class_hash(address).await
    }
    async fn get_class(&self, class_hash: Felt) -> Result<ContractClass>;
    /// Read a single contract storage slot. Used as the RPC fallback when
    /// pf-query's batch endpoint isn't reachable, called concurrently from
    /// the privacy-pool sync. Default impl returns an error so non-RPC
    /// sources don't pretend to support it; the RPC source overrides.
    async fn get_storage_at(
        &self,
        _contract: Felt,
        _key: Felt,
        _block: Option<u64>,
    ) -> Result<Felt> {
        Err(crate::error::StarktopError::Provider(
            "get_storage_at not implemented for this DataSource".into(),
        ))
    }
    /// Fetch the execution trace of a transaction (recursive call tree with
    /// nested events, calldata, and results). Used by the tx-detail Trace tab.
    async fn get_trace(&self, hash: Felt) -> Result<TransactionTrace>;
    async fn get_recent_blocks(&self, count: usize) -> Result<Vec<SnBlock>>;
    /// Fetch recent events emitted by or targeting an address.
    ///
    /// `to_block` is an inclusive upper bound; `None` means "up to latest".
    /// Used by pagination to fetch events strictly older than a cursor.
    async fn get_events_for_address(
        &self,
        address: Felt,
        from_block: Option<u64>,
        to_block: Option<u64>,
        limit: usize,
    ) -> Result<Vec<SnEvent>>;
    /// Load cached tx summaries for an address (returns empty if none).
    fn load_cached_address_txs(&self, _address: &Felt) -> Vec<AddressTxSummary> {
        Vec::new() // Default: no cache. CachingDataSource overrides.
    }
    /// Save tx summaries for an address to persistent cache.
    fn save_address_txs(&self, _address: &Felt, _txs: &[AddressTxSummary]) {
        // Default: no-op. CachingDataSource overrides.
    }
    /// Load every cached on-chain ERC-20 metadata entry. Used at app
    /// boot to seed the in-memory token-metadata cache so the first
    /// render of unknown tokens already has decimals + symbol from the
    /// last session, no round-trip required.
    fn load_token_metadata(&self) -> Vec<(Felt, crate::data::token_metadata::TokenMeta)> {
        Vec::new()
    }
    /// Save one (token, meta) row. Called from the App reducer after a
    /// successful background fetch lands.
    fn save_token_metadata(&self, _address: &Felt, _meta: &crate::data::token_metadata::TokenMeta) {
        // Default: no-op. CachingDataSource overrides.
    }
    /// Load every persisted forward-decrypted Privacy Pool note plus the
    /// nullifier→note_id index. Used at boot to seed `app.private_notes`
    /// and `app.private_nullifiers` so the Privacy tab can annotate
    /// matching events on the very first frame, before any in-session
    /// sync has run.
    fn load_private_notes(
        &self,
    ) -> (
        Vec<crate::decode::privacy_sync::DecryptedNote>,
        Vec<(Felt, Felt)>,
    ) {
        (Vec::new(), Vec::new())
    }
    /// Persist a user's freshly-synced notes + nullifiers + last-synced
    /// block. Replaces any prior rows for the same user. Called by the
    /// network task after `sync_user_notes` succeeds.
    fn save_private_notes_for_user(
        &self,
        _user: &Felt,
        _notes: &[crate::decode::privacy_sync::DecryptedNote],
        _nullifiers: &[(Felt, Felt)],
        _last_synced_block: u64,
    ) {
        // Default: no-op. CachingDataSource overrides.
    }
    /// Load the persisted notes + nullifiers for a single user, narrowed
    /// from the global cache. Used by the network task to seed
    /// `SyncResume` before invoking `sync_user_notes`, so the walk
    /// resumes from the last persisted state instead of re-enumerating
    /// from genesis.
    fn load_private_notes_for_user(
        &self,
        _user: &Felt,
    ) -> (
        Vec<crate::decode::privacy_sync::DecryptedNote>,
        Vec<(Felt, Felt)>,
    ) {
        (Vec::new(), Vec::new())
    }
    /// Load cached contract call summaries for an address.
    fn load_cached_address_calls(&self, _address: &Felt) -> Vec<ContractCallSummary> {
        Vec::new()
    }
    /// Upsert call summaries by tx hash; the address's other cached rows are kept.
    fn save_address_calls(&self, _address: &Felt, _calls: &[ContractCallSummary]) {
        // Default: no-op. CachingDataSource overrides.
    }
    /// Load the block ranges `[lo, hi]` we have *fully* scanned for contract
    /// calls on this address via on-demand gap fills. Used to suppress
    /// re-surfacing a genuinely-sparse hole as a Calls-tab gap after we've
    /// already scanned it and found no (or few) calls. Persisted so the
    /// "closed" knowledge survives re-navigation and restarts.
    fn load_call_scanned_ranges(&self, _address: &Felt) -> Vec<(u64, u64)> {
        Vec::new()
    }
    /// Record `[lo, hi]` as a fully-scanned contract-call range, coalescing it
    /// into any existing persisted ranges for the address.
    fn add_call_scanned_range(&self, _address: &Felt, _lo: u64, _hi: u64) {
        // Default: no-op. CachingDataSource overrides.
    }
    /// Cached ERC-20 transfers touching an address, newest-first.
    fn load_cached_transfers(&self, _address: &Felt) -> Vec<TokenTransfer> {
        Vec::new()
    }
    /// Upsert transfer rows for an address, keyed by `(tx_hash, event_index)`.
    fn save_transfers(&self, _address: &Felt, _rows: &[TokenTransfer]) {}
    /// Block ranges fully scanned for transfers (same model as the Calls tab).
    fn load_transfer_scanned_ranges(&self, _address: &Felt) -> Vec<(u64, u64)> {
        Vec::new()
    }
    fn add_transfer_scanned_range(&self, _address: &Felt, _lo: u64, _hi: u64) {}
    /// Every `Transfer` event in `[from_block, to_block]` (inclusive) where
    /// `address` is `from` or `to`, across all token contracts.
    async fn get_transfer_events(
        &self,
        _address: Felt,
        _from_block: u64,
        _to_block: u64,
    ) -> Result<Vec<TokenTransfer>> {
        Err(crate::error::StarktopError::Provider(
            "get_transfer_events not implemented for this DataSource".into(),
        ))
    }
    /// Load cached meta-tx (outside-execution) summaries for an address where the
    /// address is the intender.
    fn load_cached_meta_txs(&self, _address: &Felt) -> Vec<MetaTxIntenderSummary> {
        Vec::new()
    }
    /// Save meta-tx summaries for an address (intender) to persistent cache.
    fn save_meta_txs(&self, _address: &Felt, _txs: &[MetaTxIntenderSummary]) {
        // Default: no-op. CachingDataSource overrides.
    }
    /// Load cached activity range for an address (min_block, max_block, event_count).
    /// Returns None if not cached or stale (> 1 hour).
    fn load_cached_activity_range(&self, _address: &Felt) -> Option<(u64, u64)> {
        None // Default: no cache. CachingDataSource overrides.
    }
    /// Load cached activity range with event count.
    fn load_cached_activity_range_with_count(&self, _address: &Felt) -> Option<(u64, u64, u64)> {
        None
    }
    /// Load cached activity range ignoring freshness. Used by the probe
    /// TopDelta path: a stale but present row still has a valid `min_block`
    /// (the deploy/first-activity floor never regresses), so we can avoid
    /// re-probing the entire history and only extend `max_block` + count
    /// from the cached high-water mark.
    fn load_cached_activity_range_any_age(&self, _address: &Felt) -> Option<(u64, u64, u64)> {
        None
    }
    /// Save discovered activity range for an address.
    fn save_activity_range(&self, _address: &Felt, _min_block: u64, _max_block: u64) {
        // Default: no-op. CachingDataSource overrides.
    }
    /// Save discovered activity range with event count.
    fn save_activity_range_with_count(
        &self,
        _address: &Felt,
        _min_block: u64,
        _max_block: u64,
        _event_count: u64,
    ) {
        // Default: no-op. CachingDataSource overrides.
    }
    /// Fetch events emitted by a contract (all events, not just transaction_executed).
    /// Used for finding calls TO a contract.
    ///
    /// `to_block` is an inclusive upper bound; `None` means "up to latest".
    async fn get_contract_events(
        &self,
        address: Felt,
        from_block: Option<u64>,
        to_block: Option<u64>,
        limit: usize,
    ) -> Result<Vec<SnEvent>> {
        // Default: same as get_events_for_address (overridden in RPC impl)
        self.get_events_for_address(address, from_block, to_block, limit)
            .await
    }
    /// Call a contract view function (e.g., balance_of).
    async fn call_contract(
        &self,
        contract_address: Felt,
        selector: Felt,
        calldata: Vec<Felt>,
    ) -> Result<Vec<Felt>>;

    /// Batch multiple view-function calls into a single JSON-RPC round trip.
    ///
    /// Returns per-call results in the same order as `calls`. The default
    /// implementation issues each call sequentially — the RPC-backed source
    /// overrides this to use `starknet_call` batching (issue #12), which
    /// turns N round trips into one for things like fetching balances across
    /// a fixed set of tokens.
    async fn batch_call_contracts(
        &self,
        calls: Vec<(Felt, Felt, Vec<Felt>)>,
    ) -> Vec<Result<Vec<Felt>>> {
        let mut out = Vec::with_capacity(calls.len());
        for (contract, selector, calldata) in calls {
            out.push(self.call_contract(contract, selector, calldata).await);
        }
        out
    }

    /// Batch many `starknet_getStorageAt` reads into a single JSON-RPC
    /// round trip. Used as the fast RPC fallback for the privacy-pool
    /// sync when pf-query's `/storage-batch` isn't reachable — without
    /// this, the fallback degrades to N individual HTTP calls.
    ///
    /// Returns per-key values in the same order as `keys`. The default
    /// implementation issues each read sequentially via
    /// `get_storage_at`; the RPC-backed source overrides to use
    /// `provider.batch_requests`. Order is preserved on success; on
    /// batch failure the override falls back to per-key sequential
    /// reads so a single bad key doesn't sink the whole batch.
    async fn batch_get_storage_at(
        &self,
        contract: Felt,
        keys: &[Felt],
        block: Option<u64>,
    ) -> Vec<Result<Felt>> {
        let mut out = Vec::with_capacity(keys.len());
        for k in keys {
            out.push(self.get_storage_at(contract, *k, block).await);
        }
        out
    }

    // --- Deploy info cache ---
    /// Load cached deploy tx info for an address. Returns (tx_hash, block, deployer).
    fn load_cached_deploy_info(&self, _address: &Felt) -> Option<(Felt, u64, Option<Felt>)> {
        None
    }
    /// Save deploy tx info for an address.
    fn save_deploy_info(
        &self,
        _address: &Felt,
        _tx_hash: &Felt,
        _block: u64,
        _deployer: Option<&Felt>,
    ) {
    }

    // --- Class history cache ---
    /// Load the cached pf-query class-hash history for an address, ordered
    /// from latest to oldest (matches the pf-query response shape so the UI
    /// can treat cached and live results identically).
    fn load_cached_class_history(&self, _address: &Felt) -> Vec<ClassHashEntry> {
        Vec::new()
    }
    /// Persist the full class-hash history for an address. Replaces any
    /// existing rows so a refreshed pf-query response is the source of truth.
    fn save_class_history(&self, _address: &Felt, _entries: &[ClassHashEntry]) {}
    /// Highest block at which a pf-query response confirmed the cached
    /// class-history is complete. `None` if never validated by pf.
    fn load_class_history_max_block(&self, _address: &Felt) -> Option<u64> {
        None
    }
    /// Record the block at which pf-query just re-validated the cached
    /// class-history. Callers must NOT advance this when pf is unavailable —
    /// the watermark must reflect verified coverage only.
    fn save_class_history_max_block(&self, _address: &Felt, _block: u64) {}

    // --- Nonce cache ---
    /// Load cached nonce + block number for an address.
    fn load_cached_nonce(&self, _address: &Felt) -> Option<(Felt, u64)> {
        None
    }
    /// Save nonce + block number for an address.
    fn save_cached_nonce(&self, _address: &Felt, _nonce: &Felt, _block: u64) {}

    // --- Class-hash cache (synchronous read for cache-first paint paths) ---
    /// Load the cached class_hash for an address without any network IO.
    /// Used by the address pipeline's cache-first emit so a re-visit can
    /// render the live `class_hash` from disk before the RPC join lands.
    /// `None` ⇒ no class_hash ever cached for this address.
    fn load_cached_class_hash(&self, _address: &Felt) -> Option<Felt> {
        None
    }

    // --- Search progress cache ---
    /// Load cached search progress `(min_searched_block, max_searched_block)`
    /// for `(address, filter_kind)`. `None` ⇒ no scan of that kind recorded.
    fn load_search_progress(
        &self,
        _address: &Felt,
        _filter_kind: FilterKind,
    ) -> Option<(u64, u64)> {
        None
    }
    /// Save (merge-expand) search progress for `(address, filter_kind)`.
    /// The SQLite impl extends the existing min/max range rather than
    /// replacing, so repeated windowed scans accumulate coverage.
    fn save_search_progress(
        &self,
        _address: &Felt,
        _filter_kind: FilterKind,
        _min_block: u64,
        _max_block: u64,
    ) {
    }

    /// Load the last-known upstream event-count total (e.g. Dune probe) for
    /// an address. `None` means "never probed" — not "zero activity".
    fn load_activity_total(&self, _address: &Felt) -> Option<u64> {
        None
    }
    /// Persist the upstream event-count total. Survives restarts so that UI
    /// labels like "(204 / 11400)" don't regress to "(204)" on revisit.
    fn save_activity_total(&self, _address: &Felt, _total: u64) {}

    /// Load all cached events for an address (newest-first when persisted
    /// through the merge path). Empty vec if nothing cached.
    fn load_address_events(&self, _address: &Felt) -> Vec<SnEvent> {
        Vec::new()
    }

    /// Additive merge of `new_events` into the per-address event cache. Dedupes
    /// on (tx_hash, block, event_index), sorts newest-first, persists, and
    /// returns the merged list.
    ///
    /// Use this instead of `save_address_events` when appending a top-of-tip
    /// or bottom-extension window — it preserves older cached events.
    fn merge_address_events(&self, _address: &Felt, new_events: &[SnEvent]) -> Vec<SnEvent> {
        new_events.to_vec()
    }

    /// Persist `events` into the per-address event cache without reading it
    /// back. Fire-and-forget, for hot paths like the WS stream.
    fn append_address_events(&self, _address: &Felt, _events: &[SnEvent]) {}

    // --- Class declaration cache ---
    /// Load cached declare info for a class hash. Declarations are immutable
    /// (a class's declaration block/tx never changes), so there is no TTL.
    fn load_cached_class_declaration(&self, _class_hash: &Felt) -> Option<ClassDeclareInfo> {
        None
    }
    /// Persist the declare info for a class hash.
    fn save_class_declaration(&self, _class_hash: &Felt, _info: &ClassDeclareInfo) {}

    // --- Class contracts cache ---
    /// Load cached list of contracts deployed with this class hash. Returns
    /// `None` if not cached or the cached entry is stale (> 1 hour old) —
    /// contracts-by-class grows monotonically as new deploys happen, so it
    /// needs a short TTL unlike the immutable declaration.
    fn load_cached_class_contracts(&self, _class_hash: &Felt) -> Option<Vec<ClassContractEntry>> {
        None
    }
    /// Persist the full contracts list for a class hash (replaces any prior
    /// list) and refresh the fetched-at timestamp used for TTL.
    fn save_class_contracts(&self, _class_hash: &Felt, _contracts: &[ClassContractEntry]) {}
}