Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(trade-fee): charge a 1% fee in the same transaction on every customer trade three.ws builds or signs

nirholasb5d9579a163e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6f54fa18e..c70321c5c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Docs · The /launch launchpad** (`/docs/launchpad`): How three.ws/launch launches a pump.fun coin for a 3D agent: agent-linked metadata, the 1% dev-buy fee, v0 lookup-table and Solana transaction v1 formats, claiming creator rewards on three.ws, and the API behind it.
- **A cleaner launchpad for your 3D agent's coin, with rewards you claim right here**: three.ws/launch is rebuilt around one flow: pick one of your 3D agents, name the coin, and launch it on pump.fun from your wallet or from the agent's own wallet. The coin's metadata links your agent's page and 3D body, a live preview and cost panel show exactly what you will pay (including a 1% three.ws fee on the dev buy), and a new My coins tab shows unclaimed creator rewards and claims them in one click, no pump.fun app needed. Launches now fit in a single transaction thanks to pump.fun's lookup table, and larger ones, like USDC-paired coins with a dev buy, use Solana transaction v1 automatically when your wallet supports it. This also fixes launches that were failing because an on-chain buyback program stopped accepting new agents. (`/launch`) `[feature, improvement, fix]`
+- **A flat 1% fee on trades made through three.ws**: Trades that three.ws builds or runs for you now carry a 1% fee, paid in the same transaction as the trade: buys and sells in the coin trade window, trades from your agent's wallet, and trades your agents make through strategies, mirror trading, orders, market making and sniping. The fee is shown before you confirm, both in the trade window and in the agent wallet's trade tab. Trades you make on other apps are not affected, and three.ws's own agents are never charged. (`/legal/tos`) `[improvement]`
- **Deploy your agent on-chain with Solana's new transaction v1**: Minting an agent to Solana now uses the new transaction v1 format whenever your wallet supports it, from the agent deploy button, the registration wizard (vanity addresses included), and /deploy-onchain. On /deploy-onchain that turns a Genesis-shape deploy from two wallet transactions into one: the asset is created and registered in the Metaplex Agent Registry atomically, so there is no half-finished deploy if something fails in between. Each deploy spells out its compute, account data, and priority fee limits instead of relying on defaults, and three.ws checks that the transaction that landed on-chain is the exact version it prepared before recording your agent. Wallets that have not added v1 yet keep working exactly as before, and a deployed agent now shows which transaction format it used. (`/deploy-onchain`) `[feature, security]`
- **GitHub fee claims now say what they actually prove**: A GitHub fee claim on pump.fun proves that a GitHub account collected creator fees routed to it. It does not prove that person built the coin, owns the linked repository, or backs the project. Claim cards on /pumpfun used to read as a developer endorsing a coin even when the account was a lookalike name, the coin had no GitHub link at all, or one fee account was shared by several coins and the card simply picked the biggest one. Every claim now carries one of five labels: verified repository, verified creator wallet, identity mismatch, unverified, or unresolved pooled withdrawal. Only the two verified labels get trade buttons or count toward a coin's reputation score, mismatches are flagged in red, and the Telegram claims channel follows the same rules. (`/pumpfun`) `[fix, improvement]`
- **pump.fun agent skills now launch holder-reward coins**: The pump.fun launch, swap and fee skills that agents use on three.ws now run on version 2 of the pump.fun SDK. Launching a coin can now turn on holder rewards, which sends every creator fee to the coin's holders instead of the launcher, permanently. Cashback launches were retired by pump.fun, so the skill now refuses them up front with a clear message instead of handing back a transaction that would fail after you sign it. The fee skill also recognizes holder-reward coins and explains where their fees go rather than trying to collect them. `[improvement, fix]`
diff --git a/api/_lib/agent-mirror.js b/api/_lib/agent-mirror.js
index cd6860e85..ec1ab6c45 100644
--- a/api/_lib/agent-mirror.js
+++ b/api/_lib/agent-mirror.js
@@ -276,7 +276,7 @@ export async function runFollowerTrade({
let instructions;
try {
- instructions = await buildTradeInstructions({ side, conn, network, mintPk, ownerPk: keypair.publicKey, quote, slippageBps, solAmount, tokenAmountRaw });
+ instructions = await buildTradeInstructions({ userId: ownerId, side, conn, network, mintPk, ownerPk: keypair.publicKey, quote, slippageBps, solAmount, tokenAmountRaw });
} catch (e) {
await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'build_failed', message: (e?.message || '').slice(0, 200) } }).catch(() => {});
return { status: 'failed', code: 'build_failed' };
diff --git a/api/_lib/agent-strategy-runtime.js b/api/_lib/agent-strategy-runtime.js
index bfb3746a3..dfcaf4b82 100644
--- a/api/_lib/agent-strategy-runtime.js
+++ b/api/_lib/agent-strategy-runtime.js
@@ -252,7 +252,7 @@ export async function runStrategyTrade({
let instructions;
try {
- instructions = await buildTradeInstructions({ side, conn, network, mintPk, ownerPk: keypair.publicKey, quote, slippageBps, solAmount, tokenAmountRaw });
+ instructions = await buildTradeInstructions({ userId: ownerId, side, conn, network, mintPk, ownerPk: keypair.publicKey, quote, slippageBps, solAmount, tokenAmountRaw });
} catch (e) {
await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'build_failed', message: (e?.message || '').slice(0, 200) } }).catch(() => {});
return { status: 'failed', code: 'build_failed' };
diff --git a/api/_lib/pump-platform-fee.js b/api/_lib/pump-platform-fee.js
index 82457adff..6f8daebdd 100644
--- a/api/_lib/pump-platform-fee.js
+++ b/api/_lib/pump-platform-fee.js
@@ -27,16 +27,16 @@ const WSOL_MINT = 'So11111111111111111111111111111111111111112';
const MAX_FEE_BPS = 500; // 5%
/**
- * The platform trade-fee rate in basis points. Defaults to 0 (OFF) so the fee
- * ships inert and never activates on deploy by surprise — set
- * PUMP_PLATFORM_FEE_BPS=100 to charge 1% (matching pump.fun's trade fee) once
- * trading has been verified. Clamped to [0, MAX_FEE_BPS]. The fee also requires
- * a configured recipient (pumpFeeRecipient), so both knobs must be set to bill.
+ * The platform trade-fee rate in basis points: 1% (100) of every customer trade
+ * three.ws builds or signs, the rate the owner set on 2026-09-16.
+ * PUMP_PLATFORM_FEE_BPS overrides it (0 turns it off). Clamped to
+ * [0, MAX_FEE_BPS]. The fee also requires a resolvable recipient
+ * (pumpFeeRecipient), so an environment with no treasury bills nothing.
* @returns {number}
*/
export function pumpPlatformFeeBps() {
const raw = process.env.PUMP_PLATFORM_FEE_BPS;
- const n = raw == null || String(raw).trim() === '' ? 0 : parseInt(raw, 10);
+ 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);
}
@@ -228,4 +228,55 @@ export function txPaidPlatformFee(tx, fee, quoteMint) {
return sum(meta.postTokenBalances) - sum(meta.preTokenBalances) >= want;
}
+const platformOwnerCache = new Map(); // userId -> { at, owned }
+const PLATFORM_OWNER_TTL_MS = 10 * 60_000;
+
+/**
+ * True when the account is one of the platform's own agent owners. Their trades
+ * (the $THREE circulation desk, house fleets, buybacks run through agent
+ * wallets) are three.ws moving its own money, so they are never billed.
+ * @param {string|null|undefined} userId
+ */
+export async function isPlatformOwnedUser(userId) {
+ if (!userId) return false;
+ const hit = platformOwnerCache.get(userId);
+ if (hit && Date.now() - hit.at < PLATFORM_OWNER_TTL_MS) return hit.owned;
+ const [{ sql }, { isPlatformOwnedAgent }] = await Promise.all([
+ import('./db.js'),
+ import('./custodial-key-health.js'),
+ ]);
+ const [row] = await sql`select email from users where id = ${userId} limit 1`;
+ const owned = isPlatformOwnedAgent(row?.email);
+ platformOwnerCache.set(userId, { at: Date.now(), owned });
+ return owned;
+}
+
+/**
+ * The trade fee for a server-signed agent trade: 1% of the quote spent on a
+ * buy, or of the guaranteed minimum quote out on a sell (the minimum, so a sell
+ * that fills at the slippage floor still covers its own fee). Returns null for
+ * a platform-owned account or when no fee applies.
+ *
+ * @param {object} o
+ * @param {'mainnet'|'devnet'} o.network
+ * @param {PublicKey|string} o.payer the agent wallet that signs
+ * @param {string|null} o.userId the agent owner's account id
+ * @param {'buy'|'sell'} o.side
+ * @param {bigint|number|string} o.lamports quote atomics in (buy) or minimum out (sell):
+ * lamports for SOL, USDC base units for USDC
+ * @param {boolean} [o.isUsdc] the coin is USDC-quoted
+ * @param {string} [o.quoteMint] the USDC mint for a USDC-quoted coin
+ */
+export async function buildAgentTradeFee({ network, payer, userId, side, lamports, isUsdc = false, quoteMint }) {
+ if (await isPlatformOwnedUser(userId)) return null;
+ return buildPlatformFeeInstructions({
+ network,
+ payer,
+ isUsdc,
+ ...(isUsdc && quoteMint ? { quoteMintPk: quoteMint } : {}),
+ grossAtomics: lamports,
+ basis: side === 'buy' ? 'agent_buy' : 'agent_sell',
+ });
+}
+
export { WSOL_MINT, MAX_FEE_BPS };
diff --git a/api/agents/agent-trade.js b/api/agents/agent-trade.js
index 5b792efd9..913737e45 100644
--- a/api/agents/agent-trade.js
+++ b/api/agents/agent-trade.js
@@ -45,6 +45,7 @@ import {
} from '../_lib/agent-trade-guards.js';
import { assessTradeSafety, recordFirewallDecision, firewallGuardResponse } from '../_lib/trade-firewall.js';
import { submitProtected } from '../_lib/execution-engine.js';
+import { buildAgentTradeFee } from '../_lib/pump-platform-fee.js';
const WSOL_MINT = 'So11111111111111111111111111111111111111112';
const CONFIRM_TIMEOUT_MS = 45_000;
@@ -245,7 +246,7 @@ async function buildTradeInstructions({ ctx, side, venue, mintPk, ownerPk, lampo
// shape. Buys are gated on the lamport caps + USD ceiling + balance; sells only
// move SOL inward, so they skip the spend caps but still honor the kill switch,
// the price-impact breaker, and a fee-headroom floor.
-async function runGuards({ id, side, tradeLimits, prep, walletLamports, network, meta, mintPk, ownerPk, userId }) {
+async function runGuards({ id, side, tradeLimits, prep, walletLamports, network, meta, mintPk, ownerPk, userId, feeLamports = 0n }) {
const killed = checkKillSwitch(tradeLimits.kill_switch);
if (killed) return tradeGuardResponse(killed);
@@ -279,7 +280,7 @@ async function runGuards({ id, side, tradeLimits, prep, walletLamports, network,
throw e;
}
- const headroom = checkSolHeadroom(walletLamports, lamports, SOL_FEE_HEADROOM_LAMPORTS);
+ const headroom = checkSolHeadroom(walletLamports, BigInt(lamports) + BigInt(feeLamports), SOL_FEE_HEADROOM_LAMPORTS);
if (headroom) return tradeGuardResponse(headroom);
// Rug/honeypot firewall — a REAL on-chain simulated buy→sell round-trip +
@@ -499,10 +500,22 @@ export async function executeAgentTrade({ id, userId, meta, input, req = null, s
try { prep.usdValue = await lamportsToUsd(prep.lamports); } catch { prep.usdValue = null; }
}
+ // The three.ws trade fee rides in the trade transaction: on the SOL spent for a
+ // buy, on the guaranteed minimum SOL out for a sell. Priced before the guards
+ // so the SOL headroom check covers it. Platform-owned agents pay nothing.
+ let tradeFee;
+ try {
+ tradeFee = await buildAgentTradeFee({ network, payer: ownerPk, userId, side, lamports: side === 'buy' ? prep.lamports : prep.minOutRaw });
+ } catch (e) {
+ console.error('[agents/agent-trade] fee build failed', e?.message);
+ return fail(502, 'fee_build_failed', 'could not price the trade fee, try again');
+ }
+ const feeLamports = tradeFee ? BigInt(tradeFee.disclosure.amount) : 0n;
+
// Run the shared guardrails — identical for manual + strategy trades.
let blocked;
try {
- blocked = await runGuards({ id, side, tradeLimits, prep, walletLamports, network, meta, mintPk: input.mintPk, ownerPk, userId });
+ blocked = await runGuards({ id, side, tradeLimits, prep, walletLamports, network, meta, mintPk: input.mintPk, ownerPk, userId, feeLamports });
} catch (e) {
console.error('[agents/agent-trade] guard check failed', e?.message);
return fail(502, 'guard_check_failed', 'could not verify the trade guardrails — try again');
@@ -520,6 +533,7 @@ export async function executeAgentTrade({ id, userId, meta, input, req = null, s
console.error('[agents/agent-trade] build failed', e?.message);
return fail(502, 'build_failed', 'could not build the trade — try again');
}
+ if (tradeFee) built.instructions = [...built.instructions, ...tradeFee.instructions];
const ledgerMeta = {
side, mint: input.mint, venue: prep.venue, slippage_bps: input.slippageBps,
@@ -527,6 +541,7 @@ export async function executeAgentTrade({ id, userId, meta, input, req = null, s
expected_out: prep.expectedOutRaw.toString(),
min_out: prep.minOutRaw.toString(),
...(side === 'sell' ? { base_amount: prep.baseAmount.toString(), token_decimals: prep.decimals } : {}),
+ ...(tradeFee ? { platform_fee: tradeFee.disclosure } : {}),
...(isStrategy ? { source: 'strategy', strategy: sourceMeta?.strategy ?? null, strategy_id: sourceMeta?.strategy_id ?? null, equip_id: sourceMeta?.equip_id ?? null } : {}),
};
@@ -758,8 +773,12 @@ async function handleQuote(req, res, id) {
try { prep.usdValue = await lamportsToUsd(prep.lamports); } catch { prep.usdValue = null; }
}
+ let tradeFee = null;
+ try { tradeFee = await buildAgentTradeFee({ network, payer: ownerPk, userId: auth.userId, side, lamports: side === 'buy' ? prep.lamports : prep.minOutRaw }); } catch { tradeFee = null; }
+ const feeLamports = tradeFee ? BigInt(tradeFee.disclosure.amount) : 0n;
+
let blocked = null;
- try { blocked = await runGuards({ id, side, tradeLimits, prep, walletLamports, network, meta, mintPk: input.mintPk, ownerPk, userId: auth.userId }); } catch { blocked = null; }
+ try { blocked = await runGuards({ id, side, tradeLimits, prep, walletLamports, network, meta, mintPk: input.mintPk, ownerPk, userId: auth.userId, feeLamports }); } catch { blocked = null; }
return json(res, 200, {
data: {
@@ -770,6 +789,7 @@ async function handleQuote(req, res, id) {
? { sol_in: lamportsToSol(prep.lamports), expected_tokens_out: prep.expectedOutRaw.toString() }
: { tokens_in: prep.baseAmount.toString(), token_decimals: prep.decimals, expected_sol_out: lamportsToSol(prep.expectedOutRaw) }),
min_out: prep.minOutRaw.toString(),
+ platform_fee: tradeFee ? tradeFee.disclosure : null,
wallet_balance_sol: Number(walletLamports) / 1e9,
allowed: !blocked,
blocked_reason: blocked ? { code: blocked.code, message: blocked.message, detail: blocked.detail } : null,
diff --git a/api/agents/pumpfun/[action].js b/api/agents/pumpfun/[action].js
index 5ffa24d65..2bef5b991 100644
--- a/api/agents/pumpfun/[action].js
+++ b/api/agents/pumpfun/[action].js
@@ -28,6 +28,7 @@ import { limits, clientIp } from '../../_lib/rate-limit.js';
import { isUuid } from '../../_lib/validate.js';
import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
import { submitProtected } from '../../_lib/execution-engine.js';
+import { buildAgentTradeFee } from '../../_lib/pump-platform-fee.js';
import { reserveSpend, finalizeSpend, releaseSpend } from '../../_lib/agent-spend-policy.js';
import { grindMintKeypair } from '../../_lib/pump-vanity.js';
import { isRpcOutageError } from '../../_lib/rpc-degrade.js';
@@ -291,6 +292,14 @@ async function handleBuy(req, res, id) {
return respondError(res, err.status || 422, err.code || 'build_failed', err);
}
+ // three.ws trade fee on the quote spent, in the same transaction.
+ const tradeFee = await buildAgentTradeFee({
+ network: body.network, payer: keypair.publicKey, userId: auth.userId, side: 'buy',
+ lamports: quoteAtomics.toString(), isUsdc: quote.isUsdc, quoteMint: quote.quoteMint,
+ });
+ if (tradeFee) instructions = [...instructions, ...tradeFee.instructions];
+ const feeSol = tradeFee && tradeFee.disclosure.asset === 'SOL' ? Number(tradeFee.disclosure.amount) / 1e9 : 0;
+
// Reserve against the daily SOL cap for SOL spends only — atomically, BEFORE
// sending, so two concurrent buys on a stolen session can't both slip past
// the limit. USDC buys move USDC, not SOL, so they are gated by the up-front
@@ -301,7 +310,7 @@ async function handleBuy(req, res, id) {
agentId: id,
meta,
mint: body.mint,
- solAmount: body.solAmount,
+ solAmount: body.solAmount + feeSol,
type: 'pumpfun.buy',
payload: { slippageBps: body.slippageBps, network: body.network },
});
@@ -1170,6 +1179,15 @@ async function handleSell(req, res, id) {
return respondError(res, err.status || 422, err.code || 'build_failed', err);
}
+ // three.ws trade fee on the slippage-floor proceeds, in the same transaction.
+ const sellSlippageBps = Number.isFinite(body.slippageBps) ? body.slippageBps : 500;
+ const tradeFee = await buildAgentTradeFee({
+ network: body.network, payer: keypair.publicKey, userId: auth.userId, side: 'sell',
+ lamports: (BigInt(expectedQuoteStr) * BigInt(Math.max(0, 10_000 - sellSlippageBps))) / 10_000n,
+ isUsdc: quote.isUsdc, quoteMint: quote.quoteMint,
+ });
+ if (tradeFee) instructions = [...instructions, ...tradeFee.instructions];
+
let signature;
try {
// Protected send: priority fee + CU estimate, rebroadcast with blockhash
@@ -1352,6 +1370,7 @@ async function handleSwap(req, res, id) {
let instructions;
let quotedAmount;
+ let feeBasis = null; // quote atomics the trade fee is charged on
try {
if (body.side === 'buy') {
// Spend the pool's quote asset: USDC atomics (6dp) or SOL lamports.
@@ -1396,6 +1415,7 @@ async function handleSwap(req, res, id) {
}
instructions = await amm.buyQuoteInput(swapState, quoteIn, slippage);
+ feeBasis = BigInt(quoteIn.toString());
quotedAmount = quote.isUsdc
? { quote_usdc_atomics: quoteIn.toString() }
: { quote_lamports: quoteIn.toString() };
@@ -1426,6 +1446,8 @@ async function handleSwap(req, res, id) {
});
const expected = r?.uiQuote ?? r?.minQuote ?? null;
if (expected != null) {
+ const swapSlippageBps = Number.isFinite(body.slippageBps) ? body.slippageBps : 500;
+ feeBasis = (BigInt(expected.toString()) * BigInt(Math.max(0, 10_000 - swapSlippageBps))) / 10_000n;
quotedAmount[quote.isUsdc ? 'expectedUsdcAtomics' : 'expectedSolLamports'] =
expected.toString();
}
@@ -1438,6 +1460,15 @@ async function handleSwap(req, res, id) {
return error(res, 422, 'build_failed', err.message || 'could not build swap ix');
}
+ // three.ws trade fee in the same transaction. A sell whose proceeds could not
+ // be quoted has no basis to bill and goes through without it.
+ const tradeFee = feeBasis == null ? null : await buildAgentTradeFee({
+ network: body.network, payer: keypair.publicKey, userId: auth.userId, side: body.side,
+ lamports: feeBasis, isUsdc: quote.isUsdc, quoteMint: quote.quoteMint,
+ });
+ if (tradeFee) instructions = [...instructions, ...tradeFee.instructions];
+ const feeSol = tradeFee && tradeFee.disclosure.asset === 'SOL' ? Number(tradeFee.disclosure.amount) / 1e9 : 0;
+
// A SOL swap-buy is a SOL outflow — reserve it against the daily cap atomically
// before sending (closes the concurrent-spend TOCTOU). USDC buys move USDC, not
// SOL (gated by the balance check above); sells are inflows. Neither reserves.
@@ -1447,7 +1478,7 @@ async function handleSwap(req, res, id) {
agentId: id,
meta,
mint: body.mint,
- solAmount: body.solAmount,
+ solAmount: body.solAmount + feeSol,
type: 'pumpfun.swap.buy',
payload: { slippageBps: body.slippageBps, network: body.network, venue: 'amm' },
});
diff --git a/api/agents/solana-trade.js b/api/agents/solana-trade.js
index 83714d1b7..677b8abac 100644
--- a/api/agents/solana-trade.js
+++ b/api/agents/solana-trade.js
@@ -44,6 +44,7 @@ import { getBuyQuote, getSellQuote } from '../_lib/solana/sdk-bridge.js';
import { getAmmPoolState } from '../_lib/pump.js';
import { assessTradeSafety, recordFirewallDecision } from '../_lib/trade-firewall.js';
import { submitProtected } from '../_lib/execution-engine.js';
+import { buildAgentTradeFee } from '../_lib/pump-platform-fee.js';
const LAMPORTS_PER_SOL = 1_000_000_000;
const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
@@ -437,9 +438,16 @@ export async function handleTrade(req, res, id) {
try { walletLamports = BigInt(await solanaPublicConnection(network).getBalance(ownerPk, 'confirmed')); }
catch { walletLamports = null; }
}
+ let feeBps = 0;
+ try {
+ const feeLib = await import('../_lib/pump-platform-fee.js');
+ feeBps = (await feeLib.isPlatformOwnedUser(auth.userId)) ? 0 : await feeLib.effectivePumpFeeBps();
+ } catch { feeBps = 0; }
+
let fundsWarning = null;
if (walletLamports != null) {
- const spendLamports = side === 'buy' ? BigInt(quote.inAtomics) : 0n;
+ // A buy also pays the three.ws trade fee out of the same wallet.
+ const spendLamports = side === 'buy' ? BigInt(quote.inAtomics) + (BigInt(quote.inAtomics) * BigInt(feeBps)) / 10_000n : 0n;
const head = checkSolHeadroom(walletLamports, spendLamports, SOL_FEE_HEADROOM_LAMPORTS);
if (head) {
const needed = spendLamports + SOL_FEE_HEADROOM_LAMPORTS;
@@ -453,9 +461,6 @@ export async function handleTrade(req, res, id) {
}
}
- let feeBps = 0;
- try { feeBps = await (await import('../_lib/pump-platform-fee.js')).effectivePumpFeeBps(); } catch { feeBps = 0; }
-
const quotePayload = {
side, mint: mintStr, network, venue: quote.venue, graduated: quote.graduated,
slippage_bps: slippageBps,
@@ -547,7 +552,7 @@ export async function handleTrade(req, res, id) {
let instructions;
try {
- instructions = await buildTradeInstructions({ side, conn: readConn, network, mintPk, ownerPk: keypair.publicKey, quote, slippageBps, solAmount, tokenAmountRaw });
+ instructions = await buildTradeInstructions({ userId: auth.userId, side, conn: readConn, network, mintPk, ownerPk: keypair.publicKey, quote, slippageBps, solAmount, tokenAmountRaw });
} catch (e) {
await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'build_failed', message: (e?.message || '').slice(0, 200) } }).catch(() => {});
if (e?.status) return error(res, e.status, e.code, e.message);
@@ -614,10 +619,24 @@ export async function handleTrade(req, res, id) {
});
}
-// Build the on-chain instructions for the resolved venue + side. Curve trades use
-// the pump-sdk v2 builders; graduated trades use the pump-swap AMM SDK. Mirrors
-// api/agents/pumpfun/[action].js so there is one instruction-building convention.
-export async function buildTradeInstructions({ side, conn, network, mintPk, ownerPk, quote, slippageBps, solAmount, tokenAmountRaw }) {
+// Build the on-chain instructions for the resolved venue + side, with the
+// three.ws trade fee appended for customer-owned agents. Every server-signed
+// caller (the trade endpoint, strategies, mirror trading) builds here, so the
+// fee cannot be skipped by picking a different entry point. `userId` is the
+// agent owner; platform-owned accounts are never billed.
+export async function buildTradeInstructions({ userId = null, ...args }) {
+ const swap = await buildSwapInstructions(args);
+ const instructions = Array.isArray(swap) ? [...swap] : [swap];
+ const lamports = args.side === 'buy' ? args.quote.inAtomics : args.quote.minOutAtomics;
+ const fee = await buildAgentTradeFee({ network: args.network, payer: args.ownerPk, userId, side: args.side, lamports });
+ if (fee) instructions.push(...fee.instructions);
+ return instructions;
+}
+
+// Curve trades use the pump-sdk v2 builders; graduated trades use the pump-swap
+// AMM SDK. Mirrors api/agents/pumpfun/[action].js so there is one
+// instruction-building convention.
+async function buildSwapInstructions({ side, conn, network, mintPk, ownerPk, quote, slippageBps, solAmount, tokenAmountRaw }) {
const BNmod = (await import('bn.js')).default;
if (quote.venue === 'bonding_curve') {
diff --git a/data/changelog.json b/data/changelog.json
index 0418c6977..2397b99fa 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-09-16",
+ "title": "A flat 1% fee on trades made through three.ws",
+ "summary": "Trades that three.ws builds or runs for you now carry a 1% fee, paid in the same transaction as the trade: buys and sells in the coin trade window, trades from your agent's wallet, and trades your agents make through strategies, mirror trading, orders, market making and sniping. The fee is shown before you confirm, both in the trade window and in the agent wallet's trade tab. Trades you make on other apps are not affected, and three.ws's own agents are never charged.",
+ "tags": [
+ "improvement"
+ ],
+ "link": "/legal/tos"
+ },
{
"date": "2026-09-16",
"title": "Deploy your agent on-chain with Solana's new transaction v1",
diff --git a/docs/launchpad.md b/docs/launchpad.md
index 082300bba..1e4e3b0bb 100644
--- a/docs/launchpad.md
+++ b/docs/launchpad.md
@@ -39,7 +39,9 @@ reaches the browser, so the wallet adds exactly one signature.
| three.ws launch fee | platform treasury | 1% of the dev buy (`PUMP_LAUNCH_FEE_BPS`) |
The launch fee rides in the same transaction and is shown in the cost panel before you sign. No dev
-buy, no fee. Details and env vars: [pump-platform-fee.md](./pump-platform-fee.md#launch-fee-on-by-default).
+buy, no fee. After launch, every trade of the coin made through three.ws (the trade modal, agent
+wallets, strategies, snipers) carries the same 1% trade fee. Trades made on pump.fun or elsewhere
+do not. Details and env vars: [pump-platform-fee.md](./pump-platform-fee.md).
## Transaction formats
diff --git a/docs/pump-platform-fee.md b/docs/pump-platform-fee.md
index 4f10db6b4..7c2f74d79 100644
--- a/docs/pump-platform-fee.md
+++ b/docs/pump-platform-fee.md
@@ -1,57 +1,54 @@
# Pump.fun platform trade fee
-three.ws can charge a platform fee on every pump.fun buy/sell routed through the
-trade modal (`src/game/coin-buy.js` → `/api/pump/buy-prep` · `/api/pump/sell-prep`).
-The fee matches pump.fun's own trade-fee rate and is a **real on-chain transfer
-added to the same transaction the user signs** — native SOL for SOL-paired
-trades, USDC for USDC-paired trades — sent to the platform fee wallet. One
-signature, no custody.
-
-## Status: OFF by default
-
-The fee ships **inert**. It activates only when BOTH are configured:
+three.ws charges **1% of trading volume on every customer trade it builds or signs**. The fee is a
+**real on-chain transfer inside the same transaction as the trade** (native SOL for SOL-paired
+coins, USDC for USDC-paired coins) to the platform treasury. One transaction, no custody, no second
+signature.
+
+## Where it applies
+
+| Surface | Path | Fee basis |
+|---|---|---|
+| Trade modal (your wallet signs) | `src/game/coin-buy.js` → `/api/pump/buy-prep` · `/api/pump/sell-prep` | quote spent (buy) / expected proceeds (sell) |
+| Agent wallet trade tab + `/api/agents/:id/solana/trade` | `api/agents/solana-trade.js` `buildTradeInstructions` | SOL spent / minimum SOL out |
+| Agent strategies and mirror trading | same builder (`agent-strategy-runtime.js`, `agent-mirror.js`) | SOL spent / minimum SOL out |
+| `/api/agents/:id/trade`, the market-maker (`workers/agent-mm`), programmable orders (`workers/agent-orders`) | `api/agents/agent-trade.js` `executeAgentTrade` | SOL spent / minimum SOL out |
+| Sniper buys and sells (`workers/agent-sniper/executor.js`) | appended before broadcast; included in the position's cost basis and P&L | SOL spent / slippage-floor proceeds |
+| Agent pump.fun buy, sell, AMM swap (`/api/agents/:id/pumpfun/*`) | `api/agents/pumpfun/[action].js` | quote spent / slippage-floor proceeds |
+| Coin launches | the dev buy, see [Launch fee](#launch-fee-on-by-default) | dev buy |
+
+Server-signed sells are billed on the **minimum** proceeds the slippage setting guarantees, so a
+sell that fills at its floor always covers its own fee.
+
+**Not billed:**
+- **Platform-owned agents** (owner account `[email protected]` or `@agents.three.ws`,
+ `isPlatformOwnedAgent`): the $THREE circulation desk, house sniper fleets and other three.ws
+ money movements (`isPlatformOwnedUser` in `api/_lib/pump-platform-fee.js`).
+- **Trades made outside three.ws.** A trade on pump.fun, a terminal or another app never touches
+ our transaction builders, and the pump.fun program has no third-party fee hook, so there is
+ nothing to attach a fee to.
+- The embeddable agent-skills SDK's direct client-built trades (`src/agent-skills-pumpfun.js`
+ without `serverFlow`): that library signs with the site visitor's own wallet on third-party
+ pages. Its `serverFlow` mode goes through `buy-prep`/`sell-prep` and is billed.
+
+## Configuration
| Env var | Effect |
|---|---|
-| `PUMP_PLATFORM_FEE_BPS` | Rate in basis points. **Default `0` (off).** Set `100` for 1% (pump.fun's rate). Hard-capped at 500 (5%). |
-| `PUMP_PLATFORM_FEE_WALLET` | Recipient Solana address. Falls back to the platform treasury keypair (`PLATFORM_TREASURY_KEYPAIR` / `TREASURY_KEYPAIR`) pubkey if unset. |
-
-With either knob missing/zero, `buildPlatformFeeInstructions` returns `null`, no
-fee instruction is added, and the quote/UI report `platform_fee_bps: 0` (no fee
-line shown). This is why local/preview and a fresh deploy charge nothing — and
-why turning it on is a deliberate one-line env change after trading is verified.
-
-## How it's computed
-
-- **Buy:** fee = `bps × quote spent`, charged on top (you pay trade + fee).
-- **Sell:** fee = `bps × expected proceeds`, taken from the proceeds. AMM-sell
- proceeds are quoted via the pump-swap SDK's `sellBaseInput` (`uiQuote`); if
- that quote can't be derived the fee is skipped, never the sell.
-
-All four routes are covered: bonding-curve buy/sell and PumpSwap AMM buy/sell,
-for both SOL- and USDC-paired coins (`api/_lib/pump-platform-fee.js`).
-
-## Disclosure (required before enabling)
-
-The fee is **never** charged silently. When `platform_fee_bps > 0`:
+| `PUMP_PLATFORM_FEE_BPS` | Trade fee in basis points. **Default `100` (1%).** `0` turns it off. Hard-capped at 500 (5%). |
+| `PUMP_PLATFORM_FEE_WALLET` | Recipient Solana address. Falls back to the platform treasury keypair (`PLATFORM_TREASURY_KEYPAIR` / `TREASURY_KEYPAIR`) pubkey. |
-1. The trade modal shows a live fee line ("Platform fee 1% · ~0.01 SOL") and the
- exact amount at the wallet-approval step (`coin-buy.js#_renderFee` / `_feeNote`).
-2. **Before flipping the rate on in production, add a fees clause to the Terms**
- stating that three.ws charges a trading fee at pump.fun's rate on trades
- routed through the platform, and add a public changelog entry. Disclosure in
- the UI is already wired; the Terms + changelog are the remaining steps and
- must land in the same change that enables the fee.
+With no recipient resolvable, `buildPlatformFeeInstructions` returns `null`, no fee instruction is
+added and quotes report `platform_fee_bps: 0`, so a local environment without the treasury bills
+nothing.
-## Enable checklist
+## Disclosure
-1. Verify SOL + USDC buy/sell end-to-end with the fee at 0.
-2. Set `PUMP_PLATFORM_FEE_WALLET` (or confirm the treasury keypair pubkey is the
- intended recipient).
-3. Add the Terms fees clause + a changelog entry.
-4. Set `PUMP_PLATFORM_FEE_BPS=100`.
-5. Confirm the modal shows the fee line and a test trade routes the fee to the
- wallet.
+- The trade modal shows a fee line and the exact amount at the wallet-approval step.
+- The agent wallet trade tab shows a "three.ws fee" row with the SOL amount before the trade.
+- Agent trade previews and results carry `platform_fee` (`bps`, `asset`, `amount`, `recipient`, `basis`),
+ and the custody ledger row records it.
+- Section 8 of the [Terms](https://three.ws/legal/tos) discloses platform fees on Real-Funds Features.
## Launch fee (on by default)
diff --git a/public/changelog-recent.json b/public/changelog-recent.json
index 6de8ae002..cd5a59dde 100644
--- a/public/changelog-recent.json
+++ b/public/changelog-recent.json
@@ -1,11 +1,11 @@
{
- "generated_at": "2026-09-16T20:04:22.550Z",
+ "generated_at": "2026-09-16T21:09:38.691Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
- "total": 3687,
+ "total": 3688,
"complete": false,
"full_feed": "/changelog.json",
"entries": [
@@ -31,6 +31,16 @@
"fix"
]
},
+ {
+ "date": "2026-09-16",
+ "type": "update",
+ "title": "A flat 1% fee on trades made through three.ws",
+ "summary": "Trades that three.ws builds or runs for you now carry a 1% fee, paid in the same transaction as the trade: buys and sells in the coin trade window, trades from your agent's wallet, and trades your agents make through strategies, mirror trading, orders, market making and sniping. The fee is shown before you confirm, both in the trade window and in the agent wallet's trade tab. Trades you make on other apps are not affected, and three.ws's own agents are never charged.",
+ "link": "/legal/tos",
+ "tags": [
+ "improvement"
+ ]
+ },
{
"date": "2026-09-16",
"type": "update",
@@ -1609,16 +1619,6 @@
"tags": [
"launch"
]
- },
- {
- "date": "2026-09-07",
- "type": "launch",
- "title": "Portfolio universe",
- "summary": "Every asset a Robinhood Chain portfolio may hold, priced live: tokenized equities, crypto majors and chain-native tokens with on-chain liquidity, 24h volume, price change and the NAV premium against each equity's Chainlink feed. Sortable and filterable by asset class.",
- "link": "/markets/robinhood/portfolios/universe",
- "tags": [
- "launch"
- ]
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index a80cff77d..85ec38a46 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-16T20:04:22.004Z",
+ "generated_at": "2026-09-16T21:09:38.669Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -28,6 +28,16 @@
"fix"
]
},
+ {
+ "date": "2026-09-16",
+ "type": "update",
+ "title": "A flat 1% fee on trades made through three.ws",
+ "summary": "Trades that three.ws builds or runs for you now carry a 1% fee, paid in the same transaction as the trade: buys and sells in the coin trade window, trades from your agent's wallet, and trades your agents make through strategies, mirror trading, orders, market making and sniping. The fee is shown before you confirm, both in the trade window and in the agent wallet's trade tab. Trades you make on other apps are not affected, and three.ws's own agents are never charged.",
+ "link": "/legal/tos",
+ "tags": [
+ "improvement"
+ ]
+ },
{
"date": "2026-09-16",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index fec2641e2..77bdcd2cc 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -22,6 +22,14 @@
<category>feature</category>
<description>three.ws/launch is rebuilt around one flow: pick one of your 3D agents, name the coin, and launch it on pump.fun from your wallet or from the agent's own wallet. The coin's metadata links your agent's page and 3D body, a live preview and cost panel show exactly what you will pay (including a 1% three.ws fee on the dev buy), and a new My coins tab shows unclaimed creator rewards and claims them in one click, no pump.fun app needed. Launches now fit in a single transaction thanks to pump.fun's lookup table, and larger ones, like USDC-paired coins with a dev buy, use Solana transaction v1 automatically when your wallet supports it. This also fixes launches that were failing because an on-chain buyback program stopped accepting new agents.</description>
</item>
+ <item>
+ <title>A flat 1% fee on trades made through three.ws</title>
+ <link>https://three.ws/legal/tos</link>
+ <guid isPermaLink="false">2026-09-16:A flat 1% fee on trades made through three.ws</guid>
+ <pubDate>Wed, 16 Sep 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Trades that three.ws builds or runs for you now carry a 1% fee, paid in the same transaction as the trade: buys and sells in the coin trade window, trades from your agent's wallet, and trades your agents make through strategies, mirror trading, orders, market making and sniping. The fee is shown before you confirm, both in the trade window and in the agent wallet's trade tab. Trades you make on other apps are not affected, and three.ws's own agents are never charged.</description>
+ </item>
<item>
<title>Deploy your agent on-chain with Solana's new transaction v1</title>
<link>https://three.ws/deploy-onchain</link>
diff --git a/public/features.json b/public/features.json
index 1612abe8d..7591c7ab8 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-16T20:04:21.849Z",
+ "generated_at": "2026-09-16T21:09:38.654Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/legal/tos.html b/public/legal/tos.html
index 2c3a76551..efecef772 100644
--- a/public/legal/tos.html
+++ b/public/legal/tos.html
@@ -104,7 +104,7 @@
<li data-i18n-html="legal_tos.total_loss_is_possible_digital_assets_are"><strong>Total loss is possible.</strong> Digital assets are volatile and speculative; any amount you commit can be lost entirely, quickly, and permanently. Blockchain transactions are irreversible.</li>
<li data-i18n-html="legal_tos.nothing_on_the_service_is_financial_investme"><strong>Nothing on the Service is financial, investment, legal, accounting, or tax advice</strong>, or a recommendation to buy, sell, or hold any asset. We are not your broker, adviser, or fiduciary, and no fiduciary duty is created by your use of the Service.</li>
<li data-i18n-html="legal_tos.autonomous_features_act_on_your_instructions"><strong>Autonomous features act on your instructions.</strong> Features you enable (autopilot, strategies, agent delegation) can transact on your behalf without asking again. You are responsible for what you enable and for monitoring it.</li>
- <li><strong>Platform fees are shown before you sign.</strong> Some Real-Funds Features carry a three.ws fee on top of network and third-party fees, for example a percentage of the dev buy when you launch a coin through three.ws. The fee is shown in the interface before you approve, travels in the same transaction you sign, and is non-refundable once that transaction confirms.</li>
+ <li><strong>Platform fees are shown before you sign.</strong> Some Real-Funds Features carry a three.ws fee on top of network and third-party fees, for example 1% of the value of each trade three.ws builds or executes for you or your agents, including the dev buy when you launch a coin. The fee is shown in the interface before you approve, travels in the same transaction you sign, and is non-refundable once that transaction confirms.</li>
<li data-i18n-html="legal_tos.taxes_are_yours_you_are_solely_responsible"><strong>Taxes are yours.</strong> You are solely responsible for determining and paying any taxes that apply to your transactions.</li>
</ul>
diff --git a/src/agent-wallet-hub/tabs/trade.js b/src/agent-wallet-hub/tabs/trade.js
index 78b8f6ff7..27179d99f 100644
--- a/src/agent-wallet-hub/tabs/trade.js
+++ b/src/agent-wallet-hub/tabs/trade.js
@@ -611,13 +611,21 @@ registerWalletTab({
<div class="awh-tr-qrow"><dt>Minimum received</dt><dd>${esc(minStr)}</dd></div>
<div class="awh-tr-qrow"><dt>Price impact</dt><dd class="${impactCls}">${impact.toFixed(2)}%</dd></div>
<div class="awh-tr-qrow"><dt>Max slippage</dt><dd>${(state.slippageBps / 100).toFixed(state.slippageBps % 100 ? 1 : 0)}%</dd></div>
- <div class="awh-tr-qrow"><dt>Route</dt><dd>${q.venue === 'amm' ? 'AMM pool' : 'Bonding curve'}${feeBps > 0 ? ` · ${(feeBps / 100).toFixed(2)}% fee` : ''}</dd></div>
+ <div class="awh-tr-qrow"><dt>Route</dt><dd>${q.venue === 'amm' ? 'AMM pool' : 'Bonding curve'}</dd></div>
+ ${feeBps > 0 ? `<div class="awh-tr-qrow"><dt>three.ws fee · ${feeBps / 100}%</dt><dd>${esc(feeLine(q, feeBps))}</dd></div>` : ''}
${impact >= IMPACT_WARN ? `<div class="awh-tr-quote-note is-warn">⚠ High price impact (${impact.toFixed(1)}%). You may receive significantly less than the market rate.</div>` : ''}
${guard ? `<div class="awh-tr-quote-note is-err">⚠ ${esc(guard.message)}</div>` : ''}
${funds ? `<div class="awh-tr-quote-note is-err">⚠ ${esc(funds.message)}</div>` : ''}
</dl>`;
}
+ // The fee is charged on the SOL spent (buy) or the minimum SOL received (sell),
+ // the same basis the server bills, so this is the exact amount at most.
+ function feeLine(q, feeBps) {
+ const basis = Number(state.side === 'buy' ? q.in?.amount : q.min_received?.amount);
+ return Number.isFinite(basis) && basis > 0 ? `◎${formatSol((basis * feeBps) / 10_000)}` : `${feeBps / 100}% of the trade`;
+ }
+
function actionsInnerHtml() {
const args = tradeArgs();
const q = state.quote;
diff --git a/tests/pump-trade-fee.test.js b/tests/pump-trade-fee.test.js
new file mode 100644
index 000000000..5f7d8fb60
--- /dev/null
+++ b/tests/pump-trade-fee.test.js
@@ -0,0 +1,63 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const users = vi.hoisted(() => new Map());
+vi.mock('../api/_lib/db.js', () => ({
+ sql: async (strings, ...values) => {
+ const email = users.get(values[0]);
+ return email ? [{ email }] : [];
+ },
+}));
+
+const RECIPIENT = 'WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW';
+const PAYER = '5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9';
+
+describe('three.ws trade fee', () => {
+ let fee;
+ beforeEach(async () => {
+ vi.resetModules();
+ process.env.PUMP_PLATFORM_FEE_WALLET = RECIPIENT;
+ delete process.env.PUMP_PLATFORM_FEE_BPS;
+ users.clear();
+ users.set('customer-1', '[email protected]');
+ users.set('house-1', '[email protected]');
+ users.set('house-2', '[email protected]');
+ fee = await import('../api/_lib/pump-platform-fee.js');
+ });
+ afterEach(() => {
+ delete process.env.PUMP_PLATFORM_FEE_WALLET;
+ delete process.env.PUMP_PLATFORM_FEE_BPS;
+ });
+
+ it('charges 1% by default and can be turned off', () => {
+ expect(fee.pumpPlatformFeeBps()).toBe(100);
+ process.env.PUMP_PLATFORM_FEE_BPS = '0';
+ expect(fee.pumpPlatformFeeBps()).toBe(0);
+ process.env.PUMP_PLATFORM_FEE_BPS = '900';
+ expect(fee.pumpPlatformFeeBps()).toBe(500);
+ });
+
+ it('bills a customer agent buy 1% of the SOL spent, to the treasury', async () => {
+ const out = await fee.buildAgentTradeFee({ network: 'mainnet', payer: PAYER, userId: 'customer-1', side: 'buy', lamports: 250_000_000n });
+ expect(out.disclosure).toMatchObject({ bps: 100, asset: 'SOL', amount: '2500000', recipient: RECIPIENT, basis: 'agent_buy' });
+ expect(out.instructions).toHaveLength(1);
+ });
+
+ it('bills a sell on its minimum proceeds', async () => {
+ const out = await fee.buildAgentTradeFee({ network: 'mainnet', payer: PAYER, userId: 'customer-1', side: 'sell', lamports: '99000000' });
+ expect(out.disclosure).toMatchObject({ amount: '990000', basis: 'agent_sell' });
+ });
+
+ it('never bills the platform-owned agents', async () => {
+ expect(await fee.buildAgentTradeFee({ network: 'mainnet', payer: PAYER, userId: 'house-1', side: 'buy', lamports: 1_000_000_000n })).toBeNull();
+ expect(await fee.buildAgentTradeFee({ network: 'mainnet', payer: PAYER, userId: 'house-2', side: 'sell', lamports: 1_000_000_000n })).toBeNull();
+ });
+
+ it('bills a USDC-quoted trade in USDC', async () => {
+ const out = await fee.buildAgentTradeFee({
+ network: 'mainnet', payer: PAYER, userId: 'customer-1', side: 'buy', lamports: 50_000_000n,
+ isUsdc: true, quoteMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ });
+ expect(out.disclosure).toMatchObject({ asset: 'USDC', amount: '500000' });
+ expect(out.instructions).toHaveLength(2);
+ });
+});
diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.js
index 4a89e6942..11fc52473 100644
--- a/workers/agent-sniper/executor.js
+++ b/workers/agent-sniper/executor.js
@@ -27,6 +27,7 @@ import { getWalletBaseBalance, reconcileVanishedBag } from './reconcile.js';
import { assessTradeSafety, recordFirewallDecision, criticalFirewallReason } from '../../api/_lib/trade-firewall.js';
import { recordDecision } from '../../api/_lib/reasoning-ledger.js';
import { screenPush } from './screen-push.js';
+import { buildAgentTradeFee } from '../../api/_lib/pump-platform-fee.js';
// Self-rated conviction for a snipe entry, 0..1. Lower price impact and a clean
// firewall verdict raise it; a warned verdict and heavy impact lower it. This is
@@ -538,6 +539,13 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
const baseAmount = BigInt(built.expectedBaseTokens.toString());
if (baseAmount <= 0n) return await fail(posId, tag, 'zero_tokens');
+ // The three.ws trade fee rides in the buy transaction for customer agents
+ // and is part of the position's cost basis, so paper and live P&L both
+ // net it out. Platform-owned fleets pay nothing.
+ const buyFee = await buildAgentTradeFee({ network: cfg.network, payer: keypair.publicKey, userId: strat.user_id, side: 'buy', lamports: perTrade });
+ if (buyFee) built = { ...built, instructions: [...built.instructions, ...buyFee.instructions] };
+ const entryCost = perTrade + (buyFee ? BigInt(buyFee.disclosure.amount) : 0n);
+
let sig = 'SIMULATED';
// Execution telemetry — only set on a live broadcast; simulate keeps nulls
// (except a 'simulated' route marker so the UI can label paper fills).
@@ -573,7 +581,7 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
UPDATE agent_sniper_positions SET
status = 'open', buy_sig = ${sig},
error = ${ammEntry ? 'graduated:amm_entry' : null},
- entry_quote_lamports = ${perTrade.toString()},
+ entry_quote_lamports = ${entryCost.toString()},
base_amount = ${baseAmount.toString()},
entry_price_lamports_per_token = ${pricePerToken},
entry_price_impact_pct = ${Number(quote.priceImpactPct)},
@@ -595,7 +603,7 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
});
screenPush(`Bought $${(mint.symbol || mint.mint.slice(0, 6)).toUpperCase()} at ${lamportsToSol(perTrade).toFixed(4)} SOL — position open`, 'trade');
notifyBuy({ agentName: strat.agent_name || strat.agent_id, symbol: mint.symbol, mint: mint.mint, solSpent: lamportsToSol(perTrade), mode: cfg.mode, sig, chatId: strat.telegram_chat_id || null });
- await recordSnipeSpend({ agentId: strat.agent_id, userId: strat.user_id, network: cfg.network, lamports: perTrade, signature: sig, mode: cfg.mode, mint: mint.mint, capabilityId: spendCapabilityId });
+ await recordSnipeSpend({ agentId: strat.agent_id, userId: strat.user_id, network: cfg.network, lamports: entryCost, signature: sig, mode: cfg.mode, mint: mint.mint, capabilityId: spendCapabilityId });
await recordSnipeDecision({
strat, network: cfg.network, mint, posId, sig, mode: cfg.mode,
priceImpactPct: Number(quote.priceImpactPct), firewall: firewallSnapshot, perTradeLamports: perTrade,
@@ -735,6 +743,13 @@ export async function executeSell({ cfg, position, reason, fraction = 1, recover
}
}
+ // The trade fee on a sell is taken on the slippage-floor proceeds, so a fill
+ // at the floor still covers it, and it comes out of the leg's P&L.
+ const sellFloor = (BigInt(expectedOut) * BigInt(Math.max(0, Math.round((100 - slippagePct) * 100)))) / 10_000n;
+ const sellFee = await buildAgentTradeFee({ network: cfg.network, payer: keypair.publicKey, userId: position.user_id, side: 'sell', lamports: sellFloor });
+ if (sellFee) built = { ...built, instructions: [...built.instructions, ...sellFee.instructions] };
+ const sellFeeLamports = sellFee ? BigInt(sellFee.disclosure.amount) : 0n;
+
let sig = 'SIMULATED';
if (cfg.mode === 'live') {
sig = await signAndSend(ctx, keypair, built.instructions, cfg.confirmTimeoutMs);
@@ -747,7 +762,7 @@ export async function executeSell({ cfg, position, reason, fraction = 1, recover
// partial take-initials books the profit on just the half it sold and the
// remainder keeps its own proportional basis.
const soldCostBasis = partial ? (entryFull * ppm) / 1_000_000n : entryFull;
- const legPnl = expectedOut - soldCostBasis;
+ const legPnl = expectedOut - sellFeeLamports - soldCostBasis;
const priorRealized = BigInt(position.realized_pnl_lamports || '0');
const cumRealized = priorRealized + legPnl;