solwatch 0.1.18

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
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
//! Offline unit tests — no network. They exercise the real decoders and the
//! scoring model with fixtures shaped exactly like live RPC responses.

use serde_json::json;
use solwatch::chain::{is_pubkey, metadata_pda, parse_metaplex};
use solwatch::checks::bundles::mint_deltas;
use solwatch::checks::holders::vault_reserve_owners;
use solwatch::types::{score_flags, Flag, Severity, Verdict};

const BONK: &str = "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263";

/// A launchpad reserve vault (the token account holding the undistributed
/// curve supply) must be recognized when its pubkey appears inside the pool
/// account — so it's excluded from concentration instead of read as a whale.
/// Regression for the live 2026-07-18 Meteora DBC false positive (the pool
/// reserve posted as a 92% "single whale" + a fake 94% transfer-ring cluster).
#[test]
fn pool_reserve_vault_is_detected() {
    let reserve_ta = "7h8WiEhfhgcZC3ThcBBWTEL6dh6NyLmMad5aXCbs1nji";
    let reserve_owner = "FhVo3mqL8PW5pH5U2CN4XE33DokiyZnUwuGpH2hmHLuM";
    let real_holder_ta = "Dbpr8Sa1wVSLu6szQsyE9nMN2fcms9LdLk4tRTv1C2Po";
    let real_holder_owner = "3xEGYaVoEjfWjwMo5WbYscu8q9KcDqvQLmUC6ewzQBSS";

    // A synthetic pool blob: padding + the reserve's token-account pubkey + more
    // padding — exactly how a DBC/AMM pool account embeds its base vault.
    let ta_bytes = bs58::decode(reserve_ta).into_vec().unwrap();
    let mut blob = vec![0u8; 168];
    blob.extend_from_slice(&ta_bytes);
    blob.extend_from_slice(&[9u8; 64]);

    let accounts = vec![
        (reserve_ta.to_string(), reserve_owner.to_string()),
        (real_holder_ta.to_string(), real_holder_owner.to_string()),
    ];
    let vaults = vault_reserve_owners(&[blob], &accounts);
    assert!(
        vaults.contains(reserve_owner),
        "the reserve owner must be flagged as a pool vault"
    );
    assert!(
        !vaults.contains(real_holder_owner),
        "a real holder whose token account is NOT in any pool must never be excluded"
    );
}

/// No pools, or a pool that doesn't reference any of our accounts, excludes
/// nothing — the matcher never invents a vault.
#[test]
fn no_false_vault_exclusions() {
    let accounts = vec![(
        "7h8WiEhfhgcZC3ThcBBWTEL6dh6NyLmMad5aXCbs1nji".to_string(),
        "FhVo3mqL8PW5pH5U2CN4XE33DokiyZnUwuGpH2hmHLuM".to_string(),
    )];
    assert!(vault_reserve_owners(&[], &accounts).is_empty());
    assert!(vault_reserve_owners(&[vec![7u8; 300]], &accounts).is_empty());
}

#[test]
fn score_clean_token() {
    let flags = vec![
        Flag::new("mint_authority", Severity::Good, "ok", "".into(), 0),
        Flag::new("freeze_authority", Severity::Good, "ok", "".into(), 0),
    ];
    let (score, verdict) = score_flags(&flags, true);
    assert_eq!(score, 100);
    assert_eq!(verdict, Verdict::LowRisk);
}

#[test]
fn score_honeypot_hard_caps_at_5() {
    let flags = vec![Flag::new(
        "non_transferable",
        Severity::Critical,
        "honeypot",
        "".into(),
        60,
    )
    .hard()];
    let (score, verdict) = score_flags(&flags, true);
    assert!(score <= 5, "critical hard fail must cap at 5, got {score}");
    assert_eq!(verdict, Verdict::Avoid);
}

#[test]
fn score_non_critical_hard_caps_at_20() {
    let flags = vec![Flag::new("no_liquidity", Severity::Danger, "x", "".into(), 25).hard()];
    let (score, _) = score_flags(&flags, true);
    assert!(score <= 20);
}

#[test]
fn score_unresolved_token_is_unknown() {
    let (score, verdict) = score_flags(&[], false);
    assert_eq!(score, 0);
    assert_eq!(verdict, Verdict::Unknown);
}

