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(earnings): read creator fees from pump.fun's live fees API after it retired the v1 creator routes
nirholas233305db1eef
diff --git a/api/_lib/creator-earnings-snapshot.js b/api/_lib/creator-earnings-snapshot.jsindex f0a173444..2f20b9c07 100644--- a/api/_lib/creator-earnings-snapshot.js+++ b/api/_lib/creator-earnings-snapshot.js@@ -94,10 +94,11 @@ async function storeBuckets(creator, interval, buckets) {for (const b of buckets) {await sql`insert into creator_fee_buckets (creator, bucket_interval, bucket_start, fee_lamports, num_trades, refreshed_at)- values (${creator}, ${interval}, ${b.bucket_start}, ${big(b.fee_lamports)}, ${b.num_trades}, now())+ values (${creator}, ${interval}, ${b.bucket_start}, ${big(b.fee_lamports)}, ${b.num_trades ?? 0}, now())on conflict (creator, bucket_interval, bucket_start) do update setfee_lamports = excluded.fee_lamports,- num_trades = excluded.num_trades,+ -- pump.fun stopped reporting trade counts; keep a count it gave earlier.+ num_trades = coalesce(${b.num_trades}, creator_fee_buckets.num_trades),refreshed_at = now()`;}diff --git a/api/_lib/pump-creator-fees.js b/api/_lib/pump-creator-fees.jsindex d3a143ed1..5bb653b25 100644--- a/api/_lib/pump-creator-fees.js+++ b/api/_lib/pump-creator-fees.js@@ -11,11 +11,15 @@// metadata `creator` field is NOT used: for a gasless launch it// names the sponsor that paid the transaction, not the wallet// that collects the fees.-// earned pump.fun's creator-fee index, GET swap-api.pump.fun-// /v1/creators/<wallet>/fees/total (lifetime, lamports) and-// /v1/creators/<wallet>/fees?interval=1d|30m (bucketed). It is-// keyed by creator WALLET, so one wallet that created several-// coins reports one combined figure. The fee-sharing totals+// earned pump.fun's creator-fee index, GET frontend-api-v3.pump.fun+// /fees/creator/<wallet>?interval=1d|30m&period=30d|7d: the+// lifetime figure per quote asset (`earned`) plus a bucketed+// series. When that read fails, the lifetime figure falls back to+// swap-api.pump.fun /v2/creators/<wallet>/fees/total. pump.fun+// retired the /v1/creators routes both used before (404 since+// early October 2026). The index is keyed by creator WALLET, so+// one wallet that created several coins reports one combined+// figure. The fee-sharing totals// endpoint the coin page used before answers 0 for every coin// that never set up a sharing config, which is every coin// three.ws has launched, so the page never showed a real figure.@@ -34,9 +38,11 @@import { PublicKey } from '@solana/web3.js';import { withBreaker } from './resilience.js';-import { pumpFetchJson, PUMP_SWAP_BASE } from './pump-feed-fetch.js';+import { pumpFetchJson, PUMP_FRONTEND_BASE, PUMP_SWAP_BASE } from './pump-feed-fetch.js';export const CREATOR_FEES_BREAKER = 'pumpfun:creator-fees';+// The fallback rung gets its own breaker so a sick primary cannot open it.+export const CREATOR_FEES_FALLBACK_BREAKER = 'pumpfun:creator-fees-swap-v2';const BREAKER_OPTS = { threshold: 3, halfOpenAfterMs: 30_000 };const TIMEOUT_MS = 6000;@@ -51,16 +57,21 @@ function toLamports(v) {}}+// pump.fun names the SOL quote by the wrapped-SOL mint on /fees/creator and by+// the system program id on the swap-api totals.+const SOL_QUOTES = new Set(['So11111111111111111111111111111111111111112', '11111111111111111111111111111111']);+/**- * Run one pump.fun read behind the shared breaker. `fn` throws on an unhealthy- * upstream; the breaker turns that (or an open circuit) into `{ ok: false }`.+ * Run one pump.fun read behind a breaker. `fn` throws on an unhealthy upstream;+ * the breaker turns that (or an open circuit) into `{ ok: false }`.* @template T* @param {() => Promise<T>} fn+ * @param {string} [breaker]* @returns {Promise<{ ok: true, value: T } | { ok: false, error: string }>}*/-async function guarded(fn) {+async function guarded(fn, breaker = CREATOR_FEES_BREAKER) {return withBreaker(- CREATOR_FEES_BREAKER,+ breaker,async () => ({ ok: /** @type {const} */ (true), value: await fn() }),{...BREAKER_OPTS,@@ -72,49 +83,77 @@ async function guarded(fn) {);}+/**+ * GET /fees/creator/<wallet>: lifetime earnings per quote plus one series.+ * Throws on anything but a well-formed answer.+ * @param {string} wallet+ * @param {'1d'|'30m'} interval+ */+async function fetchCreatorEarnings(wallet, interval) {+ const period = interval === '30m' ? '7d' : '30d';+ const r = await pumpFetchJson(+ `${PUMP_FRONTEND_BASE}/fees/creator/${encodeURIComponent(wallet)}?interval=${interval}&period=${period}`,+ { timeoutMs: TIMEOUT_MS },+ );+ if (!r.ok) throw new Error(`pump.fun creator fees ${r.status}`);+ if (!Array.isArray(r.body?.earned) || !Array.isArray(r.body?.series)) {+ throw new Error('pump.fun creator fees: no earned/series in response');+ }+ return r.body;+}++/**+ * The SOL leg of a list of per-quote amounts, in lamports. No SOL leg means+ * nothing was earned in SOL: zero, not unknown.+ * @param {Array<{ quote?: { address?: string }, amount?: { raw?: string } }>} legs+ */+function solLamports(legs) {+ const leg = legs.find((l) => SOL_QUOTES.has(String(l?.quote?.address || '')));+ if (!leg) return 0n;+ const lamports = toLamports(leg.amount?.raw);+ if (lamports == null) throw new Error('pump.fun creator fees: SOL leg without an amount');+ return lamports;+}+/*** Lifetime creator fees earned by one wallet, in lamports, across every coin* that wallet created.* @param {string} wallet*/export async function fetchCreatorFeeTotal(wallet) {- return guarded(async () => {+ const primary = await guarded(async () => solLamports((await fetchCreatorEarnings(wallet, '1d')).earned));+ if (primary.ok) return primary;+ const fallback = await guarded(async () => {const r = await pumpFetchJson(- `${PUMP_SWAP_BASE}/v1/creators/${encodeURIComponent(wallet)}/fees/total`,+ `${PUMP_SWAP_BASE}/v2/creators/${encodeURIComponent(wallet)}/fees/total`,{ timeoutMs: TIMEOUT_MS },);- if (!r.ok) throw new Error(`pump.fun creator fees ${r.status}`);- const lamports = toLamports(r.body?.totalFees);- if (lamports == null) throw new Error('pump.fun creator fees: no totalFees in response');- return lamports;- });+ if (!r.ok) throw new Error(`pump.fun creator fee totals ${r.status}`);+ const legs = r.body?.totalFeesByQuoteMint;+ if (!Array.isArray(legs)) throw new Error('pump.fun creator fee totals: no totalFeesByQuoteMint');+ return solLamports(legs.map((l) => ({ quote: { address: l?.quoteMintAddress }, amount: { raw: l?.totalFeesAtomic } })));+ }, CREATOR_FEES_FALLBACK_BREAKER);+ return fallback.ok ? fallback : { ok: false, error: `${primary.error}; fallback: ${fallback.error}` };}/**- * Bucketed creator fees for one wallet. pump.fun answers the most recent ~100- * buckets: `1d` spans about 100 days, `30m` about the last 50 hours. Zero- * buckets are dropped; they add nothing to a windowed sum.+ * Bucketed creator fees for one wallet, SOL leg only. pump.fun serves `1d`+ * buckets for the last 30 days and `30m` buckets for the last 7. It no longer+ * reports a trade count per bucket, so `num_trades` is null. Zero buckets are+ * dropped; they add nothing to a windowed sum.* @param {string} wallet* @param {'1d'|'30m'} interval*/export async function fetchCreatorFeeBuckets(wallet, interval) {return guarded(async () => {- const r = await pumpFetchJson(- `${PUMP_SWAP_BASE}/v1/creators/${encodeURIComponent(wallet)}/fees?interval=${interval}`,- { timeoutMs: TIMEOUT_MS },- );- if (!r.ok) throw new Error(`pump.fun creator fee buckets ${r.status}`);- if (!Array.isArray(r.body)) throw new Error('pump.fun creator fee buckets: not an array');+ const body = await fetchCreatorEarnings(wallet, interval);const out = [];- for (const b of r.body) {- const fee = toLamports(b?.creatorFee);- const at = Date.parse(b?.bucket);- if (fee == null || !Number.isFinite(at) || fee === 0n) continue;- out.push({- bucket_start: new Date(at).toISOString(),- fee_lamports: fee,- num_trades: Number.isFinite(Number(b?.numTrades)) ? Number(b.numTrades) : 0,- });+ for (const b of body.series) {+ const at = Number(b?.bucketStart);+ if (!Number.isFinite(at) || !Array.isArray(b?.byQuote)) continue;+ const fee = solLamports(b.byQuote);+ if (fee === 0n) continue;+ out.push({ bucket_start: new Date(at).toISOString(), fee_lamports: fee, num_trades: null });}return out;});diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 04a3abeba..65e7d4e62 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -6902,7 +6902,7 @@ Cached 5 minutes in the shared cache and at the CDN| `marketplace_volume_three` | three | price of those sales paid in $THREE, in whole tokens || `marketplace_volume_usd` | usd | price of those sales paid in USDC || `hire_volume_usd` | usd | completed `agent_hires`, read through the same helper as `/api/agent-economy/volume` |-| `creator_fees` | sol | lifetime creator fees of agents' own custodial wallets from the `agent_coin_earnings` snapshot (same counting rule as `/api/agents/:id/earnings`); daily series from the fee index's daily buckets, about 100 days deep |+| `creator_fees` | sol | lifetime creator fees of agents' own custodial wallets from the `agent_coin_earnings` snapshot (same counting rule as `/api/agents/:id/earnings`); daily series from the fee index's daily buckets, stored as each snapshot reads them (pump.fun serves the last 30 days per read, so older days come from earlier snapshots) |`total` is all time; `window_total` is the sum of `daily`; `daily` has oneentry per UTC day from `from` to `to`, zeros included. For `window=all`,diff --git a/tests/pump-creator-fees.test.js b/tests/pump-creator-fees.test.jsindex 74874a5f9..e1dcf3b54 100644--- a/tests/pump-creator-fees.test.js+++ b/tests/pump-creator-fees.test.js@@ -1,7 +1,8 @@// api/_lib/pump-creator-fees.js: the pump.fun creator-fee reads behind the-// earnings snapshot and the coin page. Payload shapes are the ones-// swap-api.pump.fun returns for /v1/creators/<wallet>/fees/total and-// /v1/creators/<wallet>/fees?interval=..., captured 2026-09-30.+// earnings snapshot and the coin page. Payload shapes are the ones pump.fun+// returns for frontend-api-v3 /fees/creator/<wallet> and the swap-api fallback+// /v2/creators/<wallet>/fees/total, captured 2026-10-08 after pump.fun retired+// the /v1/creators routes.import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';@@ -9,8 +10,20 @@ const { fetchCreatorFeeTotal, fetchCreatorFeeBuckets } = await import('../api/_lconst { _resetBreakers } = await import('../api/_lib/resilience.js');const WALLET = 'THREEsynthetic11111111111111111111111111111';+const WSOL = 'So11111111111111111111111111111111111111112';+const SOLANA = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';const originalFetch = global.fetch;const reply = (status, body) => ({ ok: status >= 200 && status < 300, status, headers: new Headers(), json: async () => body });+const solLeg = (raw) => ({ quote: { chainId: SOLANA, address: WSOL }, amount: { raw, decimals: 9 }, usd: '1.0' });+const earnings = ({ earned = [solLeg('73148608')], series = [] } = {}) => ({+ creator: WALLET,+ interval: '1d',+ period: '30d',+ earned,+ isClaimable: true,+ claimable: { usd: '0.5', native: '0.004', nativeAsset: { chainId: SOLANA, address: '', symbol: 'SOL' } },+ series,+});beforeEach(() => _resetBreakers());afterEach(() => {@@ -18,49 +31,66 @@ afterEach(() => {});describe('fetchCreatorFeeTotal', () => {- it('reads lifetime lamports from totalFees', async () => {+ it('reads lifetime lamports from the SOL leg of /fees/creator', async () => {global.fetch = vi.fn(async (url) => {- expect(String(url)).toContain(`/v1/creators/${WALLET}/fees/total`);- return reply(200, { totalFees: '73148608', totalFeesSOL: '0.073148608' });+ expect(String(url)).toContain(`/fees/creator/${WALLET}?interval=1d&period=30d`);+ return reply(200, earnings());});- const r = await fetchCreatorFeeTotal(WALLET);- expect(r).toEqual({ ok: true, value: 73148608n });+ expect(await fetchCreatorFeeTotal(WALLET)).toEqual({ ok: true, value: 73148608n });});- it('treats a wallet with no fees as a healthy zero, not a failure', async () => {- global.fetch = vi.fn(async () => reply(200, { totalFees: '0', totalFeesSOL: '0' }));+ it('treats a wallet with no SOL earnings as a healthy zero, not a failure', async () => {+ global.fetch = vi.fn(async () => reply(200, earnings({ earned: [] })));expect(await fetchCreatorFeeTotal(WALLET)).toEqual({ ok: true, value: 0n });});- it('reports an upstream failure so the caller keeps its last good figure', async () => {+ it('falls back to the swap-api v2 totals when /fees/creator fails', async () => {+ global.fetch = vi.fn(async (url) => {+ if (String(url).includes('/fees/creator/')) return reply(503, { degraded_lanes: ['trade_api.get_fees'] });+ expect(String(url)).toContain(`/v2/creators/${WALLET}/fees/total`);+ return reply(200, {+ totalFeesSOL: '0.004610377',+ totalFeesByQuoteMint: [+ { quoteMintAddress: '11111111111111111111111111111111', totalFeesAtomic: '4610377', totalFeesQuote: '0.004610377' },+ ],+ });+ });+ expect(await fetchCreatorFeeTotal(WALLET)).toEqual({ ok: true, value: 4610377n });+ });++ it('reports a failure on both rungs so the caller keeps its last good figure', async () => {global.fetch = vi.fn(async () => reply(404, { statusCode: 404 }));const r = await fetchCreatorFeeTotal(WALLET);expect(r.ok).toBe(false);- expect(r.error).toMatch(/404/);+ expect(r.error).toMatch(/404.*fallback.*404/);});});describe('fetchCreatorFeeBuckets', () => {- it('keeps only non-zero buckets, as lamports with ISO starts', async () => {+ it('keeps only non-zero SOL buckets, as lamports with ISO starts', async () => {global.fetch = vi.fn(async (url) => {- expect(String(url)).toContain('interval=1d');- return reply(200, [- { bucket: '2026-07-25T00:00:00.000Z', creatorFee: '0', creatorFeeSOL: '0', numTrades: 0 },- { bucket: '2026-07-26T00:00:00.000Z', creatorFee: '73094972', creatorFeeSOL: '0.073094972', numTrades: 65 },- { bucket: '2026-07-27T00:00:00.000Z', creatorFee: '53636', creatorFeeSOL: '0.000053636', numTrades: 1 },- ]);+ expect(String(url)).toContain('interval=30m&period=7d');+ return reply(+ 200,+ earnings({+ series: [+ { bucketStart: Date.parse('2026-10-07T12:00:00.000Z'), earned: { native: '0.000404407' }, byQuote: [solLeg('404407')] },+ { bucketStart: Date.parse('2026-10-07T11:30:00.000Z'), earned: { native: '0' }, byQuote: [solLeg('0')] },+ { bucketStart: Date.parse('2026-10-07T11:00:00.000Z'), earned: { native: '0' }, byQuote: [] },+ ],+ }),+ );+ });+ const r = await fetchCreatorFeeBuckets(WALLET, '30m');+ expect(r).toEqual({+ ok: true,+ value: [{ bucket_start: '2026-10-07T12:00:00.000Z', fee_lamports: 404407n, num_trades: null }],});- const r = await fetchCreatorFeeBuckets(WALLET, '1d');- expect(r.ok).toBe(true);- expect(r.value).toEqual([- { bucket_start: '2026-07-26T00:00:00.000Z', fee_lamports: 73094972n, num_trades: 65 },- { bucket_start: '2026-07-27T00:00:00.000Z', fee_lamports: 53636n, num_trades: 1 },- ]);});- it('fails on a body that is not a bucket list', async () => {+ it('fails on a body without a series', async () => {global.fetch = vi.fn(async () => reply(200, { statusCode: 400, message: 'interval must be one of' }));- const r = await fetchCreatorFeeBuckets(WALLET, '30m');+ const r = await fetchCreatorFeeBuckets(WALLET, '1d');expect(r.ok).toBe(false);});});