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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(earnings): surface skill royalties in the creator dashboard with a proof lane
nirholas15d7ebe61c3c
diff --git a/scripts/royalty-proof.mjs b/scripts/royalty-proof.mjsnew file mode 100644index 000000000..e0d010cc5--- /dev/null+++ b/scripts/royalty-proof.mjs@@ -0,0 +1,177 @@+#!/usr/bin/env node+/**+ * Skill-royalty proof lane (Roadmap phase 3).+ *+ * Proves, end to end and against a real Postgres, that a paid skill call+ * accrues the author's share and that the accrual reaches the author's+ * earnings surface. It runs the SHIPPING code, not a re-implementation:+ * computeSkillRoyaltySplit + accrueSkillCallRoyalty write the row, and+ * MonetizationService.getCreatorEconomics reads it back exactly as+ * /api/users/me/earnings does.+ *+ * NO FUNDS MOVE. The script never contacts a facilitator, an RPC node, or a+ * chain. It supplies the settlement fields (payer, network, transaction) that+ * a settled x402 payment would hand the onSettled hook, tagged with a+ * PROOF-LANE marker so a proof row can never be mistaken for a real+ * settlement. What is proved is the accounting path; activating real+ * settlement is the owner-gated step documented in+ * docs/skill-royalties.md.+ *+ * Usage:+ * ROYALTY_PROOF_DATABASE_URL=postgres://user:pass@host:5432/db \+ * node scripts/royalty-proof.mjs+ *+ * Against a local Postgres reached through a Neon HTTP proxy (the driver in+ * api/_lib/db.js speaks Neon's HTTP protocol, not raw TCP), also set:+ * ROYALTY_PROOF_FETCH_ENDPOINT=http://localhost:54331/sql+ *+ * The script REFUSES to run without ROYALTY_PROOF_DATABASE_URL: pointing it at+ * a production DATABASE_URL by accident would write ledger rows into real+ * creator earnings. Everything it seeds is deleted on the way out, including+ * after a failure.+ */++import { neonConfig } from '@neondatabase/serverless';++const proofUrl = process.env.ROYALTY_PROOF_DATABASE_URL;+if (!proofUrl) {+ console.error(+ 'ROYALTY_PROOF_DATABASE_URL is not set.\n' ++ 'This lane writes and deletes ledger rows, so it requires an explicit\n' ++ 'throwaway database rather than falling back to DATABASE_URL.\n' ++ 'See docs/skill-royalties.md for the one-command local setup.',+ );+ process.exit(2);+}++// api/_lib/db.js builds its client from env.DATABASE_URL, lazily on first+// query. Point it at the proof database before importing anything that queries.+process.env.DATABASE_URL = proofUrl;+if (process.env.ROYALTY_PROOF_FETCH_ENDPOINT) {+ neonConfig.fetchEndpoint = process.env.ROYALTY_PROOF_FETCH_ENDPOINT;+ neonConfig.useSecureWebSocket = false;+ neonConfig.poolQueryViaFetch = true;+}++const { sql } = await import('../api/_lib/db.js');+const { computeSkillRoyaltySplit, skillRoyaltyPlatformBps, accrueSkillCallRoyalty } = await import(+ '../api/_lib/skill-royalty.js'+);+const { MonetizationService } = await import('../api/_lib/services/MonetizationService.js');+const { NETWORK_SOLANA_MAINNET } = await import('../api/_lib/x402-spec.js');++// Solana leads: the proof settles on the Solana rail, the platform's home chain.+const PROOF_NETWORK = NETWORK_SOLANA_MAINNET;+// Deliberately not a real signature. A proof row must be impossible to mistake+// for a settled payment when someone greps the ledger later.+const PROOF_TX = 'PROOF-LANE-NOT-A-REAL-SETTLEMENT';+const PROOF_PAYER = 'PROOF-LANE-PAYER-WALLET';+const PRICE_USD = 0.25;++const checks = [];+function check(name, pass, detail) {+ checks.push({ name, pass, detail });+ console.log(` ${pass ? 'PASS' : 'FAIL'} ${name}${detail ? ` — ${detail}` : ''}`);+}++const tag = `royalty-proof-${process.pid}`;+let authorId = null;++try {+ console.log(`\nSkill-royalty proof lane\n database: ${redact(proofUrl)}\n chain: ${PROOF_NETWORK}\n`);++ // ── 1. Seed a real author and a real priced marketplace skill ─────────────+ const [author] = await sql`+ INSERT INTO users (email, display_name)+ VALUES (${`${tag}@proof.invalid`}, ${'Royalty Proof Author'})+ RETURNING id+ `;+ authorId = author.id;++ const [skill] = await sql`+ INSERT INTO marketplace_skills+ (author_id, name, slug, description, category, content, is_public, price_per_call_usd)+ VALUES+ (${authorId}, ${'Royalty Proof Skill'}, ${tag}, ${'Proof-lane skill for royalty accrual.'},+ ${'general'}, ${'# Royalty Proof Skill'}, ${true}, ${PRICE_USD})+ RETURNING id, slug, price_per_call_usd+ `;+ console.log(`Seeded author ${authorId} and skill ${skill.slug} at $${Number(skill.price_per_call_usd)}/call\n`);++ // ── 2. The split the rail applies at settlement ───────────────────────────+ const platformBps = skillRoyaltyPlatformBps();+ const priceAtomics = BigInt(Math.round(PRICE_USD * 1_000_000));+ const split = computeSkillRoyaltySplit({ priceAtomics, platformBps });+ console.log(+ `Split at ${platformBps} bps: author ${split.authorAtomics} atomics ($${split.authorUsd}), ` ++ `platform ${split.platformAtomics} atomics ($${split.platformUsd})\n`,+ );++ console.log('Checks:');+ check(+ 'split conserves value (author + platform === price)',+ split.authorAtomics + split.platformAtomics === priceAtomics,+ `${split.authorAtomics} + ${split.platformAtomics} = ${priceAtomics}`,+ );+ check('author receives the majority share', split.authorAtomics > split.platformAtomics);++ // ── 3. Accrue, exactly as the onSettled hook in /api/x402/skill-call does ──+ const accrual = await accrueSkillCallRoyalty({+ skillId: skill.id,+ authorId,+ payer: PROOF_PAYER,+ network: PROOF_NETWORK,+ txHash: PROOF_TX,+ priceAtomics,+ });+ check('accrueSkillCallRoyalty recorded the accrual', accrual.ok === true, accrual.reason ?? `ledger ${accrual.accrual?.ledgerId}`);++ const [row] = await sql`+ SELECT price_usd, platform_fee_usd, status, source, network, payer, tx_hash, agent_id, settled_at+ FROM royalty_ledger WHERE author_user_id = ${authorId}+ `;+ check('ledger row exists for the author', Boolean(row));+ check('row credits the author share, not the gross price', Number(row?.price_usd) === split.authorUsd, `${row?.price_usd} USD`);+ check('row records the platform cut', Number(row?.platform_fee_usd) === split.platformUsd, `${row?.platform_fee_usd} USD`);+ check("row is tagged to the x402 rail", row?.source === 'x402', String(row?.source));+ check('row lands settled (funds routed at settle time)', row?.status === 'settled' && Boolean(row?.settled_at));+ check('row carries the settlement chain and payer', row?.network === PROOF_NETWORK && row?.payer === PROOF_PAYER);+ check('row has no agent_id (the caller is a paying wallet)', row?.agent_id === null);++ // ── 4. Read it back through the author earnings surface ───────────────────+ // This is the exact call /api/users/me/earnings makes. Before the LEFT JOIN+ // fix in MonetizationService.getCreatorSalesData, this returned zero rows for+ // x402 accruals: agent_id is null, and the inner join on agent_identities+ // dropped every one of them.+ const economics = await new MonetizationService(authorId).getCreatorEconomics();+ const entry = (economics.entries || []).find((e) => e.source === 'x402');+ check('earnings surface returns the accrual', Boolean(entry), `${economics.entries?.length ?? 0} entr(ies)`);+ check('earnings surface names the skill', entry?.skill_name === 'Royalty Proof Skill', String(entry?.skill_name));+ check('earnings surface reports the author amount', Number(entry?.price_usd) === split.authorUsd, `$${entry?.price_usd}`);+ check('earnings surface carries the chain and transaction', entry?.network === PROOF_NETWORK && entry?.tx_hash === PROOF_TX);+ check('settled total includes the accrual', Number(economics.settled_usd) === split.authorUsd, `$${economics.settled_usd}`);+ check('platform fee total is reported', Number(economics.platform_fee_usd) === split.platformUsd, `$${economics.platform_fee_usd}`);++ // ── 5. A free skill must never accrue ─────────────────────────────────────+ const zero = await accrueSkillCallRoyalty({ skillId: skill.id, authorId, priceAtomics: 0n });+ check('a zero-price call accrues nothing', zero.ok === false && zero.reason === 'zero_price');+ const [{ count }] = await sql`SELECT COUNT(*)::int AS count FROM royalty_ledger WHERE author_user_id = ${authorId}`;+ check('ledger still holds exactly one row', count === 1, `${count} row(s)`);+} finally {+ if (authorId) {+ // users → marketplace_skills is ON DELETE SET NULL, so drop the skill (and+ // its cascading ledger rows) before the author.+ await sql`DELETE FROM marketplace_skills WHERE slug = ${tag}`;+ await sql`DELETE FROM royalty_ledger WHERE author_user_id = ${authorId}`;+ await sql`DELETE FROM users WHERE id = ${authorId}`;+ console.log('\nProof rows deleted.');+ }+}++const failed = checks.filter((c) => !c.pass);+console.log(`\n${checks.length - failed.length}/${checks.length} checks passed. No funds moved.\n`);+process.exit(failed.length === 0 ? 0 : 1);++function redact(url) {+ return String(url).replace(/\/\/[^@]*@/, '//***@');+}diff --git a/src/dashboard-next/pages/creator-helpers.js b/src/dashboard-next/pages/creator-helpers.jsindex 1f86cf005..648e16870 100644--- a/src/dashboard-next/pages/creator-helpers.js+++ b/src/dashboard-next/pages/creator-helpers.js@@ -183,16 +183,47 @@ export function groupLedgerByStatus(entries) {return { buckets, totals };}-/** Build a CSV string from royalty-ledger / earnings entries for export. */-export function ledgerToCsv(entries) {- const header = ['Date', 'Type', 'Skill', 'Agent', 'Amount (USD)', 'Status'];+// Which rail earned a ledger entry, in the author's words. `source` comes from+// royalty_ledger.source: 'x402' is a per-call payment on the platform's own+// rail (the money routed to the author's wallet at settle time), while+// 'skill-runtime' is an in-process invocation that settles later through the+// delegated-permission redeem leg. Asset sales ride the same table for display.+const RAIL_LABELS = Object.freeze({+ x402: 'Per-call (x402)',+ 'skill-runtime': 'In-app call',+ 'asset-sale': 'Asset sale',+});++/**+ * Human label for a royalty entry's earning rail.+ * @param {string|null|undefined} source+ * @returns {string}+ */+export function railLabel(source) {+ return RAIL_LABELS[source] || RAIL_LABELS['skill-runtime'];+}++/**+ * Build a CSV string from royalty-ledger / earnings entries for export.+ * Carries the settlement provenance (rail, chain, transaction) so an exported+ * row can be reconciled against the chain without opening the dashboard.+ */+export function ledgerToCsv(entries, { networkLabel = (n) => n || '' } = {}) {+ const header = ['Date', 'Type', 'Skill', 'Agent', 'Amount (USD)', 'Platform fee (USD)', 'Status', 'Rail', 'Chain', 'Transaction'];const rows = (entries || []).map((e) => [csvCell(e?.created_at || ''),csvCell(e?.kind || 'skill'),csvCell(e?.skill_name || ''),csvCell(e?.agent_name || ''),- csvCell(Number(e?.price_usd ?? 0).toFixed(4)),+ // Six decimals, matching USDC's precision and the numeric(10,6) ledger+ // column. Per-call royalties are routinely sub-cent, so the previous+ // 4-decimal export rounded real money out of the author's own records.+ csvCell(Number(e?.price_usd ?? 0).toFixed(6)),+ csvCell(e?.platform_fee_usd == null ? '' : Number(e.platform_fee_usd).toFixed(6)),csvCell(e?.status || ''),+ csvCell(railLabel(e?.source)),+ csvCell(e?.network ? networkLabel(e.network) : ''),+ csvCell(e?.tx_hash || ''),]);return [header.map(csvCell).join(','), ...rows.map((r) => r.join(','))].join('\n');}diff --git a/src/dashboard-next/pages/creator-helpers.test.js b/src/dashboard-next/pages/creator-helpers.test.jsindex 424060ca3..16caa2048 100644--- a/src/dashboard-next/pages/creator-helpers.test.js+++ b/src/dashboard-next/pages/creator-helpers.test.js@@ -9,6 +9,7 @@ import {effectivePriceNow,groupLedgerByStatus,ledgerToCsv,+ railLabel,funnelStage,TIER_LADDER,} from './creator-helpers.js';@@ -157,19 +158,63 @@ describe('groupLedgerByStatus', () => {});});+const CSV_HEADER = 'Date,Type,Skill,Agent,Amount (USD),Platform fee (USD),Status,Rail,Chain,Transaction';++describe('railLabel', () => {+ it('names each earning rail', () => {+ expect(railLabel('x402')).toBe('Per-call (x402)');+ expect(railLabel('skill-runtime')).toBe('In-app call');+ expect(railLabel('asset-sale')).toBe('Asset sale');+ });+ it('falls back to the in-app lane for an unknown or missing source', () => {+ expect(railLabel(undefined)).toBe('In-app call');+ expect(railLabel('something-new')).toBe('In-app call');+ });+});+describe('ledgerToCsv', () => {it('emits a header and escapes cells with commas/quotes', () => {const csv = ledgerToCsv([{ created_at: '2026-06-01', kind: 'skill', skill_name: 'Do, a thing', agent_name: 'Agent "X"', price_usd: 1.5, status: 'settled' },]);const lines = csv.split('\n');- expect(lines[0]).toBe('Date,Type,Skill,Agent,Amount (USD),Status');+ expect(lines[0]).toBe(CSV_HEADER);expect(lines[1]).toContain('"Do, a thing"');expect(lines[1]).toContain('"Agent ""X"""');- expect(lines[1]).toContain('1.5000');+ expect(lines[1]).toContain('1.500000');+ });++ it('carries the settlement provenance of a per-call royalty', () => {+ const csv = ledgerToCsv(+ [{+ created_at: '2026-08-13', kind: 'skill', skill_name: 'Wallet Balance', agent_name: null,+ price_usd: 0.24375, platform_fee_usd: 0.00625, status: 'settled',+ source: 'x402', network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', tx_hash: '5xTxSignature',+ }],+ { networkLabel: () => 'Solana' },+ );+ const row = csv.split('\n')[1];+ expect(row).toContain('Per-call (x402)');+ expect(row).toContain('Solana');+ expect(row).toContain('5xTxSignature');+ // Full USDC precision: per-call royalties are routinely sub-cent, so a+ // 4-decimal export would round real money out of the author's records.+ expect(row).toContain('0.243750');+ expect(row).toContain('0.006250');+ });++ it('keeps a sub-cent royalty from rounding to zero', () => {+ const csv = ledgerToCsv([{ created_at: '2026-08-13', price_usd: 0.000001, status: 'settled' }]);+ expect(csv.split('\n')[1]).toContain('0.000001');});++ it('leaves the fee, chain and transaction blank rather than guessing', () => {+ const csv = ledgerToCsv([{ created_at: '2026-08-13', price_usd: 1, status: 'pending', source: 'skill-runtime' }]);+ expect(csv.split('\n')[1].endsWith(',,')).toBe(true);+ });+it('handles empty input', () => {- expect(ledgerToCsv([])).toBe('Date,Type,Skill,Agent,Amount (USD),Status');+ expect(ledgerToCsv([])).toBe(CSV_HEADER);});});diff --git a/src/dashboard-next/pages/creator.js b/src/dashboard-next/pages/creator.jsindex 3b3c04c56..1916ae19d 100644--- a/src/dashboard-next/pages/creator.js+++ b/src/dashboard-next/pages/creator.js@@ -24,8 +24,14 @@ import {effectivePriceNow,groupLedgerByStatus,ledgerToCsv,+ railLabel,funnelStage,} from './creator-helpers.js';+// Chain identity lives in one place for the whole platform: the ledger stores+// CAIP-2 ids ('solana:5eykt4Us…', 'eip155:8453') and this module owns the+// id → label and id → explorer mapping, so a Base settlement never links to a+// Solana explorer. Pure string/data code, safe in the browser bundle.+import { networkLabel, revenueTxUrl } from '../../../api/_lib/x402/revenue-networks.js';const SOLANA_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;const EVM_ADDR_RE = /^0x[a-fA-F0-9]{40}$/;@@ -145,8 +151,20 @@ function renderAgentSelector(host, contentHost) {async function loadAndRender(host) {if (!STATE.agents.length) {+ // Royalties are AUTHOR-scoped, not agent-scoped: a marketplace skill author+ // earns on every paid /api/x402/skill-call whether or not they ever+ // registered an agent. Load the author ledger BEFORE the agent gate so a+ // creator who is already being paid never hits a "create an agent" wall+ // standing between them and their own money.+ const earnings = await safe(() => get('/api/users/me/earnings'));+ STATE.earnings = earnings || { pending_usd: 0, settled_usd: 0, entries: [] };host.innerHTML = '';- host.appendChild(renderNoAgents());+ if ((STATE.earnings.entries || []).length) {+ host.appendChild(renderAuthorOnlyIntro());+ host.appendChild(renderRoyaltyLedger());+ } else {+ host.appendChild(renderNoAgents());+ }return;}@@ -280,7 +298,10 @@ function renderEarningsHero() {const net = Number(r.net_usdc || 0);const fees = Number(r.total_fees_usdc || 0);const count = Number(r.event_count || 0);- const pending = Number(STATE.earnings?.pending_usd || 0);+ // Unsettled = not yet in the author's wallet. 'settling' rows are claimed by+ // an in-flight redeem pass, so counting only 'pending' understated what the+ // author is still owed.+ const pending = Number(STATE.earnings?.pending_usd || 0) + Number(STATE.earnings?.settling_usd || 0);const available = Number(STATE.balance?.available_usdc || 0);const periodLabel = (PERIODS.find((p) => p.key === STATE.period) || PERIODS[1]).label.toLowerCase();@@ -875,7 +896,7 @@ function renderRoyaltyLedger() {body.innerHTML = `<div style="overflow-x:auto"><table class="cs-table">- <thead><tr><th scope="col">When</th><th scope="col">Skill</th><th scope="col">Agent</th><th scope="col" style="text-align:right">Amount</th><th scope="col">Status</th></tr></thead>+ <thead><tr><th scope="col">When</th><th scope="col">Skill</th><th scope="col">Rail</th><th scope="col">Agent</th><th scope="col" style="text-align:right">Amount</th><th scope="col">Status</th></tr></thead><tbody>${sorted.map(ledgerRow).join('')}</tbody></table></div>@@ -883,7 +904,7 @@ function renderRoyaltyLedger() {}panel.querySelector('[data-action="export"]')?.addEventListener('click', () => {- const csv = ledgerToCsv(entries);+ const csv = ledgerToCsv(entries, { networkLabel });downloadCsv(csv, `creator-royalties-${STATE.agentId?.slice(0, 8) || 'all'}.csv`);toast('Royalty history exported');});@@ -901,12 +922,23 @@ function ledgerRow(e) {settling: '<span class="cs-tag accent">Settling</span>',failed: '<span class="cs-tag bad">Failed</span>',}[e.status] || '<span class="cs-tag warn">Pending</span>';+ // Per-call x402 rows carry the settlement transaction, so the amount links+ // straight to the explorer: the author can verify their own payout on-chain+ // instead of trusting this table. Rows with no tx (in-app calls awaiting the+ // redeem leg) render the plain amount.+ const txUrl = e.tx_hash ? revenueTxUrl(e.tx_hash, e.network) : null;+ const amount = usd(Number(e.price_usd || 0));+ const amountCell = txUrl+ ? `<a href="${esc(txUrl)}" target="_blank" rel="noopener" title="View this settlement on the explorer">${amount}</a>`+ : amount;+ const chain = e.network ? networkLabel(e.network) : '';return `<tr><td style="white-space:nowrap;color:var(--nxt-ink-dim)">${esc(relTime(e.created_at))}</td>- <td>${esc(e.skill_name || e.kind || '—')}</td>- <td style="color:var(--nxt-ink-dim)">${esc(e.agent_name || '—')}</td>- <td style="text-align:right">${usd(Number(e.price_usd || 0))}</td>+ <td>${esc(e.skill_name || e.kind || '(removed)')}</td>+ <td style="color:var(--nxt-ink-dim)">${esc(railLabel(e.source))}${chain ? ` · ${esc(chain)}` : ''}</td>+ <td style="color:var(--nxt-ink-dim)">${esc(e.agent_name || 'Direct call')}</td>+ <td style="text-align:right">${amountCell}</td><td>${tag}</td></tr>`;}@@ -1011,6 +1043,26 @@ async function reloadAgentPricing(host) {await loadAndRender(host);}+// Shown to an author who earns skill royalties but has no agent yet: their+// money first, the upsell second. The rest of Creator Studio (pricing rules,+// payouts, per-agent analytics) genuinely needs an agent, so it stays behind+// the link rather than rendering half-empty panels.+function renderAuthorOnlyIntro() {+ const el = document.createElement('div');+ el.className = 'dn-panel';+ const { totals } = groupLedgerByStatus(STATE.earnings?.entries || []);+ const earned = totals.pending + totals.settling + totals.settled;+ el.innerHTML = `+ <div class="dn-panel-title">You're earning skill royalties</div>+ <div class="dn-panel-sub">+ You've earned ${esc(usd(earned))} from calls to skills you published to the marketplace.+ Every paid call routes your share straight to your wallet.+ Create an agent to unlock pricing rules, payouts, and per-skill analytics.+ </div>+ <a class="dn-btn primary" href="/dashboard/agents" style="margin-top:14px">Create an agent</a>`;+ return el;+}+function renderNoAgents() {const el = document.createElement('div');el.className = 'dn-panel';diff --git a/tests/skill-royalty-earnings.test.js b/tests/skill-royalty-earnings.test.jsnew file mode 100644index 000000000..3234c6d50--- /dev/null+++ b/tests/skill-royalty-earnings.test.js@@ -0,0 +1,167 @@+// Author earnings surface for per-call skill royalties (Roadmap phase 3).+//+// The split math and the accrual writer are covered in tests/skill-royalty.test.js.+// This suite covers the READ side: MonetizationService.getCreatorSalesData, which+// backs /api/users/me/earnings and the Creator Studio royalty ledger, plus the+// presentation helpers that turn a ledger row into something an author can+// reconcile against the chain.+//+// The regression that motivates most of it: royalty_ledger.agent_id is NULL for+// every accrual on the platform's own x402 rail (the caller is a paying wallet,+// not a registered agent), so an INNER JOIN on agent_identities silently dropped+// 100% of per-call royalties from the surface. Authors earning real USDC saw an+// empty ledger and a $0 total.++import { describe, it, expect } from 'vitest';+import { MonetizationService } from '../api/_lib/services/MonetizationService.js';+import { railLabel, ledgerToCsv, groupLedgerByStatus } from '../src/dashboard-next/pages/creator-helpers.js';++// Queue-driven tagged-template stub, injected through the service's `deps.sql`+// seam. Records every query so the join shape itself can be asserted.+function makeSql(queue) {+ const calls = [];+ const sql = async (strings, ...values) => {+ calls.push({ query: Array.isArray(strings) ? strings.join('?') : String(strings), values });+ return queue.length ? queue.shift() : [];+ };+ sql.calls = calls;+ return sql;+}++const AUTHOR = 'author-1';++// One settled accrual from the x402 rail: no agent, full settlement provenance.+const X402_ROW = {+ id: 'ledger-x402',+ price_usd: '0.243750',+ status: 'settled',+ created_at: '2026-08-13T12:00:00.000Z',+ settled_at: '2026-08-13T12:00:01.000Z',+ source: 'x402',+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ tx_hash: '5xTxSignature',+ platform_fee_usd: '0.006250',+ skill_name: 'Wallet Balance',+ skill_slug: 'wallet-balance',+ agent_name: null,+};++// One in-process runtime accrual: has an agent, no chain provenance yet.+const RUNTIME_ROW = {+ id: 'ledger-runtime',+ price_usd: '0.100000',+ status: 'pending',+ created_at: '2026-08-13T11:00:00.000Z',+ settled_at: null,+ source: 'skill-runtime',+ network: null,+ tx_hash: null,+ platform_fee_usd: null,+ skill_name: 'Summarize',+ skill_slug: 'summarize',+ agent_name: 'Scout',+};++describe('getCreatorSalesData — both royalty lanes reach the author', () => {+ it('LEFT JOINs agent_identities so x402 accruals are not dropped', async () => {+ const sql = makeSql([[X402_ROW], []]);+ await new MonetizationService(AUTHOR, { sql }).getCreatorSalesData();++ const ledgerQuery = sql.calls[0].query;+ expect(ledgerQuery).toMatch(/LEFT JOIN agent_identities/i);+ // An inner join here is the exact bug: it discards every NULL agent_id.+ expect(ledgerQuery).not.toMatch(/\n\s*JOIN agent_identities/i);+ });++ it('returns the x402 accrual with its settlement provenance', async () => {+ const sql = makeSql([[X402_ROW], []]);+ const data = await new MonetizationService(AUTHOR, { sql }).getCreatorSalesData();++ expect(data.entries).toHaveLength(1);+ const [entry] = data.entries;+ expect(entry.source).toBe('x402');+ expect(entry.skill_name).toBe('Wallet Balance');+ expect(entry.skill_slug).toBe('wallet-balance');+ expect(entry.price_usd).toBe(0.24375);+ expect(entry.platform_fee_usd).toBe(0.00625);+ expect(entry.network).toBe('solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp');+ expect(entry.tx_hash).toBe('5xTxSignature');+ expect(entry.agent_name).toBeNull();+ });++ it('defaults a row with no recorded source to the runtime lane', async () => {+ const sql = makeSql([[{ ...RUNTIME_ROW, source: null }], []]);+ const data = await new MonetizationService(AUTHOR, { sql }).getCreatorSalesData();+ expect(data.entries[0].source).toBe('skill-runtime');+ });++ it('separates pending, settling and settled totals', async () => {+ const rows = [+ X402_ROW,+ RUNTIME_ROW,+ { ...RUNTIME_ROW, id: 'ledger-settling', status: 'settling', price_usd: '0.050000' },+ ];+ const sql = makeSql([rows, []]);+ const data = await new MonetizationService(AUTHOR, { sql }).getCreatorSalesData();++ expect(data.pending_usd).toBeCloseTo(0.1, 6);+ expect(data.settling_usd).toBeCloseTo(0.05, 6);+ expect(data.settled_usd).toBeCloseTo(0.24375, 6);+ });++ it('sums the platform cut and treats a null fee as zero', async () => {+ const sql = makeSql([[X402_ROW, RUNTIME_ROW], []]);+ const data = await new MonetizationService(AUTHOR, { sql }).getCreatorSalesData();+ expect(data.platform_fee_usd).toBeCloseTo(0.00625, 6);+ });++ it('keeps asset sales in the same feed with a distinct source', async () => {+ const assetRow = {+ id: 'asset-1',+ item_type: 'avatar',+ item_id: 'avatar-1',+ amount: '2500000',+ currency_mint: null,+ confirmed_at: '2026-08-13T13:00:00.000Z',+ created_at: '2026-08-13T13:00:00.000Z',+ status: 'confirmed',+ item_name: 'Knight',+ };+ const sql = makeSql([[X402_ROW], [assetRow]]);+ const data = await new MonetizationService(AUTHOR, { sql }).getCreatorSalesData();++ const asset = data.entries.find((e) => e.kind === 'avatar');+ expect(asset.source).toBe('asset-sale');+ expect(asset.price_usd).toBe(2.5);+ // Asset revenue tops up the settled total alongside settled royalties.+ expect(data.settled_usd).toBeCloseTo(2.74375, 6);+ });++ it('requires an authenticated author', async () => {+ const sql = makeSql([]);+ await expect(new MonetizationService(null, { sql }).getCreatorSalesData()).rejects.toMatchObject({ status: 401 });+ });+});++describe('the ledger entry a Creator Studio row is built from', () => {+ it('survives the round trip into the CSV export the author downloads', async () => {+ const sql = makeSql([[X402_ROW], []]);+ const data = await new MonetizationService(AUTHOR, { sql }).getCreatorSalesData();+ const row = ledgerToCsv(data.entries, { networkLabel: () => 'Solana' }).split('\n')[1];++ expect(row).toContain(railLabel('x402'));+ expect(row).toContain('Solana');+ expect(row).toContain('5xTxSignature');+ expect(row).toContain('0.243750');+ });++ it('buckets a settled per-call royalty as settled', async () => {+ const sql = makeSql([[X402_ROW, RUNTIME_ROW], []]);+ const data = await new MonetizationService(AUTHOR, { sql }).getCreatorSalesData();+ const { totals, buckets } = groupLedgerByStatus(data.entries);++ expect(totals.settled).toBeCloseTo(0.24375, 6);+ expect(totals.pending).toBeCloseTo(0.1, 6);+ expect(buckets.settled[0].source).toBe('x402');+ });+});