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 pumpfun integration with payments and strategy features

nirholas56d56d5fa974
diff --git a/api/pump/strategy-backtest.js b/api/pump/strategy-backtest.js
new file mode 100644
index 000000000..adc8d2c0b
--- /dev/null
+++ b/api/pump/strategy-backtest.js
@@ -0,0 +1,86 @@
+// POST /api/pump/strategy-backtest
+// Body: { strategy, mints?: string[], sinceMs?: number, useStub?: boolean }
+//
+// 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.
+
+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: {} };
+}
+
+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) 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);
+ };
+ }
+
+ // 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,
+ );
+ if (!result.ok) return error(res, 400, 'validation_error', result.error);
+ return json(res, 200, { data: result.data, stub: useStub });
+});
diff --git a/api/pump/strategy-run.js b/api/pump/strategy-run.js
new file mode 100644
index 000000000..bf5419edb
--- /dev/null
+++ b/api/pump/strategy-run.js
@@ -0,0 +1,112 @@
+// POST /api/pump/strategy-run (Server-Sent Events)
+// Body: { strategy, durationSec, useStub?: boolean }
+//
+// Streams a simulated live run as SSE. Each line of activity (skip / enter /
+// exit / error) is emitted as `event: log` with a JSON payload. A final
+// `event: done` carries the summary. Always simulate=true on this endpoint —
+// no real signing from the browser-facing surface.
+
+import { cors, method, 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 = Date.now();
+ if (tool === 'pump-fun.getNewTokens' || tool === 'pump-fun.getTrendingTokens') {
+ const limit = args?.limit ?? 5;
+ return { ok: true, data: { tokens: Array.from({ length: limit }, (_, i) => ({ mint: `MINT${Math.floor(t0 / 1000)}_${i}` })) } };
+ }
+ if (tool === 'pump-fun.getTokenDetails') {
+ return { ok: true, data: { creator: `CREATOR_${args.mint.slice(0, 4)}`, createdAt: new Date().toISOString(), marketCapSol: 12 } };
+ }
+ if (tool === 'pump-fun.getTokenHolders') {
+ const seed = [...args.mint].reduce((s, c) => s + c.charCodeAt(0), 0);
+ return { ok: true, data: { total: 30 + (seed % 200), holders: [{ pct: 5 + (seed % 35) }] } };
+ }
+ if (tool === 'pump-fun.getCreatorProfile') {
+ return { ok: true, data: { rugCount: 0 } };
+ }
+ if (tool === 'pump-fun.getBondingCurve') {
+ const seed = [...(args?.mint ?? '')].reduce((s, c) => s + c.charCodeAt(0), 0);
+ // Drift price up over time so exits eventually trigger.
+ const drift = ((Date.now() / 5000) % 30) * 0.00002 * (seed % 3 === 0 ? 1 : -1);
+ return { ok: true, data: { priceSol: Math.max(0.0001, 0.001 + drift), graduationPct: 12 } };
+ }
+ if (tool === 'pump-fun.getTokenTrades') {
+ return { ok: true, data: { trades: [] } };
+ }
+ return { ok: true, data: {} };
+}
+
+export default async function handler(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');
+
+ let body;
+ try { body = await readJson(req); } catch (e) { return error(res, 400, 'validation_error', e.message); }
+ if (!body?.strategy) return error(res, 400, 'validation_error', 'strategy required');
+ const durationSec = Math.max(5, Math.min(120, Number(body.durationSec) || 30));
+
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/event-stream');
+ res.setHeader('cache-control', 'no-cache, no-transform');
+ res.setHeader('connection', 'keep-alive');
+ res.setHeader('access-control-allow-origin', '*');
+
+ const send = (event, data) => {
+ res.write(`event: ${event}\n`);
+ res.write(`data: ${JSON.stringify(data)}\n\n`);
+ };
+
+ const useStub = body.useStub === true || !process.env.PUMPFUN_BOT_URL;
+ const rt = makeRuntime({ onEvent: (e) => send('memory', e) });
+
+ let invoke = rt.invoke;
+ if (useStub) {
+ invoke = async (tool, args) => {
+ if (tool.startsWith('pump-fun.')) return stubInvoke(tool, args);
+ return rt.invoke(tool, args);
+ };
+ }
+
+ send('start', { durationSec, useStub });
+
+ const { runStrategy } = await import('../../examples/skills/pump-fun-strategy/handlers.js');
+ const ctx = {
+ skills: { invoke },
+ skillConfig: { defaultPollMs: 1500 },
+ memory: { note: (tag, value) => send('memory', { tag, value }) },
+ };
+
+ // Patch the log via a Proxy on the strategy state isn't trivial — instead
+ // run with a short poll interval and stream the final log piece-by-piece by
+ // wrapping invoke to forward enter/skip/exit decisions live.
+ const wrappedCtx = {
+ ...ctx,
+ skills: {
+ invoke: async (tool, args) => {
+ const r = await invoke(tool, args);
+ if (tool === 'pump-fun-trade.buyToken' || tool === 'pump-fun-trade.sellToken') {
+ send('trade', { tool, args, result: r });
+ }
+ return r;
+ },
+ },
+ };
+
+ try {
+ const result = await runStrategy(
+ { strategy: body.strategy, durationSec, simulate: true },
+ wrappedCtx,
+ );
+ // Stream the trade log as discrete events for the UI.
+ for (const entry of result.data?.log ?? []) send('log', entry);
+ send('done', result.data);
+ } catch (e) {
+ send('error', { message: e.message });
+ }
+ res.end();
+}
diff --git a/api/widgets/_demo-fixtures.js b/api/widgets/_demo-fixtures.js
index 039e12d37..d5afab3f9 100644
--- a/api/widgets/_demo-fixtures.js
+++ b/api/widgets/_demo-fixtures.js
@@ -125,6 +125,25 @@ export const DEMO_WIDGETS = {
hotspots: [],
},
}),
+
+ wdgt_demo_pumpfun: fixture({
+ id: 'wdgt_demo_pumpfun',
+ type: 'pumpfun-feed',
+ name: 'Pump.fun Live Feed',
+ modelUrl: SOLDIER,
+ config: {
+ background: '#0a0a0a',
+ accent: '#8b5cf6',
+ caption: '',
+ showControls: false,
+ autoRotate: true,
+ envPreset: 'neutral',
+ kind: 'all',
+ minTier: '',
+ autoNarrate: true,
+ maxCards: 8,
+ },
+ }),
};
export function isDemoWidgetId(id) {
diff --git a/public/agent-passport.html b/public/agent-passport.html
index c18717e6c..cb2ccc345 100644
--- a/public/agent-passport.html
+++ b/public/agent-passport.html
@@ -200,6 +200,7 @@
if (!asset) { showError('identity', 'Enter an asset pubkey above.'); return; }
if (!PUBKEY_RE.test(asset)) { showError('identity', 'That doesn’t look like a Solana pubkey.'); return; }
+ stopPolling();
history.replaceState({}, '', `?asset=${asset}&network=${network}`);
$('load').disabled = true;
showSkeletons('identity', 1);
@@ -209,17 +210,25 @@
$('filters').hidden = true;
try {
- const [card, rep, atts] = await Promise.all([
+ const [card, rep, atts, hist] = await Promise.all([
fetch(`/api/agents/solana-card?asset=${asset}`).then((r) => r.ok ? r.json() : null).catch(() => null),
fetch(`/api/agents/solana-reputation?asset=${asset}&network=${network}`).then((r) => r.json()),
fetch(`/api/agents/solana-attestations?asset=${asset}&network=${network}&limit=25`).then((r) => r.json()),
+ fetch(`/api/agents/solana-reputation-history?asset=${asset}&network=${network}&days=30`).then((r) => r.json()).catch(() => ({ series: [] })),
]);
- renderIdentity(card, rep, asset, network);
+ const initialRows = atts.data || [];
+ renderIdentity(card, rep, asset, network, hist?.series || []);
renderReputation(rep);
- cache = { rows: atts.data || [], net: network };
+ cache = {
+ rows: initialRows,
+ net: network,
+ knownSigs: new Set(initialRows.map((r) => r.signature)),
+ freshSigs: new Set(),
+ };
$('filters').hidden = false;
renderAttestations();
+ startPolling(asset, network);
} catch (e) {
showError('identity', `Failed to load: ${e.message || e}`);
} finally {
@@ -227,13 +236,64 @@
}
}
- function renderIdentity(card, rep, asset, network) {
+ // -- Live polling --------------------------------------------------
+
+ function startPolling(asset, network) {
+ stopPolling();
+ setLive(true);
+ const tick = async () => {
+ if (document.hidden) return;
+ try {
+ const [atts, rep] = await Promise.all([
+ fetch(`/api/agents/solana-attestations?asset=${asset}&network=${network}&limit=25`).then((r) => r.json()),
+ fetch(`/api/agents/solana-reputation?asset=${asset}&network=${network}`).then((r) => r.json()),
+ ]);
+ const rows = atts.data || [];
+ const freshSigs = new Set();
+ for (const r of rows) {
+ if (!cache.knownSigs.has(r.signature)) freshSigs.add(r.signature);
+ }
+ if (freshSigs.size > 0) {
+ cache.rows = rows;
+ cache.knownSigs = new Set(rows.map((r) => r.signature));
+ cache.freshSigs = freshSigs;
+ renderAttestations();
+ renderReputation(rep);
+ // clear the highlight class after the animation
+ setTimeout(() => { cache.freshSigs = new Set(); }, 4500);
+ }
+ } catch {
+ // transient — stay live, try again next tick
+ }
+ };
+ pollTimer = setInterval(tick, POLL_MS);
+ }
+
+ function stopPolling() {
+ if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
+ setLive(false);
+ }
+
+ function setLive(on) {
+ const el = $('live');
+ el.classList.toggle('on', on);
+ el.classList.toggle('off', !on);
+ el.textContent = on ? 'live' : 'off';
+ }
+
+ document.addEventListener('visibilitychange', () => {
+ if (!pollTimer) return;
+ setLive(!document.hidden);
+ });
+
+ function renderIdentity(card, rep, asset, network, history = []) {
const id = card?.identity || {};
const name = card?.name || '(unindexed agent)';
const trust = computeTrust(rep);
const lastIndexed = rep?.last_indexed_at
? `indexed ${new Date(rep.last_indexed_at).toLocaleString()}`
: 'never indexed';
+ const sparkSvg = renderSparkline(history);
const vanity = id.vanity_prefix && asset.startsWith(id.vanity_prefix) ? id.vanity_prefix : null;
const shortAddrHtml = vanity
? `<span class="addr-prefix">${escapeHtml(vanity)}</span>${escapeHtml(asset.slice(vanity.length, 4))}…${escapeHtml(asset.slice(-4))}`
@@ -258,6 +318,7 @@
<div style="font-weight:600">Trust grade</div>
<div class="trust-summary">${escapeHtml(trust.summary)}</div>
</div>
+ <div class="spark" title="30-day score history">${sparkSvg}</div>
</div>
</div>`;
$('identity').querySelectorAll('[data-copy]').forEach((b) => {
@@ -327,8 +388,9 @@
if (row.disputed) flags.push(pill('disputed', 'warn'));
if (row.revoked) flags.push(pill('revoked', 'bad'));
if (row.payload?.source?.startsWith?.('pumpkit.')) flags.push(pill(row.payload.source, 'info'));
+ const fresh = cache.freshSigs.has(row.signature) ? ' fresh' : '';
return `
- <div class="att">
+ <div class="att${fresh}">
<div class="kind-${k}"><strong>${escapeHtml(k)}</strong></div>
<div>
<div>${escapeHtml(describe(row))}</div>
@@ -368,6 +430,28 @@
return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' })[c]);
}
+ // SVG sparkline of historical scores (1..5 fixed y-axis).
+ function renderSparkline(series) {
+ if (!series || series.length < 2) {
+ return `<div class="spark-empty">${series?.length ? '1 day' : 'no history'}</div>`;
+ }
+ const W = 120, H = 32, P = 2;
+ const xs = series.map((_, i) => P + (i * (W - 2 * P)) / (series.length - 1));
+ const ys = series.map((d) => {
+ const score = Math.max(1, Math.min(5, d.score || 0));
+ return P + (1 - (score - 1) / 4) * (H - 2 * P);
+ });
+ const path = xs.map((x, i) => `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${ys[i].toFixed(1)}`).join(' ');
+ const lastScore = series[series.length - 1].score;
+ const stroke = lastScore >= 4 ? '#1b5e20' : lastScore >= 3 ? '#855008' : '#c62828';
+ const fillPath = `${path} L${xs[xs.length-1].toFixed(1)},${H - P} L${xs[0].toFixed(1)},${H - P} Z`;
+ return `<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" aria-label="score history">
+ <path d="${fillPath}" fill="${stroke}" opacity=".12" />
+ <path d="${path}" fill="none" stroke="${stroke}" stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round" />
+ <circle cx="${xs[xs.length-1].toFixed(1)}" cy="${ys[ys.length-1].toFixed(1)}" r="2" fill="${stroke}" />
+ </svg>`;
+ }
+
async function copyText(text, btn) {
try {
await navigator.clipboard.writeText(text);
@@ -381,6 +465,14 @@
$('asset').addEventListener('keydown', (e) => { if (e.key === 'Enter') load(); });
$('network').addEventListener('change', () => { if ($('asset').value.trim()) load(); });
$('share').onclick = () => copyText(location.href, $('share'));
+ $('embed').onclick = () => {
+ const asset = $('asset').value.trim();
+ const network = $('network').value;
+ if (!asset || !PUBKEY_RE.test(asset)) return;
+ const src = `${location.origin}/agent-badge.html?asset=${asset}&network=${network}`;
+ const snippet = `<iframe src="${src}" width="320" height="80" style="border:0" loading="lazy"></iframe>`;
+ copyText(snippet, $('embed'));
+ };
$('filters').addEventListener('click', (e) => {
const btn = e.target.closest('.chip');
if (!btn) return;
diff --git a/public/dashboard/agent-pumpfun.html b/public/dashboard/agent-pumpfun.html
new file mode 100644
index 000000000..9b7d4897c
--- /dev/null
+++ b/public/dashboard/agent-pumpfun.html
@@ -0,0 +1,587 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Agent · Pump.fun · Dashboard · three.ws</title>
+ <link rel="icon" href="/favicon.ico" />
+ <style>
+ :root {
+ color-scheme: dark;
+ --accent: #6a5cff;
+ --accent2: #ff5ca8;
+ --ok: #4ade80;
+ --warn: #fbbf24;
+ --err: #f87171;
+ --border: #22222e;
+ --bg: #0b0b10;
+ --panel: #14141c;
+ --panel2: #1a1a24;
+ --muted: #888;
+ }
+ * { box-sizing: border-box; }
+ body {
+ font: 15px/1.55 -apple-system, system-ui, Segoe UI, Roboto, sans-serif;
+ color: #eee;
+ margin: 0;
+ background: var(--bg);
+ min-height: 100vh;
+ }
+ a { color: #9a8cff; text-decoration: none; }
+ a:hover { text-decoration: underline; }
+ header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 16px 24px;
+ border-bottom: 1px solid var(--border);
+ position: sticky;
+ top: 0;
+ background: var(--bg);
+ z-index: 5;
+ }
+ .brand { font-weight: 600; letter-spacing: -0.01em; }
+ main { padding: 28px; max-width: 980px; margin: 0 auto; }
+ h1 { font-size: 22px; margin: 0 0 6px; letter-spacing: -0.01em; }
+ .sub { color: var(--muted); margin: 0 0 22px; font-size: 14px; }
+ .panel {
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 14px;
+ padding: 18px 20px;
+ margin: 0 0 18px;
+ }
+ .panel h2 {
+ margin: 0 0 12px;
+ font-size: 15px;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ color: #ddd;
+ text-transform: uppercase;
+ }
+ .row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
+ .col { display: flex; flex-direction: column; gap: 10px; }
+ label { display: block; font-size: 12px; color: var(--muted); margin-bottom: 4px; }
+ input, select {
+ background: var(--panel2);
+ color: #eee;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 9px 11px;
+ font: inherit;
+ min-width: 0;
+ }
+ input:focus, select:focus { outline: none; border-color: var(--accent); }
+ .field { flex: 1 1 180px; min-width: 0; }
+ .btn {
+ padding: 9px 14px;
+ border-radius: 9px;
+ border: 0;
+ font: inherit;
+ font-weight: 600;
+ cursor: pointer;
+ background: var(--accent);
+ color: #fff;
+ }
+ .btn:hover { filter: brightness(1.1); }
+ .btn:disabled { opacity: 0.45; cursor: not-allowed; }
+ .btn.ghost { background: transparent; border: 1px solid var(--border); color: #ddd; }
+ .btn.danger { background: #3a1d22; color: var(--err); border: 1px solid #4a2329; }
+ .kv { display: grid; grid-template-columns: 140px 1fr; gap: 6px 14px; font-size: 13px; }
+ .kv dt { color: var(--muted); }
+ .kv dd { margin: 0; word-break: break-all; font-family: ui-monospace, Menlo, monospace; }
+ pre {
+ background: var(--panel2);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 10px 12px;
+ overflow-x: auto;
+ font-size: 12px;
+ color: #cbd5e1;
+ white-space: pre-wrap;
+ word-break: break-all;
+ }
+ .toast {
+ position: fixed;
+ right: 22px;
+ bottom: 22px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ padding: 11px 14px;
+ font-size: 13px;
+ max-width: 400px;
+ box-shadow: 0 6px 24px rgba(0, 0, 0, 0.5);
+ opacity: 0;
+ transform: translateY(8px);
+ transition: opacity 0.18s, transform 0.18s;
+ pointer-events: none;
+ }
+ .toast.show { opacity: 1; transform: none; }
+ .toast.ok { border-color: #1f4232; }
+ .toast.err { border-color: #4a2329; color: var(--err); }
+ table { width: 100%; border-collapse: collapse; font-size: 13px; }
+ th, td { padding: 8px 10px; border-bottom: 1px solid var(--border); text-align: left; }
+ th { color: var(--muted); font-weight: 500; font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
+ td.mono { font-family: ui-monospace, Menlo, monospace; font-size: 12px; }
+ .pnl-pos { color: var(--ok); }
+ .pnl-neg { color: var(--err); }
+ .muted { color: var(--muted); }
+ .tag { font-size: 11px; padding: 2px 7px; border-radius: 999px; background: var(--panel2); border: 1px solid var(--border); }
+ .tag.devnet { color: var(--warn); border-color: #4a3a18; }
+ </style>
+ </head>
+ <body>
+ <header>
+ <div class="row">
+ <a class="brand" href="/dashboard">← Dashboard</a>
+ <span class="muted">/</span>
+ <span class="brand">Agent · Pump.fun</span>
+ </div>
+ <div class="row">
+ <a href="/dashboard/wallets">Wallets</a>
+ <a href="/discover">Discover</a>
+ </div>
+ </header>
+
+ <main>
+ <h1>Agent control panel</h1>
+ <p class="sub">
+ Each agent has its own Solana wallet. Launch tokens, trade on the bonding curve, and watch
+ positions — the agent signs every transaction from its server-held keypair (subject to
+ its spend policy).
+ </p>
+
+ <section class="panel" id="agent-panel">
+ <h2>Agent</h2>
+ <div class="row">
+ <div class="field">
+ <label for="agent-select">Identity</label>
+ <select id="agent-select"></select>
+ </div>
+ <div class="field" style="flex: 0 0 160px">
+ <label for="network-select">Network</label>
+ <select id="network-select">
+ <option value="mainnet">mainnet</option>
+ <option value="devnet">devnet</option>
+ </select>
+ </div>
+ <div style="flex: 0 0 auto; padding-top: 19px">
+ <button class="btn ghost" id="refresh-btn">Refresh</button>
+ </div>
+ </div>
+ <div style="margin-top: 14px">
+ <dl class="kv">
+ <dt>Address</dt>
+ <dd id="agent-address" class="muted">—</dd>
+ <dt>Balance</dt>
+ <dd id="agent-balance" class="muted">—</dd>
+ </dl>
+ <div class="row" style="margin-top: 10px">
+ <button class="btn ghost" id="provision-btn" hidden>Provision Solana wallet</button>
+ <a id="explorer-link" class="muted" href="#" target="_blank" rel="noopener" hidden>Open on Solscan ↗</a>
+ </div>
+ </div>
+ </section>
+
+ <section class="panel">
+ <h2>Launch a pump.fun token</h2>
+ <div class="row">
+ <div class="field">
+ <label for="launch-name">Name</label>
+ <input id="launch-name" placeholder="My Agent Coin" />
+ </div>
+ <div class="field" style="flex: 0 0 160px">
+ <label for="launch-symbol">Symbol</label>
+ <input id="launch-symbol" placeholder="AGENT" maxlength="10" />
+ </div>
+ <div class="field" style="flex: 0 0 140px">
+ <label for="launch-vanity">Vanity prefix</label>
+ <input id="launch-vanity" placeholder="PUMP" maxlength="6" />
+ </div>
+ <div class="field" style="flex: 0 0 140px">
+ <label for="launch-sol">Initial buy (SOL)</label>
+ <input id="launch-sol" type="number" min="0" step="0.001" placeholder="0" />
+ </div>
+ </div>
+ <div class="row" style="margin-top: 10px">
+ <div class="field">
+ <label for="launch-uri">Metadata URI <span class="muted">(auto-filled to agent metadata)</span></label>
+ <input id="launch-uri" />
+ </div>
+ <div style="flex: 0 0 auto; padding-top: 19px">
+ <button class="btn" id="launch-btn">Launch</button>
+ </div>
+ </div>
+ <p class="muted" style="margin: 10px 0 0; font-size: 12px">
+ Vanity prefix uses base58 (no 0/O/I/l). 4 chars = seconds. 5+ may time out — keep it short for the demo.
+ </p>
+ </section>
+
+ <section class="panel">
+ <h2>Trade on the bonding curve</h2>
+ <div class="row">
+ <div class="field">
+ <label for="trade-mint">Mint</label>
+ <input id="trade-mint" placeholder="Mint address" />
+ </div>
+ <div class="field" style="flex: 0 0 140px">
+ <label for="trade-slippage">Slippage (bps)</label>
+ <input id="trade-slippage" type="number" min="0" max="10000" value="500" />
+ </div>
+ </div>
+ <div class="row" style="margin-top: 10px">
+ <div class="field">
+ <label for="buy-sol">Buy with SOL</label>
+ <input id="buy-sol" type="number" min="0" step="0.001" placeholder="0.05" />
+ </div>
+ <div style="flex: 0 0 auto; padding-top: 19px">
+ <button class="btn" id="buy-btn">Buy</button>
+ </div>
+ <div class="field">
+ <label for="sell-tokens">Sell tokens (base units)</label>
+ <input id="sell-tokens" placeholder="1000000000" />
+ </div>
+ <div style="flex: 0 0 auto; padding-top: 19px">
+ <button class="btn ghost" id="sell-btn">Sell</button>
+ </div>
+ </div>
+ </section>
+
+ <section class="panel">
+ <div class="row" style="justify-content: space-between">
+ <h2 style="margin: 0">Portfolio</h2>
+ <button class="btn ghost" id="portfolio-btn">Refresh portfolio</button>
+ </div>
+ <div id="portfolio-totals" class="muted" style="margin: 10px 0; font-size: 13px">—</div>
+ <div id="portfolio-table-wrap"><table id="portfolio-table"><thead><tr>
+ <th>Mint</th><th>SOL in</th><th>SOL out</th><th>Token bal</th><th>Est. value (SOL)</th><th>Unrealized PnL</th><th></th>
+ </tr></thead><tbody><tr><td colspan="7" class="muted">No positions yet.</td></tr></tbody></table></div>
+ </section>
+
+ <section class="panel">
+ <h2>Last response</h2>
+ <pre id="log">—</pre>
+ </section>
+ </main>
+
+ <div class="toast" id="toast"></div>
+
+ <script type="module">
+ const $ = (sel) => document.querySelector(sel);
+ const els = {
+ agentSelect: $('#agent-select'),
+ networkSelect: $('#network-select'),
+ refreshBtn: $('#refresh-btn'),
+ provisionBtn: $('#provision-btn'),
+ agentAddress: $('#agent-address'),
+ agentBalance: $('#agent-balance'),
+ explorerLink: $('#explorer-link'),
+ launchName: $('#launch-name'),
+ launchSymbol: $('#launch-symbol'),
+ launchVanity: $('#launch-vanity'),
+ launchSol: $('#launch-sol'),
+ launchUri: $('#launch-uri'),
+ launchBtn: $('#launch-btn'),
+ tradeMint: $('#trade-mint'),
+ tradeSlippage: $('#trade-slippage'),
+ buySol: $('#buy-sol'),
+ buyBtn: $('#buy-btn'),
+ sellTokens: $('#sell-tokens'),
+ sellBtn: $('#sell-btn'),
+ portfolioBtn: $('#portfolio-btn'),
+ portfolioTotals: $('#portfolio-totals'),
+ portfolioTable: $('#portfolio-table tbody'),
+ log: $('#log'),
+ toast: $('#toast'),
+ };
+
+ let toastTimer;
+ function toast(msg, kind = 'ok') {
+ els.toast.textContent = msg;
+ els.toast.className = `toast show ${kind}`;
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => (els.toast.className = 'toast'), 3500);
+ }
+
+ function logResponse(label, body) {
+ els.log.textContent = `[${label}]\n` + JSON.stringify(body, null, 2);
+ }
+
+ function explorerTxUrl(sig, network) {
+ return `https://solscan.io/tx/${sig}${network === 'devnet' ? '?cluster=devnet' : ''}`;
+ }
+
+ function explorerAddrUrl(addr, network) {
+ return `https://solscan.io/account/${addr}${network === 'devnet' ? '?cluster=devnet' : ''}`;
+ }
+
+ async function api(path, opts = {}) {
+ const res = await fetch(path, {
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ ...opts,
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ const code = body.error || res.status;
+ const msg = body.error_description || res.statusText;
+ throw Object.assign(new Error(`${code}: ${msg}`), { body });
+ }
+ return body;
+ }
+
+ function currentAgentId() {
+ return els.agentSelect.value || '';
+ }
+ function currentNetwork() {
+ return els.networkSelect.value;
+ }
+
+ async function loadAgents() {
+ try {
+ const { agents = [] } = await api('/api/agents');
+ els.agentSelect.innerHTML = '';
+ if (!agents.length) {
+ const opt = document.createElement('option');
+ opt.textContent = 'No agents — create one in the dashboard';
+ opt.disabled = true;
+ els.agentSelect.appendChild(opt);
+ return;
+ }
+ for (const a of agents) {
+ const opt = document.createElement('option');
+ opt.value = a.id;
+ opt.textContent = `${a.name || 'Untitled'} · ${a.id.slice(0, 8)}`;
+ els.agentSelect.appendChild(opt);
+ }
+ } catch (err) {
+ toast(err.message, 'err');
+ }
+ }
+
+ async function refreshAgent() {
+ const id = currentAgentId();
+ if (!id) return;
+ const network = currentNetwork();
+ const origin = window.location.origin;
+ els.launchUri.value = `${origin}/api/agents/pumpfun-metadata?id=${encodeURIComponent(id)}`;
+ els.agentAddress.textContent = '…';
+ els.agentBalance.textContent = '…';
+ els.explorerLink.hidden = true;
+ els.provisionBtn.hidden = true;
+ try {
+ const { data } = await api(`/api/agents/${id}/solana?network=${network}`);
+ els.agentAddress.textContent = data.address;
+ els.agentAddress.classList.remove('muted');
+ els.agentBalance.textContent = data.sol == null ? 'unknown' : `${data.sol.toFixed(6)} SOL`;
+ els.agentBalance.classList.remove('muted');
+ els.explorerLink.href = explorerAddrUrl(data.address, network);
+ els.explorerLink.hidden = false;
+ } catch (err) {
+ if (err.body?.error === 'not_found') {
+ els.agentAddress.textContent = 'No Solana wallet yet';
+ els.provisionBtn.hidden = false;
+ } else {
+ els.agentAddress.textContent = err.message;
+ }
+ }
+ }
+
+ async function provision() {
+ const id = currentAgentId();
+ if (!id) return;
+ try {
+ await api(`/api/agents/${id}/solana`, { method: 'POST' });
+ toast('Wallet provisioned');
+ await refreshAgent();
+ } catch (err) {
+ toast(err.message, 'err');
+ }
+ }
+
+ async function launchToken() {
+ const id = currentAgentId();
+ if (!id) return;
+ const body = {
+ name: els.launchName.value.trim(),
+ symbol: els.launchSymbol.value.trim().toUpperCase(),
+ uri: els.launchUri.value.trim(),
+ network: currentNetwork(),
+ };
+ if (!body.name || !body.symbol || !body.uri) {
+ toast('Name, symbol, and metadata URI are required', 'err');
+ return;
+ }
+ const vanity = els.launchVanity.value.trim();
+ if (vanity) body.vanityPrefix = vanity;
+ const sol = parseFloat(els.launchSol.value);
+ if (sol > 0) body.solAmount = sol;
+ els.launchBtn.disabled = true;
+ els.launchBtn.textContent = vanity ? 'Grinding & launching…' : 'Launching…';
+ try {
+ const { data } = await api(`/api/agents/${id}/pumpfun/launch`, {
+ method: 'POST',
+ body: JSON.stringify(body),
+ });
+ logResponse('launch', data);
+ toast(`Launched ${data.mint.slice(0, 8)}… (${data.vanity_iterations} attempts)`);
+ els.tradeMint.value = data.mint;
+ await refreshAgent();
+ await refreshPortfolio();
+ } catch (err) {
+ logResponse('launch error', err.body || { error: err.message });
+ toast(err.message, 'err');
+ } finally {
+ els.launchBtn.disabled = false;
+ els.launchBtn.textContent = 'Launch';
+ }
+ }
+
+ async function buy() {
+ const id = currentAgentId();
+ const mint = els.tradeMint.value.trim();
+ const solAmount = parseFloat(els.buySol.value);
+ if (!id || !mint || !solAmount) {
+ toast('Mint and SOL amount required', 'err');
+ return;
+ }
+ els.buyBtn.disabled = true;
+ try {
+ const { data } = await api(`/api/agents/${id}/pumpfun/buy`, {
+ method: 'POST',
+ body: JSON.stringify({
+ mint,
+ solAmount,
+ slippageBps: parseInt(els.tradeSlippage.value, 10) || 500,
+ network: currentNetwork(),
+ }),
+ });
+ logResponse('buy', data);
+ toast(`Bought ${solAmount} SOL of ${mint.slice(0, 8)}…`);
+ await refreshAgent();
+ await refreshPortfolio();
+ } catch (err) {
+ logResponse('buy error', err.body || { error: err.message });
+ toast(err.message, 'err');
+ } finally {
+ els.buyBtn.disabled = false;
+ }
+ }
+
+ async function sell() {
+ const id = currentAgentId();
+ const mint = els.tradeMint.value.trim();
+ const tokenAmount = els.sellTokens.value.trim();
+ if (!id || !mint || !tokenAmount) {
+ toast('Mint and token amount required', 'err');
+ return;
+ }
+ els.sellBtn.disabled = true;
+ try {
+ const { data } = await api(`/api/agents/${id}/pumpfun/sell`, {
+ method: 'POST',
+ body: JSON.stringify({
+ mint,
+ tokenAmount,
+ slippageBps: parseInt(els.tradeSlippage.value, 10) || 500,
+ network: currentNetwork(),
+ }),
+ });
+ logResponse('sell', data);
+ toast(`Sold ${tokenAmount} of ${mint.slice(0, 8)}…`);
+ await refreshAgent();
+ await refreshPortfolio();
+ } catch (err) {
+ logResponse('sell error', err.body || { error: err.message });
+ toast(err.message, 'err');
+ } finally {
+ els.sellBtn.disabled = false;
+ }
+ }
+
+ function pnlClass(n) {
+ if (n == null) return 'muted';
+ if (n > 0.000001) return 'pnl-pos';
+ if (n < -0.000001) return 'pnl-neg';
+ return '';
+ }
+ function fmtSol(n) {
+ if (n == null || Number.isNaN(n)) return '—';
+ return Number(n).toFixed(6);
+ }
+
+ async function refreshPortfolio() {
+ const id = currentAgentId();
+ if (!id) return;
+ const network = currentNetwork();
+ try {
+ const { data } = await api(`/api/agents/${id}/pumpfun/portfolio?network=${network}`);
+ logResponse('portfolio', data);
+ const t = data.totals || {};
+ els.portfolioTotals.innerHTML =
+ `SOL in: <b>${fmtSol(t.sol_in)}</b> · SOL out: <b>${fmtSol(t.sol_out)}</b> · ` +
+ `Est. value: <b>${fmtSol(t.estimated_value_sol)}</b> · Unrealized: ` +
+ `<b class="${pnlClass(t.unrealized_pnl_sol)}">${fmtSol(t.unrealized_pnl_sol)}</b>`;
+
+ const tbody = els.portfolioTable;
+ if (!data.positions.length) {
+ tbody.innerHTML = '<tr><td colspan="7" class="muted">No positions yet.</td></tr>';
+ return;
+ }
+ tbody.innerHTML = '';
+ for (const p of data.positions) {
+ const tr = document.createElement('tr');
+ const grad = p.graduated ? ' <span class="tag">graduated</span>' : '';
+ const err = p.error ? ` <span class="tag" style="color:var(--err)">${p.error}</span>` : '';
+ tr.innerHTML =
+ `<td class="mono"><a href="https://pump.fun/${p.mint}" target="_blank" rel="noopener">${p.mint.slice(0, 12)}…</a>${grad}${err}</td>` +
+ `<td>${fmtSol(p.sol_in)}</td>` +
+ `<td>${fmtSol(p.sol_out)}</td>` +
+ `<td class="mono">${p.token_balance}</td>` +
+ `<td>${fmtSol(p.estimated_sol_value)}</td>` +
+ `<td class="${pnlClass(p.unrealized_pnl_sol)}">${fmtSol(p.unrealized_pnl_sol)}</td>` +
+ `<td><button class="btn ghost" data-mint="${p.mint}" data-action="use">Use</button></td>`;
+ tbody.appendChild(tr);
+ }
+ tbody.querySelectorAll('button[data-action="use"]').forEach((b) => {
+ b.addEventListener('click', () => {
+ els.tradeMint.value = b.dataset.mint;
+ toast('Mint copied to trade panel');
+ });
+ });
+ } catch (err) {
+ els.portfolioTotals.textContent = err.message;
+ }
+ }
+
+ els.agentSelect.addEventListener('change', async () => {
+ await refreshAgent();
+ await refreshPortfolio();
+ });
+ els.networkSelect.addEventListener('change', async () => {
+ const isDev = currentNetwork() === 'devnet';
+ document.querySelectorAll('.network-tag').forEach((e) => (e.className = `tag${isDev ? ' devnet' : ''}`));
+ await refreshAgent();
+ await refreshPortfolio();
+ });
+ els.refreshBtn.addEventListener('click', () => {
+ refreshAgent();
+ refreshPortfolio();
+ });
+ els.provisionBtn.addEventListener('click', provision);
+ els.launchBtn.addEventListener('click', launchToken);
+ els.buyBtn.addEventListener('click', buy);
+ els.sellBtn.addEventListener('click', sell);
+ els.portfolioBtn.addEventListener('click', refreshPortfolio);
+
+ (async () => {
+ await loadAgents();
+ if (currentAgentId()) {
+ await refreshAgent();
+ await refreshPortfolio();
+ }
+ })();
+ </script>
+ </body>
+</html>
diff --git a/public/pumpfun-demo.html b/public/pumpfun-demo.html
new file mode 100644
index 000000000..056c18ec9
--- /dev/null
+++ b/public/pumpfun-demo.html
@@ -0,0 +1,110 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Pump.fun live feed — three.ws demo</title>
+ <style>
+ :root { color-scheme: dark; }
+ html, body { margin: 0; height: 100%; background: #0a0a0a; color: #f0f0f0;
+ font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; }
+ header { padding: 14px 20px; border-bottom: 1px solid #1f1f1f;
+ display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
+ header h1 { margin: 0; font-size: 16px; font-weight: 600; }
+ header .desc { color: #888; font-size: 13px; }
+ header .ctl { margin-left: auto; display: flex; gap: 8px; align-items: center; }
+ header select, header input[type="text"], header button {
+ background: #161616; color: #f0f0f0; border: 1px solid #2a2a2a;
+ border-radius: 6px; padding: 6px 10px; font-size: 13px; }
+ header button { cursor: pointer; }
+ header button:hover { background: #222; }
+ main { position: relative; height: calc(100% - 56px); }
+ #stage { position: absolute; inset: 0; }
+ .notice { position: absolute; left: 16px; bottom: 16px; max-width: 360px;
+ background: #161616; border: 1px solid #2a2a2a; border-radius: 8px;
+ padding: 10px 12px; font-size: 12px; color: #aaa; z-index: 10; }
+ .notice b { color: #f0f0f0; }
+ a { color: #8b5cf6; }
+ </style>
+</head>
+<body>
+ <header>
+ <h1>✦ Pump.fun Live Feed</h1>
+ <span class="desc">3D agent narrates pump.fun activity in real time.</span>
+ <div class="ctl">
+ <label style="font-size:12px;color:#888">Filter mint
+ <input id="ctl-mint" type="text" placeholder="(any)" size="22" />
+ </label>
+ <select id="ctl-tier" title="Minimum tier for claim cards">
+ <option value="">Tier: any</option>
+ <option value="notable">Notable+</option>
+ <option value="influencer">Influencer+</option>
+ <option value="mega">Mega only</option>
+ </select>
+ <button id="ctl-toggle" type="button">Pause narration</button>
+ </div>
+ </header>
+ <main>
+ <div id="stage">
+ <agent-3d
+ id="pumpfun-agent"
+ model="/avatars/cz.glb"
+ widget="wdgt_demo_pumpfun"
+ kiosk="true"
+ eager
+ style="display:block;width:100%;height:100%;background:#0a0a0a"
+ ></agent-3d>
+ </div>
+ <div class="notice">
+ <b>Heads up:</b> set <code>PUMPFUN_BOT_URL</code> in your env to enable the live feed.
+ Without it the SSE stream returns 503 and no cards stream in. See
+ <a href="/docs/solana-pumpfun.md">solana-pumpfun.md</a>.
+ </div>
+ </main>
+ <script type="module">
+ import './agent-3d/latest/agent-3d.js?demo=pumpfun';
+ </script>
+ <script>
+ // Wire the toolbar to the live-mounted widget overlay.
+ const stage = document.querySelector('main');
+
+ document.getElementById('ctl-mint').addEventListener('input', (e) => {
+ const mint = e.target.value.trim();
+ stage.dispatchEvent(
+ new CustomEvent('pumpfun-feed:focus-mint', {
+ detail: { mint: mint || null },
+ bubbles: true,
+ }),
+ );
+ });
+
+ document.getElementById('ctl-tier').addEventListener('change', (e) => {
+ // Tier filter requires reconnecting the SSE; reload the agent element.
+ const a = document.getElementById('pumpfun-agent');
+ const tier = e.target.value;
+ const url = new URL(location.href);
+ if (tier) url.searchParams.set('minTier', tier);
+ else url.searchParams.delete('minTier');
+ history.replaceState(null, '', url);
+ location.reload();
+ });
+
+ const toggle = document.getElementById('ctl-toggle');
+ let muted = false;
+ toggle.addEventListener('click', () => {
+ muted = !muted;
+ toggle.textContent = muted ? 'Resume narration' : 'Pause narration';
+ // The agent protocol bus is exposed via window.VIEWER.agent_protocol once mounted.
+ const proto = window.VIEWER?.agent_protocol;
+ if (!proto) return;
+ if (muted) {
+ proto._mutedSpeak = (e) => e.stopImmediatePropagation();
+ proto.addEventListener('speak', proto._mutedSpeak, true);
+ } else if (proto._mutedSpeak) {
+ proto.removeEventListener('speak', proto._mutedSpeak, true);
+ proto._mutedSpeak = null;
+ }
+ });
+ </script>
+</body>
+</html>
diff --git a/public/studio/studio.js b/public/studio/studio.js
index a41f73b71..8bfb0c849 100644
--- a/public/studio/studio.js
+++ b/public/studio/studio.js
@@ -61,6 +61,7 @@ const DEMO_WIDGET_IDS = Object.freeze({
'talking-agent': 'wdgt_demo_talking',
passport: 'wdgt_demo_passprt',
'hotspot-tour': 'wdgt_demo_hotspot',
+ 'pumpfun-feed': 'wdgt_demo_pumpfun',
});
const BRAND_DEFAULTS = Object.freeze({
@@ -104,6 +105,7 @@ const TYPE_DEFAULTS = {
rotationSpeed: 0.6,
},
'hotspot-tour': { hotspots: [] },
+ 'pumpfun-feed': { kind: 'all', minTier: '', autoNarrate: true, maxCards: 8 },
};
function defaultConfig(type) {
@@ -318,6 +320,62 @@ function renderTypeFields() {
}),
);
}
+ if (state.type === 'pumpfun-feed') {
+ wrap.appendChild(
+ selectField('kind', 'Event kind', state.config.kind ?? 'all', [
+ ['all', 'All events'],
+ ['claims', 'Claims only'],
+ ['graduations', 'Graduations only'],
+ ]),
+ );
+ wrap.appendChild(
+ selectField('minTier', 'Minimum tier (claims)', state.config.minTier ?? '', [
+ ['', 'Any'],
+ ['notable', 'Notable+'],
+ ['influencer', 'Influencer+'],
+ ['mega', 'Mega only'],
+ ]),
+ );
+ wrap.appendChild(
+ boolField('autoNarrate', 'Avatar narrates events', state.config.autoNarrate !== false),
+ );
+ wrap.appendChild(
+ numberField('maxCards', 'Max cards on screen', state.config.maxCards ?? 8, {
+ min: 1,
+ max: 50,
+ step: 1,
+ }),
+ );
+ }
+}
+
+function selectField(name, label, value, options) {
+ const f = document.createElement('label');
+ f.className = 'field';
+ const opts = options
+ .map(
+ ([v, l]) =>
+ `<option value="${attr(v)}"${v === value ? ' selected' : ''}>${escapeHtml(l)}</option>`,
+ )
+ .join('');
+ f.innerHTML = `<span>${escapeHtml(label)}</span><select name="${attr(name)}">${opts}</select>`;
+ f.querySelector('select').addEventListener('change', (e) => {
+ state.config[name] = e.target.value;
+ schedulePreview();
+ });
+ return f;
+}
+
+function boolField(name, label, checked) {
+ const f = document.createElement('label');
+ f.className = 'field';
+ f.innerHTML = `<input type="checkbox" name="${attr(name)}"${checked ? ' checked' : ''}>
+ <span>${escapeHtml(label)}</span>`;
+ f.querySelector('input').addEventListener('change', (e) => {
+ state.config[name] = e.target.checked;
+ schedulePreview();
+ });
+ return f;
}
function numberField(name, label, value, { min, max, step }) {
diff --git a/src/agent-home-pumpfun.js b/src/agent-home-pumpfun.js
index 221455de4..fd034b963 100644
--- a/src/agent-home-pumpfun.js
+++ b/src/agent-home-pumpfun.js
@@ -46,7 +46,23 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
quote: null,
quoting: false,
signer: 'agent', // 'agent' = server-side agent wallet; 'owner' = browser wallet
+ // vanity launch
+ vanityEnabled: false,
+ vanitySuffix: 'pump',
+ vanityProgress: null,
+ // auto-trader
+ botOpen: false,
+ botMode: 'auto-snipe',
+ botSimulate: true,
+ botDurationSec: 60,
+ botPerTradeSol: 0.05,
+ botCapSol: 0.5,
+ botQuery: '',
+ botWallet: '',
+ botSessionId: `s-${Date.now().toString(36)}`,
+ botRunning: false,
};
+ let botAbort = null;
let refreshTimer = null;
let quoteTimer = null;
let unsubProtocol = null;
@@ -62,6 +78,12 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
<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>
+ <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>
+ <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>` : ''}
<button class="pumpfun-btn pumpfun-btn--primary" id="pf-launch-btn">
Launch ${deriveSymbol(identity.name)}
</button>
@@ -100,8 +122,47 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
<button class="pumpfun-btn ${s.tradeOpen === 'buy' ? 'pumpfun-btn--active' : ''}" data-action="toggle-buy">Buy</button>
<button class="pumpfun-btn ${s.tradeOpen === 'sell' ? 'pumpfun-btn--active' : ''}" data-action="toggle-sell">Sell</button>
<button class="pumpfun-btn pumpfun-btn--ghost" data-action="claim">Claim fees</button>
+ <button class="pumpfun-btn ${s.botOpen ? 'pumpfun-btn--active' : ''}" data-action="toggle-bot">🤖 Auto</button>
</div>
${s.tradeOpen ? tradePanel(s) : ''}
+ ${s.botOpen ? botPanel(s) : ''}
+ </div>
+ `;
+ };
+
+ const botPanel = (s) => {
+ const modes = [
+ ['research-and-buy', 'Research & Buy'],
+ ['auto-snipe', 'Auto-Snipe'],
+ ['copy-trade', 'Copy-Trade'],
+ ['rug-exit-watch', 'Rug Exit'],
+ ];
+ const needsQuery = s.botMode === 'research-and-buy';
+ const needsWallet = s.botMode === 'copy-trade';
+ const isExitWatch = s.botMode === 'rug-exit-watch';
+ return `
+ <div class="pumpfun-trade pumpfun-bot">
+ <div class="pumpfun-bot-modes">
+ ${modes.map(([k, label]) => `<button class="pumpfun-btn ${s.botMode === k ? 'pumpfun-btn--active' : ''}" data-action="bot-mode" data-mode="${k}" ${s.botRunning ? 'disabled' : ''}>${label}</button>`).join('')}
+ </div>
+ ${needsQuery ? `<label class="pumpfun-trade-label"><span>Query</span><input class="pumpfun-trade-input" data-bot-field="query" type="text" placeholder="name, symbol, or mint" value="${escapeAttr(s.botQuery)}" ${s.botRunning ? 'disabled' : ''}></label>` : ''}
+ ${needsWallet ? `<label class="pumpfun-trade-label"><span>Wallet</span><input class="pumpfun-trade-input" data-bot-field="wallet" type="text" placeholder="creator/wallet pubkey" value="${escapeAttr(s.botWallet)}" ${s.botRunning ? 'disabled' : ''}></label>` : ''}
+ <div class="pumpfun-bot-grid">
+ <label class="pumpfun-trade-label"><span>Duration (s)</span><input class="pumpfun-trade-input" data-bot-field="durationSec" type="number" min="10" max="3600" value="${s.botDurationSec}" ${s.botRunning ? 'disabled' : ''}></label>
+ ${isExitWatch ? '' : `<label class="pumpfun-trade-label"><span>Per-trade SOL</span><input class="pumpfun-trade-input" data-bot-field="perTradeSol" type="number" min="0.001" step="0.001" value="${s.botPerTradeSol}" ${s.botRunning ? 'disabled' : ''}></label>`}
+ ${isExitWatch ? '' : `<label class="pumpfun-trade-label"><span>Cap SOL</span><input class="pumpfun-trade-input" data-bot-field="capSol" type="number" min="0.001" step="0.01" value="${s.botCapSol}" ${s.botRunning ? 'disabled' : ''}></label>`}
+ </div>
+ <label class="pumpfun-vanity-row">
+ <input type="checkbox" data-bot-field="simulate" ${s.botSimulate ? 'checked' : ''} ${s.botRunning ? 'disabled' : ''}>
+ <span>Simulate (dry-run, no signing)</span>
+ </label>
+ <div class="pumpfun-trade-actions">
+ <button class="pumpfun-btn pumpfun-btn--ghost" data-action="close-bot" ${s.botRunning ? 'disabled' : ''}>Close</button>
+ ${s.botRunning
+ ? `<button class="pumpfun-btn pumpfun-btn--primary" data-action="bot-stop">Stop</button>`
+ : `<button class="pumpfun-btn pumpfun-btn--primary" data-action="bot-run">${s.botSimulate ? 'Run dry-run' : 'Run live'}</button>`}
+ </div>
+ ${s.botRunning ? `<div class="pumpfun-quote"><span class="pumpfun-quote-status">Running ${escapeHtml(s.botMode)} (session ${escapeHtml(s.botSessionId)})…</span></div>` : ''}
</div>
`;
};
diff --git a/src/agent-home.js b/src/agent-home.js
index 5e97afbba..40e4a4f01 100644
--- a/src/agent-home.js
+++ b/src/agent-home.js
@@ -40,11 +40,13 @@ export class AgentHome {
* @param {import('./agent-protocol.js').AgentProtocol} protocol
* @param {import('./agent-avatar.js').AgentAvatar} [avatar]
*/
- constructor(containerEl, identity, protocol, avatar = null) {
+ constructor(containerEl, identity, protocol, avatar = null, opts = {}) {
this.container = containerEl;
this.identity = identity;
this.protocol = protocol;
this.avatar = avatar;
+ this.skills = opts.skills || null;
+ this.memory = opts.memory || null;
this._panel = null;
this._timeline = [];
@@ -166,11 +168,22 @@ export class AgentHome {
// Pump.fun card — only meaningful for Solana-registered agents.
if (this.identity?.meta?.chain_type === 'solana' || this.identity?.solana_address) {
try {
+ const skills =
+ this.skills ||
+ (typeof window !== 'undefined'
+ ? window.VIEWER?.agent_skills || window.VIEWER?.app?.agent_skills
+ : null);
+ const memory =
+ this.memory ||
+ (typeof window !== 'undefined'
+ ? window.VIEWER?.agent_memory || window.VIEWER?.app?.agent_memory
+ : null);
mountPumpFunCard({
panel,
identity: this.identity,
- skills: this.skills || (typeof window !== 'undefined' ? window.VIEWER?.agent_skills : null),
- memory: this.memory,
+ skills,
+ memory,
+ protocol: this.protocol,
});
} catch {
/* card is optional */
diff --git a/src/agent-skills-pumpfun-compose.js b/src/agent-skills-pumpfun-compose.js
index 5ffeb2cb1..f403486e7 100644
--- a/src/agent-skills-pumpfun-compose.js
+++ b/src/agent-skills-pumpfun-compose.js
@@ -326,7 +326,7 @@ export function registerPumpFunComposeSkills(skills) {
const devSellLimit = cfg(ctx, 'exitOnDevSellPct');
const state = await loadState(ctx?.memory, sessionId, { exited: new Set(), log: [] });
- while (Date.now() < deadline && state.exited.size < args.mints.length) {
+ while (!args.signal?.aborted && Date.now() < deadline && state.exited.size < args.mints.length) {
for (const mint of args.mints) {
if (state.exited.has(mint)) continue;
const [holders, trades, details] = await Promise.all([
diff --git a/src/app.js b/src/app.js
index 5ee449118..0a5fb1188 100644
--- a/src/app.js
+++ b/src/app.js
@@ -428,7 +428,10 @@ class App {
if (homeEl) {
if (this.agentHome) this.agentHome.destroy();
homeEl.innerHTML = '';
- this.agentHome = new AgentHome(homeEl, this.identity, protocol, this.avatar);
+ this.agentHome = new AgentHome(homeEl, this.identity, protocol, this.avatar, {
+ skills: this.agent_skills || window.VIEWER?.agent_skills,
+ memory: this.agent_memory || window.VIEWER?.agent_memory,
+ });
await this.agentHome.render();
}
diff --git a/src/element.js b/src/element.js
index 5651767e3..bfde4ad4a 100644
--- a/src/element.js
+++ b/src/element.js
@@ -146,8 +146,43 @@ const BASE_STYLE = `
backdrop-filter: blur(12px);
}
.chat:empty { display: none; }
- .msg { margin: 4px 0; }
+ .msg { margin: 6px 0; padding: 8px 10px; border-radius: 10px; border-left: 3px solid transparent; transition: border-color .2s; }
+ .msg.celebration { border-left-color: rgba(34,197,94,0.85); background: rgba(34,197,94,0.06); }
+ .msg.concern { border-left-color: rgba(239,68,68,0.85); background: rgba(239,68,68,0.06); }
+ .msg.curiosity { border-left-color: rgba(59,130,246,0.7); background: rgba(59,130,246,0.05); }
.msg .role { opacity: 0.55; font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; }
+ .msg .body { white-space: pre-wrap; }
+ /* Suggestion chips when the conversation is empty */
+ .suggest-row { display: flex; flex-wrap: wrap; gap: 6px; padding: 8px 0 0; }
+ .suggest-chip { font: 600 11px/1 var(--agent-chat-font); color: var(--agent-on-surface); background: rgba(255,255,255,.06); border: 1px solid rgba(255,255,255,.1); padding: 6px 10px; border-radius: 999px; cursor: pointer; transition: all .12s; }
+ .suggest-chip:hover { background: rgba(255,255,255,.12); border-color: rgba(255,255,255,.18); }
+ /* Tool-call indicator near the bottom of the canvas */
+ .tool-indicator { position: absolute; left: 50%; bottom: 96px; transform: translateX(-50%); display: none; align-items: center; gap: 8px; padding: 6px 12px; background: var(--agent-surface); color: var(--agent-on-surface); border-radius: 999px; font: 12px var(--agent-chat-font); backdrop-filter: blur(12px); pointer-events: none; opacity: 0; transition: opacity .15s; z-index: 3; }
+ .tool-indicator[data-active="true"] { display: inline-flex; opacity: 1; }
+ .tool-indicator .spin { width: 10px; height: 10px; border-radius: 50%; border: 2px solid rgba(255,255,255,.25); border-top-color: var(--agent-accent); animation: spin .9s linear infinite; }
+ @keyframes spin { to { transform: rotate(360deg); } }
+ /* Sticky alert banner (e.g. rug flag) */
+ .alert-banner { position: absolute; top: 12px; left: 12px; right: 12px; padding: 8px 12px; border-radius: 10px; font: 600 12px/1.4 var(--agent-chat-font); display: none; align-items: center; gap: 8px; backdrop-filter: blur(12px); z-index: 3; }
+ .alert-banner[data-active="true"] { display: flex; }
+ .alert-banner.warn { background: rgba(234,179,8,.15); color: #fde68a; border: 1px solid rgba(234,179,8,.4); }
+ .alert-banner.danger { background: rgba(239,68,68,.18); color: #fecaca; border: 1px solid rgba(239,68,68,.4); }
+ .alert-banner button { background: none; border: 0; color: inherit; font: 600 14px var(--agent-chat-font); cursor: pointer; padding: 0 4px; opacity: .7; }
+ .alert-banner button:hover { opacity: 1; }
+ /* Rich token card unfurl rendered inline in chat */
+ .token-card { margin: 6px 0; padding: 10px 12px; background: rgba(0,0,0,.25); border: 1px solid rgba(255,255,255,.08); border-radius: 10px; font: 12px var(--agent-chat-font); color: var(--agent-on-surface); }
+ .token-card.solana { border-left: 3px solid #c084fc; }
+ .token-card-header { display: flex; align-items: center; gap: 8px; }
+ .token-card-symbol { font: 700 14px var(--agent-chat-font); }
+ .token-card-name { opacity: .7; }
+ .token-card-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 12px; margin-top: 8px; }
+ .token-card-stat { display: flex; flex-direction: column; gap: 2px; }
+ .token-card-stat .label { font: 600 9px/1 var(--agent-chat-font); letter-spacing: .06em; text-transform: uppercase; opacity: .5; }
+ .token-card-stat .value { font: 600 13px var(--agent-chat-font); font-variant-numeric: tabular-nums; }
+ .token-card-bar { margin-top: 8px; height: 6px; background: rgba(255,255,255,.08); border-radius: 999px; overflow: hidden; }
+ .token-card-bar .fill { height: 100%; background: linear-gradient(90deg, #3b82f6, #c084fc); transition: width .4s; }
+ .token-card-bar .fill.danger { background: linear-gradient(90deg, #f59e0b, #ef4444); }
+ .token-card .flags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; }
+ .token-card .flag { font: 600 9px/1 var(--agent-chat-font); letter-spacing: .04em; text-transform: uppercase; padding: 3px 6px; border-radius: 4px; background: rgba(239,68,68,.18); color: #fecaca; border: 1px solid rgba(239,68,68,.32); }
.input-row {
display: flex;
gap: 6px;
@@ -415,7 +450,81 @@ class Agent3DElement extends HTMLElement {
this._chatEl = chat;
this._inputEl = input;
this._micEl = micBtn;
+
+ // Tool-call indicator ("Checking the chain…").
+ const toolInd = document.createElement('div');
+ toolInd.className = 'tool-indicator';
+ toolInd.part = 'tool-indicator';
+ toolInd.innerHTML = '<span class="spin"></span><span class="label">Working…</span>';
+ this.shadowRoot.appendChild(toolInd);
+ this._toolIndicatorEl = toolInd;
+
+ // Sticky alert banner (rug flags etc.).
+ const banner = document.createElement('div');
+ banner.className = 'alert-banner';
+ banner.part = 'alert-banner';
+ banner.innerHTML = '<span class="msg-text"></span><button aria-label="Dismiss">×</button>';
+ banner.querySelector('button').addEventListener('click', () => {
+ banner.dataset.active = 'false';
+ });
+ this.shadowRoot.appendChild(banner);
+ this._alertBannerEl = banner;
+
+ // Suggestion chips visible while the chat is empty.
+ this._renderSuggestions();
+ }
+ }
+
+ _renderSuggestions() {
+ if (!this._chatEl) return;
+ const existing = this._chatEl.querySelector('.suggest-row');
+ if (existing) existing.remove();
+ const row = document.createElement('div');
+ row.className = 'suggest-row';
+ const chips = this._suggestionChips();
+ for (const c of chips) {
+ const btn = document.createElement('button');
+ btn.className = 'suggest-chip';
+ btn.textContent = c.label;
+ btn.addEventListener('click', () => {
+ row.remove();
+ this.say(c.prompt);
+ });
+ row.appendChild(btn);
+ }
+ this._chatEl.appendChild(row);
+ }
+
+ _suggestionChips() {
+ // Tailor the chip set to which skills are installed; fall back to a
+ // generic greeting set otherwise. Skill names come from the manifest,
+ // not the registry, so this works even before runtime boot.
+ const installed = new Set(
+ (this._manifest?.skills || []).map((s) => {
+ if (typeof s === 'string') return s.replace(/\/$/, '').split('/').pop();
+ if (s?.id) return s.id;
+ if (s?.uri) return String(s.uri).replace(/\/$/, '').split('/').pop();
+ return '';
+ }),
+ );
+ const chips = [];
+ if (installed.has('pump-fun')) {
+ chips.push(
+ { label: '🔥 Trending now', prompt: 'What are the trending tokens on pump.fun right now?' },
+ { label: '👑 King of the hill', prompt: "Who's the king of the hill on pump.fun?" },
+ { label: '🆕 New launches', prompt: 'Show me the newest pump.fun launches.' },
+ );
+ }
+ if (installed.has('dca')) {
+ chips.push({ label: '💸 Set up DCA', prompt: 'Help me set up a weekly USDC → WETH DCA.' });
+ }
+ if (chips.length === 0) {
+ chips.push(
+ { label: '👋 Say hi', prompt: 'Hi! Who are you?' },
+ { label: '🎬 Show your animations', prompt: 'What animations can you do?' },
+ );
}
+ return chips.slice(0, 4);
}
_isResponsive() {
diff --git a/src/onchain/payments-buttons.js b/src/onchain/payments-buttons.js
new file mode 100644
index 000000000..22cb55793
--- /dev/null
+++ b/src/onchain/payments-buttons.js
@@ -0,0 +1,256 @@
+/**
+ * Payments UI components.
+ *
+ * • EnablePaymentsButton — owner-only. Becomes enabled once the agent has a
+ * launched token. One click registers the agent for payments. Then
+ * rehydrates as a "Payments enabled" chip on subsequent renders.
+ *
+ * • PayAgentButton — anyone signed in. Visible only when the agent has
+ * payments configured. Opens an inline modal for amount + currency mint,
+ * then walks the user through their wallet to pay.
+ */
+
+import { getPaymentsAdapter } from './payments/index.js';
+import { isUserRejection } from './adapters/index.js';
+
+const USDC_MAINNET = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const USDC_DEVNET = '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU';
+
+function _esc(s) {
+ return String(s ?? '')
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+// ── Owner-side: enable payments ─────────────────────────────────────────────
+
+export class EnablePaymentsButton {
+ constructor({ agent, container }) {
+ this._agent = agent;
+ this._container = container;
+ this._adapter = getPaymentsAdapter('pumpfun');
+ this._root = null;
+ }
+
+ mount() {
+ this._root = document.createElement('div');
+ this._root.className = 'enable-payments-root';
+ this._container.appendChild(this._root);
+ this._render();
+ }
+
+ unmount() {
+ this._root?.remove();
+ this._root = null;
+ }
+
+ _render() {
+ if (!this._root) return;
+ const payments = this._agent.payments || this._agent.meta?.payments;
+ if (payments?.configured) return this._renderChip(payments);
+
+ if (!(this._agent.token?.mint || this._agent.meta?.token?.mint)) {
+ return this._renderDisabled('Launch the agent token before enabling payments.');
+ }
+
+ this._renderEnableButton();
+ }
+
+ _renderEnableButton() {
+ this._root.innerHTML = `
+ <button class="enable-payments-btn" title="Register this agent to accept payments">
+ &#x1F4B3; Enable payments
+ </button>
+ `;
+ this._root.querySelector('.enable-payments-btn').addEventListener('click', () => this._enable());
+ }
+
+ _renderDisabled(reason) {
+ this._root.innerHTML = `
+ <button class="enable-payments-btn enable-payments-btn--disabled" disabled title="${_esc(reason)}">
+ &#x1F4B3; Enable payments
+ </button>
+ <span class="enable-payments-tooltip">${_esc(reason)}</span>
+ `;
+ }
+
+ _renderChip(_payments) {
+ this._root.innerHTML = `
+ <span class="enable-payments-chip">
+ &#x2705; Payments enabled
+ </span>
+ `;
+ }
+
+ _renderProgress(step) {
+ const labels = {
+ connect: 'Connecting wallet…',
+ prep: 'Preparing…',
+ sign: 'Sign in your wallet…',
+ submit: 'Submitting…',
+ confirm: 'Saving…',
+ };
+ this._root.innerHTML = `
+ <div class="enable-payments-progress" role="status" aria-live="polite">
+ ${_esc(labels[step] || step)}
+ </div>
+ `;
+ }
+
+ _renderError(msg) {
+ this._root.innerHTML = `
+ <div class="enable-payments-error" role="alert">
+ <span>${_esc(msg)}</span>
+ <button class="enable-payments-retry">Try again</button>
+ </div>
+ `;
+ this._root.querySelector('.enable-payments-retry').addEventListener('click', () => this._render());
+ }
+
+ async _enable() {
+ try {
+ const result = await this._adapter.enableForAgent({
+ agent: this._agent,
+ onProgress: (step) => this._renderProgress(step),
+ });
+ this._agent.payments = result.payments;
+ this._renderChip(result.payments);
+ } catch (err) {
+ if (isUserRejection(err)) return this._render();
+ this._renderError(err.message || 'Could not enable payments.');
+ }
+ }
+}
+
+// ── Payer-side: pay an agent ────────────────────────────────────────────────
+
+export class PayAgentButton {
+ constructor({ agent, container }) {
+ this._agent = agent;
+ this._container = container;
+ this._adapter = getPaymentsAdapter('pumpfun');
+ this._root = null;
+ }
+
+ mount() {
+ this._root = document.createElement('div');
+ this._root.className = 'pay-agent-root';
+ this._container.appendChild(this._root);
+ this._render();
+ }
+
+ unmount() {
+ this._root?.remove();
+ this._root = null;
+ }
+
+ _render() {
+ if (!this._root) return;
+ const payments = this._agent.payments || this._agent.meta?.payments;
+ if (!payments?.configured) {
+ this._root.innerHTML = '';
+ return;
+ }
+ this._root.innerHTML = `
+ <button class="pay-agent-btn" title="Pay this agent">
+ &#x1F4B0; Pay agent
+ </button>
+ `;
+ this._root.querySelector('.pay-agent-btn').addEventListener('click', () => this._openModal());
+ }
+
+ _renderProgress(step) {
+ const labels = {
+ connect: 'Connecting wallet…',
+ prep: 'Building payment…',
+ sign: 'Sign in your wallet…',
+ submit: 'Submitting payment…',
+ confirm: 'Verifying…',
+ };
+ this._root.innerHTML = `
+ <div class="pay-agent-progress" role="status" aria-live="polite">
+ ${_esc(labels[step] || step)}
+ </div>
+ `;
+ }
+
+ _renderSuccess(intent) {
+ this._root.innerHTML = `
+ <span class="pay-agent-success">&#x2705; Paid &middot; <a href="https://solscan.io/tx/${_esc(intent.txSignature)}" target="_blank" rel="noopener noreferrer">view tx</a></span>
+ `;
+ }
+
+ _renderError(msg) {
+ this._root.innerHTML = `
+ <div class="pay-agent-error" role="alert">
+ <span>${_esc(msg)}</span>
+ <button class="pay-agent-retry">Try again</button>
+ </div>
+ `;
+ this._root.querySelector('.pay-agent-retry').addEventListener('click', () => this._render());
+ }
+
+ _openModal() {
+ const cluster =
+ this._agent.payments?.cluster || this._agent.meta?.payments?.cluster || 'mainnet';
+ const defaultUsdc = cluster === 'devnet' ? USDC_DEVNET : USDC_MAINNET;
+
+ const overlay = document.createElement('div');
+ overlay.className = 'pay-agent-modal-overlay';
+ overlay.innerHTML = `
+ <div class="pay-agent-modal" role="dialog" aria-label="Pay agent">
+ <h3>Pay ${_esc(this._agent.name || 'agent')}</h3>
+ <p>Send a payment to this agent's Pump.fun payment account. The agent will be able to acknowledge and use the funds.</p>
+ <form class="pay-agent-form">
+ <label>Currency mint
+ <input name="currency_mint" required value="${_esc(defaultUsdc)}" />
+ <small>Default: USDC ${_esc(cluster)}</small>
+ </label>
+ <label>Amount (raw token units)
+ <input name="amount" type="text" required pattern="[0-9]+" value="1000000" />
+ <small>1 USDC = 1000000 (6 decimals)</small>
+ </label>
+ <div class="pay-agent-modal-actions">
+ <button type="button" class="pay-agent-cancel">Cancel</button>
+ <button type="submit" class="pay-agent-submit">Pay</button>
+ </div>
+ </form>
+ </div>
+ `;
+ document.body.appendChild(overlay);
+
+ const close = () => overlay.remove();
+ overlay.querySelector('.pay-agent-cancel').addEventListener('click', close);
+ overlay.addEventListener('click', (e) => {
+ if (e.target === overlay) close();
+ });
+
+ overlay.querySelector('.pay-agent-form').addEventListener('submit', async (ev) => {
+ ev.preventDefault();
+ const fd = new FormData(ev.target);
+ const params = {
+ currencyMint: String(fd.get('currency_mint') || '').trim(),
+ amount: String(fd.get('amount') || '').trim(),
+ };
+ close();
+ await this._pay(params);
+ });
+ }
+
+ async _pay({ currencyMint, amount }) {
+ try {
+ const result = await this._adapter.payAgent({
+ agent: this._agent,
+ currencyMint,
+ amount,
+ onProgress: (step) => this._renderProgress(step),
+ });
+ this._renderSuccess(result);
+ } catch (err) {
+ if (isUserRejection(err)) return this._render();
+ this._renderError(err.message || 'Payment failed.');
+ }
+ }
+}
diff --git a/tests/src/onchain-payments.test.js b/tests/src/onchain-payments.test.js
new file mode 100644
index 000000000..a330cae67
--- /dev/null
+++ b/tests/src/onchain-payments.test.js
@@ -0,0 +1,43 @@
+/**
+ * Pure-logic smoke tests for the payments adapter facade.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ getPaymentsAdapter,
+ _resetPaymentsAdapters,
+} from '../../src/onchain/payments/index.js';
+
+describe('PaymentsAdapter factory', () => {
+ it('returns and caches the pumpfun adapter', () => {
+ _resetPaymentsAdapters();
+ const a = getPaymentsAdapter('pumpfun');
+ const b = getPaymentsAdapter();
+ expect(a).toBe(b);
+ expect(a.provider).toBe('pumpfun');
+ });
+
+ it('rejects unknown providers', () => {
+ expect(() => getPaymentsAdapter('stripe')).toThrow();
+ });
+});
+
+describe('PumpfunPaymentsAdapter precondition shape', () => {
+ it('enableForAgent rejects when no token launched', async () => {
+ const adapter = getPaymentsAdapter('pumpfun');
+ await expect(adapter.enableForAgent({ agent: { id: 'x' } })).rejects.toMatchObject({
+ code: 'PRECONDITION_FAILED',
+ });
+ });
+
+ it('payAgent rejects when payments not configured', async () => {
+ const adapter = getPaymentsAdapter('pumpfun');
+ await expect(
+ adapter.payAgent({
+ agent: { id: 'x' },
+ currencyMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ amount: '1000000',
+ }),
+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ });
+});