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.

docs(native-launch): document the self-hosted curve lane, and cover it with tests

nirholasf801681bcf9b
diff --git a/docs/native-launchpad.md b/docs/native-launchpad.md
new file mode 100644
index 000000000..fbf17bf9c
--- /dev/null
+++ b/docs/native-launchpad.md
@@ -0,0 +1,188 @@
+# The three.ws launchpad: our own bonding curve
+
+three.ws has always been able to launch a coin for an agent. Until now, every one of those launches went out on pump.fun: their program, their curve, their fee schedule. That lane still exists and still matters, because that is where the buyers are.
+
+This document covers the second lane: **the native launchpad**, a coin launch that runs on a bonding curve three.ws configures and owns. Same launch button, same 3D agent identity attached to the coin, different economics underneath.
+
+Related surfaces: [the pump.fun lane](./api-reference.md) (`/api/pump/*`), [agent wallets](./agent-wallets.md) (custody), and [the launch page](https://three.ws/launch).
+
+---
+
+## Why a second lane exists
+
+A launchpad's revenue is a share of trading fees. On the pump.fun lane, three.ws only ever touches the creator-fee side of a launch, because the platform fee belongs to pump.fun. On the native lane, three.ws is the on-chain partner of the curve itself, so the platform earns a share of every trade on every coin launched through it, plus a share of the fees the pool keeps earning after graduation.
+
+The tradeoff is honest and worth stating plainly: pump.fun brings order flow that a new curve does not have. Trading terminals and aggregators index pump.fun natively. So the two lanes are not a migration, they are a choice the launcher makes per coin: **reach, or economics.**
+
+## What the native lane does not do
+
+Building our own bonding-curve program from scratch would mean writing, auditing, and maintaining custody-grade Solana code, and then bootstrapping liquidity for graduated coins with no venue to graduate into. We did not do that.
+
+The native lane runs on **Meteora's Dynamic Bonding Curve (DBC)** program: an audited, permissionless launchpad-as-infrastructure program. three.ws creates a *partner config* on it once per network. That config encodes our curve shape, our fee split, and our graduation target, and every pool created under our config key is a three.ws launch. We own the product, the economics, and the brand; we do not own the risk of unaudited custody code, and graduated coins land in a real AMM pool with real routing.
+
+---
+
+## The curve
+
+All of it lives in one file, [`api/_lib/native-launch/config.js`](../api/_lib/native-launch/config.js), so the numbers a user is shown can never drift from the numbers the chain enforces.
+
+| Property | Value |
+|---|---|
+| Quote asset | SOL |
+| Supply | 1,000,000,000 (6 decimals) |
+| Metadata authority | Immutable at launch |
+| Starting market cap | ~28 SOL |
+| Graduation market cap | ~410 SOL (≈85 SOL raised on the curve) |
+| Trading fee | 1%, taken in SOL, plus a volatility-scaled dynamic fee during spikes |
+| Trading fee split | 50% coin creator / 50% three.ws |
+| Migration fee | 1% of the raised SOL, split 50/50 |
+| Graduates into | A Meteora DAMM v2 pool |
+| LP at graduation | 100% permanently locked (50% creator / 50% platform) |
+
+Two of these deserve emphasis:
+
+**The metadata authority is immutable.** Nobody, including three.ws, can rewrite a launched coin's name, symbol, or image after the fact.
+
+**All liquidity is permanently locked at graduation.** Neither the creator nor the platform can withdraw the pool. A graduated native coin cannot be rugged by liquidity removal, and both sides keep earning LP fees on it for as long as it trades.
+
+The graduation target deliberately mirrors the shape traders already recognise from pump.fun (~85 SOL raised), so the lane feels familiar rather than novel where novelty would only add friction.
+
+### 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.
+
+---
+
+## How a launch works
+
+The custody model is identical to the pump.fun lane: **the server never holds a user key.** It builds an unsigned transaction; the browser signs it with the launcher's wallet and the new mint's keypair; a confirm step verifies the landed transaction on-chain before anything is recorded.
+
+```
+POST /api/native-launch/launch-prep → unsigned create-pool tx + mint keypair
+ ↓ (browser signs with wallet + mint, submits to Solana)
+POST /api/native-launch/launch-confirm → verifies on-chain, records the launch
+```
+
+### `POST /api/native-launch/launch-prep`
+
+Requires a session and a Solana wallet linked to that account.
+
+```json
+{
+ "avatar_id": "e29028e5-dcdf-4359-8101-0fb8cbba5dc3",
+ "wallet_address": "<your linked Solana wallet>",
+ "name": "Native Coin",
+ "symbol": "NTV",
+ "uri": "https://three.ws/metadata.json",
+ "sol_buy_in": 0.05,
+ "network": "mainnet"
+}
+```
+
+`agent_id` may be sent instead of `avatar_id`. `sol_buy_in` is an optional first buy bundled into the same transaction. `mint_address` may carry a client-ground vanity mint; omit it and the server grinds one.
+
+Returns `201` with the unsigned transaction and the deterministic pool address:
+
+```json
+{
+ "prep_id": "…",
+ "agent_id": "…",
+ "lane": "native",
+ "mint": "3ws…",
+ "pool": "…",
+ "config_key": "…",
+ "mint_secret_key_b64": "…",
+ "client_supplied_mint": false,
+ "tx_base64": "…",
+ "network": "mainnet",
+ "expires_at": "2026-07-27T17:50:51.336Z"
+}
+```
+
+Every three.ws coin's mint address carries the `3ws` mark, on both lanes. When the server stamps the mint it returns the secret so the browser can co-sign; when you supply your own ground vanity mint, the server never sees its key.
+
+Errors: `401` not signed in, `403` wallet not linked to your account, `400 unbranded_mint` for a supplied mint without the mark, `503 lane_not_configured` when the curve is not deployed on that network.
+
+### `POST /api/native-launch/launch-confirm`
+
+```json
+{ "prep_id": "…", "tx_signature": "…" }
+```
+
+Before recording anything, the server independently verifies the signature against the chain and applies two guards:
+
+1. The prepped mint must appear in the transaction's account keys.
+2. The transaction must actually have **invoked the bonding-curve program** (`422 not_a_native_launch` otherwise).
+
+The second guard is the important one: without it, a confirmed memo or transfer that merely touches the new mint account could be recorded as a launch. Returns `201` with the recorded row, or `409` if that mint is already registered.
+
+### Read endpoints
+
+All public, no auth:
+
+- `GET /api/native-launch/config[?network=]` — the lane's live economics and whether it is deployed. This is what the launch UI renders, so the fee story on the page always comes from the same source as the on-chain config.
+- `GET /api/native-launch/pool?mint=…[&network=]` — pool address, curve progress (0..1), SOL raised, graduation threshold, migration status.
+- `GET /api/native-launch/quote?mint=…&sol_in=…[&network=]` — a live buy quote off the curve: tokens out, minimum out, and the fee breakdown.
+- `GET /api/native-launch/launches[?network=&agent_id=&limit=&offset=]` — the native launch directory, each row carrying its agent and avatar thumbnail.
+
+---
+
+## Deploying the lane on a network
+
+The partner config is created once per network and then pinned in the environment. Until it is pinned, the lane reports itself unavailable, the launch UI hides the lane toggle entirely, and every launch stays on pump.fun. There is no half-configured state.
+
+```bash
+# devnet (the partner wallet needs ~0.05 SOL for rent + fees)
+node scripts/native-launchpad-create-config.mjs --network devnet --airdrop
+
+# mainnet
+node scripts/native-launchpad-create-config.mjs --network mainnet
+```
+
+The script prints the config pubkey. Pin it:
+
+| Variable | Meaning |
+|---|---|
+| `NATIVE_LAUNCH_CONFIG_KEY` | Mainnet partner config pubkey |
+| `NATIVE_LAUNCH_CONFIG_KEY_DEVNET` | Devnet partner config pubkey |
+| `NATIVE_LAUNCH_FEE_WALLET` | Platform fee claimer + leftover receiver (defaults to the treasury wallet) |
+| `NATIVE_LAUNCH_PARTNER_SECRET_BASE58` | Signer that creates the config (falls back to the treasury secret) |
+
+On production these live on the Cloud Run service, not in a file.
+
+### Verifying a deployment end to end
+
+`scripts/native-launchpad-e2e-devnet.mjs` drives the real modules the API uses: it builds a create-pool transaction, signs and lands it on devnet, reads the pool back, quotes a buy, executes that buy, and asserts the curve moved.
+
+```bash
+node scripts/native-launchpad-e2e-devnet.mjs
+```
+
+The devnet run that shipped this feature created config `FK3HQrWG5y6rh3SC8ew5WVUfo31bfmkm2Z1nwuZaKcam`, launched a pool, and confirmed the fee math on-chain: a 0.5 SOL buy moved the pool's reserve by exactly 0.49499951 SOL, i.e. precisely the 1% fee.
+
+---
+
+## Where it lives
+
+| Piece | Path |
+|---|---|
+| Curve economics (single source of truth) | [`api/_lib/native-launch/config.js`](../api/_lib/native-launch/config.js) |
+| DBC wrapper (build tx, read pool, quote) | [`api/_lib/native-launch/dbc.js`](../api/_lib/native-launch/dbc.js) |
+| HTTP dispatcher | [`api/native-launch/[action].js`](../api/native-launch/%5Baction%5D.js) |
+| Launch table | `native_launches` (migration `20260726100000_native_launchpad.sql`) |
+| Launch UI (lane toggle) | [`public/studio/launch-panel.js`](../public/studio/launch-panel.js) |
+| Config creation | [`scripts/native-launchpad-create-config.mjs`](../scripts/native-launchpad-create-config.mjs) |
+| Devnet end-to-end | [`scripts/native-launchpad-e2e-devnet.mjs`](../scripts/native-launchpad-e2e-devnet.mjs) |
+| Tests | `tests/native-launch-curve.test.js`, `tests/native-launch-endpoint.test.js` |
+
+Note the namespace: this lane is `/api/native-launch/*`. The unrelated `/api/launchpad/*` endpoints belong to Launchpad Studio, the page builder.
+
+---
+
+## Current limits
+
+Stated plainly, because a half-built feature that claims to be finished is worse than one that names its edges:
+
+- **No custodial launch path.** The pump.fun lane can launch from an agent's own server-signed wallet; the native lane is always signed by the launcher's connected wallet. The lane toggle switches the signer back to the connected wallet automatically rather than offering an option that would fail.
+- **No coin-detail page yet.** `/launches/<mint>` reads price history, trades, safety, and smart-money data from pump-specific endpoints, so it cannot render a native coin. The launch success screen links to Solscan and the agent page instead of a link that would 404.
+- **No coin variants.** Mayhem, USDC pairing, buyback binding, and delegated reward splits are pump.fun program features. The native lane is SOL-quoted and variant-free, so that picker is withheld on this lane rather than shown with dead options.
diff --git a/tests/native-launch-curve.test.js b/tests/native-launch-curve.test.js
new file mode 100644
index 000000000..8ae728abe
--- /dev/null
+++ b/tests/native-launch-curve.test.js
@@ -0,0 +1,160 @@
+// The three.ws native launch lane: curve economics + the SDK-built config.
+//
+// These assertions are the guard rails on real money. The curve config is what
+// decides how much of every trade reaches the coin's creator and the platform,
+// where the coin graduates, and whether the graduated pool can be pulled — so a
+// silent edit to config.js (or an SDK bump that reinterprets a field) has to
+// fail here rather than on mainnet.
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import {
+ buildCurveWithMarketCap,
+ validateConfigParameters,
+ TokenType,
+ TokenDecimal,
+ TokenAuthorityOption,
+ BaseFeeMode,
+ CollectFeeMode,
+ MigrationOption,
+ MigrationFeeOption,
+ ActivationType,
+} from '@meteora-ag/dynamic-bonding-curve-sdk';
+import { Keypair } from '@solana/web3.js';
+import { NATIVE_LANE, curveBuildParams, configKeyFor, laneInfo } from '../api/_lib/native-launch/config.js';
+
+const params = () => curveBuildParams();
+
+describe('native lane economics', () => {
+ it('quotes in SOL with a fixed 1B supply at 6 decimals', () => {
+ expect(NATIVE_LANE.quote).toBe('SOL');
+ expect(NATIVE_LANE.totalSupply).toBe(1_000_000_000);
+ expect(NATIVE_LANE.decimals).toBe(6);
+ });
+
+ it('splits the trading fee evenly between creator and platform', () => {
+ expect(NATIVE_LANE.tradeFeeBps).toBe(100); // 1%
+ expect(NATIVE_LANE.creatorTradeFeePercent).toBe(50);
+ const info = laneInfo('mainnet');
+ expect(info.fee_split.creator_percent + info.fee_split.platform_percent).toBe(100);
+ });
+
+ it('locks 100% of graduated liquidity', () => {
+ expect(NATIVE_LANE.lpLockedPercent).toBe(100);
+ const { liquidityDistribution: d } = params();
+ // Every LP share is permanently locked: nothing is withdrawable, which is
+ // what makes a graduated native coin un-ruggable.
+ expect(d.partnerLiquidityPercentage).toBe(0);
+ expect(d.creatorLiquidityPercentage).toBe(0);
+ expect(
+ d.partnerPermanentLockedLiquidityPercentage + d.creatorPermanentLockedLiquidityPercentage,
+ ).toBe(100);
+ });
+
+ it('graduates above its starting market cap', () => {
+ expect(NATIVE_LANE.migrationMarketCapSol).toBeGreaterThan(NATIVE_LANE.initialMarketCapSol);
+ });
+});
+
+describe('curveBuildParams', () => {
+ it('uses the SDK enum values the on-chain program expects', () => {
+ const p = params();
+ expect(p.token.tokenType).toBe(TokenType.SPLToken);
+ expect(p.token.tokenBaseDecimal).toBe(TokenDecimal.SIX);
+ expect(p.token.tokenQuoteDecimal).toBe(TokenDecimal.NINE);
+ // 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);
+ // Fees accrue in the quote token so creators are paid in SOL, not in
+ // their own (possibly worthless) coin.
+ expect(p.fee.collectFeeMode).toBe(CollectFeeMode.QuoteToken);
+ expect(p.migration.migrationOption).toBe(MigrationOption.MET_DAMM_V2);
+ expect(p.migration.migrationFeeOption).toBe(MigrationFeeOption.FixedBps100);
+ expect(p.activationType).toBe(ActivationType.Slot);
+ });
+
+ it('charges a flat fee for the whole curve (no decaying schedule)', () => {
+ const { feeSchedulerParam: f } = params().fee.baseFeeParams;
+ expect(f.startingFeeBps).toBe(f.endingFeeBps);
+ expect(f.startingFeeBps).toBe(NATIVE_LANE.tradeFeeBps);
+ });
+
+ it('keeps a leftover dust unit so the program supply check passes', () => {
+ // The DBC program requires curve + migration + leftover to reconcile
+ // exactly against the fixed supply; leftover 0 is rejected on-chain with
+ // InvalidTokenSupply. Verified against devnet before this was pinned.
+ expect(params().token.leftover).toBeGreaterThan(0);
+ });
+
+ it('never vests or withholds supply from the curve', () => {
+ const v = params().lockedVesting;
+ expect(v.totalLockedVestingAmount).toBe(0);
+ expect(v.cliffUnlockAmount).toBe(0);
+ });
+});
+
+describe('curve built through the SDK', () => {
+ const built = () => buildCurveWithMarketCap(params());
+
+ it('passes the SDK config validator', () => {
+ expect(() =>
+ validateConfigParameters({
+ ...built(),
+ leftoverReceiver: Keypair.generate().publicKey,
+ }),
+ ).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('carries the creator fee share and migration fee onto the config', () => {
+ const cfg = built();
+ expect(cfg.creatorTradingFeePercentage).toBe(NATIVE_LANE.creatorTradeFeePercent);
+ expect(cfg.migrationFee.feePercentage).toBe(NATIVE_LANE.migrationFeePercent);
+ expect(cfg.migrationFee.creatorFeePercentage).toBe(NATIVE_LANE.creatorMigrationFeePercent);
+ });
+
+ it('produces a rising multi-point curve', () => {
+ const curve = built().curve;
+ expect(curve.length).toBeGreaterThan(1);
+ for (let i = 1; i < curve.length; i++) {
+ expect(curve[i].sqrtPrice.gt(curve[i - 1].sqrtPrice)).toBe(true);
+ }
+ });
+
+ it('starts strictly below the graduation price', () => {
+ const cfg = built();
+ expect(cfg.sqrtStartPrice.lt(cfg.curve[cfg.curve.length - 1].sqrtPrice)).toBe(true);
+ });
+});
+
+describe('config key resolution', () => {
+ const saved = {};
+ beforeEach(() => {
+ saved.main = process.env.NATIVE_LAUNCH_CONFIG_KEY;
+ saved.dev = process.env.NATIVE_LAUNCH_CONFIG_KEY_DEVNET;
+ });
+ afterEach(() => {
+ if (saved.main === undefined) delete process.env.NATIVE_LAUNCH_CONFIG_KEY;
+ else process.env.NATIVE_LAUNCH_CONFIG_KEY = saved.main;
+ if (saved.dev === undefined) delete process.env.NATIVE_LAUNCH_CONFIG_KEY_DEVNET;
+ else process.env.NATIVE_LAUNCH_CONFIG_KEY_DEVNET = saved.dev;
+ });
+
+ it('reads the network-matched env var', () => {
+ process.env.NATIVE_LAUNCH_CONFIG_KEY = 'MainnetConfigKey1111111111111111111111111111';
+ process.env.NATIVE_LAUNCH_CONFIG_KEY_DEVNET = 'DevnetConfigKey11111111111111111111111111111';
+ expect(configKeyFor('mainnet')).toBe('MainnetConfigKey1111111111111111111111111111');
+ expect(configKeyFor('devnet')).toBe('DevnetConfigKey11111111111111111111111111111');
+ });
+
+ it('reports the lane unavailable when its network has no config', () => {
+ delete process.env.NATIVE_LAUNCH_CONFIG_KEY;
+ expect(configKeyFor('mainnet')).toBeNull();
+ expect(laneInfo('mainnet').config_key).toBeNull();
+ });
+});
diff --git a/tests/native-launch-endpoint.test.js b/tests/native-launch-endpoint.test.js
new file mode 100644
index 000000000..e74000781
--- /dev/null
+++ b/tests/native-launch-endpoint.test.js
@@ -0,0 +1,291 @@
+// /api/native-launch/* dispatcher behavior: routing, auth gating, validation,
+// and the two on-chain guards that decide whether a transaction is allowed to
+// be recorded as a launch. The Solana/DBC layer is stubbed — the real curve is
+// covered by native-launch-curve.test.js and by the devnet end-to-end script.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+let sessionUser = { id: 'user-1' };
+const dbRows = { user_wallets: [], native_launches: [], pending: [] };
+
+vi.mock('../api/_lib/http.js', () => ({
+ wrap: (fn) => fn,
+ cors: () => false,
+ method: () => true,
+ readJson: async (req) => req.body ?? {},
+ rateLimited: (res) => {
+ res._json = { status: 429, body: { error: 'rate_limited' } };
+ return res;
+ },
+ error: (res, status, code, message, extra = {}) => {
+ res._json = { status, body: { error: code, error_description: message, ...extra } };
+ return res;
+ },
+ json: (res, status, body) => {
+ res._json = { status, body };
+ return res;
+ },
+}));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ authIp: vi.fn(async () => ({ success: true })),
+ authedReadIp: vi.fn(async () => ({ success: true })),
+ mcpIp: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: () => '1.2.3.4',
+}));
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => sessionUser),
+}));
+// A tagged-template stub that answers by inspecting the SQL text.
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (strings) => {
+ const text = strings.join(' ');
+ if (text.includes('from user_wallets')) return Promise.resolve(dbRows.user_wallets);
+ if (text.includes('from native_launches')) return Promise.resolve(dbRows.native_launches);
+ if (text.includes('from agent_registrations_pending')) return Promise.resolve(dbRows.pending);
+ return Promise.resolve([]);
+ },
+}));
+vi.mock('../api/_lib/r2.js', () => ({ publicUrl: (k) => `https://cdn.test/${k}` }));
+vi.mock('../api/_lib/feed.js', () => ({ publishFeedEvent: vi.fn(async () => {}) }));
+vi.mock('../api/_lib/agent-identity.js', () => ({
+ resolveOrCreateAgentForAvatar: vi.fn(async () => ({ id: 'agent-1' })),
+}));
+vi.mock('../api/_lib/usage.js', () => ({
+ logger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
+}));
+
+const verifySignature = vi.fn();
+vi.mock('../api/_lib/pump.js', () => ({
+ verifySignature: (...a) => verifySignature(...a),
+ // Accepts anything base58-ish and long enough to be a pubkey.
+ solanaPubkey: (s) =>
+ typeof s === 'string' && s.length >= 32 && s.length <= 44 && /^[1-9A-HJ-NP-Za-km-z]+$/.test(s)
+ ? { toBase58: () => s }
+ : null,
+}));
+
+const txInvokesDbcProgram = vi.fn(() => true);
+vi.mock('../api/_lib/native-launch/dbc.js', () => ({
+ txInvokesDbcProgram: (...a) => txInvokesDbcProgram(...a),
+ buildCreatePoolTx: vi.fn(async () => ({
+ txBase64: 'AQID',
+ pool: 'PoolAddress11111111111111111111111111111111',
+ configKey: 'ConfigKey111111111111111111111111111111111',
+ })),
+ getPoolState: vi.fn(async () => ({ pool: 'PoolAddress11111111111111111111111111111111' })),
+ quoteBuy: vi.fn(async () => ({ pool: 'p', sol_in: 1, tokens_out: 100 })),
+}));
+
+import handler from '../api/native-launch/[action].js';
+import { configKeyFor } from '../api/_lib/native-launch/config.js';
+
+const CONFIG_KEY = 'DevnetConfigKey11111111111111111111111111111';
+const WALLET = 'FjRJ24ecvmPX488PcN3RpNPM9gq3xCxRjnju4LSr9M6f';
+const MINT = '3wsr2fWnuQ4hFRPHsxWin9YWiUT4qGMhGpE1CrboX47J';
+const SIG = 'x'.repeat(88);
+
+function makeRes() {
+ const res = { _json: null };
+ res.setHeader = () => res;
+ return res;
+}
+const call = (action, { method = 'GET', body, query = {} } = {}) => {
+ const qs = new URLSearchParams({ action, ...query }).toString();
+ const req = { url: `/api/native-launch/${action}?${qs}`, method, headers: { host: 'x' }, query: { action }, body };
+ const res = makeRes();
+ return handler(req, res).then(() => res._json);
+};
+
+beforeEach(() => {
+ sessionUser = { id: 'user-1' };
+ dbRows.user_wallets = [];
+ dbRows.native_launches = [];
+ dbRows.pending = [];
+ verifySignature.mockReset();
+ txInvokesDbcProgram.mockReset().mockReturnValue(true);
+ process.env.NATIVE_LAUNCH_CONFIG_KEY_DEVNET = CONFIG_KEY;
+ delete process.env.NATIVE_LAUNCH_CONFIG_KEY;
+});
+
+describe('dispatcher', () => {
+ it('404s an unknown action', async () => {
+ const r = await call('bogus');
+ expect(r.status).toBe(404);
+ expect(r.body.error).toBe('not_found');
+ });
+});
+
+describe('config', () => {
+ it('reports availability per network from the pinned config key', async () => {
+ const dev = await call('config', { query: { network: 'devnet' } });
+ expect(dev.status).toBe(200);
+ expect(dev.body.available).toBe(true);
+ expect(dev.body.config_key).toBe(CONFIG_KEY);
+
+ // Mainnet has no key set in this test, so the lane must read as absent
+ // rather than falling back to the devnet curve.
+ const main = await call('config');
+ expect(main.body.available).toBe(false);
+ expect(main.body.config_key).toBeNull();
+ expect(configKeyFor('mainnet')).toBeNull();
+ });
+
+ it('never advertises a fee split that does not add up', async () => {
+ const { fee_split } = (await call('config')).body;
+ expect(fee_split.creator_percent + fee_split.platform_percent).toBe(100);
+ });
+});
+
+describe('quote', () => {
+ it('rejects a malformed mint', async () => {
+ const r = await call('quote', { query: { mint: 'not-a-mint', sol_in: '1' } });
+ 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 } });
+ expect(r.status).toBe(400);
+ }
+ });
+});
+
+describe('launch-prep', () => {
+ const body = {
+ avatar_id: '00000000-0000-0000-0000-000000000001',
+ wallet_address: WALLET,
+ name: 'Native Coin',
+ symbol: 'NTV',
+ uri: 'https://three.ws/meta.json',
+ network: 'devnet',
+ };
+
+ it('requires a session', async () => {
+ sessionUser = null;
+ const r = await call('launch-prep', { method: 'POST', body });
+ expect(r.status).toBe(401);
+ });
+
+ it('refuses a wallet the user has not linked', async () => {
+ dbRows.user_wallets = [];
+ const r = await call('launch-prep', { method: 'POST', body });
+ expect(r.status).toBe(403);
+ expect(r.body.error).toBe('forbidden');
+ });
+
+ it('503s when the lane has no curve deployed on the requested network', async () => {
+ delete process.env.NATIVE_LAUNCH_CONFIG_KEY_DEVNET;
+ dbRows.user_wallets = [{ id: 'w1' }];
+ const r = await call('launch-prep', { method: 'POST', body });
+ expect(r.status).toBe(503);
+ expect(r.body.error).toBe('lane_not_configured');
+ });
+
+ it('returns an unsigned tx plus the derived pool for a linked wallet', async () => {
+ dbRows.user_wallets = [{ id: 'w1' }];
+ const r = await call('launch-prep', { method: 'POST', body });
+ expect(r.status).toBe(201);
+ expect(r.body.lane).toBe('native');
+ expect(r.body.tx_base64).toBe('AQID');
+ expect(r.body.pool).toBe('PoolAddress11111111111111111111111111111111');
+ expect(r.body.prep_id).toBeTruthy();
+ // A server-stamped mint must hand back its secret — the browser has to
+ // co-sign with it — and the mint has to carry the three.ws mark.
+ expect(r.body.mint_secret_key_b64).toBeTruthy();
+ expect(r.body.mint.toLowerCase()).toContain('3ws');
+ });
+});
+
+describe('launch-confirm', () => {
+ const prepRow = {
+ id: 'p1',
+ metadata_uri: 'https://three.ws/meta.json',
+ payload: {
+ kind: 'native_launch',
+ prep_id: 'prep123456',
+ agent_id: 'agent-1',
+ wallet_address: WALLET,
+ creator_address: WALLET,
+ mint: MINT,
+ pool: 'PoolAddress11111111111111111111111111111111',
+ config_key: CONFIG_KEY,
+ name: 'Native Coin',
+ symbol: 'NTV',
+ network: 'devnet',
+ },
+ };
+ const body = { prep_id: 'prep123456', tx_signature: SIG };
+
+ it('404s an unknown or expired prep', async () => {
+ dbRows.pending = [];
+ const r = await call('launch-confirm', { method: 'POST', body });
+ expect(r.status).toBe(404);
+ });
+
+ it('refuses a prep issued by the other lane', async () => {
+ dbRows.pending = [{ ...prepRow, payload: { ...prepRow.payload, kind: 'pump_launch' } }];
+ const r = await call('launch-confirm', { method: 'POST', body });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toBe('wrong_kind');
+ });
+
+ it('refuses a transaction that does not contain the prepped mint', async () => {
+ dbRows.pending = [prepRow];
+ verifySignature.mockResolvedValue({
+ transaction: { message: { accountKeys: [{ pubkey: 'SomeOtherAccount1111111111111111111111111' }] } },
+ });
+ const r = await call('launch-confirm', { method: 'POST', body });
+ expect(r.status).toBe(422);
+ expect(r.body.error).toBe('mint_not_in_tx');
+ });
+
+ it('refuses a transaction that never invoked the bonding-curve program', async () => {
+ // The critical guard: a confirmed memo or transfer that merely touches the
+ // new mint account must not be recordable as a launch.
+ dbRows.pending = [prepRow];
+ verifySignature.mockResolvedValue({
+ transaction: { message: { accountKeys: [{ pubkey: MINT }] } },
+ });
+ txInvokesDbcProgram.mockReturnValue(false);
+ const r = await call('launch-confirm', { method: 'POST', body });
+ expect(r.status).toBe(422);
+ expect(r.body.error).toBe('not_a_native_launch');
+ });
+
+ it('refuses a mint that is already recorded', async () => {
+ dbRows.pending = [prepRow];
+ dbRows.native_launches = [{ id: 'existing' }];
+ verifySignature.mockResolvedValue({
+ transaction: { message: { accountKeys: [{ pubkey: MINT }] } },
+ });
+ const r = await call('launch-confirm', { method: 'POST', body });
+ expect(r.status).toBe(409);
+ });
+
+ it('surfaces an unverifiable signature as the RPC reported it', async () => {
+ dbRows.pending = [prepRow];
+ verifySignature.mockRejectedValue(
+ Object.assign(new Error('tx not found'), { status: 422, code: 'tx_not_found' }),
+ );
+ const r = await call('launch-confirm', { method: 'POST', body });
+ expect(r.status).toBe(422);
+ expect(r.body.error).toBe('tx_not_found');
+ });
+});
+
+describe('launches', () => {
+ it('returns an empty, well-formed page when nothing has launched', async () => {
+ const r = await call('launches', { query: { network: 'devnet' } });
+ expect(r.status).toBe(200);
+ expect(r.body.data).toEqual({
+ launches: [],
+ has_more: false,
+ offset: 0,
+ limit: 24,
+ network: 'devnet',
+ });
+ });
+});