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/sources.ts ADDED
@@ -0,0 +1,714 @@
1
+ /**
2
+ * sources.ts — the "what they claim" side of the ledger.
3
+ *
4
+ * Every source here is keyless and free by default:
5
+ * - GeckoTerminal v2 (CoinGecko's on-chain product) — reported pool reserves
6
+ * - DexScreener — reported liquidity + venue map
7
+ * - Jupiter quote (lite-api) — on-chain execution oracle (price impact)
8
+ * - CoinGecko public /simple/price — spot SOL/USD + token/USD
9
+ *
10
+ * A CoinGecko Pro API key is OPTIONAL. Set COINGECKO_API_KEY (or put it in
11
+ * a .env file) and the CoinGecko calls move to the Pro host with the key
12
+ * attached; without it they stay on the free public endpoints. Nothing in
13
+ * the tool breaks when the key is missing, and no key is ever required.
14
+ */
15
+
16
+ import { fetchJson, DiskCache, TtlCache } from './util.js';
17
+ import { readFileSync } from 'node:fs';
18
+
19
+ export const MINT = {
20
+ SOL: 'So11111111111111111111111111111111111111112',
21
+ USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
22
+ } as const;
23
+
24
+ /**
25
+ * Assets that are "money" in their own right.
26
+ *
27
+ * A SOL/USDC pool legitimately holds ~86% of its value in SOL, so a low
28
+ * deposit coverage there is NORMAL, not suspicious — a constant-product AMM
29
+ * with a 2:1 imbalance is perfectly liquid. Auditing these pairs is still
30
+ * useful as a sanity check on our own engine, but they must never be
31
+ * reported as findings.
32
+ */
33
+ export const MAJOR_MINTS = new Set<string>([
34
+ MINT.SOL,
35
+ MINT.USDC,
36
+ 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB', // USDT
37
+ '3NZ9J6BMfW6N1LoKoqZfioDRWfzxE3Ds8uj119bJ3oj', // WBTC (wrapped)
38
+ 'cbbtc3xrnz8A2XazhrcqQjkQxjWZ6Y4m4jKSXWCPn5G', // cbBTC
39
+ 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263', // BONK (bluechip)
40
+ 'JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN', // JUP
41
+ ]);
42
+
43
+ /** Is this mint a major, fully-backed asset rather than a speculative token? */
44
+ export function isMajorMint(mint: string): boolean {
45
+ return MAJOR_MINTS.has(mint);
46
+ }
47
+
48
+ const GT_BASE = 'https://api.geckoterminal.com/api/v2';
49
+ const CG_BASE = 'https://api.coingecko.com/api/v3';
50
+ const JUP_BASE = 'https://lite-api.jup.ag';
51
+ const DS_BASE = 'https://api.dexscreener.com';
52
+
53
+ /**
54
+ * The CoinGecko Pro API key, if one was provided.
55
+ *
56
+ * LIQPROOF runs entirely on the free public endpoints, so the key is
57
+ * optional by design. When one is present the CoinGecko calls move to the
58
+ * Pro host and carry it in the `x-cg-pro-api-key` header, which raises the
59
+ * rate limit and unlocks the deeper endpoints.
60
+ *
61
+ * The key is read from the environment and from a local .env file. It is
62
+ * never written to disk, never printed, and never committed.
63
+ */
64
+ function readEnvFile(): Record<string, string> {
65
+ const out: Record<string, string> = {};
66
+ for (const path of ['.env', '.env.local']) {
67
+ try {
68
+ const text = readFileSync(path, 'utf8');
69
+ for (const line of text.split('\n')) {
70
+ const trimmed = line.trim();
71
+ if (!trimmed || trimmed.startsWith('#')) continue;
72
+ const eq = trimmed.indexOf('=');
73
+ if (eq <= 0) continue;
74
+ const key = trimmed.slice(0, eq).trim();
75
+ let value = trimmed.slice(eq + 1).trim();
76
+ if (
77
+ (value.startsWith('"') && value.endsWith('"')) ||
78
+ (value.startsWith("'") && value.endsWith("'"))
79
+ ) {
80
+ value = value.slice(1, -1);
81
+ }
82
+ out[key] = value;
83
+ }
84
+ } catch {
85
+ // no .env file: the environment alone is enough
86
+ }
87
+ }
88
+ return out;
89
+ }
90
+
91
+ function coingeckoKey(): string {
92
+ return (
93
+ process.env.COINGECKO_API_KEY ||
94
+ process.env.CG_API_KEY ||
95
+ process.env.X_CG_PRO_API_KEY ||
96
+ readEnvFile().COINGECKO_API_KEY ||
97
+ ''
98
+ );
99
+ }
100
+
101
+ /** The base URL and headers for the CoinGecko API, keyless or with a key. */
102
+ export function coingeckoTarget(): { base: string; headers: Record<string, string> } {
103
+ const key = coingeckoKey();
104
+ if (!key) return { base: CG_BASE, headers: {} };
105
+ return {
106
+ base: 'https://pro-api.coingecko.com/api/v3',
107
+ headers: { 'x-cg-pro-api-key': key },
108
+ };
109
+ }
110
+
111
+ export interface PoolReport {
112
+ address: string;
113
+ name: string;
114
+ dexId: string;
115
+ /** reported liquidity in USD, as claimed by the aggregator */
116
+ reportedLiquidityUsd: number;
117
+ reportedVolume24hUsd: number;
118
+ baseTokenAddress: string;
119
+ baseTokenSymbol: string;
120
+ quoteTokenAddress: string;
121
+ quoteTokenSymbol: string;
122
+ basePriceUsd: number;
123
+ quotePriceUsd: number;
124
+ source: string;
125
+ createdAt?: string;
126
+ }
127
+ export interface TokenReport {
128
+ mint: string;
129
+ symbol?: string;
130
+ name?: string;
131
+ baseTokenSymbol?: string;
132
+ priceUsd?: number;
133
+ marketCapUsd?: number;
134
+ fdvUsd?: number;
135
+ pools: PoolReport[];
136
+ /** the pool with the largest reported liquidity (the one we audit) */
137
+ primaryPool?: PoolReport;
138
+ }
139
+
140
+ const gtCache = new DiskCache<unknown>(15 * 60_000);
141
+ const dsCache = new DiskCache<unknown>(5 * 60_000);
142
+ const priceCache = new DiskCache<unknown>(5 * 60_000);
143
+
144
+ // ── GeckoTerminal ───────────────────────────────────────────────────────────
145
+
146
+ interface GtPool {
147
+ id?: string;
148
+ type?: string;
149
+ attributes?: Record<string, any>;
150
+ relationships?: Record<string, any>;
151
+ }
152
+
153
+ function relationId(rel: any): { address: string; symbol?: string } | null {
154
+ const id = rel?.data?.id;
155
+ if (typeof id !== 'string') return null;
156
+ const address = id.includes('_') ? id.slice(id.indexOf('_') + 1) : id;
157
+ return { address };
158
+ }
159
+
160
+ /**
161
+ * The DEX id lives in `relationships.dex.data.id`, not in `attributes`.
162
+ *
163
+ * GeckoTerminal's pool attributes carry no `dex_id` field at all — the only
164
+ * place the venue is named is the relationship. We were reading
165
+ * `a.dex_id`, which is always undefined, so every receipt in the dataset
166
+ * had a blank dex. That field is not cosmetic: the AMM family decides which
167
+ * vault layout we decode, so a blank dex means we silently fall back to the
168
+ * conservative path.
169
+ */
170
+ function relationDexId(rel: any): string {
171
+ const id = rel?.data?.id;
172
+ return typeof id === 'string' ? id : '';
173
+ }
174
+
175
+ /** Pools for a token, sorted by reported reserve (desc). */
176
+ export async function geckoTerminalPools(mint: string): Promise<PoolReport[]> {
177
+ const key = `gt:pools:${mint}`;
178
+ const cached = gtCache.get(key);
179
+ let payload: { data?: GtPool[] };
180
+ if (cached) {
181
+ payload = cached as { data?: GtPool[] };
182
+ } else {
183
+ try {
184
+ payload = await fetchJson<{ data?: GtPool[] }>(
185
+ `${GT_BASE}/networks/solana/tokens/${mint}/pools`,
186
+ { headers: { accept: 'application/json' }, retries: 4, timeoutMs: 30_000 },
187
+ );
188
+ gtCache.set(key, payload);
189
+ } catch (err) {
190
+ // Rate-limited (or offline). Fall back to the last good response —
191
+ // a slightly stale claim beats no claim, and the receipt records the
192
+ // age of the data. Never let a transport failure look like "no pools".
193
+ const stale = gtCache.getStale(key);
194
+ if (!stale) throw err;
195
+ payload = stale.value as { data?: GtPool[] };
196
+ }
197
+ }
198
+
199
+ const out: PoolReport[] = [];
200
+ for (const p of payload.data ?? []) {
201
+ const a = p.attributes ?? {};
202
+ const base = relationId(p.relationships?.base_token);
203
+ const quote = relationId(p.relationships?.quote_token);
204
+ if (!a.address) continue;
205
+ out.push({
206
+ address: a.address,
207
+ name: a.name ?? '',
208
+ dexId: a.dex_id ?? a.dexId ?? relationDexId(p.relationships?.dex),
209
+ reportedLiquidityUsd: Number(a.reserve_in_usd ?? 0),
210
+ reportedVolume24hUsd: Number(a.volume_usd?.h24 ?? a.volume_usd?.h24 ?? 0),
211
+ baseTokenAddress: base?.address ?? mint,
212
+ baseTokenSymbol: '',
213
+ quoteTokenAddress: quote?.address ?? '',
214
+ quoteTokenSymbol: '',
215
+ basePriceUsd: Number(a.base_token_price_usd ?? 0),
216
+ quotePriceUsd: Number(a.quote_token_price_usd ?? 0),
217
+ source: 'geckoterminal',
218
+ createdAt: a.pool_created_at ?? a.pool_created_at_timestamp,
219
+ });
220
+ }
221
+ out.sort((x, y) => y.reportedLiquidityUsd - x.reportedLiquidityUsd);
222
+ return out;
223
+ }
224
+
225
+ /** New pools on Solana (mining feed). */
226
+ export async function geckoTerminalNewPools(page = 1): Promise<PoolReport[]> {
227
+ const key = `gt:new:${page}`;
228
+ const cached = gtCache.get(key);
229
+ let payload: { data?: GtPool[] };
230
+ if (cached) {
231
+ payload = cached as { data?: GtPool[] };
232
+ } else {
233
+ try {
234
+ payload = await fetchJson<{ data?: GtPool[] }>(`${GT_BASE}/networks/solana/new_pools?page=${page}`, {
235
+ retries: 4,
236
+ timeoutMs: 30_000,
237
+ });
238
+ gtCache.set(key, payload);
239
+ } catch (err) {
240
+ const stale = gtCache.getStale(key);
241
+ if (!stale) throw err;
242
+ payload = stale.value as { data?: GtPool[] };
243
+ }
244
+ }
245
+ return toPoolReports(payload.data ?? []);
246
+ }
247
+
248
+ /**
249
+ * Top pools on Solana by reported reserve.
250
+ *
251
+ * This is the feed that matters for finding fake liquidity: unlike
252
+ * `new_pools` (where `reserve_in_usd` is still 0 for a pool that was created
253
+ * ten seconds ago), every pool here already advertises a real number — which
254
+ * is exactly the number we can check against the chain.
255
+ */
256
+ export async function geckoTerminalTopPools(page = 1): Promise<PoolReport[]> {
257
+ return gtPaged(`gt:top:${page}`, `${GT_BASE}/networks/solana/pools?page=${page}`);
258
+ }
259
+
260
+ /** Pools with the most recent trading activity. */
261
+ export async function geckoTerminalTrendingPools(page = 1): Promise<PoolReport[]> {
262
+ return gtPaged(`gt:trending:${page}`, `${GT_BASE}/networks/solana/trending_pools?page=${page}`);
263
+ }
264
+
265
+ /** Shared fetch + cache + stale-fallback for a paged GeckoTerminal feed. */
266
+ async function gtPaged(key: string, url: string): Promise<PoolReport[]> {
267
+ const cached = gtCache.get(key);
268
+ let payload: { data?: GtPool[] };
269
+ if (cached) {
270
+ payload = cached as { data?: GtPool[] };
271
+ } else {
272
+ try {
273
+ payload = await fetchJson<{ data?: GtPool[] }>(url, {
274
+ headers: { accept: 'application/json' },
275
+ retries: 4,
276
+ timeoutMs: 30_000,
277
+ });
278
+ gtCache.set(key, payload);
279
+ } catch (err) {
280
+ const stale = gtCache.getStale(key);
281
+ if (!stale) throw err;
282
+ payload = stale.value as { data?: GtPool[] };
283
+ }
284
+ }
285
+ return toPoolReports(payload.data ?? []);
286
+ }
287
+
288
+ /** Normalise a raw GeckoTerminal pool payload into our PoolReport shape. */
289
+ function toPoolReports(raw: GtPool[]): PoolReport[] {
290
+ const out: PoolReport[] = [];
291
+ for (const p of raw) {
292
+ const a = p.attributes ?? {};
293
+ const base = relationId(p.relationships?.base_token);
294
+ const quote = relationId(p.relationships?.quote_token);
295
+ if (!a.address) continue;
296
+ out.push({
297
+ address: a.address,
298
+ name: a.name ?? '',
299
+ dexId: a.dex_id ?? relationDexId(p.relationships?.dex),
300
+ reportedLiquidityUsd: Number(a.reserve_in_usd ?? 0),
301
+ reportedVolume24hUsd: Number(a.volume_usd?.h24 ?? 0),
302
+ baseTokenAddress: base?.address ?? '',
303
+ baseTokenSymbol: '',
304
+ quoteTokenAddress: quote?.address ?? '',
305
+ quoteTokenSymbol: '',
306
+ basePriceUsd: Number(a.base_token_price_usd ?? 0),
307
+ quotePriceUsd: Number(a.quote_token_price_usd ?? 0),
308
+ source: 'geckoterminal',
309
+ createdAt: a.pool_created_at,
310
+ });
311
+ }
312
+ return out;
313
+ }
314
+
315
+ // ── DexScreener ─────────────────────────────────────────────────────────────
316
+
317
+ /**
318
+ * Discovery feeds from DexScreener — keyless, and the right way to find
319
+ * tokens worth auditing.
320
+ *
321
+ * WHY NOT THE "TOP POOLS" LIST: GeckoTerminal's `/pools` endpoint is a
322
+ * curated popularity list. We checked it ten pages deep and it never
323
+ * contains a pool whose liquidity claim is fake — the fakers are not
324
+ * popular, and the honest giants are all that show up. A sweep over that
325
+ * feed can only ever return zero findings, which is a scanner that never
326
+ * fires.
327
+ *
328
+ * WHY THIS FEED: a token that PAYS for a DexScreener boost needs a big
329
+ * liquidity number to make the promoted card look good. The boost feed is
330
+ * therefore structurally enriched with tokens whose advertised liquidity
331
+ * is inflated — which is exactly the population a receipt can expose.
332
+ * The profile feed is the same idea one step earlier in the funnel.
333
+ */
334
+ export type DiscoveryFeed = 'boosts_top' | 'boosts_latest' | 'profiles_latest';
335
+
336
+ export interface DiscoveryToken {
337
+ mint: string;
338
+ chainId: string;
339
+ description: string;
340
+ url: string;
341
+ }
342
+
343
+ const DISCOVERY_PATHS: Record<DiscoveryFeed, string> = {
344
+ boosts_top: '/token-boosts/top/v1',
345
+ boosts_latest: '/token-boosts/latest/v1',
346
+ profiles_latest: '/token-profiles/latest/v1',
347
+ };
348
+
349
+ /** Fetch one discovery feed. 30 tokens per call, no key, no quota meter. */
350
+ export async function dexscreenerDiscovery(feed: DiscoveryFeed): Promise<DiscoveryToken[]> {
351
+ const key = `ds:discovery:${feed}`;
352
+ const cached = dsCache.get(key);
353
+ let arr: any[];
354
+ if (cached) {
355
+ arr = cached as any[];
356
+ } else {
357
+ try {
358
+ arr = await fetchJson<any[]>(`${DS_BASE}${DISCOVERY_PATHS[feed]}`, {
359
+ retries: 4,
360
+ timeoutMs: 30_000,
361
+ });
362
+ dsCache.set(key, arr);
363
+ } catch {
364
+ const stale = dsCache.getStale(key);
365
+ arr = stale ? (stale.value as any[]) : [];
366
+ }
367
+ }
368
+ const out: DiscoveryToken[] = [];
369
+ for (const p of arr ?? []) {
370
+ const mint = String(p?.tokenAddress ?? '').trim();
371
+ if (!mint) continue;
372
+ out.push({
373
+ mint,
374
+ chainId: String(p?.chainId ?? ''),
375
+ description: String(p?.description ?? '').slice(0, 200),
376
+ url: String(p?.url ?? ''),
377
+ });
378
+ }
379
+ return out;
380
+ }
381
+
382
+ /**
383
+ * DexScreener accepts up to 30 addresses per call, which turns a
384
+ * 250-token sweep into 9 HTTP requests instead of 250.
385
+ */
386
+ export async function dexscreenerPairsBatch(mints: string[]): Promise<PoolReport[]> {
387
+ const out: PoolReport[] = [];
388
+ const CHUNK = 30;
389
+ for (let i = 0; i < mints.length; i += CHUNK) {
390
+ const chunk = mints.slice(i, i + CHUNK);
391
+ const key = `ds:batch:${chunk.join(',')}`;
392
+ const cached = dsCache.get(key);
393
+ let arr: any[];
394
+ if (cached) {
395
+ arr = cached as any[];
396
+ } else {
397
+ try {
398
+ arr = await fetchJson<any[]>(`${DS_BASE}/tokens/v1/solana/${chunk.join(',')}`, {
399
+ retries: 4,
400
+ timeoutMs: 30_000,
401
+ });
402
+ dsCache.set(key, arr);
403
+ } catch {
404
+ const stale = dsCache.getStale(key);
405
+ arr = stale ? (stale.value as any[]) : [];
406
+ }
407
+ }
408
+ for (const p of arr ?? []) {
409
+ if (!p?.pairAddress) continue;
410
+ out.push({
411
+ address: p.pairAddress,
412
+ name: p.pairAddress,
413
+ dexId: p.dexId ?? '',
414
+ reportedLiquidityUsd: Number(p.liquidity?.usd ?? 0),
415
+ reportedVolume24hUsd: Number(p.volume?.h24 ?? 0),
416
+ baseTokenAddress: p.baseToken?.address ?? '',
417
+ baseTokenSymbol: p.baseToken?.symbol ?? '',
418
+ quoteTokenAddress: p.quoteToken?.address ?? '',
419
+ quoteTokenSymbol: p.quoteToken?.symbol ?? '',
420
+ basePriceUsd: Number(p.priceUsd ?? 0),
421
+ quotePriceUsd: 0,
422
+ source: 'dexscreener',
423
+ createdAt: p.pairCreatedAt ? new Date(p.pairCreatedAt).toISOString() : undefined,
424
+ });
425
+ }
426
+ }
427
+ return out;
428
+ }
429
+
430
+ /**
431
+ * The blind universe.
432
+ *
433
+ * CoinGecko's public API gives us the whole coin list with platform
434
+ * addresses in ONE request (21,093 coins, 7,028 of them on Solana), and
435
+ * `/coins/markets` gives the ranked list. Two requests and we know every
436
+ * Solana mint worth auditing — no API key, no paid tier, no indexer.
437
+ *
438
+ * We use this as the sweep's seed because it is the only free source that
439
+ * covers the *whole* market rather than a curated slice. It is how a blind
440
+ * sweep reaches a dead pool that no trending feed will ever surface.
441
+ */
442
+ export interface UniverseToken {
443
+ mint: string;
444
+ coinId: string;
445
+ symbol: string;
446
+ name: string;
447
+ marketCap: number;
448
+ claimedLiquidityUsd: number;
449
+ }
450
+
451
+ /** coin id → Solana mint. One request, the entire market. */
452
+ export async function coingeckoSolanaPlatforms(): Promise<Map<string, string>> {
453
+ const key = 'cg:platforms:solana';
454
+ const cached = priceCache.get(key);
455
+ let list: any[];
456
+ if (cached) {
457
+ list = cached as any[];
458
+ } else {
459
+ const cg = coingeckoTarget();
460
+ list = await fetchJson<any[]>(`${cg.base}/coins/list?include_platform=true`, {
461
+ retries: 4,
462
+ timeoutMs: 60_000,
463
+ headers: cg.headers,
464
+ });
465
+ priceCache.set(key, list);
466
+ }
467
+ const map = new Map<string, string>();
468
+ for (const c of list ?? []) {
469
+ const sol = c?.platforms?.solana;
470
+ if (sol) map.set(c.id, sol);
471
+ }
472
+ return map;
473
+ }
474
+
475
+ /**
476
+ * The top N coins by market cap that live on Solana.
477
+ *
478
+ * Note a measured gotcha: CoinGecko's platform map for Basic Attention
479
+ * Token points at the **Wormhole-bridged** mint, not the native Solana one.
480
+ * The native BAT — the one everybody trades, and the one whose pool claims
481
+ * $136 million — is not in CoinGecko's map at all. So this universe is a
482
+ * good seed but not the whole truth, which is exactly why the sweep also
483
+ * runs DexScreener's boost and profile feeds.
484
+ */
485
+ export async function coingeckoTopSolanaTokens(pages = 1): Promise<UniverseToken[]> {
486
+ const platforms = await coingeckoSolanaPlatforms();
487
+ const cg = coingeckoTarget();
488
+ const out: UniverseToken[] = [];
489
+ const seen = new Set<string>();
490
+ for (let page = 1; page <= pages; page++) {
491
+ const markets = await fetchJson<any[]>(
492
+ `${cg.base}/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=250&page=${page}`,
493
+ { retries: 4, timeoutMs: 60_000, headers: cg.headers },
494
+ );
495
+ for (const m of markets ?? []) {
496
+ const mint = platforms.get(m.id);
497
+ if (!mint || seen.has(mint)) continue;
498
+ seen.add(mint);
499
+ out.push({
500
+ mint,
501
+ coinId: m.id,
502
+ symbol: String(m.symbol ?? ''),
503
+ name: String(m.name ?? ''),
504
+ marketCap: Number(m.market_cap ?? 0),
505
+ claimedLiquidityUsd: Number(m.total_liquidity ?? 0),
506
+ });
507
+ }
508
+ if (!markets?.length) break;
509
+ }
510
+ return out;
511
+ }
512
+
513
+ export async function dexscreenerPairs(mint: string): Promise<PoolReport[]> {
514
+ const key = `ds:${mint}`;
515
+ const cached = dsCache.get(key);
516
+ let arr: any[];
517
+ if (cached) {
518
+ arr = cached as any[];
519
+ } else {
520
+ try {
521
+ arr = await fetchJson<any[]>(`${DS_BASE}/tokens/v1/solana/${mint}`, {
522
+ retries: 4,
523
+ timeoutMs: 30_000,
524
+ });
525
+ dsCache.set(key, arr);
526
+ } catch {
527
+ // Rate-limited: fall back to the last good response.
528
+ const stale = dsCache.getStale(key);
529
+ arr = stale ? (stale.value as any[]) : [];
530
+ }
531
+ }
532
+ const out: PoolReport[] = [];
533
+ for (const p of arr ?? []) {
534
+ if (!p?.pairAddress) continue;
535
+ out.push({
536
+ address: p.pairAddress,
537
+ name: p.pairAddress,
538
+ dexId: p.dexId ?? '',
539
+ reportedLiquidityUsd: Number(p.liquidity?.usd ?? 0),
540
+ reportedVolume24hUsd: Number(p.volume?.h24 ?? 0),
541
+ baseTokenAddress: p.baseToken?.address ?? '',
542
+ baseTokenSymbol: p.baseToken?.symbol ?? '',
543
+ quoteTokenAddress: p.quoteToken?.address ?? '',
544
+ quoteTokenSymbol: p.quoteToken?.symbol ?? '',
545
+ basePriceUsd: Number(p.priceUsd ?? 0),
546
+ quotePriceUsd: 0,
547
+ source: 'dexscreener',
548
+ createdAt: p.pairCreatedAt ? new Date(p.pairCreatedAt).toISOString() : undefined,
549
+ });
550
+ }
551
+ out.sort((x, y) => y.reportedLiquidityUsd - x.reportedLiquidityUsd);
552
+ return out;
553
+ }
554
+
555
+ // ── CoinGecko spot prices ───────────────────────────────────────────────────
556
+
557
+ export async function spotPriceUsd(coinIds: string[]): Promise<Record<string, number>> {
558
+ if (coinIds.length === 0) return {};
559
+ const key = `cg:price:${coinIds.slice().sort().join(',')}`;
560
+ const cached = priceCache.get(key);
561
+ if (cached) return cached as Record<string, number>;
562
+ const ids = coinIds.join(',');
563
+ let j: Record<string, { usd?: number }>;
564
+ try {
565
+ const cg = coingeckoTarget();
566
+ j = await fetchJson<Record<string, { usd?: number }>>(
567
+ `${cg.base}/simple/price?ids=${encodeURIComponent(ids)}&vs_currencies=usd`,
568
+ { retries: 4, timeoutMs: 30_000, headers: cg.headers },
569
+ );
570
+ priceCache.set(key, j);
571
+ } catch {
572
+ const stale = priceCache.getStale(key);
573
+ if (!stale) throw new Error(`CoinGecko price unavailable for ${ids}`);
574
+ j = stale.value as Record<string, { usd?: number }>;
575
+ }
576
+ const out: Record<string, number> = {};
577
+ for (const [k, v] of Object.entries(j ?? {})) out[k] = Number(v?.usd ?? 0);
578
+ priceCache.set(key, out);
579
+ return out;
580
+ }
581
+
582
+ /** SOL/USD spot from CoinGecko (falls back to Jupiter SOL→USDC quote). */
583
+ export async function solPriceUsd(): Promise<number> {
584
+ const p = await spotPriceUsd(['solana']);
585
+ if (p.solana && p.solana > 0) return p.solana;
586
+ const q = await jupiterQuote(MINT.SOL, MINT.USDC, '1000000000');
587
+ if (q?.outAmount) return Number(q.outAmount) / 1_000_000;
588
+ return 0;
589
+ }
590
+
591
+ /**
592
+ * USD price of a quote-side token (SOL, USDC, JitoSOL, ...).
593
+ *
594
+ * We must NOT assume the quote token is USDC or SOL: JTO/JUP pools on
595
+ * GeckoTerminal quote against JitoSOL, and a wrong price here produces a
596
+ * false accusation. Order of trust:
597
+ * 1. USDC → exactly $1
598
+ * 2. SOL → CoinGecko spot
599
+ * 3. the aggregator's own quote_token_price_usd (measured, per-pool)
600
+ * 4. Jupiter quote for the pair
601
+ */
602
+ export async function quoteTokenPriceUsd(
603
+ quoteMint: string,
604
+ aggregatorPrice?: number,
605
+ baseMint?: string,
606
+ ): Promise<number> {
607
+ if (!quoteMint) return 0;
608
+ if (quoteMint === MINT.USDC) return 1;
609
+ if (quoteMint === MINT.SOL) {
610
+ const sol = await solPriceUsd();
611
+ if (sol > 0) return sol;
612
+ }
613
+ if (aggregatorPrice && aggregatorPrice > 0) return aggregatorPrice;
614
+
615
+ // Last resort: ask Jupiter for the price of the quote token in USDC.
616
+ if (baseMint) {
617
+ const q = await jupiterQuote(quoteMint, MINT.USDC, '1000000');
618
+ if (q && !q.error && Number(q.outAmount) > 0) return Number(q.outAmount) / 1_000_000;
619
+ }
620
+ return 0;
621
+ }
622
+
623
+ // ── Jupiter execution oracle ───────────────────────────────────────────────
624
+
625
+ export interface JupiterQuote {
626
+ inputMint: string;
627
+ outputMint: string;
628
+ inAmount: string;
629
+ outAmount: string;
630
+ /** 0..1 — 1.0 means the trade destroys 100% of the value (honeypot) */
631
+ priceImpactPct: number;
632
+ contextSlot: number;
633
+ timeTaken: number;
634
+ routePlan: Array<{ swapInfo?: { ammKey?: string; label?: string; dexId?: string } }>;
635
+ error?: string;
636
+ httpStatus?: number;
637
+ }
638
+
639
+ /**
640
+ * Ask Jupiter for a real quote. This is the *execution* oracle:
641
+ * a genuine pool routes with a low priceImpactPct; a fake-liquidity
642
+ * pool returns impact 1.0 (or HTTP 400) because the quote side is empty.
643
+ */
644
+ export async function jupiterQuote(
645
+ inputMint: string,
646
+ outputMint: string,
647
+ amount: string,
648
+ ): Promise<JupiterQuote | null> {
649
+ const url =
650
+ `${JUP_BASE}/swap/v1/quote?inputMint=${inputMint}&outputMint=${outputMint}` +
651
+ `&amount=${amount}&slippageBps=100&restrictIntermediateTokens=true`;
652
+ try {
653
+ const j = await fetchJson<any>(url, { timeoutMs: 15_000, retries: 1 });
654
+ if (!j || typeof j.outAmount === 'undefined') return null;
655
+ return {
656
+ inputMint,
657
+ outputMint,
658
+ inAmount: String(j.inAmount ?? amount),
659
+ outAmount: String(j.outAmount),
660
+ priceImpactPct: Number(j.priceImpactPct ?? 0),
661
+ contextSlot: Number(j.contextSlot ?? 0),
662
+ timeTaken: Number(j.timeTaken ?? 0),
663
+ routePlan: j.routePlan ?? [],
664
+ };
665
+ } catch (err: any) {
666
+ return {
667
+ inputMint,
668
+ outputMint,
669
+ inAmount: amount,
670
+ outAmount: '0',
671
+ priceImpactPct: 1,
672
+ contextSlot: 0,
673
+ timeTaken: 0,
674
+ routePlan: [],
675
+ error: err?.message ?? String(err),
676
+ httpStatus: err?.status,
677
+ };
678
+ }
679
+ }
680
+
681
+ /** Combined token report: aggregator claims for a mint. */
682
+ export async function tokenReport(mint: string): Promise<TokenReport> {
683
+ // Fetch both aggregators concurrently but tolerate either failing: a claim
684
+ // from one source is still evidence, and a hard failure must never be
685
+ // mistaken for "this token is fine".
686
+ const [gtRes, dsRes] = await Promise.allSettled([
687
+ geckoTerminalPools(mint),
688
+ dexscreenerPairs(mint),
689
+ ]);
690
+ const gtPools = gtRes.status === 'fulfilled' ? gtRes.value : [];
691
+ const dsPools = dsRes.status === 'fulfilled' ? dsRes.value : [];
692
+
693
+ // Prefer the pool with the largest claimed liquidity across both sources.
694
+ const all = [...gtPools, ...dsPools];
695
+ all.sort((a, b) => b.reportedLiquidityUsd - a.reportedLiquidityUsd);
696
+ const primary = all[0];
697
+
698
+ const report: TokenReport = {
699
+ mint,
700
+ pools: all,
701
+ primaryPool: primary,
702
+ };
703
+
704
+ const dsPrimary = dsPools[0];
705
+ if (dsPrimary) {
706
+ report.symbol = dsPrimary.baseTokenSymbol || undefined;
707
+ report.priceUsd = dsPrimary.basePriceUsd || undefined;
708
+ }
709
+ if (primary) {
710
+ report.baseTokenSymbol ||= primary.baseTokenSymbol;
711
+ report.priceUsd ||= primary.basePriceUsd || undefined;
712
+ }
713
+ return report;
714
+ }