liqproof 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +536 -2
  3. package/bugs/README.md +144 -0
  4. package/bugs/coin-gecko-liquidity-report.md +283 -0
  5. package/bugs/collect-ds-aggregate.mjs +213 -0
  6. package/bugs/collect-evidence.mjs +458 -0
  7. package/bugs/collect-gt-aggregate.mjs +215 -0
  8. package/bugs/collect-raw-rpc.mjs +165 -0
  9. package/bugs/collect-sweep-context.mjs +162 -0
  10. package/bugs/dexscreener-fake-liquidity-report.md +310 -0
  11. package/bugs/evidence/aggregator-liquidity-claims.json +648 -0
  12. package/bugs/evidence/aggregator-liquidity-claims.md +103 -0
  13. package/bugs/evidence/bat-native-pool-drained.json +136 -0
  14. package/bugs/evidence/bat-native-pool-drained.md +51 -0
  15. package/bugs/evidence/chz-impersonator-pool-drained.json +136 -0
  16. package/bugs/evidence/chz-impersonator-pool-drained.md +51 -0
  17. package/bugs/evidence/gt-stale-reserve-after-drain.json +141 -0
  18. package/bugs/evidence/gt-stale-reserve-after-drain.md +31 -0
  19. package/bugs/evidence/raw-rpc-transcript.json +683 -0
  20. package/bugs/evidence/raw-rpc-transcript.md +308 -0
  21. package/bugs/evidence/sweep-context.json +325 -0
  22. package/bugs/evidence/sweep-context.md +55 -0
  23. package/bugs/evidence/verified-aggregate.json +526 -0
  24. package/bugs/evidence/verified-aggregate.md +24 -0
  25. package/bugs/evidence/verified-ds-liquidity-usd.json +1197 -0
  26. package/bugs/evidence/verified-ds-liquidity-usd.md +250 -0
  27. package/bugs/evidence/verified-gt-reserve-in-usd.json +1002 -0
  28. package/bugs/evidence/verified-gt-reserve-in-usd.md +218 -0
  29. package/bugs/fix-bundle-titles.mjs +72 -0
  30. package/bugs/geckoterminal-stale-reserve-after-drain.md +137 -0
  31. package/data/dataset-summary.md +103 -0
  32. package/data/impersonators.json +12888 -0
  33. package/data/verified-impersonators.json +725 -0
  34. package/data/wallets.json +23 -0
  35. package/dist/base58.js +70 -0
  36. package/dist/base58.js.map +1 -0
  37. package/dist/canonical.js +372 -0
  38. package/dist/canonical.js.map +1 -0
  39. package/dist/cli.js +830 -0
  40. package/dist/cli.js.map +1 -0
  41. package/dist/curve.js +255 -0
  42. package/dist/curve.js.map +1 -0
  43. package/dist/dashboard.js +485 -0
  44. package/dist/dashboard.js.map +1 -0
  45. package/dist/keccak.js +197 -0
  46. package/dist/keccak.js.map +1 -0
  47. package/dist/mcp.js +604 -0
  48. package/dist/mcp.js.map +1 -0
  49. package/dist/operator.js +180 -0
  50. package/dist/operator.js.map +1 -0
  51. package/dist/pda.js +86 -0
  52. package/dist/pda.js.map +1 -0
  53. package/dist/receipt.js +897 -0
  54. package/dist/receipt.js.map +1 -0
  55. package/dist/render.js +335 -0
  56. package/dist/render.js.map +1 -0
  57. package/dist/rpc.js +377 -0
  58. package/dist/rpc.js.map +1 -0
  59. package/dist/sources.js +599 -0
  60. package/dist/sources.js.map +1 -0
  61. package/dist/store.js +330 -0
  62. package/dist/store.js.map +1 -0
  63. package/dist/tokenmeta.js +424 -0
  64. package/dist/tokenmeta.js.map +1 -0
  65. package/dist/util.js +273 -0
  66. package/dist/util.js.map +1 -0
  67. package/dist/vaults.js +510 -0
  68. package/dist/vaults.js.map +1 -0
  69. package/dist/wallet.js +404 -0
  70. package/dist/wallet.js.map +1 -0
  71. package/dist/warnings.js +41 -0
  72. package/dist/warnings.js.map +1 -0
  73. package/dist/worker.js +857 -0
  74. package/dist/worker.js.map +1 -0
  75. package/dist/x402.js +549 -0
  76. package/dist/x402.js.map +1 -0
  77. package/docs/HACKATHON-SUBMISSION.md +264 -0
  78. package/docs/liqproof-plan.md +221 -0
  79. package/docs/llms.txt +32 -0
  80. package/docs/mcp-registry.md +165 -0
  81. package/docs/screenshots/01-dashboard.png +0 -0
  82. package/docs/screenshots/02-receipt-drained.png +0 -0
  83. package/docs/screenshots/03-receipt-impersonator.png +0 -0
  84. package/docs/screenshots/04-receipt-canonical.png +0 -0
  85. package/docs/x402-pricing.md +171 -0
  86. package/docs/zero-xyz.md +250 -0
  87. package/out/6eftxVbSAunVEoxUWdGhPdxg5UdsJ8Wkwy5w5YFuxouw.json +1171 -0
  88. package/out/6eftxVbSAunVEoxUWdGhPdxg5UdsJ8Wkwy5w5YFuxouw.md +52 -0
  89. package/out/6eftxVbSAunVEoxUWdGhPdxg5UdsJ8Wkwy5w5YFuxouw.svg +25 -0
  90. package/out/BTNiaZb6HaEFWeEtND4SXtZ7T6mgtDwSryHTAj6PuPyp.json +3975 -0
  91. package/out/BTNiaZb6HaEFWeEtND4SXtZ7T6mgtDwSryHTAj6PuPyp.md +90 -0
  92. package/out/BTNiaZb6HaEFWeEtND4SXtZ7T6mgtDwSryHTAj6PuPyp.svg +25 -0
  93. package/out/ENGkoidj2jNs73A7GZuseVmnkRg6EVF9tDtViwPz8o85.json +1446 -0
  94. package/out/ENGkoidj2jNs73A7GZuseVmnkRg6EVF9tDtViwPz8o85.md +66 -0
  95. package/out/ENGkoidj2jNs73A7GZuseVmnkRg6EVF9tDtViwPz8o85.svg +25 -0
  96. package/out/dataset.csv +67 -0
  97. package/out/impersonation-table.md +156 -0
  98. package/out/index.html +1179 -0
  99. package/package.json +78 -4
  100. package/scripts/assert-no-canonical-accusations.mjs +193 -0
  101. package/scripts/backfill.mjs +1063 -0
  102. package/scripts/bundle-evidence.mjs +237 -0
  103. package/scripts/bundle-stale-claim.mjs +417 -0
  104. package/scripts/capture-bch-evidence.mjs +58 -0
  105. package/scripts/check-orientation-fix.mjs +40 -0
  106. package/scripts/check-wallet.mjs +54 -0
  107. package/scripts/daily-refresh.mjs +451 -0
  108. package/scripts/decode-clmm-vaults.mjs +180 -0
  109. package/scripts/falsifiability.mjs +263 -0
  110. package/scripts/impersonator-mining.mjs +156 -0
  111. package/scripts/inspect-matches.mjs +73 -0
  112. package/scripts/operator-sweep.mjs +252 -0
  113. package/scripts/publish-release.mjs +248 -0
  114. package/scripts/refresh-store.mjs +78 -0
  115. package/scripts/survival-miner.mjs +951 -0
  116. package/scripts/test-keccak.mjs +103 -0
  117. package/scripts/verify-bch-1p95b.mjs +124 -0
  118. package/scripts/verify-clmm-1p95b.mjs +127 -0
  119. package/scripts/verify-clmm-control.mjs +84 -0
  120. package/scripts/verify-impersonators.mjs +138 -0
  121. package/scripts/verify-raw.mjs +110 -0
  122. package/scripts/verify-raw2.mjs +99 -0
  123. package/server.json +34 -0
  124. package/src/base58.ts +68 -0
  125. package/src/canonical.ts +447 -0
  126. package/src/cli.ts +941 -0
  127. package/src/curve.ts +349 -0
  128. package/src/dashboard.ts +504 -0
  129. package/src/keccak.ts +228 -0
  130. package/src/mcp.ts +735 -0
  131. package/src/operator.ts +219 -0
  132. package/src/receipt.ts +1219 -0
  133. package/src/render.ts +396 -0
  134. package/src/rpc.ts +435 -0
  135. package/src/sources.ts +714 -0
  136. package/src/store.ts +428 -0
  137. package/src/tokenmeta.ts +460 -0
  138. package/src/util.ts +276 -0
  139. package/src/vaults.ts +574 -0
  140. package/src/wallet.ts +459 -0
  141. package/src/warnings.ts +40 -0
  142. package/src/worker.ts +1086 -0
  143. package/src/x402.ts +717 -0
