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/x402.ts ADDED
@@ -0,0 +1,717 @@
1
+ /**
2
+ * x402.ts — HTTP 402 (Payment Required) payment middleware for LIQPROOF.
3
+ *
4
+ * ── WHAT THIS IS ────────────────────────────────────────────────────────────
5
+ *
6
+ * x402 is an open standard for machine-to-machine payments over plain HTTP:
7
+ * the server answers `402 Payment Required` with the price, the network, the
8
+ * asset and the recipient; the client pays; the client retries with proof of
9
+ * payment. We implement the **v2** shape (protocol version 2, CAIP-2 aware
10
+ * network identifiers, `PAYMENT-REQUIRED` / `PAYMENT-SIGNATURE` headers).
11
+ *
12
+ * ── WHAT THIS IS NOT (and this is the whole point) ─────────────────────────
13
+ *
14
+ * THIS MODULE DOES NOT SIGN ANYTHING AND DOES NOT BROADCAST ANYTHING.
15
+ *
16
+ * The zero-capital thesis of LIQPROOF is that a *verifier* needs no money and
17
+ * no authority: it reads public chain state and publishes a receipt. So the
18
+ * only privileged operation we ever perform on behalf of a payer is
19
+ * **verification**: we ask a free facilitator whether the payment the CLIENT
20
+ * already made is real, and we publish the receipt if it is.
21
+ *
22
+ * We deliberately do NOT call the facilitator's `/settle` endpoint. Settling
23
+ * means committing state (and, on most facilitators, broadcasting a
24
+ * transaction) — which would drag a chain-write path into a product whose
25
+ * entire value proposition is that it cannot move money. The client settles
26
+ * its own payment; the server only reads the proof.
27
+ *
28
+ * There is no wallet, no key material, no signing helper and no transaction
29
+ * builder anywhere in this file. `liqproof verify` greps the whole source
30
+ * tree for those paths and must keep passing.
31
+ *
32
+ * ── WHY THE FREE TIER EXISTS ────────────────────────────────────────────────
33
+ *
34
+ * A paid tool that nobody can evaluate is a dead tool. The first N receipts
35
+ * per day are served WITHOUT payment (N = 25 by default) so a prospective
36
+ * buyer can read real receipts before spending anything. After that the
37
+ * server answers 402 with the exact challenge a client needs to pay.
38
+ *
39
+ * Usage is tracked through a tiny `UsageStore` interface so the same code
40
+ * serves three runtimes:
41
+ *
42
+ * • Node CLI → `DiskUsageStore` over the project's `DiskCache` (survives
43
+ * restarts, no database, no server, no cost).
44
+ * • Worker → `MemoryUsageStore` (a Worker isolate has no writable disk)
45
+ * or a Cloudflare KV binding when one is attached.
46
+ *
47
+ * ── ZERO DEPENDENCIES ───────────────────────────────────────────────────────
48
+ *
49
+ * This file imports nothing from Node's standard library and nothing from
50
+ * npm. `fetch`, `TextEncoder`/`TextDecoder` and `btoa`/`atob` are Web
51
+ * standards available in Node 22, in Cloudflare Workers and in every browser.
52
+ */
53
+
54
+ // NOTE: this module deliberately imports NOTHING from Node's standard library
55
+ // and nothing from npm, so the Cloudflare Worker can import it without
56
+ // dragging a writable filesystem into an isolate that has none. The
57
+ // disk-backed usage store is wired in by the CLI (`liqproof serve`), which
58
+ // owns the Node side of the project.
59
+
60
+ // ── protocol constants ───────────────────────────────────────────────────────
61
+
62
+ /** x402 protocol version implemented here. */
63
+ export const X402_VERSION = 2;
64
+
65
+ /** Response header carrying the base64-encoded challenge (x402 v2). */
66
+ export const HEADER_PAYMENT_REQUIRED = 'payment-required';
67
+
68
+ /** Request header carrying the base64-encoded payment payload (x402 v2). */
69
+ export const HEADER_PAYMENT_SIGNATURE = 'payment-signature';
70
+
71
+ /** Request header used by x402 v1 clients — accepted for compatibility. */
72
+ export const HEADER_PAYMENT_LEGACY = 'x-payment';
73
+
74
+ /** USDC (mainnet) mint. */
75
+ export const USDC_MINT_MAINNET = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
76
+
77
+ /** USDC (devnet) mint. */
78
+ export const USDC_MINT_DEVNET = '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU';
79
+
80
+ /** USDC has 6 decimals, so $0.25 is 250000 atomic units. */
81
+ export const USDC_DECIMALS = 6;
82
+
83
+ /** Networks we can charge on. */
84
+ export type X402Network = 'solana' | 'solana-devnet';
85
+
86
+ /** USDC mint per network. */
87
+ export const NETWORK_USDC_MINT: Record<X402Network, string> = {
88
+ solana: USDC_MINT_MAINNET,
89
+ 'solana-devnet': USDC_MINT_DEVNET,
90
+ };
91
+
92
+ /**
93
+ * CAIP-2 identifiers for the same networks.
94
+ *
95
+ * We keep the human-readable `solana` / `solana-devnet` names in the
96
+ * `network` field (that is what our own docs, our CLI and our clients use),
97
+ * and publish the CAIP-2 form alongside it in `extra` so a facilitator that
98
+ * validates CAIP-2 identifiers can match the payment it is asked to verify.
99
+ */
100
+ export const NETWORK_CAIP2: Record<X402Network, string> = {
101
+ solana: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
102
+ 'solana-devnet': 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',
103
+ };
104
+
105
+ /**
106
+ * Free facilitators, in the order we try them.
107
+ *
108
+ * 1. dexter.cash — free, no account, no key, Solana + 10 EVM networks.
109
+ * 2. x402.dexter.cash — the same service under its SDK-facing hostname.
110
+ * 3. x402.org — the reference testnet facilitator.
111
+ *
112
+ * Coinbase's CDP facilitator is supported too but needs a (free-tier) CDP API
113
+ * key, so it is opt-in via configuration rather than part of the default
114
+ * chain — see `CDP_FACILITATOR`.
115
+ */
116
+ export const DEFAULT_FACILITATORS: string[] = [
117
+ 'https://dexter.cash/facilitator',
118
+ 'https://x402.dexter.cash',
119
+ 'https://x402.org/facilitator',
120
+ ];
121
+
122
+ /** Coinbase CDP facilitator — opt-in, requires an API key. */
123
+ export const CDP_FACILITATOR = 'https://api.cdp.coinbase.com/platform/v2/x402';
124
+
125
+ /** Default price of one receipt, in US dollars. */
126
+ export const DEFAULT_PRICE_USD = 0.25;
127
+
128
+ /** Default number of free receipts per day, per client. */
129
+ export const DEFAULT_FREE_TIER = 25;
130
+
131
+ // ── types ────────────────────────────────────────────────────────────────────
132
+
133
+ /**
134
+ * One acceptable way to pay for the resource.
135
+ *
136
+ * Field names follow the x402 v2 `PaymentRequirements` object. `description`
137
+ * is our addition: it is what a human (or an agent reading the challenge)
138
+ * sees next to the price.
139
+ */
140
+ export interface PaymentRequirement {
141
+ /** Payment scheme. Only the exact scheme is implemented. */
142
+ scheme: 'exact';
143
+ /** Network the payment must settle on. */
144
+ network: X402Network;
145
+ /** Token mint (Solana) the payment must be denominated in. */
146
+ asset: string;
147
+ /** Price in atomic units of `asset`, as a decimal string. */
148
+ amount: string;
149
+ /** Where the payment goes. */
150
+ payTo: string;
151
+ /** How long the client has to pay, in seconds. */
152
+ maxTimeoutSeconds: number;
153
+ /** Human-readable description of what is being bought. */
154
+ description: string;
155
+ /** Scheme-specific extras (asset name/version, CAIP-2 network id, …). */
156
+ extra?: Record<string, unknown>;
157
+ }
158
+
159
+ /** Description of the protected resource. */
160
+ export interface ResourceInfo {
161
+ url: string;
162
+ description: string;
163
+ mimeType: string;
164
+ }
165
+
166
+ /**
167
+ * The challenge we hand back with HTTP 402.
168
+ *
169
+ * This is the x402 v2 `PaymentRequired` object. It travels twice: as JSON in
170
+ * the response body (easy to read, easy to `jq`) and base64-encoded in the
171
+ * `PAYMENT-REQUIRED` header (the canonical v2 wire location).
172
+ */
173
+ export interface PaymentRequiredChallenge {
174
+ /** Always 2. */
175
+ x402Version: number;
176
+ /** Why payment is required. */
177
+ error: string;
178
+ /** The resource being protected. */
179
+ resource: ResourceInfo;
180
+ /** One entry per acceptable payment method. */
181
+ accepts: PaymentRequirement[];
182
+ }
183
+
184
+ /** The payload a paying client sends back to us. */
185
+ export interface PaymentPayload {
186
+ x402Version?: number;
187
+ scheme?: string;
188
+ network?: string;
189
+ payload?: unknown;
190
+ resource?: { url?: string; description?: string; mimeType?: string };
191
+ accepted?: Record<string, unknown>;
192
+ extensions?: Record<string, unknown>;
193
+ }
194
+
195
+ /** Outcome of a facilitator verification. */
196
+ export interface FacilitatorVerifyResult {
197
+ /** Did the facilitator accept the payment? */
198
+ ok: boolean;
199
+ /** Amount that was verified, in atomic units (null when invalid). */
200
+ amount: string | null;
201
+ /** Address that paid, when the facilitator tells us. */
202
+ payer: string | null;
203
+ /** Machine-readable failure reason. */
204
+ reason: string | null;
205
+ /** Human-readable failure explanation. */
206
+ message: string | null;
207
+ /** Which facilitator answered. */
208
+ facilitator: string | null;
209
+ }
210
+
211
+ /** Options for `verifyPayment`. */
212
+ export interface VerifyOptions {
213
+ /** The requirement the payment is supposed to satisfy. */
214
+ requirement: PaymentRequirement;
215
+ /** Facilitator base URLs, tried in order. */
216
+ facilitators?: string[];
217
+ /** Optional API key (Coinbase CDP). */
218
+ apiKey?: string;
219
+ /** Per-request timeout in milliseconds. */
220
+ timeoutMs?: number;
221
+ /** Injectable fetch, for tests. */
222
+ fetchImpl?: typeof fetch;
223
+ }
224
+
225
+ /** Result of a free-tier check. */
226
+ export interface FreeTierState {
227
+ /** May the request proceed without payment? */
228
+ allowed: boolean;
229
+ /** Receipts already served to this client today (including this one). */
230
+ used: number;
231
+ /** Daily allowance. */
232
+ limit: number;
233
+ /** UTC day the counter belongs to, `YYYY-MM-DD`. */
234
+ day: string;
235
+ }
236
+
237
+ /**
238
+ * A tiny key/value store for daily counters.
239
+ *
240
+ * `DiskCache` (see `src/util.ts`) satisfies the synchronous half of this
241
+ * interface; Cloudflare KV satisfies the asynchronous half. We keep the
242
+ * interface deliberately small so both fit.
243
+ */
244
+ export interface UsageStore {
245
+ get(key: string): Promise<number | undefined>;
246
+ set(key: string, value: number): Promise<void>;
247
+ }
248
+
249
+ /** The synchronous shape of the project's `DiskCache<number>`. */
250
+ export interface DiskCacheLike {
251
+ get(key: string): number | undefined;
252
+ set(key: string, value: number): void;
253
+ }
254
+
255
+ /** The asynchronous shape of a Cloudflare KV namespace binding. */
256
+ export interface KvLike {
257
+ get(key: string): Promise<string | null>;
258
+ put(
259
+ key: string,
260
+ value: string,
261
+ options?: { expirationTtl?: number },
262
+ ): Promise<void>;
263
+ }
264
+
265
+ /**
266
+ * How long a daily usage counter stays in KV.
267
+ *
268
+ * Two days is enough for the counter to survive the day it belongs to (the
269
+ * counter is keyed by UTC day, so a stale one is never read again) while
270
+ * letting Cloudflare expire it on its own instead of us paying to delete it.
271
+ */
272
+ const KV_USAGE_TTL_SECONDS = 2 * 24 * 60 * 60;
273
+
274
+ // ── pure helpers ─────────────────────────────────────────────────────────────
275
+
276
+ /**
277
+ * Convert a dollar price into USDC atomic units.
278
+ *
279
+ * Pure on purpose: it is the one place where a rounding mistake would mean
280
+ * charging the wrong amount, so it is trivially testable.
281
+ */
282
+ export function priceUsdToAtomic(priceUsd: number): string {
283
+ if (!Number.isFinite(priceUsd) || priceUsd < 0) {
284
+ throw new Error(`invalid price: ${priceUsd}`);
285
+ }
286
+ return String(Math.round(priceUsd * 10 ** USDC_DECIMALS));
287
+ }
288
+
289
+ /** Convert USDC atomic units back into dollars (for display only). */
290
+ export function atomicToUsd(amount: string | number): number {
291
+ const n = typeof amount === 'number' ? amount : Number(amount);
292
+ if (!Number.isFinite(n)) return 0;
293
+ return n / 10 ** USDC_DECIMALS;
294
+ }
295
+
296
+ /** Base64-encode a UTF-8 string using only Web-standard APIs. */
297
+ export function base64Encode(text: string): string {
298
+ const bytes = new TextEncoder().encode(text);
299
+ let binary = '';
300
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
301
+ return btoa(binary);
302
+ }
303
+
304
+ /** Decode a base64 string back into UTF-8 text. */
305
+ export function base64Decode(text: string): string {
306
+ const binary = atob(text);
307
+ const bytes = new Uint8Array(binary.length);
308
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
309
+ return new TextDecoder().decode(bytes);
310
+ }
311
+
312
+ /** UTC day bucket, `YYYY-MM-DD`. Usage counters roll over at 00:00 UTC. */
313
+ export function utcDay(now: number = Date.now()): string {
314
+ return new Date(now).toISOString().slice(0, 10);
315
+ }
316
+
317
+ /** Key used for a client's daily free-tier counter. */
318
+ export function freeTierKey(clientKey: string, day: string): string {
319
+ return `x402:free:${day}:${clientKey}`;
320
+ }
321
+
322
+ /** Normalise a network string, defaulting to mainnet Solana. */
323
+ export function normalizeNetwork(value: string | undefined | null): X402Network {
324
+ const v = (value ?? '').trim().toLowerCase();
325
+ if (v === 'solana-devnet' || v === 'devnet' || v === 'solana:devnet') return 'solana-devnet';
326
+ return 'solana';
327
+ }
328
+
329
+ /**
330
+ * Build the 402 challenge for a resource.
331
+ *
332
+ * Pure: same inputs, same challenge, every time. The 402 body is a receipt
333
+ * for the receipt.
334
+ */
335
+ export function buildChallenge(opts: {
336
+ network?: X402Network;
337
+ priceUsd?: number;
338
+ payTo: string;
339
+ resourceUrl: string;
340
+ description: string;
341
+ mimeType?: string;
342
+ error?: string;
343
+ maxTimeoutSeconds?: number;
344
+ }): PaymentRequiredChallenge {
345
+ const network = opts.network ?? 'solana';
346
+ const priceUsd = opts.priceUsd ?? DEFAULT_PRICE_USD;
347
+ const asset = NETWORK_USDC_MINT[network];
348
+ const requirement: PaymentRequirement = {
349
+ scheme: 'exact',
350
+ network,
351
+ asset,
352
+ amount: priceUsdToAtomic(priceUsd),
353
+ payTo: opts.payTo,
354
+ maxTimeoutSeconds: opts.maxTimeoutSeconds ?? 300,
355
+ description: opts.description,
356
+ extra: {
357
+ name: 'USDC',
358
+ version: '2',
359
+ decimals: USDC_DECIMALS,
360
+ networkCaip2: NETWORK_CAIP2[network],
361
+ },
362
+ };
363
+ return {
364
+ x402Version: X402_VERSION,
365
+ error: opts.error ?? 'PAYMENT-SIGNATURE header is required',
366
+ resource: {
367
+ url: opts.resourceUrl,
368
+ description: opts.description,
369
+ mimeType: opts.mimeType ?? 'application/json',
370
+ },
371
+ accepts: [requirement],
372
+ };
373
+ }
374
+
375
+ /** The challenge in the exact shape the facilitator expects. */
376
+ export function toFacilitatorRequirement(requirement: PaymentRequirement): Record<string, unknown> {
377
+ return {
378
+ scheme: requirement.scheme,
379
+ network: requirement.network,
380
+ amount: requirement.amount,
381
+ asset: requirement.asset,
382
+ payTo: requirement.payTo,
383
+ maxTimeoutSeconds: requirement.maxTimeoutSeconds,
384
+ extra: requirement.extra ?? {},
385
+ };
386
+ }
387
+
388
+ /**
389
+ * Base64 encoding of the challenge, for the `PAYMENT-REQUIRED` header.
390
+ *
391
+ * Accepts either the challenge object or an already-serialized JSON string.
392
+ * The string form exists so a server can serialize the challenge ONCE and
393
+ * put the very same bytes in the body and in the header — a client can then
394
+ * decode the header and compare it with the body without parsing either.
395
+ */
396
+ export function encodeChallengeHeader(challenge: PaymentRequiredChallenge | string): string {
397
+ const text = typeof challenge === 'string' ? challenge : JSON.stringify(challenge);
398
+ return base64Encode(text);
399
+ }
400
+
401
+ /**
402
+ * Parse the payment payload a client sent us.
403
+ *
404
+ * Accepts both the v2 `PAYMENT-SIGNATURE` header and the legacy `X-PAYMENT`
405
+ * header, base64-encoded JSON in either case. Returns null when the header is
406
+ * absent or unreadable — never throws, because a malformed header is a
407
+ * client error and must turn into a 402, not a 500.
408
+ */
409
+ export function parsePaymentHeader(raw: string | null | undefined): PaymentPayload | null {
410
+ if (!raw) return null;
411
+ const trimmed = raw.trim();
412
+ if (!trimmed) return null;
413
+ let json = trimmed;
414
+ try {
415
+ json = base64Decode(trimmed);
416
+ } catch {
417
+ // Not base64 — maybe the client sent raw JSON. Try that before giving up.
418
+ }
419
+ try {
420
+ const parsed = JSON.parse(json) as unknown;
421
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
422
+ return parsed as PaymentPayload;
423
+ }
424
+ return null;
425
+ } catch {
426
+ return null;
427
+ }
428
+ }
429
+
430
+ /**
431
+ * Ask a facilitator whether a payment is real.
432
+ *
433
+ * READ-ONLY BY CONSTRUCTION: this only ever calls the facilitator's `/verify`
434
+ * endpoint, which the x402 specification defines as read-only ("validates
435
+ * payment state but MUST NOT commit payment state or write onchain state").
436
+ * We never call `/settle`, never build a transaction and never sign.
437
+ *
438
+ * Facilitators are tried in order; the first one that answers wins. A
439
+ * facilitator that says "invalid" is authoritative — we report that verdict
440
+ * rather than asking somebody else, because a second opinion on an invalid
441
+ * payment is just a way to lose money.
442
+ */
443
+ export async function verifyPayment(
444
+ payload: PaymentPayload,
445
+ opts: VerifyOptions,
446
+ ): Promise<FacilitatorVerifyResult> {
447
+ const facilitators = opts.facilitators?.length ? opts.facilitators : DEFAULT_FACILITATORS;
448
+ const doFetch = opts.fetchImpl ?? fetch;
449
+ const timeoutMs = opts.timeoutMs ?? 15_000;
450
+ let lastReason = 'facilitator_unavailable';
451
+
452
+ for (const base of facilitators) {
453
+ const url = `${base.replace(/\/+$/, '')}/verify`;
454
+ const controller = new AbortController();
455
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
456
+ try {
457
+ const res = await doFetch(url, {
458
+ method: 'POST',
459
+ headers: {
460
+ 'content-type': 'application/json',
461
+ accept: 'application/json',
462
+ ...facilitatorAuthHeaders(base, opts.apiKey),
463
+ },
464
+ body: JSON.stringify({
465
+ x402Version: X402_VERSION,
466
+ paymentPayload: payload,
467
+ paymentRequirements: toFacilitatorRequirement(opts.requirement),
468
+ }),
469
+ signal: controller.signal,
470
+ });
471
+
472
+ const text = await res.text();
473
+ if (!res.ok) {
474
+ // 4xx means "this facilitator will not answer that" — try the next.
475
+ // 5xx might be transient — also try the next.
476
+ lastReason = `facilitator_http_${res.status}`;
477
+ continue;
478
+ }
479
+
480
+ let parsed: Record<string, unknown>;
481
+ try {
482
+ parsed = JSON.parse(text) as Record<string, unknown>;
483
+ } catch {
484
+ lastReason = 'facilitator_invalid_json';
485
+ continue;
486
+ }
487
+
488
+ const ok = parsed.isValid === true || parsed.success === true;
489
+ const amount =
490
+ firstString(parsed, ['amount', 'settledAmount', 'paidAmount']) ??
491
+ (ok ? opts.requirement.amount : null);
492
+ return {
493
+ ok,
494
+ amount,
495
+ payer: firstString(parsed, ['payer', 'from', 'payerAddress']),
496
+ reason: ok ? null : firstString(parsed, ['invalidReason', 'errorReason', 'reason']),
497
+ message: ok ? null : firstString(parsed, ['invalidMessage', 'errorMessage', 'message']),
498
+ facilitator: base,
499
+ };
500
+ } catch (err) {
501
+ lastReason = `facilitator_error:${(err as Error).message.slice(0, 120)}`;
502
+ continue;
503
+ } finally {
504
+ clearTimeout(timer);
505
+ }
506
+ }
507
+
508
+ return {
509
+ ok: false,
510
+ amount: null,
511
+ payer: null,
512
+ reason: lastReason,
513
+ message: 'no facilitator could verify this payment',
514
+ facilitator: null,
515
+ };
516
+ }
517
+
518
+ /** Auth headers for a facilitator, if any are needed. */
519
+ function facilitatorAuthHeaders(base: string, apiKey?: string): Record<string, string> {
520
+ if (!apiKey) return {};
521
+ // CDP uses a bearer token on the v2 endpoints and `x-cdp-api-key` on the
522
+ // older ones; sending both is harmless and keeps one code path.
523
+ return {
524
+ authorization: `Bearer ${apiKey}`,
525
+ 'x-cdp-api-key': apiKey,
526
+ };
527
+ }
528
+
529
+ /** First string-valued key from a list of candidate keys. */
530
+ function firstString(obj: Record<string, unknown>, keys: string[]): string | null {
531
+ for (const key of keys) {
532
+ const v = obj[key];
533
+ if (typeof v === 'string' && v.length > 0) return v;
534
+ }
535
+ return null;
536
+ }
537
+
538
+ // ── usage stores ─────────────────────────────────────────────────────────────
539
+
540
+ /**
541
+ * In-memory daily counters.
542
+ *
543
+ * Used by the Worker: a Worker isolate has no writable disk, so the counter
544
+ * lives for the lifetime of the isolate. That is a *lower* bound on the free
545
+ * tier, never a higher one — a paid request is still paid, and the worst
546
+ * case is that a very long-lived isolate hands out a few extra free
547
+ * receipts. Attach a KV binding (see `KvUsageStore`) if you want the counter
548
+ * to survive isolate recycling.
549
+ */
550
+ export class MemoryUsageStore implements UsageStore {
551
+ private readonly map = new Map<string, number>();
552
+
553
+ async get(key: string): Promise<number | undefined> {
554
+ return this.map.get(key);
555
+ }
556
+
557
+ async set(key: string, value: number): Promise<void> {
558
+ this.map.set(key, value);
559
+ }
560
+ }
561
+
562
+ /**
563
+ * Disk-backed daily counters, on top of the project's `DiskCache`.
564
+ *
565
+ * The cache is one JSON file per key under `.liqproof/cache`, so it is
566
+ * inspectable, greppable, safe to delete and — crucially — free. No
567
+ * database, no server, no account.
568
+ *
569
+ * The `DiskCache` instance is injected rather than created here so this
570
+ * module stays free of Node-only imports: the Worker never imports it.
571
+ */
572
+ export class DiskUsageStore implements UsageStore {
573
+ constructor(private readonly cache: DiskCacheLike) {}
574
+
575
+ async get(key: string): Promise<number | undefined> {
576
+ return this.cache.get(key);
577
+ }
578
+
579
+ async set(key: string, value: number): Promise<void> {
580
+ this.cache.set(key, value);
581
+ }
582
+ }
583
+
584
+ /**
585
+ * Cloudflare KV-backed daily counters.
586
+ *
587
+ * KV is free at our scale (we write a handful of integers per day) and it
588
+ * survives isolate recycling, which is what a public Worker needs.
589
+ */
590
+ export class KvUsageStore implements UsageStore {
591
+ constructor(private readonly kv: KvLike) {}
592
+
593
+ async get(key: string): Promise<number | undefined> {
594
+ const raw = await this.kv.get(key);
595
+ if (raw === null || raw === undefined) return undefined;
596
+ const n = Number(raw);
597
+ return Number.isFinite(n) ? n : undefined;
598
+ }
599
+
600
+ async set(key: string, value: number): Promise<void> {
601
+ await this.kv.put(key, String(value), { expirationTtl: KV_USAGE_TTL_SECONDS });
602
+ }
603
+ }
604
+
605
+ /**
606
+ * The daily free tier.
607
+ *
608
+ * `consume()` is atomic enough for our purpose: read the counter, and if the
609
+ * client is still under the limit, write `used + 1`. Two concurrent requests
610
+ * from the same client could both read `used = 24` and both write `25`; the
611
+ * cost of that race is one free receipt, which is not worth a lock.
612
+ */
613
+ export class FreeTier {
614
+ constructor(
615
+ private readonly store: UsageStore,
616
+ private readonly limit: number = DEFAULT_FREE_TIER,
617
+ private readonly now: () => number = () => Date.now(),
618
+ ) {}
619
+
620
+ /** How many free receipts this client may still take today. */
621
+ async consume(clientKey: string): Promise<FreeTierState> {
622
+ const day = utcDay(this.now());
623
+ const key = freeTierKey(clientKey, day);
624
+ const used = (await this.store.get(key)) ?? 0;
625
+ if (used >= this.limit) {
626
+ return { allowed: false, used, limit: this.limit, day };
627
+ }
628
+ const next = used + 1;
629
+ await this.store.set(key, next);
630
+ return { allowed: true, used: next, limit: this.limit, day };
631
+ }
632
+
633
+ /** Read the counter without consuming it. */
634
+ async peek(clientKey: string): Promise<FreeTierState> {
635
+ const day = utcDay(this.now());
636
+ const used = (await this.store.get(freeTierKey(clientKey, day))) ?? 0;
637
+ return { allowed: used < this.limit, used, limit: this.limit, day };
638
+ }
639
+
640
+ /**
641
+ * Hand one receipt back to the daily allowance.
642
+ *
643
+ * Used when the receipt could not actually be produced — a rate-limited RPC,
644
+ * an aggregator outage. A client must not lose one of their free receipts
645
+ * because OUR infrastructure was briefly unavailable.
646
+ */
647
+ async refund(clientKey: string): Promise<void> {
648
+ const day = utcDay(this.now());
649
+ const key = freeTierKey(clientKey, day);
650
+ const used = (await this.store.get(key)) ?? 0;
651
+ if (used > 0) await this.store.set(key, used - 1);
652
+ }
653
+ }
654
+
655
+ // ── self-check ───────────────────────────────────────────────────────────────
656
+
657
+ /**
658
+ * Pure-function self-check for the x402 module.
659
+ *
660
+ * Run with `liqproof x402 --selftest`. It touches no network and no disk, so
661
+ * it is safe to run anywhere — including in CI on a machine that has never
662
+ * seen a Solana RPC.
663
+ */
664
+ export function x402SelfTest(): string[] {
665
+ const failures: string[] = [];
666
+
667
+ // price → atomic units
668
+ if (priceUsdToAtomic(0.25) !== '250000') failures.push('priceUsdToAtomic(0.25) !== 250000');
669
+ if (priceUsdToAtomic(2) !== '2000000') failures.push('priceUsdToAtomic(2) !== 2000000');
670
+ if (priceUsdToAtomic(25) !== '25000000') failures.push('priceUsdToAtomic(25) !== 25000000');
671
+ if (atomicToUsd('250000') !== 0.25) failures.push('atomicToUsd(250000) !== 0.25');
672
+
673
+ // base64 round-trip
674
+ const sample = 'LIQPROOF — receipts ✓';
675
+ if (base64Decode(base64Encode(sample)) !== sample) failures.push('base64 round-trip failed');
676
+
677
+ // challenge shape
678
+ const challenge = buildChallenge({
679
+ payTo: 'So11111111111111111111111111111111111111112',
680
+ resourceUrl: 'https://liqproof.example.workers.dev/receipt/ABC',
681
+ description: 'one liquidity receipt',
682
+ });
683
+ if (challenge.x402Version !== X402_VERSION) failures.push('challenge x402Version !== 2');
684
+ if (challenge.accepts.length !== 1) failures.push('challenge.accepts.length !== 1');
685
+ if (challenge.accepts[0]?.asset !== USDC_MINT_MAINNET) failures.push('challenge asset is not USDC');
686
+ if (challenge.accepts[0]?.amount !== '250000') failures.push('challenge amount is not 250000');
687
+ if (challenge.accepts[0]?.network !== 'solana') failures.push('challenge network is not solana');
688
+ if (!challenge.error) failures.push('challenge.error is empty');
689
+
690
+ // network normalisation
691
+ if (normalizeNetwork('SOLANA-DEVNET') !== 'solana-devnet') failures.push('normalizeNetwork devnet');
692
+ if (normalizeNetwork(undefined) !== 'solana') failures.push('normalizeNetwork default');
693
+
694
+ // header round-trip
695
+ const decoded = base64Decode(encodeChallengeHeader(challenge));
696
+ const reparsed = JSON.parse(decoded) as PaymentRequiredChallenge;
697
+ if (reparsed.accepts[0]?.payTo !== challenge.accepts[0]?.payTo) {
698
+ failures.push('challenge header round-trip failed');
699
+ }
700
+ // a pre-serialized challenge must survive the header encoding byte for byte
701
+ const pretty = JSON.stringify(challenge, null, 2);
702
+ if (base64Decode(encodeChallengeHeader(pretty)) !== pretty) {
703
+ failures.push('pre-serialized challenge header round-trip failed');
704
+ }
705
+
706
+ // payment header parsing
707
+ const payload: PaymentPayload = { x402Version: 2, payload: { signature: 'x' } };
708
+ const parsedPayload = parsePaymentHeader(base64Encode(JSON.stringify(payload)));
709
+ if (!parsedPayload || parsedPayload.x402Version !== 2) failures.push('parsePaymentHeader failed');
710
+ if (parsePaymentHeader('not-base64-!!') !== null) failures.push('parsePaymentHeader should reject junk');
711
+ if (parsePaymentHeader(null) !== null) failures.push('parsePaymentHeader(null) should be null');
712
+
713
+ // day bucketing
714
+ if (utcDay(Date.UTC(2026, 11, 4, 23, 59, 59)) !== '2026-12-04') failures.push('utcDay rollover');
715
+
716
+ return failures;
717
+ }