Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: enhance authentication handling by adding payment challenge for missing tokens

nirholasce7846dcc947
diff --git a/api/mcp.js b/api/mcp.js
index b03544c1e..abb4350ec 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -44,7 +44,10 @@ export default wrap(async (req, res) => {
const bearer = extractBearer(req);
const auth = await authenticateBearer(bearer, { audience: env.MCP_RESOURCE });
- if (!auth) return send401(res, 'missing or invalid access token');
+ if (!auth) {
+ if (!bearer && !req.headers['x-payment']) return sendX402Challenge(req, res);
+ return send401(res, 'missing or invalid access token');
+ }
const ipRl = await limits.mcpIp(clientIp(req));
if (!ipRl.success)
@@ -854,6 +857,10 @@ function formatAvatarList(avatars, { public: isPublic = false } = {}) {
async function handleSse(req, res) {
// We don't hold long-lived server→client subscriptions yet; respond politely.
const bearer = extractBearer(req);
+ // Unauthenticated callers without an X-PAYMENT header get an x402 challenge
+ // so x402scan / x402 clients can discover the price. Invalid bearers still
+ // get 401 with WWW-Authenticate so OAuth clients can re-auth correctly.
+ if (!bearer && !req.headers['x-payment']) return sendX402Challenge(req, res);
const auth = await authenticateBearer(bearer, { audience: env.MCP_RESOURCE });
if (!auth) return send401(res, 'missing or invalid access token');
res.statusCode = 405;
@@ -872,6 +879,39 @@ function quoteString(s) {
return `"${String(s).replace(/[\\"]/g, '\\$&')}"`;
}
+// x402 payment-required challenge (spec: https://x402.org).
+// Solana USDC, fixed price 0.001 USDC = 1000 base units (6 decimals).
+const X402_PAY_TO = 'BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN';
+const X402_USDC_SOLANA_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+function sendX402Challenge(req, res) {
+ const proto = (req.headers['x-forwarded-proto'] || 'https').toString().split(',')[0].trim();
+ const host = (req.headers['x-forwarded-host'] || req.headers.host || '').toString();
+ const resource = host ? `${proto}://${host}/api/mcp` : `${env.APP_ORIGIN}/api/mcp`;
+ res.statusCode = 402;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(
+ JSON.stringify({
+ x402Version: 1,
+ error: 'X-PAYMENT header is required',
+ accepts: [
+ {
+ scheme: 'exact',
+ network: 'solana',
+ maxAmountRequired: '1000',
+ resource,
+ description: 'MCP tool call',
+ mimeType: 'application/json',
+ payTo: X402_PAY_TO,
+ maxTimeoutSeconds: 60,
+ asset: X402_USDC_SOLANA_MINT,
+ extra: { name: 'USDC', decimals: 6 },
+ },
+ ],
+ }),
+ );
+}
+
function send401(res, msg) {
const resource = env.MCP_RESOURCE;
res.statusCode = 401;
diff --git a/api/openapi-json.js b/api/openapi-json.js
index e2b53372e..0c066dd2e 100644
--- a/api/openapi-json.js
+++ b/api/openapi-json.js
@@ -89,8 +89,15 @@ export default wrap(async (req, res) => {
amount: '0.001',
},
protocols: [
- { x402: {} },
- { mpp: { method: '', intent: '', currency: '' } },
+ {
+ x402: {
+ network: 'solana',
+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ payTo: 'BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN',
+ scheme: 'exact',
+ maxAmountRequired: '1000',
+ },
+ },
],
},
},
@@ -143,24 +150,6 @@ export default wrap(async (req, res) => {
},
},
},
- '/api/avatars/public': {
- get: {
- operationId: 'browse_public_avatars',
- summary: 'Browse public avatars',
- parameters: [
- { name: 'q', in: 'query', schema: { type: 'string' } },
- {
- name: 'limit',
- in: 'query',
- schema: { type: 'integer', default: 20, maximum: 100 },
- },
- { name: 'cursor', in: 'query', schema: { type: 'string' } },
- ],
- responses: {
- 200: { description: 'Paginated list of public avatars' },
- },
- },
- },
'/api/agents': {
get: {
operationId: 'list_agents',
diff --git a/docs/x402.md b/docs/x402.md
new file mode 100644
index 000000000..846b3f283
--- /dev/null
+++ b/docs/x402.md
@@ -0,0 +1,124 @@
+# x402 — paid agent skills
+
+This codebase implements [x402](https://x402.org) `HTTP 402 Payment Required`
+on top of Pump.fun agent payments. Callers pay an agent in any SPL token to
+invoke a skill; the agent verifies the on-chain payment and dispatches the
+call.
+
+## Server side
+
+Wire any endpoint as a paid skill in three lines:
+
+```js
+import { emit402, verifyPaid, consumeIntent } from 'api/_lib/x402.js';
+
+const paid = await verifyPaid(req, {
+ agentId: agent.id,
+ skill: 'summarize',
+ expectedAmount: '10000', // raw token units
+ expectedCurrency: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
+});
+if (!paid) {
+ return emit402(res, {
+ agent, skill: 'summarize',
+ amount: '10000',
+ currency: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ });
+}
+await consumeIntent(paid.intentId); // single-shot
+return doTheThing();
+```
+
+Reference implementation: `api/agents/x402/invoke.js`.
+
+## 402 manifest shape
+
+```json
+{
+ "version": "x402/0.1",
+ "kind": "agent-skill",
+ "agent_id": "<uuid>",
+ "skill": "summarize",
+ "amount": "10000",
+ "currency": "<mint base58>",
+ "recipient": "<owner wallet base58>",
+ "memo": "<u64 invoice nonce>",
+ "valid_until": <unix>,
+ "intent_url": "/api/agents/payments/pay-prep",
+ "verify_url": "/api/agents/payments/pay-confirm",
+ "retry_with_header": "x-payment-intent"
+}
+```
+
+Discovery:
+
+- `GET /.well-known/x402` — site-level resource list.
+- `GET /api/agents/x402/manifest?agent_id=…&skill=…` — per-skill price
+ manifest, returned as 200 (not 402) for prefetch.
+- The 402 response includes a `Link: <…>; rel="payment-manifest"` header
+ pointing at the manifest URL.
+
+## Pricing
+
+`api/agents/x402/invoke.js` resolves the price for `(agent, skill)` via:
+
+1. `agent.meta.skill_prices[skill]` — `{ amount, currency }` per skill.
+2. `agent.meta.payments.default_price` — fallback for unspecified skills.
+3. Hard default: 10000 raw USDC = $0.01.
+
+Update via `PATCH /api/agents/:id` with `{ meta: { skill_prices: {...} } }`.
+
+## Caller (browser) — automatic
+
+```js
+import { x402Fetch } from 'src/onchain/x402/client.js';
+
+const res = await x402Fetch('/api/agents/x402/invoke', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agent_id, skill: 'echo', args: { hi: 1 } }),
+ onPaymentRequired: (manifest) => 'auto', // or 'reject' to abort
+ onProgress: (step) => console.log(step),
+});
+```
+
+The wrapper pays via Pump.fun's `agent_accept_payment`, attaches
+`x-payment-intent: <intent_id>`, and retries the original call exactly once.
+
+## Caller (server / SDK) — manual
+
+```bash
+# 1. Discover the price.
+curl 'https://three.ws/api/agents/x402/manifest?agent_id=AGENT&skill=echo'
+
+# 2. Pay (prep + sign + confirm). Receive intent_id.
+curl -X POST https://three.ws/api/agents/payments/pay-prep -d '{...}'
+# (sign the returned tx_base64 with the caller's wallet, submit to Solana)
+curl -X POST https://three.ws/api/agents/payments/pay-confirm -d '{...}'
+
+# 3. Retry with the intent header.
+curl -X POST https://three.ws/api/agents/x402/invoke \
+ -H 'x-payment-intent: <intent_id>' \
+ -d '{"agent_id":"AGENT","skill":"echo","args":{}}'
+```
+
+## Single-shot semantics
+
+A paid intent is consumed on first successful call. Failed calls don't refund —
+the intent paid for the *attempt*, not the *result*. Retrying a failed call
+requires a new intent.
+
+For idempotency (don't double-charge on network retry), pass an
+`Idempotency-Key` header — implementations are free to dedupe before
+consuming the intent. Not yet enforced server-side.
+
+## Differences from x402 mainline
+
+- We bind intents to `(agent, skill)` server-side — the manifest's
+ `recipient` is the agent owner's wallet, but the server tracks the
+ invoice via `agent_payment_intents.payload.skill`.
+- We use Pump.fun's `agent_accept_payment` rather than a generic SPL
+ transfer. This adds buyback/burn semantics on top of the basic spec but
+ the wire shape (manifest + retry header) is unchanged.
+- Currency is always an SPL mint pubkey. SOL-native payments aren't
+ supported yet.
diff --git a/public/dashboard/index.html b/public/dashboard/index.html
index b46a7a43b..2c976488a 100644
--- a/public/dashboard/index.html
+++ b/public/dashboard/index.html
@@ -7,7 +7,10 @@
<link rel="icon" href="/favicon.ico" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet" />
+ <link
+ href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap"
+ rel="stylesheet"
+ />
<link rel="stylesheet" href="/footer.css" />
<style>
:root {
@@ -75,14 +78,18 @@
overflow-x: auto;
scrollbar-width: none;
}
- .dash-header-nav::-webkit-scrollbar { display: none; }
+ .dash-header-nav::-webkit-scrollbar {
+ display: none;
+ }
.dash-header-nav a {
padding: 6px 10px;
border-radius: 6px;
color: #888;
font-size: 13px;
text-decoration: none;
- transition: color 0.15s, background 0.15s;
+ transition:
+ color 0.15s,
+ background 0.15s;
white-space: nowrap;
}
.dash-header-nav a:hover {
@@ -1173,7 +1180,9 @@
<p class="h-footer-tagline">Give your AI a body.</p>
</div>
<nav class="h-footer-links" aria-label="Footer">
- <a href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener">GitHub</a>
+ <a href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener"
+ >GitHub</a
+ >
<a href="/create">Create</a>
<a href="/studio">Studio</a>
<a href="/widgets">Widgets</a>
@@ -1181,7 +1190,9 @@
<a href="/discover">Discover</a>
<a href="/showcase">Showcase</a>
<a href="/docs">Docs</a>
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener">ERC-8004</a>
+ <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener"
+ >ERC-8004</a
+ >
<a href="/legal/privacy">Privacy</a>
<a href="/legal/tos">Terms</a>
</nav>
@@ -1194,11 +1205,27 @@
<span>All systems normal</span>
</span>
<span class="h-footer-badge">
- <svg viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M8 0a8 8 0 1 0 0 16A8 8 0 0 0 8 0zm0 14.5A6.5 6.5 0 1 1 8 1.5a6.5 6.5 0 0 1 0 13zm-1-9.25a1 1 0 1 1 2 0v3.5a1 1 0 1 1-2 0v-3.5zm1 6.5a1.1 1.1 0 1 1 0-2.2 1.1 1.1 0 0 1 0 2.2z"/></svg>
+ <svg viewBox="0 0 16 16" aria-hidden="true">
+ <path
+ fill="currentColor"
+ d="M8 0a8 8 0 1 0 0 16A8 8 0 0 0 8 0zm0 14.5A6.5 6.5 0 1 1 8 1.5a6.5 6.5 0 0 1 0 13zm-1-9.25a1 1 0 1 1 2 0v3.5a1 1 0 1 1-2 0v-3.5zm1 6.5a1.1 1.1 0 1 1 0-2.2 1.1 1.1 0 0 1 0 2.2z"
+ />
+ </svg>
<span>Transparent by default</span>
</span>
- <a class="h-footer-badge" href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener" aria-label="View source on GitHub">
- <svg viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>
+ <a
+ class="h-footer-badge"
+ href="https://github.com/nirholas/three.ws"
+ target="_blank"
+ rel="noopener"
+ aria-label="View source on GitHub"
+ >
+ <svg viewBox="0 0 16 16" aria-hidden="true">
+ <path
+ fill="currentColor"
+ d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"
+ />
+ </svg>
<span>Open source</span>
</a>
</div>
diff --git a/public/dashboard/pump-relay.html b/public/dashboard/pump-relay.html
index 48aef2686..de415a880 100644
--- a/public/dashboard/pump-relay.html
+++ b/public/dashboard/pump-relay.html
@@ -16,26 +16,113 @@
--panel: #14141c;
--muted: #888;
}
- * { box-sizing: border-box; }
- body { font: 15px/1.55 system-ui, sans-serif; color: #eee; margin: 0; background: var(--bg); }
- header { display: flex; justify-content: space-between; padding: 16px 24px; border-bottom: 1px solid var(--border); }
- main { padding: 28px; max-width: 880px; margin: 0 auto; }
- h1 { font-size: 22px; margin: 0 0 6px; }
- .sub { color: var(--muted); margin: 0 0 22px; }
- .panel { background: var(--panel); border: 1px solid var(--border); border-radius: 14px; padding: 18px 20px; margin-bottom: 18px; }
- label { display: block; font-size: 13px; color: var(--muted); margin: 8px 0 4px; }
- input, select { width: 100%; padding: 8px 10px; background: #0e0e14; border: 1px solid var(--border); border-radius: 8px; color: #eee; font: inherit; }
- button { background: var(--accent); color: white; border: 0; padding: 9px 16px; border-radius: 8px; font: inherit; cursor: pointer; }
- button:disabled { opacity: .5; cursor: not-allowed; }
- button.ghost { background: transparent; border: 1px solid var(--border); color: #eee; }
- .row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
- .muted { color: var(--muted); }
- .ok { color: var(--ok); }
- .err { color: var(--err); }
- pre { background: #08080c; border: 1px solid var(--border); border-radius: 8px; padding: 10px; overflow: auto; font-size: 12px; }
- table { width: 100%; border-collapse: collapse; font-size: 13px; }
- td, th { padding: 8px 6px; border-bottom: 1px solid var(--border); text-align: left; }
- .mono { font-family: ui-monospace, monospace; }
+ * {
+ box-sizing: border-box;
+ }
+ body {
+ font:
+ 15px/1.55 system-ui,
+ sans-serif;
+ color: #eee;
+ margin: 0;
+ background: var(--bg);
+ }
+ header {
+ display: flex;
+ justify-content: space-between;
+ padding: 16px 24px;
+ border-bottom: 1px solid var(--border);
+ }
+ main {
+ padding: 28px;
+ max-width: 880px;
+ margin: 0 auto;
+ }
+ h1 {
+ font-size: 22px;
+ margin: 0 0 6px;
+ }
+ .sub {
+ color: var(--muted);
+ margin: 0 0 22px;
+ }
+ .panel {
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 14px;
+ padding: 18px 20px;
+ margin-bottom: 18px;
+ }
+ label {
+ display: block;
+ font-size: 13px;
+ color: var(--muted);
+ margin: 8px 0 4px;
+ }
+ input,
+ select {
+ width: 100%;
+ padding: 8px 10px;
+ background: #0e0e14;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ color: #eee;
+ font: inherit;
+ }
+ button {
+ background: var(--accent);
+ color: white;
+ border: 0;
+ padding: 9px 16px;
+ border-radius: 8px;
+ font: inherit;
+ cursor: pointer;
+ }
+ button:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+ button.ghost {
+ background: transparent;
+ border: 1px solid var(--border);
+ color: #eee;
+ }
+ .row {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 12px;
+ }
+ .muted {
+ color: var(--muted);
+ }
+ .ok {
+ color: var(--ok);
+ }
+ .err {
+ color: var(--err);
+ }
+ pre {
+ background: #08080c;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 10px;
+ overflow: auto;
+ font-size: 12px;
+ }
+ table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 13px;
+ }
+ td,
+ th {
+ padding: 8px 6px;
+ border-bottom: 1px solid var(--border);
+ text-align: left;
+ }
+ .mono {
+ font-family: ui-monospace, monospace;
+ }
</style>
</head>
<body>
@@ -45,15 +132,18 @@
</header>
<main>
<h1>Pump.fun relay trading</h1>
- <p class="sub">Authorize the three.ws server keypair to execute pump.fun trades on your behalf, capped by SOL and TTL. MCP clients without a wallet can then drive trades.</p>
+ <p class="sub">
+ Authorize the three.ws server keypair to execute pump.fun trades on your behalf,
+ capped by SOL and TTL. MCP clients without a wallet can then drive trades.
+ </p>
<div class="panel">
- <h2 style="margin-top:0">Server relayer</h2>
+ <h2 style="margin-top: 0">Server relayer</h2>
<div id="relayer-info">Loading…</div>
</div>
<div class="panel">
- <h2 style="margin-top:0">Authorize</h2>
+ <h2 style="margin-top: 0">Authorize</h2>
<div class="row">
<div>
<label>Wallet (base58)</label>
@@ -61,13 +151,23 @@
</div>
<div>
<label>Network</label>
- <select id="network"><option>mainnet</option><option>devnet</option></select>
+ <select id="network">
+ <option>mainnet</option>
+ <option>devnet</option>
+ </select>
</div>
</div>
<div class="row">
<div>
<label>Max SOL (cumulative cap)</label>
- <input id="max-sol" type="number" min="0.01" max="100" step="0.01" value="0.5" />
+ <input
+ id="max-sol"
+ type="number"
+ min="0.01"
+ max="100"
+ step="0.01"
+ value="0.5"
+ />
</div>
<div>
<label>TTL (hours)</label>
@@ -77,28 +177,62 @@
<div class="row">
<div>
<label>Direction</label>
- <select id="direction"><option>both</option><option>buy</option><option>sell</option></select>
+ <select id="direction">
+ <option>both</option>
+ <option>buy</option>
+ <option>sell</option>
+ </select>
</div>
<div>
<label>Mint filter (optional)</label>
<input id="mint-filter" placeholder="lock to a single mint" />
</div>
</div>
- <div style="margin-top:14px; display:flex; gap:8px">
+ <div style="margin-top: 14px; display: flex; gap: 8px">
<button id="authorize">Sign + authorize</button>
<button id="refresh" class="ghost">Refresh delegations</button>
</div>
- <div id="status" class="muted" style="margin-top:10px"></div>
+ <div id="status" class="muted" style="margin-top: 10px"></div>
</div>
<div class="panel">
- <h2 style="margin-top:0">Active delegations</h2>
+ <h2 style="margin-top: 0">Active delegations</h2>
<div id="delegations">Loading…</div>
</div>
</main>
<script type="module">
- import { buildRelayAuthorizationMessage } from '/src/agent-skills-pumpfun.js';
+ function buildRelayAuthorizationMessage({
+ userWallet,
+ relayerPubkey,
+ maxSol,
+ mint,
+ direction = 'both',
+ network = 'mainnet',
+ ttlHours = 24,
+ domain = location.host,
+ }) {
+ const issuedAt = new Date().toISOString();
+ const expiresAt = new Date(Date.now() + ttlHours * 3600 * 1000).toISOString();
+ const nonce = Math.random().toString(36).slice(2, 14);
+ const statement =
+ `Authorize three.ws relayer ${relayerPubkey} to trade pump.fun on my behalf.\n` +
+ `max=${maxSol}\nexpires=${expiresAt}\ndirection=${direction}` +
+ (mint ? `\nmint=${mint}` : '');
+ return [
+ `${domain} wants you to sign in with your Solana account:`,
+ userWallet,
+ '',
+ statement,
+ '',
+ `URI: https://${domain}/api/pump/relay-authorize`,
+ 'Version: 1',
+ `Chain ID: ${network}`,
+ `Nonce: ${nonce}`,
+ `Issued At: ${issuedAt}`,
+ `Expiration Time: ${expiresAt}`,
+ ].join('\n');
+ }
const $ = (id) => document.getElementById(id);
let RELAYER_PUBKEY = null;
@@ -108,9 +242,11 @@
const r = await fetch('/api/pump/relayer-info').then((r) => r.json());
if (r.relayer_pubkey) {
RELAYER_PUBKEY = r.relayer_pubkey;
- $('relayer-info').innerHTML = `<div class="mono" style="word-break:break-all">${r.relayer_pubkey}</div><div class="muted" style="margin-top:4px">Fund this address with SOL to cover trade fees.</div>`;
+ $('relayer-info').innerHTML =
+ `<div class="mono" style="word-break:break-all">${r.relayer_pubkey}</div><div class="muted" style="margin-top:4px">Fund this address with SOL to cover trade fees.</div>`;
} else {
- $('relayer-info').innerHTML = `<span class="err">Relayer not configured (PUMP_RELAYER_SECRET_KEY_B64 unset)</span>`;
+ $('relayer-info').innerHTML =
+ `<span class="err">Relayer not configured (PUMP_RELAYER_SECRET_KEY_B64 unset)</span>`;
}
} catch (e) {
$('relayer-info').innerHTML = `<span class="err">${e.message}</span>`;
@@ -119,11 +255,14 @@
async function loadDelegations() {
try {
- const r = await fetch('/api/pump/relay-delegations', { credentials: 'include' });
+ const r = await fetch('/api/pump/relay-delegations', {
+ credentials: 'include',
+ });
if (!r.ok) throw new Error(`${r.status}`);
const data = await r.json();
if (!data.data || data.data.length === 0) {
- $('delegations').innerHTML = '<div class="muted">No active delegations.</div>';
+ $('delegations').innerHTML =
+ '<div class="muted">No active delegations.</div>';
return;
}
const rows = data.data
@@ -170,7 +309,7 @@
const mintFilter = $('mint-filter').value.trim() || null;
const ttlHours = Number($('ttl-hours').value);
- const { message } = buildRelayAuthorizationMessage({
+ const message = buildRelayAuthorizationMessage({
userWallet: wallet,
relayerPubkey: RELAYER_PUBKEY,
maxSol,
diff --git a/scripts/apply-migrations.mjs b/scripts/apply-migrations.mjs
index 4bb2f2fb3..db581816b 100755
--- a/scripts/apply-migrations.mjs
+++ b/scripts/apply-migrations.mjs
@@ -51,9 +51,7 @@ async function ensureTrackingTable() {
}
async function listPending() {
- const all = (await readdir(MIG_DIR))
- .filter((f) => f.endsWith('.sql'))
- .sort();
+ const all = (await readdir(MIG_DIR)).filter((f) => f.endsWith('.sql')).sort();
const applied = await sql`select filename, sha256 from schema_migrations`;
const appliedMap = new Map(applied.map((r) => [r.filename, r.sha256]));
@@ -63,7 +61,12 @@ async function listPending() {
const body = await readFile(path.join(MIG_DIR, fname), 'utf-8');
const hash = createHash('sha256').update(body).digest('hex');
const prior = appliedMap.get(fname);
- out.push({ fname, body, hash, status: !prior ? 'pending' : prior === hash ? 'applied' : 'drift' });
+ out.push({
+ fname,
+ body,
+ hash,
+ status: !prior ? 'pending' : prior === hash ? 'applied' : 'drift',
+ });
}
return out;
}
@@ -122,7 +125,9 @@ async function main() {
return;
}
- console.log(`\nApplying ${pending.length} migration(s) to ${maskUrl(process.env.DATABASE_URL)} …`);
+ console.log(
+ `\nApplying ${pending.length} migration(s) to ${maskUrl(process.env.DATABASE_URL)} …`,
+ );
for (const i of pending) await applyOne(i);
console.log('Done.');
}
diff --git a/src/onchain/README.md b/src/onchain/README.md
index 83f347b69..4cc870d7b 100644
--- a/src/onchain/README.md
+++ b/src/onchain/README.md
@@ -256,6 +256,77 @@ Schema: `payment_configs_pending` + `agent_payment_intents` (see migration
}
```
+## Vanity wallets (custodial agent identities)
+
+Agents can be provisioned with a custodial Solana wallet whose address starts
+with a chosen base58 prefix. The secret key is encrypted server-side
+(AES-GCM, HKDF-derived from `JWT_SECRET`) and never leaves the server after
+provisioning.
+
+```js
+import { VanityWalletButton } from 'src/onchain/vanity-wallet-button.js';
+new VanityWalletButton({ agent, container }).mount();
+```
+
+Headless usage:
+
+```js
+import { provisionVanityForAgent } from 'src/onchain/vanity/index.js';
+await provisionVanityForAgent({
+ agentId,
+ prefix: 'AGNT',
+ ignoreCase: false,
+ onProgress: ({ rate, eta }) => console.log(rate, eta),
+});
+```
+
+Grinding happens client-side via Web Workers (one per logical core, capped
+at 8). Long prefixes take time — pass an `AbortSignal` to support a Cancel
+UX. Server-side grinding for 5+ char prefixes already exists in
+`api/_lib/pump-vanity.js` and is wired into the legacy `pumpfun/launch`
+flow.
+
+The provisioning endpoint (`POST /api/agents/:id/solana`) verifies that the
+submitted secret derives the claimed pubkey and that the prefix matches
+before storing the encrypted secret.
+
+## x402 (HTTP 402 Payment Required for paid skills)
+
+Wires the agent payments layer to per-call paywalls. Any agent endpoint can
+return `402 Payment Required` with a canonical manifest; clients pay via the
+Pump.fun agent-payments flow and retry with `x-payment-intent`.
+
+Server middleware:
+
+```js
+import { emit402, verifyPaid, consumeIntent } from 'api/_lib/x402.js';
+
+const paid = await verifyPaid(req, {
+ agentId, skill: 'summarize',
+ expectedAmount: '10000',
+ expectedCurrency: USDC_MINT,
+});
+if (!paid) return emit402(res, { agent, skill, amount, currency });
+await consumeIntent(paid.intentId); // single-shot
+return doTheThing();
+```
+
+Reference impl: `api/agents/x402/invoke.js` (paid-skill router with `echo`
+demo skill). Manifest discovery at `GET /api/agents/x402/manifest`.
+
+Client wrapper that follows 402 automatically:
+
+```js
+import { x402Fetch } from 'src/onchain/x402/client.js';
+const res = await x402Fetch('/api/agents/x402/invoke', {
+ method: 'POST',
+ body: JSON.stringify({ agent_id, skill: 'echo', args: {} }),
+ onPaymentRequired: () => 'auto',
+});
+```
+
+Full spec at [docs/x402.md](../../docs/x402.md).
+
Note: the agent-payments-sdk is published as a restricted npm package. If
`npm install` fails with 403, contact Pump.fun for access. The pump-sdk used
for token launches is public and unaffected.
diff --git a/tests/api/x402.test.js b/tests/api/x402.test.js
new file mode 100644
index 000000000..a05b539d6
--- /dev/null
+++ b/tests/api/x402.test.js
@@ -0,0 +1,122 @@
+/**
+ * Tests for the x402 helper. Pure-logic only — no DB, no fetch.
+ *
+ * verifyPaid touches the DB (via _lib/db.js); we exercise emit402 and
+ * manifestOnly, which are stateless transformations of agent + skill.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { emit402, manifestOnly, X402_VERSION } from '../../api/_lib/x402.js';
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(name, value) {
+ this.headers[name.toLowerCase()] = value;
+ },
+ end(body) {
+ this.body = body;
+ },
+ };
+}
+
+function makeAgent(overrides = {}) {
+ return {
+ id: 'agent-uuid',
+ name: 'Test Agent',
+ meta: {
+ payments: {
+ configured: true,
+ provider: 'pumpfun',
+ mint: 'MintPubkey1111111111111111111111111111111',
+ receiver: 'OwnerWallet111111111111111111111111111111',
+ cluster: 'mainnet',
+ },
+ ...overrides,
+ },
+ };
+}
+
+describe('emit402', () => {
+ it('returns 402 with a canonical manifest', () => {
+ const res = makeRes();
+ emit402(res, {
+ agent: makeAgent(),
+ skill: 'summarize',
+ amount: '10000',
+ currency: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ });
+ expect(res.statusCode).toBe(402);
+ expect(res.headers['content-type']).toBe('application/json');
+ expect(res.headers['cache-control']).toBe('no-store');
+ expect(res.headers['link']).toMatch(/payment-manifest/);
+
+ const body = JSON.parse(res.body);
+ expect(body.version).toBe(X402_VERSION);
+ expect(body.kind).toBe('agent-skill');
+ expect(body.agent_id).toBe('agent-uuid');
+ expect(body.skill).toBe('summarize');
+ expect(body.amount).toBe('10000');
+ expect(body.currency).toBe('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');
+ expect(body.recipient).toBe('OwnerWallet111111111111111111111111111111');
+ expect(body.intent_url).toBe('/api/agents/payments/pay-prep');
+ expect(body.verify_url).toBe('/api/agents/payments/pay-confirm');
+ expect(body.retry_with_header).toBe('x-payment-intent');
+ expect(typeof body.valid_until).toBe('number');
+ expect(body.valid_until).toBeGreaterThan(Date.now() / 1000);
+ });
+
+ it('refuses to 402 when payments are not configured', () => {
+ const res = makeRes();
+ const agent = { id: 'x', name: 'x', meta: { payments: { configured: false } } };
+ // emit402 should fall through to error() — we just assert it didn't 402.
+ emit402(res, { agent, skill: 's', amount: '1', currency: 'X' });
+ expect(res.statusCode).not.toBe(402);
+ });
+
+ it('honors validForSec', () => {
+ const res = makeRes();
+ const before = Math.floor(Date.now() / 1000);
+ emit402(res, {
+ agent: makeAgent(),
+ skill: 's',
+ amount: '1',
+ currency: 'X',
+ validForSec: 60,
+ });
+ const body = JSON.parse(res.body);
+ expect(body.valid_until - before).toBeGreaterThanOrEqual(59);
+ expect(body.valid_until - before).toBeLessThanOrEqual(61);
+ });
+});
+
+describe('manifestOnly', () => {
+ it('returns the same manifest shape with status 200', () => {
+ // We mock just enough of the http json() helper to get a captured body.
+ const captured = {};
+ const res = {
+ statusCode: 0,
+ headers: {},
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(body) {
+ captured.body = body;
+ captured.status = this.statusCode;
+ },
+ };
+ manifestOnly(res, {
+ agent: makeAgent(),
+ skill: 'echo',
+ amount: '5000',
+ currency: 'CURRENCY-MINT',
+ });
+ expect(captured.status).toBe(200);
+ const body = JSON.parse(captured.body);
+ expect(body.version).toBe(X402_VERSION);
+ expect(body.skill).toBe('echo');
+ expect(body.amount).toBe('5000');
+ });
+});