Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(launcher): let automatic creator-fee claims and 201 launches actually record
nirholas41efe0bac812
diff --git a/api/_lib/launcher-engine.js b/api/_lib/launcher-engine.jsindex dd73fd614..7200e9b91 100644--- a/api/_lib/launcher-engine.js+++ b/api/_lib/launcher-engine.js@@ -94,6 +94,8 @@ export function ownerAllowlist() {// ── schema guard ────────────────────────────────────────────────────────────────// Self-contained so the engine runs whether or not 20260629060000_coin_launcher.sql// has been applied. Mirrors that migration; CREATE … IF NOT EXISTS is idempotent.+// launcher_claims is not created here: migration 20260930120000_launcher_claims.sql+// owns it (with its agent_id and (mint, network) indexes).let _ensured = false;async function ensureSchema() {if (_ensured) return;@@ -161,24 +163,6 @@ async function ensureSchema() {await sql`create index if not exists launcher_runs_scope_idx on launcher_runs (scope, created_at desc)`;await sql`create index if not exists launcher_runs_spend_idx on launcher_runs (created_at) where status in ('funded','launched','confirmed')`;await sql`create unique index if not exists launcher_runs_mint_uniq on launcher_runs (mint) where mint is not null`;- await sql`- create table if not exists launcher_claims (- id uuid primary key default gen_random_uuid(),- run_id uuid references launcher_runs(id) on delete set null,- agent_id uuid,- mint text not null,- claimed_lamports bigint not null default 0,- claimed_sol float8 not null default 0,- buyback_sol float8 not null default 0,- buyback_sig text,- claim_sig text,- network text not null default 'mainnet',- scope text not null default 'global',- created_at timestamptz not null default now()- )- `;- await sql`create index if not exists launcher_claims_run_idx on launcher_claims (run_id, created_at desc)`;- await sql`create index if not exists launcher_claims_created_idx on launcher_claims (created_at desc)`;await sql`insert into launcher_config (scope, enabled, dry_run, mode, per_launch_sol, dev_buy_sol)values ('global', true, false, 'hybrid', 0.04, 0.01)@@ -321,6 +305,8 @@ async function postAs(ownerUserId, path, body, timeoutMs = 55_000) {return { status: res.status, body: parsed };}+const isHttpSuccess = (status) => status >= 200 && status < 300;+async function launchCoin(cfg, agent, coin) {// Forward the agent's own socials when it has them; the metadata builder falls// back to the agent profile page (website) and the three.ws X/Telegram otherwise,@@ -336,7 +322,7 @@ async function launchCoin(cfg, agent, coin) {...(agent.telegram ? { telegram: agent.telegram } : {}),});if (meta.timedOut) throw new Error('metadata build timed out');- if (meta.status !== 200 || !meta.body?.metadata_url) {+ if (!isHttpSuccess(meta.status) || !meta.body?.metadata_url) {throw new Error(`metadata build ${meta.status}: ${meta.body?.error || 'no url'}`);}@@ -354,7 +340,9 @@ async function launchCoin(cfg, agent, coin) {if (launch.timedOut) throw new Error('launch timed out');const mint = launch.body?.mint || launch.body?.data?.mint;const sig = launch.body?.sig || launch.body?.signature || launch.body?.data?.sig || null;- if (launch.status !== 200 || !mint) {+ // launch-agent answers a created coin with 201; any 2xx carrying a mint is a+ // launch. Requiring exactly 200 recorded real launches as failed with no mint.+ if (!isHttpSuccess(launch.status) || !mint) {// Carry the HTTP status so callers can classify (402 unfunded ⇒ recoverable// skip on the self-funded path, everything else ⇒ failure).throw Object.assign(diff --git a/api/_lib/migrations/20260930120000_launcher_claims.sql b/api/_lib/migrations/20260930120000_launcher_claims.sqlnew file mode 100644index 000000000..0f2f3ac81--- /dev/null+++ b/api/_lib/migrations/20260930120000_launcher_claims.sql@@ -0,0 +1,37 @@+-- Migration: give launcher_claims a real home.+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260930120000_launcher_claims.sql+-- Idempotent.+--+-- launcher_claims records every pump.fun creator-fee claim the launcher claimer+-- (api/cron/launcher-claimer.js) makes for an autonomously launched coin. It was+-- created on the fly in two files (the claimer and api/_lib/launcher-engine.js)+-- with no index on agent_id or mint, and nothing read it. Per-agent creator+-- earnings (GET /api/agents/:id/earnings) now join it as the list of claim+-- transactions, which reads by agent_id and by (mint, network).+--+-- Columns match the on-the-fly definition exactly, so production (where the+-- table already exists) only gains the two indexes.++begin;++create table if not exists launcher_claims (+ id uuid primary key default gen_random_uuid(),+ run_id uuid references launcher_runs(id) on delete set null,+ agent_id uuid,+ mint text not null,+ claimed_lamports bigint not null default 0,+ claimed_sol float8 not null default 0,+ buyback_sol float8 not null default 0,+ buyback_sig text,+ claim_sig text,+ network text not null default 'mainnet',+ scope text not null default 'global',+ created_at timestamptz not null default now()+);++create index if not exists launcher_claims_run_idx on launcher_claims (run_id, created_at desc);+create index if not exists launcher_claims_created_idx on launcher_claims (created_at desc);+create index if not exists launcher_claims_agent_idx on launcher_claims (agent_id, created_at desc);+create index if not exists launcher_claims_mint_network_idx on launcher_claims (mint, network);++commit;diff --git a/api/_lib/pump-fee-schemas.js b/api/_lib/pump-fee-schemas.jsnew file mode 100644index 000000000..ea78cca12--- /dev/null+++ b/api/_lib/pump-fee-schemas.js@@ -0,0 +1,21 @@+// @ts-check+// Request-body contracts for the agent-signed creator-fee endpoints+// (/api/pump/collect-creator-fee-agent and /api/pump/distribute-creator-fees-agent).+//+// They live here, not inline in api/pump/[action].js, so every internal caller+// can be tested against the exact schema the handler parses. The launcher+// claimer once posted `{ agentId }` to an endpoint that only knows `agent_id`,+// and every automatic claim failed validation for months because its test+// mocked fetch with a stub that accepted any body.++import { z } from 'zod';++export const collectFeeAgentSchema = z+ .object({+ agent_id: z.string().uuid().optional(),+ avatar_id: z.string().uuid().optional(),+ mint: z.string().min(32).max(44),+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),+ all_quotes: z.boolean().default(false),+ })+ .refine((b) => b.agent_id || b.avatar_id, { message: 'agent_id or avatar_id required' });diff --git a/api/cron/launcher-claimer.js b/api/cron/launcher-claimer.jsindex c5b207937..dee234042 100644--- a/api/cron/launcher-claimer.js+++ b/api/cron/launcher-claimer.js@@ -5,7 +5,8 @@// been claimed in the last 24 hours:// 1. Query live fee-info from the platform pump API// 2. Claim via collect-creator-fee-agent (agent signs its own claim, same as the launch)-// 3. Record in launcher_claims (claimed_sol, buyback_sol earmarked, claim_sig)+// 3. Record in launcher_claims (claimed_sol, buyback_sol earmarked, claim_sig).+// The table is owned by migration 20260930120000_launcher_claims.sql.//// This closes the creator-fee loop: launch → creator fees accrue → claim → record.// The same tick cranks the fee distribution of every gasless (sponsored) launch,@@ -30,32 +31,6 @@ const CLAIM_THRESHOLD_SOL = 0.01;const ORIGIN = env.APP_ORIGIN || 'https://three.ws';const MAX_PER_TICK = 20;-let _schemaDone = false;-async function ensureSchema() {- if (_schemaDone) return;- // Idempotent - launcher-engine.js creates the same table on runLauncherTick().- // Duplicated here so the claimer works even when the engine hasn't ticked yet.- await sql`- create table if not exists launcher_claims (- id uuid primary key default gen_random_uuid(),- run_id uuid references launcher_runs(id) on delete set null,- agent_id uuid,- mint text not null,- claimed_lamports bigint not null default 0,- claimed_sol float8 not null default 0,- buyback_sol float8 not null default 0,- buyback_sig text,- claim_sig text,- network text not null default 'mainnet',- scope text not null default 'global',- created_at timestamptz not null default now()- )- `;- await sql`create index if not exists launcher_claims_run_idx on launcher_claims (run_id, created_at desc)`;- await sql`create index if not exists launcher_claims_created_idx on launcher_claims (created_at desc)`;- _schemaDone = true;-}-// One machine session per owner per tick, minted lazily and revoked when the// tick ends (see runClaimerTick's finally). Minting one per REQUEST, the// previous shape, left two live sessions behind for every coin checked, up to@@ -113,7 +88,8 @@ async function processMint(run, token) {const claimRes = await agentFetch(token, '/api/pump/collect-creator-fee-agent', {method: 'POST',headers: { 'content-type': 'application/json' },- body: JSON.stringify({ agentId, mint, network }),+ // snake_case: the endpoint parses collectFeeAgentSchema (api/_lib/pump-fee-schemas.js).+ body: JSON.stringify({ agent_id: agentId, mint, network }),});if (!claimRes || !claimRes.ok) return { runId, status: 'claim-failed' };const claimData = await claimRes.json().catch(() => null);@@ -147,8 +123,6 @@ async function processMint(run, token) {}async function runClaimerTick() {- await ensureSchema();-// Find minted coins that either have never been claimed or whose last successful// claim was > 24 hours ago (fees re-accrue after each claim).const runs = await sql`diff --git a/api/pump/[action].js b/api/pump/[action].jsindex 5e070c78c..db24e2ef6 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -91,6 +91,7 @@ import { grindVanityNode, GrindExhaustedError } from '../../src/solana/vanity/grimport { logger } from '../_lib/usage.js';import { cacheGet, cacheSet } from '../_lib/cache.js';import { pumpFetchJson } from '../_lib/pump-feed-fetch.js';+import { collectFeeAgentSchema } from '../_lib/pump-fee-schemas.js';import { isRpcOutageError, staleEnvelope } from '../_lib/rpc-degrade.js';import { getLaunchEconomics, describeFeeSplit } from '../_lib/launch-economics.js';import {@@ -5351,16 +5352,7 @@ async function resolveAgentFeeContext(req, res, body, { agreementContext = null// ── collect-creator-fee-agent ──────────────────────────────────────────────// Server-signs the creator-fee collection with the agent custodial wallet. Use// for coins launched from the agent wallet (agent_authority == agent wallet).--const collectFeeAgentSchema = z- .object({- agent_id: z.string().uuid().optional(),- avatar_id: z.string().uuid().optional(),- mint: z.string().min(32).max(44),- network: z.enum(['mainnet', 'devnet']).default('mainnet'),- all_quotes: z.boolean().default(false),- })- .refine((b) => b.agent_id || b.avatar_id, { message: 'agent_id or avatar_id required' });+// The body contract (collectFeeAgentSchema) lives in api/_lib/pump-fee-schemas.js.async function handleCollectCreatorFeeAgent(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;diff --git a/tests/api/launcher-claimer-cron.test.js b/tests/api/launcher-claimer-cron.test.jsindex 595a79728..afa6c2b33 100644--- a/tests/api/launcher-claimer-cron.test.js+++ b/tests/api/launcher-claimer-cron.test.js@@ -30,6 +30,7 @@ vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn() }));vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: vi.fn() }));const { default: handler } = await import('../../api/cron/launcher-claimer.js');+const { collectFeeAgentSchema } = await import('../../api/_lib/pump-fee-schemas.js');const OWNER_A = '11111111-1111-1111-1111-111111111111';const OWNER_B = '22222222-2222-2222-2222-222222222222';@@ -159,4 +160,32 @@ describe('GET/POST /api/cron/launcher-claimer', () => {expect(res.body.skipped).toBe(1);expect(res.body.details[0]).toMatchObject({ runId: 'run-1', status: 'below-threshold' });});++ // The claim endpoint validates its body with collectFeeAgentSchema before it+ // does anything else. This stub applies that same schema and answers 400 the+ // way the real handler does, so a body the endpoint cannot read fails here+ // instead of in production (the claimer used to send `agentId`, which the+ // schema does not know, and every automatic claim came back 400).+ it('posts a claim body the real collect-creator-fee-agent schema accepts', async () => {+ const agentId = '33333333-3333-4333-8333-333333333333';+ const mint = 'THREEsynthetic11111111111111111111111111111';+ withRuns([{ ...runRow('run-9', OWNER_A, mint), agent_id: agentId }]);+ const claimBodies = [];+ global.fetch = vi.fn(async (url, opts = {}) => {+ if (String(url).includes('fee-info')) {+ return { ok: true, status: 200, json: async () => ({ claimable_lamports: '50000000' }) };+ }+ const body = JSON.parse(opts.body || '{}');+ claimBodies.push(body);+ const parsed = collectFeeAgentSchema.safeParse(body);+ if (!parsed.success) {+ return { ok: false, status: 400, json: async () => ({ error: 'validation_error' }) };+ }+ return { ok: true, status: 201, json: async () => ({ ok: true, signature: 'sig-9', lamports: 50_000_000 }) };+ });+ const res = await call();+ expect(res.body.details[0]).toMatchObject({ runId: 'run-9', status: 'claimed', sig: 'sig-9' });+ expect(claimBodies).toHaveLength(1);+ expect(claimBodies[0]).toMatchObject({ agent_id: agentId, mint, network: 'mainnet' });+ });});diff --git a/tests/launcher-engine.test.js b/tests/launcher-engine.test.jsindex 29fb337a1..23fd3c5f0 100644--- a/tests/launcher-engine.test.js+++ b/tests/launcher-engine.test.js@@ -1,4 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';// Shared, test-controlled state for the fake DB + mocks. vi.hoisted lets the// mock factories (hoisted above imports) read/write it.@@ -316,3 +318,56 @@ describe('runLauncherTick — live user scope (self-funded)', () => {vi.unstubAllGlobals();});});++// The success status of POST /api/pump/launch-agent, read from the handler+// itself so this suite follows the real contract instead of a status someone+// typed into a stub. The engine used to accept exactly 200 while the handler+// answers 201, so the first live autonomous launch would have been recorded as+// failed with a null mint and never claimed.+function launchAgentSuccessStatus() {+ const src = readFileSync(fileURLToPath(new URL('../api/pump/[action].js', import.meta.url)), 'utf8');+ const start = src.indexOf('async function handleLaunchAgent(');+ const end = src.indexOf('\nasync function ', start + 1);+ const body = src.slice(start, end);+ const statuses = [...body.matchAll(/json\(res, (2\d\d), \{\s*ok: true/g)].map((m) => Number(m[1]));+ expect(statuses.length).toBeGreaterThan(0);+ return statuses[statuses.length - 1];+}++describe('runLauncherTick: launch-agent response contract', () => {+ it('records the mint when launch-agent answers with its real 201 success', async () => {+ const status = launchAgentSuccessStatus();+ expect(status).toBe(201);+ H.configs = [makeConfig({ dry_run: false })];+ vi.stubGlobal('fetch', vi.fn(async (url) => {+ const u = String(url);+ if (u.includes('/api/pump/build-metadata')) return { status: 200, json: async () => ({ metadata_url: 'ipfs://meta' }) };+ if (u.includes('/api/pump/launch-agent')) {+ return { status, json: async () => ({ ok: true, mint: 'MINTcreated', signature: 'sig-201' }) };+ }+ return { status: 404, json: async () => ({}) };+ }));++ const out = await runLauncherTick();+ expect(out.results[0].mint).toBe('MINTcreated');+ expect(out.results[0].error).toBeUndefined();++ vi.unstubAllGlobals();+ });++ it('still fails a non-2xx launch even when the body names a mint', async () => {+ H.configs = [makeConfig({ dry_run: false })];+ vi.stubGlobal('fetch', vi.fn(async (url) => {+ const u = String(url);+ if (u.includes('/api/pump/build-metadata')) return { status: 200, json: async () => ({ metadata_url: 'ipfs://meta' }) };+ if (u.includes('/api/pump/launch-agent')) return { status: 502, json: async () => ({ mint: 'MINTghost', error: 'rpc_error' }) };+ return { status: 404, json: async () => ({}) };+ }));++ const out = await runLauncherTick();+ expect(out.results[0].mint).toBeUndefined();+ expect(String(out.results[0].error)).toMatch(/launch 502/);++ vi.unstubAllGlobals();+ });+});