Skip to content

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.

feat(x402): answer and pay MPP Payment challenges on Solana beside x402 on the same URL

nirholasc28db0aaf3c5
diff --git a/STRUCTURE.md b/STRUCTURE.md
index f966096f2..c76852319 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -299,6 +299,7 @@ packages, a generated standalone GitHub mirror). See
| Cross-chain SDKs | [sdk/](sdk), [solana-agent-sdk/](solana-agent-sdk), [agent-payments-sdk/](agent-payments-sdk), [agent-protocol-sdk/](agent-protocol-sdk) | Published | Cross-chain agent SDKs |
| MCP integration | [mcp-server/](mcp-server), [mcp-bridge/](mcp-bridge), [packages/*-mcp/](packages) | <!-- mcp-count:stdio.servers -->41<!-- /mcp-count --> npm servers + <!-- mcp-count:hosted.servers -->10<!-- /mcp-count --> hosted remote (<!-- mcp-count:all.servers -->51<!-- /mcp-count --> total, incl. the free `/api/mcp-studio` 3D Studio, whose ChatGPT plugin surface [api/mcp-chatgpt.js](api/mcp-chatgpt.js) `→ /api/mcp-chatgpt` serves the eight 3D tools and the model viewer without the persona tools or any `frameDomains`, and [api/mcp-grok.js](api/mcp-grok.js) `→ /api/mcp-grok` serves every studio tool with no widget templates plus, for a caller signed in with OAuth 2.1 or a connector key, the account's agent tools from the core server through [api/_mcp-studio/account-tools.js](api/_mcp-studio/account-tools.js), never a value-moving one ([tests/mcp-grok-accounts.test.js](tests/mcp-grok-accounts.test.js)); all three doors share [api/_mcp-studio/handler.js](api/_mcp-studio/handler.js), and `SURFACES` in [api/_mcp-studio/dispatch.js](api/_mcp-studio/dispatch.js) defines what each advertises), all in the [MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas). Canonical metadata: [prompts/store-submissions/_generated/mcp-listing-source.json](prompts/store-submissions/_generated/mcp-listing-source.json), generated from the manifests by [scripts/build-mcp-listing-source.mjs](scripts/build-mcp-listing-source.mjs) (`npm run audit:mcp-listing` fails when it drifts) | Model Context Protocol surface, full server list in [docs/mcp.md](docs/mcp.md). One-click client setup: [pages/connect.html](pages/connect.html) `→ /connect` (Claude, Cursor and VS Code install links plus ChatGPT, Grok Bot, Claude Code and generic steps; the Grok Bot tab is the shared connector card [src/grok-connector.js](src/grok-connector.js), also mounted on the Grok landing page [pages/grok.html](pages/grok.html) `→ /grok` ([src/grok-page.js](src/grok-page.js): capabilities, a live strip of recent gallery creations, an in-page MCP demo against `/api/mcp-grok`, three scheduled recipes, the skill file); /connect is built live from [public/.well-known/mcp.json](public/.well-known/mcp.json) with tool counts from the catalog; config names match the CLI's `slugForPath`). CLI: [packages/three-ws-cli/](packages/three-ws-cli) (`npx three-ws setup`), docs [docs/cli.md](docs/cli.md) `→ /docs/cli`. One-command setup per client (`npx three-ws --claude`), `doctor`, `agent status` and `team` live in [packages/three-ws-cli/src/commands/](packages/three-ws-cli/src/commands); the hosted installers [public/cli/](public/cli) (`/cli/install`, `/cli/claude`, each with a `.sha256` and an ed25519 `.sig`, public key `signing-key.pem`) are signed by [scripts/sign-cli-scripts.mjs](scripts/sign-cli-scripts.mjs) (`npm run sign:cli`, verified by `npm run check:cli-scripts` in the gate); the clean-container check is [packages/three-ws-cli/tests/container/run.sh](packages/three-ws-cli/tests/container/run.sh). Per-tool pages (schema, example call, price, a try-it for free read-only tools): [pages/mcp-tool.html](pages/mcp-tool.html) `→ /mcp-tools/<server>/<tool>`. The census (tools, resources, prompts per server, with a how-it-is-calculated note) is computed at build time into [public/tools.json](public/tools.json) and at request time by [api/mcp-census.js](api/mcp-census.js) `→ /api/mcp-census` ([api/_lib/mcp-census.js](api/_lib/mcp-census.js)); the release-by-release diff of added tools is [public/mcp-tool-history.json](public/mcp-tool-history.json) ([scripts/build-mcp-tool-history.mjs](scripts/build-mcp-tool-history.mjs)); docs that quote a count use `<!-- mcp-count:... -->` markers that `npm run check:mcp-counts` ([scripts/check-mcp-counts.mjs](scripts/check-mcp-counts.mjs)) verifies in the gate, alongside [tests/mcp-tool-quality.test.js](tests/mcp-tool-quality.test.js) and [tests/mcp-prompt-references.test.js](tests/mcp-prompt-references.test.js) (`npm run test:mcp-surface`). Searchable index of every tool: [pages/mcp-tools.html](pages/mcp-tools.html) `→ /mcp-tools`, rendered from the generated [public/mcp-catalog.json](public/mcp-catalog.json) ([scripts/build-mcp-catalog.mjs](scripts/build-mcp-catalog.mjs), `npm run build:mcp-catalog`, staleness gated by `npm run audit:mcp-catalog`). Tool safety annotations are verified against each handler by [scripts/audit-mcp-safety.mjs](scripts/audit-mcp-safety.mjs) (`npm run audit:mcp-safety`, rules in [scripts/lib/mcp-safety-check.mjs](scripts/lib/mcp-safety-check.mjs), guarded-file list shared with the golden snapshot via [scripts/lib/mcp-tool-sources.mjs](scripts/lib/mcp-tool-sources.mjs)); docs [docs/mcp-safety.md](docs/mcp-safety.md) `→ /docs/mcp-safety`. Trust policy: [api/mcp-policy.js](api/mcp-policy.js) `-> GET /api/mcp-policy` turns those verified labels into a ready-to-paste client allowlist (profiles strict/balanced/open x formats claude/vscode/json), surfaced by the builder panel on `/mcp-tools`. Connector-review readiness (every paid stdio tool answers a clean x402 challenge, and the reviewer entitlement lifts it): [scripts/audit-mcp-reviewer-path.mjs](scripts/audit-mcp-reviewer-path.mjs), `npm run audit:mcp-reviewer`. Tests: [tests/mcp-safety-audit.test.js](tests/mcp-safety-audit.test.js), [tests/mcp-catalog.test.js](tests/mcp-catalog.test.js), [tests/api/mcp-policy.test.js](tests/api/mcp-policy.test.js) |
| CLI payer (x402 and MPP) | [packages/three-ws-cli/src/pay/](packages/three-ws-cli/src/pay) (challenge parser, permissions and daily ledger, keychain/sealed-file keystore, x402 and MPP signers, engine, stdio MCP server), commands [pay.js](packages/three-ws-cli/src/commands/pay.js) and [wallet.js](packages/three-ws-cli/src/commands/wallet.js) | Live | `three-ws pay <url>` settles an x402 v1/v2 or MPP Solana 402 with a locally held key, inside `~/.config/three-ws/pay-permissions.json`; `--dry-run` signs nothing; refusals exit 10 with a reason string; `pay mcp` exposes `pay_quote` and `pay_fetch`. Docs: [README](packages/three-ws-cli/README.md#pay-for-x402-and-mpp-resources-from-the-terminal). Tests: [pay-units](packages/three-ws-cli/tests/pay-units.test.js), [pay-flow](packages/three-ws-cli/tests/pay-flow.test.js), [pay-cli](packages/three-ws-cli/tests/pay-cli.test.js) |
+| MPP on Solana (one URL, two challenge formats) and skill rails | Wire layer [api/_lib/mpp-solana.js](api/_lib/mpp-solana.js) (mppx core), seller option `mpp: true` in [api/_lib/x402-paid-endpoint.js](api/_lib/x402-paid-endpoint.js) (enabled on [api/x402/gas-oracle.js](api/x402/gas-oracle.js)), agent payer `dryRun` / `preferProtocol` in [api/_lib/x402-buyer-fetch.js](api/_lib/x402-buyer-fetch.js), skill router [api/skills/[id]/invoke.js](api/skills/[id]/invoke.js) + [api/_lib/skill-rails.js](api/_lib/skill-rails.js) | Live (mainnet settlement owner-gated) | A paid route answers an unpaid call with the x402 accepts list AND `WWW-Authenticate: Payment` (Solana `charge`, pull mode) at the same price; an `Authorization: Payment` credential settles through the existing x402 verify/settle path and the response carries `Payment-Receipt`. The agent payer reads either, applies its spending caps to the charge, and can quote in dry run. Marketplace skills are priced once and served over x402, MPP, A2A and AP2 with one split and one receipt. Docs: [docs/mpp-solana.md](docs/mpp-solana.md), [docs/skill-rails.md](docs/skill-rails.md). Tests: [tests/mpp-solana.test.js](tests/mpp-solana.test.js), [tests/skill-rails.test.js](tests/skill-rails.test.js) |
| Grok Bot integration (custom MCP connector) | Door [api/mcp-grok.js](api/mcp-grok.js) `→ /api/mcp-grok` on the shared studio handler [api/_mcp-studio/](api/_mcp-studio) (signed-in account tools [api/_mcp-studio/account-tools.js](api/_mcp-studio/account-tools.js), job tools [api/_mcp-studio/job-tools.js](api/_mcp-studio/job-tools.js)), install tokens [api/mcp-studio/install.js](api/mcp-studio/install.js) `→ /api/mcp-studio/install`, guided prompts [api/_mcp/prompts.js](api/_mcp/prompts.js), landing page [pages/grok.html](pages/grok.html) `→ /grok`, connector card [src/grok-connector.js](src/grok-connector.js) (also on `/connect`), skill file [public/grok-skill.md](public/grok-skill.md) (template [data/grok-skill-md.template.md](data/grok-skill-md.template.md)), connector probe [scripts/mcp-client-probe.mjs](scripts/mcp-client-probe.mjs) (`npm run probe:mcp-clients`) | Free remote MCP server for Grok Bot, Grok connectors and the xAI API: no call hangs, quota per MCP session or install token, the free studio anonymously, plus the account's agent tools with a connector key or OAuth 2.1 (`?auth=oauth`), never a value-moving tool. Connector reference [docs/grok-bot.md](docs/grok-bot.md) `→ /docs/grok-bot` (setup per auth mode, server choice, links contract, jobs and idempotency, limits, spend rule, prompts, probe troubleshooting; samples run by [scripts/run-doc-samples.mjs](scripts/run-doc-samples.mjs), drift test [tests/grok-bot-doc.test.js](tests/grok-bot-doc.test.js)); product tour [docs/grok.md](docs/grok.md) |
| X creation claim | Page [pages/x-claim.html](pages/x-claim.html) `→ /x/claim` ([src/x-claim.js](src/x-claim.js)), API [api/x/claim.js](api/x/claim.js), logic [api/_lib/x-creation-claim.js](api/_lib/x-creation-claim.js), ledger migration [api/_lib/migrations/20261009213000_x_creation_claims.sql](api/_lib/migrations/20261009213000_x_creation_claims.sql) | Models the @-mention bot made for an X author move from the bot account into their library when they link the same X id (on link, on the page, or at creation time). Doc: [docs/x-mention-bot.md](docs/x-mention-bot.md). Tests: [tests/x-creation-claim.test.js](tests/x-creation-claim.test.js) |
| Awesome 3D Agents (curated list) | Source [data/awesome.json](data/awesome.json), generator [scripts/build-awesome.mjs](scripts/build-awesome.mjs) (`npm run build:awesome`, drift-gated by `npm run check:awesome`, publishable mirror via `npm run awesome:standalone`), outputs [awesome/README.md](awesome/README.md) + [public/awesome.json](public/awesome.json), page [pages/awesome.html](pages/awesome.html) `-> /awesome`, link checker [scripts/check-awesome-links.mjs](scripts/check-awesome-links.mjs) (`npm run awesome:links`) | Live | An awesome-list of everything needed to give an AI agent a body: text-to-3D, capture and splatting, avatars, rigging, motion, lipsync and voice, web renderers, asset pipelines, physics and networking, agent frameworks, datasets, free assets, learning. One JSON source produces both the GitHub-facing list and the searchable page, so they cannot disagree. Every url is fetched and classified (ok / moved / bot-filtered / broken) before it ships; the checker stays out of the deploy path so a third-party outage cannot redden someone else's build. The README is written to pass `npx awesome-lint`: badge on the heading line, no License section, no Contributing entry in the contents, and every description capitalised and ended with a period, all enforced by the generator and by [tests/awesome-list.test.js](tests/awesome-list.test.js). Its last two lint rules read GitHub repository topics, which a list inside a product repo cannot satisfy, so `--standalone` emits a ready-to-publish mirror repo (readme, contributing, code of conduct, license) outside this checkout. Contributing: [awesome/CONTRIBUTING.md](awesome/CONTRIBUTING.md) |
diff --git a/api/_lib/mpp-solana.js b/api/_lib/mpp-solana.js
new file mode 100644
index 000000000..9d75fd842
--- /dev/null
+++ b/api/_lib/mpp-solana.js
@@ -0,0 +1,293 @@
+// MPP (Machine Payments Protocol) charge on Solana: the wire layer, both sides.
+//
+// MPP answers a request with `402` + `WWW-Authenticate: Payment ...`, the payer
+// retries with `Authorization: Payment <credential>`, and the server confirms
+// with a `Payment-Receipt` header. The Solana `charge` method (pull mode) puts a
+// partially signed SPL TransferChecked transaction in the credential payload,
+// which is the same transaction an x402 `exact` payment carries. So this module
+// owns the framing (built on the official `mppx` core for challenge ids,
+// credential and receipt encoding) and converts to and from the x402 `exact`
+// requirement the platform's verify and settle path already enforces. Nothing
+// here signs or settles: signing is the caller's signer, settlement is
+// x402-spec.js.
+//
+// Server: buildSolanaChargeChallenge, parseSolanaChargeCredential,
+// solanaChargeReceiptHeader, installMppResponse.
+// Buyer: readSolanaChargeChallenges, chargeToRequirement, solanaChargeAuthorization,
+// readSolanaChargeReceipt.
+
+import { Challenge, Credential, Receipt } from 'mppx';
+
+import { env } from './env.js';
+import { NETWORK_SOLANA_DEVNET, NETWORK_SOLANA_MAINNET, isSolanaNetwork } from './x402/solana-networks.js';
+
+export const MPP_REALM = 'three.ws';
+export const MPP_CHALLENGE_TTL_SECONDS = 300;
+
+const NETWORK_NAMES = { [NETWORK_SOLANA_MAINNET]: 'mainnet', [NETWORK_SOLANA_DEVNET]: 'devnet' };
+const NETWORK_FROM_NAME = {
+ solana: NETWORK_SOLANA_MAINNET,
+ mainnet: NETWORK_SOLANA_MAINNET,
+ 'mainnet-beta': NETWORK_SOLANA_MAINNET,
+ 'solana-mainnet': NETWORK_SOLANA_MAINNET,
+ devnet: NETWORK_SOLANA_DEVNET,
+ 'solana-devnet': NETWORK_SOLANA_DEVNET,
+};
+
+function mppSecret() {
+ return env.MPP_SECRET_KEY || env.A2A_MANDATE_SECRET;
+}
+
+/** CAIP-2 id for a network name carried in a challenge (`mainnet`, `devnet`, or a CAIP-2 id). */
+export function networkFromName(name) {
+ const v = String(name ?? 'mainnet').trim();
+ return NETWORK_FROM_NAME[v] ?? v;
+}
+
+/** The first Solana `exact` requirement, the only kind a pull-mode charge can settle. */
+export function pickSolanaExact(requirements, { asset } = {}) {
+ return (
+ (requirements || []).find(
+ (r) => r.scheme === 'exact' && isSolanaNetwork(r.network) && (!asset || r.asset === asset),
+ ) || null
+ );
+}
+
+// ── Server ───────────────────────────────────────────────────────────────────
+
+/**
+ * Build the MPP `charge` challenge for a Solana `exact` requirement. The id is an
+ * HMAC over the challenge terms (mppx), so nothing is stored: a credential that
+ * echoes a valid id proves we issued exactly these terms.
+ * @param {{ requirement: object, description?: string, nowSec?: number, secretKey?: string }} args
+ * @returns {{ id: string, expires: number, header: string, challenge: object }}
+ */
+export function buildSolanaChargeChallenge({
+ requirement,
+ description,
+ nowSec = Math.floor(Date.now() / 1000),
+ secretKey = mppSecret(),
+}) {
+ if (!requirement || !isSolanaNetwork(requirement.network)) {
+ throw new Error('buildSolanaChargeChallenge: a Solana exact requirement is required');
+ }
+ const feePayerKey = requirement.extra?.feePayer;
+ const methodDetails = {
+ network: NETWORK_NAMES[requirement.network] ?? requirement.network,
+ decimals: Number.isInteger(requirement.extra?.decimals) ? requirement.extra.decimals : 6,
+ ...(feePayerKey ? { feePayer: true, feePayerKey } : {}),
+ };
+ const expires = nowSec + MPP_CHALLENGE_TTL_SECONDS;
+ const challenge = Challenge.from(
+ {
+ secretKey,
+ realm: MPP_REALM,
+ method: 'solana',
+ intent: 'charge',
+ request: {
+ amount: String(requirement.amount),
+ currency: requirement.asset,
+ recipient: requirement.payTo,
+ methodDetails,
+ },
+ expires: new Date(expires * 1000).toISOString(),
+ ...(description ? { description: String(description).slice(0, 256) } : {}),
+ },
+ );
+ return { id: challenge.id, expires, header: Challenge.serialize(challenge), challenge };
+}
+
+/**
+ * Parse and authenticate an `Authorization: Payment` credential for the Solana
+ * charge method: the echoed challenge id must be the HMAC of exactly its terms and
+ * still inside its lifetime, and the payload must carry a transaction.
+ * @returns {{ ok: true, challenge: object, request: object, transaction: string, source?: string } | { ok: false, code: string, message: string }}
+ */
+export function parseSolanaChargeCredential(
+ authorization,
+ { nowSec = Math.floor(Date.now() / 1000), secretKey = mppSecret() } = {},
+) {
+ let credential;
+ try {
+ credential = Credential.deserialize(String(authorization || '').trim());
+ } catch {
+ return { ok: false, code: 'invalid_credential', message: 'Authorization must be "Payment <base64url credential>"' };
+ }
+ const { challenge, payload } = credential;
+ if (challenge.method !== 'solana' || challenge.intent !== 'charge') {
+ return { ok: false, code: 'unsupported_method', message: 'this server accepts only the solana charge method' };
+ }
+ const expiresMs = challenge.expires ? Date.parse(challenge.expires) : NaN;
+ if (!Number.isFinite(expiresMs) || nowSec * 1000 >= expiresMs) {
+ return { ok: false, code: 'challenge_expired', message: 'the payment challenge has expired, request a new one' };
+ }
+ if (!Challenge.verify(challenge, { secretKey })) {
+ return { ok: false, code: 'challenge_mismatch', message: 'credential does not match a challenge issued by this server' };
+ }
+ if (!payload || payload.type !== 'transaction' || typeof payload.transaction !== 'string' || !payload.transaction) {
+ return { ok: false, code: 'invalid_credential', message: 'payload must be { type: "transaction", transaction: <base64> }' };
+ }
+ return {
+ ok: true,
+ challenge,
+ request: challenge.request,
+ transaction: payload.transaction,
+ ...(credential.source ? { source: credential.source } : {}),
+ };
+}
+
+/**
+ * True when a credential's terms are exactly the requirement's, so a challenge
+ * issued for one price or payee cannot redeem another.
+ */
+export function chargeMatchesRequirement(request, requirement) {
+ return (
+ String(request?.amount) === String(requirement.amount) &&
+ request?.recipient === requirement.payTo &&
+ request?.currency === requirement.asset &&
+ networkFromName(request?.methodDetails?.network) === requirement.network
+ );
+}
+
+/** The x402 payment payload that settles a parsed charge credential. */
+export function chargeToX402Payment({ requirement, transaction }) {
+ return { x402Version: 2, accepted: requirement, payload: { transaction } };
+}
+
+/** The `Payment-Receipt` header value for a settled charge. */
+export function solanaChargeReceiptHeader({ transaction, network, payer, nowSec = Math.floor(Date.now() / 1000) }) {
+ return Receipt.serialize(
+ Receipt.from({
+ method: 'solana',
+ reference: transaction,
+ status: 'success',
+ timestamp: new Date(nowSec * 1000).toISOString(),
+ ...(network ? { network } : {}),
+ ...(payer ? { payer } : {}),
+ }),
+ );
+}
+
+/**
+ * Make a response speak MPP without touching the handler that produces it: a 402
+ * gains the `WWW-Authenticate: Payment` challenge, and a settled 200 (which
+ * already carries `x-payment-response`) gains `Payment-Receipt`. Installed once
+ * per request, before anything is written.
+ * @param {import('node:http').ServerResponse} res
+ * @param {{ challengeHeader: string }} args
+ */
+export function installMppResponse(res, { challengeHeader }) {
+ const end = res.end.bind(res);
+ res.end = (...args) => {
+ try {
+ if (res.statusCode === 402) {
+ res.setHeader('www-authenticate', challengeHeader);
+ } else if (res.statusCode >= 200 && res.statusCode < 300) {
+ const settlement = decodeSettlement(res.getHeader('x-payment-response'));
+ if (settlement?.transaction) {
+ res.setHeader(
+ 'payment-receipt',
+ solanaChargeReceiptHeader({
+ transaction: settlement.transaction,
+ network: settlement.network,
+ payer: settlement.payer,
+ }),
+ );
+ }
+ }
+ } catch {
+ // headers already sent: the body still ships, the receipt is advisory
+ }
+ return end(...args);
+ };
+}
+
+function decodeSettlement(header) {
+ if (!header) return null;
+ try {
+ return JSON.parse(Buffer.from(String(header), 'base64').toString('utf8'));
+ } catch {
+ return null;
+ }
+}
+
+// ── Buyer ────────────────────────────────────────────────────────────────────
+
+/**
+ * Every Solana charge challenge on a 402 response, each with the x402-shaped
+ * requirement the platform's guard layers already understand.
+ * @param {Headers} headers
+ * @param {{ nowSec?: number }} [opts]
+ * @returns {{ challenge: object, requirement: object, expired: boolean }[]}
+ */
+export function readSolanaChargeChallenges(headers, { nowSec = Math.floor(Date.now() / 1000) } = {}) {
+ const raw = headers.get('www-authenticate');
+ if (!raw || !/\bpayment\b/i.test(raw)) return [];
+ let challenges;
+ try {
+ challenges = Challenge.fromHeadersList(headers);
+ } catch {
+ return [];
+ }
+ const out = [];
+ for (const challenge of challenges) {
+ if (challenge.method !== 'solana' || challenge.intent !== 'charge') continue;
+ const requirement = chargeToRequirement(challenge);
+ if (!requirement) continue;
+ const expiresMs = challenge.expires ? Date.parse(challenge.expires) : NaN;
+ out.push({ challenge, requirement, expired: Number.isFinite(expiresMs) && nowSec * 1000 >= expiresMs });
+ }
+ return out;
+}
+
+/**
+ * An MPP solana charge expressed as the x402 `exact` requirement it settles as,
+ * or null when it asks for something a pull-mode SPL charge cannot do (native
+ * SOL, confidential transfers, splits).
+ */
+export function chargeToRequirement(challenge) {
+ const request = challenge.request ?? {};
+ const details = request.methodDetails ?? {};
+ if (!request.currency || request.currency === 'sol') return null;
+ if (details.confidential || (Array.isArray(details.splits) && details.splits.length > 0)) return null;
+ if (!/^\d+$/.test(String(request.amount ?? '')) || typeof request.recipient !== 'string') return null;
+ if (details.feePayer && typeof details.feePayerKey !== 'string') return null;
+ return {
+ scheme: 'exact',
+ network: networkFromName(details.network),
+ asset: request.currency,
+ payTo: request.recipient,
+ amount: String(request.amount),
+ maxTimeoutSeconds: MPP_CHALLENGE_TTL_SECONDS,
+ extra: {
+ ...(details.feePayerKey ? { feePayer: details.feePayerKey } : {}),
+ ...(Number.isInteger(details.decimals) ? { decimals: details.decimals } : {}),
+ ...(details.tokenProgram ? { tokenProgram: details.tokenProgram } : {}),
+ },
+ };
+}
+
+/**
+ * The `Authorization` header value that redeems a challenge with a signed
+ * transaction (base64 wire format).
+ */
+export function solanaChargeAuthorization({ challenge, transaction, source }) {
+ return Credential.serialize(
+ Credential.from({
+ challenge,
+ payload: { type: 'transaction', transaction },
+ ...(source ? { source } : {}),
+ }),
+ );
+}
+
+/** Decoded `Payment-Receipt` from a response, or null. */
+export function readSolanaChargeReceipt(response) {
+ const header = response.headers.get('payment-receipt');
+ if (!header) return null;
+ try {
+ return Receipt.deserialize(header);
+ } catch {
+ return null;
+ }
+}
diff --git a/api/_lib/x402-buyer-fetch.js b/api/_lib/x402-buyer-fetch.js
index 3d5322dd0..c04bdfb89 100644
--- a/api/_lib/x402-buyer-fetch.js
+++ b/api/_lib/x402-buyer-fetch.js
@@ -26,6 +26,7 @@
import { enforceCap, commit, releaseUnusedCap, rollbackReservation } from './x402-spending-cap.js';
import { BUILDER_CODE } from './x402-builder-code.js';
import { env } from './env.js';
+import { readSolanaChargeChallenges, readSolanaChargeReceipt, solanaChargeAuthorization } from './mpp-solana.js';
function selectRequirement(challenge, prefer, preferScheme) {
let accepts = Array.isArray(challenge?.accepts) ? challenge.accepts : [];
@@ -88,6 +89,14 @@ function b64decode(s) {
// { ok: true, result, response, payment, settled }
// { ok: false, abort: true, reason } — cap rejected; no network call
// { ok: false, status, error } — server returned non-2xx
+//
+// The same call pays either protocol a 402 can speak. An x402 `accepts` list is
+// preferred; when a server offers only an MPP `WWW-Authenticate: Payment`
+// Solana charge (or `preferProtocol: 'mpp'` is set and one is on offer), the
+// charge is expressed as the equivalent `exact` requirement, so the spending
+// caps, `signPayment` and the guard layers see one shape, and the signed
+// transaction goes back as `Authorization: Payment`. `dryRun: true` stops after
+// the cap check and returns the quote, signing and paying nothing.
export async function buyerFetch(url, opts = {}) {
const {
method = 'GET',
@@ -97,6 +106,8 @@ export async function buyerFetch(url, opts = {}) {
signPayment,
preferNetwork,
preferScheme,
+ preferProtocol,
+ dryRun = false,
fetchImpl = globalThis.fetch,
} = opts;
@@ -124,11 +135,22 @@ export async function buyerFetch(url, opts = {}) {
const header = probe.headers.get('payment-required');
return header ? b64decode(header) : null;
})();
- if (!challenge || !Array.isArray(challenge.accepts)) {
+ const mppOffers = readSolanaChargeChallenges(probe.headers).filter((o) => !o.expired);
+ const hasX402 = Boolean(challenge) && Array.isArray(challenge.accepts);
+ if (!hasX402 && !mppOffers.length) {
return { ok: false, status: 402, error: 'invalid_402_body' };
}
- const requirement = selectRequirement(challenge, preferNetwork, preferScheme);
+ let protocol = 'x402';
+ let mppOffer = null;
+ let requirement = null;
+ if (hasX402 && preferProtocol !== 'mpp') requirement = selectRequirement(challenge, preferNetwork, preferScheme);
+ if (!requirement && mppOffers.length) {
+ mppOffer = mppOffers.find((o) => o.requirement.network === preferNetwork) || mppOffers[0];
+ requirement = mppOffer.requirement;
+ protocol = 'mpp';
+ }
+ if (!requirement && hasX402) requirement = selectRequirement(challenge, preferNetwork, preferScheme);
if (!requirement) {
return { ok: false, status: 402, error: 'no_acceptable_requirement' };
}
@@ -137,11 +159,25 @@ export async function buyerFetch(url, opts = {}) {
if (caps) {
const verdict = await enforceCap({ requirement, opts: caps });
if (verdict.abort) {
- return { ok: false, abort: true, reason: verdict.reason };
+ return { ok: false, abort: true, reason: verdict.reason, protocol, ...(dryRun ? { dryRun: true } : {}) };
}
reservation = verdict.reservation;
}
+ if (dryRun) {
+ if (reservation) await rollbackReservation(reservation);
+ return {
+ ok: true,
+ dryRun: true,
+ protocol,
+ quote: requirement,
+ offers: {
+ x402: hasX402 ? challenge.accepts : [],
+ mpp: mppOffers.map((o) => o.requirement),
+ },
+ };
+ }
+
try {
let paymentPayload;
try {
@@ -150,12 +186,26 @@ export async function buyerFetch(url, opts = {}) {
if (reservation) await rollbackReservation(reservation);
throw err;
}
- ensureBuilderCodeEcho(challenge, paymentPayload);
-
- const xPayment = b64encode(paymentPayload);
+ let paidHeaders;
+ if (protocol === 'mpp') {
+ const transaction = paymentPayload?.payload?.transaction;
+ if (typeof transaction !== 'string' || !transaction) {
+ throw new Error('buyerFetch: signPayment must return a Solana exact payload ({ payload: { transaction } }) to pay an MPP charge');
+ }
+ paidHeaders = {
+ Authorization: solanaChargeAuthorization({
+ challenge: mppOffer.challenge,
+ transaction,
+ ...(typeof paymentPayload.payer === 'string' ? { source: paymentPayload.payer } : {}),
+ }),
+ };
+ } else {
+ ensureBuilderCodeEcho(challenge, paymentPayload);
+ paidHeaders = { 'X-PAYMENT': b64encode(paymentPayload) };
+ }
const paid = await fetchImpl(url, {
...init,
- headers: { ...(init.headers || {}), 'X-PAYMENT': xPayment },
+ headers: { ...(init.headers || {}), ...paidHeaders },
});
const paidText = await paid.text();
const paidJson = safeJson(paidText) ?? paidText;
@@ -169,7 +219,10 @@ export async function buyerFetch(url, opts = {}) {
response: paid,
};
}
- const settled = b64decode(paid.headers.get('x-payment-response'));
+ const receipt = protocol === 'mpp' ? readSolanaChargeReceipt(paid) : null;
+ const settled = receipt
+ ? { success: true, transaction: receipt.reference, network: receipt.network ?? requirement.network, payer: receipt.payer }
+ : b64decode(paid.headers.get('x-payment-response'));
if (reservation && requirement.scheme === 'upto' && settled?.amount != null) {
reservation = await releaseUnusedCap(reservation, requirement, settled.amount);
}
@@ -182,6 +235,7 @@ export async function buyerFetch(url, opts = {}) {
}
return {
ok: true,
+ protocol,
result: paidJson,
response: paid,
payment: paymentPayload,
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index b2de8c827..bbcbb13bc 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -76,6 +76,14 @@ import {
writeConflict,
writeInflight,
} from './x402/payment-identifier-server.js';
+import {
+ buildSolanaChargeChallenge,
+ chargeMatchesRequirement,
+ chargeToX402Payment,
+ installMppResponse,
+ parseSolanaChargeCredential,
+ pickSolanaExact,
+} from './mpp-solana.js';
import { authenticateSiwx, declareSiwxExtensionFor, recordSiwxPayment } from './siwx-server.js';
import { verifyAuthHintsSiwx } from './x402/auth-hints.js';
import { declarePrepaidExtension, prepaidRequirement, servePrepaid } from './x402/prepaid-route.js';
@@ -466,6 +474,13 @@ export function paidEndpoint(spec) {
// (api/_lib/x402/prepaid-ledger.js); a call that fails is never debited.
// A caller without a balance gets the normal 402 and can still pay per call.
mode = 'exact',
+ // MPP (Machine Payments Protocol) on Solana, additive to x402: when true
+ // the 402 also carries `WWW-Authenticate: Payment ... method="solana"
+ // intent="charge"`, an `Authorization: Payment` credential is redeemed
+ // through the same verify/settle path as an x402 `exact` payment, and a
+ // settled response gains `Payment-Receipt`. One price, one payee, one
+ // receipt. See api/_lib/mpp-solana.js and docs/mpp.md.
+ mpp = false,
// Optional post-settlement hook for per-job metering (Roadmap phase 4:
// inference settlement). Called with the settled payment context BEFORE
// the response is flushed; the value it returns is JSON-merged into the
@@ -582,7 +597,16 @@ export function paidEndpoint(spec) {
// wrong method that carries NO payment or auth credentials can only
// ever want the challenge, so serve it; anything carrying credentials
// intended to redeem the resource still gets the strict 405.
+ // An MPP credential is a payment, not a bearer token: lift it out of
+ // `authorization` so access control and the authenticated-caller bypass
+ // never mistake it for a login.
+ let mppAuthorization = null;
+ if (mpp && /^payment\s/i.test(req.headers?.authorization || '')) {
+ mppAuthorization = req.headers.authorization;
+ delete req.headers.authorization;
+ }
const hasCredentials =
+ !!mppAuthorization ||
!!req.headers?.['x-payment'] ||
!!req.headers?.['payment-signature'] ||
!!req.headers?.['sign-in-with-x'] ||
@@ -639,6 +663,28 @@ export function paidEndpoint(spec) {
);
}
+ if (mpp) {
+ const charge = pickSolanaExact(requirements);
+ if (charge) {
+ const challenge = buildSolanaChargeChallenge({ requirement: charge, description });
+ installMppResponse(res, { challengeHeader: challenge.header });
+ if (mppAuthorization && !req.headers['x-payment'] && !req.headers['payment-signature']) {
+ const parsed = parseSolanaChargeCredential(mppAuthorization);
+ if (!parsed.ok && parsed.code !== 'challenge_expired') {
+ return error(res, 401, parsed.code, parsed.message);
+ }
+ if (parsed.ok) {
+ if (!chargeMatchesRequirement(parsed.request, charge)) {
+ return error(res, 402, 'challenge_mismatch', 'the price or payee changed since this challenge, retry with a fresh one');
+ }
+ req.headers['x-payment'] = Buffer.from(
+ JSON.stringify(chargeToX402Payment({ requirement: charge, transaction: parsed.transaction })),
+ ).toString('base64');
+ }
+ }
+ }
+ }
+
if (upto && uptoEnabled() && networks.includes('solana')) {
try {
const uptoAccept = await buildUptoOffer({ upto, resourceUrl, payTo });
diff --git a/api/x402/gas-oracle.js b/api/x402/gas-oracle.js
index 654659835..14381decb 100644
--- a/api/x402/gas-oracle.js
+++ b/api/x402/gas-oracle.js
@@ -239,6 +239,7 @@ export default paidEndpoint({
method: 'GET',
priceAtomics: priceFor('gas-oracle', '1000'), // $0.001 USDC
networks: ['solana', 'base'],
+ mpp: true,
description: DESCRIPTION,
bazaar: BAZAAR,
service: withService({
diff --git a/data/changelog.json b/data/changelog.json
index 5e066ad9e..cb00dd65f 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -3,10 +3,13 @@
"entries": [
{
"date": "2026-10-23",
- "title": "Trade from Telegram and Discord with a typed yes",
- "summary": "A paired chat now takes /buy, /sell, /snipe, /orders and /cancel. Each replies with a quote (route, price impact, RugCheck, fees) and only the exact word yes typed within 60 seconds executes it; anything else cancels and a late yes sends nothing. Buys can rest a linked take-profit and stop-loss, and /positions sends a P&L share card for recent closes.",
- "tags": ["feature"],
- "link": "/docs/chat-gateways"
+ "title": "Pay any paid endpoint over MPP on Solana, and sell a skill on four rails from one price",
+ "summary": "Paid endpoints can now answer with an MPP Payment challenge beside the x402 one at the same price, and the agent payer pays either from one call with its spending caps and a dry-run quote. Marketplace skills are defined once and served over x402, MPP, A2A and AP2 with the same author and platform split and the same receipt.",
+ "tags": [
+ "feature",
+ "sdk"
+ ],
+ "link": "/docs/mpp-solana"
},
{
"date": "2026-10-23",
diff --git a/data/pages.json b/data/pages.json
index 99523855d..50ad1016c 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -4750,6 +4750,18 @@
"added": "2026-10-23"
},
{
+ "path": "/docs/skill-rails",
+ "title": "Docs · One paid skill, four rails",
+ "description": "Price a marketplace skill once and serve it over x402, MPP, A2A and AP2 with the same author and platform split, one agent card and one receipt. Includes the dry-run quote, rail toggles and 404 on a disabled rail.",
+ "added": "2026-10-23"
+ },
+ {
+ "path": "/docs/mpp-solana",
+ "title": "Docs · MPP on Solana",
+ "description": "Serve and pay MPP Payment challenges on Solana beside x402 on the same URL: the challenge and credential wire format, the mpp option on paid endpoints, the agent payer with spending caps and a dry-run quote, and how to verify it.",
+ "added": "2026-10-23"
+ },
+ {
"path": "/docs/skill-import",
"title": "Docs · Importing skills",
"description": "Install SKILL.md skills from any public GitHub repository or registry manifest: pinned to an exact commit, licence-checked, scanned for hostile instructions, approved by the owner, and run under the spend gate when they ask to spend, sign or message. Includes the fork and publish flow, the MCP tools and the REST API.",
diff --git a/docs/mpp-solana.md b/docs/mpp-solana.md
new file mode 100644
index 000000000..c62b84c98
--- /dev/null
+++ b/docs/mpp-solana.md
@@ -0,0 +1,59 @@
+# MPP on Solana
+
+MPP (Machine Payments Protocol) is the HTTP 402 payment scheme built on `WWW-Authenticate: Payment`. three.ws speaks the Solana `charge` method alongside x402 on the same URL: one price, one payee, one settlement path, one receipt.
+
+## What a buyer sees
+
+An endpoint that opts in answers an unpaid request with a normal x402 `402` body and `PAYMENT-REQUIRED` header, plus:
+
+```
+www-authenticate: Payment id="...", realm="three.ws", method="solana", intent="charge", request="<base64url JSON>", expires="<ISO time>"
+```
+
+The decoded `request` is `{ amount, currency, recipient, methodDetails: { network, decimals, feePayer, feePayerKey } }`. The amount, mint and payee are exactly the x402 `exact` Solana accept entry. `expires` is five minutes out. The challenge `id` is an HMAC of its terms (secret: `MPP_SECRET_KEY`, falling back to `A2A_MANDATE_SECRET`), so nothing is stored: a credential that echoes a valid id proves we issued those exact terms.
+
+## Paying
+
+Pull mode. The payer builds the same partially signed SPL `TransferChecked` transaction an x402 `exact` payment carries (the sponsor fee-payer slot stays empty) and retries with:
+
+```
+Authorization: Payment <base64url {challenge, source, payload: {type: "transaction", transaction: <base64>}}>
+```
+
+On success the response carries `Payment-Receipt` (method `solana`, `reference` = settlement signature) next to the usual `x-payment-response`. Native SOL, split and confidential charges are declined by the buyer rather than mispaid.
+
+The credential is lifted out of `Authorization` before access control runs, so it is never mistaken for a login, and it settles through the existing verify and settle path: the facilitator check, the replay guard, the per-route price and the receipt row are shared with x402.
+
+## Selling
+
+```js
+export default paidEndpoint({
+ route: '/api/x402/gas-oracle',
+ networks: ['solana', 'base'],
+ mpp: true,
+ // ...
+});
+```
+
+`mpp: true` needs a Solana network on the route. Paid skills enable it per skill through the `mpp` rail (see [one definition, many rails](./skill-rails.md)). Wire layer: [api/_lib/mpp-solana.js](../api/_lib/mpp-solana.js), built on the MIT `mppx` core.
+
+## Agent payer
+
+`buyerFetch` pays either protocol with one call:
+
+```js
+const quote = await buyerFetch(url, { dryRun: true, caps, signPayment }); // reads the offers, checks the cap, signs nothing
+const paid = await buyerFetch(url, { preferProtocol: 'mpp', caps, signPayment });
+```
+
+An MPP charge is expressed as the equivalent `exact` requirement, so the spending caps (`maxPerCall`, hourly, daily), `signPayment` and the guard layers see one shape. `result.protocol` says which protocol paid, and `result.settled` is read from `Payment-Receipt`. The terminal payer (`three-ws pay`, see [cli](./cli.md)) redeems the same challenge.
+
+## Verifying
+
+`npx vitest run tests/mpp-solana.test.js` runs a real HTTP server around `paidEndpoint`, real transaction signing against a local JSON-RPC stub, the buyer caps, a forged and an expired credential, and the CLI payer's challenge parser and signer against the server.
+
+Mainnet settlement of a real charge spends USDC and is owner-gated. After approval, point the CLI at a live MPP endpoint:
+
+```
+three-ws pay https://three.ws/api/x402/gas-oracle --max 0.002
+```
diff --git a/tests/mpp-solana.test.js b/tests/mpp-solana.test.js
new file mode 100644
index 000000000..e6a4748af
--- /dev/null
+++ b/tests/mpp-solana.test.js
@@ -0,0 +1,380 @@
+// MPP (Machine Payments Protocol) charge on Solana, end to end.
+//
+// Real: a paidEndpoint() served over a local HTTP server, mppx challenge and
+// credential encoding, the @x402/svm client building and ed25519-signing the SPL
+// TransferChecked transaction (against a local JSON-RPC stub for the blockhash
+// and mint), the buyer (buyerFetch) with its spending caps. Test-controlled: the
+// facilitator, which keeps the cryptographic checks (the buyer signed, the
+// sponsor fee-payer slot is empty, the amount is in the transfer) and replaces
+// only the chain with an in-memory ledger.
+
+import http from 'node:http';
+
+import { generateKeyPairSigner, getBase64Encoder, getTransactionDecoder } from '@solana/kit';
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const USDC_MAINNET = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
+const PRICE = '1000'; // 0.001 USDC
+
+const { ledger } = vi.hoisted(() => ({ ledger: { verified: [], settled: [] } }));
+
+vi.mock('@coinbase/x402', () => ({ createCdpAuthHeaders: vi.fn(async () => ({})) }));
+
+vi.mock('../api/_lib/x402-spec.js', async (importActual) => {
+ const actual = await importActual();
+ const { getBase64Encoder: b64, getTransactionDecoder: decoder } = await import('@solana/kit');
+ return {
+ ...actual,
+ verifyPayment: vi.fn(async ({ paymentHeader, requirements }) => {
+ const payment = JSON.parse(Buffer.from(paymentHeader, 'base64').toString('utf8'));
+ const all = Array.isArray(requirements) ? requirements : [requirements];
+ const requirement = all.find(
+ (r) => r.network === payment.accepted?.network && r.payTo === payment.accepted?.payTo && r.amount === payment.accepted?.amount,
+ );
+ if (!requirement) throw new actual.X402Error('requirement_mismatch', 'payment does not match an advertised requirement', 402);
+ const tx = decoder().decode(b64().encode(payment.payload.transaction));
+ const signed = Object.entries(tx.signatures).filter(([, sig]) => sig);
+ const unsigned = Object.entries(tx.signatures).filter(([, sig]) => !sig);
+ if (signed.length !== 1 || unsigned.length !== 1) {
+ throw new actual.X402Error('bad_signatures', 'expected the payer signed and the sponsor slot empty', 402);
+ }
+ if (unsigned[0][0] !== requirement.extra.feePayer) {
+ throw new actual.X402Error('bad_fee_payer', 'sponsor slot is not the advertised fee payer', 402);
+ }
+ ledger.verified.push({ payer: signed[0][0], requirement, signature: signed[0][1] });
+ return { payer: signed[0][0], requirement, paymentPayload: payment };
+ }),
+ settlePayment: vi.fn(async ({ verified }) => {
+ const transaction = `sig${ledger.settled.length + 1}${'x'.repeat(40)}`;
+ ledger.settled.push({ transaction, payer: verified.payer, requirement: verified.requirement });
+ return { transaction, network: verified.requirement.network, payer: verified.payer };
+ }),
+ };
+});
+
+let server;
+let origin;
+let rpcServer;
+let rpcUrl;
+let blockhashSeq = 0;
+let payer;
+let payTo;
+let feePayer;
+let freshBlockhashes = [];
+let challengeLog = [];
+
+function startRpcStub() {
+ return new Promise((resolve) => {
+ rpcServer = http.createServer((req, res) => {
+ let body = '';
+ req.on('data', (c) => (body += c));
+ req.on('end', () => {
+ const call = JSON.parse(body);
+ let result = null;
+ if (call.method === 'getLatestBlockhash') {
+ result = {
+ context: { slot: 1 },
+ value: { blockhash: freshBlockhashes[blockhashSeq++ % freshBlockhashes.length], lastValidBlockHeight: 100 },
+ };
+ } else if (call.method === 'getAccountInfo') {
+ const mint = Buffer.alloc(82);
+ mint[44] = 6; // decimals
+ mint[45] = 1; // initialized
+ result = {
+ context: { slot: 1 },
+ value: {
+ data: [mint.toString('base64'), 'base64'],
+ executable: false,
+ lamports: 1,
+ owner: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',
+ rentEpoch: 0,
+ },
+ };
+ }
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: call.id, result }));
+ });
+ });
+ rpcServer.listen(0, '127.0.0.1', () => {
+ rpcUrl = `http://127.0.0.1:${rpcServer.address().port}`;
+ resolve();
+ });
+ });
+}
+
+beforeAll(async () => {
+ process.env.X402_ALLOW_MEMORY_FALLBACK = '1';
+ process.env.A2A_MANDATE_SECRET = 'mpp-solana-test-secret-0123456789abcdef';
+ delete process.env.DATABASE_URL;
+ delete process.env.X402_BUILDER_CODE_APP;
+
+ payer = await generateKeyPairSigner();
+ feePayer = await generateKeyPairSigner();
+ payTo = (await generateKeyPairSigner()).address;
+ freshBlockhashes = await Promise.all(Array.from({ length: 24 }, async () => (await generateKeyPairSigner()).address));
+
+ process.env.X402_PAY_TO_SOLANA = payTo;
+ process.env.X402_ASSET_MINT_SOLANA = USDC_MAINNET;
+ process.env.X402_FEE_PAYER_SOLANA = feePayer.address;
+
+ await startRpcStub();
+
+ const { paidEndpoint } = await import('../api/_lib/x402-paid-endpoint.js');
+ const endpoint = paidEndpoint({
+ route: '/api/x402/mpp-test',
+ method: 'GET',
+ networks: ['solana'],
+ priceAtomics: PRICE,
+ description: 'MPP on Solana integration test',
+ mpp: true,
+ bazaar: {
+ discoverable: true,
+ info: { input: { type: 'object', properties: {}, required: [] }, output: { type: 'object', properties: { ok: { type: 'boolean' } } } },
+ schema: { type: 'object' },
+ },
+ handler: async () => ({ ok: true }),
+ });
+ const plain = paidEndpoint({
+ route: '/api/x402/mpp-off',
+ method: 'GET',
+ networks: ['solana'],
+ priceAtomics: PRICE,
+ description: 'x402 only control',
+ bazaar: {
+ discoverable: true,
+ info: { input: { type: 'object', properties: {}, required: [] }, output: { type: 'object', properties: { ok: { type: 'boolean' } } } },
+ schema: { type: 'object' },
+ },
+ handler: async () => ({ ok: true }),
+ });
+ server = http.createServer((req, res) => (req.url.startsWith('/api/x402/mpp-off') ? plain(req, res) : endpoint(req, res)));
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ origin = `http://127.0.0.1:${server.address().port}`;
+});
+
+afterAll(async () => {
+ await new Promise((resolve) => server?.close(resolve));
+ await new Promise((resolve) => rpcServer?.close(resolve));
+});
+
+beforeEach(() => {
+ ledger.verified.length = 0;
+ ledger.settled.length = 0;
+ challengeLog = [];
+});
+
+const url = () => `${origin}/api/x402/mpp-test`;
+
+async function signPayment({ requirement }) {
+ const { buildSolanaExactPayload } = await import('../api/_lib/x402/a2a-client.js');
+ return buildSolanaExactPayload({ accept: requirement, signer: payer, resource: url(), rpcUrl });
+}
+
+describe('one URL, two challenge formats', () => {
+ it('answers 402 with the x402 accepts list AND an MPP Payment challenge at the same price', async () => {
+ const res = await fetch(url());
+ expect(res.status).toBe(402);
+ const www = res.headers.get('www-authenticate');
+ const body = await res.json();
+ console.log(`HTTP 402\nwww-authenticate: ${www}\nx402 accepts[0]: ${JSON.stringify(body.accepts[0])}`);
+
+ const { Challenge } = await import('mppx');
+ const [challenge] = Challenge.fromHeadersList(res.headers);
+ expect(challenge.method).toBe('solana');
+ expect(challenge.intent).toBe('charge');
+ expect(challenge.request.amount).toBe(PRICE);
+ expect(challenge.request.currency).toBe(USDC_MAINNET);
+ expect(challenge.request.recipient).toBe(payTo);
+ expect(challenge.request.methodDetails).toMatchObject({ network: 'mainnet', decimals: 6, feePayer: true, feePayerKey: feePayer.address });
+
+ const x402 = body.accepts.find((a) => a.network === SOLANA_MAINNET);
+ expect(x402.amount).toBe(challenge.request.amount);
+ expect(x402.payTo).toBe(challenge.request.recipient);
+ expect(x402.asset).toBe(challenge.request.currency);
+ });
+
+ it('does not offer MPP on an endpoint that did not opt in', async () => {
+ const res = await fetch(`${origin}/api/x402/mpp-off`);
+ expect(res.status).toBe(402);
+ expect(res.headers.get('www-authenticate')).toBeNull();
+ });
+});
+
+describe('the agent payer', () => {
+ it('completes an MPP quote in dry run: reads the charge, checks the cap, signs and pays nothing', async () => {
+ const { buyerFetch } = await import('../api/_lib/x402-buyer-fetch.js');
+ const signer = vi.fn();
+ const result = await buyerFetch(url(), {
+ preferProtocol: 'mpp',
+ dryRun: true,
+ caps: { address: 'dry-run-agent', maxPerCall: '5000' },
+ signPayment: signer,
+ });
+ console.log(`dry-run transcript:\n${JSON.stringify({ ok: result.ok, protocol: result.protocol, quote: result.quote, mppOffers: result.offers.mpp.length }, null, 2)}`);
+ expect(result.ok).toBe(true);
+ expect(result.dryRun).toBe(true);
+ expect(result.protocol).toBe('mpp');
+ expect(result.quote).toMatchObject({ scheme: 'exact', network: SOLANA_MAINNET, asset: USDC_MAINNET, payTo, amount: PRICE });
+ expect(result.offers.mpp).toHaveLength(1);
+ expect(signer).not.toHaveBeenCalled();
+ expect(ledger.verified).toHaveLength(0);
+ });
+
+ it('pays an MPP charge with a really signed transaction and reads the Payment-Receipt', async () => {
+ const { buyerFetch } = await import('../api/_lib/x402-buyer-fetch.js');
+ const result = await buyerFetch(url(), { preferProtocol: 'mpp', signPayment, caps: { address: 'mpp-agent', maxPerCall: '5000' } });
+ expect(result.ok, JSON.stringify(result.result)).toBe(true);
+ expect(result.protocol).toBe('mpp');
+ expect(result.result).toEqual({ ok: true });
+ expect(ledger.settled).toHaveLength(1);
+ expect(ledger.verified[0].payer).toBe(payer.address);
+ expect(result.settled).toMatchObject({ success: true, transaction: ledger.settled[0].transaction, payer: payer.address });
+ expect(result.response.headers.get('payment-receipt')).toBeTruthy();
+ });
+
+ it('still pays the same endpoint over x402 when MPP is not preferred', async () => {
+ const { buyerFetch } = await import('../api/_lib/x402-buyer-fetch.js');
+ const result = await buyerFetch(url(), { signPayment });
+ expect(result.ok, JSON.stringify(result.result)).toBe(true);
+ expect(result.protocol).toBe('x402');
+ expect(result.response.headers.get('x-payment-response')).toBeTruthy();
+ expect(ledger.settled).toHaveLength(1);
+ });
+
+ it('pays an MPP-only server (no x402 body at all)', async () => {
+ const { buyerFetch } = await import('../api/_lib/x402-buyer-fetch.js');
+ const mppOnly = async (input, init) => {
+ const res = await fetch(input, init);
+ if (res.status !== 402) return res;
+ const headers = new Headers(res.headers);
+ headers.delete('payment-required');
+ return new Response('payment required', { status: 402, headers });
+ };
+ const result = await buyerFetch(url(), { signPayment, fetchImpl: mppOnly });
+ expect(result.ok, JSON.stringify(result.result)).toBe(true);
+ expect(result.protocol).toBe('mpp');
+ expect(ledger.settled).toHaveLength(1);
+ });
+});
+
+describe('interop with the three-ws CLI payer', () => {
+ it('parses the challenge, signs a credential and redeems it for a Payment-Receipt', async () => {
+ const { readChallenge } = await import('../packages/three-ws-cli/src/pay/challenge.js');
+ const { signMpp, readMppReceipt } = await import('../packages/three-ws-cli/src/pay/mpp.js');
+ const probe = await fetch(url());
+ const { offers } = await readChallenge(probe);
+ const offer = offers.find((o) => o.protocol === 'mpp');
+ expect(offer.unsupported).toBeUndefined();
+ expect(offer.amountAtomic).toBe(BigInt(PRICE));
+ const { authorization } = await signMpp({ offer, signer: payer, rpcUrl });
+ const paid = await fetch(url(), { headers: { authorization } });
+ expect(paid.status, await paid.clone().text()).toBe(200);
+ expect(readMppReceipt(paid)).toMatchObject({ method: 'solana', status: 'success', reference: ledger.settled[0].transaction });
+ });
+});
+
+describe('guard layers on an MPP challenge', () => {
+ it('blocks a charge above the per-call cap before anything is signed', async () => {
+ const { buyerFetch } = await import('../api/_lib/x402-buyer-fetch.js');
+ const signer = vi.fn();
+ const result = await buyerFetch(url(), {
+ preferProtocol: 'mpp',
+ signPayment: signer,
+ caps: { address: 'capped-agent', maxPerCall: '999' },
+ });
+ expect(result.ok).toBe(false);
+ expect(result.abort).toBe(true);
+ expect(result.protocol).toBe('mpp');
+ expect(result.reason).toMatch(/per-call cap/);
+ expect(signer).not.toHaveBeenCalled();
+ expect(ledger.settled).toHaveLength(0);
+ });
+
+ it('blocks the same charge in dry run so a quote never promises what a payment would refuse', async () => {
+ const { buyerFetch } = await import('../api/_lib/x402-buyer-fetch.js');
+ const result = await buyerFetch(url(), { preferProtocol: 'mpp', dryRun: true, signPayment: vi.fn(), caps: { address: 'capped-agent', maxPerCall: '999' } });
+ expect(result.ok).toBe(false);
+ expect(result.abort).toBe(true);
+ expect(result.dryRun).toBe(true);
+ });
+});
+
+describe('the server refuses what it did not issue', () => {
+ async function challengeFor() {
+ const res = await fetch(url());
+ const { Challenge } = await import('mppx');
+ return Challenge.fromHeadersList(res.headers)[0];
+ }
+
+ it('rejects a credential whose terms were edited after issue', async () => {
+ const { solanaChargeAuthorization, chargeToRequirement } = await import('../api/_lib/mpp-solana.js');
+ const challenge = await challengeFor();
+ const payload = await signPayment({ requirement: chargeToRequirement(challenge) });
+ const forged = { ...challenge, request: { ...challenge.request, amount: '1' } };
+ const res = await fetch(url(), { headers: { authorization: solanaChargeAuthorization({ challenge: forged, transaction: payload.payload.transaction }) } });
+ expect(res.status).toBe(401);
+ expect((await res.json()).error).toBe('challenge_mismatch');
+ expect(ledger.settled).toHaveLength(0);
+ });
+
+ it('rejects a malformed Payment credential', async () => {
+ const res = await fetch(url(), { headers: { authorization: 'Payment not-a-credential' } });
+ expect(res.status).toBe(401);
+ expect(ledger.settled).toHaveLength(0);
+ });
+
+ it('answers payment required again, with a fresh challenge, for an expired one', async () => {
+ const { buildSolanaChargeChallenge, solanaChargeAuthorization, chargeToRequirement } = await import('../api/_lib/mpp-solana.js');
+ const live = await challengeFor();
+ const requirement = chargeToRequirement(live);
+ const stale = buildSolanaChargeChallenge({
+ requirement: { ...requirement, extra: { ...requirement.extra } },
+ nowSec: Math.floor(Date.now() / 1000) - 3600,
+ });
+ const payload = await signPayment({ requirement });
+ const res = await fetch(url(), { headers: { authorization: solanaChargeAuthorization({ challenge: stale.challenge, transaction: payload.payload.transaction }) } });
+ expect(res.status).toBe(402);
+ expect(res.headers.get('www-authenticate')).toMatch(/^Payment /);
+ expect(ledger.settled).toHaveLength(0);
+ });
+
+ it('settles one signed transaction once and answers a replay from the original result', async () => {
+ const { solanaChargeAuthorization, chargeToRequirement } = await import('../api/_lib/mpp-solana.js');
+ const challenge = await challengeFor();
+ const payload = await signPayment({ requirement: chargeToRequirement(challenge) });
+ const authorization = solanaChargeAuthorization({ challenge, transaction: payload.payload.transaction });
+ const first = await fetch(url(), { headers: { authorization } });
+ expect(first.status).toBe(200);
+ const second = await fetch(url(), { headers: { authorization } });
+ expect(second.headers.get('x-x402-idempotent')).toBe('replay');
+ expect(second.headers.get('payment-receipt')).toBe(first.headers.get('payment-receipt'));
+ expect(ledger.settled).toHaveLength(1);
+ });
+});
+
+describe('what a pull-mode charge cannot do', () => {
+ it('declines native SOL, split and confidential charges instead of mispaying them', async () => {
+ const { chargeToRequirement } = await import('../api/_lib/mpp-solana.js');
+ const base = { amount: '1000', currency: USDC_MAINNET, recipient: payTo, methodDetails: { network: 'mainnet', decimals: 6 } };
+ expect(chargeToRequirement({ request: base })).toMatchObject({ scheme: 'exact', amount: '1000' });
+ expect(chargeToRequirement({ request: { ...base, currency: 'sol' } })).toBeNull();
+ expect(chargeToRequirement({ request: { ...base, methodDetails: { ...base.methodDetails, splits: [{ recipient: payTo, amount: '1' }] } } })).toBeNull();
+ expect(chargeToRequirement({ request: { ...base, methodDetails: { ...base.methodDetails, confidential: true } } })).toBeNull();
+ expect(chargeToRequirement({ request: { ...base, amount: '1.5' } })).toBeNull();
+ });
+
+ it('keeps the decoded transaction a plain two-slot partial signature', async () => {
+ const challenge = await (async () => {
+ const res = await fetch(url());
+ const { Challenge } = await import('mppx');
+ return Challenge.fromHeadersList(res.headers)[0];
+ })();
+ const { chargeToRequirement } = await import('../api/_lib/mpp-solana.js');
+ const payload = await signPayment({ requirement: chargeToRequirement(challenge) });
+ const tx = getTransactionDecoder().decode(getBase64Encoder().encode(payload.payload.transaction));
+ expect(Object.keys(tx.signatures)).toContain(feePayer.address);
+ expect(tx.signatures[feePayer.address]).toBeNull();
+ expect(tx.signatures[payer.address]).toBeTruthy();
+ });
+});