Skip to content

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

feat(compete): add the builder competition registration API, ranking by creator fees earned, and the competition_entries migration

nirholas439b4a256cc1
diff --git a/api/_lib/agent-earnings.js b/api/_lib/agent-earnings.js
index 213dcaeb8..6694a5231 100644
--- a/api/_lib/agent-earnings.js
+++ b/api/_lib/agent-earnings.js
@@ -151,6 +151,23 @@ async function creatorFeeRows(window, { agentId = null, publicOnly = false, back
`;
}
+/**
+ * Lifetime creator-fee lamports for a set of public agents, keyed by agent id,
+ * counted by the same attribution rule as getAgentEarnings (an agent's own
+ * custodial wallet, never shared). Agents with no counted fees are absent.
+ * @param {string[]} agentIds
+ * @returns {Promise<Map<string, { lamports: bigint, refreshed_at: any }>>}
+ */
+export async function creatorFeesByAgent(agentIds) {
+ const wanted = new Set(agentIds);
+ const out = new Map();
+ if (!wanted.size) return out;
+ for (const r of await creatorFeeRows('all', { publicOnly: true })) {
+ if (wanted.has(r.agent_id)) out.set(r.agent_id, { lamports: BigInt(r.lifetime_lamports || 0), refreshed_at: r.refreshed_at });
+ }
+ return out;
+}
+
/** Skill sales (USDC net), completed hires and paid invoices, per agent, for a window. */
async function serviceRows(window, { agentId = null, publicOnly = false, back = 0 } = {}) {
const range = windowRange(window, back);
diff --git a/api/_lib/competitions.js b/api/_lib/competitions.js
new file mode 100644
index 000000000..722de30d3
--- /dev/null
+++ b/api/_lib/competitions.js
@@ -0,0 +1,251 @@
+// @ts-check
+// Builder competitions. The decisions (dates, tracks, prizes, judges, rules)
+// live in data/competitions.json, which ships as an empty array; this module
+// validates that file, works out a competition's phase from the clock, and
+// reads registrations (competition_entries) joined to the platform's own launch
+// records (pump_agent_mints) and creator-fee snapshot. Nothing about a prize or
+// a deadline is typed anywhere else.
+//
+// A tokenized entry is one whose agent launched a mainnet coin through three.ws
+// between `starts_at` and `tokenize_by`. Entries rank by the creator fees that
+// agent has earned (agent-earnings.js, the same attribution rule as the agent
+// page and the earnings leaderboard).
+
+import { readFileSync } from 'node:fs';
+import { z } from 'zod';
+import { sql } from './db.js';
+import { creatorFeesByAgent } from './agent-earnings.js';
+
+const DEFAULT_FILE = new URL('../../data/competitions.json', import.meta.url);
+
+const isoDate = z
+ .string()
+ .refine((v) => Number.isFinite(Date.parse(v)) && /^\d{4}-\d{2}-\d{2}/.test(v), 'must be an ISO 8601 date');
+
+const competitionSchema = z
+ .object({
+ slug: z
+ .string()
+ .min(1)
+ .max(64)
+ .regex(/^[a-z0-9][a-z0-9-]*$/, 'slug must be lowercase alphanumeric with -'),
+ title: z.string().min(1).max(120),
+ summary: z.string().max(400).optional(),
+ starts_at: isoDate,
+ register_by: isoDate,
+ tokenize_by: isoDate,
+ ends_at: isoDate,
+ tracks: z.array(z.object({ name: z.string().min(1).max(80), description: z.string().max(600) })).default([]),
+ prizes: z
+ .array(
+ z.object({
+ place: z.string().min(1).max(60),
+ amount: z.number().nonnegative(),
+ asset: z.string().min(1).max(20),
+ vesting: z.string().max(300).optional(),
+ }),
+ )
+ .default([]),
+ judges: z.array(z.object({ name: z.string().min(1).max(80), role: z.string().max(120).optional(), url: z.string().url().optional() })).default([]),
+ rules: z.array(z.string().min(1).max(600)).default([]),
+ winners: z.array(z.object({ place: z.string().min(1).max(60), agent_id: z.string().uuid(), note: z.string().max(300).optional() })).default([]),
+ })
+ .strict()
+ .superRefine((c, ctx) => {
+ const t = (k) => Date.parse(c[k]);
+ const bad = (path, message) => ctx.addIssue({ code: 'custom', path: [path], message });
+ if (!(t('starts_at') < t('register_by'))) bad('register_by', 'must be after starts_at');
+ if (!(t('starts_at') < t('tokenize_by'))) bad('tokenize_by', 'must be after starts_at');
+ if (!(t('register_by') <= t('ends_at'))) bad('ends_at', 'must be on or after register_by');
+ if (!(t('tokenize_by') <= t('ends_at'))) bad('ends_at', 'must be on or after tokenize_by');
+ });
+
+/**
+ * Validate a parsed competitions file. Throws one Error naming every problem.
+ * @param {unknown} raw
+ */
+export function parseCompetitions(raw) {
+ if (!Array.isArray(raw)) throw new Error('competitions: the file must be a JSON array');
+ const out = [];
+ const seen = new Set();
+ raw.forEach((item, i) => {
+ const r = competitionSchema.safeParse(item);
+ if (!r.success) {
+ const detail = r.error.issues.map((x) => `${x.path.join('.') || 'value'}: ${x.message}`).join('; ');
+ throw new Error(`competitions[${i}]: ${detail}`);
+ }
+ if (seen.has(r.data.slug)) throw new Error(`competitions[${i}]: duplicate slug "${r.data.slug}"`);
+ seen.add(r.data.slug);
+ out.push(r.data);
+ });
+ return out;
+}
+
+/** Read and validate the competitions file. `COMPETITIONS_FILE` overrides the path (tests). */
+export function loadCompetitions() {
+ const file = process.env.COMPETITIONS_FILE || DEFAULT_FILE;
+ return parseCompetitions(JSON.parse(readFileSync(file, 'utf8')));
+}
+
+/** @param {string} slug */
+export function findCompetition(slug) {
+ return loadCompetitions().find((c) => c.slug === slug) || null;
+}
+
+/**
+ * Where a competition is on the clock.
+ * upcoming before starts_at, registration not open
+ * open registration open (starts_at to register_by)
+ * building registration closed, entrants still building and tokenizing
+ * ended after ends_at
+ * `tokenizing` says whether launches still count; `next_deadline` is the next
+ * moment the page counts down to.
+ * @param {z.infer<typeof competitionSchema>} c
+ * @param {number} [now]
+ */
+export function competitionPhase(c, now = Date.now()) {
+ const starts = Date.parse(c.starts_at);
+ const registerBy = Date.parse(c.register_by);
+ const tokenizeBy = Date.parse(c.tokenize_by);
+ const ends = Date.parse(c.ends_at);
+ /** @type {'upcoming'|'open'|'building'|'ended'} */
+ let phase;
+ if (now < starts) phase = 'upcoming';
+ else if (now < registerBy) phase = 'open';
+ else if (now < ends) phase = 'building';
+ else phase = 'ended';
+ const marks = [
+ { key: 'starts_at', label: 'Registration opens', at: starts },
+ { key: 'register_by', label: 'Registration closes', at: registerBy },
+ { key: 'tokenize_by', label: 'Launch your coin by', at: tokenizeBy },
+ { key: 'ends_at', label: 'Competition ends', at: ends },
+ ]
+ .filter((m) => m.at > now)
+ .sort((a, b) => a.at - b.at)[0];
+ return {
+ phase,
+ registration_open: phase === 'open',
+ tokenizing: now >= starts && now < tokenizeBy,
+ next_deadline: marks ? { key: marks.key, label: marks.label, at: new Date(marks.at).toISOString() } : null,
+ };
+}
+
+/** The listing shape: the config minus nothing secret, plus the phase. */
+export function describeCompetition(c, now = Date.now()) {
+ return { ...c, ...competitionPhase(c, now) };
+}
+
+export function rankingMethod(c) {
+ return (
+ `Entries are ranked by the creator fees (SOL) their agent's own wallet has earned on pump.fun, from the ` +
+ `platform's creator-earnings snapshot (refreshed every 30 minutes) and attributed by the same rule as the ` +
+ `agent earnings page. Only a tokenized entry is ranked: its agent launched a mainnet coin through three.ws ` +
+ `between ${c.starts_at} and ${c.tokenize_by}. Other entries are listed after the ranked ones, in registration order.`
+ );
+}
+
+/**
+ * Public entries of a competition with their coin and fees, ranked.
+ * Only public agents are listed.
+ * @param {z.infer<typeof competitionSchema>} c
+ */
+export async function listEntries(c) {
+ const rows = await sql`
+ select e.id, e.agent_id, e.team_name, e.x_handle, e.track, e.created_at,
+ ai.name as agent_name
+ from competition_entries e
+ join agent_identities ai on ai.id = e.agent_id
+ where e.competition = ${c.slug} and ai.is_public = true and ai.deleted_at is null
+ order by e.created_at asc
+ `;
+ if (!rows.length) return { entries: [], refreshed_at: null };
+ const ids = rows.map((r) => r.agent_id);
+ const [coins, fees] = await Promise.all([
+ sql`
+ select distinct on (agent_id) agent_id, mint, symbol, name, created_at
+ from pump_agent_mints
+ where agent_id = any(${ids}) and network = 'mainnet'
+ and created_at >= ${c.starts_at} and created_at <= ${c.tokenize_by}
+ order by agent_id, created_at asc
+ `,
+ creatorFeesByAgent(ids),
+ ]);
+ const coinBy = new Map(coins.map((x) => [x.agent_id, x]));
+ const entries = rows.map((r) => {
+ const coin = coinBy.get(r.agent_id) || null;
+ const fee = fees.get(r.agent_id);
+ return {
+ id: r.id,
+ agent: { id: r.agent_id, name: r.agent_name, url: `/agents/${r.agent_id}` },
+ team_name: r.team_name,
+ x_handle: r.x_handle,
+ track: r.track,
+ registered_at: r.created_at,
+ tokenized: !!coin,
+ coin: coin ? { mint: coin.mint, symbol: coin.symbol, name: coin.name, url: `/launches/${coin.mint}`, launched_at: coin.created_at } : null,
+ fees_sol: coin ? Number(fee ? fee.lamports : 0n) / 1e9 : null,
+ _fee_lamports: coin && fee ? fee.lamports : 0n,
+ };
+ });
+ entries.sort((a, b) => {
+ if (a.tokenized !== b.tokenized) return a.tokenized ? -1 : 1;
+ if (a.tokenized) {
+ if (a._fee_lamports !== b._fee_lamports) return a._fee_lamports > b._fee_lamports ? -1 : 1;
+ }
+ return String(a.registered_at) < String(b.registered_at) ? -1 : 1;
+ });
+ let rank = 0;
+ const out = entries.map(({ _fee_lamports, ...e }) => ({ rank: e.tokenized ? ++rank : null, ...e }));
+ const stamps = [...fees.values()].map((f) => f.refreshed_at).filter(Boolean).map((d) => new Date(d).getTime());
+ return { entries: out, refreshed_at: stamps.length ? new Date(Math.min(...stamps)).toISOString() : null };
+}
+
+export class RegistrationError extends Error {
+ /** @param {number} status @param {string} code @param {string} message */
+ constructor(status, code, message) {
+ super(message);
+ this.status = status;
+ this.code = code;
+ }
+}
+
+/**
+ * Register a caller's agent. Enforces the window, ownership, a public agent and
+ * a known track; one entry per agent per competition.
+ * @param {z.infer<typeof competitionSchema>} c
+ * @param {string} userId
+ * @param {{ agent_id: string, team_name?: string, x_handle?: string, track?: string }} input
+ * @param {number} [now]
+ */
+export async function registerEntry(c, userId, input, now = Date.now()) {
+ const p = competitionPhase(c, now);
+ if (p.phase === 'upcoming') throw new RegistrationError(409, 'registration_not_open', `Registration opens ${c.starts_at}.`);
+ if (!p.registration_open) throw new RegistrationError(409, 'registration_closed', `Registration closed ${c.register_by}.`);
+ if (c.tracks.length && !input.track) throw new RegistrationError(400, 'validation_error', 'Choose a track.');
+ if (input.track && !c.tracks.some((t) => t.name === input.track)) {
+ throw new RegistrationError(400, 'validation_error', `Unknown track. Choose one of: ${c.tracks.map((t) => t.name).join(', ')}.`);
+ }
+ const [agent] = await sql`
+ select id, user_id, is_public from agent_identities where id = ${input.agent_id} and deleted_at is null
+ `;
+ if (!agent || agent.user_id !== userId) {
+ throw new RegistrationError(403, 'forbidden', 'That agent does not belong to your account.');
+ }
+ if (!agent.is_public) {
+ throw new RegistrationError(409, 'agent_not_public', 'Make the agent public first: entries appear on the public leaderboard.');
+ }
+ const [row] = await sql`
+ insert into competition_entries (competition, user_id, agent_id, team_name, x_handle, track)
+ values (${c.slug}, ${userId}, ${input.agent_id}, ${input.team_name || null}, ${input.x_handle || null}, ${input.track || null})
+ on conflict (competition, agent_id) do nothing
+ returning id, created_at
+ `;
+ if (!row) throw new RegistrationError(409, 'already_registered', 'This agent is already entered.');
+ return row;
+}
+
+/** Entries a signed-in user already has in a competition (agent ids). */
+export async function viewerEntries(slug, userId) {
+ const rows = await sql`select agent_id from competition_entries where competition = ${slug} and user_id = ${userId}`;
+ return rows.map((r) => r.agent_id);
+}
diff --git a/api/_lib/migrations/20261023200000_competition_entries.sql b/api/_lib/migrations/20261023200000_competition_entries.sql
new file mode 100644
index 000000000..e2216459e
--- /dev/null
+++ b/api/_lib/migrations/20261023200000_competition_entries.sql
@@ -0,0 +1,27 @@
+-- Migration: builder competition registrations.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261023200000_competition_entries.sql
+-- Idempotent.
+--
+-- The competitions themselves (dates, tracks, prizes, judges, rules) live in
+-- data/competitions.json, not in the database. This table only holds who
+-- entered: one row per agent per competition. A tokenized entry is derived at
+-- read time from pump_agent_mints, so nothing here is copied from launch data.
+
+begin;
+
+create table if not exists competition_entries (
+ id uuid primary key default gen_random_uuid(),
+ competition text not null,
+ user_id uuid not null references users(id) on delete cascade,
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ team_name text,
+ x_handle text,
+ track text,
+ created_at timestamptz not null default now(),
+ unique (competition, agent_id)
+);
+
+create index if not exists competition_entries_comp_idx on competition_entries (competition, created_at);
+create index if not exists competition_entries_user_idx on competition_entries (user_id);
+
+commit;
diff --git a/api/competitions.js b/api/competitions.js
new file mode 100644
index 000000000..0783faea0
--- /dev/null
+++ b/api/competitions.js
@@ -0,0 +1,96 @@
+// Builder competitions.
+//
+// GET /api/competitions every configured competition, with its phase
+// GET /api/competitions/:slug one competition, its ranked entries, and the viewer's entries
+// GET /api/competitions/:slug/entries the ranked public entries
+// POST /api/competitions/:slug/entries register one of the caller's agents (session or key, CSRF-guarded)
+//
+// The competitions come from data/competitions.json (empty until the owner adds
+// one). Docs: docs/competitions.md.
+
+import { z } from 'zod';
+import { cors, json, error, wrap, method, readJson, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { getRequestUser, getSessionUser } from './_lib/auth.js';
+import { requireCsrf } from './_lib/csrf.js';
+import { parse } from './_lib/validate.js';
+import {
+ loadCompetitions,
+ describeCompetition,
+ listEntries,
+ rankingMethod,
+ registerEntry,
+ viewerEntries,
+ RegistrationError,
+} from './_lib/competitions.js';
+
+const entrySchema = z.object({
+ agent_id: z.string().uuid(),
+ team_name: z.string().trim().max(80).optional(),
+ x_handle: z
+ .string()
+ .trim()
+ .regex(/^@?[A-Za-z0-9_]{1,15}$/, 'x_handle must be a valid X handle')
+ .transform((h) => h.replace(/^@/, ''))
+ .optional(),
+ track: z.string().trim().max(80).optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const url = new URL(req.url, 'http://x');
+ const slug = url.searchParams.get('slug');
+ const part = url.searchParams.get('part');
+
+ let competitions;
+ try {
+ competitions = loadCompetitions();
+ } catch (e) {
+ return error(res, 500, 'competitions_config_invalid', e.message);
+ }
+
+ if (!slug) {
+ if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'use GET');
+ res.setHeader('cache-control', 'public, max-age=30, s-maxage=60, stale-while-revalidate=120');
+ return json(res, 200, { competitions: competitions.map((c) => describeCompetition(c)) });
+ }
+
+ const comp = competitions.find((c) => c.slug === slug);
+ if (!comp) return error(res, 404, 'not_found', 'competition not found');
+
+ if (req.method === 'POST') {
+ if (part !== 'entries') return error(res, 405, 'method_not_allowed', 'POST to /entries');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ const user = await getRequestUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in to enter');
+ if (!(await requireCsrf(req, res, user.id))) return;
+ const body = parse(entrySchema, await readJson(req));
+ try {
+ const row = await registerEntry(comp, user.id, body);
+ return json(res, 201, { entry: { id: row.id, competition: comp.slug, agent_id: body.agent_id, registered_at: row.created_at } });
+ } catch (e) {
+ if (e instanceof RegistrationError) return error(res, e.status, e.code, e.message);
+ throw e;
+ }
+ }
+
+ const { entries, refreshed_at } = await listEntries(comp);
+ if (part === 'entries') {
+ res.setHeader('cache-control', 'public, max-age=30, s-maxage=60, stale-while-revalidate=120');
+ return json(res, 200, { competition: comp.slug, entries, refreshed_at, method: rankingMethod(comp) });
+ }
+
+ const viewer = await getSessionUser(req).catch(() => null);
+ const mine = viewer ? await viewerEntries(comp.slug, viewer.id) : [];
+ res.setHeader('cache-control', viewer ? 'private, no-store' : 'public, max-age=30, s-maxage=60, stale-while-revalidate=120');
+ return json(res, 200, {
+ competition: describeCompetition(comp),
+ entries,
+ refreshed_at,
+ method: rankingMethod(comp),
+ viewer: viewer ? { signed_in: true, entered_agent_ids: mine } : { signed_in: false, entered_agent_ids: [] },
+ });
+});
diff --git a/data/competitions.json b/data/competitions.json
new file mode 100644
index 000000000..fe51488c7
--- /dev/null
+++ b/data/competitions.json
@@ -0,0 +1 @@
+[]
diff --git a/tests/competitions.test.js b/tests/competitions.test.js
new file mode 100644
index 000000000..b5a517d7f
--- /dev/null
+++ b/tests/competitions.test.js
@@ -0,0 +1,271 @@
+// Builder competitions against the REAL competition_entries and
+// agent_coin_earnings migrations (PGlite), the real config validator and the
+// real HTTP handler. Only auth/CSRF/rate-limit edges are replaced.
+
+import { readFileSync, writeFileSync, mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Readable } from 'node:stream';
+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';
+import { PGlite } from '@electric-sql/pglite';
+
+const dbState = { pg: null };
+const authState = { user: null };
+
+vi.mock('../api/_lib/db.js', () => {
+ // A tagged template that is also a fragment: nested sql`` values are inlined
+ // when the outer query is awaited, as the real driver does.
+ const build = (strings, values) => {
+ let text = '';
+ const params = [];
+ strings.forEach((part, i) => {
+ text += part;
+ if (i >= values.length) return;
+ const v = values[i];
+ if (v && v.__frag) {
+ const inner = build(v.strings, v.values);
+ const shifted = inner.text.replace(/\$(\d+)/g, (_, n) => `$${Number(n) + params.length}`);
+ text += shifted;
+ params.push(...inner.params);
+ } else {
+ params.push(v);
+ text += `$${params.length}`;
+ }
+ });
+ return { text, params };
+ };
+ const sql = (strings, ...values) => {
+ const frag = {
+ __frag: true,
+ strings,
+ values,
+ then(res, rej) {
+ const { text, params } = build(strings, values);
+ return dbState.pg.query(text, params).then((r) => r.rows).then(res, rej);
+ },
+ };
+ return frag;
+ };
+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };
+});
+vi.mock('../api/_lib/auth.js', () => ({
+ getRequestUser: async () => authState.user,
+ getSessionUser: async () => authState.user,
+}));
+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: async () => true }));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: async () => ({ success: true }) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const lib = await import('../api/_lib/competitions.js');
+const handler = (await import('../api/competitions.js')).default;
+
+const MIG = new URL('../api/_lib/migrations/', import.meta.url);
+const read = (f) => readFileSync(new URL(f, MIG), 'utf8');
+
+const USER = '11111111-1111-4111-8111-111111111111';
+const OTHER = '22222222-2222-4222-8222-222222222222';
+const A1 = 'a1111111-1111-4111-8111-111111111111';
+const A2 = 'a2222222-2222-4222-8222-222222222222';
+const A3 = 'a3333333-3333-4333-8333-333333333333';
+const A_PRIVATE = 'a4444444-4444-4444-8444-444444444444';
+const A_OTHER = 'a5555555-5555-4555-8555-555555555555';
+
+const NOW = Date.now();
+const iso = (offsetDays) => new Date(NOW + offsetDays * 86_400_000).toISOString();
+const comp = (over = {}) => ({
+ slug: 'spring-build',
+ title: 'Spring Build',
+ starts_at: iso(-10),
+ register_by: iso(10),
+ tokenize_by: iso(20),
+ ends_at: iso(30),
+ tracks: [{ name: 'Trading', description: 'Agents that trade.' }],
+ prizes: [{ place: '1st', amount: 1000, asset: 'USDC', vesting: 'Paid at the end.' }],
+ judges: [{ name: 'A Judge' }],
+ rules: ['Launch your coin through three.ws.'],
+ ...over,
+});
+
+let dir;
+function useConfig(list) {
+ const file = join(dir, `c-${Math.random().toString(36).slice(2)}.json`);
+ writeFileSync(file, JSON.stringify(list));
+ process.env.COMPETITIONS_FILE = file;
+}
+
+function call(method, { url, body } = {}) {
+ return new Promise((resolve) => {
+ const headers = {};
+ const res = {
+ statusCode: 200,
+ setHeader: (k, v) => (headers[k.toLowerCase()] = v),
+ getHeader: (k) => headers[k.toLowerCase()],
+ writeHead(s) {
+ this.statusCode = s;
+ },
+ end(data) {
+ resolve({ status: this.statusCode, body: data ? JSON.parse(data) : null, headers });
+ },
+ };
+ const raw = body ? Buffer.from(JSON.stringify(body)) : null;
+ const req = Object.assign(Readable.from(raw ? [raw] : []), {
+ method,
+ url,
+ headers: { host: 'x', origin: 'https://three.ws', 'content-type': 'application/json' },
+ socket: { remoteAddress: '127.0.0.1' },
+ });
+ handler(req, res);
+ });
+}
+
+beforeAll(() => {
+ dir = mkdtempSync(join(tmpdir(), 'comp-'));
+});
+
+beforeEach(async () => {
+ authState.user = null;
+ const pg = new PGlite();
+ dbState.pg = pg;
+ await pg.exec(`
+ create table users (id uuid primary key);
+ create table agent_identities (
+ id uuid primary key, user_id uuid not null references users(id), name text,
+ is_public boolean not null default true, deleted_at timestamptz, meta jsonb not null default '{}'::jsonb);
+ create table pump_agent_mints (
+ id uuid primary key default gen_random_uuid(), agent_id uuid not null references agent_identities(id),
+ user_id uuid not null references users(id), network text not null, mint text not null, name text, symbol text,
+ created_at timestamptz not null default now());
+ `);
+ await pg.exec(read('20260930121000_agent_coin_earnings.sql'));
+ await pg.exec(read('20261023200000_competition_entries.sql'));
+ await pg.exec(`
+ insert into users values ('${USER}'), ('${OTHER}');
+ insert into agent_identities (id, user_id, name, is_public, meta) values
+ ('${A1}', '${USER}', 'Alpha', true, '{"solana_address":"W1"}'),
+ ('${A2}', '${USER}', 'Beta', true, '{"solana_address":"W2"}'),
+ ('${A3}', '${USER}', 'Gamma', true, '{"solana_address":"W3"}'),
+ ('${A_PRIVATE}', '${USER}', 'Hidden', false, '{}'),
+ ('${A_OTHER}', '${OTHER}', 'Theirs', true, '{}');
+ `);
+});
+
+afterEach(() => {
+ delete process.env.COMPETITIONS_FILE;
+});
+
+describe('config', () => {
+ it('the committed file is valid and ships empty', () => {
+ const committed = JSON.parse(readFileSync(new URL('../data/competitions.json', import.meta.url), 'utf8'));
+ expect(committed).toEqual([]);
+ expect(lib.parseCompetitions(committed)).toEqual([]);
+ });
+
+ it('rejects out-of-order dates, duplicate slugs and unknown keys with a named reason', () => {
+ expect(() => lib.parseCompetitions([comp({ register_by: iso(-20) })])).toThrow(/register_by: must be after starts_at/);
+ expect(() => lib.parseCompetitions([comp(), comp()])).toThrow(/duplicate slug/);
+ expect(() => lib.parseCompetitions([{ ...comp(), prize_pool: 5 }])).toThrow(/competitions\[0\]/);
+ expect(() => lib.parseCompetitions({})).toThrow(/JSON array/);
+ });
+
+ it('works out the phase and next deadline from the clock', () => {
+ const c = lib.parseCompetitions([comp()])[0];
+ expect(lib.competitionPhase(c, NOW).phase).toBe('open');
+ expect(lib.competitionPhase(c, NOW).next_deadline.key).toBe('register_by');
+ expect(lib.competitionPhase(c, NOW - 20 * 86_400_000).phase).toBe('upcoming');
+ expect(lib.competitionPhase(c, NOW + 15 * 86_400_000)).toMatchObject({ phase: 'building', registration_open: false, tokenizing: true });
+ expect(lib.competitionPhase(c, NOW + 40 * 86_400_000)).toMatchObject({ phase: 'ended', next_deadline: null });
+ });
+});
+
+describe('empty config', () => {
+ it('lists nothing and 404s an unknown slug', async () => {
+ useConfig([]);
+ const list = await call('GET', { url: '/api/competitions' });
+ expect(list.status).toBe(200);
+ expect(list.body).toEqual({ competitions: [] });
+ expect((await call('GET', { url: '/api/competitions.js?slug=nope' })).status).toBe(404);
+ });
+});
+
+describe('registration', () => {
+ const post = (body, slug = 'spring-build') =>
+ call('POST', { url: `/api/competitions.js?slug=${slug}&part=entries`, body });
+
+ it('requires sign in', async () => {
+ useConfig([comp()]);
+ expect((await post({ agent_id: A1, track: 'Trading' })).status).toBe(401);
+ });
+
+ it('enters the caller\'s own public agent once', async () => {
+ useConfig([comp()]);
+ authState.user = { id: USER };
+ const ok = await post({ agent_id: A1, track: 'Trading', team_name: 'Team A', x_handle: '@alpha' });
+ expect(ok.status).toBe(201);
+ const again = await post({ agent_id: A1, track: 'Trading' });
+ expect(again.status).toBe(409);
+ expect(again.body.error).toBe('already_registered');
+ const [row] = (await dbState.pg.query('select x_handle, team_name from competition_entries')).rows;
+ expect(row).toEqual({ x_handle: 'alpha', team_name: 'Team A' });
+ });
+
+ it('refuses another user\'s agent, a private agent and an unknown track', async () => {
+ useConfig([comp()]);
+ authState.user = { id: USER };
+ expect((await post({ agent_id: A_OTHER, track: 'Trading' })).body.error).toBe('forbidden');
+ expect((await post({ agent_id: A_PRIVATE, track: 'Trading' })).body.error).toBe('agent_not_public');
+ expect((await post({ agent_id: A1, track: 'Nope' })).status).toBe(400);
+ expect((await post({ agent_id: A1 })).status).toBe(400);
+ expect((await dbState.pg.query('select 1 from competition_entries')).rows).toHaveLength(0);
+ });
+
+ it('enforces the window on both sides', async () => {
+ authState.user = { id: USER };
+ useConfig([comp({ starts_at: iso(1), register_by: iso(5), tokenize_by: iso(9), ends_at: iso(10) })]);
+ expect((await post({ agent_id: A1, track: 'Trading' })).body.error).toBe('registration_not_open');
+ useConfig([comp({ starts_at: iso(-9), register_by: iso(-1), tokenize_by: iso(9), ends_at: iso(10) })]);
+ expect((await post({ agent_id: A1, track: 'Trading' })).body.error).toBe('registration_closed');
+ });
+});
+
+describe('leaderboard', () => {
+ it('ranks tokenized entries by creator fees from the earnings snapshot, in-window launches only', async () => {
+ useConfig([comp()]);
+ const pg = dbState.pg;
+ for (const [agent, team] of [[A1, 'one'], [A2, 'two'], [A3, 'three']]) {
+ await pg.query(`insert into competition_entries (competition, user_id, agent_id, team_name, track) values ('spring-build', $1, $2, $3, 'Trading')`, [USER, agent, team]);
+ }
+ await pg.query(
+ `insert into pump_agent_mints (agent_id, user_id, network, mint, symbol, created_at) values
+ ($1, $4, 'mainnet', 'MINT1', 'ONE', $5),
+ ($2, $4, 'mainnet', 'MINT2', 'TWO', $5),
+ ($3, $4, 'mainnet', 'MINT3', 'OLD', $6)`,
+ [A1, A2, A3, USER, iso(-5), iso(-60)],
+ );
+ await pg.query(
+ `insert into agent_coin_earnings (mint, agent_id, creator, earned_lamports, source, refreshed_at) values
+ ('MINT1', $1, 'W1', 1000000000, 'pumpfun_creator_fees', now()),
+ ('MINT2', $2, 'W2', 3000000000, 'pumpfun_creator_fees', now()),
+ ('MINT3', $3, 'W3', 9000000000, 'pumpfun_creator_fees', now())`,
+ [A1, A2, A3],
+ );
+ const res = await call('GET', { url: '/api/competitions.js?slug=spring-build' });
+ expect(res.status).toBe(200);
+ const rows = res.body.entries.map((e) => [e.agent.name, e.rank, e.tokenized, e.fees_sol]);
+ expect(rows).toEqual([
+ ['Beta', 1, true, 3],
+ ['Alpha', 2, true, 1],
+ ['Gamma', null, false, null],
+ ]);
+ expect(res.body.entries[0].coin.mint).toBe('MINT2');
+ expect(res.body.method).toMatch(/creator fees/);
+ expect(res.body.viewer).toEqual({ signed_in: false, entered_agent_ids: [] });
+ });
+
+ it('is empty, not an error, with no entries', async () => {
+ useConfig([comp()]);
+ const res = await call('GET', { url: '/api/competitions.js?slug=spring-build&part=entries' });
+ expect(res.body.entries).toEqual([]);
+ });
+});