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 a revenue ledger with reconciliation and creator payout core logic, with tests

nirholas03a1e149b4f0
diff --git a/api/_lib/creator-payouts-core.js b/api/_lib/creator-payouts-core.js
new file mode 100644
index 000000000..a9d3b02e6
--- /dev/null
+++ b/api/_lib/creator-payouts-core.js
@@ -0,0 +1,258 @@
+// Pure logic for creator-fee payouts: the signed payout-wallet message, the
+// reasons a distribution is held, the per-$100 flow explainer, a plain-language
+// reading of a cron expression, and the CSV export. No I/O lives here so every
+// rule is unit-testable (tests/creator-payouts.test.js); api/_lib/creator-payouts.js
+// does the database and chain work around it.
+
+import { CREATOR_FEE_CLAIM_POLICY } from './token/config.js';
+
+export const LAMPORTS_PER_SOL = 1_000_000_000;
+/** A creator share below this stays held until the unsent total reaches it. */
+export const MIN_PAYOUT_LAMPORTS = 10_000_000;
+/** A changed payout wallet receives nothing until this long after the signed change. */
+export const WALLET_CHANGE_COOLDOWN_MS = 48 * 3_600_000;
+/** A signed registration message is only honoured this long after it was issued. */
+export const MESSAGE_MAX_AGE_MS = 5 * 60_000;
+export const MESSAGE_MAX_FUTURE_MS = 60_000;
+/** SOL kept in the agent wallet so it can still pay network fees and stay rent-exempt. */
+export const WALLET_RESERVE_LAMPORTS = 2_000_000;
+
+export const HOLD_REASONS = Object.freeze({
+ wallet_not_registered: {
+ label: 'No payout wallet registered',
+ fix: 'Register a payout wallet by signing a message with it. Held shares are sent on the next distribution after you do.',
+ },
+ cooldown: {
+ label: 'Payout wallet change in cooldown',
+ fix: 'A new payout wallet receives funds only after the cooldown ends. Cancel the change if you did not make it.',
+ },
+ below_minimum: {
+ label: 'Below the minimum payout',
+ fix: 'Shares are batched until your unsent total reaches the minimum, so a transfer is never smaller than its worth.',
+ },
+ agent_wallet_low: {
+ label: 'Agent wallet balance too low',
+ fix: 'The agent wallet holds less SOL than this payout plus a fee reserve. Top it up or wait for more claims to land.',
+ },
+ payouts_paused: {
+ label: 'Distribution not enabled yet',
+ fix: 'The operator has not switched on automatic distribution. Shares stay recorded and are sent when it is enabled.',
+ },
+ signing_unavailable: {
+ label: 'Agent wallet cannot sign payouts',
+ fix: 'This agent uses self-custody or an unavailable signer, so the platform cannot send its payout. Claim and withdraw from the wallet directly.',
+ },
+});
+
+/** Every status a distribution row can be in. */
+export const DISTRIBUTION_STATUSES = Object.freeze(['pending', 'held', 'sending', 'sent']);
+
+// ── Signed payout-wallet message ─────────────────────────────────────────────
+
+const NONCE_RE = /^[0-9a-f]{32}$/;
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+export const isNonce = (v) => typeof v === 'string' && NONCE_RE.test(v);
+export const isSolanaAddress = (v) => typeof v === 'string' && BASE58_RE.test(v);
+
+/** The exact text the payout wallet signs. Ed25519 over these UTF-8 bytes. */
+export function buildRegistrationMessage({ agentId, wallet, nonce, issuedAt }) {
+ return [
+ 'three.ws creator payout wallet',
+ `Agent: ${agentId}`,
+ `Wallet: ${wallet}`,
+ `Nonce: ${nonce}`,
+ `Issued: ${issuedAt}`,
+ 'Signing this message makes this wallet the destination for this agent\'s creator-fee payouts.',
+ ].join('\n');
+}
+
+/**
+ * Parse and check a registration message against the request it arrived with.
+ * Returns `{ ok: true, nonce, issuedAt }` or `{ ok: false, code, message }`.
+ * Replay protection (the nonce being unused) is the caller's atomic insert.
+ */
+export function checkRegistrationMessage(message, { agentId, wallet, now = Date.now() }) {
+ const m = /^three\.ws creator payout wallet\nAgent: (\S+)\nWallet: (\S+)\nNonce: (\S+)\nIssued: (\S+)\nSigning this message makes this wallet the destination for this agent's creator-fee payouts\.$/.exec(
+ String(message || ''),
+ );
+ if (!m) return { ok: false, code: 'invalid_message', message: 'The signed message is not the payout registration message.' };
+ const [, msgAgent, msgWallet, nonce, issuedAt] = m;
+ if (!UUID_RE.test(msgAgent) || msgAgent.toLowerCase() !== String(agentId).toLowerCase()) {
+ return { ok: false, code: 'wrong_agent', message: 'The signed message is for a different agent.' };
+ }
+ if (msgWallet !== wallet) return { ok: false, code: 'wrong_wallet', message: 'The signed message names a different wallet.' };
+ if (!isNonce(nonce)) return { ok: false, code: 'invalid_nonce', message: 'The nonce in the signed message is malformed.' };
+ const issued = Date.parse(issuedAt);
+ if (!Number.isFinite(issued)) return { ok: false, code: 'invalid_timestamp', message: 'The timestamp in the signed message is not valid.' };
+ if (now - issued > MESSAGE_MAX_AGE_MS) return { ok: false, code: 'message_expired', message: 'That signed message has expired. Request a new one and sign again.' };
+ if (issued - now > MESSAGE_MAX_FUTURE_MS) return { ok: false, code: 'invalid_timestamp', message: 'The timestamp in the signed message is in the future.' };
+ return { ok: true, nonce, issuedAt };
+}
+
+// ── Held reasons ─────────────────────────────────────────────────────────────
+
+/**
+ * Why an agent's unsent creator share cannot go out right now, or null when it
+ * can. Order matters and is the order an owner can act on: register first, wait
+ * out a cooldown, then volume, then the platform-side conditions.
+ *
+ * @param {{
+ * activeWallet: string | null,
+ * pendingWallet: string | null,
+ * pendingEffectiveAt: Date | string | null,
+ * unsentLamports: bigint,
+ * minimumLamports?: bigint,
+ * live: boolean,
+ * now?: number,
+ * }} s
+ */
+export function holdReason(s) {
+ const now = s.now ?? Date.now();
+ const min = s.minimumLamports ?? BigInt(MIN_PAYOUT_LAMPORTS);
+ if (s.pendingWallet) {
+ const eff = s.pendingEffectiveAt ? new Date(s.pendingEffectiveAt).getTime() : Infinity;
+ if (eff > now) return 'cooldown';
+ }
+ if (!s.activeWallet && !s.pendingWallet) return 'wallet_not_registered';
+ if (s.unsentLamports < min) return 'below_minimum';
+ if (!s.live) return 'payouts_paused';
+ return null;
+}
+
+// ── Per-$100 flow explainer ──────────────────────────────────────────────────
+
+/**
+ * Where $100 of claimed creator fees goes, generated from a split policy. The
+ * policy is data (api/_lib/token/config.js CREATOR_FEE_CLAIM_POLICY), so
+ * the explainer can never drift from what the claimer earmarks.
+ */
+export function flowPer100(policy = CREATOR_FEE_CLAIM_POLICY, amountUsd = 100) {
+ if (!Array.isArray(policy) || !policy.length) return { amount_usd: amountUsd, legs: [] };
+ const total = policy.reduce((s, l) => s + l.bps, 0);
+ const meta = {
+ seller: { label: 'You (your payout wallet)', detail: 'Sent to the payout wallet you registered, in batches of at least the minimum payout.' },
+ treasury: { label: 'Platform buyback', detail: 'Earmarked for the platform $THREE buyback, not paid out.' },
+ rewards: { label: 'Holder rewards', detail: 'Reflected to holders.' },
+ };
+ return {
+ amount_usd: amountUsd,
+ total_bps: total,
+ legs: policy.map((l) => ({
+ role: l.role,
+ bps: l.bps,
+ usd: Math.round((amountUsd * l.bps) / 100) / 100,
+ label: meta[l.role]?.label || l.role,
+ detail: meta[l.role]?.detail || '',
+ })),
+ };
+}
+
+/** The creator's share of a claim in lamports, given the buyback share recorded with it. */
+export function creatorShareLamports(claimedLamports, buybackSol) {
+ const claimed = BigInt(claimedLamports || 0);
+ const buyback = BigInt(Math.round(Number(buybackSol || 0) * LAMPORTS_PER_SOL));
+ const share = claimed - buyback;
+ return share > 0n ? share : 0n;
+}
+
+// ── Cron expressions in plain language ───────────────────────────────────────
+
+const pad2 = (n) => String(n).padStart(2, '0');
+
+/**
+ * A short reading of a five-field cron expression, for the schedules this
+ * platform actually uses (minute steps, hourly, every N hours, daily). Anything
+ * else is returned as `cron <expr> (UTC)` so the page never claims more than
+ * the expression says.
+ */
+export function describeCron(expr) {
+ const f = String(expr || '').trim().split(/\s+/);
+ if (f.length !== 5) return `cron ${expr} (UTC)`;
+ const [min, hour, dom, mon, dow] = f;
+ if (dom !== '*' || mon !== '*' || dow !== '*') return `cron ${expr} (UTC)`;
+ const step = /^(?:\*|\d+(?:-\d+)?)\/(\d+)$/.exec(min);
+ if (step && hour === '*') return `every ${step[1]} minutes`;
+ if (/^\d+$/.test(min) && hour === '*') return Number(min) === 0 ? 'every hour, on the hour' : `every hour at :${pad2(min)}`;
+ const hstep = /^\*\/(\d+)$/.exec(hour);
+ if (/^\d+$/.test(min) && hstep) return `every ${hstep[1]} hours at :${pad2(min)}`;
+ if (/^\d+$/.test(min) && /^\d+$/.test(hour)) return `daily at ${pad2(hour)}:${pad2(min)} UTC`;
+ if (/^\d+(?:,\d+)+$/.test(min) && hour === '*') return `twice an hour, at ${min.split(',').map((m) => `:${pad2(m)}`).join(' and ')}`;
+ return `cron ${expr} (UTC)`;
+}
+
+/**
+ * Pick the crons that drive creator-fee money out of a parsed vercel.json and
+ * describe them. `crons` is the file's `crons` array.
+ */
+export function payoutSchedule(crons) {
+ const stages = [
+ { key: 'snapshot', path: '/api/cron/creator-earnings-snapshot', label: 'Earnings refresh', does: 'Reads what each coin has earned from pump.fun and the on-chain vault.' },
+ { key: 'claim', path: '/api/cron/launcher-claimer', label: 'Fee collection', does: 'Claims accrued creator fees from the vault into the agent wallet once they pass the claim threshold.' },
+ { key: 'distribute', path: '/api/cron/creator-payout-distribute', label: 'Distribution', does: 'Sends your share of each claim to your payout wallet, or records why it is held.' },
+ { key: 'reconcile', path: '/api/cron/creator-payout-reconcile', label: 'Reconciliation', does: 'Checks on-chain vault balances and sent transfers against our records and alerts on drift.' },
+ ];
+ const list = Array.isArray(crons) ? crons : [];
+ return stages.map((s) => {
+ const c = list.find((x) => x.path === s.path);
+ return { ...s, schedule: c?.schedule || null, cadence: c ? describeCron(c.schedule) : 'not scheduled' };
+ });
+}
+
+// ── CSV ──────────────────────────────────────────────────────────────────────
+
+export const DISTRIBUTION_CSV_COLUMNS = Object.freeze([
+ 'date', 'agent_id', 'mint', 'status', 'hold_reason', 'creator_share_sol', 'payout_wallet', 'claim_signature', 'payout_signature',
+]);
+
+const csvCell = (v) => {
+ let s = v == null ? '' : String(v);
+ // A cell that starts with a formula character would execute in a spreadsheet.
+ if (/^[=+\-@\t\r]/.test(s)) s = `'${s}`;
+ return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
+};
+
+export function solFromLamports(lamports) {
+ const v = BigInt(lamports || 0);
+ const whole = v / BigInt(LAMPORTS_PER_SOL);
+ const frac = (v % BigInt(LAMPORTS_PER_SOL)).toString().padStart(9, '0').replace(/0+$/, '');
+ return `${whole}${frac ? `.${frac}` : ''}`;
+}
+
+export function distributionsToCsv(rows) {
+ const lines = [DISTRIBUTION_CSV_COLUMNS.join(',')];
+ for (const r of rows) {
+ lines.push(
+ [
+ new Date(r.created_at).toISOString(),
+ r.agent_id,
+ r.mint,
+ r.status,
+ r.hold_reason || '',
+ solFromLamports(r.creator_lamports),
+ r.payout_wallet || '',
+ r.claim_sig || '',
+ r.tx_signature || '',
+ ]
+ .map(csvCell)
+ .join(','),
+ );
+ }
+ return `${lines.join('\n')}\n`;
+}
+
+/** Summarise distribution rows into the five totals plus per-reason held amounts. */
+export function summarizeDistributions(rows) {
+ const out = { sent: 0n, pending: 0n, held: 0n, held_by_reason: {} };
+ for (const r of rows) {
+ const v = BigInt(r.creator_lamports || 0);
+ if (r.status === 'sent') out.sent += v;
+ else if (r.status === 'held') {
+ out.held += v;
+ const k = r.hold_reason || 'unknown';
+ out.held_by_reason[k] = (out.held_by_reason[k] || 0n) + v;
+ } else out.pending += v;
+ }
+ return out;
+}
diff --git a/api/_lib/revenue-ledger-core.js b/api/_lib/revenue-ledger-core.js
new file mode 100644
index 000000000..06887db19
--- /dev/null
+++ b/api/_lib/revenue-ledger-core.js
@@ -0,0 +1,506 @@
+// Pure logic for the revenue ledger and reinvest rules: source mapping, USD
+// valuation, period bucketing, totals, CSV, the trailing-window projection and
+// the reinvest split planner. No I/O lives here so every rule is unit-testable
+// (tests/revenue-ledger.test.js); api/_lib/revenue-ledger.js does the database
+// and chain work around it.
+
+import { createHash } from 'node:crypto';
+
+export const USDC_MINTS = Object.freeze({
+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',
+});
+export const SOL_DECIMALS = 9;
+export const USDC_DECIMALS = 6;
+
+/** The six income sources, in the fixed order charts assign colour slots. */
+export const SOURCES = Object.freeze([
+ { key: 'creator_fee_claim', kind: 'revenue', label: 'Creator fees', how: 'Pump.fun creator fees the agent claimed to its wallet. Counted when claimed (the claim is the transaction), valued in USD at the SOL price when the ledger first saw the claim.' },
+ { key: 'skill_sale', kind: 'revenue', label: 'Skill and API sales', how: 'x402 skill and agent-API sales, net of the platform fee, from agent_revenue_events. Valued in USD from the settled asset.' },
+ { key: 'hire', kind: 'revenue', label: 'Hires', how: 'Completed agent-to-agent hires paid to this agent, at the USD amount recorded when the hire settled.' },
+ { key: 'skill_royalty', kind: 'revenue', label: 'Skill royalties', how: 'The author share of marketplace skill calls (royalty_ledger, settled rows), at the USD amount recorded at settlement. Credited to the owner, not a specific agent.' },
+ { key: 'invoice', kind: 'revenue', label: 'Invoices', how: 'Agent invoices that reached paid, at the USD value fixed when the invoice was paid.' },
+ { key: 'trading_pnl', kind: 'pnl', label: 'Trading PnL (realised)', how: 'Realised profit or loss of closed sniper positions, in SOL at the exit, valued at the SOL price when the ledger first saw the close. Reported separately: it is not revenue and can be negative.' },
+]);
+export const SOURCE_KEYS = Object.freeze(SOURCES.map((s) => s.key));
+export const SOURCE_BY_KEY = Object.freeze(Object.fromEntries(SOURCES.map((s) => [s.key, s])));
+
+const PERIODS = new Set(['day', 'week', 'month']);
+
+/** Decimal string for an atomic amount, without float drift. */
+export function formatAtomics(atomics, decimals) {
+ const neg = BigInt(atomics) < 0n;
+ const abs = neg ? -BigInt(atomics) : BigInt(atomics);
+ const base = 10n ** BigInt(decimals);
+ const whole = abs / base;
+ const frac = (abs % base).toString().padStart(decimals, '0').replace(/0+$/, '');
+ return `${neg ? '-' : ''}${whole}${frac ? `.${frac}` : ''}`;
+}
+
+/** Convert a JS number of USD to 6-decimal atomics of USDC. */
+export function usdToUsdcAtomics(usd) {
+ return BigInt(Math.round(Number(usd) * 1e6));
+}
+
+function toIso(v) {
+ const d = v instanceof Date ? v : new Date(v);
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
+}
+
+function networkFromCaip(network) {
+ const n = String(network || '').toLowerCase();
+ if (n.startsWith('eip155') || n === 'base' || n === 'base-sepolia') return { chain: 'base', network: 'mainnet' };
+ if (n.includes('devnet') || n.includes('etwtrabzayq6imfeykouru166vu2xqa1')) return { chain: 'solana', network: 'devnet' };
+ return { chain: 'solana', network: 'mainnet' };
+}
+
+function base(row, o) {
+ return {
+ user_id: o.user_id,
+ agent_id: o.agent_id ?? null,
+ source: o.source,
+ kind: SOURCE_BY_KEY[o.source].kind,
+ source_ref: String(o.source_ref),
+ occurred_at: toIso(o.occurred_at),
+ asset: o.asset,
+ amount_atomics: String(o.amount_atomics),
+ decimals: o.decimals,
+ usd: o.usd ?? null,
+ usd_basis: o.usd_basis ?? 'unvalued',
+ usd_price: o.usd_price ?? null,
+ tx_signature: o.tx_signature || null,
+ chain: o.chain || 'solana',
+ network: o.network || 'mainnet',
+ counterparty: o.counterparty || null,
+ label: o.label || null,
+ counted: o.counted !== false,
+ exclusion_reason: o.exclusion_reason || null,
+ meta: o.meta || {},
+ };
+}
+
+/** launcher_claims row (joined to its agent owner) to a ledger entry. */
+export function mapCreatorClaim(r) {
+ const lamports = BigInt(r.claimed_lamports ?? 0);
+ if (!r.user_id || !r.agent_id || lamports <= 0n || !r.claim_sig) return null;
+ return base(r, {
+ user_id: r.user_id,
+ agent_id: r.agent_id,
+ source: 'creator_fee_claim',
+ source_ref: r.id,
+ occurred_at: r.created_at,
+ asset: 'SOL',
+ amount_atomics: lamports,
+ decimals: SOL_DECIMALS,
+ tx_signature: r.claim_sig,
+ network: r.network === 'devnet' ? 'devnet' : 'mainnet',
+ label: 'Creator fee claim',
+ counterparty: r.mint,
+ meta: { mint: r.mint, buyback_sol: r.buyback_sol ?? 0, buyback_sig: r.buyback_sig || null },
+ });
+}
+
+function mintAsset(mint) {
+ if (mint === USDC_MINTS.mainnet) return { asset: 'USDC', decimals: USDC_DECIMALS, network: 'mainnet' };
+ if (mint === USDC_MINTS.devnet) return { asset: 'USDC', decimals: USDC_DECIMALS, network: 'devnet' };
+ return null;
+}
+
+/** agent_revenue_events row (joined to its agent) to a ledger entry. */
+export function mapRevenueEvent(r, { threeMint = null, threeDecimals = 6 } = {}) {
+ const net = BigInt(r.net_amount ?? 0);
+ const userId = r.owner_user_id || r.user_id;
+ if (!userId || net <= 0n) return null;
+ let spec = mintAsset(r.currency_mint);
+ if (!spec && threeMint && r.currency_mint === threeMint) spec = { asset: 'THREE', decimals: threeDecimals, network: 'mainnet' };
+ const intent = String(r.intent_id || '');
+ const m = /^x402:([1-9A-HJ-NP-Za-km-z]{60,100})$/.exec(intent);
+ const isBase = r.chain && r.chain !== 'solana';
+ return base(r, {
+ user_id: userId,
+ agent_id: r.agent_id,
+ source: 'skill_sale',
+ source_ref: r.id,
+ occurred_at: r.created_at,
+ asset: spec?.asset || 'UNKNOWN',
+ amount_atomics: net,
+ decimals: spec?.decimals ?? 0,
+ usd: spec?.asset === 'USDC' ? Number(formatAtomics(net, spec.decimals)) : null,
+ usd_basis: spec?.asset === 'USDC' ? 'exact' : 'unvalued',
+ usd_price: spec?.asset === 'USDC' ? 1 : null,
+ tx_signature: isBase ? null : m ? m[1] : null,
+ chain: isBase ? 'base' : 'solana',
+ network: spec?.network || 'mainnet',
+ counterparty: r.payer_address,
+ label: r.skill || 'Skill sale',
+ counted: !isBase,
+ exclusion_reason: isBase ? 'evm_not_included' : null,
+ meta: { gross_amount: String(r.gross_amount ?? ''), fee_amount: String(r.fee_amount ?? ''), settled_to_wallet: r.settled_to_wallet ?? null, currency_mint: r.currency_mint },
+ });
+}
+
+/** Completed agent_hires row to a ledger entry for the provider. */
+export function mapHire(r) {
+ if (r.status !== 'completed' || !r.provider_agent_id || !r.provider_user_id) return null;
+ const atomics = BigInt(r.amount_atomics ?? 0);
+ if (atomics <= 0n) return null;
+ const usd = r.usd != null ? Number(r.usd) : null;
+ return base(r, {
+ user_id: r.provider_user_id,
+ agent_id: r.provider_agent_id,
+ source: 'hire',
+ source_ref: r.id,
+ occurred_at: r.completed_at || r.created_at,
+ asset: String(r.currency || 'USDC').toUpperCase(),
+ amount_atomics: atomics,
+ decimals: USDC_DECIMALS,
+ usd,
+ usd_basis: usd != null ? 'recorded' : 'unvalued',
+ tx_signature: r.payment_signature,
+ counterparty: r.payer_address,
+ label: r.skill_name || 'Hire',
+ meta: { service_slug: r.service_slug || null, invocation_signature: r.invocation_signature || null },
+ });
+}
+
+/** Settled royalty_ledger row to a ledger entry for the author. */
+export function mapRoyalty(r) {
+ if (r.status !== 'settled' || !r.author_user_id) return null;
+ const usd = Number(r.price_usd);
+ if (!Number.isFinite(usd) || usd <= 0) return null;
+ const { chain, network } = networkFromCaip(r.network);
+ return base(r, {
+ user_id: r.author_user_id,
+ agent_id: r.agent_id,
+ source: 'skill_royalty',
+ source_ref: r.id,
+ occurred_at: r.settled_at || r.created_at,
+ asset: 'USDC',
+ amount_atomics: usdToUsdcAtomics(usd),
+ decimals: USDC_DECIMALS,
+ usd,
+ usd_basis: 'recorded',
+ tx_signature: chain === 'solana' ? r.tx_hash : null,
+ chain,
+ network,
+ counterparty: r.payer,
+ label: 'Skill royalty',
+ counted: chain === 'solana',
+ exclusion_reason: chain === 'solana' ? null : 'evm_not_included',
+ meta: { skill_id: r.skill_id, source: r.source, platform_fee_usd: r.platform_fee_usd ?? null, tx_hash: r.tx_hash || null },
+ });
+}
+
+/** Paid agent_commerce_invoices row (with its first counted payment) to an entry. */
+export function mapInvoice(r) {
+ if (r.status !== 'paid' || !r.user_id) return null;
+ const atomics = BigInt(r.paid_atomics ?? 0);
+ if (atomics <= 0n) return null;
+ const usd = r.paid_usd != null ? Number(r.paid_usd) : null;
+ return base(r, {
+ user_id: r.user_id,
+ agent_id: r.agent_id,
+ source: 'invoice',
+ source_ref: r.id,
+ occurred_at: r.paid_at || r.updated_at,
+ asset: r.asset,
+ amount_atomics: atomics,
+ decimals: r.decimals,
+ usd,
+ usd_basis: usd != null ? 'recorded' : 'unvalued',
+ tx_signature: r.payment_signature || null,
+ network: r.network === 'devnet' ? 'devnet' : 'mainnet',
+ counterparty: r.paid_by || r.payer_address,
+ label: `Invoice ${r.number}`,
+ meta: { number: r.number, paid_late: Boolean(r.paid_late) },
+ });
+}
+
+/** Closed agent_sniper_positions row to a realised-PnL entry. */
+export function mapTradePnl(r) {
+ if (r.status !== 'closed' || r.realized_pnl_lamports == null || !r.user_id) return null;
+ const lamports = BigInt(String(r.realized_pnl_lamports).split('.')[0]);
+ if (lamports === 0n) return null;
+ // A simulated fill never touched the chain; its signature is synthetic.
+ const simulated = r.exec_route === 'simulated' || r.sell_sig === 'SIMULATED';
+ return base(r, {
+ user_id: r.user_id,
+ agent_id: r.agent_id,
+ source: 'trading_pnl',
+ source_ref: r.id,
+ occurred_at: r.closed_at || r.opened_at,
+ asset: 'SOL',
+ amount_atomics: lamports,
+ decimals: SOL_DECIMALS,
+ tx_signature: r.sell_sig,
+ network: r.network === 'devnet' ? 'devnet' : 'mainnet',
+ label: r.symbol ? `${r.symbol} position` : 'Closed position',
+ counterparty: r.mint,
+ counted: !simulated,
+ exclusion_reason: simulated ? 'simulated_fill' : null,
+ meta: { mint: r.mint, exec_route: r.exec_route || null, exit_reason: r.exit_reason || null, pnl_pct: r.realized_pnl_pct ?? null },
+ });
+}
+
+/**
+ * Value an entry in USD. Entries that already carry a recorded or exact USD keep
+ * it. SOL and $THREE entries take the sync-time price; with no price they stay
+ * unvalued and are listed as such, never guessed.
+ */
+export function valueEntry(entry, prices = {}) {
+ if (entry.usd != null) return entry;
+ const price = prices[entry.asset];
+ if (!(price > 0)) return entry;
+ const units = Number(formatAtomics(entry.amount_atomics, entry.decimals));
+ return { ...entry, usd: Math.round(units * price * 1e6) / 1e6, usd_basis: 'sync_price', usd_price: price };
+}
+
+/** Whether an entry belongs in totals: mainnet Solana, flagged counted. */
+export function inTotals(e) {
+ return e.counted !== false && e.chain === 'solana' && e.network === 'mainnet';
+}
+
+/** Start (UTC) of the day, ISO week (Monday) or month holding `date`. */
+export function bucketStart(date, period) {
+ if (!PERIODS.has(period)) throw new Error(`period must be one of ${[...PERIODS].join(', ')}`);
+ const d = new Date(date);
+ const day = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
+ if (period === 'day') return day;
+ if (period === 'week') {
+ const dow = (day.getUTCDay() + 6) % 7;
+ return new Date(day.getTime() - dow * 86400000);
+ }
+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1));
+}
+
+function nextBucket(d, period) {
+ if (period === 'day') return new Date(d.getTime() + 86400000);
+ if (period === 'week') return new Date(d.getTime() + 7 * 86400000);
+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1));
+}
+
+/**
+ * Totals by source and a gap-free series by period. Only entries in totals are
+ * summed; unvalued ones are counted and reported so the page can say so.
+ * `revenue_usd` excludes trading PnL, which is reported on its own line.
+ */
+export function summarize(entries, { period = 'month', from = null, to = null } = {}) {
+ const fromMs = from ? new Date(from).getTime() : -Infinity;
+ const toMs = to ? new Date(to).getTime() : Infinity;
+ const bySource = Object.fromEntries(SOURCE_KEYS.map((k) => [k, { usd: 0, count: 0, unvalued: 0 }]));
+ const buckets = new Map();
+ let unvaluedCount = 0;
+ let excludedCount = 0;
+ for (const e of entries) {
+ const t = new Date(e.occurred_at).getTime();
+ if (t < fromMs || t >= toMs) continue;
+ if (!inTotals(e)) {
+ excludedCount++;
+ continue;
+ }
+ const s = bySource[e.source];
+ if (!s) continue;
+ s.count++;
+ if (e.usd == null) {
+ s.unvalued++;
+ unvaluedCount++;
+ continue;
+ }
+ const usd = Number(e.usd);
+ s.usd += usd;
+ const key = bucketStart(t, period).toISOString();
+ const b = buckets.get(key) || Object.fromEntries(SOURCE_KEYS.map((k) => [k, 0]));
+ b[e.source] += usd;
+ buckets.set(key, b);
+ }
+ for (const s of Object.values(bySource)) s.usd = Math.round(s.usd * 1e6) / 1e6;
+ const revenueUsd = SOURCES.filter((s) => s.kind === 'revenue').reduce((a, s) => a + bySource[s.key].usd, 0);
+ const pnlUsd = bySource.trading_pnl.usd;
+
+ const series = [];
+ if (buckets.size) {
+ const keys = [...buckets.keys()].sort();
+ let cur = new Date(keys[0]);
+ const last = new Date(keys[keys.length - 1]);
+ while (cur <= last) {
+ const b = buckets.get(cur.toISOString()) || Object.fromEntries(SOURCE_KEYS.map((k) => [k, 0]));
+ series.push({ start: cur.toISOString(), ...Object.fromEntries(SOURCE_KEYS.map((k) => [k, Math.round(b[k] * 1e6) / 1e6])) });
+ cur = nextBucket(cur, period);
+ }
+ }
+ return {
+ period,
+ by_source: bySource,
+ revenue_usd: Math.round(revenueUsd * 1e6) / 1e6,
+ trading_pnl_usd: pnlUsd,
+ net_usd: Math.round((revenueUsd + pnlUsd) * 1e6) / 1e6,
+ unvalued_count: unvaluedCount,
+ excluded_count: excludedCount,
+ series,
+ };
+}
+
+const csvCell = (v) => {
+ if (v == null) return '';
+ let s = String(v);
+ // Spreadsheet formula injection: a cell that starts with = + - @ is quoted as text.
+ if (/^[=+\-@\t\r]/.test(s) && !/^-?\d+(\.\d+)?$/.test(s)) s = `'${s}`;
+ return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
+};
+
+export const CSV_COLUMNS = Object.freeze([
+ 'occurred_at', 'source', 'kind', 'agent_id', 'asset', 'amount', 'usd', 'usd_basis', 'usd_price',
+ 'tx_signature', 'chain', 'network', 'counterparty', 'label', 'counted', 'exclusion_reason', 'chain_status', 'source_ref',
+]);
+
+export function toCsv(entries) {
+ const lines = [CSV_COLUMNS.join(',')];
+ for (const e of entries) {
+ const row = { ...e, amount: formatAtomics(e.amount_atomics, e.decimals) };
+ lines.push(CSV_COLUMNS.map((c) => csvCell(row[c])).join(','));
+ }
+ return `${lines.join('\n')}\n`;
+}
+
+/**
+ * Forward projection from trailing real history only. The run rate is revenue
+ * in the last `windowDays` divided by the days covered, carried flat. No growth
+ * term is ever added. With under `minDays` of history or `minEntries` entries it
+ * refuses rather than extrapolating from noise.
+ */
+export function project(entries, { now = Date.now(), windowDays = 30, horizonDays = 30, minDays = 7, minEntries = 3 } = {}) {
+ const rev = entries.filter((e) => inTotals(e) && e.kind === 'revenue' && e.usd != null);
+ const firstMs = rev.length ? Math.min(...rev.map((e) => new Date(e.occurred_at).getTime())) : null;
+ const historyDays = firstMs == null ? 0 : (now - firstMs) / 86400000;
+ const window_start = new Date(now - windowDays * 86400000).toISOString();
+ const inWin = rev.filter((e) => new Date(e.occurred_at).getTime() >= now - windowDays * 86400000);
+ const base = { window_days: windowDays, window_start, window_end: new Date(now).toISOString(), horizon_days: horizonDays, entries_in_window: inWin.length, history_days: Math.round(historyDays * 10) / 10 };
+ if (historyDays < minDays || inWin.length < minEntries) {
+ return { ...base, available: false, reason: `Needs at least ${minDays} days of history and ${minEntries} income entries in the trailing ${windowDays} days (has ${Math.floor(historyDays)} days, ${inWin.length} entries).` };
+ }
+ const covered = Math.min(windowDays, historyDays);
+ const total = inWin.reduce((a, e) => a + Number(e.usd), 0);
+ const perDay = total / covered;
+ return {
+ ...base,
+ available: true,
+ trailing_revenue_usd: Math.round(total * 100) / 100,
+ days_covered: Math.round(covered * 10) / 10,
+ per_day_usd: Math.round(perDay * 100) / 100,
+ projected_usd: Math.round(perDay * horizonDays * 100) / 100,
+ method: `Trailing ${Math.round(covered)}-day revenue divided by days covered, held flat for ${horizonDays} days. No growth assumed.`,
+ };
+}
+
+// ── reinvest rules ──────────────────────────────────────────────────────────
+
+export const LEG_KINDS = Object.freeze(['model_credits', 'dca_own_coin', 'tools_budget']);
+export const LEG_LABELS = Object.freeze({ model_credits: 'Model credits', dca_own_coin: "DCA into the agent's own coin", tools_budget: 'Tools budget' });
+export const RULE_PERIODS = Object.freeze(['daily', 'weekly', 'monthly']);
+
+export class RuleError extends Error {
+ constructor(message) {
+ super(message);
+ this.code = 'invalid_rule';
+ this.status = 400;
+ }
+}
+
+/** Validate and normalise a rule body. Throws RuleError with a fixable message. */
+export function normalizeRule(input) {
+ const legsIn = Array.isArray(input?.legs) ? input.legs : [];
+ if (!legsIn.length) throw new RuleError('Add at least one leg (model credits, own-coin DCA or tools budget).');
+ const seen = new Set();
+ let total = 0;
+ const legs = legsIn.map((l) => {
+ const kind = String(l?.kind || '');
+ if (!LEG_KINDS.includes(kind)) throw new RuleError(`Unknown leg "${kind}". Use ${LEG_KINDS.join(', ')}.`);
+ if (seen.has(kind)) throw new RuleError(`${LEG_LABELS[kind]} appears twice. Combine them into one leg.`);
+ seen.add(kind);
+ const pct = Number(l.pct);
+ if (!Number.isFinite(pct) || pct <= 0 || pct > 100) throw new RuleError(`${LEG_LABELS[kind]} needs a percent between 0 and 100.`);
+ total += pct;
+ const out = { kind, pct: Math.round(pct * 100) / 100 };
+ if (kind === 'tools_budget') {
+ if (!/^[0-9a-f-]{36}$/i.test(String(l.session_id || ''))) throw new RuleError('The tools budget leg needs the payment session it tops up (session_id).');
+ out.session_id = String(l.session_id);
+ }
+ return out;
+ });
+ if (total > 100 + 1e-9) throw new RuleError(`The legs add up to ${total}%, over 100%.`);
+ const perRun = Number(input.per_run_cap_usd);
+ const lifetime = Number(input.lifetime_cap_usd);
+ if (!(perRun > 0)) throw new RuleError('Set a per-run cap in USD greater than 0.');
+ if (!(lifetime > 0)) throw new RuleError('Set a lifetime cap in USD greater than 0.');
+ if (lifetime < perRun) throw new RuleError('The lifetime cap cannot be below the per-run cap.');
+ const period = RULE_PERIODS.includes(input.period) ? input.period : 'weekly';
+ const basis = input.basis === 'revenue_and_trading_profit' ? 'revenue_and_trading_profit' : 'revenue';
+ const minRun = input.min_run_usd == null ? 1 : Number(input.min_run_usd);
+ if (!(minRun >= 0)) throw new RuleError('The minimum run size cannot be negative.');
+ const network = input.network === 'devnet' ? 'devnet' : 'mainnet';
+ return { name: String(input.name || 'Reinvest rule').trim().slice(0, 80) || 'Reinvest rule', network, period, basis, legs, per_run_cap_usd: perRun, lifetime_cap_usd: lifetime, min_run_usd: minRun };
+}
+
+/** Hash of everything the owner confirmed. Any edit changes it and clears the confirmation. */
+export function ruleHash(rule) {
+ const canon = {
+ agent_id: rule.agent_id,
+ network: rule.network,
+ period: rule.period,
+ basis: rule.basis,
+ per_run_cap_usd: Number(rule.per_run_cap_usd),
+ lifetime_cap_usd: Number(rule.lifetime_cap_usd),
+ min_run_usd: Number(rule.min_run_usd),
+ legs: [...rule.legs].sort((a, b) => a.kind.localeCompare(b.kind)).map((l) => ({ kind: l.kind, pct: Number(l.pct), session_id: l.session_id || null })),
+ };
+ return createHash('sha256').update(JSON.stringify(canon)).digest('hex');
+}
+
+/** The last complete [start, end) UTC period before `now`. */
+export function lastPeriod(period, now = Date.now()) {
+ const cur = bucketStart(now, period === 'daily' ? 'day' : period === 'weekly' ? 'week' : 'month');
+ const unit = period === 'daily' ? 'day' : period === 'weekly' ? 'week' : 'month';
+ let start;
+ if (unit === 'day') start = new Date(cur.getTime() - 86400000);
+ else if (unit === 'week') start = new Date(cur.getTime() - 7 * 86400000);
+ else start = new Date(Date.UTC(cur.getUTCFullYear(), cur.getUTCMonth() - 1, 1));
+ return { start, end: cur };
+}
+
+export const runKey = (ruleId, periodStart) => `revenue_reinvest:${ruleId}:${new Date(periodStart).toISOString()}`;
+export const legKey = (ruleId, periodStart, kind) => `${runKey(ruleId, periodStart)}:${kind}`;
+
+/**
+ * Plan one run. Base is the period's income; each leg takes its percent. When
+ * the legs together exceed the per-run cap or the lifetime headroom, every leg
+ * is scaled down by the same factor, so the owner's split ratios survive the cap.
+ * Below the minimum run size nothing executes.
+ */
+export function planRun({ baseUsd, legs, perRunCapUsd, lifetimeCapUsd, lifetimeSpentUsd = 0, minRunUsd = 0 }) {
+ const base = Math.max(0, Number(baseUsd) || 0);
+ const headroom = Math.max(0, Number(lifetimeCapUsd) - Number(lifetimeSpentUsd));
+ const wanted = legs.map((l) => ({ ...l, planned_usd: Math.round(base * (l.pct / 100) * 1e6) / 1e6 }));
+ const wantedTotal = wanted.reduce((a, l) => a + l.planned_usd, 0);
+ const ceiling = Math.min(Number(perRunCapUsd), headroom);
+ const factor = wantedTotal > ceiling && wantedTotal > 0 ? ceiling / wantedTotal : 1;
+ const planned = wanted.map((l) => ({ ...l, capped_usd: Math.floor(l.planned_usd * factor * 1e6) / 1e6 }));
+ const total = planned.reduce((a, l) => a + l.capped_usd, 0);
+ let skip = null;
+ if (base <= 0) skip = 'No income in this period.';
+ else if (headroom <= 0) skip = 'The lifetime cap has been reached.';
+ else if (total < Number(minRunUsd)) skip = `The split comes to $${total.toFixed(2)}, under the $${Number(minRunUsd).toFixed(2)} minimum run size.`;
+ return {
+ legs: planned.map((l) => ({ ...l, capped_usd: skip ? 0 : l.capped_usd })),
+ planned_usd: Math.round(wantedTotal * 1e6) / 1e6,
+ executable_usd: skip ? 0 : Math.round(total * 1e6) / 1e6,
+ kept_usd: Math.round((base - (skip ? 0 : total)) * 1e6) / 1e6,
+ scaled: factor < 1,
+ skip,
+ };
+}
+
+/** Milestones announced once per scope. */
+export const MILESTONES_USD = Object.freeze([1, 10, 100, 1000, 10000, 100000]);
+export function reachedMilestones(totalUsd) {
+ return MILESTONES_USD.filter((m) => totalUsd >= m);
+}
diff --git a/api/_lib/revenue-ledger.js b/api/_lib/revenue-ledger.js
new file mode 100644
index 000000000..7d66c1370
--- /dev/null
+++ b/api/_lib/revenue-ledger.js
@@ -0,0 +1,228 @@
+// The revenue ledger: one row per income event across every way an agent earns,
+// each linked to its transaction. The source tables stay the system of record;
+// this module copies their rows in idempotently (unique on source + source_ref),
+// values them in USD once, and serves the queries, totals and exports the
+// /earnings pages use. Pure rules live in revenue-ledger-core.js.
+
+import { sql } from './db.js';
+import {
+ SOURCES, SOURCE_KEYS, mapCreatorClaim, mapRevenueEvent, mapHire, mapRoyalty, mapInvoice, mapTradePnl,
+ valueEntry, summarize, project, toCsv, inTotals, formatAtomics,
+} from './revenue-ledger-core.js';
+import { cachedSolUsd } from './trader-stats.js';
+import { usdPrice } from './agent-commerce/assets.js';
+import { TOKEN_MINT, TOKEN_DECIMALS } from './token/config.js';
+
+const CHUNK = 200;
+
+async function loadPrices() {
+ const [sol, three] = await Promise.all([cachedSolUsd().catch(() => null), usdPrice('THREE').catch(() => null)]);
+ return { SOL: sol > 0 ? sol : null, THREE: three > 0 ? three : null };
+}
+
+/** Read every source row in scope, mapped to ledger entries (unvalued where a price is needed). */
+async function collect({ userId = null, agentId = null, since = null }) {
+ const u = userId;
+ const a = agentId;
+ const s = since;
+ const [claims, events, hires, royalties, invoices, trades] = await Promise.all([
+ sql`
+ select c.id, c.agent_id, ai.user_id, c.mint, c.claimed_lamports, c.buyback_sol, c.buyback_sig, c.claim_sig, c.network, c.created_at
+ from launcher_claims c join agent_identities ai on ai.id = c.agent_id
+ where c.claim_sig is not null and c.claimed_lamports > 0
+ and (${u}::uuid is null or ai.user_id = ${u}) and (${a}::uuid is null or c.agent_id = ${a})
+ and (${s}::timestamptz is null or c.created_at >= ${s})`,
+ sql`
+ select r.id, r.agent_id, coalesce(r.owner_user_id, ai.user_id) as owner_user_id, r.intent_id, r.skill,
+ r.gross_amount, r.fee_amount, r.net_amount, r.currency_mint, r.chain, r.payer_address, r.settled_to_wallet, r.created_at
+ from agent_revenue_events r join agent_identities ai on ai.id = r.agent_id
+ where r.net_amount > 0
+ and (${u}::uuid is null or coalesce(r.owner_user_id, ai.user_id) = ${u}) and (${a}::uuid is null or r.agent_id = ${a})
+ and (${s}::timestamptz is null or r.created_at >= ${s})`,
+ sql`
+ select id, provider_agent_id, provider_user_id, service_slug, skill_name, amount_atomics, usd, currency, status,
+ payment_signature, invocation_signature, payer_address, created_at, completed_at
+ from agent_hires
+ where status = 'completed' and provider_agent_id is not null and provider_user_id is not null
+ and (${u}::uuid is null or provider_user_id = ${u}) and (${a}::uuid is null or provider_agent_id = ${a})
+ and (${s}::timestamptz is null or coalesce(completed_at, created_at) >= ${s})`,
+ a
+ ? Promise.resolve([])
+ : sql`
+ select id, skill_id, agent_id, author_user_id, price_usd, status, settled_at, tx_hash, network, payer, source, platform_fee_usd, created_at
+ from royalty_ledger
+ where status = 'settled' and author_user_id is not null
+ and (${u}::uuid is null or author_user_id = ${u})
+ and (${s}::timestamptz is null or coalesce(settled_at, created_at) >= ${s})`,
+ sql`
+ select i.id, i.number, i.user_id, i.agent_id, i.asset, i.decimals, i.paid_atomics, i.paid_usd, i.paid_at, i.updated_at,
+ i.paid_by, i.payer_address, i.paid_late, i.network, i.status,
+ (select p.signature from agent_commerce_invoice_payments p where p.invoice_id = i.id and p.counted order by p.created_at limit 1) as payment_signature
+ from agent_commerce_invoices i
+ where i.status = 'paid'
+ and (${u}::uuid is null or i.user_id = ${u}) and (${a}::uuid is null or i.agent_id = ${a})
+ and (${s}::timestamptz is null or coalesce(i.paid_at, i.updated_at) >= ${s})`,
+ sql`
+ select id, agent_id, user_id, network, mint, symbol, status, exit_reason, sell_sig, realized_pnl_lamports, realized_pnl_pct, exec_route, opened_at, closed_at
+ from agent_sniper_positions
+ where status = 'closed' and realized_pnl_lamports is not null
+ and (${u}::uuid is null or user_id = ${u}) and (${a}::uuid is null or agent_id = ${a})
+ and (${s}::timestamptz is null or closed_at >= ${s})`,
+ ]);
+ const three = { threeMint: TOKEN_MINT, threeDecimals: TOKEN_DECIMALS };
+ return [
+ ...claims.map(mapCreatorClaim),
+ ...events.map((r) => mapRevenueEvent(r, three)),
+ ...hires.map(mapHire),
+ ...royalties.map(mapRoyalty),
+ ...invoices.map(mapInvoice),
+ ...trades.map(mapTradePnl),
+ ].filter(Boolean);
+}
+
+/**
+ * Copy new income rows into the ledger and value any still-unvalued ones.
+ * Idempotent: a row already present keeps its recorded USD, and only a missing
+ * valuation or signature is filled in. Returns counts for the cron log.
+ * @param {{ userId?: string|null, agentId?: string|null, since?: string|null }} scope
+ */
+export async function syncLedger(scope = {}) {
+ const prices = await loadPrices();
+ const entries = (await collect(scope)).map((e) => valueEntry(e, prices));
+ let written = 0;
+ for (let i = 0; i < entries.length; i += CHUNK) {
+ const chunk = entries.slice(i, i + CHUNK);
+ const rows = await sql`
+ insert into revenue_ledger_entries
+ (user_id, agent_id, source, kind, source_ref, occurred_at, asset, amount_atomics, decimals, usd, usd_basis, usd_price,
+ tx_signature, chain, network, counterparty, label, counted, exclusion_reason, meta)
+ select t.user_id, t.agent_id, t.source, t.kind, t.source_ref, t.occurred_at, t.asset, t.amount_atomics, t.decimals, t.usd, t.usd_basis, t.usd_price,
+ t.tx_signature, t.chain, t.network, t.counterparty, t.label, t.counted, t.exclusion_reason, t.meta
+ from jsonb_to_recordset(${JSON.stringify(chunk)}::jsonb) as t(
+ user_id uuid, agent_id uuid, source text, kind text, source_ref text, occurred_at timestamptz, asset text,
+ amount_atomics numeric, decimals int, usd numeric, usd_basis text, usd_price numeric, tx_signature text,
+ chain text, network text, counterparty text, label text, counted boolean, exclusion_reason text, meta jsonb)
+ on conflict (source, source_ref) do update set
+ usd = coalesce(revenue_ledger_entries.usd, excluded.usd),
+ usd_basis = case when revenue_ledger_entries.usd is null and excluded.usd is not null then excluded.usd_basis else revenue_ledger_entries.usd_basis end,
+ usd_price = coalesce(revenue_ledger_entries.usd_price, excluded.usd_price),
+ tx_signature = coalesce(revenue_ledger_entries.tx_signature, excluded.tx_signature),
+ counted = excluded.counted,
+ exclusion_reason = excluded.exclusion_reason,
+ synced_at = now()
+ returning (xmax = 0) as inserted`;
+ written += rows.filter((r) => r.inserted).length;
+ }
+ return { scanned: entries.length, inserted: written, prices };
+}
+
+const ENTRY_COLS = sql`id, user_id, agent_id, source, kind, source_ref, occurred_at, asset, amount_atomics, decimals, usd, usd_basis, usd_price,
+ tx_signature, chain, network, counterparty, label, counted, exclusion_reason, chain_status, chain_checked_at, chain_detail`;
+
+/** Ledger rows for an owner (all agents) or one agent, newest first. */
+export async function listEntries({ userId, agentId = null, source = null, from = null, to = null, limit = 500, before = null }) {
+ const rows = await sql`
+ select ${ENTRY_COLS} from revenue_ledger_entries
+ where user_id = ${userId}
+ and (${agentId}::uuid is null or agent_id = ${agentId})
+ and (${source}::text is null or source = ${source})
+ and (${from}::timestamptz is null or occurred_at >= ${from})
+ and (${to}::timestamptz is null or occurred_at < ${to})
+ and (${before}::timestamptz is null or occurred_at < ${before})
+ order by occurred_at desc, id
+ limit ${Math.min(Math.max(Number(limit) || 500, 1), 50000)}`;
+ return rows.map(shape);
+}
+
+function shape(r) {
+ return {
+ ...r,
+ amount_atomics: String(r.amount_atomics),
+ amount: formatAtomics(String(r.amount_atomics), r.decimals),
+ usd: r.usd == null ? null : Number(r.usd),
+ usd_price: r.usd_price == null ? null : Number(r.usd_price),
+ occurred_at: new Date(r.occurred_at).toISOString(),
+ explorer_url: r.tx_signature && r.chain === 'solana' ? `https://solscan.io/tx/${r.tx_signature}${r.network === 'devnet' ? '?cluster=devnet' : ''}` : null,
+ };
+}
+
+/** Summary, projection and the creator-fee memo for a scope. */
+export async function ledgerView({ userId, agentId = null, period = 'month', from = null, to = null, windowDays = 30 }) {
+ const entries = await listEntries({ userId, agentId, limit: 50000 });
+ const summary = summarize(entries, { period, from, to });
+ const projection = project(entries, { windowDays });
+ const unclaimed = await unclaimedCreatorFees({ userId, agentId }).catch(() => null);
+ const last = await sql`select max(synced_at) as at from revenue_ledger_entries where user_id = ${userId} and (${agentId}::uuid is null or agent_id = ${agentId})`;
+ const chain = { verified: 0, unchecked: 0, issues: 0 };
+ for (const e of entries) {
+ if (!inTotals(e) || !e.tx_signature) continue;
+ if (e.chain_status === 'verified') chain.verified++;
+ else if (e.chain_status === 'mismatch' || e.chain_status === 'not_found') chain.issues++;
+ else chain.unchecked++;
+ }
+ return {
+ summary, projection, unclaimed_creator_fees: unclaimed, chain_verification: chain,
+ entries_total: entries.length, synced_at: last[0]?.at ? new Date(last[0].at).toISOString() : null,
+ sources: SOURCES.map(({ key, label, kind, how }) => ({ key, label, kind, how })),
+ not_included: ['EVM and Base sales (shown in the entry list as excluded, never in totals)', 'Devnet activity (test traffic)', 'Unclaimed creator fees (a memo below, counted once claimed)'],
+ };
+}
+
+/** Creator fees earned but not yet claimed, from the earnings snapshot (a memo, not income yet). */
+async function unclaimedCreatorFees({ userId, agentId }) {
+ const [row] = await sql`
+ select coalesce(sum(e.unclaimed_lamports), 0)::numeric as lamports, max(e.refreshed_at) as refreshed_at
+ from agent_coin_earnings e join agent_identities ai on ai.id = e.agent_id
+ where ai.user_id = ${userId} and e.network = 'mainnet' and e.source = 'pumpfun_creator_fees'
+ and (${agentId}::uuid is null or e.agent_id = ${agentId})`;
+ const lamports = BigInt(String(row?.lamports ?? 0).split('.')[0]);
+ if (lamports <= 0n) return { sol: '0', usd: 0, refreshed_at: row?.refreshed_at ? new Date(row.refreshed_at).toISOString() : null };
+ const price = await cachedSolUsd().catch(() => null);
+ const sol = formatAtomics(lamports, 9);
+ return { sol, usd: price ? Math.round(Number(sol) * price * 100) / 100 : null, refreshed_at: row?.refreshed_at ? new Date(row.refreshed_at).toISOString() : null };
+}
+
+export async function exportCsv(args) {
+ return toCsv(await listEntries({ ...args, limit: 50000 }));
+}
+
+// ── public toggle ───────────────────────────────────────────────────────────
+
+export async function getSettings(agentId) {
+ const [r] = await sql`select agent_id, user_id, public_earnings, public_since from revenue_ledger_settings where agent_id = ${agentId}`;
+ return r ? { public_earnings: r.public_earnings, public_since: r.public_since } : { public_earnings: false, public_since: null };
+}
+
+export async function setPublic({ agentId, userId, isPublic }) {
+ const [r] = await sql`
+ insert into revenue_ledger_settings (agent_id, user_id, public_earnings, public_since, updated_at)
+ values (${agentId}, ${userId}, ${isPublic}, ${isPublic ? new Date().toISOString() : null}, now())
+ on conflict (agent_id) do update set
+ public_earnings = excluded.public_earnings,
+ public_since = case when excluded.public_earnings and not revenue_ledger_settings.public_earnings then now()
+ when excluded.public_earnings then revenue_ledger_settings.public_since else null end,
+ updated_at = now()
+ returning public_earnings, public_since`;
+ return r;
+}
+
+/**
+ * The public earnings page for an agent whose owner switched it on. Everything
+ * shown is a ledger row with its transaction; counterparty addresses are
+ * withheld and amounts are the same numbers the owner sees.
+ */
+export async function publicView({ agentId, period = 'month' }) {
+ const [agent] = await sql`select id, user_id, name from agent_identities where id = ${agentId} and deleted_at is null`;
+ if (!agent) return null;
+ const settings = await getSettings(agentId);
+ if (!settings.public_earnings) return null;
+ const view = await ledgerView({ userId: agent.user_id, agentId, period });
+ const entries = (await listEntries({ userId: agent.user_id, agentId, limit: 200 })).map((e) => ({
+ occurred_at: e.occurred_at, source: e.source, label: e.label, asset: e.asset, amount: e.amount, usd: e.usd, usd_basis: e.usd_basis,
+ tx_signature: e.tx_signature, explorer_url: e.explorer_url, chain: e.chain, network: e.network, counted: e.counted,
+ exclusion_reason: e.exclusion_reason, chain_status: e.chain_status,
+ }));
+ return { agent: { id: agent.id, name: agent.name }, public_since: settings.public_since, ...view, entries };
+}
+
+export { SOURCE_KEYS };
diff --git a/api/_lib/revenue-reconcile.js b/api/_lib/revenue-reconcile.js
new file mode 100644
index 000000000..0485bb91c
--- /dev/null
+++ b/api/_lib/revenue-reconcile.js
@@ -0,0 +1,172 @@
+// Scheduled reconciliation of the revenue ledger. Two independent checks:
+//
+// 1. Database drift. For each source, count and sum what the source table
+// says is eligible income and compare it with the ledger. A difference
+// means a row was missed, deleted or changed after the last sync. A sync
+// runs first, so drift left over after it is real.
+// 2. Chain verification. A sample of mainnet Solana entries (never-checked
+// first, then oldest check) is looked up on the cluster. A transaction that
+// is missing or failed on-chain is flagged; one that landed is stamped
+// verified with the time of the check.
+//
+// Drift alerts the affected owners once per distinct drift (not on every run).
+
+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';
+
+const CHAIN_SAMPLE = 120;
+const NOT_FOUND_GRACE_MS = 2 * 3600 * 1000;
+// The RPC pool is not an archive node: a signature older than this cannot be
+// judged missing, so it is skipped rather than reported as drift.
+const HISTORY_WINDOW_MS = Number(process.env.REVENUE_CHAIN_HISTORY_DAYS || 3) * 86400000;
+
+/** Per-source counts and sums straight from the source tables, against the ledger. */
+async function dbChecks() {
+ const src = await sql`
+ select 'creator_fee_claim' as source, count(*)::int as n, coalesce(sum(c.claimed_lamports), 0)::numeric as atomics
+ from launcher_claims c join agent_identities ai on ai.id = c.agent_id
+ where c.claim_sig is not null and c.claimed_lamports > 0
+ union all
+ select 'skill_sale', count(*)::int, coalesce(sum(r.net_amount), 0)::numeric
+ from agent_revenue_events r join agent_identities ai on ai.id = r.agent_id
+ where r.net_amount > 0 and coalesce(r.owner_user_id, ai.user_id) is not null
+ union all
+ select 'hire', count(*)::int, coalesce(sum(amount_atomics::numeric), 0)
+ from agent_hires where status = 'completed' and provider_agent_id is not null and provider_user_id is not null and amount_atomics::numeric > 0
+ union all
+ select 'skill_royalty', count(*)::int, coalesce(sum(round(price_usd * 1000000)), 0)::numeric
+ from royalty_ledger where status = 'settled' and author_user_id is not null and price_usd > 0
+ union all
+ select 'invoice', count(*)::int, coalesce(sum(paid_atomics), 0)
+ from agent_commerce_invoices where status = 'paid' and paid_atomics > 0
+ union all
+ select 'trading_pnl', count(*)::int, coalesce(sum(realized_pnl_lamports), 0)::numeric
+ from agent_sniper_positions where status = 'closed' and realized_pnl_lamports is not null and realized_pnl_lamports <> 0 and user_id is not null`;
+ const led = await sql`select source, count(*)::int as n, coalesce(sum(amount_atomics), 0)::numeric as atomics from revenue_ledger_entries group by source`;
+ const byLed = new Map(led.map((r) => [r.source, r]));
+ return src.map((s) => {
+ const l = byLed.get(s.source);
+ const ledgerN = l?.n ?? 0;
+ const ledgerAtomics = BigInt(String(l?.atomics ?? 0).split('.')[0]);
+ const sourceAtomics = BigInt(String(s.atomics).split('.')[0]);
+ return {
+ source: s.source, label: SOURCE_BY_KEY[s.source].label,
+ source_count: s.n, ledger_count: ledgerN,
+ source_atomics: sourceAtomics.toString(), ledger_atomics: ledgerAtomics.toString(),
+ drift: s.n !== ledgerN || sourceAtomics !== ledgerAtomics,
+ };
+ });
+}
+
+/** Look a sample of signatures up on mainnet and stamp each entry. */
+async function chainVerify() {
+ const rows = await sql`
+ select id, user_id, tx_signature, occurred_at from revenue_ledger_entries
+ where tx_signature is not null and chain = 'solana' and network = 'mainnet' and counted
+ and chain_status in ('unchecked', 'verified', 'mismatch', 'not_found')
+ order by chain_checked_at nulls first, occurred_at desc
+ limit ${CHAIN_SAMPLE}`;
+ if (!rows.length) return { checked: 0, mismatches: 0, not_found: 0, flagged: [] };
+ const conn = solanaConnection({ network: 'mainnet' });
+ const sigs = [...new Set(rows.map((r) => r.tx_signature))];
+ const status = new Map();
+ for (let i = 0; i < sigs.length; i += 100) {
+ const batch = sigs.slice(i, i + 100);
+ const res = await conn.getSignatureStatuses(batch, { searchTransactionHistory: true });
+ batch.forEach((sig, j) => status.set(sig, res.value[j]));
+ }
+ let mismatches = 0;
+ let notFound = 0;
+ const flagged = [];
+ for (const r of rows) {
+ const st = status.get(r.tx_signature);
+ let next;
+ let detail;
+ if (st?.err) {
+ next = 'mismatch';
+ detail = `Transaction failed on-chain: ${JSON.stringify(st.err).slice(0, 160)}`;
+ mismatches++;
+ } else if (st) {
+ next = 'verified';
+ detail = `Landed at slot ${st.slot} (${st.confirmationStatus || 'confirmed'}).`;
+ } else if (Date.now() - new Date(r.occurred_at).getTime() < NOT_FOUND_GRACE_MS) {
+ next = 'unchecked';
+ detail = 'Too recent to judge; will be checked again.';
+ } else if (Date.now() - new Date(r.occurred_at).getTime() > HISTORY_WINDOW_MS) {
+ next = 'skipped';
+ detail = `Older than the ${Math.round(HISTORY_WINDOW_MS / 86400000)}-day window the RPC pool can search, so it cannot be checked; the source row is the record.`;
+ } else {
+ next = 'not_found';
+ detail = 'No transaction with this signature was found on mainnet.';
+ notFound++;
+ }
+ if (next === 'mismatch' || next === 'not_found') flagged.push({ id: r.id, user_id: r.user_id, tx_signature: r.tx_signature, status: next });
+ await sql`update revenue_ledger_entries set chain_status = ${next}, chain_checked_at = now(), chain_detail = ${detail} where id = ${r.id}`;
+ }
+ return { checked: rows.length, mismatches, not_found: notFound, flagged };
+}
+
+/**
+ * One reconcile run. Records it in revenue_reconcile_runs and alerts owners
+ * whose entries are flagged, and every owner when a source drifted.
+ */
+export async function runReconcile() {
+ const [run] = await sql`insert into revenue_reconcile_runs default values returning id`;
+ try {
+ 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 [{ 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';
+
+ const [prev] = await sql`select db_drift_count, chain_mismatches, chain_not_found from revenue_reconcile_runs where id <> ${run.id} and status <> 'running' order by started_at desc limit 1`;
+ const changed = !prev || prev.db_drift_count !== dbDrift || prev.chain_mismatches !== chain.mismatches || prev.chain_not_found !== chain.not_found;
+ let alerted = 0;
+ if (status === 'drift' && changed) {
+ const owners = new Map();
+ for (const f of chain.flagged) owners.set(f.user_id, (owners.get(f.user_id) || 0) + 1);
+ for (const [userId, count] of owners) {
+ insertNotification(userId, 'revenue_reconcile_drift', {
+ title: 'Revenue ledger needs a look',
+ body: `${count} income ${count === 1 ? 'entry has' : 'entries have'} a transaction that is missing or failed on-chain.`,
+ link: '/earnings',
+ });
+ alerted++;
+ }
+ if (dbDrift) {
+ const affected = await sql`select distinct user_id from revenue_ledger_entries`;
+ for (const { user_id } of affected) {
+ if (owners.has(user_id)) continue;
+ insertNotification(user_id, 'revenue_reconcile_drift', {
+ title: 'Revenue ledger drifted from its sources',
+ body: `${dbDrift} income ${dbDrift === 1 ? 'source differs' : 'sources differ'} from the ledger. It re-syncs every cycle; open the earnings page for the detail.`,
+ link: '/earnings',
+ });
+ alerted++;
+ }
+ }
+ }
+ await sql`
+ update revenue_reconcile_runs set finished_at = now(), status = ${status}, entries_total = ${n},
+ db_checks = ${JSON.stringify(checks)}::jsonb, db_drift_count = ${dbDrift}, chain_checked = ${chain.checked},
+ 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 };
+ } 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;
+ }
+}
+
+/** Latest finished run, for the "how reconciliation is doing" line. */
+export async function latestReconcile() {
+ const [r] = await sql`
+ select id, started_at, finished_at, status, entries_total, db_checks, db_drift_count, chain_checked, chain_mismatches, chain_not_found
+ from revenue_reconcile_runs where status <> 'running' order by started_at desc limit 1`;
+ return r || null;
+}
diff --git a/tests/revenue-ledger.test.js b/tests/revenue-ledger.test.js
new file mode 100644
index 000000000..f67f2f354
--- /dev/null
+++ b/tests/revenue-ledger.test.js
@@ -0,0 +1,174 @@
+import { describe, it, expect } from 'vitest';
+import {
+ mapCreatorClaim, mapRevenueEvent, mapHire, mapRoyalty, mapInvoice, mapTradePnl, valueEntry, summarize,
+ toCsv, project, normalizeRule, ruleHash, planRun, lastPeriod, runKey, legKey, bucketStart, formatAtomics,
+ USDC_MINTS, reachedMilestones,
+} from '../api/_lib/revenue-ledger-core.js';
+
+const U = '11111111-1111-1111-1111-111111111111';
+const A = '22222222-2222-2222-2222-222222222222';
+const SIG = '5'.repeat(88);
+
+describe('source mapping', () => {
+ it('maps a creator fee claim in lamports with its signature', () => {
+ const e = mapCreatorClaim({ id: 'c1', user_id: U, agent_id: A, claimed_lamports: 2_500_000_000, claim_sig: SIG, created_at: '2026-10-01T00:00:00Z', network: 'mainnet', mint: 'M' });
+ expect(e).toMatchObject({ source: 'creator_fee_claim', asset: 'SOL', amount_atomics: '2500000000', tx_signature: SIG, usd: null });
+ expect(valueEntry(e, { SOL: 100 })).toMatchObject({ usd: 250, usd_basis: 'sync_price' });
+ });
+ it('skips claims with no signature or no owner', () => {
+ expect(mapCreatorClaim({ id: 'c', user_id: U, agent_id: A, claimed_lamports: 5, claim_sig: null })).toBeNull();
+ expect(mapCreatorClaim({ id: 'c', user_id: null, agent_id: A, claimed_lamports: 5, claim_sig: SIG })).toBeNull();
+ });
+ it('values USDC sales exactly and extracts the tx from the intent id', () => {
+ const e = mapRevenueEvent({ id: 'r1', owner_user_id: U, agent_id: A, net_amount: 1_500_000, currency_mint: USDC_MINTS.mainnet, chain: 'solana', intent_id: `x402:${SIG}`, created_at: '2026-10-02T00:00:00Z' });
+ expect(e).toMatchObject({ usd: 1.5, usd_basis: 'exact', tx_signature: SIG, counted: true });
+ });
+ it('does not invent a signature from a random-uuid intent id and flags base as excluded', () => {
+ const e = mapRevenueEvent({ id: 'r2', owner_user_id: U, agent_id: A, net_amount: 1_000_000, currency_mint: USDC_MINTS.mainnet, chain: 'base', intent_id: 'x402:eip155:8453:abc', created_at: '2026-10-02T00:00:00Z' });
+ expect(e).toMatchObject({ tx_signature: null, counted: false, exclusion_reason: 'evm_not_included', chain: 'base' });
+ });
+ it('leaves an unknown currency unvalued', () => {
+ const e = mapRevenueEvent({ id: 'r3', owner_user_id: U, agent_id: A, net_amount: 7, currency_mint: 'Weird', chain: 'solana', intent_id: 'x', created_at: '2026-10-02T00:00:00Z' });
+ expect(e.usd).toBeNull();
+ expect(valueEntry(e, { SOL: 100 }).usd).toBeNull();
+ });
+ it('maps only completed hires to the provider', () => {
+ const h = { id: 'h', status: 'completed', provider_agent_id: A, provider_user_id: U, amount_atomics: '250000', usd: 0.25, currency: 'USDC', payment_signature: SIG, created_at: '2026-10-03T00:00:00Z' };
+ expect(mapHire(h)).toMatchObject({ source: 'hire', usd: 0.25, usd_basis: 'recorded', tx_signature: SIG });
+ expect(mapHire({ ...h, status: 'pending' })).toBeNull();
+ });
+ it('maps settled royalties, excluding EVM ones from totals', () => {
+ const r = { id: 'y', status: 'settled', author_user_id: U, price_usd: '0.0075', network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', tx_hash: SIG, settled_at: '2026-10-04T00:00:00Z' };
+ expect(mapRoyalty(r)).toMatchObject({ amount_atomics: '7500', usd: 0.0075, counted: true });
+ expect(mapRoyalty({ ...r, network: 'eip155:8453' })).toMatchObject({ counted: false, chain: 'base', tx_signature: null });
+ expect(mapRoyalty({ ...r, status: 'pending' })).toBeNull();
+ });
+ it('maps paid invoices and keeps devnet out of mainnet totals', () => {
+ const i = { id: 'i', status: 'paid', user_id: U, agent_id: A, paid_atomics: '5000000', decimals: 6, asset: 'USDC', paid_usd: '5', paid_at: '2026-10-05T00:00:00Z', number: 'INV-1', network: 'devnet', payment_signature: SIG };
+ const e = mapInvoice(i);
+ expect(e).toMatchObject({ usd: 5, network: 'devnet' });
+ expect(summarize([e]).revenue_usd).toBe(0);
+ });
+ it('maps closed positions with signed PnL', () => {
+ const e = mapTradePnl({ id: 'p', status: 'closed', user_id: U, agent_id: A, realized_pnl_lamports: '-1000000000', sell_sig: SIG, closed_at: '2026-10-06T00:00:00Z', network: 'mainnet', symbol: 'X' });
+ expect(e).toMatchObject({ kind: 'pnl', amount_atomics: '-1000000000' });
+ expect(valueEntry(e, { SOL: 150 }).usd).toBe(-150);
+ });
+});
+
+describe('totals', () => {
+ const mk = (source, usd, at) => ({ source, kind: source === 'trading_pnl' ? 'pnl' : 'revenue', usd, occurred_at: at, chain: 'solana', network: 'mainnet', counted: true });
+ it('sums by source, separates PnL, counts unvalued and fills empty periods', () => {
+ const s = summarize([
+ mk('hire', 2, '2026-10-01T10:00:00Z'),
+ mk('skill_sale', 3, '2026-10-01T11:00:00Z'),
+ mk('trading_pnl', -1, '2026-10-03T10:00:00Z'),
+ mk('invoice', null, '2026-10-03T10:00:00Z'),
+ ], { period: 'day' });
+ expect(s.revenue_usd).toBe(5);
+ expect(s.trading_pnl_usd).toBe(-1);
+ expect(s.net_usd).toBe(4);
+ expect(s.unvalued_count).toBe(1);
+ expect(s.series.map((p) => p.start.slice(0, 10))).toEqual(['2026-10-01', '2026-10-02', '2026-10-03']);
+ expect(s.series[1].hire).toBe(0);
+ });
+ it('buckets weeks on Monday and months on the first', () => {
+ expect(bucketStart('2026-10-23T12:00:00Z', 'week').toISOString()).toBe('2026-10-19T00:00:00.000Z');
+ expect(bucketStart('2026-10-23T12:00:00Z', 'month').toISOString()).toBe('2026-10-01T00:00:00.000Z');
+ });
+ it('exports CSV with exact amounts and neutralises formula cells', () => {
+ const csv = toCsv([{ occurred_at: '2026-10-01T00:00:00Z', source: 'hire', kind: 'revenue', asset: 'USDC', amount_atomics: '1500000', decimals: 6, usd: 1.5, counterparty: '=cmd()', label: 'a,b', counted: true }]);
+ const [head, row] = csv.trim().split('\n');
+ expect(head.startsWith('occurred_at,source')).toBe(true);
+ expect(row).toContain(',1.5,');
+ expect(row).toContain("'=cmd()");
+ expect(row).toContain('"a,b"');
+ });
+ it('formats atomics without float drift', () => {
+ expect(formatAtomics('1500000', 6)).toBe('1.5');
+ expect(formatAtomics('-1000000000', 9)).toBe('-1');
+ expect(formatAtomics('1', 9)).toBe('0.000000001');
+ });
+ it('announces milestones in order', () => {
+ expect(reachedMilestones(150)).toEqual([1, 10, 100]);
+ });
+});
+
+describe('projection', () => {
+ const now = Date.parse('2026-10-23T00:00:00Z');
+ const e = (days, usd) => ({ kind: 'revenue', usd, chain: 'solana', network: 'mainnet', counted: true, occurred_at: new Date(now - days * 86400000).toISOString() });
+ it('refuses with too little history', () => {
+ const p = project([e(2, 5), e(1, 5)], { now });
+ expect(p.available).toBe(false);
+ expect(p.reason).toMatch(/at least 7 days/);
+ });
+ it('holds the trailing run rate flat with no growth term', () => {
+ const p = project([e(40, 100), e(20, 30), e(10, 30), e(1, 30)], { now, windowDays: 30, horizonDays: 30 });
+ expect(p.available).toBe(true);
+ expect(p.trailing_revenue_usd).toBe(90);
+ expect(p.per_day_usd).toBe(3);
+ expect(p.projected_usd).toBe(90);
+ expect(p.window_days).toBe(30);
+ });
+});
+
+describe('reinvest rules', () => {
+ const body = { legs: [{ kind: 'model_credits', pct: 20 }, { kind: 'dca_own_coin', pct: 20 }, { kind: 'tools_budget', pct: 10, session_id: '33333333-3333-3333-3333-333333333333' }], per_run_cap_usd: 50, lifetime_cap_usd: 500 };
+ it('accepts the brief example and keeps the rest implicit', () => {
+ const r = normalizeRule(body);
+ expect(r.legs).toHaveLength(3);
+ expect(r.period).toBe('weekly');
+ });
+ it('rejects over 100 percent, duplicates, missing session and missing caps', () => {
+ expect(() => normalizeRule({ ...body, legs: [{ kind: 'model_credits', pct: 60 }, { kind: 'dca_own_coin', pct: 50 }] })).toThrow(/over 100/);
+ expect(() => normalizeRule({ ...body, legs: [{ kind: 'model_credits', pct: 5 }, { kind: 'model_credits', pct: 5 }] })).toThrow(/twice/);
+ expect(() => normalizeRule({ ...body, legs: [{ kind: 'tools_budget', pct: 5 }] })).toThrow(/session/);
+ expect(() => normalizeRule({ ...body, per_run_cap_usd: 0 })).toThrow(/per-run cap/);
+ expect(() => normalizeRule({ ...body, lifetime_cap_usd: 10 })).toThrow(/lifetime cap/);
+ });
+ it('changes the confirmation hash on any edit', () => {
+ const a = { ...normalizeRule(body), agent_id: 'a' };
+ const b = { ...a, legs: a.legs.map((l) => (l.kind === 'model_credits' ? { ...l, pct: 25 } : l)) };
+ expect(ruleHash(a)).toBe(ruleHash({ ...a, legs: [...a.legs].reverse() }));
+ expect(ruleHash(a)).not.toBe(ruleHash(b));
+ expect(ruleHash(a)).not.toBe(ruleHash({ ...a, per_run_cap_usd: 51 }));
+ });
+ it('plans the split and keeps the remainder', () => {
+ const p = planRun({ baseUsd: 100, legs: normalizeRule(body).legs, perRunCapUsd: 50, lifetimeCapUsd: 500 });
+ expect(p.legs.map((l) => l.capped_usd)).toEqual([20, 20, 10]);
+ expect(p.kept_usd).toBe(50);
+ expect(p.scaled).toBe(false);
+ });
+ it('scales every leg proportionally under the per-run cap', () => {
+ const p = planRun({ baseUsd: 1000, legs: normalizeRule(body).legs, perRunCapUsd: 50, lifetimeCapUsd: 500 });
+ expect(p.executable_usd).toBeLessThanOrEqual(50);
+ expect(p.legs[0].capped_usd).toBeCloseTo(p.legs[1].capped_usd, 5);
+ expect(p.legs[0].capped_usd / p.legs[2].capped_usd).toBeCloseTo(2, 3);
+ expect(p.scaled).toBe(true);
+ });
+ it('stops at the lifetime cap and under the minimum run', () => {
+ const legs = normalizeRule(body).legs;
+ expect(planRun({ baseUsd: 100, legs, perRunCapUsd: 50, lifetimeCapUsd: 500, lifetimeSpentUsd: 500 }).skip).toMatch(/lifetime/);
+ expect(planRun({ baseUsd: 100, legs, perRunCapUsd: 50, lifetimeCapUsd: 500, lifetimeSpentUsd: 495 }).executable_usd).toBeLessThanOrEqual(5);
+ const small = planRun({ baseUsd: 1, legs, perRunCapUsd: 50, lifetimeCapUsd: 500, minRunUsd: 1 });
+ expect(small.skip).toMatch(/minimum/);
+ expect(small.executable_usd).toBe(0);
+ expect(planRun({ baseUsd: 0, legs, perRunCapUsd: 50, lifetimeCapUsd: 500 }).skip).toMatch(/No income/);
+ });
+ it('derives stable idempotency keys and the last complete period', () => {
+ const { start, end } = lastPeriod('weekly', Date.parse('2026-10-23T12:00:00Z'));
+ expect(start.toISOString()).toBe('2026-10-12T00:00:00.000Z');
+ expect(end.toISOString()).toBe('2026-10-19T00:00:00.000Z');
+ expect(runKey('r', start)).toBe('revenue_reinvest:r:2026-10-12T00:00:00.000Z');
+ expect(legKey('r', start, 'model_credits')).toBe(`${runKey('r', start)}:model_credits`);
+ expect(lastPeriod('monthly', Date.parse('2026-01-15T00:00:00Z')).start.toISOString()).toBe('2025-12-01T00:00:00.000Z');
+ });
+});
+
+describe('simulated fills', () => {
+ it('keeps simulated positions out of totals', () => {
+ const e = mapTradePnl({ id: 'p', status: 'closed', user_id: U, agent_id: A, realized_pnl_lamports: '1000000000', sell_sig: SIG, closed_at: '2026-10-06T00:00:00Z', network: 'mainnet', exec_route: 'simulated' });
+ expect(e).toMatchObject({ counted: false, exclusion_reason: 'simulated_fill' });
+ expect(summarize([valueEntry(e, { SOL: 100 })]).trading_pnl_usd).toBe(0);
+ });
+});