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/rpc.ts ADDED
@@ -0,0 +1,435 @@
1
+ /**
2
+ * rpc.ts — rate-aware JSON-RPC client for free public Solana endpoints.
3
+ *
4
+ * MEASURED constraints (2026-12-04, not assumptions):
5
+ *
6
+ * api.mainnet-beta.solana.com (free tier, x-ratelimit-tier: free)
7
+ * getSlot 150 / 10s
8
+ * getAccountInfo 50 / 10s
9
+ * getTransaction 10 / 10s <-- hard bottleneck
10
+ * getSignaturesForAddress 10 / 10s
11
+ * getTokenAccountsByOwner 10 / 10s (indexed)
12
+ * endpoint limit unlimited
13
+ * rps limit 250
14
+ *
15
+ * solana-mainnet.gateway.tatum.io (anonymous)
16
+ * getTransaction works, ~5 req/min after burst
17
+ * getSignaturesForAddress PAID ONLY
18
+ * getTokenAccountsByOwner PAID ONLY
19
+ *
20
+ * Critical findings that shape this file:
21
+ * 1. A 429 can arrive INSIDE a JSON-RPC body (HTTP 200 + error.code 429).
22
+ * It must be treated as retryable, not as a terminal error.
23
+ * 2. The server's own `x-ratelimit-method-remaining` header is the
24
+ * authoritative budget. We read it and adapt, rather than guessing.
25
+ * 3. Batching reduces round-trips but each sub-call still consumes budget.
26
+ * 4. `commitment` must be omitted on several methods (HTTP 413).
27
+ * 5. `getProgramAccounts` is banned (375MB payload).
28
+ *
29
+ * Therefore the pool is built as a per-(endpoint, method) token bucket that
30
+ * self-corrects from response headers, with automatic rotation.
31
+ */
32
+
33
+ import { fetchJson, HttpError } from './util.js';
34
+
35
+ export const DEFAULT_ENDPOINTS = [
36
+ 'https://api.mainnet-beta.solana.com',
37
+ 'https://solana-mainnet.gateway.tatum.io',
38
+ ];
39
+
40
+ /** Fallback limits (calls per 10s window) used until the server tells us. */
41
+ const DEFAULT_METHOD_LIMITS: Record<string, number> = {
42
+ getSlot: 140,
43
+ getAccountInfo: 45,
44
+ getTransaction: 9,
45
+ getSignaturesForAddress: 9,
46
+ getTokenAccountsByOwner: 9,
47
+ getBlock: 9,
48
+ getBlockTime: 40,
49
+ getTokenSupply: 9,
50
+ getMultipleAccounts: 40,
51
+ getProgramAccounts: 0, // banned
52
+ };
53
+
54
+ export interface RpcCall {
55
+ method: string;
56
+ params?: unknown[];
57
+ }
58
+
59
+ export interface RpcPoolOptions {
60
+ endpoints?: string[];
61
+ batchSize?: number;
62
+ windowMs?: number;
63
+ maxRetries?: number;
64
+ timeoutMs?: number;
65
+ verbose?: boolean;
66
+ onEvent?: (event: RpcEvent) => void;
67
+ }
68
+
69
+ export type RpcEvent =
70
+ | { kind: 'rotate'; endpoint: string; reason: string }
71
+ | { kind: 'throttle'; method: string; endpoint: string; waitMs: number }
72
+ | { kind: 'rpc429'; method: string; endpoint: string }
73
+ | { kind: 'error'; method: string; error: string }
74
+ | { kind: 'ok'; method: string; ms: number; batch: number; endpoint: string };
75
+
76
+ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
77
+
78
+ interface Bucket {
79
+ /** timestamps of consumed budget inside the current window */
80
+ stamps: number[];
81
+ /** server-reported per-window limit, learned from headers */
82
+ limit: number;
83
+ /** set when the server rejects us: block until this time */
84
+ blockedUntil: number;
85
+ }
86
+
87
+ export interface BatchResult {
88
+ value?: any;
89
+ error?: string;
90
+ rpcCode?: number;
91
+ retriable?: boolean;
92
+ }
93
+
94
+ export class RpcPool {
95
+ readonly endpoints: string[];
96
+ private readonly batchSize: number;
97
+ private readonly windowMs: number;
98
+ private readonly maxRetries: number;
99
+ private readonly timeoutMs: number;
100
+ private readonly verbose: boolean;
101
+ private readonly onEvent?: (event: RpcEvent) => void;
102
+ private readonly buckets = new Map<string, Bucket>();
103
+ private readonly endpointBlocked = new Map<string, number>();
104
+ private id = 1;
105
+
106
+ /** counters for the doctor command */
107
+ readonly stats = { requests: 0, calls: 0, rpc429: 0, httpErrors: 0, retries: 0 };
108
+
109
+ constructor(opts: RpcPoolOptions = {}) {
110
+ this.endpoints = opts.endpoints?.length ? opts.endpoints : DEFAULT_ENDPOINTS;
111
+ this.batchSize = opts.batchSize ?? 20;
112
+ this.windowMs = opts.windowMs ?? 10_000;
113
+ this.maxRetries = opts.maxRetries ?? 5;
114
+ this.timeoutMs = opts.timeoutMs ?? 25_000;
115
+ this.verbose = opts.verbose ?? false;
116
+ this.onEvent = opts.onEvent;
117
+ }
118
+
119
+ // ── budget bookkeeping ────────────────────────────────────────────────────
120
+ private bucket(endpoint: string, method: string): Bucket {
121
+ const key = `${endpoint}::${method}`;
122
+ let b = this.buckets.get(key);
123
+ if (!b) {
124
+ b = {
125
+ stamps: [],
126
+ limit: DEFAULT_METHOD_LIMITS[method] ?? 8,
127
+ blockedUntil: 0,
128
+ };
129
+ this.buckets.set(key, b);
130
+ }
131
+ return b;
132
+ }
133
+
134
+ private learnLimits(endpoint: string, method: string, headers: Headers): void {
135
+ const limit = Number(headers.get('x-ratelimit-method-limit'));
136
+ if (Number.isFinite(limit) && limit > 0) {
137
+ const b = this.bucket(endpoint, method);
138
+ // never trust the server upward past our own conservative ceiling
139
+ b.limit = Math.min(limit, DEFAULT_METHOD_LIMITS[method] ?? 8);
140
+ }
141
+ }
142
+
143
+ private prune(b: Bucket): void {
144
+ const now = Date.now();
145
+ while (b.stamps.length && now - b.stamps[0]! >= this.windowMs) b.stamps.shift();
146
+ }
147
+
148
+ /** Wait until `n` calls of `method` fit in the endpoint's budget. */
149
+ private async acquire(endpoint: string, method: string, n: number): Promise<void> {
150
+ const b = this.bucket(endpoint, method);
151
+ for (;;) {
152
+ const now = Date.now();
153
+
154
+ const blocked = Math.max(b.blockedUntil, this.endpointBlocked.get(endpoint) ?? 0);
155
+ if (blocked > now) {
156
+ const waitMs = blocked - now + 25;
157
+ this.onEvent?.({ kind: 'throttle', method, endpoint, waitMs });
158
+ await sleep(waitMs);
159
+ continue;
160
+ }
161
+
162
+ this.prune(b);
163
+ if (b.stamps.length + n <= b.limit) {
164
+ for (let i = 0; i < n; i++) b.stamps.push(now);
165
+ return;
166
+ }
167
+
168
+ const waitMs = this.windowMs - (now - b.stamps[0]!) + 30;
169
+ this.onEvent?.({ kind: 'throttle', method, endpoint, waitMs });
170
+ await sleep(Math.max(40, waitMs));
171
+ }
172
+ }
173
+
174
+ private block(endpoint: string, method: string, ms: number): void {
175
+ const b = this.bucket(endpoint, method);
176
+ b.blockedUntil = Math.max(b.blockedUntil, Date.now() + ms);
177
+ this.buckets.set(`${endpoint}::${method}`, b);
178
+ }
179
+
180
+ /**
181
+ * Pick the endpoint to use for a given method.
182
+ *
183
+ * Critical: this must be STABLE for the duration of one request. The
184
+ * budget for a call is reserved against a specific endpoint, so if the
185
+ * endpoint changed between reserving and sending, the accounting (and the
186
+ * rate limiting) would be wrong.
187
+ *
188
+ * We also remember which endpoints have REFUSED a method (e.g. Tatum
189
+ * requires a paid plan for getSignaturesForAddress) and skip them.
190
+ */
191
+ private pickEndpoint(method: string): string {
192
+ const now = Date.now();
193
+ const candidates = this.endpoints.filter((ep) => {
194
+ if ((this.endpointBlocked.get(ep) ?? 0) > now) return false;
195
+ const b = this.bucket(ep, method);
196
+ if (b.blockedUntil > now) return false;
197
+ if (this.unsupported.get(`${ep}::${method}`)) return false;
198
+ return true;
199
+ });
200
+
201
+ if (candidates.length === 0) {
202
+ // Everything is blocked for this method. Fall back to an endpoint that
203
+ // at least supports it, even if it is currently cooling down.
204
+ const supporting = this.endpoints.filter((ep) => !this.unsupported.get(`${ep}::${method}`));
205
+ return supporting[0] ?? this.endpoints[0]!;
206
+ }
207
+
208
+ // Round-robin among the usable candidates so load is spread, but always
209
+ // return a deterministic answer for the duration of one call chain.
210
+ const idx = this.cursor % candidates.length;
211
+ this.cursor++;
212
+ return candidates[idx]!;
213
+ }
214
+ private cursor = 0;
215
+ private unsupported = new Map<string, boolean>();
216
+
217
+ /** Remember that an endpoint refuses a method (paid plan, etc.). */
218
+ private markUnsupported(endpoint: string, method: string): void {
219
+ this.unsupported.set(`${endpoint}::${method}`, true);
220
+ }
221
+
222
+ // ── transport ─────────────────────────────────────────────────────────────
223
+ private async post(endpoint: string, body: unknown): Promise<{ responses: any[]; headers: Headers }> {
224
+ const res = await fetch(endpoint, {
225
+ method: 'POST',
226
+ headers: {
227
+ 'content-type': 'application/json',
228
+ accept: 'application/json',
229
+ 'user-agent': 'liqproof/0.1 (+read-only on-chain receipts)',
230
+ },
231
+ body: JSON.stringify(body),
232
+ });
233
+ this.stats.requests++;
234
+ const text = await res.text();
235
+ if (!res.ok) {
236
+ this.stats.httpErrors++;
237
+ throw new HttpError(res.status, text.slice(0, 400), endpoint);
238
+ }
239
+ let parsed: any;
240
+ try {
241
+ parsed = JSON.parse(text);
242
+ } catch {
243
+ throw new Error(`invalid JSON from ${endpoint}: ${text.slice(0, 160)}`);
244
+ }
245
+ return { responses: Array.isArray(parsed) ? parsed : [parsed], headers: res.headers };
246
+ }
247
+
248
+ /**
249
+ * Execute calls in order. Results are returned one-per-call, in input
250
+ * order. RPC-level 429s are retried after a cooldown; other RPC errors
251
+ * are returned as `{ error }` so a single bad tx never kills a backfill.
252
+ */
253
+ async batch(calls: RpcCall[]): Promise<BatchResult[]> {
254
+ if (calls.length === 0) return [];
255
+ const results: BatchResult[] = new Array(calls.length);
256
+
257
+ const chunks: RpcCall[][] = [];
258
+ for (let i = 0; i < calls.length; i += this.batchSize) {
259
+ chunks.push(calls.slice(i, i + this.batchSize));
260
+ }
261
+
262
+ for (let ci = 0; ci < chunks.length; ci++) {
263
+ const chunk = chunks[ci]!;
264
+ const base = ci * this.batchSize;
265
+
266
+ // Group the chunk by method so we can reserve budget per method and
267
+ // report headers correctly. A chunk may contain mixed methods.
268
+ const byMethod = new Map<string, number[]>();
269
+ chunk.forEach((c, i) => {
270
+ const arr = byMethod.get(c.method) ?? [];
271
+ arr.push(i);
272
+ byMethod.set(c.method, arr);
273
+ });
274
+
275
+ // ONE endpoint for the whole chunk: the budget must be reserved against
276
+ // the same endpoint the request is actually sent to.
277
+ const primaryMethod = chunk[0]!.method;
278
+ let endpoint = this.pickEndpoint(primaryMethod);
279
+
280
+ // Reserve budget for every call in the chunk before sending.
281
+ for (const [method, idxs] of byMethod) {
282
+ await this.acquire(endpoint, method, idxs.length);
283
+ }
284
+
285
+ const payload = chunk.map((call) => ({
286
+ jsonrpc: '2.0',
287
+ id: this.id++,
288
+ method: call.method,
289
+ params: call.params ?? [],
290
+ }));
291
+
292
+ let attempt = 0;
293
+ let settled = false;
294
+
295
+ while (!settled && attempt <= this.maxRetries) {
296
+ const started = Date.now();
297
+
298
+ try {
299
+ const { responses, headers } = await this.post(endpoint, payload);
300
+ this.stats.calls += chunk.length;
301
+
302
+ const primary = chunk[0]!.method;
303
+ this.learnLimits(endpoint, primary, headers);
304
+
305
+ const byId = new Map<number, any>();
306
+ for (const r of responses) byId.set(r?.id, r);
307
+
308
+ let sawRpc429 = false;
309
+ let sawUnsupported = false;
310
+ payload.forEach((p, i) => {
311
+ const r = byId.get(p.id);
312
+ const slot = base + i;
313
+ if (!r) {
314
+ results[slot] = { error: 'missing response', retriable: true };
315
+ } else if (r.error) {
316
+ const code = Number(r.error.code);
317
+ const is429 = code === 429 || code === -32005;
318
+ // -16401 / -32601 = "method not available on this endpoint"
319
+ const isUnsupported = code === -16401 || code === -32601;
320
+ if (is429) sawRpc429 = true;
321
+ if (isUnsupported) sawUnsupported = true;
322
+ results[slot] = {
323
+ error: `${code}: ${r.error.message}`,
324
+ rpcCode: code,
325
+ retriable: is429,
326
+ };
327
+ } else {
328
+ results[slot] = { value: r.result };
329
+ }
330
+ });
331
+
332
+ if (sawUnsupported) {
333
+ // This endpoint refuses one of these methods (paid plan). Mark it
334
+ // and retry the whole chunk elsewhere.
335
+ for (const [method] of byMethod) this.markUnsupported(endpoint, method);
336
+ attempt++;
337
+ endpoint = this.pickEndpoint(primaryMethod);
338
+ for (const [method, idxs] of byMethod) {
339
+ await this.acquire(endpoint, method, idxs.length);
340
+ }
341
+ await sleep(200);
342
+ continue;
343
+ }
344
+
345
+ if (sawRpc429) {
346
+ this.stats.rpc429++;
347
+ this.onEvent?.({ kind: 'rpc429', method: primary, endpoint });
348
+ // The server is stricter than our model: back off the whole method.
349
+ this.block(endpoint, primary, this.windowMs);
350
+ attempt++;
351
+ await sleep(300 * attempt);
352
+ // Re-reserve budget on the SAME endpoint (the previous reservation
353
+ // was consumed by the rejected attempt).
354
+ for (const [method, idxs] of byMethod) {
355
+ await this.acquire(endpoint, method, idxs.length);
356
+ }
357
+ continue;
358
+ }
359
+
360
+ this.onEvent?.({
361
+ kind: 'ok',
362
+ method: primary,
363
+ ms: Date.now() - started,
364
+ batch: chunk.length,
365
+ endpoint,
366
+ });
367
+ settled = true;
368
+ } catch (err) {
369
+ const isHttp = err instanceof HttpError;
370
+ const status = isHttp ? (err as HttpError).status : 0;
371
+ const retryable = status === 429 || status >= 500 || status === 0;
372
+ if (!retryable) {
373
+ const msg = (err as Error).message;
374
+ this.onEvent?.({ kind: 'error', method: primaryMethod, error: msg });
375
+ for (let i = 0; i < chunk.length; i++) {
376
+ if (results[base + i] === undefined) results[base + i] = { error: msg };
377
+ }
378
+ settled = true;
379
+ } else {
380
+ this.stats.retries++;
381
+ this.endpointBlocked.set(endpoint, Date.now() + 1500 * attempt);
382
+ this.onEvent?.({ kind: 'rotate', endpoint, reason: `HTTP ${status}` });
383
+ await sleep(400 * 2 ** attempt + Math.floor(Math.random() * 300));
384
+ attempt++;
385
+ endpoint = this.pickEndpoint(primaryMethod);
386
+ for (const [method, idxs] of byMethod) {
387
+ await this.acquire(endpoint, method, idxs.length);
388
+ }
389
+ }
390
+ }
391
+ }
392
+
393
+ // If we exhausted retries without settling, fill every remaining slot so
394
+ // callers never see `undefined` holes.
395
+ if (!settled) {
396
+ const msg = `exhausted ${this.maxRetries} retries for ${chunk[0]!.method}`;
397
+ for (let i = 0; i < chunk.length; i++) {
398
+ if (results[base + i] === undefined) results[base + i] = { error: msg };
399
+ }
400
+ }
401
+ }
402
+ return results;
403
+ }
404
+
405
+ /** Single call. Throws on RPC error. */
406
+ async call<T>(method: string, params: unknown[] = []): Promise<T> {
407
+ const [res] = await this.batch([{ method, params }]);
408
+ if (!res) throw new Error(`no response for ${method}`);
409
+ if (res.error) throw new Error(`${method}: ${res.error}`);
410
+ return res.value as T;
411
+ }
412
+
413
+ /**
414
+ * Single call that returns null on error.
415
+ * NOTE: `null` means "the call failed", which is different from "the call
416
+ * succeeded and the answer was empty". Callers that need to distinguish
417
+ * must use `batch()` and inspect `error`.
418
+ */
419
+ async tryCall<T>(method: string, params: unknown[] = []): Promise<T | null> {
420
+ const [res] = await this.batch([{ method, params }]);
421
+ if (!res || res.error) return null;
422
+ return res.value as T;
423
+ }
424
+
425
+ /** Single call with an explicit success flag — no ambiguity. */
426
+ async callDetailed<T>(
427
+ method: string,
428
+ params: unknown[] = [],
429
+ ): Promise<{ ok: boolean; value: T | null; error?: string }> {
430
+ const [res] = await this.batch([{ method, params }]);
431
+ if (!res) return { ok: false, value: null, error: 'no response' };
432
+ if (res.error) return { ok: false, value: null, error: res.error };
433
+ return { ok: true, value: res.value as T };
434
+ }
435
+ }