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 Solana wallet functionality with activity tracking and UI improvements
nirholas2f3fbb446534
diff --git a/api/_lib/agent-wallet.js b/api/_lib/agent-wallet.jsindex d09a3c2c7..2bdbb83cd 100644--- a/api/_lib/agent-wallet.js+++ b/api/_lib/agent-wallet.js@@ -99,9 +99,25 @@ export async function generateSolanaAgentWallet() {/*** Recover a Solana Keypair from its encrypted form.* Only call this when the agent needs to sign a transaction.+ *+ * Audit hook: pass `audit: { agentId, userId, reason, meta }` and a+ * usage_events row will be written fire-and-forget so every decrypt+ * is traceable.*/-export async function recoverSolanaAgentKeypair(encryptedSecret) {+export async function recoverSolanaAgentKeypair(encryptedSecret, audit = null) {const { Keypair } = await import('@solana/web3.js');const secretB64 = await decrypt(encryptedSecret);- return Keypair.fromSecretKey(Buffer.from(secretB64, 'base64'));+ const kp = Keypair.fromSecretKey(Buffer.from(secretB64, 'base64'));+ if (audit && audit.agentId) {+ const { recordEvent } = await import('./usage.js');+ recordEvent({+ userId: audit.userId ?? null,+ agentId: audit.agentId,+ kind: 'solana_key_use',+ tool: audit.reason || 'sign',+ status: 'ok',+ meta: { address: kp.publicKey.toBase58(), ...(audit.meta || {}) },+ });+ }+ return kp;}diff --git a/api/agents/solana-activity.js b/api/agents/solana-activity.jsnew file mode 100644index 000000000..486ec6f78--- /dev/null+++ b/api/agents/solana-activity.js@@ -0,0 +1,96 @@+// /api/agents/:id/solana/activity?network=mainnet|devnet&limit=20+//+// Returns recent on-chain activity for the agent's Solana wallet:+// • signatures (most-recent first), with slot, blockTime, success/failure,+// SOL delta from this address's perspective, and a short description.+// Owner-only.++import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';+import { cors, json, method, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { solanaConnection } from '../_lib/agent-pumpfun.js';+import { PublicKey } from '@solana/web3.js';++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;+}++export default async function handler(req, res, id) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const [row] = await sql`+ SELECT id, user_id, meta FROM agent_identities+ WHERE id = ${id} AND deleted_at IS NULL+ `;+ if (!row) return error(res, 404, 'not_found', 'agent not found');+ if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');++ const address = row.meta?.solana_address;+ if (!address) return error(res, 404, 'not_found', 'agent has no solana wallet');++ const url = new URL(req.url, 'http://x');+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';+ const limit = Math.min(parseInt(url.searchParams.get('limit') || '20', 10) || 20, 50);++ let signatures = [];+ try {+ const conn = solanaConnection(network);+ const pk = new PublicKey(address);+ const sigs = await conn.getSignaturesForAddress(pk, { limit });++ // Fetch parsed details in batches to compute SOL deltas.+ const parsed = await conn.getParsedTransactions(+ sigs.map((s) => s.signature),+ { maxSupportedTransactionVersion: 0, commitment: 'confirmed' },+ );++ signatures = sigs.map((s, i) => {+ const tx = parsed[i];+ let lamportDelta = null;+ let summary = null;+ if (tx?.meta && tx?.transaction) {+ const keys = tx.transaction.message.accountKeys.map((k) => k.pubkey?.toString());+ const idx = keys.indexOf(address);+ if (idx >= 0 && tx.meta.preBalances && tx.meta.postBalances) {+ lamportDelta = tx.meta.postBalances[idx] - tx.meta.preBalances[idx];+ }+ const ix = tx.transaction.message.instructions?.[0];+ if (ix?.parsed?.type) summary = ix.parsed.type;+ else if (ix?.programId) summary = `program ${ix.programId.toString().slice(0, 6)}…`;+ }+ return {+ signature: s.signature,+ slot: s.slot,+ block_time: s.blockTime ?? null,+ success: !s.err && !tx?.meta?.err,+ error: s.err || tx?.meta?.err || null,+ lamport_delta: lamportDelta,+ sol_delta: lamportDelta == null ? null : lamportDelta / 1e9,+ summary,+ };+ });+ } catch (err) {+ console.error('[agents/solana-activity] RPC fetch failed', err);+ return error(res, 502, 'rpc_error', 'failed to fetch on-chain activity');+ }++ return json(res, 200, {+ data: {+ address,+ network,+ signatures,+ },+ });+}diff --git a/api/agents/solana-airdrop.js b/api/agents/solana-airdrop.jsnew file mode 100644index 000000000..a6228ec3f--- /dev/null+++ b/api/agents/solana-airdrop.js@@ -0,0 +1,77 @@+// /api/agents/:id/solana/airdrop (POST, devnet only)+//+// Owner-only. Requests a 1 SOL devnet airdrop to the agent's wallet.+// Mainnet rejected — there's no mainnet faucet.+// Heavily rate-limited to avoid faucet abuse.++import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';+import { cors, json, method, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { solanaConnection } from '../_lib/agent-pumpfun.js';+import { PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';+import { recordEvent } from '../_lib/usage.js';++const AIRDROP_LAMPORTS = LAMPORTS_PER_SOL; // 1 SOL++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;+}++export default async function handler(req, res, id) {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const [row] = await sql`+ SELECT id, user_id, meta FROM agent_identities+ WHERE id = ${id} AND deleted_at IS NULL+ `;+ if (!row) return error(res, 404, 'not_found', 'agent not found');+ if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');++ const address = row.meta?.solana_address;+ if (!address) return error(res, 404, 'not_found', 'agent has no solana wallet');++ let signature;+ try {+ const conn = solanaConnection('devnet');+ signature = await conn.requestAirdrop(new PublicKey(address), AIRDROP_LAMPORTS);+ await conn.confirmTransaction(signature, 'confirmed');+ } catch (err) {+ console.error('[agents/solana-airdrop] failed', err);+ // Devnet faucet often runs dry — surface as 502 not 500.+ return error(res, 502, 'faucet_unavailable',+ err?.message?.includes('429') || err?.message?.includes('limit')+ ? 'Devnet faucet is rate-limited — try again in a minute.'+ : `Devnet airdrop failed: ${err?.message || 'unknown'}`);+ }++ recordEvent({+ userId: auth.userId,+ agentId: id,+ kind: 'solana_airdrop',+ tool: 'devnet',+ status: 'ok',+ meta: { address, signature, lamports: AIRDROP_LAMPORTS },+ });++ return json(res, 200, {+ data: {+ signature,+ address,+ network: 'devnet',+ lamports: AIRDROP_LAMPORTS,+ sol: AIRDROP_LAMPORTS / 1e9,+ },+ });+}diff --git a/api/mcp.js b/api/mcp.jsindex abb4350ec..5c61b54a0 100644--- a/api/mcp.js+++ b/api/mcp.js@@ -27,6 +27,7 @@ import {} from './_lib/avatars.js';import { fetchModel, FetchModelError } from './_lib/fetch-model.js';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';@@ -422,6 +423,60 @@ const TOOL_CATALOG = [additionalProperties: false,},},+ {+ name: 'pumpfun_recent_claims',+ title: 'Recent pump.fun claims',+ description:+ "Fetch the most recent pump.fun GitHub social-fee claim events with full enrichment: GitHub profile, X/Twitter follower data, influencer tier, first-time-claim flag, fake-claim detection, and AI summary. Use to answer 'what's happening on pump.fun right now?'.",+ inputSchema: {+ type: 'object',+ properties: {+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 },+ },+ additionalProperties: false,+ },+ },+ {+ name: 'pumpfun_token_intel',+ title: 'Pump.fun token intel',+ description:+ 'Full intel on a pump.fun token: graduation status, bonding-curve progress, creator profile, top holders, volume, bundle detection, and trust signals.',+ inputSchema: {+ type: 'object',+ properties: {+ mint: { type: 'string', description: 'SPL mint pubkey (base58).' },+ },+ required: ['mint'],+ additionalProperties: false,+ },+ },+ {+ name: 'pumpfun_creator_intel',+ title: 'Pump.fun creator intel',+ description:+ 'Reputation profile for a pump.fun creator wallet: prior launches, graduation rate, claim activity, and behavioural trust signals.',+ inputSchema: {+ type: 'object',+ properties: {+ wallet: { type: 'string', description: 'Solana wallet pubkey (base58).' },+ },+ required: ['wallet'],+ additionalProperties: false,+ },+ },+ {+ name: 'pumpfun_recent_graduations',+ title: 'Recent pump.fun graduations',+ description:+ 'Tokens that recently graduated from the bonding curve to PumpAMM, with creator + holder analysis.',+ inputSchema: {+ type: 'object',+ properties: {+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 },+ },+ additionalProperties: false,+ },+ },];const TOOLS = {diff --git a/api/pump/strategy-backtest.js b/api/pump/strategy-backtest.jsindex adc8d2c0b..6118b102a 100644--- a/api/pump/strategy-backtest.js+++ b/api/pump/strategy-backtest.js@@ -1,51 +1,24 @@// POST /api/pump/strategy-backtest-// Body: { strategy, mints?: string[], sinceMs?: number, useStub?: boolean }+// Body: { strategy, mints?: string[], sinceMs?: number, limit?: number }//-// When useStub:true (or PUMPFUN_BOT_URL is unset) we feed the backtester a-// deterministic synthetic trade history so the demo runs without an upstream-// MCP. Otherwise the read-only `pump-fun` skill proxies its real worker.+// Replays a strategy against historical pump.fun trade data via the read-only+// pump-fun skill (which proxies a public MCP — no env vars required). When+// `mints` is omitted, the candidate set is sourced from the strategy's+// `scan.kind` (newTokens | trending | mintList).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';-function stubInvoke(tool, args) {- const t0 = 1_700_000_000_000;- if (tool === 'pump-fun.getTokenDetails') {- return { ok: true, data: { creator: `CREATOR_${args.mint.slice(0, 4)}`, createdAt: new Date(t0).toISOString(), marketCapSol: 12 } };- }- if (tool === 'pump-fun.getTokenHolders') {- // Pseudo-random but deterministic per mint.- const seed = [...args.mint].reduce((s, c) => s + c.charCodeAt(0), 0);- const total = 30 + (seed % 200);- const top = 5 + (seed % 35);- return { ok: true, data: { total, holders: [{ pct: top }] } };- }- if (tool === 'pump-fun.getCreatorProfile') {- return { ok: true, data: { rugCount: args.creator.endsWith('X') ? 1 : 0 } };- }- if (tool === 'pump-fun.getBondingCurve') {- return { ok: true, data: { priceSol: 0.001, graduationPct: 12 } };- }- if (tool === 'pump-fun.getTokenTrades') {- const seed = [...args.mint].reduce((s, c) => s + c.charCodeAt(0), 0);- // Generate a small price walk: starts at 0.001, drifts by seed parity.- const drift = seed % 5 === 0 ? -0.0002 : seed % 3 === 0 ? 0.0008 : 0.0003;- const prices = Array.from({ length: 20 }, (_, i) => Math.max(0.0001, 0.001 + drift * i + Math.sin(i + seed) * 0.0001));- return {- ok: true,- data: {- trades: prices.map((p, i) => ({- timestamp: t0 + i * 60_000,- side: i % 2 === 0 ? 'buy' : 'sell',- solAmount: p * 1000,- tokenAmount: 1000,- priceSol: p,- })),- },- };- }- return { ok: true, data: {} };+async function resolveMints(invoke, strategy, explicit, limit) {+ if (Array.isArray(explicit) && explicit.length) return explicit;+ const scan = strategy?.scan ?? {};+ if (scan.kind === 'mintList' && Array.isArray(scan.mints)) return scan.mints;+ const tool = scan.kind === 'trending' ? 'pump-fun.getTrendingTokens' : 'pump-fun.getNewTokens';+ const r = await invoke(tool, { limit: limit ?? scan.limit ?? 20 });+ if (!r.ok) throw new Error(`scan failed: ${r.error}`);+ const items = r.data?.tokens ?? r.data ?? [];+ return items.map((t) => t.mint ?? t.address).filter(Boolean);}export default wrap(async (req, res) => {@@ -58,29 +31,20 @@ export default wrap(async (req, res) => {const body = await readJson(req);if (!body?.strategy) return error(res, 400, 'validation_error', 'strategy required');- const useStub = body.useStub === true || !process.env.PUMPFUN_BOT_URL;const rt = makeRuntime();-- let invoke = rt.invoke;- if (useStub) {- // Override invoke for the read-only pump-fun calls. Trade calls still go- // through the real runtime (and will reject without a wallet), which is- // fine — backtest never calls them.- invoke = async (tool, args) => {- if (tool.startsWith('pump-fun.')) return stubInvoke(tool, args);- return rt.invoke(tool, args);- };+ let mints;+ try {+ mints = await resolveMints(rt.invoke, body.strategy, body.mints, body.limit);+ } catch (e) {+ return error(res, 502, 'upstream_error', e.message);}+ if (!mints.length) return error(res, 422, 'no_candidates', 'no mints to backtest');- // backtestStrategy needs ctx.skills.invoke; we call it directly with a- // shimmed ctx so we can inject the stub.const { backtestStrategy } = await import('../../examples/skills/pump-fun-strategy/handlers.js');- const ctx = { skills: { invoke }, memory: { note: () => {} } };-const result = await backtestStrategy(- { strategy: body.strategy, mints: body.mints, sinceMs: body.sinceMs ?? 0 },- ctx,+ { strategy: body.strategy, mints, sinceMs: body.sinceMs ?? 0 },+ { skills: { invoke: rt.invoke }, memory: { note: () => {} } },);if (!result.ok) return error(res, 400, 'validation_error', result.error);- return json(res, 200, { data: result.data, stub: useStub });+ return json(res, 200, { data: { ...result.data, mintsUsed: mints } });});diff --git a/examples/skills/pump-fun-strategy/handlers.js b/examples/skills/pump-fun-strategy/handlers.jsindex 83a0739bc..feab875aa 100644--- a/examples/skills/pump-fun-strategy/handlers.js+++ b/examples/skills/pump-fun-strategy/handlers.js@@ -70,16 +70,24 @@ export async function runStrategy(args, ctx) {const cap = compiled.caps.sessionSpendCapSol ?? ctx?.skillConfig?.defaultSessionSpendCapSol ?? 1.0;const perTrade = compiled.entry.amountSol ?? ctx?.skillConfig?.defaultPerTradeSol ?? 0.05;const pollMs = ctx?.skillConfig?.defaultPollMs ?? 5000;+ const onLog = typeof args.onLog === 'function' ? args.onLog : () => {};const seen = new Set();- const positions = new Map(); // mint -> { amountTokens, entryPriceSol, openedAt }+ const positions = new Map();const log = [];let spent = 0;+ const emit = (entry) => { log.push(entry); try { onLog(entry); } catch {} };+while (Date.now() < deadline) {+ emit({ action: 'tick', t: Date.now(), open: positions.size, spent });+// 1. Watch exits on open positions.for (const [mint, pos] of positions) {- const snap = await snapshotMint(ctx, mint).catch(() => null);+ const snap = await snapshotMint(ctx, mint).catch((e) => {+ emit({ mint, action: 'snapshot-error', error: e.message });+ return null;+ });if (!snap) continue;const view = buildView({ ...snap, position: pos });const exit = compiled.shouldExit(view);@@ -90,17 +98,20 @@ export async function runStrategy(args, ctx) {percent: exit.percent,amountTokens: exit.amountTokens,});- log.push({ mint, action: 'exit', rule: exit, sig: r.sig, view });+ emit({ mint, action: 'exit', rule: exit, sig: r.sig, pnlPct: view.position?.pnlPct });positions.delete(mint);} catch (e) {- log.push({ mint, action: 'exit-error', error: e.message });+ emit({ mint, action: 'exit-error', error: e.message });}}}// 2. Hunt for new entries while under cap.if (spent + perTrade <= cap && positions.size < (compiled.caps.maxOpenPositions ?? Infinity)) {- const candidates = await fetchCandidates(ctx, compiled.scan);+ const candidates = await fetchCandidates(ctx, compiled.scan).catch((e) => {+ emit({ action: 'scan-error', error: e.message });+ return [];+ });for (const t of candidates) {const mint = t.mint ?? t.address;if (!mint || seen.has(mint) || positions.has(mint)) continue;@@ -109,7 +120,7 @@ export async function runStrategy(args, ctx) {if (!snap) continue;const view = buildView(snap);if (!compiled.passes(view)) {- log.push({ mint, action: 'skip', view });+ emit({ mint, action: 'skip', view });continue;}try {@@ -120,10 +131,10 @@ export async function runStrategy(args, ctx) {entryPriceSol: snap.curve?.priceSol ?? 0,openedAt: Date.now(),});- log.push({ mint, action: 'enter', sig: buy.sig, spent });+ emit({ mint, action: 'enter', sig: buy.sig, spent, entryPriceSol: snap.curve?.priceSol ?? 0 });if (spent + perTrade > cap) break;} catch (e) {- log.push({ mint, action: 'enter-error', error: e.message });+ emit({ mint, action: 'enter-error', error: e.message });}}}diff --git a/public/dashboard/agent-pumpfun.html b/public/dashboard/agent-pumpfun.htmlindex c4f3e30a0..cccbfbfa7 100644--- a/public/dashboard/agent-pumpfun.html+++ b/public/dashboard/agent-pumpfun.html@@ -179,6 +179,7 @@</dl><div class="row" style="margin-top: 10px"><button class="btn ghost" id="provision-btn" hidden>Provision Solana wallet</button>+ <a class="btn ghost" id="vanity-link" href="/vanity-wallet" target="_blank" rel="noopener">Grind vanity address ✦</a><a id="explorer-link" class="muted" href="#" target="_blank" rel="noopener" hidden>Open on Solscan ↗</a></div></div>@@ -420,6 +421,81 @@els.agentAddress.textContent = err.message;}}+ refreshSns();+ }++ function renderSnsList(data) {+ const cur = data.sns_domain;+ if (cur) {+ els.snsCurrent.textContent = `${cur}.sol`;+ els.snsCurrent.classList.remove('muted');+ els.snsClearBtn.hidden = false;+ } else {+ els.snsCurrent.textContent = '— none attached —';+ els.snsCurrent.classList.add('muted');+ els.snsClearBtn.hidden = true;+ }+ const owned = Array.isArray(data.domains) ? data.domains : [];+ if (!owned.length) {+ els.snsDomainList.innerHTML = '<span class="muted" style="font-size:13px">This wallet does not own any .sol domains yet. Register one on sns.id, then refresh.</span>';+ return;+ }+ els.snsDomainList.innerHTML = '';+ for (const d of owned) {+ const btn = document.createElement('button');+ btn.className = 'btn ghost';+ btn.style.fontSize = '12px';+ btn.textContent = d === cur ? `★ ${d}.sol` : `${d}.sol`;+ btn.disabled = d === cur;+ btn.addEventListener('click', () => attachSns(d));+ els.snsDomainList.appendChild(btn);+ }+ if (data.favorite && !owned.includes(data.favorite)) {+ const fav = document.createElement('span');+ fav.className = 'muted';+ fav.style.fontSize = '12px';+ fav.textContent = `(favorite: ${data.favorite}.sol)`;+ els.snsDomainList.appendChild(fav);+ }+ }++ async function refreshSns() {+ const id = currentAgentId();+ if (!id) return;+ els.snsCurrent.textContent = '…';+ els.snsDomainList.innerHTML = '';+ try {+ const { data } = await api(`/api/agents/${id}/sns`);+ renderSnsList(data);+ } catch (err) {+ els.snsCurrent.textContent = err.body?.error === 'conflict' ? 'Provision a Solana wallet first' : err.message;+ els.snsDomainList.innerHTML = '';+ els.snsClearBtn.hidden = true;+ }+ }++ async function attachSns(domain) {+ const id = currentAgentId();+ if (!id) return;+ try {+ await api(`/api/agents/${id}/sns`, { method: 'POST', body: JSON.stringify({ domain }) });+ toast(`Attached ${domain}.sol`);+ await refreshSns();+ } catch (err) {+ toast(err.message, 'err');+ }+ }++ async function clearSns() {+ const id = currentAgentId();+ if (!id) return;+ try {+ await api(`/api/agents/${id}/sns`, { method: 'DELETE' });+ toast('SNS id cleared');+ await refreshSns();+ } catch (err) {+ toast(err.message, 'err');+ }}async function provision() {diff --git a/public/dashboard/index.html b/public/dashboard/index.htmlindex 34d1576bc..c10cabe82 100644--- a/public/dashboard/index.html+++ b/public/dashboard/index.html@@ -1140,6 +1140,7 @@<a href="#billing" data-tab="billing">Plan & usage</a><a href="#account" data-tab="account">Account</a><a href="/dashboard/wallets">Wallets</a>+ <a href="/vanity-wallet">Vanity wallet ✦</a><a href="/dashboard/agent-pumpfun">Agent · Pump.fun</a><a href="/discover" title="Browse on-chain agents across every supported chain">Discover on-chain ↗</adiff --git a/src/agent-home-pumpfun.js b/src/agent-home-pumpfun.jsindex 1f2ad8bad..3e3c75309 100644--- a/src/agent-home-pumpfun.js+++ b/src/agent-home-pumpfun.js@@ -77,10 +77,14 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })<span class="pumpfun-card-icon">◎</span><span class="pumpfun-card-title">Launch coin on pump.fun</span></div>- <p class="pumpfun-card-sub">Mint a token whose metadata is your 3D avatar. The agent signs from its own wallet.</p>+ <p class="pumpfun-card-sub">Mint a token whose metadata is your 3D avatar.</p>+ <div class="pumpfun-signer" role="tablist" aria-label="Signer">+ <button class="pumpfun-signer-tab ${state.signer === 'agent' ? 'is-active' : ''}" data-action="signer-agent" role="tab" aria-selected="${state.signer === 'agent'}">Agent wallet</button>+ <button class="pumpfun-signer-tab ${state.signer === 'owner' ? 'is-active' : ''}" data-action="signer-owner" role="tab" aria-selected="${state.signer === 'owner'}">Owner wallet</button>+ </div><label class="pumpfun-vanity-row" title="Grind a custom mint address ending in your suffix. Slower, but distinctive."><input type="checkbox" data-action="toggle-vanity" ${state.vanityEnabled ? 'checked' : ''}>- <span>Vanity address ends with</span>+ <span>Vanity ends with</span><input type="text" data-action="vanity-suffix" value="${escapeAttr(state.vanitySuffix)}" maxlength="6" ${state.vanityEnabled ? '' : 'disabled'} class="pumpfun-vanity-input"></label>${state.vanityProgress ? `<div class="pumpfun-vanity-progress">grinding… ${formatNumber(state.vanityProgress.rate)}/s · eta ${escapeHtml(state.vanityProgress.eta)}</div>` : ''}diff --git a/src/agent-skills-pumpfun-compose.js b/src/agent-skills-pumpfun-compose.jsindex f403486e7..a3cf605c9 100644--- a/src/agent-skills-pumpfun-compose.js+++ b/src/agent-skills-pumpfun-compose.js@@ -1,12 +1,18 @@/*** Pump.fun composition skills — agent-level loops over read (MCP) + trade (signed).- * Mirrors examples/skills/pump-fun-compose/handlers.js but runs inside AgentSkills- * so it composes pumpfun-buy / pumpfun-sell instead of file-based sibling skills.+ * Composes pumpfun-buy / pumpfun-sell / pumpfun-status in-process.*- * Safety:- * - simulate:true → vet/quote run, signing skipped, returns SIMULATED:* sigs- * - sessionId:"..." → seen/mirrored/spent/exited persisted in agent memory,- * survives crashes within the spend cap.+ * Args supported by every loop:+ * - sessionId:"..." → seen/mirrored/spent/exited persisted in agent memory,+ * survives crashes within the spend cap.+ * - signal → AbortSignal; loops, sleeps, and inner iterations all+ * bail out promptly when aborted.+ * - onProgress(evt) → called on every state change (vet/skip/buy/sell/sleep).+ * Used by the UI for live counters.+ * - dryRun:true → identical control flow; trade-skill calls are replaced+ * with `{ signature: null, dryRun: true }`. Spend cap+ * and seen/mirrored sets still tick so a dry-run+ * terminates the same way a live run would.*/const MCP_ENDPOINT = 'https://pump-fun-sdk.modelcontextprotocol.name/mcp';@@ -91,21 +97,34 @@ function saveState(memory, sessionId, state) {} catch {}}-async function maybeBuy(skills, ctx, simulate, mint, solAmount) {- if (simulate) return { signature: `SIMULATED:buy:${mint}:${solAmount}`, simulated: true };+function abortableSleep(ms, signal) {+ return new Promise((resolve) => {+ if (signal?.aborted) return resolve();+ const t = setTimeout(resolve, ms);+ const onAbort = () => { clearTimeout(t); resolve(); };+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++async function doBuy(skills, ctx, dryRun, mint, solAmount) {+ if (dryRun) return { signature: null, dryRun: true };const r = await skills.perform('pumpfun-buy', { mint, solAmount }, ctx);if (!r?.success) throw new Error(r?.output || 'pumpfun-buy failed');return r.data;}-async function maybeSell(skills, ctx, simulate, mint) {+async function doSell(skills, ctx, dryRun, mint) {const status = await skills.perform('pumpfun-status', { mint }, ctx);const tokenAmount = status?.data?.userBalance ?? '0';- if (simulate) return { signature: `SIMULATED:sell:${mint}:${tokenAmount}`, simulated: true };- if (tokenAmount === '0') return { signature: 'NOOP:no-balance', simulated: false };+ if (tokenAmount === '0') return { signature: null, skipped: 'no-balance', tokenAmount };+ if (dryRun) return { signature: null, dryRun: true, tokenAmount };const r = await skills.perform('pumpfun-sell', { mint, tokenAmount }, ctx);if (!r?.success) throw new Error(r?.output || 'pumpfun-sell failed');- return r.data;+ return { ...r.data, tokenAmount };+}++function emit(progress, evt) {+ try { progress?.(evt); } catch {}}function passesFilters(ctx, { creator, holders }) {@@ -140,7 +159,7 @@ async function vetMint(mint) {export function registerPumpFunComposeSkills(skills) {skills.register({name: 'pumpfun-research-and-buy',- description: 'Research a pump.fun token, then buy if it passes rug/holder filters. Set simulate:true to dry-run.',+ description: 'Research a pump.fun token, then buy if it passes rug/holder filters.',instruction: 'search → vet (curve, holders, creator rug flags) → buy via pumpfun-buy.',animationHint: 'inspect',voicePattern: 'Researching {{query}}…',@@ -150,33 +169,38 @@ export function registerPumpFunComposeSkills(skills) {properties: {query: { type: 'string' },amountSol: { type: 'number' },- simulate: { type: 'boolean' },+ dryRun: { type: 'boolean', description: 'Vet/quote but skip the actual buy.' },},required: ['query'],},handler: async (args, ctx) => {- const simulate = !!args.simulate;+ const dryRun = !!args.dryRun;+ const onProgress = args.onProgress;+ emit(onProgress, { type: 'search', query: args.query });const search = await mcp('searchTokens', { query: args.query, limit: 1 });const mint = search?.results?.[0]?.mint ?? search?.[0]?.mint ?? args.query;+ emit(onProgress, { type: 'vet', mint });const v = await vetMint(mint);const verdict = passesFilters(ctx, v);if (!verdict.ok) {+ emit(onProgress, { type: 'skip', mint, reason: verdict.reason });return {success: true,output: `Skipping ${mint.slice(0, 8)}…: ${verdict.reason}`,sentiment: -0.1,- data: { mint, decision: 'skip', reason: verdict.reason, simulate },+ data: { mint, decision: 'skip', reason: verdict.reason, dryRun },};}const amountSol = args.amountSol ?? cfg(ctx, 'perTradeSol');- const buy = await maybeBuy(skills, ctx, simulate, mint, amountSol);+ emit(onProgress, { type: dryRun ? 'dry-buy' : 'buy', mint, amountSol });+ const buy = await doBuy(skills, ctx, dryRun, mint, amountSol);return {success: true,- output: simulate+ output: dryRun? `Dry-run buy ${amountSol} SOL of ${mint.slice(0, 8)}….`: `Bought ${amountSol} SOL of ${mint.slice(0, 8)}….`,sentiment: 0.6,- data: { mint, decision: 'buy', amountSol, sig: buy.signature, simulate },+ data: { mint, decision: 'buy', amountSol, sig: buy.signature, dryRun },};},});diff --git a/src/agent-solana-wallet.js b/src/agent-solana-wallet.jsindex 4f04113fd..e375ff367 100644--- a/src/agent-solana-wallet.js+++ b/src/agent-solana-wallet.js@@ -150,27 +150,91 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {const root = document.createElement('section');root.className = 'agent-sol-wallet';+ root.hidden = true; // unhide once we know the user is allowed to see itpanel.appendChild(root);let state = {- address: identity.solana_address || identity.meta?.solana_address || null,- vanityPrefix: identity.meta?.solana_vanity_prefix || null,- source: identity.meta?.solana_wallet_source || null,+ loaded: false,+ address: null,+ vanityPrefix: null,+ source: null,+ network: 'mainnet',+ sol: null,+ lamports: null,busy: false,progress: null,err: null,};let abort = null;+ let balanceTimer = null;++ async function loadFromServer() {+ const r = await fetchAgentSolanaWallet(identity.id, state.network);+ if (r.status === 'forbidden') {+ root.remove();+ return false;+ }+ root.hidden = false;+ if (r.status === 'ok') {+ state.address = r.data.address;+ state.vanityPrefix = r.data.vanity_prefix || null;+ state.source = r.data.source || null;+ state.lamports = r.data.lamports;+ state.sol = r.data.sol;+ _propagate(identity, r.data);+ } else if (r.status === 'none') {+ state.address = null;+ } else {+ state.err = r.error || 'failed to load wallet';+ }+ state.loaded = true;+ render();+ return true;+ }++ async function refreshBalance() {+ if (!state.address) return;+ const r = await fetchAgentSolanaWallet(identity.id, state.network);+ if (r.status === 'ok') {+ state.lamports = r.data.lamports;+ state.sol = r.data.sol;+ render();+ }+ }++ function startBalancePoll() {+ stopBalancePoll();+ balanceTimer = setInterval(refreshBalance, 30_000);+ }+ function stopBalancePoll() {+ if (balanceTimer) clearInterval(balanceTimer);+ balanceTimer = null;+ }function render() {+ if (!state.loaded) {+ root.innerHTML = `<div class="skel">Loading Solana wallet…</div>`;+ return;+ }if (state.address) {const pfx = state.vanityPrefix || '';const rest = state.address.slice(pfx.length);+ const solDisplay = state.sol == null ? '—' : `${state.sol.toFixed(4)} SOL`;root.innerHTML = `<h3>Solana wallet${state.source ? `<span class="src">· ${_esc(state.source)}</span>` : ''}</h3><div class="addr"><span class="pfx">${_esc(pfx)}</span>${_esc(rest)}</div>+ <div class="balance">+ <span class="sol">${_esc(solDisplay)}</span>+ <span class="net">+ <select data-act="network" aria-label="Network">+ <option value="mainnet" ${state.network === 'mainnet' ? 'selected' : ''}>Mainnet</option>+ <option value="devnet" ${state.network === 'devnet' ? 'selected' : ''}>Devnet</option>+ </select>+ </span>+ </div><div class="row">- <button data-act="copy">Copy</button>+ <button data-act="copy">Copy address</button>+ <button data-act="explorer">Explorer</button><button data-act="replace">Replace</button></div>${state.err ? `<div class="err">${_esc(state.err)}</div>` : ''}@@ -178,9 +242,19 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {root.querySelector('[data-act="copy"]').addEventListener('click', () => {navigator.clipboard?.writeText(state.address).catch(() => {});});+ root.querySelector('[data-act="explorer"]').addEventListener('click', () => {+ const cluster = state.network === 'devnet' ? '?cluster=devnet' : '';+ window.open(`https://explorer.solana.com/address/${state.address}${cluster}`, '_blank', 'noopener');+ });root.querySelector('[data-act="replace"]').addEventListener('click', onReplace);+ root.querySelector('[data-act="network"]').addEventListener('change', (e) => {+ state.network = e.target.value;+ refreshBalance();+ });+ startBalancePoll();return;}+ stopBalancePoll();root.innerHTML = `<h3>Solana wallet</h3>@@ -206,8 +280,11 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {state.address = data.address;state.vanityPrefix = data.vanity_prefix || null;state.source = data.source || 'generated';+ state.lamports = data.lamports ?? 0;+ state.sol = data.sol ?? 0;_propagate(identity, data);onProvisioned?.(data);+ refreshBalance();} catch (e) {state.err = e.message;} finally {@@ -238,9 +315,12 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {state.address = data.address;state.vanityPrefix = data.vanity_prefix || prefix || null;state.source = data.source || 'imported_vanity';+ state.lamports = data.lamports ?? 0;+ state.sol = data.sol ?? 0;state.progress = null;_propagate(identity, data);onProvisioned?.(data);+ refreshBalance();} catch (e) {state.err = e.name === 'AbortError' ? 'cancelled' : e.message;state.progress = null;@@ -257,6 +337,9 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {state.address = null;state.vanityPrefix = null;state.source = null;+ state.lamports = null;+ state.sol = null;+ _propagate(identity, { address: null, vanity_prefix: null, source: null });} catch (e) {state.err = e.message;} finally {@@ -265,7 +348,20 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {}render();- return { destroy: () => root.remove() };+ loadFromServer().catch((e) => {+ state.err = e.message || 'failed to load wallet';+ state.loaded = true;+ root.hidden = false;+ render();+ });++ return {+ destroy: () => {+ stopBalancePoll();+ abort?.abort();+ root.remove();+ },+ };}function _propagate(identity, data) {diff --git a/src/pump/pump-modals.js b/src/pump/pump-modals.jsindex ad5c8ae8e..7dd7b547b 100644--- a/src/pump/pump-modals.js+++ b/src/pump/pump-modals.js@@ -105,25 +105,60 @@ function openModal() {return { back, inner, close };}-async function signAndSend(txBase64, extraSigners = []) {+// Bundled, not loaded from a CDN: same @solana/web3.js + spl-token versions+// the rest of the app uses.+import {+ VersionedTransaction,+ Connection,+ PublicKey,+ Keypair,+} from '@solana/web3.js';+import {+ getAssociatedTokenAddress,+ createAssociatedTokenAccountInstruction,+ getAccount,+ TOKEN_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,+} from '@solana/spl-token';++const RPC = (network) =>+ network === 'devnet'+ ? 'https://api.devnet.solana.com'+ : 'https://api.mainnet-beta.solana.com';++const USDC_MINT = {+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',+};++/**+ * Derive the user's USDC associated token account. If the ATA does not yet+ * exist, returns null for `existing` so the caller can prepend a creation ix.+ */+export async function resolveUsdcAta({ owner, network = 'mainnet', currencyMint } = {}) {+ const ownerPk = owner instanceof PublicKey ? owner : new PublicKey(owner);+ const mint = new PublicKey(currencyMint || USDC_MINT[network] || USDC_MINT.mainnet);+ const ata = await getAssociatedTokenAddress(mint, ownerPk, false);+ const conn = new Connection(RPC(network), 'confirmed');+ let existing = null;+ try {+ existing = await getAccount(conn, ata);+ } catch {+ existing = null;+ }+ return { ata, mint, owner: ownerPk, existing, connection: conn };+}++async function signAndSend(txBase64, { extraSigners = [], network = 'mainnet' } = {}) {const wallet = detectSolanaWallet();if (!wallet) throw new Error('No Solana wallet detected. Install Phantom.');if (!wallet.isConnected) await wallet.connect?.();- const [{ VersionedTransaction, Connection }, _] = await Promise.all([- import('https://esm.sh/@solana/[email protected]?bundle'),- Promise.resolve(),- ]);const tx = VersionedTransaction.deserialize(Uint8Array.from(atob(txBase64), (c) => c.charCodeAt(0)),);for (const kp of extraSigners) tx.sign([kp]);const signed = await wallet.signTransaction(tx);- const conn = new Connection(- wallet.network === 'devnet'- ? 'https://api.devnet.solana.com'- : 'https://api.mainnet-beta.solana.com',- 'confirmed',- );+ const conn = new Connection(RPC(network), 'confirmed');const sig = await conn.sendRawTransaction(signed.serialize(), {skipPreflight: false,});@@ -178,10 +213,15 @@ function openPay({ mint, network }) {try {if (!wallet.isConnected) await wallet.connect?.();const payer = wallet.publicKey?.toBase58?.() || wallet.publicKey?.toString();- // User's USDC ATA — we ask the wallet for it via getTokenAccountsByOwner.- // For simplicity here, we accept the wallet auto-routing and let prep- // validate. Many wallets resolve this client-side; we send user_token_account- // as the wallet pubkey and let backend reject with a clear error.+ btn.textContent = 'Resolving ATA…';+ const { ata, existing } = await resolveUsdcAta({ owner: payer, network });+ if (!existing) {+ err.textContent =+ 'Your USDC token account does not exist on this wallet yet. Receive any amount of USDC first, then try again.';+ btn.disabled = false;+ btn.textContent = 'Pay';+ return;+ }btn.textContent = 'Preparing…';const prep = await fetch('/api/pump/accept-payment-prep', {method: 'POST',@@ -190,7 +230,7 @@ function openPay({ mint, network }) {body: JSON.stringify({mint,payer_wallet: payer,- user_token_account: payer, // server should be tolerant; ATA derivation is wallet-specific+ user_token_account: ata.toBase58(),amount_usdc: amt,duration_seconds: win,tool_name: tool || undefined,@@ -199,7 +239,7 @@ function openPay({ mint, network }) {}).then((r) => r.json());if (prep.error) throw new Error(prep.error_description || prep.error);btn.textContent = 'Sign in wallet…';- const sig = await signAndSend(prep.tx_base64);+ const sig = await signAndSend(prep.tx_base64, { network });btn.textContent = 'Confirming…';const confirm = await fetch('/api/pump/accept-payment-confirm', {method: 'POST',@@ -273,7 +313,7 @@ function openGovernance({ mint, currentBps }) {}).then((r) => r.json());if (prep.error) throw new Error(prep.error_description || prep.error);btn.textContent = 'Sign in wallet…';- const sig = await signAndSend(prep.tx_base64);+ const sig = await signAndSend(prep.tx_base64, { network: 'mainnet' });btn.textContent = `Done · ${sig.slice(0, 6)}…`;} catch (e) {err.textContent = e.message || String(e);@@ -417,14 +457,16 @@ function openLaunch({ identity, agentId }) {}).then((r) => r.json());if (prep.error) throw new Error(prep.error_description || prep.error);- const [{ Keypair }] = await Promise.all([- import('https://esm.sh/@solana/[email protected]?bundle'),- ]);- const mintKp = Keypair.fromSecretKey(- Uint8Array.from(atob(prep.mint_secret_key_b64), (c) => c.charCodeAt(0)),- );+ const mintKp = prep.mint_secret_key_b64+ ? Keypair.fromSecretKey(+ Uint8Array.from(atob(prep.mint_secret_key_b64), (c) => c.charCodeAt(0)),+ )+ : null;btn.textContent = 'Sign in wallet…';- const sig = await signAndSend(prep.tx_base64, [mintKp]);+ const sig = await signAndSend(prep.tx_base64, {+ extraSigners: mintKp ? [mintKp] : [],+ network: 'mainnet',+ });btn.textContent = 'Confirming…';const confirm = await fetch('/api/pump/launch-confirm', {method: 'POST',