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.

fix(leaderboard): count launches from the platform's launch records and add GET /api/leaderboard/earnings

nirholas2be894e19e13
diff --git a/api/_lib/launch-counts.js b/api/_lib/launch-counts.js
new file mode 100644
index 000000000..9a1f08091
--- /dev/null
+++ b/api/_lib/launch-counts.js
@@ -0,0 +1,46 @@
+// @ts-check
+// Mainnet coin launches per user: the single count behind the `launches` metric
+// of GET /api/leaderboard/unified and the daily top-10 badge sweep in
+// api/cron/leaderboard-rollup.js, so the board and the badge rank the same way.
+//
+// A launch is a mainnet mint recorded in the platform's own launch records:
+// pump_agent_mints (every pump.fun launch, including the ones signed by an
+// agent's custodial wallet) or fixed_supply_launches (fixed-supply venue
+// launches). Each mint counts once. Both used to read
+// agent_identities.meta.token.mint instead, which agent-wallet launches leave
+// empty, so the board undercounted every builder who launched from an agent.
+//
+// A pump.fun launch counts when its agent is public and not deleted, as before.
+// A fixed-supply launch counts when it has no agent or its agent is public.
+
+import { sql } from './db.js';
+
+/**
+ * @param {{ limit?: number | null }} [opts] `limit` keeps the top N, highest first.
+ * @returns {Promise<Array<{ user_id: string, value: string }>>}
+ */
+export function launchCountsByUser({ limit = null } = {}) {
+ const top = limit == null ? sql`` : sql`limit ${limit}`;
+ return sql`
+ with launches as (
+ select pam.user_id, pam.mint
+ from pump_agent_mints pam
+ join agent_identities ai on ai.id = pam.agent_id
+ where pam.network = 'mainnet'
+ and ai.is_public = true
+ and ai.deleted_at is null
+ union
+ select fsl.user_id, fsl.mint
+ from fixed_supply_launches fsl
+ left join agent_identities ai on ai.id = fsl.agent_id
+ where fsl.network = 'mainnet'
+ and (fsl.agent_id is null or (ai.is_public = true and ai.deleted_at is null))
+ )
+ select user_id, count(distinct mint)::bigint as value
+ from launches
+ where user_id is not null
+ group by user_id
+ order by value desc, user_id
+ ${top}
+ `;
+}
diff --git a/api/cron/leaderboard-rollup.js b/api/cron/leaderboard-rollup.js
index 2f1fce677..6d7751c75 100644
--- a/api/cron/leaderboard-rollup.js
+++ b/api/cron/leaderboard-rollup.js
@@ -16,6 +16,7 @@ import { json, method, wrapCron } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
import { unlockBadge, BADGES } from '../_lib/streaks.js';
import { requireCron } from '../_lib/cron-auth.js';
+import { launchCountsByUser } from '../_lib/launch-counts.js';
const METRICS = ['creations', 'remixes_received', 'launches', 'followers', 'walk_distance'];
@@ -60,15 +61,7 @@ async function top10UserIds(metric) {
return rows.map((r) => r.user_id);
}
if (metric === 'launches') {
- const rows = await sql`
- select user_id, count(*)::bigint as value
- from agent_identities
- where user_id is not null and is_public = true and deleted_at is null
- and meta->'token'->>'mint' is not null
- group by user_id
- order by value desc
- limit 10
- `;
+ const rows = await launchCountsByUser({ limit: 10 });
return rows.map((r) => r.user_id);
}
if (metric === 'followers') {
diff --git a/api/leaderboard/earnings.js b/api/leaderboard/earnings.js
new file mode 100644
index 000000000..f0567cc6f
--- /dev/null
+++ b/api/leaderboard/earnings.js
@@ -0,0 +1,44 @@
+// GET /api/leaderboard/earnings[?window=24h|7d|30d|all&limit=&offset=]: public
+// agents ranked by what they earned in a window. Earnings are pump.fun creator
+// fees on the coins an agent launched plus its service income (x402 skill sales
+// and completed hires), each shown separately with the total in SOL and USD.
+//
+// The ranking and every row's figures come from listEarningsLeaderboard in
+// api/_lib/agent-earnings.js, the same computation behind
+// GET /api/agents/:id/earnings, so a row and the agent's own Earned card always
+// agree. Rows carry their rank in the previous window of the same length
+// (`previous_rank`, `movement`), except for 'all'.
+//
+// Figures come from the creator-earnings snapshot the cron refreshes every 30
+// minutes, so the response is cached for a minute at the edge.
+
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { listEarningsLeaderboard, normalizeWindow } from '../_lib/agent-earnings.js';
+
+const MAX_LIMIT = 100;
+const DEFAULT_LIMIT = 25;
+
+/** @param {string | null} v @param {number} fallback @param {number} max */
+function intParam(v, fallback, max) {
+ const n = Number.parseInt(String(v ?? ''), 10);
+ if (!Number.isFinite(n) || n < 0) return fallback;
+ return Math.min(n, max);
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://x');
+ const window = normalizeWindow(url.searchParams.get('window') || '7d');
+ const limit = Math.max(1, intParam(url.searchParams.get('limit'), DEFAULT_LIMIT, MAX_LIMIT));
+ const offset = intParam(url.searchParams.get('offset'), 0, 100_000);
+
+ const body = await listEarningsLeaderboard({ window, limit, offset });
+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=120, stale-while-revalidate=300');
+ return json(res, 200, body);
+});
diff --git a/api/leaderboard/unified.js b/api/leaderboard/unified.js
index ffddfbccb..2b321c96f 100644
--- a/api/leaderboard/unified.js
+++ b/api/leaderboard/unified.js
@@ -15,8 +15,8 @@
// finished creations. Both sides must be status='done',
// and a creator's own refines of their own model never
// count (a real derivative count, not a view/like one).
-// · launches — pump.fun coins minted from this user's agents
-// (agent_identities.meta->'token'->>'mint').
+// · launches: mainnet coins this user launched, from the
+// platform's launch records (api/_lib/launch-counts.js).
// · followers — user_follows platform-wide follower count.
// · walk_distance — total metres walked while signed in (walk_metrics,
// all-time, signed-in walkers only — the anonymous
@@ -41,6 +41,7 @@ import { sql } from '../_lib/db.js';
import { getSessionUser, extractBearer, authenticateBearer } from '../_lib/auth.js';
import { thumbnailUrl } from '../_lib/r2.js';
import { getStreak, listBadges } from '../_lib/streaks.js';
+import { launchCountsByUser } from '../_lib/launch-counts.js';
export const maxDuration = 10;
@@ -96,17 +97,7 @@ async function rankingRows(metric) {
group by m.user_id
`;
}
- if (metric === 'launches') {
- return sql`
- select user_id, count(*)::bigint as value
- from agent_identities
- where user_id is not null
- and is_public = true
- and deleted_at is null
- and meta->'token'->>'mint' is not null
- group by user_id
- `;
- }
+ if (metric === 'launches') return launchCountsByUser();
if (metric === 'followers') {
return sql`
select following_id as user_id, count(*)::bigint as value
diff --git a/tests/leaderboard-launch-counts.test.js b/tests/leaderboard-launch-counts.test.js
new file mode 100644
index 000000000..1adcdcaa4
--- /dev/null
+++ b/tests/leaderboard-launch-counts.test.js
@@ -0,0 +1,152 @@
+// The `launches` metric of GET /api/leaderboard/unified, driven through the real
+// handler against an in-process Postgres (PGlite), so the count runs as real SQL.
+//
+// Regression: the board used to count agent_identities.meta.token.mint, which a
+// launch signed by an agent's custodial wallet never writes, so those builders
+// ranked with zero launches. The count now comes from the platform's launch
+// records (pump_agent_mints, fixed_supply_launches) via api/_lib/launch-counts.js,
+// which the daily badge sweep shares.
+
+import { Readable } from 'node:stream';
+import { beforeAll, beforeEach, describe, it, expect, vi } from 'vitest';
+import { createPgliteSql } from './_helpers/pglite-sql.js';
+
+const holder = vi.hoisted(() => ({ db: null }));
+
+vi.mock('../api/_lib/db.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, sql: (...args) => holder.db.sql(...args) };
+});
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: async () => null,
+ authenticateBearer: async () => null,
+ extractBearer: () => null,
+}));
+vi.mock('../api/_lib/rate-limit.js', async (importActual) => {
+ const actual = await importActual();
+ const ok = async () => ({ success: true, limit: 100, remaining: 99, reset: Date.now() + 60_000 });
+ return { ...actual, limits: new Proxy({}, { get: () => ok }) };
+});
+vi.mock('../api/_lib/r2.js', () => ({ thumbnailUrl: () => null }));
+
+process.env.DATABASE_URL ||= 'postgres://pglite.test/db';
+
+const AGENT_WALLET_BUILDER = '11111111-1111-4111-8111-111111111111';
+const STUDIO_BUILDER = '22222222-2222-4222-8222-222222222222';
+const HIDDEN_BUILDER = '33333333-3333-4333-8333-333333333333';
+// Synthetic, keyless mint-shaped strings; not anyone's coin.
+const MINT = (n) => `THREEsynthetic${String(n).padStart(30, '1')}`;
+
+const DDL = `
+ create table users (id uuid primary key, username text, display_name text, deleted_at timestamptz);
+ create table avatars (id uuid primary key default gen_random_uuid(), owner_id uuid, thumbnail_key text,
+ created_at timestamptz default now(), deleted_at timestamptz);
+ create table agent_identities (
+ id uuid primary key default gen_random_uuid(), user_id uuid, name text,
+ meta jsonb default '{}'::jsonb, is_public boolean default true, deleted_at timestamptz
+ );
+ create table pump_agent_mints (
+ id uuid primary key default gen_random_uuid(), agent_id uuid, user_id uuid, network text, mint text
+ );
+ create table fixed_supply_launches (
+ id uuid primary key default gen_random_uuid(), agent_id uuid, user_id uuid not null,
+ network text not null default 'mainnet', mint text not null
+ );
+`;
+
+function mockReqRes(url) {
+ const req = Object.assign(new Readable({ read() {} }), {
+ method: 'GET',
+ url,
+ headers: {},
+ query: {},
+ connection: { remoteAddress: '127.0.0.1' },
+ socket: { remoteAddress: '127.0.0.1' },
+ });
+ req.push(null);
+ const chunks = [];
+ const headers = {};
+ const res = {
+ statusCode: 200,
+ writableEnded: false,
+ headersSent: false,
+ setHeader: (k, v) => { headers[k.toLowerCase()] = v; },
+ getHeader: (k) => headers[k.toLowerCase()],
+ writeHead(code, h) { res.statusCode = code; Object.assign(headers, h || {}); },
+ write: (c) => chunks.push(c),
+ end(b) { if (b !== undefined) chunks.push(b); res.writableEnded = true; },
+ get json() { return JSON.parse(chunks.join('') || 'null'); },
+ };
+ return { req, res };
+}
+
+let handler;
+async function launchesBoard() {
+ const { req, res } = mockReqRes('/api/leaderboard/unified?metric=launches');
+ await handler(req, res);
+ return { status: res.statusCode, body: res.json };
+}
+
+async function agent(userId, { meta = {}, isPublic = true } = {}) {
+ const [row] = await holder.db.query(
+ `insert into agent_identities (user_id, name, meta, is_public) values ($1, 'Agent', $2, $3) returning id`,
+ [userId, JSON.stringify(meta), isPublic],
+ );
+ return row.id;
+}
+
+beforeAll(async () => {
+ ({ default: handler } = await import('../api/leaderboard/unified.js'));
+});
+
+beforeEach(async () => {
+ holder.db = createPgliteSql();
+ await holder.db.exec(DDL);
+ await holder.db.query(
+ `insert into users (id, username) values ($1, 'agentwallet'), ($2, 'studio'), ($3, 'hidden')`,
+ [AGENT_WALLET_BUILDER, STUDIO_BUILDER, HIDDEN_BUILDER],
+ );
+});
+
+describe('launches metric', () => {
+ it('counts a launch signed by an agent wallet, which leaves meta.token empty', async () => {
+ const a = await agent(AGENT_WALLET_BUILDER);
+ await holder.db.query(
+ `insert into pump_agent_mints (agent_id, user_id, network, mint) values ($1, $2, 'mainnet', $3), ($1, $2, 'mainnet', $4)`,
+ [a, AGENT_WALLET_BUILDER, MINT(1), MINT(2)],
+ );
+ const { status, body } = await launchesBoard();
+ expect(status).toBe(200);
+ expect(body.rows).toEqual([expect.objectContaining({ userId: AGENT_WALLET_BUILDER, value: 2, rank: 1 })]);
+ });
+
+ it('adds fixed-supply launches and counts a mint once', async () => {
+ const a = await agent(STUDIO_BUILDER, { meta: { token: { mint: MINT(3) } } });
+ await holder.db.query(
+ `insert into pump_agent_mints (agent_id, user_id, network, mint) values ($1, $2, 'mainnet', $3)`,
+ [a, STUDIO_BUILDER, MINT(3)],
+ );
+ await holder.db.query(
+ `insert into fixed_supply_launches (agent_id, user_id, network, mint)
+ values (null, $1, 'mainnet', $2), ($3, $1, 'mainnet', $4)`,
+ [STUDIO_BUILDER, MINT(4), a, MINT(3)],
+ );
+ const { body } = await launchesBoard();
+ expect(body.rows).toEqual([expect.objectContaining({ userId: STUDIO_BUILDER, value: 2 })]);
+ });
+
+ it('leaves out devnet coins and coins of private or deleted agents', async () => {
+ const priv = await agent(HIDDEN_BUILDER, { isPublic: false });
+ const gone = await agent(HIDDEN_BUILDER);
+ await holder.db.query(`update agent_identities set deleted_at = now() where id = $1`, [gone]);
+ const live = await agent(HIDDEN_BUILDER);
+ await holder.db.query(
+ `insert into pump_agent_mints (agent_id, user_id, network, mint)
+ values ($1, $4, 'mainnet', $5), ($2, $4, 'mainnet', $6), ($3, $4, 'devnet', $7)`,
+ [priv, gone, live, HIDDEN_BUILDER, MINT(5), MINT(6), MINT(7)],
+ );
+ const { body } = await launchesBoard();
+ expect(body.total).toBe(0);
+ expect(body.rows).toEqual([]);
+ });
+});