Skip to content

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

feat: add x402 protocol implementation for facilitator-mediated micropayments and enhance agent functionality with new Solana wallet endpoints

nirholas49e176f306d6
diff --git a/api/_lib/migrations/2026-04-29-attest-event-bridge.sql b/api/_lib/migrations/2026-04-29-attest-event-bridge.sql
new file mode 100644
index 000000000..4c8550047
--- /dev/null
+++ b/api/_lib/migrations/2026-04-29-attest-event-bridge.sql
@@ -0,0 +1,46 @@
+-- Migration: pumpkit -> attestation bridge state.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-04-29-attest-event-bridge.sql
+-- Idempotent.
+--
+-- Tables/indexes for the production webhook in api/agents/solana-attest-event.js.
+-- Combines the two earlier scripts/migrations files into a single canonical
+-- migration alongside the rest of the dated migration set.
+
+begin;
+
+-- ── solana_attest_event_claims ─────────────────────────────────────────────
+-- Pre-tx idempotency claim. The handler INSERTs a claim row before sending
+-- the Solana transaction; the primary key serializes concurrent retries so
+-- only one delivery pays the on-chain fee. Stale claims (signature still null
+-- after the tx send timed out or crashed) are reaped by the cleanup cron at
+-- /api/cron/solana-attest-event-cleanup.
+
+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;
+
+-- ── solana_attestations payload event_id index ─────────────────────────────
+-- 1. Performance: the dedupe lookup uses payload->>'event_id'. Without an
+-- expression index this is O(n) over the table.
+-- 2. Correctness: the unique partial index closes the race window between the
+-- app-layer SELECT and the INSERT in the webhook handler. On Postgres 23505
+-- the handler catches and returns the winning signature.
+-- Partial because legacy memo feedback rows do not carry an event_id.
+
+create unique index if not exists
+ solana_attestations_event_id_uniq
+ on solana_attestations (agent_asset, network, (payload->>'event_id'))
+ where payload ? 'event_id';
+
+commit;
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
new file mode 100644
index 000000000..30d9acea6
--- /dev/null
+++ b/api/_lib/x402-spec.js
@@ -0,0 +1,173 @@
+// x402 protocol — facilitator-mediated micropayments.
+// Spec: https://x402.org / https://github.com/coinbase/x402
+//
+// This module implements the *standard* x402 wire flow used by x402scan and
+// agentcash. (api/_lib/x402.js is the unrelated Pump.fun agent-skill flow.)
+//
+// Server flow on a paid resource:
+// 1. No X-PAYMENT header → 402 with { x402Version, accepts:[paymentRequirements] }
+// 2. Client retries with X-PAYMENT (base64-encoded PaymentPayload).
+// 3. Server POSTs facilitator /verify with { x402Version, paymentPayload, paymentRequirements }
+// → { isValid, invalidReason?, payer? }
+// 4. If isValid, do the work.
+// 5. Server POSTs facilitator /settle (same body) → { success, transaction, network, payer }
+// Server attaches a base64 settlement object as `X-PAYMENT-RESPONSE` on the success reply.
+
+import { env } from './env.js';
+
+export const X402_VERSION = 1;
+
+export class X402Error extends Error {
+ constructor(code, message, status = 402) {
+ super(message);
+ this.code = code;
+ this.status = status;
+ }
+}
+
+export function paymentRequirements({ resource, description = '' } = {}) {
+ return {
+ scheme: 'exact',
+ network: env.X402_NETWORK,
+ maxAmountRequired: env.X402_MAX_AMOUNT_REQUIRED,
+ resource,
+ description,
+ mimeType: 'application/json',
+ payTo: env.X402_PAY_TO,
+ maxTimeoutSeconds: 60,
+ asset: env.X402_ASSET_MINT,
+ extra: { name: 'USDC', decimals: 6 },
+ };
+}
+
+function decodePaymentHeader(header) {
+ if (!header) throw new X402Error('payment_required', 'X-PAYMENT header required', 402);
+ let json;
+ try {
+ json = Buffer.from(String(header), 'base64').toString('utf8');
+ } catch (err) {
+ throw new X402Error('invalid_payment', `X-PAYMENT base64 decode failed: ${err.message}`, 400);
+ }
+ let payload;
+ try {
+ payload = JSON.parse(json);
+ } catch (err) {
+ throw new X402Error('invalid_payment', `X-PAYMENT JSON parse failed: ${err.message}`, 400);
+ }
+ if (!payload || typeof payload !== 'object') {
+ throw new X402Error('invalid_payment', 'X-PAYMENT must decode to a JSON object', 400);
+ }
+ return payload;
+}
+
+async function callFacilitator(path, body) {
+ const url = `${env.X402_FACILITATOR_URL}${path}`;
+ const headers = { 'content-type': 'application/json', accept: 'application/json' };
+ if (env.X402_FACILITATOR_TOKEN) {
+ headers.authorization = `Bearer ${env.X402_FACILITATOR_TOKEN}`;
+ }
+ let res;
+ try {
+ res = await fetch(url, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(15_000),
+ });
+ } catch (err) {
+ throw new X402Error(
+ 'facilitator_unreachable',
+ `facilitator ${path} fetch failed: ${err.message}`,
+ 502,
+ );
+ }
+ const text = await res.text();
+ let data = {};
+ if (text) {
+ try {
+ data = JSON.parse(text);
+ } catch {
+ throw new X402Error(
+ 'facilitator_bad_response',
+ `facilitator ${path} returned non-JSON (status ${res.status})`,
+ 502,
+ );
+ }
+ }
+ if (!res.ok) {
+ throw new X402Error(
+ 'facilitator_error',
+ `facilitator ${path} ${res.status}: ${data.error || data.message || text.slice(0, 200)}`,
+ 502,
+ );
+ }
+ return data;
+}
+
+// Verify a base64 X-PAYMENT header against payment requirements.
+// Returns { paymentPayload, payer } on success; throws X402Error on failure.
+export async function verifyPayment({ paymentHeader, requirements }) {
+ const paymentPayload = decodePaymentHeader(paymentHeader);
+ const result = await callFacilitator('/verify', {
+ x402Version: X402_VERSION,
+ paymentPayload,
+ paymentRequirements: requirements,
+ });
+ if (!result.isValid) {
+ throw new X402Error(
+ 'invalid_payment',
+ `payment rejected: ${result.invalidReason || 'unknown reason'}`,
+ 402,
+ );
+ }
+ return { paymentPayload, payer: result.payer || null };
+}
+
+// Settle the verified payment on-chain via the facilitator.
+export async function settlePayment({ paymentPayload, requirements }) {
+ const result = await callFacilitator('/settle', {
+ x402Version: X402_VERSION,
+ paymentPayload,
+ paymentRequirements: requirements,
+ });
+ if (!result.success) {
+ throw new X402Error(
+ 'settle_failed',
+ `settle failed: ${result.errorReason || 'unknown reason'}`,
+ 502,
+ );
+ }
+ return result;
+}
+
+export function encodePaymentResponseHeader(settleResult) {
+ const body = {
+ success: true,
+ transaction: settleResult.transaction,
+ network: settleResult.network,
+ payer: settleResult.payer,
+ };
+ return Buffer.from(JSON.stringify(body), 'utf8').toString('base64');
+}
+
+export function send402(res, requirements, error = 'X-PAYMENT header is required') {
+ res.statusCode = 402;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ res.end(
+ JSON.stringify({
+ x402Version: X402_VERSION,
+ error,
+ accepts: [requirements],
+ }),
+ );
+}
+
+// Resolve the canonical resource URL the client hit, so the facilitator can
+// match the payer's signed payload against the same string we advertise.
+export function resolveResourceUrl(req, path) {
+ const proto = (req.headers['x-forwarded-proto'] || 'https').toString().split(',')[0].trim();
+ const host = (req.headers['x-forwarded-host'] || req.headers.host || '').toString();
+ if (host) return `${proto}://${host}${path}`;
+ return `${env.APP_ORIGIN}${path}`;
+}
diff --git a/api/agents/[id].js b/api/agents/[id].js
index 7fac3c656..d7982d2a4 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -2,6 +2,8 @@
* /api/agents/:id — agent CRUD
* /api/agents/:id/wallet — link / update EVM wallet
* /api/agents/:id/solana — agent's Solana wallet (address + balance, provision)
+ * /api/agents/:id/solana/activity — recent on-chain signatures for the wallet
+ * /api/agents/:id/solana/airdrop — devnet airdrop (1 SOL)
* /api/agents/:id/sns — list owned .sol domains and attach one as the agent's SNS id
* /api/agents/:id/pumpfun/launch — create a pump.fun token from this agent
* /api/agents/:id/pumpfun/buy — bonding-curve buy
@@ -28,6 +30,14 @@ export default wrap(async function handler(req, res) {
if (sub === 'wallet') return handleWallet(req, res, id);
if (sub === 'solana') {
+ if (action === 'activity') {
+ const mod = await import('./solana-activity.js');
+ return mod.default(req, res, id);
+ }
+ if (action === 'airdrop') {
+ const mod = await import('./solana-airdrop.js');
+ return mod.default(req, res, id);
+ }
const mod = await import('./solana-wallet.js');
return mod.default(req, res, id);
}
diff --git a/api/mcp.js b/api/mcp.js
index 5c61b54a0..e56c97901 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -30,6 +30,15 @@ import { crawlAgentAttestations, KIND_MAP } from './_lib/solana-attestations.js'
import { pumpfunMcp, pumpfunBotEnabled } from './_lib/pumpfun-mcp.js';
import { inspectModel, suggestOptimizations } from './_lib/model-inspect.js';
import { validateBytes } from 'gltf-validator';
+import {
+ X402Error,
+ paymentRequirements,
+ verifyPayment,
+ settlePayment,
+ encodePaymentResponseHeader,
+ send402,
+ resolveResourceUrl,
+} from './_lib/x402-spec.js';
const PROTOCOL_VERSION = '2025-06-18';
const SERVER_INFO = { name: '3d-agent-mcp', version: '1.0.0' };
@@ -701,8 +710,64 @@ const TOOLS = {
};
},
},
+
+ pumpfun_recent_claims: {
+ async handler(args) {
+ return pumpfunToolResult(
+ await pumpfunMcp.recentClaims({ limit: clamp(args?.limit, 1, 50, 10) }),
+ );
+ },
+ },
+
+ pumpfun_token_intel: {
+ async handler(args) {
+ if (!args?.mint) throw Object.assign(new Error('mint required'), { status: 400 });
+ return pumpfunToolResult(await pumpfunMcp.tokenIntel({ mint: args.mint }));
+ },
+ },
+
+ pumpfun_creator_intel: {
+ async handler(args) {
+ if (!args?.wallet) throw Object.assign(new Error('wallet required'), { status: 400 });
+ return pumpfunToolResult(await pumpfunMcp.creatorIntel({ wallet: args.wallet }));
+ },
+ },
+
+ pumpfun_recent_graduations: {
+ async handler(args) {
+ return pumpfunToolResult(
+ await pumpfunMcp.graduations({ limit: clamp(args?.limit, 1, 50, 10) }),
+ );
+ },
+ },
};
+function pumpfunToolResult(r) {
+ if (!pumpfunBotEnabled()) {
+ return {
+ content: [{ type: 'text', text: 'pump.fun feed is not configured on this server.' }],
+ isError: true,
+ };
+ }
+ if (!r.ok) {
+ return {
+ content: [{ type: 'text', text: `pump.fun upstream error: ${r.error}` }],
+ isError: true,
+ };
+ }
+ const payload = Array.isArray(r.data) ? { items: r.data } : r.data;
+ return {
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
+ structuredContent: payload,
+ };
+}
+
+function clamp(n, lo, hi, fallback) {
+ const x = Number(n);
+ if (!Number.isFinite(x)) return fallback;
+ return Math.max(lo, Math.min(hi, x));
+}
+
// ─── Solana attestation tool helpers ────────────────────────────────────────
async function ensureWarm({ asset, network }) {
diff --git a/public/dashboard/agent-pumpfun.html b/public/dashboard/agent-pumpfun.html
index cccbfbfa7..e7309a203 100644
--- a/public/dashboard/agent-pumpfun.html
+++ b/public/dashboard/agent-pumpfun.html
@@ -685,6 +685,8 @@
refreshPortfolio();
});
els.provisionBtn.addEventListener('click', provision);
+ els.snsRefreshBtn.addEventListener('click', refreshSns);
+ els.snsClearBtn.addEventListener('click', clearSns);
els.launchBtn.addEventListener('click', launchToken);
els.buyBtn.addEventListener('click', buy);
els.sellBtn.addEventListener('click', sell);
diff --git a/public/pumpfun-demo.html b/public/pumpfun.html
similarity index 100%
rename from public/pumpfun-demo.html
rename to public/pumpfun.html
diff --git a/src/agent-home-pumpfun.js b/src/agent-home-pumpfun.js
index 3e3c75309..9313d716e 100644
--- a/src/agent-home-pumpfun.js
+++ b/src/agent-home-pumpfun.js
@@ -286,38 +286,50 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
async function doLaunch(launchBtn) {
launchBtn.disabled = true;
- launchBtn.textContent = state.vanityEnabled ? 'Grinding vanity…' : 'Launching…';
+ const useAgent = state.signer === 'agent';
+ const wantsVanity = state.vanityEnabled && state.vanitySuffix?.trim();
+ launchBtn.textContent = wantsVanity ? 'Grinding vanity…' : 'Launching…';
try {
- let vanityArgs = null;
- if (state.vanityEnabled && state.vanitySuffix?.trim()) {
- try {
- const { grindVanity } = await import('./solana/vanity/grinder.js');
- const ground = await grindVanity({
- suffix: state.vanitySuffix.trim(),
- onProgress: (p) => {
- state.vanityProgress = { rate: p.rate, eta: p.eta };
- const slot = cardBody.querySelector('.pumpfun-vanity-progress');
- if (slot) slot.textContent = `grinding… ${formatNumber(p.rate)}/s · eta ${p.eta}`;
- },
- });
- vanityArgs = {
- mintPublicKey: ground.publicKey,
- mintSecretKeyB64: btoa(String.fromCharCode(...ground.secretKey)),
- };
- state.vanityProgress = null;
- launchBtn.textContent = `Launching ${shortMint(ground.publicKey)}…`;
- } catch (err) {
- state.vanityProgress = null;
- launchBtn.disabled = false;
- launchBtn.textContent = `Retry launch ${deriveSymbol(identity.name)}`;
- toast(err.message || 'Vanity grind failed', null, null, 'error');
- render();
- return;
+ let extraArgs = {};
+ if (wantsVanity) {
+ if (useAgent) {
+ // Server grinds + signs in the same request.
+ extraArgs = { vanitySuffix: state.vanitySuffix.trim() };
+ launchBtn.textContent = `Launching with …${state.vanitySuffix.trim()}…`;
+ } else {
+ // Client grinds with workers, owner wallet signs.
+ try {
+ const { grindVanity } = await import('./solana/vanity/grinder.js');
+ const ground = await grindVanity({
+ suffix: state.vanitySuffix.trim(),
+ onProgress: (p) => {
+ state.vanityProgress = { rate: p.rate, eta: p.eta };
+ const slot = cardBody.querySelector('.pumpfun-vanity-progress');
+ if (slot) slot.textContent = `grinding… ${formatNumber(p.rate)}/s · eta ${p.eta}`;
+ },
+ });
+ extraArgs = {
+ mintPublicKey: ground.publicKey,
+ mintSecretKeyB64: btoa(String.fromCharCode(...ground.secretKey)),
+ };
+ state.vanityProgress = null;
+ launchBtn.textContent = `Launching ${shortMint(ground.publicKey)}…`;
+ } catch (err) {
+ state.vanityProgress = null;
+ launchBtn.disabled = false;
+ launchBtn.textContent = `Retry launch ${deriveSymbol(identity.name)}`;
+ toast(err.message || 'Vanity grind failed', null, null, 'error');
+ render();
+ return;
+ }
}
}
+ const skillName = useAgent
+ ? 'pumpfun-self-launch-from-identity'
+ : 'pumpfun-launch-from-agent';
const r = await skills?.perform(
- 'pumpfun-launch-from-agent',
- { network: state.network, ...(vanityArgs || {}) },
+ skillName,
+ { network: state.network, ...extraArgs },
{ identity },
);
if (r?.success && r.data?.mint) {
diff --git a/src/agent-skills-pumpfun-compose.js b/src/agent-skills-pumpfun-compose.js
index a3cf605c9..5d870abee 100644
--- a/src/agent-skills-pumpfun-compose.js
+++ b/src/agent-skills-pumpfun-compose.js
@@ -218,49 +218,60 @@ export function registerPumpFunComposeSkills(skills) {
durationSec: { type: 'integer', minimum: 10, maximum: 3600 },
perTradeSol: { type: 'number' },
sessionId: { type: 'string' },
- simulate: { type: 'boolean' },
+ dryRun: { type: 'boolean' },
},
required: ['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 perTrade = args.perTradeSol ?? cfg(ctx, 'perTradeSol');
const cap = cfg(ctx, 'sessionSpendCapSol');
const state = await loadState(ctx?.memory, sessionId, { seen: new Set(), spent: 0, log: [] });
+ emit(onProgress, { type: 'start', mode: 'auto-snipe', spent: state.spent, cap });
- while (!args.signal?.aborted && Date.now() < deadline && state.spent + perTrade <= cap) {
+ while (!signal?.aborted && Date.now() < deadline && state.spent + perTrade <= cap) {
const fresh = await mcp('getNewTokens', { limit: 20 }).catch(() => null);
const items = fresh?.tokens ?? fresh ?? [];
for (const t of items) {
+ if (signal?.aborted) break;
const mint = t.mint ?? t.address;
if (!mint || state.seen.has(mint)) continue;
state.seen.add(mint);
+ emit(onProgress, { type: 'vet', mint });
const v = await vetMint(mint).catch((e) => ({ verdict: { ok: false, reason: e.message } }));
const verdict = v.verdict || passesFilters(ctx, v);
if (!verdict.ok) {
state.log.push({ mint, action: 'skip', reason: verdict.reason });
+ emit(onProgress, { type: 'skip', mint, reason: verdict.reason, spent: state.spent });
continue;
}
try {
- const buy = await maybeBuy(skills, ctx, simulate, mint, perTrade);
+ const buy = await doBuy(skills, ctx, dryRun, mint, perTrade);
state.spent += perTrade;
- state.log.push({ mint, action: simulate ? 'simulate-buy' : 'buy', sig: buy.signature, spent: state.spent });
+ state.log.push({ mint, action: dryRun ? 'dry-buy' : 'buy', sig: buy.signature, spent: state.spent });
saveState(ctx?.memory, sessionId, state);
+ emit(onProgress, { type: dryRun ? 'dry-buy' : 'buy', mint, sig: buy.signature, spent: state.spent });
if (state.spent + perTrade > cap) break;
} catch (e) {
state.log.push({ mint, action: 'error', reason: 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 + perTrade > 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' : 'Snipe'} done. Spent ${state.spent} SOL across ${state.log.length} events.`,
+ output: `${dryRun ? 'Dry-run' : 'Snipe'} done (${reason}). Spent ${state.spent} SOL across ${state.log.length} events.`,
sentiment: 0.4,
- data: { spent: state.spent, trades: state.log, simulate, sessionId },
+ data: { spent: state.spent, trades: state.log, dryRun, sessionId, reason },
};
},
});