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.
- package/LICENSE +21 -0
- package/README.md +536 -2
- package/bugs/README.md +144 -0
- package/bugs/coin-gecko-liquidity-report.md +283 -0
- package/bugs/collect-ds-aggregate.mjs +213 -0
- package/bugs/collect-evidence.mjs +458 -0
- package/bugs/collect-gt-aggregate.mjs +215 -0
- package/bugs/collect-raw-rpc.mjs +165 -0
- package/bugs/collect-sweep-context.mjs +162 -0
- package/bugs/dexscreener-fake-liquidity-report.md +310 -0
- package/bugs/evidence/aggregator-liquidity-claims.json +648 -0
- package/bugs/evidence/aggregator-liquidity-claims.md +103 -0
- package/bugs/evidence/bat-native-pool-drained.json +136 -0
- package/bugs/evidence/bat-native-pool-drained.md +51 -0
- package/bugs/evidence/chz-impersonator-pool-drained.json +136 -0
- package/bugs/evidence/chz-impersonator-pool-drained.md +51 -0
- package/bugs/evidence/gt-stale-reserve-after-drain.json +141 -0
- package/bugs/evidence/gt-stale-reserve-after-drain.md +31 -0
- package/bugs/evidence/raw-rpc-transcript.json +683 -0
- package/bugs/evidence/raw-rpc-transcript.md +308 -0
- package/bugs/evidence/sweep-context.json +325 -0
- package/bugs/evidence/sweep-context.md +55 -0
- package/bugs/evidence/verified-aggregate.json +526 -0
- package/bugs/evidence/verified-aggregate.md +24 -0
- package/bugs/evidence/verified-ds-liquidity-usd.json +1197 -0
- package/bugs/evidence/verified-ds-liquidity-usd.md +250 -0
- package/bugs/evidence/verified-gt-reserve-in-usd.json +1002 -0
- package/bugs/evidence/verified-gt-reserve-in-usd.md +218 -0
- package/bugs/fix-bundle-titles.mjs +72 -0
- package/bugs/geckoterminal-stale-reserve-after-drain.md +137 -0
- package/data/dataset-summary.md +103 -0
- package/data/impersonators.json +12888 -0
- package/data/verified-impersonators.json +725 -0
- package/data/wallets.json +23 -0
- package/dist/base58.js +70 -0
- package/dist/base58.js.map +1 -0
- package/dist/canonical.js +372 -0
- package/dist/canonical.js.map +1 -0
- package/dist/cli.js +830 -0
- package/dist/cli.js.map +1 -0
- package/dist/curve.js +255 -0
- package/dist/curve.js.map +1 -0
- package/dist/dashboard.js +485 -0
- package/dist/dashboard.js.map +1 -0
- package/dist/keccak.js +197 -0
- package/dist/keccak.js.map +1 -0
- package/dist/mcp.js +604 -0
- package/dist/mcp.js.map +1 -0
- package/dist/operator.js +180 -0
- package/dist/operator.js.map +1 -0
- package/dist/pda.js +86 -0
- package/dist/pda.js.map +1 -0
- package/dist/receipt.js +897 -0
- package/dist/receipt.js.map +1 -0
- package/dist/render.js +335 -0
- package/dist/render.js.map +1 -0
- package/dist/rpc.js +377 -0
- package/dist/rpc.js.map +1 -0
- package/dist/sources.js +599 -0
- package/dist/sources.js.map +1 -0
- package/dist/store.js +330 -0
- package/dist/store.js.map +1 -0
- package/dist/tokenmeta.js +424 -0
- package/dist/tokenmeta.js.map +1 -0
- package/dist/util.js +273 -0
- package/dist/util.js.map +1 -0
- package/dist/vaults.js +510 -0
- package/dist/vaults.js.map +1 -0
- package/dist/wallet.js +404 -0
- package/dist/wallet.js.map +1 -0
- package/dist/warnings.js +41 -0
- package/dist/warnings.js.map +1 -0
- package/dist/worker.js +857 -0
- package/dist/worker.js.map +1 -0
- package/dist/x402.js +549 -0
- package/dist/x402.js.map +1 -0
- package/docs/HACKATHON-SUBMISSION.md +264 -0
- package/docs/liqproof-plan.md +221 -0
- package/docs/llms.txt +32 -0
- package/docs/mcp-registry.md +165 -0
- package/docs/screenshots/01-dashboard.png +0 -0
- package/docs/screenshots/02-receipt-drained.png +0 -0
- package/docs/screenshots/03-receipt-impersonator.png +0 -0
- package/docs/screenshots/04-receipt-canonical.png +0 -0
- package/docs/x402-pricing.md +171 -0
- package/docs/zero-xyz.md +250 -0
- package/out/6eftxVbSAunVEoxUWdGhPdxg5UdsJ8Wkwy5w5YFuxouw.json +1171 -0
- package/out/6eftxVbSAunVEoxUWdGhPdxg5UdsJ8Wkwy5w5YFuxouw.md +52 -0
- package/out/6eftxVbSAunVEoxUWdGhPdxg5UdsJ8Wkwy5w5YFuxouw.svg +25 -0
- package/out/BTNiaZb6HaEFWeEtND4SXtZ7T6mgtDwSryHTAj6PuPyp.json +3975 -0
- package/out/BTNiaZb6HaEFWeEtND4SXtZ7T6mgtDwSryHTAj6PuPyp.md +90 -0
- package/out/BTNiaZb6HaEFWeEtND4SXtZ7T6mgtDwSryHTAj6PuPyp.svg +25 -0
- package/out/ENGkoidj2jNs73A7GZuseVmnkRg6EVF9tDtViwPz8o85.json +1446 -0
- package/out/ENGkoidj2jNs73A7GZuseVmnkRg6EVF9tDtViwPz8o85.md +66 -0
- package/out/ENGkoidj2jNs73A7GZuseVmnkRg6EVF9tDtViwPz8o85.svg +25 -0
- package/out/dataset.csv +67 -0
- package/out/impersonation-table.md +156 -0
- package/out/index.html +1179 -0
- package/package.json +78 -4
- package/scripts/assert-no-canonical-accusations.mjs +193 -0
- package/scripts/backfill.mjs +1063 -0
- package/scripts/bundle-evidence.mjs +237 -0
- package/scripts/bundle-stale-claim.mjs +417 -0
- package/scripts/capture-bch-evidence.mjs +58 -0
- package/scripts/check-orientation-fix.mjs +40 -0
- package/scripts/check-wallet.mjs +54 -0
- package/scripts/daily-refresh.mjs +451 -0
- package/scripts/decode-clmm-vaults.mjs +180 -0
- package/scripts/falsifiability.mjs +263 -0
- package/scripts/impersonator-mining.mjs +156 -0
- package/scripts/inspect-matches.mjs +73 -0
- package/scripts/operator-sweep.mjs +252 -0
- package/scripts/publish-release.mjs +248 -0
- package/scripts/refresh-store.mjs +78 -0
- package/scripts/survival-miner.mjs +951 -0
- package/scripts/test-keccak.mjs +103 -0
- package/scripts/verify-bch-1p95b.mjs +124 -0
- package/scripts/verify-clmm-1p95b.mjs +127 -0
- package/scripts/verify-clmm-control.mjs +84 -0
- package/scripts/verify-impersonators.mjs +138 -0
- package/scripts/verify-raw.mjs +110 -0
- package/scripts/verify-raw2.mjs +99 -0
- package/server.json +34 -0
- package/src/base58.ts +68 -0
- package/src/canonical.ts +447 -0
- package/src/cli.ts +941 -0
- package/src/curve.ts +349 -0
- package/src/dashboard.ts +504 -0
- package/src/keccak.ts +228 -0
- package/src/mcp.ts +735 -0
- package/src/operator.ts +219 -0
- package/src/receipt.ts +1219 -0
- package/src/render.ts +396 -0
- package/src/rpc.ts +435 -0
- package/src/sources.ts +714 -0
- package/src/store.ts +428 -0
- package/src/tokenmeta.ts +460 -0
- package/src/util.ts +276 -0
- package/src/vaults.ts +574 -0
- package/src/wallet.ts +459 -0
- package/src/warnings.ts +40 -0
- package/src/worker.ts +1086 -0
- package/src/x402.ts +717 -0
package/dist/worker.js
ADDED
|
@@ -0,0 +1,857 @@
|
|
|
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
|
+
// ── imports ──────────────────────────────────────────────────────────────────
|
|
52
|
+
//
|
|
53
|
+
// Everything below is either a project module or a Web standard. There is no
|
|
54
|
+
// npm dependency here, and there is no runtime dependency in this project at
|
|
55
|
+
// all — the $0 budget is structural, not a promise.
|
|
56
|
+
import { buildReceipt } from './receipt.js';
|
|
57
|
+
import { renderMarkdown } from './render.js';
|
|
58
|
+
import { RpcPool } from './rpc.js';
|
|
59
|
+
import { buildChallenge, DEFAULT_FACILITATORS, DEFAULT_FREE_TIER, DEFAULT_PRICE_USD, encodeChallengeHeader, FreeTier, HEADER_PAYMENT_LEGACY, HEADER_PAYMENT_REQUIRED, HEADER_PAYMENT_SIGNATURE, KvUsageStore, MemoryUsageStore, normalizeNetwork, parsePaymentHeader, verifyPayment, } from './x402.js';
|
|
60
|
+
// ── constants ────────────────────────────────────────────────────────────────
|
|
61
|
+
/** Version reported by `/health` and embedded in the OpenAPI document. */
|
|
62
|
+
export const VERSION = '0.1.0';
|
|
63
|
+
/** When this isolate started. `/health` reports uptime against it. */
|
|
64
|
+
const STARTED_AT = Date.now();
|
|
65
|
+
/** How long a built receipt stays in the in-isolate cache. */
|
|
66
|
+
const RECEIPT_TTL_MS = 60_000;
|
|
67
|
+
/**
|
|
68
|
+
* How long a built receipt may live in Cloudflare KV.
|
|
69
|
+
*
|
|
70
|
+
* Five minutes is short enough that a drain event cannot stay hidden for
|
|
71
|
+
* long, and long enough to take the expensive RPC work off the hot path —
|
|
72
|
+
* which matters because the Workers free plan only grants 10 ms of CPU per
|
|
73
|
+
* invocation.
|
|
74
|
+
*/
|
|
75
|
+
const RECEIPT_KV_TTL_SECONDS = 300;
|
|
76
|
+
/**
|
|
77
|
+
* The mint used for the live example on the landing page.
|
|
78
|
+
*
|
|
79
|
+
* BAT (native) is the canonical trap: the market advertises ~$136,104,308 of
|
|
80
|
+
* liquidity and the pool vault holds ~$23.53 of real USDC. It is a good
|
|
81
|
+
* first impression because the gap is impossible to argue with.
|
|
82
|
+
*/
|
|
83
|
+
export const EXAMPLE_MINT = 'BTNiaZb6HaEFWeEtND4SXtZ7T6mgtDwSryHTAj6PuPyp';
|
|
84
|
+
/** A Solana mint or wallet address is base58, 32–44 characters. */
|
|
85
|
+
const SOLANA_ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
|
|
86
|
+
/** Default number of transactions the liquidity curve may scan. */
|
|
87
|
+
const DEFAULT_MAX_TRANSACTIONS = 120;
|
|
88
|
+
/**
|
|
89
|
+
* Turn the raw environment into a validated configuration.
|
|
90
|
+
*
|
|
91
|
+
* Every value falls back to a free default rather than failing the request:
|
|
92
|
+
* a deployment with no configuration at all still serves the free tier, which
|
|
93
|
+
* is the whole point of the free tier.
|
|
94
|
+
*/
|
|
95
|
+
export function resolveConfig(env) {
|
|
96
|
+
const priceUsd = Number(env.X402_PRICE_USD ?? DEFAULT_PRICE_USD);
|
|
97
|
+
const freeTier = Number(env.X402_FREE_TIER ?? DEFAULT_FREE_TIER);
|
|
98
|
+
const facilitator = (env.X402_FACILITATOR ?? '').trim();
|
|
99
|
+
const maxTx = Number(env.X402_MAX_TX ?? DEFAULT_MAX_TRANSACTIONS);
|
|
100
|
+
const payTo = (env.PAY_TO ?? '').trim();
|
|
101
|
+
return {
|
|
102
|
+
payTo: SOLANA_ADDRESS.test(payTo) ? payTo : null,
|
|
103
|
+
priceUsd: Number.isFinite(priceUsd) && priceUsd >= 0 ? priceUsd : DEFAULT_PRICE_USD,
|
|
104
|
+
freeTier: Number.isFinite(freeTier) && freeTier >= 0 ? Math.floor(freeTier) : DEFAULT_FREE_TIER,
|
|
105
|
+
network: normalizeNetwork(env.X402_NETWORK),
|
|
106
|
+
// A configured facilitator is tried FIRST; the free defaults remain as a
|
|
107
|
+
// fallback so a typo in configuration degrades to "still works".
|
|
108
|
+
facilitators: facilitator ? [facilitator, ...DEFAULT_FACILITATORS] : DEFAULT_FACILITATORS,
|
|
109
|
+
apiKey: (env.X402_API_KEY ?? '').trim() || undefined,
|
|
110
|
+
maxTransactions: Number.isFinite(maxTx) && maxTx > 0 ? Math.floor(maxTx) : DEFAULT_MAX_TRANSACTIONS,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
// ── shared, isolate-scoped state ─────────────────────────────────────────────
|
|
114
|
+
/**
|
|
115
|
+
* One RPC pool per isolate.
|
|
116
|
+
*
|
|
117
|
+
* The pool learns the free tier's real rate limits from response headers and
|
|
118
|
+
* keeps a token bucket per (endpoint, method). Creating a new pool per
|
|
119
|
+
* request would throw that state away every time and earn us a 429.
|
|
120
|
+
*/
|
|
121
|
+
const rpc = new RpcPool({});
|
|
122
|
+
const receiptCache = new Map();
|
|
123
|
+
/**
|
|
124
|
+
* In-isolate usage counters.
|
|
125
|
+
*
|
|
126
|
+
* A Worker has no writable disk, so the daily free-tier counters live in
|
|
127
|
+
* memory. The worst case is that a very long-lived isolate hands out a few
|
|
128
|
+
* extra free receipts; attach a KV binding (`LIQPROOF_USAGE`) to make the
|
|
129
|
+
* counter survive isolate recycling.
|
|
130
|
+
*/
|
|
131
|
+
const memoryUsage = new MemoryUsageStore();
|
|
132
|
+
/** Pick the usage store: an injected one, else KV, else isolate memory. */
|
|
133
|
+
function usageStore(env) {
|
|
134
|
+
if (env.USAGE_STORE)
|
|
135
|
+
return env.USAGE_STORE;
|
|
136
|
+
if (env.LIQPROOF_USAGE)
|
|
137
|
+
return new KvUsageStore(env.LIQPROOF_USAGE);
|
|
138
|
+
return memoryUsage;
|
|
139
|
+
}
|
|
140
|
+
// ── small helpers ────────────────────────────────────────────────────────────
|
|
141
|
+
/** JSON response with the headers every endpoint wants. */
|
|
142
|
+
function json(value, status = 200, extraHeaders = {}) {
|
|
143
|
+
return new Response(JSON.stringify(value, null, 2), {
|
|
144
|
+
status,
|
|
145
|
+
headers: {
|
|
146
|
+
'content-type': 'application/json; charset=utf-8',
|
|
147
|
+
'cache-control': 'no-store',
|
|
148
|
+
...extraHeaders,
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
/** FNV-1a 32-bit hash — stable, dependency-free, good enough for a key. */
|
|
153
|
+
function hash32(s) {
|
|
154
|
+
let h = 0x811c9dc5;
|
|
155
|
+
for (let i = 0; i < s.length; i++) {
|
|
156
|
+
h ^= s.charCodeAt(i);
|
|
157
|
+
h = Math.imul(h, 0x01000193) >>> 0;
|
|
158
|
+
}
|
|
159
|
+
return h.toString(16).padStart(8, '0');
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Escape a value for interpolation into the landing page.
|
|
163
|
+
*
|
|
164
|
+
* A local copy of the helper in `src/dashboard.ts` — importing that module
|
|
165
|
+
* would drag `src/store.ts` (node:sqlite) into the Worker. The duplication
|
|
166
|
+
* is deliberate and is the reason this file carries the note at the top.
|
|
167
|
+
*/
|
|
168
|
+
function escapeHtml(value) {
|
|
169
|
+
const amp = String.fromCharCode(38);
|
|
170
|
+
const s = String(value ?? '');
|
|
171
|
+
return s
|
|
172
|
+
.replace(/&/g, amp + 'amp;')
|
|
173
|
+
.replace(/</g, amp + 'lt;')
|
|
174
|
+
.replace(/>/g, amp + 'gt;')
|
|
175
|
+
.replace(/"/g, amp + 'quot;')
|
|
176
|
+
.replace(/'/g, amp + '#39;');
|
|
177
|
+
}
|
|
178
|
+
/** Format a dollar amount the way the dashboard does. */
|
|
179
|
+
function formatUsd(n) {
|
|
180
|
+
if (n === null || n === undefined || !Number.isFinite(n))
|
|
181
|
+
return '—';
|
|
182
|
+
const abs = Math.abs(n);
|
|
183
|
+
if (abs >= 1_000_000_000)
|
|
184
|
+
return `$${(n / 1_000_000_000).toFixed(2)}B`;
|
|
185
|
+
if (abs >= 1_000_000)
|
|
186
|
+
return `$${(n / 1_000_000).toFixed(2)}M`;
|
|
187
|
+
if (abs >= 1_000)
|
|
188
|
+
return `$${(n / 1_000).toFixed(2)}K`;
|
|
189
|
+
if (abs >= 1)
|
|
190
|
+
return `$${n.toFixed(2)}`;
|
|
191
|
+
return `$${n.toFixed(4)}`;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Coverage needs extra digits when it is tiny: 0.0000% is the difference
|
|
195
|
+
* between "empty" and "one part in a million".
|
|
196
|
+
*/
|
|
197
|
+
function formatCoverage(n) {
|
|
198
|
+
if (n === null || n === undefined || !Number.isFinite(n))
|
|
199
|
+
return '—';
|
|
200
|
+
const pctValue = n * 100;
|
|
201
|
+
if (pctValue === 0)
|
|
202
|
+
return '0%';
|
|
203
|
+
if (pctValue < 0.0001)
|
|
204
|
+
return `${pctValue.toExponential(3)}%`;
|
|
205
|
+
if (pctValue < 0.01)
|
|
206
|
+
return `${pctValue.toFixed(6)}%`;
|
|
207
|
+
if (pctValue < 1)
|
|
208
|
+
return `${pctValue.toFixed(4)}%`;
|
|
209
|
+
return `${pctValue.toFixed(2)}%`;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Identify the client for the purpose of the daily free tier.
|
|
213
|
+
*
|
|
214
|
+
* Cloudflare puts the real client address in `CF-Connecting-IP`; the local
|
|
215
|
+
* Node server has neither, so the user agent stands in. Either way the key
|
|
216
|
+
* is opaque and nobody has to trust a header we did not ask for.
|
|
217
|
+
*/
|
|
218
|
+
function clientKey(request) {
|
|
219
|
+
const forwarded = request.headers.get('x-forwarded-for');
|
|
220
|
+
const ip = request.headers.get('cf-connecting-ip') ?? (forwarded ? forwarded.split(',')[0]?.trim() : null);
|
|
221
|
+
if (ip)
|
|
222
|
+
return ip;
|
|
223
|
+
const agent = request.headers.get('user-agent');
|
|
224
|
+
if (agent)
|
|
225
|
+
return 'ua-' + hash32(agent);
|
|
226
|
+
return 'anonymous';
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Build a receipt, using every cache we have.
|
|
230
|
+
*
|
|
231
|
+
* Order matters. The in-isolate `Map` is the fastest and the freshest; KV
|
|
232
|
+
* is slower but survives isolate recycling; only when both miss do we spend
|
|
233
|
+
* RPC calls and CPU to build the receipt from scratch.
|
|
234
|
+
*/
|
|
235
|
+
async function loadReceipt(mint, opts, env) {
|
|
236
|
+
const key = `${mint}|${opts.curve ? 'full' : 'quick'}`;
|
|
237
|
+
const hit = receiptCache.get(key);
|
|
238
|
+
if (hit && Date.now() < hit.expires) {
|
|
239
|
+
return { receipt: hit.receipt, origin: 'isolate-cache' };
|
|
240
|
+
}
|
|
241
|
+
const kv = env.LIQPROOF_RECEIPTS;
|
|
242
|
+
if (kv) {
|
|
243
|
+
const raw = await kv.get(`receipt:${key}`);
|
|
244
|
+
if (raw) {
|
|
245
|
+
try {
|
|
246
|
+
const parsed = JSON.parse(raw);
|
|
247
|
+
if (parsed && parsed.mint === mint) {
|
|
248
|
+
receiptCache.set(key, { receipt: parsed, expires: Date.now() + RECEIPT_TTL_MS });
|
|
249
|
+
return { receipt: parsed, origin: 'kv-cache' };
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
// A corrupt cache entry must never break a request: fall through and
|
|
254
|
+
// rebuild from the chain.
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
const receipt = await buildReceipt(rpc, mint, {
|
|
259
|
+
includeCurve: opts.curve,
|
|
260
|
+
maxTransactions: opts.maxTransactions,
|
|
261
|
+
});
|
|
262
|
+
receiptCache.set(key, { receipt, expires: Date.now() + RECEIPT_TTL_MS });
|
|
263
|
+
if (kv) {
|
|
264
|
+
try {
|
|
265
|
+
await kv.put(`receipt:${key}`, JSON.stringify(receipt), {
|
|
266
|
+
expirationTtl: RECEIPT_KV_TTL_SECONDS,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
// A KV write failure is not a request failure.
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return { receipt, origin: 'fresh' };
|
|
274
|
+
}
|
|
275
|
+
/** The 402 challenge for one resource. */
|
|
276
|
+
function challengeFor(url, config, mint, error) {
|
|
277
|
+
return buildChallenge({
|
|
278
|
+
network: config.network,
|
|
279
|
+
priceUsd: config.priceUsd,
|
|
280
|
+
payTo: config.payTo ?? '',
|
|
281
|
+
resourceUrl: `${url.origin}/receipt/${mint}`,
|
|
282
|
+
description: `LIQPROOF liquidity receipt for ${mint}`,
|
|
283
|
+
mimeType: 'application/json',
|
|
284
|
+
error: error ?? undefined,
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Look for a payment and, if there is one, ask a facilitator about it.
|
|
289
|
+
*
|
|
290
|
+
* READ-ONLY BY CONSTRUCTION: `verifyPayment` only ever calls the
|
|
291
|
+
* facilitator's `/verify` endpoint. We never call `/settle`, never build a
|
|
292
|
+
* transaction and never sign. If the client paid, the client settled it.
|
|
293
|
+
*/
|
|
294
|
+
async function checkPayment(request, url, config, mint) {
|
|
295
|
+
const raw = request.headers.get(HEADER_PAYMENT_SIGNATURE) ??
|
|
296
|
+
request.headers.get(HEADER_PAYMENT_LEGACY);
|
|
297
|
+
if (!raw) {
|
|
298
|
+
return { present: false, ok: false, reason: null, result: null };
|
|
299
|
+
}
|
|
300
|
+
const payload = parsePaymentHeader(raw);
|
|
301
|
+
if (!payload) {
|
|
302
|
+
return {
|
|
303
|
+
present: true,
|
|
304
|
+
ok: false,
|
|
305
|
+
reason: 'the payment header is not a base64-encoded JSON payload',
|
|
306
|
+
result: null,
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
const requirement = challengeFor(url, config, mint).accepts[0];
|
|
310
|
+
const result = await verifyPayment(payload, {
|
|
311
|
+
requirement,
|
|
312
|
+
facilitators: config.facilitators,
|
|
313
|
+
apiKey: config.apiKey,
|
|
314
|
+
});
|
|
315
|
+
return {
|
|
316
|
+
present: true,
|
|
317
|
+
ok: result.ok,
|
|
318
|
+
reason: result.ok
|
|
319
|
+
? null
|
|
320
|
+
: (result.message ?? result.reason ?? 'the facilitator rejected this payment'),
|
|
321
|
+
result,
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* The 402 answer: the challenge as JSON and as the v2 response header.
|
|
326
|
+
*
|
|
327
|
+
* The challenge is serialized ONCE, so the header and the body carry the
|
|
328
|
+
* exact same bytes. A client can decode the header and compare it with the
|
|
329
|
+
* body without parsing anything.
|
|
330
|
+
*/
|
|
331
|
+
function challengeResponse(challenge) {
|
|
332
|
+
const text = JSON.stringify(challenge, null, 2);
|
|
333
|
+
return new Response(text, {
|
|
334
|
+
status: 402,
|
|
335
|
+
headers: {
|
|
336
|
+
'content-type': 'application/json; charset=utf-8',
|
|
337
|
+
'cache-control': 'no-store',
|
|
338
|
+
[HEADER_PAYMENT_REQUIRED]: encodeChallengeHeader(text),
|
|
339
|
+
},
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
// ── routes ───────────────────────────────────────────────────────────────────
|
|
343
|
+
/**
|
|
344
|
+
* Serve a receipt for one mint.
|
|
345
|
+
*
|
|
346
|
+
* The order of the checks is the product:
|
|
347
|
+
*
|
|
348
|
+
* 1. Is there a valid payment? Serve it (and do not touch the free tier).
|
|
349
|
+
* 2. Is the client under its daily allowance? Serve it free.
|
|
350
|
+
* 3. Otherwise answer 402 with the exact challenge.
|
|
351
|
+
*/
|
|
352
|
+
async function receiptRoute(request, url, env) {
|
|
353
|
+
const mint = url.pathname.slice('/receipt/'.length).split('/')[0].trim();
|
|
354
|
+
if (!SOLANA_ADDRESS.test(mint)) {
|
|
355
|
+
return json({
|
|
356
|
+
error: 'invalid_mint',
|
|
357
|
+
hint: 'expected a base58 Solana mint (32-44 characters)',
|
|
358
|
+
}, 400);
|
|
359
|
+
}
|
|
360
|
+
const format = url.searchParams.get('format') === 'md' || url.searchParams.get('format') === 'markdown'
|
|
361
|
+
? 'md'
|
|
362
|
+
: 'json';
|
|
363
|
+
const config = resolveConfig(env);
|
|
364
|
+
// Without a payment recipient we cannot ask for money we cannot receive.
|
|
365
|
+
// We still serve the free tier — that is the whole point of the free tier.
|
|
366
|
+
const canCharge = config.payTo !== null;
|
|
367
|
+
const payment = canCharge
|
|
368
|
+
? await checkPayment(request, url, config, mint)
|
|
369
|
+
: { present: false, ok: false, reason: null, result: null };
|
|
370
|
+
const client = clientKey(request);
|
|
371
|
+
const tier = new FreeTier(usageStore(env), config.freeTier);
|
|
372
|
+
if (payment.ok) {
|
|
373
|
+
return serveReceipt(mint, format, config, env, {
|
|
374
|
+
access: 'paid',
|
|
375
|
+
freeTier: null,
|
|
376
|
+
payer: payment.result?.payer ?? null,
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
// No valid payment: fall back to the free allowance.
|
|
380
|
+
const state = await tier.consume(client);
|
|
381
|
+
if (state.allowed) {
|
|
382
|
+
try {
|
|
383
|
+
return await serveReceipt(mint, format, config, env, {
|
|
384
|
+
access: 'free',
|
|
385
|
+
freeTier: state,
|
|
386
|
+
payer: null,
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
catch (err) {
|
|
390
|
+
// Our infrastructure failed, not the client. Give the receipt back.
|
|
391
|
+
await tier.refund(client);
|
|
392
|
+
throw err;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
// Over the allowance and unpaid. If a payment WAS sent and rejected, say
|
|
396
|
+
// why — a silent 402 would send the client around in circles.
|
|
397
|
+
if (payment.present && payment.reason) {
|
|
398
|
+
return challengeResponse(challengeFor(url, config, mint, payment.reason));
|
|
399
|
+
}
|
|
400
|
+
if (!canCharge) {
|
|
401
|
+
return json({
|
|
402
|
+
error: 'payment_recipient_not_configured',
|
|
403
|
+
hint: 'this deployment has no PAY_TO address, so paid access is disabled',
|
|
404
|
+
}, 503);
|
|
405
|
+
}
|
|
406
|
+
return challengeResponse(challengeFor(url, config, mint));
|
|
407
|
+
}
|
|
408
|
+
/** Build and return the receipt itself, in JSON or markdown. */
|
|
409
|
+
async function serveReceipt(mint, format, config, env, access) {
|
|
410
|
+
const { receipt, origin } = await loadReceipt(mint, { curve: true, maxTransactions: config.maxTransactions }, env);
|
|
411
|
+
const headers = {
|
|
412
|
+
'x-liqproof-access': access.access,
|
|
413
|
+
'x-liqproof-receipt-origin': origin,
|
|
414
|
+
'x-liqproof-verdict': receipt.verdict,
|
|
415
|
+
};
|
|
416
|
+
if (access.freeTier) {
|
|
417
|
+
headers['x-liqproof-free-tier'] = `${access.freeTier.used}/${access.freeTier.limit}`;
|
|
418
|
+
}
|
|
419
|
+
if (access.payer)
|
|
420
|
+
headers['x-liqproof-payer'] = access.payer;
|
|
421
|
+
if (format === 'md') {
|
|
422
|
+
return new Response(renderMarkdown(receipt), {
|
|
423
|
+
status: 200,
|
|
424
|
+
headers: {
|
|
425
|
+
...headers,
|
|
426
|
+
'content-type': 'text/markdown; charset=utf-8',
|
|
427
|
+
'cache-control': 'no-store',
|
|
428
|
+
},
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
return json(receipt, 200, headers);
|
|
432
|
+
}
|
|
433
|
+
/** `/health` — cheap, uncached, never touches the chain. */
|
|
434
|
+
function healthResponse() {
|
|
435
|
+
return json({
|
|
436
|
+
ok: true,
|
|
437
|
+
version: VERSION,
|
|
438
|
+
uptime: Math.floor((Date.now() - STARTED_AT) / 1000),
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
// ── landing page ─────────────────────────────────────────────────────────────
|
|
442
|
+
/**
|
|
443
|
+
* The landing page.
|
|
444
|
+
*
|
|
445
|
+
* One LIVE example receipt, built from the chain at request time, in the
|
|
446
|
+
* visual language of the offline dashboard (`src/dashboard.ts`). A landing
|
|
447
|
+
* page that shows invented numbers would be the exact opposite of this
|
|
448
|
+
* product, so if the chain cannot be read right now we say so instead of
|
|
449
|
+
* printing stale fiction.
|
|
450
|
+
*/
|
|
451
|
+
async function landingResponse(url, env) {
|
|
452
|
+
const config = resolveConfig(env);
|
|
453
|
+
let example = null;
|
|
454
|
+
let exampleError = null;
|
|
455
|
+
try {
|
|
456
|
+
// The curve is skipped here: the landing page needs the verdict and the
|
|
457
|
+
// vault balances, not the whole transaction history, and the curve is
|
|
458
|
+
// the expensive part.
|
|
459
|
+
const loaded = await loadReceipt(EXAMPLE_MINT, { curve: false, maxTransactions: config.maxTransactions }, env);
|
|
460
|
+
example = loaded.receipt;
|
|
461
|
+
}
|
|
462
|
+
catch (err) {
|
|
463
|
+
exampleError = err.message.slice(0, 120);
|
|
464
|
+
}
|
|
465
|
+
const html = renderLanding(example, exampleError, url.origin, config);
|
|
466
|
+
return new Response(html, {
|
|
467
|
+
status: 200,
|
|
468
|
+
headers: {
|
|
469
|
+
'content-type': 'text/html; charset=utf-8',
|
|
470
|
+
'cache-control': 'public, max-age=60',
|
|
471
|
+
},
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
/** Render the landing page HTML. Pure — takes the receipt, returns a string. */
|
|
475
|
+
export function renderLanding(example, exampleError, origin, config) {
|
|
476
|
+
const exampleBlock = example
|
|
477
|
+
? `
|
|
478
|
+
<section>
|
|
479
|
+
<h2>Live example — ${escapeHtml(example.symbol ?? example.mint)}</h2>
|
|
480
|
+
<div class="panel">
|
|
481
|
+
<div class="stats">
|
|
482
|
+
<div class="stat bad"><div class="stat-label">claimed liquidity</div><div class="stat-value">${escapeHtml(formatUsd(example.claimed.liquidityUsd))}</div></div>
|
|
483
|
+
<div class="stat good"><div class="stat-label">actually deposited</div><div class="stat-value">${escapeHtml(formatUsd(example.real.depositedUsd))}</div></div>
|
|
484
|
+
<div class="stat"><div class="stat-label">coverage</div><div class="stat-value">${escapeHtml(formatCoverage(example.real.coverage))}</div></div>
|
|
485
|
+
<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>
|
|
486
|
+
</div>
|
|
487
|
+
<p class="headline">${escapeHtml(example.headline)}</p>
|
|
488
|
+
<p class="mono dim">${escapeHtml(example.mint)}</p>
|
|
489
|
+
<p class="mono dim">read from Solana mainnet at ${escapeHtml(example.generatedAt)}</p>
|
|
490
|
+
<p><a href="${escapeHtml(origin)}/receipt/${escapeHtml(example.mint)}">open the full receipt →</a></p>
|
|
491
|
+
</div>
|
|
492
|
+
</section>`
|
|
493
|
+
: `
|
|
494
|
+
<section>
|
|
495
|
+
<h2>Live example</h2>
|
|
496
|
+
<div class="panel">
|
|
497
|
+
<p class="dim">The example receipt could not be built right now${exampleError ? `: ${escapeHtml(exampleError)}` : '.'}</p>
|
|
498
|
+
<p class="dim">We will not print numbers we did not just read from the chain. Try the receipt endpoint directly:</p>
|
|
499
|
+
<p><a href="${escapeHtml(origin)}/receipt/${escapeHtml(EXAMPLE_MINT)}">/receipt/${escapeHtml(EXAMPLE_MINT)} →</a></p>
|
|
500
|
+
</div>
|
|
501
|
+
</section>`;
|
|
502
|
+
return `<!doctype html>
|
|
503
|
+
<html lang="en">
|
|
504
|
+
<head>
|
|
505
|
+
<meta charset="utf-8">
|
|
506
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
507
|
+
<title>LIQPROOF — on-chain liquidity receipts</title>
|
|
508
|
+
<style>
|
|
509
|
+
:root {
|
|
510
|
+
--bg: #0a0a0f;
|
|
511
|
+
--panel: #11111a;
|
|
512
|
+
--panel-2: #161622;
|
|
513
|
+
--line: #262633;
|
|
514
|
+
--fg: #f2f2f6;
|
|
515
|
+
--dim: #8b8b9a;
|
|
516
|
+
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
|
|
517
|
+
--red: #ff3b5c;
|
|
518
|
+
--green: #22c55e;
|
|
519
|
+
--amber: #ffb020;
|
|
520
|
+
--gray: #8b8b9a;
|
|
521
|
+
}
|
|
522
|
+
* { box-sizing: border-box; }
|
|
523
|
+
html, body { margin: 0; padding: 0; background: var(--bg); color: var(--fg); }
|
|
524
|
+
body { font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; line-height: 1.5; padding: 0 0 48px; }
|
|
525
|
+
.mono, code, th, .stat-value, .tag { font-family: var(--mono); }
|
|
526
|
+
header { border-bottom: 1px solid var(--line); background: linear-gradient(180deg, #0d0d15 0%, #0a0a0f 100%); padding: 28px 20px 22px; }
|
|
527
|
+
.wrap { max-width: 980px; margin: 0 auto; }
|
|
528
|
+
h1 { font-family: var(--mono); font-size: 26px; letter-spacing: 6px; margin: 0 0 6px; }
|
|
529
|
+
.tagline { color: var(--dim); margin: 0 0 22px; font-size: 15px; }
|
|
530
|
+
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; }
|
|
531
|
+
.stat { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 12px 14px; }
|
|
532
|
+
.stat-label { color: var(--dim); font-size: 11px; letter-spacing: 1.5px; text-transform: uppercase; font-family: var(--mono); }
|
|
533
|
+
.stat-value { font-size: 22px; margin-top: 4px; }
|
|
534
|
+
.stat.bad .stat-value { color: var(--red); }
|
|
535
|
+
.stat.good .stat-value { color: var(--green); }
|
|
536
|
+
main { max-width: 980px; margin: 0 auto; padding: 24px 20px; }
|
|
537
|
+
section { margin-bottom: 34px; }
|
|
538
|
+
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; }
|
|
539
|
+
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 16px; }
|
|
540
|
+
.headline { margin: 14px 0 6px; font-size: 16px; }
|
|
541
|
+
.dim { color: var(--dim); }
|
|
542
|
+
.tag { font-size: 11px; letter-spacing: 1px; padding: 2px 7px; border-radius: 4px; border: 1px solid currentColor; display: inline-block; }
|
|
543
|
+
.tag.FAKE_LIQUIDITY, .tag.NO_DEPTH, .tag.DRAINED { color: var(--red); }
|
|
544
|
+
.tag.THIN, .tag.UNBACKED_LIQUIDITY { color: var(--amber); }
|
|
545
|
+
.tag.NO_ROUTE { color: #38bdf8; }
|
|
546
|
+
.tag.CONSISTENT { color: var(--green); }
|
|
547
|
+
.tag.UNKNOWN { color: var(--gray); }
|
|
548
|
+
table { border-collapse: collapse; width: 100%; }
|
|
549
|
+
td, th { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); font-size: 13px; }
|
|
550
|
+
th { color: var(--dim); font-size: 11px; letter-spacing: 1px; text-transform: uppercase; font-family: var(--mono); font-weight: 400; }
|
|
551
|
+
a { color: #6ea8fe; text-decoration: none; }
|
|
552
|
+
a:hover { text-decoration: underline; }
|
|
553
|
+
code { color: #c3e88d; }
|
|
554
|
+
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; }
|
|
555
|
+
@media (max-width: 640px) { h1 { font-size: 20px; letter-spacing: 4px; } }
|
|
556
|
+
</style>
|
|
557
|
+
</head>
|
|
558
|
+
<body>
|
|
559
|
+
<header>
|
|
560
|
+
<div class="wrap">
|
|
561
|
+
<h1>LIQPROOF</h1>
|
|
562
|
+
<p class="tagline">The chain doesn't lie. We keep receipts.</p>
|
|
563
|
+
</div>
|
|
564
|
+
</header>
|
|
565
|
+
<main>
|
|
566
|
+
<section>
|
|
567
|
+
<h2>What this is</h2>
|
|
568
|
+
<div class="panel">
|
|
569
|
+
<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>
|
|
570
|
+
<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>
|
|
571
|
+
</div>
|
|
572
|
+
</section>
|
|
573
|
+
${exampleBlock}
|
|
574
|
+
<section>
|
|
575
|
+
<h2>Endpoints</h2>
|
|
576
|
+
<div class="panel">
|
|
577
|
+
<table>
|
|
578
|
+
<thead><tr><th>route</th><th>what it returns</th></tr></thead>
|
|
579
|
+
<tbody>
|
|
580
|
+
<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>
|
|
581
|
+
<tr><td class="mono"><a href="${escapeHtml(origin)}/health">GET /health</a></td><td>liveness, version, uptime</td></tr>
|
|
582
|
+
<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>
|
|
583
|
+
</tbody>
|
|
584
|
+
</table>
|
|
585
|
+
</div>
|
|
586
|
+
</section>
|
|
587
|
+
</main>
|
|
588
|
+
<footer>
|
|
589
|
+
<p>LIQPROOF reports on-chain measurements only. It does not issue investment advice or legal conclusions.</p>
|
|
590
|
+
<p>Read-only on-chain measurements. No gas, no paid APIs, no chain mutation.</p>
|
|
591
|
+
</footer>
|
|
592
|
+
</body>
|
|
593
|
+
</html>
|
|
594
|
+
`;
|
|
595
|
+
}
|
|
596
|
+
// ── OpenAPI ──────────────────────────────────────────────────────────────────
|
|
597
|
+
/**
|
|
598
|
+
* The OpenAPI 3.1 description of this API.
|
|
599
|
+
*
|
|
600
|
+
* 3.1 (not 3.0) because it is the version that matches JSON Schema 2020-12,
|
|
601
|
+
* which is what the x402 challenge object is.
|
|
602
|
+
*/
|
|
603
|
+
export function openApiDocument(origin) {
|
|
604
|
+
return {
|
|
605
|
+
openapi: '3.1.0',
|
|
606
|
+
info: {
|
|
607
|
+
title: 'LIQPROOF',
|
|
608
|
+
version: VERSION,
|
|
609
|
+
summary: 'On-chain liquidity receipts.',
|
|
610
|
+
description: '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.',
|
|
611
|
+
license: { name: 'MIT', identifier: 'MIT' },
|
|
612
|
+
},
|
|
613
|
+
servers: [{ url: origin }],
|
|
614
|
+
paths: {
|
|
615
|
+
'/receipt/{mint}': {
|
|
616
|
+
get: {
|
|
617
|
+
operationId: 'getReceipt',
|
|
618
|
+
summary: 'Get the liquidity receipt for a Solana mint.',
|
|
619
|
+
description: '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.',
|
|
620
|
+
parameters: [
|
|
621
|
+
{
|
|
622
|
+
name: 'mint',
|
|
623
|
+
in: 'path',
|
|
624
|
+
required: true,
|
|
625
|
+
description: 'Base58 Solana mint address.',
|
|
626
|
+
schema: { type: 'string', pattern: '^[1-9A-HJ-NP-Za-km-z]{32,44}$' },
|
|
627
|
+
},
|
|
628
|
+
{
|
|
629
|
+
name: 'format',
|
|
630
|
+
in: 'query',
|
|
631
|
+
required: false,
|
|
632
|
+
description: 'Response format.',
|
|
633
|
+
schema: { type: 'string', enum: ['json', 'md'], default: 'json' },
|
|
634
|
+
},
|
|
635
|
+
],
|
|
636
|
+
responses: {
|
|
637
|
+
'200': {
|
|
638
|
+
description: 'The receipt.',
|
|
639
|
+
content: {
|
|
640
|
+
'application/json': {
|
|
641
|
+
schema: { $ref: '#/components/schemas/Receipt' },
|
|
642
|
+
},
|
|
643
|
+
'text/markdown': {
|
|
644
|
+
schema: { type: 'string' },
|
|
645
|
+
},
|
|
646
|
+
},
|
|
647
|
+
},
|
|
648
|
+
'400': {
|
|
649
|
+
description: 'The mint is not a base58 Solana address.',
|
|
650
|
+
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
|
651
|
+
},
|
|
652
|
+
'402': {
|
|
653
|
+
description: 'Payment required. The body and the PAYMENT-REQUIRED header both carry the x402 challenge.',
|
|
654
|
+
headers: {
|
|
655
|
+
'payment-required': {
|
|
656
|
+
description: 'Base64-encoded x402 challenge (same JSON as the body).',
|
|
657
|
+
schema: { type: 'string' },
|
|
658
|
+
},
|
|
659
|
+
},
|
|
660
|
+
content: {
|
|
661
|
+
'application/json': {
|
|
662
|
+
schema: { $ref: '#/components/schemas/PaymentRequired' },
|
|
663
|
+
},
|
|
664
|
+
},
|
|
665
|
+
},
|
|
666
|
+
'503': {
|
|
667
|
+
description: 'This deployment has no payment recipient configured.',
|
|
668
|
+
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
|
|
669
|
+
},
|
|
670
|
+
},
|
|
671
|
+
},
|
|
672
|
+
},
|
|
673
|
+
'/health': {
|
|
674
|
+
get: {
|
|
675
|
+
operationId: 'getHealth',
|
|
676
|
+
summary: 'Liveness probe.',
|
|
677
|
+
responses: {
|
|
678
|
+
'200': {
|
|
679
|
+
description: 'The worker is alive.',
|
|
680
|
+
content: {
|
|
681
|
+
'application/json': {
|
|
682
|
+
schema: {
|
|
683
|
+
type: 'object',
|
|
684
|
+
required: ['ok', 'version', 'uptime'],
|
|
685
|
+
properties: {
|
|
686
|
+
ok: { type: 'boolean' },
|
|
687
|
+
version: { type: 'string' },
|
|
688
|
+
uptime: { type: 'integer', description: 'Seconds since start.' },
|
|
689
|
+
},
|
|
690
|
+
},
|
|
691
|
+
},
|
|
692
|
+
},
|
|
693
|
+
},
|
|
694
|
+
},
|
|
695
|
+
},
|
|
696
|
+
},
|
|
697
|
+
},
|
|
698
|
+
components: {
|
|
699
|
+
schemas: {
|
|
700
|
+
PaymentRequired: {
|
|
701
|
+
type: 'object',
|
|
702
|
+
required: ['x402Version', 'error', 'resource', 'accepts'],
|
|
703
|
+
properties: {
|
|
704
|
+
x402Version: { type: 'integer', const: 2 },
|
|
705
|
+
error: { type: 'string' },
|
|
706
|
+
resource: {
|
|
707
|
+
type: 'object',
|
|
708
|
+
required: ['url', 'description', 'mimeType'],
|
|
709
|
+
properties: {
|
|
710
|
+
url: { type: 'string' },
|
|
711
|
+
description: { type: 'string' },
|
|
712
|
+
mimeType: { type: 'string' },
|
|
713
|
+
},
|
|
714
|
+
},
|
|
715
|
+
accepts: {
|
|
716
|
+
type: 'array',
|
|
717
|
+
items: { $ref: '#/components/schemas/PaymentRequirements' },
|
|
718
|
+
},
|
|
719
|
+
},
|
|
720
|
+
},
|
|
721
|
+
PaymentRequirements: {
|
|
722
|
+
type: 'object',
|
|
723
|
+
required: ['scheme', 'network', 'asset', 'amount', 'payTo', 'maxTimeoutSeconds'],
|
|
724
|
+
properties: {
|
|
725
|
+
scheme: { type: 'string', const: 'exact' },
|
|
726
|
+
network: { type: 'string', enum: ['solana', 'solana-devnet'] },
|
|
727
|
+
asset: { type: 'string', description: 'USDC mint.' },
|
|
728
|
+
amount: { type: 'string', description: 'Price in atomic units of the asset.' },
|
|
729
|
+
payTo: { type: 'string', description: 'Recipient address.' },
|
|
730
|
+
maxTimeoutSeconds: { type: 'integer' },
|
|
731
|
+
description: { type: 'string' },
|
|
732
|
+
extra: { type: 'object', additionalProperties: true },
|
|
733
|
+
},
|
|
734
|
+
},
|
|
735
|
+
Receipt: {
|
|
736
|
+
type: 'object',
|
|
737
|
+
required: ['version', 'generatedAt', 'mint', 'verdict', 'claimed', 'real'],
|
|
738
|
+
properties: {
|
|
739
|
+
version: { type: 'string' },
|
|
740
|
+
generatedAt: { type: 'string' },
|
|
741
|
+
mint: { type: 'string' },
|
|
742
|
+
symbol: { type: 'string' },
|
|
743
|
+
name: { type: 'string' },
|
|
744
|
+
verdict: {
|
|
745
|
+
type: 'string',
|
|
746
|
+
enum: [
|
|
747
|
+
'FAKE_LIQUIDITY',
|
|
748
|
+
'UNBACKED_LIQUIDITY',
|
|
749
|
+
'NO_DEPTH',
|
|
750
|
+
'DRAINED',
|
|
751
|
+
'THIN',
|
|
752
|
+
'CONSISTENT',
|
|
753
|
+
'NO_ROUTE',
|
|
754
|
+
'UNKNOWN',
|
|
755
|
+
],
|
|
756
|
+
},
|
|
757
|
+
headline: { type: 'string' },
|
|
758
|
+
summary: { type: 'string' },
|
|
759
|
+
claimed: { type: 'object', additionalProperties: true },
|
|
760
|
+
real: { type: 'object', additionalProperties: true },
|
|
761
|
+
evidence: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
762
|
+
},
|
|
763
|
+
},
|
|
764
|
+
Error: {
|
|
765
|
+
type: 'object',
|
|
766
|
+
required: ['error'],
|
|
767
|
+
properties: {
|
|
768
|
+
error: { type: 'string' },
|
|
769
|
+
hint: { type: 'string' },
|
|
770
|
+
},
|
|
771
|
+
},
|
|
772
|
+
},
|
|
773
|
+
},
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
// ── the handler ──────────────────────────────────────────────────────────────
|
|
777
|
+
/**
|
|
778
|
+
* Add the CORS headers every endpoint wants.
|
|
779
|
+
*
|
|
780
|
+
* The receipts are meant to be read by agents and browsers alike, so every
|
|
781
|
+
* response — including the preflight — carries them.
|
|
782
|
+
*/
|
|
783
|
+
function withCors(response) {
|
|
784
|
+
const headers = new Headers(response.headers);
|
|
785
|
+
headers.set('access-control-allow-origin', '*');
|
|
786
|
+
headers.set('access-control-expose-headers', 'payment-required, x-liqproof-access, x-liqproof-free-tier, x-liqproof-verdict');
|
|
787
|
+
return new Response(response.body, {
|
|
788
|
+
status: response.status,
|
|
789
|
+
statusText: response.statusText,
|
|
790
|
+
headers,
|
|
791
|
+
});
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Handle one request.
|
|
795
|
+
*
|
|
796
|
+
* Exported so the local CLI (`liqproof serve`) can serve exactly the same
|
|
797
|
+
* API from Node — one implementation, two hosts, no drift.
|
|
798
|
+
*/
|
|
799
|
+
export async function handleRequest(request, env) {
|
|
800
|
+
if (request.method === 'OPTIONS') {
|
|
801
|
+
return withCors(new Response(null, {
|
|
802
|
+
status: 204,
|
|
803
|
+
headers: {
|
|
804
|
+
'access-control-allow-methods': 'GET, HEAD, OPTIONS',
|
|
805
|
+
'access-control-allow-headers': 'content-type, payment-signature, x-payment',
|
|
806
|
+
'access-control-max-age': '86400',
|
|
807
|
+
},
|
|
808
|
+
}));
|
|
809
|
+
}
|
|
810
|
+
return withCors(await route(request, env));
|
|
811
|
+
}
|
|
812
|
+
/** The routing table. */
|
|
813
|
+
async function route(request, env) {
|
|
814
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
815
|
+
return json({ error: 'method_not_allowed', allowed: ['GET', 'HEAD'] }, 405, { allow: 'GET, HEAD' });
|
|
816
|
+
}
|
|
817
|
+
const url = new URL(request.url);
|
|
818
|
+
const path = url.pathname.replace(/\/+$/, '') || '/';
|
|
819
|
+
if (path === '/health')
|
|
820
|
+
return healthResponse();
|
|
821
|
+
if (path === '/openapi.json')
|
|
822
|
+
return json(openApiDocument(url.origin));
|
|
823
|
+
if (path === '/')
|
|
824
|
+
return landingResponse(url, env);
|
|
825
|
+
if (path === '/receipt' || path.startsWith('/receipt/')) {
|
|
826
|
+
try {
|
|
827
|
+
return await receiptRoute(request, url, env);
|
|
828
|
+
}
|
|
829
|
+
catch (err) {
|
|
830
|
+
// The chain could not be read. Say so honestly instead of returning a
|
|
831
|
+
// half-built receipt that looks like evidence.
|
|
832
|
+
return json({
|
|
833
|
+
error: 'receipt_unavailable',
|
|
834
|
+
message: err.message.slice(0, 200),
|
|
835
|
+
hint: 'the free public RPC is rate limited; retry in a few seconds',
|
|
836
|
+
}, 502);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
return json({
|
|
840
|
+
error: 'not_found',
|
|
841
|
+
hint: 'GET /, /health, /openapi.json, /receipt/<mint>',
|
|
842
|
+
}, 404);
|
|
843
|
+
}
|
|
844
|
+
// ── the Worker entry point ───────────────────────────────────────────────────
|
|
845
|
+
/**
|
|
846
|
+
* Cloudflare Workers entry point.
|
|
847
|
+
*
|
|
848
|
+
* `export default { fetch(request, env) }` is the whole contract. There is
|
|
849
|
+
* no scheduled handler, no queue consumer and no durable object: the service
|
|
850
|
+
* is stateless apart from two KV bindings it uses when they are attached.
|
|
851
|
+
*/
|
|
852
|
+
export default {
|
|
853
|
+
async fetch(request, env) {
|
|
854
|
+
return handleRequest(request, env ?? {});
|
|
855
|
+
},
|
|
856
|
+
};
|
|
857
|
+
//# sourceMappingURL=worker.js.map
|