package/src/receipt.ts ADDED
@@ -0,0 +1,1219 @@
1
+ /**
2
+ * receipt.ts — build the LIQPROOF artifact.
3
+ *
4
+ * The artifact is a RECEIPT, not a score. It answers four questions with
5
+ * on-chain evidence:
6
+ *
7
+ * 1. What did the market CLAIM? (aggregator-reported liquidity, USD)
8
+ * 2. What is ACTUALLY there? (pool vault balances, read from the chain)
9
+ * 3. When did it change? (timestamped liquidity curve from tx metadata)
10
+ * 4. Can you actually trade? (Jupiter execution oracle: price impact)
11
+ *
12
+ * THE HEADLINE METRIC — DEPOSIT COVERAGE:
13
+ *
14
+ * coverage = (USDC actually sitting in the pool) / (USD the market claims)
15
+ *
16
+ * For an honest pool this is ~50-100%. For a rug it is 0.00003%. That single
17
+ * number is falsifiable, timestampable, and impossible to fake without
18
+ * actually depositing the money.
19
+ *
20
+ * THE SECOND METRIC — PRICE DIVERGENCE:
21
+ *
22
+ * divergence = (displayed price) / (price a real $1 buy actually gets you)
23
+ *
24
+ * When a pool is full of its own token and the quote side is nearly empty,
25
+ * the "price" is a fiction: $1 buys you a rounding error of tokens.
26
+ */
27
+
28
+ import { RpcPool } from './rpc.js';
29
+ import {
30
+ jupiterQuote,
31
+ quoteTokenPriceUsd,
32
+ solPriceUsd,
33
+ tokenReport,
34
+ type JupiterQuote,
35
+ type PoolReport,
36
+ } from './sources.js';
37
+ import { liquidityCurve, type CurvePoint, type LiquidityCurve } from './curve.js';
38
+ import { readPoolVaults, mintMeta, type PoolVaults, type Vault } from './vaults.js';
39
+ import { MINT } from './sources.js';
40
+ import { tokenMetadata, type TokenMetadata } from './tokenmeta.js';
41
+ import { loadCanonicalIndex, resolveCanonical, type CanonicalResolution } from './canonical.js';
42
+ import { loadOperatorRegistry, findOperatorLink, type OperatorLink } from './operator.js';
43
+ import { ratio } from './util.js';
44
+
45
+ export type Verdict =
46
+ | 'FAKE_LIQUIDITY'
47
+ | 'UNBACKED_LIQUIDITY'
48
+ | 'NO_DEPTH'
49
+ | 'DRAINED'
50
+ | 'THIN'
51
+ | 'CONSISTENT'
52
+ | 'NO_ROUTE'
53
+ | 'UNKNOWN';
54
+
55
+ export interface VaultSnapshot {
56
+ pool: string;
57
+ dexId: string;
58
+ claimedLiquidityUsd: number;
59
+ realQuoteUsd: number;
60
+ realBaseTokens: number;
61
+ /**
62
+ * How much of the claimed liquidity is denominated in the token itself.
63
+ * Aggregators compute reserve_in_usd = base_tokens × price + quote_usd,
64
+ * so a pool stuffed with its own token inflates its own liquidity number.
65
+ * This is the ratio that separates "real money" from "circular valuation".
66
+ */
67
+ selfDenominatedPct: number;
68
+ /** the same ratio computed per reporting source — for auditability */
69
+ selfDenominatedBySource: Array<{
70
+ source: string;
71
+ claimUsd: number;
72
+ priceUsd: number;
73
+ selfDenominatedPct: number;
74
+ }>;
75
+ baseMint: string;
76
+ quoteMint: string;
77
+ quoteSymbol: string;
78
+ baseSymbol: string;
79
+ coverage: number;
80
+ divergenceRatio: number;
81
+ vaults: Array<{
82
+ address: string;
83
+ mint: string;
84
+ side: string;
85
+ amount: string;
86
+ uiAmount: number;
87
+ decimals: number;
88
+ }>;
89
+ poolOwnerProgram?: string;
90
+ poolLamports: number;
91
+ method?: string;
92
+ note?: string;
93
+ }
94
+
95
+ export interface OracleSnapshot {
96
+ buyQuote?: JupiterQuote | null;
97
+ sellQuote?: JupiterQuote | null;
98
+ /** price per token implied by a real executable $1 buy */
99
+ executablePriceUsd?: number;
100
+ /** displayed price from aggregators */
101
+ displayedPriceUsd?: number;
102
+ /** displayed / executable */
103
+ priceDivergence?: number;
104
+ /** how many tokens a real $1 buy returns */
105
+ tokensPerDollar?: number;
106
+ solToTokenRoutable?: boolean;
107
+ tokenToSolRoutable?: boolean;
108
+ }
109
+
110
+ export interface Receipt {
111
+ version: '1.0';
112
+ generatedAt: string;
113
+ mint: string;
114
+ symbol?: string;
115
+ name?: string;
116
+ verdict: Verdict;
117
+ headline: string;
118
+ summary: string;
119
+
120
+ /**
121
+ * What the token says it is, and whether that claim holds.
122
+ *
123
+ * This block exists because a ticker is not an identity. Two mints can
124
+ * both be called "CHZ"; only one of them is Chiliz. Before LIQPROOF is
125
+ * allowed to accuse a token it resolves the canonical mint and records
126
+ * the proof — so a reader can check the accusation instead of trusting it.
127
+ */
128
+ identity: {
129
+ /** name as recorded in the mint's own Metaplex metadata account */
130
+ onChainName?: string;
131
+ /** ticker as recorded in the mint's own Metaplex metadata account */
132
+ onChainSymbol?: string;
133
+ /** the metadata account (PDA) — the on-chain proof of the name */
134
+ metadataPda?: string;
135
+ /** creators recorded in the metadata account */
136
+ creators?: Array<{ address: string; verified: boolean; share: number }>;
137
+ canonical: {
138
+ status: 'canonical' | 'impersonator' | 'unresolved';
139
+ /** true when this mint IS the canonical token for its name */
140
+ isCanonical: boolean;
141
+ /** how we resolved it — printed verbatim so it can be audited */
142
+ method: string;
143
+ confidence: 'confirmed' | 'symbol-only' | 'unresolved';
144
+ /** the canonical token this mint appears to impersonate */
145
+ impersonates?: {
146
+ mint: string;
147
+ name: string;
148
+ symbol: string;
149
+ source: string;
150
+ proof: string;
151
+ proofLabel: string;
152
+ };
153
+ };
154
+ /** link to the wallet that deployed this token and its siblings */
155
+ operator?: {
156
+ creator: string;
157
+ link: 'identical' | 'prefix';
158
+ cluster: string;
159
+ /** how many tokens in the cluster share this creator */
160
+ clusterSize: number;
161
+ peers: Array<{ mint: string; name?: string; symbol?: string }>;
162
+ };
163
+ };
164
+
165
+ /** short machine-readable findings, e.g. IMPERSONATION, FACTORY_LINK */
166
+ flags: string[];
167
+
168
+ claimed: {
169
+ liquidityUsd: number;
170
+ priceUsd: number;
171
+ sources: Array<{ source: string; liquidityUsd: number; priceUsd: number; pool: string }>;
172
+ };
173
+
174
+ real: {
175
+ depositedUsd: number;
176
+ heldTokens: number;
177
+ coverage: number;
178
+ divergenceRatio: number;
179
+ /** fraction of the claimed liquidity that is the token itself (circular) */
180
+ selfDenominatedPct: number;
181
+ peakDepositedUsd?: number;
182
+ peakAt?: string;
183
+ drainAt?: string;
184
+ drainSlot?: number;
185
+ drainSignature?: string;
186
+ drainDeltaUsd?: number;
187
+ };
188
+
189
+ oracle: OracleSnapshot;
190
+
191
+ timeline: {
192
+ points: Array<{
193
+ at: string;
194
+ slot: number;
195
+ signature: string;
196
+ depositedUsd: number;
197
+ deltaUsd: number;
198
+ note?: string;
199
+ }>;
200
+ scanned: number;
201
+ unavailable: number;
202
+ truncated: boolean;
203
+ strategy: string;
204
+ totalSignatures: number;
205
+ };
206
+
207
+ pools: VaultSnapshot[];
208
+
209
+ /**
210
+ * Which pool this receipt is about, and how the audited mint sits in it.
211
+ *
212
+ * This exists because of a mistake we made and caught: we published a
213
+ * receipt for USDC that was measured on a pool where USDC was only the
214
+ * counterparty, and the shortfall in that pool was published as though it
215
+ * were USDC's own fault. A reader must be able to see, without asking,
216
+ * whose number this is.
217
+ */
218
+ audited: {
219
+ pool: string;
220
+ dexId: string;
221
+ name: string;
222
+ orientation: 'base' | 'quote' | 'unknown';
223
+ /** true when the audited mint is only the counterparty in this pool */
224
+ counterpartyOnly: boolean;
225
+ /** how many candidate pools the mint had, and how many were base-side */
226
+ candidatePools: number;
227
+ baseSidePools: number;
228
+ };
229
+
230
+ evidence: Array<{ kind: string; url: string; label: string }>;
231
+
232
+ methodology: string[];
233
+ disclaimer: string;
234
+ }
235
+
236
+ const METHODOLOGY = [
237
+ "Deposited USD = SPL token-account balance of the pool's quote-side vault, read directly from Solana mainnet (no aggregator, no paid API).",
238
+ 'Claimed USD = reserve_in_usd as reported by GeckoTerminal (CoinGecko) and DexScreener.',
239
+ 'Historical liquidity curve reconstructed from preTokenBalances/postTokenBalances in transaction metadata — no archive node required.',
240
+ 'Executable price derived from a live Jupiter swap quote (lite-api), which simulates the actual route and reports price impact.',
241
+ 'Every number above is reproducible with the read-only public RPC; no private indexer, no paid API, no chain mutation.',
242
+ ];
243
+
244
+ const DISCLAIMER =
245
+ 'LIQPROOF reports on-chain measurements only. It does not issue investment advice or legal conclusions. ' +
246
+ 'Values are derived from public chain state at the stated slot and may differ from the state at the time of reading.';
247
+
248
+ /**
249
+ * A pool as seen by one or more aggregators, merged into a single view.
250
+ *
251
+ * `claimedLiquidityUsd` is the HIGHEST claim any source makes. We use the
252
+ * maximum on purpose: it is the number most favourable to the token, so
253
+ * every accusation we make is made against the strongest claim on record.
254
+ */
255
+ interface PoolView extends Omit<PoolReport, 'source'> {
256
+ /** every source row that refers to this pool address */
257
+ entries: PoolReport[];
258
+ /** the distinct sources that reported this pool */
259
+ sources: string[];
260
+ }
261
+
262
+ /** Merge aggregator rows that describe the same on-chain pool. */
263
+ function mergePools(pools: PoolReport[]): PoolView[] {
264
+ const byAddress = new Map<string, PoolView>();
265
+ for (const p of pools) {
266
+ if (!p.address) continue;
267
+ const existing = byAddress.get(p.address);
268
+ if (!existing) {
269
+ byAddress.set(p.address, {
270
+ ...p,
271
+ reportedLiquidityUsd: p.reportedLiquidityUsd,
272
+ entries: [p],
273
+ sources: [p.source],
274
+ });
275
+ continue;
276
+ }
277
+ existing.entries.push(p);
278
+ if (!existing.sources.includes(p.source)) existing.sources.push(p.source);
279
+ // Keep the largest claim (and the price that came with it).
280
+ if (p.reportedLiquidityUsd > existing.reportedLiquidityUsd) {
281
+ existing.reportedLiquidityUsd = p.reportedLiquidityUsd;
282
+ existing.basePriceUsd = p.basePriceUsd || existing.basePriceUsd;
283
+ existing.quotePriceUsd = p.quotePriceUsd || existing.quotePriceUsd;
284
+ }
285
+ // Fill in any field a previous source left empty.
286
+ existing.baseTokenAddress ||= p.baseTokenAddress;
287
+ existing.baseTokenSymbol ||= p.baseTokenSymbol;
288
+ existing.quoteTokenAddress ||= p.quoteTokenAddress;
289
+ existing.quoteTokenSymbol ||= p.quoteTokenSymbol;
290
+ existing.dexId ||= p.dexId;
291
+ existing.name ||= p.name;
292
+ existing.createdAt ||= p.createdAt;
293
+ }
294
+ const out = [...byAddress.values()];
295
+ out.sort((a, b) => b.reportedLiquidityUsd - a.reportedLiquidityUsd);
296
+ return out;
297
+ }
298
+
299
+ /**
300
+ * Fraction of a pool's value that is denominated in the token itself.
301
+ *
302
+ * self% = base_value / (base_value + quote_value)
303
+ *
304
+ * `baseTokens` is the live base-side balance, `priceUsd` the market price of
305
+ * that token, `quoteUsd` the live quote-side value (real money). The result
306
+ * is always in [0, 1] and always consistent in time, because both legs come
307
+ * from the same on-chain snapshot.
308
+ */
309
+ function computeSelfDenominated(
310
+ baseTokens: number,
311
+ priceUsd: number,
312
+ quoteUsd: number,
313
+ ): number {
314
+ const baseValue = baseTokens * priceUsd;
315
+ const total = baseValue + quoteUsd;
316
+ if (!Number.isFinite(total) || total <= 0) return 0;
317
+ return Math.max(0, Math.min(1, baseValue / total));
318
+ }
319
+
320
+ function pct(n: number): string {
321
+ if (!Number.isFinite(n)) return 'n/a';
322
+ if (n === 0) return '0%';
323
+ if (n < 0.001) return `${(n * 100).toPrecision(3)}%`;
324
+ return `${(n * 100).toFixed(2)}%`;
325
+ }
326
+
327
+ function fmtUsd(n: number): string {
328
+ if (!Number.isFinite(n)) return 'n/a';
329
+ const abs = Math.abs(n);
330
+ if (abs >= 1_000_000_000) return `$${(n / 1_000_000_000).toFixed(2)}B`;
331
+ if (abs >= 1_000_000) return `$${(n / 1_000_000).toFixed(2)}M`;
332
+ if (abs >= 1_000) return `$${(n / 1_000).toFixed(2)}K`;
333
+ if (abs >= 1) return `$${n.toFixed(2)}`;
334
+ return `$${n.toFixed(4)}`;
335
+ }
336
+
337
+ /**
338
+ * Format an overstatement ratio for prose.
339
+ *
340
+ * The drained "BCH" pool measures 1.93 × 10¹⁵. Writing that out in full
341
+ * ("1,928,462,445,799,058×") implies a precision the measurement does not
342
+ * have and makes the sentence unreadable, so we scale it instead.
343
+ *
344
+ * (One implementation, shared with the renderer — see `ratio` in util.ts.)
345
+ */
346
+ const fmtRatio = ratio;
347
+
348
+ export interface BuildReceiptOptions {
349
+ maxTransactions?: number;
350
+ includeCurve?: boolean;
351
+ focusPool?: string;
352
+ /**
353
+ * The aggregator row for `focusPool`, when the token's own pool list does
354
+ * not contain it. Mining feeds (top pools, trending pools) surface pools
355
+ * that a token's `/pools` endpoint does not return — without this we would
356
+ * audit nothing and report UNKNOWN for a pool we know has a claim.
357
+ */
358
+ focusPoolData?: PoolReport;
359
+ verbose?: boolean;
360
+ }
361
+
362
+ /** Build a receipt for a mint. */
363
+ export async function buildReceipt(
364
+ rpc: RpcPool,
365
+ mint: string,
366
+ opts: BuildReceiptOptions = {},
367
+ ): Promise<Receipt> {
368
+ const includeCurve = opts.includeCurve ?? true;
369
+ const maxTransactions = opts.maxTransactions ?? 600;
370
+
371
+ // ── 1. what the market claims ────────────────────────────────────────────
372
+ const report = await tokenReport(mint);
373
+ const pools: PoolReport[] = report.pools;
374
+
375
+ // ── 1b. what the token says it IS ────────────────────────────────────────
376
+ //
377
+ // The aggregator's `name` is a third party's claim. The mint's own
378
+ // Metaplex metadata account is the token's statement, and it is the only
379
+ // statement that cannot be edited without touching the chain. We read it
380
+ // directly, from the account's own PDA, and we surface the PDA as
381
+ // evidence so the reader can open it and check us.
382
+ let meta: TokenMetadata | null = null;
383
+ try {
384
+ meta = await tokenMetadata(rpc, mint);
385
+ } catch {
386
+ meta = null;
387
+ }
388
+
389
+ const identityName = meta?.name || report.name || '';
390
+ const identitySymbol = meta?.symbol || report.symbol || '';
391
+
392
+ // Resolve the canonical token behind this name/ticker. This is the step
393
+ // that stops us from calling a real project a counterfeit: on 2026-12-04
394
+ // it is the difference between accusing Chiliz and accusing the wallet
395
+ // that copied Chiliz's name.
396
+ let canonicalIndex: Awaited<ReturnType<typeof loadCanonicalIndex>> | null = null;
397
+ let canonical: CanonicalResolution;
398
+ try {
399
+ canonicalIndex = await loadCanonicalIndex();
400
+ canonical = resolveCanonical(
401
+ mint,
402
+ { name: identityName, symbol: identitySymbol },
403
+ canonicalIndex,
404
+ );
405
+ } catch {
406
+ canonical = resolveCanonical(mint, null, {
407
+ entries: [],
408
+ byMint: new Map(),
409
+ bySymbol: new Map(),
410
+ byCoreName: new Map(),
411
+ loadedAt: '',
412
+ counts: {},
413
+ });
414
+ }
415
+
416
+ // If the canonical index could not be loaded at all we do not know what
417
+ // the genuine article is — and a tool that cannot tell a real project
418
+ // from a fake one must not issue accusations.
419
+ const canonicalIndexAvailable = (canonicalIndex?.entries.length ?? 0) > 0;
420
+ const tokenIsCanonical = canonical.isCanonical;
421
+
422
+ // Link this mint to the wallet that deployed it and its siblings.
423
+ let operator: OperatorLink | null = null;
424
+ if (meta?.creators?.length) {
425
+ try {
426
+ operator = findOperatorLink(loadOperatorRegistry(), mint, meta.creators);
427
+ } catch {
428
+ operator = null;
429
+ }
430
+ }
431
+
432
+ // Several aggregators report the SAME pool address. If we audited one row
433
+ // per source we would read the same vaults twice and DOUBLE the deposit —
434
+ // we measured exactly that ($42.91 instead of the real $21.45). So merge by
435
+ // address FIRST, then audit each unique pool once.
436
+ const views = mergePools(pools);
437
+
438
+ /**
439
+ * ORIENTATION — whose liquidity is this pool, really?
440
+ *
441
+ * A pool in which the audited mint is only the QUOTE token is not evidence
442
+ * about that mint's liquidity; it is evidence about the other token. We got
443
+ * this wrong once and it produced the single most misleading row in our own
444
+ * dataset: USDT was audited on "BCH / USDT" — a pool whose entire reserve
445
+ * had been drained — so USDT was published as holding $0.00 of liquidity.
446
+ * The pool was the problem. USDT was the innocent counterparty, and the
447
+ * honest $40-billion USDT market was made to look like a scam.
448
+ *
449
+ * So: audit a pool where the mint is the BASE token whenever one exists.
450
+ * Only when there is no base-side pool at all do we fall back to a
451
+ * quote-side pool, and then the receipt says so in plain words instead of
452
+ * quietly blaming the counterparty.
453
+ */
454
+ const baseSidePools = views.filter((v) => v.baseTokenAddress === mint);
455
+ const quoteSidePools = views.filter(
456
+ (v) => v.baseTokenAddress !== mint && v.quoteTokenAddress === mint,
457
+ );
458
+ const preferredPools = baseSidePools.length
459
+ ? baseSidePools
460
+ : quoteSidePools.length
461
+ ? quoteSidePools
462
+ : views;
463
+
464
+ let focus = opts.focusPool ?? preferredPools[0]?.address ?? views[0]?.address;
465
+ let focusView = views.find((v) => v.address === focus);
466
+
467
+ // The mining feed may know a pool that the token's own pool list does not
468
+ // return. Fall back to the feed's row so the audit still happens.
469
+ if (!focusView && opts.focusPoolData) {
470
+ const extra = mergePools([opts.focusPoolData]);
471
+ focusView = extra[0];
472
+ focus = focusView?.address;
473
+ }
474
+
475
+ const claimedLiquidityUsd = focusView?.reportedLiquidityUsd ?? 0;
476
+ const displayedPriceUsd = report.priceUsd ?? focusView?.basePriceUsd ?? 0;
477
+
478
+ /**
479
+ * How the audited mint sits in the pool we audited.
480
+ *
481
+ * 'base' — the mint IS the pool's base token. The pool's liquidity is
482
+ * the mint's liquidity, and every number in this receipt is a
483
+ * statement about the mint.
484
+ * 'quote' — the mint is only the counterparty (e.g. USDC in a BCH/USDT
485
+ * pool). The pool's numbers describe the OTHER token; a
486
+ * shortfall here is a finding about that pool, never about the
487
+ * mint. We say so out loud rather than publishing a number
488
+ * that reads as an accusation.
489
+ * 'unknown' — the aggregator did not tell us the orientation.
490
+ */
491
+ const orientation: 'base' | 'quote' | 'unknown' =
492
+ focusView && focusView.baseTokenAddress === mint
493
+ ? 'base'
494
+ : focusView && focusView.quoteTokenAddress === mint
495
+ ? 'quote'
496
+ : 'unknown';
497
+
498
+ const claimSources = (focusView?.entries ?? []).slice(0, 4).map((p) => ({
499
+ source: p.source,
500
+ liquidityUsd: p.reportedLiquidityUsd,
501
+ priceUsd: p.basePriceUsd,
502
+ pool: p.address,
503
+ }));
504
+
505
+ const solUsd = await solPriceUsd();
506
+
507
+ // ── 2. pick the pool to audit ────────────────────────────────────────────
508
+ const auditList = focusView ? [focusView] : [];
509
+
510
+ const snapshots: VaultSnapshot[] = [];
511
+ let curve: LiquidityCurve | undefined;
512
+ let oracle: OracleSnapshot = {};
513
+ let baseDecimals = 6;
514
+ let poolQuotePrice = 0;
515
+
516
+ for (const pool of auditList) {
517
+ const baseMint = pool.baseTokenAddress || mint;
518
+ const quoteMint = pool.quoteTokenAddress || MINT.USDC;
519
+ const vaults = await readPoolVaults(rpc, pool.address, baseMint, quoteMint);
520
+
521
+ const baseVault = vaults.base;
522
+ const quoteVault = vaults.quote;
523
+ const quotePrice = await quoteTokenPriceUsd(
524
+ quoteMint,
525
+ pool.quotePriceUsd,
526
+ baseMint,
527
+ );
528
+ if (poolQuotePrice === 0 && quotePrice > 0) poolQuotePrice = quotePrice;
529
+ const realQuoteUsd = quoteVault ? quoteVault.uiAmount * quotePrice : 0;
530
+ const realBaseTokens = baseVault?.uiAmount ?? 0;
531
+ const coverage = claimedLiquidityUsd > 0 ? realQuoteUsd / claimedLiquidityUsd : 0;
532
+ const divergenceRatio = realQuoteUsd > 0 ? claimedLiquidityUsd / realQuoteUsd : Infinity;
533
+
534
+ // How much of the claimed liquidity is the token itself valued at its own
535
+ // price? (aggregator formula: reserve_in_usd = base_tokens × price + quote_usd)
536
+ //
537
+ // Each source is evaluated with ITS OWN price and ITS OWN claim, then we
538
+ // keep the SMALLEST percentage. That is the reading least favourable to
539
+ // an accusation — we only call a pool circular when even the most
540
+ // generous reading of the data says so.
541
+ // How much of the pool's value is the token itself?
542
+ //
543
+ // IMPORTANT — this is computed from the LIVE on-chain balances, NOT from
544
+ // the aggregator's claim. We originally derived it as
545
+ // (base_tokens × price) / claimed_liquidity, but that mixes a live
546
+ // balance with a claim that may be up to 15 minutes old, and the ratio
547
+ // could then exceed 100% and accuse an honest token (we caught exactly
548
+ // that: BONK, a bluechip, was briefly reported as FAKE_LIQUIDITY).
549
+ //
550
+ // The on-chain formulation cannot exceed 100% by construction and is
551
+ // time-consistent:
552
+ //
553
+ // self% = base_value / (base_value + quote_value)
554
+ //
555
+ // where base_value = live base balance × market price, and
556
+ // quote_value = live quote balance (real money, in USD).
557
+ //
558
+ // Honest pools land at 45-75% (the base token is the bigger leg).
559
+ // A pool whose "liquidity" is 99.99% its own token is circular.
560
+ const selfDenominatedPct = computeSelfDenominated(
561
+ realBaseTokens,
562
+ pool.basePriceUsd || displayedPriceUsd,
563
+ realQuoteUsd,
564
+ );
565
+
566
+ // Per-source breakdown for auditability (each source contributes its own
567
+ // price for the base leg).
568
+ const selfBySource: VaultSnapshot['selfDenominatedBySource'] = [];
569
+ for (const e of pool.entries) {
570
+ const px = e.basePriceUsd || pool.basePriceUsd || displayedPriceUsd;
571
+ if (px <= 0) continue;
572
+ selfBySource.push({
573
+ source: e.source,
574
+ claimUsd: e.reportedLiquidityUsd,
575
+ priceUsd: px,
576
+ selfDenominatedPct: computeSelfDenominated(realBaseTokens, px, realQuoteUsd),
577
+ });
578
+ }
579
+
580
+ if (baseMint === mint) {
581
+ const mm = await mintMeta(rpc, mint);
582
+ if (mm) baseDecimals = mm.decimals;
583
+ }
584
+
585
+ snapshots.push({
586
+ pool: pool.address,
587
+ dexId: pool.dexId,
588
+ claimedLiquidityUsd: pool.reportedLiquidityUsd,
589
+ realQuoteUsd,
590
+ realBaseTokens,
591
+ selfDenominatedPct,
592
+ selfDenominatedBySource: selfBySource,
593
+ baseMint,
594
+ quoteMint,
595
+ quoteSymbol:
596
+ pool.quoteTokenSymbol ||
597
+ (quoteMint === MINT.USDC ? 'USDC' : quoteMint === MINT.SOL ? 'SOL' : ''),
598
+ baseSymbol: pool.baseTokenSymbol || report.symbol || '',
599
+ coverage,
600
+ divergenceRatio,
601
+ vaults: vaults.all.map((v: Vault) => ({
602
+ address: v.address,
603
+ mint: v.mint,
604
+ side: v.side,
605
+ amount: v.amount,
606
+ uiAmount: v.uiAmount,
607
+ decimals: v.decimals,
608
+ })),
609
+ poolOwnerProgram: vaults.poolOwnerProgram,
610
+ poolLamports: vaults.poolLamports,
611
+ method: vaults.method,
612
+ note: vaults.note,
613
+ });
614
+
615
+ // ── 3. the curve ───────────────────────────────────────────────────────
616
+ if (includeCurve && !curve && vaults.all.length > 0) {
617
+ const vaultAddresses = vaults.all.map((v) => v.address);
618
+ const vaultMints: Record<string, string> = {};
619
+ for (const v of vaults.all) vaultMints[v.address] = v.mint;
620
+
621
+ const prices: Record<string, number> = { [MINT.USDC]: 1, [MINT.SOL]: solUsd };
622
+ if (quotePrice > 0) prices[quoteMint] = quotePrice;
623
+
624
+ curve = await liquidityCurve(rpc, pool.address, vaultAddresses, vaultMints, {
625
+ maxTransactions,
626
+ maxSignatures: Math.max(maxTransactions * 5, 3000),
627
+ prices,
628
+ });
629
+ }
630
+ }
631
+
632
+ // ── 4. the execution oracle ──────────────────────────────────────────────
633
+ const BUY_AMOUNT = 1_000_000; // 1 USDC in base units
634
+ const buyQuote = await jupiterQuote(MINT.USDC, mint, String(BUY_AMOUNT));
635
+ const solToToken = await jupiterQuote(MINT.SOL, mint, '10000000'); // 0.01 SOL
636
+ const sellAmount = 10 ** baseDecimals; // 1 whole token
637
+ const sellQuote = await jupiterQuote(mint, MINT.USDC, String(sellAmount));
638
+
639
+ // tokens actually received for $1
640
+ const tokensPerDollar =
641
+ buyQuote && !buyQuote.error && Number(buyQuote.outAmount) > 0
642
+ ? Number(buyQuote.outAmount) / 10 ** baseDecimals
643
+ : undefined;
644
+
645
+ // executable unit price = what one token actually costs in a real trade
646
+ const executablePriceUsd = tokensPerDollar ? 1 / tokensPerDollar : undefined;
647
+ const priceDivergence =
648
+ executablePriceUsd && executablePriceUsd > 0 && displayedPriceUsd > 0
649
+ ? displayedPriceUsd / executablePriceUsd
650
+ : undefined;
651
+
652
+ oracle = {
653
+ buyQuote,
654
+ sellQuote,
655
+ executablePriceUsd,
656
+ displayedPriceUsd: displayedPriceUsd || undefined,
657
+ priceDivergence,
658
+ tokensPerDollar,
659
+ solToTokenRoutable: !!(solToToken && !solToToken.error),
660
+ tokenToSolRoutable: !!(sellQuote && !sellQuote.error),
661
+ };
662
+
663
+ // ── 5. assemble ──────────────────────────────────────────────────────────
664
+ const depositedUsd = snapshots.reduce((s, p) => s + p.realQuoteUsd, 0);
665
+ const heldTokens = snapshots.reduce((s, p) => s + p.realBaseTokens, 0);
666
+ const coverage = claimedLiquidityUsd > 0 ? depositedUsd / claimedLiquidityUsd : 0;
667
+ const divergenceRatio = depositedUsd > 0 ? claimedLiquidityUsd / depositedUsd : Infinity;
668
+ const selfDenominatedPct = snapshots.length
669
+ ? snapshots.reduce((s, p) => s + p.selfDenominatedPct, 0) / snapshots.length
670
+ : 0;
671
+
672
+ // peak deposited USD across the whole reconstructed history.
673
+ // Use the "before" balance too — the peak may only appear as a pre-image.
674
+ const quoteMint = snapshots[0]?.quoteMint ?? MINT.USDC;
675
+ // Reuse the price we already resolved while auditing the pool. Recomputing
676
+ // here would issue a second round of network calls and could come back
677
+ // empty (which would wrongly gate the verdict to UNKNOWN).
678
+ const quotePriceUsd = poolQuotePrice > 0 ? poolQuotePrice : await quoteTokenPriceUsd(
679
+ quoteMint,
680
+ undefined,
681
+ snapshots[0]?.baseMint,
682
+ );
683
+ const quoteDecimals = snapshots[0]?.vaults.find((v) => v.side === 'quote')?.decimals ?? 6;
684
+
685
+ let peakDepositedUsd: number | undefined;
686
+ let peakPoint: CurvePoint | undefined;
687
+ for (const p of curve?.points ?? []) {
688
+ const post = p.balances[quoteMint];
689
+ const pre = p.before[quoteMint];
690
+ for (const raw of [post, pre]) {
691
+ if (raw === undefined) continue;
692
+ const v = (Number(raw) / 10 ** quoteDecimals) * quotePriceUsd;
693
+ if (peakDepositedUsd === undefined || v > peakDepositedUsd) {
694
+ peakDepositedUsd = v;
695
+ peakPoint = p;
696
+ }
697
+ }
698
+ }
699
+
700
+ // ── 6. verdict ───────────────────────────────────────────────────────────
701
+ //
702
+ // EVIDENCE GATING — the most important rule in this file.
703
+ // A receipt that accuses a token when it simply FAILED to read the vaults
704
+ // is worse than useless: it destroys the credibility of every other receipt
705
+ // we publish. Therefore:
706
+ //
707
+ // • no quote-side vault located → we have no deposit evidence → UNKNOWN
708
+ // • no quote price available → we cannot value the deposit → UNKNOWN
709
+ // • only then may we issue an adverse verdict
710
+ //
711
+ const impact = buyQuote && !buyQuote.error ? buyQuote.priceImpactPct : 1;
712
+ const quoteVaultFound = !!snapshots[0]?.vaults.some((v) => v.side === 'quote');
713
+ const quotePriced = quotePriceUsd > 0;
714
+ const hasDepositEvidence = quoteVaultFound && quotePriced;
715
+
716
+ // ── the tradeability oracle, and why it needs corroboration ──────────────
717
+ //
718
+ // A quote API's price-impact field is a RATIO where 1 means 100%. We
719
+ // verified this against four known pools: a dead BAT pool returns 1.0, a
720
+ // healthy bluechip returns 0.0007, a healthy but one-sided pool returns
721
+ // 0.00005.
722
+ //
723
+ // But the field is not self-describing. A price-impact number tells you
724
+ // how the ROUTER priced the route; it does not tell you whether the
725
+ // pool behind it holds anything. A consumer that thresholds on that one
726
+ // field will block healthy routes and wave through empty ones — we have
727
+ // seen both failure modes in our own tool, which is why the rule below
728
+ // exists.
729
+ //
730
+ // THE RULE: the oracle is a WITNESS, not a JUDGE. `impact === 1` is never
731
+ // a verdict on its own. It is only evidence when the on-chain depth
732
+ // independently agrees that there is almost nothing to trade against.
733
+ // Two channels must corroborate each other, or there is no verdict.
734
+ const quoteUsable = !!buyQuote && !buyQuote.error && Number(buyQuote.outAmount ?? 0) > 0;
735
+ const impactSevere = quoteUsable && impact >= 0.95;
736
+
737
+ /**
738
+ * NO_DEPTH — the pool advertises depth it does not have.
739
+ *
740
+ * Requires BOTH:
741
+ * • a real route exists (the quote succeeded) and a $1 trade costs
742
+ * ~the whole position (impact ≥ 95%), AND
743
+ * • the on-chain quote-side reserve is genuinely tiny.
744
+ *
745
+ * The second condition is what kills the OpenUSD false positive.
746
+ */
747
+ const noDepth =
748
+ hasDepositEvidence &&
749
+ impactSevere &&
750
+ depositedUsd < 10_000 &&
751
+ claimedLiquidityUsd > 100_000;
752
+
753
+ /**
754
+ * NO_ROUTE — the money IS there, but no router can reach it.
755
+ *
756
+ * This is NOT an accusation against the token: the pool is funded. It is a
757
+ * finding about the ROUTER, and it is exactly the kind of thing an
758
+ * aggregator's bug bounty pays for. We keep it separate from NO_DEPTH so we
759
+ * never call a well-funded pool "fake".
760
+ */
761
+ const noRoute =
762
+ hasDepositEvidence &&
763
+ !quoteUsable &&
764
+ buyQuote?.error != null &&
765
+ depositedUsd >= 10_000 &&
766
+ claimedLiquidityUsd > 100_000;
767
+
768
+ /**
769
+ * DRAINED — the money was there and is gone.
770
+ *
771
+ * Requires a positive signal that money left (a drain event we can point
772
+ * at), not merely a small balance. A pool that was born empty is
773
+ * FAKE_LIQUIDITY; a pool that was robbed is DRAINED, and the receipt
774
+ * should link the transaction that emptied it.
775
+ */
776
+ const soldOut =
777
+ hasDepositEvidence &&
778
+ depositedUsd < 100 &&
779
+ claimedLiquidityUsd > 100_000 &&
780
+ !!curve?.drain;
781
+
782
+ /**
783
+ * FAKE_LIQUIDITY — the advertised liquidity is essentially not there.
784
+ *
785
+ * The hard, on-chain-only test, and it needs BOTH halves:
786
+ *
787
+ * - coverage < 0.5% - less than half a percent of the advertised value
788
+ * is backed by real money in the quote-side vault, AND
789
+ * - deposited < $1,000 - there is not even a dollar's worth of depth, so
790
+ * the pool cannot absorb a single $1 trade.
791
+ *
792
+ * The absolute floor matters as much as the ratio: a ratio alone would
793
+ * equally accuse a $39,000 pool holding $124 (0.3% coverage) AND a
794
+ * $136,000,000 pool holding $23. Both are fake, and they are fake for the
795
+ * same reason, which is "there is no money", not "the ratio is small".
796
+ *
797
+ * Measured on live pools:
798
+ * BAT (native) $136,104,312 claim → $23.53 = 0.000017% → FAKE
799
+ * BAT trap #2 $1,099,765,355 claim → $22.06 = 0.0000020% → FAKE
800
+ * CHZ (fake A) $48,925,026 claim → $9.62 = 0.000019% → FAKE
801
+ * GRASS $242,698 claim → $15,600.34 = 6.43% → THIN
802
+ * YZY $37,992,428 claim → $1,535,634.52 = 4.04% → THIN
803
+ * OUSD $18,741,848 claim → $12,663,732.85 = 67.6% → CONSISTENT
804
+ * JUP $1,571,103 claim → $851,139.75 = 54.2% → CONSISTENT
805
+ *
806
+ * The gap between 0.32% and 4% is more than an order of magnitude wide.
807
+ * Any threshold in between separates the traps from every honest pool we
808
+ * have ever measured, and we chose 0.5% because it is the least
809
+ * aggressive value that still isolates the traps.
810
+ */
811
+ const fake =
812
+ hasDepositEvidence &&
813
+ coverage < 0.005 &&
814
+ depositedUsd < 1_000 &&
815
+ claimedLiquidityUsd > 10_000;
816
+
817
+ /**
818
+ * UNBACKED_LIQUIDITY — the money is not there, but we will not call the
819
+ * token fake.
820
+ *
821
+ * This is the verdict we issue when the liquidity gap is real but the
822
+ * token itself is NOT an impostor — either because we resolved it to the
823
+ * canonical mint, or because we could not resolve the canonical mint at
824
+ * all and therefore refuse to accuse.
825
+ *
826
+ * It is a DIFFERENT claim and it is deliberately weaker:
827
+ *
828
+ * FAKE_LIQUIDITY = "this pool's advertised number is not backed by
829
+ * deposits, and this mint is not the genuine token"
830
+ * UNBACKED_LIQUIDITY = "this pool's advertised number is not backed by
831
+ * deposits" — and nothing about the token's identity
832
+ *
833
+ * We hit exactly this case on the official Chiliz mint
834
+ * (6eftxVbSA…): its Meteora pool advertises $39,099 and holds $124.12 of
835
+ * USDC. The number is wrong, but Chiliz is Chiliz, and a receipt that
836
+ * said "FAKE_LIQUIDITY" there would be a lie about a real project.
837
+ */
838
+ /**
839
+ * Can we issue an accusation against THIS mint?
840
+ *
841
+ * Three independent gates, all of which must open:
842
+ *
843
+ * 1. the canonical index loaded at all — if we do not know what the
844
+ * genuine article is, we do not accuse;
845
+ * 2. this mint is NOT the canonical token — a real project is never
846
+ * accused, its pool may still be reported (UNBACKED_LIQUIDITY);
847
+ * 3. the audited pool is one where the mint is the BASE token — a pool
848
+ * in which the mint is only the counterparty says nothing about the
849
+ * mint's own liquidity.
850
+ */
851
+ const canAccuse =
852
+ canonicalIndexAvailable && !tokenIsCanonical && orientation !== 'quote';
853
+
854
+ /**
855
+ * EVERY verdict that can read as an accusation goes through the SAME gate.
856
+ *
857
+ * This gate used to protect FAKE_LIQUIDITY only. DRAINED and NO_DEPTH were
858
+ * issued without it, which is how the canonical USDB mint
859
+ * (9GV3oZL4p5uGFhtSxS4JsyP64Dqvw4ZuvzgX7FzJ7eTD) ended up in the
860
+ * published dataset as NO_DEPTH on a $500M claim — one real project, one
861
+ * accusation we never meant to make, and exactly the class of mistake this
862
+ * product exists to avoid.
863
+ *
864
+ * The rule is now the rule it always should have been: a verdict that
865
+ * names the token as fake, drained or untradeable is only issued against a
866
+ * mint that is NOT the canonical token, AND only when the canonical index
867
+ * was available, AND only when the audited mint is the base side of the
868
+ * pool. Everything else is a finding about a POOL and is reported as
869
+ * UNBACKED_LIQUIDITY.
870
+ */
871
+ const accusation = fake || soldOut || noDepth;
872
+ const unbacked = accusation && !canAccuse;
873
+
874
+ /**
875
+ * THIN — a fact, not an accusation.
876
+ *
877
+ * Less than 10% of the advertised value is real money. This is NOT proof
878
+ * of wrongdoing: a constant-product AMM naturally becomes one-sided when
879
+ * the price moves, and we measured a perfectly tradable pool at 4%.
880
+ * We publish it because a trader needs to know: "the headline number is
881
+ * mostly inventory, and here is how much is actually cash."
882
+ */
883
+ const thin =
884
+ hasDepositEvidence && coverage < 0.1 && claimedLiquidityUsd > 10_000;
885
+
886
+ let verdict: Verdict = 'UNKNOWN';
887
+ if (!hasDepositEvidence) {
888
+ verdict = 'UNKNOWN';
889
+ } else if (soldOut && canAccuse) {
890
+ verdict = 'DRAINED';
891
+ } else if (fake && canAccuse) {
892
+ verdict = 'FAKE_LIQUIDITY';
893
+ } else if (unbacked) {
894
+ verdict = 'UNBACKED_LIQUIDITY';
895
+ } else if (noDepth && canAccuse) {
896
+ verdict = 'NO_DEPTH';
897
+ } else if (noRoute) {
898
+ verdict = 'NO_ROUTE';
899
+ } else if (thin) {
900
+ verdict = 'THIN';
901
+ } else {
902
+ verdict = 'CONSISTENT';
903
+ }
904
+
905
+ // ── flags: short machine-readable findings ───────────────────────────────
906
+ //
907
+ // A flag is a FACT, never an accusation. CREATOR_LINEAGE says "this mint
908
+ // was deployed by the same wallet as N other tokens" — which is true of
909
+ // every launchpad in the market and is therefore not, by itself, a
910
+ // finding. The accusation lives in the verdict, and it is earned by the
911
+ // on-chain money evidence plus a cited canonical mint.
912
+ const flags: string[] = [];
913
+ if (canonical.status === 'impersonator') {
914
+ // Two levels of impersonation evidence, and the receipt says which:
915
+ // IMPERSONATION — the NAME is already owned by a cited canonical mint
916
+ // TICKER_COLLISION — only the TICKER matched; real, but weaker
917
+ flags.push(canonical.confidence === 'confirmed' ? 'IMPERSONATION' : 'TICKER_COLLISION');
918
+ }
919
+ if (operator) flags.push('CREATOR_LINEAGE');
920
+ if (selfDenominatedPct > 0.99) flags.push('SELF_DENOMINATED');
921
+ if (canonical.status === 'canonical') flags.push('CANONICAL');
922
+
923
+ /**
924
+ * STALE_CLAIM_AFTER_DRAIN — the aggregator is still advertising a pool we
925
+ * can prove was emptied.
926
+ *
927
+ * This is the strongest single signal LIQPROOF produces, because it needs
928
+ * no interpretation: we link the transaction that took the money, and the
929
+ * aggregator is still showing the number. Measured on 2026-12-04 on a
930
+ * Raydium CLMM pool that GeckoTerminal still listed at $1,924,538,558.67
931
+ * eleven hours after a single transaction moved the entire reserve to the
932
+ * pool creator.
933
+ *
934
+ * It is a FACT about the data, not a claim about the token — and it is
935
+ * exactly the shape of thing an aggregator's bug bounty pays for.
936
+ */
937
+ if (curve?.drain && claimedLiquidityUsd > 100_000 && depositedUsd < 100) {
938
+ flags.push('STALE_CLAIM_AFTER_DRAIN');
939
+ }
940
+ if (orientation === 'quote') flags.push('COUNTERPARTY_POOL');
941
+
942
+ const headline = buildHeadline({
943
+ verdict,
944
+ claimedLiquidityUsd,
945
+ depositedUsd,
946
+ coverage,
947
+ divergenceRatio,
948
+ impact,
949
+ executablePriceUsd,
950
+ displayedPriceUsd,
951
+ priceDivergence,
952
+ selfDenominatedPct,
953
+ identityName,
954
+ identitySymbol,
955
+ canonicalName: canonical.impersonates?.name,
956
+ canonicalConfirmed: canonical.confidence === 'confirmed',
957
+ tokenIsCanonical,
958
+ });
959
+
960
+ const summary = buildSummary({
961
+ verdict,
962
+ claimedLiquidityUsd,
963
+ depositedUsd,
964
+ coverage,
965
+ divergenceRatio,
966
+ impact,
967
+ priceDivergence,
968
+ peakDepositedUsd,
969
+ selfDenominatedPct,
970
+ flags,
971
+ tokenIsCanonical,
972
+ });
973
+
974
+ const timelinePoints = (curve?.points ?? []).map((p) => {
975
+ const raw = p.balances[quoteMint] ?? '0';
976
+ const deposited = (Number(raw) / 10 ** quoteDecimals) * quotePriceUsd;
977
+ return {
978
+ at: p.timestamp ? new Date(p.timestamp * 1000).toISOString() : `slot:${p.slot}`,
979
+ slot: p.slot,
980
+ signature: p.signature,
981
+ depositedUsd: deposited,
982
+ deltaUsd: p.deltaUsd,
983
+ note: p.deltaUsd < -100 ? 'LIQUIDITY_REMOVED' : undefined,
984
+ };
985
+ });
986
+
987
+ const evidence: Array<{ kind: string; url: string; label: string }> = [];
988
+ for (const s of snapshots) {
989
+ evidence.push({
990
+ kind: 'pool',
991
+ url: `https://solscan.io/account/${s.pool}`,
992
+ label: `pool ${s.pool}`,
993
+ });
994
+ for (const v of s.vaults) {
995
+ evidence.push({
996
+ kind: 'vault',
997
+ url: `https://solscan.io/account/${v.address}`,
998
+ label: `${v.side} vault ${v.address}`,
999
+ });
1000
+ }
1001
+ }
1002
+ if (curve?.drain) {
1003
+ evidence.push({
1004
+ kind: 'tx',
1005
+ url: `https://solscan.io/tx/${curve.drain.signature}`,
1006
+ label: `drain tx ${curve.drain.signature.slice(0, 12)}…`,
1007
+ });
1008
+ }
1009
+ evidence.push({
1010
+ kind: 'source',
1011
+ url: `https://dexscreener.com/solana/${mint}`,
1012
+ label: 'aggregator claim',
1013
+ });
1014
+
1015
+ // Identity evidence. The metadata account is the token's own statement;
1016
+ // the canonical proof is the receipt for that statement being false.
1017
+ if (meta?.metadataPda) {
1018
+ evidence.push({
1019
+ kind: 'metadata',
1020
+ url: `https://solscan.io/account/${meta.metadataPda}`,
1021
+ label: `on-chain metadata "${meta.name}" / "${meta.symbol}"`,
1022
+ });
1023
+ }
1024
+ if (canonical.impersonates) {
1025
+ evidence.push({
1026
+ kind: 'canonical',
1027
+ url: canonical.impersonates.proof,
1028
+ label: `canonical ${canonical.impersonates.name} (${canonical.impersonates.source})`,
1029
+ });
1030
+ evidence.push({
1031
+ kind: 'canonical-mint',
1032
+ url: `https://solscan.io/account/${canonical.impersonates.mint}`,
1033
+ label: `canonical mint ${canonical.impersonates.mint}`,
1034
+ });
1035
+ }
1036
+ for (const c of meta?.creators ?? []) {
1037
+ evidence.push({
1038
+ kind: 'creator',
1039
+ url: `https://solscan.io/account/${c.address}`,
1040
+ label: `metadata creator ${c.address.slice(0, 12)}…`,
1041
+ });
1042
+ }
1043
+
1044
+ return {
1045
+ version: '1.0',
1046
+ generatedAt: new Date().toISOString(),
1047
+ mint,
1048
+ symbol: identitySymbol || report.symbol,
1049
+ name: identityName || report.name,
1050
+ verdict,
1051
+ headline,
1052
+ summary,
1053
+ identity: {
1054
+ onChainName: meta?.name,
1055
+ onChainSymbol: meta?.symbol,
1056
+ metadataPda: meta?.metadataPda,
1057
+ creators: meta?.creators,
1058
+ canonical: {
1059
+ status: canonical.status,
1060
+ isCanonical: canonical.isCanonical,
1061
+ method: canonical.method,
1062
+ confidence: canonical.confidence,
1063
+ impersonates: canonical.impersonates
1064
+ ? {
1065
+ mint: canonical.impersonates.mint,
1066
+ name: canonical.impersonates.name,
1067
+ symbol: canonical.impersonates.symbol,
1068
+ source: canonical.impersonates.source,
1069
+ proof: canonical.impersonates.proof,
1070
+ proofLabel: canonical.impersonates.proofLabel,
1071
+ }
1072
+ : undefined,
1073
+ },
1074
+ operator: operator
1075
+ ? {
1076
+ creator: operator.creator,
1077
+ link: operator.link,
1078
+ cluster: operator.cluster.id,
1079
+ clusterSize: operator.cluster.members.length,
1080
+ peers: operator.peers,
1081
+ }
1082
+ : undefined,
1083
+ },
1084
+ flags,
1085
+ claimed: {
1086
+ liquidityUsd: claimedLiquidityUsd,
1087
+ priceUsd: displayedPriceUsd,
1088
+ sources: claimSources,
1089
+ },
1090
+ real: {
1091
+ depositedUsd,
1092
+ heldTokens,
1093
+ coverage,
1094
+ divergenceRatio,
1095
+ selfDenominatedPct,
1096
+ peakDepositedUsd,
1097
+ peakAt: peakPoint?.timestamp
1098
+ ? new Date(peakPoint.timestamp * 1000).toISOString()
1099
+ : peakPoint
1100
+ ? `slot:${peakPoint.slot}`
1101
+ : undefined,
1102
+ drainAt: curve?.drain?.timestamp
1103
+ ? new Date(curve.drain.timestamp * 1000).toISOString()
1104
+ : curve?.drain
1105
+ ? `slot:${curve.drain.slot}`
1106
+ : undefined,
1107
+ drainSlot: curve?.drain?.slot,
1108
+ drainSignature: curve?.drain?.signature,
1109
+ drainDeltaUsd: curve?.drain?.deltaUsd,
1110
+ },
1111
+ oracle,
1112
+ timeline: {
1113
+ points: timelinePoints,
1114
+ scanned: curve?.scanned ?? 0,
1115
+ unavailable: curve?.unavailable ?? 0,
1116
+ truncated: curve?.truncated ?? false,
1117
+ strategy: curve?.strategy ?? 'none',
1118
+ totalSignatures: curve?.totalSignatures ?? 0,
1119
+ },
1120
+ pools: snapshots,
1121
+ audited: {
1122
+ pool: focusView?.address ?? '',
1123
+ dexId: focusView?.dexId ?? '',
1124
+ name: focusView?.name ?? '',
1125
+ orientation,
1126
+ counterpartyOnly: orientation === 'quote',
1127
+ candidatePools: views.length,
1128
+ baseSidePools: baseSidePools.length,
1129
+ },
1130
+ evidence,
1131
+ methodology: METHODOLOGY,
1132
+ disclaimer: DISCLAIMER,
1133
+ };
1134
+ }
1135
+
1136
+ function buildHeadline(x: {
1137
+ verdict: Verdict;
1138
+ claimedLiquidityUsd: number;
1139
+ depositedUsd: number;
1140
+ coverage: number;
1141
+ divergenceRatio: number;
1142
+ impact: number;
1143
+ executablePriceUsd?: number;
1144
+ displayedPriceUsd?: number;
1145
+ priceDivergence?: number;
1146
+ selfDenominatedPct: number;
1147
+ identityName?: string;
1148
+ identitySymbol?: string;
1149
+ canonicalName?: string;
1150
+ canonicalConfirmed?: boolean;
1151
+ tokenIsCanonical?: boolean;
1152
+ }): string {
1153
+ switch (x.verdict) {
1154
+ case 'FAKE_LIQUIDITY':
1155
+ if (x.canonicalName && x.canonicalConfirmed) {
1156
+ return `Market claims ${fmtUsd(x.claimedLiquidityUsd)} for "${x.identityName}". The pool holds ${fmtUsd(x.depositedUsd)}. This mint is not ${x.canonicalName}.`;
1157
+ }
1158
+ if (x.selfDenominatedPct > 0.9) {
1159
+ return `${fmtUsd(x.claimedLiquidityUsd)} advertised — but ${pct(x.selfDenominatedPct)} of it is the token itself. Only ${fmtUsd(x.depositedUsd)} is real money.`;
1160
+ }
1161
+ return `Market claims ${fmtUsd(x.claimedLiquidityUsd)}. The pool actually holds ${fmtUsd(x.depositedUsd)}.`;
1162
+ case 'UNBACKED_LIQUIDITY':
1163
+ // A canonical mint gets the plainest possible sentence: the NUMBER is
1164
+ // wrong, the TOKEN is not. The reader must never be able to quote this
1165
+ // receipt as an accusation against a real project.
1166
+ if (x.tokenIsCanonical) {
1167
+ return `${fmtUsd(x.claimedLiquidityUsd)} advertised, ${fmtUsd(x.depositedUsd)} deposited — a finding about this pool, not about the token.`;
1168
+ }
1169
+ return `${fmtUsd(x.claimedLiquidityUsd)} advertised, ${fmtUsd(x.depositedUsd)} deposited — ${Number.isFinite(x.divergenceRatio) ? fmtRatio(x.divergenceRatio) + ' overstated' : 'unbacked'}.`;
1170
+ case 'NO_DEPTH':
1171
+ return `${fmtUsd(x.claimedLiquidityUsd)} claimed, but a $1 buy costs ${(x.impact * 100).toFixed(0)}% of the position.`;
1172
+ case 'DRAINED':
1173
+ return `Pool drained to ${fmtUsd(x.depositedUsd)} while still advertising ${fmtUsd(x.claimedLiquidityUsd)}.`;
1174
+ case 'THIN':
1175
+ return `Only ${pct(x.coverage)} of the claimed ${fmtUsd(x.claimedLiquidityUsd)} is actually deposited.`;
1176
+ case 'CONSISTENT':
1177
+ return `${fmtUsd(x.claimedLiquidityUsd)} claimed, ${fmtUsd(x.depositedUsd)} verified on-chain.`;
1178
+ default:
1179
+ return 'Insufficient on-chain data to form a verdict.';
1180
+ }
1181
+ }
1182
+
1183
+ function buildSummary(x: {
1184
+ verdict: Verdict;
1185
+ claimedLiquidityUsd: number;
1186
+ depositedUsd: number;
1187
+ coverage: number;
1188
+ divergenceRatio: number;
1189
+ impact: number;
1190
+ priceDivergence?: number;
1191
+ peakDepositedUsd?: number;
1192
+ selfDenominatedPct: number;
1193
+ flags: string[];
1194
+ tokenIsCanonical?: boolean;
1195
+ }): string {
1196
+ const parts: string[] = [];
1197
+ parts.push(`claimed ${fmtUsd(x.claimedLiquidityUsd)} vs deposited ${fmtUsd(x.depositedUsd)}`);
1198
+ parts.push(`coverage ${pct(x.coverage)}`);
1199
+ if (x.tokenIsCanonical) {
1200
+ parts.push('canonical token — pool finding only, never an accusation');
1201
+ }
1202
+ if (x.selfDenominatedPct > 0.5) {
1203
+ parts.push(`${pct(x.selfDenominatedPct)} of the claim is the token itself`);
1204
+ }
1205
+ if (Number.isFinite(x.divergenceRatio) && x.divergenceRatio > 1.5) {
1206
+ parts.push(`${fmtRatio(x.divergenceRatio)} overstated`);
1207
+ }
1208
+ if (x.peakDepositedUsd !== undefined && x.peakDepositedUsd > x.depositedUsd * 1.5) {
1209
+ parts.push(`peak ever deposited ${fmtUsd(x.peakDepositedUsd)}`);
1210
+ }
1211
+ parts.push(`buy price impact ${(x.impact * 100).toFixed(0)}%`);
1212
+ if (x.priceDivergence && x.priceDivergence > 10) {
1213
+ parts.push(
1214
+ `displayed price ${Math.round(x.priceDivergence).toLocaleString('en-US')}× the executable price`,
1215
+ );
1216
+ }
1217
+ if (x.flags.length) parts.push(x.flags.join(' + '));
1218
+ return parts.join(' · ');
1219
+ }