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
fix(monetization): reject an unpayable price and report the wallet a payout would use
nirholasb75da7737870
diff --git a/api/monetization/prices.js b/api/monetization/prices.jsindex c4edb8964..a865a2026 100644--- a/api/monetization/prices.js+++ b/api/monetization/prices.js@@ -17,6 +17,11 @@ const SKILL_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;const SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;// USDC has 6 decimals. 0.000001 USDC = 1 atomic unit.const MIN_PRICE_ATOMIC = 1;+// Ceiling on a single skill price. Without it an absurd `price_usdc` (1e30, or+// Infinity, which z.number() accepts on its own) is multiplied to atomic units+// and overflows the bigint `amount` column, so Postgres rejects the INSERT and+// the caller gets a 500 where a 400 is the truthful answer.+const MAX_PRICE_USDC = 1_000_000;const putBody = z.object({@@ -24,7 +29,7 @@ const putBody = zskill_name: z.string().trim().min(1).max(64).regex(SKILL_RE, 'skill_name must be alphanumeric with hyphens/underscores, max 64 chars'),// Required for a price gate; ignored for an NFT gate (access is the holding,// not a payment), so optional here and refined below.- price_usdc: z.number().positive().optional(),+ price_usdc: z.number().finite().positive().max(MAX_PRICE_USDC, `price_usdc must be at most ${MAX_PRICE_USDC}`).optional(),currency_mint: z.string().trim().min(1).max(100).default('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),chain: z.enum(['solana', 'base', 'evm']).default('solana'),// Access gate: 'price' (default) sells the skill; 'nft' restricts it todiff --git a/api/monetization/revenue.js b/api/monetization/revenue.jsindex 53f94398b..20d286550 100644--- a/api/monetization/revenue.js+++ b/api/monetization/revenue.js@@ -12,11 +12,13 @@ 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';-const PERIOD_TO_INTERVAL = {- '1d': '1 day',- '7d': '7 days',- '30d': '30 days',- '90d': '90 days',+// 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,};@@ -56,15 +58,14 @@ export default wrap(async (req, res) => {}const period = params.get('period') || '7d';- if (!PERIOD_TO_INTERVAL.hasOwnProperty(period)) {- return error(res, 400, 'validation_error', 'period must be one of: 1d, 7d, 30d, 90d, all');+ 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 interval = PERIOD_TO_INTERVAL[period];+ const windowMs = PERIOD_TO_MS[period];const now = new Date();- const fromDate = interval- ? new Date(now.getTime() - parseIntervalMs(interval))- : new Date('2020-01-01');+ // `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@@ -142,11 +143,3 @@ export default wrap(async (req, res) => {})),});});--function parseIntervalMs(interval) {- const m = /^(\d+)\s*(day|days|hour|hours)$/.exec(interval);- if (!m) return 7 * 86400e3;- const n = parseInt(m[1], 10);- const unit = m[2].startsWith('hour') ? 3600e3 : 86400e3;- return n * unit;-}diff --git a/api/monetization/wallet.js b/api/monetization/wallet.jsindex 3ad5c335d..43e64af00 100644--- a/api/monetization/wallet.js+++ b/api/monetization/wallet.js@@ -70,15 +70,15 @@ export default wrap(async (req, res) => {ORDER BY agent_id NULLS LAST, is_default DESC, created_at DESC`;- // Also build a summary view: resolve which addresses would be used for each chain- const evmWallet = wallets.find(- (w) =>- (w.chain === 'base' || w.chain === 'evm') &&- (agentId ? w.agent_id === agentId : true),- );- const solanaWallet = wallets.find(- (w) => w.chain === 'solana' && (agentId ? w.agent_id === agentId : true),- );+ // Summary view: which address a payout would actually land on per chain.+ // This must mirror the payout-wallet resolution in withdrawals.js, where an+ // agent-specific row wins and a user-level row (agent_id IS NULL) is the+ // fallback. The ORDER BY above already puts agent rows ahead of user-level+ // ones, so the first match per chain is the row that would be paid; matching+ // on agent_id alone would report "no wallet" for an agent that inherits one.+ const resolveWallet = (chains) => wallets.find((w) => chains.includes(w.chain));+ const evmWallet = resolveWallet(['base', 'evm']);+ const solanaWallet = resolveWallet(['solana']);return json(res, 200, {wallets,@@ -141,8 +141,7 @@ export default wrap(async (req, res) => {await sql`UPDATE agent_payout_walletsSET is_default = false- WHERE user_id = ${userId} AND chain = 'solana'- AND (agent_id = ${agent_id} OR (agent_id IS NULL AND ${agent_id}::uuid IS NULL))+ WHERE user_id = ${userId} AND chain = 'solana' AND agent_id = ${agent_id}`;const [wallet] = await sql`@@ -164,8 +163,7 @@ export default wrap(async (req, res) => {await sql`UPDATE agent_payout_walletsSET is_default = false- WHERE user_id = ${userId} AND chain = 'base'- AND (agent_id = ${agent_id} OR (agent_id IS NULL AND ${agent_id}::uuid IS NULL))+ WHERE user_id = ${userId} AND chain = 'base' AND agent_id = ${agent_id}`;const [wallet] = await sql`diff --git a/api/monetization/withdrawals.js b/api/monetization/withdrawals.jsindex 3ca6763c9..3068f1974 100644--- a/api/monetization/withdrawals.js+++ b/api/monetization/withdrawals.js@@ -8,17 +8,23 @@ import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';-import { parse, isValidSolanaAddress, isValidEvmAddress, isUuid } from '../_lib/validate.js';+import { parse, isUuid } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';+import { parseLimit, parseOffset } from '../_lib/http-params.js';import { requireCsrf } from '../_lib/csrf.js';import { getAvailableBalance } from '../_lib/monetization.js';const MIN_WITHDRAWAL_USDC = 1; // 1 USDC minimumconst MIN_WITHDRAWAL_ATOMIC = MIN_WITHDRAWAL_USDC * 1_000_000;+// The lifecycle the payout cron (api/cron/[name].js) actually writes. Anything+// else in `?status=` is a caller typo, and answering it with an empty page+// reads as "you have no withdrawals" instead of "that filter is not a status".+const WITHDRAWAL_STATUSES = ['pending', 'processing', 'completed', 'failed'];+const postBody = z.object({agent_id: z.string().uuid(),- amount_usdc: z.number().positive().nullable().optional(),+ amount_usdc: z.number().finite().positive().nullable().optional(),});async function resolveUser(req) {@@ -44,13 +50,19 @@ export default wrap(async (req, res) => {const params = new URL(req.url, 'http://x').searchParams;const agentId = params.get('agent_id') || null;const statusFilter = params.get('status') || null;- const limit = Math.min(100, Math.max(1, parseInt(params.get('limit') || '20', 10)));- const offset = Math.max(0, parseInt(params.get('offset') || '0', 10));+ // clampInt-backed so `?limit=abc` falls back to the default page instead of+ // binding NaN, which reaches Postgres as NULL and silently removes the LIMIT.+ const limit = parseLimit(params, { fallback: 20, max: 100 });+ const offset = parseOffset(params);if (agentId && !isUuid(agentId)) {return error(res, 400, 'validation_error', 'agent_id must be a UUID');}+ if (statusFilter && !WITHDRAWAL_STATUSES.includes(statusFilter)) {+ return error(res, 400, 'validation_error', `status must be one of: ${WITHDRAWAL_STATUSES.join(', ')}`);+ }+// Verify agent ownership if specifiedif (agentId) {const [agent] = await sql`diff --git a/scripts/monetization-api-proof.mjs b/scripts/monetization-api-proof.mjsindex 9b5009eb8..74070d0c0 100644--- a/scripts/monetization-api-proof.mjs+++ b/scripts/monetization-api-proof.mjs@@ -73,6 +73,11 @@ function check(name, cond, detail) {return !!cond;}+// Everything the server process wrote. Kept at module scope so a fatal abort+// can print it: a handler 500 is opaque from the HTTP side (wrap() answers with+// an error ref only), and the matching stack is in here.+const serverLog = [];+// process helpersconst cleanup = [];async function shutdown() {@@ -319,7 +324,6 @@ async function main() {stdio: ['ignore', 'pipe', 'pipe'],});if (!KEEP) cleanup.push(() => server.kill('SIGKILL'));- const serverLog = [];server.stdout.on('data', (d) => serverLog.push(String(d)));server.stderr.on('data', (d) => serverLog.push(String(d)));await waitFor(async () => (await fetch(`${HTTP_BASE}/api/version`)).ok, { label: 'local server' });@@ -687,6 +691,8 @@ main()}).catch(async (err) => {console.error(`\nFATAL: ${err?.stack || err}`);+ const tail = serverLog.join('').split('\n').slice(-40).join('\n').trim();+ if (tail) console.error(`\nserver log (last 40 lines):\n${tail}`);if (!KEEP) await shutdown();process.exit(1);});