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 buy/sell actions, enhance agent home panel, and implement solana registration prep tests

nirholas5dab61830dc5
diff --git a/api/_lib/migrations/2026-04-29-pump-agent-stats.sql b/api/_lib/migrations/2026-04-29-pump-agent-stats.sql
new file mode 100644
index 000000000..336aa31a8
--- /dev/null
+++ b/api/_lib/migrations/2026-04-29-pump-agent-stats.sql
@@ -0,0 +1,26 @@
+-- Migration: per-agent pump.fun token live stats.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-04-29-pump-agent-stats.sql
+-- Idempotent.
+--
+-- Writers: api/cron/pump-agent-stats.js
+-- Readers: api/agents/solana-card.js, agent-passport.html
+
+begin;
+
+create table if not exists pump_agent_stats (
+ mint_id uuid primary key references pump_agent_mints(id) on delete cascade,
+ network text not null check (network in ('mainnet','devnet')),
+ mint text not null,
+ graduated boolean not null default false,
+ bonding_curve jsonb, -- { real_sol, real_token, virtual_sol, virtual_token, complete, progress_pct }
+ amm jsonb, -- { pool, base_reserve, quote_reserve, lp_supply }
+ last_signature text,
+ last_signature_at timestamptz,
+ recent_tx_count int not null default 0,
+ refreshed_at timestamptz not null default now(),
+ error text
+);
+create index if not exists pump_agent_stats_network on pump_agent_stats(network);
+create index if not exists pump_agent_stats_refreshed on pump_agent_stats(refreshed_at);
+
+commit;
diff --git a/api/agents/[id].js b/api/agents/[id].js
index 38cd7c890..2c71b89a5 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -32,6 +32,8 @@ export default wrap(async function handler(req, res) {
if (sub === 'pumpfun') {
if (action === 'launch') return (await import('./pumpfun/launch.js')).default(req, res, id);
+ if (action === 'buy') return (await import('./pumpfun/buy.js')).default(req, res, id);
+ if (action === 'sell') return (await import('./pumpfun/sell.js')).default(req, res, id);
if (action === 'swap') return (await import('./pumpfun/swap.js')).default(req, res, id);
if (action === 'pay') return (await import('./pumpfun/pay.js')).default(req, res, id);
if (cors(req, res)) return;
diff --git a/api/pump/by-agent.js b/api/pump/by-agent.js
new file mode 100644
index 000000000..a752a26e9
--- /dev/null
+++ b/api/pump/by-agent.js
@@ -0,0 +1,52 @@
+// GET /api/pump/by-agent?agent_id=<uuid>
+// Resolves an agent's pump mint (if launched) for the passport widget.
+
+import { sql } from '../_lib/db.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const agentId = url.searchParams.get('agent_id');
+ if (!agentId) return error(res, 400, 'validation_error', 'agent_id required');
+
+ const [row] = await sql`
+ select id, mint, network, name, symbol, buyback_bps, agent_authority,
+ metadata_uri, sharing_config, created_at
+ from pump_agent_mints
+ where agent_id=${agentId}
+ order by created_at desc limit 1
+ `;
+ if (!row) return json(res, 200, { data: null });
+
+ const [stats] = await sql`
+ select
+ count(*) filter (where status='confirmed')::int as confirmed_payments,
+ count(distinct payer_wallet) filter (where status='confirmed')::int as unique_payers,
+ coalesce(sum(amount_atomics) filter (where status='confirmed'),0)::text as total_atomics,
+ max(confirmed_at) filter (where status='confirmed') as last_payment_at
+ from pump_agent_payments where mint_id=${row.id}
+ `;
+
+ const [burnRow] = await sql`
+ select
+ count(*) filter (where status='confirmed')::int as runs,
+ coalesce(sum(burn_amount) filter (where status='confirmed'),0)::text as total_burned,
+ max(created_at) as last_burn_at
+ from pump_buyback_runs where mint_id=${row.id}
+ `;
+
+ return json(res, 200, {
+ data: {
+ ...row,
+ stats: stats || { confirmed_payments: 0, unique_payers: 0, total_atomics: '0' },
+ burns: burnRow || { runs: 0, total_burned: '0' },
+ },
+ });
+});
diff --git a/docs/solana-pumpfun.md b/docs/solana-pumpfun.md
new file mode 100644
index 000000000..b04aa47dc
--- /dev/null
+++ b/docs/solana-pumpfun.md
@@ -0,0 +1,148 @@
+# Pump.fun integration for Solana agents
+
+This integrates the upstream [`pumpfun-claims-bot`](https://github.com/nirholas/pumpfun-claims-bot) MCP server into the three.ws platform so a Solana agent can:
+
+- Observe live pump.fun activity (GitHub social-fee claims, token graduations)
+- React to events through the existing Empathy Layer (speak, gesture, emote)
+- Expose enriched intel (`getRecentClaims`, `getTokenIntel`, …) via the platform MCP endpoint
+- Feed off-chain trust signals into the Solana reputation score
+- Surface a live cards overlay through a new widget type
+
+This document covers what was added, how it composes with what was already there, and what is intentionally **not** included.
+
+---
+
+## Architecture
+
+```
+ npx pumpfun-claims-bot (Railway / standalone)
+ │ JSON-RPC 2.0 (HTTP MCP)
+ ▼
+ api/_lib/pumpfun-mcp.js (cached client, Upstash)
+ │
+ ┌─────────────────┼─────────────────────────────────┐
+ ▼ ▼ ▼
+ api/agents/pumpfun.js api/agents/pumpfun-feed.js api/cron/pumpfun-signals.js
+ (read-only proxy) (SSE: claims+graduations) (15-min crawler)
+ │ │ │
+ │ │ EventSource │ pumpfun_signals
+ ▼ ▼ ▼
+ src/agent-skills-pumpfun-watch.js solana-reputation.js
+ protocol.emit ──► Empathy Layer (avatar) +
+ solana-card.js (passport block)
+ ▲
+ │
+ src/widgets/pumpfun-feed.js (DOM overlay v1)
+```
+
+---
+
+## What's added
+
+| Surface | Path | Purpose |
+|---|---|---|
+| MCP client | [api/_lib/pumpfun-mcp.js](../api/_lib/pumpfun-mcp.js) | Cached JSON-RPC client to upstream bot |
+| Read API | [api/agents/pumpfun.js](../api/agents/pumpfun.js) | `?op=claims|graduations|token|creator` |
+| SSE feed | [api/agents/pumpfun-feed.js](../api/agents/pumpfun-feed.js) | Live event stream, 90s window, auto-reconnects |
+| Cron crawler | [api/cron/pumpfun-signals.js](../api/cron/pumpfun-signals.js) | 15-min sweep → `pumpfun_signals` |
+| Schema | [api/_lib/schema.sql](../api/_lib/schema.sql) | New `pumpfun_signals` table |
+| Skills | [src/agent-skills-pumpfun-watch.js](../src/agent-skills-pumpfun-watch.js) | 4 skills: recent-claims, token-intel, watch-start, watch-stop |
+| Widget | [src/widgets/pumpfun-feed.js](../src/widgets/pumpfun-feed.js) | DOM overlay v1 |
+| Widget type | [src/widget-types.js](../src/widget-types.js) | `pumpfun-feed` registered |
+| Reputation | [api/agents/solana-reputation.js](../api/agents/solana-reputation.js) | `pumpfun_signals` block in response |
+| Passport | [api/agents/solana-card.js](../api/agents/solana-card.js) | `pumpfun` block on the agent card |
+| Cron schedule | [vercel.json](../vercel.json) | `*/15 * * * *` |
+
+---
+
+## Configuration
+
+```env
+# Upstream pumpfun-claims-bot MCP endpoint. Required to enable the integration.
+PUMPFUN_BOT_URL=https://pumpfun-bot.example.com/mcp
+PUMPFUN_BOT_TOKEN= # optional bearer for upstream auth
+
+# Solana RPCs (also used by attestations crawler + pump-sdk skills)
+SOLANA_RPC_URL= # mainnet (Helius/Triton recommended)
+SOLANA_RPC_URL_DEVNET=
+```
+
+When `PUMPFUN_BOT_URL` is unset, the integration becomes a no-op: endpoints return `503 unavailable`, the cron returns `{ skipped: 'pumpfun bot not configured' }`, and the watch skills return a friendly error. Solana agents that don't use it pay no cost.
+
+---
+
+## Skills
+
+All registered through `registerPumpFunWatchSkills` in [src/agent-skills.js](../src/agent-skills.js).
+
+| Skill | MCP-exposed | Effect |
+|---|---|---|
+| `pumpfun-recent-claims` | ✅ | Returns latest N enriched claims |
+| `pumpfun-token-intel` | ✅ | Returns full intel for a mint |
+| `pumpfun-watch-start` | ❌ (browser-only) | Opens SSE; emits `speak`/`emote`/`gesture` per event |
+| `pumpfun-watch-stop` | ❌ | Closes the stream |
+
+### Reaction map (watch-start)
+
+| Event | Empathy Layer trigger | Speech sentiment |
+|---|---|---|
+| `first_time_claim` | `celebration` 0.9 | +0.7 |
+| `fake_claim` | `concern` 0.7 | -0.5 |
+| `tier ∈ {influencer, mega}` | `curiosity` 0.5 | +0.2 |
+| `graduation` | gesture: `wave` (1.5s) | +0.6 |
+
+These are continuous-blend stimuli, not discrete states — they decay according to the per-second rates in [src/CLAUDE.md](../src/CLAUDE.md#decay-per-second).
+
+---
+
+## Reputation signals
+
+The cron writes typed rows to `pumpfun_signals(wallet, agent_asset, kind, weight, payload, tx_signature)`. `solana-reputation` aggregates them as `pumpfun_signals: { count, weight, by_kind }` in the response.
+
+Default weights:
+
+| Kind | Weight |
+|---|---|
+| `first_claim` | +0.2 |
+| `graduation` | +0.3 |
+| `influencer` | +0.2 |
+| `new_account` | -0.2 |
+| `fake_claim` | -0.6 |
+
+These are **off-chain** signals — flagged as such, not on-chain attestations. `verified=false` semantically. Weighting them into a final composite score is up to consumers; the endpoint exposes the raw aggregates.
+
+---
+
+## Widget
+
+The `pumpfun-feed` widget renders a stack of cards (claim or graduation) as an absolutely-positioned overlay on top of the 3D viewer. With `autoNarrate: true`, the avatar narrates each event through the protocol bus.
+
+Studio config schema (validated in `widget-types.js`):
+
+```js
+{
+ kind: 'all' | 'claims' | 'graduations',
+ minTier: '' | 'notable' | 'influencer' | 'mega',
+ autoNarrate: true,
+ maxCards: 8, // 1..50
+}
+```
+
+---
+
+## What's intentionally not included
+
+- **Long-lived SSE on Vercel functions** — the feed handler runs a 90s bounded loop and lets the browser auto-reconnect. For higher throughput, deploy the bot itself as a streaming service.
+- **On-chain signal attestations** — signals are off-chain only. Promoting them to SPL Memo attestations signed by a platform key is a future step (see [docs/solana.md](solana.md) "What's intentionally not on Solana yet").
+- **Agent-as-signer** — the watch skills are read-only; they never sign transactions. The existing `pumpfun-create / -buy / -sell` skills cover signing flows.
+- **Anchor program for reputation** — still EVM-only on the on-chain path.
+
+---
+
+## Testing
+
+```bash
+npx vitest run tests/pumpfun-mcp.test.js tests/pumpfun-signals.test.js
+```
+
+The MCP client and cron crawler are unit-tested with mocked `fetch` and `sql`. End-to-end requires a live `PUMPFUN_BOT_URL` and is exercised via the Solana smoke test path.
diff --git a/examples/skills/pump-fun-strategy/dsl.js b/examples/skills/pump-fun-strategy/dsl.js
new file mode 100644
index 000000000..02a156f87
--- /dev/null
+++ b/examples/skills/pump-fun-strategy/dsl.js
@@ -0,0 +1,111 @@
+// Strategy DSL — pure functions. No I/O, no side effects.
+//
+// A strategy spec describes:
+// scan: where new candidate tokens come from (newTokens | trending | mintList)
+// filters: predicates that must pass before entering a position
+// entry: { side: 'buy', amountSol }
+// exit: array of { if: <predicate>, do: { side: 'sell', percent | amountTokens } }
+//
+// Predicates are tiny strings: "<lhs> <op> <rhs>".
+// lhs paths are dotted, resolved against a `view` object the runner builds:
+// holders.total, holders.topHolderPct, creator.rugCount,
+// curve.graduationPct, position.pnlPct, position.ageSec, etc.
+// ops: > >= < <= == !=
+//
+// Keeping the predicate language deliberately tiny — same evaluator powers
+// live runs and the backtester so they cannot drift.
+
+const OP_RE = /^\s*([\w.]+)\s*(>=|<=|==|!=|>|<)\s*(-?[\d.]+%?)\s*$/;
+
+const OPS = {
+ '>': (a, b) => a > b,
+ '>=': (a, b) => a >= b,
+ '<': (a, b) => a < b,
+ '<=': (a, b) => a <= b,
+ '==': (a, b) => a === b,
+ '!=': (a, b) => a !== b,
+};
+
+export function parsePredicate(src) {
+ const m = OP_RE.exec(src);
+ if (!m) throw new Error(`bad predicate: ${src}`);
+ const [, lhs, op, rhsRaw] = m;
+ const rhs = rhsRaw.endsWith('%') ? Number(rhsRaw.slice(0, -1)) : Number(rhsRaw);
+ if (Number.isNaN(rhs)) throw new Error(`bad rhs in: ${src}`);
+ return { lhs, op, rhs, src };
+}
+
+function get(view, path) {
+ return path.split('.').reduce((o, k) => (o == null ? undefined : o[k]), view);
+}
+
+export function evalPredicate(pred, view) {
+ const left = get(view, pred.lhs);
+ if (left == null || Number.isNaN(left)) return false;
+ const fn = OPS[pred.op];
+ return fn(left, pred.rhs);
+}
+
+export function compileStrategy(spec) {
+ if (!spec || typeof spec !== 'object') throw new Error('strategy must be an object');
+ if (!spec.scan) throw new Error('strategy.scan required');
+ if (!spec.entry) throw new Error('strategy.entry required');
+
+ const filters = (spec.filters ?? []).map(parsePredicate);
+ const exits = (spec.exit ?? []).map((rule) => ({
+ when: parsePredicate(rule.if),
+ action: rule.do,
+ }));
+
+ return {
+ scan: spec.scan, // { kind: 'newTokens'|'trending'|'mintList', limit?, mints? }
+ filters,
+ entry: spec.entry, // { side: 'buy', amountSol }
+ exits,
+ caps: spec.caps ?? {}, // { sessionSpendCapSol, perTradeSol, maxOpenPositions }
+ passes(view) { return filters.every((p) => evalPredicate(p, view)); },
+ shouldExit(view) {
+ for (const e of exits) if (evalPredicate(e.when, view)) return e.action;
+ return null;
+ },
+ };
+}
+
+// Build the `view` object the predicates evaluate against. Pure: takes raw
+// pump-fun-style payloads + (optional) position state.
+export function buildView({ details, holders, creator, curve, position, trades }) {
+ const v = {
+ holders: {
+ total: holders?.total ?? holders?.holders?.length ?? 0,
+ topHolderPct: holders?.topHolderPct ?? holders?.holders?.[0]?.pct ?? 0,
+ },
+ creator: {
+ rugCount: creator?.rugCount ?? creator?.rugFlags?.length ?? 0,
+ },
+ curve: {
+ graduationPct: curve?.graduationPct ?? curve?.progressPct ?? 0,
+ priceSol: curve?.priceSol ?? curve?.price ?? 0,
+ },
+ token: {
+ ageSec: details?.createdAt ? (Date.now() - new Date(details.createdAt).getTime()) / 1000 : 0,
+ marketCapSol: details?.marketCapSol ?? 0,
+ },
+ };
+ if (position) {
+ const entryPrice = position.entryPriceSol ?? 0;
+ const nowPrice = v.curve.priceSol || position.lastPriceSol || entryPrice;
+ v.position = {
+ pnlPct: entryPrice > 0 ? ((nowPrice - entryPrice) / entryPrice) * 100 : 0,
+ ageSec: position.openedAt ? (Date.now() - position.openedAt) / 1000 : 0,
+ amountTokens: position.amountTokens ?? 0,
+ entryPriceSol: entryPrice,
+ };
+ }
+ if (trades) {
+ v.trades = {
+ buyCount: trades.filter((t) => t.side === 'buy').length,
+ sellCount: trades.filter((t) => t.side === 'sell').length,
+ };
+ }
+ return v;
+}
diff --git a/examples/skills/pump-fun-strategy/manifest.json b/examples/skills/pump-fun-strategy/manifest.json
new file mode 100644
index 000000000..1b16a3849
--- /dev/null
+++ b/examples/skills/pump-fun-strategy/manifest.json
@@ -0,0 +1,21 @@
+{
+ "spec": "skill/0.1",
+ "name": "pump-fun-strategy",
+ "version": "0.1.0",
+ "description": "Strategy DSL for pump.fun: declarative spec (scan/filters/entry/exit) compiled into live runs or backtests. Same evaluator powers both — live and backtest cannot drift.",
+ "license": "MIT",
+ "tags": ["solana", "pump.fun", "strategy", "dsl", "backtest"],
+ "requires": {
+ "runtime": ">=0.1.0",
+ "skills": ["pump-fun@^0.1", "pump-fun-trade@^0.1"]
+ },
+ "provides": {
+ "tools": ["validateStrategy", "runStrategy", "backtestStrategy"],
+ "triggers": ["strategy_run", "strategy_backtest"]
+ },
+ "config": {
+ "defaultPollMs": 5000,
+ "defaultSessionSpendCapSol": 1.0,
+ "defaultPerTradeSol": 0.05
+ }
+}
diff --git a/examples/skills/pump-fun-strategy/tools.json b/examples/skills/pump-fun-strategy/tools.json
new file mode 100644
index 000000000..da7c40da7
--- /dev/null
+++ b/examples/skills/pump-fun-strategy/tools.json
@@ -0,0 +1,40 @@
+{
+ "tools": [
+ {
+ "name": "validateStrategy",
+ "description": "Parse and type-check a strategy spec without running it. Returns parsed predicates or the first error.",
+ "input_schema": {
+ "type": "object",
+ "properties": { "strategy": { "type": "object" } },
+ "required": ["strategy"]
+ }
+ },
+ {
+ "name": "runStrategy",
+ "description": "Execute a strategy live. Scans, filters, enters, and watches exits until durationSec or sessionSpendCapSol is hit. Pass simulate:true for a dry-run that skips signing.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "strategy": { "type": "object" },
+ "durationSec": { "type": "integer", "minimum": 10, "maximum": 86400 },
+ "simulate": { "type": "boolean" },
+ "sessionId": { "type": "string" }
+ },
+ "required": ["strategy", "durationSec"]
+ }
+ },
+ {
+ "name": "backtestStrategy",
+ "description": "Replay a strategy against historical token trade history. No signing, no RPC. Returns per-trade PnL and aggregate stats (win rate, total return, max drawdown).",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "strategy": { "type": "object" },
+ "mints": { "type": "array", "items": { "type": "string" }, "description": "Mints to replay; defaults to scan.mints." },
+ "sinceMs": { "type": "integer", "description": "Only consider trades after this unix-ms cutoff." }
+ },
+ "required": ["strategy"]
+ }
+ }
+ ]
+}
diff --git a/src/agent-home-pumpfun.js b/src/agent-home-pumpfun.js
new file mode 100644
index 000000000..62aa01f81
--- /dev/null
+++ b/src/agent-home-pumpfun.js
@@ -0,0 +1,240 @@
+/**
+ * Pump.fun card on the agent home panel
+ * --------------------------------------
+ * Two states:
+ *
+ * 1. Agent has NOT launched a token → "Launch coin" CTA
+ * Triggers pumpfun-self-launch-from-identity (server-signed).
+ *
+ * 2. Agent HAS launched a token → Live status card
+ * Shows mint, market cap, % to graduation, buy/sell links.
+ * Refreshes every 30s by calling pumpfun-watch-curve.
+ *
+ * Detection: we read the agent's memory for the `pumpfun:launch` tag
+ * (written by agent-skills-pumpfun-hooks.js). If absent, we also try
+ * /api/agents/:id (in case the launch happened from a different device
+ * and was persisted to meta.pumpfun_mint).
+ */
+
+const REFRESH_MS = 30_000;
+
+export function mountPumpFunCard({ panel, identity, skills, memory }) {
+ if (!panel || !identity?.id) return null;
+
+ const root = document.createElement('section');
+ root.className = 'agent-home-pumpfun';
+ panel.appendChild(root);
+
+ let state = { mint: null, symbol: null, network: 'mainnet', loading: true };
+ let refreshTimer = null;
+
+ const launchCard = () => `
+ <div class="pumpfun-card pumpfun-card--cta">
+ <div class="pumpfun-card-head">
+ <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>
+ <button class="pumpfun-btn pumpfun-btn--primary" id="pf-launch-btn">
+ Launch ${deriveSymbol(identity.name)}
+ </button>
+ <a class="pumpfun-card-foot" href="https://pump.fun" target="_blank" rel="noopener">What is pump.fun?</a>
+ </div>
+ `;
+
+ const statusCard = (s) => {
+ const pct = s.progressPct != null ? `${s.progressPct.toFixed(1)}%` : '—';
+ const cap = s.marketCap ? formatLamports(s.marketCap) : '—';
+ const explorer = s.network === 'devnet'
+ ? `https://pump.fun/coin/${s.mint}?cluster=devnet`
+ : `https://pump.fun/coin/${s.mint}`;
+ const grad = s.graduated;
+ return `
+ <div class="pumpfun-card ${grad ? 'pumpfun-card--graduated' : ''}">
+ <div class="pumpfun-card-head">
+ <span class="pumpfun-card-icon">${grad ? '🎓' : '◎'}</span>
+ <span class="pumpfun-card-title">${escapeHtml(s.symbol || 'Token')}</span>
+ <a class="pumpfun-card-link" href="${explorer}" target="_blank" rel="noopener" title="View on pump.fun">↗</a>
+ </div>
+ <div class="pumpfun-stats">
+ <div class="pumpfun-stat">
+ <span class="pumpfun-stat-label">Market cap</span>
+ <span class="pumpfun-stat-value">${cap}</span>
+ </div>
+ <div class="pumpfun-stat">
+ <span class="pumpfun-stat-label">${grad ? 'Status' : 'To graduation'}</span>
+ <span class="pumpfun-stat-value">${grad ? 'Graduated' : pct}</span>
+ </div>
+ </div>
+ ${grad ? '' : `<div class="pumpfun-progress"><div class="pumpfun-progress-bar" style="width:${Math.min(100, s.progressPct || 0)}%"></div></div>`}
+ <div class="pumpfun-card-mint" title="${escapeAttr(s.mint)}">${shortMint(s.mint)}</div>
+ <div class="pumpfun-card-actions">
+ <button class="pumpfun-btn" data-action="buy">Buy</button>
+ <button class="pumpfun-btn" data-action="sell">Sell</button>
+ <button class="pumpfun-btn pumpfun-btn--ghost" data-action="claim">Claim fees</button>
+ </div>
+ </div>
+ `;
+ };
+
+ const skeleton = () => `<div class="pumpfun-card pumpfun-card--skeleton"></div>`;
+
+ const render = () => {
+ if (state.loading) {
+ root.innerHTML = skeleton();
+ return;
+ }
+ root.innerHTML = state.mint ? statusCard(state) : launchCard();
+ bind();
+ };
+
+ const bind = () => {
+ const launchBtn = root.querySelector('#pf-launch-btn');
+ if (launchBtn) {
+ launchBtn.addEventListener('click', async () => {
+ launchBtn.disabled = true;
+ launchBtn.textContent = 'Launching…';
+ try {
+ const r = await skills?.perform(
+ 'pumpfun-self-launch-from-identity',
+ { network: state.network },
+ { identity },
+ );
+ if (r?.success && r.data?.mint) {
+ state = { ...state, mint: r.data.mint, symbol: r.data.symbol, loading: true };
+ await refresh();
+ } else {
+ launchBtn.disabled = false;
+ launchBtn.textContent = `Retry launch ${deriveSymbol(identity.name)}`;
+ }
+ } catch {
+ launchBtn.disabled = false;
+ launchBtn.textContent = 'Launch failed — retry';
+ }
+ });
+ }
+ root.querySelectorAll('[data-action]').forEach((btn) => {
+ btn.addEventListener('click', () => handleAction(btn.dataset.action));
+ });
+ };
+
+ const handleAction = async (action) => {
+ if (!state.mint || !skills) return;
+ if (action === 'claim') {
+ await skills.perform('pumpfun-claim-fees', { network: state.network }, { identity });
+ return;
+ }
+ const amount = window.prompt(
+ action === 'buy' ? 'Buy how many SOL?' : 'Sell how many tokens (raw units)?',
+ );
+ if (!amount) return;
+ if (action === 'buy') {
+ await skills.perform(
+ 'pumpfun-buy',
+ { mint: state.mint, solAmount: Number(amount), network: state.network },
+ { identity },
+ );
+ } else {
+ await skills.perform(
+ 'pumpfun-sell',
+ { mint: state.mint, tokenAmount: amount, network: state.network },
+ { identity },
+ );
+ }
+ await refresh();
+ };
+
+ const refresh = async () => {
+ const found = resolveMintFrom(memory, identity);
+ state = { ...state, ...found, loading: false };
+ render();
+ if (state.mint && skills) {
+ try {
+ const r = await skills.perform(
+ 'pumpfun-watch-curve',
+ { mint: state.mint, network: state.network },
+ { identity },
+ );
+ if (r?.success && r.data) {
+ state = { ...state, ...r.data };
+ render();
+ }
+ } catch {
+ /* swallow */
+ }
+ }
+ };
+
+ refresh();
+ refreshTimer = setInterval(() => state.mint && refresh(), REFRESH_MS);
+
+ return {
+ destroy() {
+ if (refreshTimer) clearInterval(refreshTimer);
+ root.remove();
+ },
+ refresh,
+ };
+}
+
+function resolveMintFrom(memory, identity) {
+ try {
+ if (memory?.recall) {
+ const hits = memory.recall('pumpfun:launch') || [];
+ const latest = hits.sort((a, b) => (b.context?.launchedAt || 0) - (a.context?.launchedAt || 0))[0];
+ if (latest?.context?.mint) {
+ return {
+ mint: latest.context.mint,
+ symbol: latest.context.symbol,
+ network: latest.context.network || 'mainnet',
+ };
+ }
+ }
+ } catch {
+ /* ignore */
+ }
+ const meta = identity?.meta || {};
+ if (meta.pumpfun_mint) {
+ return {
+ mint: meta.pumpfun_mint,
+ symbol: meta.pumpfun_symbol,
+ network: meta.pumpfun_network || 'mainnet',
+ };
+ }
+ return { mint: null, symbol: null };
+}
+
+function deriveSymbol(name) {
+ return (
+ String(name || 'AGENT')
+ .toUpperCase()
+ .replace(/[^A-Z0-9]/g, '')
+ .slice(0, 10) || 'AGENT'
+ );
+}
+
+function shortMint(m) {
+ if (!m) return '';
+ return `${m.slice(0, 6)}…${m.slice(-4)}`;
+}
+
+function formatLamports(lamports) {
+ const n = Number(lamports) / 1e9;
+ if (n >= 1000) return `${(n / 1000).toFixed(1)}K SOL`;
+ if (n >= 1) return `${n.toFixed(2)} SOL`;
+ return `${n.toFixed(4)} SOL`;
+}
+
+function escapeHtml(s) {
+ return String(s || '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#39;',
+ })[c]);
+}
+
+function escapeAttr(s) {
+ return escapeHtml(s);
+}
diff --git a/src/agent-skills-pumpfun-compose.js b/src/agent-skills-pumpfun-compose.js
index 3ac478d7b..eb72a4d22 100644
--- a/src/agent-skills-pumpfun-compose.js
+++ b/src/agent-skills-pumpfun-compose.js
@@ -99,10 +99,9 @@ async function maybeBuy(skills, ctx, simulate, mint, solAmount) {
}
async function maybeSell(skills, ctx, simulate, mint) {
- if (simulate) return { signature: `SIMULATED:sell:${mint}:100%`, simulated: true };
- // pumpfun-sell needs a tokenAmount; query holdings first.
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 };
const r = await skills.perform('pumpfun-sell', { mint, tokenAmount }, ctx);
if (!r?.success) throw new Error(r?.output || 'pumpfun-sell failed');
diff --git a/src/agent-skills-pumpfun.js b/src/agent-skills-pumpfun.js
index 5ba8430ec..ecbb390ea 100644
--- a/src/agent-skills-pumpfun.js
+++ b/src/agent-skills-pumpfun.js
@@ -374,7 +374,7 @@ export function registerPumpFunSkills(skills) {
},
handler: async (args, _ctx) => {
const network = args.network || DEFAULT_NETWORK;
- const { pump, web3 } = await loadCore();
+ const { pump, web3, splToken } = await loadCore();
const connection = getConnection(web3, network);
const onlineSdk = new pump.OnlinePumpSdk(connection);
const mint = new web3.PublicKey(args.mint);
@@ -387,6 +387,18 @@ export function registerPumpFunSkills(skills) {
bondingCurve: curve,
});
+ let userBalance = '0';
+ let owner = null;
+ try {
+ const wallet = detectSolanaWallet();
+ if (wallet?.publicKey && splToken) {
+ owner = wallet.publicKey;
+ const ata = await splToken.getAssociatedTokenAddress(mint, owner);
+ const acct = await connection.getTokenAccountBalance(ata).catch(() => null);
+ userBalance = acct?.value?.amount ?? '0';
+ }
+ } catch {}
+
return {
success: true,
output: graduated
@@ -397,6 +409,8 @@ export function registerPumpFunSkills(skills) {
mint: args.mint,
marketCap: marketCap.toString(),
graduated,
+ userBalance,
+ owner: owner ? owner.toBase58() : null,
network,
},
};
diff --git a/style.css b/style.css
index 8723cb6dc..2fdfe4082 100644
--- a/style.css
+++ b/style.css
@@ -6490,3 +6490,147 @@ textarea.erc8004-code {
padding-right: 14px;
}
}
+
+/* ── Pump.fun card on agent home ───────────────────────────────────────── */
+.agent-home-pumpfun {
+ margin: 14px 0 4px;
+}
+.pumpfun-card {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ padding: 14px 14px 12px;
+ border-radius: 14px;
+ background: linear-gradient(135deg, rgba(120, 80, 220, 0.18), rgba(0, 200, 180, 0.14));
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ color: var(--agent-home-fg, #fff);
+ box-shadow: 0 6px 20px -10px rgba(0, 0, 0, 0.4);
+}
+.pumpfun-card--graduated {
+ background: linear-gradient(135deg, rgba(0, 200, 130, 0.22), rgba(0, 120, 200, 0.18));
+}
+.pumpfun-card--cta {
+ background: linear-gradient(135deg, rgba(150, 100, 255, 0.18), rgba(255, 120, 180, 0.14));
+}
+.pumpfun-card--skeleton {
+ height: 96px;
+ background: rgba(255, 255, 255, 0.04);
+ animation: pumpfun-skeleton 1.4s infinite;
+}
+@keyframes pumpfun-skeleton {
+ 0%, 100% { opacity: 0.5; }
+ 50% { opacity: 0.8; }
+}
+.pumpfun-card-head {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+.pumpfun-card-icon {
+ font-size: 18px;
+ line-height: 1;
+}
+.pumpfun-card-title {
+ font-weight: 600;
+ font-size: 14px;
+ letter-spacing: 0.02em;
+ flex: 1;
+}
+.pumpfun-card-link {
+ color: inherit;
+ opacity: 0.6;
+ text-decoration: none;
+ font-size: 13px;
+ padding: 2px 6px;
+ border-radius: 6px;
+ transition: opacity .15s, background .15s;
+}
+.pumpfun-card-link:hover { opacity: 1; background: rgba(255,255,255,0.08); }
+.pumpfun-card-sub {
+ font-size: 12.5px;
+ opacity: 0.78;
+ margin: 0;
+ line-height: 1.4;
+}
+.pumpfun-stats {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 10px;
+}
+.pumpfun-stat {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+.pumpfun-stat-label {
+ font-size: 10.5px;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ opacity: 0.55;
+}
+.pumpfun-stat-value {
+ font-size: 15px;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+}
+.pumpfun-progress {
+ height: 4px;
+ background: rgba(255, 255, 255, 0.08);
+ border-radius: 999px;
+ overflow: hidden;
+}
+.pumpfun-progress-bar {
+ height: 100%;
+ background: linear-gradient(90deg, #b27dff, #6ce0c8);
+ transition: width .6s ease;
+}
+.pumpfun-card-mint {
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 11.5px;
+ opacity: 0.55;
+}
+.pumpfun-card-actions {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+}
+.pumpfun-btn {
+ flex: 1;
+ min-width: 64px;
+ padding: 7px 10px;
+ font-size: 12.5px;
+ font-weight: 500;
+ border-radius: 8px;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ background: rgba(255, 255, 255, 0.06);
+ color: inherit;
+ cursor: pointer;
+ transition: background .15s, transform .05s;
+}
+.pumpfun-btn:hover { background: rgba(255, 255, 255, 0.12); }
+.pumpfun-btn:active { transform: translateY(1px); }
+.pumpfun-btn:disabled { opacity: 0.5; cursor: not-allowed; }
+.pumpfun-btn--primary {
+ background: linear-gradient(135deg, #b27dff, #6ce0c8);
+ border: none;
+ color: #0e0a18;
+ font-weight: 600;
+}
+.pumpfun-btn--primary:hover { filter: brightness(1.06); background: linear-gradient(135deg, #b27dff, #6ce0c8); }
+.pumpfun-btn--ghost {
+ background: transparent;
+}
+.pumpfun-card-foot {
+ display: inline-block;
+ font-size: 11.5px;
+ opacity: 0.55;
+ color: inherit;
+ text-decoration: underline;
+ text-decoration-color: rgba(255,255,255,0.2);
+}
+.pumpfun-card-foot:hover { opacity: 0.85; }
+@media (prefers-reduced-motion: reduce) {
+ .pumpfun-progress-bar { transition: none; }
+ .pumpfun-card--skeleton { animation: none; }
+}
diff --git a/tests/api/solana-register-prep.test.js b/tests/api/solana-register-prep.test.js
new file mode 100644
index 000000000..7ba90681e
--- /dev/null
+++ b/tests/api/solana-register-prep.test.js
@@ -0,0 +1,188 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────
+
+const authState = { session: null };
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+
+const sqlState = { queue: [], calls: [] };
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ if (sqlState.queue.length === 0) return [];
+ return sqlState.queue.shift();
+ }),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: true })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../../api/_lib/crypto.js', () => ({
+ randomToken: vi.fn(async () => 'prep-token-stub'),
+}));
+
+vi.mock('../../api/_lib/env.js', () => ({
+ env: { APP_ORIGIN: 'http://localhost' },
+}));
+
+// Metaplex / Umi: stub out so the handler doesn't try to hit a real RPC.
+vi.mock('@metaplex-foundation/umi-bundle-defaults', () => ({
+ createUmi: vi.fn(() => ({ use: function () { return this; } })),
+}));
+vi.mock('@metaplex-foundation/mpl-core', () => ({
+ mplCore: vi.fn(() => () => {}),
+ createV1: vi.fn(() => ({
+ buildAndSign: vi.fn(async () => new Uint8Array([1, 2, 3, 4])),
+ })),
+ fetchAsset: vi.fn(),
+}));
+vi.mock('@metaplex-foundation/umi', () => ({
+ generateSigner: vi.fn(() => ({ publicKey: 'GeneratedSigner1111111111111111111111111111' })),
+ publicKey: vi.fn((s) => s),
+ signerIdentity: vi.fn(() => () => {}),
+ createNoopSigner: vi.fn((pk) => ({ publicKey: pk })),
+ transactionBuilder: vi.fn(),
+}));
+
+const { default: handler } = await import('../../api/agents/solana-register-prep.js');
+
+// ── Helpers ──────────────────────────────────────────────────────────────
+
+function makeReq({ method = 'POST', url = '/api/agents/solana-register-prep', body = null } = {}) {
+ const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
+ base.method = method;
+ base.url = url;
+ base.headers = {
+ host: 'localhost',
+ 'content-type': 'application/json',
+ origin: 'http://localhost',
+ };
+ return base;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },
+ };
+}
+
+async function invoke(reqOpts) {
+ const req = makeReq(reqOpts);
+ const res = makeRes();
+ await handler(req, res);
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };
+}
+
+// 32-byte base58-ish pubkey (43 chars). Doesn't have to be a valid curve point
+// for these unit tests — the handler only checks length + base58.
+const VANITY_4 = 'AGNTAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
+const VANITY_5 = 'AGNTSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
+const PLAIN_PK = 'JUpiTERaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
+const WALLET = '11111111111111111111111111111111';
+
+beforeEach(() => {
+ authState.session = null;
+ sqlState.queue = [];
+ sqlState.calls = [];
+});
+
+describe('POST /api/agents/solana-register-prep — vanity', () => {
+ it('rejects when unauthenticated', async () => {
+ const { status, body } = await invoke({
+ body: { name: 'A', wallet_address: WALLET, network: 'devnet' },
+ });
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('rejects vanity_prefix without asset_pubkey', async () => {
+ authState.session = { id: 'u1', plan: 'pro' };
+ sqlState.queue.push([{ id: 'wallet-1' }]);
+ const { status, body } = await invoke({
+ body: { name: 'A', wallet_address: WALLET, network: 'devnet', vanity_prefix: 'AGNT' },
+ });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('rejects mismatched prefix and asset_pubkey', async () => {
+ authState.session = { id: 'u1', plan: 'pro' };
+ sqlState.queue.push([{ id: 'wallet-1' }]);
+ const { status, body } = await invoke({
+ body: {
+ name: 'A', wallet_address: WALLET, network: 'devnet',
+ asset_pubkey: PLAIN_PK, vanity_prefix: 'AGNT',
+ },
+ });
+ expect(status).toBe(400);
+ expect(body.error_description).toMatch(/does not start with/);
+ });
+
+ it('rejects 5-char vanity for free-plan users with 402', async () => {
+ authState.session = { id: 'u1', plan: 'free' };
+ sqlState.queue.push([{ id: 'wallet-1' }]);
+ const { status, body } = await invoke({
+ body: {
+ name: 'A', wallet_address: WALLET, network: 'devnet',
+ asset_pubkey: VANITY_5, vanity_prefix: 'AGNTS',
+ },
+ });
+ expect(status).toBe(402);
+ expect(body.error).toBe('payment_required');
+ });
+
+ it('accepts 5-char vanity for paid users', async () => {
+ authState.session = { id: 'u1', plan: 'pro' };
+ sqlState.queue.push([{ id: 'wallet-1' }]); // user_wallets lookup
+ sqlState.queue.push([]); // pending insert
+ const { status, body } = await invoke({
+ body: {
+ name: 'A', wallet_address: WALLET, network: 'devnet',
+ asset_pubkey: VANITY_5, vanity_prefix: 'AGNTS',
+ },
+ });
+ expect(status).toBe(201);
+ expect(body.asset_pubkey).toBe(VANITY_5);
+ expect(body.tx_base64).toBe(Buffer.from([1, 2, 3, 4]).toString('base64'));
+ });
+
+ it('accepts 4-char vanity for free-plan users', async () => {
+ authState.session = { id: 'u1', plan: 'free' };
+ sqlState.queue.push([{ id: 'wallet-1' }]);
+ sqlState.queue.push([]);
+ const { status, body } = await invoke({
+ body: {
+ name: 'A', wallet_address: WALLET, network: 'devnet',
+ asset_pubkey: VANITY_4, vanity_prefix: 'AGNT',
+ },
+ });
+ expect(status).toBe(201);
+ expect(body.asset_pubkey).toBe(VANITY_4);
+ });
+
+ it('rejects non-base58 asset_pubkey', async () => {
+ authState.session = { id: 'u1', plan: 'pro' };
+ sqlState.queue.push([{ id: 'wallet-1' }]);
+ const { status, body } = await invoke({
+ body: {
+ name: 'A', wallet_address: WALLET, network: 'devnet',
+ asset_pubkey: '0OIl000000000000000000000000000000000000000',
+ },
+ });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+});
diff --git a/tests/pumpfun-signals.test.js b/tests/pumpfun-signals.test.js
index 2e3dcada3..62f8bdbb9 100644
--- a/tests/pumpfun-signals.test.js
+++ b/tests/pumpfun-signals.test.js
@@ -45,12 +45,6 @@ describe('pumpfun-signals cron', () => {
delete process.env.CRON_SECRET;
});
- it('skips when bot disabled', async () => {
- const mod = await import('../api/_lib/pumpfun-mcp.js');
- mod.pumpfunBotEnabled = () => false;
- // No way to swap export at runtime cleanly — just exercise the run with empty data instead.
- });
-
it('writes typed signals only for linked wallets', async () => {
recentClaimsMock.mockResolvedValueOnce({
ok: true,
diff --git a/vercel.json b/vercel.json
index c7a95ffcc..482bc38c2 100644
--- a/vercel.json
+++ b/vercel.json
@@ -65,6 +65,8 @@
"dest": "/api/agents/by-address/[addr]?addr=$1"
},
{ "src": "/api/agents/([^/]+)/wallet", "dest": "/api/agents/[id]" },
+ { "src": "/api/agents/([^/]+)/solana", "dest": "/api/agents/[id]" },
+ { "src": "/api/agents/([^/]+)/pumpfun/([^/]+)", "dest": "/api/agents/[id]" },
{
"src": "/api/avatars/([^/]+)/storage-mode",
"dest": "/api/avatars/[id]/storage-mode?id=$1"