#[test]
fn pubkey_validation() {
    assert!(is_pubkey(BONK));
    assert!(is_pubkey("So11111111111111111111111111111111111111112"));
    assert!(!is_pubkey("0x8e62F281f282686fCa6dCB39288069a93fC23F1c")); // EVM
    assert!(!is_pubkey("notbase58!!!"));
    assert!(!is_pubkey(""));
}

#[test]
fn metadata_pda_derivation() {
    // Verified live 2026-07-13: Metaplex metadata PDA for the BONK mint.
    let pda = metadata_pda(BONK).expect("pda derives");
    assert!(is_pubkey(&pda));
    // Deterministic: same input, same PDA.
    assert_eq!(pda, metadata_pda(BONK).unwrap());
}

#[test]
fn metaplex_parser_roundtrip() {
    // Hand-built borsh Metadata: key, update_auth(32), mint(32),
    // name/symbol/uri (u32-len strings, null-padded), sfbp, no creators,
    // primary_sale=0, is_mutable=1.
    let mut b: Vec<u8> = vec![4];
    b.extend([7u8; 32]); // update authority
    b.extend([9u8; 32]); // mint
    for (s, cap) in [("Bonk", 32), ("BONK", 10), ("https://x/meta.json", 200)] {
        b.extend((cap as u32).to_le_bytes());
        let mut raw = s.as_bytes().to_vec();
        raw.resize(cap, 0);
        b.extend(raw);
    }
    b.extend(100u16.to_le_bytes()); // seller fee bps
    b.push(0); // no creators
    b.push(0); // primary sale
    b.push(1); // is_mutable
    let m = parse_metaplex(&b).expect("parses");
    assert_eq!(m.name, "Bonk");
    assert_eq!(m.symbol, "BONK");
    assert_eq!(m.uri, "https://x/meta.json");
    assert!(m.is_mutable);
    assert_eq!(m.update_authority, bs58_of([7u8; 32]));
}

#[test]
fn metaplex_parser_rejects_garbage() {
    assert!(parse_metaplex(&[]).is_none());
    assert!(parse_metaplex(&[4u8; 40]).is_none());
    // absurd string length must bail, not allocate
    let mut b: Vec<u8> = vec![4];
    b.extend([0u8; 64]);
    b.extend(u32::MAX.to_le_bytes());
    assert!(parse_metaplex(&b).is_none());
}

fn bs58_of(b: [u8; 32]) -> String {
    bs58::encode(b).into_string()
}

#[test]
fn mint_deltas_from_parsed_tx() {
    let mint = "M1nt111111111111111111111111111111111111111";
    let tx = json!({
        "meta": {
            "preTokenBalances": [
                {"accountIndex": 3, "mint": mint, "owner": "curve", "uiTokenAmount": {"amount": "1000"}},
                {"accountIndex": 4, "mint": "OTHER", "owner": "alice", "uiTokenAmount": {"amount": "5"}}
            ],
            "postTokenBalances": [
                {"accountIndex": 3, "mint": mint, "owner": "curve", "uiTokenAmount": {"amount": "400"}},
                {"accountIndex": 5, "mint": mint, "owner": "alice", "uiTokenAmount": {"amount": "600"}},
                {"accountIndex": 4, "mint": "OTHER", "owner": "alice", "uiTokenAmount": {"amount": "9"}}
            ]
        }
    });
    let mut d = mint_deltas(&tx, mint);
    d.sort();
    // alice gained 600 of OUR mint (the OTHER-mint gain is ignored);
    // the curve LOST tokens so it must not appear.
    assert_eq!(d, vec![("alice".to_string(), 600u128)]);
}

