Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: implement TokenAdapter and PumpfunTokenAdapter for token launch functionality
nirholase996655a58e6
diff --git a/api/_lib/migrations/2026-04-29-token-launches.sql b/api/_lib/migrations/2026-04-29-token-launches.sqlnew file mode 100644index 000000000..6826d4bd3--- /dev/null+++ b/api/_lib/migrations/2026-04-29-token-launches.sql@@ -0,0 +1,53 @@+-- Migration: agent token launches (Pump.fun + future providers).+--+-- Adds:+-- • token_launches_pending — transient prep records (mirrors+-- agent_registrations_pending, but for token launches).+-- • Documents the canonical agent_identities.meta.token shape.+-- • Indexes meta.token.mint for fast lookups by mint pubkey.+--+-- Idempotent: safe to re-run.++begin;++create table if not exists token_launches_pending (+ id text primary key, -- prep_id (random token)+ user_id uuid not null references users(id) on delete cascade,+ agent_id uuid not null references agent_identities(id) on delete cascade,+ provider text not null check (provider in ('pumpfun')),+ cluster text not null check (cluster in ('mainnet', 'devnet')),+ mint text not null, -- base58 mint pubkey+ metadata_uri text not null,+ cid text not null,+ payload jsonb not null,+ created_at timestamptz not null default now(),+ expires_at timestamptz not null+);++create index if not exists token_launches_pending_user_expiry+ on token_launches_pending(user_id, expires_at);++create index if not exists token_launches_pending_agent+ on token_launches_pending(agent_id);++-- Garbage-collection helper. Optional — Vercel/Neon don't auto-vacuum these,+-- so a daily cleanup job (or the prep endpoint itself, lazily) should run:+-- delete from token_launches_pending where expires_at < now() - interval '7 days';++-- Index meta.token.mint so we can answer "which agent owns this mint?" cheaply.+create index if not exists agent_identities_token_mint+ on agent_identities ((meta->'token'->>'mint'))+ where deleted_at is null and (meta ? 'token');++create index if not exists agent_identities_token_provider+ on agent_identities ((meta->'token'->>'provider'))+ where deleted_at is null and (meta ? 'token');++-- Document the canonical shape (no schema change — just a comment for humans).+comment on column agent_identities.meta is+ 'jsonb. Canonical blocks: '+ 'meta.onchain (deploy: chain, family, tx_hash, contract_or_mint, wallet, metadata_uri, confirmed_at) | '+ 'meta.token (launch: provider, mint, symbol, name, metadata_uri, cluster, creator, tx_signature, launched_at) | '+ 'meta.payments (configure: receiver, accepted_tokens) — reserved for future use';++commit;diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 690295c06..bf5fe89ac 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -681,3 +681,21 @@ create table if not exists user_prefs (prefs jsonb not null default '{}'::jsonb,updated_at timestamptz not null default now());++-- ── pumpfun_signals — off-chain pump.fun activity signals attached to a wallet ─+-- Not an on-chain attestation — these are crawled from the upstream+-- pumpfun-claims-bot enrichment pipeline. Used to weight Solana reputation+-- and surface trust signals on the agent passport.+create table if not exists pumpfun_signals (+ id bigserial primary key,+ wallet text not null, -- claimer / creator base58 pubkey+ agent_asset text, -- linked Solana agent if known+ kind text not null, -- 'first_claim' | 'fake_claim' | 'graduation' | 'influencer' | 'new_account'+ weight real not null default 0,-- reputation impact, -1..1+ payload jsonb not null default '{}'::jsonb,+ tx_signature text unique,+ seen_at timestamptz not null default now()+);+create index if not exists pumpfun_signals_wallet on pumpfun_signals(wallet, seen_at desc);+create index if not exists pumpfun_signals_agent on pumpfun_signals(agent_asset, seen_at desc) where agent_asset is not null;+create index if not exists pumpfun_signals_kind on pumpfun_signals(kind, seen_at desc);diff --git a/api/_lib/solana-wallet.js b/api/_lib/solana-wallet.jsnew file mode 100644index 000000000..5f29ae628--- /dev/null+++ b/api/_lib/solana-wallet.js@@ -0,0 +1,48 @@+// Solana wallet adapter — produces the `ctx.wallet` contract used by signing skills+// (pump-fun-trade, jupiter-swap, etc). Built on top of recoverSolanaAgentKeypair.++import { Connection, PublicKey, Transaction, VersionedTransaction } from '@solana/web3.js';+import { recoverSolanaAgentKeypair } from './agent-wallet.js';++/**+ * Build a wallet from an encrypted secret. Returns the contract:+ * { publicKey, signTransaction(tx), sendAndConfirm(tx, conn) }+ * publicKey is a PublicKey (not a string) so it can be used with web3.js directly.+ */+export async function loadWallet(encryptedSecret) {+ const kp = await recoverSolanaAgentKeypair(encryptedSecret);++ function signTransaction(tx) {+ if (tx instanceof VersionedTransaction) {+ tx.sign([kp]);+ } else if (tx instanceof Transaction) {+ tx.partialSign(kp);+ } else {+ throw new Error('signTransaction: unsupported tx type');+ }+ return tx;+ }++ async function sendAndConfirm(tx, conn) {+ signTransaction(tx);+ const raw = tx.serialize();+ const sig = await conn.sendRawTransaction(raw, { skipPreflight: false });+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash();+ await conn.confirmTransaction(+ { signature: sig, blockhash, lastValidBlockHeight },+ 'confirmed',+ );+ return sig;+ }++ return { publicKey: kp.publicKey, signTransaction, sendAndConfirm };+}++/**+ * Convenience: build a Connection from a URL, defaulting to mainnet.+ */+export function makeConnection(rpcUrl) {+ return new Connection(rpcUrl ?? 'https://api.mainnet-beta.solana.com', 'confirmed');+}++export { PublicKey };diff --git a/api/agents/[id].js b/api/agents/[id].jsindex 976b5b215..94f092732 100644--- a/api/agents/[id].js+++ b/api/agents/[id].js@@ -1,6 +1,10 @@/**- * /api/agents/:id and /api/agents/:id/wallet- * Routes to the appropriate handler in api/agents.js+ * /api/agents/:id — agent CRUD+ * /api/agents/:id/wallet — link / update EVM wallet+ * /api/agents/:id/solana — agent's Solana wallet (address + balance, provision)+ * /api/agents/:id/pumpfun/launch — create a pump.fun token from this agent+ * /api/agents/:id/pumpfun/swap — swap via @pump-fun/pump-swap-sdk+ * /api/agents/:id/pumpfun/pay — agent payment via @pump-fun/agent-payments-sdk*/import { handleGetOne, handleWallet } from '../agents.js';import { cors, error, wrap } from '../_lib/http.js';@@ -8,9 +12,9 @@ import { cors, error, wrap } from '../_lib/http.js';export default wrap(async function handler(req, res) {const url = new URL(req.url, 'http://x');const parts = url.pathname.split('/').filter(Boolean);- // parts: ['api', 'agents', ':id'] or ['api', 'agents', ':id', 'wallet']const id = parts[2];const sub = parts[3];+ const action = parts[4];if (!id) {if (cors(req, res)) return;@@ -18,5 +22,19 @@ export default wrap(async function handler(req, res) {}if (sub === 'wallet') return handleWallet(req, res, id);++ if (sub === 'solana') {+ const mod = await import('./solana-wallet.js');+ return mod.default(req, res, id);+ }++ if (sub === 'pumpfun') {+ if (action === 'launch') return (await import('./pumpfun/launch.js')).default(req, res, id);+ if (action === 'swap') return (await import('./pumpfun/swap.js')).default(req, res, id);+ if (action === 'pay') return (await import('./pumpfun/pay.js')).default(req, res, id);+ if (cors(req, res)) return;+ return error(res, 404, 'not_found', 'unknown pumpfun action');+ }+return handleGetOne(req, res, id);});diff --git a/api/agents/solana-attest-event.js b/api/agents/solana-attest-event.jsindex 64b78a3bb..d5ad202d8 100644--- a/api/agents/solana-attest-event.js+++ b/api/agents/solana-attest-event.js@@ -2,6 +2,16 @@// Receives a signed webhook from a pumpkit monitor and emits a// threews.* SPL Memo on Solana, then mirrors it into solana_attestations// so reputation reflects the event without waiting for the crawler.+//+// Webhook contract:+// POST /api/agents/solana-attest-event+// headers:+// x-pumpkit-timestamp: <unix seconds>+// x-pumpkit-signature: hex(hmac_sha256(secret, "<ts>.<raw-body>"))+// body: { event_id, event_type, agent_asset, network, token_mint, task_id, detail? }+//+// Idempotency: each (agent_asset, payload.event_id) pair is emitted at most once.+// Replay: rejects timestamps outside REPLAY_WINDOW_SECS.import crypto from 'node:crypto';import {@@ -16,78 +26,71 @@ import bs58 from 'bs58';import { z } from 'zod';import { sql } from '../_lib/db.js';-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error } from '../_lib/http.js';import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { RPC, KIND_MAP } from '../_lib/solana-attestations.js';const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');+const REPLAY_WINDOW_SECS = 5 * 60;+const MAX_BODY_BYTES = 64_000;const bodySchema = z.object({- event_type: z.enum(['graduation', 'fee_claim', 'whale_trade', 'cto_detected']),+ event_id: z.string().min(1).max(128),+ event_type: z.enum(['graduation', 'fee_claim', 'whale_trade', 'cto_detected']),agent_asset: z.string().min(32).max(44),- network: z.enum(['mainnet', 'devnet']),- token_mint: z.string().min(32).max(44),- task_id: z.string().min(1).max(128),- detail: z.record(z.unknown()).optional(),+ network: z.enum(['mainnet', 'devnet']),+ token_mint: z.string().min(32).max(44),+ task_id: z.string().min(1).max(128),+ detail: z.record(z.unknown()).optional(),});-// Map a pumpkit event onto a 3ws attestation envelope.-function buildPayload({ event_type, agent_asset, token_mint, task_id, detail }) {- const base = { v: 1, agent: agent_asset, ts: Math.floor(Date.now() / 1000) };+// -- Pure helpers (exported for tests) -----------------------------------++export function taskHash(task_id, token_mint) {+ return crypto.createHash('sha256').update(`${task_id}:${token_mint}`).digest('hex');+}++export function buildPayload({ event_id, event_type, agent_asset, token_mint, task_id, detail }) {+ const base = { v: 1, agent: agent_asset, ts: Math.floor(Date.now() / 1000), event_id };switch (event_type) {case 'graduation':- return {- ...base,- kind: KIND_MAP.validation,- task_hash: task_hash(task_id, token_mint),- passed: true,- source: 'pumpkit.graduation',- token: token_mint,- };+ return { ...base, kind: KIND_MAP.validation,+ task_hash: taskHash(task_id, token_mint), passed: true,+ source: 'pumpkit.graduation', token: token_mint };case 'fee_claim':- return {- ...base,- kind: KIND_MAP.feedback,- score: 5,- source: 'pumpkit.fee_claim',- token: token_mint,- detail: detail ?? null,- };+ return { ...base, kind: KIND_MAP.feedback,+ score: 5, source: 'pumpkit.fee_claim',+ token: token_mint, detail: detail ?? null };case 'whale_trade':- return {- ...base,- kind: KIND_MAP.task,- task_id,- scope_hash: task_hash(task_id, token_mint),- source: 'pumpkit.whale',- };+ return { ...base, kind: KIND_MAP.task,+ task_id, scope_hash: taskHash(task_id, token_mint),+ source: 'pumpkit.whale' };case 'cto_detected':- return {- ...base,- kind: KIND_MAP.validation,- task_hash: task_hash(task_id, token_mint),- passed: false,- source: 'pumpkit.cto',- token: token_mint,- };+ return { ...base, kind: KIND_MAP.validation,+ task_hash: taskHash(task_id, token_mint), passed: false,+ source: 'pumpkit.cto', token: token_mint };}}-function task_hash(task_id, token_mint) {- return crypto.createHash('sha256').update(`${task_id}:${token_mint}`).digest('hex');+// Signed message is `${timestamp}.${raw}` — binds body to its declared time+// so a captured signature can't be replayed against a fresh body.+export function verifyPumpkitSignature({ secret, timestamp, signature, raw, nowSecs = Math.floor(Date.now() / 1000) }) {+ if (!secret || !timestamp || !signature) return { ok: false, reason: 'missing' };+ const ts = Number(timestamp);+ if (!Number.isFinite(ts)) return { ok: false, reason: 'bad_timestamp' };+ if (Math.abs(nowSecs - ts) > REPLAY_WINDOW_SECS) return { ok: false, reason: 'stale' };++ const expect = crypto.createHmac('sha256', secret)+ .update(`${ts}.`).update(raw).digest();+ let got;+ try { got = Buffer.from(signature, 'hex'); }+ catch { return { ok: false, reason: 'bad_signature' }; }+ if (got.length !== expect.length) return { ok: false, reason: 'bad_signature' };+ return { ok: crypto.timingSafeEqual(got, expect), reason: 'ok' };}-function verifyPumpkitSignature(req, raw) {- const secret = process.env.PUMPKIT_WEBHOOK_SECRET;- if (!secret) throw Object.assign(new Error('webhook secret not configured'), { status: 500 });- const got = req.headers['x-pumpkit-signature'];- if (!got || typeof got !== 'string') return false;- const expect = crypto.createHmac('sha256', secret).update(raw).digest('hex');- const a = Buffer.from(got, 'hex');- const b = Buffer.from(expect, 'hex');- return a.length === b.length && crypto.timingSafeEqual(a, b);-}+// -- Handler -------------------------------------------------------------function loadAttesterKeypair() {const k = process.env.ATTEST_AGENT_SECRET_KEY;@@ -95,6 +98,17 @@ function loadAttesterKeypair() {return Keypair.fromSecretKey(bs58.decode(k));}+async function readBuffered(req) {+ const chunks = [];+ let total = 0;+ for await (const c of req) {+ chunks.push(c);+ total += c.length;+ if (total > MAX_BODY_BYTES) throw Object.assign(new Error('payload too large'), { status: 413 });+ }+ return Buffer.concat(chunks);+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (!method(req, res, ['POST'])) return;@@ -102,16 +116,42 @@ export default wrap(async (req, res) => {const rl = await limits.authIp(clientIp(req));if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');- // Read raw body once for HMAC, then parse.+ const secret = process.env.PUMPKIT_WEBHOOK_SECRET;+ if (!secret) return error(res, 500, 'internal', 'webhook secret not configured');+const raw = await readBuffered(req);- if (!verifyPumpkitSignature(req, raw)) {- return error(res, 401, 'unauthorized', 'invalid webhook signature');- }+ const verdict = verifyPumpkitSignature({+ secret,+ timestamp: req.headers['x-pumpkit-timestamp'],+ signature: req.headers['x-pumpkit-signature'],+ raw,+ });+ if (!verdict.ok) return error(res, 401, 'unauthorized', `invalid webhook signature (${verdict.reason})`);+let parsed;try { parsed = JSON.parse(raw.toString('utf8')); }catch { return error(res, 400, 'validation_error', 'invalid JSON'); }const body = parse(bodySchema, parsed);+ // Confirm the agent exists in our registry on the declared network.+ const [agent] = await sql`+ select id from agent_identities+ where meta->'onchain'->>'sol_asset' = ${body.agent_asset}+ or meta->>'sol_mint_address' = ${body.agent_asset}+ limit 1+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent_asset not registered');++ // Idempotency: short-circuit if we've already attested this event_id.+ const [existing] = await sql`+ select signature from solana_attestations+ where agent_asset = ${body.agent_asset}+ and network = ${body.network}+ and payload->>'event_id' = ${body.event_id}+ limit 1+ `;+ if (existing) return json(res, 200, { data: { signature: existing.signature, deduped: true } });+const payload = buildPayload(body);const memo = JSON.stringify(payload);@@ -119,7 +159,7 @@ export default wrap(async (req, res) => {const attester = loadAttesterKeypair();const agentKey = new PublicKey(body.agent_asset);- // Memo with the agent asset as a signer-less referenced key, so+ // Memo includes the agent asset as a non-signer key so// getSignaturesForAddress(agent) finds the tx during crawl.const ix = new TransactionInstruction({programId: MEMO_PROGRAM_ID,@@ -131,9 +171,7 @@ export default wrap(async (req, res) => {});const tx = new Transaction().add(ix);- const signature = await sendAndConfirmTransaction(conn, tx, [attester], {- commitment: 'confirmed',- });+ const signature = await sendAndConfirmTransaction(conn, tx, [attester], { commitment: 'confirmed' });// Mirror into the index immediately; crawler dedupes via unique signature.// Verified semantics match _lib/solana-attestations.js#computeVerified for@@ -152,16 +190,5 @@ export default wrap(async (req, res) => {on conflict (signature) do nothing`;- return json(res, 201, { data: { signature, kind: payload.kind } });+ return json(res, 201, { data: { signature, kind: payload.kind, deduped: false } });});--async function readBuffered(req) {- const chunks = [];- let total = 0;- for await (const c of req) {- chunks.push(c);- total += c.length;- if (total > 64_000) throw Object.assign(new Error('payload too large'), { status: 413 });- }- return Buffer.concat(chunks);-}diff --git a/api/agents/solana-register-confirm.js b/api/agents/solana-register-confirm.jsindex d26c3367b..88e5a68bc 100644--- a/api/agents/solana-register-confirm.js+++ b/api/agents/solana-register-confirm.js@@ -109,6 +109,7 @@ export default wrap(async (req, res) => {network,sol_mint_address: asset_pubkey,tx_signature,+ ...(payload.vanity_prefix ? { vanity_prefix: payload.vanity_prefix } : {}),})}::jsonb)returning id, name, description, wallet_address, meta, created_atdiff --git a/api/agents/solana-register-prep.js b/api/agents/solana-register-prep.jsindex ca60d134c..54843a0c7 100644--- a/api/agents/solana-register-prep.js+++ b/api/agents/solana-register-prep.js@@ -28,6 +28,11 @@ import { env } from '../_lib/env.js';const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+// Base58 alphabet excluding 0/O/I/l. Mirrors src/solana/vanity/validation.js.+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;+// Vanity prefixes >= this length require a paid plan.+const VANITY_FREE_THRESHOLD = 5;+const bodySchema = z.object({name: z.string().trim().min(1).max(60),description: z.string().trim().max(280).default(''),@@ -35,6 +40,11 @@ const bodySchema = z.object({wallet_address: z.string().min(32).max(44), // Solana base58 pubkeymetadata_uri: z.string().url().optional(), // pre-pinned IPFS or HTTPS URInetwork: z.enum(['mainnet', 'devnet']).default('mainnet'),+ // Optional client-grinded vanity asset pubkey. When provided, the server+ // builds the tx against this pubkey (noop signer) and the client must+ // sign the tx with the matching keypair before submitting.+ asset_pubkey: z.string().min(32).max(44).optional(),+ vanity_prefix: z.string().min(1).max(6).optional(),});export default wrap(async (req, res) => {@@ -48,7 +58,7 @@ export default wrap(async (req, res) => {if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');const body = parse(bodySchema, await readJson(req));- const { name, description, avatar_id, wallet_address, network } = body;+ const { name, description, avatar_id, wallet_address, network, asset_pubkey, vanity_prefix } = body;// Verify wallet belongs to this user.const [walletRow] = await sql`@@ -64,6 +74,29 @@ export default wrap(async (req, res) => {if (!av) return error(res, 404, 'not_found', 'avatar not found');}+ // Vanity validation + paywall. Both fields are optional but must agree+ // when present (we don't trust the client to honestly report length).+ if (vanity_prefix && !asset_pubkey) {+ return error(res, 400, 'validation_error', 'vanity_prefix requires asset_pubkey');+ }+ if (asset_pubkey) {+ if (!BASE58_RE.test(asset_pubkey)) {+ return error(res, 400, 'validation_error', 'asset_pubkey is not valid base58');+ }+ if (vanity_prefix) {+ if (!BASE58_RE.test(vanity_prefix)) {+ return error(res, 400, 'validation_error', 'vanity_prefix is not valid base58');+ }+ if (!asset_pubkey.startsWith(vanity_prefix)) {+ return error(res, 400, 'validation_error', 'asset_pubkey does not start with vanity_prefix');+ }+ if (vanity_prefix.length >= VANITY_FREE_THRESHOLD && (user.plan ?? 'free') === 'free') {+ return error(res, 402, 'payment_required',+ `vanity prefixes of ${VANITY_FREE_THRESHOLD}+ characters require a paid plan`);+ }+ }+ }+const rpcEndpoint = network === 'devnet'? (process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'): SOLANA_RPC;@@ -71,8 +104,11 @@ export default wrap(async (req, res) => {// Build Umi instance. We use a noop signer since the user's wallet will sign.const umi = createUmi(rpcEndpoint).use(mplCore());const ownerPubkey = umiPublicKey(wallet_address);- // Create a throwaway mint keypair — the actual signer will be the user's wallet for the asset account.- const assetSigner = generateSigner(umi);+ // Asset signer: either the client-supplied vanity pubkey (noop — client signs)+ // or a freshly-generated server-side throwaway keypair.+ const assetSigner = asset_pubkey+ ? createNoopSigner(umiPublicKey(asset_pubkey))+ : generateSigner(umi);// Set the owner as a noop signer so Umi treats them as a required signer.umi.use(signerIdentity(createNoopSigner(ownerPubkey)));@@ -108,6 +144,7 @@ export default wrap(async (req, res) => {asset_pubkey: assetSigner.publicKey,network,prep_id: prepId,+ vanity_prefix: vanity_prefix || null,})}::jsonb,${expiresAt})diff --git a/api/agents/solana-reputation.js b/api/agents/solana-reputation.jsindex 3533d9678..89df8a470 100644--- a/api/agents/solana-reputation.js+++ b/api/agents/solana-reputation.js@@ -133,9 +133,53 @@ export default wrap(async (req, res) => {select last_indexed_at from solana_attestations_cursor where agent_asset = ${asset} limit 1`;+ // Pump.fun off-chain signals: claim/graduation activity attached to the+ // agent's wallet. Aggregated as a positive/negative weight contribution.+ let pumpfunSignals = { count: 0, weight: 0, by_kind: {} };+ try {+ const rows = await sql`+ select kind, count(*)::int as n, coalesce(sum(weight), 0)::float as w+ from pumpfun_signals+ where agent_asset = ${asset}+ group by kind+ `;+ const byKind = {};+ let total = 0,+ weight = 0;+ for (const r of rows) {+ byKind[r.kind] = { count: r.n, weight: Number(r.w.toFixed(3)) };+ total += r.n;+ weight += r.w;+ }+ pumpfunSignals = { count: total, weight: Number(weight.toFixed(3)), by_kind: byKind };+ } catch {+ // pumpfun_signals table may not exist yet — silently ignore.+ }++ // Pump.fun agent-payments signal: confirmed acceptPayment receipts add a+ // volume-weighted, Sybil-resistant reputation lane on top of memo attestations.+ let pumpPayments = { confirmed_count: 0, unique_payers: 0, total_atomics: '0' };+ try {+ const [row] = await sql`+ select+ count(*) filter (where p.status='confirmed')::int as confirmed_count,+ count(distinct p.payer_wallet) filter (where p.status='confirmed')::int as unique_payers,+ coalesce(sum(p.amount_atomics) filter (where p.status='confirmed'), 0)::text as total_atomics+ from pump_agent_payments p+ join pump_agent_mints m on m.id = p.mint_id+ join agent_identities a on a.id = m.agent_id+ where (a.meta->>'sol_mint_address') = ${asset} and m.network = ${network}+ `;+ if (row) pumpPayments = row;+ } catch {+ // pump_agent_payments table may not exist yet (migration not applied) — silently ignore.+ }+return json(res, 200, {agent: asset,network,+ pump_payments: pumpPayments,+ pumpfun_signals: pumpfunSignals,feedback: {total: fb.total,verified: fb.verified,diff --git a/api/cron/pumpfun-signals.js b/api/cron/pumpfun-signals.jsnew file mode 100644index 000000000..037d32b22--- /dev/null+++ b/api/cron/pumpfun-signals.js@@ -0,0 +1,164 @@+/**+ * Pump.fun signals crawler.+ *+ * Periodically pulls recent claim activity from the upstream pumpfun-claims-bot+ * MCP server, filters to claims/graduations whose creator or claimer wallet is+ * linked to a `user_wallets` row (chain_type='solana'), and writes typed signals+ * to `pumpfun_signals`. The `solana-reputation` endpoint reads these to weight+ * the Solana agent reputation score.+ *+ * Runs every 15 minutes via Vercel Cron (see vercel.json). Manually triggerable+ * with `Authorization: Bearer $CRON_SECRET`.+ *+ * Idempotent: tx_signature is unique; duplicate inserts are skipped.+ */++import { sql } from '../_lib/db.js';+import { cors, error, json, wrap } from '../_lib/http.js';+import { pumpfunMcp, pumpfunBotEnabled } from '../_lib/pumpfun-mcp.js';++const CLAIMS_PER_RUN = 200;+const GRADS_PER_RUN = 50;++const SIGNAL_WEIGHT = {+ first_claim: +0.2,+ graduation: +0.3,+ influencer: +0.2,+ fake_claim: -0.6,+ new_account: -0.2,+};++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;++ const auth = req.headers['authorization'] || '';+ const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;+ const fromCron = req.headers['x-vercel-cron'] === '1';+ if (!fromCron && expected && auth !== expected) {+ return error(res, 401, 'unauthorized', 'cron secret required');+ }++ if (!pumpfunBotEnabled()) {+ return json(res, 200, { skipped: 'pumpfun bot not configured' });+ }++ const [claims, grads] = await Promise.all([+ pumpfunMcp.recentClaims({ limit: CLAIMS_PER_RUN }),+ pumpfunMcp.graduations({ limit: GRADS_PER_RUN }),+ ]);++ const report = { claims: 0, graduations: 0, inserted: 0, skipped: 0, errors: [] };++ const claimItems = arr(claims.ok ? claims.data : null);+ const gradItems = arr(grads.ok ? grads.data : null);+ report.claims = claimItems.length;+ report.graduations = gradItems.length;++ const wallets = collectWallets(claimItems, gradItems);+ const linked = await linkedWalletMap(wallets);++ for (const ev of claimItems) {+ const wallet = ev.claimer || ev.github_wallet;+ if (!wallet || !linked.has(wallet)) {+ report.skipped++;+ continue;+ }+ try {+ const inserts = signalsFromClaim(ev);+ for (const sig of inserts) {+ const ok = await insertSignal({+ wallet,+ agent_asset: linked.get(wallet) || null,+ kind: sig.kind,+ weight: SIGNAL_WEIGHT[sig.kind] ?? 0,+ payload: sig.payload,+ tx_signature: sig.tx_signature,+ });+ if (ok) report.inserted++;+ }+ } catch (err) {+ report.errors.push({ tx: ev.tx_signature, error: err.message });+ }+ }++ for (const ev of gradItems) {+ const wallet = ev.creator || ev.dev_wallet;+ if (!wallet || !linked.has(wallet)) {+ report.skipped++;+ continue;+ }+ try {+ const ok = await insertSignal({+ wallet,+ agent_asset: linked.get(wallet) || null,+ kind: 'graduation',+ weight: SIGNAL_WEIGHT.graduation,+ payload: { mint: ev.mint, symbol: ev.symbol, name: ev.name },+ tx_signature: ev.tx_signature || ev.signature,+ });+ if (ok) report.inserted++;+ } catch (err) {+ report.errors.push({ tx: ev.tx_signature, error: err.message });+ }+ }++ return json(res, 200, report);+});++function arr(x) {+ if (!x) return [];+ return Array.isArray(x) ? x : x.items || [];+}++function collectWallets(claims, grads) {+ const out = new Set();+ for (const c of claims) {+ if (c.claimer) out.add(c.claimer);+ if (c.github_wallet) out.add(c.github_wallet);+ }+ for (const g of grads) {+ if (g.creator) out.add(g.creator);+ if (g.dev_wallet) out.add(g.dev_wallet);+ }+ return [...out];+}++async function linkedWalletMap(wallets) {+ const map = new Map();+ if (wallets.length === 0) return map;+ const rows = await sql`+ select uw.address, ai.meta->>'sol_mint_address' as agent_asset+ from user_wallets uw+ left join agent_identities ai+ on ai.user_id = uw.user_id+ and ai.deleted_at is null+ and ai.meta->>'chain_type' = 'solana'+ where uw.chain_type = 'solana'+ and uw.address = any(${wallets})+ `;+ for (const r of rows) map.set(r.address, r.agent_asset);+ return map;+}++function signalsFromClaim(ev) {+ const out = [];+ const base = { tx_signature: ev.tx_signature, payload: ev };+ if (ev.first_time_claim) out.push({ kind: 'first_claim', ...base });+ if (ev.fake_claim) out.push({ kind: 'fake_claim', ...base });+ if (ev.tier === 'mega' || ev.tier === 'influencer') out.push({ kind: 'influencer', ...base });+ if (ev.github_account_age_days != null && ev.github_account_age_days < 30) {+ out.push({ kind: 'new_account', ...base });+ }+ return out;+}++async function insertSignal({ wallet, agent_asset, kind, weight, payload, tx_signature }) {+ if (!tx_signature) return false;+ const result = await sql`+ insert into pumpfun_signals (wallet, agent_asset, kind, weight, payload, tx_signature)+ values (${wallet}, ${agent_asset}, ${kind}, ${weight}, ${JSON.stringify(payload)}::jsonb, ${tx_signature})+ on conflict (tx_signature) do nothing+ returning id+ `;+ return result.length > 0;+}diff --git a/api/wk-x402.js b/api/wk-x402.jsindex 7dcce258d..861a2a948 100644--- a/api/wk-x402.js+++ b/api/wk-x402.js@@ -13,6 +13,19 @@ export default wrap(async (req, res) => {{version: 1,resources: ['POST /api/mcp'],+ schemes: ['solana-pay', 'evm-erc20', 'pump-agent-payments'],+ // pump-agent-payments: settlement via @pump-fun/agent-payments-sdk+ // acceptPayment ix. Each paid call funds an on-chain receipt PDA tied+ // to the resource's agent mint, automatically splitting revenue into+ // buyback + withdraw vaults per the agent's configured buybackBps.+ // Discovery: GET /api/pump/balances?mint=<agent_mint> returns vault+ // state for the resource. Settlement endpoint:+ // POST /api/pump/accept-payment-prep + /api/pump/accept-payment-confirm.+ pump_agent_payments: {+ prep: '/api/pump/accept-payment-prep',+ confirm: '/api/pump/accept-payment-confirm',+ balances: '/api/pump/balances',+ },},{ 'cache-control': 'public, max-age=300' },);diff --git a/public/skills-index.json b/public/skills-index.jsonindex 0a757ce24..d772a0803 100644--- a/public/skills-index.json+++ b/public/skills-index.json@@ -31,5 +31,14 @@"uri": "skills/dca/","author": "3d-agent","tags": ["defi", "uniswap", "metamask", "permissions"]+ },+ {+ "id": "pump-fun",+ "name": "Pump.fun Market Intel",+ "description": "Read-only Solana market intel: search tokens, inspect bonding curves, surface trending/new/graduated tokens, and flag rug-pull risk.",+ "version": "0.1.0",+ "uri": "skills/pump-fun/",+ "author": "3d-agent",+ "tags": ["solana", "pump.fun", "market-data", "mcp", "read-only"]}]diff --git a/src/agent-skills-pumpfun.js b/src/agent-skills-pumpfun.jsindex ea9265a41..5ba8430ec 100644--- a/src/agent-skills-pumpfun.js+++ b/src/agent-skills-pumpfun.js@@ -1,34 +1,52 @@/*** Pump.fun skills for Solana agents* ---------------------------------- * Wraps @nirholas/pump-sdk so an agent can launch its own coin, buy, sell,- * and report bonding-curve state through chat / MCP.- *- * Skills registered:- * - pumpfun-create → mint a new token whose metadata points at the agent- * - pumpfun-buy → buy on the bonding curve with SOL- * - pumpfun-sell → sell tokens back to the curve- * - pumpfun-status → market cap + graduation progress for a mint+ * Wraps the official @pump-fun SDKs so an agent can:+ * - launch a token (bonding curve) → pumpfun-create+ * - launch one auto-derived from identity → pumpfun-launch-from-agent+ * - trade on the curve → pumpfun-buy / pumpfun-sell+ * - trade on the AMM (post-graduation) → pumpfun-amm-buy / pumpfun-amm-sell+ * - read live curve state → pumpfun-status+ * - claim creator fees → pumpfun-claim-fees+ * - accept paid invocations → pumpfun-accept-payment** Wallet: uses the same injected Solana wallet as src/erc8004/solana-deploy.js* (Phantom / Backpack / Solflare). All txs are signed by the agent owner;* this module never holds keys.*- * SDK is loaded lazily so non-Solana agents don't pay the import cost.+ * SDKs are loaded lazily so non-Solana agents don't pay the import cost.*/import { detectSolanaWallet, SOLANA_RPC } from './erc8004/solana-deploy.js';const DEFAULT_NETWORK = 'mainnet';+const DEFAULT_SLIPPAGE_BPS = 500;++async function loadCore() {+ const [pump, web3, BN, splToken] = await Promise.all([+ import('@pump-fun/pump-sdk'),+ import('@solana/web3.js'),+ import('bn.js').then((m) => m.default || m),+ import('@solana/spl-token').catch(() => null),+ ]);+ return { pump, web3, BN, splToken };+}++async function loadAmm() {+ const [amm, web3, BN] = await Promise.all([+ import('@pump-fun/pump-swap-sdk'),+ import('@solana/web3.js'),+ import('bn.js').then((m) => m.default || m),+ ]);+ return { amm, web3, BN };+}-async function loadSdk() {- const [{ OnlinePumpSdk, PUMP_SDK, getBuyTokenAmountFromSolAmount }, web3, BN] =- await Promise.all([- import('@nirholas/pump-sdk'),- import('@solana/web3.js'),- import('bn.js').then((m) => m.default || m),- ]);- return { OnlinePumpSdk, PUMP_SDK, getBuyTokenAmountFromSolAmount, web3, BN };+async function loadAgentPayments() {+ const [pay, web3] = await Promise.all([+ import('@pump-fun/agent-payments-sdk'),+ import('@solana/web3.js'),+ ]);+ return { pay, web3 };}function getConnection(web3, network) {@@ -51,66 +69,94 @@ async function sendIxs({ web3, connection, wallet, payer, instructions, extraSigtx.add(...instructions);if (extraSigners.length) tx.partialSign(...extraSigners);const signed = await wallet.signTransaction(tx);- const sig = await connection.sendRawTransaction(signed.serialize(), {- skipPreflight: false,- });+ const sig = await connection.sendRawTransaction(signed.serialize(), { skipPreflight: false });await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight });return sig;}+function deriveSymbol(name) {+ return (+ String(name || 'AGENT')+ .toUpperCase()+ .replace(/[^A-Z0-9]/g, '')+ .slice(0, 10) || 'AGENT'+ );+}+/*** Register pump.fun skills onto an AgentSkills instance.* @param {import('./agent-skills.js').AgentSkills} skills*/export function registerPumpFunSkills(skills) {+ // ── pumpfun-create ────────────────────────────────────────────────────────skills.register({name: 'pumpfun-create',description:- 'Launch a pump.fun token on Solana whose metadata points at this agent. Returns the mint address and tx signature.',- instruction:- 'Mint a new pump.fun token. The agent owner signs. Name/symbol default to the agent identity.',+ 'Launch a pump.fun token on Solana. Owner signs. Returns mint address + tx signature.',+ instruction: 'Mint a new pump.fun token using the official @pump-fun/pump-sdk.',animationHint: 'celebrate',voicePattern: 'Launching {{symbol}} on pump.fun…',mcpExposed: true,inputSchema: {type: 'object',properties: {- name: { type: 'string', description: 'Token name (defaults to agent name)' },- symbol: { type: 'string', description: 'Ticker, ≤10 chars' },- uri: {- type: 'string',- description: 'Metadata JSON URI (Arweave/IPFS). Should reference the agent GLB + bio.',- },+ name: { type: 'string' },+ symbol: { type: 'string', description: '≤10 chars' },+ uri: { type: 'string', description: 'Metaplex metadata URI' },network: { type: 'string', enum: ['mainnet', 'devnet'] },+ initialBuySol: { type: 'number', description: 'Optional dev-buy in same tx (SOL)' },},required: ['symbol', 'uri'],},handler: async (args, ctx) => {const network = args.network || DEFAULT_NETWORK;const tokenName = args.name || ctx.identity?.name || 'Agent';- const symbol = String(args.symbol).toUpperCase().slice(0, 10);+ const symbol = deriveSymbol(args.symbol);- const { PUMP_SDK, web3 } = await loadSdk();+ const { pump, web3, BN } = await loadCore();const { wallet, pubkey } = await requireWallet();const connection = getConnection(web3, network);const mintKeypair = web3.Keypair.generate();- const createIx = await PUMP_SDK.createV2Instruction({- mint: mintKeypair.publicKey,- name: tokenName,- symbol,- uri: args.uri,- creator: pubkey,- user: pubkey,- mayhemMode: false,- });+ const offline = new pump.PumpSdk();+ let instructions;++ if (args.initialBuySol && args.initialBuySol > 0) {+ const onlineSdk = new pump.OnlinePumpSdk(connection);+ const global = await onlineSdk.fetchGlobal();+ const solLamports = new BN(Math.floor(args.initialBuySol * web3.LAMPORTS_PER_SOL));+ instructions = await offline.createV2AndBuyInstructions({+ global,+ mint: mintKeypair.publicKey,+ name: tokenName,+ symbol,+ uri: args.uri,+ creator: pubkey,+ user: pubkey,+ amount: new BN(0),+ solAmount: solLamports,+ mayhemMode: false,+ });+ } else {+ instructions = [+ await offline.createV2Instruction({+ mint: mintKeypair.publicKey,+ name: tokenName,+ symbol,+ uri: args.uri,+ creator: pubkey,+ user: pubkey,+ mayhemMode: false,+ }),+ ];+ }const sig = await sendIxs({web3,connection,wallet,payer: pubkey,- instructions: [createIx],+ instructions,extraSigners: [mintKeypair],});@@ -129,10 +175,54 @@ export function registerPumpFunSkills(skills) {},});+ // ── pumpfun-launch-from-agent ─────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-launch-from-agent',+ description:+ 'One-shot: launch a pump.fun token whose metadata is auto-generated from this agent (name, GLB, bio).',+ instruction: 'Resolves the agent metadata URL, then calls pumpfun-create.',+ animationHint: 'celebrate',+ voicePattern: 'Launching myself on pump.fun…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string' },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ initialBuySol: { type: 'number' },+ },+ },+ handler: async (args, ctx) => {+ const id = ctx.identity?.id;+ if (!id) {+ return {+ success: false,+ output: 'No agent identity. Register the agent first.',+ sentiment: -0.3,+ };+ }+ const origin = (typeof window !== 'undefined' && window.location?.origin) || '';+ const uri = `${origin}/api/agents/pumpfun-metadata?id=${encodeURIComponent(id)}`;+ const symbol = args.symbol || deriveSymbol(ctx.identity?.name);+ return skills.perform(+ 'pumpfun-create',+ {+ name: ctx.identity?.name,+ symbol,+ uri,+ network: args.network,+ initialBuySol: args.initialBuySol,+ },+ ctx,+ );+ },+ });++ // ── pumpfun-buy ───────────────────────────────────────────────────────────skills.register({name: 'pumpfun-buy',description: 'Buy a pump.fun token with SOL on the bonding curve.',- instruction: 'Buy tokens for the agent owner.',+ instruction: 'Bonding-curve buy. Reverts if the token has graduated — use pumpfun-amm-buy.',animationHint: 'gesture',voicePattern: 'Buying {{solAmount}} SOL of {{mint}}…',mcpExposed: true,@@ -140,35 +230,45 @@ export function registerPumpFunSkills(skills) {type: 'object',properties: {mint: { type: 'string' },- solAmount: { type: 'number', description: 'Amount of SOL to spend' },- slippageBps: { type: 'number', description: 'Slippage tolerance, bps (default 500)' },+ solAmount: { type: 'number' },+ slippageBps: { type: 'number' },network: { type: 'string', enum: ['mainnet', 'devnet'] },},required: ['mint', 'solAmount'],},handler: async (args, _ctx) => {const network = args.network || DEFAULT_NETWORK;- const slippageBps = args.slippageBps ?? 500;- const { OnlinePumpSdk, getBuyTokenAmountFromSolAmount, web3, BN } = await loadSdk();+ const slippageBps = args.slippageBps ?? DEFAULT_SLIPPAGE_BPS;+ const { pump, web3, BN } = await loadCore();const { wallet, pubkey } = await requireWallet();const connection = getConnection(web3, network);const mint = new web3.PublicKey(args.mint);- const sdk = new OnlinePumpSdk(connection);- const lamports = new BN(Math.floor(args.solAmount * web3.LAMPORTS_PER_SOL));+ const onlineSdk = new pump.OnlinePumpSdk(connection);+ const offline = new pump.PumpSdk();- const curve = await sdk.fetchBondingCurve(mint);- const expectedTokens = getBuyTokenAmountFromSolAmount({- bondingCurve: curve,- solAmount: lamports,+ const global = await onlineSdk.fetchGlobal();+ const state = await onlineSdk.fetchBuyState(mint, pubkey);+ const solLamports = new BN(Math.floor(args.solAmount * web3.LAMPORTS_PER_SOL));+ const expected = pump.getBuyTokenAmountFromSolAmount({+ global,+ feeConfig: null,+ mintSupply: state.bondingCurve.tokenTotalSupply,+ bondingCurve: state.bondingCurve,+ amount: solLamports,});- const buyIxs = await sdk.buyInstructions({+ const buyIxs = await offline.buyInstructions({+ global,+ bondingCurveAccountInfo: state.bondingCurveAccountInfo,+ bondingCurve: state.bondingCurve,+ associatedUserAccountInfo: state.associatedUserAccountInfo,mint,user: pubkey,- solAmount: lamports,- tokenAmount: expectedTokens,- slippageBps,+ amount: expected,+ solAmount: solLamports,+ slippage: slippageBps / 10_000,+ tokenProgram: web3.TOKEN_PROGRAM_ID || (await import('@solana/spl-token')).TOKEN_PROGRAM_ID,});const sig = await sendIxs({@@ -178,20 +278,20 @@ export function registerPumpFunSkills(skills) {payer: pubkey,instructions: buyIxs,});-return {success: true,- output: `Bought ~${expectedTokens.toString()} units of ${args.mint.slice(0, 8)}… for ${args.solAmount} SOL.`,+ output: `Bought ~${expected.toString()} units of ${args.mint.slice(0, 8)}… for ${args.solAmount} SOL.`,sentiment: 0.6,data: { signature: sig, mint: args.mint, solAmount: args.solAmount, network },};},});+ // ── pumpfun-sell ──────────────────────────────────────────────────────────skills.register({name: 'pumpfun-sell',description: 'Sell a pump.fun token back to the bonding curve for SOL.',- instruction: 'Sell tokens held by the agent owner.',+ instruction: 'Bonding-curve sell. Reverts if graduated — use pumpfun-amm-sell.',animationHint: 'gesture',voicePattern: 'Selling {{tokenAmount}} of {{mint}}…',mcpExposed: true,@@ -199,7 +299,7 @@ export function registerPumpFunSkills(skills) {type: 'object',properties: {mint: { type: 'string' },- tokenAmount: { type: 'string', description: 'Token amount as base-unit integer string' },+ tokenAmount: { type: 'string', description: 'Base-unit integer string' },slippageBps: { type: 'number' },network: { type: 'string', enum: ['mainnet', 'devnet'] },},@@ -207,20 +307,37 @@ export function registerPumpFunSkills(skills) {},handler: async (args, _ctx) => {const network = args.network || DEFAULT_NETWORK;- const slippageBps = args.slippageBps ?? 500;- const { OnlinePumpSdk, web3, BN } = await loadSdk();+ const slippageBps = args.slippageBps ?? DEFAULT_SLIPPAGE_BPS;+ const { pump, web3, BN } = await loadCore();const { wallet, pubkey } = await requireWallet();const connection = getConnection(web3, network);const mint = new web3.PublicKey(args.mint);- const sdk = new OnlinePumpSdk(connection);+ const onlineSdk = new pump.OnlinePumpSdk(connection);+ const offline = new pump.PumpSdk();+ const global = await onlineSdk.fetchGlobal();+ const state = await onlineSdk.fetchSellState(mint, pubkey);+const tokenAmount = new BN(args.tokenAmount);+ const expectedSol = pump.getSellSolAmountFromTokenAmount({+ global,+ feeConfig: null,+ mintSupply: state.bondingCurve.tokenTotalSupply,+ bondingCurve: state.bondingCurve,+ amount: tokenAmount,+ });- const sellIxs = await sdk.sellInstructions({+ const sellIxs = await offline.sellInstructions({+ global,+ bondingCurveAccountInfo: state.bondingCurveAccountInfo,+ bondingCurve: state.bondingCurve,mint,user: pubkey,- tokenAmount,- slippageBps,+ amount: tokenAmount,+ solAmount: expectedSol,+ slippage: slippageBps / 10_000,+ tokenProgram: (await import('@solana/spl-token')).TOKEN_PROGRAM_ID,+ mayhemMode: false,});const sig = await sendIxs({@@ -230,7 +347,6 @@ export function registerPumpFunSkills(skills) {payer: pubkey,instructions: sellIxs,});-return {success: true,output: `Sold ${args.tokenAmount} of ${args.mint.slice(0, 8)}…`,@@ -240,94 +356,276 @@ export function registerPumpFunSkills(skills) {},});+ // ── pumpfun-status ────────────────────────────────────────────────────────skills.register({- name: 'pumpfun-launch-from-agent',- description:- 'One-shot: launch a pump.fun token whose metadata is auto-generated from this agent (name, GLB, bio).',- instruction:- 'Resolves the agent metadata URL, then calls pumpfun-create. The agent owner signs the launch tx.',- animationHint: 'celebrate',- voicePattern: 'Launching myself on pump.fun…',+ name: 'pumpfun-status',+ description: 'Read live state for a pump.fun mint: market cap, graduation status.',+ instruction: 'Read-only. No wallet required.',+ animationHint: 'inspect',+ voicePattern: '{{mint}} status',mcpExposed: true,inputSchema: {type: 'object',properties: {- symbol: { type: 'string', description: 'Override symbol; defaults to derived from name' },+ mint: { type: 'string' },network: { type: 'string', enum: ['mainnet', 'devnet'] },},+ required: ['mint'],},- handler: async (args, ctx) => {- const id = ctx.identity?.id;- if (!id) {+ handler: async (args, _ctx) => {+ const network = args.network || DEFAULT_NETWORK;+ const { pump, web3 } = await loadCore();+ const connection = getConnection(web3, network);+ const onlineSdk = new pump.OnlinePumpSdk(connection);+ const mint = new web3.PublicKey(args.mint);++ const curve = await onlineSdk.fetchBondingCurve(mint);+ const global = await onlineSdk.fetchGlobal();+ const graduated = !!curve.complete;+ const marketCap = pump.bondingCurveMarketCap({+ global,+ bondingCurve: curve,+ });++ return {+ success: true,+ output: graduated+ ? `Graduated to AMM. Market cap ~${marketCap.toString()} lamports.`+ : `On bonding curve. Market cap ~${marketCap.toString()} lamports.`,+ sentiment: graduated ? 0.7 : 0.2,+ data: {+ mint: args.mint,+ marketCap: marketCap.toString(),+ graduated,+ network,+ },+ };+ },+ });++ // ── pumpfun-amm-buy ───────────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-amm-buy',+ description: 'Buy a graduated pump.fun token from the AMM pool with SOL.',+ instruction: 'AMM buy via @pump-fun/pump-swap-sdk. Use after graduation.',+ animationHint: 'gesture',+ voicePattern: 'AMM buy {{solAmount}} SOL of {{mint}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ mint: { type: 'string' },+ solAmount: { type: 'number' },+ slippageBps: { type: 'number' },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ },+ required: ['mint', 'solAmount'],+ },+ handler: async (args, _ctx) => {+ const network = args.network || DEFAULT_NETWORK;+ const slippage = (args.slippageBps ?? DEFAULT_SLIPPAGE_BPS) / 10_000;+ const { amm, web3, BN } = await loadAmm();+ const { wallet, pubkey } = await requireWallet();+ const connection = getConnection(web3, network);++ const mint = new web3.PublicKey(args.mint);+ const sdk = new amm.OnlinePumpAmmSdk(connection);+ const solLamports = new BN(Math.floor(args.solAmount * web3.LAMPORTS_PER_SOL));++ const ixs = await sdk.swapAutocompleteBaseFromQuote({+ pool: amm.canonicalPumpPoolPda(mint)[0],+ quote: solLamports,+ slippage,+ direction: 'quoteToBase',+ user: pubkey,+ });++ const sig = await sendIxs({+ web3,+ connection,+ wallet,+ payer: pubkey,+ instructions: Array.isArray(ixs) ? ixs : ixs.instructions || [],+ });++ return {+ success: true,+ output: `AMM-bought ${args.mint.slice(0, 8)}… for ${args.solAmount} SOL.`,+ sentiment: 0.6,+ data: { signature: sig, mint: args.mint, network },+ };+ },+ });++ // ── pumpfun-amm-sell ──────────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-amm-sell',+ description: 'Sell a graduated pump.fun token to the AMM pool for SOL.',+ instruction: 'AMM sell via @pump-fun/pump-swap-sdk.',+ animationHint: 'gesture',+ voicePattern: 'AMM sell {{tokenAmount}} of {{mint}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ mint: { type: 'string' },+ tokenAmount: { type: 'string' },+ slippageBps: { type: 'number' },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ },+ required: ['mint', 'tokenAmount'],+ },+ handler: async (args, _ctx) => {+ const network = args.network || DEFAULT_NETWORK;+ const slippage = (args.slippageBps ?? DEFAULT_SLIPPAGE_BPS) / 10_000;+ const { amm, web3, BN } = await loadAmm();+ const { wallet, pubkey } = await requireWallet();+ const connection = getConnection(web3, network);++ const mint = new web3.PublicKey(args.mint);+ const sdk = new amm.OnlinePumpAmmSdk(connection);+ const tokenAmount = new BN(args.tokenAmount);++ const ixs = await sdk.swapAutocompleteQuoteFromBase({+ pool: amm.canonicalPumpPoolPda(mint)[0],+ base: tokenAmount,+ slippage,+ direction: 'baseToQuote',+ user: pubkey,+ });++ const sig = await sendIxs({+ web3,+ connection,+ wallet,+ payer: pubkey,+ instructions: Array.isArray(ixs) ? ixs : ixs.instructions || [],+ });++ return {+ success: true,+ output: `AMM-sold ${args.tokenAmount} of ${args.mint.slice(0, 8)}…`,+ sentiment: 0.4,+ data: { signature: sig, mint: args.mint, network },+ };+ },+ });++ // ── pumpfun-claim-fees ────────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-claim-fees',+ description:+ 'Claim accumulated creator fees from the agent-creator vault to the agent owner wallet.',+ instruction: 'Calls collectCoinCreatorFeeInstructions on OnlinePumpSdk.',+ animationHint: 'celebrate',+ voicePattern: 'Claiming creator fees…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: { network: { type: 'string', enum: ['mainnet', 'devnet'] } },+ },+ handler: async (args, _ctx) => {+ const network = args.network || DEFAULT_NETWORK;+ const { pump, web3 } = await loadCore();+ const { wallet, pubkey } = await requireWallet();+ const connection = getConnection(web3, network);++ const onlineSdk = new pump.OnlinePumpSdk(connection);+ const balance = await onlineSdk.getCreatorVaultBalanceBothPrograms(pubkey);+ if (balance.isZero?.() || balance.toString() === '0') {return {- success: false,- output: 'No agent identity. Register the agent first.',- sentiment: -0.3,+ success: true,+ output: 'No creator fees to claim right now.',+ sentiment: 0.1,+ data: { lamports: '0' },};}- const origin =- (typeof window !== 'undefined' && window.location?.origin) || '';- const uri = `${origin}/api/agents/pumpfun-metadata?id=${encodeURIComponent(id)}`;-- const symbol =- args.symbol ||- String(ctx.identity?.name || 'AGENT')- .toUpperCase()- .replace(/[^A-Z0-9]/g, '')- .slice(0, 10) ||- 'AGENT';-- return skills.perform(- 'pumpfun-create',- {- name: ctx.identity?.name,- symbol,- uri,- network: args.network,- },- ctx,- );+ const ixs = await onlineSdk.collectCoinCreatorFeeInstructions(pubkey, pubkey);+ const sig = await sendIxs({+ web3,+ connection,+ wallet,+ payer: pubkey,+ instructions: ixs,+ });+ return {+ success: true,+ output: `Claimed ${balance.toString()} lamports of creator fees.`,+ sentiment: 0.8,+ data: { signature: sig, lamports: balance.toString(), network },+ };},});+ // ── pumpfun-accept-payment ────────────────────────────────────────────────skills.register({- name: 'pumpfun-status',+ name: 'pumpfun-accept-payment',description:- 'Read live bonding-curve state for a pump.fun mint: market cap, graduation progress.',- instruction: 'Read-only. Safe to call without a connected wallet.',- animationHint: 'inspect',- voicePattern: '{{symbol}} is at {{progress}}% to graduation.',+ 'Accept a paid invocation of this agent via @pump-fun/agent-payments-sdk. Splits revenue per the on-chain sharing config.',+ instruction:+ 'Builds an accept_payment tx for a fixed price in a given currency mint. Caller signs as `user`.',+ animationHint: 'gesture',+ voicePattern: 'Invoicing {{amount}} for service {{memo}}…',mcpExposed: true,inputSchema: {type: 'object',properties: {- mint: { type: 'string' },+ agentMint: {+ type: 'string',+ description: 'The agent token mint registered with PumpAgent',+ },+ currencyMint: {+ type: 'string',+ description: 'Currency mint (USDC, SOL wrapper, etc.)',+ },+ amount: { type: 'string', description: 'Amount in base units (string-encoded bigint)' },+ memo: { type: 'string', description: 'Invoice memo / nonce (uint)' },+ durationSeconds: { type: 'number', description: 'Validity window (default 600)' },network: { type: 'string', enum: ['mainnet', 'devnet'] },},- required: ['mint'],+ required: ['agentMint', 'currencyMint', 'amount', 'memo'],},handler: async (args, _ctx) => {const network = args.network || DEFAULT_NETWORK;- const { OnlinePumpSdk, web3 } = await loadSdk();+ const duration = args.durationSeconds ?? 600;+ const { pay, web3 } = await loadAgentPayments();+ const { wallet, pubkey } = await requireWallet();const connection = getConnection(web3, network);- const sdk = new OnlinePumpSdk(connection);- const summary = await sdk.fetchBondingCurveSummary(new web3.PublicKey(args.mint));- const progressPct = (summary.progressBps ?? 0) / 100;- const graduated = !!summary.isGraduated;+ const agentMint = new web3.PublicKey(args.agentMint);+ const currencyMint = new web3.PublicKey(args.currencyMint);+ const env = network === 'devnet' ? 'devnet' : 'mainnet-beta';++ const agent = new pay.PumpAgent(agentMint, env, connection);+ const now = Math.floor(Date.now() / 1000);+ const ixs = await agent.buildAcceptPaymentInstructions({+ user: pubkey,+ currencyMint,+ amount: args.amount,+ memo: args.memo,+ startTime: now,+ endTime: now + duration,+ });++ const sig = await sendIxs({+ web3,+ connection,+ wallet,+ payer: pubkey,+ instructions: ixs,+ });return {success: true,- output: graduated- ? `Graduated to AMM. Market cap ~${summary.marketCap?.toString()} lamports.`- : `${progressPct.toFixed(1)}% to graduation. Market cap ~${summary.marketCap?.toString()} lamports.`,- sentiment: graduated ? 0.7 : 0.2,+ output: `Payment of ${args.amount} accepted. Memo ${args.memo}.`,+ sentiment: 0.7,data: {- mint: args.mint,- marketCap: summary.marketCap?.toString(),- progressBps: summary.progressBps,- graduated,+ signature: sig,+ agentMint: args.agentMint,+ currencyMint: args.currencyMint,+ amount: args.amount,+ memo: args.memo,network,},};diff --git a/src/agent-skills.js b/src/agent-skills.jsindex f6e3cb246..eb26d1cd5 100644--- a/src/agent-skills.js+++ b/src/agent-skills.js@@ -13,6 +13,7 @@import { ACTION_TYPES } from './agent-protocol.js';import { MEMORY_TYPES } from './agent-memory.js';import { registerPumpFunSkills } from './agent-skills-pumpfun.js';+import { registerPumpFunWatchSkills } from './agent-skills-pumpfun-watch.js';/*** @typedef {Object} SkillContext@@ -55,6 +56,7 @@ export class AgentSkills {this._registerBuiltins();registerPumpFunSkills(this);+ registerPumpFunWatchSkills(this);}// ── Registry ──────────────────────────────────────────────────────────────diff --git a/src/erc8004/deploy-button.js b/src/erc8004/deploy-button.jsindex e3c842c0e..297e6a4c2 100644--- a/src/erc8004/deploy-button.js+++ b/src/erc8004/deploy-button.js@@ -124,6 +124,7 @@ export class DeployButton {const solanaOptionFor = (id) =>`<option value="${id}"${id === this._chainId ? ' selected' : ''}>${_esc(SOLANA_LABELS[id])}</option>`;+ const showVanity = _isSolana(this._chainId);this._root.innerHTML = `<div class="deploy-chain-row"><select class="deploy-chain-select" title="Choose chain to deploy to" aria-label="Target chain">@@ -135,13 +136,49 @@ export class DeployButton {⬢ Deploy on-chain</button></div>+ <div class="deploy-vanity-row" style="${showVanity ? '' : 'display:none'};margin-top:6px;font-size:12px;">+ <input class="deploy-vanity-input" type="text" maxlength="6" placeholder="Vanity prefix (optional)"+ title="Grind a Solana address that starts with these Base58 characters. 5+ chars requires a paid plan."+ aria-label="Vanity address prefix"+ style="font-family:monospace;width:14ch" />+ <span class="deploy-vanity-status" style="margin-left:8px;color:var(--muted,#888)"></span>+ </div>`;const select = this._root.querySelector('.deploy-chain-select');+ const vanityRow = this._root.querySelector('.deploy-vanity-row');+ const vanityInput = this._root.querySelector('.deploy-vanity-input');+ const vanityStatus = this._root.querySelector('.deploy-vanity-status');++ // Restore prior vanity value if user toggled chains.+ if (this._vanityPrefix) vanityInput.value = this._vanityPrefix;++ vanityInput.addEventListener('input', (ev) => {+ const raw = ev.target.value;+ this._vanityPrefix = raw;+ if (!raw) { vanityStatus.textContent = ''; return; }+ if (!/^[1-9A-HJ-NP-Za-km-z]+$/.test(raw)) {+ vanityStatus.textContent = 'invalid base58 char';+ vanityStatus.style.color = 'var(--danger,#c33)';+ return;+ }+ vanityStatus.style.color = '';+ // 58^n expected attempts; rough rate ~5k/s/core, assume 4 cores → ~20k/s.+ const attempts = Math.pow(58, raw.length);+ const seconds = attempts / 20000;+ const human = seconds < 1 ? '<1s'+ : seconds < 60 ? `~${Math.round(seconds)}s`+ : seconds < 3600 ? `~${Math.round(seconds / 60)}m`+ : `~${Math.round(seconds / 3600)}h`;+ const paid = raw.length >= 5 ? ' (paid plan)' : '';+ vanityStatus.textContent = `est. ${human}${paid}`;+ });+select.addEventListener('change', async (ev) => {const raw = ev.target.value;const newChainId = _isSolana(raw) ? raw : Number(raw);this._chainId = newChainId;+ vanityRow.style.display = _isSolana(newChainId) ? '' : 'none';if (!_isSolana(newChainId) && _hasWallet()) {select.disabled = true;try {diff --git a/src/erc8004/solana-deploy.js b/src/erc8004/solana-deploy.jsindex 28cdbbbeb..1328bb6b0 100644--- a/src/erc8004/solana-deploy.js+++ b/src/erc8004/solana-deploy.js@@ -12,7 +12,8 @@* returns 403 otherwise.*/-import { Connection, Transaction, VersionedTransaction } from '@solana/web3.js';+import { Connection, Keypair, Transaction, VersionedTransaction } from '@solana/web3.js';+import { grindVanity } from '../solana/vanity/grinder.js';/** Detect an injected Solana wallet (Phantom / Backpack / Solflare). */export function detectSolanaWallet() {@@ -55,9 +56,13 @@ function decodeBase64Tx(b64) {* @param {object} opts* @param {object} opts.agent Agent record. Required: id, name. Optional: avatarId, description.* @param {'mainnet'|'devnet'} opts.network- * @returns {Promise<{ assetPubkey: string, txSignature: string, network: string, agent: object }>}+ * @param {object} [opts.vanity] Optional vanity prefix config.+ * @param {string} [opts.vanity.prefix] Base58 prefix to grind.+ * @param {(p: { attempts: number, rate: number, eta: string }) => void} [opts.vanity.onProgress]+ * @param {AbortSignal} [opts.vanity.signal]+ * @returns {Promise<{ assetPubkey: string, txSignature: string, network: string, agent: object, vanityPrefix?: string }>}*/-export async function runSolanaDeploy({ agent, network }) {+export async function runSolanaDeploy({ agent, network, vanity }) {const wallet = detectSolanaWallet();if (!wallet) {const err = new Error('No Solana wallet detected. Install Phantom to continue.');@@ -69,6 +74,17 @@ export async function runSolanaDeploy({ agent, network }) {const walletAddress = (conn?.publicKey || wallet.publicKey)?.toString();if (!walletAddress) throw new Error('Could not read Solana wallet address.');+ // Optional: grind a vanity asset keypair before asking the server to build the tx.+ let vanityKeypair = null;+ if (vanity?.prefix) {+ const result = await grindVanity({+ prefix: vanity.prefix,+ onProgress: vanity.onProgress,+ signal: vanity.signal,+ });+ vanityKeypair = Keypair.fromSecretKey(result.secretKey);+ }+const prepResp = await fetch('/api/agents/solana-register-prep', {method: 'POST',credentials: 'include',@@ -79,6 +95,10 @@ export async function runSolanaDeploy({ agent, network }) {avatar_id: agent.avatarId || agent.avatar_id,wallet_address: walletAddress,network,+ ...(vanityKeypair ? {+ asset_pubkey: vanityKeypair.publicKey.toBase58(),+ vanity_prefix: vanity.prefix,+ } : {}),}),});if (!prepResp.ok) {@@ -93,6 +113,16 @@ export async function runSolanaDeploy({ agent, network }) {const prep = await prepResp.json();const tx = decodeBase64Tx(prep.tx_base64);+ // If we used a vanity keypair, the server built the tx with a noop signer+ // for the asset slot — we must fill it in here before the wallet signs.+ // VersionedTransaction.sign() only modifies signatures whose pubkey matches+ // a provided signer, so the wallet sig slot is preserved as zero for Phantom.+ if (vanityKeypair && tx instanceof VersionedTransaction) {+ tx.sign([vanityKeypair]);+ } else if (vanityKeypair && tx instanceof Transaction) {+ tx.partialSign(vanityKeypair);+ }+// Phantom + Backpack expose signAndSendTransaction; Solflare does too.const endpoint = RPC[network] || RPC.mainnet;let signature;@@ -140,5 +170,6 @@ export async function runSolanaDeploy({ agent, network }) {txSignature: signature,network,agent: confirmed.agent,+ ...(vanity?.prefix ? { vanityPrefix: vanity.prefix } : {}),};}