solwatch 0.1.15

Real-data Solana memecoin auditor — rug/freeze/bundle scanner with a 0-100 risk score, plain-English flags, and a live dashboard. Sister tool to Hoodwatch.
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
//! Launch bundle / sniper detection — the TrenchBot-style signal. Walks the
//! mint's signature history back to its very first transaction (the launch),
//! parses the token-balance deltas of every transaction in the first slots,
//! and reports: % of supply sniped at launch, wallets buying in the exact
//! creation slot (a coordinated bundle), fresh-wallet ratio, the dev's own
//! initial allocation, and how much the snipers STILL hold right now.

use crate::chain::{pumpfun_bonding_curve_pda, SolClient};
use crate::config;
use crate::types::{Flag, Severity};
use futures::StreamExt;
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};

// How far back we'll walk signature history to reach the launch. Public RPC
// only pages newest-first (1000 sigs/page, one call each), so this bounds the
// reachable-launch horizon: 30 pages = 30k transactions since launch.
const MAX_PAGES: usize = 30;
const SNIPE_WINDOW_SLOTS: u64 = 12; // ~5 seconds of Solana time
const MAX_TX_FETCHES: usize = 150;
const FRESH_PROBE_TOP: usize = 8;

/// One launch-window buyer, with everything downstream passes need.
#[derive(Debug, Clone)]
pub struct BuyerInfo {
    pub owner: String,
    /// Token account(s) this owner received into (observed in the launch txs).
    pub token_accounts: Vec<String>,
    pub amount: u128,
    pub first_slot: u64,
    pub fresh: Option<bool>,
    /// Raw units still held NOW (None = probe unavailable, never assume 0).
    pub held: Option<u128>,
    /// Signatures of the launch-window txs this owner bought in.
    pub signatures: Vec<String>,
}

/// One fetched launch-window transaction, kept for the Jito/cluster passes.
#[derive(Debug, Clone)]
pub struct LaunchTx {
    pub signature: String,
    pub slot: u64,
    pub fee_payer: String,
    pub tx: Value,
}

/// Full result of the launch-window pass.
pub struct BundleAnalysis {
    pub section: Value,
    pub flags: Vec<Flag>,
    pub buyers: Vec<BuyerInfo>,
    pub launch_slot: Option<u64>,
    pub launch_txs: Vec<LaunchTx>,
    /// tx_parsed / total_in_window (1.0 = every launch-window tx was read).
    pub coverage: f64,
    /// The dev wallet actually used (Jupiter's, else the creation-tx fee payer).
    pub dev: Option<String>,
}

impl BundleAnalysis {
    fn skipped(note: String, flags: Vec<Flag>) -> Self {
        BundleAnalysis {
            section: json!({"analyzed": false, "note": note}),
            flags,
            buyers: vec![],
            launch_slot: None,
            launch_txs: vec![],
            coverage: 0.0,
            dev: None,
        }
    }
}

fn round2(n: f64) -> f64 {
    (n * 100.0).round() / 100.0
}

