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(earnings): add the /earnings ledger console, public agent earnings page and revenue ledger docs

nirholasab9e36b55f24
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 43b367a5e..63ec26e9a 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -90,6 +90,7 @@ packages, a generated standalone GitHub mirror). See
| Agent creator earnings ("Earned") | API [api/agents/[id]/earnings.js](api/agents/%5Bid%5D/earnings.js) `→ GET /api/agents/:id/earnings`, read model [api/_lib/agent-earnings.js](api/_lib/agent-earnings.js), snapshot [api/_lib/creator-earnings-snapshot.js](api/_lib/creator-earnings-snapshot.js) run by [api/cron/creator-earnings-snapshot.js](api/cron/creator-earnings-snapshot.js) (every 30 min), pump.fun + on-chain client [api/_lib/pump-creator-fees.js](api/_lib/pump-creator-fees.js), migrations [20260930120000_launcher_claims.sql](api/_lib/migrations/20260930120000_launcher_claims.sql) and [20260930121000_agent_coin_earnings.sql](api/_lib/migrations/20260930121000_agent_coin_earnings.sql), card [src/shared/agent-earnings-card.js](src/shared/agent-earnings-card.js) on `/agents/:id`, `/agents/:id/profile` and the coin page `/launches/:mint`, MCP resource `three://agents/{agentId}/earnings` | Live | What each agent has earned, in SOL with USD beside it: lifetime pump.fun creator fees from its coins (earned, claimed, unclaimed, per coin) with every recorded claim linked to Solscan, plus x402 skill sales and hires. Each coin's fee recipient is read on-chain; pump.fun's creator-fee index supplies per-wallet totals and 30-minute/daily buckets (the 24h/7d/30d windows); unclaimed is the vault balance on-chain. A wallet's fees count toward an agent only when it is that agent's own custodial wallet; other wallets' coins are listed as not counted. Devnet excluded. Docs: [docs/api-reference.md](docs/api-reference.md#agent-earnings). Tests: [tests/agent-earnings.test.js](tests/agent-earnings.test.js), [tests/pump-creator-fees.test.js](tests/pump-creator-fees.test.js) |
| Trader + earnings leaderboard | [pages/leaderboard.html](pages/leaderboard.html) `→ /leaderboard`, controller [src/leaderboard.js](src/leaderboard.js), Earned tab [src/leaderboard-earned.js](src/leaderboard-earned.js), styles [src/leaderboard.css](src/leaderboard.css); APIs [api/sniper/leaderboard.js](api/sniper/leaderboard.js) `→ GET /api/sniper/leaderboard` (trading, `getLeaderboard` in [api/_lib/trader-stats.js](api/_lib/trader-stats.js)) and [api/leaderboard/earnings.js](api/leaderboard/earnings.js) `→ GET /api/leaderboard/earnings` (earned, read model [api/_lib/agent-earnings.js](api/_lib/agent-earnings.js)) | Live | Two boards on one page, with the tab and window in the URL (`?tab=earned&window=7d`) so any view is shareable. Trading ranks agents by a provable sniper track record (score, realized P&L, win rate, ROI). Earned ranks public agents by what they earned in 24h, 7d, 30d or all time: creator fees from their coins plus service income (x402 skill sales and hires), each shown beside the total in SOL with USD, with rank movement against the previous window and the agent's coin. Every Earned row comes from the same computation as the agent's own Earned card, which links back with its rank ("#1 this week"). Designed empty window (launch a coin), stale-snapshot notice and retryable error. Docs: [docs/api-reference.md](docs/api-reference.md#earnings-leaderboard). Tests: [tests/agent-earnings-board.test.js](tests/agent-earnings-board.test.js); live cross-check [scripts/check-earnings-board.mjs](scripts/check-earnings-board.mjs) |
| Creator-fee payouts | Core [api/_lib/creator-payouts-core.js](api/_lib/creator-payouts-core.js), store and sender [api/_lib/creator-payouts.js](api/_lib/creator-payouts.js), endpoint [api/creator-payouts.js](api/creator-payouts.js), crons [creator-payout-distribute.js](api/cron/creator-payout-distribute.js) + [creator-payout-reconcile.js](api/cron/creator-payout-reconcile.js), page [pages/creator-payouts.html](pages/creator-payouts.html) `→ /creator/payouts` + [src/creator-payouts-page.js](src/creator-payouts-page.js), migration `20261023190000_creator_payouts.sql` | Live; sending off until `CREATOR_PAYOUTS_LIVE=true` | The creator's share of every claimed pump.fun fee, sent to a wallet the owner registers by signature plus step-up (48 hour cooldown on change, session-only). One distribution row per claim, held with a named reason (no wallet, cooldown, below minimum, paused), reconciled against the chain. Docs: [docs/creator-payouts.md](docs/creator-payouts.md). Tests: [tests/creator-payouts.test.js](tests/creator-payouts.test.js) |
+| Revenue ledger and reinvest rules | Core [api/_lib/revenue-ledger-core.js](api/_lib/revenue-ledger-core.js), sync [api/_lib/revenue-ledger.js](api/_lib/revenue-ledger.js), reconcile [api/_lib/revenue-reconcile.js](api/_lib/revenue-reconcile.js), rules and runs [api/_lib/revenue-reinvest.js](api/_lib/revenue-reinvest.js), routes [api/_lib/revenue-routes.js](api/_lib/revenue-routes.js) `→ /api/revenue/*`, crons [revenue-ledger-reconcile.js](api/cron/revenue-ledger-reconcile.js) + [revenue-reinvest.js](api/cron/revenue-reinvest.js), pages [pages/earnings.html](pages/earnings.html) `→ /earnings` + [pages/agent-earnings.html](pages/agent-earnings.html) `→ /agents/:id/earnings` with [src/earnings-page.js](src/earnings-page.js), [src/earnings-chart.js](src/earnings-chart.js), [src/agent-earnings-page.js](src/agent-earnings-page.js), migration `20261023170000_revenue_ledger.sql` | Live; reinvest legs need an owner confirmation and obey spend guards | Every income event (creator fees, skill sales, hires, royalties, invoices, realised trading PnL) in one ledger with its Solana transaction, hourly chain reconcile, CSV and JSON export, optional public page, and capped reinvest rules the owner confirms in the browser. Docs: [docs/revenue-ledger.md](docs/revenue-ledger.md). Tests: [tests/revenue-ledger.test.js](tests/revenue-ledger.test.js) |
| Creator-fee payouts | Core [api/_lib/creator-payouts-core.js](api/_lib/creator-payouts-core.js), store and sender [api/_lib/creator-payouts.js](api/_lib/creator-payouts.js), endpoint [api/creator-payouts.js](api/creator-payouts.js), crons [creator-payout-distribute.js](api/cron/creator-payout-distribute.js) + [creator-payout-reconcile.js](api/cron/creator-payout-reconcile.js), page [pages/creator-payouts.html](pages/creator-payouts.html) `→ /creator/payouts` + [src/creator-payouts-page.js](src/creator-payouts-page.js), migration `20261023190000_creator_payouts.sql` | Live; sending off until `CREATOR_PAYOUTS_LIVE=true` | The creator's share of every claimed pump.fun fee, sent to a wallet the owner registers by signature plus step-up (48 hour cooldown on change, session-only). One distribution row per claim, held with a named reason (no wallet, cooldown, below minimum, paused), reconciled against the chain. Docs: [docs/creator-payouts.md](docs/creator-payouts.md). Tests: [tests/creator-payouts.test.js](tests/creator-payouts.test.js) |
| Funded launch intents | Pairs [api/pump/pairs.js](api/pump/pairs.js) + [api/_lib/pump-launch-pairs.js](api/_lib/pump-launch-pairs.js), intents [api/pump/launch-intents.js](api/pump/launch-intents.js) + [api/_lib/pump-funded-launch.js](api/_lib/pump-funded-launch.js), page [pages/launch-intent.html](pages/launch-intent.html) `→ /launch/intents` + [src/launch/launch-intent-page.js](src/launch/launch-intent-page.js), CLI `three-ws agent launch --intent`, migration `20261011000000_pump_funded_launch_intents.sql` | Live | A launch priced up front and paid by the agent wallet: quote, paid, submitted, confirmed, indexed. Only a same-site session can fund or confirm (a bearer can create, read and dry-run), the funding proof is once-only and replayable, the creator fee is picked inside the range the program allows, and a devnet lane rehearses it with no real funds. Docs: [docs/launch-intents.md](docs/launch-intents.md). Tests: [tests/pump-funded-launch.test.js](tests/pump-funded-launch.test.js) |
| create-agent (one command, one 3D character) | [packages/create-agent/](packages/create-agent) (client [src/forge.js](packages/create-agent/src/forge.js), scaffold [src/scaffold.js](packages/create-agent/src/scaffold.js), CLI [bin/create-agent.js](packages/create-agent/bin/create-agent.js)), server tools [api/_mcp-studio/tools.js](api/_mcp-studio/tools.js) | Live | `npm create @three-ws/agent "a friendly cartoon astronaut"` generates a textured figure, rigs it, downloads the GLB, and writes a folder with a working demo page and the embed snippet. No account and no API key: it rides the public, keyless JSON-RPC tools on [/api/mcp-studio](api/_mcp-studio) (`forge_avatar`, `forge_free`, `rig_mesh`) that the platform already exposes to MCP clients. A rigged character reliably outlives the endpoint's inline wait, so the client collects the returned poll handle and, when the job that finished was only the mesh, rigs it before reporting done: that is what the `stage` field on a pending result exists for. Progress is real elapsed time, never an invented bar. Docs [docs/create-agent.md](docs/create-agent.md). Tests: [tests/create-agent.test.js](tests/create-agent.test.js) |
diff --git a/api/_lib/revenue-routes.js b/api/_lib/revenue-routes.js
index 8037e54ff..c9d36cce9 100644
--- a/api/_lib/revenue-routes.js
+++ b/api/_lib/revenue-routes.js
@@ -9,6 +9,7 @@
// GET /entries ledger rows, each with its transaction
// GET /export the same rows as CSV (default) or JSON
// GET /reconcile the latest reconcile run
+// GET /sessions the owner's active payment sessions (targets for a tools-budget leg)
// 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
@@ -171,6 +172,19 @@ async function runsRoute({ principal, query }) {
return { runs: await listRuns({ userId: principal.userId, agentId, ruleId, limit: intParam(query.limit, { name: 'limit', min: 1, max: 100, fallback: 30 }) }) };
}
+async function sessionsRoute({ principal }) {
+ const rows = await sql`
+ select id, label, budget_usdc, spent_usdc, network, expires_at from payment_sessions
+ where user_id = ${principal.userId} and status = 'active' and network = 'solana' and expires_at > now()
+ order by created_at desc limit 50`;
+ return {
+ sessions: rows.map((r) => ({
+ id: r.id, label: r.label || 'Payment session', network: r.network, expires_at: r.expires_at,
+ budget_usd: Number(r.budget_usdc) / 1e6, spent_usd: Number(r.spent_usdc) / 1e6,
+ })),
+ };
+}
+
async function sourcesRoute() {
return { sources: SOURCES.map(({ key, label, kind, how }) => ({ key, label, kind, how })) };
}
@@ -182,6 +196,7 @@ export const revenueRoutes = [
{ 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: 'GET', path: '/sessions', name: 'revenue.sessions', auth: 'required', scope: 'wallet:read', handler: sessionsRoute },
{ 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 },
diff --git a/data/changelog.json b/data/changelog.json
index fb347af85..e80a339a9 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-10-23",
+ "title": "One earnings ledger for everything your agents earn, with reinvest rules",
+ "summary": "The new Earnings page totals creator fees, skill and API sales, hires, royalties, invoices and realised trading PnL by source and period, links every row to its Solana transaction, reconciles against the chain every hour, and exports CSV or JSON. Agents can publish a public earnings page, and confirmed reinvest rules put a capped share of each period into model credits, a tools budget or a DCA of the agent's own coin, with a receipt for every run.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/earnings"
+ },
{
"date": "2026-10-23",
"title": "Creator-fee payouts: register a wallet and see every distribution",
diff --git a/data/pages.json b/data/pages.json
index d8862eb62..864621d4c 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -448,6 +448,23 @@
"added": "2026-10-10",
"indexable": false
},
+ {
+ "path": "/earnings",
+ "title": "Earnings",
+ "description": "One ledger for everything your agents earn: creator fees, skill sales, hires, royalties, invoices and realised trading PnL, each row linked to its Solana transaction, plus reinvest rules you confirm.",
+ "priority": 0.5,
+ "changefreq": "daily",
+ "added": "2026-10-23",
+ "indexable": false
+ },
+ {
+ "path": "/docs/revenue-ledger",
+ "title": "Docs · Revenue ledger",
+ "description": "How the earnings ledger counts creator fees, skill sales, hires, royalties, invoices and trading PnL, reconciles them against the chain, and how confirmed reinvest rules spend a share of each period's income.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-10-23"
+ },
{
"path": "/commerce",
"title": "Agent Commerce",
diff --git a/docs/revenue-ledger.md b/docs/revenue-ledger.md
new file mode 100644
index 000000000..f8a0d7b33
--- /dev/null
+++ b/docs/revenue-ledger.md
@@ -0,0 +1,84 @@
+# Revenue ledger and reinvest rules
+
+One ledger for everything your agents earn, with every row tied to its Solana transaction, plus standing rules that put a share of each period's income back to work. The owner console is [/earnings](https://three.ws/earnings). An agent can also publish its own page at `/agents/<id>/earnings`.
+
+## What is counted
+
+| Source | Where it comes from | Valued in USD |
+| --- | --- | --- |
+| Creator fees | Pump.fun creator fees claimed to the agent wallet (`launcher_claims`) | SOL price when the ledger first saw the claim |
+| Skill and API sales | x402 sales, net of the platform fee (`agent_revenue_events`) | The settled asset (USDC exactly) |
+| Hires | Completed agent-to-agent hires paid to the agent | The USD amount recorded at settlement |
+| Skill royalties | Author share of marketplace skill calls (`royalty_ledger`, settled) | The USD amount recorded at settlement |
+| Invoices | Agent invoices that reached paid | The USD value fixed when paid |
+| Trading PnL (realised) | Closed sniper positions | SOL at exit, valued at first sight. Reported apart: it is not revenue and can be negative |
+
+Mainnet Solana only. EVM and Base sales appear in the entry list marked as excluded and never enter a total. Devnet is test traffic and stays out. Unclaimed creator fees are shown as a memo and counted once claimed.
+
+Each entry is copied from the table that owns it, keyed by `(source, source_ref)`, so a sync can run any number of times without double counting. The price used is stored on the row (`usd_price`, `usd_basis`) and never re-computed, so a past total does not move when the market does.
+
+## Reconciliation
+
+An hourly cron (`/api/cron/revenue-ledger-reconcile`, `11 * * * *`) re-derives each source total from the owning table and compares it with the ledger (database drift), and checks recent entries' signatures on chain (verified, mismatch or not found). The console shows the latest run and a verified count. Chain history reaches back `REVENUE_CHAIN_HISTORY_DAYS` days (default in code). A drift or mismatch raises a notification.
+
+## Projection
+
+The projection is the trailing revenue (default 30 days) divided by the days covered, held flat for 30 days, with no growth assumed. It needs at least 7 days of history and 3 income entries in the window and says so when it has too little to project.
+
+## Public earnings page
+
+Off by default. The owner switches it on per agent in the console. The public view carries entries with their transaction links and the totals, and leaves out counterparty addresses and internal ids. Switching it off removes it immediately.
+
+## Reinvest rules
+
+A rule says what share of each period's income goes where.
+
+| Leg | What it does |
+| --- | --- |
+| Model credits | USDC from the agent wallet to the platform deposit wallet, then your credit balance is credited from that signature |
+| Tools budget | The same deposit, then the credits move into a named x402 payment session's budget |
+| DCA into the agent's own coin | A pump.fun buy of the agent's own coin through the standard trade pipeline |
+
+The base is the last complete period (day, week or month, UTC) of revenue, or revenue plus realised trading profit.
+
+Safety, in the order it bites:
+
+1. A rule only runs after the owner confirms its exact terms in a signed-in browser. The confirmation table lists every destination, asset, chain, amount and both caps. An API key or agent token cannot confirm (`POST /rules/:id/confirm` is session-only).
+2. Any edit changes the rule hash and clears the confirmation.
+3. A per-run cap and a lifetime cap scale every leg by the same factor, so the split ratios survive the cap. Below the minimum run size nothing executes.
+4. Each period runs once. The run row is unique on `(rule, period)` and every leg has its own idempotency key, so a retry never sends twice.
+5. Every leg passes the same spend guards as any agent spend. A guard that needs the owner parks the leg in the [approvals inbox](approvals.md) instead of failing.
+6. Repeated failures pause the rule and notify the owner.
+
+A test run plans the next run and paper-trades the buys. Nothing is sent. Every real run leaves a receipt with its legs, transaction signatures and approval state, shown on the console under the rule.
+
+An hourly cron (`/api/cron/revenue-reinvest`, `37 * * * *`) runs due rules.
+
+## API
+
+All under `/api/revenue`. Owner routes take a session, API key or OAuth token with `wallet:read` (`agents:write` for settings).
+
+| Method and path | Purpose |
+| --- | --- |
+| `GET /public/:agentId` | Public earnings, only when the owner switched them on |
+| `GET /sources` | The sources and how each is calculated |
+| `GET /ledger?agent_id&period&from&to` | Totals by source and period, projection, unclaimed memo, chain checks, reconcile status |
+| `GET /entries?agent_id&source&before&limit` | Ledger rows, each with its explorer link |
+| `GET /export?format=csv\|json` | Every row for the scope |
+| `GET /reconcile` | Latest reconcile run |
+| `GET /sessions` | Active Solana payment sessions, targets for a tools-budget leg |
+| `POST /sync` | Bring the ledger up to date now |
+| `GET/PUT /agents/:id/settings` | The public toggle |
+| `GET/POST /rules`, `PATCH/DELETE /rules/:id` | Manage rules |
+| `GET /rules/:id/preview` | The confirmation table for the rule's current terms |
+| `POST /rules/:id/confirm` | The explicit yes (session only), body `{ hash }` |
+| `POST /rules/:id/pause`, `POST /rules/:id/test-run` | Pause, or paper-run |
+| `GET /runs?agent_id&rule_id` | Run receipts |
+
+## Files
+
+- Pure logic: `api/_lib/revenue-ledger-core.js`. Database and sync: `api/_lib/revenue-ledger.js`. Reconcile: `api/_lib/revenue-reconcile.js`. Rules and runs: `api/_lib/revenue-reinvest.js`. Routes: `api/_lib/revenue-routes.js`, mounted at `api/revenue/[...route].js`.
+- Crons: `api/cron/revenue-ledger-reconcile.js`, `api/cron/revenue-reinvest.js`.
+- Migration: `api/_lib/migrations/20261023170000_revenue_ledger.sql`.
+- Pages: `pages/earnings.html` with `src/earnings-page.js`, `src/earnings-chart.js`, `src/earnings.css`; public `pages/agent-earnings.html` with `src/agent-earnings-page.js`.
+- Tests: `tests/revenue-ledger.test.js`.
diff --git a/pages/agent-earnings.html b/pages/agent-earnings.html
new file mode 100644
index 000000000..3326547fb
--- /dev/null
+++ b/pages/agent-earnings.html
@@ -0,0 +1,105 @@
+<!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: no-flash; runtime in /theme-switcher.js */(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" />
+ <title>Agent earnings · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="theme-color" content="#000000" />
+ <meta name="description" content="What this agent has earned: creator fees, skill sales, hires, royalties, invoices and realised trading PnL, every row linked to its Solana transaction." />
+ <meta name="robots" content="noindex" />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/agents" />
+ <meta property="og:title" content="Agent earnings · three.ws" />
+ <meta property="og:description" content="What this agent has earned, every row linked to its transaction." />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Agent+earnings&amp;d=Every+row+linked+to+its+Solana+transaction." />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <link rel="canonical" href="https://three.ws/agents" />
+
+ <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="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ </head>
+ <body>
+ <div id="nav-container"></div>
+
+ <main class="ac-wrap">
+ <p class="ac-crumb"><a href="/">Home</a> / <a href="/agents" id="ae-agents-link">Agents</a> / <span id="ae-crumb">Earnings</span></p>
+ <div class="ac-hero">
+ <div>
+ <h1 class="ac-h1" id="ae-title">Earnings</h1>
+ <p class="ac-lede">Everything this agent has earned, copied from the records that own it and linked to its Solana transaction. Nothing is estimated.</p>
+ </div>
+ <button type="button" class="ac-btn" id="er-how">How it is calculated</button>
+ </div>
+
+ <div id="er-live" class="ac-sr" aria-live="polite"></div>
+ <div id="er-error" class="ac-notice ac-notice-error" role="alert" hidden></div>
+
+ <div id="ae-private" class="ac-empty" hidden>
+ <div class="ac-empty-icon" aria-hidden="true">🔒</div>
+ <h3>This agent's earnings are private</h3>
+ <p>Its owner has not made them public. If this is your agent, sign in and switch on the public earnings page from your earnings console.</p>
+ <a class="ac-btn ac-btn-primary" href="/earnings">Open my earnings</a>
+ </div>
+
+ <div id="er-skel" aria-hidden="true">
+ <div class="er-stats"><div class="er-skel"></div><div class="er-skel"></div><div class="er-skel"></div></div>
+ <div class="er-skel" style="height:300px"></div>
+ </div>
+
+ <div id="er-main" hidden>
+ <div class="er-controls">
+ <div class="ac-field">
+ <label for="er-period">Group by</label>
+ <select id="er-period"><option value="day">Day</option><option value="week">Week</option><option value="month" selected>Month</option></select>
+ </div>
+ <div class="er-spacer"></div>
+ <p class="ac-hint" id="ae-since" style="margin:0"></p>
+ </div>
+ <dl class="er-stats" id="er-stats"></dl>
+ <section class="er-panel" aria-labelledby="er-chart-h">
+ <h2 class="ac-h2" id="er-chart-h">Income by source</h2>
+ <p class="ac-hint">Revenue only, in USD, stacked by source. Trading PnL is reported separately because it is not revenue and can be negative.</p>
+ <div class="er-chart" id="er-chart"></div>
+ </section>
+ <div class="er-split">
+ <section class="er-panel" aria-labelledby="er-src-h">
+ <h2 class="ac-h2" id="er-src-h">By source</h2>
+ <ul class="er-sources" id="er-sources"></ul>
+ </section>
+ <div>
+ <section class="er-panel" aria-labelledby="er-proj-h"><h2 class="ac-h2" id="er-proj-h">Projection</h2><div id="er-proj"></div></section>
+ <section class="er-panel" aria-labelledby="er-rec-h"><h2 class="ac-h2" id="er-rec-h">Verification</h2><div id="er-rec"></div></section>
+ </div>
+ </div>
+ <section class="er-panel" aria-labelledby="er-led-h">
+ <h2 class="ac-h2" id="er-led-h">Latest ledger rows</h2>
+ <p class="ac-hint">The newest 200 events. Every row with a transaction links to Solscan.</p>
+ <div class="er-ledger" id="er-ledger"></div>
+ </section>
+ </div>
+ </main>
+
+ <div class="er-drawer-backdrop" id="er-backdrop" hidden></div>
+ <aside class="er-drawer" id="er-drawer" role="dialog" aria-modal="true" aria-labelledby="er-drawer-h" hidden></aside>
+
+ <script type="module" src="/src/agent-earnings-page.js"></script>
+ <script src="/nav.js" defer></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/i18n.js"></script>
+ </body>
+</html>
diff --git a/pages/earnings.html b/pages/earnings.html
new file mode 100644
index 000000000..4f92da7f0
--- /dev/null
+++ b/pages/earnings.html
@@ -0,0 +1,156 @@
+<!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: no-flash; runtime in /theme-switcher.js */(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" />
+ <title>Earnings · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="theme-color" content="#000000" />
+ <meta name="description" content="Everything your agents earn in one ledger: creator fees, skill sales, hires, royalties, invoices and realised trading PnL, each row linked to its Solana transaction, with reinvest rules you confirm." />
+ <meta name="robots" content="noindex" />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/earnings" />
+ <meta property="og:title" content="Earnings · three.ws" />
+ <meta property="og:description" content="One ledger for everything your agents earn, every row linked to its transaction." />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Earnings&amp;d=One+ledger+for+everything+your+agents+earn%2C+every+row+linked+to+its+transaction.&amp;p=%2Fearnings" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <link rel="canonical" href="https://three.ws/earnings" />
+
+ <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="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ </head>
+ <body>
+ <div id="nav-container"></div>
+
+ <main class="ac-wrap">
+ <p class="ac-crumb"><a href="/">Home</a> / <a href="/dashboard">Dashboard</a> / Earnings</p>
+ <div class="ac-hero">
+ <div>
+ <h1 class="ac-h1">Earnings</h1>
+ <p class="ac-lede">Every way your agents earn, in one ledger. Each row links to its Solana transaction, the totals are reconciled against the chain and the database every hour, and nothing here is estimated except the projection, which says exactly what it is built from.</p>
+ </div>
+ <button type="button" class="ac-btn" id="er-how">How it is calculated</button>
+ </div>
+
+ <div id="er-live" class="ac-sr" aria-live="polite"></div>
+ <div id="er-error" class="ac-notice ac-notice-error" role="alert" hidden></div>
+ <div id="er-flash" class="ac-notice ac-notice-ok" role="status" hidden></div>
+
+ <div id="er-auth" class="ac-empty" hidden>
+ <div class="ac-empty-icon" aria-hidden="true">📒</div>
+ <h3>Sign in to see what your agents earned</h3>
+ <p>The ledger belongs to the agents you own. Sign in to see it.</p>
+ <a class="ac-btn ac-btn-primary" id="er-login" href="/login?next=/earnings">Sign in</a>
+ </div>
+
+ <div id="er-skel" aria-hidden="true">
+ <div class="er-stats"><div class="er-skel"></div><div class="er-skel"></div><div class="er-skel"></div></div>
+ <div class="er-skel" style="height:300px"></div>
+ </div>
+
+ <div id="er-main" hidden>
+ <div class="er-controls">
+ <div class="ac-field">
+ <label for="er-agent">Agent</label>
+ <select id="er-agent"></select>
+ </div>
+ <div class="ac-field">
+ <label for="er-period">Group by</label>
+ <select id="er-period">
+ <option value="day">Day</option>
+ <option value="week">Week</option>
+ <option value="month" selected>Month</option>
+ </select>
+ </div>
+ <div class="er-spacer"></div>
+ <div class="er-actions">
+ <button type="button" class="ac-btn" id="er-sync">Sync now</button>
+ <a class="ac-btn" id="er-csv" href="/api/revenue/export?format=csv" download>Export CSV</a>
+ <a class="ac-btn" id="er-json" href="/api/revenue/export?format=json" target="_blank" rel="noopener">Export JSON</a>
+ </div>
+ </div>
+
+ <dl class="er-stats" id="er-stats"></dl>
+
+ <section class="er-panel" aria-labelledby="er-chart-h">
+ <h2 class="ac-h2" id="er-chart-h">Income by source</h2>
+ <p class="ac-hint">Revenue only, in USD, stacked by source. Trading PnL is reported separately because it is not revenue and can be negative.</p>
+ <div class="er-chart" id="er-chart"></div>
+ </section>
+
+ <div class="er-split">
+ <section class="er-panel" aria-labelledby="er-src-h">
+ <h2 class="ac-h2" id="er-src-h">By source</h2>
+ <p class="ac-hint">Lifetime totals in the selected scope, mainnet Solana only.</p>
+ <ul class="er-sources" id="er-sources"></ul>
+ </section>
+ <div>
+ <section class="er-panel" aria-labelledby="er-proj-h">
+ <h2 class="ac-h2" id="er-proj-h">Projection</h2>
+ <div id="er-proj"></div>
+ </section>
+ <section class="er-panel" aria-labelledby="er-rec-h">
+ <h2 class="ac-h2" id="er-rec-h">Reconciliation</h2>
+ <div id="er-rec"></div>
+ </section>
+ <section class="er-panel" aria-labelledby="er-pub-h" id="er-pub-panel" hidden>
+ <h2 class="ac-h2" id="er-pub-h">Public earnings page</h2>
+ <p class="ac-hint">Show this agent's earnings, with every row linked to its transaction, on a public page anyone can open. Counterparty addresses stay private.</p>
+ <label class="er-toggle"><input type="checkbox" id="er-pub" /> <span id="er-pub-label">Public</span></label>
+ <p class="ac-hint" id="er-pub-link" hidden></p>
+ </section>
+ </div>
+ </div>
+
+ <section class="er-panel" aria-labelledby="er-led-h">
+ <div class="ac-bar">
+ <div>
+ <h2 class="ac-h2" id="er-led-h">Ledger</h2>
+ <p class="ac-hint">Newest first. Every row is one income event copied from the table that owns it.</p>
+ </div>
+ <div class="ac-field" style="margin:0">
+ <label for="er-src-filter" class="ac-sr">Filter by source</label>
+ <select id="er-src-filter"><option value="">All sources</option></select>
+ </div>
+ </div>
+ <div class="er-ledger" id="er-ledger"></div>
+ <div class="ac-more" id="er-more" hidden><button type="button" class="ac-btn" id="er-more-btn">Load more</button></div>
+ </section>
+
+ <section class="er-panel" id="rules" aria-labelledby="er-rules-h">
+ <div class="ac-bar">
+ <div>
+ <h2 class="ac-h2" id="er-rules-h">Reinvest rules</h2>
+ <p class="ac-hint">Say what share of each period's income goes where. A rule only runs after you confirm its exact amounts and destinations here, in your browser, and any edit asks again. Every run is capped, idempotent and leaves a receipt.</p>
+ </div>
+ <button type="button" class="ac-btn ac-btn-primary" id="er-rule-new">New rule</button>
+ </div>
+ <form class="ac-card ac-form" id="er-rule-form" novalidate hidden></form>
+ <div id="er-rules"></div>
+ </section>
+ </div>
+ </main>
+
+ <div class="er-drawer-backdrop" id="er-backdrop" hidden></div>
+ <aside class="er-drawer" id="er-drawer" role="dialog" aria-modal="true" aria-labelledby="er-drawer-h" hidden></aside>
+
+ <script type="module" src="/src/earnings-page.js"></script>
+ <script src="/nav.js" defer></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/i18n.js"></script>
+ </body>
+</html>
diff --git a/src/agent-earnings-page.js b/src/agent-earnings-page.js
new file mode 100644
index 000000000..61367e05d
--- /dev/null
+++ b/src/agent-earnings-page.js
@@ -0,0 +1,139 @@
+// Public earnings page for one agent (pages/agent-earnings.html, route
+// /agents/:id/earnings). Only renders when the owner switched the page on; the
+// API answers 404 not_public otherwise. Same numbers and chart as the owner
+// console, with counterparty addresses withheld by the server.
+// API: GET /api/revenue/public/:agentId. Doc: docs/revenue-ledger.md.
+
+import './agent-commerce.css';
+import './earnings.css';
+import { esc, relTime } from './agent-commerce-format.js';
+import { renderEarningsChart, slotOf, usd } from './earnings-chart.js';
+
+const $ = (id) => document.getElementById(id);
+const agentId = (location.pathname.match(/\/agents\/([^/]+)\/earnings/) || [])[1];
+let view = null;
+let drawerReturn = null;
+
+const signedUsd = (n) => `${Number(n) < 0 ? '-' : ''}${usd(Math.abs(Number(n)))}`;
+const fmtDate = (iso) => (iso ? new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }) : '');
+const short = (sig) => (sig ? `${sig.slice(0, 6)}…${sig.slice(-6)}` : '');
+const sourceOf = (key) => view?.sources?.find((s) => s.key === key);
+
+function showError(msg, retry) {
+ const el = $('er-error');
+ el.innerHTML = `<strong>${esc(msg)}</strong>${retry ? '<br><button type="button" class="ac-btn ac-btn-sm" data-retry>Try again</button>' : ''}`;
+ el.hidden = false;
+ el._retry = retry || null;
+}
+
+async function load() {
+ $('er-error').hidden = true;
+ $('er-skel').hidden = false;
+ let res;
+ try {
+ res = await fetch(`/api/revenue/public/${encodeURIComponent(agentId)}?period=${$('er-period').value}`, { headers: { accept: 'application/json' } });
+ } catch {
+ $('er-skel').hidden = true;
+ return showError('Network error. Check your connection and try again.', load);
+ }
+ const json = await res.json().catch(() => ({}));
+ $('er-skel').hidden = true;
+ if (res.status === 404 || res.status === 400) {
+ $('er-main').hidden = true;
+ $('ae-private').hidden = false;
+ return;
+ }
+ if (!res.ok) return showError(json?.error?.message || `Could not load these earnings (${res.status}).`, load);
+ view = json?.data ?? json;
+ $('ae-private').hidden = true;
+ $('er-main').hidden = false;
+ render();
+}
+
+function render() {
+ const { agent, summary, projection: p, sources } = view;
+ document.title = `${agent.name || 'Agent'} earnings · three.ws`;
+ $('ae-title').textContent = `${agent.name || 'Agent'} earnings`;
+ $('ae-crumb').textContent = 'Earnings';
+ $('ae-agents-link').href = `/agent/${agent.id}`;
+ $('ae-agents-link').textContent = agent.name || 'Agent';
+ $('ae-since').textContent = view.public_since ? `Public since ${fmtDate(view.public_since)}` : '';
+
+ const pnl = summary.trading_pnl_usd;
+ const un = view.unclaimed_creator_fees;
+ const tiles = [
+ { k: 'Revenue', v: usd(summary.revenue_usd), s: 'Creator fees, sales, hires, royalties and invoices.' },
+ { k: 'Realised trading PnL', v: `<span class="${pnl < 0 ? 'er-neg' : ''}">${signedUsd(pnl)}</span>`, s: 'Closed positions only. Not revenue.' },
+ { k: 'Net', v: `<span class="${summary.net_usd < 0 ? 'er-neg' : ''}">${signedUsd(summary.net_usd)}</span>`, s: 'Revenue plus realised PnL.' },
+ ];
+ if (un && Number(un.sol) > 0) tiles.push({ k: 'Unclaimed creator fees', v: un.usd != null ? usd(un.usd) : `${un.sol} SOL`, s: `${un.sol} SOL not yet claimed. Counted once claimed.` });
+ $('er-stats').innerHTML = tiles.map((t) => `<div class="er-stat"><dt>${esc(t.k)}</dt><dd>${t.v}</dd><small>${t.s}</small></div>`).join('');
+
+ renderEarningsChart($('er-chart'), { summary, sources });
+
+ $('er-sources').innerHTML = sources.map((s) => {
+ const v = summary.by_source[s.key];
+ const sub = v.count ? `${v.count} ${v.count === 1 ? 'event' : 'events'}` : 'Nothing yet';
+ return `<li><span class="er-swatch" style="background:var(--er-s${slotOf(sources, s.key)})" aria-hidden="true"></span><span>${esc(s.label)}${s.kind === 'pnl' ? ' <span class="er-chip">not revenue</span>' : ''}</span><span class="er-amt ${s.kind === 'pnl' && v.usd < 0 ? 'er-neg' : ''}">${s.kind === 'pnl' ? signedUsd(v.usd) : usd(v.usd)}</span><span class="er-sub">${esc(sub)}</span></li>`;
+ }).join('');
+
+ $('er-proj').innerHTML = p.available
+ ? `<p><span class="ac-num" style="font-size:var(--text-xl);color:var(--ink-bright)">${usd(p.projected_usd)}</span></p><p class="ac-hint">Expected over the next ${p.horizon_days} days. ${esc(p.method)}</p><p class="ac-hint">Window: ${esc(fmtDate(p.window_start))} to ${esc(fmtDate(p.window_end))}, ${p.entries_in_window} income ${p.entries_in_window === 1 ? 'event' : 'events'}. A projection, not income.</p>`
+ : `<p class="ac-hint">No projection yet. ${esc(p.reason)}</p>`;
+
+ const c = view.chain_verification;
+ $('er-rec').innerHTML = `<p class="ac-hint">${c.verified} ${c.verified === 1 ? 'transaction' : 'transactions'} verified on-chain${c.issues ? `, <strong class="er-neg">${c.issues} under review</strong>` : ''}${c.unchecked ? `, ${c.unchecked} not yet checked` : ''}.</p>${view.synced_at ? `<p class="ac-hint">Ledger synced ${esc(relTime(view.synced_at))}.</p>` : ''}`;
+
+ renderLedger();
+}
+
+function renderLedger() {
+ if (!view.entries.length) {
+ $('er-ledger').innerHTML = '<div class="ac-empty"><h3>No income recorded yet</h3><p>Rows appear here as this agent earns.</p></div>';
+ return;
+ }
+ const rows = view.entries.map((e) => {
+ const src = sourceOf(e.source);
+ const tx = e.explorer_url ? `<a href="${esc(e.explorer_url)}" target="_blank" rel="noopener" class="ac-mono">${esc(short(e.tx_signature))}</a>` : '<span class="er-dim">no transaction</span>';
+ const chain = e.chain_status === 'verified' ? '<span class="er-chip er-chip-ok">verified</span>' : '';
+ const net = e.network !== 'mainnet' || e.chain !== 'solana' ? `<span class="er-chip" title="${esc(e.exclusion_reason || '')}">${esc(e.chain === 'solana' ? e.network : e.chain)}</span>` : '';
+ return `<tr class="${e.counted ? '' : 'is-excluded'}"><td>${esc(fmtDate(e.occurred_at))}</td><td><span class="er-swatch" style="background:var(--er-s${slotOf(view.sources, e.source)})" aria-hidden="true"></span> ${esc(src?.label || e.source)} ${net}</td><td class="er-label">${esc(e.label || '')}</td><td class="er-r">${esc(e.amount)} ${esc(e.asset)}</td><td class="er-r">${e.usd == null ? '<span class="er-dim">unvalued</span>' : `<span class="${e.usd < 0 ? 'er-neg' : ''}">${signedUsd(e.usd)}</span>`}</td><td>${tx} ${chain}</td></tr>`;
+ }).join('');
+ $('er-ledger').innerHTML = `<table><caption class="ac-sr">Earnings ledger</caption><thead><tr><th scope="col">When</th><th scope="col">Source</th><th scope="col">Detail</th><th scope="col" class="er-r">Amount</th><th scope="col" class="er-r">USD</th><th scope="col">Transaction</th></tr></thead><tbody>${rows}</tbody></table>`;
+}
+
+function openDrawer() {
+ const sources = view?.sources || [];
+ const drawer = $('er-drawer');
+ drawer.innerHTML = `
+ <button type="button" class="ac-btn ac-btn-sm er-drawer-close" data-close>Close</button>
+ <h2 class="ac-h2" id="er-drawer-h">How this is calculated</h2>
+ <p class="ac-hint">The ledger is a copy of income events from the tables that own them, re-checked against them and against the chain every hour.</p>
+ <dl>${sources.map((s) => `<dt><span class="er-swatch" style="background:var(--er-s${slotOf(sources, s.key)})" aria-hidden="true"></span>${esc(s.label)}</dt><dd>${esc(s.how)}</dd>`).join('')}</dl>
+ <h3 class="ac-section-title" style="margin-top:20px">Not included</h3>
+ <ul>${(view?.not_included || []).map((x) => `<li>${esc(x)}</li>`).join('')}</ul>
+ <h3 class="ac-section-title" style="margin-top:20px">Projection</h3>
+ <ul><li>Trailing real revenue divided by the days it covers, held flat for 30 days. It needs 7 days of history and 3 income events. No growth is assumed.</li></ul>`;
+ drawerReturn = document.activeElement;
+ $('er-backdrop').hidden = false;
+ drawer.hidden = false;
+ drawer.querySelector('[data-close]').focus();
+}
+function closeDrawer() {
+ $('er-drawer').hidden = true;
+ $('er-backdrop').hidden = true;
+ drawerReturn?.focus?.();
+}
+
+if (!agentId) {
+ $('er-skel').hidden = true;
+ $('ae-private').hidden = false;
+} else {
+ $('er-period').addEventListener('change', load);
+ $('er-how').addEventListener('click', openDrawer);
+ $('er-backdrop').addEventListener('click', closeDrawer);
+ $('er-drawer').addEventListener('click', (e) => { if (e.target.closest('[data-close]')) closeDrawer(); });
+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !$('er-drawer').hidden) closeDrawer(); });
+ $('er-error').addEventListener('click', (e) => { if (e.target.closest('[data-retry]')) $('er-error')._retry?.(); });
+ load();
+}
diff --git a/src/earnings-chart.js b/src/earnings-chart.js
new file mode 100644
index 000000000..dec742f2d
--- /dev/null
+++ b/src/earnings-chart.js
@@ -0,0 +1,201 @@
+// Stacked-bar chart of income by source over time, shared by the owner console
+// (/earnings) and the public page (/agents/:id/earnings). Plain SVG, no library.
+//
+// One axis (USD), the five revenue sources stacked in their fixed colour slots
+// (api/_lib/revenue-ledger-core.js SOURCES order), a legend, a total label over
+// each bar, a hover/focus tooltip and a table view of the same numbers. Trading
+// PnL is not stacked: it can be negative and it is not revenue, so the page
+// shows it as its own figure. Colours live in src/earnings.css as tokens.
+
+import { esc } from './agent-commerce-format.js';
+
+const STACK = ['creator_fee_claim', 'skill_sale', 'hire', 'skill_royalty', 'invoice'];
+const SVG_NS = 'http://www.w3.org/2000/svg';
+
+export const usd = (n) => `$${Number(n || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
+
+function usdShort(n) {
+ const v = Number(n || 0);
+ if (v >= 10000) return `$${(v / 1000).toFixed(v >= 100000 ? 0 : 1)}k`;
+ if (v >= 100) return `$${Math.round(v)}`;
+ return `$${v.toFixed(2).replace(/\.00$/, '')}`;
+}
+
+function bucketLabel(iso, period) {
+ const d = new Date(iso);
+ if (period === 'month') return d.toLocaleDateString(undefined, { month: 'short', year: '2-digit', timeZone: 'UTC' });
+ return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', timeZone: 'UTC' });
+}
+
+function bucketTitle(iso, period) {
+ const d = new Date(iso);
+ if (period === 'month') return d.toLocaleDateString(undefined, { month: 'long', year: 'numeric', timeZone: 'UTC' });
+ if (period === 'week') return `Week of ${d.toLocaleDateString(undefined, { dateStyle: 'medium', timeZone: 'UTC' })}`;
+ return d.toLocaleDateString(undefined, { dateStyle: 'medium', timeZone: 'UTC' });
+}
+
+function niceMax(v) {
+ if (v <= 0) return 1;
+ const pow = 10 ** Math.floor(Math.log10(v));
+ const n = v / pow;
+ const step = n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10;
+ return step * pow;
+}
+
+function svg(tag, attrs = {}, text) {
+ const el = document.createElementNS(SVG_NS, tag);
+ for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, String(v));
+ if (text != null) el.textContent = text;
+ return el;
+}
+
+/** Colour slot (1-6) for a source key, by its position in the full source list. */
+export function slotOf(sources, key) {
+ const i = sources.findIndex((s) => s.key === key);
+ return i < 0 ? 6 : i + 1;
+}
+
+/**
+ * Mount the chart into `host`.
+ * summary: the `summary` object from the ledger view; sources: the `sources` list.
+ */
+export function renderEarningsChart(host, { summary, sources }) {
+ const series = summary.series || [];
+ const period = summary.period || 'month';
+ const stack = STACK.filter((k) => sources.some((s) => s.key === k));
+ const label = (k) => sources.find((s) => s.key === k)?.label || k;
+ const present = stack.filter((k) => summary.by_source[k] && (summary.by_source[k].usd > 0 || summary.by_source[k].count > 0));
+
+ host.innerHTML = '';
+ if (!series.length || !stack.some((k) => series.some((b) => b[k] > 0))) {
+ host.innerHTML = '<p class="er-chart-empty">No valued income in this period yet. Bars appear here as soon as the first sale, fee claim, hire, royalty or invoice lands.</p>';
+ return;
+ }
+
+ const legend = document.createElement('ul');
+ legend.className = 'er-legend';
+ legend.setAttribute('aria-label', 'Income sources');
+ for (const k of (present.length ? present : stack)) {
+ const li = document.createElement('li');
+ li.innerHTML = `<span class="er-swatch" style="background:var(--er-s${slotOf(sources, k)})" aria-hidden="true"></span>${esc(label(k))}`;
+ legend.append(li);
+ }
+
+ const tabs = document.createElement('div');
+ tabs.className = 'er-viewtoggle';
+ tabs.setAttribute('role', 'group');
+ tabs.setAttribute('aria-label', 'Chart view');
+ tabs.innerHTML = '<button type="button" class="ac-btn ac-btn-sm" data-view="chart" aria-pressed="true">Chart</button><button type="button" class="ac-btn ac-btn-sm" data-view="table" aria-pressed="false">Table</button>';
+
+ const head = document.createElement('div');
+ head.className = 'er-chart-head';
+ head.append(legend, tabs);
+
+ const stage = document.createElement('div');
+ stage.className = 'er-stage';
+ const tip = document.createElement('div');
+ tip.className = 'er-tip';
+ tip.setAttribute('role', 'status');
+ tip.hidden = true;
+
+ const tableWrap = document.createElement('div');
+ tableWrap.className = 'er-tablewrap';
+ tableWrap.hidden = true;
+ tableWrap.innerHTML = tableHtml(series, stack, label, period);
+
+ host.append(head, stage, tip, tableWrap);
+
+ const W = 720;
+ const H = 280;
+ const m = { top: 22, right: 8, bottom: 30, left: 48 };
+ const iw = W - m.left - m.right;
+ const ih = H - m.top - m.bottom;
+ const totals = series.map((b) => stack.reduce((a, k) => a + (b[k] > 0 ? b[k] : 0), 0));
+ const max = niceMax(Math.max(...totals));
+ const y = (v) => m.top + ih - (v / max) * ih;
+ const slot = iw / series.length;
+ const bw = Math.min(56, Math.max(6, slot * 0.62));
+
+ const root = svg('svg', { viewBox: `0 0 ${W} ${H}`, class: 'er-svg', role: 'img', 'aria-label': `Stacked bars of income in USD per ${period}, ${series.length} ${period}s, highest ${usd(Math.max(...totals))}` });
+
+ for (let i = 0; i <= 4; i++) {
+ const v = (max / 4) * i;
+ const gy = y(v);
+ root.append(svg('line', { x1: m.left, x2: W - m.right, y1: gy, y2: gy, class: i === 0 ? 'er-base' : 'er-grid' }));
+ root.append(svg('text', { x: m.left - 8, y: gy + 4, class: 'er-tick', 'text-anchor': 'end' }, usdShort(v)));
+ }
+
+ const every = Math.ceil(series.length / Math.max(1, Math.floor(iw / 56)));
+ const hits = [];
+ series.forEach((b, i) => {
+ const cx = m.left + slot * i + slot / 2;
+ const x = cx - bw / 2;
+ let acc = 0;
+ const g = svg('g', { class: 'er-bar', tabindex: 0, 'data-i': i, role: 'img', 'aria-label': `${bucketTitle(b.start, period)}: ${usd(totals[i])}` });
+ const parts = stack.filter((k) => b[k] > 0);
+ parts.forEach((k, pi) => {
+ const h = (b[k] / max) * ih;
+ const top = y(acc + b[k]);
+ acc += b[k];
+ const isTop = pi === parts.length - 1;
+ const r = Math.min(4, h);
+ // 2px surface gap between segments; the top segment rounds its data end.
+ const hh = Math.max(0, h - (pi === 0 ? 0 : 2));
+ const yy = pi === 0 ? top : top;
+ const d = isTop && hh > r
+ ? `M${x},${yy + hh} V${yy + r} Q${x},${yy} ${x + r},${yy} H${x + bw - r} Q${x + bw},${yy} ${x + bw},${yy + r} V${yy + hh} Z`
+ : `M${x},${yy} H${x + bw} V${yy + hh} H${x} Z`;
+ g.append(svg('path', { d, fill: `var(--er-s${slotOf(sources, k)})`, class: 'er-seg' }));
+ });
+ if (totals[i] > 0 && slot >= 34) g.append(svg('text', { x: cx, y: y(totals[i]) - 6, class: 'er-total', 'text-anchor': 'middle' }, usdShort(totals[i])));
+ if (i % every === 0) root.append(svg('text', { x: cx, y: H - 10, class: 'er-tick', 'text-anchor': 'middle' }, bucketLabel(b.start, period)));
+ const hit = svg('rect', { x: m.left + slot * i, y: m.top, width: slot, height: ih, class: 'er-hit', 'data-i': i });
+ hits.push({ g, hit, cx });
+ root.append(g, hit);
+ });
+ stage.append(root);
+
+ const show = (i) => {
+ const b = series[i];
+ const rows = stack.filter((k) => b[k] > 0).map((k) => `<li><span class="er-swatch" style="background:var(--er-s${slotOf(sources, k)})" aria-hidden="true"></span><span class="er-tip-k">${esc(label(k))}</span><span class="er-tip-v">${usd(b[k])}</span></li>`).join('');
+ tip.innerHTML = `<strong>${esc(bucketTitle(b.start, period))}</strong><ul>${rows || '<li>No income</li>'}</ul><div class="er-tip-total"><span>Total</span><span>${usd(totals[i])}</span></div>`;
+ tip.hidden = false;
+ const box = stage.getBoundingClientRect();
+ const px = (hits[i].cx / W) * box.width;
+ const flip = px > box.width * 0.6;
+ tip.style.left = `${px}px`;
+ tip.style.transform = flip ? 'translateX(calc(-100% - 14px))' : 'translateX(14px)';
+ tip.style.top = `${stage.offsetTop + 8}px`;
+ hits.forEach((h, j) => h.g.classList.toggle('is-active', j === i));
+ };
+ const hide = () => {
+ tip.hidden = true;
+ hits.forEach((h) => h.g.classList.remove('is-active'));
+ };
+ hits.forEach(({ g, hit }, i) => {
+ hit.addEventListener('pointerenter', () => show(i));
+ hit.addEventListener('pointermove', () => show(i));
+ g.addEventListener('focus', () => show(i));
+ g.addEventListener('blur', hide);
+ });
+ stage.addEventListener('pointerleave', hide);
+
+ tabs.addEventListener('click', (e) => {
+ const b = e.target.closest('[data-view]');
+ if (!b) return;
+ const table = b.dataset.view === 'table';
+ tabs.querySelectorAll('[data-view]').forEach((x) => x.setAttribute('aria-pressed', String(x === b)));
+ stage.hidden = table;
+ tableWrap.hidden = !table;
+ tip.hidden = true;
+ });
+}
+
+function tableHtml(series, stack, label, period) {
+ const head = `<tr><th scope="col">${period === 'month' ? 'Month' : period === 'week' ? 'Week of' : 'Day'}</th>${stack.map((k) => `<th scope="col" class="er-r">${esc(label(k))}</th>`).join('')}<th scope="col" class="er-r">Total</th></tr>`;
+ const body = [...series].reverse().map((b) => {
+ const total = stack.reduce((a, k) => a + (b[k] > 0 ? b[k] : 0), 0);
+ return `<tr><th scope="row">${esc(bucketTitle(b.start, period))}</th>${stack.map((k) => `<td class="er-r">${b[k] > 0 ? usd(b[k]) : '<span class="er-dim">-</span>'}</td>`).join('')}<td class="er-r"><strong>${usd(total)}</strong></td></tr>`;
+ }).join('');
+ return `<table class="er-table"><caption class="ac-sr">Income per ${period} by source, USD</caption><thead>${head}</thead><tbody>${body}</tbody></table>`;
+}
diff --git a/src/earnings-page.js b/src/earnings-page.js
new file mode 100644
index 000000000..cc51fc288
--- /dev/null
+++ b/src/earnings-page.js
@@ -0,0 +1,606 @@
+// Earnings console (pages/earnings.html, route /earnings).
+//
+// The owner's revenue ledger: totals by source and period, the stacked chart,
+// the ledger with a transaction link on every row, CSV and JSON export, the
+// reconcile status, the trailing-window projection, the public-page toggle and
+// the reinvest rules. A rule is only switched on by the explicit confirm step,
+// which shows the exact destinations and amounts and sends the hash the owner
+// reviewed; the server refuses it if anything changed since.
+// API: api/_lib/revenue-routes.js. Doc: docs/revenue-ledger.md.
+
+import './agent-commerce.css';
+import './earnings.css';
+import { apiFetch } from './api.js';
+import { esc, relTime } from './agent-commerce-format.js';
+import { renderEarningsChart, slotOf, usd } from './earnings-chart.js';
+
+const API = '/api/revenue';
+const PAGE = 100;
+const LEGS = [
+ { kind: 'model_credits', label: 'Model credits', hint: 'USDC to the platform deposit wallet, credited to your balance.' },
+ { kind: 'dca_own_coin', label: "DCA into the agent's own coin", hint: 'A SOL buy of the agent\'s own pump.fun coin from its wallet.' },
+ { kind: 'tools_budget', label: 'Tools budget', hint: 'USDC credited, then added to a payment session your agent spends from.' },
+];
+
+const $ = (id) => document.getElementById(id);
+const els = {};
+const state = {
+ agents: [], agentId: '', period: 'month', source: '',
+ view: null, entries: [], nextBefore: null,
+ rules: [], runs: [], sessions: [], editing: null, previews: new Map(),
+ busy: new Set(),
+};
+
+// ── helpers ──────────────────────────────────────────────────────────────────
+
+async function call(path, { method = 'GET', body } = {}) {
+ const headers = { accept: 'application/json' };
+ if (body) headers['content-type'] = 'application/json';
+ let res;
+ try {
+ res = await apiFetch(`${API}${path}`, { method, allowAnonymous: true, headers, body: body ? JSON.stringify(body) : undefined });
+ } catch (err) {
+ if (err?.redirected) return { ok: false, status: 401, data: null, message: 'Your session expired.' };
+ return { ok: false, status: 0, data: null, message: 'Network error. Check your connection and try again.' };
+ }
+ const json = await res.json().catch(() => ({}));
+ const code = json?.error?.code || null;
+ if (res.status === 401 && method !== 'GET') showAuthWall();
+ return {
+ ok: res.ok, status: res.status, code, data: json?.data ?? json,
+ message: json?.error?.message || json?.error_description || (typeof json?.error === 'string' ? json.error : null) || `Request failed (${res.status})`,
+ };
+}
+
+function announce(msg) {
+ els.live.textContent = '';
+ requestAnimationFrame(() => { els.live.textContent = msg; });
+}
+function flash(msg) {
+ els.flash.textContent = msg;
+ els.flash.hidden = false;
+ announce(msg);
+ clearTimeout(flash.t);
+ flash.t = setTimeout(() => { els.flash.hidden = true; }, 6000);
+}
+function showError(msg, retry) {
+ els.error.innerHTML = `<strong>${esc(msg)}</strong>${retry ? '<br><button type="button" class="ac-btn ac-btn-sm" data-retry>Try again</button>' : ''}`;
+ els.error.hidden = false;
+ els.error._retry = retry || null;
+}
+function clearError() { els.error.hidden = true; }
+
+const fmtDate = (iso) => (iso ? new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }) : '');
+const signedUsd = (n) => `${Number(n) < 0 ? '-' : ''}${usd(Math.abs(Number(n)))}`;
+const sourceOf = (key) => state.view?.sources?.find((s) => s.key === key);
+const short = (sig) => (sig ? `${sig.slice(0, 6)}…${sig.slice(-6)}` : '');
+const agentName = (id) => state.agents.find((a) => a.id === id)?.name || 'Unnamed agent';
+
+function showAuthWall() {
+ els.main.hidden = true;
+ els.skel.hidden = true;
+ els.auth.hidden = false;
+ els.login.href = `/login?next=${encodeURIComponent(location.pathname + location.search + location.hash)}`;
+}
+
+function qs(extra = {}) {
+ const p = new URLSearchParams();
+ if (state.agentId) p.set('agent_id', state.agentId);
+ for (const [k, v] of Object.entries(extra)) if (v != null && v !== '') p.set(k, v);
+ const s = p.toString();
+ return s ? `?${s}` : '';
+}
+
+const BASIS_NOTE = {
+ exact: 'Exact: valued from the settled USDC amount.',
+ recorded: 'Recorded: the USD amount stored when the event settled.',
+ sync_price: 'Valued at the SOL price when the ledger first saw the row.',
+ event_price: 'Valued at the price at the event.',
+ unvalued: 'No USD price was available, so this row is listed but not in USD totals.',
+};
+
+// ── ledger ───────────────────────────────────────────────────────────────────
+
+async function loadLedger() {
+ clearError();
+ const res = await call(`/ledger${qs({ period: state.period })}`);
+ if (res.status === 401) return showAuthWall();
+ if (!res.ok) {
+ els.skel.hidden = true;
+ return showError(`Could not load the ledger: ${res.message}`, loadLedger);
+ }
+ state.view = res.data;
+ els.skel.hidden = true;
+ els.main.hidden = false;
+ renderStats();
+ renderChart();
+ renderSources();
+ renderProjection();
+ renderReconcile();
+ renderPublic();
+ fillSourceFilter();
+ await loadEntries(true);
+}
+
+function renderStats() {
+ const { summary, unclaimed_creator_fees: un } = state.view;
+ const pnl = summary.trading_pnl_usd;
+ const tiles = [
+ { k: 'Revenue', v: usd(summary.revenue_usd), s: `${sumCount(summary, true)} income events since the first row` },
+ { k: 'Realised trading PnL', v: `<span class="${pnl < 0 ? 'er-neg' : ''}">${signedUsd(pnl)}</span>`, s: 'Closed positions only. Reported apart from revenue.' },
+ { k: 'Net', v: `<span class="${summary.net_usd < 0 ? 'er-neg' : ''}">${signedUsd(summary.net_usd)}</span>`, s: 'Revenue plus realised PnL.' },
+ ];
+ if (un && Number(un.sol) > 0) {
+ tiles.push({ k: 'Unclaimed creator fees', v: un.usd != null ? usd(un.usd) : `${un.sol} SOL`, s: `${un.sol} SOL waiting to be claimed. Counted once claimed.${un.refreshed_at ? ` Refreshed ${esc(relTime(un.refreshed_at))}.` : ''}` });
+ }
+ let notes = '';
+ if (summary.unvalued_count) notes += `${summary.unvalued_count} ${summary.unvalued_count === 1 ? 'row has' : 'rows have'} no USD price and ${summary.unvalued_count === 1 ? 'is' : 'are'} left out of USD totals. `;
+ if (summary.excluded_count) notes += `${summary.excluded_count} ${summary.excluded_count === 1 ? 'row is' : 'rows are'} excluded (devnet or non-Solana).`;
+ els.stats.innerHTML = tiles.map((t) => `<div class="er-stat"><dt>${esc(t.k)}</dt><dd>${t.v}</dd><small>${t.s}</small></div>`).join('');
+ els.statNote.textContent = notes.trim();
+ els.statNote.hidden = !notes;
+}
+
+function sumCount(summary, revenueOnly) {
+ return Object.entries(summary.by_source).reduce((a, [k, s]) => a + (revenueOnly && sourceOf(k)?.kind !== 'revenue' ? 0 : s.count), 0);
+}
+
+function renderChart() {
+ renderEarningsChart(els.chart, { summary: state.view.summary, sources: state.view.sources });
+}
+
+function renderSources() {
+ const { summary, sources } = state.view;
+ const rows = sources.map((s) => {
+ const v = summary.by_source[s.key];
+ const amount = s.kind === 'pnl' ? signedUsd(v.usd) : usd(v.usd);
+ const sub = v.count ? `${v.count} ${v.count === 1 ? 'event' : 'events'}${v.unvalued ? `, ${v.unvalued} unvalued` : ''}` : 'Nothing yet';
+ return `<li><span class="er-swatch" style="background:var(--er-s${slotOf(sources, s.key)})" aria-hidden="true"></span><span>${esc(s.label)}${s.kind === 'pnl' ? ' <span class="er-chip">not revenue</span>' : ''}</span><span class="er-amt ${s.kind === 'pnl' && v.usd < 0 ? 'er-neg' : ''}">${amount}</span><span class="er-sub">${esc(sub)}</span></li>`;
+ });
+ els.sources.innerHTML = rows.join('');
+}
+
+function renderProjection() {
+ const p = state.view.projection;
+ if (!p.available) {
+ els.proj.innerHTML = `<p class="ac-hint">No projection yet. ${esc(p.reason)}</p><p class="ac-hint">Projections use only real trailing history, never a guess.</p>`;
+ return;
+ }
+ els.proj.innerHTML = `
+ <p class="er-stat" style="padding:0;border:0;background:none"><span class="ac-num" style="font-size:var(--text-xl);color:var(--ink-bright)">${usd(p.projected_usd)}</span></p>
+ <p class="ac-hint">Expected over the next ${p.horizon_days} days. ${esc(p.method)}</p>
+ <p class="ac-hint">Window: ${esc(fmtDate(p.window_start))} to ${esc(fmtDate(p.window_end))}, ${p.entries_in_window} income ${p.entries_in_window === 1 ? 'event' : 'events'}, ${usd(p.per_day_usd)} per day. A projection, not income.</p>`;
+}
+
+function renderReconcile() {
+ const { reconcile: r, chain_verification: c, synced_at } = state.view;
+ const bits = [];
+ if (!r) {
+ bits.push('<p class="ac-hint">The first reconcile has not run yet. It runs hourly and compares every source table against this ledger and samples transactions on-chain.</p>');
+ } else {
+ const chip = r.status === 'clean' ? '<span class="er-chip er-chip-ok">Clean</span>' : r.status === 'drift' ? '<span class="er-chip er-chip-bad">Drift found</span>' : '<span class="er-chip er-chip-dim">Error</span>';
+ bits.push(`<p>${chip} <span class="ac-hint">Last run ${esc(relTime(r.started_at))}, ${r.entries_total} entries.</span></p>`);
+ const drifted = (r.db_checks || []).filter((x) => x.drift);
+ if (drifted.length) bits.push(`<ul class="ac-hint">${drifted.map((d) => `<li>${esc(d.label)}: source has ${d.source_count}, ledger has ${d.ledger_count}.</li>`).join('')}</ul>`);
+ }
+ bits.push(`<p class="ac-hint">Transactions: ${c.verified} verified on-chain${c.issues ? `, <strong class="er-neg">${c.issues} need a look</strong>` : ''}${c.unchecked ? `, ${c.unchecked} not yet checked` : ''}.</p>`);
+ if (synced_at) bits.push(`<p class="ac-hint">Ledger synced ${esc(relTime(synced_at))}.</p>`);
+ els.rec.innerHTML = bits.join('');
+}
+
+function renderPublic() {
+ els.pubPanel.hidden = !state.agentId;
+ if (!state.agentId) return;
+ const link = `${location.origin}/agents/${state.agentId}/earnings`;
+ els.pubLink.hidden = !els.pub.checked;
+ els.pubLink.innerHTML = els.pub.checked ? `Live at <a href="${esc(link)}" target="_blank" rel="noopener">${esc(link)}</a>` : '';
+}
+
+async function loadPublicSetting() {
+ if (!state.agentId) return;
+ const res = await call(`/agents/${state.agentId}/settings`);
+ els.pub.checked = Boolean(res.ok && res.data?.public_earnings);
+ els.pubLabel.textContent = els.pub.checked ? 'Public' : 'Private';
+ renderPublic();
+}
+
+function fillSourceFilter() {
+ if (els.srcFilter.options.length > 1) return;
+ for (const s of state.view.sources) els.srcFilter.append(new Option(s.label, s.key));
+}
+
+async function loadEntries(reset) {
+ if (reset) {
+ state.entries = [];
+ state.nextBefore = null;
+ els.ledger.innerHTML = '<div class="er-skel"></div>';
+ }
+ const res = await call(`/entries${qs({ limit: PAGE, source: state.source, before: reset ? '' : state.nextBefore })}`);
+ if (!res.ok) {
+ els.ledger.innerHTML = '';
+ return showError(`Could not load ledger rows: ${res.message}`, () => loadEntries(true));
+ }
+ state.entries.push(...res.data.entries);
+ state.nextBefore = res.data.next_before;
+ renderLedger();
+}
+
+function renderLedger() {
+ if (!state.entries.length) {
+ els.ledger.innerHTML = `<div class="ac-empty"><h3>${state.source ? 'No rows for this source' : 'No income recorded yet'}</h3><p>${state.source ? 'Pick another source, or clear the filter.' : 'Creator fees, skill sales, hires, royalties, invoices and closed trades appear here as they happen. Press Sync now to pull in anything new, or <a href="/commerce">send an invoice</a> from one of your agents.'}</p></div>`;
+ els.more.hidden = true;
+ return;
+ }
+ const showAgent = !state.agentId && state.agents.length > 1;
+ const rows = state.entries.map((e) => {
+ const src = sourceOf(e.source);
+ const usdCell = e.usd == null ? '<span class="er-dim" title="No USD price was available">unvalued</span>' : `<span class="${e.usd < 0 ? 'er-neg' : ''}" title="${esc(BASIS_NOTE[e.usd_basis] || '')}">${signedUsd(e.usd)}</span>`;
+ const tx = e.explorer_url
+ ? `<a href="${esc(e.explorer_url)}" target="_blank" rel="noopener" class="ac-mono">${esc(short(e.tx_signature))}</a>`
+ : '<span class="er-dim">no transaction</span>';
+ const chain = e.chain_status === 'verified' ? '<span class="er-chip er-chip-ok" title="Found on-chain">verified</span>' : e.chain_status === 'mismatch' || e.chain_status === 'not_found' ? `<span class="er-chip er-chip-bad" title="${esc(e.chain_detail || '')}">check</span>` : '';
+ const net = e.network !== 'mainnet' || e.chain !== 'solana' ? `<span class="er-chip" title="${esc(e.exclusion_reason || '')}">${esc(e.chain === 'solana' ? e.network : e.chain)}</span>` : '';
+ return `<tr class="${e.counted ? '' : 'is-excluded'}">
+ <td>${esc(fmtDate(e.occurred_at))}</td>
+ <td><span class="er-swatch" style="background:var(--er-s${slotOf(state.view.sources, e.source)})" aria-hidden="true"></span> ${esc(src?.label || e.source)} ${net}</td>
+ ${showAgent ? `<td>${esc(e.agent_id ? agentName(e.agent_id) : 'Account')}</td>` : ''}
+ <td class="er-label">${esc(e.label || '')}</td>
+ <td class="er-r">${esc(e.amount)} ${esc(e.asset)}</td>
+ <td class="er-r">${usdCell}</td>
+ <td>${tx} ${chain}</td>
+ </tr>`;
+ }).join('');
+ els.ledger.innerHTML = `<table><caption class="ac-sr">Revenue ledger</caption><thead><tr><th scope="col">When</th><th scope="col">Source</th>${showAgent ? '<th scope="col">Agent</th>' : ''}<th scope="col">Detail</th><th scope="col" class="er-r">Amount</th><th scope="col" class="er-r">USD</th><th scope="col">Transaction</th></tr></thead><tbody>${rows}</tbody></table>`;
+ els.more.hidden = !state.nextBefore;
+}
+
+// ── drawer ───────────────────────────────────────────────────────────────────
+
+let drawerReturn = null;
+function openDrawer() {
+ const v = state.view;
+ const sources = v?.sources || [];
+ els.drawer.innerHTML = `
+ <button type="button" class="ac-btn ac-btn-sm er-drawer-close" data-close>Close</button>
+ <h2 class="ac-h2" id="er-drawer-h">How this is calculated</h2>
+ <p class="ac-hint">The ledger is a copy of income events from the tables that own them. The source tables stay the record, and an hourly job proves the two still match.</p>
+ <dl>${sources.map((s) => `<dt><span class="er-swatch" style="background:var(--er-s${slotOf(sources, s.key)})" aria-hidden="true"></span>${esc(s.label)}</dt><dd>${esc(s.how)}</dd>`).join('')}</dl>
+ <h3 class="ac-section-title" style="margin-top:20px">Valuation</h3>
+ <ul>
+ <li>USD comes from the settled amount (USDC is $1), the amount stored when the event settled, or, for SOL, the SOL price when the ledger first saw the row. The price used is never changed afterwards, so history does not move.</li>
+ <li>A row with no price is listed and counted as an event but kept out of USD totals, and the page says how many.</li>
+ </ul>
+ <h3 class="ac-section-title" style="margin-top:20px">Not included</h3>
+ <ul>${(v?.not_included || []).map((x) => `<li>${esc(x)}</li>`).join('')}</ul>
+ <h3 class="ac-section-title" style="margin-top:20px">Reconciliation</h3>
+ <ul>
+ <li>Every hour each source table is re-summed against the ledger. Any difference is flagged and you are notified once per distinct drift.</li>
+ <li>A sample of mainnet transactions is looked up on-chain. A signature that is missing or failed is flagged. Signatures older than the RPC history window cannot be judged and are marked skipped.</li>
+ </ul>
+ <h3 class="ac-section-title" style="margin-top:20px">Projection</h3>
+ <ul><li>Trailing real revenue divided by the days it covers, held flat for 30 days. It needs 7 days of history and 3 income events, and says so when it does not have them. No growth is assumed.</li></ul>`;
+ drawerReturn = document.activeElement;
+ els.backdrop.hidden = false;
+ els.drawer.hidden = false;
+ els.drawer.querySelector('[data-close]').focus();
+}
+function closeDrawer() {
+ els.drawer.hidden = true;
+ els.backdrop.hidden = true;
+ drawerReturn?.focus?.();
+}
+
+// ── reinvest rules ───────────────────────────────────────────────────────────
+
+async function loadRules() {
+ const [r, runs] = await Promise.all([call(`/rules${qs()}`), call(`/runs${qs({ limit: 40 })}`)]);
+ if (!r.ok) {
+ els.rules.innerHTML = '';
+ return showError(`Could not load reinvest rules: ${r.message}`, loadRules);
+ }
+ state.rules = r.data.rules || [];
+ state.runs = runs.ok ? runs.data.runs || [] : [];
+ renderRules();
+}
+
+const STATUS_CHIP = { draft: ['Needs confirmation', 'er-chip'], active: ['Active', 'er-chip er-chip-ok'], paused: ['Paused', 'er-chip er-chip-dim'] };
+const RUN_STATUS = { completed: 'Completed', partial: 'Partly done', awaiting_approval: 'Waiting for your approval', skipped: 'Skipped', failed: 'Failed', running: 'Running' };
+
+function legSummary(rule) {
+ return rule.legs.map((l) => `${l.pct}% ${LEGS.find((x) => x.kind === l.kind)?.label || l.kind}`).join(', ');
+}
+
+function renderRules() {
+ if (!state.rules.length) {
+ els.rules.innerHTML = `<div class="ac-empty"><h3>No reinvest rules yet</h3><p>Decide once what happens to your agent's income: for example 20% to model credits, 20% into its own coin, 10% to a tools budget, and keep the rest. Nothing moves until you confirm the exact terms.</p></div>`;
+ return;
+ }
+ els.rules.innerHTML = state.rules.map((r) => {
+ const [label, cls] = STATUS_CHIP[r.status] || [r.status, 'er-chip'];
+ const keep = Math.max(0, 100 - r.legs.reduce((a, l) => a + Number(l.pct), 0));
+ const runs = state.runs.filter((x) => x.rule_id === r.id).slice(0, 5);
+ const preview = state.previews.get(r.id);
+ const busy = state.busy.has(r.id);
+ return `<article class="ac-card er-rule" data-rule="${esc(r.id)}">
+ <div class="er-rule-head">
+ <div><strong>${esc(r.name)}</strong> <span class="${cls}">${esc(label)}</span> ${r.network === 'devnet' ? '<span class="ac-badge-devnet">devnet</span>' : ''}</div>
+ <div class="ac-row-actions">
+ <button type="button" class="ac-btn ac-btn-sm ${r.confirmed ? '' : 'ac-btn-primary'}" data-act="review" ${busy ? 'disabled' : ''}>${r.confirmed ? 'View terms' : 'Review and confirm'}</button>
+ <button type="button" class="ac-btn ac-btn-sm" data-act="test" ${busy ? 'disabled' : ''}>Test run</button>
+ ${r.status === 'active' ? `<button type="button" class="ac-btn ac-btn-sm" data-act="pause" ${busy ? 'disabled' : ''}>Pause</button>` : ''}
+ <button type="button" class="ac-btn ac-btn-sm" data-act="edit" ${busy ? 'disabled' : ''}>Edit</button>
+ <button type="button" class="ac-btn ac-btn-sm ac-btn-danger" data-act="delete" ${busy ? 'disabled' : ''}>Delete</button>
+ </div>
+ </div>
+ <p class="ac-hint" style="margin:0">${esc(agentName(r.agent_id))}: each ${esc(r.period === 'daily' ? 'day' : r.period === 'weekly' ? 'week' : 'month')}, ${esc(legSummary(r))}${keep ? `, keep ${keep}%` : ''}. Caps: ${usd(r.per_run_cap_usd)} per run, ${usd(r.lifetime_cap_usd)} lifetime, skip runs under ${usd(r.min_run_usd)}. Basis: ${r.basis === 'revenue' ? 'revenue only' : 'revenue plus realised trading profit'}.</p>
+ ${r.paused_reason ? `<div class="ac-notice ac-notice-warn" style="margin:0">${esc(r.paused_reason)}</div>` : ''}
+ <div data-slot="preview">${preview ? previewHtml(r, preview) : ''}</div>
+ <div data-slot="msg" class="ac-form-msg" role="status"></div>
+ ${runs.length ? `<div class="er-runs"><strong class="ac-hint">Recent runs</strong>${runs.map(runHtml).join('')}</div>` : '<p class="ac-hint" style="margin:0">No runs yet. A rule runs once per complete period after you confirm it.</p>'}
+ </article>`;
+ }).join('');
+}
+
+function runHtml(run) {
+ const legs = (run.legs || []).map((l) => {
+ const st = l.status === 'executed' ? 'sent' : l.status === 'awaiting_approval' ? 'waiting for your approval' : l.status;
+ const tx = l.signature ? ` <a href="https://solscan.io/tx/${esc(l.signature)}${run.rule_snapshot?.network === 'devnet' ? '?cluster=devnet' : ''}" target="_blank" rel="noopener">${esc(short(l.signature))}</a>` : '';
+ return `<li>${esc(l.kind.replace(/_/g, ' '))}: ${usd(l.capped_usd)} ${esc(st)}${tx}${l.error ? ` (${esc(l.error)})` : ''}</li>`;
+ }).join('');
+ return `<div class="er-run"><div><strong>${esc(RUN_STATUS[run.status] || run.status)}</strong> ${run.mode === 'preview' ? '<span class="er-chip">test</span>' : ''} <span class="ac-hint">${esc(fmtDate(run.period_start))} to ${esc(fmtDate(run.period_end))}. Income ${usd(run.base_usd)}, sent ${usd(run.executed_usd)}, kept ${usd(run.kept_usd)}.</span></div>${run.note ? `<div class="ac-hint">${esc(run.note)}</div>` : ''}${run.error ? `<div class="ac-hint er-neg">${esc(run.error)}</div>` : ''}${legs ? `<ul>${legs}</ul>` : ''}</div>`;
+}
+
+function previewHtml(rule, p) {
+ const rows = p.confirmation.map((c) => `<tr>
+ <td>${esc(c.label)}<br><span class="ac-hint">${c.pct}%</span></td>
+ <td>${esc(c.asset)} on Solana ${esc(c.network)}</td>
+ <td>${c.recipient ? `<span class="ac-mono">${esc(c.recipient)}</span>` : '<span class="er-neg">Not available</span>'}<br><span class="ac-hint">${esc(c.recipient_label)}</span></td>
+ <td class="er-r ac-num">${usd(c.would_send_usd)}</td>
+ </tr>`).join('');
+ const ready = p.confirmation.every((c) => c.ready);
+ const skip = p.plan.skip ? `<p class="ac-hint">With last period's income this rule would send nothing: ${esc(p.plan.skip)}</p>` : '';
+ return `<div class="ac-card" style="margin:0">
+ <h3 class="ac-section-title" style="margin-top:0">${rule.confirmed ? 'Confirmed terms' : 'Confirm these exact terms'}</h3>
+ <div class="er-ledger"><table class="er-confirm"><thead><tr><th scope="col">Leg</th><th scope="col">Asset and chain</th><th scope="col">Recipient</th><th scope="col" class="er-r">Would send (last period)</th></tr></thead><tbody>${rows}</tbody></table></div>
+ <p class="ac-hint">Last period (${esc(fmtDate(p.period.start))} to ${esc(fmtDate(p.period.end))}) income was ${usd(p.base_usd)}; ${usd(p.plan.executable_usd)} would be reinvested and ${usd(p.plan.kept_usd)} kept. ${p.plan.scaled ? 'The caps scaled the legs down. ' : ''}Lifetime reinvested so far: ${usd(p.lifetime_spent_usd)}.</p>
+ ${skip}
+ <p class="ac-hint">${esc(p.note)}</p>
+ ${rule.confirmed ? '' : `<div class="ac-form-foot"><button type="button" class="ac-btn ac-btn-primary" data-act="confirm" ${ready ? '' : 'disabled'}>I confirm: run this rule every period</button>${ready ? '' : '<span class="ac-hint">A destination above is not available yet, so this cannot be confirmed.</span>'}</div>`}
+ </div>`;
+}
+
+function ruleMsg(card, msg, bad) {
+ const slot = card.querySelector('[data-slot="msg"]');
+ slot.textContent = msg;
+ slot.style.color = bad ? 'var(--danger)' : '';
+ announce(msg);
+}
+
+async function ruleAction(card, act) {
+ const id = card.dataset.rule;
+ const rule = state.rules.find((r) => r.id === id);
+ if (!rule || state.busy.has(id)) return;
+ if (act === 'edit') return openRuleForm(rule);
+ if (act === 'delete' && !confirm(`Delete "${rule.name}"? Its run history is deleted with it.`)) return;
+ state.busy.add(id);
+ card.querySelectorAll('button').forEach((b) => { b.disabled = true; });
+ try {
+ if (act === 'review') {
+ const res = await call(`/rules/${id}/preview`);
+ if (!res.ok) return ruleMsg(card, res.message, true);
+ state.previews.set(id, res.data);
+ card.querySelector('[data-slot="preview"]').innerHTML = previewHtml(rule, res.data);
+ } else if (act === 'confirm') {
+ const p = state.previews.get(id);
+ const res = await call(`/rules/${id}/confirm`, { method: 'POST', body: { hash: p?.rule?.hash || rule.hash } });
+ if (!res.ok) {
+ if (res.code === 'rule_changed') state.previews.delete(id);
+ return ruleMsg(card, res.code === 'rule_changed' ? 'This rule changed since you opened it. Review the new terms and confirm again.' : res.message, true);
+ }
+ state.previews.delete(id);
+ flash(`"${rule.name}" is active. It runs after each complete period.`);
+ await loadRules();
+ return;
+ } else if (act === 'pause') {
+ const res = await call(`/rules/${id}/pause`, { method: 'POST', body: {} });
+ if (!res.ok) return ruleMsg(card, res.message, true);
+ flash(`"${rule.name}" is paused.`);
+ await loadRules();
+ return;
+ } else if (act === 'test') {
+ const res = await call(`/rules/${id}/test-run`, { method: 'POST', body: {} });
+ if (!res.ok) return ruleMsg(card, res.message, true);
+ const d = res.data;
+ flash(d.skipped ? `Test run skipped: ${d.reason || 'nothing to do'}` : `Test run done: ${usd(d.run?.executed_usd)} of ${usd(d.run?.planned_usd)} planned. Nothing was sent.`);
+ await loadRules();
+ return;
+ } else if (act === 'delete') {
+ const res = await call(`/rules/${id}`, { method: 'DELETE' });
+ if (!res.ok) return ruleMsg(card, res.message, true);
+ flash(`Deleted "${rule.name}".`);
+ await loadRules();
+ return;
+ }
+ } finally {
+ state.busy.delete(id);
+ card.querySelectorAll('button').forEach((b) => { b.disabled = false; });
+ }
+}
+
+function openRuleForm(rule = null) {
+ state.editing = rule?.id || null;
+ const f = els.ruleForm;
+ const agentId = rule?.agent_id || state.agentId || state.agents[0]?.id || '';
+ const legOf = (k) => rule?.legs.find((l) => l.kind === k);
+ const sessions = state.sessions;
+ f.innerHTML = `
+ <h3 class="ac-section-title" style="margin:0">${rule ? 'Edit rule' : 'New reinvest rule'}</h3>
+ ${rule?.confirmed ? '<div class="ac-notice ac-notice-warn" style="margin:0">Saving a change switches this rule off until you confirm the new terms.</div>' : ''}
+ <div class="ac-field"><label for="rf-name">Name</label><input id="rf-name" name="name" maxlength="80" value="${esc(rule?.name || 'Weekly reinvest')}" required /></div>
+ <div class="ac-field"><label for="rf-agent">Agent</label><select id="rf-agent" name="agent_id" ${rule ? 'disabled' : ''}>${state.agents.map((a) => `<option value="${esc(a.id)}" ${a.id === agentId ? 'selected' : ''}>${esc(a.name || 'Unnamed agent')}</option>`).join('')}</select><small>Funds move from this agent's Solana wallet.</small></div>
+ <div class="ac-inline">
+ <div class="ac-field"><label for="rf-period">Runs</label><select id="rf-period" name="period">${['daily', 'weekly', 'monthly'].map((p) => `<option value="${p}" ${(rule?.period || 'weekly') === p ? 'selected' : ''}>${p[0].toUpperCase() + p.slice(1)}</option>`).join('')}</select></div>
+ <div class="ac-field"><label for="rf-network">Network</label><select id="rf-network" name="network"><option value="mainnet" ${rule?.network !== 'devnet' ? 'selected' : ''}>Mainnet</option><option value="devnet" ${rule?.network === 'devnet' ? 'selected' : ''}>Devnet (no real funds)</option></select></div>
+ <div class="ac-field"><label for="rf-basis">Income counted</label><select id="rf-basis" name="basis"><option value="revenue" ${rule?.basis !== 'revenue_and_trading_profit' ? 'selected' : ''}>Revenue only</option><option value="revenue_and_trading_profit" ${rule?.basis === 'revenue_and_trading_profit' ? 'selected' : ''}>Revenue plus trading profit</option></select></div>
+ </div>
+ <fieldset class="ac-field" style="border:0;padding:0;margin:0"><span class="lbl">Where each period's income goes (percent)</span>
+ <div class="er-legs">${LEGS.map((l) => `
+ <div class="er-leg" data-leg="${l.kind}">
+ <div class="ac-field"><label for="rf-pct-${l.kind}">${esc(l.label)}</label><small>${esc(l.hint)}</small>
+ ${l.kind === 'tools_budget' ? `<select id="rf-session" aria-label="Payment session to top up" ${sessions.length ? '' : 'disabled'}>${sessions.length ? sessions.map((s) => `<option value="${esc(s.id)}" ${legOf('tools_budget')?.session_id === s.id ? 'selected' : ''}>${esc(s.label)} (${usd(s.budget_usd - s.spent_usd)} left)</option>`).join('') : '<option value="">No active payment session</option>'}</select>` : ''}
+ </div>
+ <div class="ac-field"><input id="rf-pct-${l.kind}" inputmode="decimal" autocomplete="off" placeholder="0" value="${legOf(l.kind)?.pct ?? ''}" aria-label="${esc(l.label)} percent" /></div>
+ <span class="ac-hint" aria-hidden="true">%</span>
+ </div>`).join('')}</div>
+ <small id="rf-keep">Keep: 100%</small>
+ </fieldset>
+ <div class="ac-inline">
+ <div class="ac-field"><label for="rf-per">Cap per run (USD)</label><input id="rf-per" name="per_run_cap_usd" inputmode="decimal" value="${rule?.per_run_cap_usd ?? '25'}" required /></div>
+ <div class="ac-field"><label for="rf-life">Lifetime cap (USD)</label><input id="rf-life" name="lifetime_cap_usd" inputmode="decimal" value="${rule?.lifetime_cap_usd ?? '250'}" required /></div>
+ <div class="ac-field"><label for="rf-min">Skip runs under (USD)</label><input id="rf-min" name="min_run_usd" inputmode="decimal" value="${rule?.min_run_usd ?? '1'}" /></div>
+ </div>
+ <div class="ac-form-foot"><button type="submit" class="ac-btn ac-btn-primary">${rule ? 'Save changes' : 'Create rule'}</button><button type="button" class="ac-btn" data-cancel>Cancel</button><span class="ac-form-msg" id="rf-msg" role="alert"></span></div>`;
+ f.hidden = false;
+ updateKeep();
+ f.querySelector('#rf-name').focus();
+}
+
+function updateKeep() {
+ const total = LEGS.reduce((a, l) => a + (Number($(`rf-pct-${l.kind}`)?.value) || 0), 0);
+ const keep = $('rf-keep');
+ keep.textContent = total > 100 ? `Over by ${Math.round((total - 100) * 100) / 100}%. The legs must add up to 100% or less.` : `Keep: ${Math.round((100 - total) * 100) / 100}%`;
+ keep.style.color = total > 100 ? 'var(--danger)' : '';
+}
+
+async function submitRule(e) {
+ e.preventDefault();
+ const f = els.ruleForm;
+ const msg = $('rf-msg');
+ msg.textContent = '';
+ const legs = LEGS.map((l) => ({ kind: l.kind, pct: Number($(`rf-pct-${l.kind}`).value) })).filter((l) => l.pct > 0);
+ const tools = legs.find((l) => l.kind === 'tools_budget');
+ if (tools) tools.session_id = $('rf-session')?.value || '';
+ const body = {
+ name: $('rf-name').value, period: $('rf-period').value, network: $('rf-network').value, basis: $('rf-basis').value, legs,
+ per_run_cap_usd: Number($('rf-per').value), lifetime_cap_usd: Number($('rf-life').value), min_run_usd: Number($('rf-min').value || 0),
+ };
+ const btn = f.querySelector('[type="submit"]');
+ btn.disabled = true;
+ const res = state.editing
+ ? await call(`/rules/${state.editing}`, { method: 'PATCH', body })
+ : await call('/rules', { method: 'POST', body: { ...body, agent_id: $('rf-agent').value } });
+ btn.disabled = false;
+ if (!res.ok) {
+ msg.textContent = res.message;
+ return;
+ }
+ f.hidden = true;
+ state.previews.clear();
+ flash(state.editing ? 'Rule saved. Review and confirm the new terms to switch it on.' : 'Rule created. Review and confirm its terms to switch it on.');
+ await loadRules();
+}
+
+// ── boot ─────────────────────────────────────────────────────────────────────
+
+function bind() {
+ els.agent.addEventListener('change', async () => {
+ state.agentId = els.agent.value;
+ syncExportLinks();
+ history.replaceState(null, '', `${location.pathname}${state.agentId ? `?agent=${state.agentId}` : ''}${location.hash}`);
+ await Promise.all([loadLedger(), loadPublicSetting(), loadRules()]);
+ });
+ els.period.addEventListener('change', async () => {
+ state.period = els.period.value;
+ await loadLedger();
+ });
+ els.srcFilter.addEventListener('change', async () => {
+ state.source = els.srcFilter.value;
+ syncExportLinks();
+ await loadEntries(true);
+ });
+ els.moreBtn.addEventListener('click', () => loadEntries(false));
+ els.how.addEventListener('click', openDrawer);
+ els.backdrop.addEventListener('click', closeDrawer);
+ els.drawer.addEventListener('click', (e) => { if (e.target.closest('[data-close]')) closeDrawer(); });
+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !els.drawer.hidden) closeDrawer(); });
+ els.error.addEventListener('click', (e) => { if (e.target.closest('[data-retry]')) els.error._retry?.(); });
+
+ els.sync.addEventListener('click', async () => {
+ els.sync.disabled = true;
+ els.sync.textContent = 'Syncing…';
+ const res = await call('/sync', { method: 'POST', body: { agent_id: state.agentId || undefined } });
+ els.sync.disabled = false;
+ els.sync.textContent = 'Sync now';
+ if (!res.ok) return showError(`Sync failed: ${res.message}`, null);
+ flash('Ledger is up to date.');
+ await loadLedger();
+ });
+
+ els.pub.addEventListener('change', async () => {
+ const want = els.pub.checked;
+ els.pub.disabled = true;
+ const res = await call(`/agents/${state.agentId}/settings`, { method: 'PUT', body: { public_earnings: want } });
+ els.pub.disabled = false;
+ if (!res.ok) {
+ els.pub.checked = !want;
+ return showError(`Could not change the public page: ${res.message}`, null);
+ }
+ els.pubLabel.textContent = want ? 'Public' : 'Private';
+ renderPublic();
+ flash(want ? 'Your earnings page is public.' : 'Your earnings page is private again.');
+ });
+
+ els.ruleNew.addEventListener('click', () => openRuleForm());
+ els.ruleForm.addEventListener('submit', submitRule);
+ els.ruleForm.addEventListener('input', (e) => { if (e.target.id?.startsWith('rf-pct-')) updateKeep(); });
+ els.ruleForm.addEventListener('click', (e) => { if (e.target.closest('[data-cancel]')) els.ruleForm.hidden = true; });
+ els.rules.addEventListener('click', (e) => {
+ const b = e.target.closest('[data-act]');
+ const card = e.target.closest('[data-rule]');
+ if (b && card) ruleAction(card, b.dataset.act);
+ });
+}
+
+function syncExportLinks() {
+ els.csv.href = `${API}/export${qs({ format: 'csv', source: state.source })}`;
+ els.json.href = `${API}/export${qs({ format: 'json', source: state.source })}`;
+}
+
+async function boot() {
+ Object.assign(els, {
+ main: $('er-main'), auth: $('er-auth'), login: $('er-login'), skel: $('er-skel'), error: $('er-error'), flash: $('er-flash'), live: $('er-live'),
+ agent: $('er-agent'), period: $('er-period'), sync: $('er-sync'), csv: $('er-csv'), json: $('er-json'), how: $('er-how'),
+ stats: $('er-stats'), chart: $('er-chart'), sources: $('er-sources'), proj: $('er-proj'), rec: $('er-rec'),
+ pubPanel: $('er-pub-panel'), pub: $('er-pub'), pubLabel: $('er-pub-label'), pubLink: $('er-pub-link'),
+ ledger: $('er-ledger'), more: $('er-more'), moreBtn: $('er-more-btn'), srcFilter: $('er-src-filter'),
+ rules: $('er-rules'), ruleForm: $('er-rule-form'), ruleNew: $('er-rule-new'),
+ drawer: $('er-drawer'), backdrop: $('er-backdrop'),
+ });
+ els.statNote = document.createElement('p');
+ els.statNote.className = 'ac-hint';
+ els.statNote.hidden = true;
+ els.stats.after(els.statNote);
+ bind();
+
+ const agents = await apiFetch('/api/agents', { allowAnonymous: true, headers: { accept: 'application/json' } }).catch(() => null);
+ if (!agents) return showError('Network error. Check your connection and try again.', boot);
+ if (agents.status === 401) return showAuthWall();
+ const json = await agents.json().catch(() => ({}));
+ if (!agents.ok) return showError(`Could not load your agents: ${json?.error?.message || agents.status}`, boot);
+ state.agents = (json?.data ?? json)?.agents || [];
+ els.agent.innerHTML = `<option value="">All agents</option>${state.agents.map((a) => `<option value="${esc(a.id)}">${esc(a.name || 'Unnamed agent')}</option>`).join('')}`;
+ const want = new URLSearchParams(location.search).get('agent');
+ if (want && state.agents.some((a) => a.id === want)) {
+ state.agentId = want;
+ els.agent.value = want;
+ }
+ syncExportLinks();
+
+ const sess = await call('/sessions');
+ state.sessions = sess.ok ? sess.data.sessions || [] : [];
+
+ await Promise.all([loadLedger(), loadPublicSetting(), loadRules()]);
+ if (location.hash === '#rules') $('rules').scrollIntoView();
+}
+
+boot();
diff --git a/src/earnings.css b/src/earnings.css
new file mode 100644
index 000000000..b45e6eab3
--- /dev/null
+++ b/src/earnings.css
@@ -0,0 +1,142 @@
+/* Earnings ledger pages: owner console (/earnings) and the public per-agent
+ page (/agents/:id/earnings). Layout classes come from agent-commerce.css;
+ this file adds the chart tokens and the ledger-specific pieces. The six
+ source colours are the dataviz reference palette (validated light and dark
+ with validate_palette.js; slots 4-5 sit under 3:1 on the light surface, so
+ every mark has a legend, a total label and a table view). */
+
+.er-chart, .er-legend, .er-tip {
+ --er-surface: #fcfcfb;
+ --er-s1: #2a78d6; --er-s2: #eb6834; --er-s3: #1baf7a; --er-s4: #eda100; --er-s5: #e87ba4; --er-s6: #008300;
+ --er-grid: color-mix(in srgb, var(--ink-dim) 22%, transparent);
+ --er-base: color-mix(in srgb, var(--ink-dim) 55%, transparent);
+}
+@media (prefers-color-scheme: dark) {
+ :root:not([data-theme="light"]) .er-chart, :root:not([data-theme="light"]) .er-legend, :root:not([data-theme="light"]) .er-tip {
+ --er-surface: #1a1a19;
+ --er-s1: #3987e5; --er-s2: #d95926; --er-s3: #199e70; --er-s4: #c98500; --er-s5: #d55181; --er-s6: #008300;
+ }
+}
+:root[data-theme="dark"] .er-chart, :root[data-theme="dark"] .er-legend, :root[data-theme="dark"] .er-tip {
+ --er-surface: #1a1a19;
+ --er-s1: #3987e5; --er-s2: #d95926; --er-s3: #199e70; --er-s4: #c98500; --er-s5: #d55181; --er-s6: #008300;
+}
+
+.er-controls { display: flex; flex-wrap: wrap; gap: var(--space-sm); align-items: flex-end; margin-bottom: var(--space-md); }
+.er-controls .ac-field { margin: 0; min-width: 160px; }
+.er-controls .er-spacer { flex: 1; }
+.er-actions { display: flex; flex-wrap: wrap; gap: 8px; }
+
+.er-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: var(--space-sm); margin: 0 0 var(--space-md); }
+.er-stat { background: var(--surface-2); border: 1px solid var(--stroke-strong); border-radius: var(--radius-card, 12px); padding: 14px 16px; }
+.er-stat dt { font-size: var(--text-xs); color: var(--ink-dim); margin: 0 0 6px; }
+.er-stat dd { margin: 0; font-size: var(--text-xl); color: var(--ink-bright); font-variant-numeric: tabular-nums; line-height: 1.1; }
+.er-stat small { display: block; margin-top: 6px; font-size: var(--text-xs); color: var(--ink-dim); line-height: 1.4; }
+.er-neg { color: var(--danger); }
+
+.er-panel { background: var(--surface-2); border: 1px solid var(--stroke-strong); border-radius: var(--radius-card, 12px); padding: 16px; margin-bottom: var(--space-md); }
+.er-panel h2 { margin: 0 0 4px; }
+.er-panel > .ac-hint:first-of-type { margin-bottom: 12px; }
+
+.er-chart-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
+.er-legend { display: flex; flex-wrap: wrap; gap: 6px 16px; list-style: none; margin: 0; padding: 0; font-size: var(--text-xs); color: var(--ink); }
+.er-legend li { display: inline-flex; align-items: center; gap: 6px; }
+.er-swatch { width: 10px; height: 10px; border-radius: 2px; flex: none; display: inline-block; }
+.er-viewtoggle { display: inline-flex; gap: 6px; }
+.er-viewtoggle [aria-pressed="true"] { background: var(--surface-3); border-color: var(--ink-dim); }
+.er-stage { position: relative; }
+.er-svg { width: 100%; height: auto; display: block; overflow: visible; }
+.er-grid { stroke: var(--er-grid); stroke-width: 1; }
+.er-base { stroke: var(--er-base); stroke-width: 1; }
+.er-tick { fill: var(--ink-dim); font-size: 11px; font-variant-numeric: tabular-nums; }
+.er-total { fill: var(--ink); font-size: 11px; font-weight: 600; font-variant-numeric: tabular-nums; }
+.er-bar { outline: none; }
+.er-bar .er-seg { transition: opacity var(--duration-fast, .15s); }
+.er-svg:has(.er-bar.is-active) .er-bar:not(.is-active) .er-seg { opacity: .55; }
+.er-bar:focus-visible .er-seg { stroke: var(--focus-ring-color, #3b82f6); stroke-width: 2; }
+.er-hit { fill: transparent; cursor: crosshair; }
+.er-tip {
+ position: absolute; z-index: 2; min-width: 190px; max-width: 280px; pointer-events: none;
+ background: var(--surface-1, var(--er-surface)); color: var(--ink);
+ border: 1px solid var(--stroke-strong); border-radius: 10px; padding: 10px 12px;
+ box-shadow: 0 6px 24px rgb(0 0 0 / .25); font-size: var(--text-xs);
+}
+.er-tip strong { display: block; color: var(--ink-bright); margin-bottom: 6px; }
+.er-tip ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; }
+.er-tip li { display: flex; align-items: center; gap: 6px; }
+.er-tip-k { flex: 1; }
+.er-tip-v, .er-tip-total span:last-child { font-variant-numeric: tabular-nums; }
+.er-tip-total { display: flex; justify-content: space-between; border-top: 1px solid var(--stroke-strong); margin-top: 8px; padding-top: 6px; color: var(--ink-bright); font-weight: 600; }
+.er-chart-empty { color: var(--ink-dim); font-size: var(--text-sm); margin: 8px 0; }
+
+.er-tablewrap { overflow-x: auto; }
+.er-table { width: 100%; border-collapse: collapse; font-size: var(--text-sm); font-variant-numeric: tabular-nums; }
+.er-table th, .er-table td { padding: 8px 10px; border-bottom: 1px solid var(--stroke-strong); text-align: left; white-space: nowrap; }
+.er-table thead th { color: var(--ink-dim); font-weight: var(--weight-medium); font-size: var(--text-xs); }
+.er-table tbody th { font-weight: var(--weight-medium); color: var(--ink); }
+.er-table .er-r { text-align: right; }
+.er-dim { color: var(--ink-dim); }
+
+.er-split { display: grid; gap: var(--space-md); grid-template-columns: 1fr; }
+@media (min-width: 860px) { .er-split { grid-template-columns: 1.4fr 1fr; } }
+
+.er-sources { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
+.er-sources li { display: grid; grid-template-columns: 12px 1fr auto; gap: 8px; align-items: center; font-size: var(--text-sm); }
+.er-sources .er-sub { grid-column: 2 / 4; font-size: var(--text-xs); color: var(--ink-dim); margin-top: -4px; }
+.er-sources .er-amt { font-variant-numeric: tabular-nums; color: var(--ink-bright); }
+
+.er-chip { display: inline-block; font-size: var(--text-2xs, 11px); padding: 1px 7px; border-radius: 99px; border: 1px solid var(--stroke-strong); color: var(--ink-dim); white-space: nowrap; }
+.er-chip-ok { color: var(--success, #1baf7a); border-color: color-mix(in srgb, var(--success, #1baf7a) 45%, transparent); }
+.er-chip-bad { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 45%, transparent); }
+.er-chip-dim { color: var(--ink-dim); }
+
+.er-ledger { overflow-x: auto; }
+.er-ledger table { width: 100%; border-collapse: collapse; font-size: var(--text-sm); }
+.er-ledger th, .er-ledger td { padding: 9px 10px; border-bottom: 1px solid var(--stroke-strong); text-align: left; vertical-align: top; }
+.er-ledger thead th { position: sticky; top: 0; background: var(--surface-2); color: var(--ink-dim); font-size: var(--text-xs); font-weight: var(--weight-medium); white-space: nowrap; }
+.er-ledger td.er-r, .er-ledger th.er-r { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
+.er-ledger tr.is-excluded td { color: var(--ink-dim); }
+.er-ledger .er-label { max-width: 260px; overflow-wrap: anywhere; }
+.er-ledger a { color: var(--accent); text-decoration: none; }
+.er-ledger a:hover { text-decoration: underline; }
+
+.er-drawer-backdrop { position: fixed; inset: 0; background: rgb(0 0 0 / .5); z-index: 90; }
+.er-drawer {
+ position: fixed; top: 0; right: 0; bottom: 0; z-index: 91; width: min(480px, 100vw);
+ background: var(--surface-1, var(--surface-2)); border-left: 1px solid var(--stroke-strong);
+ padding: 20px; overflow-y: auto; box-shadow: -8px 0 32px rgb(0 0 0 / .3);
+}
+.er-drawer h2 { margin: 0 0 4px; }
+.er-drawer dl { margin: 16px 0 0; display: grid; gap: 14px; }
+.er-drawer dt { font-weight: var(--weight-semibold); color: var(--ink-bright); display: flex; align-items: center; gap: 8px; }
+.er-drawer dd { margin: 4px 0 0; color: var(--ink-dim); font-size: var(--text-sm); line-height: 1.5; }
+.er-drawer ul { margin: 6px 0 0; padding-left: 18px; color: var(--ink-dim); font-size: var(--text-sm); line-height: 1.5; }
+.er-drawer-close { float: right; }
+
+.er-rule { display: grid; gap: 10px; }
+.er-rule-head { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; }
+.er-rule-head strong { color: var(--ink-bright); }
+.er-legs { display: grid; gap: 8px; }
+.er-leg { display: grid; grid-template-columns: 1fr 110px auto; gap: 8px; align-items: end; }
+.er-leg .ac-field { margin: 0; }
+.er-confirm { width: 100%; border-collapse: collapse; font-size: var(--text-sm); }
+.er-confirm th, .er-confirm td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--stroke-strong); vertical-align: top; }
+.er-confirm th { font-size: var(--text-xs); color: var(--ink-dim); font-weight: var(--weight-medium); }
+.er-confirm .ac-mono { font-size: var(--text-xs); }
+.er-runs { display: grid; gap: 8px; }
+.er-run { border: 1px solid var(--stroke-strong); border-radius: 10px; padding: 10px 12px; font-size: var(--text-sm); }
+.er-run ul { margin: 6px 0 0; padding-left: 18px; color: var(--ink-dim); font-size: var(--text-xs); line-height: 1.6; }
+
+.er-skel { height: 96px; border-radius: 12px; background: linear-gradient(90deg, var(--surface-2), var(--surface-3), var(--surface-2)); background-size: 200% 100%; animation: er-shimmer 1.4s linear infinite; }
+@keyframes er-shimmer { to { background-position: -200% 0; } }
+@media (prefers-reduced-motion: reduce) { .er-skel { animation: none; } .er-bar .er-seg { transition: none; } }
+
+.er-toggle { display: inline-flex; align-items: center; gap: 10px; cursor: pointer; font-size: var(--text-sm); }
+.er-toggle input { width: 18px; height: 18px; accent-color: var(--accent); }
+.er-toggle input:focus-visible { outline: var(--focus-ring-width, 2px) solid var(--focus-ring-color, #3b82f6); outline-offset: 2px; }
+.er-footnote { font-size: var(--text-xs); color: var(--ink-dim); line-height: 1.6; }
+
+@media (max-width: 560px) {
+ .er-leg { grid-template-columns: 1fr 90px; }
+ .er-leg button { grid-column: 1 / -1; }
+}
diff --git a/vercel.json b/vercel.json
index abb663edf..13c9d2df2 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1436,6 +1436,10 @@
"src": "/commerce/?",
"dest": "/commerce.html"
},
+ {
+ "src": "/earnings/?",
+ "dest": "/earnings.html"
+ },
{
"src": "/invoices/?",
"dest": "/commerce.html"
@@ -5832,6 +5836,10 @@
"src": "/agents/[^/.]+/mail/?",
"dest": "/agent-mail.html"
},
+ {
+ "src": "/agents/([^/.]+)/earnings/?",
+ "dest": "/agent-earnings.html"
+ },
{
"src": "/agents/([^/.]+)/classic/?",
"dest": "/agent-detail-classic.html"
@@ -7654,6 +7662,10 @@
{
"path": "/api/cron/revenue-reinvest",
"schedule": "37 * * * *"
+ },
+ {
+ "path": "/api/cron/data-canary",
+ "schedule": "*/30 * * * *"
}
]
}
diff --git a/vite.config.js b/vite.config.js
index 74feb6684..4d262ea4f 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -920,6 +920,8 @@ const appConfig = {
quests: resolve(__dirname, 'pages/quests.html'),
approvals: resolve(__dirname, 'pages/approvals.html'),
commerce: resolve(__dirname, 'pages/commerce.html'),
+ earnings: resolve(__dirname, 'pages/earnings.html'),
+ 'agent-earnings': resolve(__dirname, 'pages/agent-earnings.html'),
'agent-invoice': resolve(__dirname, 'pages/agent-invoice.html'),
spend: resolve(__dirname, 'pages/spend.html'),
duels: resolve(__dirname, 'pages/duels.html'),
@@ -2494,6 +2496,12 @@ const appConfig = {
filePath = resolve(root, 'pages/commerce.html');
else if (!filePath && /^\/invoices\/[^/.]+\/?$/.test(path))
filePath = resolve(root, 'pages/agent-invoice.html');
+ // /earnings → the revenue ledger console; /agents/:id/earnings → the
+ // agent's public earnings page. Mirrors vercel.json.
+ else if (!filePath && /^\/earnings\/?$/.test(path))
+ filePath = resolve(root, 'pages/earnings.html');
+ else if (!filePath && /^\/agents\/[^/.]+\/earnings\/?$/.test(path))
+ filePath = resolve(root, 'pages/agent-earnings.html');
// /launch/intents/:id → one funded pump.fun launch intent (quote, funding,
// confirmation, stage tracker). Mirrors vercel.json's
// `/launch/intents/([^/.]+)/?`; the list itself is /launch/intents.