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
use starknet::core::types::Felt;

/// Block summary for the block list.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SnBlock {
    pub number: u64,
    pub hash: Felt,
    pub parent_hash: Felt,
    pub timestamp: u64,
    pub sequencer_address: Felt,
    pub transaction_count: usize,
    // Gas prices in fri (10^-18 STRK)
    pub l1_gas_price_fri: u128,
    pub l1_gas_price_wei: u128,
    pub l2_gas_price_fri: u128,
    pub l1_data_gas_price_fri: u128,
    pub starknet_version: String,
    /// Block finality: "ACCEPTED_ON_L1" / "ACCEPTED_ON_L2" / "PENDING" /
    /// "REJECTED" / "PRE_CONFIRMED". `serde(default)` keeps blocks cached
    /// before this field existed deserializable (they get ""), and an empty
    /// or non-L1 status is treated as not-yet-final so it is re-probed.
    #[serde(default)]
    pub status: String,
}

/// Transaction types on Starknet.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum SnTransaction {
    Invoke(InvokeTx),
    Declare(DeclareTx),
    DeployAccount(DeployAccountTx),
    L1Handler(L1HandlerTx),
    Deploy(DeployTx),
}

impl SnTransaction {
    pub fn hash(&self) -> Felt {
        match self {
            SnTransaction::Invoke(tx) => tx.hash,
            SnTransaction::Declare(tx) => tx.hash,
            SnTransaction::DeployAccount(tx) => tx.hash,
            SnTransaction::L1Handler(tx) => tx.hash,
            SnTransaction::Deploy(tx) => tx.hash,
        }
    }

    pub fn sender(&self) -> Felt {
        match self {
            SnTransaction::Invoke(tx) => tx.sender_address,
            SnTransaction::Declare(tx) => tx.sender_address,
            SnTransaction::DeployAccount(tx) => tx.contract_address,
            SnTransaction::L1Handler(tx) => tx.contract_address,
            SnTransaction::Deploy(tx) => tx.contract_address,
        }
    }

    pub fn type_name(&self) -> &'static str {
        match self {
            SnTransaction::Invoke(_) => "INVOKE",
            SnTransaction::Declare(_) => "DECLARE",
            SnTransaction::DeployAccount(_) => "DEPLOY_ACCOUNT",
            SnTransaction::L1Handler(_) => "L1_HANDLER",
            SnTransaction::Deploy(_) => "DEPLOY",
        }
    }

    pub fn actual_fee(&self) -> Option<Felt> {
        match self {
            SnTransaction::Invoke(tx) => tx.actual_fee,
            SnTransaction::Declare(tx) => tx.actual_fee,
            SnTransaction::DeployAccount(tx) => tx.actual_fee,
            SnTransaction::L1Handler(tx) => tx.actual_fee,
            SnTransaction::Deploy(tx) => tx.actual_fee,
        }
    }

    pub fn set_actual_fee(&mut self, fee: Felt) {
        match self {
            SnTransaction::Invoke(tx) => tx.actual_fee = Some(fee),
            SnTransaction::Declare(tx) => tx.actual_fee = Some(fee),
            SnTransaction::DeployAccount(tx) => tx.actual_fee = Some(fee),
            SnTransaction::L1Handler(tx) => tx.actual_fee = Some(fee),
            SnTransaction::Deploy(tx) => tx.actual_fee = Some(fee),
        }
    }

    pub fn tip(&self) -> u64 {
        match self {
            SnTransaction::Invoke(tx) => tx.tip,
            SnTransaction::Declare(tx) => tx.tip,
            SnTransaction::DeployAccount(tx) => tx.tip,
            SnTransaction::L1Handler(_) | SnTransaction::Deploy(_) => 0,
        }
    }

    pub fn block_number(&self) -> u64 {
        match self {
            SnTransaction::Invoke(tx) => tx.block_number,
            SnTransaction::Declare(tx) => tx.block_number,
            SnTransaction::DeployAccount(tx) => tx.block_number,
            SnTransaction::L1Handler(tx) => tx.block_number,
            SnTransaction::Deploy(tx) => tx.block_number,
        }
    }

    pub fn index(&self) -> u64 {
        match self {
            SnTransaction::Invoke(tx) => tx.index,
            SnTransaction::Declare(tx) => tx.index,
            SnTransaction::DeployAccount(tx) => tx.index,
            SnTransaction::L1Handler(tx) => tx.index,
            SnTransaction::Deploy(tx) => tx.index,
        }
    }

    pub fn nonce(&self) -> Option<Felt> {
        match self {
            SnTransaction::Invoke(tx) => tx.nonce,
            SnTransaction::Declare(_) => None,
            SnTransaction::DeployAccount(tx) => tx.nonce,
            SnTransaction::L1Handler(tx) => tx.nonce,
            SnTransaction::Deploy(_) => None,
        }
    }

    /// The first selector called (for Invoke txs, from multicall calldata).
    /// Used for the decoded endpoint column in block detail.
    pub fn first_selector(&self) -> Option<Felt> {
        match self {
            SnTransaction::Invoke(tx) => {
                // Multicall: calldata[0]=num_calls, [1]=addr, [2]=selector
                if tx.calldata.len() >= 3 {
                    Some(tx.calldata[2])
                } else {
                    None
                }
            }
            SnTransaction::L1Handler(tx) => Some(tx.entry_point_selector),
            _ => None,
        }
    }
}

