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(tokens): give an agent a saved, editable launch plan before it mints
nirholas75641382f3da
diff --git a/api/_lib/agent-token-plan.js b/api/_lib/agent-token-plan.jsnew file mode 100644index 000000000..5206c560c--- /dev/null+++ b/api/_lib/agent-token-plan.js@@ -0,0 +1,372 @@+// Agent token plans — the launch configuration bound to an agent record.+//+// An agent token is the economic object an agent becomes: one coin, on Solana,+// whose identity belongs to the agent rather than to whichever form the owner+// happened to fill in. This module owns that object end to end:+//+// - normalization of a submitted configuration (`normalizePlanInput`)+// - the readiness verdict that decides draft vs ready (`planReadiness`)+// - the launch cost estimate the owner sees before spending (`estimateLaunchCost`)+// - the DB accessors the API handlers use (get / upsert / markLaunched / delete)+//+// Everything above `getPlan` is pure so the rules are unit-testable without a+// database or a chain. Solana is the home chain: `network` is 'mainnet' or+// 'devnet' and nothing here has an EVM leg.+//+// The plan never spends. It is configuration plus a free proof lane (see the+// `plan-dry-run` action in api/agents/tokens/[action].js, which compiles and+// simulates the real launch instructions without broadcasting). The only writes+// that cost money live on the existing launch paths, which call+// `markPlanLaunched` once a real mint confirms.++import { sql } from './db.js';++/** Hard bounds, mirrored by the zod schema on the API and by the SQL checks. */+export const PLAN_LIMITS = {+ nameMax: 32,+ symbolMin: 2,+ symbolMax: 10,+ descriptionMax: 280,+ solBuyInMax: 50,+ usdcBuyInMax: 1_000_000,+ buybackBpsMax: 10_000,+};++export const COIN_TYPES = ['regular', 'mayhem', 'agent'];+export const QUOTE_CURRENCIES = ['sol', 'usdc'];+export const NETWORKS = ['mainnet', 'devnet'];++// Conservative upper bounds for a pump.fun create, in SOL. These are the rents+// and fees the launch transaction pays regardless of any dev buy: they are the+// same numbers the /api/agents/tokens/launch-quote endpoint quotes, exported+// from here so the quote and the plan can never disagree about what a launch+// costs.+export const FIXED_LAUNCH_COST_SOL = {+ mintRent: 0.00146,+ bondingCurveRent: 0.00203,+ metadataRent: 0.00561,+ txFee: 0.000005,+};++export const FIXED_LAUNCH_TOTAL_SOL =+ FIXED_LAUNCH_COST_SOL.mintRent ++ FIXED_LAUNCH_COST_SOL.bondingCurveRent ++ FIXED_LAUNCH_COST_SOL.metadataRent ++ FIXED_LAUNCH_COST_SOL.txFee;++// pump.fun takes ~1% of an initial buy as protocol fee.+const PROTOCOL_FEE_RATE = 0.01;++const str = (v) => (typeof v === 'string' ? v.trim() : '');+const num = (v) => {+ const n = typeof v === 'string' ? Number(v) : v;+ return Number.isFinite(n) ? n : 0;+};++/**+ * Normalize a submitted plan configuration into the exact shape the table+ * stores. Pure: no DB, no chain, no clock. Out-of-range numbers are clamped+ * rather than rejected so a slider that overshoots by a hair still saves; the+ * shape errors that matter (missing name/symbol, a symbol with punctuation in+ * it) are the readiness check's job, which reports them to the owner instead of+ * throwing them away.+ *+ * @param {object} raw+ * @returns {{+ * network: string, name: string, symbol: string, description: string,+ * image_url: string|null, website: string|null, twitter: string|null,+ * telegram: string|null, coin_type: string, quote_currency: string,+ * buyback_bps: number, sol_buy_in: number, usdc_buy_in: number+ * }}+ */+export function normalizePlanInput(raw = {}) {+ const network = NETWORKS.includes(raw.network) ? raw.network : 'mainnet';+ const coinType = COIN_TYPES.includes(raw.coin_type) ? raw.coin_type : 'agent';+ const quoteCurrency = QUOTE_CURRENCIES.includes(raw.quote_currency) ? raw.quote_currency : 'sol';++ const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));+ // A buyback share only means anything on an agent-bound coin: the on-chain+ // pump agent that enforces it is only created for coin_type 'agent'.+ const buybackBps = coinType === 'agent'+ ? Math.round(clamp(num(raw.buyback_bps), 0, PLAN_LIMITS.buybackBpsMax))+ : 0;++ // The dev buy is denominated in the quote currency. Carrying a stale amount+ // in the other currency would silently spend it if the owner flipped the+ // pairing back, so the inactive leg is zeroed at save time.+ const solBuyIn = quoteCurrency === 'sol'+ ? clamp(num(raw.sol_buy_in), 0, PLAN_LIMITS.solBuyInMax)+ : 0;+ const usdcBuyIn = quoteCurrency === 'usdc'+ ? clamp(num(raw.usdc_buy_in), 0, PLAN_LIMITS.usdcBuyInMax)+ : 0;++ const optional = (v) => str(v) || null;++ return {+ network,+ name: str(raw.name).slice(0, PLAN_LIMITS.nameMax),+ symbol: str(raw.symbol).toUpperCase().slice(0, PLAN_LIMITS.symbolMax),+ description: str(raw.description).slice(0, PLAN_LIMITS.descriptionMax),+ image_url: optional(raw.image_url ?? raw.image),+ website: optional(raw.website),+ twitter: optional(raw.twitter),+ telegram: optional(raw.telegram),+ coin_type: coinType,+ quote_currency: quoteCurrency,+ buyback_bps: buybackBps,+ sol_buy_in: solBuyIn,+ usdc_buy_in: usdcBuyIn,+ };+}++const HTTP_URL = /^https?:\/\/\S+$/i;+const SYMBOL_OK = /^[A-Z0-9]+$/;++/**+ * Is this configuration launchable, and if not, what exactly is missing?+ *+ * Readiness is reported, never enforced by deletion: a draft keeps every field+ * the owner already filled in and simply lists what remains. `blockers` are the+ * reasons a launch would fail or embarrass; `warnings` are things that will+ * work but that the owner probably did not intend.+ *+ * @param {object} plan A normalized plan (or a stored row).+ * @returns {{ ready: boolean, blockers: string[], warnings: string[] }}+ */+export function planReadiness(plan = {}) {+ const blockers = [];+ const warnings = [];++ const name = str(plan.name);+ const symbol = str(plan.symbol);++ if (!name) blockers.push('Give the coin a name.');+ else if (name.length > PLAN_LIMITS.nameMax) blockers.push(`Name must be ${PLAN_LIMITS.nameMax} characters or fewer.`);++ if (!symbol) blockers.push('Give the coin a ticker symbol.');+ else if (symbol.length < PLAN_LIMITS.symbolMin) blockers.push(`Symbol must be at least ${PLAN_LIMITS.symbolMin} characters.`);+ else if (symbol.length > PLAN_LIMITS.symbolMax) blockers.push(`Symbol must be ${PLAN_LIMITS.symbolMax} characters or fewer.`);+ else if (!SYMBOL_OK.test(symbol)) blockers.push('Symbol must be letters and digits only.');++ for (const [field, label] of [+ ['image_url', 'Image URL'],+ ['website', 'Website'],+ ['twitter', 'X profile'],+ ['telegram', 'Telegram'],+ ]) {+ const v = str(plan[field]);+ if (v && !HTTP_URL.test(v)) blockers.push(`${label} must be a full http(s) URL.`);+ }++ if (!str(plan.description)) warnings.push('No description: the coin page will show only the name and ticker.');+ if (!str(plan.image_url)) warnings.push('No image: the coin will launch without artwork.');++ if (plan.coin_type === 'agent' && num(plan.buyback_bps) === 0) {+ warnings.push('Buyback share is 0%: the agent will not buy back its own coin from what it earns.');+ }+ if (plan.coin_type !== 'agent' && num(plan.buyback_bps) > 0) {+ warnings.push('Buyback share is ignored: only an agent-bound coin can run buybacks.');+ }+ if (num(plan.sol_buy_in) === 0 && num(plan.usdc_buy_in) === 0) {+ warnings.push('No dev buy: the agent will not hold any of its own coin at launch.');+ }++ return { ready: blockers.length === 0, blockers, warnings };+}++/**+ * What this launch will cost, in SOL, broken out so the owner can see rent and+ * fees separately from the money that actually goes into the curve. A+ * USDC-paired dev buy moves no SOL, so it is reported on its own line and the+ * SOL total covers only rent + fees.+ *+ * @param {object} plan A normalized plan (or a stored row).+ * @returns {{+ * fixed: typeof FIXED_LAUNCH_COST_SOL, fixed_total_sol: number,+ * dev_buy_sol: number, protocol_fee_sol: number, total_sol: number,+ * dev_buy_usdc: number, quote_currency: string+ * }}+ */+export function estimateLaunchCost(plan = {}) {+ const quoteCurrency = QUOTE_CURRENCIES.includes(plan.quote_currency) ? plan.quote_currency : 'sol';+ const devBuySol = quoteCurrency === 'sol' ? Math.max(0, num(plan.sol_buy_in)) : 0;+ const devBuyUsdc = quoteCurrency === 'usdc' ? Math.max(0, num(plan.usdc_buy_in)) : 0;+ const protocolFeeSol = devBuySol * PROTOCOL_FEE_RATE;++ return {+ fixed: { ...FIXED_LAUNCH_COST_SOL },+ fixed_total_sol: FIXED_LAUNCH_TOTAL_SOL,+ dev_buy_sol: devBuySol,+ protocol_fee_sol: protocolFeeSol,+ total_sol: FIXED_LAUNCH_TOTAL_SOL + devBuySol + protocolFeeSol,+ dev_buy_usdc: devBuyUsdc,+ quote_currency: quoteCurrency,+ };+}++/**+ * Public JSON shape for a stored plan row. Numeric columns come back from+ * Postgres as strings, so they are coerced here once rather than at every+ * consumer. Readiness and the cost estimate are derived, never stored, so an+ * edit to the rules applies to plans saved before the rules changed.+ *+ * @param {object|null} row+ * @returns {object|null}+ */+export function shapePlan(row) {+ if (!row) return null;+ const plan = {+ id: row.id,+ agent_id: row.agent_id,+ network: row.network,+ name: row.name || '',+ symbol: row.symbol || '',+ description: row.description || '',+ image_url: row.image_url || null,+ website: row.website || null,+ twitter: row.twitter || null,+ telegram: row.telegram || null,+ coin_type: row.coin_type,+ quote_currency: row.quote_currency,+ buyback_bps: Number(row.buyback_bps) || 0,+ sol_buy_in: Number(row.sol_buy_in) || 0,+ usdc_buy_in: Number(row.usdc_buy_in) || 0,+ status: row.status,+ mint: row.mint || null,+ launched_at: row.launched_at || null,+ last_dry_run_at: row.last_dry_run_at || null,+ last_dry_run: row.last_dry_run || null,+ created_at: row.created_at || null,+ updated_at: row.updated_at || null,+ };+ return {+ ...plan,+ readiness: planReadiness(plan),+ cost_estimate: estimateLaunchCost(plan),+ };+}++// ── Storage ──────────────────────────────────────────────────────────────────++/**+ * The plan for one agent on one network, or null.+ * @param {{ agentId: string, network?: string }} o+ */+export async function getPlan({ agentId, network = 'mainnet' }) {+ if (!agentId) return null;+ const [row] = await sql`+ select * from agent_token_plans+ where agent_id = ${agentId} and network = ${network}+ limit 1+ `;+ return row || null;+}++/** Every plan an agent holds, newest-updated first (mainnet and devnet). */+export async function listPlansForAgent(agentId) {+ if (!agentId) return [];+ return sql`+ select * from agent_token_plans+ where agent_id = ${agentId}+ order by updated_at desc+ `;+}++/**+ * Create or replace the plan for (agent, network). A launched plan is immutable:+ * its configuration is what actually minted, so editing it would rewrite+ * history. The caller gets `{ locked: true }` back and nothing is written.+ *+ * @param {{ agentId: string, userId: string, input: object }} o+ * @returns {Promise<{ locked: boolean, row: object|null }>}+ */+export async function upsertPlan({ agentId, userId, input }) {+ const plan = normalizePlanInput(input);+ const { ready } = planReadiness(plan);+ const status = ready ? 'ready' : 'draft';++ const existing = await getPlan({ agentId, network: plan.network });+ if (existing && existing.status === 'launched') {+ return { locked: true, row: existing };+ }++ const [row] = await sql`+ insert into agent_token_plans+ (agent_id, user_id, network, name, symbol, description, image_url,+ website, twitter, telegram, coin_type, quote_currency, buyback_bps,+ sol_buy_in, usdc_buy_in, status)+ values+ (${agentId}, ${userId}, ${plan.network}, ${plan.name}, ${plan.symbol},+ ${plan.description}, ${plan.image_url}, ${plan.website}, ${plan.twitter},+ ${plan.telegram}, ${plan.coin_type}, ${plan.quote_currency},+ ${plan.buyback_bps}, ${plan.sol_buy_in}, ${plan.usdc_buy_in}, ${status})+ on conflict (agent_id, network) do update set+ name = excluded.name,+ symbol = excluded.symbol,+ description = excluded.description,+ image_url = excluded.image_url,+ website = excluded.website,+ twitter = excluded.twitter,+ telegram = excluded.telegram,+ coin_type = excluded.coin_type,+ quote_currency = excluded.quote_currency,+ buyback_bps = excluded.buyback_bps,+ sol_buy_in = excluded.sol_buy_in,+ usdc_buy_in = excluded.usdc_buy_in,+ status = excluded.status,+ updated_at = now()+ returning *+ `;+ return { locked: false, row: row || null };+}++/** Drop the plan for (agent, network). A launched plan is kept: it is a record. */+export async function deletePlan({ agentId, network = 'mainnet' }) {+ const rows = await sql`+ delete from agent_token_plans+ where agent_id = ${agentId} and network = ${network} and status <> 'launched'+ returning id+ `;+ return rows.length > 0;+}++/**+ * Record the free proof run against the plan, so the owner can see the last+ * verdict without re-running it.+ *+ * @param {{ agentId: string, network: string, result: object }} o+ */+export async function recordDryRun({ agentId, network, result }) {+ const [row] = await sql`+ update agent_token_plans+ set last_dry_run = ${JSON.stringify(result)}::jsonb,+ last_dry_run_at = now(),+ updated_at = now()+ where agent_id = ${agentId} and network = ${network}+ returning *+ `;+ return row || null;+}++/**+ * Bind a confirmed on-chain launch back to the plan it came from. Idempotent and+ * safe to call when no plan exists (the launch paths accept a launch configured+ * inline, without a saved plan) — it simply writes nothing and returns null.+ *+ * @param {{ agentId: string, network: string, mint: string }} o+ * @returns {Promise<object|null>} the launched plan row, or null+ */+export async function markPlanLaunched({ agentId, network, mint }) {+ if (!agentId || !mint || !NETWORKS.includes(network)) return null;+ const [row] = await sql`+ update agent_token_plans+ set status = 'launched',+ mint = ${mint},+ launched_at = now(),+ updated_at = now()+ where agent_id = ${agentId} and network = ${network} and status <> 'launched'+ returning *+ `;+ return row || null;+}diff --git a/api/agents/tokens/[action].js b/api/agents/tokens/[action].jsindex 25bacc59b..c23496aff 100644--- a/api/agents/tokens/[action].js+++ b/api/agents/tokens/[action].js@@ -1,13 +1,23 @@/*** Agent Tokens Dispatcher* ------------------------ * POST /api/agents/tokens/launch-prep- * POST /api/agents/tokens/launch-confirm- * GET /api/agents/tokens/launch-quote+ * GET /api/agents/tokens/plan read the agent's saved launch plan+ * PUT /api/agents/tokens/plan save it (owner only)+ * DELETE /api/agents/tokens/plan discard an unlaunched plan (owner only)+ * POST /api/agents/tokens/plan-dry-run compile + simulate the plan, no broadcast+ * POST /api/agents/tokens/launch-prep+ * POST /api/agents/tokens/launch-confirm+ * GET /api/agents/tokens/launch-quote** Single Vercel function that dispatches on req.query.action (auto-populated* from the [action] filename). Consolidated to reduce function count and* avoid bundling the heavy Pump.fun/Solana SDKs three times.+ *+ * The plan is the agent's token identity before it exists on chain: one saved,+ * editable configuration per (agent, network) that launch-prep reads instead of+ * re-collecting, that the profile renders while the coin is still unlaunched,+ * and that launch-confirm flips to 'launched' with the real mint. The rules live+ * in api/_lib/agent-token-plan.js; only the HTTP shell is here.*/import { z } from 'zod';@@ -15,7 +25,7 @@ import { solanaConnection } from '../../_lib/solana/connection.js';import { createHash } from 'crypto';import { sql } from '../../_lib/db.js';-import { getSessionUser } from '../../_lib/auth.js';+import { getSessionUser, isSameSiteOrigin } from '../../_lib/auth.js';import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { parse } from '../../_lib/validate.js';@@ -23,6 +33,21 @@ import { randomToken } from '../../_lib/crypto.js';import { env } from '../../_lib/env.js';import { r2, publicUrl } from '../../_lib/r2.js';import { buildTokenMetadata, agentHomeUrl } from '../../_lib/three-brand.js';+import { usdcMintFor } from '../../_lib/pump-quote.js';+import {+ getPlan,+ upsertPlan,+ deletePlan,+ recordDryRun,+ markPlanLaunched,+ shapePlan,+ planReadiness,+ estimateLaunchCost,+ normalizePlanInput,+ FIXED_LAUNCH_COST_SOL,+ FIXED_LAUNCH_TOTAL_SOL,+ PLAN_LIMITS,+} from '../../_lib/agent-token-plan.js';// Heavy SDKs (Solana web3, Pump.fun, AWS S3 commands) are dynamic-imported// inside the handlers that need them. Loading them at module top-level was@@ -52,6 +77,10 @@ function rpcUrl(cluster) {export default wrap(async (req, res) => {const action = req.query?.action;switch (action) {+ case 'plan':+ return handlePlan(req, res);+ case 'plan-dry-run':+ return handlePlanDryRun(req, res);case 'launch-prep':return handleLaunchPrep(req, res);case 'launch-confirm':@@ -63,6 +92,398 @@ export default wrap(async (req, res) => {}});+// ── plan ─────────────────────────────────────────────────────────────────────+//+// The launch configuration bound to the agent record. One plan per (agent,+// network). Reads are public for a plan the owner has finished ('ready') or+// already launched — an agent announcing the coin it is about to become is a+// product feature, and the launch history that follows renders from the same+// object. Drafts stay private to the owner: an unfinished ticker is not an+// announcement.++/**+ * Load an agent and decide whether the caller owns it. Returns null when the+ * agent does not exist or is deleted, so callers answer a single 404 for both.+ *+ * @returns {Promise<{ agent: object, isOwner: boolean, userId: string|null }|null>}+ */+async function loadAgentForPlan(req, agentId) {+ if (!agentId) return null;+ const [agent] = await sql`+ select id, name, user_id, wallet_address, meta+ from agent_identities+ where id = ${agentId} and deleted_at is null+ limit 1+ `;+ if (!agent) return null;+ const user = await getSessionUser(req);+ return { agent, isOwner: !!user && agent.user_id === user.id, userId: user?.id || null };+}++/** The Solana address a launch from this agent would pay and sign from. */+function agentLaunchWallet(agent) {+ const onchain = agent?.meta?.onchain;+ if (onchain?.family === 'solana' && onchain.wallet) return onchain.wallet;+ return agent?.meta?.solana_address || agent?.wallet_address || null;+}++const planSaveSchema = z.object({+ agent_id: z.string().uuid(),+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),+ name: z.string().trim().max(PLAN_LIMITS.nameMax).default(''),+ symbol: z.string().trim().max(PLAN_LIMITS.symbolMax).default(''),+ description: z.string().trim().max(PLAN_LIMITS.descriptionMax).default(''),+ image_url: z.string().trim().max(500).default(''),+ website: z.string().trim().max(500).default(''),+ twitter: z.string().trim().max(500).default(''),+ telegram: z.string().trim().max(500).default(''),+ coin_type: z.enum(['regular', 'mayhem', 'agent']).default('agent'),+ quote_currency: z.enum(['sol', 'usdc']).default('sol'),+ buyback_bps: z.coerce.number().int().min(0).max(PLAN_LIMITS.buybackBpsMax).default(0),+ sol_buy_in: z.coerce.number().min(0).max(PLAN_LIMITS.solBuyInMax).default(0),+ usdc_buy_in: z.coerce.number().min(0).max(PLAN_LIMITS.usdcBuyInMax).default(0),+});++async function handlePlan(req, res) {+ if (cors(req, res, { methods: 'GET,PUT,DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'PUT', 'DELETE'])) return;++ if (req.method === 'GET') return handlePlanRead(req, res);++ // Writes ride the session cookie, so a cross-site POST must never reach them.+ if (!isSameSiteOrigin(req)) return error(res, 403, 'forbidden', 'cross-site request blocked');++ 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 rateLimited(res, rl);++ if (req.method === 'DELETE') {+ const url = new URL(req.url, 'http://x');+ const agentId = url.searchParams.get('agent_id') || '';+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';+ const loaded = await loadAgentForPlan(req, agentId);+ if (!loaded) return error(res, 404, 'not_found', 'agent not found');+ if (!loaded.isOwner) return error(res, 403, 'forbidden', 'only the agent owner can edit its token plan');+ const removed = await deletePlan({ agentId, network });+ if (!removed) {+ return error(res, 409, 'conflict', 'no editable plan on this network — a launched plan is permanent');+ }+ return json(res, 200, { ok: true, agent_id: agentId, network, plan: null });+ }++ const body = parse(planSaveSchema, await readJson(req));+ const loaded = await loadAgentForPlan(req, body.agent_id);+ if (!loaded) return error(res, 404, 'not_found', 'agent not found');+ if (!loaded.isOwner) return error(res, 403, 'forbidden', 'only the agent owner can edit its token plan');++ const { locked, row } = await upsertPlan({ agentId: body.agent_id, userId: user.id, input: body });+ if (locked) {+ return error(+ res,+ 409,+ 'conflict',+ 'this agent already launched its token on this network — the plan that minted it is permanent',+ );+ }+ return json(res, 200, { ok: true, plan: shapePlan(row), is_owner: true });+}++async function handlePlanRead(req, res) {+ const rl = await limits.authedReadIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const agentId = url.searchParams.get('agent_id') || '';+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';+ if (!agentId) return error(res, 400, 'validation_error', 'agent_id is required');++ const loaded = await loadAgentForPlan(req, agentId);+ if (!loaded) return error(res, 404, 'not_found', 'agent not found');++ const row = await getPlan({ agentId, network });+ // A draft is the owner's private workbench; visitors see it as "no plan yet".+ const visible = row && (loaded.isOwner || row.status !== 'draft') ? row : null;++ return json(+ res,+ 200,+ {+ agent_id: agentId,+ network,+ is_owner: loaded.isOwner,+ launch_wallet: loaded.isOwner ? agentLaunchWallet(loaded.agent) : null,+ plan: shapePlan(visible),+ },+ // Ownership changes the body, so this must never land in a shared cache.+ { 'cache-control': 'private, no-store' },+ );+}++// ── plan-dry-run ─────────────────────────────────────────────────────────────+//+// The free proof path. It builds the SAME pump.fun create instructions the real+// launch builds from the SAME saved plan, compiles them into a real transaction+// against a real blockhash, and simulates that transaction on the cluster. It+// never signs and never broadcasts, so it costs nothing and mints nothing.+//+// Two verdicts come back, deliberately separate:+// compiled — the transaction built and fits Solana's 1232-byte packet limit.+// A plan whose name + ticker + metadata URI overflow fails here,+// which is the failure a real launch would otherwise hit at+// signing time with the owner's money already committed.+// simulation — the cluster executed it. `funding_required` is reported apart+// from a genuine program failure, because an unfunded devnet+// rehearsal wallet is a funding fact, not a broken plan.++const planDryRunSchema = z.object({+ agent_id: z.string().uuid(),+ // Devnet is the default: the proof lane should cost nothing and touch nothing+ // that trades. A mainnet dry run is still read-only, so it stays available.+ network: z.enum(['mainnet', 'devnet']).default('devnet'),+});++/** The metadata URI the real launch would carry, derived without pinning. */+function plannedMetadataUri(meta) {+ const bytes = Buffer.from(JSON.stringify(buildTokenMetadata(meta)), 'utf-8');+ const hash = createHash('sha256').update(bytes).digest('hex');+ return { uri: publicUrl(`tm/${hash.slice(0, 16)}.json`), bytes: bytes.length };+}++// Did the cluster reject this only because the payer cannot cover it?+function isFundingFailure(err, logs) {+ const blob = `${JSON.stringify(err ?? '')} ${(logs || []).join(' ')}`;+ return /AccountNotFound|InsufficientFundsForRent|insufficient lamports|insufficient funds|Attempt to debit an account but found no record/i.test(+ blob,+ );+}++async function handlePlanDryRun(req, res) {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;+ if (!isSameSiteOrigin(req)) return error(res, 403, 'forbidden', 'cross-site request blocked');++ 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 rateLimited(res, rl);++ const body = parse(planDryRunSchema, await readJson(req));+ const loaded = await loadAgentForPlan(req, body.agent_id);+ if (!loaded) return error(res, 404, 'not_found', 'agent not found');+ if (!loaded.isOwner) return error(res, 403, 'forbidden', 'only the agent owner can dry-run its token plan');++ const row = await getPlan({ agentId: body.agent_id, network: body.network });+ if (!row) {+ return error(+ res,+ 404,+ 'not_found',+ `no token plan saved for this agent on ${body.network} — save one first`,+ );+ }+ const plan = normalizePlanInput(row);+ const readiness = planReadiness(plan);+ if (!readiness.ready) {+ return json(res, 409, {+ ok: false,+ code: 'plan_not_ready',+ network: body.network,+ readiness,+ plan: shapePlan(row),+ });+ }++ const payerAddress = agentLaunchWallet(loaded.agent);+ if (!payerAddress) {+ return error(+ res,+ 409,+ 'precondition_failed',+ 'this agent has no Solana wallet yet — deploy it on Solana before rehearsing a launch',+ );+ }++ const result = await simulatePlanLaunch({ plan, agent: loaded.agent, payerAddress });+ const saved = await recordDryRun({ agentId: body.agent_id, network: body.network, result });++ return json(res, 200, {+ ok: true,+ broadcast: false,+ network: body.network,+ result,+ plan: shapePlan(saved || row),+ });+}++/**+ * Compile and simulate the plan's launch transaction. Never signs, never sends.+ *+ * @param {{ plan: object, agent: object, payerAddress: string }} o+ * @returns {Promise<object>} the dry-run result, safe to persist as JSON+ */+async function simulatePlanLaunch({ plan, agent, payerAddress }) {+ const { Keypair, PublicKey, TransactionMessage, VersionedTransaction, ComputeBudgetProgram } =+ await loadSolanaWeb3();+ const { PumpSdk, OnlinePumpSdk, getBuyTokenAmountFromSolAmount, BN, isLegacyQuoteMint } =+ await loadPumpSdk();++ const { uri: metadataUri, bytes: metadataBytes } = plannedMetadataUri({+ name: plan.name,+ symbol: plan.symbol,+ description: plan.description,+ image: plan.image_url || '',+ website: plan.website || '',+ twitter: plan.twitter || '',+ telegram: plan.telegram || '',+ agentUrl: agentHomeUrl(agent.id),+ creatorAddress: payerAddress,+ createdAt: new Date().toISOString(),+ });++ const conn = solanaConnection({ url: rpcUrl(plan.network), commitment: 'confirmed' });+ const onlineSdk = new OnlinePumpSdk(conn);+ const sdk = new PumpSdk();++ // Ephemeral: a launch mints a brand-new address every time, and this one is+ // discarded when the request ends. The rehearsal only needs an address of the+ // right shape for the instruction layout and the size measurement.+ const mintKeypair = Keypair.generate();+ const creator = new PublicKey(payerAddress);+ const quoteMint = plan.quote_currency === 'usdc' ? new PublicKey(usdcMintFor(plan.network)) : null;+ const isMayhem = plan.coin_type === 'mayhem';++ const ixs = [+ ComputeBudgetProgram.setComputeUnitLimit({ units: 350_000 }),+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 100_000 }),+ ];++ const createArgs = {+ mint: mintKeypair.publicKey,+ name: plan.name,+ symbol: plan.symbol,+ uri: metadataUri,+ creator,+ user: creator,+ mayhemMode: isMayhem,+ };++ if (quoteMint && !isLegacyQuoteMint(quoteMint)) {+ if (plan.usdc_buy_in > 0) {+ const global = await onlineSdk.fetchGlobal();+ const quoteAmount = new BN(Math.round(plan.usdc_buy_in * 1_000_000));+ const tokenAmount = getBuyTokenAmountFromSolAmount({+ global,+ feeConfig: null,+ mintSupply: null,+ bondingCurve: null,+ amount: quoteAmount,+ quoteMint,+ });+ const built = await sdk.createV2AndBuyV2Instructions({+ global,+ ...createArgs,+ quoteAmount,+ amount: tokenAmount,+ quoteMint,+ });+ ixs.push(...(Array.isArray(built) ? built : [built]));+ } else {+ ixs.push(await sdk.createV2Instruction({ ...createArgs, quoteMint }));+ }+ } else if (plan.sol_buy_in > 0) {+ const global = await onlineSdk.fetchGlobal();+ const solAmount = new BN(Math.floor(plan.sol_buy_in * 1_000_000_000));+ const tokenAmount = getBuyTokenAmountFromSolAmount({+ global,+ feeConfig: null,+ mintSupply: null,+ bondingCurve: null,+ amount: solAmount,+ });+ const built = await sdk.createV2AndBuyInstructions({+ global,+ ...createArgs,+ amount: tokenAmount,+ solAmount,+ });+ ixs.push(...(Array.isArray(built) ? built : [built]));+ } else {+ ixs.push(await sdk.createV2Instruction(createArgs));+ }++ const { blockhash } = await conn.getLatestBlockhash('confirmed');+ const message = new TransactionMessage({+ payerKey: creator,+ recentBlockhash: blockhash,+ instructions: ixs,+ }).compileToV0Message();+ const tx = new VersionedTransaction(message);++ // Structural proof: a transaction that cannot serialize is a launch that+ // would have died at signing time, and the byte count says by how much.+ let txBytes = null;+ let compileError = null;+ try {+ txBytes = tx.serialize().length;+ } catch (err) {+ compileError = /too large|overruns/i.test(err?.message || '')+ ? 'transaction exceeds Solana packet limits — shorten the coin name or the metadata'+ : err?.message || 'transaction failed to serialize';+ }++ const base = {+ checked_at: new Date().toISOString(),+ network: plan.network,+ payer: payerAddress,+ mint_preview: mintKeypair.publicKey.toBase58(),+ metadata_uri: metadataUri,+ metadata_bytes: metadataBytes,+ metadata_pinned: false,+ instruction_count: ixs.length,+ quote_currency: plan.quote_currency,+ cost_estimate: estimateLaunchCost(plan),+ compiled: compileError === null,+ tx_bytes: txBytes,+ compile_error: compileError,+ };+ if (compileError) return { ...base, verdict: 'compile_failed', simulation: null };++ // `sigVerify: false` because nothing is signed here — the point is to execute+ // the instructions, not to prove a signature. `replaceRecentBlockhash` keeps+ // the simulation valid even if the blockhash aged out between the two calls.+ let sim;+ try {+ sim = await conn.simulateTransaction(tx, {+ sigVerify: false,+ replaceRecentBlockhash: true,+ commitment: 'confirmed',+ });+ } catch (err) {+ return {+ ...base,+ verdict: 'rpc_unavailable',+ simulation: { error: err?.message || 'simulation RPC call failed', logs: [] },+ };+ }++ const value = sim?.value || {};+ const logs = Array.isArray(value.logs) ? value.logs.slice(-25) : [];+ const simulation = {+ error: value.err ? JSON.stringify(value.err) : null,+ units_consumed: value.unitsConsumed ?? null,+ logs,+ };+ if (!value.err) return { ...base, verdict: 'would_succeed', simulation };+ return {+ ...base,+ verdict: isFundingFailure(value.err, logs) ? 'funding_required' : 'would_fail',+ simulation,+ };+}+// ── launch-prep ──────────────────────────────────────────────────────────────const launchPrepSchema = z.object({@@ -86,8 +507,41 @@ const launchPrepSchema = z.object({twitter: z.string().url().or(z.literal('')).default(''),telegram: z.string().url().or(z.literal('')).default(''),initial_buy_sol: z.number().min(0).max(50).default(0),+ // When true, the coin identity comes from the agent's saved plan instead of+ // this body. Anything the caller does supply still wins, so the launch screen+ // can prefill from the plan and let the owner tweak one field at the last+ // moment without discarding the rest.+ use_plan: z.boolean().default(false),});+/**+ * Overlay the agent's saved plan under an inbound launch body. The body wins on+ * every field it actually carries; the plan fills the rest. Returns null when+ * the agent has no plan on this cluster.+ */+async function launchBodyFromPlan(raw, agentId) {+ const network = raw.cluster === 'devnet' ? 'devnet' : 'mainnet';+ const row = await getPlan({ agentId, network });+ if (!row) return null;+ const plan = normalizePlanInput(row);+ const pick = (bodyValue, planValue) =>+ bodyValue === undefined || bodyValue === null || bodyValue === '' ? planValue : bodyValue;+ return {+ ...raw,+ name: pick(raw.name, plan.name),+ symbol: pick(raw.symbol, plan.symbol),+ description: pick(raw.description, plan.description),+ image: pick(raw.image, plan.image_url || ''),+ website: pick(raw.website, plan.website || ''),+ twitter: pick(raw.twitter, plan.twitter || ''),+ telegram: pick(raw.telegram, plan.telegram || ''),+ // This path launches a SOL-paired coin from the user's own wallet, so only+ // the SOL dev buy applies; a USDC-paired plan launches from the agent+ // custodial path (/api/pump/launch-agent) instead.+ initial_buy_sol: pick(raw.initial_buy_sol, plan.sol_buy_in),+ };+}+async function pinTokenMetadata(meta) {const json = buildTokenMetadata(meta);const bytes = Buffer.from(JSON.stringify(json), 'utf-8');@@ -138,17 +592,37 @@ async function handleLaunchPrep(req, res) {const rl = await limits.authIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const body = parse(launchPrepSchema, await readJson(req));+ const raw = (await readJson(req)) || {};++ // Ownership resolves before anything reads the plan, so a signed-in stranger+ // can never probe another owner's unlaunched token configuration through+ // `use_plan`.+ const agentId = typeof raw.agent_id === 'string' ? raw.agent_id.trim() : '';+ if (!agentId) return error(res, 400, 'validation_error', 'agent_id is required');// Resolve agent + ownership + Solana deploy stateconst [agent] = await sql`select id, name, user_id, wallet_address, metafrom agent_identities- where id = ${body.agent_id} and user_id = ${user.id} and deleted_at is null+ where id = ${agentId} and user_id = ${user.id} and deleted_at is nulllimit 1`;if (!agent) return error(res, 404, 'not_found', 'agent not found');+ let source = raw;+ if (raw.use_plan === true) {+ source = await launchBodyFromPlan(raw, agentId);+ if (!source) {+ return error(+ res,+ 404,+ 'not_found',+ `no token plan saved for this agent on ${raw.cluster === 'devnet' ? 'devnet' : 'mainnet'} — save one first`,+ );+ }+ }+ const body = parse(launchPrepSchema, source);+const onchain = agent.meta?.onchain;if (!onchain || onchain.family !== 'solana') {return error(@@ -404,6 +878,33 @@ async function handleLaunchConfirm(req, res) {: {}),};+ // Register the launch BEFORE the agent record flips to "has a token". Both+ // writes below are idempotent, and this order means a failure here leaves the+ // agent unmarked so the same prep can simply be confirmed again — the reverse+ // order would strand a confirmed coin outside the launch directory forever,+ // with the retry rejected by the "already has a launched token" guard.+ //+ // pump_agent_mints is the platform's own launch directory: it is what powers+ // /launches, the agent profile's launch history, and GET /api/v1/pump/launches.+ // Coins launched from the user's wallet through this path used to be invisible+ // to all three because only the agent-custodial path (/api/pump/launch-agent)+ // ever wrote a row. buyback_bps is 0 here on purpose: this path creates no+ // on-chain pump agent, so claiming a buyback share would be claiming an+ // enforcement that does not exist.+ await sql`+ insert into pump_agent_mints+ (agent_id, user_id, network, mint, name, symbol, metadata_uri, agent_authority, buyback_bps)+ values+ (${agent.id}, ${user.id}, ${prep.cluster}, ${prep.mint}, ${prep.payload.name},+ ${prep.payload.symbol}, ${prep.metadata_uri}, ${body.wallet_address}, 0)+ on conflict (mint, network) do nothing+ `;+ const launchedPlan = await markPlanLaunched({+ agentId: agent.id,+ network: prep.cluster,+ mint: prep.mint,+ });+const mergedMeta = { ...(agent.meta || {}), token };const [updated] = await sql`update agent_identities@@ -418,6 +919,7 @@ async function handleLaunchConfirm(req, res) {return json(res, 201, {ok: true,agent: { ...updated, token, home_url: `${env.APP_ORIGIN}/agent/${updated.id}` },+ plan: shapePlan(launchedPlan),});}@@ -428,18 +930,12 @@ const launchQuoteSchema = z.object({cluster: z.enum(['mainnet', 'devnet']).default('mainnet'),});-// Conservative upper bounds, in SOL.-const FIXED_LAUNCH_COST = {- mintRent: 0.00146,- bondingCurveRent: 0.00203,- metadataRent: 0.00561,- txFee: 0.000005,-};-const FIXED_LAUNCH_TOTAL =- FIXED_LAUNCH_COST.mintRent +- FIXED_LAUNCH_COST.bondingCurveRent +- FIXED_LAUNCH_COST.metadataRent +- FIXED_LAUNCH_COST.txFee;+// Conservative upper bounds, in SOL. These live in api/_lib/agent-token-plan.js+// so this quote and the cost estimate a saved plan reports are the same numbers:+// an owner who reads "0.0091 SOL" on the plan card must be quoted the same thing+// at launch time.+const FIXED_LAUNCH_COST = FIXED_LAUNCH_COST_SOL;+const FIXED_LAUNCH_TOTAL = FIXED_LAUNCH_TOTAL_SOL;async function handleLaunchQuote(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;