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
@@ -0,0 +1,1063 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * backfill.mjs — grow the LIQPROOF dataset.
4
+ *
5
+ * WHAT THIS DOES
6
+ * 1. Pulls the broadest free universe that exists without a key:
7
+ * A. CoinGecko's whole coin list with platform addresses
8
+ * (`include_platform=true`) → every Solana mint it knows
9
+ * (~7,000) in ONE request;
10
+ * B. DexScreener's boost + profile feeds (a token that PAYS for a
11
+ * boost needs a big liquidity number to look good, so this feed
12
+ * is structurally enriched with inflated claims);
13
+ * C. GeckoTerminal's `new_pools` and `trending_pools`, paginated.
14
+ * 2. Scores every candidate with the CHEAP suspicion metric that this
15
+ * project already validated:
16
+ *
17
+ * suspicion = claimed_liquidity / (24h_volume + 1000)
18
+ *
19
+ * A pool advertising $38,000,000 that traded $1,761 yesterday scores
20
+ * 21,000× higher than one advertising the same and traded $18,500,000.
21
+ * 3. Audits only the top-N candidates (default 150) with the REAL receipt
22
+ * logic — the same code path `liqproof receipt <mint>` uses — and
23
+ * appends the results to the sqlite store, so `out/dataset.csv` and
24
+ * `out/index.html` grow with every run.
25
+ * 4. Writes a human-readable run summary to `data/dataset-summary.md`.
26
+ *
27
+ * ── THE CANONICAL GUARD (read this before changing anything) ────────────────
28
+ *
29
+ * A mint that resolves as CANONICAL is a real project. It must NEVER be
30
+ * recorded as an accusation. We already shipped this bug once: the
31
+ * official Chiliz mint was about to be labelled a fake. So:
32
+ *
33
+ * • every receipt is re-resolved against the canonical index here,
34
+ * independently of the receipt's own resolution;
35
+ * • if the mint is canonical, an accusatory verdict (FAKE_LIQUIDITY,
36
+ * NO_DEPTH, DRAINED) is DOWNGRADED to UNBACKED_LIQUIDITY, which is a
37
+ * statement about the POOL and never about the TOKEN;
38
+ * • the number of protected mints is printed in the summary, so the
39
+ * guard is visible instead of invisible.
40
+ *
41
+ * COST: zero. HTTP only for discovery; the Solana RPC is touched once per
42
+ * audited candidate and never for a candidate that did not make the
43
+ * cut.
44
+ */
45
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
46
+ import path from 'node:path';
47
+ import { fileURLToPath, pathToFileURL } from 'node:url';
48
+ import { spawnSync } from 'node:child_process';
49
+
50
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
51
+ const ROOT = path.resolve(HERE, '..');
52
+
53
+ // node:sqlite emits an ExperimentalWarning on Node 22. It is harmless, but
54
+ // it would pollute CI logs, so we drop the default warning printer and keep
55
+ // every warning that is not about SQLite.
56
+ process.removeAllListeners('warning');
57
+ process.on('warning', (w) => {
58
+ if (w?.name === 'ExperimentalWarning') return;
59
+ console.warn(w);
60
+ });
61
+
62
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
63
+
64
+ // ── CLI ──────────────────────────────────────────────────────────────────────
65
+
66
+ function parseArgs(argv) {
67
+ const out = {};
68
+ for (const a of argv) {
69
+ if (!a.startsWith('--')) continue;
70
+ const eq = a.indexOf('=');
71
+ if (eq === -1) out[a.slice(2)] = true;
72
+ else out[a.slice(2, eq)] = a.slice(eq + 1);
73
+ }
74
+ return out;
75
+ }
76
+
77
+ const args = parseArgs(process.argv.slice(2));
78
+
79
+ const CFG = {
80
+ top: Number(args.top ?? 150),
81
+ pages: Number(args.pages ?? 2),
82
+ feed: String(args.feed ?? 'all'),
83
+ dryRun: !!args['dry-run'],
84
+ minClaimed: Number(args['min-claimed'] ?? 10_000),
85
+ universeLimit: Number(args['universe-limit'] ?? 0),
86
+ curve: !!args.curve,
87
+ txs: Number(args.txs ?? 120),
88
+ db: args.db ? path.resolve(String(args.db)) : path.join(ROOT, '.liqproof', 'liqproof.db'),
89
+ outDir: args.out ? path.resolve(String(args.out)) : path.join(ROOT, 'out'),
90
+ summaryPath: args.summary ? path.resolve(String(args.summary)) : path.join(ROOT, 'data', 'dataset-summary.md'),
91
+ exportDataset: args['no-export'] ? false : true,
92
+ verbose: !!args.verbose,
93
+ };
94
+
95
+ /** Verdict buckets that accuse a TOKEN of being fake. */
96
+ const ACCUSATORY = new Set(['FAKE_LIQUIDITY', 'NO_DEPTH', 'DRAINED']);
97
+
98
+ // ── formatting ───────────────────────────────────────────────────────────────
99
+
100
+ function usd(n) {
101
+ if (!Number.isFinite(n)) return 'n/a';
102
+ const abs = Math.abs(n);
103
+ if (abs >= 1_000_000_000) return `$${(n / 1_000_000_000).toFixed(2)}B`;
104
+ if (abs >= 1_000_000) return `$${(n / 1_000_000).toFixed(2)}M`;
105
+ if (abs >= 1_000) return `$${(n / 1_000).toFixed(2)}K`;
106
+ if (abs >= 1) return `$${n.toFixed(2)}`;
107
+ return `$${n.toFixed(4)}`;
108
+ }
109
+
110
+ function pct(n) {
111
+ if (!Number.isFinite(n)) return 'n/a';
112
+ if (n === 0) return '0%';
113
+ if (n < 0.0001) return `${(n * 100).toPrecision(3)}%`;
114
+ return `${(n * 100).toFixed(2)}%`;
115
+ }
116
+
117
+ function plainNumber(n) {
118
+ if (n === null || n === undefined || !Number.isFinite(n)) return '';
119
+ const s = String(n);
120
+ if (!/[eE]/.test(s)) return s;
121
+ const m = /^(-?)(\d+(?:\.\d+)?)[eE]([+-]?\d+)$/.exec(s);
122
+ if (!m) return s;
123
+ const sign = m[1];
124
+ const num = Number(`${m[2]}e${m[3]}`);
125
+ return sign + num.toFixed(20).replace(/0+$/, '').replace(/\.$/, '');
126
+ }
127
+
128
+ // ── project modules ──────────────────────────────────────────────────────────
129
+
130
+ let src = null;
131
+ async function loadSrc() {
132
+ if (src) return src;
133
+ const missing = ['rpc.js', 'receipt.js', 'store.js', 'sources.js', 'canonical.js', 'util.js'].filter(
134
+ (f) => !existsSync(path.join(ROOT, 'dist', f)),
135
+ );
136
+ if (missing.length) {
137
+ console.error(`\n dist/ is missing (${missing.join(', ')}). Build it first:\n npm run build\n`);
138
+ process.exit(1);
139
+ }
140
+ const [rpc, receipt, store, sources, canonical, util] = await Promise.all([
141
+ import('../dist/rpc.js'),
142
+ import('../dist/receipt.js'),
143
+ import('../dist/store.js'),
144
+ import('../dist/sources.js'),
145
+ import('../dist/canonical.js'),
146
+ import('../dist/util.js'),
147
+ ]);
148
+ src = { rpc, receipt, store, sources, canonical, util };
149
+ return src;
150
+ }
151
+
152
+ // ── DexScreener batch reader (30 mints per call, rate-limited, cached) ──────
153
+
154
+ /**
155
+ * DexScreener accepts up to 30 addresses per call, which turns a
156
+ * 7,000-mint universe into 235 HTTP requests instead of 7,000.
157
+ *
158
+ * We space those requests 230 ms apart (≈260 req/min, inside their
159
+ * 300 req/min) and cache every chunk on disk for six hours, so a re-run
160
+ * costs ZERO requests and a rate-limited run still serves the last good
161
+ * answer instead of pretending the token has no pools.
162
+ */
163
+ async function dsPairsBatched(mints, { chunk = 30, sleepMs = 230 } = {}) {
164
+ const { util } = await loadSrc();
165
+ const cache = new util.DiskCache(6 * 60 * 60_000, path.join(ROOT, '.liqproof', 'cache'));
166
+ const out = [];
167
+ let requests = 0;
168
+
169
+ for (let i = 0; i < mints.length; i += chunk) {
170
+ const part = mints.slice(i, i + chunk);
171
+ const key = `ds:batch:${part.join(',')}`;
172
+ let arr = cache.get(key);
173
+ if (!arr) {
174
+ try {
175
+ arr = await util.fetchJson(
176
+ `https://api.dexscreener.com/tokens/v1/solana/${part.join(',')}`,
177
+ { retries: 4, timeoutMs: 30_000 },
178
+ );
179
+ cache.set(key, arr);
180
+ requests++;
181
+ } catch {
182
+ const stale = cache.getStale(key);
183
+ arr = stale?.value ?? [];
184
+ }
185
+ await sleep(sleepMs);
186
+ }
187
+ for (const p of arr ?? []) {
188
+ if (!p?.pairAddress) continue;
189
+ out.push({
190
+ address: p.pairAddress,
191
+ dexId: p.dexId ?? '',
192
+ reportedLiquidityUsd: Number(p.liquidity?.usd ?? 0),
193
+ reportedVolume24hUsd: Number(p.volume?.h24 ?? 0),
194
+ baseTokenAddress: p.baseToken?.address ?? '',
195
+ baseTokenSymbol: p.baseToken?.symbol ?? '',
196
+ quoteTokenAddress: p.quoteToken?.address ?? '',
197
+ quoteTokenSymbol: p.quoteToken?.symbol ?? '',
198
+ basePriceUsd: Number(p.priceUsd ?? 0),
199
+ source: 'dexscreener',
200
+ });
201
+ }
202
+ if (i % (chunk * 20) === 0 && i > 0) {
203
+ process.stdout.write(` dex pairs ${Math.min(i, mints.length)}/${mints.length}\n`);
204
+ }
205
+ }
206
+ return { pools: out, requests };
207
+ }
208
+
209
+ // ── universe collection ──────────────────────────────────────────────────────
210
+
211
+ /**
212
+ * Collect every candidate pool, keyed by mint.
213
+ *
214
+ * Returns `{ pools, mintsSeen, stats }` where each pool carries the claim
215
+ * (advertised liquidity) and the 24h volume that together produce the
216
+ * suspicion score.
217
+ */
218
+ export async function collectUniverse(opts = {}) {
219
+ const { sources } = await loadSrc();
220
+ const feed = opts.feed ?? CFG.feed;
221
+ const pages = opts.pages ?? CFG.pages;
222
+ const universeLimit = opts.universeLimit ?? CFG.universeLimit;
223
+
224
+ const byMint = new Map(); // mint -> { mint, pools: Map(address -> pool) }
225
+ const stats = { mintsSeen: 0, dexRequests: 0, sources: [] };
226
+
227
+ /**
228
+ * Merge a pool row into the index.
229
+ *
230
+ * The same pool is often reported by more than one source, and the rows
231
+ * disagree: one knows the volume, the other knows the pool address. We
232
+ * keep the HIGHEST liquidity claim (the number most favourable to the
233
+ * token, so every accusation is made against the strongest claim) and the
234
+ * HIGHEST volume seen, and we keep every non-empty identity field.
235
+ *
236
+ * One exception: a LIVE row (one that carries a volume) always wins the
237
+ * claim over a registry row. The registry remembers what a pool claimed
238
+ * when we convicted it; the aggregator remembers what it claims NOW. A
239
+ * receipt must measure the present, so the live number is the one that
240
+ * goes into the receipt.
241
+ */
242
+ const addPool = (mint, pool) => {
243
+ if (!mint || !pool?.address) return;
244
+ let entry = byMint.get(mint);
245
+ if (!entry) {
246
+ entry = { mint, pools: new Map() };
247
+ byMint.set(mint, entry);
248
+ }
249
+ const prev = entry.pools.get(pool.address);
250
+ if (!prev) {
251
+ entry.pools.set(pool.address, { ...pool, sources: [pool.source].filter(Boolean) });
252
+ return;
253
+ }
254
+ const prevLive = (prev.reportedVolume24hUsd ?? 0) > 0;
255
+ const nextLive = (pool.reportedVolume24hUsd ?? 0) > 0;
256
+ const claim =
257
+ prevLive && !nextLive
258
+ ? prev.reportedLiquidityUsd
259
+ : nextLive && !prevLive
260
+ ? pool.reportedLiquidityUsd
261
+ : Math.max(prev.reportedLiquidityUsd ?? 0, pool.reportedLiquidityUsd ?? 0);
262
+ const merged = {
263
+ ...prev,
264
+ ...pool,
265
+ reportedLiquidityUsd: claim,
266
+ reportedVolume24hUsd: Math.max(prev.reportedVolume24hUsd ?? 0, pool.reportedVolume24hUsd ?? 0),
267
+ baseTokenAddress: prev.baseTokenAddress || pool.baseTokenAddress,
268
+ baseTokenSymbol: prev.baseTokenSymbol || pool.baseTokenSymbol,
269
+ quoteTokenAddress: prev.quoteTokenAddress || pool.quoteTokenAddress,
270
+ quoteTokenSymbol: prev.quoteTokenSymbol || pool.quoteTokenSymbol,
271
+ basePriceUsd: prev.basePriceUsd || pool.basePriceUsd,
272
+ quotePriceUsd: prev.quotePriceUsd || pool.quotePriceUsd,
273
+ dexId: prev.dexId || pool.dexId,
274
+ sources: [...new Set([...(prev.sources ?? []), pool.source].filter(Boolean))],
275
+ };
276
+ entry.pools.set(pool.address, merged);
277
+ };
278
+
279
+ const useUniverse = feed === 'universe' || feed === 'all';
280
+ const useDiscovery = feed === 'boosts' || feed === 'profiles' || feed === 'all';
281
+ const usePools = feed === 'pools' || feed === 'trending' || feed === 'all';
282
+
283
+ // ── A0. the seeds we already proved ─────────────────────────────────────
284
+ //
285
+ // A token that impersonates a real project is NOT in CoinGecko's platform
286
+ // map — that is precisely what makes it a fake. So the blind universe can
287
+ // never find them on its own. The mints we have already PROVEN (in
288
+ // `data/verified-impersonators.json` and `data/impersonators.json`) are
289
+ // therefore seeded into every run: they are the highest-suspicion tokens
290
+ // in the market by construction, and re-auditing them is what turns the
291
+ // dataset into a longitudinal record instead of a snapshot.
292
+ const seedMints = [];
293
+ const seedPools = [];
294
+ for (const file of ['verified-impersonators.json', 'impersonators.json']) {
295
+ const p = path.join(ROOT, 'data', file);
296
+ if (!existsSync(p)) continue;
297
+ try {
298
+ const j = JSON.parse(readFileSync(p, 'utf8'));
299
+ const list = j.results ?? j.provenImpersonators ?? [];
300
+ for (const r of list) {
301
+ if (!r?.mint) continue;
302
+ seedMints.push(r.mint);
303
+ // The registry knows the pool and the claim even when DexScreener
304
+ // has already dropped the pair. Keep it: a proven fake that lost
305
+ // its DexScreener listing is EXACTLY the case we must keep auditing.
306
+ const claimed = Number(r.claimed ?? r.liquidity ?? 0);
307
+ if (r.pool && claimed > 0) {
308
+ seedPools.push({
309
+ address: r.pool,
310
+ dexId: '',
311
+ reportedLiquidityUsd: claimed,
312
+ reportedVolume24hUsd: 0,
313
+ baseTokenAddress: r.mint,
314
+ baseTokenSymbol: r.symbol ?? '',
315
+ quoteTokenAddress:
316
+ (r.vaults ?? []).find((v) => v.side === 'quote')?.mint ?? '',
317
+ quoteTokenSymbol: '',
318
+ basePriceUsd: 0,
319
+ source: 'verified-impersonators',
320
+ });
321
+ }
322
+ }
323
+ } catch {
324
+ /* a malformed registry must not kill the run */
325
+ }
326
+ }
327
+ const uniqueSeeds = [...new Set(seedMints)];
328
+ for (const pool of seedPools) addPool(pool.baseTokenAddress, pool);
329
+ if (uniqueSeeds.length) {
330
+ stats.sources.push(`seeds:${uniqueSeeds.length}`);
331
+ console.log(` seeds ${uniqueSeeds.length} previously-proven mints`);
332
+ }
333
+
334
+ // ── A. the blind universe (CoinGecko platform map, one request) ──────────
335
+ const universeMints = [];
336
+ if (useUniverse) {
337
+ try {
338
+ const platforms = await sources.coingeckoSolanaPlatforms();
339
+ const mints = [...new Set(platforms.values())];
340
+ const limited = universeLimit > 0 ? mints.slice(0, universeLimit) : mints;
341
+ universeMints.push(...limited);
342
+ stats.sources.push(`coingecko:${limited.length}`);
343
+ console.log(` universe ${limited.length} Solana mints`);
344
+ } catch (err) {
345
+ console.log(` universe failed: ${err.message}`);
346
+ }
347
+ }
348
+
349
+ // ── B. DexScreener discovery feeds ──────────────────────────────────────
350
+ const discoveryMints = [];
351
+ const discoveryFeeds = feed === 'profiles' ? ['profiles_latest'] : ['boosts_top', 'boosts_latest', 'profiles_latest'];
352
+ if (useDiscovery) {
353
+ for (const f of discoveryFeeds) {
354
+ try {
355
+ const tokens = await sources.dexscreenerDiscovery(f);
356
+ let n = 0;
357
+ for (const t of tokens) {
358
+ if (t.chainId && t.chainId !== 'solana') continue;
359
+ discoveryMints.push(t.mint);
360
+ n++;
361
+ }
362
+ stats.sources.push(`${f}:${n}`);
363
+ console.log(` discovery ${f.padEnd(16)} ${String(n).padStart(4)} mints`);
364
+ await sleep(250);
365
+ } catch (err) {
366
+ console.log(` discovery ${f} failed: ${err.message}`);
367
+ }
368
+ }
369
+ }
370
+
371
+ // ── C. GeckoTerminal pool feeds (these carry the pool address directly) ─
372
+ if (usePools) {
373
+ const poolFeeds = [
374
+ ['new_pools', (p) => sources.geckoTerminalNewPools(p), pages],
375
+ ['trending_pools', (p) => sources.geckoTerminalTrendingPools(p), Math.max(1, Math.floor(pages / 2))],
376
+ ];
377
+ for (const [name, fn, count] of poolFeeds) {
378
+ try {
379
+ let total = 0;
380
+ for (let p = 1; p <= count; p++) {
381
+ const pools = await fn(p);
382
+ for (const pool of pools) {
383
+ if (!pool.baseTokenAddress) continue;
384
+ addPool(pool.baseTokenAddress, {
385
+ address: pool.address,
386
+ dexId: pool.dexId ?? '',
387
+ reportedLiquidityUsd: Number(pool.reportedLiquidityUsd ?? 0),
388
+ reportedVolume24hUsd: Number(pool.reportedVolume24hUsd ?? 0),
389
+ baseTokenAddress: pool.baseTokenAddress,
390
+ baseTokenSymbol: pool.baseTokenSymbol ?? '',
391
+ quoteTokenAddress: pool.quoteTokenAddress ?? '',
392
+ quoteTokenSymbol: pool.quoteTokenSymbol ?? '',
393
+ basePriceUsd: Number(pool.basePriceUsd ?? 0),
394
+ quotePriceUsd: Number(pool.quotePriceUsd ?? 0),
395
+ source: 'geckoterminal',
396
+ createdAt: pool.createdAt,
397
+ });
398
+ }
399
+ total += pools.length;
400
+ await sleep(250);
401
+ }
402
+ stats.sources.push(`${name}:${total}`);
403
+ console.log(` pools ${name.padEnd(16)} ${String(total).padStart(4)} pools`);
404
+ } catch (err) {
405
+ console.log(` pools ${name} failed: ${err.message}`);
406
+ }
407
+ }
408
+ }
409
+
410
+ // ── D. score every candidate mint ───────────────────────────────────────
411
+ // The claim and the volume both come from DexScreener's pair list, which
412
+ // is why the universe mints are read in 30-mint batches.
413
+ const needPairs = [...new Set([...universeMints, ...discoveryMints, ...seedMints])].filter(Boolean);
414
+
415
+ if (needPairs.length) {
416
+ console.log(` dex pairs ${needPairs.length} mints in ${Math.ceil(needPairs.length / 30)} batches …`);
417
+ const { pools, requests } = await dsPairsBatched(needPairs);
418
+ stats.dexRequests += requests;
419
+ for (const pool of pools) {
420
+ addPool(pool.baseTokenAddress, pool);
421
+ }
422
+ console.log(` dex pairs ${pools.length} pools (${requests} HTTP requests)`);
423
+ }
424
+
425
+ // ── E. rank by suspicion ────────────────────────────────────────────────
426
+ //
427
+ // suspicion = claimed_liquidity / (24h_volume + floor)
428
+ //
429
+ // A pool advertising $38,000,000 that traded $1,761 yesterday scores 21,000×
430
+ // higher than one advertising the same and traded $18,500,000. That single
431
+ // ratio is what turned a sweep that found nothing into a sweep that finds
432
+ // the traps.
433
+ const FLOOR = 1000;
434
+ const candidates = [];
435
+ for (const entry of byMint.values()) {
436
+ let best = null;
437
+ for (const pool of entry.pools.values()) {
438
+ const score = pool.reportedLiquidityUsd / Math.max(pool.reportedVolume24hUsd, FLOOR);
439
+ if (!best || score > best.score) best = { pool, score };
440
+ }
441
+ if (!best) continue;
442
+ if (best.pool.reportedLiquidityUsd < CFG.minClaimed) continue;
443
+ candidates.push({
444
+ mint: entry.mint,
445
+ pool: best.pool,
446
+ score: best.score,
447
+ claimedUsd: best.pool.reportedLiquidityUsd,
448
+ volume24hUsd: best.pool.reportedVolume24hUsd,
449
+ seeded: uniqueSeeds.includes(entry.mint),
450
+ });
451
+ }
452
+ candidates.sort((a, b) => b.score - a.score);
453
+
454
+ stats.mintsSeen = byMint.size;
455
+ return { candidates, mintsSeen: byMint.size, stats, seededMints: uniqueSeeds };
456
+ }
457
+
458
+ // ── the canonical guard ──────────────────────────────────────────────────────
459
+
460
+ /**
461
+ * Re-resolve a mint against the canonical index and make sure a real
462
+ * project is never recorded as an accusation.
463
+ *
464
+ * This runs INDEPENDENTLY of the receipt's own resolution: if the two ever
465
+ * disagree we take the SAFE answer (treat it as canonical, downgrade the
466
+ * verdict). A false accusation costs the product its credibility; a missed
467
+ * headline costs it one tweet.
468
+ */
469
+ export function applyCanonicalGuard(receipt, index) {
470
+ if (!src) throw new Error('applyCanonicalGuard called before loadSrc()');
471
+ const identity = receipt.identity ?? {};
472
+ const name = identity.onChainName ?? receipt.name ?? '';
473
+ const symbol = identity.onChainSymbol ?? receipt.symbol ?? '';
474
+ const resolution = index
475
+ ? src.canonical.resolveCanonical(receipt.mint, { name, symbol }, index)
476
+ : null;
477
+
478
+ const receiptStatus = identity.canonical?.status ?? 'unresolved';
479
+ const resolvedStatus = resolution?.status ?? receiptStatus;
480
+ // The safe reading of a disagreement is "canonical".
481
+ const status = resolvedStatus === 'canonical' || receiptStatus === 'canonical' ? 'canonical' : resolvedStatus;
482
+
483
+ const out = { ...receipt };
484
+ let protectedMint = false;
485
+ let downgraded = false;
486
+
487
+ if (status === 'canonical') {
488
+ protectedMint = true;
489
+ if (ACCUSATORY.has(out.verdict)) {
490
+ const claimed = out.claimed?.liquidityUsd ?? 0;
491
+ const deposited = out.real?.depositedUsd ?? 0;
492
+ const ratio = deposited > 0 ? claimed / deposited : Infinity;
493
+ out.verdict = 'UNBACKED_LIQUIDITY';
494
+ out.headline =
495
+ `${usd(claimed)} advertised, ${usd(deposited)} deposited` +
496
+ (Number.isFinite(ratio) ? ` — ${ratio.toLocaleString('en-US', { maximumFractionDigits: 0 })}× overstated.` : ' — unbacked.');
497
+ out.summary =
498
+ `claimed ${usd(claimed)} vs deposited ${usd(deposited)} · coverage ${pct(out.real?.coverage ?? 0)} · ` +
499
+ `CANONICAL mint — reported as UNBACKED_LIQUIDITY, never as an accusation`;
500
+ out.flags = [...new Set([...(out.flags ?? []), 'CANONICAL_PROTECTED'])];
501
+ downgraded = true;
502
+ }
503
+ out.identity = {
504
+ ...identity,
505
+ canonical: {
506
+ ...(identity.canonical ?? {}),
507
+ status: 'canonical',
508
+ isCanonical: true,
509
+ method: resolution?.method ?? identity.canonical?.method ?? 'canonical',
510
+ confidence: 'confirmed',
511
+ },
512
+ };
513
+ }
514
+
515
+ return { receipt: out, protectedMint, downgraded, status, resolution };
516
+ }
517
+
518
+ // ── audit ────────────────────────────────────────────────────────────────────
519
+
520
+ /**
521
+ * Choose which candidates to audit.
522
+ *
523
+ * The ranking is by suspicion, but the seeds (mints we have already PROVEN
524
+ * are impersonators) are not allowed to be crowded out by a lucky draw from
525
+ * the live feeds. They are the backbone of the dataset and the only way to
526
+ * show a finding SURVIVING across days, so they get a reserved share of the
527
+ * budget; the rest goes to the highest-suspicion fresh candidates.
528
+ */
529
+ export function selectCandidates(candidates, limit, seedShare = 0.34) {
530
+ const seeds = candidates.filter((c) => c.seeded);
531
+ const fresh = candidates.filter((c) => !c.seeded);
532
+ const seedBudget = Math.min(seeds.length, Math.max(1, Math.floor(limit * seedShare)));
533
+ const chosen = [...seeds.slice(0, seedBudget)];
534
+ const chosenMints = new Set(chosen.map((c) => c.mint));
535
+ for (const c of fresh) {
536
+ if (chosen.length >= limit) break;
537
+ if (chosenMints.has(c.mint)) continue;
538
+ chosen.push(c);
539
+ chosenMints.add(c.mint);
540
+ }
541
+ // If the seeds did not fill their share, top the list up with fresh ones.
542
+ for (const c of fresh) {
543
+ if (chosen.length >= limit) break;
544
+ if (chosenMints.has(c.mint)) continue;
545
+ chosen.push(c);
546
+ chosenMints.add(c.mint);
547
+ }
548
+ return chosen;
549
+ }
550
+
551
+ /**
552
+ * Count the RPC calls per method.
553
+ *
554
+ * `RpcPool` only reports a total, but the free-tier limits are PER METHOD,
555
+ * so the only way to state an honest budget is to count them here. We wrap
556
+ * the pool in a proxy: `call` / `tryCall` / `callDetailed` all take the RPC
557
+ * method as their first argument, and `batch` takes a list of
558
+ * `{ method }` calls — so every JSON-RPC method that leaves the process is
559
+ * tallied under its real name.
560
+ */
561
+ function countMethods(rpc) {
562
+ const byMethod = {};
563
+ const bump = (method, n = 1) => {
564
+ byMethod[method] = (byMethod[method] ?? 0) + n;
565
+ };
566
+ const wrap = (target) =>
567
+ new Proxy(target, {
568
+ get(obj, prop) {
569
+ const value = obj[prop];
570
+ if (typeof value !== 'function') return value;
571
+ if (prop === 'batch') {
572
+ return (...args) => {
573
+ for (const call of args[0] ?? []) bump(call?.method);
574
+ return value.apply(obj, args);
575
+ };
576
+ }
577
+ if (prop === 'call' || prop === 'tryCall' || prop === 'callDetailed') {
578
+ return (...args) => {
579
+ bump(args[0]);
580
+ return value.apply(obj, args);
581
+ };
582
+ }
583
+ return (...args) => value.apply(obj, args);
584
+ },
585
+ });
586
+ return { rpc: wrap(rpc), byMethod };
587
+ }
588
+
589
+ /**
590
+ * Audit the top-N candidates with the real receipt logic.
591
+ *
592
+ * The receipt is the SAME code path the CLI uses, so a dataset row and a
593
+ * published receipt can never disagree.
594
+ */
595
+ export async function auditCandidates(candidates, opts = {}) {
596
+ const { rpc: rpcMod, receipt: receiptMod, store: storeMod, canonical } = await loadSrc();
597
+ const limit = opts.limit ?? CFG.top;
598
+ const pool = new rpcMod.RpcPool({
599
+ verbose: false,
600
+ onEvent: (e) => {
601
+ if (!CFG.verbose) return;
602
+ if (e.kind === 'rotate') console.log(` rpc rotate ${e.endpoint} (${e.reason})`);
603
+ if (e.kind === 'throttle') console.log(` rpc throttle ${e.method} ${e.waitMs}ms`);
604
+ if (e.kind === 'rpc429') console.log(` rpc 429 ${e.method}`);
605
+ },
606
+ });
607
+
608
+ const index = await canonical.loadCanonicalIndex().catch(() => null);
609
+ const indexSize = index?.entries?.length ?? 0;
610
+
611
+ const { rpc: counted, byMethod } = countMethods(pool);
612
+
613
+ const store = opts.store ?? new storeMod.Store(CFG.db);
614
+ const results = [];
615
+ const counts = {};
616
+ let protectedCount = 0;
617
+ let downgradedCount = 0;
618
+ let failures = 0;
619
+
620
+ const list = selectCandidates(candidates, limit, opts.seedShare);
621
+ console.log(
622
+ `▸ auditing ${list.length} candidates (${list.filter((c) => c.seeded).length} proven seeds · canonical index: ${indexSize} entries)`,
623
+ );
624
+
625
+ for (let i = 0; i < list.length; i++) {
626
+ const cand = list[i];
627
+ const label = (cand.pool.baseTokenSymbol || cand.mint.slice(0, 12)).slice(0, 14);
628
+ process.stdout.write(` ${String(i + 1).padStart(3)}. ${label.padEnd(14)} `);
629
+ try {
630
+ const raw = await receiptMod.buildReceipt(counted, cand.mint, {
631
+ includeCurve: CFG.curve,
632
+ maxTransactions: CFG.txs,
633
+ focusPool: cand.pool.address,
634
+ focusPoolData: cand.pool,
635
+ });
636
+
637
+ const guarded = applyCanonicalGuard(raw, index);
638
+ const r = guarded.receipt;
639
+
640
+ if (guarded.protectedMint) protectedCount++;
641
+ if (guarded.downgraded) {
642
+ downgradedCount++;
643
+ console.log(` [canonical guard] ${cand.mint} → UNBACKED_LIQUIDITY`);
644
+ }
645
+
646
+ counts[r.verdict] = (counts[r.verdict] ?? 0) + 1;
647
+
648
+ if (!CFG.dryRun) {
649
+ const now = Math.floor(Date.now() / 1000);
650
+ store.upsertToken({
651
+ mint: r.mint,
652
+ symbol: r.symbol,
653
+ first_seen: now,
654
+ last_seen: now,
655
+ verdict: r.verdict,
656
+ claimed_usd: r.claimed.liquidityUsd,
657
+ deposited_usd: r.real.depositedUsd,
658
+ coverage: r.real.coverage,
659
+ price_impact: r.oracle.buyQuote?.priceImpactPct,
660
+ });
661
+ for (const p of r.pools) {
662
+ store.upsertPool(p.pool, r.mint, p.dexId, p.claimedLiquidityUsd, p.realQuoteUsd);
663
+ if (r.real.drainSignature) {
664
+ store.insertEvent({
665
+ mint: r.mint,
666
+ pool: p.pool,
667
+ slot: r.real.drainSlot ?? 0,
668
+ ts: r.real.drainAt ? Math.floor(Date.parse(r.real.drainAt) / 1000) : null,
669
+ signature: r.real.drainSignature,
670
+ kind: 'LIQUIDITY_REMOVED',
671
+ delta_usd: r.real.drainDeltaUsd ?? 0,
672
+ deposited_usd: p.realQuoteUsd,
673
+ });
674
+ }
675
+ }
676
+ store.saveReceipt(r.mint, r.generatedAt, r.verdict, JSON.stringify(r));
677
+ }
678
+
679
+ results.push({
680
+ mint: r.mint,
681
+ symbol: r.symbol,
682
+ name: r.name,
683
+ verdict: r.verdict,
684
+ claimedUsd: r.claimed.liquidityUsd,
685
+ depositedUsd: r.real.depositedUsd,
686
+ coverage: r.real.coverage,
687
+ selfDenominatedPct: r.real.selfDenominatedPct,
688
+ priceImpact: r.oracle.buyQuote?.priceImpactPct ?? null,
689
+ canonicalStatus: guarded.status,
690
+ canonicalName: r.identity.canonical?.impersonates?.name ?? null,
691
+ canonicalProof: r.identity.canonical?.impersonates?.proof ?? null,
692
+ pool: r.pools[0]?.pool ?? cand.pool.address,
693
+ score: cand.score,
694
+ firstSeenIso: new Date().toISOString(),
695
+ lastSeenIso: new Date().toISOString(),
696
+ protected: guarded.protectedMint,
697
+ downgraded: guarded.downgraded,
698
+ });
699
+
700
+ console.log(
701
+ `${r.verdict.padEnd(18)} claimed=${usd(r.claimed.liquidityUsd).padStart(11)} deposited=${usd(r.real.depositedUsd).padStart(11)} cov=${pct(r.real.coverage).padStart(10)}`,
702
+ );
703
+ } catch (err) {
704
+ failures++;
705
+ counts.ERROR = (counts.ERROR ?? 0) + 1;
706
+ console.log(`ERROR ${String(err.message).slice(0, 60)}`);
707
+ }
708
+ if ((i + 1) % 10 === 0) {
709
+ console.log(` … ${i + 1}/${list.length} · rpc calls ${pool.stats.calls} · 429 ${pool.stats.rpc429}`);
710
+ }
711
+ }
712
+
713
+ if (!opts.store) store.close();
714
+
715
+ return {
716
+ results,
717
+ counts,
718
+ protectedCount,
719
+ downgradedCount,
720
+ failures,
721
+ indexSize,
722
+ rpcStats: { ...pool.stats, byMethod },
723
+ };
724
+ }
725
+
726
+ // ── summary ──────────────────────────────────────────────────────────────────
727
+
728
+ /**
729
+ * `data/dataset-summary.md` has two machine-editable regions:
730
+ *
731
+ * <!-- LIQPROOF:BACKFILL:BEGIN --> … <!-- LIQPROOF:BACKFILL:END -->
732
+ * the latest backfill run — rewritten every time
733
+ * <!-- LIQPROOF:REFRESH:BEGIN --> … <!-- LIQPROOF:REFRESH:END -->
734
+ * one dated entry per daily refresh — appended, one per day
735
+ *
736
+ * The backfill owns the first region, the daily refresh owns the second,
737
+ * and neither ever destroys the other's work. That is what makes both
738
+ * scripts idempotent and re-runnable.
739
+ */
740
+ const MARK_BACKFILL = ['<!-- LIQPROOF:BACKFILL:BEGIN -->', '<!-- LIQPROOF:BACKFILL:END -->'];
741
+ const MARK_REFRESH = ['<!-- LIQPROOF:REFRESH:BEGIN -->', '<!-- LIQPROOF:REFRESH:END -->'];
742
+
743
+ function readSummaryFile() {
744
+ if (!existsSync(CFG.summaryPath)) return '';
745
+ try {
746
+ return readFileSync(CFG.summaryPath, 'utf8');
747
+ } catch {
748
+ return '';
749
+ }
750
+ }
751
+
752
+ /** Replace the text between two markers, keeping everything outside. */
753
+ function replaceRegion(text, [begin, end], body) {
754
+ const i = text.indexOf(begin);
755
+ const j = text.indexOf(end);
756
+ if (i === -1 || j === -1 || j < i) {
757
+ // No region yet — append it.
758
+ return `${text.trimEnd()}\n\n${begin}\n${body}\n${end}\n`;
759
+ }
760
+ return `${text.slice(0, i + begin.length)}\n${body}\n${text.slice(j)}`;
761
+ }
762
+
763
+ /**
764
+ * Write `data/dataset-summary.md`.
765
+ *
766
+ * The table columns are a STRICT SUPERSET of `out/dataset.csv`:
767
+ * mint, symbol, verdict, claimed_usd, deposited_usd, coverage,
768
+ * self_denominated_pct, price_impact, first_seen_iso, last_seen_iso
769
+ * plus the canonical resolution, the canonical proof URL, the pool and the
770
+ * suspicion score. A reader who has the CSV can read this file and know
771
+ * strictly more.
772
+ */
773
+ export function writeSummary(summary) {
774
+ const {
775
+ generatedAt,
776
+ durationSeconds,
777
+ mintsSeen,
778
+ audited,
779
+ counts,
780
+ results,
781
+ protectedCount,
782
+ downgradedCount,
783
+ failures,
784
+ indexSize,
785
+ stats,
786
+ rpcStats,
787
+ feed,
788
+ } = summary;
789
+
790
+ const totalClaimed = results.reduce((s, r) => s + (r.claimedUsd || 0), 0);
791
+ const totalDeposited = results.reduce((s, r) => s + (r.depositedUsd || 0), 0);
792
+ const overallCoverage = totalClaimed > 0 ? totalDeposited / totalClaimed : 0;
793
+ const overstatement = totalDeposited > 0 ? totalClaimed / totalDeposited : Infinity;
794
+
795
+ const adverse = results
796
+ .filter((r) => r.verdict !== 'CONSISTENT' && r.verdict !== 'UNKNOWN')
797
+ .sort((a, b) => (b.claimedUsd || 0) - (a.claimedUsd || 0));
798
+
799
+ const lines = [];
800
+ lines.push(`Generated ${generatedAt} · run ${durationSeconds.toFixed(1)}s · feed \`${feed}\``);
801
+ lines.push('');
802
+ lines.push('## Run');
803
+ lines.push('');
804
+ lines.push(`- **mints seen**: ${mintsSeen}`);
805
+ lines.push(`- **mints audited**: ${audited}`);
806
+ lines.push(`- **errors**: ${failures}`);
807
+ lines.push(`- **universe sources**: ${(stats?.sources ?? []).join(', ') || 'none'}`);
808
+ lines.push(`- **free HTTP requests (DexScreener)**: ${stats?.dexRequests ?? 0}`);
809
+ lines.push(`- **Solana RPC calls**: ${rpcStats?.calls ?? 0} · 429s ${rpcStats?.rpc429 ?? 0}`);
810
+ lines.push('');
811
+ lines.push('### RPC calls by method');
812
+ lines.push('');
813
+ lines.push('| method | calls | free-tier limit |');
814
+ lines.push('| --- | ---: | --- |');
815
+ const LIMITS = {
816
+ getSlot: '150 / 10 s',
817
+ getAccountInfo: '50 / 10 s',
818
+ getMultipleAccounts: '50 / 10 s (100 addresses each)',
819
+ getTokenAccountsByOwner: '10 / 10 s',
820
+ getSignaturesForAddress: '10 / 10 s',
821
+ getTransaction: '10 / 10 s',
822
+ };
823
+ const methods = Object.entries(rpcStats?.byMethod ?? {}).sort((a, b) => b[1] - a[1]);
824
+ if (!methods.length) {
825
+ lines.push('| _(none)_ | 0 | — |');
826
+ }
827
+ for (const [m, n] of methods) {
828
+ lines.push(`| \`${m}\` | ${n} | ${LIMITS[m] ?? '—'} |`);
829
+ }
830
+ lines.push('');
831
+ lines.push('## Verdicts');
832
+ lines.push('');
833
+ lines.push('| verdict | count |');
834
+ lines.push('| --- | ---: |');
835
+ for (const [v, n] of Object.entries(counts).sort((a, b) => b[1] - a[1])) {
836
+ lines.push(`| ${v} | ${n} |`);
837
+ }
838
+ lines.push('');
839
+ lines.push('## Advertised vs deposited');
840
+ lines.push('');
841
+ lines.push(`- **total advertised**: ${usd(totalClaimed)}`);
842
+ lines.push(`- **total deposited**: ${usd(totalDeposited)}`);
843
+ lines.push(`- **overall coverage**: ${pct(overallCoverage)}`);
844
+ lines.push(
845
+ `- **overstatement**: ${Number.isFinite(overstatement) ? overstatement.toLocaleString('en-US', { maximumFractionDigits: 0 }) + '×' : '∞'}`,
846
+ );
847
+ lines.push('');
848
+ lines.push('## False-positive guard');
849
+ lines.push('');
850
+ lines.push(`- **canonical index entries**: ${indexSize}`);
851
+ lines.push(`- **canonical mints protected**: ${protectedCount}`);
852
+ lines.push(`- **verdicts downgraded to UNBACKED_LIQUIDITY**: ${downgradedCount}`);
853
+ lines.push(
854
+ `- **accusations issued against a canonical mint**: 0 — the guard downgrades every one of them before the receipt is stored.`,
855
+ );
856
+ lines.push('');
857
+ lines.push('## Top findings');
858
+ lines.push('');
859
+ lines.push(
860
+ '| mint | symbol | verdict | claimed_usd | deposited_usd | coverage | self_denominated_pct | price_impact | canonical | canonical_proof | pool | suspicion | first_seen_iso | last_seen_iso |',
861
+ );
862
+ lines.push(
863
+ '| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | --- | --- | --- | ---: | --- | --- |',
864
+ );
865
+ for (const r of adverse.slice(0, 10)) {
866
+ lines.push(
867
+ `| ${r.mint} | ${r.symbol ?? ''} | ${r.verdict} | ${plainNumber(r.claimedUsd)} | ${plainNumber(r.depositedUsd)} | ${plainNumber(r.coverage)} | ${plainNumber((r.selfDenominatedPct ?? 0) * 100)} | ${plainNumber(r.priceImpact)} | ${r.canonicalStatus}${r.canonicalName ? ` (${r.canonicalName})` : ''} | ${r.canonicalProof ?? ''} | ${r.pool} | ${plainNumber(r.score)} | ${r.firstSeenIso} | ${r.lastSeenIso} |`,
868
+ );
869
+ }
870
+ if (!adverse.length) lines.push('| — | — | — | — | — | — | — | — | — | — | — | — | — | — |');
871
+ lines.push('');
872
+ lines.push('---');
873
+ lines.push('');
874
+ lines.push(
875
+ 'Read-only on-chain measurements. No gas, no paid APIs, no chain mutation. LIQPROOF reports measurements, not investment advice.',
876
+ );
877
+ lines.push('');
878
+
879
+ const body = lines.join('\n');
880
+ mkdirSync(path.dirname(CFG.summaryPath), { recursive: true });
881
+
882
+ // Keep whatever the daily refresh has appended; replace only our region.
883
+ let text = readSummaryFile();
884
+ if (!text.trim()) {
885
+ text = '# LIQPROOF dataset summary\n';
886
+ }
887
+ if (!text.includes(MARK_BACKFILL[0])) {
888
+ text = `${text.trimEnd()}\n\n${MARK_BACKFILL[0]}\n${MARK_BACKFILL[1]}\n`;
889
+ }
890
+ text = replaceRegion(text, MARK_BACKFILL, body);
891
+
892
+ // The refresh region may not exist yet — make sure it does, so the daily
893
+ // refresh always has a place to write.
894
+ if (!text.includes(MARK_REFRESH[0])) {
895
+ text = `${text.trimEnd()}\n\n${MARK_REFRESH[0]}\n_(no daily refresh yet)_\n${MARK_REFRESH[1]}\n`;
896
+ }
897
+
898
+ writeFileSync(CFG.summaryPath, text);
899
+ return { totalClaimed, totalDeposited, overallCoverage, overstatement, adverse };
900
+ }
901
+
902
+ /**
903
+ * Append (or replace) one dated daily-refresh entry in the summary file.
904
+ *
905
+ * The daily refresh does NOT rewrite the backfill's section: it only ever
906
+ * touches its own dated entry, so running it twice on the same day is
907
+ * idempotent and running it never destroys the backfill's detail.
908
+ */
909
+ export function appendRefreshSummary(entry) {
910
+ let text = readSummaryFile();
911
+ if (!text.trim()) text = '# LIQPROOF dataset summary\n';
912
+ if (!text.includes(MARK_REFRESH[0])) {
913
+ text = `${text.trimEnd()}\n\n${MARK_REFRESH[0]}\n${MARK_REFRESH[1]}\n`;
914
+ }
915
+ const i = text.indexOf(MARK_REFRESH[0]);
916
+ const j = text.indexOf(MARK_REFRESH[1]);
917
+ let inner = text.slice(i + MARK_REFRESH[0].length, j).trim();
918
+ if (inner === '_(no daily refresh yet)_') inner = '';
919
+
920
+ // Remove any previous entry for this date (idempotent re-run).
921
+ const marker = `### ${entry.date}`;
922
+ const parts = inner.split(/\n(?=### \d{4}-\d{2}-\d{2})/).filter(Boolean);
923
+ const kept = parts.filter((p) => !p.trimStart().startsWith(marker));
924
+
925
+ const lines = [];
926
+ lines.push(`### ${entry.date}`);
927
+ lines.push('');
928
+ lines.push(`- **findings**: ${entry.findings} (previous snapshot: ${entry.prevFindings})`);
929
+ lines.push(`- **new findings**: ${entry.newFindings}`);
930
+ lines.push(`- **resolved findings**: ${entry.resolvedFindings}`);
931
+ lines.push(`- **newly audited mints**: ${entry.newMints}`);
932
+ lines.push(`- **coverage changes**: ${entry.coverageChanges}`);
933
+ lines.push(`- **pools polled**: ${entry.poolsPolled}`);
934
+ lines.push(`- **liquidity events**: ${entry.events} (${entry.sudden} sudden)`);
935
+ lines.push(`- **findings surviving >1 snapshot**: ${entry.persistent}`);
936
+ if (entry.longest > 1) {
937
+ lines.push(
938
+ `- **longest survival run**: ${entry.longest} snapshot(s) — the claim has been false for that long, on-chain`,
939
+ );
940
+ }
941
+ if (entry.newFindingRows?.length) {
942
+ lines.push('');
943
+ lines.push('| verdict | symbol | mint | claimed_usd | deposited_usd | coverage |');
944
+ lines.push('| --- | --- | --- | ---: | ---: | ---: |');
945
+ for (const r of entry.newFindingRows) {
946
+ lines.push(
947
+ `| ${r.verdict} | ${r.symbol ?? ''} | ${r.mint} | ${plainNumber(r.claimedUsd)} | ${plainNumber(r.depositedUsd)} | ${plainNumber(r.coverage)} |`,
948
+ );
949
+ }
950
+ }
951
+ lines.push('');
952
+
953
+ kept.push(lines.join('\n'));
954
+ const merged = kept.join('\n').trim();
955
+ text = `${text.slice(0, i + MARK_REFRESH[0].length)}\n${merged}\n${text.slice(j)}`;
956
+ mkdirSync(path.dirname(CFG.summaryPath), { recursive: true });
957
+ writeFileSync(CFG.summaryPath, text);
958
+ }
959
+
960
+ // ── export the dataset ───────────────────────────────────────────────────────
961
+
962
+ /**
963
+ * Regenerate `out/dataset.csv` + `out/index.html` from the store.
964
+ *
965
+ * We call the project's own CLI so the published dataset is byte-identical
966
+ * to what `npm run export` produces — there is no second, divergent export
967
+ * path.
968
+ */
969
+ function exportDataset() {
970
+ const cli = path.join(ROOT, 'dist', 'cli.js');
971
+ if (!existsSync(cli)) {
972
+ console.log(' export skipped (dist/cli.js missing — run npm run build)');
973
+ return false;
974
+ }
975
+ const res = spawnSync(process.execPath, [cli, 'export', '--out=' + CFG.outDir], {
976
+ cwd: ROOT,
977
+ stdio: 'inherit',
978
+ });
979
+ if (res.status !== 0) {
980
+ console.log(` export failed (exit ${res.status})`);
981
+ return false;
982
+ }
983
+ return true;
984
+ }
985
+
986
+ // ── main ─────────────────────────────────────────────────────────────────────
987
+
988
+ export async function runBackfill(opts = {}) {
989
+ const started = Date.now();
990
+ console.log('▸ LIQPROOF BACKFILL');
991
+ console.log(
992
+ ` feed=${opts.feed ?? CFG.feed} top=${opts.top ?? CFG.top} pages=${opts.pages ?? CFG.pages} dry-run=${CFG.dryRun}`,
993
+ );
994
+
995
+ const { candidates, mintsSeen, stats } = await collectUniverse(opts);
996
+ console.log(`▸ ${mintsSeen} mints seen · ${candidates.length} above $${CFG.minClaimed.toLocaleString()}`);
997
+
998
+ if (CFG.dryRun) {
999
+ const preview = selectCandidates(candidates, Math.min(candidates.length, opts.top ?? CFG.top));
1000
+ console.log('\n top candidates by suspicion (claim ÷ volume):');
1001
+ for (const c of preview.slice(0, Math.min(30, preview.length))) {
1002
+ console.log(
1003
+ ` ${String(Math.round(c.score)).padStart(10)}× ${usd(c.claimedUsd).padStart(12)} vol ${usd(c.volume24hUsd).padStart(12)} ${(c.pool.baseTokenSymbol || c.mint.slice(0, 14)).padEnd(14).slice(0, 14)} ${c.pool.address.slice(0, 12)}…${c.seeded ? ' [seed]' : ''}`,
1004
+ );
1005
+ }
1006
+ const n = preview.length;
1007
+ // The ratio is MEASURED, not guessed: one receipt costs 3 getAccountInfo,
1008
+ // 1 getSignaturesForAddress, 1 getTransaction and 1 getMultipleAccounts
1009
+ // (see the "RPC calls by method" table in the summary).
1010
+ console.log(
1011
+ ` dry run: ${n} receipts would cost roughly ${n * 6} RPC calls ` +
1012
+ `(≈${n * 3} getAccountInfo, ≈${n} getSignaturesForAddress, ≈${n} getTransaction, ≈${n} getMultipleAccounts).`,
1013
+ );
1014
+ console.log(
1015
+ ` at the free-tier ceilings (getSignaturesForAddress / getTransaction: 10 per 10 s) ` +
1016
+ `the bottleneck alone needs ≈${(n / 1).toFixed(0)} s of wall clock.`,
1017
+ );
1018
+ console.log(` done in ${((Date.now() - started) / 1000).toFixed(1)}s — nothing was written.`);
1019
+ return { dryRun: true, candidates, mintsSeen, stats, durationSeconds: (Date.now() - started) / 1000 };
1020
+ }
1021
+
1022
+ const audit = await auditCandidates(candidates, { limit: opts.top ?? CFG.top });
1023
+
1024
+ const summary = {
1025
+ generatedAt: new Date().toISOString(),
1026
+ durationSeconds: (Date.now() - started) / 1000,
1027
+ mintsSeen,
1028
+ audited: audit.results.length,
1029
+ counts: audit.counts,
1030
+ results: audit.results,
1031
+ protectedCount: audit.protectedCount,
1032
+ downgradedCount: audit.downgradedCount,
1033
+ failures: audit.failures,
1034
+ indexSize: audit.indexSize,
1035
+ stats,
1036
+ rpcStats: audit.rpcStats,
1037
+ feed: opts.feed ?? CFG.feed,
1038
+ };
1039
+
1040
+ const totals = writeSummary(summary);
1041
+ console.log(
1042
+ `\n audited ${audit.results.length} · ${audit.protectedCount} canonical protected · ${audit.downgradedCount} downgraded · ${audit.failures} errors`,
1043
+ );
1044
+ console.log(` advertised ${usd(totals.totalClaimed)} vs deposited ${usd(totals.totalDeposited)} (${pct(totals.overallCoverage)})`);
1045
+ console.log(` wrote ${CFG.summaryPath}`);
1046
+
1047
+ if (CFG.exportDataset) {
1048
+ console.log('▸ exporting dataset');
1049
+ exportDataset();
1050
+ }
1051
+
1052
+ return { ...summary, ...totals };
1053
+ }
1054
+
1055
+ const invokedDirectly =
1056
+ process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url;
1057
+
1058
+ if (invokedDirectly) {
1059
+ runBackfill().catch((err) => {
1060
+ console.error(`\n fatal: ${err?.stack ?? err}`);
1061
+ process.exit(1);
1062
+ });
1063
+ }