/// Resource bounds for a V3 transaction.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct SnResourceBounds {
    pub l1_gas_max_amount: u64,
    pub l1_gas_max_price: u128,
    pub l2_gas_max_amount: u64,
    pub l2_gas_max_price: u128,
    pub l1_data_gas_max_amount: u64,
    pub l1_data_gas_max_price: u128,
}

/// Actual resources consumed (from receipt).
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct SnExecutionResources {
    pub l1_gas: u64,
    pub l2_gas: u64,
    pub l1_data_gas: u64,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct InvokeTx {
    pub hash: Felt,
    pub sender_address: Felt,
    pub calldata: Vec<Felt>,
    pub nonce: Option<Felt>,
    pub version: Felt,
    pub actual_fee: Option<Felt>,
    pub execution_status: ExecutionStatus,
    pub block_number: u64,
    pub index: u64,
    pub tip: u64,
    pub resource_bounds: Option<SnResourceBounds>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DeclareTx {
    pub hash: Felt,
    pub sender_address: Felt,
    pub class_hash: Felt,
    pub version: Felt,
    pub actual_fee: Option<Felt>,
    pub execution_status: ExecutionStatus,
    pub block_number: u64,
    pub index: u64,
    pub tip: u64,
    pub resource_bounds: Option<SnResourceBounds>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DeployAccountTx {
    pub hash: Felt,
    pub contract_address: Felt,
    pub class_hash: Felt,
    pub constructor_calldata: Vec<Felt>,
    #[serde(default)]
    pub contract_address_salt: Felt,
    pub nonce: Option<Felt>,
    pub version: Felt,
    pub actual_fee: Option<Felt>,
    pub execution_status: ExecutionStatus,
    pub block_number: u64,
    pub index: u64,
    pub tip: u64,
    pub resource_bounds: Option<SnResourceBounds>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct L1HandlerTx {
    pub hash: Felt,
    pub contract_address: Felt,
    pub entry_point_selector: Felt,
    pub calldata: Vec<Felt>,
    pub nonce: Option<Felt>,
    pub actual_fee: Option<Felt>,
    pub execution_status: ExecutionStatus,
    pub block_number: u64,
    pub index: u64,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DeployTx {
    pub hash: Felt,
    pub contract_address: Felt,
    pub class_hash: Felt,
    pub constructor_calldata: Vec<Felt>,
    pub version: Felt,
    pub actual_fee: Option<Felt>,
    pub execution_status: ExecutionStatus,
    pub block_number: u64,
    pub index: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ExecutionStatus {
    Succeeded,
    Reverted(String),
    Unknown,
}

/// Transaction receipt.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SnReceipt {
    pub transaction_hash: Felt,
    pub block_number: u64,
    pub block_hash: Option<Felt>,
    pub actual_fee: Felt,
    pub fee_unit: String,
    pub execution_status: ExecutionStatus,
    pub execution_resources: SnExecutionResources,
    pub events: Vec<SnEvent>,
    pub revert_reason: Option<String>,
    pub finality: String, // "ACCEPTED_ON_L2", "ACCEPTED_ON_L1", "PRE_CONFIRMED"
}

/// A single event emitted during transaction execution.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SnEvent {
    pub from_address: Felt,
    pub keys: Vec<Felt>,
    pub data: Vec<Felt>,
    pub transaction_hash: Felt,
    pub block_number: u64,
    pub event_index: u64,
}

/// A transaction summary for the address tx list.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AddressTxSummary {
    pub hash: Felt,
    pub nonce: u64,
    pub block_number: u64,
    pub timestamp: u64,
    pub endpoint_names: String, // comma-separated decoded selectors
    pub total_fee_fri: u128,
    pub tip: u64,
    pub tx_type: String,
    pub status: String, // "OK", "REVERTED", or "?"
    /// The actual sender of this transaction (may differ from the viewed address for deployment txs).
    #[serde(default)]
    pub sender: Option<Felt>,
    /// Contracts reached by this tx, in first-seen order with duplicates
    /// removed. Includes each top-level multicall target plus the inner
    /// target of any outside-execution call so privacy-pool reaches via
    /// `execute_from_outside*` / `execute_private_sponsored` wrappers are
    /// surfaced alongside the wrapper itself.
    ///
    /// Populated by the same path that fills `endpoint_names`; remains
    /// empty for non-INVOKE txs and pre-enrichment stubs. Consumers (Txs
    /// tab Contracts column, privacy-tx predicate, palette color map)
    /// treat the union as a single set — they don't need to distinguish
    /// top-level from OE-inner.
    #[serde(default)]
    pub called_contracts: Vec<Felt>,
}

impl AddressTxSummary {
    /// Whether this row still needs an enrichment fetch.
    ///
    /// `endpoint_names` is only meaningful for INVOKE — DECLARE/DEPLOY_ACCOUNT/
    /// L1_HANDLER have no multicall to decode, so an empty string there is a
    /// terminal state, not "unfetched". Treating it as unfetched caused
    /// pf-query refetches on every scroll keystroke.
    pub fn needs_enrichment(&self) -> bool {
        self.timestamp == 0 || (self.tx_type == "INVOKE" && self.endpoint_names.is_empty())
    }
}

/// A meta-transaction (SNIP-9 outside execution) summary for the MetaTxs tab on
/// an address view. Represents a tx where the viewed address is the intender
/// (original signer), not the on-chain sender (paymaster/relayer).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MetaTxIntenderSummary {
    /// On-chain tx hash.
    pub hash: Felt,
    /// Block the tx landed in.
    pub block_number: u64,
    /// Index within the block (tie-break for recency ordering).
    pub tx_index: u64,
    /// Block timestamp (unix seconds).
    pub timestamp: u64,
    /// The address that submitted the on-chain tx (relayer / AVNU forwarder / paymaster).
    pub paymaster: Felt,
    /// Outside-execution version: "v1" | "v2" | "v3" | "avnu".
    pub version: String,
    /// Outside-execution nonce (signed by the intender, not the sender's tx nonce).
    pub oe_nonce: Felt,
    /// Total fee paid by the paymaster (FRI).
    pub total_fee_fri: u128,
    /// Execution status ("OK" / "REV" / "?").
    pub status: String,
    /// Target addresses of every inner call (first rendered in the row, rest shown as "+N").
    pub inner_targets: Vec<Felt>,
    /// Comma-joined decoded entrypoint names of the inner calls (e.g. "approve, swap_exact_in").
    pub inner_endpoints: String,
    /// The `caller` field from the OE struct (ANY_CALLER sentinel or a specific forwarder).
    pub caller: Felt,
}

/// A call to a contract (for the Calls tab on contract addresses).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ContractCallSummary {
    pub tx_hash: Felt,
    pub sender: Felt,
    pub function_name: String,
    pub block_number: u64,
    pub timestamp: u64,
    pub total_fee_fri: u128,
    pub status: String,
    /// Sender tx nonce. `None` from Dune-sourced rows (not in `starknet.calls`);
    /// populated from RPC/pf-query rows and merged in by `deduplicate_contract_calls`.
    #[serde(default)]
    pub nonce: Option<u64>,
    /// Sender tip (FRI). `0` from Dune-sourced rows and stubs; filled by RPC/pf path.
    #[serde(default)]
    pub tip: u64,
    /// Target addresses of any outside-execution inner calls in this tx's
    /// multicall (deduped, first-seen order). Empty for Dune-only stubs (no
    /// calldata) and non-INVOKE rows. Used by the Calls-tab Prv column to
    /// flag txs that reach a privacy address only via an OE wrapper.
    #[serde(default)]
    pub inner_targets: Vec<Felt>,
}

/// Label information fetched from Voyager for a contract/account address.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct VoyagerLabelInfo {
    /// Display name shown on Voyager (e.g. "Binance: Hot Wallet", "Ether").
    pub name: Option<String>,
    /// Human-readable class alias (e.g. "OpenZeppelin Account", "ERC20").
    pub class_alias: Option<String>,
    /// Block number where the contract was deployed (from Voyager `blockNumber` field).
    /// Provides a known lower bound for the activity range.
    #[serde(default)]
    pub deploy_block: Option<u64>,
}

