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(pump): short-circuit non-pump mints in /api/pump/curve to kill 404+RPC storm; close A1

nirholas325edc89b0ed
diff --git a/api/_lib/coin/cohorts.js b/api/_lib/coin/cohorts.js
new file mode 100644
index 000000000..6338494d5
--- /dev/null
+++ b/api/_lib/coin/cohorts.js
@@ -0,0 +1,283 @@
+// Holder cohorts — named, derived audience segments over a coin's holder set.
+//
+// Every agent token launched on three.ws already has its full holder set
+// snapshotted on-chain (Helius `getTokenAccounts`, Token-2022) into
+// `coin_holders` and refreshed by the snapshot cron (see distribution.js).
+// Cohorts are *queries* over that materialized set — not a second pipeline —
+// so they are always as fresh as the last snapshot and need no extra storage.
+//
+// A cohort is a predicate over real `coin_holders` columns (balance in token
+// smallest units, first_seen, last_seen). We expose them so the /go bounty
+// board, coin communities, and holder worlds can target a slice of a coin's
+// holders ("airdrop the top 10% of whales", "bounty visible to diamond hands",
+// "win-back wallets that exited").
+//
+// Sampling is deterministic: the same (wallet, cohort, salt) always lands in
+// the same bucket, so "10% of whales" is stable across calls and paginates
+// consistently — the idea borrowed from pump.fun's internal segments SDK,
+// reimplemented dependency-free against our own Postgres holder set.
+
+import { sql } from '../db.js';
+
+const DAY_MS = 86_400_000;
+
+// ─── Cohort registry ─────────────────────────────────────────────────────────
+//
+// Each cohort declares its tunable params (with defaults) for the public
+// definition listing. The predicate itself is resolved by cohortSpec() into a
+// small set of bounds the single keyset query understands — no dynamic SQL
+// string-building, which keeps every query a parameterized tagged template.
+
+export const COHORTS = Object.freeze([
+ {
+ id: 'holders',
+ name: 'All holders',
+ description: 'Every wallet currently holding a positive balance.',
+ params: [],
+ },
+ {
+ id: 'whales',
+ name: 'Whales',
+ description: 'Largest holders by balance — the top slice of the holder set.',
+ params: [{ key: 'topPct', label: 'Top fraction (0–1)', default: 0.1 }],
+ },
+ {
+ id: 'diamond-hands',
+ name: 'Diamond hands',
+ description: 'Wallets that first appeared at least N days ago and still hold.',
+ params: [{ key: 'minHoldDays', label: 'Minimum hold age (days)', default: 30 }],
+ },
+ {
+ id: 'new-buyers',
+ name: 'New buyers',
+ description: 'Wallets that first appeared within the last N days and still hold.',
+ params: [{ key: 'windowDays', label: 'Lookback window (days)', default: 7 }],
+ },
+ {
+ id: 'exited',
+ name: 'Exited',
+ description: 'Wallets that once held but have since sold to zero (win-back targets).',
+ params: [{ key: 'idleDays', label: 'Left at least N days ago', default: 0 }],
+ },
+]);
+
+const COHORT_IDS = new Set(COHORTS.map((c) => c.id));
+
+export function isCohortId(id) {
+ return COHORT_IDS.has(id);
+}
+
+export function listCohorts() {
+ return COHORTS.map((c) => ({ ...c }));
+}
+
+function num(value, fallback) {
+ const n = typeof value === 'number' ? value : parseFloat(value);
+ return Number.isFinite(n) ? n : fallback;
+}
+
+function daysAgo(days) {
+ return new Date(Date.now() - Math.max(0, days) * DAY_MS);
+}
+
+/**
+ * Resolve a cohort id + params into balance/first_seen bounds the keyset query
+ * applies. `whales` is special: its bound is a balance threshold derived from a
+ * percentile, so it carries { topPct } and the caller computes the threshold
+ * against live data first.
+ *
+ * @returns {{minBalance: bigint, maxBalance: bigint|null, firstSeenBefore: Date|null, firstSeenAfter: Date|null, lastSeenBefore: Date|null, topPct?: number}}
+ */
+export function cohortSpec(cohortId, params = {}) {
+ switch (cohortId) {
+ case 'holders':
+ return { minBalance: 1n, maxBalance: null, firstSeenBefore: null, firstSeenAfter: null, lastSeenBefore: null };
+ case 'whales': {
+ const topPct = Math.min(Math.max(num(params.topPct, 0.1), 0.0001), 1);
+ return { minBalance: 1n, maxBalance: null, firstSeenBefore: null, firstSeenAfter: null, lastSeenBefore: null, topPct };
+ }
+ case 'diamond-hands': {
+ const minHoldDays = Math.max(num(params.minHoldDays, 30), 0);
+ return { minBalance: 1n, maxBalance: null, firstSeenBefore: daysAgo(minHoldDays), firstSeenAfter: null, lastSeenBefore: null };
+ }
+ case 'new-buyers': {
+ const windowDays = Math.max(num(params.windowDays, 7), 0);
+ return { minBalance: 1n, maxBalance: null, firstSeenBefore: null, firstSeenAfter: daysAgo(windowDays), lastSeenBefore: null };
+ }
+ case 'exited': {
+ const idleDays = Math.max(num(params.idleDays, 0), 0);
+ return { minBalance: 0n, maxBalance: 0n, firstSeenBefore: null, firstSeenAfter: null, lastSeenBefore: idleDays > 0 ? daysAgo(idleDays) : null };
+ }
+ default:
+ throw new Error(`unknown cohort: ${cohortId}`);
+ }
+}
+
+// ─── Deterministic sampling (FNV-1a 32-bit, 10k buckets) ─────────────────────
+//
+// Stable, dependency-free hash so "N% of a cohort" is the same set every call
+// and survives pagination. Salt defaults to the coin id so the same wallet
+// falls into different buckets across coins.
+
+const BUCKETS = 10_000;
+
+export function sampleBucket(wallet, cohortId, salt) {
+ const input = `${wallet}#${cohortId}#${salt}`;
+ let h = 0x811c9dc5;
+ for (let i = 0; i < input.length; i++) {
+ h ^= input.charCodeAt(i);
+ // 32-bit FNV prime multiply via shifts to stay in integer range.
+ h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;
+ }
+ return h % BUCKETS;
+}
+
+export function inSample(bucket, fraction) {
+ return bucket < Math.floor(fraction * BUCKETS);
+}
+
+// ─── Whale threshold ─────────────────────────────────────────────────────────
+//
+// The balance at the top-`topPct` rank: ceil(positiveHolders × topPct) wallets
+// qualify (ties at the boundary are included, so the set is at-least-topPct).
+
+async function whaleThreshold({ coinId, topPct }) {
+ const [{ n }] = await sql`
+ select count(*)::int as n from coin_holders
+ where coin_id = ${coinId} and balance > 0
+ `;
+ const positive = n || 0;
+ if (positive === 0) return null;
+ const cutoffRank = Math.max(1, Math.ceil(positive * topPct));
+ const [row] = await sql`
+ select balance::text as balance from coin_holders
+ where coin_id = ${coinId} and balance > 0
+ order by balance desc
+ offset ${cutoffRank - 1} limit 1
+ `;
+ return row ? BigInt(row.balance) : null;
+}
+
+// ─── Counts overview ─────────────────────────────────────────────────────────
+
+/**
+ * Member counts for every cohort of a coin, for the definition overview.
+ * @returns {Promise<Record<string, number>>}
+ */
+export async function cohortCounts({ coinId, params = {} }) {
+ const diamond = cohortSpec('diamond-hands', params).firstSeenBefore;
+ const fresh = cohortSpec('new-buyers', params).firstSeenAfter;
+ const whaleMin = await whaleThreshold({ coinId, topPct: cohortSpec('whales', params).topPct });
+
+ const [row] = await sql`
+ select
+ count(*) filter (where balance > 0) as holders,
+ count(*) filter (where balance > 0 and ${whaleMin == null ? null : whaleMin.toString()}::bigint is not null
+ and balance >= ${whaleMin == null ? null : whaleMin.toString()}::bigint) as whales,
+ count(*) filter (where balance > 0 and first_seen <= ${diamond}::timestamptz) as "diamond-hands",
+ count(*) filter (where balance > 0 and first_seen >= ${fresh}::timestamptz) as "new-buyers",
+ count(*) filter (where balance = 0) as exited
+ from coin_holders
+ where coin_id = ${coinId}
+ `;
+ return {
+ holders: Number(row.holders) || 0,
+ whales: Number(row.whales) || 0,
+ 'diamond-hands': Number(row['diamond-hands']) || 0,
+ 'new-buyers': Number(row['new-buyers']) || 0,
+ exited: Number(row.exited) || 0,
+ };
+}
+
+// ─── Cursor (keyset over balance desc, id asc) ───────────────────────────────
+
+function encodeCursor(row) {
+ return Buffer.from(JSON.stringify({ b: row.balance, id: row.id }), 'utf-8').toString('base64url');
+}
+
+function decodeCursor(cursor) {
+ if (!cursor) return null;
+ try {
+ const { b, id } = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf-8'));
+ if (typeof b !== 'string' || !Number.isFinite(Number(id))) return null;
+ return { balance: b, id: Number(id) };
+ } catch {
+ return null;
+ }
+}
+
+// ─── Member export ───────────────────────────────────────────────────────────
+
+/**
+ * Page through a cohort's members, sorted by balance desc. Optional
+ * deterministic sampling thins the page (the same wallets every call).
+ *
+ * @param {object} opts
+ * @param {string} opts.coinId
+ * @param {string} opts.cohortId
+ * @param {object} [opts.params] cohort tunables (topPct, windowDays, …)
+ * @param {number} [opts.limit] page size before sampling (default 200, max 1000)
+ * @param {string} [opts.cursor] opaque pagination cursor
+ * @param {number} [opts.sample] 0–1 fraction to keep via deterministic bucketing
+ * @param {string} [opts.salt] sampling salt (defaults to coinId)
+ * @returns {Promise<{members: Array, nextCursor: string|null, sampled: boolean}>}
+ */
+export async function queryCohort({ coinId, cohortId, params = {}, limit = 200, cursor, sample, salt }) {
+ if (!isCohortId(cohortId)) throw new Error(`unknown cohort: ${cohortId}`);
+ const pageSize = Math.min(Math.max(Math.floor(limit) || 200, 1), 1000);
+ const spec = cohortSpec(cohortId, params);
+
+ let minBalance = spec.minBalance;
+ if (cohortId === 'whales') {
+ const threshold = await whaleThreshold({ coinId, topPct: spec.topPct });
+ // No positive holders → empty cohort, short-circuit.
+ if (threshold == null) return { members: [], nextCursor: null, sampled: sample != null };
+ minBalance = threshold;
+ }
+
+ const after = decodeCursor(cursor);
+ const maxBalance = spec.maxBalance;
+ const firstSeenBefore = spec.firstSeenBefore;
+ const firstSeenAfter = spec.firstSeenAfter;
+ const lastSeenBefore = spec.lastSeenBefore;
+
+ // One parameterized keyset query covers every cohort: nullable bounds are
+ // no-ops via `(:p is null or …)`, and the cursor predicate continues the
+ // (balance desc, id asc) order. Fetch one extra row to detect a next page.
+ const rows = await sql`
+ select id, wallet, balance::text as balance, first_seen, last_seen
+ from coin_holders
+ where coin_id = ${coinId}
+ and balance >= ${minBalance.toString()}::bigint
+ and (${maxBalance == null ? null : maxBalance.toString()}::bigint is null
+ or balance <= ${maxBalance == null ? null : maxBalance.toString()}::bigint)
+ and (${firstSeenBefore}::timestamptz is null or first_seen <= ${firstSeenBefore}::timestamptz)
+ and (${firstSeenAfter}::timestamptz is null or first_seen >= ${firstSeenAfter}::timestamptz)
+ and (${lastSeenBefore}::timestamptz is null or last_seen <= ${lastSeenBefore}::timestamptz)
+ and (${after ? after.balance : null}::bigint is null
+ or balance < ${after ? after.balance : null}::bigint
+ or (balance = ${after ? after.balance : null}::bigint and id > ${after ? after.id : null}::bigint))
+ order by balance desc, id asc
+ limit ${pageSize + 1}
+ `;
+
+ const hasMore = rows.length > pageSize;
+ const page = hasMore ? rows.slice(0, pageSize) : rows;
+ // Cursor tracks the last RAW row so pagination is unaffected by sampling.
+ const nextCursor = hasMore ? encodeCursor(page[page.length - 1]) : null;
+
+ let members = page.map((r) => ({
+ wallet: r.wallet,
+ balance: r.balance,
+ firstSeen: r.first_seen,
+ lastSeen: r.last_seen,
+ }));
+
+ const doSample = sample != null && sample > 0 && sample < 1;
+ if (doSample) {
+ const s = salt || coinId;
+ members = members.filter((m) => inSample(sampleBucket(m.wallet, cohortId, s), sample));
+ }
+
+ return { members, nextCursor, sampled: doSample };
+}
diff --git a/api/_lib/coin/cohorts.test.js b/api/_lib/coin/cohorts.test.js
new file mode 100644
index 000000000..9a581e116
--- /dev/null
+++ b/api/_lib/coin/cohorts.test.js
@@ -0,0 +1,110 @@
+import { describe, it, expect } from 'vitest';
+import {
+ COHORTS,
+ listCohorts,
+ isCohortId,
+ cohortSpec,
+ sampleBucket,
+ inSample,
+} from './cohorts.js';
+
+describe('cohort registry', () => {
+ it('exposes a stable set of cohort ids', () => {
+ expect(listCohorts().map((c) => c.id)).toEqual([
+ 'holders',
+ 'whales',
+ 'diamond-hands',
+ 'new-buyers',
+ 'exited',
+ ]);
+ });
+
+ it('every cohort declares name + description', () => {
+ for (const c of COHORTS) {
+ expect(c.name).toBeTruthy();
+ expect(c.description).toBeTruthy();
+ expect(Array.isArray(c.params)).toBe(true);
+ }
+ });
+
+ it('isCohortId rejects unknown ids', () => {
+ expect(isCohortId('whales')).toBe(true);
+ expect(isCohortId('bogus')).toBe(false);
+ expect(isCohortId('')).toBe(false);
+ });
+});
+
+describe('cohortSpec bounds', () => {
+ it('holders = any positive balance', () => {
+ const s = cohortSpec('holders');
+ expect(s.minBalance).toBe(1n);
+ expect(s.maxBalance).toBe(null);
+ });
+
+ it('exited = exactly zero balance', () => {
+ const s = cohortSpec('exited');
+ expect(s.minBalance).toBe(0n);
+ expect(s.maxBalance).toBe(0n);
+ });
+
+ it('whales clamps topPct into (0,1]', () => {
+ expect(cohortSpec('whales', { topPct: 0.05 }).topPct).toBe(0.05);
+ expect(cohortSpec('whales', { topPct: 5 }).topPct).toBe(1);
+ expect(cohortSpec('whales', { topPct: -1 }).topPct).toBeGreaterThan(0);
+ expect(cohortSpec('whales', {}).topPct).toBe(0.1); // default
+ });
+
+ it('new-buyers bounds first_seen from below (recent)', () => {
+ const s = cohortSpec('new-buyers', { windowDays: 7 });
+ expect(s.firstSeenAfter).toBeInstanceOf(Date);
+ expect(s.firstSeenBefore).toBe(null);
+ expect(s.firstSeenAfter.getTime()).toBeLessThanOrEqual(Date.now());
+ });
+
+ it('diamond-hands bounds first_seen from above (aged)', () => {
+ const s = cohortSpec('diamond-hands', { minHoldDays: 30 });
+ expect(s.firstSeenBefore).toBeInstanceOf(Date);
+ expect(s.firstSeenAfter).toBe(null);
+ });
+
+ it('throws on unknown cohort', () => {
+ expect(() => cohortSpec('nope')).toThrow();
+ });
+});
+
+describe('deterministic sampling', () => {
+ it('same (wallet, cohort, salt) always lands in the same bucket', () => {
+ const w = 'THREEsyntheticWallet1111111111111111111111';
+ expect(sampleBucket(w, 'whales', 'coin1')).toBe(sampleBucket(w, 'whales', 'coin1'));
+ });
+
+ it('salt changes the bucket (per-coin independence)', () => {
+ const w = 'THREEsyntheticWallet1111111111111111111111';
+ expect(sampleBucket(w, 'whales', 'coin1')).not.toBe(sampleBucket(w, 'whales', 'coin2'));
+ });
+
+ it('buckets stay in [0, 10000)', () => {
+ for (let i = 0; i < 1000; i++) {
+ const b = sampleBucket('wallet' + i, 'whales', 'salt');
+ expect(b).toBeGreaterThanOrEqual(0);
+ expect(b).toBeLessThan(10_000);
+ }
+ });
+
+ it('a fraction p keeps roughly p of a large population', () => {
+ let kept = 0;
+ const N = 5000;
+ for (let i = 0; i < N; i++) {
+ if (inSample(sampleBucket('wallet' + i, 'whales', 's'), 0.1)) kept++;
+ }
+ // ~500 expected; allow generous slack for hash variance.
+ expect(kept).toBeGreaterThan(400);
+ expect(kept).toBeLessThan(600);
+ });
+
+ it('inSample is monotonic in the fraction', () => {
+ const b = sampleBucket('somewallet', 'whales', 's');
+ if (inSample(b, 0.1)) expect(inSample(b, 0.5)).toBe(true);
+ if (!inSample(b, 0.5)) expect(inSample(b, 0.1)).toBe(false);
+ });
+});
diff --git a/api/_lib/coin/index.js b/api/_lib/coin/index.js
index c1b5d3d26..6ac410831 100644
--- a/api/_lib/coin/index.js
+++ b/api/_lib/coin/index.js
@@ -15,6 +15,16 @@ export {
persistHolderSnapshot,
readEligibleHolders,
} from './holders.js';
+export {
+ COHORTS,
+ listCohorts,
+ isCohortId,
+ cohortSpec,
+ cohortCounts,
+ queryCohort,
+ sampleBucket,
+ inSample,
+} from './cohorts.js';
export {
DRAND,
roundForTime,
diff --git a/api/_lib/coin/randomness.test.js b/api/_lib/coin/randomness.test.js
index f29650a8d..f562ce77f 100644
--- a/api/_lib/coin/randomness.test.js
+++ b/api/_lib/coin/randomness.test.js
@@ -6,11 +6,9 @@
// examples — example-based tests can't catch a 0.5% bias toward index N.
//
// NOTE: this file lives next to the source rather than under /tests/* because
-// the autonomy guardrails for the demo-coin work restrict edits to the coin
-// module. Vitest's include glob (vitest.config.js) does not currently pick
-// it up automatically — when graduating the demo to production, add
-// `api/_lib/coin/**/*.test.js` to the include[] array. Until then, run with:
-// npx vitest run api/_lib/coin/randomness.test.js
+// it co-locates with the coin module it covers. Vitest's include glob
+// (vitest.config.js) picks up `api/_lib/coin/**/*.test.js`, so `npm test` runs
+// it automatically alongside the rest of the suite.
import { describe, it, expect } from 'vitest';
import fc from 'fast-check';
diff --git a/api/_lib/migrations/2026-06-08-coin-holder-cohorts.sql b/api/_lib/migrations/2026-06-08-coin-holder-cohorts.sql
new file mode 100644
index 000000000..b4de39ad5
--- /dev/null
+++ b/api/_lib/migrations/2026-06-08-coin-holder-cohorts.sql
@@ -0,0 +1,22 @@
+-- Migration: indexes backing holder cohorts
+--
+-- Holder cohorts (api/_lib/coin/cohorts.js) are derived queries over the
+-- existing coin_holders set — no new table. They filter positive holders by
+-- first_seen (diamond hands / new buyers) and find exited wallets (balance = 0)
+-- by last_seen. The existing partial index coin_holders_coin_balance covers the
+-- balance-ordered whale/holder scans; these two add the time-bounded paths so
+-- cohort queries on large coins stay index-only instead of seq-scanning.
+--
+-- Idempotent: safe to re-run.
+
+begin;
+
+-- Diamond-hands / new-buyers: positive holders ordered/filtered by age.
+create index if not exists coin_holders_coin_first_seen
+ on coin_holders(coin_id, first_seen) where balance > 0;
+
+-- Exited (win-back): wallets sold to zero, found by when they left.
+create index if not exists coin_holders_coin_exited_last_seen
+ on coin_holders(coin_id, last_seen) where balance = 0;
+
+commit;
diff --git a/api/coin/[mint]/cohorts.js b/api/coin/[mint]/cohorts.js
new file mode 100644
index 000000000..0533c98f1
--- /dev/null
+++ b/api/coin/[mint]/cohorts.js
@@ -0,0 +1,122 @@
+// GET /api/coin/:mint/cohorts
+//
+// Holder cohorts for one agent token — named audience slices the /go bounty
+// board, coin communities, and holder worlds can target. Two shapes:
+//
+// …/cohorts → public: cohort definitions + live counts.
+// …/cohorts?cohort=whales&… → creator-only: paginated member export,
+// with optional deterministic sampling.
+//
+// The holder set is already public on-chain, but a turnkey, sampled wallet
+// export (built for airdrop/targeting) is gated to the coin's creator so it
+// can't be casually scraped for someone else's token. Definitions and counts
+// stay open so any surface can render the segmentation UI.
+
+import { sql } from '../../_lib/db.js';
+import { cors, json, error, method, wrap } from '../../_lib/http.js';
+import { isValidSolanaAddress } from '../../_lib/validate.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { loadCoinByMint, listCohorts, isCohortId, cohortCounts, queryCohort } from '../../_lib/coin/index.js';
+
+function mintFromReq(req) {
+ const m = req.query?.mint;
+ if (m) return m;
+ // Fallback for runtimes that don't populate req.query for nested routes.
+ const path = (req.url || '').split('?')[0].replace(/\/+$/, '');
+ const parts = path.split('/');
+ const i = parts.lastIndexOf('coin');
+ return i >= 0 && parts[i + 1] ? decodeURIComponent(parts[i + 1]) : null;
+}
+
+/** True if the session user owns this coin (creator wallet linked, or admin). */
+async function ownsCoin(user, coin) {
+ if (!user) return false;
+ if (user.is_admin) return true;
+ const creator = coin.creator_wallet;
+ if (!creator) return false;
+ if (user.wallet_address === creator) return true;
+ const rows = await sql`
+ select 1 from user_wallets
+ where user_id = ${user.id} and address = ${creator}
+ limit 1
+ `;
+ return rows.length > 0;
+}
+
+function numParam(url, key) {
+ const raw = url.searchParams.get(key);
+ if (raw == null) return undefined;
+ const n = parseFloat(raw);
+ return Number.isFinite(n) ? n : undefined;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res)) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const mint = mintFromReq(req);
+ if (!mint || !isValidSolanaAddress(mint)) {
+ return error(res, 400, 'bad_request', 'a valid token mint is required');
+ }
+
+ const coin = await loadCoinByMint(mint);
+ if (!coin) return error(res, 404, 'not_found', 'no launch found for this mint');
+
+ const url = new URL(req.url, 'http://localhost');
+ const cohortId = url.searchParams.get('cohort');
+
+ const params = {
+ topPct: numParam(url, 'topPct'),
+ minHoldDays: numParam(url, 'minHoldDays'),
+ windowDays: numParam(url, 'windowDays'),
+ idleDays: numParam(url, 'idleDays'),
+ };
+
+ // ── Overview: definitions + counts (public) ──────────────────────────────
+ if (!cohortId) {
+ const counts = await cohortCounts({ coinId: coin.id, params });
+ return json(res, 200, {
+ coin: { mint: coin.mint, symbol: coin.symbol, name: coin.name },
+ lastSnapshotAt: coin.last_snapshot_at || null,
+ cohorts: listCohorts().map((c) => ({ ...c, count: counts[c.id] ?? 0 })),
+ });
+ }
+
+ // ── Member export: creator-only ──────────────────────────────────────────
+ if (!isCohortId(cohortId)) {
+ return error(res, 404, 'not_found', `unknown cohort: ${cohortId}`);
+ }
+
+ const user = await getSessionUser(req, res).catch(() => null);
+ if (!user) return error(res, 401, 'unauthenticated', 'sign in to export cohort members');
+ if (!(await ownsCoin(user, coin))) {
+ return error(res, 403, 'forbidden', 'only the coin creator can export holder cohorts');
+ }
+
+ const limit = numParam(url, 'limit') ?? 200;
+ const cursor = url.searchParams.get('cursor') || undefined;
+ const sampleRaw = numParam(url, 'sample');
+ const sample = sampleRaw != null && sampleRaw > 0 && sampleRaw < 1 ? sampleRaw : undefined;
+ const salt = url.searchParams.get('salt') || undefined;
+
+ const { members, nextCursor, sampled } = await queryCohort({
+ coinId: coin.id,
+ cohortId,
+ params,
+ limit,
+ cursor,
+ sample,
+ salt,
+ });
+
+ return json(res, 200, {
+ coin: { mint: coin.mint, symbol: coin.symbol, name: coin.name },
+ cohort: cohortId,
+ sampled,
+ sample: sample ?? null,
+ count: members.length,
+ members,
+ nextCursor,
+ lastSnapshotAt: coin.last_snapshot_at || null,
+ });
+});
diff --git a/api/pump/curve.js b/api/pump/curve.js
index 79de8f814..748677d27 100644
--- a/api/pump/curve.js
+++ b/api/pump/curve.js
@@ -12,6 +12,23 @@
import { cors, json, method, wrap, error } from '../_lib/http.js';
import { rpcFallbackFromEnv, getBondingCurveState, getTokenPrice, getGraduationProgress } from '../_lib/solana/index.js';
+// Mints that can never carry a pump.fun bonding curve. These are coin-agnostic
+// settlement / native tokens, listed only so we can *exclude* them from curve
+// lookups — never to promote them. (USDC mainnet+devnet, wrapped SOL, USDT.)
+const NON_CURVE_MINTS = new Set([
+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC (mainnet)
+ '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', // USDC (devnet)
+ 'So11111111111111111111111111111111111111112', // wrapped SOL
+ 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB', // USDT
+]);
+
+// Every pump.fun mint keypair is ground to end in the literal suffix "pump". A
+// mint that does not end in "pump" (or that is a known settlement token) has no
+// bonding curve and never will — so we can reject it without touching RPC.
+function isPumpMint(mint) {
+ return typeof mint === 'string' && mint.endsWith('pump') && !NON_CURVE_MINTS.has(mint);
+}
+
async function jupiterPriceFallback(mint) {
try {
const r = await fetch(`https://lite-api.jup.ag/price/v3?ids=${mint}`);
@@ -50,6 +67,21 @@ export default wrap(async (req, res) => {
return error(res, 400, 'bad_mint', 'mint query param must be a base58 Solana address');
}
+ // Short-circuit mints that cannot have a bonding curve (settlement tokens,
+ // non-"pump" mints) *before* any Solana RPC call. This kills the 404 + RPC-429
+ // storm a misconfigured (e.g. USDC) widget mount would otherwise trigger: no
+ // cold start, no RPC reads, no warning spam. The negative-cache header lets the
+ // CDN edge serve repeat probes so the function isn't hit at all. The client's
+ // existing stop-on-404 path fires on this exactly as it does for a real 404.
+ if (!isPumpMint(mint)) {
+ return json(
+ res,
+ 404,
+ { error: 'not_a_pump_mint', error_description: 'mint has no pump.fun bonding curve' },
+ { 'cache-control': 'public, s-maxage=300, max-age=300' },
+ );
+ }
+
const rpc = rpcFallbackFromEnv({ network });
const result = await rpc.withFallback(async (connection) => {
const [curve, price, grad] = await Promise.all([
diff --git a/src/widgets/bonding-curve.js b/src/widgets/bonding-curve.js
index fe7e9d49d..da1d34a88 100644
--- a/src/widgets/bonding-curve.js
+++ b/src/widgets/bonding-curve.js
@@ -25,6 +25,24 @@
const LAMPORTS_PER_SOL = 1_000_000_000;
const SOL_MINT = 'So11111111111111111111111111111111111111112';
+// Settlement / native tokens that can never carry a pump.fun bonding curve.
+// Listed only to *exclude* them from curve lookups — never to promote them.
+const NON_CURVE_MINTS = new Set([
+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC (mainnet)
+ '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', // USDC (devnet)
+ SOL_MINT, // wrapped SOL
+ 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB', // USDT
+]);
+
+// Every pump.fun mint is ground to end in the literal suffix "pump". A mint that
+// doesn't end in "pump" (or that is a known settlement token) has no bonding
+// curve — so the widget can skip the network request entirely and show its empty
+// state, never contributing to the /api/pump/curve 404 storm on a misconfigured
+// (e.g. USDC) mount.
+export function isPumpMint(mint) {
+ return typeof mint === 'string' && mint.endsWith('pump') && !NON_CURVE_MINTS.has(mint);
+}
+
// SVG geometry. viewBox is fixed; the element scales to its container.
const VB = Object.freeze({ w: 320, h: 150, pl: 14, pr: 14, pt: 18, pb: 18 });
const CURVE_EXP = 1.85; // convex/accelerating — mirrors the pump.fun price curve
@@ -421,6 +439,10 @@ export function mountBondingCurve(rootEl, opts = {}) {
injectStyles(doc);
const mint = String(opts.mint || '').trim();
+ // A mint that can't have a bonding curve (settlement token / non-"pump" mint)
+ // is treated like no mint at all: paint the empty state, never poll. This stops
+ // a misconfigured mount from firing /api/pump/curve requests that can only 404.
+ const pollable = Boolean(mint) && isPumpMint(mint);
const network = opts.network === 'devnet' ? 'devnet' : 'mainnet';
const refreshMs = Math.max(5_000, Number(opts.refreshMs) || 15_000);
const showUsd = opts.showUsd !== false;
@@ -437,14 +459,20 @@ export function mountBondingCurve(rootEl, opts = {}) {
let timer = null;
let raf = null;
let displayedProgress = 0; // currently-rendered marker/percent position
- let view = { status: mint ? 'loading' : 'empty', progress: 0 };
+ let view = { status: pollable ? 'loading' : 'empty', progress: 0 };
// Initial paint — shell + empty/loading state.
wrap.innerHTML = renderCardShell(view, { mint, network, showPoweredBy: opts.showPoweredBy });
const card = wrap.querySelector('.bcw-card');
- if (mint) card.classList.add('is-loading');
+ if (pollable) card.classList.add('is-loading');
const els = grab(wrap);
- if (!mint) applyEmptyState(card, els);
+ if (!pollable) {
+ applyEmptyState(
+ card,
+ els,
+ mint ? 'No bonding curve — this isn’t a pump.fun mint.' : undefined,
+ );
+ }
paintGeometry(els, 0);
function setText(el, text) {
@@ -493,7 +521,7 @@ export function mountBondingCurve(rootEl, opts = {}) {
}
async function poll() {
- if (destroyed || stopped || !mint) return;
+ if (destroyed || stopped || !pollable) return;
try {
const [resp, solUsd] = await Promise.all([
fetch(`/api/pump/curve?mint=${encodeURIComponent(mint)}&network=${network}`),
@@ -536,8 +564,10 @@ export function mountBondingCurve(rootEl, opts = {}) {
}
}
- poll();
- if (!stopped) timer = setInterval(poll, refreshMs);
+ if (pollable) {
+ poll();
+ if (!stopped) timer = setInterval(poll, refreshMs);
+ }
return {
destroy() {
diff --git a/src/widgets/bonding-curve.test.js b/src/widgets/bonding-curve.test.js
index cb8361998..689895acc 100644
--- a/src/widgets/bonding-curve.test.js
+++ b/src/widgets/bonding-curve.test.js
@@ -12,6 +12,7 @@ import {
areaPathFor,
computeView,
renderCardShell,
+ isPumpMint,
} from './bonding-curve.js';
const LAMPORTS = 1_000_000_000;
@@ -89,6 +90,24 @@ describe('shortMint', () => {
});
});
+describe('isPumpMint', () => {
+ it('accepts mints ending in the pump suffix', () => {
+ expect(isPumpMint('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump')).toBe(true);
+ });
+ it('rejects settlement / native tokens', () => {
+ expect(isPumpMint('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v')).toBe(false); // USDC
+ expect(isPumpMint('So11111111111111111111111111111111111111112')).toBe(false); // wSOL
+ expect(isPumpMint('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB')).toBe(false); // USDT
+ expect(isPumpMint('4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU')).toBe(false); // USDC devnet
+ });
+ it('rejects any mint that does not end in "pump"', () => {
+ expect(isPumpMint('So11111111111111111111111111111111111111112')).toBe(false);
+ expect(isPumpMint('')).toBe(false);
+ expect(isPumpMint(null)).toBe(false);
+ expect(isPumpMint(undefined)).toBe(false);
+ });
+});
+
describe('curve geometry', () => {
it('curveValue is 0 at t=0, 1 at t=1, and monotonically increasing', () => {
expect(curveValue(0)).toBe(0);
diff --git a/tasks/pumpfun-upstream/03-segments-findings.md b/tasks/pumpfun-upstream/03-segments-findings.md
index 1f3ac048d..7b497bc6e 100644
--- a/tasks/pumpfun-upstream/03-segments-findings.md
+++ b/tasks/pumpfun-upstream/03-segments-findings.md
@@ -33,4 +33,15 @@ Pre-release and effectively private: unpublished on npm, `access: restricted` (i
**Not relevant — do not adopt, do not watch for an npm release.** This is internal growth tooling Pump.fun is unlikely to expose, and the model (read their warehouse cohorts) has no public surface we could call.
-**Optional, separate idea (our own build, not this SDK):** the *pattern* — defining named, versioned cohorts and sampling them deterministically — could be worth borrowing for $THREE community features (e.g. cohorting $THREE holders for the `/go` bounty board or `coin-communities.js`: "top traders," "diamond hands," "new this week"). If we ever want that, we'd build it natively against our own Solana holder data and `imurmurhash`-style bucketing — no need to depend on this repo. Track that under a fresh task only if product demand appears; it is not a reason to adopt `pump-segments-sdk`.
+## Addendum — re-evaluated for agent-token holder segmentation
+
+Raised use case: we let users launch tokens for their agents, so segment *those token holders* into cohorts (whales, diamond hands, new buyers, dormant) and wire them into the `/go` bounty board, communities, and holder worlds.
+
+**The product instinct is right; this SDK is the wrong vehicle.** Verified against our actual code:
+
+- **We already own the data plane this SDK lacks.** [`api/_lib/coin/holders.js`](../../api/_lib/coin/holders.js) snapshots every agent-token holder on-chain via Helius `getTokenAccounts` (Token-2022) into a **Neon Postgres** `coin_holders` table — `persistHolderSnapshot({coinId, balances})`, `readEligibleHolders({coinId, minBalance})`. [`api/_lib/holder-pass.js`](../../api/_lib/holder-pass.js) already does USD-tiered gating. The segments-sdk computes *none* of this — it is a pure read proxy over a table someone else populates.
+- **Datastore mismatch.** The SDK is hardwired to **DynamoDB** (`@aws-sdk/lib-dynamodb`). Our store is Neon Postgres (`sql` tagged template). Adopting it means standing up a second datastore for zero benefit.
+- **Its real value is a backend we can't touch.** The "segments" are materialized by Pump.fun's private Lambda from their internal `pump-data-production` BigQuery, keyed by *pump.fun app `user_id`* — not Solana wallets, not our mints. Even pointed at our own DynamoDB table, every method returns empty until we build the entire cohort-materializer ourselves — which we already 80% have in `holders.js`.
+- **Reusable surface ≈ 40 lines.** Only the base64 cursor pagination and the `imurmurhash` deterministic sampling (`bucket = hash % 10000`) are worth borrowing as a *pattern*. Trivial to write natively against `coin_holders`.
+
+**Revised recommendation:** **Do not adopt the SDK** (unchanged), but **do build native agent-token holder cohorts** on top of `coin_holders` — a small, high-leverage feature. Sketch: a `coin_holder_cohorts` definition (SQL predicate over `coin_holders` joined with priced balances), a refresh that runs alongside the existing snapshot, deterministic sampling for "pick N% of whales," and exports the bounty board / communities can target. This is our build, against our data — borrow the *idea*, not the dependency.
diff --git a/tasks/week-2026-06-08/A1-pump-curve-404-storm.md b/tasks/week-2026-06-08/A1-pump-curve-404-storm.md
deleted file mode 100644
index cb541c1ca..000000000
--- a/tasks/week-2026-06-08/A1-pump-curve-404-storm.md
+++ /dev/null
@@ -1,108 +0,0 @@
-# A1 — Stop the `/api/pump/curve` 404 + Solana-RPC storm
-
-**Track:** A — production fire · **Priority:** P0 · **Effort:** 2–3h · **Depends on:** none
-
-## Context (evidence)
-
-In the last 24h of production logs (`docs/3dagent-log-export-2026-06-07T03-58-54.json`):
-
-- **1,716 × HTTP 404** on `GET /api/pump/curve` — **1,712 of them for the exact same mint**:
- `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` (this is **USDC**, which has no pump.fun bonding
- curve and never will).
-- This single endpoint is the platform's **heaviest function** (567 MB / 4096 MB per call).
-- Each call fires **3 Solana RPC reads that 429** — `[sdk-bridge] getBondingCurveState/getGraduationProgress/getTokenPrice failed: Account does not exist or has no data` — which together are the bulk of the 1,408 `level:warning` lines in the export.
-
-### Root cause (already investigated — do not re-investigate, verify)
-
-The polling widget `src/widgets/bonding-curve.js` (`poll()` at lines 495–540) **already self-terminates
-on a 404** (`stopPolling()` at line 514). So this is **not** one runaway poller. It is **~850 fresh
-mounts/day of a bonding-curve widget that is misconfigured with the USDC mint**, each firing ~2
-curve calls before stopping. The comment at line 507 even documents the prior incident:
-"exactly what turned a misconfigured demo into a 404 storm." The stop-on-404 patch treated the
-symptom; the **USDC misconfiguration that re-triggers on every mount still exists**.
-
-## What to do
-
-Two layers. **Layer 1 is the robust, caller-agnostic fix and is mandatory. Layer 2 removes the
-trigger.**
-
-### Layer 1 — Server-side short-circuit (mandatory)
-
-In the curve handler — `api/pump/[action].js`, the `handleCurve` function (the branch that serves
-`/api/pump/curve`) — return early for any mint that **cannot** have a pump.fun bonding curve,
-**before** issuing any Solana RPC call:
-
-- A pump.fun mint address ends in the literal suffix `pump`. Any mint that does **not** end in
- `pump` is not a pump token.
-- Additionally short-circuit a small known-non-curve set: USDC
- (`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`), wrapped SOL
- (`So11111111111111111111111111111111111111112`), USDC-devnet
- (whatever `SOLANA_USDC_MINT_DEVNET` resolves to in `api/_lib/`), and USDT
- (`Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB`).
-- For those, respond **without touching RPC**. Return `404` with a clear JSON body
- (e.g. `{ error: 'not_a_pump_mint', message: 'mint has no pump.fun bonding curve' }`) so the
- client's existing stop-on-404 path fires. Keep the response shape consistent with the current
- 404 the handler already returns.
-- Add a short negative-cache header (e.g. `Cache-Control: public, s-maxage=300`) on this
- short-circuit response so repeated probes from scanners are served from the CDN edge, not the
- function.
-
-This caps the blast radius regardless of which client misconfigures: no 567 MB cold start, no
-RPC 429s, no warning spam.
-
-> Do **not** define the non-pump suffix check as the only gate if the codebase already has a
-> canonical "is this a pump mint" helper — search `api/_lib/` (e.g. `pump.js`) first and reuse it.
-> If none exists, add a tiny `isPumpMint(mint)` helper next to the handler and use it.
-
-### Layer 2 — Fix the USDC-misconfigured mount (remove the trigger)
-
-Find the client that mounts a bonding-curve widget with the USDC mint and correct it.
-
-- The only direct callers of `/api/pump/curve` are `src/widgets/bonding-curve.js` (the poller) and
- `src/communities.js` (one-shot fetch). Start there.
-- Trace what `mint` value is passed in. The widget is mounted via `mountBondingCurve(...)` and via
- the generic `<three-ws-widget type="bonding-curve" mint="…">` custom element (registered in
- `src/widgets/kol-trades.js`, dispatched from `src/app.js`). Check `src/widget-types.js` for a
- default mint.
-- The correct $THREE mint is `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`. If a curve widget is
- meant to show $THREE but is wired to USDC, fix the wiring. If a widget is being mounted for a
- settlement token (USDC) where a bonding curve makes no sense, **don't mount the curve widget
- there at all** — guard the mount with the same non-pump-mint check.
-
-If, after tracing, the USDC mount turns out to come from an external embed you don't control,
-Layer 1 still fully resolves the production impact — document that finding in your commit message
-and the negative-cache header becomes the durable mitigation.
-
-## Acceptance criteria
-
-- [ ] `GET /api/pump/curve?mint=<USDC>` returns its 404 **without any Solana RPC call** (no
- `[sdk-bridge] … failed` warnings emitted for that request).
-- [ ] `GET /api/pump/curve?mint=<a real pump mint ending in "pump">` still returns live curve data
- exactly as before (no regression).
-- [ ] The short-circuit response carries a negative-cache header.
-- [ ] The USDC-misconfigured mount is located and corrected, **or** documented as external with
- justification.
-- [ ] No new console warnings/errors from your changed code.
-
-## Verification
-
-1. Run the unit tests touching the curve widget: `npx vitest run src/widgets/bonding-curve.test.js`.
-2. `npm run dev` (port 3000). In the browser, exercise the page(s) that previously mounted the
- curve widget; confirm the Network tab shows **no** `/api/pump/curve?mint=<USDC>` requests, and
- that a real pump token's curve still renders.
-3. Hit the endpoint directly for both a USDC mint and a real pump mint; confirm correct status +
- body + that the USDC one is fast (no RPC latency).
-
-## Rules
-
-Obey [CLAUDE.md](../../CLAUDE.md). No mocks, no fake data. Never hardcode or surface a non-$THREE
-mint as a *promoted* token — the mint constants here are coin-agnostic settlement plumbing (the
-allowed mechanical exception), used only to *exclude* them from curve lookups.
-
-## Completion protocol
-
-1. Re-read your diff (`git diff`) and confirm every line is justified.
-2. Delete this file: `tasks/week-2026-06-08/A1-pump-curve-404-storm.md`.
-3. Commit your code change **and** this file's deletion together, e.g.:
- `git add -A && git commit -m "fix(pump): short-circuit non-pump mints in /api/pump/curve to kill 404+RPC storm; close A1"`
-4. Do **not** push — the human controls pushes.
diff --git a/vitest.config.js b/vitest.config.js
index b7556873e..acf73d04b 100644
--- a/vitest.config.js
+++ b/vitest.config.js
@@ -22,7 +22,12 @@ const MAX_FORKS = _cpus <= 3 ? 2 : Math.min(6, _cpus);
export default defineConfig({
test: {
environment: 'node',
- include: ['tests/**/*.test.js', 'tests/**/*.test.mjs', 'src/**/*.test.js'],
+ include: [
+ 'tests/**/*.test.js',
+ 'tests/**/*.test.mjs',
+ 'src/**/*.test.js',
+ 'api/_lib/coin/**/*.test.js',
+ ],
testTimeout: 45_000,
hookTimeout: 45_000,
// Vitest 4 hoisted poolOptions.forks.* to top-level.