Skip to content

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

feat(x402): split ring dogfooding out of revenue so analytics report external traction only

nirholas2a9ced95019c
diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.js
index a510c5753..683b92208 100644
--- a/api/_lib/x402/autonomous-registry.js
+++ b/api/_lib/x402/autonomous-registry.js
@@ -3596,6 +3596,13 @@ const SELF_ENDPOINTS = [
underused_endpoints: Array.isArray(r?.underused_endpoints)
? r.underused_endpoints.map((e) => e?.route).filter(Boolean)
: [],
+ // total_usdc_paid above is gross, and this loop is itself the source
+ // of nearly all of it. Lifting the external share into the same
+ // signal keeps the ring's own journal from reading as revenue:
+ // null means the split was unavailable, not that it was zero.
+ external_usdc: r?.revenue_split?.external?.volume_usdc ?? null,
+ external_payers: r?.revenue_split?.external?.unique_payers ?? null,
+ split_confident: r?.revenue_split?.confident ?? null,
}),
},
diff --git a/api/_lib/x402/revenue-split.js b/api/_lib/x402/revenue-split.js
new file mode 100644
index 000000000..56db5c536
--- /dev/null
+++ b/api/_lib/x402/revenue-split.js
@@ -0,0 +1,223 @@
+// @ts-check
+// api/_lib/x402/revenue-split.js
+//
+// External vs internal revenue: the one classifier that decides which settled
+// x402 payments count as traction.
+//
+// three.ws runs a closed dogfooding loop (the x402 ring, docs/x402-ring-economy.md):
+// platform-controlled wallets pay platform endpoints on a cron so the payment
+// rails stay warm and provably live. That volume is real money moving on real
+// chains, and it dwarfs everything else. As of this module landing, 38,613 of
+// 38,619 settled payments came from four ring wallets. A gross figure read off
+// x402_audit_log is therefore ~100% our own money, and reporting it as revenue
+// would be fabricated traction. The operating rule (docs/internal/fable-playbook.md §4)
+// is blunt: external revenue only, never report ring volume as traction.
+//
+// Nothing enforced that rule mechanically until this module. Every consumer of
+// the ledger (the readout script, the paid analytics report) now splits
+// through one function so the two can never disagree.
+//
+// Three buckets, not two:
+//
+// internal payer is a platform-controlled wallet (ring roles, the
+// x402_ring_wallets registry, platform signers, USDC ATAs of all
+// of them). Dogfooding. Never traction.
+// synthetic payer is not a plausible on-chain address at all: a literal
+// like 'PAYER' written by a replay/self-test path. Not a buyer,
+// not revenue, and counting it as external would be worse than
+// counting ring volume, because it is not even money.
+// external a real address we do not control. This is the only bucket that
+// counts toward the revenue ladder.
+//
+// ── Why classification is conservative ────────────────────────────────────────
+// ringAllowedAddresses() degrades by SHRINKING (an unreachable DB or an
+// unconfigured signer drops addresses). For leak scanning that is the safe
+// direction, more false leak alerts. For revenue it is the DANGEROUS direction:
+// a shrunk controlled set reclassifies our own wallets as external and inflates
+// the number we are least allowed to inflate. So this module reports how the set
+// was resolved and marks the split `confident: false` when the registry came
+// back empty, and every caller is expected to refuse to publish an unconfident
+// external figure rather than quietly print a flattering one.
+
+import { ringAllowedAddresses } from './ring-allowlist.js';
+
+/** Solana pubkeys are base58, 32-44 chars. */
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+/** EVM addresses are 0x + 40 hex. */
+const EVM_RE = /^0x[0-9a-fA-F]{40}$/;
+
+/**
+ * True when `payer` looks like an address on a chain we settle on. Anything
+ * else (null, '', 'PAYER', 'test-wallet') is a synthetic ledger artifact.
+ * @param {unknown} payer
+ * @returns {boolean}
+ */
+export function isPlausibleAddress(payer) {
+ if (typeof payer !== 'string') return false;
+ const s = payer.trim();
+ return BASE58_RE.test(s) || EVM_RE.test(s);
+}
+
+/**
+ * Resolve the platform-controlled wallet set plus the provenance needed to
+ * judge whether an external figure derived from it is publishable.
+ *
+ * @param {{ sql?: Function }} [deps] inject the sql tag (tests)
+ * @returns {Promise<{ addresses: Set<string>, registryRows: number, confident: boolean, reason: string|null }>}
+ */
+export async function controlledPayers(deps = {}) {
+ let addresses = new Set();
+ let error = null;
+ try {
+ addresses = await ringAllowedAddresses(deps);
+ } catch (err) {
+ error = err instanceof Error ? err.message : String(err);
+ }
+
+ // The registry is the dominant source: every wallet that has actually paid
+ // lives there, while the env-derived additions are belt-and-braces. An empty
+ // registry means the set cannot be trusted to cover our own payers.
+ let registryRows = 0;
+ try {
+ const sql = deps.sql || (await import('../db.js')).sql;
+ const rows = await sql`SELECT count(*)::int AS c FROM x402_ring_wallets WHERE enabled = true`;
+ registryRows = rows?.[0]?.c || 0;
+ } catch {
+ registryRows = 0;
+ }
+
+ const confident = registryRows > 0 && addresses.size > 0;
+ const reason = confident
+ ? null
+ : error
+ ? `controlled-wallet set unresolved (${error})`
+ : 'x402_ring_wallets returned no enabled rows, so ring payers would misclassify as external';
+
+ return { addresses, registryRows, confident, reason };
+}
+
+/**
+ * Bucket one payer.
+ * @param {unknown} payer
+ * @param {Set<string>} controlled
+ * @returns {'internal'|'synthetic'|'external'}
+ */
+export function classifyPayer(payer, controlled) {
+ if (!isPlausibleAddress(payer)) return 'synthetic';
+ const s = String(payer).trim();
+ return controlled.has(s) ? 'internal' : 'external';
+}
+
+/** Atomic USDC (6dp) → a fixed-precision decimal string. Never floats the sum. */
+function atomicsToUsdc(atomics) {
+ const n = BigInt(atomics || 0n);
+ const neg = n < 0n;
+ const abs = neg ? -n : n;
+ const whole = abs / 1_000_000n;
+ const frac = (abs % 1_000_000n).toString().padStart(6, '0');
+ return `${neg ? '-' : ''}${whole}.${frac}`;
+}
+
+function emptyBucket() {
+ return { calls: 0, volume_atomics: 0n, payers: new Set(), routes: new Map() };
+}
+
+function finishBucket(bucket, totalCalls) {
+ const routes = [...bucket.routes.entries()]
+ .map(([route, v]) => ({ route, calls: v.calls, volume_usdc: atomicsToUsdc(v.atomics) }))
+ .sort((a, b) => b.calls - a.calls);
+ return {
+ calls: bucket.calls,
+ volume_atomics: bucket.volume_atomics.toString(),
+ volume_usdc: atomicsToUsdc(bucket.volume_atomics),
+ unique_payers: bucket.payers.size,
+ share_of_calls: totalCalls > 0 ? Number((bucket.calls / totalCalls).toFixed(6)) : 0,
+ routes,
+ };
+}
+
+/**
+ * Split settled x402 payments into internal / synthetic / external over a window.
+ *
+ * Reads x402_audit_log directly (the durable settlement ledger) rather than a
+ * pre-aggregated view, because the split is per-payer and no aggregate carries
+ * the payer identity forward.
+ *
+ * @param {{ since?: string|Date|null, sql?: Function }} [opts]
+ * `since` null/undefined = all time.
+ * @returns {Promise<{
+ * since: string|null,
+ * generated_at: string,
+ * confident: boolean,
+ * confidence_note: string|null,
+ * controlled_wallets: number,
+ * total: { calls: number, volume_atomics: string, volume_usdc: string, unique_payers: number },
+ * external: object, internal: object, synthetic: object,
+ * }>}
+ */
+export async function revenueSplit({ since = null, sql: injected } = {}) {
+ const sql = injected || (await import('../db.js')).sql;
+ const sinceIso = since == null ? null : new Date(since).toISOString();
+
+ const { addresses, registryRows, confident, reason } = await controlledPayers({ sql });
+
+ const rows = await sql`
+ SELECT
+ payer,
+ route,
+ count(*)::int AS calls,
+ coalesce(sum(
+ CASE WHEN amount_atomics IS NOT NULL AND amount_atomics ~ '^[0-9]+$'
+ THEN amount_atomics::numeric ELSE 0 END
+ ), 0)::text AS atomics
+ FROM x402_audit_log
+ WHERE event_type = 'payment_settled'
+ AND (${sinceIso}::timestamptz IS NULL OR created_at >= ${sinceIso}::timestamptz)
+ GROUP BY payer, route
+ `;
+
+ const buckets = { internal: emptyBucket(), synthetic: emptyBucket(), external: emptyBucket() };
+ let totalCalls = 0;
+ let totalAtomics = 0n;
+ const allPayers = new Set();
+
+ for (const row of rows) {
+ const calls = Number(row.calls) || 0;
+ const atomics = BigInt(String(row.atomics || '0').split('.')[0] || '0');
+ const bucket = buckets[classifyPayer(row.payer, addresses)];
+
+ bucket.calls += calls;
+ bucket.volume_atomics += atomics;
+ if (row.payer) bucket.payers.add(String(row.payer));
+
+ const route = row.route || '(unrouted)';
+ const seen = bucket.routes.get(route) || { calls: 0, atomics: 0n };
+ seen.calls += calls;
+ seen.atomics += atomics;
+ bucket.routes.set(route, seen);
+
+ totalCalls += calls;
+ totalAtomics += atomics;
+ if (row.payer) allPayers.add(String(row.payer));
+ }
+
+ return {
+ since: sinceIso,
+ generated_at: new Date().toISOString(),
+ confident,
+ confidence_note: reason,
+ controlled_wallets: addresses.size,
+ registry_rows: registryRows,
+ total: {
+ calls: totalCalls,
+ volume_atomics: totalAtomics.toString(),
+ volume_usdc: atomicsToUsdc(totalAtomics),
+ unique_payers: allPayers.size,
+ },
+ external: finishBucket(buckets.external, totalCalls),
+ internal: finishBucket(buckets.internal, totalCalls),
+ synthetic: finishBucket(buckets.synthetic, totalCalls),
+ };
+}
+
+export { atomicsToUsdc };
diff --git a/api/x402/analytics.js b/api/x402/analytics.js
index 615e51309..882ed25c4 100644
--- a/api/x402/analytics.js
+++ b/api/x402/analytics.js
@@ -37,6 +37,7 @@ import { solUsdPrice } from '../_lib/avatar-wallet.js';
import { buildSniperAnalytics } from '../_lib/x402/sniper-analytics-store.js';
import { computeUserActivity, normalizePeriod } from '../_lib/x402/user-activity-analytics.js';
import { getPaymentStats } from '../_lib/x402/audit-log.js';
+import { revenueSplit } from '../_lib/x402/revenue-split.js';
const ROUTE = '/api/x402/analytics';
@@ -578,6 +579,15 @@ async function volumeReport(seconds) {
.sort((a, b) => a.count - b.count || Number(a.volume) - Number(b.volume))
.slice(0, UNDERUSED_LIMIT);
+ // The totals above are GROSS: they include the x402 ring, the closed
+ // dogfooding loop in which platform-controlled wallets pay platform
+ // endpoints on a cron. That traffic is the overwhelming majority of settled
+ // volume, so a buyer reading total_usdc_paid as "three.ws revenue" would be
+ // reading our own money back to us. `revenue_split` states which share is
+ // external, and folds a soft failure to null rather than guessing, because a
+ // missing split is honest where a fabricated one is not.
+ const revenueSplitBlock = await buildRevenueSplit(since);
+
return {
total_calls: stats.total_payments || 0,
total_usdc_paid: stats.total_volume_usdc || '0.000000',
@@ -588,9 +598,39 @@ async function volumeReport(seconds) {
by_endpoint: byEndpoint,
by_network: stats.by_network || [],
underused_endpoints: underused,
+ revenue_split: revenueSplitBlock,
};
}
+// Compact the full split (api/_lib/x402/revenue-split.js) down to what a paid
+// buyer needs: the three buckets and whether the classification is trustworthy.
+// Route-level external attribution stays internal to the readout script; it
+// names the endpoints our few real buyers touched, which is our commercial
+// detail rather than the buyer's.
+async function buildRevenueSplit(since) {
+ try {
+ const split = await revenueSplit({ since });
+ const bucket = (b) => ({
+ calls: b.calls,
+ volume_usdc: b.volume_usdc,
+ unique_payers: b.unique_payers,
+ share_of_calls: b.share_of_calls,
+ });
+ return {
+ confident: split.confident,
+ confidence_note: split.confidence_note,
+ external: bucket(split.external),
+ internal_ring: bucket(split.internal),
+ synthetic: bucket(split.synthetic),
+ };
+ } catch {
+ // A split we cannot compute is reported as absent. The gross totals above
+ // remain accurate on their own terms; what is unavailable is the
+ // interpretation, and inventing one is the failure mode this guards.
+ return null;
+ }
+}
+
export default paidEndpoint({
route: ROUTE,
method: 'POST',
diff --git a/docs/autonomous-x402.md b/docs/autonomous-x402.md
index 56d995667..bbb5e76cc 100644
--- a/docs/autonomous-x402.md
+++ b/docs/autonomous-x402.md
@@ -158,6 +158,35 @@ automatically (and `tests/x402-ring-catalog.test.js` fails until it is cataloged
> [Circulation engine](circulation-engine.md), real `agent_hire` commerce,
> discovery), not a heavier self-paid sweep.
+**Excluding it is mechanical, not a matter of remembering to.**
+`api/_lib/x402/revenue-split.js` classifies every settled payment in
+`x402_audit_log` into three buckets by payer: `internal` (any
+platform-controlled wallet, resolved through `ringAllowedAddresses()`),
+`synthetic` (a payer string that is not a plausible on-chain address at all, such
+as the literal `PAYER` written by replay-test paths), and `external` (a real
+address we do not control). Only the last one is revenue.
+
+```bash
+npm run readout:revenue # trailing 30 days
+npm run readout:revenue -- --window all # all time
+npm run readout:revenue -- --json # machine-readable
+```
+
+The same split ships as `revenue_split` on the `x402_volume` report of the paid
+`/api/x402/analytics` endpoint, so a buyer reading `total_usdc_paid` can see what
+share of it is our own money, and the volume loop's own
+`x402_autonomous_log.signal_data` now carries `external_usdc` beside the gross
+figure.
+
+The classification is deliberately conservative in one direction. If the
+controlled-wallet registry (`x402_ring_wallets`) returns no enabled rows, the
+ring's own wallets would be classified as external customers and the headline
+number would inflate. The split reports `confident: false` with the reason
+instead, and the readout script exits 2 rather than printing a figure it cannot
+stand behind. An unavailable split is reported as `null`, never as a confident
+zero: "we could not classify" and "there was no external revenue" are different
+claims.
+
## The Datapoint Fabric Volume Sweep
One registry entry — `datapoint-volume-sweep`, pipeline `datapoint`, cooldown
diff --git a/package.json b/package.json
index acff66d02..93f261dd5 100644
--- a/package.json
+++ b/package.json
@@ -201,6 +201,7 @@
"smoke:agent-wallet": "node scripts/agent-wallet-smoke.mjs",
"audit:mcp": "node scripts/audit-mcp-manifests.mjs",
"smoke:mcp": "node scripts/smoke-mcp-remotes.mjs",
+ "readout:revenue": "node scripts/x402-revenue-readout.mjs",
"test:mcp": "node scripts/test-mcp-all.mjs",
"audit:pages": "node scripts/audit-page-index.mjs --strict",
"audit:meetup": "node scripts/meetup-audit.mjs",
diff --git a/scripts/x402-revenue-readout.mjs b/scripts/x402-revenue-readout.mjs
new file mode 100755
index 000000000..d8372ecc1
--- /dev/null
+++ b/scripts/x402-revenue-readout.mjs
@@ -0,0 +1,138 @@
+#!/usr/bin/env node
+// scripts/x402-revenue-readout.mjs
+//
+// The weekly revenue readout (docs/internal/fable-playbook.md §2). The only sanctioned
+// way to answer "how much revenue does three.ws actually have?"
+//
+// The trap this exists to close: x402_audit_log holds tens of thousands of real,
+// on-chain-settled payments, and essentially all of them are the x402 ring
+// paying itself (docs/x402-ring-economy.md). Any gross number read off that
+// ledger is dogfooding volume wearing a revenue costume. This script splits the
+// ledger through api/_lib/x402/revenue-split.js and leads with the external
+// figure, which is the only one that counts toward the ladder in the playbook.
+//
+// It refuses to print an external number it cannot stand behind: if the
+// controlled-wallet set fails to resolve, our own ring wallets would be counted
+// as external customers, so the run exits non-zero with the reason instead.
+//
+// Usage:
+// node scripts/x402-revenue-readout.mjs # trailing 30 days
+// node scripts/x402-revenue-readout.mjs --window 7d # 24h | 7d | 30d | 90d | all
+// node scripts/x402-revenue-readout.mjs --json # machine-readable
+// node scripts/x402-revenue-readout.mjs --routes 10 # external route rows to show
+//
+// Exit codes: 0 = readout produced, 2 = classification not trustworthy,
+// 1 = the ledger could not be read.
+
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+// Load .env.local then .env; first definition wins (matches apply-migrations.mjs).
+for (const envFile of ['.env.local', '.env']) {
+ try {
+ const raw = readFileSync(path.resolve(REPO_ROOT, envFile), 'utf8');
+ for (const line of raw.split('\n')) {
+ const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
+ if (!m || process.env[m[1]]) continue;
+ let val = m[2].trim();
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
+ val = val.slice(1, -1);
+ }
+ process.env[m[1]] = val;
+ }
+ } catch { /* file not present */ }
+}
+
+const WINDOWS = { '24h': 86_400, '7d': 604_800, '30d': 2_592_000, '90d': 7_776_000, all: null };
+
+const args = process.argv.slice(2);
+const JSON_OUT = args.includes('--json');
+const windowArg = (args[args.indexOf('--window') + 1] || '').trim();
+const WINDOW = args.includes('--window') && windowArg in WINDOWS ? windowArg : '30d';
+const routesArg = Number(args[args.indexOf('--routes') + 1]);
+const ROUTE_LIMIT = args.includes('--routes') && Number.isFinite(routesArg) ? Math.max(1, routesArg) : 8;
+
+if (args.includes('--window') && !(windowArg in WINDOWS)) {
+ console.error(`unknown --window "${windowArg}"; expected one of ${Object.keys(WINDOWS).join(', ')}`);
+ process.exit(1);
+}
+
+/** Right-align a number for the fixed-width report columns. */
+const num = (n, w = 9) => String(n).padStart(w);
+const usd = (s) => `$${s}`;
+
+function renderRoutes(label, bucket, limit) {
+ if (!bucket.routes.length) return [];
+ const out = [` ${label}`];
+ for (const r of bucket.routes.slice(0, limit)) {
+ out.push(` ${num(r.calls, 7)} ${usd(r.volume_usdc).padStart(14)} ${r.route}`);
+ }
+ const rest = bucket.routes.length - limit;
+ if (rest > 0) out.push(` ${' '.repeat(7)} ${' '.repeat(14)} (+${rest} more route${rest === 1 ? '' : 's'})`);
+ return out;
+}
+
+async function main() {
+ if (!process.env.DATABASE_URL) {
+ console.error('DATABASE_URL is not set. Copy .env.local into this tree (see CLAUDE.md).');
+ process.exit(1);
+ }
+
+ const { revenueSplit } = await import('../api/_lib/x402/revenue-split.js');
+ const seconds = WINDOWS[WINDOW];
+ const since = seconds == null ? null : new Date(Date.now() - seconds * 1000);
+
+ const split = await revenueSplit({ since });
+
+ if (JSON_OUT) {
+ console.log(JSON.stringify({ window: WINDOW, ...split }, null, 2));
+ return split.confident ? 0 : 2;
+ }
+
+ const { total, external, internal, synthetic } = split;
+ const pct = (b) => `${(b.share_of_calls * 100).toFixed(2).padStart(6)}%`;
+
+ const lines = [
+ '',
+ `x402 revenue readout, window: ${WINDOW}${split.since ? ` (since ${split.since.slice(0, 10)})` : ' (all time)'}`,
+ `generated ${split.generated_at}`,
+ '',
+ ` settled calls ${num(total.calls)}`,
+ ` gross volume ${usd(total.volume_usdc).padStart(9)} USDC ${total.unique_payers} distinct payer${total.unique_payers === 1 ? '' : 's'}`,
+ '',
+ ` calls volume share`,
+ ` EXTERNAL ${num(external.calls)} ${usd(external.volume_usdc).padStart(14)} ${pct(external)} <- the only revenue`,
+ ` internal ring ${num(internal.calls)} ${usd(internal.volume_usdc).padStart(14)} ${pct(internal)} dogfooding, never traction`,
+ ` synthetic ${num(synthetic.calls)} ${usd(synthetic.volume_usdc).padStart(14)} ${pct(synthetic)} test payers, not money`,
+ '',
+ ` external buyers ${external.unique_payers} controlled wallets known ${split.controlled_wallets} (registry rows ${split.registry_rows})`,
+ '',
+ ];
+
+ lines.push(...renderRoutes('external revenue by route:', external, ROUTE_LIMIT));
+ if (!external.routes.length) {
+ lines.push(' external revenue by route: none in this window');
+ }
+ lines.push('');
+
+ if (!split.confident) {
+ lines.push(` NOT PUBLISHABLE: ${split.confidence_note}`);
+ lines.push(' Ring wallets would be counted as external customers. Fix the wallet');
+ lines.push(' registry before quoting any number from this run.');
+ lines.push('');
+ }
+
+ console.log(lines.join('\n'));
+ return split.confident ? 0 : 2;
+}
+
+main().then(
+ (code) => process.exit(code),
+ (err) => {
+ console.error(`revenue readout failed: ${err?.message || err}`);
+ process.exit(1);
+ },
+);
diff --git a/tests/x402-analytics-volume.test.js b/tests/x402-analytics-volume.test.js
index 4186dd1cf..e655e313b 100644
--- a/tests/x402-analytics-volume.test.js
+++ b/tests/x402-analytics-volume.test.js
@@ -26,6 +26,15 @@ const SAMPLE = {
{ route: '/api/x402/did', count: 1, volume: '0.001000' },
{ route: '/api/x402/model-check', count: 30, volume: '0.030000' },
],
+ // The gross totals above are almost entirely the ring paying itself, so the
+ // report carries the external/internal split alongside them.
+ revenue_split: {
+ confident: true,
+ confidence_note: null,
+ external: { calls: 4, volume_usdc: '0.004000', unique_payers: 3, share_of_calls: 0.003115 },
+ internal_ring: { calls: 1278, volume_usdc: '12.834000', unique_payers: 33, share_of_calls: 0.995327 },
+ synthetic: { calls: 2, volume_usdc: '0.002000', unique_payers: 1, share_of_calls: 0.001558 },
+ },
};
describe('autonomous registry — analytics-x402-volume entry', () => {
@@ -73,4 +82,21 @@ describe('autonomous registry — analytics-x402-volume entry', () => {
expect(sig.top_endpoint).toBeNull();
expect(sig.underused_endpoints).toEqual([]);
});
+
+ it('extractSignal carries the external share so the journal is not read as revenue', () => {
+ const sig = entry.extractSignal(SAMPLE);
+ expect(sig.external_usdc).toBe('0.004000');
+ expect(sig.external_payers).toBe(3);
+ expect(sig.split_confident).toBe(true);
+ });
+
+ it('extractSignal reports an unavailable split as null, never as zero revenue', () => {
+ // A missing split means "we could not classify", which is a different
+ // claim from "no external revenue". Collapsing the two would let a
+ // degraded run look like a confident zero.
+ const sig = entry.extractSignal({ total_calls: 12 });
+ expect(sig.external_usdc).toBeNull();
+ expect(sig.external_payers).toBeNull();
+ expect(sig.split_confident).toBeNull();
+ });
});
diff --git a/tests/x402-revenue-split.test.js b/tests/x402-revenue-split.test.js
new file mode 100644
index 000000000..ff6e76e6d
--- /dev/null
+++ b/tests/x402-revenue-split.test.js
@@ -0,0 +1,128 @@
+import { describe, it, expect } from 'vitest';
+
+import {
+ isPlausibleAddress,
+ classifyPayer,
+ atomicsToUsdc,
+ revenueSplit,
+} from '../api/_lib/x402/revenue-split.js';
+
+// A tagged-template stub standing in for _lib/db.js's `sql`. It routes on the
+// query text so one stub can serve both the ring-wallet registry lookups and
+// the settlement aggregate, exactly as the real tag does.
+function makeSql({ ringPubkeys = [], settlements = [] } = {}) {
+ return function sql(strings) {
+ const text = strings.join(' ');
+ if (text.includes('count(*)::int AS c') && text.includes('x402_ring_wallets')) {
+ return Promise.resolve([{ c: ringPubkeys.length }]);
+ }
+ if (text.includes('x402_ring_wallets')) {
+ return Promise.resolve(ringPubkeys.map((pubkey) => ({ pubkey })));
+ }
+ if (text.includes('x402_audit_log')) return Promise.resolve(settlements);
+ return Promise.resolve([]);
+ };
+}
+
+const RING = 'X4o2UuVNMxnrgkzVy97kPF5gmS6CLRCVJGB48VastML';
+const BUYER_EVM = '0xC533Bf5268A2F64aDDe58dcE380651f70Aa92D7A';
+const BUYER_SOL = '5uShZo7i8JqT7YuWR4iqheydkrVgBtno4XNUboP7Knm2';
+
+describe('revenue-split: address plausibility', () => {
+ it('accepts real Solana and EVM addresses', () => {
+ expect(isPlausibleAddress(RING)).toBe(true);
+ expect(isPlausibleAddress(BUYER_EVM)).toBe(true);
+ });
+
+ it('rejects the ledger artifacts that must never count as buyers', () => {
+ // 'PAYER' is a literal written by a replay/self-test path and is present
+ // in the real production ledger. Counting it as an external customer
+ // would fabricate traction out of a string.
+ expect(isPlausibleAddress('PAYER')).toBe(false);
+ expect(isPlausibleAddress('')).toBe(false);
+ expect(isPlausibleAddress(null)).toBe(false);
+ expect(isPlausibleAddress('0xdeadbeef')).toBe(false);
+ });
+});
+
+describe('revenue-split: payer classification', () => {
+ const controlled = new Set([RING]);
+
+ it('buckets controlled, external and synthetic payers apart', () => {
+ expect(classifyPayer(RING, controlled)).toBe('internal');
+ expect(classifyPayer(BUYER_EVM, controlled)).toBe('external');
+ expect(classifyPayer('PAYER', controlled)).toBe('synthetic');
+ });
+});
+
+describe('revenue-split: atomics formatting', () => {
+ it('renders 6dp USDC without floating point', () => {
+ expect(atomicsToUsdc(0n)).toBe('0.000000');
+ expect(atomicsToUsdc(1000n)).toBe('0.001000');
+ expect(atomicsToUsdc(972_088_000n)).toBe('972.088000');
+ });
+});
+
+describe('revenueSplit', () => {
+ it('keeps ring volume out of the external figure', async () => {
+ const split = await revenueSplit({
+ sql: makeSql({
+ ringPubkeys: [RING],
+ settlements: [
+ { payer: RING, route: '/api/x402/echo', calls: 1000, atomics: '1000000' },
+ { payer: BUYER_EVM, route: '/api/x402/skill-marketplace', calls: 2, atomics: '2000' },
+ { payer: 'PAYER', route: '/api/x402/replay-test', calls: 2, atomics: '2000' },
+ ],
+ }),
+ });
+
+ expect(split.total.calls).toBe(1004);
+ expect(split.internal.calls).toBe(1000);
+ expect(split.external.calls).toBe(2);
+ expect(split.external.volume_usdc).toBe('0.002000');
+ expect(split.external.unique_payers).toBe(1);
+ expect(split.synthetic.calls).toBe(2);
+ expect(split.confident).toBe(true);
+ });
+
+ it('attributes external volume by route', async () => {
+ const split = await revenueSplit({
+ sql: makeSql({
+ ringPubkeys: [RING],
+ settlements: [
+ { payer: BUYER_EVM, route: '/api/x402/forge', calls: 5, atomics: '50000' },
+ { payer: BUYER_SOL, route: '/api/x402/crypto-intel', calls: 1, atomics: '1000' },
+ ],
+ }),
+ });
+
+ expect(split.external.routes[0]).toEqual({
+ route: '/api/x402/forge',
+ calls: 5,
+ volume_usdc: '0.050000',
+ });
+ expect(split.external.unique_payers).toBe(2);
+ });
+
+ it('refuses confidence when the controlled-wallet registry is empty', async () => {
+ // The dangerous failure: with no registry rows, ring wallets classify as
+ // external and the headline number inflates. The split must say so.
+ const split = await revenueSplit({
+ sql: makeSql({
+ ringPubkeys: [],
+ settlements: [{ payer: RING, route: '/api/x402/echo', calls: 1000, atomics: '1000000' }],
+ }),
+ });
+
+ expect(split.confident).toBe(false);
+ expect(split.confidence_note).toMatch(/misclassify as external/);
+ });
+
+ it('reports a real zero rather than dividing by nothing on an empty window', async () => {
+ const split = await revenueSplit({ sql: makeSql({ ringPubkeys: [RING], settlements: [] }) });
+ expect(split.total.calls).toBe(0);
+ expect(split.external.share_of_calls).toBe(0);
+ expect(split.external.volume_usdc).toBe('0.000000');
+ expect(split.external.routes).toEqual([]);
+ });
+});