Skip to content

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

feat: enhance MCP authentication to support x402 payment headers and improve error handling feat: remove unused Solana attest event claims migration scripts feat: refactor pumpfun autonomous skills to support dry run functionality and improve transaction handling feat: update agent token widget to streamline withdrawal process and enhance error messaging

nirholas635338d44823
diff --git a/api/agents/pumpfun/launch.js b/api/agents/pumpfun/launch.js
index f20661828..a58f06170 100644
--- a/api/agents/pumpfun/launch.js
+++ b/api/agents/pumpfun/launch.js
@@ -127,13 +127,14 @@ export default async function handler(req, res, id) {
return error(res, 502, 'rpc_error', err.message || 'transaction failed');
}
+ const mintAddr = mint.publicKey.toBase58();
await sql`
INSERT INTO agent_actions (agent_id, type, payload, source_skill)
VALUES (
${id},
${'pumpfun.launch'},
${JSON.stringify({
- mint: mint.publicKey.toBase58(),
+ mint: mintAddr,
name: body.name,
symbol: body.symbol,
uri: body.uri,
@@ -149,6 +150,16 @@ export default async function handler(req, res, id) {
)
`.catch((e) => console.error('[pumpfun/launch] log failed', e));
+ // Register the mint in the indexer table so pump-agent-stats cron picks it up.
+ await sql`
+ INSERT INTO pump_agent_mints
+ (agent_id, user_id, network, mint, name, symbol, metadata_uri, agent_authority)
+ VALUES
+ (${id}, ${auth.userId}, ${body.network}, ${mintAddr},
+ ${body.name}, ${body.symbol}, ${body.uri}, ${keypair.publicKey.toBase58()})
+ ON CONFLICT (mint, network) DO NOTHING
+ `.catch((e) => console.error('[pumpfun/launch] mint index failed', e));
+
return json(res, 201, {
data: {
mint: mint.publicKey.toBase58(),
diff --git a/api/mcp.js b/api/mcp.js
index e56c97901..5e368038d 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -52,11 +52,41 @@ export default wrap(async (req, res) => {
if (req.method === 'DELETE') return handleTerminate(req, res);
if (req.method !== 'POST') return send401(res, 'method not supported');
+ // Auth: either a Bearer token (OAuth/API key) OR an x402 X-PAYMENT header.
const bearer = extractBearer(req);
- const auth = await authenticateBearer(bearer, { audience: env.MCP_RESOURCE });
- if (!auth) {
- if (!bearer && !req.headers['x-payment']) return sendX402Challenge(req, res);
- return send401(res, 'missing or invalid access token');
+ const paymentHeader = req.headers['x-payment'];
+ let auth = null;
+ let x402Ctx = null;
+
+ if (bearer) {
+ auth = await authenticateBearer(bearer, { audience: env.MCP_RESOURCE });
+ if (!auth) return send401(res, 'missing or invalid access token');
+ } else if (paymentHeader) {
+ const requirements = paymentRequirements({
+ resource: resolveResourceUrl(req, '/api/mcp'),
+ description: 'MCP tool call',
+ });
+ try {
+ const verified = await verifyPayment({ paymentHeader, requirements });
+ x402Ctx = { requirements, paymentPayload: verified.paymentPayload, payer: verified.payer };
+ } catch (err) {
+ return sendX402Error(res, requirements, err);
+ }
+ // Anonymous paid caller — synthesize an auth principal scoped to MCP read tools.
+ auth = {
+ userId: `x402:${x402Ctx.payer || 'unknown'}`,
+ scope: 'avatars:read profile',
+ source: 'x402',
+ payer: x402Ctx.payer,
+ };
+ } else {
+ return send402(
+ res,
+ paymentRequirements({
+ resource: resolveResourceUrl(req, '/api/mcp'),
+ description: 'MCP tool call',
+ }),
+ );
}
const ipRl = await limits.mcpIp(clientIp(req));
@@ -82,12 +112,42 @@ export default wrap(async (req, res) => {
const r = await dispatch(msg, auth, req);
if (r !== null) responses.push(r);
}
+
+ // Settle the x402 payment AFTER the work succeeded — atomic from the caller's
+ // perspective: if settle fails, the payer's signed payload is not broadcast
+ // and they get a 502 instead of having paid for nothing.
+ if (x402Ctx) {
+ try {
+ const settled = await settlePayment({
+ paymentPayload: x402Ctx.paymentPayload,
+ requirements: x402Ctx.requirements,
+ });
+ res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));
+ } catch (err) {
+ return sendX402Error(res, x402Ctx.requirements, err);
+ }
+ }
+
res.statusCode = 200;
res.setHeader('content-type', 'application/json; charset=utf-8');
res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);
res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));
});
+function sendX402Error(res, requirements, err) {
+ if (err instanceof X402Error) {
+ if (err.status === 402) return send402(res, requirements, err.message);
+ res.statusCode = err.status;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify({ error: err.code, error_description: err.message }));
+ return;
+ }
+ log.error('x402_unexpected', { message: err?.message });
+ res.statusCode = 500;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify({ error: 'internal', error_description: 'x402 processing failed' }));
+}
+
// ── JSON-RPC dispatch ────────────────────────────────────────────────────────
async function dispatch(msg, auth, req) {
const started = Date.now();
diff --git a/scripts/migrations/add-solana-attest-event-claims.sql b/scripts/migrations/add-solana-attest-event-claims.sql
deleted file mode 100644
index 20cd1c9b9..000000000
--- a/scripts/migrations/add-solana-attest-event-claims.sql
+++ /dev/null
@@ -1,23 +0,0 @@
--- Pre-tx idempotency claim table for the pumpkit -> attestation bridge
--- (api/agents/solana-attest-event.js).
---
--- Design: the handler INSERTs a claim row before sending the Solana
--- transaction. The primary key serializes concurrent webhook deliveries
--- at the DB layer, so only one delivery pays the on-chain fee. Other
--- deliveries hit unique_violation (Postgres 23505), short-circuit, and
--- return the winning signature once the leader records it.
-
-create table if not exists solana_attest_event_claims (
- agent_asset text not null,
- network text not null,
- event_id text not null,
- attester text not null,
- claimed_at timestamptz not null default now(),
- completed_at timestamptz,
- signature text,
- primary key (agent_asset, network, event_id)
-);
-
-create index if not exists solana_attest_event_claims_pending_idx
- on solana_attest_event_claims (claimed_at)
- where signature is null;
diff --git a/scripts/migrations/add-solana-attestations-event-id-index.sql b/scripts/migrations/add-solana-attestations-event-id-index.sql
deleted file mode 100644
index 233302f66..000000000
--- a/scripts/migrations/add-solana-attestations-event-id-index.sql
+++ /dev/null
@@ -1,20 +0,0 @@
--- Indexes the event_id stored in solana_attestations.payload for the
--- pumpkit -> attestation bridge (api/agents/solana-attest-event.js).
---
--- Two effects:
--- 1. Performance: the idempotency lookup
--- select 1 from solana_attestations
--- where agent_asset = $1 and network = $2 and payload->>'event_id' = $3
--- becomes O(log n) instead of a sequential scan.
--- 2. Correctness: the unique partial index serializes concurrent webhook
--- retries at the DB layer. If two webhook deliveries race past the
--- app-level dedupe check, the second insert hits unique_violation
--- (Postgres 23505) and the handler returns deduped:true.
---
--- Partial because legacy attestations (user-submitted feedback memos) do
--- not carry an event_id, and we don't want to constrain those.
-
-create unique index concurrently if not exists
- solana_attestations_event_id_uniq
- on solana_attestations (agent_asset, network, (payload->>'event_id'))
- where payload ? 'event_id';
diff --git a/src/agent-skills-pumpfun-autonomous.js b/src/agent-skills-pumpfun-autonomous.js
index c8d418c0c..31fc09622 100644
--- a/src/agent-skills-pumpfun-autonomous.js
+++ b/src/agent-skills-pumpfun-autonomous.js
@@ -74,7 +74,7 @@ export function registerPumpFunAutonomousSkills(skills) {
},
handler: async (args, ctx) => {
const id = requireAgentId(ctx);
- const data = await postJson(ENDPOINT(id, 'launch'), {
+ const resp = await postJson(ENDPOINT(id, 'launch'), {
name: args.name || ctx.identity?.name,
symbol: args.symbol,
uri: args.uri,
@@ -84,11 +84,13 @@ export function registerPumpFunAutonomousSkills(skills) {
vanitySuffix: args.vanitySuffix,
vanityIgnoreCase: args.vanityIgnoreCase,
});
+ // Server uses { data: {...} } envelope per api/_lib/http.json convention.
+ const payload = resp?.data || resp;
return {
success: true,
- output: `Launched ${data.symbol || args.symbol}. Mint: ${data.mint}`,
+ output: `Launched ${args.symbol}. Mint: ${payload.mint}`,
sentiment: 0.9,
- data,
+ data: { ...payload, symbol: args.symbol, network: args.network || 'mainnet' },
};
},
});
diff --git a/src/agent-skills-pumpfun-compose.js b/src/agent-skills-pumpfun-compose.js
index 5d870abee..d511d522f 100644
--- a/src/agent-skills-pumpfun-compose.js
+++ b/src/agent-skills-pumpfun-compose.js
@@ -290,48 +290,58 @@ export function registerPumpFunComposeSkills(skills) {
sizeMultiplier: { type: 'number', minimum: 0.001, maximum: 10 },
durationSec: { type: 'integer', minimum: 10, maximum: 7200 },
sessionId: { type: 'string' },
- simulate: { type: 'boolean' },
+ dryRun: { type: 'boolean' },
},
required: ['wallet', 'durationSec'],
},
handler: async (args, ctx) => {
- const simulate = !!args.simulate;
+ const dryRun = !!args.dryRun;
+ const onProgress = args.onProgress;
+ const signal = args.signal;
const sessionId = args.sessionId;
const deadline = Date.now() + args.durationSec * 1000;
const mult = args.sizeMultiplier ?? 1;
const cap = cfg(ctx, 'sessionSpendCapSol');
const state = await loadState(ctx?.memory, sessionId, { mirrored: new Set(), spent: 0, log: [] });
+ emit(onProgress, { type: 'start', mode: 'copy-trade', wallet: args.wallet, spent: state.spent, cap });
- while (!args.signal?.aborted && Date.now() < deadline && state.spent < cap) {
+ while (!signal?.aborted && Date.now() < deadline && state.spent < cap) {
const profile = await mcp('getCreatorProfile', { creator: args.wallet }).catch(() => null);
const recentMints = (profile?.tokens ?? []).map((t) => t.mint).filter(Boolean);
for (const mint of recentMints) {
+ if (signal?.aborted) break;
const trades = await mcp('getTokenTrades', { mint, limit: 20 }).catch(() => null);
const buys = (trades?.trades ?? trades ?? []).filter(
(t) => t.side === 'buy' && t.wallet === args.wallet && !state.mirrored.has(t.sig),
);
for (const b of buys) {
+ if (signal?.aborted) break;
state.mirrored.add(b.sig);
const amountSol = Math.min((b.solAmount ?? 0) * mult, cap - state.spent);
if (amountSol <= 0) break;
try {
- const r = await maybeBuy(skills, ctx, simulate, mint, amountSol);
+ const r = await doBuy(skills, ctx, dryRun, mint, amountSol);
state.spent += amountSol;
- state.log.push({ mint, mirroredFrom: b.sig, sig: r.signature, amountSol, simulate });
+ state.log.push({ mint, mirroredFrom: b.sig, sig: r.signature, amountSol, dryRun });
saveState(ctx?.memory, sessionId, state);
+ emit(onProgress, { type: dryRun ? 'dry-buy' : 'buy', mint, sig: r.signature, amountSol, spent: state.spent });
} catch (e) {
state.log.push({ mint, error: e.message });
+ emit(onProgress, { type: 'error', mint, reason: e.message });
}
}
}
saveState(ctx?.memory, sessionId, state);
- await new Promise((r) => setTimeout(r, cfg(ctx, 'pollMs')));
+ if (signal?.aborted || Date.now() >= deadline || state.spent >= cap) break;
+ emit(onProgress, { type: 'poll-sleep', ms: cfg(ctx, 'pollMs') });
+ await abortableSleep(cfg(ctx, 'pollMs'), signal);
}
+ const reason = signal?.aborted ? 'aborted' : Date.now() >= deadline ? 'duration' : 'cap';
return {
success: true,
- output: `${simulate ? 'Dry-run' : 'Copy-trade'} done. Mirrored ${state.log.length} buys, spent ${state.spent} SOL.`,
+ output: `${dryRun ? 'Dry-run' : 'Copy-trade'} done (${reason}). Mirrored ${state.log.length} buys, spent ${state.spent} SOL.`,
sentiment: 0.4,
- data: { spent: state.spent, mirrors: state.log, simulate, sessionId },
+ data: { spent: state.spent, mirrors: state.log, dryRun, sessionId, reason },
};
},
});
diff --git a/src/pump/agent-token-widget.js b/src/pump/agent-token-widget.js
index 52115076f..eec2a0b80 100644
--- a/src/pump/agent-token-widget.js
+++ b/src/pump/agent-token-widget.js
@@ -567,36 +567,89 @@ export class AgentTokenWidget {
}
async _onWithdraw() {
- // Triggers the prep endpoint and surfaces a wallet popup expectation.
- // The actual signing path lives in src/onchain/launch-token-button.js
- // patterns and on-chain wallet adapters; here we just kick off prep.
const wd = this.mount.querySelector('.atok-withdraw');
const orig = wd.textContent;
wd.disabled = true;
wd.textContent = 'Preparing…';
try {
- const resp = await fetch('/api/pump/withdraw-prep', {
+ // Lazy-import so non-owner views don't pay the bundle cost.
+ const [
+ { resolveUsdcAta, signAndSendVTx },
+ ] = await Promise.all([import('./pump-modals.js')]);
+ const wallet =
+ typeof window !== 'undefined' &&
+ (window.solana || window.phantom?.solana || window.backpack || window.solflare);
+ if (!wallet) throw new Error('No Solana wallet detected. Install Phantom.');
+ if (!wallet.isConnected) await wallet.connect?.();
+ const authority =
+ wallet.publicKey?.toBase58?.() || wallet.publicKey?.toString();
+ if (authority !== this.token.agent_authority) {
+ throw new Error('Connected wallet is not the agent authority.');
+ }
+ wd.textContent = 'Resolving ATA…';
+ const { ata, existing, connection } = await resolveUsdcAta({
+ owner: authority,
+ network: this.token.network,
+ });
+ // If owner has no USDC ATA yet, prepend a creation ix; the offline SDK
+ // withdraw ix expects the receiver ATA to exist.
+ let createAtaPrep = null;
+ if (!existing) {
+ const { createAssociatedTokenAccountInstruction, ASSOCIATED_TOKEN_PROGRAM_ID } =
+ await import('@solana/spl-token');
+ const { PublicKey } = await import('@solana/web3.js');
+ createAtaPrep = createAssociatedTokenAccountInstruction(
+ new PublicKey(authority),
+ ata,
+ new PublicKey(authority),
+ new PublicKey(
+ this.token.network === 'devnet'
+ ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'
+ : 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ ),
+ );
+ }
+ wd.textContent = 'Building tx…';
+ const prep = await fetch('/api/pump/withdraw-prep', {
method: 'POST',
headers: { 'content-type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
mint: this.token.mint,
- authority_wallet: this.token.agent_authority,
- receiver_ata: this.token.agent_authority, // owner self-ATA, frontend resolves
+ authority_wallet: authority,
+ receiver_ata: ata.toBase58(),
network: this.token.network,
}),
}).then((r) => r.json());
- if (resp.error) throw new Error(resp.error_description || resp.error);
- window.dispatchEvent(
- new CustomEvent('pump-withdraw-prepared', { detail: resp }),
- );
+ if (prep.error) throw new Error(prep.error_description || prep.error);
wd.textContent = 'Sign in wallet…';
+ const sig = await signAndSendVTx(prep.tx_base64, {
+ network: this.token.network,
+ prependIxs: createAtaPrep ? [createAtaPrep] : [],
+ wallet,
+ connection,
+ });
+ wd.textContent = 'Confirming…';
+ const conf = await fetch('/api/pump/withdraw-confirm', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({
+ mint: this.token.mint,
+ authority_wallet: authority,
+ tx_signature: sig,
+ network: this.token.network,
+ }),
+ }).then((r) => r.json());
+ if (conf.error) throw new Error(conf.error_description || conf.error);
+ wd.textContent = 'Done 🎉';
+ setTimeout(() => this._refresh().catch(() => {}), 1200);
} catch (e) {
- wd.textContent = `Failed: ${e.message}`;
+ wd.textContent = `Failed: ${(e.message || String(e)).slice(0, 32)}`;
setTimeout(() => {
wd.textContent = orig;
wd.disabled = false;
- }, 2400);
+ }, 3000);
}
}
diff --git a/src/pump/pump-modals.js b/src/pump/pump-modals.js
index 7dd7b547b..fdad6cb1a 100644
--- a/src/pump/pump-modals.js
+++ b/src/pump/pump-modals.js
@@ -166,6 +166,52 @@ async function signAndSend(txBase64, { extraSigners = [], network = 'mainnet' }
return sig;
}
+/**
+ * Sign + send a server-prepared VersionedTransaction. Optionally prepend
+ * additional instructions (e.g. ATA creation) before submission. Used by the
+ * widget's withdraw flow which needs a CreateATA + Withdraw atomic.
+ *
+ * Note: prepending ixs requires recompiling to a v0 message because the server
+ * already finalized the message. We prepend by deserialising, building a fresh
+ * message with the original blockhash + payer + (extra + original) ixs is not
+ * possible without reading the original ixs from the message — which we do via
+ * `getMessage()` decompile. Fallback: if prependIxs is empty, just re-sign.
+ */
+export async function signAndSendVTx(
+ txBase64,
+ { extraSigners = [], network = 'mainnet', prependIxs = [], wallet, connection } = {},
+) {
+ const w = wallet || detectSolanaWallet();
+ if (!w) throw new Error('No Solana wallet detected. Install Phantom.');
+ if (!w.isConnected) await w.connect?.();
+ const conn = connection || new Connection(RPC(network), 'confirmed');
+
+ const original = VersionedTransaction.deserialize(
+ Uint8Array.from(atob(txBase64), (c) => c.charCodeAt(0)),
+ );
+
+ let toSign = original;
+ if (prependIxs && prependIxs.length) {
+ // Decompile original message → splice in prepend ixs → recompile.
+ const { TransactionMessage } = await import('@solana/web3.js');
+ const decompiled = TransactionMessage.decompile(original.message);
+ const merged = new TransactionMessage({
+ payerKey: decompiled.payerKey,
+ recentBlockhash: decompiled.recentBlockhash,
+ instructions: [...prependIxs, ...decompiled.instructions],
+ }).compileToV0Message();
+ toSign = new VersionedTransaction(merged);
+ }
+
+ for (const kp of extraSigners) toSign.sign([kp]);
+ const signed = await w.signTransaction(toSign);
+ const sig = await conn.sendRawTransaction(signed.serialize(), {
+ skipPreflight: false,
+ });
+ await conn.confirmTransaction(sig, 'confirmed');
+ return sig;
+}
+
// ── Pay modal ───────────────────────────────────────────────────────────────
function openPay({ mint, network }) {
const { inner, close } = openModal();
diff --git a/vercel.json b/vercel.json
index c76d3b9f9..0f7974555 100644
--- a/vercel.json
+++ b/vercel.json
@@ -69,6 +69,7 @@
},
{ "src": "/api/agents/([^/]+)/wallet", "dest": "/api/agents/[id]" },
{ "src": "/api/agents/([^/]+)/solana", "dest": "/api/agents/[id]" },
+ { "src": "/api/agents/([^/]+)/solana/([^/]+)", "dest": "/api/agents/[id]" },
{ "src": "/api/agents/([^/]+)/pumpfun/([^/]+)", "dest": "/api/agents/[id]" },
{
"src": "/api/avatars/([^/]+)/storage-mode",