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.

fix(revenue): count direct-to-seller sales as settled, pay withdrawals only in the chain's USDC, and price creator cuts in USDC

nirholas7934d52ba077
diff --git a/api/_lib/migrations/20261008150000_revenue_direct_settle_backfill.sql b/api/_lib/migrations/20261008150000_revenue_direct_settle_backfill.sql
new file mode 100644
index 000000000..8d4662e15
--- /dev/null
+++ b/api/_lib/migrations/20261008150000_revenue_direct_settle_backfill.sql
@@ -0,0 +1,22 @@
+-- Migration: flag direct-to-seller sales as already settled to the seller's wallet.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261008150000_revenue_direct_settle_backfill.sql
+-- Idempotent.
+--
+-- Skill purchases (intent_id 'sp_<purchase id>'), bundle purchases
+-- ('bundle_<purchase id>') and agent x402 skill calls (intent_id = an
+-- agent_payment_intents id) all settle the buyer's payment straight into the
+-- seller's own payout wallet. Their revenue rows were written with
+-- settled_to_wallet = false, so the withdrawal ledger counted each sale as money
+-- the treasury owed the seller and the payout cron paid it a second time. The
+-- write paths now set the flag; this marks the rows written before that.
+-- Rows stay in place (they are real income for every earnings view); only
+-- their treasury-liability meaning changes.
+
+update agent_revenue_events re
+set settled_to_wallet = true
+where re.settled_to_wallet = false
+ and (
+ re.intent_id like 'sp\_%' escape '\'
+ or re.intent_id like 'bundle\_%' escape '\'
+ or exists (select 1 from agent_payment_intents pi where pi.id::text = re.intent_id)
+ );
diff --git a/api/_lib/purchase-confirm.js b/api/_lib/purchase-confirm.js
index edec3c2bf..16be73cdd 100644
--- a/api/_lib/purchase-confirm.js
+++ b/api/_lib/purchase-confirm.js
@@ -568,14 +568,18 @@ async function finalizeSkillConfirmation(pur, txSignature, payoutAddress, platfo
referralAmt = (grossAmt * BigInt(referralBps())) / 10000n;
}
const netAmt = grossAmt - platformFee - referralAmt;
+ // settled_to_wallet: the buyer paid the seller's payout wallet (or its
+ // split contract) directly, so the seller already holds this money. Left
+ // false, the withdrawal ledger counted it as a treasury liability and the
+ // payout cron paid it a second time from the treasury.
await sql`
INSERT INTO agent_revenue_events
(agent_id, intent_id, skill, gross_amount, fee_amount, platform_fee_amount,
- net_amount, currency_mint, chain, payer_address)
+ net_amount, currency_mint, chain, payer_address, settled_to_wallet)
VALUES
(${pur.agent_id}, ${intentId}, ${pur.skill},
${grossAmt.toString()}, ${referralAmt.toString()}, ${platformFee.toString()},
- ${netAmt.toString()}, ${pur.currency_mint}, ${pur.chain}, ${payoutAddress})
+ ${netAmt.toString()}, ${pur.currency_mint}, ${pur.chain}, ${payoutAddress}, true)
ON CONFLICT (intent_id) DO NOTHING
`;
diff --git a/api/agents/x402/[action].js b/api/agents/x402/[action].js
index b947b7451..f4da4b5ff 100644
--- a/api/agents/x402/[action].js
+++ b/api/agents/x402/[action].js
@@ -268,11 +268,13 @@ async function handleInvoke(req, res) {
// hard backstop against double-crediting.
const gross = parseInt(paid.amount, 10);
const { fee, net } = calculateFee(gross);
+ // settled_to_wallet: the intent paid the owner's payout wallet directly, so
+ // this is income already held, never a treasury-withdrawable balance.
await sql`
insert into agent_revenue_events
- (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount, currency_mint, chain, payer_address)
+ (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount, currency_mint, chain, payer_address, settled_to_wallet)
values
- (${agent.id}, ${paid.intentId}, ${body.skill}, ${gross}, ${fee}, ${net}, ${paid.currency}, ${price.chain ?? 'solana'}, ${paid.payerAddress})
+ (${agent.id}, ${paid.intentId}, ${body.skill}, ${gross}, ${fee}, ${net}, ${paid.currency}, ${price.chain ?? 'solana'}, ${paid.payerAddress}, true)
on conflict (intent_id) do nothing
`;
insertNotification(agent.user_id, 'payment_received', {
diff --git a/api/billing/withdrawals/index.js b/api/billing/withdrawals/index.js
index 80040d2fb..d25fad63a 100644
--- a/api/billing/withdrawals/index.js
+++ b/api/billing/withdrawals/index.js
@@ -9,6 +9,7 @@ import { parse, isValidSolanaAddress, isValidEvmAddress } from '../../_lib/valid
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { parseLimit, parseOffset } from '../../_lib/http-params.js';
import { requireCsrf } from '../../_lib/csrf.js';
+import { SOLANA_USDC_MINT, EVM_USDC } from '../../payments/_config.js';
// Note: the payout destination is intentionally NOT accepted from the client.
// It is resolved server-side from the user's saved `agent_payout_wallets` so a
@@ -87,6 +88,15 @@ export default wrap(async (req, res) => {
const body = parse(postBody, await readJson(req));
const { amount, currency_mint, chain, agent_id = null } = body;
+ // The treasury pays USDC on the requested chain, so the balance being drawn
+ // must be that chain's USDC. A free-form mint let a seller accrue revenue in
+ // a worthless token of their own and have the EVM payout leg (which always
+ // sends Base USDC) pay it out as real dollars.
+ const expectedMint = chain === 'solana' ? SOLANA_USDC_MINT : EVM_USDC[8453];
+ if (currency_mint.toLowerCase() !== expectedMint.toLowerCase()) {
+ return error(res, 422, 'unsupported_currency', `Withdrawals on ${chain} pay USDC; currency_mint must be ${expectedMint}`);
+ }
+
const MIN_WITHDRAWAL = 1_000_000;
if (amount < MIN_WITHDRAWAL) {
return error(res, 422, 'below_minimum', 'Minimum withdrawal is 1 USDC');
diff --git a/api/cron/[name].js b/api/cron/[name].js
index dc68e5e5c..166133f40 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -64,7 +64,7 @@ import { mintAttestation, deriveEventId, loadAttesterKeypair } from '../_lib/att
import { pumpfunMcp, pumpfunBotEnabled } from '../_lib/pumpfun-mcp.js';
import { getMints, getWhales, getClaims } from '../_lib/channel-feed-sources.js';
import { crawlAgentAttestations } from '../_lib/solana-attestations.js';
-import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';
+import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET, EVM_USDC } from '../payments/_config.js';
import { chargeSubscription, failPayment } from '../_lib/subscription-billing.js';
import { sendEmail } from '../_lib/email.js';
import { fetchSafePublicUrl } from '../_lib/ssrf-guard.js';
@@ -4419,8 +4419,17 @@ async function handleProcessWithdrawals(req, res) {
continue;
}
+ const EVM_USDC_BASE_LC = EVM_USDC[8453].toLowerCase();
try {
let sig;
+ // Pay only the chain's USDC against a USDC balance. The EVM leg always
+ // sends Base USDC, so a row carrying any other mint would turn a balance
+ // in a worthless token into real dollars.
+ const solUsdc = w.chain === 'solana' && w.currency_mint === SOLANA_USDC_MINT;
+ const evmUsdc = w.chain !== 'solana' && String(w.currency_mint || '').toLowerCase() === EVM_USDC_BASE_LC;
+ if (!solUsdc && !evmUsdc) {
+ throw new Error(`withdrawal mint ${w.currency_mint} is not USDC on ${w.chain}`);
+ }
if (w.chain === 'solana') {
if (!treasuryKeypair) {
throw new Error('TREASURY_KEYPAIR not configured for solana withdrawal');
diff --git a/api/marketplace/purchase-bundle.js b/api/marketplace/purchase-bundle.js
index 298569eab..9478f1196 100644
--- a/api/marketplace/purchase-bundle.js
+++ b/api/marketplace/purchase-bundle.js
@@ -227,14 +227,16 @@ async function handleConfirm(req, res, purchaseId) {
const gross = Number(purchase.price_amount);
const platformFee = Number(purchase.platform_fee_amount ?? 0);
const net = gross - platformFee;
+ // settled_to_wallet: the buyer paid the creator's payout wallet directly,
+ // so this is income already held, never a treasury-withdrawable balance.
await sql`
INSERT INTO agent_revenue_events
(agent_id, intent_id, skill, gross_amount, fee_amount, platform_fee_amount,
- net_amount, currency_mint, chain, payer_address)
+ net_amount, currency_mint, chain, payer_address, settled_to_wallet)
VALUES
(${purchase.agent_id}, ${'bundle_' + purchase.id}, ${'bundle'},
${gross}, ${0}, ${platformFee}, ${net},
- ${purchase.currency_mint}, ${purchase.chain}, ${null})
+ ${purchase.currency_mint}, ${purchase.chain}, ${null}, true)
ON CONFLICT (intent_id) DO NOTHING
`;
diff --git a/api/x402/cosmetic-purchase.js b/api/x402/cosmetic-purchase.js
index 09803c0c9..4a90aeb51 100644
--- a/api/x402/cosmetic-purchase.js
+++ b/api/x402/cosmetic-purchase.js
@@ -290,7 +290,11 @@ export default async function handler(req, res) {
payerWallet: payer ?? null,
payerNetwork: requirement?.network ?? null,
asset: requirement?.asset ?? null,
- priceAtomics: requirement?.amount ?? priceAtomics,
+ // The cut is a share of the item's USDC list price. requirement.amount
+ // is in the PAID asset's atomics: a 10 $THREE accept is 10,000,000,
+ // which the USDC payout read as $10 and paid half of to whoever
+ // launched the coin, on every purchase with a fresh account.
+ priceAtomics,
mint: coin,
});
if (result?.creatorWallet) {
diff --git a/tests/billing-endpoints.test.js b/tests/billing-endpoints.test.js
index f20b06057..ff582c144 100644
--- a/tests/billing-endpoints.test.js
+++ b/tests/billing-endpoints.test.js
@@ -325,7 +325,7 @@ describe('GET /api/billing/withdrawals', () => {
method: 'POST',
url: '/api/billing/withdrawals',
headers: { 'content-type': 'application/json' },
- body: { amount: 500000, currency_mint: 'THREEsynthetic1111', chain: 'solana' },
+ body: { amount: 500000, currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', chain: 'solana' },
}),
res,
);
@@ -333,6 +333,23 @@ describe('GET /api/billing/withdrawals', () => {
expect(parse(res).error).toBe('below_minimum');
});
+ it('refuses a mint that is not the chain\'s USDC, so a junk-token balance never pays out as dollars', async () => {
+ for (const [mint, chain] of [['THREEsynthetic1111', 'base'], ['THREEsynthetic1111', 'solana'], ['EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', 'base']]) {
+ const res = mkRes();
+ await withdrawalsHandler(
+ mkReq({
+ method: 'POST',
+ url: '/api/billing/withdrawals',
+ headers: { 'content-type': 'application/json' },
+ body: { amount: 2000000, currency_mint: mint, chain },
+ }),
+ res,
+ );
+ expect(res.statusCode).toBe(422);
+ expect(parse(res).error).toBe('unsupported_currency');
+ }
+ });
+
it('refuses to queue a payout when no wallet is registered for the chain', async () => {
queueSql([]);
const res = mkRes();
@@ -341,7 +358,7 @@ describe('GET /api/billing/withdrawals', () => {
method: 'POST',
url: '/api/billing/withdrawals',
headers: { 'content-type': 'application/json' },
- body: { amount: 2000000, currency_mint: 'THREEsynthetic1111', chain: 'solana' },
+ body: { amount: 2000000, currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', chain: 'solana' },
}),
res,
);
diff --git a/tests/cosmetics-purchase.test.js b/tests/cosmetics-purchase.test.js
index f1eb30e10..84ca35052 100644
--- a/tests/cosmetics-purchase.test.js
+++ b/tests/cosmetics-purchase.test.js
@@ -218,3 +218,14 @@ describe('cosmetic-purchase endpoint boundary', () => {
expect(sol.asset).toBe('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');
});
});
+
+describe('creator split basis', () => {
+ it('computes the creator cut from the USDC list price, never the paid asset amount', async () => {
+ const { readFileSync } = await import('node:fs');
+ const src = readFileSync(new URL('../api/x402/cosmetic-purchase.js', import.meta.url), 'utf8');
+ // A $THREE accept carries 10,000,000 atomics; read as USDC that paid the coin
+ // creator $5 per purchase out of the treasury.
+ expect(src).not.toMatch(/priceAtomics:\s*requirement\?\.amount/);
+ expect(src).toMatch(/recordSaleAndSplit\(\{[\s\S]*?\n\s*priceAtomics,\n/);
+ });
+});
diff --git a/tests/revenue-direct-settle.test.js b/tests/revenue-direct-settle.test.js
new file mode 100644
index 000000000..3efa76cb6
--- /dev/null
+++ b/tests/revenue-direct-settle.test.js
@@ -0,0 +1,38 @@
+// A sale the buyer paid straight into the seller's own wallet is never a
+// treasury liability.
+//
+// agent_revenue_events doubles as the withdrawal ledger: every row with
+// settled_to_wallet = false is money the treasury owes the seller. Skill
+// purchases, bundle purchases and agent x402 skill calls all settle into the
+// seller's payout wallet, yet wrote their rows with the default false, so a
+// seller could buy their own skill from a second account (losing nothing) and
+// withdraw the price again from the treasury, as often as they liked.
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const read = (rel) => readFileSync(new URL(`../${rel}`, import.meta.url), 'utf8');
+
+function revenueInserts(src) {
+ return src.match(/insert into agent_revenue_events[\s\S]*?on conflict/gi) || [];
+}
+
+describe('direct-to-seller revenue rows are flagged settled_to_wallet', () => {
+ for (const rel of ['api/_lib/purchase-confirm.js', 'api/marketplace/purchase-bundle.js', 'api/agents/x402/[action].js']) {
+ it(rel, () => {
+ const inserts = revenueInserts(read(rel));
+ expect(inserts.length).toBeGreaterThan(0);
+ for (const ins of inserts) {
+ expect(ins).toMatch(/settled_to_wallet\)/);
+ expect(ins).toMatch(/,\s*true\)\s*\n\s*on conflict/i);
+ }
+ });
+ }
+
+ it('ships a backfill for rows written before the fix', () => {
+ const sql = read('api/_lib/migrations/20261008150000_revenue_direct_settle_backfill.sql');
+ expect(sql).toMatch(/set settled_to_wallet = true/);
+ expect(sql).toMatch(/'sp\\_%'/);
+ expect(sql).toMatch(/'bundle\\_%'/);
+ });
+});