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
feat(earnings): show what each agent earned from its coins on the profile, avatar page, coin page and over MCP
nirholas3581568ff4d0
diff --git a/api/_lib/agent-earnings.js b/api/_lib/agent-earnings.jsnew file mode 100644index 000000000..9568ecba3--- /dev/null+++ b/api/_lib/agent-earnings.js@@ -0,0 +1,465 @@+// @ts-check+// Agent earnings read model: the single computation behind+// GET /api/agents/:id/earnings and GET /api/leaderboard/earnings, so an agent's+// own page and its leaderboard row can never disagree.+//+// An agent earns two ways, and both are counted here:+//+// creator fees pump.fun creator fees on the coins it launched, from the+// agent_coin_earnings snapshot (api/_lib/creator-earnings-snapshot.js).+// pump.fun reports these per creator WALLET, so a wallet's+// figure counts toward an agent only when that wallet is the+// agent's own custodial wallet (agent_identities.meta.solana_address)+// and no other agent's coin on file shares it. A coin whose+// fees go to any other wallet (an owner's connected wallet, a+// launch sponsor) is listed but not counted: that wallet's+// total can include coins launched anywhere.+// service income x402 skill sales (agent_revenue_events, USDC net of the+// platform fee) and hires by other agents (agent_hires,+// completed). USDC is valued 1:1 in USD.+//+// Windows: 'all' uses the lifetime creator-fee totals; '24h' sums the 30-minute+// fee buckets of the last 24 hours; '7d' and '30d' sum UTC-day buckets (today+// plus the previous 6 or 29 days). Service income uses the same time range.+// Everything is converted at one SOL/USD price per call (solPriceUsd()).++import { sql } from './db.js';+import { solPriceUsd } from './sol-price.js';+import { SOLANA_USDC_MINT } from '../payments/_config.js';+import { publicUrl as r2PublicUrl } from './r2.js';++// A portrait is decoration: a misconfigured public-URL resolver degrades it to+// null instead of failing the board.+function safeR2Url(key) {+ if (!key) return null;+ try {+ return r2PublicUrl(key);+ } catch {+ return null;+ }+}++export const EARNINGS_WINDOWS = /** @type {const} */ (['24h', '7d', '30d', 'all']);+const DAY_MS = 86_400_000;++/** @param {unknown} w */+export function normalizeWindow(w) {+ return EARNINGS_WINDOWS.includes(/** @type {any} */ (w)) ? /** @type {'24h'|'7d'|'30d'|'all'} */ (w) : 'all';+}++/**+ * The time range a window covers, `back` windows ago (0 = current, 1 = the one+ * before it, used for rank movement). 'all' has no range.+ * @param {'24h'|'7d'|'30d'|'all'} window+ * @param {number} [back]+ * @param {number} [now]+ * @returns {{ interval: '30m'|'1d', start: Date, end: Date } | null}+ */+export function windowRange(window, back = 0, now = Date.now()) {+ if (window === 'all') return null;+ if (window === '24h') {+ const end = new Date(now - back * DAY_MS);+ return { interval: '30m', start: new Date(end.getTime() - DAY_MS), end };+ }+ const days = window === '7d' ? 7 : 30;+ const todayStart = Math.floor(now / DAY_MS) * DAY_MS;+ const end = new Date(todayStart + DAY_MS - back * days * DAY_MS);+ return { interval: '1d', start: new Date(end.getTime() - days * DAY_MS), end };+}++export function earningsMethod(window) {+ const range =+ window === 'all'+ ? 'lifetime totals'+ : window === '24h'+ ? 'the last 24 hours, summed from 30-minute buckets'+ : `the last ${window === '7d' ? 7 : 30} UTC days including today, summed from daily buckets`;+ return (+ `Creator fees come from pump.fun's creator-fee index for each coin's on-chain fee recipient ` ++ `(read from the bonding curve or AMM pool), refreshed every 30 minutes into a snapshot; ` ++ `unclaimed is the creator vault balance read on-chain, claimed is earned minus unclaimed. ` ++ `pump.fun reports fees per creator wallet, so a wallet counts toward an agent only when it is ` ++ `that agent's own custodial wallet; coins paying any other wallet are listed but not counted. ` ++ `Service income is x402 skill sales (net, USDC) plus completed hires by other agents, valued 1:1 in USD. ` ++ `Figures cover ${range}. SOL and USD are converted at one live SOL/USD price. Devnet coins are excluded.`+ );+}++const lamportsToSol = (v) => (v == null ? null : Number(BigInt(v)) / 1e9);+const round = (n, dp) => (n == null || !Number.isFinite(n) ? null : Math.round(n * 10 ** dp) / 10 ** dp);++/**+ * Per-agent creator-fee lamports for a window, plus lifetime claimed/unclaimed.+ * Only counted wallets (see header). `agentId` narrows to one agent; `publicOnly`+ * keeps the leaderboard to public agents.+ */+async function creatorFeeRows(window, { agentId = null, publicOnly = false, back = 0 } = {}) {+ const range = windowRange(window, back);+ const agentFilter = agentId ? sql`and e.agent_id = ${agentId}` : sql``;+ const publicFilter = publicOnly ? sql`and ai.is_public = true` : sql``;+ const windowed = range+ ? sql`+ left join (+ select creator, sum(fee_lamports) as fee+ from creator_fee_buckets+ where bucket_interval = ${range.interval}+ and bucket_start >= ${range.start.toISOString()}+ and bucket_start < ${range.end.toISOString()}+ group by creator+ ) b on b.creator = w.creator`+ : sql``;+ const value = range ? sql`coalesce(b.fee, 0)` : sql`coalesce(w.earned_lamports, 0)`;+ return sql`+ with w as (+ select distinct on (e.creator)+ e.creator, e.agent_id, e.earned_lamports, e.claimed_lamports, e.unclaimed_lamports, e.refreshed_at+ from agent_coin_earnings e+ join agent_identities ai on ai.id = e.agent_id and ai.deleted_at is null+ where e.network = 'mainnet'+ and e.source = 'pumpfun_creator_fees'+ and e.wallet_agent_count = 1+ and e.creator = ai.meta->>'solana_address'+ ${agentFilter}+ ${publicFilter}+ order by e.creator, e.refreshed_at desc nulls last+ )+ select w.agent_id,+ sum(${value})::text as lamports,+ sum(coalesce(w.earned_lamports, 0))::text as lifetime_lamports,+ sum(coalesce(w.claimed_lamports, 0))::text as claimed_lamports,+ sum(coalesce(w.unclaimed_lamports, 0))::text as unclaimed_lamports,+ min(w.refreshed_at) as refreshed_at+ from w+ ${windowed}+ group by w.agent_id+ `;+}++/** Skill sales (USDC net) and completed hires, per agent, for a window. */+async function serviceRows(window, { agentId = null, publicOnly = false, back = 0 } = {}) {+ const range = windowRange(window, back);+ const salesRange = range+ ? sql`and r.created_at >= ${range.start.toISOString()} and r.created_at < ${range.end.toISOString()}`+ : sql``;+ const hireRange = range+ ? sql`and coalesce(h.completed_at, h.created_at) >= ${range.start.toISOString()}+ and coalesce(h.completed_at, h.created_at) < ${range.end.toISOString()}`+ : sql``;+ const salesAgent = agentId ? sql`and r.agent_id = ${agentId}` : sql``;+ const hireAgent = agentId ? sql`and h.provider_agent_id = ${agentId}` : sql``;+ const publicFilter = publicOnly ? sql`and ai.is_public = true` : sql``;+ const [sales, hires] = await Promise.all([+ sql`+ select r.agent_id, sum(r.net_amount)::text as atomics, count(*)::int as n+ from agent_revenue_events r+ join agent_identities ai on ai.id = r.agent_id and ai.deleted_at is null+ where r.currency_mint = ${SOLANA_USDC_MINT} ${salesRange} ${salesAgent} ${publicFilter}+ group by r.agent_id+ `,+ sql`+ select h.provider_agent_id as agent_id, coalesce(sum(h.usd), 0)::float8 as usd, count(*)::int as n+ from agent_hires h+ join agent_identities ai on ai.id = h.provider_agent_id and ai.deleted_at is null+ where h.status = 'completed' ${hireRange} ${hireAgent} ${publicFilter}+ group by h.provider_agent_id+ `,+ ]);+ return { sales, hires };+}++/**+ * Totals per agent for one window, as plain numbers, keyed by agent id.+ * @returns {Promise<Map<string, { creator_lamports: bigint, lifetime_lamports: bigint, claimed_lamports: bigint, unclaimed_lamports: bigint, refreshed_at: any, skill_sales_usd: number, skill_sales_count: number, hires_usd: number, hires_count: number }>>}+ */+async function totalsByAgent(window, opts) {+ const [fees, service] = await Promise.all([creatorFeeRows(window, opts), serviceRows(window, opts)]);+ const out = new Map();+ const get = (id) => {+ let row = out.get(id);+ if (!row) {+ row = {+ creator_lamports: 0n,+ lifetime_lamports: 0n,+ claimed_lamports: 0n,+ unclaimed_lamports: 0n,+ refreshed_at: null,+ skill_sales_usd: 0,+ skill_sales_count: 0,+ hires_usd: 0,+ hires_count: 0,+ };+ out.set(id, row);+ }+ return row;+ };+ for (const f of fees) {+ const row = get(f.agent_id);+ row.creator_lamports = BigInt(f.lamports || 0);+ row.lifetime_lamports = BigInt(f.lifetime_lamports || 0);+ row.claimed_lamports = BigInt(f.claimed_lamports || 0);+ row.unclaimed_lamports = BigInt(f.unclaimed_lamports || 0);+ row.refreshed_at = f.refreshed_at;+ }+ for (const s of service.sales) {+ const row = get(s.agent_id);+ row.skill_sales_usd = Number(BigInt(s.atomics || 0)) / 1e6;+ row.skill_sales_count = s.n;+ }+ for (const h of service.hires) {+ const row = get(h.agent_id);+ row.hires_usd = Number(h.usd) || 0;+ row.hires_count = h.n;+ }+ return out;+}++/**+ * Shape one agent's totals into the public figures. Exported so both endpoints+ * shape identically.+ */+export function shapeTotals(t, price) {+ const creatorSol = Number(t.creator_lamports) / 1e9;+ const serviceUsd = t.skill_sales_usd + t.hires_usd;+ const serviceSol = price > 0 ? serviceUsd / price : null;+ const totalSol = creatorSol + (serviceSol ?? 0);+ return {+ creator_fees: {+ lamports: t.creator_lamports.toString(),+ sol: round(creatorSol, 9),+ usd: price > 0 ? round(creatorSol * price, 2) : null,+ },+ service_income: {+ skill_sales_usd: round(t.skill_sales_usd, 2),+ skill_sales_count: t.skill_sales_count,+ hires_usd: round(t.hires_usd, 2),+ hires_count: t.hires_count,+ usd: round(serviceUsd, 2),+ sol: serviceSol == null ? null : round(serviceSol, 9),+ },+ total: {+ sol: round(totalSol, 9),+ usd: price > 0 ? round(totalSol * price, 2) : serviceUsd > 0 ? round(serviceUsd, 2) : null,+ },+ };+}++const rankKey = (t, price) => Number(t.creator_lamports) / 1e9 + (price > 0 ? (t.skill_sales_usd + t.hires_usd) / price : 0);++/** Ranked public agents for a window (only agents that earned something). */+async function rankedAgents(window, price, back = 0) {+ const totals = await totalsByAgent(window, { publicOnly: true, back });+ return [...totals.entries()]+ .map(([agentId, t]) => ({ agentId, t, key: rankKey(t, price) }))+ .filter((r) => r.key > 0)+ .sort((a, b) => b.key - a.key || String(a.agentId).localeCompare(String(b.agentId)));+}++/**+ * One agent's earnings: windowed totals, lifetime creator-fee figures, the+ * per-coin breakdown, and its recorded claims.+ * @param {{ id: string, name: string, is_public: boolean, solana_address: string | null }} agent+ * @param {{ window?: string }} [opts]+ */+export async function getAgentEarnings(agent, { window: rawWindow = 'all' } = {}) {+ const window = normalizeWindow(rawWindow);+ const [price, totals, lifetimeTotals, coins, devnet, claims] = await Promise.all([+ solPriceUsd(),+ totalsByAgent(window, { agentId: agent.id }),+ window === 'all' ? null : totalsByAgent('all', { agentId: agent.id }),+ sql`+ select pam.mint, pam.name, pam.symbol, pam.created_at,+ e.creator, e.earned_lamports::text, e.claimed_lamports::text, e.unclaimed_lamports::text,+ e.wallet_coin_count, e.wallet_agent_count, e.source, e.error, e.refreshed_at, e.attempted_at+ from pump_agent_mints pam+ left join agent_coin_earnings e on e.mint = pam.mint and e.network = pam.network+ where pam.agent_id = ${agent.id} and pam.network = 'mainnet'+ order by pam.created_at desc+ `,+ sql`select count(*)::int as n from pump_agent_mints where agent_id = ${agent.id} and network = 'devnet'`,+ recentClaims(agent.id),+ ]);+ const t = totals.get(agent.id) || emptyTotals();+ const life = (lifetimeTotals ? lifetimeTotals.get(agent.id) : totals.get(agent.id)) || emptyTotals();+ const shaped = shapeTotals(t, price);+ const lifeSol = (v) => round(Number(v) / 1e9, 9);+ const usd = (sol) => (price > 0 && sol != null ? round(sol * price, 2) : null);++ const coinRows = coins.map((c) => shapeCoin(c, agent.solana_address, price));+ const refreshedTimes = coinRows.map((c) => c.refreshed_at).filter(Boolean).map((d) => new Date(d).getTime());+ const refreshedAt = refreshedTimes.length ? new Date(Math.min(...refreshedTimes)).toISOString() : null;++ let rank = null;+ if (agent.is_public) rank = await agentRank(agent.id, window === 'all' ? '7d' : window, price);++ return {+ agent: { id: agent.id, name: agent.name, url: `/agents/${agent.id}` },+ network: 'mainnet',+ window,+ sol_price_usd: price > 0 ? price : null,+ has_coins: coins.length > 0,+ devnet_coins_excluded: devnet[0]?.n || 0,+ ...shaped,+ lifetime_creator_fees: {+ earned_sol: lifeSol(life.lifetime_lamports),+ earned_usd: usd(lifeSol(life.lifetime_lamports)),+ claimed_sol: lifeSol(life.claimed_lamports),+ claimed_usd: usd(lifeSol(life.claimed_lamports)),+ unclaimed_sol: lifeSol(life.unclaimed_lamports),+ unclaimed_usd: usd(lifeSol(life.unclaimed_lamports)),+ },+ coins: coinRows,+ claims,+ rank,+ refreshed_at: refreshedAt,+ stale: refreshedAt ? Date.now() - new Date(refreshedAt).getTime() > 2 * 3_600_000 : false,+ method: earningsMethod(window),+ };+}++function emptyTotals() {+ return {+ creator_lamports: 0n,+ lifetime_lamports: 0n,+ claimed_lamports: 0n,+ unclaimed_lamports: 0n,+ refreshed_at: null,+ skill_sales_usd: 0,+ skill_sales_count: 0,+ hires_usd: 0,+ hires_count: 0,+ };+}++function shapeCoin(c, agentWallet, price) {+ const reported = c.source === 'pumpfun_creator_fees' && c.earned_lamports != null;+ const counted = reported && c.creator === agentWallet && Number(c.wallet_agent_count) === 1;+ const earnedSol = reported ? lamportsToSol(c.earned_lamports) : null;+ return {+ mint: c.mint,+ name: c.name,+ symbol: c.symbol,+ url: `/launches/${c.mint}`,+ launched_at: c.created_at,+ creator: c.creator || null,+ status: !reported ? 'not_reported' : counted ? 'counted' : 'other_wallet',+ earned_sol: earnedSol,+ earned_usd: price > 0 && earnedSol != null ? round(earnedSol * price, 2) : null,+ claimed_sol: reported ? lamportsToSol(c.claimed_lamports) : null,+ unclaimed_sol: reported ? lamportsToSol(c.unclaimed_lamports) : null,+ wallet_coin_count: c.wallet_coin_count ?? null,+ refreshed_at: c.refreshed_at || null,+ error: c.error || null,+ };+}++/**+ * Recorded creator-fee claims for an agent: autonomous claims (launcher_claims)+ * and owner-triggered claims (agent_actions 'pumpfun.collect_creator_fee').+ * A claim sweeps every coin of the wallet at once, so `mint` names the coin the+ * claim was started from.+ */+async function recentClaims(agentId) {+ const [launcher, studio] = await Promise.all([+ sql`+ select claim_sig as signature, claimed_lamports::text as lamports, mint, created_at+ from launcher_claims+ where agent_id = ${agentId} and network = 'mainnet' and claim_sig is not null+ order by created_at desc limit 20+ `,+ sql`+ select payload->>'signature' as signature, payload->>'lamports' as lamports,+ payload->>'mint' as mint, created_at+ from agent_actions+ where agent_id = ${agentId} and type = 'pumpfun.collect_creator_fee'+ and coalesce(payload->>'network', 'mainnet') = 'mainnet'+ and payload->>'signature' is not null+ order by created_at desc limit 20+ `,+ ]);+ const rows = [+ ...launcher.map((r) => ({ ...r, source: 'autonomous' })),+ ...studio.map((r) => ({ ...r, source: 'owner' })),+ ];+ rows.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());+ return rows.slice(0, 20).map((r) => ({+ signature: r.signature,+ sol: r.lamports != null && /^\d+$/.test(String(r.lamports)) ? lamportsToSol(r.lamports) : null,+ mint: r.mint,+ at: r.created_at,+ source: r.source,+ explorer: `https://solscan.io/tx/${r.signature}`,+ }));+}++/** Rank of one public agent on the earnings board for a window, or null. */+async function agentRank(agentId, window, price) {+ const ranked = await rankedAgents(window, price);+ const i = ranked.findIndex((r) => r.agentId === agentId);+ return i < 0 ? null : { window, position: i + 1, of: ranked.length, url: `/leaderboard?tab=earned&window=${window}` };+}++/**+ * The earnings leaderboard for a window, paginated. Each row's figures come+ * from shapeTotals over the same totals getAgentEarnings uses.+ */+export async function listEarningsLeaderboard({ window: rawWindow = '7d', limit = 25, offset = 0 } = {}) {+ const window = normalizeWindow(rawWindow);+ const price = await solPriceUsd();+ const [ranked, previous] = await Promise.all([+ rankedAgents(window, price),+ window === 'all' ? null : rankedAgents(window, price, 1),+ ]);+ const prevPos = new Map((previous || []).map((r, i) => [r.agentId, i + 1]));+ const page = ranked.slice(offset, offset + limit);+ const ids = page.map((r) => r.agentId);+ const [profiles, coins] = ids.length+ ? await Promise.all([+ sql`+ select ai.id, ai.name, ai.meta->>'solana_address' as solana_address,+ a.thumbnail_key, a.visibility+ from agent_identities ai+ left join avatars a on a.id = ai.avatar_id and a.deleted_at is null+ where ai.id = any(${ids})+ `,+ sql`+ select distinct on (pam.agent_id) pam.agent_id, pam.mint, pam.symbol, pam.name+ from pump_agent_mints pam+ left join agent_coin_earnings e on e.mint = pam.mint and e.network = pam.network+ where pam.agent_id = any(${ids}) and pam.network = 'mainnet'+ order by pam.agent_id, e.earned_lamports desc nulls last, pam.created_at desc+ `,+ ])+ : [[], []];+ const byId = new Map(profiles.map((p) => [p.id, p]));+ const coinById = new Map(coins.map((c) => [c.agent_id, c]));+ const refreshed = ranked.map((r) => r.t.refreshed_at).filter(Boolean).map((d) => new Date(d).getTime());++ return {+ window,+ sol_price_usd: price > 0 ? price : null,+ total: ranked.length,+ limit,+ offset,+ refreshed_at: refreshed.length ? new Date(Math.min(...refreshed)).toISOString() : null,+ method: earningsMethod(window),+ rows: page.map((r, i) => {+ const p = byId.get(r.agentId) || {};+ const coin = coinById.get(r.agentId) || null;+ const rank = offset + i + 1;+ const prev = prevPos.get(r.agentId) ?? null;+ return {+ rank,+ previous_rank: prev,+ movement: window === 'all' ? null : prev == null ? 'new' : prev - rank,+ agent: {+ id: r.agentId,+ name: p.name || 'Agent',+ url: `/agents/${r.agentId}`,+ thumbnail_url: p.visibility === 'public' || p.visibility === 'unlisted' ? safeR2Url(p.thumbnail_key) : null,+ },+ coin: coin ? { mint: coin.mint, symbol: coin.symbol, name: coin.name, url: `/launches/${coin.mint}` } : null,+ ...shapeTotals(r.t, price),+ };+ }),+ };+}diff --git a/api/_mcp/resources.js b/api/_mcp/resources.jsindex ca84e74a1..23530fa1c 100644--- a/api/_mcp/resources.js+++ b/api/_mcp/resources.js@@ -138,6 +138,7 @@ function agentLinks(id) {orders: `three://agents/${id}/orders`,dca: `three://agents/${id}/dca`,intents: `three://agents/${id}/intents`,+ earnings: `three://agents/${id}/earnings`,},};}@@ -822,6 +823,23 @@ async function readAsset(ctx, { id }) {};}+// three://agents/{agentId}/earnings (api/agents/[id]/earnings.js)+// Public like its REST twin: a public agent's creator fees and claims are+// on-chain for anyone to read. A private agent reads only for its owner.+async function readEarnings(ctx, { agentId }) {+ if (!UUID_RE.test(agentId)) throw notFound(ctx.uri);+ const [agent] = await sql`+ SELECT id, name, is_public, user_id, meta->>'solana_address' AS solana_address+ FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ LIMIT 1+ `;+ if (!agent) throw notFound(ctx.uri);+ if (!agent.is_public && agent.user_id !== ctx.auth?.userId) throw notFound(ctx.uri);+ const { getAgentEarnings } = await import('../_lib/agent-earnings.js');+ return { ...(await getAgentEarnings(agent)), page: `${origin()}/agents/${agent.id}` };+}+// ── Registry ──────────────────────────────────────────────────────────────────const AGENT_SCOPES = ['agents:read', 'agents:write'];@@ -940,6 +958,16 @@ export const RESOURCES = [perAgent: true,read: readIntents,},+ {+ key: 'earnings',+ uriTemplate: 'three://agents/{agentId}/earnings',+ name: 'agent-earnings',+ title: 'Agent earnings',+ description: 'What an agent has earned: lifetime pump.fun creator fees from its coins (earned, claimed, unclaimed, in SOL and USD, per coin), its recorded claim transactions with explorer links, x402 skill sales and hires, its earnings-leaderboard rank, and a method line saying where every number comes from. Public for public agents.',+ access: 'public',+ perAgent: true,+ read: readEarnings,+ },{key: 'marketplace',uri: 'three://marketplace',@@ -1002,8 +1030,8 @@ const BY_KEY = new Map(RESOURCES.map((r) => [r.key, r]));// Which resources each hosted server exposes.const SERVER_RESOURCES = {- mcp: ['me', 'agents', 'agent', 'wallet', 'usage', 'chat', 'runs', 'run', 'orders', 'dca', 'intents', 'marketplace', 'models', 'wallets', 'launches', 'x402-services'],- 'mcp-agent': ['me', 'agents', 'agent', 'wallet', 'usage', 'runs', 'run', 'orders', 'dca', 'intents', 'wallets', 'launches', 'marketplace', 'x402-services'],+ mcp: ['me', 'agents', 'agent', 'wallet', 'usage', 'chat', 'runs', 'run', 'orders', 'dca', 'intents', 'earnings', 'marketplace', 'models', 'wallets', 'launches', 'x402-services'],+ 'mcp-agent': ['me', 'agents', 'agent', 'wallet', 'usage', 'runs', 'run', 'orders', 'dca', 'intents', 'earnings', 'wallets', 'launches', 'marketplace', 'x402-services'],'mcp-3d': ['me', 'agents', 'agent', 'asset', 'models'],'mcp-bazaar': ['me', 'x402-services', 'marketplace'],};diff --git a/api/_mcp/tools/resources.js b/api/_mcp/tools/resources.jsindex 82cd06795..1133108f3 100644--- a/api/_mcp/tools/resources.js+++ b/api/_mcp/tools/resources.js@@ -14,7 +14,7 @@ export const toolDefs = [openWorldHint: false,},description:- 'Read a live three.ws resource by URI: three://me (account, scopes, quota), three://agents and three://agents/<id> (your agents), three://agents/<id>/wallet (balances, limits, freeze state), .../usage, .../chat, .../runs, .../orders, .../dca, .../intents, three://wallets, three://launches, three://marketplace, three://models and three://x402/services. Omit uri to list every resource you can read. Set format to markdown for a readable rendering.',+ 'Read a live three.ws resource by URI: three://me (account, scopes, quota), three://agents and three://agents/<id> (your agents), three://agents/<id>/wallet (balances, limits, freeze state), .../usage, .../chat, .../runs, .../orders, .../dca, .../intents, .../earnings (public: creator fees, claims, service income), three://wallets, three://launches, three://marketplace, three://models and three://x402/services. Omit uri to list every resource you can read. Set format to markdown for a readable rendering.',inputSchema: {type: 'object',properties: {diff --git a/api/agents/[id]/earnings.js b/api/agents/[id]/earnings.jsnew file mode 100644index 000000000..5cd5a0351--- /dev/null+++ b/api/agents/[id]/earnings.js@@ -0,0 +1,52 @@+// GET /api/agents/:id/earnings[?window=24h|7d|30d|all]: what an agent has+// earned, publicly. Creator fees from the coins it launched on pump.fun (earned,+// claimed, unclaimed, per coin, with the recorded claim transactions) plus its+// service income (x402 skill sales and hires), in SOL and USD.+//+// Public on purpose: creator fees and claims are on-chain for anyone to read,+// and service income is the headline an agent's builder wants to show. A private+// agent answers 404 to everyone but its owner.+//+// The computation lives in api/_lib/agent-earnings.js and is shared with+// GET /api/leaderboard/earnings, so the two can never disagree. Figures come+// from the snapshot the creator-earnings cron refreshes every 30 minutes;+// `refreshed_at` says how old they are and `method` says where they come from.++import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { sql } from '../../_lib/db.js';+import { getSessionUser } from '../../_lib/auth.js';+import { isUuid } from '../../_lib/validate.js';+import { getAgentEarnings } from '../../_lib/agent-earnings.js';++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 id = url.searchParams.get('id') || url.pathname.split('/').filter(Boolean)[2];+ // The vercel.json rewrite lands here directly, so the uuid gate api/agents/[id].js+ // applies never runs; a malformed id must not reach a uuid column as a 500.+ if (!isUuid(id)) return error(res, 404, 'not_found', 'agent not found');++ const [agent] = await sql`+ select id, name, is_public, user_id, meta->>'solana_address' as solana_address+ from agent_identities+ where id = ${id} and deleted_at is null+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ if (!agent.is_public) {+ const viewer = await getSessionUser(req).catch(() => null);+ if (!viewer || viewer.id !== agent.user_id) return error(res, 404, 'not_found', 'agent not found');+ }++ const body = await getAgentEarnings(agent, { window: url.searchParams.get('window') || 'all' });+ res.setHeader(+ 'cache-control',+ agent.is_public ? 'public, max-age=60, s-maxage=120, stale-while-revalidate=300' : 'private, no-store',+ );+ return json(res, 200, body);+});diff --git a/api/pump/launch-detail.js b/api/pump/launch-detail.jsindex 0cea207b5..bc3ba696b 100644--- a/api/pump/launch-detail.js+++ b/api/pump/launch-detail.js@@ -33,8 +33,9 @@ import { sql } from '../_lib/db.js';import { publicUrl as r2PublicUrl } from '../_lib/r2.js';import { normalizeGatewayURL } from '../../src/ipfs.js';import { getTraderStats } from '../_lib/trader-stats.js';-import { withBreaker } from '../_lib/resilience.js';-import { pumpFetchJson } from '../_lib/pump-feed-fetch.js';+import { getConnection } from '../_lib/pump.js';+import { solPriceUsd } from '../_lib/sol-price.js';+import { resolveCoinCreators, readCreatorFeeReport } from '../_lib/pump-creator-fees.js';const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;const lamportsToSol = (v) => (v == null ? null : Number(BigInt(v)) / 1e9);@@ -52,48 +53,54 @@ function safeR2Url(key) {}}-// Creator fee-sharing earnings — what the coin's creator has actually earned-// from pump.fun's creator-reward program. Two public pump.fun endpoints (the-// same ones the pump.fun frontend calls): coin metadata → creator wallet, then-// the creator's fee-sharing totals filtered to this mint.+// Creator fees: what the coin's creator wallet has earned from pump.fun's+// creator-fee program. Read from the agent_coin_earnings snapshot the+// creator-earnings cron refreshes every 30 minutes, so a page view never waits+// on pump.fun. A coin the snapshot has not reached yet (launched minutes ago)+// falls back to one live read through the shared client in+// api/_lib/pump-creator-fees.js, which runs behind the 'pumpfun:creator-fees'+// circuit breaker and resolves the fee recipient on-chain.//-// Each call is timeout-bounded, and the whole thing runs behind a circuit-// breaker at the call site (see buildDetail): an UNHEALTHY upstream (network-// error, timeout, non-2xx) throws so consecutive failures open the breaker and-// later requests skip pump.fun instantly instead of every launch-page load-// waiting out two 5s timeouts during an outage. A VALID-but-empty response (no-// creator, no earnings) returns null and counts as a success — it isn't an-// outage, so it must not trip the breaker.-const PUMP_FRONTEND_V3 = 'https://frontend-api-v3.pump.fun';-const PUMP_SWAP_API = 'https://swap-api.pump.fun';--async function fetchCreatorFees(mint, network) {+// pump.fun indexes these fees per creator wallet: `wallet_coin_count` > 1 means+// the figure is shared by that many coins from the same wallet.+async function creatorFeesFor(mint, network, price) {if (network !== 'mainnet') return null;- // pump.fun answers a burst with 429 far more often than it goes down, and a- // bare fetch treated the two identically. pumpFetchJson honours Retry-After- // and retries once, which is the difference between a launch page rendering- // and a launch page erroring during someone else's mint.- const metaRes = await pumpFetchJson(`${PUMP_FRONTEND_V3}/coins-v2/${mint}`, { timeoutMs: 5000 });- if (!metaRes.ok) throw new Error(`pump.fun coin meta ${metaRes.status}`);- const meta = metaRes.body;- const creator = meta?.creator || meta?.creator_address;- if (!creator || typeof creator !== 'string') return null; // valid: no creator on file-- const totRes = await pumpFetchJson(- `${PUMP_SWAP_API}/v1/fee-sharing/account/${creator}/totals?mint=${mint}`,- { timeoutMs: 5000 },- );- if (!totRes.ok) throw new Error(`pump.fun fee-sharing ${totRes.status}`);- const t = totRes.body;- const earnedSol = Number(t?.shareholderTotalEarned?.sol);- if (!Number.isFinite(earnedSol)) return null; // valid: creator has no fee-sharing earnings+ const toUsd = (sol) => (price > 0 && sol != null ? Math.round(sol * price * 100) / 100 : null);+ const [snap] = await sql`+ select creator, earned_lamports::text, claimed_lamports::text, unclaimed_lamports::text,+ wallet_coin_count, source, refreshed_at+ from agent_coin_earnings+ where mint = ${mint} and network = 'mainnet'+ `;+ if (snap?.source === 'pumpfun_creator_fees' && snap.earned_lamports != null) {+ const earned = lamportsToSol(snap.earned_lamports);+ return {+ creator: snap.creator,+ earned_sol: earned,+ earned_usd: toUsd(earned),+ claimed_sol: lamportsToSol(snap.claimed_lamports),+ unclaimed_sol: lamportsToSol(snap.unclaimed_lamports),+ wallet_coin_count: snap.wallet_coin_count,+ refreshed_at: snap.refreshed_at,+ source: 'snapshot',+ };+ }+ const connection = getConnection({ network: 'mainnet' });+ const creators = await resolveCoinCreators(connection, [mint]).catch(() => null);+ const creator = creators?.get(mint)?.creator;+ if (!creator) return null;+ const report = await readCreatorFeeReport(connection, creator);+ if (!report.ok) return null;+ const earned = Number(report.earned_lamports) / 1e9;return {creator,- earned_sol: earnedSol,- earned_usd: Number(t?.shareholderTotalEarned?.usd) || null,- claimed_sol: Number(t?.shareholderClaimed?.sol) || 0,- unclaimed_sol: Number(t?.shareholderUnclaimed?.sol) || 0,- mint_count: t?.mintCount != null ? Number(t.mintCount) : null,+ earned_sol: earned,+ earned_usd: toUsd(earned),+ claimed_sol: report.claimed_lamports == null ? null : Number(report.claimed_lamports) / 1e9,+ unclaimed_sol: report.unclaimed_lamports == null ? null : Number(report.unclaimed_lamports) / 1e9,+ wallet_coin_count: null,+ refreshed_at: new Date().toISOString(),+ source: 'live',};}@@ -210,15 +217,10 @@ async function buildDetail(mint, network) {where mint_id=${reg.id} and status='confirmed'order by created_at desc limit 8`,- // Behind a circuit breaker: a healthy pump.fun returns the fees (or a- // valid null); a sick one trips the breaker after 3 failures so later- // launch-page loads skip it instantly and degrade to null instead of- // each waiting out two 5s timeouts during an outage.- withBreaker('pumpfun:creator-fees', () => fetchCreatorFees(mint, network), {- fallback: null,- threshold: 3,- halfOpenAfterMs: 30_000,- }),+ // Snapshot first; a live read (behind the shared creator-fee breaker)+ // only for a coin the snapshot has not reached. Enrichment, so a+ // failure degrades to null rather than failing the page.+ solPriceUsd().then((price) => creatorFeesFor(mint, network, price)).catch(() => null),]);economics = {confirmed_payments: stats?.confirmed_payments ?? 0,diff --git a/pages/agent-detail.html b/pages/agent-detail.htmlindex 5dcf0ccb5..237308208 100644--- a/pages/agent-detail.html+++ b/pages/agent-detail.html@@ -502,6 +502,14 @@</div></section>+ <section class="ad-card" id="ad-earned-card">+ <div class="ad-card-head">+ <span class="ad-bullet ad-bullet-amber"></span>+ <h2>EARNED</h2>+ </div>+ <div id="ad-earned-body"></div>+ </section>+<section class="ad-card" id="ad-trading-card-section" data-span="2" hidden><div class="ad-card-head"><span class="ad-bullet"></span>diff --git a/src/agent-detail.js b/src/agent-detail.jsindex d0cbb6c2a..47cf50f4f 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -37,6 +37,7 @@ import { log } from './shared/log.js';import { track, trackError, ANALYTICS_EVENTS } from './analytics.js';import { mountViewSwitcher } from './view-switcher.js';import { mountCoinStatus } from './pump/coin-status-card.js';+import { mountEarningsCard } from './shared/agent-earnings-card.js';import { mountAgentTokenPlan } from './agent-token-plan.js';import { consumeCsrfToken } from './api.js';import { countUp, updateValue, flashValue, ring, playRings, sparkline, enterStagger } from './ui-juice.js';@@ -53,6 +54,7 @@ let _streamHandle = null;let _strategyHandle = null;let _cardHandle = null;let _patronageHandle = null;+let _earnedHandle = null;let _watchHandle = null;let _achievementsHandle = null;// Live WebGL avatar mounts (hero + fullscreen modal). Disposed on re-render so a@@ -1444,6 +1446,18 @@ function render(agent) {}}+ // Earned: creator fees from the agent's coins plus service income, from+ // GET /api/agents/:id/earnings, through the shared card the agent page mounts+ // too. It renders its own loading, empty ("launch a coin"), nothing-earned-yet+ // and error states. The classic layout has no #ad-earned-body.+ {+ const earnedBody = $('ad-earned-body');+ if (_earnedHandle) { try { _earnedHandle.destroy(); } catch { /* idempotent */ } _earnedHandle = null; }+ if (earnedBody && agent.id) {+ _earnedHandle = mountEarningsCard({ mount: earnedBody, agentId: agent.id });+ }+ }+// A re-render (avatar refresh) clears the token body below; tear down any// coin-status widgets first so their refresh timers don't leak.destroyCoinStatus();diff --git a/src/avatar-page.js b/src/avatar-page.jsindex 69d63144b..7c92039f1 100644--- a/src/avatar-page.js+++ b/src/avatar-page.js@@ -37,6 +37,7 @@ import { emitRecallFromChat } from './agents/memory-client.js';import { moodEngine } from './agents/mood-engine.js';import { skillLabel } from './shared/skill-label.js';import { mountCoinStatus } from './pump/coin-status-card.js';+import { mountEarningsCard } from './shared/agent-earnings-card.js';import { renderHomeConfirmation } from './home-confirm-card.js';const ATTACHED_KEY_PREFIX = 'avatar_attached_v1:';@@ -703,6 +704,10 @@ function renderShell(glbUrl) {? `<section class="av-coin" id="av-coin" hidden aria-labelledby="av-coin-heading"><h3 class="av-used-by-heading" id="av-coin-heading">Its coin</h3><div id="av-coin-slot"></div>+ </section>+ <section class="av-coin" id="av-earned" aria-labelledby="av-earned-heading">+ <h3 class="av-used-by-heading" id="av-earned-heading">Earned</h3>+ <div id="av-earned-slot"></div></section>`: ''}${mode === 'agent' ? bodyCardHTML() : ''}@@ -814,6 +819,20 @@ function renderShell(glbUrl) {mountWalletManager();mountAgentCoin();+ mountEarned();+}++/**+ * What this agent has earned: creator fees from its coins plus service income,+ * from GET /api/agents/:id/earnings via the shared Earned card (the same widget+ * the full profile mounts). Shown for every agent; the card itself renders the+ * "launch a coin" empty state, the nothing-earned-yet state and the error state.+ */+function mountEarned() {+ const slot = $('av-earned-slot');+ const agentId = agent?.id || entityId;+ if (!slot || mode !== 'agent' || !agentId) return;+ mountEarningsCard({ mount: slot, agentId });}/**diff --git a/src/launch-detail.css b/src/launch-detail.cssindex d5c45160f..d9667a3b0 100644--- a/src/launch-detail.css+++ b/src/launch-detail.css@@ -475,6 +475,10 @@ body {.ld-econ-val { font-family: var(--font-mono); font-size: var(--text-lg); font-weight: var(--weight-bold); color: var(--ink-bright); }.ld-econ-label { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.1em; color: var(--ink-dim); }.ld-econ-sub { font-size: var(--text-2xs); color: var(--ink-faint); }+.ld-econ-note { margin: 0; font-size: var(--text-xs); color: var(--ink-faint); line-height: 1.5; }+.ld-econ-note a { color: var(--ink-dim); text-underline-offset: 2px; transition: color var(--duration-fast) var(--ease-standard); }+.ld-econ-note a:hover { color: var(--ink-bright); }+.ld-econ-note a:focus-visible { outline: var(--focus-ring-width, 2px) solid var(--focus-ring-color); outline-offset: 2px; border-radius: 3px; }.ld-burn-feed { display: flex; flex-direction: column; gap: var(--space-2xs); padding-top: var(--space-sm); border-top: 1px solid var(--stroke); }.ld-burn-feed-title { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.14em; color: var(--ink-dim); }.ld-burn-row {diff --git a/src/launch-detail.js b/src/launch-detail.jsindex fe09dbec1..d734fef30 100644--- a/src/launch-detail.js+++ b/src/launch-detail.js@@ -1201,7 +1201,9 @@ function renderEconomics() {}const creatorFees = econ?.creator_fees;- const hasCreatorFees = !!creatorFees && Number(creatorFees.earned_sol) > 0;+ // Present whenever the earnings snapshot (or the live fallback) reported this+ // coin, zero included: "earned 0 SOL so far" is a real, useful answer.+ const hasCreatorFees = !!creatorFees && creatorFees.earned_sol != null;if (buybackBps <= 0 && (!econ || econ.confirmed_payments === 0) && !hasCreatorFees) {section(@@ -1224,11 +1226,15 @@ function renderEconomics() {]);const body = el('div', { class: 'ld-econ' }, [- el('p', { class: 'ld-econ-lede', text: `Every agent payment routes ${(buybackBps / 100).toFixed(1)}% into an automated buyback that burns supply — paying users fund a deflationary loop.` }),+ buybackBps > 0+ ? el('p', { class: 'ld-econ-lede', text: `Every agent payment routes ${(buybackBps / 100).toFixed(1)}% into an automated buyback that burns supply, so paying users fund a deflationary loop.` })+ : el('p', { class: 'ld-econ-lede', text: 'Every trade of this coin pays its creator a fee. Here is what it has earned, claimed and left to claim.' }),el('div', { class: 'ld-econ-grid' }, [- metric('Buyback rate', `${(buybackBps / 100).toFixed(1)}%`),- metric('Paid calls', compact(econ?.confirmed_payments || 0), `${compact(econ?.unique_payers || 0)} payers`),- metric('Burn runs', compact(econ?.burns?.runs || 0)),+ buybackBps > 0 ? metric('Buyback rate', `${(buybackBps / 100).toFixed(1)}%`) : null,+ buybackBps > 0 || econ?.confirmed_payments+ ? metric('Paid calls', compact(econ?.confirmed_payments || 0), `${compact(econ?.unique_payers || 0)} payers`)+ : null,+ buybackBps > 0 ? metric('Burn runs', compact(econ?.burns?.runs || 0)) : null,burned > 0 ? metric('Supply burned', compact(burned / 1e6)) : null,hasCreatorFees? metric(@@ -1237,8 +1243,15 @@ function renderEconomics() {creatorFees.earned_usd != null ? fmtUsd(Number(creatorFees.earned_usd), { sign: false }) : null,): null,+ hasCreatorFees && creatorFees.claimed_sol != null+ ? metric('Claimed', fmtSol(Number(creatorFees.claimed_sol), { sign: false }))+ : null,+ hasCreatorFees && creatorFees.unclaimed_sol != null+ ? metric('Unclaimed', fmtSol(Number(creatorFees.unclaimed_sol), { sign: false }))+ : null,]),]);+ if (hasCreatorFees) body.appendChild(creatorFeesNote(creatorFees));// Recent burn proofs — each links to its Solana transaction.const feed = (econ?.burns_feed || []).slice(0, 5);@@ -1271,6 +1284,28 @@ function renderEconomics() {section(target, 'Economics', body, { tag: 'on-chain' });}+// Where the creator-fee figures come from, how fresh they are, and (when+// pump.fun reports one figure for a wallet that created several coins) that+// the number is shared. Links to the agent's full earnings on its own page.+function creatorFeesNote(fees) {+ const parts = [];+ if (Number(fees.wallet_coin_count) > 1) {+ parts.push(`Combined for ${fees.wallet_coin_count} coins created by the same wallet.`);+ }+ parts.push(+ fees.refreshed_at+ ? `Creator fees from pump.fun, updated ${relTime(fees.refreshed_at)}.`+ : 'Creator fees from pump.fun.',+ );+ const agent = state.detail.agent;+ return el('p', { class: 'ld-econ-note' }, [+ el('span', { text: parts.join(' ') + ' ' }),+ agent?.id && agent.is_public+ ? el('a', { href: `/agents/${encodeURIComponent(agent.id)}#av-earned`, text: 'See everything this agent earned →' })+ : null,+ ]);+}+// ════════════════════════════════════════════════════════════════════════════// AGENT BEHIND THE COIN// ════════════════════════════════════════════════════════════════════════════diff --git a/src/shared/agent-earnings-card.js b/src/shared/agent-earnings-card.jsnew file mode 100644index 000000000..411ae5704--- /dev/null+++ b/src/shared/agent-earnings-card.js@@ -0,0 +1,275 @@+// Earned card: what an agent has earned, on its public pages.+// ============================================================+// One number a builder can screenshot: lifetime creator fees from the coins the+// agent launched on pump.fun, in SOL with USD beside it, plus its service income+// (x402 skill sales and hires). Below it: claimed vs unclaimed, the per-coin+// breakdown, and every recorded claim with its Solscan link. Every figure comes+// from GET /api/agents/:id/earnings; the card never computes or invents one.+//+// Single source of truth: import and mount it, never copy it per page.+// import { mountEarningsCard } from './shared/agent-earnings-card.js';+// const handle = mountEarningsCard({ mount, agentId, onState });+// handle.refresh(); handle.destroy();+//+// `onState(state)` reports 'loading' | 'empty' | 'zero' | 'earned' | 'error' so a+// host page can decide whether to show the surrounding card at all.++const STYLE_ID = 'tws-earnings-card-styles';++const esc = (s) =>+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+const shortAddr = (a) => (a && a.length > 10 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a || '');++export function fmtSol(n) {+ const v = Number(n);+ if (!Number.isFinite(v) || v === 0) return '0 SOL';+ if (v < 0.001) return `${v.toFixed(6)} SOL`;+ if (v < 1) return `${v.toFixed(4)} SOL`;+ if (v < 1000) return `${v.toFixed(3)} SOL`;+ return `${Math.round(v).toLocaleString('en-US')} SOL`;+}++export function fmtUsd(n) {+ const v = Number(n);+ if (n == null || !Number.isFinite(v)) return '';+ if (v === 0) return '$0';+ if (v < 0.01) return '<$0.01';+ if (v < 1000) return `$${v.toFixed(2)}`;+ return `$${Math.round(v).toLocaleString('en-US')}`;+}++export function relTime(iso) {+ if (!iso) return '';+ const d = Date.now() - new Date(iso).getTime();+ if (!Number.isFinite(d)) return '';+ const s = Math.max(0, Math.round(d / 1000));+ if (s < 60) return 'just now';+ const m = Math.round(s / 60);+ if (m < 60) return `${m}m ago`;+ const h = Math.round(m / 60);+ if (h < 24) return `${h}h ago`;+ const day = Math.round(h / 24);+ if (day < 30) return `${day}d ago`;+ return `${Math.round(day / 30)}mo ago`;+}++function ensureStyles() {+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const style = document.createElement('style');+ style.id = STYLE_ID;+ style.textContent = `+.ern { display: flex; flex-direction: column; gap: var(--space-md, 1rem); font-family: var(--font-body, Inter, sans-serif); color: var(--ink, #e8e8e8); min-width: 0; }+.ern-sk { border-radius: var(--radius-md, 10px); background: linear-gradient(100deg, var(--skeleton-base, rgba(255,255,255,.04)) 30%, var(--skeleton-sheen, rgba(255,255,255,.09)) 50%, var(--skeleton-base, rgba(255,255,255,.04)) 70%); background-size: 200% 100%; animation: ern-shimmer 1.4s linear infinite; }+@keyframes ern-shimmer { to { background-position: -200% 0; } }+@media (prefers-reduced-motion: reduce) { .ern-sk { animation: none; } }+.ern-sk-hero { height: 44px; width: 62%; }+.ern-sk-row { height: 14px; width: 100%; }+.ern-sk-row.short { width: 45%; }+.ern-hero { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }+.ern-total { font-family: var(--font-display, 'Space Grotesk', sans-serif); font-size: clamp(1.6rem, 5vw, 2.1rem); font-weight: 700; letter-spacing: -.02em; line-height: 1.05; color: var(--ink-bright, #fff); font-variant-numeric: tabular-nums; }+.ern-usd { font-family: var(--font-mono, 'JetBrains Mono', monospace); font-size: var(--text-md, .8125rem); color: var(--ink-dim, #999); }+.ern-rank { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; font-size: var(--text-xs, .72rem); font-weight: 600; color: var(--accent, #c4b5fd); background: var(--accent-soft, rgba(139,92,246,.12)); border: 1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: var(--radius-pill, 999px); padding: 3px 10px; text-decoration: none; transition: border-color var(--duration-fast, .14s) var(--ease-standard, ease), transform var(--duration-fast, .14s) var(--ease-standard, ease); }+.ern-rank:hover { border-color: var(--stroke-strong, rgba(255,255,255,.25)); transform: translateY(-1px); }+.ern-rank:active { transform: translateY(0); }+.ern-sub { margin: -6px 0 0; font-size: var(--text-sm, .78rem); color: var(--ink-dim, #999); }+.ern-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 8px; }+.ern-stat { border: 1px solid var(--stroke, rgba(255,255,255,.08)); background: var(--surface-1, rgba(255,255,255,.03)); border-radius: var(--radius-md, 10px); padding: 8px 10px; display: flex; flex-direction: column; gap: 2px; min-width: 0; }+.ern-stat-k { font-size: var(--text-2xs, .6875rem); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-faint, #777); }+.ern-stat-v { font-family: var(--font-mono, monospace); font-size: var(--text-md, .8125rem); color: var(--ink, #e8e8e8); font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }+.ern-stat-s { font-size: var(--text-2xs, .6875rem); color: var(--ink-dim, #999); }+.ern-h { margin: 0; font-size: var(--text-2xs, .6875rem); text-transform: uppercase; letter-spacing: .08em; color: var(--ink-faint, #777); font-weight: 600; }+.ern-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }+.ern-row { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); background: var(--surface-1, rgba(255,255,255,.03)); min-width: 0; }+a.ern-row { color: inherit; text-decoration: none; transition: border-color var(--duration-fast, .14s) var(--ease-standard, ease), background var(--duration-fast, .14s) var(--ease-standard, ease); }+a.ern-row:hover { border-color: var(--stroke-strong, rgba(255,255,255,.22)); background: var(--surface-2, rgba(255,255,255,.05)); }+a.ern-row:active { background: var(--surface-3, rgba(255,255,255,.08)); }+.ern-row-main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }+.ern-row-t { font-weight: 600; font-size: var(--text-md, .8125rem); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.ern-row-d { font-size: var(--text-2xs, .6875rem); color: var(--ink-dim, #999); overflow-wrap: anywhere; }+.ern-row-v { font-family: var(--font-mono, monospace); font-size: var(--text-sm, .78rem); text-align: right; white-space: nowrap; font-variant-numeric: tabular-nums; }+.ern-row-v small { display: block; color: var(--ink-dim, #999); font-size: var(--text-2xs, .6875rem); }+.ern-pill { display: inline-block; font-size: 10px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; padding: 1px 6px; border-radius: var(--radius-pill, 999px); border: 1px solid var(--stroke, rgba(255,255,255,.12)); color: var(--ink-dim, #999); margin-left: 6px; vertical-align: 1px; }+.ern-pill.ok { color: var(--success, #34d399); border-color: color-mix(in srgb, var(--success, #34d399) 40%, transparent); }+.ern-foot { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font-size: var(--text-2xs, .6875rem); color: var(--ink-faint, #777); }+.ern-foot.stale { color: var(--warn, #f59e0b); }+.ern-how summary { cursor: pointer; color: var(--ink-dim, #999); text-decoration: underline; text-underline-offset: 2px; border-radius: 4px; }+.ern-how summary:hover { color: var(--ink, #e8e8e8); }+.ern-how summary:focus-visible, .ern a:focus-visible, .ern button:focus-visible { outline: var(--focus-ring-width, 2px) solid var(--focus-ring-color, #a78bfa); outline-offset: var(--focus-ring-offset, 2px); }+.ern-how p { margin: 6px 0 0; line-height: 1.5; color: var(--ink-dim, #999); font-size: var(--text-xs, .72rem); }+.ern-empty { display: flex; flex-direction: column; gap: 10px; align-items: flex-start; padding: 4px 0; }+.ern-empty p { margin: 0; font-size: var(--text-sm, .78rem); color: var(--ink-dim, #999); line-height: 1.5; }+.ern-btn { display: inline-flex; align-items: center; gap: 6px; font: inherit; font-size: var(--text-sm, .78rem); font-weight: 600; color: var(--ink-bright, #fff); background: var(--surface-2, rgba(255,255,255,.06)); border: 1px solid var(--stroke-strong, rgba(255,255,255,.18)); border-radius: var(--radius-pill, 999px); padding: 6px 14px; cursor: pointer; text-decoration: none; transition: background var(--duration-fast, .14s) var(--ease-standard, ease), transform var(--duration-fast, .14s) var(--ease-standard, ease); }+.ern-btn:hover { background: var(--surface-3, rgba(255,255,255,.1)); transform: translateY(-1px); }+.ern-btn:active { transform: translateY(0); }+.ern-err { color: var(--danger, #f87171); }+.ern-fade { animation: ern-in var(--duration-base, .24s) var(--ease-emphasized, cubic-bezier(.22,1,.36,1)) both; }+@keyframes ern-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }+@media (prefers-reduced-motion: reduce) { .ern-fade { animation: none; } }+`;+ (document.head || document.documentElement).appendChild(style);+}++function skeleton() {+ return `<div class="ern" aria-busy="true" aria-label="Loading earnings">+ <div class="ern-sk ern-sk-hero"></div>+ <div class="ern-sk ern-sk-row"></div>+ <div class="ern-sk ern-sk-row short"></div>+ </div>`;+}++const COIN_STATUS = {+ counted: null,+ other_wallet: 'not counted',+ not_reported: 'not reported',+};++function coinRow(c) {+ const label = c.symbol ? `$${c.symbol}` : c.name || shortAddr(c.mint);+ let detail;+ let value;+ if (c.status === 'not_reported') {+ detail = c.error ? 'pump.fun has not reported fees for this coin yet' : 'Waiting for the first earnings snapshot';+ value = '<span>not reported</span>';+ } else {+ const shared = Number(c.wallet_coin_count) > 1 ? ` · combined for ${c.wallet_coin_count} coins from the same wallet` : '';+ detail =+ c.status === 'other_wallet'+ ? `Fees go to ${esc(shortAddr(c.creator))}, not this agent's wallet${shared}`+ : `Unclaimed ${esc(fmtSol(c.unclaimed_sol))}${shared}`;+ value = `${esc(fmtSol(c.earned_sol))}${c.earned_usd != null ? `<small>${esc(fmtUsd(c.earned_usd))}</small>` : ''}`;+ }+ const pill = COIN_STATUS[c.status] ? `<span class="ern-pill">${COIN_STATUS[c.status]}</span>` : '';+ return `<li><a class="ern-row" href="${esc(c.url)}" aria-label="${esc(label)} coin page">+ <span class="ern-row-main">+ <span class="ern-row-t">${esc(label)}${pill}</span>+ <span class="ern-row-d">${detail}</span>+ </span>+ <span class="ern-row-v">${value}</span>+ </a></li>`;+}++function claimRow(c) {+ const who = c.source === 'autonomous' ? 'Autonomous claim' : 'Claimed by owner';+ return `<li><a class="ern-row" href="${esc(c.explorer)}" target="_blank" rel="noopener noreferrer" aria-label="${esc(who)} on Solscan">+ <span class="ern-row-main">+ <span class="ern-row-t">${esc(who)}</span>+ <span class="ern-row-d">${esc(relTime(c.at))} · ${esc(shortAddr(c.signature))} · Solscan ↗</span>+ </span>+ <span class="ern-row-v">${c.sol != null ? esc(fmtSol(c.sol)) : 'swept'}</span>+ </a></li>`;+}++function footer(d) {+ const updated = d.refreshed_at ? `Updated ${esc(relTime(d.refreshed_at))}` : 'Not refreshed yet';+ return `<div class="ern-foot${d.stale ? ' stale' : ''}">+ <span>${d.stale ? 'Figures may be out of date. ' : ''}${updated}</span>+ <details class="ern-how"><summary>How it's calculated</summary><p>${esc(d.method)}</p></details>+ </div>`;+}++function render(d) {+ const lifetime = d.lifetime_creator_fees || {};+ const service = d.service_income || {};+ const totalSol = Number(lifetime.earned_sol || 0) + Number(service.sol || 0);+ const totalUsd =+ lifetime.earned_usd != null || service.usd+ ? Number(lifetime.earned_usd || 0) + Number(service.usd || 0)+ : null;+ const rank = d.rank+ ? `<a class="ern-rank" href="${esc(d.rank.url)}" title="Rank on the earnings leaderboard">#${d.rank.position} ${d.rank.window === '7d' ? 'this week' : d.rank.window === '24h' ? 'today' : d.rank.window === '30d' ? 'this month' : 'all time'}</a>`+ : '';++ if (!d.has_coins && !service.usd) {+ return {+ state: 'empty',+ html: `<div class="ern ern-fade"><div class="ern-empty">+ <p>No coin launched yet. When this agent launches a coin on pump.fun, every trade pays it a creator fee and the total shows up here.</p>+ <a class="ern-btn" href="/launch">Launch a coin →</a>+ </div>${footer({ ...d, refreshed_at: null, stale: false })}</div>`,+ };+ }++ const coins = d.coins || [];+ const claims = d.claims || [];+ const zero = totalSol === 0;+ const stats = [+ ['Claimed', fmtSol(lifetime.claimed_sol), fmtUsd(lifetime.claimed_usd)],+ ['Unclaimed', fmtSol(lifetime.unclaimed_sol), fmtUsd(lifetime.unclaimed_usd)],+ ];+ if (service.usd) {+ stats.push([+ 'Service income',+ fmtUsd(service.usd),+ `${service.skill_sales_count} sales · ${service.hires_count} hires`,+ ]);+ }+ const html = `<div class="ern ern-fade">+ <div class="ern-hero">+ <span class="ern-total">${esc(fmtSol(totalSol))}</span>+ ${totalUsd != null ? `<span class="ern-usd">${esc(fmtUsd(totalUsd))}</span>` : ''}+ ${rank}+ </div>+ <p class="ern-sub">${+ zero+ ? 'Nothing earned yet. Creator fees accrue with every trade of this agent’s coin.'+ : 'Lifetime creator fees from its coins' + (service.usd ? ' plus service income' : '') + '.'+ }</p>+ <div class="ern-stats">${stats+ .map(+ ([k, v, s]) =>+ `<div class="ern-stat"><span class="ern-stat-k">${esc(k)}</span><span class="ern-stat-v">${esc(v)}</span>${s ? `<span class="ern-stat-s">${esc(s)}</span>` : ''}</div>`,+ )+ .join('')}</div>+ ${coins.length ? `<h4 class="ern-h">Per coin</h4><ul class="ern-list">${coins.map(coinRow).join('')}</ul>` : ''}+ ${claims.length ? `<h4 class="ern-h">Claims</h4><ul class="ern-list">${claims.map(claimRow).join('')}</ul>` : ''}+ ${footer(d)}+ </div>`;+ return { state: zero ? 'zero' : 'earned', html };+}++/**+ * Mount the Earned card for one agent.+ * @param {{ mount: HTMLElement, agentId: string, onState?: (state: string, data?: object) => void }} opts+ */+export function mountEarningsCard({ mount, agentId, onState = () => {} }) {+ ensureStyles();+ let ctrl = null;+ let destroyed = false;++ async function load() {+ ctrl?.abort();+ ctrl = new AbortController();+ mount.innerHTML = skeleton();+ onState('loading');+ try {+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}/earnings`, {+ credentials: 'include',+ signal: ctrl.signal,+ });+ if (!r.ok) throw new Error(r.status === 404 ? 'not_found' : `HTTP ${r.status}`);+ const data = await r.json();+ if (destroyed) return;+ const { state, html } = render(data);+ mount.innerHTML = html;+ onState(state, data);+ } catch (err) {+ if (destroyed || err?.name === 'AbortError') return;+ mount.innerHTML = `<div class="ern ern-fade"><div class="ern-empty">+ <p class="ern-err">Couldn't load earnings${err?.message === 'not_found' ? ': this agent is private or no longer exists.' : '. The earnings service did not answer.'}</p>+ <button type="button" class="ern-btn" data-ern-retry>Try again</button>+ </div></div>`;+ mount.querySelector('[data-ern-retry]')?.addEventListener('click', load);+ onState('error');+ }+ }++ load();+ return {+ refresh: load,+ destroy() {+ destroyed = true;+ ctrl?.abort();+ mount.innerHTML = '';+ },+ };+}diff --git a/tests/mcp-resources.test.js b/tests/mcp-resources.test.jsindex 8ffa727cc..c5a11d7ba 100644--- a/tests/mcp-resources.test.js+++ b/tests/mcp-resources.test.js@@ -141,6 +141,7 @@ describe('resource registry', () => {'three://agents/{agentId}/orders','three://agents/{agentId}/dca','three://agents/{agentId}/intents',+ 'three://agents/{agentId}/earnings','three://marketplace','three://models','three://wallets',diff --git a/vercel.json b/vercel.jsonindex 7f872edc5..6d732cb4e 100644--- a/vercel.json+++ b/vercel.json@@ -718,6 +718,10 @@"src": "/api/agents/([^/]+)/economy","dest": "/api/agents/[id]/economy?id=$1"},+ {+ "src": "/api/agents/([^/]+)/earnings",+ "dest": "/api/agents/[id]/earnings?id=$1"+ },{"src": "/api/agents/([^/]+)/skills-pricing","dest": "/api/agents/[id]/skills-pricing?id=$1"@@ -1246,6 +1250,14 @@"src": "/quests/?","dest": "/quests.html"},+ {+ "src": "/duels/?",+ "dest": "/duels.html"+ },+ {+ "src": "/duels/([^/.]+)/?",+ "dest": "/duel.html"+ },{"src": "/fade/?","dest": "/fade.html"@@ -6673,6 +6685,10 @@"path": "/api/cron/launcher-claimer","schedule": "*/5 * * * *"},+ {+ "path": "/api/cron/creator-earnings-snapshot",+ "schedule": "11,41 * * * *"+ },{"path": "/api/cron/fee-bridge","schedule": "*/10 * * * *"@@ -6808,6 +6824,10 @@{"path": "/api/cron/forge-web-variants","schedule": "*/10 * * * *"+ },+ {+ "path": "/api/cron/duels-tick",+ "schedule": "*/15 * * * *"}]}