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
pub mod known_addresses;
pub mod user_labels;
pub mod viewing_keys;

use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::RwLock;

use starknet::core::types::Felt;
use tracing::info;

use crate::decode::privacy_crypto::types::SecretFelt;
use crate::error::Result;
use known_addresses::{KnownAddress, load_known_addresses};
use user_labels::{UserLabel, UserTxLabel, load_user_labels};
use viewing_keys::{ViewingKey, load_viewing_keys};

/// What kind of on-chain entity a search entry/result points at. Drives
/// downstream navigation (address view vs transaction detail view).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntryKind {
    Address,
    Transaction,
}

/// Unified address + tx-hash registry over user labels + known addresses.
/// User labels take priority over known addresses.
/// Pre-builds a search index for fast prefix/substring matching.
pub struct AddressRegistry {
    /// User address labels (highest priority)
    user: Vec<UserLabel>,
    /// User transaction labels
    tx_labels: Vec<UserTxLabel>,
    /// Known addresses (curated)
    known: Vec<KnownAddress>,
    /// Privacy-pool viewing keys keyed by user address. Deliberately NOT
    /// in the search index — secrets shouldn't surface in autocomplete.
    viewing_keys: Vec<ViewingKey>,
    // Point-lookup indexes into the Vecs above; first occurrence wins.
    user_by_addr: HashMap<Felt, usize>,
    known_by_addr: HashMap<Felt, usize>,
    tx_by_hash: HashMap<Felt, usize>,
    viewing_key_by_user: HashMap<Felt, usize>,
    privacy: HashSet<Felt>,
    /// Search index: sorted entries for fast lookup.
    /// Behind RwLock so Voyager labels can be added at runtime.
    search_index: RwLock<Vec<SearchEntry>>,
}

#[derive(Debug, Clone)]
struct SearchEntry {
    name_lower: String,
    display_name: String,
    /// Address or tx hash, depending on `kind`.
    felt: Felt,
    hex_lower: String,
    is_user: bool,
    /// Lowercase tags for search matching (user labels only).
    tags_lower: Vec<String>,
    kind: EntryKind,
}

/// A search result returned to the UI.
#[derive(Debug, Clone)]
pub struct SearchResult {
    pub display: String,
    /// Address or tx hash, depending on `kind`.
    pub felt: Felt,
    pub is_user: bool,
    pub kind: EntryKind,
}

/// Metadata for a resolved address.
#[derive(Debug, Clone)]
pub struct AddressMeta {
    pub name: String,
    pub addr_type: String,
    pub decimals: Option<u8>,
    pub is_user: bool,
}

impl AddressRegistry {
    /// Load from user labels, viewing keys, and bundled known addresses.
    /// Returns `(registry, warnings)`. Warnings collect non-fatal issues
    /// from any of the input files (corrupt TOML etc.) so all of them
    /// can surface in the UI rather than the first one masking the rest.
    pub fn load(user_labels_path: &Path, viewing_keys_path: &Path) -> Result<(Self, Vec<String>)> {
        let (user, tx_labels, labels_warning) = load_user_labels(user_labels_path)?;
        let (viewing_keys, vk_warning) = load_viewing_keys(viewing_keys_path)?;
        let known = load_known_addresses()?;
        let mut warnings = Vec::new();
        if let Some(w) = labels_warning {
            warnings.push(w);
        }
        if let Some(w) = vk_warning {
            warnings.push(w);
        }

        let user_by_addr = index_by(&user, |u| u.address);
        let known_by_addr = index_by(&known, |k| k.address);
        let tx_by_hash = index_by(&tx_labels, |t| t.hash);
        let viewing_key_by_user = index_by(&viewing_keys, |vk| vk.user);
        let privacy: HashSet<Felt> = known
            .iter()
            .filter(|k| k.addr_type == "Privacy")
            .map(|k| k.address)
            .collect();

        let mut search_index = Vec::with_capacity(user.len() + tx_labels.len() + known.len());

        // User labels first (higher priority in search results)
        for label in &user {
            let hex = format!("{:#x}", label.address);
            search_index.push(SearchEntry {
                name_lower: label.name.to_lowercase(),
                display_name: label.name.clone(),
                felt: label.address,
                hex_lower: hex.to_lowercase(),
                is_user: true,
                tags_lower: label.tags.iter().map(|t| t.to_lowercase()).collect(),
                kind: EntryKind::Address,
            });
        }

        // User tx labels: same priority as address labels (the user added them)
        for label in &tx_labels {
            let hex = format!("{:#x}", label.hash);
            search_index.push(SearchEntry {
                name_lower: label.name.to_lowercase(),
                display_name: label.name.clone(),
                felt: label.hash,
                hex_lower: hex.to_lowercase(),
                is_user: true,
                tags_lower: Vec::new(),
                kind: EntryKind::Transaction,
            });
        }

        // Then known addresses
        for addr in &known {
            // Skip if user already has a label for this address
            if user_by_addr.contains_key(&addr.address) {
                continue;
            }
            let hex = format!("{:#x}", addr.address);
            search_index.push(SearchEntry {
                name_lower: addr.name.to_lowercase(),
                display_name: addr.name.clone(),
                felt: addr.address,
                hex_lower: hex.to_lowercase(),
                is_user: false,
                tags_lower: Vec::new(),
                kind: EntryKind::Address,
            });
        }

        // Sort by name for consistent ordering
        search_index.sort_by(|a, b| a.name_lower.cmp(&b.name_lower));

        info!(
            user = user.len(),
            tx_labels = tx_labels.len(),
            viewing_keys = viewing_keys.len(),
            known = known.len(),
            index = search_index.len(),
            "Address registry loaded"
        );

        Ok((
            Self {
                user,
                tx_labels,
                known,
                viewing_keys,
                user_by_addr,
                known_by_addr,
                tx_by_hash,
                viewing_key_by_user,
                privacy,
                search_index: RwLock::new(search_index),
            },
            warnings,
        ))
    }

