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(launchpad): sweep creator fees held on the curve and pool before every claim
nirholas48fceb9a136b
diff --git a/api/_lib/coin/creator-fees.js b/api/_lib/coin/creator-fees.jsindex f41ed1611..c816fb5b6 100644--- a/api/_lib/coin/creator-fees.js+++ b/api/_lib/coin/creator-fees.js@@ -27,6 +27,7 @@ import { NATIVE_MINT, getAssociatedTokenAddressSync, createCloseAccountInstructiimport { getConnection, getPumpSdk, solanaPubkey } from '../pump.js';import { submitProtected } from '../execution-engine.js';+import { creatorFeeSweepInstructions, readCreatorFeeBuckets, unsweptCreatorFees } from '../pump-creator-fees.js';const PRIORITY_MICRO_LAMPORTS = 100_000;@@ -63,10 +64,20 @@ export async function claimCreatorFees({ coin, coinCreator, treasury }) {// robust against SDK version drift.const balanceBefore = BigInt(await connection.getBalance(creatorPk, 'confirmed'));- const ixs = await sdk.collectCoinCreatorFeeInstructions(creatorPk, treasuryPk);- if (!Array.isArray(ixs) || ixs.length === 0) {+ const collectIxs = await sdk.collectCoinCreatorFeeInstructions(creatorPk, treasuryPk);+ if (!Array.isArray(collectIxs) || collectIxs.length === 0) {return { tx_signature: null, claimed_lamports: 0n, was_empty: true };}+ // v3 / PumpSwap v2 trades leave the creator fee on the curve or in the pool+ // until it is swept into the vault: sweep this coin's SOL legs first so the+ // collect picks them up in the same transaction.+ const legs = coin.mint+ ? unsweptCreatorFees((await readCreatorFeeBuckets(connection, [coin.mint])).values(), creatorPk.toBase58()).filter(+ (l) => l.quoteMint === NATIVE_MINT.toBase58(),+ )+ : [];+ const { instructions: sweeps } = await creatorFeeSweepInstructions(connection, { legs, payer: treasuryPk });+ const ixs = [...sweeps, ...collectIxs];// Append close-account on the creator's WSOL ATA to unwrap any wSOL that// landed there during the AMM collect path. If the ATA doesn't exist ordiff --git a/api/_lib/creator-earnings-snapshot.js b/api/_lib/creator-earnings-snapshot.jsindex 2f20b9c07..95ab1539e 100644--- a/api/_lib/creator-earnings-snapshot.js+++ b/api/_lib/creator-earnings-snapshot.js@@ -112,7 +112,7 @@ async function refreshWallet(connection, creator, coins) {const walletCoins = coins.length;const walletAgents = new Set(coins.map((c) => c.agent_id).filter(Boolean)).size || 1;const [report, days, halfHours] = await Promise.all([- readCreatorFeeReport(connection, creator),+ readCreatorFeeReport(connection, creator, { mints: coins.map((c) => c.mint) }),fetchCreatorFeeBuckets(creator, '1d'),fetchCreatorFeeBuckets(creator, '30m'),]);diff --git a/api/_lib/pump-creator-fees.js b/api/_lib/pump-creator-fees.jsindex 5bb653b25..63ac9abd0 100644--- a/api/_lib/pump-creator-fees.js+++ b/api/_lib/pump-creator-fees.js@@ -25,7 +25,9 @@// three.ws has launched, so the page never showed a real figure.// unclaimed the creator vault balances read straight from the cluster// (pump bonding-curve vault plus the PumpSwap coin-creator vault),-// the exact lamports a claim would sweep right now.+// plus, when the caller names the wallet's coins, the fees v3 and+// PumpSwap v2 trades left on their curves and pools: the lamports+// a claim (which sweeps those buckets first) would collect now.// claimed earned minus unclaimed: every lamport the index says was// earned and the vault no longer holds was swept by a claim.//@@ -39,6 +41,18 @@import { PublicKey } from '@solana/web3.js';import { withBreaker } from './resilience.js';import { pumpFetchJson, PUMP_FRONTEND_BASE, PUMP_SWAP_BASE } from './pump-feed-fetch.js';+import { readCreatorFeeBuckets, sumByQuote, unsweptCreatorFees } from '../../src/solana/pump-creator-sweep.js';++// The bucket reads and sweep builders are chain-only and shared with the+// browser skills, so they live in src/solana/pump-creator-sweep.js.+export {+ MAX_SWEEPS_PER_TX,+ creatorExtraQuoteMints,+ creatorFeeSweepInstructions,+ readCreatorFeeBuckets,+ sumByQuote,+ unsweptCreatorFees,+} from '../../src/solana/pump-creator-sweep.js';export const CREATOR_FEES_BREAKER = 'pumpfun:creator-fees';// The fallback rung gets its own breaker so a sick primary cannot open it.@@ -160,36 +174,21 @@ export async function fetchCreatorFeeBuckets(wallet, interval) {}/**- * The on-chain fee recipient of each mint. Bonding curves are read in one- * batched RPC call per 100 mints; a graduated coin's recipient comes from its- * canonical PumpSwap pool. A mint whose curve cannot be read maps to null.+ * The on-chain fee recipient of each mint, read from the bonding curve, or from+ * the canonical PumpSwap pool once the coin graduated. A mint whose curve+ * cannot be read maps to null.** @param {import('@solana/web3.js').Connection} connection* @param {string[]} mints* @returns {Promise<Map<string, { creator: string, graduated: boolean } | null>>}*/export async function resolveCoinCreators(connection, mints) {- const [{ PumpSdk, bondingCurvePda, canonicalPumpPoolPda }, { OnlinePumpAmmSdk }] = await Promise.all([- import('@pump-fun/pump-sdk'),- import('@pump-fun/pump-swap-sdk'),- ]);- const offline = new PumpSdk();+ const buckets = await readCreatorFeeBuckets(connection, mints);/** @type {Map<string, { creator: string, graduated: boolean } | null>} */const out = new Map();- for (let i = 0; i < mints.length; i += 100) {- const chunk = mints.slice(i, i + 100);- const infos = await connection.getMultipleAccountsInfo(chunk.map((m) => bondingCurvePda(new PublicKey(m))));- chunk.forEach((mint, j) => {- const info = infos[j];- const curve = info ? offline.decodeBondingCurveNullable(info) : null;- out.set(mint, curve ? { creator: curve.creator.toBase58(), graduated: curve.complete === true } : null);- });- }- const amm = new OnlinePumpAmmSdk(connection);- for (const [mint, row] of out) {- if (!row?.graduated) continue;- const pool = await amm.fetchPool(canonicalPumpPoolPda(new PublicKey(mint))).catch(() => null);- if (pool?.coinCreator) row.creator = pool.coinCreator.toBase58();+ for (const mint of mints) {+ const b = buckets.get(mint);+ out.set(mint, b ? { creator: b.pool?.coinCreator ?? b.creator, graduated: b.complete } : null);}return out;}@@ -212,20 +211,48 @@ export async function readUnclaimedLamports(connection, wallet) {}}+/**+ * SOL creator fees still on `wallet`'s coins' curves and pools (not yet swept+ * into the vault), in lamports. Null when the cluster could not be read.+ * @param {import('@solana/web3.js').Connection} connection+ * @param {string} wallet+ * @param {string[]} mints+ * @returns {Promise<bigint | null>}+ */+export async function readUnsweptLamports(connection, wallet, mints) {+ if (!mints.length) return 0n;+ try {+ const legs = unsweptCreatorFees((await readCreatorFeeBuckets(connection, mints)).values(), wallet);+ const byQuote = sumByQuote(legs);+ let total = 0n;+ for (const [quote, amount] of byQuote) if (SOL_QUOTES.has(quote)) total += amount;+ return total;+ } catch {+ return null;+ }+}+/*** One wallet's full creator-fee report: lifetime total, unclaimed, derived* claimed. `ok: false` when pump.fun could not answer (the caller keeps its last* good figure). `unclaimed_lamports` is null when the cluster read failed; the* report is still good, claimed is then unknown.*+ * Pass the wallet's coins as `mints` so unclaimed also counts the fees v3 and+ * PumpSwap v2 trades left on their curves and pools: they are earned and not+ * yet collected, and without them every such lamport would read as claimed.+ ** @param {import('@solana/web3.js').Connection} connection* @param {string} wallet+ * @param {{ mints?: string[] }} [opts]*/-export async function readCreatorFeeReport(connection, wallet) {- const [total, unclaimed] = await Promise.all([+export async function readCreatorFeeReport(connection, wallet, { mints = [] } = {}) {+ const [total, vault, unswept] = await Promise.all([fetchCreatorFeeTotal(wallet),readUnclaimedLamports(connection, wallet),+ readUnsweptLamports(connection, wallet, mints),]);+ const unclaimed = vault == null || unswept == null ? null : vault + unswept;if (!total.ok) return { ok: false, error: total.error };const earned = total.value;// The index can lag a fresh trade by a few seconds while the vault is live, sodiff --git a/api/_lib/pump-launch-tx.js b/api/_lib/pump-launch-tx.jsindex 38c4388cd..4dfc29575 100644--- a/api/_lib/pump-launch-tx.js+++ b/api/_lib/pump-launch-tx.js@@ -77,6 +77,40 @@ export async function getPumpLookupTables({ network = 'mainnet' } = {}) {return tables;}+/**+ * How many of `prefix` (leading instructions that are worth sending but not+ * required, such as creator-fee sweeps in front of a collect) fit with `rest`+ * in one v0 legacy-size transaction compiled against `tables`. `reserveBytes`+ * holds room for what a sender appends later (compute-budget instructions, a+ * tip). Returns 0 when not even `rest` alone fits; the send then fails on its+ * own with the real size error.+ *+ * @param {object} o+ * @param {PublicKey} o.payer+ * @param {import('@solana/web3.js').TransactionInstruction[]} o.prefix+ * @param {import('@solana/web3.js').TransactionInstruction[]} o.rest+ * @param {AddressLookupTableAccount[]} [o.tables]+ * @param {number} [o.reserveBytes]+ * @param {number} [o.extraSigners] signatures beyond the payer's+ */+export function countPrefixThatFits({ payer, prefix, rest, tables = [], reserveBytes = 0, extraSigners = 0 }) {+ const limit = LEGACY_TRANSACTION_LIMIT - reserveBytes - extraSigners * 64;+ for (let n = prefix.length; n > 0; n--) {+ try {+ const msg = new TransactionMessage({+ payerKey: payer,+ recentBlockhash: PublicKey.default.toBase58(),+ instructions: [...prefix.slice(0, n), ...rest],+ }).compileToV0Message(tables);+ if (new VersionedTransaction(msg).serialize().length <= limit) return n;+ } catch (err) {+ const overflow = err instanceof RangeError || /overruns|too large/i.test(/** @type {any} */ (err)?.message || '');+ if (!overflow) throw err;+ }+ }+ return 0;+}+/*** The PumpAgent program rejects new agents: `create` fails with custom error* 6015 AgentInitializationNotSupported (simulated on mainnet 2026-09-16). Everydiff --git a/api/pump/[action].js b/api/pump/[action].jsindex d28996aa5..9ac825e6c 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -82,10 +82,18 @@ import {} from '../_lib/pump-platform-fee.js';import {buildLaunchTransaction,+ countPrefixThatFits,getPumpLookupTables,pumpAgentBuybackAvailable,transactionV1Status,} from '../_lib/pump-launch-tx.js';+import {+ creatorExtraQuoteMints,+ creatorFeeSweepInstructions,+ readCreatorFeeBuckets,+ sumByQuote,+ unsweptCreatorFees,+} from '../_lib/pump-creator-fees.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';@@ -4559,19 +4567,99 @@ const PUMP_QUOTE_LABELS = {'4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU': { symbol: 'USDC', decimals: 6 },};-async function creatorRewardBalances(connection, creator) {+// ── unswept creator fees ───────────────────────────────────────────────────+// v3 bonding-curve and v2 PumpSwap trades (pump-sdk 4.0) leave the creator fee+// on the curve or in the pool until a permissionless sweep moves it into the+// creator vault. Every claim below sweeps first, so it collects those fees in+// the same transaction, and every balance counts what is still waiting there.++const SOL_QUOTE_MINT = 'So11111111111111111111111111111111111111112';+// Room for the compute-budget instructions submitProtected adds to a send.+const PROTECTED_SEND_RESERVE_BYTES = 120;++// Coins a creator wallet launched through three.ws, plus any the caller named.+async function creatorCoinMints(creator, network, extra = []) {+ const rows = await sql`+ select mint from pump_agent_mints+ where agent_authority = ${creator} and network = ${network}+ order by created_at desc+ limit 500+ `;+ return [...new Set([...rows.map((r) => r.mint), ...extra])];+}++// Sweeps (largest first) and the extra quote mints for one creator's collect.+// A failed chain read degrades to a vault-only claim instead of no claim.+async function prepareCreatorSweeps(connection, { creator, mints, payer, solOnly }) {+ const empty = { sweeps: [], swept: [], legs: [], extraQuoteMints: [] };+ if (!mints.length) return empty;+ try {+ const buckets = await readCreatorFeeBuckets(connection, mints);+ const legs = unsweptCreatorFees(buckets.values(), creator).filter(+ (l) => !solOnly || l.quoteMint === SOL_QUOTE_MINT,+ );+ const { instructions, swept } = await creatorFeeSweepInstructions(connection, { legs, payer });+ return { sweeps: instructions, swept, legs, extraQuoteMints: creatorExtraQuoteMints(buckets.values(), creator) };+ } catch (e) {+ console.warn('[pump] creator-fee bucket read failed, collecting the vault only', creator, e?.message);+ return empty;+ }+}++// The first `count` swept legs, as the claim responses report them.+function sweptReport(swept, count) {+ return swept.slice(0, count).map((l) => ({+ mint: l.mint,+ source: l.source,+ quote_mint: l.quoteMint,+ amount: l.amount.toString(),+ }));+}++// Every nonzero creator-fee bucket on one coin, swept to whoever it belongs to:+// the programs refuse a distribution, CTO or fee-sharing change while one is+// nonzero (CreatorFeesNotSwept), so these go first in the same transaction.+async function coinSweepInstructions(connection, mintPk, payer) {+ const buckets = await readCreatorFeeBuckets(connection, [mintPk.toBase58()]);+ const { instructions } = await creatorFeeSweepInstructions(connection, {+ legs: unsweptCreatorFees(buckets.values()),+ payer,+ });+ return instructions;+}++// The quote mint and payer buildDistributeCreatorFeesInstructions needs: with+// the payer it also sweeps the pool bucket, with the quote mint it finds a+// token-quoted coin's pool and vaults instead of treating it as SOL.+async function distributeOptions(onlineSdk, mintPk, payer) {+ const { normalizeQuoteMint } = await import('@pump-fun/pump-sdk');+ const curve = await onlineSdk.fetchBondingCurve(mintPk).catch(() => null);+ return curve ? { payer, quoteMint: normalizeQuoteMint(curve.quoteMint) } : { payer };+}++// One creator's waiting rewards per quote mint: the vaults plus the fees still+// on that creator's curves and pools, which the claim sweeps in first.+async function creatorRewardBalances(connection, creator, buckets) {const { OnlinePumpSdk } = await import('@pump-fun/pump-sdk');- const rows = await new OnlinePumpSdk(connection).getCreatorVaultQuoteBalances(new PublicKey(creator));- return rows- .map((r) => {- const mint = r.mint.toBase58();+ const list = [...buckets.values()];+ const pending = sumByQuote(unsweptCreatorFees(list, creator));+ const rows = await new OnlinePumpSdk(connection).getCreatorVaultQuoteBalances(+ new PublicKey(creator),+ creatorExtraQuoteMints(list, creator),+ );+ const byMint = new Map(rows.map((r) => [r.mint.toBase58(), BigInt(r.total.toString())]));+ for (const mint of pending.keys()) if (!byMint.has(mint)) byMint.set(mint, 0n);+ return [...byMint.entries()]+ .map(([mint, vault]) => {const label = PUMP_QUOTE_LABELS[mint] || { symbol: `${mint.slice(0, 4)}…`, decimals: null };- const total = BigInt(r.total.toString());+ const unswept = pending.get(mint) || 0n;+ const total = vault + unswept;return {mint,symbol: label.symbol,amount: total.toString(),amount_ui: label.decimals == null ? null : Number(total) / 10 ** label.decimals,+ unswept: unswept.toString(),};}).filter((r) => r.amount !== '0');@@ -4657,10 +4745,17 @@ async function handleMyCoins(req, res) {}const connection = getConnection({ network });+ const claimMints = [...creators.values()].flatMap((g) => g.coins);+ const buckets = claimMints.length+ ? await readCreatorFeeBuckets(connection, claimMints).catch((e) => {+ console.warn('[pump/my-coins] fee bucket read failed', e?.message);+ return new Map();+ })+ : new Map();await Promise.all([...creators.values()].map(async (group) => {try {- group.rewards = await creatorRewardBalances(connection, group.address);+ group.rewards = await creatorRewardBalances(connection, group.address, buckets);} catch (e) {group.balance_error = isRpcOutageError(e) ? 'rpc_unavailable' : 'balance_read_failed';console.warn('[pump/my-coins] vault read failed', group.address, e?.message);@@ -4687,6 +4782,9 @@ const collectCreatorFeePrepSchema = z.object({// Sweep every quote mint (SOL plus USDC and any other listed quote) instead// of SOL alone, so a USDC-paired coin's rewards are claimable too.all_quotes: z.boolean().default(false),+ // Coins this creator made outside three.ws whose curve or pool fees should be+ // swept in too. Coins launched here are found from the launch records.+ mints: z.array(z.string().min(32).max(44)).max(50).default([]),transaction_version: z.union([z.literal('auto'), z.literal(0), z.literal(1)]).default('auto'),v1_capable: z.boolean().default(false),});@@ -4707,16 +4805,30 @@ async function handleCollectCreatorFeePrep(req, res) {if (!creatorPk || !feePayer) return error(res, 400, 'validation_error', 'invalid pubkeys');try {- const { sdk, connection } = await getPumpSdk({ network: body.network });+ const { connection } = await getPumpSdk({ network: body.network });const { OnlinePumpSdk } = await import('@pump-fun/pump-sdk');const onlineSdk = new OnlinePumpSdk(connection);+ const extraMints = body.mints.filter((m) => solanaPubkey(m));+ const prep = await prepareCreatorSweeps(connection, {+ creator: creatorPk.toBase58(),+ mints: await creatorCoinMints(creatorPk.toBase58(), body.network, extraMints),+ payer: feePayer,+ solOnly: !body.all_quotes,+ });const ixs = body.all_quotes- ? await onlineSdk.collectCoinCreatorFeeAllQuotesInstructions(creatorPk, feePayer)+ ? await onlineSdk.collectCoinCreatorFeeAllQuotesInstructions(creatorPk, feePayer, prep.extraQuoteMints): await onlineSdk.collectCoinCreatorFeeInstructions(creatorPk, feePayer);+ const collectIxs = Array.isArray(ixs) ? ixs : [ixs];+ const sweepCount = countPrefixThatFits({+ payer: feePayer,+ prefix: prep.sweeps,+ rest: collectIxs,+ tables: await getPumpLookupTables({ network: body.network }),+ });const built = await buildLaunchTransaction({network: body.network,payer: feePayer,- instructions: Array.isArray(ixs) ? ixs : [ixs],+ instructions: [...prep.sweeps.slice(0, sweepCount), ...collectIxs],transactionVersion: body.transaction_version,v1Capable: body.v1_capable,});@@ -4725,6 +4837,10 @@ async function handleCollectCreatorFeePrep(req, res) {network: body.network,tx_base64: built.tx_base64,transaction_version: built.transaction_version,+ swept: sweptReport(prep.swept, sweepCount),+ // Fee legs left on curves or pools after this claim (too many for one+ // transaction); claiming again sweeps the next largest.+ sweeps_remaining: prep.legs.length - sweepCount,});} catch (e) {return error(@@ -4776,8 +4892,10 @@ async function handleDistributeCreatorFeesPrep(req, res) {const { connection } = await getPumpSdk({ network: body.network });const { OnlinePumpSdk } = await import('@pump-fun/pump-sdk');const onlineSdk = new OnlinePumpSdk(connection);- const { instructions, isGraduated } =- await onlineSdk.buildDistributeCreatorFeesInstructions(mintPk);+ const { instructions, isGraduated } = await onlineSdk.buildDistributeCreatorFeesInstructions(+ mintPk,+ await distributeOptions(onlineSdk, mintPk, payerPk),+ );const tx_base64 = await buildUnsignedTxBase64({network: body.network,payer: payerPk,@@ -4910,7 +5028,7 @@ async function handleUpdateFeeSharesPrep(req, res) {const tx_base64 = await buildUnsignedTxBase64({network: body.network,payer: payerPk,- instructions: [ix],+ instructions: [...(await coinSweepInstructions(connection, mintPk, payerPk)), ix],});return json(res, 201, {mint: body.mint,@@ -4990,7 +5108,7 @@ async function handleCreateFeeSharingPrep(req, res) {const tx_base64 = await buildUnsignedTxBase64({network: body.network,payer: payerPk,- instructions: [ix],+ instructions: [...(await coinSweepInstructions(connection, mintPk, payerPk)), ix],});return json(res, 201, {mint: body.mint,@@ -5188,7 +5306,7 @@ async function handleFeeInfo(req, res) {try {const connection = getConnection({ network });const [- { PumpSdk, OnlinePumpSdk, canonicalPumpPoolPda, creatorVaultPda, feeSharingConfigPda },+ { PumpSdk, OnlinePumpSdk, canonicalPumpPoolPdaWithQuote, normalizeQuoteMint, creatorVaultPda, feeSharingConfigPda },{ OnlinePumpAmmSdk, coinCreatorVaultAuthorityPda, coinCreatorVaultAtaPda },{ AccountLayout, NATIVE_MINT, TOKEN_PROGRAM_ID },] = await Promise.all([@@ -5203,7 +5321,7 @@ async function handleFeeInfo(req, res) {if (!bondingCurve) return error(res, 404, 'not_found', 'no bonding curve for this mint');const isHolderReward = bondingCurve.isHolderReward === true;- const poolPda = canonicalPumpPoolPda(mintPk);+ const poolPda = canonicalPumpPoolPdaWithQuote(mintPk, normalizeQuoteMint(bondingCurve.quoteMint));const poolInfo = await connection.getAccountInfo(poolPda);let isGraduated = false;let poolCoinCreator = null;@@ -5255,11 +5373,19 @@ async function handleFeeInfo(req, res) {}}- // Vault balance = pump native creator vault (minus rent) + AMM WSOL vault.+ // Vault balance = pump native creator vault (minus rent) + AMM WSOL vault,+ // plus the SOL creator fees v3 / PumpSwap v2 trades left on this coin's+ // curve and pool, which a claim sweeps into the vault first.// When a sharing config exists, fees accrue under the config PDA.let claimableLamports = 0n;+ let unsweptLamports = 0n;if (!isCashbackCoin) {const vaultCreator = hasSharingConfig ? feeSharingConfigPda(mintPk) : effectiveCreator;+ const buckets = await readCreatorFeeBuckets(connection, [mintPk.toBase58()]);+ for (const leg of unsweptCreatorFees(buckets.values(), vaultCreator.toBase58())) {+ if (leg.quoteMint === SOL_QUOTE_MINT) unsweptLamports += leg.amount;+ }+ claimableLamports += unsweptLamports;const nativeVault = creatorVaultPda(vaultCreator);const nativeInfo = await connection.getAccountInfo(nativeVault);if (nativeInfo) {@@ -5303,6 +5429,8 @@ async function handleFeeInfo(req, res) {creator: effectiveCreator.toBase58(),claimable_lamports: claimableLamports.toString(),claimable_sol: Number(claimableLamports) / LAMPORTS_PER_SOL,+ // The part of claimable still on the curve or pool (swept by the claim).+ unswept_lamports: unsweptLamports.toString(),fee_destination: feeDestination,sharing_config: sharingConfig,});@@ -5319,7 +5447,7 @@ async function handleFeeInfo(req, res) {// Build a v0 transaction from `instructions`, sign with the agent keypair (and// any extra signers), send, and confirm. Mirrors the launch-agent send path so// every server-signed pump action uses the same RPC handling.-async function signSendWithAgent({ network, agentKeypair, instructions, extraSigners = [] }) {+async function signSendWithAgent({ network, agentKeypair, instructions, extraSigners = [], lookupTables = [] }) {const conn = solanaConnection(network);// Protected send: priority fee + CU estimate, rebroadcast with blockhash// refresh, hard throw on an on-chain revert.@@ -5328,7 +5456,7 @@ async function signSendWithAgent({ network, agentKeypair, instructions, extraSigconnection: conn,payer: agentKeypair,instructions,- opts: { extraSigners },+ opts: { extraSigners, addressLookupTables: lookupTables },});return signature;}@@ -5411,20 +5539,39 @@ async function handleCollectCreatorFeeAgent(req, res) {// lamports the claim delivered (net of tx fee): callers (the launcher// claimer, the studio) need the real figure, not a boolean.const balanceBefore = await connection.getBalance(creatorPk).catch(() => null);+ // Fees v3 / PumpSwap v2 trades left on the creator's curves and pools are+ // swept into the vault first, so this one claim collects them too.+ const prep = await prepareCreatorSweeps(connection, {+ creator: ctx.creator,+ mints: await creatorCoinMints(ctx.creator, body.network, [body.mint]),+ payer: creatorPk,+ solOnly: !body.all_quotes,+ });const ixs = body.all_quotes- ? await onlineSdk.collectCoinCreatorFeeAllQuotesInstructions(creatorPk, creatorPk)+ ? await onlineSdk.collectCoinCreatorFeeAllQuotesInstructions(creatorPk, creatorPk, prep.extraQuoteMints): await onlineSdk.collectCoinCreatorFeeInstructions(creatorPk, creatorPk);+ const collectIxs = Array.isArray(ixs) ? ixs : [ixs];+ const lookupTables = await getPumpLookupTables({ network: body.network });+ const sweepCount = countPrefixThatFits({+ payer: creatorPk,+ prefix: prep.sweeps,+ rest: collectIxs,+ tables: lookupTables,+ reserveBytes: PROTECTED_SEND_RESERVE_BYTES,+ });const signature = await signSendWithAgent({network: body.network,agentKeypair: ctx.loaded.keypair,- instructions: Array.isArray(ixs) ? ixs : [ixs],+ instructions: [...prep.sweeps.slice(0, sweepCount), ...collectIxs],+ lookupTables,});+ const swept = sweptReport(prep.swept, sweepCount);const balanceAfter = balanceBefore == null ? null : await connection.getBalance(creatorPk).catch(() => null);const lamports = balanceBefore != null && balanceAfter != null ? Math.max(0, balanceAfter - balanceBefore) : null;await sql`insert into agent_actions (agent_id, type, payload, source_skill)values (${ctx.agent.id}, ${'pumpfun.collect_creator_fee'},- ${JSON.stringify({ mint: body.mint, network: body.network, signature, lamports, source: 'studio_agent_wallet' })}::jsonb,+ ${JSON.stringify({ mint: body.mint, network: body.network, signature, lamports, swept, source: 'studio_agent_wallet' })}::jsonb,${'pumpfun'})`.catch((e) => console.error('[pump/collect-creator-fee-agent] log failed', e?.message));return json(res, 201, {@@ -5434,6 +5581,8 @@ async function handleCollectCreatorFeeAgent(req, res) {signature,lamports,sol: lamports == null ? null : lamports / LAMPORTS_PER_SOL,+ swept,+ sweeps_remaining: prep.legs.length - sweepCount,explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,});} catch (e) {@@ -5461,8 +5610,10 @@ async function handleDistributeCreatorFeesAgent(req, res) {const { connection } = await getPumpSdk({ network: body.network });const { OnlinePumpSdk } = await import('@pump-fun/pump-sdk');const onlineSdk = new OnlinePumpSdk(connection);+ const mintPk = new PublicKey(body.mint);const { instructions } = await onlineSdk.buildDistributeCreatorFeesInstructions(- new PublicKey(body.mint),+ mintPk,+ await distributeOptions(onlineSdk, mintPk, ctx.loaded.keypair.publicKey),);const signature = await signSendWithAgent({network: body.network,@@ -5581,7 +5732,7 @@ async function handleFeeSharingAgent(req, res) {await signSendWithAgent({network: body.network,agentKeypair: ctx.loaded.keypair,- instructions: [createIx],+ instructions: [...(await coinSweepInstructions(connection, mintPk, creator)), createIx],}),);}@@ -5605,7 +5756,7 @@ async function handleFeeSharingAgent(req, res) {await signSendWithAgent({network: body.network,agentKeypair: ctx.loaded.keypair,- instructions: [updateIx],+ instructions: [...(await coinSweepInstructions(connection, mintPk, creator)), updateIx],}),);diff --git a/api/pump/launch-detail.js b/api/pump/launch-detail.jsindex bc3ba696b..b8575fd82 100644--- a/api/pump/launch-detail.js+++ b/api/pump/launch-detail.js@@ -89,7 +89,7 @@ async function creatorFeesFor(mint, network, price) {const creators = await resolveCoinCreators(connection, [mint]).catch(() => null);const creator = creators?.get(mint)?.creator;if (!creator) return null;- const report = await readCreatorFeeReport(connection, creator);+ const report = await readCreatorFeeReport(connection, creator, { mints: [mint] });if (!report.ok) return null;const earned = Number(report.earned_lamports) / 1e9;return {diff --git a/docs/launchpad.md b/docs/launchpad.mdindex 1e4e3b0bb..213ecfae5 100644--- a/docs/launchpad.md+++ b/docs/launchpad.md@@ -64,7 +64,15 @@ clear error instead of a failed signature. You can pin v0 or v1 under **Transactpump.fun pools creator rewards per creator wallet, not per coin. **My coins**(`GET /api/pump/my-coins`) groups your coins by the wallet that earns their rewards and reads the-live unclaimed balance for every quote mint (bonding curve and PumpSwap vaults both).+live unclaimed balance for every quote mint (bonding curve and PumpSwap vaults both). Since+pump.fun's October 2026 program update, newer trades leave the creator fee on the coin's bonding+curve or pool until it is swept into the vault; those amounts are counted too (`rewards[].unswept`+is the part still waiting on a curve or pool), so the balance is what a claim collects now.++Every claim sweeps first: the transaction moves the fees held on your coins' curves and pools+into your vaults, then collects the vaults, all in one signature. When more coins hold fees than+fit in one transaction, the largest go first and the response says how many wait for the next+claim (`sweeps_remaining`).- **Your wallet:** Claim builds `collect-creator-fee-prep` with `all_quotes: true`, your wallet signs,the page confirms it.@@ -87,8 +95,9 @@ linked to it (`/api/auth/wallets/link-solana`).| `POST launch-confirm` | Verify the confirmed transaction (pump.fun program invoked, launch fee paid) and record the launch. || `POST launch-agent` | Launch signed by the agent's custodial wallet. Returns `platform_fee` with `settlement`. || `GET my-coins` | Your coins plus unclaimed rewards per creator wallet. |-| `POST collect-creator-fee-prep` | Claim transaction for a wallet creator. `all_quotes: true` sweeps SOL and USDC vaults. |-| `POST collect-creator-fee-agent` | Server-signed claim for an agent-wallet creator. |+| `POST collect-creator-fee-prep` | Claim transaction for a wallet creator. `all_quotes: true` collects every quote vault (SOL, USDC, and any pump coin your coins are paired with). `mints` (up to 50) adds coins to sweep beyond the ones you launched here. Returns `swept` (`mint`, `source` `curve` or `pool`, `quote_mint`, `amount`) and `sweeps_remaining`. |+| `POST collect-creator-fee-agent` | Server-signed claim for an agent-wallet creator. Sweeps the agent's coins first; returns `swept` and `sweeps_remaining`. |+| `GET fee-info` | One coin's fee setup and claimable balance. `claimable_lamports` includes `unswept_lamports`, the SOL fees still on the coin's curve or pool. |```bashcurl -s https://three.ws/api/pump/launch-configdiff --git a/pump-fun-skills/coin-fees/scripts/build-collect-fee-tx.mjs b/pump-fun-skills/coin-fees/scripts/build-collect-fee-tx.mjsindex aba53a0db..73c270842 100644--- a/pump-fun-skills/coin-fees/scripts/build-collect-fee-tx.mjs+++ b/pump-fun-skills/coin-fees/scripts/build-collect-fee-tx.mjs@@ -3,7 +3,9 @@* Only use this script when the user explicitly requests it. Default: POST https://fun-block.pump.fun/agents/collect-fees** Build a transaction to collect creator fees (crank) for a coin with no sharing config.- * Uses OnlinePumpSdk.collectCoinCreatorFeeInstructions — permissionless.+ * Sweeps the coin's creator fees still on its bonding curve or pool into the+ * vault first (v3 / PumpSwap v2 trades leave them there), then collects with+ * OnlinePumpSdk.collectCoinCreatorFeeInstructions. Permissionless.*/import { parseArgs } from "node:util";import {@@ -23,6 +25,7 @@ import {requirePublicKey,} from "./lib/args.mjs";import { buildAndPartialSignTx, transactionToBase64 } from "./lib/tx-build.mjs";+import { coinCreatorFeeSweeps } from "./lib/sweep.mjs";const COLLECT_FEE_DEFAULT_UNITS = 200_000;@@ -154,10 +157,11 @@ async function main() {}}- const sdkInstructions = await onlineSdk.collectCoinCreatorFeeInstructions(- creator,- user,- );+ const sweeps = await coinCreatorFeeSweeps(connection, { mint, payer: user, recipient: creator });+ const sdkInstructions = [+ ...sweeps.instructions,+ ...(await onlineSdk.collectCoinCreatorFeeInstructions(creator, user)),+ ];const tx = await buildAndPartialSignTx({connection,@@ -172,6 +176,7 @@ async function main() {printJson({transaction: transactionToBase64(tx),creator: creator.toBase58(),+ swept: sweeps.swept,frontRunnerProtection,});}diff --git a/pump-fun-skills/coin-fees/scripts/build-distribute-fees-tx.mjs b/pump-fun-skills/coin-fees/scripts/build-distribute-fees-tx.mjsindex 9f5560933..53878e482 100644--- a/pump-fun-skills/coin-fees/scripts/build-distribute-fees-tx.mjs+++ b/pump-fun-skills/coin-fees/scripts/build-distribute-fees-tx.mjs@@ -4,8 +4,10 @@* (The API auto-detects sharing config vs direct collect.)** Build a transaction to distribute creator fees when a sharing config exists.- * If graduated: transferCreatorFeesToPump + distributeCreatorFees.- * If not graduated: distributeCreatorFees only.+ * Any creator fees still on the bonding curve or pool (left there by v3 /+ * PumpSwap v2 trades) are swept first: distribution is refused while they sit there.+ * If graduated: sweeps + transferCreatorFeesToPump + distributeCreatorFees.+ * If not graduated: sweeps + distributeCreatorFees.*/import { parseArgs } from "node:util";import {@@ -37,6 +39,7 @@ import {requirePublicKey,} from "./lib/args.mjs";import { buildAndPartialSignTx, transactionToBase64 } from "./lib/tx-build.mjs";+import { coinCreatorFeeSweeps } from "./lib/sweep.mjs";const DISTRIBUTE_FEE_DEFAULT_UNITS = 200_000;@@ -131,8 +134,9 @@ async function main() {const sharingConfig = PUMP_SDK.decodeSharingConfig(sharingConfigAccountInfo);- // Build instructions- const instructions = [];+ // Build instructions: empty the curve and pool buckets first+ const sweeps = await coinCreatorFeeSweeps(connection, { mint, payer: user });+ const instructions = [...sweeps.instructions];if (isGraduated) {const pumpAmmProgram = getPumpAmmProgram(connection);@@ -190,6 +194,7 @@ async function main() {sharingConfigAddress: sharingConfigAddress.toBase58(),shareholderCount: sharingConfig.shareholders.length,isGraduated,+ swept: sweeps.swept,frontRunnerProtection,});}diff --git a/pump-fun-skills/coin-fees/scripts/lib/sweep.mjs b/pump-fun-skills/coin-fees/scripts/lib/sweep.mjsnew file mode 100644index 000000000..6eb244637--- /dev/null+++ b/pump-fun-skills/coin-fees/scripts/lib/sweep.mjs@@ -0,0 +1,75 @@+/**+ * Creator-fee sweeps for one coin.+ *+ * Since pump-sdk 4.0 (the v3 bonding-curve and v2 PumpSwap trade instructions),+ * a trade can leave its creator fee on the bonding curve (`creatorFee`) or in+ * the canonical pool (`creatorFees`) instead of paying the creator vault. A+ * collect only drains the vault, and a distribution is refused with+ * `CreatorFeesNotSwept` while either bucket is nonzero, so both builders put+ * these permissionless sweeps first.+ * Docs: https://github.com/pump-fun/pump-public-docs/blob/main/docs/SWEEP_FEES.md+ */+import {+ PUMP_SDK,+ bondingCurvePda,+ canonicalPumpPoolPdaWithQuote,+ normalizeQuoteMint,+} from "@pump-fun/pump-sdk";+import { PumpAmmSdk } from "@pump-fun/pump-swap-sdk";+import { NATIVE_MINT } from "@solana/spl-token";++/**+ * Sweep instructions for every nonzero creator-fee bucket of `mint`.+ *+ * @param {import("@solana/web3.js").Connection} connection+ * @param {object} o+ * @param {import("@solana/web3.js").PublicKey} o.mint+ * @param {import("@solana/web3.js").PublicKey} o.payer signs and pays any vault rent+ * @param {import("@solana/web3.js").PublicKey} [o.recipient] only sweep buckets owed to this creator+ * @returns {Promise<{ instructions: import("@solana/web3.js").TransactionInstruction[], swept: Array<{ source: "curve" | "pool", recipient: string, quoteMint: string, amount: string }> }>}+ */+export async function coinCreatorFeeSweeps(connection, { mint, payer, recipient }) {+ const curveInfo = await connection.getAccountInfo(bondingCurvePda(mint));+ const curve = curveInfo ? PUMP_SDK.decodeBondingCurveNullable(curveInfo) : null;+ if (!curve) return { instructions: [], swept: [] };++ const quoteMint = normalizeQuoteMint(curve.quoteMint);+ const legs = [];+ if (!curve.creatorFee.isZero()) {+ legs.push({ source: "curve", recipient: curve.creator, quoteMint, amount: curve.creatorFee });+ }+ if (curve.complete) {+ const poolInfo = await connection.getAccountInfo(canonicalPumpPoolPdaWithQuote(mint, quoteMint));+ const pool = poolInfo ? new PumpAmmSdk().decodePoolNullable(poolInfo) : null;+ if (pool && !pool.creatorFees.isZero()) {+ legs.push({ source: "pool", recipient: pool.coinCreator, quoteMint: pool.quoteMint, amount: pool.creatorFees });+ }+ }+ const owed = recipient ? legs.filter((l) => l.recipient.equals(recipient)) : legs;+ if (!owed.length) return { instructions: [], swept: [] };++ let quoteTokenProgram;+ if (!quoteMint.equals(NATIVE_MINT)) {+ const quoteInfo = await connection.getAccountInfo(quoteMint);+ if (!quoteInfo) throw new Error(`Quote mint ${quoteMint.toBase58()} not found on-chain.`);+ quoteTokenProgram = quoteInfo.owner;+ }++ const instructions = [];+ for (const leg of owed) {+ instructions.push(+ leg.source === "curve"+ ? await PUMP_SDK.sweepCreatorFeeInstruction({ payer, mint, creator: leg.recipient, quoteMint: leg.quoteMint, quoteTokenProgram })+ : await PUMP_SDK.sweepPoolCreatorFeeInstruction({ payer, mint, coinCreator: leg.recipient, quoteMint: leg.quoteMint, quoteTokenProgram }),+ );+ }+ return {+ instructions,+ swept: owed.map((l) => ({+ source: l.source,+ recipient: l.recipient.toBase58(),+ quoteMint: l.quoteMint.toBase58(),+ amount: l.amount.toString(),+ })),+ };+}diff --git a/src/agent-skills-pumpfun.js b/src/agent-skills-pumpfun.jsindex 15d61bb33..63500d39d 100644--- a/src/agent-skills-pumpfun.js+++ b/src/agent-skills-pumpfun.js@@ -852,23 +852,44 @@ export function registerPumpFunSkills(skills) {name: 'pumpfun-claim-fees',description:'Claim accumulated creator fees from the agent-creator vault to the agent owner wallet.',- instruction: 'Calls collectCoinCreatorFeeInstructions on OnlinePumpSdk.',+ instruction:+ 'Sweeps the fees v3 / PumpSwap v2 trades left on the given coins\' curves and pools, then calls collectCoinCreatorFeeInstructions on OnlinePumpSdk.',animationHint: 'celebrate',voicePattern: 'Claiming creator fees…',mcpExposed: true,inputSchema: {type: 'object',- properties: { network: { type: 'string', enum: ['mainnet', 'devnet'] } },+ properties: {+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ mints: {+ type: 'array',+ items: { type: 'string' },+ maxItems: 20,+ description: 'Coins this wallet created. Their creator fees still on the curve or pool are swept in first.',+ },+ },},handler: async (args, _ctx) => {const network = args.network || DEFAULT_NETWORK;const { pump, web3 } = await loadCore();const { wallet, pubkey } = await requireWallet();const connection = getConnection(web3, network);+ const creator = pubkey.toBase58();+ const { readCreatorFeeBuckets, unsweptCreatorFees, creatorFeeSweepInstructions } = await import(+ './solana/pump-creator-sweep.js'+ );+ const mints = (Array.isArray(args.mints) ? args.mints : []).filter((m) => typeof m === 'string' && m.length >= 32);+ const legs = mints.length+ ? unsweptCreatorFees((await readCreatorFeeBuckets(connection, mints)).values(), creator).filter(+ (l) => l.quoteMint === 'So11111111111111111111111111111111111111112',+ )+ : [];+ const unswept = legs.reduce((sum, l) => sum + l.amount, 0n);const onlineSdk = new pump.OnlinePumpSdk(connection);- const balance = await onlineSdk.getCreatorVaultBalanceBothPrograms(pubkey);- if (balance.isZero?.() || balance.toString() === '0') {+ const vault = BigInt((await onlineSdk.getCreatorVaultBalanceBothPrograms(pubkey)).toString());+ const total = vault + unswept;+ if (total === 0n) {return {success: true,output: 'No creator fees to claim right now.',@@ -877,19 +898,21 @@ export function registerPumpFunSkills(skills) {};}+ const { instructions: sweeps, swept } = await creatorFeeSweepInstructions(connection, { legs, payer: pubkey });+ const claimed = vault + swept.reduce((sum, l) => sum + l.amount, 0n);const ixs = await onlineSdk.collectCoinCreatorFeeInstructions(pubkey, pubkey);const sig = await sendIxs({web3,connection,wallet,payer: pubkey,- instructions: ixs,+ instructions: [...sweeps, ...ixs],});return {success: true,- output: `Claimed ${balance.toString()} lamports of creator fees.`,+ output: `Claimed ${claimed.toString()} lamports of creator fees.`,sentiment: 0.8,- data: { signature: sig, lamports: balance.toString(), network },+ data: { signature: sig, lamports: claimed.toString(), swept: swept.length, network },};},});diff --git a/src/launch/launch-page.js b/src/launch/launch-page.jsindex 4f736e16d..cbc4f372a 100644--- a/src/launch/launch-page.js+++ b/src/launch/launch-page.js@@ -1292,12 +1292,16 @@ async function claim(address) {renderCoins();try {let signature;+ // Each claim sweeps the fees still held on its coins' curves and pools+ // first; what does not fit in one transaction waits for the next claim.+ let remaining = 0;if (w.kind === 'agent') {const out = await api('/api/pump/collect-creator-fee-agent', {method: 'POST',body: { agent_id: w.agent.id, mint: w.claim_mint, network: 'mainnet', all_quotes: true },});signature = out.signature;+ remaining = out.sweeps_remaining || 0;} else {if (!state.wallet || state.wallet.address !== address) {await connectWallet();@@ -1307,8 +1311,16 @@ async function claim(address) {}const prep = await api('/api/pump/collect-creator-fee-prep', {method: 'POST',- body: { creator_address: address, wallet_address: address, network: 'mainnet', all_quotes: true, v1_capable: !!state.wallet.v1 },+ body: {+ creator_address: address,+ wallet_address: address,+ network: 'mainnet',+ all_quotes: true,+ v1_capable: !!state.wallet.v1,+ mints: w.coins.slice(0, 50),+ },});+ remaining = prep.sweeps_remaining || 0;signature = await signAndBroadcast({ txBase64: prep.tx_base64, version: prep.transaction_version, address });const confirmed = await waitForConfirmation(signature);if (!confirmed) {@@ -1316,7 +1328,10 @@ async function claim(address) {return;}}- status(`<div class="lx-alert is-good">Rewards claimed. <a class="lx-link" href="https://solscan.io/tx/${esc(signature)}" target="_blank" rel="noopener">View transaction</a></div>`);+ const more = remaining > 0+ ? ` ${remaining === 1 ? 'One coin still holds' : `${remaining} coins still hold`} rewards that did not fit in this transaction: claim again to collect ${remaining === 1 ? 'it' : 'them'}.`+ : '';+ status(`<div class="lx-alert is-good">Rewards claimed.${more} <a class="lx-link" href="https://solscan.io/tx/${esc(signature)}" target="_blank" rel="noopener">View transaction</a></div>`);} catch (err) {status(`<div class="lx-alert" role="alert">${esc(friendlyLaunchError(err))}</div>`);} finally {diff --git a/src/pump/trade-events.js b/src/pump/trade-events.jsnew file mode 100644index 000000000..fd61382a8--- /dev/null+++ b/src/pump/trade-events.js@@ -0,0 +1,95 @@+// Pump bonding-curve trades from decoded Anchor events, with synthetic+// migration folded in.+//+// Since pump-sdk 4.0 the v3 buy (or a multi_hop_swap curve hop) that empties a+// bonding curve keeps buying past it, from the tokens that would seed the+// PumpSwap pool. It emits three events in order: `TradeEvent` (the curve part+// only), `CompleteEvent`, then `PostCompleteBuyEvent` (the pool part). The+// buyer's real trade is the sum of both parts, so a consumer that reads+// `TradeEvent` alone undercounts exactly the largest buy a coin ever sees.+// Docs: https://github.com/pump-fun/pump-public-docs/blob/main/docs/SYNTHETIC_MIGRATION.md+//+// Pure and browser-safe: the API trade firehose, the MCP trade tools and the+// in-browser whale watcher share it.++const SOL_QUOTES = new Set(['So11111111111111111111111111111111111111112', '11111111111111111111111111111111']);++/**+ * Read a decoded event field under either casing: the current anchor + pump+ * IDL emits snake_case, older toolchains camelCased it.+ * @param {Record<string, any> | null | undefined} data+ * @param {string} snake+ */+function field(data, snake) {+ if (data == null) return undefined;+ if (data[snake] !== undefined) return data[snake];+ return data[snake.replace(/_([a-z])/g, (_, c) => c.toUpperCase())];+}++/** @param {unknown} v */+function toBigInt(v) {+ if (v == null) return 0n;+ try {+ return BigInt(String(/** @type {any} */ (v).toString()));+ } catch {+ return 0n;+ }+}++/** @param {unknown} key */+function keyString(key) {+ return key == null ? '' : String(/** @type {any} */ (key).toString());+}++/**+ * @typedef {object} PumpTrade+ * @property {Record<string, any>} data the `TradeEvent` fields as decoded+ * @property {string} mint+ * @property {string} user+ * @property {boolean} isBuy+ * @property {bigint} solAmount lamports for the whole trade (curve part plus a SOL pool part)+ * @property {bigint} tokenAmount base units for the whole trade+ * @property {Record<string, any> | null} postComplete the `PostCompleteBuyEvent` fields, when this buy completed the curve+ */++/**+ * Every `TradeEvent` in one transaction's decoded events, each with the+ * `PostCompleteBuyEvent` that follows it (same mint and buyer) folded into its+ * amounts. Order is preserved.+ *+ * @param {Iterable<{ name: string, data: Record<string, any> }>} events+ * @returns {PumpTrade[]}+ */+export function pumpTradesFromEvents(events) {+ /** @type {PumpTrade[]} */+ const trades = [];+ for (const event of events) {+ if (event?.name === 'TradeEvent') {+ const d = event.data;+ trades.push({+ data: d,+ mint: keyString(d?.mint),+ user: keyString(d?.user),+ isBuy: !!field(d, 'is_buy'),+ solAmount: toBigInt(field(d, 'sol_amount')),+ tokenAmount: toBigInt(field(d, 'token_amount')),+ postComplete: null,+ });+ continue;+ }+ if (event?.name !== 'PostCompleteBuyEvent') continue;+ const p = event.data;+ const mint = keyString(p?.mint);+ const user = keyString(p?.user);+ for (let i = trades.length - 1; i >= 0; i--) {+ const t = trades[i];+ if (!t.isBuy || t.postComplete || t.mint !== mint || t.user !== user) continue;+ t.postComplete = p;+ t.tokenAmount += toBigInt(field(p, 'base_out'));+ const quote = keyString(field(p, 'quote_mint'));+ if (!quote || SOL_QUOTES.has(quote)) t.solAmount += toBigInt(field(p, 'quote_in'));+ break;+ }+ }+ return trades;+}diff --git a/src/solana/pump-creator-sweep.js b/src/solana/pump-creator-sweep.jsnew file mode 100644index 000000000..e12aca917--- /dev/null+++ b/src/solana/pump-creator-sweep.js@@ -0,0 +1,198 @@+// Creator-fee buckets on pump.fun coins, and the sweeps that empty them.+//+// Since the v3 bonding-curve and v2 PumpSwap trade instructions (pump-sdk 4.0,+// October 2026) a trade no longer pays the creator fee into the creator vault.+// It accrues on the bonding curve (`BondingCurve.creatorFee`) or in the+// canonical pool (`Pool.creatorFees`) until the permissionless+// `sweep_creator_fee` of each program moves it into the vault. A vault read or+// a collect alone misses it, and a distribution, CTO or fee-sharing change is+// refused (`CreatorFeesNotSwept`) while a bucket is nonzero.+//+// Chain reads only, no server dependencies: the API (api/_lib/pump-creator-fees.js+// re-exports these) and the browser wallet skills (src/agent-skills-pumpfun.js)+// share this module.+// Docs: https://github.com/pump-fun/pump-public-docs/blob/main/docs/SWEEP_FEES.md++import { PublicKey } from '@solana/web3.js';++// SOL quotes: the wrapped-SOL mint, and the zero key legacy curves store.+const SOL_QUOTES = new Set(['So11111111111111111111111111111111111111112', '11111111111111111111111111111111']);++/**+ * @typedef {object} CreatorFeeBuckets+ * @property {string} mint+ * @property {string} creator the curve's current `creator` (wallet, sharing config or holder-rewards PDA)+ * @property {string} quoteMint the curve's quote mint, normalized (wrapped SOL for a SOL curve)+ * @property {boolean} complete the curve finished (the coin graduated, or is migrating)+ * @property {bigint} curveFee creator fees v3 trades left on the curve (`BondingCurve.creatorFee`)+ * @property {{ address: string, coinCreator: string, quoteMint: string, fee: bigint } | null} pool+ * the canonical PumpSwap pool of a complete curve; `fee` is what v2 pool trades+ * left in it (`Pool.creatorFees`). Null while the curve is live or the pool is missing.+ */++/**+ * Every listed coin's creator-fee buckets. One batched read per 100 curves, then one per 100 pools (complete curves+ * only, at the quote-aware canonical pool). A mint whose curve cannot be read+ * maps to null.+ *+ * @param {import('@solana/web3.js').Connection} connection+ * @param {string[]} mints+ * @returns {Promise<Map<string, CreatorFeeBuckets | null>>}+ */+export async function readCreatorFeeBuckets(connection, mints) {+ const [{ PumpSdk, bondingCurvePda, canonicalPumpPoolPdaWithQuote, normalizeQuoteMint }, { PumpAmmSdk }] =+ await Promise.all([import('@pump-fun/pump-sdk'), import('@pump-fun/pump-swap-sdk')]);+ const offline = new PumpSdk();+ const offlineAmm = new PumpAmmSdk();+ const unique = [...new Set(mints)];+ /** @type {Map<string, CreatorFeeBuckets | null>} */+ const out = new Map();+ for (let i = 0; i < unique.length; i += 100) {+ const chunk = unique.slice(i, i + 100);+ const infos = await connection.getMultipleAccountsInfo(chunk.map((m) => bondingCurvePda(new PublicKey(m))));+ chunk.forEach((mint, j) => {+ const info = infos[j];+ const curve = info ? offline.decodeBondingCurveNullable(info) : null;+ if (!curve) return out.set(mint, null);+ out.set(mint, {+ mint,+ creator: curve.creator.toBase58(),+ quoteMint: normalizeQuoteMint(curve.quoteMint).toBase58(),+ complete: curve.complete === true,+ curveFee: bnToBigInt(curve.creatorFee),+ pool: null,+ });+ });+ }+ const complete = [...out.values()].filter((b) => b?.complete);+ for (let i = 0; i < complete.length; i += 100) {+ const chunk = /** @type {CreatorFeeBuckets[]} */ (complete.slice(i, i + 100));+ const addresses = chunk.map((b) => canonicalPumpPoolPdaWithQuote(new PublicKey(b.mint), new PublicKey(b.quoteMint)));+ const infos = await connection.getMultipleAccountsInfo(addresses);+ chunk.forEach((b, j) => {+ const info = infos[j];+ const pool = info ? offlineAmm.decodePoolNullable(info) : null;+ if (!pool) return;+ b.pool = {+ address: addresses[j].toBase58(),+ coinCreator: pool.coinCreator.toBase58(),+ quoteMint: pool.quoteMint.toBase58(),+ fee: bnToBigInt(pool.creatorFees),+ };+ });+ }+ return out;+}++/** @param {{ toString(): string } | null | undefined} bn */+function bnToBigInt(bn) {+ if (bn == null) return 0n;+ try {+ return BigInt(bn.toString());+ } catch {+ return 0n;+ }+}++/**+ * The unswept fee legs that belong to `creator`: a curve leg when the curve's+ * creator is `creator`, a pool leg when the pool's coin creator is. Largest first.+ *+ * @param {Iterable<CreatorFeeBuckets | null>} buckets+ * @param {string | null} [creator] null keeps every nonzero leg (a permissionless crank)+ * @returns {Array<{ mint: string, source: 'curve' | 'pool', recipient: string, quoteMint: string, amount: bigint }>}+ */+export function unsweptCreatorFees(buckets, creator = null) {+ const legs = [];+ for (const b of buckets) {+ if (!b) continue;+ if (b.curveFee > 0n && (!creator || b.creator === creator)) {+ legs.push({ mint: b.mint, source: /** @type {const} */ ('curve'), recipient: b.creator, quoteMint: b.quoteMint, amount: b.curveFee });+ }+ if (b.pool && b.pool.fee > 0n && (!creator || b.pool.coinCreator === creator)) {+ legs.push({ mint: b.mint, source: /** @type {const} */ ('pool'), recipient: b.pool.coinCreator, quoteMint: b.pool.quoteMint, amount: b.pool.fee });+ }+ }+ return legs.sort((a, b) => (b.amount > a.amount ? 1 : b.amount < a.amount ? -1 : 0));+}++/**+ * Unswept creator fees summed per quote mint, for adding to a vault balance.+ * @param {ReturnType<typeof unsweptCreatorFees>} legs+ * @returns {Map<string, bigint>}+ */+export function sumByQuote(legs) {+ const out = new Map();+ for (const leg of legs) out.set(leg.quoteMint, (out.get(leg.quoteMint) || 0n) + leg.amount);+ return out;+}++/**+ * The quote mints of `creator`'s coins that are not SOL: pass them to+ * `collectCoinCreatorFeeAllQuotesInstructions` / `getCreatorVaultQuoteBalances`+ * as `extraQuoteMints`, so a coin quoted in a de-listed mint or in another pump+ * coin (pump-sdk 4.0 pump-coin pairs, never listed anywhere) is still collected.+ *+ * @param {Iterable<CreatorFeeBuckets | null>} buckets+ * @param {string} creator+ * @returns {PublicKey[]}+ */+export function creatorExtraQuoteMints(buckets, creator) {+ const mints = new Set();+ for (const b of buckets) {+ if (!b) continue;+ if (b.creator === creator && !SOL_QUOTES.has(b.quoteMint)) mints.add(b.quoteMint);+ if (b.pool && b.pool.coinCreator === creator && !SOL_QUOTES.has(b.pool.quoteMint)) mints.add(b.pool.quoteMint);+ }+ return [...mints].map((m) => new PublicKey(m));+}++// Each sweep adds the coin's mint, curve or pool, vault and quote accounts that+// no lookup table covers; four of them plus a collect stay inside one packet.+export const MAX_SWEEPS_PER_TX = 4;++/**+ * Sweep instructions that move unswept creator fees into the creator vaults,+ * to put first in a collect (so it collects them) or in front of a+ * distribution, CTO or fee-sharing change (which the programs refuse with+ * `CreatorFeesNotSwept` while a bucket is nonzero). Permissionless: `payer`+ * signs and covers any vault rent. Largest legs first, capped at `max`.+ *+ * @param {import('@solana/web3.js').Connection} connection+ * @param {object} o+ * @param {ReturnType<typeof unsweptCreatorFees>} o.legs+ * @param {PublicKey} o.payer+ * @param {number} [o.max]+ * @returns {Promise<{ instructions: import('@solana/web3.js').TransactionInstruction[], swept: ReturnType<typeof unsweptCreatorFees>, deferred: number }>}+ */+export async function creatorFeeSweepInstructions(connection, { legs, payer, max = MAX_SWEEPS_PER_TX }) {+ const take = legs.slice(0, Math.max(0, max));+ if (!take.length) return { instructions: [], swept: [], deferred: legs.length };+ const { PumpSdk } = await import('@pump-fun/pump-sdk');+ const sdk = new PumpSdk();+ const tokenQuotes = [...new Set(take.map((l) => l.quoteMint).filter((m) => !SOL_QUOTES.has(m)))];+ /** @type {Map<string, PublicKey>} */+ const programs = new Map();+ if (tokenQuotes.length) {+ const infos = await connection.getMultipleAccountsInfo(tokenQuotes.map((m) => new PublicKey(m)));+ tokenQuotes.forEach((m, i) => {+ if (infos[i]) programs.set(m, infos[i].owner);+ });+ }+ const instructions = [];+ const swept = [];+ for (const leg of take) {+ const quoteMint = new PublicKey(leg.quoteMint);+ const quoteTokenProgram = programs.get(leg.quoteMint);+ if (!SOL_QUOTES.has(leg.quoteMint) && !quoteTokenProgram) continue;+ const mint = new PublicKey(leg.mint);+ const recipient = new PublicKey(leg.recipient);+ instructions.push(+ leg.source === 'curve'+ ? await sdk.sweepCreatorFeeInstruction({ payer, mint, creator: recipient, quoteMint, quoteTokenProgram })+ : await sdk.sweepPoolCreatorFeeInstruction({ payer, mint, coinCreator: recipient, quoteMint, quoteTokenProgram }),+ );+ swept.push(leg);+ }+ return { instructions, swept, deferred: legs.length - swept.length };+}diff --git a/tests/pump-creator-sweep.test.js b/tests/pump-creator-sweep.test.jsnew file mode 100644index 000000000..b2acd7661--- /dev/null+++ b/tests/pump-creator-sweep.test.js@@ -0,0 +1,272 @@+// src/solana/pump-creator-sweep.js and src/pump/trade-events.js: the pump-sdk+// 4.0 changes. v3 curve and v2 PumpSwap trades leave the creator fee on the+// curve (`creator_fee`) or pool (`creator_fees`) until a sweep moves it into the+// creator vault, and the buy that completes a curve reports its+// synthetic-migration pool part in a separate PostCompleteBuyEvent.+//+// Accounts are encoded with the published pump / pump-amm IDLs, so the SDK+// decoders read them exactly as they read the cluster.++import { describe, it, expect } from 'vitest';+import anchor from '@coral-xyz/anchor';+import { Keypair, PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js';+import { bondingCurvePda, canonicalPumpPoolPdaWithQuote, pumpIdl, PUMP_PROGRAM_ID } from '@pump-fun/pump-sdk';+import { pumpAmmJson, PUMP_AMM_PROGRAM_ID } from '@pump-fun/pump-swap-sdk';++const {+ readCreatorFeeBuckets,+ unsweptCreatorFees,+ sumByQuote,+ creatorExtraQuoteMints,+ creatorFeeSweepInstructions,+} = await import('../src/solana/pump-creator-sweep.js');+const { pumpTradesFromEvents } = await import('../src/pump/trade-events.js');+const { countPrefixThatFits } = await import('../api/_lib/pump-launch-tx.js');++const { BN, BorshAccountsCoder } = anchor;+const WSOL = 'So11111111111111111111111111111111111111112';+const key = (n) => new PublicKey(Buffer.alloc(32, n));+const CREATOR = key(7);+const OTHER = key(8);+const QUOTE_COIN = key(9); // a pump coin used as another coin's quote+const MINT_LIVE = key(11);+const MINT_DONE = key(12);+const MINT_COIN_QUOTED = key(13);++const pumpCoder = new BorshAccountsCoder(pumpIdl);+const ammCoder = new BorshAccountsCoder(pumpAmmJson);++// Zero value for every field of an IDL struct, so a fixture names only what it tests.+function zeroed(idl, typeName) {+ const def = idl.types.find((t) => t.name === typeName);+ const out = {};+ for (const f of def.type.fields) {+ if (f.type === 'pubkey') out[f.name] = PublicKey.default;+ else if (f.type === 'bool') out[f.name] = false;+ else out[f.name] = new BN(0);+ }+ return out;+}++async function curveAccount({ creator = CREATOR, quoteMint = PublicKey.default, complete = false, creatorFee = 0 }) {+ const data = await pumpCoder.encode('BondingCurve', {+ ...zeroed(pumpIdl, 'BondingCurve'),+ creator,+ quote_mint: quoteMint,+ complete,+ creator_fee: new BN(creatorFee),+ depth: 0,+ });+ return { data, owner: PUMP_PROGRAM_ID, lamports: 1, executable: false };+}++async function poolAccount({ mint, coinCreator = CREATOR, quoteMint = new PublicKey(WSOL), creatorFees = 0 }) {+ const data = await ammCoder.encode('Pool', {+ ...zeroed(pumpAmmJson, 'Pool'),+ pool_bump: 255,+ index: 0,+ base_mint: mint,+ quote_mint: quoteMint,+ coin_creator: coinCreator,+ creator_fees: new BN(creatorFees),+ });+ return { data, owner: PUMP_AMM_PROGRAM_ID, lamports: 1, executable: false };+}++// A connection that answers getMultipleAccountsInfo from a fixed account map.+function fakeConnection(accounts) {+ const calls = [];+ return {+ calls,+ async getMultipleAccountsInfo(keys) {+ calls.push(keys.length);+ return keys.map((k) => accounts.get(k.toBase58()) ?? null);+ },+ };+}++describe('readCreatorFeeBuckets', () => {+ it('reads curve fees, and pool fees at the quote-aware pool of a complete curve', async () => {+ const accounts = new Map([+ [bondingCurvePda(MINT_LIVE).toBase58(), await curveAccount({ creatorFee: 1500 })],+ [bondingCurvePda(MINT_DONE).toBase58(), await curveAccount({ complete: true, creatorFee: 20 })],+ [+ canonicalPumpPoolPdaWithQuote(MINT_DONE, new PublicKey(WSOL)).toBase58(),+ await poolAccount({ mint: MINT_DONE, creatorFees: 391886 }),+ ],+ [bondingCurvePda(MINT_COIN_QUOTED).toBase58(), await curveAccount({ quoteMint: QUOTE_COIN, complete: true })],+ [+ canonicalPumpPoolPdaWithQuote(MINT_COIN_QUOTED, QUOTE_COIN).toBase58(),+ await poolAccount({ mint: MINT_COIN_QUOTED, quoteMint: QUOTE_COIN, creatorFees: 5 }),+ ],+ ]);+ const missing = key(99).toBase58();+ const buckets = await readCreatorFeeBuckets(fakeConnection(accounts), [+ MINT_LIVE.toBase58(),+ MINT_DONE.toBase58(),+ MINT_COIN_QUOTED.toBase58(),+ missing,+ ]);++ expect(buckets.get(missing)).toBeNull();+ const live = buckets.get(MINT_LIVE.toBase58());+ // A legacy curve stores the zero key as its quote; it normalizes to wrapped SOL.+ expect(live).toMatchObject({ creator: CREATOR.toBase58(), quoteMint: WSOL, complete: false, curveFee: 1500n, pool: null });+ expect(buckets.get(MINT_DONE.toBase58())).toMatchObject({+ complete: true,+ curveFee: 20n,+ pool: { coinCreator: CREATOR.toBase58(), quoteMint: WSOL, fee: 391886n },+ });+ expect(buckets.get(MINT_COIN_QUOTED.toBase58())?.pool).toMatchObject({ quoteMint: QUOTE_COIN.toBase58(), fee: 5n });+ });++ it('batches curve reads 100 at a time and skips the pool read while curves are live', async () => {+ const mints = Array.from({ length: 150 }, (_, i) => Keypair.generate().publicKey.toBase58());+ const conn = fakeConnection(new Map());+ await readCreatorFeeBuckets(conn, [...mints, mints[0]]);+ expect(conn.calls).toEqual([100, 50]);+ });+});++const bucket = (over) => ({+ mint: MINT_LIVE.toBase58(),+ creator: CREATOR.toBase58(),+ quoteMint: WSOL,+ complete: false,+ curveFee: 0n,+ pool: null,+ ...over,+});++describe('unsweptCreatorFees / sumByQuote / creatorExtraQuoteMints', () => {+ const buckets = [+ bucket({ curveFee: 10n }),+ bucket({+ mint: MINT_DONE.toBase58(),+ complete: true,+ curveFee: 3n,+ pool: { address: 'p', coinCreator: CREATOR.toBase58(), quoteMint: WSOL, fee: 900n },+ }),+ bucket({ mint: MINT_COIN_QUOTED.toBase58(), creator: OTHER.toBase58(), quoteMint: QUOTE_COIN.toBase58(), curveFee: 50n }),+ null,+ ];++ it("keeps only the creator's legs, largest first", () => {+ const legs = unsweptCreatorFees(buckets, CREATOR.toBase58());+ expect(legs.map((l) => [l.source, l.amount])).toEqual([+ ['pool', 900n],+ ['curve', 10n],+ ['curve', 3n],+ ]);+ });++ it('keeps every nonzero leg for a permissionless crank', () => {+ expect(unsweptCreatorFees(buckets)).toHaveLength(4);+ });++ it('sums per quote mint', () => {+ const byQuote = sumByQuote(unsweptCreatorFees(buckets));+ expect(byQuote.get(WSOL)).toBe(913n);+ expect(byQuote.get(QUOTE_COIN.toBase58())).toBe(50n);+ });++ it("lists a creator's non-SOL quotes so a collect reaches pump-coin pairs", () => {+ expect(creatorExtraQuoteMints(buckets, CREATOR.toBase58())).toEqual([]);+ expect(creatorExtraQuoteMints(buckets, OTHER.toBase58()).map(String)).toEqual([QUOTE_COIN.toBase58()]);+ });+});++describe('creatorFeeSweepInstructions', () => {+ const payer = key(20);+ const solLeg = (mint, source, amount) => ({ mint: mint.toBase58(), source, recipient: CREATOR.toBase58(), quoteMint: WSOL, amount });++ it('builds one curve or pool sweep per leg, capped at max', async () => {+ const legs = [solLeg(MINT_DONE, 'pool', 9n), solLeg(MINT_LIVE, 'curve', 5n), solLeg(MINT_DONE, 'curve', 1n)];+ const out = await creatorFeeSweepInstructions(fakeConnection(new Map()), { legs, payer, max: 2 });+ expect(out.instructions).toHaveLength(2);+ expect(out.swept).toEqual(legs.slice(0, 2));+ expect(out.deferred).toBe(1);+ expect(out.instructions[0].programId.equals(PUMP_AMM_PROGRAM_ID)).toBe(true);+ expect(out.instructions[1].programId.equals(PUMP_PROGRAM_ID)).toBe(true);+ });++ it('skips a token-quoted leg whose quote mint cannot be read', async () => {+ const legs = [{ ...solLeg(MINT_COIN_QUOTED, 'curve', 4n), quoteMint: QUOTE_COIN.toBase58() }, solLeg(MINT_LIVE, 'curve', 2n)];+ const out = await creatorFeeSweepInstructions(fakeConnection(new Map()), { legs, payer });+ expect(out.swept.map((l) => l.mint)).toEqual([MINT_LIVE.toBase58()]);+ expect(out.deferred).toBe(1);+ });++ it('returns nothing to do for no legs', async () => {+ expect(await creatorFeeSweepInstructions(fakeConnection(new Map()), { legs: [], payer })).toEqual({+ instructions: [],+ swept: [],+ deferred: 0,+ });+ });+});++describe('countPrefixThatFits', () => {+ const payer = key(30);+ const transfer = (n) => SystemProgram.transfer({ fromPubkey: payer, toPubkey: key(40 + n), lamports: 1 });+ const blob = (bytes) => new TransactionInstruction({ programId: key(60), keys: [], data: Buffer.alloc(bytes) });++ it('keeps every prefix instruction that fits', () => {+ expect(countPrefixThatFits({ payer, prefix: [transfer(1), transfer(2)], rest: [transfer(3)] })).toBe(2);+ });++ it('drops trailing prefix instructions until the packet fits', () => {+ const prefix = [blob(400), blob(400), blob(400)];+ expect(countPrefixThatFits({ payer, prefix, rest: [blob(100)] })).toBe(2);+ expect(countPrefixThatFits({ payer, prefix, rest: [blob(100)], reserveBytes: 300 })).toBe(1);+ });++ it('answers 0 when the required instructions alone overflow', () => {+ expect(countPrefixThatFits({ payer, prefix: [transfer(1)], rest: [blob(1300)] })).toBe(0);+ });+});++describe('pumpTradesFromEvents', () => {+ const ev = (name, data) => ({ name, data });+ const trade = (over = {}) =>+ ev('TradeEvent', { mint: MINT_LIVE, user: CREATOR, is_buy: true, sol_amount: new BN(1_000), token_amount: new BN(70), timestamp: new BN(1), ...over });++ it('folds the synthetic-migration pool part into the buy that completed the curve', () => {+ const trades = pumpTradesFromEvents([+ trade(),+ ev('CompleteEvent', { mint: MINT_LIVE }),+ ev('PostCompleteBuyEvent', { mint: MINT_LIVE, user: CREATOR, quote_mint: new PublicKey(WSOL), base_out: new BN(30), quote_in: new BN(600) }),+ ]);+ expect(trades).toHaveLength(1);+ expect(trades[0]).toMatchObject({ isBuy: true, solAmount: 1_600n, tokenAmount: 100n });+ expect(trades[0].postComplete).not.toBeNull();+ });++ it('adds pool-part tokens but not non-SOL quote to the SOL amount of a token-paired coin', () => {+ const [t] = pumpTradesFromEvents([+ trade(),+ ev('PostCompleteBuyEvent', { mint: MINT_LIVE, user: CREATOR, quote_mint: QUOTE_COIN, base_out: new BN(30), quote_in: new BN(600) }),+ ]);+ expect(t).toMatchObject({ solAmount: 1_000n, tokenAmount: 100n });+ });++ it('leaves ordinary trades, sells and other mints untouched', () => {+ const trades = pumpTradesFromEvents([+ trade({ is_buy: false }),+ trade({ mint: MINT_DONE }),+ ev('PostCompleteBuyEvent', { mint: MINT_LIVE, user: CREATOR, base_out: new BN(5), quote_in: new BN(5) }),+ ]);+ expect(trades.map((t) => [t.isBuy, t.solAmount, t.tokenAmount])).toEqual([+ [false, 1_000n, 70n],+ [true, 1_000n, 70n],+ ]);+ });++ it('reads camelCased fields from older coders', () => {+ const [t] = pumpTradesFromEvents([+ ev('TradeEvent', { mint: MINT_LIVE, user: CREATOR, isBuy: true, solAmount: new BN(2), tokenAmount: new BN(3) }),+ ev('PostCompleteBuyEvent', { mint: MINT_LIVE, user: CREATOR, baseOut: new BN(4), quoteIn: new BN(5) }),+ ]);+ expect(t).toMatchObject({ solAmount: 7n, tokenAmount: 7n });+ });+});diff --git a/workers/agent-sniper/auto-claimer.js b/workers/agent-sniper/auto-claimer.jsindex dd6f86be7..37c28667a 100644--- a/workers/agent-sniper/auto-claimer.js+++ b/workers/agent-sniper/auto-claimer.js@@ -54,8 +54,10 @@ async function fetchFeeInfo(mint, network) {}/**- * POST collect-creator-fee-agent to claim fees.- * Returns { ok, sig, lamports } on success, null on failure.+ * POST collect-creator-fee-agent to claim fees. The endpoint sweeps the fees+ * v3 / PumpSwap v2 trades left on the agent's curves and pools in the same+ * transaction, and collects every quote mint (SOL and token-paired coins).+ * Returns { ok, signature, lamports } on success, null on failure.*/async function collectCreatorFee(agentId, mint, network) {const url = `${API_BASE}/api/pump?action=collect-creator-fee-agent`;@@ -66,7 +68,7 @@ async function collectCreatorFee(agentId, mint, network) {'content-type': 'application/json',authorization: `Bearer ${AGENT_JWT}`,},- body: JSON.stringify({ agentId, mint, network }),+ body: JSON.stringify({ agent_id: agentId, mint, network, all_quotes: true }),});if (!res.ok) {const body = await res.text().catch(() => '');@@ -186,13 +188,13 @@ async function processCoin(cfg, coin) {await sql`UPDATE agent_launched_coinsSET claimable_lamports = 0,- last_claim_sig = ${result.sig ?? null},+ last_claim_sig = ${result.signature ?? null},last_claim_at = now(),total_claimed_lamports = ${newTotal.toString()}WHERE id = ${coin.id}`;} catch (err) {- log.warn('claim db update failed', { mint: coin.mint, sig: result.sig, err: err?.message });+ log.warn('claim db update failed', { mint: coin.mint, sig: result.signature, err: err?.message });}log.trade('creator-fee-claimed', {@@ -202,7 +204,7 @@ async function processCoin(cfg, coin) {claimed_lamports: claimedLamports.toString(),claimed_sol: lamportsToSol(claimedLamports),total_claimed_sol: Number(totalSol),- sig: result.sig,+ sig: result.signature,});screenPush(`Claimed ${lamportsToSol(claimedLamports)} SOL from $${symbol} — total: ${totalSol} SOL`, 'trade');