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(api): add payment preparation and reputation history endpoints

nirholasbf1208378180
diff --git a/api/agents/payments/create-prep.js b/api/agents/payments/create-prep.js
new file mode 100644
index 000000000..3ceb5d17c
--- /dev/null
+++ b/api/agents/payments/create-prep.js
@@ -0,0 +1,128 @@
+/**
+ * POST /api/agents/payments/create-prep
+ *
+ * Build the unsigned PumpAgentPayments `create` transaction that registers
+ * an agent's launched token to accept payments. Owner-only. Pre-conditions:
+ * • Agent must already have meta.token.mint set (Pump.fun token launched).
+ * • Caller must own the agent and the wallet they're using.
+ *
+ * Returns a base64 partially-built tx the user signs in their wallet. The
+ * confirm endpoint persists `meta.payments` once the tx lands on-chain.
+ */
+
+import { z } from 'zod';
+import {
+ Connection,
+ PublicKey,
+ Transaction,
+ ComputeBudgetProgram,
+} from '@solana/web3.js';
+import { PumpAgentOffline, PUMP_AGENT_PAYMENTS_PROGRAM_ID } from '@pump-fun/agent-payments-sdk';
+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';
+
+const bodySchema = z.object({
+ agent_id: z.string().min(1).max(80),
+ wallet_address: z.string().min(32).max(44),
+ cluster: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+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 [agent] = await sql`
+ select id, user_id, 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 tokenMint = agent.meta?.token?.mint;
+ if (!tokenMint) {
+ return error(res, 409, 'precondition_failed', 'agent has no launched token yet');
+ }
+ if (agent.meta?.payments?.configured) {
+ return error(res, 409, 'conflict', 'payments already configured for this agent');
+ }
+ if (agent.meta?.onchain?.wallet !== body.wallet_address) {
+ return error(res, 403, 'forbidden', 'wallet does not match agent owner');
+ }
+
+ const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
+ const mint = new PublicKey(tokenMint);
+ const owner = new PublicKey(body.wallet_address);
+ const offline = PumpAgentOffline.load(mint, conn);
+
+ // `create` registers the TokenAgentPayments PDA. Authority defaults to the
+ // caller (owner). Buyback bps + sharing config can be configured later via
+ // updateBuybackBps; for the initial config we accept defaults so a single
+ // click enables payments.
+ const createIx = await offline.create({
+ user: owner,
+ authority: owner,
+ });
+
+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');
+ const tx = new Transaction({ feePayer: owner, blockhash, lastValidBlockHeight }).add(
+ ComputeBudgetProgram.setComputeUnitLimit({
+ units: PumpAgentOffline.DEFAULT_COMPUTE_UNIT_LIMIT_FOR_AGENT_PAYMENTS,
+ }),
+ ComputeBudgetProgram.setComputeUnitPrice({
+ microLamports: PumpAgentOffline.DEFAULT_PRIORITY_FEE_MICRO_LAMPORTS,
+ }),
+ createIx,
+ );
+
+ const txBase64 = tx
+ .serialize({ requireAllSignatures: false, verifySignatures: false })
+ .toString('base64');
+
+ const prepId = await randomToken(24);
+ const expiresAt = new Date(Date.now() + 30 * 60 * 1000);
+
+ await sql`
+ insert into payment_configs_pending
+ (id, user_id, agent_id, cluster, mint, payload, expires_at)
+ values (
+ ${prepId},
+ ${user.id},
+ ${agent.id},
+ ${body.cluster},
+ ${tokenMint},
+ ${JSON.stringify({
+ wallet_address: body.wallet_address,
+ program_id: PUMP_AGENT_PAYMENTS_PROGRAM_ID.toString(),
+ })}::jsonb,
+ ${expiresAt}
+ )
+ on conflict (id) do nothing
+ `;
+
+ return json(res, 201, {
+ prep_id: prepId,
+ mint: tokenMint,
+ tx_base64: txBase64,
+ cluster: body.cluster,
+ expires_at: expiresAt.toISOString(),
+ });
+});
diff --git a/api/agents/solana-reputation-history.js b/api/agents/solana-reputation-history.js
new file mode 100644
index 000000000..1ddd60473
--- /dev/null
+++ b/api/agents/solana-reputation-history.js
@@ -0,0 +1,101 @@
+/**
+ * GET /api/agents/solana-reputation-history?asset=<pubkey>&network=devnet|mainnet&days=30
+ *
+ * Daily reputation buckets for sparkline rendering. Each bucket is the
+ * average feedback score for that UTC day. Days with no feedback are
+ * elided — the client should render gaps appropriately.
+ *
+ * Returns the strongest available tier per bucket (credentialed >
+ * verified > event-attested > raw) so the line reflects the same trust
+ * model as the headline grade on the passport.
+ */
+
+import { sql } from '../_lib/db.js';
+import { PublicKey } from '@solana/web3.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+const MAX_DAYS = 90;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) 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 asset = url.searchParams.get('asset');
+ const network = url.searchParams.get('network') === 'mainnet' ? 'mainnet' : 'devnet';
+ const days = Math.min(Math.max(Number(url.searchParams.get('days') || 30), 1), MAX_DAYS);
+
+ if (!asset) return error(res, 400, 'validation_error', 'asset query param required');
+ try { new PublicKey(asset); }
+ catch { return error(res, 400, 'validation_error', 'invalid asset pubkey'); }
+
+ const rows = await sql`
+ with feedback as (
+ select
+ date_trunc('day', f.block_time) as day,
+ f.attester,
+ (f.payload->>'score')::int as score,
+ exists (
+ select 1 from solana_attestations a
+ where a.agent_asset = f.agent_asset
+ and a.kind = 'threews.accept.v1'
+ and a.payload->>'task_id' = f.payload->>'task_id'
+ and a.verified = true
+ and f.payload->>'task_id' is not null
+ ) as task_accepted,
+ exists (
+ select 1 from solana_credentials c
+ where c.subject = f.attester
+ and c.network = f.network
+ and c.kind = 'threews.verified-client.v1'
+ and c.closed = false
+ and (c.expiry is null or c.expiry > f.block_time)
+ ) as credentialed,
+ (f.payload->>'source' like 'pumpkit.%') as event_attested
+ from solana_attestations f
+ where f.agent_asset = ${asset}
+ and f.network = ${network}
+ and f.kind = 'threews.feedback.v1'
+ and f.revoked = false
+ and f.block_time >= now() - (${days} || ' days')::interval
+ )
+ select
+ day,
+ count(*)::int as n,
+ coalesce(avg(score) filter (where credentialed), 0)::float as score_credentialed,
+ coalesce(avg(score) filter (where task_accepted), 0)::float as score_verified,
+ coalesce(avg(score) filter (where event_attested), 0)::float as score_event,
+ coalesce(avg(score), 0)::float as score_raw,
+ count(*) filter (where credentialed)::int as n_credentialed,
+ count(*) filter (where task_accepted)::int as n_verified,
+ count(*) filter (where event_attested)::int as n_event
+ from feedback
+ group by day
+ order by day asc
+ `;
+
+ const series = rows.map((r) => {
+ const tier =
+ r.n_credentialed > 0 ? { tier: 'credentialed', score: r.score_credentialed, n: r.n_credentialed } :
+ r.n_verified > 0 ? { tier: 'verified', score: r.score_verified, n: r.n_verified } :
+ r.n_event > 0 ? { tier: 'event', score: r.score_event, n: r.n_event } :
+ { tier: 'community', score: r.score_raw, n: r.n };
+ return {
+ day: r.day instanceof Date ? r.day.toISOString().slice(0, 10) : String(r.day).slice(0, 10),
+ tier: tier.tier,
+ score: Number(tier.score.toFixed(3)),
+ n: tier.n,
+ };
+ });
+
+ return json(res, 200, {
+ agent: asset,
+ network,
+ days,
+ series,
+ });
+});
diff --git a/api/pump/buy-prep.js b/api/pump/buy-prep.js
new file mode 100644
index 000000000..3d55e2895
--- /dev/null
+++ b/api/pump/buy-prep.js
@@ -0,0 +1,113 @@
+// POST /api/pump/buy-prep
+//
+// Auto-routes between bonding-curve buy (pre-graduation) and AMM buy
+// (post-graduation), returning an unsigned tx the wallet signs and submits.
+// Body: { mint, network, sol, slippage_bps?, wallet_address }
+
+import { z } from 'zod';
+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 {
+ getConnection,
+ getPumpSdk,
+ getAmmPoolState,
+ buildUnsignedTxBase64,
+ solanaPubkey,
+} from '../_lib/pump.js';
+
+const bodySchema = z.object({
+ mint: z.string().min(32).max(44),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ sol: z.number().positive().max(50),
+ slippage_bps: z.number().int().min(0).max(5000).default(100),
+ wallet_address: z.string().min(32).max(44),
+});
+
+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 userPk = solanaPubkey(body.wallet_address);
+ const mintPk = solanaPubkey(body.mint);
+ if (!userPk || !mintPk) return error(res, 400, 'validation_error', 'invalid pubkeys');
+
+ try {
+ const { sdk, BN, web3 } = await getPumpSdk({ network: body.network });
+ const lamports = new BN(Math.floor(body.sol * web3.LAMPORTS_PER_SOL));
+ const slippage = body.slippage_bps / 10_000;
+
+ // Try bonding curve.
+ let buyState = null;
+ try {
+ if (sdk.fetchBuyState) buyState = await sdk.fetchBuyState(mintPk, userPk);
+ } catch {
+ buyState = null;
+ }
+
+ if (buyState && buyState.bondingCurve && !buyState.bondingCurve.complete) {
+ const global = await sdk.fetchGlobal();
+ const ixs = await sdk.buyInstructions({
+ global,
+ bondingCurveAccountInfo: buyState.bondingCurveAccountInfo,
+ bondingCurve: buyState.bondingCurve,
+ associatedUserAccountInfo: buyState.associatedUserAccountInfo,
+ mint: mintPk,
+ user: userPk,
+ amount: new BN(0),
+ solAmount: lamports,
+ slippage,
+ });
+ const tx_base64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: userPk,
+ instructions: ixs,
+ });
+ return json(res, 201, {
+ route: 'bonding_curve',
+ mint: body.mint,
+ network: body.network,
+ sol_in: body.sol,
+ slippage_bps: body.slippage_bps,
+ tx_base64,
+ });
+ }
+
+ // AMM
+ const amm = await getAmmPoolState({ network: body.network, mint: mintPk });
+ const ammMod = await import('@pump-fun/pump-swap-sdk');
+ const offline = new ammMod.PumpAmmSdk();
+ const onlineAmm = new ammMod.OnlinePumpAmmSdk(getConnection({ network: body.network }));
+ const swapState = await onlineAmm.swapSolanaState(amm.poolKey, userPk);
+ const ixs = await offline.buyQuoteInput(swapState, lamports, slippage);
+ const tx_base64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: userPk,
+ instructions: ixs,
+ });
+ return json(res, 201, {
+ route: 'amm',
+ pool: amm.poolKey.toString(),
+ mint: body.mint,
+ network: body.network,
+ sol_in: body.sol,
+ slippage_bps: body.slippage_bps,
+ tx_base64,
+ });
+ } catch (e) {
+ return error(
+ res,
+ e.status || 502,
+ e.code || 'pump_sdk_error',
+ e.message || 'failed to build buy tx',
+ );
+ }
+});
diff --git a/api/pump/launch-prep.js b/api/pump/launch-prep.js
index d602de66e..638d80ccb 100644
--- a/api/pump/launch-prep.js
+++ b/api/pump/launch-prep.js
@@ -158,13 +158,17 @@ export default wrap(async (req, res) => {
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'),
+ // Mint keypair must co-sign the tx. When server-generated, we hand
+ // the secret to the frontend; when client-supplied (vanity), the
+ // client already holds it and the server never sees it.
+ mint_secret_key_b64: mintKeypair ? Buffer.from(mintKeypair.secretKey).toString('base64') : null,
+ client_supplied_mint: !mintKeypair,
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.',
+ instructions: mintKeypair
+ ? '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.'
+ : 'Decode tx_base64 as VersionedTransaction. Sign with your locally-held vanity mint keypair AND the user wallet, submit, then POST /api/pump/launch-confirm with the tx_signature.',
});
});
diff --git a/api/pump/sell-prep.js b/api/pump/sell-prep.js
new file mode 100644
index 000000000..eecb336d9
--- /dev/null
+++ b/api/pump/sell-prep.js
@@ -0,0 +1,109 @@
+// POST /api/pump/sell-prep
+//
+// Auto-routes between bonding-curve sell and AMM sell. Returns unsigned tx.
+// Body: { mint, network, tokens, slippage_bps?, wallet_address }
+
+import { z } from 'zod';
+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 {
+ getConnection,
+ getPumpSdk,
+ getAmmPoolState,
+ buildUnsignedTxBase64,
+ solanaPubkey,
+} from '../_lib/pump.js';
+
+const bodySchema = z.object({
+ mint: z.string().min(32).max(44),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ tokens: z.string().regex(/^\d+$/, 'tokens must be a base-units integer string'),
+ slippage_bps: z.number().int().min(0).max(5000).default(100),
+ wallet_address: z.string().min(32).max(44),
+});
+
+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 userPk = solanaPubkey(body.wallet_address);
+ const mintPk = solanaPubkey(body.mint);
+ if (!userPk || !mintPk) return error(res, 400, 'validation_error', 'invalid pubkeys');
+
+ try {
+ const { sdk, BN } = await getPumpSdk({ network: body.network });
+ const tokens = new BN(body.tokens);
+ const slippage = body.slippage_bps / 10_000;
+
+ let sellState = null;
+ try {
+ if (sdk.fetchSellState) sellState = await sdk.fetchSellState(mintPk, userPk);
+ } catch {
+ sellState = null;
+ }
+
+ if (sellState && sellState.bondingCurve && !sellState.bondingCurve.complete) {
+ const global = await sdk.fetchGlobal();
+ const ixs = await sdk.sellInstructions({
+ global,
+ bondingCurveAccountInfo: sellState.bondingCurveAccountInfo,
+ bondingCurve: sellState.bondingCurve,
+ mint: mintPk,
+ user: userPk,
+ amount: tokens,
+ solAmount: new BN(0),
+ slippage,
+ });
+ const tx_base64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: userPk,
+ instructions: ixs,
+ });
+ return json(res, 201, {
+ route: 'bonding_curve',
+ mint: body.mint,
+ network: body.network,
+ tokens_in: body.tokens,
+ slippage_bps: body.slippage_bps,
+ tx_base64,
+ });
+ }
+
+ const amm = await getAmmPoolState({ network: body.network, mint: mintPk });
+ const ammMod = await import('@pump-fun/pump-swap-sdk');
+ const offline = new ammMod.PumpAmmSdk();
+ const onlineAmm = new ammMod.OnlinePumpAmmSdk(getConnection({ network: body.network }));
+ const swapState = await onlineAmm.swapSolanaState(amm.poolKey, userPk);
+ const ixs = await offline.sellBaseInput(swapState, tokens, slippage);
+ const tx_base64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: userPk,
+ instructions: ixs,
+ });
+ return json(res, 201, {
+ route: 'amm',
+ pool: amm.poolKey.toString(),
+ mint: body.mint,
+ network: body.network,
+ tokens_in: body.tokens,
+ slippage_bps: body.slippage_bps,
+ tx_base64,
+ });
+ } catch (e) {
+ return error(
+ res,
+ e.status || 502,
+ e.code || 'pump_sdk_error',
+ e.message || 'failed to build sell tx',
+ );
+ }
+});
diff --git a/public/agent-badge.html b/public/agent-badge.html
new file mode 100644
index 000000000..b22a7fbdf
--- /dev/null
+++ b/public/agent-badge.html
@@ -0,0 +1,112 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>Agent badge</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <style>
+ * { box-sizing: border-box; }
+ html, body { margin: 0; padding: 0; background: transparent; }
+ body { font: 12px/1.35 system-ui, -apple-system, sans-serif; color: #111; }
+ body[data-theme="dark"] { color: #f5f5f5; }
+ .badge {
+ display: inline-flex; align-items: center; gap: .65rem;
+ padding: .55rem .75rem; border: 1px solid #e5e5e5; border-radius: 10px;
+ background: #fff; min-width: 240px; max-width: 320px;
+ text-decoration: none; color: inherit;
+ }
+ body[data-theme="dark"] .badge { background: #18181b; border-color: #2a2a2e; }
+ .grade { font-size: 1.6rem; font-weight: 700; line-height: 1; min-width: 1.4rem; text-align: center; }
+ .grade.A { color: #1b5e20; } .grade.B { color: #2e7d32; }
+ .grade.C { color: #855008; } .grade.D { color: #c62828; }
+ .grade.NA { color: #888; }
+ body[data-theme="dark"] .grade.A { color: #81c784; }
+ body[data-theme="dark"] .grade.B { color: #a5d6a7; }
+ body[data-theme="dark"] .grade.C { color: #ffd180; }
+ body[data-theme="dark"] .grade.D { color: #ef9a9a; }
+ .body { display: flex; flex-direction: column; min-width: 0; flex: 1; }
+ .title { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 200px; }
+ .meta { color: #666; font-size: 11px; }
+ body[data-theme="dark"] .meta { color: #a1a1aa; }
+ .chain { display: inline-block; padding: 0 .35rem; border-radius: 999px; font-size: 10px; line-height: 16px; height: 16px; vertical-align: 1px; }
+ .chain.devnet { background: #fff3cd; color: #855008; }
+ .chain.mainnet { background: #e7f5e9; color: #1b5e20; }
+ .error { color: #c62828; padding: .4rem .55rem; font-size: 11px; }
+ </style>
+</head>
+<body>
+ <div id="root"><div class="badge"><div class="grade NA">…</div><div class="body"><div class="title">loading</div></div></div></div>
+
+ <script type="module">
+ const params = new URLSearchParams(location.search);
+ const asset = (params.get('asset') || '').trim();
+ const network = params.get('network') === 'mainnet' ? 'mainnet' : 'devnet';
+ const theme = params.get('theme') === 'dark' ? 'dark' : 'light';
+ const link = params.get('link') !== '0';
+ document.body.dataset.theme = theme;
+
+ const PUBKEY_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+ const $root = document.getElementById('root');
+
+ function fmt(n) { return (typeof n === 'number' && n > 0) ? n.toFixed(2) : '—'; }
+
+ function computeTrust(rep) {
+ const f = rep?.feedback || {};
+ const v = rep?.validation || {};
+ const tiers = [
+ { score: f.score_avg_weighted_credentialed, n: f.unique_credentialed_attesters, tier: 'credentialed' },
+ { score: f.score_avg_weighted_verified, n: f.unique_verified_attesters, tier: 'verified' },
+ { score: f.score_avg_event_attested, n: f.event_attested, tier: 'event' },
+ { score: f.score_avg_weighted, n: f.unique_attesters, tier: 'community' },
+ ];
+ const best = tiers.find((t) => t.score > 0 && (t.n || 0) > 0);
+ if (!best) return { grade: '—', cls: 'NA', tier: '—', score: 0, n: 0 };
+ const passed = v.audited_passed || v.self_passed || 0;
+ const failed = v.audited_failed || v.self_failed || 0;
+ const passRate = (passed + failed) ? passed / (passed + failed) : 1;
+ const adjust = best.score - (f.disputed > 0 ? 0.5 : 0) - (passRate < 0.5 ? 1 : 0);
+ const grade = adjust >= 4.5 ? 'A' : adjust >= 3.8 ? 'B' : adjust >= 3.0 ? 'C' : 'D';
+ return { grade, cls: grade, tier: best.tier, score: best.score, n: best.n };
+ }
+
+ function escapeHtml(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' })[c]);
+ }
+
+ function render(card, rep) {
+ const t = computeTrust(rep);
+ const name = card?.name || '(agent)';
+ const passportUrl = `/agent-passport.html?asset=${encodeURIComponent(asset)}&network=${network}`;
+ const inner = `
+ <div class="grade ${t.cls}">${t.grade}</div>
+ <div class="body">
+ <div class="title">${escapeHtml(name)}</div>
+ <div class="meta">
+ <span class="chain ${network}">${network}</span>
+ ${t.grade !== '—' ? `· ${t.tier} ${fmt(t.score)} · ${t.n} attester${t.n === 1 ? '' : 's'}` : '· no attestations'}
+ </div>
+ </div>`;
+ $root.innerHTML = link
+ ? `<a class="badge" href="${passportUrl}" target="_blank" rel="noopener">${inner}</a>`
+ : `<div class="badge">${inner}</div>`;
+ }
+
+ async function load() {
+ if (!PUBKEY_RE.test(asset)) {
+ $root.innerHTML = `<div class="error">invalid asset</div>`;
+ return;
+ }
+ try {
+ const [card, rep] = await Promise.all([
+ fetch(`/api/agents/solana-card?asset=${asset}`).then((r) => r.ok ? r.json() : null).catch(() => null),
+ fetch(`/api/agents/solana-reputation?asset=${asset}&network=${network}`).then((r) => r.json()),
+ ]);
+ render(card, rep);
+ } catch (e) {
+ $root.innerHTML = `<div class="error">${escapeHtml(e.message || 'load failed')}</div>`;
+ }
+ }
+ load();
+ </script>
+</body>
+</html>
diff --git a/src/agent-home-pumpfun.js b/src/agent-home-pumpfun.js
index 62aa01f81..07b1a4d75 100644
--- a/src/agent-home-pumpfun.js
+++ b/src/agent-home-pumpfun.js
@@ -1,32 +1,58 @@
/**
* Pump.fun card on the agent home panel
* --------------------------------------
- * Two states:
+ * States:
+ * - skeleton (loading)
+ * - cta (no token yet) → one-click launch
+ * - active (token launched) → live status + inline trade panel
+ * - graduated (curve complete) → AMM badge
*
- * 1. Agent has NOT launched a token → "Launch coin" CTA
- * Triggers pumpfun-self-launch-from-identity (server-signed).
+ * Trade UX:
+ * - Inline trade panel (no window.prompt). Live-quotes via pumpfun-curve-quote
+ * while the user types (debounced). Shows expected output and price impact.
+ * - Skill toasts: every successful pumpfun-* result surfaces a transient
+ * toast with the tx signature linking to the explorer.
*
- * 2. Agent HAS launched a token → Live status card
- * Shows mint, market cap, % to graduation, buy/sell links.
- * Refreshes every 30s by calling pumpfun-watch-curve.
+ * Mobile: action buttons wrap; trade panel collapses to a single column.
*
- * Detection: we read the agent's memory for the `pumpfun:launch` tag
- * (written by agent-skills-pumpfun-hooks.js). If absent, we also try
- * /api/agents/:id (in case the launch happened from a different device
- * and was persisted to meta.pumpfun_mint).
+ * Mint click: opens the existing pumpfun-feed widget filtered to that mint
+ * inside the host page (when available) instead of leaving for pump.fun.
*/
+import { ACTION_TYPES } from './agent-protocol.js';
+
const REFRESH_MS = 30_000;
+const QUOTE_DEBOUNCE_MS = 250;
-export function mountPumpFunCard({ panel, identity, skills, memory }) {
+export function mountPumpFunCard({ panel, identity, skills, memory, protocol }) {
if (!panel || !identity?.id) return null;
+ protocol = protocol || (typeof window !== 'undefined' ? window.VIEWER?.agent_protocol : null);
const root = document.createElement('section');
root.className = 'agent-home-pumpfun';
panel.appendChild(root);
- let state = { mint: null, symbol: null, network: 'mainnet', loading: true };
+ const toastTray = document.createElement('div');
+ toastTray.className = 'pumpfun-toasts';
+ root.appendChild(toastTray);
+
+ let state = {
+ mint: null,
+ symbol: null,
+ network: 'mainnet',
+ loading: true,
+ tradeOpen: null, // null | 'buy' | 'sell'
+ tradeAmount: '',
+ quote: null,
+ quoting: false,
+ };
let refreshTimer = null;
+ let quoteTimer = null;
+ let unsubProtocol = null;
+
+ const cardBody = document.createElement('div');
+ cardBody.className = 'pumpfun-card-body';
+ root.appendChild(cardBody);
const launchCard = () => `
<div class="pumpfun-card pumpfun-card--cta">
@@ -45,16 +71,17 @@ export function mountPumpFunCard({ panel, identity, skills, memory }) {
const statusCard = (s) => {
const pct = s.progressPct != null ? `${s.progressPct.toFixed(1)}%` : '—';
const cap = s.marketCap ? formatLamports(s.marketCap) : '—';
- const explorer = s.network === 'devnet'
- ? `https://pump.fun/coin/${s.mint}?cluster=devnet`
- : `https://pump.fun/coin/${s.mint}`;
+ const explorer =
+ s.network === 'devnet'
+ ? `https://pump.fun/coin/${s.mint}?cluster=devnet`
+ : `https://pump.fun/coin/${s.mint}`;
const grad = s.graduated;
return `
<div class="pumpfun-card ${grad ? 'pumpfun-card--graduated' : ''}">
<div class="pumpfun-card-head">
<span class="pumpfun-card-icon">${grad ? '🎓' : '◎'}</span>
<span class="pumpfun-card-title">${escapeHtml(s.symbol || 'Token')}</span>
- <a class="pumpfun-card-link" href="${explorer}" target="_blank" rel="noopener" title="View on pump.fun">↗</a>
+ <a class="pumpfun-card-link" href="${explorer}" target="_blank" rel="noopener" title="Open on pump.fun">↗</a>
</div>
<div class="pumpfun-stats">
<div class="pumpfun-stat">
@@ -66,13 +93,57 @@ export function mountPumpFunCard({ panel, identity, skills, memory }) {
<span class="pumpfun-stat-value">${grad ? 'Graduated' : pct}</span>
</div>
</div>
- ${grad ? '' : `<div class="pumpfun-progress"><div class="pumpfun-progress-bar" style="width:${Math.min(100, s.progressPct || 0)}%"></div></div>`}
- <div class="pumpfun-card-mint" title="${escapeAttr(s.mint)}">${shortMint(s.mint)}</div>
+ ${grad ? '' : `<div class="pumpfun-progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${(s.progressPct || 0).toFixed(1)}"><div class="pumpfun-progress-bar" style="width:${Math.min(100, s.progressPct || 0)}%"></div></div>`}
+ <button class="pumpfun-card-mint" data-action="open-feed" title="Open live feed for this mint">${shortMint(s.mint)}</button>
<div class="pumpfun-card-actions">
- <button class="pumpfun-btn" data-action="buy">Buy</button>
- <button class="pumpfun-btn" data-action="sell">Sell</button>
+ <button class="pumpfun-btn ${s.tradeOpen === 'buy' ? 'pumpfun-btn--active' : ''}" data-action="toggle-buy">Buy</button>
+ <button class="pumpfun-btn ${s.tradeOpen === 'sell' ? 'pumpfun-btn--active' : ''}" data-action="toggle-sell">Sell</button>
<button class="pumpfun-btn pumpfun-btn--ghost" data-action="claim">Claim fees</button>
</div>
+ ${s.tradeOpen ? tradePanel(s) : ''}
+ </div>
+ `;
+ };
+
+ const tradePanel = (s) => {
+ const isBuy = s.tradeOpen === 'buy';
+ const placeholder = isBuy ? '0.1' : '1000000';
+ const unit = isBuy ? 'SOL' : 'units';
+ const q = s.quote;
+ let preview = '';
+ if (s.quoting) {
+ preview = `<span class="pumpfun-quote-status">Quoting…</span>`;
+ } else if (q && q.success) {
+ const out = isBuy
+ ? `≈ ${formatNumber(q.data?.tokensOut)} ${escapeHtml(s.symbol || 'tokens')}`
+ : `≈ ${formatLamports(q.data?.solOut)}`;
+ preview = `<span class="pumpfun-quote-out">${out}</span>`;
+ } else if (q && !q.success) {
+ preview = `<span class="pumpfun-quote-err">${escapeHtml(q.output || 'No quote')}</span>`;
+ }
+ return `
+ <div class="pumpfun-trade">
+ <label class="pumpfun-trade-label">
+ <span>${isBuy ? 'Spend' : 'Sell'}</span>
+ <input
+ class="pumpfun-trade-input"
+ id="pf-trade-amount"
+ type="text"
+ inputmode="decimal"
+ placeholder="${placeholder}"
+ value="${escapeAttr(s.tradeAmount)}"
+ autocomplete="off"
+ spellcheck="false"
+ >
+ <span class="pumpfun-trade-unit">${unit}</span>
+ </label>
+ <div class="pumpfun-quote">${preview}</div>
+ <div class="pumpfun-trade-actions">
+ <button class="pumpfun-btn pumpfun-btn--ghost" data-action="close-trade">Cancel</button>
+ <button class="pumpfun-btn pumpfun-btn--primary" data-action="confirm-trade" ${isExecutable(s) ? '' : 'disabled'}>
+ ${isBuy ? 'Buy' : 'Sell'}${q?.success ? '' : ''}
+ </button>
+ </div>
</div>
`;
};
@@ -81,67 +152,231 @@ export function mountPumpFunCard({ panel, identity, skills, memory }) {
const render = () => {
if (state.loading) {
- root.innerHTML = skeleton();
+ cardBody.innerHTML = skeleton();
return;
}
- root.innerHTML = state.mint ? statusCard(state) : launchCard();
+ cardBody.innerHTML = state.mint ? statusCard(state) : launchCard();
bind();
+ // Restore focus to the input after re-render so typing stays uninterrupted.
+ if (state.tradeOpen) {
+ const el = cardBody.querySelector('#pf-trade-amount');
+ if (el) {
+ el.focus();
+ const len = el.value.length;
+ try { el.setSelectionRange(len, len); } catch {/*ignore*/}
+ }
+ }
};
const bind = () => {
- const launchBtn = root.querySelector('#pf-launch-btn');
+ const launchBtn = cardBody.querySelector('#pf-launch-btn');
if (launchBtn) {
- launchBtn.addEventListener('click', async () => {
- launchBtn.disabled = true;
- launchBtn.textContent = 'Launching…';
- try {
- const r = await skills?.perform(
- 'pumpfun-self-launch-from-identity',
- { network: state.network },
- { identity },
- );
- if (r?.success && r.data?.mint) {
- state = { ...state, mint: r.data.mint, symbol: r.data.symbol, loading: true };
- await refresh();
- } else {
- launchBtn.disabled = false;
- launchBtn.textContent = `Retry launch ${deriveSymbol(identity.name)}`;
- }
- } catch {
- launchBtn.disabled = false;
- launchBtn.textContent = 'Launch failed — retry';
+ launchBtn.addEventListener('click', () => doLaunch(launchBtn));
+ }
+ cardBody.querySelectorAll('[data-action]').forEach((btn) => {
+ btn.addEventListener('click', (e) => handleAction(btn.dataset.action, e));
+ });
+ const input = cardBody.querySelector('#pf-trade-amount');
+ if (input) {
+ input.addEventListener('input', (e) => {
+ state.tradeAmount = e.target.value;
+ scheduleQuote();
+ const btn = cardBody.querySelector('[data-action="confirm-trade"]');
+ if (btn) btn.disabled = !isExecutable(state);
+ });
+ input.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && isExecutable(state)) {
+ e.preventDefault();
+ executeTrade();
+ } else if (e.key === 'Escape') {
+ closeTrade();
}
});
}
- root.querySelectorAll('[data-action]').forEach((btn) => {
- btn.addEventListener('click', () => handleAction(btn.dataset.action));
- });
};
- const handleAction = async (action) => {
- if (!state.mint || !skills) return;
- if (action === 'claim') {
- await skills.perform('pumpfun-claim-fees', { network: state.network }, { identity });
+ async function doLaunch(launchBtn) {
+ launchBtn.disabled = true;
+ launchBtn.textContent = 'Launching…';
+ try {
+ const r = await skills?.perform(
+ 'pumpfun-launch-and-narrate',
+ { network: state.network },
+ { identity },
+ );
+ if (r?.success && r.data?.mint) {
+ toast(`Launched ${r.data.symbol || ''}`, r.data.signature, state.network, 'success');
+ state = { ...state, mint: r.data.mint, symbol: r.data.symbol, loading: true };
+ await refresh();
+ } else {
+ launchBtn.disabled = false;
+ launchBtn.textContent = `Retry launch ${deriveSymbol(identity.name)}`;
+ toast(r?.output || 'Launch failed', null, null, 'error');
+ }
+ } catch (err) {
+ launchBtn.disabled = false;
+ launchBtn.textContent = 'Launch failed — retry';
+ toast(err.message || 'Launch failed', null, null, 'error');
+ }
+ }
+
+ const handleAction = (action) => {
+ if (action === 'open-feed') return openFeed();
+ if (action === 'claim') return doClaim();
+ if (action === 'toggle-buy') return toggleTrade('buy');
+ if (action === 'toggle-sell') return toggleTrade('sell');
+ if (action === 'close-trade') return closeTrade();
+ if (action === 'confirm-trade') return executeTrade();
+ };
+
+ const toggleTrade = (side) => {
+ state.tradeOpen = state.tradeOpen === side ? null : side;
+ state.tradeAmount = '';
+ state.quote = null;
+ render();
+ };
+
+ const closeTrade = () => {
+ state.tradeOpen = null;
+ state.tradeAmount = '';
+ state.quote = null;
+ render();
+ };
+
+ const scheduleQuote = () => {
+ if (quoteTimer) clearTimeout(quoteTimer);
+ const amt = state.tradeAmount?.trim();
+ if (!amt || !isFinite(parseFloat(amt))) {
+ state.quote = null;
+ updateQuoteDOM();
return;
}
- const amount = window.prompt(
- action === 'buy' ? 'Buy how many SOL?' : 'Sell how many tokens (raw units)?',
- );
- if (!amount) return;
- if (action === 'buy') {
- await skills.perform(
- 'pumpfun-buy',
- { mint: state.mint, solAmount: Number(amount), network: state.network },
+ state.quoting = true;
+ updateQuoteDOM();
+ quoteTimer = setTimeout(async () => {
+ try {
+ const isBuy = state.tradeOpen === 'buy';
+ const r = await skills.perform(
+ 'pumpfun-curve-quote',
+ {
+ mint: state.mint,
+ side: isBuy ? 'buy' : 'sell',
+ solAmount: isBuy ? parseFloat(amt) : undefined,
+ tokenAmount: isBuy ? undefined : amt.replace(/\D/g, ''),
+ network: state.network,
+ },
+ { identity },
+ );
+ state.quote = r;
+ state.quoting = false;
+ updateQuoteDOM();
+ } catch {
+ state.quote = { success: false, output: 'Quote unavailable' };
+ state.quoting = false;
+ updateQuoteDOM();
+ }
+ }, QUOTE_DEBOUNCE_MS);
+ };
+
+ const updateQuoteDOM = () => {
+ const slot = cardBody.querySelector('.pumpfun-quote');
+ const btn = cardBody.querySelector('[data-action="confirm-trade"]');
+ if (!slot) return;
+ const q = state.quote;
+ if (state.quoting) {
+ slot.innerHTML = `<span class="pumpfun-quote-status">Quoting…</span>`;
+ } else if (q && q.success) {
+ const isBuy = state.tradeOpen === 'buy';
+ const out = isBuy
+ ? `≈ ${formatNumber(q.data?.tokensOut)} ${escapeHtml(state.symbol || 'tokens')}`
+ : `≈ ${formatLamports(q.data?.solOut)}`;
+ slot.innerHTML = `<span class="pumpfun-quote-out">${out}</span>`;
+ } else if (q && !q.success) {
+ slot.innerHTML = `<span class="pumpfun-quote-err">${escapeHtml(q.output || 'No quote')}</span>`;
+ } else {
+ slot.innerHTML = '';
+ }
+ if (btn) btn.disabled = !isExecutable(state);
+ };
+
+ const executeTrade = async () => {
+ if (!isExecutable(state)) return;
+ const isBuy = state.tradeOpen === 'buy';
+ const btn = cardBody.querySelector('[data-action="confirm-trade"]');
+ if (btn) {
+ btn.disabled = true;
+ btn.textContent = 'Sending…';
+ }
+ try {
+ const r = await skills.perform(
+ isBuy ? 'pumpfun-buy-with-quote' : 'pumpfun-sell',
+ isBuy
+ ? { mint: state.mint, solAmount: parseFloat(state.tradeAmount), network: state.network }
+ : {
+ mint: state.mint,
+ tokenAmount: state.tradeAmount.replace(/\D/g, ''),
+ network: state.network,
+ },
{ identity },
);
- } else {
- await skills.perform(
- 'pumpfun-sell',
- { mint: state.mint, tokenAmount: amount, network: state.network },
+ if (r?.success) {
+ toast(
+ isBuy ? `Bought ${state.tradeAmount} SOL` : `Sold ${state.tradeAmount} units`,
+ r.data?.signature,
+ state.network,
+ 'success',
+ );
+ closeTrade();
+ await refresh();
+ } else {
+ toast(r?.output || 'Trade failed', null, null, 'error');
+ if (btn) {
+ btn.disabled = false;
+ btn.textContent = isBuy ? 'Buy' : 'Sell';
+ }
+ }
+ } catch (err) {
+ toast(err.message || 'Trade failed', null, null, 'error');
+ if (btn) {
+ btn.disabled = false;
+ btn.textContent = isBuy ? 'Buy' : 'Sell';
+ }
+ }
+ };
+
+ const doClaim = async () => {
+ try {
+ const r = await skills.perform(
+ 'pumpfun-claim-fees',
+ { network: state.network },
{ identity },
);
+ toast(
+ r?.output || (r?.success ? 'Fees claimed' : 'Claim failed'),
+ r?.data?.signature,
+ state.network,
+ r?.success ? 'success' : 'error',
+ );
+ } catch (err) {
+ toast(err.message || 'Claim failed', null, null, 'error');
+ }
+ };
+
+ const openFeed = () => {
+ // If host has the pumpfun-feed widget mounted, expose mint via custom event.
+ // Otherwise fall back to opening pump.fun in a new tab.
+ const ev = new CustomEvent('pumpfun-feed:focus-mint', {
+ detail: { mint: state.mint, network: state.network },
+ bubbles: true,
+ });
+ const handled = !root.dispatchEvent(ev) || ev.defaultPrevented;
+ if (!handled) {
+ const url =
+ state.network === 'devnet'
+ ? `https://pump.fun/coin/${state.mint}?cluster=devnet`
+ : `https://pump.fun/coin/${state.mint}`;
+ window.open(url, '_blank', 'noopener');
}
- await refresh();
};
const refresh = async () => {
@@ -159,29 +394,82 @@ export function mountPumpFunCard({ panel, identity, skills, memory }) {
state = { ...state, ...r.data };
render();
}
- } catch {
- /* swallow */
- }
+ } catch {/* swallow */}
}
};
+ // ── Toasts ───────────────────────────────────────────────────────────────
+ function toast(message, signature, network, level = 'info') {
+ const el = document.createElement('div');
+ el.className = `pumpfun-toast pumpfun-toast--${level}`;
+ const explorer = signature
+ ? network === 'devnet'
+ ? `https://explorer.solana.com/tx/${signature}?cluster=devnet`
+ : `https://solscan.io/tx/${signature}`
+ : null;
+ el.innerHTML = `
+ <span class="pumpfun-toast-msg">${escapeHtml(message)}</span>
+ ${explorer ? `<a class="pumpfun-toast-link" href="${explorer}" target="_blank" rel="noopener">↗</a>` : ''}
+ `;
+ toastTray.appendChild(el);
+ // Trigger entry animation on next frame.
+ requestAnimationFrame(() => el.classList.add('is-in'));
+ setTimeout(() => {
+ el.classList.remove('is-in');
+ setTimeout(() => el.remove(), 240);
+ }, 5500);
+ }
+
+ // Subscribe to skill-done events globally so non-card-initiated trades
+ // (e.g. from the LLM tool loop or chat) also surface as toasts here.
+ if (protocol?.on) {
+ const handler = (ev) => {
+ const skill = ev.detail?.payload?.skill;
+ const result = ev.detail?.payload?.result;
+ if (!skill || !skill.startsWith('pumpfun-') || !result) return;
+ // Skip the ones that are reads or already toasted by direct caller.
+ if (skill === 'pumpfun-watch-curve' || skill === 'pumpfun-curve-quote' || skill === 'pumpfun-status')
+ return;
+ if (result.success && result.data?.signature) {
+ toast(result.output || 'Done', result.data.signature, result.data.network || state.network, 'success');
+ }
+ };
+ protocol.on(ACTION_TYPES.SKILL_DONE, handler);
+ unsubProtocol = () => protocol.off?.(ACTION_TYPES.SKILL_DONE, handler);
+ }
+
refresh();
- refreshTimer = setInterval(() => state.mint && refresh(), REFRESH_MS);
+ refreshTimer = setInterval(() => state.mint && !state.tradeOpen && refresh(), REFRESH_MS);
return {
destroy() {
if (refreshTimer) clearInterval(refreshTimer);
+ if (quoteTimer) clearTimeout(quoteTimer);
+ if (unsubProtocol) unsubProtocol();
root.remove();
},
refresh,
};
}
+// ── helpers ─────────────────────────────────────────────────────────────────
+
+function isExecutable(s) {
+ if (!s.tradeOpen || !s.tradeAmount) return false;
+ const n = parseFloat(s.tradeAmount);
+ if (!isFinite(n) || n <= 0) return false;
+ if (s.quoting) return false;
+ if (s.quote && s.quote.success === false) return false;
+ return true;
+}
+
function resolveMintFrom(memory, identity) {
try {
if (memory?.recall) {
const hits = memory.recall('pumpfun:launch') || [];
- const latest = hits.sort((a, b) => (b.context?.launchedAt || 0) - (a.context?.launchedAt || 0))[0];
+ const latest = hits.sort(
+ (a, b) => (b.context?.launchedAt || 0) - (a.context?.launchedAt || 0),
+ )[0];
if (latest?.context?.mint) {
return {
mint: latest.context.mint,
@@ -190,9 +478,7 @@ function resolveMintFrom(memory, identity) {
};
}
}
- } catch {
- /* ignore */
- }
+ } catch {/* ignore */}
const meta = identity?.meta || {};
if (meta.pumpfun_mint) {
return {
@@ -220,11 +506,22 @@ function shortMint(m) {
function formatLamports(lamports) {
const n = Number(lamports) / 1e9;
+ if (!isFinite(n)) return '—';
if (n >= 1000) return `${(n / 1000).toFixed(1)}K SOL`;
if (n >= 1) return `${n.toFixed(2)} SOL`;
return `${n.toFixed(4)} SOL`;
}
+function formatNumber(s) {
+ if (s == null) return '—';
+ const n = Number(s);
+ if (!isFinite(n)) return String(s);
+ if (n >= 1e9) return `${(n / 1e9).toFixed(2)}B`;
+ if (n >= 1e6) return `${(n / 1e6).toFixed(2)}M`;
+ if (n >= 1e3) return `${(n / 1e3).toFixed(2)}K`;
+ return String(Math.round(n));
+}
+
function escapeHtml(s) {
return String(s || '').replace(/[&<>"']/g, (c) => ({
'&': '&amp;',
diff --git a/src/solana/vanity/launch-with-vanity.js b/src/solana/vanity/launch-with-vanity.js
new file mode 100644
index 000000000..fc9193b4e
--- /dev/null
+++ b/src/solana/vanity/launch-with-vanity.js
@@ -0,0 +1,73 @@
+/**
+ * Vanity-launch helper: grind a vanity mint address client-side, POST it to
+ * /api/pump/launch-prep so the unsigned tx is built around the vanity pubkey,
+ * then return the prep payload + the locally-held mint keypair for co-signing.
+ *
+ * The mint secret never leaves the browser.
+ *
+ * Usage:
+ * const { prep, mintKeypair } = await launchWithVanity({
+ * agentId, walletAddress, name, symbol, uri,
+ * suffix: 'pump',
+ * onProgress: ({ rate, eta }) => console.log(rate, eta),
+ * });
+ * // ...co-sign prep.tx_base64 with both `mintKeypair` and the user wallet,
+ * // submit, then POST /api/pump/launch-confirm with the tx_signature.
+ */
+
+import { Keypair } from '@solana/web3.js';
+import { grindVanity } from './grinder.js';
+
+/**
+ * @param {object} args
+ * @param {string} args.agentId
+ * @param {string} args.walletAddress
+ * @param {string} args.name
+ * @param {string} args.symbol
+ * @param {string} args.uri
+ * @param {'mainnet'|'devnet'} [args.network]
+ * @param {number} [args.buybackBps]
+ * @param {number} [args.solBuyIn]
+ * @param {string} [args.prefix]
+ * @param {string} [args.suffix]
+ * @param {boolean} [args.ignoreCase]
+ * @param {AbortSignal} [args.signal]
+ * @param {(p: { attempts: number, rate: number, eta: string }) => void} [args.onProgress]
+ * @param {typeof fetch} [args.fetchImpl]
+ * @param {string} [args.endpoint='/api/pump/launch-prep']
+ * @returns {Promise<{ prep: object, mintKeypair: Keypair }>}
+ */
+export async function launchWithVanity(args) {
+ const { prefix, suffix, ignoreCase, signal, onProgress } = args;
+ if (!prefix && !suffix) throw new Error('prefix or suffix required for vanity launch');
+
+ const ground = await grindVanity({ prefix, suffix, ignoreCase, signal, onProgress });
+ const mintKeypair = Keypair.fromSecretKey(ground.secretKey);
+
+ const fetchImpl = args.fetchImpl || globalThis.fetch;
+ const res = await fetchImpl(args.endpoint || '/api/pump/launch-prep', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ agent_id: args.agentId,
+ wallet_address: args.walletAddress,
+ name: args.name,
+ symbol: args.symbol,
+ uri: args.uri,
+ network: args.network ?? 'mainnet',
+ buyback_bps: args.buybackBps ?? 0,
+ sol_buy_in: args.solBuyIn ?? 0,
+ mint_address: mintKeypair.publicKey.toBase58(),
+ }),
+ });
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(`launch-prep failed: ${res.status} ${body.error_description ?? body.error ?? ''}`);
+ }
+ const prep = await res.json();
+ if (prep.mint !== mintKeypair.publicKey.toBase58()) {
+ throw new Error('server returned a different mint than the vanity pubkey we sent');
+ }
+ return { prep, mintKeypair, vanity: { attempts: ground.attempts, durationMs: ground.durationMs, workers: ground.workers } };
+}
diff --git a/tests/api/pump.test.js b/tests/api/pump.test.js
index 27d2677f3..38dfae290 100644
--- a/tests/api/pump.test.js
+++ b/tests/api/pump.test.js
@@ -293,6 +293,44 @@ describe('POST /api/pump/withdraw-prep', () => {
});
});
+describe('GET /api/pump/by-agent', () => {
+ beforeEach(resetAll);
+
+ it('returns null when no mint exists', async () => {
+ sqlState.queue = [[]];
+ const { default: handler } = await import('../../api/pump/by-agent.js');
+ const { res, json } = await invoke(handler, {
+ method: 'GET',
+ url: '/api/pump/by-agent?agent_id=00000000-0000-0000-0000-000000000001',
+ });
+ expect(res.statusCode).toBe(200);
+ expect(json.data).toBe(null);
+ });
+
+ it('returns mint with stats and burns', async () => {
+ sqlState.queue = [
+ [{ id: 'mint-1', mint: mintB58, network: 'mainnet', name: 'Foo', symbol: 'FOO', buyback_bps: 500, agent_authority: walletB58 }],
+ [{ confirmed_payments: 3, unique_payers: 2, total_atomics: '1500000', last_payment_at: '2026-04-29T10:00:00Z' }],
+ [{ runs: 1, total_burned: '50000', last_burn_at: '2026-04-29T11:00:00Z' }],
+ ];
+ const { default: handler } = await import('../../api/pump/by-agent.js');
+ const { res, json } = await invoke(handler, {
+ method: 'GET',
+ url: '/api/pump/by-agent?agent_id=00000000-0000-0000-0000-000000000001',
+ });
+ expect(res.statusCode).toBe(200);
+ expect(json.data.mint).toBe(mintB58);
+ expect(json.data.stats.confirmed_payments).toBe(3);
+ expect(json.data.burns.total_burned).toBe('50000');
+ });
+
+ it('400s without agent_id', async () => {
+ const { default: handler } = await import('../../api/pump/by-agent.js');
+ const { res } = await invoke(handler, { method: 'GET', url: '/api/pump/by-agent' });
+ expect(res.statusCode).toBe(400);
+ });
+});
+
describe('GET /.well-known/x402', () => {
beforeEach(resetAll);