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/vaults.ts ADDED
@@ -0,0 +1,574 @@
1
+ /**
2
+ * vaults.ts — read the REAL balances of a pool's vaults straight from the chain.
3
+ *
4
+ * Three strategies, all $0:
5
+ *
6
+ * A. TRANSACTION PROBE: one `getTransaction` on the pool's newest tx returns
7
+ * `accountKeys` + `preTokenBalances`/`postTokenBalances`. Mapping
8
+ * accountIndex → pubkey yields the vault addresses AND their balances in
9
+ * a single RPC call. No indexed method, no offset guessing.
10
+ *
11
+ * B. OWNER SCAN: `getTokenAccountsByOwner(pool, {mint})` returns the vault
12
+ * token accounts owned by the pool. Reliable but "indexed" → only 10
13
+ * calls / 10s on the free tier.
14
+ *
15
+ * C. RAW SCAN: scan the pool account's raw bytes for embedded pubkeys and
16
+ * verify them with ONE `getMultipleAccounts` call (100 addresses max).
17
+ * Works for every AMM layout, including CLMM and bonding curves.
18
+ *
19
+ * MEASURED FACTS that this file encodes:
20
+ * - Vault pubkeys are NOT 8-byte aligned inside pool account data
21
+ * (Raydium CPMM: base@137, quote@169) → we must scan every byte offset.
22
+ * - `getMultipleAccounts` accepts up to 100 addresses and answers in ~80ms
23
+ * → the whole raw scan costs ONE call, not 40.
24
+ * - `getTokenAccountsByOwner` is rate-limited to 10 calls / 10s and returns
25
+ * 429 after that → it is a fallback, not the primary.
26
+ * - The pool's quote token may be SOL, USDC, JitoSOL, or any SPL token.
27
+ * Its USD price must come from the aggregator (quote_token_price_usd),
28
+ * not from a hardcoded table.
29
+ */
30
+
31
+ import { encodeBase58, decodeBase58, bytesEqual } from './base58.js';
32
+ import { RpcPool } from './rpc.js';
33
+
34
+ export const TOKEN_PROGRAM = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
35
+ export const TOKEN_2022_PROGRAM = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';
36
+
37
+ export interface Vault {
38
+ address: string;
39
+ mint: string;
40
+ amount: string;
41
+ decimals: number;
42
+ uiAmount: number;
43
+ side: 'base' | 'quote';
44
+ method: 'txProbe' | 'ownerScan' | 'rawScan' | 'nativeSol';
45
+ /**
46
+ * True for the synthetic "quote = native SOL held by the pool account"
47
+ * entry. It is not an SPL token account, so it must never be re-read
48
+ * through getMultipleAccounts.
49
+ */
50
+ synthetic?: boolean;
51
+ }
52
+
53
+ export interface PoolVaults {
54
+ pool: string;
55
+ poolOwnerProgram?: string;
56
+ base?: Vault;
57
+ quote?: Vault;
58
+ all: Vault[];
59
+ poolLamports: number;
60
+ method: Vault['method'] | 'none';
61
+ /** how confident we are that `all` really are the pool's vaults */
62
+ confidence: 'high' | 'medium' | 'low' | 'none';
63
+ note?: string;
64
+ }
65
+ /** Read supply + decimals of a mint. */
66
+ export async function mintMeta(
67
+ rpc: RpcPool,
68
+ mint: string,
69
+ ): Promise<{ supply: string; decimals: number } | null> {
70
+ const res = await rpc.callDetailed<any>('getAccountInfo', [mint, { encoding: 'base64' }]);
71
+ const data = res.value?.value?.data?.[0];
72
+ if (!data) return null;
73
+ const buf = Buffer.from(data, 'base64');
74
+ if (buf.length < 45) return null;
75
+ return {
76
+ supply: buf.readBigUInt64LE(36).toString(),
77
+ decimals: buf.readUInt8(44),
78
+ };
79
+ }
80
+
81
+ /** Map accountIndex → pubkey for a jsonParsed transaction. */
82
+ export function accountKeyMap(tx: any): string[] {
83
+ const staticKeys: string[] = (tx?.transaction?.message?.accountKeys ?? []).map((k: any) =>
84
+ typeof k === 'string' ? k : k.pubkey,
85
+ );
86
+ const loadedWritable: string[] = tx?.meta?.loadedAddresses?.writable ?? [];
87
+ const loadedReadonly: string[] = tx?.meta?.loadedAddresses?.readonly ?? [];
88
+ return [...staticKeys, ...loadedWritable, ...loadedReadonly];
89
+ }
90
+
91
+ /**
92
+ * Strategy A: derive vaults + balances from one transaction.
93
+ * `balances` may be 'post' (after the tx) or 'pre' (before it).
94
+ *
95
+ * We probe the newest few transactions, not just the newest one: the most
96
+ * recent tx on a pool is not always a swap (it can be a fee claim or an LP
97
+ * close), and a tx that never touched the vaults carries no vault balances.
98
+ */
99
+ export async function vaultsFromTransaction(
100
+ rpc: RpcPool,
101
+ pool: string,
102
+ baseMint: string,
103
+ quoteMint: string,
104
+ which: 'post' | 'pre' = 'post',
105
+ maxProbes = 4,
106
+ ): Promise<{ vaults: Vault[]; slot: number; signature: string; timestamp: number | null } | null> {
107
+ const sigRes = await rpc.callDetailed<any[]>('getSignaturesForAddress', [
108
+ pool,
109
+ { limit: Math.max(1, maxProbes) },
110
+ ]);
111
+ if (!sigRes.ok) return null;
112
+ const sigs = sigRes.value ?? [];
113
+
114
+ let best: { vaults: Vault[]; slot: number; signature: string; timestamp: number | null } | null = null;
115
+
116
+ for (const sig of sigs) {
117
+ if (!sig?.signature) continue;
118
+ const txRes = await rpc.callDetailed<any>('getTransaction', [
119
+ sig.signature,
120
+ // Version 1 transactions (address lookup tables) are what brand-new
121
+ // pump.fun / PumpSwap pools emit. Asking for version 0 only makes the
122
+ // node answer `-32015`, which silently cost us every new pool.
123
+ { encoding: 'jsonParsed', maxSupportedTransactionVersion: 1 },
124
+ ]);
125
+ if (!txRes.ok) continue;
126
+ const tx = txRes.value;
127
+ if (!tx?.meta) continue;
128
+
129
+ const keys = accountKeyMap(tx);
130
+ const list = which === 'post' ? tx.meta.postTokenBalances : tx.meta.preTokenBalances;
131
+
132
+ // Collect balances of token accounts OWNED BY THE POOL.
133
+ const byOwner = new Map<string, { mint: string; amount: string; decimals: number; ui: number }>();
134
+ const anyOwned = new Map<string, { mint: string; amount: string; decimals: number; ui: number }>();
135
+
136
+ for (const b of list ?? []) {
137
+ const addr = keys[b.accountIndex];
138
+ if (!addr) continue;
139
+ const entry = {
140
+ mint: String(b.mint),
141
+ amount: String(b.uiTokenAmount?.amount ?? '0'),
142
+ decimals: Number(b.uiTokenAmount?.decimals ?? 0),
143
+ ui: Number(b.uiTokenAmount?.uiAmount ?? 0),
144
+ };
145
+ if (b.owner === pool) byOwner.set(addr, entry);
146
+ if (!anyOwned.has(addr)) anyOwned.set(addr, entry);
147
+ }
148
+
149
+ // Prefer accounts owned by the pool; fall back to any account in the tx.
150
+ const source = byOwner.size > 0 ? byOwner : anyOwned;
151
+ const vaults: Vault[] = [];
152
+ for (const [addr, e] of source) {
153
+ if (e.mint !== baseMint && e.mint !== quoteMint) continue;
154
+ vaults.push({
155
+ address: addr,
156
+ mint: e.mint,
157
+ amount: e.amount,
158
+ decimals: e.decimals,
159
+ uiAmount: e.ui,
160
+ side: e.mint === baseMint ? 'base' : 'quote',
161
+ method: 'txProbe',
162
+ });
163
+ }
164
+
165
+ const hasBase = vaults.some((v) => v.side === 'base');
166
+ const hasQuote = vaults.some((v) => v.side === 'quote');
167
+ if (hasBase && hasQuote) {
168
+ return { vaults, slot: tx.slot, signature: sig.signature, timestamp: tx.blockTime ?? null };
169
+ }
170
+ // Keep the best partial result in case no tx mentions both sides.
171
+ if (vaults.length > 0 && !best) {
172
+ best = { vaults, slot: tx.slot, signature: sig.signature, timestamp: tx.blockTime ?? null };
173
+ }
174
+ }
175
+
176
+ return best;
177
+ }
178
+
179
+ /** Strategy B: getTokenAccountsByOwner (indexed, 10 calls / 10s). */
180
+ export async function vaultsFromOwnerScan(
181
+ rpc: RpcPool,
182
+ pool: string,
183
+ baseMint: string,
184
+ quoteMint: string,
185
+ ): Promise<Vault[]> {
186
+ const out: Vault[] = [];
187
+ const seen = new Set<string>();
188
+ for (const mint of [baseMint, quoteMint].filter(Boolean)) {
189
+ const res = await rpc.callDetailed<any>('getTokenAccountsByOwner', [
190
+ pool,
191
+ { mint },
192
+ { encoding: 'jsonParsed' },
193
+ ]);
194
+ if (!res.ok) continue;
195
+ for (const acc of res.value?.value ?? []) {
196
+ if (seen.has(acc.pubkey)) continue;
197
+ seen.add(acc.pubkey);
198
+ const info = acc.account?.data?.parsed?.info;
199
+ if (!info) continue;
200
+ out.push({
201
+ address: acc.pubkey,
202
+ mint: info.mint,
203
+ amount: String(info.tokenAmount?.amount ?? '0'),
204
+ decimals: Number(info.tokenAmount?.decimals ?? 0),
205
+ uiAmount: Number(info.tokenAmount?.uiAmountString ?? info.tokenAmount?.uiAmount ?? 0),
206
+ side: info.mint === baseMint ? 'base' : 'quote',
207
+ method: 'ownerScan',
208
+ });
209
+ }
210
+ }
211
+ return out;
212
+ }
213
+
214
+ /** Strategy C: raw-byte scan of the pool account + getMultipleAccounts. */
215
+ async function vaultsFromRawScan(
216
+ rpc: RpcPool,
217
+ pool: string,
218
+ baseMint: string,
219
+ quoteMint: string,
220
+ poolDataB64?: string,
221
+ ): Promise<Vault[]> {
222
+ let b64 = poolDataB64;
223
+ if (!b64) {
224
+ const acct = await rpc.callDetailed<any>('getAccountInfo', [pool, { encoding: 'base64' }]);
225
+ b64 = acct.value?.value?.data?.[0];
226
+ }
227
+ if (!b64) return [];
228
+
229
+ const buf = Buffer.from(b64, 'base64');
230
+ const out: Vault[] = [];
231
+ const seenAddr = new Set<string>();
232
+ const needMeta = new Map<string, Vault>();
233
+
234
+ const absorb = (values: any[], candidates: string[]): boolean => {
235
+ for (let i = 0; i < values.length; i++) {
236
+ const v = values[i];
237
+ if (!v) continue;
238
+ if (v.owner !== TOKEN_PROGRAM && v.owner !== TOKEN_2022_PROGRAM) continue;
239
+ const data = v.data?.[0];
240
+ if (!data) continue;
241
+ const tb = Buffer.from(data, 'base64');
242
+ if (tb.length < 72) continue;
243
+ const mint = encodeBase58(tb.subarray(0, 32));
244
+ if (mint !== baseMint && mint !== quoteMint) continue;
245
+ const addr = candidates[i]!;
246
+ if (seenAddr.has(addr)) continue;
247
+ seenAddr.add(addr);
248
+ const amount = tb.readBigUInt64LE(64).toString();
249
+ const entry: Vault = {
250
+ address: addr,
251
+ mint,
252
+ amount,
253
+ decimals: 0,
254
+ uiAmount: 0,
255
+ side: mint === baseMint ? 'base' : 'quote',
256
+ method: 'rawScan',
257
+ };
258
+ needMeta.set(mint, entry);
259
+ out.push(entry);
260
+ }
261
+ return out.some((v) => v.side === 'base') && out.some((v) => v.side === 'quote');
262
+ };
263
+
264
+ // ── Residue-class aware scanning ─────────────────────────────────────────
265
+ // Pubkeys inside a struct sit at a FIXED alignment. Measured on mainnet:
266
+ // Raydium CPMM → offsets ≡ 1 (mod 8) (base@137, quote@169)
267
+ // Meteora DLMM → offsets ≡ 0 (mod 8) (base@120, quote@184)
268
+ // A naive "first 100 byte-offers" scan never even reaches offset 137 on a
269
+ // 1544-byte account, so we walk one alignment class at a time and stop as
270
+ // soon as both sides are found. Each class is checked with ONE
271
+ // getMultipleAccounts call (100 addresses, ~80ms).
272
+ const CLASSES = [1, 0, 2, 3, 4, 5, 6, 7];
273
+ for (const cls of CLASSES) {
274
+ const candidates: string[] = [];
275
+ const localSeen = new Set<string>();
276
+ for (let o = cls; o + 32 <= buf.length; o += 8) {
277
+ const slice = buf.subarray(o, o + 32);
278
+ if (slice.every((b) => b === 0)) continue;
279
+ const addr = encodeBase58(slice);
280
+ if (localSeen.has(addr)) continue;
281
+ localSeen.add(addr);
282
+ candidates.push(addr);
283
+ }
284
+ if (candidates.length === 0) continue;
285
+
286
+ for (let start = 0; start < candidates.length; start += 100) {
287
+ const chunk = candidates.slice(start, start + 100);
288
+ const res = await rpc.callDetailed<any>('getMultipleAccounts', [
289
+ chunk,
290
+ { encoding: 'base64' },
291
+ ]);
292
+ if (!res.ok) break;
293
+ const values = res.value?.value ?? [];
294
+ if (absorb(values, chunk)) {
295
+ // decimals live on the mint account
296
+ for (const [mint, entry] of needMeta) {
297
+ const meta = await mintMeta(rpc, mint);
298
+ entry.decimals = meta?.decimals ?? 0;
299
+ entry.uiAmount = Number(entry.amount) / 10 ** entry.decimals;
300
+ }
301
+ return out;
302
+ }
303
+ }
304
+ }
305
+
306
+ // decimals live on the mint account
307
+ for (const [mint, entry] of needMeta) {
308
+ const meta = await mintMeta(rpc, mint);
309
+ entry.decimals = meta?.decimals ?? 0;
310
+ entry.uiAmount = Number(entry.amount) / 10 ** entry.decimals;
311
+ }
312
+
313
+ return out;
314
+ }
315
+
316
+ /** SOL mint address — native SOL is also wrapped as an SPL token. */
317
+ export const WRAPPED_SOL_MINT = 'So11111111111111111111111111111111111111112';
318
+
319
+ /**
320
+ * The rent-exempt minimum lamports for an account of `dataLen` bytes.
321
+ * Subtract it from a pool's lamports so we do not count rent as liquidity.
322
+ */
323
+ function rentExemptMinimum(dataLen: number): number {
324
+ return 890_880 + dataLen * 6_960;
325
+ }
326
+
327
+ /**
328
+ * Every 32-byte window of the pool account that decodes to a pubkey.
329
+ *
330
+ * This is the AUTHORITATIVE test for "is this address one of the pool's
331
+ * vaults?": an AMM stores its vault addresses inside its own account data.
332
+ * A transaction, by contrast, mentions dozens of unrelated token accounts —
333
+ * we measured a transaction probe happily returning a TRADER's wSOL account
334
+ * (owner `DrcDxWxLi3i7Yd…`, not the pool) and we nearly counted a user's
335
+ * wallet as the pool's liquidity.
336
+ */
337
+ function poolEmbeddedKeys(buf: Buffer): Set<string> {
338
+ const set = new Set<string>();
339
+ for (let o = 0; o + 32 <= buf.length; o++) {
340
+ const s = buf.subarray(o, o + 32);
341
+ if (s.every((b) => b === 0)) continue;
342
+ set.add(encodeBase58(s));
343
+ }
344
+ return set;
345
+ }
346
+
347
+ /**
348
+ * Re-read the LIVE balance of every vault address we discovered.
349
+ *
350
+ * This matters: a transaction's `postTokenBalances` is the balance AT THAT
351
+ * SLOT, not right now. If we fall back to an older transaction (because the
352
+ * newest one did not touch the vaults) we would publish a STALE deposit as
353
+ * if it were current — we measured a pool reporting $23.53 when the live
354
+ * balance was $21.45.
355
+ *
356
+ * One `getMultipleAccounts` call (100 addresses, ~80ms) fixes it.
357
+ */
358
+ async function refreshBalances(rpc: RpcPool, vaults: Vault[]): Promise<Vault[]> {
359
+ const real = vaults.filter((v) => !v.synthetic);
360
+ if (real.length === 0) return vaults;
361
+ const res = await rpc.callDetailed<any>('getMultipleAccounts', [
362
+ real.map((v) => v.address),
363
+ { encoding: 'base64' },
364
+ ]);
365
+ if (!res.ok) return vaults;
366
+ const values = res.value?.value ?? [];
367
+ const refreshed = real.map((v, i) => {
368
+ const acc = values[i];
369
+ if (!acc) return v;
370
+ const data = acc.data?.[0];
371
+ if (!data) return v;
372
+ const tb = Buffer.from(data, 'base64');
373
+ if (tb.length < 72) return v;
374
+ const amount = tb.readBigUInt64LE(64).toString();
375
+ return {
376
+ ...v,
377
+ amount,
378
+ uiAmount: Number(amount) / 10 ** (v.decimals || 0),
379
+ };
380
+ });
381
+ // Put the refreshed real vaults back, preserving order, then keep the
382
+ // synthetic entries in place.
383
+ let ri = 0;
384
+ return vaults.map((v) => (v.synthetic ? v : refreshed[ri++]!));
385
+ }
386
+
387
+ /**
388
+ * Read pool vault balances using the cheapest reliable strategy.
389
+ */
390
+ export async function readPoolVaults(
391
+ rpc: RpcPool,
392
+ pool: string,
393
+ baseMint: string,
394
+ quoteMint: string,
395
+ opts: { allowIndexed?: boolean } = {},
396
+ ): Promise<PoolVaults> {
397
+ const acct = await rpc.callDetailed<any>('getAccountInfo', [pool, { encoding: 'base64' }]);
398
+ const poolOwnerProgram: string | undefined = acct.value?.value?.owner;
399
+ const poolLamports: number = acct.value?.value?.lamports ?? 0;
400
+ const poolDataB64: string | undefined = acct.value?.value?.data?.[0];
401
+
402
+ let all: Vault[] = [];
403
+ let method: Vault['method'] | 'none' = 'none';
404
+ let confidence: PoolVaults['confidence'] = 'none';
405
+
406
+ // A — transaction probe
407
+ const probe = await vaultsFromTransaction(rpc, pool, baseMint, quoteMint, 'post');
408
+ if (probe && probe.vaults.length > 0) {
409
+ // Cross-check every candidate against the pool's own account data. A
410
+ // transaction mentions lots of token accounts that have nothing to do
411
+ // with the pool; only the addresses the pool actually stores are its
412
+ // vaults.
413
+ const buf = poolDataB64 ? Buffer.from(poolDataB64, 'base64') : null;
414
+ const embedded = buf ? poolEmbeddedKeys(buf) : null;
415
+ const confirmed = embedded
416
+ ? probe.vaults.filter((v) => embedded.has(v.address))
417
+ : probe.vaults;
418
+ if (confirmed.length > 0) {
419
+ all = confirmed;
420
+ method = 'txProbe';
421
+ confidence = confirmed.some((v) => v.side === 'quote') ? 'high' : 'medium';
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Do we still need to hunt for a side?
427
+ *
428
+ * A side counts as "found" only if it holds a NON-TRIVIAL balance. A wSOL
429
+ * account with 1e-9 in it is a placeholder, not the reserve — treating it
430
+ * as found made us stop looking and report a pool as having no quote side
431
+ * when it actually had a real wSOL vault at a different offset.
432
+ */
433
+ const needsSide = (mint: string, side: 'base' | 'quote'): boolean => {
434
+ const cands = all.filter((v) => v.mint === mint || v.side === side);
435
+ if (cands.length === 0) return true;
436
+ const best = pickLargest(cands);
437
+ return !best || best.uiAmount <= 1e-6;
438
+ };
439
+
440
+ // C — raw scan (1 RPC call, works for every AMM layout). Preferred over the
441
+ // indexed owner scan because it costs one call instead of a rate-limited one.
442
+ if (needsSide(baseMint, 'base') || needsSide(quoteMint, 'quote')) {
443
+ const rawVaults = await vaultsFromRawScan(rpc, pool, baseMint, quoteMint, poolDataB64);
444
+ if (rawVaults.length > 0) {
445
+ all = mergeVaults(all, rawVaults);
446
+ method = method === 'none' ? 'rawScan' : method;
447
+ confidence = hasSide(all, quoteMint, 'quote') ? 'high' : 'medium';
448
+ }
449
+ }
450
+
451
+ // B — owner scan (last resort; indexed and rate-limited).
452
+ //
453
+ // It must run when EITHER side is missing, not only when the quote is
454
+ // missing. Measured on a pump.fun/PumpSwap pool: the transaction probe
455
+ // found the quote vault but not the base vault, and because the quote was
456
+ // present we never fell back to the owner scan — so the base side was
457
+ // silently missing and the token looked like it held no tokens at all.
458
+ if (
459
+ (needsSide(baseMint, 'base') || needsSide(quoteMint, 'quote')) &&
460
+ opts.allowIndexed !== false
461
+ ) {
462
+ const ownerVaults = await vaultsFromOwnerScan(rpc, pool, baseMint, quoteMint);
463
+ if (ownerVaults.length > 0) {
464
+ all = mergeVaults(all, ownerVaults);
465
+ method = method === 'none' ? 'ownerScan' : method;
466
+ confidence = hasSide(all, quoteMint, 'quote') ? 'high' : 'medium';
467
+ }
468
+ }
469
+
470
+ // Pick THE VAULT, not just any account with the right mint.
471
+ //
472
+ // A pool can own SEVERAL token accounts for the same mint. Measured on
473
+ // PYTH: the Raydium pool owns `AKriQaPM…` holding 15.99 PYTH (dust) AND
474
+ // `CKzYCVH5…` holding 2,999,128 PYTH (the real reserve vault). Taking the
475
+ // first one made the token look worthless and the self-denominated
476
+ // percentage collapse to 0%.
477
+ //
478
+ // The reserve vault is the one with the LARGER balance. We only fall back
479
+ // to a smaller account when it is the only one we found.
480
+ const base = pickLargest(all.filter((v) => v.mint === baseMint || v.side === 'base'));
481
+ const quote = pickLargest(all.filter((v) => v.mint === quoteMint || v.side === 'quote'));
482
+
483
+ // ── Native SOL held by the pool account ─────────────────────────────────
484
+ // A SOL-quoted pool does not necessarily keep the SOL in a wSOL token
485
+ // account. Measured on brand-new pump.fun pools: the wSOL vault existed
486
+ // but held 0, while the pool account itself held 230.9 SOL. That SOL is
487
+ // the real quote-side deposit, so we add it as a synthetic quote leg and
488
+ // let `pickLargest` decide which leg is the real reserve.
489
+ //
490
+ // Rent-exempt lamports are subtracted so we never count rent as liquidity.
491
+ if (quoteMint === WRAPPED_SOL_MINT && poolLamports > 0) {
492
+ const dataLen = Buffer.from(poolDataB64 ?? '', 'base64').length;
493
+ const spendable = Math.max(0, poolLamports - rentExemptMinimum(dataLen));
494
+ const sol = spendable / 1e9;
495
+ if (sol > 0) {
496
+ all = mergeVaults(all, [
497
+ {
498
+ address: pool,
499
+ mint: WRAPPED_SOL_MINT,
500
+ amount: String(spendable),
501
+ decimals: 9,
502
+ uiAmount: sol,
503
+ side: 'quote',
504
+ method: 'nativeSol',
505
+ synthetic: true,
506
+ },
507
+ ]);
508
+ }
509
+ }
510
+
511
+ // Addresses may have come from a transaction snapshot (stale) — always read
512
+ // the balance that is true RIGHT NOW.
513
+ if (all.length > 0) {
514
+ all = await refreshBalances(rpc, all);
515
+ }
516
+
517
+ const finalBase = pickLargest(all.filter((v) => v.mint === baseMint || v.side === 'base'));
518
+ const finalQuote = pickLargest(all.filter((v) => v.mint === quoteMint || v.side === 'quote'));
519
+
520
+ return {
521
+ pool,
522
+ poolOwnerProgram,
523
+ base: finalBase,
524
+ quote: finalQuote,
525
+ all,
526
+ poolLamports,
527
+ method,
528
+ confidence,
529
+ note:
530
+ all.length === 0
531
+ ? 'no SPL vault accounts could be located for this pool'
532
+ : !quote
533
+ ? 'quote-side vault not located; deposit coverage cannot be computed'
534
+ : undefined,
535
+ };
536
+ }
537
+
538
+ /** Merge two vault lists, keeping the first observation per address. */
539
+ function mergeVaults(a: Vault[], b: Vault[]): Vault[] {
540
+ const out = [...a];
541
+ const seen = new Set(a.map((v) => v.address));
542
+ for (const v of b) {
543
+ if (seen.has(v.address)) continue;
544
+ seen.add(v.address);
545
+ out.push(v);
546
+ }
547
+ return out;
548
+ }
549
+
550
+ /** The vault with the largest balance — the reserve, not the dust. */
551
+ function pickLargest(vs: Vault[]): Vault | undefined {
552
+ if (vs.length === 0) return undefined;
553
+ let best = vs[0]!;
554
+ for (const v of vs) {
555
+ if (v.uiAmount > best.uiAmount) best = v;
556
+ else if (v.uiAmount === best.uiAmount && Number(v.amount) > Number(best.amount)) best = v;
557
+ }
558
+ return best;
559
+ }
560
+
561
+ /** Do we have a vault for this mint (or this side)? */
562
+ function hasSide(vs: Vault[], mint: string, side: 'base' | 'quote'): boolean {
563
+ return vs.some((v) => (mint ? v.mint === mint : true) && v.side === side);
564
+ }
565
+
566
+ /** Find the byte offset of a pubkey inside raw account data. */
567
+ export function findVaultInRawData(b64: string, mint: string): number {
568
+ const buf = Buffer.from(b64, 'base64');
569
+ const target = decodeBase58(mint);
570
+ for (let o = 0; o + 32 <= buf.length; o++) {
571
+ if (bytesEqual(buf.subarray(o, o + 32), target)) return o;
572
+ }
573
+ return -1;
574
+ }