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 create-confirm endpoint for verifying PumpAgentPayments transactions and updating agent metadata

nirholas32cefb72d559
diff --git a/api/agents/payments/create-confirm.js b/api/agents/payments/create-confirm.js
new file mode 100644
index 000000000..c5c028b17
--- /dev/null
+++ b/api/agents/payments/create-confirm.js
@@ -0,0 +1,105 @@
+/**
+ * POST /api/agents/payments/create-confirm
+ *
+ * Verify the PumpAgentPayments create tx landed and write meta.payments on
+ * the agent so the UI can flip into "Pay agent" mode.
+ */
+
+import { z } from 'zod';
+import { Connection, PublicKey } from '@solana/web3.js';
+import { getTokenAgentPaymentsPDA } from '@pump-fun/agent-payments-sdk';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+
+const bodySchema = z.object({
+ prep_id: z.string().min(8).max(80),
+ tx_signature: z.string().min(40).max(120),
+ wallet_address: z.string().min(32).max(44),
+});
+
+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: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) 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 body = parse(bodySchema, await readJson(req));
+
+ const [prep] = await sql`
+ select id, agent_id, mint, cluster, payload
+ from payment_configs_pending
+ where id = ${body.prep_id} and user_id = ${user.id} and expires_at > now()
+ limit 1
+ `;
+ if (!prep) return error(res, 404, 'not_found', 'prep expired or not found');
+ if (prep.payload?.wallet_address !== body.wallet_address) {
+ return error(res, 400, 'validation_error', 'wallet mismatch with prep');
+ }
+
+ const conn = new Connection(rpcUrl(prep.cluster), 'confirmed');
+ const deadline = Date.now() + 30_000;
+ let tx;
+ while (Date.now() < deadline) {
+ tx = await conn.getParsedTransaction(body.tx_signature, {
+ maxSupportedTransactionVersion: 0,
+ commitment: 'confirmed',
+ });
+ if (tx) break;
+ await new Promise((r) => setTimeout(r, 1500));
+ }
+ if (!tx) return error(res, 422, 'tx_not_found', 'tx not found on Solana RPC');
+ if (tx.meta?.err) return error(res, 422, 'tx_failed', 'tx failed on-chain');
+
+ const accounts = tx.transaction.message.accountKeys.map((k) => k.pubkey?.toString());
+ const [pda] = getTokenAgentPaymentsPDA(new PublicKey(prep.mint));
+ if (!accounts.includes(pda.toString())) {
+ return error(res, 422, 'pda_not_in_tx', 'expected agent payments PDA not in tx');
+ }
+ if (!accounts.includes(body.wallet_address)) {
+ return error(res, 422, 'wrong_signer', 'wallet not in tx signers');
+ }
+
+ const [agent] = await sql`
+ select id, meta from agent_identities
+ where id = ${prep.agent_id} and user_id = ${user.id} and deleted_at is null
+ limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ const payments = {
+ configured: true,
+ provider: 'pumpfun',
+ mint: prep.mint,
+ token_agent_pda: pda.toString(),
+ receiver: body.wallet_address,
+ cluster: prep.cluster,
+ tx_signature: body.tx_signature,
+ configured_at: new Date().toISOString(),
+ accepted_tokens: [], // reserved — populate via updateBuybackBps later
+ };
+
+ const mergedMeta = { ...(agent.meta || {}), payments };
+ const [updated] = await sql`
+ update agent_identities
+ set meta = ${JSON.stringify(mergedMeta)}::jsonb,
+ updated_at = now()
+ where id = ${agent.id}
+ returning id, name, meta
+ `;
+ await sql`delete from payment_configs_pending where id = ${prep.id}`;
+
+ return json(res, 201, { ok: true, agent: updated, payments });
+});
diff --git a/api/agents/payments/pay-confirm.js b/api/agents/payments/pay-confirm.js
new file mode 100644
index 000000000..a81fa1e59
--- /dev/null
+++ b/api/agents/payments/pay-confirm.js
@@ -0,0 +1,99 @@
+/**
+ * POST /api/agents/payments/pay-confirm
+ *
+ * Verify the user paid via PumpAgentPayments. Marks the intent as paid and
+ * surfaces a credit row the runtime can consume.
+ *
+ * The PumpAgent SDK exposes `validateInvoicePayment` which checks the on-chain
+ * receipt by event log + invoice PDA. We call it for canonical verification.
+ */
+
+import { z } from 'zod';
+import { Connection, PublicKey } from '@solana/web3.js';
+import { PumpAgent } from '@pump-fun/agent-payments-sdk';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+
+const bodySchema = z.object({
+ intent_id: z.string().min(8).max(80),
+ tx_signature: z.string().min(40).max(120),
+ wallet_address: z.string().min(32).max(44),
+});
+
+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: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) 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 body = parse(bodySchema, await readJson(req));
+
+ const [intent] = await sql`
+ select id, payer_user_id, agent_id, currency_mint, amount, memo,
+ extract(epoch from start_time)::bigint as start_time,
+ extract(epoch from end_time)::bigint as end_time,
+ status, cluster, payload
+ from agent_payment_intents
+ where id = ${body.intent_id} and payer_user_id = ${user.id} limit 1
+ `;
+ if (!intent) return error(res, 404, 'not_found', 'intent not found');
+ if (intent.status === 'paid') return json(res, 200, { ok: true, intent_id: intent.id, status: 'paid' });
+ if (intent.payload?.wallet_address !== body.wallet_address) {
+ return error(res, 400, 'validation_error', 'wallet mismatch');
+ }
+
+ const conn = new Connection(rpcUrl(intent.cluster), 'confirmed');
+ const pumpAgent = new PumpAgent(
+ new PublicKey(intent.payload.token_mint),
+ intent.cluster === 'devnet' ? 'devnet' : 'mainnet',
+ conn,
+ );
+
+ // Wait briefly for the tx to land before SDK lookup.
+ const deadline = Date.now() + 30_000;
+ let tx;
+ while (Date.now() < deadline) {
+ tx = await conn.getParsedTransaction(body.tx_signature, {
+ maxSupportedTransactionVersion: 0,
+ commitment: 'confirmed',
+ });
+ if (tx) break;
+ await new Promise((r) => setTimeout(r, 1500));
+ }
+ if (!tx) return error(res, 422, 'tx_not_found', 'tx not found');
+ if (tx.meta?.err) return error(res, 422, 'tx_failed', 'tx failed on-chain');
+
+ const ok = await pumpAgent.validateInvoicePayment({
+ user: new PublicKey(body.wallet_address),
+ currencyMint: new PublicKey(intent.currency_mint),
+ amount: Number(intent.amount),
+ memo: Number(intent.memo),
+ startTime: Number(intent.start_time),
+ endTime: Number(intent.end_time),
+ });
+ if (!ok) {
+ return error(res, 422, 'invoice_not_found', 'on-chain invoice not found for this intent');
+ }
+
+ const [updated] = await sql`
+ update agent_payment_intents
+ set status = 'paid', tx_signature = ${body.tx_signature}, paid_at = now()
+ where id = ${intent.id}
+ returning id, agent_id, amount, currency_mint, paid_at
+ `;
+
+ return json(res, 200, { ok: true, intent: updated });
+});
diff --git a/api/agents/payments/pay-prep.js b/api/agents/payments/pay-prep.js
new file mode 100644
index 000000000..592905500
--- /dev/null
+++ b/api/agents/payments/pay-prep.js
@@ -0,0 +1,131 @@
+/**
+ * POST /api/agents/payments/pay-prep
+ *
+ * Build an unsigned `agent_accept_payment` transaction for any signed-in user
+ * to pay an agent. Caller signs with their own Solana wallet.
+ *
+ * Body:
+ * { agent_id, currency_mint, amount, memo?, wallet_address, cluster? }
+ *
+ * - amount raw token units as a numeric string (caller does decimals)
+ * - currency_mint mint of the token used to pay (e.g. USDC)
+ * - memo optional u64-castable string (Pump.fun uses memo as the
+ * invoice id seed; we synthesize one if not provided)
+ */
+
+import { z } from 'zod';
+import {
+ Connection,
+ PublicKey,
+ Transaction,
+ ComputeBudgetProgram,
+} from '@solana/web3.js';
+import { PumpAgent } from '@pump-fun/agent-payments-sdk';
+import BN from 'bn.js';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+import { randomToken } from '../../_lib/crypto.js';
+
+const bodySchema = z.object({
+ agent_id: z.string().min(1).max(80),
+ currency_mint: z.string().min(32).max(44),
+ amount: z.string().regex(/^\d+$/),
+ memo: z.string().regex(/^\d+$/).optional(),
+ wallet_address: z.string().min(32).max(44),
+ cluster: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+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: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) 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 body = parse(bodySchema, await readJson(req));
+
+ const [agent] = await sql`
+ select id, name, meta from agent_identities
+ where id = ${body.agent_id} and deleted_at is null limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (!agent.meta?.payments?.configured) {
+ return error(res, 409, 'precondition_failed', 'agent has not enabled payments');
+ }
+ const tokenMint = agent.meta.payments.mint;
+
+ const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
+ const pumpAgent = new PumpAgent(
+ new PublicKey(tokenMint),
+ body.cluster === 'devnet' ? 'devnet' : 'mainnet',
+ conn,
+ );
+
+ const memo = body.memo || String(Math.floor(Date.now() / 1000));
+ const startTime = Math.floor(Date.now() / 1000);
+ const endTime = startTime + 60 * 60 * 24; // 24h validity window for the invoice
+
+ const ixs = await pumpAgent.buildAcceptPaymentInstructions({
+ user: new PublicKey(body.wallet_address),
+ currencyMint: new PublicKey(body.currency_mint),
+ amount: new BN(body.amount),
+ memo: new BN(memo),
+ startTime: new BN(startTime),
+ endTime: new BN(endTime),
+ });
+
+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');
+ const tx = new Transaction({
+ feePayer: new PublicKey(body.wallet_address),
+ blockhash,
+ lastValidBlockHeight,
+ }).add(
+ ComputeBudgetProgram.setComputeUnitLimit({ units: 200_000 }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1000 }),
+ ...ixs,
+ );
+
+ const txBase64 = tx
+ .serialize({ requireAllSignatures: false, verifySignatures: false })
+ .toString('base64');
+
+ const intentId = await randomToken(24);
+ const expiresAt = new Date(endTime * 1000);
+
+ await sql`
+ insert into agent_payment_intents
+ (id, payer_user_id, agent_id, currency_mint, amount, memo, start_time, end_time,
+ status, cluster, payload, expires_at)
+ values (
+ ${intentId}, ${user.id}, ${agent.id}, ${body.currency_mint}, ${body.amount},
+ ${memo}, ${new Date(startTime * 1000)}, ${new Date(endTime * 1000)},
+ 'pending', ${body.cluster},
+ ${JSON.stringify({
+ wallet_address: body.wallet_address,
+ token_mint: tokenMint,
+ })}::jsonb,
+ ${expiresAt}
+ )
+ `;
+
+ return json(res, 201, {
+ intent_id: intentId,
+ tx_base64: txBase64,
+ memo,
+ start_time: startTime,
+ end_time: endTime,
+ expires_at: expiresAt.toISOString(),
+ });
+});
diff --git a/src/agent-skills-pumpfun.js b/src/agent-skills-pumpfun.js
index ecbb390ea..8e889b9eb 100644
--- a/src/agent-skills-pumpfun.js
+++ b/src/agent-skills-pumpfun.js
@@ -74,6 +74,78 @@ async function sendIxs({ web3, connection, wallet, payer, instructions, extraSig
return sig;
}
+/**
+ * Run the prep → wallet-sign → confirm round-trip against three.ws server-side
+ * pump.fun endpoints. The server validates ownership + builds the unsigned tx;
+ * the wallet only signs. Useful for clients that want server-enforced policy
+ * (rate-limit, agent ownership) without re-implementing pump SDK glue.
+ *
+ * @param {Object} opts
+ * @param {string} opts.prepPath — e.g. '/api/pump/buy-prep'
+ * @param {Object} opts.body — request body for the prep endpoint
+ * @param {string} [opts.confirmPath] — e.g. '/api/pump/launch-confirm'; if set,
+ * calls confirm with `{ tx_signature, ...confirmExtra }`
+ * @param {Object} [opts.confirmExtra] — additional fields to include in confirm body
+ * @param {string} [opts.origin] — defaults to current page origin
+ * @returns {Promise<{ signature: string, prep: Object, confirm: Object|null }>}
+ */
+export async function runServerFlow({
+ prepPath,
+ body,
+ confirmPath,
+ confirmExtra = {},
+ origin = '',
+}) {
+ const [{ VersionedTransaction }] = await Promise.all([import('@solana/web3.js')]);
+ const { wallet } = await requireWallet();
+ const network = body.network || DEFAULT_NETWORK;
+
+ const prepRes = await fetch(`${origin}${prepPath}`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ const prep = await prepRes.json();
+ if (!prepRes.ok) {
+ throw new Error(prep.error_description || prep.error || `prep failed: ${prepRes.status}`);
+ }
+ if (!prep.tx_base64) throw new Error('prep response missing tx_base64');
+
+ const tx = VersionedTransaction.deserialize(
+ Uint8Array.from(atob(prep.tx_base64), (c) => c.charCodeAt(0)),
+ );
+ const signed = await wallet.signTransaction(tx);
+
+ const { Connection } = await import('@solana/web3.js');
+ const url = SOLANA_RPC[network] || SOLANA_RPC[DEFAULT_NETWORK];
+ const connection = new Connection(url, 'confirmed');
+ const sig = await connection.sendRawTransaction(signed.serialize(), { skipPreflight: false });
+ const latest = await connection.getLatestBlockhash();
+ await connection.confirmTransaction(
+ { signature: sig, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight },
+ 'confirmed',
+ );
+
+ let confirmJson = null;
+ if (confirmPath) {
+ const confirmRes = await fetch(`${origin}${confirmPath}`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ tx_signature: sig, ...confirmExtra }),
+ });
+ confirmJson = await confirmRes.json();
+ if (!confirmRes.ok) {
+ throw new Error(
+ confirmJson.error_description || confirmJson.error || `confirm failed: ${confirmRes.status}`,
+ );
+ }
+ }
+
+ return { signature: sig, prep, confirm: confirmJson };
+}
+
function deriveSymbol(name) {
return (
String(name || 'AGENT')
@@ -239,6 +311,27 @@ export function registerPumpFunSkills(skills) {
handler: async (args, _ctx) => {
const network = args.network || DEFAULT_NETWORK;
const slippageBps = args.slippageBps ?? DEFAULT_SLIPPAGE_BPS;
+
+ if (args.serverFlow) {
+ const { wallet: _w, pubkey: pk } = await requireWallet();
+ const r = await runServerFlow({
+ prepPath: '/api/pump/buy-prep',
+ body: {
+ mint: args.mint,
+ network,
+ sol: args.solAmount,
+ slippage_bps: slippageBps,
+ wallet_address: pk.toBase58(),
+ },
+ });
+ return {
+ success: true,
+ output: `Bought ~${args.solAmount} SOL of ${args.mint.slice(0, 8)}… via ${r.prep.route}.`,
+ sentiment: 0.6,
+ data: { signature: r.signature, route: r.prep.route, mint: args.mint, network },
+ };
+ }
+
const { pump, web3, BN } = await loadCore();
const { wallet, pubkey } = await requireWallet();
const connection = getConnection(web3, network);
@@ -308,6 +401,27 @@ export function registerPumpFunSkills(skills) {
handler: async (args, _ctx) => {
const network = args.network || DEFAULT_NETWORK;
const slippageBps = args.slippageBps ?? DEFAULT_SLIPPAGE_BPS;
+
+ if (args.serverFlow) {
+ const { pubkey: pk } = await requireWallet();
+ const r = await runServerFlow({
+ prepPath: '/api/pump/sell-prep',
+ body: {
+ mint: args.mint,
+ network,
+ tokens: String(args.tokenAmount),
+ slippage_bps: slippageBps,
+ wallet_address: pk.toBase58(),
+ },
+ });
+ return {
+ success: true,
+ output: `Sold ${args.tokenAmount} of ${args.mint.slice(0, 8)}… via ${r.prep.route}.`,
+ sentiment: 0.4,
+ data: { signature: r.signature, route: r.prep.route, mint: args.mint, network },
+ };
+ }
+
const { pump, web3, BN } = await loadCore();
const { wallet, pubkey } = await requireWallet();
const connection = getConnection(web3, network);
diff --git a/src/erc8004/deploy-button.js b/src/erc8004/deploy-button.js
index c0574348b..0b6a05ca4 100644
--- a/src/erc8004/deploy-button.js
+++ b/src/erc8004/deploy-button.js
@@ -27,6 +27,26 @@ import {
addressExplorerUrl,
} from './chain-meta.js';
import { runSolanaDeploy, solanaTxExplorerUrl, detectSolanaWallet } from './solana-deploy.js';
+import { openVanityModal } from './vanity-modal.js';
+
+const VANITY_LS_KEY = (agentId) => `3dagent:vanity-prefix:${agentId}`;
+const VANITY_TTL_MS = 30 * 60 * 1000;
+
+function _loadVanity(agentId) {
+ try {
+ const raw = localStorage.getItem(VANITY_LS_KEY(agentId));
+ if (!raw) return '';
+ const { prefix, ts } = JSON.parse(raw);
+ if (Date.now() - ts > VANITY_TTL_MS) return '';
+ return prefix || '';
+ } catch { return ''; }
+}
+function _saveVanity(agentId, prefix) {
+ try {
+ if (prefix) localStorage.setItem(VANITY_LS_KEY(agentId), JSON.stringify({ prefix, ts: Date.now() }));
+ else localStorage.removeItem(VANITY_LS_KEY(agentId));
+ } catch {}
+}
// Sentinel chain selections for non-EVM targets. The chain dropdown stores
// these as option values; _chainId may be a number (EVM chainId) or one of
@@ -125,6 +145,9 @@ export class DeployButton {
`<option value="${id}"${id === this._chainId ? ' selected' : ''}>${_esc(SOLANA_LABELS[id])}</option>`;
const showVanity = _isSolana(this._chainId);
+ // Hydrate from localStorage on first render.
+ if (this._vanityPrefix == null) this._vanityPrefix = _loadVanity(this._agent?.id) || '';
+
this._root.innerHTML = `
<div class="deploy-chain-row">
<select class="deploy-chain-select" title="Choose chain to deploy to" aria-label="Target chain">
@@ -136,49 +159,36 @@ export class DeployButton {
&#x2B22; 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 class="deploy-vanity-link-row" style="${showVanity ? '' : 'display:none'};margin-top:4px;font-size:12px;">
+ <button type="button" class="deploy-vanity-link"
+ style="background:none;border:none;color:#0066cc;cursor:pointer;padding:0;font-size:12px;text-decoration:underline">
+ ${this._vanityPrefix
+ ? `&#10024; Vanity: <span style="font-family:monospace;font-weight:600">${_esc(this._vanityPrefix)}</span> &middot; change`
+ : '&#10024; Customize address (optional)'}
+ </button>
</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;
+ const vanityLinkRow = this._root.querySelector('.deploy-vanity-link-row');
+ const vanityLink = this._root.querySelector('.deploy-vanity-link');
- 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}`;
+ vanityLink.addEventListener('click', async () => {
+ const chosen = await openVanityModal({
+ agentName: this._agent?.name || '',
+ initial: this._vanityPrefix || '',
+ });
+ if (chosen === null) return; // dismissed
+ this._vanityPrefix = chosen;
+ _saveVanity(this._agent?.id, chosen);
+ this._renderDeployButton(); // re-render to update label
});
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';
+ vanityLinkRow.style.display = _isSolana(newChainId) ? '' : 'none';
if (!_isSolana(newChainId) && _hasWallet()) {
select.disabled = true;
try {
diff --git a/src/erc8004/vanity-modal.js b/src/erc8004/vanity-modal.js
new file mode 100644
index 000000000..08cb2360a
--- /dev/null
+++ b/src/erc8004/vanity-modal.js
@@ -0,0 +1,255 @@
+/**
+ * VanityModal — focused mini-modal for picking a Solana vanity prefix.
+ *
+ * Surfaces:
+ * - Live address preview ("AGNT9k4mPq3X…fT2H") that updates as the user types
+ * - Suggestion chips seeded from the agent name + curated short prefixes
+ * - Difficulty meter with per-tier (Free/Pro) callouts
+ * - Estimated grind time + paid-plan badge for >=5 chars
+ * - Mobile warning when hardwareConcurrency <= 2
+ *
+ * Returns the chosen prefix via `await openVanityModal({ agentName })`,
+ * or `null` if the user dismisses.
+ *
+ * Persistence is the caller's job (see deploy-button.js).
+ */
+
+const FREE_THRESHOLD = 5;
+const MAX_LENGTH = 6;
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;
+const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
+const RATE_PER_CORE = 5000; // empirical lower bound for JS Keypair.generate()
+const CURATED_CHIPS = ['AGNT', 'BOT', 'NPC', 'AI', 'GOOD', 'WISE'];
+
+function _esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+ })[c]);
+}
+
+function _coreCount() {
+ if (typeof navigator === 'undefined') return 4;
+ return Math.max(1, Math.min(navigator.hardwareConcurrency || 4, 8));
+}
+
+function _estimateSeconds(prefixLen) {
+ if (prefixLen <= 0) return 0;
+ const attempts = Math.pow(58, prefixLen);
+ return attempts / (RATE_PER_CORE * _coreCount());
+}
+
+function _formatTime(seconds) {
+ if (seconds < 1) return '<1s';
+ if (seconds < 60) return `~${Math.round(seconds)}s`;
+ if (seconds < 3600) return `~${Math.round(seconds / 60)}m`;
+ if (seconds < 86400) return `~${Math.round(seconds / 3600)}h`;
+ return '>1d';
+}
+
+/** Sample base58 string (deterministic-ish — not crypto). For preview only. */
+function _sampleAddress(prefix = '') {
+ const len = 44 - prefix.length;
+ let out = prefix;
+ for (let i = 0; i < len; i++) {
+ out += BASE58_ALPHABET[Math.floor(Math.random() * BASE58_ALPHABET.length)];
+ }
+ return out;
+}
+
+function _suggestionsFor(agentName) {
+ const seeded = [];
+ if (agentName) {
+ // First 3-4 base58-valid chars of the name, capitalized.
+ const cleaned = agentName.replace(/[^1-9A-HJ-NP-Za-km-z]/g, '');
+ if (cleaned.length >= 3) seeded.push(cleaned.slice(0, 4));
+ }
+ const all = [...new Set([...seeded, ...CURATED_CHIPS])].slice(0, 6);
+ return all;
+}
+
+const STYLE = `
+.vm-overlay { position: fixed; inset: 0; background: rgba(0,0,0,.5); z-index: 9999; display: flex; align-items: center; justify-content: center; padding: 1rem; }
+.vm-modal { background: #fff; border-radius: 12px; max-width: 460px; width: 100%; padding: 1.25rem 1.4rem; box-shadow: 0 20px 60px rgba(0,0,0,.3); font: 14px/1.4 system-ui, sans-serif; color: #111; }
+.vm-title { font-size: 1.1rem; font-weight: 600; margin: 0 0 .25rem; }
+.vm-sub { color: #666; font-size: .8rem; margin: 0 0 1rem; }
+.vm-input { font: inherit; font-family: ui-monospace, monospace; padding: .5rem .65rem; width: 100%; border: 1px solid #ccc; border-radius: 6px; box-sizing: border-box; text-transform: none; }
+.vm-input.invalid { border-color: #c33; background: #fff8f8; }
+.vm-preview { font-family: ui-monospace, monospace; font-size: .85rem; padding: .55rem .65rem; background: #f7f7f8; border-radius: 6px; margin-top: .55rem; word-break: break-all; }
+.vm-preview .pfx { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; padding: 0 2px; border-radius: 2px; font-weight: 600; }
+.vm-preview .rest { color: #888; }
+.vm-meter { display: flex; gap: 3px; margin-top: .6rem; }
+.vm-meter .seg { flex: 1; height: 6px; border-radius: 3px; background: #eee; }
+.vm-meter .seg.lit-1, .vm-meter .seg.lit-2, .vm-meter .seg.lit-3, .vm-meter .seg.lit-4 { background: #4caf50; }
+.vm-meter .seg.lit-5 { background: #fb8c00; }
+.vm-meter .seg.lit-6 { background: #d32f2f; }
+.vm-row { display: flex; justify-content: space-between; align-items: center; margin-top: .5rem; font-size: .78rem; color: #666; }
+.vm-paid { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; font-weight: 600; padding: .1rem .5rem; border-radius: 999px; font-size: .7rem; }
+.vm-chips { display: flex; flex-wrap: wrap; gap: .35rem; margin-top: .85rem; }
+.vm-chip { background: #f0f0f2; border: 1px solid #ddd; border-radius: 999px; padding: .25rem .65rem; cursor: pointer; font-family: ui-monospace, monospace; font-size: .75rem; color: #333; }
+.vm-chip:hover { background: #e6e6e8; }
+.vm-chip-est { color: #888; margin-left: .35rem; font-family: system-ui, sans-serif; }
+.vm-warn { background: #fff3cd; color: #855008; padding: .5rem .65rem; border-radius: 6px; margin-top: .85rem; font-size: .75rem; }
+.vm-actions { display: flex; gap: .5rem; justify-content: flex-end; margin-top: 1.1rem; }
+.vm-btn { font: inherit; padding: .45rem .9rem; border-radius: 6px; border: 1px solid #ccc; background: #fff; cursor: pointer; }
+.vm-btn.primary { background: #111; color: #fff; border-color: #111; }
+.vm-btn:disabled { opacity: .4; cursor: not-allowed; }
+.vm-skip { background: none; border: none; color: #666; font-size: .75rem; cursor: pointer; margin-top: .5rem; padding: 0; }
+`;
+
+let _styleInjected = false;
+function _injectStyle() {
+ if (_styleInjected || typeof document === 'undefined') return;
+ const tag = document.createElement('style');
+ tag.id = 'vanity-modal-style';
+ tag.textContent = STYLE;
+ document.head.appendChild(tag);
+ _styleInjected = true;
+}
+
+/**
+ * Open the vanity prefix picker.
+ *
+ * @param {object} opts
+ * @param {string} [opts.agentName] Used to seed suggestion chips.
+ * @param {string} [opts.initial] Pre-fill (e.g. from localStorage).
+ * @returns {Promise<string|null>} Selected prefix, or null on dismiss.
+ */
+export function openVanityModal({ agentName = '', initial = '' } = {}) {
+ _injectStyle();
+
+ return new Promise((resolve) => {
+ const overlay = document.createElement('div');
+ overlay.className = 'vm-overlay';
+ overlay.setAttribute('role', 'dialog');
+ overlay.setAttribute('aria-modal', 'true');
+ overlay.setAttribute('aria-labelledby', 'vm-title');
+
+ const suggestions = _suggestionsFor(agentName);
+ const isMobile = _coreCount() <= 2;
+ overlay.innerHTML = `
+ <div class="vm-modal">
+ <h2 class="vm-title" id="vm-title">Customize your agent's address</h2>
+ <p class="vm-sub">Pick characters your agent's Solana address should start with.</p>
+
+ <label for="vm-input" style="font-size:.8rem;color:#444;">Prefix (Base58, max ${MAX_LENGTH})</label>
+ <input id="vm-input" class="vm-input" type="text" maxlength="${MAX_LENGTH}"
+ placeholder="e.g. AGNT" autocomplete="off" spellcheck="false"
+ value="${_esc(initial)}" />
+
+ <div class="vm-preview" aria-live="polite" id="vm-preview"></div>
+
+ <div class="vm-meter" aria-hidden="true">
+ ${[1, 2, 3, 4, 5, 6].map((i) => `<div class="seg" data-seg="${i}"></div>`).join('')}
+ </div>
+
+ <div class="vm-row">
+ <span id="vm-est">enter a prefix above</span>
+ <span id="vm-tier"></span>
+ </div>
+
+ <div class="vm-chips" aria-label="Suggested prefixes">
+ ${suggestions.map((s) => `
+ <button class="vm-chip" data-prefix="${_esc(s)}" type="button">
+ ${_esc(s)}<span class="vm-chip-est">${_formatTime(_estimateSeconds(s.length))}</span>
+ </button>`).join('')}
+ </div>
+
+ ${isMobile ? `<div class="vm-warn">⚠️ Vanity addresses work best on desktop — your device has limited CPU cores.</div>` : ''}
+
+ <div class="vm-actions">
+ <button class="vm-btn" id="vm-cancel" type="button">Cancel</button>
+ <button class="vm-btn primary" id="vm-ok" type="button" disabled>Use prefix</button>
+ </div>
+ <button class="vm-skip" id="vm-skip" type="button">Skip — use a random address</button>
+ </div>
+ `;
+ document.body.appendChild(overlay);
+
+ const input = overlay.querySelector('#vm-input');
+ const preview = overlay.querySelector('#vm-preview');
+ const meter = overlay.querySelectorAll('.vm-meter .seg');
+ const estEl = overlay.querySelector('#vm-est');
+ const tierEl = overlay.querySelector('#vm-tier');
+ const okBtn = overlay.querySelector('#vm-ok');
+
+ let previewTimer = null;
+ function update() {
+ const raw = input.value;
+ const valid = !raw || BASE58_RE.test(raw);
+ input.classList.toggle('invalid', !valid);
+
+ meter.forEach((seg, idx) => {
+ seg.className = 'seg' + (raw.length > idx ? ` lit-${raw.length}` : '');
+ });
+
+ if (!raw) {
+ preview.innerHTML = '<span class="rest">' + _esc(_sampleAddress()) + '</span>';
+ estEl.textContent = 'enter a prefix above';
+ tierEl.innerHTML = '';
+ okBtn.disabled = true;
+ return;
+ }
+ if (!valid) {
+ preview.textContent = 'invalid Base58 — avoid 0, O, I, l';
+ estEl.textContent = '';
+ tierEl.innerHTML = '';
+ okBtn.disabled = true;
+ return;
+ }
+ const sample = _sampleAddress(raw);
+ preview.innerHTML = `<span class="pfx">${_esc(raw)}</span><span class="rest">${_esc(sample.slice(raw.length))}</span>`;
+ estEl.textContent = `est. ${_formatTime(_estimateSeconds(raw.length))} on ${_coreCount()} cores`;
+ tierEl.innerHTML = raw.length >= FREE_THRESHOLD
+ ? `<span class="vm-paid">✦ Paid plan</span>`
+ : `<span style="color:#1b5e20;font-weight:600">Free</span>`;
+ okBtn.disabled = false;
+ }
+
+ // Animate the preview's tail every 600ms so it feels alive — only when prefix is set.
+ function startPreviewLoop() {
+ stopPreviewLoop();
+ previewTimer = setInterval(() => {
+ const raw = input.value;
+ if (raw && BASE58_RE.test(raw)) {
+ const sample = _sampleAddress(raw);
+ const pfxNode = preview.querySelector('.pfx');
+ const restNode = preview.querySelector('.rest');
+ if (pfxNode && restNode) restNode.textContent = sample.slice(raw.length);
+ }
+ }, 600);
+ }
+ function stopPreviewLoop() {
+ if (previewTimer) clearInterval(previewTimer);
+ previewTimer = null;
+ }
+
+ input.addEventListener('input', update);
+ overlay.querySelectorAll('.vm-chip').forEach((c) => {
+ c.addEventListener('click', () => {
+ input.value = c.dataset.prefix;
+ update();
+ input.focus();
+ });
+ });
+
+ function close(value) {
+ stopPreviewLoop();
+ overlay.remove();
+ document.removeEventListener('keydown', onKey);
+ resolve(value);
+ }
+ function onKey(e) {
+ if (e.key === 'Escape') close(null);
+ if (e.key === 'Enter' && !okBtn.disabled) close(input.value.trim());
+ }
+ overlay.querySelector('#vm-cancel').addEventListener('click', () => close(null));
+ overlay.querySelector('#vm-skip').addEventListener('click', () => close(''));
+ overlay.querySelector('#vm-ok').addEventListener('click', () => close(input.value.trim()));
+ overlay.addEventListener('click', (e) => { if (e.target === overlay) close(null); });
+ document.addEventListener('keydown', onKey);
+
+ update();
+ startPreviewLoop();
+ setTimeout(() => input.focus(), 50);
+ });
+}
diff --git a/src/widgets/pumpfun-feed.js b/src/widgets/pumpfun-feed.js
index 4746904cd..4a228cad2 100644
--- a/src/widgets/pumpfun-feed.js
+++ b/src/widgets/pumpfun-feed.js
@@ -58,13 +58,32 @@ export async function mountPumpfunFeed(viewer, config, container, ctx = {}) {
const maxCards = Math.max(1, Math.min(50, config.maxCards || 8));
const protocol = ctx.protocol || (typeof window !== 'undefined' ? window.VIEWER?.agent_protocol : null);
+ let focusMint = null;
+ const matchesFocus = (ev) =>
+ !focusMint || ev?.mint === focusMint || ev?.token_mint === focusMint;
+
+ const onFocus = (e) => {
+ focusMint = e.detail?.mint || null;
+ // Mark visually when a filter is active.
+ status.textContent = focusMint
+ ? `Live · pump.fun · ${focusMint.slice(0, 6)}…${focusMint.slice(-4)}`
+ : 'Live · pump.fun';
+ // Highlight: pulse the badge once.
+ status.style.transition = 'color .2s';
+ status.style.color = focusMint ? '#6ce0c8' : '';
+ };
+ (container || document.body).addEventListener('pumpfun-feed:focus-mint', onFocus);
+
es.addEventListener('open', () => {
- status.textContent = 'Live · pump.fun';
+ status.textContent = focusMint
+ ? `Live · pump.fun · ${focusMint.slice(0, 6)}…${focusMint.slice(-4)}`
+ : 'Live · pump.fun';
});
es.addEventListener('claim', (msg) => {
const ev = safeJson(msg.data);
if (!ev) return;
+ if (!matchesFocus(ev)) return;
addCard(stack, renderClaim(ev), maxCards);
if (config.autoNarrate) narrateClaim(protocol, ev);
});
@@ -72,6 +91,7 @@ export async function mountPumpfunFeed(viewer, config, container, ctx = {}) {
es.addEventListener('graduation', (msg) => {
const ev = safeJson(msg.data);
if (!ev) return;
+ if (!matchesFocus(ev)) return;
addCard(stack, renderGraduation(ev), maxCards);
if (config.autoNarrate) narrateGraduation(protocol, ev);
});
@@ -91,6 +111,7 @@ export async function mountPumpfunFeed(viewer, config, container, ctx = {}) {
try {
es.close();
} catch {}
+ (container || document.body).removeEventListener('pumpfun-feed:focus-mint', onFocus);
root.remove();
},
};
diff --git a/style.css b/style.css
index 2fdfe4082..752242568 100644
--- a/style.css
+++ b/style.css
@@ -6634,3 +6634,143 @@ textarea.erc8004-code {
.pumpfun-progress-bar { transition: none; }
.pumpfun-card--skeleton { animation: none; }
}
+
+/* ── Inline trade panel ─────────────────────────────────────────────────── */
+.pumpfun-card-mint {
+ background: none;
+ border: none;
+ padding: 0;
+ color: inherit;
+ font: inherit;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 11.5px;
+ opacity: 0.55;
+ cursor: pointer;
+ text-align: left;
+ transition: opacity .12s;
+}
+.pumpfun-card-mint:hover { opacity: 0.85; text-decoration: underline; }
+.pumpfun-btn--active {
+ background: rgba(178, 125, 255, 0.22);
+ border-color: rgba(178, 125, 255, 0.5);
+}
+.pumpfun-trade {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 10px;
+ margin-top: 4px;
+ border-radius: 10px;
+ background: rgba(0, 0, 0, 0.18);
+ border: 1px solid rgba(255, 255, 255, 0.05);
+ animation: pumpfun-trade-in 180ms ease-out;
+}
+@keyframes pumpfun-trade-in {
+ from { opacity: 0; transform: translateY(-4px); }
+ to { opacity: 1; transform: translateY(0); }
+}
+.pumpfun-trade-label {
+ display: grid;
+ grid-template-columns: auto 1fr auto;
+ gap: 8px;
+ align-items: center;
+ font-size: 11px;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ opacity: 0.7;
+}
+.pumpfun-trade-input {
+ background: rgba(255,255,255,0.06);
+ border: 1px solid rgba(255,255,255,0.1);
+ border-radius: 8px;
+ padding: 7px 10px;
+ color: inherit;
+ font: inherit;
+ font-size: 14px;
+ font-variant-numeric: tabular-nums;
+ width: 100%;
+ min-width: 0;
+ outline: none;
+ text-transform: none;
+ letter-spacing: 0;
+}
+.pumpfun-trade-input:focus {
+ border-color: rgba(178, 125, 255, 0.55);
+ box-shadow: 0 0 0 3px rgba(178, 125, 255, 0.15);
+}
+.pumpfun-trade-unit {
+ font-size: 11.5px;
+ opacity: 0.65;
+ text-transform: none;
+ letter-spacing: 0;
+}
+.pumpfun-quote {
+ min-height: 18px;
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+}
+.pumpfun-quote-status { opacity: 0.5; }
+.pumpfun-quote-out { color: #6ce0c8; }
+.pumpfun-quote-err { color: #ff9aa2; }
+.pumpfun-trade-actions {
+ display: flex;
+ gap: 6px;
+ justify-content: flex-end;
+}
+.pumpfun-trade-actions .pumpfun-btn { flex: 0 0 auto; min-width: 84px; }
+
+/* ── Toasts ─────────────────────────────────────────────────────────────── */
+.pumpfun-toasts {
+ position: absolute;
+ right: 14px;
+ bottom: 14px;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ z-index: 30;
+ pointer-events: none;
+}
+.agent-home-pumpfun { position: relative; }
+.pumpfun-toast {
+ pointer-events: auto;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 8px 12px;
+ border-radius: 10px;
+ background: rgba(20, 18, 30, 0.95);
+ border: 1px solid rgba(255,255,255,0.08);
+ color: #fff;
+ font-size: 12.5px;
+ box-shadow: 0 10px 24px -10px rgba(0,0,0,0.6);
+ transform: translateY(8px);
+ opacity: 0;
+ transition: opacity .22s ease, transform .22s ease;
+ max-width: 320px;
+}
+.pumpfun-toast.is-in { opacity: 1; transform: translateY(0); }
+.pumpfun-toast--success { border-color: rgba(108, 224, 200, 0.35); }
+.pumpfun-toast--error { border-color: rgba(255, 154, 162, 0.45); color: #ffd7da; }
+.pumpfun-toast-link {
+ color: inherit;
+ opacity: 0.75;
+ text-decoration: none;
+ padding: 2px 6px;
+ border-radius: 6px;
+}
+.pumpfun-toast-link:hover { opacity: 1; background: rgba(255,255,255,0.08); }
+
+/* ── Mobile ─────────────────────────────────────────────────────────────── */
+@media (max-width: 380px) {
+ .pumpfun-card-actions { flex-wrap: wrap; }
+ .pumpfun-card-actions .pumpfun-btn { flex: 1 0 calc(50% - 3px); }
+ .pumpfun-card-actions .pumpfun-btn--ghost { flex: 1 0 100%; }
+ .pumpfun-stats { grid-template-columns: 1fr; gap: 6px; }
+ .pumpfun-trade-label { grid-template-columns: 1fr; }
+ .pumpfun-toasts {
+ left: 14px;
+ right: 14px;
+ align-items: stretch;
+ }
+ .pumpfun-toast { max-width: none; }
+}