pub async fn analyze(
    client: &SolClient,
    mint: &str,
    supply: u128,
    pool_owners: &HashSet<String>,
    pool_addresses: &[String],
    dev: Option<&str>,
) -> BundleAnalysis {
    // Pools/curves must never count as "buyers". Three sources, unioned:
    //  1. the holder pass's classified pool owners (needs the RPC holder list),
    //  2. DexScreener pair addresses (needs DexScreener to have indexed),
    //  3. the DERIVED pump.fun bonding-curve PDA — pure math, ALWAYS available.
    // On a seconds-old token 1+2 are often both empty; without 3 the curve's
    // ~793M initial allocation counts as a buyer and pctSupplySniped is absurd.
    let mut pool_owners: HashSet<String> = pool_owners.clone();
    pool_owners.extend(pool_addresses.iter().cloned());
    if let Some(curve) = pumpfun_bonding_curve_pda(mint) {
        // The delta's `owner` field is the curve PDA itself; its associated
        // token account shows up as a raw account key — exclude both.
        for tp in [config::SPL_TOKEN, config::TOKEN_2022] {
            if let Some(ata) = crate::chain::ata_pda(&curve, mint, tp) {
                pool_owners.insert(ata);
            }
        }
        pool_owners.insert(curve);
    }
    let pool_owners = &pool_owners;

    // 1. Walk back to the first-ever signature (bounded). Public RPC only pages
    //    newest-first, so a mint buried under >MAX_PAGES×1000 txs is unreachable
    //    this way.
    let (mut oldest_page, mut truncated) = match client.oldest_signatures(mint, MAX_PAGES).await {
        Ok(r) => r,
        Err(e) => {
            return BundleAnalysis::skipped(
                format!("signature history unavailable: {e}"),
                vec![Flag::new("bundle_skip", Severity::Info, "Bundle scan skipped",
                    "Could not read the mint's transaction history (RPC limits) — launch snipe analysis was not performed.".into(), 0)],
            );
        }
    };
    // Anchor fallback: when the mint's own history is too deep, the pump.fun
    // bonding-curve PDA was created AT launch and carries a far shorter,
    // launch-anchored history (it stops accruing at graduation). Walking it
    // recovers the same launch window without the mint's noise. Derived offline
    // and free — on a non-pump.fun token its history is empty and we fall
    // through to the honest skip.
    let mut anchor = "mint";
    if truncated {
        if let Some(curve) = pumpfun_bonding_curve_pda(mint) {
            // Verify it's a REAL bonding curve for THIS mint before trusting it:
            // the derived PDA is a valid address for any mint, and a non-pump.fun
            // token's derived curve can carry unrelated activity that would forge
            // a bogus launch slot. A genuine curve account is owned by the
            // pump.fun program (persists through graduation).
            let is_real_curve = client
                .account_info(&curve)
                .await
                .ok()
                .and_then(|v| {
                    v.get("owner")
                        .and_then(|o| o.as_str())
                        .map(|o| o == config::PUMPFUN_PROGRAM)
                })
                .unwrap_or(false);
            if is_real_curve {
                if let Ok((page, curve_trunc)) = client.oldest_signatures(&curve, MAX_PAGES).await {
                    if !curve_trunc && !page.is_empty() {
                        oldest_page = page;
                        truncated = false;
                        anchor = "bonding_curve";
                    }
                }
            }
        }
    }
    if truncated {
        return BundleAnalysis::skipped(
            format!("launch unreachable: >{MAX_PAGES}k transactions since launch (public RPC pages history newest-first)"),
            vec![Flag::new("bundle_skip", Severity::Info, "Launch window unreachable",
                format!("The launch is buried under {MAX_PAGES},000+ transactions and public RPC can only walk history newest-first, so launch-window metrics (snipes, bundles, dev allocation, first-block buyers still holding) couldn't be read. A dedicated RPC (SOLWATCH_RPC_URL / HELIUS_API_KEY) reaches deeper, faster. Wallet-cluster analysis of CURRENT holders — funding links and transfers — still ran."), 0)],
        );
    }
    if oldest_page.is_empty() {
        return BundleAnalysis::skipped("no transaction history".into(), vec![]);
    }

    // Signatures come newest-first; the tail of the last page is the launch.
    let launch = oldest_page.last().unwrap().clone();
    let launch_slot = launch.slot;
    let window_end = launch_slot + SNIPE_WINDOW_SLOTS;
    let mut window: Vec<_> = oldest_page
        .iter()
        .filter(|s| s.slot <= window_end && s.err.is_none())
        .collect();
    window.reverse(); // oldest first — the creation tx is index 0
    let total_in_window = window.len();
    window.truncate(MAX_TX_FETCHES);

    // 2. Fetch + parse the launch-window transactions (the client's global
    //    limiter paces the actual RPC traffic).
    let window_owned: Vec<(String, u64)> = window
        .iter()
        .map(|s| (s.signature.clone(), s.slot))
        .collect();
    let fetched: Vec<Option<LaunchTx>> =
        futures::stream::iter(window_owned.into_iter().map(|(sig, slot)| async move {
            let tx = client.transaction(&sig).await.ok()?;
            let fee_payer = tx
                .pointer("/transaction/message/accountKeys/0/pubkey")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            Some(LaunchTx {
                signature: sig,
                slot,
                fee_payer,
                tx,
            })
        }))
        .buffer_unordered(8)
        .collect()
        .await;
    let launch_txs: Vec<LaunchTx> = fetched.into_iter().flatten().collect();
    let tx_parsed = launch_txs.len();
    let coverage = if total_in_window == 0 {
        0.0
    } else {
        tx_parsed as f64 / total_in_window as f64
    };

    // 3. Deterministic dev attribution: Jupiter's dev wins; otherwise the fee
    //    payer of THE creation transaction (the mint's earliest signature) —
    //    never "whichever launch tx happened to parse first".
    let creation_fee_payer = launch_txs
        .iter()
        .find(|t| t.signature == launch.signature)
        .map(|t| t.fee_payer.clone())
        .filter(|p| !p.is_empty());
    let dev_resolved: Option<String> = dev.map(String::from).or(creation_fee_payer.clone());

    // 4. Aggregate buyers (positive delta), excluding pools/curves; track the
    //    dev's own allocation separately.
    let mut buyers: HashMap<String, BuyerInfo> = HashMap::new();
    let mut dev_received: u128 = 0;
    let mut rows: Vec<(u64, String, u128)> = vec![]; // timeline for the dashboard
    for lt in &launch_txs {
        for d in mint_deltas_detailed(&lt.tx, mint) {
            if pool_owners.contains(&d.owner)
                || d.token_account
                    .as_deref()
                    .map(|ta| pool_owners.contains(ta))
                    .unwrap_or(false)
            {
                continue;
            }
            let is_dev = dev_resolved.as_deref() == Some(d.owner.as_str());
            if is_dev {
                dev_received += d.amount;
                rows.push((lt.slot, format!("{} (dev)", d.owner), d.amount));
                continue;
            }
            rows.push((lt.slot, d.owner.clone(), d.amount));
            let e = buyers.entry(d.owner.clone()).or_insert(BuyerInfo {
                owner: d.owner,
                token_accounts: vec![],
                amount: 0,
                first_slot: lt.slot,
                fresh: None,
                held: None,
                signatures: vec![],
            });
            e.amount += d.amount;
            e.first_slot = e.first_slot.min(lt.slot);
            if let Some(ta) = d.token_account {
                if !e.token_accounts.contains(&ta) {
                    e.token_accounts.push(ta);
                }
            }
            if !e.signatures.contains(&lt.signature) {
                e.signatures.push(lt.signature.clone());
            }
        }
    }

    // 4b. Classify buyer OWNER accounts (one batched call): a "buyer" whose
    //     owner account is owned by an AMM / launchpad / locker program is a
    //     POOL receiving inventory — the normal shape on non-pump.fun
    //     launchpads (Meteora DBC, Raydium LaunchLab, …) when the holder pass
    //     couldn't classify it (throttled RPC, unindexed pair). Without this,
    //     the pool's initial allocation reads as a 100% "snipe".
    let mut excluded_pools: Vec<(String, u128, String)> = vec![];
    {
        let labels: HashMap<&str, &str> = config::pool_program_labels()
            .into_iter()
            .chain(config::locker_program_labels())
            .collect();
        let owners: Vec<String> = {
            let mut v: Vec<String> = buyers.keys().cloned().collect();
            v.sort();
            v
        };
        for chunk in owners.chunks(100) {
            if let Ok(accts) = client.multiple_accounts(chunk).await {
                for (owner, acc) in chunk.iter().zip(accts.iter()) {
                    let prog = acc.get("owner").and_then(|o| o.as_str()).unwrap_or("");
                    if let Some(l) = labels.get(prog) {
                        if let Some(b) = buyers.remove(owner) {
                            excluded_pools.push((owner.clone(), b.amount, (*l).to_string()));
                        }
                    }
                }
            }
        }
        excluded_pools.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    }

    let pct = |v: u128| -> Option<f64> {
        v.saturating_mul(10000)
            .checked_div(supply)
            .map(|bp| round2(bp as f64 / 100.0))
    };

    let snipers = buyers.len();
    let same_slot = buyers
        .values()
        .filter(|b| b.first_slot == launch_slot)
        .count();
    let total_sniped: u128 = buyers.values().map(|b| b.amount).sum();
    let pct_sniped = pct(total_sniped);
    let pct_dev = pct(dev_received);

    // 5. Still-hold probe for EVERY buyer at once: getMultipleAccounts on the
    //    token accounts observed in the launch txs (batched, 2-3 calls total)
    //    — so "% snipers still hold" covers the SAME set as "% sniped", not
    //    just the top 8.
    let ta_owner: Vec<(String, String)> = buyers
        .values()
        .flat_map(|b| {
            b.token_accounts
                .iter()
                .map(|ta| (ta.clone(), b.owner.clone()))
        })
        .collect();
    let mut probe_ok = true;
    for chunk in ta_owner.chunks(100) {
        let addrs: Vec<String> = chunk.iter().map(|(ta, _)| ta.clone()).collect();
        match client.multiple_accounts(&addrs).await {
            Ok(accounts) => {
                for ((_, owner), acc) in chunk.iter().zip(accounts.iter()) {
                    let bal: u128 = acc
                        .pointer("/data/parsed/info/tokenAmount/amount")
                        .and_then(|v| v.as_str())
                        .and_then(|s| s.parse().ok())
                        .unwrap_or(0); // closed/absent account = sold out
                    if let Some(b) = buyers.get_mut(owner) {
                        *b.held.get_or_insert(0) += bal;
                    }
                }
            }
            Err(_) => probe_ok = false,
        }
    }

    // 6. Fresh-wallet probe for the top snipers (needs a signature call each).
    let mut ranked: Vec<&mut BuyerInfo> = buyers.values_mut().collect();
    ranked.sort_by(|a, b| b.amount.cmp(&a.amount).then(a.owner.cmp(&b.owner)));
    let take = ranked.len().min(FRESH_PROBE_TOP);
    let probes = ranked.iter().take(take).map(|b| {
        let owner = b.owner.clone();
        async move {
            client
                .signatures(&owner, 25, None)
                .await
                .ok()
                .map(|h| h.len() < 25)
        }
    });
    let probe_results = futures::future::join_all(probes).await;
    let mut fresh_count = 0usize;
    for (b, fresh) in ranked.iter_mut().take(take).zip(probe_results) {
        b.fresh = fresh;
        if fresh == Some(true) {
            fresh_count += 1;
        }
    }
    let fresh_ratio = (take > 0).then(|| round2(fresh_count as f64 / take as f64));
    let still_held: Option<u128> = if probe_ok {
        Some(ranked.iter().map(|b| b.held.unwrap_or(0)).sum())
    } else {
        None
    };
    let pct_held = still_held.and_then(pct);

    // 7. Flags. Confidence first: a partial parse means pctSupplySniped is a
    //    FLOOR — say so instead of presenting it as the full picture.
    let mut flags = vec![];
    let full_coverage = tx_parsed == total_in_window && total_in_window > 0;
    if !full_coverage && total_in_window > 0 {
        let cov_pct = (coverage * 100.0).round();
        flags.push(Flag::new(
            "snipe_coverage",
            Severity::Info,
            "Launch-window coverage is partial",
            format!(
                "Only {tx_parsed} of {total_in_window} launch-window transactions were parsed ({cov_pct}%) — the sniped-supply number is a FLOOR, the real figure may be higher."
            ),
            0,
        ));
    }
    let held_note = match pct_held {
        Some(h) => format!(" (snipers still hold ~{h}%)."),
        None => " (still-holding probe unavailable — assume they still hold).".into(),
    };
    if let Some(ps) = pct_sniped {
        let floor = if full_coverage { "" } else { " at least" };
        let still_heavy = pct_held.map(|h| h >= 10.0).unwrap_or(true);
        if ps >= 40.0 {
            flags.push(Flag::new(
                "heavy_bundle",
                if still_heavy {
                    Severity::Danger
                } else {
                    Severity::Warning
                },
                "Heavy launch sniping",
                format!(
                    "{}{ps}% of the supply was bought by {snipers} wallets within ~{SNIPE_WINDOW_SLOTS} slots of launch{held_note}",
                    if floor.is_empty() { "" } else { "At least " }
                ),
                if still_heavy { 25 } else { 12 },
            ));
        } else if ps >= 15.0 {
            flags.push(Flag::new(
                "bundle",
                Severity::Warning,
                "Notable launch sniping",
                format!(
                    "{}{ps}% of the supply was sniped at launch by {snipers} wallets{held_note}",
                    if floor.is_empty() { "" } else { "At least " }
                ),
                if still_heavy { 12 } else { 6 },
            ));
        } else if full_coverage {
            flags.push(Flag::new(
                "low_snipe",
                Severity::Good,
                "Low launch sniping",
                format!("Only {ps}% of the supply was sniped at launch."),
                0,
            ));
        } else {
            flags.push(Flag::new(
                "low_snipe",
                Severity::Info,
                "Low observed launch sniping",
                format!("{ps}% of the supply sniped in the transactions we could parse — coverage was partial, so this is a floor, not a clean bill."),
                0,
            ));
        }
    }
    if same_slot >= 4 {
        flags.push(Flag::new(
            "same_slot_bundle",
            Severity::Warning,
            "Same-slot buy bundle",
            format!("{same_slot} wallets bought in the exact creation slot — a coordinated (likely dev-run) bundle."),
            10,
        ));
    }
    if let Some(fr) = fresh_ratio {
        if fr >= 0.6 && snipers >= 4 {
            flags.push(Flag::new(
                "fresh_snipers",
                Severity::Warning,
                "Fresh-wallet snipers",
                format!(
                    "{}% of the top snipers are brand-new wallets — manufactured demand, not real buyers.",
                    (fr * 100.0).round()
                ),
                8,
            ));
        }
    }
    if let Some(pd) = pct_dev {
        if pd >= 20.0 {
            flags.push(Flag::new(
                "dev_allocation",
                Severity::Danger,
                "Dev took a huge launch allocation",
                format!("The creator received {pd}% of the supply in the launch window."),
                15,
            ));
        } else if pd >= 5.0 {
            flags.push(Flag::new(
                "dev_allocation",
                Severity::Warning,
                "Dev bought at launch",
                format!("The creator received {pd}% of the supply in the launch window."),
                6,
            ));
        }
    }

    let top_snipers: Vec<_> = ranked
        .iter()
        .take(FRESH_PROBE_TOP)
        .map(|b| {
            json!({
                "owner": b.owner,
                "pct": pct(b.amount).unwrap_or(0.0),
                "heldPct": b.held.and_then(pct),
                "sameSlot": b.first_slot == launch_slot,
                "freshWallet": b.fresh,
            })
        })
        .collect();
    let excluded_owners: HashSet<&str> =
        excluded_pools.iter().map(|(o, _, _)| o.as_str()).collect();
    rows.retain(|(_, owner, _)| !excluded_owners.contains(owner.as_str()));
    rows.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
    let timeline: Vec<_> = rows
        .iter()
        .map(|(slot, owner, amount)| {
            json!({"slotOffset": slot - launch_slot, "owner": owner, "pct": pct(*amount).unwrap_or(0.0)})
        })
        .collect();

    let section = json!({
        "analyzed": true,
        "launchAnchor": anchor,
        "launchSlot": launch_slot,
        "launchTime": launch.block_time,
        "snipers": snipers,
        "sameSlotBuyers": same_slot,
        "pctSupplySniped": pct_sniped,
        "pctSnipersStillHold": pct_held,
        "pctDevAllocation": pct_dev,
        "freshWalletRatio": fresh_ratio,
        "coverage": round2(coverage),
        "topSnipers": top_snipers,
        "excludedPools": excluded_pools.iter().map(|(o, a, l)| json!({
            "owner": o, "pct": pct(*a), "label": l,
        })).collect::<Vec<_>>(),
        "timeline": timeline,
        "note": format!(
            "Parsed {tx_parsed}/{total_in_window} transactions in slots {launch_slot}{window_end}{}. Still-hold covers ALL parsed buyers, not just the top few.",
            if anchor == "bonding_curve" {
                " (launch reached via the pump.fun bonding-curve — the mint's own history was too deep to page)"
            } else {
                ""
            }
        ),
    });
    let buyers_out: Vec<BuyerInfo> = {
        let mut v: Vec<BuyerInfo> = buyers.into_values().collect();
        v.sort_by(|a, b| b.amount.cmp(&a.amount).then(a.owner.cmp(&b.owner)));
        v
    };
    BundleAnalysis {
        section,
        flags,
        buyers: buyers_out,
        launch_slot: Some(launch_slot),
        launch_txs,
        coverage,
        dev: dev_resolved,
    }
}

