Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: add AgentTokenWidget for managing $AGENT token state and interactions

nirholas46cb318002a4
diff --git a/api/_lib/agent-spend-policy.js b/api/_lib/agent-spend-policy.js
new file mode 100644
index 000000000..9138fc904
--- /dev/null
+++ b/api/_lib/agent-spend-policy.js
@@ -0,0 +1,67 @@
+// Spend-policy guard for agent-signed Solana transactions.
+//
+// Policy lives on agent_identities.meta.spend_policy:
+// {
+// max_sol_per_tx: number, // hard cap per individual buy
+// daily_sol_cap: number, // rolling 24h sum across pumpfun.buy
+// allowed_mints?: string[], // optional allowlist (omit = any mint)
+// }
+//
+// If no policy is set, a conservative default is applied so a freshly
+// provisioned agent can't be drained by a stolen session token.
+
+import { sql } from './db.js';
+
+const DEFAULT_POLICY = {
+ max_sol_per_tx: 1,
+ daily_sol_cap: 5,
+ allowed_mints: null,
+};
+
+export function resolveSpendPolicy(meta) {
+ const p = (meta && meta.spend_policy) || {};
+ return {
+ max_sol_per_tx: Number.isFinite(p.max_sol_per_tx) ? p.max_sol_per_tx : DEFAULT_POLICY.max_sol_per_tx,
+ daily_sol_cap: Number.isFinite(p.daily_sol_cap) ? p.daily_sol_cap : DEFAULT_POLICY.daily_sol_cap,
+ allowed_mints: Array.isArray(p.allowed_mints) && p.allowed_mints.length ? p.allowed_mints : null,
+ };
+}
+
+// Returns null if allowed, or { status, code, msg } if blocked.
+export async function checkBuyAllowed({ agentId, meta, mint, solAmount }) {
+ const policy = resolveSpendPolicy(meta);
+
+ if (solAmount > policy.max_sol_per_tx) {
+ return {
+ status: 403,
+ code: 'spend_cap_exceeded',
+ msg: `solAmount ${solAmount} > max_sol_per_tx ${policy.max_sol_per_tx}`,
+ };
+ }
+
+ if (policy.allowed_mints && !policy.allowed_mints.includes(mint)) {
+ return {
+ status: 403,
+ code: 'mint_not_allowed',
+ msg: `mint ${mint} not in allowed_mints`,
+ };
+ }
+
+ const [{ spent_24h } = { spent_24h: 0 }] = await sql`
+ SELECT COALESCE(SUM((payload->>'solAmount')::numeric), 0) AS spent_24h
+ FROM agent_actions
+ WHERE agent_id = ${agentId}
+ AND type = 'pumpfun.buy'
+ AND created_at > NOW() - INTERVAL '24 hours'
+ `;
+ const spent = Number(spent_24h) || 0;
+ if (spent + solAmount > policy.daily_sol_cap) {
+ return {
+ status: 403,
+ code: 'daily_cap_exceeded',
+ msg: `would spend ${spent + solAmount} SOL in 24h, cap is ${policy.daily_sol_cap}`,
+ };
+ }
+
+ return null;
+}
diff --git a/api/agents.js b/api/agents.js
index 39caeafcb..8b31d1040 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -310,6 +310,23 @@ function decorate(row, isOwner = true) {
delete meta.encrypted_wallet_key;
delete meta.encrypted_solana_secret;
+ // Surface canonical blocks at the top level so the frontend doesn't need to
+ // know they live under `meta`. Treat `meta.*` as the source of truth for
+ // new code; legacy fields (chain_id, erc8004_agent_id) are still emitted
+ // for backwards compat below.
+ const onchain = meta.onchain || null;
+ const token = meta.token || null;
+ const payments = meta.payments
+ ? {
+ // Public-safe view: the receiver address is intended to be public,
+ // but anything secret (bot keys, configured webhook secrets, etc.)
+ // must never leave the server. Whitelist explicitly.
+ receiver: meta.payments.receiver,
+ accepted_tokens: meta.payments.accepted_tokens || [],
+ configured_at: meta.payments.configured_at,
+ }
+ : null;
+
const base = {
id: row.id,
name: row.name,
@@ -318,7 +335,10 @@ function decorate(row, isOwner = true) {
home_url: row.home_url || `/agent/${row.id}`,
skills: row.skills || [],
meta,
- is_registered: Boolean(row.erc8004_agent_id),
+ onchain,
+ token,
+ payments,
+ is_registered: Boolean(row.erc8004_agent_id) || !!onchain,
created_at: row.created_at,
};
if (isOwner) {
diff --git a/api/agents/pumpfun/buy.js b/api/agents/pumpfun/buy.js
index b0b4b3e81..d3f52ec50 100644
--- a/api/agents/pumpfun/buy.js
+++ b/api/agents/pumpfun/buy.js
@@ -8,6 +8,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/au
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 { checkBuyAllowed } from '../../_lib/agent-spend-policy.js';
import { sql } from '../../_lib/db.js';
import { Transaction, PublicKey } from '@solana/web3.js';
import { z } from 'zod';
@@ -45,7 +46,15 @@ export default async function handler(req, res, id) {
const loaded = await loadAgentForSigning(id, auth.userId);
if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
- const { keypair } = loaded;
+ const { keypair, meta } = loaded;
+
+ 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 [{ PumpSdk, OnlinePumpSdk, getBuyTokenAmountFromSolAmount }, BN, splToken] =
await Promise.all([
diff --git a/api/agents/pumpfun/portfolio.js b/api/agents/pumpfun/portfolio.js
new file mode 100644
index 000000000..b8b7d7d3d
--- /dev/null
+++ b/api/agents/pumpfun/portfolio.js
@@ -0,0 +1,186 @@
+// GET /api/agents/:id/pumpfun/portfolio?network=mainnet|devnet
+//
+// Aggregates pumpfun.buy / pumpfun.sell rows from agent_actions into per-mint
+// positions. For each mint with a non-zero token balance, fetches the current
+// SPL token amount from chain and quotes a sell-back to estimate live value.
+//
+// Response shape:
+// {
+// data: {
+// wallet, // agent's solana_address
+// network,
+// positions: [{
+// mint,
+// sol_in, // total SOL spent buying
+// sol_out, // total SOL received selling
+// realized_pnl_sol, // sol_out - matched-cost portion (FIFO not modeled; = sol_out)
+// token_balance, // base-unit string from chain
+// estimated_sol_value, // sell-back quote in SOL (decimal), null if graduated/curve missing
+// unrealized_pnl_sol, // estimated_sol_value - sol_in + sol_out
+// graduated, // bondingCurve.complete
+// }],
+// totals: { sol_in, sol_out, estimated_value_sol, unrealized_pnl_sol },
+// }
+// }
+//
+// Pricing is best-effort — RPC failures per mint are surfaced as
+// `error: <code>` on the position, not a 5xx for the whole call.
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, method, 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 } from '@solana/web3.js';
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+function lamportsToSol(bnLike) {
+ if (!bnLike) return 0;
+ const s = typeof bnLike === 'string' ? bnLike : bnLike.toString();
+ return Number(s) / 1e9;
+}
+
+export default async function handler(req, res, id) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+
+ const loaded = await loadAgentForSigning(id, auth.userId);
+ if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
+ const { keypair, meta } = loaded;
+
+ const rows = await sql`
+ SELECT type, payload
+ FROM agent_actions
+ WHERE agent_id = ${id}
+ AND type IN ('pumpfun.buy', 'pumpfun.sell', 'pumpfun.launch')
+ AND (payload->>'network') = ${network}
+ `;
+
+ // Aggregate per mint
+ const byMint = new Map();
+ for (const row of rows) {
+ const p = row.payload || {};
+ const mint = p.mint;
+ if (!mint) continue;
+ const e = byMint.get(mint) || { mint, sol_in: 0, sol_out: 0 };
+ if (row.type === 'pumpfun.buy' || row.type === 'pumpfun.launch') {
+ e.sol_in += Number(p.solAmount) || 0;
+ } else if (row.type === 'pumpfun.sell') {
+ e.sol_out += lamportsToSol(p.expectedSolLamports);
+ }
+ byMint.set(mint, e);
+ }
+
+ if (byMint.size === 0) {
+ return json(res, 200, {
+ data: {
+ wallet: meta.solana_address,
+ network,
+ positions: [],
+ totals: { sol_in: 0, sol_out: 0, estimated_value_sol: 0, unrealized_pnl_sol: 0 },
+ },
+ });
+ }
+
+ const conn = solanaConnection(network);
+ const [{ PumpSdk, OnlinePumpSdk, getSellSolAmountFromTokenAmount }, splToken, BN] =
+ await Promise.all([
+ import('@pump-fun/pump-sdk'),
+ import('@solana/spl-token'),
+ import('bn.js').then((m) => m.default || m),
+ ]);
+ const online = new OnlinePumpSdk(conn);
+ let global;
+ try {
+ global = await online.fetchGlobal();
+ } catch (err) {
+ console.error('[pumpfun/portfolio] fetchGlobal failed', err);
+ global = null;
+ }
+
+ const positions = await Promise.all(
+ [...byMint.values()].map(async (pos) => {
+ const out = { ...pos, token_balance: '0', estimated_sol_value: null, unrealized_pnl_sol: null, graduated: null };
+ let mintPk;
+ try {
+ mintPk = new PublicKey(pos.mint);
+ } catch {
+ out.error = 'invalid_mint';
+ return out;
+ }
+
+ try {
+ const ata = await splToken.getAssociatedTokenAddress(mintPk, keypair.publicKey);
+ const bal = await conn.getTokenAccountBalance(ata).catch(() => null);
+ out.token_balance = bal?.value?.amount || '0';
+ } catch (err) {
+ out.error = 'balance_fetch_failed';
+ }
+
+ if (out.token_balance === '0' || !global) {
+ out.unrealized_pnl_sol = out.sol_out - out.sol_in;
+ out.estimated_sol_value = 0;
+ return out;
+ }
+
+ 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;
+ 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';
+ }
+
+ return out;
+ }),
+ );
+
+ const totals = positions.reduce(
+ (acc, p) => {
+ acc.sol_in += p.sol_in;
+ acc.sol_out += p.sol_out;
+ if (typeof p.estimated_sol_value === 'number') acc.estimated_value_sol += p.estimated_sol_value;
+ return acc;
+ },
+ { sol_in: 0, sol_out: 0, estimated_value_sol: 0 },
+ );
+ totals.unrealized_pnl_sol = totals.estimated_value_sol + totals.sol_out - totals.sol_in;
+
+ return json(res, 200, {
+ data: {
+ wallet: meta.solana_address,
+ network,
+ positions,
+ totals,
+ },
+ });
+}
diff --git a/api/agents/solana-card.js b/api/agents/solana-card.js
index 19c80996b..64d57ea1b 100644
--- a/api/agents/solana-card.js
+++ b/api/agents/solana-card.js
@@ -63,6 +63,35 @@ export default wrap(async (req, res) => {
// pumpfun_signals table not present — omit the block entirely.
}
+ // Live token stats from the pump-agent-stats cron snapshot. Joined to
+ // pump_agent_mints so we only return data for mints we actually track.
+ let token_stats = null;
+ try {
+ const [s] = await sql`
+ select s.graduated, s.bonding_curve, s.amm,
+ s.last_signature, s.last_signature_at,
+ s.recent_tx_count, s.refreshed_at, m.mint, m.network
+ from pump_agent_stats s
+ join pump_agent_mints m on m.id = s.mint_id
+ where m.mint = ${asset} limit 1
+ `;
+ if (s) {
+ token_stats = {
+ mint: s.mint,
+ network: s.network,
+ graduated: s.graduated,
+ bonding_curve: s.bonding_curve,
+ amm: s.amm,
+ last_signature: s.last_signature,
+ last_signature_at: s.last_signature_at,
+ recent_tx_count: s.recent_tx_count,
+ refreshed_at: s.refreshed_at,
+ };
+ }
+ } catch {
+ // table missing — skip
+ }
+
return json(res, 200, {
schema_version: '1.0',
// A2A core
@@ -90,5 +119,6 @@ export default wrap(async (req, res) => {
usage: 'Sign an SPL Memo tx with one of the published schemas as JSON, including this asset_pubkey as a non-signer key.',
},
...(pumpfun ? { pumpfun } : {}),
+ ...(token_stats ? { token_stats } : {}),
}, { 'cache-control': 'public, max-age=120', 'access-control-allow-origin': '*' });
});
diff --git a/api/agents/tokens/launch-quote.js b/api/agents/tokens/launch-quote.js
new file mode 100644
index 000000000..331d1edc2
--- /dev/null
+++ b/api/agents/tokens/launch-quote.js
@@ -0,0 +1,106 @@
+/**
+ * GET /api/agents/tokens/launch-quote?initial_buy_sol=0.5&cluster=mainnet
+ *
+ * Pre-flight cost estimate for a Pump.fun coin launch. Returned to the UI
+ * before the user clicks "Launch" so they can see what the transaction will
+ * cost from their wallet.
+ *
+ * Costs:
+ * • Mint account rent ~ 0.00146 SOL (fixed; SystemProgram.createAccount)
+ * • Bonding curve PDA rent ~ 0.00203 SOL (Pump.fun create instruction)
+ * • Metadata account ~ 0.00561 SOL (Metaplex CPI inside create)
+ * • Tx fee (1 sig) ~ 0.000005 SOL
+ * • Initial buy user-provided lamports + ~1% protocol fee
+ *
+ * The exact rent numbers come from Pump.fun's program; we use conservative
+ * upper bounds rather than fetching them per-request — they don't change.
+ */
+
+import { z } from 'zod';
+import BN from 'bn.js';
+import { Connection } from '@solana/web3.js';
+import { PumpSdk, getBuyTokenAmountFromSolAmount } from '@pump-fun/pump-sdk';
+
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+
+const querySchema = z.object({
+ initial_buy_sol: z.coerce.number().min(0).max(50).default(0),
+ cluster: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+// Conservative upper bounds, in SOL.
+const FIXED_LAUNCH_COST = {
+ mintRent: 0.00146,
+ bondingCurveRent: 0.00203,
+ metadataRent: 0.00561,
+ txFee: 0.000005,
+};
+const FIXED_LAUNCH_TOTAL =
+ FIXED_LAUNCH_COST.mintRent +
+ FIXED_LAUNCH_COST.bondingCurveRent +
+ FIXED_LAUNCH_COST.metadataRent +
+ FIXED_LAUNCH_COST.txFee;
+
+function rpcUrl(cluster) {
+ return cluster === 'devnet'
+ ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
+ : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) 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://x');
+ const q = querySchema.parse({
+ initial_buy_sol: url.searchParams.get('initial_buy_sol'),
+ cluster: url.searchParams.get('cluster') || undefined,
+ });
+
+ let buyEstimate = null;
+ if (q.initial_buy_sol > 0) {
+ try {
+ const conn = new Connection(rpcUrl(q.cluster), 'confirmed');
+ const sdk = new PumpSdk(conn);
+ const global = await sdk.fetchGlobal();
+ const lamports = new BN(Math.floor(q.initial_buy_sol * 1_000_000_000));
+ const tokensOut = getBuyTokenAmountFromSolAmount({
+ global,
+ feeConfig: null,
+ mintSupply: null,
+ bondingCurve: null,
+ amount: lamports,
+ });
+ // Pump.fun protocol fee on initial buy is ~1%; surface as a separate
+ // line so the user sees what's spent vs what funds the curve.
+ buyEstimate = {
+ sol: q.initial_buy_sol,
+ tokens_out: tokensOut.toString(),
+ protocol_fee_sol: q.initial_buy_sol * 0.01,
+ };
+ } catch (e) {
+ // If RPC is unhealthy, return the structural estimate without the
+ // curve quote — the UI can still show launch costs.
+ console.warn('[launch-quote] RPC fetch failed:', e.message);
+ }
+ }
+
+ const totalSol =
+ FIXED_LAUNCH_TOTAL + q.initial_buy_sol + (buyEstimate?.protocol_fee_sol || 0);
+
+ return json(res, 200, {
+ cluster: q.cluster,
+ fixed: FIXED_LAUNCH_COST,
+ fixed_total_sol: FIXED_LAUNCH_TOTAL,
+ initial_buy: buyEstimate,
+ total_sol: totalSol,
+ });
+});
diff --git a/api/cron/pump-agent-stats.js b/api/cron/pump-agent-stats.js
new file mode 100644
index 000000000..48fcd7e6b
--- /dev/null
+++ b/api/cron/pump-agent-stats.js
@@ -0,0 +1,157 @@
+// GET/POST /api/cron/pump-agent-stats
+//
+// For every pump_agent_mints row, fetch the bonding curve (pre-graduation) or
+// canonical AMM pool (post-graduation) state plus a recent-tx snapshot, and
+// upsert into pump_agent_stats. Read endpoints (solana-card, passport) join
+// against this table instead of hitting RPC on every page load.
+//
+// Auth: `Bearer $CRON_SECRET` or Vercel cron header.
+
+import { sql } from '../_lib/db.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import {
+ getConnection,
+ getPumpSdk,
+ getAmmPoolState,
+ solanaPubkey,
+} from '../_lib/pump.js';
+
+const MAX_PER_RUN = 100;
+
+// Pump.fun graduation threshold (mainnet curve). Used only as a UI hint —
+// progress_pct is a coarse bar, not financial advice.
+const GRADUATION_REAL_SOL = 85_000_000_000n; // ~85 SOL in lamports
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const auth = req.headers.authorization || '';
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron) {
+ if (!env.CRON_SECRET) return error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ if (auth !== `Bearer ${env.CRON_SECRET}`)
+ return error(res, 401, 'unauthorized', 'cron auth required');
+ }
+
+ const mints = await sql`
+ select id, mint, network from pump_agent_mints
+ order by id limit ${MAX_PER_RUN}
+ `;
+
+ const report = { scanned: mints.length, updated: 0, errors: 0 };
+ for (const m of mints) {
+ try {
+ const stats = await snapshotMint(m);
+ await sql`
+ insert into pump_agent_stats
+ (mint_id, network, mint, graduated, bonding_curve, amm,
+ last_signature, last_signature_at, recent_tx_count, refreshed_at, error)
+ values (
+ ${m.id}, ${m.network}, ${m.mint}, ${stats.graduated},
+ ${stats.bonding_curve ? JSON.stringify(stats.bonding_curve) : null}::jsonb,
+ ${stats.amm ? JSON.stringify(stats.amm) : null}::jsonb,
+ ${stats.last_signature}, ${stats.last_signature_at},
+ ${stats.recent_tx_count}, now(), null
+ )
+ on conflict (mint_id) do update set
+ graduated = excluded.graduated,
+ bonding_curve = excluded.bonding_curve,
+ amm = excluded.amm,
+ last_signature = excluded.last_signature,
+ last_signature_at = excluded.last_signature_at,
+ recent_tx_count = excluded.recent_tx_count,
+ refreshed_at = now(),
+ error = null
+ `;
+ report.updated++;
+ } catch (e) {
+ report.errors++;
+ await sql`
+ insert into pump_agent_stats (mint_id, network, mint, error, refreshed_at)
+ values (${m.id}, ${m.network}, ${m.mint}, ${e.message || 'snapshot failed'}, now())
+ on conflict (mint_id) do update set error = excluded.error, refreshed_at = now()
+ `;
+ }
+ }
+
+ return json(res, 200, report);
+});
+
+async function snapshotMint({ network, mint }) {
+ const mintPk = solanaPubkey(mint);
+ if (!mintPk) throw new Error('invalid mint pubkey');
+
+ const out = {
+ graduated: false,
+ bonding_curve: null,
+ amm: null,
+ last_signature: null,
+ last_signature_at: null,
+ recent_tx_count: 0,
+ };
+
+ // Bonding curve
+ let curve = null;
+ try {
+ const { sdk } = await getPumpSdk({ network });
+ if (sdk.fetchBuyState) {
+ const state = await sdk.fetchBuyState(mintPk, mintPk);
+ curve = state.bondingCurve;
+ } else if (sdk.fetchBondingCurve) {
+ curve = await sdk.fetchBondingCurve(mintPk);
+ }
+ } catch {
+ curve = null;
+ }
+
+ if (curve && !curve.complete) {
+ const realSol = BigInt(curve.realSolReserves?.toString?.() ?? '0');
+ const pct =
+ GRADUATION_REAL_SOL > 0n
+ ? Number((realSol * 10000n) / GRADUATION_REAL_SOL) / 100
+ : null;
+ out.bonding_curve = {
+ real_sol: realSol.toString(),
+ real_token: curve.realTokenReserves?.toString?.() ?? null,
+ virtual_sol: curve.virtualSolReserves?.toString?.() ?? null,
+ virtual_token: curve.virtualTokenReserves?.toString?.() ?? null,
+ complete: curve.complete ?? false,
+ progress_pct: pct != null ? Math.min(100, Math.max(0, pct)) : null,
+ };
+ } else {
+ // Try AMM pool
+ try {
+ const amm = await getAmmPoolState({ network, mint: mintPk });
+ out.graduated = true;
+ out.amm = {
+ pool: amm.poolKey.toString(),
+ base_reserve: amm.baseReserve.toString(),
+ quote_reserve: amm.quoteReserve.toString(),
+ lp_supply: amm.pool.lpSupply?.toString?.() ?? null,
+ };
+ } catch (e) {
+ if (e.code !== 'pool_not_found') throw e;
+ // graduated state inferred from curve.complete only
+ if (curve?.complete) out.graduated = true;
+ }
+ }
+
+ // Recent activity snapshot via RPC
+ try {
+ const conn = getConnection({ network });
+ const sigs = await conn.getSignaturesForAddress(mintPk, { limit: 50 });
+ out.recent_tx_count = sigs.length;
+ if (sigs.length > 0) {
+ out.last_signature = sigs[0].signature;
+ if (sigs[0].blockTime) {
+ out.last_signature_at = new Date(sigs[0].blockTime * 1000).toISOString();
+ }
+ }
+ } catch {
+ // RPC hiccup — leave activity fields null
+ }
+
+ return out;
+}
diff --git a/docs/solana.md b/docs/solana.md
index feee86224..4b03e4ae3 100644
--- a/docs/solana.md
+++ b/docs/solana.md
@@ -206,7 +206,7 @@ There is no global Solana registry to query — discovery happens via the platfo
## What's intentionally not on Solana yet
-- **Reputation**: ERC-8004's `ReputationRegistry` is EVM-only. Solana agents have no on-chain feedback aggregation today. Reviews would need to live in the platform DB or in a future Anchor program.
+- **Reputation**: ERC-8004's `ReputationRegistry` is EVM-only. Solana agents have no on-chain feedback aggregation today. Reviews live in the platform DB. Off-chain pump.fun behavior signals are crawled into `pumpfun_signals` and surfaced through `solana-reputation` — see [solana-pumpfun.md](solana-pumpfun.md).
- **Validation**: Same. The `ValidationRegistry` is EVM testnet only; there is no Solana analog.
- **Delegated wallet (EIP-712)**: There is no equivalent for Solana agents. Owner = the wallet that signed the mint.
- **Cross-chain identifier**: EVM agents use `eip155:<chainId>:<registry>:<agentId>` (CAIP-10). Solana agents use the asset pubkey directly; a CAIP-10 form (`solana:<cluster-genesis>:<asset-pubkey>`) is not currently emitted by the platform.
diff --git a/examples/skills/pump-fun-strategy/SKILL.md b/examples/skills/pump-fun-strategy/SKILL.md
new file mode 100644
index 000000000..fbb2ada1a
--- /dev/null
+++ b/examples/skills/pump-fun-strategy/SKILL.md
@@ -0,0 +1,49 @@
+# pump-fun-strategy
+
+Declarative strategies. One JSON spec → live run *or* backtest, sharing the
+same evaluator so they cannot drift.
+
+## Spec
+
+```json
+{
+ "scan": { "kind": "newTokens", "limit": 20 },
+ "filters": [
+ "holders.total > 50",
+ "holders.topHolderPct < 20",
+ "creator.rugCount == 0"
+ ],
+ "entry": { "side": "buy", "amountSol": 0.05 },
+ "exit": [
+ { "if": "position.pnlPct > 50", "do": { "side": "sell", "percent": 50 } },
+ { "if": "holders.topHolderPct > 40", "do": { "side": "sell", "percent": 100 } },
+ { "if": "position.ageSec > 1800", "do": { "side": "sell", "percent": 100 } }
+ ],
+ "caps": { "sessionSpendCapSol": 0.5, "perTradeSol": 0.05, "maxOpenPositions": 5 }
+}
+```
+
+### Predicate language
+
+`<lhs> <op> <rhs>` where lhs is a dotted path into the runtime view, op is
+one of `> >= < <= == !=`, and rhs is a number (trailing `%` allowed for
+readability). The view exposes `holders.*`, `creator.*`, `curve.*`,
+`token.*`, `position.*`, `trades.*` — see [dsl.js:buildView](dsl.js).
+
+## Tools
+
+| Tool | Use it for |
+|---|---|
+| `validateStrategy` | Parse + type-check before running |
+| `runStrategy` | Live (with `simulate: true` for dry-run) |
+| `backtestStrategy` | Replay against historical trades from `getTokenTrades` |
+
+## Why this matters
+
+Compose-skill loops are imperative and hard to share. The DSL turns a strategy
+into a portable artifact you can:
+
+- Backtest before risking SOL
+- Hand to another agent to copy-trade
+- Diff between versions ("v2 added the 30-min stop")
+- Publish on the agent passport as a signed track record
diff --git a/examples/skills/pump-fun-strategy/handlers.js b/examples/skills/pump-fun-strategy/handlers.js
new file mode 100644
index 000000000..83a0739bc
--- /dev/null
+++ b/examples/skills/pump-fun-strategy/handlers.js
@@ -0,0 +1,267 @@
+// pump-fun-strategy — DSL runner + backtester. The `compileStrategy` evaluator
+// in dsl.js is the single source of truth: live runs and backtests share it,
+// so a backtest is a faithful preview of a live run.
+
+import { compileStrategy, buildView, parsePredicate, evalPredicate } from './dsl.js';
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+async function call(ctx, tool, args) {
+ const res = await ctx.skills.invoke(tool, args);
+ if (!res?.ok) throw new Error(`${tool}: ${res?.error ?? 'unknown'}`);
+ return res.data;
+}
+
+export async function validateStrategy({ strategy }) {
+ try {
+ const compiled = compileStrategy(strategy);
+ return {
+ ok: true,
+ data: {
+ filterCount: compiled.filters.length,
+ exitCount: compiled.exits.length,
+ filters: compiled.filters.map((p) => p.src),
+ exits: compiled.exits.map((e) => ({ if: e.when.src, do: e.action })),
+ },
+ };
+ } catch (e) {
+ return { ok: false, error: e.message };
+ }
+}
+
+async function fetchCandidates(ctx, scan) {
+ if (scan.kind === 'mintList') {
+ return (scan.mints ?? []).map((mint) => ({ mint }));
+ }
+ if (scan.kind === 'trending') {
+ const r = await call(ctx, 'pump-fun.getTrendingTokens', { limit: scan.limit ?? 20 });
+ return r?.tokens ?? r ?? [];
+ }
+ const r = await call(ctx, 'pump-fun.getNewTokens', { limit: scan.limit ?? 20 });
+ return r?.tokens ?? r ?? [];
+}
+
+async function snapshotMint(ctx, mint) {
+ const [details, holders, curve] = await Promise.all([
+ call(ctx, 'pump-fun.getTokenDetails', { mint }),
+ call(ctx, 'pump-fun.getTokenHolders', { mint, limit: 20 }),
+ call(ctx, 'pump-fun.getBondingCurve', { mint }).catch(() => null),
+ ]);
+ const creatorAddr = details?.creator ?? details?.token?.creator;
+ const creator = creatorAddr
+ ? await call(ctx, 'pump-fun.getCreatorProfile', { creator: creatorAddr }).catch(() => ({}))
+ : {};
+ return { details, holders, curve, creator };
+}
+
+async function maybeBuy(ctx, simulate, mint, amountSol) {
+ if (simulate) return { sig: `SIMULATED:buy:${mint}:${amountSol}`, simulated: true };
+ return call(ctx, 'pump-fun-trade.buyToken', { mint, amountSol });
+}
+async function maybeSell(ctx, simulate, args) {
+ if (simulate) return { sig: `SIMULATED:sell:${args.mint}`, simulated: true };
+ return call(ctx, 'pump-fun-trade.sellToken', args);
+}
+
+export async function runStrategy(args, ctx) {
+ const compiled = compileStrategy(args.strategy);
+ const simulate = !!args.simulate;
+ const deadline = Date.now() + args.durationSec * 1000;
+ const cap = compiled.caps.sessionSpendCapSol ?? ctx?.skillConfig?.defaultSessionSpendCapSol ?? 1.0;
+ const perTrade = compiled.entry.amountSol ?? ctx?.skillConfig?.defaultPerTradeSol ?? 0.05;
+ const pollMs = ctx?.skillConfig?.defaultPollMs ?? 5000;
+
+ const seen = new Set();
+ const positions = new Map(); // mint -> { amountTokens, entryPriceSol, openedAt }
+ const log = [];
+ let spent = 0;
+
+ while (Date.now() < deadline) {
+ // 1. Watch exits on open positions.
+ for (const [mint, pos] of positions) {
+ const snap = await snapshotMint(ctx, mint).catch(() => null);
+ if (!snap) continue;
+ const view = buildView({ ...snap, position: pos });
+ const exit = compiled.shouldExit(view);
+ if (exit) {
+ try {
+ const r = await maybeSell(ctx, simulate, {
+ mint,
+ percent: exit.percent,
+ amountTokens: exit.amountTokens,
+ });
+ log.push({ mint, action: 'exit', rule: exit, sig: r.sig, view });
+ positions.delete(mint);
+ } catch (e) {
+ log.push({ mint, action: 'exit-error', error: e.message });
+ }
+ }
+ }
+
+ // 2. Hunt for new entries while under cap.
+ if (spent + perTrade <= cap && positions.size < (compiled.caps.maxOpenPositions ?? Infinity)) {
+ const candidates = await fetchCandidates(ctx, compiled.scan);
+ for (const t of candidates) {
+ const mint = t.mint ?? t.address;
+ if (!mint || seen.has(mint) || positions.has(mint)) continue;
+ seen.add(mint);
+ const snap = await snapshotMint(ctx, mint).catch(() => null);
+ if (!snap) continue;
+ const view = buildView(snap);
+ if (!compiled.passes(view)) {
+ log.push({ mint, action: 'skip', view });
+ continue;
+ }
+ try {
+ const buy = await maybeBuy(ctx, simulate, mint, perTrade);
+ spent += perTrade;
+ positions.set(mint, {
+ amountTokens: buy.amountTokens ?? 0,
+ entryPriceSol: snap.curve?.priceSol ?? 0,
+ openedAt: Date.now(),
+ });
+ log.push({ mint, action: 'enter', sig: buy.sig, spent });
+ if (spent + perTrade > cap) break;
+ } catch (e) {
+ log.push({ mint, action: 'enter-error', error: e.message });
+ }
+ }
+ }
+
+ await sleep(pollMs);
+ }
+
+ return {
+ ok: true,
+ data: {
+ spent,
+ openPositions: [...positions.entries()].map(([mint, p]) => ({ mint, ...p })),
+ log,
+ simulate,
+ },
+ };
+}
+
+// ── Backtester ──────────────────────────────────────────────────────────────
+// Replays a strategy against historical trade arrays. No RPC, no signing.
+
+function priceFromTrade(t) {
+ // Best-effort across pump-fun shapes.
+ if (t.priceSol != null) return t.priceSol;
+ if (t.solAmount && t.tokenAmount) return t.solAmount / t.tokenAmount;
+ return null;
+}
+
+export async function backtestStrategy(args, ctx) {
+ const compiled = compileStrategy(args.strategy);
+ const mints = args.mints ?? args.strategy?.scan?.mints ?? [];
+ if (!mints.length) return { ok: false, error: 'backtest requires mints (in args or strategy.scan.mints)' };
+ const sinceMs = args.sinceMs ?? 0;
+
+ const perTrade = compiled.entry.amountSol ?? 0.05;
+ const cap = compiled.caps.sessionSpendCapSol ?? Infinity;
+
+ const trades = [];
+ let spent = 0;
+ let realized = 0;
+
+ for (const mint of mints) {
+ if (spent + perTrade > cap) break;
+
+ const [details, holders, curve, history] = await Promise.all([
+ call(ctx, 'pump-fun.getTokenDetails', { mint }).catch(() => ({})),
+ call(ctx, 'pump-fun.getTokenHolders', { mint, limit: 20 }).catch(() => ({})),
+ call(ctx, 'pump-fun.getBondingCurve', { mint }).catch(() => null),
+ call(ctx, 'pump-fun.getTokenTrades', { mint, limit: 200 }).catch(() => ({ trades: [] })),
+ ]);
+ const creatorAddr = details?.creator ?? details?.token?.creator;
+ const creator = creatorAddr
+ ? await call(ctx, 'pump-fun.getCreatorProfile', { creator: creatorAddr }).catch(() => ({}))
+ : {};
+
+ // Entry view = state at the *first* trade after sinceMs.
+ const tradeList = (history?.trades ?? history ?? [])
+ .filter((t) => (t.timestamp ?? 0) >= sinceMs)
+ .sort((a, b) => (a.timestamp ?? 0) - (b.timestamp ?? 0));
+ if (!tradeList.length) continue;
+
+ const entryView = buildView({ details, holders, creator, curve });
+ if (!compiled.passes(entryView)) {
+ trades.push({ mint, action: 'skip', view: entryView });
+ continue;
+ }
+
+ const entryPrice = priceFromTrade(tradeList[0]);
+ if (!entryPrice) {
+ trades.push({ mint, action: 'skip', reason: 'no entry price' });
+ continue;
+ }
+
+ const tokens = perTrade / entryPrice;
+ spent += perTrade;
+
+ // Walk forward, evaluating exit predicates at each tick.
+ let exitedAt = null;
+ let exitReason = 'eod';
+ let exitPrice = priceFromTrade(tradeList[tradeList.length - 1]) ?? entryPrice;
+
+ const openedAt = tradeList[0].timestamp ?? Date.now();
+ for (const t of tradeList) {
+ const px = priceFromTrade(t);
+ if (!px) continue;
+ const view = buildView({
+ details, holders, creator,
+ curve: { ...curve, priceSol: px },
+ position: { entryPriceSol: entryPrice, amountTokens: tokens, openedAt },
+ });
+ const exit = compiled.shouldExit(view);
+ if (exit) {
+ exitPrice = px;
+ exitedAt = t.timestamp ?? Date.now();
+ exitReason = exit;
+ break;
+ }
+ }
+
+ const proceeds = tokens * exitPrice;
+ const pnl = proceeds - perTrade;
+ realized += pnl;
+
+ trades.push({
+ mint,
+ action: 'trade',
+ entryPrice,
+ exitPrice,
+ pnlSol: pnl,
+ pnlPct: ((exitPrice - entryPrice) / entryPrice) * 100,
+ heldSec: exitedAt ? (exitedAt - openedAt) / 1000 : null,
+ exitReason,
+ });
+ }
+
+ const completed = trades.filter((t) => t.action === 'trade');
+ const wins = completed.filter((t) => t.pnlSol > 0).length;
+ let peak = 0, trough = 0, runningPnl = 0, maxDrawdown = 0;
+ for (const t of completed) {
+ runningPnl += t.pnlSol;
+ if (runningPnl > peak) peak = runningPnl;
+ const dd = peak - runningPnl;
+ if (dd > maxDrawdown) { maxDrawdown = dd; trough = runningPnl; }
+ }
+
+ return {
+ ok: true,
+ data: {
+ spent,
+ realizedPnlSol: realized,
+ roiPct: spent > 0 ? (realized / spent) * 100 : 0,
+ tradeCount: completed.length,
+ winRate: completed.length ? wins / completed.length : 0,
+ maxDrawdownSol: maxDrawdown,
+ trades,
+ },
+ };
+}
+
+// Re-exported for tests.
+export { parsePredicate, evalPredicate, buildView, compileStrategy };
diff --git a/index.html b/index.html
index c61783966..d5efaa453 100644
--- a/index.html
+++ b/index.html
@@ -859,11 +859,6 @@
loading="eager"
></model-viewer>
</a>
- <div class="hero-avatar-tag" aria-hidden="true">
- <span class="hero-avatar-tag-dot"></span>
- <span class="hero-avatar-tag-label">agent</span>
- <span class="hero-avatar-tag-value">0x3d…a9f</span>
- </div>
</div>
<div class="hero-scroll-hint scroll-reveal" aria-hidden="true">
<span>scroll</span>
diff --git a/public/agent-passport.html b/public/agent-passport.html
index 3b96866d0..d7c2f4957 100644
--- a/public/agent-passport.html
+++ b/public/agent-passport.html
@@ -6,52 +6,118 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* { box-sizing: border-box; }
- body { font: 14px/1.5 system-ui, sans-serif; max-width: 880px; margin: 2rem auto; padding: 0 1rem; color: #111; }
+ :root {
+ --fg: #111; --muted: #555; --border: #e5e5e5; --bg: #fafafa;
+ --ok-bg: #e7f5e9; --ok-fg: #1b5e20;
+ --warn-bg: #fff3cd; --warn-fg: #855008;
+ --bad-bg: #fce8e8; --bad-fg: #b71c1c;
+ --info-bg: #e3f2fd; --info-fg: #0d47a1;
+ }
+ body { font: 14px/1.5 system-ui, -apple-system, sans-serif; max-width: 880px; margin: 1.5rem auto; padding: 0 1rem; color: var(--fg); }
h1 { font-size: 1.4rem; margin: 0 0 .25rem; }
- .muted { color: #666; }
- .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: .75rem; margin: 1rem 0; }
- .card { border: 1px solid #e5e5e5; border-radius: 8px; padding: .75rem 1rem; background: #fafafa; }
- .card .v { font-size: 1.6rem; font-weight: 600; }
- .card .l { font-size: .8rem; color: #666; }
- .row { display: flex; gap: 1rem; align-items: center; flex-wrap: wrap; margin: .5rem 0 1.5rem; }
- .pill { display: inline-block; padding: .15rem .55rem; border-radius: 999px; font-size: .75rem; }
- .ok { background: #e7f5e9; color: #1b5e20; }
- .warn { background: #fff3cd; color: #855008; }
- .bad { background: #fce8e8; color: #b71c1c; }
- .vanity { background: linear-gradient(90deg, #ffd54f, #ff8a65); color: #1a1a1a; font-weight: 600; }
- .addr-prefix { background: #fff7c2; padding: 0 2px; border-radius: 2px; font-weight: 600; }
+ h2 { font-size: 1rem; margin: 1.5rem 0 .5rem; display: flex; align-items: baseline; gap: .5rem; }
+ h2 .hint { font-weight: 400; font-size: .8rem; color: var(--muted); }
+ .muted { color: var(--muted); }
+ .row { display: flex; gap: .5rem; align-items: center; flex-wrap: wrap; margin: .5rem 0 1rem; }
+ .row input { font: inherit; padding: .4rem .55rem; border: 1px solid var(--border); border-radius: 6px; flex: 1 1 320px; min-width: 0; }
+ .row input.invalid { border-color: var(--bad-fg); background: #fff8f8; }
+ .row select, .row button { font: inherit; padding: .4rem .65rem; border: 1px solid #ccc; background: #fff; border-radius: 6px; cursor: pointer; }
+ .row button.primary { background: #111; color: #fff; border-color: #111; }
+ .row button:disabled { opacity: .5; cursor: wait; }
+
+ .identity-card { border: 1px solid var(--border); border-radius: 10px; padding: 1rem 1.1rem; background: #fff; }
+ .identity-row { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; }
+ .identity-name { font-size: 1.2rem; font-weight: 600; }
+ .identity-meta { display: flex; gap: .5rem; flex-wrap: wrap; align-items: center; font-size: .8rem; color: var(--muted); margin-top: .35rem; }
+ .identity-meta code { background: #f3f3f3; padding: .1rem .35rem; border-radius: 4px; font-size: .75rem; }
+ .copy-btn { padding: .1rem .35rem; font-size: .7rem; line-height: 1.4; cursor: pointer; border: 1px solid var(--border); background: #fff; border-radius: 4px; }
+ .copy-btn:hover { background: #f3f3f3; }
+
+ .trust-bar { display: flex; align-items: center; gap: .75rem; margin-top: .75rem; padding: .65rem .85rem; border-radius: 8px; background: var(--bg); border: 1px solid var(--border); }
+ .trust-grade { font-size: 1.6rem; font-weight: 700; min-width: 2rem; text-align: center; }
+ .trust-A { color: var(--ok-fg); }
+ .trust-B { color: #2e7d32; }
+ .trust-C { color: var(--warn-fg); }
+ .trust-D { color: #c62828; }
+ .trust-NA { color: var(--muted); }
+ .trust-summary { font-size: .85rem; color: var(--muted); }
+
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: .65rem; margin: .75rem 0; }
+ .card { border: 1px solid var(--border); border-radius: 8px; padding: .65rem .85rem; background: var(--bg); position: relative; }
+ .card .v { font-size: 1.55rem; font-weight: 600; line-height: 1.1; }
+ .card .v small { font-size: 1rem; color: var(--muted); font-weight: 400; }
+ .card .l { font-size: .75rem; color: var(--muted); margin-top: .15rem; display: flex; align-items: center; gap: .25rem; }
+ .card.tier-credentialed { border-color: #b8d8e8; background: #f4faff; }
+ .card.tier-event { border-color: #d4c5f0; background: #f8f4ff; }
+ .card.tier-pump { border-color: #ffd8b8; background: #fff8f0; }
+ .card.danger { border-color: #f5c6c6; background: #fff5f5; }
+
+ .tip { display: inline-block; cursor: help; color: var(--muted); border: 1px solid var(--border); border-radius: 50%; width: 13px; height: 13px; font-size: 9px; line-height: 11px; text-align: center; }
+
+ .pill { display: inline-block; padding: .1rem .55rem; border-radius: 999px; font-size: .7rem; line-height: 1.5; }
+ .ok { background: var(--ok-bg); color: var(--ok-fg); }
+ .warn { background: var(--warn-bg); color: var(--warn-fg); }
+ .bad { background: var(--bad-bg); color: var(--bad-fg); }
+ .info { background: var(--info-bg); color: var(--info-fg); }
+
+ .filters { display: flex; gap: .35rem; flex-wrap: wrap; margin: .5rem 0 .75rem; }
+ .chip { padding: .2rem .65rem; border: 1px solid var(--border); border-radius: 999px; cursor: pointer; font-size: .75rem; background: #fff; user-select: none; }
+ .chip[aria-pressed="true"] { background: #111; color: #fff; border-color: #111; }
+
.atts { border-top: 1px solid #eee; }
- .att { padding: .6rem 0; border-bottom: 1px solid #eee; display: grid; grid-template-columns: 80px 1fr auto; gap: .75rem; align-items: baseline; }
- .att code { font-size: .75rem; color: #555; }
- .kind-feedback { color: #1b5e20; }
- .kind-validation { color: #0d47a1; }
+ .att { padding: .55rem .25rem; border-bottom: 1px solid #eee; display: grid; grid-template-columns: 92px 1fr; gap: .5rem .75rem; align-items: baseline; }
+ .att code { font-size: .72rem; color: #555; }
+ .kind-feedback { color: var(--ok-fg); }
+ .kind-validation { color: var(--info-fg); }
.kind-task { color: #6a1b9a; }
.kind-accept { color: #4527a0; }
- .kind-revoke { color: #b71c1c; }
+ .kind-revoke { color: var(--bad-fg); }
.kind-dispute { color: #ef6c00; }
- input { font: inherit; padding: .35rem .5rem; width: 100%; }
- button { font: inherit; padding: .35rem .75rem; border: 1px solid #ccc; background: #fff; border-radius: 6px; cursor: pointer; }
+
+ .skeleton { background: linear-gradient(90deg, #eee 0%, #f6f6f6 50%, #eee 100%); background-size: 200% 100%; animation: shimmer 1.2s infinite; border-radius: 6px; }
+ @keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
+ .sk-row { height: 76px; margin: .65rem 0; }
+
+ .error-box { padding: .65rem .85rem; border: 1px solid #f5c6c6; background: #fff5f5; color: var(--bad-fg); border-radius: 6px; }
+
details { margin-top: .25rem; }
- details pre { font-size: .75rem; background: #f4f4f4; padding: .4rem; border-radius: 4px; overflow: auto; }
- a { color: #0d47a1; }
+ details pre { font-size: .72rem; background: #f4f4f4; padding: .4rem; border-radius: 4px; overflow: auto; max-height: 240px; }
+ a { color: var(--info-fg); }
+
+ @media (max-width: 520px) {
+ .att { grid-template-columns: 1fr; }
+ .identity-name { font-size: 1.05rem; }
+ }
</style>
</head>
<body>
<h1>Solana agent passport</h1>
- <p class="muted">ERC-8004-style identity, reputation, and validation — no deployed program. <a href="/.well-known/agent-attestation-schemas" target="_blank">View schemas</a></p>
+ <p class="muted">ERC-8004-style identity, reputation, and validation. <a href="/.well-known/agent-attestation-schemas" target="_blank">View schemas</a></p>
<div class="row">
- <input id="asset" placeholder="Metaplex Core asset pubkey…">
- <select id="network"><option value="devnet">devnet</option><option value="mainnet">mainnet</option></select>
- <button id="load">Load</button>
+ <input id="asset" placeholder="Metaplex Core asset pubkey…" autocomplete="off" spellcheck="false">
+ <select id="network">
+ <option value="devnet">devnet</option>
+ <option value="mainnet">mainnet</option>
+ </select>
+ <button id="load" class="primary">Load</button>
+ <button id="share" title="Copy shareable link">Share</button>
</div>
<div id="identity"></div>
- <h2 style="font-size: 1rem; margin: 1.5rem 0 .25rem;">Reputation</h2>
- <div id="reputation" class="grid"></div>
+ <h2>Reputation <span class="hint" id="rep-hint"></span></h2>
+ <div id="reputation"></div>
- <h2 style="font-size: 1rem; margin: 1.5rem 0 .25rem;">Recent attestations</h2>
+ <h2>Recent attestations <span class="hint" id="atts-count"></span></h2>
+ <div class="filters" id="filters" hidden>
+ <button class="chip" data-filter="all" aria-pressed="true">all</button>
+ <button class="chip" data-filter="feedback" aria-pressed="false">feedback</button>
+ <button class="chip" data-filter="validation" aria-pressed="false">validation</button>
+ <button class="chip" data-filter="task" aria-pressed="false">task</button>
+ <button class="chip" data-filter="event" aria-pressed="false">event-attested</button>
+ <button class="chip" data-filter="disputed" aria-pressed="false">disputed</button>
+ </div>
<div id="atts" class="atts"></div>
<script type="module">
@@ -60,119 +126,249 @@
$('asset').value = params.get('asset') || '';
$('network').value = params.get('network') || 'devnet';
- function pill(text, cls = '') { return `<span class="pill ${cls}">${text}</span>`; }
+ let cache = { rows: [], net: 'devnet' };
+ let activeFilter = 'all';
+
+ const PUBKEY_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+ function pill(text, cls = '') { return `<span class="pill ${cls}">${escapeHtml(text)}</span>`; }
+ function tip(text) { return `<span class="tip" title="${escapeHtml(text)}">?</span>`; }
function explorer(sig, net) {
return `https://explorer.solana.com/tx/${sig}${net === 'devnet' ? '?cluster=devnet' : ''}`;
}
+ function shortKey(k) { return k ? `${k.slice(0,4)}…${k.slice(-4)}` : ''; }
+ function fmtScore(n) { return (typeof n === 'number' && n > 0) ? n.toFixed(2) : '—'; }
+
+ // Trust grade. Order: credentialed > verified > event-attested > raw.
+ function computeTrust(rep) {
+ const f = rep?.feedback || {};
+ const v = rep?.validation || {};
+ const tiers = [
+ { score: f.score_avg_weighted_credentialed, n: f.unique_credentialed_attesters, tier: 'credentialed' },
+ { score: f.score_avg_weighted_verified, n: f.unique_verified_attesters, tier: 'verified' },
+ { score: f.score_avg_event_attested, n: f.event_attested, tier: 'event-attested' },
+ { score: f.score_avg_weighted, n: f.unique_attesters, tier: 'community' },
+ ];
+ const best = tiers.find((t) => t.score > 0 && (t.n || 0) > 0);
+ if (!best) return { grade: '—', cls: 'NA', summary: 'no attestations yet' };
+
+ const passed = v.audited_passed || v.self_passed || 0;
+ const failed = v.audited_failed || v.self_failed || 0;
+ const passRate = (passed + failed) ? passed / (passed + failed) : 1;
+
+ const adjust = best.score
+ - (f.disputed > 0 ? 0.5 : 0)
+ - (passRate < 0.5 ? 1 : 0);
+
+ const grade =
+ adjust >= 4.5 ? 'A' :
+ adjust >= 3.8 ? 'B' :
+ adjust >= 3.0 ? 'C' : 'D';
+ return {
+ grade,
+ cls: grade,
+ summary: `${best.tier} ${best.score.toFixed(2)} from ${best.n} attester${best.n === 1 ? '' : 's'}`
+ + (f.disputed ? ` · ${f.disputed} disputed` : '')
+ + (failed ? ` · ${failed} failed validation${failed === 1 ? '' : 's'}` : ''),
+ };
+ }
+
+ function showError(target, message) { $(target).innerHTML = `<div class="error-box">${escapeHtml(message)}</div>`; }
+ function showSkeletons(target, count = 1) {
+ $(target).innerHTML = Array.from({ length: count }, () => `<div class="skeleton sk-row"></div>`).join('');
+ }
async function load() {
const asset = $('asset').value.trim();
const network = $('network').value;
- if (!asset) return;
- history.replaceState({}, '', `?asset=${asset}&network=${network}`);
+ $('asset').classList.toggle('invalid', !!asset && !PUBKEY_RE.test(asset));
+ if (!asset) { showError('identity', 'Enter an asset pubkey above.'); return; }
+ if (!PUBKEY_RE.test(asset)) { showError('identity', 'That doesn’t look like a Solana pubkey.'); return; }
- $('identity').innerHTML = '<p class="muted">loading…</p>';
+ history.replaceState({}, '', `?asset=${asset}&network=${network}`);
+ $('load').disabled = true;
+ showSkeletons('identity', 1);
+ showSkeletons('reputation', 1);
+ $('atts').innerHTML = '';
+ $('atts-count').textContent = '';
+ $('filters').hidden = true;
- let card;
try {
- card = await (await fetch(`/api/agents/solana-card?asset=${asset}`)).json();
- } catch {}
-
- let rep, atts;
- [rep, atts] = await Promise.all([
- fetch(`/api/agents/solana-reputation?asset=${asset}&network=${network}`).then((r) => r.json()),
- fetch(`/api/agents/solana-attestations?asset=${asset}&network=${network}&limit=25`).then((r) => r.json()),
- ]);
+ const [card, rep, atts] = await Promise.all([
+ fetch(`/api/agents/solana-card?asset=${asset}`).then((r) => r.ok ? r.json() : null).catch(() => null),
+ fetch(`/api/agents/solana-reputation?asset=${asset}&network=${network}`).then((r) => r.json()),
+ fetch(`/api/agents/solana-attestations?asset=${asset}&network=${network}&limit=25`).then((r) => r.json()),
+ ]);
- renderIdentity(card, asset, network);
- renderReputation(rep);
- renderAttestations(atts.data || [], network);
- }
-
- function escapeHtml(s) {
- return String(s).replace(/[&<>"']/g, (c) => ({
- '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
- })[c]);
+ renderIdentity(card, rep, asset, network);
+ renderReputation(rep);
+ cache = { rows: atts.data || [], net: network };
+ $('filters').hidden = false;
+ renderAttestations();
+ } catch (e) {
+ showError('identity', `Failed to load: ${e.message || e}`);
+ } finally {
+ $('load').disabled = false;
+ }
}
- function renderIdentity(card, asset, network) {
+ function renderIdentity(card, rep, asset, network) {
const id = card?.identity || {};
const name = card?.name || '(unindexed agent)';
- const vanity = id.vanity_prefix;
- const addrHtml = vanity && asset.startsWith(vanity)
- ? `<span class="addr-prefix">${escapeHtml(vanity)}</span>${escapeHtml(asset.slice(vanity.length))}`
- : escapeHtml(asset);
- const vanityBadge = vanity
- ? ` ${pill(`✦ vanity ${escapeHtml(vanity)}`, 'vanity')}`
- : '';
+ const trust = computeTrust(rep);
+ const lastIndexed = rep?.last_indexed_at
+ ? `indexed ${new Date(rep.last_indexed_at).toLocaleString()}`
+ : 'never indexed';
$('identity').innerHTML = `
- <div class="card" style="background:white;">
- <div style="font-size:1.2rem;font-weight:600">${escapeHtml(name)}${vanityBadge}</div>
- <div class="muted">${escapeHtml(card?.description || '')}</div>
- <div class="muted" style="margin-top:.4rem;font-size:.8rem">
- <code>${addrHtml}</code> · <span class="pill ${network === 'mainnet' ? 'ok' : 'warn'}">${network}</span>
- ${id.owner ? ` · owner <code>${escapeHtml(id.owner.slice(0, 6))}…${escapeHtml(id.owner.slice(-4))}</code>` : ''}
+ <div class="identity-card">
+ <div class="identity-row">
+ <div class="identity-name">${escapeHtml(name)}</div>
+ <span class="pill ${network === 'mainnet' ? 'ok' : 'warn'}">${network}</span>
+ </div>
+ ${card?.description ? `<div class="muted" style="margin-top:.2rem">${escapeHtml(card.description)}</div>` : ''}
+ <div class="identity-meta">
+ <code>${escapeHtml(shortKey(asset))}</code>
+ <button class="copy-btn" data-copy="${escapeHtml(asset)}">copy</button>
+ ${id.owner ? `<span>· owner</span> <code>${escapeHtml(shortKey(id.owner))}</code> <button class="copy-btn" data-copy="${escapeHtml(id.owner)}">copy</button>` : ''}
+ <span>· ${escapeHtml(lastIndexed)}</span>
+ </div>
+ <div class="trust-bar">
+ <div class="trust-grade trust-${trust.cls}">${trust.grade}</div>
+ <div>
+ <div style="font-weight:600">Trust grade</div>
+ <div class="trust-summary">${escapeHtml(trust.summary)}</div>
+ </div>
</div>
</div>`;
+ $('identity').querySelectorAll('[data-copy]').forEach((b) => {
+ b.addEventListener('click', () => copyText(b.dataset.copy, b));
+ });
}
function renderReputation(r) {
if (!r || r.error) { $('reputation').innerHTML = `<p class="muted">no data</p>`; return; }
- const f = r.feedback || {}, v = r.validation || {};
- const verifiedPct = f.total ? Math.round((f.verified / f.total) * 100) : 0;
- $('reputation').innerHTML = `
- <div class="card"><div class="v">${f.score_avg_weighted_credentialed?.toFixed(2) || '—'}</div><div class="l">credentialed weighted score (1–5)</div></div>
- <div class="card"><div class="v">${f.score_avg_weighted_verified?.toFixed(2) || '—'}</div><div class="l">verified weighted score</div></div>
- <div class="card"><div class="v">${f.score_avg_weighted?.toFixed(2) || '—'}</div><div class="l">all weighted score</div></div>
- <div class="card"><div class="v">${f.unique_credentialed_attesters || 0}<span class="muted" style="font-size:1rem">/${f.unique_attesters || 0}</span></div><div class="l">credentialed / unique attesters</div></div>
- <div class="card"><div class="v">${f.verified || 0}<span class="muted" style="font-size:1rem">/${f.total || 0}</span></div><div class="l">verified / total feedback (${verifiedPct}%)</div></div>
- <div class="card"><div class="v">${v.audited_passed || 0}<span class="muted" style="font-size:1rem">/${(v.audited_passed||0)+(v.audited_failed||0)}</span></div><div class="l">audited validation passed</div></div>
- <div class="card"><div class="v">${v.self_passed || 0}<span class="muted" style="font-size:1rem">/${(v.self_passed||0)+(v.self_failed||0)}</span></div><div class="l">self validation passed</div></div>
- <div class="card"><div class="v">${f.disputed || 0}</div><div class="l">disputed</div></div>
- <div class="card"><div class="v">${r.tasks?.accepted || 0}<span class="muted" style="font-size:1rem">/${r.tasks?.offered || 0}</span></div><div class="l">tasks accepted / offered</div></div>
- <div class="card"><div class="v">${r.revoked_count || 0}</div><div class="l">revoked</div></div>
- `;
+ const f = r.feedback || {}, v = r.validation || {}, p = r.pump_payments || {};
+ $('rep-hint').textContent = 'higher tiers are more Sybil-resistant';
+
+ const cards = [
+ { cls: 'tier-credentialed', value: fmtScore(f.score_avg_weighted_credentialed),
+ label: 'credentialed score',
+ tooltip: 'Average from attesters holding a threews.verified-client.v1 SAS credential. Strongest Sybil resistance.' },
+ { cls: 'tier-credentialed', value: `${f.unique_credentialed_attesters || 0}<small>/${f.unique_attesters || 0}</small>`,
+ label: 'credentialed / unique attesters' },
+ { cls: '', value: fmtScore(f.score_avg_weighted_verified),
+ label: 'verified score',
+ tooltip: 'Feedback whose task_id has a matching threews.accept.v1 from the agent owner.' },
+ { cls: 'tier-event', value: fmtScore(f.score_avg_event_attested),
+ label: 'event-attested score',
+ tooltip: 'Feedback sourced from on-chain event monitors (e.g. pumpkit). Sybil-resistant via the event.' },
+ { cls: 'tier-event', value: `${f.event_attested || 0}`,
+ label: 'event-attested feedback' },
+ { cls: '', value: fmtScore(f.score_avg_weighted),
+ label: 'all-feedback score',
+ tooltip: 'Per-attester average then averaged. Raw signal.' },
+ { cls: '', value: `${f.verified || 0}<small>/${f.total || 0}</small>`,
+ label: 'verified / total feedback' },
+ { cls: '', value: `${v.audited_passed || 0}<small>/${(v.audited_passed||0)+(v.audited_failed||0)}</small>`,
+ label: 'audited validation passed',
+ tooltip: 'From SAS-credentialed validators.' },
+ { cls: '', value: `${v.event_passed || 0}<small>/${(v.event_passed||0)+(v.event_failed||0)}</small>`,
+ label: 'event validation passed',
+ tooltip: 'From on-chain event monitors (graduations vs CTOs).' },
+ { cls: '', value: `${r.tasks?.accepted || 0}<small>/${r.tasks?.offered || 0}</small>`,
+ label: 'tasks accepted / offered' },
+ ...(Number(p.confirmed_count) ? [
+ { cls: 'tier-pump', value: `${p.confirmed_count}<small>/${p.unique_payers || 0}</small>`,
+ label: 'pump payments / unique payers',
+ tooltip: 'Confirmed acceptPayment receipts. Volume-weighted reputation lane.' },
+ ] : []),
+ ...(f.disputed ? [{ cls: 'danger', value: f.disputed, label: 'disputed' }] : []),
+ ...(r.revoked_count ? [{ cls: 'danger', value: r.revoked_count, label: 'revoked' }] : []),
+ ];
+
+ $('reputation').innerHTML = `<div class="grid">${cards.map((c) => `
+ <div class="card ${c.cls}">
+ <div class="v">${c.value}</div>
+ <div class="l">${escapeHtml(c.label)}${c.tooltip ? ' ' + tip(c.tooltip) : ''}</div>
+ </div>`).join('')}</div>`;
}
- function renderAttestations(rows, net) {
- if (!rows.length) { $('atts').innerHTML = `<p class="muted">no attestations yet</p>`; return; }
+ function renderAttestations() {
+ const rows = filterRows(cache.rows, activeFilter);
+ $('atts-count').textContent = `${rows.length} of ${cache.rows.length}`;
+ if (!rows.length) {
+ $('atts').innerHTML = `<p class="muted" style="padding:.75rem 0">no matching attestations</p>`;
+ return;
+ }
$('atts').innerHTML = rows.map((row) => {
- const k = row.kind.split('.')[1];
+ const k = row.kind?.split('.')[1] || 'unknown';
const flags = [];
if (row.verified) flags.push(pill('verified', 'ok'));
if (row.disputed) flags.push(pill('disputed', 'warn'));
+ if (row.revoked) flags.push(pill('revoked', 'bad'));
+ if (row.payload?.source?.startsWith?.('pumpkit.')) flags.push(pill(row.payload.source, 'info'));
return `
<div class="att">
- <div class="kind-${k}"><strong>${k}</strong></div>
+ <div class="kind-${k}"><strong>${escapeHtml(k)}</strong></div>
<div>
- <div>${describe(row)}</div>
- <div class="muted" style="font-size:.75rem">
- by <code>${row.attester?.slice(0,6)}…${row.attester?.slice(-4) || ''}</code>
- · slot ${row.slot}
- · <a href="${explorer(row.signature, net)}" target="_blank">tx</a>
- ${flags.join(' ')}
+ <div>${escapeHtml(describe(row))}</div>
+ <div class="muted" style="font-size:.72rem; margin-top:.15rem">
+ by <code>${escapeHtml(shortKey(row.attester))}</code>
+ · slot ${row.slot ?? '—'}
+ · <a href="${explorer(row.signature, cache.net)}" target="_blank" rel="noopener">tx ↗</a>
+ ${flags.length ? ' ' + flags.join(' ') : ''}
</div>
- <details><summary class="muted" style="font-size:.75rem">payload</summary><pre>${JSON.stringify(row.payload, null, 2)}</pre></details>
+ <details><summary class="muted" style="font-size:.72rem">payload</summary><pre>${escapeHtml(JSON.stringify(row.payload, null, 2))}</pre></details>
</div>
- <div></div>
</div>`;
}).join('');
}
+ function filterRows(rows, filter) {
+ if (filter === 'all') return rows;
+ if (filter === 'disputed') return rows.filter((r) => r.disputed || r.revoked);
+ if (filter === 'event') return rows.filter((r) => r.payload?.source?.startsWith?.('pumpkit.'));
+ return rows.filter((r) => r.kind?.includes(`.${filter}.`));
+ }
+
function describe(row) {
const p = row.payload || {};
switch (row.kind) {
- case 'threews.feedback.v1': return `score ${p.score}/5${p.task_id ? ` for task ${p.task_id}` : ''}`;
- case 'threews.validation.v1': return `validation ${p.passed ? '✓ passed' : '✗ failed'} (task hash ${p.task_hash?.slice(0,12)}…)`;
+ case 'threews.feedback.v1': return `score ${p.score}/5${p.task_id ? ` for task ${p.task_id}` : ''}${p.source ? ` (${p.source})` : ''}`;
+ case 'threews.validation.v1': return `validation ${p.passed ? '✓ passed' : '✗ failed'}${p.task_hash ? ` (task hash ${String(p.task_hash).slice(0,12)}…)` : ''}`;
case 'threews.task.v1': return `task offered: ${p.task_id}`;
case 'threews.accept.v1': return `task accepted: ${p.task_id}`;
- case 'threews.revoke.v1': return `revoked ${p.target_signature?.slice(0,12)}…`;
- case 'threews.dispute.v1': return `disputed ${p.target_signature?.slice(0,12)}…${p.reason ? ` — ${p.reason}` : ''}`;
+ case 'threews.revoke.v1': return `revoked ${String(p.target_signature || '').slice(0,12)}…`;
+ case 'threews.dispute.v1': return `disputed ${String(p.target_signature || '').slice(0,12)}…${p.reason ? ` — ${p.reason}` : ''}`;
default: return row.kind;
}
}
+ function escapeHtml(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' })[c]);
+ }
+
+ async function copyText(text, btn) {
+ try {
+ await navigator.clipboard.writeText(text);
+ const prev = btn.textContent;
+ btn.textContent = 'copied';
+ setTimeout(() => { btn.textContent = prev; }, 1200);
+ } catch {}
+ }
+
$('load').onclick = load;
+ $('asset').addEventListener('keydown', (e) => { if (e.key === 'Enter') load(); });
+ $('network').addEventListener('change', () => { if ($('asset').value.trim()) load(); });
+ $('share').onclick = () => copyText(location.href, $('share'));
+ $('filters').addEventListener('click', (e) => {
+ const btn = e.target.closest('.chip');
+ if (!btn) return;
+ activeFilter = btn.dataset.filter;
+ $('filters').querySelectorAll('.chip').forEach((c) => c.setAttribute('aria-pressed', c === btn ? 'true' : 'false'));
+ renderAttestations();
+ });
+
if ($('asset').value) load();
</script>
</body>
diff --git a/public/agent/index.html b/public/agent/index.html
index 0a9629497..91e282bfc 100644
--- a/public/agent/index.html
+++ b/public/agent/index.html
@@ -735,6 +735,9 @@
</div>
</div>
+ <!-- $AGENT pump.fun token widget (rendered when this agent has a launched mint) -->
+ <div id="agent-token-widget"></div>
+
<!-- Permissions panel (owner only, mounted by JS) -->
<div id="agent-permissions-mount"></div>
@@ -781,6 +784,8 @@
import { protocol } from '/src/agent-protocol.js';
import { renderHubActions } from '/src/agent-hub-actions.js';
import { mountManagePanel } from '/src/permissions/manage-panel.js';
+ import { AgentTokenWidget } from '/src/pump/agent-token-widget.js';
+ import { mountPumpModals } from '/src/pump/pump-modals.js';
// Pull agent id from URL: /agent/:id
const agentId = location.pathname.split('/').filter(Boolean).pop();
@@ -820,6 +825,35 @@
// Inject hub actions if the viewer is the owner (user_id present = owner)
const isOwner = Boolean(rawAgent?.user_id);
+
+ // Mount the $AGENT pump.fun token widget. Renders empty-state for
+ // not-yet-launched agents (with a "Launch" CTA for owners) and full
+ // live state when a mint exists. Wires avatar emotion to bus events.
+ const tokenMount = document.getElementById('agent-token-widget');
+ if (tokenMount && agentId) {
+ const widget = new AgentTokenWidget({
+ mount: tokenMount,
+ agentId,
+ isOwner,
+ protocol,
+ identity,
+ });
+ widget.render().catch(() => {});
+
+ // Avatar reactions: a new payment is curiosity+celebration; a
+ // graduation is a one-shot celebration emote.
+ protocol.on?.('pump-payment', () => {
+ protocol.emit?.('emote', { trigger: 'celebration', weight: 0.6 });
+ protocol.emit?.('emote', { trigger: 'curiosity', weight: 0.4 });
+ });
+ protocol.on?.('pump-graduated', () => {
+ protocol.emit?.('emote', { trigger: 'celebration', weight: 0.95 });
+ protocol.emit?.('gesture', { name: 'celebrate', duration: 2400 });
+ });
+
+ // Pay / governance / withdraw modals listen on window CustomEvents.
+ mountPumpModals({ identity, agentId });
+ }
if (isOwner) {
const panel = container.querySelector('.agent-home-panel');
if (panel) renderHubActions(panel, identity, rawAgent);
diff --git a/src/agent-home.js b/src/agent-home.js
index ee0b1e6e8..5e97afbba 100644
--- a/src/agent-home.js
+++ b/src/agent-home.js
@@ -10,6 +10,7 @@
import { ACTION_TYPES } from './agent-protocol.js';
import { MEMORY_TYPES } from './agent-memory.js';
+import { mountPumpFunCard } from './agent-home-pumpfun.js';
const ACTION_ICONS = {
[ACTION_TYPES.SPEAK]: '💬',
@@ -162,6 +163,20 @@ export class AgentHome {
this.container.appendChild(panel);
this._panel = panel;
+ // Pump.fun card — only meaningful for Solana-registered agents.
+ if (this.identity?.meta?.chain_type === 'solana' || this.identity?.solana_address) {
+ try {
+ mountPumpFunCard({
+ panel,
+ identity: this.identity,
+ skills: this.skills || (typeof window !== 'undefined' ? window.VIEWER?.agent_skills : null),
+ memory: this.memory,
+ });
+ } catch {
+ /* card is optional */
+ }
+ }
+
// Permissions manage panel — lazy load; degrades gracefully if unauthenticated
const agentId = this.identity.id;
if (agentId) {
diff --git a/src/editor/manifest-builder.js b/src/editor/manifest-builder.js
index 6d479150d..18fcc30e9 100644
--- a/src/editor/manifest-builder.js
+++ b/src/editor/manifest-builder.js
@@ -198,11 +198,36 @@ const STYLE = `
.drop-zone.filled { border-style: solid; border-color: #374151; color: #9ca3af; }
.drop-zone input[type="file"] { display: none; }
- .skill-item { display: flex; align-items: center; justify-content: space-between; padding: 6px 10px; background: #111827; border: 1px solid #1f2937; border-radius: 6px; margin: 4px 0; font-size: 12px; }
- .skill-item-info .skill-item-name { font-weight: 600; color: #e5e7eb; }
- .skill-item-info .skill-item-desc { color: #6b7280; font-size: 11px; margin-top: 1px; }
- .skill-toggle { background: transparent; border: 1px solid #374151; color: #9ca3af; border-radius: 5px; padding: 3px 9px; font: 12px system-ui; cursor: pointer; flex-shrink: 0; }
+ .skill-item { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; padding: 8px 10px; background: #111827; border: 1px solid #1f2937; border-radius: 8px; margin: 6px 0; font-size: 12px; transition: border-color .15s, transform .15s; }
+ .skill-item:hover { border-color: #374151; }
+ .skill-item.installed { border-color: #2563eb; background: linear-gradient(180deg, rgba(37,99,235,.08), #111827); }
+ .skill-item-info { flex: 1; min-width: 0; }
+ .skill-item-info .skill-item-name { font-weight: 600; color: #e5e7eb; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
+ .skill-item-info .skill-item-desc { color: #9ca3af; font-size: 11px; margin-top: 3px; line-height: 1.4; }
+ .skill-tags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; }
+ .skill-tag { font: 600 9px/1 system-ui; letter-spacing: .04em; text-transform: uppercase; color: #93c5fd; background: rgba(59,130,246,.12); border: 1px solid rgba(59,130,246,.25); padding: 3px 6px; border-radius: 4px; }
+ .skill-tag[data-chain="solana"] { color: #c4b5fd; background: rgba(139,92,246,.14); border-color: rgba(139,92,246,.28); }
+ .skill-tag[data-chain="evm"] { color: #93c5fd; background: rgba(59,130,246,.14); border-color: rgba(59,130,246,.28); }
+ .skill-tag[data-kind="readonly"] { color: #6ee7b7; background: rgba(16,185,129,.12); border-color: rgba(16,185,129,.28); }
+ .skill-tag[data-kind="payments"] { color: #fbbf24; background: rgba(234,179,8,.12); border-color: rgba(234,179,8,.28); }
+ .skill-actions { display: flex; flex-direction: column; gap: 4px; flex-shrink: 0; align-items: flex-end; }
+ .skill-toggle { background: transparent; border: 1px solid #374151; color: #9ca3af; border-radius: 5px; padding: 4px 10px; font: 600 11px system-ui; cursor: pointer; flex-shrink: 0; transition: all .12s; }
+ .skill-toggle:hover { border-color: #6b7280; color: #d1d5db; }
.skill-toggle.on { background: #1e3a5f; border-color: #3b82f6; color: #93c5fd; }
+ .skill-toggle.on:hover { background: #1e40af; }
+ .skill-preview-btn { font: 10px system-ui; color: #6b7280; background: none; border: 0; cursor: pointer; padding: 0; }
+ .skill-preview-btn:hover { color: #9ca3af; }
+ .skill-tools-preview { margin-top: 8px; padding: 8px; background: #0b1220; border: 1px solid #1f2937; border-radius: 6px; display: none; }
+ .skill-tools-preview.open { display: block; }
+ .skill-tools-preview h5 { font: 600 9px/1 system-ui; letter-spacing: .08em; text-transform: uppercase; color: #6b7280; margin: 0 0 6px; }
+ .skill-tools-preview ul { list-style: none; padding: 0; margin: 0; display: flex; flex-wrap: wrap; gap: 4px; }
+ .skill-tools-preview li { font: 11px ui-monospace, SFMono-Regular, monospace; color: #cbd5e1; background: #1f2937; padding: 2px 6px; border-radius: 4px; }
+ .skill-tools-preview .example { margin-top: 6px; font-size: 11px; color: #9ca3af; font-style: italic; }
+ .skill-filters { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 8px; }
+ .skill-chip { font: 600 10px/1 system-ui; letter-spacing: .04em; text-transform: uppercase; color: #9ca3af; background: #1f2937; border: 1px solid #1f2937; padding: 5px 9px; border-radius: 999px; cursor: pointer; transition: all .12s; }
+ .skill-chip:hover { color: #d1d5db; border-color: #374151; }
+ .skill-chip.active { color: #93c5fd; background: rgba(59,130,246,.18); border-color: rgba(59,130,246,.38); }
+ .skill-empty { font-size: 12px; color: #4b5563; padding: 12px; text-align: center; border: 1px dashed #1f2937; border-radius: 6px; }
.skill-custom-row { display: flex; gap: 6px; margin-top: 8px; }
.skill-custom-row input { flex: 1; background: #111827; color: #f4f4f5; border: 1px solid #1f2937; border-radius: 6px; padding: 6px 8px; font: 12px system-ui; }
.skill-custom-row input:focus { outline: none; border-color: #3b82f6; }
@@ -576,6 +601,7 @@ export function mountManifestBuilder(rootEl, options = {}) {
<summary>Skills</summary>
<div class="section-body">
<input id="skill-search" type="text" placeholder="Search skills…" style="width:100%;background:#111827;color:#f4f4f5;border:1px solid #1f2937;border-radius:6px;padding:6px 8px;font:13px system-ui;margin-bottom:8px">
+ <div id="skill-filters" class="skill-filters"></div>
<div id="skills-list"></div>
<div style="font:600 11px system-ui;letter-spacing:.06em;text-transform:uppercase;color:#4b5563;margin:10px 0 4px">Custom skill URI</div>
<div class="skill-custom-row">
@@ -887,31 +913,118 @@ export function mountManifestBuilder(rootEl, options = {}) {
if (sec) sec.style.display = state.sttProvider === 'none' ? 'none' : '';
}
+ // Active tag filter (only one at a time keeps the UI simple).
+ let activeSkillFilter = null;
+ // Memoized tool previews keyed by skill id (lazy-loaded on first expand).
+ const _skillPreviews = new Map();
+
+ function _skillTagKind(tag) {
+ const t = String(tag || '').toLowerCase();
+ if (t === 'solana' || t.includes('pump.fun')) return { chain: 'solana' };
+ if (t === 'evm' || t === 'uniswap' || t === 'metamask' || t === 'erc7710') return { chain: 'evm' };
+ if (t === 'read-only' || t === 'readonly') return { kind: 'readonly' };
+ if (t === 'payments' || t === 'tip' || t === 'usdc') return { kind: 'payments' };
+ return {};
+ }
+
+ function _collectFilterTags() {
+ const seen = new Set();
+ for (const s of allSkills) for (const t of s.tags || []) seen.add(String(t).toLowerCase());
+ // Surface the curated set first if present, then alphabetical extras.
+ const curated = ['solana', 'evm', 'defi', 'payments', 'read-only', 'mcp', 'pump.fun'];
+ const ordered = [
+ ...curated.filter((t) => seen.has(t)),
+ ...[...seen].filter((t) => !curated.includes(t)).sort(),
+ ];
+ return ordered;
+ }
+
+ function refreshSkillFilters() {
+ const wrap = $('#skill-filters');
+ if (!wrap) return;
+ const tags = _collectFilterTags();
+ if (tags.length === 0) { wrap.innerHTML = ''; return; }
+ wrap.innerHTML = ['all', ...tags]
+ .map((t) => {
+ const active = (t === 'all' && !activeSkillFilter) || t === activeSkillFilter;
+ return `<button class="skill-chip${active ? ' active' : ''}" data-tag="${esc(t)}">${esc(t)}</button>`;
+ })
+ .join('');
+ wrap.querySelectorAll('.skill-chip').forEach((btn) =>
+ btn.addEventListener('click', () => {
+ const tag = btn.dataset.tag;
+ activeSkillFilter = tag === 'all' ? null : tag;
+ refreshSkillFilters();
+ const q = $('#skill-search')?.value || '';
+ refreshSkillsList(q);
+ }),
+ );
+ }
+
+ async function _loadSkillPreview(sk) {
+ if (_skillPreviews.has(sk.id)) return _skillPreviews.get(sk.id);
+ // Resolve relative bundle URIs against the site origin.
+ const base = sk.uri.endsWith('/') ? sk.uri : `${sk.uri}/`;
+ try {
+ const res = await fetch(`${base}tools.json`);
+ if (!res.ok) throw new Error(String(res.status));
+ const json = await res.json();
+ const preview = { tools: (json.tools || []).map((t) => t.name).filter(Boolean) };
+ _skillPreviews.set(sk.id, preview);
+ return preview;
+ } catch {
+ const preview = { tools: [], error: true };
+ _skillPreviews.set(sk.id, preview);
+ return preview;
+ }
+ }
+
function refreshSkillsList(query = '') {
const list = $('#skills-list');
if (!list) return;
+ refreshSkillFilters();
const q = query.toLowerCase();
- const filtered = q
+ let filtered = q
? allSkills.filter(
(s) =>
- s.name.toLowerCase().includes(q) || s.description.toLowerCase().includes(q),
+ s.name.toLowerCase().includes(q) ||
+ s.description.toLowerCase().includes(q) ||
+ (s.tags || []).some((t) => t.toLowerCase().includes(q)),
)
- : allSkills;
+ : allSkills.slice();
+ if (activeSkillFilter) {
+ filtered = filtered.filter((s) =>
+ (s.tags || []).map((t) => t.toLowerCase()).includes(activeSkillFilter),
+ );
+ }
if (filtered.length === 0) {
- list.innerHTML = `<div style="font-size:12px;color:#4b5563;padding:4px 0">No skills found</div>`;
+ list.innerHTML = `<div class="skill-empty">No skills match this filter.</div>`;
return;
}
list.innerHTML = '';
for (const sk of filtered) {
const installed = !!state.installedSkills[sk.id];
+ const tags = sk.tags || [];
+ const tagsHtml = tags
+ .map((t) => {
+ const kind = _skillTagKind(t);
+ const attrs = Object.entries(kind).map(([k, v]) => ` data-${k}="${esc(v)}"`).join('');
+ return `<span class="skill-tag"${attrs}>${esc(t)}</span>`;
+ })
+ .join('');
const item = document.createElement('div');
- item.className = 'skill-item';
+ item.className = `skill-item${installed ? ' installed' : ''}`;
item.innerHTML = `
<div class="skill-item-info">
<div class="skill-item-name">${esc(sk.name)} <span style="color:#4b5563;font-weight:400;font-size:10px">v${esc(sk.version)}</span></div>
<div class="skill-item-desc">${esc(sk.description)}</div>
+ ${tagsHtml ? `<div class="skill-tags">${tagsHtml}</div>` : ''}
+ <div class="skill-tools-preview" data-preview-for="${esc(sk.id)}"></div>
+ </div>
+ <div class="skill-actions">
+ <button class="skill-toggle ${installed ? 'on' : ''}" data-skill-id="${esc(sk.id)}">${installed ? 'Installed' : 'Install'}</button>
+ <button class="skill-preview-btn" data-preview-toggle="${esc(sk.id)}">What can it do?</button>
</div>
- <button class="skill-toggle ${installed ? 'on' : ''}" data-skill-id="${esc(sk.id)}">${installed ? 'Installed' : 'Install'}</button>
`;
item.querySelector('.skill-toggle').addEventListener('click', () => {
if (state.installedSkills[sk.id]) {
@@ -922,10 +1035,47 @@ export function mountManifestBuilder(rootEl, options = {}) {
refreshSkillsList(query);
scheduleDraft();
});
+ const previewEl = item.querySelector(`[data-preview-for="${sk.id}"]`);
+ item.querySelector('[data-preview-toggle]').addEventListener('click', async () => {
+ if (previewEl.classList.contains('open')) {
+ previewEl.classList.remove('open');
+ return;
+ }
+ if (!previewEl.dataset.loaded) {
+ previewEl.innerHTML = `<div class="example">Loading…</div>`;
+ const preview = await _loadSkillPreview(sk);
+ if (preview.error) {
+ previewEl.innerHTML = `<div class="example">Tool list unavailable for this bundle.</div>`;
+ } else if (preview.tools.length === 0) {
+ previewEl.innerHTML = `<div class="example">This skill exposes UI actions, not LLM tools.</div>`;
+ } else {
+ const example = _exampleForSkill(sk);
+ previewEl.innerHTML = `
+ <h5>Tools (${preview.tools.length})</h5>
+ <ul>${preview.tools.map((t) => `<li>${esc(t)}</li>`).join('')}</ul>
+ ${example ? `<div class="example">Try: <em>${esc(example)}</em></div>` : ''}
+ `;
+ }
+ previewEl.dataset.loaded = '1';
+ }
+ previewEl.classList.add('open');
+ });
list.appendChild(item);
}
}
+ // Curated example prompts keyed by skill id. Falls back to nothing.
+ function _exampleForSkill(sk) {
+ const examples = {
+ 'pump-fun': "what's the king of the hill on pump.fun right now?",
+ wave: 'wave at me!',
+ dance: 'dance for me',
+ 'explain-gltf': "tell me about this model's animations",
+ dca: 'set up a weekly $50 USDC → WETH DCA',
+ };
+ return examples[sk.id] || '';
+ }
+
function refreshCustomSkillsList() {
const list = $('#custom-skills-list');
if (!list) return;
diff --git a/src/pump/agent-token-widget.js b/src/pump/agent-token-widget.js
new file mode 100644
index 000000000..52115076f
--- /dev/null
+++ b/src/pump/agent-token-widget.js
@@ -0,0 +1,636 @@
+/**
+ * AgentTokenWidget — the $AGENT card on the agent passport.
+ *
+ * Self-contained: pass a mount node + agentId, it figures out the rest. Reads:
+ * GET /api/pump/by-agent?agent_id=… (mint + stats + burn history)
+ * GET /api/pump/balances?mint=… (live vault balances, polled)
+ * GET /api/pump/quote?mint=… (price + graduation status)
+ * GET /api/pump/payments-list?mint=… (recent receipts feed)
+ *
+ * Emits on the protocol bus (when one is passed):
+ * `pump-balance` { paymentDelta, buybackDelta, withdrawDelta }
+ * `pump-graduated` { mint }
+ * `pump-payment` { payer, atomics, skill }
+ *
+ * Renders four states: not-launched, launching, live (curve), live (AMM).
+ * Live state shows: ticker, price, buyback gauge, 3 vault balances, burns,
+ * recent payment feed, owner withdraw button, governance explainer.
+ */
+
+const POLL_MS = 10_000;
+
+function fmtUsdc(atomics) {
+ const n = Number(BigInt(atomics || '0')) / 1_000_000;
+ if (n === 0) return '$0.00';
+ if (n < 0.01) return `<$0.01`;
+ return `$${n.toFixed(n < 1 ? 4 : 2)}`;
+}
+
+function fmtSol(lamports) {
+ if (!lamports) return '0 SOL';
+ const n = Number(lamports) / 1_000_000_000;
+ return `${n.toFixed(n < 1 ? 4 : 2)} SOL`;
+}
+
+function fmtBps(bps) {
+ if (bps == null) return '—';
+ return `${(bps / 100).toFixed(bps % 100 === 0 ? 0 : 1)}%`;
+}
+
+function shortAddr(s, n = 4) {
+ if (!s) return '';
+ return `${s.slice(0, n)}…${s.slice(-n)}`;
+}
+
+function timeAgo(iso) {
+ if (!iso) return '';
+ const ms = Date.now() - new Date(iso).getTime();
+ if (ms < 60_000) return `${Math.max(1, Math.floor(ms / 1000))}s ago`;
+ if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m ago`;
+ if (ms < 86_400_000) return `${Math.floor(ms / 3_600_000)}h ago`;
+ return `${Math.floor(ms / 86_400_000)}d ago`;
+}
+
+const STYLES = `
+.atok {
+ max-width: 520px; margin: 1.5rem auto; padding: 1.25rem 1.4rem;
+ border: 1px solid rgba(255,255,255,0.08); border-radius: 14px;
+ background: linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0));
+ color: #e5e5e5; font: 14px/1.5 Inter, sans-serif;
+}
+.atok-head {
+ display: flex; align-items: baseline; justify-content: space-between;
+ gap: 0.6rem; margin-bottom: 0.25rem;
+}
+.atok-symbol {
+ font-size: 1.05rem; font-weight: 500; letter-spacing: 0.03em;
+}
+.atok-symbol .atok-sigil { color: rgba(255,255,255,0.45); margin-right: 0.18em; }
+.atok-status {
+ font-size: 0.7rem; padding: 0.1rem 0.5rem; border-radius: 999px;
+ background: rgba(120,200,140,0.12); color: rgba(180,230,200,0.95);
+ letter-spacing: 0.03em;
+}
+.atok-status.curve { background: rgba(120,160,255,0.12); color: rgba(180,210,255,0.95); }
+.atok-status.empty { background: rgba(255,255,255,0.04); color: rgba(255,255,255,0.45); }
+.atok-status.error { background: rgba(255,140,140,0.1); color: rgba(255,180,180,0.95); }
+.atok-price-row {
+ display: flex; align-items: baseline; gap: 0.6rem; margin-top: 0.1rem;
+}
+.atok-price {
+ font-size: 1.4rem; font-weight: 300; color: #fff; font-variant-numeric: tabular-nums;
+ transition: color 0.4s ease;
+}
+.atok-price.tick-up { color: #a4f0bc; }
+.atok-price.tick-down { color: #f6b3b3; }
+.atok-price-label {
+ font-size: 0.72rem; color: rgba(255,255,255,0.4); letter-spacing: 0.05em; text-transform: uppercase;
+}
+
+.atok-grad-bar {
+ height: 4px; background: rgba(255,255,255,0.05); border-radius: 999px;
+ margin: 0.9rem 0 0.3rem; overflow: hidden;
+}
+.atok-grad-fill {
+ height: 100%; background: linear-gradient(90deg, #6a93ff, #a4f0bc);
+ transition: width 0.6s cubic-bezier(.2,.8,.2,1);
+}
+.atok-grad-label {
+ font-size: 0.7rem; color: rgba(255,255,255,0.5); display: flex; justify-content: space-between;
+}
+
+.atok-buyback {
+ margin-top: 1rem; padding: 0.7rem 0.85rem; border-radius: 10px;
+ background: rgba(255,255,255,0.025);
+ display: flex; align-items: center; gap: 0.7rem;
+}
+.atok-buyback-gauge {
+ flex: 1; height: 6px; background: rgba(255,255,255,0.05); border-radius: 999px; overflow: hidden;
+}
+.atok-buyback-fill {
+ height: 100%; background: linear-gradient(90deg, #f6b3b3, #ffd57a, #a4f0bc);
+ transition: width 0.8s cubic-bezier(.2,.8,.2,1);
+}
+.atok-buyback-label {
+ font-size: 0.78rem; white-space: nowrap; color: rgba(255,255,255,0.85);
+ font-variant-numeric: tabular-nums;
+}
+.atok-buyback-explain {
+ font-size: 0.7rem; color: rgba(255,255,255,0.45); margin-top: 0.35rem; line-height: 1.45;
+}
+.atok-buyback-explain b { color: rgba(255,255,255,0.85); font-weight: 500; }
+
+.atok-vaults {
+ display: grid; grid-template-columns: repeat(3, 1fr);
+ gap: 0.5rem; margin-top: 0.9rem;
+}
+.atok-vault {
+ padding: 0.55rem 0.7rem; border-radius: 8px; background: rgba(255,255,255,0.025);
+}
+.atok-vault-name {
+ font-size: 0.65rem; color: rgba(255,255,255,0.45); letter-spacing: 0.06em; text-transform: uppercase;
+}
+.atok-vault-val {
+ font-size: 0.95rem; margin-top: 0.15rem; font-variant-numeric: tabular-nums;
+ transition: color 0.4s ease;
+}
+.atok-vault-val.tick-up { color: #a4f0bc; }
+.atok-vault-payment .atok-vault-name { color: rgba(180,210,255,0.6); }
+.atok-vault-buyback .atok-vault-name { color: rgba(255,200,140,0.6); }
+.atok-vault-withdraw .atok-vault-name { color: rgba(180,230,200,0.6); }
+
+.atok-burned {
+ margin-top: 0.7rem; padding: 0.55rem 0.7rem; border-radius: 8px;
+ background: rgba(120,200,140,0.06); color: rgba(200,240,210,0.9);
+ font-size: 0.78rem;
+}
+.atok-burned b { color: #d8f5e2; font-weight: 500; }
+
+.atok-feed {
+ margin-top: 1rem; border-top: 1px solid rgba(255,255,255,0.05); padding-top: 0.7rem;
+}
+.atok-feed-title {
+ font-size: 0.7rem; letter-spacing: 0.06em; text-transform: uppercase;
+ color: rgba(255,255,255,0.45); margin-bottom: 0.4rem;
+}
+.atok-feed-row {
+ display: flex; justify-content: space-between; gap: 0.6rem;
+ padding: 0.3rem 0; font-size: 0.8rem; color: rgba(255,255,255,0.78);
+}
+.atok-feed-row + .atok-feed-row { border-top: 1px solid rgba(255,255,255,0.03); }
+.atok-feed-row code { font-family: ui-monospace, monospace; color: rgba(255,255,255,0.5); font-size: 0.75rem; }
+.atok-feed-row .atok-buyback-pill {
+ font-size: 0.65rem; padding: 0.05rem 0.4rem; border-radius: 999px;
+ background: rgba(255,200,140,0.08); color: rgba(255,210,160,0.85); white-space: nowrap;
+}
+
+.atok-actions { display: flex; gap: 0.5rem; margin-top: 1rem; }
+.atok-btn {
+ flex: 1; padding: 0.55rem 0.8rem; border-radius: 8px; cursor: pointer;
+ background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.07);
+ color: rgba(255,255,255,0.85); font-size: 0.82rem; transition: 0.15s;
+}
+.atok-btn:hover { background: rgba(255,255,255,0.07); border-color: rgba(255,255,255,0.14); }
+.atok-btn[disabled] { opacity: 0.45; cursor: not-allowed; }
+.atok-btn-primary {
+ background: rgba(120,200,140,0.16); border-color: rgba(120,200,140,0.3); color: #d8f5e2;
+}
+.atok-btn-primary:hover { background: rgba(120,200,140,0.22); }
+
+.atok-empty {
+ text-align: center; padding: 1rem 0.5rem; color: rgba(255,255,255,0.6);
+}
+.atok-empty-title { font-weight: 500; color: rgba(255,255,255,0.85); margin-bottom: 0.3rem; }
+.atok-empty-sub { font-size: 0.82rem; color: rgba(255,255,255,0.5); line-height: 1.5; }
+
+.atok-gov {
+ margin-top: 0.8rem; font-size: 0.72rem; color: rgba(255,255,255,0.45);
+ border-left: 2px solid rgba(255,200,140,0.2); padding: 0.3rem 0.6rem;
+}
+.atok-gov b { color: rgba(255,200,140,0.85); font-weight: 500; }
+
+.atok-mobile-strip {
+ display: none;
+}
+
+@media (max-width: 640px) {
+ .atok { margin: 0.6rem; padding: 1rem; }
+ .atok-vaults { grid-template-columns: 1fr 1fr 1fr; gap: 0.35rem; }
+ .atok-vault { padding: 0.45rem 0.5rem; }
+ .atok-vault-val { font-size: 0.85rem; }
+ .atok-mobile-strip {
+ display: flex; position: fixed; bottom: 0; left: 0; right: 0;
+ padding: 0.7rem 1rem env(safe-area-inset-bottom, 0.7rem);
+ background: rgba(8,8,10,0.92); backdrop-filter: blur(12px);
+ border-top: 1px solid rgba(255,255,255,0.06); gap: 0.6rem; align-items: center;
+ z-index: 50;
+ }
+ .atok-mobile-price { flex: 1; font-variant-numeric: tabular-nums; }
+ .atok-mobile-price small { display: block; font-size: 0.65rem; color: rgba(255,255,255,0.5); }
+ .atok-mobile-pay {
+ padding: 0.55rem 1rem; border-radius: 8px; cursor: pointer;
+ background: rgba(120,200,140,0.18); border: 1px solid rgba(120,200,140,0.3);
+ color: #d8f5e2; font-size: 0.85rem;
+ }
+}
+`;
+
+let stylesInjected = false;
+function injectStyles() {
+ if (stylesInjected) return;
+ const tag = document.createElement('style');
+ tag.textContent = STYLES;
+ document.head.appendChild(tag);
+ stylesInjected = true;
+}
+
+export class AgentTokenWidget {
+ /**
+ * @param {object} opts
+ * @param {HTMLElement} opts.mount
+ * @param {string} opts.agentId
+ * @param {boolean} [opts.isOwner]
+ * @param {EventTarget} [opts.protocol]
+ * @param {object} [opts.identity]
+ */
+ constructor({ mount, agentId, isOwner = false, protocol = null, identity = null }) {
+ this.mount = mount;
+ this.agentId = agentId;
+ this.isOwner = isOwner;
+ this.protocol = protocol;
+ this.identity = identity;
+ this.token = null; // /api/pump/by-agent payload
+ this.balances = null;
+ this.quote = null;
+ this.feed = [];
+ this.lastPrice = null;
+ this.lastVaults = null;
+ this.lastFeedTop = null;
+ this._mobileStrip = null;
+ this._poll = null;
+ this._destroyed = false;
+ injectStyles();
+ }
+
+ async render() {
+ this.mount.classList.add('atok-mount');
+ 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);
+ }
+ }
+
+ destroy() {
+ this._destroyed = true;
+ if (this._poll) clearInterval(this._poll);
+ if (this._mobileStrip?.parentNode) this._mobileStrip.parentNode.removeChild(this._mobileStrip);
+ }
+
+ async _refresh() {
+ if (this._destroyed) return;
+ try {
+ const tokenResp = await fetch(`/api/pump/by-agent?agent_id=${this.agentId}`).then((r) =>
+ r.json(),
+ );
+ this.token = tokenResp.data;
+ } catch (e) {
+ this._renderError(e.message);
+ return;
+ }
+
+ if (!this.token) {
+ this._renderEmpty();
+ return;
+ }
+
+ // Live state: parallel fetch balances, quote, feed.
+ try {
+ const [balRes, quoteRes, feedRes] = await Promise.all([
+ fetch(
+ `/api/pump/balances?mint=${this.token.mint}&network=${this.token.network}`,
+ ).then((r) => r.json()),
+ fetch(
+ `/api/pump/quote?mint=${this.token.mint}&network=${this.token.network}&direction=buy&sol=1`,
+ ).then((r) => r.json()),
+ fetch(
+ `/api/pump/payments-list?mint=${this.token.mint}&network=${this.token.network}&limit=8`,
+ ).then((r) => r.json()),
+ ]);
+ this._compareAndEmit(balRes.balances, feedRes.data);
+ this.balances = balRes.balances || null;
+ this.quote = quoteRes || null;
+ this.feed = feedRes.data || [];
+ this._renderLive();
+ } catch (e) {
+ this._renderError(e.message);
+ }
+ }
+
+ _compareAndEmit(newBal, newFeed) {
+ // Vault deltas → emit pump-balance event so other modules (avatar, etc.)
+ // can react to live revenue.
+ if (this.lastVaults && newBal && this.protocol?.emit) {
+ const dPay = this._delta(newBal.payment, this.lastVaults.payment);
+ const dBuy = this._delta(newBal.buyback, this.lastVaults.buyback);
+ const dWdr = this._delta(newBal.withdraw, this.lastVaults.withdraw);
+ if (dPay || dBuy || dWdr) {
+ this.protocol.emit('pump-balance', {
+ paymentDelta: dPay,
+ buybackDelta: dBuy,
+ withdrawDelta: dWdr,
+ });
+ }
+ }
+ this.lastVaults = newBal;
+
+ // New top-of-feed → emit pump-payment so avatar can celebrate.
+ if (newFeed && newFeed.length) {
+ const top = newFeed[0];
+ if (this.lastFeedTop && this.lastFeedTop !== top.id) {
+ this.protocol?.emit?.('pump-payment', {
+ payer: top.payer_wallet,
+ atomics: top.amount_atomics,
+ skill: top.skill_id,
+ tool: top.tool_name,
+ });
+ }
+ this.lastFeedTop = top.id;
+ }
+
+ // Graduation transition → one-time celebration.
+ if (
+ this.quote &&
+ this.lastQuoteGraduated === false &&
+ this.quote.graduated === true
+ ) {
+ this.protocol?.emit?.('pump-graduated', { mint: this.token.mint });
+ }
+ if (this.quote) this.lastQuoteGraduated = this.quote.graduated;
+ }
+
+ _delta(a, b) {
+ try {
+ return Number(BigInt(a?.balance ?? '0') - BigInt(b?.balance ?? '0'));
+ } catch {
+ return 0;
+ }
+ }
+
+ _renderEmpty() {
+ const ownerCta = this.isOwner
+ ? `<div style="margin-top:0.7rem"><a href="/dashboard/pump-launch?agent=${this.agentId}" class="atok-btn atok-btn-primary" style="text-decoration:none;display:inline-block">Launch $AGENT →</a></div>`
+ : '';
+ this.mount.innerHTML = `
+ <div class="atok">
+ <div class="atok-head">
+ <div class="atok-symbol"><span class="atok-sigil">$</span>AGENT</div>
+ <div class="atok-status empty">not launched</div>
+ </div>
+ <div class="atok-empty">
+ <div class="atok-empty-title">No agent token yet</div>
+ <div class="atok-empty-sub">
+ When this agent launches a pump.fun token, every paid call funds
+ an on-chain receipt that splits revenue between an automatic
+ buyback and the owner. ${this.isOwner ? 'Configure once, accrue forever.' : 'Be the first to fund it.'}
+ </div>
+ ${ownerCta}
+ </div>
+ </div>`;
+ }
+
+ _renderError(msg) {
+ this.mount.innerHTML = `
+ <div class="atok">
+ <div class="atok-head">
+ <div class="atok-symbol"><span class="atok-sigil">$</span>AGENT</div>
+ <div class="atok-status error">offline</div>
+ </div>
+ <div class="atok-empty"><div class="atok-empty-sub">${msg || 'Could not load token state.'}</div></div>
+ </div>`;
+ }
+
+ _renderLive() {
+ const t = this.token;
+ const b = this.balances || {};
+ const q = this.quote || {};
+ const symbol = t.symbol || 'AGENT';
+ const graduated = q.graduated === true;
+ const buybackBps = t.buyback_bps || 0;
+ const buybackPct = buybackBps / 100;
+
+ // Curve progress
+ let progressPct = null;
+ if (!graduated && q.bonding_curve) {
+ const real = Number(q.bonding_curve.real_token_reserves || 0);
+ const virt = Number(q.bonding_curve.virtual_token_reserves || 0);
+ if (virt > 0) progressPct = Math.max(0, Math.min(100, (1 - real / virt) * 100));
+ }
+
+ // Live price expressed as USDC of 1 SOL → tokens out (curve) or null (AMM).
+ const priceText =
+ q.quote && q.quote.tokens_out
+ ? `${Number(q.quote.tokens_out).toLocaleString()} ${symbol}`
+ : graduated
+ ? 'graduated'
+ : '—';
+
+ const tickClass =
+ this.lastPrice != null && q.quote?.tokens_out
+ ? Number(q.quote.tokens_out) > Number(this.lastPrice)
+ ? 'tick-up'
+ : Number(q.quote.tokens_out) < Number(this.lastPrice)
+ ? 'tick-down'
+ : ''
+ : '';
+ this.lastPrice = q.quote?.tokens_out;
+
+ const stats = t.stats || {};
+ const burns = t.burns || { runs: 0, total_burned: '0' };
+ const totalBurned = burns.total_burned && burns.total_burned !== '0'
+ ? `<div class="atok-burned">🔥 <b>${fmtUsdc(burns.total_burned)}</b> burned across ${burns.runs} buyback${burns.runs === 1 ? '' : 's'}.</div>`
+ : '';
+
+ const projection =
+ stats.confirmed_payments > 0
+ ? `${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 feedRows = (this.feed || [])
+ .slice(0, 5)
+ .map((p) => {
+ const why = p.tool_name
+ ? `<code>${p.tool_name}</code>`
+ : p.skill_id
+ ? `<code>${p.skill_id}</code>`
+ : 'paid call';
+ const buybackShare = (BigInt(p.amount_atomics || '0') * BigInt(buybackBps)) / 10_000n;
+ 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>` : ''}
+ <span style="color:rgba(255,255,255,0.35);font-size:0.7rem;">${timeAgo(p.confirmed_at || p.created_at)}</span>
+ </div>
+ </div>`;
+ })
+ .join('');
+
+ const feedBlock = feedRows
+ ? `<div class="atok-feed">
+ <div class="atok-feed-title">Recent payments</div>
+ ${feedRows}
+ </div>`
+ : stats.confirmed_payments === 0
+ ? `<div class="atok-feed">
+ <div class="atok-feed-title">Recent payments</div>
+ <div class="atok-empty-sub">First payment will fund: <b>${buybackPct}%</b> buyback, <b>${100 - buybackPct}%</b> to owner.</div>
+ </div>`
+ : '';
+
+ const ownerActions = this.isOwner
+ ? `<div class="atok-actions">
+ <button class="atok-btn atok-withdraw" ${
+ BigInt(b.withdraw?.balance || '0') === 0n ? 'disabled' : ''
+ }>
+ Withdraw ${fmtUsdc(b.withdraw?.balance || '0')}
+ </button>
+ <button class="atok-btn atok-governance">Buyback ${fmtBps(buybackBps)} ⚙</button>
+ </div>`
+ : `<div class="atok-actions">
+ <button class="atok-btn atok-btn-primary atok-pay">Pay this agent</button>
+ </div>`;
+
+ const govExplain =
+ buybackBps > 0
+ ? `<div class="atok-gov">
+ <b>Buyback ${fmtBps(buybackBps)}</b> of every paid call burns $${symbol}.
+ If this agent's reputation drops below <b>3.5★</b> for 7 days, buyback auto-lowers.
+ </div>`
+ : '';
+
+ this.mount.innerHTML = `
+ <div class="atok">
+ <div class="atok-head">
+ <div class="atok-symbol"><span class="atok-sigil">$</span>${symbol}</div>
+ <div class="atok-status ${graduated ? 'live' : 'curve'}">
+ ${graduated ? 'graduated' : 'bonding curve'}
+ </div>
+ </div>
+
+ <div class="atok-price-row">
+ <div class="atok-price ${tickClass}">${priceText}</div>
+ <div class="atok-price-label">${q.quote ? 'per 1 SOL' : ''}</div>
+ </div>
+
+ ${
+ progressPct != null
+ ? `<div class="atok-grad-bar"><div class="atok-grad-fill" style="width:${progressPct.toFixed(1)}%"></div></div>
+ <div class="atok-grad-label"><span>${progressPct.toFixed(1)}% to graduation</span><span>${graduated ? 'AMM' : 'curve'}</span></div>`
+ : graduated
+ ? `<div class="atok-grad-label" style="margin-top:0.6rem"><span>🎓 Graduated to AMM</span><span></span></div>`
+ : ''
+ }
+
+ <div class="atok-buyback">
+ <div class="atok-buyback-gauge"><div class="atok-buyback-fill" style="width:${buybackPct}%"></div></div>
+ <div class="atok-buyback-label">${fmtBps(buybackBps)} buyback</div>
+ </div>
+ <div class="atok-buyback-explain">${projection}</div>
+
+ <div class="atok-vaults">
+ <div class="atok-vault atok-vault-payment">
+ <div class="atok-vault-name">Pending</div>
+ <div class="atok-vault-val ${this._tickClassFor('payment', b.payment?.balance)}">${fmtUsdc(b.payment?.balance || '0')}</div>
+ </div>
+ <div class="atok-vault atok-vault-buyback">
+ <div class="atok-vault-name">Buyback</div>
+ <div class="atok-vault-val ${this._tickClassFor('buyback', b.buyback?.balance)}">${fmtUsdc(b.buyback?.balance || '0')}</div>
+ </div>
+ <div class="atok-vault atok-vault-withdraw">
+ <div class="atok-vault-name">Owner</div>
+ <div class="atok-vault-val ${this._tickClassFor('withdraw', b.withdraw?.balance)}">${fmtUsdc(b.withdraw?.balance || '0')}</div>
+ </div>
+ </div>
+
+ ${totalBurned}
+ ${govExplain}
+ ${feedBlock}
+ ${ownerActions}
+ </div>
+ `;
+
+ this._wireActions();
+ this._updateMobileStrip(symbol, priceText);
+ }
+
+ _tickClassFor(name, newBal) {
+ const last = this._lastVaultBalances || {};
+ const cls =
+ last[name] != null && newBal != null
+ ? BigInt(newBal) > BigInt(last[name])
+ ? 'tick-up'
+ : ''
+ : '';
+ this._lastVaultBalances = { ...last, [name]: newBal };
+ return cls;
+ }
+
+ _wireActions() {
+ const wd = this.mount.querySelector('.atok-withdraw');
+ if (wd) wd.addEventListener('click', () => this._onWithdraw());
+ const gv = this.mount.querySelector('.atok-governance');
+ if (gv) gv.addEventListener('click', () => this._onGovernance());
+ const pay = this.mount.querySelector('.atok-pay');
+ if (pay) pay.addEventListener('click', () => this._onPay());
+ }
+
+ async _onWithdraw() {
+ // Triggers the prep endpoint and surfaces a wallet popup expectation.
+ // The actual signing path lives in src/onchain/launch-token-button.js
+ // patterns and on-chain wallet adapters; here we just kick off prep.
+ const wd = this.mount.querySelector('.atok-withdraw');
+ const orig = wd.textContent;
+ wd.disabled = true;
+ wd.textContent = 'Preparing…';
+ try {
+ const resp = await fetch('/api/pump/withdraw-prep', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({
+ mint: this.token.mint,
+ authority_wallet: this.token.agent_authority,
+ receiver_ata: this.token.agent_authority, // owner self-ATA, frontend resolves
+ network: this.token.network,
+ }),
+ }).then((r) => r.json());
+ if (resp.error) throw new Error(resp.error_description || resp.error);
+ window.dispatchEvent(
+ new CustomEvent('pump-withdraw-prepared', { detail: resp }),
+ );
+ wd.textContent = 'Sign in wallet…';
+ } catch (e) {
+ wd.textContent = `Failed: ${e.message}`;
+ setTimeout(() => {
+ wd.textContent = orig;
+ wd.disabled = false;
+ }, 2400);
+ }
+ }
+
+ _onGovernance() {
+ window.dispatchEvent(
+ new CustomEvent('pump-governance-open', {
+ detail: { mint: this.token.mint, currentBps: this.token.buyback_bps },
+ }),
+ );
+ }
+
+ _onPay() {
+ window.dispatchEvent(
+ new CustomEvent('pump-pay-open', {
+ detail: { mint: this.token.mint, network: this.token.network },
+ }),
+ );
+ }
+
+ _updateMobileStrip(symbol, priceText) {
+ if (window.innerWidth > 640) return;
+ if (!this._mobileStrip) {
+ const el = document.createElement('div');
+ el.className = 'atok-mobile-strip';
+ document.body.appendChild(el);
+ this._mobileStrip = el;
+ }
+ this._mobileStrip.innerHTML = `
+ <div class="atok-mobile-price">
+ <div>$${symbol}</div>
+ <small>${priceText}</small>
+ </div>
+ <button class="atok-mobile-pay">Pay</button>`;
+ const pay = this._mobileStrip.querySelector('.atok-mobile-pay');
+ if (pay) pay.addEventListener('click', () => this._onPay());
+ }
+}
diff --git a/tests/src/pumpfun-compose-contract.test.js b/tests/src/pumpfun-compose-contract.test.js
new file mode 100644
index 000000000..d262e01c3
--- /dev/null
+++ b/tests/src/pumpfun-compose-contract.test.js
@@ -0,0 +1,174 @@
+/**
+ * Contract test for pump-fun MCP read-tool response shapes that the
+ * compose loops depend on. Mocks the MCP endpoint and asserts that
+ * realistic JSON-RPC responses parse into the fields the loops consume:
+ * - searchTokens → results[].mint
+ * - getNewTokens → tokens[].mint
+ * - getTokenHolders → topHolderPct OR holders[].pct
+ * - getCreatorProfile→ rugCount + tokens[].mint
+ * - getTokenDetails → creator
+ * - getTokenTrades → trades[] with side/wallet/sig/solAmount/pctOfSupply
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { registerPumpFunComposeSkills } from '../../src/agent-skills-pumpfun-compose.js';
+
+function jsonRpc(payload) {
+ return {
+ ok: true,
+ json: async () => ({
+ jsonrpc: '2.0',
+ id: 1,
+ result: { content: [{ type: 'text', text: JSON.stringify(payload) }] },
+ }),
+ };
+}
+
+function makeSkills() {
+ const map = new Map();
+ const performed = [];
+ return {
+ register: (def) => map.set(def.name, def),
+ get: (n) => map.get(n),
+ perform: vi.fn(async (name, args) => {
+ performed.push({ name, args });
+ if (name === 'pumpfun-buy') return { success: true, data: { signature: `sig:${args.mint}:${args.solAmount}` } };
+ if (name === 'pumpfun-sell') return { success: true, data: { signature: `sell:${args.mint}` } };
+ if (name === 'pumpfun-status') return { success: true, data: { userBalance: '12345' } };
+ return { success: false };
+ }),
+ _performed: performed,
+ };
+}
+
+describe('pump-fun compose ↔ MCP contract', () => {
+ const fetchMock = vi.fn();
+ beforeEach(() => {
+ fetchMock.mockReset();
+ globalThis.fetch = fetchMock;
+ });
+
+ it('researchAndBuy: parses searchTokens.results[].mint and routes to pumpfun-buy', async () => {
+ const skills = makeSkills();
+ registerPumpFunComposeSkills(skills);
+ const skill = skills.get('pumpfun-research-and-buy');
+
+ fetchMock.mockResolvedValueOnce(jsonRpc({ results: [{ mint: 'MINT1' }] })); // searchTokens
+ fetchMock.mockResolvedValueOnce(jsonRpc({ creator: 'CREATOR1' })); // getTokenDetails
+ fetchMock.mockResolvedValueOnce(jsonRpc({ total: 100, topHolderPct: 10 })); // getTokenHolders
+ fetchMock.mockResolvedValueOnce(jsonRpc({ rugCount: 0, tokens: [] })); // getCreatorProfile
+
+ const r = await skill.handler({ query: 'foo', amountSol: 0.1 }, {});
+ expect(r.success).toBe(true);
+ expect(r.data.decision).toBe('buy');
+ expect(r.data.mint).toBe('MINT1');
+ expect(skills._performed).toContainEqual({ name: 'pumpfun-buy', args: { mint: 'MINT1', solAmount: 0.1 } });
+ });
+
+ it('researchAndBuy with simulate:true skips signing but still vets', async () => {
+ const skills = makeSkills();
+ registerPumpFunComposeSkills(skills);
+ const skill = skills.get('pumpfun-research-and-buy');
+
+ fetchMock.mockResolvedValueOnce(jsonRpc({ results: [{ mint: 'MINT2' }] }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ creator: 'CREATOR2' }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ total: 100, topHolderPct: 5 }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ rugCount: 0 }));
+
+ const r = await skill.handler({ query: 'bar', amountSol: 0.05, simulate: true }, {});
+ expect(r.data.decision).toBe('buy');
+ expect(r.data.simulate).toBe(true);
+ expect(r.data.sig).toMatch(/^SIMULATED:buy:/);
+ expect(skills.perform).not.toHaveBeenCalledWith('pumpfun-buy', expect.anything(), expect.anything());
+ });
+
+ it('filters reject high top-holder concentration', async () => {
+ const skills = makeSkills();
+ registerPumpFunComposeSkills(skills);
+ const skill = skills.get('pumpfun-research-and-buy');
+
+ fetchMock.mockResolvedValueOnce(jsonRpc({ results: [{ mint: 'WHALE' }] }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ creator: 'C' }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ holders: [{ pct: 80 }] })); // topHolderPct via fallback path
+ fetchMock.mockResolvedValueOnce(jsonRpc({ rugCount: 0 }));
+
+ const r = await skill.handler({ query: 'x' }, {});
+ expect(r.data.decision).toBe('skip');
+ expect(r.data.reason).toMatch(/top holder owns 80/);
+ });
+
+ it('filters reject creator with prior rugs', async () => {
+ const skills = makeSkills();
+ registerPumpFunComposeSkills(skills);
+ const skill = skills.get('pumpfun-research-and-buy');
+
+ fetchMock.mockResolvedValueOnce(jsonRpc({ results: [{ mint: 'RUGGED' }] }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ creator: 'BAD' }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ total: 100, topHolderPct: 5 }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ rugFlags: ['x', 'y', 'z'] })); // rugFlags fallback path
+
+ const r = await skill.handler({ query: 'x' }, {});
+ expect(r.data.decision).toBe('skip');
+ expect(r.data.reason).toMatch(/3 prior rug/);
+ });
+
+ it('rugExitWatch sells when top holder crosses concentration threshold', async () => {
+ const skills = makeSkills();
+ registerPumpFunComposeSkills(skills);
+ const skill = skills.get('pumpfun-rug-exit-watch');
+
+ fetchMock.mockResolvedValueOnce(jsonRpc({ topHolderPct: 60 })); // holders
+ fetchMock.mockResolvedValueOnce(jsonRpc({ trades: [] })); // trades
+ fetchMock.mockResolvedValueOnce(jsonRpc({ creator: 'DEV' })); // details
+
+ const r = await skill.handler({ mints: ['MINT_X'], durationSec: 1, simulate: false }, {});
+ 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());
+ });
+
+ it('rugExitWatch sells when dev sells exceed devSell threshold', async () => {
+ const skills = makeSkills();
+ registerPumpFunComposeSkills(skills);
+ const skill = skills.get('pumpfun-rug-exit-watch');
+
+ fetchMock.mockResolvedValueOnce(jsonRpc({ topHolderPct: 5 }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ trades: [{ side: 'sell', wallet: 'DEV', pctOfSupply: 30 }] }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ creator: 'DEV' }));
+
+ const r = await skill.handler({ mints: ['MINT_Y'], durationSec: 1 }, {});
+ expect(r.data.exited).toEqual(['MINT_Y']);
+ expect(r.data.events[0].trigger).toMatch(/dev sold 30/);
+ });
+
+ it('sessionId persists spent across two autoSnipe runs (no double-spend)', async () => {
+ const skills = makeSkills();
+ registerPumpFunComposeSkills(skills);
+ const snipe = skills.get('pumpfun-auto-snipe');
+
+ const memoryEntries = [];
+ const ctx = {
+ memory: {
+ add: (e) => memoryEntries.push(e),
+ query: ({ tags }) => memoryEntries.filter((m) => (m.tags || []).some((t) => tags.includes(t))).slice(-1),
+ },
+ skillConfig: { sessionSpendCapSol: 0.05, perTradeSol: 0.05, pollMs: 0 },
+ };
+
+ // Run 1: 1 fresh token, 1 buy → spent = 0.05, then cap blocks further loops
+ fetchMock.mockResolvedValueOnce(jsonRpc({ tokens: [{ mint: 'A' }] }));
+ fetchMock.mockResolvedValueOnce(jsonRpc({ creator: 'CA' })); // details
+ fetchMock.mockResolvedValueOnce(jsonRpc({ total: 100, topHolderPct: 5 })); // holders
+ fetchMock.mockResolvedValueOnce(jsonRpc({ rugCount: 0 })); // creator
+
+ const r1 = await snipe.handler({ durationSec: 1, sessionId: 'S1' }, ctx);
+ expect(r1.data.spent).toBe(0.05);
+
+ // Run 2: same sessionId, fresh cap. State should restore — A is in `seen`,
+ // won't re-buy even though the cap would otherwise allow it.
+ ctx.skillConfig.sessionSpendCapSol = 0.5;
+ fetchMock.mockResolvedValueOnce(jsonRpc({ tokens: [{ mint: 'A' }] }));
+ const r2 = await snipe.handler({ durationSec: 1, sessionId: 'S1' }, ctx);
+ expect(r2.data.spent).toBe(0.05); // unchanged — A was already seen
+ });
+});
diff --git a/vercel.json b/vercel.json
index 482bc38c2..24e7d0891 100644
--- a/vercel.json
+++ b/vercel.json
@@ -250,6 +250,7 @@
{ "path": "/api/cron/index-delegations", "schedule": "*/5 * * * *" },
{ "path": "/api/cron/run-dca", "schedule": "0 * * * *" },
{ "path": "/api/cron/run-subscriptions", "schedule": "0 * * * *" },
- { "path": "/api/cron/pumpfun-signals", "schedule": "*/15 * * * *" }
+ { "path": "/api/cron/pumpfun-signals", "schedule": "*/15 * * * *" },
+ { "path": "/api/cron/pump-agent-stats", "schedule": "*/10 * * * *" }
]
}