Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(launchpad): quote every native launch in $THREE, with buy and sell on the curve
ni3a06f42ded465d
diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 13f098dd0..8ed3d5505 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -1349,6 +1349,11 @@ export const env = {get NATIVE_LAUNCH_CONFIG_KEY_DEVNET() {return addr(opt('NATIVE_LAUNCH_CONFIG_KEY_DEVNET'));},+ // Devnet stand-in for $THREE (which exists on mainnet only): the quote mint the+ // devnet native-launch config was created against.+ get NATIVE_LAUNCH_QUOTE_MINT_DEVNET() {+ return addr(opt('NATIVE_LAUNCH_QUOTE_MINT_DEVNET'));+ },// Platform trading-fee claimer + leftover receiver for native launches.// Defaults (in the create-config script) to the treasury wallet.get NATIVE_LAUNCH_FEE_WALLET() {diff --git a/api/_lib/native-launch/config.js b/api/_lib/native-launch/config.jsindex 783d8d750..247a2211a 100644--- a/api/_lib/native-launch/config.js+++ b/api/_lib/native-launch/config.js@@ -5,21 +5,37 @@// platform's share of trading fees, and every pool created under our config// key belongs to the three.ws launchpad.//-// Curve design (v1, SOL-quoted, pump-parity graduation):+// Curve design (v2, $THREE-quoted):+// - every coin is priced in, bought with, and graduates into a pool against+// $THREE. Buying any coin on this lane means buying $THREE first, the fees+// creators earn are paid in $THREE, and each graduation locks the $THREE it+// raised in a pool nobody can withdraw. SOL-quoted launches are what the+// pump.fun lane is for; this lane exists to put $THREE at the centre.// - 1B supply, 6 decimals, immutable metadata authority (no rug lever)-// - starts at ~28 SOL market cap, graduates at ~410 SOL market cap-// (≈85 SOL raised on the curve — the same shape traders already know)-// - 1% trading fee in SOL, split 50/50 creator / three.ws, plus Meteora's+// - starts at a 4M $THREE market cap, graduates at 60M $THREE+// (about 12.3M $THREE raised on the curve, roughly 1.2% of $THREE's supply+// per graduated coin). Sized to match pump.fun's 28 -> 410 SOL shape at the+// $THREE price on 2026-09-20. The thresholds are fixed in the on-chain+// config, so re-sizing them later means creating a new config and+// re-pinning the env key; coins already launched keep the curve they had.+// - 1% trading fee in $THREE, split 50/50 creator / three.ws, plus Meteora's// volatility-scaled dynamic fee on top during spikes// - graduates to DAMM v2 with 100% of LP permanently locked (50 creator /-// 50 platform) — the pool can never be pulled, both sides earn LP fees+// 50 platform): the pool can never be pulled, both sides earn LP fees// forever-// - 1% migration fee on the raised SOL, split 50/50 creator / three.ws+// - 1% migration fee on the raised $THREE, split 50/50 creator / three.ws+//+// The quote mint is verified acceptable to the DBC program: $THREE is a Token-2022+// mint carrying only the metadata-pointer and token-metadata extensions, with no+// mint or freeze authority, and a mainnet simulation of createConfig against it+// succeeds (scripts/native-launchpad-create-config.mjs --simulate).//// The partner config account is created once per network by// scripts/native-launchpad-create-config.mjs and pinned via env:// NATIVE_LAUNCH_CONFIG_KEY (mainnet config pubkey)// NATIVE_LAUNCH_CONFIG_KEY_DEVNET (devnet config pubkey)+// NATIVE_LAUNCH_QUOTE_MINT_DEVNET (devnet stand-in for $THREE, which only+// exists on mainnet)// NATIVE_LAUNCH_FEE_WALLET (platform fee claimer + leftover receiver)import { env } from '../env.js';@@ -27,14 +43,15 @@ import { env } from '../env.js';export const NATIVE_LANE = {id: 'native',label: 'three.ws launchpad',- quote: 'SOL',+ quote: '$THREE',+ quoteDecimals: 6,totalSupply: 1_000_000_000,decimals: 6,- initialMarketCapSol: 28,- migrationMarketCapSol: 410,- // buildCurveWithMarketCap resolves this to ~85.12 SOL for the params above;- // kept here as display metadata only — the on-chain config is authoritative.- graduationSolApprox: 85,+ initialMarketCapThree: 4_000_000,+ migrationMarketCapThree: 60_000_000,+ // buildCurveWithMarketCap resolves this to 12,338,105 $THREE for the params+ // above; kept here as display metadata only. The on-chain config is authoritative.+ graduationThreeApprox: 12_340_000,tradeFeeBps: 100,creatorTradeFeePercent: 50, // % of the trade fee that goes to the coin creatormigrationFeePercent: 1,@@ -50,7 +67,7 @@ export function curveBuildParams() {token: {tokenType: 0, // TokenType.SPLTokentokenBaseDecimal: NATIVE_LANE.decimals, // TokenDecimal.SIX- tokenQuoteDecimal: 9, // TokenDecimal.NINE (SOL)+ tokenQuoteDecimal: NATIVE_LANE.quoteDecimals, // TokenDecimal.SIX ($THREE)tokenAuthorityOption: 1, // TokenAuthorityOption.ImmutabletotalTokenSupply: NATIVE_LANE.totalSupply,// The DBC program requires curve + migration + leftover to sum exactly@@ -69,7 +86,7 @@ export function curveBuildParams() {},},dynamicFeeEnabled: true,- collectFeeMode: 0, // CollectFeeMode.QuoteToken (fees accrue in SOL)+ collectFeeMode: 0, // CollectFeeMode.QuoteToken (fees accrue in $THREE)creatorTradingFeePercentage: NATIVE_LANE.creatorTradeFeePercent,poolCreationFee: 0,enableFirstSwapWithMinFee: true, // creator's own first buy pays the minimum fee@@ -96,8 +113,8 @@ export function curveBuildParams() {cliffDurationFromMigrationTime: 0,},activationType: 0, // ActivationType.Slot- initialMarketCap: NATIVE_LANE.initialMarketCapSol,- migrationMarketCap: NATIVE_LANE.migrationMarketCapSol,+ initialMarketCap: NATIVE_LANE.initialMarketCapThree,+ migrationMarketCap: NATIVE_LANE.migrationMarketCapThree,};}@@ -107,6 +124,14 @@ export function configKeyFor(network) {: env.NATIVE_LAUNCH_CONFIG_KEY || null;}+// The mint every coin on this lane is quoted in: $THREE on mainnet. $THREE does not+// exist on devnet, so devnet runs against a stand-in mint with the same token+// program, decimals and extensions (scripts/native-launchpad-create-config.mjs+// --network devnet creates one and prints the env line).+export function quoteMintFor(network) {+ return network === 'devnet' ? env.NATIVE_LAUNCH_QUOTE_MINT_DEVNET || null : env.THREE_TOKEN_MINT;+}+export function feeWallet() {return env.NATIVE_LAUNCH_FEE_WALLET || null;}@@ -121,11 +146,13 @@ export function laneInfo(network = 'mainnet') {network,config_key: configKeyFor(network),quote: NATIVE_LANE.quote,+ quote_mint: quoteMintFor(network),+ quote_decimals: NATIVE_LANE.quoteDecimals,total_supply: NATIVE_LANE.totalSupply,decimals: NATIVE_LANE.decimals,- initial_market_cap_sol: NATIVE_LANE.initialMarketCapSol,- migration_market_cap_sol: NATIVE_LANE.migrationMarketCapSol,- graduation_sol_approx: NATIVE_LANE.graduationSolApprox,+ initial_market_cap_three: NATIVE_LANE.initialMarketCapThree,+ migration_market_cap_three: NATIVE_LANE.migrationMarketCapThree,+ graduation_three_approx: NATIVE_LANE.graduationThreeApprox,trade_fee_bps: NATIVE_LANE.tradeFeeBps,fee_split: {creator_percent: NATIVE_LANE.creatorTradeFeePercent,@@ -133,6 +160,6 @@ export function laneInfo(network = 'mainnet') {},migration_fee_percent: NATIVE_LANE.migrationFeePercent,lp_locked_percent: NATIVE_LANE.lpLockedPercent,- graduates_to: 'Meteora DAMM v2 (LP permanently locked, creator keeps earning LP fees)',+ 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.jsindex bc19d1e06..44422a4d8 100644--- a/api/_lib/native-launch/dbc.js+++ b/api/_lib/native-launch/dbc.js@@ -5,7 +5,7 @@// so both lanes share RPC selection, rotation, and priority-fee behavior.import { getConnection, buildUnsignedTxBase64, solanaPubkey, txProgramIds } from '../pump.js';-import { curveBuildParams, configKeyFor, NATIVE_LANE } from './config.js';+import { curveBuildParams, configKeyFor, quoteMintFor, NATIVE_LANE } from './config.js';let _sdk = null;async function sdk() {@@ -47,8 +47,65 @@ export function requireConfigKey(network) {return key;}+// The mint this lane is quoted in on `network`, as a PublicKey. A lane with no quote+// mint (devnet before the stand-in is created) is unconfigured, same as no config key.+function requireQuoteMint(network) {+ const mint = solanaPubkey(quoteMintFor(network));+ if (!mint) {+ throw Object.assign(+ new Error(`native launchpad quote mint not set on ${network}: set NATIVE_LAUNCH_QUOTE_MINT_DEVNET`),+ { status: 503, code: 'lane_not_configured' },+ );+ }+ return mint;+}++// The DBC program takes the quote mint's token program as an ordinary account, so a+// Token-2022 quote like $THREE is supported on-chain. The SDK (1.5.x) nevertheless+// hardcodes the legacy SPL Token program into `token_quote_program` when it builds a+// pool-initialize instruction, and the instruction then dies with IncorrectProgramId+// the moment the program tries to create the quote vault. Swaps are unaffected (the+// SDK reads the token program from the config for those). Until the SDK is fixed+// upstream, rewrite that one account, located by its position in the program's own+// IDL so a base mint that legitimately uses the legacy program is never touched.+const POOL_INIT_INSTRUCTIONS = ['initialize_virtual_pool_with_spl_token', 'initialize_virtual_pool_with_token2022'];++export async function withQuoteTokenProgram(instructions, quoteTokenProgramId) {+ const { DynamicBondingCurveIdl: idl } = await sdk();+ const byDiscriminator = new Map();+ for (const name of POOL_INIT_INSTRUCTIONS) {+ const ix = idl.instructions.find((i) => i.name === name);+ const index = ix.accounts.findIndex((a) => a.name === 'token_quote_program');+ byDiscriminator.set(Buffer.from(ix.discriminator).toString('hex'), index);+ }+ for (const ix of instructions) {+ if (ix.programId.toBase58() !== DBC_PROGRAM_ID) continue;+ const index = byDiscriminator.get(Buffer.from(ix.data.subarray(0, 8)).toString('hex'));+ if (index === undefined) continue;+ ix.keys[index] = { ...ix.keys[index], pubkey: quoteTokenProgramId };+ }+ return instructions;+}++// The token program that owns the quote mint on `network`, read from the chain.+async function quoteTokenProgramFor(network, quoteMint) {+ const info = await getConnection({ network }).getAccountInfo(quoteMint);+ if (!info) {+ throw Object.assign(new Error(`quote mint ${quoteMint.toBase58()} not found on ${network}`), {+ status: 503,+ code: 'lane_not_configured',+ });+ }+ return info.owner;+}++const QUOTE_UNIT = 10 ** NATIVE_LANE.quoteDecimals;+const BASE_UNIT = 10 ** NATIVE_LANE.decimals;+const toAtomics = (amount, unit) => Math.round(amount * unit);+const fromAtomics = (v, unit) => Number((v ?? 0).toString()) / unit;+// Unsigned create-pool (+ optional first buy) transaction, base64. The base-// mint keypair and the payer wallet both sign client-side — the server never+// mint keypair and the payer wallet both sign client-side. The server never// holds user keys, matching the pump lane's prep/confirm custody model.export async function buildCreatePoolTx({network = 'mainnet',@@ -58,9 +115,10 @@ export async function buildCreatePoolTx({name,symbol,uri,- solBuyIn = 0,+ threeBuyIn = 0, // creator's optional first buy, in $THREE} = {}) {const configKey = requireConfigKey(network);+ const quoteMint = requireQuoteMint(network);const client = await getDbcClient({ network });const { deriveDbcPoolAddress } = await sdk();const BN = (await import('bn.js')).default;@@ -84,51 +142,45 @@ export async function buildCreatePoolTx({baseMint: mintPk,},firstBuyParam:- solBuyIn > 0+ threeBuyIn > 0? {buyer: payerPk,- buyAmount: new BN(Math.round(solBuyIn * 1e9)),+ buyAmount: new BN(toAtomics(threeBuyIn, QUOTE_UNIT)),minimumAmountOut: new BN(1),referralTokenAccount: null,}: undefined,});- // WSOL is the quote side of every SOL-paired DBC pool.- const { NATIVE_MINT } = await import('@solana/spl-token');- const pool = deriveDbcPoolAddress(NATIVE_MINT, mintPk, configPk);+ const pool = deriveDbcPoolAddress(quoteMint, mintPk, configPk);+ const instructions = await withQuoteTokenProgram(tx.instructions, await quoteTokenProgramFor(network, quoteMint));const txBase64 = await buildUnsignedTxBase64({network,payer: payerPk,- instructions: tx.instructions,+ instructions,});return { txBase64, pool: pool.toBase58(), configKey };}-// True when a confirmed tx actually invoked the DBC program — same guard the-// pump lane applies before recording a launch (see txInvokesPumpProgram).+// True when a parsed/landed transaction invoked the DBC program: the confirm+// step uses this to refuse signatures that aren't native-lane launches.export function txInvokesDbcProgram(tx) {return txProgramIds(tx).has(DBC_PROGRAM_ID);}-// The pool address is deterministic from (quote=WSOL, baseMint, config), so-// derive it instead of scanning with getPoolByBaseMint — that helper needs-// getProgramAccounts, which several RPC tiers block outright.export async function derivePool({ network = 'mainnet', mint } = {}) {const { deriveDbcPoolAddress } = await sdk();- const { NATIVE_MINT } = await import('@solana/spl-token');const configKey = requireConfigKey(network);- return deriveDbcPoolAddress(NATIVE_MINT, solanaPubkey(mint), solanaPubkey(configKey));+ return deriveDbcPoolAddress(requireQuoteMint(network), solanaPubkey(mint), solanaPubkey(configKey));}async function fetchPool({ network, mint }) {const client = await getDbcClient({ network });const pool = await derivePool({ network, mint });- // getPool decodes the anchor account as `{ poolState: VirtualPool }`; older- // SDK builds returned the state flat. Accept both so an SDK bump can't- // silently break every read surface.+ // The SDK has returned both a bare account and a { poolState } wrapper across+ // versions; normalise so callers can rely on one shape.const raw = await client.state.getPool(pool);const account = raw?.poolState ?? raw;if (!account?.config) {@@ -137,14 +189,10 @@ async function fetchPool({ network, mint }) {code: 'pool_not_found',});}- // `account` is the flat state (field reads); `wrapped` is the shape- // swapQuote() expects, which dereferences virtualPool.poolState.const wrapped = raw?.poolState ? raw : { poolState: account };return { client, pool, account, wrapped };}-// Live pool snapshot for the detail/quote surfaces.-// Throws { status: 404, code: 'pool_not_found' } when the mint has no pool.export async function getPoolState({ network = 'mainnet', mint } = {}) {const { client, pool, account } = await fetchPool({ network, mint });const [progress, threshold] = await Promise.all([@@ -157,39 +205,92 @@ export async function getPoolState({ network = 'mainnet', mint } = {}) {creator: account.creator.toBase58(),migrated: Number(account.isMigrated ?? 0) === 1,curve_progress: progress, // 0..1- migration_quote_threshold_sol: Number(threshold.toString()) / 1e9,- quote_reserve_sol: Number(account.quoteReserve.toString()) / 1e9,+ quote_mint: quoteMintFor(network),+ migration_quote_threshold_three: fromAtomics(threshold, QUOTE_UNIT),+ quote_reserve_three: fromAtomics(account.quoteReserve, QUOTE_UNIT),};}-// Buy quote against the live curve: `solIn` SOL -> tokens out (pre-slippage).-export async function quoteBuy({ network = 'mainnet', mint, solIn, slippageBps = 100 } = {}) {+// 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 }) {const BN = (await import('bn.js')).default;const { client, pool, account, wrapped } = await fetchPool({ network, mint });const config = await client.state.getPoolConfig(account.config);const slot = await getConnection({ network }).getSlot();+ const selling = side === 'sell';// client.pool.swapQuote takes a params object; the module-level swapQuote- // export is positional — use the client so an argument-order change in the+ // export is positional. Use the client so an argument-order change in the// SDK can't silently mis-price a quote.const quote = client.pool.swapQuote({virtualPool: wrapped,config,- swapBaseForQuote: false,- amountIn: new BN(Math.round(solIn * 1e9)),+ swapBaseForQuote: selling,+ amountIn: new BN(toAtomics(amountIn, selling ? BASE_UNIT : QUOTE_UNIT)),slippageBps,hasReferral: false,eligibleForFirstSwapWithMinFee: false,currentPoint: new BN(slot),});- const lamports = (v) => Number((v ?? 0).toString()) / 1e9;- const tokens = (v) => Number((v ?? 0).toString()) / 10 ** NATIVE_LANE.decimals;+ return { pool, quote, selling };+}++export async function quoteBuy({ network = 'mainnet', mint, threeIn, slippageBps = 100 } = {}) {+ const { pool, quote } = await quoteSwap({ network, mint, side: 'buy', amountIn: threeIn, slippageBps });+ return {+ pool: pool.toBase58(),+ side: 'buy',+ three_in: threeIn,+ slippage_bps: slippageBps,+ tokens_out: fromAtomics(quote.outputAmount, BASE_UNIT),+ min_tokens_out: fromAtomics(quote.minimumAmountOut ?? quote.outputAmount, BASE_UNIT),+ trading_fee_three: fromAtomics(quote.tradingFee, QUOTE_UNIT),+ protocol_fee_three: fromAtomics(quote.protocolFee, QUOTE_UNIT),+ };+}++export async function quoteSell({ network = 'mainnet', mint, tokensIn, slippageBps = 100 } = {}) {+ const { pool, quote } = await quoteSwap({ network, mint, side: 'sell', amountIn: tokensIn, slippageBps });+ return {+ pool: pool.toBase58(),+ side: 'sell',+ tokens_in: tokensIn,+ slippage_bps: slippageBps,+ three_out: fromAtomics(quote.outputAmount, QUOTE_UNIT),+ min_three_out: fromAtomics(quote.minimumAmountOut ?? quote.outputAmount, QUOTE_UNIT),+ trading_fee_three: fromAtomics(quote.tradingFee, QUOTE_UNIT),+ protocol_fee_three: fromAtomics(quote.protocolFee, QUOTE_UNIT),+ };+}++// 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 } = {}) {+ 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 { pool, quote, selling } = await quoteSwap({ network, mint, side, amountIn, slippageBps });+ const client = await getDbcClient({ network });+ const tx = await client.pool.swap({+ owner: traderPk,+ payer: traderPk,+ pool,+ amountIn: new BN(toAtomics(amountIn, selling ? BASE_UNIT : QUOTE_UNIT)),+ minimumAmountOut: quote.minimumAmountOut ?? quote.outputAmount,+ swapBaseForQuote: selling,+ referralTokenAccount: null,+ });+ const txBase64 = await buildUnsignedTxBase64({ network, payer: traderPk, instructions: tx.instructions });+ const outUnit = selling ? QUOTE_UNIT : BASE_UNIT;return {+ txBase64,pool: pool.toBase58(),- sol_in: solIn,+ side: selling ? 'sell' : 'buy',+ amount_in: amountIn,+ expected_out: fromAtomics(quote.outputAmount, outUnit),+ min_out: fromAtomics(quote.minimumAmountOut ?? quote.outputAmount, outUnit),slippage_bps: slippageBps,- tokens_out: tokens(quote.outputAmount),- min_tokens_out: tokens(quote.minimumAmountOut ?? quote.outputAmount),- trading_fee_sol: lamports(quote.tradingFee),- protocol_fee_sol: lamports(quote.protocolFee),};}diff --git a/api/native-launch/[action].js b/api/native-launch/[action].jsindex f2e09aeec..3e61c7887 100644--- a/api/native-launch/[action].js+++ b/api/native-launch/[action].js@@ -10,7 +10,8 @@//// Action map:// config -> handleConfig (public: lane economics + config key)-// quote -> handleQuote (public: buy quote on a live curve)+// quote -> handleQuote (public: buy or sell quote on a live curve)+// swap-prep -> handleSwapPrep (public: unsigned buy/sell tx for the trader's wallet)// pool -> handlePool (public: pool state / curve progress)// launch-prep -> handleLaunchPrep (authed: unsigned create-pool tx)// launch-confirm -> handleLaunchConfirm (authed: verify + record launch)@@ -32,12 +33,14 @@ import { normalizeGatewayURL } from '../../src/ipfs.js';import { THREE_WS_VANITY, hasThreeWsMark } from '../../src/solana/vanity/brand.js';import { grindVanityNode, GrindExhaustedError } from '../../src/solana/vanity/grinder-node.js';import { verifySignature, solanaPubkey } from '../_lib/pump.js';-import { laneInfo, configKeyFor } from '../_lib/native-launch/config.js';+import { laneInfo, configKeyFor, quoteMintFor } from '../_lib/native-launch/config.js';import {buildCreatePoolTx,txInvokesDbcProgram,getPoolState,quoteBuy,+ quoteSell,+ buildSwapTx,} from '../_lib/native-launch/dbc.js';import { logger } from '../_lib/usage.js';@@ -64,6 +67,9 @@ async function handleConfig(req, res) {// ── quote / pool (public reads) ────────────────────────────────────────────+// Both a coin's supply and $THREE's are 1B, so no single swap can exceed this.+const MAX_SWAP_AMOUNT = 1_000_000_000;+async function handleQuote(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;@@ -72,17 +78,70 @@ async function handleQuote(req, res) {const url = new URL(req.url, `http://${req.headers.host}`);const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';const mint = url.searchParams.get('mint');- const solIn = Number(url.searchParams.get('sol_in') || '0.1');if (!mint || !solanaPubkey(mint)) return error(res, 400, 'validation_error', 'valid mint required');- if (!(solIn > 0) || solIn > 1000) return error(res, 400, 'validation_error', 'sol_in must be in (0, 1000]');+ // A buy is sized in $THREE (three_in), a sell in the coin's own tokens (tokens_in).+ const selling = url.searchParams.has('tokens_in');+ const amount = Number(url.searchParams.get(selling ? 'tokens_in' : 'three_in') || (selling ? '0' : '1000'));+ if (!(amount > 0) || amount > MAX_SWAP_AMOUNT) {+ return error(res, 400, 'validation_error', `${selling ? 'tokens_in' : 'three_in'} must be in (0, ${MAX_SWAP_AMOUNT}]`);+ }try {- const quote = await quoteBuy({ network, mint, solIn });+ const quote = selling+ ? await quoteSell({ network, mint, tokensIn: amount })+ : await quoteBuy({ network, mint, threeIn: amount });return json(res, 200, { network, mint, ...quote });} catch (e) {return error(res, e.status || 500, e.code || 'quote_failed', e.message);}}+// ── swap-prep ──────────────────────────────────────────────────────────────++const swapPrepSchema = z.object({+ mint: z.string().min(32).max(44),+ wallet_address: z.string().min(32).max(44),+ side: z.enum(['buy', 'sell']),+ amount: z.number().positive().max(MAX_SWAP_AMOUNT),+ slippage_bps: z.number().int().min(1).max(5000).default(100),+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),+});++// Builds the unsigned swap and nothing else: the trader's wallet signs and sends it,+// so this needs no session. A buy spends `amount` $THREE, a sell spends `amount` tokens.+async function handleSwapPrep(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(swapPrepSchema, await readJson(req));+ if (!solanaPubkey(body.mint) || !solanaPubkey(body.wallet_address)) {+ return error(res, 400, 'validation_error', 'valid mint and wallet_address required');+ }+ const built = await buildSwapTx({+ network: body.network,+ mint: body.mint,+ trader: body.wallet_address,+ side: body.side,+ amountIn: body.amount,+ slippageBps: body.slippage_bps,+ });+ return json(res, 200, {+ network: body.network,+ mint: body.mint,+ tx_base64: built.txBase64,+ pool: built.pool,+ side: built.side,+ amount_in: built.amount_in,+ expected_out: built.expected_out,+ min_out: built.min_out,+ slippage_bps: built.slippage_bps,+ });+ } catch (e) {+ return error(res, e.status || 500, e.code || 'swap_prep_failed', e.message);+ }+}+async function handlePool(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;@@ -112,7 +171,8 @@ const launchPrepSchema = zsymbol: z.string().trim().min(1).max(10),uri: z.string().url().max(200),network: z.enum(['mainnet', 'devnet']).default('mainnet'),- sol_buy_in: z.number().min(0).max(50).default(0),+ // The creator's optional first buy, in $THREE.+ three_buy_in: z.number().min(0).max(10_000_000).default(0),mint_address: z.string().min(32).max(44).optional(),}).refine((b) => b.agent_id || b.avatar_id, { message: 'agent_id or avatar_id required' });@@ -213,7 +273,7 @@ async function handleLaunchPrep(req, res) {name: body.name,symbol: body.symbol,uri: body.uri,- solBuyIn: body.sol_buy_in,+ threeBuyIn: body.three_buy_in,});} catch (e) {log.warn('create_pool_build_failed', { message: e.message });@@ -314,10 +374,10 @@ async function handleLaunchConfirm(req, res) {const [row] = await sql`insert into native_launches- (agent_id, user_id, network, mint, pool, config_key, name, symbol, metadata_uri, creator_address)+ (agent_id, user_id, network, mint, pool, config_key, name, symbol, metadata_uri, creator_address, quote_mint)values(${p.agent_id}, ${user.id}, ${p.network}, ${p.mint}, ${p.pool}, ${p.config_key},- ${p.name}, ${p.symbol}, ${pending.metadata_uri || null}, ${p.creator_address})+ ${p.name}, ${p.symbol}, ${pending.metadata_uri || null}, ${p.creator_address}, ${quoteMintFor(p.network)})returning id, mint, pool, network, created_at`;@@ -423,6 +483,7 @@ async function dispatch(req, res) {switch (action) {case 'config': return handleConfig(req, res);case 'quote': return handleQuote(req, res);+ case 'swap-prep': return handleSwapPrep(req, res);case 'pool': return handlePool(req, res);case 'launch-prep': return handleLaunchPrep(req, res);case 'launch-confirm': return handleLaunchConfirm(req, res);diff --git a/scripts/native-launchpad-create-config.mjs b/scripts/native-launchpad-create-config.mjsindex dd1ea4ecb..3616ef590 100644--- a/scripts/native-launchpad-create-config.mjs+++ b/scripts/native-launchpad-create-config.mjs@@ -1,43 +1,183 @@#!/usr/bin/env node-// Create the three.ws partner config for the native launchpad (Meteora DBC).+// Create the three.ws native-launchpad partner config on Meteora's Dynamic Bonding+// Curve program. The config fixes the curve, the fee split, the graduation target and+// the quote mint for every coin launched under it. The quote mint is $THREE.//-// One-shot per network. The config account is a fresh keypair that signs its-// own creation; after it lands, pin the printed pubkey in the environment:-// devnet -> NATIVE_LAUNCH_CONFIG_KEY_DEVNET-// mainnet -> NATIVE_LAUNCH_CONFIG_KEY+// node scripts/native-launchpad-create-config.mjs --simulate+// Mainnet dry run. Needs no key and spends nothing: simulates creating the+// config AND a coin's pool under it in one transaction, which proves the DBC+// program accepts $THREE as a quote mint with this curve and can open a+// $THREE-quoted pool (Token-2022 quote vault included).+//+// node scripts/native-launchpad-create-config.mjs --network devnet --create-quote-mint [--airdrop]+// $THREE exists on mainnet only, so devnet first mints a stand-in with the same+// token program (Token-2022), decimals and extensions, then creates the config+// against it. Prints both env lines to pin.//-// Usage:-// node scripts/native-launchpad-create-config.mjs --network devnet-// node scripts/native-launchpad-create-config.mjs --network devnet --airdrop// node scripts/native-launchpad-create-config.mjs --network mainnet+// The real thing. Spends SOL on rent and fees from the partner wallet, so it is+// owner-approved only.//-// The payer/partner keypair comes from NATIVE_LAUNCH_PARTNER_SECRET_BASE58,-// falling back to X402_TREASURY_SECRET_BASE58 (the platform treasury). The-// same wallet becomes feeClaimer + leftoverReceiver unless-// NATIVE_LAUNCH_FEE_WALLET overrides the claimer.+// Signer: NATIVE_LAUNCH_PARTNER_SECRET_BASE58, else X402_TREASURY_SECRET_BASE58.+// Fee claimer: NATIVE_LAUNCH_FEE_WALLET, else the signer.import 'dotenv/config';import bs58 from 'bs58';-import { Connection, Keypair, PublicKey } from '@solana/web3.js';-import { NATIVE_MINT } from '@solana/spl-token';+import {+ Connection,+ Keypair,+ PublicKey,+ SystemProgram,+ Transaction,+ TransactionMessage,+ VersionedTransaction,+} from '@solana/web3.js';+import {+ ExtensionType,+ TOKEN_2022_PROGRAM_ID,+ TYPE_SIZE,+ LENGTH_SIZE,+ getMintLen,+ getAssociatedTokenAddressSync,+ createInitializeMintInstruction,+ createInitializeMetadataPointerInstruction,+ createAssociatedTokenAccountIdempotentInstruction,+ createMintToInstruction,+} from '@solana/spl-token';+import { createInitializeInstruction, pack } from '@solana/spl-token-metadata';import { DynamicBondingCurveClient, buildCurveWithMarketCap } from '@meteora-ag/dynamic-bonding-curve-sdk';-import { curveBuildParams } from '../api/_lib/native-launch/config.js';+import { curveBuildParams, quoteMintFor, NATIVE_LANE } from '../api/_lib/native-launch/config.js';+import { withQuoteTokenProgram } from '../api/_lib/native-launch/dbc.js';const args = process.argv.slice(2);-const network = args.includes('--network') ? args[args.indexOf('--network') + 1] : 'devnet';+const simulate = args.includes('--simulate');+const network = args.includes('--network') ? args[args.indexOf('--network') + 1] : simulate ? 'mainnet' : 'devnet';const doAirdrop = args.includes('--airdrop');+const createQuoteMint = args.includes('--create-quote-mint');if (!['mainnet', 'devnet'].includes(network)) {console.error('--network must be mainnet or devnet');process.exit(1);}+if (createQuoteMint && network !== 'devnet') {+ console.error('--create-quote-mint is devnet only: mainnet is quoted in the real $THREE mint');+ process.exit(1);+}const RPC =network === 'devnet'? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com': process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+const connection = new Connection(RPC, 'confirmed');+const client = new DynamicBondingCurveClient(connection, 'confirmed');+const curveConfig = buildCurveWithMarketCap(curveBuildParams());+const QUOTE_UNIT = 10 ** NATIVE_LANE.quoteDecimals;+console.log(`network: ${network}`);+console.log(+ `curve: graduates at ${(Number(curveConfig.migrationQuoteThreshold.toString()) / QUOTE_UNIT).toLocaleString('en-US')} ${NATIVE_LANE.quote} raised`,+);++async function sendAndConfirm(tx, signers) {+ tx.feePayer = signers[0].publicKey;+ tx.recentBlockhash = (await connection.getLatestBlockhash('confirmed')).blockhash;+ tx.sign(...signers);+ const sig = await connection.sendRawTransaction(tx.serialize());+ for (let i = 0; i < 40; i++) {+ await new Promise((r) => setTimeout(r, 1500));+ const s = (await connection.getSignatureStatuses([sig])).value?.[0];+ if (s?.err) throw new Error(`transaction failed: ${JSON.stringify(s.err)} (${sig})`);+ if (s?.confirmationStatus === 'confirmed' || s?.confirmationStatus === 'finalized') return sig;+ }+ throw new Error(`confirmation timed out, check the signature manually: ${sig}`);+}++// A Token-2022 mint shaped like $THREE: 6 decimals, metadata-pointer and token-metadata+// extensions, and no mint or freeze authority once the supply is out.+async function createStandInQuoteMint(payer) {+ const mint = Keypair.generate();+ const metadata = {+ mint: mint.publicKey,+ name: 'THREE (devnet stand-in)',+ symbol: 'THREE',+ uri: 'https://three.ws/three-token',+ additionalMetadata: [],+ };+ const mintLen = getMintLen([ExtensionType.MetadataPointer]);+ const metadataLen = TYPE_SIZE + LENGTH_SIZE + pack(metadata).length;+ const lamports = await connection.getMinimumBalanceForRentExemption(mintLen + metadataLen);+ const ata = getAssociatedTokenAddressSync(mint.publicKey, payer.publicKey, false, TOKEN_2022_PROGRAM_ID);+ const supply = BigInt(1_000_000_000) * BigInt(QUOTE_UNIT);++ const tx = new Transaction().add(+ SystemProgram.createAccount({+ fromPubkey: payer.publicKey,+ newAccountPubkey: mint.publicKey,+ space: mintLen,+ lamports,+ programId: TOKEN_2022_PROGRAM_ID,+ }),+ createInitializeMetadataPointerInstruction(mint.publicKey, payer.publicKey, mint.publicKey, TOKEN_2022_PROGRAM_ID),+ createInitializeMintInstruction(mint.publicKey, NATIVE_LANE.quoteDecimals, payer.publicKey, null, TOKEN_2022_PROGRAM_ID),+ createInitializeInstruction({+ programId: TOKEN_2022_PROGRAM_ID,+ metadata: mint.publicKey,+ updateAuthority: payer.publicKey,+ mint: mint.publicKey,+ mintAuthority: payer.publicKey,+ name: metadata.name,+ symbol: metadata.symbol,+ uri: metadata.uri,+ }),+ createAssociatedTokenAccountIdempotentInstruction(payer.publicKey, ata, payer.publicKey, mint.publicKey, TOKEN_2022_PROGRAM_ID),+ createMintToInstruction(mint.publicKey, ata, payer.publicKey, supply, [], TOKEN_2022_PROGRAM_ID),+ );+ const sig = await sendAndConfirm(tx, [payer, mint]);+ console.log(`quote: created stand-in ${mint.publicKey.toBase58()} (${sig})`);+ return mint.publicKey;+}++if (simulate) {+ const quoteMint = new PublicKey(quoteMintFor(network));+ // Simulation needs a fee payer that exists and holds SOL, never its signature.+ const payer = new PublicKey(args.includes('--payer') ? args[args.indexOf('--payer') + 1] : '5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9');+ const config = Keypair.generate().publicKey;+ const tx = await client.partner.createConfigAndPool({+ ...curveConfig,+ config,+ feeClaimer: payer,+ leftoverReceiver: payer,+ quoteMint,+ payer,+ preCreatePoolParam: {+ name: 'Simulated Launch',+ symbol: 'SIM',+ uri: 'https://three.ws/launchpad',+ poolCreator: payer,+ baseMint: Keypair.generate().publicKey,+ },+ });+ const quoteTokenProgram = (await connection.getAccountInfo(quoteMint)).owner;+ const message = new TransactionMessage({+ payerKey: payer,+ recentBlockhash: (await connection.getLatestBlockhash()).blockhash,+ instructions: await withQuoteTokenProgram(tx.instructions, quoteTokenProgram),+ }).compileToV0Message();+ const sim = await connection.simulateTransaction(new VersionedTransaction(message), {+ sigVerify: false,+ replaceRecentBlockhash: true,+ });+ console.log(`quote: ${quoteMint.toBase58()}`);+ if (sim.value.err) {+ console.error('simulation FAILED:', JSON.stringify(sim.value.err));+ console.error((sim.value.logs || []).slice(-6).join('\n'));+ process.exit(1);+ }+ console.log(+ `simulation OK: config + a ${NATIVE_LANE.quote}-quoted pool created by the live DBC program (${sim.value.unitsConsumed} compute units)`,+ );+ process.exit(0);+}-const secret =- process.env.NATIVE_LAUNCH_PARTNER_SECRET_BASE58 || process.env.X402_TREASURY_SECRET_BASE58;+const secret = process.env.NATIVE_LAUNCH_PARTNER_SECRET_BASE58 || process.env.X402_TREASURY_SECRET_BASE58;if (!secret) {console.error('set NATIVE_LAUNCH_PARTNER_SECRET_BASE58 (or X402_TREASURY_SECRET_BASE58)');process.exit(1);@@ -47,20 +187,17 @@ const feeClaimer = process.env.NATIVE_LAUNCH_FEE_WALLET? new PublicKey(process.env.NATIVE_LAUNCH_FEE_WALLET): partner.publicKey;-const connection = new Connection(RPC, 'confirmed');-if (doAirdrop && network === 'devnet') {console.log(`airdropping 2 SOL to ${partner.publicKey.toBase58()} …`);try {const sig = await connection.requestAirdrop(partner.publicKey, 2e9);await connection.confirmTransaction(sig, 'confirmed');} catch (e) {- console.warn(`airdrop failed (${e.message}) — continuing with existing balance`);+ console.warn(`airdrop failed (${e.message}), continuing with existing balance`);}}const balance = await connection.getBalance(partner.publicKey);-console.log(`network: ${network}`);console.log(`partner: ${partner.publicKey.toBase58()} (${(balance / 1e9).toFixed(4)} SOL)`);console.log(`claimer: ${feeClaimer.toBase58()}`);if (balance < 0.05e9) {@@ -68,50 +205,28 @@ if (balance < 0.05e9) {process.exit(1);}-const curveConfig = buildCurveWithMarketCap(curveBuildParams());-console.log(- `curve: graduation at ${(Number(curveConfig.migrationQuoteThreshold.toString()) / 1e9).toFixed(2)} SOL raised`,-);+const quoteMint = createQuoteMint ? await createStandInQuoteMint(partner) : new PublicKey(quoteMintFor(network) || PublicKey.default);+if (quoteMint.equals(PublicKey.default)) {+ console.error('no quote mint on devnet: pass --create-quote-mint, or set NATIVE_LAUNCH_QUOTE_MINT_DEVNET');+ process.exit(1);+}+console.log(`quote: ${quoteMint.toBase58()}`);-const client = new DynamicBondingCurveClient(connection, 'confirmed');const configKeypair = Keypair.generate();-const tx = await client.partner.createConfig({...curveConfig,config: configKeypair.publicKey,feeClaimer,leftoverReceiver: feeClaimer,- quoteMint: NATIVE_MINT,+ quoteMint,payer: partner.publicKey,});--// Poll for confirmation instead of sendAndConfirmTransaction: several devnet-// RPCs (e.g. Alchemy) reject the signatureSubscribe websocket, which makes the-// subscription-based confirm throw expiry errors on transactions that landed.-tx.feePayer = partner.publicKey;-tx.recentBlockhash = (await connection.getLatestBlockhash('confirmed')).blockhash;-tx.sign(partner, configKeypair);-const sig = await connection.sendRawTransaction(tx.serialize());-let landed = false;-for (let i = 0; i < 40 && !landed; i++) {- await new Promise((r) => setTimeout(r, 1500));- const st = await connection.getSignatureStatuses([sig]);- const s = st.value?.[0];- if (s?.err) {- console.error('transaction failed:', JSON.stringify(s.err));- process.exit(1);- }- landed = s?.confirmationStatus === 'confirmed' || s?.confirmationStatus === 'finalized';-}-if (!landed) {- console.error(`confirmation timed out — check the signature manually: ${sig}`);- process.exit(1);-}+const sig = await sendAndConfirm(tx, [partner, configKeypair]);console.log('');console.log(`config created: ${configKeypair.publicKey.toBase58()}`);console.log(`tx: https://solscan.io/tx/${sig}${network === 'devnet' ? '?cluster=devnet' : ''}`);console.log('');-console.log(- `pin it: ${network === 'devnet' ? 'NATIVE_LAUNCH_CONFIG_KEY_DEVNET' : 'NATIVE_LAUNCH_CONFIG_KEY'}=${configKeypair.publicKey.toBase58()}`,-);+console.log('pin it:');+console.log(` ${network === 'devnet' ? 'NATIVE_LAUNCH_CONFIG_KEY_DEVNET' : 'NATIVE_LAUNCH_CONFIG_KEY'}=${configKeypair.publicKey.toBase58()}`);+if (network === 'devnet') console.log(` NATIVE_LAUNCH_QUOTE_MINT_DEVNET=${quoteMint.toBase58()}`);diff --git a/scripts/native-launchpad-e2e-devnet.mjs b/scripts/native-launchpad-e2e-devnet.mjsindex 37f88e9f7..71c0aa179 100644--- a/scripts/native-launchpad-e2e-devnet.mjs+++ b/scripts/native-launchpad-e2e-devnet.mjs@@ -4,80 +4,81 @@import 'dotenv/config';import bs58 from 'bs58';import { Connection, Keypair, VersionedTransaction } from '@solana/web3.js';-import BN from 'bn.js';-import {- buildCreatePoolTx,- getPoolState,- quoteBuy,- getDbcClient,-} from '../api/_lib/native-launch/dbc.js';+import { buildCreatePoolTx, buildSwapTx, getPoolState, quoteBuy } from '../api/_lib/native-launch/dbc.js';-const conn = new Connection(process.env.SOLANA_RPC_URL_DEVNET, 'confirmed');-const wallet = Keypair.fromSecretKey(bs58.decode(process.env.X402_TREASURY_SECRET_BASE58));+const conn = new Connection(process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com', 'confirmed');+const secret = process.env.NATIVE_LAUNCH_PARTNER_SECRET_BASE58 || process.env.X402_TREASURY_SECRET_BASE58;+if (!secret || !process.env.NATIVE_LAUNCH_CONFIG_KEY_DEVNET || !process.env.NATIVE_LAUNCH_QUOTE_MINT_DEVNET) {+ console.error(+ 'needs a devnet signer plus NATIVE_LAUNCH_CONFIG_KEY_DEVNET and NATIVE_LAUNCH_QUOTE_MINT_DEVNET:\n' ++ ' node scripts/native-launchpad-create-config.mjs --network devnet --create-quote-mint --airdrop',+ );+ process.exit(1);+}+// The signer that ran --create-quote-mint holds the whole stand-in $THREE supply.+const wallet = Keypair.fromSecretKey(bs58.decode(secret));const mintKp = Keypair.generate();+const mint = mintKp.publicKey.toBase58();-async function sendAndPoll(raw) {- const sig = await conn.sendRawTransaction(raw, { skipPreflight: false });+async function signAndLand(txBase64, signers) {+ const tx = VersionedTransaction.deserialize(Buffer.from(txBase64, 'base64'));+ tx.sign(signers);+ const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });for (let i = 0; i < 40; i++) {await new Promise((r) => setTimeout(r, 1500));- const st = await conn.getSignatureStatuses([sig]);- const s = st.value?.[0];+ const s = (await conn.getSignatureStatuses([sig])).value?.[0];if (s?.err) throw new Error(`tx failed: ${JSON.stringify(s.err)} (${sig})`);if (s?.confirmationStatus === 'confirmed' || s?.confirmationStatus === 'finalized') return sig;}throw new Error(`confirm timeout: ${sig}`);}+function assert(cond, message) {+ if (!cond) throw new Error(`assertion failed: ${message}`);+}+console.log('wallet:', wallet.publicKey.toBase58());-console.log('mint: ', mintKp.publicKey.toBase58());+console.log('mint: ', mint);-// 1 — build the unsigned create-pool tx exactly like /api/native-launch/launch-prepconst built = await buildCreatePoolTx({network: 'devnet',payer: wallet.publicKey.toBase58(),creator: wallet.publicKey.toBase58(),- baseMint: mintKp.publicKey.toBase58(),+ baseMint: mint,name: 'Native Lane Test',symbol: 'NLT',uri: 'https://three.ws/launchpad',- solBuyIn: 0.05,+ threeBuyIn: 50_000,});console.log('pool: ', built.pool);+const createSig = await signAndLand(built.txBase64, [wallet, mintKp]);+console.log('create + first buy landed:', createSig);-// 2 — sign like the frontend does (user wallet + mint keypair) and send-const tx = VersionedTransaction.deserialize(Buffer.from(built.txBase64, 'base64'));-tx.sign([wallet, mintKp]);-const createSig = await sendAndPoll(tx.serialize());-console.log('create landed:', createSig);+const afterCreate = await getPoolState({ network: 'devnet', mint });+console.log('state after create + first buy:', JSON.stringify(afterCreate, null, 1));+assert(afterCreate.quote_reserve_three > 0, 'the first buy put $THREE into the curve');-// 3 — pool state via the same module the /pool endpoint uses-const state = await getPoolState({ network: 'devnet', mint: mintKp.publicKey.toBase58() });-console.log('state after create+first buy:', JSON.stringify(state, null, 1));+const quote = await quoteBuy({ network: 'devnet', mint, threeIn: 250_000 });+console.log(`quote 250,000 $THREE -> ${quote.tokens_out} tokens, fee ${quote.trading_fee_three} $THREE`);-// 4 — quote a 0.5 SOL buy via the /quote path-const q = await quoteBuy({ network: 'devnet', mint: mintKp.publicKey.toBase58(), solIn: 0.5 });-console.log('quote 0.5 SOL ->', q.tokens_out, 'tokens, fee', q.trading_fee_sol, 'SOL');+const buy = await buildSwapTx({ network: 'devnet', mint, trader: wallet.publicKey.toBase58(), side: 'buy', amountIn: 250_000 });+console.log('buy landed: ', await signAndLand(buy.txBase64, [wallet]));+const afterBuy = await getPoolState({ network: 'devnet', mint });+assert(afterBuy.curve_progress > afterCreate.curve_progress, 'a buy moves the curve forward');-// 5 — execute a real 0.5 SOL buy on the curve-const client = await getDbcClient({ network: 'devnet' });-const swapTx = await client.pool.swap({- owner: wallet.publicKey,- pool: built.pool,- amountIn: new BN(0.5e9),- minimumAmountOut: new BN(1),- swapBaseForQuote: false,- referralTokenAccount: null,+const sell = await buildSwapTx({+ network: 'devnet',+ mint,+ trader: wallet.publicKey.toBase58(),+ side: 'sell',+ amountIn: Math.floor(buy.expected_out / 2),});-swapTx.feePayer = wallet.publicKey;-swapTx.recentBlockhash = (await conn.getLatestBlockhash()).blockhash;-swapTx.sign(wallet);-const buySig = await sendAndPoll(swapTx.serialize());-console.log('buy landed:', buySig);+console.log('sell landed:', await signAndLand(sell.txBase64, [wallet]));+const afterSell = await getPoolState({ network: 'devnet', mint });+assert(afterSell.quote_reserve_three < afterBuy.quote_reserve_three, 'a sell pays $THREE back out of the curve');-// 6 — state after the buy: progress must have moved-const after = await getPoolState({ network: 'devnet', mint: mintKp.publicKey.toBase58() });-console.log('progress:', state.curve_progress, '->', after.curve_progress);-console.log('quote reserve SOL:', state.quote_reserve_sol, '->', after.quote_reserve_sol);+console.log('progress: ', afterCreate.curve_progress, '->', afterBuy.curve_progress, '->', afterSell.curve_progress);+console.log('$THREE in curve: ', afterCreate.quote_reserve_three, '->', afterBuy.quote_reserve_three, '->', afterSell.quote_reserve_three);console.log('');console.log('E2E OK');console.log(`explorer: https://solscan.io/tx/${createSig}?cluster=devnet`);diff --git a/tests/native-launch-curve.test.js b/tests/native-launch-curve.test.jsindex 8ae728abe..8331e9b5b 100644--- a/tests/native-launch-curve.test.js+++ b/tests/native-launch-curve.test.js@@ -25,8 +25,9 @@ import { NATIVE_LANE, curveBuildParams, configKeyFor, laneInfo } from '../api/_lconst params = () => curveBuildParams();describe('native lane economics', () => {- it('quotes in SOL with a fixed 1B supply at 6 decimals', () => {- expect(NATIVE_LANE.quote).toBe('SOL');+ it('quotes in $THREE with a fixed 1B supply at 6 decimals', () => {+ expect(NATIVE_LANE.quote).toBe('$THREE');+ expect(NATIVE_LANE.quoteDecimals).toBe(6);expect(NATIVE_LANE.totalSupply).toBe(1_000_000_000);expect(NATIVE_LANE.decimals).toBe(6);});@@ -51,7 +52,7 @@ describe('native lane economics', () => {});it('graduates above its starting market cap', () => {- expect(NATIVE_LANE.migrationMarketCapSol).toBeGreaterThan(NATIVE_LANE.initialMarketCapSol);+ expect(NATIVE_LANE.migrationMarketCapThree).toBeGreaterThan(NATIVE_LANE.initialMarketCapThree);});});@@ -60,7 +61,7 @@ describe('curveBuildParams', () => {const p = params();expect(p.token.tokenType).toBe(TokenType.SPLToken);expect(p.token.tokenBaseDecimal).toBe(TokenDecimal.SIX);- expect(p.token.tokenQuoteDecimal).toBe(TokenDecimal.NINE);+ expect(p.token.tokenQuoteDecimal).toBe(TokenDecimal.SIX);// Immutable metadata: no one, including us, can rewrite a launched coin.expect(p.token.tokenAuthorityOption).toBe(TokenAuthorityOption.Immutable);expect(p.fee.baseFeeParams.baseFeeMode).toBe(BaseFeeMode.FeeSchedulerLinear);@@ -104,11 +105,11 @@ describe('curve built through the SDK', () => {).not.toThrow();});- it('graduates near the advertised SOL raise', () => {- const sol = Number(built().migrationQuoteThreshold.toString()) / 1e9;- // laneInfo advertises graduation_sol_approx to users; it must stay within- // a SOL of what the curve actually enforces or the UI is lying.- expect(Math.abs(sol - NATIVE_LANE.graduationSolApprox)).toBeLessThan(1);+ it('graduates near the advertised $THREE raise', () => {+ const three = Number(built().migrationQuoteThreshold.toString()) / 10 ** NATIVE_LANE.quoteDecimals;+ // laneInfo advertises graduation_three_approx to users; it must stay within+ // 0.1% of what the curve actually enforces or the UI is lying.+ expect(Math.abs(three - NATIVE_LANE.graduationThreeApprox) / three).toBeLessThan(0.001);});it('carries the creator fee share and migration fee onto the config', () => {diff --git a/tests/native-launch-endpoint.test.js b/tests/native-launch-endpoint.test.jsindex b2e964fb6..4e6f0101f 100644--- a/tests/native-launch-endpoint.test.js+++ b/tests/native-launch-endpoint.test.js@@ -84,7 +84,17 @@ vi.mock('../api/_lib/native-launch/dbc.js', () => ({configKey: 'ConfigKey111111111111111111111111111111111',})),getPoolState: vi.fn(async () => ({ pool: 'PoolAddress11111111111111111111111111111111' })),- quoteBuy: vi.fn(async () => ({ pool: 'p', sol_in: 1, tokens_out: 100 })),+ quoteBuy: vi.fn(async () => ({ pool: 'p', side: 'buy', three_in: 1000, tokens_out: 100 })),+ quoteSell: vi.fn(async () => ({ pool: 'p', side: 'sell', tokens_in: 100, three_out: 990 })),+ buildSwapTx: vi.fn(async ({ side, amountIn, slippageBps }) => ({+ txBase64: 'AQID',+ pool: 'PoolAddress11111111111111111111111111111111',+ side,+ amount_in: amountIn,+ expected_out: 100,+ min_out: 99,+ slippage_bps: slippageBps,+ })),}));import handler from '../api/native-launch/[action].js';@@ -150,14 +160,48 @@ describe('config', () => {describe('quote', () => {it('rejects a malformed mint', async () => {- const r = await call('quote', { query: { mint: 'not-a-mint', sol_in: '1' } });+ const r = await call('quote', { query: { mint: 'not-a-mint', three_in: '1000' } });expect(r.status).toBe(400);expect(r.body.error).toBe('validation_error');});- it('rejects a non-positive or oversized sol_in', async () => {- for (const sol_in of ['0', '-1', '100000']) {- const r = await call('quote', { query: { mint: MINT, sol_in } });+ it('rejects a non-positive or oversized three_in', async () => {+ for (const three_in of ['0', '-1', '1000000001']) {+ const r = await call('quote', { query: { mint: MINT, three_in } });+ expect(r.status).toBe(400);+ }+ });++ it('quotes a buy in $THREE by default and a sell when tokens_in is given', async () => {+ const buy = await call('quote', { query: { mint: MINT, three_in: '1000' } });+ expect(buy.status).toBe(200);+ expect(buy.body).toMatchObject({ side: 'buy', three_in: 1000 });++ const sell = await call('quote', { query: { mint: MINT, tokens_in: '100' } });+ expect(sell.status).toBe(200);+ expect(sell.body).toMatchObject({ side: 'sell', three_out: 990 });+ });+});++describe('swap-prep', () => {+ const body = { mint: MINT, wallet_address: WALLET, side: 'buy', amount: 5000, network: 'devnet' };++ it('returns an unsigned buy sized in $THREE, with no session required', async () => {+ sessionUser = null;+ const r = await call('swap-prep', { method: 'POST', body });+ expect(r.status).toBe(200);+ expect(r.body).toMatchObject({ tx_base64: 'AQID', side: 'buy', amount_in: 5000, min_out: 99, slippage_bps: 100 });+ });++ it('passes the side and slippage through for a sell', async () => {+ const r = await call('swap-prep', { method: 'POST', body: { ...body, side: 'sell', slippage_bps: 250 } });+ expect(r.status).toBe(200);+ expect(r.body).toMatchObject({ side: 'sell', slippage_bps: 250 });+ });++ it('rejects a bad side, a non-positive amount and a malformed wallet', async () => {+ for (const bad of [{ side: 'hold' }, { amount: 0 }, { amount: -5 }, { wallet_address: 'not-a-wallet-address-not-a-wallet-addr' }]) {+ const r = await call('swap-prep', { method: 'POST', body: { ...body, ...bad } });expect(r.status).toBe(400);}});