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(royalties): accrue per-call author royalties on paid skill calls

nirholasf0e177a09383
diff --git a/api/_lib/migrations/20260812120000_skill_call_royalties.sql b/api/_lib/migrations/20260812120000_skill_call_royalties.sql
new file mode 100644
index 000000000..28020a47a
--- /dev/null
+++ b/api/_lib/migrations/20260812120000_skill_call_royalties.sql
@@ -0,0 +1,32 @@
+-- Per-call skill royalties on the platform x402 rail (Roadmap phase 3).
+--
+-- Until now royalty_ledger only served in-process skill invocations billed
+-- through api/_lib/royalty.js, so every column assumed a registered agent
+-- caller (agent_id NOT NULL) and a later EIP-7710 redeem (status pending →
+-- settled by the settle-royalties cron). The /api/x402/skill-call rail is
+-- different: the caller is an anonymous paying wallet, and the USDC already
+-- routed to the author at settle time. This migration widens the ledger so
+-- both lanes coexist:
+--
+-- * agent_id becomes nullable (x402 callers have no agent_identities row).
+-- * network / payer / source / platform_fee_usd record settlement
+-- provenance: which rail charged whom, and the platform's cut in USD.
+-- * The status CHECK gains no new values: x402 rows land 'settled'
+-- directly (money already moved), runtime rows keep pending → settling →
+-- settled.
+--
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260812120000_skill_call_royalties.sql
+-- Idempotent.
+
+begin;
+
+alter table royalty_ledger
+ alter column agent_id drop not null;
+
+alter table royalty_ledger
+ add column if not exists network text,
+ add column if not exists payer text,
+ add column if not exists source text not null default 'skill-runtime',
+ add column if not exists platform_fee_usd numeric(10,6);
+
+commit;
diff --git a/api/_lib/royalty.js b/api/_lib/royalty.js
index ead24a4ed..86302811d 100644
--- a/api/_lib/royalty.js
+++ b/api/_lib/royalty.js
@@ -79,9 +79,19 @@ const SETTLE_THRESHOLD_USD = 0.01;
* Groups by (agent_id, chain_id), looks up delegation, redeems via the
* /api/permissions/redeem relayer endpoint, then marks rows settled or failed.
*
+ * The EVM delegation-redeem leg is flag-gated
+ * (SKILL_ROYALTIES_EVM_7710_ENABLED): with the flag off, pending groups are
+ * left pending and counted as skipped, so the cron is provably inert until
+ * the owner activates it. x402-rail rows land 'settled' at accrual time and
+ * never pass through here.
+ *
* @param {string} authorUserId
+ * @returns {Promise<{ skipped?: boolean, groups?: number }>}
*/
export async function settleRoyalties(authorUserId) {
+ if (!env.SKILL_ROYALTIES_EVM_7710_ENABLED) {
+ return { skipped: true, reason: 'evm_7710_disabled' };
+ }
// Aggregate pending rows by agent + chain.
const groups = await sql`
SELECT
@@ -145,13 +155,19 @@ export async function settleRoyalties(authorUserId) {
`;
}
}
+ return { groups: groups.length };
}
/**
* Settle all authors with pending balances above the threshold.
- * Called by the cron job.
+ * Called by the cron job. With the EVM 7710 flag off this is a no-op that
+ * still reports honestly, so the daily cron run stays green while the leg
+ * waits for owner activation.
*/
export async function settleAllPendingRoyalties() {
+ if (!env.SKILL_ROYALTIES_EVM_7710_ENABLED) {
+ return { settled: 0, failed: 0, authors: 0, skipped: true, reason: 'evm_7710_disabled' };
+ }
const authors = await sql`
SELECT DISTINCT author_user_id
FROM royalty_ledger
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 91398efcc..0066e3b85 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -1435,12 +1435,19 @@ alter table marketplace_skills add column if not exists price_per_call_usd numer
create table if not exists royalty_ledger (
id uuid primary key default gen_random_uuid(),
skill_id uuid not null references marketplace_skills(id) on delete cascade,
- agent_id uuid not null references agent_identities(id) on delete cascade,
+ -- nullable: /api/x402/skill-call callers are paying wallets, not agents
+ agent_id uuid references agent_identities(id) on delete cascade,
author_user_id uuid not null references users(id) on delete cascade,
price_usd numeric(10,6) not null,
status text not null default 'pending',
settled_at timestamptz,
tx_hash text,
+ -- settlement provenance (x402 rail): which network, which paying wallet,
+ -- which lane accrued the row, and the platform's cut in USD
+ network text,
+ payer text,
+ source text not null default 'skill-runtime',
+ platform_fee_usd numeric(10,6),
created_at timestamptz not null default now(),
constraint royalty_ledger_status_check check (status in ('pending', 'settling', 'settled', 'failed'))
);
diff --git a/api/_lib/skill-royalty.js b/api/_lib/skill-royalty.js
new file mode 100644
index 000000000..c151de312
--- /dev/null
+++ b/api/_lib/skill-royalty.js
@@ -0,0 +1,127 @@
+// Skill-call royalties: the author share of a paid skill invocation.
+//
+// Two payment lanes reach a priced marketplace skill, and both must accrue to
+// the same author ledger:
+//
+// 1. The platform's own x402 rail (/api/x402/skill-call). The caller pays the
+// per-call price in USDC (Solana first, Base second); the endpoint routes
+// the full payment to the author's primary wallet via a payTo override,
+// minus the platform royalty bps declared here, and this module records
+// the author accrual against royalty_ledger after settlement.
+// 2. In-process skill invocations (api/_lib/skill-runtime.js), which bill via
+// billSkillRoyalty in api/_lib/royalty.js and settle later through the
+// EIP-7710 delegation redeem leg (EVM, flag-gated).
+//
+// This module is the split math (pure, unit-tested) plus the accrual writer.
+// The pure part has no DB and no chain access so the split invariants are
+// provable in isolation; the writer is fire-and-forget from the paid-endpoint
+// settle hook so an accrual failure can never break a settled payment.
+
+import { sql } from './db.js';
+
+// The platform's cut of a per-call skill payment, in basis points (default
+// 2.5%, matching the marketplace fee in api/_lib/fee.js). The author keeps the
+// rest. Overridable per-deploy via X402_SKILL_ROYALTY_PLATFORM_BPS; clamped to
+// [0, 5000] so a misconfig can never take more than half a call's revenue.
+export const SKILL_ROYALTY_DEFAULT_PLATFORM_BPS = 250;
+export const SKILL_ROYALTY_MAX_PLATFORM_BPS = 5000;
+
+export function skillRoyaltyPlatformBps(env = process.env) {
+ const raw = Number.parseInt(String(env.X402_SKILL_ROYALTY_PLATFORM_BPS ?? ''), 10);
+ if (!Number.isFinite(raw) || raw < 0) return SKILL_ROYALTY_DEFAULT_PLATFORM_BPS;
+ return Math.min(raw, SKILL_ROYALTY_MAX_PLATFORM_BPS);
+}
+
+// USDC is 6-decimal everywhere the x402 rail settles.
+const USDC_DECIMALS = 6;
+
+function toAtomics(value) {
+ if (typeof value === 'bigint') return value < 0n ? 0n : value;
+ if (typeof value === 'number') {
+ if (!Number.isFinite(value) || value <= 0) return 0n;
+ return BigInt(Math.floor(value));
+ }
+ const s = String(value ?? '').trim();
+ if (!/^\d+$/.test(s)) return 0n;
+ return BigInt(s);
+}
+
+/**
+ * Split a settled per-call payment between the skill author and the platform.
+ * Pure and exact: author = price - floor(price × platformBps / 10000), so
+ * authorAtomics + platformAtomics === priceAtomics for every input and no
+ * value is created or lost. The author rounds up on odd atomics (the platform
+ * absorbs the rounding dust), which is the deliberate bias toward the creator.
+ *
+ * @param {{ priceAtomics: bigint|number|string, platformBps?: number }} args
+ * @returns {{
+ * priceAtomics: bigint,
+ * platformBps: number,
+ * authorAtomics: bigint,
+ * platformAtomics: bigint,
+ * authorUsd: number,
+ * platformUsd: number,
+ * }}
+ */
+export function computeSkillRoyaltySplit({ priceAtomics, platformBps }) {
+ const price = toAtomics(priceAtomics);
+ const bps = Math.max(
+ 0,
+ Math.min(
+ SKILL_ROYALTY_MAX_PLATFORM_BPS,
+ Math.round(Number(platformBps ?? SKILL_ROYALTY_DEFAULT_PLATFORM_BPS) || 0),
+ ),
+ );
+ const platform = price > 0n && bps > 0 ? (price * BigInt(bps)) / 10000n : 0n;
+ const author = price - platform;
+ return {
+ priceAtomics: price,
+ platformBps: bps,
+ authorAtomics: author,
+ platformAtomics: platform,
+ authorUsd: Number(author) / 10 ** USDC_DECIMALS,
+ platformUsd: Number(platform) / 10 ** USDC_DECIMALS,
+ };
+}
+
+/**
+ * Record a royalty accrual for one settled x402 skill call. Called from the
+ * paid-endpoint onSettled hook (fire-and-forget): NEVER throws, so a Neon
+ * hiccup can never fail a payment that already settled on-chain. The author
+ * accrual is what they earned; on the x402 rail the funds already routed to
+ * their wallet at settle time, so the row lands 'settled' with the rail's
+ * transaction as provenance (source 'x402'). Rows billed by the in-process
+ * runtime (source 'skill-runtime') stay 'pending' for the delegation redeem
+ * leg instead — settleRoyalties in api/_lib/royalty.js owns those.
+ *
+ * @param {{ skillId: string, authorId: string, payer?: string|null,
+ * network?: string|null, txHash?: string|null, priceAtomics: bigint|number|string,
+ * platformBps?: number }} opts
+ * @returns {Promise<{ ok: boolean, accrual?: object, reason?: string }>}
+ */
+export async function accrueSkillCallRoyalty(opts) {
+ try {
+ const { skillId, authorId } = opts;
+ if (!skillId || !authorId) return { ok: false, reason: 'missing_skill_or_author' };
+ const split = computeSkillRoyaltySplit({
+ priceAtomics: opts.priceAtomics,
+ platformBps: opts.platformBps ?? skillRoyaltyPlatformBps(),
+ });
+ if (split.authorAtomics <= 0n) return { ok: false, reason: 'zero_price', accrual: split };
+
+ const [row] = await sql`
+ INSERT INTO royalty_ledger
+ (skill_id, agent_id, author_user_id, price_usd, status,
+ settled_at, tx_hash, network, payer, source, platform_fee_usd)
+ VALUES
+ (${skillId}, null, ${authorId}, ${split.authorUsd}, 'settled',
+ now(), ${opts.txHash ?? null}, ${opts.network ?? null},
+ ${opts.payer ?? null}, 'x402', ${split.platformUsd})
+ RETURNING id
+ `;
+ return { ok: true, accrual: { ...split, ledgerId: row?.id ?? null } };
+ } catch (e) {
+ console.error('[skill-royalty] accrual failed', e?.message);
+ return { ok: false, reason: e?.message ?? 'accrual_failed' };
+ }
+}
diff --git a/api/x402/skill-call.js b/api/x402/skill-call.js
index 83b159a33..3f1c737c8 100644
--- a/api/x402/skill-call.js
+++ b/api/x402/skill-call.js
@@ -24,6 +24,7 @@ import { priceFor } from '../_lib/x402-prices.js';
import { sql } from '../_lib/db.js';
import { error } from '../_lib/http.js';
import { env } from '../_lib/env.js';
+import { accrueSkillCallRoyalty } from '../_lib/skill-royalty.js';
import skillCallListing from '../_lib/service-catalog/services/skill-call.js';
const ROUTE = '/api/x402/skill-call';
@@ -216,6 +217,21 @@ export default async function handler(req, res) {
tags: ['skill', 'agent', 'tool', 'pay-per-call'],
}),
payTo: Object.keys(payTo).length ? payTo : undefined,
+ // Roadmap phase 3: per-call author royalties. After settlement lands,
+ // record the author's share (price minus the platform bps) on
+ // royalty_ledger with the rail's tx as provenance. Fire-and-forget by
+ // contract of onSettled; an accrual failure never breaks the response.
+ onSettled: skill.author_id
+ ? ({ payer, network, txHash, amountAtomics }) =>
+ accrueSkillCallRoyalty({
+ skillId: skill.id,
+ authorId: skill.author_id,
+ payer,
+ network,
+ txHash,
+ priceAtomics: amountAtomics ?? priceAtomics,
+ })
+ : undefined,
// Per-call resource key so payment-identifier idempotency and audit logs
// attribute to the specific skill being called.
resourceUrlBuilder: () => `${env.APP_ORIGIN}${ROUTE}?skill=${encodeURIComponent(skill.slug)}`,
diff --git a/tests/skill-royalty.test.js b/tests/skill-royalty.test.js
new file mode 100644
index 000000000..6fea144a4
--- /dev/null
+++ b/tests/skill-royalty.test.js
@@ -0,0 +1,181 @@
+// Tests for api/_lib/skill-royalty.js: the per-call author royalty split
+// (pure math) plus the royalty_ledger accrual writer, and for the
+// SKILL_ROYALTIES_EVM_7710_ENABLED flag gate on the EIP-7710 redeem leg in
+// api/_lib/royalty.js.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+const sqlMock = vi.fn(() => Promise.resolve([{ id: 'ledger-1' }]));
+vi.mock('../api/_lib/db.js', () => ({ sql: sqlMock }));
+
+const {
+ computeSkillRoyaltySplit,
+ skillRoyaltyPlatformBps,
+ accrueSkillCallRoyalty,
+ SKILL_ROYALTY_DEFAULT_PLATFORM_BPS,
+ SKILL_ROYALTY_MAX_PLATFORM_BPS,
+} = await import('../api/_lib/skill-royalty.js');
+
+beforeEach(() => {
+ sqlMock.mockClear();
+ sqlMock.mockResolvedValue([{ id: 'ledger-1' }]);
+ delete process.env.X402_SKILL_ROYALTY_PLATFORM_BPS;
+});
+
+afterEach(() => {
+ delete process.env.X402_SKILL_ROYALTY_PLATFORM_BPS;
+});
+
+describe('skillRoyaltyPlatformBps', () => {
+ it('defaults to the marketplace fee rate (250 bps)', () => {
+ expect(SKILL_ROYALTY_DEFAULT_PLATFORM_BPS).toBe(250);
+ expect(skillRoyaltyPlatformBps({})).toBe(250);
+ });
+
+ it('honors a valid env override', () => {
+ expect(skillRoyaltyPlatformBps({ X402_SKILL_ROYALTY_PLATFORM_BPS: '500' })).toBe(500);
+ });
+
+ it('clamps an out-of-range override to the max', () => {
+ expect(skillRoyaltyPlatformBps({ X402_SKILL_ROYALTY_PLATFORM_BPS: '9000' })).toBe(
+ SKILL_ROYALTY_MAX_PLATFORM_BPS,
+ );
+ });
+
+ it('falls back to the default on garbage or negative input', () => {
+ expect(skillRoyaltyPlatformBps({ X402_SKILL_ROYALTY_PLATFORM_BPS: 'abc' })).toBe(250);
+ expect(skillRoyaltyPlatformBps({ X402_SKILL_ROYALTY_PLATFORM_BPS: '-5' })).toBe(250);
+ });
+});
+
+describe('computeSkillRoyaltySplit', () => {
+ it('splits a 0.01 USDC call at the default 2.5% platform rate', () => {
+ const s = computeSkillRoyaltySplit({ priceAtomics: 10_000n });
+ expect(s.platformAtomics).toBe(250n);
+ expect(s.authorAtomics).toBe(9_750n);
+ expect(s.authorUsd).toBeCloseTo(0.00975, 9);
+ expect(s.platformUsd).toBeCloseTo(0.00025, 9);
+ });
+
+ it('conserves value: author + platform === price for many inputs', () => {
+ const prices = [1n, 7n, 999n, 10_000n, 1_000_000n, 3_333_333n, 123_456_789n];
+ const rates = [0, 1, 250, 1000, 5000];
+ for (const p of prices) {
+ for (const r of rates) {
+ const s = computeSkillRoyaltySplit({ priceAtomics: p, platformBps: r });
+ expect(s.authorAtomics + s.platformAtomics).toBe(p);
+ expect(s.authorAtomics >= 0n).toBe(true);
+ expect(s.platformAtomics >= 0n).toBe(true);
+ }
+ }
+ });
+
+ it('the author rounds up on odd atomics (platform absorbs rounding dust)', () => {
+ // 3 atomics at 33%: floor(3*3333/10000)=0 platform, author keeps all 3.
+ const s = computeSkillRoyaltySplit({ priceAtomics: 3n, platformBps: 3333 });
+ expect(s.platformAtomics).toBe(0n);
+ expect(s.authorAtomics).toBe(3n);
+ });
+
+ it('a 0 bps rate pays the author everything', () => {
+ const s = computeSkillRoyaltySplit({ priceAtomics: 1_000_000n, platformBps: 0 });
+ expect(s.platformAtomics).toBe(0n);
+ expect(s.authorAtomics).toBe(1_000_000n);
+ });
+
+ it('clamps a platform rate above the hard max', () => {
+ const s = computeSkillRoyaltySplit({ priceAtomics: 1_000_000n, platformBps: 9999 });
+ expect(s.platformBps).toBe(SKILL_ROYALTY_MAX_PLATFORM_BPS);
+ expect(s.platformAtomics).toBe(500_000n);
+ expect(s.authorAtomics).toBe(500_000n);
+ });
+
+ it('coerces string and number prices and rejects garbage', () => {
+ expect(computeSkillRoyaltySplit({ priceAtomics: '1000000' }).authorAtomics).toBe(975_000n);
+ expect(computeSkillRoyaltySplit({ priceAtomics: 10_000 }).priceAtomics).toBe(10_000n);
+ expect(computeSkillRoyaltySplit({ priceAtomics: 'not-a-number' }).priceAtomics).toBe(0n);
+ expect(computeSkillRoyaltySplit({ priceAtomics: -5 }).priceAtomics).toBe(0n);
+ });
+});
+
+describe('accrueSkillCallRoyalty', () => {
+ const base = {
+ skillId: '11111111-1111-1111-1111-111111111111',
+ authorId: '22222222-2222-2222-2222-222222222222',
+ payer: 'BuyerWallet111',
+ network: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',
+ txHash: 'sig-abc',
+ };
+
+ it('inserts a settled x402 accrual row with provenance and returns the split', async () => {
+ const out = await accrueSkillCallRoyalty({ ...base, priceAtomics: 10_000n });
+ expect(out.ok).toBe(true);
+ expect(out.accrual.authorAtomics).toBe(9_750n);
+ expect(out.accrual.platformAtomics).toBe(250n);
+ expect(out.accrual.ledgerId).toBe('ledger-1');
+
+ expect(sqlMock).toHaveBeenCalledTimes(1);
+ const [strings, ...values] = sqlMock.mock.calls[0];
+ const text = strings.join('?');
+ expect(text).toMatch(/INSERT INTO royalty_ledger/i);
+ // author share (0.00975) then platform fee (0.00025) land as USD values.
+ expect(values).toContain(base.skillId);
+ expect(values).toContain(null); // agent_id is null for x402 callers
+ expect(values).toContain(base.authorId);
+ expect(values).toContain(0.00975);
+ expect(values).toContain('settled');
+ expect(values).toContain('sig-abc');
+ expect(values).toContain('solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1');
+ expect(values).toContain('BuyerWallet111');
+ expect(values).toContain('x402');
+ expect(values).toContain(0.00025);
+ });
+
+ it('refuses to write without a skill or author', async () => {
+ expect((await accrueSkillCallRoyalty({ ...base, skillId: null, priceAtomics: 10_000n })).ok).toBe(false);
+ expect((await accrueSkillCallRoyalty({ ...base, authorId: null, priceAtomics: 10_000n })).ok).toBe(false);
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('skips a zero-price call without writing', async () => {
+ const out = await accrueSkillCallRoyalty({ ...base, priceAtomics: 0n });
+ expect(out.ok).toBe(false);
+ expect(out.reason).toBe('zero_price');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('never throws when the insert fails (fire-and-forget contract)', async () => {
+ sqlMock.mockRejectedValueOnce(new Error('neon down'));
+ const out = await accrueSkillCallRoyalty({ ...base, priceAtomics: 10_000n });
+ expect(out.ok).toBe(false);
+ expect(out.reason).toMatch(/neon down/);
+ });
+});
+
+describe('settle-royalties EVM flag gate (api/_lib/royalty.js)', () => {
+ afterEach(() => {
+ delete process.env.SKILL_ROYALTIES_EVM_7710_ENABLED;
+ vi.resetModules();
+ });
+
+ it('settleAllPendingRoyalties is a no-op while the flag is off', async () => {
+ delete process.env.SKILL_ROYALTIES_EVM_7710_ENABLED;
+ vi.resetModules();
+ sqlMock.mockClear();
+ const { settleAllPendingRoyalties } = await import('../api/_lib/royalty.js');
+ const report = await settleAllPendingRoyalties();
+ expect(report).toMatchObject({ settled: 0, failed: 0, authors: 0, skipped: true });
+ // No author lookup query ever runs while the leg is gated.
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('settleRoyalties skips an author while the flag is off', async () => {
+ process.env.SKILL_ROYALTIES_EVM_7710_ENABLED = 'false';
+ vi.resetModules();
+ sqlMock.mockClear();
+ const { settleRoyalties } = await import('../api/_lib/royalty.js');
+ const report = await settleRoyalties('22222222-2222-2222-2222-222222222222');
+ expect(report).toMatchObject({ skipped: true, reason: 'evm_7710_disabled' });
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+});