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/store.ts ADDED
@@ -0,0 +1,428 @@
1
+ /**
2
+ * store.ts — local "hunting pool" using node:sqlite (built into Node 22).
3
+ * Zero native dependencies, zero hosted database, zero cost.
4
+ */
5
+
6
+ import { createRequire } from 'node:module';
7
+ import { mkdirSync } from 'node:fs';
8
+ import { dirname } from 'node:path';
9
+ import type { DatabaseSync as DatabaseSyncType } from 'node:sqlite';
10
+
11
+ /**
12
+ * `node:sqlite` is loaded LAZILY, on the first Store, through createRequire.
13
+ *
14
+ * A static `import` would link the builtin during the module-linking phase,
15
+ * which happens before any module body runs - so Node's "SQLite is an
16
+ * experimental feature" notice could not be caught by warnings.ts, and it
17
+ * would be printed on every single command, including `liqproof verify`.
18
+ * Loading it on demand means the notice only ever happens when a store is
19
+ * actually opened, and by then the filter is already in place.
20
+ */
21
+ let sqliteCtor: typeof import('node:sqlite').DatabaseSync | null = null;
22
+
23
+ function databaseSync(): typeof import('node:sqlite').DatabaseSync {
24
+ if (!sqliteCtor) {
25
+ const require = createRequire(import.meta.url);
26
+ sqliteCtor = require('node:sqlite').DatabaseSync as typeof DatabaseSyncType;
27
+ }
28
+ return sqliteCtor;
29
+ }
30
+
31
+ /**
32
+ * The verdicts that name the TOKEN.
33
+ *
34
+ * FAKE_LIQUIDITY says "this token's liquidity is fake"; DRAINED says "this
35
+ * token's pool was emptied"; NO_DEPTH says "this token cannot be traded".
36
+ * All three can be read as an accusation against a real project, so all
37
+ * three are protected by exactly one rule: a CANONICAL mint never carries
38
+ * one. It gets UNBACKED_LIQUIDITY, which is a statement about a POOL.
39
+ *
40
+ * THIN, NO_ROUTE and CONSISTENT are measurements, not accusations, and are
41
+ * deliberately NOT in this set.
42
+ */
43
+ const ACCUSATORY_VERDICTS = new Set(['FAKE_LIQUIDITY', 'NO_DEPTH', 'DRAINED']);
44
+
45
+ /** Local money formatter — the store must not depend on the receipt engine. */
46
+ function fmtUsd(n: number): string {
47
+ if (!Number.isFinite(n)) return '$0';
48
+ if (n >= 1_000_000_000) return `$${(n / 1_000_000_000).toFixed(2)}B`;
49
+ if (n >= 1_000_000) return `$${(n / 1_000_000).toFixed(2)}M`;
50
+ if (n >= 1_000) return `$${(n / 1_000).toFixed(2)}K`;
51
+ return `$${n.toFixed(2)}`;
52
+ }
53
+
54
+ export interface TokenRow {
55
+ mint: string;
56
+ symbol?: string;
57
+ first_seen: number;
58
+ last_seen: number;
59
+ verdict?: string;
60
+ claimed_usd?: number;
61
+ deposited_usd?: number;
62
+ coverage?: number;
63
+ price_impact?: number;
64
+ }
65
+
66
+ /** One row of the `receipts` table. */
67
+ export interface ReceiptRow {
68
+ mint: string;
69
+ generated_at: string;
70
+ verdict: string;
71
+ payload: string;
72
+ }
73
+
74
+ export interface EventRow {
75
+ id: number;
76
+ mint: string;
77
+ pool: string;
78
+ slot: number;
79
+ ts: number | null;
80
+ signature: string;
81
+ kind: string;
82
+ delta_usd: number;
83
+ deposited_usd: number;
84
+ }
85
+
86
+ export class Store {
87
+ private db: DatabaseSyncType;
88
+
89
+ constructor(path = '.liqproof/liqproof.db') {
90
+ if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true });
91
+ const DatabaseSync = databaseSync();
92
+ this.db = new DatabaseSync(path);
93
+ this.db.exec('PRAGMA journal_mode = WAL;');
94
+ this.migrate();
95
+ }
96
+
97
+ private migrate(): void {
98
+ this.db.exec(`
99
+ CREATE TABLE IF NOT EXISTS tokens (
100
+ mint TEXT PRIMARY KEY,
101
+ symbol TEXT,
102
+ first_seen INTEGER NOT NULL,
103
+ last_seen INTEGER NOT NULL,
104
+ verdict TEXT,
105
+ claimed_usd REAL,
106
+ deposited_usd REAL,
107
+ coverage REAL,
108
+ price_impact REAL
109
+ );
110
+
111
+ CREATE TABLE IF NOT EXISTS pools (
112
+ address TEXT PRIMARY KEY,
113
+ mint TEXT,
114
+ dex TEXT,
115
+ claimed_usd REAL,
116
+ deposited_usd REAL,
117
+ first_seen INTEGER,
118
+ last_seen INTEGER
119
+ );
120
+
121
+ CREATE TABLE IF NOT EXISTS events (
122
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
123
+ mint TEXT NOT NULL,
124
+ pool TEXT NOT NULL,
125
+ slot INTEGER NOT NULL,
126
+ ts INTEGER,
127
+ signature TEXT NOT NULL,
128
+ kind TEXT NOT NULL,
129
+ delta_usd REAL NOT NULL,
130
+ deposited_usd REAL NOT NULL
131
+ );
132
+
133
+ CREATE TABLE IF NOT EXISTS receipts (
134
+ mint TEXT NOT NULL,
135
+ generated_at TEXT NOT NULL,
136
+ verdict TEXT NOT NULL,
137
+ payload TEXT NOT NULL,
138
+ PRIMARY KEY (mint, generated_at)
139
+ );
140
+
141
+ CREATE INDEX IF NOT EXISTS idx_events_mint ON events(mint);
142
+ CREATE INDEX IF NOT EXISTS idx_tokens_verdict ON tokens(verdict);
143
+ CREATE INDEX IF NOT EXISTS idx_tokens_seen ON tokens(first_seen);
144
+ `);
145
+ }
146
+
147
+ upsertToken(row: TokenRow): void {
148
+ const now = Math.floor(Date.now() / 1000);
149
+ this.db
150
+ .prepare(
151
+ `INSERT INTO tokens (mint, symbol, first_seen, last_seen, verdict, claimed_usd, deposited_usd, coverage, price_impact)
152
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
153
+ ON CONFLICT(mint) DO UPDATE SET
154
+ symbol = COALESCE(excluded.symbol, tokens.symbol),
155
+ last_seen = excluded.last_seen,
156
+ verdict = COALESCE(excluded.verdict, tokens.verdict),
157
+ claimed_usd = COALESCE(excluded.claimed_usd, tokens.claimed_usd),
158
+ deposited_usd = COALESCE(excluded.deposited_usd, tokens.deposited_usd),
159
+ coverage = COALESCE(excluded.coverage, tokens.coverage),
160
+ price_impact = COALESCE(excluded.price_impact, tokens.price_impact)`,
161
+ )
162
+ .run(
163
+ row.mint,
164
+ row.symbol ?? null,
165
+ row.first_seen ?? now,
166
+ row.last_seen ?? now,
167
+ row.verdict ?? null,
168
+ row.claimed_usd ?? null,
169
+ row.deposited_usd ?? null,
170
+ row.coverage ?? null,
171
+ row.price_impact ?? null,
172
+ );
173
+ }
174
+
175
+ upsertPool(
176
+ address: string,
177
+ mint: string,
178
+ dex: string,
179
+ claimedUsd: number,
180
+ depositedUsd: number,
181
+ ): void {
182
+ const now = Math.floor(Date.now() / 1000);
183
+ this.db
184
+ .prepare(
185
+ `INSERT INTO pools (address, mint, dex, claimed_usd, deposited_usd, first_seen, last_seen)
186
+ VALUES (?, ?, ?, ?, ?, ?, ?)
187
+ ON CONFLICT(address) DO UPDATE SET
188
+ mint = excluded.mint,
189
+ dex = excluded.dex,
190
+ claimed_usd = excluded.claimed_usd,
191
+ deposited_usd = excluded.deposited_usd,
192
+ last_seen = excluded.last_seen`,
193
+ )
194
+ .run(address, mint, dex, claimedUsd, depositedUsd, now, now);
195
+ }
196
+
197
+ insertEvent(e: Omit<EventRow, 'id'>): void {
198
+ this.db
199
+ .prepare(
200
+ `INSERT INTO events (mint, pool, slot, ts, signature, kind, delta_usd, deposited_usd)
201
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
202
+ )
203
+ .run(e.mint, e.pool, e.slot, e.ts, e.signature, e.kind, e.delta_usd, e.deposited_usd);
204
+ }
205
+
206
+ /**
207
+ * THE CANONICAL GUARD — applied at STORE time, for every writer.
208
+ *
209
+ * WHY HERE AND NOT ONLY IN THE RECEIPT BUILDER
210
+ *
211
+ * The receipt builder resolves the canonical index and refuses to accuse a
212
+ * canonical mint. That is the first line of defence. It used to be the
213
+ * ONLY line, and the second defence lived inside one mining script
214
+ * (`scripts/backfill.mjs`), which meant every other writer — the CLI
215
+ * `scan`, the MCP server, the verification scripts — could write an
216
+ * accusatory verdict for a real project. It did: the canonical USDB mint
217
+ * (9GV3oZL4p5uGFhtSxS4JsyP64Dqvw4ZuvzgX7FzJ7eTD) reached the published
218
+ * dataset as NO_DEPTH on a $500M claim.
219
+ *
220
+ * So the guard is now a property of the STORE, not of a caller. Whatever
221
+ * a writer passes in, a receipt that says "this mint is canonical" can
222
+ * never be stored with an accusatory verdict. The receipt's own identity
223
+ * block carries the canonical resolution, so this check needs no network
224
+ * access and no new dependency — it is a pure function of the payload.
225
+ *
226
+ * The same check re-reads the payload of every stored receipt, so a row
227
+ * written by an older build is repaired rather than trusted.
228
+ */
229
+ private guardCanonical(
230
+ verdict: string,
231
+ payload: string,
232
+ ): { verdict: string; payload: string; protectedMint: boolean } {
233
+ let parsed: {
234
+ verdict?: string;
235
+ headline?: string;
236
+ summary?: string;
237
+ flags?: string[];
238
+ identity?: { canonical?: Record<string, unknown> };
239
+ claimed?: { liquidityUsd?: number };
240
+ real?: { depositedUsd?: number };
241
+ };
242
+ try {
243
+ parsed = JSON.parse(payload);
244
+ } catch {
245
+ // A payload we cannot parse is left exactly as it is. The store does
246
+ // not destroy data it does not understand.
247
+ return { verdict, payload, protectedMint: false };
248
+ }
249
+
250
+ const identity = parsed.identity ?? {};
251
+ const canonical = identity.canonical ?? {};
252
+ const flags = Array.isArray(parsed.flags) ? parsed.flags : [];
253
+ const isCanonical =
254
+ canonical.isCanonical === true ||
255
+ canonical.status === 'canonical' ||
256
+ flags.includes('CANONICAL');
257
+
258
+ if (!isCanonical || !ACCUSATORY_VERDICTS.has(verdict)) {
259
+ return { verdict, payload, protectedMint: false };
260
+ }
261
+
262
+ const claimed = Number(parsed.claimed?.liquidityUsd ?? 0);
263
+ const deposited = Number(parsed.real?.depositedUsd ?? 0);
264
+
265
+ parsed.verdict = 'UNBACKED_LIQUIDITY';
266
+ parsed.headline =
267
+ `${fmtUsd(claimed)} advertised, ${fmtUsd(deposited)} deposited` +
268
+ ' — a finding about this pool, not about the token.';
269
+ parsed.summary =
270
+ `claimed ${fmtUsd(claimed)} vs deposited ${fmtUsd(deposited)}` +
271
+ ' · canonical token — pool finding only, never an accusation';
272
+ parsed.flags = [...new Set([...flags, 'CANONICAL_PROTECTED'])];
273
+ parsed.identity = {
274
+ ...identity,
275
+ canonical: {
276
+ ...canonical,
277
+ status: 'canonical',
278
+ isCanonical: true,
279
+ confidence: 'confirmed',
280
+ },
281
+ };
282
+
283
+ return {
284
+ verdict: 'UNBACKED_LIQUIDITY',
285
+ payload: JSON.stringify(parsed),
286
+ protectedMint: true,
287
+ };
288
+ }
289
+
290
+ /**
291
+ * Store a receipt — guarded.
292
+ *
293
+ * The verdict that lands in the database is the guarded one, and the
294
+ * denormalised `tokens` row is kept in step with it, because the dashboard
295
+ * and the CSV export read `tokens.verdict`. A row that drifts from its
296
+ * receipt is exactly how an unguarded verdict reaches the published
297
+ * dataset, so it cannot drift.
298
+ */
299
+ saveReceipt(mint: string, generatedAt: string, verdict: string, payload: string): void {
300
+ const guarded = this.guardCanonical(verdict, payload);
301
+ this.db
302
+ .prepare(
303
+ `INSERT OR REPLACE INTO receipts (mint, generated_at, verdict, payload) VALUES (?, ?, ?, ?)`,
304
+ )
305
+ .run(mint, generatedAt, guarded.verdict, guarded.payload);
306
+
307
+ if (guarded.protectedMint) {
308
+ this.db.prepare(`UPDATE tokens SET verdict = ? WHERE mint = ?`).run(guarded.verdict, mint);
309
+ }
310
+ }
311
+
312
+ /**
313
+ * Re-apply the canonical guard to every receipt already in the store.
314
+ *
315
+ * Used to repair rows written by older builds (or by a writer that bypassed
316
+ * the guard). It never touches a receipt whose verdict is already safe,
317
+ * and it never invents a verdict — it only downgrades an accusatory one
318
+ * for a mint that its own payload says is canonical.
319
+ */
320
+ repairCanonicalRows(): { receipts: number; tokens: number } {
321
+ const rows = this.db
322
+ .prepare('SELECT mint, generated_at, verdict, payload FROM receipts')
323
+ .all() as unknown as ReceiptRow[];
324
+
325
+ let repairedReceipts = 0;
326
+ for (const r of rows) {
327
+ const guarded = this.guardCanonical(r.verdict, r.payload);
328
+ if (guarded.verdict === r.verdict && guarded.payload === r.payload) continue;
329
+ this.db
330
+ .prepare(
331
+ 'UPDATE receipts SET verdict = ?, payload = ? WHERE mint = ? AND generated_at = ?',
332
+ )
333
+ .run(guarded.verdict, guarded.payload, r.mint, r.generated_at);
334
+ repairedReceipts++;
335
+ }
336
+
337
+ // The tokens table is denormalised; repair it from the receipts it owns.
338
+ const latestByMint = new Map<string, ReceiptRow>();
339
+ for (const r of this.latestReceipts()) latestByMint.set(r.mint, r);
340
+
341
+ let repairedTokens = 0;
342
+ for (const t of this.allTokens()) {
343
+ if (!ACCUSATORY_VERDICTS.has(t.verdict ?? '')) continue;
344
+ const latest = latestByMint.get(t.mint);
345
+ if (!latest) continue;
346
+ const guarded = this.guardCanonical(t.verdict ?? '', latest.payload);
347
+ if (guarded.verdict === t.verdict) continue;
348
+ this.db.prepare('UPDATE tokens SET verdict = ? WHERE mint = ?').run(guarded.verdict, t.mint);
349
+ repairedTokens++;
350
+ }
351
+
352
+ return { receipts: repairedReceipts, tokens: repairedTokens };
353
+ }
354
+
355
+ getToken(mint: string): TokenRow | undefined {
356
+ return this.db.prepare('SELECT * FROM tokens WHERE mint = ?').get(mint) as TokenRow | undefined;
357
+ }
358
+
359
+ allTokens(): TokenRow[] {
360
+ return this.db.prepare('SELECT * FROM tokens ORDER BY last_seen DESC').all() as unknown as TokenRow[];
361
+ }
362
+
363
+ /**
364
+ * The most recent stored receipt for every mint.
365
+ * Used by the dashboard to recover fields that are not denormalised into
366
+ * the `tokens` table (e.g. the self-denominated percentage).
367
+ */
368
+ latestReceipts(): ReceiptRow[] {
369
+ return this.db
370
+ .prepare(
371
+ `SELECT r.mint, r.generated_at, r.verdict, r.payload
372
+ FROM receipts r
373
+ JOIN (
374
+ SELECT mint, MAX(generated_at) AS latest
375
+ FROM receipts
376
+ GROUP BY mint
377
+ ) m ON m.mint = r.mint AND m.latest = r.generated_at
378
+ ORDER BY r.generated_at DESC`,
379
+ )
380
+ .all() as unknown as ReceiptRow[];
381
+ }
382
+
383
+ eventsFor(mint: string, limit = 200): EventRow[] {
384
+ return this.db
385
+ .prepare('SELECT * FROM events WHERE mint = ? ORDER BY slot DESC LIMIT ?')
386
+ .all(mint, limit) as unknown as EventRow[];
387
+ }
388
+
389
+ counts(): { tokens: number; events: number; receipts: number } {
390
+ const t = this.db.prepare('SELECT COUNT(*) AS n FROM tokens').get() as { n: number };
391
+ const e = this.db.prepare('SELECT COUNT(*) AS n FROM events').get() as { n: number };
392
+ const r = this.db.prepare('SELECT COUNT(*) AS n FROM receipts').get() as { n: number };
393
+ return { tokens: t.n, events: e.n, receipts: r.n };
394
+ }
395
+
396
+ /** Survival statistics: what fraction of tokens still have real liquidity. */
397
+ survival(): {
398
+ total: number;
399
+ byVerdict: Record<string, number>;
400
+ fake: number;
401
+ consistent: number;
402
+ coverageAvg: number;
403
+ } {
404
+ const rows = this.allTokens();
405
+ const byVerdict: Record<string, number> = {};
406
+ let coverageSum = 0;
407
+ let coverageN = 0;
408
+ for (const r of rows) {
409
+ const v = r.verdict ?? 'UNKNOWN';
410
+ byVerdict[v] = (byVerdict[v] ?? 0) + 1;
411
+ if (typeof r.coverage === 'number' && Number.isFinite(r.coverage)) {
412
+ coverageSum += r.coverage;
413
+ coverageN++;
414
+ }
415
+ }
416
+ return {
417
+ total: rows.length,
418
+ byVerdict,
419
+ fake: (byVerdict.FAKE_LIQUIDITY ?? 0) + (byVerdict.NO_DEPTH ?? 0) + (byVerdict.DRAINED ?? 0),
420
+ consistent: byVerdict.CONSISTENT ?? 0,
421
+ coverageAvg: coverageN ? coverageSum / coverageN : 0,
422
+ };
423
+ }
424
+
425
+ close(): void {
426
+ this.db.close();
427
+ }
428
+ }