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(pump): add API endpoints for payment acceptance, balance retrieval, and launch preparation

nirholas76fb46689e5b
diff --git a/api/_lib/pumpfun-mcp.js b/api/_lib/pumpfun-mcp.js
new file mode 100644
index 000000000..0726ca6fe
--- /dev/null
+++ b/api/_lib/pumpfun-mcp.js
@@ -0,0 +1,121 @@
+// Thin client for the upstream `pumpfun-claims-bot` MCP server.
+//
+// The bot is run as a long-lived service (e.g. Railway) that exposes a JSON-RPC
+// 2.0 MCP endpoint over HTTPS. This module fans calls out to its `tools/call`
+// method and caches the result in Upstash Redis when available so each Vercel
+// function cold start does not re-fetch the same data.
+//
+// Configure via env:
+// PUMPFUN_BOT_URL Full URL to the bot's MCP endpoint (required to enable)
+// PUMPFUN_BOT_TOKEN Optional bearer for authenticated MCP transports
+//
+// All exported helpers return `{ ok, data, error }`. They never throw on
+// network failure — callers degrade gracefully.
+
+import { Redis } from '@upstash/redis';
+import { env } from './env.js';
+
+const TOOL_TIMEOUT_MS = 8000;
+const CACHE_TTL_S = 60;
+
+let _redis = null;
+function redis() {
+ if (_redis !== null) return _redis;
+ if (!env.UPSTASH_REDIS_REST_URL || !env.UPSTASH_REDIS_REST_TOKEN) {
+ _redis = false;
+ return null;
+ }
+ _redis = new Redis({
+ url: env.UPSTASH_REDIS_REST_URL,
+ token: env.UPSTASH_REDIS_REST_TOKEN,
+ });
+ return _redis;
+}
+
+export function pumpfunBotEnabled() {
+ return !!process.env.PUMPFUN_BOT_URL;
+}
+
+function botUrl() {
+ const u = process.env.PUMPFUN_BOT_URL;
+ if (!u) throw Object.assign(new Error('pumpfun bot not configured'), { status: 503 });
+ return u.replace(/\/$/, '');
+}
+
+async function rpc(method, params) {
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), TOOL_TIMEOUT_MS);
+ try {
+ const headers = { 'content-type': 'application/json', accept: 'application/json' };
+ if (process.env.PUMPFUN_BOT_TOKEN) {
+ headers.authorization = `Bearer ${process.env.PUMPFUN_BOT_TOKEN}`;
+ }
+ const r = await fetch(botUrl(), {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
+ signal: ctrl.signal,
+ });
+ if (!r.ok) return { ok: false, error: `bot ${r.status}` };
+ const j = await r.json();
+ if (j.error) return { ok: false, error: j.error.message || 'rpc error' };
+ return { ok: true, data: j.result };
+ } catch (err) {
+ return { ok: false, error: err?.name === 'AbortError' ? 'timeout' : err?.message || 'fetch failed' };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+async function callTool(name, args, { ttl = CACHE_TTL_S } = {}) {
+ const cacheKey = `pf:${name}:${JSON.stringify(args || {})}`;
+ const r = redis();
+ if (r) {
+ try {
+ const cached = await r.get(cacheKey);
+ if (cached) return { ok: true, data: cached, cached: true };
+ } catch {}
+ }
+ const res = await rpc('tools/call', { name, arguments: args || {} });
+ if (!res.ok) return res;
+ // MCP tool result envelope → unwrap structuredContent if present.
+ const payload = res.data?.structuredContent ?? res.data?.content ?? res.data;
+ if (r && payload) {
+ try {
+ await r.set(cacheKey, payload, { ex: ttl });
+ } catch {}
+ }
+ return { ok: true, data: payload };
+}
+
+export const pumpfunMcp = {
+ enabled: pumpfunBotEnabled,
+
+ listTools() {
+ return rpc('tools/list', {});
+ },
+
+ recentClaims({ limit = 20 } = {}) {
+ return callTool('getRecentClaims', { limit }, { ttl: 30 });
+ },
+
+ graduations({ limit = 20 } = {}) {
+ return callTool('getGraduations', { limit }, { ttl: 60 });
+ },
+
+ tokenIntel({ mint }) {
+ if (!mint) return Promise.resolve({ ok: false, error: 'mint required' });
+ return callTool('getTokenIntel', { mint }, { ttl: 120 });
+ },
+
+ creatorIntel({ wallet }) {
+ if (!wallet) return Promise.resolve({ ok: false, error: 'wallet required' });
+ return callTool('getCreatorIntel', { wallet }, { ttl: 300 });
+ },
+
+ // Polling helper: serverless cannot hold a long-lived subscription, so the
+ // browser-side watch skill polls this and dedupes by tx signature.
+ claimsSince({ sinceSig = null, limit = 50 } = {}) {
+ return callTool('getClaimsSince', { sinceSig, limit }, { ttl: 5 });
+ },
+};
diff --git a/api/agents/pumpfun-feed.js b/api/agents/pumpfun-feed.js
new file mode 100644
index 000000000..e5616494f
--- /dev/null
+++ b/api/agents/pumpfun-feed.js
@@ -0,0 +1,111 @@
+/**
+ * GET /api/agents/pumpfun-feed
+ * ---------------------------------
+ * Live pump.fun activity feed for Solana agents. Streams `claim` and
+ * `graduation` events as Server-Sent Events.
+ *
+ * Auth: session OR bearer (scope `mcp` or `profile`).
+ * Query: ?kind=claims|graduations|all (default all)
+ * ?minTier=notable|influencer|mega (claim filter, optional)
+ *
+ * Implementation: serverless functions cannot hold long-lived connections
+ * efficiently, so we run a bounded poll loop (every 4s, up to 90s) and let
+ * the browser EventSource auto-reconnect. Each tick fetches `claimsSince`
+ * from the upstream pumpfun-claims-bot and emits new events.
+ */
+
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { cors, method, error, wrap } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { pumpfunMcp, pumpfunBotEnabled } from '../_lib/pumpfun-mcp.js';
+
+const POLL_MS = 4000;
+const MAX_DURATION_MS = 90_000;
+const TIER_RANK = { notable: 1, influencer: 2, mega: 3 };
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ if (!pumpfunBotEnabled()) {
+ return error(res, 503, 'unavailable', 'pumpfun feed not configured');
+ }
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ if (bearer && !hasScope(bearer.scope, 'mcp') && !hasScope(bearer.scope, 'profile')) {
+ return error(res, 403, 'insufficient_scope', 'requires mcp or profile scope');
+ }
+
+ const userId = session?.id ?? bearer.userId;
+ const rl = await limits.mcpUser(String(userId));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many feed connections');
+
+ const url = new URL(req.url, 'http://x');
+ const kind = url.searchParams.get('kind') || 'all';
+ const minTierParam = url.searchParams.get('minTier');
+ const minTier = TIER_RANK[minTierParam] || 0;
+
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/event-stream; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('connection', 'keep-alive');
+ res.setHeader('x-accel-buffering', 'no');
+ res.flushHeaders?.();
+
+ writeSse(res, 'open', { kind, minTier: minTierParam || null });
+
+ const seen = new Set();
+ let lastSig = null;
+ const started = Date.now();
+ let active = true;
+ req.on('close', () => {
+ active = false;
+ });
+
+ const tick = async () => {
+ const tasks = [];
+ if (kind === 'claims' || kind === 'all') {
+ tasks.push(pumpfunMcp.claimsSince({ sinceSig: lastSig, limit: 25 }).then((r) => ({ t: 'claim', r })));
+ }
+ if (kind === 'graduations' || kind === 'all') {
+ tasks.push(pumpfunMcp.graduations({ limit: 10 }).then((r) => ({ t: 'graduation', r })));
+ }
+ const results = await Promise.all(tasks);
+ for (const { t, r } of results) {
+ if (!r.ok) continue;
+ const items = Array.isArray(r.data) ? r.data : r.data?.items || [];
+ for (const ev of items) {
+ const id = ev.tx_signature || ev.signature || ev.id;
+ if (!id || seen.has(id)) continue;
+ seen.add(id);
+ if (t === 'claim') {
+ if (minTier && TIER_RANK[(ev.tier || '').toLowerCase()] < minTier) continue;
+ lastSig = id;
+ }
+ writeSse(res, t, ev);
+ }
+ }
+ };
+
+ while (active && Date.now() - started < MAX_DURATION_MS) {
+ try {
+ await tick();
+ } catch {}
+ writeSse(res, 'ping', { t: Date.now() });
+ await sleep(POLL_MS);
+ }
+
+ writeSse(res, 'close', { reason: 'duration_limit' });
+ res.end();
+});
+
+function writeSse(res, event, data) {
+ res.write(`event: ${event}\n`);
+ res.write(`data: ${JSON.stringify(data)}\n\n`);
+}
+
+function sleep(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+}
diff --git a/api/agents/pumpfun.js b/api/agents/pumpfun.js
new file mode 100644
index 000000000..547609096
--- /dev/null
+++ b/api/agents/pumpfun.js
@@ -0,0 +1,81 @@
+/**
+ * GET /api/agents/pumpfun
+ * -----------------------
+ * Read-only proxy to the upstream pumpfun-claims-bot MCP server. Backs the
+ * `pumpfun-recent-claims` and `pumpfun-token-intel` skills, plus any external
+ * MCP client that wants enriched pump.fun intel without standing up its own
+ * indexer.
+ *
+ * Query:
+ * ?op=claims &limit=10
+ * ?op=graduations &limit=10
+ * ?op=token &mint=<base58>
+ * ?op=creator &wallet=<base58>
+ *
+ * Auth: session OR bearer (scope `mcp` or `profile`).
+ * Cache: per-op, short TTL handled in api/_lib/pumpfun-mcp.js.
+ */
+
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { cors, json, method, error, wrap } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { pumpfunMcp, pumpfunBotEnabled } from '../_lib/pumpfun-mcp.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ if (!pumpfunBotEnabled()) {
+ return error(res, 503, 'unavailable', 'pumpfun feed not configured');
+ }
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ if (bearer && !hasScope(bearer.scope, 'mcp') && !hasScope(bearer.scope, 'profile')) {
+ return error(res, 403, 'insufficient_scope', 'requires mcp or profile scope');
+ }
+
+ const userId = session?.id ?? bearer.userId;
+ const rl = await limits.mcpUser(String(userId));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const op = url.searchParams.get('op') || 'claims';
+ const limit = clamp(Number(url.searchParams.get('limit')) || 10, 1, 50);
+
+ let result;
+ switch (op) {
+ case 'claims':
+ result = await pumpfunMcp.recentClaims({ limit });
+ break;
+ case 'graduations':
+ result = await pumpfunMcp.graduations({ limit });
+ break;
+ case 'token': {
+ const mint = url.searchParams.get('mint');
+ if (!mint) return error(res, 400, 'validation_error', 'mint required');
+ result = await pumpfunMcp.tokenIntel({ mint });
+ break;
+ }
+ case 'creator': {
+ const wallet = url.searchParams.get('wallet');
+ if (!wallet) return error(res, 400, 'validation_error', 'wallet required');
+ result = await pumpfunMcp.creatorIntel({ wallet });
+ break;
+ }
+ default:
+ return error(res, 400, 'validation_error', 'unknown op');
+ }
+
+ if (!result.ok) {
+ return error(res, 502, 'upstream_error', result.error || 'pumpfun bot unavailable');
+ }
+
+ const payload = Array.isArray(result.data) ? { items: result.data } : result.data;
+ return json(res, 200, payload);
+});
+
+function clamp(n, lo, hi) {
+ return Math.max(lo, Math.min(hi, n));
+}
diff --git a/api/agents/pumpfun/launch.js b/api/agents/pumpfun/launch.js
new file mode 100644
index 000000000..90cac07a0
--- /dev/null
+++ b/api/agents/pumpfun/launch.js
@@ -0,0 +1,137 @@
+// POST /api/agents/:id/pumpfun/launch
+// Create a new pump.fun token whose creator is the agent's Solana wallet.
+// Optional `solAmount` immediately buys an initial supply for the agent.
+//
+// Body: { name, symbol, uri, solAmount?, network? }
+// - uri: already-hosted JSON metadata URL (caller is responsible for upload)
+// - solAmount: optional initial buy in SOL (decimal); creates+buys atomically
+// - network: 'mainnet' | 'devnet' (default mainnet)
+//
+// The agent signs as creator/user. A fresh mint Keypair is generated and also
+// signs the create transaction. We return the new mint, transaction signature,
+// and explorer URL.
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, method, readJson, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
+import { sql } from '../../_lib/db.js';
+import { Keypair, Transaction, SystemProgram } from '@solana/web3.js';
+import { z } from 'zod';
+
+const bodySchema = z.object({
+ name: z.string().trim().min(1).max(32),
+ symbol: z.string().trim().min(1).max(10),
+ uri: z.string().url().max(2048),
+ solAmount: z.number().nonnegative().max(1000).optional(),
+ tokenAmount: z.number().nonnegative().optional(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+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;
+}
+
+export default async function handler(req, res, id) {
+ 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');
+
+ let body;
+ try {
+ body = bodySchema.parse(await readJson(req));
+ } catch (e) {
+ return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
+ }
+
+ const loaded = await loadAgentForSigning(id, auth.userId);
+ if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
+ const { keypair } = loaded;
+
+ const { PumpSdk, OnlinePumpSdk } = await import('@pump-fun/pump-sdk');
+ const BN = (await import('bn.js')).default;
+ const conn = solanaConnection(body.network);
+ const online = new OnlinePumpSdk(conn);
+ const sdk = new PumpSdk();
+
+ const mint = Keypair.generate();
+ const solLamports = new BN(Math.floor((body.solAmount || 0) * 1e9));
+ const tokenAmount = new BN(body.tokenAmount || 0);
+
+ let instructions;
+ if (solLamports.gtn(0)) {
+ const global = await online.fetchGlobal();
+ instructions = await sdk.createV2AndBuyInstructions({
+ global,
+ mint: mint.publicKey,
+ name: body.name,
+ symbol: body.symbol,
+ uri: body.uri,
+ creator: keypair.publicKey,
+ user: keypair.publicKey,
+ amount: tokenAmount,
+ solAmount: solLamports,
+ mayhemMode: false,
+ });
+ } else {
+ const ix = await sdk.createV2Instruction({
+ mint: mint.publicKey,
+ name: body.name,
+ symbol: body.symbol,
+ uri: body.uri,
+ creator: keypair.publicKey,
+ user: keypair.publicKey,
+ mayhemMode: false,
+ });
+ instructions = [ix];
+ }
+
+ const tx = new Transaction().add(...instructions);
+ tx.feePayer = keypair.publicKey;
+ const { blockhash } = await conn.getLatestBlockhash();
+ tx.recentBlockhash = blockhash;
+ tx.sign(keypair, mint);
+
+ let signature;
+ try {
+ signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
+ await conn.confirmTransaction(signature, 'confirmed');
+ } catch (err) {
+ console.error('[pumpfun/launch] send failed', err);
+ return error(res, 502, 'rpc_error', err.message || 'transaction failed');
+ }
+
+ await sql`
+ INSERT INTO agent_actions (agent_id, type, payload, source_skill)
+ VALUES (
+ ${id},
+ ${'pumpfun.launch'},
+ ${JSON.stringify({
+ mint: mint.publicKey.toBase58(),
+ name: body.name,
+ symbol: body.symbol,
+ uri: body.uri,
+ signature,
+ network: body.network,
+ })}::jsonb,
+ ${'pumpfun'}
+ )
+ `.catch((e) => console.error('[pumpfun/launch] log failed', e));
+
+ return json(res, 201, {
+ data: {
+ mint: mint.publicKey.toBase58(),
+ signature,
+ explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
+ pumpfun_url: `https://pump.fun/${mint.publicKey.toBase58()}`,
+ },
+ });
+}
diff --git a/api/agents/pumpfun/pay.js b/api/agents/pumpfun/pay.js
new file mode 100644
index 000000000..780895cb9
--- /dev/null
+++ b/api/agents/pumpfun/pay.js
@@ -0,0 +1,128 @@
+// POST /api/agents/:id/pumpfun/pay
+// Wraps @pump-fun/agent-payments-sdk.
+//
+// Body: { action, tokenMint, currencyMint, ...params, network? }
+// action='accept' — pay an agent token (the agent IS the user paying);
+// params: amount (string raw units), memo, startTime, endTime
+// action='withdraw' — agent withdraws collected payments for the token
+// it is the agent-authority of; params: receiverAta
+// action='balances' — read-only; returns vault balances for currencyMint
+//
+// Server signs with the agent's wallet.
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, method, readJson, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
+import { PublicKey, Transaction } from '@solana/web3.js';
+import { z } from 'zod';
+
+const bodySchema = z.object({
+ action: z.enum(['accept', 'withdraw', 'balances']),
+ tokenMint: z.string().min(32).max(64),
+ currencyMint: z.string().min(32).max(64),
+ amount: z.string().regex(/^\d+$/).optional(),
+ memo: z.string().regex(/^\d+$/).optional(),
+ startTime: z.number().int().nonnegative().optional(),
+ endTime: z.number().int().nonnegative().optional(),
+ receiverAta: z.string().min(32).max(64).optional(),
+ userTokenAccount: z.string().min(32).max(64).optional(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+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;
+}
+
+export default async function handler(req, res, id) {
+ 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');
+
+ let body;
+ try {
+ body = bodySchema.parse(await readJson(req));
+ } catch (e) {
+ return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
+ }
+
+ const loaded = await loadAgentForSigning(id, auth.userId);
+ if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
+ const { keypair } = loaded;
+
+ const conn = solanaConnection(body.network);
+ const tokenMint = new PublicKey(body.tokenMint);
+ const currencyMint = new PublicKey(body.currencyMint);
+ const { PumpAgent } = await import('@pump-fun/agent-payments-sdk');
+ const agent = new PumpAgent(tokenMint, body.network, conn);
+
+ if (body.action === 'balances') {
+ const balances = await agent.getBalances(currencyMint);
+ return json(res, 200, {
+ data: {
+ balances: Object.fromEntries(
+ Object.entries(balances).map(([k, v]) => [
+ k,
+ v && typeof v === 'object'
+ ? { ...v, balance: v.balance?.toString?.() ?? String(v.balance) }
+ : v,
+ ]),
+ ),
+ },
+ });
+ }
+
+ let instructions;
+ if (body.action === 'accept') {
+ if (!body.userTokenAccount || !body.amount || !body.memo || body.startTime == null || body.endTime == null)
+ return error(res, 400, 'validation_error', 'accept requires userTokenAccount, amount, memo, startTime, endTime');
+ instructions = await agent.buildAcceptPaymentInstructions({
+ user: keypair.publicKey,
+ currencyMint,
+ amount: body.amount,
+ memo: body.memo,
+ startTime: body.startTime,
+ endTime: body.endTime,
+ });
+ } else {
+ if (!body.receiverAta) return error(res, 400, 'validation_error', 'withdraw requires receiverAta');
+ const ix = await agent.withdraw({
+ authority: keypair.publicKey,
+ currencyMint,
+ receiverAta: new PublicKey(body.receiverAta),
+ });
+ instructions = [ix];
+ }
+
+ const tx = new Transaction().add(...instructions);
+ tx.feePayer = keypair.publicKey;
+ const { blockhash } = await conn.getLatestBlockhash();
+ tx.recentBlockhash = blockhash;
+ tx.sign(keypair);
+
+ let signature;
+ try {
+ signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
+ await conn.confirmTransaction(signature, 'confirmed');
+ } catch (err) {
+ console.error('[pumpfun/pay] send failed', err);
+ return error(res, 502, 'rpc_error', err.message || 'transaction failed');
+ }
+
+ return json(res, 200, {
+ data: {
+ signature,
+ action: body.action,
+ tokenMint: body.tokenMint,
+ explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
+ },
+ });
+}
diff --git a/api/agents/pumpfun/swap.js b/api/agents/pumpfun/swap.js
new file mode 100644
index 000000000..0cff304b4
--- /dev/null
+++ b/api/agents/pumpfun/swap.js
@@ -0,0 +1,151 @@
+// POST /api/agents/:id/pumpfun/swap
+// Buy or sell a pump.fun token from the agent's Solana wallet.
+// While the token is on the bonding curve, uses @pump-fun/pump-sdk.
+// After graduation (AMM), uses @pump-fun/pump-swap-sdk.
+//
+// Body: { mint, side: 'buy'|'sell', solAmount?, tokenAmount?, slippageBps?, network? }
+// - For buy: provide solAmount (SOL to spend). tokenAmount can be 0 (sdk computes).
+// - For sell: provide tokenAmount (raw smallest-units). solAmount is min-out.
+// - slippageBps: 0–10000 (default 500 = 5%)
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, method, readJson, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
+import { PublicKey, Transaction } from '@solana/web3.js';
+import { z } from 'zod';
+
+const bodySchema = z.object({
+ mint: z.string().trim().min(32).max(64),
+ side: z.enum(['buy', 'sell']),
+ solAmount: z.number().nonnegative().optional(),
+ tokenAmount: z.string().regex(/^\d+$/).optional(),
+ slippageBps: z.number().int().min(0).max(10000).default(500),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+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;
+}
+
+export default async function handler(req, res, id) {
+ 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');
+
+ let body;
+ try {
+ body = bodySchema.parse(await readJson(req));
+ } catch (e) {
+ return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
+ }
+
+ const loaded = await loadAgentForSigning(id, auth.userId);
+ if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
+ const { keypair } = loaded;
+
+ const conn = solanaConnection(body.network);
+ const mint = new PublicKey(body.mint);
+ const BN = (await import('bn.js')).default;
+ const { TOKEN_PROGRAM_ID } = await import('@solana/spl-token').catch(() => ({}));
+ const tokenProgram = TOKEN_PROGRAM_ID || new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
+
+ const { PumpSdk } = await import('@pump-fun/pump-sdk');
+ const sdk = new PumpSdk();
+
+ // Read bonding curve to decide bonding-curve vs AMM path.
+ const { bondingCurvePda } = await import('@pump-fun/pump-sdk');
+ const bcInfo = await conn.getAccountInfo(bondingCurvePda(mint));
+
+ let instructions;
+ if (bcInfo && !sdk.decodeBondingCurveNullable(bcInfo)?.complete) {
+ const { OnlinePumpSdk } = await import('@pump-fun/pump-sdk');
+ const online = new OnlinePumpSdk(conn);
+ const global = await online.fetchGlobal();
+ const bondingCurve = sdk.decodeBondingCurve(bcInfo);
+ const slip = body.slippageBps / 100; // sdk takes a percentage
+
+ if (body.side === 'buy') {
+ const { associatedUserAccountInfo } = await online.fetchBuyState(mint, keypair.publicKey, tokenProgram);
+ instructions = await sdk.buyInstructions({
+ global,
+ bondingCurveAccountInfo: bcInfo,
+ bondingCurve,
+ associatedUserAccountInfo,
+ mint,
+ user: keypair.publicKey,
+ amount: new BN(body.tokenAmount || '0'),
+ solAmount: new BN(Math.floor((body.solAmount || 0) * 1e9)),
+ slippage: slip,
+ tokenProgram,
+ });
+ } else {
+ instructions = await sdk.sellInstructions({
+ global,
+ bondingCurveAccountInfo: bcInfo,
+ bondingCurve,
+ mint,
+ user: keypair.publicKey,
+ amount: new BN(body.tokenAmount || '0'),
+ solAmount: new BN(Math.floor((body.solAmount || 0) * 1e9)),
+ slippage: slip,
+ tokenProgram,
+ mayhemMode: false,
+ });
+ }
+ } else {
+ // Graduated → AMM swap via pump-swap-sdk.
+ const swap = await import('@pump-fun/pump-swap-sdk');
+ const { OnlinePumpAmmSdk } = swap;
+ const amm = new OnlinePumpAmmSdk(conn);
+ if (body.side === 'buy') {
+ instructions = await swap.buyQuoteInput({
+ amm,
+ baseMint: mint,
+ user: keypair.publicKey,
+ quoteAmount: new BN(Math.floor((body.solAmount || 0) * 1e9)),
+ slippageBps: body.slippageBps,
+ });
+ } else {
+ instructions = await swap.sellBaseInput({
+ amm,
+ baseMint: mint,
+ user: keypair.publicKey,
+ baseAmount: new BN(body.tokenAmount || '0'),
+ slippageBps: body.slippageBps,
+ });
+ }
+ }
+
+ const tx = new Transaction().add(...instructions);
+ tx.feePayer = keypair.publicKey;
+ const { blockhash } = await conn.getLatestBlockhash();
+ tx.recentBlockhash = blockhash;
+ tx.sign(keypair);
+
+ let signature;
+ try {
+ signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
+ await conn.confirmTransaction(signature, 'confirmed');
+ } catch (err) {
+ console.error('[pumpfun/swap] send failed', err);
+ return error(res, 502, 'rpc_error', err.message || 'transaction failed');
+ }
+
+ return json(res, 200, {
+ data: {
+ signature,
+ mint: body.mint,
+ side: body.side,
+ explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
+ },
+ });
+}
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
new file mode 100644
index 000000000..95da9485b
--- /dev/null
+++ b/api/agents/solana-wallet.js
@@ -0,0 +1,73 @@
+// /api/agents/:id/solana
+// GET — return the agent's Solana address + SOL balance (owner only).
+// POST — provision a Solana wallet for this agent if it doesn't have one.
+// Idempotent: returns the existing address if already provisioned.
+//
+// The encrypted secret never leaves the server. Signing is done by the
+// pump.fun action endpoints in api/agents/pumpfun/*.
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { generateSolanaAgentWallet } from '../_lib/agent-wallet.js';
+import { solanaConnection } from '../_lib/agent-pumpfun.js';
+import { PublicKey } from '@solana/web3.js';
+
+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;
+}
+
+export default async function handler(req, res, id) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', '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 [row] = await sql`
+ SELECT id, user_id, meta FROM agent_identities
+ WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!row) return error(res, 404, 'not_found', 'agent not found');
+ if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ let meta = { ...(row.meta || {}) };
+
+ if (req.method === 'POST' && !meta.solana_address) {
+ const sol = await generateSolanaAgentWallet();
+ meta = { ...meta, solana_address: sol.address, encrypted_solana_secret: sol.encrypted_secret };
+ await sql`
+ UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}
+ `;
+ }
+
+ if (!meta.solana_address) {
+ return error(res, 404, 'not_found', 'agent has no solana wallet — POST to provision');
+ }
+
+ const network = (req.query?.network || new URL(req.url, 'http://x').searchParams.get('network') || 'mainnet').toString();
+ let lamports = null;
+ try {
+ const conn = solanaConnection(network === 'devnet' ? 'devnet' : 'mainnet');
+ lamports = await conn.getBalance(new PublicKey(meta.solana_address));
+ } catch (err) {
+ console.error('[agents/solana] balance fetch failed', err);
+ }
+
+ return json(res, 200, {
+ data: {
+ address: meta.solana_address,
+ network,
+ lamports,
+ sol: lamports == null ? null : lamports / 1e9,
+ },
+ });
+}
diff --git a/api/agents/tokens/launch-confirm.js b/api/agents/tokens/launch-confirm.js
new file mode 100644
index 000000000..61105353d
--- /dev/null
+++ b/api/agents/tokens/launch-confirm.js
@@ -0,0 +1,136 @@
+/**
+ * POST /api/agents/tokens/launch-confirm
+ *
+ * Verify the Pump.fun coin-creation transaction landed on Solana and write
+ * the canonical token block onto agent_identities.meta.token:
+ *
+ * meta.token = {
+ * provider: 'pumpfun',
+ * mint: '<base58>',
+ * symbol, name, metadata_uri,
+ * cluster: 'mainnet' | 'devnet',
+ * creator: '<base58>',
+ * tx_signature: '<base58>',
+ * launched_at: ISO,
+ * pumpfun_url: 'https://pump.fun/<mint>' (mainnet only)
+ * }
+ */
+
+import { z } from 'zod';
+import { Connection } from '@solana/web3.js';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } 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 { env } from '../../_lib/env.js';
+
+const bodySchema = z.object({
+ prep_id: z.string().min(8).max(80),
+ tx_signature: z.string().min(40).max(120),
+ wallet_address: z.string().min(32).max(44),
+});
+
+function rpcUrl(cluster) {
+ return cluster === 'devnet'
+ ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
+ : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) 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 = parse(bodySchema, await readJson(req));
+
+ const [prep] = await sql`
+ select id, agent_id, mint, metadata_uri, cluster, payload
+ from token_launches_pending
+ where id = ${body.prep_id} and user_id = ${user.id} and expires_at > now()
+ limit 1
+ `;
+ if (!prep) return error(res, 404, 'not_found', 'prep expired or not found');
+
+ if (prep.payload?.wallet_address !== body.wallet_address) {
+ return error(res, 400, 'validation_error', 'wallet mismatch with prep');
+ }
+
+ // Verify on-chain
+ const conn = new Connection(rpcUrl(prep.cluster), 'confirmed');
+
+ const deadline = Date.now() + 30_000;
+ let tx;
+ while (Date.now() < deadline) {
+ tx = await conn.getParsedTransaction(body.tx_signature, {
+ maxSupportedTransactionVersion: 0,
+ commitment: 'confirmed',
+ });
+ if (tx) break;
+ await new Promise((r) => setTimeout(r, 1500));
+ }
+ if (!tx) return error(res, 422, 'tx_not_found', 'tx not found on Solana RPC');
+ if (tx.meta?.err) return error(res, 422, 'tx_failed', 'tx failed on-chain');
+
+ const accounts = tx.transaction.message.accountKeys.map((k) => k.pubkey?.toString());
+ if (!accounts.includes(prep.mint)) {
+ return error(res, 422, 'mint_not_in_tx', 'expected mint not in tx');
+ }
+ if (!accounts.includes(body.wallet_address)) {
+ return error(res, 422, 'wrong_signer', 'wallet not in tx signers');
+ }
+
+ // Resolve agent (re-check ownership + still no token)
+ const [agent] = await sql`
+ select id, meta from agent_identities
+ where id = ${prep.agent_id} and user_id = ${user.id} and deleted_at is null
+ limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (agent.meta?.token?.mint) {
+ return error(res, 409, 'conflict', 'agent already has a launched token');
+ }
+
+ const token = {
+ provider: 'pumpfun',
+ mint: prep.mint,
+ name: prep.payload.name,
+ symbol: prep.payload.symbol,
+ description: prep.payload.description,
+ image: prep.payload.image,
+ metadata_uri: prep.metadata_uri,
+ cluster: prep.cluster,
+ creator: body.wallet_address,
+ tx_signature: body.tx_signature,
+ launched_at: new Date().toISOString(),
+ ...(prep.cluster === 'mainnet'
+ ? { pumpfun_url: `https://pump.fun/${prep.mint}` }
+ : {
+ explorer_url: `https://explorer.solana.com/address/${prep.mint}?cluster=devnet`,
+ }),
+ ...(prep.payload.initial_buy_sol > 0
+ ? { initial_buy_sol: prep.payload.initial_buy_sol }
+ : {}),
+ };
+
+ const mergedMeta = { ...(agent.meta || {}), token };
+ const [updated] = await sql`
+ update agent_identities
+ set meta = ${JSON.stringify(mergedMeta)}::jsonb,
+ updated_at = now()
+ where id = ${agent.id}
+ returning id, name, description, wallet_address, meta, created_at
+ `;
+
+ await sql`delete from token_launches_pending where id = ${prep.id}`;
+
+ return json(res, 201, {
+ ok: true,
+ agent: { ...updated, token, home_url: `${env.APP_ORIGIN}/agent/${updated.id}` },
+ });
+});
diff --git a/api/agents/tokens/launch-prep.js b/api/agents/tokens/launch-prep.js
new file mode 100644
index 000000000..9d4ab1384
--- /dev/null
+++ b/api/agents/tokens/launch-prep.js
@@ -0,0 +1,261 @@
+/**
+ * POST /api/agents/tokens/launch-prep
+ *
+ * Build an unsigned Pump.fun coin-creation transaction for the user to sign.
+ *
+ * Flow:
+ * 1. Verify the agent belongs to caller and was deployed on Solana.
+ * 2. Verify caller's wallet matches the agent's owner wallet.
+ * 3. Pin token metadata JSON (name/symbol/description/image) to IPFS.
+ * 4. Generate a fresh mint Keypair, build the create instruction via
+ * @pump-fun/pump-sdk, partial-sign with the mint, return base64.
+ * 5. Persist a prep record (`token_launches_pending`) the confirm endpoint
+ * validates against.
+ *
+ * The mint Keypair is destroyed after partial-signing — its signature is now
+ * embedded in the serialized tx bytes, so we never need to retain the secret.
+ */
+
+import { z } from 'zod';
+import {
+ Connection,
+ Keypair,
+ PublicKey,
+ Transaction,
+ ComputeBudgetProgram,
+ SystemProgram,
+} from '@solana/web3.js';
+import { PumpSdk, getBuyTokenAmountFromSolAmount } from '@pump-fun/pump-sdk';
+import BN from 'bn.js';
+
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } 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 { randomToken } from '../../_lib/crypto.js';
+import { env } from '../../_lib/env.js';
+import { r2 } from '../../_lib/r2.js';
+import { PutObjectCommand } from '@aws-sdk/client-s3';
+import { createHash } from 'crypto';
+
+const bodySchema = z.object({
+ agent_id: z.string().min(1).max(80),
+ provider: z.literal('pumpfun'),
+ cluster: z.enum(['mainnet', 'devnet']),
+ wallet_address: z.string().min(32).max(44),
+ name: z.string().trim().min(1).max(32),
+ // Pump.fun caps symbols at ~10 chars; let's be permissive but clamped.
+ symbol: z
+ .string()
+ .trim()
+ .min(2)
+ .max(10)
+ .regex(/^[A-Za-z0-9]+$/, 'symbol must be alphanumeric'),
+ description: z.string().trim().max(280).default(''),
+ image: z.string().url().or(z.literal('')).default(''),
+ initial_buy_sol: z.number().min(0).max(50).default(0),
+});
+
+function rpcUrl(cluster) {
+ return cluster === 'devnet'
+ ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
+ : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+}
+
+async function pinTokenMetadata({ name, symbol, description, image }) {
+ const json = {
+ name,
+ symbol,
+ description,
+ image,
+ showName: true,
+ createdOn: 'three.ws',
+ };
+ const bytes = Buffer.from(JSON.stringify(json), 'utf-8');
+ const token = process.env.WEB3_STORAGE_TOKEN;
+ if (token) {
+ try {
+ const r = await fetch('https://api.web3.storage/upload', {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}` },
+ body: bytes,
+ });
+ if (r.ok) {
+ const data = await r.json();
+ if (data.cid) return { cid: data.cid, uri: `ipfs://${data.cid}` };
+ }
+ } catch (e) {
+ console.warn('[token launch-prep] web3.storage pin failed:', e.message);
+ }
+ }
+ const hash = createHash('sha256').update(bytes).digest('hex');
+ const stub = `bafkreigenerated${hash.slice(0, 40)}`;
+ const key = `token-metadata/${Date.now()}-${Math.random().toString(36).slice(2)}.json`;
+ await r2.send(
+ new PutObjectCommand({
+ Bucket: env.S3_BUCKET,
+ Key: key,
+ Body: bytes,
+ ContentType: 'application/json',
+ }),
+ );
+ return { cid: stub, uri: `ipfs://${stub}` };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) 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 = parse(bodySchema, await readJson(req));
+
+ // Resolve agent + ownership + Solana deploy state
+ const [agent] = await sql`
+ select id, name, user_id, wallet_address, meta
+ from agent_identities
+ where id = ${body.agent_id} and user_id = ${user.id} and deleted_at is null
+ limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ const onchain = agent.meta?.onchain;
+ if (!onchain || onchain.family !== 'solana') {
+ return error(
+ res,
+ 409,
+ 'precondition_failed',
+ 'agent must be deployed on Solana before launching a token',
+ );
+ }
+ if (onchain.wallet?.toLowerCase?.() !== body.wallet_address.toLowerCase?.()) {
+ // Solana addresses are case-sensitive; equality check is exact.
+ if (onchain.wallet !== body.wallet_address) {
+ return error(res, 403, 'forbidden', 'wallet does not match agent owner');
+ }
+ }
+ if (agent.meta?.token?.mint) {
+ return error(res, 409, 'conflict', 'agent already has a launched token');
+ }
+
+ // 3. Pin token metadata
+ const { cid, uri: metadataUri } = await pinTokenMetadata({
+ name: body.name,
+ symbol: body.symbol,
+ description: body.description,
+ image: body.image,
+ });
+
+ // 4. Build the launch tx
+ const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
+ const sdk = new PumpSdk(conn);
+
+ const mintKeypair = Keypair.generate();
+ const creator = new PublicKey(body.wallet_address);
+ const userPk = creator;
+
+ const ixs = [
+ // Bump compute budget — coin creation routinely exceeds the 200k default.
+ ComputeBudgetProgram.setComputeUnitLimit({ units: 350_000 }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 100_000 }),
+ ];
+
+ if (body.initial_buy_sol > 0) {
+ const global = await sdk.fetchGlobal();
+ const lamports = new BN(Math.floor(body.initial_buy_sol * 1_000_000_000));
+ const tokenAmount = getBuyTokenAmountFromSolAmount({
+ global,
+ feeConfig: null,
+ mintSupply: null,
+ bondingCurve: null,
+ amount: lamports,
+ });
+ const launchIxs = await sdk.createAndBuyInstructions({
+ global,
+ mint: mintKeypair.publicKey,
+ name: body.name,
+ symbol: body.symbol,
+ uri: metadataUri,
+ creator,
+ user: userPk,
+ amount: tokenAmount,
+ solAmount: lamports,
+ });
+ ixs.push(...launchIxs);
+ } else {
+ const ix = await sdk.createV2Instruction({
+ mint: mintKeypair.publicKey,
+ name: body.name,
+ symbol: body.symbol,
+ uri: metadataUri,
+ creator,
+ user: userPk,
+ mayhemMode: false,
+ });
+ ixs.push(ix);
+ }
+
+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');
+ const tx = new Transaction({
+ feePayer: creator,
+ blockhash,
+ lastValidBlockHeight,
+ }).add(...ixs);
+
+ // Partial-sign with the mint keypair. The user's wallet adds the creator
+ // signature client-side before submission. After this serialize, the mint
+ // secret key is no longer needed and goes out of scope.
+ tx.partialSign(mintKeypair);
+
+ const txBase64 = tx
+ .serialize({ requireAllSignatures: false, verifySignatures: false })
+ .toString('base64');
+
+ // 5. Persist prep
+ const prepId = await randomToken(24);
+ const expiresAt = new Date(Date.now() + 30 * 60 * 1000);
+
+ await sql`
+ insert into token_launches_pending
+ (id, user_id, agent_id, provider, cluster, mint, metadata_uri, cid, payload, expires_at)
+ values (
+ ${prepId},
+ ${user.id},
+ ${agent.id},
+ 'pumpfun',
+ ${body.cluster},
+ ${mintKeypair.publicKey.toBase58()},
+ ${metadataUri},
+ ${cid},
+ ${JSON.stringify({
+ name: body.name,
+ symbol: body.symbol,
+ description: body.description,
+ image: body.image,
+ initial_buy_sol: body.initial_buy_sol,
+ wallet_address: body.wallet_address,
+ })}::jsonb,
+ ${expiresAt}
+ )
+ on conflict (id) do nothing
+ `;
+
+ return json(res, 201, {
+ prep_id: prepId,
+ mint: mintKeypair.publicKey.toBase58(),
+ tx_base64: txBase64,
+ metadata_uri: metadataUri,
+ cluster: body.cluster,
+ expires_at: expiresAt.toISOString(),
+ });
+});
+
+// Make sure SystemProgram import isn't tree-shaken away (some bundlers complain
+// about unused imports). It's a peer for compute-budget instructions on some
+// Pump.fun program versions.
+void SystemProgram;
diff --git a/api/cron/run-buyback.js b/api/cron/run-buyback.js
new file mode 100644
index 000000000..73ad3e56e
--- /dev/null
+++ b/api/cron/run-buyback.js
@@ -0,0 +1,148 @@
+// GET /api/cron/run-buyback
+//
+// For every agent mint with non-zero buybackVault balance, builds a
+// `buybackTrigger` ix that CPIs into pump-swap to swap currency → agent token
+// then burn. If PUMP_CRON_RELAYER_SECRET_KEY_B64 is set, signs + lands the tx;
+// otherwise persists unsigned txs for an external keeper.
+//
+// Auth: `Bearer $CRON_SECRET`.
+//
+// NOTE: swapInstructionData / remainingAccounts construction is swap-program-
+// specific. This implementation supports the empty-data "burn-only" form
+// (which the SDK accepts to skip the swap and just burn whatever is already
+// in the buyback vault denominated in the agent token). Full swap path is
+// gated behind PUMP_BUYBACK_FULL_SWAP=true and uses pump-swap-sdk to build
+// the inner ix.
+
+import { sql } from '../_lib/db.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import {
+ getPumpAgent,
+ getPumpAgentOffline,
+ getConnection,
+ buildUnsignedTxBase64,
+ solanaPubkey,
+} from '../_lib/pump.js';
+import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';
+
+async function loadRelayer() {
+ const b64 = process.env.PUMP_CRON_RELAYER_SECRET_KEY_B64;
+ if (!b64) return null;
+ const [{ Keypair }] = await Promise.all([import('@solana/web3.js')]);
+ return Keypair.fromSecretKey(Buffer.from(b64, 'base64'));
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const auth = req.headers.authorization || '';
+ if (!env.CRON_SECRET) return error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ if (auth !== `Bearer ${env.CRON_SECRET}`) {
+ return error(res, 401, 'unauthorized', 'cron auth required');
+ }
+
+ const fullSwap = process.env.PUMP_BUYBACK_FULL_SWAP === 'true';
+ const relayer = await loadRelayer();
+
+ const mints = await sql`
+ select id, mint, network from pump_agent_mints limit 200
+ `;
+
+ const results = [];
+ for (const m of mints) {
+ const currencyStr = m.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT;
+ const currency = solanaPubkey(currencyStr);
+
+ try {
+ const { agent } = await getPumpAgent({ network: m.network, mint: m.mint });
+ const balances = await agent.getBalances(currency);
+ const buyback = BigInt(balances.buybackVault?.balance ?? 0);
+
+ if (buyback === 0n) {
+ const [run] = await sql`
+ insert into pump_buyback_runs (mint_id, currency_mint, status)
+ values (${m.id}, ${currencyStr}, 'skipped') returning id
+ `;
+ results.push({ mint: m.mint, status: 'skipped', run_id: run.id });
+ continue;
+ }
+
+ const { offline } = await getPumpAgentOffline({ network: m.network, mint: m.mint });
+ const [{ PUMP_PROGRAM_ID }] = await Promise.all([
+ import('@pump-fun/agent-payments-sdk'),
+ ]);
+
+ const payerPk = relayer ? relayer.publicKey : solanaPubkey(m.mint);
+ const params = {
+ globalBuybackAuthority: payerPk, // gated by globalConfig — for skipped-swap form, can be relayer
+ currencyMint: currency,
+ swapProgramToInvoke: PUMP_PROGRAM_ID || payerPk, // sentinel program for skip-swap path
+ swapInstructionData: Buffer.alloc(0), // empty = skip swap, just burn
+ remainingAccounts: [],
+ };
+
+ if (fullSwap) {
+ // TODO(Phase 3.1): build pump-swap inner ix here. Skipping for safety;
+ // keepers should supply this off-chain until tested on devnet.
+ }
+
+ let ix;
+ try {
+ ix = await offline.buybackTrigger(params);
+ } catch (e) {
+ const [run] = await sql`
+ insert into pump_buyback_runs (mint_id, currency_mint, status, error)
+ values (${m.id}, ${currencyStr}, 'failed', ${'buybackTrigger build failed: ' + e.message})
+ returning id
+ `;
+ results.push({ mint: m.mint, status: 'failed', error: e.message, run_id: run.id });
+ continue;
+ }
+
+ if (!relayer) {
+ const txBase64 = await buildUnsignedTxBase64({
+ network: m.network,
+ payer: payerPk,
+ instructions: [ix],
+ });
+ const [run] = await sql`
+ insert into pump_buyback_runs (mint_id, currency_mint, status, burn_amount)
+ values (${m.id}, ${currencyStr}, 'pending', ${buyback.toString()})
+ returning id
+ `;
+ results.push({ mint: m.mint, status: 'pending', run_id: run.id, tx_base64: txBase64 });
+ continue;
+ }
+
+ const connection = getConnection({ network: m.network });
+ const [{ Transaction }] = await Promise.all([import('@solana/web3.js')]);
+ const tx = new Transaction();
+ tx.add(ix);
+ const { blockhash } = await connection.getLatestBlockhash('confirmed');
+ tx.recentBlockhash = blockhash;
+ tx.feePayer = relayer.publicKey;
+ tx.sign(relayer);
+ const sig = await connection.sendRawTransaction(tx.serialize());
+ await connection.confirmTransaction(sig, 'confirmed');
+
+ const [run] = await sql`
+ insert into pump_buyback_runs
+ (mint_id, currency_mint, tx_signature, status, burn_amount)
+ values
+ (${m.id}, ${currencyStr}, ${sig}, 'confirmed', ${buyback.toString()})
+ returning id
+ `;
+ results.push({ mint: m.mint, status: 'confirmed', tx_signature: sig, run_id: run.id });
+ } catch (err) {
+ await sql`
+ insert into pump_buyback_runs (mint_id, currency_mint, status, error)
+ values (${m.id}, ${currencyStr}, 'failed', ${err.message || String(err)})
+ `;
+ results.push({ mint: m.mint, status: 'failed', error: err.message });
+ }
+ }
+
+ return json(res, 200, { ok: true, processed: results.length, results });
+});
diff --git a/api/cron/run-distribute-payments.js b/api/cron/run-distribute-payments.js
new file mode 100644
index 000000000..897c38e68
--- /dev/null
+++ b/api/cron/run-distribute-payments.js
@@ -0,0 +1,153 @@
+// GET /api/cron/run-distribute-payments
+//
+// Permissionless: builds + (optionally) submits `distributePayments` for every
+// agent mint that has unrouted paymentVault balance. distribute is permissionless
+// per the SDK, so any signer works — we use the cron relayer keypair if set,
+// otherwise we just *prepare* and persist the unsigned tx for an external
+// keeper to land.
+//
+// Authorized via Vercel Cron `Bearer $CRON_SECRET` (see env.CRON_SECRET).
+
+import { sql } from '../_lib/db.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import {
+ getPumpAgent,
+ getPumpAgentOffline,
+ getConnection,
+ buildUnsignedTxBase64,
+ solanaPubkey,
+} from '../_lib/pump.js';
+import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';
+
+const CRON_RELAYER_SECRET_KEY_B64 = () => process.env.PUMP_CRON_RELAYER_SECRET_KEY_B64 || null;
+
+async function loadRelayer() {
+ const b64 = CRON_RELAYER_SECRET_KEY_B64();
+ if (!b64) return null;
+ const [{ Keypair }] = await Promise.all([import('@solana/web3.js')]);
+ return Keypair.fromSecretKey(Buffer.from(b64, 'base64'));
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ // Auth: cron secret OR admin bearer.
+ const auth = req.headers.authorization || '';
+ const cronSecret = env.CRON_SECRET;
+ if (!cronSecret) return error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ if (auth !== `Bearer ${cronSecret}`) {
+ return error(res, 401, 'unauthorized', 'cron auth required');
+ }
+
+ // Pick mints to consider: those with confirmed payments since last
+ // distribute run, or never run before.
+ const mints = await sql`
+ select m.id, m.mint, m.network, m.buyback_bps
+ from pump_agent_mints m
+ where exists (
+ select 1 from pump_agent_payments p
+ where p.mint_id = m.id and p.status = 'confirmed'
+ and (
+ p.confirmed_at > coalesce(
+ (select max(created_at) from pump_distribute_runs r where r.mint_id = m.id),
+ 'epoch'::timestamptz
+ )
+ )
+ )
+ limit 200
+ `;
+
+ const relayer = await loadRelayer();
+ const results = [];
+
+ for (const m of mints) {
+ const currencyStr = m.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT;
+ const currency = solanaPubkey(currencyStr);
+
+ try {
+ const { agent } = await getPumpAgent({ network: m.network, mint: m.mint });
+ const balancesBefore = await agent.getBalances(currency);
+ const paymentBalance = BigInt(balancesBefore.paymentVault.balance ?? 0);
+
+ if (paymentBalance === 0n) {
+ const [run] = await sql`
+ insert into pump_distribute_runs (mint_id, currency_mint, status, balances_before)
+ values (${m.id}, ${currencyStr}, 'skipped', ${JSON.stringify({ payment: paymentBalance.toString() })}::jsonb)
+ returning id
+ `;
+ results.push({ mint: m.mint, status: 'skipped', run_id: run.id });
+ continue;
+ }
+
+ const { offline } = await getPumpAgentOffline({ network: m.network, mint: m.mint });
+
+ if (!relayer) {
+ // No relayer: build unsigned tx for an external keeper. Persist run as 'pending'.
+ const ixs = await offline.distributePayments({
+ user: solanaPubkey(process.env.PUMP_DISTRIBUTE_FALLBACK_PAYER || m.mint),
+ currencyMint: currency,
+ });
+ const txBase64 = await buildUnsignedTxBase64({
+ network: m.network,
+ payer: solanaPubkey(process.env.PUMP_DISTRIBUTE_FALLBACK_PAYER || m.mint),
+ instructions: Array.isArray(ixs) ? ixs : [ixs],
+ });
+ const [run] = await sql`
+ insert into pump_distribute_runs (mint_id, currency_mint, status, balances_before)
+ values (${m.id}, ${currencyStr}, 'pending', ${JSON.stringify({ payment: paymentBalance.toString() })}::jsonb)
+ returning id
+ `;
+ results.push({ mint: m.mint, status: 'pending', run_id: run.id, tx_base64: txBase64 });
+ continue;
+ }
+
+ // Relayer path: sign + send.
+ const ixs = await offline.distributePayments({
+ user: relayer.publicKey,
+ currencyMint: currency,
+ });
+ const connection = getConnection({ network: m.network });
+ const [{ Transaction }] = await Promise.all([import('@solana/web3.js')]);
+ const tx = new Transaction();
+ tx.add(...(Array.isArray(ixs) ? ixs : [ixs]));
+ const { blockhash } = await connection.getLatestBlockhash('confirmed');
+ tx.recentBlockhash = blockhash;
+ tx.feePayer = relayer.publicKey;
+ tx.sign(relayer);
+ const sig = await connection.sendRawTransaction(tx.serialize(), {
+ skipPreflight: false,
+ });
+ await connection.confirmTransaction(sig, 'confirmed');
+
+ const balancesAfter = await agent.getBalances(currency);
+ const [run] = await sql`
+ insert into pump_distribute_runs
+ (mint_id, currency_mint, tx_signature, status, balances_before, balances_after)
+ values
+ (${m.id}, ${currencyStr}, ${sig}, 'confirmed',
+ ${JSON.stringify({ payment: paymentBalance.toString() })}::jsonb,
+ ${JSON.stringify({
+ buyback: balancesAfter.buybackVault?.balance?.toString?.(),
+ withdraw: balancesAfter.withdrawVault?.balance?.toString?.(),
+ })}::jsonb)
+ returning id
+ `;
+ results.push({ mint: m.mint, status: 'confirmed', tx_signature: sig, run_id: run.id });
+ } catch (err) {
+ await sql`
+ insert into pump_distribute_runs (mint_id, currency_mint, status, error)
+ values (${m.id}, ${currencyStr}, 'failed', ${err.message || String(err)})
+ `;
+ results.push({ mint: m.mint, status: 'failed', error: err.message });
+ }
+ }
+
+ return json(res, 200, {
+ ok: true,
+ processed: results.length,
+ relayer: relayer ? relayer.publicKey.toBase58() : null,
+ results,
+ });
+});
diff --git a/api/pump/accept-payment-confirm.js b/api/pump/accept-payment-confirm.js
new file mode 100644
index 000000000..436db819b
--- /dev/null
+++ b/api/pump/accept-payment-confirm.js
@@ -0,0 +1,65 @@
+// POST /api/pump/accept-payment-confirm
+// Verify the acceptPayment tx landed; mark the payment row confirmed.
+
+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 { verifySignature } from '../_lib/pump.js';
+
+const bodySchema = z.object({
+ payment_id: z.string().uuid(),
+ tx_signature: z.string().min(80).max(100),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'auth required');
+
+ 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 [payment] = await sql`
+ select p.*, m.mint, m.network from pump_agent_payments p
+ join pump_agent_mints m on m.id = p.mint_id
+ where p.id=${body.payment_id} limit 1
+ `;
+ if (!payment) return error(res, 404, 'not_found', 'payment not found');
+ if (payment.status === 'confirmed')
+ return error(res, 409, 'already_confirmed', 'payment already confirmed');
+
+ let tx;
+ try {
+ tx = await verifySignature({ network: payment.network, signature: body.tx_signature });
+ } catch (e) {
+ await sql`update pump_agent_payments set status='failed' where id=${payment.id}`;
+ return error(res, e.status || 422, e.code || 'tx_failed', e.message);
+ }
+
+ const accountKeys = tx.transaction.message.accountKeys.map((k) =>
+ (k.pubkey || k).toString(),
+ );
+ if (!accountKeys.includes(payment.mint)) {
+ return error(res, 422, 'mint_not_in_tx', 'agent mint not in tx accounts');
+ }
+
+ await sql`
+ update pump_agent_payments
+ set status='confirmed', tx_signature=${body.tx_signature}, confirmed_at=now()
+ where id=${payment.id}
+ `;
+
+ return json(res, 200, {
+ ok: true,
+ payment_id: payment.id,
+ invoice_id: payment.invoice_id,
+ tx_signature: body.tx_signature,
+ });
+});
diff --git a/api/pump/accept-payment-prep.js b/api/pump/accept-payment-prep.js
new file mode 100644
index 000000000..18388c421
--- /dev/null
+++ b/api/pump/accept-payment-prep.js
@@ -0,0 +1,136 @@
+// POST /api/pump/accept-payment-prep
+//
+// Builds the unsigned tx for `acceptPayment` against an agent's
+// pump-agent-payments PDA. Caller (the payer) signs + submits. Used as the
+// pump-native settle step for X402-gated resources (see /.well-known/x402).
+
+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 { randomToken } from '../_lib/crypto.js';
+import {
+ getPumpAgentOffline,
+ buildUnsignedTxBase64,
+ solanaPubkey,
+} from '../_lib/pump.js';
+import {
+ SOLANA_USDC_MINT,
+ SOLANA_USDC_MINT_DEVNET,
+ toUsdcAtomics,
+} from '../payments/_config.js';
+
+const bodySchema = z.object({
+ mint: z.string().min(32).max(44), // pump.fun token mint = agent token
+ payer_wallet: z.string().min(32).max(44),
+ amount_usdc: z.number().positive().max(100_000),
+ currency_mint: z.string().min(32).max(44).optional(), // defaults to USDC
+ currency_token_program: z.string().min(32).max(44).optional(),
+ user_token_account: z.string().min(32).max(44), // payer ATA
+ skill_id: z.string().max(100).optional(),
+ tool_name: z.string().max(100).optional(),
+ duration_seconds: z.number().int().positive().max(60 * 60 * 24 * 365).default(60),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+function bnFromBigint(BN, v) {
+ return new BN(v.toString());
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ // Allow both session users (browser) and bearer (MCP / agent) callers.
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer)
+ return error(res, 401, 'unauthorized', 'sign in or supply a bearer token');
+ const userId = session?.id ?? bearer?.userId ?? null;
+
+ 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 payer = solanaPubkey(body.payer_wallet);
+ const userAta = solanaPubkey(body.user_token_account);
+ if (!payer) return error(res, 400, 'validation_error', 'invalid payer_wallet');
+ if (!userAta) return error(res, 400, 'validation_error', 'invalid user_token_account');
+
+ const [agent] = await sql`
+ select id, mint, network, buyback_bps from pump_agent_mints
+ where mint=${body.mint} and network=${body.network} limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent mint not registered');
+
+ const currencyStr =
+ body.currency_mint ||
+ (body.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT);
+ const currency = solanaPubkey(currencyStr);
+ if (!currency) return error(res, 400, 'validation_error', 'invalid currency_mint');
+
+ const { offline, BN } = await getPumpAgentOffline({
+ network: body.network,
+ mint: body.mint,
+ });
+
+ // Invoice ID = random 64-bit unsigned (memo BN). Used as the PDA seed and
+ // as the X402 receipt identifier downstream.
+ const invoiceIdHex = (await randomToken(8)).slice(0, 16);
+ const invoiceId = new BN(invoiceIdHex, 16);
+
+ const startTime = Math.floor(Date.now() / 1000);
+ const endTime = startTime + body.duration_seconds;
+
+ const amountAtomics = toUsdcAtomics(body.amount_usdc); // bigint, USDC = 6 dp
+
+ const tokenProgram = body.currency_token_program
+ ? solanaPubkey(body.currency_token_program)
+ : undefined;
+
+ const ix = await offline.acceptPayment({
+ user: payer,
+ userTokenAccount: userAta,
+ currencyMint: currency,
+ amount: bnFromBigint(BN, amountAtomics),
+ memo: invoiceId,
+ startTime: new BN(startTime),
+ endTime: new BN(endTime),
+ ...(tokenProgram ? { tokenProgram } : {}),
+ });
+
+ const txBase64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer,
+ instructions: [ix],
+ });
+
+ const [row] = await sql`
+ insert into pump_agent_payments
+ (mint_id, user_id, payer_wallet, currency_mint, amount_atomics,
+ invoice_id, start_time, end_time, status, skill_id, tool_name)
+ values
+ (${agent.id}, ${userId}, ${body.payer_wallet}, ${currencyStr},
+ ${amountAtomics.toString()}, ${invoiceId.toString()},
+ to_timestamp(${startTime}), to_timestamp(${endTime}),
+ 'pending', ${body.skill_id || null}, ${body.tool_name || null})
+ returning id, invoice_id, start_time, end_time, status
+ `;
+
+ return json(res, 201, {
+ payment_id: row.id,
+ mint: body.mint,
+ invoice_id: invoiceId.toString(),
+ amount_usdc: body.amount_usdc,
+ amount_atomics: amountAtomics.toString(),
+ currency_mint: currencyStr,
+ start_time: row.start_time,
+ end_time: row.end_time,
+ network: body.network,
+ tx_base64: txBase64,
+ instructions:
+ 'Decode tx_base64, sign with payer wallet, submit, then call /api/pump/accept-payment-confirm with the tx_signature and payment_id.',
+ });
+});
diff --git a/api/pump/balances.js b/api/pump/balances.js
new file mode 100644
index 000000000..8d9411d3d
--- /dev/null
+++ b/api/pump/balances.js
@@ -0,0 +1,57 @@
+// GET /api/pump/balances?mint=<pubkey>&currency=<mint>&network=...
+//
+// Three vault balances for an agent that has been bound to pump-agent-payments:
+// paymentVault — incoming counterparty payments
+// buybackVault — share routed to buyback (deflationary)
+// withdrawVault — share the agent owner can sweep
+// All denominated in `currency` (USDC by default).
+
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getPumpAgent, solanaPubkey } from '../_lib/pump.js';
+import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';
+
+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.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const mintStr = url.searchParams.get('mint');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const currencyArg = url.searchParams.get('currency');
+
+ const mint = solanaPubkey(mintStr);
+ if (!mint) return error(res, 400, 'validation_error', 'invalid mint');
+
+ const currencyStr =
+ currencyArg || (network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT);
+ const currency = solanaPubkey(currencyStr);
+ if (!currency) return error(res, 400, 'validation_error', 'invalid currency');
+
+ try {
+ const { agent, agentPda } = await getPumpAgent({ network, mint });
+ const balances = await agent.getBalances(currency);
+ const fmt = (v) =>
+ v && {
+ address: v.address?.toString?.() ?? String(v.address),
+ balance: v.balance?.toString?.() ?? String(v.balance ?? 0),
+ };
+ return json(res, 200, {
+ mint: mintStr,
+ network,
+ currency: currencyStr,
+ agent_pda: agentPda?.toString?.() ?? null,
+ balances: {
+ payment: fmt(balances.paymentVault),
+ buyback: fmt(balances.buybackVault),
+ withdraw: fmt(balances.withdrawVault),
+ },
+ });
+ } catch (err) {
+ // Most common: agent not yet bound to mint → PDA missing.
+ return error(res, 502, 'pump_agent_error', err.message || 'pump-agent SDK error');
+ }
+});
diff --git a/api/pump/governance-prep.js b/api/pump/governance-prep.js
new file mode 100644
index 000000000..6136d87b2
--- /dev/null
+++ b/api/pump/governance-prep.js
@@ -0,0 +1,72 @@
+// POST /api/pump/governance-prep
+//
+// Builds an unsigned `updateBuybackBps` ix for the agent owner. Frontend signs
+// + submits with the agent authority wallet. Reputation-tied governance hook:
+// admins can also drive this from server via PUMP_GOVERNANCE_RELAYER_KEY (off
+// by default) when an agent's reputation drops below threshold — we expose
+// that path as POST /api/admin/pump/governance instead, separately.
+
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+import { getSessionUser } 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 {
+ getPumpAgentOffline,
+ buildUnsignedTxBase64,
+ solanaPubkey,
+} from '../_lib/pump.js';
+
+const bodySchema = z.object({
+ mint: z.string().min(32).max(44),
+ authority_wallet: z.string().min(32).max(44),
+ new_buyback_bps: z.number().int().min(0).max(10_000),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) 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 = parse(bodySchema, await readJson(req));
+ const authority = solanaPubkey(body.authority_wallet);
+ if (!authority) return error(res, 400, 'validation_error', 'invalid authority_wallet');
+
+ const [row] = await sql`
+ select id, user_id, agent_authority from pump_agent_mints
+ where mint=${body.mint} and network=${body.network} limit 1
+ `;
+ if (!row) return error(res, 404, 'not_found', 'agent mint not registered');
+ if (row.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');
+ if (row.agent_authority && row.agent_authority !== body.authority_wallet) {
+ return error(res, 403, 'forbidden', 'authority does not match');
+ }
+
+ const { offline } = await getPumpAgentOffline({ network: body.network, mint: body.mint });
+ const ix = await offline.updateBuybackBps(
+ { authority, buybackBps: body.new_buyback_bps },
+ {}, // UpdateBuybackBpsOptions — empty default
+ );
+
+ const txBase64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: authority,
+ instructions: [ix],
+ });
+
+ return json(res, 201, {
+ mint: body.mint,
+ network: body.network,
+ new_buyback_bps: body.new_buyback_bps,
+ tx_base64: txBase64,
+ instructions:
+ 'Sign with the agent authority wallet, submit, then optionally PATCH the local row via /api/agents/:id to refresh display.',
+ });
+});
diff --git a/api/pump/launch-confirm.js b/api/pump/launch-confirm.js
new file mode 100644
index 000000000..2b697830b
--- /dev/null
+++ b/api/pump/launch-confirm.js
@@ -0,0 +1,73 @@
+// POST /api/pump/launch-confirm
+// Verifies the launch tx landed and persists the pump_agent_mints row.
+
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+import { getSessionUser } 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 { verifySignature } from '../_lib/pump.js';
+
+const bodySchema = z.object({
+ prep_id: z.string().min(8),
+ tx_signature: z.string().min(80).max(100),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) 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 = parse(bodySchema, await readJson(req));
+
+ const [pending] = await sql`
+ select id, payload from agent_registrations_pending
+ where user_id=${user.id} and payload->>'prep_id'=${body.prep_id}
+ and expires_at > now()
+ order by created_at desc limit 1
+ `;
+ if (!pending) return error(res, 404, 'not_found', 'prep not found or expired');
+ const p = pending.payload;
+ if (p.kind !== 'pump_launch') return error(res, 400, 'wrong_kind', 'prep is not a pump launch');
+
+ let tx;
+ try {
+ tx = await verifySignature({ network: p.network, signature: body.tx_signature });
+ } catch (e) {
+ return error(res, e.status || 422, e.code || 'tx_failed', e.message);
+ }
+ const accountKeys = tx.transaction.message.accountKeys.map((k) =>
+ (k.pubkey || k).toString(),
+ );
+ if (!accountKeys.includes(p.mint)) {
+ return error(res, 422, 'mint_not_in_tx', 'mint pubkey not present in tx');
+ }
+
+ const [existing] = await sql`
+ select id from pump_agent_mints where mint=${p.mint} and network=${p.network} limit 1
+ `;
+ if (existing) return error(res, 409, 'conflict', 'mint already registered');
+
+ const [row] = await sql`
+ insert into pump_agent_mints
+ (agent_id, user_id, network, mint, name, symbol, agent_authority, buyback_bps)
+ values
+ (${p.agent_id}, ${user.id}, ${p.network}, ${p.mint},
+ ${p.name}, ${p.symbol}, ${p.wallet_address}, ${p.buyback_bps})
+ returning id, mint, network, buyback_bps, created_at
+ `;
+
+ await sql`delete from agent_registrations_pending where id=${pending.id}`;
+
+ return json(res, 201, {
+ ok: true,
+ pump_agent_mint: row,
+ tx_signature: body.tx_signature,
+ });
+});
diff --git a/api/pump/launch-prep.js b/api/pump/launch-prep.js
new file mode 100644
index 000000000..9c9a9cbb3
--- /dev/null
+++ b/api/pump/launch-prep.js
@@ -0,0 +1,158 @@
+// POST /api/pump/launch-prep
+//
+// Builds an unsigned transaction that:
+// 1. creates a pump.fun bonding-curve token (createInstruction or
+// createAndBuyInstructions if `sol_buy_in` > 0)
+// 2. binds it to a pump-agent-payments PDA via PumpAgent.create with the
+// caller's chosen buybackBps
+//
+// The user signs + submits in their wallet, then calls launch-confirm.
+
+import { z } from 'zod';
+import { Keypair } from '@solana/web3.js';
+import { sql } from '../_lib/db.js';
+import { getSessionUser } 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 { randomToken } from '../_lib/crypto.js';
+import {
+ getPumpSdk,
+ getPumpAgentOffline,
+ buildUnsignedTxBase64,
+ solanaPubkey,
+} from '../_lib/pump.js';
+
+const bodySchema = z.object({
+ agent_id: z.string().uuid(),
+ wallet_address: z.string().min(32).max(44),
+ name: z.string().trim().min(1).max(32),
+ symbol: z.string().trim().min(1).max(10),
+ uri: z.string().url(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ buyback_bps: z.number().int().min(0).max(10_000).default(0),
+ sol_buy_in: z.number().nonnegative().max(50).default(0), // optional creator initial buy, capped 50 SOL
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) 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 = parse(bodySchema, await readJson(req));
+ const creator = solanaPubkey(body.wallet_address);
+ if (!creator) return error(res, 400, 'validation_error', 'invalid wallet_address');
+
+ // Verify wallet linked to user.
+ const [walletRow] = await sql`
+ select id from user_wallets
+ where user_id=${user.id} and address=${body.wallet_address} and chain_type='solana'
+ limit 1
+ `;
+ if (!walletRow) return error(res, 403, 'forbidden', 'wallet not linked to your account');
+
+ // Verify the agent belongs to this user.
+ const [agent] = await sql`
+ select id, name from agent_identities
+ where id=${body.agent_id} and user_id=${user.id} and deleted_at is null limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ // Generate fresh mint keypair. Frontend must include it as an additional
+ // signer when submitting (we return the secret key b64).
+ const mintKeypair = Keypair.generate();
+ const mint = mintKeypair.publicKey;
+
+ const { sdk, BN } = await getPumpSdk({ network: body.network });
+ const LAMPORTS_PER_SOL = 1_000_000_000;
+
+ const instructions = [];
+ if (body.sol_buy_in > 0 && sdk.createAndBuyInstructions) {
+ const global = await sdk.fetchGlobal();
+ const solAmount = new BN(Math.floor(body.sol_buy_in * LAMPORTS_PER_SOL));
+ const pumpSdk = await import('@pump-fun/pump-sdk');
+ const tokenAmount = pumpSdk.getBuyTokenAmountFromSolAmount(global, null, solAmount);
+ const ixs = await sdk.createAndBuyInstructions({
+ global,
+ mint,
+ name: body.name,
+ symbol: body.symbol,
+ uri: body.uri,
+ creator,
+ user: creator,
+ solAmount,
+ amount: tokenAmount,
+ });
+ instructions.push(...(Array.isArray(ixs) ? ixs : [ixs]));
+ } else {
+ const ix = await sdk.createInstruction({
+ mint,
+ name: body.name,
+ symbol: body.symbol,
+ uri: body.uri,
+ creator,
+ user: creator,
+ });
+ instructions.push(ix);
+ }
+
+ // Bind PumpAgent.create.
+ if (body.buyback_bps > 0) {
+ const { offline } = await getPumpAgentOffline({ network: body.network, mint });
+ const createIx = await offline.create({
+ authority: creator,
+ mint,
+ agentAuthority: creator,
+ buybackBps: body.buyback_bps,
+ });
+ instructions.push(createIx);
+ }
+
+ const txBase64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: creator,
+ instructions,
+ });
+
+ const prepId = await randomToken(24);
+ const expiresAt = new Date(Date.now() + 30 * 60 * 1000);
+
+ await sql`
+ insert into agent_registrations_pending (user_id, cid, metadata_uri, payload, expires_at)
+ values (
+ ${user.id},
+ ${mint.toBase58()},
+ ${body.uri},
+ ${JSON.stringify({
+ kind: 'pump_launch',
+ agent_id: body.agent_id,
+ wallet_address: body.wallet_address,
+ mint: mint.toBase58(),
+ name: body.name,
+ symbol: body.symbol,
+ network: body.network,
+ buyback_bps: body.buyback_bps,
+ prep_id: prepId,
+ })}::jsonb,
+ ${expiresAt}
+ )
+ `;
+
+ return json(res, 201, {
+ prep_id: prepId,
+ mint: mint.toBase58(),
+ // Mint keypair must co-sign the tx — frontend appends it before submit.
+ mint_secret_key_b64: Buffer.from(mintKeypair.secretKey).toString('base64'),
+ tx_base64: txBase64,
+ network: body.network,
+ buyback_bps: body.buyback_bps,
+ expires_at: expiresAt.toISOString(),
+ instructions:
+ 'Decode tx_base64 as VersionedTransaction. Sign with the mint keypair (mint_secret_key_b64) AND the user wallet, submit, then POST /api/pump/launch-confirm with the tx_signature.',
+ });
+});
diff --git a/api/pump/payments-list.js b/api/pump/payments-list.js
new file mode 100644
index 000000000..0b421ccd2
--- /dev/null
+++ b/api/pump/payments-list.js
@@ -0,0 +1,67 @@
+// GET /api/pump/payments-list?mint=<pubkey>&network=...&limit=...
+//
+// Public read of the local pump_agent_payments index for an agent. The
+// on-chain TokenAgentPaymentInCurrency PDAs are the source of truth; this
+// endpoint exposes the cached view used by the dashboard / passport / and
+// reputation engine. Confirmed payments only by default.
+
+import { sql } from '../_lib/db.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+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.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const mint = url.searchParams.get('mint');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const limit = Math.min(Number(url.searchParams.get('limit') || 50), 500);
+ const includePending = url.searchParams.get('include_pending') === '1';
+
+ if (!mint) return error(res, 400, 'validation_error', 'mint required');
+
+ const [agent] = await sql`
+ select id, mint, network, buyback_bps from pump_agent_mints
+ where mint=${mint} and network=${network} limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent mint not registered');
+
+ const rows = includePending
+ ? await sql`
+ select id, payer_wallet, currency_mint, amount_atomics, invoice_id,
+ start_time, end_time, status, skill_id, tool_name,
+ tx_signature, created_at, confirmed_at
+ from pump_agent_payments
+ where mint_id=${agent.id}
+ order by created_at desc limit ${limit}
+ `
+ : await sql`
+ select id, payer_wallet, currency_mint, amount_atomics, invoice_id,
+ start_time, end_time, status, skill_id, tool_name,
+ tx_signature, created_at, confirmed_at
+ from pump_agent_payments
+ where mint_id=${agent.id} and status='confirmed'
+ order by confirmed_at desc nulls last limit ${limit}
+ `;
+
+ const [agg] = await sql`
+ select
+ count(*)::int as total,
+ count(*) filter (where status='confirmed')::int as confirmed,
+ count(distinct payer_wallet) filter (where status='confirmed')::int as unique_payers,
+ coalesce(sum(amount_atomics) filter (where status='confirmed'), 0)::text as total_atomics
+ from pump_agent_payments where mint_id=${agent.id}
+ `;
+
+ return json(res, 200, {
+ mint,
+ network,
+ buyback_bps: agent.buyback_bps,
+ summary: agg,
+ data: rows,
+ });
+});
diff --git a/api/pump/quote.js b/api/pump/quote.js
new file mode 100644
index 000000000..40cf96631
--- /dev/null
+++ b/api/pump/quote.js
@@ -0,0 +1,112 @@
+// GET /api/pump/quote?mint=<pubkey>&network=mainnet|devnet&sol=<amount>&direction=buy|sell
+//
+// Read-only price/quote for a pump.fun token. Auto-routes between bonding-curve
+// (pre-graduation) via @pump-fun/pump-sdk and AMM (post-graduation) via
+// @pump-fun/pump-swap-sdk. No wallet, no signing.
+
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getPumpSdk, getPumpSwapSdk, solanaPubkey } from '../_lib/pump.js';
+
+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.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const mintStr = url.searchParams.get('mint');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const direction = url.searchParams.get('direction') === 'sell' ? 'sell' : 'buy';
+ const solRaw = url.searchParams.get('sol');
+ const tokenRaw = url.searchParams.get('token');
+
+ const mint = solanaPubkey(mintStr);
+ if (!mint) return error(res, 400, 'validation_error', 'invalid mint');
+
+ try {
+ // Try bonding curve first.
+ const { sdk, BN, web3 } = await getPumpSdk({ network });
+ const LAMPORTS_PER_SOL = web3.LAMPORTS_PER_SOL || 1_000_000_000;
+
+ let curve = null;
+ try {
+ if (sdk.fetchBuyState) {
+ const state = await sdk.fetchBuyState(mint, mint); // any pubkey works for read
+ curve = state.bondingCurve;
+ } else if (sdk.fetchBondingCurve) {
+ curve = await sdk.fetchBondingCurve(mint);
+ }
+ } catch {
+ curve = null;
+ }
+
+ if (curve && !curve.complete) {
+ const global =
+ typeof sdk.fetchGlobal === 'function' ? await sdk.fetchGlobal() : null;
+ const pumpSdk = await import('@pump-fun/pump-sdk');
+ let quote = null;
+
+ if (direction === 'buy' && solRaw) {
+ const sol = Number(solRaw);
+ if (!(sol > 0)) return error(res, 400, 'validation_error', 'sol must be > 0');
+ const lamports = new BN(Math.floor(sol * LAMPORTS_PER_SOL));
+ const tokens = pumpSdk.getBuyTokenAmountFromSolAmount(global, curve, lamports);
+ quote = { sol_in: sol, tokens_out: tokens.toString(), source: 'bonding_curve' };
+ } else if (direction === 'sell' && tokenRaw) {
+ const tokens = new BN(tokenRaw);
+ const lamports = pumpSdk.getSellSolAmountFromTokenAmount(global, curve, tokens);
+ quote = {
+ tokens_in: tokenRaw,
+ sol_out: Number(lamports.toString()) / LAMPORTS_PER_SOL,
+ source: 'bonding_curve',
+ };
+ }
+
+ return json(res, 200, {
+ mint: mintStr,
+ network,
+ graduated: false,
+ bonding_curve: {
+ real_sol_reserves: curve.realSolReserves?.toString?.() ?? null,
+ real_token_reserves: curve.realTokenReserves?.toString?.() ?? null,
+ virtual_sol_reserves: curve.virtualSolReserves?.toString?.() ?? null,
+ virtual_token_reserves: curve.virtualTokenReserves?.toString?.() ?? null,
+ complete: curve.complete ?? false,
+ },
+ quote,
+ });
+ }
+
+ // Post-graduation: AMM
+ const { sdk: ammSdk, BN: BN2 } = await getPumpSwapSdk({ network });
+ // Find pool for this mint vs WSOL (or USDC). Pool discovery is left to
+ // caller for now — if not implemented, return graduated:true with no quote.
+ let pool = null;
+ try {
+ if (ammSdk.findPoolByMint) {
+ pool = await ammSdk.findPoolByMint(mint);
+ }
+ } catch {
+ pool = null;
+ }
+
+ return json(res, 200, {
+ mint: mintStr,
+ network,
+ graduated: true,
+ pool: pool
+ ? {
+ address: pool.address?.toString?.() ?? String(pool.address),
+ base: pool.baseMint?.toString?.() ?? null,
+ quote: pool.quoteMint?.toString?.() ?? null,
+ }
+ : null,
+ quote: null,
+ note: pool ? null : 'Post-graduation pool lookup requires explicit pool key',
+ });
+ } catch (err) {
+ return error(res, 502, 'pump_sdk_error', err.message || 'pump.fun SDK error');
+ }
+});
diff --git a/api/pump/withdraw-prep.js b/api/pump/withdraw-prep.js
new file mode 100644
index 000000000..3cf09f26a
--- /dev/null
+++ b/api/pump/withdraw-prep.js
@@ -0,0 +1,86 @@
+// POST /api/pump/withdraw-prep
+// Builds an unsigned `withdraw` ix the agent owner signs to sweep withdrawVault.
+
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+import { getSessionUser } 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 {
+ getPumpAgentOffline,
+ buildUnsignedTxBase64,
+ solanaPubkey,
+} from '../_lib/pump.js';
+import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';
+
+const bodySchema = z.object({
+ mint: z.string().min(32).max(44),
+ authority_wallet: z.string().min(32).max(44),
+ receiver_ata: z.string().min(32).max(44),
+ currency_mint: z.string().min(32).max(44).optional(),
+ currency_token_program: z.string().min(32).max(44).optional(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) 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 = parse(bodySchema, await readJson(req));
+ const authority = solanaPubkey(body.authority_wallet);
+ const receiverAta = solanaPubkey(body.receiver_ata);
+ if (!authority || !receiverAta)
+ return error(res, 400, 'validation_error', 'invalid pubkeys');
+
+ const [row] = await sql`
+ select m.id, m.mint, m.user_id, m.agent_authority, m.network from pump_agent_mints m
+ where m.mint=${body.mint} and m.network=${body.network} limit 1
+ `;
+ if (!row) return error(res, 404, 'not_found', 'agent mint not registered');
+ if (row.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');
+ if (row.agent_authority && row.agent_authority !== body.authority_wallet) {
+ return error(res, 403, 'forbidden', 'authority does not match');
+ }
+
+ const currencyStr =
+ body.currency_mint ||
+ (body.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT);
+ const currency = solanaPubkey(currencyStr);
+ if (!currency) return error(res, 400, 'validation_error', 'invalid currency_mint');
+
+ const { offline } = await getPumpAgentOffline({
+ network: body.network,
+ mint: body.mint,
+ });
+
+ const tokenProgram = body.currency_token_program
+ ? solanaPubkey(body.currency_token_program)
+ : undefined;
+
+ const ix = await offline.withdraw({
+ authority,
+ currencyMint: currency,
+ receiverAta,
+ ...(tokenProgram ? { tokenProgram } : {}),
+ });
+
+ const txBase64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: authority,
+ instructions: [ix],
+ });
+
+ return json(res, 201, {
+ mint: body.mint,
+ network: body.network,
+ currency_mint: currencyStr,
+ tx_base64: txBase64,
+ });
+});
diff --git a/examples/skills/pump-fun-compose/SKILL.md b/examples/skills/pump-fun-compose/SKILL.md
new file mode 100644
index 000000000..30a3689ed
--- /dev/null
+++ b/examples/skills/pump-fun-compose/SKILL.md
@@ -0,0 +1,37 @@
+# pump-fun-compose
+
+Agent-level loops that compose `pump-fun` (read) and `pump-fun-trade` (sign).
+
+| Tool | Loop |
+|---|---|
+| `researchAndBuy` | search → vet (curve, holders, creator) → quote → buy |
+| `autoSnipe` | poll new tokens → vet → buy until session cap |
+| `copyTrade` | watch a wallet's recent buys → mirror with size scaling |
+| `rugExitWatch` | watch held mints → sell on concentration or dev-sell triggers |
+
+## Filters (manifest.config)
+
+- `minHoldersForBuy` — reject thin books
+- `maxTopHolderPct` — reject whale-controlled supplies
+- `rejectIfCreatorRugCount` — reject repeat ruggers
+- `exitOnConcentrationPct` / `exitOnDevSellPct` — exit triggers
+- `sessionSpendCapSol` / `perTradeSol` — hard spend caps
+
+## Wiring
+
+The host runtime injects:
+
+- `ctx.skills.invoke('skill.tool', args)` — sibling-skill calls
+- `ctx.wallet` — used by the trade skill (this one never touches keys directly)
+- `ctx.memory.note` — every action is auditable
+
+## Composition example
+
+```js
+await ctx.skills.invoke('pump-fun-compose.autoSnipe', { durationSec: 600 });
+// then babysit positions
+await ctx.skills.invoke('pump-fun-compose.rugExitWatch', {
+ mints: heldMints,
+ durationSec: 3600,
+});
+```
diff --git a/examples/skills/pump-fun-compose/handlers.js b/examples/skills/pump-fun-compose/handlers.js
new file mode 100644
index 000000000..16bcb645e
--- /dev/null
+++ b/examples/skills/pump-fun-compose/handlers.js
@@ -0,0 +1,160 @@
+// pump-fun-compose — agent-level loops over the read + trade skills.
+// All sibling-skill calls go through ctx.skills.invoke('skill.tool', args).
+
+function cfg(ctx, key, fallback) {
+ return ctx?.skillConfig?.[key] ?? fallback;
+}
+
+async function call(ctx, tool, args) {
+ const res = await ctx.skills.invoke(tool, args);
+ if (!res?.ok) throw new Error(`${tool} failed: ${res?.error ?? 'unknown'}`);
+ return res.data;
+}
+
+function passesFilters(ctx, { creator, holders }) {
+ const rugCount = creator?.rugCount ?? creator?.rugFlags?.length ?? 0;
+ if (rugCount >= cfg(ctx, 'rejectIfCreatorRugCount', 1)) {
+ return { ok: false, reason: `creator has ${rugCount} prior rug(s)` };
+ }
+ const holderCount = holders?.total ?? holders?.holders?.length ?? 0;
+ if (holderCount < cfg(ctx, 'minHoldersForBuy', 30)) {
+ return { ok: false, reason: `only ${holderCount} holders` };
+ }
+ const top = holders?.topHolderPct ?? holders?.holders?.[0]?.pct ?? 0;
+ if (top > cfg(ctx, 'maxTopHolderPct', 25)) {
+ return { ok: false, reason: `top holder owns ${top}%` };
+ }
+ return { ok: true };
+}
+
+async function vetMint(ctx, mint) {
+ const [details, holders] = await Promise.all([
+ call(ctx, 'pump-fun.getTokenDetails', { mint }),
+ call(ctx, 'pump-fun.getTokenHolders', { mint, limit: 20 }),
+ ]);
+ const creatorAddr = details?.creator ?? details?.token?.creator;
+ const creator = creatorAddr
+ ? await call(ctx, 'pump-fun.getCreatorProfile', { creator: creatorAddr })
+ : { rugCount: 0 };
+ return { details, holders, creator, verdict: passesFilters(ctx, { creator, holders }) };
+}
+
+export async function researchAndBuy(args, ctx) {
+ const search = await call(ctx, 'pump-fun.searchTokens', { query: args.query, limit: 1 });
+ const mint = search?.results?.[0]?.mint ?? search?.[0]?.mint ?? args.query;
+ const vet = await vetMint(ctx, mint);
+ if (!vet.verdict.ok) return { ok: true, data: { mint, decision: 'skip', reason: vet.verdict.reason } };
+
+ const amountSol = args.amountSol ?? cfg(ctx, 'perTradeSol', 0.05);
+ const quote = await call(ctx, 'pump-fun-trade.quoteTrade', { mint, side: 'buy', amountSol });
+ const buy = await call(ctx, 'pump-fun-trade.buyToken', { mint, amountSol });
+ return { ok: true, data: { mint, decision: 'buy', quote, sig: buy.sig } };
+}
+
+export async function autoSnipe(args, ctx) {
+ const deadline = Date.now() + args.durationSec * 1000;
+ const perTrade = args.perTradeSol ?? cfg(ctx, 'perTradeSol', 0.05);
+ const cap = cfg(ctx, 'sessionSpendCapSol', 1.0);
+ const seen = new Set();
+ const log = [];
+ let spent = 0;
+
+ while (Date.now() < deadline && spent + perTrade <= cap) {
+ const fresh = await call(ctx, 'pump-fun.getNewTokens', { limit: 20 });
+ const items = fresh?.tokens ?? fresh ?? [];
+ for (const t of items) {
+ const mint = t.mint ?? t.address;
+ if (!mint || seen.has(mint)) continue;
+ seen.add(mint);
+ const vet = await vetMint(ctx, mint).catch((e) => ({ verdict: { ok: false, reason: e.message } }));
+ if (!vet.verdict.ok) {
+ log.push({ mint, action: 'skip', reason: vet.verdict.reason });
+ continue;
+ }
+ try {
+ const buy = await call(ctx, 'pump-fun-trade.buyToken', { mint, amountSol: perTrade });
+ spent += perTrade;
+ log.push({ mint, action: 'buy', sig: buy.sig, spent });
+ if (spent + perTrade > cap) break;
+ } catch (e) {
+ log.push({ mint, action: 'error', reason: e.message });
+ }
+ }
+ await new Promise((r) => setTimeout(r, cfg(ctx, 'pollMs', 5000)));
+ }
+ return { ok: true, data: { spent, trades: log } };
+}
+
+export async function copyTrade(args, ctx) {
+ const deadline = Date.now() + args.durationSec * 1000;
+ const mult = args.sizeMultiplier ?? 1;
+ const cap = cfg(ctx, 'sessionSpendCapSol', 1.0);
+ const mirrored = new Set();
+ const log = [];
+ let spent = 0;
+
+ while (Date.now() < deadline && spent < cap) {
+ const profile = await call(ctx, 'pump-fun.getCreatorProfile', { creator: args.wallet });
+ const recentMints = (profile?.tokens ?? []).map((t) => t.mint).filter(Boolean);
+ for (const mint of recentMints) {
+ const trades = await call(ctx, 'pump-fun.getTokenTrades', { mint, limit: 20 });
+ const buys = (trades?.trades ?? trades ?? []).filter(
+ (t) => t.side === 'buy' && t.wallet === args.wallet && !mirrored.has(t.sig),
+ );
+ for (const b of buys) {
+ mirrored.add(b.sig);
+ const amountSol = Math.min((b.solAmount ?? 0) * mult, cap - spent);
+ if (amountSol <= 0) break;
+ try {
+ const r = await call(ctx, 'pump-fun-trade.buyToken', { mint, amountSol });
+ spent += amountSol;
+ log.push({ mint, mirroredFrom: b.sig, sig: r.sig, amountSol });
+ } catch (e) {
+ log.push({ mint, error: e.message });
+ }
+ }
+ }
+ await new Promise((r) => setTimeout(r, cfg(ctx, 'pollMs', 5000)));
+ }
+ return { ok: true, data: { spent, mirrors: log } };
+}
+
+export async function rugExitWatch(args, ctx) {
+ const deadline = Date.now() + args.durationSec * 1000;
+ const concentrationLimit = cfg(ctx, 'exitOnConcentrationPct', 40);
+ const devSellLimit = cfg(ctx, 'exitOnDevSellPct', 25);
+ const exited = new Set();
+ const log = [];
+
+ while (Date.now() < deadline && exited.size < args.mints.length) {
+ for (const mint of args.mints) {
+ if (exited.has(mint)) continue;
+ const [holders, trades, details] = await Promise.all([
+ call(ctx, 'pump-fun.getTokenHolders', { mint, limit: 10 }),
+ call(ctx, 'pump-fun.getTokenTrades', { mint, limit: 50 }),
+ call(ctx, 'pump-fun.getTokenDetails', { mint }),
+ ]);
+ const top = holders?.topHolderPct ?? holders?.holders?.[0]?.pct ?? 0;
+ const dev = details?.creator ?? details?.token?.creator;
+ const devSells = (trades?.trades ?? trades ?? []).filter(
+ (t) => t.side === 'sell' && t.wallet === dev,
+ );
+ const devSellPct = devSells.reduce((s, t) => s + (t.pctOfSupply ?? 0), 0);
+
+ let trigger = null;
+ if (top >= concentrationLimit) trigger = `top holder ${top}%`;
+ else if (devSellPct >= devSellLimit) trigger = `dev sold ${devSellPct}%`;
+ if (!trigger) continue;
+
+ try {
+ const sell = await call(ctx, 'pump-fun-trade.sellToken', { mint, percent: 100 });
+ exited.add(mint);
+ log.push({ mint, trigger, sig: sell.sig });
+ } catch (e) {
+ log.push({ mint, trigger, error: e.message });
+ }
+ }
+ await new Promise((r) => setTimeout(r, cfg(ctx, 'pollMs', 5000)));
+ }
+ return { ok: true, data: { exited: [...exited], events: log } };
+}
diff --git a/public/skills/pump-fun/SKILL.md b/public/skills/pump-fun/SKILL.md
new file mode 100644
index 000000000..bd584216b
--- /dev/null
+++ b/public/skills/pump-fun/SKILL.md
@@ -0,0 +1,47 @@
+# pump-fun
+
+Read-only Solana market intel for three.ws agents. Proxies the
+[pump-fun-workers](https://github.com/nirholas/pump-fun-workers) MCP server
+(Cloudflare Worker) so any agent can search, inspect, and rug-check pump.fun
+tokens during conversation.
+
+## Tools
+
+| Tool | Use it for |
+|---|---|
+| `searchTokens` | Find a token by name, symbol, or mint |
+| `getTokenDetails` | Full metadata for a mint |
+| `getBondingCurve` | Reserves, price, graduation % |
+| `getTokenTrades` | Recent buy/sell history |
+| `getTrendingTokens` | Top by market cap |
+| `getNewTokens` | Most recent launches |
+| `getGraduatedTokens` | Tokens that hit Raydium |
+| `getKingOfTheHill` | Highest mcap still on the curve |
+| `getCreatorProfile` | Creator's tokens + rug flags |
+| `getTokenHolders` | Top holders + concentration |
+
+All tools are read-only. No wallet keys are required or accepted.
+
+## Endpoint
+
+Defaults to `https://pump-fun-sdk.modelcontextprotocol.name/mcp`. Override per
+install via `manifest.config.endpoint` to point at a self-hosted Worker.
+
+## Install
+
+Reference the bundle from your agent manifest:
+
+```json
+{
+ "skills": [
+ { "uri": "https://cdn.three.ws/skills/pump-fun/" }
+ ]
+}
+```
+
+## Suggested instructions
+
+> When the user mentions a token name, symbol, or mint address, call
+> `searchTokens` first, then `getBondingCurve` and `getTokenHolders` before
+> giving an opinion. Always check `getCreatorProfile` for rug flags before
+> recommending a buy.
diff --git a/public/skills/pump-fun/handlers.js b/public/skills/pump-fun/handlers.js
new file mode 100644
index 000000000..749b5288d
--- /dev/null
+++ b/public/skills/pump-fun/handlers.js
@@ -0,0 +1,53 @@
+// pump-fun skill — proxies tool calls to the pump-fun-workers MCP server.
+// https://github.com/nirholas/pump-fun-workers
+
+const DEFAULT_ENDPOINT = 'https://pump-fun-sdk.modelcontextprotocol.name/mcp';
+
+let _rpcId = 0;
+
+async function callMcp(endpoint, name, args, ctx) {
+ const fetchImpl = ctx?.fetch ?? globalThis.fetch;
+ const res = await fetchImpl(endpoint, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: ++_rpcId,
+ method: 'tools/call',
+ params: { name, arguments: args ?? {} },
+ }),
+ });
+
+ if (!res.ok) throw new Error(`pump-fun MCP HTTP ${res.status}`);
+ const body = await res.json();
+ if (body.error) throw new Error(body.error.message ?? 'pump-fun MCP error');
+
+ const content = body.result?.content ?? [];
+ const text = content.find((c) => c.type === 'text')?.text;
+ if (!text) return body.result;
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+}
+
+function makeHandler(toolName) {
+ return async (args, ctx) => {
+ const endpoint = ctx?.skillConfig?.endpoint ?? DEFAULT_ENDPOINT;
+ const data = await callMcp(endpoint, toolName, args, ctx);
+ ctx?.memory?.note?.(`pump-fun:${toolName}`, { args });
+ return { ok: true, data };
+ };
+}
+
+export const searchTokens = makeHandler('searchTokens');
+export const getTokenDetails = makeHandler('getTokenDetails');
+export const getBondingCurve = makeHandler('getBondingCurve');
+export const getTokenTrades = makeHandler('getTokenTrades');
+export const getTrendingTokens = makeHandler('getTrendingTokens');
+export const getNewTokens = makeHandler('getNewTokens');
+export const getGraduatedTokens = makeHandler('getGraduatedTokens');
+export const getKingOfTheHill = makeHandler('getKingOfTheHill');
+export const getCreatorProfile = makeHandler('getCreatorProfile');
+export const getTokenHolders = makeHandler('getTokenHolders');
diff --git a/public/skills/pump-fun/manifest.json b/public/skills/pump-fun/manifest.json
new file mode 100644
index 000000000..343c93f9d
--- /dev/null
+++ b/public/skills/pump-fun/manifest.json
@@ -0,0 +1,30 @@
+{
+ "spec": "skill/0.1",
+ "name": "pump-fun",
+ "version": "0.1.0",
+ "description": "Read-only pump.fun (Solana) market intel: search tokens, inspect bonding curves, surface trending/new/graduated tokens, and flag rug-pull risk.",
+ "license": "MIT",
+ "tags": ["solana", "pump.fun", "market-data", "mcp"],
+ "requires": {
+ "runtime": ">=0.1.0",
+ "tools": []
+ },
+ "provides": {
+ "tools": [
+ "searchTokens",
+ "getTokenDetails",
+ "getBondingCurve",
+ "getTokenTrades",
+ "getTrendingTokens",
+ "getNewTokens",
+ "getGraduatedTokens",
+ "getKingOfTheHill",
+ "getCreatorProfile",
+ "getTokenHolders"
+ ],
+ "triggers": ["token_lookup", "market_check", "rug_check"]
+ },
+ "config": {
+ "endpoint": "https://pump-fun-sdk.modelcontextprotocol.name/mcp"
+ }
+}
diff --git a/public/skills/pump-fun/tools.json b/public/skills/pump-fun/tools.json
new file mode 100644
index 000000000..3f006b749
--- /dev/null
+++ b/public/skills/pump-fun/tools.json
@@ -0,0 +1,102 @@
+{
+ "tools": [
+ {
+ "name": "searchTokens",
+ "description": "Search pump.fun tokens by name, symbol, or mint address.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "query": { "type": "string" },
+ "limit": { "type": "integer", "minimum": 1, "maximum": 50, "default": 10 }
+ },
+ "required": ["query"]
+ }
+ },
+ {
+ "name": "getTokenDetails",
+ "description": "Full details for a specific pump.fun token by mint address.",
+ "input_schema": {
+ "type": "object",
+ "properties": { "mint": { "type": "string" } },
+ "required": ["mint"]
+ }
+ },
+ {
+ "name": "getBondingCurve",
+ "description": "Bonding curve analysis: reserves, current price, and graduation progress.",
+ "input_schema": {
+ "type": "object",
+ "properties": { "mint": { "type": "string" } },
+ "required": ["mint"]
+ }
+ },
+ {
+ "name": "getTokenTrades",
+ "description": "Recent trade history (buys & sells) for a token.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "mint": { "type": "string" },
+ "limit": { "type": "integer", "minimum": 1, "maximum": 200, "default": 50 }
+ },
+ "required": ["mint"]
+ }
+ },
+ {
+ "name": "getTrendingTokens",
+ "description": "Top pump.fun tokens by market cap.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "limit": { "type": "integer", "minimum": 1, "maximum": 50, "default": 10 }
+ }
+ }
+ },
+ {
+ "name": "getNewTokens",
+ "description": "Most recently launched pump.fun tokens.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "limit": { "type": "integer", "minimum": 1, "maximum": 50, "default": 10 }
+ }
+ }
+ },
+ {
+ "name": "getGraduatedTokens",
+ "description": "Tokens that have graduated from the bonding curve to Raydium AMM.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "limit": { "type": "integer", "minimum": 1, "maximum": 50, "default": 10 }
+ }
+ }
+ },
+ {
+ "name": "getKingOfTheHill",
+ "description": "Highest-market-cap token still on the bonding curve.",
+ "input_schema": { "type": "object", "properties": {} }
+ },
+ {
+ "name": "getCreatorProfile",
+ "description": "All tokens by a creator wallet, with rug-pull risk flags.",
+ "input_schema": {
+ "type": "object",
+ "properties": { "creator": { "type": "string" } },
+ "required": ["creator"]
+ }
+ },
+ {
+ "name": "getTokenHolders",
+ "description": "Top holders of a token with concentration analysis.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "mint": { "type": "string" },
+ "limit": { "type": "integer", "minimum": 1, "maximum": 100, "default": 20 }
+ },
+ "required": ["mint"]
+ }
+ }
+ ]
+}
diff --git a/src/agent-skills-pumpfun-watch.js b/src/agent-skills-pumpfun-watch.js
new file mode 100644
index 000000000..d5455d7e7
--- /dev/null
+++ b/src/agent-skills-pumpfun-watch.js
@@ -0,0 +1,230 @@
+/**
+ * Pump.fun watch skills
+ * ---------------------
+ * Read-only skills that let a Solana agent observe live pump.fun activity.
+ * Pairs with /api/agents/pumpfun-feed (SSE) and the upstream pumpfun-claims-bot
+ * MCP server.
+ *
+ * Skills registered:
+ * - pumpfun-recent-claims → list the latest N claims with intel
+ * - pumpfun-token-intel → enriched analysis of a specific mint
+ * - pumpfun-watch-start → subscribe to live feed; agent reacts per event
+ * - pumpfun-watch-stop → unsubscribe
+ *
+ * Reactions (handled inside watch-start) emit existing protocol events:
+ * - first-time claim → emote celebration + speak the AI take
+ * - fake claim → emote concern + warn
+ * - graduation → gesture wave + speak
+ *
+ * No keys held. No transactions signed. Pure read + react.
+ */
+
+import { ACTION_TYPES } from './agent-protocol.js';
+
+const FEED_PATH = '/api/agents/pumpfun-feed';
+const TIER_BADGE = { mega: '🔥🔥', influencer: '🔥', notable: '⭐' };
+
+const _state = {
+ es: null,
+ startedAt: 0,
+ count: 0,
+};
+
+async function fetchJson(url) {
+ const r = await fetch(url, { credentials: 'include' });
+ if (!r.ok) throw new Error(`request failed: ${r.status}`);
+ return r.json();
+}
+
+function summarizeClaim(ev) {
+ const tier = ev.tier ? `${TIER_BADGE[ev.tier] || ''} ${ev.tier}` : '';
+ const who = ev.github_user ? `@${ev.github_user}` : ev.claimer || 'unknown';
+ const sol = ev.amount_sol != null ? `${Number(ev.amount_sol).toFixed(3)} SOL` : '—';
+ return `${who} claimed ${sol} ${tier}`.trim();
+}
+
+/**
+ * Register pump.fun watch skills onto an AgentSkills instance.
+ * @param {import('./agent-skills.js').AgentSkills} skills
+ */
+export function registerPumpFunWatchSkills(skills) {
+ skills.register({
+ name: 'pumpfun-recent-claims',
+ description: 'List the most recent pump.fun GitHub social-fee claims with intel.',
+ instruction: 'Returns up to N enriched claim records. Read-only.',
+ animationHint: 'curiosity',
+ voicePattern: 'Pulling the last {{limit}} claims…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: { limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },
+ },
+ handler: async (args) => {
+ const limit = Math.min(50, Math.max(1, Number(args?.limit) || 10));
+ try {
+ const data = await fetchJson(`/api/agents/pumpfun?op=claims&limit=${limit}`);
+ const items = data?.items || [];
+ return {
+ success: true,
+ output: items.length
+ ? `Last ${items.length} claims:\n` + items.map(summarizeClaim).join('\n')
+ : 'No claims found in feed.',
+ sentiment: 0.2,
+ data: { items },
+ };
+ } catch (err) {
+ return { success: false, output: `Could not fetch claims: ${err.message}`, sentiment: -0.3 };
+ }
+ },
+ });
+
+ skills.register({
+ name: 'pumpfun-token-intel',
+ description: 'Get pump.fun token intel: graduation status, creator, holders, trust signals.',
+ instruction: 'Read-only enrichment for a specific mint address.',
+ animationHint: 'think',
+ voicePattern: 'Analyzing {{mint}}…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: { mint: { type: 'string', description: 'SPL mint pubkey (base58)' } },
+ required: ['mint'],
+ },
+ handler: async (args) => {
+ if (!args?.mint) return { success: false, output: 'mint required', sentiment: -0.2 };
+ try {
+ const data = await fetchJson(
+ `/api/agents/pumpfun?op=token&mint=${encodeURIComponent(args.mint)}`,
+ );
+ const t = data || {};
+ const lines = [
+ t.name ? `${t.name}${t.symbol ? ` ($${t.symbol})` : ''}` : args.mint,
+ t.graduated ? 'Graduated to PumpAMM' : `Curve progress: ${t.curve_progress ?? '—'}%`,
+ t.creator ? `Creator: ${t.creator}` : null,
+ t.warnings?.length ? `⚠️ ${t.warnings.join(', ')}` : null,
+ ].filter(Boolean);
+ return {
+ success: true,
+ output: lines.join('\n'),
+ sentiment: t.warnings?.length ? -0.2 : 0.3,
+ data: t,
+ };
+ } catch (err) {
+ return { success: false, output: `Could not fetch intel: ${err.message}`, sentiment: -0.3 };
+ }
+ },
+ });
+
+ skills.register({
+ name: 'pumpfun-watch-start',
+ description: 'Subscribe to live pump.fun events; agent narrates and reacts as they arrive.',
+ instruction: 'Opens an SSE stream. Emits speak/gesture/emote per event.',
+ animationHint: 'curiosity',
+ voicePattern: 'Watching pump.fun live.',
+ mcpExposed: false, // browser-only — needs EventSource
+ inputSchema: {
+ type: 'object',
+ properties: {
+ kind: { type: 'string', enum: ['all', 'claims', 'graduations'], default: 'all' },
+ minTier: { type: 'string', enum: ['notable', 'influencer', 'mega'] },
+ },
+ },
+ handler: async (args, ctx) => {
+ if (typeof window === 'undefined' || !window.EventSource) {
+ return { success: false, output: 'Live watch requires a browser.', sentiment: -0.3 };
+ }
+ if (_state.es) {
+ return { success: true, output: 'Already watching.', sentiment: 0.1 };
+ }
+ const params = new URLSearchParams();
+ params.set('kind', args?.kind || 'all');
+ if (args?.minTier) params.set('minTier', args.minTier);
+ const url = `${FEED_PATH}?${params.toString()}`;
+
+ _state.es = new EventSource(url, { withCredentials: true });
+ _state.startedAt = Date.now();
+ _state.count = 0;
+
+ const protocol = ctx.protocol;
+ const speak = (text, sentiment = 0) =>
+ protocol?.emit({ type: ACTION_TYPES.SPEAK, payload: { text, sentiment } });
+ const emote = (trigger, weight) =>
+ protocol?.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger, weight } });
+ const gesture = (name, duration = 1500) =>
+ protocol?.emit({ type: ACTION_TYPES.GESTURE, payload: { name, duration } });
+
+ _state.es.addEventListener('claim', (msg) => {
+ _state.count++;
+ const ev = safeJson(msg.data);
+ if (!ev) return;
+ if (ev.first_time_claim) {
+ emote('celebration', 0.9);
+ speak(
+ `First-time claim! ${summarizeClaim(ev)}${ev.ai_take ? ` — ${ev.ai_take}` : ''}`,
+ 0.7,
+ );
+ } else if (ev.fake_claim) {
+ emote('concern', 0.7);
+ speak(`Fake claim detected: ${summarizeClaim(ev)}`, -0.5);
+ } else if (ev.tier) {
+ emote('curiosity', 0.5);
+ speak(summarizeClaim(ev), 0.2);
+ }
+ });
+
+ _state.es.addEventListener('graduation', (msg) => {
+ const ev = safeJson(msg.data);
+ if (!ev) return;
+ gesture('wave', 1500);
+ speak(`Graduation: ${ev.symbol || ev.mint || 'a token'} hit PumpAMM.`, 0.6);
+ });
+
+ _state.es.addEventListener('error', () => {
+ // EventSource auto-reconnects; surface only if it permanently closes.
+ if (_state.es && _state.es.readyState === EventSource.CLOSED) {
+ emote('concern', 0.4);
+ _state.es = null;
+ }
+ });
+
+ return {
+ success: true,
+ output: `Watching pump.fun (${args?.kind || 'all'}).`,
+ sentiment: 0.4,
+ };
+ },
+ });
+
+ skills.register({
+ name: 'pumpfun-watch-stop',
+ description: 'Stop the live pump.fun watch.',
+ instruction: 'Closes the SSE stream.',
+ animationHint: 'patience',
+ voicePattern: 'Stopping the watch.',
+ mcpExposed: false,
+ inputSchema: { type: 'object', properties: {} },
+ handler: async () => {
+ if (!_state.es) {
+ return { success: true, output: 'Not currently watching.', sentiment: 0 };
+ }
+ _state.es.close();
+ const seen = _state.count;
+ _state.es = null;
+ _state.count = 0;
+ return {
+ success: true,
+ output: `Stopped. Saw ${seen} events.`,
+ sentiment: 0.1,
+ data: { events: seen },
+ };
+ },
+ });
+}
+
+function safeJson(s) {
+ try {
+ return JSON.parse(s);
+ } catch {
+ return null;
+ }
+}
diff --git a/src/onchain/tokens/base.js b/src/onchain/tokens/base.js
new file mode 100644
index 000000000..fc77c7472
--- /dev/null
+++ b/src/onchain/tokens/base.js
@@ -0,0 +1,57 @@
+/**
+ * TokenAdapter — the contract every token-launch backend implements.
+ *
+ * Parallel to WalletAdapter. The deploy orchestrator and UI talk only to this
+ * interface; new launchpads (Zora, Bonfida, Streamflow…) plug in as new
+ * adapters without forking the calling code.
+ *
+ * A "token" here is a fungible asset bound to an agent identity (memecoin on a
+ * bonding curve, social token, etc.). Distinct from the agent's *identity* NFT
+ * minted via the deploy flow.
+ */
+
+/**
+ * @typedef {object} LaunchPrep
+ * @property {string} prepId
+ * @property {string} mint Mint pubkey (Solana base58, EVM addr, etc.)
+ * @property {string} txBase64 Partially-signed unsigned-by-user tx
+ * @property {string} metadataUri Token metadata pointer (ipfs://...)
+ * @property {string} family 'solana' | 'evm' | ...
+ * @property {string} provider 'pumpfun' | 'zora' | ...
+ * @property {string} [cluster] For Solana
+ */
+
+/**
+ * @typedef {object} LaunchResult
+ * @property {string} mint
+ * @property {string} txHash Tx hash / signature
+ * @property {string} provider
+ * @property {string} [curve] Provider-specific curve / pool ID
+ */
+
+/**
+ * @abstract
+ */
+export class TokenAdapter {
+ /** @returns {string} 'pumpfun' | etc. */
+ get provider() {
+ throw new Error('not implemented');
+ }
+
+ /** @returns {string} 'solana' | 'evm' */
+ get family() {
+ throw new Error('not implemented');
+ }
+
+ /**
+ * Validate that a launch is permitted for the given agent state. Adapters
+ * use this to enforce constraints (Pump.fun is Solana-only, requires the
+ * agent to already have a Solana identity, etc.).
+ *
+ * @param {{ agent: object }} ctx
+ * @returns {{ ok: boolean, reason?: string }}
+ */
+ validatePreconditions(_ctx) {
+ throw new Error('not implemented');
+ }
+}
diff --git a/src/onchain/tokens/index.js b/src/onchain/tokens/index.js
new file mode 100644
index 000000000..9f51b9abc
--- /dev/null
+++ b/src/onchain/tokens/index.js
@@ -0,0 +1,30 @@
+/**
+ * Token-adapter factory. Mirrors src/onchain/adapters/index.js for the wallet
+ * layer.
+ */
+
+import { PumpfunTokenAdapter } from './pumpfun.js';
+
+const cache = new Map();
+
+/**
+ * @param {'pumpfun'} provider
+ * @returns {import('./base.js').TokenAdapter}
+ */
+export function getTokenAdapter(provider) {
+ if (cache.has(provider)) return cache.get(provider);
+ let inst;
+ if (provider === 'pumpfun') inst = new PumpfunTokenAdapter();
+ else throw new Error(`No token adapter for provider: ${provider}`);
+ cache.set(provider, inst);
+ return inst;
+}
+
+export function _resetTokenAdapters() {
+ cache.clear();
+}
+
+/** @returns {string[]} */
+export function listProviders() {
+ return ['pumpfun'];
+}
diff --git a/src/onchain/tokens/pumpfun.js b/src/onchain/tokens/pumpfun.js
new file mode 100644
index 000000000..b1f9dd38f
--- /dev/null
+++ b/src/onchain/tokens/pumpfun.js
@@ -0,0 +1,204 @@
+/**
+ * PumpfunTokenAdapter — front-end facade for launching an agent's token on
+ * Pump.fun's bonding curve.
+ *
+ * Most of the heavy lifting (mint keypair generation, fetching `global`,
+ * building the `createV2Instruction` tx) happens server-side in
+ * api/agents/tokens/launch-prep.js — this module only:
+ *
+ * 1. Validates that the agent has a Solana identity (Pump.fun is Solana-only).
+ * 2. Calls the prep endpoint, gets back a base64 partially-signed tx.
+ * 3. Hands the tx to the user's Solana wallet for the user-signature.
+ * 4. Submits the fully-signed tx through our own Connection on the chosen
+ * cluster (mirroring the SolanaAdapter discipline of not trusting the
+ * wallet's RPC).
+ * 5. Calls the confirm endpoint to verify + persist `meta.token`.
+ */
+
+import { Connection, Transaction, VersionedTransaction } from '@solana/web3.js';
+import { TokenAdapter } from './base.js';
+import { getAdapter as getWalletAdapter } from '../adapters/index.js';
+
+const SOLANA_RPC = {
+ mainnet: 'https://api.mainnet-beta.solana.com',
+ devnet: 'https://api.devnet.solana.com',
+};
+
+function decodeTx(b64) {
+ const bin = atob(b64);
+ const bytes = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
+ try {
+ return VersionedTransaction.deserialize(bytes);
+ } catch {
+ return Transaction.from(bytes);
+ }
+}
+
+export class PumpfunTokenAdapter extends TokenAdapter {
+ get provider() {
+ return 'pumpfun';
+ }
+
+ get family() {
+ return 'solana';
+ }
+
+ /** @param {{ agent: object }} ctx */
+ validatePreconditions({ agent }) {
+ const onchain = agent?.onchain;
+ if (!onchain) {
+ return {
+ ok: false,
+ reason: 'Agent must be deployed on-chain before launching a token.',
+ };
+ }
+ if (onchain.family !== 'solana') {
+ return {
+ ok: false,
+ reason: 'Pump.fun launches require a Solana-deployed agent.',
+ };
+ }
+ if (agent?.token?.mint) {
+ return { ok: false, reason: 'This agent already has a launched token.' };
+ }
+ return { ok: true };
+ }
+
+ /**
+ * @param {object} opts
+ * @param {object} opts.agent
+ * @param {{ name: string, symbol: string, description?: string, image?: string, initialBuySol?: number }} opts.params
+ * @param {(step: 'connect'|'prep'|'sign'|'submit'|'confirm') => void} [opts.onProgress]
+ * @returns {Promise<{ mint: string, txHash: string, provider: 'pumpfun', cluster: 'mainnet'|'devnet' }>}
+ */
+ async launch({ agent, params, onProgress = () => {} }) {
+ const pre = this.validatePreconditions({ agent });
+ if (!pre.ok) {
+ const err = new Error(pre.reason);
+ err.code = 'PRECONDITION_FAILED';
+ throw err;
+ }
+
+ const cluster = agent.onchain.cluster || 'mainnet';
+ const wallet = getWalletAdapter('solana');
+ if (!wallet.isAvailable()) {
+ const err = new Error('No Solana wallet detected.');
+ err.code = 'NO_PROVIDER';
+ err.installUrl = wallet.installUrl();
+ throw err;
+ }
+
+ onProgress('connect');
+ const { address } = await wallet.connect({ ensureLinked: true, cluster });
+ if (address !== agent.onchain.wallet) {
+ const err = new Error(
+ 'Connected wallet does not match the agent owner. Switch wallets and retry.',
+ );
+ err.code = 'WALLET_MISMATCH';
+ throw err;
+ }
+
+ onProgress('prep');
+ const prepResp = await fetch('/api/agents/tokens/launch-prep', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ agent_id: agent.id,
+ provider: 'pumpfun',
+ cluster,
+ wallet_address: address,
+ name: params.name,
+ symbol: params.symbol,
+ description: params.description || '',
+ image: params.image || agent.thumbnailUrl || '',
+ initial_buy_sol: Number.isFinite(params.initialBuySol) ? params.initialBuySol : 0,
+ }),
+ });
+ if (!prepResp.ok) {
+ const data = await prepResp.json().catch(() => ({}));
+ const err = new Error(
+ data.error_description || `launch-prep returned ${prepResp.status}`,
+ );
+ err.status = prepResp.status;
+ err.code = data.error;
+ throw err;
+ }
+ const prep = await prepResp.json();
+
+ onProgress('sign');
+ const provider =
+ window.phantom?.solana || window.solana || window.backpack?.solana || window.solflare;
+ if (!provider) throw new Error('Solana wallet vanished mid-flow.');
+
+ const tx = decodeTx(prep.tx_base64);
+ const signed = await provider.signTransaction(tx);
+
+ onProgress('submit');
+ const conn = new Connection(SOLANA_RPC[cluster], 'confirmed');
+ const signature = await conn.sendRawTransaction(signed.serialize(), {
+ skipPreflight: false,
+ preflightCommitment: 'confirmed',
+ });
+
+ // Bounded poll (Pump.fun launches occasionally take 10–20s on devnet).
+ await this.#waitForConfirmation(conn, signature, 90_000);
+
+ onProgress('confirm');
+ const confirmResp = await fetch('/api/agents/tokens/launch-confirm', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ prep_id: prep.prep_id,
+ tx_signature: signature,
+ wallet_address: address,
+ }),
+ });
+ if (!confirmResp.ok) {
+ const data = await confirmResp.json().catch(() => ({}));
+ const err = new Error(
+ data.error_description || `launch-confirm returned ${confirmResp.status}`,
+ );
+ err.status = confirmResp.status;
+ err.code = data.error;
+ err.txSignature = signature;
+ throw err;
+ }
+ const confirmed = await confirmResp.json();
+ return {
+ mint: prep.mint,
+ txHash: signature,
+ provider: 'pumpfun',
+ cluster,
+ agent: confirmed.agent,
+ pumpfunUrl:
+ cluster === 'mainnet'
+ ? `https://pump.fun/${prep.mint}`
+ : `https://explorer.solana.com/address/${prep.mint}?cluster=devnet`,
+ };
+ }
+
+ async #waitForConfirmation(conn, signature, timeoutMs) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const { value } = await conn.getSignatureStatuses([signature]);
+ const s = value?.[0];
+ if (s) {
+ if (s.err) {
+ const e = new Error(`Token launch failed: ${JSON.stringify(s.err)}`);
+ e.code = 'TX_FAILED';
+ throw e;
+ }
+ if (s.confirmationStatus === 'confirmed' || s.confirmationStatus === 'finalized') {
+ return;
+ }
+ }
+ await new Promise((r) => setTimeout(r, 1500));
+ }
+ const e = new Error('Launch confirmation timed out. Tx may still land — check explorer.');
+ e.code = 'TX_TIMEOUT';
+ throw e;
+ }
+}
diff --git a/src/solana/vanity/grinder.js b/src/solana/vanity/grinder.js
new file mode 100644
index 000000000..5330a6f93
--- /dev/null
+++ b/src/solana/vanity/grinder.js
@@ -0,0 +1,141 @@
+/**
+ * Solana vanity address grinder — main-thread API.
+ *
+ * Spawns a pool of Web Workers (one per logical core, capped) that race
+ * to find a Keypair whose Base58 public key matches the requested prefix
+ * and/or suffix. First match wins; the rest are terminated.
+ *
+ * Usage:
+ * const { publicKey, secretKey, attempts, durationMs } = await grindVanity({
+ * prefix: 'AGNT',
+ * onProgress: ({ attempts, rate, eta }) => updateUI(...),
+ * signal,
+ * });
+ *
+ * The returned `secretKey` is a Uint8Array(64) — Solana's standard
+ * Ed25519 keypair format, compatible with `Keypair.fromSecretKey()`.
+ *
+ * Algorithm parity with nirholas/solana-wallet-toolkit. WASM backend
+ * (~10× faster) is a future optimization — see TODO at bottom.
+ */
+
+import { validatePattern, estimateAttempts, formatTimeEstimate } from './validation.js';
+
+const DEFAULT_MAX_WORKERS = 8;
+
+/**
+ * @typedef {object} GrindOptions
+ * @property {string} [prefix] - Base58 prefix to match.
+ * @property {string} [suffix] - Base58 suffix to match.
+ * @property {boolean} [ignoreCase=false] - Case-insensitive match.
+ * @property {number} [maxWorkers] - Cap on workers (defaults to hardwareConcurrency).
+ * @property {AbortSignal} [signal] - Cancel the grind.
+ * @property {(p: { attempts: number, rate: number, eta: string }) => void} [onProgress]
+ */
+
+/**
+ * @typedef {object} GrindResult
+ * @property {string} publicKey - Base58 address.
+ * @property {Uint8Array} secretKey - 64-byte Ed25519 secret key.
+ * @property {number} attempts - Total attempts across all workers.
+ * @property {number} durationMs - Wall-clock duration.
+ * @property {number} workers - Number of workers used.
+ */
+
+/**
+ * Grind for a vanity Solana address.
+ * @param {GrindOptions} opts
+ * @returns {Promise<GrindResult>}
+ */
+export function grindVanity(opts = {}) {
+ const { prefix = '', suffix = '', ignoreCase = false, signal, onProgress } = opts;
+
+ if (!prefix && !suffix) {
+ return Promise.reject(new Error('prefix or suffix is required'));
+ }
+ if (prefix) {
+ const v = validatePattern(prefix);
+ if (!v.valid) return Promise.reject(new Error(`invalid prefix: ${v.errors.join('; ')}`));
+ }
+ if (suffix) {
+ const v = validatePattern(suffix);
+ if (!v.valid) return Promise.reject(new Error(`invalid suffix: ${v.errors.join('; ')}`));
+ }
+
+ const cores = Math.max(1, Math.min(
+ opts.maxWorkers || (typeof navigator !== 'undefined' && navigator.hardwareConcurrency) || 4,
+ DEFAULT_MAX_WORKERS,
+ ));
+ const expected = estimateAttempts((prefix?.length || 0) + (suffix?.length || 0));
+ const startedAt = performance.now();
+
+ /** @type {Worker[]} */
+ const workers = [];
+ const ratesByWorker = new Array(cores).fill(0);
+ const attemptsByWorker = new Array(cores).fill(0);
+
+ const stopAll = () => {
+ for (const w of workers) {
+ try { w.postMessage({ type: 'stop' }); } catch {}
+ try { w.terminate(); } catch {}
+ }
+ workers.length = 0;
+ };
+
+ return new Promise((resolve, reject) => {
+ const onAbort = () => {
+ stopAll();
+ reject(new DOMException('vanity grind aborted', 'AbortError'));
+ };
+ if (signal) {
+ if (signal.aborted) return onAbort();
+ signal.addEventListener('abort', onAbort, { once: true });
+ }
+
+ for (let i = 0; i < cores; i++) {
+ const w = new Worker(new URL('./grinder-worker.js', import.meta.url), { type: 'module' });
+ workers.push(w);
+
+ w.onmessage = (e) => {
+ const msg = e.data;
+ if (msg.type === 'match') {
+ stopAll();
+ if (signal) signal.removeEventListener('abort', onAbort);
+ const totalAttempts = attemptsByWorker.reduce((a, b) => a + b, 0) + msg.attempts;
+ resolve({
+ publicKey: msg.publicKey,
+ secretKey: new Uint8Array(msg.secretKey),
+ attempts: totalAttempts,
+ durationMs: performance.now() - startedAt,
+ workers: cores,
+ });
+ } else if (msg.type === 'progress') {
+ attemptsByWorker[i] = msg.attempts;
+ ratesByWorker[i] = msg.rate;
+ if (onProgress) {
+ const totalRate = ratesByWorker.reduce((a, b) => a + b, 0);
+ const totalAttempts = attemptsByWorker.reduce((a, b) => a + b, 0);
+ onProgress({
+ attempts: totalAttempts,
+ rate: totalRate,
+ eta: formatTimeEstimate(Math.max(0, expected - totalAttempts), totalRate),
+ });
+ }
+ }
+ };
+
+ w.onerror = (err) => {
+ stopAll();
+ if (signal) signal.removeEventListener('abort', onAbort);
+ reject(err.error || new Error(err.message || 'vanity worker crashed'));
+ };
+
+ w.postMessage({ type: 'start', prefix, suffix, ignoreCase });
+ }
+ });
+}
+
+// TODO(perf): drop in a WASM grinder backed by the toolkit's Rust crate
+// (nirholas/solana-wallet-toolkit/rust). Expected ~10× over JS Keypair.generate().
+// Public API of grindVanity() is intentionally backend-agnostic so the swap is
+// transparent to callers.
diff --git a/tests/api/pump.test.js b/tests/api/pump.test.js
new file mode 100644
index 000000000..27d2677f3
--- /dev/null
+++ b/tests/api/pump.test.js
@@ -0,0 +1,306 @@
+// Tests for pump.fun integration endpoints. SDKs and Solana RPC are fully
+// mocked — no network, no chain. Verifies request/response shapes, auth,
+// validation, and that the right SDK calls are issued in the right order.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+// ── Auth state ────────────────────────────────────────────────────────────
+const authState = { session: null, bearer: null };
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => authState.bearer),
+ extractBearer: vi.fn(() => null),
+}));
+
+// ── SQL mock ──────────────────────────────────────────────────────────────
+const sqlState = { queue: [], calls: [] };
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ if (sqlState.queue.length === 0) return [];
+ return sqlState.queue.shift();
+ }),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: true })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../../api/_lib/crypto.js', () => ({
+ randomToken: vi.fn(async (n) => 'a'.repeat((n || 16) * 2)),
+}));
+
+// ── pump-fun SDK mocks ────────────────────────────────────────────────────
+const mockPumpAgentOffline = {
+ create: vi.fn(async () => ({ programId: 'agent', keys: [], data: Buffer.alloc(0) })),
+ acceptPayment: vi.fn(async () => ({ programId: 'pay', keys: [], data: Buffer.alloc(0) })),
+ withdraw: vi.fn(async () => ({ programId: 'wd', keys: [], data: Buffer.alloc(0) })),
+ updateBuybackBps: vi.fn(async () => ({ programId: 'bp', keys: [], data: Buffer.alloc(0) })),
+ distributePayments: vi.fn(async () => [{ programId: 'd', keys: [], data: Buffer.alloc(0) }]),
+ buybackTrigger: vi.fn(async () => ({ programId: 'b', keys: [], data: Buffer.alloc(0) })),
+};
+const mockPumpAgent = {
+ getBalances: vi.fn(async () => ({
+ paymentVault: { address: 'PaymPda', balance: 1_000_000n }, // 1 USDC
+ buybackVault: { address: 'BuybkPda', balance: 0n },
+ withdrawVault: { address: 'WdrwPda', balance: 0n },
+ })),
+};
+
+vi.mock('../../api/_lib/pump.js', () => ({
+ getConnection: vi.fn(() => ({})),
+ solanaPubkey: vi.fn((s) => (s ? { toBase58: () => s, toString: () => s } : null)),
+ getPumpSdk: vi.fn(async () => ({
+ sdk: {
+ fetchGlobal: async () => ({}),
+ createInstruction: async () => ({ keys: [], data: Buffer.alloc(0) }),
+ createAndBuyInstructions: async () => [{ keys: [], data: Buffer.alloc(0) }],
+ },
+ BN: function MockBN(v) { this.v = v; this.toString = () => String(v); },
+ web3: { LAMPORTS_PER_SOL: 1_000_000_000 },
+ })),
+ getPumpSwapSdk: vi.fn(async () => ({ sdk: {}, BN: class {}, web3: {} })),
+ getPumpAgent: vi.fn(async () => ({
+ agent: mockPumpAgent,
+ agentPda: { toString: () => 'AgentPda' },
+ BN: class {},
+ web3: {},
+ })),
+ getPumpAgentOffline: vi.fn(async () => ({
+ offline: mockPumpAgentOffline,
+ BN: function MockBN(v) {
+ const inst = { v, toString: () => String(v) };
+ return inst;
+ },
+ web3: {},
+ agentPda: { toString: () => 'AgentPda' },
+ })),
+ verifySignature: vi.fn(async () => ({
+ transaction: { message: { accountKeys: [{ pubkey: { toString: () => 'MintPubkey1111111111111111111111111111' } }] } },
+ meta: {},
+ })),
+ buildUnsignedTxBase64: vi.fn(async () => 'BASE64TX'),
+}));
+
+// ── helpers ───────────────────────────────────────────────────────────────
+function makeReq({ method = 'GET', url = '/', headers = {}, body = null } = {}) {
+ const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
+ base.method = method;
+ base.url = url;
+ base.headers = {
+ host: 'localhost',
+ ...(body ? { 'content-type': 'application/json' } : {}),
+ ...headers,
+ };
+ return base;
+}
+function makeRes() {
+ return {
+ statusCode: 200, headers: {}, body: '', writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },
+ };
+}
+async function invoke(handler, opts) {
+ const req = makeReq(opts); const res = makeRes();
+ await handler(req, res);
+ return { res, json: res.body ? JSON.parse(res.body) : null };
+}
+function resetAll() {
+ authState.session = null; authState.bearer = null;
+ sqlState.queue = []; sqlState.calls = [];
+ mockPumpAgentOffline.create.mockClear();
+ mockPumpAgentOffline.acceptPayment.mockClear();
+ mockPumpAgentOffline.withdraw.mockClear();
+ mockPumpAgentOffline.updateBuybackBps.mockClear();
+ mockPumpAgentOffline.distributePayments.mockClear();
+ mockPumpAgentOffline.buybackTrigger.mockClear();
+ mockPumpAgent.getBalances.mockClear();
+}
+
+// ── Tests ─────────────────────────────────────────────────────────────────
+const mintB58 = 'MintPubkey1111111111111111111111111111';
+const walletB58 = 'WalletPubkey111111111111111111111111111';
+const ataB58 = 'AtaPubkey1111111111111111111111111111111';
+
+describe('GET /api/pump/balances', () => {
+ beforeEach(resetAll);
+
+ it('returns three vault balances', async () => {
+ const { default: handler } = await import('../../api/pump/balances.js');
+ const { res, json } = await invoke(handler, {
+ method: 'GET',
+ url: `/api/pump/balances?mint=${mintB58}&network=devnet`,
+ });
+ expect(res.statusCode).toBe(200);
+ expect(json.balances.payment.balance).toBe('1000000');
+ expect(json.balances.buyback.balance).toBe('0');
+ expect(json.balances.withdraw.balance).toBe('0');
+ expect(mockPumpAgent.getBalances).toHaveBeenCalledOnce();
+ });
+
+ it('400s on bad mint', async () => {
+ const { default: handler } = await import('../../api/pump/balances.js');
+ const pumpMod = await import('../../api/_lib/pump.js');
+ pumpMod.solanaPubkey.mockReturnValueOnce(null); // invalid mint
+ const { res, json } = await invoke(handler, {
+ method: 'GET', url: '/api/pump/balances?mint=bad',
+ });
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('validation_error');
+ });
+});
+
+describe('POST /api/pump/launch-prep', () => {
+ beforeEach(resetAll);
+
+ it('rejects unauthenticated', async () => {
+ const { default: handler } = await import('../../api/pump/launch-prep.js');
+ const { res } = await invoke(handler, {
+ method: 'POST', url: '/api/pump/launch-prep',
+ body: { agent_id: '00000000-0000-0000-0000-000000000001',
+ wallet_address: walletB58, name: 'X', symbol: 'X', uri: 'https://x/m.json' },
+ });
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('builds unsigned tx for valid request', async () => {
+ authState.session = { id: 'user-1' };
+ sqlState.queue = [
+ [{ id: 'wallet-1' }], // wallet check
+ [{ id: 'agent-1', name: 'Foo' }], // agent check
+ [], // insert pending
+ ];
+ const { default: handler } = await import('../../api/pump/launch-prep.js');
+ const { res, json } = await invoke(handler, {
+ method: 'POST', url: '/api/pump/launch-prep',
+ body: {
+ agent_id: '00000000-0000-0000-0000-000000000001',
+ wallet_address: walletB58,
+ name: 'Foo', symbol: 'FOO', uri: 'https://x/m.json',
+ network: 'devnet', buyback_bps: 500,
+ },
+ });
+ expect(res.statusCode).toBe(201);
+ expect(json.tx_base64).toBe('BASE64TX');
+ expect(json.buyback_bps).toBe(500);
+ expect(mockPumpAgentOffline.create).toHaveBeenCalledOnce();
+ expect(mockPumpAgentOffline.create.mock.calls[0][0].buybackBps).toBe(500);
+ });
+});
+
+describe('POST /api/pump/accept-payment-prep', () => {
+ beforeEach(resetAll);
+
+ it('builds acceptPayment ix and persists pending row', async () => {
+ authState.session = { id: 'user-1' };
+ sqlState.queue = [
+ [{ id: 'mint-1', mint: mintB58, network: 'devnet', buyback_bps: 500 }], // mint lookup
+ [{ id: 'pay-1', invoice_id: '1234', start_time: '2026-01-01', end_time: '2026-01-02', status: 'pending' }],
+ ];
+ const { default: handler } = await import('../../api/pump/accept-payment-prep.js');
+ const { res, json } = await invoke(handler, {
+ method: 'POST', url: '/api/pump/accept-payment-prep',
+ body: {
+ mint: mintB58, payer_wallet: walletB58, amount_usdc: 1.5,
+ user_token_account: ataB58, network: 'devnet', duration_seconds: 60,
+ skill_id: 'optimize',
+ },
+ });
+ expect(res.statusCode).toBe(201);
+ expect(json.tx_base64).toBe('BASE64TX');
+ expect(json.amount_atomics).toBe('1500000');
+ expect(mockPumpAgentOffline.acceptPayment).toHaveBeenCalledOnce();
+ });
+
+ it('404s if mint not registered', async () => {
+ authState.session = { id: 'user-1' };
+ sqlState.queue = [[]]; // mint lookup empty
+ const { default: handler } = await import('../../api/pump/accept-payment-prep.js');
+ const { res, json } = await invoke(handler, {
+ method: 'POST', url: '/api/pump/accept-payment-prep',
+ body: {
+ mint: mintB58, payer_wallet: walletB58, amount_usdc: 1,
+ user_token_account: ataB58, network: 'devnet',
+ },
+ });
+ expect(res.statusCode).toBe(404);
+ expect(json.error).toBe('not_found');
+ });
+});
+
+describe('POST /api/pump/accept-payment-confirm', () => {
+ beforeEach(resetAll);
+
+ it('marks payment confirmed when tx verifies', async () => {
+ authState.session = { id: 'user-1' };
+ sqlState.queue = [
+ [{ id: 'pay-1', mint: mintB58, network: 'devnet', invoice_id: '1234', status: 'pending' }],
+ [], // update
+ ];
+ const { default: handler } = await import('../../api/pump/accept-payment-confirm.js');
+ const { res, json } = await invoke(handler, {
+ method: 'POST', url: '/api/pump/accept-payment-confirm',
+ body: {
+ payment_id: '00000000-0000-0000-0000-000000000001',
+ tx_signature: 'a'.repeat(88),
+ },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(json.ok).toBe(true);
+ });
+});
+
+describe('POST /api/pump/withdraw-prep', () => {
+ beforeEach(resetAll);
+
+ it('builds withdraw ix for owner', async () => {
+ authState.session = { id: 'user-1' };
+ sqlState.queue = [[{
+ id: 'mint-1', mint: mintB58, user_id: 'user-1',
+ agent_authority: walletB58, network: 'devnet',
+ }]];
+ const { default: handler } = await import('../../api/pump/withdraw-prep.js');
+ const { res, json } = await invoke(handler, {
+ method: 'POST', url: '/api/pump/withdraw-prep',
+ body: {
+ mint: mintB58, authority_wallet: walletB58, receiver_ata: ataB58,
+ network: 'devnet',
+ },
+ });
+ expect(res.statusCode).toBe(201);
+ expect(json.tx_base64).toBe('BASE64TX');
+ expect(mockPumpAgentOffline.withdraw).toHaveBeenCalledOnce();
+ });
+
+ it('forbids non-owner', async () => {
+ authState.session = { id: 'other-user' };
+ sqlState.queue = [[{
+ id: 'mint-1', mint: mintB58, user_id: 'user-1',
+ agent_authority: walletB58, network: 'devnet',
+ }]];
+ const { default: handler } = await import('../../api/pump/withdraw-prep.js');
+ const { res } = await invoke(handler, {
+ method: 'POST', url: '/api/pump/withdraw-prep',
+ body: {
+ mint: mintB58, authority_wallet: walletB58, receiver_ata: ataB58,
+ network: 'devnet',
+ },
+ });
+ expect(res.statusCode).toBe(403);
+ });
+});
+
+describe('GET /.well-known/x402', () => {
+ beforeEach(resetAll);
+
+ it('advertises pump-agent-payments scheme', async () => {
+ const { default: handler } = await import('../../api/wk-x402.js');
+ const { res, json } = await invoke(handler, { method: 'GET', url: '/.well-known/x402' });
+ expect(res.statusCode).toBe(200);
+ expect(json.schemes).toContain('pump-agent-payments');
+ expect(json.pump_agent_payments.prep).toBe('/api/pump/accept-payment-prep');
+ });
+});
diff --git a/tests/api/solana-attest-event.test.js b/tests/api/solana-attest-event.test.js
new file mode 100644
index 000000000..d8d753d64
--- /dev/null
+++ b/tests/api/solana-attest-event.test.js
@@ -0,0 +1,103 @@
+import { describe, it, expect } from 'vitest';
+import crypto from 'node:crypto';
+
+import {
+ buildPayload,
+ taskHash,
+ verifyPumpkitSignature,
+} from '../../api/agents/solana-attest-event.js';
+
+const SECRET = 'test-secret';
+const AGENT = 'AgentAssetPubkey1111111111111111111111111111';
+const TOKEN = 'TokenMintPubkey22222222222222222222222222222';
+
+function sign(timestamp, raw, secret = SECRET) {
+ return crypto.createHmac('sha256', secret).update(`${timestamp}.`).update(raw).digest('hex');
+}
+
+describe('taskHash', () => {
+ it('is deterministic for the same inputs', () => {
+ expect(taskHash('t1', TOKEN)).toBe(taskHash('t1', TOKEN));
+ });
+ it('differs across token mints', () => {
+ expect(taskHash('t1', TOKEN)).not.toBe(taskHash('t1', TOKEN.replace('2', '3')));
+ });
+});
+
+describe('buildPayload', () => {
+ const base = { event_id: 'evt-1', agent_asset: AGENT, token_mint: TOKEN, task_id: 'task-1' };
+
+ it('graduation -> validation passed=true with pumpkit.graduation source', () => {
+ const p = buildPayload({ ...base, event_type: 'graduation' });
+ expect(p.kind).toBe('threews.validation.v1');
+ expect(p.passed).toBe(true);
+ expect(p.source).toBe('pumpkit.graduation');
+ expect(p.event_id).toBe('evt-1');
+ expect(p.agent).toBe(AGENT);
+ });
+
+ it('cto_detected -> validation passed=false', () => {
+ const p = buildPayload({ ...base, event_type: 'cto_detected' });
+ expect(p.kind).toBe('threews.validation.v1');
+ expect(p.passed).toBe(false);
+ expect(p.source).toBe('pumpkit.cto');
+ });
+
+ it('fee_claim -> feedback score=5', () => {
+ const p = buildPayload({ ...base, event_type: 'fee_claim', detail: { lamports: 1_000_000 } });
+ expect(p.kind).toBe('threews.feedback.v1');
+ expect(p.score).toBe(5);
+ expect(p.source).toBe('pumpkit.fee_claim');
+ expect(p.detail).toEqual({ lamports: 1_000_000 });
+ });
+
+ it('whale_trade -> task with scope_hash', () => {
+ const p = buildPayload({ ...base, event_type: 'whale_trade' });
+ expect(p.kind).toBe('threews.task.v1');
+ expect(p.task_id).toBe('task-1');
+ expect(p.scope_hash).toBe(taskHash('task-1', TOKEN));
+ });
+});
+
+describe('verifyPumpkitSignature', () => {
+ const raw = Buffer.from('{"event_id":"e","x":1}', 'utf8');
+ const now = 1_700_000_000;
+
+ it('accepts a fresh, correctly signed request', () => {
+ const ts = now;
+ const sig = sign(ts, raw);
+ expect(verifyPumpkitSignature({ secret: SECRET, timestamp: ts, signature: sig, raw, nowSecs: now }))
+ .toEqual({ ok: true, reason: 'ok' });
+ });
+
+ it('rejects a stale timestamp outside the replay window', () => {
+ const ts = now - 10 * 60;
+ const sig = sign(ts, raw);
+ expect(verifyPumpkitSignature({ secret: SECRET, timestamp: ts, signature: sig, raw, nowSecs: now }))
+ .toMatchObject({ ok: false, reason: 'stale' });
+ });
+
+ it('rejects a signature computed against a different body (replay binding)', () => {
+ const ts = now;
+ const sig = sign(ts, Buffer.from('{"event_id":"different"}', 'utf8'));
+ expect(verifyPumpkitSignature({ secret: SECRET, timestamp: ts, signature: sig, raw, nowSecs: now }))
+ .toMatchObject({ ok: false });
+ });
+
+ it('rejects the wrong secret', () => {
+ const ts = now;
+ const sig = sign(ts, raw, 'other-secret');
+ expect(verifyPumpkitSignature({ secret: SECRET, timestamp: ts, signature: sig, raw, nowSecs: now }))
+ .toMatchObject({ ok: false });
+ });
+
+ it('rejects when headers are missing', () => {
+ expect(verifyPumpkitSignature({ secret: SECRET, timestamp: undefined, signature: undefined, raw, nowSecs: now }))
+ .toMatchObject({ ok: false, reason: 'missing' });
+ });
+
+ it('rejects a non-numeric timestamp', () => {
+ expect(verifyPumpkitSignature({ secret: SECRET, timestamp: 'not-a-number', signature: 'aa', raw, nowSecs: now }))
+ .toMatchObject({ ok: false, reason: 'bad_timestamp' });
+ });
+});
diff --git a/tests/src/vanity-validation.test.js b/tests/src/vanity-validation.test.js
new file mode 100644
index 000000000..6dbe67f5a
--- /dev/null
+++ b/tests/src/vanity-validation.test.js
@@ -0,0 +1,67 @@
+import { describe, it, expect } from 'vitest';
+import {
+ validatePattern,
+ estimateAttempts,
+ formatTimeEstimate,
+ BASE58_ALPHABET,
+ MAX_PATTERN_LENGTH,
+} from '../../src/solana/vanity/validation.js';
+
+describe('vanity validation', () => {
+ it('accepts valid base58 prefixes', () => {
+ expect(validatePattern('AGNT').valid).toBe(true);
+ expect(validatePattern('So').valid).toBe(true);
+ expect(validatePattern('123').valid).toBe(true);
+ });
+
+ it('rejects empty string', () => {
+ expect(validatePattern('').valid).toBe(false);
+ });
+
+ it('rejects each confused character with a hint', () => {
+ for (const c of ['0', 'O', 'I', 'l']) {
+ const r = validatePattern(c);
+ expect(r.valid).toBe(false);
+ expect(r.errors.join(' ')).toMatch(c);
+ }
+ });
+
+ it('rejects patterns longer than the maximum', () => {
+ const tooLong = 'A'.repeat(MAX_PATTERN_LENGTH + 1);
+ expect(validatePattern(tooLong).valid).toBe(false);
+ });
+
+ it('rejects whitespace', () => {
+ expect(validatePattern(' AB').valid).toBe(false);
+ expect(validatePattern('AB ').valid).toBe(false);
+ });
+
+ it('alphabet excludes confused chars', () => {
+ expect(BASE58_ALPHABET).not.toMatch(/[0OIl]/);
+ expect(BASE58_ALPHABET.length).toBe(58);
+ });
+});
+
+describe('estimateAttempts', () => {
+ it('returns 58^length', () => {
+ expect(estimateAttempts(1)).toBe(58);
+ expect(estimateAttempts(2)).toBe(58 * 58);
+ expect(estimateAttempts(4)).toBe(Math.pow(58, 4));
+ });
+});
+
+describe('formatTimeEstimate', () => {
+ it('returns unknown for zero rate', () => {
+ expect(formatTimeEstimate(1000, 0)).toBe('unknown');
+ });
+ it('formats sub-second', () => {
+ expect(formatTimeEstimate(10, 1000)).toBe('less than a second');
+ });
+ it('formats seconds/minutes/hours/days/years', () => {
+ expect(formatTimeEstimate(30, 1)).toMatch(/seconds/);
+ expect(formatTimeEstimate(300, 1)).toMatch(/minutes/);
+ expect(formatTimeEstimate(7200, 1)).toMatch(/hours/);
+ expect(formatTimeEstimate(86400 * 3, 1)).toMatch(/days/);
+ expect(formatTimeEstimate(31536000 * 2, 1)).toMatch(/years/);
+ });
+});