/// One owner's positive balance change of `mint` in one parsed transaction.
#[derive(Debug, Clone)]
pub struct MintDelta {
    pub owner: String,
    /// The receiving token-account address (resolved via accountIndex).
    pub token_account: Option<String>,
    pub amount: u128,
}

/// Per-owner positive balance delta of `mint` in one parsed transaction, with
/// the receiving token account. Public for the unit tests — they must exercise
/// THIS decoder, not a reimplementation.
pub fn mint_deltas_detailed(tx: &Value, mint: &str) -> Vec<MintDelta> {
    let keys: Vec<String> = tx
        .pointer("/transaction/message/accountKeys")
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|k| k.get("pubkey").and_then(|p| p.as_str()).map(String::from))
                .collect()
        })
        .unwrap_or_default();
    // owner -> (balance, token_accounts touched)
    let read = |key: &str| -> HashMap<String, (u128, Vec<String>)> {
        let mut m: HashMap<String, (u128, Vec<String>)> = HashMap::new();
        if let Some(list) = tx
            .pointer(&format!("/meta/{key}"))
            .and_then(|v| v.as_array())
        {
            for b in list {
                if b.get("mint").and_then(|v| v.as_str()) != Some(mint) {
                    continue;
                }
                let Some(owner) = b.get("owner").and_then(|v| v.as_str()) else {
                    continue;
                };
                let amt: u128 = b
                    .pointer("/uiTokenAmount/amount")
                    .and_then(|v| v.as_str())
                    .and_then(|s| s.parse().ok())
                    .unwrap_or(0);
                let ta = b
                    .get("accountIndex")
                    .and_then(|v| v.as_u64())
                    .and_then(|i| keys.get(i as usize))
                    .cloned();
                let e = m.entry(owner.to_string()).or_insert((0, vec![]));
                e.0 += amt;
                if let Some(ta) = ta {
                    if !e.1.contains(&ta) {
                        e.1.push(ta);
                    }
                }
            }
        }
        m
    };
    let pre = read("preTokenBalances");
    let post = read("postTokenBalances");
    let mut out = vec![];
    for (owner, (after, tas)) in post {
        let before = pre.get(&owner).map(|(b, _)| *b).unwrap_or(0);
        if after > before {
            out.push(MintDelta {
                owner,
                token_account: tas.first().cloned(),
                amount: after - before,
            });
        }
    }
    out.sort_by(|a, b| a.owner.cmp(&b.owner));
    out
}

/// Back-compat thin wrapper: per-owner positive deltas as (owner, amount).
pub fn mint_deltas(tx: &Value, mint: &str) -> Vec<(String, u128)> {
    mint_deltas_detailed(tx, mint)
        .into_iter()
        .map(|d| (d.owner, d.amount))
        .collect()
}