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(launchpad): preview and simulate launch fee schedules, accept swap referrals, validate shared fee vaults

nirholascb1743ee06c7
diff --git a/STRUCTURE.md b/STRUCTURE.md
index b39cecd4e..59bbd0fe4 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -373,7 +373,7 @@ packages, a generated standalone GitHub mirror). See
| Perpetual contract detail page | [pages/derivative.html](pages/derivative.html) + [src/derivative-page.js](src/derivative-page.js) + [src/derivative-page.css](src/derivative-page.css) `→ /derivative/:venue/:symbol` over [api/coin/derivative.js](api/coin/derivative.js); slug helper [src/shared/derivative-slug.js](src/shared/derivative-slug.js) vendored to [api/_lib/derivative-slug.js](api/_lib/derivative-slug.js); venue directory [api/_lib/derivative-venues.js](api/_lib/derivative-venues.js) | In-repo | Every row of `/derivatives` now opens a full contract page instead of dead-ending in the table: mark price against its own index and the basis between them, the funding rate turned into what a position you size yourself pays per interval, per day and per year, open interest and volume with the contract's rank across every venue listing that underlying, the underlying's spot chart, and a cross-venue funding table with callouts for the cheapest venue to hold a long, the best paid venue to hold a short, the funding spread and price dispersion (liquid venues only). Also reached from the contracts table on a derivatives venue's `/exchange/:id` profile. Tests: [tests/api/derivative-contract.test.js](tests/api/derivative-contract.test.js). Docs: [docs/coin-pages.md](docs/coin-pages.md) |
| Crypto news + archive + markets hub | [pages/markets.html](pages/markets.html) + [src/markets-page.js](src/markets-page.js) `→ /markets`, [pages/markets-news.html](pages/markets-news.html) + [src/markets-news.js](src/markets-news.js) `→ /markets/news`, [pages/news-article.html](pages/news-article.html) + [src/news-article.js](src/news-article.js) `→ /markets/news/article`, [pages/news-archive.html](pages/news-archive.html) + [src/news-archive.js](src/news-archive.js) `→ /markets/archive`, [pages/news-digest.html](pages/news-digest.html) + [src/news-digest.js](src/news-digest.js) `→ /markets/digest`; backend [api/news/](api/news) (feed, article, knowledge, archive, digest, rss, image) over [api/_lib/article-extract.js](api/_lib/article-extract.js) (page→reader→feed→preview ladder) and [api/_lib/news-rights.js](api/_lib/news-rights.js) (publisher rights layer, enforced at every read path), [api/_lib/news-coins.js](api/_lib/news-coins.js) (ticker→live market snapshot), [api/_lib/news-knowledge-store.js](api/_lib/news-knowledge-store.js) (durable `news_knowledge` corpus) + hourly archiver [api/cron/news-archive-append.js](api/cron/news-archive-append.js) over [api/_lib/news.js](api/_lib/news.js) + [api/_lib/news-sources.js](api/_lib/news-sources.js), corpus on `gs://three-ws-news-archive`, purge tooling [scripts/news-takedown-purge.mjs](scripts/news-takedown-purge.mjs) | In-repo | The Markets news wing + front door: /markets/news is “Your briefing”: live news aggregated natively from 197 publisher feeds (Featured/Trending/Saved tabs, breaking ticker, AI briefing card, top-stories hero + rail, search, sentiment, ticker chips, og:image preview resolution for imageless feeds), a rich article reader that shows a bounded lead excerpt plus our own summary/key points/entities/market context and sends the reader to the publisher for the rest (the excerpt cap and any rightsholder takedowns are enforced server-side across the reader, RSS mirror, archive search, and agent knowledge corpus, never just hidden client-side), and renders **live coin cards** (price/24h/7d/sparkline→/coin/:id) for detected tickers, and related coverage. Every read story is recorded to a durable **news knowledge base** (`GET /api/news/knowledge`) that grounds the 3D agents, itself subject to the same excerpt limit. Plus the largest open crypto-news archive (662,047 enriched articles, Sept 2017 → today, EN+中文, GCS-hosted) and the /markets hub aggregating global stats, the top-100 table, breaking news, and every market surface as a hero card. Docs: [docs/coin-pages.md](docs/coin-pages.md), [docs/api-reference.md](docs/api-reference.md), [docs/news-rights.md](docs/news-rights.md) (publisher takedown path) |
| Robinhood Chain markets + buy flow | Hub + detail pages [pages/markets-robinhood.html](pages/markets-robinhood.html) + [src/markets-robinhood.js](src/markets-robinhood.js) `→ /markets/robinhood`, [pages/robinhood-stock.html](pages/robinhood-stock.html) + [src/robinhood-stock.js](src/robinhood-stock.js) `→ /markets/robinhood/stock/:symbol`, [pages/robinhood-coin.html](pages/robinhood-coin.html) + [src/robinhood-coin.js](src/robinhood-coin.js) `→ /markets/robinhood/coin/:address`, buy flow [src/robinhood-purchase.js](src/robinhood-purchase.js), wallet desk [pages/hood-desk.html](pages/hood-desk.html) + [src/hood-desk.js](src/hood-desk.js) + [src/hood-desk.css](src/hood-desk.css) `→ /markets/robinhood/desk`; backend [api/_lib/robinhood.js](api/_lib/robinhood.js) + `api/v1/robinhood/{chain,stocks,stocks-detail,coins,coins-detail,launches,desk,wallet}.js` (free, the last two composed for the desk over [api/_lib/robinhood-desk.js](api/_lib/robinhood-desk.js)) + [api/x402/robinhood-portfolio.js](api/x402/robinhood-portfolio.js) (x402 paid) | In-repo | The 24/7 tokenized-equity board for Robinhood Chain (4663): live Chainlink NAV vs. Uniswap DEX premium for every Stock Token (one multicall, never 95 RPC calls), a memecoin screener across NOXA/The Odyssey launchpads (CoinGecko categories + on-chain launch logs via Blockscout), and chain TVL/gas/block stats. Detail pages add NAV history, holders, transfers, and contract links. Coin pages carry a real buy panel: injected-wallet connect, chain-switch to 4663, live Uniswap v3 `QuoterV2` quote + `SwapRouter02` swap with slippage, LI.FI bridge deep-link; Stock Tokens are display-only (tokenized securities, not offered to US persons) with an eligibility-gated outbound DEX link instead. Paid `portfolio` endpoint returns ERC-8056 `uiMultiplier`-correct holdings. The Hood Desk (`/markets/robinhood/desk`) is the wallet-first view of the same chain: paste or connect any address and it loads that wallet's book (native + priced ERC-20 positions), its native balance curve rebuilt from Blockscout's daily and per-transaction feeds (the public RPC is not an archive node), an activity tape that folds token transfers onto the transaction that emitted them, the NAV premium ridge layered by liquidity floor, counterparty flow, and memecoin movers. Read-only and signature-free; the trade ticket reuses the coin pages' swap panel and the Stock Token eligibility gate. Tests: [tests/robinhood-desk.test.js](tests/robinhood-desk.test.js) (the derivations) and [tests/e2e/hood-desk.spec.js](tests/e2e/hood-desk.spec.js) (the panels, the empty states, the ladder collapse and the trade ticket). Docs: [docs/robinhood-chain-markets.md](docs/robinhood-chain-markets.md) |
-| $THREE launchpad (native bonding curve) | Page [pages/three-launchpad.html](pages/three-launchpad.html) + [src/three-launchpad/](src/three-launchpad) `→ /three-launchpad`; backend [api/_lib/native-launch/](api/_lib/native-launch) + [api/native-launch/[action].js](api/native-launch/%5Baction%5D.js); lane toggle in [public/studio/launch-panel.js](public/studio/launch-panel.js); config + devnet scripts `scripts/native-launchpad-*.mjs` | In-repo · code-complete, mainnet config creation owner-gated (about 0.006 SOL) | Solana. Every coin launched on the lane is quoted in $THREE on Meteora's Dynamic Bonding Curve: buys are made with $THREE, creators earn 50% of the 1% fee in $THREE, and graduation (60M $THREE market cap, about 12.3M $THREE raised) locks 100% of LP in a DAMM v2 pool against $THREE. Public buy and sell via `swap-prep`, no session needed. Verified by a keyless mainnet simulation that creates the config and a $THREE-quoted pool against the live program. Docs: [docs/native-launchpad.md](docs/native-launchpad.md) |
+| $THREE launchpad (native bonding curve) | Page [pages/three-launchpad.html](pages/three-launchpad.html) + [src/three-launchpad/](src/three-launchpad) `→ /three-launchpad`; backend [api/_lib/native-launch/](api/_lib/native-launch) + [api/native-launch/[action].js](api/native-launch/%5Baction%5D.js); lane toggle in [public/studio/launch-panel.js](public/studio/launch-panel.js); config + devnet scripts `scripts/native-launchpad-*.mjs`; fee schedule rules [src/shared/launch-fees.js](src/shared/launch-fees.js), preview/simulation [api/_lib/native-launch/fee-config.js](api/_lib/native-launch/fee-config.js) | In-repo · code-complete, mainnet config creation owner-gated (about 0.006 SOL) | Solana. Every coin launched on the lane is quoted in $THREE on Meteora's Dynamic Bonding Curve: buys are made with $THREE, creators earn 50% of the 1% fee in $THREE, and graduation (60M $THREE market cap, about 12.3M $THREE raised) locks 100% of LP in a DAMM v2 pool against $THREE. Public buy and sell via `swap-prep`, no session needed. Verified by a keyless mainnet simulation that creates the config and a $THREE-quoted pool against the live program. Docs: [docs/native-launchpad.md](docs/native-launchpad.md) |
| Uniswap v4 hooks (EVM) | [contracts/v4-hooks/](contracts/v4-hooks): `SkinHook` + `SkinToken` (wearable 3D items as coins), `AgentTierHook` (ERC-8004 reputation fee tiers), CREATE2 address mining and deploy scripts; hook census [scripts/uniswap-v4-hook-census.mjs](scripts/uniswap-v4-hook-census.mjs) (decodes permission bits, flags HookForge hooks), HookForge catalog generator [scripts/gen-hookforge-catalog.mjs](scripts/gen-hookforge-catalog.mjs) over the pinned snapshot [data/hookforge-registry.json](data/hookforge-registry.json) | In-repo · contracts code-complete and tested against real v4-core and a live Base fork, not deployed (owner-gated) | Additional EVM surface, Solana stays the home chain. `SkinHook`: every wearable is a fixed-supply ERC-20 with its own ETH pool; equipping locks one whole token in the hook so each wearer shrinks the float, a 2% ETH-side fee is split creator / referrer (named in `hookData`, the embed that sold it) / treasury as ERC-6909 claims, and the whole supply is seeded as one permanent single-sided position. `AgentTierHook`: dynamic LP fee by ERC-8004 standing, read from the canonical registries with a pool-configured reviewer set, cached by a permissionless `refreshTier`, every registry failure resolving to the base fee. v4-core vendored at v4.0.0 under `contracts/v4-hooks/lib`. Docs: [contracts/v4-hooks/README.md](contracts/v4-hooks/README.md), [docs/uniswap-v4-hooks.md](docs/uniswap-v4-hooks.md) |
| Robinhood Chain coin launches (Pons) | Page [pages/launch-robinhood.html](pages/launch-robinhood.html) + [src/launch-robinhood/page.js](src/launch-robinhood/page.js) `→ /launch/robinhood`; HTTP [api/agents/pons/[action].js](api/agents/pons/[action].js) (`POST /api/agents/:id/pons/{quote,launch}`); custodial launch [api/_lib/evm-leg/pons-launch.js](api/_lib/evm-leg/pons-launch.js); calldata, curve math and launch feed [api/_lib/pons.js](api/_lib/pons.js); agent skill [src/agent-skills-pons.js](src/agent-skills-pons.js) (`pons-launch`) | In-repo | An agent launches a coin on Pons V2 (ETH bonding curve graduating into a locked Uniswap V4 pool) from its own EVM wallet, with an atomic opening buy and the quoted economics pinned on chain. Same gates as every custodial spend: ownership, platform-signing mode, real-funds agreement, per-chain USD spend policy with a pending ledger row before send, audited key decrypt. Landed coins go to `fixed_supply_launches` (chain `robinhood`, venue `pons`) so /launches and agent profiles list them. The same module feeds Pons launches (curve price, market cap, graduation %) into `/api/v1/robinhood/launches`. Tests: [tests/pons.test.js](tests/pons.test.js) rebuilds real mainnet launches byte-for-byte. Docs: [docs/pons-launch.md](docs/pons-launch.md) |
| Paired coins (Robinhood Chain, multi-quote launchpad) | Hub [pages/paired-coins.html](pages/paired-coins.html) + [src/paired/hub.js](src/paired/hub.js) `→ /markets/robinhood/paired`, coin page [pages/paired-coin.html](pages/paired-coin.html) + [src/paired/coin.js](src/paired/coin.js) + trade ticket [src/paired/trade.js](src/paired/trade.js) `→ /markets/robinhood/paired/:address`, launch page [pages/launch-paired.html](pages/launch-paired.html) + [src/paired/launch.js](src/paired/launch.js) `→ /launch/paired`; reads [api/_lib/paired-launchpad.js](api/_lib/paired-launchpad.js) + [api/_lib/paired-markets.js](api/_lib/paired-markets.js) + [api/_lib/paired-directory.js](api/_lib/paired-directory.js) + [api/_lib/paired-trades.js](api/_lib/paired-trades.js) behind `api/v1/robinhood/paired-{markets,coins,coins-detail}.js` (free); custodial launch [api/_lib/evm-leg/paired-launch.js](api/_lib/evm-leg/paired-launch.js) behind [api/agents/paired/[action].js](api/agents/paired/[action].js) (`POST /api/agents/:id/paired/{quote,launch,claim}`, `GET .../fees`); MCP [api/_mcp/tools/paired.js](api/_mcp/tools/paired.js); agent skills [src/agent-skills-paired.js](src/agent-skills-paired.js); contracts [contracts/paired-launchpad/](contracts/paired-launchpad); operator script [scripts/paired-register-quotes.mjs](scripts/paired-register-quotes.mjs) (`npm run paired:quotes`) | In-repo · launchpad live on chain 4663, quote registration owner-gated | A coin with a fixed 1B supply split across one to five constant-product curves, one per quote asset from the launchpad's on-chain registry (tokenized stocks, WETH, stablecoins, chain coins). Each curve opens on a virtual quote reserve, so launching costs only the flat ETH fee and gas; liquidity never migrates and cannot be withdrawn, and the creator earns 70% of every swap fee in each asset it trades in. The launchpad is the only source of truth for coins, markets, prices and trades (candles come from its `Swap` events). Agents launch from their custodial EVM wallet under the same gates as every custodial spend, with an atomic opening buy pinned to the quoted fill; landed coins go to `fixed_supply_launches` (chain `robinhood`, venue `paired`). New quotes are calibrated to a common dollar opening value by `paired:quotes`, which only prints a plan unless given `--apply` and the owner key. Docs: [docs/paired-coins.md](docs/paired-coins.md) |
diff --git a/api/_lib/native-launch/config.js b/api/_lib/native-launch/config.js
index 3c31ea65f..215a7a0f2 100644
--- a/api/_lib/native-launch/config.js
+++ b/api/_lib/native-launch/config.js
@@ -42,6 +42,14 @@
// NATIVE_LAUNCH_FEE_WALLET (platform fee claimer + leftover receiver)
import { env } from '../env.js';
+import {
+ FEE_SCHEDULE_MODES,
+ MIN_FEE_BPS,
+ MAX_FEE_BPS,
+ describeFeeSchedule,
+ describeReferral,
+ referralShareOfTradingFeePercent,
+} from '../../../src/shared/launch-fees.js';
export const NATIVE_LANE = {
id: 'native',
@@ -74,10 +82,26 @@ export const NATIVE_LANE = {
antiSnipeDecaySlots: 100,
};
+// The lane's own decaying-fee schedule in the shape src/shared/launch-fees.js
+// validates, so the page, the preview endpoint and the on-chain config all read
+// the same numbers.
+export function defaultFeeSchedule() {
+ return {
+ mode: 'exponential',
+ start_fee_bps: NATIVE_LANE.antiSnipeStartFeeBps,
+ end_fee_bps: NATIVE_LANE.antiSnipeEndFeeBps,
+ periods: NATIVE_LANE.antiSnipeDecayPeriods,
+ duration_slots: NATIVE_LANE.antiSnipeDecaySlots,
+ };
+}
+
// Params for buildCurveWithMarketCap(). Enum values are inlined as numbers so
// this module stays importable without pulling the SDK (the SDK is only
// loaded lazily by dbc.js); dbc.js asserts them against the real enums.
-export function curveBuildParams() {
+//
+// `feeSchedule` (already run through validateFeeSchedule) swaps in a different
+// decaying-fee schedule for a candidate config; omitted, it builds the live lane.
+export function curveBuildParams({ feeSchedule = defaultFeeSchedule() } = {}) {
return {
token: {
tokenType: 0, // TokenType.SPLToken
@@ -99,12 +123,12 @@ export function curveBuildParams() {
// measure on devnet before it gets there. Exponential over linear
// because it front-loads the decay (steepest drop right after
// activation, where the snipers are, instead of a constant slope).
- baseFeeMode: 1, // BaseFeeMode.FeeSchedulerExponential
+ baseFeeMode: FEE_SCHEDULE_MODES[feeSchedule.mode], // 0 Linear, 1 Exponential
feeSchedulerParam: {
- startingFeeBps: NATIVE_LANE.antiSnipeStartFeeBps,
- endingFeeBps: NATIVE_LANE.antiSnipeEndFeeBps,
- numberOfPeriod: NATIVE_LANE.antiSnipeDecayPeriods,
- totalDuration: NATIVE_LANE.antiSnipeDecaySlots,
+ startingFeeBps: feeSchedule.start_fee_bps,
+ endingFeeBps: feeSchedule.end_fee_bps,
+ numberOfPeriod: feeSchedule.periods,
+ totalDuration: feeSchedule.duration_slots,
},
},
dynamicFeeEnabled: true,
@@ -192,6 +216,13 @@ export function laneInfo(network = 'mainnet') {
decay_slots: NATIVE_LANE.antiSnipeDecaySlots,
creator_first_buy_exempt: true,
},
+ fee_schedule: defaultFeeSchedule(),
+ fee_schedule_preview: describeFeeSchedule(defaultFeeSchedule()),
+ fee_limits: { min_fee_bps: MIN_FEE_BPS, max_fee_bps: MAX_FEE_BPS, slot_seconds: 0.4 },
+ referral: {
+ share_of_trading_fee_percent: referralShareOfTradingFeePercent(),
+ preview: describeReferral(),
+ },
migration_fee_percent: NATIVE_LANE.migrationFeePercent,
lp_locked_percent: NATIVE_LANE.lpLockedPercent,
graduates_to: 'Meteora DAMM v2 against $THREE (LP permanently locked, creator keeps earning LP fees)',
diff --git a/api/_lib/native-launch/dbc.js b/api/_lib/native-launch/dbc.js
index 44422a4d8..53195622f 100644
--- a/api/_lib/native-launch/dbc.js
+++ b/api/_lib/native-launch/dbc.js
@@ -213,7 +213,7 @@ export async function getPoolState({ network = 'mainnet', mint } = {}) {
// Live quote against the curve. side 'buy': `amountIn` $THREE -> tokens out.
// side 'sell': `amountIn` tokens -> $THREE out. Amounts are whole units, pre-slippage.
-async function quoteSwap({ network, mint, side, amountIn, slippageBps }) {
+async function quoteSwap({ network, mint, side, amountIn, slippageBps, hasReferral = false }) {
const BN = (await import('bn.js')).default;
const { client, pool, account, wrapped } = await fetchPool({ network, mint });
const config = await client.state.getPoolConfig(account.config);
@@ -228,7 +228,7 @@ async function quoteSwap({ network, mint, side, amountIn, slippageBps }) {
swapBaseForQuote: selling,
amountIn: new BN(toAtomics(amountIn, selling ? BASE_UNIT : QUOTE_UNIT)),
slippageBps,
- hasReferral: false,
+ hasReferral,
eligibleForFirstSwapWithMinFee: false,
currentPoint: new BN(slot),
});
@@ -266,12 +266,20 @@ export async function quoteSell({ network = 'mainnet', mint, tokensIn, slippageB
// Unsigned buy or sell on a live curve, for the trader's own wallet to sign. The
// quote is taken in the same call, so the slippage floor in the transaction is the
// one the trader was just shown.
-export async function buildSwapTx({ network = 'mainnet', mint, trader, side, amountIn, slippageBps = 100 } = {}) {
+//
+// `referralTokenAccount` (optional) is the referrer's token account for the quote mint:
+// the program pays it the referral share of the protocol fee, taken out of the
+// protocol's cut so the trader's price is unchanged.
+export async function buildSwapTx({ network = 'mainnet', mint, trader, side, amountIn, slippageBps = 100, referralTokenAccount = null } = {}) {
const BN = (await import('bn.js')).default;
const traderPk = solanaPubkey(trader);
if (!traderPk) throw Object.assign(new Error('invalid trader pubkey'), { status: 400, code: 'validation_error' });
+ const referralPk = referralTokenAccount ? solanaPubkey(referralTokenAccount) : null;
+ if (referralTokenAccount && !referralPk) {
+ throw Object.assign(new Error('invalid referral token account'), { status: 400, code: 'validation_error' });
+ }
- const { pool, quote, selling } = await quoteSwap({ network, mint, side, amountIn, slippageBps });
+ const { pool, quote, selling } = await quoteSwap({ network, mint, side, amountIn, slippageBps, hasReferral: Boolean(referralPk) });
const client = await getDbcClient({ network });
const tx = await client.pool.swap({
owner: traderPk,
@@ -280,7 +288,7 @@ export async function buildSwapTx({ network = 'mainnet', mint, trader, side, amo
amountIn: new BN(toAtomics(amountIn, selling ? BASE_UNIT : QUOTE_UNIT)),
minimumAmountOut: quote.minimumAmountOut ?? quote.outputAmount,
swapBaseForQuote: selling,
- referralTokenAccount: null,
+ referralTokenAccount: referralPk,
});
const txBase64 = await buildUnsignedTxBase64({ network, payer: traderPk, instructions: tx.instructions });
const outUnit = selling ? QUOTE_UNIT : BASE_UNIT;
@@ -292,5 +300,6 @@ export async function buildSwapTx({ network = 'mainnet', mint, trader, side, amo
expected_out: fromAtomics(quote.outputAmount, outUnit),
min_out: fromAtomics(quote.minimumAmountOut ?? quote.outputAmount, outUnit),
slippage_bps: slippageBps,
+ referral: Boolean(referralPk),
};
}
diff --git a/api/_lib/native-launch/fee-config.js b/api/_lib/native-launch/fee-config.js
new file mode 100644
index 000000000..e93bb1e6f
--- /dev/null
+++ b/api/_lib/native-launch/fee-config.js
@@ -0,0 +1,123 @@
+// Candidate fee configuration for the native lane: validate a decaying-fee schedule,
+// run it through Meteora's own config validators, describe it in plain language and,
+// on request, simulate creating the config plus a pool under it against a live RPC.
+// Nothing here signs or sends: the simulation runs with signature verification off
+// and the returned transaction is unsigned.
+
+import { Keypair, TransactionMessage, VersionedTransaction } from '@solana/web3.js';
+import { getConnection, solanaPubkey } from '../pump.js';
+import { validateFeeSchedule, describeFeeSchedule, describeReferral, referralShareOfTradingFeePercent } from '../../../src/shared/launch-fees.js';
+import { curveBuildParams, defaultFeeSchedule, quoteMintFor, feeWallet, NATIVE_LANE } from './config.js';
+import { getDbcClient, withQuoteTokenProgram } from './dbc.js';
+
+const badRequest = (message, details) => Object.assign(new Error(message), { status: 400, code: 'validation_error', details });
+
+let _sdk = null;
+const sdk = async () => (_sdk ||= await import('@meteora-ag/dynamic-bonding-curve-sdk'));
+
+// Fee in basis points `slot` slots after activation, evaluated from the scheduler
+// parameters the SDK resolves (getBaseFeeParams): the fee steps down once every
+// `periodFrequency` slots, `numberOfPeriod` times, linearly or by a fixed ratio.
+// The SDK dropped its own evaluator in 2.0, so this mirrors the program's rule.
+export async function feeBpsAtSlot(baseFeeParams, slot) {
+ const { getBaseFeeParams, MAX_BASIS_POINT } = await sdk();
+ const sp = getBaseFeeParams(baseFeeParams);
+ const cliff = Number(sp.cliffFeeNumerator.toString());
+ const periods = Number(sp.firstFactor);
+ const frequency = Number(sp.secondFactor.toString());
+ const reduction = Number(sp.thirdFactor.toString());
+ if (periods === 0 || frequency === 0) return cliff / 100_000;
+ const elapsed = Math.min(Math.floor(slot / frequency), periods);
+ const numerator =
+ sp.baseFeeMode === 0
+ ? cliff - elapsed * reduction
+ : cliff * (1 - reduction / (MAX_BASIS_POINT ?? 10_000)) ** elapsed;
+ return Math.round((numerator / 100_000) * 100) / 100;
+}
+
+async function feeCurve(baseFeeParams, durationSlots) {
+ const marks = [0, 0.25, 0.5, 0.75, 1].map((f) => Math.round(durationSlots * f));
+ return Promise.all(
+ marks.map(async (slot) => ({
+ slot,
+ seconds: Math.round(slot * 0.4),
+ fee_bps: await feeBpsAtSlot(baseFeeParams, slot),
+ })),
+ );
+}
+
+// Validates `input` (defaults to the live lane schedule) and returns the normalised
+// schedule, its preview text and the fee curve. Throws a 400 with every problem found.
+export async function previewFeeConfig(input) {
+ const checked = validateFeeSchedule(input ?? defaultFeeSchedule());
+ if (!checked.ok) throw badRequest(checked.errors[0], checked.errors);
+ const { schedule } = checked;
+ const { buildCurveWithMarketCap, validateConfigParameters } = await sdk();
+ let config;
+ try {
+ config = buildCurveWithMarketCap(curveBuildParams({ feeSchedule: schedule }));
+ validateConfigParameters({ ...config, leftoverReceiver: Keypair.generate().publicKey });
+ } catch (e) {
+ throw badRequest(e.message, [e.message]);
+ }
+ return {
+ schedule,
+ preview: describeFeeSchedule(schedule),
+ referral_preview: describeReferral(),
+ referral_share_of_trading_fee_percent: referralShareOfTradingFeePercent(),
+ fee_curve: await feeCurve(curveBuildParams({ feeSchedule: schedule }).fee.baseFeeParams, schedule.duration_slots),
+ config,
+ };
+}
+
+// Simulates `createConfigAndPool` for a candidate schedule on `network`. The fee
+// payer only has to exist and hold SOL; its signature is never checked.
+export async function simulateFeeConfig({ network = 'mainnet', schedule, payer } = {}) {
+ const quoteMintStr = quoteMintFor(network);
+ const quoteMint = solanaPubkey(quoteMintStr);
+ if (!quoteMint) {
+ throw Object.assign(new Error(`native launchpad quote mint not set on ${network}`), { status: 503, code: 'lane_not_configured' });
+ }
+ const payerPk = solanaPubkey(payer || feeWallet());
+ if (!payerPk) throw badRequest('payer wallet required: pass wallet_address (any funded address; it is never asked to sign)');
+ const { config } = await previewFeeConfig(schedule);
+ const connection = getConnection({ network });
+ const client = await getDbcClient({ network });
+ const tx = await client.partner.createConfigAndPool({
+ ...config,
+ config: Keypair.generate().publicKey,
+ feeClaimer: payerPk,
+ leftoverReceiver: payerPk,
+ quoteMint,
+ payer: payerPk,
+ preCreatePoolParam: {
+ name: 'Fee Config Simulation',
+ symbol: 'SIM',
+ uri: 'https://three.ws/launchpad',
+ poolCreator: payerPk,
+ baseMint: Keypair.generate().publicKey,
+ },
+ });
+ const info = await connection.getAccountInfo(quoteMint);
+ if (!info) throw Object.assign(new Error(`quote mint ${quoteMintStr} not found on ${network}`), { status: 503, code: 'lane_not_configured' });
+ const instructions = await withQuoteTokenProgram(tx.instructions, info.owner);
+ const message = new TransactionMessage({
+ payerKey: payerPk,
+ recentBlockhash: (await connection.getLatestBlockhash()).blockhash,
+ instructions,
+ }).compileToV0Message();
+ const versioned = new VersionedTransaction(message);
+ const sim = await connection.simulateTransaction(versioned, { sigVerify: false, replaceRecentBlockhash: true });
+ return {
+ network,
+ quote: NATIVE_LANE.quote,
+ quote_mint: quoteMintStr,
+ ok: !sim.value.err,
+ error: sim.value.err ?? null,
+ units_consumed: sim.value.unitsConsumed ?? null,
+ logs_tail: (sim.value.logs || []).slice(-6),
+ unsigned_tx_base64: Buffer.from(versioned.serialize()).toString('base64'),
+ note: 'Simulation only. The config account is an ephemeral key, so this transaction is not submittable.',
+ };
+}
+
diff --git a/api/native-launch/[action].js b/api/native-launch/[action].js
index 3e61c7887..2d5a8588e 100644
--- a/api/native-launch/[action].js
+++ b/api/native-launch/[action].js
@@ -16,6 +16,7 @@
// launch-prep -> handleLaunchPrep (authed: unsigned create-pool tx)
// launch-confirm -> handleLaunchConfirm (authed: verify + record launch)
// launches -> handleLaunches (public: native launch directory)
+// fee-config -> handleFeeConfig (public: validate + describe a decaying-fee schedule, optional devnet/mainnet simulation)
import { z } from 'zod';
import { Keypair } from '@solana/web3.js';
@@ -34,6 +35,7 @@ import { THREE_WS_VANITY, hasThreeWsMark } from '../../src/solana/vanity/brand.j
import { grindVanityNode, GrindExhaustedError } from '../../src/solana/vanity/grinder-node.js';
import { verifySignature, solanaPubkey } from '../_lib/pump.js';
import { laneInfo, configKeyFor, quoteMintFor } from '../_lib/native-launch/config.js';
+import { previewFeeConfig, simulateFeeConfig } from '../_lib/native-launch/fee-config.js';
import {
buildCreatePoolTx,
txInvokesDbcProgram,
@@ -103,6 +105,8 @@ const swapPrepSchema = z.object({
side: z.enum(['buy', 'sell']),
amount: z.number().positive().max(MAX_SWAP_AMOUNT),
slippage_bps: z.number().int().min(1).max(5000).default(100),
+ // Referrer's token account for the quote mint; it earns the referral share of the protocol fee.
+ referral_token_account: z.string().min(32).max(44).optional(),
network: z.enum(['mainnet', 'devnet']).default('mainnet'),
});
@@ -125,6 +129,7 @@ async function handleSwapPrep(req, res) {
side: body.side,
amountIn: body.amount,
slippageBps: body.slippage_bps,
+ referralTokenAccount: body.referral_token_account ?? null,
});
return json(res, 200, {
network: body.network,
@@ -136,6 +141,7 @@ async function handleSwapPrep(req, res) {
expected_out: built.expected_out,
min_out: built.min_out,
slippage_bps: built.slippage_bps,
+ referral: built.referral,
});
} catch (e) {
return error(res, e.status || 500, e.code || 'swap_prep_failed', e.message);
@@ -477,6 +483,58 @@ async function handleLaunches(req, res) {
// ── dispatcher ─────────────────────────────────────────────────────────────
+// ── fee-config ─────────────────────────────────────────────────────────────
+
+const feeConfigSchema = z.object({
+ fee_schedule: z
+ .object({
+ mode: z.string().max(24).optional(),
+ start_fee_bps: z.number(),
+ end_fee_bps: z.number(),
+ periods: z.number().optional(),
+ duration_slots: z.number().optional(),
+ })
+ .optional(),
+ simulate: z.boolean().default(false),
+ wallet_address: z.string().min(32).max(44).optional(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+// Validates a candidate fee schedule exactly as the Dynamic Bonding Curve SDK and
+// program will (rate-limiter mode is refused), returns its plain-language preview and
+// fee curve, and with simulate:true also simulates creating the config plus a pool
+// under it. Nothing is signed or sent; omitting fee_schedule previews the live lane.
+async function handleFeeConfig(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['POST'])) return;
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ try {
+ const body = parse(feeConfigSchema, await readJson(req));
+ const preview = await previewFeeConfig(body.fee_schedule);
+ const out = {
+ network: body.network,
+ fee_schedule: preview.schedule,
+ preview: preview.preview,
+ fee_curve: preview.fee_curve,
+ referral: {
+ share_of_trading_fee_percent: preview.referral_share_of_trading_fee_percent,
+ preview: preview.referral_preview,
+ },
+ };
+ if (body.simulate) {
+ out.simulation = await simulateFeeConfig({
+ network: body.network,
+ schedule: preview.schedule,
+ payer: body.wallet_address,
+ });
+ }
+ return json(res, 200, out);
+ } catch (e) {
+ return error(res, e.status || 500, e.code || 'fee_config_failed', e.message, e.details ? { details: e.details } : undefined);
+ }
+}
+
async function dispatch(req, res) {
const url = new URL(req.url, `http://${req.headers.host}`);
const action = req.query?.action || url.searchParams.get('action');
@@ -488,6 +546,7 @@ async function dispatch(req, res) {
case 'launch-prep': return handleLaunchPrep(req, res);
case 'launch-confirm': return handleLaunchConfirm(req, res);
case 'launches': return handleLaunches(req, res);
+ case 'fee-config': return handleFeeConfig(req, res);
default:
return error(res, 404, 'not_found', `unknown launchpad action: ${action || '(none)'}`);
}
diff --git a/api/pump/[action].js b/api/pump/[action].js
index b56139134..27add2073 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -51,6 +51,7 @@
// fee-sharing-agent -> handleFeeSharingAgent (server-signs create +
// update sharing config; delegated fee rewards)
+import { validateShareholders } from '../../src/shared/launch-fees.js';
import { z } from 'zod';
import { Keypair, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';
import { sql } from '../_lib/db.js';
@@ -4956,11 +4957,9 @@ const updateFeeSharesSchema = z.object({
)
.min(1)
.max(10)
- .refine((arr) => arr.reduce((s, x) => s + x.share_bps, 0) === 10_000, {
- message: 'share_bps must sum to 10000',
- })
- .refine((arr) => new Set(arr.map((x) => x.address)).size === arr.length, {
- message: 'duplicate shareholder addresses',
+ .superRefine((arr, ctx) => {
+ // One rule set for the server and the launch UI: src/shared/launch-fees.js.
+ for (const message of validateShareholders(arr).errors) ctx.addIssue({ code: 'custom', message });
}),
});
diff --git a/data/changelog.json b/data/changelog.json
index a66a70591..d388bbca8 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$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, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-10-24",
+ "title": "See and test launch fees before a coin goes live",
+ "summary": "The $THREE launchpad form now shows the launch fee in plain words and as a fee-over-time table. A new fee-config endpoint validates a decaying fee schedule against the Meteora SDK rules and can simulate the config transaction unsigned. Swap preparation accepts a referral token account, and a shared pump.fun fee vault now rejects holder splits that do not total 100 percent across 1 to 10 wallets.",
+ "tags": [
+ "feature",
+ "docs"
+ ],
+ "link": "/docs/native-launchpad"
+ },
{
"date": "2026-10-24",
"title": "See what a prediction strategy would have earned before it trades",
diff --git a/docs/native-launchpad.md b/docs/native-launchpad.md
index 0dd8441de..31bf8066a 100644
--- a/docs/native-launchpad.md
+++ b/docs/native-launchpad.md
@@ -71,6 +71,16 @@ This mirrors the owner's EVM `anti-snipe-ramp` hook concept, but it is built ent
One honest difference from the EVM hook: on an EVM AMM, an anti-snipe ramp's excess fee typically accrues to the pool's liquidity providers. On this lane, all trading fees (ramped or steady-state) flow through the same 50/50 creator/three.ws split that every other trade uses, never to LPs, because DBC pools have no third-party LPs before graduation. The anti-snipe premium a sniper pays is extra revenue for the coin's creator and the platform, not a yield booster for outside liquidity.
+### Fee schedule, referral share and shared fee vaults
+
+The lane's decaying fee is one value, `defaultFeeSchedule()` in [`config.js`](../api/_lib/native-launch/config.js), read by the on-chain config builder, `GET /api/native-launch/config` (`fee_schedule`, `fee_schedule_preview`, `fee_limits`, `referral`) and the launch form. Rules live in [`src/shared/launch-fees.js`](../src/shared/launch-fees.js) so the server and browser reject the same inputs. They mirror the SDK's `getFeeSchedulerParams`: fees between 25 and 9900 bps, a schedule that can only fall, `periods` and `duration_slots` both above zero when it falls (and both zero when it is flat), and `duration_slots >= periods`. The rate limiter mode is refused with the SDK's own reason: the program rejects it for new configs.
+
+`POST /api/native-launch/fee-config` (public, no session) takes `{ fee_schedule?, simulate?, wallet_address?, network? }`, runs the schedule through `buildCurveWithMarketCap` and `validateConfigParameters`, and returns a plain-language `preview` ("Fee starts at 30% and falls to 1% over about 80 seconds ..."), the fee at five points in the window, and the referral line. With `simulate: true` it also simulates `createConfigAndPool` for that schedule against the live DBC program and returns the unsigned transaction; the config account is an ephemeral key, so the result is never submittable. From a shell: `node scripts/native-launchpad-simulate-fees.mjs --start 3000 --end 100 --periods 20 --slots 200 [--network devnet]`. Creating a new on-chain config from a schedule stays the owner-gated `native-launchpad-create-config.mjs` step; coins already launched keep the config they launched under.
+
+Referral share: `swap-prep` takes an optional `referral_token_account` (the referrer's account for the quote mint). The program pays it 20% of the protocol's 20% cut of the trading fee (4% of the fee), taken out of the protocol's share, so the trader's price does not change.
+
+Shared fee vaults on the pump.fun lane use the same module: `POST /api/pump/update-fee-shares-prep` accepts 1 to 10 distinct wallets whose `share_bps` total exactly 10000 (`validateShareholders`), and the studio fees panel applies the same total-100% rule before it asks for a signature.
+
### Why `leftover: 1`
The DBC program requires that the tokens on the curve, the tokens reserved for migration, and the leftover reconcile *exactly* against the fixed supply. A leftover of `0` fails that check on-chain with `InvalidTokenSupply`. One base unit of dust satisfies it. This was found by simulating the real `create_config` instruction against devnet, and it is pinned by a test so nobody "cleans it up" later.
diff --git a/scripts/native-launchpad-simulate-fees.mjs b/scripts/native-launchpad-simulate-fees.mjs
new file mode 100644
index 000000000..d5314d9c3
--- /dev/null
+++ b/scripts/native-launchpad-simulate-fees.mjs
@@ -0,0 +1,45 @@
+#!/usr/bin/env node
+// Preview and simulate a candidate fee schedule for the native launchpad config.
+// Spends nothing and signs nothing: the schedule goes through the SDK validators,
+// then `createConfigAndPool` is simulated against a live RPC with signature
+// verification off.
+//
+// node scripts/native-launchpad-simulate-fees.mjs --start 3000 --end 100 --periods 20 --slots 200 \
+// [--mode exponential|linear] [--network mainnet|devnet] [--payer <funded address>]
+//
+// Omit the fee flags to simulate the live lane schedule.
+
+import 'dotenv/config';
+import { previewFeeConfig, simulateFeeConfig } from '../api/_lib/native-launch/fee-config.js';
+import { defaultFeeSchedule } from '../api/_lib/native-launch/config.js';
+
+const args = process.argv.slice(2);
+const flag = (name) => (args.includes(`--${name}`) ? args[args.indexOf(`--${name}`) + 1] : undefined);
+const num = (name, fallback) => (flag(name) === undefined ? fallback : Number(flag(name)));
+const base = defaultFeeSchedule();
+const schedule = {
+ mode: flag('mode') ?? base.mode,
+ start_fee_bps: num('start', base.start_fee_bps),
+ end_fee_bps: num('end', base.end_fee_bps),
+ periods: num('periods', base.periods),
+ duration_slots: num('slots', base.duration_slots),
+};
+const network = flag('network') ?? 'mainnet';
+
+try {
+ const preview = await previewFeeConfig(schedule);
+ console.log(preview.preview);
+ console.log(preview.referral_preview);
+ console.log('fee curve:', JSON.stringify(preview.fee_curve));
+ const sim = await simulateFeeConfig({ network, schedule, payer: flag('payer') });
+ console.log(
+ sim.ok
+ ? `simulation OK on ${network}: config + pool accepted by the DBC program (${sim.units_consumed} compute units, tx ${sim.unsigned_tx_base64.length} base64 chars, unsigned)`
+ : `simulation FAILED on ${network}: ${JSON.stringify(sim.error)}\n${sim.logs_tail.join('\n')}`,
+ );
+ process.exit(sim.ok ? 0 : 1);
+} catch (e) {
+ console.error(`${e.code || 'error'}: ${e.message}`);
+ if (e.details?.length > 1) console.error(e.details.join('\n'));
+ process.exit(1);
+}
diff --git a/src/shared/launch-fees.js b/src/shared/launch-fees.js
new file mode 100644
index 000000000..606dfb321
--- /dev/null
+++ b/src/shared/launch-fees.js
@@ -0,0 +1,133 @@
+// Launch-time fee configuration rules, shared by the server (api/_lib/native-launch,
+// api/pump) and the launch UI so the number a creator sees is the number the
+// program accepts. Pure functions, no imports.
+//
+// The limits mirror the Meteora Dynamic Bonding Curve SDK's own validators
+// (getFeeSchedulerParams) and pump.fun's fee-sharing config rules. The server
+// still runs the SDK validators on top; this module exists so the browser can
+// reject a bad value before any request is made.
+
+export const SLOT_SECONDS = 0.4;
+export const MIN_FEE_BPS = 25;
+export const MAX_FEE_BPS = 9_900;
+export const MAX_FEE_PERIODS = 65_535;
+export const MAX_SHAREHOLDERS = 10;
+// The program pays a swap referrer this share of the protocol's cut of the trading fee.
+export const REFERRAL_SHARE_OF_PROTOCOL_FEE_PERCENT = 20;
+export const PROTOCOL_SHARE_OF_TRADING_FEE_PERCENT = 20;
+
+export const FEE_SCHEDULE_MODES = Object.freeze({ linear: 0, exponential: 1 });
+
+const BASE58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+const isInt = (v) => Number.isInteger(v);
+
+function pct(bps) {
+ const v = bps / 100;
+ return `${Number.isInteger(v) ? v : v.toFixed(2).replace(/0+$/, '').replace(/\.$/, '')}%`;
+}
+
+function span(slots) {
+ const seconds = Math.round(slots * SLOT_SECONDS);
+ if (seconds < 90) return `${seconds} seconds`;
+ const minutes = seconds / 60;
+ if (minutes < 90) return `${Number.isInteger(minutes) ? minutes : minutes.toFixed(1)} minutes`;
+ const hours = minutes / 60;
+ return `${Number.isInteger(hours) ? hours : hours.toFixed(1)} hours`;
+}
+
+// Validates a decaying-fee schedule. Returns { ok, errors[], schedule } where
+// `schedule` is the normalised value. Rate-limiter mode is refused with the SDK's
+// reason: the program rejects it for new configs.
+export function validateFeeSchedule(input) {
+ const errors = [];
+ const mode = input?.mode ?? 'exponential';
+ if (mode === 'rate_limiter' || mode === 'rateLimiter') {
+ errors.push(
+ 'The rate limiter is deprecated by the Dynamic Bonding Curve program and is rejected for new configs. Use a linear or exponential fee schedule.',
+ );
+ } else if (!(mode in FEE_SCHEDULE_MODES)) {
+ errors.push('mode must be "linear" or "exponential".');
+ }
+ const start = input?.start_fee_bps;
+ const end = input?.end_fee_bps;
+ const periods = input?.periods ?? 0;
+ const duration = input?.duration_slots ?? 0;
+ for (const [label, v] of [['start_fee_bps', start], ['end_fee_bps', end]]) {
+ if (!isInt(v) || v < MIN_FEE_BPS || v > MAX_FEE_BPS) {
+ errors.push(`${label} must be a whole number of basis points between ${MIN_FEE_BPS} and ${MAX_FEE_BPS}.`);
+ }
+ }
+ if (isInt(start) && isInt(end)) {
+ if (end > start) {
+ errors.push('end_fee_bps must be less than or equal to start_fee_bps: a schedule can only fall.');
+ } else if (start === end) {
+ if (periods !== 0 || duration !== 0) {
+ errors.push('periods and duration_slots must both be 0 when the fee is constant.');
+ }
+ } else {
+ if (!isInt(periods) || periods <= 0 || !isInt(duration) || duration <= 0) {
+ errors.push('periods and duration_slots must both be greater than 0 when the fee falls.');
+ } else {
+ if (periods > MAX_FEE_PERIODS) errors.push(`periods must be at most ${MAX_FEE_PERIODS}.`);
+ if (duration < periods) errors.push('duration_slots must be at least periods.');
+ }
+ }
+ }
+ if (errors.length) return { ok: false, errors, schedule: null };
+ return {
+ ok: true,
+ errors: [],
+ schedule: { mode, start_fee_bps: start, end_fee_bps: end, periods, duration_slots: duration },
+ };
+}
+
+// "Fee starts at 50% and falls to 1% over about 40 seconds (100 slots, in 25 steps)."
+export function describeFeeSchedule(schedule) {
+ if (schedule.start_fee_bps === schedule.end_fee_bps) {
+ return `Fee is a flat ${pct(schedule.start_fee_bps)} from the first trade.`;
+ }
+ const shape =
+ schedule.mode === 'linear' ? 'in equal steps' : 'with the steepest drop first';
+ return `Fee starts at ${pct(schedule.start_fee_bps)} and falls to ${pct(schedule.end_fee_bps)} over about ${span(schedule.duration_slots)} (${schedule.duration_slots} slots, ${schedule.periods} steps, ${shape}).`;
+}
+
+// Plain-language line for the swap referral share of a trading fee, as a percentage
+// of the whole trading fee.
+export function referralShareOfTradingFeePercent() {
+ return (PROTOCOL_SHARE_OF_TRADING_FEE_PERCENT * REFERRAL_SHARE_OF_PROTOCOL_FEE_PERCENT) / 100;
+}
+
+export function describeReferral() {
+ return `A swap referrer earns ${REFERRAL_SHARE_OF_PROTOCOL_FEE_PERCENT}% of the protocol's ${PROTOCOL_SHARE_OF_TRADING_FEE_PERCENT}% cut of each trading fee (${referralShareOfTradingFeePercent()}% of the fee), paid by the program when the swap names a referral token account.`;
+}
+
+// Validates a shared fee vault split: 1 to 10 distinct wallets whose percentages
+// total exactly 100. Each row is { address, percent } or { address, share_bps }.
+// Returns { ok, errors[], shareholders: [{ address, share_bps }] } (bps total 10000,
+// the unit pump.fun's fee-sharing config takes).
+export function validateShareholders(rows) {
+ const errors = [];
+ if (!Array.isArray(rows) || rows.length === 0) {
+ return { ok: false, errors: ['Add at least one shareholder.'], shareholders: [] };
+ }
+ if (rows.length > MAX_SHAREHOLDERS) errors.push(`A shared fee vault holds at most ${MAX_SHAREHOLDERS} shareholders.`);
+ const seen = new Set();
+ const out = [];
+ let total = 0;
+ for (const [i, row] of rows.entries()) {
+ const address = typeof row?.address === 'string' ? row.address.trim() : '';
+ const bps = row?.share_bps ?? (typeof row?.percent === 'number' ? Math.round(row.percent * 100) : NaN);
+ if (!BASE58.test(address)) errors.push(`Shareholder ${i + 1} needs a valid Solana wallet address.`);
+ else if (seen.has(address)) errors.push(`Shareholder ${i + 1} repeats a wallet already in the list.`);
+ seen.add(address);
+ if (!isInt(bps) || bps < 1 || bps > 10_000) {
+ errors.push(`Shareholder ${i + 1} needs a share between 0.01% and 100%.`);
+ continue;
+ }
+ total += bps;
+ out.push({ address, share_bps: bps });
+ }
+ if (total !== 10_000) errors.push(`Shares must total 100% (currently ${pct(total)}).`);
+ return { ok: errors.length === 0, errors, shareholders: out };
+}
diff --git a/src/three-launchpad/page.css b/src/three-launchpad/page.css
index 4859a674d..81e7bd2fd 100644
--- a/src/three-launchpad/page.css
+++ b/src/three-launchpad/page.css
@@ -539,3 +539,51 @@
.tl-notice a {
color: var(--tl-accent);
}
+
+.tl-fees {
+ margin-top: 6px;
+ padding: 14px 16px;
+ border: 1px solid var(--border, rgba(255, 255, 255, 0.12));
+ border-radius: var(--radius-card, 16px);
+ background: var(--surface-2);
+}
+.tl-fees h3 {
+ margin: 0 0 6px;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--ink);
+}
+.tl-fees-line {
+ margin: 0 0 10px;
+ font-size: 13px;
+ line-height: 1.5;
+ color: var(--ink-dim);
+}
+.tl-fees-ref {
+ margin: 10px 0 0;
+}
+.tl-fees-table {
+ width: 100%;
+ border-collapse: collapse;
+ font: 500 12px/1.4 var(--font-mono);
+ color: var(--ink-dim);
+}
+.tl-fees-table th,
+.tl-fees-table td {
+ padding: 4px 0;
+ text-align: left;
+ border-bottom: 1px solid var(--border, rgba(255, 255, 255, 0.08));
+}
+.tl-fees-table td:last-child,
+.tl-fees-table th:last-child {
+ text-align: right;
+ color: var(--ink);
+}
+.tl-sr {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ white-space: nowrap;
+}
diff --git a/src/three-launchpad/page.js b/src/three-launchpad/page.js
index a7a8f3e0d..de27d6f7a 100644
--- a/src/three-launchpad/page.js
+++ b/src/three-launchpad/page.js
@@ -449,6 +449,12 @@ function renderLaunch() {
<label class="tl-field"><span><span>Ticker</span><span>max 10</span></span><input name="symbol" maxlength="10" required autocomplete="off" placeholder="NOVA" /></label>
<label class="tl-field tl-span"><span><span>Description</span><span>optional</span></span><textarea name="description" maxlength="500" placeholder="What this agent does and why its coin exists."></textarea></label>
<label class="tl-field tl-span"><span><span>Your first buy, in $THREE</span><span>optional, fills the start of your own curve</span></span><input name="buy" inputmode="decimal" autocomplete="off" placeholder="0" /></label>
+ <section class="tl-span tl-fees" aria-labelledby="tl-fees-h">
+ <h3 id="tl-fees-h">Fee schedule</h3>
+ <p class="tl-fees-line" id="tl-fees-preview">${esc(state.lane?.fee_schedule_preview || '')}</p>
+ <div id="tl-fees-curve" aria-live="polite"><div class="tl-skel" aria-busy="true" style="height:56px"></div></div>
+ <p class="tl-fees-line tl-fees-ref">${esc(state.lane?.referral?.preview || '')}</p>
+ </section>
<div class="tl-span" style="margin-top:18px"><button type="submit" class="tl-btn tl-btn--primary tl-btn--block" id="tl-launch-btn">Launch on the $THREE curve</button><p class="tl-status" id="tl-launch-status" aria-live="polite"></p></div>
</form>`;
const form = $('#tl-form');
@@ -456,6 +462,28 @@ function renderLaunch() {
form.symbol.addEventListener('input', () => (form.symbol.value = form.symbol.value.toUpperCase().replace(/[^A-Z0-9]/g, '')));
form.buy.addEventListener('input', () => (form.buy.value = form.buy.value.replace(/[^0-9.]/g, '')));
form.addEventListener('submit', onLaunchSubmit);
+ loadFeeCurve();
+}
+
+// The fee a trade pays at several points in the pool's opening window, evaluated by the
+// server with the program's own scheduler rule for the config this lane launches under.
+async function loadFeeCurve() {
+ const slot = $('#tl-fees-curve');
+ if (!slot) return;
+ try {
+ const data = await api('/api/native-launch/fee-config', { method: 'POST', body: { network: NETWORK } });
+ if (!$('#tl-fees-curve')) return;
+ $('#tl-fees-preview').textContent = data.preview;
+ slot.innerHTML = `<table class="tl-fees-table"><caption class="tl-sr">Trading fee by time after the pool opens</caption><thead><tr><th scope="col">After</th><th scope="col">Fee</th></tr></thead><tbody>${data.fee_curve
+ .map((p) => `<tr><td>${p.seconds === 0 ? 'First block' : `${p.seconds}s`}</td><td>${fmt(p.fee_bps / 100, 2)}%</td></tr>`)
+ .join('')}</tbody></table>`;
+ } catch (err) {
+ slot.innerHTML = `<p class="tl-status" data-tone="error" role="alert">Could not load the fee curve: ${esc(err.message)} <button type="button" class="tl-btn" id="tl-fees-retry">Try again</button></p>`;
+ $('#tl-fees-retry')?.addEventListener('click', () => {
+ slot.innerHTML = '<div class="tl-skel" aria-busy="true" style="height:56px"></div>';
+ loadFeeCurve();
+ });
+ }
}
// A launch plan handed over by another surface (a team's Launcher, for one)
diff --git a/tests/launch-fee-config.test.js b/tests/launch-fee-config.test.js
new file mode 100644
index 000000000..82055a29c
--- /dev/null
+++ b/tests/launch-fee-config.test.js
@@ -0,0 +1,138 @@
+// Launch-time fee configuration: the shared validators (decaying-fee schedule,
+// shared fee vault split, referral copy) and the server-side preview that runs a
+// candidate schedule through the Dynamic Bonding Curve SDK's own validators.
+
+import { describe, it, expect } from 'vitest';
+import {
+ validateFeeSchedule,
+ describeFeeSchedule,
+ describeReferral,
+ referralShareOfTradingFeePercent,
+ validateShareholders,
+} from '../src/shared/launch-fees.js';
+import { previewFeeConfig, feeBpsAtSlot } from '../api/_lib/native-launch/fee-config.js';
+import { curveBuildParams, defaultFeeSchedule, laneInfo } from '../api/_lib/native-launch/config.js';
+
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+// Distinct synthetic base58 wallets: a letter per index, repeated to 32 chars.
+const wallet = (n) => 'ABCDEFGHJKLMNPQRSTUVWXYZ'[n - 1].repeat(32);
+const good = { mode: 'exponential', start_fee_bps: 3000, end_fee_bps: 100, periods: 20, duration_slots: 200 };
+
+describe('validateFeeSchedule', () => {
+ it('accepts a falling schedule and a flat fee', () => {
+ expect(validateFeeSchedule(good).ok).toBe(true);
+ expect(validateFeeSchedule({ start_fee_bps: 100, end_fee_bps: 100 }).ok).toBe(true);
+ });
+
+ it('rejects a fee that rises', () => {
+ const r = validateFeeSchedule({ ...good, start_fee_bps: 100, end_fee_bps: 500 });
+ expect(r.ok).toBe(false);
+ expect(r.errors.join(' ')).toMatch(/can only fall/);
+ });
+
+ it('rejects fees outside the program range', () => {
+ expect(validateFeeSchedule({ ...good, start_fee_bps: 9901 }).ok).toBe(false);
+ expect(validateFeeSchedule({ ...good, end_fee_bps: 10 }).ok).toBe(false);
+ });
+
+ it('requires periods and duration when the fee falls, and forbids them when flat', () => {
+ expect(validateFeeSchedule({ ...good, periods: 0 }).ok).toBe(false);
+ expect(validateFeeSchedule({ ...good, periods: 50, duration_slots: 10 }).errors.join(' ')).toMatch(/at least periods/);
+ expect(validateFeeSchedule({ start_fee_bps: 100, end_fee_bps: 100, periods: 5, duration_slots: 5 }).ok).toBe(false);
+ });
+
+ it('refuses the deprecated rate limiter with the reason', () => {
+ const r = validateFeeSchedule({ ...good, mode: 'rate_limiter' });
+ expect(r.ok).toBe(false);
+ expect(r.errors[0]).toMatch(/deprecated/);
+ });
+
+ it('describes the schedule in plain language', () => {
+ expect(describeFeeSchedule(validateFeeSchedule(good).schedule)).toBe(
+ 'Fee starts at 30% and falls to 1% over about 80 seconds (200 slots, 20 steps, with the steepest drop first).',
+ );
+ expect(describeFeeSchedule({ start_fee_bps: 100, end_fee_bps: 100 })).toBe('Fee is a flat 1% from the first trade.');
+ });
+
+ it('states the referral share without promising returns', () => {
+ expect(referralShareOfTradingFeePercent()).toBe(4);
+ expect(describeReferral()).toMatch(/4% of the fee/);
+ expect(describeReferral()).not.toMatch(/buyback|return|profit/i);
+ });
+});
+
+describe('validateShareholders (shared fee vault)', () => {
+ const rows = (...bps) => bps.map((share_bps, i) => ({ address: wallet(i + 1), share_bps }));
+
+ it('accepts one to ten holders that total 100%', () => {
+ expect(validateShareholders(rows(10_000)).ok).toBe(true);
+ expect(validateShareholders(rows(...Array(10).fill(1_000))).ok).toBe(true);
+ expect(validateShareholders([{ address: THREE_MINT, percent: 100 }]).ok).toBe(true);
+ });
+
+ it('rejects shares that do not total 100%', () => {
+ const under = validateShareholders(rows(5_000, 4_000));
+ expect(under.ok).toBe(false);
+ expect(under.errors.join(' ')).toMatch(/total 100% \(currently 90%\)/);
+ expect(validateShareholders(rows(6_000, 5_000)).ok).toBe(false);
+ });
+
+ it('rejects more than ten holders, duplicates, bad addresses and empty lists', () => {
+ expect(validateShareholders(rows(...Array(11).fill(909))).errors.join(' ')).toMatch(/at most 10/);
+ const dup = validateShareholders([
+ { address: wallet(1), share_bps: 5_000 },
+ { address: wallet(1), share_bps: 5_000 },
+ ]);
+ expect(dup.errors.join(' ')).toMatch(/repeats/);
+ expect(validateShareholders([{ address: 'not-a-wallet', share_bps: 10_000 }]).ok).toBe(false);
+ expect(validateShareholders([]).ok).toBe(false);
+ });
+
+ it('returns basis points ready for the fee-sharing instruction', () => {
+ const r = validateShareholders([
+ { address: wallet(1), percent: 33.33 },
+ { address: wallet(2), percent: 66.67 },
+ ]);
+ expect(r.shareholders.map((s) => s.share_bps)).toEqual([3333, 6667]);
+ });
+});
+
+describe('previewFeeConfig', () => {
+ it('builds the live lane schedule through the SDK validators', async () => {
+ const p = await previewFeeConfig();
+ expect(p.schedule).toEqual(defaultFeeSchedule());
+ expect(p.fee_curve[0].fee_bps).toBe(5_000);
+ expect(p.preview).toMatch(/^Fee starts at 50%/);
+ });
+
+ it('carries a candidate schedule onto the SDK-built config and decays monotonically', async () => {
+ const p = await previewFeeConfig(good);
+ expect(p.config.poolFees.baseFee.cliffFeeNumerator.toString()).toBe('300000000');
+ const fees = p.fee_curve.map((c) => c.fee_bps);
+ expect(fees[0]).toBe(3_000);
+ for (let i = 1; i < fees.length; i++) expect(fees[i]).toBeLessThan(fees[i - 1]);
+ expect(await feeBpsAtSlot(curveBuildParams({ feeSchedule: good }).fee.baseFeeParams, 10_000)).toBe(fees.at(-1));
+ });
+
+ it('supports a linear schedule', async () => {
+ const p = await previewFeeConfig({ ...good, mode: 'linear' });
+ expect(p.fee_curve[2].fee_bps).toBeGreaterThan(1_000);
+ expect(p.fee_curve.at(-1).fee_bps).toBeGreaterThanOrEqual(100);
+ });
+
+ it('turns validator and SDK failures into 400s that name the problem', async () => {
+ await expect(previewFeeConfig({ ...good, mode: 'rate_limiter' })).rejects.toMatchObject({ status: 400, code: 'validation_error' });
+ await expect(previewFeeConfig({ ...good, start_fee_bps: 100, end_fee_bps: 500 })).rejects.toMatchObject({ status: 400 });
+ await expect(previewFeeConfig({ ...good, start_fee_bps: 26, end_fee_bps: 25, periods: 60000, duration_slots: 60000 })).rejects.toMatchObject({ status: 400 });
+ });
+});
+
+describe('laneInfo fee surface', () => {
+ it('publishes the schedule, its preview, the limits and the referral share', () => {
+ const info = laneInfo('mainnet');
+ expect(info.fee_schedule).toEqual(defaultFeeSchedule());
+ expect(info.fee_schedule_preview).toMatch(/falls to 1%/);
+ expect(info.fee_limits).toMatchObject({ min_fee_bps: 25, max_fee_bps: 9900 });
+ expect(info.referral.share_of_trading_fee_percent).toBe(4);
+ });
+});
diff --git a/tests/native-launch-curve.test.js b/tests/native-launch-curve.test.js
index 55f5229e3..5dc01531a 100644
--- a/tests/native-launch-curve.test.js
+++ b/tests/native-launch-curve.test.js
@@ -11,8 +11,7 @@ import {
buildCurveWithMarketCap,
validateConfigParameters,
getBaseFeeParams,
- getBaseFeeNumerator,
- feeNumeratorToBps,
+ calculateFeeSchedulerEndingBaseFeeBps,
TokenType,
TokenDecimal,
TokenAuthorityOption,
@@ -25,6 +24,7 @@ import {
import { Keypair } from '@solana/web3.js';
import BN from 'bn.js';
import { NATIVE_LANE, curveBuildParams, configKeyFor, laneInfo } from '../api/_lib/native-launch/config.js';
+import { feeBpsAtSlot as feeBpsAtSlotFor } from '../api/_lib/native-launch/fee-config.js';
const params = () => curveBuildParams();
@@ -106,48 +106,47 @@ describe('curveBuildParams', () => {
});
describe('anti-snipe fee schedule', () => {
- // feeAtSlot mirrors exactly what the DBC program does on-chain: resolve the
- // scheduler's cliff/reduction factors once (getBaseFeeParams), then evaluate
- // the fee at a given slot since pool activation (getBaseFeeNumerator). No
- // network call, no mocking of the curve math itself.
- const schedulerParams = () => getBaseFeeParams(params().fee.baseFeeParams);
- const activationPoint = new BN(0);
- function feeBpsAtSlot(slot) {
- const sp = schedulerParams();
- const numerator = getBaseFeeNumerator(
- sp.cliffFeeNumerator,
- sp.firstFactor,
- sp.secondFactor,
- sp.thirdFactor,
- sp.baseFeeMode,
- new BN(slot),
- activationPoint,
- );
- return feeNumeratorToBps(numerator);
- }
+ // Evaluates the scheduler the way the DBC program does: resolve the cliff and
+ // reduction factors once (getBaseFeeParams), then the fee at a slot since pool
+ // activation. No network call, no mocking of the curve math itself.
+ const feeBpsAtSlot = (slot) => feeBpsAtSlotFor(params().fee.baseFeeParams, slot);
- it('starts at the configured anti-snipe fee in the pool\'s first slot', () => {
- expect(feeBpsAtSlot(0)).toBe(NATIVE_LANE.antiSnipeStartFeeBps);
+ it('starts at the configured anti-snipe fee in the pool\'s first slot', async () => {
+ expect(await feeBpsAtSlot(0)).toBe(NATIVE_LANE.antiSnipeStartFeeBps);
});
- it('decays monotonically slot by slot across the decay window', () => {
- let previous = feeBpsAtSlot(0);
+ it('decays monotonically slot by slot across the decay window', async () => {
+ let previous = await feeBpsAtSlot(0);
for (let slot = 1; slot <= NATIVE_LANE.antiSnipeDecaySlots; slot++) {
- const fee = feeBpsAtSlot(slot);
+ const fee = await feeBpsAtSlot(slot);
expect(fee).toBeLessThanOrEqual(previous);
previous = fee;
}
});
- it('reaches exactly the steady-state fee at the window\'s end, and stays there', () => {
- expect(feeBpsAtSlot(NATIVE_LANE.antiSnipeDecaySlots)).toBe(NATIVE_LANE.antiSnipeEndFeeBps);
- expect(feeBpsAtSlot(NATIVE_LANE.antiSnipeDecaySlots + 1000)).toBe(NATIVE_LANE.antiSnipeEndFeeBps);
+ it('settles at the steady-state fee at the window\'s end, and stays there', async () => {
+ // The on-chain scheduler rounds the final step to whole reduction units, so the
+ // end fee lands within a bps of the configured value, and agrees with the SDK's
+ // own ending-fee calculator.
+ const end = await feeBpsAtSlot(NATIVE_LANE.antiSnipeDecaySlots);
+ expect(end).toBeGreaterThanOrEqual(NATIVE_LANE.antiSnipeEndFeeBps);
+ expect(end).toBeLessThan(NATIVE_LANE.antiSnipeEndFeeBps + 1);
+ const sp = getBaseFeeParams(params().fee.baseFeeParams);
+ const sdkEnd = calculateFeeSchedulerEndingBaseFeeBps(
+ sp.cliffFeeNumerator,
+ sp.firstFactor,
+ sp.secondFactor,
+ sp.thirdFactor,
+ sp.baseFeeMode,
+ );
+ expect(Math.abs(end - sdkEnd)).toBeLessThan(0.5);
+ expect(await feeBpsAtSlot(NATIVE_LANE.antiSnipeDecaySlots + 1000)).toBe(end);
});
- it('taxes a snipe in the first few slots well above the steady-state fee', () => {
+ it('taxes a snipe in the first few slots well above the steady-state fee', async () => {
// A bot landing in slot 1-3 (one to a couple of blocks after activation)
// should still pay a meaningfully punitive fee, not something close to normal.
- expect(feeBpsAtSlot(2)).toBeGreaterThan(NATIVE_LANE.antiSnipeEndFeeBps * 10);
+ expect(await feeBpsAtSlot(2)).toBeGreaterThan(NATIVE_LANE.antiSnipeEndFeeBps * 10);
});
});
@@ -179,7 +178,8 @@ describe('curve built through the SDK', () => {
it('produces a rising multi-point curve', () => {
const curve = built().curve;
- expect(curve.length).toBeGreaterThan(1);
+ expect(curve.length).toBeGreaterThanOrEqual(1);
+ expect(curve[0].sqrtPrice.gt(built().sqrtStartPrice)).toBe(true);
for (let i = 1; i < curve.length; i++) {
expect(curve[i].sqrtPrice.gt(curve[i - 1].sqrtPrice)).toBe(true);
}
diff --git a/vercel.json b/vercel.json
index 135c490bd..f42bbae40 100644
--- a/vercel.json
+++ b/vercel.json
@@ -4616,7 +4616,7 @@
"dest": "/api/pump/[action]?action=launches"
},
{
- "src": "/api/native-launch/(config|quote|pool|launch-prep|launch-confirm|launches)",
+ "src": "/api/native-launch/(config|quote|pool|launch-prep|launch-confirm|launches|swap-prep|fee-config)",
"dest": "/api/native-launch/[action]?action=$1"
},
{