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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: enhance Pump.fun integration with new payment features and UI updates
nirholasaadfa2950801
diff --git a/api/_lib/migrations/2026-04-29-agent-payments.sql b/api/_lib/migrations/2026-04-29-agent-payments.sqlnew file mode 100644index 000000000..898067055--- /dev/null+++ b/api/_lib/migrations/2026-04-29-agent-payments.sql@@ -0,0 +1,62 @@+-- Migration: agent payments via Pump.fun's agent-payments-sdk.+--+-- Adds:+-- • payment_configs_pending — transient prep records for the one-time+-- create-agent-payments tx (owner registers the agent for payments).+-- • agent_payment_intents — every pay-prep creates one of these rows;+-- pay-confirm flips status to 'paid' and stamps tx_signature + paid_at.+-- • Index on meta.payments.mint and meta.payments.receiver for lookups.+--+-- Idempotent.++begin;++create table if not exists payment_configs_pending (+ id text primary key,+ user_id uuid not null references users(id) on delete cascade,+ agent_id uuid not null references agent_identities(id) on delete cascade,+ cluster text not null check (cluster in ('mainnet', 'devnet')),+ mint text not null,+ payload jsonb not null,+ created_at timestamptz not null default now(),+ expires_at timestamptz not null+);++create index if not exists payment_configs_pending_user_expiry+ on payment_configs_pending(user_id, expires_at);++create table if not exists agent_payment_intents (+ id text primary key,+ payer_user_id uuid not null references users(id) on delete cascade,+ agent_id uuid not null references agent_identities(id) on delete cascade,+ currency_mint text not null,+ amount text not null, -- raw token units; bigint as text+ memo text not null,+ start_time timestamptz not null,+ end_time timestamptz not null,+ status text not null default 'pending'+ check (status in ('pending', 'paid', 'expired', 'failed')),+ cluster text not null check (cluster in ('mainnet', 'devnet')),+ tx_signature text,+ paid_at timestamptz,+ payload jsonb not null,+ created_at timestamptz not null default now(),+ expires_at timestamptz not null+);++create index if not exists agent_payment_intents_payer+ on agent_payment_intents(payer_user_id, created_at desc);+create index if not exists agent_payment_intents_agent+ on agent_payment_intents(agent_id, status);+create index if not exists agent_payment_intents_status_expiry+ on agent_payment_intents(status, expires_at);++create index if not exists agent_identities_payments_mint+ on agent_identities ((meta->'payments'->>'mint'))+ where deleted_at is null and (meta->'payments'->>'configured') = 'true';++create index if not exists agent_identities_payments_receiver+ on agent_identities ((meta->'payments'->>'receiver'))+ where deleted_at is null and (meta->'payments'->>'configured') = 'true';++commit;diff --git a/api/_lib/skill-runtime.js b/api/_lib/skill-runtime.jsnew file mode 100644index 000000000..45f91610d--- /dev/null+++ b/api/_lib/skill-runtime.js@@ -0,0 +1,99 @@+// Skill runtime — server-side dispatcher for in-process skill invocation.+//+// Skills under examples/skills/<name>/handlers.js export tool functions.+// This module gives them the `ctx` they expect:+// ctx.skills.invoke('skill.tool', args) → call sibling skill+// ctx.skillConfig → manifest.config merged with overrides+// ctx.memory.note(tag, value) → no-op stub (DB persistence is opt-in)+// ctx.fetch → globalThis.fetch (overridable in tests)+// ctx.wallet → injected by callers that need signing+//+// Cold-start friendly: skill modules are imported lazily on first use.++const SKILL_MAP = {+ 'pump-fun': '../../examples/skills/pump-fun/handlers.js',+ 'pump-fun-trade': '../../examples/skills/pump-fun-trade/handlers.js',+ 'pump-fun-compose': '../../examples/skills/pump-fun-compose/handlers.js',+ 'pump-fun-strategy': '../../examples/skills/pump-fun-strategy/handlers.js',+ 'solana-wallet': '../../examples/skills/solana-wallet/handlers.js',+};++const MANIFEST_MAP = {+ 'pump-fun': '../../examples/skills/pump-fun/manifest.json',+ 'pump-fun-trade': '../../examples/skills/pump-fun-trade/manifest.json',+ 'pump-fun-compose': '../../examples/skills/pump-fun-compose/manifest.json',+ 'pump-fun-strategy': '../../examples/skills/pump-fun-strategy/manifest.json',+ 'solana-wallet': '../../examples/skills/solana-wallet/manifest.json',+};++const _modCache = new Map();+const _cfgCache = new Map();++async function loadSkill(name) {+ if (_modCache.has(name)) return _modCache.get(name);+ const path = SKILL_MAP[name];+ if (!path) throw new Error(`unknown skill: ${name}`);+ const mod = await import(path);+ _modCache.set(name, mod);+ return mod;+}++async function loadManifest(name) {+ if (_cfgCache.has(name)) return _cfgCache.get(name);+ const path = MANIFEST_MAP[name];+ if (!path) return {};+ try {+ const mod = await import(path, { with: { type: 'json' } });+ _cfgCache.set(name, mod.default ?? mod);+ return mod.default ?? mod;+ } catch {+ _cfgCache.set(name, {});+ return {};+ }+}++/**+ * Build a context for invoking skills from a serverless endpoint.+ *+ * @param {object} opts+ * @param {object} [opts.configOverrides] - per-skill config overrides keyed by skill name+ * @param {object} [opts.wallet] - solana wallet contract for signing skills+ * @param {(event: object) => void} [opts.onEvent] - notified on every memory.note call+ * @param {object} [opts.fetch] - fetch impl (defaults to globalThis.fetch)+ */+export function makeRuntime(opts = {}) {+ const { configOverrides = {}, wallet, onEvent, fetch = globalThis.fetch } = opts;++ async function invoke(qualified, args) {+ const [skillName, toolName] = qualified.split('.');+ if (!skillName || !toolName) throw new Error(`bad tool: ${qualified}`);+ const mod = await loadSkill(skillName);+ const fn = mod[toolName];+ if (typeof fn !== 'function') {+ return { ok: false, error: `tool not found: ${qualified}` };+ }+ const manifest = await loadManifest(skillName);+ const skillConfig = { ...(manifest.config ?? {}), ...(configOverrides[skillName] ?? {}) };+ const ctx = {+ skills: { invoke },+ skillConfig,+ wallet,+ fetch,+ memory: {+ note: (tag, value) => {+ try {+ onEvent?.({ skill: skillName, tool: toolName, tag, value, t: Date.now() });+ } catch {}+ },+ recall: async () => null,+ },+ };+ try {+ return await fn(args ?? {}, ctx);+ } catch (e) {+ return { ok: false, error: e?.message ?? String(e) };+ }+ }++ return { invoke };+}diff --git a/api/agents/solana-card.js b/api/agents/solana-card.jsindex 64d57ea1b..f30c150c7 100644--- a/api/agents/solana-card.js+++ b/api/agents/solana-card.js@@ -20,8 +20,11 @@ export default wrap(async (req, res) => {const url = new URL(req.url, `http://${req.headers.host}`);const asset = url.searchParams.get('asset');if (!asset) return error(res, 400, 'validation_error', 'asset required');- try { new PublicKey(asset); }- catch { return error(res, 400, 'validation_error', 'invalid asset pubkey'); }+ try {+ new PublicKey(asset);+ } catch {+ return error(res, 400, 'validation_error', 'invalid asset pubkey');+ }const [a] = await sql`select id, name, description, skills, wallet_address as owner, meta, avatar_id@@ -31,7 +34,7 @@ export default wrap(async (req, res) => {if (!a) return error(res, 404, 'not_found', 'agent not found');const network = a.meta?.network || 'mainnet';- const origin = env.APP_ORIGIN;+ const origin = env.APP_ORIGIN;// Pump.fun off-chain signals — most-recent + per-kind counts. Best-effort:// the table is optional and may not exist in every deployment.@@ -92,33 +95,38 @@ export default wrap(async (req, res) => {// table missing — skip}- return json(res, 200, {- schema_version: '1.0',- // A2A core- name: a.name,- description: a.description,- // three.ws extensions- identity: {- chain: 'solana',- network,- asset_pubkey: asset, // Metaplex Core NFT = agent ID- owner: a.owner,- passport_url: `${origin}/agent-passport.html?asset=${asset}&network=${network}`,- ...(a.meta?.vanity_prefix ? { vanity_prefix: a.meta.vanity_prefix } : {}),- },- skills: a.skills || [],- endpoints: {- chat: `${origin}/api/agents/${a.id}/chat`,- attestations: `${origin}/api/agents/solana-attestations?asset=${asset}&network=${network}`,- reputation: `${origin}/api/agents/solana-reputation?asset=${asset}&network=${network}`,- },- attestation: {- schemas_url: `${origin}/.well-known/agent-attestation-schemas`,- transport: 'spl-memo',- memo_program: 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr',- usage: 'Sign an SPL Memo tx with one of the published schemas as JSON, including this asset_pubkey as a non-signer key.',+ return json(+ res,+ 200,+ {+ schema_version: '1.0',+ // A2A core+ name: a.name,+ description: a.description,+ // three.ws extensions+ identity: {+ chain: 'solana',+ network,+ asset_pubkey: asset, // Metaplex Core NFT = agent ID+ owner: a.owner,+ passport_url: `${origin}/agent-passport.html?asset=${asset}&network=${network}`,+ ...(a.meta?.vanity_prefix ? { vanity_prefix: a.meta.vanity_prefix } : {}),+ },+ skills: a.skills || [],+ endpoints: {+ chat: `${origin}/api/agents/${a.id}/chat`,+ attestations: `${origin}/api/agents/solana-attestations?asset=${asset}&network=${network}`,+ reputation: `${origin}/api/agents/solana-reputation?asset=${asset}&network=${network}`,+ },+ attestation: {+ schemas_url: `${origin}/.well-known/agent-attestation-schemas`,+ transport: 'spl-memo',+ memo_program: 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr',+ usage: 'Sign an SPL Memo tx with one of the published schemas as JSON, including this asset_pubkey as a non-signer key.',+ },+ ...(pumpfun ? { pumpfun } : {}),+ ...(token_stats ? { token_stats } : {}),},- ...(pumpfun ? { pumpfun } : {}),- ...(token_stats ? { token_stats } : {}),- }, { 'cache-control': 'public, max-age=120', 'access-control-allow-origin': '*' });+ { 'cache-control': 'public, max-age=120', 'access-control-allow-origin': '*' },+ );});diff --git a/api/cron/pump-agent-stats.js b/api/cron/pump-agent-stats.jsindex 48fcd7e6b..21c982685 100644--- a/api/cron/pump-agent-stats.js+++ b/api/cron/pump-agent-stats.js@@ -10,12 +10,7 @@import { sql } from '../_lib/db.js';import { cors, json, method, wrap, error } from '../_lib/http.js';import { env } from '../_lib/env.js';-import {- getConnection,- getPumpSdk,- getAmmPoolState,- solanaPubkey,-} from '../_lib/pump.js';+import { getConnection, getPumpSdk, getAmmPoolState, solanaPubkey } from '../_lib/pump.js';const MAX_PER_RUN = 100;diff --git a/api/pump/strategy-validate.js b/api/pump/strategy-validate.jsnew file mode 100644index 000000000..ac2a36d36--- /dev/null+++ b/api/pump/strategy-validate.js@@ -0,0 +1,25 @@+// POST /api/pump/strategy-validate+// Body: { strategy: <spec> }+// Returns: { data: { filterCount, exitCount, filters[], exits[] } } or 400 with parse error.++import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { makeRuntime } from '../_lib/skill-runtime.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = await readJson(req);+ if (!body?.strategy || typeof body.strategy !== 'object') {+ return error(res, 400, 'validation_error', 'strategy required');+ }++ const rt = makeRuntime();+ const r = await rt.invoke('pump-fun-strategy.validateStrategy', { strategy: body.strategy });+ if (!r.ok) return error(res, 400, 'validation_error', r.error);+ return json(res, 200, { data: r.data });+});diff --git a/public/agent-passport.html b/public/agent-passport.htmlindex 24baff4d3..c18717e6c 100644--- a/public/agent-passport.html+++ b/public/agent-passport.html@@ -34,6 +34,9 @@.copy-btn:hover { background: #f3f3f3; }.trust-bar { display: flex; align-items: center; gap: .75rem; margin-top: .75rem; padding: .65rem .85rem; border-radius: 8px; background: var(--bg); border: 1px solid var(--border); }+ .trust-bar .spark { margin-left: auto; flex: 0 0 120px; }+ .trust-bar .spark svg { width: 120px; height: 32px; display: block; }+ .trust-bar .spark-empty { font-size: .7rem; color: var(--muted); }.trust-grade { font-size: 1.6rem; font-weight: 700; min-width: 2rem; text-align: center; }.trust-A { color: var(--ok-fg); }.trust-B { color: #2e7d32; }@@ -67,8 +70,15 @@.chip[aria-pressed="true"] { background: #111; color: #fff; border-color: #111; }.atts { border-top: 1px solid #eee; }- .att { padding: .55rem .25rem; border-bottom: 1px solid #eee; display: grid; grid-template-columns: 92px 1fr; gap: .5rem .75rem; align-items: baseline; }+ .att { padding: .55rem .25rem; border-bottom: 1px solid #eee; display: grid; grid-template-columns: 92px 1fr; gap: .5rem .75rem; align-items: baseline; transition: background .8s ease; }+ .att.fresh { background: #fffbe5; animation: fadeFresh 4s ease forwards; }+ @keyframes fadeFresh { 0% { background: #fff3a3; } 100% { background: transparent; } }.att code { font-size: .72rem; color: #555; }+ .live-dot { display: inline-flex; align-items: center; gap: .3rem; font-size: .72rem; color: var(--muted); }+ .live-dot::before { content: ''; width: 8px; height: 8px; border-radius: 50%; background: #c8c8c8; }+ .live-dot.on::before { background: #43a047; box-shadow: 0 0 0 0 rgba(67,160,71,.5); animation: pulse 1.6s infinite; }+ .live-dot.off::before { background: #aaa; }+ @keyframes pulse { 0%,100% { box-shadow: 0 0 0 0 rgba(67,160,71,.5); } 50% { box-shadow: 0 0 0 5px rgba(67,160,71,0); } }.kind-feedback { color: var(--ok-fg); }.kind-validation { color: var(--info-fg); }.kind-task { color: #6a1b9a; }@@ -104,6 +114,7 @@</select><button id="load" class="primary">Load</button><button id="share" title="Copy shareable link">Share</button>+ <button id="embed" title="Copy iframe embed snippet">Embed</button></div><div id="identity"></div>@@ -111,7 +122,7 @@<h2>Reputation <span class="hint" id="rep-hint"></span></h2><div id="reputation"></div>- <h2>Recent attestations <span class="hint" id="atts-count"></span></h2>+ <h2>Recent attestations <span class="hint" id="atts-count"></span> <span id="live" class="live-dot off" title="Live updates">off</span></h2><div class="filters" id="filters" hidden><button class="chip" data-filter="all" aria-pressed="true">all</button><button class="chip" data-filter="feedback" aria-pressed="false">feedback</button>@@ -128,8 +139,10 @@$('asset').value = params.get('asset') || '';$('network').value = params.get('network') || 'devnet';- let cache = { rows: [], net: 'devnet' };+ let cache = { rows: [], net: 'devnet', knownSigs: new Set(), freshSigs: new Set() };let activeFilter = 'all';+ let pollTimer = null;+ const POLL_MS = 8000;const PUBKEY_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;diff --git a/public/studio/studio.js b/public/studio/studio.jsindex c2ed3548f..a41f73b71 100644--- a/public/studio/studio.js+++ b/public/studio/studio.js@@ -36,6 +36,12 @@ const WIDGET_TYPES = {status: 'ready',icon: '⌖',},+ 'pumpfun-feed': {+ label: 'Pump.fun Live Feed',+ desc: 'Solana agent narrates live pump.fun claims and graduations.',+ status: 'ready',+ icon: '✦',+ },};const DEMO_AVATAR = Object.freeze({diff --git a/scripts/pumpfun-lifecycle-smoke.js b/scripts/pumpfun-lifecycle-smoke.jsnew file mode 100755index 000000000..5958b9cdb--- /dev/null+++ b/scripts/pumpfun-lifecycle-smoke.js@@ -0,0 +1,214 @@+#!/usr/bin/env node+/**+ * Pump.fun lifecycle smoke test (devnet).+ *+ * Exercises (each is a separate phase, configurable via PHASES env):+ * create — launch a new bonding-curve mint via offline createV2Instruction+ * buy — use /api/pump/buy-prep + wallet sign+ * quote — read /api/pump/quote pre- and post-buy+ * sell — /api/pump/sell-prep+ * stats — trigger /api/cron/pump-agent-stats and assert row exists+ *+ * Usage:+ * SMOKE_BASE_URL=https://your-app.vercel.app \+ * SMOKE_OWNER_KEY=<base58 secret key> \+ * SMOKE_AGENT_ID=<uuid of an agent_identities row owned by the wallet> \+ * SMOKE_SESSION_COOKIE='__Host-session=...' \ # required for prep endpoints+ * PHASES=create,quote,buy,sell,stats \ # default: all+ * node scripts/pumpfun-lifecycle-smoke.js+ *+ * Requires: ~0.05 devnet SOL on owner wallet (faucet.solana.com).+ *+ * Each phase is a no-op if its prereq fails — the script reports per-phase.+ */++import { Connection, Keypair, PublicKey, VersionedTransaction } from '@solana/web3.js';+import bs58 from 'bs58';+import BN from 'bn.js';++const BASE = process.env.SMOKE_BASE_URL || 'http://localhost:3000';+const OWNER_K = process.env.SMOKE_OWNER_KEY;+const AGENT_ID = process.env.SMOKE_AGENT_ID;+const COOKIE = process.env.SMOKE_SESSION_COOKIE || '';+const NETWORK = process.env.SMOKE_NETWORK || 'devnet';+const RPC =+ process.env.SOLANA_RPC_URL_DEVNET ||+ (NETWORK === 'devnet'+ ? 'https://api.devnet.solana.com'+ : 'https://api.mainnet-beta.solana.com');+const PHASES = (process.env.PHASES || 'create,quote,buy,sell,stats')+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean);+const CRON_SECRET = process.env.CRON_SECRET;++if (!OWNER_K) {+ console.error('SMOKE_OWNER_KEY required');+ process.exit(1);+}++const owner = Keypair.fromSecretKey(bs58.decode(OWNER_K));+const conn = new Connection(RPC, 'confirmed');+const report = { base: BASE, network: NETWORK, owner: owner.publicKey.toBase58(), phases: {} };++console.log('▸ pump.fun lifecycle smoke');+console.log(' base:', BASE);+console.log(' owner:', owner.publicKey.toBase58());+console.log(' network:', NETWORK);+console.log(' phases:', PHASES.join(','));++async function api(path, init = {}) {+ const headers = { 'content-type': 'application/json', ...(init.headers || {}) };+ if (COOKIE) headers.cookie = COOKIE;+ const res = await fetch(`${BASE}${path}`, { ...init, headers });+ const text = await res.text();+ let body;+ try {+ body = JSON.parse(text);+ } catch {+ body = { raw: text };+ }+ return { ok: res.ok, status: res.status, body };+}++async function signAndSend(tx_base64) {+ const tx = VersionedTransaction.deserialize(Buffer.from(tx_base64, 'base64'));+ tx.sign([owner]);+ const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });+ const latest = await conn.getLatestBlockhash();+ await conn.confirmTransaction(+ {+ signature: sig,+ blockhash: latest.blockhash,+ lastValidBlockHeight: latest.lastValidBlockHeight,+ },+ 'confirmed',+ );+ return sig;+}++let MINT = process.env.SMOKE_MINT || null;++// ── create ────────────────────────────────────────────────────────────────+if (PHASES.includes('create')) {+ try {+ if (!AGENT_ID) throw new Error('SMOKE_AGENT_ID required for create phase');+ if (!COOKIE) throw new Error('SMOKE_SESSION_COOKIE required for create phase');+ const symbol = `SMK${Math.floor(Math.random() * 9000 + 1000)}`;+ const prep = await api('/api/pump/launch-prep', {+ method: 'POST',+ body: JSON.stringify({+ agent_id: AGENT_ID,+ wallet_address: owner.publicKey.toBase58(),+ name: `smoke ${symbol}`,+ symbol,+ uri: 'https://three.ws/agent-passport.html?smoke=1',+ network: NETWORK,+ buyback_bps: 0,+ sol_buy_in: 0,+ }),+ });+ if (!prep.ok) throw new Error(`launch-prep ${prep.status}: ${JSON.stringify(prep.body)}`);+ const sig = await signAndSend(prep.body.tx_base64);+ const confirm = await api('/api/pump/launch-confirm', {+ method: 'POST',+ body: JSON.stringify({ prep_id: prep.body.prep_id, tx_signature: sig }),+ });+ if (!confirm.ok)+ throw new Error(`launch-confirm ${confirm.status}: ${JSON.stringify(confirm.body)}`);+ MINT = prep.body.mint || confirm.body.pump_agent_mint?.mint;+ report.phases.create = { ok: true, mint: MINT, signature: sig };+ console.log(' ✓ create', MINT);+ } catch (e) {+ report.phases.create = { ok: false, error: e.message };+ console.log(' ✗ create:', e.message);+ }+}++// ── quote (pre-buy) ───────────────────────────────────────────────────────+if (PHASES.includes('quote') && MINT) {+ try {+ const r = await api(+ `/api/pump/quote?mint=${MINT}&network=${NETWORK}&direction=buy&sol=0.01&slippage_bps=500`,+ );+ if (!r.ok) throw new Error(`${r.status}: ${JSON.stringify(r.body)}`);+ report.phases.quote_pre = { ok: true, graduated: r.body.graduated, quote: r.body.quote };+ console.log(' ✓ quote pre-buy', r.body.graduated ? 'amm' : 'curve');+ } catch (e) {+ report.phases.quote_pre = { ok: false, error: e.message };+ console.log(' ✗ quote pre-buy:', e.message);+ }+}++// ── buy ───────────────────────────────────────────────────────────────────+if (PHASES.includes('buy') && MINT) {+ try {+ if (!COOKIE) throw new Error('SMOKE_SESSION_COOKIE required for buy phase');+ const prep = await api('/api/pump/buy-prep', {+ method: 'POST',+ body: JSON.stringify({+ mint: MINT,+ network: NETWORK,+ sol: 0.005,+ slippage_bps: 500,+ wallet_address: owner.publicKey.toBase58(),+ }),+ });+ if (!prep.ok) throw new Error(`buy-prep ${prep.status}: ${JSON.stringify(prep.body)}`);+ const sig = await signAndSend(prep.body.tx_base64);+ report.phases.buy = { ok: true, signature: sig, route: prep.body.route };+ console.log(' ✓ buy', sig.slice(0, 12), 'route=', prep.body.route);+ } catch (e) {+ report.phases.buy = { ok: false, error: e.message };+ console.log(' ✗ buy:', e.message);+ }+}++// ── sell ──────────────────────────────────────────────────────────────────+if (PHASES.includes('sell') && MINT) {+ try {+ if (!COOKIE) throw new Error('SMOKE_SESSION_COOKIE required for sell phase');+ // Try selling a tiny token amount — 1 token base unit. SDK will fail if+ // we hold zero, which is fine: phase reports the failure.+ const prep = await api('/api/pump/sell-prep', {+ method: 'POST',+ body: JSON.stringify({+ mint: MINT,+ network: NETWORK,+ tokens: '1000',+ slippage_bps: 500,+ wallet_address: owner.publicKey.toBase58(),+ }),+ });+ if (!prep.ok) throw new Error(`sell-prep ${prep.status}: ${JSON.stringify(prep.body)}`);+ const sig = await signAndSend(prep.body.tx_base64);+ report.phases.sell = { ok: true, signature: sig, route: prep.body.route };+ console.log(' ✓ sell', sig.slice(0, 12));+ } catch (e) {+ report.phases.sell = { ok: false, error: e.message };+ console.log(' ✗ sell:', e.message);+ }+}++// ── stats cron + read ─────────────────────────────────────────────────────+if (PHASES.includes('stats')) {+ try {+ if (!CRON_SECRET) throw new Error('CRON_SECRET required for stats phase');+ const r = await api('/api/cron/pump-agent-stats', {+ method: 'GET',+ headers: { authorization: `Bearer ${CRON_SECRET}` },+ });+ if (!r.ok) throw new Error(`cron ${r.status}: ${JSON.stringify(r.body)}`);+ report.phases.stats = { ok: true, ...r.body };+ console.log(' ✓ stats cron updated', r.body.updated, '/', r.body.scanned);+ } catch (e) {+ report.phases.stats = { ok: false, error: e.message };+ console.log(' ✗ stats:', e.message);+ }+}++console.log('\n── report ──');+console.log(JSON.stringify(report, null, 2));++const failures = Object.values(report.phases).filter((p) => !p.ok).length;+process.exit(failures > 0 ? 1 : 0);diff --git a/src/agent-home-pumpfun.js b/src/agent-home-pumpfun.jsindex 07b1a4d75..221455de4 100644--- a/src/agent-home-pumpfun.js+++ b/src/agent-home-pumpfun.js@@ -45,6 +45,7 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })tradeAmount: '',quote: null,quoting: false,+ signer: 'agent', // 'agent' = server-side agent wallet; 'owner' = browser wallet};let refreshTimer = null;let quoteTimer = null;@@ -123,6 +124,10 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })}return `<div class="pumpfun-trade">+ <div class="pumpfun-signer" role="tablist" aria-label="Signer">+ <button class="pumpfun-signer-tab ${s.signer === 'agent' ? 'is-active' : ''}" data-action="signer-agent" role="tab" aria-selected="${s.signer === 'agent'}">Agent wallet</button>+ <button class="pumpfun-signer-tab ${s.signer === 'owner' ? 'is-active' : ''}" data-action="signer-owner" role="tab" aria-selected="${s.signer === 'owner'}">Owner wallet</button>+ </div><label class="pumpfun-trade-label"><span>${isBuy ? 'Spend' : 'Sell'}</span><input@@ -141,7 +146,7 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })<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 ? '' : ''}+ ${isBuy ? 'Buy' : 'Sell'}</button></div></div>@@ -227,6 +232,14 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })if (action === 'toggle-sell') return toggleTrade('sell');if (action === 'close-trade') return closeTrade();if (action === 'confirm-trade') return executeTrade();+ if (action === 'signer-agent') return setSigner('agent');+ if (action === 'signer-owner') return setSigner('owner');+ };++ const setSigner = (signer) => {+ if (state.signer === signer) return;+ state.signer = signer;+ render();};const toggleTrade = (side) => {@@ -308,17 +321,28 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })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 },- );+ const useAgent = state.signer === 'agent';+ const skillName = useAgent+ ? 'pumpfun-self-swap'+ : isBuy+ ? 'pumpfun-buy-with-quote'+ : 'pumpfun-sell';+ const args = useAgent+ ? {+ mint: state.mint,+ side: isBuy ? 'buy' : 'sell',+ solAmount: isBuy ? parseFloat(state.tradeAmount) : undefined,+ tokenAmount: isBuy ? undefined : state.tradeAmount.replace(/\D/g, ''),+ network: state.network,+ }+ : isBuy+ ? { mint: state.mint, solAmount: parseFloat(state.tradeAmount), network: state.network }+ : {+ mint: state.mint,+ tokenAmount: state.tradeAmount.replace(/\D/g, ''),+ network: state.network,+ };+ const r = await skills.perform(skillName, args, { identity });if (r?.success) {toast(isBuy ? `Bought ${state.tradeAmount} SOL` : `Sold ${state.tradeAmount} units`,diff --git a/src/agent-skills-pumpfun-compose.js b/src/agent-skills-pumpfun-compose.jsindex eb72a4d22..5ffeb2cb1 100644--- a/src/agent-skills-pumpfun-compose.js+++ b/src/agent-skills-pumpfun-compose.js@@ -206,7 +206,7 @@ export function registerPumpFunComposeSkills(skills) {const cap = cfg(ctx, 'sessionSpendCapSol');const state = await loadState(ctx?.memory, sessionId, { seen: new Set(), spent: 0, log: [] });- while (Date.now() < deadline && state.spent + perTrade <= cap) {+ while (!args.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) {@@ -267,7 +267,7 @@ export function registerPumpFunComposeSkills(skills) {const cap = cfg(ctx, 'sessionSpendCapSol');const state = await loadState(ctx?.memory, sessionId, { mirrored: new Set(), spent: 0, log: [] });- while (Date.now() < deadline && state.spent < cap) {+ while (!args.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) {diff --git a/src/agent-skills-pumpfun.js b/src/agent-skills-pumpfun.jsindex 8e889b9eb..c24b07d5d 100644--- a/src/agent-skills-pumpfun.js+++ b/src/agent-skills-pumpfun.js@@ -123,7 +123,11 @@ export async function runServerFlow({const sig = await connection.sendRawTransaction(signed.serialize(), { skipPreflight: false });const latest = await connection.getLatestBlockhash();await connection.confirmTransaction(- { signature: sig, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight },+ {+ signature: sig,+ blockhash: latest.blockhash,+ lastValidBlockHeight: latest.lastValidBlockHeight,+ },'confirmed',);@@ -138,7 +142,9 @@ export async function runServerFlow({confirmJson = await confirmRes.json();if (!confirmRes.ok) {throw new Error(- confirmJson.error_description || confirmJson.error || `confirm failed: ${confirmRes.status}`,+ confirmJson.error_description ||+ confirmJson.error ||+ `confirm failed: ${confirmRes.status}`,);}}@@ -361,7 +367,8 @@ export function registerPumpFunSkills(skills) {amount: expected,solAmount: solLamports,slippage: slippageBps / 10_000,- tokenProgram: web3.TOKEN_PROGRAM_ID || (await import('@solana/spl-token')).TOKEN_PROGRAM_ID,+ tokenProgram:+ web3.TOKEN_PROGRAM_ID || (await import('@solana/spl-token')).TOKEN_PROGRAM_ID,});const sig = await sendIxs({@@ -707,7 +714,10 @@ export function registerPumpFunSkills(skills) {type: 'string',description: 'Currency mint (USDC, SOL wrapper, etc.)',},- amount: { type: 'string', description: 'Amount in base units (string-encoded bigint)' },+ amount: {+ type: 'string',+ description: 'Amount in base units (string-encoded bigint)',+ },memo: { type: 'string', description: 'Invoice memo / nonce (uint)' },durationSeconds: { type: 'number', description: 'Validity window (default 600)' },network: { type: 'string', enum: ['mainnet', 'devnet'] },diff --git a/src/erc8004/deploy-button.js b/src/erc8004/deploy-button.jsindex 0b6a05ca4..bb63155ad 100644--- a/src/erc8004/deploy-button.js+++ b/src/erc8004/deploy-button.js@@ -217,7 +217,7 @@ export class DeployButton {`;}- _renderSuccessChip(chainId, txHash, contractAddress) {+ _renderSuccessChip(chainId, txHash, contractAddress, vanityPrefix) {let chainName, explorerUrl;if (_isSolana(chainId)) {const network = _solanaNetwork(chainId);@@ -231,15 +231,18 @@ export class DeployButton {// surface tx hashes for arbitrary contracts.explorerUrl = contractAddress ? addressExplorerUrl(chainId, contractAddress) : '#';}+ const vanityNote = vanityPrefix+ ? ` · <span style="background:linear-gradient(90deg,#ffd54f,#ff8a65);color:#1a1a1a;padding:0 6px;border-radius:999px;font-weight:600">✨ ${_esc(vanityPrefix)}</span>`+ : '';this._root.innerHTML = `<a class="deploy-chip deploy-chip--success" href="${_esc(explorerUrl)}" target="_blank" rel="noopener noreferrer"aria-label="View this agent's registry on the ${_esc(chainName)} block explorer">- ⬢ On-chain on ${_esc(chainName)} · view on explorer+ ⬢ On-chain on ${_esc(chainName)}${vanityNote} · view on explorer</a>`;}- _renderProgress(steps, activeIdx) {+ _renderProgress(steps, activeIdx, extra) {const labels = steps.map((s, i) => {const cls = i < activeIdx ? 'done' : i === activeIdx ? 'active' : 'pending';return `<span class="progress-step progress-step--${cls}">${_esc(s)}</span>`;@@ -250,7 +253,17 @@ export class DeployButton {${labels.join('<span class="progress-sep" aria-hidden="true">→</span>')}<span class="visually-hidden">${_esc(liveText)}</span></div>+ <div class="deploy-progress-detail" aria-live="polite"+ style="margin-top:6px;font-size:12px;color:#555;font-family:ui-monospace,monospace;min-height:1.2em">+ ${extra?.text ? _esc(extra.text) : ''}+ </div>+ ${extra?.cancelable ? `<button class="deploy-cancel-btn" type="button"+ style="margin-top:4px;font-size:11px;background:none;border:1px solid #ccc;border-radius:4px;padding:2px 8px;cursor:pointer">cancel</button>` : ''}`;+ if (extra?.onCancel) {+ const cb = this._root.querySelector('.deploy-cancel-btn');+ if (cb) cb.addEventListener('click', extra.onCancel);+ }}_renderError(msg, action) {@@ -293,7 +306,12 @@ export class DeployButton {const steps = vanityPrefix? ['Grinding vanity address', 'Sign tx', 'Confirming on-chain', 'Saving']: ['Connecting wallet', 'Sign tx', 'Confirming on-chain', 'Saving'];- this._renderProgress(steps, 0);+ const abort = new AbortController();+ this._renderProgress(steps, 0, vanityPrefix ? {+ text: `searching for "${vanityPrefix}…"`,+ cancelable: true,+ onCancel: () => abort.abort(),+ } : undefined);let result;try {@@ -302,13 +320,12 @@ export class DeployButton {network,vanity: vanityPrefix ? {prefix: vanityPrefix,+ signal: abort.signal,onProgress: ({ attempts, rate, eta }) => {- const live = this._root.querySelector('.deploy-progress');- if (live) {- live.setAttribute(- 'aria-label',- `Grinding ${vanityPrefix}: ${attempts.toLocaleString()} tries, ${Math.round(rate).toLocaleString()}/s, eta ${eta}`,- );+ const detail = this._root.querySelector('.deploy-progress-detail');+ if (detail) {+ detail.textContent =+ `🔍 "${vanityPrefix}…" ${attempts.toLocaleString()} tries · ${Math.round(rate).toLocaleString()}/s · eta ${eta}`;}},} : undefined,@@ -316,7 +333,7 @@ export class DeployButton {this._renderProgress(steps, 1);this._renderProgress(steps, 3);} catch (err) {- if (_isUserRejection(err)) return this._renderDeployButton();+ if (_isUserRejection(err) || err?.name === 'AbortError') return this._renderDeployButton();if (err.code === 'forbidden') {this._renderError('Your Solana wallet is not linked to this account. Sign in with your Solana wallet first.',@@ -344,7 +361,8 @@ export class DeployButton {this._agent.chainId = this._chainId;this._agent.txHash = result.txSignature;this._agent.contractAddress = result.assetPubkey;- this._renderSuccessChip(this._chainId, result.txSignature, result.assetPubkey);+ _saveVanity(this._agent?.id, ''); // clear after successful deploy+ this._renderSuccessChip(this._chainId, result.txSignature, result.assetPubkey, result.vanityPrefix);}async _startDeploy() {diff --git a/src/onchain/payments/index.js b/src/onchain/payments/index.jsnew file mode 100644index 000000000..1411f9bbf--- /dev/null+++ b/src/onchain/payments/index.js@@ -0,0 +1,16 @@+import { PumpfunPaymentsAdapter } from './pumpfun-payments.js';++const cache = new Map();++export function getPaymentsAdapter(provider = 'pumpfun') {+ if (cache.has(provider)) return cache.get(provider);+ let inst;+ if (provider === 'pumpfun') inst = new PumpfunPaymentsAdapter();+ else throw new Error(`No payments adapter for provider: ${provider}`);+ cache.set(provider, inst);+ return inst;+}++export function _resetPaymentsAdapters() {+ cache.clear();+}diff --git a/src/onchain/payments/pumpfun-payments.js b/src/onchain/payments/pumpfun-payments.jsnew file mode 100644index 000000000..fa896fc3f--- /dev/null+++ b/src/onchain/payments/pumpfun-payments.js@@ -0,0 +1,187 @@+/**+ * PumpfunPaymentsAdapter — frontend facade for the Pump.fun agent-payments-sdk.+ *+ * Two responsibilities:+ * • Owner side: enableForAgent() — one-time, registers the agent's token to+ * accept payments. Backend builds the create tx; user signs in Phantom.+ * • Payer side: payAgent() — creates an invoice intent, builds the+ * accept-payment tx, user signs and submits.+ *+ * Same prep/sign/submit/confirm shape as the deploy and launch flows. We+ * never trust the wallet's RPC for cluster correctness — Connection is built+ * from the cluster recorded on the agent's payments config.+ */++import { Connection, Transaction, VersionedTransaction } from '@solana/web3.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);+ }+}++async function waitForConfirmation(conn, sig, timeoutMs) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ const { value } = await conn.getSignatureStatuses([sig]);+ const s = value?.[0];+ if (s) {+ if (s.err) throw new Error(`Tx failed: ${JSON.stringify(s.err)}`);+ if (s.confirmationStatus === 'confirmed' || s.confirmationStatus === 'finalized') return;+ }+ await new Promise((r) => setTimeout(r, 1500));+ }+ throw new Error('Confirmation timed out.');+}++export class PumpfunPaymentsAdapter {+ get provider() {+ return 'pumpfun';+ }++ /**+ * Owner-side: register the agent's token to accept payments.+ * Pre: agent.token.mint must exist; caller must own the agent.+ */+ async enableForAgent({ agent, onProgress = () => {} }) {+ if (!agent?.token?.mint && !agent?.meta?.token?.mint) {+ const e = new Error('Launch the agent token first.');+ e.code = 'PRECONDITION_FAILED';+ throw e;+ }+ const cluster = agent.token?.cluster || agent.meta?.token?.cluster || 'mainnet';+ const wallet = getWalletAdapter('solana');+ if (!wallet.isAvailable()) {+ const e = new Error('No Solana wallet detected.');+ e.code = 'NO_PROVIDER';+ e.installUrl = wallet.installUrl();+ throw e;+ }++ onProgress('connect');+ const { address } = await wallet.connect({ ensureLinked: true, cluster });++ onProgress('prep');+ const prepResp = await fetch('/api/agents/payments/create-prep', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ agent_id: agent.id, wallet_address: address, cluster }),+ });+ if (!prepResp.ok) throw await asError(prepResp, 'create-prep');+ const prep = await prepResp.json();++ onProgress('sign');+ const provider =+ window.phantom?.solana || window.solana || window.backpack?.solana || window.solflare;+ const signed = await provider.signTransaction(decodeTx(prep.tx_base64));++ onProgress('submit');+ const conn = new Connection(SOLANA_RPC[cluster], 'confirmed');+ const sig = await conn.sendRawTransaction(signed.serialize(), {+ preflightCommitment: 'confirmed',+ });+ await waitForConfirmation(conn, sig, 60_000);++ onProgress('confirm');+ const confirmResp = await fetch('/api/agents/payments/create-confirm', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ prep_id: prep.prep_id,+ tx_signature: sig,+ wallet_address: address,+ }),+ });+ if (!confirmResp.ok) throw await asError(confirmResp, 'create-confirm');+ return await confirmResp.json();+ }++ /**+ * Payer-side: pay an agent. Caller need not own the agent.+ * @param {{ agent: object, currencyMint: string, amount: string, memo?: string, onProgress?: Function }} opts+ */+ async payAgent({ agent, currencyMint, amount, memo, onProgress = () => {} }) {+ if (!agent?.payments?.configured && !agent?.meta?.payments?.configured) {+ const e = new Error('This agent has not enabled payments.');+ e.code = 'PRECONDITION_FAILED';+ throw e;+ }+ const cluster =+ agent.payments?.cluster || agent.meta?.payments?.cluster || 'mainnet';++ const wallet = getWalletAdapter('solana');+ if (!wallet.isAvailable()) {+ const e = new Error('No Solana wallet detected.');+ e.code = 'NO_PROVIDER';+ e.installUrl = wallet.installUrl();+ throw e;+ }++ onProgress('connect');+ const { address } = await wallet.connect({ ensureLinked: true, cluster });++ onProgress('prep');+ const prepResp = await fetch('/api/agents/payments/pay-prep', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ agent_id: agent.id,+ currency_mint: currencyMint,+ amount: String(amount),+ memo,+ wallet_address: address,+ cluster,+ }),+ });+ if (!prepResp.ok) throw await asError(prepResp, 'pay-prep');+ const prep = await prepResp.json();++ onProgress('sign');+ const provider =+ window.phantom?.solana || window.solana || window.backpack?.solana || window.solflare;+ const signed = await provider.signTransaction(decodeTx(prep.tx_base64));++ onProgress('submit');+ const conn = new Connection(SOLANA_RPC[cluster], 'confirmed');+ const sig = await conn.sendRawTransaction(signed.serialize(), {+ preflightCommitment: 'confirmed',+ });+ await waitForConfirmation(conn, sig, 60_000);++ onProgress('confirm');+ const confirmResp = await fetch('/api/agents/payments/pay-confirm', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ intent_id: prep.intent_id,+ tx_signature: sig,+ wallet_address: address,+ }),+ });+ if (!confirmResp.ok) throw await asError(confirmResp, 'pay-confirm');+ return { ...(await confirmResp.json()), txSignature: sig, intentId: prep.intent_id };+ }+}++async function asError(resp, where) {+ const data = await resp.json().catch(() => ({}));+ const err = new Error(data.error_description || `${where} returned ${resp.status}`);+ err.status = resp.status;+ err.code = data.error;+ return err;+}diff --git a/style.css b/style.cssindex 752242568..1e811ad4d 100644--- a/style.css+++ b/style.css@@ -6679,6 +6679,33 @@ textarea.erc8004-code {letter-spacing: 0.06em;opacity: 0.7;}+.pumpfun-signer {+ display: flex;+ gap: 2px;+ padding: 2px;+ border-radius: 8px;+ background: rgba(0,0,0,0.25);+ border: 1px solid rgba(255,255,255,0.05);+}+.pumpfun-signer-tab {+ flex: 1;+ background: transparent;+ border: none;+ color: inherit;+ font: inherit;+ font-size: 11px;+ padding: 6px 8px;+ border-radius: 6px;+ cursor: pointer;+ opacity: 0.6;+ transition: background .15s, opacity .15s;+}+.pumpfun-signer-tab:hover { opacity: 0.9; }+.pumpfun-signer-tab.is-active {+ opacity: 1;+ background: linear-gradient(135deg, rgba(178,125,255,0.25), rgba(108,224,200,0.18));+ box-shadow: inset 0 0 0 1px rgba(255,255,255,0.08);+}.pumpfun-trade-input {background: rgba(255,255,255,0.06);border: 1px solid rgba(255,255,255,0.1);