#[test]
fn tweet_is_bounded() {
    use solwatch::report::render_tweet;
    use solwatch::types::{AuditResult, TokenMeta};
    let r = AuditResult {
        address: BONK.into(),
        chain: "solana",
        scanned_at: "2026-07-13T00:00:00Z".into(),
        token: TokenMeta {
            symbol: Some("X".repeat(120)),
            market_cap_usd: Some(123456789012345.0),
            ..Default::default()
        },
        score: 3,
        verdict: Verdict::Avoid,
        flags: vec![
            Flag::new(
                "a",
                Severity::Critical,
                &"very long flag title ".repeat(10),
                "d".into(),
                60,
            ),
            Flag::new(
                "b",
                Severity::Danger,
                &"another long one ".repeat(10),
                "d".into(),
                30,
            ),
        ],
        sections: json!({}),
        warnings: vec![],
        coverage_gaps: vec![],
        rokha_url: None,
        rokha_app: serde_json::Value::Null,
    };
    assert!(render_tweet(&r).chars().count() <= 280);
    // The APP-view block + HTML artifact build from any result without panic.
    let app = solwatch::report::render_rokha_app(&r);
    assert_eq!(app["verdict"], "avoid");
    let html = solwatch::report::render_html(&r);
    assert!(html.contains("__AUDIT"));
    assert!(!html.contains("</script><script>alert")); // json stays inert

    // write_report: .md + .json + index always; .html only on opt-in.
    let dir = std::env::temp_dir().join(format!("solwatch-test-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let md = solwatch::report::write_report(&r, &dir, false).unwrap();
    let base = md.strip_suffix(".md").unwrap();
    assert!(dir.join(&md).exists());
    assert!(dir.join(format!("{base}.json")).exists());
    assert!(dir.join("index.json").exists());
    assert!(
        !dir.join(format!("{base}.html")).exists(),
        ".html written without --report-html"
    );
    let md = solwatch::report::write_report(&r, &dir, true).unwrap();
    let base = md.strip_suffix(".md").unwrap();
    assert!(dir.join(format!("{base}.html")).exists());
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn raydium_shared_vault_authorities_excluded() {
    // Both are real Raydium vault authorities that are NOT program-owned
    // (AMM v4 authority has no account; CPMM authority is system-owned), so
    // they must be excluded by ADDRESS or a Raydium pool ranks as a whale.
    let auth: std::collections::HashMap<&str, &str> = solwatch::config::shared_pool_authorities()
        .into_iter()
        .collect();
    // The canonical Raydium Authority V4 ends in `...pge4j1` — an earlier
    // constant dropped the trailing `1`, so it never matched a live pool.
    assert!(auth.contains_key("5Q544fKrFoe6tsEbD7S8EmxGTJYAKtTVhAW5Q5pge4j1"));
    assert!(auth.contains_key("GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL"));
}

// ---- New data-quality guards (mint-level honeypot levers + tweet honesty) ----

fn t2022_mint(extensions: Vec<serde_json::Value>) -> solwatch::chain::MintInfo {
    solwatch::chain::MintInfo {
        program: solwatch::config::TOKEN_2022.into(),
        decimals: 6,
        supply: 1_000_000,
        supply_raw: "1000000".into(),
        mint_authority: None,
        freeze_authority: None,
        extensions,
    }
}

#[test]
fn pausable_authority_is_hard_danger() {
    let m = t2022_mint(vec![json!({
        "extension": "pausableConfig",
        "state": {"authority": "Pause111111111111111111111111111111111111111", "paused": false}
    })]);
    let a = solwatch::checks::mint::analyze(&m, None);
    let f = a
        .flags
        .iter()
        .find(|f| f.id == "pausable")
        .expect("pausable flag");
    assert_eq!(f.severity, Severity::Danger);
    assert!(
        f.hard_fail,
        "a live pause authority must hard-cap the score"
    );
}

#[test]
fn paused_now_is_critical_honeypot() {
    let m = t2022_mint(vec![json!({
        "extension": "pausableConfig",
        "state": {"authority": "Pause111111111111111111111111111111111111111", "paused": true}
    })]);
    let a = solwatch::checks::mint::analyze(&m, None);
    let f = a
        .flags
        .iter()
        .find(|f| f.id == "paused")
        .expect("paused flag");
    assert_eq!(f.severity, Severity::Critical);
    assert!(f.hard_fail);
    // No separate "pausable" flag when it's already paused.
    assert!(a.flags.iter().all(|f| f.id != "pausable"));
}

#[test]
fn revoked_pause_authority_is_silent() {
    let m = t2022_mint(vec![json!({
        "extension": "pausableConfig",
        "state": {"authority": serde_json::Value::Null, "paused": false}
    })]);
    let a = solwatch::checks::mint::analyze(&m, None);
    assert!(a
        .flags
        .iter()
        .all(|f| f.id != "pausable" && f.id != "paused"));
}

#[test]
fn zero_fee_with_live_authority_flags() {
    let m = t2022_mint(vec![json!({
        "extension": "transferFeeConfig",
        "state": {
            "transferFeeConfigAuthority": "Fee1111111111111111111111111111111111111111",
            "newerTransferFee": {"transferFeeBasisPoints": 0}
        }
    })]);
    let a = solwatch::checks::mint::analyze(&m, None);
    assert!(
        a.flags
            .iter()
            .any(|f| f.id == "transfer_fee_authority" && f.severity == Severity::Warning),
        "0% fee with a live authority must warn it can be switched on"
    );
    // The fee itself is 0 → no active-fee flag.
    assert!(a.flags.iter().all(|f| f.id != "transfer_fee"));
}

#[test]
fn zero_fee_revoked_authority_is_silent() {
    let m = t2022_mint(vec![json!({
        "extension": "transferFeeConfig",
        "state": {
            "transferFeeConfigAuthority": serde_json::Value::Null,
            "newerTransferFee": {"transferFeeBasisPoints": 0}
        }
    })]);
    let a = solwatch::checks::mint::analyze(&m, None);
    assert!(a.flags.iter().all(|f| f.id != "transfer_fee_authority"));
}

#[test]
fn tweet_marks_partial_scan_on_reassuring_verdict() {
    use solwatch::report::render_tweet;
    use solwatch::types::{AuditResult, TokenMeta};
    let mk = |verdict, coverage: &str| AuditResult {
        address: BONK.into(),
        chain: "solana",
        scanned_at: "2026-07-16T00:00:00Z".into(),
        token: TokenMeta {
            symbol: Some("PONS".into()),
            market_cap_usd: Some(500_000.0),
            ..Default::default()
        },
        score: 85,
        verdict,
        flags: vec![],
        sections: json!({"cluster": {"scope": {"coverage": coverage}}}),
        warnings: vec![],
        coverage_gaps: vec![],
        rokha_url: None,
        rokha_app: serde_json::Value::Null,
    };
    // Reassuring verdict + non-full coverage → the caveat must ride the tweet.
    assert!(render_tweet(&mk(Verdict::LowRisk, "partial")).contains("partial scan"));
    // Full coverage → no caveat.
    assert!(!render_tweet(&mk(Verdict::LowRisk, "full")).contains("partial scan"));
    // A RISK verdict on a partial scan must ALSO carry the caveat. This
    // assertion was previously inverted ("a risk verdict already warns"), which
    // conflated two different things: a risk verdict warns about RISK, not
    // about COVERAGE. Tweet compression keeps only `flag.title` and drops the
    // "at least" / "treat this as a floor" qualifiers that live in
    // `flag.detail` — so an ACCUSATION made on partial data needs the hedge
    // more than a reassurance does. That was the reputational landmine.
    assert!(render_tweet(&mk(Verdict::Avoid, "partial")).contains("partial scan"));
    // A gap recorded by ANY pass (e.g. --fast) marks the tweet even when the
    // cluster pass itself reported full coverage.
    let mut fast = mk(Verdict::LowRisk, "full");
    fast.coverage_gaps = vec!["launch-window + cluster passes skipped (--fast)".into()];
    assert!(render_tweet(&fast).contains("partial scan"));
}

#[test]
fn coverage_ceiling_downgrades_low_risk_to_fair() {
    use solwatch::types::verdict_from_score;
    // A clean token scores high; a blind scan caps the score at 79 → FAIR,
    // so an un-verifiable concentration read can never post as LOW RISK.
    assert_eq!(verdict_from_score(88), Verdict::LowRisk);
    assert_eq!(verdict_from_score(79), Verdict::Fair);
    // Risk bands are untouched by the mapping.
    assert_eq!(verdict_from_score(35), Verdict::HighRisk);
    assert_eq!(verdict_from_score(5), Verdict::Avoid);
}

// ---------------------------------------------------------------------------
// Accuracy-audit regressions (2026-07-19). Each test pins a path that could
// publish a claim the evidence did not support — in EITHER direction: a false
// accusation against a named wallet, or a false all-clear on a honeypot.
// ---------------------------------------------------------------------------

#[test]
fn undecodable_extension_is_never_silent() {
    // An extension the RPC build can't parse arrives as "unparseableExtension".
    // Every check is a lookup by extension NAME, so silence here would render a
    // live pause authority as an absent one — a clean bill on a honeypot.
    let m = t2022_mint(vec![json!({"extension": "unparseableExtension"})]);
    let a = solwatch::checks::mint::analyze(&m, None);
    assert!(
        a.flags.iter().any(|f| f.id == "extension_undecodable"),
        "an undecodable Token-2022 extension must raise a flag — unknown powers are not absent powers"
    );
}

#[test]
fn revoked_permanent_delegate_is_not_a_honeypot() {
    // The extension survives revocation and the delegate field goes null. The
    // old `unwrap_or("?")` fired a 60-weight honeypot hard-fail naming the
    // delegate as "?" on a token whose dev had correctly revoked it.
    let revoked = t2022_mint(vec![json!({
        "extension": "permanentDelegate",
        "state": {"delegate": serde_json::Value::Null}
    })]);
    let a = solwatch::checks::mint::analyze(&revoked, None);
    assert!(
        a.flags.iter().all(|f| f.id != "permanent_delegate"),
        "a revoked permanent delegate must not be flagged as an active seize power"
    );

    // An ACTIVE delegate must still hard-fail.
    let active = t2022_mint(vec![json!({
        "extension": "permanentDelegate",
        "state": {"delegate": "De1e9ate11111111111111111111111111111111111"}
    })]);
    let a2 = solwatch::checks::mint::analyze(&active, None);
    let f = a2
        .flags
        .iter()
        .find(|f| f.id == "permanent_delegate")
        .expect("an active permanent delegate is a honeypot lever and must flag");
    assert!(f.hard_fail);
}

#[test]
fn scheduled_transfer_fee_reports_the_higher_rate() {
    // Token-2022 fee changes are epoch-scheduled: `newerTransferFee` only
    // applies from its epoch, so a dev can set 50% now and schedule 0% later.
    // Preferring "newer" unconditionally read 0 bps and published an 8-point
    // advisory on a 50% sell tax. We take the max — fail toward warning.
    let m = t2022_mint(vec![json!({
        "extension": "transferFeeConfig",
        "state": {
            "newerTransferFee": {"transferFeeBasisPoints": 0, "epoch": 999},
            "olderTransferFee": {"transferFeeBasisPoints": 5000, "epoch": 1},
            "transferFeeConfigAuthority": serde_json::Value::Null
        }
    })]);
    let a = solwatch::checks::mint::analyze(&m, None);
    let f = a
        .flags
        .iter()
        .find(|f| f.id == "transfer_fee")
        .expect("a 50% active fee must be flagged even when a 0% change is scheduled");
    assert_eq!(f.severity, Severity::Critical);
    assert!(f.hard_fail);
    assert!(a.flags.iter().any(|f| f.id == "transfer_fee_scheduled"));
}

#[test]
fn coverage_accumulator_gates_the_verdict_cap() {
    use solwatch::types::Coverage;
    let mut cov = Coverage::new();
    assert!(!cov.is_blind(), "a fresh accumulator is not blind");

    // The --fast case: the old two-input derivation (holders + RPC pressure)
    // never saw this, so a bundled rug with a clean mint published LOW RISK
    // 100/100, byte-indistinguishable from a full clean audit.
    cov.degrade("launch-window bundle + wallet-cluster passes skipped (--fast)");
    assert!(cov.is_blind());
    assert!(cov.summary().contains("--fast"));

    // Gaps dedupe so a repeated failure doesn't spam the report.
    let before = cov.gaps().len();
    cov.degrade("launch-window bundle + wallet-cluster passes skipped (--fast)");
    assert_eq!(cov.gaps().len(), before);

    // And the cap maps through the same band logic.
    assert_eq!(solwatch::types::verdict_from_score(79), Verdict::Fair);
}

#[test]
fn unknown_verdict_publishes_no_score() {
    use solwatch::report::render_tweet;
    use solwatch::types::{AuditResult, TokenMeta};
    // UNKNOWN means nothing could be read. "0/100" beside it reads as a
    // catastrophic score rather than an absent one.
    let r = AuditResult {
        address: BONK.into(),
        chain: "solana",
        scanned_at: "2026-07-19T00:00:00Z".into(),
        token: TokenMeta::default(),
        score: 0,
        verdict: Verdict::Unknown,
        flags: vec![],
        sections: json!({}),
        warnings: vec![],
        coverage_gaps: vec!["mint account unresolved — no checks could run".into()],
        rokha_url: None,
        rokha_app: serde_json::Value::Null,
    };
    let t = render_tweet(&r);
    assert!(
        !t.contains("0/100"),
        "UNKNOWN must not publish a 0/100 score: {t}"
    );
}

#[test]
fn rokha_app_carries_coverage() {
    use solwatch::types::{AuditResult, TokenMeta};
    // The APP rail + public rig product pages render this block. It previously
    // carried no coverage and no warnings, so the most-seen surface was the
    // least disclosed — a degraded run showed a clean score card.
    let r = AuditResult {
        address: BONK.into(),
        chain: "solana",
        scanned_at: "2026-07-19T00:00:00Z".into(),
        token: TokenMeta {
            symbol: Some("BONK".into()),
            ..Default::default()
        },
        score: 79,
        verdict: Verdict::Fair,
        flags: vec![],
        sections: json!({}),
        warnings: vec!["jupiter: timeout".into()],
        coverage_gaps: vec!["live holder concentration unreadable".into()],
        rokha_url: None,
        rokha_app: serde_json::Value::Null,
    };
    let app = solwatch::report::render_rokha_app(&r);
    assert_eq!(app["coverage"], "partial");
    assert_eq!(
        app["coverageGaps"][0],
        "live holder concentration unreadable"
    );
    assert_eq!(app["warnings"][0], "jupiter: timeout");
}

#[test]
fn mispriced_pairs_are_dropped() {
    use solwatch::chain::dexscreener::{drop_mispriced_pairs, DexPair};
    // Reproduces the live 2026-07-19 JUP case: two Meteora /MET pairs quoted
    // JUP at ~$950 against a true ~$0.194 (~4,900x off). Summing them produced
    // $425M of phantom liquidity and a $6.7 TRILLION FDV printed next to a
    // $643M market cap in the same report.
    let mk = |price: &str, liq: f64| -> DexPair {
        serde_json::from_value(json!({
            "chainId": "solana",
            "dexId": "meteora",
            "pairAddress": format!("pair{price}"),
            "baseToken": {"address": "JUP", "symbol": "JUP", "name": "Jupiter"},
            "quoteToken": {"address": "Q", "symbol": "Q", "name": "Q"},
            "priceUsd": price,
            "liquidity": {"usd": liq},
        }))
        .expect("fixture parses")
    };

    let mut pairs = vec![
        mk("949.12", 369_384_475.0), // poisoned
        mk("952.99", 53_296_320.0),  // poisoned
        mk("0.1943", 840_227.0),     // real
        mk("0.1942", 319_783.0),     // real
        mk("0.1939", 138_845.0),     // real
    ];
    let (dropped, median) = drop_mispriced_pairs(&mut pairs);
    assert_eq!(dropped, 2, "both ~4,900x-off pairs must be discarded");
    assert_eq!(pairs.len(), 3);
    assert!(median.is_some_and(|m| (m - 0.1943).abs() < 0.01));
    let total: f64 = pairs.iter().map(solwatch::chain::dexscreener::liq).sum();
    assert!(
        total < 1_500_000.0,
        "liquidity must reflect the real pools only, got {total}"
    );

    // Normal cross-venue spread must NEVER be discarded — a few percent of
    // price difference between pools is ordinary market behaviour.
    let mut normal = vec![mk("1.00", 100.0), mk("1.03", 100.0), mk("0.97", 100.0)];
    let (dropped2, _) = drop_mispriced_pairs(&mut normal);
    assert_eq!(dropped2, 0, "a few percent of spread is not mispricing");

    // A pair with no published price (bonding-curve venues) is kept: it
    // contributes no price/FDV, so it cannot poison anything.
    let mut curve: Vec<DexPair> = vec![
        serde_json::from_value(json!({
            "chainId": "solana", "dexId": "pumpfun", "pairAddress": "curve",
            "baseToken": {"address": "T", "symbol": "T", "name": "T"},
            "quoteToken": {"address": "S", "symbol": "S", "name": "S"},
        }))
        .unwrap(),
        mk("1.00", 10.0),
    ];
    let (dropped3, _) = drop_mispriced_pairs(&mut curve);
    assert_eq!(dropped3, 0);
}

/// Build an AuditResult carrying a v2 wallet-link section.
#[cfg(test)]
fn result_with_cluster(section: serde_json::Value) -> solwatch::types::AuditResult {
    use solwatch::types::{AuditResult, TokenMeta};
    AuditResult {
        address: BONK.into(),
        chain: "solana",
        scanned_at: "2026-07-19T00:00:00Z".into(),
        token: TokenMeta {
            symbol: Some("BONK".into()),
            ..Default::default()
        },
        score: 50,
        verdict: Verdict::Fair,
        flags: vec![],
        sections: json!({ "cluster": section }),
        warnings: vec![],
        coverage_gaps: vec![],
        rokha_url: None,
        rokha_app: serde_json::Value::Null,
    }
}

#[cfg(test)]
fn v2_section() -> serde_json::Value {
    json!({
        "schema": 2,
        "scope": {
            "wallets_analyzed": 14, "holders_analyzed": 9, "snipers_analyzed": 5,
            "funder_hops": 3, "transfer_probes": 10, "transfer_txs_sampled": 31,
            "coverage": "partial", "jitoApiOk": true,
            "limits": ["holder set is capped at the 20 largest token accounts"],
            "note": "",
        },
        "findings": [
            {"id": 1, "wallets": ["A","B"], "pct_combined": 22.5, "pct_bought": 30.0,
             "evidence": "jito_bundle", "confidence": "proven", "proof": "jito:abc", "note": "n1"},
            {"id": 2, "wallets": ["C","D"], "pct_combined": 8.0, "pct_bought": 9.0,
             "evidence": "shared_funder", "confidence": "probable", "proof": null, "note": "n2"},
            {"wallets": ["E","F"], "pct_combined": 3.0, "pct_bought": null,
             "evidence": "same_slot", "confidence": "lead", "proof": null, "note": "n3"},
        ],
        "effective_concentration": {
            "top10_raw_pct": 41.0, "top10_entity_pct_floor": 52.0,
            "largest_entity_pct_floor": 22.5, "is_floor": true,
        },
    })
}

#[test]
fn wallet_link_renderers_read_the_v2_contract() {
    // These renderers reach into the section with JSON POINTERS, so a field
    // rename compiles clean and silently renders nothing. That is exactly how
    // the v1 -> v2 cut could have shipped a blank panel, so both surfaces are
    // pinned here.
    let r = result_with_cluster(v2_section());

    let md = solwatch::report::render_markdown(&r);
    assert!(
        md.contains("## Linked wallets"),
        "md section missing:\n{md}"
    );
    assert!(md.contains("jito bundle"), "evidence not rendered:\n{md}");
    assert!(md.contains("**proven**"), "confidence not rendered:\n{md}");
    assert!(
        md.contains("_lead only_"),
        "leads must still be listed:\n{md}"
    );
    assert!(
        md.contains("at least 52%") && md.contains("floors"),
        "entity concentration must read as a floor:\n{md}"
    );
    assert!(
        md.contains("20 largest token accounts"),
        "structural limits must ride the durable report:\n{md}"
    );

    let app = solwatch::report::render_rokha_app(&r);
    let headings: Vec<&str> = app["sections"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|s| s["heading"].as_str())
        .collect();
    assert!(headings.contains(&"Linked wallets"), "{headings:?}");
    assert!(
        headings.contains(&"What the wallet-link pass cannot see"),
        "the app block must carry the limits too: {headings:?}"
    );
    let metrics = app["metrics"].as_array().unwrap();
    let entity = metrics
        .iter()
        .find(|m| m["label"] == "Entity top-10")
        .expect("entity top-10 metric missing");
    assert_eq!(
        entity["value"], "≥52%",
        "the metric tile must show a floor, not a point estimate"
    );
}

#[test]
fn a_quiet_wallet_link_pass_still_states_its_limits() {
    // No findings is the highest-risk presentation: a reader takes silence for
    // independence. The limits must render anyway.
    let mut section = v2_section();
    section["findings"] = json!([]);
    let r = result_with_cluster(section);
    let app = solwatch::report::render_rokha_app(&r);
    let headings: Vec<&str> = app["sections"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|s| s["heading"].as_str())
        .collect();
    assert!(
        headings.contains(&"What the wallet-link pass cannot see"),
        "limits must survive an empty findings list: {headings:?}"
    );
}

#[test]
fn the_bubblemap_payload_is_gone() {
    // nodes/edges existed for the removed canvas map only. If they come back,
    // something is rebuilding a completeness claim this data cannot support.
    let s = v2_section();
    assert!(s.get("nodes").is_none(), "nodes must not be re-serialized");
    assert!(s.get("edges").is_none(), "edges must not be re-serialized");
    assert!(
        s.get("linked_groups").is_none(),
        "leads belong in `findings` at confidence=lead, not a parallel array"
    );
    assert_eq!(s["schema"], 2);
}