/// Fill `existing`'s missing fields from `incoming` (same tx hash). Returns
/// whether anything changed, so callers can persist only touched rows.
pub fn merge_call_into(existing: &mut ContractCallSummary, incoming: ContractCallSummary) -> bool {
    let mut changed = false;
    // Union of endpoint names: the two rows may describe different calls of one multicall.
    for name in incoming.function_name.split(", ").filter(|s| !s.is_empty()) {
        if !existing.function_name.split(", ").any(|n| n == name) {
            if !existing.function_name.is_empty() {
                existing.function_name.push_str(", ");
            }
            existing.function_name.push_str(name);
            changed = true;
        }
    }
    // A ZERO sender is a WS stub; a later real sender wins, otherwise first wins.
    if existing.sender == Felt::ZERO && incoming.sender != Felt::ZERO {
        existing.sender = incoming.sender;
        changed = true;
    }
    if existing.total_fee_fri == 0 && incoming.total_fee_fri > 0 {
        existing.total_fee_fri = incoming.total_fee_fri;
        changed = true;
    }
    if existing.timestamp == 0 && incoming.timestamp > 0 {
        existing.timestamp = incoming.timestamp;
        changed = true;
    }
    if existing.status == "?" && incoming.status != "?" {
        existing.status = incoming.status;
        changed = true;
    }
    if existing.nonce.is_none() && incoming.nonce.is_some() {
        existing.nonce = incoming.nonce;
        changed = true;
    }
    if existing.tip == 0 && incoming.tip > 0 {
        existing.tip = incoming.tip;
        changed = true;
    }
    if existing.inner_targets.is_empty() && !incoming.inner_targets.is_empty() {
        existing.inner_targets = incoming.inner_targets;
        changed = true;
    }
    changed
}

