Skip to content

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

feat(payouts): add the creator payouts API, hourly distribution cron and reconcile cron with routes

nirholas00dd6e509984
diff --git a/api/_lib/agent-earnings.js b/api/_lib/agent-earnings.js
index 8fe97233a..a0761a499 100644
--- a/api/_lib/agent-earnings.js
+++ b/api/_lib/agent-earnings.js
@@ -36,6 +36,7 @@ import { sql } from './db.js';
import { solPriceUsd } from './sol-price.js';
import { SOLANA_USDC_MINT } from '../payments/_config.js';
import { cdnUrl } from './r2.js';
+import { getAgentPayouts } from './creator-payouts.js';
// A portrait is decoration: a misconfigured URL resolver degrades it to null
// instead of failing the board. Routed through /cdn/ (not a raw publicUrl())
@@ -301,7 +302,7 @@ async function rankedAgents(window, price, back = 0) {
*/
export async function getAgentEarnings(agent, { window: rawWindow = 'all' } = {}) {
const window = normalizeWindow(rawWindow);
- const [price, totals, lifetimeTotals, coins, devnet, claims] = await Promise.all([
+ const [price, totals, lifetimeTotals, coins, devnet, claims, payouts] = await Promise.all([
solPriceUsd(),
totalsByAgent(window, { agentId: agent.id }),
window === 'all' ? null : totalsByAgent('all', { agentId: agent.id }),
@@ -318,6 +319,8 @@ export async function getAgentEarnings(agent, { window: rawWindow = 'all' } = {}
`,
sql`select count(*)::int as n from pump_agent_mints where agent_id = ${agent.id} and network = 'devnet'`,
recentClaims(agent.id),
+ // The payout ledger is an additive block: a failure here must not hide earnings.
+ getAgentPayouts(agent.id).catch(() => null),
]);
const t = totals.get(agent.id) || emptyTotals();
const life = (lifetimeTotals ? lifetimeTotals.get(agent.id) : totals.get(agent.id)) || emptyTotals();
@@ -325,7 +328,10 @@ export async function getAgentEarnings(agent, { window: rawWindow = 'all' } = {}
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 coinRows = coins.map((c) => ({
+ ...shapeCoin(c, agent.solana_address, price),
+ payout: payouts?.per_coin?.[c.mint] || { sent_sol: 0, pending_sol: 0, held_sol: 0 },
+ }));
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;
@@ -350,6 +356,14 @@ export async function getAgentEarnings(agent, { window: rawWindow = 'all' } = {}
},
coins: coinRows,
claims,
+ payouts: payouts && {
+ ...payouts,
+ total_earned_sol: lifeSol(life.lifetime_lamports),
+ total_claimed_sol: lifeSol(life.claimed_lamports),
+ // Earned and claimed are the lifetime creator-fee figures; sent, pending and
+ // held are the creator's share of recorded claims (claim minus the buyback earmark).
+ basis: 'Earned and claimed are lifetime creator fees. Sent, pending and held are your share of each recorded claim after the buyback earmark.',
+ },
rank,
refreshed_at: refreshedAt,
stale: refreshedAt ? Date.now() - new Date(refreshedAt).getTime() > 2 * 3_600_000 : false,
diff --git a/api/creator-payouts.js b/api/creator-payouts.js
new file mode 100644
index 000000000..8aa343db3
--- /dev/null
+++ b/api/creator-payouts.js
@@ -0,0 +1,128 @@
+// /api/creator-payouts: where an agent's creator-fee share is paid, and the
+// record of every distribution.
+//
+// GET ?info=1 Public. The cadence of each stage, read from
+// the vercel.json cron definitions, and the
+// per-$100 flow, generated from the split policy.
+// GET ?agent=<uuid> Owner. Payout wallet (and any pending change),
+// totals, held reasons, recent distributions.
+// GET ?agent=<uuid>&format=csv Owner. Every distribution as CSV.
+// POST { action: 'challenge', agent_id, wallet }
+// Owner session. The message the wallet must sign.
+// POST { action: 'register', agent_id, wallet, message, signature, grant }
+// Owner session + step-up grant (action 'stepup'
+// on /api/wallet-whitelist with kind 'payout_wallet'
+// and op { wallet }). Registers or stages a change.
+// POST { action: 'cancel', agent_id }
+// Owner session. Drops a staged wallet change.
+//
+// Library: api/_lib/creator-payouts.js. Doc: docs/creator-payouts.md.
+
+import { readFileSync } from 'node:fs';
+import { getRequestUser } from './_lib/auth.js';
+import { cors, json, method, wrap, error, readJson, rateLimited } from './_lib/http.js';
+import { requireCsrf } from './_lib/csrf.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { WhitelistError, STEP_UP_METHODS } from './_lib/destination-whitelist.js';
+import { getAgentPayouts, listDistributions, issueRegistrationChallenge, registerPayoutWallet, cancelPendingWallet } from './_lib/creator-payouts.js';
+import { distributionsToCsv, flowPer100, payoutSchedule, MIN_PAYOUT_LAMPORTS, LAMPORTS_PER_SOL } from './_lib/creator-payouts-core.js';
+import { sql } from './_lib/db.js';
+
+function readCrons() {
+ try {
+ const parsed = JSON.parse(readFileSync(new URL('../vercel.json', import.meta.url), 'utf8'));
+ return Array.isArray(parsed.crons) ? parsed.crons : [];
+ } catch {
+ return [];
+ }
+}
+
+function info() {
+ const crons = readCrons();
+ return {
+ schedule: payoutSchedule(crons),
+ schedule_source: crons.length ? 'vercel.json crons' : 'unavailable',
+ flow: flowPer100(),
+ minimum_payout_sol: MIN_PAYOUT_LAMPORTS / LAMPORTS_PER_SOL,
+ };
+}
+
+function actorFor(user) {
+ if (user.sid) return { kind: 'owner', userId: user.id, sessionId: user.sid };
+ return { kind: user.connector ? 'oauth' : 'api_key', userId: user.id, sessionId: null };
+}
+
+async function ownedAgent(agentId, userId) {
+ if (!/^[0-9a-f-]{36}$/i.test(String(agentId || ''))) throw new WhitelistError(400, 'invalid_agent_id', 'agent must be a UUID');
+ const [a] = await sql`SELECT id, name, user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;
+ if (!a) throw new WhitelistError(404, 'agent_not_found', 'Agent not found.');
+ if (a.user_id !== userId) throw new WhitelistError(403, 'forbidden', 'Only the owner of this agent can see its payout records.');
+ return a;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+ const params = new URL(req.url, 'http://x').searchParams;
+
+ try {
+ if (req.method === 'GET' && params.get('info') === '1') {
+ const rl = await limits.creatorPayoutInfoIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ return json(res, 200, info(), { 'cache-control': 'public, max-age=300, s-maxage=300' });
+ }
+
+ const user = await getRequestUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.creatorPayoutUser(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ if (req.method === 'GET') {
+ const agent = await ownedAgent(params.get('agent'), user.id);
+ if (params.get('format') === 'csv') {
+ const all = [];
+ for (let offset = 0; offset < 20_000; offset += 1000) {
+ const page = await listDistributions(agent.id, { limit: 1000, offset });
+ all.push(...page);
+ if (page.length < 1000) break;
+ }
+ const csv = distributionsToCsv(all.map((r) => ({ ...r })));
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/csv; charset=utf-8');
+ res.setHeader('content-disposition', `attachment; filename="creator-payouts-${agent.id}.csv"`);
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('x-content-type-options', 'nosniff');
+ return res.end(csv);
+ }
+ const payouts = await getAgentPayouts(agent.id);
+ return json(res, 200, { agent: { id: agent.id, name: agent.name }, payouts, step_up_methods: STEP_UP_METHODS, ...info() }, { 'cache-control': 'no-store' });
+ }
+
+ if (!(await requireCsrf(req, res, user.id))) return;
+ const body = (await readJson(req)) || {};
+ const actor = actorFor(user);
+ const grantId = typeof body.grant === 'string' ? body.grant : null;
+
+ switch (body.action) {
+ case 'challenge':
+ return json(res, 200, await issueRegistrationChallenge({ agentId: body.agent_id, userId: user.id, wallet: String(body.wallet || '') }), { 'cache-control': 'no-store' });
+ case 'register':
+ return json(
+ res,
+ 200,
+ await registerPayoutWallet({
+ actor, agentId: body.agent_id, wallet: String(body.wallet || ''),
+ message: String(body.message || ''), signature: String(body.signature || ''), grantId, req,
+ }),
+ { 'cache-control': 'no-store' },
+ );
+ case 'cancel':
+ return json(res, 200, await cancelPendingWallet({ actor, agentId: body.agent_id, req }), { 'cache-control': 'no-store' });
+ default:
+ return error(res, 400, 'invalid_action', 'action must be challenge, register or cancel');
+ }
+ } catch (e) {
+ if (e instanceof WhitelistError) return error(res, e.status, e.code, e.message, e.extra);
+ throw e;
+ }
+});
diff --git a/api/cron/creator-payout-distribute.js b/api/cron/creator-payout-distribute.js
new file mode 100644
index 000000000..1bc820aed
--- /dev/null
+++ b/api/cron/creator-payout-distribute.js
@@ -0,0 +1,23 @@
+// @ts-check
+// GET/POST /api/cron/creator-payout-distribute: record each new creator-fee
+// claim's creator share and send what can be sent to the registered payout
+// wallets (hourly, Cloud Scheduler). The rules live in api/_lib/creator-payouts.js.
+//
+// Sending is off until the operator sets CREATOR_PAYOUTS_LIVE=true; until then
+// every share is recorded and held with the reason 'payouts_paused', so the
+// earnings page is accurate and enabling it later sends the backlog.
+//
+// Response: { ok, live, ingested, agents, sent_batches, sent_sol, held_agents, failed[], promoted }.
+//
+// Auth: CRON_SECRET Bearer (same gate as every cron endpoint).
+
+import { json, method, wrapCron } from '../_lib/http.js';
+import { requireCron } from '../_lib/cron-auth.js';
+import { runDistribution, payoutsLive } from '../_lib/creator-payouts.js';
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+ const out = await runDistribution();
+ return json(res, 200, { ok: true, live: payoutsLive(), ...out });
+});
diff --git a/api/cron/creator-payout-reconcile.js b/api/cron/creator-payout-reconcile.js
new file mode 100644
index 000000000..e00e94112
--- /dev/null
+++ b/api/cron/creator-payout-reconcile.js
@@ -0,0 +1,19 @@
+// @ts-check
+// GET/POST /api/cron/creator-payout-reconcile: check our creator-payout records
+// against the chain and alert on drift (every three hours, Cloud Scheduler).
+// Read-only on the chain; the checks are in reconcilePayouts().
+//
+// Response: { ok, checked: { stuck_batches, sent_signatures, vaults }, drift[] }.
+//
+// Auth: CRON_SECRET Bearer (same gate as every cron endpoint).
+
+import { json, method, wrapCron } from '../_lib/http.js';
+import { requireCron } from '../_lib/cron-auth.js';
+import { reconcilePayouts } from '../_lib/creator-payouts.js';
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+ const out = await reconcilePayouts();
+ return json(res, 200, out);
+});
diff --git a/vercel.json b/vercel.json
index 9c33aa7de..48a55b0ad 100644
--- a/vercel.json
+++ b/vercel.json
@@ -776,6 +776,14 @@
"src": "/api/agents/([^/]+)/economy",
"dest": "/api/agents/[id]/economy?id=$1"
},
+ {
+ "src": "/api/creator-payouts",
+ "dest": "/api/creator-payouts.js"
+ },
+ {
+ "src": "/creator/payouts/?",
+ "dest": "/creator-payouts.html"
+ },
{
"src": "/api/agents/([^/]+)/earnings",
"dest": "/api/agents/[id]/earnings?id=$1"
@@ -7447,6 +7455,14 @@
"path": "/api/cron/creator-earnings-snapshot",
"schedule": "11,41 * * * *"
},
+ {
+ "path": "/api/cron/creator-payout-distribute",
+ "schedule": "20 * * * *"
+ },
+ {
+ "path": "/api/cron/creator-payout-reconcile",
+ "schedule": "50 */3 * * *"
+ },
{
"path": "/api/cron/fee-bridge",
"schedule": "*/10 * * * *"