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
fix(pump): fit launches in one transaction with lookup tables or v1, and charge the disclosed launch fee
Nicholas8d4174e2e55d
diff --git a/api/_lib/execution-engine.js b/api/_lib/execution-engine.jsindex 77ab3ef60..2c990dbe5 100644--- a/api/_lib/execution-engine.js+++ b/api/_lib/execution-engine.js@@ -200,13 +200,13 @@ async function recentPrioritizationFee(connection) {// A REAL simulateTransaction of the trade instructions to read unitsConsumed,// padded 15% for the runtime drift between sim and land. Not cached (it depends on// the exact instruction set), but it's a single RPC call on the hot path.-async function estimateComputeUnits(connection, payer, instructions) {+async function estimateComputeUnits(connection, payer, instructions, lookupTables = []) {const { blockhash } = await connection.getLatestBlockhash('confirmed');const msg = new TransactionMessage({payerKey: payer.publicKey,recentBlockhash: blockhash,instructions,- }).compileToV0Message();+ }).compileToV0Message(lookupTables);const sim = await connection.simulateTransaction(new VersionedTransaction(msg), {sigVerify: false,replaceRecentBlockhash: true,@@ -422,6 +422,8 @@ async function sendProtected(signedTx, signature, connection, blockhashCtx, conf* @param {import('@solana/web3.js').Keypair[]} [o.opts.extraSigners=[]] co-signers* beyond the fee-payer (e.g. a new mint Keypair on a launch)* @param {number} [o.opts.confirmTimeoutMs=45000] protected-route confirm bound+ * @param {import('@solana/web3.js').AddressLookupTableAccount[]} [o.opts.addressLookupTables=[]]+ * tables to compile the v0 message against (a launch needs pump.fun's to fit)* @param {boolean} [o.opts.preSimulated=false] caller already simulated (firewall) — still estimates CU* @param {(tipLamports: bigint, route: string) => Promise<void>} [o.opts.onTip]* Spend-guard hook invoked BEFORE a tip is appended. Throw to veto the@@ -438,6 +440,7 @@ export async function submitProtected({ network, connection, payer, instructions// signature set. (Sim uses sigVerify:false, so it needs only the account metas// the instructions already carry, not these keypairs.)const extraSigners = Array.isArray(opts.extraSigners) ? opts.extraSigners : [];+ const lookupTables = Array.isArray(opts.addressLookupTables) ? opts.addressLookupTables : [];// Strip any caller-supplied ComputeBudget instructions: this engine sets its own// data-driven CU limit + escalating priority fee, and a SECOND ComputeBudget// instruction of the same kind makes the runtime reject the whole transaction.@@ -455,7 +458,7 @@ export async function submitProtected({ network, connection, payer, instructions// parallel — both are real RPC reads (fee cached, CU is a fresh simulate).const [priorityFeeBase, cuLimit] = await Promise.all([estimatePriorityFeeMicroLamports(connection, network),- estimateComputeUnits(connection, payer, userIxs),+ estimateComputeUnits(connection, payer, userIxs, lookupTables),]);const canJito = jitoEligible(network, tipMode);@@ -531,7 +534,7 @@ export async function submitProtected({ network, connection, payer, instructionspayerKey: payer.publicKey,recentBlockhash: blockhashCtx.blockhash,instructions: txIxs,- }).compileToV0Message();+ }).compileToV0Message(lookupTables);const tx = new VersionedTransaction(msg);tx.sign([payer, ...extraSigners]);const signature = bs58Sig(tx);diff --git a/api/_lib/pump-launch-tx.js b/api/_lib/pump-launch-tx.jsnew file mode 100644index 000000000..4b3df2bce--- /dev/null+++ b/api/_lib/pump-launch-tx.js@@ -0,0 +1,223 @@+// Transaction assembly for pump.fun coin launches.+//+// A launch is the biggest transaction three.ws asks a wallet to sign: the+// createV2 + dev-buy instructions alone measured 1,229 bytes against Solana's+// 1,232-byte legacy limit with a 32-char name (mainnet, 2026-09-16), so anything+// appended (the three.ws launch fee, a USDC-quote transfer) overflowed. Two+// tools keep every launch inside a packet:+//+// 1. pump.fun's published address lookup table. Compiling the v0 message+// against it replaces the repeated program/global/fee accounts with 1-byte+// indexes: the same SOL launch drops to 984 bytes, leaving room for the fee.+// 2. Solana transaction v1 (feature txv1aq4…, active on mainnet since slot+// 447,120,000). A 4,096-byte envelope with explicit resource limits. It has+// no lookup tables, but at 4 KB it fits every launch shape we build,+// including the USDC-quoted ones that overflow v0 even with the table.+//+// `buildLaunchTransaction` picks between them: v0 + lookup table when it fits+// (widest wallet support), v1 when the caller asked for it or when v0 overflows+// and the wallet advertised v1 signing. Mint co-signatures are applied here, so+// the browser only has to add the wallet's own signature.++import {+ AddressLookupTableAccount,+ PublicKey,+ TransactionMessage,+ VersionedTransaction,+} from '@solana/web3.js';+import { ed25519 } from '@noble/curves/ed25519.js';+import { getConnection } from './pump.js';+import { isRpcOutageError, rpcUnavailableError } from './rpc-degrade.js';+import {+ buildPartiallySignedV1Transaction,+ decodeFeatureActivationSlot,+ LEGACY_TRANSACTION_LIMIT,+ TX_V1_FEATURE_ADDRESS,+ V1_TRANSACTION_LIMIT,+} from './solana/transaction-v1.js';++// Published by pump.fun for its own create/trade transactions.+export const PUMP_LOOKUP_TABLES = Object.freeze({+ mainnet: '7mFD2mUtRS65XstiSAvCJuYmdesZoQwCwRJhq1p3eRMe',+ devnet: '7y3623xaVQzsLxHRyp1wQD4Pmer5JjgbaagGFAEqCjua',+});++// A simulated createV2 + dev buy + fee transfer consumed ~205k CU and loaded+// 14.4 MB of account data on mainnet. v1 carries these as hard caps (an unset+// cap is zero, not a default), so leave real headroom on both.+export const LAUNCH_V1_CONFIG = Object.freeze({+ computeUnitLimit: 400_000,+ loadedAccountsDataSizeLimit: 32 * 1024 * 1024,+ priorityFeeLamports: 10_000n,+});++const ALT_TTL_MS = 10 * 60_000;+const altCache = new Map(); // network -> { at, tables }++/**+ * The pump.fun lookup table(s) for a network. An RPC miss returns [] so a+ * launch degrades to an un-tabled v0 message instead of failing outright.+ * @returns {Promise<AddressLookupTableAccount[]>}+ */+export async function getPumpLookupTables({ network = 'mainnet' } = {}) {+ const hit = altCache.get(network);+ if (hit && Date.now() - hit.at < ALT_TTL_MS) return hit.tables;+ const key = PUMP_LOOKUP_TABLES[network];+ let tables = [];+ if (key) {+ try {+ const { value } = await getConnection({ network }).getAddressLookupTable(new PublicKey(key));+ if (value) tables = [new AddressLookupTableAccount({ key: value.key, state: value.state })];+ } catch (err) {+ console.warn('[pump-launch-tx] lookup table fetch failed', network, err?.message);+ }+ }+ altCache.set(network, { at: Date.now(), tables });+ return tables;+}++/**+ * The PumpAgent program rejects new agents: `create` fails with custom error+ * 6015 AgentInitializationNotSupported (simulated on mainnet 2026-09-16). Every+ * launch that appended it reverted, so the buyback binding is off unless an+ * operator confirms the program accepts it again and sets+ * PUMP_AGENT_INIT_ENABLED=1.+ */+export function pumpAgentBuybackAvailable() {+ const v = String(process.env.PUMP_AGENT_INIT_ENABLED || '').trim().toLowerCase();+ return v === '1' || v === 'true';+}++const v1StatusCache = new Map(); // network -> { at, status }+const V1_STATUS_TTL_MS = 5 * 60_000;++/**+ * Whether the transaction-v1 feature is active on a cluster, read from the+ * feature account itself rather than assumed.+ * @returns {Promise<{ active: boolean, activation_slot: number|null }>}+ */+export async function transactionV1Status({ network = 'mainnet' } = {}) {+ const hit = v1StatusCache.get(network);+ if (hit && Date.now() - hit.at < V1_STATUS_TTL_MS) return hit.status;+ let status = { active: false, activation_slot: null };+ try {+ const info = await getConnection({ network }).getAccountInfo(new PublicKey(TX_V1_FEATURE_ADDRESS));+ const slot = info ? decodeFeatureActivationSlot(info.data) : null;+ status = { active: slot != null, activation_slot: slot };+ } catch (err) {+ // Unknown is reported as inactive and not cached, so the next read retries.+ console.warn('[pump-launch-tx] v1 feature read failed', network, err?.message);+ return status;+ }+ v1StatusCache.set(network, { at: Date.now(), status });+ return status;+}++function launchTooLarge(message) {+ return Object.assign(new Error(message), { status: 413, code: 'launch_payload_too_large' });+}++function kitSigner(keypair) {+ const seed = keypair.secretKey.slice(0, 32);+ return {+ publicKey: keypair.publicKey.toBase58(),+ signMessage: async (bytes) => ed25519.sign(bytes, seed),+ };+}++async function latestBlockhash(connection) {+ try {+ return await connection.getLatestBlockhash('confirmed');+ } catch (err) {+ if (isRpcOutageError(err)) {+ throw rpcUnavailableError('could not fetch a recent blockhash: Solana RPC is temporarily unavailable', err);+ }+ throw err;+ }+}++/**+ * Compile a launch transaction for a browser wallet to sign.+ *+ * @param {object} o+ * @param {'mainnet'|'devnet'} o.network+ * @param {PublicKey} o.payer the wallet that signs and pays+ * @param {import('@solana/web3.js').TransactionInstruction[]} o.instructions+ * @param {'auto'|0|1} [o.transactionVersion] 'auto' = v0 when it fits, else v1+ * @param {boolean} [o.v1Capable] the wallet advertised v1 signing+ * @param {import('@solana/web3.js').Keypair[]} [o.signers] co-signers applied here (the mint)+ * @returns {Promise<{ tx_base64: string, transaction_version: 0|1, bytes: number, limit_bytes: number }>}+ */+export async function buildLaunchTransaction({+ network,+ payer,+ instructions,+ transactionVersion = 'auto',+ v1Capable = false,+ signers = [],+}) {+ const connection = getConnection({ network });+ const lifetime = await latestBlockhash(connection);++ if (transactionVersion !== 1) {+ const tables = await getPumpLookupTables({ network });+ try {+ const msg = new TransactionMessage({+ payerKey: payer,+ recentBlockhash: lifetime.blockhash,+ instructions,+ }).compileToV0Message(tables);+ const vtx = new VersionedTransaction(msg);+ if (signers.length) vtx.sign(signers);+ const bytes = vtx.serialize();+ if (bytes.length > LEGACY_TRANSACTION_LIMIT) throw new RangeError('over legacy limit');+ return {+ tx_base64: Buffer.from(bytes).toString('base64'),+ transaction_version: 0,+ bytes: bytes.length,+ limit_bytes: LEGACY_TRANSACTION_LIMIT,+ };+ } catch (err) {+ // web3.js reports an oversized message as a RangeError/"encoding+ // overruns" from its fixed 1,232-byte buffer. Anything else is real.+ const overflow = err instanceof RangeError || /overruns|too large|over legacy limit/i.test(err?.message || '');+ if (!overflow) throw err;+ if (transactionVersion === 0 || !v1Capable) {+ throw launchTooLarge(+ transactionVersion === 0+ ? 'this launch does not fit in a legacy transaction: switch the transaction format to v1, or drop the dev buy'+ : 'this launch needs a Solana transaction v1, which your wallet does not advertise: update the wallet, or launch SOL-paired',+ );+ }+ }+ }++ const { active } = await transactionV1Status({ network });+ if (!active) {+ throw Object.assign(new Error(`Solana transaction v1 is not active on ${network} yet`), {+ status: 409,+ code: 'tx_v1_inactive',+ });+ }+ let bytes;+ try {+ bytes = await buildPartiallySignedV1Transaction({+ instructions,+ signers: signers.map(kitSigner),+ feePayer: payer.toBase58(),+ lifetime,+ config: LAUNCH_V1_CONFIG,+ });+ } catch (err) {+ if (/size|limit|too large/i.test(err?.message || '')) {+ throw launchTooLarge('this launch exceeds even the 4,096-byte v1 envelope: shorten the name or metadata');+ }+ throw err;+ }+ return {+ tx_base64: Buffer.from(bytes).toString('base64'),+ transaction_version: 1,+ bytes: bytes.length,+ limit_bytes: V1_TRANSACTION_LIMIT,+ };+}diff --git a/api/_lib/pump-platform-fee.js b/api/_lib/pump-platform-fee.jsindex 7011b10a4..82457adff 100644--- a/api/_lib/pump-platform-fee.js+++ b/api/_lib/pump-platform-fee.js@@ -41,6 +41,21 @@ export function pumpPlatformFeeBps() {return Math.min(n, MAX_FEE_BPS);}+/**+ * The launch-fee rate in basis points: charged on the dev buy of a coin+ * launched through three.ws, on top of pump.fun's own fees. Defaults to 100+ * (1%), the rate the owner set for the launchpad; PUMP_LAUNCH_FEE_BPS=0 turns+ * it off. Clamped to [0, MAX_FEE_BPS]. Like the trade fee it only bills when a+ * recipient wallet resolves, and a launch with no dev buy pays nothing.+ * @returns {number}+ */+export function pumpLaunchFeeBps() {+ const raw = process.env.PUMP_LAUNCH_FEE_BPS;+ const n = raw == null || String(raw).trim() === '' ? 100 : parseInt(raw, 10);+ if (!Number.isFinite(n) || n < 0) return 0;+ return Math.min(n, MAX_FEE_BPS);+}+/*** The fee rate that will ACTUALLY be charged right now: the configured bps when* a recipient wallet is set, otherwise 0. Quote/UI surfaces use this so the@@ -114,6 +129,7 @@ export function pumpFeeAtomics(grossAtomics, bps = pumpPlatformFeeBps()) {* @param {PublicKey|string} [o.quoteMintPk] the quote mint (USDC trades)* @param {PublicKey} [o.quoteTokenProgram] the quote mint's token program* @param {bigint|number|string} o.grossAtomics quote spend (buy) / proceeds (sell)+ * @param {number} [o.bps] rate override (the launch fee); defaults to the trade fee* @returns {Promise<{ instructions: import('@solana/web3.js').TransactionInstruction[],* disclosure: { bps:number, asset:'SOL'|'USDC', amount:string, amount_ui:number,* recipient:string, basis:string } } | null>}@@ -126,8 +142,8 @@ export async function buildPlatformFeeInstructions({quoteTokenProgram,grossAtomics,basis = 'trade',+ bps = pumpPlatformFeeBps(),}) {- const bps = pumpPlatformFeeBps();const fee = pumpFeeAtomics(grossAtomics, bps);if (fee <= 0n) return null;@@ -182,4 +198,34 @@ export async function buildPlatformFeeInstructions({};}+/**+ * Did a confirmed, parsed transaction deliver a disclosed platform fee? Reads+ * the recipient's balance delta from the transaction's own meta (lamports for+ * SOL, the quote mint's token balance for SPL), so a transaction assembled+ * outside three.ws without the fee transfer is caught at confirm time.+ *+ * @param {object} tx getParsedTransaction result+ * @param {{ asset:'SOL'|'USDC', amount:string, recipient:string }} fee+ * @param {string} [quoteMint] the SPL quote mint for USDC fees+ * @returns {boolean}+ */+export function txPaidPlatformFee(tx, fee, quoteMint) {+ if (!fee) return true;+ const want = BigInt(fee.amount || '0');+ if (want <= 0n) return true;+ const meta = tx?.meta;+ if (!meta) return false;+ if (fee.asset === 'SOL') {+ const keys = tx.transaction.message.accountKeys.map((k) => String(k.pubkey || k));+ const i = keys.indexOf(fee.recipient);+ if (i < 0) return false;+ return BigInt(meta.postBalances[i] ?? 0) - BigInt(meta.preBalances[i] ?? 0) >= want;+ }+ const sum = (rows) =>+ (rows || [])+ .filter((b) => b.owner === fee.recipient && (!quoteMint || b.mint === quoteMint))+ .reduce((acc, b) => acc + BigInt(b.uiTokenAmount?.amount || '0'), 0n);+ return sum(meta.postTokenBalances) - sum(meta.preTokenBalances) >= want;+}+export { WSOL_MINT, MAX_FEE_BPS };diff --git a/api/pump/[action].js b/api/pump/[action].jsindex c707ecb72..fd6176b6e 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -70,7 +70,19 @@ import { publishFeedEvent } from '../_lib/feed.js';import { recordDailyActivity } from '../_lib/streaks.js';import { normalizeGatewayURL } from '../../src/ipfs.js';import { buildTokenMetadata } from '../_lib/three-brand.js';-import { buildPlatformFeeInstructions, effectivePumpFeeBps } from '../_lib/pump-platform-fee.js';+import {+ buildPlatformFeeInstructions,+ effectivePumpFeeBps,+ pumpFeeRecipient,+ pumpLaunchFeeBps,+ txPaidPlatformFee,+} from '../_lib/pump-platform-fee.js';+import {+ buildLaunchTransaction,+ getPumpLookupTables,+ pumpAgentBuybackAvailable,+ transactionV1Status,+} from '../_lib/pump-launch-tx.js';import { pinToIPFS, ipfsPinningConfigured } from '../_lib/ipfs-pin.js';import { THREE_WS_VANITY, hasThreeWsMark } from '../../src/solana/vanity/brand.js';import { grindVanityNode, GrindExhaustedError } from '../../src/solana/vanity/grinder-node.js';@@ -1274,6 +1286,11 @@ const launchPrepSchema = z// Pump SDK 2.0 holder-reward launch. Creator fees accrue to the// protocol-derived holder rewards PDA instead of a creator wallet.holder_reward: z.boolean().default(false),+ // Transaction format. 'auto' compiles v0 against pump.fun's lookup table and+ // only moves to the 4,096-byte v1 envelope when v0 overflows AND the wallet+ // advertised v1 signing (`v1_capable`). 0 or 1 pins the format.+ transaction_version: z.union([z.literal('auto'), z.literal(0), z.literal(1)]).default('auto'),+ v1_capable: z.boolean().default(false),// Optional Launch Copilot attach: a market-maker policy to arm on this coin// the moment it's confirmed (the success screen can also attach one after).// Validated + safety-gated by api/_lib/market-maker.js at confirm time.@@ -1416,7 +1433,11 @@ async function handleLaunchPrep(req, res) {// regular→ V1 path, no agent bindingconst isMayhem = body.coin_type === 'mayhem';const isAgent = body.coin_type === 'agent';- const effBuyback = isAgent ? body.buyback_bps : 0;+ // The PumpAgent program currently refuses new agents (see+ // pumpAgentBuybackAvailable), so an 'agent' coin launches without the+ // on-chain buyback binding instead of reverting the whole launch.+ const buybackAvailable = pumpAgentBuybackAvailable();+ const effBuyback = isAgent && buybackAvailable ? body.buyback_bps : 0;// Resolve the quote pairing: null → SOL-paired; an explicit mint (e.g. USDC)// → stable-paired so the agent's USDC buyback can swap+burn natively. The@@ -1460,13 +1481,33 @@ async function handleLaunchPrep(req, res) {instructions.push(createIx);}+ // three.ws launch fee: a disclosed share of the dev buy, paid by the signer in+ // the same transaction as the create. No dev buy, no fee.+ const launchFee = await buildPlatformFeeInstructions({+ network: body.network,+ payer: signer,+ isUsdc: quote.isUsdc,+ quoteMintPk: launchQuoteMint,+ grossAtomics: quote.isUsdc+ ? BigInt(Math.round((body.usdc_buy_in || 0) * 1_000_000))+ : BigInt(Math.floor((body.sol_buy_in || 0) * LAMPORTS_PER_SOL_LAUNCH)),+ basis: 'launch_dev_buy',+ bps: pumpLaunchFeeBps(),+ });+ if (launchFee) instructions.push(...launchFee.instructions);+// Signer pays gas + funds the initial buy. Creator stays on-chain as the- // reward recipient regardless of who paid.- const txBase64 = await buildUnsignedTxBase64({+ // reward recipient regardless of who paid. A server-ground mint co-signs+ // here so the browser only adds the wallet signature.+ const built = await buildLaunchTransaction({network: body.network,payer: signer,instructions,+ transactionVersion: body.transaction_version,+ v1Capable: body.v1_capable,+ signers: mintKeypair ? [mintKeypair] : [],});+ const txBase64 = built.tx_base64;const prepId = await randomToken(24);const expiresAt = new Date(Date.now() + 30 * 60 * 1000);@@ -1490,6 +1531,8 @@ async function handleLaunchPrep(req, res) {coin_type: body.coin_type,holder_reward: body.holder_reward,quote_mint: quote.quoteMint, // null = SOL-paired; else the stable quote mint+ platform_fee: launchFee ? launchFee.disclosure : null,+ transaction_version: built.transaction_version,prep_id: prepId,mm: body.mm || null, // optional Launch Copilot policy to arm on confirm})}::jsonb,@@ -1508,7 +1551,13 @@ async function handleLaunchPrep(req, res) {? Buffer.from(mintKeypair.secretKey).toString('base64'): null,client_supplied_mint: !mintKeypair,+ mint_presigned: !!mintKeypair,tx_base64: txBase64,+ transaction_version: built.transaction_version,+ tx_bytes: built.bytes,+ tx_limit_bytes: built.limit_bytes,+ platform_fee: launchFee ? launchFee.disclosure : null,+ buyback_available: buybackAvailable,network: body.network,buyback_bps: effBuyback,coin_type: body.coin_type,@@ -1517,7 +1566,7 @@ async function handleLaunchPrep(req, res) {quote_currency: quote.label,expires_at: expiresAt.toISOString(),instructions: mintKeypair- ? 'Decode tx_base64 as VersionedTransaction. Sign with the mint keypair (mint_secret_key_b64) AND the user wallet, submit, then POST /api/pump/launch-confirm with the tx_signature.'+ ? 'The mint keypair has already co-signed tx_base64. Have the user wallet sign it (a Wallet Standard signTransaction for transaction_version 1), submit, then POST /api/pump/launch-confirm with the tx_signature.': 'Decode tx_base64 as VersionedTransaction. Sign with your locally-held vanity mint keypair AND the user wallet, submit, then POST /api/pump/launch-confirm with the tx_signature.',});}@@ -1571,6 +1620,12 @@ async function handleLaunchConfirm(req, res) {if (!txInvokesPumpProgram(tx)) {return error(res, 422, 'not_a_pump_launch', 'transaction did not invoke the pump.fun program');}+ // The launch fee rode inside the transaction launch-prep built. A signature+ // for some other transaction (the same mint, minus the fee) is not a+ // three.ws launch and is not listed as one.+ if (!txPaidPlatformFee(tx, p.platform_fee, p.quote_mint || undefined)) {+ return error(res, 422, 'platform_fee_missing', 'transaction did not include the disclosed three.ws launch fee');+ }const [existing] = await sql`select id from pump_agent_mints where mint=${p.mint} and network=${p.network} limit 1@@ -1827,6 +1882,22 @@ async function handleLaunchAgent(req, res) {const quote = classifyLaunchQuote({ quoteMint: requestedQuoteMint, network: body.network });const launchQuoteMint = quote.quoteMint ? solanaPubkey(quote.quoteMint) : null;+ // three.ws launch fee on the dev buy, paid by the agent wallet in the launch+ // transaction itself. Built before the preflight so the balance check covers it.+ const launchFee = await buildPlatformFeeInstructions({+ network: body.network,+ payer: creator,+ isUsdc: quote.isUsdc,+ quoteMintPk: launchQuoteMint,+ grossAtomics: quote.isUsdc+ ? BigInt(Math.round((body.usdc_buy_in || 0) * 1_000_000))+ : BigInt(Math.floor((body.sol_buy_in || 0) * LAMPORTS_PER_SOL)),+ basis: 'launch_dev_buy',+ bps: pumpLaunchFeeBps(),+ });+ const feeLamports = launchFee && launchFee.disclosure.asset === 'SOL' ? Number(launchFee.disclosure.amount) : 0;+ const feeUsdcAtomics = launchFee && launchFee.disclosure.asset === 'USDC' ? BigInt(launchFee.disclosure.amount) : 0n;+// Pre-flight: make sure the agent wallet can afford the launch.const conn = solanaConnection(body.network);const PUMP_BASE_LAMPORTS = Math.floor(0.022 * LAMPORTS_PER_SOL);@@ -1836,7 +1907,7 @@ async function handleLaunchAgent(req, res) {const initialBuyLamports = quote.isUsdc? 0: Math.floor((body.sol_buy_in || 0) * LAMPORTS_PER_SOL);- const requiredLamports = PUMP_BASE_LAMPORTS + initialBuyLamports;+ const requiredLamports = PUMP_BASE_LAMPORTS + initialBuyLamports + feeLamports;let balanceLamports = 0;try {balanceLamports = await conn.getBalance(creator);@@ -1855,7 +1926,7 @@ async function handleLaunchAgent(req, res) {// USDC dev buy: the custodial wallet must hold the USDC it will spend, or the// create+buy reverts on-chain. Verify up front so it fails cleanly here.if (quote.isUsdc && body.usdc_buy_in > 0) {- const needAtomics = BigInt(Math.round(body.usdc_buy_in * 1_000_000));+ const needAtomics = BigInt(Math.round(body.usdc_buy_in * 1_000_000)) + feeUsdcAtomics;let haveAtomics = 0n;try {const { getAssociatedTokenAddressSync } = await import('@solana/spl-token');@@ -1879,7 +1950,8 @@ async function handleLaunchAgent(req, res) {const isMayhem = body.coin_type === 'mayhem';const isAgent = body.coin_type === 'agent';- const effBuyback = isAgent ? body.buyback_bps : 0;+ const buybackAvailable = pumpAgentBuybackAvailable();+ const effBuyback = isAgent && buybackAvailable ? body.buyback_bps : 0;const instructions = await buildLaunchInstructions({sdk,@@ -1906,6 +1978,7 @@ async function handleLaunchAgent(req, res) {});instructions.push(createIx);}+ if (launchFee) instructions.push(...launchFee.instructions);// Spend-policy gate: this path signs server-side with the agent's custodial// wallet, so a stolen session could otherwise drive an arbitrarily large SOL@@ -1914,7 +1987,7 @@ async function handleLaunchAgent(req, res) {// so concurrent launches can't both pass, and the launch is recorded toward// the daily cap. A USDC-paired dev buy moves no SOL (amount 0). Released on// send failure, finalized with the signature on success.- const launchSolOutflow = quote.isUsdc ? 0 : body.sol_buy_in || 0;+ const launchSolOutflow = (quote.isUsdc ? 0 : body.sol_buy_in || 0) + feeLamports / LAMPORTS_PER_SOL;const reservation = await reserveSpend({agentId: resolvedAgentId,meta: loaded.meta,@@ -1940,7 +2013,10 @@ async function handleLaunchAgent(req, res) {connection: conn,payer: agentKeypair,instructions,- opts: { extraSigners: [mintKeypair] },+ opts: {+ extraSigners: [mintKeypair],+ addressLookupTables: await getPumpLookupTables({ network: body.network }),+ },}));} catch (err) {await releaseSpend(reservation.reservationId);@@ -1986,6 +2062,7 @@ async function handleLaunchAgent(req, res) {buyback_bps: effBuyback,coin_type: body.coin_type,holder_reward: body.holder_reward,+ platform_fee: launchFee ? launchFee.disclosure : null,source: 'studio_agent_wallet',});@@ -2018,6 +2095,8 @@ async function handleLaunchAgent(req, res) {quote_mint: quote.quoteMint,quote_currency: quote.label,pump_agent_mint: row || null,+ platform_fee: launchFee ? launchFee.disclosure : null,+ buyback_available: buybackAvailable,explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,pumpfun_url: `https://pump.fun/coin/${mintAddr}`,});