/// Deduplicate contract calls by transaction hash.
///
/// When multiple calls share the same `tx_hash` (e.g. a single transaction
/// calls the target contract several times from different endpoints), merge
/// them into one entry:
/// - Function names are joined with ", " (duplicates removed).
/// - Fee, status, block, and timestamp are taken from whichever entry has data.
/// - The sender from the first occurrence is kept, *except* when it is `ZERO`
///   (a WS stub that enrichment hasn't filled yet) — then a later real sender
///   wins. `merge_calls` keeps existing items first, so without this a stub
///   would permanently mask the enriched row for the same tx. Callers can still
///   overwrite a non-zero sender later (see `enrich_dune_calls`, which replaces
///   Dune's immediate `caller_address` with the real tx sender).
pub fn deduplicate_contract_calls(calls: Vec<ContractCallSummary>) -> Vec<ContractCallSummary> {
    use std::collections::HashMap;

    let mut seen: HashMap<Felt, usize> = HashMap::new();
    let mut result: Vec<ContractCallSummary> = Vec::new();

    for call in calls {
        if let Some(&idx) = seen.get(&call.tx_hash) {
            merge_call_into(&mut result[idx], call);
        } else {
            seen.insert(call.tx_hash, result.len());
            result.push(call);
        }
    }

    result
}

