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: update Vercel configuration and add new Solana agent operations

nirholasb23472146943
diff --git a/.env.example b/.env.example
index d05463c5a..1056d2cb1 100644
--- a/.env.example
+++ b/.env.example
@@ -113,3 +113,16 @@ PUMPFUN_BOT_TOKEN=
# Defaults to public mainnet/devnet — set Helius/Triton/QuickNode for prod.
SOLANA_RPC_URL=
SOLANA_RPC_URL_DEVNET=
+
+# ── x402 micropayments (POST /api/mcp) ─────────────────────────────────────
+# Solana wallet that receives USDC for paid MCP calls.
+X402_PAY_TO=BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN
+# USDC mint on Solana mainnet.
+X402_ASSET_MINT=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
+X402_NETWORK=solana
+# Price in base units (USDC = 6 decimals; 1000 = 0.001 USDC).
+X402_MAX_AMOUNT_REQUIRED=1000
+# Public Solana facilitator. Self-host or swap providers via this var.
+X402_FACILITATOR_URL=https://facilitator.payai.network
+# Optional bearer for self-hosted/private facilitators.
+X402_FACILITATOR_TOKEN=
diff --git a/api/_lib/agent-pumpfun.js b/api/_lib/agent-pumpfun.js
index 4c66ee5d6..390e32005 100644
--- a/api/_lib/agent-pumpfun.js
+++ b/api/_lib/agent-pumpfun.js
@@ -23,10 +23,13 @@ export function solanaConnection(network = 'mainnet') {
* (older rows from before pump-fun integration), one is generated and
* persisted into meta in-place.
*
+ * `audit` is passed through to `recoverSolanaAgentKeypair` so every key
+ * decrypt is recorded in usage_events. Always pass `{ reason }` at minimum.
+ *
* Returns { agent, keypair, meta }. Caller is responsible for calling
* agent-payments / pump-sdk / pump-swap-sdk with `keypair`.
*/
-export async function loadAgentForSigning(agentId, userId) {
+export async function loadAgentForSigning(agentId, userId, audit = null) {
const [row] = await sql`
SELECT * FROM agent_identities
WHERE id = ${agentId} AND deleted_at IS NULL
@@ -38,7 +41,12 @@ export async function loadAgentForSigning(agentId, userId) {
let meta = { ...(row.meta || {}) };
if (!meta.encrypted_solana_secret || !meta.solana_address) {
const sol = await generateSolanaAgentWallet();
- meta = { ...meta, solana_address: sol.address, encrypted_solana_secret: sol.encrypted_secret };
+ meta = {
+ ...meta,
+ solana_address: sol.address,
+ encrypted_solana_secret: sol.encrypted_secret,
+ solana_wallet_source: 'auto_provisioned',
+ };
await sql`
UPDATE agent_identities
SET meta = ${JSON.stringify(meta)}::jsonb
@@ -46,6 +54,11 @@ export async function loadAgentForSigning(agentId, userId) {
`;
}
- const keypair = await recoverSolanaAgentKeypair(meta.encrypted_solana_secret);
+ const keypair = await recoverSolanaAgentKeypair(meta.encrypted_solana_secret, {
+ agentId,
+ userId,
+ reason: audit?.reason || 'pumpfun_action',
+ meta: audit?.meta,
+ });
return { agent: row, keypair, meta };
}
diff --git a/api/_lib/skill-runtime.js b/api/_lib/skill-runtime.js
index 1e5942060..c57bcbe95 100644
--- a/api/_lib/skill-runtime.js
+++ b/api/_lib/skill-runtime.js
@@ -60,9 +60,33 @@ async function loadManifest(name) {
* @param {object} [opts.wallet] - solana wallet contract for signing skills
* @param {(event: object) => void} [opts.onEvent] - notified on every memory.note call
* @param {object} [opts.fetch] - fetch impl (defaults to globalThis.fetch)
+ * @param {string} [opts.agentId] - if set, every memory.note is persisted to agent_actions
+ * @param {string} [opts.signerAddress] - persisted with each agent_actions row when agentId is set
*/
export function makeRuntime(opts = {}) {
- const { configOverrides = {}, wallet, onEvent, fetch = globalThis.fetch } = opts;
+ const { configOverrides = {}, wallet, onEvent, fetch = globalThis.fetch, agentId, signerAddress } = opts;
+ let _sql;
+ async function persistAction(skillName, tag, value) {
+ if (!agentId) return;
+ try {
+ if (!_sql) _sql = (await import('./db.js')).sql;
+ const [, type] = (tag ?? '').split(':'); // e.g. 'pump-fun-trade:buy' → 'buy'
+ await _sql`
+ INSERT INTO agent_actions (agent_id, type, payload, source_skill, signature, signer_address)
+ VALUES (
+ ${agentId},
+ ${type || tag || 'note'},
+ ${JSON.stringify(value ?? {})}::jsonb,
+ ${skillName},
+ ${value?.sig ?? null},
+ ${signerAddress ?? null}
+ )
+ `;
+ } catch (e) {
+ // Persistence is best-effort; never break the strategy on a DB hiccup.
+ console.error('[skill-runtime] persistAction failed', e?.message);
+ }
+ }
async function invoke(qualified, args) {
const [skillName, toolName] = qualified.split('.');
@@ -83,9 +107,9 @@ export function makeRuntime(opts = {}) {
fetch,
memory: {
note: (tag, value) => {
- try {
- onEvent?.({ skill: skillName, tool: toolName, tag, value, t: Date.now() });
- } catch {}
+ try { onEvent?.({ skill: skillName, tool: toolName, tag, value, t: Date.now() }); } catch {}
+ // Fire and forget — don't block the strategy loop on disk writes.
+ persistAction(skillName, tag, value);
},
recall: async () => null,
},
diff --git a/api/agents/SOLANA_OPS.md b/api/agents/SOLANA_OPS.md
new file mode 100644
index 000000000..a05384491
--- /dev/null
+++ b/api/agents/SOLANA_OPS.md
@@ -0,0 +1,120 @@
+# Solana agent stack — operations
+
+Single source of truth for what's deployed, what env vars enable it, what cron schedules it, and what the wire formats are. No demo paths, no mocks — every endpoint listed here writes to or reads from the same Postgres + Solana RPC.
+
+## Endpoints (Vercel auto-routed by file path)
+
+| Path | Method | Purpose |
+|---|---|---|
+| `/api/agents/solana-register-prep` | POST | Build unsigned Metaplex Core createV1 tx for the user's wallet. Optional vanity (`asset_pubkey`, `vanity_prefix`). |
+| `/api/agents/solana-register-confirm` | POST | Verify on-chain confirmation, upsert `agent_identities` row with `meta.sol_mint_address`. |
+| `/api/agents/onchain/prep` + `/confirm` | POST | Unified EVM + Solana variant. Stores `meta.onchain` block. |
+| `/api/agents/solana-card` | GET | A2A-compatible agent card (`identity`, endpoints, schemas). |
+| `/api/agents/solana-attestations` | GET | Read indexed attestations. Cold cache → inline RPC crawl. |
+| `/api/agents/solana-reputation` | GET | Computed reputation: feedback (raw / verified / credentialed / event-attested), validation, tasks, pump-payments, token activity. |
+| `/api/agents/solana-reputation-history` | GET | Daily score buckets for sparkline. `?days=1..90`. |
+| `/api/agents/solana-attest-event` | POST | **Webhook bridge.** HMAC-verified, idempotent, claims-table-serialised. |
+
+## Required env vars
+
+| Var | Used by | Purpose |
+|---|---|---|
+| `DATABASE_URL` | all | Neon Postgres. |
+| `SOLANA_RPC_URL` | reads + crawler | Mainnet RPC. |
+| `SOLANA_RPC_URL_DEVNET` | reads + crawler | Devnet RPC. |
+| `PUMPKIT_WEBHOOK_SECRET` | `solana-attest-event` | HMAC-SHA256 secret shared with the upstream pumpkit monitor. |
+| `ATTEST_AGENT_SECRET_KEY` | `solana-attest-event` | bs58-encoded 64-byte Ed25519 secret of the server-side attester wallet. **Must hold SOL** on the target network to pay memo tx fees (~0.000005 SOL/tx). |
+| `CRON_SECRET` | all `/api/cron/*` | Manual cron trigger auth. Vercel Cron uses `x-vercel-cron: 1` instead. |
+| `PUMPFUN_BOT_URL` (optional) | `pumpfun-signals` | Upstream pumpfun-claims-bot MCP endpoint. |
+| `PUMPFUN_BOT_TOKEN` (optional) | `pumpfun-signals` | Bearer token for the MCP endpoint. |
+
+## Cron schedule (vercel.json)
+
+| Path | Schedule | Job |
+|---|---|---|
+| `/api/cron/solana-attestations-crawl` | `*/5 * * * *` | Crawl SPL Memo attestations into `solana_attestations`. |
+| `/api/cron/erc8004-crawl` | `*/15 * * * *` | EVM IdentityRegistry crawler. |
+| `/api/cron/pumpfun-signals` | `*/15 * * * *` | Pull claim/graduation signals from upstream MCP. |
+| `/api/cron/pump-agent-stats` | `*/10 * * * *` | Refresh pump.fun token state per agent. |
+| `/api/cron/solana-attest-event-cleanup` | `*/10 * * * *` | Reap stale claim rows (>1h, signature null). |
+
+## Database tables
+
+Migrations are under `api/_lib/migrations/<date>-<name>.sql`, applied with:
+```
+psql "$DATABASE_URL" -f api/_lib/migrations/<file>.sql
+```
+
+The new ones are:
+- `2026-04-29-attest-event-bridge.sql` — `solana_attest_event_claims` + the partial unique index `solana_attestations_event_id_uniq`.
+
+Pre-existing relevant tables: `solana_attestations`, `solana_attestations_cursor`, `solana_credentials`, `pump_agent_mints`, `pump_agent_payments`, `pump_agent_stats`, `pump_agent_trades`, `pumpfun_signals`, `agent_identities`, `usage_events`.
+
+## Webhook contract — `/api/agents/solana-attest-event`
+
+```http
+POST /api/agents/solana-attest-event
+content-type: application/json
+x-pumpkit-timestamp: <unix-seconds>
+x-pumpkit-signature: <hex hmac_sha256(secret, "<ts>.<raw-body>")>
+
+{
+ "event_id": "<unique per event>",
+ "event_type": "graduation" | "fee_claim" | "whale_trade" | "cto_detected",
+ "agent_asset": "<base58 Metaplex Core asset pubkey>",
+ "network": "mainnet" | "devnet",
+ "token_mint": "<base58 spl mint>",
+ "task_id": "<correlation id>",
+ "detail": { ... } // optional, opaque
+}
+```
+
+**Responses:**
+- `201 { data: { signature, kind, deduped: false } }` — new attestation minted on-chain.
+- `200 { data: { signature, deduped: true } }` — duplicate `event_id` for this agent; previous signature returned.
+- `202 { data: { deduped: true, status: 'in_progress' } }` — leader still processing; retry later.
+- `401 unauthorized (missing|stale|bad_timestamp|bad_signature)` — HMAC failed.
+- `404 not_found` — `agent_asset` not registered.
+- `429 rate_limited` — IP exceeded the auth-IP bucket.
+- `500 internal` — `PUMPKIT_WEBHOOK_SECRET` or `ATTEST_AGENT_SECRET_KEY` not configured.
+
+**Replay window:** 5 minutes (timestamp skew). **Body limit:** 64 KB.
+
+## Trust tiers (read by `solana-reputation`)
+
+In order of Sybil resistance (strongest first):
+
+1. **Credentialed** — feedback from attesters holding `threews.verified-client.v1` SAS credentials.
+2. **Verified** — feedback whose `task_id` has a matching `threews.accept.v1` from the agent owner.
+3. **Event-attested** — feedback whose `payload.source` starts with `pumpkit.` (issued by this webhook).
+4. **Community** — raw memo feedback.
+
+The passport (`/agent-passport.html`) renders all four tiers and computes a top-level **A/B/C/D trust grade** from the strongest available tier, penalised by disputes and validation-failure rate.
+
+## Live UI surface
+
+| Page | Reads from |
+|---|---|
+| `/agent-passport.html?asset=<asset>&network=<n>` | card + reputation + attestations + history. 8s polling. |
+| `/agent-badge.html?asset=<asset>&network=<n>&theme=<light\|dark>` | card + reputation. Iframe-friendly. |
+| `/agent/index.html?id=<agent-id>` | $AGENT pump.fun token widget. Real-time bus updates. |
+
+## Verifying production wiring
+
+```bash
+# 1. Schema present
+psql "$DATABASE_URL" -c "\d solana_attest_event_claims"
+psql "$DATABASE_URL" -c "\di solana_attestations_event_id_uniq"
+
+# 2. Attester funded
+solana balance "$ATTESTER_PUBKEY" --url devnet # or mainnet-beta
+
+# 3. Webhook reachable + reject without HMAC
+curl -i -X POST https://<host>/api/agents/solana-attest-event \
+ -H 'content-type: application/json' -d '{}' # expect 401 unauthorized
+
+# 4. Cron auth
+curl -i -H "Authorization: Bearer $CRON_SECRET" \
+ https://<host>/api/cron/solana-attest-event-cleanup
+# expect { "deleted": 0, ... } on a healthy table
+```
diff --git a/api/agents/pumpfun/buy.js b/api/agents/pumpfun/buy.js
index d3f52ec50..771fef9df 100644
--- a/api/agents/pumpfun/buy.js
+++ b/api/agents/pumpfun/buy.js
@@ -130,6 +130,29 @@ export default async function handler(req, res, id) {
)
`.catch((e) => console.error('[pumpfun/buy] log failed', e));
+ // Mirror into pump_agent_trades for cross-feature analytics (reputation,
+ // admin health, strategy backtests). Best-effort — agent may not have a
+ // pump_agent_mints row yet if the mint was launched outside three.ws.
+ try {
+ const [m] = await sql`
+ select id from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1
+ `;
+ if (m) {
+ const lamports = BigInt(Math.floor(body.solAmount * 1_000_000_000));
+ await sql`
+ INSERT INTO pump_agent_trades
+ (mint_id, user_id, wallet, direction, route, sol_amount, slippage_bps, tx_signature, network)
+ VALUES
+ (${m.id}, ${auth.userId}, ${keypair.publicKey.toBase58()}, 'buy',
+ 'bonding_curve', ${lamports.toString()}, ${body.slippageBps || null},
+ ${signature}, ${body.network})
+ ON CONFLICT (tx_signature, network) DO NOTHING
+ `;
+ }
+ } catch (e) {
+ console.error('[pumpfun/buy] trade index failed', e);
+ }
+
return json(res, 200, {
data: {
signature,
diff --git a/api/agents/pumpfun/launch.js b/api/agents/pumpfun/launch.js
index a58f06170..bd57da51c 100644
--- a/api/agents/pumpfun/launch.js
+++ b/api/agents/pumpfun/launch.js
@@ -140,6 +140,7 @@ export default async function handler(req, res, id) {
uri: body.uri,
signature,
network: body.network,
+ solAmount: body.solAmount || 0,
vanity_prefix: body.vanityPrefix || null,
vanity_suffix: body.vanitySuffix || null,
vanity_ignore_case: body.vanityIgnoreCase || false,
diff --git a/api/agents/pumpfun/pay.js b/api/agents/pumpfun/pay.js
index 780895cb9..b1561d8e8 100644
--- a/api/agents/pumpfun/pay.js
+++ b/api/agents/pumpfun/pay.js
@@ -1,32 +1,62 @@
// POST /api/agents/:id/pumpfun/pay
-// Wraps @pump-fun/agent-payments-sdk.
+//
+// Full @pump-fun/agent-payments-sdk surface, signed by the agent's wallet.
//
// Body: { action, tokenMint, currencyMint, ...params, network? }
-// action='accept' — pay an agent token (the agent IS the user paying);
-// params: amount (string raw units), memo, startTime, endTime
-// action='withdraw' — agent withdraws collected payments for the token
-// it is the agent-authority of; params: receiverAta
-// action='balances' — read-only; returns vault balances for currencyMint
//
-// Server signs with the agent's wallet.
+// Actions (all return { signature, action, ... } except `balances`):
+// create — register the agent's wallet as authority for tokenMint.
+// Requires: buybackBps (0–10_000).
+// The agent must already be the bonding-curve creator
+// of `tokenMint`; otherwise the program rejects.
+// accept — agent pays the token's payment vault for an invoice.
+// Requires: amount (raw units, string), memo (string),
+// startTime, endTime (unix seconds).
+// withdraw — agent withdraws collected payments for tokenMint.
+// Requires: receiverAta. The ATA must already exist;
+// create it client-side or via /accept-payment first.
+// distribute — permissionless distribution from payment vault to the
+// buyback + withdraw vaults. Anyone can call.
+// extend_account — pay rent to extend a program account.
+// Requires: account.
+// update_authority — rotate the agent authority. Requires: newAuthority.
+// update_buyback — change buyback bps. Requires: buybackBps.
+// balances — read-only; returns vault balances for currencyMint.
+//
+// Spend-policy is enforced on `accept` (it spends agent SOL/SPL).
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
import { cors, json, method, readJson, error } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
+import { sql } from '../../_lib/db.js';
import { PublicKey, Transaction } from '@solana/web3.js';
import { z } from 'zod';
+const NATIVE_SOL_MINT = 'So11111111111111111111111111111111111111112';
+
const bodySchema = z.object({
- action: z.enum(['accept', 'withdraw', 'balances']),
+ action: z.enum([
+ 'create',
+ 'accept',
+ 'withdraw',
+ 'distribute',
+ 'extend_account',
+ 'update_authority',
+ 'update_buyback',
+ 'balances',
+ ]),
tokenMint: z.string().min(32).max(64),
- currencyMint: z.string().min(32).max(64),
+ currencyMint: z.string().min(32).max(64).default(NATIVE_SOL_MINT),
amount: z.string().regex(/^\d+$/).optional(),
memo: z.string().regex(/^\d+$/).optional(),
startTime: z.number().int().nonnegative().optional(),
endTime: z.number().int().nonnegative().optional(),
receiverAta: z.string().min(32).max(64).optional(),
userTokenAccount: z.string().min(32).max(64).optional(),
+ account: z.string().min(32).max(64).optional(),
+ newAuthority: z.string().min(32).max(64).optional(),
+ buybackBps: z.number().int().min(0).max(10_000).optional(),
network: z.enum(['mainnet', 'devnet']).default('mainnet'),
});
@@ -38,6 +68,17 @@ async function resolveAuth(req) {
return null;
}
+function need(body, ...fields) {
+ const missing = fields.filter((f) => body[f] == null || body[f] === '');
+ if (missing.length)
+ return { status: 400, code: 'validation_error', msg: `missing: ${missing.join(', ')}` };
+ return null;
+}
+
+function explorerUrl(sig, network) {
+ return `https://solscan.io/tx/${sig}${network === 'devnet' ? '?cluster=devnet' : ''}`;
+}
+
export default async function handler(req, res, id) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
@@ -54,7 +95,10 @@ export default async function handler(req, res, id) {
return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
}
- const loaded = await loadAgentForSigning(id, auth.userId);
+ const loaded = await loadAgentForSigning(id, auth.userId, {
+ reason: `pumpfun.pay.${body.action}`,
+ meta: { tokenMint: body.tokenMint, network: body.network },
+ });
if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
const { keypair } = loaded;
@@ -64,42 +108,129 @@ export default async function handler(req, res, id) {
const { PumpAgent } = await import('@pump-fun/agent-payments-sdk');
const agent = new PumpAgent(tokenMint, body.network, conn);
+ // ── Read-only ──────────────────────────────────────────────────────────
if (body.action === 'balances') {
- const balances = await agent.getBalances(currencyMint);
- return json(res, 200, {
- data: {
- balances: Object.fromEntries(
- Object.entries(balances).map(([k, v]) => [
- k,
- v && typeof v === 'object'
- ? { ...v, balance: v.balance?.toString?.() ?? String(v.balance) }
- : v,
- ]),
- ),
- },
- });
+ try {
+ const balances = await agent.getBalances(currencyMint);
+ return json(res, 200, {
+ data: {
+ tokenMint: body.tokenMint,
+ currencyMint: body.currencyMint,
+ balances: {
+ paymentVault: {
+ address: balances.paymentVault.address.toBase58(),
+ balance: balances.paymentVault.balance.toString(),
+ },
+ buybackVault: {
+ address: balances.buybackVault.address.toBase58(),
+ balance: balances.buybackVault.balance.toString(),
+ },
+ withdrawVault: {
+ address: balances.withdrawVault.address.toBase58(),
+ balance: balances.withdrawVault.balance.toString(),
+ },
+ },
+ },
+ });
+ } catch (err) {
+ console.error('[pumpfun/pay] balances failed', err);
+ return error(res, 502, 'rpc_error', err.message || 'balance fetch failed');
+ }
}
+ // ── Build instructions per action ──────────────────────────────────────
let instructions;
- if (body.action === 'accept') {
- if (!body.userTokenAccount || !body.amount || !body.memo || body.startTime == null || body.endTime == null)
- return error(res, 400, 'validation_error', 'accept requires userTokenAccount, amount, memo, startTime, endTime');
- instructions = await agent.buildAcceptPaymentInstructions({
- user: keypair.publicKey,
- currencyMint,
- amount: body.amount,
- memo: body.memo,
- startTime: body.startTime,
- endTime: body.endTime,
- });
- } else {
- if (!body.receiverAta) return error(res, 400, 'validation_error', 'withdraw requires receiverAta');
- const ix = await agent.withdraw({
- authority: keypair.publicKey,
- currencyMint,
- receiverAta: new PublicKey(body.receiverAta),
- });
- instructions = [ix];
+ let extra = {};
+ try {
+ switch (body.action) {
+ case 'create': {
+ const miss = need(body, 'buybackBps');
+ if (miss) return error(res, miss.status, miss.code, miss.msg);
+ const ix = await agent.create({
+ authority: keypair.publicKey,
+ mint: tokenMint,
+ agentAuthority: keypair.publicKey,
+ buybackBps: body.buybackBps,
+ });
+ instructions = [ix];
+ extra = { buybackBps: body.buybackBps };
+ break;
+ }
+ case 'accept': {
+ const miss = need(body, 'amount', 'memo', 'startTime', 'endTime');
+ if (miss) return error(res, miss.status, miss.code, miss.msg);
+ instructions = await agent.buildAcceptPaymentInstructions({
+ user: keypair.publicKey,
+ currencyMint,
+ amount: body.amount,
+ memo: body.memo,
+ startTime: body.startTime,
+ endTime: body.endTime,
+ });
+ extra = {
+ amount: body.amount,
+ memo: body.memo,
+ startTime: body.startTime,
+ endTime: body.endTime,
+ };
+ break;
+ }
+ case 'withdraw': {
+ const miss = need(body, 'receiverAta');
+ if (miss) return error(res, miss.status, miss.code, miss.msg);
+ const ix = await agent.withdraw({
+ authority: keypair.publicKey,
+ currencyMint,
+ receiverAta: new PublicKey(body.receiverAta),
+ });
+ instructions = [ix];
+ extra = { receiverAta: body.receiverAta };
+ break;
+ }
+ case 'distribute': {
+ instructions = await agent.distributePayments({
+ user: keypair.publicKey,
+ currencyMint,
+ });
+ break;
+ }
+ case 'extend_account': {
+ const miss = need(body, 'account');
+ if (miss) return error(res, miss.status, miss.code, miss.msg);
+ const ix = await agent.extendAccount({
+ account: new PublicKey(body.account),
+ user: keypair.publicKey,
+ });
+ instructions = [ix];
+ extra = { account: body.account };
+ break;
+ }
+ case 'update_authority': {
+ const miss = need(body, 'newAuthority');
+ if (miss) return error(res, miss.status, miss.code, miss.msg);
+ const ix = await agent.updateAuthority({
+ authority: keypair.publicKey,
+ newAuthority: new PublicKey(body.newAuthority),
+ });
+ instructions = [ix];
+ extra = { newAuthority: body.newAuthority };
+ break;
+ }
+ case 'update_buyback': {
+ const miss = need(body, 'buybackBps');
+ if (miss) return error(res, miss.status, miss.code, miss.msg);
+ const ix = await agent.updateBuybackBps({
+ authority: keypair.publicKey,
+ buybackBps: body.buybackBps,
+ });
+ instructions = [ix];
+ extra = { buybackBps: body.buybackBps };
+ break;
+ }
+ }
+ } catch (err) {
+ console.error(`[pumpfun/pay] ${body.action} build failed`, err);
+ return error(res, 422, 'build_failed', err.message || 'could not build instruction');
}
const tx = new Transaction().add(...instructions);
@@ -113,16 +244,34 @@ export default async function handler(req, res, id) {
signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
await conn.confirmTransaction(signature, 'confirmed');
} catch (err) {
- console.error('[pumpfun/pay] send failed', err);
+ console.error(`[pumpfun/pay] ${body.action} send failed`, err);
return error(res, 502, 'rpc_error', err.message || 'transaction failed');
}
+ await sql`
+ INSERT INTO agent_actions (agent_id, type, payload, source_skill)
+ VALUES (
+ ${id},
+ ${`pumpfun.pay.${body.action}`},
+ ${JSON.stringify({
+ tokenMint: body.tokenMint,
+ currencyMint: body.currencyMint,
+ signature,
+ network: body.network,
+ ...extra,
+ })}::jsonb,
+ ${'pumpfun'}
+ )
+ `.catch((e) => console.error('[pumpfun/pay] log failed', e));
+
return json(res, 200, {
data: {
signature,
action: body.action,
tokenMint: body.tokenMint,
- explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
+ currencyMint: body.currencyMint,
+ explorer: explorerUrl(signature, body.network),
+ ...extra,
},
});
}
diff --git a/api/agents/pumpfun/portfolio.js b/api/agents/pumpfun/portfolio.js
index b8b7d7d3d..b31bdadbf 100644
--- a/api/agents/pumpfun/portfolio.js
+++ b/api/agents/pumpfun/portfolio.js
@@ -98,13 +98,16 @@ export default async function handler(req, res, id) {
}
const conn = solanaConnection(network);
- const [{ PumpSdk, OnlinePumpSdk, getSellSolAmountFromTokenAmount }, splToken, BN] =
+ const [{ PumpSdk, OnlinePumpSdk, getSellSolAmountFromTokenAmount }, ammMod, splToken, BN] =
await Promise.all([
import('@pump-fun/pump-sdk'),
+ import('@pump-fun/pump-swap-sdk'),
import('@solana/spl-token'),
import('bn.js').then((m) => m.default || m),
]);
const online = new OnlinePumpSdk(conn);
+ const onlineAmm = new ammMod.OnlinePumpAmmSdk(conn);
+ const ammSdk = new ammMod.PumpAmmSdk();
let global;
try {
global = await online.fetchGlobal();
@@ -141,21 +144,51 @@ export default async function handler(req, res, id) {
try {
const state = await online.fetchSellState(mintPk, keypair.publicKey);
out.graduated = !!state.bondingCurve.complete;
- if (out.graduated) {
- // AMM pricing path not implemented here; surface graduation
- out.estimated_sol_value = null;
+ if (!out.graduated) {
+ const expectedSol = getSellSolAmountFromTokenAmount({
+ global,
+ feeConfig: null,
+ mintSupply: state.bondingCurve.tokenTotalSupply,
+ bondingCurve: state.bondingCurve,
+ amount: new BN(out.token_balance),
+ });
+ out.estimated_sol_value = lamportsToSol(expectedSol);
+ out.venue = 'curve';
+ } else {
+ // AMM quote: simulate sellBaseInput to get expected SOL out.
+ try {
+ const poolKey = ammMod.canonicalPumpPoolPda(mintPk);
+ const swapState = await onlineAmm.swapSolanaState(poolKey, keypair.publicKey);
+ const result = ammSdk.sellAutocompleteQuoteFromBase
+ ? ammSdk.sellAutocompleteQuoteFromBase(swapState, new BN(out.token_balance), 0)
+ : null;
+ if (result && result.uiQuote != null) {
+ out.estimated_sol_value = lamportsToSol(result.uiQuote);
+ } else {
+ const pool = swapState.pool;
+ const baseReserve = pool.baseReserve || pool.virtualBaseReserves;
+ const quoteReserve = pool.quoteReserve || pool.virtualQuoteReserves;
+ if (baseReserve && quoteReserve) {
+ const bal = new BN(out.token_balance);
+ const out_q = bal.mul(quoteReserve).div(baseReserve.add(bal));
+ out.estimated_sol_value = lamportsToSol(out_q);
+ } else {
+ out.estimated_sol_value = null;
+ }
+ }
+ out.venue = 'amm';
+ out.pool = poolKey.toBase58();
+ } catch (e) {
+ console.error('[pumpfun/portfolio] amm quote failed', e);
+ out.estimated_sol_value = null;
+ out.error = 'amm_quote_failed';
+ }
+ }
+ if (typeof out.estimated_sol_value === 'number') {
+ out.unrealized_pnl_sol = out.estimated_sol_value + out.sol_out - out.sol_in;
+ } else {
out.unrealized_pnl_sol = null;
- return out;
}
- const expectedSol = getSellSolAmountFromTokenAmount({
- global,
- feeConfig: null,
- mintSupply: state.bondingCurve.tokenTotalSupply,
- bondingCurve: state.bondingCurve,
- amount: new BN(out.token_balance),
- });
- out.estimated_sol_value = lamportsToSol(expectedSol);
- out.unrealized_pnl_sol = out.estimated_sol_value + out.sol_out - out.sol_in;
} catch (err) {
out.error = out.error || 'curve_quote_failed';
}
diff --git a/api/agents/pumpfun/sell.js b/api/agents/pumpfun/sell.js
index bd70da90e..c4d67d26c 100644
--- a/api/agents/pumpfun/sell.js
+++ b/api/agents/pumpfun/sell.js
@@ -125,6 +125,25 @@ export default async function handler(req, res, id) {
)
`.catch((e) => console.error('[pumpfun/sell] log failed', e));
+ try {
+ const [m] = await sql`
+ select id from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1
+ `;
+ if (m) {
+ await sql`
+ INSERT INTO pump_agent_trades
+ (mint_id, user_id, wallet, direction, route, sol_amount, token_amount, slippage_bps, tx_signature, network)
+ VALUES
+ (${m.id}, ${auth.userId}, ${keypair.publicKey.toBase58()}, 'sell',
+ 'bonding_curve', ${expectedSolStr || null}, ${body.tokenAmount},
+ ${body.slippageBps || null}, ${signature}, ${body.network})
+ ON CONFLICT (tx_signature, network) DO NOTHING
+ `;
+ }
+ } catch (e) {
+ console.error('[pumpfun/sell] trade index failed', e);
+ }
+
return json(res, 200, {
data: {
signature,
diff --git a/api/agents/pumpfun/swap.js b/api/agents/pumpfun/swap.js
index 0cff304b4..f75fb8717 100644
--- a/api/agents/pumpfun/swap.js
+++ b/api/agents/pumpfun/swap.js
@@ -1,26 +1,28 @@
// POST /api/agents/:id/pumpfun/swap
-// Buy or sell a pump.fun token from the agent's Solana wallet.
-// While the token is on the bonding curve, uses @pump-fun/pump-sdk.
-// After graduation (AMM), uses @pump-fun/pump-swap-sdk.
+// AMM swap for graduated pump.fun tokens via @pump-fun/pump-swap-sdk.
+// If the requested mint has not graduated yet, the request is auto-routed
+// to the bonding-curve buy/sell endpoint so callers don't need to know.
//
// Body: { mint, side: 'buy'|'sell', solAmount?, tokenAmount?, slippageBps?, network? }
-// - For buy: provide solAmount (SOL to spend). tokenAmount can be 0 (sdk computes).
-// - For sell: provide tokenAmount (raw smallest-units). solAmount is min-out.
-// - slippageBps: 0–10000 (default 500 = 5%)
+// side='buy' → spend `solAmount` SOL (decimal) for `mint`
+// side='sell' → sell `tokenAmount` (base-unit integer string) for SOL
+// slippageBps: 0–10_000 (default 500 = 5%)
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
import { cors, json, method, readJson, error } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
-import { PublicKey, Transaction } from '@solana/web3.js';
+import { checkBuyAllowed } from '../../_lib/agent-spend-policy.js';
+import { sql } from '../../_lib/db.js';
+import { Transaction, PublicKey } from '@solana/web3.js';
import { z } from 'zod';
const bodySchema = z.object({
- mint: z.string().trim().min(32).max(64),
+ mint: z.string().min(32).max(64),
side: z.enum(['buy', 'sell']),
- solAmount: z.number().nonnegative().optional(),
+ solAmount: z.number().nonnegative().max(1000).optional(),
tokenAmount: z.string().regex(/^\d+$/).optional(),
- slippageBps: z.number().int().min(0).max(10000).default(500),
+ slippageBps: z.number().int().min(0).max(10_000).default(500),
network: z.enum(['mainnet', 'devnet']).default('mainnet'),
});
@@ -47,82 +49,76 @@ export default async function handler(req, res, id) {
} catch (e) {
return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
}
+ if (body.side === 'buy' && !body.solAmount)
+ return error(res, 400, 'validation_error', 'side=buy requires solAmount');
+ if (body.side === 'sell' && !body.tokenAmount)
+ return error(res, 400, 'validation_error', 'side=sell requires tokenAmount');
- const loaded = await loadAgentForSigning(id, auth.userId);
+ const loaded = await loadAgentForSigning(id, auth.userId, {
+ reason: `pumpfun.swap.${body.side}`,
+ meta: { mint: body.mint, network: body.network },
+ });
if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
- const { keypair } = loaded;
+ const { keypair, meta } = loaded;
+
+ if (body.side === 'buy') {
+ const blocked = await checkBuyAllowed({
+ agentId: id, meta, mint: body.mint, solAmount: body.solAmount,
+ });
+ if (blocked) return error(res, blocked.status, blocked.code, blocked.msg);
+ }
const conn = solanaConnection(body.network);
const mint = new PublicKey(body.mint);
+
+ // Detect graduation. If still on bonding curve, delegate to /buy or /sell.
+ const { PumpSdk, bondingCurvePda } = await import('@pump-fun/pump-sdk');
+ const pumpSdk = new PumpSdk();
+ const bcInfo = await conn.getAccountInfo(bondingCurvePda(mint));
+ const bc = bcInfo ? pumpSdk.decodeBondingCurveNullable(bcInfo) : null;
+ const graduated = !bc || bc.complete;
+
+ if (!graduated) {
+ return error(
+ res,
+ 409,
+ 'not_graduated',
+ `mint is still on the bonding curve — use /api/agents/${id}/pumpfun/${body.side} instead`,
+ );
+ }
+
+ // AMM path.
+ const { PumpAmmSdk, OnlinePumpAmmSdk, canonicalPumpPoolPda } = await import(
+ '@pump-fun/pump-swap-sdk'
+ );
const BN = (await import('bn.js')).default;
- const { TOKEN_PROGRAM_ID } = await import('@solana/spl-token').catch(() => ({}));
- const tokenProgram = TOKEN_PROGRAM_ID || new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
+ const amm = new PumpAmmSdk();
+ const online = new OnlinePumpAmmSdk(conn);
- const { PumpSdk } = await import('@pump-fun/pump-sdk');
- const sdk = new PumpSdk();
+ const poolKey = canonicalPumpPoolPda(mint);
+ const swapState = await online.swapSolanaState(poolKey, keypair.publicKey).catch(async (err) => {
+ // Fall back: pool account may not be initialized (race after graduation).
+ console.error('[pumpfun/swap] swapSolanaState failed', err);
+ return online.swapSolanaStateNoPool(poolKey, keypair.publicKey);
+ });
- // Read bonding curve to decide bonding-curve vs AMM path.
- const { bondingCurvePda } = await import('@pump-fun/pump-sdk');
- const bcInfo = await conn.getAccountInfo(bondingCurvePda(mint));
+ const slippage = body.slippageBps / 10_000;
let instructions;
- if (bcInfo && !sdk.decodeBondingCurveNullable(bcInfo)?.complete) {
- const { OnlinePumpSdk } = await import('@pump-fun/pump-sdk');
- const online = new OnlinePumpSdk(conn);
- const global = await online.fetchGlobal();
- const bondingCurve = sdk.decodeBondingCurve(bcInfo);
- const slip = body.slippageBps / 100; // sdk takes a percentage
-
- if (body.side === 'buy') {
- const { associatedUserAccountInfo } = await online.fetchBuyState(mint, keypair.publicKey, tokenProgram);
- instructions = await sdk.buyInstructions({
- global,
- bondingCurveAccountInfo: bcInfo,
- bondingCurve,
- associatedUserAccountInfo,
- mint,
- user: keypair.publicKey,
- amount: new BN(body.tokenAmount || '0'),
- solAmount: new BN(Math.floor((body.solAmount || 0) * 1e9)),
- slippage: slip,
- tokenProgram,
- });
- } else {
- instructions = await sdk.sellInstructions({
- global,
- bondingCurveAccountInfo: bcInfo,
- bondingCurve,
- mint,
- user: keypair.publicKey,
- amount: new BN(body.tokenAmount || '0'),
- solAmount: new BN(Math.floor((body.solAmount || 0) * 1e9)),
- slippage: slip,
- tokenProgram,
- mayhemMode: false,
- });
- }
- } else {
- // Graduated → AMM swap via pump-swap-sdk.
- const swap = await import('@pump-fun/pump-swap-sdk');
- const { OnlinePumpAmmSdk } = swap;
- const amm = new OnlinePumpAmmSdk(conn);
+ let quotedAmount;
+ try {
if (body.side === 'buy') {
- instructions = await swap.buyQuoteInput({
- amm,
- baseMint: mint,
- user: keypair.publicKey,
- quoteAmount: new BN(Math.floor((body.solAmount || 0) * 1e9)),
- slippageBps: body.slippageBps,
- });
+ const quoteLamports = new BN(Math.floor(body.solAmount * 1e9));
+ instructions = await amm.buyQuoteInput(swapState, quoteLamports, slippage);
+ quotedAmount = { quote_lamports: quoteLamports.toString() };
} else {
- instructions = await swap.sellBaseInput({
- amm,
- baseMint: mint,
- user: keypair.publicKey,
- baseAmount: new BN(body.tokenAmount || '0'),
- slippageBps: body.slippageBps,
- });
+ const baseAmount = new BN(body.tokenAmount);
+ instructions = await amm.sellBaseInput(swapState, baseAmount, slippage);
+ quotedAmount = { base_amount: baseAmount.toString() };
}
+ } catch (err) {
+ console.error('[pumpfun/swap] build failed', err);
+ return error(res, 422, 'build_failed', err.message || 'could not build swap ix');
}
const tx = new Transaction().add(...instructions);
@@ -140,11 +136,34 @@ export default async function handler(req, res, id) {
return error(res, 502, 'rpc_error', err.message || 'transaction failed');
}
+ await sql`
+ INSERT INTO agent_actions (agent_id, type, payload, source_skill)
+ VALUES (
+ ${id},
+ ${`pumpfun.swap.${body.side}`},
+ ${JSON.stringify({
+ mint: body.mint,
+ side: body.side,
+ ...(body.side === 'buy'
+ ? { solAmount: body.solAmount }
+ : { tokenAmount: body.tokenAmount }),
+ slippageBps: body.slippageBps,
+ signature,
+ network: body.network,
+ venue: 'amm',
+ ...quotedAmount,
+ })}::jsonb,
+ ${'pumpfun'}
+ )
+ `.catch((e) => console.error('[pumpfun/swap] log failed', e));
+
return json(res, 200, {
data: {
signature,
mint: body.mint,
side: body.side,
+ venue: 'amm',
+ pool: poolKey.toBase58(),
explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
},
});
diff --git a/api/agents/solana-attest-event.js b/api/agents/solana-attest-event.js
index 1abd2f8f1..a72b13bdd 100644
--- a/api/agents/solana-attest-event.js
+++ b/api/agents/solana-attest-event.js
@@ -30,6 +30,7 @@ import { cors, json, method, wrap, error } from '../_lib/http.js';
import { parse } from '../_lib/validate.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { RPC, KIND_MAP } from '../_lib/solana-attestations.js';
+import { recordEvent } from '../_lib/usage.js';
const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');
const REPLAY_WINDOW_SECS = 5 * 60;
@@ -113,6 +114,8 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
+ const startedAt = Date.now();
+
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
@@ -135,7 +138,7 @@ export default wrap(async (req, res) => {
// Confirm the agent exists in our registry on the declared network.
const [agent] = await sql`
- select id from agent_identities
+ select id, user_id from agent_identities
where meta->'onchain'->>'sol_asset' = ${body.agent_asset}
or meta->>'sol_mint_address' = ${body.agent_asset}
limit 1
@@ -243,8 +246,26 @@ export default wrap(async (req, res) => {
and payload->>'event_id' = ${body.event_id}
limit 1
`;
+ recordEvent({
+ userId: agent.user_id,
+ agentId: agent.id,
+ kind: 'attest_event',
+ tool: `pumpkit.${body.event_type}`,
+ status: 'deduped',
+ latencyMs: Date.now() - startedAt,
+ meta: { network: body.network, event_id: body.event_id, signature: winner?.signature ?? null },
+ });
return json(res, 200, { data: { signature: winner?.signature ?? null, deduped: true } });
}
+ recordEvent({
+ userId: agent.user_id,
+ agentId: agent.id,
+ kind: 'attest_event',
+ tool: `pumpkit.${body.event_type}`,
+ status: 'ok',
+ latencyMs: Date.now() - startedAt,
+ meta: { network: body.network, event_id: body.event_id, signature, kind: payload.kind },
+ });
return json(res, 201, { data: { signature, kind: payload.kind, deduped: false } });
});
diff --git a/api/agents/solana-card.js b/api/agents/solana-card.js
index 83d3ae6df..528488b20 100644
--- a/api/agents/solana-card.js
+++ b/api/agents/solana-card.js
@@ -111,6 +111,13 @@ export default wrap(async (req, res) => {
owner: a.owner,
passport_url: `${origin}/agent-passport.html?asset=${asset}&network=${network}`,
...(a.meta?.vanity_prefix ? { vanity_prefix: a.meta.vanity_prefix } : {}),
+ ...(a.meta?.solana_address ? {
+ operator_wallet: {
+ address: a.meta.solana_address,
+ ...(a.meta.solana_vanity_prefix ? { vanity_prefix: a.meta.solana_vanity_prefix } : {}),
+ ...(a.meta.solana_wallet_source ? { source: a.meta.solana_wallet_source } : {}),
+ },
+ } : {}),
},
skills: a.skills || [],
endpoints: {
diff --git a/api/agents/solana-reputation.js b/api/agents/solana-reputation.js
index 1cdd290b6..b142512f4 100644
--- a/api/agents/solana-reputation.js
+++ b/api/agents/solana-reputation.js
@@ -136,75 +136,58 @@ export default wrap(async (req, res) => {
select last_indexed_at from solana_attestations_cursor where agent_asset = ${asset} limit 1
`;
- // Pump.fun off-chain signals: claim/graduation activity attached to the
- // agent's wallet. Aggregated as a positive/negative weight contribution.
- let pumpfunSignals = { count: 0, weight: 0, by_kind: {} };
- try {
- const rows = await sql`
- select kind, count(*)::int as n, coalesce(sum(weight), 0)::float as w
- from pumpfun_signals
- where agent_asset = ${asset}
- group by kind
- `;
- const byKind = {};
- let total = 0,
- weight = 0;
- for (const r of rows) {
- byKind[r.kind] = { count: r.n, weight: Number(r.w.toFixed(3)) };
- total += r.n;
- weight += r.w;
- }
- pumpfunSignals = { count: total, weight: Number(weight.toFixed(3)), by_kind: byKind };
- } catch {
- // pumpfun_signals table may not exist yet — silently ignore.
+ // Pump.fun off-chain signals (claim/graduation activity).
+ const pumpfunRows = await sql`
+ select kind, count(*)::int as n, coalesce(sum(weight), 0)::float as w
+ from pumpfun_signals
+ where agent_asset = ${asset}
+ group by kind
+ `;
+ const pumpfunByKind = {};
+ let pumpfunTotal = 0, pumpfunWeight = 0;
+ for (const r of pumpfunRows) {
+ pumpfunByKind[r.kind] = { count: r.n, weight: Number(r.w.toFixed(3)) };
+ pumpfunTotal += r.n;
+ pumpfunWeight += r.w;
}
+ const pumpfunSignals = {
+ count: pumpfunTotal,
+ weight: Number(pumpfunWeight.toFixed(3)),
+ by_kind: pumpfunByKind,
+ };
- // Pump.fun token activity from indexer snapshot: graduation + recent tx
- // count contribute small positive weights to overall agent reputation.
- let tokenActivity = { graduated: false, recent_tx_count: 0, trade_count: 0, weight: 0 };
- try {
- const [row] = await sql`
- select s.graduated, s.recent_tx_count,
- (select count(*)::int from pump_agent_trades t where t.mint_id = m.id) as trade_count
- from pump_agent_stats s
- join pump_agent_mints m on m.id = s.mint_id
- where m.mint = ${asset} and m.network = ${network}
- limit 1
- `;
- if (row) {
- const w =
- (row.graduated ? 0.3 : 0) +
- Math.min(0.4, (row.recent_tx_count || 0) * 0.005) +
- Math.min(0.3, (row.trade_count || 0) * 0.01);
- tokenActivity = {
- graduated: !!row.graduated,
- recent_tx_count: row.recent_tx_count || 0,
- trade_count: row.trade_count || 0,
- weight: Number(w.toFixed(3)),
- };
- }
- } catch {
- // tables not present
- }
+ // Pump.fun token activity (graduation + recent tx + trade counts).
+ const [actRow] = await sql`
+ select s.graduated, s.recent_tx_count,
+ (select count(*)::int from pump_agent_trades t where t.mint_id = m.id) as trade_count
+ from pump_agent_stats s
+ join pump_agent_mints m on m.id = s.mint_id
+ where m.mint = ${asset} and m.network = ${network}
+ limit 1
+ `;
+ const tokenActivity = actRow ? {
+ graduated: !!actRow.graduated,
+ recent_tx_count: actRow.recent_tx_count || 0,
+ trade_count: actRow.trade_count || 0,
+ weight: Number((
+ (actRow.graduated ? 0.3 : 0)
+ + Math.min(0.4, (actRow.recent_tx_count || 0) * 0.005)
+ + Math.min(0.3, (actRow.trade_count || 0) * 0.01)
+ ).toFixed(3)),
+ } : { graduated: false, recent_tx_count: 0, trade_count: 0, weight: 0 };
- // Pump.fun agent-payments signal: confirmed acceptPayment receipts add a
- // volume-weighted, Sybil-resistant reputation lane on top of memo attestations.
- let pumpPayments = { confirmed_count: 0, unique_payers: 0, total_atomics: '0' };
- try {
- const [row] = await sql`
- select
- count(*) filter (where p.status='confirmed')::int as confirmed_count,
- count(distinct p.payer_wallet) filter (where p.status='confirmed')::int as unique_payers,
- coalesce(sum(p.amount_atomics) filter (where p.status='confirmed'), 0)::text as total_atomics
- from pump_agent_payments p
- join pump_agent_mints m on m.id = p.mint_id
- join agent_identities a on a.id = m.agent_id
- where (a.meta->>'sol_mint_address') = ${asset} and m.network = ${network}
- `;
- if (row) pumpPayments = row;
- } catch {
- // pump_agent_payments table may not exist yet (migration not applied) — silently ignore.
- }
+ // Pump.fun agent-payments signal: confirmed acceptPayment receipts.
+ const [payRow] = await sql`
+ select
+ count(*) filter (where p.status='confirmed')::int as confirmed_count,
+ count(distinct p.payer_wallet) filter (where p.status='confirmed')::int as unique_payers,
+ coalesce(sum(p.amount_atomics) filter (where p.status='confirmed'), 0)::text as total_atomics
+ from pump_agent_payments p
+ join pump_agent_mints m on m.id = p.mint_id
+ join agent_identities a on a.id = m.agent_id
+ where (a.meta->>'sol_mint_address') = ${asset} and m.network = ${network}
+ `;
+ const pumpPayments = payRow || { confirmed_count: 0, unique_payers: 0, total_atomics: '0' };
return json(res, 200, {
agent: asset,
diff --git a/api/cron/solana-attest-event-cleanup.js b/api/cron/solana-attest-event-cleanup.js
new file mode 100644
index 000000000..c52b56541
--- /dev/null
+++ b/api/cron/solana-attest-event-cleanup.js
@@ -0,0 +1,41 @@
+/**
+ * Stale-claim reaper for the pumpkit -> attestation bridge.
+ *
+ * Drops solana_attest_event_claims rows where the leader crashed or the
+ * Solana RPC timed out before a signature could be recorded. The handler
+ * deletes its own claim on tx-send failure, but a process crash between
+ * `INSERT claim` and `delete on throw` leaves an orphan that would block
+ * future retries forever.
+ *
+ * Runs every 10 minutes via Vercel Cron (vercel.json). Manually triggerable
+ * with `Authorization: Bearer $CRON_SECRET`.
+ */
+
+import { sql } from '../_lib/db.js';
+import { cors, error, json, wrap } from '../_lib/http.js';
+
+const STALE_AFTER_SECS = 60 * 60; // 1 hour
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ const auth = req.headers['authorization'] || '';
+ const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron && expected && auth !== expected) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+
+ const result = await sql`
+ delete from solana_attest_event_claims
+ where signature is null
+ and claimed_at < now() - (${STALE_AFTER_SECS} || ' seconds')::interval
+ returning agent_asset, network, event_id, claimed_at
+ `;
+
+ return json(res, 200, {
+ deleted: result.length,
+ stale_after_secs: STALE_AFTER_SECS,
+ samples: result.slice(0, 10),
+ });
+});
diff --git a/api/mcp.js b/api/mcp.js
index 5e368038d..3469bfad9 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -72,10 +72,16 @@ export default wrap(async (req, res) => {
} catch (err) {
return sendX402Error(res, requirements, err);
}
- // Anonymous paid caller — synthesize an auth principal scoped to MCP read tools.
+ // Anonymous paid caller — synthesize an auth principal scoped to public-read tools.
+ // userId is null because usage_events.user_id is a UUID FK; the payer wallet is
+ // kept on the auth object so handlers and rate limits can key off of it.
auth = {
- userId: `x402:${x402Ctx.payer || 'unknown'}`,
- scope: 'avatars:read profile',
+ userId: null,
+ rateKey: `x402:${x402Ctx.payer || 'anon'}`,
+ // Pay-per-call callers have no user account, so they cannot read or
+ // write account-scoped data. They get only the no-scope public tools
+ // (search_public_avatars, validate/inspect/optimize_model, solana_*).
+ scope: '',
source: 'x402',
payer: x402Ctx.payer,
};
@@ -94,7 +100,7 @@ export default wrap(async (req, res) => {
return sendJsonRpcError(res, null, -32000, 'rate_limited', {
retry_after: Math.ceil((ipRl.reset - Date.now()) / 1000),
});
- const userRl = await limits.mcpUser(auth.userId);
+ const userRl = await limits.mcpUser(auth.userId || auth.rateKey || clientIp(req));
if (!userRl.success)
return sendJsonRpcError(res, null, -32000, 'rate_limited', {
retry_after: Math.ceil((userRl.reset - Date.now()) / 1000),
@@ -669,7 +675,7 @@ const TOOLS = {
validate_model: {
async handler(args, auth) {
- const rl = await limits.mcpValidate(auth.userId);
+ const rl = await limits.mcpValidate(auth.userId || auth.rateKey);
if (!rl.success)
throw rpcError(-32000, 'rate_limited', {
retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
@@ -705,7 +711,7 @@ const TOOLS = {
inspect_model: {
async handler(args, auth) {
- const rl = await limits.mcpInspect(auth.userId);
+ const rl = await limits.mcpInspect(auth.userId || auth.rateKey);
if (!rl.success)
throw rpcError(-32000, 'rate_limited', {
retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
@@ -721,7 +727,7 @@ const TOOLS = {
optimize_model: {
async handler(args, auth) {
- const rl = await limits.mcpOptimize(auth.userId);
+ const rl = await limits.mcpOptimize(auth.userId || auth.rateKey);
if (!rl.success)
throw rpcError(-32000, 'rate_limited', {
retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
@@ -1040,7 +1046,15 @@ async function handleSse(req, res) {
// Unauthenticated callers without an X-PAYMENT header get an x402 challenge
// so x402scan / x402 clients can discover the price. Invalid bearers still
// get 401 with WWW-Authenticate so OAuth clients can re-auth correctly.
- if (!bearer && !req.headers['x-payment']) return sendX402Challenge(req, res);
+ if (!bearer && !req.headers['x-payment']) {
+ return send402(
+ res,
+ paymentRequirements({
+ resource: resolveResourceUrl(req, '/api/mcp'),
+ description: 'MCP tool call',
+ }),
+ );
+ }
const auth = await authenticateBearer(bearer, { audience: env.MCP_RESOURCE });
if (!auth) return send401(res, 'missing or invalid access token');
res.statusCode = 405;
@@ -1059,39 +1073,6 @@ function quoteString(s) {
return `"${String(s).replace(/[\\"]/g, '\\$&')}"`;
}
-// x402 payment-required challenge (spec: https://x402.org).
-// Solana USDC, fixed price 0.001 USDC = 1000 base units (6 decimals).
-const X402_PAY_TO = 'BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN';
-const X402_USDC_SOLANA_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
-
-function sendX402Challenge(req, res) {
- const proto = (req.headers['x-forwarded-proto'] || 'https').toString().split(',')[0].trim();
- const host = (req.headers['x-forwarded-host'] || req.headers.host || '').toString();
- const resource = host ? `${proto}://${host}/api/mcp` : `${env.APP_ORIGIN}/api/mcp`;
- res.statusCode = 402;
- res.setHeader('content-type', 'application/json; charset=utf-8');
- res.end(
- JSON.stringify({
- x402Version: 1,
- error: 'X-PAYMENT header is required',
- accepts: [
- {
- scheme: 'exact',
- network: 'solana',
- maxAmountRequired: '1000',
- resource,
- description: 'MCP tool call',
- mimeType: 'application/json',
- payTo: X402_PAY_TO,
- maxTimeoutSeconds: 60,
- asset: X402_USDC_SOLANA_MINT,
- extra: { name: 'USDC', decimals: 6 },
- },
- ],
- }),
- );
-}
-
function send401(res, msg) {
const resource = env.MCP_RESOURCE;
res.statusCode = 401;
diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.js
new file mode 100644
index 000000000..802508b91
--- /dev/null
+++ b/api/pump-fun-mcp.js
@@ -0,0 +1,432 @@
+// POST /api/pump-fun-mcp
+//
+// Real, in-house JSON-RPC 2.0 MCP server exposing read-only pump.fun tools to
+// the in-page <agent-3d> skill bundle (public/skills/pump-fun/).
+//
+// Tools backed by on-chain reads (no external indexer required):
+// - getBondingCurve → @pump-fun/pump-sdk fetchBondingCurve
+// - getTokenDetails → @solana/web3.js getAccountInfo + Metaplex metadata
+// - getTokenHolders → connection.getTokenLargestAccounts + concentration
+//
+// Tools that require indexed/aggregate data are routed through the existing
+// pumpfunMcp client (api/_lib/pumpfun-mcp.js → upstream pumpfun-claims-bot).
+// When PUMPFUN_BOT_URL is unset they return JSON-RPC error -32004 ("indexer
+// not configured") — never a fabricated payload.
+//
+// Methods: initialize, tools/list, tools/call. CORS open (read-only data).
+// Rate-limited by IP via limits.mcpIp.
+
+import { cors, json, method, wrap, readJson, error } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { getPumpSdk, getConnection, solanaPubkey } from './_lib/pump.js';
+import { pumpfunMcp, pumpfunBotEnabled } from './_lib/pumpfun-mcp.js';
+
+// ── Tool registry ──────────────────────────────────────────────────────────
+
+const TOOLS = [
+ {
+ name: 'searchTokens',
+ description: 'Search pump.fun tokens by name, symbol, or mint address.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string' },
+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 },
+ },
+ required: ['query'],
+ },
+ },
+ {
+ name: 'getTokenDetails',
+ description: 'Full details for a specific pump.fun token by mint address.',
+ inputSchema: {
+ type: 'object',
+ properties: { mint: { type: 'string' } },
+ required: ['mint'],
+ },
+ },
+ {
+ name: 'getBondingCurve',
+ description:
+ 'Bonding curve analysis: real reserves, virtual reserves, and graduation progress (on-chain).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ },
+ required: ['mint'],
+ },
+ },
+ {
+ name: 'getTokenTrades',
+ description: 'Recent buy/sell history for a token.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ limit: { type: 'integer', minimum: 1, maximum: 200, default: 50 },
+ },
+ required: ['mint'],
+ },
+ },
+ {
+ name: 'getTrendingTokens',
+ description: 'Top pump.fun tokens by market cap.',
+ inputSchema: {
+ type: 'object',
+ properties: { limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },
+ },
+ },
+ {
+ name: 'getNewTokens',
+ description: 'Most recently launched pump.fun tokens.',
+ inputSchema: {
+ type: 'object',
+ properties: { limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },
+ },
+ },
+ {
+ name: 'getGraduatedTokens',
+ description: 'Tokens that graduated from the bonding curve to Raydium AMM.',
+ inputSchema: {
+ type: 'object',
+ properties: { limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },
+ },
+ },
+ {
+ name: 'getKingOfTheHill',
+ description: 'Highest-market-cap token still on the bonding curve.',
+ inputSchema: { type: 'object', properties: {} },
+ },
+ {
+ name: 'getCreatorProfile',
+ description: 'All tokens by a creator wallet, with rug-pull risk flags.',
+ inputSchema: {
+ type: 'object',
+ properties: { creator: { type: 'string' } },
+ required: ['creator'],
+ },
+ },
+ {
+ name: 'getTokenHolders',
+ description: 'Top holders of a token with concentration analysis (on-chain).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ limit: { type: 'integer', minimum: 1, maximum: 20, default: 10 },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ },
+ required: ['mint'],
+ },
+ },
+];
+
+// ── On-chain handlers ──────────────────────────────────────────────────────
+
+const TOTAL_PUMP_TOKEN_SUPPLY = 1_000_000_000; // 1B pump.fun standard
+const GRADUATION_REAL_SOL_LAMPORTS = 85_000_000_000n; // ~85 SOL — heuristic
+
+async function handleGetBondingCurve({ mint, network = 'mainnet' }) {
+ const pk = solanaPubkey(mint);
+ if (!pk) throw rpcError(-32602, 'invalid mint');
+ const { sdk } = await getPumpSdk({ network });
+ let curve;
+ try {
+ if (sdk.fetchBuyState) {
+ const state = await sdk.fetchBuyState(pk, pk);
+ curve = state.bondingCurve;
+ } else if (sdk.fetchBondingCurve) {
+ curve = await sdk.fetchBondingCurve(pk);
+ }
+ } catch (e) {
+ throw rpcError(-32004, `bonding curve unavailable: ${e?.message || 'unknown'}`);
+ }
+ if (!curve) throw rpcError(-32004, 'no bonding curve found for this mint');
+
+ const realSol = BigInt(curve.realSolReserves?.toString?.() ?? '0');
+ const realToken = BigInt(curve.realTokenReserves?.toString?.() ?? '0');
+ const virtSol = BigInt(curve.virtualSolReserves?.toString?.() ?? '0');
+ const virtToken = BigInt(curve.virtualTokenReserves?.toString?.() ?? '0');
+ const complete = !!curve.complete;
+ // Graduation % heuristic: complete=100, else realSol/graduationTarget * 100.
+ const graduationPercent = complete
+ ? 100
+ : Number((realSol * 10000n) / GRADUATION_REAL_SOL_LAMPORTS) / 100;
+
+ return {
+ mint,
+ network,
+ complete,
+ graduationPercent,
+ solReserves: (Number(realSol) / 1e9).toFixed(4),
+ tokenReserves: realToken.toString(),
+ virtualSolReserves: virtSol.toString(),
+ virtualTokenReserves: virtToken.toString(),
+ };
+}
+
+async function handleGetTokenDetails({ mint, network = 'mainnet' }) {
+ const pk = solanaPubkey(mint);
+ if (!pk) throw rpcError(-32602, 'invalid mint');
+ const connection = getConnection({ network });
+ const [{ MintLayout }, { PublicKey }] = await Promise.all([
+ import('@solana/spl-token'),
+ import('@solana/web3.js'),
+ ]);
+
+ const info = await connection.getAccountInfo(pk);
+ if (!info) throw rpcError(-32004, 'mint account not found');
+ const mintAccount = MintLayout.decode(info.data);
+
+ // Best-effort Metaplex Token Metadata read. PDA = [b"metadata", program, mint].
+ const METADATA_PROGRAM = new PublicKey('metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s');
+ const [metadataPda] = PublicKey.findProgramAddressSync(
+ [Buffer.from('metadata'), METADATA_PROGRAM.toBuffer(), pk.toBuffer()],
+ METADATA_PROGRAM,
+ );
+ let name = null;
+ let symbol = null;
+ let uri = null;
+ try {
+ const metaInfo = await connection.getAccountInfo(metadataPda);
+ if (metaInfo) {
+ // Layout: 1 key + 32 updateAuthority + 32 mint + 4-byte string-length-prefixed name/symbol/uri.
+ const buf = metaInfo.data;
+ let cursor = 1 + 32 + 32;
+ const readStr = (max) => {
+ const len = buf.readUInt32LE(cursor);
+ cursor += 4;
+ const slice = buf.slice(cursor, cursor + len);
+ cursor += max;
+ return slice.toString('utf8').replace(/\0+$/g, '').trim();
+ };
+ name = readStr(32);
+ symbol = readStr(10);
+ uri = readStr(200);
+ }
+ } catch {
+ // Metadata is optional — proceed without it.
+ }
+
+ const supply = mintAccount.supply.toString();
+ const decimals = mintAccount.decimals;
+
+ return {
+ mint,
+ name,
+ symbol,
+ uri,
+ decimals,
+ supply,
+ mintAuthority: mintAccount.mintAuthorityOption ? mintAccount.mintAuthority.toString() : null,
+ freezeAuthority: mintAccount.freezeAuthorityOption
+ ? mintAccount.freezeAuthority.toString()
+ : null,
+ };
+}
+
+async function handleGetTokenHolders({ mint, limit = 10, network = 'mainnet' }) {
+ const pk = solanaPubkey(mint);
+ if (!pk) throw rpcError(-32602, 'invalid mint');
+ const connection = getConnection({ network });
+ let largest;
+ try {
+ largest = await connection.getTokenLargestAccounts(pk);
+ } catch (e) {
+ throw rpcError(-32004, `holders unavailable: ${e?.message || 'rpc error'}`);
+ }
+ const accounts = (largest?.value || []).slice(0, Math.min(20, Math.max(1, limit)));
+ const total = accounts.reduce((sum, a) => sum + Number(a.uiAmount || 0), 0);
+ const holders = accounts.map((a) => ({
+ address: a.address.toString(),
+ amount: a.amount,
+ uiAmount: a.uiAmount,
+ percent: total > 0 ? (Number(a.uiAmount || 0) / total) * 100 : 0,
+ }));
+ const topHolderPercent = holders[0]?.percent ?? 0;
+ return {
+ mint,
+ count: holders.length,
+ topHolderPercent,
+ holders,
+ };
+}
+
+// ── Indexer-backed handlers (route through pumpfunMcp) ─────────────────────
+
+function indexerOrUnavailable(name) {
+ return async (args) => {
+ if (!pumpfunBotEnabled()) {
+ throw rpcError(
+ -32004,
+ `tool "${name}" requires the pump.fun indexer (PUMPFUN_BOT_URL) to be configured`,
+ );
+ }
+ // Map our tool names to the upstream bot's tool surface.
+ const upstreamMap = {
+ searchTokens: { tool: 'searchTokens', args: { query: args.query, limit: args.limit } },
+ getTokenTrades: { tool: 'getTokenTrades', args: { mint: args.mint, limit: args.limit } },
+ getTrendingTokens: { tool: 'getTrendingTokens', args: { limit: args.limit } },
+ getNewTokens: { tool: 'getNewTokens', args: { limit: args.limit } },
+ getGraduatedTokens: { tool: 'getGraduatedTokens', args: { limit: args.limit } },
+ getKingOfTheHill: { tool: 'getKingOfTheHill', args: {} },
+ getCreatorProfile: { tool: 'getCreatorIntel', args: { wallet: args.creator } },
+ };
+ const upstream = upstreamMap[name];
+ if (!upstream) throw rpcError(-32601, `tool "${name}" not implemented`);
+ // Use the lower-level rpc-style call via callTool; pumpfunMcp's named
+ // methods cover only a subset, so fall back to a generic invocation.
+ const r = await pumpfunMcpCall(upstream.tool, upstream.args);
+ if (!r.ok) throw rpcError(-32004, r.error || 'indexer error');
+ return r.data;
+ };
+}
+
+// Generic tools/call against the upstream bot using the same transport that
+// pumpfunMcp uses internally. Encapsulated here so we don't leak transport
+// details into the route.
+async function pumpfunMcpCall(tool, args) {
+ if (tool === 'getCreatorIntel') return pumpfunMcp.creatorIntel({ wallet: args?.wallet });
+ if (tool === 'getRecentClaims') return pumpfunMcp.recentClaims({ limit: args?.limit });
+ if (tool === 'getGraduations') return pumpfunMcp.graduations({ limit: args?.limit });
+ // Fall through: not in the named surface — call raw rpc.
+ return rawBotCall(tool, args);
+}
+
+async function rawBotCall(tool, args) {
+ const url = process.env.PUMPFUN_BOT_URL;
+ if (!url) return { ok: false, error: 'PUMPFUN_BOT_URL not set' };
+ const headers = { 'content-type': 'application/json', accept: 'application/json' };
+ if (process.env.PUMPFUN_BOT_TOKEN)
+ headers.authorization = `Bearer ${process.env.PUMPFUN_BOT_TOKEN}`;
+ const ctrl = new AbortController();
+ const t = setTimeout(() => ctrl.abort(), 8000);
+ try {
+ const r = await fetch(url.replace(/\/$/, ''), {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: tool, arguments: args || {} },
+ }),
+ signal: ctrl.signal,
+ });
+ if (!r.ok) return { ok: false, error: `bot ${r.status}` };
+ const j = await r.json();
+ if (j.error) return { ok: false, error: j.error.message || 'rpc error' };
+ const payload = j.result?.structuredContent ?? j.result?.content ?? j.result;
+ return { ok: true, data: payload };
+ } catch (err) {
+ return {
+ ok: false,
+ error: err?.name === 'AbortError' ? 'timeout' : err?.message || 'fetch failed',
+ };
+ } finally {
+ clearTimeout(t);
+ }
+}
+
+// ── Dispatch ───────────────────────────────────────────────────────────────
+
+const HANDLERS = {
+ getBondingCurve: handleGetBondingCurve,
+ getTokenDetails: handleGetTokenDetails,
+ getTokenHolders: handleGetTokenHolders,
+ searchTokens: indexerOrUnavailable('searchTokens'),
+ getTokenTrades: indexerOrUnavailable('getTokenTrades'),
+ getTrendingTokens: indexerOrUnavailable('getTrendingTokens'),
+ getNewTokens: indexerOrUnavailable('getNewTokens'),
+ getGraduatedTokens: indexerOrUnavailable('getGraduatedTokens'),
+ getKingOfTheHill: indexerOrUnavailable('getKingOfTheHill'),
+ getCreatorProfile: indexerOrUnavailable('getCreatorProfile'),
+};
+
+function rpcError(code, message) {
+ const err = new Error(message);
+ err.rpcCode = code;
+ return err;
+}
+
+function rpcEnvelope(id, result, errObj) {
+ if (errObj) {
+ return { jsonrpc: '2.0', id: id ?? null, error: errObj };
+ }
+ return { jsonrpc: '2.0', id: id ?? null, result };
+}
+
+// ── HTTP entrypoint ────────────────────────────────────────────────────────
+
+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.mcpIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (e) {
+ return json(res, 400, rpcEnvelope(null, null, { code: -32700, message: 'parse error' }));
+ }
+
+ const { id = null, method: rpcMethod, params } = body || {};
+
+ if (rpcMethod === 'initialize') {
+ return json(
+ res,
+ 200,
+ rpcEnvelope(id, {
+ protocolVersion: '2024-11-05',
+ capabilities: { tools: {} },
+ serverInfo: { name: 'three.ws-pumpfun-mcp', version: '0.1.0' },
+ }),
+ );
+ }
+
+ if (rpcMethod === 'tools/list') {
+ return json(res, 200, rpcEnvelope(id, { tools: TOOLS }));
+ }
+
+ if (rpcMethod === 'tools/call') {
+ const name = params?.name;
+ const args = params?.arguments || {};
+ const handler = HANDLERS[name];
+ if (!handler) {
+ return json(
+ res,
+ 200,
+ rpcEnvelope(id, null, { code: -32601, message: `unknown tool: ${name}` }),
+ );
+ }
+ try {
+ const data = await handler(args);
+ // Mirror MCP content shape so existing skill clients can unwrap text.
+ return json(
+ res,
+ 200,
+ rpcEnvelope(id, {
+ content: [{ type: 'text', text: JSON.stringify(data) }],
+ structuredContent: data,
+ }),
+ );
+ } catch (err) {
+ const code = err.rpcCode || -32603;
+ return json(
+ res,
+ 200,
+ rpcEnvelope(id, null, { code, message: err.message || 'tool error' }),
+ );
+ }
+ }
+
+ return json(
+ res,
+ 200,
+ rpcEnvelope(id, null, { code: -32601, message: `unknown method: ${rpcMethod}` }),
+ );
+});
diff --git a/api/pump/by-agent.js b/api/pump/by-agent.js
index a752a26e9..37b93c81e 100644
--- a/api/pump/by-agent.js
+++ b/api/pump/by-agent.js
@@ -42,11 +42,22 @@ export default wrap(async (req, res) => {
from pump_buyback_runs where mint_id=${row.id}
`;
+ // Burns feed (separate from payments feed) — recent confirmed buyback runs
+ // for the dashboard / passport "🔥 burns" stream.
+ const burnsFeed = await sql`
+ select id, currency_mint, tx_signature, burn_amount, created_at
+ from pump_buyback_runs
+ where mint_id=${row.id} and status='confirmed'
+ order by created_at desc
+ limit 10
+ `;
+
return json(res, 200, {
data: {
...row,
stats: stats || { confirmed_payments: 0, unique_payers: 0, total_atomics: '0' },
burns: burnRow || { runs: 0, total_burned: '0' },
+ burns_feed: burnsFeed,
},
});
});
diff --git a/api/pump/payments-list.js b/api/pump/payments-list.js
index 0b421ccd2..016c2b65b 100644
--- a/api/pump/payments-list.js
+++ b/api/pump/payments-list.js
@@ -34,7 +34,7 @@ export default wrap(async (req, res) => {
? await sql`
select id, payer_wallet, currency_mint, amount_atomics, invoice_id,
start_time, end_time, status, skill_id, tool_name,
- tx_signature, created_at, confirmed_at
+ invoice_pda, tx_signature, created_at, confirmed_at
from pump_agent_payments
where mint_id=${agent.id}
order by created_at desc limit ${limit}
@@ -42,12 +42,37 @@ export default wrap(async (req, res) => {
: await sql`
select id, payer_wallet, currency_mint, amount_atomics, invoice_id,
start_time, end_time, status, skill_id, tool_name,
- tx_signature, created_at, confirmed_at
+ invoice_pda, tx_signature, created_at, confirmed_at
from pump_agent_payments
where mint_id=${agent.id} and status='confirmed'
order by confirmed_at desc nulls last limit ${limit}
`;
+ // Derive invoice PDAs for any rows that lack one (older rows pre-PDA backfill).
+ // We do it lazily here so the widget can deep-link without a backfill cron.
+ let pdaErrored = false;
+ const needsPda = rows.filter((r) => !r.invoice_pda && r.invoice_id);
+ if (needsPda.length > 0) {
+ try {
+ const [{ getInvoiceIdPDA }, { PublicKey }] = await Promise.all([
+ import('@pump-fun/agent-payments-sdk'),
+ import('@solana/web3.js'),
+ ]);
+ const BN = (await import('bn.js')).default || (await import('bn.js'));
+ const mintPk = new PublicKey(mint);
+ for (const r of needsPda) {
+ try {
+ const [pda] = getInvoiceIdPDA(mintPk, new BN(r.invoice_id));
+ r.invoice_pda = pda.toBase58();
+ } catch {
+ /* skip individual failures */
+ }
+ }
+ } catch {
+ pdaErrored = true;
+ }
+ }
+
const [agg] = await sql`
select
count(*)::int as total,
diff --git a/api/pump/portfolio.js b/api/pump/portfolio.js
new file mode 100644
index 000000000..386c93870
--- /dev/null
+++ b/api/pump/portfolio.js
@@ -0,0 +1,138 @@
+// GET /api/pump/portfolio?agentId=<uuid>&network=mainnet|devnet
+//
+// Real chain-direct portfolio for an agent's hot wallet. No third-party API,
+// no caching layer beyond the underlying RPC — every call queries the chain.
+//
+// Response:
+// {
+// data: {
+// address, network, lamports, sol,
+// holdings: [{ mint, amount, decimals, valueSol, priceSol }],
+// totalValueSol, totalCostBasisSol, unrealizedPnlSol, unrealizedPnlPct,
+// openPositions: [...] // joined with strategy ledger if available
+// }
+// }
+//
+// Cost-basis is read from agent_actions where source_skill='pump-fun-trade'
+// and type='buy'. If there's no recorded entry, that holding is reported with
+// costBasisSol = null (not zero — to avoid lying about PnL).
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { solanaConnection } from '../_lib/agent-pumpfun.js';
+import { PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';
+import { makeRuntime } from '../_lib/skill-runtime.js';
+
+const TOKEN_PROGRAM_ID = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const agentId = url.searchParams.get('agentId');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
+
+ const [agent] = await sql`
+ SELECT user_id, meta FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+ const address = agent.meta?.solana_address;
+ if (!address) return error(res, 409, 'conflict', 'agent has no solana wallet');
+
+ const conn = solanaConnection(network);
+ const owner = new PublicKey(address);
+
+ const [lamports, tokenResp, recentBuys] = await Promise.all([
+ conn.getBalance(owner),
+ conn.getParsedTokenAccountsByOwner(owner, { programId: TOKEN_PROGRAM_ID }),
+ sql`
+ SELECT payload, created_at FROM agent_actions
+ WHERE agent_id = ${agentId}
+ AND source_skill = 'pump-fun-trade'
+ AND type = 'buy'
+ ORDER BY created_at DESC
+ LIMIT 500
+ `.catch(() => []),
+ ]);
+
+ const holdings = tokenResp.value
+ .map((acc) => {
+ const info = acc.account.data.parsed.info;
+ return {
+ mint: info.mint,
+ amount: info.tokenAmount.uiAmount ?? 0,
+ decimals: info.tokenAmount.decimals,
+ };
+ })
+ .filter((h) => h.amount > 0);
+
+ // Cost basis from recorded buys.
+ const basisByMint = new Map();
+ for (const row of recentBuys) {
+ const p = row.payload || {};
+ if (!p.mint) continue;
+ const prev = basisByMint.get(p.mint) ?? { sol: 0, tokens: 0 };
+ prev.sol += Number(p.amountSol) || 0;
+ prev.tokens += Number(p.amountTokens) || 0;
+ basisByMint.set(p.mint, prev);
+ }
+
+ // Live price per holding via the read-only pump-fun MCP (parallelized).
+ const rt = makeRuntime();
+ const priced = await Promise.all(holdings.map(async (h) => {
+ const [curve, basis] = [
+ await rt.invoke('pump-fun.getBondingCurve', { mint: h.mint }).catch(() => ({ ok: false })),
+ basisByMint.get(h.mint),
+ ];
+ const priceSol = curve?.ok ? (curve.data?.priceSol ?? curve.data?.price ?? null) : null;
+ const valueSol = priceSol != null ? priceSol * h.amount : null;
+ const costBasisSol = basis ? basis.sol : null;
+ const unrealizedSol = valueSol != null && costBasisSol != null ? valueSol - costBasisSol : null;
+ return {
+ ...h,
+ priceSol,
+ valueSol,
+ costBasisSol,
+ unrealizedPnlSol: unrealizedSol,
+ unrealizedPnlPct: unrealizedSol != null && costBasisSol > 0 ? (unrealizedSol / costBasisSol) * 100 : null,
+ };
+ }));
+
+ const totalValueSol = priced.reduce((s, p) => s + (p.valueSol ?? 0), 0);
+ const totalCostBasisSol = priced.reduce((s, p) => s + (p.costBasisSol ?? 0), 0);
+ const unrealizedPnlSol = totalValueSol - totalCostBasisSol;
+
+ return json(res, 200, {
+ data: {
+ address,
+ network,
+ lamports,
+ sol: lamports / LAMPORTS_PER_SOL,
+ holdings: priced,
+ totalValueSol,
+ totalCostBasisSol,
+ unrealizedPnlSol,
+ unrealizedPnlPct: totalCostBasisSol > 0 ? (unrealizedPnlSol / totalCostBasisSol) * 100 : null,
+ },
+ });
+});
diff --git a/api/pump/strategy-run.js b/api/pump/strategy-run.js
index bf5419edb..69778e020 100644
--- a/api/pump/strategy-run.js
+++ b/api/pump/strategy-run.js
@@ -1,109 +1,132 @@
// 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.
+// Body:
+// strategy: <spec> required
+// durationSec: number 5..600
+// mode: 'simulate' | 'live' default 'simulate'
+// agentId: string required when mode='live'
+// network: 'mainnet' | 'devnet' default 'mainnet'
+//
+// In 'simulate' mode the read-only pump-fun MCP is queried for real holder /
+// curve / creator data, but trades are not signed (a SIMULATED:* sig is
+// returned so the orchestrator state machine still progresses). This is a
+// genuine dry-run against live chain state.
+//
+// In 'live' mode the caller must own an agent identity with a provisioned
+// Solana wallet (see /api/agents/:id/solana). The encrypted secret is loaded
+// server-side and used to actually sign + send buys/sells via the
+// pump-fun-trade skill.
+//
+// Each scan/exit/entry decision is streamed as it happens via SSE. A final
+// `event: done` carries the summary.
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { cors, method, error, readJson } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { makeRuntime } from '../_lib/skill-runtime.js';
+import { loadWallet } from '../_lib/solana-wallet.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: {} };
+const RPC = {
+ mainnet: process.env.SOLANA_MAINNET_RPC || 'https://api.mainnet-beta.solana.com',
+ devnet: process.env.SOLANA_DEVNET_RPC || 'https://api.devnet.solana.com',
+};
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+async function loadAgentWallet(agentId, userId) {
+ const [row] = await sql`
+ SELECT user_id, meta FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!row) throw Object.assign(new Error('agent not found'), { status: 404 });
+ if (row.user_id !== userId) throw Object.assign(new Error('not your agent'), { status: 403 });
+ const enc = row.meta?.encrypted_solana_secret;
+ if (!enc) throw Object.assign(new Error('agent has no solana wallet — provision via /api/agents/:id/solana'), { status: 409 });
+ const wallet = await loadWallet(enc);
+ return { wallet, address: wallet.publicKey.toBase58() };
}
export default async function handler(req, res) {
- if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) 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); }
+ 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));
+ const durationSec = Math.max(5, Math.min(600, Number(body.durationSec) || 30));
+ const mode = body.mode === 'live' ? 'live' : 'simulate';
+ const network = body.network === 'devnet' ? 'devnet' : 'mainnet';
+
+ let wallet = null, walletAddress = null;
+ if (mode === 'live') {
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required for live mode');
+ if (!body.agentId) return error(res, 400, 'validation_error', 'agentId required for live mode');
+ try {
+ const r = await loadAgentWallet(body.agentId, auth.userId);
+ wallet = r.wallet;
+ walletAddress = r.address;
+ } catch (e) {
+ return error(res, e.status ?? 500, e.status === 409 ? 'conflict' : 'unauthorized', e.message);
+ }
+ }
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 aborted = false;
+ req.on('close', () => { aborted = true; });
- let invoke = rt.invoke;
- if (useStub) {
- invoke = async (tool, args) => {
- if (tool.startsWith('pump-fun.')) return stubInvoke(tool, args);
- return rt.invoke(tool, args);
- };
- }
+ const rt = makeRuntime({
+ wallet,
+ agentId: mode === 'live' ? body.agentId : undefined,
+ signerAddress: walletAddress,
+ configOverrides: {
+ 'pump-fun-trade': { rpc: RPC[network] },
+ 'solana-wallet': { rpc: RPC[network] },
+ },
+ onEvent: (e) => send('memory', e),
+ });
- send('start', { durationSec, useStub });
+ send('start', { durationSec, mode, network, walletAddress });
const { runStrategy } = await import('../../examples/skills/pump-fun-strategy/handlers.js');
const ctx = {
- skills: { invoke },
- skillConfig: { defaultPollMs: 1500 },
+ skills: { invoke: rt.invoke },
+ skillConfig: { defaultPollMs: Math.max(1500, Number(body.pollMs) || 3000) },
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;
- },
- },
+ wallet,
};
try {
const result = await runStrategy(
- { strategy: body.strategy, durationSec, simulate: true },
- wrappedCtx,
+ {
+ strategy: body.strategy,
+ durationSec,
+ simulate: mode === 'simulate',
+ onLog: (entry) => { if (!aborted) send('log', entry); },
+ },
+ ctx,
);
- // 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 });
diff --git a/examples/skills/pump-fun/handlers.js b/examples/skills/pump-fun/handlers.js
index 207517e8a..74d6126ca 100644
--- a/examples/skills/pump-fun/handlers.js
+++ b/examples/skills/pump-fun/handlers.js
@@ -1,17 +1,33 @@
-// pump-fun skill — proxies tool calls to the pump-fun-workers MCP server.
-// https://github.com/nirholas/pump-fun-workers
+// pump-fun skill — proxies tool calls to the in-house MCP route at
+// /api/pump-fun-mcp. The route is implemented in api/pump-fun-mcp.js and
+// serves on-chain reads (bonding curve, token details, holders) via the
+// official @pump-fun/* SDKs + Solana RPC. Indexer-backed tools (search,
+// trending, new, graduated, king-of-the-hill, creator profile, trades) are
+// proxied through the upstream pumpfun-claims-bot MCP and return a clear
+// JSON-RPC error when PUMPFUN_BOT_URL is not configured.
+//
+// Endpoint resolution: we resolve /api/pump-fun-mcp against the *page*
+// origin (window.location.origin) so the skill works whether the host page
+// is three.ws, a self-hosted deployment, or localhost during development.
//
// Some handlers return a `sentiment` (-1..1) so the Empathy Layer reacts
// (rug flags → concern, near-graduation → celebration). _onSkillDone in
// agent-avatar.js consumes result.sentiment automatically.
-const ENDPOINT = 'https://pump-fun-sdk.modelcontextprotocol.name/mcp';
+function _endpoint() {
+ if (typeof globalThis !== 'undefined' && globalThis.location?.origin) {
+ return `${globalThis.location.origin}/api/pump-fun-mcp`;
+ }
+ // Skill workers run without window — fall back to a same-origin relative
+ // fetch which the host shell will resolve.
+ return '/api/pump-fun-mcp';
+}
let _rpcId = 0;
async function callMcp(name, args, ctx) {
const fetchImpl = ctx?.fetch ?? globalThis.fetch;
- const res = await fetchImpl(ENDPOINT, {
+ const res = await fetchImpl(_endpoint(), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
diff --git a/public/dashboard/agent-pumpfun.html b/public/dashboard/agent-pumpfun.html
index e7309a203..1c0d7ea4f 100644
--- a/public/dashboard/agent-pumpfun.html
+++ b/public/dashboard/agent-pumpfun.html
@@ -19,16 +19,28 @@
--panel2: #1a1a24;
--muted: #888;
}
- * { box-sizing: border-box; }
+ * {
+ box-sizing: border-box;
+ }
body {
- font: 15px/1.55 -apple-system, system-ui, Segoe UI, Roboto, sans-serif;
+ 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; }
+ a {
+ color: #9a8cff;
+ text-decoration: none;
+ }
+ a:hover {
+ text-decoration: underline;
+ }
header {
display: flex;
align-items: center;
@@ -40,10 +52,25 @@
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; }
+ .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);
@@ -59,10 +86,25 @@
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 {
+ .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);
@@ -71,8 +113,15 @@
font: inherit;
min-width: 0;
}
- input:focus, select:focus { outline: none; border-color: var(--accent); }
- .field { flex: 1 1 180px; 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;
@@ -83,13 +132,37 @@
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; }
+ .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);
@@ -114,21 +187,64 @@
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.5);
opacity: 0;
transform: translateY(8px);
- transition: opacity 0.18s, transform 0.18s;
+ 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; }
+ .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>
@@ -147,9 +263,9 @@
<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).
+ 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">
@@ -178,27 +294,61 @@
<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 class="btn ghost" id="vanity-link" href="/vanity-wallet" target="_blank" rel="noopener">Grind vanity address ✦</a>
- <a id="explorer-link" class="muted" href="#" target="_blank" rel="noopener" hidden>Open on Solscan ↗</a>
+ <button class="btn ghost" id="provision-btn" hidden>
+ Provision Solana wallet
+ </button>
+ <a
+ class="btn ghost"
+ id="vanity-link"
+ href="/vanity-wallet"
+ target="_blank"
+ rel="noopener"
+ >Grind vanity address ✦</a
+ >
+ <a
+ id="explorer-link"
+ class="muted"
+ href="#"
+ target="_blank"
+ rel="noopener"
+ hidden
+ >Open on Solscan ↗</a
+ >
</div>
</div>
</section>
<section class="panel" id="sns-panel">
- <h2>SNS identity <span class="muted" style="font-size: 13px; font-weight: normal">(Solana Name Service)</span></h2>
+ <h2>
+ SNS identity
+ <span class="muted" style="font-size: 13px; font-weight: normal"
+ >(Solana Name Service)</span
+ >
+ </h2>
<p class="muted" style="margin: 0 0 10px; font-size: 13px">
- Attach a <code>.sol</code> domain owned by this agent's wallet so it can be referenced by name.
+ Attach a <code>.sol</code> domain owned by this agent's wallet so it can be
+ referenced by name.
</p>
<dl class="kv">
<dt>Current</dt>
<dd id="sns-current" class="muted">—</dd>
</dl>
- <div id="sns-domain-list" class="row" style="margin-top: 8px; flex-wrap: wrap; gap: 6px"></div>
+ <div
+ id="sns-domain-list"
+ class="row"
+ style="margin-top: 8px; flex-wrap: wrap; gap: 6px"
+ ></div>
<div class="row" style="margin-top: 10px">
<button class="btn ghost" id="sns-refresh-btn">Refresh domains</button>
<button class="btn ghost" id="sns-clear-btn" hidden>Clear SNS id</button>
- <a id="sns-register-link" class="muted" href="https://www.sns.id" target="_blank" rel="noopener">Register a name on sns.id</a>
+ <a
+ id="sns-register-link"
+ class="muted"
+ href="https://www.sns.id"
+ target="_blank"
+ rel="noopener"
+ >Register a name on sns.id</a
+ >
</div>
</section>
@@ -226,14 +376,17 @@
<input id="launch-sol" type="number" min="0" step="0.001" placeholder="0" />
</div>
<div class="field" style="flex: 0 0 auto; padding-top: 22px">
- <label style="display:flex; align-items:center; gap:6px; color:#ddd">
+ <label style="display: flex; align-items: center; gap: 6px; color: #ddd">
<input type="checkbox" id="launch-vanity-ic" /> ignore case
</label>
</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>
+ <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">
@@ -241,8 +394,14 @@
</div>
</div>
<p class="muted" style="margin: 10px 0 0; font-size: 12px">
- Base58 only (no 0/O/I/l). Combined prefix+suffix length: 3 chars ≈ instant, 4 ≈ seconds, 5 ≈ minutes, 6+ may time out. Powered by
- <a href="https://github.com/nirholas/solana-wallet-toolkit" target="_blank" rel="noopener">solana-wallet-toolkit</a>.
+ Base58 only (no 0/O/I/l). Combined prefix+suffix length: 3 chars ≈ instant, 4 ≈
+ seconds, 5 ≈ minutes, 6+ may time out. Powered by
+ <a
+ href="https://github.com/nirholas/solana-wallet-toolkit"
+ target="_blank"
+ rel="noopener"
+ >solana-wallet-toolkit</a
+ >.
</p>
</section>
@@ -281,10 +440,71 @@
<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>
+ <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" id="indexer-panel" hidden>
+ <div style="display: flex; justify-content: space-between; align-items: center">
+ <h2 style="margin: 0">Token indexer</h2>
+ <button class="btn ghost" id="indexer-refresh">Refresh</button>
+ </div>
+ <div class="muted" style="font-size: 13px; margin: 6px 0 12px">
+ Live snapshot from <code>/api/cron/pump-agent-stats</code> + price history.
+ </div>
+ <div id="token-stats">Pick a launched mint above (Trade panel) to see stats.</div>
+ <canvas
+ id="price-chart"
+ width="640"
+ height="120"
+ style="
+ display: block;
+ margin-top: 12px;
+ max-width: 100%;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: #0a0a12;
+ "
+ ></canvas>
+ </section>
+
+ <section class="panel" id="signals-panel">
+ <h2>
+ Live pump.fun signals
+ <span class="muted" style="font-weight:400;font-size:13px">
+ — off-chain claim/graduation activity tied to your agent's wallet
+ </span>
+ </h2>
+ <div id="signals-grid" class="muted">No signals yet. The crawler runs every 15 minutes.</div>
+ <div class="row" style="margin-top: 12px">
+ <a class="btn ghost" id="open-live-feed" href="/pumpfun" target="_blank" rel="noopener">
+ Open live feed ↗
+ </a>
+ <a class="btn ghost" id="open-passport" href="#" target="_blank" rel="noopener">
+ Open agent passport ↗
+ </a>
+ </div>
</section>
<section class="panel">
@@ -409,7 +629,8 @@
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.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;
@@ -437,7 +658,8 @@
}
const owned = Array.isArray(data.domains) ? data.domains : [];
if (!owned.length) {
- els.snsDomainList.innerHTML = '<span class="muted" style="font-size:13px">This wallet does not own any .sol domains yet. Register one on sns.id, then refresh.</span>';
+ els.snsDomainList.innerHTML =
+ '<span class="muted" style="font-size:13px">This wallet does not own any .sol domains yet. Register one on sns.id, then refresh.</span>';
return;
}
els.snsDomainList.innerHTML = '';
@@ -468,7 +690,10 @@
const { data } = await api(`/api/agents/${id}/sns`);
renderSnsList(data);
} catch (err) {
- els.snsCurrent.textContent = err.body?.error === 'conflict' ? 'Provision a Solana wallet first' : err.message;
+ els.snsCurrent.textContent =
+ err.body?.error === 'conflict'
+ ? 'Provision a Solana wallet first'
+ : err.message;
els.snsDomainList.innerHTML = '';
els.snsClearBtn.hidden = true;
}
@@ -478,7 +703,10 @@
const id = currentAgentId();
if (!id) return;
try {
- await api(`/api/agents/${id}/sns`, { method: 'POST', body: JSON.stringify({ domain }) });
+ await api(`/api/agents/${id}/sns`, {
+ method: 'POST',
+ body: JSON.stringify({ domain }),
+ });
toast(`Attached ${domain}.sol`);
await refreshSns();
} catch (err) {
@@ -531,7 +759,8 @@
const sol = parseFloat(els.launchSol.value);
if (sol > 0) body.solAmount = sol;
els.launchBtn.disabled = true;
- els.launchBtn.textContent = vanity || vanitySuffix ? 'Grinding & launching…' : 'Launching…';
+ els.launchBtn.textContent =
+ vanity || vanitySuffix ? 'Grinding & launching…' : 'Launching…';
try {
const { data } = await api(`/api/agents/${id}/pumpfun/launch`, {
method: 'POST',
@@ -631,7 +860,9 @@
if (!id) return;
const network = currentNetwork();
try {
- const { data } = await api(`/api/agents/${id}/pumpfun/portfolio?network=${network}`);
+ const { data } = await api(
+ `/api/agents/${id}/pumpfun/portfolio?network=${network}`,
+ );
logResponse('portfolio', data);
const t = data.totals || {};
els.portfolioTotals.innerHTML =
@@ -641,14 +872,17 @@
const tbody = els.portfolioTable;
if (!data.positions.length) {
- tbody.innerHTML = '<tr><td colspan="7" class="muted">No positions yet.</td></tr>';
+ 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>` : '';
+ 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>` +
@@ -676,7 +910,9 @@
});
els.networkSelect.addEventListener('change', async () => {
const isDev = currentNetwork() === 'devnet';
- document.querySelectorAll('.network-tag').forEach((e) => (e.className = `tag${isDev ? ' devnet' : ''}`));
+ document
+ .querySelectorAll('.network-tag')
+ .forEach((e) => (e.className = `tag${isDev ? ' devnet' : ''}`));
await refreshAgent();
await refreshPortfolio();
});
@@ -692,6 +928,116 @@
els.sellBtn.addEventListener('click', sell);
els.portfolioBtn.addEventListener('click', refreshPortfolio);
+ // ── Token indexer panel ──────────────────────────────────────────
+ const indexerPanel = document.getElementById('indexer-panel');
+ const tokenStatsEl = document.getElementById('token-stats');
+ const chartEl = document.getElementById('price-chart');
+
+ function fmtSolLamports(s) {
+ if (s == null) return '—';
+ return (Number(s) / 1e9).toFixed(4) + ' SOL';
+ }
+
+ async function refreshIndexer() {
+ const mint = els.tradeMint.value.trim();
+ const network = currentNetwork();
+ if (!mint) {
+ indexerPanel.hidden = true;
+ return;
+ }
+ indexerPanel.hidden = false;
+ tokenStatsEl.innerHTML = '<div class="muted">Loading…</div>';
+ try {
+ const card = await fetch(`/api/agents/solana-card?asset=${mint}`)
+ .then((r) => (r.ok ? r.json() : null))
+ .catch(() => null);
+ const ts = card?.token_stats;
+ if (!ts) {
+ tokenStatsEl.innerHTML =
+ '<div class="muted">No indexed stats yet — pump-agent-stats cron runs every 10 min after launch.</div>';
+ } else {
+ const refreshedAgo = ts.refreshed_at
+ ? `${Math.max(0, Math.round((Date.now() - new Date(ts.refreshed_at)) / 60000))}m ago`
+ : '—';
+ let body;
+ if (ts.graduated) {
+ const a = ts.amm || {};
+ body =
+ `<span class="tag" style="background:#5c8fff22;color:#9bf">graduated · AMM</span>` +
+ ` <span class="muted">refreshed ${refreshedAgo}</span>` +
+ `<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px;margin-top:8px">` +
+ `<div><div class="muted">Pool quote</div><b>${fmtSolLamports(a.quote_reserve)}</b></div>` +
+ `<div><div class="muted">Pool base (tokens)</div><b>${a.base_reserve ? Number(a.base_reserve).toExponential(2) : '—'}</b></div>` +
+ `<div><div class="muted">Recent tx (50-tail)</div><b>${ts.recent_tx_count || 0}</b></div>` +
+ `</div>`;
+ } else if (ts.bonding_curve) {
+ const c = ts.bonding_curve;
+ const pct = Number(c.progress_pct || 0);
+ body =
+ `<div>Curve · <b>${pct.toFixed(1)}%</b> to graduation <span class="muted">refreshed ${refreshedAgo}</span></div>` +
+ `<div style="background:#222;border-radius:6px;height:10px;overflow:hidden;margin:6px 0 10px"><div style="background:linear-gradient(90deg,#5c8fff,#00d4ff);width:${Math.min(100, pct)}%;height:100%"></div></div>` +
+ `<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px">` +
+ `<div><div class="muted">Real SOL reserves</div><b>${fmtSolLamports(c.real_sol)}</b></div>` +
+ `<div><div class="muted">Real token reserves</div><b>${c.real_token ? Number(c.real_token).toExponential(2) : '—'}</b></div>` +
+ `<div><div class="muted">Recent tx (50-tail)</div><b>${ts.recent_tx_count || 0}</b></div>` +
+ `</div>`;
+ } else {
+ body = `<div class="muted">No bonding curve or AMM pool detected.</div>`;
+ }
+ tokenStatsEl.innerHTML = body;
+ }
+
+ const hist = await fetch(
+ `/api/agents/solana-price-history?asset=${mint}&network=${network}&hours=72`,
+ )
+ .then((r) => (r.ok ? r.json() : null))
+ .catch(() => null);
+ drawSparkline(chartEl, hist?.points || []);
+ } catch (e) {
+ tokenStatsEl.innerHTML = `<div class="muted">${e.message}</div>`;
+ }
+ }
+
+ function drawSparkline(canvas, points) {
+ const ctx = canvas.getContext('2d');
+ const w = canvas.width,
+ h = canvas.height;
+ ctx.clearRect(0, 0, w, h);
+ if (!points.length) {
+ ctx.fillStyle = '#666';
+ ctx.font = '12px system-ui';
+ ctx.fillText('No price points yet (cron runs every 10 min).', 10, h / 2);
+ return;
+ }
+ const xs = points.map((_, i) => i);
+ const ys = points.map((p) => Number(p.sol_per_token) || 0);
+ const min = Math.min(...ys),
+ max = Math.max(...ys);
+ const span = max - min || 1;
+ const sx = (i) => (i / Math.max(1, xs.length - 1)) * (w - 16) + 8;
+ const sy = (v) => h - 8 - ((v - min) / span) * (h - 16);
+ ctx.strokeStyle = '#6a5cff';
+ ctx.lineWidth = 2;
+ ctx.beginPath();
+ ys.forEach((v, i) => {
+ const x = sx(i),
+ y = sy(v);
+ if (i === 0) ctx.moveTo(x, y);
+ else ctx.lineTo(x, y);
+ });
+ ctx.stroke();
+ ctx.fillStyle = '#888';
+ ctx.font = '11px system-ui';
+ ctx.fillText(
+ `${ys[0].toExponential(2)} → ${ys[ys.length - 1].toExponential(2)} SOL/tok`,
+ 8,
+ 14,
+ );
+ }
+
+ document.getElementById('indexer-refresh').addEventListener('click', refreshIndexer);
+ els.tradeMint.addEventListener('change', refreshIndexer);
+
(async () => {
await loadAgents();
if (currentAgentId()) {
diff --git a/public/pumpfun.html b/public/pumpfun.html
index c5a0a35ec..a5f24359d 100644
--- a/public/pumpfun.html
+++ b/public/pumpfun.html
@@ -3,38 +3,57 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
- <title>Pump.fun live feed — three.ws demo</title>
+ <title>Pump.fun live · three.ws</title>
+ <link rel="icon" href="/favicon.ico" />
<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; }
+ :root { color-scheme: dark; --accent: #6a5cff; --border: #1f1f29; --bg: #0a0a0f; --panel: #14141c; --muted: #888; }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; height: 100%; background: var(--bg); color: #eee;
+ font: 14px/1.55 -apple-system, system-ui, Segoe UI, Roboto, sans-serif; }
+ header { padding: 12px 18px; border-bottom: 1px solid var(--border);
+ display: flex; align-items: center; gap: 14px; flex-wrap: wrap; background: var(--panel); }
+ header h1 { margin: 0; font-size: 15px; font-weight: 600; }
+ header .desc { color: var(--muted); font-size: 12px; }
+ header .ctl { margin-left: auto; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
+ header label { font-size: 12px; color: var(--muted); display: inline-flex; align-items: center; gap: 6px; }
header select, header input[type="text"], header button {
- background: #161616; color: #f0f0f0; border: 1px solid #2a2a2a;
+ background: #161620; color: #eee; border: 1px solid #2a2a36;
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; }
- iframe { width: 100%; height: 100%; border: 0; display: block; background: #0a0a0a; }
- .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; }
+ header button:hover { background: #20202c; }
+ header button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
+ main { position: relative; height: calc(100% - 52px); display: grid; grid-template-columns: 1fr 360px; }
+ #stage { position: relative; }
+ iframe { width: 100%; height: 100%; border: 0; display: block; background: var(--bg); }
+ #side { border-left: 1px solid var(--border); background: var(--panel); display: flex; flex-direction: column; overflow-y: auto; }
+ #side h2 { font-size: 12px; text-transform: uppercase; letter-spacing: 0.06em;
+ color: var(--muted); margin: 14px 16px 8px; font-weight: 600; }
+ #agent-card, #signals { padding: 4px 16px 12px; border-bottom: 1px solid var(--border); }
+ .kv { display: flex; justify-content: space-between; padding: 4px 0; font-size: 13px; gap: 8px; }
+ .kv span:first-child { color: var(--muted); }
+ .kv code { font-size: 11px; background: #1a1a24; padding: 1px 5px; border-radius: 3px; }
+ .signal-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
+ .signal { background: #1a1a24; border: 1px solid #232330; border-radius: 6px; padding: 8px; }
+ .signal .v { font-size: 18px; font-weight: 600; }
+ .signal .l { font-size: 11px; color: var(--muted); margin-top: 2px; }
+ .signal.neg { border-color: #4a1f23; background: #1f1418; }
+ .empty { color: var(--muted); font-size: 12px; padding: 8px 0; }
+ a { color: #9a8cff; }
+ .warn { background: #2a1f0d; border: 1px solid #463a14; padding: 8px 10px; border-radius: 6px;
+ color: #fbbf24; font-size: 12px; margin: 12px 16px; }
+ @media (max-width: 720px) { main { grid-template-columns: 1fr; } #side { display: none; } }
</style>
</head>
<body>
<header>
- <h1>✦ Pump.fun Live Feed</h1>
- <span class="desc">3D agent narrates pump.fun activity in real time.</span>
+ <h1>✦ Pump.fun live</h1>
+ <span class="desc">3D Solana agent narrating live pump.fun activity.</span>
<div class="ctl">
- <label style="font-size:12px;color:#888">Filter mint
- <input id="ctl-mint" type="text" placeholder="(any)" size="22" />
+ <label>Agent
+ <input id="ctl-asset" type="text" placeholder="Solana asset pubkey" size="22" />
+ </label>
+ <label>Mint
+ <input id="ctl-mint" type="text" placeholder="Filter mint…" size="20" />
</label>
<select id="ctl-kind">
<option value="all">All events</option>
@@ -48,58 +67,128 @@
<option value="mega">Mega only</option>
</select>
<button id="ctl-narrate" type="button" data-on="1">Narration: on</button>
- <button id="ctl-reload" type="button">Apply</button>
+ <button id="ctl-apply" class="primary" type="button">Apply</button>
</div>
</header>
<main>
<div id="stage">
- <iframe id="agent" src="/app#widget=wdgt_demo_pumpfun&kiosk=true" allow="autoplay"></iframe>
- </div>
- <div class="notice">
- <b>Heads up:</b> set <code>PUMPFUN_BOT_URL</code> in your environment to enable the live feed.
- Without it the SSE stream returns <code>503</code> and no cards arrive. See
- <a href="/docs/solana-pumpfun.md">solana-pumpfun.md</a>.
+ <iframe id="agent" allow="autoplay" title="3D agent"></iframe>
</div>
+ <aside id="side">
+ <h2>Agent</h2>
+ <div id="agent-card"><div class="empty">Paste a Solana asset pubkey above to bind a specific agent. Without one, the default narrator avatar is shown.</div></div>
+ <h2>Reputation signals</h2>
+ <div id="signals"><div class="empty">Bind a Solana agent to see live pump.fun signals.</div></div>
+ </aside>
</main>
<script>
- const iframe = document.getElementById('agent');
+ const url = new URL(location.href);
+ const $ = (id) => document.getElementById(id);
+ const iframe = $('agent');
+
+ const params = {
+ asset: url.searchParams.get('asset') || '',
+ mint: url.searchParams.get('mint') || '',
+ kind: url.searchParams.get('kind') || 'all',
+ minTier: url.searchParams.get('minTier') || '',
+ network: url.searchParams.get('network') || 'mainnet',
+ narrate: url.searchParams.get('narrate') !== '0',
+ };
+ $('ctl-asset').value = params.asset;
+ $('ctl-mint').value = params.mint;
+ $('ctl-kind').value = params.kind;
+ $('ctl-tier').value = params.minTier;
+ $('ctl-narrate').dataset.on = params.narrate ? '1' : '0';
+ $('ctl-narrate').textContent = params.narrate ? 'Narration: on' : 'Narration: off';
+
+ async function mountAgent() {
+ const cfgPart = `&type=pumpfun-feed&kind=${encodeURIComponent(params.kind)}` +
+ (params.minTier ? `&minTier=${encodeURIComponent(params.minTier)}` : '') +
+ (params.narrate ? '' : '&narrate=0');
+ let modelHash = '';
+ let widgetId = 'wdgt_demo_pumpfun';
+ if (params.asset) {
+ try {
+ const r = await fetch(`/api/agents/solana-card?asset=${encodeURIComponent(params.asset)}`);
+ if (r.ok) {
+ const card = await r.json();
+ renderAgentCard(card);
+ const avatarUrl = card?.identity?.avatar_url || card?.avatar_url;
+ if (avatarUrl) modelHash = `&model=${encodeURIComponent(avatarUrl)}`;
+ }
+ const repR = await fetch(`/api/agents/solana-reputation?asset=${encodeURIComponent(params.asset)}&network=${params.network}`);
+ if (repR.ok) renderSignals(await repR.json());
+ } catch {}
+ }
+ iframe.src = `/app#widget=${widgetId}&kiosk=true${cfgPart}${modelHash}`;
+ }
+
+ function renderAgentCard(card) {
+ const id = card?.identity || {};
+ const el = $('agent-card');
+ el.innerHTML = `
+ <div class="kv"><span>Name</span><strong>${escapeHtml(card?.name || '—')}</strong></div>
+ <div class="kv"><span>Network</span><code>${escapeHtml(id.network || '—')}</code></div>
+ <div class="kv"><span>Asset</span><code>${shortKey(id.asset_pubkey || '')}</code></div>
+ ${id.owner ? `<div class="kv"><span>Owner</span><code>${shortKey(id.owner)}</code></div>` : ''}
+ ${id.passport_url ? `<div class="kv"><span>Passport</span><a href="${attr(id.passport_url)}" target="_blank">open ↗</a></div>` : ''}
+ `;
+ }
+
+ function renderSignals(rep) {
+ const pf = rep?.pumpfun_signals || { count: 0, weight: 0, by_kind: {} };
+ const el = $('signals');
+ if (!pf.count) {
+ el.innerHTML = `<div class="empty">No pump.fun signals tied to this agent yet.</div>`;
+ return;
+ }
+ const cards = [
+ `<div class="signal"><div class="v">${pf.count}</div><div class="l">total signals</div></div>`,
+ `<div class="signal ${pf.weight < 0 ? 'neg' : ''}"><div class="v">${pf.weight >= 0 ? '+' : ''}${pf.weight.toFixed(2)}</div><div class="l">aggregate weight</div></div>`,
+ ...Object.entries(pf.by_kind).map(([k, info]) =>
+ `<div class="signal ${info.weight < 0 ? 'neg' : ''}"><div class="v">${info.count}</div><div class="l">${escapeHtml(k.replace('_', ' '))}</div></div>`),
+ ];
+ el.innerHTML = `<div class="signal-grid">${cards.join('')}</div>`;
+ }
- // Build hash from current toolbar state.
- const params = new URLSearchParams(location.search);
- const $kind = document.getElementById('ctl-kind');
- const $tier = document.getElementById('ctl-tier');
- const $narr = document.getElementById('ctl-narrate');
- $kind.value = params.get('kind') || 'all';
- $tier.value = params.get('minTier') || '';
- const narrate = params.get('narrate') !== '0';
- $narr.dataset.on = narrate ? '1' : '0';
- $narr.textContent = narrate ? 'Narration: on' : 'Narration: off';
+ function shortKey(s) { s = String(s || ''); return s.length > 12 ? `${s.slice(0,4)}…${s.slice(-4)}` : s; }
+ function escapeHtml(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c])); }
+ function attr(s) { return escapeHtml(s); }
- document.getElementById('ctl-narrate').addEventListener('click', (e) => {
+ $('ctl-mint').addEventListener('input', (e) => {
+ const mint = e.target.value.trim() || null;
+ iframe.contentWindow?.postMessage({ type: 'pumpfun-feed:focus-mint', mint }, '*');
+ });
+
+ $('ctl-narrate').addEventListener('click', (e) => {
const on = e.target.dataset.on !== '1';
e.target.dataset.on = on ? '1' : '0';
e.target.textContent = on ? 'Narration: on' : 'Narration: off';
+ iframe.contentWindow?.postMessage({ type: 'pumpfun-feed:set-narrate', on }, '*');
});
- document.getElementById('ctl-reload').addEventListener('click', () => {
+ $('ctl-apply').addEventListener('click', () => {
const u = new URL(location.href);
- u.searchParams.set('kind', $kind.value);
- if ($tier.value) u.searchParams.set('minTier', $tier.value);
+ u.searchParams.set('kind', $('ctl-kind').value);
+ if ($('ctl-tier').value) u.searchParams.set('minTier', $('ctl-tier').value);
else u.searchParams.delete('minTier');
- u.searchParams.set('narrate', $narr.dataset.on === '1' ? '1' : '0');
+ const asset = $('ctl-asset').value.trim();
+ if (asset) u.searchParams.set('asset', asset);
+ else u.searchParams.delete('asset');
+ u.searchParams.set('narrate', $('ctl-narrate').dataset.on === '1' ? '1' : '0');
location.href = u.toString();
});
- // Live mint focus — postMessage into the iframe so the widget filters
- // without reloading. The widget listens for a CustomEvent on its
- // container; we proxy via the iframe's window.
- document.getElementById('ctl-mint').addEventListener('input', (e) => {
- const mint = e.target.value.trim() || null;
- iframe.contentWindow?.postMessage(
- { type: 'pumpfun-feed:focus-mint', mint },
- '*',
- );
- });
+ fetch('/api/agents/pumpfun?op=claims&limit=1', { credentials: 'include' }).then((r) => {
+ if (r.status === 503) {
+ const w = document.createElement('div');
+ w.className = 'warn';
+ w.innerHTML = 'Pump.fun feed is not configured on this server. Set <code>PUMPFUN_BOT_URL</code> to enable. See <a href="/docs/solana-pumpfun.md">solana-pumpfun.md</a>.';
+ document.querySelector('header').insertAdjacentElement('afterend', w);
+ }
+ }).catch(() => {});
+
+ mountAgent();
</script>
</body>
</html>
diff --git a/public/skills/pump-fun/handlers.js b/public/skills/pump-fun/handlers.js
index 207517e8a..74d6126ca 100644
--- a/public/skills/pump-fun/handlers.js
+++ b/public/skills/pump-fun/handlers.js
@@ -1,17 +1,33 @@
-// pump-fun skill — proxies tool calls to the pump-fun-workers MCP server.
-// https://github.com/nirholas/pump-fun-workers
+// pump-fun skill — proxies tool calls to the in-house MCP route at
+// /api/pump-fun-mcp. The route is implemented in api/pump-fun-mcp.js and
+// serves on-chain reads (bonding curve, token details, holders) via the
+// official @pump-fun/* SDKs + Solana RPC. Indexer-backed tools (search,
+// trending, new, graduated, king-of-the-hill, creator profile, trades) are
+// proxied through the upstream pumpfun-claims-bot MCP and return a clear
+// JSON-RPC error when PUMPFUN_BOT_URL is not configured.
+//
+// Endpoint resolution: we resolve /api/pump-fun-mcp against the *page*
+// origin (window.location.origin) so the skill works whether the host page
+// is three.ws, a self-hosted deployment, or localhost during development.
//
// Some handlers return a `sentiment` (-1..1) so the Empathy Layer reacts
// (rug flags → concern, near-graduation → celebration). _onSkillDone in
// agent-avatar.js consumes result.sentiment automatically.
-const ENDPOINT = 'https://pump-fun-sdk.modelcontextprotocol.name/mcp';
+function _endpoint() {
+ if (typeof globalThis !== 'undefined' && globalThis.location?.origin) {
+ return `${globalThis.location.origin}/api/pump-fun-mcp`;
+ }
+ // Skill workers run without window — fall back to a same-origin relative
+ // fetch which the host shell will resolve.
+ return '/api/pump-fun-mcp';
+}
let _rpcId = 0;
async function callMcp(name, args, ctx) {
const fetchImpl = ctx?.fetch ?? globalThis.fetch;
- const res = await fetchImpl(ENDPOINT, {
+ const res = await fetchImpl(_endpoint(), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
diff --git a/src/agent-home-pumpfun.js b/src/agent-home-pumpfun.js
index 9313d716e..f19f3bf1a 100644
--- a/src/agent-home-pumpfun.js
+++ b/src/agent-home-pumpfun.js
@@ -53,16 +53,25 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
// auto-trader
botOpen: false,
botMode: 'auto-snipe',
- botSimulate: true,
+ botDryRun: false,
botDurationSec: 60,
botPerTradeSol: 0.05,
botCapSol: 0.5,
botQuery: '',
botWallet: '',
- botSessionId: `s-${Date.now().toString(36)}`,
botRunning: false,
+ botProgress: null, // last onProgress event
+ botSpent: 0,
+ botEventCount: 0,
};
let botAbort = null;
+ // Stable per-mode session ids — re-running the same mode resumes prior state.
+ const botSessionIds = {
+ 'research-and-buy': `pf-research-${identity.id}`,
+ 'auto-snipe': `pf-snipe-${identity.id}`,
+ 'copy-trade': `pf-copy-${identity.id}`,
+ 'rug-exit-watch': `pf-exit-${identity.id}`,
+ };
let refreshTimer = null;
let quoteTimer = null;
let unsubProtocol = null;
@@ -156,21 +165,31 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
${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 class="pumpfun-vanity-row" title="Run filters/quotes only — no signing or SOL spent. Useful for tuning before going live.">
+ <input type="checkbox" data-bot-field="dryRun" ${s.botDryRun ? 'checked' : ''} ${s.botRunning ? 'disabled' : ''}>
+ <span>Dry run</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>`}
+ : `<button class="pumpfun-btn pumpfun-btn--primary" data-action="bot-run">${s.botDryRun ? '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 class="pumpfun-bot-progress" id="pf-bot-progress">${botProgressLine(s)}</div>
</div>
`;
};
+ function botProgressLine(s) {
+ if (!s.botRunning && !s.botProgress) return '';
+ const e = s.botProgress;
+ const head = s.botRunning
+ ? `<span class="pumpfun-quote-status">${escapeHtml(s.botMode)} · ${s.botEventCount} events · ${s.botSpent.toFixed(4)} SOL</span>`
+ : `<span class="pumpfun-quote-out">done · ${s.botEventCount} events · ${s.botSpent.toFixed(4)} SOL</span>`;
+ const last = e ? `<span class="pumpfun-quote-out"> · last: ${escapeHtml(e.type)}${e.mint ? ` ${shortMint(e.mint)}` : ''}${e.reason ? ` (${escapeHtml(e.reason)})` : ''}</span>` : '';
+ return head + last;
+ }
+
const tradePanel = (s) => {
const isBuy = s.tradeOpen === 'buy';
const placeholder = isBuy ? '0.1' : '1000000';
@@ -278,7 +297,7 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
const v = el.type === 'checkbox' ? e.target.checked
: el.type === 'number' ? parseFloat(e.target.value) || 0
: e.target.value;
- const map = { simulate: 'botSimulate', durationSec: 'botDurationSec', perTradeSol: 'botPerTradeSol', capSol: 'botCapSol', query: 'botQuery', wallet: 'botWallet' };
+ const map = { dryRun: 'botDryRun', durationSec: 'botDurationSec', perTradeSol: 'botPerTradeSol', capSol: 'botCapSol', query: 'botQuery', wallet: 'botWallet' };
if (map[field]) state[map[field]] = v;
});
});
@@ -350,11 +369,22 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
async function runBot() {
if (state.botRunning) return;
+ const skillConfig = {
+ sessionSpendCapSol: parseFloat(state.botCapSol) || 0.5,
+ perTradeSol: parseFloat(state.botPerTradeSol) || 0.05,
+ };
const skillName = `pumpfun-${state.botMode}`;
const args = {
- sessionId: state.botSessionId,
- simulate: !!state.botSimulate,
+ sessionId: botSessionIds[state.botMode],
+ dryRun: !!state.botDryRun,
durationSec: Math.max(10, parseInt(state.botDurationSec, 10) || 60),
+ onProgress: (evt) => {
+ state.botProgress = evt;
+ state.botEventCount += 1;
+ if (typeof evt.spent === 'number') state.botSpent = evt.spent;
+ const slot = cardBody.querySelector('#pf-bot-progress');
+ if (slot) slot.innerHTML = botProgressLine(state);
+ },
};
if (state.botMode === 'research-and-buy') {
if (!state.botQuery?.trim()) return toast('Query required', null, null, 'error');
@@ -373,12 +403,15 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
botAbort = new AbortController();
args.signal = botAbort.signal;
state.botRunning = true;
+ state.botSpent = 0;
+ state.botEventCount = 0;
+ state.botProgress = null;
render();
try {
- const r = await skills.perform(skillName, args, { identity, memory });
+ const r = await skills.perform(skillName, args, { identity, memory, skillConfig });
if (r?.success) {
- const summary = r.output || `${state.botMode} done`;
- toast(`${state.botSimulate ? '[dry-run] ' : ''}${summary}`, null, null, 'success');
+ if (typeof r.data?.spent === 'number') state.botSpent = r.data.spent;
+ toast(`${state.botDryRun ? '[dry-run] ' : ''}${r.output || `${state.botMode} done`}`, null, null, 'success');
} else {
toast(r?.output || `${state.botMode} failed`, null, null, 'error');
}
@@ -387,7 +420,6 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
} finally {
state.botRunning = false;
botAbort = null;
- state.botSessionId = `s-${Date.now().toString(36)}`;
render();
}
}
diff --git a/src/agent-skills-pumpfun-autonomous.js b/src/agent-skills-pumpfun-autonomous.js
index 31fc09622..46bf55bb6 100644
--- a/src/agent-skills-pumpfun-autonomous.js
+++ b/src/agent-skills-pumpfun-autonomous.js
@@ -168,7 +168,7 @@ export function registerPumpFunAutonomousSkills(skills) {
},
handler: async (args, ctx) => {
const id = requireAgentId(ctx);
- const data = await postJson(ENDPOINT(id, 'swap'), {
+ const resp = await postJson(ENDPOINT(id, 'swap'), {
mint: args.mint,
side: args.side,
solAmount: args.solAmount,
@@ -176,6 +176,7 @@ export function registerPumpFunAutonomousSkills(skills) {
slippageBps: args.slippageBps ?? 500,
network: args.network || 'mainnet',
});
+ const payload = resp?.data || resp;
return {
success: true,
output:
@@ -183,7 +184,7 @@ export function registerPumpFunAutonomousSkills(skills) {
? `Bought ${args.mint.slice(0, 8)}… for ${args.solAmount} SOL.`
: `Sold ${args.tokenAmount} of ${args.mint.slice(0, 8)}…`,
sentiment: 0.5,
- data,
+ data: { ...payload, mint: args.mint, side: args.side, network: args.network || 'mainnet', solAmount: args.solAmount },
};
},
});
@@ -214,16 +215,22 @@ export function registerPumpFunAutonomousSkills(skills) {
},
handler: async (args, ctx) => {
const id = requireAgentId(ctx);
- const data = await postJson(ENDPOINT(id, 'pay'), args);
+ const resp = await postJson(ENDPOINT(id, 'pay'), args);
+ const payload = resp?.data || resp;
let output;
if (args.action === 'balances') {
- output = `Balances: ${JSON.stringify(data.balances || data)}`;
+ output = `Balances: ${JSON.stringify(payload.balances || payload)}`;
} else if (args.action === 'accept') {
output = `Payment accepted (${args.amount}).`;
} else {
output = `Withdraw complete.`;
}
- return { success: true, output, sentiment: 0.5, data };
+ return {
+ success: true,
+ output,
+ sentiment: 0.5,
+ data: { ...payload, network: args.network || 'mainnet' },
+ };
},
});
}
diff --git a/src/agent-skills-pumpfun-compose.js b/src/agent-skills-pumpfun-compose.js
index d511d522f..afe0a2f5c 100644
--- a/src/agent-skills-pumpfun-compose.js
+++ b/src/agent-skills-pumpfun-compose.js
@@ -359,20 +359,24 @@ export function registerPumpFunComposeSkills(skills) {
mints: { type: 'array', items: { type: 'string' } },
durationSec: { type: 'integer', minimum: 10, maximum: 86400 },
sessionId: { type: 'string' },
- simulate: { type: 'boolean' },
+ dryRun: { type: 'boolean' },
},
required: ['mints', 'durationSec'],
},
handler: async (args, ctx) => {
- const simulate = !!args.simulate;
+ const dryRun = !!args.dryRun;
+ const onProgress = args.onProgress;
+ const signal = args.signal;
const sessionId = args.sessionId;
const deadline = Date.now() + args.durationSec * 1000;
const concentrationLimit = cfg(ctx, 'exitOnConcentrationPct');
const devSellLimit = cfg(ctx, 'exitOnDevSellPct');
const state = await loadState(ctx?.memory, sessionId, { exited: new Set(), log: [] });
+ emit(onProgress, { type: 'start', mode: 'rug-exit-watch', mints: args.mints });
- while (!args.signal?.aborted && Date.now() < deadline && state.exited.size < args.mints.length) {
+ while (!signal?.aborted && Date.now() < deadline && state.exited.size < args.mints.length) {
for (const mint of args.mints) {
+ if (signal?.aborted) break;
if (state.exited.has(mint)) continue;
const [holders, trades, details] = await Promise.all([
mcp('getTokenHolders', { mint, limit: 10 }).catch(() => null),
@@ -387,25 +391,38 @@ export function registerPumpFunComposeSkills(skills) {
let trigger = null;
if (top >= concentrationLimit) trigger = `top holder ${top}%`;
else if (devSellPct >= devSellLimit) trigger = `dev sold ${devSellPct}%`;
- if (!trigger) continue;
+ if (!trigger) {
+ emit(onProgress, { type: 'tick', mint, top, devSellPct });
+ continue;
+ }
try {
- const sell = await maybeSell(skills, ctx, simulate, mint);
- state.exited.add(mint);
- state.log.push({ mint, trigger, sig: sell.signature, simulate });
+ const sell = await doSell(skills, ctx, dryRun, mint);
+ if (sell.skipped === 'no-balance') {
+ state.log.push({ mint, trigger, action: 'skipped-no-balance' });
+ emit(onProgress, { type: 'skip', mint, reason: 'no-balance' });
+ } else {
+ state.exited.add(mint);
+ state.log.push({ mint, trigger, sig: sell.signature, tokenAmount: sell.tokenAmount, dryRun });
+ emit(onProgress, { type: dryRun ? 'dry-sell' : 'sell', mint, sig: sell.signature, trigger });
+ }
saveState(ctx?.memory, sessionId, state);
} catch (e) {
state.log.push({ mint, trigger, error: e.message });
+ emit(onProgress, { type: 'error', mint, reason: e.message });
}
}
saveState(ctx?.memory, sessionId, state);
- await new Promise((r) => setTimeout(r, cfg(ctx, 'pollMs')));
+ if (signal?.aborted || Date.now() >= deadline || state.exited.size >= args.mints.length) break;
+ emit(onProgress, { type: 'poll-sleep', ms: cfg(ctx, 'pollMs') });
+ await abortableSleep(cfg(ctx, 'pollMs'), signal);
}
+ const reason = signal?.aborted ? 'aborted' : Date.now() >= deadline ? 'duration' : 'all-exited';
return {
success: true,
- output: `Exit watch done. Exited ${state.exited.size}/${args.mints.length} positions.`,
+ output: `Exit watch done (${reason}). Exited ${state.exited.size}/${args.mints.length} positions.`,
sentiment: state.exited.size > 0 ? -0.2 : 0.2,
- data: { exited: [...state.exited], events: state.log, simulate, sessionId },
+ data: { exited: [...state.exited], events: state.log, dryRun, sessionId, reason },
};
},
});
diff --git a/src/agent-solana-wallet.js b/src/agent-solana-wallet.js
index e375ff367..6624d3950 100644
--- a/src/agent-solana-wallet.js
+++ b/src/agent-solana-wallet.js
@@ -98,6 +98,29 @@ export async function deleteAgentSolanaWallet(agentId) {
}
}
+/** Fetch the agent wallet's recent on-chain activity. */
+export async function fetchAgentSolanaActivity(agentId, network = 'mainnet', limit = 10) {
+ const url = `/api/agents/${encodeURIComponent(agentId)}/solana/activity?network=${encodeURIComponent(network)}&limit=${limit}`;
+ const resp = await fetch(url, { credentials: 'include' });
+ if (!resp.ok) {
+ const j = await resp.json().catch(() => ({}));
+ throw new Error(j?.error_description || j?.error?.message || `activity fetch failed (${resp.status})`);
+ }
+ const json = await resp.json();
+ return json.data;
+}
+
+/** Request a 1 SOL devnet airdrop into the agent's wallet. */
+export async function requestAgentSolanaAirdrop(agentId) {
+ const url = `/api/agents/${encodeURIComponent(agentId)}/solana/airdrop`;
+ const resp = await fetch(url, { method: 'POST', credentials: 'include' });
+ const json = await resp.json().catch(() => ({}));
+ if (!resp.ok) {
+ throw new Error(json?.error_description || json?.error?.message || `airdrop failed (${resp.status})`);
+ }
+ return json.data;
+}
+
// ── UI card ─────────────────────────────────────────────────────────────────
const STYLE = `
@@ -118,6 +141,18 @@ const STYLE = `
.agent-sol-wallet .balance .net { margin-left: auto; font-size: .7rem; }
.agent-sol-wallet .balance select { font: inherit; font-size: .7rem; padding: .15rem .25rem; border: 1px solid #ddd; border-radius: 4px; background: #fff; }
.agent-sol-wallet .skel { color: #999; font-size: .75rem; padding: .35rem 0; }
+.agent-sol-wallet .activity { margin-top: .65rem; border-top: 1px solid #f0f0f0; padding-top: .5rem; }
+.agent-sol-wallet .activity-h { font-size: .72rem; color: #888; text-transform: uppercase; letter-spacing: .05em; margin-bottom: .35rem; display: flex; align-items: center; gap: .35rem; }
+.agent-sol-wallet .activity-h button { padding: .1rem .4rem; font-size: .7rem; line-height: 1; }
+.agent-sol-wallet .activity-row { display: flex; align-items: center; gap: .5rem; font-size: .75rem; padding: .25rem 0; border-bottom: 1px dashed #eee; }
+.agent-sol-wallet .activity-row:last-child { border-bottom: none; }
+.agent-sol-wallet .activity-row .sig { font-family: ui-monospace, monospace; color: #555; }
+.agent-sol-wallet .activity-row .delta { font-family: ui-monospace, monospace; margin-left: auto; }
+.agent-sol-wallet .activity-row .delta.pos { color: #1b5e20; }
+.agent-sol-wallet .activity-row .delta.neg { color: #c62828; }
+.agent-sol-wallet .activity-row .ts { color: #999; font-size: .7rem; }
+.agent-sol-wallet .activity-empty { color: #aaa; font-size: .75rem; padding: .35rem 0; }
+.agent-sol-wallet .badge-airdrop { background: #e7f5e9; color: #1b5e20; padding: .1rem .45rem; border-radius: 999px; font-size: .65rem; font-weight: 600; margin-left: .35rem; }
`;
let _styleInjected = false;
@@ -136,6 +171,40 @@ function _esc(s) {
})[c]);
}
+function _shortSig(sig) { return sig ? `${sig.slice(0, 6)}…${sig.slice(-4)}` : ''; }
+function _ago(ts) {
+ if (!ts) return '';
+ const sec = Math.max(0, Math.floor(Date.now() / 1000 - ts));
+ if (sec < 60) return `${sec}s ago`;
+ if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;
+ if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;
+ return `${Math.floor(sec / 86400)}d ago`;
+}
+function _explorerTxUrl(sig, network) {
+ return network === 'devnet'
+ ? `https://explorer.solana.com/tx/${sig}?cluster=devnet`
+ : `https://solscan.io/tx/${sig}`;
+}
+function _renderActivityRow(a, network) {
+ const sigShort = _shortSig(a.signature);
+ const url = _explorerTxUrl(a.signature, network);
+ const delta = a.sol_delta;
+ let deltaCls = '', deltaText = '—';
+ if (typeof delta === 'number') {
+ deltaCls = delta > 0 ? 'pos' : delta < 0 ? 'neg' : '';
+ deltaText = `${delta > 0 ? '+' : ''}${delta.toFixed(4)} SOL`;
+ }
+ const failed = a.success === false ? '<span class="ts" style="color:#c62828">·failed</span>' : '';
+ const summary = a.summary ? `<span class="ts">· ${_esc(a.summary)}</span>` : '';
+ return `
+ <div class="activity-row">
+ <a class="sig" href="${_esc(url)}" target="_blank" rel="noopener">${_esc(sigShort)}</a>
+ <span class="ts">${_esc(_ago(a.block_time))}</span>
+ ${summary}${failed}
+ <span class="delta ${deltaCls}">${_esc(deltaText)}</span>
+ </div>`;
+}
+
/**
* Mount the wallet card into the agent home panel.
*
@@ -164,6 +233,10 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {
busy: false,
progress: null,
err: null,
+ activity: [],
+ activityLoaded: false,
+ airdropping: false,
+ airdropMsg: null,
};
let abort = null;
let balanceTimer = null;
@@ -211,6 +284,49 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {
balanceTimer = null;
}
+ async function refreshActivity() {
+ if (!state.address) return;
+ try {
+ const data = await fetchAgentSolanaActivity(identity.id, state.network, 10);
+ state.activity = data?.signatures || [];
+ state.activityLoaded = true;
+ const host = root.querySelector('[data-host="activity-list"]');
+ if (host) {
+ host.innerHTML = state.activity.length
+ ? state.activity.map((a) => _renderActivityRow(a, state.network)).join('')
+ : '<div class="activity-empty">No on-chain activity yet.</div>';
+ }
+ } catch (e) {
+ state.activityLoaded = true;
+ const host = root.querySelector('[data-host="activity-list"]');
+ if (host) host.innerHTML = `<div class="activity-empty" style="color:#b71c1c">Could not load activity: ${_esc(e.message)}</div>`;
+ }
+ }
+
+ async function onAirdrop() {
+ state.airdropping = true;
+ state.airdropMsg = 'Requesting devnet airdrop…';
+ state.err = null;
+ render();
+ try {
+ const data = await requestAgentSolanaAirdrop(identity.id);
+ state.airdropMsg = `Airdrop confirmed: +${data.sol} SOL`;
+ // Wait a moment for RPC to reflect, then refresh.
+ setTimeout(() => {
+ refreshBalance();
+ refreshActivity();
+ state.airdropMsg = null;
+ render();
+ }, 1500);
+ } catch (e) {
+ state.err = e.message;
+ state.airdropMsg = null;
+ } finally {
+ state.airdropping = false;
+ render();
+ }
+ }
+
function render() {
if (!state.loaded) {
root.innerHTML = `<div class="skel">Loading Solana wallet…</div>`;
@@ -220,6 +336,7 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {
const pfx = state.vanityPrefix || '';
const rest = state.address.slice(pfx.length);
const solDisplay = state.sol == null ? '—' : `${state.sol.toFixed(4)} SOL`;
+ const isDevnet = state.network === 'devnet';
root.innerHTML = `
<h3>Solana wallet${state.source ? `<span class="src">· ${_esc(state.source)}</span>` : ''}</h3>
<div class="addr"><span class="pfx">${_esc(pfx)}</span>${_esc(rest)}</div>
@@ -233,25 +350,54 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {
</span>
</div>
<div class="row">
- <button data-act="copy">Copy address</button>
- <button data-act="explorer">Explorer</button>
+ <button data-act="copy">Copy</button>
+ <button data-act="explorer">Explorer ↗</button>
+ ${isDevnet ? `<button data-act="airdrop" ${state.airdropping ? 'disabled' : ''}>${state.airdropping ? 'Requesting…' : 'Airdrop 1 SOL'}</button>` : ''}
+ <button data-act="refresh-activity">Refresh</button>
<button data-act="replace">Replace</button>
</div>
+ ${state.airdropMsg ? `<div class="progress">${_esc(state.airdropMsg)}</div>` : ''}
${state.err ? `<div class="err">${_esc(state.err)}</div>` : ''}
+ <div class="activity" data-host="activity">
+ <div class="activity-h">Recent activity <button data-act="refresh-activity-mini" type="button">↻</button></div>
+ <div data-host="activity-list">
+ ${state.activityLoaded
+ ? (state.activity.length
+ ? state.activity.map((a) => _renderActivityRow(a, state.network)).join('')
+ : '<div class="activity-empty">No on-chain activity yet.</div>')
+ : '<div class="activity-empty">Loading…</div>'}
+ </div>
+ </div>
`;
- root.querySelector('[data-act="copy"]').addEventListener('click', () => {
+ root.querySelector('[data-act="copy"]').addEventListener('click', (e) => {
navigator.clipboard?.writeText(state.address).catch(() => {});
+ e.currentTarget.textContent = 'Copied';
+ setTimeout(() => { const b = root.querySelector('[data-act="copy"]'); if (b) b.textContent = 'Copy'; }, 1200);
});
root.querySelector('[data-act="explorer"]').addEventListener('click', () => {
- const cluster = state.network === 'devnet' ? '?cluster=devnet' : '';
+ const cluster = isDevnet ? '?cluster=devnet' : '';
window.open(`https://explorer.solana.com/address/${state.address}${cluster}`, '_blank', 'noopener');
});
root.querySelector('[data-act="replace"]').addEventListener('click', onReplace);
root.querySelector('[data-act="network"]').addEventListener('change', (e) => {
state.network = e.target.value;
+ state.activityLoaded = false;
+ state.activity = [];
+ refreshBalance();
+ refreshActivity();
+ });
+ root.querySelector('[data-act="refresh-activity"]')?.addEventListener('click', () => {
refreshBalance();
+ refreshActivity();
+ });
+ root.querySelector('[data-act="refresh-activity-mini"]')?.addEventListener('click', () => {
+ refreshActivity();
});
+ if (isDevnet) {
+ root.querySelector('[data-act="airdrop"]').addEventListener('click', onAirdrop);
+ }
startBalancePoll();
+ if (!state.activityLoaded) refreshActivity();
return;
}
stopBalancePoll();
diff --git a/src/app.js b/src/app.js
index ce3c6b255..3e75ea0dc 100644
--- a/src/app.js
+++ b/src/app.js
@@ -1094,6 +1094,14 @@ class App {
}),
);
}
+ if (data.type === 'pumpfun-feed:set-narrate') {
+ document.body.dispatchEvent(
+ new CustomEvent('pumpfun-feed:set-narrate', {
+ detail: { on: !!data.on },
+ bubbles: true,
+ }),
+ );
+ }
});
}
diff --git a/src/pump/agent-token-widget.js b/src/pump/agent-token-widget.js
index eec2a0b80..3dfa8ac3e 100644
--- a/src/pump/agent-token-widget.js
+++ b/src/pump/agent-token-widget.js
@@ -189,6 +189,15 @@ const STYLES = `
}
.atok-gov b { color: rgba(255,200,140,0.85); font-weight: 500; }
+.atok-rep {
+ margin-top: 0.7rem; padding: 0.45rem 0.7rem; border-radius: 8px;
+ background: rgba(255,200,140,0.05); display: flex; align-items: center; gap: 0.5rem;
+ font-size: 0.82rem; color: rgba(255,220,180,0.95);
+}
+.atok-rep-stars { letter-spacing: 0.04em; color: #ffd57a; }
+.atok-rep-num { font-variant-numeric: tabular-nums; color: #fff; }
+.atok-rep-meta { color: rgba(255,255,255,0.5); font-size: 0.75rem; }
+
.atok-mobile-strip {
display: none;
}
@@ -243,12 +252,15 @@ export class AgentTokenWidget {
this.balances = null;
this.quote = null;
this.feed = [];
+ this.reputation = null; // /api/agents/solana-reputation snapshot
this.lastPrice = null;
this.lastVaults = null;
this.lastFeedTop = null;
this._mobileStrip = null;
this._poll = null;
this._destroyed = false;
+ this._wsUnsubs = []; // realtime onAccountChange subscriptions
+ this._wsConn = null;
injectStyles();
}
@@ -257,16 +269,81 @@ export class AgentTokenWidget {
this.mount.innerHTML = `<div class="atok"><div class="atok-empty">Loading $AGENT…</div></div>`;
await this._refresh();
if (this.token) {
- this._poll = setInterval(() => this._refresh().catch(() => {}), POLL_MS);
+ // Polling is the fallback. Real-time vault subscription kicks in via
+ // _ensureRealtime() and shrinks the polling interval to a long beat
+ // (60s) used only for stats/feed/quote that lack account-subscriptions.
+ this._poll = setInterval(() => this._refresh().catch(() => {}), 60_000);
+ this._ensureRealtime().catch(() => {});
}
}
destroy() {
this._destroyed = true;
if (this._poll) clearInterval(this._poll);
+ this._teardownRealtime();
if (this._mobileStrip?.parentNode) this._mobileStrip.parentNode.removeChild(this._mobileStrip);
}
+ async _ensureRealtime() {
+ if (!this.token || !this.balances) return;
+ if (this._wsUnsubs.length) return; // already subscribed
+ try {
+ const [{ Connection, PublicKey }] = await Promise.all([import('@solana/web3.js')]);
+ const url =
+ this.token.network === 'devnet'
+ ? 'https://api.devnet.solana.com'
+ : 'https://api.mainnet-beta.solana.com';
+ const conn = new Connection(url, 'confirmed');
+ this._wsConn = conn;
+ const subscribe = (addr, name) => {
+ if (!addr) return;
+ try {
+ const id = conn.onAccountChange(
+ new PublicKey(addr),
+ () => this._refreshBalancesOnly().catch(() => {}),
+ 'confirmed',
+ );
+ this._wsUnsubs.push({ id, conn });
+ } catch {
+ /* ignore subscription failures, polling fallback covers it */
+ }
+ };
+ subscribe(this.balances.payment?.address, 'payment');
+ subscribe(this.balances.buyback?.address, 'buyback');
+ subscribe(this.balances.withdraw?.address, 'withdraw');
+ } catch {
+ /* RPC may not support websocket; polling continues */
+ }
+ }
+
+ _teardownRealtime() {
+ for (const sub of this._wsUnsubs) {
+ try {
+ sub.conn.removeAccountChangeListener(sub.id);
+ } catch {
+ /* swallow */
+ }
+ }
+ this._wsUnsubs = [];
+ this._wsConn = null;
+ }
+
+ async _refreshBalancesOnly() {
+ if (this._destroyed || !this.token) return;
+ try {
+ const balRes = await fetch(
+ `/api/pump/balances?mint=${this.token.mint}&network=${this.token.network}`,
+ ).then((r) => r.json());
+ if (balRes.balances) {
+ this._compareAndEmit(balRes.balances, this.feed);
+ this.balances = balRes.balances;
+ this._renderLive();
+ }
+ } catch {
+ /* silent */
+ }
+ }
+
async _refresh() {
if (this._destroyed) return;
try {
@@ -284,9 +361,12 @@ export class AgentTokenWidget {
return;
}
- // Live state: parallel fetch balances, quote, feed.
+ // Live state: parallel fetch balances, quote, feed, and reputation
+ // overlay. Reputation lookup keys off the agent's metaplex-core asset
+ // pubkey from the parent identity (passed in via the `identity` prop).
try {
- const [balRes, quoteRes, feedRes] = await Promise.all([
+ const repAsset = this.identity?.meta?.sol_mint_address || this.identity?.meta?.onchain?.onchain_id || null;
+ const [balRes, quoteRes, feedRes, repRes] = await Promise.all([
fetch(
`/api/pump/balances?mint=${this.token.mint}&network=${this.token.network}`,
).then((r) => r.json()),
@@ -296,12 +376,21 @@ export class AgentTokenWidget {
fetch(
`/api/pump/payments-list?mint=${this.token.mint}&network=${this.token.network}&limit=8`,
).then((r) => r.json()),
+ repAsset
+ ? fetch(
+ `/api/agents/solana-reputation?asset=${repAsset}&network=${this.token.network}`,
+ )
+ .then((r) => r.json())
+ .catch(() => null)
+ : Promise.resolve(null),
]);
this._compareAndEmit(balRes.balances, feedRes.data);
this.balances = balRes.balances || null;
this.quote = quoteRes || null;
this.feed = feedRes.data || [];
+ this.reputation = repRes || null;
this._renderLive();
+ this._ensureRealtime().catch(() => {});
} catch (e) {
this._renderError(e.message);
}
@@ -436,6 +525,7 @@ export class AgentTokenWidget {
? `${fmtUsdc((BigInt(stats.total_atomics || '0') * BigInt(buybackBps)) / 10_000n)} routed to buyback so far across <b>${stats.unique_payers}</b> unique payer${stats.unique_payers === 1 ? '' : 's'}.`
: `If this agent earns <b>$10/mo</b>, buyback burns <b>${fmtUsdc((10_000_000n * BigInt(buybackBps)) / 10_000n)}/mo</b> of $${symbol}.`;
+ const solscanCluster = this.token.network === 'devnet' ? '?cluster=devnet' : '';
const feedRows = (this.feed || [])
.slice(0, 5)
.map((p) => {
@@ -445,18 +535,56 @@ export class AgentTokenWidget {
? `<code>${p.skill_id}</code>`
: 'paid call';
const buybackShare = (BigInt(p.amount_atomics || '0') * BigInt(buybackBps)) / 10_000n;
+ const pdaLink = p.invoice_pda
+ ? `<a href="https://solscan.io/account/${p.invoice_pda}${solscanCluster}" target="_blank" rel="noopener" title="Open on-chain invoice receipt" style="color:rgba(180,210,255,0.7);text-decoration:none;font-size:0.7rem;">PDA↗</a>`
+ : '';
+ const txLink = p.tx_signature
+ ? `<a href="https://solscan.io/tx/${p.tx_signature}${solscanCluster}" target="_blank" rel="noopener" title="Open settlement tx" style="color:rgba(180,210,255,0.7);text-decoration:none;font-size:0.7rem;">tx↗</a>`
+ : '';
return `
<div class="atok-feed-row">
<div>${shortAddr(p.payer_wallet, 4)} · ${why}</div>
<div style="display:flex;gap:0.5rem;align-items:center;">
<span>${fmtUsdc(p.amount_atomics)}</span>
${buybackBps > 0 ? `<span class="atok-buyback-pill">+${fmtUsdc(buybackShare)} 🔥</span>` : ''}
+ ${pdaLink}
+ ${txLink}
<span style="color:rgba(255,255,255,0.35);font-size:0.7rem;">${timeAgo(p.confirmed_at || p.created_at)}</span>
</div>
</div>`;
})
.join('');
+ // Burns feed (separate from payments)
+ const burnsFeedRows = (t.burns_feed || [])
+ .slice(0, 5)
+ .map((b) => `
+ <div class="atok-feed-row">
+ <div>🔥 burn</div>
+ <div style="display:flex;gap:0.5rem;align-items:center;">
+ <span>${fmtUsdc(b.burn_amount || '0')}</span>
+ ${b.tx_signature ? `<a href="https://solscan.io/tx/${b.tx_signature}${solscanCluster}" target="_blank" rel="noopener" style="color:rgba(180,210,255,0.7);text-decoration:none;font-size:0.7rem;">tx↗</a>` : ''}
+ <span style="color:rgba(255,255,255,0.35);font-size:0.7rem;">${timeAgo(b.created_at)}</span>
+ </div>
+ </div>`)
+ .join('');
+ const burnsBlock = burnsFeedRows
+ ? `<div class="atok-feed">
+ <div class="atok-feed-title">Buybacks</div>
+ ${burnsFeedRows}
+ </div>`
+ : '';
+
+ // Reputation overlay
+ const rep = this.reputation;
+ const repBlock = rep && rep.feedback?.total > 0
+ ? `<div class="atok-rep" title="Reputation drives auto-governance of buyback share.">
+ <span class="atok-rep-stars">${'★'.repeat(Math.round(rep.feedback.score_avg_weighted || rep.feedback.score_avg || 0))}${'☆'.repeat(5 - Math.round(rep.feedback.score_avg_weighted || rep.feedback.score_avg || 0))}</span>
+ <span class="atok-rep-num">${(rep.feedback.score_avg_weighted || rep.feedback.score_avg || 0).toFixed(2)}</span>
+ <span class="atok-rep-meta">· ${rep.feedback.total} review${rep.feedback.total === 1 ? '' : 's'}${rep.feedback.unique_attesters ? ` · ${rep.feedback.unique_attesters} unique` : ''}</span>
+ </div>`
+ : '';
+
const feedBlock = feedRows
? `<div class="atok-feed">
<div class="atok-feed-title">Recent payments</div>
@@ -535,8 +663,10 @@ export class AgentTokenWidget {
</div>
${totalBurned}
+ ${repBlock}
${govExplain}
${feedBlock}
+ ${burnsBlock}
${ownerActions}
</div>
`;
diff --git a/src/widgets/pumpfun-feed.js b/src/widgets/pumpfun-feed.js
index 4a228cad2..60ae66b63 100644
--- a/src/widgets/pumpfun-feed.js
+++ b/src/widgets/pumpfun-feed.js
@@ -57,6 +57,12 @@ export async function mountPumpfunFeed(viewer, config, container, ctx = {}) {
const maxCards = Math.max(1, Math.min(50, config.maxCards || 8));
const protocol = ctx.protocol || (typeof window !== 'undefined' ? window.VIEWER?.agent_protocol : null);
+ let narrateOn = config.autoNarrate !== false;
+
+ const onNarrateToggle = (e) => {
+ narrateOn = !!e.detail?.on;
+ };
+ (container || document.body).addEventListener('pumpfun-feed:set-narrate', onNarrateToggle);
let focusMint = null;
const matchesFocus = (ev) =>
@@ -85,7 +91,7 @@ export async function mountPumpfunFeed(viewer, config, container, ctx = {}) {
if (!ev) return;
if (!matchesFocus(ev)) return;
addCard(stack, renderClaim(ev), maxCards);
- if (config.autoNarrate) narrateClaim(protocol, ev);
+ if (narrateOn) narrateClaim(protocol, ev);
});
es.addEventListener('graduation', (msg) => {
@@ -93,7 +99,7 @@ export async function mountPumpfunFeed(viewer, config, container, ctx = {}) {
if (!ev) return;
if (!matchesFocus(ev)) return;
addCard(stack, renderGraduation(ev), maxCards);
- if (config.autoNarrate) narrateGraduation(protocol, ev);
+ if (narrateOn) narrateGraduation(protocol, ev);
});
es.addEventListener('error', () => {
@@ -112,6 +118,7 @@ export async function mountPumpfunFeed(viewer, config, container, ctx = {}) {
es.close();
} catch {}
(container || document.body).removeEventListener('pumpfun-feed:focus-mint', onFocus);
+ (container || document.body).removeEventListener('pumpfun-feed:set-narrate', onNarrateToggle);
root.remove();
},
};
diff --git a/tests/api/pump-fun-mcp.test.js b/tests/api/pump-fun-mcp.test.js
new file mode 100644
index 000000000..15a9d5b89
--- /dev/null
+++ b/tests/api/pump-fun-mcp.test.js
@@ -0,0 +1,200 @@
+// Tests for /api/pump-fun-mcp — the in-house JSON-RPC route serving the
+// pump-fun skill. SDKs and Solana RPC are mocked; the test focuses on the
+// route's contract: JSON-RPC envelope, tool dispatch, on-chain reads, and
+// the indexer-not-configured error path (no fabricated payloads).
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+// Mock rate-limit + clientIp so the route never blocks on Upstash.
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { mcpIp: vi.fn(async () => ({ success: true })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+// Mock the pump.js SDK adapter — we exercise the route, not Solana.
+const sdkMock = {
+ fetchBuyState: vi.fn(),
+ fetchBondingCurve: vi.fn(),
+ fetchGlobal: vi.fn(),
+};
+const connectionMock = {
+ getAccountInfo: vi.fn(),
+ getTokenLargestAccounts: vi.fn(),
+};
+vi.mock('../../api/_lib/pump.js', () => ({
+ getPumpSdk: vi.fn(async () => ({ sdk: sdkMock, BN: function () {}, web3: {} })),
+ getConnection: vi.fn(() => connectionMock),
+ solanaPubkey: vi.fn((s) => {
+ if (!s || s === 'bad') return null;
+ return { toString: () => s, toBuffer: () => Buffer.alloc(32) };
+ }),
+}));
+
+// Mock the upstream pumpfun-claims-bot client.
+vi.mock('../../api/_lib/pumpfun-mcp.js', () => ({
+ pumpfunBotEnabled: vi.fn(() => false),
+ pumpfunMcp: { creatorIntel: vi.fn(), recentClaims: vi.fn(), graduations: vi.fn() },
+}));
+
+// ── helpers ────────────────────────────────────────────────────────────────
+function makeReq(body) {
+ const stream = body
+ ? Readable.from([Buffer.from(JSON.stringify(body))])
+ : Readable.from([]);
+ stream.method = 'POST';
+ stream.url = '/api/pump-fun-mcp';
+ stream.headers = { host: 'localhost', 'content-type': 'application/json' };
+ return stream;
+}
+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 call(rpc) {
+ const { default: handler } = await import('../../api/pump-fun-mcp.js');
+ const res = makeRes();
+ await handler(makeReq(rpc), res);
+ return { res, json: res.body ? JSON.parse(res.body) : null };
+}
+
+beforeEach(() => {
+ sdkMock.fetchBuyState.mockReset();
+ sdkMock.fetchBondingCurve.mockReset();
+ connectionMock.getAccountInfo.mockReset();
+ connectionMock.getTokenLargestAccounts.mockReset();
+});
+
+// ── Tests ──────────────────────────────────────────────────────────────────
+
+describe('initialize', () => {
+ it('returns server info and protocol version', async () => {
+ const { res, json } = await call({ jsonrpc: '2.0', id: 1, method: 'initialize' });
+ expect(res.statusCode).toBe(200);
+ expect(json.result.protocolVersion).toBeDefined();
+ expect(json.result.serverInfo.name).toBe('three.ws-pumpfun-mcp');
+ });
+});
+
+describe('tools/list', () => {
+ it('returns all 10 declared tools with schemas', async () => {
+ const { json } = await call({ jsonrpc: '2.0', id: 1, method: 'tools/list' });
+ expect(Array.isArray(json.result.tools)).toBe(true);
+ expect(json.result.tools).toHaveLength(10);
+ const names = json.result.tools.map((t) => t.name).sort();
+ expect(names).toEqual(
+ [
+ 'getBondingCurve',
+ 'getCreatorProfile',
+ 'getGraduatedTokens',
+ 'getKingOfTheHill',
+ 'getNewTokens',
+ 'getTokenDetails',
+ 'getTokenHolders',
+ 'getTokenTrades',
+ 'getTrendingTokens',
+ 'searchTokens',
+ ].sort(),
+ );
+ for (const t of json.result.tools) expect(t.inputSchema.type).toBe('object');
+ });
+});
+
+describe('tools/call getBondingCurve', () => {
+ it('returns curve data from on-chain fetchBuyState', async () => {
+ sdkMock.fetchBuyState.mockResolvedValueOnce({
+ bondingCurve: {
+ realSolReserves: { toString: () => '50000000000' }, // 50 SOL
+ realTokenReserves: { toString: () => '500000000' },
+ virtualSolReserves: { toString: () => '30000000000' },
+ virtualTokenReserves: { toString: () => '1073000000' },
+ complete: false,
+ },
+ });
+ const { json } = await call({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'getBondingCurve', arguments: { mint: 'Mint1', network: 'mainnet' } },
+ });
+ expect(json.error).toBeUndefined();
+ const data = json.result.structuredContent;
+ expect(data.complete).toBe(false);
+ expect(data.solReserves).toBe('50.0000');
+ expect(data.graduationPercent).toBeGreaterThan(0);
+ expect(data.graduationPercent).toBeLessThan(100);
+ });
+
+ it('returns rpc error -32602 on invalid mint', async () => {
+ const { json } = await call({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'getBondingCurve', arguments: { mint: 'bad' } },
+ });
+ expect(json.error.code).toBe(-32602);
+ });
+});
+
+describe('tools/call getTokenHolders', () => {
+ it('returns concentration analysis from getTokenLargestAccounts', async () => {
+ connectionMock.getTokenLargestAccounts.mockResolvedValueOnce({
+ value: [
+ { address: { toString: () => 'A' }, amount: '5000000', uiAmount: 50 },
+ { address: { toString: () => 'B' }, amount: '3000000', uiAmount: 30 },
+ { address: { toString: () => 'C' }, amount: '2000000', uiAmount: 20 },
+ ],
+ });
+ const { json } = await call({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'getTokenHolders', arguments: { mint: 'M', limit: 3 } },
+ });
+ const data = json.result.structuredContent;
+ expect(data.count).toBe(3);
+ expect(data.topHolderPercent).toBeCloseTo(50);
+ expect(data.holders[0].percent).toBeCloseTo(50);
+ });
+});
+
+describe('tools/call indexer-required tools', () => {
+ it('returns -32004 when PUMPFUN_BOT_URL is not configured', async () => {
+ const { json } = await call({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'getTrendingTokens', arguments: { limit: 5 } },
+ });
+ expect(json.error.code).toBe(-32004);
+ expect(json.error.message).toMatch(/indexer/i);
+ });
+});
+
+describe('unknown methods/tools', () => {
+ it('returns -32601 for unknown method', async () => {
+ const { json } = await call({ jsonrpc: '2.0', id: 1, method: 'tools/eat' });
+ expect(json.error.code).toBe(-32601);
+ });
+
+ it('returns -32601 for unknown tool', async () => {
+ const { json } = await call({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'mintInfiniteUSDC', arguments: {} },
+ });
+ expect(json.error.code).toBe(-32601);
+ });
+});
diff --git a/tests/src/pump-fun-skill.test.js b/tests/src/pump-fun-skill.test.js
index c5a618e9d..2c77161e2 100644
--- a/tests/src/pump-fun-skill.test.js
+++ b/tests/src/pump-fun-skill.test.js
@@ -74,6 +74,9 @@ describe('pump-fun skill bundle', () => {
expect(captured.body.method).toBe('tools/call');
expect(captured.body.params.name).toBe('searchTokens');
expect(captured.body.params.arguments).toEqual({ query: 'pepe', limit: 3 });
+ // Endpoint must resolve against the page origin (or the same-origin
+ // fallback) and target our in-house MCP route, never an external host.
+ expect(captured.url.endsWith('/api/pump-fun-mcp')).toBe(true);
});
it('getCreatorProfile returns negative sentiment when rug flags present', async () => {
diff --git a/tests/src/pumpfun-compose-contract.test.js b/tests/src/pumpfun-compose-contract.test.js
index 5906e7769..87406f88e 100644
--- a/tests/src/pumpfun-compose-contract.test.js
+++ b/tests/src/pumpfun-compose-contract.test.js
@@ -65,7 +65,7 @@ describe('pump-fun compose ↔ MCP contract', () => {
expect(skills._performed).toContainEqual({ name: 'pumpfun-buy', args: { mint: 'MINT1', solAmount: 0.1 } });
});
- it('researchAndBuy with simulate:true skips signing but still vets', async () => {
+ it('researchAndBuy with dryRun:true skips signing but still vets', async () => {
const skills = makeSkills();
registerPumpFunComposeSkills(skills);
const skill = skills.get('pumpfun-research-and-buy');
@@ -75,10 +75,10 @@ describe('pump-fun compose ↔ MCP contract', () => {
fetchMock.mockResolvedValueOnce(jsonRpc({ total: 100, topHolderPct: 5 }));
fetchMock.mockResolvedValueOnce(jsonRpc({ rugCount: 0 }));
- const r = await skill.handler({ query: 'bar', amountSol: 0.05, simulate: true }, {});
+ const r = await skill.handler({ query: 'bar', amountSol: 0.05, dryRun: true }, {});
expect(r.data.decision).toBe('buy');
- expect(r.data.simulate).toBe(true);
- expect(r.data.sig).toMatch(/^SIMULATED:buy:/);
+ expect(r.data.dryRun).toBe(true);
+ expect(r.data.sig).toBe(null);
expect(skills.perform).not.toHaveBeenCalledWith('pumpfun-buy', expect.anything(), expect.anything());
});
@@ -121,7 +121,7 @@ describe('pump-fun compose ↔ MCP contract', () => {
fetchMock.mockResolvedValueOnce(jsonRpc({ trades: [] })); // trades
fetchMock.mockResolvedValueOnce(jsonRpc({ creator: 'DEV' })); // details
- const r = await skill.handler({ mints: ['MINT_X'], durationSec: 1, simulate: false }, { skillConfig: { pollMs: 0 } });
+ const r = await skill.handler({ mints: ['MINT_X'], durationSec: 1, dryRun: false }, { skillConfig: { pollMs: 0 } });
expect(r.data.exited).toEqual(['MINT_X']);
expect(r.data.events[0].trigger).toMatch(/top holder 60/);
expect(skills.perform).toHaveBeenCalledWith('pumpfun-sell', { mint: 'MINT_X', tokenAmount: '12345' }, expect.anything());
@@ -171,4 +171,62 @@ describe('pump-fun compose ↔ MCP contract', () => {
const r2 = await snipe.handler({ durationSec: 1, sessionId: 'S1' }, ctx);
expect(r2.data.spent).toBe(0.05); // unchanged — A was already seen
});
+
+ it('rugExitWatch skips (no `exited` mark) when userBalance is 0', async () => {
+ const skills = makeSkills();
+ // Override pumpfun-status to return zero balance
+ skills.perform = vi.fn(async (name) => {
+ if (name === 'pumpfun-status') return { success: true, data: { userBalance: '0' } };
+ return { success: false };
+ });
+ registerPumpFunComposeSkills(skills);
+ const skill = skills.get('pumpfun-rug-exit-watch');
+
+ fetchMock.mockResolvedValueOnce(jsonRpc({ topHolderPct: 60 }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ trades: [] }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ creator: 'DEV' }));
+
+ const r = await skill.handler(
+ { mints: ['MINT_Z'], durationSec: 1, dryRun: false },
+ { skillConfig: { pollMs: 0 } },
+ );
+ expect(r.data.exited).toEqual([]); // not marked as exited — we never owned it
+ expect(r.data.events[0].action).toBe('skipped-no-balance');
+ expect(skills.perform).not.toHaveBeenCalledWith('pumpfun-sell', expect.anything(), expect.anything());
+ });
+
+ it('autoSnipe aborts promptly via signal', async () => {
+ const skills = makeSkills();
+ registerPumpFunComposeSkills(skills);
+ const snipe = skills.get('pumpfun-auto-snipe');
+ const ctrl = new AbortController();
+
+ // Pre-abort the signal — loop should bail before any MCP call.
+ ctrl.abort();
+ const start = Date.now();
+ const r = await snipe.handler(
+ { durationSec: 60, signal: ctrl.signal },
+ { skillConfig: { pollMs: 100, perTradeSol: 0.05, sessionSpendCapSol: 1 } },
+ );
+ expect(Date.now() - start).toBeLessThan(200); // would otherwise wait pollMs+
+ expect(r.data.reason).toBe('aborted');
+ });
+
+ it('compose progress events fire on every state change', async () => {
+ const skills = makeSkills();
+ registerPumpFunComposeSkills(skills);
+ const skill = skills.get('pumpfun-research-and-buy');
+
+ fetchMock.mockResolvedValueOnce(jsonRpc({ results: [{ mint: 'MINT3' }] }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ creator: 'C3' }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ total: 100, topHolderPct: 5 }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ rugCount: 0 }));
+
+ const events = [];
+ const onProgress = (e) => events.push(e.type);
+ await skill.handler({ query: 'foo', dryRun: true, onProgress }, {});
+ expect(events).toContain('search');
+ expect(events).toContain('vet');
+ expect(events).toContain('dry-buy');
+ });
});
diff --git a/vercel.json b/vercel.json
index 0f7974555..f59909f15 100644
--- a/vercel.json
+++ b/vercel.json
@@ -46,8 +46,8 @@
{ "src": "/reset-password", "dest": "/reset-password.html" },
{ "src": "/wallet-login.js", "dest": "/wallet-login.js" },
{ "src": "/wallet/(.*)", "dest": "/wallet/$1" },
- { "src": "/pumpfun", "dest": "/pumpfun-demo.html" },
- { "src": "/pumpfun/", "dest": "/pumpfun-demo.html" },
+ { "src": "/pumpfun", "dest": "/pumpfun.html" },
+ { "src": "/pumpfun/", "dest": "/pumpfun.html" },
{ "src": "/deploy", "dest": "/app.html" },
{ "src": "/dashboard", "dest": "/dashboard/index.html" },
{ "src": "/dashboard/", "dest": "/dashboard/index.html" },
@@ -256,6 +256,7 @@
{ "path": "/api/cron/run-dca", "schedule": "0 * * * *" },
{ "path": "/api/cron/run-subscriptions", "schedule": "0 * * * *" },
{ "path": "/api/cron/pumpfun-signals", "schedule": "*/15 * * * *" },
- { "path": "/api/cron/pump-agent-stats", "schedule": "*/10 * * * *" }
+ { "path": "/api/cron/pump-agent-stats", "schedule": "*/10 * * * *" },
+ { "path": "/api/cron/solana-attest-event-cleanup", "schedule": "*/10 * * * *" }
]
}