Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(x402): free developer toolkit — echo, debug, verify-receipt
fudjia0ebeb0e2d6a0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c44e8c840..096c9d18a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Docs · Crypto Data API** (`/docs/crypto-api`) — Developer reference for the free, keyless Crypto Data API bundle: the one-call discovery endpoint (GET /api/crypto), the generated OpenAPI 3.1 spec, and every endpoint's inputs, outputs, states, and curl examples — token snapshots, bonding status, whales, trending, wallet portfolios, and symbol availability.- **Docs · Pump Launcher** (`/docs/pump-launcher`) — Deploy a brand-new pump.fun token in one paid call — no SOL, no wallet, no account. Inputs, outputs, pricing, correctness guarantees, and the free symbol-check → launch → launch-feed funnel.- **Docs · Trust Primitives** (`/docs/trust-primitives`) — Cross-chain Agent Reputation — score any wallet, mint, or agent id (Solana or EVM) 0–100 from real on-chain evidence before your agent pays, trades, or delegates.+- **Docs · x402 Developer Tools** (`/docs/x402-dev-tools`) — A free test bench for x402 developers — echo your payment envelope, debug a failed 402 exchange, and verify a receipt's attestation and settlement against a live server, all without spending anything.- **3D model inspection is now free** — Validating and optimizing a glTF/GLB no longer costs anything. The new free, keyless /api/3d/inspect takes a model URL (or a raw upload) and returns whether it's spec-valid, its full structural stats — vertices, triangles, materials, textures, animations, extensions — and a severity-ranked list of exactly what to fix to make it smaller and faster for the web. It runs the official Khronos glTF-Validator plus the same inspection core the platform's paid pipelines use. This capability used to be a paid x402 endpoint (model-check); a validation utility should be free — it builds trust and points agents at the paid Forge Pro, Rigged Avatar, and optimization tiers when they need the heavy lifting done for them. `[feature, improvement]`- **3D Studio tools can now be paid on X Layer via the OKX Agent Payments Protocol** — Agents on the OKX.AI marketplace can now pay for our 3D tools the way that marketplace expects: our payment challenge now offers X Layer (chain 196) in the USD₮0 stablecoin alongside the existing USDC-on-Base/Solana options, and speaks the OKX buyer flow end to end — it verifies the payment on-chain before doing any work and only charges after the tool succeeds. Existing customers paying on Base or Solana are unaffected; this simply adds a rail. It's the integration OKX asked us to complete before re-listing our 3D Studio agent. `[feature, infra]`- **Agent reputation now scores any wallet or agent on any chain** — The paid Agent Reputation endpoint no longer only works on three.ws agents — pass ANY counterparty and get a deterministic 0–100 trust score before you pay, trade, or delegate to it. It auto-detects the type — a Solana wallet, an EVM 0x address, a pump.fun mint, an ERC-8004 agent id, or a three.ws agent_id — and scores it from real on-chain evidence: transaction history, account age, distinct counterparties, holdings, settlement reliability, prior settled agent payments, and ERC-8004 feedback. Every score comes with the underlying evidence links and a clear list of what couldn't be read; an unknown or unscannable subject returns score:null, never a fabricated number. A new batch mode scores up to 25 counterparties in one call. It's a genuine pre-transaction trust primitive that works across chains, not just on our own platform. (`/docs/trust-primitives`) `[feature, improvement]`@@ -29,6 +30,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Free trending-tokens API for crypto agents** — New free, keyless endpoint GET /api/crypto/trending gives any AI agent a ranked "what's hot right now" list in one call — no account, no key. Tokens are ranked by momentum (a 0–100 score blending windowed trade volume, buy pressure, a volume-spike signal, and short-window price change), fused live across pump.fun, DexScreener's boosted board, and GMGN smart money. Pick a window (5m, 1h, or 24h) and a source (pump.fun only or all), and get back each token's mint, symbol, market cap, volume, price change, score, and link. If an upstream is down it returns whatever ranked data it has with a note instead of failing. (`/docs/crypto-api`) `[feature]`- **Free wallet portfolio API for agents** — New free, keyless endpoint: GET /api/crypto/wallet returns any wallet's native balance, every token it holds, and a rough USD valuation in one call — no account, no API key. It's built for agents that need to size up a wallet before they act: a treasury agent checking its own runway, a copy-trade agent reading a leader's holdings, or a pre-trade check on a counterparty. Solana works with no key at all (it falls back to the public RPC plus Jupiter and pump.fun pricing); tokens that can't be priced are still listed with their balance, never dropped or faked. `[feature]`- **Free whale-activity API for crypto agents** — A new free, keyless endpoint tells an AI agent whether big money is moving before it trades. Call /api/crypto/whales with a token mint to see the large buys of that coin, or without one to see the top whale wallets active across pump.fun right now. Each response carries a plain bullish/bearish/neutral signal derived from net whale flow — the SOL whales bought minus the SOL they sold — with no black-box scoring. No account, no key, no payment. `[feature]`+- **Free x402 developer toolkit — echo, debug, and verify a receipt against a live server** — Building an x402 integration against three.ws just got easier. Three new free, keyless tools: echo shows you exactly what the server sees when you send a payment — the decoded envelope with every signature redacted, plus a local valid/invalid verdict without charging you. debug turns a failed 402 exchange into an ordered fix list keyed to the real reasons a payment gets rejected (wrong version, shorthand network, decimal amounts, underpayment). verify-receipt recomputes a paid response's SHA-256 attestation to prove it wasn't altered, and confirms a settlement transaction on-chain. A new docs page ties all six developer tools together. (`/docs/x402-dev-tools`) `[feature, docs]`- **Give your assistant a living 3D body that lip-syncs and emotes in the chat** — Turn any generated avatar into a persistent, named agent body that renders right inside ChatGPT or Claude. It lip-syncs each reply, shows the matching expression and gesture, idles between turns, and comes back as the same body when you return to it — no account needed. Three new free 3D Studio tools drive it: save an avatar as a persona, make it speak a reply, and reload it by id in a later session. A rig with no facial morphs still animates its mouth from the jaw, and a non-humanoid model falls back to a gentle idle instead of a broken pose. `[feature]`- **Hire and pay another agent, transparently — the live agent-to-agent commerce loop** — Your agent can now discover a specialist agent, check its on-chain reputation, pay it in USDC, hand off the task, and get the result back with a full receipt — who it hired, the reputation behind the choice, exactly what it cost, and the on-chain settlement reference. The agent_hire_discover tool ranks candidates by task fit, ERC-8004 reputation and real engagement; agent_hire runs the whole thing end to end and renders an inline provenance receipt card. Hard spend guardrails protect you throughout: a per-call cap, a per-session budget, and a confirmation prompt for anything above a threshold — and a blocked or failed hire is never charged. Discovery no longer comes up empty on a plain-language request, and paid hires now complete against a live agent. `[feature, improvement]`- **Mint a generated 3D avatar as an on-chain Solana NFT — with a live 3D viewer as its media** — You can now turn a generated or owned avatar into real, ownable on-chain property. The new mint_3d_asset tool mints your rigged GLB as a Solana NFT whose media is a live, interactive 3D viewer — not a flat picture — with the model, a rendered thumbnail, and its full provenance (who made it, the prompt, the model, its lineage) travelling with it. Creator royalties are enforced on every resale, capped at 10%. A companion get_3d_asset_onchain tool resolves any mint back to its current holder, live viewer, provenance, and royalty terms. Minting defaults to devnet for safe testing; mainnet is an explicit opt-in. It's idempotent, so a retried mint never creates a duplicate. `[feature, sdk]`diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 1f21ace84..d52a07346 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -670,6 +670,11 @@ export const limits = {// Vercel) bounds one IP's throughput just as well without spending a Redis// command per page view. The largest single source of avoidable quota burn.publicIp: (ip) => getLimiter('public:ip', { limit: 60, window: '1 m', local: true }).limit(ip),+ // Free x402 developer toolkit (echo / debug / verify-receipt). Free ≠+ // abusable: these decode caller-supplied payment envelopes and recompute+ // hashes, so 30/min per IP is generous for a developer iterating on their+ // integration while bounding a script that hammers the decode path.+ x402DevToolIp: (ip) => getLimiter('x402-dev-tool:ip', { limit: 30, window: '1 m' }).limit(ip),// Client-side error report ingestion (api/client-errors). The browser// reporter batches and caps itself at 25 events/page, so legitimate traffic// is a handful of requests per pageview even on a broken page; 30/min perdiff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.jsindex 9f90fc8e2..28e4030f1 100644--- a/api/_lib/x402-spec.js+++ b/api/_lib/x402-spec.js@@ -445,7 +445,7 @@ async function authHeadersFor(config, path) {return config.token ? { Authorization: `Bearer ${config.token}` } : {};}-function decodePaymentHeader(header) {+export function decodePaymentHeader(header) {if (!header) throw new X402Error('payment_required', 'X-PAYMENT header required', 402);let json;try {@@ -825,7 +825,7 @@ function selectRequirement(paymentPayload, allRequirements) {// Defense-in-depth: a compromised facilitator could otherwise verify a// payment for a smaller amount than the requirement and we'd happily// deliver the resource. Per the audit, this is the underpayment vector.-function decodeSignedAmount(paymentPayload) {+export function decodeSignedAmount(paymentPayload) {const inner = paymentPayload?.payload;if (!inner || typeof inner !== 'object') return null;// EIP-3009 transferWithAuthorization — `authorization.value` is the@@ -874,7 +874,7 @@ function decodeSignedAmount(paymentPayload) {// Defense-in-depth: the EIP-712 signature commits to `to`, so a payment whose// signed recipient differs from the offered payTo is invalid regardless of// what /verify returns.-function decodeSignedRecipient(paymentPayload) {+export function decodeSignedRecipient(paymentPayload) {const inner = paymentPayload?.payload;if (!inner || typeof inner !== 'object') return null;// EIP-3009 transferWithAuthorization — `authorization.to` is signed.diff --git a/api/_lib/x402/dev-tools.js b/api/_lib/x402/dev-tools.jsnew file mode 100644index 000000000..f4c8ea7bc--- /dev/null+++ b/api/_lib/x402/dev-tools.js@@ -0,0 +1,368 @@+// Pure logic for the free x402 developer toolkit (echo / debug / verify-receipt).+//+// Kept I/O-free so every branch is unit-testable without a network or a live+// facilitator. The route handlers in api/x402/{echo,debug,verify-receipt}.js are+// thin wrappers that add CORS, rate limiting, and body parsing on top of these.+//+// Three capabilities:+// • redactPaymentEnvelope() — decode an X-PAYMENT header and strip every+// signature/secret down to a short prefix so echo can show a developer the+// server's view of their payload WITHOUT leaking a reusable authorization.+// • structuralVerdict() — the rail's LOCAL verification (shape + signed+// amount vs required + signed recipient vs payTo + builder-code echo). No+// facilitator round-trip, no settlement — a fast, safe "would this pass our+// own pre-facilitator checks?" verdict.+// • diagnoseExchange() — turn a failed 402 exchange (challenge / payment /+// response, any subset) into a [{severity, field, problem, fix}] list keyed+// to the real failure modes our rail produces.+// • recomputeAttestation() / verifyAttestation() — recompute a three.ws+// SHA-256 response attestation (fact-check style) and confirm/deny integrity.++import { createHash } from 'crypto';++import {+ decodePaymentHeader,+ decodeSignedAmount,+ decodeSignedRecipient,+ X402_VERSION,+ NETWORK_BASE_MAINNET,+ NETWORK_SOLANA_MAINNET,+} from '../x402-spec.js';++// Every field name whose value is a signature, private authorization, or other+// secret that must never be echoed back in full. Matched case-insensitively,+// substring — `signature`, `sig`, `authorization`, `secret`, `privateKey`, etc.+const SECRET_KEY_PATTERNS = [+ 'signature',+ 'sig',+ 'secret',+ 'privatekey',+ 'private_key',+ 'mnemonic',+ 'seed',+ 'password',+ 'passphrase',+];++// How many leading characters of a redacted secret to keep, so a developer can+// still eyeball "yes that's my sig" without the value being replayable.+const REDACT_KEEP = 10;++function looksSecret(key) {+ const k = String(key).toLowerCase();+ return SECRET_KEY_PATTERNS.some((p) => k.includes(p));+}++// Replace a secret value with `<prefix>…(redacted, N chars)`. Non-string+// secrets (rare) collapse to a type marker so nothing sensitive survives.+function redactValue(value) {+ if (typeof value !== 'string') return '<redacted:non-string>';+ if (value.length <= REDACT_KEEP) return `${value}…(redacted)`;+ return `${value.slice(0, REDACT_KEEP)}…(redacted, ${value.length} chars)`;+}++// Deep-clone `obj`, redacting any value whose key looks like a secret. Also+// redacts long hex/base64 blobs living under an `authorization` object even when+// the key itself is innocuous (e.g. EIP-3009 `v`/`r`/`s` split signatures).+export function redactSecrets(obj, { inAuthorization = false } = {}) {+ if (Array.isArray(obj)) return obj.map((v) => redactSecrets(v, { inAuthorization }));+ if (obj && typeof obj === 'object') {+ const out = {};+ for (const [k, v] of Object.entries(obj)) {+ const childInAuth = inAuthorization || k.toLowerCase() === 'authorization';+ if (looksSecret(k)) {+ out[k] = redactValue(v);+ } else if (+ childInAuth &&+ typeof v === 'string' &&+ /^0x[0-9a-fA-F]{16,}$/.test(v)+ ) {+ // A long 0x blob inside the signed authorization is signature+ // material regardless of its field name — redact it too.+ out[k] = redactValue(v);+ } else if (v && typeof v === 'object') {+ out[k] = redactSecrets(v, { inAuthorization: childInAuth });+ } else {+ out[k] = v;+ }+ }+ return out;+ }+ return obj;+}++// Decode an X-PAYMENT header and return a redacted view of the envelope plus the+// fields a developer needs to debug: version, scheme, network, and the located+// signed amount/recipient. Throws on a structurally invalid header (base64 / JSON+// / not-an-object) — the caller maps that to a 400 with the thrown message.+export function redactPaymentEnvelope(paymentHeader) {+ const payload = decodePaymentHeader(paymentHeader); // throws X402Error on bad shape+ const signedAmount = decodeSignedAmount(payload);+ const signedRecipient = decodeSignedRecipient(payload);+ return {+ x402Version: payload.x402Version ?? null,+ scheme: payload.scheme ?? payload.accepted?.scheme ?? null,+ network: payload.network ?? payload.accepted?.network ?? null,+ signedAmount: signedAmount === null ? null : signedAmount.toString(),+ signedRecipient,+ envelope: redactSecrets(payload),+ };+}++// The rail's LOCAL pre-facilitator verdict for a decoded payment against a single+// requirement (accept entry). Mirrors the defense-in-depth checks verifyPayment()+// runs before ever calling the facilitator, but performs no network I/O and never+// settles. Returns { valid, checks[], reason? }.+//+// `requirement` is one accepts[] entry ({ scheme, network, amount, payTo, ... }).+// When omitted, only the envelope-shape checks run (amount/recipient are reported+// as "no requirement to compare against").+export function structuralVerdict(payload, requirement) {+ const checks = [];+ const fail = (field, detail) => checks.push({ field, pass: false, detail });+ const pass = (field, detail) => checks.push({ field, pass: true, detail });++ // Shape.+ if (!payload || typeof payload !== 'object') {+ return { valid: false, checks: [{ field: 'payload', pass: false, detail: 'not an object' }], reason: 'payload is not an object' };+ }+ if (payload.x402Version === X402_VERSION) pass('x402Version', `is ${X402_VERSION}`);+ else fail('x402Version', `expected ${X402_VERSION}, got ${payload.x402Version ?? 'undefined'}`);++ const scheme = payload.scheme ?? payload.accepted?.scheme;+ if (scheme) pass('scheme', String(scheme));+ else fail('scheme', 'missing scheme (top-level or accepted.scheme)');++ const network = payload.network ?? payload.accepted?.network;+ if (network) pass('network', String(network));+ else fail('network', 'missing network');++ // Amount: the signed amount must be ≥ the required amount (underpayment guard).+ const signedAmount = decodeSignedAmount(payload);+ if (requirement && requirement.amount != null) {+ if (signedAmount === null) {+ pass('amount', 'signed amount not locally decodable (Solana SPL / opaque) — facilitator-trusted');+ } else {+ let required = null;+ try {+ required = BigInt(requirement.amount);+ } catch {+ fail('amount', `requirement.amount "${requirement.amount}" is not an integer string`);+ }+ if (required !== null) {+ if (signedAmount >= required) pass('amount', `signed ${signedAmount} ≥ required ${required}`);+ else fail('amount', `signed ${signedAmount} < required ${required} (underpayment)`);+ }+ }+ } else if (signedAmount !== null) {+ pass('amount', `signed ${signedAmount} (no requirement supplied to compare)`);+ }++ // Recipient: the signed `to` must equal the requirement's payTo.+ const signedRecipient = decodeSignedRecipient(payload);+ if (requirement && requirement.payTo) {+ if (signedRecipient === null) {+ pass('payTo', 'signed recipient not locally decodable — facilitator-trusted');+ } else if (signedRecipient === String(requirement.payTo).toLowerCase()) {+ pass('payTo', 'signed recipient matches requirement.payTo');+ } else {+ fail('payTo', `signed recipient ${signedRecipient} ≠ requirement.payTo ${String(requirement.payTo).toLowerCase()}`);+ }+ }++ const failed = checks.filter((c) => !c.pass);+ return {+ valid: failed.length === 0,+ checks,+ ...(failed.length ? { reason: failed.map((c) => `${c.field}: ${c.detail}`).join('; ') } : {}),+ };+}++// Known networks our rail settles on, for the debugger's network sanity check.+const KNOWN_NETWORKS = new Set([+ NETWORK_BASE_MAINNET,+ NETWORK_SOLANA_MAINNET,+ 'eip155:42161',+ 'eip155:56',+ 'eip155:196',+]);++// Common shorthand a developer might send instead of the CAIP-2 id our accepts[]+// advertise — flagged with the canonical form as the fix.+const NETWORK_ALIASES = {+ base: NETWORK_BASE_MAINNET,+ 'base-mainnet': NETWORK_BASE_MAINNET,+ solana: NETWORK_SOLANA_MAINNET,+ 'solana-mainnet': NETWORK_SOLANA_MAINNET,+ arbitrum: 'eip155:42161',+ bsc: 'eip155:56',+ xlayer: 'eip155:196',+};++// Diagnose a failed x402 exchange. `input` may carry any subset of+// { challenge, payment, response }. Returns a flat list of findings ordered+// most-severe first: [{ severity: 'error'|'warning'|'info', field, problem, fix }].+export function diagnoseExchange(input = {}) {+ const findings = [];+ const add = (severity, field, problem, fix) => findings.push({ severity, field, problem, fix });++ const { challenge, payment, response } = input || {};++ if (challenge === undefined && payment === undefined && response === undefined) {+ add('error', 'input', 'no challenge, payment, or response supplied', 'POST at least one of { challenge, payment, response } — the 402 body, your X-PAYMENT payload (decoded), and/or the server response you got back.');+ return { findings, ok: false };+ }++ // ── Challenge (the 402 body the server sent) ────────────────────────────+ let accepts = null;+ if (challenge !== undefined) {+ if (!challenge || typeof challenge !== 'object') {+ add('error', 'challenge', 'challenge is not a JSON object', 'Paste the parsed 402 response body, e.g. { x402Version, accepts: [...] }.');+ } else {+ if (challenge.x402Version !== undefined && challenge.x402Version !== X402_VERSION) {+ add('warning', 'challenge.x402Version', `challenge advertises x402Version ${challenge.x402Version}; this server speaks ${X402_VERSION}`, `Send x402Version: ${X402_VERSION} in your payment payload.`);+ }+ accepts = challenge.accepts || challenge.requirements || null;+ if (!Array.isArray(accepts) || accepts.length === 0) {+ add('error', 'challenge.accepts', 'challenge has no accepts[] array', 'A valid 402 body carries accepts[] (v2) or requirements[] (legacy) with at least one payment option.');+ } else {+ for (let i = 0; i < accepts.length; i++) {+ const a = accepts[i];+ if (a?.amount != null && !/^\d+$/.test(String(a.amount))) {+ add('error', `challenge.accepts[${i}].amount`, `amount "${a.amount}" is not an integer atomic-units string`, 'amount is in the asset\'s smallest unit as a string (USDC 6-decimals → "10000" = $0.01), never a decimal like "0.01".');+ }+ }+ }+ }+ }++ // ── Payment (the decoded X-PAYMENT payload the caller signed) ───────────+ if (payment !== undefined) {+ if (!payment || typeof payment !== 'object') {+ add('error', 'payment', 'payment is not a JSON object', 'Base64-decode your X-PAYMENT header and paste the resulting JSON here (or POST the raw header to /api/x402/echo).');+ } else {+ if (payment.x402Version !== undefined && payment.x402Version !== X402_VERSION) {+ add('error', 'payment.x402Version', `payment declares x402Version ${payment.x402Version}; server requires ${X402_VERSION}`, `Set x402Version: ${X402_VERSION}.`);+ } else if (payment.x402Version === undefined) {+ add('warning', 'payment.x402Version', 'payment payload omits x402Version', `Include x402Version: ${X402_VERSION}.`);+ }+ const net = payment.network ?? payment.accepted?.network;+ if (net) {+ const alias = NETWORK_ALIASES[String(net).toLowerCase()];+ if (alias && alias !== net) {+ add('error', 'payment.network', `network "${net}" is a shorthand, not the CAIP-2 id the rail matches on`, `Use "${alias}".`);+ } else if (!KNOWN_NETWORKS.has(net) && !alias) {+ add('warning', 'payment.network', `network "${net}" is not one this server advertises`, 'Copy the exact network string from an accepts[] entry in the 402 challenge.');+ }+ // Cross-check against the challenge's offered networks.+ if (Array.isArray(accepts) && accepts.length) {+ const offered = accepts.map((a) => a.network).filter(Boolean);+ if (offered.length && !offered.includes(net)) {+ add('error', 'payment.network', `you signed for "${net}" but the challenge only offers [${offered.join(', ')}]`, 'Pick one of the offered networks and re-sign against that accepts[] entry.');+ }+ }+ } else {+ add('error', 'payment.network', 'payment payload has no network', 'Set network to the CAIP-2 id from the accepts[] entry you chose.');+ }++ // Amount vs the matching accept.+ const signed = decodeSignedAmount(payment);+ if (signed !== null && Array.isArray(accepts) && accepts.length) {+ const match = accepts.find((a) => a.network === (payment.network ?? payment.accepted?.network)) || accepts[0];+ if (match?.amount != null && /^\d+$/.test(String(match.amount))) {+ const required = BigInt(match.amount);+ if (signed < required) {+ add('error', 'payment.authorization.value', `signed amount ${signed} is below the required ${required}`, 'Sign an authorization for at least the amount in the accepts[] entry (atomic units).');+ }+ }+ }+ // Decimal-vs-atomic footgun: an authorization value that looks like a+ // human decimal ("0.01") never parses as atomic units.+ const rawVal = payment?.payload?.authorization?.value;+ if (typeof rawVal === 'string' && rawVal.includes('.')) {+ add('error', 'payment.authorization.value', `value "${rawVal}" contains a decimal point`, 'Authorization value is atomic units as an integer string ("10000"), not a decimal token amount.');+ }+ }+ }++ // ── Response (the server's error the caller got back) ───────────────────+ if (response !== undefined && response && typeof response === 'object') {+ const code = response.error || response.code;+ const known = {+ payment_required: 'No X-PAYMENT header was sent (or it was empty). Attach your base64 payment payload as the X-PAYMENT header and retry.',+ invalid_payment: 'The payload was structurally valid but failed a check — usually underpayment, wrong payTo, or a malformed authorization. Run /api/x402/echo on your header to see the decoded amount/recipient.',+ unsupported_network: 'The network in your payload is not one this resource offers. Use a network from the challenge accepts[].',+ builder_code_tampered: 'The builder-code extension in your payload does not echo the one the challenge declared. Do not modify extensions[]; pass them through verbatim.',+ };+ if (code && known[code]) {+ add('info', 'response.error', `server returned "${code}"`, known[code]);+ } else if (code) {+ add('info', 'response.error', `server returned "${code}"`, 'See docs/x402 for the full error catalog.');+ }+ }++ // Order: error → warning → info.+ const rank = { error: 0, warning: 1, info: 2 };+ findings.sort((a, b) => rank[a.severity] - rank[b.severity]);+ return { findings, ok: findings.every((f) => f.severity !== 'error') };+}++// Recompute a three.ws fact-check style attestation from the response fields it+// commits to. The scheme (api/x402/fact-check.js) is:+// "sha256:" + sha256(JSON.stringify({ verdict, confidence, claim, sources: [urls] }))+// Returns the recomputed "sha256:<hex>" string.+export function recomputeAttestation(result) {+ const sources = Array.isArray(result?.sources)+ ? result.sources.map((s) => (typeof s === 'string' ? s : s?.url)).filter(Boolean)+ : [];+ return (+ 'sha256:' ++ createHash('sha256')+ .update(+ JSON.stringify({+ verdict: result?.verdict,+ confidence: result?.confidence,+ claim: result?.claim,+ sources,+ }),+ )+ .digest('hex')+ );+}++// Confirm/deny a claimed attestation against the result it was computed over.+// Returns { verified, scheme, recomputed, claimed, mismatchReason? }.+export function verifyAttestation(result) {+ const claimed = result?.attestation;+ if (typeof claimed !== 'string' || !claimed.startsWith('sha256:')) {+ return {+ verified: false,+ scheme: 'sha256',+ recomputed: null,+ claimed: claimed ?? null,+ mismatchReason: 'no sha256: attestation string present on the object',+ };+ }+ // Everything the scheme hashes must be present, else "verified: true" would be+ // vacuous (hashing undefineds).+ const missing = ['verdict', 'confidence', 'claim', 'sources'].filter(+ (k) => result[k] === undefined || result[k] === null,+ );+ if (missing.length) {+ return {+ verified: false,+ scheme: 'sha256',+ recomputed: null,+ claimed,+ mismatchReason: `cannot recompute — the attested fields are missing: ${missing.join(', ')}`,+ };+ }+ const recomputed = recomputeAttestation(result);+ return {+ verified: recomputed === claimed,+ scheme: 'sha256',+ recomputed,+ claimed,+ ...(recomputed === claimed ? {} : { mismatchReason: 'recomputed digest does not match the attested one — the object was altered after signing' }),+ };+}diff --git a/api/x402/debug.js b/api/x402/debug.jsnew file mode 100644index 000000000..661c29f59--- /dev/null+++ b/api/x402/debug.js@@ -0,0 +1,49 @@+// POST /api/x402/debug+//+// x402 exchange debugger — FREE, keyless. Paste any subset of a failed 402+// exchange and get a structured diagnosis of what's wrong and how to fix it,+// keyed to the real failure modes this server's payment rail produces.+//+// Body: { challenge?, payment?, response? } — any subset+// challenge — the parsed 402 body you received ({ x402Version, accepts: [...] })+// payment — your DECODED X-PAYMENT payload (base64-decode it first, or run+// /api/x402/echo to decode it for you)+// response — the error body the server returned ({ error, message, ... })+//+// Returns: { ok, findings: [{ severity, field, problem, fix }], count, ts }+// ok is true only when no `error`-severity finding was raised.++import { wrap, cors, method, json, error, readJson, rateLimited, setRateLimitHeaders } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { diagnoseExchange } from '../_lib/x402/dev-tools.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['POST'])) return;++ const ip = clientIp(req);+ const rl = await limits.x402DevToolIp(ip);+ if (!rl.success) return rateLimited(res, rl);+ setRateLimitHeaders(res, rl);++ let body;+ try {+ body = (await readJson(req)) || {};+ } catch (err) {+ return error(res, 400, 'invalid_json', err.message || 'request body must be valid JSON');+ }++ if (!body || typeof body !== 'object' || Array.isArray(body)) {+ return error(res, 400, 'invalid_body', 'body must be a JSON object with any of { challenge, payment, response }');+ }++ const { findings, ok } = diagnoseExchange({+ challenge: body.challenge,+ payment: body.payment,+ response: body.response,+ });++ return json(res, 200, { ok, findings, count: findings.length, ts: new Date().toISOString() }, {+ 'cache-control': 'no-store',+ });+});diff --git a/api/x402/echo.js b/api/x402/echo.jsnew file mode 100644index 000000000..df6d150db--- /dev/null+++ b/api/x402/echo.js@@ -0,0 +1,99 @@+// POST/GET /api/x402/echo+//+// httpbin for x402 — FREE, keyless. Returns exactly what your request looked+// like from this server's perspective: method, the headers that matter for a+// paid call, and your body. If an X-PAYMENT header is present (or you pass+// `paymentHeader` in the body), it is base64-decoded and echoed back with every+// signature and secret REDACTED to a short prefix, plus the rail's LOCAL+// verification verdict — the same pre-facilitator checks a real paid endpoint+// runs — WITHOUT settling or charging anything. Use it to see why your payload+// is being rejected before you spend a cent.+//+// Body (all optional): { paymentHeader?: string, requirement?: object }+// paymentHeader — a base64 X-PAYMENT value to decode (alternative to the header)+// requirement — one accepts[] entry to check the payment against (amount/payTo)++import { wrap, cors, method, json, error, readJson, rateLimited, setRateLimitHeaders } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { redactPaymentEnvelope, structuralVerdict } from '../_lib/x402/dev-tools.js';+import { decodePaymentHeader } from '../_lib/x402-spec.js';++// Request headers a developer debugging an x402 call cares about. We never echo+// cookies, authorization bearer tokens, or the raw signed X-PAYMENT value.+const RELEVANT_HEADERS = [+ 'content-type',+ 'accept',+ 'user-agent',+ 'x-payment',+ 'payment-signature',+ 'x-provider-key',+ 'x402-version',+];++// Summarize which payment-bearing headers were present (redacted) so a caller+// sees the server received their header without the value being replayable.+function headerView(req) {+ const out = {};+ for (const h of RELEVANT_HEADERS) {+ const v = req.headers?.[h];+ if (v === undefined) continue;+ if (h === 'x-payment' || h === 'payment-signature') {+ const s = String(v);+ out[h] = s.length > 10 ? `${s.slice(0, 10)}…(redacted, ${s.length} chars)` : '(present)';+ } else {+ out[h] = v;+ }+ }+ return out;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const ip = clientIp(req);+ const rl = await limits.x402DevToolIp(ip);+ if (!rl.success) return rateLimited(res, rl);+ setRateLimitHeaders(res, rl);++ let body = {};+ if (req.method === 'POST') {+ try {+ body = (await readJson(req)) || {};+ } catch (err) {+ return error(res, 400, 'invalid_json', err.message || 'request body must be valid JSON');+ }+ }++ const out = {+ ok: true,+ method: req.method,+ headers: headerView(req),+ body: req.method === 'POST' ? body : null,+ ts: new Date().toISOString(),+ };++ // Locate a payment envelope: the real X-PAYMENT header wins; else body.paymentHeader.+ const headerVal = req.headers?.['x-payment'] || req.headers?.['payment-signature'];+ const paymentHeader = headerVal || (typeof body.paymentHeader === 'string' ? body.paymentHeader : null);++ if (paymentHeader) {+ try {+ out.payment = redactPaymentEnvelope(paymentHeader);+ // Local structural verdict — never calls the facilitator, never settles.+ const decoded = decodePaymentHeader(paymentHeader);+ out.payment.verdict = structuralVerdict(decoded, body.requirement);+ out.payment.note =+ 'Local pre-facilitator verdict only — no facilitator round-trip, no settlement, no charge.';+ } catch (err) {+ // A malformed header is the developer's answer, not a server error.+ out.payment = {+ decodable: false,+ error: err.code || 'invalid_payment',+ message: err.message,+ };+ }+ }++ return json(res, 200, out, { 'cache-control': 'no-store' });+});diff --git a/api/x402/verify-receipt.js b/api/x402/verify-receipt.jsnew file mode 100644index 000000000..2ce3d74e2--- /dev/null+++ b/api/x402/verify-receipt.js@@ -0,0 +1,123 @@+// POST/GET /api/x402/verify-receipt+//+// x402 receipt verifier — FREE, keyless. Two independent checks; supply either+// or both, and the response says exactly what was and wasn't verifiable.+//+// 1. Attestation integrity — pass a three.ws paid-response object that carries+// a "sha256:…" attestation (fact-check style). We recompute the digest over+// the fields the scheme commits to and confirm or deny that the object is+// unaltered. No trust in the caller: if a committed field was changed after+// signing, the recomputed digest won't match.+// 2. Settlement confirmation — pass { tx: { hash, network } } and we do a+// read-only on-chain lookup to confirm the settlement transaction exists and+// is confirmed on that chain. RPC unavailable → reported as "unverifiable",+// never a false "confirmed".+//+// Body: { result?: object, tx?: { hash: string, network: string } }+// result.attestation — the "sha256:…" string; result must also carry the+// attested fields (verdict, confidence, claim, sources).+// tx.network — CAIP-2 ("solana:…", "eip155:8453") or shorthand+// ("solana", "base").++import { wrap, cors, method, json, error, readJson, rateLimited, setRateLimitHeaders } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { verifyAttestation } from '../_lib/x402/dev-tools.js';++// Map a network string (CAIP-2 or shorthand) to a chain family + EVM chainId.+function resolveNetwork(network) {+ const n = String(network || '').toLowerCase().trim();+ if (!n) return { family: null };+ if (n.startsWith('solana') || n === 'sol') return { family: 'solana' };+ const caip = n.match(/^eip155:(\d+)$/);+ if (caip) return { family: 'evm', chainId: Number(caip[1]) };+ const alias = { base: 8453, arbitrum: 42161, bsc: 56, xlayer: 196, ethereum: 1 }[n];+ if (alias) return { family: 'evm', chainId: alias };+ return { family: null };+}++// Read-only confirmation that a settlement tx landed on-chain. Never throws —+// returns { verified, status, detail } with verified:false + a reason when the+// chain can't be read (so an outage never reads as "confirmed").+async function confirmSettlementTx(hash, network) {+ const { family, chainId } = resolveNetwork(network);+ if (!family) {+ return { verified: false, status: 'unsupported_network', detail: `network "${network}" is not one we can look up (use solana / eip155:<id>)` };+ }+ if (typeof hash !== 'string' || !hash.trim()) {+ return { verified: false, status: 'invalid_hash', detail: 'tx.hash is required' };+ }++ try {+ if (family === 'solana') {+ const { solanaConnection } = await import('../_lib/solana/connection.js');+ const conn = solanaConnection({ commitment: 'confirmed' });+ const statuses = await conn.getSignatureStatuses([hash.trim()], { searchTransactionHistory: true });+ const st = statuses?.value?.[0];+ if (!st) return { verified: false, status: 'not_found', detail: 'signature not found on Solana mainnet' };+ if (st.err) return { verified: false, status: 'failed', detail: 'transaction failed on-chain', slot: st.slot ?? null };+ const confirmed = st.confirmationStatus === 'confirmed' || st.confirmationStatus === 'finalized';+ return { verified: confirmed, status: st.confirmationStatus || 'processed', detail: confirmed ? 'settlement confirmed on Solana' : 'seen but not yet confirmed', slot: st.slot ?? null };+ }+ // EVM+ const { evmFallbackProvider } = await import('../_lib/evm/rpc.js');+ const provider = await evmFallbackProvider(chainId);+ const receipt = await provider.getTransactionReceipt(hash.trim());+ if (!receipt) return { verified: false, status: 'not_found', detail: `transaction not found on chain ${chainId} (pending or wrong network?)` };+ const ok = Number(receipt.status) === 1;+ return { verified: ok, status: ok ? 'confirmed' : 'reverted', detail: ok ? `settlement confirmed on chain ${chainId}` : 'transaction reverted on-chain', block: receipt.blockNumber ?? null };+ } catch (err) {+ return { verified: false, status: 'rpc_unavailable', detail: `could not reach the chain RPC to confirm: ${err?.message || 'unknown error'}` };+ }+}++async function handle(req, res) {+ const ip = clientIp(req);+ const rl = await limits.x402DevToolIp(ip);+ if (!rl.success) return rateLimited(res, rl);+ setRateLimitHeaders(res, rl);++ let body = {};+ if (req.method === 'POST') {+ try {+ body = (await readJson(req)) || {};+ } catch (err) {+ return error(res, 400, 'invalid_json', err.message || 'request body must be valid JSON');+ }+ }++ const result = body.result;+ const tx = body.tx;+ if (result === undefined && tx === undefined) {+ return error(res, 400, 'nothing_to_verify', 'provide `result` (an attested paid response) and/or `tx` ({ hash, network })', {+ example: { result: { verdict: 'true', confidence: 0.9, claim: '…', sources: ['https://…'], attestation: 'sha256:…' }, tx: { hash: '…', network: 'solana' } },+ });+ }++ const out = { ok: true, ts: new Date().toISOString() };++ if (result !== undefined) {+ if (!result || typeof result !== 'object') {+ out.attestation = { verified: false, mismatchReason: 'result must be a JSON object carrying the attested fields' };+ } else {+ out.attestation = verifyAttestation(result);+ }+ }++ if (tx !== undefined) {+ if (!tx || typeof tx !== 'object') {+ out.settlement = { verified: false, status: 'invalid_tx', detail: 'tx must be an object { hash, network }' };+ } else {+ out.settlement = await confirmSettlementTx(tx.hash, tx.network);+ }+ }++ // Top-level ok reflects that we RAN the checks, not that they passed — each+ // sub-result carries its own verified flag so a caller reads outcomes precisely.+ return json(res, 200, out, { 'cache-control': 'no-store' });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;+ return handle(req, res);+});diff --git a/data/changelog.json b/data/changelog.jsonindex 843380607..c72cdc591 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-07",+ "title": "Free x402 developer toolkit — echo, debug, and verify a receipt against a live server",+ "summary": "Building an x402 integration against three.ws just got easier. Three new free, keyless tools: echo shows you exactly what the server sees when you send a payment — the decoded envelope with every signature redacted, plus a local valid/invalid verdict without charging you. debug turns a failed 402 exchange into an ordered fix list keyed to the real reasons a payment gets rejected (wrong version, shorthand network, decimal amounts, underpayment). verify-receipt recomputes a paid response's SHA-256 attestation to prove it wasn't altered, and confirms a settlement transaction on-chain. A new docs page ties all six developer tools together.",+ "tags": [+ "feature",+ "docs"+ ],+ "link": "/docs/x402-dev-tools"+ },{"date": "2026-07-07","title": "Give your assistant a living 3D body that lip-syncs and emotes in the chat",diff --git a/data/pages.json b/data/pages.jsonindex 44866568f..f5c003d4c 100644--- a/data/pages.json+++ b/data/pages.json@@ -1658,6 +1658,12 @@"description": "Deploy a brand-new pump.fun token in one paid call — no SOL, no wallet, no account. Inputs, outputs, pricing, correctness guarantees, and the free symbol-check → launch → launch-feed funnel.","added": "2026-07-07"},+ {+ "path": "/docs/x402-dev-tools",+ "title": "Docs · x402 Developer Tools",+ "description": "A free test bench for x402 developers — echo your payment envelope, debug a failed 402 exchange, and verify a receipt's attestation and settlement against a live server, all without spending anything.",+ "added": "2026-07-07"+ },{"path": "/docs/x402-buyer","title": "Docs · x402 Buyer Client",diff --git a/docs/start-here.md b/docs/start-here.mdindex b80fcf080..4a98e058d 100644--- a/docs/start-here.md+++ b/docs/start-here.md@@ -69,6 +69,7 @@ If you're here to create and share agents rather than write code, follow this pa- **Trading?** → [The trading surfaces](./trading-surfaces.md) maps the solo stack (Radar, Coin Intelligence, Live Trade Feed, Watchlist, Mission Control); [trading arenas](./trading-arenas.md) covers tournaments, the theater, vaults, and swarms; [Oracle](./oracle.md) is the conviction engine underneath all of it- **Trusting an agent with money?** → [Custody you can verify](./custody.md) — spend limits, freeze, Merkle proof-of-custody, and social recovery; [claim your wallet](./trader-card.md) turns any pump.fun track record into a public, provable Trader Card. Every real-funds feature sits behind the [risk acknowledgment](./risk-acknowledgment.md) — read the [Risk Disclosure](https://three.ws/legal/risk) before committing anything- **Vetting a counterparty before you pay it?** → [Trust primitives](./trust-primitives.md) — the cross-chain Agent Reputation endpoint scores ANY wallet, mint, or agent id (Solana or EVM) 0–100 from real on-chain evidence, in one paid call, before your agent transacts+- **Debugging an x402 integration?** → [x402 developer tools](./x402-dev-tools.md) — a free test bench: echo your payment envelope (signatures redacted), debug a failed 402 exchange into an ordered fix list, and verify a receipt's attestation and on-chain settlement, all against a live server without spending anything- **Want a branded on-chain address?** → [Vanity grinder](./vanity.md) — grind a Solana address that starts with your ticker (branded token mint or agent/treasury wallet) in one paid USDC call; keypair or importable mnemonic, nothing stored, optional sealed delivery, plus a provably-fair variant and a pre-ground premium inventory- **Going Pro?** → [Paid plans](./plan-checkout.md) — upgrade with a single on-chain payment in USDC, SOL, or $THREE (the platform coin takes 20% off); [hold-to-access](./hold-to-access.md) covers the separate hold-$THREE tier ladder- **Developer docs** → Read the [Introduction](./introduction.md) for the full technical picturediff --git a/docs/x402-dev-tools.md b/docs/x402-dev-tools.mdnew file mode 100644index 000000000..63f275b13--- /dev/null+++ b/docs/x402-dev-tools.md@@ -0,0 +1,187 @@+# x402 Developer Tools++A free test bench for building and debugging x402 integrations against a live+server. Six tools — three new free diagnostics plus three pre-existing probe+endpoints — that let you inspect what the server sees, understand why a payment+was rejected, and confirm a receipt, all without spending anything.++Every tool here is **free and keyless** except the two paid probes noted below.+The three new diagnostic tools are rate-limited to **30 requests/minute per IP**.++Base URL: `https://three.ws`++---++## The three free diagnostics++### 1. Echo — `POST /api/x402/echo`++httpbin for x402. Returns exactly what your request looked like from the+server's perspective: method, the headers that matter for a paid call, and your+body. If an `X-PAYMENT` header is present (or you pass `paymentHeader` in the+body), it is base64-decoded and echoed back with **every signature and secret+redacted to a short prefix**, plus the rail's local verification verdict — the+same pre-facilitator checks a real paid endpoint runs — **without settling or+charging anything**.++Pass a `requirement` (one `accepts[]` entry) to have the verdict check your+signed amount and recipient against it:++```bash+curl -s https://three.ws/api/x402/echo \+ -H 'content-type: application/json' \+ -d '{+ "paymentHeader": "<base64 X-PAYMENT value>",+ "requirement": { "amount": "10000", "payTo": "0x…", "network": "eip155:8453" }+ }'+```++Response (abridged):++```json+{+ "ok": true,+ "method": "POST",+ "headers": { "x-payment": "eyJ4NDAyVm…(redacted, 512 chars)" },+ "payment": {+ "x402Version": 2,+ "scheme": "exact",+ "network": "eip155:8453",+ "signedAmount": "10000",+ "signedRecipient": "0x75d0…cf69",+ "envelope": { "payload": { "signature": "0xdededede…(redacted, 132 chars)" } },+ "verdict": { "valid": true, "checks": [ … ] },+ "note": "Local pre-facilitator verdict only — no facilitator round-trip, no settlement, no charge."+ }+}+```++You can also send the payment as a real `X-PAYMENT` header instead of in the+body — the header wins when both are present. The full signature is never+returned; only a prefix, so the echo is safe to paste into a bug report.++### 2. Debug — `POST /api/x402/debug`++Paste any subset of a failed exchange and get a structured diagnosis keyed to+the failure modes this server's rail actually produces. Each finding is+`{ severity, field, problem, fix }`, ordered most-severe first.++```bash+curl -s https://three.ws/api/x402/debug \+ -H 'content-type: application/json' \+ -d '{+ "challenge": { "x402Version": 2, "accepts": [{ "scheme": "exact", "network": "eip155:8453", "amount": "10000", "payTo": "0x…" }] },+ "payment": { "x402Version": 1, "network": "base", "payload": { "authorization": { "value": "0.01", "to": "0x…" } } },+ "response": { "error": "invalid_payment" }+ }'+```++Response:++```json+{+ "ok": false,+ "count": 4,+ "findings": [+ { "severity": "error", "field": "payment.x402Version", "problem": "payment declares x402Version 1; server requires 2", "fix": "Set x402Version: 2." },+ { "severity": "error", "field": "payment.network", "problem": "network \"base\" is a shorthand, not the CAIP-2 id the rail matches on", "fix": "Use \"eip155:8453\"." },+ { "severity": "error", "field": "payment.authorization.value", "problem": "value \"0.01\" contains a decimal point", "fix": "Authorization value is atomic units as an integer string (\"10000\"), not a decimal token amount." },+ { "severity": "info", "field": "response.error", "problem": "server returned \"invalid_payment\"", "fix": "The payload was structurally valid but failed a check — usually underpayment, wrong payTo, or a malformed authorization. Run /api/x402/echo on your header to see the decoded amount/recipient." }+ ]+}+```++Common footguns it catches: wrong `x402Version`, shorthand instead of CAIP-2+network ids, signing for a network the challenge doesn't offer, decimal amounts+where atomic-unit integer strings are required, underpayment, and a missing+`accepts[]` array.++### 3. Verify receipt — `POST /api/x402/verify-receipt`++Two independent checks; supply either or both. The response says exactly what+was and wasn't verifiable.++**Attestation integrity** — pass a three.ws paid response carrying a+`sha256:…` attestation (e.g. from [`/api/x402/fact-check`](./x402-endpoints.md)).+The digest is recomputed over the committed fields; if any was altered after+signing, the recomputed digest won't match.++```bash+curl -s https://three.ws/api/x402/verify-receipt \+ -H 'content-type: application/json' \+ -d '{ "result": { "verdict": "true", "confidence": 0.92, "claim": "…", "sources": ["https://…"], "attestation": "sha256:…" } }'+```++```json+{ "ok": true, "attestation": { "verified": true, "scheme": "sha256", "recomputed": "sha256:…", "claimed": "sha256:…" } }+```++**Settlement confirmation** — pass `{ tx: { hash, network } }` for a read-only+on-chain lookup confirming the settlement transaction exists and is confirmed.+`network` is CAIP-2 (`solana:…`, `eip155:8453`) or shorthand (`solana`, `base`).+An unreachable RPC is reported as `status: "rpc_unavailable"`, never a false+`confirmed`.++```bash+curl -s https://three.ws/api/x402/verify-receipt \+ -H 'content-type: application/json' \+ -d '{ "tx": { "hash": "<signature or txhash>", "network": "solana" } }'+```++```json+{ "ok": true, "settlement": { "verified": true, "status": "confirmed", "detail": "settlement confirmed on Solana", "slot": 301234567 } }+```++---++## The three probe endpoints++These already existed; the docs are consolidated here.++### Schema check — `POST /api/x402/schema-check` *(paid, $0.001 USDC)*++Fetches a named three.ws public JSON API and validates its response against the+declared schema, so a breaking change surfaces before consumers notice. Current+target: `changelog_json` (the `/changelog.json` feed).++```bash+# Requires an x402 payment; see docs/x402-buyer.md for the buyer flow.+curl -s https://three.ws/api/x402/schema-check -d '{ "api": "changelog_json" }'+```++### Rate-limit probe — `POST /api/x402/rate-limit-probe` *(paid, $0.001 USDC)*++Returns how many more calls the x402 autonomous loop can make to a target+endpoint today before hitting its daily USDC spend cap — `remaining_calls`,+`reset_at`, and `cooldown_active` — so an agent can throttle before it fails.++```bash+curl -s https://three.ws/api/x402/rate-limit-probe -d '{ "endpoint": "/api/x402/forge" }'+```++### Permit2 paid demo — `GET /api/x402/permit2-paid-demo` *(paid)*++A target that advertises **only** the Permit2 + EIP-2612 gas-sponsoring accept+(no EIP-3009 fallback), so you can prove a wallet with USDC but zero native gas+can pay end-to-end through the gasless path. Use it to test a Permit2 client+implementation against a live server.++---++## Typical debugging loop++1. Your paid call fails. Copy the base64 `X-PAYMENT` header you sent.+2. `POST /api/x402/echo` with it → see the decoded amount, recipient, and the+ local verdict. If the verdict is invalid, the `reason` tells you which check+ failed.+3. Still unclear? `POST /api/x402/debug` with `{ challenge, payment, response }`+ → get an ordered fix list.+4. After a successful call, `POST /api/x402/verify-receipt` to confirm the+ attestation and settlement.++## Related++- [x402 Protocol](./x402.md) — the challenge / verify / settle mechanics.+- [x402 Paid Endpoints](./x402-endpoints.md) — the full catalog and pricing.+- [x402 Buyer Client](./x402-buyer.md) — how to settle a challenge from code.+- [x402 Revenue & Receipts](./x402-revenue.md) — how signed receipts are recorded.diff --git a/docs/x402-endpoints.md b/docs/x402-endpoints.mdindex f0bd09026..a5afade79 100644--- a/docs/x402-endpoints.md+++ b/docs/x402-endpoints.md@@ -154,6 +154,7 @@ for to feed the oracle and sniper.| `/api/x402/notify` | $0.001 | Notification gateway (Telegram + the autonomous loop's `canary` heartbeat lane). || `/api/x402/wallet-connect` | $0.001 | Wallet-bridge connect probe. || `/api/x402/permit2-paid-demo` | $0.001 | Reference endpoint for the Permit2 / EIP-2612 gasless-approval scheme. |+| `/api/x402/remix-asset` | $0.25 | Paid remix of a published, remixable 3D asset — generates a new anchored model and routes the source creator's royalty (≤20%) on-chain. || `/api/x402/cross-chain`, `/api/x402/network-cost` | per call | Cross-chain cost comparison. || `/api/x402/rate-limit-probe`, `/api/x402/schema-check` | $0.001 | Paid diagnostic probes used by the autonomous loop. || `/api/x402/auth-health`, `/api/x402/api-key-health`, `/api/x402/feed-health`, `/api/x402/granite-health`, `/api/x402/telegram-health`, `/api/x402/solana-register-health` | $0.001 | Paid SLA/health probes for each backend dependency (auth, API keys, the live feed, IBM Granite, Telegram, Solana register). |@@ -182,6 +183,9 @@ directory.| `/api/x402/my-receipts` | free | A buyer's own settled receipts, gated by a wallet signature (SIWX) rather than a payment. || `/api/x402/mcp-perf` | free | MCP tool latency dashboard data. || `/api/x402/service-pricing-report` | free | Tracked upstream-dependency price catalog + active price-increase/-drop alerts. |+| `/api/x402/echo` | free | httpbin for x402 — decodes your `X-PAYMENT` header (signatures redacted) and returns a local verify verdict without settling. See [x402 dev tools](x402-dev-tools.md). |+| `/api/x402/debug` | free | Diagnoses a failed 402 exchange (`{challenge, payment, response}`) into an ordered `{severity, field, problem, fix}` list. See [x402 dev tools](x402-dev-tools.md). |+| `/api/x402/verify-receipt` | free | Recomputes a paid response's SHA-256 attestation and confirms a settlement tx on-chain. See [x402 dev tools](x402-dev-tools.md). |## $THREE onlydiff --git a/public/changelog.json b/public/changelog.jsonindex 54a33d344..5f3f2fe5d 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-07T12:18:42.073Z",+ "generated_at": "2026-07-07T13:43:23.851Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -56,6 +56,16 @@"launch"]},+ {+ "date": "2026-07-07",+ "type": "launch",+ "title": "Docs · x402 Developer Tools",+ "summary": "A free test bench for x402 developers — echo your payment envelope, debug a failed 402 exchange, and verify a receipt's attestation and settlement against a live server, all without spending anything.",+ "link": "/docs/x402-dev-tools",+ "tags": [+ "launch"+ ]+ },{"date": "2026-07-07","type": "update",@@ -244,6 +254,17 @@"feature"]},+ {+ "date": "2026-07-07",+ "type": "update",+ "title": "Free x402 developer toolkit — echo, debug, and verify a receipt against a live server",+ "summary": "Building an x402 integration against three.ws just got easier. Three new free, keyless tools: echo shows you exactly what the server sees when you send a payment — the decoded envelope with every signature redacted, plus a local valid/invalid verdict without charging you. debug turns a failed 402 exchange into an ordered fix list keyed to the real reasons a payment gets rejected (wrong version, shorthand network, decimal amounts, underpayment). verify-receipt recomputes a paid response's SHA-256 attestation to prove it wasn't altered, and confirms a settlement transaction on-chain. A new docs page ties all six developer tools together.",+ "link": "/docs/x402-dev-tools",+ "tags": [+ "feature",+ "docs"+ ]+ },{"date": "2026-07-07","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 765409ba1..c6430d86e 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -46,6 +46,14 @@<category>launch</category><description>Cross-chain Agent Reputation — score any wallet, mint, or agent id (Solana or EVM) 0–100 from real on-chain evidence before your agent pays, trades, or delegates.</description></item>+ <item>+ <title>Docs · x402 Developer Tools</title>+ <link>https://three.ws/docs/x402-dev-tools</link>+ <guid isPermaLink="false">2026-07-07:Docs · x402 Developer Tools</guid>+ <pubDate>Tue, 07 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>A free test bench for x402 developers — echo your payment envelope, debug a failed 402 exchange, and verify a receipt's attestation and settlement against a live server, all without spending anything.</description>+ </item><item><title>3D model inspection is now free</title><link>https://three.ws/changelog</link>@@ -190,6 +198,14 @@<category>feature</category><description>A new free, keyless endpoint tells an AI agent whether big money is moving before it trades. Call /api/crypto/whales with a token mint to see the large buys of that coin, or without one to see the top whale wallets active across pump.fun right now. Each response carries a plain bullish/bearish/neutral signal derived from net whale flow — the SOL whales bought minus the SOL they sold — with no black-box scoring. No account, no key, no payment.</description></item>+ <item>+ <title>Free x402 developer toolkit — echo, debug, and verify a receipt against a live server</title>+ <link>https://three.ws/docs/x402-dev-tools</link>+ <guid isPermaLink="false">2026-07-07:Free x402 developer toolkit — echo, debug, and verify a receipt against a live server</guid>+ <pubDate>Tue, 07 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Building an x402 integration against three.ws just got easier. Three new free, keyless tools: echo shows you exactly what the server sees when you send a payment — the decoded envelope with every signature redacted, plus a local valid/invalid verdict without charging you. debug turns a failed 402 exchange into an ordered fix list keyed to the real reasons a payment gets rejected (wrong version, shorthand network, decimal amounts, underpayment). verify-receipt recomputes a paid response's SHA-256 attestation to prove it wasn't altered, and confirms a settlement transaction on-chain. A new docs page ties all six developer tools together.</description>+ </item><item><title>Give your assistant a living 3D body that lip-syncs and emotes in the chat</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex 8c60c3550..6c3ed9707 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-07T12:18:42.059Z",+ "generated_at": "2026-07-07T13:43:23.839Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -2037,6 +2037,16 @@"tags": [],"showcase": false},+ {+ "path": "/docs/x402-dev-tools",+ "title": "Docs · x402 Developer Tools",+ "description": "A free test bench for x402 developers — echo your payment envelope, debug a failed 402 exchange, and verify a receipt's attestation and settlement against a live server, all without spending anything.",+ "added": "2026-07-07",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/docs/x402-buyer","title": "Docs · x402 Buyer Client",diff --git a/public/llms-full.txt b/public/llms-full.txtindex a98784d88..582d6727d 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -1246,6 +1246,12 @@ URL: https://three.ws/docs/pump-launcherDeploy a brand-new pump.fun token in one paid call — no SOL, no wallet, no account. Inputs, outputs, pricing, correctness guarantees, and the free symbol-check → launch → launch-feed funnel.+### Docs · x402 Developer Tools++URL: https://three.ws/docs/x402-dev-tools++A free test bench for x402 developers — echo your payment envelope, debug a failed 402 exchange, and verify a receipt's attestation and settlement against a live server, all without spending anything.+### Docs · x402 Buyer ClientURL: https://three.ws/docs/x402-buyerdiff --git a/public/llms.txt b/public/llms.txtindex 871d0ca36..a5afb756c 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -228,6 +228,7 @@ Docs, tutorials, and reference.- [Docs · x402 Paid Endpoints](https://three.ws/docs/x402-endpoints): The catalog of three.ws's own paid HTTP endpoints — what each charges, the price-override scheme, and what it returns.- [Docs · x402 Revenue & Receipts](https://three.ws/docs/x402-revenue): Where settled x402 payments are recorded (x402_audit_log), how to read endpoint revenue, and how signed receipts work.- [Docs · Pump Launcher](https://three.ws/docs/pump-launcher): Deploy a brand-new pump.fun token in one paid call — no SOL, no wallet, no account. Inputs, outputs, pricing, correctness guarantees, and the free symbol-check → launch → launch-feed funnel.+- [Docs · x402 Developer Tools](https://three.ws/docs/x402-dev-tools): A free test bench for x402 developers — echo your payment envelope, debug a failed 402 exchange, and verify a receipt's attestation and settlement against a live server, all without spending anything.- [Docs · x402 Buyer Client](https://three.ws/docs/x402-buyer): How to settle a 402 challenge and pay three.ws's paid endpoints from code.- [Docs · Autonomous x402 Loop](https://three.ws/docs/autonomous-x402): The scheduled buyer that pays x402 endpoints on a cadence to feed the oracle and sniper — real USDC, real settlements.- [Docs · Circulation Engine](https://three.ws/docs/circulation-engine): The autonomous agent-to-agent activity loop — a pool of real platform agents tipping, paying, trading, and launching with one another.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 81786db2d..53c694f93 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 387 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 388 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 387 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 388 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -1410,7 +1410,7 @@<section class="sm-section" id="learn"><header>- <h2>Learn<span class="sm-count" data-count>58</span></h2>+ <h2>Learn<span class="sm-count" data-count>59</span></h2><p class="sm-section-desc">Docs, tutorials, and reference.</p></header><ul class="sm-list">@@ -1540,6 +1540,13 @@<span class="sm-desc">Deploy a brand-new pump.fun token in one paid call — no SOL, no wallet, no account. Inputs, outputs, pricing, correctness guarantees, and the free symbol-check → launch → launch-feed funnel.</span></a></li>+ <li>+ <a href="/docs/x402-dev-tools">+ <span class="sm-title">Docs · x402 Developer Tools</span>+ <span class="sm-path">/docs/x402-dev-tools</span>+ <span class="sm-desc">A free test bench for x402 developers — echo your payment envelope, debug a failed 402 exchange, and verify a receipt's attestation and settlement against a live server, all without spending anything.</span>+ </a>+ </li><li><a href="/docs/x402-buyer"><span class="sm-title">Docs · x402 Buyer Client</span>diff --git a/tests/api/x402-dev-toolkit.test.js b/tests/api/x402-dev-toolkit.test.jsnew file mode 100644index 000000000..c8289a3ac--- /dev/null+++ b/tests/api/x402-dev-toolkit.test.js@@ -0,0 +1,326 @@+// Tests for the free x402 developer toolkit — echo, debug, verify-receipt+// (api/x402/{echo,debug,verify-receipt}.js + api/_lib/x402/dev-tools.js).+//+// The pure core (redaction, structural verdict, diagnosis, attestation) is+// exercised directly. Handler tests drive the default exports with mock req/res.+// Malformed exchanges are generated by encoding real payment envelopes the wrong+// way (wrong version, shorthand network, decimal amount) — no captured mocks.+//+// Addresses/mints are three.ws's own (owner wallet, $THREE) or synthetic.++import { describe, it, expect } from 'vitest';+import { Readable } from 'node:stream';+import { createHash } from 'crypto';++import echoHandler from '../../api/x402/echo.js';+import debugHandler from '../../api/x402/debug.js';+import verifyHandler from '../../api/x402/verify-receipt.js';+import {+ redactSecrets,+ redactPaymentEnvelope,+ structuralVerdict,+ diagnoseExchange,+ recomputeAttestation,+ verifyAttestation,+} from '../../api/_lib/x402/dev-tools.js';+import { decodePaymentHeader } from '../../api/_lib/x402-spec.js';++// ── Fixtures ────────────────────────────────────────────────────────────────+const PAY_TO = '0x75d00a2713565171f33216e5aa2a375e076ecf69'; // three.ws owner wallet+const FULL_SIG = '0x' + 'de'.repeat(65); // 132-char fake signature++function eip3009Envelope({ value = '10000', to = PAY_TO, version = 2, network = 'eip155:8453' } = {}) {+ return {+ x402Version: version,+ scheme: 'exact',+ network,+ payload: {+ authorization: {+ from: '0xAAA1111111111111111111111111111111111111',+ to,+ value,+ validAfter: '0',+ validBefore: '9999999999',+ nonce: '0x' + 'ab'.repeat(32),+ },+ signature: FULL_SIG,+ },+ };+}++function encodeHeader(envelope) {+ return Buffer.from(JSON.stringify(envelope)).toString('base64');+}++function factCheckResult(overrides = {}) {+ const result = {+ verdict: 'true',+ confidence: 0.92,+ claim: 'the sky is blue',+ strictness: 'normal',+ sources: [{ url: 'https://a.example' }, { url: 'https://b.example' }],+ ...overrides,+ };+ // Attestation computed EXACTLY as api/x402/fact-check.js does.+ result.attestation =+ 'sha256:' ++ createHash('sha256')+ .update(+ JSON.stringify({+ verdict: result.verdict,+ confidence: result.confidence,+ claim: result.claim,+ sources: result.sources.map((s) => s.url),+ }),+ )+ .digest('hex');+ return result;+}++// ── req/res mocks ─────────────────────────────────────────────────────────+function makeReq({ method = 'POST', url = '/api/x402/echo', headers = {}, body = null } = {}) {+ const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);+ base.method = method;+ base.url = url;+ base.headers = { host: 'localhost', ...(body ? { 'content-type': 'application/json' } : {}), ...headers };+ base.socket = { remoteAddress: '203.0.113.9' };+ return base;+}++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; this.headersSent = true; },+ };+}++async function invoke(handler, reqOpts) {+ const req = makeReq(reqOpts);+ const res = makeRes();+ await handler(req, res);+ return { res, status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };+}++// ── Pure: redaction ───────────────────────────────────────────────────────+describe('redactSecrets / redactPaymentEnvelope', () => {+ it('redacts signature fields to a short prefix, never the full value', () => {+ const out = redactSecrets({ signature: FULL_SIG, value: '10000' });+ expect(out.signature).toContain('redacted');+ expect(out.signature).not.toContain('de'.repeat(65));+ expect(out.value).toBe('10000'); // non-secret preserved+ });++ it('redacts secret-looking keys regardless of nesting', () => {+ const out = redactSecrets({ a: { b: { privateKey: 'abcdef0123456789', passphrase: 'hunter2hunter2' } } });+ expect(out.a.b.privateKey).toContain('redacted');+ expect(out.a.b.passphrase).toContain('redacted');+ });++ it('decodes an X-PAYMENT header and never leaks the full signature', () => {+ const view = redactPaymentEnvelope(encodeHeader(eip3009Envelope()));+ expect(view.x402Version).toBe(2);+ expect(view.scheme).toBe('exact');+ expect(view.signedAmount).toBe('10000');+ expect(view.signedRecipient).toBe(PAY_TO.toLowerCase());+ expect(JSON.stringify(view)).not.toContain('de'.repeat(65));+ });++ it('throws on a structurally invalid header', () => {+ expect(() => redactPaymentEnvelope('not-base64-!!!')).toThrow();+ expect(() => redactPaymentEnvelope(Buffer.from('not json').toString('base64'))).toThrow();+ });+});++// ── Pure: structural verdict ────────────────────────────────────────────────+describe('structuralVerdict', () => {+ const decoded = () => decodePaymentHeader(encodeHeader(eip3009Envelope()));++ it('passes an exact-match payment against its requirement', () => {+ const v = structuralVerdict(decoded(), { scheme: 'exact', network: 'eip155:8453', amount: '10000', payTo: PAY_TO });+ expect(v.valid).toBe(true);+ });++ it('fails an underpayment', () => {+ const v = structuralVerdict(decoded(), { amount: '20000', payTo: PAY_TO, network: 'eip155:8453' });+ expect(v.valid).toBe(false);+ expect(v.reason).toMatch(/underpayment/);+ });++ it('fails a recipient mismatch', () => {+ const v = structuralVerdict(decoded(), { amount: '10000', payTo: '0x0000000000000000000000000000000000000001', network: 'eip155:8453' });+ expect(v.valid).toBe(false);+ expect(v.reason).toMatch(/recipient/);+ });++ it('flags a wrong x402Version even with no requirement', () => {+ const v = structuralVerdict(decodePaymentHeader(encodeHeader(eip3009Envelope({ version: 1 }))));+ expect(v.valid).toBe(false);+ expect(v.checks.find((c) => c.field === 'x402Version').pass).toBe(false);+ });+});++// ── Pure: diagnosis matrix ──────────────────────────────────────────────────+describe('diagnoseExchange', () => {+ it('returns an error when nothing is supplied', () => {+ const { findings, ok } = diagnoseExchange({});+ expect(ok).toBe(false);+ expect(findings[0].field).toBe('input');+ });++ it('catches version, shorthand-network, offered-network, and decimal footguns at once', () => {+ const { findings } = diagnoseExchange({+ challenge: { x402Version: 2, accepts: [{ scheme: 'exact', network: 'eip155:8453', amount: '10000', payTo: PAY_TO }] },+ payment: { x402Version: 1, network: 'base', payload: { authorization: { value: '0.01', to: PAY_TO } } },+ response: { error: 'invalid_payment' },+ });+ const fields = findings.map((f) => `${f.severity}:${f.field}`);+ expect(fields).toContain('error:payment.x402Version');+ expect(fields).toContain('error:payment.network'); // shorthand + offered mismatch+ expect(fields).toContain('error:payment.authorization.value'); // decimal+ expect(fields).toContain('info:response.error'); // maps the rail error code+ // errors sort ahead of info+ expect(findings[0].severity).toBe('error');+ });++ it('flags a decimal atomic amount in the challenge itself', () => {+ const { findings } = diagnoseExchange({+ challenge: { x402Version: 2, accepts: [{ scheme: 'exact', network: 'eip155:8453', amount: '0.01', payTo: PAY_TO }] },+ });+ expect(findings.some((f) => f.field.includes('accepts[0].amount'))).toBe(true);+ });++ it('reports a clean exchange as ok', () => {+ const { ok } = diagnoseExchange({+ challenge: { x402Version: 2, accepts: [{ scheme: 'exact', network: 'eip155:8453', amount: '10000', payTo: PAY_TO }] },+ payment: eip3009Envelope(),+ });+ expect(ok).toBe(true);+ });+});++// ── Pure: attestation ───────────────────────────────────────────────────────+describe('verifyAttestation', () => {+ it('confirms an untampered fact-check attestation (matches the real scheme)', () => {+ const result = factCheckResult();+ expect(recomputeAttestation(result)).toBe(result.attestation);+ expect(verifyAttestation(result).verified).toBe(true);+ });++ it('denies a tampered result', () => {+ const result = factCheckResult();+ const tampered = { ...result, verdict: 'false' }; // attestation unchanged+ expect(verifyAttestation(tampered).verified).toBe(false);+ expect(verifyAttestation(tampered).mismatchReason).toMatch(/altered/);+ });++ it('reports partial when the attested fields are missing', () => {+ const r = verifyAttestation({ attestation: 'sha256:deadbeef' });+ expect(r.verified).toBe(false);+ expect(r.mismatchReason).toMatch(/missing/);+ });++ it('reports absent when no attestation string is present', () => {+ const r = verifyAttestation({ verdict: 'true' });+ expect(r.verified).toBe(false);+ expect(r.mismatchReason).toMatch(/no sha256/);+ });+});++// ── Handler: echo ───────────────────────────────────────────────────────────+describe('POST /api/x402/echo', () => {+ it('reflects the request and decodes+redacts an X-PAYMENT header', async () => {+ const header = encodeHeader(eip3009Envelope());+ const { status, body } = await invoke(echoHandler, {+ url: '/api/x402/echo',+ headers: { 'x-payment': header },+ body: { requirement: { amount: '10000', payTo: PAY_TO, network: 'eip155:8453' } },+ });+ expect(status).toBe(200);+ expect(body.method).toBe('POST');+ // header echoed but redacted+ expect(body.headers['x-payment']).toContain('redacted');+ // decoded envelope + local verdict, no full signature anywhere+ expect(body.payment.verdict.valid).toBe(true);+ expect(JSON.stringify(body)).not.toContain('de'.repeat(65));+ expect(body.payment.note).toMatch(/no settlement/i);+ });++ it('accepts paymentHeader in the body and reports a malformed one as decodable:false', async () => {+ const { status, body } = await invoke(echoHandler, {+ body: { paymentHeader: Buffer.from('not json').toString('base64') },+ });+ expect(status).toBe(200);+ expect(body.payment.decodable).toBe(false);+ });++ it('works as a bare GET with no payment', async () => {+ const { status, body } = await invoke(echoHandler, { method: 'GET' });+ expect(status).toBe(200);+ expect(body.payment).toBeUndefined();+ });+});++// ── Handler: debug ──────────────────────────────────────────────────────────+describe('POST /api/x402/debug', () => {+ it('diagnoses a broken exchange with fix guidance', async () => {+ const { status, body } = await invoke(debugHandler, {+ url: '/api/x402/debug',+ body: {+ challenge: { x402Version: 2, accepts: [{ scheme: 'exact', network: 'eip155:8453', amount: '10000', payTo: PAY_TO }] },+ payment: { x402Version: 1, network: 'base', payload: { authorization: { value: '0.01', to: PAY_TO } } },+ },+ });+ expect(status).toBe(200);+ expect(body.ok).toBe(false);+ expect(body.count).toBeGreaterThan(0);+ expect(body.findings.every((f) => f.fix && f.problem)).toBe(true);+ });++ it('rejects a GET', async () => {+ const { status } = await invoke(debugHandler, { method: 'GET', url: '/api/x402/debug' });+ expect(status).toBe(405);+ });+});++// ── Handler: verify-receipt ─────────────────────────────────────────────────+describe('POST /api/x402/verify-receipt', () => {+ it('confirms a valid attestation', async () => {+ const { status, body } = await invoke(verifyHandler, {+ url: '/api/x402/verify-receipt',+ body: { result: factCheckResult() },+ });+ expect(status).toBe(200);+ expect(body.attestation.verified).toBe(true);+ });++ it('denies a tampered attestation', async () => {+ const result = factCheckResult();+ const { body } = await invoke(verifyHandler, {+ url: '/api/x402/verify-receipt',+ body: { result: { ...result, confidence: 0.1 } },+ });+ expect(body.attestation.verified).toBe(false);+ });++ it('400s when nothing to verify', async () => {+ const { status, body } = await invoke(verifyHandler, { url: '/api/x402/verify-receipt', body: {} });+ expect(status).toBe(400);+ expect(body.error).toBe('nothing_to_verify');+ });++ it('reports an unsupported settlement network without throwing', async () => {+ const { status, body } = await invoke(verifyHandler, {+ url: '/api/x402/verify-receipt',+ body: { tx: { hash: 'abc', network: 'dogechain' } },+ });+ expect(status).toBe(200);+ expect(body.settlement.verified).toBe(false);+ expect(body.settlement.status).toBe('unsupported_network');+ });+});