/// Address information for the address view.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SnAddressInfo {
    pub address: Felt,
    pub nonce: Felt,
    pub class_hash: Option<Felt>,
    pub recent_events: Vec<SnEvent>,
    pub token_balances: Vec<TokenBalance>,
}

/// A token balance for an address.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TokenBalance {
    pub token_address: Felt,
    pub token_name: String,
    pub balance_raw: Felt,
    pub decimals: u8,
}

/// One ERC-20 `Transfer` where the viewed address is `from` or `to`.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TokenTransfer {
    pub token: Felt,
    pub from: Felt,
    pub to: Felt,
    pub amount_low: u128,
    pub amount_high: u128,
    pub tx_hash: Felt,
    pub block_number: u64,
    #[serde(default)]
    pub tx_index: u64,
    /// Index within the transaction; `(tx_hash, event_index)` identifies the row.
    pub event_index: u64,
    #[serde(default)]
    pub timestamp: u64,
    /// Indexer-reported metadata; `None` for RPC/WS-sourced rows.
    #[serde(default)]
    pub symbol: Option<String>,
    #[serde(default)]
    pub decimals: Option<u8>,
    /// USD value at transfer time, as reported by the indexer.
    #[serde(default)]
    pub value_usd: Option<f64>,
}

impl TokenTransfer {
    pub fn key(&self) -> (Felt, u64) {
        (self.tx_hash, self.event_index)
    }

    /// Decode a `Transfer` event. Cairo 1 tokens key `from`/`to`; legacy Cairo 0
    /// tokens put `[from, to, low, high]` in data with the selector as the only key.
    pub fn from_event(event: &SnEvent, tx_index: u64) -> Option<Self> {
        let selector = Felt::from_hex(crate::data::pathfinder::TRANSFER_SELECTOR).ok()?;
        if event.keys.first() != Some(&selector) {
            return None;
        }
        let (from, to, low, high) = match event.keys.len() {
            n if n >= 3 => (
                event.keys[1],
                event.keys[2],
                *event.data.first()?,
                event.data.get(1).copied().unwrap_or(Felt::ZERO),
            ),
            1 if event.data.len() >= 3 => (
                event.data[0],
                event.data[1],
                event.data[2],
                event.data.get(3).copied().unwrap_or(Felt::ZERO),
            ),
            _ => return None,
        };
        Some(Self {
            token: event.from_address,
            from,
            to,
            amount_low: crate::utils::felt_to_u128(&low),
            amount_high: crate::utils::felt_to_u128(&high),
            tx_hash: event.transaction_hash,
            block_number: event.block_number,
            tx_index,
            event_index: event.event_index,
            timestamp: 0,
            symbol: None,
            decimals: None,
            value_usd: None,
        })
    }

    /// Newest-first ordering shared by the in-memory list and the cache.
    pub fn cmp_newest_first(a: &Self, b: &Self) -> std::cmp::Ordering {
        b.block_number
            .cmp(&a.block_number)
            .then(b.tx_index.cmp(&a.tx_index))
            .then(b.event_index.cmp(&a.event_index))
    }
}

/// A contract deployed with a given class hash (for the ClassInfo view).
#[derive(Debug, Clone)]
pub struct ClassContractEntry {
    pub address: Felt,
    pub block_number: u64,
}

/// Declaration info for a class hash (from PF+RPC or Dune fallback).
#[derive(Debug, Clone)]
pub struct ClassDeclareInfo {
    pub tx_hash: Felt,
    pub sender: Felt,
    pub block_number: u64,
    pub timestamp: u64,
}