    fn user_label(&self, address: &Felt) -> Option<&UserLabel> {
        self.user_by_addr.get(address).map(|&i| &self.user[i])
    }

    fn known_addr(&self, address: &Felt) -> Option<&KnownAddress> {
        self.known_by_addr.get(address).map(|&i| &self.known[i])
    }

    /// Look up a user-supplied private viewing key for an address.
    /// Returns None if the user has no viewing key registered for it.
    pub fn viewing_key(&self, user: &Felt) -> Option<&SecretFelt> {
        self.viewing_key_by_user
            .get(user)
            .map(|&i| &self.viewing_keys[i].private_key)
    }

    /// Iterate over all `(user_address, viewing_key)` pairs the user has
    /// configured. Iteration order is stable for the lifetime of the
    /// registry but is not guaranteed to match the on-disk ordering of
    /// `viewing_keys.toml` (the file is parsed via TOML's map type).
    pub fn iter_viewing_keys(&self) -> impl Iterator<Item = (Felt, &SecretFelt)> {
        self.viewing_keys
            .iter()
            .map(|vk| (vk.user, &vk.private_key))
    }

    /// Resolve an address to its display name. User labels take priority.
    pub fn resolve(&self, address: &Felt) -> Option<&str> {
        self.user_label(address)
            .map(|l| l.name.as_str())
            .or_else(|| self.known_addr(address).map(|k| k.name.as_str()))
    }

    /// Resolve a transaction hash to its user-supplied display name.
    pub fn resolve_tx(&self, hash: &Felt) -> Option<&str> {
        self.tx_by_hash
            .get(hash)
            .map(|&i| self.tx_labels[i].name.as_str())
    }

    /// Get metadata for an address.
    pub fn get_metadata(&self, address: &Felt) -> Option<AddressMeta> {
        if let Some(label) = self.user_label(address) {
            return Some(AddressMeta {
                name: label.name.clone(),
                addr_type: String::new(),
                decimals: None,
                is_user: true,
            });
        }
        if let Some(addr) = self.known_addr(address) {
            return Some(AddressMeta {
                name: addr.name.clone(),
                addr_type: addr.addr_type.clone(),
                decimals: addr.decimals,
                is_user: false,
            });
        }
        None
    }

    /// Get token decimals for an address (from known addresses).
    pub fn get_decimals(&self, address: &Felt) -> Option<u8> {
        self.known_addr(address).and_then(|k| k.decimals)
    }

    /// Search the registry by prefix or substring. Returns up to `limit` results.
    /// Must complete in <1ms for 10k entries.
    pub fn search(&self, query: &str, limit: usize) -> Vec<SearchResult> {
        if query.is_empty() {
            return Vec::new();
        }

        let index = self.search_index.read().unwrap();
        let query_lower = query.to_lowercase();
        let mut results = Vec::new();

        // Prefix matches first (highest relevance)
        for entry in index.iter() {
            if entry.name_lower.starts_with(&query_lower) {
                results.push(make_result(entry));
            }
            if results.len() >= limit {
                return results;
            }
        }

        // Then substring matches (name or tags)
        for entry in index.iter() {
            if results
                .iter()
                .any(|r| r.felt == entry.felt && r.kind == entry.kind)
            {
                continue;
            }
            let name_match = entry.name_lower.contains(&query_lower);
            let tag_match = entry
                .tags_lower
                .iter()
                .any(|t| t.starts_with(&query_lower) || t.contains(&query_lower));
            if name_match || tag_match {
                results.push(make_result(entry));
            }
            if results.len() >= limit {
                return results;
            }
        }

        // Hex prefix matches
        if query_lower.starts_with("0x") {
            for entry in index.iter() {
                if entry.hex_lower.starts_with(&query_lower)
                    && !results
                        .iter()
                        .any(|r| r.felt == entry.felt && r.kind == entry.kind)
                {
                    results.push(make_result(entry));
                }
                if results.len() >= limit {
                    return results;
                }
            }
        }

        results
    }

