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(revenue): add revenue routes, ledger reconcile and reinvest crons, creator payouts page and docs, with tests

nirholascdd6d5c763cc
diff --git a/api/_lib/agent-earnings.js b/api/_lib/agent-earnings.js
index a0761a499..213dcaeb8 100644
--- a/api/_lib/agent-earnings.js
+++ b/api/_lib/agent-earnings.js
@@ -356,8 +356,12 @@ export async function getAgentEarnings(agent, { window: rawWindow = 'all' } = {}
},
coins: coinRows,
claims,
+ // Public read model: the registered wallet and totals only. A staged wallet
+ // change and the cooldown stay on the owner's /creator/payouts page.
payouts: payouts && {
...payouts,
+ wallet: { ...payouts.wallet, pending: null },
+ recent_distributions: payouts.recent_distributions.map(({ payout_wallet, ...rest }) => rest),
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
diff --git a/api/_lib/revenue-reconcile.js b/api/_lib/revenue-reconcile.js
index 0485bb91c..7234bc49d 100644
--- a/api/_lib/revenue-reconcile.js
+++ b/api/_lib/revenue-reconcile.js
@@ -15,7 +15,7 @@ import { sql } from './db.js';
import { solanaConnection } from './solana/connection.js';
import { insertNotification } from './notify.js';
import { syncLedger } from './revenue-ledger.js';
-import { SOURCE_BY_KEY } from './revenue-ledger-core.js';
+import { SOURCE_BY_KEY, reachedMilestones } from './revenue-ledger-core.js';
const CHAIN_SAMPLE = 120;
const NOT_FOUND_GRACE_MS = 2 * 3600 * 1000;
@@ -109,6 +109,34 @@ async function chainVerify() {
return { checked: rows.length, mismatches, not_found: notFound, flagged };
}
+/**
+ * Announce lifetime-revenue milestones once per agent. Revenue only (trading
+ * PnL is not income), mainnet only, valued entries only. The unique
+ * (scope, milestone) row makes each fire exactly once.
+ */
+export async function announceMilestones() {
+ const totals = await sql`
+ select user_id, agent_id, sum(usd)::float8 as usd from revenue_ledger_entries
+ where kind = 'revenue' and counted and usd is not null and agent_id is not null group by user_id, agent_id`;
+ let announced = 0;
+ for (const t of totals) {
+ for (const m of reachedMilestones(t.usd)) {
+ const [row] = await sql`
+ insert into revenue_milestones (user_id, scope, milestone, usd_at_reach)
+ values (${t.user_id}, ${`agent:${t.agent_id}`}, ${`revenue_usd_${m}`}, ${t.usd})
+ on conflict (scope, milestone) do nothing returning id`;
+ if (!row) continue;
+ announced++;
+ insertNotification(t.user_id, 'revenue_milestone', {
+ title: `Your agent has earned $${m.toLocaleString('en-US')}`,
+ body: 'Lifetime revenue across creator fees, skill sales, hires, royalties and invoices.',
+ link: '/earnings',
+ });
+ }
+ }
+ return announced;
+}
+
/**
* One reconcile run. Records it in revenue_reconcile_runs and alerts owners
* whose entries are flagged, and every owner when a source drifted.
@@ -119,6 +147,7 @@ export async function runReconcile() {
const synced = await syncLedger({});
const checks = await dbChecks();
const chain = await chainVerify().catch((e) => ({ checked: 0, mismatches: 0, not_found: 0, flagged: [], error: e?.message }));
+ const milestones = await announceMilestones().catch(() => 0);
const [{ n }] = await sql`select count(*)::int as n from revenue_ledger_entries`;
const dbDrift = checks.filter((c) => c.drift).length;
const status = dbDrift || chain.mismatches || chain.not_found ? 'drift' : chain.error ? 'error' : 'clean';
@@ -156,7 +185,7 @@ export async function runReconcile() {
chain_mismatches = ${chain.mismatches}, chain_not_found = ${chain.not_found}, alerted_users = ${alerted},
error = ${chain.error || null}
where id = ${run.id}`;
- return { id: run.id, status, synced, entries_total: n, db_checks: checks, chain: { checked: chain.checked, mismatches: chain.mismatches, not_found: chain.not_found, error: chain.error || null }, alerted };
+ return { id: run.id, status, synced, milestones, entries_total: n, db_checks: checks, chain: { checked: chain.checked, mismatches: chain.mismatches, not_found: chain.not_found, error: chain.error || null }, alerted };
} catch (err) {
await sql`update revenue_reconcile_runs set finished_at = now(), status = 'error', error = ${String(err?.message || err).slice(0, 500)} where id = ${run.id}`;
throw err;
diff --git a/api/_lib/revenue-reinvest.js b/api/_lib/revenue-reinvest.js
new file mode 100644
index 000000000..b55a1109d
--- /dev/null
+++ b/api/_lib/revenue-reinvest.js
@@ -0,0 +1,502 @@
+// Reinvest rules: the owner's standing instruction for what an agent's income
+// does next ("20% to model credits, 20% into a DCA of the agent's own coin,
+// 10% to a tools budget, keep the rest").
+//
+// Safety model, in the order it bites:
+// 1. A rule only runs after the owner confirmed its exact hash (ruleHash).
+// Any edit clears the confirmation. The confirmation screen shows every
+// destination, the split and both caps (see rulePreview).
+// 2. Each period runs once: the run row is unique on (rule, period), every
+// leg has its own idempotency key, and a leg that already executed is
+// never sent again.
+// 3. Per-run and lifetime caps scale all legs by one factor (planRun).
+// 4. Every leg goes through the same spend guards as any other agent spend.
+// A guard that wants the owner (step-up, burner cap) parks the leg in the
+// approvals inbox instead of failing; nothing moves until the owner says yes.
+// 5. Repeated failures pause the rule and tell the owner.
+//
+// Legs:
+// model_credits USDC from the agent wallet to the platform deposit wallet,
+// then the owner's credit balance is credited from that signature.
+// tools_budget the same on-chain deposit, then the credits are moved into the
+// named x402 payment session's budget.
+// dca_own_coin a pump.fun buy of the agent's own coin through the standard
+// trade pipeline (kill switch, caps, firewall, ledger).
+
+import { sql } from './db.js';
+import { insertNotification } from './notify.js';
+import {
+ RuleError, normalizeRule, ruleHash, lastPeriod, runKey, legKey, planRun, LEG_LABELS, usdToUsdcAtomics, formatAtomics,
+} from './revenue-ledger-core.js';
+import { cachedSolUsd } from './trader-stats.js';
+
+export const FAILURES_BEFORE_PAUSE = 3;
+const RULE_COLS = sql`id, user_id, agent_id, name, status, network, period, basis, legs, per_run_cap_usd, lifetime_cap_usd, min_run_usd,
+ confirmed_hash, confirmed_at, paused_reason, consecutive_failures, active_from, created_at, updated_at`;
+
+const num = (v) => (v == null ? null : Number(v));
+
+function fail(status, code, message) {
+ return Object.assign(new Error(message), { status, code });
+}
+
+export function ruleView(r) {
+ const hash = ruleHash({ ...r, per_run_cap_usd: r.per_run_cap_usd, lifetime_cap_usd: r.lifetime_cap_usd });
+ return {
+ id: r.id, agent_id: r.agent_id, name: r.name, status: r.status, network: r.network, period: r.period, basis: r.basis,
+ legs: r.legs, per_run_cap_usd: num(r.per_run_cap_usd), lifetime_cap_usd: num(r.lifetime_cap_usd), min_run_usd: num(r.min_run_usd),
+ confirmed: Boolean(r.confirmed_hash) && r.confirmed_hash === hash,
+ confirmed_at: r.confirmed_at, paused_reason: r.paused_reason, consecutive_failures: r.consecutive_failures,
+ active_from: r.active_from, created_at: r.created_at, updated_at: r.updated_at,
+ hash,
+ };
+}
+
+async function ownedAgent(agentId, userId) {
+ const [a] = await sql`select id, user_id, name, meta from agent_identities where id = ${agentId} and user_id = ${userId} and deleted_at is null`;
+ if (!a) throw fail(404, 'not_found', 'Agent not found.');
+ return a;
+}
+
+async function assertSession(sessionId, userId) {
+ const [s] = await sql`select id, status, network from payment_sessions where id = ${sessionId} and user_id = ${userId}`;
+ if (!s) throw new RuleError('That payment session does not exist or is not yours.');
+ if (s.status !== 'active') throw new RuleError(`That payment session is ${s.status}. Pick an active one.`);
+ return s;
+}
+
+export async function listRules({ userId, agentId = null }) {
+ const rows = await sql`select ${RULE_COLS} from revenue_reinvest_rules where user_id = ${userId} ${agentId ? sql`and agent_id = ${agentId}` : sql``} order by created_at desc`;
+ return rows.map(ruleView);
+}
+
+export async function getRule(ruleId, userId) {
+ const [r] = await sql`select ${RULE_COLS} from revenue_reinvest_rules where id = ${ruleId} and user_id = ${userId}`;
+ if (!r) throw fail(404, 'not_found', 'Rule not found.');
+ return r;
+}
+
+export async function createRule({ userId, agentId, body }) {
+ await ownedAgent(agentId, userId);
+ const rule = normalizeRule(body);
+ for (const l of rule.legs) if (l.kind === 'tools_budget') await assertSession(l.session_id, userId);
+ const [row] = await sql`
+ insert into revenue_reinvest_rules (user_id, agent_id, name, network, period, basis, legs, per_run_cap_usd, lifetime_cap_usd, min_run_usd)
+ values (${userId}, ${agentId}, ${rule.name}, ${rule.network}, ${rule.period}, ${rule.basis}, ${JSON.stringify(rule.legs)}::jsonb,
+ ${rule.per_run_cap_usd}, ${rule.lifetime_cap_usd}, ${rule.min_run_usd})
+ returning ${RULE_COLS}`;
+ return ruleView(row);
+}
+
+/** Editing clears the confirmation and returns the rule to draft: the owner must confirm the new terms. */
+export async function updateRule({ ruleId, userId, body }) {
+ const cur = await getRule(ruleId, userId);
+ const rule = normalizeRule({ ...cur, ...body, legs: body.legs ?? cur.legs });
+ for (const l of rule.legs) if (l.kind === 'tools_budget') await assertSession(l.session_id, userId);
+ const [row] = await sql`
+ update revenue_reinvest_rules set name = ${rule.name}, network = ${rule.network}, period = ${rule.period}, basis = ${rule.basis},
+ legs = ${JSON.stringify(rule.legs)}::jsonb, per_run_cap_usd = ${rule.per_run_cap_usd}, lifetime_cap_usd = ${rule.lifetime_cap_usd},
+ min_run_usd = ${rule.min_run_usd}, confirmed_hash = null, confirmed_at = null, status = 'draft', active_from = null,
+ paused_reason = null, consecutive_failures = 0, updated_at = now()
+ where id = ${ruleId} and user_id = ${userId}
+ returning ${RULE_COLS}`;
+ return ruleView(row);
+}
+
+export async function deleteRule({ ruleId, userId }) {
+ const gone = await sql`delete from revenue_reinvest_rules where id = ${ruleId} and user_id = ${userId} returning id`;
+ if (!gone.length) throw fail(404, 'not_found', 'Rule not found.');
+}
+
+/**
+ * The owner's explicit yes. `hash` must be the hash of the terms the owner was
+ * shown; if the rule changed since, the confirm is refused and nothing activates.
+ * Only periods that end after `active_from` are ever run, so confirming never
+ * back-fills income earned before the owner said yes.
+ */
+export async function confirmRule({ ruleId, userId, hash }) {
+ const cur = await getRule(ruleId, userId);
+ const now = ruleView(cur);
+ if (!hash || hash !== now.hash) throw fail(409, 'rule_changed', 'The rule changed since you reviewed it. Review the terms again and confirm.');
+ const [row] = await sql`
+ update revenue_reinvest_rules set confirmed_hash = ${now.hash}, confirmed_at = now(), status = 'active',
+ active_from = coalesce(active_from, now()), paused_reason = null, consecutive_failures = 0, updated_at = now()
+ where id = ${ruleId} and user_id = ${userId}
+ returning ${RULE_COLS}`;
+ return ruleView(row);
+}
+
+export async function pauseRule({ ruleId, userId, reason = 'Paused by you.' }) {
+ await getRule(ruleId, userId);
+ const [row] = await sql`
+ update revenue_reinvest_rules set status = 'paused', paused_reason = ${reason}, updated_at = now()
+ where id = ${ruleId} and user_id = ${userId} returning ${RULE_COLS}`;
+ return ruleView(row);
+}
+
+// ── what a run would do ─────────────────────────────────────────────────────
+
+async function baseIncome(rule, start, end) {
+ const rows = await sql`
+ select kind, coalesce(sum(usd), 0)::float8 as usd, count(*)::int as n
+ from revenue_ledger_entries
+ where agent_id = ${rule.agent_id} and user_id = ${rule.user_id} and counted and usd is not null
+ and network = ${rule.network} and occurred_at >= ${start} and occurred_at < ${end}
+ group by kind`;
+ const revenue = rows.find((r) => r.kind === 'revenue')?.usd || 0;
+ const pnl = rows.find((r) => r.kind === 'pnl')?.usd || 0;
+ const trading = rule.basis === 'revenue_and_trading_profit' ? Math.max(0, pnl) : 0;
+ return { base: revenue + trading, breakdown: { revenue_usd: revenue, trading_pnl_usd: pnl, trading_profit_counted_usd: trading, entries: rows.reduce((a, r) => a + r.n, 0) } };
+}
+
+async function lifetimeSpent(ruleId) {
+ const [r] = await sql`
+ select coalesce(sum(l.capped_usd), 0)::float8 as usd
+ from revenue_reinvest_legs l join revenue_reinvest_runs r on r.id = l.run_id
+ where r.rule_id = ${ruleId} and r.mode = 'live' and l.status in ('executed', 'awaiting_approval')`;
+ return r.usd;
+}
+
+async function ownCoinMint(agentId, network) {
+ const [m] = await sql`select mint, symbol from pump_agent_mints where agent_id = ${agentId} and network = ${network} order by created_at desc limit 1`;
+ return m || null;
+}
+
+/** The confirmation table: every destination, amount basis and cap, from live data. */
+export async function rulePreview({ ruleId, userId, now = Date.now() }) {
+ const cur = await getRule(ruleId, userId);
+ const rule = ruleView(cur);
+ const { start, end } = lastPeriod(rule.period, now);
+ const { base, breakdown } = await baseIncome(cur, start, end);
+ const spent = await lifetimeSpent(ruleId);
+ const plan = planRun({ baseUsd: base, legs: rule.legs, perRunCapUsd: rule.per_run_cap_usd, lifetimeCapUsd: rule.lifetime_cap_usd, lifetimeSpentUsd: spent, minRunUsd: rule.min_run_usd });
+ const deposit = (await import('./credit-deposit.js')).depositWallet();
+ const coin = await ownCoinMint(cur.agent_id, cur.network);
+ const table = rule.legs.map((l) => {
+ const p = plan.legs.find((x) => x.kind === l.kind);
+ const base = { kind: l.kind, label: LEG_LABELS[l.kind], pct: l.pct, chain: 'solana', network: rule.network, would_send_usd: p?.capped_usd ?? 0 };
+ if (l.kind === 'dca_own_coin') return { ...base, asset: 'SOL', recipient: coin?.mint || null, recipient_label: coin ? `${coin.symbol || 'own coin'} (pump.fun)` : 'Agent has no coin on this network', ready: Boolean(coin) };
+ return { ...base, asset: 'USDC', recipient: deposit, recipient_label: l.kind === 'tools_budget' ? `Platform deposit wallet, then payment session ${String(l.session_id).slice(0, 8)}` : 'Platform deposit wallet, credited to your balance', ready: Boolean(deposit) };
+ });
+ return {
+ rule, confirmation: table,
+ period: { start: start.toISOString(), end: end.toISOString() },
+ base_usd: base, base_breakdown: breakdown, lifetime_spent_usd: spent,
+ plan: { executable_usd: plan.executable_usd, kept_usd: plan.kept_usd, scaled: plan.scaled, skip: plan.skip },
+ note: rule.network === 'devnet' ? 'Devnet rule: no real funds move.' : 'Confirming authorises this rule to send the amounts above, from this agent wallet, to these destinations, every period, within both caps. Any edit asks you again.',
+ };
+}
+
+// ── legs ────────────────────────────────────────────────────────────────────
+
+async function getApproval(id) {
+ const [a] = await sql`select id, status, signature, result from approval_requests where id = ${id}`;
+ return a || null;
+}
+
+async function parkTransfer({ rule, run, leg, atomics, gateReason }) {
+ const { createApprovalRequest } = await import('./approvals.js');
+ const dest = (await import('./credit-deposit.js')).depositWallet();
+ const usd = Number(leg.capped_usd);
+ const created = await createApprovalRequest({
+ userId: rule.user_id, agentId: rule.agent_id, source: 'revenue_reinvest', sourceRef: `leg:${leg.leg_key}`,
+ actionType: 'reinvest_transfer', venue: 'revenue_reinvest',
+ payload: { kind: 'reinvest_leg', leg_id: leg.id, leg_key: leg.leg_key, run_id: run.id, rule_id: rule.id, agent_id: rule.agent_id, network: rule.network, leg_kind: leg.kind, atomics: atomics.toString(), recipient: dest },
+ summary: `Reinvest ${formatAtomics(atomics, 6)} USDC into ${LEG_LABELS[leg.kind].toLowerCase()} (rule "${rule.name}")`,
+ amount: Number(formatAtomics(atomics, 6)), amountUsd: usd, asset: 'USDC', chain: 'solana', network: rule.network,
+ recipient: dest, recipientLabel: 'Platform deposit wallet',
+ riskNotes: ['This is an automatic reinvest from a rule you confirmed. It needs your yes this time because of your spend policy.'],
+ gateReason, idempotencyKey: `reinvest-approval:${leg.leg_key}`, autoApprovable: false,
+ });
+ return created.request;
+}
+
+/** Move the deposited USDC into the owner's credit balance, and from there into a payment session budget. */
+async function creditDeposit({ rule, leg, signature, usd, atomics }) {
+ if (rule.network !== 'mainnet') return { credited: false, note: 'Devnet deposit: nothing is credited.' };
+ const { creditAccount } = await import('./credits.js');
+ await creditAccount({
+ userId: rule.user_id, amountUsd: usd, kind: 'deposit', action: 'reinvest_deposit', refType: 'revenue_reinvest_leg', refId: leg.id,
+ txSignature: signature, asset: 'USDC', assetAmount: formatAtomics(atomics, 6), priceUsd: 1, idempotencyKey: `${leg.idempotency_key}:credit`,
+ meta: { rule_id: rule.id, leg: leg.kind },
+ });
+ if (leg.kind !== 'tools_budget') return { credited: true };
+ const cfg = rule.legs.find((l) => l.kind === 'tools_budget');
+ const topUp = await topUpPaymentSession({ userId: rule.user_id, sessionId: cfg.session_id, usd, atomics, idempotencyKey: `${leg.idempotency_key}:session` });
+ return { credited: true, session_id: cfg.session_id, session_budget_usd: topUp.budgetUsd };
+}
+
+/**
+ * Add `usd` to an active payment session's budget, paid from the owner's credits.
+ * The debit is idempotent on the key, and the budget bump runs only when the
+ * debit was new, so a retry can never top the session up twice.
+ */
+export async function topUpPaymentSession({ userId, sessionId, usd, atomics, idempotencyKey }) {
+ const [s] = await sql`select id, status from payment_sessions where id = ${sessionId} and user_id = ${userId}`;
+ if (!s || s.status !== 'active') throw fail(409, 'session_inactive', 'The tools budget session is not active, so credits were kept as a balance instead.');
+ const { debitCredits } = await import('./credits.js');
+ const debit = await debitCredits({ userId, amountUsd: usd, action: 'payment_session_topup', refType: 'payment_session', refId: sessionId, idempotencyKey });
+ if (!debit.replay) {
+ await sql`update payment_sessions set budget_usdc = budget_usdc + ${atomics.toString()}, updated_at = now() where id = ${sessionId} and user_id = ${userId}`;
+ }
+ const [after] = await sql`select budget_usdc from payment_sessions where id = ${sessionId}`;
+ return { budgetUsd: Number(formatAtomics(BigInt(String(after.budget_usdc).split('.')[0]), 6)), replay: debit.replay };
+}
+
+async function setLeg(id, patch) {
+ const [l] = await sql`
+ update revenue_reinvest_legs set status = ${patch.status}, signature = ${patch.signature ?? null}, approval_id = ${patch.approval_id ?? null},
+ destination = ${patch.destination ?? null}, asset = ${patch.asset ?? null}, amount_atomics = ${patch.amount_atomics ?? null},
+ detail = detail || ${JSON.stringify(patch.detail || {})}::jsonb, error = ${patch.error ?? null},
+ executed_at = ${patch.status === 'executed' ? sql`now()` : null}
+ where id = ${id} returning *`;
+ return l;
+}
+
+async function runTransferLeg({ rule, run, leg, stepUpApproved = false, approvalId = null }) {
+ const { depositWallet } = await import('./credit-deposit.js');
+ const dest = depositWallet();
+ if (!dest) return setLeg(leg.id, { status: 'failed', error: 'No platform deposit wallet is configured, so nothing was sent.' });
+ const cfg = rule.legs.find((l) => l.kind === leg.kind);
+ if (leg.kind === 'tools_budget') {
+ try { await assertSession(cfg.session_id, rule.user_id); } catch (e) { return setLeg(leg.id, { status: 'failed', error: `${e.message} Nothing was sent.` }); }
+ }
+ const usd = Number(leg.capped_usd);
+ const atomics = usdToUsdcAtomics(usd);
+ if (atomics <= 0n) return setLeg(leg.id, { status: 'skipped', detail: { reason: 'Amount rounds to zero.' } });
+ const { agentTransfer } = await import('./agent-commerce/transfer.js');
+ const { SpendLimitError } = await import('./agent-trade-guards.js');
+ let sent;
+ try {
+ sent = await agentTransfer({
+ agentId: rule.agent_id, userId: rule.user_id, network: rule.network, asset: 'USDC', recipient: dest, atomics,
+ category: 'transfer', memo: 'reinvest', destinationTrust: 'system', stepUpApproved,
+ rowMeta: { source: 'revenue_reinvest', rule_id: rule.id, run_id: run.id, leg: leg.kind, idempotency_key: leg.idempotency_key },
+ });
+ } catch (err) {
+ if (err instanceof SpendLimitError && err.code === 'policy_step_up' && !stepUpApproved) {
+ const req = await parkTransfer({ rule, run, leg, atomics, gateReason: err.message });
+ return setLeg(leg.id, { status: 'awaiting_approval', approval_id: req.id, destination: dest, asset: 'USDC', amount_atomics: atomics.toString(), detail: { gate: err.message } });
+ }
+ return setLeg(leg.id, { status: 'failed', destination: dest, asset: 'USDC', amount_atomics: atomics.toString(), error: String(err?.message || err).slice(0, 300) });
+ }
+ let credit = {};
+ try {
+ credit = await creditDeposit({ rule, leg, signature: sent.signature, usd: sent.usd ?? usd, atomics });
+ } catch (err) {
+ // The USDC is already at the deposit wallet. Record that honestly; a later credit
+ // attempt reuses the same idempotency key so it cannot double-credit.
+ credit = { credit_error: String(err?.message || err).slice(0, 200) };
+ }
+ return setLeg(leg.id, {
+ status: 'executed', signature: sent.signature, approval_id: approvalId, destination: dest, asset: 'USDC', amount_atomics: atomics.toString(),
+ detail: { usd: sent.usd ?? usd, ...credit },
+ });
+}
+
+async function runDcaLeg({ rule, run, leg, preview }) {
+ const coin = await ownCoinMint(rule.agent_id, rule.network);
+ if (!coin) return setLeg(leg.id, { status: 'failed', error: 'This agent has no coin on this network to buy. Nothing was sent.' });
+ const solUsd = await cachedSolUsd().catch(() => null);
+ if (!solUsd) return setLeg(leg.id, { status: 'failed', error: 'No live SOL price right now, so the buy size cannot be set. It will not retry this period.' });
+ const sol = Math.floor((Number(leg.capped_usd) / solUsd) * 1e6) / 1e6;
+ if (!(sol > 0)) return setLeg(leg.id, { status: 'skipped', detail: { reason: 'Amount rounds to zero.' } });
+ const { executeAgentTrade, parseTradeInput } = await import('../agents/agent-trade.js');
+ const { getTradeLimits } = await import('./agent-trade-guards.js');
+ const [agent] = await sql`select id, user_id, meta from agent_identities where id = ${rule.agent_id} and deleted_at is null`;
+ if (!agent) return setLeg(leg.id, { status: 'failed', error: 'The agent no longer exists.' });
+ let input;
+ try {
+ input = parseTradeInput({ side: 'buy', mint: coin.mint, amount: sol, network: rule.network, simulate: preview, idempotency_key: leg.idempotency_key }, getTradeLimits(agent.meta));
+ } catch (e) {
+ return setLeg(leg.id, { status: 'failed', error: e?.message || 'The buy is not valid.' });
+ }
+ let r;
+ try {
+ r = await executeAgentTrade({ id: agent.id, userId: agent.user_id, meta: agent.meta || {}, input, source: 'discretionary' });
+ } catch (e) {
+ return setLeg(leg.id, { status: 'failed', destination: coin.mint, asset: 'SOL', error: String(e?.message || e).slice(0, 300) });
+ }
+ if (!r.ok) return setLeg(leg.id, { status: 'failed', destination: coin.mint, asset: 'SOL', error: `${r.message || r.code}`.slice(0, 300) });
+ if (r.data?.pending_approval) {
+ return setLeg(leg.id, { status: 'awaiting_approval', approval_id: r.data.approval_id, destination: coin.mint, asset: 'SOL', detail: { sol, gate: r.data.reason } });
+ }
+ if (r.data?.simulated) return setLeg(leg.id, { status: 'planned', destination: coin.mint, asset: 'SOL', detail: { simulated: true, sol, err: r.data.err } });
+ return setLeg(leg.id, { status: 'executed', signature: r.data.signature, destination: coin.mint, asset: 'SOL', detail: { sol, usd: leg.capped_usd, symbol: coin.symbol } });
+}
+
+// ── runs ────────────────────────────────────────────────────────────────────
+
+async function pauseAfterFailures(rule, why) {
+ await sql`update revenue_reinvest_rules set status = 'paused', paused_reason = ${why}, updated_at = now() where id = ${rule.id}`;
+ insertNotification(rule.user_id, 'reinvest_rule_failed', {
+ title: `Reinvest rule paused: ${rule.name}`,
+ body: `${why} Nothing further runs until you review it.`,
+ link: '/earnings#rules',
+ });
+}
+
+/**
+ * Run one rule for its last complete period. Safe to call repeatedly: a
+ * period that already has a live run returns that run untouched.
+ * `preview: true` plans and simulates (paper trades, no transfers) and writes nothing live.
+ */
+export async function runRule({ rule: cur, now = Date.now(), preview = false }) {
+ const rule = { ...cur, legs: cur.legs };
+ const view = ruleView(rule);
+ if (!preview) {
+ if (rule.status !== 'active') return { skipped: true, reason: `Rule is ${rule.status}.` };
+ if (!view.confirmed) return { skipped: true, reason: 'The owner has not confirmed the current terms.' };
+ }
+ const { start, end } = lastPeriod(rule.period, now);
+ if (!preview && rule.active_from && end <= new Date(rule.active_from)) return { skipped: true, reason: 'This period ended before the rule was confirmed.' };
+
+ const key = preview ? `${runKey(rule.id, start)}:preview:${now}` : runKey(rule.id, start);
+ const { base, breakdown } = await baseIncome(rule, start, end);
+ const spent = await lifetimeSpent(rule.id);
+ const plan = planRun({ baseUsd: base, legs: rule.legs, perRunCapUsd: num(rule.per_run_cap_usd), lifetimeCapUsd: num(rule.lifetime_cap_usd), lifetimeSpentUsd: spent, minRunUsd: num(rule.min_run_usd) });
+
+ const inserted = await sql`
+ insert into revenue_reinvest_runs (rule_id, user_id, agent_id, mode, period_start, period_end, idempotency_key, status, base_usd, base_breakdown, planned_usd, kept_usd, rule_snapshot, note)
+ values (${rule.id}, ${rule.user_id}, ${rule.agent_id}, ${preview ? 'preview' : 'live'}, ${start}, ${end}, ${key}, 'running', ${base}, ${JSON.stringify(breakdown)}::jsonb,
+ ${plan.planned_usd}, ${plan.kept_usd}, ${JSON.stringify({ hash: view.hash, legs: rule.legs, per_run_cap_usd: num(rule.per_run_cap_usd), lifetime_cap_usd: num(rule.lifetime_cap_usd) })}::jsonb, ${plan.skip})
+ on conflict do nothing returning *`;
+ if (!inserted.length) {
+ const [existing] = await sql`select * from revenue_reinvest_runs where idempotency_key = ${key} or (rule_id = ${rule.id} and period_start = ${start} and mode = 'live') limit 1`;
+ return { skipped: true, reason: 'This period already ran.', run: existing };
+ }
+ const run = inserted[0];
+
+ if (plan.skip) {
+ await sql`update revenue_reinvest_runs set status = 'skipped', finished_at = now() where id = ${run.id}`;
+ return { run: { ...run, status: 'skipped' }, plan, legs: [] };
+ }
+
+ const legRows = [];
+ for (const p of plan.legs) {
+ const [l] = await sql`
+ insert into revenue_reinvest_legs (run_id, leg_key, kind, pct, planned_usd, capped_usd, idempotency_key, status)
+ values (${run.id}, ${preview ? `${legKey(rule.id, start, p.kind)}:preview` : legKey(rule.id, start, p.kind)}, ${p.kind}, ${p.pct}, ${p.planned_usd}, ${p.capped_usd},
+ ${preview ? `${legKey(rule.id, start, p.kind)}:preview:${now}` : legKey(rule.id, start, p.kind)}, 'planned')
+ on conflict (run_id, leg_key) do update set capped_usd = excluded.capped_usd returning *`;
+ legRows.push(l);
+ }
+
+ const done = [];
+ for (const leg of legRows) {
+ if (Number(leg.capped_usd) <= 0) { done.push(await setLeg(leg.id, { status: 'skipped', detail: { reason: 'Nothing left after the caps.' } })); continue; }
+ if (preview) {
+ done.push(leg.kind === 'dca_own_coin'
+ ? await runDcaLeg({ rule, run, leg, preview: true })
+ : await setLeg(leg.id, { status: 'planned', asset: 'USDC', detail: { preview: true, would_send_usd: Number(leg.capped_usd) } }));
+ continue;
+ }
+ done.push(leg.kind === 'dca_own_coin' ? await runDcaLeg({ rule, run, leg, preview: false }) : await runTransferLeg({ rule, run, leg }));
+ }
+
+ return finishRun({ rule, run, legs: done, preview });
+}
+
+async function finishRun({ rule, run, legs, preview }) {
+ const executed = legs.filter((l) => l.status === 'executed');
+ const failed = legs.filter((l) => l.status === 'failed');
+ const waiting = legs.filter((l) => l.status === 'awaiting_approval');
+ const executedUsd = executed.reduce((a, l) => a + Number(l.capped_usd), 0);
+ const status = preview ? 'completed' : failed.length && !executed.length && !waiting.length ? 'failed' : failed.length ? 'partial' : waiting.length ? 'awaiting_approval' : 'completed';
+ const error = failed.map((l) => `${l.kind}: ${l.error}`).join(' | ') || null;
+ const [row] = await sql`
+ update revenue_reinvest_runs set status = ${status}, executed_usd = ${executedUsd}, error = ${error}, finished_at = now() where id = ${run.id} returning *`;
+ if (!preview) {
+ if (failed.length) {
+ const [r] = await sql`update revenue_reinvest_rules set consecutive_failures = consecutive_failures + 1, updated_at = now() where id = ${rule.id} returning consecutive_failures`;
+ insertNotification(rule.user_id, 'reinvest_rule_failed', {
+ title: `Reinvest run had a failure: ${rule.name}`,
+ body: `${error}`.slice(0, 280),
+ link: '/earnings#rules',
+ });
+ if (r.consecutive_failures >= FAILURES_BEFORE_PAUSE) await pauseAfterFailures(rule, `${FAILURES_BEFORE_PAUSE} runs in a row had a failure.`);
+ } else if (executed.length || waiting.length) {
+ await sql`update revenue_reinvest_rules set consecutive_failures = 0 where id = ${rule.id}`;
+ if (executed.length) {
+ insertNotification(rule.user_id, 'reinvest_run', {
+ title: `Reinvested $${executedUsd.toFixed(2)}: ${rule.name}`,
+ body: executed.map((l) => `${LEG_LABELS[l.kind]} $${Number(l.capped_usd).toFixed(2)}`).join(', '),
+ link: '/earnings#rules',
+ });
+ }
+ }
+ }
+ return { run: row, legs };
+}
+
+/** Resolve legs that waited on the owner: record what the approval became. */
+export async function settleApprovals() {
+ const waiting = await sql`
+ select l.id, l.kind, l.approval_id, l.run_id, a.status as a_status, a.signature as a_sig, r.rule_id, r.user_id
+ from revenue_reinvest_legs l join revenue_reinvest_runs r on r.id = l.run_id join approval_requests a on a.id = l.approval_id
+ where l.status = 'awaiting_approval' and a.status in ('executed', 'denied', 'expired', 'failed')`;
+ let settled = 0;
+ for (const w of waiting) {
+ if (w.a_status === 'executed') {
+ await sql`update revenue_reinvest_legs set status = 'executed', signature = coalesce(${w.a_sig}, signature), executed_at = now() where id = ${w.id}`;
+ } else {
+ await sql`update revenue_reinvest_legs set status = 'failed', error = ${`Approval ${w.a_status}; nothing was sent.`} where id = ${w.id}`;
+ }
+ const open = await sql`select 1 from revenue_reinvest_legs where run_id = ${w.run_id} and status = 'awaiting_approval' limit 1`;
+ if (!open.length) {
+ const legs = await sql`select status, capped_usd from revenue_reinvest_legs where run_id = ${w.run_id}`;
+ const ex = legs.filter((l) => l.status === 'executed');
+ const bad = legs.filter((l) => l.status === 'failed');
+ await sql`update revenue_reinvest_runs set status = ${bad.length ? (ex.length ? 'partial' : 'failed') : 'completed'},
+ executed_usd = ${ex.reduce((a, l) => a + Number(l.capped_usd), 0)}, finished_at = now() where id = ${w.run_id}`;
+ }
+ settled++;
+ }
+ return settled;
+}
+
+/** Cron entry: settle approvals, then run every active, confirmed rule for its last period. */
+export async function runDueRules({ now = Date.now() } = {}) {
+ const settled = await settleApprovals().catch(() => 0);
+ const rules = await sql`select ${RULE_COLS} from revenue_reinvest_rules where status = 'active' and confirmed_hash is not null`;
+ const out = { settled, rules: rules.length, ran: 0, skipped: 0, failed: 0 };
+ for (const r of rules) {
+ try {
+ const res = await runRule({ rule: r, now });
+ if (res.skipped) out.skipped++;
+ else out.ran++;
+ } catch (err) {
+ out.failed++;
+ console.error('[revenue-reinvest] rule failed', r.id, err?.message);
+ }
+ }
+ return out;
+}
+
+/**
+ * Executor for approved reinvest transfers (registered in approvals.js).
+ * Runs ONLY the stored leg, for the rule's agent, if the approving account still owns it.
+ */
+export async function executeApprovedReinvestLeg(row) {
+ const p = row.payload || {};
+ if (p.kind !== 'reinvest_leg') return { status: 'error', note: 'Unknown reinvest action, so nothing was executed.' };
+ const [leg] = await sql`select * from revenue_reinvest_legs where id = ${p.leg_id}`;
+ const [run] = leg ? await sql`select * from revenue_reinvest_runs where id = ${leg.run_id}` : [];
+ const [rule] = run ? await sql`select ${RULE_COLS} from revenue_reinvest_rules where id = ${run.rule_id}` : [];
+ if (!leg || !rule) return { status: 'error', note: 'The rule behind this request was deleted, so nothing was executed.' };
+ if (String(rule.user_id) !== String(row.user_id)) return { status: 'error', note: 'This rule is no longer owned by the account that approved it, so nothing was executed.' };
+ if (leg.status === 'executed') return { status: 'ok', signature: leg.signature, usd: Number(leg.capped_usd) };
+ const done = await runTransferLeg({ rule, run, leg, stepUpApproved: true, approvalId: row.id });
+ if (done.status !== 'executed') return { status: 'error', note: done.error || 'The reinvest transfer did not go through.' };
+ return { status: 'ok', signature: done.signature, usd: Number(done.capped_usd) };
+}
+
+export async function listRuns({ userId, ruleId = null, agentId = null, limit = 30 }) {
+ const runs = await sql`
+ select * from revenue_reinvest_runs where user_id = ${userId} ${ruleId ? sql`and rule_id = ${ruleId}` : sql``} ${agentId ? sql`and agent_id = ${agentId}` : sql``}
+ order by started_at desc limit ${Math.min(Number(limit) || 30, 100)}`;
+ if (!runs.length) return [];
+ const ids = runs.map((r) => r.id);
+ const legs = await sql`select * from revenue_reinvest_legs where run_id = any(${ids}::uuid[]) order by created_at`;
+ return runs.map((r) => ({ ...r, legs: legs.filter((l) => l.run_id === r.id) }));
+}
diff --git a/api/_lib/revenue-routes.js b/api/_lib/revenue-routes.js
new file mode 100644
index 000000000..8037e54ff
--- /dev/null
+++ b/api/_lib/revenue-routes.js
@@ -0,0 +1,197 @@
+// Route table for /api/revenue/*, in the v1 API contract (api/_lib/agents-v1/http.js).
+// Mounted by api/revenue/[...route].js. Guide: docs/revenue-ledger.md.
+//
+// Public:
+// GET /public/:agentId the agent's earnings, only when its owner switched the page on
+//
+// Owner (session, API key or OAuth token):
+// GET /ledger totals by source and period, projection, unclaimed memo, chain checks
+// GET /entries ledger rows, each with its transaction
+// GET /export the same rows as CSV (default) or JSON
+// GET /reconcile the latest reconcile run
+// POST /sync bring the ledger up to date now
+// GET/PUT /agents/:id/settings the public-earnings toggle
+// GET/POST /rules, PATCH/DELETE /rules/:id, GET /rules/:id/preview, POST /rules/:id/pause
+// POST /rules/:id/test-run plan + paper-trade a run; nothing real moves
+// GET /runs per-run receipts with every leg
+//
+// Owner, browser session only (an agent's key can never turn a rule on):
+// POST /rules/:id/confirm the explicit yes to the exact terms (hash)
+
+import { apiError, requireUuid, strParam, intParam } from './agents-v1/http.js';
+import { limits } from './rate-limit.js';
+import { sql } from './db.js';
+import {
+ listEntries, ledgerView, exportCsv, syncLedger, getSettings, setPublic, publicView, SOURCE_KEYS,
+} from './revenue-ledger.js';
+import { latestReconcile } from './revenue-reconcile.js';
+import {
+ listRules, createRule, updateRule, deleteRule, confirmRule, pauseRule, rulePreview, getRule, runRule, listRuns, ruleView,
+} from './revenue-reinvest.js';
+import { CSV_COLUMNS, RULE_PERIODS, LEG_LABELS, SOURCES } from './revenue-ledger-core.js';
+
+const PERIODS = ['day', 'week', 'month'];
+
+function sessionOnly(principal) {
+ if (principal?.source !== 'session') {
+ throw apiError(403, 'session_required', 'Only the owner, signed in on three.ws, can do this. API keys and agent tokens cannot.');
+ }
+}
+
+async function ownedAgentId(value, userId) {
+ const id = strParam(value, { name: 'agent_id', max: 40 });
+ if (!id) return null;
+ requireUuid(id, 'agent');
+ const [a] = await sql`select id from agent_identities where id = ${id} and user_id = ${userId} and deleted_at is null`;
+ if (!a) throw apiError(404, 'not_found', 'No agent with that id.');
+ return id;
+}
+
+function dateParam(v, name) {
+ if (v === undefined || v === null || v === '') return null;
+ const d = new Date(v);
+ if (Number.isNaN(d.getTime())) throw apiError(400, 'invalid_parameter', `${name} must be a date.`, { parameter: name });
+ return d.toISOString();
+}
+
+function scope(q, userId) {
+ const period = PERIODS.includes(q.period) ? q.period : 'month';
+ return {
+ period, from: dateParam(q.from, 'from'), to: dateParam(q.to, 'to'),
+ source: q.source && SOURCE_KEYS.includes(q.source) ? q.source : null,
+ windowDays: intParam(q.window_days, { name: 'window_days', min: 7, max: 365, fallback: 30 }),
+ };
+}
+
+async function ledgerRoute({ principal, query }) {
+ const agentId = await ownedAgentId(query.agent_id, principal.userId);
+ const s = scope(query);
+ const view = await ledgerView({ userId: principal.userId, agentId, period: s.period, from: s.from, to: s.to, windowDays: s.windowDays });
+ const reconcile = await latestReconcile();
+ return { ...view, reconcile, agent_id: agentId };
+}
+
+async function entriesRoute({ principal, query }) {
+ const agentId = await ownedAgentId(query.agent_id, principal.userId);
+ const s = scope(query);
+ const limit = intParam(query.limit, { name: 'limit', min: 1, max: 1000, fallback: 200 });
+ const rows = await listEntries({ userId: principal.userId, agentId, source: s.source, from: s.from, to: s.to, limit, before: dateParam(query.before, 'before') });
+ return { entries: rows, next_before: rows.length === limit ? rows[rows.length - 1].occurred_at : null };
+}
+
+async function exportRoute({ principal, query, res }) {
+ const agentId = await ownedAgentId(query.agent_id, principal.userId);
+ const s = scope(query);
+ const args = { userId: principal.userId, agentId, source: s.source, from: s.from, to: s.to };
+ const stamp = new Date().toISOString().slice(0, 10);
+ if (query.format === 'json') {
+ const entries = await listEntries({ ...args, limit: 50000 });
+ return { columns: CSV_COLUMNS, entries };
+ }
+ const csv = await exportCsv(args);
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/csv; charset=utf-8');
+ res.setHeader('content-disposition', `attachment; filename="three-ws-revenue-${stamp}.csv"`);
+ res.setHeader('cache-control', 'no-store');
+ res.end(csv);
+ return null;
+}
+
+async function reconcileRoute() {
+ return { latest: await latestReconcile() };
+}
+
+async function syncRoute({ principal, body }) {
+ const agentId = await ownedAgentId(body.agent_id, principal.userId);
+ return syncLedger({ userId: principal.userId, agentId });
+}
+
+async function getSettingsRoute({ principal, params }) {
+ const agentId = await ownedAgentId(params.id, principal.userId);
+ return getSettings(agentId);
+}
+
+async function putSettingsRoute({ principal, params, body }) {
+ const agentId = await ownedAgentId(params.id, principal.userId);
+ if (typeof body.public_earnings !== 'boolean') throw apiError(400, 'invalid_parameter', 'public_earnings must be true or false.', { parameter: 'public_earnings' });
+ return setPublic({ agentId, userId: principal.userId, isPublic: body.public_earnings });
+}
+
+async function publicRoute({ params, query, ip }) {
+ const rl = await limits.commercePublic(ip);
+ if (!rl.success) throw apiError(429, 'rate_limited', 'Too many requests. Slow down and retry.');
+ requireUuid(params.agentId, 'agent');
+ const view = await publicView({ agentId: params.agentId, period: PERIODS.includes(query.period) ? query.period : 'month' });
+ if (!view) throw apiError(404, 'not_public', 'This agent has not made its earnings public.');
+ return view;
+}
+
+async function listRulesRoute({ principal, query }) {
+ const agentId = await ownedAgentId(query.agent_id, principal.userId);
+ return { rules: await listRules({ userId: principal.userId, agentId }), leg_kinds: LEG_LABELS, periods: RULE_PERIODS };
+}
+
+async function createRuleRoute({ principal, body }) {
+ const agentId = await ownedAgentId(body.agent_id, principal.userId);
+ if (!agentId) throw apiError(400, 'missing_parameter', 'agent_id is required.', { parameter: 'agent_id' });
+ return { rule: await createRule({ userId: principal.userId, agentId, body }) };
+}
+
+async function patchRuleRoute({ principal, params, body }) {
+ return { rule: await updateRule({ ruleId: requireUuid(params.id, 'rule'), userId: principal.userId, body }) };
+}
+
+async function deleteRuleRoute({ principal, params }) {
+ await deleteRule({ ruleId: requireUuid(params.id, 'rule'), userId: principal.userId });
+ return { deleted: true };
+}
+
+async function previewRoute({ principal, params }) {
+ return rulePreview({ ruleId: requireUuid(params.id, 'rule'), userId: principal.userId });
+}
+
+async function confirmRoute({ principal, params, body }) {
+ sessionOnly(principal);
+ return { rule: await confirmRule({ ruleId: requireUuid(params.id, 'rule'), userId: principal.userId, hash: body.hash }) };
+}
+
+async function pauseRoute({ principal, params }) {
+ return { rule: await pauseRule({ ruleId: requireUuid(params.id, 'rule'), userId: principal.userId }) };
+}
+
+async function testRunRoute({ principal, params }) {
+ const rule = await getRule(requireUuid(params.id, 'rule'), principal.userId);
+ const out = await runRule({ rule, preview: true });
+ return { rule: ruleView(rule), ...out, note: 'Preview only: transfers are planned, buys are paper trades, and nothing was sent.' };
+}
+
+async function runsRoute({ principal, query }) {
+ const agentId = await ownedAgentId(query.agent_id, principal.userId);
+ const ruleId = query.rule_id ? requireUuid(query.rule_id, 'rule') : null;
+ return { runs: await listRuns({ userId: principal.userId, agentId, ruleId, limit: intParam(query.limit, { name: 'limit', min: 1, max: 100, fallback: 30 }) }) };
+}
+
+async function sourcesRoute() {
+ return { sources: SOURCES.map(({ key, label, kind, how }) => ({ key, label, kind, how })) };
+}
+
+export const revenueRoutes = [
+ { method: 'GET', path: '/public/:agentId', name: 'revenue.public', auth: 'public', handler: publicRoute },
+ { method: 'GET', path: '/sources', name: 'revenue.sources', auth: 'public', handler: sourcesRoute },
+ { method: 'GET', path: '/ledger', name: 'revenue.ledger', auth: 'required', scope: 'wallet:read', handler: ledgerRoute },
+ { method: 'GET', path: '/entries', name: 'revenue.entries', auth: 'required', scope: 'wallet:read', handler: entriesRoute },
+ { method: 'GET', path: '/export', name: 'revenue.export', auth: 'required', scope: 'wallet:read', handler: exportRoute },
+ { method: 'GET', path: '/reconcile', name: 'revenue.reconcile', auth: 'required', scope: 'wallet:read', handler: reconcileRoute },
+ { method: 'POST', path: '/sync', name: 'revenue.sync', auth: 'required', scope: 'wallet:read', handler: syncRoute },
+ { method: 'GET', path: '/agents/:id/settings', name: 'revenue.settings.get', auth: 'required', scope: 'wallet:read', handler: getSettingsRoute },
+ { method: 'PUT', path: '/agents/:id/settings', name: 'revenue.settings.put', auth: 'required', scope: 'agents:write', handler: putSettingsRoute },
+ { method: 'GET', path: '/rules', name: 'revenue.rules.list', auth: 'required', scope: 'wallet:read', handler: listRulesRoute },
+ { method: 'POST', path: '/rules', name: 'revenue.rules.create', auth: 'required', scope: 'agents:write', handler: createRuleRoute },
+ { method: 'PATCH', path: '/rules/:id', name: 'revenue.rules.update', auth: 'required', scope: 'agents:write', handler: patchRuleRoute },
+ { method: 'DELETE', path: '/rules/:id', name: 'revenue.rules.delete', auth: 'required', scope: 'agents:write', handler: deleteRuleRoute },
+ { method: 'GET', path: '/rules/:id/preview', name: 'revenue.rules.preview', auth: 'required', scope: 'wallet:read', handler: previewRoute },
+ { method: 'POST', path: '/rules/:id/confirm', name: 'revenue.rules.confirm', auth: 'required', handler: confirmRoute },
+ { method: 'POST', path: '/rules/:id/pause', name: 'revenue.rules.pause', auth: 'required', scope: 'agents:write', handler: pauseRoute },
+ { method: 'POST', path: '/rules/:id/test-run', name: 'revenue.rules.test', auth: 'required', scope: 'agents:write', handler: testRunRoute },
+ { method: 'GET', path: '/runs', name: 'revenue.runs', auth: 'required', scope: 'wallet:read', handler: runsRoute },
+];
diff --git a/api/cron/revenue-ledger-reconcile.js b/api/cron/revenue-ledger-reconcile.js
new file mode 100644
index 000000000..c8da22fe5
--- /dev/null
+++ b/api/cron/revenue-ledger-reconcile.js
@@ -0,0 +1,17 @@
+// GET /api/cron/revenue-ledger-reconcile: bring the revenue ledger up to date
+// from every income source, prove it still matches those sources, verify a
+// sample of mainnet transactions on-chain, announce milestones and alert owners
+// to drift. Idempotent: the ledger upsert is keyed by (source, source_ref).
+// Library: api/_lib/revenue-reconcile.js. Guide: docs/revenue-ledger.md.
+
+import { json, method, wrapCron } from '../_lib/http.js';
+import { requireCron } from '../_lib/cron-auth.js';
+import { runReconcile } from '../_lib/revenue-reconcile.js';
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const summary = await runReconcile();
+ return json(res, 200, { ok: true, ...summary }, { 'cache-control': 'no-store' });
+});
diff --git a/api/cron/revenue-reinvest.js b/api/cron/revenue-reinvest.js
new file mode 100644
index 000000000..e5f1d5aa7
--- /dev/null
+++ b/api/cron/revenue-reinvest.js
@@ -0,0 +1,17 @@
+// GET /api/cron/revenue-reinvest: run every active, owner-confirmed reinvest
+// rule for its last complete period, and settle legs that were waiting on an
+// approval. Idempotent: one live run per (rule, period) and one idempotency key
+// per leg, so overlapping ticks never send twice.
+// Library: api/_lib/revenue-reinvest.js. Guide: docs/revenue-ledger.md.
+
+import { json, method, wrapCron } from '../_lib/http.js';
+import { requireCron } from '../_lib/cron-auth.js';
+import { runDueRules } from '../_lib/revenue-reinvest.js';
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const summary = await runDueRules();
+ return json(res, 200, { ok: true, ...summary }, { 'cache-control': 'no-store' });
+});
diff --git a/api/revenue/[...route].js b/api/revenue/[...route].js
new file mode 100644
index 000000000..0d4174164
--- /dev/null
+++ b/api/revenue/[...route].js
@@ -0,0 +1,8 @@
+// /api/revenue/*: the revenue ledger, reconciliation status, the public
+// earnings toggle and the reinvest rules. Route table: api/_lib/revenue-routes.js.
+// Guide: docs/revenue-ledger.md.
+
+import { defineRouter } from '../_lib/agents-v1/http.js';
+import { revenueRoutes } from '../_lib/revenue-routes.js';
+
+export default defineRouter({ base: '/api/revenue', routes: revenueRoutes });
diff --git a/docs/creator-payouts.md b/docs/creator-payouts.md
new file mode 100644
index 000000000..1f20afad1
--- /dev/null
+++ b/docs/creator-payouts.md
@@ -0,0 +1,77 @@
+# Creator payouts
+
+Creator fees from an agent's coins are claimed into the agent's custodial wallet. Creator payouts send the creator's share of each claim to a wallet you register, and record every distribution so you can see what was sent, what is waiting and why.
+
+Use it to get your share out of the agent wallet on a schedule, with a full audit trail. The page is [/creator/payouts](https://three.ws/creator/payouts).
+
+## The flow
+
+```
+earnings refresh -> fee collection -> distribution -> reconciliation
+```
+
+| Stage | Cron | What it does |
+| --- | --- | --- |
+| Earnings refresh | `/api/cron/creator-earnings-snapshot` | Reads what each coin has earned from pump.fun and the on-chain vault. |
+| Fee collection | `/api/cron/launcher-claimer` | Claims accrued creator fees into the agent wallet once they pass the claim threshold, and records the claim with its buyback earmark. |
+| Distribution | `/api/cron/creator-payout-distribute` | Records each new claim's creator share, then sends what can be sent to the payout wallet. |
+| Reconciliation | `/api/cron/creator-payout-reconcile` | Checks the on-chain vault balances and sent transfers against the records, and alerts on drift. |
+
+Cadences are read from the cron definitions in `vercel.json` by `GET /api/creator-payouts?info=1`, so the page never shows a stale schedule.
+
+## Where $100 of claimed fees goes
+
+Generated from `CREATOR_FEE_CLAIM_POLICY` in `api/_lib/token/config.js`, the same policy the claimer uses to earmark the platform $THREE buyback. The remainder is your share, sent to the payout wallet.
+
+## The payout wallet
+
+- Register it on the page by connecting the wallet. The wallet signs a challenge message that names the agent, the wallet, a one-use nonce and a timestamp (Ed25519, valid for five minutes).
+- A step-up confirms the owner is at the keyboard: account password or an emailed code, through the same grant mechanism as the [destination allowlist](destination-whitelist.md).
+- Only a signed-in browser session can register. A bearer token or API key is refused, so a leaked key can never redirect payouts.
+- The nonce is spent once, so a captured signature cannot register twice.
+- The first wallet is active immediately. Changing it stages the new wallet for 48 hours, and payouts are held until it takes effect. The owner can cancel the change during the wait, and is notified.
+
+## Why a share is held
+
+| Reason | Meaning |
+| --- | --- |
+| `wallet_not_registered` | No payout wallet yet. Register one and the share is sent. |
+| `cooldown` | A wallet change is waiting out its 48 hour protection window. |
+| `below_minimum` | Unsent shares total less than the minimum payout (0.01 SOL). They add up across claims. |
+| `payouts_paused` | Payouts are not switched on. Shares are recorded and sent once they are. |
+
+A held share notifies the owner once per reason change, not once per run.
+
+## Safety properties
+
+- Every claim has exactly one distribution row (`claim_id` is unique), so the cron can re-run without double-recording.
+- A batch moves `pending` to `sending` to `sent` with the transfer signature. A run that dies after sending is reconciled from the chain, not re-sent.
+- The agent wallet keeps a small reserve for fees.
+- Sending is gated by `CREATOR_PAYOUTS_LIVE=true` and is off by default.
+
+## API
+
+| Method and path | Auth | Purpose |
+| --- | --- | --- |
+| `GET /api/creator-payouts?info=1` | none | Stage cadences and the per-$100 flow. |
+| `GET /api/creator-payouts?agent=<id>` | owner session | Payout wallet, pending change, totals, held reasons, recent distributions. |
+| `GET /api/creator-payouts?agent=<id>&format=csv` | owner session | Every distribution as CSV. |
+| `POST /api/creator-payouts` `{ action: "challenge" }` | owner session | The message the wallet must sign. |
+| `POST /api/creator-payouts` `{ action: "register" }` | owner session + step-up grant | Register or stage a wallet change. |
+| `POST /api/creator-payouts` `{ action: "cancel" }` | owner session | Drop a staged wallet change. |
+
+`GET /api/agents/:id/earnings` carries a public `payouts` block with the registered wallet and the sent, pending and held totals. A staged change stays on the owner page.
+
+## Configuration
+
+| Variable | Default | Meaning |
+| --- | --- | --- |
+| `CREATOR_PAYOUTS_LIVE` | unset (off) | Set to `true` to send. Until then shares are recorded and held as `payouts_paused`. |
+
+## Files
+
+- Logic: `api/_lib/creator-payouts-core.js` (pure), `api/_lib/creator-payouts.js` (database and chain).
+- Endpoint: `api/creator-payouts.js`. Crons: `api/cron/creator-payout-distribute.js`, `api/cron/creator-payout-reconcile.js`.
+- Migration: `api/_lib/migrations/20261023190000_creator_payouts.sql`.
+- Page: `pages/creator-payouts.html`, `src/creator-payouts-page.js`.
+- Tests: `tests/creator-payouts.test.js`.
diff --git a/pages/creator-payouts.html b/pages/creator-payouts.html
new file mode 100644
index 000000000..5ea9dcf44
--- /dev/null
+++ b/pages/creator-payouts.html
@@ -0,0 +1,190 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <style>/* three.ws hidden-guard: make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>
+ <script>/* three.ws theme boot */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Creator payouts · three.ws</title>
+ <meta name="description" content="Register the wallet your agent's creator-fee share is paid to, see what is sent, pending or held and why, and export every distribution." />
+ <meta name="robots" content="noindex" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ :root {
+ --bg: #0d0d0d;
+ --bg-2: #141414;
+ --card: #181818;
+ --line: rgba(255,255,255,0.07);
+ --line-2: rgba(255,255,255,0.12);
+ --line-3: rgba(255,255,255,0.3);
+ --text: #e7e9ee;
+ --muted: rgba(231,233,238,0.6);
+ --dim: rgba(231,233,238,0.4);
+ --blue: #3b82f6;
+ --green: #22c55e;
+ --green-ink: #052e16;
+ --red: #ef4444;
+ --amber: #f59e0b;
+ --radius: 12px;
+ --skeleton-base: rgba(255,255,255,0.04);
+ --skeleton-sheen: rgba(255,255,255,0.08);
+ --mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace;
+ }
+ [data-theme="light"] {
+ --bg: #f5f5f5;
+ --bg-2: #ffffff;
+ --card: #ffffff;
+ --line: rgba(0,0,0,0.07);
+ --line-2: rgba(0,0,0,0.12);
+ --line-3: rgba(0,0,0,0.3);
+ --text: #111;
+ --muted: rgba(0,0,0,0.6);
+ --dim: rgba(0,0,0,0.42);
+ --green: #15803d;
+ --green-ink: #ffffff;
+ --red: #dc2626;
+ --amber: #b45309;
+ --skeleton-base: rgba(0,0,0,0.04);
+ --skeleton-sheen: rgba(0,0,0,0.08);
+ }
+ *{box-sizing:border-box;margin:0;padding:0;}
+ html,body{background:var(--bg);color:var(--text);font-family:'Inter',system-ui,sans-serif;min-height:100vh;}
+ a{color:inherit;}
+ .page-shell{max-width:860px;margin:0 auto;padding:0 16px 100px;}
+ .crumbs{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--muted);padding-top:28px;}
+ .crumbs a{text-decoration:none;}
+ .crumbs a:hover{color:var(--text);}
+ .crumbs .here{color:var(--text);}
+ .page-hero{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;padding:20px 0 24px;flex-wrap:wrap;}
+ .page-hero h1{font-size:28px;font-weight:700;letter-spacing:-0.02em;}
+ .page-hero p{color:var(--muted);margin-top:8px;font-size:14px;line-height:1.5;max-width:560px;}
+ .page-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap;}
+ .btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;font-size:13px;font-weight:500;padding:8px 14px;border-radius:8px;background:var(--card);color:var(--text);border:1px solid var(--line-2);cursor:pointer;transition:border-color .15s,background .15s,transform .08s,opacity .15s;font-family:inherit;text-decoration:none;min-height:36px;}
+ .btn:hover{border-color:var(--line-3);}
+ .btn:active{transform:translateY(1px);}
+ .btn:disabled{opacity:.45;cursor:default;transform:none;}
+ .btn:focus-visible,select:focus-visible,input:focus-visible,textarea:focus-visible,.li-pair:focus-visible,.li-copy:focus-visible,summary:focus-visible{outline:2px solid var(--blue);outline-offset:2px;}
+ .btn-primary{background:var(--green);border-color:var(--green);color:var(--green-ink);font-weight:600;}
+ .btn-primary:hover{border-color:var(--green);filter:brightness(1.08);}
+ .btn-danger{color:var(--red);}
+ .btn-danger:hover{border-color:var(--red);background:color-mix(in srgb,var(--red) 8%,transparent);}
+ .btn-sm{padding:6px 10px;font-size:12px;min-height:30px;}
+ .notice{border-radius:10px;padding:14px 16px;font-size:13px;line-height:1.5;margin-bottom:16px;border:1px solid;}
+ .notice strong{font-weight:600;}
+ .notice-error{background:color-mix(in srgb,var(--red) 8%,transparent);border-color:color-mix(in srgb,var(--red) 30%,transparent);color:var(--red);}
+ .notice-ok{background:color-mix(in srgb,var(--green) 8%,transparent);border-color:color-mix(in srgb,var(--green) 30%,transparent);color:var(--green);}
+ .notice-warn{background:color-mix(in srgb,var(--amber) 9%,transparent);border-color:color-mix(in srgb,var(--amber) 32%,transparent);color:var(--amber);}
+ .notice-info{background:var(--bg-2);border-color:var(--line-2);color:var(--muted);}
+ .notice a{color:inherit;}
+ .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0;}
+
+ /* Auth / empty / skeleton */
+ .li-auth{text-align:center;padding:110px 20px;}
+ .li-auth h2{font-size:22px;font-weight:700;margin-bottom:12px;}
+ .li-auth p{color:var(--muted);font-size:14px;margin:0 auto 24px;max-width:440px;line-height:1.55;}
+ .li-empty{text-align:center;padding:56px 20px;color:var(--muted);border:1px dashed var(--line-2);border-radius:var(--radius);}
+ .li-empty h3{font-size:17px;font-weight:600;color:var(--text);margin-bottom:8px;}
+ .li-empty p{font-size:14px;line-height:1.55;max-width:440px;margin:0 auto;}
+ .skeleton{background:var(--skeleton-base);background-image:linear-gradient(90deg,var(--skeleton-base) 0%,var(--skeleton-sheen) 50%,var(--skeleton-base) 100%);background-size:200% 100%;border-radius:6px;animation:shimmer 1.4s ease-in-out infinite;}
+ @keyframes shimmer{0%{background-position:200% 0;}100%{background-position:-200% 0;}}
+ .cp-card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:20px;margin-bottom:16px;}
+ .cp-card h2{font-size:16px;font-weight:600;margin-bottom:6px;}
+ .cp-card p,.cp-card small{font-size:13px;color:var(--muted);line-height:1.55;}
+ .cp-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin:14px 0 0;}
+ .cp-stat{background:var(--bg-2);border:1px solid var(--line);border-radius:10px;padding:12px 14px;}
+ .cp-stat b{display:block;font-size:20px;font-weight:700;font-variant-numeric:tabular-nums;}
+ .cp-stat span{font-size:12px;color:var(--muted);}
+ .cp-row{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-top:12px;}
+ .cp-row input,.cp-field input,.cp-field select{flex:1;min-width:200px;width:100%;background:var(--bg-2);color:var(--text);border:1px solid var(--line-2);border-radius:8px;padding:9px 12px;font:inherit;font-size:13px;}
+ .cp-row input{width:auto;}
+ .cp-field{margin-top:12px;}
+ .cp-field label{display:block;font-size:12px;color:var(--muted);margin-bottom:5px;}
+ .mono{font-family:var(--mono);font-size:12px;word-break:break-all;}
+ .cp-table{width:100%;border-collapse:collapse;font-size:13px;margin-top:10px;}
+ .cp-table th{text-align:left;font-weight:500;color:var(--muted);font-size:12px;padding:8px;border-bottom:1px solid var(--line-2);}
+ .cp-table td{padding:10px 8px;border-bottom:1px solid var(--line);vertical-align:top;}
+ .cp-scroll{overflow-x:auto;}
+ .pill{display:inline-block;font-size:11px;font-weight:600;padding:2px 8px;border-radius:99px;border:1px solid var(--line-2);}
+ .pill.sent{color:var(--green);border-color:color-mix(in srgb,var(--green) 40%,transparent);}
+ .pill.held{color:var(--amber);border-color:color-mix(in srgb,var(--amber) 40%,transparent);}
+ .cp-flow{display:grid;gap:8px;margin-top:12px;}
+ .cp-leg{display:grid;grid-template-columns:90px 1fr;gap:12px;align-items:baseline;}
+ .cp-leg b{font-size:18px;font-variant-numeric:tabular-nums;}
+ .cp-leg span{font-size:13px;color:var(--muted);}
+ .cp-sched{list-style:none;margin-top:10px;}
+ .cp-sched li{display:flex;justify-content:space-between;gap:12px;padding:9px 0;border-bottom:1px solid var(--line);font-size:13px;}
+ .cp-sched li span:last-child{color:var(--muted);text-align:right;}
+ .cp-empty{padding:18px;text-align:center;color:var(--muted);font-size:13px;border:1px dashed var(--line-2);border-radius:10px;margin-top:10px;}
+ .cp-hold{margin-top:10px;font-size:13px;}
+ .cp-hold li{margin:6px 0 0 18px;line-height:1.5;}
+ @media(max-width:640px){.cp-stats{grid-template-columns:1fr;}.page-hero h1{font-size:24px;}.cp-leg{grid-template-columns:70px 1fr;}}
+ @media(prefers-reduced-motion:reduce){.skeleton{animation:none;}}
+ </style>
+ <link rel="canonical" href="https://three.ws/creator/payouts">
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:title" content="Creator payouts · three.ws">
+ <meta property="og:description" content="Register the wallet your agent's creator-fee share is paid to and see every distribution.">
+ <meta property="og:url" content="https://three.ws/creator/payouts">
+ <meta name="twitter:card" content="summary">
+ <meta name="twitter:site" content="@trythreews">
+ <meta name="twitter:title" content="Creator payouts · three.ws">
+ <meta name="twitter:description" content="Register the wallet your agent's creator-fee share is paid to and see every distribution.">
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="page-shell" id="main-content">
+ <nav class="crumbs" aria-label="Breadcrumb">
+ <a href="/dashboard">Dashboard</a>
+ <span aria-hidden="true">/</span>
+ <span class="here">Creator payouts</span>
+ </nav>
+ <div class="page-hero">
+ <div>
+ <h1>Creator payouts</h1>
+ <p>Your agent's coins earn creator fees. Register the wallet that receives your share, then watch each claim become a payout, or see exactly why it is held.</p>
+ </div>
+ <div class="page-actions">
+ <a href="/launch/intents" class="btn">Funded launches</a>
+ <a href="/approvals" class="btn">Approvals</a>
+ </div>
+ </div>
+
+ <div id="cp-auth" class="notice notice-info" hidden>
+ <strong>Sign in to manage payouts.</strong> Payout wallets belong to an agent you own.
+ <a href="/login?next=/creator/payouts" id="cp-login">Sign in</a>
+ </div>
+ <div id="cp-error" class="notice notice-error" role="alert" hidden></div>
+ <div id="cp-live" class="sr-only" aria-live="polite"></div>
+
+ <div id="cp-main" hidden>
+ <div class="cp-card">
+ <div class="cp-field" style="margin-top:0">
+ <label for="cp-agent">Agent</label>
+ <select id="cp-agent"></select>
+ </div>
+ </div>
+ <section id="cp-body" aria-label="Payout details" aria-busy="true">
+ <div class="cp-card"><div class="skeleton" style="height:18px;width:40%"></div><div class="skeleton" style="height:60px;margin-top:14px"></div></div>
+ <div class="cp-card"><div class="skeleton" style="height:18px;width:30%"></div><div class="skeleton" style="height:120px;margin-top:14px"></div></div>
+ </section>
+ </div>
+
+ <section class="cp-card" aria-labelledby="cp-how-h">
+ <h2 id="cp-how-h">How a claim becomes a payout</h2>
+ <div id="cp-flow" class="cp-flow"><div class="skeleton" style="height:48px"></div></div>
+ <ul id="cp-sched" class="cp-sched"></ul>
+ <p style="margin-top:10px">Schedules are read from the live cron definitions. Payouts under the minimum wait and add up across claims.</p>
+ </section>
+ </main>
+ <script src="/footer.js"></script>
+ <script type="module" src="/src/creator-payouts-page.js"></script>
+ </body>
+</html>
diff --git a/src/creator-payouts-page.js b/src/creator-payouts-page.js
new file mode 100644
index 000000000..af0aa4764
--- /dev/null
+++ b/src/creator-payouts-page.js
@@ -0,0 +1,393 @@
+// /creator/payouts: where an agent's creator-fee share is paid.
+//
+// The owner picks an agent, registers the wallet that receives their share
+// (the wallet signs a challenge in the browser, and a step-up confirms it is
+// really the owner at the keyboard), and sees totals, why anything is held,
+// and every distribution. The explainer at the bottom is read from
+// /api/creator-payouts?info=1, so cadence and the per-$100 split are never
+// hand-written copy.
+//
+// Nothing here moves funds. The page only registers a destination; the
+// distribution cron sends, and only when payouts are switched live.
+
+import { apiFetch } from './api.js';
+import { injectedProvider } from './launch/launch-wallet.js';
+import { shortAddress } from './shared/address.js';
+
+const $ = (id) => document.getElementById(id);
+const esc = (s) =>
+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+const fmtSol = (n) => Number(n || 0).toLocaleString('en-US', { maximumFractionDigits: 6 });
+const when = (iso) => (iso ? new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }) : 'n/a');
+
+const state = { agents: [], agentId: null, data: null, step: null, busy: false, error: null };
+
+async function call(path, { method = 'GET', body } = {}) {
+ const res = await apiFetch(path, {
+ method,
+ allowAnonymous: method === 'GET',
+ headers: body ? { 'content-type': 'application/json' } : undefined,
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ const data = await res.json().catch(() => ({}));
+ return { ok: res.ok, status: res.status, data: data?.data ?? data };
+}
+
+const describe = (data, fallback) => data?.error_description || data?.message || data?.error || fallback;
+
+function showError(msg) {
+ const el = $('cp-error');
+ el.textContent = msg || '';
+ el.hidden = !msg;
+}
+
+function announce(msg) {
+ $('cp-live').textContent = msg;
+}
+
+// ── Explainer (public, from ?info=1) ─────────────────────────────────────────
+
+async function loadInfo() {
+ const r = await call('/api/creator-payouts?info=1');
+ if (!r.ok) {
+ $('cp-flow').innerHTML = `<div class="cp-empty">Could not load the payout schedule (${esc(describe(r.data, `HTTP ${r.status}`))}). Reload to try again.</div>`;
+ return;
+ }
+ const legs = r.data.flow?.legs || [];
+ $('cp-flow').innerHTML = legs.length
+ ? legs
+ .map(
+ (l) =>
+ `<div class="cp-leg"><b>$${esc(l.usd)}</b><span><strong>${esc(l.label)}</strong>. ${esc(l.detail)}</span></div>`,
+ )
+ .join('') + `<small>Per $100 of creator fees claimed. Minimum payout ${esc(fmtSol(r.data.minimum_payout_sol))} SOL.</small>`
+ : '<div class="cp-empty">The split policy is not available right now.</div>';
+ $('cp-sched').innerHTML = (r.data.schedule || [])
+ .map((s) => `<li><span><strong>${esc(s.label)}</strong><br><small>${esc(s.does)}</small></span><span>${esc(s.cadence)}</span></li>`)
+ .join('');
+}
+
+// ── Owner view ───────────────────────────────────────────────────────────────
+
+function renderBody() {
+ const body = $('cp-body');
+ body.setAttribute('aria-busy', 'false');
+ const d = state.data;
+ if (!d) return;
+ const p = d.payouts;
+ const w = p.wallet;
+ const live = p.live;
+
+ const stats = `
+ <div class="cp-stats">
+ <div class="cp-stat"><b>${esc(fmtSol(p.total_sent_sol))}</b><span>SOL sent</span></div>
+ <div class="cp-stat"><b>${esc(fmtSol(p.total_pending_sol))}</b><span>SOL pending</span></div>
+ <div class="cp-stat"><b>${esc(fmtSol(p.total_held_sol))}</b><span>SOL held</span></div>
+ </div>`;
+
+ const held = p.held_reasons.length
+ ? `<ul class="cp-hold">${p.held_reasons
+ .map((h) => `<li><strong>${esc(fmtSol(h.sol))} SOL held: ${esc(h.label)}.</strong> ${esc(h.fix)}</li>`)
+ .join('')}</ul>`
+ : '';
+
+ const pauseNote = live
+ ? ''
+ : '<div class="notice notice-warn" style="margin-top:14px">Payouts are not switched on yet. Shares are recorded and shown here, and are sent once payouts go live.</div>';
+
+ let walletBlock;
+ if (w.wallet) {
+ walletBlock = `<p>Payouts go to <span class="mono">${esc(w.wallet)}</span>, registered ${esc(when(w.registered_at))}.</p>`;
+ } else if (w.pending) {
+ walletBlock = '<p>No active payout wallet yet.</p>';
+ } else {
+ walletBlock = '<div class="cp-empty">No payout wallet registered. Register one below and your share is sent there. Until then it is held, never lost.</div>';
+ }
+ const pending = w.pending
+ ? `<div class="notice notice-warn" style="margin-top:12px">
+ <strong>Wallet change pending.</strong> <span class="mono">${esc(w.pending.wallet)}</span> takes effect ${esc(when(w.pending.effective_at))}
+ (a ${esc(w.cooldown_hours)} hour wait protects you if someone else changed it). Payouts are held until then.
+ <div class="cp-row"><button class="btn btn-sm btn-danger" data-act="cancel" ${state.busy ? 'disabled' : ''}>Cancel change</button></div>
+ </div>`
+ : '';
+
+ const step = state.step ? renderStep() : '';
+ const regBtn = !state.step
+ ? `<div class="cp-row"><button class="btn btn-primary" data-act="register" ${state.busy ? 'disabled' : ''}>${w.wallet ? 'Change payout wallet' : 'Register payout wallet'} with a connected wallet</button></div>
+ <small>You sign a message with the wallet to prove you control it. Nothing is spent. ${w.wallet ? `A change waits ${esc(w.cooldown_hours)} hours before it applies.` : ''}</small>`
+ : '';
+
+ const rows = p.recent_distributions;
+ const table = rows.length
+ ? `<div class="cp-scroll"><table class="cp-table"><thead><tr><th>Date</th><th>Coin</th><th>Share (SOL)</th><th>Status</th><th>Transfer</th></tr></thead><tbody>${rows
+ .map(
+ (r) => `<tr>
+ <td>${esc(when(r.at))}</td>
+ <td class="mono">${esc(shortAddress(r.mint, 4, 4))}</td>
+ <td>${esc(fmtSol(r.sol))}</td>
+ <td><span class="pill ${esc(r.status)}">${esc(r.status)}</span>${r.hold_reason ? `<br><small>${esc(r.hold?.label || r.hold_reason)}</small>` : ''}</td>
+ <td>${r.signature ? `<a class="mono" target="_blank" rel="noopener" href="${esc(r.explorer)}">${esc(shortAddress(r.signature, 6, 6))}</a>` : 'n/a'}</td>
+ </tr>`,
+ )
+ .join('')}</tbody></table></div>`
+ : '<div class="cp-empty">No distributions yet. When one of this agent\'s coins earns creator fees and the fees are claimed, your share appears here.</div>';
+
+ body.innerHTML = `
+ <div class="cp-card">
+ <h2>Payout wallet</h2>
+ ${walletBlock}${pending}${pauseNote}${step}${regBtn}
+ <div id="cp-reg-err" class="notice notice-error" role="alert" style="margin-top:12px" ${state.error ? '' : 'hidden'}>${esc(state.error)}</div>
+ </div>
+ <div class="cp-card">
+ <h2>Earnings</h2>
+ <p>Minimum payout ${esc(fmtSol(p.minimum_payout_sol))} SOL. Smaller shares wait and add up.</p>
+ ${stats}${held}
+ </div>
+ <div class="cp-card">
+ <div class="cp-row" style="margin-top:0;justify-content:space-between">
+ <h2 style="margin:0">Distributions</h2>
+ <button class="btn btn-sm" data-act="csv" ${rows.length ? '' : 'disabled'}>Export CSV</button>
+ </div>
+ ${table}
+ </div>`;
+ bind();
+}
+
+function renderStep() {
+ const s = state.step;
+ return `<div class="cp-field" style="border:1px solid var(--line-2);border-radius:10px;padding:14px">
+ <strong style="font-size:13px">Confirm it is you</strong>
+ <p>Registering <span class="mono">${esc(shortAddress(s.wallet, 6, 6))}</span> as the payout wallet needs your account password or an emailed code.</p>
+ <div class="cp-row">
+ <button class="btn btn-sm" data-method="password" aria-pressed="${s.method === 'password'}">Password</button>
+ <button class="btn btn-sm" data-method="email_code" aria-pressed="${s.method === 'email_code'}">Emailed code</button>
+ ${s.method === 'email_code' ? `<button class="btn btn-sm" data-act="send-code" ${s.busy ? 'disabled' : ''}>${s.codeSent ? 'Resend code' : 'Send code'}</button>` : ''}
+ </div>
+ <div class="cp-field"><label for="cp-proof">${s.method === 'password' ? 'Password' : 'Code from the email'}</label>
+ <input id="cp-proof" type="${s.method === 'password' ? 'password' : 'text'}" autocomplete="${s.method === 'password' ? 'current-password' : 'one-time-code'}" /></div>
+ ${s.err ? `<div class="notice notice-error" role="alert" style="margin-top:12px">${esc(s.err)}</div>` : ''}
+ <div class="cp-row">
+ <button class="btn btn-primary" data-act="confirm" ${s.busy ? 'disabled' : ''}>${s.busy ? 'Working' : 'Confirm and sign'}</button>
+ <button class="btn" data-act="step-cancel" ${s.busy ? 'disabled' : ''}>Back</button>
+ </div>
+ </div>`;
+}
+
+function bind() {
+ const body = $('cp-body');
+ body.querySelector('[data-act="register"]')?.addEventListener('click', startRegister);
+ body.querySelector('[data-act="cancel"]')?.addEventListener('click', cancelPending);
+ body.querySelector('[data-act="csv"]')?.addEventListener('click', downloadCsv);
+ body.querySelector('[data-act="step-cancel"]')?.addEventListener('click', () => {
+ state.step = null;
+ state.error = null;
+ renderBody();
+ });
+ body.querySelector('[data-act="send-code"]')?.addEventListener('click', sendCode);
+ body.querySelector('[data-act="confirm"]')?.addEventListener('click', confirmRegister);
+ body.querySelectorAll('[data-method]').forEach((b) =>
+ b.addEventListener('click', () => {
+ state.step.method = b.dataset.method;
+ state.step.err = null;
+ renderBody();
+ $('cp-proof')?.focus();
+ }),
+ );
+ $('cp-proof')?.addEventListener('keydown', (ev) => {
+ if (ev.key === 'Enter') confirmRegister();
+ });
+}
+
+async function load() {
+ $('cp-body').setAttribute('aria-busy', 'true');
+ const r = await call(`/api/creator-payouts?agent=${encodeURIComponent(state.agentId)}`);
+ if (!r.ok) {
+ showError(`Could not load payouts: ${describe(r.data, `HTTP ${r.status}`)}`);
+ $('cp-body').innerHTML = '<div class="cp-card"><div class="cp-empty">Payout details are unavailable. <button class="btn btn-sm" id="cp-retry">Try again</button></div></div>';
+ $('cp-body').setAttribute('aria-busy', 'false');
+ $('cp-retry')?.addEventListener('click', () => {
+ showError('');
+ load();
+ });
+ return;
+ }
+ showError('');
+ state.data = r.data;
+ renderBody();
+}
+
+// ── Register a payout wallet ─────────────────────────────────────────────────
+
+async function startRegister() {
+ state.error = null;
+ const provider = injectedProvider();
+ if (!provider) {
+ state.error = 'No Solana wallet found in this browser. Install Phantom, Backpack or Solflare, then try again.';
+ renderBody();
+ return;
+ }
+ let address;
+ try {
+ const resp = await provider.connect();
+ address = (resp?.publicKey || provider.publicKey)?.toString();
+ } catch {
+ state.error = 'The wallet connection was declined.';
+ renderBody();
+ return;
+ }
+ if (!address) {
+ state.error = 'Could not read the wallet address.';
+ renderBody();
+ return;
+ }
+ state.step = { wallet: address, method: 'password', codeSent: false, busy: false, err: null };
+ renderBody();
+ $('cp-proof')?.focus();
+}
+
+async function sendCode() {
+ const s = state.step;
+ s.busy = true;
+ s.err = null;
+ renderBody();
+ const r = await call('/api/wallet-whitelist', {
+ method: 'POST',
+ body: { action: 'stepup_code', agent_id: state.agentId, kind: 'payout_wallet', op: { wallet: s.wallet } },
+ });
+ s.busy = false;
+ if (r.ok) {
+ s.codeSent = true;
+ announce('Code sent to your email');
+ } else s.err = describe(r.data, 'Could not send the code.');
+ renderBody();
+ $('cp-proof')?.focus();
+}
+
+async function confirmRegister() {
+ const s = state.step;
+ if (!s || s.busy) return;
+ const proofVal = $('cp-proof')?.value || '';
+ if (!proofVal) {
+ s.err = s.method === 'password' ? 'Enter your password.' : 'Enter the code from the email.';
+ renderBody();
+ return;
+ }
+ s.busy = true;
+ s.err = null;
+ renderBody();
+ const fail = (msg) => {
+ s.busy = false;
+ s.err = msg;
+ renderBody();
+ };
+
+ const grant = await call('/api/wallet-whitelist', {
+ method: 'POST',
+ body: {
+ action: 'stepup',
+ agent_id: state.agentId,
+ kind: 'payout_wallet',
+ op: { wallet: s.wallet },
+ method: s.method,
+ proof: s.method === 'password' ? { password: proofVal } : { code: proofVal },
+ },
+ });
+ if (!grant.ok) return fail(describe(grant.data, 'Confirmation failed.'));
+
+ const ch = await call('/api/creator-payouts', {
+ method: 'POST',
+ body: { action: 'challenge', agent_id: state.agentId, wallet: s.wallet },
+ });
+ if (!ch.ok) return fail(describe(ch.data, 'Could not start the signature.'));
+
+ let signature;
+ try {
+ const provider = injectedProvider();
+ const signed = await provider.signMessage(new TextEncoder().encode(ch.data.message), 'utf8');
+ const bytes = signed?.signature || signed;
+ signature = btoa(String.fromCharCode(...new Uint8Array(bytes)));
+ } catch {
+ return fail('The wallet did not sign. Approve the signature request to register the wallet.');
+ }
+
+ const reg = await call('/api/creator-payouts', {
+ method: 'POST',
+ body: {
+ action: 'register',
+ agent_id: state.agentId,
+ wallet: s.wallet,
+ message: ch.data.message,
+ signature,
+ grant: grant.data.grant || grant.data.id,
+ },
+ });
+ if (!reg.ok) return fail(describe(reg.data, 'Registration failed.'));
+
+ state.step = null;
+ announce('Payout wallet saved');
+ await load();
+}
+
+async function cancelPending() {
+ state.busy = true;
+ renderBody();
+ const r = await call('/api/creator-payouts', { method: 'POST', body: { action: 'cancel', agent_id: state.agentId } });
+ state.busy = false;
+ if (!r.ok) state.error = describe(r.data, 'Could not cancel the change.');
+ else announce('Pending change cancelled');
+ await load();
+}
+
+async function downloadCsv() {
+ try {
+ const res = await apiFetch(`/api/creator-payouts?agent=${encodeURIComponent(state.agentId)}&format=csv`);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const url = URL.createObjectURL(await res.blob());
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `creator-payouts-${state.agentId}.csv`;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ URL.revokeObjectURL(url);
+ } catch (e) {
+ showError(`Could not export the CSV: ${e.message}`);
+ }
+}
+
+// ── Boot ─────────────────────────────────────────────────────────────────────
+
+async function boot() {
+ loadInfo();
+ const agents = await call('/api/agents');
+ if (agents.status === 401 || agents.status === 403) {
+ $('cp-auth').hidden = false;
+ $('cp-login').href = `/login?next=${encodeURIComponent(window.location.pathname)}`;
+ return;
+ }
+ if (!agents.ok) {
+ showError(`Could not load your agents: ${describe(agents.data, `HTTP ${agents.status}`)}`);
+ return;
+ }
+ state.agents = (agents.data.agents || []).filter((a) => a.id);
+ $('cp-main').hidden = false;
+ if (!state.agents.length) {
+ $('cp-body').setAttribute('aria-busy', 'false');
+ $('cp-body').innerHTML = '<div class="cp-card"><div class="cp-empty">You have no agents yet. <a href="/create">Create one</a> and launch a coin to start earning creator fees.</div></div>';
+ return;
+ }
+ const sel = $('cp-agent');
+ sel.innerHTML = state.agents.map((a) => `<option value="${esc(a.id)}">${esc(a.name || a.id)}</option>`).join('');
+ const fromUrl = new URLSearchParams(window.location.search).get('agent');
+ state.agentId = state.agents.some((a) => a.id === fromUrl) ? fromUrl : state.agents[0].id;
+ sel.value = state.agentId;
+ sel.addEventListener('change', () => {
+ state.agentId = sel.value;
+ state.step = null;
+ state.error = null;
+ load();
+ });
+ await load();
+}
+
+boot();
diff --git a/src/shared/agent-earnings-card.js b/src/shared/agent-earnings-card.js
index a3c678db4..efab9abeb 100644
--- a/src/shared/agent-earnings-card.js
+++ b/src/shared/agent-earnings-card.js
@@ -197,6 +197,17 @@ function subline(zero, coins, service) {
return 'Nothing earned yet. Creator fees accrue with every trade of this agent’s coin.';
}
+function payoutLine(p) {
+ if (!p) return '';
+ const w = p.wallet?.wallet;
+ const parts = [];
+ if (Number(p.total_sent_sol) > 0) parts.push(`${fmtSol(p.total_sent_sol)} sent`);
+ if (Number(p.total_pending_sol) > 0) parts.push(`${fmtSol(p.total_pending_sol)} pending`);
+ if (Number(p.total_held_sol) > 0) parts.push(`${fmtSol(p.total_held_sol)} held`);
+ const where = w ? `Paid to ${shortAddr(w)}` : 'No payout wallet registered';
+ return `<p class="ern-sub">${esc(where)}${parts.length ? ` · ${esc(parts.join(' · '))}` : ''}</p>`;
+}
+
function render(d) {
const lifetime = d.lifetime_creator_fees || {};
const service = d.service_income || {};
@@ -246,6 +257,7 @@ function render(d) {
`<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>
+ ${payoutLine(d.payouts)}
${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)}
diff --git a/tests/creator-payouts.test.js b/tests/creator-payouts.test.js
new file mode 100644
index 000000000..938fe6a6e
--- /dev/null
+++ b/tests/creator-payouts.test.js
@@ -0,0 +1,216 @@
+// Creator-fee payouts: the held reasons, the signed payout-wallet message and its
+// replay guard, the cron reading, the per-$100 flow and the CSV export.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { generateKeyPairSync, sign } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import bs58 from 'bs58';
+
+const state = { nonces: new Set(), wallet: null, grants: 0, agentOwner: 'user-1' };
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...vals) => {
+ const q = strings.join('?');
+ if (q.includes('FROM agent_identities')) return [{ id: vals[0], user_id: state.agentOwner, name: 'Test agent' }];
+ if (q.includes('INSERT INTO creator_payout_nonces')) {
+ if (state.nonces.has(vals[0])) return [];
+ state.nonces.add(vals[0]);
+ return [{ nonce: vals[0] }];
+ }
+ if (q.includes('UPDATE creator_payout_wallets') && q.includes('RETURNING agent_id, user_id, wallet')) return [];
+ if (q.includes('SELECT * FROM creator_payout_wallets')) {
+ return state.wallet ? [{ agent_id: vals[0], wallet: state.wallet, registered_at: new Date().toISOString(), pending_wallet: null }] : [];
+ }
+ if (q.includes('INSERT INTO creator_payout_wallets')) {
+ state.wallet = vals[2];
+ return [];
+ }
+ return [];
+ }),
+}));
+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
+vi.mock('../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn() }));
+vi.mock('../api/_lib/notify.js', () => ({ insertNotification: vi.fn(async () => ({ id: 'n' })) }));
+vi.mock('../api/_lib/destination-whitelist.js', async (orig) => {
+ const real = await orig();
+ return { ...real, consumeGrant: vi.fn(async () => { state.grants += 1; return 'wallet'; }) };
+});
+
+const core = await import('../api/_lib/creator-payouts-core.js');
+const lib = await import('../api/_lib/creator-payouts.js');
+
+const AGENT = '11111111-2222-4333-8444-555555555555';
+const NOW = Date.UTC(2026, 9, 23, 12, 0, 0);
+
+function newWallet() {
+ const { publicKey, privateKey } = generateKeyPairSync('ed25519');
+ const raw = publicKey.export({ format: 'der', type: 'spki' }).subarray(-32);
+ return { address: bs58.encode(raw), signMessage: (m) => bs58.encode(sign(null, Buffer.from(m), privateKey)) };
+}
+
+const H = (over) => ({
+ activeWallet: 'W', pendingWallet: null, pendingEffectiveAt: null, unsentLamports: 50_000_000n, live: true, now: NOW, ...over,
+});
+
+describe('holdReason', () => {
+ it('is null when a registered wallet, enough volume and live distribution line up', () => {
+ expect(core.holdReason(H())).toBeNull();
+ });
+ it('holds an unregistered agent until a wallet is signed', () => {
+ expect(core.holdReason(H({ activeWallet: null }))).toBe('wallet_not_registered');
+ });
+ it('holds during the cooldown of a changed wallet, even though the old one is active', () => {
+ const later = new Date(NOW + 3_600_000).toISOString();
+ expect(core.holdReason(H({ pendingWallet: 'N', pendingEffectiveAt: later }))).toBe('cooldown');
+ });
+ it('releases once the cooldown has ended', () => {
+ const past = new Date(NOW - 1000).toISOString();
+ expect(core.holdReason(H({ pendingWallet: 'N', pendingEffectiveAt: past }))).toBeNull();
+ });
+ it('holds shares under the minimum until they add up', () => {
+ expect(core.holdReason(H({ unsentLamports: BigInt(core.MIN_PAYOUT_LAMPORTS - 1) }))).toBe('below_minimum');
+ expect(core.holdReason(H({ unsentLamports: BigInt(core.MIN_PAYOUT_LAMPORTS) }))).toBeNull();
+ });
+ it('says so when distribution is switched off', () => {
+ expect(core.holdReason(H({ live: false }))).toBe('payouts_paused');
+ });
+ it('puts the owner-actionable reason first', () => {
+ expect(core.holdReason(H({ activeWallet: null, unsentLamports: 1n, live: false }))).toBe('wallet_not_registered');
+ });
+ it('gives every reason a label and a fix', () => {
+ for (const r of Object.values(core.HOLD_REASONS)) {
+ expect(r.label.length).toBeGreaterThan(5);
+ expect(r.fix.length).toBeGreaterThan(20);
+ }
+ });
+});
+
+describe('registration message', () => {
+ const base = { agentId: AGENT, wallet: 'W'.repeat(44), nonce: 'a'.repeat(32), issuedAt: new Date(NOW).toISOString() };
+ it('round-trips', () => {
+ const msg = core.buildRegistrationMessage(base);
+ expect(core.checkRegistrationMessage(msg, { agentId: AGENT, wallet: base.wallet, now: NOW })).toMatchObject({ ok: true, nonce: base.nonce });
+ });
+ it('refuses a message for another agent or wallet', () => {
+ const msg = core.buildRegistrationMessage(base);
+ expect(core.checkRegistrationMessage(msg, { agentId: '99999999-2222-4333-8444-555555555555', wallet: base.wallet, now: NOW }).code).toBe('wrong_agent');
+ expect(core.checkRegistrationMessage(msg, { agentId: AGENT, wallet: 'X'.repeat(44), now: NOW }).code).toBe('wrong_wallet');
+ });
+ it('refuses a stale or future timestamp', () => {
+ const msg = core.buildRegistrationMessage(base);
+ expect(core.checkRegistrationMessage(msg, { agentId: AGENT, wallet: base.wallet, now: NOW + core.MESSAGE_MAX_AGE_MS + 1 }).code).toBe('message_expired');
+ expect(core.checkRegistrationMessage(msg, { agentId: AGENT, wallet: base.wallet, now: NOW - core.MESSAGE_MAX_FUTURE_MS - 1 }).code).toBe('invalid_timestamp');
+ });
+ it('refuses free text', () => {
+ expect(core.checkRegistrationMessage('hello', { agentId: AGENT, wallet: 'W', now: NOW }).code).toBe('invalid_message');
+ });
+});
+
+describe('registerPayoutWallet', () => {
+ const actor = { kind: 'owner', userId: 'user-1', sessionId: 'sess-1' };
+ beforeEach(() => {
+ state.nonces.clear();
+ state.wallet = null;
+ state.grants = 0;
+ });
+
+ async function signedFor(w, over = {}) {
+ const nonce = over.nonce || 'b'.repeat(32);
+ const message = core.buildRegistrationMessage({ agentId: AGENT, wallet: w.address, nonce, issuedAt: new Date(NOW).toISOString() });
+ return { message, signature: w.signMessage(message) };
+ }
+
+ it('registers the first wallet at once and spends one grant', async () => {
+ const w = newWallet();
+ const { message, signature } = await signedFor(w);
+ const out = await lib.registerPayoutWallet({ actor, agentId: AGENT, wallet: w.address, message, signature, grantId: 'g', now: NOW });
+ expect(out.outcome).toBe('registered');
+ expect(state.grants).toBe(1);
+ });
+
+ it('refuses a replay of the same signed message and does not spend a second grant', async () => {
+ const w = newWallet();
+ const { message, signature } = await signedFor(w);
+ await lib.registerPayoutWallet({ actor, agentId: AGENT, wallet: w.address, message, signature, grantId: 'g', now: NOW });
+ await expect(lib.registerPayoutWallet({ actor, agentId: AGENT, wallet: w.address, message, signature, grantId: 'g2', now: NOW + 1000 }))
+ .rejects.toMatchObject({ code: 'nonce_used', status: 409 });
+ expect(state.grants).toBe(1);
+ });
+
+ it('refuses a signature from a different key', async () => {
+ const w = newWallet();
+ const other = newWallet();
+ const { message } = await signedFor(w);
+ await expect(lib.registerPayoutWallet({ actor, agentId: AGENT, wallet: w.address, message, signature: other.signMessage(message), grantId: 'g', now: NOW }))
+ .rejects.toMatchObject({ code: 'bad_signature' });
+ expect(state.nonces.size).toBe(0);
+ });
+
+ it('refuses a bearer or API key, which has no browser session', async () => {
+ const w = newWallet();
+ const { message, signature } = await signedFor(w);
+ await expect(lib.registerPayoutWallet({ actor: { kind: 'api_key', userId: 'user-1', sessionId: null }, agentId: AGENT, wallet: w.address, message, signature, grantId: 'g', now: NOW }))
+ .rejects.toMatchObject({ code: 'session_required' });
+ });
+
+ it('refuses someone who does not own the agent', async () => {
+ const w = newWallet();
+ const { message, signature } = await signedFor(w);
+ await expect(lib.registerPayoutWallet({ actor: { ...actor, userId: 'intruder' }, agentId: AGENT, wallet: w.address, message, signature, grantId: 'g', now: NOW }))
+ .rejects.toMatchObject({ code: 'forbidden' });
+ });
+});
+
+describe('flow, schedule and csv', () => {
+ it('builds the per-$100 flow from the split policy and it sums to the amount', () => {
+ const f = core.flowPer100();
+ expect(f.legs.reduce((s, l) => s + l.usd, 0)).toBeCloseTo(100, 6);
+ expect(f.total_bps).toBe(10_000);
+ expect(f.legs.map((l) => l.role)).toEqual(['seller', 'treasury']);
+ });
+
+ it('reads the cadence of every stage from the real vercel.json crons', () => {
+ const crons = JSON.parse(readFileSync(new URL('../vercel.json', import.meta.url), 'utf8')).crons;
+ const sched = core.payoutSchedule(crons);
+ expect(sched.map((s) => s.key)).toEqual(['snapshot', 'claim', 'distribute', 'reconcile']);
+ for (const s of sched) expect(s.schedule, s.path).toBeTruthy();
+ expect(sched.find((s) => s.key === 'claim').cadence).toBe('every 5 minutes');
+ });
+
+ it('does not claim more than an unfamiliar cron says', () => {
+ expect(core.describeCron('0 6 * * 1')).toBe('cron 0 6 * * 1 (UTC)');
+ expect(core.describeCron('20 * * * *')).toBe('every hour at :20');
+ expect(core.describeCron('0 * * * *')).toBe('every hour, on the hour');
+ expect(core.describeCron('50 */3 * * *')).toBe('every 3 hours at :50');
+ expect(core.describeCron('11,41 * * * *')).toBe('twice an hour, at :11 and :41');
+ });
+
+ it('shares are claim minus the buyback earmark', () => {
+ expect(core.creatorShareLamports(100_000_000, 0.05)).toBe(50_000_000n);
+ expect(core.creatorShareLamports(100_000_000, 0.2)).toBe(0n);
+ });
+
+ it('summarises sent, pending and held with per-reason held amounts', () => {
+ const t = core.summarizeDistributions([
+ { status: 'sent', creator_lamports: '5' },
+ { status: 'pending', creator_lamports: '2' },
+ { status: 'sending', creator_lamports: '1' },
+ { status: 'held', creator_lamports: '7', hold_reason: 'cooldown' },
+ { status: 'held', creator_lamports: '3', hold_reason: 'cooldown' },
+ ]);
+ expect(t.sent).toBe(5n);
+ expect(t.pending).toBe(3n);
+ expect(t.held).toBe(10n);
+ expect(t.held_by_reason.cooldown).toBe(10n);
+ });
+
+ it('exports csv and neutralises spreadsheet formulas', () => {
+ const csv = core.distributionsToCsv([
+ { created_at: '2026-10-23T00:00:00Z', agent_id: AGENT, mint: 'M', status: 'held', hold_reason: 'cooldown', creator_lamports: '1500000000', payout_wallet: '=HYPERLINK("x")', claim_sig: 'c', tx_signature: null },
+ ]);
+ const [head, row] = csv.trim().split('\n');
+ expect(head).toBe(core.DISTRIBUTION_CSV_COLUMNS.join(','));
+ expect(row).toContain(',1.5,');
+ expect(row).toContain(`"'=HYPERLINK(""x"")"`);
+ });
+});
diff --git a/vercel.json b/vercel.json
index 48a55b0ad..abb663edf 100644
--- a/vercel.json
+++ b/vercel.json
@@ -7646,6 +7646,14 @@
{
"path": "/api/cron/event-market-announce",
"schedule": "*/15 * * * *"
+ },
+ {
+ "path": "/api/cron/revenue-ledger-reconcile",
+ "schedule": "11 * * * *"
+ },
+ {
+ "path": "/api/cron/revenue-reinvest",
+ "schedule": "37 * * * *"
}
]
}
diff --git a/vite.config.js b/vite.config.js
index fcbbf4da4..74feb6684 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -1064,6 +1064,7 @@ const appConfig = {
'launch-paired': resolve(__dirname, 'pages/launch-paired.html'),
'launch-uniswap': resolve(__dirname, 'pages/launch-uniswap.html'),
'launch-intent': resolve(__dirname, 'pages/launch-intent.html'),
+ 'creator-payouts': resolve(__dirname, 'pages/creator-payouts.html'),
credits: resolve(__dirname, 'pages/credits.html'),
'mcp-plans': resolve(__dirname, 'pages/mcp-plans.html'),
domains: resolve(__dirname, 'pages/domains.html'),
@@ -1899,6 +1900,8 @@ const appConfig = {
'/launch/uniswap/': resolve(root, 'pages/launch-uniswap.html'),
'/launch/intents': resolve(root, 'pages/launch-intent.html'),
'/launch/intents/': resolve(root, 'pages/launch-intent.html'),
+ '/creator/payouts': resolve(root, 'pages/creator-payouts.html'),
+ '/creator/payouts/': resolve(root, 'pages/creator-payouts.html'),
'/markets/robinhood/portfolios': resolve(root, 'pages/hood-portfolios.html'),
'/markets/robinhood/portfolios/': resolve(root, 'pages/hood-portfolios.html'),
'/markets/robinhood/portfolios/universe': resolve(root, 'pages/hood-portfolios-universe.html'),