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,951 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * survival-miner.mjs — watch tracked pools and publish liquidity SURVIVAL /
4
+ * DRAIN receipts over time.
5
+ *
6
+ * WHAT THIS DOES
7
+ * 1. Builds the TRACKED SET from two places we already trust:
8
+ * A. the local sqlite store (`.liqproof/liqproof.db`, table `pools`)
9
+ * — every pool LIQPROOF has ever audited;
10
+ * B. `data/verified-impersonators.json` — every pool we have already
11
+ * convicted, which are exactly the pools worth watching for the
12
+ * moment the money leaves.
13
+ * 2. Every poll reads the QUOTE-SIDE vault balance of every tracked pool
14
+ * straight from the chain and converts it to USD. After the first poll
15
+ * the vault addresses are known, so a poll is ONE `getMultipleAccounts`
16
+ * call per 100 pools — the cheapest read the chain offers.
17
+ * 3. Compares each reading with the previous one and emits:
18
+ * LIQUIDITY_REMOVED — the deposit fell by more than the threshold
19
+ * (default: 20% relative OR $1,000 absolute,
20
+ * whichever is SMALLER, so small pools need a
21
+ * small absolute drop and huge pools need a
22
+ * small relative one).
23
+ * LIQUIDITY_RESTORED — the deposit came back by more than 50% of the
24
+ * amount that had been removed.
25
+ * A fall of more than 50% inside ONE poll interval is flagged SUDDEN:
26
+ * that is the drain signature, and for a sudden fall we go back to the
27
+ * chain and name the transaction that emptied the pool.
28
+ * 4. Appends one row per pool per poll to `data/survival-timeline.json`.
29
+ *
30
+ * WHY IT EXISTS
31
+ * A receipt is a snapshot: it proves what one pool looked like at one
32
+ * moment. The product's real claim is longitudinal — "we watched this pool
33
+ * and the money left" — and that claim only has evidence if somebody keeps
34
+ * watching. This script is that somebody. It is the difference between a
35
+ * scanner and a forensic record.
36
+ *
37
+ * COST: zero. One free public RPC batch per poll, plus keyless HTTP for
38
+ * prices and claims. No gas, no signing, no wallet, ever.
39
+ *
40
+ * USAGE
41
+ * node scripts/survival-miner.mjs --once
42
+ * node scripts/survival-miner.mjs --every=15m --limit=25
43
+ * node scripts/survival-miner.mjs --pool=<pool address> --once
44
+ * node scripts/survival-miner.mjs --mint=<mint> --once
45
+ *
46
+ * FLAGS
47
+ * --pool=<address> watch only this pool
48
+ * --mint=<mint> watch only the pools of this mint
49
+ * --every=15m poll interval (s / m / h / d)
50
+ * --once one sweep, then exit
51
+ * --limit=N watch at most N pools per sweep
52
+ * --out=<path> timeline file (default data/survival-timeline.json)
53
+ * --db=<path> sqlite store (default .liqproof/liqproof.db)
54
+ * --rel-drop=0.2 relative drop threshold (default 0.2)
55
+ * --abs-drop=1000 absolute drop threshold in USD (default 1000)
56
+ * --restore=0.5 restore threshold, fraction of the loss (default 0.5)
57
+ * --no-signature never look up drain transaction signatures
58
+ */
59
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
60
+ import path from 'node:path';
61
+ import { fileURLToPath, pathToFileURL } from 'node:url';
62
+
63
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
64
+ const ROOT = path.resolve(HERE, '..');
65
+
66
+ // node:sqlite emits an ExperimentalWarning on Node 22. It is harmless, but
67
+ // it would pollute CI logs, so we drop the default warning printer and keep
68
+ // every warning that is not about SQLite.
69
+ process.removeAllListeners('warning');
70
+ process.on('warning', (w) => {
71
+ if (w?.name === 'ExperimentalWarning') return;
72
+ console.warn(w);
73
+ });
74
+
75
+ // ── tiny helpers ─────────────────────────────────────────────────────────────
76
+
77
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
78
+
79
+ function parseArgs(argv) {
80
+ const out = {};
81
+ for (const a of argv) {
82
+ if (!a.startsWith('--')) continue;
83
+ const eq = a.indexOf('=');
84
+ if (eq === -1) out[a.slice(2)] = true;
85
+ else out[a.slice(2, eq)] = a.slice(eq + 1);
86
+ }
87
+ return out;
88
+ }
89
+
90
+ function parseDuration(input) {
91
+ const s = String(input ?? '').trim().toLowerCase();
92
+ const m = /^(\d+(?:\.\d+)?)\s*(s|m|h|d)?$/.exec(s);
93
+ if (!m) return 15 * 60_000;
94
+ const n = Number(m[1]);
95
+ const unit = m[2] ?? 'm';
96
+ const mult = unit === 's' ? 1000 : unit === 'h' ? 3_600_000 : unit === 'd' ? 86_400_000 : 60_000;
97
+ return Math.max(1000, n * mult);
98
+ }
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
+ // ── configuration ────────────────────────────────────────────────────────────
118
+
119
+ const args = parseArgs(process.argv.slice(2));
120
+
121
+ const CFG = {
122
+ out: args.out ? path.resolve(String(args.out)) : path.join(ROOT, 'data', 'survival-timeline.json'),
123
+ db: args.db ? path.resolve(String(args.db)) : path.join(ROOT, '.liqproof', 'liqproof.db'),
124
+ everyMs: parseDuration(args.every ?? '15m'),
125
+ limit: args.limit ? Math.max(1, Number(args.limit)) : Infinity,
126
+ relDrop: Number(args['rel-drop'] ?? 0.2),
127
+ absDrop: Number(args['abs-drop'] ?? 1000),
128
+ restoreFrac: Number(args.restore ?? 0.5),
129
+ once: !!args.once,
130
+ poolFilter: args.pool ? String(args.pool) : null,
131
+ mintFilter: args.mint ? String(args.mint) : null,
132
+ wantSignature: !args['no-signature'],
133
+ verbose: !!args.verbose,
134
+ };
135
+
136
+ const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
137
+ const WSOL = 'So11111111111111111111111111111111111111112';
138
+
139
+ // ── RPC client with explicit per-method token buckets ───────────────────────
140
+ //
141
+ // MEASURED FREE-TIER LIMITS (authoritative, 10 second window):
142
+ //
143
+ // getSlot 150 / 10s
144
+ // getAccountInfo 50 / 10s
145
+ // getMultipleAccounts 50 / 10s (up to 100 addresses per call)
146
+ // getTokenAccountsByOwner 10 / 10s (indexed method)
147
+ // getSignaturesForAddress 10 / 10s
148
+ // getTransaction 10 / 10s (the hard bottleneck)
149
+ //
150
+ // The buckets below are deliberately set BELOW the published ceilings so a
151
+ // shared IP (CI runners, NAT, an office) never trips the limiter. Every
152
+ // method gets its OWN bucket: the node meters per method, so a budget spent
153
+ // on `getMultipleAccounts` never eats into `getTransaction`'s budget.
154
+ //
155
+ // We also never send `commitment` — several methods answer HTTP 413 when it
156
+ // is present — and `getProgramAccounts` is banned outright (375 MB payload).
157
+ const BUCKET_LIMITS = {
158
+ getSlot: 140,
159
+ getAccountInfo: 45,
160
+ getMultipleAccounts: 40,
161
+ getTokenAccountsByOwner: 9,
162
+ getSignaturesForAddress: 9,
163
+ getTransaction: 9,
164
+ };
165
+
166
+ const ENDPOINTS = {
167
+ mainnet: 'https://api.mainnet-beta.solana.com',
168
+ tatum: 'https://solana-mainnet.gateway.tatum.io',
169
+ };
170
+
171
+ // Which endpoint may serve which method (measured):
172
+ // tatum: getTokenAccountsByOwner and getSignaturesForAddress are PAID ONLY
173
+ // tatum: getTransaction works but is throttled to ~5 req/min
174
+ // so those three methods go to mainnet only.
175
+ const METHOD_ENDPOINTS = {
176
+ getSlot: ['mainnet', 'tatum'],
177
+ getAccountInfo: ['mainnet', 'tatum'],
178
+ getMultipleAccounts: ['mainnet', 'tatum'],
179
+ getTokenAccountsByOwner: ['mainnet'],
180
+ getSignaturesForAddress: ['mainnet'],
181
+ getTransaction: ['mainnet'],
182
+ };
183
+
184
+ class TokenBucket {
185
+ constructor(limit, windowMs = 10_000) {
186
+ this.limit = limit;
187
+ this.windowMs = windowMs;
188
+ this.stamps = [];
189
+ }
190
+
191
+ async take(n = 1) {
192
+ for (;;) {
193
+ const now = Date.now();
194
+ while (this.stamps.length && now - this.stamps[0] >= this.windowMs) this.stamps.shift();
195
+ if (this.stamps.length + n <= this.limit) {
196
+ for (let i = 0; i < n; i++) this.stamps.push(now);
197
+ return;
198
+ }
199
+ const waitMs = this.windowMs - (now - this.stamps[0]) + 25;
200
+ await sleep(Math.max(40, waitMs));
201
+ }
202
+ }
203
+ }
204
+
205
+ class MinerRpc {
206
+ constructor() {
207
+ this.buckets = new Map();
208
+ this.stats = { calls: 0, byMethod: {}, http429: 0, retries: 0 };
209
+ this.id = 1;
210
+ this.blocked = new Map();
211
+ }
212
+
213
+ bucket(method) {
214
+ let b = this.buckets.get(method);
215
+ if (!b) {
216
+ b = new TokenBucket(BUCKET_LIMITS[method] ?? 8);
217
+ this.buckets.set(method, b);
218
+ }
219
+ return b;
220
+ }
221
+
222
+ async call(method, params = []) {
223
+ await this.bucket(method).take(1);
224
+ const hosts = METHOD_ENDPOINTS[method] ?? ['mainnet'];
225
+ let lastErr = null;
226
+
227
+ for (let attempt = 0; attempt <= 5; attempt++) {
228
+ const host = hosts[attempt % hosts.length];
229
+ const endpoint = ENDPOINTS[host];
230
+ const blockedUntil = this.blocked.get(endpoint) ?? 0;
231
+ if (blockedUntil > Date.now()) await sleep(blockedUntil - Date.now() + 25);
232
+
233
+ try {
234
+ const res = await fetch(endpoint, {
235
+ method: 'POST',
236
+ headers: {
237
+ 'content-type': 'application/json',
238
+ accept: 'application/json',
239
+ 'user-agent': 'liqproof-survival-miner/0.1 (+read-only on-chain receipts)',
240
+ },
241
+ body: JSON.stringify({ jsonrpc: '2.0', id: this.id++, method, params }),
242
+ });
243
+
244
+ if (res.status === 429) {
245
+ this.stats.http429++;
246
+ const retryAfter = Number(res.headers.get('retry-after') ?? 0);
247
+ const wait = retryAfter > 0 ? retryAfter * 1000 : 750 * 2 ** attempt;
248
+ this.blocked.set(endpoint, Date.now() + wait);
249
+ await sleep(wait);
250
+ this.stats.retries++;
251
+ continue;
252
+ }
253
+ if (!res.ok) throw new Error(`HTTP ${res.status} on ${method}`);
254
+
255
+ const json = await res.json();
256
+ if (json?.error) {
257
+ const code = Number(json.error.code);
258
+ if (code === 429 || code === -32005) {
259
+ this.stats.http429++;
260
+ this.blocked.set(endpoint, Date.now() + 750 * 2 ** attempt);
261
+ await sleep(750 * 2 ** attempt);
262
+ this.stats.retries++;
263
+ continue;
264
+ }
265
+ throw new Error(`${method}: ${json.error.message ?? 'rpc error'}`);
266
+ }
267
+ this.stats.calls++;
268
+ this.stats.byMethod[method] = (this.stats.byMethod[method] ?? 0) + 1;
269
+ return json.result;
270
+ } catch (err) {
271
+ lastErr = err;
272
+ this.stats.retries++;
273
+ await sleep(400 * 2 ** Math.min(attempt, 4));
274
+ }
275
+ }
276
+ throw lastErr ?? new Error(`${method}: exhausted retries`);
277
+ }
278
+
279
+ async getMultipleAccounts(addresses) {
280
+ // 100 addresses per call is the measured maximum and the fastest shape.
281
+ const out = [];
282
+ for (let i = 0; i < addresses.length; i += 100) {
283
+ const chunk = addresses.slice(i, i + 100);
284
+ const res = await this.call('getMultipleAccounts', [chunk, { encoding: 'base64' }]);
285
+ out.push({ slot: res?.context?.slot ?? 0, values: res?.value ?? [] });
286
+ }
287
+ return out;
288
+ }
289
+ }
290
+
291
+ // ── on-chain helpers ─────────────────────────────────────────────────────────
292
+
293
+ /** Read one account out of a `getMultipleAccounts` batch. */
294
+ function readAccount(acc) {
295
+ if (!acc) return null;
296
+ const b64 = acc.data?.[0];
297
+ const lamports = Number(acc.lamports ?? 0);
298
+ if (!b64) return { amount: 0, raw: '0', dataLen: 0, lamports, isToken: false };
299
+ const buf = Buffer.from(b64, 'base64');
300
+ const dataLen = buf.length;
301
+ // An SPL token account stores its amount as a u64 at offset 64.
302
+ const isToken = dataLen >= 72;
303
+ const amount = isToken ? Number(buf.readBigUInt64LE(64)) : 0;
304
+ return { amount, raw: String(amount), dataLen, lamports, isToken };
305
+ }
306
+
307
+ /** Rent-exempt minimum for an account of `dataLen` bytes (Solana formula). */
308
+ function rentExemptMinimum(dataLen) {
309
+ return 890_880 + dataLen * 6_960;
310
+ }
311
+
312
+ // ── project modules (built output of src/, see `npm run build`) ──────────────
313
+
314
+ let src = null;
315
+ async function loadSrc() {
316
+ if (src) return src;
317
+ const missing = ['rpc.js', 'vaults.js', 'sources.js', 'canonical.js', 'store.js'].filter(
318
+ (f) => !existsSync(path.join(ROOT, 'dist', f)),
319
+ );
320
+ if (missing.length) {
321
+ console.error(
322
+ `\n dist/ is missing (${missing.join(', ')}). Build it first:\n npm run build\n`,
323
+ );
324
+ process.exit(1);
325
+ }
326
+ const [sources, canonical, store, vaults] = await Promise.all([
327
+ import('../dist/sources.js'),
328
+ import('../dist/canonical.js'),
329
+ import('../dist/store.js'),
330
+ import('../dist/vaults.js'),
331
+ ]);
332
+ src = { sources, canonical, store, vaults };
333
+ return src;
334
+ }
335
+
336
+ // ── tracked set ──────────────────────────────────────────────────────────────
337
+
338
+ /**
339
+ * Read the tracked pools.
340
+ *
341
+ * Three sources, merged by pool address:
342
+ * - the sqlite store: every pool LIQPROOF has audited;
343
+ * - `data/verified-impersonators.json`: every pool we convicted, with the
344
+ * vault addresses already known (so those pools cost zero discovery);
345
+ * - `data/survival-timeline.json`: every pool this miner has ever polled.
346
+ *
347
+ * The third source matters on CI: the sqlite store lives in `.liqproof/`,
348
+ * which is NOT committed, so a fresh runner starts with an empty database.
349
+ * The timeline IS committed, so it is what lets a daily run keep watching
350
+ * the same pools — and it already knows every vault address, so a warm
351
+ * timeline costs one `getMultipleAccounts` call per 100 pools.
352
+ */
353
+ async function collectTracked(limitOverride) {
354
+ const pools = new Map();
355
+
356
+ // A. sqlite store
357
+ try {
358
+ const { DatabaseSync } = await import('node:sqlite');
359
+ if (existsSync(CFG.db)) {
360
+ const db = new DatabaseSync(CFG.db);
361
+ try {
362
+ const rows = db
363
+ .prepare('SELECT address, mint, dex, claimed_usd, last_seen FROM pools')
364
+ .all();
365
+ for (const r of rows) {
366
+ if (!r?.address || !r?.mint) continue;
367
+ pools.set(r.address, {
368
+ address: r.address,
369
+ mint: r.mint,
370
+ dex: r.dex ?? '',
371
+ claimedUsd: Number(r.claimed_usd ?? 0),
372
+ lastSeen: Number(r.last_seen ?? 0),
373
+ source: 'store',
374
+ });
375
+ }
376
+ } finally {
377
+ db.close();
378
+ }
379
+ }
380
+ } catch (err) {
381
+ console.log(` store unavailable (${err.message}) — continuing with the registry`);
382
+ }
383
+
384
+ // B. verified impersonators (with vault addresses already known)
385
+ const regPath = path.join(ROOT, 'data', 'verified-impersonators.json');
386
+ if (existsSync(regPath)) {
387
+ try {
388
+ const reg = JSON.parse(readFileSync(regPath, 'utf8'));
389
+ for (const r of reg.results ?? []) {
390
+ if (!r?.pool || !r?.mint) continue;
391
+ const quote = (r.vaults ?? []).find((v) => v.side === 'quote');
392
+ const existing = pools.get(r.pool);
393
+ const entry = existing ?? {
394
+ address: r.pool,
395
+ mint: r.mint,
396
+ dex: '',
397
+ claimedUsd: 0,
398
+ lastSeen: 0,
399
+ source: 'verified-impersonators',
400
+ };
401
+ entry.claimedUsd = entry.claimedUsd || Number(r.claimed ?? r.liquidity ?? 0);
402
+ if (quote) {
403
+ entry.vaultAddress = quote.address;
404
+ entry.quoteMint = quote.mint;
405
+ entry.decimals = Number(quote.decimals ?? 0);
406
+ entry.baseMint = r.mint;
407
+ }
408
+ pools.set(r.pool, entry);
409
+ }
410
+ } catch (err) {
411
+ console.log(` verified-impersonators.json unreadable (${err.message})`);
412
+ }
413
+ }
414
+
415
+ // C. the survival timeline — every pool this miner has ever polled.
416
+ //
417
+ // This is the source that survives a wiped machine: the sqlite store is
418
+ // disposable, the timeline is not. It also carries the vault address, so
419
+ // a pool that is already in the timeline never needs discovery again.
420
+ const timelinePath = path.join(ROOT, 'data', 'survival-timeline.json');
421
+ if (existsSync(timelinePath)) {
422
+ try {
423
+ const timeline = JSON.parse(readFileSync(timelinePath, 'utf8'));
424
+ for (const [address, st] of Object.entries(timeline.state?.pools ?? {})) {
425
+ if (!address) continue;
426
+ const mint = st.baseMint ?? st.mint ?? '';
427
+ const existing = pools.get(address);
428
+ const entry = existing ?? {
429
+ address,
430
+ mint,
431
+ dex: '',
432
+ claimedUsd: Number(st.claimedUsd ?? 0),
433
+ lastSeen: Date.parse(st.lastTs ?? '') || 0,
434
+ source: 'timeline',
435
+ };
436
+ entry.mint = entry.mint || mint;
437
+ entry.claimedUsd = entry.claimedUsd || Number(st.claimedUsd ?? 0);
438
+ if (!entry.lastSeen) entry.lastSeen = Date.parse(st.lastTs ?? '') || 0;
439
+ entry.vaultAddress = entry.vaultAddress ?? st.vaultAddress;
440
+ entry.quoteMint = entry.quoteMint ?? st.quoteMint;
441
+ entry.decimals = entry.decimals ?? st.decimals;
442
+ entry.baseMint = entry.baseMint ?? st.baseMint;
443
+ entry.nativeSol = entry.nativeSol ?? !!st.nativeSol;
444
+ entry.quotePriceUsd = entry.quotePriceUsd ?? st.quotePriceUsd ?? 0;
445
+ pools.set(address, entry);
446
+ }
447
+ } catch (err) {
448
+ console.log(` survival-timeline.json unreadable (${err.message})`);
449
+ }
450
+ }
451
+
452
+ let list = [...pools.values()];
453
+
454
+ if (CFG.poolFilter) list = list.filter((p) => p.address === CFG.poolFilter);
455
+ if (CFG.mintFilter) list = list.filter((p) => p.mint === CFG.mintFilter);
456
+
457
+ // Most recently seen first, then the biggest claims: those are the pools
458
+ // whose survival actually matters.
459
+ list.sort((a, b) => (b.lastSeen ?? 0) - (a.lastSeen ?? 0) || b.claimedUsd - a.claimedUsd);
460
+ const limit = limitOverride ?? CFG.limit;
461
+ if (Number.isFinite(limit)) list = list.slice(0, limit);
462
+
463
+ return list;
464
+ }
465
+
466
+ // ── vault discovery ──────────────────────────────────────────────────────────
467
+
468
+ /**
469
+ * Find the quote-side vault of a pool we have not seen before.
470
+ *
471
+ * Cost: ONE `getTokenAccountsByOwner` call (the pool owns its vaults), plus
472
+ * one keyless HTTP call for the aggregator row that tells us which mint is
473
+ * the quote side. The result is cached in the timeline state file, so this
474
+ * cost is paid once per pool, ever.
475
+ *
476
+ * NOTE on the parameter shape: `getTokenAccountsByOwner` takes
477
+ * `[owner, {mint?, programId?}, {encoding}]` — the encoding goes in the
478
+ * THIRD slot, and `commitment` is omitted on purpose (some endpoints answer
479
+ * HTTP 413 when it is present).
480
+ */
481
+ async function discoverPool(rpc, pool, state) {
482
+ const cached = state.pools?.[pool.address];
483
+ if (cached?.vaultAddress || cached?.nativeSol) {
484
+ pool.vaultAddress = cached.vaultAddress;
485
+ pool.quoteMint = cached.quoteMint;
486
+ pool.decimals = cached.decimals;
487
+ pool.baseMint = cached.baseMint ?? pool.mint;
488
+ pool.nativeSol = !!cached.nativeSol;
489
+ pool.quotePriceUsd = cached.quotePriceUsd ?? 0;
490
+ return;
491
+ }
492
+
493
+ const { sources } = await loadSrc();
494
+
495
+ // 1. the aggregator row for this pool (claim, dex, quote mint, quote price)
496
+ try {
497
+ const pairs = await sources.dexscreenerPairs(pool.mint);
498
+ const row = pairs.find((p) => p.address === pool.address) ?? null;
499
+ if (row) {
500
+ pool.dex = pool.dex || row.dexId;
501
+ pool.claimedUsd = pool.claimedUsd || Number(row.reportedLiquidityUsd ?? 0);
502
+ pool.quoteMint = row.quoteTokenAddress || pool.quoteMint;
503
+ pool.quotePriceUsd = Number(row.quotePriceUsd ?? 0);
504
+ pool.baseMint = row.baseTokenAddress || pool.mint;
505
+ } else {
506
+ const gt = await sources.geckoTerminalPools(pool.mint);
507
+ const grow = gt.find((p) => p.address === pool.address) ?? null;
508
+ if (grow) {
509
+ pool.dex = pool.dex || grow.dexId;
510
+ pool.claimedUsd = pool.claimedUsd || Number(grow.reportedLiquidityUsd ?? 0);
511
+ pool.quoteMint = grow.quoteTokenAddress || pool.quoteMint;
512
+ pool.quotePriceUsd = Number(grow.quotePriceUsd ?? 0);
513
+ pool.baseMint = grow.baseTokenAddress || pool.mint;
514
+ }
515
+ }
516
+ } catch {
517
+ /* the claim is optional; the chain reading is not */
518
+ }
519
+
520
+ // 2. the token accounts the pool owns.
521
+ let accounts = [];
522
+ try {
523
+ const filter = pool.quoteMint ? { mint: pool.quoteMint } : {};
524
+ const res = await rpc.call('getTokenAccountsByOwner', [
525
+ pool.address,
526
+ filter,
527
+ { encoding: 'jsonParsed' },
528
+ ]);
529
+ accounts = res?.value ?? [];
530
+ } catch (err) {
531
+ console.log(` discovery failed for ${pool.address.slice(0, 12)}… (${err.message})`);
532
+ return;
533
+ }
534
+
535
+ const parsed = [];
536
+ for (const acc of accounts) {
537
+ const info = acc?.account?.data?.parsed?.info;
538
+ if (!info?.mint) continue;
539
+ parsed.push({
540
+ address: acc.pubkey,
541
+ mint: info.mint,
542
+ amount: Number(info.tokenAmount?.amount ?? 0),
543
+ decimals: Number(info.tokenAmount?.decimals ?? 0),
544
+ uiAmount: Number(info.tokenAmount?.uiAmountString ?? info.tokenAmount?.uiAmount ?? 0),
545
+ });
546
+ }
547
+
548
+ let quote = null;
549
+ if (pool.quoteMint) {
550
+ const cands = parsed.filter((a) => a.mint === pool.quoteMint);
551
+ quote = cands.sort((a, b) => b.amount - a.amount)[0] ?? null;
552
+ }
553
+ if (!quote) {
554
+ // Fall back: the quote side is the vault that is NOT the base token.
555
+ const cands = parsed.filter((a) => a.mint !== (pool.baseMint ?? pool.mint));
556
+ quote = cands.sort((a, b) => b.amount - a.amount)[0] ?? null;
557
+ }
558
+
559
+ if (quote) {
560
+ pool.vaultAddress = quote.address;
561
+ pool.quoteMint = quote.mint;
562
+ pool.decimals = quote.decimals;
563
+ pool.baseMint = pool.baseMint ?? pool.mint;
564
+ } else {
565
+ // No SPL quote vault: the pool may hold native SOL. We read the pool
566
+ // account's lamports instead and subtract the rent-exempt minimum.
567
+ pool.nativeSol = true;
568
+ pool.quoteMint = pool.quoteMint || WSOL;
569
+ pool.baseMint = pool.baseMint ?? pool.mint;
570
+ }
571
+ }
572
+
573
+ // ── timeline file ────────────────────────────────────────────────────────────
574
+
575
+ function readTimeline(file) {
576
+ if (!existsSync(file)) {
577
+ return { version: 1, updatedAt: null, rows: [], events: [], state: { pools: {} } };
578
+ }
579
+ try {
580
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
581
+ return {
582
+ version: 1,
583
+ updatedAt: parsed.updatedAt ?? null,
584
+ rows: Array.isArray(parsed.rows) ? parsed.rows : [],
585
+ events: Array.isArray(parsed.events) ? parsed.events : [],
586
+ state: parsed.state && typeof parsed.state === 'object' ? parsed.state : { pools: {} },
587
+ };
588
+ } catch {
589
+ return { version: 1, updatedAt: null, rows: [], events: [], state: { pools: {} } };
590
+ }
591
+ }
592
+
593
+ function writeTimeline(file, data) {
594
+ mkdirSync(path.dirname(file), { recursive: true });
595
+ const tmp = `${file}.tmp`;
596
+ writeFileSync(tmp, JSON.stringify(data, null, 2));
597
+ renameSync(tmp, file);
598
+ }
599
+
600
+ // ── drain signature lookup ───────────────────────────────────────────────────
601
+
602
+ /**
603
+ * Find the transaction that emptied a pool.
604
+ *
605
+ * We ask for the pool's recent signatures (10/10s) and read the candidates
606
+ * one by one (10/10s), looking for the transaction whose post-balance of our
607
+ * quote vault is far below its pre-balance. This is the same evidence the
608
+ * flagship BAT receipt carries: a drain with a signature a reader can open.
609
+ *
610
+ * Bounded on purpose: at most 12 transactions, because the free tier gives
611
+ * us ten per ten seconds and a miner that stalls is worse than a miner that
612
+ * says "signature not found".
613
+ */
614
+ async function findDrainSignature(rpc, pool, vaultAddress, dropUsd) {
615
+ if (!CFG.wantSignature || !vaultAddress) return null;
616
+ let sigs = [];
617
+ try {
618
+ sigs = await rpc.call('getSignaturesForAddress', [pool.address, { limit: 25 }]);
619
+ } catch {
620
+ return null;
621
+ }
622
+ if (!Array.isArray(sigs) || !sigs.length) return null;
623
+
624
+ let best = null;
625
+ let examined = 0;
626
+ for (const s of sigs.slice(0, 12)) {
627
+ if (!s?.signature) continue;
628
+ examined++;
629
+ let tx = null;
630
+ try {
631
+ tx = await rpc.call('getTransaction', [
632
+ s.signature,
633
+ { encoding: 'jsonParsed', maxSupportedTransactionVersion: 1 },
634
+ ]);
635
+ } catch {
636
+ continue;
637
+ }
638
+ const meta = tx?.meta;
639
+ if (!meta) continue;
640
+ const keys = src.vaults.accountKeyMap(tx);
641
+ const indexOf = (list) => {
642
+ const map = new Map();
643
+ for (const b of list ?? []) {
644
+ const addr = keys[b.accountIndex];
645
+ if (!addr) continue;
646
+ map.set(addr, Number(b.uiTokenAmount?.amount ?? 0));
647
+ }
648
+ return map;
649
+ };
650
+ const pre = indexOf(meta.preTokenBalances);
651
+ const post = indexOf(meta.postTokenBalances);
652
+ if (!pre.has(vaultAddress)) continue;
653
+ const before = pre.get(vaultAddress) ?? 0;
654
+ const after = post.get(vaultAddress) ?? 0;
655
+ const delta = before - after;
656
+ if (delta <= 0) continue;
657
+ if (!best || delta > best.delta) {
658
+ best = {
659
+ signature: s.signature,
660
+ slot: tx.slot ?? s.slot ?? 0,
661
+ blockTime: tx.blockTime ?? s.blockTime ?? null,
662
+ deltaRaw: delta,
663
+ deltaUsd: dropUsd ?? 0,
664
+ };
665
+ }
666
+ }
667
+ if (best) best.examined = examined;
668
+ return best;
669
+ }
670
+
671
+ // ── the sweep ────────────────────────────────────────────────────────────────
672
+
673
+ /**
674
+ * One polling sweep.
675
+ *
676
+ * `opts.limit` caps how many tracked pools are polled (the daily refresh
677
+ * passes a small one so it never blows the RPC budget) and `opts.out` says
678
+ * where the append-only timeline is written. Both default to the CLI
679
+ * configuration, so `node scripts/survival-miner.mjs` is unaffected.
680
+ */
681
+ async function sweep(rpc, timeline, opts = {}) {
682
+ const started = Date.now();
683
+ await loadSrc();
684
+ const tracked = await collectTracked(opts.limit);
685
+ console.log(`▸ tracked pools: ${tracked.length}`);
686
+
687
+ // ── discovery (only for pools we have never read) ────────────────────────
688
+ let discovered = 0;
689
+ for (const pool of tracked) {
690
+ const known = timeline.state.pools?.[pool.address];
691
+ const wasKnown = !!(known?.vaultAddress || known?.nativeSol);
692
+ await discoverPool(rpc, pool, timeline.state);
693
+ if (!wasKnown && (pool.vaultAddress || pool.nativeSol)) {
694
+ discovered++;
695
+ if (discovered % 10 === 0) process.stdout.write(` discovered ${discovered}\n`);
696
+ }
697
+ await sleep(120);
698
+ }
699
+ if (discovered) console.log(` discovered ${discovered} new pool vaults`);
700
+
701
+ // ── poll: one getMultipleAccounts batch per 100 vaults ────────────────────
702
+ const readable = tracked.filter((p) => p.vaultAddress || p.nativeSol);
703
+ const addresses = readable.map((p) => p.vaultAddress ?? p.address);
704
+ const batches = await rpc.getMultipleAccounts(addresses);
705
+
706
+ const balances = new Map();
707
+ let slot = 0;
708
+ let cursor = 0;
709
+ for (const batch of batches) {
710
+ slot = Math.max(slot, batch.slot ?? 0);
711
+ for (let i = 0; i < batch.values.length; i++) {
712
+ const addr = addresses[cursor++];
713
+ if (!addr) break;
714
+ balances.set(addr, readAccount(batch.values[i]));
715
+ }
716
+ }
717
+
718
+ // ── prices ───────────────────────────────────────────────────────────────
719
+ const { sources } = await loadSrc();
720
+ const priceCache = new Map();
721
+ async function quotePrice(quoteMint, aggregatorPrice, baseMint) {
722
+ if (!quoteMint) return 0;
723
+ if (!priceCache.has(quoteMint)) {
724
+ let p = 0;
725
+ try {
726
+ p = await sources.quoteTokenPriceUsd(quoteMint, aggregatorPrice, baseMint);
727
+ } catch {
728
+ p = 0;
729
+ }
730
+ priceCache.set(quoteMint, p);
731
+ }
732
+ return priceCache.get(quoteMint);
733
+ }
734
+
735
+ // ── compare with the previous reading, emit events ───────────────────────
736
+ const now = new Date();
737
+ const ts = now.toISOString();
738
+ const rows = [];
739
+ const newEvents = [];
740
+ let suddenCount = 0;
741
+
742
+ for (const pool of readable) {
743
+ const addr = pool.vaultAddress ?? pool.address;
744
+ const acc = balances.get(addr);
745
+ if (!acc) continue;
746
+
747
+ let quoteAmount = 0;
748
+ if (pool.nativeSol) {
749
+ const dataLen = acc.dataLen ?? 0;
750
+ const spendable = Math.max(0, Number(acc.lamports ?? 0) - rentExemptMinimum(dataLen));
751
+ quoteAmount = spendable / 1e9;
752
+ } else {
753
+ quoteAmount = acc.amount / 10 ** (pool.decimals ?? 0);
754
+ }
755
+
756
+ const price = await quotePrice(pool.quoteMint, pool.quotePriceUsd, pool.baseMint ?? pool.mint);
757
+ const depositedUsd = quoteAmount * price;
758
+ const claimedUsd = pool.claimedUsd ?? 0;
759
+ const coverage = claimedUsd > 0 ? depositedUsd / claimedUsd : 0;
760
+
761
+ rows.push({
762
+ pool: pool.address,
763
+ mint: pool.mint,
764
+ ts,
765
+ depositedUsd,
766
+ claimedUsd,
767
+ coverage,
768
+ });
769
+
770
+ const st = timeline.state.pools?.[pool.address] ?? {};
771
+ const prev = typeof st.lastDepositedUsd === 'number' ? st.lastDepositedUsd : undefined;
772
+
773
+ if (prev !== undefined && prev > 0) {
774
+ const drop = prev - depositedUsd;
775
+ const threshold = Math.min(prev * CFG.relDrop, CFG.absDrop);
776
+ const ratio = drop / prev;
777
+
778
+ if (st.drop) {
779
+ // We are inside a removal episode: track the low-water mark and watch
780
+ // for a restore.
781
+ if (depositedUsd < st.drop.to) st.drop.to = depositedUsd;
782
+ const recovered = depositedUsd - st.drop.to;
783
+ const needed = CFG.restoreFrac * (st.drop.from - st.drop.to);
784
+ if (needed > 0 && recovered > needed) {
785
+ const ev = {
786
+ pool: pool.address,
787
+ mint: pool.mint,
788
+ ts,
789
+ kind: 'LIQUIDITY_RESTORED',
790
+ from: st.drop.from,
791
+ to: depositedUsd,
792
+ deltaUsd: depositedUsd - st.drop.to,
793
+ restoredFraction: (depositedUsd - st.drop.to) / (st.drop.from - st.drop.to),
794
+ sudden: false,
795
+ };
796
+ newEvents.push(ev);
797
+ st.drop = null;
798
+ }
799
+ } else if (drop > threshold) {
800
+ const sudden = ratio > 0.5;
801
+ const ev = {
802
+ pool: pool.address,
803
+ mint: pool.mint,
804
+ ts,
805
+ kind: 'LIQUIDITY_REMOVED',
806
+ from: prev,
807
+ to: depositedUsd,
808
+ deltaUsd: -drop,
809
+ dropFraction: ratio,
810
+ sudden,
811
+ };
812
+ if (sudden) {
813
+ suddenCount++;
814
+ const sig = await findDrainSignature(rpc, pool, pool.vaultAddress, -drop);
815
+ if (sig) {
816
+ ev.signature = sig.signature;
817
+ ev.slot = sig.slot;
818
+ ev.blockTime = sig.blockTime ? new Date(sig.blockTime * 1000).toISOString() : null;
819
+ }
820
+ }
821
+ newEvents.push(ev);
822
+ st.drop = { from: prev, to: depositedUsd, ts, sudden };
823
+ }
824
+ }
825
+
826
+ timeline.state.pools[pool.address] = {
827
+ ...st,
828
+ lastDepositedUsd: depositedUsd,
829
+ lastTs: ts,
830
+ lastSlot: slot,
831
+ claimedUsd,
832
+ quoteMint: pool.quoteMint,
833
+ baseMint: pool.baseMint ?? pool.mint,
834
+ vaultAddress: pool.vaultAddress,
835
+ decimals: pool.decimals,
836
+ nativeSol: !!pool.nativeSol,
837
+ quotePriceUsd: pool.quotePriceUsd ?? 0,
838
+ mint: pool.mint,
839
+ };
840
+ }
841
+
842
+ // ── persist: rows are APPEND-ONLY, state is a checkpoint ─────────────────
843
+ timeline.rows.push(...rows);
844
+ timeline.events.push(...newEvents);
845
+ timeline.updatedAt = ts;
846
+ timeline.state.lastRunAt = ts;
847
+ timeline.state.lastSlot = slot;
848
+ writeTimeline(opts.out ?? CFG.out, timeline);
849
+
850
+ // ── mirror the events into the sqlite store (best effort) ────────────────
851
+ if (newEvents.length) {
852
+ try {
853
+ const { store } = await loadSrc();
854
+ const st = new store.Store(CFG.db);
855
+ try {
856
+ for (const ev of newEvents) {
857
+ st.insertEvent({
858
+ mint: ev.mint,
859
+ pool: ev.pool,
860
+ slot: ev.slot ?? slot ?? 0,
861
+ ts: Math.floor(Date.parse(ev.ts) / 1000),
862
+ signature: ev.signature ?? '',
863
+ kind: ev.kind,
864
+ delta_usd: ev.deltaUsd ?? 0,
865
+ deposited_usd: ev.to ?? 0,
866
+ });
867
+ }
868
+ } finally {
869
+ st.close();
870
+ }
871
+ } catch (err) {
872
+ if (CFG.verbose) console.log(` store mirror failed: ${err.message}`);
873
+ }
874
+ }
875
+
876
+ // ── report ────────────────────────────────────────────────────────────────
877
+ const covered = rows.filter((r) => r.claimedUsd > 0);
878
+ const avgCoverage = covered.length
879
+ ? covered.reduce((s, r) => s + r.coverage, 0) / covered.length
880
+ : 0;
881
+ console.log(
882
+ ` polled ${readable.length}/${tracked.length} pools · ${rows.length} rows · avg coverage ${pct(avgCoverage)}`,
883
+ );
884
+ for (const ev of newEvents) {
885
+ if (ev.kind === 'LIQUIDITY_REMOVED') {
886
+ console.log(
887
+ ` ▼ ${ev.kind}${ev.sudden ? ' (SUDDEN — drain signature)' : ''} ${ev.pool.slice(0, 12)}… ${usd(ev.from)} → ${usd(ev.to)} (${pct(ev.dropFraction ?? 0)} gone)`,
888
+ );
889
+ if (ev.signature) console.log(` tx ${ev.signature}`);
890
+ } else {
891
+ console.log(
892
+ ` ▲ ${ev.kind} ${ev.pool.slice(0, 12)}… ${usd(ev.from)} → ${usd(ev.to)} (${pct(ev.restoredFraction ?? 0)} of the loss returned)`,
893
+ );
894
+ }
895
+ }
896
+ if (!newEvents.length) console.log(' no liquidity events');
897
+ console.log(
898
+ ` rpc calls ${rpc.stats.calls} ${JSON.stringify(rpc.stats.byMethod)} · sweep ${((Date.now() - started) / 1000).toFixed(1)}s`,
899
+ );
900
+
901
+ return { rows, events: newEvents, suddenCount };
902
+ }
903
+
904
+ // ── main ─────────────────────────────────────────────────────────────────────
905
+
906
+ async function main() {
907
+ const timeline = readTimeline(CFG.out);
908
+ const rpc = new MinerRpc();
909
+ await loadSrc();
910
+
911
+ let stopping = false;
912
+ const stop = (signal) => {
913
+ if (stopping) return;
914
+ stopping = true;
915
+ console.log(`\n ${signal} — finishing this sweep and saving state…`);
916
+ };
917
+ process.on('SIGINT', () => stop('SIGINT (Ctrl-C)'));
918
+ process.on('SIGTERM', () => stop('SIGTERM'));
919
+
920
+ console.log('▸ LIQPROOF SURVIVAL MINER');
921
+ console.log(
922
+ ` interval ${Math.round(CFG.everyMs / 1000)}s · threshold min(${pct(CFG.relDrop)} relative, ${usd(CFG.absDrop)} absolute) · restore ${pct(CFG.restoreFrac)}`,
923
+ );
924
+
925
+ for (;;) {
926
+ try {
927
+ await sweep(rpc, timeline);
928
+ } catch (err) {
929
+ console.log(` sweep failed: ${err.message}`);
930
+ }
931
+ if (CFG.once || stopping) break;
932
+ const wait = CFG.everyMs;
933
+ const deadline = Date.now() + wait;
934
+ while (!stopping && Date.now() < deadline) await sleep(Math.min(1000, deadline - Date.now()));
935
+ }
936
+
937
+ console.log(` timeline: ${CFG.out}`);
938
+ console.log(` rows ${timeline.rows.length} · events ${timeline.events.length}`);
939
+ }
940
+
941
+ const invokedDirectly =
942
+ process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url;
943
+
944
+ if (invokedDirectly) {
945
+ main().catch((err) => {
946
+ console.error(`\n fatal: ${err?.stack ?? err}`);
947
+ process.exit(1);
948
+ });
949
+ }
950
+
951
+ export { sweep, collectTracked, readTimeline, writeTimeline, MinerRpc, CFG };