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/worker.ts ADDED
@@ -0,0 +1,1086 @@
1
+ /**
2
+ * worker.ts — the LIQPROOF HTTP surface.
3
+ *
4
+ * ── ONE IMPLEMENTATION, TWO HOSTS ───────────────────────────────────────────
5
+ *
6
+ * This module IS the LIQPROOF server. It runs in two places:
7
+ *
8
+ * • Cloudflare Workers — `export default { fetch(request, env) }`.
9
+ * • The local Node CLI — `liqproof serve` imports `handleRequest` and
10
+ * bridges Node's `http` server onto the Web `Request`/`Response` pair.
11
+ *
12
+ * One implementation means the local server and the deployed Worker cannot
13
+ * drift apart: the 402 challenge a developer tests against locally is
14
+ * byte-for-byte the one a client gets in production.
15
+ *
16
+ * ── WHAT THE WORKER PATH DELIBERATELY AVOIDS ────────────────────────────────
17
+ *
18
+ * 1. `src/store.ts` (node:sqlite). A Worker isolate has no writable disk
19
+ * and `node:sqlite` is a non-functional stub there. Usage counters live
20
+ * in a Cloudflare KV binding (`LIQPROOF_USAGE`) or, failing that, in
21
+ * isolate memory — see `src/x402.ts`.
22
+ *
23
+ * 2. `src/dashboard.ts`. It imports `src/store.ts`, so pulling it in would
24
+ * drag node:sqlite into the Worker for the sake of one HTML-escaping
25
+ * helper. The landing page below therefore keeps its own tiny
26
+ * `escapeHtml` and mirrors the dashboard's visual language by hand.
27
+ *
28
+ * `node:fs` IS reachable from this path, indirectly: `src/util.ts` uses it
29
+ * for the on-disk response cache and `src/canonical.ts` uses it for the
30
+ * canonical-token index. Under the `nodejs_compat` flag (see
31
+ * `deploy/wrangler.toml`) those calls are supported; every one of them is
32
+ * already wrapped in a try/catch, so a read-only virtual filesystem degrades
33
+ * a receipt instead of breaking the request.
34
+ *
35
+ * ── THE MONEY PATH ──────────────────────────────────────────────────────────
36
+ *
37
+ * A request for a receipt is answered in one of three ways:
38
+ *
39
+ * 1. FREE — the client is under its daily allowance. No payment, no
40
+ * signature, no chain write.
41
+ * 2. PAID — the client sent a `PAYMENT-SIGNATURE` header and a FREE
42
+ * facilitator confirmed the payment. We only ever call the
43
+ * facilitator's `/verify` endpoint, which is read-only by
44
+ * specification; `/settle` is never called.
45
+ * 3. 402 — the client is over its allowance and has not paid. We answer
46
+ * with the exact challenge a paying client needs.
47
+ *
48
+ * There is no fourth way. This module cannot move money, and `liqproof
49
+ * verify` proves it by grepping the whole source tree.
50
+ */
51
+
52
+ // ── imports ──────────────────────────────────────────────────────────────────
53
+ //
54
+ // Everything below is either a project module or a Web standard. There is no
55
+ // npm dependency here, and there is no runtime dependency in this project at
56
+ // all — the $0 budget is structural, not a promise.
57
+
58
+ import { buildReceipt, type Receipt } from './receipt.js';
59
+ import { renderMarkdown } from './render.js';
60
+ import { RpcPool } from './rpc.js';
61
+ import {
62
+ buildChallenge,
63
+ DEFAULT_FACILITATORS,
64
+ DEFAULT_FREE_TIER,
65
+ DEFAULT_PRICE_USD,
66
+ encodeChallengeHeader,
67
+ FreeTier,
68
+ HEADER_PAYMENT_LEGACY,
69
+ HEADER_PAYMENT_REQUIRED,
70
+ HEADER_PAYMENT_SIGNATURE,
71
+ KvUsageStore,
72
+ MemoryUsageStore,
73
+ normalizeNetwork,
74
+ parsePaymentHeader,
75
+ verifyPayment,
76
+ type FacilitatorVerifyResult,
77
+ type KvLike,
78
+ type PaymentRequiredChallenge,
79
+ type UsageStore,
80
+ type X402Network,
81
+ } from './x402.js';
82
+
83
+ // ── constants ────────────────────────────────────────────────────────────────
84
+
85
+ /** Version reported by `/health` and embedded in the OpenAPI document. */
86
+ export const VERSION = '0.1.0';
87
+
88
+ /** When this isolate started. `/health` reports uptime against it. */
89
+ const STARTED_AT = Date.now();
90
+
91
+ /** How long a built receipt stays in the in-isolate cache. */
92
+ const RECEIPT_TTL_MS = 60_000;
93
+
94
+ /**
95
+ * How long a built receipt may live in Cloudflare KV.
96
+ *
97
+ * Five minutes is short enough that a drain event cannot stay hidden for
98
+ * long, and long enough to take the expensive RPC work off the hot path —
99
+ * which matters because the Workers free plan only grants 10 ms of CPU per
100
+ * invocation.
101
+ */
102
+ const RECEIPT_KV_TTL_SECONDS = 300;
103
+
104
+ /**
105
+ * The mint used for the live example on the landing page.
106
+ *
107
+ * BAT (native) is the canonical trap: the market advertises ~$136,104,308 of
108
+ * liquidity and the pool vault holds ~$23.53 of real USDC. It is a good
109
+ * first impression because the gap is impossible to argue with.
110
+ */
111
+ export const EXAMPLE_MINT = 'BTNiaZb6HaEFWeEtND4SXtZ7T6mgtDwSryHTAj6PuPyp';
112
+
113
+ /** A Solana mint or wallet address is base58, 32–44 characters. */
114
+ const SOLANA_ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
115
+
116
+ /** Default number of transactions the liquidity curve may scan. */
117
+ const DEFAULT_MAX_TRANSACTIONS = 120;
118
+
119
+ // ── environment ──────────────────────────────────────────────────────────────
120
+
121
+ /**
122
+ * Everything the server can be configured with.
123
+ *
124
+ * In a Worker these are `vars` and `secrets` from `deploy/wrangler.toml`; in
125
+ * the local CLI they are built from flags and environment variables. Same
126
+ * shape, same semantics, one implementation.
127
+ */
128
+ export interface WorkerEnv {
129
+ /** Solana address that receives USDC payments. */
130
+ PAY_TO?: string;
131
+ /** Facilitator base URL. Free defaults are used when unset. */
132
+ X402_FACILITATOR?: string;
133
+ /** Price of one receipt, in US dollars. */
134
+ X402_PRICE_USD?: string;
135
+ /** Free receipts per client per UTC day. */
136
+ X402_FREE_TIER?: string;
137
+ /** `solana` (default) or `solana-devnet`. */
138
+ X402_NETWORK?: string;
139
+ /** Optional facilitator API key (Coinbase CDP). */
140
+ X402_API_KEY?: string;
141
+ /** How many transactions the liquidity curve may scan. */
142
+ X402_MAX_TX?: string;
143
+ /** Optional KV namespace holding the daily usage counters. */
144
+ LIQPROOF_USAGE?: KvLike;
145
+ /** Optional KV namespace holding built receipts. */
146
+ LIQPROOF_RECEIPTS?: KvLike;
147
+ /**
148
+ * An explicitly injected usage store.
149
+ *
150
+ * The Worker has no writable disk, so it uses a KV binding. The local CLI
151
+ * has a disk and no KV, so it injects a `DiskUsageStore` over the project's
152
+ * own `DiskCache` — which means the local server's daily free-tier counter
153
+ * survives a restart without a database.
154
+ */
155
+ USAGE_STORE?: UsageStore;
156
+ }
157
+
158
+ /** The resolved, validated configuration for one request. */
159
+ export interface ServerConfig {
160
+ /** Where payments go, or null when the deployment has no recipient. */
161
+ payTo: string | null;
162
+ priceUsd: number;
163
+ freeTier: number;
164
+ network: X402Network;
165
+ facilitators: string[];
166
+ apiKey?: string;
167
+ maxTransactions: number;
168
+ }
169
+
170
+ /**
171
+ * Turn the raw environment into a validated configuration.
172
+ *
173
+ * Every value falls back to a free default rather than failing the request:
174
+ * a deployment with no configuration at all still serves the free tier, which
175
+ * is the whole point of the free tier.
176
+ */
177
+ export function resolveConfig(env: WorkerEnv): ServerConfig {
178
+ const priceUsd = Number(env.X402_PRICE_USD ?? DEFAULT_PRICE_USD);
179
+ const freeTier = Number(env.X402_FREE_TIER ?? DEFAULT_FREE_TIER);
180
+ const facilitator = (env.X402_FACILITATOR ?? '').trim();
181
+ const maxTx = Number(env.X402_MAX_TX ?? DEFAULT_MAX_TRANSACTIONS);
182
+ const payTo = (env.PAY_TO ?? '').trim();
183
+
184
+ return {
185
+ payTo: SOLANA_ADDRESS.test(payTo) ? payTo : null,
186
+ priceUsd: Number.isFinite(priceUsd) && priceUsd >= 0 ? priceUsd : DEFAULT_PRICE_USD,
187
+ freeTier:
188
+ Number.isFinite(freeTier) && freeTier >= 0 ? Math.floor(freeTier) : DEFAULT_FREE_TIER,
189
+ network: normalizeNetwork(env.X402_NETWORK),
190
+ // A configured facilitator is tried FIRST; the free defaults remain as a
191
+ // fallback so a typo in configuration degrades to "still works".
192
+ facilitators: facilitator ? [facilitator, ...DEFAULT_FACILITATORS] : DEFAULT_FACILITATORS,
193
+ apiKey: (env.X402_API_KEY ?? '').trim() || undefined,
194
+ maxTransactions:
195
+ Number.isFinite(maxTx) && maxTx > 0 ? Math.floor(maxTx) : DEFAULT_MAX_TRANSACTIONS,
196
+ };
197
+ }
198
+
199
+ // ── shared, isolate-scoped state ─────────────────────────────────────────────
200
+
201
+ /**
202
+ * One RPC pool per isolate.
203
+ *
204
+ * The pool learns the free tier's real rate limits from response headers and
205
+ * keeps a token bucket per (endpoint, method). Creating a new pool per
206
+ * request would throw that state away every time and earn us a 429.
207
+ */
208
+ const rpc = new RpcPool({});
209
+
210
+ /**
211
+ * In-isolate receipt cache.
212
+ *
213
+ * A Worker isolate is reused across requests, so a `Map` is a real cache and
214
+ * not just a convenient container. Sixty seconds is short enough that the
215
+ * numbers on a receipt are still true, and long enough to absorb a burst.
216
+ */
217
+ interface ReceiptCacheEntry {
218
+ receipt: Receipt;
219
+ expires: number;
220
+ }
221
+
222
+ const receiptCache = new Map<string, ReceiptCacheEntry>();
223
+
224
+ /**
225
+ * In-isolate usage counters.
226
+ *
227
+ * A Worker has no writable disk, so the daily free-tier counters live in
228
+ * memory. The worst case is that a very long-lived isolate hands out a few
229
+ * extra free receipts; attach a KV binding (`LIQPROOF_USAGE`) to make the
230
+ * counter survive isolate recycling.
231
+ */
232
+ const memoryUsage = new MemoryUsageStore();
233
+
234
+ /** Pick the usage store: an injected one, else KV, else isolate memory. */
235
+ function usageStore(env: WorkerEnv): UsageStore {
236
+ if (env.USAGE_STORE) return env.USAGE_STORE;
237
+ if (env.LIQPROOF_USAGE) return new KvUsageStore(env.LIQPROOF_USAGE);
238
+ return memoryUsage;
239
+ }
240
+
241
+ // ── small helpers ────────────────────────────────────────────────────────────
242
+
243
+ /** JSON response with the headers every endpoint wants. */
244
+ function json(value: unknown, status = 200, extraHeaders: Record<string, string> = {}): Response {
245
+ return new Response(JSON.stringify(value, null, 2), {
246
+ status,
247
+ headers: {
248
+ 'content-type': 'application/json; charset=utf-8',
249
+ 'cache-control': 'no-store',
250
+ ...extraHeaders,
251
+ },
252
+ });
253
+ }
254
+
255
+ /** FNV-1a 32-bit hash — stable, dependency-free, good enough for a key. */
256
+ function hash32(s: string): string {
257
+ let h = 0x811c9dc5;
258
+ for (let i = 0; i < s.length; i++) {
259
+ h ^= s.charCodeAt(i);
260
+ h = Math.imul(h, 0x01000193) >>> 0;
261
+ }
262
+ return h.toString(16).padStart(8, '0');
263
+ }
264
+
265
+ /**
266
+ * Escape a value for interpolation into the landing page.
267
+ *
268
+ * A local copy of the helper in `src/dashboard.ts` — importing that module
269
+ * would drag `src/store.ts` (node:sqlite) into the Worker. The duplication
270
+ * is deliberate and is the reason this file carries the note at the top.
271
+ */
272
+ function escapeHtml(value: unknown): string {
273
+ const amp = String.fromCharCode(38);
274
+ const s = String(value ?? '');
275
+ return s
276
+ .replace(/&/g, amp + 'amp;')
277
+ .replace(/</g, amp + 'lt;')
278
+ .replace(/>/g, amp + 'gt;')
279
+ .replace(/"/g, amp + 'quot;')
280
+ .replace(/'/g, amp + '#39;');
281
+ }
282
+
283
+ /** Format a dollar amount the way the dashboard does. */
284
+ function formatUsd(n: number | null | undefined): string {
285
+ if (n === null || n === undefined || !Number.isFinite(n)) return '—';
286
+ const abs = Math.abs(n);
287
+ if (abs >= 1_000_000_000) return `$${(n / 1_000_000_000).toFixed(2)}B`;
288
+ if (abs >= 1_000_000) return `$${(n / 1_000_000).toFixed(2)}M`;
289
+ if (abs >= 1_000) return `$${(n / 1_000).toFixed(2)}K`;
290
+ if (abs >= 1) return `$${n.toFixed(2)}`;
291
+ return `$${n.toFixed(4)}`;
292
+ }
293
+
294
+ /**
295
+ * Coverage needs extra digits when it is tiny: 0.0000% is the difference
296
+ * between "empty" and "one part in a million".
297
+ */
298
+ function formatCoverage(n: number | null | undefined): string {
299
+ if (n === null || n === undefined || !Number.isFinite(n)) return '—';
300
+ const pctValue = n * 100;
301
+ if (pctValue === 0) return '0%';
302
+ if (pctValue < 0.0001) return `${pctValue.toExponential(3)}%`;
303
+ if (pctValue < 0.01) return `${pctValue.toFixed(6)}%`;
304
+ if (pctValue < 1) return `${pctValue.toFixed(4)}%`;
305
+ return `${pctValue.toFixed(2)}%`;
306
+ }
307
+
308
+ /**
309
+ * Identify the client for the purpose of the daily free tier.
310
+ *
311
+ * Cloudflare puts the real client address in `CF-Connecting-IP`; the local
312
+ * Node server has neither, so the user agent stands in. Either way the key
313
+ * is opaque and nobody has to trust a header we did not ask for.
314
+ */
315
+ function clientKey(request: Request): string {
316
+ const forwarded = request.headers.get('x-forwarded-for');
317
+ const ip =
318
+ request.headers.get('cf-connecting-ip') ?? (forwarded ? forwarded.split(',')[0]?.trim() : null);
319
+ if (ip) return ip;
320
+ const agent = request.headers.get('user-agent');
321
+ if (agent) return 'ua-' + hash32(agent);
322
+ return 'anonymous';
323
+ }
324
+
325
+ // ── receipt loading ──────────────────────────────────────────────────────────
326
+
327
+ /** Where a receipt came from. Surfaced as a response header. */
328
+ export type ReceiptOrigin = 'fresh' | 'isolate-cache' | 'kv-cache';
329
+
330
+ interface LoadedReceipt {
331
+ receipt: Receipt;
332
+ origin: ReceiptOrigin;
333
+ }
334
+
335
+ /**
336
+ * Build a receipt, using every cache we have.
337
+ *
338
+ * Order matters. The in-isolate `Map` is the fastest and the freshest; KV
339
+ * is slower but survives isolate recycling; only when both miss do we spend
340
+ * RPC calls and CPU to build the receipt from scratch.
341
+ */
342
+ async function loadReceipt(
343
+ mint: string,
344
+ opts: { curve: boolean; maxTransactions: number },
345
+ env: WorkerEnv,
346
+ ): Promise<LoadedReceipt> {
347
+ const key = `${mint}|${opts.curve ? 'full' : 'quick'}`;
348
+
349
+ const hit = receiptCache.get(key);
350
+ if (hit && Date.now() < hit.expires) {
351
+ return { receipt: hit.receipt, origin: 'isolate-cache' };
352
+ }
353
+
354
+ const kv = env.LIQPROOF_RECEIPTS;
355
+ if (kv) {
356
+ const raw = await kv.get(`receipt:${key}`);
357
+ if (raw) {
358
+ try {
359
+ const parsed = JSON.parse(raw) as Receipt;
360
+ if (parsed && parsed.mint === mint) {
361
+ receiptCache.set(key, { receipt: parsed, expires: Date.now() + RECEIPT_TTL_MS });
362
+ return { receipt: parsed, origin: 'kv-cache' };
363
+ }
364
+ } catch {
365
+ // A corrupt cache entry must never break a request: fall through and
366
+ // rebuild from the chain.
367
+ }
368
+ }
369
+ }
370
+
371
+ const receipt = await buildReceipt(rpc, mint, {
372
+ includeCurve: opts.curve,
373
+ maxTransactions: opts.maxTransactions,
374
+ });
375
+
376
+ receiptCache.set(key, { receipt, expires: Date.now() + RECEIPT_TTL_MS });
377
+
378
+ if (kv) {
379
+ try {
380
+ await kv.put(`receipt:${key}`, JSON.stringify(receipt), {
381
+ expirationTtl: RECEIPT_KV_TTL_SECONDS,
382
+ });
383
+ } catch {
384
+ // A KV write failure is not a request failure.
385
+ }
386
+ }
387
+
388
+ return { receipt, origin: 'fresh' };
389
+ }
390
+
391
+ // ── the x402 gate ────────────────────────────────────────────────────────────
392
+
393
+ /** The outcome of looking for a payment on an incoming request. */
394
+ interface PaymentCheck {
395
+ /** Did the client send a payment header at all? */
396
+ present: boolean;
397
+ /** Did a facilitator confirm it? */
398
+ ok: boolean;
399
+ /** Why it failed, when it failed. */
400
+ reason: string | null;
401
+ /** The facilitator's verdict, when there was one. */
402
+ result: FacilitatorVerifyResult | null;
403
+ }
404
+
405
+ /** The 402 challenge for one resource. */
406
+ function challengeFor(
407
+ url: URL,
408
+ config: ServerConfig,
409
+ mint: string,
410
+ error?: string | null,
411
+ ): PaymentRequiredChallenge {
412
+ return buildChallenge({
413
+ network: config.network,
414
+ priceUsd: config.priceUsd,
415
+ payTo: config.payTo ?? '',
416
+ resourceUrl: `${url.origin}/receipt/${mint}`,
417
+ description: `LIQPROOF liquidity receipt for ${mint}`,
418
+ mimeType: 'application/json',
419
+ error: error ?? undefined,
420
+ });
421
+ }
422
+
423
+ /**
424
+ * Look for a payment and, if there is one, ask a facilitator about it.
425
+ *
426
+ * READ-ONLY BY CONSTRUCTION: `verifyPayment` only ever calls the
427
+ * facilitator's `/verify` endpoint. We never call `/settle`, never build a
428
+ * transaction and never sign. If the client paid, the client settled it.
429
+ */
430
+ async function checkPayment(
431
+ request: Request,
432
+ url: URL,
433
+ config: ServerConfig,
434
+ mint: string,
435
+ ): Promise<PaymentCheck> {
436
+ const raw =
437
+ request.headers.get(HEADER_PAYMENT_SIGNATURE) ??
438
+ request.headers.get(HEADER_PAYMENT_LEGACY);
439
+ if (!raw) {
440
+ return { present: false, ok: false, reason: null, result: null };
441
+ }
442
+
443
+ const payload = parsePaymentHeader(raw);
444
+ if (!payload) {
445
+ return {
446
+ present: true,
447
+ ok: false,
448
+ reason: 'the payment header is not a base64-encoded JSON payload',
449
+ result: null,
450
+ };
451
+ }
452
+
453
+ const requirement = challengeFor(url, config, mint).accepts[0]!;
454
+ const result = await verifyPayment(payload, {
455
+ requirement,
456
+ facilitators: config.facilitators,
457
+ apiKey: config.apiKey,
458
+ });
459
+
460
+ return {
461
+ present: true,
462
+ ok: result.ok,
463
+ reason: result.ok
464
+ ? null
465
+ : (result.message ?? result.reason ?? 'the facilitator rejected this payment'),
466
+ result,
467
+ };
468
+ }
469
+
470
+ /**
471
+ * The 402 answer: the challenge as JSON and as the v2 response header.
472
+ *
473
+ * The challenge is serialized ONCE, so the header and the body carry the
474
+ * exact same bytes. A client can decode the header and compare it with the
475
+ * body without parsing anything.
476
+ */
477
+ function challengeResponse(challenge: PaymentRequiredChallenge): Response {
478
+ const text = JSON.stringify(challenge, null, 2);
479
+ return new Response(text, {
480
+ status: 402,
481
+ headers: {
482
+ 'content-type': 'application/json; charset=utf-8',
483
+ 'cache-control': 'no-store',
484
+ [HEADER_PAYMENT_REQUIRED]: encodeChallengeHeader(text),
485
+ },
486
+ });
487
+ }
488
+
489
+ // ── routes ───────────────────────────────────────────────────────────────────
490
+
491
+ /**
492
+ * Serve a receipt for one mint.
493
+ *
494
+ * The order of the checks is the product:
495
+ *
496
+ * 1. Is there a valid payment? Serve it (and do not touch the free tier).
497
+ * 2. Is the client under its daily allowance? Serve it free.
498
+ * 3. Otherwise answer 402 with the exact challenge.
499
+ */
500
+ async function receiptRoute(
501
+ request: Request,
502
+ url: URL,
503
+ env: WorkerEnv,
504
+ ): Promise<Response> {
505
+ const mint = url.pathname.slice('/receipt/'.length).split('/')[0]!.trim();
506
+ if (!SOLANA_ADDRESS.test(mint)) {
507
+ return json(
508
+ {
509
+ error: 'invalid_mint',
510
+ hint: 'expected a base58 Solana mint (32-44 characters)',
511
+ },
512
+ 400,
513
+ );
514
+ }
515
+
516
+ const format =
517
+ url.searchParams.get('format') === 'md' || url.searchParams.get('format') === 'markdown'
518
+ ? 'md'
519
+ : 'json';
520
+
521
+ const config = resolveConfig(env);
522
+
523
+ // Without a payment recipient we cannot ask for money we cannot receive.
524
+ // We still serve the free tier — that is the whole point of the free tier.
525
+ const canCharge = config.payTo !== null;
526
+
527
+ const payment = canCharge
528
+ ? await checkPayment(request, url, config, mint)
529
+ : { present: false, ok: false, reason: null, result: null };
530
+
531
+ const client = clientKey(request);
532
+ const tier = new FreeTier(usageStore(env), config.freeTier);
533
+
534
+ if (payment.ok) {
535
+ return serveReceipt(mint, format, config, env, {
536
+ access: 'paid',
537
+ freeTier: null,
538
+ payer: payment.result?.payer ?? null,
539
+ });
540
+ }
541
+
542
+ // No valid payment: fall back to the free allowance.
543
+ const state = await tier.consume(client);
544
+ if (state.allowed) {
545
+ try {
546
+ return await serveReceipt(mint, format, config, env, {
547
+ access: 'free',
548
+ freeTier: state,
549
+ payer: null,
550
+ });
551
+ } catch (err) {
552
+ // Our infrastructure failed, not the client. Give the receipt back.
553
+ await tier.refund(client);
554
+ throw err;
555
+ }
556
+ }
557
+
558
+ // Over the allowance and unpaid. If a payment WAS sent and rejected, say
559
+ // why — a silent 402 would send the client around in circles.
560
+ if (payment.present && payment.reason) {
561
+ return challengeResponse(challengeFor(url, config, mint, payment.reason));
562
+ }
563
+
564
+ if (!canCharge) {
565
+ return json(
566
+ {
567
+ error: 'payment_recipient_not_configured',
568
+ hint: 'this deployment has no PAY_TO address, so paid access is disabled',
569
+ },
570
+ 503,
571
+ );
572
+ }
573
+
574
+ return challengeResponse(challengeFor(url, config, mint));
575
+ }
576
+
577
+ /** How a receipt is being served, for the response headers. */
578
+ interface AccessInfo {
579
+ access: 'free' | 'paid';
580
+ freeTier: { used: number; limit: number; day: string } | null;
581
+ payer: string | null;
582
+ }
583
+
584
+ /** Build and return the receipt itself, in JSON or markdown. */
585
+ async function serveReceipt(
586
+ mint: string,
587
+ format: 'json' | 'md',
588
+ config: ServerConfig,
589
+ env: WorkerEnv,
590
+ access: AccessInfo,
591
+ ): Promise<Response> {
592
+ const { receipt, origin } = await loadReceipt(
593
+ mint,
594
+ { curve: true, maxTransactions: config.maxTransactions },
595
+ env,
596
+ );
597
+
598
+ const headers: Record<string, string> = {
599
+ 'x-liqproof-access': access.access,
600
+ 'x-liqproof-receipt-origin': origin,
601
+ 'x-liqproof-verdict': receipt.verdict,
602
+ };
603
+ if (access.freeTier) {
604
+ headers['x-liqproof-free-tier'] = `${access.freeTier.used}/${access.freeTier.limit}`;
605
+ }
606
+ if (access.payer) headers['x-liqproof-payer'] = access.payer;
607
+
608
+ if (format === 'md') {
609
+ return new Response(renderMarkdown(receipt), {
610
+ status: 200,
611
+ headers: {
612
+ ...headers,
613
+ 'content-type': 'text/markdown; charset=utf-8',
614
+ 'cache-control': 'no-store',
615
+ },
616
+ });
617
+ }
618
+
619
+ return json(receipt, 200, headers);
620
+ }
621
+
622
+ /** `/health` — cheap, uncached, never touches the chain. */
623
+ function healthResponse(): Response {
624
+ return json({
625
+ ok: true,
626
+ version: VERSION,
627
+ uptime: Math.floor((Date.now() - STARTED_AT) / 1000),
628
+ });
629
+ }
630
+
631
+ // ── landing page ─────────────────────────────────────────────────────────────
632
+
633
+ /**
634
+ * The landing page.
635
+ *
636
+ * One LIVE example receipt, built from the chain at request time, in the
637
+ * visual language of the offline dashboard (`src/dashboard.ts`). A landing
638
+ * page that shows invented numbers would be the exact opposite of this
639
+ * product, so if the chain cannot be read right now we say so instead of
640
+ * printing stale fiction.
641
+ */
642
+ async function landingResponse(url: URL, env: WorkerEnv): Promise<Response> {
643
+ const config = resolveConfig(env);
644
+
645
+ let example: Receipt | null = null;
646
+ let exampleError: string | null = null;
647
+ try {
648
+ // The curve is skipped here: the landing page needs the verdict and the
649
+ // vault balances, not the whole transaction history, and the curve is
650
+ // the expensive part.
651
+ const loaded = await loadReceipt(
652
+ EXAMPLE_MINT,
653
+ { curve: false, maxTransactions: config.maxTransactions },
654
+ env,
655
+ );
656
+ example = loaded.receipt;
657
+ } catch (err) {
658
+ exampleError = (err as Error).message.slice(0, 120);
659
+ }
660
+
661
+ const html = renderLanding(example, exampleError, url.origin, config);
662
+
663
+ return new Response(html, {
664
+ status: 200,
665
+ headers: {
666
+ 'content-type': 'text/html; charset=utf-8',
667
+ 'cache-control': 'public, max-age=60',
668
+ },
669
+ });
670
+ }
671
+
672
+ /** Render the landing page HTML. Pure — takes the receipt, returns a string. */
673
+ export function renderLanding(
674
+ example: Receipt | null,
675
+ exampleError: string | null,
676
+ origin: string,
677
+ config: ServerConfig,
678
+ ): string {
679
+ const exampleBlock = example
680
+ ? `
681
+ <section>
682
+ <h2>Live example — ${escapeHtml(example.symbol ?? example.mint)}</h2>
683
+ <div class="panel">
684
+ <div class="stats">
685
+ <div class="stat bad"><div class="stat-label">claimed liquidity</div><div class="stat-value">${escapeHtml(formatUsd(example.claimed.liquidityUsd))}</div></div>
686
+ <div class="stat good"><div class="stat-label">actually deposited</div><div class="stat-value">${escapeHtml(formatUsd(example.real.depositedUsd))}</div></div>
687
+ <div class="stat"><div class="stat-label">coverage</div><div class="stat-value">${escapeHtml(formatCoverage(example.real.coverage))}</div></div>
688
+ <div class="stat"><div class="stat-label">verdict</div><div class="stat-value"><span class="tag ${escapeHtml(example.verdict)}">${escapeHtml(example.verdict)}</span></div></div>
689
+ </div>
690
+ <p class="headline">${escapeHtml(example.headline)}</p>
691
+ <p class="mono dim">${escapeHtml(example.mint)}</p>
692
+ <p class="mono dim">read from Solana mainnet at ${escapeHtml(example.generatedAt)}</p>
693
+ <p><a href="${escapeHtml(origin)}/receipt/${escapeHtml(example.mint)}">open the full receipt →</a></p>
694
+ </div>
695
+ </section>`
696
+ : `
697
+ <section>
698
+ <h2>Live example</h2>
699
+ <div class="panel">
700
+ <p class="dim">The example receipt could not be built right now${exampleError ? `: ${escapeHtml(exampleError)}` : '.'}</p>
701
+ <p class="dim">We will not print numbers we did not just read from the chain. Try the receipt endpoint directly:</p>
702
+ <p><a href="${escapeHtml(origin)}/receipt/${escapeHtml(EXAMPLE_MINT)}">/receipt/${escapeHtml(EXAMPLE_MINT)} →</a></p>
703
+ </div>
704
+ </section>`;
705
+
706
+ return `<!doctype html>
707
+ <html lang="en">
708
+ <head>
709
+ <meta charset="utf-8">
710
+ <meta name="viewport" content="width=device-width, initial-scale=1">
711
+ <title>LIQPROOF — on-chain liquidity receipts</title>
712
+ <style>
713
+ :root {
714
+ --bg: #0a0a0f;
715
+ --panel: #11111a;
716
+ --panel-2: #161622;
717
+ --line: #262633;
718
+ --fg: #f2f2f6;
719
+ --dim: #8b8b9a;
720
+ --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
721
+ --red: #ff3b5c;
722
+ --green: #22c55e;
723
+ --amber: #ffb020;
724
+ --gray: #8b8b9a;
725
+ }
726
+ * { box-sizing: border-box; }
727
+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--fg); }
728
+ body { font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; line-height: 1.5; padding: 0 0 48px; }
729
+ .mono, code, th, .stat-value, .tag { font-family: var(--mono); }
730
+ header { border-bottom: 1px solid var(--line); background: linear-gradient(180deg, #0d0d15 0%, #0a0a0f 100%); padding: 28px 20px 22px; }
731
+ .wrap { max-width: 980px; margin: 0 auto; }
732
+ h1 { font-family: var(--mono); font-size: 26px; letter-spacing: 6px; margin: 0 0 6px; }
733
+ .tagline { color: var(--dim); margin: 0 0 22px; font-size: 15px; }
734
+ .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; }
735
+ .stat { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 12px 14px; }
736
+ .stat-label { color: var(--dim); font-size: 11px; letter-spacing: 1.5px; text-transform: uppercase; font-family: var(--mono); }
737
+ .stat-value { font-size: 22px; margin-top: 4px; }
738
+ .stat.bad .stat-value { color: var(--red); }
739
+ .stat.good .stat-value { color: var(--green); }
740
+ main { max-width: 980px; margin: 0 auto; padding: 24px 20px; }
741
+ section { margin-bottom: 34px; }
742
+ h2 { font-family: var(--mono); font-size: 14px; letter-spacing: 2px; text-transform: uppercase; color: var(--dim); margin: 0 0 12px; border-bottom: 1px solid var(--line); padding-bottom: 8px; }
743
+ .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 16px; }
744
+ .headline { margin: 14px 0 6px; font-size: 16px; }
745
+ .dim { color: var(--dim); }
746
+ .tag { font-size: 11px; letter-spacing: 1px; padding: 2px 7px; border-radius: 4px; border: 1px solid currentColor; display: inline-block; }
747
+ .tag.FAKE_LIQUIDITY, .tag.NO_DEPTH, .tag.DRAINED { color: var(--red); }
748
+ .tag.THIN, .tag.UNBACKED_LIQUIDITY { color: var(--amber); }
749
+ .tag.NO_ROUTE { color: #38bdf8; }
750
+ .tag.CONSISTENT { color: var(--green); }
751
+ .tag.UNKNOWN { color: var(--gray); }
752
+ table { border-collapse: collapse; width: 100%; }
753
+ td, th { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); font-size: 13px; }
754
+ th { color: var(--dim); font-size: 11px; letter-spacing: 1px; text-transform: uppercase; font-family: var(--mono); font-weight: 400; }
755
+ a { color: #6ea8fe; text-decoration: none; }
756
+ a:hover { text-decoration: underline; }
757
+ code { color: #c3e88d; }
758
+ footer { max-width: 980px; margin: 0 auto; padding: 0 20px; color: var(--dim); font-size: 12px; border-top: 1px solid var(--line); padding-top: 16px; }
759
+ @media (max-width: 640px) { h1 { font-size: 20px; letter-spacing: 4px; } }
760
+ </style>
761
+ </head>
762
+ <body>
763
+ <header>
764
+ <div class="wrap">
765
+ <h1>LIQPROOF</h1>
766
+ <p class="tagline">The chain doesn't lie. We keep receipts.</p>
767
+ </div>
768
+ </header>
769
+ <main>
770
+ <section>
771
+ <h2>What this is</h2>
772
+ <div class="panel">
773
+ <p>Every token claim gets a receipt: what the market <strong>claimed</strong>, what is <strong>actually deposited</strong> in the pool vault, when the money left, and whether you can really trade it.</p>
774
+ <p class="dim">Read-only. No gas. No paid APIs. No chain mutation. ${escapeHtml(config.freeTier)} free receipts per client per day, then ${escapeHtml(formatUsd(config.priceUsd))} each via x402.</p>
775
+ </div>
776
+ </section>
777
+ ${exampleBlock}
778
+ <section>
779
+ <h2>Endpoints</h2>
780
+ <div class="panel">
781
+ <table>
782
+ <thead><tr><th>route</th><th>what it returns</th></tr></thead>
783
+ <tbody>
784
+ <tr><td class="mono"><a href="${escapeHtml(origin)}/receipt/<mint>">GET /receipt/{mint}</a></td><td>the receipt as JSON, or markdown with <code>?format=md</code></td></tr>
785
+ <tr><td class="mono"><a href="${escapeHtml(origin)}/health">GET /health</a></td><td>liveness, version, uptime</td></tr>
786
+ <tr><td class="mono"><a href="${escapeHtml(origin)}/openapi.json">GET /openapi.json</a></td><td>OpenAPI 3.1 description of this API</td></tr>
787
+ </tbody>
788
+ </table>
789
+ </div>
790
+ </section>
791
+ </main>
792
+ <footer>
793
+ <p>LIQPROOF reports on-chain measurements only. It does not issue investment advice or legal conclusions.</p>
794
+ <p>Read-only on-chain measurements. No gas, no paid APIs, no chain mutation.</p>
795
+ </footer>
796
+ </body>
797
+ </html>
798
+ `;
799
+ }
800
+
801
+ // ── OpenAPI ──────────────────────────────────────────────────────────────────
802
+
803
+ /**
804
+ * The OpenAPI 3.1 description of this API.
805
+ *
806
+ * 3.1 (not 3.0) because it is the version that matches JSON Schema 2020-12,
807
+ * which is what the x402 challenge object is.
808
+ */
809
+ export function openApiDocument(origin: string): Record<string, unknown> {
810
+ return {
811
+ openapi: '3.1.0',
812
+ info: {
813
+ title: 'LIQPROOF',
814
+ version: VERSION,
815
+ summary: 'On-chain liquidity receipts.',
816
+ description:
817
+ 'Every token claim gets a receipt: what the market claimed, what is actually deposited in the pool vault, when the money left, and whether you can really trade it. Read-only, $0 infrastructure.',
818
+ license: { name: 'MIT', identifier: 'MIT' },
819
+ },
820
+ servers: [{ url: origin }],
821
+ paths: {
822
+ '/receipt/{mint}': {
823
+ get: {
824
+ operationId: 'getReceipt',
825
+ summary: 'Get the liquidity receipt for a Solana mint.',
826
+ description:
827
+ 'Returns the receipt for the given mint. The first requests of each day are free; afterwards the endpoint answers 402 with an x402 challenge. Pay with USDC on Solana and retry with the PAYMENT-SIGNATURE header.',
828
+ parameters: [
829
+ {
830
+ name: 'mint',
831
+ in: 'path',
832
+ required: true,
833
+ description: 'Base58 Solana mint address.',
834
+ schema: { type: 'string', pattern: '^[1-9A-HJ-NP-Za-km-z]{32,44}$' },
835
+ },
836
+ {
837
+ name: 'format',
838
+ in: 'query',
839
+ required: false,
840
+ description: 'Response format.',
841
+ schema: { type: 'string', enum: ['json', 'md'], default: 'json' },
842
+ },
843
+ ],
844
+ responses: {
845
+ '200': {
846
+ description: 'The receipt.',
847
+ content: {
848
+ 'application/json': {
849
+ schema: { $ref: '#/components/schemas/Receipt' },
850
+ },
851
+ 'text/markdown': {
852
+ schema: { type: 'string' },
853
+ },
854
+ },
855
+ },
856
+ '400': {
857
+ description: 'The mint is not a base58 Solana address.',
858
+ content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
859
+ },
860
+ '402': {
861
+ description:
862
+ 'Payment required. The body and the PAYMENT-REQUIRED header both carry the x402 challenge.',
863
+ headers: {
864
+ 'payment-required': {
865
+ description: 'Base64-encoded x402 challenge (same JSON as the body).',
866
+ schema: { type: 'string' },
867
+ },
868
+ },
869
+ content: {
870
+ 'application/json': {
871
+ schema: { $ref: '#/components/schemas/PaymentRequired' },
872
+ },
873
+ },
874
+ },
875
+ '503': {
876
+ description: 'This deployment has no payment recipient configured.',
877
+ content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
878
+ },
879
+ },
880
+ },
881
+ },
882
+ '/health': {
883
+ get: {
884
+ operationId: 'getHealth',
885
+ summary: 'Liveness probe.',
886
+ responses: {
887
+ '200': {
888
+ description: 'The worker is alive.',
889
+ content: {
890
+ 'application/json': {
891
+ schema: {
892
+ type: 'object',
893
+ required: ['ok', 'version', 'uptime'],
894
+ properties: {
895
+ ok: { type: 'boolean' },
896
+ version: { type: 'string' },
897
+ uptime: { type: 'integer', description: 'Seconds since start.' },
898
+ },
899
+ },
900
+ },
901
+ },
902
+ },
903
+ },
904
+ },
905
+ },
906
+ },
907
+ components: {
908
+ schemas: {
909
+ PaymentRequired: {
910
+ type: 'object',
911
+ required: ['x402Version', 'error', 'resource', 'accepts'],
912
+ properties: {
913
+ x402Version: { type: 'integer', const: 2 },
914
+ error: { type: 'string' },
915
+ resource: {
916
+ type: 'object',
917
+ required: ['url', 'description', 'mimeType'],
918
+ properties: {
919
+ url: { type: 'string' },
920
+ description: { type: 'string' },
921
+ mimeType: { type: 'string' },
922
+ },
923
+ },
924
+ accepts: {
925
+ type: 'array',
926
+ items: { $ref: '#/components/schemas/PaymentRequirements' },
927
+ },
928
+ },
929
+ },
930
+ PaymentRequirements: {
931
+ type: 'object',
932
+ required: ['scheme', 'network', 'asset', 'amount', 'payTo', 'maxTimeoutSeconds'],
933
+ properties: {
934
+ scheme: { type: 'string', const: 'exact' },
935
+ network: { type: 'string', enum: ['solana', 'solana-devnet'] },
936
+ asset: { type: 'string', description: 'USDC mint.' },
937
+ amount: { type: 'string', description: 'Price in atomic units of the asset.' },
938
+ payTo: { type: 'string', description: 'Recipient address.' },
939
+ maxTimeoutSeconds: { type: 'integer' },
940
+ description: { type: 'string' },
941
+ extra: { type: 'object', additionalProperties: true },
942
+ },
943
+ },
944
+ Receipt: {
945
+ type: 'object',
946
+ required: ['version', 'generatedAt', 'mint', 'verdict', 'claimed', 'real'],
947
+ properties: {
948
+ version: { type: 'string' },
949
+ generatedAt: { type: 'string' },
950
+ mint: { type: 'string' },
951
+ symbol: { type: 'string' },
952
+ name: { type: 'string' },
953
+ verdict: {
954
+ type: 'string',
955
+ enum: [
956
+ 'FAKE_LIQUIDITY',
957
+ 'UNBACKED_LIQUIDITY',
958
+ 'NO_DEPTH',
959
+ 'DRAINED',
960
+ 'THIN',
961
+ 'CONSISTENT',
962
+ 'NO_ROUTE',
963
+ 'UNKNOWN',
964
+ ],
965
+ },
966
+ headline: { type: 'string' },
967
+ summary: { type: 'string' },
968
+ claimed: { type: 'object', additionalProperties: true },
969
+ real: { type: 'object', additionalProperties: true },
970
+ evidence: { type: 'array', items: { type: 'object', additionalProperties: true } },
971
+ },
972
+ },
973
+ Error: {
974
+ type: 'object',
975
+ required: ['error'],
976
+ properties: {
977
+ error: { type: 'string' },
978
+ hint: { type: 'string' },
979
+ },
980
+ },
981
+ },
982
+ },
983
+ };
984
+ }
985
+
986
+ // ── the handler ──────────────────────────────────────────────────────────────
987
+
988
+ /**
989
+ * Add the CORS headers every endpoint wants.
990
+ *
991
+ * The receipts are meant to be read by agents and browsers alike, so every
992
+ * response — including the preflight — carries them.
993
+ */
994
+ function withCors(response: Response): Response {
995
+ const headers = new Headers(response.headers);
996
+ headers.set('access-control-allow-origin', '*');
997
+ headers.set(
998
+ 'access-control-expose-headers',
999
+ 'payment-required, x-liqproof-access, x-liqproof-free-tier, x-liqproof-verdict',
1000
+ );
1001
+ return new Response(response.body, {
1002
+ status: response.status,
1003
+ statusText: response.statusText,
1004
+ headers,
1005
+ });
1006
+ }
1007
+
1008
+ /**
1009
+ * Handle one request.
1010
+ *
1011
+ * Exported so the local CLI (`liqproof serve`) can serve exactly the same
1012
+ * API from Node — one implementation, two hosts, no drift.
1013
+ */
1014
+ export async function handleRequest(request: Request, env: WorkerEnv): Promise<Response> {
1015
+ if (request.method === 'OPTIONS') {
1016
+ return withCors(
1017
+ new Response(null, {
1018
+ status: 204,
1019
+ headers: {
1020
+ 'access-control-allow-methods': 'GET, HEAD, OPTIONS',
1021
+ 'access-control-allow-headers': 'content-type, payment-signature, x-payment',
1022
+ 'access-control-max-age': '86400',
1023
+ },
1024
+ }),
1025
+ );
1026
+ }
1027
+
1028
+ return withCors(await route(request, env));
1029
+ }
1030
+
1031
+ /** The routing table. */
1032
+ async function route(request: Request, env: WorkerEnv): Promise<Response> {
1033
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
1034
+ return json(
1035
+ { error: 'method_not_allowed', allowed: ['GET', 'HEAD'] },
1036
+ 405,
1037
+ { allow: 'GET, HEAD' },
1038
+ );
1039
+ }
1040
+
1041
+ const url = new URL(request.url);
1042
+ const path = url.pathname.replace(/\/+$/, '') || '/';
1043
+
1044
+ if (path === '/health') return healthResponse();
1045
+ if (path === '/openapi.json') return json(openApiDocument(url.origin));
1046
+ if (path === '/') return landingResponse(url, env);
1047
+ if (path === '/receipt' || path.startsWith('/receipt/')) {
1048
+ try {
1049
+ return await receiptRoute(request, url, env);
1050
+ } catch (err) {
1051
+ // The chain could not be read. Say so honestly instead of returning a
1052
+ // half-built receipt that looks like evidence.
1053
+ return json(
1054
+ {
1055
+ error: 'receipt_unavailable',
1056
+ message: (err as Error).message.slice(0, 200),
1057
+ hint: 'the free public RPC is rate limited; retry in a few seconds',
1058
+ },
1059
+ 502,
1060
+ );
1061
+ }
1062
+ }
1063
+
1064
+ return json(
1065
+ {
1066
+ error: 'not_found',
1067
+ hint: 'GET /, /health, /openapi.json, /receipt/<mint>',
1068
+ },
1069
+ 404,
1070
+ );
1071
+ }
1072
+
1073
+ // ── the Worker entry point ───────────────────────────────────────────────────
1074
+
1075
+ /**
1076
+ * Cloudflare Workers entry point.
1077
+ *
1078
+ * `export default { fetch(request, env) }` is the whole contract. There is
1079
+ * no scheduled handler, no queue consumer and no durable object: the service
1080
+ * is stateless apart from two KV bindings it uses when they are attached.
1081
+ */
1082
+ export default {
1083
+ async fetch(request: Request, env: WorkerEnv): Promise<Response> {
1084
+ return handleRequest(request, env ?? {});
1085
+ },
1086
+ };