Skip to content

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

feat(x402+marketplace): solana x402 pay endpoint, skill-purchase migration, marketplace flow updates

nirholasd410def148e2
diff --git a/.gitignore b/.gitignore
index 45961f9e2..370b8154a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -64,3 +64,5 @@ wallets/
x402-test-wallets/
3dagent-log-export-2026-05-09T23-08-55.csv
pump-sdk-case-study.html
+.claude/scheduled_tasks.lock
+threews-launch-week-case-study.html
diff --git a/api/_lib/migrations/2026-05-10-skill-purchases.sql b/api/_lib/migrations/2026-05-10-skill-purchases.sql
new file mode 100644
index 000000000..aac9ec853
--- /dev/null
+++ b/api/_lib/migrations/2026-05-10-skill-purchases.sql
@@ -0,0 +1,54 @@
+-- Migration: canonical skill_purchases table.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-05-10-skill-purchases.sql
+-- Idempotent.
+--
+-- Replaces the never-deployed skill_purchases / user_skill_purchases that were
+-- referenced by code but never created. Aligns column names with the deployed
+-- agent_skill_prices schema (column "skill", not "skill_name" or "skill_id").
+--
+-- State machine:
+-- pending — buyer fetched Solana Pay params; no on-chain confirmation yet
+-- confirmed — reference observed on-chain, payment to creator wallet matched
+-- failed — explicit rejection (refunded, expired, malformed)
+
+begin;
+
+create table if not exists skill_purchases (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id) on delete cascade,
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ skill text not null,
+ status text not null default 'pending'
+ check (status in ('pending', 'confirmed', 'failed')),
+ reference text not null unique,
+ tx_signature text unique,
+ amount bigint not null,
+ currency_mint text not null,
+ chain text not null default 'solana',
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ confirmed_at timestamptz
+);
+
+-- A user holds at most one confirmed purchase for a given (agent, skill);
+-- multiple pending/failed attempts are allowed.
+create unique index if not exists skill_purchases_one_confirmed_per_user
+ on skill_purchases (user_id, agent_id, skill)
+ where status = 'confirmed';
+
+create index if not exists skill_purchases_user_agent
+ on skill_purchases (user_id, agent_id);
+
+create index if not exists skill_purchases_agent
+ on skill_purchases (agent_id);
+
+create index if not exists skill_purchases_status_created
+ on skill_purchases (status, created_at desc);
+
+-- Auto-bump updated_at; reuse the standard set_updated_at trigger function.
+do $$ begin
+ create trigger skill_purchases_set_updated_at before update on skill_purchases
+ for each row execute function set_updated_at();
+exception when duplicate_object then null; end $$;
+
+commit;
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index ddf258b95..806d8f9a6 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -77,6 +77,11 @@ export const limits = {
getLimiter('avatar:rollback', { limit: 10, window: '1 h' }).limit(userId),
chatUser: (userId) => getLimiter('chat:user', { limit: 40, window: '1 m' }).limit(userId),
chatIp: (ip) => getLimiter('chat:ip', { limit: 60, window: '1 m' }).limit(ip),
+ // Demo /api/x402-pay — agent wallet pays real USDC per call, so we keep the
+ // per-IP burst small (6/min ≈ $0.006/min) and rely on the agent wallet
+ // balance as the global ceiling.
+ x402PayIp: (ip) => getLimiter('x402:pay:ip', { limit: 6, window: '1 m' }).limit(ip),
+ x402PayGlobal: () => getLimiter('x402:pay:global', { limit: 600, window: '1 h' }).limit('global'),
checkName: (ip) => getLimiter('check-name:ip', { limit: 60, window: '1 m' }).limit(ip),
ensResolve: (ip) => getLimiter('ens:resolve:ip', { limit: 60, window: '1 m' }).limit(ip),
// Generic public read endpoints (explore, showcase, public agent fetch). 60/min per IP.
diff --git a/api/agents.js b/api/agents.js
index 1a99400fe..08fde9407 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -199,21 +199,15 @@ export async function handleGetOne(req, res, id) {
`;
if (!row) return error(res, 404, 'not_found', 'agent not found');
- // Pricing is non-critical for the detail view; the agent_skill_prices
- // schema has churned across migrations (skill / skill_name / skill_id),
- // so a column mismatch must never 500 the agent page.
- row.skill_prices = {};
- try {
- const prices = await sql`
- SELECT skill_name, amount, currency_mint FROM agent_skill_prices WHERE agent_id = ${id}
- `;
- row.skill_prices = prices.reduce((acc, p) => {
- acc[p.skill_name] = { amount: p.amount, currency_mint: p.currency_mint };
- return acc;
- }, {});
- } catch (e) {
- console.error('[agents] skill_prices lookup failed', e?.message || e);
- }
+ const prices = await sql`
+ SELECT skill, amount, currency_mint, chain
+ FROM agent_skill_prices
+ WHERE agent_id = ${id} AND is_active = true
+ `;
+ row.skill_prices = prices.reduce((acc, p) => {
+ acc[p.skill] = { amount: p.amount, currency_mint: p.currency_mint, chain: p.chain };
+ return acc;
+ }, {});
await healStaleAvatarId(row);
diff --git a/api/marketplace/[action].js b/api/marketplace/[action].js
index abf46e232..fa6dbcc31 100644
--- a/api/marketplace/[action].js
+++ b/api/marketplace/[action].js
@@ -327,9 +327,16 @@ async function handleDetail(req, res, id) {
}
const [priceRows, purchasedRows] = await Promise.all([
- sql`SELECT skill, currency_mint, chain, amount FROM agent_skill_prices WHERE agent_id = ${id} AND is_active = true`,
+ sql`
+ SELECT skill, currency_mint, chain, amount
+ FROM agent_skill_prices
+ WHERE agent_id = ${id} AND is_active = true
+ `,
auth
- ? sql`SELECT skill_name FROM skill_purchases WHERE user_id = ${auth.userId} AND agent_id = ${id}`
+ ? sql`
+ SELECT skill FROM skill_purchases
+ WHERE user_id = ${auth.userId} AND agent_id = ${id} AND status = 'confirmed'
+ `
: Promise.resolve([]),
]);
@@ -343,7 +350,7 @@ async function handleDetail(req, res, id) {
const skill_prices = Object.fromEntries(
priceRows.map((p) => [p.skill, { amount: p.amount, currency_mint: p.currency_mint, chain: p.chain }]),
);
- const purchased_skills = purchasedRows.map((r) => r.skill_name);
+ const purchased_skills = purchasedRows.map((r) => r.skill);
return json(
res,
diff --git a/api/marketplace/check-skill-access.js b/api/marketplace/check-skill-access.js
index 8d374aac9..687647928 100644
--- a/api/marketplace/check-skill-access.js
+++ b/api/marketplace/check-skill-access.js
@@ -1,33 +1,37 @@
-import { sql } from '../_lib/db.js';
-import { json, method, cors, error, auth } from '../_lib/http.js';
-
-export default async function checkSkillAccess(req, res) {
- if (cors(req, res)) return;
- if (!method(req, res, ['GET'])) return;
- const authUser = await auth(req, res);
- if (!authUser) return;
+/**
+ * GET /api/marketplace/check-skill-access?agent_id=…&skill=…
+ * Returns { has_access: boolean } for the authenticated caller.
+ */
- const { agent_id, skill_name } = req.query;
+import { sql } from '../_lib/db.js';
+import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
+import { cors, error, json, method, wrap } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
- if (!agent_id || !skill_name) {
- return error(res, 400, 'bad_request', 'Missing agent_id or skill_name.');
- }
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
- try {
- const [purchase] = await sql`
- SELECT id FROM skill_purchases
- WHERE user_id = ${authUser.id}
- AND agent_id = ${agent_id}
- AND skill_name = ${skill_name}
- LIMIT 1;
- `;
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id || bearer?.userId;
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
- const has_access = !!purchase;
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
- return json(res, 200, { ok: true, has_access });
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agent_id');
+ const skill = url.searchParams.get('skill');
+ if (!agentId || !skill) {
+ return error(res, 400, 'validation_error', 'agent_id and skill required');
+ }
- } catch (e) {
- console.error('Error checking skill access:', e);
- return error(res, 500, 'server_error', 'Failed to check access.');
- }
-}
+ const [row] = await sql`
+ SELECT 1 AS x FROM skill_purchases
+ WHERE user_id = ${userId} AND agent_id = ${agentId}
+ AND skill = ${skill} AND status = 'confirmed'
+ LIMIT 1
+ `;
+ return json(res, 200, { data: { has_access: !!row } });
+});
diff --git a/api/marketplace/purchase.js b/api/marketplace/purchase.js
index 426b0122b..4ccaedb6f 100644
--- a/api/marketplace/purchase.js
+++ b/api/marketplace/purchase.js
@@ -1,58 +1,274 @@
+/**
+ * Skill purchase flow (Solana Pay).
+ * ---------------------------------
+ * POST /api/marketplace/purchase
+ * Body: { agent_id, skill }
+ * Creates a pending skill_purchases row and returns Solana Pay params.
+ *
+ * GET /api/marketplace/purchase/:reference
+ * Returns { status, tx_signature, confirmed_at } for the caller's purchase.
+ *
+ * POST /api/marketplace/purchase/:reference/confirm
+ * Looks up the on-chain transaction by `reference`, validates it sent the
+ * expected amount of the expected SPL token to the agent owner's payout
+ * wallet, marks the purchase confirmed, records agent_revenue_events.
+ *
+ * Routed via vercel.json rewrites — see project root.
+ */
+
+import { Keypair, PublicKey } from '@solana/web3.js';
+import { findReference, validateTransfer } from '@solana/pay';
+import BigNumber from 'bignumber.js';
+
import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { error, json, readJson, wrap } from '../_lib/http.js';
-import { z } from 'zod';
+import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { rpcFallbackFromEnv } from '../_lib/solana/rpc-fallback.js';
-const purchaseSchema = z.object({
- agent_id: z.string().uuid(),
- skill_id: z.string().min(1),
-});
+let _rpc;
+function rpc() {
+ if (!_rpc) _rpc = rpcFallbackFromEnv({ network: 'mainnet' });
+ return _rpc;
+}
+
+const REFERENCE_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/; // base58 Pubkey
export default wrap(async (req, res) => {
- if (req.method !== 'POST') return error(res, 405, 'method_not_allowed');
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized');
-
- const body = purchaseSchema.parse(await readJson(req));
-
- // Check for existing purchase
- const [existingPurchase] = await sql`
- SELECT id FROM user_skill_purchases
- WHERE user_id = ${user.id} AND agent_id = ${body.agent_id} AND skill_id = ${body.skill_id} AND status = 'confirmed'
- `;
- if (existingPurchase) {
- return error(res, 409, 'already_owned', 'You have already purchased this skill.');
- }
-
- // Fetch price and creator info
- const [priceInfo] = await sql`
- SELECT asp.id, asp.creator_id, asp.amount, asp.currency_mint, u.wallet_address as creator_wallet
- FROM agent_skill_prices asp
- JOIN users u ON asp.creator_id = u.id
- WHERE asp.agent_id = ${body.agent_id} AND asp.skill_id = ${body.skill_id} AND asp.deleted_at IS NULL
- `;
- if (!priceInfo) return error(res, 404, 'price_not_found', 'This skill is not for sale.');
- if (!priceInfo.creator_wallet) return error(res, 500, 'creator_wallet_missing', 'The skill creator has not configured a wallet for payments.');
-
-
- // Create pending purchase record
- const [purchase] = await sql`
- INSERT INTO user_skill_purchases (user_id, agent_id, skill_id, price_id, status)
- VALUES (${user.id}, ${body.agent_id}, ${body.skill_id}, ${priceInfo.id}, 'pending')
- ON CONFLICT (user_id, agent_id, skill_id) DO UPDATE
- SET status = 'pending', price_id = EXCLUDED.price_id, updated_at = NOW()
- RETURNING id
- `;
-
- // Return details for Solana Pay transaction
- return json(res, {
- purchaseId: purchase.id,
- recipient: priceInfo.creator_wallet,
- amount: (priceInfo.amount / 1_000_000).toString(), // Assuming 6 decimals for USDC
- splToken: priceInfo.currency_mint,
- reference: purchase.id,
- label: `3D-Agent Skill: ${body.skill_id}`,
- message: `Purchase of skill '${body.skill_id}' for agent.`
- });
+ const url = new URL(req.url, 'http://x');
+ // Vercel rewrites pass reference/op as query params; allow path form too for
+ // local dev where the rewrite chain may be skipped.
+ const parts = url.pathname.split('/').filter(Boolean); // ['api','marketplace','purchase', ...]
+ const reference = url.searchParams.get('reference') || parts[3] || null;
+ const op = url.searchParams.get('op') || parts[4] || null;
+
+ if (!reference) {
+ if (req.method === 'POST') return handleCreate(req, res);
+ return error(res, 405, 'method_not_allowed', 'POST required');
+ }
+
+ if (!REFERENCE_RE.test(reference)) {
+ return error(res, 400, 'validation_error', 'invalid reference');
+ }
+
+ if (!op) return handleStatus(req, res, reference);
+ if (op === 'confirm') return handleConfirm(req, res, reference);
+ return error(res, 404, 'not_found', 'unknown purchase action');
});
+
+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 };
+ return null;
+}
+
+// ── Create ─────────────────────────────────────────────────────────────────
+
+async function handleCreate(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 required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = await readJson(req).catch(() => null);
+ const agentId = body?.agent_id;
+ const skill = typeof body?.skill === 'string' ? body.skill.trim() : null;
+ if (!agentId || !skill) {
+ return error(res, 400, 'validation_error', 'agent_id and skill required');
+ }
+
+ // Look up the active price for this skill on this agent.
+ const [price] = await sql`
+ SELECT amount, currency_mint, chain
+ FROM agent_skill_prices
+ WHERE agent_id = ${agentId} AND skill = ${skill} AND is_active = true
+ `;
+ if (!price) return error(res, 404, 'not_found', 'this skill is not for sale');
+
+ // Look up the agent owner's payout wallet for the relevant chain.
+ const [payout] = await sql`
+ SELECT pw.address
+ FROM agent_identities a
+ JOIN agent_payout_wallets pw
+ ON pw.user_id = a.user_id
+ AND pw.chain = ${price.chain}
+ AND (pw.agent_id = a.id OR pw.is_default = true)
+ WHERE a.id = ${agentId} AND a.deleted_at IS NULL
+ ORDER BY (pw.agent_id IS NOT NULL) DESC, pw.is_default DESC, pw.created_at ASC
+ LIMIT 1
+ `;
+ if (!payout?.address) {
+ return error(res, 412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');
+ }
+
+ // Block double-purchase: if the buyer already has a confirmed purchase
+ // for this (agent, skill), return it as-is rather than minting a new ref.
+ const [existing] = await sql`
+ SELECT reference, status, tx_signature, confirmed_at
+ FROM skill_purchases
+ WHERE user_id = ${auth.userId} AND agent_id = ${agentId} AND skill = ${skill}
+ AND status = 'confirmed'
+ LIMIT 1
+ `;
+ if (existing) {
+ return json(res, 200, {
+ data: {
+ already_owned: true,
+ reference: existing.reference,
+ status: existing.status,
+ tx_signature: existing.tx_signature,
+ confirmed_at: existing.confirmed_at,
+ },
+ });
+ }
+
+ const reference = Keypair.generate().publicKey.toBase58();
+ const label = `Skill: ${skill.slice(0, 40)}`;
+ const message = `Unlock '${skill}' for this agent`;
+
+ const [row] = await sql`
+ INSERT INTO skill_purchases (
+ user_id, agent_id, skill, status, reference,
+ amount, currency_mint, chain
+ )
+ VALUES (
+ ${auth.userId}, ${agentId}, ${skill}, 'pending', ${reference},
+ ${price.amount}, ${price.currency_mint}, ${price.chain}
+ )
+ RETURNING reference, amount, currency_mint, chain, created_at
+ `;
+
+ return json(res, 201, {
+ data: {
+ reference: row.reference,
+ recipient: payout.address,
+ amount: String(row.amount),
+ currency_mint: row.currency_mint,
+ chain: row.chain,
+ label,
+ message,
+ },
+ });
+}
+
+// ── Status ─────────────────────────────────────────────────────────────────
+
+async function handleStatus(req, res, reference) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [row] = await sql`
+ SELECT reference, agent_id, skill, status, tx_signature, confirmed_at,
+ amount, currency_mint, chain
+ FROM skill_purchases
+ WHERE reference = ${reference} AND user_id = ${auth.userId}
+ `;
+ if (!row) return error(res, 404, 'not_found', 'purchase not found');
+
+ return json(res, 200, { data: row }, { 'cache-control': 'no-store' });
+}
+
+// ── Confirm ────────────────────────────────────────────────────────────────
+
+async function handleConfirm(req, res, reference) {
+ 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 required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [pur] = await sql`
+ SELECT id, user_id, agent_id, skill, status, amount, currency_mint, chain, tx_signature
+ FROM skill_purchases
+ WHERE reference = ${reference} AND user_id = ${auth.userId}
+ `;
+ if (!pur) return error(res, 404, 'not_found', 'purchase not found');
+ if (pur.status === 'confirmed') {
+ return json(res, 200, { data: { status: 'confirmed', tx_signature: pur.tx_signature } });
+ }
+ if (pur.chain !== 'solana') {
+ return error(res, 501, 'not_implemented', `chain '${pur.chain}' confirmation not yet supported`);
+ }
+
+ // Resolve the agent owner's payout wallet again — it must match what the
+ // buyer paid to. Re-resolving on confirm protects against owner key
+ // rotation between create and confirm.
+ const [payout] = await sql`
+ SELECT pw.address
+ FROM agent_identities a
+ JOIN agent_payout_wallets pw
+ ON pw.user_id = a.user_id
+ AND pw.chain = ${pur.chain}
+ AND (pw.agent_id = a.id OR pw.is_default = true)
+ WHERE a.id = ${pur.agent_id}
+ ORDER BY (pw.agent_id IS NOT NULL) DESC, pw.is_default DESC, pw.created_at ASC
+ LIMIT 1
+ `;
+ if (!payout?.address) {
+ return error(res, 412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');
+ }
+
+ const refKey = new PublicKey(reference);
+ const recipient = new PublicKey(payout.address);
+ const splToken = new PublicKey(pur.currency_mint);
+ const expectedAmount = new BigNumber(pur.amount).dividedBy(1e6); // assume 6 decimals (USDC)
+
+ let signatureInfo;
+ try {
+ signatureInfo = await rpc().withFallback((conn) => findReference(conn, refKey, { finality: 'confirmed' }));
+ } catch (e) {
+ // Solana Pay throws FindReferenceError when no tx is found yet.
+ if (/FindReferenceError|not found/i.test(e?.message || '')) {
+ return json(res, 200, { data: { status: 'pending' } });
+ }
+ throw e;
+ }
+
+ const txSignature = signatureInfo.signature;
+
+ try {
+ await rpc().withFallback((conn) =>
+ validateTransfer(
+ conn,
+ txSignature,
+ { recipient, amount: expectedAmount, splToken, reference: refKey },
+ { commitment: 'confirmed' },
+ ),
+ );
+ } catch (e) {
+ // Transfer was found but doesn't match — mark failed so the user can retry.
+ await sql`
+ UPDATE skill_purchases
+ SET status = 'failed', tx_signature = ${txSignature}
+ WHERE id = ${pur.id} AND status = 'pending'
+ `;
+ return error(res, 409, 'transfer_mismatch', `on-chain transfer did not match expected: ${e.message}`);
+ }
+
+ // Atomic confirm. The status='pending' guard keeps concurrent confirms idempotent.
+ // Revenue aggregation is derived from skill_purchases at query time; we don't
+ // write to agent_revenue_events here because its intent_id FK constrains it
+ // to the agent_payment_intents flow (subscriptions / x402), not skill purchases.
+ await sql`
+ UPDATE skill_purchases
+ SET status = 'confirmed', tx_signature = ${txSignature}, confirmed_at = now()
+ WHERE id = ${pur.id} AND status = 'pending'
+ `;
+
+ return json(res, 200, { data: { status: 'confirmed', tx_signature: txSignature } });
+}
diff --git a/api/users/me/purchased-skills.js b/api/users/me/purchased-skills.js
index b40240135..d08596589 100644
--- a/api/users/me/purchased-skills.js
+++ b/api/users/me/purchased-skills.js
@@ -1,18 +1,31 @@
-import { getSessionUser } from '../../_lib/auth.js';
+/**
+ * GET /api/users/me/purchased-skills
+ * Returns the authenticated caller's confirmed skill purchases.
+ */
+
import { sql } from '../../_lib/db.js';
-import { error, json, method, wrap } from '../../_lib/http.js';
+import { authenticateBearer, extractBearer, getSessionUser } from '../../_lib/auth.js';
+import { cors, error, json, method, wrap } from '../../_lib/http.js';
+import { clientIp, limits } from '../../_lib/rate-limit.js';
export default wrap(async (req, res) => {
- if (!method(req, res, ['GET'])) return;
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id || bearer?.userId;
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
- const purchases = await sql`
- SELECT agent_id, skill_name
- FROM skill_purchases
- WHERE user_id = ${user.id}
- `;
+ const purchases = await sql`
+ SELECT agent_id, skill, amount, currency_mint, chain, tx_signature, confirmed_at
+ FROM skill_purchases
+ WHERE user_id = ${userId} AND status = 'confirmed'
+ ORDER BY confirmed_at DESC
+ `;
- return json(res, 200, { purchases });
+ return json(res, 200, { data: { purchases } });
});
diff --git a/api/x402-pay.js b/api/x402-pay.js
new file mode 100644
index 000000000..5e1c61c18
--- /dev/null
+++ b/api/x402-pay.js
@@ -0,0 +1,232 @@
+// POST /api/x402-pay
+//
+// Server-side x402 payer: takes { tool, args } from the chat UI, fires a
+// real paid x402 call to /api/mcp using a server-held Solana keypair, and
+// returns the MCP result + on-chain settlement proof.
+//
+// This powers the demo at /pay (and the in-chat x402 button) — the agent
+// pays USDC on behalf of the viewer so the UX is one-click.
+//
+// Env (required for prod):
+// X402_AGENT_SOLANA_SECRET_BASE58 base58-encoded 64-byte ed25519 secret key
+// Local dev fallback (when env unset): reads the keypair JSON at
+// /home/codespace/.config/x402-test-wallets/solana.json
+
+import { readFileSync } from 'node:fs';
+import {
+ Connection, PublicKey, Keypair, TransactionMessage, VersionedTransaction,
+ ComputeBudgetProgram,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync, createTransferCheckedInstruction,
+ createAssociatedTokenAccountIdempotentInstruction,
+ TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID, getMint,
+} from '@solana/spl-token';
+import bs58 from 'bs58';
+
+import { cors, json, readJson, wrap } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+
+const ALLOWED_TOOLS = new Set([
+ 'tools/list',
+ 'validate_model',
+ 'inspect_model',
+ 'optimize_model',
+ 'search_public_avatars',
+]);
+
+const MCP_URL = process.env.X402_PAY_TARGET_URL || 'https://three.ws/api/mcp';
+const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+
+let _agent = null;
+function loadAgentKeypair() {
+ if (_agent) return _agent;
+ const b58 = process.env.X402_AGENT_SOLANA_SECRET_BASE58;
+ if (b58) {
+ _agent = Keypair.fromSecretKey(bs58.decode(b58));
+ return _agent;
+ }
+ try {
+ const path = '/home/codespace/.config/x402-test-wallets/solana.json';
+ const arr = JSON.parse(readFileSync(path, 'utf8'));
+ _agent = Keypair.fromSecretKey(Uint8Array.from(arr));
+ return _agent;
+ } catch (err) {
+ const e = new Error('agent wallet not configured (set X402_AGENT_SOLANA_SECRET_BASE58)');
+ e.status = 500;
+ throw e;
+ }
+}
+
+function buildJsonRpc(tool, args) {
+ if (tool === 'tools/list') {
+ return { jsonrpc: '2.0', id: 1, method: 'tools/list' };
+ }
+ return {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: tool, arguments: args || {} },
+ };
+}
+
+async function buildSolanaPaymentPayload({ accept, buyer, conn }) {
+ const mint = new PublicKey(accept.asset);
+ const payTo = new PublicKey(accept.payTo);
+ const feePayer = new PublicKey(accept.extra.feePayer);
+ const amount = BigInt(accept.amount);
+
+ const senderAta = getAssociatedTokenAddressSync(
+ mint, buyer.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ const receiverAta = getAssociatedTokenAddressSync(
+ mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+
+ const mintInfo = await getMint(conn, mint);
+
+ const ixs = [
+ ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 }),
+ ];
+ const receiverInfo = await conn.getAccountInfo(receiverAta);
+ if (!receiverInfo) {
+ ixs.push(createAssociatedTokenAccountIdempotentInstruction(
+ feePayer, receiverAta, payTo, mint,
+ TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ ));
+ }
+ ixs.push(createTransferCheckedInstruction(
+ senderAta, mint, receiverAta, buyer.publicKey,
+ amount, mintInfo.decimals, [], TOKEN_PROGRAM_ID,
+ ));
+
+ const { blockhash } = await conn.getLatestBlockhash('confirmed');
+ const message = new TransactionMessage({
+ payerKey: feePayer,
+ recentBlockhash: blockhash,
+ instructions: ixs,
+ }).compileToV0Message();
+ const vtx = new VersionedTransaction(message);
+ vtx.sign([buyer]);
+
+ const txBase64 = Buffer.from(vtx.serialize()).toString('base64');
+ return {
+ x402Version: 2,
+ scheme: 'exact',
+ network: accept.network,
+ resource: { url: MCP_URL, mimeType: 'application/json' },
+ accepted: accept,
+ payload: { transaction: txBase64 },
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
+ if (req.method !== 'POST') return json(res, 405, { error: 'method_not_allowed' });
+
+ const ip = clientIp(req);
+ const ipRl = await limits.x402PayIp(ip);
+ if (!ipRl.success) {
+ return json(res, 429, {
+ error: 'rate_limited',
+ retry_after: Math.ceil((ipRl.reset - Date.now()) / 1000),
+ });
+ }
+ const globalRl = await limits.x402PayGlobal();
+ if (!globalRl.success) {
+ return json(res, 429, {
+ error: 'rate_limited_global',
+ retry_after: Math.ceil((globalRl.reset - Date.now()) / 1000),
+ });
+ }
+
+ const input = await readJson(req, 50_000);
+ const tool = String(input.tool || '');
+ const args = input.args && typeof input.args === 'object' ? input.args : {};
+ if (!ALLOWED_TOOLS.has(tool)) {
+ return json(res, 400, { error: 'invalid_tool', allowed: [...ALLOWED_TOOLS] });
+ }
+
+ const buyer = loadAgentKeypair();
+ const conn = new Connection(SOLANA_RPC, 'confirmed');
+
+ const t0 = Date.now();
+ const initRes = await fetch(MCP_URL, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify(buildJsonRpc(tool, args)),
+ });
+ const tInit = Date.now();
+ if (initRes.status !== 402) {
+ const body = await initRes.text();
+ return json(res, 502, {
+ error: 'unexpected_initial_response',
+ status: initRes.status,
+ body: body.slice(0, 1000),
+ });
+ }
+ const initBody = await initRes.json();
+ const accept = (initBody.accepts || []).find((a) => a.network && a.network.startsWith('solana:'));
+ if (!accept) {
+ return json(res, 502, { error: 'no_solana_accept_in_402' });
+ }
+
+ const paymentPayload = await buildSolanaPaymentPayload({ accept, buyer, conn });
+ const tBuilt = Date.now();
+ const xPayment = Buffer.from(JSON.stringify(paymentPayload)).toString('base64');
+
+ const paidRes = await fetch(MCP_URL, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ accept: 'application/json',
+ 'x-payment': xPayment,
+ },
+ body: JSON.stringify(buildJsonRpc(tool, args)),
+ });
+ const tPaid = Date.now();
+ const settleHeader = paidRes.headers.get('x-payment-response');
+ let settle = null;
+ if (settleHeader) {
+ try {
+ settle = JSON.parse(Buffer.from(settleHeader, 'base64').toString('utf8'));
+ } catch {}
+ }
+ const text = await paidRes.text();
+ let parsed;
+ try { parsed = JSON.parse(text); } catch { parsed = { raw: text }; }
+
+ if (!paidRes.ok) {
+ return json(res, paidRes.status, {
+ ok: false,
+ error: parsed.error || 'paid_call_failed',
+ body: parsed,
+ payment: { network: accept.network, payer: buyer.publicKey.toBase58(), amount: accept.amount, asset: accept.asset },
+ });
+ }
+
+ return json(res, 200, {
+ ok: true,
+ tool,
+ args,
+ result: parsed.result ?? parsed,
+ payment: {
+ network: accept.network,
+ payer: buyer.publicKey.toBase58(),
+ payTo: accept.payTo,
+ asset: accept.asset,
+ amount: accept.amount,
+ tx: settle?.transaction || null,
+ explorer: settle?.transaction
+ ? `https://solscan.io/tx/${settle.transaction}`
+ : null,
+ },
+ durations: {
+ challenge_ms: tInit - t0,
+ build_ms: tBuilt - tInit,
+ settle_ms: tPaid - tBuilt,
+ total_ms: tPaid - t0,
+ },
+ });
+});
diff --git a/scripts/x402-pay-three-ws-sol.mjs b/scripts/x402-pay-three-ws-sol.mjs
new file mode 100644
index 000000000..cde0e4321
--- /dev/null
+++ b/scripts/x402-pay-three-ws-sol.mjs
@@ -0,0 +1,116 @@
+import { readFileSync } from 'node:fs';
+import {
+ Connection, PublicKey, Keypair, TransactionMessage, VersionedTransaction,
+ ComputeBudgetProgram,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync, createTransferCheckedInstruction,
+ createAssociatedTokenAccountIdempotentInstruction,
+ TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID, getMint,
+} from '@solana/spl-token';
+
+const secretArr = JSON.parse(readFileSync('/home/codespace/.config/x402-test-wallets/solana.json', 'utf8'));
+const buyer = Keypair.fromSecretKey(Uint8Array.from(secretArr));
+const RPC = 'https://api.mainnet-beta.solana.com';
+const conn = new Connection(RPC, 'confirmed');
+console.log('[x402] buyer:', buyer.publicKey.toBase58());
+
+const url = 'https://three.ws/api/mcp';
+const body = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' });
+
+console.log('[x402] POST 1 (no payment)');
+const initRes = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
+ body,
+});
+console.log(' ->', initRes.status);
+const initBody = await initRes.json();
+const accept = initBody.accepts.find(a => a.network.startsWith('solana:'));
+console.log(' accept:', accept.network, accept.amount, 'to', accept.payTo);
+console.log(' feePayer:', accept.extra.feePayer);
+
+const mint = new PublicKey(accept.asset);
+const payTo = new PublicKey(accept.payTo);
+const feePayer = new PublicKey(accept.extra.feePayer);
+const amount = BigInt(accept.amount);
+
+const senderAta = getAssociatedTokenAddressSync(mint, buyer.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);
+const receiverAta = getAssociatedTokenAddressSync(mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);
+console.log(' senderATA:', senderAta.toBase58());
+console.log(' receiverATA:', receiverAta.toBase58());
+
+const mintInfo = await getMint(conn, mint);
+
+const ixs = [
+ ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 }),
+];
+const receiverInfo = await conn.getAccountInfo(receiverAta);
+if (!receiverInfo) {
+ console.log(' receiver ATA missing — including idempotent create (payer = feePayer)');
+ ixs.push(createAssociatedTokenAccountIdempotentInstruction(
+ feePayer, receiverAta, payTo, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ ));
+}
+ixs.push(createTransferCheckedInstruction(
+ senderAta, mint, receiverAta, buyer.publicKey,
+ amount, mintInfo.decimals, [], TOKEN_PROGRAM_ID,
+));
+
+const { blockhash } = await conn.getLatestBlockhash('confirmed');
+const message = new TransactionMessage({
+ payerKey: feePayer,
+ recentBlockhash: blockhash,
+ instructions: ixs,
+}).compileToV0Message();
+const vtx = new VersionedTransaction(message);
+vtx.sign([buyer]);
+
+const txBase64 = Buffer.from(vtx.serialize()).toString('base64');
+console.log('[x402] partially-signed tx size:', txBase64.length, 'b64 chars');
+
+const paymentPayload = {
+ x402Version: 2,
+ scheme: 'exact',
+ network: accept.network,
+ resource: { url, mimeType: 'application/json' },
+ accepted: accept,
+ payload: { transaction: txBase64 },
+};
+const xPayment = Buffer.from(JSON.stringify(paymentPayload)).toString('base64');
+
+console.log('[x402] POST 2 (X-PAYMENT, Solana exact)');
+const t0 = Date.now();
+const paidRes = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'accept': 'application/json',
+ 'X-PAYMENT': xPayment,
+ },
+ body,
+});
+const ms = Date.now() - t0;
+console.log(` -> HTTP ${paidRes.status} in ${ms}ms`);
+
+const settle = paidRes.headers.get('x-payment-response') || paidRes.headers.get('payment-response');
+if (settle) {
+ try {
+ const decoded = JSON.parse(Buffer.from(settle, 'base64').toString('utf8'));
+ console.log('[x402] settlement:', JSON.stringify(decoded, null, 2));
+ } catch { console.log('[x402] settle (raw):', settle.slice(0, 300)); }
+}
+const text = await paidRes.text();
+let parsed; try { parsed = JSON.parse(text); } catch { parsed = text; }
+const summary = typeof parsed === 'object' && parsed !== null
+ ? { status: paidRes.status, error: parsed.error, has_result: !!parsed.result }
+ : (typeof parsed === 'string' ? parsed.slice(0, 500) : parsed);
+console.log('[x402] summary:', summary);
+
+if (paidRes.ok && parsed?.result) {
+ console.log('[x402] result preview:', JSON.stringify(parsed.result, null, 2).slice(0, 700));
+ console.log('\nDone — Bazaar should index in a few minutes.');
+} else {
+ process.exit(1);
+}
diff --git a/vercel.json b/vercel.json
index d5cfd598e..77c3e107b 100644
--- a/vercel.json
+++ b/vercel.json
@@ -256,6 +256,14 @@
"src": "/api/marketplace/agents/([^/]+)/([^/]+)",
"dest": "/api/marketplace/[action]?action=agents&id=$1&sub=$2"
},
+ {
+ "src": "/api/marketplace/purchase/([^/]+)/confirm",
+ "dest": "/api/marketplace/purchase?reference=$1&op=confirm"
+ },
+ {
+ "src": "/api/marketplace/purchase/([^/]+)",
+ "dest": "/api/marketplace/purchase?reference=$1"
+ },
{
"src": "/marketplace",
"dest": "/marketplace.html"