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.

test

nirholase37762990a99
diff --git a/.env.example b/.env.example
index 9d3794cf3..2359819c3 100644
--- a/.env.example
+++ b/.env.example
@@ -240,6 +240,33 @@ X402_FEE_PAYER_SOLANA=2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4
# the app that exposed the paid endpoint.
X402_BUILDER_CODE_APP=three_d_agent
+# Wallet builder code our own buyer client attributes itself with when
+# making outbound paid calls (USE-20). Distinct from X402_BUILDER_CODE_APP:
+# this populates `w` on PaymentPayload.extensions["builder-code"] so the
+# settlement CBOR records both who exposed the endpoint AND who paid for it.
+X402_BUILDER_CODE_WALLET=3d_agent
+
+# Spending caps for buyer clients (USE-22). All values are micro-USD
+# (6-decimal atomics of USDC); leave any line blank to skip that cap.
+# Example: 1_000_000 = $1.00; 100_000 = $0.10; 1_000 = $0.001.
+# Per-call ceiling enforced before signing; hourly/daily are sliding
+# windows tracked in Redis (server) or localStorage (browser).
+X402_MAX_PER_CALL_ATOMIC=1000000
+X402_MAX_PER_HOUR_ATOMIC=10000000
+X402_MAX_PER_DAY_ATOMIC=100000000
+
+# ── x402 access-control bypass (USE-23) ────────────────────────────────────
+# Shared secret for internal service-to-service calls. Any Vercel function
+# (cron job, webhook handler, the agent runtime) that hits one of our own
+# paid /api/x402/* endpoints sends `X-API-Key: $INTERNAL_API_KEY` to skip
+# the 402 challenge — we don't pay ourselves to call our own infra.
+# Generate: openssl rand -base64 32
+# Compared with constant-time equality in api/_lib/x402/access-control.js.
+# Leave unset to disable internal bypass (subscription keys and OAuth bypass
+# still work). Partner / subscription keys are issued at
+# POST /api/x402/admin/subscriptions and stored hashed in x402_subscriptions.
+INTERNAL_API_KEY=
+
# ── x402 Offer & Receipt extension (USE-17) ────────────────────────────────
# Signs every 402 offer and every settled-payment receipt so buyers get
# cryptographic proof of the interaction. Verifiers resolve the signer key via
@@ -329,3 +356,48 @@ DEV_TO_API_KEY=
# the syndicator auto-discovers it via /v1/me and caches in-memory.
MEDIUM_INTEGRATION_TOKEN=
MEDIUM_AUTHOR_ID=
+
+# ── x402 MCP bridge (USE-11) ────────────────────────────────────────────────
+# The mcp-bridge/ workspace is a Claude Desktop / Cursor MCP server that
+# auto-pays for x402-paid HTTP endpoints. It registers a single
+# `call_paid_endpoint` fallback tool plus one tool per resource discovered
+# from the Coinbase x402 Bazaar. Channel state (batch-settlement vouchers)
+# persists in ~/.x402-mcp-bridge/channels/client/ so Claude Desktop restarts
+# don't re-deposit on the next call.
+#
+# Buyer keys — one of EVM or SVM is required for the bridge to start.
+# These keys SIGN PAYMENTS. Never share them, never commit them, and never
+# point them at a wallet you don't control.
+MCP_BRIDGE_EVM_PRIVATE_KEY=
+MCP_BRIDGE_SVM_PRIVATE_KEY=
+# Per-call spending cap in atomic units of the accept's asset. Default 100000
+# = $0.10 USDC (6 decimals). Payments above this are aborted with a clear
+# error before any signature is created.
+MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC=100000
+# Max number of bazaar tools to register at startup. Set 0 to disable
+# bazaar-driven dynamic tools (the fallback call_paid_endpoint still works).
+MCP_BRIDGE_DISCOVER_LIMIT=20
+# Override the bazaar discovery endpoint (default = CDP mainnet bazaar).
+MCP_BRIDGE_BAZAAR_URL=https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources
+# Batch-settlement tuning. The bridge pre-funds N request-amounts on the first
+# call so subsequent voucher-only calls don't pay gas. MAX_DEPOSIT_ATOMIC is a
+# hard ceiling on any single deposit (default $5).
+MCP_BRIDGE_BATCH_DEPOSIT_MULTIPLIER=5
+MCP_BRIDGE_MAX_DEPOSIT_ATOMIC=5000000
+# Override where batch-settlement channel state is persisted. Defaults to
+# ~/.x402-mcp-bridge/channels. Restart-safe.
+X402_MCP_BRIDGE_CHANNELS_DIR=
+
+# ── USE-10: @3d-agent/mcp-server (paid MCP tools for Claude Desktop / Cursor) ─
+# Wallets that RECEIVE USDC payments when an MCP client pays for a tool call.
+# Default to the existing X402_PAY_TO_* wallets when unset.
+MCP_EVM_PAYMENT_ADDRESS=
+MCP_SVM_PAYMENT_ADDRESS=
+# Override the previewUrl returned by get_pose_seed.
+MCP_POSE_PREVIEW_BASE=https://three.ws/pose
+# Per-chain RPC override for agent_reputation reads. Example:
+# MCP_AGENT_REP_RPC_8453=https://mainnet.base.org
+# MCP_AGENT_REP_RPC_42161=https://arb1.arbitrum.io/rpc
+# Block window scanned for recent ReputationSubmitted/Staked events (default
+# 200000). Lower for high-RPS chains to keep RPC calls under provider limits.
+MCP_AGENT_REP_LOG_WINDOW=200000
diff --git a/agent-payments-sdk/package.json b/agent-payments-sdk/package.json
index af26f3258..d506dfb6a 100644
--- a/agent-payments-sdk/package.json
+++ b/agent-payments-sdk/package.json
@@ -41,6 +41,11 @@
"types": "./dist/x402/index.d.ts",
"import": "./dist/x402/index.js",
"require": "./dist/x402/index.cjs"
+ },
+ "./a2a": {
+ "types": "./dist/a2a-helpers.d.ts",
+ "import": "./dist/a2a-helpers.js",
+ "require": "./dist/a2a-helpers.cjs"
}
},
"files": [
diff --git a/agent-payments-sdk/src/a2a-helpers.ts b/agent-payments-sdk/src/a2a-helpers.ts
new file mode 100644
index 000000000..96a1ed2dd
--- /dev/null
+++ b/agent-payments-sdk/src/a2a-helpers.ts
@@ -0,0 +1,473 @@
+// agent-payments-sdk
+// Copyright (c) 2026 nirholas | x.com/nichxbt | github.com/nirholas
+// All rights reserved.
+//
+// A2A (Agent-to-Agent) x402 client helpers.
+//
+// Drives the two-leg A2A x402 handshake described at
+// https://github.com/google-agentic-commerce/a2a-x402/blob/main/spec/v0.1/spec.md
+//
+// Other agents in this workspace import these to call a paid A2A skill on a
+// peer agent without re-implementing the JSON-RPC + EIP-3009 signing dance.
+//
+// Usage:
+// import { payA2A, createPrivateKeySigner } from "@pump-fun/agent-payments-sdk/a2a";
+//
+// const signer = await createPrivateKeySigner(process.env.AGENT_PRIVATE_KEY!);
+// const result = await payA2A({
+// endpoint: "https://three.ws/api/agents/a2a-paid",
+// signer,
+// text: "Inspect https://example.com/model.glb",
+// });
+// console.log(result.task.artifacts);
+
+import { privateKeyToAccount } from "viem/accounts";
+import type { Address, Hex } from "viem";
+
+export const A2A_X402_EXTENSION_URI =
+ "https://github.com/google-a2a/a2a-x402/v0.1";
+export const A2A_EXTENSIONS_HEADER = "X-A2A-Extensions";
+
+// ── Errors ────────────────────────────────────────────────────────────────
+
+export class A2AClientError extends Error {
+ code: string;
+ details?: unknown;
+ constructor(code: string, message: string, details?: unknown) {
+ super(message);
+ this.name = "A2AClientError";
+ this.code = code;
+ this.details = details;
+ }
+}
+
+// ── Types ─────────────────────────────────────────────────────────────────
+
+export interface A2ASigner {
+ address: Address;
+ signAuthorization(args: {
+ domain: {
+ name: string;
+ version: string;
+ chainId: number;
+ verifyingContract: Address;
+ };
+ message: {
+ from: Address;
+ to: Address;
+ value: string;
+ validAfter: number;
+ validBefore: number;
+ nonce: Hex;
+ };
+ }): Promise<Hex>;
+}
+
+export interface A2APaymentRequirementsAccept {
+ scheme: string;
+ network: string;
+ amount: string;
+ asset: Address;
+ payTo: Address;
+ maxTimeoutSeconds?: number;
+ extra?: {
+ name?: string;
+ version?: string;
+ decimals?: number;
+ [key: string]: unknown;
+ };
+}
+
+export interface A2APaymentRequirements {
+ x402Version: number;
+ error?: string;
+ resource: { url: string; description?: string; mimeType?: string };
+ accepts: A2APaymentRequirementsAccept[];
+}
+
+export interface A2APaymentPayload {
+ x402Version: number;
+ scheme: string;
+ network: string;
+ resource: { url: string; mimeType?: string; description?: string };
+ accepted: A2APaymentRequirementsAccept;
+ payload: {
+ signature: Hex;
+ authorization: {
+ from: Address;
+ to: Address;
+ value: string;
+ validAfter: string;
+ validBefore: string;
+ nonce: Hex;
+ };
+ };
+ extensions?: Record<string, unknown>;
+}
+
+export interface A2ATaskMessagePart {
+ kind: "text" | "data" | "image" | "file";
+ text?: string;
+ data?: unknown;
+ name?: string;
+ mimeType?: string;
+}
+
+export interface A2ATaskMessage {
+ kind: "message";
+ role: "agent" | "user";
+ messageId?: string;
+ taskId?: string;
+ parts: A2ATaskMessagePart[];
+ metadata?: Record<string, unknown>;
+}
+
+export interface A2ATask {
+ kind: "task";
+ id: string;
+ status: { state: string; message?: A2ATaskMessage };
+ artifacts?: Array<{
+ artifactId?: string;
+ name?: string;
+ description?: string;
+ parts?: A2ATaskMessagePart[];
+ mimeType?: string;
+ data?: unknown;
+ }>;
+}
+
+export interface A2APaymentResult {
+ task: A2ATask;
+ state: string;
+ status: string | null;
+ receipts: Array<{
+ success: boolean;
+ transaction?: string;
+ network?: string;
+ payer?: string | null;
+ errorReason?: string;
+ }>;
+ error: string | null;
+ lifecycle: string[] | null;
+}
+
+// ── Signers ───────────────────────────────────────────────────────────────
+
+export async function createPrivateKeySigner(privateKey: string): Promise<A2ASigner> {
+ if (!privateKey || typeof privateKey !== "string") {
+ throw new A2AClientError(
+ "invalid_signer",
+ "createPrivateKeySigner: hex string required",
+ );
+ }
+ const account = privateKeyToAccount(
+ privateKey.startsWith("0x") ? (privateKey as Hex) : (`0x${privateKey}` as Hex),
+ );
+ return {
+ address: account.address,
+ signAuthorization: async ({ domain, message }) =>
+ account.signTypedData({
+ domain,
+ types: {
+ TransferWithAuthorization: [
+ { name: "from", type: "address" },
+ { name: "to", type: "address" },
+ { name: "value", type: "uint256" },
+ { name: "validAfter", type: "uint256" },
+ { name: "validBefore", type: "uint256" },
+ { name: "nonce", type: "bytes32" },
+ ],
+ },
+ primaryType: "TransferWithAuthorization",
+ message,
+ }),
+ };
+}
+
+// ── Payload helpers ───────────────────────────────────────────────────────
+
+const CHAIN_ID_BY_NETWORK: Record<string, number> = {
+ "eip155:8453": 8453,
+ "eip155:84532": 84532,
+ "eip155:1": 1,
+ "eip155:137": 137,
+ "eip155:42161": 42161,
+};
+
+function chainIdFor(network: string): number {
+ if (CHAIN_ID_BY_NETWORK[network]) return CHAIN_ID_BY_NETWORK[network];
+ const m = /^eip155:(\d+)$/.exec(network);
+ if (m && m[1]) return Number(m[1]);
+ throw new A2AClientError(
+ "unsupported_network",
+ `a2a-helpers: cannot derive chainId from ${network}`,
+ );
+}
+
+function randomHex32(): Hex {
+ // 32 bytes of randomness as 0x-prefixed hex. crypto.getRandomValues is
+ // available in Node 18+ and every modern runtime.
+ const bytes = new Uint8Array(32);
+ crypto.getRandomValues(bytes);
+ let hex = "0x";
+ for (const b of bytes) hex += b.toString(16).padStart(2, "0");
+ return hex as Hex;
+}
+
+export async function buildEvmExactPayload(args: {
+ accept: A2APaymentRequirementsAccept;
+ signer: A2ASigner;
+ resource: { url: string; mimeType?: string; description?: string };
+}): Promise<A2APaymentPayload> {
+ const { accept, signer, resource } = args;
+ if (accept.scheme !== "exact") {
+ throw new A2AClientError(
+ "unsupported_scheme",
+ `a2a-helpers: only exact scheme supported, got ${accept.scheme}`,
+ );
+ }
+ const chainId = chainIdFor(accept.network);
+ const validAfter = 0;
+ const validBefore = Math.floor(Date.now() / 1000) + (accept.maxTimeoutSeconds || 600);
+ const nonce = randomHex32();
+ const domain = {
+ name: accept.extra?.name || "USD Coin",
+ version: accept.extra?.version || "2",
+ chainId,
+ verifyingContract: accept.asset,
+ };
+ const message = {
+ from: signer.address,
+ to: accept.payTo,
+ value: accept.amount,
+ validAfter,
+ validBefore,
+ nonce,
+ };
+ const signature = await signer.signAuthorization({ domain, message });
+ return {
+ x402Version: 2,
+ scheme: "exact",
+ network: accept.network,
+ resource,
+ accepted: accept,
+ payload: {
+ signature,
+ authorization: {
+ from: signer.address,
+ to: accept.payTo,
+ value: accept.amount,
+ validAfter: String(validAfter),
+ validBefore: String(validBefore),
+ nonce,
+ },
+ },
+ };
+}
+
+// ── JSON-RPC plumbing ─────────────────────────────────────────────────────
+
+function jsonRpcRequest(message: A2ATaskMessage) {
+ const id =
+ typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`;
+ return {
+ jsonrpc: "2.0" as const,
+ id,
+ method: "message/send" as const,
+ params: { message },
+ };
+}
+
+async function postJsonRpc(endpoint: string, body: unknown): Promise<A2ATask> {
+ const res = await fetch(endpoint, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ accept: "application/json",
+ [A2A_EXTENSIONS_HEADER]: A2A_X402_EXTENSION_URI,
+ },
+ body: JSON.stringify(body),
+ });
+ const text = await res.text();
+ let parsed: { result?: A2ATask; error?: { code: number; message: string; data?: unknown } };
+ try {
+ parsed = text ? JSON.parse(text) : {};
+ } catch (err) {
+ throw new A2AClientError(
+ "parse_error",
+ `non-JSON A2A reply: ${(err as Error).message}`,
+ { text },
+ );
+ }
+ if (!res.ok) {
+ throw new A2AClientError("transport_error", `HTTP ${res.status}`, {
+ status: res.status,
+ body: parsed,
+ });
+ }
+ if (parsed.error) {
+ throw new A2AClientError(
+ "jsonrpc_error",
+ parsed.error.message || "JSON-RPC error",
+ parsed.error,
+ );
+ }
+ if (!parsed.result || parsed.result.kind !== "task") {
+ throw new A2AClientError("invalid_reply", "expected `kind: task` in A2A reply", parsed.result);
+ }
+ return parsed.result;
+}
+
+function readPaymentRequired(task: A2ATask): A2APaymentRequirements | null {
+ const meta = task.status?.message?.metadata as Record<string, unknown> | undefined;
+ if (!meta || meta["x402.payment.status"] !== "payment-required") return null;
+ const required = meta["x402.payment.required"];
+ if (
+ !required ||
+ typeof required !== "object" ||
+ !Array.isArray((required as A2APaymentRequirements).accepts)
+ ) {
+ throw new A2AClientError(
+ "malformed_payment_required",
+ "task carries payment-required status but no accepts list",
+ required,
+ );
+ }
+ return required as A2APaymentRequirements;
+}
+
+function readReceiptInfo(task: A2ATask) {
+ const meta = (task.status?.message?.metadata || {}) as Record<string, unknown>;
+ return {
+ status: (meta["x402.payment.status"] as string) || null,
+ receipts: Array.isArray(meta["x402.payment.receipts"])
+ ? (meta["x402.payment.receipts"] as A2APaymentResult["receipts"])
+ : [],
+ error: (meta["x402.payment.error"] as string) || null,
+ lifecycle: Array.isArray(meta["x402.payment.lifecycle"])
+ ? (meta["x402.payment.lifecycle"] as string[])
+ : null,
+ };
+}
+
+const DEFAULT_NETWORK_PREFERENCE = ["eip155:8453", "eip155:84532", "eip155:1"];
+
+function pickAccept(
+ accepts: A2APaymentRequirementsAccept[],
+ preference?: string[],
+): A2APaymentRequirementsAccept {
+ const order = preference?.length ? preference : DEFAULT_NETWORK_PREFERENCE;
+ for (const net of order) {
+ const match = accepts.find((a) => a.network === net && a.scheme === "exact");
+ if (match) return match;
+ }
+ for (const a of accepts) {
+ if (a.scheme === "exact" && /^eip155:\d+$/.test(a.network)) return a;
+ }
+ throw new A2AClientError(
+ "no_supported_accept",
+ "a2a-helpers: peer offered no supported (scheme=exact, EVM) accept",
+ { accepts: accepts.map(({ network, scheme }) => ({ network, scheme })) },
+ );
+}
+
+// ── Public API ────────────────────────────────────────────────────────────
+
+export async function requestA2AQuote(args: {
+ endpoint: string;
+ text?: string;
+ taskId?: string;
+}): Promise<{ task: A2ATask; required: A2APaymentRequirements; taskId: string }> {
+ const message: A2ATaskMessage = {
+ kind: "message",
+ role: "user",
+ messageId: typeof crypto.randomUUID === "function" ? crypto.randomUUID() : undefined,
+ ...(args.taskId ? { taskId: args.taskId } : {}),
+ parts: [{ kind: "text", text: args.text || "Initiate paid skill." }],
+ };
+ const task = await postJsonRpc(args.endpoint, jsonRpcRequest(message));
+ const required = readPaymentRequired(task);
+ if (!required) {
+ throw new A2AClientError(
+ "unexpected_state",
+ `expected payment-required, got state ${task.status?.state || "unknown"}`,
+ { task },
+ );
+ }
+ return { task, required, taskId: task.id };
+}
+
+export async function submitA2APayment(args: {
+ endpoint: string;
+ taskId: string;
+ paymentPayload: A2APaymentPayload;
+ text?: string;
+}): Promise<A2APaymentResult> {
+ const message: A2ATaskMessage = {
+ kind: "message",
+ role: "user",
+ messageId: typeof crypto.randomUUID === "function" ? crypto.randomUUID() : undefined,
+ taskId: args.taskId,
+ parts: [{ kind: "text", text: args.text || "Here is the payment authorization." }],
+ metadata: {
+ "x402.payment.status": "payment-submitted",
+ "x402.payment.payload": args.paymentPayload,
+ },
+ };
+ const task = await postJsonRpc(args.endpoint, jsonRpcRequest(message));
+ const receipt = readReceiptInfo(task);
+ return {
+ task,
+ state: task.status?.state || "unknown",
+ ...receipt,
+ };
+}
+
+export interface PayA2AOptions {
+ endpoint: string;
+ signer: A2ASigner;
+ text?: string;
+ networkPreference?: string[];
+ onQuote?: (args: {
+ task: A2ATask;
+ required: A2APaymentRequirements;
+ taskId: string;
+ }) => void | Promise<void>;
+}
+
+export async function payA2A(opts: PayA2AOptions): Promise<A2APaymentResult> {
+ if (!opts.endpoint) {
+ throw new A2AClientError("invalid_args", "payA2A: endpoint required");
+ }
+ if (!opts.signer || typeof opts.signer.signAuthorization !== "function") {
+ throw new A2AClientError(
+ "invalid_signer",
+ "payA2A: signer with signAuthorization() required",
+ );
+ }
+
+ const quote = await requestA2AQuote({ endpoint: opts.endpoint, text: opts.text });
+ if (opts.onQuote) await opts.onQuote(quote);
+
+ const accept = pickAccept(quote.required.accepts, opts.networkPreference);
+ const resource = quote.required.resource || {
+ url: opts.endpoint,
+ mimeType: "application/json",
+ };
+ const paymentPayload = await buildEvmExactPayload({ accept, signer: opts.signer, resource });
+
+ const result = await submitA2APayment({
+ endpoint: opts.endpoint,
+ taskId: quote.taskId,
+ paymentPayload,
+ });
+
+ if (result.state !== "completed") {
+ throw new A2AClientError(
+ result.error || "payment_failed",
+ result.receipts[0]?.errorReason || `A2A task ended in state ${result.state}`,
+ result,
+ );
+ }
+ return result;
+}
diff --git a/agent-payments-sdk/src/index.ts b/agent-payments-sdk/src/index.ts
index a16553cbc..c64fd5147 100644
--- a/agent-payments-sdk/src/index.ts
+++ b/agent-payments-sdk/src/index.ts
@@ -12,3 +12,4 @@ export * from "./evm/index.js";
export * as solana from "./solana/index.js";
export * as evm from "./evm/index.js";
export * as x402Evm from "./x402/index.js";
+export * as a2a from "./a2a-helpers.js";
diff --git a/agent-payments-sdk/src/solana/x402/client.ts b/agent-payments-sdk/src/solana/x402/client.ts
index f6e0d2087..9828d02e3 100644
--- a/agent-payments-sdk/src/solana/x402/client.ts
+++ b/agent-payments-sdk/src/solana/x402/client.ts
@@ -32,6 +32,8 @@ import {
getPaymentRequiredFromResponse,
} from "./headers";
import type {
+ AuthHintsCredentials,
+ AuthHintsExtension,
X402ClientConfig,
PaymentPayload,
PaymentRequired,
@@ -45,6 +47,9 @@ import {
SOLANA_MAINNET,
} from "./types";
+const AUTH_HINTS_KEY = "auth-hints";
+const SIWX_HEADER = "SIGN-IN-WITH-X";
+
// ─── Client-side x402 fetch wrapper ─────────────────────────────────────────
/**
@@ -87,6 +92,7 @@ export function createX402Fetch(
connection,
network = SOLANA_MAINNET,
confirmationTimeoutMs = 30_000,
+ onAuthRequired,
} = config;
return async (
@@ -100,6 +106,36 @@ export function createX402Fetch(
const paymentRequired = await getPaymentRequiredFromResponse(response);
if (!paymentRequired) return response;
+ // USE-21: if the 402 advertises `auth-hints` and the caller wired up an
+ // onAuthRequired callback, let them attach OAuth/SIWX credentials and
+ // bypass payment entirely. Falls through to the payment flow when the
+ // callback returns null or no credentials match the offered methods.
+ const authExt = extractAuthHints(paymentRequired);
+ if (authExt && typeof onAuthRequired === "function") {
+ let creds: AuthHintsCredentials | null | undefined;
+ try {
+ creds = await onAuthRequired({
+ extension: authExt,
+ accepts: paymentRequired.accepts,
+ resource: paymentRequired.resource,
+ });
+ } catch {
+ creds = null;
+ }
+ if (creds && (creds.oauth2AccessToken || creds.siwxHeader)) {
+ const retryInit: RequestInit = { ...init };
+ const headers = new Headers(retryInit.headers);
+ if (creds.oauth2AccessToken) {
+ headers.set("Authorization", `Bearer ${creds.oauth2AccessToken}`);
+ }
+ if (creds.siwxHeader) {
+ headers.set(SIWX_HEADER, creds.siwxHeader);
+ }
+ retryInit.headers = headers;
+ return fetch(input, retryInit);
+ }
+ }
+
// Find a compatible requirement
const accepted = selectRequirement(paymentRequired, network);
if (!accepted) return response;
@@ -154,18 +190,34 @@ function selectRequirement(
paymentRequired: PaymentRequired,
network: string,
): PaymentRequirements | null {
+ // USE-21 auth-hints: skip free-tier accepts entries (amount === "0") that
+ // require authentication. The auth-hints code path handles them; the
+ // payment path must not try to settle a zero-amount transfer because the
+ // facilitator will reject it as invalid_payload.
+ const payable = paymentRequired.accepts.filter(
+ (r) => String(r.amount ?? "") !== "0",
+ );
// Prefer pump-agent scheme on the matching network, then fall back to exact
return (
- paymentRequired.accepts.find(
- (r) => r.scheme === "pump-agent" && r.network === network,
- ) ??
- paymentRequired.accepts.find(
- (r) => r.scheme === "exact" && r.network === network,
- ) ??
+ payable.find((r) => r.scheme === "pump-agent" && r.network === network) ??
+ payable.find((r) => r.scheme === "exact" && r.network === network) ??
null
);
}
+// ─── auth-hints extraction ──────────────────────────────────────────────────
+
+function extractAuthHints(
+ paymentRequired: PaymentRequired,
+): AuthHintsExtension | null {
+ const ext = paymentRequired.extensions?.[AUTH_HINTS_KEY] as
+ | AuthHintsExtension
+ | undefined;
+ if (!ext || typeof ext !== "object") return null;
+ if (!ext.info || !Array.isArray(ext.info.authRequirements)) return null;
+ return ext;
+}
+
// ─── Payment Proof Builder ──────────────────────────────────────────────────
async function buildPaymentProof(
diff --git a/agent-payments-sdk/tsup.config.ts b/agent-payments-sdk/tsup.config.ts
index 6634dee2d..c7a2aab7e 100644
--- a/agent-payments-sdk/tsup.config.ts
+++ b/agent-payments-sdk/tsup.config.ts
@@ -12,6 +12,7 @@ export default defineConfig({
"solana/legacy-agent-payments/index": "src/solana/legacy-agent-payments/index.ts",
"solana/solana-agent-kit/index": "src/solana/solana-agent-kit/index.ts",
"x402/index": "src/x402/index.ts",
+ "a2a-helpers": "src/a2a-helpers.ts",
},
format: ["esm", "cjs"],
dts: true,
diff --git a/api/_lib/env.js b/api/_lib/env.js
index 8c509ffe3..2b8514f0f 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -240,6 +240,25 @@ export const env = {
get X402_BUILDER_CODE_APP() {
return opt('X402_BUILDER_CODE_APP');
},
+ // Wallet builder code our outbound buyer clients self-attribute with.
+ // Populates PaymentPayload.extensions["builder-code"].w so settlement
+ // CBOR records the wallet that paid alongside the app that exposed.
+ get X402_BUILDER_CODE_WALLET() {
+ return opt('X402_BUILDER_CODE_WALLET');
+ },
+
+ // Spending caps for buyer clients (USE-22). Atomic micro-USD; leave
+ // unset to disable that cap. Read by x402-spending-cap.js when callers
+ // don't pass an explicit per-route override.
+ get X402_MAX_PER_CALL_ATOMIC() {
+ return opt('X402_MAX_PER_CALL_ATOMIC');
+ },
+ get X402_MAX_PER_HOUR_ATOMIC() {
+ return opt('X402_MAX_PER_HOUR_ATOMIC');
+ },
+ get X402_MAX_PER_DAY_ATOMIC() {
+ return opt('X402_MAX_PER_DAY_ATOMIC');
+ },
// USE-23: shared secret that lets internal Vercel functions skip the 402
// challenge on our own paid endpoints by sending X-API-Key: <this value>.
diff --git a/api/_lib/siwx-server.js b/api/_lib/siwx-server.js
index 9da670fac..e55e83f88 100644
--- a/api/_lib/siwx-server.js
+++ b/api/_lib/siwx-server.js
@@ -16,6 +16,7 @@
import {
declareSIWxExtension,
parseSIWxHeader,
+ siwxResourceServerExtension,
validateSIWxMessage,
verifySIWxSignature,
SIGN_IN_WITH_X,
@@ -49,20 +50,37 @@ export function hasEvmVerifier() {
return Boolean(env.BASE_RPC_URL);
}
-// Build the extensions block that goes into the 402 body when SIWX is
-// enabled for an endpoint. `network` accepts the same CAIP-2 strings the
-// rest of paidEndpoint() uses (e.g. 'eip155:8453', 'solana:5eykt...').
-export function declareSiwxExtensionFor({ networks, statement, expirationSeconds = 300 }) {
+// Build the SIWX extension block for the 402 body. `declareSIWxExtension`
+// alone returns a stub: the SDK pipeline normally calls
+// `siwxResourceServerExtension.enrichPaymentRequiredResponse` to fill in
+// nonce, issuedAt, domain, uri, and the supportedChains list. paidEndpoint()
+// doesn't run that pipeline, so we invoke enrich() ourselves with the
+// context (resourceUrl + requirements) the helper already has.
+export async function declareSiwxExtensionFor({
+ networks,
+ resourceUrl,
+ statement,
+ expirationSeconds = 300,
+}) {
const list = Array.isArray(networks) ? networks : [networks];
const unique = [...new Set(list.filter(Boolean))];
if (!unique.length) {
throw new Error('declareSiwxExtensionFor: at least one network required');
}
- return declareSIWxExtension({
+ if (!resourceUrl) {
+ throw new Error('declareSiwxExtensionFor: resourceUrl required');
+ }
+ const stub = declareSIWxExtension({
network: unique.length === 1 ? unique[0] : unique,
statement,
expirationSeconds,
});
+ const declaration = stub[SIGN_IN_WITH_X];
+ const enriched = await siwxResourceServerExtension.enrichPaymentRequiredResponse(declaration, {
+ resourceInfo: { url: resourceUrl },
+ requirements: unique.map((network) => ({ network })),
+ });
+ return { [SIGN_IN_WITH_X]: enriched };
}
// Given an incoming Vercel request, attempt to authenticate via
diff --git a/api/_lib/x402-buyer-axios.js b/api/_lib/x402-buyer-axios.js
new file mode 100644
index 000000000..646e9238f
--- /dev/null
+++ b/api/_lib/x402-buyer-axios.js
@@ -0,0 +1,146 @@
+// Axios variant of buyer-fetch (USE-22).
+//
+// Same surface as x402-buyer-fetch.js — `caps`, `signPayment`,
+// `preferNetwork` — but wraps an axios instance so callers in the
+// existing axios-based code paths can adopt cap enforcement without
+// rewriting to fetch. The cap install + ledger rollback semantics
+// match the fetch helper exactly.
+
+import { enforceCap, commit, rollbackReservation } from './x402-spending-cap.js';
+import { BUILDER_CODE } from './x402-builder-code.js';
+import { env } from './env.js';
+
+function selectRequirement(challenge, prefer) {
+ const accepts = Array.isArray(challenge?.accepts) ? challenge.accepts : [];
+ if (typeof prefer === 'function') {
+ const picked = prefer(accepts);
+ if (picked) return picked;
+ }
+ if (typeof prefer === 'string') {
+ const found = accepts.find((a) => a.network === prefer);
+ if (found) return found;
+ }
+ return accepts[0] || null;
+}
+
+function ensureBuilderCodeEcho(challenge, paymentPayload) {
+ const declared = challenge?.extensions?.[BUILDER_CODE];
+ const declaredA = declared?.info?.a;
+ if (!declaredA) return paymentPayload;
+ const existing = paymentPayload.extensions || {};
+ const existingBlock = existing[BUILDER_CODE] || {};
+ const echo = { ...existingBlock, a: declaredA };
+ if (env.X402_BUILDER_CODE_WALLET && !echo.w) {
+ echo.w = env.X402_BUILDER_CODE_WALLET;
+ }
+ paymentPayload.extensions = { ...existing, [BUILDER_CODE]: echo };
+ return paymentPayload;
+}
+
+function b64encode(obj) {
+ return Buffer.from(JSON.stringify(obj), 'utf8').toString('base64');
+}
+
+function b64decode(s) {
+ if (!s) return null;
+ try {
+ return JSON.parse(Buffer.from(s, 'base64').toString('utf8'));
+ } catch {
+ return null;
+ }
+}
+
+// Wrap an axios instance with one extra method, `requestPaid(config)`, that
+// performs the cap-enforced 402 dance. We avoid mutating the global axios
+// default; callers pass an already-constructed instance (or `axios` itself
+// if they don't care about isolation).
+//
+// Required config fields beyond axios's normal shape:
+// signPayment({ requirement, challenge }) — returns paymentPayload
+// caps — optional, same as enforceCap
+// preferNetwork — optional, network selector
+export function wrapAxiosWithPaidRequest(axiosInstance) {
+ if (!axiosInstance || typeof axiosInstance.request !== 'function') {
+ throw new Error('wrapAxiosWithPaidRequest: axios instance required');
+ }
+
+ async function requestPaid(config) {
+ const { caps, signPayment, preferNetwork, ...axiosConfig } = config;
+ if (typeof signPayment !== 'function') {
+ throw new Error('requestPaid: signPayment({ requirement }) callback is required');
+ }
+ // axios throws on non-2xx by default; toggle validateStatus so we can
+ // see the 402 challenge.
+ const probe = await axiosInstance.request({
+ ...axiosConfig,
+ validateStatus: () => true,
+ });
+ if (probe.status !== 402) {
+ return probe;
+ }
+ const challenge =
+ (typeof probe.data === 'object' && probe.data) ||
+ b64decode(probe.headers?.['payment-required']);
+ if (!challenge || !Array.isArray(challenge.accepts)) {
+ const err = new Error('invalid_402_body');
+ err.response = probe;
+ throw err;
+ }
+ const requirement = selectRequirement(challenge, preferNetwork);
+ if (!requirement) {
+ const err = new Error('no_acceptable_requirement');
+ err.response = probe;
+ throw err;
+ }
+
+ let reservation = null;
+ if (caps) {
+ const verdict = await enforceCap({ requirement, opts: caps });
+ if (verdict.abort) {
+ const err = new Error(verdict.reason);
+ err.code = 'cap_exceeded';
+ err.abort = true;
+ throw err;
+ }
+ reservation = verdict.reservation;
+ }
+
+ let paymentPayload;
+ try {
+ paymentPayload = await signPayment({ requirement, challenge });
+ } catch (err) {
+ if (reservation) await rollbackReservation(reservation).catch(() => undefined);
+ throw err;
+ }
+ ensureBuilderCodeEcho(challenge, paymentPayload);
+
+ const xPayment = b64encode(paymentPayload);
+ try {
+ const paid = await axiosInstance.request({
+ ...axiosConfig,
+ headers: { ...(axiosConfig.headers || {}), 'X-PAYMENT': xPayment },
+ validateStatus: () => true,
+ });
+ if (paid.status >= 200 && paid.status < 300) {
+ if (reservation) {
+ await commit(reservation, {
+ network: requirement.network,
+ asset: requirement.asset,
+ });
+ }
+ paid.x402Payment = paymentPayload;
+ paid.x402Settled = b64decode(paid.headers?.['x-payment-response']);
+ return paid;
+ }
+ if (reservation) await rollbackReservation(reservation).catch(() => undefined);
+ return paid;
+ } catch (err) {
+ if (reservation) await rollbackReservation(reservation).catch(() => undefined);
+ throw err;
+ }
+ }
+
+ const wrapped = Object.create(axiosInstance);
+ wrapped.requestPaid = requestPaid;
+ return wrapped;
+}
diff --git a/api/_lib/x402-buyer-fetch.js b/api/_lib/x402-buyer-fetch.js
new file mode 100644
index 000000000..824112294
--- /dev/null
+++ b/api/_lib/x402-buyer-fetch.js
@@ -0,0 +1,196 @@
+// Buyer-side fetch helper with spending-cap enforcement (USE-22).
+//
+// Wraps the standard 402 dance into one call, with `caps` enforcement
+// installed via the lifecycle-style enforceCap → commit / rollback
+// transaction so caps are honored even for callers that aren't using
+// the @x402/fetch SDK directly.
+//
+// Usage:
+// const { ok, response, payment, settled } = await buyerFetch(url, {
+// method: 'POST',
+// body: { url: 'https://three.ws/avatar.glb' },
+// caps: {
+// address: '0xMyAgent',
+// maxPerCall: '50000', // $0.05 per call
+// maxPerHour: '1000000', // $1/hr
+// maxPerDay: '5000000', // $5/day
+// },
+// signPayment, // ({ requirement }) => paymentPayload
+// });
+//
+// `signPayment` is supplied by the caller because signing logic varies
+// (EIP-712 transferWithAuthorization for Base, signed VersionedTransaction
+// for Solana, contract call for BSC). This module owns the cap check +
+// header dance + settlement parsing only.
+
+import { enforceCap, commit, rollbackReservation } from './x402-spending-cap.js';
+import { BUILDER_CODE } from './x402-builder-code.js';
+import { env } from './env.js';
+
+function selectRequirement(challenge, prefer) {
+ const accepts = Array.isArray(challenge?.accepts) ? challenge.accepts : [];
+ if (typeof prefer === 'function') {
+ const picked = prefer(accepts);
+ if (picked) return picked;
+ }
+ if (typeof prefer === 'string') {
+ const found = accepts.find((a) => a.network === prefer);
+ if (found) return found;
+ }
+ return accepts[0] || null;
+}
+
+function ensureBuilderCodeEcho(challenge, paymentPayload) {
+ const declared = challenge?.extensions?.[BUILDER_CODE];
+ const declaredA = declared?.info?.a;
+ if (!declaredA) return paymentPayload;
+ const existing = paymentPayload.extensions || {};
+ const existingBlock = existing[BUILDER_CODE] || {};
+ const echo = { ...existingBlock, a: declaredA };
+ if (env.X402_BUILDER_CODE_WALLET && !echo.w) {
+ echo.w = env.X402_BUILDER_CODE_WALLET;
+ }
+ paymentPayload.extensions = { ...existing, [BUILDER_CODE]: echo };
+ return paymentPayload;
+}
+
+function bodyToInit(method, body, headers = {}) {
+ if (body == null) return { method, headers };
+ if (typeof body === 'string' || body instanceof ArrayBuffer || body instanceof Uint8Array) {
+ return { method, headers, body };
+ }
+ return {
+ method,
+ headers: { 'content-type': 'application/json', ...headers },
+ body: JSON.stringify(body),
+ };
+}
+
+function b64encode(obj) {
+ return Buffer.from(JSON.stringify(obj), 'utf8').toString('base64');
+}
+
+function b64decode(s) {
+ if (!s) return null;
+ try {
+ return JSON.parse(Buffer.from(s, 'base64').toString('utf8'));
+ } catch {
+ return null;
+ }
+}
+
+// One-shot paid request. Returns:
+// { ok: true, result, response, payment, settled }
+// { ok: false, abort: true, reason } — cap rejected; no network call
+// { ok: false, status, error } — server returned non-2xx
+export async function buyerFetch(url, opts = {}) {
+ const {
+ method = 'GET',
+ body,
+ headers,
+ caps,
+ signPayment,
+ preferNetwork,
+ fetchImpl = globalThis.fetch,
+ } = opts;
+
+ if (typeof signPayment !== 'function') {
+ throw new Error('buyerFetch: signPayment({ requirement }) callback is required');
+ }
+
+ const init = bodyToInit(method, body, headers);
+ const probe = await fetchImpl(url, init);
+ if (probe.status !== 402) {
+ const text = await probe.text();
+ const parsed = safeJson(text);
+ return {
+ ok: probe.ok,
+ status: probe.status,
+ result: parsed ?? text,
+ response: probe,
+ };
+ }
+
+ const challenge =
+ safeJson(await probe.text()) ||
+ (() => {
+ // Some servers only emit the body on the PAYMENT-REQUIRED header.
+ const header = probe.headers.get('payment-required');
+ return header ? b64decode(header) : null;
+ })();
+ if (!challenge || !Array.isArray(challenge.accepts)) {
+ return { ok: false, status: 402, error: 'invalid_402_body' };
+ }
+
+ const requirement = selectRequirement(challenge, preferNetwork);
+ if (!requirement) {
+ return { ok: false, status: 402, error: 'no_acceptable_requirement' };
+ }
+
+ let reservation = null;
+ if (caps) {
+ const verdict = await enforceCap({ requirement, opts: caps });
+ if (verdict.abort) {
+ return { ok: false, abort: true, reason: verdict.reason };
+ }
+ reservation = verdict.reservation;
+ }
+
+ try {
+ let paymentPayload;
+ try {
+ paymentPayload = await signPayment({ requirement, challenge });
+ } catch (err) {
+ if (reservation) await rollbackReservation(reservation);
+ throw err;
+ }
+ ensureBuilderCodeEcho(challenge, paymentPayload);
+
+ const xPayment = b64encode(paymentPayload);
+ const paid = await fetchImpl(url, {
+ ...init,
+ headers: { ...(init.headers || {}), 'X-PAYMENT': xPayment },
+ });
+ const paidText = await paid.text();
+ const paidJson = safeJson(paidText) ?? paidText;
+ if (!paid.ok) {
+ if (reservation) await rollbackReservation(reservation);
+ return {
+ ok: false,
+ status: paid.status,
+ error: paidJson?.error || `HTTP ${paid.status}`,
+ result: paidJson,
+ response: paid,
+ };
+ }
+ const settled = b64decode(paid.headers.get('x-payment-response'));
+ if (reservation) {
+ await commit(reservation, {
+ network: requirement.network,
+ asset: requirement.asset,
+ settlement: settled,
+ });
+ }
+ return {
+ ok: true,
+ result: paidJson,
+ response: paid,
+ payment: paymentPayload,
+ settled,
+ };
+ } catch (err) {
+ if (reservation) {
+ await rollbackReservation(reservation).catch(() => undefined);
+ }
+ throw err;
+ }
+}
+
+function safeJson(text) {
+ if (typeof text !== 'string' || !text) return null;
+ try {
+ return JSON.parse(text);
+ } catch {
+ return null;
+ }
+}
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index 77f3e2d63..a7ecc5e75 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -250,6 +250,13 @@ export function paidEndpoint(spec) {
// important than payer privacy. `offerValiditySeconds` overrides the
// 300-second default for how long signed offers stay valid.
offerReceipt = {},
+ // USE-13: Bazaar resource-level service metadata. Set per route so the
+ // facilitator can group / search / icon-ify the catalog entry. Pass
+ // `service: { serviceName, tags, iconUrl }` or use withService() from
+ // api/_lib/x402/bazaar-helpers.js to merge with three.ws defaults.
+ // Fields fall through to build402Body which gates each on the spec
+ // validation rules (printable ASCII, length caps, https URL).
+ service,
} = spec;
if (!route) throw new Error('paidEndpoint: route is required');
@@ -355,10 +362,12 @@ export function paidEndpoint(spec) {
// SIWX extension advertised on every 402 when the endpoint opts in.
// `requirements[].network` lists every CAIP-2 chain we'll accept a
- // signature for — the upstream helper turns it into supportedChains.
+ // signature for — the upstream helper turns it into supportedChains
+ // and enriches the info block (domain/uri/nonce/issuedAt) per request.
const siwxExtensions = siwx
- ? declareSiwxExtensionFor({
+ ? await declareSiwxExtensionFor({
networks: requirements.map((r) => r.network),
+ resourceUrl,
statement: siwx.statement,
expirationSeconds: siwx.expirationSeconds,
})
@@ -391,6 +400,9 @@ export function paidEndpoint(spec) {
mimeType,
bazaar,
extensions: extraExtensions,
+ ...(service?.serviceName ? { serviceName: service.serviceName } : {}),
+ ...(Array.isArray(service?.tags) && service.tags.length ? { tags: service.tags } : {}),
+ ...(service?.iconUrl ? { iconUrl: service.iconUrl } : {}),
};
// USE-21: auth-hints fast path. If the endpoint declared OAuth/SIWX as
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index 22109d803..72bc5559a 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -784,6 +784,10 @@ function hasPermit2Accept(accepts) {
// We also auto-declare the ERC-8021 `builder-code` extension when
// X402_BUILDER_CODE_APP is configured, so every paid endpoint contributes to
// on-chain attribution without having to opt in per-route.
+// USE-13: `serviceName`, `tags`, `iconUrl` belong on the `resource` object
+// per the Bazaar spec. Facilitators apply soft-drop validation so silently
+// invalid fields are skipped, but we keep them within limits here too —
+// printable-ASCII, ≤32 chars (serviceName/tag), ≤5 tags, absolute https URL.
export function build402Body({
resourceUrl,
accepts,
@@ -792,6 +796,9 @@ export function build402Body({
mimeType = 'application/json',
bazaar = bazaarExtension(),
extensions: extraExtensions,
+ serviceName,
+ tags,
+ iconUrl,
}) {
const extensions = { bazaar };
if (hasPermit2Accept(accepts)) {
@@ -809,10 +816,20 @@ export function build402Body({
if (extraExtensions && typeof extraExtensions === 'object') {
Object.assign(extensions, extraExtensions);
}
+ const resource = { url: resourceUrl, description, mimeType };
+ if (typeof serviceName === 'string' && serviceName.length) {
+ resource.serviceName = serviceName;
+ }
+ if (Array.isArray(tags) && tags.length) {
+ resource.tags = tags.slice(0, 5);
+ }
+ if (typeof iconUrl === 'string' && iconUrl.length) {
+ resource.iconUrl = iconUrl;
+ }
return {
x402Version: X402_VERSION,
error,
- resource: { url: resourceUrl, description, mimeType },
+ resource,
accepts: Array.isArray(accepts) ? accepts : [accepts],
extensions,
};
diff --git a/api/_lib/x402-spending-cap.js b/api/_lib/x402-spending-cap.js
new file mode 100644
index 000000000..4c95beb32
--- /dev/null
+++ b/api/_lib/x402-spending-cap.js
@@ -0,0 +1,257 @@
+// Spending-cap enforcement for x402 buyer clients (USE-22).
+//
+// Critical safety net for autonomous agents (USE-29..40): without per-call
+// + sliding-window caps, a bug in agent logic could drain the buyer wallet
+// across thousands of micropayments before anyone notices. The cap module
+// is the chokepoint that every buyer client routes through.
+//
+// Surface:
+// installSpendingCap(client, opts) — for clients that expose the SDK's
+// onBeforePaymentCreation / onAfterPaymentCreation lifecycle hooks
+// (e.g. @x402/fetch's wrapFetchWithPayment style). Returns an
+// `uninstall()` function.
+// enforceCap({ requirement, opts }) — lower-level entrypoint used by the
+// buyer-fetch / buyer-axios helpers, which call us imperatively
+// instead of via lifecycle hooks. Returns `{ abort: false }` on
+// success or `{ abort: true, reason }`.
+// commit(reservation) / rollback(reservation) — pair with enforceCap
+// for transactional admission.
+//
+// Strict mode is the default: we reserve the spend in Redis BEFORE the
+// payment is signed and rollback on any failure path. This closes the
+// race where two concurrent calls would both pass a relaxed read-only
+// cap check.
+
+import { current, reserve, rollback } from './x402-spending-ledger.js';
+import { toMicroUsd } from './x402-spending-price.js';
+import { env } from './env.js';
+
+const DEFAULT_OPTS = Object.freeze({
+ // All thresholds are micro-USD (6 decimals) — i.e. atomics of a USDC.
+ maxPerCall: null,
+ maxPerHour: null,
+ maxPerDay: null,
+ // `strict: true` reserves the spend pre-signing for race-free caps;
+ // `false` reads-then-writes (faster, but two concurrent calls under
+ // the limit individually can both go through). Default true because
+ // the agent use-case is exactly the scenario that creates the race.
+ strict: true,
+ // Hook fires after a successful payment; useful for sending audit
+ // events to whatever observability stack the host process uses.
+ onRecord: null,
+});
+
+function asBigInt(v, label) {
+ if (v == null) return null;
+ try {
+ return BigInt(v);
+ } catch (err) {
+ throw new Error(
+ `spending-cap: ${label} must be a base-10 integer string (got ${typeof v})`,
+ );
+ }
+}
+
+function normalizeOpts(input = {}) {
+ const opts = { ...DEFAULT_OPTS, ...input };
+ // Fall back to env-configured ceilings when the caller didn't set the
+ // explicit option. Lets operators set process-wide caps once and trust
+ // every paid endpoint inherits them.
+ if (opts.maxPerCall == null) opts.maxPerCall = env.X402_MAX_PER_CALL_ATOMIC;
+ if (opts.maxPerHour == null) opts.maxPerHour = env.X402_MAX_PER_HOUR_ATOMIC;
+ if (opts.maxPerDay == null) opts.maxPerDay = env.X402_MAX_PER_DAY_ATOMIC;
+ opts.maxPerCall = asBigInt(opts.maxPerCall, 'maxPerCall');
+ opts.maxPerHour = asBigInt(opts.maxPerHour, 'maxPerHour');
+ opts.maxPerDay = asBigInt(opts.maxPerDay, 'maxPerDay');
+ if (input.onRecord != null && typeof input.onRecord !== 'function') {
+ throw new Error('spending-cap: onRecord must be a function when provided');
+ }
+ if (!input.address || typeof input.address !== 'string') {
+ throw new Error('spending-cap: address required');
+ }
+ opts.address = input.address;
+ return opts;
+}
+
+// Single-shot admission check. Caller passes the resolved requirement
+// (the entry the SDK picked off the 402 accepts[] list) plus the
+// caps options. Returns one of:
+//
+// { abort: true, reason } — request must NOT proceed
+// { abort: false, reservation } — proceed; pass reservation
+// into commit() or rollback()
+//
+// `reservation` is opaque from the caller's perspective; we use it to
+// undo a strict-mode reserve without re-fetching from Redis.
+export async function enforceCap({ requirement, opts }) {
+ const settings = normalizeOpts(opts);
+ if (!requirement || !requirement.amount) {
+ throw new Error('spending-cap: requirement.amount required');
+ }
+
+ const microUsd = await toMicroUsd(requirement.amount, requirement);
+
+ if (settings.maxPerCall != null && microUsd > settings.maxPerCall) {
+ return {
+ abort: true,
+ reason: `Payment ${microUsd}µUSD exceeds per-call cap ${settings.maxPerCall}µUSD`,
+ };
+ }
+
+ const timestamp = Date.now();
+ if (settings.strict) {
+ // Pessimistic admission: reserve first, then check the post-state.
+ const totals = await reserve({
+ address: settings.address,
+ microUsd,
+ timestamp,
+ });
+ if (settings.maxPerHour != null && totals.hour > settings.maxPerHour) {
+ await rollback({ address: settings.address, microUsd, timestamp });
+ return {
+ abort: true,
+ reason: `Hourly cap exceeded: ${totals.hour}µUSD would exceed ${settings.maxPerHour}µUSD`,
+ };
+ }
+ if (settings.maxPerDay != null && totals.day > settings.maxPerDay) {
+ await rollback({ address: settings.address, microUsd, timestamp });
+ return {
+ abort: true,
+ reason: `Daily cap exceeded: ${totals.day}µUSD would exceed ${settings.maxPerDay}µUSD`,
+ };
+ }
+ return {
+ abort: false,
+ reservation: { address: settings.address, microUsd, timestamp, settings },
+ };
+ }
+
+ // Relaxed admission: peek at the running totals, then commit only after
+ // the payment is signed. Saves a write on every reject but has a race
+ // between two in-flight calls.
+ const totals = await current({ address: settings.address, timestamp });
+ if (settings.maxPerHour != null && totals.hour + microUsd > settings.maxPerHour) {
+ return {
+ abort: true,
+ reason: `Hourly cap would be exceeded: ${totals.hour + microUsd}µUSD > ${settings.maxPerHour}µUSD`,
+ };
+ }
+ if (settings.maxPerDay != null && totals.day + microUsd > settings.maxPerDay) {
+ return {
+ abort: true,
+ reason: `Daily cap would be exceeded: ${totals.day + microUsd}µUSD > ${settings.maxPerDay}µUSD`,
+ };
+ }
+ return {
+ abort: false,
+ reservation: {
+ address: settings.address,
+ microUsd,
+ timestamp,
+ settings,
+ pendingCommit: true,
+ },
+ };
+}
+
+// Commit a successful payment to the ledger. For strict admission the
+// reserve already happened; commit is a no-op aside from the onRecord hook.
+// For relaxed admission, commit is where the running totals actually grow.
+export async function commit(reservation, extra = {}) {
+ if (!reservation) return;
+ const { address, microUsd, timestamp, settings, pendingCommit } = reservation;
+ if (pendingCommit) {
+ await reserve({ address, microUsd, timestamp });
+ }
+ if (settings?.onRecord) {
+ try {
+ await settings.onRecord({
+ address,
+ microUsd: String(microUsd),
+ timestamp,
+ ...extra,
+ });
+ } catch (err) {
+ // onRecord failures must not break paid flows. Log and continue.
+ // eslint-disable-next-line no-console
+ console.error('[spending-cap] onRecord hook failed:', err?.message || err);
+ }
+ }
+}
+
+// Roll back an admission reservation. Idempotent in the sense that calling
+// it twice is harmless aside from the negative ledger write — we trust
+// callers to track a "did I roll back yet" boolean. This is fine because
+// the same physical reservation typically only has one terminal path.
+export async function rollbackReservation(reservation) {
+ if (!reservation) return;
+ const { address, microUsd, timestamp, pendingCommit } = reservation;
+ if (pendingCommit) return; // never reserved → nothing to undo
+ await rollback({ address, microUsd, timestamp });
+}
+
+// Install the cap as SDK-style lifecycle hooks on a client. Compatible with
+// any client object that exposes `onBeforePaymentCreation` and
+// `onAfterPaymentCreation` callbacks (e.g. @x402/fetch's createPaymentClient).
+//
+// `client.onBeforePaymentCreation(fn)` is expected to register `fn` and
+// invoke it with `{ selectedRequirements }` immediately before signing.
+// Returning `{ abort: true, reason }` aborts the call. We stash the
+// reservation in a per-client WeakMap so the after-hook can commit it.
+export function installSpendingCap(client, opts) {
+ const settings = normalizeOpts(opts);
+ if (!client || typeof client.onBeforePaymentCreation !== 'function') {
+ throw new Error('installSpendingCap: client.onBeforePaymentCreation not found');
+ }
+ if (typeof client.onAfterPaymentCreation !== 'function') {
+ throw new Error('installSpendingCap: client.onAfterPaymentCreation not found');
+ }
+ const reservations = new WeakMap();
+
+ const before = async (ctx = {}) => {
+ const requirement = ctx.selectedRequirements || ctx.requirement;
+ if (!requirement) return;
+ const res = await enforceCap({ requirement, opts: settings });
+ if (res.abort) {
+ return { abort: true, reason: res.reason };
+ }
+ reservations.set(ctx, res.reservation);
+ return undefined;
+ };
+
+ const after = async (ctx = {}) => {
+ const reservation = reservations.get(ctx);
+ if (!reservation) return;
+ reservations.delete(ctx);
+ const requirement = ctx.selectedRequirements || ctx.requirement || {};
+ await commit(reservation, {
+ network: requirement.network,
+ asset: requirement.asset,
+ });
+ };
+
+ const onError = async (ctx = {}) => {
+ const reservation = reservations.get(ctx);
+ if (!reservation) return;
+ reservations.delete(ctx);
+ await rollbackReservation(reservation);
+ };
+
+ const removeBefore = client.onBeforePaymentCreation(before);
+ const removeAfter = client.onAfterPaymentCreation(after);
+ // Best-effort error hook — not every SDK exposes it. We register only
+ // when present; otherwise relaxed-mode rollback relies on the caller
+ // catching errors.
+ const removeError =
+ typeof client.onPaymentError === 'function'
+ ? client.onPaymentError(onError)
+ : typeof client.onPaymentFailure === 'function'
+ ? client.onPaymentFailure(onError)
+ : () => undefined;
+
+ return function uninstall() {
+ if (typeof removeBefore === 'function') removeBefore();
+ if (typeof removeAfter === 'function') removeAfter();
+ if (typeof removeError === 'function') removeError();
+ };
+}
diff --git a/api/_lib/x402-spending-ledger.js b/api/_lib/x402-spending-ledger.js
index 59888db9b..6a8968490 100644
--- a/api/_lib/x402-spending-ledger.js
+++ b/api/_lib/x402-spending-ledger.js
@@ -148,10 +148,7 @@ export async function rollback({ address, microUsd, timestamp = now() }) {
memoryIncr(dKey, -delta, DAY_TTL_SECONDS);
return;
}
- await Promise.all([
- redis.incrby(hKey, -Number(delta)),
- redis.incrby(dKey, -Number(delta)),
- ]);
+ await Promise.all([redis.incrby(hKey, -Number(delta)), redis.incrby(dKey, -Number(delta))]);
}
// Snapshot of the current hour + day spend without modifying. Used by
diff --git a/api/_lib/x402/offer-receipt-issuer.js b/api/_lib/x402/offer-receipt-issuer.js
index c5f40ff2a..e86b412eb 100644
--- a/api/_lib/x402/offer-receipt-issuer.js
+++ b/api/_lib/x402/offer-receipt-issuer.js
@@ -43,23 +43,45 @@ import { env } from '../env.js';
let _issuerCache = null;
let _issuerError = null;
+// Each callable reads an env value and returns the address to compare against,
+// or null when the env is unset / the key itself is malformed. Wrapped in
+// try/catch because some envs (AGENT_RELAYER_KEY) are declared `req()` and
+// throw when unset — that throw must not stop us from running the safeguard.
+function deriveAddressIfPossible(envFn) {
+ let raw;
+ try {
+ raw = envFn();
+ } catch {
+ return null;
+ }
+ if (!raw) return null;
+ const trimmed = String(raw).trim();
+ if (/^0x[a-fA-F0-9]{40}$/.test(trimmed)) return trimmed.toLowerCase();
+ try {
+ const norm = trimmed.startsWith('0x') ? trimmed : `0x${trimmed}`;
+ return privateKeyToAccount(norm).address.toLowerCase();
+ } catch {
+ return null;
+ }
+}
+
function safeguardAgainstReusingPaymentKey(signingPrivKey) {
- const norm = String(signingPrivKey).trim().toLowerCase().replace(/^0x/, '');
- const collisions = [
- ['X402_PAY_TO_BASE', env.X402_PAY_TO_BASE],
- ['X402_PAY_TO_BSC', env.X402_PAY_TO_BSC],
- ['CLUB_EVM_TREASURY_PRIVATE_KEY', env.CLUB_EVM_TREASURY_PRIVATE_KEY],
- ['AGENT_RELAYER_KEY', env.AGENT_RELAYER_KEY ? '<set>' : undefined],
- ];
+ const norm = signingPrivKey.startsWith('0x') ? signingPrivKey : `0x${signingPrivKey}`;
let derivedAddress;
try {
- derivedAddress = privateKeyToAccount(`0x${norm}`).address.toLowerCase();
+ derivedAddress = privateKeyToAccount(norm).address.toLowerCase();
} catch {
throw new Error('OFFER_RECEIPT_SIGNING_PRIVATE_KEY is not a valid 0x-hex EVM private key');
}
- for (const [name, value] of collisions) {
- if (!value) continue;
- if (String(value).toLowerCase() === derivedAddress) {
+ const collisions = [
+ ['X402_PAY_TO_BASE', deriveAddressIfPossible(() => env.X402_PAY_TO_BASE)],
+ ['X402_PAY_TO_BSC', deriveAddressIfPossible(() => env.X402_PAY_TO_BSC)],
+ ['CLUB_EVM_TREASURY_PRIVATE_KEY', deriveAddressIfPossible(() => env.CLUB_EVM_TREASURY_PRIVATE_KEY)],
+ ['AGENT_RELAYER_KEY', deriveAddressIfPossible(() => env.AGENT_RELAYER_KEY)],
+ ];
+ for (const [name, addr] of collisions) {
+ if (!addr) continue;
+ if (addr === derivedAddress) {
throw new Error(
`OFFER_RECEIPT_SIGNING_PRIVATE_KEY derives to ${derivedAddress}, which is also ${name}. ` +
'Receipts MUST be signed with a dedicated key separate from payment-receiving wallets.',
diff --git a/api/_mcp/dispatch.js b/api/_mcp/dispatch.js
index 037c51ed3..b599c11c9 100644
--- a/api/_mcp/dispatch.js
+++ b/api/_mcp/dispatch.js
@@ -1,6 +1,7 @@
import { hasScope } from '../_lib/auth.js';
import { recordEvent, logger } from '../_lib/usage.js';
import { priceFor, findActiveSubscription, resolveBillingMint } from '../_lib/pump-pricing.js';
+import { declareMcpDiscovery } from '../_lib/x402/bazaar-helpers.js';
import { TOOL_CATALOG, TOOLS } from './catalog.js';
export const PROTOCOL_VERSION = '2025-06-18';
@@ -34,20 +35,32 @@ export async function dispatch(msg, auth, _req) {
return ok(id, {
tools: TOOL_CATALOG.map((t) => {
const price = priceFor(t.name);
- return price
- ? {
- ...t,
- pricing: {
- amount_usdc: price.amount_usdc,
- currency: 'USDC',
- description: price.description,
- scheme: 'pump-agent-payments',
- prep_endpoint: '/api/pump/accept-payment-prep',
- confirm_endpoint: '/api/pump/accept-payment-confirm',
- recipient_mint: resolveBillingMint(),
- },
- }
- : t;
+ if (!price) return t;
+ // USE-13: priced tools also surface a Bazaar discovery
+ // extension so MCP clients reading tools/list see the same
+ // catalog metadata facilitators index via
+ // /discovery/resources. The extension carries the canonical
+ // shape (transport, inputSchema, example) clients need to
+ // pay-and-call without re-reading the tool description.
+ const discovery = declareMcpDiscovery({
+ toolName: t.name,
+ description: t.description,
+ transport: 'streamable-http',
+ inputSchema: t.inputSchema,
+ });
+ return {
+ ...t,
+ pricing: {
+ amount_usdc: price.amount_usdc,
+ currency: 'USDC',
+ description: price.description,
+ scheme: 'pump-agent-payments',
+ prep_endpoint: '/api/pump/accept-payment-prep',
+ confirm_endpoint: '/api/pump/accept-payment-confirm',
+ recipient_mint: resolveBillingMint(),
+ },
+ extensions: { bazaar: discovery },
+ };
}),
});
if (method === 'tools/call') return ok(id, await onToolCall(msg.params, auth, started));
diff --git a/api/agents/a2a-paid.js b/api/agents/a2a-paid.js
new file mode 100644
index 000000000..a97e9ff49
--- /dev/null
+++ b/api/agents/a2a-paid.js
@@ -0,0 +1,174 @@
+// POST /api/agents/a2a-paid — A2A (Agent-to-Agent) x402 endpoint.
+//
+// Exposes the three.ws glTF/GLB inspector as a paid A2A skill. Other agents
+// invoke it by sending JSON-RPC `message/send` with the X-A2A-Extensions
+// header set to https://github.com/google-a2a/a2a-x402/v0.1.
+//
+// First call (no payment metadata): replies with a task in state
+// `input-required` carrying `x402.payment.required`.
+// Retry with the signed `x402.payment.payload`: replies with state
+// `completed`, a settlement receipt, and an `artifacts` entry containing
+// the structured inspection report.
+//
+// Verification + settlement reuse api/_lib/x402-spec.js so this endpoint
+// inherits Base / Solana / BSC support automatically from the env config.
+
+import { a2aPaidEndpoint } from '../_lib/x402/a2a-server.js';
+import { inspectModel, suggestOptimizations } from '../_lib/model-inspect.js';
+import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';
+
+const ROUTE = '/api/agents/a2a-paid';
+const MAX_FETCH_BYTES = 16 * 1024 * 1024;
+
+const DESCRIPTION =
+ 'three.ws A2A glTF/GLB Inspector — pay per call (USDC). Fetch a 3D model ' +
+ 'from a public URL and return structural stats (vertices, triangles, ' +
+ 'materials, textures, extensions) plus a prioritized list of optimization ' +
+ 'recommendations. Used by other agents to vet 3D assets before minting, ' +
+ 'rendering, or buying them.';
+
+const SKILL = {
+ id: 'inspect-glb-a2a',
+ name: 'Inspect glTF/GLB (A2A)',
+ description:
+ 'Run the canonical glTF-Transform inspector against a remote model URL. ' +
+ 'Returns counts, extensions used, and prioritized optimization suggestions.',
+ tags: ['model', 'gltf', 'glb', 'inspect', 'a2a'],
+ examples: [
+ 'Inspect https://three.ws/avatar/character-studio/sample.glb',
+ 'Vet this GLB before I mint it',
+ ],
+ inputModes: ['application/json', 'text/plain'],
+ outputModes: ['application/json'],
+};
+
+// Pull the model URL out of the A2A `message.parts[]`. Clients send the
+// request either as a plain text part ("Inspect https://...") or as a
+// `data` part with `{ url: "..." }`.
+function extractUrl(message) {
+ const parts = Array.isArray(message?.parts) ? message.parts : [];
+ for (const part of parts) {
+ if (part?.kind === 'data' && part.data && typeof part.data.url === 'string') {
+ return part.data.url.trim();
+ }
+ if (part?.kind === 'text' && typeof part.text === 'string') {
+ const match = /\bhttps?:\/\/\S+\.(?:glb|gltf)\b/i.exec(part.text);
+ if (match) return match[0];
+ // Allow a bare URL with no extension when the part is *only* a URL.
+ const trimmed = part.text.trim();
+ try {
+ const u = new URL(trimmed);
+ if (u.protocol === 'http:' || u.protocol === 'https:') return trimmed;
+ } catch {
+ /* not a URL, keep scanning */
+ }
+ }
+ }
+ return null;
+}
+
+async function fetchAndInspect(targetUrl) {
+ let parsed;
+ try {
+ parsed = await assertSafePublicUrl(targetUrl, { allowHttp: true });
+ } catch (err) {
+ if (err instanceof SsrfBlockedError) {
+ const e = new Error(err.message);
+ e.code = 'invalid_url';
+ e.status = 400;
+ throw e;
+ }
+ throw err;
+ }
+ let upstream;
+ try {
+ upstream = await fetch(parsed.toString(), {
+ redirect: 'follow',
+ headers: { accept: 'model/gltf-binary,model/gltf+json,application/octet-stream' },
+ signal: AbortSignal.timeout(20_000),
+ });
+ } catch (err) {
+ const e = new Error(`could not fetch model: ${err.message}`);
+ e.code = 'fetch_failed';
+ e.status = 502;
+ throw e;
+ }
+ if (!upstream.ok) {
+ const err = new Error(`upstream returned ${upstream.status} ${upstream.statusText}`);
+ err.code = 'fetch_failed';
+ err.status = 502;
+ throw err;
+ }
+ const contentLength = Number(upstream.headers.get('content-length') || 0);
+ if (contentLength && contentLength > MAX_FETCH_BYTES) {
+ const err = new Error(`model is ${contentLength} bytes; max is ${MAX_FETCH_BYTES}`);
+ err.code = 'too_large';
+ err.status = 413;
+ throw err;
+ }
+ const buf = new Uint8Array(await upstream.arrayBuffer());
+ if (buf.byteLength > MAX_FETCH_BYTES) {
+ const err = new Error(`model is ${buf.byteLength} bytes; max is ${MAX_FETCH_BYTES}`);
+ err.code = 'too_large';
+ err.status = 413;
+ throw err;
+ }
+ let info;
+ try {
+ info = await inspectModel(buf, { fileSize: buf.byteLength });
+ } catch (err) {
+ const e = new Error(err.message || 'failed to parse model');
+ e.code = 'invalid_model';
+ e.status = 422;
+ throw e;
+ }
+ return {
+ url: parsed.toString(),
+ fetchedBytes: buf.byteLength,
+ model: info,
+ suggestions: suggestOptimizations(info),
+ };
+}
+
+export default a2aPaidEndpoint({
+ route: ROUTE,
+ description: DESCRIPTION,
+ priceAtomics: '1000',
+ networks: ['base', 'solana'],
+ prompt:
+ 'Send the URL of a glTF or GLB model in the next message (text or data part). ' +
+ 'Inspection completes after payment settles.',
+ skill: SKILL,
+ services: ['gltf-inspect'],
+ async handler({ taskId, payer, message }) {
+ const url = extractUrl(message);
+ if (!url) {
+ const err = new Error(
+ 'no model URL found in message — include a text part with the URL or a data part with { url }',
+ );
+ err.code = 'missing_url';
+ throw err;
+ }
+ const report = await fetchAndInspect(url);
+ const headline =
+ `Inspected ${report.url} (${report.fetchedBytes} bytes). ` +
+ `Found ${report.model?.counts?.totalTriangles ?? '?'} triangles across ` +
+ `${report.model?.counts?.meshes ?? '?'} meshes. ` +
+ `${report.suggestions.length} optimization suggestion(s).`;
+ return {
+ text: headline,
+ artifacts: [
+ {
+ artifactId: taskId,
+ name: 'gltf-inspection.json',
+ description: 'glTF-Transform inspection report + optimization suggestions.',
+ parts: [{ kind: 'data', data: report }],
+ },
+ ],
+ metadata: {
+ 'three.ws.payer': payer || null,
+ 'three.ws.skill': SKILL.id,
+ },
+ };
+ },
+});
diff --git a/api/agents/solana/_handlers.js b/api/agents/solana/_handlers.js
index 0c43b981b..17604834d 100644
--- a/api/agents/solana/_handlers.js
+++ b/api/agents/solana/_handlers.js
@@ -215,6 +215,15 @@ export const handleCard = wrap(async (req, res) => {
schema_version: '1.0',
name: a.name,
description: a.description,
+ capabilities: {
+ extensions: [
+ {
+ uri: 'https://github.com/google-a2a/a2a-x402/v0.1',
+ description: 'Supports payments using the x402 protocol for on-chain settlement.',
+ required: true,
+ },
+ ],
+ },
identity: {
chain: 'solana', network, asset_pubkey: asset, owner: a.owner,
passport_url: `${origin}/agent-passport.html?asset=${asset}&network=${network}`,
@@ -224,6 +233,7 @@ export const handleCard = wrap(async (req, res) => {
skills: a.skills || [],
endpoints: {
chat: `${origin}/api/agents/${a.id}/chat`,
+ a2a_paid: `${origin}/api/agents/a2a-paid`,
attestations: `${origin}/api/agents/solana-attestations?asset=${asset}&network=${network}`,
reputation: `${origin}/api/agents/solana-reputation?asset=${asset}&network=${network}`,
...(token_stats ? { quote: `${origin}/api/pump/quote?mint=${asset}&network=${network}`, price_history: `${origin}/api/agents/solana-price-history?asset=${asset}&network=${network}` } : {}),
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index 9ba0520dd..59322ad94 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -73,25 +73,39 @@ const handlePresign = wrap(async (req, res) => {
// ── public ────────────────────────────────────────────────────────────────────
+// Public discovery surface — must always return 200 with a stable JSON shape so
+// agent crawlers, OpenAPI probes, and the Bazaar validator see a clean response
+// even when the DB is unreachable or the query parameters are malformed. Any
+// internal failure degrades to an empty result set rather than a 5xx.
const handlePublic = wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, 'http://x');
+ const parsedLimit = Number(url.searchParams.get('limit'));
+ const limit = Number.isFinite(parsedLimit) && parsedLimit > 0 ? parsedLimit : 24;
let result;
try {
result = await searchPublicAvatars({
q: url.searchParams.get('q') || undefined,
tag: url.searchParams.get('tag') || undefined,
- limit: Number(url.searchParams.get('limit')) || 24,
+ limit,
cursor: url.searchParams.get('cursor') || undefined,
withTotals: url.searchParams.get('totals') === '1',
});
} catch {
result = { avatars: [], next_cursor: null };
}
- result.avatars = result.avatars.map((a) => stripOwnerFor(a, null));
+ const avatars = Array.isArray(result?.avatars) ? result.avatars : [];
+ const payload = {
+ avatars: avatars.map((a) => stripOwnerFor(a, null)),
+ next_cursor: result?.next_cursor ?? null,
+ };
+ if (Object.prototype.hasOwnProperty.call(result || {}, 'total')) {
+ payload.total = result.total;
+ payload.total_views = result.total_views;
+ }
res.setHeader('cache-control', 'public, max-age=60, s-maxage=60');
- return json(res, 200, result);
+ return json(res, 200, payload);
});
// ── regenerate ────────────────────────────────────────────────────────────────
diff --git a/api/insights/revenue-vision.js b/api/insights/revenue-vision.js
index 51ecd2022..491519a5b 100644
--- a/api/insights/revenue-vision.js
+++ b/api/insights/revenue-vision.js
@@ -30,6 +30,7 @@ import {
writeCachedResponse,
writeConflict,
} from '../_lib/x402/payment-identifier-server.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
const ROUTE = '/api/insights/revenue-vision';
@@ -109,7 +110,7 @@ const ROUTE_BAZAAR = {
schema: DISCOVERY_OUTPUT_SCHEMA,
};
-function buildRequirements() {
+function buildRequirements(resourceUrl) {
return [
{
scheme: 'exact',
@@ -118,6 +119,7 @@ function buildRequirements() {
payTo: env.X402_PAY_TO_BASE,
asset: env.X402_ASSET_ADDRESS_BASE,
maxTimeoutSeconds: 60,
+ resource: resourceUrl,
extra: { name: 'USD Coin', version: '2', decimals: 6 },
},
];
@@ -172,20 +174,27 @@ async function callClaude(missionBrief, agentCodename) {
}
export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (req.method !== 'GET') {
res.setHeader('allow', 'GET');
return error(res, 405, 'method_not_allowed', 'use GET');
}
const resourceUrl = resolveResourceUrl(req, ROUTE);
- const requirements = buildRequirements();
+ const requirements = buildRequirements(resourceUrl);
+ const service = withService({
+ serviceName: 'three.ws Revenue Vision',
+ tags: ['ai', 'analysis', 'growth', 'insight', 'claude'],
+ });
const challenge = {
resourceUrl,
accepts: requirements,
description: ROUTE_DESCRIPTION,
bazaar: ROUTE_BAZAAR,
extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },
+ serviceName: service.serviceName,
+ tags: service.tags,
+ iconUrl: service.iconUrl,
};
const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];
diff --git a/api/wk.js b/api/wk.js
index cf0d9fb5b..c880e011a 100644
--- a/api/wk.js
+++ b/api/wk.js
@@ -13,6 +13,9 @@ import {
NETWORK_BASE_MAINNET,
NETWORK_SOLANA_MAINNET,
} from './_lib/x402-spec.js';
+import { declareMcpDiscovery, withService } from './_lib/x402/bazaar-helpers.js';
+import { TOOL_CATALOG } from './_mcp/catalog.js';
+import { priceFor } from './_lib/pump-pricing.js';
// ── agent-attestation-schemas ─────────────────────────────────────────────────
@@ -158,7 +161,17 @@ function handleOauthProtectedResource(req, res) {
function handleX402(req, res) {
const mcpResource = `${env.APP_ORIGIN}/api/mcp`;
- const body = build402Body({ resourceUrl: mcpResource, accepts: paymentRequirements(mcpResource) });
+ const mcpService = withService({
+ serviceName: 'three.ws MCP',
+ tags: ['mcp', '3d', 'gltf', 'solana', 'agent'],
+ });
+ const body = build402Body({
+ resourceUrl: mcpResource,
+ accepts: paymentRequirements(mcpResource),
+ serviceName: mcpService.serviceName,
+ tags: mcpService.tags,
+ iconUrl: mcpService.iconUrl,
+ });
return json(
res,
200,
@@ -218,7 +231,11 @@ function extensionsForAccepts(accepts, bazaar) {
return exts;
}
-function acceptsForPrice(amountAtomics) {
+// Build the accepts[] block for a discovery-catalog entry. `resourceUrl` is
+// echoed on every accept so reviewers + wallet/facilitator spend logs can
+// reconcile each accept entry against the resource it gates, without having
+// to walk back to the parent resource[] entry.
+function acceptsForPrice(amountAtomics, resourceUrl) {
const out = [];
const price = RAW_AMOUNT_TO_USDC(amountAtomics);
if (env.X402_PAY_TO_BASE) {
@@ -232,6 +249,7 @@ function acceptsForPrice(amountAtomics) {
asset: env.X402_ASSET_ADDRESS_BASE,
asset_symbol: 'USDC',
maxTimeoutSeconds: 60,
+ resource: resourceUrl,
extra: { name: 'USD Coin', version: '2', decimals: 6 },
});
}
@@ -246,12 +264,77 @@ function acceptsForPrice(amountAtomics) {
asset: env.X402_ASSET_MINT_SOLANA,
asset_symbol: 'USDC',
maxTimeoutSeconds: 60,
+ resource: resourceUrl,
extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
});
}
return out;
}
+// USE-13: one Bazaar catalog row per priced MCP tool. Facilitators key MCP
+// rows on (resource, toolName) so each priced tool needs its own row; the
+// shared `/api/mcp` resource alone would collapse them into one entry. We
+// only emit rows for priced tools (otherwise the row would advertise a paid
+// catalog entry for a free tool and confuse buyers about what's actually
+// gated). Falls back to the canonical `mcp://tool/<name>` identifier when
+// the spec wants a logical resource that distinguishes tools at the URL
+// level, while the actual call still goes to `/api/mcp`.
+function buildMcpToolItems({ mcpUrl, mcpAccepts, mcpService }) {
+ const items = [];
+ for (const tool of TOOL_CATALOG) {
+ const pricing = priceFor(tool.name);
+ if (!pricing) continue;
+ const exampleArgs = exampleArgsForTool(tool);
+ const discovery = declareMcpDiscovery({
+ toolName: tool.name,
+ description: tool.description,
+ // MCP 2025-06-18 transport: Streamable HTTP is the default for
+ // /api/mcp; SSE clients still work through the same path.
+ transport: 'streamable-http',
+ inputSchema: tool.inputSchema,
+ example: exampleArgs,
+ });
+ items.push({
+ type: 'mcp',
+ path: '/api/mcp',
+ url: mcpUrl,
+ toolName: tool.name,
+ method: 'POST',
+ description: tool.description,
+ mimeType: 'application/json',
+ serviceName: mcpService.serviceName,
+ tags: mcpService.tags,
+ iconUrl: mcpService.iconUrl,
+ pricing: {
+ amount_usdc: pricing.amount_usdc,
+ currency: 'USDC',
+ description: pricing.description,
+ },
+ accepts: mcpAccepts,
+ extensions: extensionsForAccepts(mcpAccepts, discovery),
+ });
+ }
+ return items;
+}
+
+// Synthesize a minimal example arguments object that satisfies the tool's
+// inputSchema.required fields. We use type-appropriate placeholders rather
+// than the full schema so the example stays short — facilitators index it
+// for search relevance, not exact matching.
+function exampleArgsForTool(tool) {
+ const props = tool.inputSchema?.properties || {};
+ const required = tool.inputSchema?.required || [];
+ const out = {};
+ for (const key of required) {
+ const def = props[key] || {};
+ if (def.type === 'integer' || def.type === 'number') out[key] = def.default ?? 1;
+ else if (def.type === 'boolean') out[key] = def.default ?? true;
+ else if (def.type === 'array') out[key] = [];
+ else out[key] = def.default ?? `example-${key}`;
+ }
+ return out;
+}
+
function handleX402Discovery(req, res) {
const origin = env.APP_ORIGIN;
const mcpUrl = `${origin}/api/mcp`;
@@ -260,9 +343,53 @@ function handleX402Discovery(req, res) {
const revenueVisionUrl = `${origin}/api/insights/revenue-vision`;
const price = RAW_AMOUNT_TO_USDC(env.X402_MAX_AMOUNT_REQUIRED);
- const mcpAccepts = [];
- if (env.X402_PAY_TO_BASE) {
- pushAcceptWithPermit2Sibling(mcpAccepts, {
+ // Build the MCP accept list (Base + Solana). `resource` is echoed on every
+ // accept so reviewers + spend logs can reconcile the entry against the
+ // resource it gates without walking back to the parent resource[] entry.
+ function buildMcpAccepts(resourceUrl) {
+ const out = [];
+ if (env.X402_PAY_TO_BASE) {
+ pushAcceptWithPermit2Sibling(out, {
+ scheme: 'exact',
+ network: NETWORK_BASE_MAINNET,
+ network_label: 'base-mainnet',
+ amount: env.X402_MAX_AMOUNT_REQUIRED,
+ price,
+ payTo: env.X402_PAY_TO_BASE,
+ asset: env.X402_ASSET_ADDRESS_BASE,
+ asset_symbol: 'USDC',
+ maxTimeoutSeconds: 60,
+ resource: resourceUrl,
+ extra: { name: 'USDC', version: '2', decimals: 6 },
+ });
+ }
+ if (env.X402_PAY_TO_SOLANA) {
+ out.push({
+ scheme: 'exact',
+ network: NETWORK_SOLANA_MAINNET,
+ network_label: 'solana-mainnet',
+ amount: env.X402_MAX_AMOUNT_REQUIRED,
+ price,
+ payTo: env.X402_PAY_TO_SOLANA,
+ asset: env.X402_ASSET_MINT_SOLANA,
+ asset_symbol: 'USDC',
+ maxTimeoutSeconds: 60,
+ resource: resourceUrl,
+ extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
+ });
+ }
+ return out;
+ }
+
+ // model-check / mint-to-mesh / revenue-vision are CDP-Bazaar-cataloged.
+ // CDP supports Base mainnet + Arbitrum One; advertise both here so
+ // agentic.market shows the same network options buyers will see in the
+ // live 402 challenge. Each EVM entry gets a Permit2 sibling so
+ // EIP-2612-aware clients can pick the gasless Permit2-via-EIP-2612 path.
+ const ARB_USDC = env.X402_ASSET_ADDRESS_ARBITRUM;
+ function buildBazaarAccepts(resourceUrl) {
+ const out = [];
+ pushAcceptWithPermit2Sibling(out, {
scheme: 'exact',
network: NETWORK_BASE_MAINNET,
network_label: 'base-mainnet',
@@ -272,55 +399,88 @@ function handleX402Discovery(req, res) {
asset: env.X402_ASSET_ADDRESS_BASE,
asset_symbol: 'USDC',
maxTimeoutSeconds: 60,
+ resource: resourceUrl,
extra: { name: 'USDC', version: '2', decimals: 6 },
});
- }
- if (env.X402_PAY_TO_SOLANA) {
- mcpAccepts.push({
+ pushAcceptWithPermit2Sibling(out, {
scheme: 'exact',
- network: NETWORK_SOLANA_MAINNET,
- network_label: 'solana-mainnet',
+ network: 'eip155:42161',
+ network_label: 'arbitrum-one',
amount: env.X402_MAX_AMOUNT_REQUIRED,
price,
- payTo: env.X402_PAY_TO_SOLANA,
- asset: env.X402_ASSET_MINT_SOLANA,
+ payTo: env.X402_PAY_TO_BASE,
+ asset: ARB_USDC,
asset_symbol: 'USDC',
maxTimeoutSeconds: 60,
- extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
+ resource: resourceUrl,
+ extra: { name: 'USDC', version: '2', decimals: 6 },
});
+ return out;
}
- // /api/x402/model-check is the CDP-Bazaar-cataloged endpoint. CDP supports
- // Base mainnet + Arbitrum One; advertise both here so agentic.market shows
- // the same network options buyers will see in the live 402 challenge.
- // Each EVM entry gets a Permit2 sibling so EIP-2612-aware clients can pick
- // the gasless Permit2-via-EIP-2612 path.
- const ARB_USDC = env.X402_ASSET_ADDRESS_ARBITRUM;
- const modelCheckAccepts = [];
- pushAcceptWithPermit2Sibling(modelCheckAccepts, {
- scheme: 'exact',
- network: NETWORK_BASE_MAINNET,
- network_label: 'base-mainnet',
- amount: env.X402_MAX_AMOUNT_REQUIRED,
- price,
- payTo: env.X402_PAY_TO_BASE,
- asset: env.X402_ASSET_ADDRESS_BASE,
- asset_symbol: 'USDC',
- maxTimeoutSeconds: 60,
- extra: { name: 'USDC', version: '2', decimals: 6 },
- });
- pushAcceptWithPermit2Sibling(modelCheckAccepts, {
- scheme: 'exact',
- network: 'eip155:42161',
- network_label: 'arbitrum-one',
- amount: env.X402_MAX_AMOUNT_REQUIRED,
- price,
- payTo: env.X402_PAY_TO_BASE,
- asset: ARB_USDC,
- asset_symbol: 'USDC',
- maxTimeoutSeconds: 60,
- extra: { name: 'USDC', version: '2', decimals: 6 },
- });
+ const mcpAccepts = buildMcpAccepts(mcpUrl);
+ const modelCheckAccepts = buildBazaarAccepts(modelCheckUrl);
+ const mintToMeshAccepts = buildBazaarAccepts(mintToMeshUrl);
+ const revenueVisionAccepts = buildBazaarAccepts(revenueVisionUrl);
+
+ // USE-13: per-route Bazaar service metadata. Echoed on each resource[]
+ // entry so facilitators crawling /.well-known/x402-discovery surface a
+ // human-readable serviceName + topical tags + icon in their search UI.
+ // Tags are deliberately short (≤32 chars each) and ≤5 entries per the
+ // spec; iconUrl falls back to THREEWS_SERVICE.iconUrl when unset.
+ const routeMeta = {
+ modelCheck: withService({
+ serviceName: 'three.ws Model Check',
+ tags: ['3d', 'gltf', 'glb', 'inspection', 'validation'],
+ }),
+ mintToMesh: withService({
+ serviceName: 'three.ws Mint to Mesh',
+ tags: ['3d', 'gltf', 'solana', 'token', 'render'],
+ }),
+ mintToMeshBatch: withService({
+ serviceName: 'three.ws Mint Mesh Batch',
+ tags: ['3d', 'gltf', 'solana', 'batch', 'render'],
+ }),
+ revenueVision: withService({
+ serviceName: 'three.ws Revenue Vision',
+ tags: ['ai', 'analysis', 'growth', 'insight', 'claude'],
+ }),
+ mcp: withService({
+ serviceName: 'three.ws MCP',
+ tags: ['mcp', '3d', 'gltf', 'solana', 'agent'],
+ }),
+ agentReputation: withService({
+ serviceName: 'three.ws Agent Reputation',
+ tags: ['reputation', 'agent', 'solana', 'attestation', 'trust'],
+ }),
+ onchainIdentity: withService({
+ serviceName: 'three.ws Identity Verify',
+ tags: ['identity', 'verification', 'agent', 'trust', 'onchain'],
+ }),
+ pumpAudit: withService({
+ serviceName: 'three.ws Pump Audit',
+ tags: ['pump.fun', 'audit', 'agent', 'risk', 'solana'],
+ }),
+ skillMarket: withService({
+ serviceName: 'three.ws Skill Market',
+ tags: ['marketplace', 'agent', 'skills', 'pricing', 'discovery'],
+ }),
+ symbolCheck: withService({
+ serviceName: 'three.ws Symbol Check',
+ tags: ['ticker', 'pump.fun', 'collision', 'launch', 'solana'],
+ }),
+ permit2Demo: withService({
+ serviceName: 'three.ws Permit2 Demo',
+ tags: ['x402', 'permit2', 'eip2612', 'gasless', 'demo'],
+ }),
+ };
+
+ // USE-13: per-tool MCP catalog entries. Each priced tool is its own
+ // catalog row keyed on (resource, toolName) so search can find them
+ // individually instead of all hiding behind the parent /api/mcp resource.
+ // Built from the live TOOL_CATALOG so adding a new priced tool only
+ // requires a pricing entry; the discovery shape follows automatically.
+ const mcpToolItems = buildMcpToolItems({ mcpUrl, mcpAccepts, mcpService: routeMeta.mcp });
return json(
res,
@@ -369,6 +529,9 @@ function handleX402Discovery(req, res) {
description:
'Fetches a glTF/GLB model from a URL and returns structural stats (vertex/triangle counts, materials, textures, animations, extensions) plus a prioritized list of optimization recommendations. Single GET, ?url=…. CDP-Bazaar-cataloged.',
mimeType: 'application/json',
+ serviceName: routeMeta.modelCheck.serviceName,
+ tags: routeMeta.modelCheck.tags,
+ iconUrl: routeMeta.modelCheck.iconUrl,
accepts: modelCheckAccepts,
extensions: extensionsForAccepts(modelCheckAccepts, {
method: 'GET',
@@ -394,8 +557,11 @@ function handleX402Discovery(req, res) {
description:
'Mint to Mesh — pass a Solana fungible-token mint, get back a binary glTF (GLB) cube themed for that token. Color is derived from a stable hash of the mint; when the off-chain Metaplex JSON exposes a PNG/JPEG, that image is embedded as a baseColor texture on every face. Asset.extras carry mint, name, symbol, and timestamp. Useful for any agent that needs an instantly renderable 3D representation of a token. CDP-Bazaar-cataloged.',
mimeType: 'application/json',
- accepts: modelCheckAccepts,
- extensions: extensionsForAccepts(modelCheckAccepts, {
+ serviceName: routeMeta.mintToMesh.serviceName,
+ tags: routeMeta.mintToMesh.tags,
+ iconUrl: routeMeta.mintToMesh.iconUrl,
+ accepts: mintToMeshAccepts,
+ extensions: extensionsForAccepts(mintToMeshAccepts, {
method: 'GET',
discoverable: true,
input: { mint: 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263' },
@@ -420,8 +586,11 @@ function handleX402Discovery(req, res) {
description:
'Revenue Vision — agentic growth analysis powered by Claude. Hand over a mission_brief and get back a single prioritized next-best move, a data-grounded insight, and an honestly-calibrated confidence rating. CDP-Bazaar-cataloged.',
mimeType: 'application/json',
- accepts: modelCheckAccepts,
- extensions: extensionsForAccepts(modelCheckAccepts, {
+ serviceName: routeMeta.revenueVision.serviceName,
+ tags: routeMeta.revenueVision.tags,
+ iconUrl: routeMeta.revenueVision.iconUrl,
+ accepts: revenueVisionAccepts,
+ extensions: extensionsForAccepts(revenueVisionAccepts, {
method: 'GET',
discoverable: true,
input: {
@@ -452,6 +621,9 @@ function handleX402Discovery(req, res) {
description:
'MCP 2025-06-18 Streamable HTTP transport — 3D avatar viewer, glTF model validation/inspection/optimization, and Solana agent data exposed as MCP tools. JSON-RPC 2.0 batch-aware. Currency: USDC.',
mimeType: 'application/json',
+ serviceName: routeMeta.mcp.serviceName,
+ tags: routeMeta.mcp.tags,
+ iconUrl: routeMeta.mcp.iconUrl,
accepts: mcpAccepts,
extensions: extensionsForAccepts(mcpAccepts, bazaarExtension()),
links: {
@@ -462,14 +634,18 @@ function handleX402Discovery(req, res) {
},
},
(() => {
- const accepts = acceptsForPrice('10000');
+ const url = `${origin}/api/x402/agent-reputation`;
+ const accepts = acceptsForPrice('10000', url);
return {
path: '/api/x402/agent-reputation',
- url: `${origin}/api/x402/agent-reputation`,
+ url,
method: 'GET',
description:
'Agent Reputation — return a reputation snapshot for a three.ws agent (USDC paid in to its pump-agent tokens, distinct payers, deployed mints, distribution success rate, Solana attestation counts). Built from three.ws\'s proprietary index of pump_agent_payments, pump_distribute_runs, and solana_attestations.',
mimeType: 'application/json',
+ serviceName: routeMeta.agentReputation.serviceName,
+ tags: routeMeta.agentReputation.tags,
+ iconUrl: routeMeta.agentReputation.iconUrl,
accepts,
extensions: extensionsForAccepts(accepts, {
method: 'GET',
@@ -484,14 +660,18 @@ function handleX402Discovery(req, res) {
};
})(),
(() => {
- const accepts = acceptsForPrice('5000');
+ const url = `${origin}/api/x402/onchain-identity-verify`;
+ const accepts = acceptsForPrice('5000', url);
return {
path: '/api/x402/onchain-identity-verify',
- url: `${origin}/api/x402/onchain-identity-verify`,
+ url,
method: 'GET',
description:
'On-Chain Identity Verifier — given a three.ws agent_id + CAIP-2 chain + contract/mint, verify ownership from the canonical meta.onchain index and return tx_hash/wallet/deploy time evidence when verified. Trust primitive before paying counterparty agents.',
mimeType: 'application/json',
+ serviceName: routeMeta.onchainIdentity.serviceName,
+ tags: routeMeta.onchainIdentity.tags,
+ iconUrl: routeMeta.onchainIdentity.iconUrl,
accepts,
extensions: extensionsForAccepts(accepts, {
method: 'GET',
@@ -514,14 +694,18 @@ function handleX402Discovery(req, res) {
};
})(),
(() => {
- const accepts = acceptsForPrice('20000');
+ const url = `${origin}/api/x402/pump-agent-audit`;
+ const accepts = acceptsForPrice('20000', url);
return {
path: '/api/x402/pump-agent-audit',
- url: `${origin}/api/x402/pump-agent-audit`,
+ url,
method: 'GET',
description:
'Pump-Agent Audit — full operational audit of a pump.fun agent-payments token: total USDC in, unique payers, distribute/buyback success history, latest error reasons, and risk flags (never_distributed, high_distribute_failure_rate, no_buybacks_run). Backed by three.ws\'s indexed pump_distribute_runs and pump_buyback_runs tables.',
mimeType: 'application/json',
+ serviceName: routeMeta.pumpAudit.serviceName,
+ tags: routeMeta.pumpAudit.tags,
+ iconUrl: routeMeta.pumpAudit.iconUrl,
accepts,
extensions: extensionsForAccepts(accepts, {
method: 'GET',
@@ -536,14 +720,18 @@ function handleX402Discovery(req, res) {
};
})(),
(() => {
- const accepts = acceptsForPrice('1000');
+ const url = `${origin}/api/x402/skill-marketplace`;
+ const accepts = acceptsForPrice('1000', url);
return {
path: '/api/x402/skill-marketplace',
- url: `${origin}/api/x402/skill-marketplace`,
+ url,
method: 'GET',
description:
'Skill Marketplace — list active skill listings with prices across all three.ws agents. Filter by skill name to find the cheapest provider for a given capability. Returns price atomics, chain, currency, trial offer, and time-pass terms.',
mimeType: 'application/json',
+ serviceName: routeMeta.skillMarket.serviceName,
+ tags: routeMeta.skillMarket.tags,
+ iconUrl: routeMeta.skillMarket.iconUrl,
accepts,
extensions: extensionsForAccepts(accepts, {
method: 'GET',
@@ -560,14 +748,18 @@ function handleX402Discovery(req, res) {
};
})(),
(() => {
- const accepts = acceptsForPrice('1000');
+ const url = `${origin}/api/x402/symbol-availability`;
+ const accepts = acceptsForPrice('1000', url);
return {
path: '/api/x402/symbol-availability',
- url: `${origin}/api/x402/symbol-availability`,
+ url,
method: 'GET',
description:
'Symbol Availability — pre-launch ticker collision check against three.ws\'s pump.fun mint index. Returns exact-symbol collisions plus trigram-similar tickers so launch agents can avoid name confusion and aggregator-search dilution.',
mimeType: 'application/json',
+ serviceName: routeMeta.symbolCheck.serviceName,
+ tags: routeMeta.symbolCheck.tags,
+ iconUrl: routeMeta.symbolCheck.iconUrl,
accepts,
extensions: extensionsForAccepts(accepts, {
method: 'GET',
@@ -590,6 +782,7 @@ function handleX402Discovery(req, res) {
// EIP-2612 → settleWithPermit path the endpoint is meant to prove.
// permit2VariantOf returns null without CDP creds, in which case we
// omit the resource from discovery (matches the runtime 402 behavior).
+ const url = `${origin}/api/x402/permit2-paid-demo`;
const price = RAW_AMOUNT_TO_USDC('1000');
const baseAccept = env.X402_PAY_TO_BASE
? {
@@ -602,6 +795,7 @@ function handleX402Discovery(req, res) {
asset: env.X402_ASSET_ADDRESS_BASE,
asset_symbol: 'USDC',
maxTimeoutSeconds: 60,
+ resource: url,
extra: { name: 'USD Coin', version: '2', decimals: 6 },
}
: null;
@@ -610,11 +804,14 @@ function handleX402Discovery(req, res) {
const accepts = [permit2];
return {
path: '/api/x402/permit2-paid-demo',
- url: `${origin}/api/x402/permit2-paid-demo`,
+ url,
method: 'GET',
description:
'Permit2 + EIP-2612 Gas Sponsoring Demo — forces the gasless Permit2 path so a fresh wallet holding USDC but ZERO ETH can complete the flow. CDP\'s x402ExactPermit2Proxy submits the EIP-2612 permit + Permit2 transfer atomically via settleWithPermit. Response surfaces the on-chain tx hash and a Basescan link.',
mimeType: 'application/json',
+ serviceName: routeMeta.permit2Demo.serviceName,
+ tags: routeMeta.permit2Demo.tags,
+ iconUrl: routeMeta.permit2Demo.iconUrl,
accepts,
extensions: extensionsForAccepts(accepts, {
method: 'GET',
@@ -629,14 +826,18 @@ function handleX402Discovery(req, res) {
};
})(),
(() => {
- const accepts = acceptsForPrice('50000');
+ const url = `${origin}/api/x402/mint-to-mesh-batch`;
+ const accepts = acceptsForPrice('50000', url);
return {
path: '/api/x402/mint-to-mesh-batch',
- url: `${origin}/api/x402/mint-to-mesh-batch`,
+ url,
method: 'POST',
description:
'Mint-to-Mesh (Batch) — resolve 1–10 Solana SPL mints to themed binary glTF cubes in a single paid call. Per-mint failures report ok:false individually instead of failing the whole batch. Output is base64 GLB bytes for Three.js / Babylon.js / model-viewer.',
mimeType: 'application/json',
+ serviceName: routeMeta.mintToMeshBatch.serviceName,
+ tags: routeMeta.mintToMeshBatch.tags,
+ iconUrl: routeMeta.mintToMeshBatch.iconUrl,
accepts,
extensions: extensionsForAccepts(accepts, {
method: 'POST',
@@ -662,6 +863,10 @@ function handleX402Discovery(req, res) {
}),
};
})(),
+ // USE-13: one Bazaar catalog row per priced MCP tool. The shared
+ // `/api/mcp` resource above is the transport entry; these are
+ // the individual paid tools facilitators index by toolName.
+ ...mcpToolItems,
].filter(Boolean),
},
{ 'cache-control': 'public, max-age=300' },
diff --git a/api/x402/agent-reputation.js b/api/x402/agent-reputation.js
index 6ef9342d1..9abbed289 100644
--- a/api/x402/agent-reputation.js
+++ b/api/x402/agent-reputation.js
@@ -15,6 +15,7 @@
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
import { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/agent-reputation';
@@ -291,6 +292,10 @@ export default paidEndpoint({
networks: ['base', 'solana'],
description: DESCRIPTION,
bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Agent Reputation',
+ tags: ['reputation', 'agent', 'solana', 'attestation', 'trust'],
+ }),
requiredScope: 'x402:bypass',
accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
// USE-21: declare auth-hints. Buyers with an OAuth2 access token granted
diff --git a/api/x402/asset-download.js b/api/x402/asset-download.js
index b4f12c6cb..251b02757 100644
--- a/api/x402/asset-download.js
+++ b/api/x402/asset-download.js
@@ -11,6 +11,7 @@
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
import { sql } from '../_lib/db.js';
import { presignGet } from '../_lib/r2.js';
import { error } from '../_lib/http.js';
@@ -134,6 +135,10 @@ export default async function handler(req, res) {
description: `${DESCRIPTION} — currently delivering: ${asset.title}.`,
mimeType: 'application/json',
bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Asset Bazaar',
+ tags: ['3d', 'asset', 'glb', 'avatar', 'download'],
+ }),
payTo: buildPayToOverride(asset),
// Make the SIWX grant key per-asset by baking the slug into the
// resource URL. Without this, paying for any one asset would unlock
diff --git a/api/x402/dance-tip.js b/api/x402/dance-tip.js
index 5335e4b98..19757729b 100644
--- a/api/x402/dance-tip.js
+++ b/api/x402/dance-tip.js
@@ -18,6 +18,7 @@
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
import { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/dance-tip';
@@ -260,6 +261,10 @@ export default paidEndpoint({
networks: ['base', 'solana'],
description: DESCRIPTION,
bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Pole Club',
+ tags: ['3d', 'dance', 'club', 'tip', 'entertainment'],
+ }),
requiredScope: 'x402:bypass',
accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
siwx: {
diff --git a/api/x402/mint-to-mesh-batch.js b/api/x402/mint-to-mesh-batch.js
index 624c3aecc..c9e5548cc 100644
--- a/api/x402/mint-to-mesh-batch.js
+++ b/api/x402/mint-to-mesh-batch.js
@@ -15,6 +15,7 @@
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
import { readJson } from '../_lib/http.js';
import { createThemedGLB, colorFromMint } from '../_lib/glb-themer.js';
import { fetchTokenMeta } from '../_lib/solana-token-meta.js';
@@ -160,6 +161,10 @@ export default paidEndpoint({
networks: ['base', 'solana'],
description: DESCRIPTION,
bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Mint Mesh Batch',
+ tags: ['3d', 'gltf', 'solana', 'batch', 'render'],
+ }),
requiredScope: 'x402:bypass',
accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
async handler({ req }) {
diff --git a/api/x402/mint-to-mesh.js b/api/x402/mint-to-mesh.js
index a01d200a3..06ae61736 100644
--- a/api/x402/mint-to-mesh.js
+++ b/api/x402/mint-to-mesh.js
@@ -40,6 +40,7 @@ import {
writeConflict,
} from '../_lib/x402/payment-identifier-server.js';
import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
const REQUIRED_SCOPE = 'x402:bypass';
const accessControl = installAccessControl({ requiredScope: REQUIRED_SCOPE });
@@ -221,12 +222,19 @@ export default wrap(async (req, res) => {
const resourceUrl = resolveResourceUrl(req, ROUTE);
const requirements = buildRequirements(resourceUrl);
+ const service = withService({
+ serviceName: 'three.ws Mint to Mesh',
+ tags: ['3d', 'gltf', 'solana', 'token', 'render'],
+ });
const challenge = {
resourceUrl,
accepts: requirements,
description: ROUTE_DESCRIPTION,
bazaar: ROUTE_BAZAAR,
extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },
+ serviceName: service.serviceName,
+ tags: service.tags,
+ iconUrl: service.iconUrl,
};
// USE-23: bypass payment for internal / subscription / OAuth callers.
diff --git a/api/x402/model-check.js b/api/x402/model-check.js
index f24a6d494..b4d112136 100644
--- a/api/x402/model-check.js
+++ b/api/x402/model-check.js
@@ -36,6 +36,7 @@ import {
writeConflict,
} from '../_lib/x402/payment-identifier-server.js';
import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
const REQUIRED_SCOPE = 'x402:bypass';
const accessControl = installAccessControl({ requiredScope: REQUIRED_SCOPE });
@@ -255,12 +256,19 @@ export default wrap(async (req, res) => {
const resourceUrl = resolveResourceUrl(req, ROUTE);
const requirements = buildRequirements(resourceUrl);
+ const service = withService({
+ serviceName: 'three.ws Model Check',
+ tags: ['3d', 'gltf', 'glb', 'inspection', 'validation'],
+ });
const challenge = {
resourceUrl,
accepts: requirements,
description: ROUTE_DESCRIPTION,
bazaar: ROUTE_BAZAAR,
extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },
+ serviceName: service.serviceName,
+ tags: service.tags,
+ iconUrl: service.iconUrl,
};
// USE-23: access-control hook short-circuits payment for internal /
diff --git a/api/x402/onchain-identity-verify.js b/api/x402/onchain-identity-verify.js
index c62d1ba6f..935f5dfcf 100644
--- a/api/x402/onchain-identity-verify.js
+++ b/api/x402/onchain-identity-verify.js
@@ -15,6 +15,7 @@
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
import { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/onchain-identity-verify';
@@ -171,6 +172,10 @@ export default paidEndpoint({
networks: ['base', 'solana'],
description: DESCRIPTION,
bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Identity Verify',
+ tags: ['identity', 'verification', 'agent', 'trust', 'onchain'],
+ }),
requiredScope: 'x402:bypass',
accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
async handler({ req }) {
diff --git a/api/x402/permit2-paid-demo.js b/api/x402/permit2-paid-demo.js
index 21266d9b3..186ceeef8 100644
--- a/api/x402/permit2-paid-demo.js
+++ b/api/x402/permit2-paid-demo.js
@@ -35,6 +35,7 @@ import {
} from '../_lib/x402-spec.js';
import { env } from '../_lib/env.js';
import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
const ROUTE = '/api/x402/permit2-paid-demo';
const REQUIRED_SCOPE = 'x402:bypass';
@@ -186,6 +187,10 @@ export default wrap(async (req, res) => {
}
const resourceUrl = resolveResourceUrl(req, ROUTE);
+ const service = withService({
+ serviceName: 'three.ws Permit2 Demo',
+ tags: ['x402', 'permit2', 'eip2612', 'gasless', 'demo'],
+ });
let requirements;
try {
requirements = buildRequirements(resourceUrl);
@@ -197,6 +202,9 @@ export default wrap(async (req, res) => {
description: ROUTE_DESCRIPTION,
bazaar: ROUTE_BAZAAR,
error: err.message,
+ serviceName: service.serviceName,
+ tags: service.tags,
+ iconUrl: service.iconUrl,
});
}
return error(
@@ -212,6 +220,9 @@ export default wrap(async (req, res) => {
accepts: requirements,
description: ROUTE_DESCRIPTION,
bazaar: ROUTE_BAZAAR,
+ serviceName: service.serviceName,
+ tags: service.tags,
+ iconUrl: service.iconUrl,
};
// USE-23: bypass payment for internal / subscription / OAuth callers.
diff --git a/api/x402/pump-agent-audit.js b/api/x402/pump-agent-audit.js
index f9a20d128..cb1c5dd04 100644
--- a/api/x402/pump-agent-audit.js
+++ b/api/x402/pump-agent-audit.js
@@ -15,6 +15,7 @@
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
import { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/pump-agent-audit';
@@ -242,6 +243,10 @@ export default paidEndpoint({
networks: ['base', 'solana'],
description: DESCRIPTION,
bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Pump Audit',
+ tags: ['pump.fun', 'audit', 'agent', 'risk', 'solana'],
+ }),
requiredScope: 'x402:bypass',
accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
async handler({ req }) {
diff --git a/api/x402/skill-marketplace.js b/api/x402/skill-marketplace.js
index adb5e3b63..52bbaafce 100644
--- a/api/x402/skill-marketplace.js
+++ b/api/x402/skill-marketplace.js
@@ -13,6 +13,7 @@
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
import { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/skill-marketplace';
@@ -181,6 +182,10 @@ export default paidEndpoint({
networks: ['base', 'solana'],
description: DESCRIPTION,
bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Skill Market',
+ tags: ['marketplace', 'agent', 'skills', 'pricing', 'discovery'],
+ }),
siwx: {
statement: 'Sign in to refresh the three.ws skill marketplace without re-paying.',
// 24h grant so a returning agent can re-poll without paying; after the
diff --git a/api/x402/symbol-availability.js b/api/x402/symbol-availability.js
index a50b14070..509bab4e7 100644
--- a/api/x402/symbol-availability.js
+++ b/api/x402/symbol-availability.js
@@ -15,6 +15,7 @@
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
import { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/symbol-availability';
@@ -156,6 +157,10 @@ export default paidEndpoint({
networks: ['base', 'solana'],
description: DESCRIPTION,
bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Symbol Check',
+ tags: ['ticker', 'pump.fun', 'collision', 'launch', 'solana'],
+ }),
requiredScope: 'x402:bypass',
accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
async handler({ req }) {
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 9f4bc2312..268a50716 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -865,6 +865,59 @@ See MCP documentation for full tool schemas and response shapes.
---
+## x402 Paid Endpoints — Sign-In-With-X (SIWX)
+
+Every paid endpoint under `/api/x402/*` is built on the shared `paidEndpoint()` helper. Endpoints can opt into **Sign-In-With-X** (SIWX, CAIP-122) so a wallet that has already paid for a resource can re-access it by signing a message — no second on-chain payment.
+
+### How it works
+
+1. **First call.** The client has no payment header. The server returns a `402 Payment Required` whose body declares both the `accepts[]` payment requirements and a `sign-in-with-x` extension (chain list, signing statement, fresh nonce, `expirationTime`).
+2. **Settle.** The client retries with `X-PAYMENT: <base64>`. The facilitator verifies and settles the USDC transfer. The server records a row in `siwx_payments` keyed by `(resource, address)`.
+3. **Re-access.** Later, the same wallet sends the `SIGN-IN-WITH-X: <base64>` header instead of `X-PAYMENT`. The server parses the CAIP-122 payload, verifies the signature (EIP-191/EIP-1271/EIP-6492 for EVM via viem's `publicClient.verifyMessage`, ed25519 for Solana), checks the nonce against `siwx_nonces` for replay protection, and looks up the grant in `siwx_payments`. On match, the handler runs and the response carries `x-siwx-address: <recovered wallet>` (no `x-payment-response`).
+
+### Opt-in for a new endpoint
+
+Add a single `siwx:` block to `paidEndpoint(spec)`:
+
+```js
+paidEndpoint({
+ route: '/api/x402/my-endpoint',
+ // …other fields…
+ siwx: {
+ statement: 'Sign in to refresh the catalog without re-paying.',
+ ttlSeconds: 24 * 3600, // grant lifetime; null = permanent
+ expirationSeconds: 300, // SIWX message validity window
+ },
+});
+```
+
+That single declaration adds the `sign-in-with-x` extension to every 402 body, accepts the `SIGN-IN-WITH-X` header on incoming requests, and records a grant when a fresh settlement completes.
+
+### Canonical example: `/api/x402/asset-download`
+
+The marquee SIWX endpoint. The catalog lives in the Neon `paid_assets` table — each row carries `slug`, `r2_key`, `price_atomics`, `mime_type`, and optional per-creator payout overrides (`creator_payto_base`, `creator_payto_solana`, `creator_payto_bsc`). Buyers pay once per slug; subsequent re-downloads from the same wallet only require a signature. The response is JSON containing a short-lived presigned R2 URL — large GLBs stream directly from R2 instead of through the function.
+
+Each asset has its own SIWX grant key: the endpoint passes a `resourceUrlBuilder` to `paidEndpoint()` that embeds the slug in the resource URI, so paying for one asset does not unlock the others.
+
+### Operator status
+
+`GET /api/x402-status` reports SIWX wiring under `.siwx`:
+
+```json
+{
+ "siwx": {
+ "configured": true,
+ "paymentsRowCount": 42,
+ "noncesRowCount": 17,
+ "evmVerifierConfigured": true
+ }
+}
+```
+
+`evmVerifierConfigured: true` means `BASE_RPC_URL` is set and smart-contract wallet signatures (Coinbase Smart Wallet, Safe) will verify. Without it, only EOA signatures are accepted.
+
+---
+
## Config API
```
diff --git a/docs/pay-skills-listing.md b/docs/pay-skills-listing.md
index 468b18870..f34d7a985 100644
--- a/docs/pay-skills-listing.md
+++ b/docs/pay-skills-listing.md
@@ -2,31 +2,38 @@
**Website:** https://three.ws
**Discovery:** https://three.ws/.well-known/x402.json
-**OpenAPI:** https://three.ws/.well-known/openapi.yaml
+**OpenAPI:** https://three.ws/openapi.json
**MCP:** https://three.ws/api/mcp
-**Networks:** Base mainnet (USDC), Solana mainnet (USDC)
+**Networks:** Base mainnet (USDC), Arbitrum One (USDC, model-check + mint-to-mesh only), Solana mainnet (USDC)
**Protocol:** x402 v2 (HTTP 402 Payment Required)
## Overview
three.ws is an agent-first 3D model platform. Paid REST endpoints cover glTF/GLB model
-validation, Solana token visualization, Pump.fun agent analytics, and on-chain identity
-verification. All endpoints settle in USDC on Base or Solana mainnet. The MCP server
-exposes the same surface as JSON-RPC tools.
+validation, Solana token visualization, Pump.fun agent analytics, on-chain identity
+verification, and a Claude-backed growth-analysis power. All endpoints settle in USDC
+on Base / Arbitrum / Solana mainnet. The MCP server exposes the same surface as
+JSON-RPC tools.
## Paid Endpoints
+This table mirrors the live `/.well-known/x402.json` resource catalog. Prices below
+are the source of truth and match what the 402 challenges advertise; verify with
+`npx x402-surface-check https://three.ws/.well-known/x402.json`.
+
| Endpoint | Method | Price | Description |
|---|---|---|---|
-| `/api/mcp` | POST | $0.001 | MCP 2025-06-18 Streamable HTTP — 3D model tools + Solana agent data as JSON-RPC |
-| `/api/x402/model-check` | GET | $0.001 | Fetch a glTF/GLB from a URL, return vertex/triangle counts, materials, textures, animations, extensions, and optimization hints |
-| `/api/x402/mint-to-mesh` | GET | $0.001 | Pass a Solana SPL mint, get a binary GLB cube themed for that token (color + texture derived from on-chain metadata) |
+| `/api/mcp` | POST | $0.001 | MCP 2025-06-18 Streamable HTTP — 3D model tools + Solana agent data as JSON-RPC 2.0 |
+| `/api/x402/model-check` | GET | $0.001 | Fetch a glTF/GLB from a URL, return vertex/triangle counts, materials, textures, animations, extensions, and optimization hints. CDP-Bazaar-cataloged. |
+| `/api/x402/mint-to-mesh` | GET | $0.001 | Pass a Solana SPL mint, get a binary glTF (GLB) cube themed for that token (color + texture derived from on-chain metadata). CDP-Bazaar-cataloged. |
+| `/api/insights/revenue-vision` | GET | $0.001 | Hand over a `mission_brief`, get back a Claude-generated `{ insight, recommended_move, confidence }` payload. CDP-Bazaar-cataloged. |
| `/api/x402/symbol-availability` | GET | $0.001 | Pre-launch ticker collision check against three.ws's pump.fun mint index; returns exact and trigram-similar matches |
| `/api/x402/skill-marketplace` | GET | $0.001 | List active skill listings and prices across all three.ws agents; filter by skill name to find the cheapest provider |
+| `/api/x402/permit2-paid-demo` | GET | $0.001 | Permit2 + EIP-2612 gas-sponsoring demo (Base only). Forces the gasless Permit2 path for fresh wallets holding USDC but zero ETH. Listed only when CDP credentials are configured. |
| `/api/x402/onchain-identity-verify` | GET | $0.005 | Verify an agent's ownership of a Solana contract/mint from three.ws's on-chain identity index; returns tx_hash + wallet evidence |
-| `/api/x402/agent-reputation` | GET | $0.010 | Reputation snapshot for a three.ws agent: USDC paid in, distinct payers, deployed mints, distribution success rate, attestation count |
-| `/api/x402/pump-agent-audit` | GET | $0.020 | Full operational audit of a pump.fun agent-payments token: USDC in, distribute/buyback history, latest error reasons, risk flags |
-| `/api/x402/mint-to-mesh-batch` | POST | $0.050 | Resolve 1–10 Solana SPL mints to themed GLB cubes in one call; per-mint failures report individually |
+| `/api/x402/agent-reputation` | GET | $0.01 | Reputation snapshot for a three.ws agent: USDC paid in, distinct payers, deployed mints, distribution success rate, attestation count |
+| `/api/x402/pump-agent-audit` | GET | $0.02 | Full operational audit of a pump.fun agent-payments token: USDC in, distribute/buyback history, latest error reasons, risk flags |
+| `/api/x402/mint-to-mesh-batch` | POST | $0.05 | Resolve 1–10 Solana SPL mints to themed GLB cubes in one call; per-mint failures report individually |
All prices are in USDC with 6 decimals. `$0.001` = 1000 atomics.
@@ -66,13 +73,22 @@ const { glb } = await res2.json(); // base64 GLB bytes
## CORS
-All paid endpoints include `Access-Control-Allow-Origin: *` — browser-based and
-server-side agents can call them directly from any origin.
+All paid endpoints (`/api/mcp`, `/api/x402/*`, `/api/insights/revenue-vision`) and the
+public discovery docs (`/.well-known/x402`, `/.well-known/x402.json`, `/openapi.json`)
+respond with `Access-Control-Allow-Origin: *` on both the OPTIONS preflight and the
+actual request. The CORS layer also exposes `PAYMENT-REQUIRED`, `x-payment-response`,
+`x-payment-network`, and `x-payment-tx` so browser-based agents can drive the 402-pay-retry
+flow and surface settlement receipts. Both server-to-server and browser-agent paths
+are supported.
## Notes
- All endpoints return structured JSON 402 challenges before access; probe with
`npx x402-surface-check https://three.ws/.well-known/x402.json` to enumerate live prices.
-- Server-to-server and browser-agent paths are both supported.
+- Every 402 challenge echoes the resource URL both at top-level `resource.url` AND in
+ each `accepts[].resource`, so wallet/facilitator spend logs reconcile cleanly without
+ relying on the buyer to remember which endpoint they hit.
- Solana routes require a `feePayer` field in the accept block (included automatically
in the 402 challenge) for PayAI's `/verify` to accept the SPL transfer.
+- No public key-generation endpoints. three.ws does not run any server-side vanity-key
+ or keypair-generation paid endpoint — wallet keys never leave the buyer's environment.
diff --git a/mcp-bridge/src/bazaar-discover.js b/mcp-bridge/src/bazaar-discover.js
index 29b9daa26..10d1639dd 100644
--- a/mcp-bridge/src/bazaar-discover.js
+++ b/mcp-bridge/src/bazaar-discover.js
@@ -48,21 +48,44 @@ function maxPriceAtomic() {
// Derive a stable MCP tool name from a Bazaar item.
//
// MCP tool names must be unique and conventionally are snake_case identifiers.
-// We start from the description's first segment (everything before "—" or "·")
-// and fall back to the URL path. Sanitize to [a-z0-9_], cap length, and
-// disambiguate collisions with a numeric suffix in the caller.
+// Strategy: prefer the URL's last path segment (operation name), then fall
+// through to the description with the publisher prefix stripped, then to a
+// generic 'tool'. Sanitize to [a-z0-9_], cap length. Caller disambiguates
+// collisions with a numeric suffix.
const NAME_PREFIX = 'paid_';
-export function deriveToolName(item) {
- const desc = String(item.description || '').trim();
- const first = desc.split(/[—·:|]/)[0]?.trim() || '';
- let base = first || new URL(item.resource).pathname.split('/').filter(Boolean).pop() || 'tool';
- base = base
+function sanitize(s) {
+ return String(s || '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '_')
.replace(/^_+|_+$/g, '')
.slice(0, 48);
- if (!base) base = 'tool';
+}
+
+export function deriveToolName(item) {
+ let candidate = '';
+ try {
+ const path = new URL(item.resource).pathname;
+ const segs = path.split('/').filter(Boolean);
+ // Skip generic segments like "api", "tools", "v1", "v2", numeric IDs.
+ for (let i = segs.length - 1; i >= 0; i--) {
+ const seg = segs[i];
+ if (/^(api|tools|v\d+|public|x402|paid)$/i.test(seg)) continue;
+ candidate = seg;
+ break;
+ }
+ } catch {
+ // resource wasn't a valid URL — fall through to description
+ }
+
+ if (!candidate) {
+ const desc = String(item.description || '').trim();
+ // Take the segment AFTER a publisher prefix like "Provider · operation".
+ const parts = desc.split(/[—·:|]/).map((s) => s.trim()).filter(Boolean);
+ candidate = parts[1] || parts[0] || '';
+ }
+
+ const base = sanitize(candidate) || 'tool';
return `${NAME_PREFIX}${base}`;
}
diff --git a/mcp-bridge/tests/smoke.mjs b/mcp-bridge/tests/smoke.mjs
new file mode 100644
index 000000000..cdab7df44
--- /dev/null
+++ b/mcp-bridge/tests/smoke.mjs
@@ -0,0 +1,155 @@
+// Smoke test for the MCP stdio bridge.
+//
+// Launches src/index.js as a subprocess with a generated test signer (no
+// real funds at risk — the bridge never tries to settle, we only exercise
+// the start-up path, tool listing, and the spending-cap abort).
+//
+// Test flow:
+// 1. Boot the bridge, send initialize/tools/list — assert call_paid_endpoint,
+// list_bazaar_tools, refresh_bazaar exist + at least one paid_* dynamic tool.
+// 2. Call call_paid_endpoint on a real x402-paid resource with
+// MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC=1 — assert the response carries
+// the cap-exceeded error string.
+// 3. Re-launch the bridge and confirm ~/.x402-mcp-bridge/channels exists
+// (storage directory survives restart). The channel file itself only
+// writes after a real settlement, so we only assert the directory.
+
+import { spawn } from 'node:child_process';
+import { existsSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { generatePrivateKey } from 'viem/accounts';
+
+let nextId = 1;
+function frame(method, params) {
+ return JSON.stringify({ jsonrpc: '2.0', id: nextId++, method, params }) + '\n';
+}
+
+async function withBridge(env, run) {
+ const child = spawn('node', [join(import.meta.dirname, '..', 'src', 'index.js')], {
+ stdio: ['pipe', 'pipe', 'pipe'],
+ env: { ...process.env, ...env },
+ });
+
+ let stdoutBuf = '';
+ let stderrBuf = '';
+ const pending = new Map();
+
+ child.stdout.on('data', (chunk) => {
+ stdoutBuf += chunk.toString('utf8');
+ let nl;
+ while ((nl = stdoutBuf.indexOf('\n')) !== -1) {
+ const line = stdoutBuf.slice(0, nl);
+ stdoutBuf = stdoutBuf.slice(nl + 1);
+ if (!line.trim()) continue;
+ let msg;
+ try {
+ msg = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ if (msg.id && pending.has(msg.id)) {
+ const { resolve } = pending.get(msg.id);
+ pending.delete(msg.id);
+ resolve(msg);
+ }
+ }
+ });
+ child.stderr.on('data', (chunk) => {
+ stderrBuf += chunk.toString('utf8');
+ });
+
+ const send = (method, params) => {
+ const json = frame(method, params);
+ const id = JSON.parse(json).id;
+ const p = new Promise((resolve, reject) => {
+ pending.set(id, { resolve, reject });
+ setTimeout(() => {
+ if (pending.has(id)) {
+ pending.delete(id);
+ reject(new Error(`timeout waiting for ${method}#${id}`));
+ }
+ }, 30_000);
+ });
+ child.stdin.write(json);
+ return p;
+ };
+
+ try {
+ await send('initialize', {
+ protocolVersion: '2025-03-26',
+ clientInfo: { name: 'smoke', version: '0.0.1' },
+ capabilities: {},
+ });
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');
+ return await run({ send, getStderr: () => stderrBuf });
+ } finally {
+ child.kill('SIGTERM');
+ await new Promise((r) => child.once('exit', r));
+ }
+}
+
+function assert(cond, msg) {
+ if (!cond) {
+ console.error('FAIL:', msg);
+ process.exit(1);
+ } else {
+ console.log('PASS:', msg);
+ }
+}
+
+const tmpRoot = mkdtempSync(join(tmpdir(), 'x402-bridge-smoke-'));
+const channelsDir = join(tmpRoot, 'channels');
+
+const env = {
+ // Burner EVM key so the bridge can boot. We never make real settlements
+ // in this test, just exercise the start-up + cap-abort paths.
+ MCP_BRIDGE_EVM_PRIVATE_KEY: generatePrivateKey(),
+ MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC: '1', // 1 atomic unit = effectively zero
+ MCP_BRIDGE_DISCOVER_LIMIT: '5',
+ X402_MCP_BRIDGE_CHANNELS_DIR: channelsDir,
+};
+
+try {
+ await withBridge(env, async ({ send }) => {
+ const tools = await send('tools/list', {});
+ const names = (tools.result?.tools || []).map((t) => t.name);
+ console.log(' registered tools:', names.slice(0, 8).join(', '), '…');
+ assert(names.includes('call_paid_endpoint'), 'call_paid_endpoint registered');
+ assert(names.includes('list_bazaar_tools'), 'list_bazaar_tools registered');
+ assert(names.includes('refresh_bazaar'), 'refresh_bazaar registered');
+ assert(names.some((n) => n.startsWith('paid_')), 'at least one dynamic paid_* tool');
+
+ // Spending-cap check: call any real x402-paid endpoint with cap=1.
+ // The bridge SHOULD return an isError tool result mentioning the cap.
+ // We pick one of the discovered tools so the URL is guaranteed live.
+ const dynamicTool = (tools.result?.tools || []).find((t) => t.name.startsWith('paid_'));
+ const resourceUrl = dynamicTool ? dynamicTool.description.match(/Resource: (\S+)/)?.[1] : null;
+ assert(!!resourceUrl, 'extracted resource URL from a dynamic tool description');
+
+ const call = await send('tools/call', {
+ name: 'call_paid_endpoint',
+ arguments: { url: resourceUrl, method: 'GET' },
+ });
+ const text =
+ call.result?.content?.map((c) => c.text || '').join('\n') ||
+ call.error?.message ||
+ JSON.stringify(call);
+ assert(call.result?.isError === true, 'call_paid_endpoint returned isError for cap-blocked call');
+ assert(
+ /exceeds spending cap|cap (1|of)/i.test(text) || /aborted/i.test(text),
+ 'error text mentions the spending cap',
+ );
+ });
+
+ // Second boot: prove the channels directory survives.
+ await withBridge(env, async ({ send }) => {
+ await send('tools/list', {});
+ });
+ assert(existsSync(channelsDir), 'channels directory persists across bridge restarts');
+ assert(existsSync(join(channelsDir, 'client')), 'channels/client subdir created by FileClientChannelStorage');
+} finally {
+ rmSync(tmpRoot, { recursive: true, force: true });
+}
+
+console.log('\nAll smoke checks passed.');
diff --git a/mcp-server/README.md b/mcp-server/README.md
new file mode 100644
index 000000000..5f9ce197b
--- /dev/null
+++ b/mcp-server/README.md
@@ -0,0 +1,199 @@
+# @3d-agent/mcp-server
+
+A local MCP server that exposes the three.ws stack as **paid MCP tools** for
+Claude Desktop, Cursor, and any MCP-compatible client. Each tool quotes a
+USDC price; calls without payment return an `x402` `PaymentRequired`
+envelope (v2 MCP transport spec — `isError: true` + `structuredContent` +
+`content[0].text`). Successful settlements are returned in
+`_meta["x402/payment-response"]` per the spec.
+
+## Tools
+
+| Tool | Scheme | Price | What it returns |
+|------|--------|-------|-----------------|
+| `get_pose_seed` | `exact` | $0.001 | Deterministic seed + full Euler-rotation pose map (radians) for the three.ws pose-studio mannequin, picked from the in-repo preset library by matching prompt tokens against preset IDs/labels/groups. Includes a previewUrl pointing at `https://three.ws/pose?seed=…&preset=…`. |
+| `pump_snapshot` | `exact` | $0.005 | Live token snapshot — USD price (Jupiter), 24h volume + pair (Dexscreener), mint metadata + image (pump.fun frontend-api-v3), and on-chain top-holder distribution (Solana RPC `getTokenLargestAccounts`). Adds Helius DAS data when `HELIUS_API_KEY` is set. |
+| `agent_reputation` | `exact` | $0.01 | ERC-8004 reputation: aggregate `getReputation`, `getTotalStake`, and the latest `ReputationSubmitted` / `ReputationStaked` events from the canonical ReputationRegistry on the requested chain (default Base). Resolves agentId from a wallet when the input is an EVM address. |
+| `vanity_grinder` | `upto` | up to $0.50 | Solana keypair whose base58 address starts with the chosen `prefix` (and optionally ends with `suffix`). Returns the full base58 secret key — handle as a secret. Actual settled USDC scales with iterations: `$0.01 base + $0.0000001 per attempt`, capped at $0.50. |
+
+All four tools are advertised to the x402 Bazaar via the per-tool
+`declareDiscoveryExtension({ toolName, transport: 'stdio', inputSchema, … })`
+extension that ships in the payment-required envelope. Bazaar-enabled
+facilitators index these tools under `type: "mcp"` once a buyer pays for them.
+
+## Architecture
+
+```
+┌─────────────────┐ ┌─────────────────────┐ ┌──────────────────────┐
+│ Claude Desktop │────▶│ @3d-agent/mcp │────▶│ x402 facilitator │
+│ / Cursor │ │ (stdio transport) │ │ (CDP for Base, │
+│ │ │ │ │ PayAI for Solana) │
+└─────────────────┘ └─────────────────────┘ └──────────────────────┘
+ │ │
+ │ tools/call (no _meta) │ 1. extract _meta["x402/payment"]
+ │──────────────────────▶│ 2. resourceServer.verifyPayment
+ │ │ 3. run tool handler
+ │ │ 4. resourceServer.settlePayment
+ │ │ 5. attach _meta["x402/payment-response"]
+ │ result + payment-meta │
+ │◀──────────────────────│
+```
+
+The server itself is the x402 **resource server**. It owns:
+
+- A shared `x402ResourceServer` with `ExactEvmScheme` (eip155:*),
+ `UptoEvmScheme` (vanity grinder), and `ExactSvmScheme` (solana:*) registered.
+- A CDP `HTTPFacilitatorClient` when `CDP_API_KEY_ID` + `CDP_API_KEY_SECRET`
+ are set (preferred for Base — required for CDP Bazaar discovery).
+- PayAI HTTP facilitators as fallback (Base + Solana).
+
+See [`src/payments.js`](src/payments.js).
+
+## Wallet config
+
+Set at least one of:
+
+- `MCP_EVM_PAYMENT_ADDRESS` (or `X402_PAY_TO_BASE`) — Base USDC payouts.
+- `MCP_SVM_PAYMENT_ADDRESS` (or `X402_PAY_TO_SOLANA`) — Solana USDC payouts.
+
+Default USDC assets (overridable):
+
+- Base: `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` (`X402_ASSET_ADDRESS_BASE`).
+- Solana: `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` (`X402_ASSET_MINT_SOLANA`).
+
+CDP facilitator (recommended for Base + Bazaar):
+
+```
+CDP_API_KEY_ID=...
+CDP_API_KEY_SECRET=...
+X402_CDP_FACILITATOR_URL=https://api.cdp.coinbase.com/platform/v2/x402
+```
+
+Without CDP credentials the server falls back to the public PayAI facilitator
+(`X402_FACILITATOR_URL_BASE`, `X402_FACILITATOR_URL_SOLANA`,
+`X402_FACILITATOR_TOKEN_*`).
+
+Tool-specific config:
+
+| Env var | Used by | Default |
+|---------|---------|---------|
+| `SOLANA_RPC_URL` | `pump_snapshot`, `vanity_grinder` | `https://api.mainnet-beta.solana.com` |
+| `HELIUS_API_KEY` | `pump_snapshot` (optional) | unset |
+| `MCP_POSE_PREVIEW_BASE` | `get_pose_seed` previewUrl | `https://three.ws/pose` |
+| `MCP_AGENT_REP_RPC_<chainId>` | `agent_reputation` per-chain RPC override | public RPC for that chain |
+| `MCP_AGENT_REP_LOG_WINDOW` | `agent_reputation` event scan window (blocks) | `200000` |
+
+## Run standalone
+
+From the monorepo root:
+
+```bash
+npm install
+node mcp-server/src/index.js
+```
+
+The server speaks stdio JSON-RPC and prints `[mcp-server] ready — 4 paid
+tools registered over stdio` to stderr once initialization finishes.
+
+### MCP inspector
+
+```bash
+npx -y @modelcontextprotocol/inspector node mcp-server/src/index.js
+```
+
+Then in the inspector UI, list tools and try calling `get_pose_seed` with
+`{ "prompt": "wave hello" }`. The first call returns the
+`PaymentRequired` envelope; the inspector lets you craft an `_meta`
+payload to retry with a real x402 payment.
+
+## Claude Desktop
+
+Edit `~/Library/Application Support/Claude/claude_desktop_config.json`
+(macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):
+
+```json
+{
+ "mcpServers": {
+ "3d-agent": {
+ "command": "node",
+ "args": ["/absolute/path/to/three.ws/mcp-server/src/index.js"],
+ "env": {
+ "MCP_EVM_PAYMENT_ADDRESS": "0xYourBaseWallet",
+ "MCP_SVM_PAYMENT_ADDRESS": "YourSolanaWallet",
+ "CDP_API_KEY_ID": "...",
+ "CDP_API_KEY_SECRET": "...",
+ "SOLANA_RPC_URL": "https://mainnet.helius-rpc.com/?api-key=YOUR_HELIUS_KEY",
+ "HELIUS_API_KEY": "YOUR_HELIUS_KEY"
+ }
+ }
+ }
+}
+```
+
+Restart Claude Desktop. The four tools appear under "3d-agent" in the
+tool picker. Ask Claude: *"Use get_pose_seed to give me a warrior pose."*
+
+## Cursor
+
+In Cursor's settings (`Cursor > Settings > Features > MCP`):
+
+```json
+{
+ "mcpServers": {
+ "3d-agent": {
+ "command": "node",
+ "args": ["/absolute/path/to/three.ws/mcp-server/src/index.js"],
+ "env": {
+ "MCP_EVM_PAYMENT_ADDRESS": "0xYourBaseWallet",
+ "MCP_SVM_PAYMENT_ADDRESS": "YourSolanaWallet"
+ }
+ }
+ }
+}
+```
+
+Cursor's MCP integration handles the x402 payment loop automatically when
+its companion x402 client is configured. Otherwise the agent will see the
+`PaymentRequired` envelope and can negotiate payment programmatically.
+
+## Programmatic client
+
+Use `@x402/mcp`'s `x402MCPClient` (or `createx402MCPClient` factory) to call
+these tools from another Node service. The client auto-handles 402 retries:
+
+```js
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import { wrapMCPClientWithPayment } from '@x402/mcp';
+import { x402Client } from '@x402/core/client';
+import { ExactEvmScheme } from '@x402/evm/exact/client';
+import { privateKeyToAccount } from 'viem/accounts';
+
+const transport = new StdioClientTransport({
+ command: 'node',
+ args: ['/abs/path/three.ws/mcp-server/src/index.js'],
+});
+const mcp = new Client({ name: 'agent', version: '1.0.0' });
+await mcp.connect(transport);
+
+const account = privateKeyToAccount(process.env.AGENT_EVM_PRIVATE_KEY);
+const x402 = new x402Client().register('eip155:8453', new ExactEvmScheme(account));
+const paid = wrapMCPClientWithPayment(mcp, x402, { autoPayment: true });
+
+const result = await paid.callTool('get_pose_seed', { prompt: 'warrior stance' });
+console.log(JSON.parse(result.content[0].text));
+```
+
+## Notes on the `upto` flow
+
+`vanity_grinder` uses the x402 `upto` scheme: the client signs an
+authorization for a maximum of $0.50 USDC, and the server-side
+`paidUpto()` wrapper calls `resourceServer.settlePayment(...,
+settlementOverrides: { amount: <actual> })` so the facilitator settles the
+real metered amount. The Permit2 nonce makes each authorization
+single-use; partial settlement is enforced by the facilitator contract.
+
+## Pricing source-of-truth
+
+Per-tool prices are declared in each tool file's `priceUsd` argument to
+`paid()` / `paidUpto()`. Changing them is a one-line edit per tool.
diff --git a/mcp-server/package.json b/mcp-server/package.json
index 69e1ee999..8f4c70aee 100644
--- a/mcp-server/package.json
+++ b/mcp-server/package.json
@@ -27,6 +27,7 @@
"@x402/mcp": "^2.12.0",
"@x402/svm": "^2.12.0",
"@coinbase/x402": "^2.1.0",
+ "bs58": "^6.0.0",
"ethers": "^6.16.0",
"zod": "^3.23.8"
}
diff --git a/mcp-server/src/index.js b/mcp-server/src/index.js
new file mode 100755
index 000000000..36c9001f1
--- /dev/null
+++ b/mcp-server/src/index.js
@@ -0,0 +1,75 @@
+#!/usr/bin/env node
+// @3d-agent/mcp-server entry point.
+//
+// Boots an MCP server over stdio that exposes paid tools for pose generation,
+// pump.fun snapshots, ERC-8004 reputation lookups, and Solana vanity mining.
+// Tool calls without payment return the v2 MCP-transport `PaymentRequired`
+// envelope (per @x402/mcp + transports-v2/mcp.md). Successful settlements are
+// reported back to the client under `_meta["x402/payment-response"]`.
+//
+// Run standalone:
+// node mcp-server/src/index.js
+//
+// Or wire into Claude Desktop / Cursor as documented in README.md.
+
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
+
+import { getLastFacilitatorInitError, getResourceServer } from './payments.js';
+import { buildPoseSeedTool } from './tools/pose-seed.js';
+import { buildPumpSnapshotTool } from './tools/pump-snapshot.js';
+import { buildAgentReputationTool } from './tools/agent-reputation.js';
+import { buildVanityGrinderTool } from './tools/vanity-grinder.js';
+
+async function main() {
+ // Force the shared x402 resource server to initialize before any tool is
+ // registered — this fetches /supported from each facilitator so verify
+ // + settle don't pay that cost on the first paid call.
+ await getResourceServer();
+ const initErr = getLastFacilitatorInitError();
+ if (initErr) {
+ console.error(`[mcp-server] facilitator init returned warnings: ${initErr.message}`);
+ }
+
+ const server = new McpServer({
+ name: '3d-agent-mcp',
+ version: '1.0.0',
+ }, {
+ capabilities: { tools: {} },
+ instructions:
+ 'Paid x402 MCP tools from three.ws. Each tool quotes its USDC price in its description. ' +
+ 'Tool calls without an x402 payment payload in _meta return a PaymentRequired structuredContent ' +
+ '(v2 MCP transport spec). Tools cover pose generation (get_pose_seed), Solana token snapshots ' +
+ '(pump_snapshot), ERC-8004 agent reputation (agent_reputation), and Solana vanity address ' +
+ 'mining (vanity_grinder, upto-priced).',
+ });
+
+ const tools = await Promise.all([
+ buildPoseSeedTool(),
+ buildPumpSnapshotTool(),
+ buildAgentReputationTool(),
+ buildVanityGrinderTool(),
+ ]);
+
+ for (const t of tools) {
+ server.registerTool(
+ t.name,
+ {
+ title: t.title,
+ description: t.description,
+ inputSchema: t.inputSchema,
+ },
+ t.handler,
+ );
+ }
+
+ const transport = new StdioServerTransport();
+ await server.connect(transport);
+ // Log to stderr so the stdout channel stays clean for MCP JSON-RPC frames.
+ console.error(`[mcp-server] ready — ${tools.length} paid tools registered over stdio`);
+}
+
+main().catch((err) => {
+ console.error(`[mcp-server] fatal: ${err.stack || err.message || err}`);
+ process.exit(1);
+});
diff --git a/mcp-server/src/payments.js b/mcp-server/src/payments.js
index 3681c361a..51e3036fa 100644
--- a/mcp-server/src/payments.js
+++ b/mcp-server/src/payments.js
@@ -30,7 +30,11 @@ import { HTTPFacilitatorClient, x402ResourceServer } from '@x402/core/server';
import { registerExactEvmScheme } from '@x402/evm/exact/server';
import { UptoEvmScheme as UptoEvmServerScheme } from '@x402/evm/upto/server';
import { registerExactSvmScheme } from '@x402/svm/exact/server';
-import { createPaymentWrapper, createToolResourceUrl } from '@x402/mcp';
+import {
+ createPaymentWrapper,
+ createToolResourceUrl,
+ extractPaymentFromMeta,
+} from '@x402/mcp';
import { declareDiscoveryExtension } from '@x402/extensions/bazaar';
// CAIP-2 IDs we care about (mirrors api/_lib/x402-spec.js).
@@ -274,4 +278,107 @@ export async function paid(cfg, handler) {
});
}
+/**
+ * Wrap an `upto`-scheme tool whose handler decides the actual settlement
+ * amount based on resource consumption. The `priceUsd` becomes the
+ * authorized maximum; the handler returns `{ result, settleAmount }` where
+ * `settleAmount` is a percent string ("50%"), atomic units ("250000"), or a
+ * USD price ("$0.25"). The wrapper settles via x402ResourceServer's
+ * settlementOverrides — facilitator enforces settle <= max.
+ *
+ * Unlike `paid()` (which uses `createPaymentWrapper`), this wrapper
+ * implements the MCP transport flow manually so it can plumb
+ * `settlementOverrides.amount` through `settlePayment`. The 402 response
+ * shape (structuredContent + content[0].text + isError:true) matches the
+ * v2 MCP transport spec.
+ */
+export async function paidUpto(cfg, handler) {
+ const {
+ toolName,
+ description,
+ priceUsd,
+ networks = [NETWORK_BASE_MAINNET],
+ inputSchema,
+ example,
+ outputExample,
+ extra,
+ } = cfg;
+
+ if (!toolName) throw new Error('paidUpto(): toolName is required');
+ if (!priceUsd) throw new Error('paidUpto(): priceUsd is required (max)');
+ if (!inputSchema) throw new Error('paidUpto(): inputSchema is required');
+
+ const resourceServer = await getResourceServer();
+ const resourceUrl = createToolResourceUrl(toolName);
+ const accepts = await buildAcceptsForTool({
+ resourceServer,
+ scheme: 'upto',
+ priceUsd,
+ networks,
+ resourceUrl,
+ extra,
+ });
+ const resourceInfo = { url: resourceUrl, description, mimeType: 'application/json' };
+ const bazaar = declareDiscoveryExtension({
+ toolName,
+ description,
+ transport: 'stdio',
+ inputSchema,
+ example,
+ output: outputExample ? { example: outputExample } : undefined,
+ });
+
+ const paymentRequiredResult = async (errorMessage) => {
+ const paymentRequired = await resourceServer.createPaymentRequiredResponse(
+ accepts,
+ resourceInfo,
+ errorMessage,
+ bazaar,
+ );
+ return {
+ structuredContent: paymentRequired,
+ content: [{ type: 'text', text: JSON.stringify(paymentRequired) }],
+ isError: true,
+ };
+ };
+
+ return async (args, extra) => {
+ const _meta = extra?._meta;
+ const paymentPayload = extractPaymentFromMeta({ name: toolName, arguments: args, _meta });
+ if (!paymentPayload) {
+ return paymentRequiredResult('Payment required to access this tool');
+ }
+ const matched = resourceServer.findMatchingRequirements(accepts, paymentPayload);
+ if (!matched) {
+ return paymentRequiredResult('No matching payment requirements for this payload');
+ }
+ const verify = await resourceServer.verifyPayment(paymentPayload, matched, bazaar);
+ if (!verify.isValid) {
+ return paymentRequiredResult(verify.invalidReason || 'Payment verification failed');
+ }
+ let handlerOutput;
+ try {
+ handlerOutput = await handler(args, { context: extra, requirement: matched });
+ } catch (err) {
+ return paymentRequiredResult(`Tool failed before settlement: ${err.message}`);
+ }
+ const { result, settleAmount } = handlerOutput;
+ if (!result) {
+ return paymentRequiredResult('Tool handler returned no result');
+ }
+ const overrides = settleAmount ? { amount: String(settleAmount) } : undefined;
+ let settle;
+ try {
+ settle = await resourceServer.settlePayment(paymentPayload, matched, bazaar, undefined, overrides);
+ } catch (err) {
+ return paymentRequiredResult(`Settlement failed: ${err.message}`);
+ }
+ const text = typeof result === 'string' ? result : JSON.stringify(result);
+ return {
+ content: [{ type: 'text', text }],
+ _meta: { 'x402/payment-response': settle },
+ };
+ };
+}
+
export { NETWORK_BASE_MAINNET, NETWORK_SOLANA_MAINNET };
diff --git a/mcp-server/src/tools/agent-reputation.js b/mcp-server/src/tools/agent-reputation.js
new file mode 100644
index 000000000..df5506f57
--- /dev/null
+++ b/mcp-server/src/tools/agent-reputation.js
@@ -0,0 +1,271 @@
+// `agent_reputation` — paid MCP tool that reads ERC-8004 reputation for an
+// agent (by agentId, EVM wallet, or "eip155:<chain>:<wallet>" CAIP-10 ID).
+//
+// Pricing: $0.01 USDC, settled `exact` on Base or Solana.
+//
+// All reads are made directly against the canonical ERC-8004 reference
+// deployments via ethers JsonRpcProvider — no third-party indexers, no
+// cached snapshots, no fallback values. By default we query Base; the
+// caller can override with `chain: "ethereum"|"base"|"arbitrum"|"optimism"|"polygon"|"bsc"`
+// or pass a numeric chainId.
+//
+// The result includes:
+// - aggregate reputation (totalScore + count + average) via getReputation
+// - total ETH staked on the agent's vouches via getTotalStake
+// - recent ReputationSubmitted + ReputationStaked events (latest 25)
+// - the agent's URI + wallet (Identity Registry) when resolvable
+//
+// All numeric responses are returned both as decimal strings (for safe
+// integer transport) and as parsed Number where the value fits in float64.
+
+import { JsonRpcProvider, Contract, isAddress, ZeroAddress } from 'ethers';
+import { z } from 'zod';
+
+import { paid } from '../payments.js';
+
+const TOOL_NAME = 'agent_reputation';
+const TOOL_DESCRIPTION =
+ 'ERC-8004 on-chain reputation for an agent: aggregate score + count + average from the canonical ReputationRegistry, total ETH staked on vouches, and the latest ReputationSubmitted/ReputationStaked events. Resolves agentId from a wallet via IdentityRegistry when needed. Reads default to Base; switch chains via "chain". Paid: $0.01 USDC.';
+
+const IDENTITY_REGISTRY_ABI = [
+ 'function balanceOf(address owner) external view returns (uint256)',
+ 'function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256)',
+ 'function ownerOf(uint256 tokenId) external view returns (address)',
+ 'function tokenURI(uint256 tokenId) external view returns (string)',
+ 'function getAgentWallet(uint256 agentId) external view returns (address)',
+ 'function totalSupply() external view returns (uint256)',
+];
+
+const REPUTATION_REGISTRY_ABI = [
+ 'function getReputation(uint256 agentId) external view returns (uint256 totalScore, uint256 count)',
+ 'function getTotalStake(uint256 agentId) external view returns (uint256)',
+ 'event ReputationSubmitted(uint256 indexed agentId, address indexed submitter, uint8 score, string comment)',
+ 'event ReputationStaked(uint256 indexed agentId, address indexed staker, uint8 score, uint256 value)',
+];
+
+const IDENTITY_REGISTRY_MAINNET = '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432';
+const REPUTATION_REGISTRY_MAINNET = '0x8004BAa17C55a88189AE136b182e5fdA19dE9b63';
+
+// Canonical mainnet RPCs. Operators may pin custom endpoints via
+// MCP_AGENT_REP_RPC_<chainId> to avoid rate-limiting the public defaults.
+const CHAINS = {
+ base: { id: 8453, rpc: 'https://mainnet.base.org', name: 'Base' },
+ ethereum: { id: 1, rpc: 'https://eth.llamarpc.com', name: 'Ethereum' },
+ arbitrum: { id: 42161, rpc: 'https://arb1.arbitrum.io/rpc', name: 'Arbitrum One' },
+ optimism: { id: 10, rpc: 'https://mainnet.optimism.io', name: 'Optimism' },
+ polygon: { id: 137, rpc: 'https://polygon-rpc.com', name: 'Polygon' },
+ bsc: { id: 56, rpc: 'https://bsc-dataseed1.binance.org', name: 'BNB Chain' },
+ avalanche: { id: 43114, rpc: 'https://api.avax.network/ext/bc/C/rpc', name: 'Avalanche' },
+ celo: { id: 42220, rpc: 'https://forno.celo.org', name: 'Celo' },
+ linea: { id: 59144, rpc: 'https://rpc.linea.build', name: 'Linea' },
+ scroll: { id: 534352, rpc: 'https://rpc.scroll.io', name: 'Scroll' },
+};
+const CHAIN_BY_ID = Object.fromEntries(Object.values(CHAINS).map((c) => [c.id, c]));
+
+function resolveChain(input) {
+ if (!input) return CHAINS.base;
+ if (typeof input === 'string') {
+ const lower = input.toLowerCase();
+ if (CHAINS[lower]) return CHAINS[lower];
+ const id = Number(input);
+ if (!Number.isNaN(id) && CHAIN_BY_ID[id]) return CHAIN_BY_ID[id];
+ }
+ if (typeof input === 'number' && CHAIN_BY_ID[input]) return CHAIN_BY_ID[input];
+ throw new Error(`unsupported chain "${input}" — known: ${Object.keys(CHAINS).join(', ')}`);
+}
+
+function rpcUrlFor(chain) {
+ const envKey = `MCP_AGENT_REP_RPC_${chain.id}`;
+ return process.env[envKey] || chain.rpc;
+}
+
+// Parse the agent identifier. Accepts: numeric ID, EVM wallet, or CAIP-10
+// "eip155:<chainId>:<address>" (which can also override the chain selection).
+function parseAgentInput(raw, defaultChain) {
+ const value = String(raw || '').trim();
+ if (!value) throw new Error('agent identifier is required');
+ if (/^\d+$/.test(value)) {
+ return { kind: 'agentId', agentId: BigInt(value), chain: defaultChain };
+ }
+ if (value.startsWith('eip155:')) {
+ const parts = value.split(':');
+ if (parts.length !== 3) throw new Error(`invalid CAIP-10 ID "${value}"`);
+ const chain = resolveChain(parts[1]);
+ const addr = parts[2];
+ if (!isAddress(addr)) throw new Error(`invalid wallet in CAIP-10 ID "${value}"`);
+ return { kind: 'wallet', wallet: addr, chain };
+ }
+ if (isAddress(value)) {
+ return { kind: 'wallet', wallet: value, chain: defaultChain };
+ }
+ throw new Error(`could not parse agent identifier "${value}" — expected uint, EVM wallet, or eip155:<chain>:<addr>`);
+}
+
+async function resolveAgentId(provider, wallet) {
+ const id = new Contract(IDENTITY_REGISTRY_MAINNET, IDENTITY_REGISTRY_ABI, provider);
+ const bal = await id.balanceOf(wallet);
+ if (bal === 0n) return null;
+ const tokenId = await id.tokenOfOwnerByIndex(wallet, 0n);
+ return BigInt(tokenId);
+}
+
+async function readIdentity(provider, agentId) {
+ const id = new Contract(IDENTITY_REGISTRY_MAINNET, IDENTITY_REGISTRY_ABI, provider);
+ const [owner, agentWallet, uri] = await Promise.allSettled([
+ id.ownerOf(agentId),
+ id.getAgentWallet(agentId),
+ id.tokenURI(agentId),
+ ]);
+ return {
+ owner: owner.status === 'fulfilled' ? owner.value : null,
+ agentWallet: agentWallet.status === 'fulfilled' ? agentWallet.value : null,
+ uri: uri.status === 'fulfilled' ? uri.value : null,
+ errors: [owner, agentWallet, uri]
+ .filter((r) => r.status === 'rejected')
+ .map((r) => r.reason?.message || String(r.reason)),
+ };
+}
+
+async function readReputationAggregate(provider, agentId) {
+ const rep = new Contract(REPUTATION_REGISTRY_MAINNET, REPUTATION_REGISTRY_ABI, provider);
+ const [agg, totalStake] = await Promise.all([rep.getReputation(agentId), rep.getTotalStake(agentId)]);
+ const [totalScore, count] = agg;
+ const totalScoreNum = Number(totalScore);
+ const countNum = Number(count);
+ return {
+ totalScore: totalScore.toString(),
+ count: count.toString(),
+ average: countNum > 0 ? totalScoreNum / countNum : null,
+ totalStakeWei: totalStake.toString(),
+ };
+}
+
+// Walk the last LOG_WINDOW_BLOCKS blocks (configurable) for recent vouches.
+// On chains where the registry has been quiet, this can return an empty
+// array — that's the truth, not a failure.
+const LOG_WINDOW_BLOCKS = Number(process.env.MCP_AGENT_REP_LOG_WINDOW || 200_000);
+
+async function readRecentEvents(provider, agentId) {
+ const rep = new Contract(REPUTATION_REGISTRY_MAINNET, REPUTATION_REGISTRY_ABI, provider);
+ const latest = await provider.getBlockNumber();
+ const from = Math.max(0, latest - LOG_WINDOW_BLOCKS);
+ const [submitted, staked] = await Promise.all([
+ rep.queryFilter(rep.filters.ReputationSubmitted(agentId), from, latest),
+ rep.queryFilter(rep.filters.ReputationStaked(agentId), from, latest),
+ ]);
+ const submittedDecoded = submitted.map((e) => ({
+ kind: 'submitted',
+ blockNumber: e.blockNumber,
+ txHash: e.transactionHash,
+ submitter: e.args?.submitter,
+ score: Number(e.args?.score),
+ comment: e.args?.comment || '',
+ }));
+ const stakedDecoded = staked.map((e) => ({
+ kind: 'staked',
+ blockNumber: e.blockNumber,
+ txHash: e.transactionHash,
+ staker: e.args?.staker,
+ score: Number(e.args?.score),
+ valueWei: e.args?.value?.toString?.() || '0',
+ }));
+ return {
+ windowBlocks: LOG_WINDOW_BLOCKS,
+ fromBlock: from,
+ toBlock: latest,
+ events: [...submittedDecoded, ...stakedDecoded].sort((a, b) => b.blockNumber - a.blockNumber).slice(0, 25),
+ };
+}
+
+const inputJsonSchema = {
+ type: 'object',
+ properties: {
+ address: {
+ type: 'string',
+ description:
+ 'ERC-8004 agentId (uint), EVM wallet address (0x...), or CAIP-10 "eip155:<chainId>:<wallet>".',
+ },
+ chain: {
+ type: 'string',
+ description: 'Chain to query (default: base). Accepts name or numeric chainId. Overridden by CAIP-10 input.',
+ },
+ },
+ required: ['address'],
+ additionalProperties: false,
+};
+
+const inputZodShape = {
+ address: z.string().min(1),
+ chain: z.string().optional(),
+};
+
+export async function buildAgentReputationTool() {
+ const handler = await paid(
+ {
+ toolName: TOOL_NAME,
+ description: TOOL_DESCRIPTION,
+ scheme: 'exact',
+ priceUsd: '$0.01',
+ inputSchema: inputJsonSchema,
+ example: { address: '1', chain: 'base' },
+ outputExample: {
+ chain: 'base',
+ agentId: '1',
+ identity: { owner: '0x...', agentWallet: '0x...', uri: 'ipfs://...' },
+ reputation: { totalScore: '42', count: '6', average: 7, totalStakeWei: '0' },
+ events: [{ kind: 'submitted', score: 5, submitter: '0x...', comment: '' }],
+ },
+ },
+ async ({ address, chain }) => {
+ const defaultChain = resolveChain(chain);
+ const parsed = parseAgentInput(address, defaultChain);
+ const provider = new JsonRpcProvider(rpcUrlFor(parsed.chain), parsed.chain.id, {
+ staticNetwork: true,
+ });
+
+ let agentId = parsed.kind === 'agentId' ? parsed.agentId : null;
+ let walletResolved = parsed.kind === 'wallet' ? parsed.wallet : null;
+ if (!agentId) {
+ agentId = await resolveAgentId(provider, walletResolved);
+ if (!agentId) {
+ return {
+ chain: parsed.chain.name,
+ chainId: parsed.chain.id,
+ input: address,
+ resolvedWallet: walletResolved,
+ error: 'no_agent_registered_for_wallet',
+ identityRegistry: IDENTITY_REGISTRY_MAINNET,
+ reputationRegistry: REPUTATION_REGISTRY_MAINNET,
+ };
+ }
+ }
+
+ const [identity, reputation, events] = await Promise.all([
+ readIdentity(provider, agentId),
+ readReputationAggregate(provider, agentId),
+ readRecentEvents(provider, agentId),
+ ]);
+
+ const isZero = identity.owner === ZeroAddress;
+ return {
+ chain: parsed.chain.name,
+ chainId: parsed.chain.id,
+ agentId: agentId.toString(),
+ agentRegistry: `eip155:${parsed.chain.id}:${IDENTITY_REGISTRY_MAINNET}`,
+ reputationRegistry: REPUTATION_REGISTRY_MAINNET,
+ identity: isZero ? null : identity,
+ reputation,
+ events,
+ rpc: rpcUrlFor(parsed.chain),
+ fetchedAt: new Date().toISOString(),
+ };
+ },
+ );
+ return {
+ name: TOOL_NAME,
+ title: 'Agent reputation ($0.01)',
+ description: TOOL_DESCRIPTION,
+ inputSchema: inputZodShape,
+ handler,
+ };
+}
diff --git a/mcp-server/src/tools/pose-seed.js b/mcp-server/src/tools/pose-seed.js
new file mode 100644
index 000000000..14469458d
--- /dev/null
+++ b/mcp-server/src/tools/pose-seed.js
@@ -0,0 +1,164 @@
+// `get_pose_seed` — paid MCP tool that maps a natural-language pose prompt to
+// a deterministic seed + a complete joint-rotation map for the three.ws
+// pose-studio mannequin.
+//
+// Pricing: $0.001 USDC, settled `exact` on Base or Solana.
+//
+// Output (real, not synthetic): the picked preset's full Euler rotation set
+// from src/pose-presets.js (the same data the public /pose page renders),
+// plus a stable seed derived from sha256(prompt|presetId), and a previewUrl
+// pointing at /pose with the seed param so the user can open the result.
+//
+// Selection algorithm: score every PRESET by token overlap against the
+// prompt, fall back to label/group substring containment, then to a
+// deterministic-by-seed pick across all presets. Always returns a real
+// preset — there is no synthetic-pose codepath.
+
+import { createHash } from 'node:crypto';
+import { z } from 'zod';
+
+import { paid } from '../payments.js';
+import { PRESETS, PRESET_GROUPS } from '../../../src/pose-presets.js';
+
+const TOOL_NAME = 'get_pose_seed';
+const TOOL_DESCRIPTION =
+ 'Deterministic pose-studio seed + complete joint rotations for the three.ws mannequin, picked from the in-repo preset library by matching natural-language prompt tokens against preset labels, IDs, and groups. Returns the preset id, the full Euler-rotation pose map (radians), a sha256-derived seed, and a previewUrl on three.ws/pose. Paid: $0.001 USDC.';
+
+const PREVIEW_BASE = process.env.MCP_POSE_PREVIEW_BASE || 'https://three.ws/pose';
+
+function tokensOf(s) {
+ return String(s || '')
+ .toLowerCase()
+ .split(/[^a-z0-9]+/g)
+ .filter(Boolean);
+}
+
+// Build a stable token set per preset once. ID, label words, and group all
+// contribute to the scoreable vocabulary so prompts like "running" hit `run`,
+// "wave" hits `wave`, "warrior pose" hits the `warrior` action preset, etc.
+const PRESET_INDEX = PRESETS.map((p) => {
+ const idTokens = tokensOf(p.id);
+ const labelTokens = tokensOf(p.label);
+ const groupTokens = tokensOf(p.group);
+ return {
+ preset: p,
+ all: new Set([...idTokens, ...labelTokens, ...groupTokens]),
+ idTokens,
+ labelTokens,
+ };
+});
+
+function scorePreset(promptTokens, entry) {
+ let score = 0;
+ for (const t of promptTokens) {
+ if (entry.all.has(t)) score += 3;
+ else {
+ // substring containment in id or label gives partial credit so
+ // "wav" hits "wave", "punch" hits "punch (right)".
+ for (const tok of [...entry.idTokens, ...entry.labelTokens]) {
+ if (tok.includes(t) || t.includes(tok)) {
+ score += 1;
+ break;
+ }
+ }
+ }
+ }
+ return score;
+}
+
+function pickPreset(prompt) {
+ const tokens = tokensOf(prompt);
+ if (tokens.length === 0) {
+ // Empty prompt is still legal — we deterministically pick a preset
+ // keyed off the prompt string (which may be whitespace) so the same
+ // caller gets the same result.
+ const hash = createHash('sha256').update(prompt).digest();
+ const idx = hash.readUInt32BE(0) % PRESETS.length;
+ return { entry: PRESET_INDEX[idx], score: 0, reason: 'no-match-deterministic-pick' };
+ }
+ let best = null;
+ let bestScore = -1;
+ for (const entry of PRESET_INDEX) {
+ const s = scorePreset(tokens, entry);
+ if (s > bestScore) {
+ best = entry;
+ bestScore = s;
+ }
+ }
+ if (bestScore <= 0) {
+ const hash = createHash('sha256').update(prompt).digest();
+ const idx = hash.readUInt32BE(0) % PRESETS.length;
+ return { entry: PRESET_INDEX[idx], score: 0, reason: 'no-match-deterministic-pick' };
+ }
+ return { entry: best, score: bestScore, reason: 'token-match' };
+}
+
+function deriveSeed(prompt, presetId) {
+ return createHash('sha256').update(`${prompt}|${presetId}`).digest('hex').slice(0, 16);
+}
+
+const inputJsonSchema = {
+ type: 'object',
+ properties: {
+ prompt: {
+ type: 'string',
+ description:
+ 'Natural-language description of the pose, e.g. "warrior stance", "wave hello", "sitting cross-legged".',
+ },
+ },
+ required: ['prompt'],
+ additionalProperties: false,
+};
+
+const inputZodShape = {
+ prompt: z.string().min(1).max(500),
+};
+
+export async function buildPoseSeedTool() {
+ const handler = await paid(
+ {
+ toolName: TOOL_NAME,
+ description: TOOL_DESCRIPTION,
+ scheme: 'exact',
+ priceUsd: '$0.001',
+ inputSchema: inputJsonSchema,
+ example: { prompt: 'wave hello' },
+ outputExample: {
+ seed: '8c12...e0f9',
+ presetId: 'wave',
+ presetLabel: 'Wave hello',
+ group: 'Standing',
+ parameters: {
+ shoulderL: { x: 0, y: 0, z: 0.1 },
+ shoulderR: { x: 0, y: 0, z: -2.45 },
+ elbowR: { x: -1.2, y: 0, z: 0 },
+ },
+ previewUrl: 'https://three.ws/pose?seed=8c12...e0f9&preset=wave',
+ match: { score: 3, reason: 'token-match' },
+ groups: PRESET_GROUPS,
+ },
+ },
+ async ({ prompt }) => {
+ const picked = pickPreset(prompt);
+ const seed = deriveSeed(prompt, picked.entry.preset.id);
+ const previewUrl = `${PREVIEW_BASE}?seed=${encodeURIComponent(seed)}&preset=${encodeURIComponent(picked.entry.preset.id)}`;
+ return {
+ seed,
+ presetId: picked.entry.preset.id,
+ presetLabel: picked.entry.preset.label,
+ group: picked.entry.preset.group,
+ parameters: picked.entry.preset.pose,
+ previewUrl,
+ match: { score: picked.score, reason: picked.reason },
+ groups: PRESET_GROUPS,
+ };
+ },
+ );
+ return {
+ name: TOOL_NAME,
+ title: 'Pose seed ($0.001)',
+ description: TOOL_DESCRIPTION,
+ inputSchema: inputZodShape,
+ handler,
+ };
+}
diff --git a/mcp-server/src/tools/pump-snapshot.js b/mcp-server/src/tools/pump-snapshot.js
new file mode 100644
index 000000000..828110460
--- /dev/null
+++ b/mcp-server/src/tools/pump-snapshot.js
@@ -0,0 +1,245 @@
+// `pump_snapshot` — paid MCP tool returning a real-time market snapshot for a
+// Solana token (pump.fun or any SPL mint).
+//
+// Pricing: $0.005 USDC, settled `exact` on Base or Solana.
+//
+// All data is fetched live from public APIs and Solana RPC. No fallback
+// arrays, no mocked numbers. If a source is unreachable the field is null
+// in the response so callers see the gap rather than fake data.
+//
+// Sources:
+// - Jupiter Lite price API (lite-api.jup.ag/price/v3) → price, priceChange24h, liquidity
+// - Dexscreener (api.dexscreener.com/latest/dex/tokens/<mint>) → volume24h, pair url, dex
+// - pump.fun frontend-api-v3 (frontend-api-v3.pump.fun/coins/<mint>) → image, name, symbol, market_cap, creator
+// - Solana RPC getTokenLargestAccounts → top holder distribution
+// - Helius DAS getAsset (if HELIUS_API_KEY is set) → exact holder count when available
+
+import { Connection, PublicKey } from '@solana/web3.js';
+import { z } from 'zod';
+
+import { paid } from '../payments.js';
+
+const TOOL_NAME = 'pump_snapshot';
+const TOOL_DESCRIPTION =
+ 'Live snapshot for a Solana SPL or pump.fun token: USD price (Jupiter), 24h volume + DEX pair (Dexscreener), mint metadata + image (pump.fun frontend-api-v3), and on-chain top-holder distribution from Solana RPC getTokenLargestAccounts. Optional Helius DAS holder count when HELIUS_API_KEY is configured. Paid: $0.005 USDC.';
+
+const SOLANA_RPC_URL = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+const HELIUS_API_KEY = process.env.HELIUS_API_KEY || '';
+
+function isValidSolanaPubkey(s) {
+ try {
+ new PublicKey(s);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+async function fetchJson(url, init = {}, timeoutMs = 8000) {
+ const controller = new AbortController();
+ const t = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const res = await fetch(url, { ...init, signal: controller.signal });
+ if (!res.ok) throw new Error(`${url} → HTTP ${res.status}`);
+ return await res.json();
+ } finally {
+ clearTimeout(t);
+ }
+}
+
+async function getJupiterPrice(mint) {
+ try {
+ const data = await fetchJson(`https://lite-api.jup.ag/price/v3?ids=${mint}`);
+ const entry = data?.[mint];
+ if (!entry) return null;
+ return {
+ usdPrice: entry.usdPrice ?? null,
+ priceChange24hPct: entry.priceChange24h ?? null,
+ liquidityUsd: entry.liquidity ?? null,
+ decimals: entry.decimals ?? null,
+ blockId: entry.blockId ?? null,
+ };
+ } catch (err) {
+ return { error: err.message };
+ }
+}
+
+async function getDexscreener(mint) {
+ try {
+ const data = await fetchJson(`https://api.dexscreener.com/latest/dex/tokens/${mint}`);
+ const pairs = Array.isArray(data?.pairs) ? data.pairs : [];
+ if (pairs.length === 0) return null;
+ // Pick the pair with the largest 24h volume so a token with multiple
+ // DEX pools surfaces its primary venue.
+ const pair = pairs.reduce((best, p) => {
+ const v = Number(p?.volume?.h24 || 0);
+ return v > (best?.vol || 0) ? { pair: p, vol: v } : best;
+ }, null)?.pair;
+ if (!pair) return null;
+ return {
+ volume24hUsd: Number(pair.volume?.h24 || 0),
+ priceUsd: pair.priceUsd ? Number(pair.priceUsd) : null,
+ priceChange24hPct: pair.priceChange?.h24 ?? null,
+ liquidityUsd: pair.liquidity?.usd ?? null,
+ fdvUsd: pair.fdv ?? null,
+ marketCapUsd: pair.marketCap ?? null,
+ pairAddress: pair.pairAddress,
+ dex: pair.dexId,
+ chain: pair.chainId,
+ url: pair.url,
+ txns24h: pair.txns?.h24 ?? null,
+ };
+ } catch (err) {
+ return { error: err.message };
+ }
+}
+
+async function getPumpFunMeta(mint) {
+ try {
+ const data = await fetchJson(`https://frontend-api-v3.pump.fun/coins/${mint}`);
+ if (!data || data.error) return null;
+ return {
+ name: data.name || null,
+ symbol: data.symbol || null,
+ description: data.description || null,
+ imageUrl: data.image_uri || null,
+ twitter: data.twitter || null,
+ telegram: data.telegram || null,
+ website: data.website || null,
+ creator: data.creator || null,
+ createdAtMs: data.created_timestamp || null,
+ complete: !!data.complete,
+ marketCapUsd: data.usd_market_cap ?? null,
+ marketCapQuote: data.market_cap ?? null,
+ totalSupply: data.total_supply_str || data.total_supply || null,
+ poolAddress: data.pool_address || null,
+ lastTradeTimestampMs: data.last_trade_timestamp || null,
+ athMarketCapUsd: data.ath_market_cap ?? null,
+ athMarketCapTimestampMs: data.ath_market_cap_timestamp || null,
+ program: data.program || null,
+ };
+ } catch (err) {
+ return { error: err.message };
+ }
+}
+
+async function getTopHolders(mint) {
+ try {
+ const conn = new Connection(SOLANA_RPC_URL, 'confirmed');
+ const res = await conn.getTokenLargestAccounts(new PublicKey(mint));
+ const top = (res?.value || []).map((acct) => ({
+ address: acct.address.toBase58(),
+ uiAmount: acct.uiAmount,
+ amount: acct.amount,
+ decimals: acct.decimals,
+ }));
+ return {
+ topHolderCount: top.length,
+ topHolders: top,
+ };
+ } catch (err) {
+ return { error: err.message };
+ }
+}
+
+async function getHeliusHolderCount(mint) {
+ if (!HELIUS_API_KEY) return null;
+ try {
+ const url = `https://mainnet.helius-rpc.com/?api-key=${HELIUS_API_KEY}`;
+ const body = {
+ jsonrpc: '2.0',
+ id: 'getAsset',
+ method: 'getAsset',
+ params: { id: mint, options: { showFungible: true } },
+ };
+ const data = await fetchJson(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ const supply = data?.result?.token_info?.supply ?? null;
+ const decimals = data?.result?.token_info?.decimals ?? null;
+ const priceInfo = data?.result?.token_info?.price_info ?? null;
+ return {
+ supply: supply !== null ? String(supply) : null,
+ decimals,
+ heliusPriceUsd: priceInfo?.price_per_token ?? null,
+ };
+ } catch (err) {
+ return { error: err.message };
+ }
+}
+
+const inputJsonSchema = {
+ type: 'object',
+ properties: {
+ token: {
+ type: 'string',
+ description: 'Solana SPL or pump.fun mint pubkey (base58).',
+ minLength: 32,
+ maxLength: 64,
+ },
+ },
+ required: ['token'],
+ additionalProperties: false,
+};
+
+const inputZodShape = {
+ token: z.string().refine((v) => isValidSolanaPubkey(v), 'must be a base58 Solana pubkey'),
+};
+
+export async function buildPumpSnapshotTool() {
+ const handler = await paid(
+ {
+ toolName: TOOL_NAME,
+ description: TOOL_DESCRIPTION,
+ scheme: 'exact',
+ priceUsd: '$0.005',
+ inputSchema: inputJsonSchema,
+ example: { token: 'HZ1JovNiVvGrGNiiYvEozEVgZ58xaU3RKwX8eACQBCt3' },
+ outputExample: {
+ token: 'HZ1JovNiVvGrGNiiYvEozEVgZ58xaU3RKwX8eACQBCt3',
+ price: { usdPrice: 0.0415, priceChange24hPct: 2.5, liquidityUsd: 107732 },
+ volume24h: { volume24hUsd: 270780.6, dex: 'raydium' },
+ holders: { topHolderCount: 20, topHolders: [{ address: '...', uiAmount: 1234 }] },
+ meta: { name: 'Pyth Network', symbol: 'PYTH', imageUrl: 'https://...' },
+ },
+ },
+ async ({ token }) => {
+ if (!isValidSolanaPubkey(token)) {
+ return { error: 'invalid_mint', token };
+ }
+ const [price, ds, meta, holders, helius] = await Promise.all([
+ getJupiterPrice(token),
+ getDexscreener(token),
+ getPumpFunMeta(token),
+ getTopHolders(token),
+ getHeliusHolderCount(token),
+ ]);
+ return {
+ token,
+ fetchedAt: new Date().toISOString(),
+ price,
+ volume24h: ds,
+ meta,
+ holders,
+ helius,
+ image: meta?.imageUrl || null,
+ sources: {
+ price: 'https://lite-api.jup.ag/price/v3',
+ volume24h: 'https://api.dexscreener.com',
+ meta: 'https://frontend-api-v3.pump.fun',
+ holders: SOLANA_RPC_URL,
+ helius: HELIUS_API_KEY ? 'https://mainnet.helius-rpc.com' : null,
+ },
+ };
+ },
+ );
+ return {
+ name: TOOL_NAME,
+ title: 'Pump.fun snapshot ($0.005)',
+ description: TOOL_DESCRIPTION,
+ inputSchema: inputZodShape,
+ handler,
+ };
+}
diff --git a/mcp-server/src/tools/vanity-grinder.js b/mcp-server/src/tools/vanity-grinder.js
new file mode 100644
index 000000000..6c23e0284
--- /dev/null
+++ b/mcp-server/src/tools/vanity-grinder.js
@@ -0,0 +1,136 @@
+// `vanity_grinder` — paid MCP tool that brute-forces a Solana keypair whose
+// base58 public key starts with a chosen prefix (and optionally ends with a
+// chosen suffix).
+//
+// Pricing: `upto` scheme on Base, max $0.50. Actual settled amount scales
+// with the number of attempts: we charge $0.01 base + ~$0.0000001 per
+// attempt, capped at $0.50. The x402 facilitator enforces settle ≤ max.
+//
+// Output (over the same MCP channel — clients should treat as secret):
+// - address (base58)
+// - privateKey64 (base58, full 64-byte secret key as @solana/web3.js expects)
+// - iterations + durationMs
+// - cost: { authorizedMaxUsd, settledUsd, settledAtomic }
+//
+// The grinder is the same async-yielding routine in api/_lib/pump-vanity.js
+// (BASE58_ALPHABET, 6-char max pattern, lowercase ignoreCase support). It
+// runs in-process — there is no external service.
+
+import { z } from 'zod';
+
+import { paidUpto } from '../payments.js';
+import { grindMintKeypair, estimateAttempts, BASE58_ALPHABET } from '../../../api/_lib/pump-vanity.js';
+import bs58 from 'bs58';
+
+const TOOL_NAME = 'vanity_grinder';
+const TOOL_DESCRIPTION =
+ 'Generate a Solana keypair whose base58 address starts with a chosen prefix (and optionally ends with a chosen suffix). Returns the full 64-byte secret key — handle as a secret. Billed via x402 `upto` (max $0.50 USDC on Base); actual cost scales with attempts so easy patterns are nearly free.';
+
+const BASE_USD = 0.01;
+const PER_ATTEMPT_USD = 1e-7;
+const MAX_USD = 0.5;
+
+function priceForAttempts(attempts) {
+ const usd = Math.min(MAX_USD, BASE_USD + attempts * PER_ATTEMPT_USD);
+ const atomic = Math.round(usd * 1_000_000); // USDC has 6 decimals
+ return { usd: Number(usd.toFixed(6)), atomicUsdc: String(atomic) };
+}
+
+const inputJsonSchema = {
+ type: 'object',
+ properties: {
+ prefix: {
+ type: 'string',
+ description: `Base58 prefix the address must start with. Allowed chars: ${BASE58_ALPHABET}. Max 6 chars.`,
+ minLength: 0,
+ maxLength: 6,
+ },
+ suffix: {
+ type: 'string',
+ description: 'Optional base58 suffix the address must end with. Max 6 chars.',
+ minLength: 0,
+ maxLength: 6,
+ },
+ ignoreCase: {
+ type: 'boolean',
+ description: 'Case-insensitive match (folds upper+lower base58 chars).',
+ },
+ maxIterations: {
+ type: 'integer',
+ description: 'Hard cap on grinder iterations. Default 2_000_000.',
+ minimum: 1,
+ maximum: 5_000_000,
+ },
+ },
+ required: ['prefix'],
+ additionalProperties: false,
+};
+
+const inputZodShape = {
+ prefix: z.string().min(1).max(6),
+ suffix: z.string().max(6).optional(),
+ ignoreCase: z.boolean().optional(),
+ maxIterations: z.number().int().min(1).max(5_000_000).optional(),
+};
+
+export async function buildVanityGrinderTool() {
+ const handler = await paidUpto(
+ {
+ toolName: TOOL_NAME,
+ description: TOOL_DESCRIPTION,
+ priceUsd: '$0.50',
+ inputSchema: inputJsonSchema,
+ example: { prefix: 'pump' },
+ outputExample: {
+ address: 'pumpXYZ...',
+ privateKey64: '5x...base58...',
+ iterations: 12345,
+ durationMs: 230,
+ cost: { authorizedMaxUsd: 0.5, settledUsd: 0.011, settledAtomic: '11234' },
+ },
+ },
+ async ({ prefix, suffix, ignoreCase = false, maxIterations = 2_000_000 }) => {
+ const expected = estimateAttempts({ prefix, suffix, ignoreCase });
+ const grind = await grindMintKeypair({
+ prefix,
+ suffix,
+ ignoreCase,
+ maxIterations,
+ });
+ const address = grind.keypair.publicKey.toBase58();
+ // @solana/web3.js Keypair.secretKey is the full 64-byte ed25519 secret
+ // (32-byte seed || 32-byte pubkey). Wallets like Phantom import this
+ // directly as base58. The client is responsible for storing it.
+ const privateKey64 = bs58.encode(Buffer.from(grind.keypair.secretKey));
+ const price = priceForAttempts(grind.iterations);
+ return {
+ result: {
+ address,
+ privateKey64,
+ iterations: grind.iterations,
+ estimatedIterations: Math.round(expected),
+ durationMs: grind.durationMs,
+ prefix,
+ suffix: suffix || null,
+ ignoreCase,
+ cost: {
+ authorizedMaxUsd: MAX_USD,
+ settledUsd: price.usd,
+ settledAtomic: price.atomicUsdc,
+ pricingNote: '$0.01 base + $0.0000001 per attempt, capped at $0.50',
+ },
+ _secretWarning:
+ 'privateKey64 is a real private key. Treat the entire MCP response as a secret and store securely.',
+ },
+ settleAmount: price.atomicUsdc,
+ };
+ },
+ );
+ return {
+ name: TOOL_NAME,
+ title: 'Solana vanity grinder (upto $0.50)',
+ description: TOOL_DESCRIPTION,
+ inputSchema: inputZodShape,
+ handler,
+ };
+}
diff --git a/package-lock.json b/package-lock.json
index 512081351..f849d0822 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -13,6 +13,8 @@
"agent-payments-sdk",
"avatar-sdk",
"character-studio",
+ "mcp-bridge",
+ "mcp-server",
"multiplayer"
],
"dependencies": {
@@ -962,6 +964,50 @@
"vite-plugin-compression": "^0.5.1"
}
},
+ "mcp-bridge": {
+ "name": "@3d-agent/mcp-bridge",
+ "version": "1.0.0",
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.29.0",
+ "@solana/kit": "^6.8.0",
+ "@x402/axios": "^2.12.0",
+ "@x402/core": "^2.12.0",
+ "@x402/evm": "^2.12.0",
+ "@x402/svm": "^2.12.0",
+ "axios": "^1.7.0",
+ "bs58": "^6.0.0",
+ "viem": "^2.18.0",
+ "zod": "^3.23.8"
+ },
+ "bin": {
+ "x402-mcp-bridge": "src/index.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "mcp-server": {
+ "name": "@3d-agent/mcp-server",
+ "version": "1.0.0",
+ "dependencies": {
+ "@coinbase/x402": "^2.1.0",
+ "@modelcontextprotocol/sdk": "^1.29.0",
+ "@solana/web3.js": "latest",
+ "@x402/core": "^2.12.0",
+ "@x402/evm": "^2.12.0",
+ "@x402/extensions": "^2.12.0",
+ "@x402/mcp": "^2.12.0",
+ "@x402/svm": "^2.12.0",
+ "ethers": "^6.16.0",
+ "zod": "^3.23.8"
+ },
+ "bin": {
+ "3d-agent-mcp": "src/index.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"multiplayer": {
"name": "@three.ws/multiplayer",
"version": "0.1.0",
@@ -1013,6 +1059,14 @@
}
}
},
+ "node_modules/@3d-agent/mcp-bridge": {
+ "resolved": "mcp-bridge",
+ "link": true
+ },
+ "node_modules/@3d-agent/mcp-server": {
+ "resolved": "mcp-server",
+ "link": true
+ },
"node_modules/@achingbrain/http-parser-js": {
"version": "0.5.9",
"resolved": "https://registry.npmjs.org/@achingbrain/http-parser-js/-/http-parser-js-0.5.9.tgz",
@@ -26643,6 +26697,17 @@
"@x402/core": "~2.12.0"
}
},
+ "node_modules/@x402/mcp": {
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@x402/mcp/-/mcp-2.12.0.tgz",
+ "integrity": "sha512-R4Z2u1tz7tO8UV0rpukhpUp6LWSxFNPgM2GFjUPqYiU/vBqVTbjfiKDkE05ixvoCPUQNIa1ZEEa0owEkPhAzJA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.12.1",
+ "@x402/core": "~2.12.0",
+ "zod": "^3.24.2"
+ }
+ },
"node_modules/@x402/svm": {
"version": "2.12.0",
"resolved": "https://registry.npmjs.org/@x402/svm/-/svm-2.12.0.tgz",
diff --git a/package.json b/package.json
index 8c5bd7232..100616af9 100644
--- a/package.json
+++ b/package.json
@@ -26,6 +26,7 @@
"agent-payments-sdk",
"avatar-sdk",
"character-studio",
+ "mcp-bridge",
"mcp-server",
"multiplayer"
],
@@ -146,6 +147,7 @@
"@x402/evm": "^2.12.0",
"@x402/express": "^2.12.0",
"@x402/extensions": "^2.12.0",
+ "@x402/mcp": "^2.12.0",
"@x402/svm": "^2.12.0",
"@zauthx402/sdk": "^0.1.14",
"agent0-sdk": "^1.7.1",
diff --git a/public/.well-known/agent-card.json b/public/.well-known/agent-card.json
index 2492d7278..04a9de375 100644
--- a/public/.well-known/agent-card.json
+++ b/public/.well-known/agent-card.json
@@ -10,7 +10,14 @@
"capabilities": {
"streaming": false,
"pushNotifications": false,
- "stateTransitionHistory": false
+ "stateTransitionHistory": false,
+ "extensions": [
+ {
+ "uri": "https://github.com/google-a2a/a2a-x402/v0.1",
+ "description": "Supports payments using the x402 protocol for on-chain settlement.",
+ "required": true
+ }
+ ]
},
"authentication": {
"schemes": ["bearer"],
@@ -86,6 +93,19 @@
"Optimize this GLB for web delivery",
"Suggest compression for https://example.com/avatar.glb"
]
+ },
+ {
+ "id": "inspect-glb-a2a",
+ "name": "Inspect glTF/GLB (A2A)",
+ "description": "Pay-per-call glTF/GLB inspector exposed over the Agent-to-Agent (A2A) protocol with x402 settlement. Send a JSON-RPC message/send to the URL below — the first call returns payment requirements, the retry with a signed PaymentPayload settles on-chain and returns the inspection report as a task artifact.",
+ "tags": ["model", "gltf", "glb", "inspect", "a2a", "x402", "paid"],
+ "examples": [
+ "Inspect https://example.com/model.glb (A2A x402)",
+ "Vet this GLB before I mint it"
+ ],
+ "inputModes": ["application/json", "text/plain"],
+ "outputModes": ["application/json"],
+ "url": "https://three.ws/api/agents/a2a-paid"
}
]
}
diff --git a/public/x402.js b/public/x402.js
index ebd511983..51f42bf45 100644
--- a/public/x402.js
+++ b/public/x402.js
@@ -114,6 +114,102 @@ function b64decode(str) {
}
}
+// ──────────────────────────────────────────── Spending caps (USE-22) ────────
+// Persists per-wallet spend in localStorage so reload-survivable caps work
+// in a pure-browser context. Keys are bucketed by UTC hour and UTC day so
+// the sliding windows reset cleanly at midnight UTC for the daily case.
+// All amounts are stored as base-10 BigInt strings of micro-USD; stablecoin
+// payments (USDC, USDT, DAI) flow through as-is since their atomics are
+// already 6-decimal USD-pegged.
+
+const SPEND_LS_PREFIX = 'x402.spend.';
+const STABLE_NAMES = new Set([
+ 'usdc', 'usd coin', 'usdt', 'tether', 'binance-peg usd coin', 'dai',
+]);
+
+function spendBuckets(timestamp = Date.now()) {
+ const hour = Math.floor(timestamp / 3_600_000);
+ const day = Math.floor(timestamp / 86_400_000);
+ return { hour, day };
+}
+
+function spendKey(address, kind, bucket) {
+ return `${SPEND_LS_PREFIX}${kind}.${address.toLowerCase()}.${bucket}`;
+}
+
+function readSpend(address, kind, bucket) {
+ try {
+ const raw = localStorage.getItem(spendKey(address, kind, bucket));
+ if (!raw) return 0n;
+ return BigInt(raw);
+ } catch {
+ return 0n;
+ }
+}
+
+function writeSpend(address, kind, bucket, value) {
+ try {
+ localStorage.setItem(spendKey(address, kind, bucket), value.toString());
+ } catch {
+ // localStorage full / disabled — caps degrade to per-call only.
+ }
+}
+
+function toMicroUsdBrowser(amount, accept) {
+ const atomic = BigInt(amount);
+ const decimals = Number(accept?.extra?.decimals ?? 6);
+ const name = String(accept?.extra?.name || '').toLowerCase();
+ if (STABLE_NAMES.has(name)) {
+ if (decimals === 6) return atomic;
+ if (decimals > 6) return atomic / 10n ** BigInt(decimals - 6);
+ return atomic * 10n ** BigInt(6 - decimals);
+ }
+ // Non-stable in the browser modal: we don't fetch live prices to keep the
+ // drop-in script dependency-free. Cap enforcement for non-stable assets
+ // must be done server-side via x402-spending-cap.js.
+ return atomic;
+}
+
+// Check the configured caps and, if admitted, reserve the spend in
+// localStorage. Returns { abort: boolean, reason?, reservation? }.
+// Reservation has { address, microUsd, buckets } so rollback can undo.
+function browserEnforceCap({ accept, caps, address }) {
+ if (!caps || !address) return { abort: false };
+ const microUsd = toMicroUsdBrowser(accept.amount, accept);
+ const maxPerCall = caps.maxPerCall != null ? BigInt(caps.maxPerCall) : null;
+ const maxPerHour = caps.maxPerHour != null ? BigInt(caps.maxPerHour) : null;
+ const maxPerDay = caps.maxPerDay != null ? BigInt(caps.maxPerDay) : null;
+ if (maxPerCall != null && microUsd > maxPerCall) {
+ return {
+ abort: true,
+ reason: `Per-call cap exceeded (${microUsd} > ${maxPerCall} µUSD)`,
+ };
+ }
+ const buckets = spendBuckets();
+ const hourTotal = readSpend(address, 'hr', buckets.hour) + microUsd;
+ const dayTotal = readSpend(address, 'day', buckets.day) + microUsd;
+ if (maxPerHour != null && hourTotal > maxPerHour) {
+ return { abort: true, reason: `Hourly cap exceeded (${hourTotal} > ${maxPerHour} µUSD)` };
+ }
+ if (maxPerDay != null && dayTotal > maxPerDay) {
+ return { abort: true, reason: `Daily cap exceeded (${dayTotal} > ${maxPerDay} µUSD)` };
+ }
+ writeSpend(address, 'hr', buckets.hour, hourTotal);
+ writeSpend(address, 'day', buckets.day, dayTotal);
+ return { abort: false, reservation: { address, microUsd, buckets } };
+}
+
+function browserRollbackReservation(reservation) {
+ if (!reservation) return;
+ const { address, microUsd, buckets } = reservation;
+ const hourCurrent = readSpend(address, 'hr', buckets.hour);
+ const dayCurrent = readSpend(address, 'day', buckets.day);
+ const hourNext = hourCurrent - microUsd;
+ const dayNext = dayCurrent - microUsd;
+ writeSpend(address, 'hr', buckets.hour, hourNext < 0n ? 0n : hourNext);
+ writeSpend(address, 'day', buckets.day, dayNext < 0n ? 0n : dayNext);
+}
+
// ──────────────────────────────────────────── ERC-8021 builder-code echo ────
// The server-side x402-spec.js enforces that any client-echoed builder-code
// `a` matches what the 402 challenge declared (anti-tamper). Builders/wallets
@@ -823,6 +919,16 @@ class CheckoutModal {
const payerAddress = (conn?.publicKey || provider.publicKey)?.toString();
if (!payerAddress) throw new Error('Phantom did not return a public key');
this.payerAddress = payerAddress;
+ const capCheck = browserEnforceCap({
+ accept,
+ caps: this.opts.caps,
+ address: payerAddress,
+ });
+ if (capCheck.abort) {
+ this.renderError('authorize', capCheck.reason);
+ return;
+ }
+ this.spendReservation = capCheck.reservation || null;
this.renderProgress('authorize', { text: `Building Solana payment for ${payerAddress.slice(0, 6)}…${payerAddress.slice(-4)}` });
const prep = await postJson(`${ORIGIN}/api/x402-checkout?action=prepare`, {
@@ -849,6 +955,10 @@ class CheckoutModal {
await this.executePaid(enc.x_payment);
} catch (err) {
+ if (this.spendReservation) {
+ browserRollbackReservation(this.spendReservation);
+ this.spendReservation = null;
+ }
this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
}
}
@@ -864,6 +974,16 @@ class CheckoutModal {
const payerAddress = accounts?.[0];
if (!payerAddress) throw new Error('Wallet did not return an account');
this.payerAddress = payerAddress;
+ const capCheck = browserEnforceCap({
+ accept,
+ caps: this.opts.caps,
+ address: payerAddress,
+ });
+ if (capCheck.abort) {
+ this.renderError('authorize', capCheck.reason);
+ return;
+ }
+ this.spendReservation = capCheck.reservation || null;
const meta = EVM_NETWORKS[accept.network];
if (!meta) throw new Error(`Unknown EVM network ${accept.network}`);
@@ -945,6 +1065,10 @@ class CheckoutModal {
const xPayment = b64encode(paymentPayload);
await this.executePaid(xPayment);
} catch (err) {
+ if (this.spendReservation) {
+ browserRollbackReservation(this.spendReservation);
+ this.spendReservation = null;
+ }
this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
}
}
@@ -979,9 +1103,14 @@ class CheckoutModal {
}
const settleHeader = res.headers.get('x-payment-response');
const payment = b64decode(settleHeader) || {};
+ this.spendReservation = null;
this.renderDone({ result, payment });
this.resolve?.({ ok: true, result, payment, response: { status: res.status, headers: headersToObject(res.headers) } });
} catch (err) {
+ if (this.spendReservation) {
+ browserRollbackReservation(this.spendReservation);
+ this.spendReservation = null;
+ }
this.renderError('verify', friendlyError(err));
}
}
diff --git a/scripts/siwx-verify-agent.mjs b/scripts/siwx-verify-agent.mjs
new file mode 100644
index 000000000..fd45af8b7
--- /dev/null
+++ b/scripts/siwx-verify-agent.mjs
@@ -0,0 +1,141 @@
+#!/usr/bin/env node
+// scripts/siwx-verify-agent.mjs
+//
+// End-to-end SIWX verification for the agent path. Drives a real /api/x402/*
+// endpoint through the same flow @x402/fetch + @x402/extensions/sign-in-with-x
+// give every shopping bot: pay once with X-PAYMENT, then re-enter for free
+// with SIGN-IN-WITH-X.
+//
+// Required env:
+// EVM_PRIVATE_KEY — 0x-prefixed funded wallet on Base mainnet (with USDC)
+// X402_RESOURCE — full URL of a SIWX-enabled paid endpoint
+//
+// Optional env:
+// SIWX_VERIFY_MODE — 'full' (default) | 'siwx-only' | 'pay-only'
+// Scenario D (negative path) uses 'siwx-only' with a
+// fresh / unfunded wallet so we exercise the
+// 402 siwx_not_paid branch directly.
+//
+// Output:
+// ~/.claude/siwx-verify/agent-result.json — JSON artifact with timestamps,
+// recovered addresses, response status codes, and the on-chain transaction
+// hash (from X-PAYMENT-RESPONSE) when the pay leg ran.
+
+import { mkdir, writeFile } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+
+import { privateKeyToAccount } from 'viem/accounts';
+import { wrapFetchWithPayment } from '@x402/fetch';
+import { wrapFetchWithSIWx } from '@x402/extensions/sign-in-with-x';
+
+const MODE = process.env.SIWX_VERIFY_MODE || 'full';
+const PK = process.env.EVM_PRIVATE_KEY;
+const URL = process.env.X402_RESOURCE;
+
+if (!PK) {
+ console.error('EVM_PRIVATE_KEY required (0x-prefixed)');
+ process.exit(2);
+}
+if (!URL) {
+ console.error('X402_RESOURCE required (full URL of SIWX-enabled endpoint)');
+ process.exit(2);
+}
+
+const signer = privateKeyToAccount(PK);
+const result = {
+ ranAt: new Date().toISOString(),
+ mode: MODE,
+ url: URL,
+ address: signer.address,
+ pay: null,
+ siwx: null,
+ pass: false,
+};
+
+function decodePaymentResponseHeader(value) {
+ if (!value) return null;
+ try {
+ return JSON.parse(Buffer.from(value, 'base64').toString('utf8'));
+ } catch {
+ return null;
+ }
+}
+
+async function readBody(res) {
+ const text = await res.text();
+ if (!text) return null;
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+}
+
+// ── Leg 1 — pay with X-PAYMENT ─────────────────────────────────────────────
+if (MODE === 'full' || MODE === 'pay-only') {
+ const fetchWithPayment = wrapFetchWithPayment(fetch, signer);
+ const t0 = Date.now();
+ const r1 = await fetchWithPayment(URL);
+ const elapsed = Date.now() - t0;
+ const body = await readBody(r1);
+ result.pay = {
+ status: r1.status,
+ elapsedMs: elapsed,
+ paymentResponse: decodePaymentResponseHeader(r1.headers.get('x-payment-response')),
+ body,
+ };
+ if (r1.status !== 200) {
+ await persist();
+ throw new Error(`pay leg failed: HTTP ${r1.status} ${JSON.stringify(body)?.slice(0, 200)}`);
+ }
+}
+
+// ── Leg 2 — SIWX retry ─────────────────────────────────────────────────────
+if (MODE === 'full' || MODE === 'siwx-only') {
+ const fetchWithSiwx = wrapFetchWithSIWx(fetch, signer);
+ const t2 = Date.now();
+ const r2 = await fetchWithSiwx(URL);
+ const elapsed = Date.now() - t2;
+ const body = await readBody(r2);
+ result.siwx = {
+ status: r2.status,
+ elapsedMs: elapsed,
+ recoveredAddress: r2.headers.get('x-siwx-address') || null,
+ body,
+ };
+ if (MODE === 'siwx-only') {
+ // Negative-path / Scenario D: we EXPECT a 402 siwx_not_paid.
+ if (r2.status === 402 && (body?.error === 'siwx_not_paid' || /siwx_not_paid/.test(JSON.stringify(body) || ''))) {
+ result.pass = true;
+ } else if (r2.status === 200) {
+ result.pass = false;
+ result.error = 'siwx-only mode unexpectedly returned 200 — this wallet already has a grant';
+ } else {
+ result.pass = false;
+ result.error = `siwx-only mode expected 402 siwx_not_paid, got ${r2.status}`;
+ }
+ } else if (r2.status !== 200) {
+ await persist();
+ throw new Error(`siwx leg failed: HTTP ${r2.status} ${JSON.stringify(body)?.slice(0, 200)}`);
+ } else {
+ result.pass = true;
+ }
+}
+
+if (MODE === 'pay-only') {
+ result.pass = result.pay?.status === 200;
+}
+
+await persist();
+console.log(`OK — wrote ${await outputPath()}`);
+
+async function outputPath() {
+ return join(homedir(), '.claude/siwx-verify/agent-result.json');
+}
+
+async function persist() {
+ const outDir = join(homedir(), '.claude/siwx-verify');
+ await mkdir(outDir, { recursive: true });
+ await writeFile(await outputPath(), JSON.stringify(result, null, 2));
+}
diff --git a/scripts/smoke-asset-download.mjs b/scripts/smoke-asset-download.mjs
new file mode 100644
index 000000000..43d6a67bd
--- /dev/null
+++ b/scripts/smoke-asset-download.mjs
@@ -0,0 +1,82 @@
+// Smoke test the asset-download endpoint without a Vercel dev server.
+// Calls the handler with a fake req/res and prints status, headers, body.
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+for (const f of ['.env.local', '.env']) {
+ try {
+ const raw = readFileSync(resolve('/workspaces/three.ws', f), 'utf8');
+ for (const line of raw.split('\n')) {
+ const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
+ if (!m || process.env[m[1]]) continue;
+ let v = m[2].trim();
+ if ((v.startsWith('"')&&v.endsWith('"'))||(v.startsWith("'")&&v.endsWith("'"))) v = v.slice(1,-1);
+ process.env[m[1]] = v;
+ }
+ break;
+ } catch {}
+}
+process.env.PUBLIC_APP_ORIGIN = process.env.PUBLIC_APP_ORIGIN || 'https://three.ws';
+
+const { default: handler } = await import('../api/x402/asset-download.js');
+
+function makeRes() {
+ const headers = {};
+ let statusCode = 200;
+ let body = '';
+ let ended = false;
+ return {
+ get statusCode() { return statusCode; },
+ set statusCode(v) { statusCode = v; },
+ get writableEnded() { return ended; },
+ setHeader(k, v) { headers[k.toLowerCase()] = v; },
+ getHeader(k) { return headers[k.toLowerCase()]; },
+ end(b) { body = b || ''; ended = true; },
+ _inspect: () => ({ statusCode, headers, body }),
+ };
+}
+
+async function probe(slug) {
+ const req = {
+ method: 'GET',
+ url: `/api/x402/asset-download?slug=${slug}`,
+ headers: {},
+ query: { slug },
+ };
+ const res = makeRes();
+ await handler(req, res);
+ const out = res._inspect();
+ console.log(`\n=== slug=${slug} (no payment header) ===`);
+ console.log('status:', out.statusCode);
+ console.log('headers:', Object.keys(out.headers));
+ try {
+ const parsed = JSON.parse(out.body);
+ console.log('body keys:', Object.keys(parsed));
+ if (parsed.error) console.log('error:', parsed.error);
+ } catch {
+ console.log('body (first 200):', out.body.slice(0, 200));
+ }
+ const pr = out.headers['payment-required'];
+ if (pr) {
+ const decoded = JSON.parse(Buffer.from(pr, 'base64').toString('utf8'));
+ console.log('PAYMENT-REQUIRED body:');
+ console.log(' resource.url:', decoded.resource?.url);
+ console.log(' accepts count:', decoded.accepts?.length);
+ console.log(' accept[0]:', JSON.stringify({
+ network: decoded.accepts?.[0]?.network,
+ amount: decoded.accepts?.[0]?.amount,
+ payTo: decoded.accepts?.[0]?.payTo,
+ }));
+ console.log(' extensions keys:', Object.keys(decoded.extensions || {}));
+ console.log(' siwx?:', !!decoded.extensions?.['sign-in-with-x']);
+ if (decoded.extensions?.['sign-in-with-x']) {
+ const ext = decoded.extensions['sign-in-with-x'];
+ console.log(' siwx.statement:', ext.statement);
+ console.log(' siwx.supportedChains:', ext.supportedChains);
+ console.log(' siwx.uri:', ext.uri);
+ }
+ }
+}
+
+await probe('pole-dancer-rumba');
+await probe('cz-avatar');
+await probe('does-not-exist');
diff --git a/tests/api/auth-hints.test.js b/tests/api/auth-hints.test.js
new file mode 100644
index 000000000..04caf79bb
--- /dev/null
+++ b/tests/api/auth-hints.test.js
@@ -0,0 +1,238 @@
+// USE-21: tests for the auth-hints extension declarator + request
+// authenticator. Uses real jose + real ed25519 verification — only mocks the
+// db and rate-limit modules to keep the tests offline.
+
+import { describe, it, expect, vi, beforeAll } from 'vitest';
+import { Wallet } from 'ethers';
+
+process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';
+process.env.JWT_SECRET ||= 'test-auth-hints-secret-at-least-32-chars-long';
+process.env.VERCEL_ENV ||= 'production';
+
+// Sql stub — auth.js touches it for API-key lookups but JWT verification
+// hits jwtVerify directly (no DB).
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => []),
+}));
+
+// SIWX storage stub — record nonces in memory so duplicate-nonce checks work.
+const siwxNonceState = new Set();
+vi.mock('../../api/_lib/siwx-storage.js', () => ({
+ siwxStorage: {
+ hasUsedNonce: vi.fn(async (n) => siwxNonceState.has(n)),
+ recordNonce: vi.fn(async (n) => {
+ siwxNonceState.add(n);
+ }),
+ hasPaid: vi.fn(async () => false),
+ recordPayment: vi.fn(async () => {}),
+ },
+ normalizeAddress: (chain, address) => {
+ if (typeof chain === 'string' && chain.startsWith('eip155'))
+ return String(address).toLowerCase();
+ return String(address);
+ },
+}));
+
+const { declareAuthHintsExtension, freeEvmAcceptForAuth, authenticateAuthHintsRequest } =
+ await import('../../api/_lib/x402/auth-hints.js');
+const { mintAccessToken } = await import('../../api/_lib/auth.js');
+const { env } = await import('../../api/_lib/env.js');
+
+// ── declareAuthHintsExtension ─────────────────────────────────────────────────
+
+describe('declareAuthHintsExtension', () => {
+ it('emits an `auth-hints` extension entry with the spec schema', () => {
+ const ext = declareAuthHintsExtension({
+ oauth2: { acceptIndexes: [3], requiredScope: 'read:agent-reputation' },
+ siwx: { acceptIndexes: [4] },
+ });
+ expect(ext['auth-hints']).toBeDefined();
+ expect(ext['auth-hints'].info.authRequirements).toHaveLength(2);
+ expect(ext['auth-hints'].schema.required).toContain('authRequirements');
+ });
+
+ it('expands the oauth2 shorthand into a full method entry', () => {
+ const ext = declareAuthHintsExtension({
+ oauth2: { acceptIndexes: [0], tokenType: 'Bearer' },
+ });
+ const [requirement] = ext['auth-hints'].info.authRequirements;
+ expect(requirement.acceptIndexes).toEqual([0]);
+ const [method] = requirement.methods;
+ expect(method.type).toBe('oauth2');
+ expect(method.tokenType).toBe('Bearer');
+ expect(method.tokenEndpoint).toMatch(/\/api\/oauth\/token$/);
+ expect(method.authorizationServer).toBe(env.APP_ORIGIN);
+ });
+
+ it('expands the siwx shorthand into a sign-in-with-x method entry', () => {
+ const ext = declareAuthHintsExtension({ siwx: { acceptIndexes: [1] } });
+ const [requirement] = ext['auth-hints'].info.authRequirements;
+ expect(requirement.acceptIndexes).toEqual([1]);
+ expect(requirement.methods[0].type).toBe('sign-in-with-x');
+ });
+
+ it('accepts a verbatim authRequirements array', () => {
+ const ext = declareAuthHintsExtension({
+ authRequirements: [
+ {
+ acceptIndexes: [2],
+ methods: [
+ {
+ type: 'oauth2',
+ tokenType: 'DPoP',
+ authorizationServer: 'https://as.example.com',
+ tokenEndpoint: 'https://as.example.com/token',
+ },
+ ],
+ },
+ ],
+ });
+ expect(ext['auth-hints'].info.authRequirements[0].methods[0].tokenType).toBe('DPoP');
+ });
+
+ it('rejects empty authRequirements', () => {
+ expect(() => declareAuthHintsExtension({})).toThrow(/non-empty/);
+ expect(() => declareAuthHintsExtension({ authRequirements: [] })).toThrow(/non-empty/);
+ });
+
+ it('rejects acceptIndexes that are not non-negative integers', () => {
+ expect(() => declareAuthHintsExtension({ oauth2: { acceptIndexes: [-1] } })).toThrow();
+ expect(() => declareAuthHintsExtension({ oauth2: { acceptIndexes: ['x'] } })).toThrow();
+ });
+});
+
+// ── freeEvmAcceptForAuth ──────────────────────────────────────────────────────
+
+describe('freeEvmAcceptForAuth', () => {
+ it('emits a zero-amount EIP-3009 accept marked with the auth type', () => {
+ const accept = freeEvmAcceptForAuth({
+ network: 'eip155:8453',
+ asset: '0xUSDC',
+ payTo: '0xWallet',
+ authType: 'oauth2',
+ });
+ expect(accept.amount).toBe('0');
+ expect(accept.scheme).toBe('exact');
+ expect(accept.network).toBe('eip155:8453');
+ expect(accept.extra.authRequired).toBe('oauth2');
+ expect(accept.extra.name).toBe('USD Coin');
+ });
+});
+
+// ── authenticateAuthHintsRequest: OAuth Bearer ────────────────────────────────
+
+describe('authenticateAuthHintsRequest — OAuth Bearer', () => {
+ let goodToken;
+ let scopedToken;
+ beforeAll(async () => {
+ goodToken = await mintAccessToken({
+ userId: 'user-42',
+ clientId: 'mcp_test',
+ scope: 'profile',
+ });
+ scopedToken = await mintAccessToken({
+ userId: 'user-99',
+ clientId: 'mcp_test',
+ scope: 'read:agent-reputation profile',
+ });
+ });
+
+ it('returns ok with an OAuth2 principal when the Bearer is valid', async () => {
+ const req = { headers: { authorization: `Bearer ${goodToken}` } };
+ const out = await authenticateAuthHintsRequest(req, {});
+ expect(out).not.toBeNull();
+ expect(out.ok).toBe(true);
+ expect(out.principal.method).toBe('oauth2');
+ expect(out.principal.userId).toBe('user-42');
+ });
+
+ it('rejects when the requiredScope is missing from the token scope', async () => {
+ const req = { headers: { authorization: `Bearer ${goodToken}` } };
+ const out = await authenticateAuthHintsRequest(req, {
+ requiredScope: 'read:agent-reputation',
+ });
+ expect(out).toEqual(expect.objectContaining({ ok: false, reason: 'insufficient_scope' }));
+ });
+
+ it('accepts when the token scope satisfies requiredScope', async () => {
+ const req = { headers: { authorization: `Bearer ${scopedToken}` } };
+ const out = await authenticateAuthHintsRequest(req, {
+ requiredScope: 'read:agent-reputation',
+ });
+ expect(out.ok).toBe(true);
+ expect(out.principal.scope).toContain('read:agent-reputation');
+ });
+
+ it('rejects an unparseable Bearer with reason=invalid_token', async () => {
+ const req = { headers: { authorization: 'Bearer not.a.valid.jwt' } };
+ const out = await authenticateAuthHintsRequest(req, {});
+ expect(out).toEqual(expect.objectContaining({ ok: false, reason: 'invalid_token' }));
+ });
+
+ it('returns null when no Authorization header is present', async () => {
+ const req = { headers: {} };
+ const out = await authenticateAuthHintsRequest(req, {});
+ expect(out).toBeNull();
+ });
+});
+
+// ── authenticateAuthHintsRequest: SIWX (EVM) ──────────────────────────────────
+//
+// The @x402/extensions sign-in-with-x parser expects a base64-encoded JSON
+// envelope built by encodeSIWxHeader. We construct a real EVM signature via
+// ethers' Wallet so the verifier (which delegates to viem.verifyMessage in
+// the smart-wallet path, or recoverAddress for EOAs) accepts it.
+
+describe('authenticateAuthHintsRequest — SIWX (EOA)', () => {
+ let header;
+ let wallet;
+ beforeAll(async () => {
+ const { createSIWxPayload, encodeSIWxHeader } = await import(
+ '@x402/extensions/sign-in-with-x'
+ );
+ wallet = Wallet.createRandom();
+ const serverExtension = {
+ type: 'caip-122',
+ version: '1',
+ schema: 'eip-4361',
+ signatureScheme: 'eip-191',
+ domain: 'app.test',
+ uri: 'https://app.test/api/x402/agent-reputation',
+ chainId: 'eip155:8453',
+ statement: 'auth-hints test',
+ nonce: 'authHintsTestNonce1234567890ab',
+ issuedAt: new Date().toISOString(),
+ expirationTime: new Date(Date.now() + 5 * 60_000).toISOString(),
+ };
+ const payload = await createSIWxPayload(serverExtension, wallet);
+ header = encodeSIWxHeader(payload);
+ });
+
+ it('authenticates a valid SIGN-IN-WITH-X header as a SIWX principal', async () => {
+ const req = { headers: { 'sign-in-with-x': header } };
+ const out = await authenticateAuthHintsRequest(req, {
+ resourceUrl: 'https://app.test/api/x402/agent-reputation',
+ });
+ expect(out).not.toBeNull();
+ expect(out.ok).toBe(true);
+ expect(out.principal.method).toBe('sign-in-with-x');
+ expect(out.principal.address).toBe(wallet.address.toLowerCase());
+ expect(out.principal.network).toBe('eip155:8453');
+ });
+
+ it('returns null when no SIWX header and no Bearer is present', async () => {
+ const req = { headers: {} };
+ const out = await authenticateAuthHintsRequest(req, {
+ resourceUrl: 'https://app.test/api/x402/agent-reputation',
+ });
+ expect(out).toBeNull();
+ });
+
+ it('rejects a malformed SIGN-IN-WITH-X header', async () => {
+ const req = { headers: { 'sign-in-with-x': 'not-base64!@#' } };
+ const out = await authenticateAuthHintsRequest(req, {
+ resourceUrl: 'https://app.test/api/x402/agent-reputation',
+ });
+ expect(out).toEqual(expect.objectContaining({ ok: false }));
+ });
+});
diff --git a/tests/api/offer-receipt.test.js b/tests/api/offer-receipt.test.js
new file mode 100644
index 000000000..0daf66c64
--- /dev/null
+++ b/tests/api/offer-receipt.test.js
@@ -0,0 +1,181 @@
+// Tests for the x402 Offer & Receipt extension (USE-17).
+//
+// Exercises the issuer + server modules without hitting the DB or the
+// facilitator. We generate a throw-away EVM private key for the signer (so
+// the dedicated-key safeguard passes), build offers + receipts, and verify
+// the resulting artifacts round-trip through @x402/extensions verifiers.
+
+import { describe, it, expect, beforeAll } from 'vitest';
+import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
+
+import {
+ OFFER_RECEIPT,
+ verifyOfferSignatureEIP712,
+ verifyReceiptSignatureEIP712,
+ verifyReceiptMatchesOffer,
+ extractOfferPayload,
+ extractReceiptPayload,
+} from '@x402/extensions';
+
+import { _resetIssuerForTests, getIssuer } from '../../api/_lib/x402/offer-receipt-issuer.js';
+import {
+ buildOffersExtension,
+ buildReceiptExtension,
+ offerReceiptEnabled,
+} from '../../api/_lib/x402/offer-receipt-server.js';
+
+const RESOURCE_URL = 'https://three.ws/api/x402/dance-tip';
+
+const PAID_TO_REQUIREMENTS = [
+ {
+ scheme: 'exact',
+ amount: '1000',
+ network: 'eip155:8453',
+ asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
+ payTo: '0x4022de2d36c334e73c7a108805cea11c0564f402',
+ maxTimeoutSeconds: 60,
+ resource: RESOURCE_URL,
+ },
+ {
+ scheme: 'exact',
+ amount: '1000',
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ payTo: 'wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV',
+ maxTimeoutSeconds: 60,
+ resource: RESOURCE_URL,
+ },
+];
+
+beforeAll(() => {
+ // Dedicated signing key — distinct from any X402_PAY_TO_* envs in
+ // .env.example. The issuer module asserts non-collision at boot.
+ process.env.OFFER_RECEIPT_SIGNING_PRIVATE_KEY = generatePrivateKey();
+ process.env.OFFER_RECEIPT_FORMAT = 'eip712';
+ _resetIssuerForTests();
+});
+
+describe('offer-receipt-issuer', () => {
+ it('builds an EIP-712 issuer with did:pkh kid bound to the signer address', async () => {
+ const built = await getIssuer();
+ expect(built).toBeTruthy();
+ expect(built.format).toBe('eip712');
+ const expected = privateKeyToAccount(
+ process.env.OFFER_RECEIPT_SIGNING_PRIVATE_KEY,
+ ).address;
+ expect(built.signerAddress).toBe(expected.toLowerCase());
+ expect(built.kid).toBe(`did:pkh:eip155:1:${expected}#key-1`);
+ });
+
+ it('returns null when no signing key is configured', async () => {
+ const savedKey = process.env.OFFER_RECEIPT_SIGNING_PRIVATE_KEY;
+ delete process.env.OFFER_RECEIPT_SIGNING_PRIVATE_KEY;
+ _resetIssuerForTests();
+ try {
+ const built = await getIssuer();
+ expect(built).toBeNull();
+ expect(await offerReceiptEnabled()).toBe(false);
+ } finally {
+ process.env.OFFER_RECEIPT_SIGNING_PRIVATE_KEY = savedKey;
+ _resetIssuerForTests();
+ }
+ });
+
+ it('rejects a signing key that collides with X402_PAY_TO_BASE', async () => {
+ const conflictKey = generatePrivateKey();
+ const conflictAddr = privateKeyToAccount(conflictKey).address;
+ const savedPayTo = process.env.X402_PAY_TO_BASE;
+ const savedSignKey = process.env.OFFER_RECEIPT_SIGNING_PRIVATE_KEY;
+ process.env.X402_PAY_TO_BASE = conflictAddr;
+ process.env.OFFER_RECEIPT_SIGNING_PRIVATE_KEY = conflictKey;
+ _resetIssuerForTests();
+ try {
+ await expect(getIssuer()).rejects.toThrow(/X402_PAY_TO_BASE/);
+ } finally {
+ process.env.X402_PAY_TO_BASE = savedPayTo;
+ process.env.OFFER_RECEIPT_SIGNING_PRIVATE_KEY = savedSignKey;
+ _resetIssuerForTests();
+ }
+ });
+});
+
+describe('buildOffersExtension', () => {
+ it('signs one offer per accepts entry and wraps them in the spec envelope', async () => {
+ const fragment = await buildOffersExtension(RESOURCE_URL, PAID_TO_REQUIREMENTS, {
+ offerValiditySeconds: 600,
+ });
+ expect(fragment).toBeTruthy();
+ const ext = fragment[OFFER_RECEIPT];
+ expect(ext).toBeTruthy();
+ expect(Array.isArray(ext.info.offers)).toBe(true);
+ expect(ext.info.offers).toHaveLength(PAID_TO_REQUIREMENTS.length);
+ expect(ext.schema).toMatchObject({ type: 'object', required: ['offers'] });
+
+ // Each EIP-712 offer recovers to the configured signing address.
+ const built = await getIssuer();
+ for (let i = 0; i < ext.info.offers.length; i++) {
+ const offer = ext.info.offers[i];
+ expect(offer.format).toBe('eip712');
+ expect(offer.acceptIndex).toBe(i);
+ const verified = await verifyOfferSignatureEIP712(offer);
+ expect(verified.signer.toLowerCase()).toBe(built.signerAddress);
+ expect(verified.payload.resourceUrl).toBe(RESOURCE_URL);
+ expect(verified.payload.payTo).toBe(PAID_TO_REQUIREMENTS[i].payTo);
+ }
+ });
+});
+
+describe('buildReceiptExtension + storage hand-off', () => {
+ it('signs a receipt that matches the offer it pairs with', async () => {
+ const offersFragment = await buildOffersExtension(RESOURCE_URL, PAID_TO_REQUIREMENTS, {});
+ const offers = offersFragment[OFFER_RECEIPT].info.offers;
+ const baseOffer = offers[0];
+ const payerKey = generatePrivateKey();
+ const payerAddress = privateKeyToAccount(payerKey).address;
+
+ const built = await buildReceiptExtension(RESOURCE_URL, {
+ payer: payerAddress,
+ network: 'eip155:8453',
+ transaction: '0xdeadbeef',
+ }, { includeTxHash: false });
+ expect(built).toBeTruthy();
+
+ const receipt = built.extensionFragment[OFFER_RECEIPT].info.receipt;
+ expect(receipt.format).toBe('eip712');
+
+ const verified = await verifyReceiptSignatureEIP712(receipt);
+ const issuer = await getIssuer();
+ expect(verified.signer.toLowerCase()).toBe(issuer.signerAddress);
+ expect(verified.payload.payer).toBe(payerAddress);
+ expect(verified.payload.transaction).toBe(''); // privacy default
+
+ const offerPayload = extractOfferPayload(baseOffer);
+ const matches = verifyReceiptMatchesOffer(
+ receipt,
+ { ...offerPayload, signedOffer: baseOffer, format: baseOffer.format, acceptIndex: 0 },
+ [payerAddress],
+ );
+ expect(matches).toBe(true);
+ });
+
+ it('includes the on-chain tx hash when includeTxHash=true', async () => {
+ const payerAddress = privateKeyToAccount(generatePrivateKey()).address;
+ const built = await buildReceiptExtension(
+ RESOURCE_URL,
+ { payer: payerAddress, network: 'eip155:8453', transaction: '0xabc123' },
+ { includeTxHash: true },
+ );
+ const receipt = built.extensionFragment[OFFER_RECEIPT].info.receipt;
+ const payload = extractReceiptPayload(receipt);
+ expect(payload.transaction).toBe('0xabc123');
+ });
+
+ it('returns null when settled response lacks payer/network', async () => {
+ expect(
+ await buildReceiptExtension(RESOURCE_URL, { network: 'eip155:8453' }, {}),
+ ).toBeNull();
+ expect(
+ await buildReceiptExtension(RESOURCE_URL, { payer: '0xabc' }, {}),
+ ).toBeNull();
+ });
+});
diff --git a/tests/api/x402-gas-sponsoring.test.js b/tests/api/x402-gas-sponsoring.test.js
new file mode 100644
index 000000000..c03ed6746
--- /dev/null
+++ b/tests/api/x402-gas-sponsoring.test.js
@@ -0,0 +1,106 @@
+// USE-19: ERC-20 Approval Gas Sponsoring + USE-18: EIP-2612 Gas Sponsoring.
+//
+// Locks in `build402Body`'s behavior of advertising BOTH gas-sponsoring
+// extensions at the top level whenever any accept entry opts into the Permit2
+// asset-transfer method. Together, the two extensions cover the full ERC-20
+// universe for gasless onboarding: EIP-2612 for tokens that implement
+// `permit()`, ERC-20 approval as the universal fallback that signs a raw
+// `approve(Permit2, MaxUint256)` tx for the facilitator to broadcast.
+//
+// Coverage:
+// • Permit2 sibling present → both extension keys advertised.
+// • Plain EIP-3009-only accept (no Permit2) → neither extension advertised.
+// • Per-route declarators emit the same extension keys (used by wk.js
+// discovery doc + x402-status surface).
+
+import { beforeAll, describe, expect, it } from 'vitest';
+
+import {
+ EIP2612_EXTENSION_KEY,
+ ERC20_APPROVAL_EXTENSION_KEY,
+ build402Body,
+ declareEip2612GasSponsoringExtension,
+ declareErc20ApprovalGasSponsoringExtension,
+ paymentRequirements,
+ permit2VariantOf,
+ NETWORK_BASE_MAINNET,
+} from '../../api/_lib/x402-spec.js';
+
+beforeAll(() => {
+ // permit2VariantOf gates Permit2 sibling emission on CDP creds being
+ // configured — set test values so the EVM accepts get a Permit2 sibling.
+ process.env.CDP_API_KEY_ID = process.env.CDP_API_KEY_ID || 'test-cdp-key';
+ process.env.CDP_API_KEY_SECRET = process.env.CDP_API_KEY_SECRET || 'test-cdp-secret';
+ process.env.X402_PAY_TO_BASE =
+ process.env.X402_PAY_TO_BASE || '0x4022de2d36c334e73c7a108805cea11c0564f402';
+});
+
+describe('build402Body — gas-sponsoring extension advertisement', () => {
+ it('advertises both eip2612 + erc20-approval when a Permit2 accept is present', () => {
+ const accepts = paymentRequirements('https://three.ws/api/x402/example');
+ const permit2 = accepts.find((a) => a?.extra?.assetTransferMethod === 'permit2');
+ expect(permit2, 'expected paymentRequirements to emit a Permit2 sibling').toBeTruthy();
+
+ const body = build402Body({
+ resourceUrl: 'https://three.ws/api/x402/example',
+ accepts,
+ });
+
+ expect(body.extensions[EIP2612_EXTENSION_KEY]).toBeTruthy();
+ expect(body.extensions[ERC20_APPROVAL_EXTENSION_KEY]).toBeTruthy();
+ });
+
+ it('does NOT advertise either extension when only EIP-3009 accepts are offered', () => {
+ const eip3009Only = {
+ scheme: 'exact',
+ network: NETWORK_BASE_MAINNET,
+ amount: '1000',
+ payTo: '0x4022de2d36c334e73c7a108805cea11c0564f402',
+ asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
+ maxTimeoutSeconds: 60,
+ extra: { name: 'USD Coin', version: '2', decimals: 6 },
+ };
+ const body = build402Body({
+ resourceUrl: 'https://three.ws/api/x402/example',
+ accepts: [eip3009Only],
+ });
+
+ expect(body.extensions[EIP2612_EXTENSION_KEY]).toBeUndefined();
+ expect(body.extensions[ERC20_APPROVAL_EXTENSION_KEY]).toBeUndefined();
+ });
+
+ it('permit2VariantOf returns an accept whose Permit2 hint triggers both extensions', () => {
+ const base = {
+ scheme: 'exact',
+ network: NETWORK_BASE_MAINNET,
+ amount: '1000',
+ payTo: '0x4022de2d36c334e73c7a108805cea11c0564f402',
+ asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
+ maxTimeoutSeconds: 60,
+ extra: { name: 'USD Coin', version: '2', decimals: 6 },
+ };
+ const sibling = permit2VariantOf(base);
+ expect(sibling).toBeTruthy();
+ expect(sibling.extra.assetTransferMethod).toBe('permit2');
+ expect(sibling.extra.supportsEip2612).toBe(true);
+
+ const body = build402Body({
+ resourceUrl: 'https://three.ws/api/x402/example',
+ accepts: [base, sibling],
+ });
+ expect(body.extensions[EIP2612_EXTENSION_KEY]).toBeTruthy();
+ expect(body.extensions[ERC20_APPROVAL_EXTENSION_KEY]).toBeTruthy();
+ });
+});
+
+describe('per-route declarators emit the expected extension keys', () => {
+ it('declareEip2612GasSponsoringExtension keys under EIP2612_EXTENSION_KEY', () => {
+ const decl = declareEip2612GasSponsoringExtension();
+ expect(decl[EIP2612_EXTENSION_KEY]).toBeTruthy();
+ });
+
+ it('declareErc20ApprovalGasSponsoringExtension keys under ERC20_APPROVAL_EXTENSION_KEY', () => {
+ const decl = declareErc20ApprovalGasSponsoringExtension();
+ expect(decl[ERC20_APPROVAL_EXTENSION_KEY]).toBeTruthy();
+ });
+});
diff --git a/tests/api/x402-paid-endpoint-siwx.test.js b/tests/api/x402-paid-endpoint-siwx.test.js
new file mode 100644
index 000000000..1e8c2d449
--- /dev/null
+++ b/tests/api/x402-paid-endpoint-siwx.test.js
@@ -0,0 +1,272 @@
+// Integration tests for SIWX opt-in on api/_lib/x402-paid-endpoint.js.
+//
+// Exercises the full paidEndpoint() wrapper end-to-end with a stubbed Vercel
+// req/res so we cover both the 402 body shape (extension advertised, nonce
+// + supportedChains present) and the SIWX short-circuit (verified signature
+// + recorded grant → 200, otherwise 402 / 401). Uses a real Solana keypair so
+// the message construction + Ed25519 signature path runs end-to-end against
+// the upstream @x402/extensions/sign-in-with-x verifier.
+//
+// DATABASE_URL is required (the storage adapter writes through to Neon).
+// Tests scope rows under a per-run resource prefix so concurrent CI runs and
+// failed prior runs don't poison each other.
+
+import crypto from 'node:crypto';
+import { Readable } from 'node:stream';
+
+import { describe, it, expect, afterAll, beforeEach } from 'vitest';
+
+import { paidEndpoint } from '../../api/_lib/x402-paid-endpoint.js';
+import { sql } from '../../api/_lib/db.js';
+import { siwxStorage } from '../../api/_lib/siwx-storage.js';
+import {
+ SIGN_IN_WITH_X,
+ createSIWxPayload,
+ encodeSIWxHeader,
+} from '@x402/extensions/sign-in-with-x';
+import { Keypair } from '@solana/web3.js';
+import bs58 from 'bs58';
+import nacl from 'tweetnacl';
+
+const HAS_DB = !!process.env.DATABASE_URL;
+const itDb = HAS_DB ? it : it.skip;
+
+const RUN_TAG = `siwx-it-${crypto.randomUUID()}`;
+const ROUTE_BASE = `/__test__/siwx-${RUN_TAG.slice(0, 12)}`;
+
+function mockReqRes({ method = 'GET', headers = {}, url = ROUTE_BASE } = {}) {
+ const lowerHeaders = {};
+ for (const [k, v] of Object.entries(headers)) lowerHeaders[k.toLowerCase()] = v;
+ const req = Object.assign(new Readable({ read() {} }), {
+ method,
+ url,
+ headers: lowerHeaders,
+ connection: { remoteAddress: '127.0.0.1' },
+ socket: { remoteAddress: '127.0.0.1' },
+ });
+ req.push(null);
+ const chunks = [];
+ const resHeaders = {};
+ const res = {
+ statusCode: 200,
+ writableEnded: false,
+ setHeader(k, v) {
+ resHeaders[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return resHeaders[k.toLowerCase()];
+ },
+ end(body) {
+ if (body !== undefined) chunks.push(body);
+ res.writableEnded = true;
+ },
+ write(chunk) {
+ chunks.push(chunk);
+ },
+ get body() {
+ return chunks.join('');
+ },
+ get headers() {
+ return resHeaders;
+ },
+ };
+ return { req, res };
+}
+
+function decodeChallenge(res) {
+ return JSON.parse(
+ Buffer.from(String(res.getHeader('payment-required')), 'base64').toString('utf8'),
+ );
+}
+
+function makeHandler() {
+ return async ({ siwx }) => ({ ok: true, served: 'plain', siwx: siwx?.address ?? null });
+}
+
+const HANDLER_BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'object', properties: {}, required: [] },
+ output: { type: 'object', properties: { ok: { type: 'boolean' } } },
+ },
+ schema: { type: 'object' },
+};
+
+function makeEndpoint({ siwx, route }) {
+ return paidEndpoint({
+ route,
+ method: 'GET',
+ networks: ['solana'],
+ description: 'siwx integration test',
+ bazaar: HANDLER_BAZAAR,
+ handler: makeHandler(),
+ siwx,
+ });
+}
+
+// Sign a SIWX payload with @solana/web3.js Keypair using the wallet-adapter
+// signer shape the SDK accepts (publicKey + signMessage(Uint8Array)).
+function solanaAdapterSigner(kp) {
+ return {
+ publicKey: bs58.encode(kp.publicKey.toBytes()),
+ signMessage: async (msg) => nacl.sign.detached(msg, kp.secretKey),
+ };
+}
+
+async function signSiwxFromChallenge(challenge, signer, chainId) {
+ const info = challenge.extensions[SIGN_IN_WITH_X].info;
+ const completeInfo = { ...info, chainId, type: 'ed25519' };
+ const payload = await createSIWxPayload(completeInfo, signer);
+ return encodeSIWxHeader(payload);
+}
+
+describeIfDb('paidEndpoint() + siwx', () => {});
+
+function describeIfDb(name, fn) {
+ if (HAS_DB) return describe(name, fn);
+ return describe.skip(name, fn);
+}
+
+describeIfDb('paidEndpoint() with siwx opt-in', () => {
+ afterAll(async () => {
+ await sql`delete from siwx_payments where resource like ${'%' + RUN_TAG + '%'}`;
+ await sql`delete from siwx_nonces where resource like ${'%' + RUN_TAG + '%'}`;
+ });
+
+ it('without siwx: no sign-in-with-x extension in the 402 body', async () => {
+ const route = `${ROUTE_BASE}/no-siwx`;
+ const handler = paidEndpoint({
+ route,
+ networks: ['solana'],
+ description: 'no siwx',
+ bazaar: HANDLER_BAZAAR,
+ handler: makeHandler(),
+ });
+ const { req, res } = mockReqRes({ url: route });
+ await handler(req, res);
+ expect(res.statusCode).toBe(402);
+ const body = decodeChallenge(res);
+ expect(body.extensions[SIGN_IN_WITH_X]).toBeUndefined();
+ });
+
+ it('with siwx: 402 body declares the sign-in-with-x extension', async () => {
+ const route = `${ROUTE_BASE}/declared`;
+ const handler = makeEndpoint({
+ route,
+ siwx: { statement: 'sign to re-access', ttlSeconds: null },
+ });
+ const { req, res } = mockReqRes({ url: route });
+ await handler(req, res);
+ expect(res.statusCode).toBe(402);
+ const body = decodeChallenge(res);
+ const ext = body.extensions[SIGN_IN_WITH_X];
+ expect(ext).toBeTruthy();
+ expect(ext.info.statement).toBe('sign to re-access');
+ expect(typeof ext.info.nonce).toBe('string');
+ expect(ext.info.nonce.length).toBeGreaterThanOrEqual(16);
+ expect(typeof ext.info.issuedAt).toBe('string');
+ expect(Array.isArray(ext.supportedChains)).toBe(true);
+ expect(ext.supportedChains.length).toBeGreaterThanOrEqual(1);
+ expect(ext.supportedChains.some((c) => c.chainId.startsWith('solana:'))).toBe(true);
+ });
+
+ it('valid signature + no prior grant → 402 siwx_not_paid', async () => {
+ const route = `${ROUTE_BASE}/no-grant`;
+ const handler = makeEndpoint({
+ route,
+ siwx: { statement: 'gated', ttlSeconds: null },
+ });
+ const { req: req1, res: res1 } = mockReqRes({ url: route });
+ await handler(req1, res1);
+ const challenge = decodeChallenge(res1);
+
+ const kp = Keypair.generate();
+ const signer = solanaAdapterSigner(kp);
+ const chainId = challenge.extensions[SIGN_IN_WITH_X].supportedChains.find((c) =>
+ c.chainId.startsWith('solana:'),
+ ).chainId;
+ const headerVal = await signSiwxFromChallenge(challenge, signer, chainId);
+
+ const { req: req2, res: res2 } = mockReqRes({
+ url: route,
+ headers: { 'sign-in-with-x': headerVal },
+ });
+ await handler(req2, res2);
+ expect(res2.statusCode).toBe(402);
+ const body = decodeChallenge(res2);
+ expect(body.error).toMatch(/has not paid/i);
+ });
+
+ itDb('valid signature + recorded grant → 200 with handler body', async () => {
+ const route = `${ROUTE_BASE}/granted`;
+ const handler = makeEndpoint({
+ route,
+ siwx: { statement: 'gated', ttlSeconds: null },
+ });
+
+ // First call: fetch the 402 challenge so the SDK can pin nonce/issuedAt.
+ const { req: req1, res: res1 } = mockReqRes({ url: route });
+ await handler(req1, res1);
+ const challenge = decodeChallenge(res1);
+
+ // Now sign with a fresh Solana keypair and pre-record the grant under
+ // the (resource, address) pair the verified signature will produce.
+ const kp = Keypair.generate();
+ const signer = solanaAdapterSigner(kp);
+ const address = bs58.encode(kp.publicKey.toBytes());
+ const chainId = challenge.extensions[SIGN_IN_WITH_X].supportedChains.find((c) =>
+ c.chainId.startsWith('solana:'),
+ ).chainId;
+ const resourceUrl = challenge.resource.url;
+ await siwxStorage.recordPayment(resourceUrl, address, { network: chainId });
+
+ const headerVal = await signSiwxFromChallenge(challenge, signer, chainId);
+ const { req: req2, res: res2 } = mockReqRes({
+ url: route,
+ headers: { 'sign-in-with-x': headerVal },
+ });
+ await handler(req2, res2);
+ expect(res2.statusCode).toBe(200);
+ expect(res2.getHeader('x-siwx-address')).toBe(address);
+ const parsed = JSON.parse(res2.body);
+ expect(parsed.ok).toBe(true);
+ expect(parsed.siwx).toBe(address);
+ });
+
+ itDb('nonce replay → second attempt rejected as siwx_message_invalid', async () => {
+ const route = `${ROUTE_BASE}/replay`;
+ const handler = makeEndpoint({
+ route,
+ siwx: { statement: 'gated', ttlSeconds: null },
+ });
+ const { req: req1, res: res1 } = mockReqRes({ url: route });
+ await handler(req1, res1);
+ const challenge = decodeChallenge(res1);
+
+ const kp = Keypair.generate();
+ const signer = solanaAdapterSigner(kp);
+ const address = bs58.encode(kp.publicKey.toBytes());
+ const chainId = challenge.extensions[SIGN_IN_WITH_X].supportedChains.find((c) =>
+ c.chainId.startsWith('solana:'),
+ ).chainId;
+ const resourceUrl = challenge.resource.url;
+ await siwxStorage.recordPayment(resourceUrl, address, { network: chainId });
+
+ const headerVal = await signSiwxFromChallenge(challenge, signer, chainId);
+ const { req: r2, res: s2 } = mockReqRes({
+ url: route,
+ headers: { 'sign-in-with-x': headerVal },
+ });
+ await handler(r2, s2);
+ expect(s2.statusCode).toBe(200);
+
+ const { req: r3, res: s3 } = mockReqRes({
+ url: route,
+ headers: { 'sign-in-with-x': headerVal },
+ });
+ await handler(r3, s3);
+ expect(s3.statusCode).toBe(401);
+ const replayBody = JSON.parse(s3.body);
+ expect(replayBody.error).toBe('siwx_message_invalid');
+ });
+});
diff --git a/tests/siwx-storage.test.js b/tests/siwx-storage.test.js
deleted file mode 100644
index 7e2001c14..000000000
--- a/tests/siwx-storage.test.js
+++ /dev/null
@@ -1,145 +0,0 @@
-// Integration test for api/_lib/siwx-storage.js against the live Neon
-// Postgres pointed at by $DATABASE_URL. Hits real tables; each run namespaces
-// its rows under `test-resource-<uuid>` and deletes them afterwards so
-// concurrent CI runs don't collide. Skipped when DATABASE_URL is absent.
-
-import { randomUUID } from 'node:crypto';
-import { readFileSync } from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { beforeAll, afterAll, describe, expect, it } from 'vitest';
-
-const HERE = path.dirname(fileURLToPath(import.meta.url));
-const REPO_ROOT = path.resolve(HERE, '..');
-
-for (const envFile of ['.env.local', '.env']) {
- try {
- const raw = readFileSync(path.resolve(REPO_ROOT, envFile), 'utf8');
- for (const line of raw.split('\n')) {
- const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
- if (!m || process.env[m[1]]) continue;
- let val = m[2].trim();
- if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
- val = val.slice(1, -1);
- }
- process.env[m[1]] = val;
- }
- break;
- } catch {
- /* file not present */
- }
-}
-
-const hasDb = !!process.env.DATABASE_URL;
-const describeIfDb = hasDb ? describe : describe.skip;
-
-const RES_PREFIX = `test-resource-${randomUUID()}`;
-const NONCE_PREFIX = `test-nonce-${randomUUID()}`;
-
-describeIfDb('siwx-storage (real Postgres)', () => {
- /** @type {import('../api/_lib/siwx-storage.js')} */
- let mod;
- /** @type {any} */
- let sql;
-
- beforeAll(async () => {
- mod = await import('../api/_lib/siwx-storage.js');
- ({ sql } = await import('../api/_lib/db.js'));
- });
-
- afterAll(async () => {
- await sql`delete from siwx_payments where resource like ${RES_PREFIX + '%'}`;
- await sql`delete from siwx_nonces where resource like ${RES_PREFIX + '%'} or nonce like ${NONCE_PREFIX + '%'}`;
- });
-
- it('hasPaid returns false for an unknown wallet', async () => {
- const resource = `${RES_PREFIX}/unknown`;
- const result = await mod.siwxStorage.hasPaid(
- resource,
- '0xdEAd000000000000000000000000000000000000',
- );
- expect(result).toBe(false);
- });
-
- it('round-trips an EVM payment with mixed-case address', async () => {
- const resource = `${RES_PREFIX}/evm`;
- const checksummed = '0xAaBbCcDdEeFf0011223344556677889900AaBbCc';
- await mod.siwxStorage.recordPayment(resource, checksummed, {
- network: 'eip155:8453',
- });
- expect(await mod.siwxStorage.hasPaid(resource, checksummed)).toBe(true);
- expect(await mod.siwxStorage.hasPaid(resource, checksummed.toLowerCase())).toBe(true);
- expect(await mod.siwxStorage.hasPaid(resource, checksummed.toUpperCase())).toBe(true);
- const rows = await sql`
- select address from siwx_payments where resource = ${resource}
- `;
- expect(rows[0].address).toBe(checksummed.toLowerCase());
- });
-
- it('round-trips a Solana payment with case-sensitive Base58', async () => {
- const resource = `${RES_PREFIX}/sol`;
- const address = 'BSmWDgE9ex6dZYbiTsJGcwMEgFp8q4aWh92hdErQPeVW';
- await mod.siwxStorage.recordPayment(resource, address, {
- network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
- });
- expect(await mod.siwxStorage.hasPaid(resource, address)).toBe(true);
- expect(await mod.siwxStorage.hasPaid(resource, address.toLowerCase())).toBe(false);
- });
-
- it('honors ttlSeconds — payment expires', async () => {
- const resource = `${RES_PREFIX}/ttl`;
- const address = '0x1111111111111111111111111111111111111111';
- await mod.siwxStorage.recordPayment(resource, address, {
- network: 'eip155:8453',
- ttlSeconds: 1,
- });
- expect(await mod.siwxStorage.hasPaid(resource, address)).toBe(true);
- await new Promise((r) => setTimeout(r, 1500));
- expect(await mod.siwxStorage.hasPaid(resource, address)).toBe(false);
- });
-
- it('round-trips a nonce and is idempotent', async () => {
- const nonce = `${NONCE_PREFIX}-once`;
- const resource = `${RES_PREFIX}/nonce`;
- expect(await mod.siwxStorage.hasUsedNonce(nonce)).toBe(false);
- await mod.siwxStorage.recordNonce(nonce, {
- resource,
- address: '0xabc0000000000000000000000000000000000000',
- });
- expect(await mod.siwxStorage.hasUsedNonce(nonce)).toBe(true);
- await mod.siwxStorage.recordNonce(nonce, {
- resource,
- address: '0xabc0000000000000000000000000000000000000',
- });
- expect(await mod.siwxStorage.hasUsedNonce(nonce)).toBe(true);
- });
-
- it('pruneOldNonces(0) clears all nonces inserted by the test', async () => {
- const n1 = `${NONCE_PREFIX}-prune-1`;
- const n2 = `${NONCE_PREFIX}-prune-2`;
- await mod.siwxStorage.recordNonce(n1, { resource: `${RES_PREFIX}/p`, address: '0x' });
- await mod.siwxStorage.recordNonce(n2, { resource: `${RES_PREFIX}/p`, address: '0x' });
- const removed = await mod.pruneOldNonces(0);
- expect(removed).toBeGreaterThanOrEqual(2);
- expect(await mod.siwxStorage.hasUsedNonce(n1)).toBe(false);
- expect(await mod.siwxStorage.hasUsedNonce(n2)).toBe(false);
- });
-
- it('pruneExpiredPayments deletes rows past grace window', async () => {
- const resource = `${RES_PREFIX}/expired`;
- const address = '0x2222222222222222222222222222222222222222';
- await mod.siwxStorage.recordPayment(resource, address, {
- network: 'eip155:8453',
- ttlSeconds: 1,
- });
- await new Promise((r) => setTimeout(r, 1500));
- const removed = await mod.pruneExpiredPayments(0);
- expect(removed).toBeGreaterThanOrEqual(1);
- expect(await mod.siwxStorage.hasPaid(resource, address)).toBe(false);
- });
-
- it('normalizeAddress rejects unknown CAIP-2 namespaces', () => {
- expect(() => mod.normalizeAddress('cosmos:cosmoshub-4', 'cosmos1abc')).toThrow();
- });
-});
diff --git a/vercel.json b/vercel.json
index 40478e657..affa12ed2 100644
--- a/vercel.json
+++ b/vercel.json
@@ -669,6 +669,10 @@
"src": "/api/agents/check-name",
"dest": "/api/agents/check-name"
},
+ {
+ "src": "/api/agents/a2a-paid",
+ "dest": "/api/agents/a2a-paid"
+ },
{
"src": "/api/auth/github/connect",
"dest": "/api/auth/github/[action]?action=connect"