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.

refactor(platform): retire the revenue reporting pages and their API endpoints

nirholas223fa834153d
diff --git a/agents/x402-buildout/self/analytics-revenue-dashboard.md b/agents/x402-buildout/self/analytics-revenue-dashboard.md
deleted file mode 100644
index d9f2d2743..000000000
--- a/agents/x402-buildout/self/analytics-revenue-dashboard.md
+++ /dev/null
@@ -1,41 +0,0 @@
-# 039: Analytics: Revenue Dashboard Aggregation
-
-## Objective
-Build a real, wired x402 use case that calls the `/api/x402/analytics` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
-
-## x402 Endpoint
-- **Path:** `/api/x402/analytics`
-- **Method:** POST
-- **Body:** `{"report":"revenue","period":"24h"}`
-
-## What to Build
-Call the analytics x402 endpoint to pull the last 24 hours of revenue data. Extract total earnings per endpoint, fee splits, and net platform revenue. Store signal_data with { total_usd, top_endpoint, fee_collected }. Wire into the autonomous loop under the oracle pipeline so the sniper sees platform health data.
-
-## Implementation Requirements
-
-1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
- - `id`: unique kebab-case string
- - `path`: `/api/x402/analytics`
- - `body`: `{"report":"revenue","period":"24h"}`
- - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
- - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
- - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
- - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
-
-2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
-
-3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
-
-4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
-
-5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
-
-6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
-
-## Definition of Done
-- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
-- [ ] `extractSignal` function tested with a real response payload
-- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
-- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
-- [ ] No console errors from this entry in the cron logs
-- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/api/_lib/x402/revenue-analytics.js b/api/_lib/x402/revenue-analytics.js
deleted file mode 100644
index f6ab93487..000000000
--- a/api/_lib/x402/revenue-analytics.js
+++ /dev/null
@@ -1,185 +0,0 @@
-// api/_lib/x402/revenue-analytics.js
-//
-// Revenue Dashboard Aggregation — the data layer behind POST /api/x402/analytics
-// ({ report: "revenue", period }). Builds a real, per-endpoint revenue report
-// from the platform's own settled-payment ledger; no estimates of demand, only
-// money that actually moved on-chain.
-//
-// Sources (both real, both already populated by live traffic):
-// • x402_audit_log (event_type = 'payment_settled') — every settled x402 call
-// with its route + atomic USDC amount. This is gross revenue, per endpoint.
-// • cross_chain_cost_comparison — the rolling on-chain settlement cost in USD
-// the cross-chain-cost pipeline measures hourly. Multiplied by the settled
-// payment count it yields the settlement fee the platform actually bears, so
-// net = gross − settlement fees is grounded in measured gas, not a guess.
-//
-// The report shape is consumed by:
-// • POST /api/x402/analytics — the paid x402 endpoint that returns it.
-// • the `platform-revenue-analytics` autonomous-loop entry, whose extractSignal
-// lifts { total_usd, top_endpoint, fee_collected } into oracle_intel_signals
-// (topic 'platform-revenue') so the sniper gate sees live platform health.
-
-import { sql } from '../db.js';
-import { atomicsToUsdc } from '../agent-paid-services.js';
-
-// Supported report periods → lookback in hours (null = all-time).
-const PERIOD_HOURS = {
- '1h': 1,
- '6h': 6,
- '24h': 24,
- '7d': 24 * 7,
- '30d': 24 * 30,
- all: null,
-};
-
-/**
- * Normalize a requested period string to a canonical key + ISO `since` bound.
- * Unknown / malformed inputs fall back to 24h (the dashboard default).
- * @param {string} raw
- * @returns {{ key: string, hours: number|null, since: string|null }}
- */
-export function resolvePeriod(raw) {
- const key = String(raw || '24h').toLowerCase().trim();
- const hours = key in PERIOD_HOURS ? PERIOD_HOURS[key] : 24;
- const canonical = key in PERIOD_HOURS ? key : '24h';
- const since = hours == null ? null : new Date(Date.now() - hours * 3600_000).toISOString();
- return { key: canonical, hours, since };
-}
-
-// 6-decimal USD string for money fields (matches the audit-log dashboard format).
-function usd(n) {
- return (Number(n) || 0).toFixed(6);
-}
-
-/**
- * Mean per-settlement on-chain cost (USD) over the window, from the cross-chain
- * cost pipeline's measurements. Prefers the windowed average and falls back to
- * the latest snapshot; returns { perTxUsd, source } where source documents which
- * measurement was used (or 'none' when the pipeline has no data yet).
- *
- * @param {number|null} windowHours lookback for the average (null → all-time)
- */
-async function settlementCostPerTx(windowHours) {
- try {
- const rows = windowHours == null
- ? await sql`
- SELECT avg(solana_gas_usd) FILTER (WHERE solana_gas_usd IS NOT NULL) AS avg_usd,
- count(*) FILTER (WHERE solana_gas_usd IS NOT NULL)::int AS samples
- FROM cross_chain_cost_comparison`
- : await sql`
- SELECT avg(solana_gas_usd) FILTER (WHERE solana_gas_usd IS NOT NULL) AS avg_usd,
- count(*) FILTER (WHERE solana_gas_usd IS NOT NULL)::int AS samples
- FROM cross_chain_cost_comparison
- WHERE checked_at >= now() - (${windowHours} || ' hours')::interval`;
- const avg = rows?.[0]?.avg_usd;
- if (avg != null && Number(avg) > 0) {
- return { perTxUsd: Number(avg), source: 'window_avg', samples: rows[0].samples || 0 };
- }
- // Window empty — fall back to the most recent measured settlement cost.
- const latest = await sql`
- SELECT solana_gas_usd FROM cross_chain_cost_comparison
- WHERE solana_gas_usd IS NOT NULL
- ORDER BY checked_at DESC LIMIT 1`;
- const last = latest?.[0]?.solana_gas_usd;
- if (last != null && Number(last) > 0) {
- return { perTxUsd: Number(last), source: 'latest_snapshot', samples: 1 };
- }
- } catch (err) {
- // Table may not exist in a fresh env — treat as "no cost data".
- if (!err?.message?.includes('does not exist')) throw err;
- }
- return { perTxUsd: 0, source: 'none', samples: 0 };
-}
-
-/**
- * Build the revenue report for a period.
- *
- * @param {object} opts
- * @param {string} [opts.period='24h']
- * @returns {Promise<object>} the full report (see the endpoint's OUTPUT_SCHEMA)
- */
-export async function buildRevenueReport({ period = '24h' } = {}) {
- const { key, hours, since } = resolvePeriod(period);
-
- // ── Gross totals over the window (settled payments only). ────────────────
- const [totals] = await sql`
- SELECT
- count(*)::int AS payments,
- count(DISTINCT payer)::int AS unique_payers,
- coalesce(sum(
- CASE WHEN amount_atomics ~ '^[0-9]+$' THEN amount_atomics::numeric ELSE 0 END
- ), 0) AS gross_atomics
- FROM x402_audit_log
- WHERE event_type = 'payment_settled'
- AND (${since}::timestamptz IS NULL OR created_at >= ${since}::timestamptz)
- `;
- const payments = totals?.payments || 0;
- const grossAtomics = Number(totals?.gross_atomics || 0);
- const grossUsd = atomicsToUsdc(grossAtomics);
-
- // ── Per-endpoint earnings, highest gross first. ──────────────────────────
- const routeRows = await sql`
- SELECT
- route,
- count(*)::int AS count,
- coalesce(sum(
- CASE WHEN amount_atomics ~ '^[0-9]+$' THEN amount_atomics::numeric ELSE 0 END
- ), 0) AS gross_atomics
- FROM x402_audit_log
- WHERE event_type = 'payment_settled'
- AND (${since}::timestamptz IS NULL OR created_at >= ${since}::timestamptz)
- GROUP BY route
- ORDER BY gross_atomics DESC, count DESC
- `;
- const byEndpoint = routeRows.map((r) => {
- const g = atomicsToUsdc(Number(r.gross_atomics || 0));
- return {
- endpoint: r.route || 'unknown',
- count: r.count,
- gross_usd: usd(g),
- share: grossUsd > 0 ? Number((g / grossUsd).toFixed(4)) : 0,
- };
- });
- const topEndpoint = byEndpoint[0]
- ? { endpoint: byEndpoint[0].endpoint, count: byEndpoint[0].count, gross_usd: byEndpoint[0].gross_usd }
- : null;
-
- // ── Settlement fee split: measured on-chain cost × settled payment count. ─
- const cost = await settlementCostPerTx(hours);
- const settlementFeeUsd = cost.perTxUsd * payments;
- const netPlatformUsd = Math.max(0, grossUsd - settlementFeeUsd);
- const effectiveFeeRate = grossUsd > 0 ? Number((settlementFeeUsd / grossUsd).toFixed(6)) : 0;
-
- const [failed] = await sql`
- SELECT count(*)::int AS n
- FROM x402_audit_log
- WHERE event_type = 'payment_failed'
- AND (${since}::timestamptz IS NULL OR created_at >= ${since}::timestamptz)
- `;
-
- return {
- report: 'revenue',
- period: key,
- since,
- generated_at: new Date().toISOString(),
- totals: {
- gross_usd: usd(grossUsd),
- net_platform_usd: usd(netPlatformUsd),
- settlement_fee_usd: usd(settlementFeeUsd),
- total_payments: payments,
- failed_payments: failed?.n || 0,
- unique_payers: totals?.unique_payers || 0,
- avg_payment_usd: usd(payments > 0 ? grossUsd / payments : 0),
- },
- fee_splits: {
- gross_usd: usd(grossUsd),
- settlement_fee_usd: usd(settlementFeeUsd),
- net_platform_usd: usd(netPlatformUsd),
- effective_fee_rate: effectiveFeeRate,
- fee_per_settlement_usd: usd(cost.perTxUsd),
- fee_source: cost.source,
- },
- by_endpoint: byEndpoint,
- top_endpoint: topEndpoint,
- };
-}
diff --git a/api/billing/revenue.js b/api/billing/revenue.js
deleted file mode 100644
index 63e52ad5b..000000000
--- a/api/billing/revenue.js
+++ /dev/null
@@ -1,211 +0,0 @@
-// GET /api/billing/revenue — aggregated earnings for the authenticated user's agents.
-// Powers the agent owner revenue dashboard (Task 12).
-
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, wrap, error } from '../_lib/http.js';
-import { isUuid } from '../_lib/validate.js';
-import { reconciliationStatus } from '../_lib/metering.js';
-
-const VALID_GRANULARITY = new Set(['day', 'week', 'month']);
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const q = req.query ?? {};
-
- // Parse and validate query params
- const agentId = q.agent_id ?? null;
- if (agentId !== null && !isUuid(agentId))
- return error(res, 400, 'validation_error', 'agent_id must be a UUID');
-
- const granularity = q.granularity ?? 'day';
- if (!VALID_GRANULARITY.has(granularity))
- return error(res, 400, 'validation_error', 'granularity must be day, week, or month');
-
- const now = new Date();
- const defaultFrom = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
-
- const fromDate = q.from ? new Date(q.from) : defaultFrom;
- const toDate = q.to ? new Date(q.to) : now;
-
- if (isNaN(fromDate.getTime()))
- return error(res, 400, 'validation_error', 'from must be a valid ISO-8601 date');
- if (isNaN(toDate.getTime()))
- return error(res, 400, 'validation_error', 'to must be a valid ISO-8601 date');
-
- const baseParams = [user.id, fromDate, toDate];
- const agentFilterSql = agentId ? `AND re.agent_id = $4::uuid` : '';
- const filterParams = agentId ? [...baseParams, agentId] : baseParams;
-
- const [summaryRow] = await sql(
- `
- SELECT
- COALESCE(SUM(re.gross_amount), 0)::bigint AS gross_total,
- COALESCE(SUM(re.fee_amount), 0)::bigint AS fee_total,
- COALESCE(SUM(re.net_amount), 0)::bigint AS net_total,
- COUNT(*)::int AS payment_count,
- MAX(re.currency_mint) AS currency_mint,
- MAX(re.chain) AS chain
- FROM agent_revenue_events re
- JOIN agent_identities ai ON ai.id = re.agent_id
- WHERE ai.user_id = $1
- AND re.created_at BETWEEN $2 AND $3
- ${agentFilterSql}
- `,
- filterParams,
- );
-
- const bySkill = await sql(
- `
- SELECT
- re.skill,
- COALESCE(SUM(re.net_amount), 0)::bigint AS net_total,
- COUNT(*)::int AS count
- FROM agent_revenue_events re
- JOIN agent_identities ai ON ai.id = re.agent_id
- WHERE ai.user_id = $1
- AND re.created_at BETWEEN $2 AND $3
- ${agentFilterSql}
- GROUP BY re.skill
- ORDER BY net_total DESC
- `,
- filterParams,
- );
-
- const tsParams = agentId
- ? [user.id, fromDate, toDate, granularity, agentId]
- : [user.id, fromDate, toDate, granularity];
- const tsAgentFilter = agentId ? `AND re.agent_id = $5::uuid` : '';
- const timeseries = await sql(
- `
- SELECT
- date_trunc($4, re.created_at) AS period,
- COALESCE(SUM(re.net_amount), 0)::bigint AS net_total,
- COUNT(*)::int AS count
- FROM agent_revenue_events re
- JOIN agent_identities ai ON ai.id = re.agent_id
- WHERE ai.user_id = $1
- AND re.created_at BETWEEN $2 AND $3
- ${tsAgentFilter}
- GROUP BY period
- ORDER BY period
- `,
- tsParams,
- );
-
- // ── Subscription income ──────────────────────────────────────────────────
- // Creator subscriptions (subscription_plans → creator_subscriptions →
- // subscription_payments) settle the creator leg DIRECTLY to the creator's
- // wallet on-chain, so they never write agent_revenue_events and are absent
- // from net_total / the withdrawable balance. Surface them here as a SEPARATE,
- // USD-denominated figure (amount_usd is numeric(8,2), not atomic units) so the
- // creator sees their full income without ever mixing units or double-counting
- // against the platform-custodied withdrawal pool. When filtering by agent we
- // count only plans scoped to that agent; creator-wide plans show in the
- // all-agents view. `subAgentFilter` reuses the same positional params as the
- // revenue queries above (so $4 is agent_id when present).
- const subAgentFilter = agentId ? `AND pl.agent_id = $4::uuid` : '';
- const [subSummaryRow] = await sql(
- `
- SELECT
- COALESCE(SUM(sp.amount_usd), 0)::numeric AS income_usd,
- COUNT(*)::int AS payment_count
- FROM subscription_payments sp
- JOIN creator_subscriptions cs ON cs.id = sp.subscription_id
- JOIN subscription_plans pl ON pl.id = cs.plan_id
- WHERE pl.creator_id = $1
- AND sp.status = 'succeeded'
- AND sp.paid_at BETWEEN $2 AND $3
- ${subAgentFilter}
- `,
- filterParams,
- );
-
- // Current-state counts (not date-bounded): active subscribers + active plans.
- const subStateAgentFilter = agentId ? `AND pl.agent_id = $2::uuid` : '';
- const subStateParams = agentId ? [user.id, agentId] : [user.id];
- const [subStateRow] = await sql(
- `
- SELECT
- COUNT(*) FILTER (WHERE cs.status = 'active')::int AS active_subscribers,
- COUNT(DISTINCT pl.id)::int AS plan_count
- FROM subscription_plans pl
- LEFT JOIN creator_subscriptions cs ON cs.plan_id = pl.id
- WHERE pl.creator_id = $1
- AND pl.active = true
- ${subStateAgentFilter}
- `,
- subStateParams,
- );
-
- const subTsAgentFilter = agentId ? `AND pl.agent_id = $5::uuid` : '';
- const subTimeseries = await sql(
- `
- SELECT
- date_trunc($4, sp.paid_at) AS period,
- COALESCE(SUM(sp.amount_usd), 0)::numeric AS income_usd,
- COUNT(*)::int AS count
- FROM subscription_payments sp
- JOIN creator_subscriptions cs ON cs.id = sp.subscription_id
- JOIN subscription_plans pl ON pl.id = cs.plan_id
- WHERE pl.creator_id = $1
- AND sp.status = 'succeeded'
- AND sp.paid_at BETWEEN $2 AND $3
- ${subTsAgentFilter}
- GROUP BY period
- ORDER BY period
- `,
- tsParams,
- );
-
- // Reconciliation status — does every metered charge map to a real settlement?
- // Surfaced on the dashboard so an operator sees "all charges reconciled" vs
- // "N unreconciled" without leaving the revenue view. Never fails the read.
- let reconciliation = null;
- try {
- reconciliation = await reconciliationStatus({ userId: user.id });
- } catch {
- reconciliation = null;
- }
-
- return json(res, 200, {
- summary: {
- gross_total: Number(summaryRow.gross_total),
- fee_total: Number(summaryRow.fee_total),
- net_total: Number(summaryRow.net_total),
- currency_mint: summaryRow.currency_mint ?? null,
- chain: summaryRow.chain ?? null,
- payment_count: summaryRow.payment_count,
- },
- by_skill: bySkill.map((r) => ({
- skill: r.skill,
- net_total: Number(r.net_total),
- count: r.count,
- })),
- timeseries: timeseries.map((r) => ({
- period: r.period instanceof Date ? r.period.toISOString().slice(0, 10) : String(r.period),
- net_total: Number(r.net_total),
- count: r.count,
- })),
- // USD-denominated, paid directly to the creator wallet (not withdrawable
- // from the platform pool — kept distinct from `summary` above by design).
- subscriptions: {
- income_usd: Number(subSummaryRow?.income_usd ?? 0),
- payment_count: subSummaryRow?.payment_count ?? 0,
- active_subscribers: subStateRow?.active_subscribers ?? 0,
- plan_count: subStateRow?.plan_count ?? 0,
- },
- subscription_timeseries: subTimeseries.map((r) => ({
- period: r.period instanceof Date ? r.period.toISOString().slice(0, 10) : String(r.period),
- income_usd: Number(r.income_usd),
- count: r.count,
- })),
- // Operator trust signal: usage charges reconciled against on-chain settlements.
- reconciliation,
- });
-});
diff --git a/api/monetization/revenue.js b/api/monetization/revenue.js
deleted file mode 100644
index 20d286550..000000000
--- a/api/monetization/revenue.js
+++ /dev/null
@@ -1,145 +0,0 @@
-// GET /api/monetization/revenue?agent_id=X&period=7d
-//
-// Returns aggregated revenue for the authenticated user's agents.
-// Periods: 1d, 7d, 30d, 90d, all
-// Response: { total_usdc, total_fees_usdc, net_usdc, event_count,
-// by_skill: [{skill, total, count}],
-// by_day: [{date, total}] }
-
-import { sql } from '../_lib/db.js';
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
-import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { isUuid } from '../_lib/validate.js';
-
-// Window length per period, in milliseconds. `all` means no lower bound.
-const DAY_MS = 86_400_000;
-const PERIOD_TO_MS = {
- '1d': DAY_MS,
- '7d': 7 * DAY_MS,
- '30d': 30 * DAY_MS,
- '90d': 90 * DAY_MS,
- 'all': null,
-};
-
-async function resolveUserId(req) {
- const session = await getSessionUser(req);
- if (session) return session.id;
- const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return bearer.userId;
- return null;
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET'])) return;
-
- const userId = await resolveUserId(req);
- if (!userId) return error(res, 401, 'unauthorized', 'Sign in required');
-
- const rl = await limits.authedReadIp(clientIp(req));
- if (!rl.success) return rateLimited(res, rl);
-
- const params = new URL(req.url, 'http://x').searchParams;
-
- const agentId = params.get('agent_id') || null;
- if (agentId && !isUuid(agentId)) {
- return error(res, 400, 'validation_error', 'agent_id must be a UUID');
- }
-
- // Verify agent ownership if agent_id is specified
- if (agentId) {
- const [agent] = await sql`
- SELECT id, user_id FROM agent_identities
- WHERE id = ${agentId} AND deleted_at IS NULL
- `;
- if (!agent) return error(res, 404, 'not_found', 'Agent not found');
- if (agent.user_id !== userId) return error(res, 403, 'forbidden', 'You don\'t own this agent');
- }
-
- const period = params.get('period') || '7d';
- if (!Object.hasOwn(PERIOD_TO_MS, period)) {
- return error(res, 400, 'validation_error', `period must be one of: ${Object.keys(PERIOD_TO_MS).join(', ')}`);
- }
-
- const windowMs = PERIOD_TO_MS[period];
- const now = new Date();
- // `all` reaches back before the platform had any revenue events.
- const fromDate = windowMs ? new Date(now.getTime() - windowMs) : new Date('2020-01-01');
- const toDate = now;
-
- // Build queries with conditional agent filter
- const baseParams = [userId, fromDate, toDate];
- const agentFilter = agentId ? 'AND re.agent_id = $4::uuid' : '';
- const filterParams = agentId ? [...baseParams, agentId] : baseParams;
-
- // Summary aggregation
- const [summary] = await sql(
- `SELECT
- COALESCE(SUM(re.gross_amount), 0)::bigint AS gross_total,
- COALESCE(SUM(re.fee_amount), 0)::bigint AS fee_total,
- COALESCE(SUM(re.net_amount), 0)::bigint AS net_total,
- COUNT(*)::int AS event_count
- FROM agent_revenue_events re
- JOIN agent_identities ai ON ai.id = re.agent_id
- WHERE ai.user_id = $1
- AND re.created_at BETWEEN $2 AND $3
- ${agentFilter}`,
- filterParams,
- );
-
- // Per-skill breakdown
- const bySkill = await sql(
- `SELECT
- re.skill,
- COALESCE(SUM(re.net_amount), 0)::bigint AS net_total,
- COUNT(*)::int AS count
- FROM agent_revenue_events re
- JOIN agent_identities ai ON ai.id = re.agent_id
- WHERE ai.user_id = $1
- AND re.created_at BETWEEN $2 AND $3
- ${agentFilter}
- GROUP BY re.skill
- ORDER BY net_total DESC`,
- filterParams,
- );
-
- // Daily timeseries
- const byDay = await sql(
- `SELECT
- date_trunc('day', re.created_at) AS period,
- COALESCE(SUM(re.net_amount), 0)::bigint AS net_total,
- COUNT(*)::int AS count
- FROM agent_revenue_events re
- JOIN agent_identities ai ON ai.id = re.agent_id
- WHERE ai.user_id = $1
- AND re.created_at BETWEEN $2 AND $3
- ${agentFilter}
- GROUP BY period
- ORDER BY period`,
- filterParams,
- );
-
- return json(res, 200, {
- total_usdc: Number(summary.gross_total) / 1_000_000,
- total_fees_usdc: Number(summary.fee_total) / 1_000_000,
- net_usdc: Number(summary.net_total) / 1_000_000,
- event_count: summary.event_count,
- // Raw atomic values for precision-sensitive clients
- total_atomic: Number(summary.gross_total),
- fees_atomic: Number(summary.fee_total),
- net_atomic: Number(summary.net_total),
- by_skill: bySkill.map((r) => ({
- skill: r.skill,
- total: Number(r.net_total) / 1_000_000,
- total_atomic: Number(r.net_total),
- count: r.count,
- })),
- by_day: byDay.map((r) => ({
- date: r.period instanceof Date ? r.period.toISOString().slice(0, 10) : String(r.period).slice(0, 10),
- total: Number(r.net_total) / 1_000_000,
- total_atomic: Number(r.net_total),
- count: r.count,
- })),
- });
-});
diff --git a/api/x402-revenue.js b/api/x402-revenue.js
deleted file mode 100644
index 166fdbaac..000000000
--- a/api/x402-revenue.js
+++ /dev/null
@@ -1,357 +0,0 @@
-// GET /api/x402-revenue — the public, real-time view of money flowing INTO the
-// platform's own x402 paid endpoints.
-//
-// This is the mirror image of the Money Pulse (/api/pulse): the Pulse surfaces
-// agent wallet SPEND (agent_custody_events); this surfaces endpoint REVENUE — the
-// USDC that buyers pay to call our paid endpoints, recorded in x402_audit_log.
-// See docs/x402-revenue.md.
-//
-// EVERY row is a real settled payment with an explorer-verifiable tx. There are no
-// synthetic events — if the endpoints are quiet, the feed is honestly empty.
-//
-// Privacy: x402_audit_log also stores ip_address and user_agent. Those are
-// operational and NEVER leave the server — this endpoint selects only the
-// already-public, on-chain-verifiable fields (route, network, amount, tx, time)
-// plus a truncated payer label. The stats view exposes only aggregates.
-//
-// Views:
-// GET /api/x402-revenue — live feed of recent settlements (keyset)
-// GET /api/x402-revenue?since=<iso> — delta poll: only settlements newer than cursor
-// GET /api/x402-revenue?endpoint=<slug>&network= — filter the feed
-// GET /api/x402-revenue?view=stats&period=24h — aggregate revenue intelligence
-// (totals, per-endpoint, per-network,
-// time-series, momentum, settlement health)
-// GET /api/x402-revenue?view=export&period=24h — CSV of settlements in the window
-
-import { sql, isDbUnavailableError } from './_lib/db.js';
-import { cors, json, method, error, serverError, rateLimited } from './_lib/http.js';
-import { limits, clientIp } from './_lib/rate-limit.js';
-import { cacheGet, cacheSet } from './_lib/cache.js';
-import { atomicsToUsdc } from './_lib/agent-paid-services.js';
-import { buildRevenueReport, resolvePeriod } from './_lib/x402/revenue-analytics.js';
-import {
- networkIdentity,
- resolveNetworkFilter,
- revenueTxUrl,
- foldNetworkRows,
-} from './_lib/x402/revenue-networks.js';
-
-const STATS_TTL_S = 30;
-const FEED_TTL_S = 8;
-const FEED_DEFAULT_LIMIT = 30;
-const FEED_MAX_LIMIT = 100;
-const EXPORT_MAX_ROWS = 5000;
-
-// Time-series bucket unit per period. Kept coarse enough to stay light, fine
-// enough to draw a smooth chart (24h→24 pts, 7d→168, 30d→30, all→daily).
-const SERIES_UNIT = { '24h': 'hour', '7d': 'hour', '30d': 'day', all: 'day' };
-
-// Shorten a wallet/payer address for display — full address stays on-chain.
-function shortAddr(a) {
- if (!a || typeof a !== 'string') return null;
- return a.length > 12 ? `${a.slice(0, 6)}…${a.slice(-4)}` : a;
-}
-
-// A caller-supplied `?endpoint=` → the canonical slug we filter on, or null when
-// it sanitizes to nothing. Echoed back in `filter.endpoint` so the response names
-// the filter that was actually applied instead of the raw string that was sent.
-export function endpointSlug(raw) {
- if (!raw) return null;
- const clean = String(raw)
- .trim()
- .replace(/^\/?(api\/x402\/)?/, '')
- .replace(/[^a-z0-9-]/gi, '');
- return clean || null;
-}
-
-// A route → slug ('/api/x402/token-intel' → 'token-intel'); null if not one of ours.
-function routeForEndpoint(slug) {
- const clean = endpointSlug(slug);
- return clean ? `/api/x402/${clean}` : null;
-}
-
-// A `?since=` / `?cursor=` value → an ISO timestamp Postgres can cast, or null
-// when the param is absent. An unparseable value used to be bound straight into
-// the ::timestamptz cast, so `?since=notadate` threw 22P02 deep in the query and
-// surfaced as a 500 on what is plainly a caller mistake. Reject it up front.
-export function timestampParam(raw, name) {
- if (raw == null || raw === '') return null;
- const ms = Date.parse(raw);
- if (!Number.isFinite(ms)) {
- throw Object.assign(new Error(`\`${name}\` must be an ISO 8601 timestamp`), {
- status: 400,
- code: `invalid_${name}`,
- });
- }
- return new Date(ms).toISOString();
-}
-
-// A `?network=` value → the raw ledger ids it selects, as a comma-joined string
-// bound once and expanded in SQL. The ledger holds CAIP-2 ids ('solana:5eykt4Us…',
-// 'eip155:8453') while callers filter by family ('solana', 'base'), so comparing
-// the two directly matches nothing; see _lib/x402/revenue-networks.js.
-function networkFilterIds(n) {
- const f = resolveNetworkFilter(n);
- return f ? f.ids.join(',') : null;
-}
-
-// Shape a settled-payment row into a privacy-safe public event.
-function shapeSettlement(r) {
- const atomics = /^[0-9]+$/.test(String(r.amount_atomics || '')) ? Number(r.amount_atomics) : 0;
- const net = r.network || null;
- const identity = networkIdentity(net);
- return {
- id: r.id,
- route: r.route || 'unknown',
- network: net,
- network_family: identity.family,
- network_label: identity.label,
- amount_usd: atomicsToUsdc(atomics),
- asset: r.asset || 'USDC',
- payer: shortAddr(r.payer),
- tx: r.tx_hash || null,
- tx_url: revenueTxUrl(r.tx_hash, net),
- ts: r.created_at instanceof Date ? r.created_at.toISOString() : r.created_at,
- };
-}
-
-// Settlement success-rate over the window: settled vs failed payment events.
-async function settlementHealth(since) {
- const [row] = await sql`
- SELECT
- count(*) FILTER (WHERE event_type = 'payment_settled')::int AS settled,
- count(*) FILTER (WHERE event_type = 'payment_failed')::int AS failed
- FROM x402_audit_log
- WHERE event_type IN ('payment_settled', 'payment_failed')
- AND (${since}::timestamptz IS NULL OR created_at >= ${since}::timestamptz)
- `;
- const settled = row?.settled || 0;
- const failed = row?.failed || 0;
- const total = settled + failed;
- return { settled, failed, success_rate: total > 0 ? Number((settled / total).toFixed(4)) : 1 };
-}
-
-// Time-bucketed revenue for the chart. Gaps (buckets with no revenue) are filled
-// client-side against the returned unit so the area chart stays continuous.
-async function revenueSeries(period) {
- const { key, since } = resolvePeriod(period);
- const unit = SERIES_UNIT[key] || 'hour';
- const rows = await sql`
- SELECT date_trunc(${unit}, created_at) AS bucket,
- count(*)::int AS count,
- coalesce(sum(CASE WHEN amount_atomics ~ '^[0-9]+$' THEN amount_atomics::numeric ELSE 0 END), 0) AS gross_atomics
- FROM x402_audit_log
- WHERE event_type = 'payment_settled'
- AND (${since}::timestamptz IS NULL OR created_at >= ${since}::timestamptz)
- GROUP BY bucket
- ORDER BY bucket ASC
- `;
- return {
- unit,
- points: rows.map((r) => ({
- ts: r.bucket instanceof Date ? r.bucket.toISOString() : r.bucket,
- count: r.count,
- gross_usd: atomicsToUsdc(Number(r.gross_atomics || 0)),
- })),
- };
-}
-
-// Revenue split by settlement network, folded to one row per chain family so the
-// UI names "Solana" rather than the genesis hash the ledger stores.
-async function revenueByNetwork(since) {
- const rows = await sql`
- SELECT network,
- count(*)::int AS count,
- coalesce(sum(CASE WHEN amount_atomics ~ '^[0-9]+$' THEN amount_atomics::numeric ELSE 0 END), 0) AS gross_atomics
- FROM x402_audit_log
- WHERE event_type = 'payment_settled'
- AND (${since}::timestamptz IS NULL OR created_at >= ${since}::timestamptz)
- GROUP BY network
- ORDER BY gross_atomics DESC
- `;
- return foldNetworkRows(
- rows.map((r) => ({
- network: r.network,
- count: r.count,
- gross_usd: atomicsToUsdc(Number(r.gross_atomics || 0)),
- })),
- );
-}
-
-// Momentum: this window's gross vs the immediately-preceding equal window, plus a
-// simple per-hour run-rate. Null for all-time (no comparable prior window).
-async function revenueMomentum(period, grossUsd) {
- const { hours, since } = resolvePeriod(period);
- if (hours == null || since == null) {
- return { change_pct: null, prev_usd: null, per_hour_usd: null };
- }
- const prevSince = new Date(Date.parse(since) - hours * 3600_000).toISOString();
- const [row] = await sql`
- SELECT coalesce(sum(CASE WHEN amount_atomics ~ '^[0-9]+$' THEN amount_atomics::numeric ELSE 0 END), 0) AS prev_atomics
- FROM x402_audit_log
- WHERE event_type = 'payment_settled'
- AND created_at >= ${prevSince}::timestamptz
- AND created_at < ${since}::timestamptz
- `;
- const prevUsd = atomicsToUsdc(Number(row?.prev_atomics || 0));
- const change = prevUsd > 0 ? (grossUsd - prevUsd) / prevUsd : grossUsd > 0 ? 1 : 0;
- return {
- change_pct: Number(change.toFixed(4)),
- prev_usd: prevUsd,
- per_hour_usd: Number((grossUsd / hours).toFixed(6)),
- };
-}
-
-async function handleStats(period) {
- const { since } = resolvePeriod(period);
- const report = await buildRevenueReport({ period });
- const grossUsd = Number(report?.totals?.gross_usd || 0);
- const [health, series, byNetwork, momentum] = await Promise.all([
- settlementHealth(since),
- revenueSeries(period),
- revenueByNetwork(since),
- revenueMomentum(period, grossUsd),
- ]);
- return { ...report, settlement_health: health, series, by_network: byNetwork, momentum };
-}
-
-async function handleFeed({ since, cursor, limit, endpoint, network }) {
- const route = routeForEndpoint(endpoint);
- const netIds = networkFilterIds(network);
- const rows = await sql`
- SELECT id, route, network, amount_atomics, asset, tx_hash, payer, created_at
- FROM x402_audit_log
- WHERE event_type = 'payment_settled'
- AND (${since}::timestamptz IS NULL OR created_at > ${since}::timestamptz)
- AND (${cursor}::timestamptz IS NULL OR created_at < ${cursor}::timestamptz)
- AND (${route}::text IS NULL OR route = ${route})
- AND (${netIds}::text IS NULL OR network = ANY(string_to_array(${netIds}::text, ',')))
- ORDER BY created_at DESC
- LIMIT ${limit}
- `;
- const events = rows.map(shapeSettlement);
- const last = rows[rows.length - 1];
- const nextCursor = last
- ? last.created_at instanceof Date
- ? last.created_at.toISOString()
- : last.created_at
- : null;
- return {
- events,
- count: events.length,
- next_cursor: events.length === limit ? nextCursor : null,
- filter: {
- endpoint: endpointSlug(endpoint),
- network: resolveNetworkFilter(network)?.family || null,
- },
- };
-}
-
-// CSV export of settlements in the window (bounded). Streams a downloadable file.
-async function handleExport(res, { period, endpoint, network }) {
- const { since } = resolvePeriod(period);
- const route = routeForEndpoint(endpoint);
- const netIds = networkFilterIds(network);
- const rows = await sql`
- SELECT route, network, amount_atomics, asset, tx_hash, payer, created_at
- FROM x402_audit_log
- WHERE event_type = 'payment_settled'
- AND (${since}::timestamptz IS NULL OR created_at >= ${since}::timestamptz)
- AND (${route}::text IS NULL OR route = ${route})
- AND (${netIds}::text IS NULL OR network = ANY(string_to_array(${netIds}::text, ',')))
- ORDER BY created_at DESC
- LIMIT ${EXPORT_MAX_ROWS}
- `;
- const header = 'timestamp,endpoint,network,chain,amount_usd,asset,payer,tx_hash,tx_url\n';
- const csv = rows.reduce((acc, r) => {
- const ev = shapeSettlement(r);
- const cells = [
- ev.ts,
- ev.route,
- ev.network || '',
- ev.network_label,
- ev.amount_usd,
- ev.asset,
- r.payer || '',
- ev.tx || '',
- ev.tx_url || '',
- ].map((c) => {
- const s = String(c ?? '');
- return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
- });
- return acc + cells.join(',') + '\n';
- }, header);
- res.statusCode = 200;
- res.setHeader('content-type', 'text/csv; charset=utf-8');
- res.setHeader(
- 'content-disposition',
- `attachment; filename="x402-revenue-${resolvePeriod(period).key}.csv"`,
- );
- res.setHeader('cache-control', 'no-store');
- res.end(csv);
-}
-
-export default async function handler(req, res) {
- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
- if (!method(req, res, ['GET'])) return;
-
- const rl = await limits.publicIp(clientIp(req));
- if (!rl.success) return rateLimited(res, rl);
-
- const url = new URL(req.url, 'http://x');
- const view = url.searchParams.get('view') || 'feed';
- const period = url.searchParams.get('period') || '24h';
- const sinceRaw = url.searchParams.get('since');
- const cursorRaw = url.searchParams.get('cursor');
- const endpoint = url.searchParams.get('endpoint');
- const network = url.searchParams.get('network');
- const limit = Math.min(
- FEED_MAX_LIMIT,
- Math.max(1, Number(url.searchParams.get('limit')) || FEED_DEFAULT_LIMIT),
- );
-
- try {
- const since = timestampParam(sinceRaw, 'since');
- const cursor = timestampParam(cursorRaw, 'cursor');
-
- if (view === 'stats') {
- const cacheKey = `x402rev:stats:${resolvePeriod(period).key}`;
- let body = await cacheGet(cacheKey);
- if (body === null) {
- body = await handleStats(period);
- await cacheSet(cacheKey, body, STATS_TTL_S);
- }
- res.setHeader('cache-control', 'public, max-age=20');
- return json(res, 200, { data: body });
- }
-
- if (view === 'export') {
- return await handleExport(res, { period, endpoint, network });
- }
-
- // Delta polls (since=) are never cached — they must reflect the latest row.
- if (since) {
- return json(res, 200, { data: await handleFeed({ since, limit, endpoint, network }) });
- }
-
- // Filtered feeds and older pages: a short cache smooths the live-poll cadence.
- const filterKey = `${routeForEndpoint(endpoint) || 'all'}:${resolveNetworkFilter(network)?.family || 'all'}`;
- const cacheKey = `x402rev:feed:${cursor || 'head'}:${limit}:${filterKey}`;
- let body = await cacheGet(cacheKey);
- if (body === null) {
- body = await handleFeed({ cursor, limit, endpoint, network });
- await cacheSet(cacheKey, body, FEED_TTL_S);
- }
- res.setHeader('cache-control', 'public, max-age=8');
- return json(res, 200, { data: body });
- } catch (err) {
- // A caller-fault throw (a malformed cursor/since) carries its own 4xx.
- if (Number.isInteger(err?.status) && err.status >= 400 && err.status < 500) {
- return error(res, err.status, err.code || 'bad_request', err.message);
- }
- if (isDbUnavailableError(err)) {
- return error(res, 503, 'db_unavailable', 'revenue ledger is temporarily unavailable');
- }
- return serverError(res, 500, 'x402_revenue_error', err);
- }
-}
diff --git a/chat/src/three-ui/pages/RevenueDashboard.svelte b/chat/src/three-ui/pages/RevenueDashboard.svelte
deleted file mode 100644
index fbec49719..000000000
--- a/chat/src/three-ui/pages/RevenueDashboard.svelte
+++ /dev/null
@@ -1,420 +0,0 @@
-<script>
- import { onMount } from 'svelte';
- import { route } from '../../stores.js';
-
- // --- state ---
- let revenueData = null;
- let wallets = [];
- let withdrawals = [];
- let withdrawalsTotal = 0;
- let loading = true;
- let loadError = '';
- let needsSignIn = false;
-
- // Available balance = net earned minus pending/processing withdrawals
- let availableBalance = 0;
- let currencyMint = null;
- let chain = null;
-
- // Form
- let amountDisplay = ''; // what user types (in USDC)
- let selectedWalletId = '';
- let submitting = false;
- let submitError = '';
- let submitSuccess = '';
-
- // History pagination
- let histOffset = 0;
- const HIST_LIMIT = 20;
-
- function formatUSDC(lamports) {
- return (lamports / 1_000_000).toLocaleString('en-US', {
- minimumFractionDigits: 2,
- maximumFractionDigits: 2,
- }) + ' USDC';
- }
-
- function truncateAddr(addr) {
- if (!addr || addr.length <= 12) return addr;
- return addr.slice(0, 6) + '…' + addr.slice(-4);
- }
-
- function explorerUrl(w) {
- if (!w.tx_signature) return null;
- if (w.chain === 'solana') return `https://solscan.io/tx/${w.tx_signature}`;
- return `https://basescan.org/tx/${w.tx_signature}`;
- }
-
- const STATUS_LABEL = { pending: 'Queued', processing: 'Processing', completed: 'Sent', failed: 'Failed' };
- const STATUS_CLASS = {
- pending: 'bg-yellow-100 text-yellow-800',
- processing: 'bg-blue-100 text-blue-800',
- completed: 'bg-green-100 text-green-800',
- failed: 'bg-red-100 text-red-800',
- };
-
- async function loadAll() {
- loading = true;
- loadError = '';
- needsSignIn = false;
- try {
- const [revRes, walletsRes, histRes] = await Promise.all([
- fetch('/api/billing/revenue', { credentials: 'include' }),
- fetch('/api/billing/payout-wallets', { credentials: 'include' }),
- fetch(`/api/billing/withdrawals?limit=${HIST_LIMIT}&offset=${histOffset}`, { credentials: 'include' }),
- ]);
-
- // 401 is not a failure, it is the page telling an anonymous visitor what
- // to do next. Saying "failed to load" there sends people hunting a bug.
- if ([revRes, walletsRes, histRes].some((r) => r.status === 401)) {
- needsSignIn = true;
- return;
- }
- if (!revRes.ok) throw new Error('Could not load your revenue. Try again in a moment.');
- if (!walletsRes.ok) throw new Error('Could not load your payout wallets. Try again in a moment.');
- if (!histRes.ok) throw new Error('Could not load your withdrawal history. Try again in a moment.');
-
- revenueData = await revRes.json();
- const walletsJson = await walletsRes.json();
- const histJson = await histRes.json();
-
- wallets = walletsJson.wallets ?? [];
- withdrawals = histJson.withdrawals ?? [];
- withdrawalsTotal = histJson.total ?? 0;
-
- // Compute available balance
- const netEarned = revenueData.summary?.net_total ?? 0;
- currencyMint = revenueData.summary?.currency_mint ?? null;
- chain = revenueData.summary?.chain ?? null;
-
- // Sum pending/processing withdrawals
- const inFlight = withdrawals
- .filter(w => w.status === 'pending' || w.status === 'processing')
- .reduce((s, w) => s + Number(w.amount), 0);
-
- availableBalance = Math.max(0, netEarned - inFlight);
-
- // Default wallet selection
- if (!selectedWalletId && wallets.length > 0) {
- const def = wallets.find(w => w.is_default) ?? wallets[0];
- selectedWalletId = def.id;
- }
- } catch (e) {
- loadError = e.message;
- } finally {
- loading = false;
- }
- }
-
- async function loadHistory() {
- try {
- const res = await fetch(`/api/billing/withdrawals?limit=${HIST_LIMIT}&offset=${histOffset}`, { credentials: 'include' });
- if (!res.ok) throw new Error('Failed to load history');
- const json = await res.json();
- withdrawals = json.withdrawals ?? [];
- withdrawalsTotal = json.total ?? 0;
- } catch (e) {
- loadError = e.message;
- }
- }
-
- function setMax() {
- amountDisplay = (availableBalance / 1_000_000).toFixed(6).replace(/\.?0+$/, '');
- }
-
- function validateAmount() {
- const v = parseFloat(amountDisplay);
- if (isNaN(v) || v <= 0) return 'Enter a valid amount';
- const lamports = Math.round(v * 1_000_000);
- if (lamports > availableBalance) return 'Insufficient balance';
- return null;
- }
-
- async function submit() {
- submitError = '';
- submitSuccess = '';
-
- const err = validateAmount();
- if (err) { submitError = err; return; }
- if (!selectedWalletId) { submitError = 'Select a payout wallet'; return; }
-
- const wallet = wallets.find(w => w.id === selectedWalletId);
- if (!wallet) { submitError = 'Wallet not found'; return; }
-
- const lamports = Math.round(parseFloat(amountDisplay) * 1_000_000);
-
- submitting = true;
- try {
- const res = await fetch('/api/billing/withdrawals', {
- method: 'POST',
- credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- amount: lamports,
- currency_mint: currencyMint ?? 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
- chain: wallet.chain,
- to_address: wallet.address,
- }),
- });
-
- const json = await res.json();
- if (!res.ok) {
- if (res.status === 422) {
- submitError = 'Insufficient balance';
- } else {
- submitError = json.error_description ?? json.error ?? 'Request failed';
- }
- return;
- }
-
- submitSuccess = 'Withdrawal requested. Processing typically takes 1-2 business days.';
- amountDisplay = '';
- await loadAll();
- } catch (e) {
- submitError = e.message;
- } finally {
- submitting = false;
- }
- }
-
- async function prevPage() {
- if (histOffset === 0) return;
- histOffset = Math.max(0, histOffset - HIST_LIMIT);
- await loadHistory();
- }
-
- async function nextPage() {
- if (histOffset + HIST_LIMIT >= withdrawalsTotal) return;
- histOffset += HIST_LIMIT;
- await loadHistory();
- }
-
- $: noWallets = wallets.length === 0;
- $: amountErr = amountDisplay ? validateAmount() : null;
-
- onMount(loadAll);
-</script>
-
-<section class="pt-10 pb-20 px-4 max-w-2xl mx-auto">
- <div class="flex items-center gap-3 mb-8">
- <button
- class="text-ink-soft hover:text-ink text-sm"
- on:click={() => route.set('chat')}
- >← Back</button>
- <h1 class="font-serif text-2xl font-semibold text-ink">Revenue &amp; Withdrawals</h1>
- </div>
-
- {#if loading}
- <p class="text-ink-soft text-sm">Loading…</p>
- {:else if needsSignIn}
- <div class="rounded-xl border border-rule bg-white p-6 text-center">
- <p class="text-sm text-ink">Sign in to see what your agents have earned.</p>
- <button
- class="mt-4 h-10 rounded-full bg-black px-5 text-sm font-medium text-white transition-colors hover:bg-[#333]"
- on:click={() => route.set('signin')}
- >Sign in</button>
- </div>
- {:else if loadError}
- <div class="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
- <p>{loadError}</p>
- <button class="mt-3 rounded-full border border-red-300 px-3 py-1 text-xs font-medium hover:bg-red-100" on:click={loadAll}>
- Retry
- </button>
- </div>
- {:else}
-
- <!-- Summary cards -->
- {#if revenueData}
- <div class="grid grid-cols-2 gap-3 mb-8 sm:grid-cols-4">
- {#each [
- { label: 'Gross Earnings', value: revenueData.summary.gross_total },
- { label: 'Platform Fees', value: revenueData.summary.fee_total, neg: true },
- { label: 'Net Earnings', value: revenueData.summary.net_total },
- { label: 'Payments', count: revenueData.summary.payment_count },
- ] as card}
- <div class="rounded-xl border border-rule bg-white p-4">
- <p class="text-xs text-ink-soft mb-1">{card.label}</p>
- {#if card.count !== undefined}
- <p class="text-lg font-semibold text-ink">{card.count}</p>
- {:else}
- <p class="text-lg font-semibold {card.neg ? 'text-red-600' : 'text-ink'}">
- {card.neg ? '−' : ''}{formatUSDC(card.value)}
- </p>
- {/if}
- </div>
- {/each}
- </div>
- {/if}
-
- <!-- Withdraw Earnings -->
- <div class="rounded-2xl border border-rule bg-white p-6 mb-6">
- <h2 class="font-semibold text-ink mb-4">Withdraw Earnings</h2>
-
- <!-- Available balance -->
- <div class="flex items-baseline gap-2 mb-5">
- <span class="text-sm text-ink-soft">Available balance</span>
- <span class="text-xl font-semibold text-ink">{formatUSDC(availableBalance)}</span>
- </div>
-
- {#if noWallets}
- <div class="rounded-xl bg-paper border border-rule p-4 text-sm text-ink-soft mb-4">
- No payout wallet configured.
- <button class="text-ink underline ml-1" on:click={() => route.set('settings/payout-wallets')}>
- Add a wallet
- </button>
- to enable withdrawals.
- </div>
- {/if}
-
- <!-- Amount -->
- <label class="block mb-4">
- <span class="text-xs font-medium text-ink-soft mb-1.5 block">Amount (USDC)</span>
- <div class="flex gap-2">
- <input
- type="number"
- min="0"
- step="0.000001"
- bind:value={amountDisplay}
- disabled={noWallets}
- placeholder="0.00"
- class="flex-1 h-11 px-4 rounded-xl border border-rule bg-white focus:outline-none focus:border-ink disabled:bg-paper disabled:text-ink-faint text-sm"
- />
- <button
- type="button"
- disabled={noWallets || availableBalance === 0}
- on:click={setMax}
- class="h-11 px-4 rounded-xl border border-rule bg-white text-sm font-medium text-ink hover:bg-paper disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
- >Max</button>
- </div>
- {#if amountErr}
- <p class="text-xs text-red-500 mt-1">{amountErr}</p>
- {/if}
- </label>
-
- <!-- Wallet selector -->
- <label class="block mb-5">
- <span class="text-xs font-medium text-ink-soft mb-1.5 block">To wallet</span>
- <div class="flex gap-2 items-center">
- {#if wallets.length > 0}
- <select
- bind:value={selectedWalletId}
- class="flex-1 h-11 px-4 rounded-xl border border-rule bg-white focus:outline-none focus:border-ink text-sm"
- >
- {#each wallets as w}
- <option value={w.id}>
- {w.chain.toUpperCase()} · {truncateAddr(w.address)}{w.is_default ? ' (default)' : ''}
- </option>
- {/each}
- </select>
- {:else}
- <div class="flex-1 h-11 px-4 rounded-xl border border-rule bg-paper flex items-center text-sm text-ink-faint">
- No wallets
- </div>
- {/if}
- <button
- class="text-sm text-ink underline whitespace-nowrap"
- on:click={() => route.set('settings/payout-wallets')}
- >+ Add wallet</button>
- </div>
- </label>
-
- <!-- Feedback messages -->
- {#if submitSuccess}
- <div class="rounded-xl border border-green-200 bg-green-50 p-3 text-sm text-green-800 mb-4">
- {submitSuccess}
- </div>
- {/if}
- {#if submitError}
- <div class="rounded-xl border border-red-200 bg-red-50 p-3 text-sm text-red-700 mb-4">
- {submitError}
- </div>
- {/if}
-
- <!-- Submit -->
- <div title={noWallets ? 'Add a payout wallet first' : ''}>
- <button
- type="button"
- disabled={noWallets || submitting || availableBalance === 0}
- on:click={submit}
- class="w-full h-11 rounded-full bg-black text-white text-sm font-medium hover:bg-ink disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
- >
- {submitting ? 'Requesting…' : 'Request Withdrawal'}
- </button>
- </div>
- </div>
-
- <!-- Withdrawal History -->
- <div class="rounded-2xl border border-rule bg-white p-6">
- <h2 class="font-semibold text-ink mb-4">Withdrawal History</h2>
-
- {#if withdrawals.length === 0}
- <p class="text-sm text-ink-faint">No withdrawals yet.</p>
- {:else}
- <div class="overflow-x-auto">
- <table class="w-full text-sm">
- <thead>
- <tr class="border-b border-rule">
- <th class="py-2 pr-4 text-left text-xs font-medium text-ink-soft">Date</th>
- <th class="py-2 pr-4 text-left text-xs font-medium text-ink-soft">Amount</th>
- <th class="py-2 pr-4 text-left text-xs font-medium text-ink-soft">Wallet</th>
- <th class="py-2 pr-4 text-left text-xs font-medium text-ink-soft">Status</th>
- <th class="py-2 text-left text-xs font-medium text-ink-soft">Tx</th>
- </tr>
- </thead>
- <tbody>
- {#each withdrawals as w}
- {@const txUrl = explorerUrl(w)}
- <tr class="border-b border-rule last:border-0">
- <td class="py-3 pr-4 text-ink-soft whitespace-nowrap">
- {new Date(w.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
- </td>
- <td class="py-3 pr-4 font-mono text-ink whitespace-nowrap">
- {formatUSDC(w.amount)}
- </td>
- <td class="py-3 pr-4 font-mono text-ink-soft whitespace-nowrap">
- {truncateAddr(w.to_address)}
- </td>
- <td class="py-3 pr-4">
- <span class="inline-block rounded-full px-2 py-0.5 text-xs font-medium {STATUS_CLASS[w.status] ?? 'bg-gray-100 text-gray-700'}">
- {STATUS_LABEL[w.status] ?? w.status}
- </span>
- </td>
- <td class="py-3">
- {#if txUrl}
- <a href={txUrl} target="_blank" rel="noopener noreferrer"
- class="text-xs text-indigo-600 hover:underline font-mono">
- {w.tx_signature.slice(0, 8)}…
- </a>
- {:else}
- <span class="text-xs text-ink-faint">-</span>
- {/if}
- </td>
- </tr>
- {/each}
- </tbody>
- </table>
- </div>
-
- <!-- Pagination -->
- {#if withdrawalsTotal > HIST_LIMIT}
- <div class="flex items-center justify-between mt-4 text-sm text-ink-soft">
- <span>{histOffset + 1}-{Math.min(histOffset + HIST_LIMIT, withdrawalsTotal)} of {withdrawalsTotal}</span>
- <div class="flex gap-2">
- <button
- disabled={histOffset === 0}
- on:click={prevPage}
- class="px-3 py-1 rounded-lg border border-rule hover:bg-paper disabled:opacity-40 disabled:cursor-not-allowed"
- >← Prev</button>
- <button
- disabled={histOffset + HIST_LIMIT >= withdrawalsTotal}
- on:click={nextPage}
- class="px-3 py-1 rounded-lg border border-rule hover:bg-paper disabled:opacity-40 disabled:cursor-not-allowed"
- >Next →</button>
- </div>
- </div>
- {/if}
- {/if}
- </div>
-
- {/if}
-</section>
diff --git a/docs/x402-revenue.md b/docs/x402-revenue.md
deleted file mode 100644
index 6dbd259a8..000000000
--- a/docs/x402-revenue.md
+++ /dev/null
@@ -1,480 +0,0 @@
-# x402 Revenue & Receipts
-
-Every time someone pays one of three.ws's [paid endpoints](x402-endpoints.md), the
-settlement is recorded. This page is the reference for **where that money is
-recorded**, how to read endpoint revenue, and how the durable receipt is issued to
-the buyer.
-
-> Source: settlement persistence
-> [`api/_lib/x402/audit-log.js`](../api/_lib/x402/audit-log.js), receipt storage
-> [`api/_lib/x402/receipt-storage.js`](../api/_lib/x402/receipt-storage.js),
-> revenue report [`api/_lib/x402/revenue-analytics.js`](../api/_lib/x402/revenue-analytics.js),
-> served by [`api/x402/analytics.js`](../api/x402/analytics.js).
-
----
-
-## Two directions of money — don't confuse them
-
-three.ws records value moving in **two opposite directions**, in two different
-tables. They never overlap, and mixing them up will double-count your numbers.
-
-| Direction | Meaning | Table | Surfaced by |
-| -------------- | ------------------------------------------------------------------------ | ---------------------- | ------------------------------------------------ |
-| **Revenue IN** | Money paid **to** our endpoints for using them | `x402_audit_log` | `/api/x402/analytics?report=revenue` (this page) |
-| **Spend OUT** | Money an agent's wallet **paid out** (tips, trades, agent-to-agent x402) | `agent_custody_events` | The [Money Pulse](money-feed.md) at `/api/pulse` |
-
-The [Money Pulse](money-feed.md) shows the agent economy — one agent paying
-another, tips, launches. **This page is the other side of the ledger:** the
-platform's own endpoint revenue. A call to `/api/x402/token-intel` writes a
-**revenue** row in `x402_audit_log`; it is not an `agent_custody_events` spend and
-does not appear in the Money Pulse.
-
-### Live view — `/x402-revenue`
-
-There is a public, live dashboard of this ledger at
-[`/x402-revenue`](https://three.ws/x402-revenue): gross revenue, the top-earning
-endpoints, the settlement success rate, and a real-time feed of each settlement
-(endpoint, amount, network, payer, explorer link) the moment it lands. It is the
-revenue mirror of the [Money Pulse](https://three.ws/pulse) and reads the public,
-unauthenticated `GET /api/x402-revenue` (operational fields like IP and user agent
-are never exposed — only the on-chain-public route, amount, payer, and tx).
-
-### The public API: `GET /api/x402-revenue`
-
-No key, no auth, CORS open. Four views:
-
-| Request | Returns |
-| --- | --- |
-| `?view=stats&period=24h\|7d\|30d\|all` | totals, fee splits, per-endpoint, per-network, hourly/daily series, momentum vs the prior window, settlement health |
-| `?view=feed&limit=30&cursor=<iso>` | recent settlements, newest first, keyset-paged |
-| `?since=<iso>` | delta poll: only settlements newer than the cursor, never cached |
-| `?view=export&period=24h` | CSV of the window (max 5000 rows) |
-
-`?endpoint=<slug>` and `?network=<chain>` filter the feed and the export.
-
-**Chain values are CAIP-2, filters are chain families.** The ledger stores
-`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp` and `eip155:8453`, so every settlement
-also carries a folded family slug and a readable label
-([`api/_lib/x402/revenue-networks.js`](../api/_lib/x402/revenue-networks.js)):
-
-```jsonc
-{
- "route": "/api/x402/token-intel",
- "network": "eip155:8453", // raw ledger value, unchanged
- "network_family": "base", // what ?network= filters by
- "network_label": "Base", // what the UI renders
- "amount_usd": 0.001,
- "tx_url": "https://basescan.org/tx/0x…" // that chain's explorer, null if unknown
-}
-```
-
-`?network=` accepts the family slug (`solana`, `base`, `bsc`), a legacy bare name,
-or a full CAIP-2 id: all three select the same rows, and an unrecognised value
-drops the filter instead of returning an empty feed. `by_network` in the stats
-view is folded the same way, one row per family with the raw ids it covers:
-
-```bash
-curl -s "https://three.ws/api/x402-revenue?view=stats&period=24h" | jq '.data.by_network'
-# [ { "network": "solana", "label": "Solana", "count": 414, "gross_usd": 8.508,
-# "caip": ["solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"] } ]
-
-curl -s "https://three.ws/api/x402-revenue?view=feed&limit=5&network=base" | jq '.data.count'
-```
-
-CSV columns: `timestamp,endpoint,network,chain,amount_usd,asset,payer,tx_hash,tx_url`
-(`network` is the raw CAIP-2 id, `chain` its readable label).
-
-**Malformed params answer 4xx, not 5xx.** `?since=` and `?cursor=` are bound into
-a `::timestamptz` cast, so an unparseable value is rejected before it reaches the
-query rather than surfacing as an opaque 500:
-
-```bash
-curl -s "https://three.ws/api/x402-revenue?since=notadate"
-# {"error":"invalid_since","error_description":"`since` must be an ISO 8601 timestamp"}
-```
-
-`?endpoint=` is sanitized to a slug (`../../etc/passwd` becomes `etcpasswd`), and
-the response echoes the sanitized value in `data.filter.endpoint`, so the filter
-you read back is always the filter that ran. `?period=` and `?network=` fall back
-to the default instead of erroring: an unrecognised period is `24h`, an
-unrecognised network drops the filter.
-
----
-
-## The settlement flow
-
-When a buyer pays a paid endpoint, the shared handler
-([`api/_lib/x402-paid-endpoint.js`](../api/_lib/x402-paid-endpoint.js)) runs:
-
-1. **Challenge** — no `X-PAYMENT` header → respond `402 Payment Required` with the
- accepted networks, asset, price, and pay-to address.
-2. **Verify** — the buyer retries with an `X-PAYMENT` header; the facilitator's
- `/verify` confirms the signed payment matches the requirement
- ([`api/_lib/x402-spec.js`](../api/_lib/x402-spec.js) `verifyPayment()`).
-3. **Settle** — the facilitator's `/settle` (or, for BSC, a direct on-chain
- `pay(bytes32)` contract call) moves the USDC (`settlePayment()`).
-4. **Persist** — `logPaymentEvent()` writes one row to `x402_audit_log`, and a
- signed receipt is stored in `x402_receipts`.
-5. **Run + respond** — the endpoint logic executes and returns the result.
-
-Steps 4's writes are fire-and-forget (`queueMicrotask`) with a connection-level
-retry, so a transient DB blip never silently drops a settled payment.
-
----
-
-## The revenue ledger — `x402_audit_log`
-
-This is the **single source of truth for money flowing through our endpoints.**
-Every payment event lands here — settled, failed, and access-control events alike.
-
-```sql
-CREATE TABLE x402_audit_log (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- event_type TEXT NOT NULL, -- 'payment_settled' | 'payment_failed'
- -- | 'siwx_grant' | 'siwx_access' | 'bypass_granted'
- route TEXT NOT NULL, -- e.g. '/api/x402/token-intel'
- resource_url TEXT,
- payer TEXT, -- wallet address
- network TEXT, -- CAIP-2 id, e.g. 'solana:5eykt4Us…' | 'eip155:8453'
- amount_atomics TEXT, -- USDC atomics (6 decimals): '10000' = $0.01
- asset TEXT,
- tx_hash TEXT,
- settlement_status TEXT, -- 'success' | 'failed'
- facilitator_response JSONB,
- duration_ms INTEGER,
- ip_address TEXT,
- user_agent TEXT,
- metadata JSONB,
- created_at TIMESTAMPTZ DEFAULT NOW()
-);
-```
-
-Schema:
-[`api/_lib/migrations/2026-05-27-x402-audit-log.sql`](../api/_lib/migrations/2026-05-27-x402-audit-log.sql).
-Filter `event_type = 'payment_settled'` for revenue; `amount_atomics` is USDC at 6
-decimals, so divide by `1e6` for dollars.
-
-### Reading revenue directly
-
-Total settled revenue and unique payers over the last 24h:
-
-```sql
-SELECT
- count(*) AS payments,
- count(DISTINCT payer) AS unique_payers,
- sum((amount_atomics)::numeric / 1e6) AS gross_usd
-FROM x402_audit_log
-WHERE event_type = 'payment_settled'
- AND created_at >= now() - interval '24 hours';
-```
-
-Revenue by endpoint, last 7 days, top 10:
-
-```sql
-SELECT
- route,
- count(*) AS calls,
- sum((amount_atomics)::numeric / 1e6) AS gross_usd
-FROM x402_audit_log
-WHERE event_type = 'payment_settled'
- AND created_at >= now() - interval '7 days'
-GROUP BY route
-ORDER BY gross_usd DESC
-LIMIT 10;
-```
-
----
-
-## The revenue report — `/api/x402/analytics`
-
-You don't have to query SQL. The `analytics` endpoint serves the same numbers,
-pre-aggregated. It is itself a [paid endpoint](x402-endpoints.md) ($0.005 default).
-It is a `POST` endpoint: pass `report` and `period` in the JSON body:
-
-```bash
-# After settling the 402 challenge (see the x402 buyer client doc), retry with:
-curl -s -X POST https://three.ws/api/x402/analytics \
- -H 'content-type: application/json' \
- -H "X-PAYMENT: <settled-payment-header>" \
- -d '{"report":"revenue","period":"24h"}'
-```
-
-`report` accepts: `revenue`, `x402_volume`, `clubs`, `marketplace`,
-`agent_leaderboard`, `sniper_trades`, `user_activity`. `period` accepts `1h`,
-`6h`, `24h`, `7d`, `30d`, `all`.
-
-The `revenue` report shape
-([`revenue-analytics.js`](../api/_lib/x402/revenue-analytics.js)); money fields
-are serialized as fixed 6-decimal strings:
-
-```json
-{
- "report": "revenue",
- "period": "24h",
- "since": "2026-06-29T00:00:00.000Z",
- "generated_at": "2026-06-30T00:00:00.000Z",
- "totals": {
- "gross_usd": "12.340000",
- "net_platform_usd": "11.900000",
- "settlement_fee_usd": "0.440000",
- "total_payments": 247,
- "failed_payments": 3,
- "unique_payers": 18,
- "avg_payment_usd": "0.050000"
- },
- "fee_splits": {
- "gross_usd": "12.340000",
- "settlement_fee_usd": "0.440000",
- "net_platform_usd": "11.900000",
- "effective_fee_rate": 0.0357,
- "fee_per_settlement_usd": "0.001800",
- "fee_source": "..."
- },
- "by_endpoint": [
- { "endpoint": "/api/x402/token-intel", "count": 120, "gross_usd": "1.200000", "share": 0.097 }
- ],
- "top_endpoint": { "endpoint": "/api/x402/token-intel", "count": 120, "gross_usd": "1.200000" }
-}
-```
-
-`net_platform_usd` is gross minus the estimated on-chain settlement fee — what the
-platform actually keeps. `failed_payments` counts `event_type = 'payment_failed'`
-rows in the same window, so you can watch the settlement success rate.
-
----
-
-## Receipts — `x402_receipts`
-
-Each successful settlement also issues the buyer a durable, signed receipt
-([`receipt-storage.js`](../api/_lib/x402/receipt-storage.js)):
-
-```sql
-CREATE TABLE x402_receipts (
- id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
- payer text NOT NULL, -- buyer wallet
- network text NOT NULL,
- resource_url text NOT NULL, -- what they paid for
- format text NOT NULL,
- receipt jsonb NOT NULL, -- the signed receipt artifact
- transaction text, -- settlement tx
- amount_atomics text, -- what it cost (atomic units)
- asset text, -- the settlement asset (USDC mint/contract)
- issued_at timestamptz NOT NULL DEFAULT now()
-);
-```
-
-A buyer reads **their own** receipts at
-[`/api/x402/my-receipts`](x402-endpoints.md) — that endpoint is free but gated by
-a wallet signature (SIWX), so a buyer proves ownership of the `payer` address
-rather than paying again.
-
-### The signed artifact vs. our row
-
-These are two different things and the difference matters:
-
-- **The signed artifact** (`receipt` column) follows the x402 Offer & Receipt
- spec §5.1. It carries no amount at all, and it omits `transaction` entirely
- whenever the endpoint declares `includeTxHash: false`, the spec §5.2 privacy
- default. That is what goes out on the wire, and it is what a third party
- verifies against our issuer key.
-- **The row** is our own audit trail. It records the settlement tx and the
- amount/asset we already had in hand at issue time, even when the artifact
- omits them. The wire format and its privacy properties are unchanged; these
- columns are only ever returned to the wallet that signed for its own
- receipts.
-
-Receipts written before 2026-07-28 have `amount_atomics` and `asset` null. The
-Receipt Vault reports that honestly ("2 of 3 priced") rather than
-under-reporting a total.
-
-### Verifying a receipt
-
-The issuer signs with an Ed25519 JWK (`OFFER_RECEIPT_FORMAT=jws`); the `kid` is
-`did:web:three.ws#key-1`, and the public key is published at
-[`https://three.ws/.well-known/did.json`](https://three.ws/.well-known/did.json)
-(served by [`api/x402/did.js`](../api/x402/did.js)). Anyone holding a receipt
-can resolve that DID document and verify the signature without trusting us.
-When neither `OFFER_RECEIPT_JWK` (jws) nor
-`OFFER_RECEIPT_SIGNING_PRIVATE_KEY` (eip712) is set, no receipts are issued or
-stored at all: the x402 wire format stays valid, the extension is purely
-additive.
-
-### The buyer's view: `/receipts`
-
-[`/receipts`](https://three.ws/receipts) is the Receipt Vault: the buyer-facing
-UI over `/api/x402/my-receipts`. Connect a Solana or EVM wallet, sign one
-read-only message, and every receipt ever issued to that wallet is listed with
-its endpoint, amount, network, and settlement tx (explorer-linked), plus a
-per-receipt JSON download of the full signed artifact and a CSV export.
-
-The signing message is a fixed four-line string and must stay byte-identical on
-both sides. [`src/receipts-lib.js`](../src/receipts-lib.js)
-`buildReceiptsMessage()` and [`api/x402/my-receipts.js`](../api/x402/my-receipts.js)
-`buildExpectedMessage()`:
-
-```
-three.ws x402 receipts read
-Network: solana
-Address: <base58 pubkey, verbatim>
-Issued At: <ISO timestamp>
-```
-
-EVM addresses are lower-cased in the message (matching how the storage layer
-normalizes them); Solana base58 is case-sensitive and stays verbatim. The
-signature is valid for 5 minutes server-side. Fetch it yourself:
-
-```bash
-# after signing the message above with the payer wallet
-curl -s "https://three.ws/api/x402/my-receipts?\
-address=$ADDRESS&signature=$SIGNATURE&issuedAt=$ISSUED_AT&network=solana&limit=50"
-```
-
-`/receipts` is the buyer-side mirror of `/x402-revenue`: that page is what the
-platform earns, this one is what a given wallet spent.
-
-### Anti-replay — `bsc_consumed_tx`
-
-For BSC direct-scheme settlements (where there is no facilitator and the buyer
-pays the `ThreeWSPayments` contract directly), each on-chain `Payment` tx is
-recorded in `bsc_consumed_tx` (`tx_hash` primary key) the first time it is spent,
-so the same on-chain payment can never be replayed against two requests.
-
----
-
-## Proof-of-volume — `x402_volume_metrics`
-
-`x402_audit_log` is the per-call ledger (one row per settlement). Alongside it,
-the **Volume Bootstrap Loop** (autonomous registry `self/026`,
-[`pipelines/volume-bootstrap-loop.js`](../api/_lib/x402/pipelines/volume-bootstrap-loop.js))
-maintains a compact **rolling aggregate keyed on endpoint** in
-`x402_volume_metrics`. On each sweep the loop round-robins the catalog of cheap
-paid self endpoints, pays each a real on-chain USDC payment, and upserts one row
-per endpoint — accumulating call / success / fail counts, total + last USDC
-spent, last tx signature, last status, and first/last call timestamps.
-
-```sql
-CREATE TABLE x402_volume_metrics (
- endpoint_key text PRIMARY KEY, -- one row per paid endpoint
- service_name text,
- endpoint_path text,
- network text NOT NULL DEFAULT 'solana:mainnet',
- asset text,
- call_count bigint NOT NULL DEFAULT 0,
- success_count bigint NOT NULL DEFAULT 0,
- fail_count bigint NOT NULL DEFAULT 0,
- total_spent_atomic bigint NOT NULL DEFAULT 0, -- USDC atomics, lifetime
- last_amount_atomic bigint NOT NULL DEFAULT 0,
- last_success boolean,
- last_status int,
- last_tx_signature text,
- last_error text,
- last_run_id uuid,
- first_called_at timestamptz DEFAULT now(),
- last_called_at timestamptz DEFAULT now()
-);
-```
-
-Schema:
-[`api/_lib/migrations/20260629110000_x402_volume_metrics.sql`](../api/_lib/migrations/20260629110000_x402_volume_metrics.sql)
-(the pipeline also creates it lazily via `ensureSchema`). It feeds two things the
-growth + status surfaces read: **proof-of-volume** (total settled calls and USDC
-volume per endpoint — the metric agentic.market ranks facilitators on) and
-**per-endpoint liveness** (`last_success` / `last_called_at` confirm each paid
-endpoint is up). Add an endpoint to `api/_lib/x402/ring-catalog.js` with
-`autobuy: true` and the cursor and ledger pick it up automatically.
-
-> **Synthetic vs organic — do not conflate them.** The Volume Bootstrap Loop pays
-> our **own** endpoints from our **own** seed wallet, and those endpoints settle
-> to the platform's own `X402_PAY_TO_*` treasury. Every transaction is real and
-> on-chain — but the _demand_ is synthetic: it is the platform paying itself, a
-> liveness canary, not external buyers. It is legitimate as **synthetic
-> monitoring** (proving every paid endpoint is live) and is bounded small by
-> design (see the budget knobs in [Autonomous x402 loop](autonomous-x402.md)).
-> It is **not** marketplace demand. Any headline "marketplace volume" or
-> facilitator-ranking number we publish must **exclude the seed wallet's own
-> calls** — filter `x402_audit_log` by `payer` to separate organic settlements
-> from the loop's synthetic ones. Reporting self-paid round-trips as organic
-> volume is wash volume: real transactions, fake demand, and trivially detectable
-> by anyone clustering the seed wallet on-chain. The honest path to real volume
-> is external demand (discovery, real `agent_hire` commerce, the
-> [Circulation engine](circulation-engine.md)), not a bigger self-paid sweep.
-
----
-
-## Reconciliation — `payment_reconciliation`
-
-A live payment platform's books must match the chain. The **Payment Revenue
-Reconciliation** job (autonomous registry `self/027`, runs **daily**,
-[`revenue-reconciliation.js`](../api/_lib/x402/revenue-reconciliation.js)) is the
-financial-integrity watchdog. Each run pulls recent records that claim settlement
-from both books — `x402_autonomous_log` (outbound spend) and
-`agent_payment_intents` (inbound revenue) — verifies each Solana signature
-on-chain via `getSignatureStatuses` (batched, full-history search), and upserts
-one verdict row per record into `payment_reconciliation`.
-
-```sql
-CREATE TABLE payment_reconciliation (
- id bigserial PRIMARY KEY,
- source text NOT NULL, -- 'autonomous_log' | 'payment_intent'
- source_ref text NOT NULL, -- row id within that book
- tx_signature text,
- network text,
- amount_atomic bigint,
- db_status text NOT NULL, -- what the book claims
- chain_status text NOT NULL, -- confirmed | failed_onchain | missing_onchain
- -- | missing_signature | skipped_non_solana | unknown
- reconciled boolean NOT NULL,
- discrepancy text, -- null when reconciled
- detail jsonb,
- run_id uuid,
- first_seen_at timestamptz NOT NULL DEFAULT now()
-);
-```
-
-Schema:
-[`api/_lib/migrations/20260629120000_payment_reconciliation.sql`](../api/_lib/migrations/20260629120000_payment_reconciliation.sql).
-The job is **read-only**, so it runs even when the spend wallet is absent (it
-falls back to a keyless RPC connection; the `/api/x402-status` probe it uses is
-free). A row with `reconciled = false` is a financial-integrity alert — the DB
-recorded a settlement the chain does not corroborate. The ops surface watches:
-
-```sql
--- Unreconciled settlements in the last day — investigate before they corrupt accounting.
-SELECT source, source_ref, tx_signature, db_status, chain_status, discrepancy
-FROM payment_reconciliation
-WHERE reconciled = false
- AND first_seen_at >= now() - interval '24 hours'
-ORDER BY first_seen_at DESC;
-```
-
-`chain_status` classifies each discrepancy: `failed_onchain` (tx reverted),
-`missing_onchain` (no tx exists), `missing_signature` (settled but no signature
-kept). EVM/Base settlements are `skipped_non_solana` (not verified here).
-
----
-
-## Driving volume through these endpoints
-
-Revenue only exists if the endpoints get called. Two systems drive **organic**
-calls: the [Circulation engine](circulation-engine.md) drives real
-agent-to-agent commerce, and the [Autonomous x402 loop](autonomous-x402.md)'s
-oracle/sniper pipelines pay our intel endpoints to feed real downstream
-decisions. Both settle **real** USDC through the flow above, from real
-counterparties.
-
-Separately, the **Volume Bootstrap Loop** (above) generates **synthetic**
-liveness traffic by paying our own endpoints from the seed wallet. Every row in
-`x402_audit_log` is a verifiable on-chain settlement — but "verifiable" is not
-"organic." When you report revenue or volume, decide explicitly whether the
-number is meant to represent external demand (exclude the seed wallet) or total
-settled activity (include it), and label it as such.
-
----
-
-## Related
-
-- [x402 paid endpoints](x402-endpoints.md) — the catalog of what charges and how much.
-- [x402 protocol](x402.md) — the challenge / verify / settle mechanics.
-- [x402 buyer client](x402-buyer.md) — how to settle a 402 challenge in code.
-- [Autonomous x402 loop](autonomous-x402.md) — the scheduled buyer that drives volume, including the Volume Bootstrap Loop and the reconciliation job.
-- [Money feed](money-feed.md) — the agent-spend side of the ledger (the Money Pulse), distinct from endpoint revenue.
diff --git a/marketing/the-first-19-weeks/images/x402-revenue.png b/marketing/the-first-19-weeks/images/x402-revenue.png
deleted file mode 100644
index d5c0a6698..000000000
Binary files a/marketing/the-first-19-weeks/images/x402-revenue.png and /dev/null differ
diff --git a/packages/billing-mcp/src/tools/get-revenue.js b/packages/billing-mcp/src/tools/get-revenue.js
deleted file mode 100644
index 8e3c7fa99..000000000
--- a/packages/billing-mcp/src/tools/get-revenue.js
+++ /dev/null
@@ -1,67 +0,0 @@
-// `get_revenue` — earnings for the agents you own: the income side of billing.
-// Account-scoped (session). Read-only.
-//
-// Wraps GET /api/billing/revenue. Aggregates agent_revenue_events for your
-// agents over a window into gross/fee/net totals, a per-skill breakdown, and a
-// time series at day/week/month granularity. Also surfaces creator-subscription
-// income (USD, settled directly to your wallet — kept separate from the
-// withdrawable pool) and a reconciliation summary.
-
-import { z } from 'zod';
-
-import { apiRequest } from '../lib/api.js';
-
-export const def = {
- name: 'get_revenue',
- title: 'My agents’ earnings (revenue + subscriptions)',
- annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },
- description:
- 'Earnings for the agents YOU own — the income side of your account economics (what you EARNED, vs what you ' +
- 'were charged in query_usage). Returns `summary` (gross_total, fee_total, net_total in token atomics, ' +
- 'plus payment_count, currency_mint, chain), `by_skill` (net_total + count per skill, top first), ' +
- '`timeseries` (net_total + count bucketed by granularity), `subscriptions` (creator-subscription income in ' +
- 'USD — income_usd, payment_count, active_subscribers, plan_count — settled directly to your wallet, kept ' +
- 'separate from the withdrawable pool so units never mix), `subscription_timeseries`, and `reconciliation`. ' +
- 'Optional `agent_id` narrows to one agent; `from`/`to` set the window (default last 30 days); `granularity` ' +
- 'is day | week | month (default day). Requires THREE_WS_SESSION. Read-only.',
- inputSchema: {
- agent_id: z
- .string()
- .uuid('agent_id must be a UUID')
- .optional()
- .describe('Limit to a single agent you own (UUID). Omit to aggregate across all your agents.'),
- from: z
- .string()
- .optional()
- .describe('Window start, ISO-8601. Defaults to 30 days ago.'),
- to: z
- .string()
- .optional()
- .describe('Window end, ISO-8601. Defaults to now.'),
- granularity: z
- .enum(['day', 'week', 'month'])
- .default('day')
- .describe('Time-series bucket size (default day).'),
- },
- async handler(args) {
- const data = await apiRequest('/api/billing/revenue', {
- auth: true,
- query: {
- agent_id: args?.agent_id,
- from: args?.from,
- to: args?.to,
- granularity: args?.granularity ?? 'day',
- },
- });
-
- return {
- ok: true,
- summary: data?.summary ?? null,
- by_skill: Array.isArray(data?.by_skill) ? data.by_skill : [],
- timeseries: Array.isArray(data?.timeseries) ? data.timeseries : [],
- subscriptions: data?.subscriptions ?? null,
- subscription_timeseries: Array.isArray(data?.subscription_timeseries) ? data.subscription_timeseries : [],
- reconciliation: data?.reconciliation ?? null,
- };
- },
-};
diff --git a/pages/dashboard-next/analytics.html b/pages/dashboard-next/analytics.html
deleted file mode 100644
index 17f4c5022..000000000
--- a/pages/dashboard-next/analytics.html
+++ /dev/null
@@ -1,19 +0,0 @@
-<!doctype html>
-<html lang="en">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width,initial-scale=1" />
- <title data-i18n="dashboard_next_analytics.meta_title">Analytics · Dashboard · three.ws</title>
- <meta name="description" content="Revenue over time, revenue by skill, widget views and chats, conversion funnel, and per-agent performance across your three.ws agents." />
- <meta name="robots" content="noindex" />
- <link rel="icon" href="/favicon.ico" />
- <link rel="stylesheet" href="/fonts/fonts.css" />
- <link rel="stylesheet" href="/dashboard-next/shell.css" />
- </head>
- <body>
- <script src="/embed.js"></script>
- <script type="module" src="/src/dashboard-next/pages/analytics.js"></script>
- <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
- <script type="module" src="/i18n.js"></script>
-</body>
-</html>
diff --git a/pages/x402-revenue.html b/pages/x402-revenue.html
deleted file mode 100644
index 5e39236a0..000000000
--- a/pages/x402-revenue.html
+++ /dev/null
@@ -1,321 +0,0 @@
-<!doctype html>
-<html lang="en">
- <head>
- <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" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title data-i18n="x402_revenue.meta_title">Endpoint Revenue · three.ws</title>
- <meta
- name="description"
- content="The live revenue layer — real-time USDC flowing into three.ws's own x402 paid endpoints. Live chart, top-earning endpoints, network split, and every settlement the moment it lands on-chain. Every payment is real and explorer-verifiable."
- data-i18n-attr="content:x402_revenue.meta_description"/>
- <meta property="og:type" content="website" />
- <meta property="og:site_name" content="three.ws" />
- <meta property="og:url" content="https://three.ws/x402-revenue" />
- <meta property="og:title" content="Endpoint Revenue · three.ws" data-i18n-attr="content:x402_revenue.meta_og_title"/>
- <meta
- property="og:description"
- content="A live stream of real USDC paid into three.ws's x402 endpoints — gross revenue, a live chart, top-earning endpoints, and every settlement the moment it lands on-chain."
- data-i18n-attr="content:x402_revenue.meta_og_description"/>
- <meta
- property="og:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Endpoint+Revenue&amp;d=The+live+revenue+layer%3A+real+USDC+flowing+into+three.ws%27s+own+x402+paid+endpoints.+A+live+revenue+chart%2C+gross%2Fnet%2Fsuccess-rate+KPIs%2C+momentum+vs+the+prior&amp;p=%2Fx402-revenue"
- />
- <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" />
- <meta name="twitter:title" content="Endpoint Revenue · three.ws" data-i18n-attr="content:x402_revenue.meta_twitter_title"/>
- <meta
- name="twitter:description"
- content="A live stream of real USDC paid into three.ws's x402 endpoints — the moment each settlement lands on-chain."
- data-i18n-attr="content:x402_revenue.meta_twitter_description"/>
- <meta
- name="twitter:image"
- content="https://three.ws/api/page-og?s=crypto&amp;t=Endpoint+Revenue&amp;d=The+live+revenue+layer%3A+real+USDC+flowing+into+three.ws%27s+own+x402+paid+endpoints.+A+live+revenue+chart%2C+gross%2Fnet%2Fsuccess-rate+KPIs%2C+momentum+vs+the+prior&amp;p=%2Fx402-revenue"
- />
- <meta name="theme-color" content="#0a0a0a" />
- <link rel="icon" href="/favicon.ico" sizes="any" />
- <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
- <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
- <link rel="manifest" href="/manifest.webmanifest" />
- <link rel="stylesheet" href="/fonts/fonts.css" />
- <link rel="stylesheet" href="/nav.css" />
- <link rel="stylesheet" href="/src/ui-juice.css" />
- <link rel="stylesheet" href="/src/x402-revenue.css" />
- <link rel="stylesheet" href="/footer.css" />
- <script defer src="/footer-newsletter.js"></script>
- <link rel="canonical" href="https://three.ws/x402-revenue" />
- <script type="application/ld+json">
- {
- "@context": "https://schema.org",
- "@type": "WebPage",
- "name": "Endpoint Revenue",
- "description": "A live stream of real USDC paid into three.ws's x402 paid endpoints — gross revenue, a live chart, top-earning endpoints, and every settlement the moment it lands on-chain.",
- "url": "https://three.ws/x402-revenue",
- "isPartOf": { "@type": "WebSite", "name": "three.ws", "url": "https://three.ws" }
- }
- </script>
- <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
- <meta property="og:locale" content="en_US" />
- <meta property="og:image:alt" content="Endpoint Revenue — three.ws" />
- </head>
- <body>
- <header><div id="nav-container"></div></header>
- <script src="/nav.js"></script>
-
- <main class="xr-shell">
- <div class="xr-glow" aria-hidden="true"></div>
-
- <!-- ── hero ─────────────────────────────────────────────────────── -->
- <section class="xr-hero">
- <div class="xr-hero-copy">
- <p class="xr-kicker" data-i18n-html="x402_revenue.live_revenue_layer">
- <span class="xr-live-dot" aria-hidden="true"></span> Live revenue layer
- </p>
- <h1 class="xr-title" data-i18n-html="x402_revenue.endpoint_revenue">Endpoint <em>Revenue</em></h1>
- <p class="xr-sub" data-i18n-html="x402_revenue.real_usdc_flowing_into_three_ws_s">
- Real USDC flowing <strong>into</strong> three.ws's own x402 paid endpoints —
- the moment each settlement lands on-chain. The mirror of the
- <a href="/pulse">Money Pulse</a>: that feed shows what agents
- <em>spend</em>; this shows what the platform <em>earns</em>. Every row is
- real and explorer-verifiable.
- </p>
- </div>
- <div class="xr-hero-controls">
- <div class="xr-period" role="tablist" aria-label="Time window">
- <button
- type="button"
- class="xr-period-btn active"
- data-period="24h"
- role="tab"
- aria-selected="true"
- data-i18n="x402_revenue.24h">
- 24h
- </button>
- <button
- type="button"
- class="xr-period-btn"
- data-period="7d"
- role="tab"
- aria-selected="false"
- data-i18n="x402_revenue.7d">
- 7d
- </button>
- <button
- type="button"
- class="xr-period-btn"
- data-period="30d"
- role="tab"
- aria-selected="false"
- data-i18n="x402_revenue.30d">
- 30d
- </button>
- <button
- type="button"
- class="xr-period-btn"
- data-period="all"
- role="tab"
- aria-selected="false"
- data-i18n="x402_revenue.all">
- All
- </button>
- </div>
- <span class="xr-updated" id="xr-updated" aria-live="polite"></span>
- </div>
- </section>
-
- <!-- ── showpiece: big number + live chart ───────────────────────── -->
- <section class="xr-showcase" aria-label="Revenue over time">
- <div class="xr-showcase-head">
- <div class="xr-big">
- <span class="xr-big-label"
- ><span data-i18n="x402_revenue.gross_revenue">Gross revenue</span> ·
- <span id="xr-window-label" data-no-i18n>24h</span></span
- >
- <span class="xr-big-val" id="xr-c-gross">—</span>
- <span class="xr-big-sub" id="xr-c-gross-sub" data-no-i18n>settled USDC</span>
- </div>
- <div class="xr-badges">
- <span class="xr-momentum" id="xr-momentum" data-dir="flat" hidden></span>
- <div class="xr-runrate">
- <span class="xr-runrate-val" id="xr-runrate">—</span>
- <span class="xr-runrate-label" data-i18n="x402_revenue.run_rate_hr">run rate · /hr</span>
- </div>
- </div>
- </div>
- <div class="xr-chart-wrap">
- <div
- class="xr-chart"
- id="xr-chart"
- role="img"
- aria-label="Revenue over the selected window"
- ></div>
- <div class="xr-chart-tip" id="xr-chart-tip" hidden></div>
- <div class="xr-chart-empty" id="xr-chart-empty" hidden>
- No revenue in this window yet.
- </div>
- </div>
- </section>
-
- <!-- ── KPI cards ────────────────────────────────────────────────── -->
- <dl class="xr-kpis" id="xr-kpis">
- <div class="xr-kpi">
- <dt data-i18n="x402_revenue.settlements">Settlements</dt>
- <dd id="xr-c-count">—</dd>
- <span class="xr-kpi-sub" data-i18n="x402_revenue.paid_calls">paid calls</span>
- </div>
- <div class="xr-kpi">
- <dt data-i18n="x402_revenue.unique_payers">Unique payers</dt>
- <dd id="xr-c-payers">—</dd>
- <span class="xr-kpi-sub" data-i18n="x402_revenue.distinct_wallets">distinct wallets</span>
- </div>
- <div class="xr-kpi">
- <dt data-i18n="x402_revenue.net_to_platform">Net to platform</dt>
- <dd id="xr-c-net">—</dd>
- <span class="xr-kpi-sub" data-i18n="x402_revenue.after_settlement_fees">after settlement fees</span>
- </div>
- <div class="xr-kpi">
- <dt data-i18n="x402_revenue.success_rate">Success rate</dt>
- <dd id="xr-c-success">—</dd>
- <span class="xr-kpi-sub" id="xr-c-success-sub" data-no-i18n>settled vs failed</span>
- </div>
- </dl>
-
- <!-- ── main grid: feed + rail ───────────────────────────────────── -->
- <div class="xr-grid">
- <div class="xr-main">
- <div class="xr-toolbar">
- <div class="xr-toolbar-left">
- <h2 class="xr-section-h" data-i18n="x402_revenue.live_settlements">Live settlements</h2>
- <span class="xr-feed-state" id="xr-feed-state" data-state="loading" data-no-i18n
- >connecting…</span
- >
- </div>
- <div class="xr-toolbar-right">
- <div class="xr-search">
- <span class="xr-search-ico" aria-hidden="true">⌕</span>
- <input
- type="search"
- id="xr-search"
- class="xr-search-input"
- placeholder="Filter rows… ( / )"
- aria-label="Filter settlements by endpoint, payer, or transaction"
- autocomplete="off"
- />
- </div>
- <button
- type="button"
- class="xr-icon-btn"
- id="xr-sound"
- aria-pressed="false"
- aria-label="Toggle chime on new settlements"
- title="Sound on new settlements (s)"
- data-i18n-attr="aria-label:x402_revenue.toggle_chime_on_new_settleme_arialabel;title:x402_revenue.sound_on_new_settlements_s_title">
- <span aria-hidden="true">♪</span>
- </button>
- <button
- type="button"
- class="xr-icon-btn"
- id="xr-pause"
- aria-pressed="false"
- aria-label="Pause the live feed"
- title="Pause / resume live feed (p)"
- data-i18n-attr="aria-label:x402_revenue.pause_the_live_feed_arialabel;title:x402_revenue.pause_resume_live_feed_p_title">
- <span aria-hidden="true" class="xr-pause-ico">॥</span>
- </button>
- <button
- type="button"
- class="xr-icon-btn xr-icon-btn--text"
- id="xr-export"
- aria-label="Export settlements as CSV"
- title="Export CSV (e)"
- data-i18n-html="x402_revenue.csv" data-i18n-attr="aria-label:x402_revenue.export_settlements_as_csv_arialabel;title:x402_revenue.export_csv_e_title">
- <span aria-hidden="true">↓</span> CSV
- </button>
- </div>
- </div>
-
- <div
- class="xr-chips"
- id="xr-chips"
- role="group"
- aria-label="Filter by endpoint or network"
- ></div>
-
- <div
- class="xr-feed"
- id="xr-feed"
- aria-live="polite"
- aria-label="Live x402 endpoint settlements"
- ></div>
- <button type="button" class="xr-more" id="xr-more" hidden data-i18n="x402_revenue.load_older_settlements">
- Load older settlements
- </button>
- </div>
-
- <aside class="xr-rail" aria-label="Revenue intelligence">
- <section class="xr-card">
- <div class="xr-card-h">
- Top earning endpoints <small id="xr-top-window" data-no-i18n>24h</small>
- </div>
- <div id="xr-top"><p class="xr-empty" data-i18n="x402_revenue.loading">Loading…</p></div>
- </section>
- <section class="xr-card">
- <div class="xr-card-h">
- Revenue by network <small id="xr-net-window" data-no-i18n>24h</small>
- </div>
- <div id="xr-networks"><p class="xr-empty" data-i18n="x402_revenue.loading_2">Loading…</p></div>
- </section>
- <section class="xr-card xr-card--quiet">
- <div class="xr-card-h">How this works</div>
- <p class="xr-note" data-i18n-html="x402_revenue.each_paid_endpoint_settles_a_small_usdc">
- Each paid endpoint settles a small USDC payment per call. Every
- settlement is recorded in the revenue ledger and surfaced here — never a
- simulation. See
- <a href="/docs/x402-revenue">x402 revenue &amp; receipts</a> and the
- <a href="/docs/x402-endpoints">endpoint catalog</a>.
- </p>
- <p class="xr-note">
- Paid for something here yourself? Every settled call issues you a
- signed receipt. Retrieve all of yours at the
- <a href="/receipts">Receipt Vault</a>: connect the wallet you paid
- with and sign one read-only message.
- </p>
- <p class="xr-hint" data-i18n-html="x402_revenue.search_p_pause_s_sound_e_export">
- <kbd>/</kbd> search · <kbd>p</kbd> pause · <kbd>s</kbd> sound ·
- <kbd>e</kbd> export · <kbd>1–4</kbd> window
- </p>
- </section>
- <p class="xr-fineprint" data-i18n="x402_revenue.operational_fields_ip_user_agent_are_never">
- Operational fields (IP, user agent) are never exposed — only the
- on-chain-public route, amount, payer, and transaction. Amounts in USDC.
- </p>
- </aside>
- </div>
- </main>
-
- <div class="xr-toast" id="xr-toast" role="status" aria-live="polite" hidden></div>
-
- <script type="module" src="/src/x402-revenue.js"></script>
- <script src="/brand.js" defer></script>
- <div id="footer-container"></div>
- <script src="/footer.js"></script>
- <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
- <script type="module" src="/i18n.js"></script>
-</body>
-</html>
diff --git a/public/media/tour/x402-revenue.thumb.webp b/public/media/tour/x402-revenue.thumb.webp
deleted file mode 100644
index fb70b6320..000000000
Binary files a/public/media/tour/x402-revenue.thumb.webp and /dev/null differ
diff --git a/public/media/tour/x402-revenue.webp b/public/media/tour/x402-revenue.webp
deleted file mode 100644
index 564a6c216..000000000
Binary files a/public/media/tour/x402-revenue.webp and /dev/null differ
diff --git a/src/dashboard-next/pages/analytics.js b/src/dashboard-next/pages/analytics.js
deleted file mode 100644
index 08d2bd611..000000000
--- a/src/dashboard-next/pages/analytics.js
+++ /dev/null
@@ -1,909 +0,0 @@
-// dashboard-next — Analytics page.
-//
-// Revenue charts, per-agent performance, skill breakdown, conversion funnel.
-// All data from real /api/billing/revenue, /api/agents, /api/widgets/:id/stats.
-// Charts drawn with Canvas 2D API directly — no chart libraries.
-
-import { mountShell } from '../shell.js';
-import { requireUser, get, esc, relTime, formatUsdc, ApiError } from '../api.js';
-import { errorStateHTML, emptyStateHTML, ensureStateKitStyles } from '../../shared/state-kit.js';
-
-const RANGES = [
- { key: '7d', days: 7, label: '7 days', granularity: 'day' },
- { key: '30d', days: 30, label: '30 days', granularity: 'day' },
- { key: '90d', days: 90, label: '90 days', granularity: 'day' },
- { key: '1y', days: 365, label: '12 months', granularity: 'week' },
-];
-
-let range = RANGES[1];
-let me = null;
-
-(async function boot() {
- const main = await mountShell();
- me = await requireUser();
-
- main.innerHTML = `
- <h1 class="dn-h1">Analytics</h1>
- <p class="dn-h1-sub">Revenue, engagement, and performance across your agents and skills.</p>
- <div data-slot="content" class="ana-root"></div>
- `;
- injectStyles();
- const root = main.querySelector('[data-slot="content"]');
- renderSkeletons(root);
- await loadAndRender(root);
-})().catch(err => {
- if (err instanceof ApiError && err.status === 401) {
- location.href = `/login?return=${encodeURIComponent(location.pathname)}`;
- return;
- }
- const main = document.querySelector('.dn-main-inner') || document.body;
- main.innerHTML = `<h1 class="dn-h1">Analytics</h1><div class="dn-panel"><div class="dn-panel-title" style="color:var(--nxt-danger)">Analytics could not be drawn</div><div class="dn-panel-sub">Something went wrong while building this page. Reloading usually clears it. If it keeps happening, <a href="/support">tell us</a> and quote the detail below.</div><div class="dn-panel-sub" style="margin-top:6px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;opacity:0.7">${esc(err?.message || 'unknown error')}</div><button type="button" class="dn-btn" data-action="reload" style="margin-top:12px">Reload</button></div>`;
- main.querySelector('[data-action="reload"]')?.addEventListener('click', () => location.reload());
-});
-
-function renderSkeletons(root) {
- root.innerHTML = `
- <div class="ana-range-bar" role="group" aria-label="Select analytics time range">${RANGES.map(r => `<button type="button" class="ana-range-btn${r.key === range.key ? ' is-active' : ''}" aria-pressed="${r.key === range.key}" disabled>${r.label}</button>`).join('')}</div>
- <div class="ana-kpi-row">${Array.from({ length: 4 }, () => `<div class="dn-panel ana-kpi"><div class="dn-skeleton" style="height:12px;width:80px;margin-bottom:8px"></div><div class="dn-skeleton" style="height:28px;width:100px"></div></div>`).join('')}</div>
- <div class="dn-panel" style="min-height:280px"><div class="dn-skeleton" style="height:12px;width:120px;margin-bottom:16px"></div><div class="dn-skeleton" style="height:220px;width:100%"></div></div>
- <div class="ana-two-col">
- <div class="dn-panel" style="min-height:200px"><div class="dn-skeleton" style="height:12px;width:100px;margin-bottom:12px"></div><div class="dn-skeleton" style="height:150px;width:100%"></div></div>
- <div class="dn-panel" style="min-height:200px"><div class="dn-skeleton" style="height:12px;width:100px;margin-bottom:12px"></div><div class="dn-skeleton" style="height:150px;width:100%"></div></div>
- </div>
- `;
-}
-
-async function loadAndRender(root) {
- const from = new Date(Date.now() - range.days * 86400_000).toISOString();
- const to = new Date().toISOString();
-
- const [revenue, agents, widgets, summary, retention] = await Promise.all([
- safe(() => get(`/api/billing/revenue?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}&granularity=${range.granularity}`)),
- safe(() => get('/api/agents?limit=50')),
- safe(() => get('/api/widgets')),
- safe(() => get('/api/billing/summary')),
- // Platform-wide week-2 retention on minted agents. Admin-only upstream, so
- // only an admin session asks for it. Every other user would get a
- // guaranteed 403, which `safe` swallows but the browser still logs as a
- // failed request on every analytics load; skipping the call keeps a normal
- // user's network panel clean and the retention panel simply does not appear.
- me?.is_admin
- ? safe(() => get('/api/analytics/retention?metric=week2_converse&weeks=12'))
- : Promise.resolve(null),
- ]);
-
- // Every primary surface (revenue, agents, widgets, summary) failing means the
- // network is down, not that the user has no data — render a retryable error
- // instead of an all-zero dashboard that looks deceptively "empty".
- if (revenue === null && agents === null && widgets === null && summary === null) {
- ensureStateKitStyles();
- root.innerHTML = errorStateHTML({
- title: "Couldn't load analytics",
- body: 'We had trouble reaching the analytics service. Check your connection and try again.',
- });
- root.querySelector('[data-sk-retry]')?.addEventListener('click', () => {
- renderSkeletons(root);
- loadAndRender(root);
- });
- return;
- }
-
- // Shape-guard the collections rather than trusting the payload: an upstream
- // that answers 200 with a non-array (a deploy skew, a proxy error page parsed
- // as JSON) would otherwise throw out of here and blank the whole page.
- const agentList = Array.isArray(agents?.agents) ? agents.agents : [];
- const widgetList = Array.isArray(widgets?.widgets) ? widgets.widgets : [];
-
- const widgetStats = await Promise.all(
- widgetList.slice(0, 20).map(w =>
- get(`/api/widgets/${encodeURIComponent(w.id)}/stats`).catch(() => null)
- )
- );
-
- const totalViews = widgetStats.reduce((s, ws) => s + (ws?.stats?.view_count ?? ws?.stats?.total_views ?? 0), 0);
- const totalChats = widgetStats.reduce((s, ws) => s + (ws?.stats?.chat_count ?? ws?.stats?.total_chats ?? 0), 0);
- const recentViews = widgetStats.reduce((s, ws) => {
- const arr = ws?.stats?.recent_views_7d ?? [];
- return s + arr.reduce((a, p) => a + (p.count ?? p.value ?? 0), 0);
- }, 0);
- const recentChats = widgetStats.reduce((s, ws) => {
- const arr = ws?.stats?.recent_chats_7d ?? [];
- return s + arr.reduce((a, p) => a + (p.count ?? p.value ?? 0), 0);
- }, 0);
-
- const revTotal = Number(revenue?.summary?.net_total ?? 0);
- const revPayments = Number(revenue?.summary?.payment_count ?? 0);
- const timeseries = Array.isArray(revenue?.timeseries) ? revenue.timeseries : [];
- const bySkill = Array.isArray(revenue?.by_skill) ? revenue.by_skill : [];
-
- // Fetch per-agent payments for the activity table
- const recentPayments = await fetchRecentActivity(agentList);
-
- // Get top agent by revenue
- const topAgent = agentList.length > 0
- ? agentList.reduce((best, a) => {
- const rev = Number(a.total_revenue ?? a.revenue ?? 0);
- return rev > (best.rev || 0) ? { name: a.name, rev } : best;
- }, { name: agentList[0].name, rev: 0 })
- : null;
-
- root.innerHTML = '';
-
- root.appendChild(renderRangeBar(root));
- root.appendChild(renderKpis({
- revTotal, revPayments, totalViews, totalChats,
- recentViews, recentChats, agentList, widgetList,
- topAgent,
- }));
- root.appendChild(renderRevenueChart(timeseries));
- if (retention) root.appendChild(renderRetentionChart(retention));
- root.appendChild(renderTwoCol(
- renderSkillBreakdown(bySkill),
- renderAgentTable(agentList, widgetList, widgetStats)
- ));
- root.appendChild(renderFunnel({ totalViews, totalChats, revPayments }));
- root.appendChild(renderActivityTable(recentPayments));
-
- root.querySelector('.ana-range-bar')?.addEventListener('click', e => {
- const btn = e.target.closest('.ana-range-btn');
- if (!btn) return;
- const idx = [...root.querySelector('.ana-range-bar').children].indexOf(btn);
- if (idx >= 0 && RANGES[idx]) {
- range = RANGES[idx];
- renderSkeletons(root);
- loadAndRender(root);
- }
- });
-}
-
-function safe(fn) { return fn().catch(() => null); }
-
-// Honor the OS "reduce motion" setting — charts render their final frame at once
-// instead of animating in.
-function prefersReducedMotion() {
- return typeof window !== 'undefined'
- && typeof window.matchMedia === 'function'
- && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-}
-
-// -- KPIs --
-
-function renderKpis({ revTotal, revPayments, recentViews, recentChats, agentList, widgetList, topAgent }) {
- const el = document.createElement('div');
- el.className = 'ana-kpi-row';
-
- const avgPrice = revPayments > 0 ? (revTotal / 1_000_000) / revPayments : 0;
- const avgPriceStr = avgPrice > 0
- ? '$' + avgPrice.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 6 })
- : '$0.00';
-
- el.innerHTML = [
- kpiCard('Total Revenue', formatUsdc(revTotal), `${revPayments} payment${revPayments !== 1 ? 's' : ''}`, 'var(--nxt-success)'),
- kpiCard('Total Callers', recentChats.toLocaleString(), `${recentViews.toLocaleString()} views`, 'var(--nxt-accent)'),
- kpiCard('Avg Price/Call', avgPriceStr, `${range.label}`, 'var(--nxt-warn)'),
- kpiCard('Top Agent', topAgent?.name || '--', topAgent?.rev > 0 ? formatUsdc(topAgent.rev) : `${agentList.length} agent${agentList.length !== 1 ? 's' : ''}`, 'var(--nxt-accent)'),
- ].join('');
- return el;
-}
-
-function kpiCard(label, value, sub, accentColor) {
- return `<div class="dn-panel ana-kpi">
- <div class="ana-kpi-label">${esc(label)}</div>
- <div class="ana-kpi-value" style="color:${accentColor || 'var(--nxt-ink)'}">${esc(value)}</div>
- <div class="ana-kpi-sub">${esc(sub)}</div>
- </div>`;
-}
-
-// -- Revenue chart (Canvas 2D) --
-
-function renderRevenueChart(timeseries) {
- const panel = document.createElement('div');
- panel.className = 'dn-panel ana-chart-panel';
-
- if (!timeseries.length) {
- panel.innerHTML = `<div class="dn-panel-title">Revenue Over Time</div><div class="ana-chart-empty">No revenue data for this period. <a href="/dashboard/monetize">Set up monetization</a></div>`;
- return panel;
- }
-
- panel.innerHTML = `
- <div class="dn-panel-title">Revenue Over Time</div>
- <div data-slot="chart" style="position:relative;width:100%;height:220px;margin-top:12px"></div>
- `;
-
- const chartHost = panel.querySelector('[data-slot="chart"]');
- requestAnimationFrame(() => paintCanvasLineChart(chartHost, timeseries));
-
- return panel;
-}
-
-function paintCanvasLineChart(host, timeseries) {
- host.innerHTML = '';
- const canvas = document.createElement('canvas');
- canvas.style.cssText = 'width:100%;height:100%;display:block';
- // Canvas is opaque to assistive tech — describe the trend it depicts.
- const total = timeseries.reduce((a, p) => a + (Number(p.value) || 0), 0);
- const peak = timeseries.reduce((m, p) => Math.max(m, Number(p.value) || 0), 0);
- canvas.setAttribute('role', 'img');
- canvas.setAttribute('aria-label',
- `Revenue over time line chart, ${timeseries.length} data points, ` +
- `total $${total.toFixed(2)}, peak day $${peak.toFixed(2)}.`);
- host.appendChild(canvas);
-
- const dpr = window.devicePixelRatio || 1;
- const rect = host.getBoundingClientRect();
- canvas.width = Math.round(rect.width * dpr);
- canvas.height = Math.round(rect.height * dpr);
- const ctx = canvas.getContext('2d');
- ctx.scale(dpr, dpr);
-
- const W = rect.width;
- const H = rect.height;
- const PAD = { top: 16, right: 16, bottom: 32, left: 52 };
- const innerW = W - PAD.left - PAD.right;
- const innerH = H - PAD.top - PAD.bottom;
-
- const data = timeseries.map(p => ({
- label: formatPeriod(p.period),
- value: Number(p.net_total ?? 0) / 1_000_000,
- count: Number(p.count ?? 0),
- raw: p,
- }));
-
- const max = Math.max(0.01, ...data.map(d => d.value));
-
- const points = data.map((d, i) => ({
- x: PAD.left + (data.length === 1 ? innerW / 2 : (i / (data.length - 1)) * innerW),
- y: PAD.top + innerH - (d.value / max) * innerH,
- }));
-
- let progress = 0;
- const duration = 600;
- const startTime = performance.now();
-
- function draw(now) {
- progress = Math.min(1, (now - startTime) / duration);
- const eased = 1 - Math.pow(1 - progress, 3);
- const visibleCount = Math.max(1, Math.ceil(eased * points.length));
-
- ctx.clearRect(0, 0, W, H);
-
- // Grid
- ctx.strokeStyle = 'rgba(255,255,255,0.05)';
- ctx.lineWidth = 0.5;
- for (let i = 0; i <= 4; i++) {
- const y = PAD.top + (i / 4) * innerH;
- ctx.beginPath();
- ctx.moveTo(PAD.left, y);
- ctx.lineTo(W - PAD.right, y);
- ctx.stroke();
-
- const val = ((4 - i) / 4) * max;
- ctx.fillStyle = 'rgba(255,255,255,0.3)';
- ctx.font = '10px Inter, system-ui, sans-serif';
- ctx.textAlign = 'right';
- ctx.fillText('$' + (val >= 100 ? val.toFixed(0) : val.toFixed(2)), PAD.left - 8, y + 4);
- }
-
- // X labels
- const showEvery = Math.max(1, Math.ceil(data.length / 10));
- ctx.fillStyle = 'rgba(255,255,255,0.3)';
- ctx.font = '10px Inter, system-ui, sans-serif';
- ctx.textAlign = 'center';
- data.forEach((d, i) => {
- if (i % showEvery === 0 && i < visibleCount) {
- ctx.fillText(d.label, points[i].x, H - 6);
- }
- });
-
- const visible = points.slice(0, visibleCount);
- if (visible.length >= 2) {
- // Gradient fill
- const gradient = ctx.createLinearGradient(0, PAD.top, 0, PAD.top + innerH);
- gradient.addColorStop(0, 'rgba(74, 222, 128, 0.2)');
- gradient.addColorStop(1, 'rgba(74, 222, 128, 0)');
-
- ctx.beginPath();
- ctx.moveTo(visible[0].x, PAD.top + innerH);
- visible.forEach(p => ctx.lineTo(p.x, p.y));
- ctx.lineTo(visible[visible.length - 1].x, PAD.top + innerH);
- ctx.closePath();
- ctx.fillStyle = gradient;
- ctx.fill();
-
- // Smooth line
- ctx.beginPath();
- ctx.moveTo(visible[0].x, visible[0].y);
- for (let i = 1; i < visible.length; i++) {
- const prev = visible[i - 1];
- const cur = visible[i];
- const cpx = (prev.x + cur.x) / 2;
- ctx.bezierCurveTo(cpx, prev.y, cpx, cur.y, cur.x, cur.y);
- }
- ctx.strokeStyle = '#4ade80';
- ctx.lineWidth = 2;
- ctx.stroke();
-
- // End dot
- const last = visible[visible.length - 1];
- ctx.beginPath();
- ctx.arc(last.x, last.y, 4, 0, Math.PI * 2);
- ctx.fillStyle = '#4ade80';
- ctx.fill();
- ctx.strokeStyle = 'rgba(0,0,0,0.3)';
- ctx.lineWidth = 1;
- ctx.stroke();
- } else if (visible.length === 1) {
- ctx.beginPath();
- ctx.arc(visible[0].x, visible[0].y, 5, 0, Math.PI * 2);
- ctx.fillStyle = '#4ade80';
- ctx.fill();
- }
-
- if (progress < 1) requestAnimationFrame(draw);
- }
-
- // Skip the reveal animation entirely under reduced-motion — draw the final frame.
- if (prefersReducedMotion()) draw(startTime + duration);
- else requestAnimationFrame(draw);
-
- // Tooltip
- canvas.addEventListener('mousemove', (e) => {
- const br = canvas.getBoundingClientRect();
- const mx = e.clientX - br.left;
- let closest = 0;
- let closestDist = Infinity;
- points.forEach((p, i) => {
- const d = Math.abs(p.x - mx);
- if (d < closestDist) { closestDist = d; closest = i; }
- });
- const d = data[closest];
- canvas.title = `${d.label}: $${d.value.toFixed(4)} (${d.count} payments)`;
- });
-}
-
-function formatPeriod(p) {
- const d = new Date(p);
- if (isNaN(d)) return String(p).slice(0, 10);
- return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
-}
-
-// -- Week-2 retention on minted agents (Canvas 2D column chart) --
-//
-// The README roadmap's phase-2 verification metric. One column per cohort week
-// (owners grouped by the ISO week they minted their first agent on-chain), height
-// = the share of them who came back to converse on days 7..13. The dashed line is
-// the roadmap's 30% bar. Cohorts whose 14-day window is still open are drawn
-// muted and labelled "open", because their number can still move.
-
-function formatPct(rate) {
- return rate == null ? '--' : `${(rate * 100).toFixed(1)}%`;
-}
-
-function formatCohortWeek(week) {
- const d = new Date(`${week}T00:00:00Z`);
- if (isNaN(d)) return String(week);
- return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
-}
-
-function renderRetentionChart(data) {
- const panel = document.createElement('div');
- panel.className = 'dn-panel ana-chart-panel';
-
- const cohorts = data.cohorts ?? [];
- const s = data.summary ?? {};
- const label = data.metric_label || 'Returned to converse';
-
- if (!cohorts.length) {
- panel.innerHTML = `
- <div class="dn-panel-title">Week-2 Retention · Minted Agents</div>
- <div class="ana-chart-empty">
- No cohorts rolled up yet. The weekly rollup fills this in once owners have minted
- agents and their 14-day window opens.
- </div>`;
- return panel;
- }
-
- const target = Number(data.target ?? 0.3);
- const headline = s.latestCompleteWeek
- ? `Latest closed cohort ${formatCohortWeek(s.latestCompleteWeek)}: <strong>${formatPct(s.latestRate)}</strong>`
- : 'No cohort has closed its 14-day window yet';
- const pooled = s.pooledRate != null
- ? ` · pooled <strong>${formatPct(s.pooledRate)}</strong> across ${s.completeCohorts} closed cohort${s.completeCohorts === 1 ? '' : 's'} (${s.retainedOwners}/${s.mintedOwners} owners)`
- : '';
-
- panel.innerHTML = `
- <div class="dn-panel-title">Week-2 Retention · Minted Agents</div>
- <div class="ana-ret-summary">${headline}${pooled}</div>
- <div data-slot="ret" style="position:relative;width:100%;height:220px;margin-top:12px"></div>
- <div class="ana-ret-legend">
- <span><i class="ana-ret-swatch is-hit"></i>${esc(label)}, at or above the ${Math.round(target * 100)}% target</span>
- <span><i class="ana-ret-swatch is-miss"></i>below target</span>
- <span><i class="ana-ret-swatch is-open"></i>window still open</span>
- </div>
- `;
-
- const host = panel.querySelector('[data-slot="ret"]');
- requestAnimationFrame(() => paintRetentionColumns(host, cohorts, target, label));
-
- return panel;
-}
-
-function paintRetentionColumns(host, cohorts, target, label) {
- host.innerHTML = '';
- const canvas = document.createElement('canvas');
- canvas.style.cssText = 'width:100%;height:100%;display:block';
- canvas.setAttribute('role', 'img');
- canvas.setAttribute(
- 'aria-label',
- `${label} week-2 retention by mint cohort, ${cohorts.length} weeks. ` +
- cohorts
- .map(
- (c) =>
- `Week of ${c.cohort_week}: ${formatPct(Number(c.retention_rate))} of ${c.minted_owners} owners` +
- `${c.is_complete ? '' : ', window still open'}`,
- )
- .join('. ') +
- `. Target ${Math.round(target * 100)} percent.`,
- );
- host.appendChild(canvas);
-
- const dpr = window.devicePixelRatio || 1;
- const rect = host.getBoundingClientRect();
- canvas.width = Math.round(rect.width * dpr);
- canvas.height = Math.round(rect.height * dpr);
- const ctx = canvas.getContext('2d');
- ctx.scale(dpr, dpr);
-
- const W = rect.width;
- const H = rect.height;
- const PAD = { top: 16, right: 16, bottom: 34, left: 44 };
- const innerW = W - PAD.left - PAD.right;
- const innerH = H - PAD.top - PAD.bottom;
-
- // Always show at least up to the target so the bar is never off-canvas, and
- // give a headroom cohort room to breathe above it.
- const peak = cohorts.reduce((m, c) => Math.max(m, Number(c.retention_rate) || 0), 0);
- const max = Math.min(1, Math.max(target * 1.4, peak * 1.2, 0.1));
-
- const slot = innerW / cohorts.length;
- const barW = Math.max(6, Math.min(46, slot * 0.62));
-
- const duration = 600;
- const startTime = performance.now();
-
- function draw(now) {
- const progress = Math.min(1, (now - startTime) / duration);
- const eased = 1 - Math.pow(1 - progress, 3);
-
- ctx.clearRect(0, 0, W, H);
-
- // Grid + percentage axis
- ctx.font = '10px Inter, system-ui, sans-serif';
- for (let i = 0; i <= 4; i++) {
- const y = PAD.top + (i / 4) * innerH;
- ctx.strokeStyle = 'rgba(255,255,255,0.05)';
- ctx.lineWidth = 0.5;
- ctx.beginPath();
- ctx.moveTo(PAD.left, y);
- ctx.lineTo(W - PAD.right, y);
- ctx.stroke();
-
- ctx.fillStyle = 'rgba(255,255,255,0.3)';
- ctx.textAlign = 'right';
- ctx.fillText(`${Math.round(((4 - i) / 4) * max * 100)}%`, PAD.left - 8, y + 4);
- }
-
- // Columns
- cohorts.forEach((c, i) => {
- const rate = Number(c.retention_rate) || 0;
- const h = Math.max(rate > 0 ? 2 : 0, (rate / max) * innerH * eased);
- const x = PAD.left + i * slot + (slot - barW) / 2;
- const y = PAD.top + innerH - h;
-
- ctx.fillStyle = !c.is_complete
- ? 'rgba(148,163,184,0.45)'
- : rate >= target
- ? '#4ade80'
- : '#fbbf24';
- ctx.beginPath();
- ctx.roundRect(x, y, barW, h, [3, 3, 0, 0]);
- ctx.fill();
- });
-
- // Target line, drawn over the columns so the bar is always readable.
- const targetY = PAD.top + innerH - (Math.min(target, max) / max) * innerH;
- ctx.save();
- ctx.setLineDash([4, 4]);
- ctx.strokeStyle = 'rgba(96,165,250,0.8)';
- ctx.lineWidth = 1;
- ctx.beginPath();
- ctx.moveTo(PAD.left, targetY);
- ctx.lineTo(W - PAD.right, targetY);
- ctx.stroke();
- ctx.restore();
- ctx.fillStyle = 'rgba(96,165,250,0.9)';
- ctx.textAlign = 'left';
- ctx.fillText(`${Math.round(target * 100)}% target`, PAD.left + 4, targetY - 4);
-
- // X labels — thinned so they never collide on a narrow viewport.
- const showEvery = Math.max(1, Math.ceil(cohorts.length / Math.max(1, Math.floor(innerW / 56))));
- ctx.fillStyle = 'rgba(255,255,255,0.3)';
- ctx.textAlign = 'center';
- cohorts.forEach((c, i) => {
- if (i % showEvery === 0) {
- ctx.fillText(formatCohortWeek(c.cohort_week), PAD.left + i * slot + slot / 2, H - 8);
- }
- });
-
- if (progress < 1) requestAnimationFrame(draw);
- }
-
- if (prefersReducedMotion()) draw(startTime + duration);
- else requestAnimationFrame(draw);
-
- canvas.addEventListener('mousemove', (e) => {
- const br = canvas.getBoundingClientRect();
- const idx = Math.floor((e.clientX - br.left - PAD.left) / slot);
- const c = cohorts[Math.max(0, Math.min(cohorts.length - 1, idx))];
- canvas.title =
- `Minted week of ${c.cohort_week}: ${formatPct(Number(c.retention_rate))} ` +
- `(${c.retained_owners}/${c.minted_owners} owners)` +
- `${c.is_complete ? '' : ' · window open until ' + c.window_end}`;
- });
-}
-
-// -- Skill breakdown (horizontal bar chart with Canvas) --
-
-function renderSkillBreakdown(bySkill) {
- const panel = document.createElement('div');
- panel.className = 'dn-panel';
-
- if (!bySkill.length) {
- panel.innerHTML = `<div class="dn-panel-title">Revenue by Skill</div><div class="ana-chart-empty">No skill revenue yet</div>`;
- return panel;
- }
-
- panel.innerHTML = `
- <div class="dn-panel-title">Revenue by Skill</div>
- <div data-slot="bars" style="position:relative;width:100%;height:200px;margin-top:12px"></div>
- `;
-
- const host = panel.querySelector('[data-slot="bars"]');
- requestAnimationFrame(() => paintHorizontalBarChart(host, bySkill));
-
- return panel;
-}
-
-function paintHorizontalBarChart(host, bySkill) {
- host.innerHTML = '';
- const canvas = document.createElement('canvas');
- canvas.style.cssText = 'width:100%;height:100%;display:block';
- const ranked = [...bySkill].sort((a, b) => Number(b.net_total) - Number(a.net_total)).slice(0, 8);
- const summary = ranked
- .map((s) => `${(s.skill || 'Other').replace(/_/g, ' ')} ${formatUsdc(Number(s.net_total))}`)
- .join(', ');
- canvas.setAttribute('role', 'img');
- canvas.setAttribute('aria-label', `Revenue by skill bar chart. ${summary}.`);
- host.appendChild(canvas);
-
- const dpr = window.devicePixelRatio || 1;
- const rect = host.getBoundingClientRect();
- canvas.width = Math.round(rect.width * dpr);
- canvas.height = Math.round(rect.height * dpr);
- const ctx = canvas.getContext('2d');
- ctx.scale(dpr, dpr);
-
- const W = rect.width;
- const H = rect.height;
-
- const sorted = [...bySkill].sort((a, b) => Number(b.net_total) - Number(a.net_total)).slice(0, 8);
- const max = Math.max(1, Number(sorted[0]?.net_total ?? 0));
- const colors = ['#4ade80', '#fbbf24', '#60a5fa', '#f472b6', '#888888', '#fb923c', '#22d3ee', '#94a3b8'];
-
- const labelW = 100;
- const valueW = 70;
- const barPad = 8;
- const barAreaW = W - labelW - valueW - barPad * 2;
- const rowH = Math.min(28, (H - 8) / sorted.length);
- const gap = 4;
-
- let progress = 0;
- const duration = 600;
- const startTime = performance.now();
-
- function draw(now) {
- progress = Math.min(1, (now - startTime) / duration);
- const eased = 1 - Math.pow(1 - progress, 3);
-
- ctx.clearRect(0, 0, W, H);
-
- sorted.forEach((s, i) => {
- const y = i * (rowH + gap) + 4;
- const val = Number(s.net_total);
- const pct = val / max;
- const barW = Math.max(2, pct * barAreaW * eased);
- const color = colors[i % colors.length];
-
- // Label
- ctx.fillStyle = 'rgba(255,255,255,0.7)';
- ctx.font = '12px Inter, system-ui, sans-serif';
- ctx.textAlign = 'left';
- const label = (s.skill || 'Other').replace(/_/g, ' ');
- ctx.fillText(label.length > 14 ? label.slice(0, 13) + '...' : label, 0, y + rowH / 2 + 4);
-
- // Bar
- ctx.fillStyle = color;
- ctx.beginPath();
- ctx.roundRect(labelW + barPad, y, barW, rowH, 4);
- ctx.fill();
-
- // Value
- ctx.fillStyle = 'rgba(255,255,255,0.5)';
- ctx.font = '11px Inter, system-ui, sans-serif';
- ctx.textAlign = 'left';
- ctx.fillText(formatUsdc(val), labelW + barPad + barW + 8, y + rowH / 2 + 4);
- });
-
- if (progress < 1) requestAnimationFrame(draw);
- }
-
- if (prefersReducedMotion()) draw(startTime + duration);
- else requestAnimationFrame(draw);
-}
-
-// -- Agent table --
-
-function renderAgentTable(agents, widgets, widgetStats) {
- const panel = document.createElement('div');
- panel.className = 'dn-panel';
-
- if (!agents.length) {
- panel.innerHTML = `<div class="dn-panel-title">Agent Performance</div>${emptyStateHTML({
- icon: '🤖',
- title: 'No agents yet',
- body: 'Per-agent views, chats, and conversion rates show up here once you have an agent live. Create one to start tracking how it performs.',
- actions: [
- { label: '+ Create your first agent', href: '/dashboard/agents', id: 'create-agent', primary: true },
- { label: "What's an agent?", href: '/docs/agents-vs-avatars', id: 'learn-agents' },
- ],
- compact: true,
- })}`;
- return panel;
- }
-
- const widgetMap = new Map();
- widgets.forEach((w, i) => {
- const stats = widgetStats[i];
- if (!stats) return;
- const key = w.avatar_id;
- if (key) {
- const prev = widgetMap.get(key) || { views: 0, chats: 0 };
- widgetMap.set(key, {
- views: prev.views + (stats.stats?.view_count ?? stats.stats?.total_views ?? 0),
- chats: prev.chats + (stats.stats?.chat_count ?? stats.stats?.total_chats ?? 0),
- });
- }
- });
-
- const rows = agents.slice(0, 10).map(a => {
- const wStats = widgetMap.get(a.avatar_id) || widgetMap.get(a.id) || { views: 0, chats: 0 };
- const convRate = wStats.views > 0 ? ((wStats.chats / wStats.views) * 100).toFixed(1) : '--';
- return `
- <tr>
- <td class="ana-tbl-name">${esc(a.name || a.slug || 'Unnamed')}</td>
- <td>${wStats.views.toLocaleString()}</td>
- <td>${wStats.chats.toLocaleString()}</td>
- <td>${convRate}${convRate !== '--' ? '%' : ''}</td>
- </tr>
- `;
- });
-
- panel.innerHTML = `
- <div class="dn-panel-title">Agent Performance</div>
- <div class="ana-tbl-wrap">
- <table class="ana-tbl">
- <thead><tr><th>Agent</th><th>Views</th><th>Chats</th><th>Conv.</th></tr></thead>
- <tbody>${rows.join('')}</tbody>
- </table>
- </div>
- `;
- return panel;
-}
-
-// -- Recent activity table --
-
-async function fetchRecentActivity(agents) {
- if (!agents.length) return [];
- const top = agents.slice(0, 5);
- const lists = await Promise.all(
- top.map(a =>
- get(`/api/agents/${encodeURIComponent(a.id)}/payments?direction=received&limit=5`)
- .then(r => (r?.payments || []).map(p => ({ ...p, _agent: a })))
- .catch(() => [])
- )
- );
- const merged = lists.flat();
- merged.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
- return merged.slice(0, 20);
-}
-
-function renderActivityTable(payments) {
- const panel = document.createElement('div');
- panel.className = 'dn-panel';
-
- if (!payments.length) {
- panel.innerHTML = `
- <div class="dn-panel-title">Recent Activity</div>
- <div class="ana-chart-empty">No revenue events yet. Earnings will appear here as callers use your agents' skills.</div>
- `;
- return panel;
- }
-
- panel.innerHTML = `
- <div class="dn-panel-title">Recent Activity</div>
- <div class="dn-panel-sub" style="margin:2px 0 14px">Latest revenue events from skill calls and API usage.</div>
- <div style="overflow-x:auto">
- <table class="ana-tbl" style="min-width:560px">
- <thead>
- <tr>
- <th>Time</th>
- <th>Skill</th>
- <th style="text-align:right">Amount</th>
- <th>Agent</th>
- <th>Status</th>
- </tr>
- </thead>
- <tbody>
- ${payments.map(p => {
- const amount = p.amount ? formatUsdc(p.amount) : '--';
- const skill = p.skill_name || p.memo?.slice(0, 40) || 'API call';
- const agent = p._agent?.name || 'Agent';
- const status = (p.status || 'pending').toLowerCase();
- const tag = status === 'confirmed' || status === 'completed' || status === 'settled'
- ? '<span class="dn-tag success">Settled</span>'
- : status === 'failed'
- ? '<span class="dn-tag danger">Failed</span>'
- : '<span class="dn-tag warn">Pending</span>';
- return `
- <tr>
- <td style="color:var(--nxt-ink-dim);white-space:nowrap">${esc(relTime(p.created_at))}</td>
- <td style="font-weight:500">${esc(skill)}</td>
- <td style="text-align:right;font-variant-numeric:tabular-nums;color:var(--nxt-success)">${esc(amount)}</td>
- <td style="color:var(--nxt-ink-dim)">${esc(agent)}</td>
- <td>${tag}</td>
- </tr>`;
- }).join('')}
- </tbody>
- </table>
- </div>
- `;
- return panel;
-}
-
-// -- Funnel --
-
-function renderFunnel({ totalViews, totalChats, revPayments }) {
- const panel = document.createElement('div');
- panel.className = 'dn-panel ana-funnel-panel';
-
- const steps = [
- { label: 'Widget Views', value: totalViews, color: '#60a5fa' },
- { label: 'Conversations', value: totalChats, color: '#888888' },
- { label: 'Payments', value: revPayments, color: '#4ade80' },
- ];
- const max = Math.max(1, steps[0].value);
-
- panel.innerHTML = `
- <div class="dn-panel-title">Conversion Funnel</div>
- <div class="dn-panel-sub">How visitors convert from views to payments (${range.label})</div>
- <div class="ana-funnel">
- ${steps.map((s, i) => {
- const pct = Math.round((s.value / max) * 100);
- const dropoff = i > 0 && steps[i - 1].value > 0
- ? ((1 - s.value / steps[i - 1].value) * 100).toFixed(1) + '% drop'
- : '';
- return `
- <div class="ana-funnel-step">
- <div class="ana-funnel-label">${esc(s.label)}</div>
- <div class="ana-funnel-bar-wrap">
- <div class="ana-funnel-bar" style="width:${Math.max(2, pct)}%;background:${s.color}"></div>
- </div>
- <div class="ana-funnel-val">${s.value.toLocaleString()}</div>
- ${dropoff ? `<div class="ana-funnel-drop">${dropoff}</div>` : ''}
- </div>
- `;
- }).join('')}
- </div>
- `;
- return panel;
-}
-
-// -- Range bar --
-
-function renderRangeBar(root) {
- const bar = document.createElement('div');
- bar.className = 'ana-range-bar';
- bar.setAttribute('role', 'group');
- bar.setAttribute('aria-label', 'Select analytics time range');
- bar.innerHTML = RANGES.map(r => {
- const active = r.key === range.key;
- return `<button type="button" class="ana-range-btn${active ? ' is-active' : ''}" data-range="${r.key}" aria-pressed="${active}" aria-label="Show the last ${esc(r.label)}">${r.label}</button>`;
- }).join('');
- return bar;
-}
-
-// -- Helpers --
-
-function renderTwoCol(left, right) {
- const wrap = document.createElement('div');
- wrap.className = 'ana-two-col';
- wrap.appendChild(left);
- wrap.appendChild(right);
- return wrap;
-}
-
-// -- Styles --
-
-function injectStyles() {
- if (document.getElementById('ana-styles')) return;
- const style = document.createElement('style');
- style.id = 'ana-styles';
- style.textContent = `
-.ana-root { display: flex; flex-direction: column; gap: 18px; min-width: 0; }
-
-.ana-range-bar { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 2px; }
-.ana-range-btn { padding: 6px 16px; border: 1px solid var(--nxt-stroke); border-radius: 8px; background: none; color: var(--nxt-ink-dim); font: inherit; font-size: 12px; font-weight: 500; cursor: pointer; transition: background 0.12s, color 0.12s, border-color 0.12s; }
-.ana-range-btn:hover { background: rgba(255,255,255,0.04); color: var(--nxt-ink); }
-.ana-range-btn.is-active { background: rgba(74,222,128,0.12); color: #4ade80; border-color: rgba(74,222,128,0.3); }
-
-.ana-kpi-row { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; }
-.ana-kpi { padding: 18px 20px; }
-.ana-kpi-label { font-size: 12px; color: var(--nxt-ink-dim); margin-bottom: 4px; text-transform: uppercase; letter-spacing: 0.04em; font-weight: 500; }
-.ana-kpi-value { font-size: 26px; font-weight: 700; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
-.ana-kpi-sub { font-size: 12px; color: var(--nxt-ink-fade); margin-top: 2px; }
-
-.ana-chart-panel { padding: 20px; }
-.ana-chart-empty { padding: 40px 0; text-align: center; color: var(--nxt-ink-dim); font-size: 13px; }
-.ana-chart-empty a { color: var(--nxt-success); }
-
-.ana-ret-summary { font-size: 13px; color: var(--nxt-ink-dim); margin-top: 6px; }
-.ana-ret-summary strong { color: var(--nxt-ink); font-variant-numeric: tabular-nums; }
-.ana-ret-legend { display: flex; flex-wrap: wrap; gap: 14px; margin-top: 10px; font-size: 11px; color: var(--nxt-ink-fade); }
-.ana-ret-legend span { display: inline-flex; align-items: center; gap: 6px; }
-.ana-ret-swatch { width: 10px; height: 10px; border-radius: 2px; display: inline-block; }
-.ana-ret-swatch.is-hit { background: #4ade80; }
-.ana-ret-swatch.is-miss { background: #fbbf24; }
-.ana-ret-swatch.is-open { background: rgba(148,163,184,0.45); }
-
-.ana-two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
-.ana-two-col > * { min-width: 0; }
-
-.ana-tbl-wrap { overflow-x: auto; margin-top: 12px; }
-.ana-tbl { width: 100%; border-collapse: collapse; font-size: 13px; }
-.ana-tbl th { text-align: left; font-weight: 500; color: var(--nxt-ink-dim); font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; padding: 8px 10px; border-bottom: 1px solid var(--nxt-stroke); }
-.ana-tbl td { padding: 10px; border-bottom: 1px solid rgba(255,255,255,0.04); }
-.ana-tbl-name { font-weight: 500; max-width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-.ana-tbl tbody tr:hover { background: rgba(255,255,255,0.02); }
-
-.ana-funnel-panel { padding: 20px; }
-.ana-funnel { display: flex; flex-direction: column; gap: 14px; margin-top: 16px; }
-.ana-funnel-step { display: grid; grid-template-columns: 120px 1fr 70px 80px; gap: 10px; align-items: center; }
-.ana-funnel-label { font-size: 13px; font-weight: 500; }
-.ana-funnel-bar-wrap { height: 24px; background: rgba(255,255,255,0.03); border-radius: 6px; overflow: hidden; }
-.ana-funnel-bar { height: 100%; border-radius: 6px; transition: width 0.4s ease; }
-.ana-funnel-val { text-align: right; font-weight: 600; font-size: 15px; }
-.ana-funnel-drop { font-size: 11px; color: rgba(248,113,113,0.8); text-align: right; }
-
-@media (max-width: 900px) {
- .ana-kpi-row { grid-template-columns: repeat(2, 1fr); }
- .ana-two-col { grid-template-columns: 1fr; }
- .ana-funnel-step { grid-template-columns: 100px 1fr 60px; }
- .ana-funnel-drop { display: none; }
-}
-@media (max-width: 600px) {
- .ana-kpi-row { grid-template-columns: 1fr; }
- .ana-kpi-value { font-size: 22px; }
-}
-`;
- document.head.appendChild(style);
-}
diff --git a/src/x402-revenue.css b/src/x402-revenue.css
deleted file mode 100644
index d36a5af6e..000000000
--- a/src/x402-revenue.css
+++ /dev/null
@@ -1,1092 +0,0 @@
-/* Endpoint Revenue — the live view of USDC flowing into three.ws x402 endpoints.
- Self-contained (xr- prefix); leans on the shared theme tokens so it tracks
- light/dark like every other surface. Revenue-tinted, glass + glow, motion-safe. */
-
-.xr-shell {
- --xr-accent: var(--success, #38d39f);
- --xr-accent-2: #3ab8e0;
- --xr-up: var(--success, #38d39f);
- --xr-down: #f0637a;
- --xr-grad: linear-gradient(135deg, var(--xr-accent) 0%, var(--xr-accent-2) 100%);
- position: relative;
- max-width: 1240px;
- margin: 0 auto;
- padding: clamp(20px, 5vw, 56px) clamp(16px, 4vw, 32px) 96px;
- font-family: var(--font-body, system-ui, sans-serif);
- color: var(--ink, #d8d8d8);
-}
-
-/* ambient glow behind the hero. The side bleed is capped at the viewport:
- the shell is centered, so (100% - 100vw) / 2 is exactly the negative offset
- that reaches the viewport edge; the extra 12px stays clear of the scrollbar
- gutter so the glow can never create horizontal scroll. The mask fades the
- capped edges so the clamp is invisible at any width. */
-.xr-glow {
- position: absolute;
- inset: -10% auto auto auto;
- left: max(-20%, calc((100% - 100vw) / 2 + 12px));
- right: max(-20%, calc((100% - 100vw) / 2 + 12px));
- height: 420px;
- mask-image: linear-gradient(
- to right,
- transparent,
- #000 32px,
- #000 calc(100% - 32px),
- transparent
- );
- -webkit-mask-image: linear-gradient(
- to right,
- transparent,
- #000 32px,
- #000 calc(100% - 32px),
- transparent
- );
- background:
- radial-gradient(
- 60% 80% at 20% 0%,
- color-mix(in srgb, var(--xr-accent) 20%, transparent),
- transparent 70%
- ),
- radial-gradient(
- 50% 70% at 85% 10%,
- color-mix(in srgb, var(--xr-accent-2) 16%, transparent),
- transparent 70%
- );
- filter: blur(20px);
- pointer-events: none;
- z-index: 0;
- opacity: 0.8;
-}
-.xr-shell > *:not(.xr-glow) {
- position: relative;
- z-index: 1;
-}
-
-/* ── hero ─────────────────────────────────────────────────────────────────── */
-.xr-hero {
- display: flex;
- align-items: flex-end;
- justify-content: space-between;
- gap: var(--space-lg, 24px);
- flex-wrap: wrap;
- margin-bottom: var(--space-xl, 32px);
-}
-.xr-hero-copy {
- min-width: 0;
- flex: 1 1 420px;
-}
-.xr-kicker {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- font-family: var(--font-mono, ui-monospace, monospace);
- font-size: var(--text-2xs, 0.72rem);
- letter-spacing: 0.14em;
- text-transform: uppercase;
- color: var(--xr-accent);
- margin: 0 0 var(--space-sm, 12px);
-}
-.xr-live-dot {
- width: 8px;
- height: 8px;
- border-radius: 50%;
- background: var(--xr-accent);
- box-shadow: 0 0 0 0 color-mix(in srgb, var(--xr-accent) 50%, transparent);
- animation: xr-ping 2.4s ease infinite;
-}
-@keyframes xr-ping {
- 0% {
- box-shadow: 0 0 0 0 color-mix(in srgb, var(--xr-accent) 45%, transparent);
- }
- 70% {
- box-shadow: 0 0 0 9px transparent;
- }
- 100% {
- box-shadow: 0 0 0 0 transparent;
- }
-}
-.xr-title {
- font-family: var(--font-display, 'Space Grotesk', sans-serif);
- font-size: clamp(2.4rem, 6vw, 3.6rem);
- font-weight: 700;
- line-height: 1;
- margin: 0 0 var(--space-sm, 12px);
- color: var(--ink-bright, #fff);
- letter-spacing: -0.025em;
-}
-.xr-title em {
- font-style: normal;
- background: var(--xr-grad);
- -webkit-background-clip: text;
- background-clip: text;
- -webkit-text-fill-color: transparent;
- color: var(--xr-accent);
-}
-.xr-sub {
- max-width: 68ch;
- margin: 0;
- font-size: var(--text-sm, 0.92rem);
- line-height: 1.6;
- color: var(--ink-dim, #9a9a9a);
-}
-.xr-sub a,
-.xr-note a {
- color: var(--ink-bright, #fff);
- text-decoration: underline;
- text-underline-offset: 2px;
-}
-.xr-sub a:hover,
-.xr-note a:hover {
- color: var(--xr-accent);
-}
-
-.xr-hero-controls {
- display: flex;
- flex-direction: column;
- align-items: flex-end;
- gap: 8px;
-}
-.xr-period {
- display: inline-flex;
- gap: 2px;
- padding: 4px;
- background: var(--surface-1, #121212);
- border: 1px solid var(--stroke, #2a2a2a);
- border-radius: var(--radius-pill, 999px);
-}
-.xr-period-btn {
- appearance: none;
- border: 0;
- background: transparent;
- cursor: pointer;
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.74rem);
- color: var(--ink-dim, #9a9a9a);
- padding: 7px 16px;
- border-radius: var(--radius-pill, 999px);
- transition:
- color 0.15s ease,
- background 0.15s ease,
- transform 0.1s ease;
-}
-.xr-period-btn:hover {
- color: var(--ink-bright, #fff);
-}
-.xr-period-btn:active {
- transform: scale(0.96);
-}
-.xr-period-btn.active {
- background: var(--xr-grad);
- color: #05221a;
- font-weight: 600;
-}
-.xr-period-btn:focus-visible {
- outline: 2px solid var(--xr-accent);
- outline-offset: 2px;
-}
-.xr-updated {
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.72rem);
- color: var(--ink-faint, #6a6a6a);
-}
-/* Degraded reads are said out loud rather than left to a frozen timestamp. */
-.xr-updated[data-state='stale'] {
- color: var(--warn, #e0a458);
-}
-.xr-updated[data-state='error'] {
- color: var(--danger, #e06c75);
-}
-
-/* ── glass surface shared ─────────────────────────────────────────────────── */
-.xr-showcase,
-.xr-kpi,
-.xr-card,
-.xr-row {
- background: color-mix(in srgb, var(--surface-1, #121212) 82%, transparent);
- border: 1px solid var(--stroke, #2a2a2a);
- border-radius: var(--radius-lg, 16px);
- backdrop-filter: blur(8px);
- -webkit-backdrop-filter: blur(8px);
-}
-
-/* ── showcase: big number + chart ─────────────────────────────────────────── */
-.xr-showcase {
- padding: clamp(18px, 3vw, 28px);
- margin-bottom: var(--space-lg, 20px);
- overflow: hidden;
-}
-.xr-showcase-head {
- display: flex;
- align-items: flex-start;
- justify-content: space-between;
- gap: var(--space-lg, 24px);
- flex-wrap: wrap;
-}
-.xr-big {
- display: flex;
- flex-direction: column;
- gap: 4px;
- min-width: 0;
-}
-.xr-big-label {
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.72rem);
- letter-spacing: 0.06em;
- text-transform: uppercase;
- color: var(--ink-dim, #9a9a9a);
-}
-.xr-big-val {
- font-family: var(--font-display, sans-serif);
- font-weight: 800;
- font-size: clamp(2.6rem, 7vw, 4.4rem);
- line-height: 1;
- letter-spacing: -0.03em;
- background: var(--xr-grad);
- -webkit-background-clip: text;
- background-clip: text;
- -webkit-text-fill-color: transparent;
- font-variant-numeric: tabular-nums;
-}
-.xr-big-sub {
- font-size: var(--text-sm, 0.86rem);
- color: var(--ink-faint, #6a6a6a);
-}
-.xr-badges {
- display: flex;
- align-items: center;
- gap: var(--space-md, 14px);
- flex-wrap: wrap;
-}
-.xr-momentum {
- display: inline-flex;
- align-items: center;
- gap: 5px;
- font-family: var(--font-mono, monospace);
- font-size: var(--text-sm, 0.82rem);
- font-weight: 600;
- padding: 6px 12px;
- border-radius: var(--radius-pill, 999px);
- border: 1px solid transparent;
-}
-.xr-momentum[data-dir='up'] {
- color: var(--xr-up);
- background: color-mix(in srgb, var(--xr-up) 12%, transparent);
- border-color: color-mix(in srgb, var(--xr-up) 30%, transparent);
-}
-.xr-momentum[data-dir='down'] {
- color: var(--xr-down);
- background: color-mix(in srgb, var(--xr-down) 12%, transparent);
- border-color: color-mix(in srgb, var(--xr-down) 30%, transparent);
-}
-.xr-momentum[data-dir='flat'] {
- color: var(--ink-dim, #9a9a9a);
- background: var(--surface-2, #171717);
- border-color: var(--stroke, #2a2a2a);
-}
-.xr-runrate {
- display: flex;
- flex-direction: column;
- align-items: flex-end;
- line-height: 1.1;
-}
-.xr-runrate-val {
- font-family: var(--font-display, sans-serif);
- font-weight: 700;
- font-size: var(--text-lg, 1.25rem);
- color: var(--ink-bright, #fff);
- font-variant-numeric: tabular-nums;
-}
-.xr-runrate-label {
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.68rem);
- text-transform: uppercase;
- letter-spacing: 0.06em;
- color: var(--ink-faint, #6a6a6a);
-}
-
-.xr-chart-wrap {
- position: relative;
- margin-top: var(--space-md, 18px);
- height: 168px;
-}
-.xr-chart {
- width: 100%;
- height: 100%;
-}
-.xr-chart svg {
- display: block;
- width: 100%;
- height: 100%;
- overflow: visible;
-}
-.xr-chart-line {
- fill: none;
- stroke: var(--xr-accent);
- stroke-width: 2;
- stroke-linejoin: round;
- stroke-linecap: round;
- filter: drop-shadow(0 0 6px color-mix(in srgb, var(--xr-accent) 45%, transparent));
-}
-.xr-chart-area {
- stroke: none;
-}
-.xr-chart-dot {
- fill: var(--ink-bright, #fff);
- stroke: var(--xr-accent);
- stroke-width: 2;
-}
-.xr-chart-cross {
- stroke: color-mix(in srgb, var(--ink-dim, #9a9a9a) 60%, transparent);
- stroke-width: 1;
- stroke-dasharray: 3 3;
-}
-.xr-chart-draw {
- stroke-dasharray: var(--len, 1000);
- stroke-dashoffset: var(--len, 1000);
- animation: xr-draw 1s ease forwards;
-}
-@keyframes xr-draw {
- to {
- stroke-dashoffset: 0;
- }
-}
-.xr-chart-tip {
- position: absolute;
- top: 0;
- transform: translate(-50%, -8px);
- background: var(--surface-3, #1d1d1d);
- border: 1px solid var(--stroke-strong, #3a3a3a);
- border-radius: var(--radius-md, 8px);
- padding: 6px 10px;
- pointer-events: none;
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.72rem);
- white-space: nowrap;
- box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
- z-index: 3;
-}
-.xr-chart-tip b {
- color: var(--xr-accent);
-}
-.xr-chart-tip span {
- color: var(--ink-faint, #6a6a6a);
-}
-.xr-chart-empty {
- position: absolute;
- inset: 0;
- display: grid;
- place-items: center;
- color: var(--ink-faint, #6a6a6a);
- font-size: var(--text-sm, 0.88rem);
-}
-
-/* ── KPI cards ────────────────────────────────────────────────────────────── */
-.xr-kpis {
- display: grid;
- grid-template-columns: repeat(4, 1fr);
- gap: var(--space-sm, 12px);
- margin: 0 0 var(--space-xl, 28px);
-}
-.xr-kpi {
- padding: var(--space-md, 16px);
- display: flex;
- flex-direction: column;
- gap: 4px;
- transition:
- border-color 0.2s ease,
- transform 0.2s ease;
-}
-.xr-kpi:hover {
- border-color: color-mix(in srgb, var(--xr-accent) 35%, var(--stroke, #2a2a2a));
- transform: translateY(-2px);
-}
-.xr-kpi dt {
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.72rem);
- letter-spacing: 0.06em;
- text-transform: uppercase;
- color: var(--ink-dim, #9a9a9a);
- margin: 0;
-}
-.xr-kpi dd {
- margin: 0;
- font-family: var(--font-display, sans-serif);
- font-weight: 700;
- font-size: clamp(1.4rem, 3.4vw, 2rem);
- color: var(--ink-bright, #fff);
- line-height: 1.05;
- font-variant-numeric: tabular-nums;
-}
-.xr-kpi-sub {
- font-size: var(--text-2xs, 0.72rem);
- color: var(--ink-faint, #6a6a6a);
-}
-
-/* ── grid ─────────────────────────────────────────────────────────────────── */
-.xr-grid {
- display: grid;
- grid-template-columns: minmax(0, 1.75fr) minmax(280px, 1fr);
- gap: var(--space-lg, 24px);
- align-items: start;
-}
-.xr-main {
- min-width: 0;
-}
-
-/* ── toolbar ──────────────────────────────────────────────────────────────── */
-.xr-toolbar {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: var(--space-md, 14px);
- margin-bottom: var(--space-sm, 12px);
- flex-wrap: wrap;
-}
-.xr-toolbar-left {
- display: inline-flex;
- align-items: baseline;
- gap: var(--space-sm, 12px);
-}
-.xr-section-h {
- font-family: var(--font-display, sans-serif);
- font-size: var(--text-lg, 1.1rem);
- color: var(--ink-bright, #fff);
- margin: 0;
-}
-.xr-feed-state {
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.72rem);
- color: var(--ink-faint, #6a6a6a);
- display: inline-flex;
- align-items: center;
- gap: 6px;
-}
-.xr-feed-state::before {
- content: '';
- width: 6px;
- height: 6px;
- border-radius: 50%;
- background: currentColor;
- box-shadow: 0 0 6px currentColor;
-}
-.xr-feed-state[data-state='live'] {
- color: var(--xr-accent);
-}
-.xr-feed-state[data-state='error'] {
- color: #e0a23a;
-}
-.xr-feed-state[data-state='paused'] {
- color: var(--ink-faint, #6a6a6a);
-}
-.xr-toolbar-right {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- flex-wrap: wrap;
-}
-.xr-search {
- position: relative;
- display: inline-flex;
- align-items: center;
-}
-.xr-search-ico {
- position: absolute;
- left: 10px;
- color: var(--ink-faint, #6a6a6a);
- font-size: 0.9rem;
- pointer-events: none;
-}
-.xr-search-input {
- appearance: none;
- background: var(--surface-1, #121212);
- border: 1px solid var(--stroke, #2a2a2a);
- border-radius: var(--radius-pill, 999px);
- color: var(--ink-bright, #fff);
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.76rem);
- padding: 8px 12px 8px 30px;
- width: 190px;
- max-width: 46vw;
- transition:
- border-color 0.15s ease,
- width 0.2s ease;
-}
-.xr-search-input:focus {
- outline: none;
- border-color: var(--xr-accent);
- width: 220px;
-}
-.xr-icon-btn {
- appearance: none;
- cursor: pointer;
- display: inline-flex;
- align-items: center;
- gap: 5px;
- background: var(--surface-1, #121212);
- border: 1px solid var(--stroke, #2a2a2a);
- border-radius: var(--radius-pill, 999px);
- color: var(--ink-dim, #9a9a9a);
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.74rem);
- padding: 7px 11px;
- line-height: 1;
- transition:
- color 0.15s ease,
- border-color 0.15s ease,
- background 0.15s ease;
-}
-.xr-icon-btn:hover {
- color: var(--ink-bright, #fff);
- border-color: color-mix(in srgb, var(--xr-accent) 40%, var(--stroke, #2a2a2a));
-}
-.xr-icon-btn:focus-visible {
- outline: 2px solid var(--xr-accent);
- outline-offset: 2px;
-}
-.xr-icon-btn[aria-pressed='true'] {
- color: var(--xr-accent);
- border-color: color-mix(in srgb, var(--xr-accent) 50%, transparent);
- background: color-mix(in srgb, var(--xr-accent) 10%, transparent);
-}
-
-/* ── chips ────────────────────────────────────────────────────────────────── */
-.xr-chips {
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
- margin-bottom: var(--space-md, 14px);
-}
-.xr-chip {
- appearance: none;
- cursor: pointer;
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.72rem);
- color: var(--ink-dim, #9a9a9a);
- background: var(--surface-1, #121212);
- border: 1px solid var(--stroke, #2a2a2a);
- border-radius: var(--radius-pill, 999px);
- padding: 5px 11px;
- transition:
- color 0.15s ease,
- border-color 0.15s ease,
- background 0.15s ease;
-}
-.xr-chip:hover {
- color: var(--ink-bright, #fff);
-}
-.xr-chip.active {
- color: #05221a;
- background: var(--xr-grad);
- border-color: transparent;
- font-weight: 600;
-}
-.xr-chip:focus-visible {
- outline: 2px solid var(--xr-accent);
- outline-offset: 2px;
-}
-
-/* ── feed rows ────────────────────────────────────────────────────────────── */
-.xr-feed {
- display: flex;
- flex-direction: column;
- gap: 6px;
-}
-.xr-row {
- display: grid;
- grid-template-columns: auto 1fr auto;
- align-items: center;
- gap: var(--space-sm, 12px);
- padding: 12px 14px;
- cursor: pointer;
- transition:
- border-color 0.15s ease,
- transform 0.1s ease,
- background 0.15s ease;
-}
-.xr-row:hover {
- border-color: color-mix(in srgb, var(--xr-accent) 40%, var(--stroke, #2a2a2a));
- background: color-mix(in srgb, var(--xr-accent) 5%, var(--surface-1, #121212));
-}
-.xr-row:active {
- transform: scale(0.997);
-}
-.xr-row:focus-visible {
- outline: 2px solid var(--xr-accent);
- outline-offset: 2px;
-}
-.xr-row-glyph {
- color: var(--xr-accent);
- font-weight: 700;
- font-size: 1rem;
-}
-.xr-row-body {
- min-width: 0;
- display: flex;
- flex-direction: column;
- gap: 2px;
-}
-.xr-row-line {
- display: flex;
- align-items: center;
- gap: 8px;
- min-width: 0;
-}
-.xr-row-ep {
- font-family: var(--font-mono, monospace);
- font-size: var(--text-sm, 0.9rem);
- font-weight: 600;
- color: var(--ink-bright, #fff);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-.xr-row-payer {
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.72rem);
- color: var(--ink-faint, #6a6a6a);
-}
-.xr-row-meta {
- display: flex;
- align-items: center;
- flex-wrap: wrap;
- gap: 4px 8px;
- min-width: 0;
-}
-.xr-row-net {
- max-width: 100%;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.68rem);
- text-transform: uppercase;
- letter-spacing: 0.04em;
- color: var(--ink-dim, #9a9a9a);
- padding: 1px 6px;
- border: 1px solid var(--stroke, #2a2a2a);
- border-radius: var(--radius-pill, 999px);
-}
-.xr-row-time {
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.72rem);
- color: var(--ink-faint, #6a6a6a);
-}
-.xr-row-amt {
- display: inline-flex;
- align-items: center;
- gap: 10px;
- font-family: var(--font-display, sans-serif);
- font-weight: 700;
- color: var(--xr-accent);
- font-variant-numeric: tabular-nums;
- white-space: nowrap;
-}
-.xr-row-tx {
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.72rem);
- font-weight: 500;
- color: var(--ink-dim, #9a9a9a);
- text-decoration: none;
-}
-.xr-row-tx:hover {
- color: var(--xr-accent);
-}
-.xr-row.hidden {
- display: none;
-}
-.xr-row--new {
- animation: xr-land 0.55s ease both;
-}
-@keyframes xr-land {
- from {
- opacity: 0;
- transform: translateY(-10px);
- border-color: var(--xr-accent);
- box-shadow: 0 0 0 1px color-mix(in srgb, var(--xr-accent) 40%, transparent);
- }
- to {
- opacity: 1;
- transform: none;
- }
-}
-.xr-more {
- appearance: none;
- cursor: pointer;
- width: 100%;
- margin-top: 10px;
- padding: 11px;
- background: var(--surface-1, #121212);
- border: 1px solid var(--stroke, #2a2a2a);
- border-radius: var(--radius-md, 10px);
- color: var(--ink-dim, #9a9a9a);
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.76rem);
- transition:
- color 0.15s ease,
- border-color 0.15s ease;
-}
-.xr-more:hover {
- color: var(--ink-bright, #fff);
- border-color: color-mix(in srgb, var(--xr-accent) 40%, var(--stroke, #2a2a2a));
-}
-.xr-more:focus-visible {
- outline: 2px solid var(--xr-accent);
- outline-offset: 2px;
-}
-.xr-more:active {
- transform: translateY(1px);
-}
-
-/* feed empty + skeleton */
-.xr-feed-empty {
- border: 1px dashed var(--stroke, #2a2a2a);
- border-radius: var(--radius-lg, 16px);
- padding: var(--space-2xl, 48px) var(--space-lg, 24px);
- text-align: center;
-}
-.xr-feed-empty-h {
- font-family: var(--font-display, sans-serif);
- font-size: var(--text-lg, 1.05rem);
- color: var(--ink-bright, #fff);
- margin: 0 0 8px;
-}
-.xr-feed-empty-p {
- font-size: var(--text-sm, 0.9rem);
- color: var(--ink-dim, #9a9a9a);
- margin: 0 auto;
- max-width: 46ch;
- line-height: 1.6;
-}
-.xr-feed-empty-p a {
- color: var(--ink-bright, #fff);
-}
-.xr-feed-empty--error {
- border-style: solid;
- border-color: color-mix(in srgb, var(--danger, #e06c75) 40%, var(--stroke, #2a2a2a));
- background: color-mix(in srgb, var(--danger, #e06c75) 6%, transparent);
-}
-/* Shared recovery affordance for the feed and stats error states. */
-.xr-retry {
- appearance: none;
- cursor: pointer;
- margin-top: 16px;
- padding: 9px 18px;
- background: transparent;
- border: 1px solid var(--stroke-strong, #3a3a3a);
- border-radius: var(--radius-pill, 999px);
- color: var(--ink-bright, #fff);
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.76rem);
- transition:
- border-color 0.15s ease,
- background 0.15s ease,
- color 0.15s ease;
-}
-.xr-retry:hover:not(:disabled) {
- border-color: var(--xr-accent);
- background: color-mix(in srgb, var(--xr-accent) 10%, transparent);
-}
-.xr-retry:active:not(:disabled) {
- transform: translateY(1px);
-}
-.xr-retry:focus-visible {
- outline: 2px solid var(--xr-accent);
- outline-offset: 2px;
-}
-.xr-retry:disabled {
- cursor: progress;
- opacity: 0.6;
-}
-.xr-skel {
- height: 58px;
- border-radius: var(--radius-md, 10px);
- background: linear-gradient(
- 100deg,
- var(--surface-1, #121212) 30%,
- var(--surface-2, #1a1a1a) 50%,
- var(--surface-1, #121212) 70%
- );
- background-size: 200% 100%;
- animation: xr-shimmer 1.3s ease-in-out infinite;
-}
-.xr-skel + .xr-skel {
- margin-top: 6px;
-}
-@keyframes xr-shimmer {
- from {
- background-position: 200% 0;
- }
- to {
- background-position: -200% 0;
- }
-}
-
-/* ── rail ─────────────────────────────────────────────────────────────────── */
-.xr-rail {
- display: flex;
- flex-direction: column;
- gap: var(--space-md, 16px);
- position: sticky;
- top: 84px;
-}
-.xr-card {
- padding: var(--space-md, 16px);
-}
-.xr-card--quiet {
- background: color-mix(in srgb, var(--surface-2, #161616) 82%, transparent);
-}
-.xr-card-h {
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.72rem);
- text-transform: uppercase;
- letter-spacing: 0.08em;
- color: var(--ink-dim, #9a9a9a);
- margin-bottom: var(--space-md, 14px);
- display: flex;
- justify-content: space-between;
- align-items: baseline;
-}
-.xr-card-h small {
- text-transform: none;
- letter-spacing: 0;
- color: var(--ink-faint, #6a6a6a);
-}
-.xr-empty {
- font-size: var(--text-sm, 0.88rem);
- color: var(--ink-faint, #6a6a6a);
- margin: 0;
-}
-
-/* top endpoints */
-.xr-top-row {
- position: relative;
- display: grid;
- grid-template-columns: 1fr auto;
- align-items: center;
- gap: 8px;
- padding: 9px 10px;
- border-radius: var(--radius-md, 8px);
- overflow: hidden;
- cursor: pointer;
- transition: background 0.15s ease;
-}
-.xr-top-row:hover {
- background: color-mix(in srgb, var(--xr-accent) 8%, transparent);
-}
-.xr-top-row.active {
- outline: 1px solid color-mix(in srgb, var(--xr-accent) 50%, transparent);
-}
-.xr-top-row:focus-visible {
- outline: 2px solid var(--xr-accent);
- outline-offset: 1px;
-}
-.xr-top-row + .xr-top-row {
- margin-top: 2px;
-}
-.xr-top-bar {
- position: absolute;
- inset: 0 auto 0 0;
- height: 100%;
- background: color-mix(in srgb, var(--xr-accent) 16%, transparent);
- z-index: 0;
- border-radius: var(--radius-md, 8px);
- transition: width 0.6s cubic-bezier(0.22, 1, 0.36, 1);
-}
-.xr-top-name,
-.xr-top-val {
- position: relative;
- z-index: 1;
-}
-.xr-top-name {
- font-family: var(--font-mono, monospace);
- font-size: var(--text-sm, 0.85rem);
- color: var(--ink-bright, #fff);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-.xr-top-val {
- font-family: var(--font-display, sans-serif);
- font-weight: 700;
- color: var(--ink-bright, #fff);
- text-align: right;
- font-variant-numeric: tabular-nums;
-}
-.xr-top-val small {
- display: block;
- font-weight: 400;
- font-size: var(--text-2xs, 0.68rem);
- color: var(--ink-faint, #6a6a6a);
-}
-
-/* network split: each row filters the feed to that chain */
-.xr-net-row {
- display: grid;
- grid-template-columns: minmax(52px, max-content) minmax(0, 1fr) auto;
- align-items: center;
- gap: 8px;
- padding: 6px 8px;
- margin: 0 -8px;
- border-radius: var(--radius-md, 8px);
- cursor: pointer;
- transition: background 0.15s ease;
-}
-.xr-net-row:hover {
- background: color-mix(in srgb, var(--xr-accent) 8%, transparent);
-}
-.xr-net-row.active {
- outline: 1px solid color-mix(in srgb, var(--xr-accent) 50%, transparent);
-}
-.xr-net-row:focus-visible {
- outline: 2px solid var(--xr-accent);
- outline-offset: 1px;
-}
-.xr-net-name {
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.74rem);
- color: var(--ink-bright, #fff);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-.xr-net-track {
- height: 8px;
- background: var(--surface-3, #1d1d1d);
- border-radius: var(--radius-pill, 999px);
- overflow: hidden;
-}
-.xr-net-fill {
- height: 100%;
- border-radius: var(--radius-pill, 999px);
- background: var(--xr-grad);
- transition: width 0.6s cubic-bezier(0.22, 1, 0.36, 1);
-}
-.xr-net-val {
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.72rem);
- color: var(--ink-dim, #9a9a9a);
- font-variant-numeric: tabular-nums;
- text-align: right;
-}
-.xr-net-val small {
- display: block;
- font-size: var(--text-3xs, 0.64rem);
- color: var(--ink-faint, #6a6a6a);
-}
-
-.xr-note {
- font-size: var(--text-sm, 0.85rem);
- color: var(--ink-dim, #9a9a9a);
- margin: 0 0 10px;
- line-height: 1.6;
-}
-.xr-hint {
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.7rem);
- color: var(--ink-faint, #6a6a6a);
- margin: 0;
- line-height: 1.9;
-}
-.xr-hint kbd {
- font-family: var(--font-mono, monospace);
- background: var(--surface-3, #1d1d1d);
- border: 1px solid var(--stroke, #2a2a2a);
- border-radius: 4px;
- padding: 1px 5px;
- color: var(--ink-bright, #fff);
-}
-.xr-fineprint {
- font-size: var(--text-2xs, 0.72rem);
- color: var(--ink-faint, #6a6a6a);
- margin: 0;
- line-height: 1.5;
-}
-
-/* ── toast ────────────────────────────────────────────────────────────────── */
-.xr-toast {
- position: fixed;
- left: 50%;
- bottom: 28px;
- transform: translateX(-50%) translateY(10px);
- background: var(--surface-3, #1d1d1d);
- border: 1px solid var(--stroke-strong, #3a3a3a);
- border-radius: var(--radius-pill, 999px);
- padding: 10px 18px;
- font-family: var(--font-mono, monospace);
- font-size: var(--text-2xs, 0.76rem);
- color: var(--ink-bright, #fff);
- box-shadow: 0 12px 34px rgba(0, 0, 0, 0.45);
- opacity: 0;
- transition:
- opacity 0.2s ease,
- transform 0.2s ease;
- z-index: 50;
-}
-.xr-toast.show {
- opacity: 1;
- transform: translateX(-50%) translateY(0);
-}
-
-/* ── responsive ───────────────────────────────────────────────────────────── */
-@media (max-width: 960px) {
- .xr-kpis {
- grid-template-columns: repeat(2, 1fr);
- }
- .xr-grid {
- grid-template-columns: 1fr;
- }
- .xr-rail {
- position: static;
- }
-}
-@media (max-width: 560px) {
- .xr-hero {
- flex-direction: column;
- align-items: stretch;
- }
- .xr-hero-controls {
- align-items: flex-start;
- }
- .xr-showcase-head {
- flex-direction: column;
- }
- .xr-badges {
- align-self: stretch;
- justify-content: space-between;
- }
- .xr-runrate {
- align-items: flex-start;
- }
- .xr-toolbar {
- align-items: stretch;
- }
- .xr-toolbar-right {
- justify-content: space-between;
- }
- .xr-search-input {
- width: 100%;
- max-width: none;
- }
- .xr-search {
- flex: 1 1 100%;
- order: 3;
- }
-}
-
-@media (prefers-reduced-motion: reduce) {
- .xr-live-dot,
- .xr-row--new,
- .xr-skel,
- .xr-chart-draw {
- animation: none;
- }
- .xr-chart-draw {
- stroke-dashoffset: 0;
- }
- .xr-top-bar,
- .xr-net-fill,
- .xr-kpi,
- .xr-row {
- transition: none;
- }
-}
diff --git a/src/x402-revenue.js b/src/x402-revenue.js
deleted file mode 100644
index 2b478328a..000000000
--- a/src/x402-revenue.js
+++ /dev/null
@@ -1,996 +0,0 @@
-/**
- * Endpoint Revenue — the public, live view of USDC flowing INTO three.ws's own
- * x402 paid endpoints. The mirror of the Money Pulse (which shows agent SPEND):
- * this page reads the platform's revenue ledger via GET /api/x402-revenue.
- *
- * GET /api/x402-revenue?view=stats&period= totals, per-endpoint, per-network,
- * time-series, momentum, health
- * GET /api/x402-revenue?view=feed&… recent settlements (keyset, filterable)
- * GET /api/x402-revenue?since=<iso>&… delta poll — only newer settlements
- * GET /api/x402-revenue?view=export&… CSV of the window
- *
- * Every row is a real, explorer-verifiable settlement. No synthetic events: a
- * quiet platform shows an honest empty state.
- */
-import { updateValue } from './ui-juice.js';
-import { timeAgo } from './shared/pulse-format.js';
-
-const POLL_MS = 12_000; // live delta cadence when visible
-const STATS_REFRESH_MS = 60_000;
-const PERIODS = ['24h', '7d', '30d', 'all'];
-// Chain families the API filters by ('solana', 'base', 'eip155-8453', …). The
-// ledger stores CAIP-2 ids; the API folds them to these slugs, so the page never
-// needs a hardcoded chain list: it validates the shape and lets the API decide.
-const NETWORK_SLUG_RE = /^[a-z0-9][a-z0-9-]{1,31}$/;
-
-const $ = (id) => document.getElementById(id);
-
-const state = {
- period: '24h',
- endpoint: null, // slug feed filter
- network: null, // chain-family feed filter
- query: '', // client-side search
- paused: false,
- sound: false,
- seen: new Set(),
- latestTs: null,
- cursor: null, // oldest ts loaded (load-more)
- pollTimer: null,
- statsTimer: null,
- firstChart: true,
- feedState: 'loading', // mirrors the live-state chip, survives an i18n repaint
- hasStats: false, // a successful stats render has landed at least once
- hasFeed: false, // the feed has rendered rows or an honest empty state
-};
-
-// ── formatters ───────────────────────────────────────────────────────────────
-function fmtUsd(v) {
- const n = Number(v) || 0;
- if (n === 0) return '$0';
- if (n >= 1_000_000) return `$${(n / 1_000_000).toFixed(2)}M`;
- if (n >= 1000) return `$${(n / 1000).toFixed(1)}k`;
- if (n >= 1) return `$${n.toFixed(2)}`;
- if (n >= 0.01) return `$${n.toFixed(3)}`;
- return `$${n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '')}`;
-}
-function fmtInt(v) {
- return new Intl.NumberFormat('en-US').format(Math.round(Number(v) || 0));
-}
-function fmtPct(v) {
- return `${Math.round((Number(v) || 0) * 100)}%`;
-}
-function fmtSignedPct(v) {
- const n = Math.round((Number(v) || 0) * 100);
- return `${n > 0 ? '+' : ''}${n}%`;
-}
-function esc(s) {
- return String(s ?? '').replace(
- /[&<>"']/g,
- (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
- );
-}
-// '/api/x402/token-intel' → 'token-intel'
-function endpointLabel(route) {
- const m = String(route || '').match(/\/api\/x402\/([^?]+)/);
- return m ? m[1] : (route || 'unknown').replace(/^\/api\//, '');
-}
-
-// ── URL deep-link ────────────────────────────────────────────────────────────
-function readUrl() {
- const p = new URLSearchParams(location.search);
- const per = p.get('period');
- if (PERIODS.includes(per)) state.period = per;
- const ep = (p.get('endpoint') || '').replace(/[^a-z0-9-]/gi, '');
- if (ep) state.endpoint = ep;
- const net = (p.get('network') || '').trim().toLowerCase();
- if (NETWORK_SLUG_RE.test(net)) state.network = net;
-}
-function writeUrl() {
- const p = new URLSearchParams();
- if (state.period !== '24h') p.set('period', state.period);
- if (state.endpoint) p.set('endpoint', state.endpoint);
- if (state.network) p.set('network', state.network);
- const qs = p.toString();
- history.replaceState(null, '', qs ? `${location.pathname}?${qs}` : location.pathname);
-}
-function feedParams(extra = {}) {
- const p = new URLSearchParams();
- if (state.endpoint) p.set('endpoint', state.endpoint);
- if (state.network) p.set('network', state.network);
- for (const [k, v] of Object.entries(extra)) if (v != null) p.set(k, String(v));
- return p.toString();
-}
-
-// ── toast ─────────────────────────────────────────────────────────────────────
-let toastTimer = null;
-function toast(msg) {
- const el = $('xr-toast');
- if (!el) return;
- el.textContent = msg;
- el.hidden = false;
- requestAnimationFrame(() => el.classList.add('show'));
- clearTimeout(toastTimer);
- toastTimer = setTimeout(() => {
- el.classList.remove('show');
- setTimeout(() => (el.hidden = true), 220);
- }, 1800);
-}
-
-// ── stats ─────────────────────────────────────────────────────────────────────
-function setCounter(id, value, format) {
- const el = $(id);
- if (!el) return;
- if (value == null || !Number.isFinite(Number(value))) {
- el.textContent = '—';
- delete el.dataset.juiceVal;
- return;
- }
- updateValue(el, Number(value), format);
-}
-
-async function loadStats() {
- let data = null;
- let reason = '';
- try {
- const res = await fetch(
- `/api/x402-revenue?view=stats&period=${encodeURIComponent(state.period)}`,
- {
- headers: { accept: 'application/json' },
- },
- );
- if (res.ok) ({ data } = await res.json());
- else
- reason =
- res.status === 503
- ? 'The revenue ledger is temporarily unavailable.'
- : `The revenue service answered ${res.status}.`;
- } catch {
- reason = 'The revenue service could not be reached.';
- }
- if (!data) {
- // A blip after a good render keeps the last-known numbers (they are still
- // true, just ageing); a failure before any render has nothing to show, so
- // the page says so and offers the retry instead of sitting on em-dashes.
- if (state.hasStats) markStale();
- else renderStatsError(reason || 'Revenue data is unavailable right now.');
- return;
- }
- state.hasStats = true;
- renderStats(data);
- const u = $('xr-updated');
- if (u) {
- u.dataset.state = 'ok';
- u.textContent = `updated ${timeAgo(new Date().toISOString())}`;
- }
-}
-
-// A degraded-but-not-empty signal: the numbers on screen are the last good ones.
-function markStale() {
- const u = $('xr-updated');
- if (!u) return;
- u.dataset.state = 'stale';
- u.textContent = 'reconnecting to the revenue ledger…';
-}
-
-// Nothing has ever loaded: replace every data region with one honest, actionable
-// explanation rather than leaving placeholder dashes and a spinner forever.
-function renderStatsError(reason) {
- const u = $('xr-updated');
- if (u) {
- u.dataset.state = 'error';
- u.textContent = 'revenue data unavailable';
- }
- const chartHost = $('xr-chart');
- if (chartHost) chartHost.innerHTML = '';
- const empty = $('xr-chart-empty');
- if (empty) {
- empty.hidden = false;
- empty.textContent = reason;
- }
- for (const id of ['xr-top', 'xr-networks']) {
- const host = $(id);
- if (host) host.innerHTML = `<p class="xr-empty">${esc(reason)}</p>`;
- }
- const chips = $('xr-chips');
- if (chips) chips.innerHTML = '';
- mountRetry('xr-stats-retry', $('xr-top'), () => {
- loadStats();
- if (!state.hasFeed) loadInitialFeed();
- });
-}
-
-// One retry affordance, reused by the stats and feed error states. Replaces any
-// previous instance so repeated failures never stack up buttons.
-function mountRetry(id, host, onRetry) {
- if (!host) return;
- document.getElementById(id)?.remove();
- const btn = document.createElement('button');
- btn.type = 'button';
- btn.id = id;
- btn.className = 'xr-retry';
- btn.textContent = 'Try again';
- btn.addEventListener('click', () => {
- btn.disabled = true;
- btn.textContent = 'Retrying…';
- onRetry();
- });
- host.appendChild(btn);
-}
-
-function renderStats(d) {
- const t = d.totals || {};
- setCounter('xr-c-gross', Number(t.gross_usd), fmtUsd);
- setCounter('xr-c-count', Number(t.total_payments), fmtInt);
- setCounter('xr-c-payers', Number(t.unique_payers), fmtInt);
- setCounter('xr-c-net', Number(t.net_platform_usd), fmtUsd);
-
- const health = d.settlement_health || {};
- setCounter('xr-c-success', Number(health.success_rate), fmtPct);
- const ss = $('xr-c-success-sub');
- if (ss)
- ss.textContent = `${fmtInt(health.settled || 0)} ok · ${fmtInt(health.failed || 0)} failed`;
-
- const gs = $('xr-c-gross-sub');
- if (gs)
- gs.textContent = `${fmtInt(t.total_payments || 0)} settled · avg ${fmtUsd(t.avg_payment_usd)}`;
-
- for (const id of ['xr-window-label', 'xr-top-window', 'xr-net-window']) {
- const el = $(id);
- if (el) el.textContent = d.period || state.period;
- }
-
- renderMomentum(d.momentum);
- renderRunRate(d.momentum);
- renderChart(d.series);
- renderTopEndpoints(d.by_endpoint || []);
- renderNetworks(d.by_network || []);
- renderChips(d.by_endpoint || [], d.by_network || []);
-}
-
-function renderMomentum(m) {
- const el = $('xr-momentum');
- if (!el) return;
- if (!m || m.change_pct == null) {
- el.hidden = true;
- return;
- }
- const pct = Number(m.change_pct);
- const dir = pct > 0.001 ? 'up' : pct < -0.001 ? 'down' : 'flat';
- el.dataset.dir = dir;
- const arrow = dir === 'up' ? '▲' : dir === 'down' ? '▼' : '→';
- el.textContent = `${arrow} ${fmtSignedPct(pct)} vs prev ${state.period}`;
- el.hidden = false;
-}
-
-function renderRunRate(m) {
- const el = $('xr-runrate');
- if (!el) return;
- el.textContent = m && m.per_hour_usd != null ? fmtUsd(m.per_hour_usd) : '—';
-}
-
-function renderTopEndpoints(rows) {
- const host = $('xr-top');
- if (!host) return;
- if (!rows.length) {
- host.innerHTML = `<p class="xr-empty">No endpoint has earned in this window yet.</p>`;
- return;
- }
- const max = Math.max(...rows.map((r) => Number(r.gross_usd) || 0), 0);
- host.innerHTML = rows
- .slice(0, 8)
- .map((r) => {
- const g = Number(r.gross_usd) || 0;
- const slug = endpointLabel(r.endpoint);
- const pct = max > 0 ? Math.max(2, Math.round((g / max) * 100)) : 2;
- const active = state.endpoint === slug ? ' active' : '';
- return (
- `<div class="xr-top-row${active}" role="button" tabindex="0" data-endpoint="${esc(slug)}" aria-label="Filter feed to ${esc(slug)}">` +
- `<span class="xr-top-bar" style="width:${pct}%" aria-hidden="true"></span>` +
- `<span class="xr-top-name">${esc(slug)}</span>` +
- `<span class="xr-top-val">${fmtUsd(g)}<small>${fmtInt(r.count)} call${r.count === 1 ? '' : 's'}</small></span>` +
- `</div>`
- );
- })
- .join('');
- for (const el of host.querySelectorAll('[data-endpoint]')) {
- const slug = el.dataset.endpoint;
- el.addEventListener('click', () => toggleEndpoint(slug));
- el.addEventListener('keydown', (e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- toggleEndpoint(slug);
- }
- });
- }
-}
-
-// The rail rows double as the network filter: clicking one scopes the feed to
-// that chain, the same toggle the chips above the feed drive.
-function renderNetworks(rows) {
- const host = $('xr-networks');
- if (!host) return;
- const real = rows.filter((r) => Number(r.gross_usd) > 0 || Number(r.count) > 0);
- if (!real.length) {
- host.innerHTML = `<p class="xr-empty">No network revenue in this window yet.</p>`;
- return;
- }
- const max = Math.max(...real.map((r) => Number(r.gross_usd) || 0), 0);
- host.innerHTML = real
- .map((r) => {
- const g = Number(r.gross_usd) || 0;
- const pct = max > 0 ? Math.max(3, Math.round((g / max) * 100)) : 3;
- const slug = r.network || 'unknown';
- const label = r.label || slug;
- const active = state.network === slug ? ' active' : '';
- return (
- `<div class="xr-net-row${active}" role="button" tabindex="0" data-network="${esc(slug)}" ` +
- `aria-label="Filter feed to ${esc(label)}">` +
- `<span class="xr-net-name">${esc(label)}</span>` +
- `<span class="xr-net-track"><span class="xr-net-fill" style="width:${pct}%"></span></span>` +
- `<span class="xr-net-val">${fmtUsd(g)}<small>${fmtInt(r.count)} call${r.count === 1 ? '' : 's'}</small></span>` +
- `</div>`
- );
- })
- .join('');
- for (const el of host.querySelectorAll('[data-network]')) {
- const slug = el.dataset.network;
- el.addEventListener('click', () => toggleNetwork(slug));
- el.addEventListener('keydown', (e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- toggleNetwork(slug);
- }
- });
- }
-}
-
-// ── SVG area chart ────────────────────────────────────────────────────────────
-function bucketStepMs(unit) {
- return unit === 'day' ? 86_400_000 : 3_600_000;
-}
-function truncUTC(ms, unit) {
- const d = new Date(ms);
- if (unit === 'day') d.setUTCHours(0, 0, 0, 0);
- else d.setUTCMinutes(0, 0, 0);
- return d.getTime();
-}
-// Fill gaps (buckets with no revenue) so the area stays continuous and honest.
-function fillGaps(series) {
- const unit = series?.unit || 'hour';
- const pts = (series?.points || []).map((p) => ({
- ms: Date.parse(p.ts),
- gross: Number(p.gross_usd) || 0,
- count: p.count || 0,
- }));
- if (!pts.length) return { unit, points: [] };
- const step = bucketStepMs(unit);
- const map = new Map(pts.map((p) => [truncUTC(p.ms, unit), p]));
- const start = truncUTC(pts[0].ms, unit);
- const end = truncUTC(Date.now(), unit);
- const out = [];
- for (let t = start; t <= end && out.length < 400; t += step) {
- const p = map.get(t);
- out.push({
- ts: new Date(t).toISOString(),
- gross_usd: p ? p.gross : 0,
- count: p ? p.count : 0,
- });
- }
- return { unit, points: out };
-}
-function bucketLabel(iso, unit) {
- const d = new Date(iso);
- if (unit === 'day') return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
- return d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
-}
-
-function renderChart(series) {
- const host = $('xr-chart');
- const empty = $('xr-chart-empty');
- if (!host) return;
- const filled = fillGaps(series);
- const points = filled.points;
- const hasData = points.some((p) => p.gross_usd > 0);
- if (!points.length || !hasData) {
- host.innerHTML = '';
- if (empty) {
- empty.textContent = 'No revenue in this window yet.';
- empty.hidden = false;
- }
- host._points = null;
- return;
- }
- if (empty) empty.hidden = true;
-
- const W = 800;
- const H = 160;
- const pad = 8;
- const n = points.length;
- const max = Math.max(...points.map((p) => p.gross_usd), 0.000001);
- const x = (i) => pad + (i / (n - 1 || 1)) * (W - 2 * pad);
- const y = (v) => H - pad - (v / max) * (H - 2 * pad);
- const pairs = points.map((p, i) => `${x(i).toFixed(1)},${y(p.gross_usd).toFixed(1)}`);
- const linePath = `M${pairs.join(' L')}`;
- const areaPath = `M${x(0).toFixed(1)},${H} L${pairs.join(' L')} L${x(n - 1).toFixed(1)},${H} Z`;
- const drawCls = state.firstChart ? ' xr-chart-draw' : '';
-
- host.innerHTML =
- `<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" aria-hidden="true">` +
- `<defs><linearGradient id="xrGrad" x1="0" y1="0" x2="0" y2="1">` +
- `<stop offset="0%" stop-color="var(--xr-accent)" stop-opacity="0.32"/>` +
- `<stop offset="100%" stop-color="var(--xr-accent)" stop-opacity="0"/>` +
- `</linearGradient></defs>` +
- `<path class="xr-chart-area" d="${areaPath}" fill="url(#xrGrad)"/>` +
- `<line class="xr-chart-cross" id="xr-cross" x1="0" y1="0" x2="0" y2="${H}" vector-effect="non-scaling-stroke" style="display:none"/>` +
- `<path class="xr-chart-line${drawCls}" d="${linePath}" vector-effect="non-scaling-stroke"/>` +
- `<circle class="xr-chart-dot" id="xr-dot" r="3.5" vector-effect="non-scaling-stroke" style="display:none"/>` +
- `</svg>`;
-
- // animate the draw only the first time
- if (state.firstChart) {
- const line = host.querySelector('.xr-chart-line');
- if (line) {
- try {
- const len = line.getTotalLength();
- line.style.setProperty('--len', String(Math.ceil(len)));
- } catch {
- line.classList.remove('xr-chart-draw');
- }
- }
- state.firstChart = false;
- }
-
- host._points = { points, unit: filled.unit, x, y, W, H };
- wireChartHover(host);
-}
-
-function wireChartHover(host) {
- const tip = $('xr-chart-tip');
- const move = (clientX) => {
- const ctx = host._points;
- if (!ctx) return;
- const rect = host.getBoundingClientRect();
- const ratio = Math.min(1, Math.max(0, (clientX - rect.left) / rect.width));
- const idx = Math.round(ratio * (ctx.points.length - 1));
- const p = ctx.points[idx];
- if (!p) return;
- const cross = host.querySelector('#xr-cross');
- const dot = host.querySelector('#xr-dot');
- const cx = ctx.x(idx);
- const cy = ctx.y(p.gross_usd);
- if (cross) {
- cross.setAttribute('x1', cx);
- cross.setAttribute('x2', cx);
- cross.style.display = '';
- }
- if (dot) {
- dot.setAttribute('cx', cx);
- dot.setAttribute('cy', cy);
- dot.style.display = '';
- }
- if (tip) {
- tip.innerHTML = `<b>${fmtUsd(p.gross_usd)}</b> <span>· ${esc(bucketLabel(p.ts, ctx.unit))} · ${fmtInt(p.count)} call${p.count === 1 ? '' : 's'}</span>`;
- tip.style.left = `${(cx / ctx.W) * 100}%`;
- tip.hidden = false;
- }
- };
- host.onpointermove = (e) => move(e.clientX);
- host.onpointerleave = () => {
- const cross = host.querySelector('#xr-cross');
- const dot = host.querySelector('#xr-dot');
- if (cross) cross.style.display = 'none';
- if (dot) dot.style.display = 'none';
- if (tip) tip.hidden = true;
- };
-}
-
-// ── filter chips ──────────────────────────────────────────────────────────────
-function renderChips(topEndpoints, networks) {
- const host = $('xr-chips');
- if (!host) return;
- const chips = [];
- const anyFilter = state.endpoint || state.network;
- chips.push(
- `<button type="button" class="xr-chip${anyFilter ? '' : ' active'}" data-all="1">All</button>`,
- );
- for (const r of topEndpoints.slice(0, 6)) {
- const slug = endpointLabel(r.endpoint);
- const active = state.endpoint === slug ? ' active' : '';
- chips.push(
- `<button type="button" class="xr-chip${active}" data-endpoint="${esc(slug)}">${esc(slug)}</button>`,
- );
- }
- for (const r of networks.filter((nr) => Number(nr.count) > 0).slice(0, 4)) {
- if (!r.network || r.network === 'unknown') continue;
- const active = state.network === r.network ? ' active' : '';
- chips.push(
- `<button type="button" class="xr-chip${active}" data-network="${esc(r.network)}">${esc(r.label || r.network)}</button>`,
- );
- }
- host.innerHTML = chips.join('');
- host.querySelector('[data-all]')?.addEventListener('click', clearFilters);
- for (const el of host.querySelectorAll('[data-endpoint]')) {
- el.addEventListener('click', () => toggleEndpoint(el.dataset.endpoint));
- }
- for (const el of host.querySelectorAll('[data-network]')) {
- el.addEventListener('click', () => toggleNetwork(el.dataset.network));
- }
-}
-
-function toggleEndpoint(slug) {
- state.endpoint = state.endpoint === slug ? null : slug;
- writeUrl();
- reloadFeed();
- loadStats(); // refresh chip active states
-}
-function toggleNetwork(net) {
- state.network = state.network === net ? null : net;
- writeUrl();
- reloadFeed();
- loadStats();
-}
-function clearFilters() {
- if (!state.endpoint && !state.network) return;
- state.endpoint = null;
- state.network = null;
- writeUrl();
- reloadFeed();
- loadStats();
-}
-
-// ── feed ────────────────────────────────────────────────────────────────────
-function setFeedState(s) {
- state.feedState = s;
- const el = $('xr-feed-state');
- if (!el) return;
- el.dataset.state = s;
- el.textContent =
- s === 'live'
- ? 'live'
- : s === 'paused'
- ? 'paused'
- : s === 'error'
- ? 'reconnecting…'
- : s === 'empty'
- ? 'no activity yet'
- : 'connecting…';
-}
-
-// The chain a row settled on reads as its family name ('Solana'), but the raw
-// CAIP-2 id stays searchable so a ledger reconciliation can find it by id.
-function networkName(e) {
- return e.network_label || e.network_family || e.network || '';
-}
-
-function searchText(e) {
- return `${endpointLabel(e.route)} ${e.payer || ''} ${e.tx || ''} ${e.network || ''} ${networkName(e)}`.toLowerCase();
-}
-
-function rowHTML(e) {
- const label = endpointLabel(e.route);
- const tx = e.tx_url
- ? `<a class="xr-row-tx" href="${esc(e.tx_url)}" target="_blank" rel="noopener" aria-label="View transaction on explorer">tx ↗</a>`
- : '';
- const payer = e.payer
- ? `<span class="xr-row-payer" title="payer wallet">${esc(e.payer)}</span>`
- : '';
- const chain = networkName(e);
- const net = chain
- ? `<span class="xr-row-net" title="${esc(e.network || chain)}">${esc(chain)}</span>`
- : '';
- const hidden = state.query && !searchText(e).includes(state.query) ? ' hidden' : '';
- return (
- `<div class="xr-row${hidden}" data-id="${esc(e.id)}" data-tx="${esc(e.tx || '')}" data-search="${esc(searchText(e))}" role="button" tabindex="0" aria-label="${esc(label)} settled ${fmtUsd(e.amount_usd)} on ${esc(chain || 'chain')}. Activate to copy the transaction signature.">` +
- `<span class="xr-row-glyph" aria-hidden="true">→</span>` +
- `<span class="xr-row-body">` +
- `<span class="xr-row-line"><span class="xr-row-ep">${esc(label)}</span> ${payer}</span>` +
- `<span class="xr-row-meta">${net}<span class="xr-row-time">${esc(timeAgo(e.ts))}</span></span>` +
- `</span>` +
- `<span class="xr-row-amt">${fmtUsd(e.amount_usd)}${tx}</span>` +
- `</div>`
- );
-}
-
-// Clipboard access is denied in plenty of real contexts (an insecure origin, a
-// denied permission prompt). Fall back to a selection-based copy so the click
-// still does what the row promises instead of dead-ending in a toast.
-function copyText(text) {
- if (navigator.clipboard?.writeText) {
- return navigator.clipboard.writeText(text).catch(() => legacyCopy(text));
- }
- return legacyCopy(text);
-}
-
-function legacyCopy(text) {
- const ta = document.createElement('textarea');
- ta.value = text;
- ta.setAttribute('readonly', '');
- ta.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none';
- document.body.appendChild(ta);
- ta.select();
- const ok = document.execCommand?.('copy');
- ta.remove();
- return ok ? Promise.resolve() : Promise.reject(new Error('copy unavailable'));
-}
-
-function wireRow(node) {
- node.addEventListener('click', (e) => {
- if (e.target.closest('.xr-row-tx')) return; // let the explorer link work
- const tx = node.dataset.tx;
- if (!tx) return;
- copyText(tx).then(
- () => toast('Transaction signature copied'),
- () => toast('Copy blocked by the browser. Open the tx link instead.'),
- );
- });
- node.addEventListener('keydown', (e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- node.click();
- }
- });
-}
-
-function showSkeleton() {
- const host = $('xr-feed');
- if (!host) return;
- host.innerHTML = Array.from({ length: 6 }, () => `<div class="xr-skel"></div>`).join('');
-}
-
-function renderInitialFeed(events) {
- const host = $('xr-feed');
- if (!host) return;
- if (!events.length) {
- const filtered = state.endpoint || state.network;
- host.innerHTML =
- `<div class="xr-feed-empty">` +
- `<p class="xr-feed-empty-h">${filtered ? 'No settlements match this filter yet.' : 'No settled payments yet.'}</p>` +
- `<p class="xr-feed-empty-p">${
- filtered
- ? 'Clear the filter to see the whole feed, or wait for the next matching settlement to land.'
- : 'The instant an agent or app pays one of the platform\'s x402 endpoints, the settlement lands here — live and verifiable. Browse what\'s payable in the <a href="/docs/x402-endpoints">endpoint catalog</a>.'
- }</p>` +
- `</div>`;
- setFeedState('empty');
- state.latestTs = null;
- state.hasFeed = true;
- return;
- }
- host.innerHTML = events.map(rowHTML).join('');
- for (const node of host.querySelectorAll('.xr-row')) wireRow(node);
- for (const e of events) state.seen.add(e.id);
- state.latestTs = events[0].ts;
- state.hasFeed = true;
- setFeedState(state.paused ? 'paused' : 'live');
-}
-
-// The feed could not be read at all. Say what happened, keep the filter escape
-// hatch reachable, and offer the retry. Never leave skeletons pulsing forever.
-function renderFeedError(reason) {
- const host = $('xr-feed');
- if (!host) return;
- setFeedState('error');
- host.innerHTML =
- `<div class="xr-feed-empty xr-feed-empty--error" role="alert">` +
- `<p class="xr-feed-empty-h">Live settlements are unavailable.</p>` +
- `<p class="xr-feed-empty-p">${esc(reason)} Nothing is lost: every settlement stays in the ledger and the feed refills the moment the service answers.</p>` +
- `</div>`;
- mountRetry('xr-feed-retry', host.querySelector('.xr-feed-empty'), () => loadInitialFeed());
- const more = $('xr-more');
- if (more) more.hidden = true;
-}
-
-function prependEvents(events) {
- const host = $('xr-feed');
- if (!host) return;
- const fresh = events.filter((e) => !state.seen.has(e.id));
- if (!fresh.length) return;
- const emptyEl = host.querySelector('.xr-feed-empty');
- if (emptyEl) host.innerHTML = '';
- const frag = document.createElement('div');
- frag.innerHTML = fresh.map(rowHTML).join('');
- const nodes = Array.from(frag.children).reverse();
- for (const node of nodes) {
- node.classList.add('xr-row--new');
- wireRow(node);
- host.prepend(node);
- }
- for (const e of fresh) state.seen.add(e.id);
- state.latestTs = fresh[0].ts;
- chime();
- const rows = host.querySelectorAll('.xr-row');
- for (let i = 240; i < rows.length; i++) rows[i].remove();
-}
-
-// `background` re-reads the head of the feed without tearing the current view
-// down: the 12s poll on a quiet (empty) feed used to flash six skeletons over
-// the empty state every cycle.
-async function loadInitialFeed({ background = false } = {}) {
- if (!background) {
- setFeedState('loading');
- showSkeleton();
- }
- state.seen.clear();
- let data = null;
- let reason = '';
- try {
- const res = await fetch(`/api/x402-revenue?view=feed&limit=30&${feedParams()}`, {
- headers: { accept: 'application/json' },
- });
- if (res.ok) ({ data } = await res.json());
- else
- reason =
- res.status === 503
- ? 'The revenue ledger is temporarily unavailable.'
- : `The revenue service answered ${res.status}.`;
- } catch {
- reason = 'The revenue service could not be reached.';
- }
- if (!data) {
- if (state.hasFeed) setFeedState('error');
- else renderFeedError(reason || 'The revenue service is not responding.');
- return;
- }
- renderInitialFeed(data.events || []);
- state.cursor = data.next_cursor || null;
- const more = $('xr-more');
- if (more) more.hidden = !state.cursor;
-}
-
-function reloadFeed() {
- loadInitialFeed();
-}
-
-async function loadMore() {
- if (!state.cursor) return;
- const more = $('xr-more');
- if (more) more.textContent = 'Loading…';
- let res;
- try {
- res = await fetch(
- `/api/x402-revenue?view=feed&limit=30&${feedParams({ cursor: state.cursor })}`,
- {
- headers: { accept: 'application/json' },
- },
- );
- } catch {
- if (more) more.textContent = 'Load older settlements';
- toast('Could not load older settlements. Try again.');
- return;
- }
- if (!res.ok) {
- // Keep the cursor: a failed page must stay retryable, not silently retire
- // the button and strand the rest of the ledger behind it.
- if (more) more.textContent = 'Load older settlements';
- toast('Could not load older settlements. Try again.');
- return;
- }
- const { data } = await res.json();
- const host = $('xr-feed');
- const events = (data?.events || []).filter((e) => !state.seen.has(e.id));
- if (host && events.length) {
- const frag = document.createElement('div');
- frag.innerHTML = events.map(rowHTML).join('');
- for (const node of Array.from(frag.children)) {
- wireRow(node);
- host.appendChild(node);
- }
- for (const e of events) state.seen.add(e.id);
- }
- state.cursor = data?.next_cursor || null;
- if (more) {
- more.hidden = !state.cursor;
- more.textContent = 'Load older settlements';
- }
-}
-
-async function pollDelta() {
- if (state.paused || !state.latestTs) return;
- let res;
- try {
- res = await fetch(`/api/x402-revenue?${feedParams({ since: state.latestTs })}`, {
- headers: { accept: 'application/json' },
- });
- } catch {
- setFeedState('error');
- return;
- }
- if (!res.ok) {
- setFeedState('error');
- return;
- }
- const { data } = await res.json();
- prependEvents(data?.events || []);
- setFeedState('live');
-}
-
-function startPolling() {
- if (state.pollTimer) return;
- state.pollTimer = setInterval(() => {
- if (document.hidden || state.paused) return;
- state.latestTs ? pollDelta() : loadInitialFeed({ background: true });
- }, POLL_MS);
-}
-
-// ── controls ──────────────────────────────────────────────────────────────────
-function setPeriod(period) {
- const target = PERIODS.includes(period) ? period : '24h';
- if (target === state.period) return;
- state.period = target;
- for (const b of document.querySelectorAll('[data-period]')) {
- const on = b.dataset.period === target;
- b.classList.toggle('active', on);
- b.setAttribute('aria-selected', String(on));
- }
- writeUrl();
- loadStats();
-}
-function wirePeriod() {
- for (const btn of document.querySelectorAll('[data-period]')) {
- btn.addEventListener('click', () => setPeriod(btn.dataset.period));
- btn.addEventListener('keydown', (e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- setPeriod(btn.dataset.period);
- }
- });
- }
- // reflect restored period in the tab UI
- for (const b of document.querySelectorAll('[data-period]')) {
- const on = b.dataset.period === state.period;
- b.classList.toggle('active', on);
- b.setAttribute('aria-selected', String(on));
- }
-}
-
-function togglePause() {
- state.paused = !state.paused;
- const btn = $('xr-pause');
- if (btn) {
- btn.setAttribute('aria-pressed', String(state.paused));
- btn.querySelector('.xr-pause-ico').textContent = state.paused ? '▶' : '॥';
- }
- setFeedState(state.paused ? 'paused' : 'live');
- if (!state.paused) pollDelta();
- toast(state.paused ? 'Live feed paused' : 'Live feed resumed');
-}
-
-let audioCtx = null;
-function chime() {
- if (!state.sound) return;
- try {
- audioCtx = audioCtx || new (window.AudioContext || window.webkitAudioContext)();
- const t = audioCtx.currentTime;
- const o = audioCtx.createOscillator();
- const g = audioCtx.createGain();
- o.type = 'sine';
- o.frequency.setValueAtTime(880, t);
- o.frequency.exponentialRampToValueAtTime(1320, t + 0.08);
- g.gain.setValueAtTime(0.0001, t);
- g.gain.exponentialRampToValueAtTime(0.06, t + 0.02);
- g.gain.exponentialRampToValueAtTime(0.0001, t + 0.26);
- o.connect(g).connect(audioCtx.destination);
- o.start(t);
- o.stop(t + 0.27);
- } catch {
- /* audio unavailable — silent */
- }
-}
-function toggleSound() {
- state.sound = !state.sound;
- const btn = $('xr-sound');
- if (btn) btn.setAttribute('aria-pressed', String(state.sound));
- try {
- localStorage.setItem('xr_sound', state.sound ? '1' : '0');
- } catch {
- /* ignore */
- }
- if (state.sound) chime();
- toast(state.sound ? 'Chime on new settlements' : 'Chime off');
-}
-
-function exportCsv() {
- const p = new URLSearchParams({ view: 'export', period: state.period });
- if (state.endpoint) p.set('endpoint', state.endpoint);
- if (state.network) p.set('network', state.network);
- window.open(`/api/x402-revenue?${p.toString()}`, '_blank', 'noopener');
- toast('Exporting CSV…');
-}
-
-function wireSearch() {
- const input = $('xr-search');
- if (!input) return;
- let deb = null;
- input.addEventListener('input', () => {
- clearTimeout(deb);
- deb = setTimeout(() => {
- state.query = input.value.trim().toLowerCase();
- for (const row of document.querySelectorAll('#xr-feed .xr-row')) {
- row.classList.toggle(
- 'hidden',
- state.query && !row.dataset.search.includes(state.query),
- );
- }
- }, 120);
- });
-}
-
-function wireKeys() {
- document.addEventListener('keydown', (e) => {
- const typing = !!e.target?.matches?.('input, textarea, [contenteditable]');
- if (typing) {
- if (e.key === 'Escape') e.target.blur();
- return;
- }
- if (e.metaKey || e.ctrlKey || e.altKey) return;
- if (e.key === '/') {
- e.preventDefault();
- $('xr-search')?.focus();
- } else if (e.key === 'p') {
- togglePause();
- } else if (e.key === 's') {
- toggleSound();
- } else if (e.key === 'e') {
- exportCsv();
- } else if (['1', '2', '3', '4'].includes(e.key)) {
- setPeriod(PERIODS[Number(e.key) - 1]);
- }
- });
-}
-
-function onVisibility() {
- if (document.hidden) {
- if (!state.paused) setFeedState('paused');
- } else {
- // Returning to a tab must not paint over a real failure with "no activity".
- if (state.feedState === 'error') setFeedState('error');
- else setFeedState(state.paused ? 'paused' : state.latestTs ? 'live' : 'empty');
- if (!state.paused) pollDelta();
- loadStats();
- }
-}
-
-function init() {
- readUrl();
- // restore persisted sound preference
- try {
- state.sound = localStorage.getItem('xr_sound') === '1';
- } catch {
- /* ignore */
- }
- $('xr-sound')?.setAttribute('aria-pressed', String(state.sound));
-
- wirePeriod();
- wireSearch();
- wireKeys();
- $('xr-pause')?.addEventListener('click', togglePause);
- $('xr-sound')?.addEventListener('click', toggleSound);
- $('xr-export')?.addEventListener('click', exportCsv);
- $('xr-more')?.addEventListener('click', loadMore);
-
- loadStats();
- loadInitialFeed().then(startPolling);
- state.statsTimer = setInterval(() => {
- if (!document.hidden) loadStats();
- }, STATS_REFRESH_MS);
- document.addEventListener('visibilitychange', onVisibility);
- // The i18n runtime applies its catalog after first paint and again on every
- // locale switch, rewriting annotated copy. Anything this page keeps live is
- // re-asserted afterwards so a translation pass can never leave the feed
- // reading "connecting…" while rows are streaming in.
- window.addEventListener('i18n:change', reassertLiveText);
-}
-
-function reassertLiveText() {
- setFeedState(state.feedState || 'loading');
- for (const id of ['xr-window-label', 'xr-top-window', 'xr-net-window']) {
- const el = $(id);
- if (el) el.textContent = state.period;
- }
-}
-
-if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
-} else {
- init();
-}