    /// Look up an entry by exact label name (case-insensitive). Returns the
    /// matched felt (address or tx hash). On a name collision between an
    /// address label and a tx label, the address wins (insertion order is
    /// preserved by the stable sort that builds the index).
    pub fn resolve_by_name(&self, name: &str) -> Option<Felt> {
        let lower = name.to_lowercase();
        let index = self.search_index.read().unwrap();
        index.iter().find(|e| e.name_lower == lower).map(|e| e.felt)
    }

    /// Add a Voyager-sourced label to the search index.
    /// Skips if the address already has an entry (user/known labels take priority).
    pub fn add_voyager_label(&self, address: Felt, name: &str) {
        let mut index = self.search_index.write().unwrap();
        // Don't duplicate if address already indexed (only check Address-kind
        // entries — a tx label sharing the same felt by accident is fine).
        if index
            .iter()
            .any(|e| e.kind == EntryKind::Address && e.felt == address)
        {
            return;
        }
        let hex = format!("{:#x}", address);
        let entry = SearchEntry {
            name_lower: name.to_lowercase(),
            display_name: name.to_string(),
            felt: address,
            hex_lower: hex.to_lowercase(),
            is_user: false,
            tags_lower: Vec::new(),
            kind: EntryKind::Address,
        };
        // Insert sorted by name
        let pos = index
            .binary_search_by(|e| e.name_lower.cmp(&entry.name_lower))
            .unwrap_or_else(|p| p);
        index.insert(pos, entry);
    }

    /// Check if an address is known (user or known).
    pub fn is_known(&self, address: &Felt) -> bool {
        self.resolve(address).is_some()
    }

    /// Every bundled known address tagged `type = "Privacy"`. Used by the
    /// UI color map to override the per-tx palette slot with the orange
    /// `PRIVACY_STYLE`, so the pool and its helper contracts visually
    /// stand out wherever they appear (Calls / Events / Trace / Privacy
    /// tabs and the address-info Calls tab). User labels can't claim this
    /// styling — it's reserved for the curated privacy bundle.
    pub fn privacy_addresses(&self) -> Vec<Felt> {
        self.known
            .iter()
            .filter(|k| k.addr_type == "Privacy")
            .map(|k| k.address)
            .collect()
    }

    /// True iff this address is in the curated privacy bundle. Independent
    /// of whether the user has shadowed it with their own label — the
    /// privacy classification comes from the bundled list and isn't
    /// something a user-label override can disclaim.
    pub fn is_privacy_address(&self, address: &Felt) -> bool {
        self.privacy.contains(address)
    }

    /// Format an address for display: label if known, truncated hex otherwise.
    pub fn format_address(&self, address: &Felt) -> String {
        if let Some(name) = self.resolve(address) {
            format!("[{}]", name)
        } else {
            let hex = format!("{:#x}", address);
            if hex.len() > 14 {
                format!("{}..{}", &hex[..6], &hex[hex.len() - 4..])
            } else {
                hex
            }
        }
    }

    /// Format an address showing both user and global labels when they differ.
    /// Returns e.g. "[My ETH] (ETH / ERC20)" or "[ETH]" or "0x49d..dc7"
    pub fn format_address_full(&self, address: &Felt) -> String {
        let user_name = self.user_label(address).map(|u| &u.name);
        let known = self.known_addr(address);

        match (user_name, known) {
            (Some(uname), Some(k)) if uname != &k.name => {
                if k.addr_type.is_empty() {
                    format!("[{}] ({})", uname, k.name)
                } else {
                    format!("[{}] ({} / {})", uname, k.name, k.addr_type)
                }
            }
            (Some(uname), Some(k)) if !k.addr_type.is_empty() => {
                format!("[{}] ({})", uname, k.addr_type)
            }
            (Some(uname), _) => format!("[{}]", uname),
            (None, Some(k)) => {
                if k.addr_type.is_empty() {
                    format!("[{}]", k.name)
                } else {
                    format!("[{}] ({})", k.name, k.addr_type)
                }
            }
            (None, None) => self.format_address(address),
        }
    }
}

/// Felt → position, first occurrence wins (same answer the linear `find`
/// calls this replaced would give).
fn index_by<T>(items: &[T], key: impl Fn(&T) -> Felt) -> HashMap<Felt, usize> {
    let mut map = HashMap::with_capacity(items.len());
    for (i, item) in items.iter().enumerate() {
        map.entry(key(item)).or_insert(i);
    }
    map
}

fn format_search_result(entry: &SearchEntry) -> String {
    let hex = &entry.hex_lower;
    let short = if hex.len() > 14 {
        format!("{}..{}", &hex[..6], &hex[hex.len() - 4..])
    } else {
        hex.clone()
    };
    let kind_tag = match entry.kind {
        EntryKind::Address => "",
        EntryKind::Transaction => " [tx]",
    };
    // The kind tag goes after the closing paren so `extract_name_from_display`
    // (which splits on " (") still recovers the bare label name for Tab-complete.
    format!("{} ({}){}", entry.display_name, short, kind_tag)
}

fn make_result(entry: &SearchEntry) -> SearchResult {
    SearchResult {
        display: format_search_result(entry),
        felt: entry.felt,
        is_user: entry.is_user,
        kind: entry.kind,
    }
}