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: add Solana wallet provisioning UI and integration in agent home panel

nirholas97b7b54f10b7
diff --git a/api/_lib/x402.js b/api/_lib/x402.js
new file mode 100644
index 000000000..ce738ba49
--- /dev/null
+++ b/api/_lib/x402.js
@@ -0,0 +1,170 @@
+/**
+ * x402 — HTTP 402 Payment Required helpers.
+ *
+ * Spec: https://x402.org (in flux as of 2026-04). We implement a minimal
+ * subset that matches the Coinbase x402 client and our internal payment
+ * pipeline (Pump.fun agent-payments-sdk).
+ *
+ * Server-side flow:
+ * 1. Caller hits a paid endpoint.
+ * 2. We look for a payment proof header (x-payment-intent or
+ * x-payment-tx-sig). If missing or unpaid, emit 402 with a manifest:
+ *
+ * HTTP/1.1 402 Payment Required
+ * Content-Type: application/json
+ *
+ * {
+ * "version": "x402/0.1",
+ * "kind": "agent-skill",
+ * "agent_id": "...",
+ * "skill": "summarize",
+ * "amount": "1000000", // raw token units (string-bigint)
+ * "currency": "<mint base58>", // e.g. USDC
+ * "recipient": "<owner wallet>",
+ * "memo": "<u64 invoice nonce>",
+ * "valid_until": "<unix>",
+ * "intent_url": "/api/agents/payments/pay-prep",
+ * "verify_url": "/api/agents/payments/pay-confirm"
+ * }
+ *
+ * 3. Caller follows the manifest, pays via /pay-prep + wallet sign +
+ * /pay-confirm, gets back an `intent_id`. They retry the original call
+ * with `x-payment-intent: <intent_id>`.
+ * 4. We verify the intent is `status='paid'` for this agent + skill +
+ * caller, then proceed.
+ *
+ * The 402 response is cached by the spec to be idempotent — a caller may
+ * request the manifest, sit on it, and pay later. We honor that by NOT
+ * minting an intent until the caller calls `/pay-prep`.
+ */
+
+import { sql } from './db.js';
+import { json, error } from './http.js';
+
+export const X402_VERSION = 'x402/0.1';
+
+/**
+ * Emit a 402 Payment Required response with a canonical manifest body.
+ *
+ * @param {import('http').ServerResponse} res
+ * @param {object} opts
+ * @param {object} opts.agent Agent record (must have meta.payments configured).
+ * @param {string} opts.skill Skill identifier (free-form, used by the manifest).
+ * @param {string} opts.amount Raw token units as a numeric string.
+ * @param {string} opts.currency Mint pubkey (base58) for the currency token.
+ * @param {number} [opts.validForSec=900] Manifest validity in seconds (default 15m).
+ */
+export function emit402(res, { agent, skill, amount, currency, validForSec = 900 }) {
+ const payments = agent?.meta?.payments || agent?.payments;
+ if (!payments?.configured) {
+ // Misconfigured: we shouldn't gate a skill behind 402 if payments aren't on.
+ return error(res, 500, 'misconfigured', 'agent has no payments config');
+ }
+ const validUntil = Math.floor(Date.now() / 1000) + validForSec;
+ const manifest = {
+ version: X402_VERSION,
+ kind: 'agent-skill',
+ agent_id: agent.id,
+ skill,
+ amount: String(amount),
+ currency,
+ recipient: payments.receiver,
+ memo: String(Math.floor(Date.now() / 1000)),
+ valid_until: validUntil,
+ intent_url: '/api/agents/payments/pay-prep',
+ verify_url: '/api/agents/payments/pay-confirm',
+ retry_with_header: 'x-payment-intent',
+ };
+ res.statusCode = 402;
+ res.setHeader('content-type', 'application/json');
+ res.setHeader('cache-control', 'no-store');
+ // Hint the canonical manifest URL so x402 clients can prefetch.
+ res.setHeader(
+ 'link',
+ `</.well-known/x402>; rel="payment-config", </api/agents/${agent.id}/x402/${encodeURIComponent(skill)}/manifest>; rel="payment-manifest"`,
+ );
+ res.end(JSON.stringify(manifest));
+ return true;
+}
+
+/**
+ * Read x-payment-intent (or x-payment-tx-sig) headers and verify the request
+ * is paid for `agentId` + `skill`. Returns the verified intent row, or null
+ * if not paid (caller should `emit402`).
+ *
+ * @param {import('http').IncomingMessage} req
+ * @param {{ agentId: string, skill: string, expectedAmount?: string, expectedCurrency?: string }} ctx
+ * @returns {Promise<null | { intentId: string, amount: string, currency: string, paidAt: Date }>}
+ */
+export async function verifyPaid(req, { agentId, skill, expectedAmount, expectedCurrency }) {
+ const intentId = (req.headers['x-payment-intent'] || '').toString().trim();
+ if (!intentId) return null;
+
+ const [row] = await sql`
+ select id, agent_id, currency_mint, amount, status, paid_at, payload, end_time
+ from agent_payment_intents
+ where id = ${intentId} and agent_id = ${agentId}
+ limit 1
+ `;
+ if (!row) return null;
+ if (row.status !== 'paid') return null;
+ if (row.end_time && new Date(row.end_time).getTime() < Date.now()) return null;
+
+ if (expectedAmount && String(row.amount) !== String(expectedAmount)) return null;
+ if (expectedCurrency && row.currency_mint !== expectedCurrency) return null;
+
+ // Bind the intent to the requested skill if the caller stored it. Skill
+ // metadata lives in payload — older intents may not have it, in which
+ // case we treat the absence as "any skill".
+ const intentSkill = row.payload?.skill;
+ if (intentSkill && intentSkill !== skill) return null;
+
+ return {
+ intentId: row.id,
+ amount: row.amount,
+ currency: row.currency_mint,
+ paidAt: row.paid_at,
+ };
+}
+
+/**
+ * Convenience: complete a paid call. Marks the intent as `consumed` so it
+ * can't be reused — paid intents are single-shot per spec.
+ */
+export async function consumeIntent(intentId) {
+ await sql`
+ update agent_payment_intents
+ set status = 'consumed'
+ where id = ${intentId} and status = 'paid'
+ `;
+}
+
+/**
+ * Emit a structured response that mixes 402 manifests with normal JSON when
+ * the caller advertises support via `Accept: application/x402+json`.
+ * Currently a no-op alias for emit402 — kept as a hook for future content
+ * negotiation.
+ */
+export const emit402Negotiated = emit402;
+
+/**
+ * Helper: respond with the manifest only (no 402), for prefetch/discovery
+ * via `GET /api/agents/:id/x402/:skill/manifest`.
+ */
+export function manifestOnly(res, opts) {
+ const validUntil = Math.floor(Date.now() / 1000) + (opts.validForSec || 900);
+ const payments = opts.agent.meta?.payments || opts.agent.payments;
+ return json(res, 200, {
+ version: X402_VERSION,
+ kind: 'agent-skill',
+ agent_id: opts.agent.id,
+ skill: opts.skill,
+ amount: String(opts.amount),
+ currency: opts.currency,
+ recipient: payments?.receiver,
+ valid_until: validUntil,
+ intent_url: '/api/agents/payments/pay-prep',
+ verify_url: '/api/agents/payments/pay-confirm',
+ retry_with_header: 'x-payment-intent',
+ });
+}
diff --git a/api/agents/x402/invoke.js b/api/agents/x402/invoke.js
new file mode 100644
index 000000000..8ae594b51
--- /dev/null
+++ b/api/agents/x402/invoke.js
@@ -0,0 +1,125 @@
+/**
+ * POST /api/agents/x402/invoke
+ *
+ * Reference paid-skill endpoint. Demonstrates the x402 flow end-to-end:
+ *
+ * 1. Caller POSTs { agent_id, skill, args } with no payment header.
+ * 2. We compute the price for (agent, skill) from the agent's skill
+ * manifest (defaulting to a flat per-call price), and emit 402 with
+ * the canonical manifest.
+ * 3. Caller pays via the payments endpoints, retries with
+ * `x-payment-intent: <intent_id>`. We verify, mark the intent
+ * consumed, then dispatch the actual skill.
+ *
+ * Skill dispatch is deliberately stub-like — production paid skills will
+ * register handlers via `registerPaidSkill('summarize', handler)` once we
+ * wire this into the runtime. For now: an `echo` skill returns the args.
+ */
+
+import { z } from 'zod';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+import { emit402, verifyPaid, consumeIntent } from '../../_lib/x402.js';
+
+const bodySchema = z.object({
+ agent_id: z.string().min(1).max(80),
+ skill: z.string().min(1).max(64),
+ args: z.record(z.any()).default({}),
+});
+
+// ── Skill registry (stub) ──────────────────────────────────────────────────
+//
+// In a future runtime hook, these are registered via the agent's skill
+// manifest; here we hardcode a single demo skill so the e2e flow is real.
+
+const HANDLERS = {
+ echo: async (args) => ({ ok: true, echoed: args }),
+};
+
+function priceFor(agent, skill) {
+ // Look up per-skill price from agent.meta.skill_prices, fall back to a
+ // flat per-call default declared at meta.payments.default_price.
+ const prices = agent.meta?.skill_prices || {};
+ const defaultPrice = agent.meta?.payments?.default_price;
+ const fromMap = prices[skill];
+ if (fromMap?.amount && fromMap?.currency) return fromMap;
+ if (defaultPrice?.amount && defaultPrice?.currency) return defaultPrice;
+ // Hard default: 0.01 USDC = 10000 raw (6 decimals). Demo-only.
+ const cluster = agent.meta?.payments?.cluster || 'mainnet';
+ return {
+ amount: '10000',
+ currency:
+ cluster === 'devnet'
+ ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'
+ : 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ };
+}
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId, scope: bearer.scope };
+ return null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a bearer token');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(bodySchema, await readJson(req));
+
+ const [agent] = await sql`
+ select id, name, meta from agent_identities
+ where id = ${body.agent_id} and deleted_at is null
+ limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (!agent.meta?.payments?.configured) {
+ return error(res, 409, 'precondition_failed', 'agent has not enabled payments');
+ }
+ if (!HANDLERS[body.skill]) {
+ return error(res, 404, 'unknown_skill', `skill "${body.skill}" is not registered`);
+ }
+
+ const price = priceFor(agent, body.skill);
+
+ // Verify payment header — emit 402 if missing or invalid.
+ const paid = await verifyPaid(req, {
+ agentId: agent.id,
+ skill: body.skill,
+ expectedAmount: price.amount,
+ expectedCurrency: price.currency,
+ });
+ if (!paid) {
+ return emit402(res, {
+ agent,
+ skill: body.skill,
+ amount: price.amount,
+ currency: price.currency,
+ });
+ }
+
+ // Single-shot: consume the intent before dispatch so a retry of the same
+ // intent fails. (Skill failures don't refund — the intent paid for the
+ // attempt, not the success. Future work: idempotency keys for retries.)
+ await consumeIntent(paid.intentId);
+
+ const result = await HANDLERS[body.skill](body.args, { agent, caller: auth });
+ return json(res, 200, {
+ ok: true,
+ intent_id: paid.intentId,
+ amount: paid.amount,
+ currency: paid.currency,
+ result,
+ });
+});
diff --git a/api/agents/x402/manifest.js b/api/agents/x402/manifest.js
new file mode 100644
index 000000000..f56b18865
--- /dev/null
+++ b/api/agents/x402/manifest.js
@@ -0,0 +1,61 @@
+/**
+ * GET /api/agents/x402/manifest?agent_id=...&skill=...
+ *
+ * Returns the x402 payment manifest for a given (agent, skill) pair *without*
+ * issuing 402. Useful for x402 clients that want to prefetch the price before
+ * making the real call, and for discovery tooling (x402scan, etc).
+ *
+ * Public — anyone can read pricing.
+ */
+
+import { z } from 'zod';
+import { sql } from '../../_lib/db.js';
+import { cors, json, method, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { manifestOnly } from '../../_lib/x402.js';
+
+const querySchema = z.object({
+ agent_id: z.string().min(1).max(80),
+ skill: z.string().min(1).max(64),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const q = querySchema.parse({
+ agent_id: url.searchParams.get('agent_id'),
+ skill: url.searchParams.get('skill'),
+ });
+
+ const [agent] = await sql`
+ select id, name, meta from agent_identities
+ where id = ${q.agent_id} and deleted_at is null limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (!agent.meta?.payments?.configured) {
+ return error(res, 409, 'no_payments', 'agent has not enabled payments');
+ }
+
+ // Same pricing rule as invoke.js — keep in sync.
+ const cluster = agent.meta.payments.cluster || 'mainnet';
+ const fallbackCurrency =
+ cluster === 'devnet'
+ ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'
+ : 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+ const prices = agent.meta.skill_prices || {};
+ const def = agent.meta.payments.default_price;
+ const price =
+ prices[q.skill] || def || { amount: '10000', currency: fallbackCurrency };
+
+ return manifestOnly(res, {
+ agent,
+ skill: q.skill,
+ amount: price.amount,
+ currency: price.currency,
+ });
+});
diff --git a/api/pump/relay-delegations.js b/api/pump/relay-delegations.js
new file mode 100644
index 000000000..26375541b
--- /dev/null
+++ b/api/pump/relay-delegations.js
@@ -0,0 +1,32 @@
+// GET /api/pump/relay-delegations
+// Lists the user's active relay delegations.
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rows = await sql`
+ select id, agent_id, relayer_pubkey, user_wallet,
+ max_sol_lamports, spent_sol_lamports,
+ direction_filter, mint_filter, network,
+ expires_at, created_at
+ from pump_trade_delegations
+ where user_id=${user.id} and revoked_at is null and expires_at > now()
+ order by created_at desc
+ `;
+
+ return json(res, 200, {
+ data: rows.map((r) => ({
+ ...r,
+ max_sol_lamports: r.max_sol_lamports.toString(),
+ spent_sol_lamports: r.spent_sol_lamports.toString(),
+ })),
+ });
+});
diff --git a/api/pump/relayer-info.js b/api/pump/relayer-info.js
new file mode 100644
index 000000000..3d1ac1924
--- /dev/null
+++ b/api/pump/relayer-info.js
@@ -0,0 +1,33 @@
+// GET /api/pump/relayer-info
+//
+// Public endpoint: returns the server relayer pubkey so clients can build
+// the SIWS authorization message. No auth — pubkey is non-sensitive.
+
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { relayerPubkeyString } from '../_lib/pump-relayer.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ try {
+ const pubkey = await relayerPubkeyString();
+ return json(
+ res,
+ 200,
+ {
+ relayer_pubkey: pubkey,
+ siws_template: [
+ `Authorize three.ws relayer ${pubkey} to trade pump.fun on my behalf.`,
+ 'max=<SOL>',
+ 'expires=<ISO8601>',
+ 'mint=<optional pubkey>',
+ 'direction=<buy|sell|both>',
+ ].join('\n'),
+ },
+ { 'cache-control': 'public, max-age=60', 'access-control-allow-origin': '*' },
+ );
+ } catch (e) {
+ return error(res, e.status || 503, e.code || 'not_configured', e.message);
+ }
+});
diff --git a/package.json b/package.json
index 6f0e2beb0..548e73750 100644
--- a/package.json
+++ b/package.json
@@ -54,7 +54,11 @@
"format": "prettier --write .",
"deploy": "npm run build:all && vercel --local-config vercel.json --prod",
"postversion": "git push && git push --tags",
- "validate:cards": "node scripts/validate-agent-cards.mjs"
+ "validate:cards": "node scripts/validate-agent-cards.mjs",
+ "db:migrate": "node scripts/apply-migrations.mjs --apply",
+ "db:status": "node scripts/apply-migrations.mjs",
+ "pump:keygen": "node scripts/pump-relayer-keygen.mjs",
+ "pump:smoke": "node scripts/pumpfun-lifecycle-smoke.js"
},
"dependencies": {
"@avaturn/sdk": "^1.1.4",
diff --git a/public/dashboard/index.html b/public/dashboard/index.html
index fdd70c0ff..b46a7a43b 100644
--- a/public/dashboard/index.html
+++ b/public/dashboard/index.html
@@ -1134,6 +1134,7 @@
<a href="#account" data-tab="account">Account</a>
<a href="/dashboard/wallets">Wallets</a>
<a href="/dashboard/agent-pumpfun">Agent · Pump.fun</a>
+ <a href="/dashboard/pump-relay">Pump · Relay trading</a>
<a href="/discover" title="Browse on-chain agents across every supported chain"
>Discover on-chain ↗</a
>
diff --git a/public/dashboard/pump-relay.html b/public/dashboard/pump-relay.html
new file mode 100644
index 000000000..48aef2686
--- /dev/null
+++ b/public/dashboard/pump-relay.html
@@ -0,0 +1,242 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Pump.fun relay · Dashboard · three.ws</title>
+ <link rel="icon" href="/favicon.ico" />
+ <style>
+ :root {
+ color-scheme: dark;
+ --accent: #6a5cff;
+ --ok: #4ade80;
+ --err: #f87171;
+ --border: #22222e;
+ --bg: #0b0b10;
+ --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; }
+ </style>
+ </head>
+ <body>
+ <header>
+ <div><a href="/dashboard">← dashboard</a></div>
+ <div class="muted">pump.fun relay</div>
+ </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>
+
+ <div class="panel">
+ <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>
+ <div class="row">
+ <div>
+ <label>Wallet (base58)</label>
+ <input id="wallet" placeholder="paste your Solana wallet pubkey" />
+ </div>
+ <div>
+ <label>Network</label>
+ <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" />
+ </div>
+ <div>
+ <label>TTL (hours)</label>
+ <input id="ttl-hours" type="number" min="1" max="720" value="24" />
+ </div>
+ </div>
+ <div class="row">
+ <div>
+ <label>Direction</label>
+ <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">
+ <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>
+
+ <div class="panel">
+ <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';
+
+ const $ = (id) => document.getElementById(id);
+ let RELAYER_PUBKEY = null;
+
+ async function loadRelayerInfo() {
+ try {
+ 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>`;
+ } else {
+ $('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>`;
+ }
+ }
+
+ async function loadDelegations() {
+ try {
+ 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>';
+ return;
+ }
+ const rows = data.data
+ .map(
+ (d) => `
+ <tr>
+ <td class="mono" style="font-size:12px">${d.id.slice(0, 8)}…</td>
+ <td>${d.network}</td>
+ <td>${(Number(d.max_sol_lamports) / 1e9).toFixed(3)} SOL</td>
+ <td>${(Number(d.spent_sol_lamports) / 1e9).toFixed(3)}</td>
+ <td>${d.direction_filter}</td>
+ <td>${new Date(d.expires_at).toLocaleString()}</td>
+ <td><button data-id="${d.id}" class="ghost revoke">Revoke</button></td>
+ </tr>
+ `,
+ )
+ .join('');
+ $('delegations').innerHTML = `
+ <table>
+ <thead><tr><th>id</th><th>net</th><th>cap</th><th>spent</th><th>dir</th><th>expires</th><th></th></tr></thead>
+ <tbody>${rows}</tbody>
+ </table>
+ `;
+ $('delegations')
+ .querySelectorAll('button.revoke')
+ .forEach((b) => b.addEventListener('click', () => revoke(b.dataset.id)));
+ } catch (e) {
+ $('delegations').innerHTML = `<span class="err">${e.message}</span>`;
+ }
+ }
+
+ async function authorize() {
+ const btn = $('authorize');
+ btn.disabled = true;
+ $('status').textContent = '';
+ $('status').className = 'muted';
+ try {
+ if (!RELAYER_PUBKEY) throw new Error('relayer not loaded');
+ const wallet = $('wallet').value.trim();
+ if (!wallet) throw new Error('wallet required');
+ const maxSol = Number($('max-sol').value);
+ const network = $('network').value;
+ const direction = $('direction').value;
+ const mintFilter = $('mint-filter').value.trim() || null;
+ const ttlHours = Number($('ttl-hours').value);
+
+ const { message } = buildRelayAuthorizationMessage({
+ userWallet: wallet,
+ relayerPubkey: RELAYER_PUBKEY,
+ maxSol,
+ mint: mintFilter,
+ direction,
+ network,
+ ttlHours,
+ });
+
+ const provider = window.solana || window.phantom?.solana;
+ if (!provider) throw new Error('No Solana wallet detected (install Phantom).');
+ if (!provider.isConnected) await provider.connect();
+ const encoded = new TextEncoder().encode(message);
+ const { signature } = await provider.signMessage(encoded, 'utf8');
+ const bs58 = await import('https://esm.sh/bs58@5');
+ const sigB58 = bs58.default.encode(signature);
+
+ const res = await fetch('/api/pump/relay-authorize', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ user_wallet: wallet,
+ max_sol: maxSol,
+ direction_filter: direction,
+ mint_filter: mintFilter || undefined,
+ network,
+ ttl_hours: ttlHours,
+ siws_message: message,
+ siws_signature: sigB58,
+ }),
+ });
+ const j = await res.json();
+ if (!res.ok) throw new Error(j.error_description || j.error || `${res.status}`);
+ $('status').textContent = `Authorized · delegation ${j.delegation_id}`;
+ $('status').className = 'ok';
+ await loadDelegations();
+ } catch (e) {
+ $('status').textContent = `Error: ${e.message}`;
+ $('status').className = 'err';
+ } finally {
+ btn.disabled = false;
+ }
+ }
+
+ async function revoke(id) {
+ if (!confirm('Revoke this delegation?')) return;
+ const res = await fetch('/api/pump/relay-revoke', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ delegation_id: id }),
+ });
+ if (!res.ok) {
+ const j = await res.json().catch(() => ({}));
+ alert(`Revoke failed: ${j.error_description || res.status}`);
+ return;
+ }
+ await loadDelegations();
+ }
+
+ $('authorize').addEventListener('click', authorize);
+ $('refresh').addEventListener('click', loadDelegations);
+
+ loadRelayerInfo();
+ loadDelegations();
+ </script>
+ </body>
+</html>
diff --git a/scripts/apply-migrations.mjs b/scripts/apply-migrations.mjs
index 74cb8bc9b..4bb2f2fb3 100755
--- a/scripts/apply-migrations.mjs
+++ b/scripts/apply-migrations.mjs
@@ -20,7 +20,9 @@ import { readFile, readdir } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
-import { neon } from '@neondatabase/serverless';
+import { neon, Pool, neonConfig } from '@neondatabase/serverless';
+import ws from 'ws';
+neonConfig.webSocketConstructor = ws;
const HERE = path.dirname(fileURLToPath(import.meta.url));
const MIG_DIR = path.resolve(HERE, '..', 'api', '_lib', 'migrations');
@@ -36,6 +38,7 @@ if (!process.env.DATABASE_URL) {
}
const sql = neon(process.env.DATABASE_URL);
+const pool = new Pool({ connectionString: process.env.DATABASE_URL });
async function ensureTrackingTable() {
await sql`
@@ -71,13 +74,8 @@ async function applyOne({ fname, body, hash }) {
// single multi-statement string. We fall back to splitting on bare ';' at
// line ends; the migrations in this repo are written to be split-safe
// (no procedural blocks, no embedded semicolons in literals).
- const stmts = body
- .split(/;\s*$/m)
- .map((s) => s.trim())
- .filter((s) => s && !/^--/.test(s));
- for (const stmt of stmts) {
- await sql.query(stmt);
- }
+ // Use websocket Pool for multi-statement execution (HTTP driver is single-stmt only).
+ await pool.query(body);
await sql`
insert into schema_migrations (filename, sha256)
values (${fname}, ${hash})
@@ -139,7 +137,9 @@ function maskUrl(url) {
}
}
-main().catch((e) => {
- console.error('FAILED:', e.message);
- process.exit(1);
-});
+main()
+ .catch((e) => {
+ console.error('FAILED:', e.message);
+ process.exitCode = 1;
+ })
+ .finally(() => pool.end());
diff --git a/scripts/pump-relayer-keygen.mjs b/scripts/pump-relayer-keygen.mjs
new file mode 100644
index 000000000..d3ba45261
--- /dev/null
+++ b/scripts/pump-relayer-keygen.mjs
@@ -0,0 +1,26 @@
+#!/usr/bin/env node
+// Generate a Solana keypair for the pump.fun trade relayer.
+// Prints the base64-encoded secret key + base58 pubkey.
+//
+// Usage:
+// node scripts/pump-relayer-keygen.mjs
+//
+// Then set in your env (Vercel project / .env.local):
+// PUMP_RELAYER_SECRET_KEY_B64=<the base64 string>
+//
+// Fund the printed pubkey with a small amount of SOL (mainnet) or use
+// `solana airdrop 1 <pubkey> --url devnet` for devnet testing.
+
+import { Keypair } from '@solana/web3.js';
+
+const kp = Keypair.generate();
+const secretB64 = Buffer.from(kp.secretKey).toString('base64');
+
+console.log('Pump relayer keypair (KEEP SECRET KEY PRIVATE):');
+console.log(' pubkey: ', kp.publicKey.toBase58());
+console.log(' secret base64: ', secretB64);
+console.log('');
+console.log('Add to env:');
+console.log(` PUMP_RELAYER_SECRET_KEY_B64='${secretB64}'`);
+console.log('');
+console.log('Fund the pubkey with SOL before serving relay-trade requests.');
diff --git a/src/agent-home.js b/src/agent-home.js
index 40e4a4f01..d4b88a2e1 100644
--- a/src/agent-home.js
+++ b/src/agent-home.js
@@ -11,6 +11,7 @@
import { ACTION_TYPES } from './agent-protocol.js';
import { MEMORY_TYPES } from './agent-memory.js';
import { mountPumpFunCard } from './agent-home-pumpfun.js';
+import { mountAgentSolanaWalletCard } from './agent-solana-wallet.js';
const ACTION_ICONS = {
[ACTION_TYPES.SPEAK]: '💬',
@@ -165,8 +166,10 @@ export class AgentHome {
this.container.appendChild(panel);
this._panel = panel;
- // Pump.fun card — only meaningful for Solana-registered agents.
- if (this.identity?.meta?.chain_type === 'solana' || this.identity?.solana_address) {
+ let _pumpMounted = false;
+ const mountPumpIfReady = () => {
+ if (_pumpMounted) return;
+ if (!(this.identity?.meta?.chain_type === 'solana' || this.identity?.solana_address)) return;
try {
const skills =
this.skills ||
@@ -185,11 +188,29 @@ export class AgentHome {
memory,
protocol: this.protocol,
});
+ _pumpMounted = true;
+ } catch {
+ /* card is optional */
+ }
+ };
+
+ // Solana wallet card — owner only. Lets the user provision a random
+ // or vanity Solana wallet for the agent. On success, lazy-mount the
+ // pump.fun card if it wasn't already mounted.
+ if (this.identity?.id && this.identity?.isOwner !== false) {
+ try {
+ mountAgentSolanaWalletCard({
+ panel,
+ identity: this.identity,
+ onProvisioned: () => mountPumpIfReady(),
+ });
} catch {
/* card is optional */
}
}
+ mountPumpIfReady();
+
// Permissions manage panel — lazy load; degrades gracefully if unauthenticated
const agentId = this.identity.id;
if (agentId) {
diff --git a/src/agent-skills-pumpfun.js b/src/agent-skills-pumpfun.js
index 5bd3745c4..890ddb7e8 100644
--- a/src/agent-skills-pumpfun.js
+++ b/src/agent-skills-pumpfun.js
@@ -153,6 +153,56 @@ export async function runServerFlow({
return { signature: sig, prep, confirm: confirmJson };
}
+/**
+ * Build the SIWS message that authorizes the three.ws relayer to trade
+ * pump.fun on the user's behalf. Caller must sign + POST to /api/pump/relay-authorize.
+ *
+ * @param {Object} opts
+ * @param {string} opts.userWallet — base58 pubkey signing the authz
+ * @param {string} opts.relayerPubkey — server pubkey from /api/pump/relayer-info
+ * @param {number} opts.maxSol — cumulative spend cap (SOL)
+ * @param {string} [opts.mint] — optional lock to a single mint
+ * @param {('buy'|'sell'|'both')} [opts.direction='both']
+ * @param {string} [opts.network='mainnet']
+ * @param {number} [opts.ttlHours=24]
+ * @param {string} [opts.domain] — defaults to current page host
+ * @returns {{ message: string, nonce: string, expiresAt: string }}
+ */
+export function buildRelayAuthorizationMessage({
+ userWallet,
+ relayerPubkey,
+ maxSol,
+ mint,
+ direction = 'both',
+ network = 'mainnet',
+ ttlHours = 24,
+ domain = typeof location !== 'undefined' ? location.host : 'three.ws',
+}) {
+ 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}\n` +
+ `expires=${expiresAt}\n` +
+ `direction=${direction}` +
+ (mint ? `\nmint=${mint}` : '');
+ const message = [
+ `${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');
+ return { message, nonce, expiresAt };
+}
+
function deriveSymbol(name) {
return (
String(name || 'AGENT')
diff --git a/src/agent-solana-wallet.js b/src/agent-solana-wallet.js
new file mode 100644
index 000000000..a9450c288
--- /dev/null
+++ b/src/agent-solana-wallet.js
@@ -0,0 +1,259 @@
+/**
+ * Agent Solana wallet — provisioning UI + client.
+ *
+ * Owner-only card on the agent home panel. Two flows:
+ * 1. Random wallet → POST /api/agents/:id/solana with empty body.
+ * 2. Vanity wallet → grind in-browser (or accept a CLI-ground keypair
+ * via the paste field) then POST { secret_key,
+ * vanity_prefix }. Server verifies and stores the
+ * encrypted secret.
+ *
+ * Existing wallets are non-destructive: a "Replace" button calls DELETE first.
+ */
+
+import { openVanityModal } from './erc8004/vanity-modal.js';
+import { grindVanity } from './solana/vanity/grinder.js';
+
+const ENDPOINT = (id) => `/api/agents/${encodeURIComponent(id)}/solana`;
+
+/**
+ * Provision (or replace) the agent's Solana wallet.
+ *
+ * @param {object} opts
+ * @param {string} opts.agentId
+ * @param {string} [opts.vanityPrefix] — base58 prefix to grind for.
+ * @param {Uint8Array} [opts.preGround] — pre-ground 64-byte secret key.
+ * @param {AbortSignal} [opts.signal]
+ * @param {(p: { rate: number, attempts: number, eta: string }) => void} [opts.onProgress]
+ * @returns {Promise<{ address: string, source: string, vanity_prefix: string|null }>}
+ */
+export async function provisionAgentSolanaWallet({
+ agentId,
+ vanityPrefix = '',
+ preGround = null,
+ signal,
+ onProgress,
+} = {}) {
+ if (!agentId) throw new Error('agentId required');
+
+ let body = null;
+ if (preGround) {
+ body = {
+ secret_key: Array.from(preGround),
+ ...(vanityPrefix ? { vanity_prefix: vanityPrefix } : {}),
+ };
+ } else if (vanityPrefix) {
+ const ground = await grindVanity({ prefix: vanityPrefix, signal, onProgress });
+ body = {
+ secret_key: Array.from(ground.secretKey),
+ vanity_prefix: vanityPrefix,
+ };
+ }
+
+ const resp = await fetch(ENDPOINT(agentId), {
+ method: 'POST',
+ credentials: 'include',
+ headers: body ? { 'Content-Type': 'application/json' } : {},
+ body: body ? JSON.stringify(body) : undefined,
+ signal,
+ });
+ const json = await resp.json().catch(() => ({}));
+ if (!resp.ok) {
+ const msg = json?.error?.message || json?.message || `provision failed (${resp.status})`;
+ const err = new Error(msg);
+ err.status = resp.status;
+ throw err;
+ }
+ return json.data;
+}
+
+export async function deleteAgentSolanaWallet(agentId) {
+ const resp = await fetch(ENDPOINT(agentId), { method: 'DELETE', credentials: 'include' });
+ if (!resp.ok) {
+ const j = await resp.json().catch(() => ({}));
+ throw new Error(j?.error?.message || `delete failed (${resp.status})`);
+ }
+}
+
+// ── UI card ─────────────────────────────────────────────────────────────────
+
+const STYLE = `
+.agent-sol-wallet { border: 1px solid #e6e6ea; border-radius: 10px; padding: .85rem 1rem; margin: .85rem 0; font: 13px/1.4 system-ui, sans-serif; background: #fff; }
+.agent-sol-wallet h3 { margin: 0 0 .25rem; font-size: .95rem; font-weight: 600; color: #1a1a1a; }
+.agent-sol-wallet .sub { color: #666; font-size: .78rem; margin: 0 0 .65rem; }
+.agent-sol-wallet .addr { font-family: ui-monospace, monospace; font-size: .8rem; background: #f7f7f8; padding: .4rem .55rem; border-radius: 5px; word-break: break-all; }
+.agent-sol-wallet .addr .pfx { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; padding: 0 2px; border-radius: 2px; font-weight: 600; }
+.agent-sol-wallet .row { display: flex; gap: .5rem; align-items: center; margin-top: .65rem; flex-wrap: wrap; }
+.agent-sol-wallet button { font: inherit; padding: .4rem .8rem; border-radius: 6px; border: 1px solid #ccc; background: #fff; cursor: pointer; }
+.agent-sol-wallet button.primary { background: #111; color: #fff; border-color: #111; }
+.agent-sol-wallet button:disabled { opacity: .5; cursor: not-allowed; }
+.agent-sol-wallet .progress { font-size: .75rem; color: #555; margin-top: .55rem; font-family: ui-monospace, monospace; }
+.agent-sol-wallet .err { color: #b71c1c; font-size: .75rem; margin-top: .5rem; }
+.agent-sol-wallet .src { font-size: .7rem; color: #888; margin-left: .35rem; }
+`;
+
+let _styleInjected = false;
+function _injectStyle() {
+ if (_styleInjected || typeof document === 'undefined') return;
+ const tag = document.createElement('style');
+ tag.id = 'agent-sol-wallet-style';
+ tag.textContent = STYLE;
+ document.head.appendChild(tag);
+ _styleInjected = true;
+}
+
+function _esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+ })[c]);
+}
+
+/**
+ * Mount the wallet card into the agent home panel.
+ *
+ * @param {object} opts
+ * @param {HTMLElement} opts.panel
+ * @param {{ id: string, name?: string, meta?: object, solana_address?: string }} opts.identity
+ * @param {(data: { address: string, vanity_prefix: string|null, source: string }) => void} [opts.onProvisioned]
+ */
+export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {
+ if (!panel || !identity?.id) return null;
+ _injectStyle();
+
+ const root = document.createElement('section');
+ root.className = 'agent-sol-wallet';
+ panel.appendChild(root);
+
+ let state = {
+ address: identity.solana_address || identity.meta?.solana_address || null,
+ vanityPrefix: identity.meta?.solana_vanity_prefix || null,
+ source: identity.meta?.solana_wallet_source || null,
+ busy: false,
+ progress: null,
+ err: null,
+ };
+ let abort = null;
+
+ function render() {
+ if (state.address) {
+ const pfx = state.vanityPrefix || '';
+ const rest = state.address.slice(pfx.length);
+ root.innerHTML = `
+ <h3>Solana wallet${state.source ? `<span class="src">· ${_esc(state.source)}</span>` : ''}</h3>
+ <div class="addr"><span class="pfx">${_esc(pfx)}</span>${_esc(rest)}</div>
+ <div class="row">
+ <button data-act="copy">Copy</button>
+ <button data-act="replace">Replace</button>
+ </div>
+ ${state.err ? `<div class="err">${_esc(state.err)}</div>` : ''}
+ `;
+ root.querySelector('[data-act="copy"]').addEventListener('click', () => {
+ navigator.clipboard?.writeText(state.address).catch(() => {});
+ });
+ root.querySelector('[data-act="replace"]').addEventListener('click', onReplace);
+ return;
+ }
+
+ root.innerHTML = `
+ <h3>Solana wallet</h3>
+ <p class="sub">Provision a wallet for this agent. Optionally pick a vanity prefix.</p>
+ <div class="row">
+ <button class="primary" data-act="vanity" ${state.busy ? 'disabled' : ''}>
+ ${state.busy ? 'Working…' : 'Choose vanity prefix'}
+ </button>
+ <button data-act="random" ${state.busy ? 'disabled' : ''}>Random</button>
+ </div>
+ ${state.progress ? `<div class="progress">grinding… ${_esc(formatRate(state.progress.rate))}/s · eta ${_esc(state.progress.eta)} <button data-act="cancel">cancel</button></div>` : ''}
+ ${state.err ? `<div class="err">${_esc(state.err)}</div>` : ''}
+ `;
+ root.querySelector('[data-act="vanity"]')?.addEventListener('click', onVanity);
+ root.querySelector('[data-act="random"]')?.addEventListener('click', onRandom);
+ root.querySelector('[data-act="cancel"]')?.addEventListener('click', () => abort?.abort());
+ }
+
+ async function onRandom() {
+ state.busy = true; state.err = null; render();
+ try {
+ const data = await provisionAgentSolanaWallet({ agentId: identity.id });
+ state.address = data.address;
+ state.vanityPrefix = data.vanity_prefix || null;
+ state.source = data.source || 'generated';
+ _propagate(identity, data);
+ onProvisioned?.(data);
+ } catch (e) {
+ state.err = e.message;
+ } finally {
+ state.busy = false; render();
+ }
+ }
+
+ async function onVanity() {
+ const choice = await openVanityModal({
+ agentName: identity.name || '',
+ initial: state.vanityPrefix || '',
+ });
+ if (choice == null || choice === '') return; // dismissed or "skip"
+
+ const prefix = typeof choice === 'string' ? choice : choice.prefix;
+ const preGround = typeof choice === 'object' ? choice.secretKey : null;
+
+ state.busy = true; state.err = null; state.progress = null; render();
+ abort = new AbortController();
+ try {
+ const data = await provisionAgentSolanaWallet({
+ agentId: identity.id,
+ vanityPrefix: prefix,
+ preGround,
+ signal: abort.signal,
+ onProgress: (p) => { state.progress = p; render(); },
+ });
+ state.address = data.address;
+ state.vanityPrefix = data.vanity_prefix || prefix || null;
+ state.source = data.source || 'imported_vanity';
+ state.progress = null;
+ _propagate(identity, data);
+ onProvisioned?.(data);
+ } catch (e) {
+ state.err = e.name === 'AbortError' ? 'cancelled' : e.message;
+ state.progress = null;
+ } finally {
+ state.busy = false; abort = null; render();
+ }
+ }
+
+ async function onReplace() {
+ if (!confirm('Replace the existing Solana wallet? The old key will be discarded — funds will be lost if not transferred first.')) return;
+ state.busy = true; state.err = null; render();
+ try {
+ await deleteAgentSolanaWallet(identity.id);
+ state.address = null;
+ state.vanityPrefix = null;
+ state.source = null;
+ } catch (e) {
+ state.err = e.message;
+ } finally {
+ state.busy = false; render();
+ }
+ }
+
+ render();
+ return { destroy: () => root.remove() };
+}
+
+function _propagate(identity, data) {
+ if (!identity || !data) return;
+ identity.solana_address = data.address;
+ identity.meta = {
+ ...(identity.meta || {}),
+ solana_address: data.address,
+ solana_vanity_prefix: data.vanity_prefix || null,
+ solana_wallet_source: data.source || null,
+ };
+}
+
+function formatRate(n) {
+ if (!n) return '0';
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
+ return Math.round(n).toString();
+}
diff --git a/src/onchain/vanity-wallet-button.js b/src/onchain/vanity-wallet-button.js
new file mode 100644
index 000000000..20c1035a3
--- /dev/null
+++ b/src/onchain/vanity-wallet-button.js
@@ -0,0 +1,209 @@
+/**
+ * VanityWalletButton — provisions a custodial Solana wallet for the agent
+ * with a user-chosen vanity prefix. Owner-only.
+ *
+ * • If the agent already has a custodial wallet → renders an address chip.
+ * • Otherwise renders "Create vanity wallet". Click opens a modal with a
+ * prefix input, live difficulty estimate, and grind progress.
+ * • Reads agent.meta.solana_address (and the existing legacy field paths)
+ * to detect whether a wallet is already provisioned.
+ */
+
+import {
+ provisionVanityForAgent,
+ validatePattern,
+ estimateAttempts,
+ formatTimeEstimate,
+} from './vanity/index.js';
+
+const RATE_PER_CORE = 5000;
+
+function _esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+ })[c]);
+}
+
+function _coreCount() {
+ if (typeof navigator === 'undefined') return 4;
+ return Math.max(1, Math.min(navigator.hardwareConcurrency || 4, 8));
+}
+
+export class VanityWalletButton {
+ constructor({ agent, container }) {
+ this._agent = agent;
+ this._container = container;
+ this._root = null;
+ this._abort = null;
+ }
+
+ mount() {
+ this._root = document.createElement('div');
+ this._root.className = 'vanity-wallet-root';
+ this._container.appendChild(this._root);
+ this._render();
+ }
+
+ unmount() {
+ try {
+ this._abort?.abort();
+ } catch {
+ /* ignore */
+ }
+ this._root?.remove();
+ this._root = null;
+ }
+
+ _currentAddress() {
+ // Prefer the new top-level field; fall back to legacy meta paths.
+ return (
+ this._agent.solana_address ||
+ this._agent.meta?.solana_address ||
+ this._agent.meta?.solana?.address ||
+ null
+ );
+ }
+
+ _render() {
+ if (!this._root) return;
+ const addr = this._currentAddress();
+ if (addr) return this._renderChip(addr);
+ this._renderCreateButton();
+ }
+
+ _renderCreateButton() {
+ this._root.innerHTML = `
+ <button class="vanity-wallet-btn" title="Create a custodial Solana wallet for this agent with a chosen prefix">
+ &#x2728; Create vanity wallet
+ </button>
+ `;
+ this._root.querySelector('.vanity-wallet-btn').addEventListener('click', () => this._openModal());
+ }
+
+ _renderChip(addr) {
+ const short = `${addr.slice(0, 6)}…${addr.slice(-4)}`;
+ this._root.innerHTML = `
+ <a class="vanity-wallet-chip" href="https://solscan.io/account/${_esc(addr)}" target="_blank" rel="noopener noreferrer"
+ aria-label="View agent wallet on Solscan">
+ &#x1F4BC; ${_esc(short)} &middot; agent wallet
+ </a>
+ `;
+ }
+
+ _renderProgress({ attempts, rate, eta }) {
+ this._root.innerHTML = `
+ <div class="vanity-wallet-progress" role="status" aria-live="polite">
+ <span>Grinding… ${attempts.toLocaleString()} attempts</span>
+ <span>${rate.toLocaleString()} k/s</span>
+ <span>~${_esc(eta)} remaining</span>
+ <button class="vanity-wallet-cancel">Cancel</button>
+ </div>
+ `;
+ this._root.querySelector('.vanity-wallet-cancel').addEventListener('click', () => {
+ try {
+ this._abort?.abort();
+ } catch {
+ /* ignore */
+ }
+ });
+ }
+
+ _renderError(msg) {
+ this._root.innerHTML = `
+ <div class="vanity-wallet-error" role="alert">
+ <span>${_esc(msg)}</span>
+ <button class="vanity-wallet-retry">Try again</button>
+ </div>
+ `;
+ this._root.querySelector('.vanity-wallet-retry').addEventListener('click', () => this._render());
+ }
+
+ _openModal() {
+ const overlay = document.createElement('div');
+ overlay.className = 'vanity-wallet-modal-overlay';
+ overlay.innerHTML = `
+ <div class="vanity-wallet-modal" role="dialog" aria-label="Create vanity wallet">
+ <h3>Create vanity wallet for ${_esc(this._agent.name || 'agent')}</h3>
+ <p>Generate a Solana keypair whose address starts with a chosen prefix. The secret key is encrypted server-side and never leaves the server after provisioning.</p>
+ <form class="vanity-wallet-form">
+ <label>Prefix (1–6 base58 chars)
+ <input name="prefix" maxlength="6" required value="AGNT" pattern="[1-9A-HJ-NP-Za-km-z]+" />
+ </label>
+ <label>
+ <input type="checkbox" name="ignore_case" />
+ Ignore case (faster)
+ </label>
+ <div class="vanity-wallet-estimate" aria-live="polite"></div>
+ <div class="vanity-wallet-modal-actions">
+ <button type="button" class="vanity-wallet-cancel-btn">Cancel</button>
+ <button type="submit" class="vanity-wallet-grind-btn">Grind &amp; provision</button>
+ </div>
+ </form>
+ </div>
+ `;
+ document.body.appendChild(overlay);
+
+ const close = () => overlay.remove();
+ overlay.querySelector('.vanity-wallet-cancel-btn').addEventListener('click', close);
+ overlay.addEventListener('click', (e) => {
+ if (e.target === overlay) close();
+ });
+
+ const prefixInput = overlay.querySelector('input[name="prefix"]');
+ const ignoreCaseInput = overlay.querySelector('input[name="ignore_case"]');
+ const estEl = overlay.querySelector('.vanity-wallet-estimate');
+ const submitBtn = overlay.querySelector('.vanity-wallet-grind-btn');
+
+ const refreshEstimate = () => {
+ const prefix = prefixInput.value.trim();
+ if (!prefix) {
+ estEl.textContent = '';
+ submitBtn.disabled = true;
+ return;
+ }
+ const v = validatePattern(prefix);
+ if (!v.valid) {
+ estEl.textContent = v.errors.join('; ');
+ submitBtn.disabled = true;
+ return;
+ }
+ const ignoreCase = ignoreCaseInput.checked;
+ const effective = ignoreCase ? prefix.length * 0.85 : prefix.length;
+ const expected = estimateAttempts(effective);
+ const seconds = expected / (RATE_PER_CORE * _coreCount());
+ estEl.innerHTML = `~${expected.toLocaleString()} attempts &middot; <strong>${_esc(formatTimeEstimate(seconds))}</strong> on ${_coreCount()} cores`;
+ submitBtn.disabled = false;
+ };
+ prefixInput.addEventListener('input', refreshEstimate);
+ ignoreCaseInput.addEventListener('change', refreshEstimate);
+ refreshEstimate();
+
+ overlay.querySelector('.vanity-wallet-form').addEventListener('submit', async (ev) => {
+ ev.preventDefault();
+ const prefix = prefixInput.value.trim();
+ const ignoreCase = ignoreCaseInput.checked;
+ close();
+ await this._provision({ prefix, ignoreCase });
+ });
+ }
+
+ async _provision({ prefix, ignoreCase }) {
+ this._abort = new AbortController();
+ try {
+ const result = await provisionVanityForAgent({
+ agentId: this._agent.id,
+ prefix,
+ ignoreCase,
+ signal: this._abort.signal,
+ onProgress: (p) => this._renderProgress(p),
+ });
+ this._agent.solana_address = result.address;
+ this._renderChip(result.address);
+ } catch (err) {
+ if (err?.name === 'AbortError') return this._render();
+ this._renderError(err.message || 'Provisioning failed.');
+ } finally {
+ this._abort = null;
+ }
+ }
+}
diff --git a/src/onchain/vanity/index.js b/src/onchain/vanity/index.js
new file mode 100644
index 000000000..2fed82468
--- /dev/null
+++ b/src/onchain/vanity/index.js
@@ -0,0 +1,85 @@
+/**
+ * Vanity wallet provisioning for agents.
+ *
+ * Wraps the existing client-side grinder (src/solana/vanity/grinder.js) and
+ * the provisioning endpoint (POST /api/agents/:id/solana with secret_key +
+ * vanity_prefix). Lets a caller grind a Solana keypair whose pubkey starts
+ * with a chosen base58 prefix, then hand it to the server, which encrypts it
+ * with AES-GCM (HKDF-derived from JWT_SECRET) and stores it on the agent.
+ *
+ * The agent thereafter has a custodial Solana wallet — the same model used
+ * by the legacy /api/agents/:id/pumpfun/* endpoints. The plaintext secret
+ * key only exists for the moment between grinding and the POST.
+ *
+ * Why client-side: keeps secret material out of server logs/RPC traces, and
+ * avoids burning Vercel function time on CPU-bound grinding. Long prefixes
+ * (5+) can take minutes — caller is responsible for surfacing a Cancel UX
+ * via AbortSignal.
+ */
+
+import { grindVanity } from '../../solana/vanity/grinder.js';
+import { Keypair } from '@solana/web3.js';
+import bs58 from 'bs58';
+
+/**
+ * @param {object} opts
+ * @param {string} opts.agentId
+ * @param {string} [opts.prefix]
+ * @param {string} [opts.suffix]
+ * @param {boolean} [opts.ignoreCase]
+ * @param {AbortSignal} [opts.signal]
+ * @param {(p: { attempts: number, rate: number, eta: string }) => void} [opts.onProgress]
+ * @returns {Promise<{ address: string, attempts: number, durationMs: number }>}
+ */
+export async function provisionVanityForAgent(opts) {
+ if (!opts?.agentId) throw new Error('agentId required');
+ if (!opts.prefix && !opts.suffix) throw new Error('prefix or suffix required');
+
+ // 1. Grind locally — secret material stays in this tab.
+ const ground = await grindVanity({
+ prefix: opts.prefix,
+ suffix: opts.suffix,
+ ignoreCase: !!opts.ignoreCase,
+ signal: opts.signal,
+ onProgress: opts.onProgress,
+ });
+
+ // 2. Sanity-check: derive the pubkey from the secret and confirm it matches.
+ // The server does this check too; doing it here surfaces local memory
+ // corruption (rare) before paying for a network round-trip.
+ const kp = Keypair.fromSecretKey(ground.secretKey);
+ if (kp.publicKey.toBase58() !== ground.publicKey) {
+ throw new Error('Locally-derived pubkey does not match grinder output.');
+ }
+
+ // 3. POST to the provisioning endpoint. The legacy endpoint accepts a
+ // base58-encoded secret_key and (optional) vanity_prefix — see
+ // api/agents/solana-wallet.js for the contract.
+ const secretBase58 = bs58.encode(ground.secretKey);
+ const resp = await fetch(`/api/agents/${encodeURIComponent(opts.agentId)}/solana`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ secret_key: secretBase58,
+ vanity_prefix: opts.prefix || undefined,
+ vanity_suffix: opts.suffix || undefined,
+ }),
+ });
+ if (!resp.ok) {
+ const data = await resp.json().catch(() => ({}));
+ const err = new Error(data.error_description || `provision returned ${resp.status}`);
+ err.status = resp.status;
+ err.code = data.error;
+ throw err;
+ }
+ const result = await resp.json();
+ return {
+ address: result.solana_address || ground.publicKey,
+ attempts: ground.attempts,
+ durationMs: ground.durationMs,
+ };
+}
+
+export { grindVanity };
+export { validatePattern, estimateAttempts, formatTimeEstimate } from '../../solana/vanity/validation.js';
diff --git a/src/onchain/x402/client.js b/src/onchain/x402/client.js
new file mode 100644
index 000000000..b9fb3fdff
--- /dev/null
+++ b/src/onchain/x402/client.js
@@ -0,0 +1,113 @@
+/**
+ * x402 client — fetch wrapper that follows 402 Payment Required automatically.
+ *
+ * Usage:
+ * 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: async (manifest) => 'auto', // or 'reject'
+ * onProgress: (step) => console.log(step),
+ * });
+ *
+ * Flow:
+ * 1. Make the request.
+ * 2. If 402: parse manifest, hand it to onPaymentRequired (caller can
+ * reject — useful for showing a confirmation modal). On 'auto', use the
+ * Pump.fun payments adapter to pay, then retry once with
+ * `x-payment-intent`.
+ * 3. Return the final response (whatever it is — 200, 4xx, etc.).
+ */
+
+import { getPaymentsAdapter } from '../payments/index.js';
+
+/** @typedef {{ version: string, kind: string, agent_id: string, skill: string, amount: string, currency: string, recipient: string, valid_until: number, intent_url: string, verify_url: string, retry_with_header: string }} X402Manifest */
+
+const MAX_RETRIES = 1;
+
+/**
+ * @param {string|URL} url
+ * @param {RequestInit & {
+ * onPaymentRequired?: (manifest: X402Manifest) => Promise<'auto'|'reject'> | 'auto' | 'reject',
+ * onProgress?: (step: string) => void,
+ * provider?: 'pumpfun',
+ * }} [opts]
+ * @returns {Promise<Response>}
+ */
+export async function x402Fetch(url, opts = {}) {
+ const {
+ onPaymentRequired = () => 'auto',
+ onProgress = () => {},
+ provider = 'pumpfun',
+ ...fetchOpts
+ } = opts;
+
+ let attempt = 0;
+ let intentId = null;
+
+ while (true) {
+ const headers = new Headers(fetchOpts.headers || {});
+ if (intentId) headers.set('x-payment-intent', intentId);
+ const response = await fetch(url, {
+ ...fetchOpts,
+ credentials: fetchOpts.credentials || 'include',
+ headers,
+ });
+
+ if (response.status !== 402) return response;
+ if (attempt >= MAX_RETRIES) return response; // gave up after one paid retry
+
+ // Parse 402 manifest. Spec says it's JSON; refuse anything else.
+ const ct = response.headers.get('content-type') || '';
+ if (!ct.includes('json')) return response;
+ const manifest = await response.json();
+ if (manifest?.version !== 'x402/0.1' || manifest?.kind !== 'agent-skill') {
+ return response;
+ }
+
+ const decision = await onPaymentRequired(manifest);
+ if (decision !== 'auto') return response;
+
+ // Pay via the configured adapter. Skill is bound into the intent
+ // payload so the server can verify the intent matches the call.
+ onProgress('paying');
+ const adapter = getPaymentsAdapter(provider);
+ const paid = await adapter.payAgent({
+ agent: {
+ id: manifest.agent_id,
+ // payAgent() reads agent.payments to discover cluster + mint.
+ // In x402, the manifest carries the cluster implicitly via the
+ // currency mint; we can read it server-side, but the adapter
+ // also needs the mint+cluster from the agent. We fetch a
+ // minimal agent record to satisfy that.
+ ...(await fetchAgentSnippet(manifest.agent_id)),
+ },
+ currencyMint: manifest.currency,
+ amount: manifest.amount,
+ memo: manifest.memo,
+ onProgress: (s) => onProgress(`paying:${s}`),
+ });
+
+ intentId = paid.intentId;
+ attempt += 1;
+ onProgress('retrying');
+ }
+}
+
+async function fetchAgentSnippet(agentId) {
+ try {
+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}`, {
+ credentials: 'include',
+ });
+ if (!r.ok) return {};
+ const data = await r.json();
+ return {
+ payments: data?.agent?.payments || data?.payments,
+ meta: { payments: data?.agent?.payments || data?.payments },
+ };
+ } catch {
+ return {};
+ }
+}
diff --git a/vercel.json b/vercel.json
index 6705bf98d..dbb506deb 100644
--- a/vercel.json
+++ b/vercel.json
@@ -75,6 +75,7 @@
},
{ "src": "/api/avatars/([^/]+)/pin-ipfs", "dest": "/api/avatars/[id]/pin-ipfs?id=$1" },
{ "src": "/dashboard/storage", "dest": "/dashboard/storage.html" },
+ { "src": "/dashboard/pump-relay", "dest": "/dashboard/pump-relay.html" },
{
"src": "/api/agents/([^/]+)/embed-policy",
"dest": "/api/agents/[id]/embed-policy?id=$1"