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
style(comments): replace banned dashes in the comments this batch touched
nirholas4cee4745cf74
diff --git a/api/_lib/referrals.js b/api/_lib/referrals.jsindex ac1ddec11..3ca3e0e36 100644--- a/api/_lib/referrals.js+++ b/api/_lib/referrals.js@@ -32,7 +32,7 @@ export function generateReferralCode(length = 8) {export const REFERRAL_CODE_MIN_LEN = 3;export const REFERRAL_CODE_MAX_LEN = 20;-// The canonical, storable shape of a referral code: A–Z and 0–9 only. Vanity+// The canonical, storable shape of a referral code: A-Z and 0-9 only. Vanity// codes accept the full alphanumeric range; the generator stays restricted so// auto-minted codes remain easy to read aloud off a membership card.export const REFERRAL_CODE_RE = new RegExp(`^[A-Z0-9]{${REFERRAL_CODE_MIN_LEN},${REFERRAL_CODE_MAX_LEN}}$`);@@ -50,7 +50,7 @@ const RESERVED_REFERRAL_CODES = new Set([/*** Normalize arbitrary user input to a canonical referral code, or null if it- * can't be one. Trims, uppercases, and validates against the canonical shape —+ * can't be one. Trims, uppercases, and validates against the canonical shape :* it never strips invalid characters (so "my-code" is rejected, not silently* mangled into "MYCODE"); callers surface the rejection to the user.*@@ -71,7 +71,7 @@ export function isReservedReferralCode(code) {/*** Derive a canonical referral code candidate from a person's name. Strips* everything but letters and digits, uppercases, and clamps to the max length.- * Returns null if nothing usable (≥ MIN_LEN chars) remains — e.g. a name that's+ * Returns null if nothing usable (≥ MIN_LEN chars) remains: e.g. a name that's* all punctuation or an emoji.** @param {string|null|undefined} name@@ -90,7 +90,7 @@ export function slugifyReferralName(name) {* Ordered candidate codes for a new account: the user's name first (so the* default referral code reads like them), then the name plus a short random* suffix to ride out collisions while staying recognizable, then pure random- * fallbacks. Finite — callers loop until an insert/update succeeds.+ * fallbacks. Finite: callers loop until an insert/update succeeds.** @param {string|null} name display name or username to seed the default* @returns {Generator<string>}@@ -203,7 +203,7 @@ export async function setReferralCode(userId, desired) {// Every user is a potential referrer, but only the email + SAML signup paths// mint a `referral_code` up front. Privy / SIWS / SIWE sign-ups (and any// pre-existing account) land with a NULL code. This lazily assigns one the-// first time the user needs it — idempotent and race-safe via the UNIQUE+// first time the user needs it: idempotent and race-safe via the UNIQUE// constraint + `WHERE referral_code IS NULL` guard.//// @param {string|number} userId@@ -213,7 +213,7 @@ export async function ensureReferralCode(userId) {if (existing?.referral_code) return existing.referral_code;// Default the code to the member's name (then name+suffix, then random) so the- // first code they ever see reads like them — they can customize it later.+ // first code they ever see reads like them: they can customize it later.for (const code of referralCodeCandidates(existing?.display_name || existing?.username)) {try {const [row] = await sql`@@ -222,7 +222,7 @@ export async function ensureReferralCode(userId) {RETURNING referral_code`;if (row?.referral_code) return row.referral_code;- // A concurrent request assigned one first — read it back.+ // A concurrent request assigned one first: read it back.const [now] = await sql`SELECT referral_code FROM users WHERE id = ${userId}`;if (now?.referral_code) return now.referral_code;} catch (err) {@@ -246,7 +246,7 @@ export async function ensureReferralCode(userId) {* unit getMembershipCard / getReferredUsers read back.** The DB credit is awaited (it's part of recording the sale); the email is- * strictly best-effort — a send failure (or missing RESEND_API_KEY) is logged,+ * strictly best-effort: a send failure (or missing RESEND_API_KEY) is logged,* never thrown, so it can never roll back or block the commission credit.** @param {object} args@@ -340,14 +340,14 @@ function clampOffset(offset) {* commission the referrer earned on it.** Revenue is the sum of every CONFIRMED purchase a referred user made where this- * user was the attributed referrer — across both monetization tables:+ * user was the attributed referrer: across both monetization tables:* • skill_purchases (referrer_user_id, user_id, amount, status)* • asset_purchases (referrer_user_id, buyer_user_id, amount, status)* Amounts are atomic USDC units (6 decimals), the same unit purchase-confirm.js* accrues into users.referral_earnings_total. Commission is derived from the* configured referral BPS so the column matches what was actually credited.*- * Sorted by revenue generated (desc), then most recent signup — the most+ * Sorted by revenue generated (desc), then most recent signup: the most* valuable referrals surface first. Paginated via limit/offset.** @param {string|number} userId the referrer@@ -373,7 +373,7 @@ export async function getReferredUsers(userId, opts = {}) {// Per-referred-user revenue, summed from both purchase tables. Each subquery// is correlated on the referred user's id AND keyed to this referrer so a// buyer's spend only counts toward the referrer who actually owns it. Only- // confirmed sales count — pending/expired/failed rows are excluded.+ // confirmed sales count: pending/expired/failed rows are excluded.const rows = await sql`SELECTru.id,@@ -445,11 +445,11 @@ function pct(numerator, denominator) {* activations, plus the two conversion rates between them.** Each stage is counted from the event that actually happened, in its own time:- * • visits — rows POST /api/referral/visit wrote into referral_visits,+ * • visits : rows POST /api/referral/visit wrote into referral_visits,* already deduped to one per (code, visitor, UTC day).- * • signups — accounts attributed to this referrer that were created in+ * • signups : accounts attributed to this referrer that were created in* the window.- * • activations — referred users who reached their first win in the window,+ * • activations: referred users who reached their first win in the window,* counted from the referred-side activation grant in* credit_ledger. Counting the referred side (not the* referrer's own grant) keeps the number honest when the@@ -509,7 +509,7 @@ export async function getReferralFunnel(userId, opts = {}) {* referral code + count, lifetime referral earnings, and a derived score.** `position` is the account's 1-based signup ordinal ("member #N"), a real,- * monotonic number — not a synthetic rank. `score` is derived purely from+ * monotonic number: not a synthetic rank. `score` is derived purely from* real referral activity so it can never drift from the underlying ledger.** @param {string|number} userId@@ -535,7 +535,7 @@ export async function getMembershipCard(userId) {AND deleted_at IS NULL`;// Platform-wide member count: a full-table COUNT(*) that is identical for- // every viewer and grows monotonically — cache for 60s instead of scanning+ // every viewer and grows monotonically: cache for 60s instead of scanning// users on every member-card render.const total = await cacheWrap('users:total:active', 60, async () => {const [{ total }] = await sql`@@ -552,7 +552,7 @@ export async function getMembershipCard(userId) {// Activation-reward credits: the two-sided "first win" bonus, paid as platform// credits (api/_lib/referral-rewards.js). Summed live from the credit ledger so- // the card reflects the full referral payoff — purchase commission AND the+ // the card reflects the full referral payoff: purchase commission AND the// activation credits both sides earn.const [rewardRow] = await sql`SELECT COALESCE(SUM(amount_usd), 0)::float AS reward_usd, COUNT(*)::int AS reward_countdiff --git a/api/notifications/index.js b/api/notifications/index.jsindex 0dcbe6885..4fde29fb0 100644--- a/api/notifications/index.js+++ b/api/notifications/index.js@@ -1,4 +1,4 @@-// GET /api/notifications — list recent notifications for the authenticated user.+// GET /api/notifications: list recent notifications for the authenticated user.import { sql } from '../_lib/db.js';import { getRequestUser } from '../_lib/auth.js';@@ -16,7 +16,7 @@ export default wrap(async (req, res) => {if (!rl.success) return rateLimited(res, rl);const params = new URL(req.url, 'http://x').searchParams;- // A non-numeric ?limit parses to NaN, and NaN survives both clamps — it then+ // A non-numeric ?limit parses to NaN, and NaN survives both clamps: it then// reached Postgres as `limit NaN` and 500'd the whole list. Fall back to the// default instead, so a junk value degrades to the normal page.const limitRaw = Number.parseInt(params.get('limit') || '20', 10);@@ -27,7 +27,7 @@ export default wrap(async (req, res) => {const type = /^[a-z0-9_]{1,40}$/.test(typeRaw) ? typeRaw : null;// Optional cursor for "load more" on the full notification-center page// (pages/notifications.html): pass the last row's created_at to page past it.- // The bell dropdown never sends this — it only ever wants the latest page.+ // The bell dropdown never sends this: it only ever wants the latest page.const beforeRaw = params.get('before');const before = beforeRaw && !Number.isNaN(Date.parse(beforeRaw)) ? new Date(beforeRaw) : null;diff --git a/api/onramp/link.js b/api/onramp/link.jsindex 5b599f7ab..9acfca2f9 100644--- a/api/onramp/link.js+++ b/api/onramp/link.js@@ -10,7 +10,7 @@// wallet, for one), and sending them USDC would never make them spendable.//// Requires:-// CDP_API_KEY_ID + CDP_API_KEY_SECRET (optional) — the Coinbase Developer+// CDP_API_KEY_ID + CDP_API_KEY_SECRET (optional): the Coinbase Developer// Platform key pair, already used by the x402// facilitator. When set, each call mints a single-use// Onramp session token bound to the user's Solana@@ -20,7 +20,7 @@// the user sends to the address the overlay shows them.//// The address param is NOT a secret (it's a Solana public key) and is only-// used as the deposit destination — it is safe to pass in a query string.+// used as the deposit destination: it is safe to pass in a query string.import { cors, json, error, rateLimited, reportServerError, wrap } from '../_lib/http.js';import { isValidSolanaAddress } from '../_lib/validate.js';diff --git a/api/pump/helius-stats.js b/api/pump/helius-stats.jsindex 4a5874336..e0776360f 100644--- a/api/pump/helius-stats.js+++ b/api/pump/helius-stats.js@@ -35,7 +35,7 @@ export function resolveProbeTarget(env = process.env) {const apiKey = env.HELIUS_API_KEY || '';const configured = env.SOLANA_RPC_URL || '';if (configured && isHeliusUrl(configured)) return { url: configured, endpoint: 'helius-rpc' };- // A Helius key with a non-Helius SOLANA_RPC_URL still means we HAVE Helius —+ // A Helius key with a non-Helius SOLANA_RPC_URL still means we HAVE Helius :// probe Helius itself rather than mislabeling the other provider.if (apiKey) return { url: `https://mainnet.helius-rpc.com/?api-key=${apiKey}`, endpoint: 'helius-rpc' };return { url: '', endpoint: null };diff --git a/api/pump/intel.js b/api/pump/intel.jsindex 85eb4dac5..3a7487350 100644--- a/api/pump/intel.js+++ b/api/pump/intel.js@@ -6,7 +6,7 @@// signals + a 0..100 quality score, and labels outcomes after the fact. It WRITES// pump_coin_intel / pump_coin_wallets / pump_coin_outcomes / pump_intel_weights.// This endpoint READS them for the /coin-intel dashboard and any agent that wants-// the same intelligence the sniper trades on — nothing here writes.+// the same intelligence the sniper trades on: nothing here writes.//// Views (query param `view`, default `feed`):// ?mint=<mint> one coin: classification + signals + outcome + top wallets (bubble-map)@@ -14,7 +14,7 @@// ?view=leaderboard highest-quality recent coins + confirmed winners (graduated/pumped)// ?view=learning learned per-signal weights + outcome distribution (what the model learned)//-// Public, cacheable briefly. No auth — this is read-only market intelligence.+// Public, cacheable briefly. No auth: this is read-only market intelligence.// Degrades gracefully (200 with degraded:true) if the engine tables don't exist// yet, so the dashboard can render its "engine warming up" state instead of 500ing.@@ -42,7 +42,7 @@ const round = (x, p = 4) => {// Human verdict derived from the transparent quality score + hard risk flags.// Hard flags (a coordinated launch, a dev dump, a single whale owning the float)-// force "avoid" regardless of score — those are the ones that lose money.+// force "avoid" regardless of score: those are the ones that lose money.const HARD_FLAGS = ['bundle_launch', 'dev_dumped', 'single_whale'];function deriveVerdict(qualityScore, riskFlags) {const flags = Array.isArray(riskFlags) ? riskFlags : [];@@ -55,14 +55,14 @@ function deriveVerdict(qualityScore, riskFlags) {}// Classify one trader within a single coin's order book / holder list, from its-// footprint on that coin. Labels stack — a wallet can be both a sniper and a whale.-// creator — the coin's deployer-// bundled — shares a SOL funder with ≥1 other buyer (coordinated launch wallet)-// sniper — first trade landed within seconds of the coin appearing-// whale — captured a large share of buy volume-// dumped — sold ~all of what it bought (paper hands / exit)-// holding — bought and never sold (diamond)-// flipped — bought and partially sold+// footprint on that coin. Labels stack: a wallet can be both a sniper and a whale.+// creator : the coin's deployer+// bundled : shares a SOL funder with ≥1 other buyer (coordinated launch wallet)+// sniper : first trade landed within seconds of the coin appearing+// whale : captured a large share of buy volume+// dumped : sold ~all of what it bought (paper hands / exit)+// holding : bought and never sold (diamond)+// flipped : bought and partially soldfunction classifyWalletInCoin(w, { coinSeenMs, bundledClusters }) {const labels = [];if (w.is_creator) labels.push('creator');@@ -100,7 +100,7 @@ function shapeCoin(r) {website: r.website || null,has_socials: !!(r.twitter || r.telegram || r.website),- // classification — the "what kind of coin is this" answer+ // classification: the "what kind of coin is this" answercategory: r.category || 'unknown',tags,narrative: r.narrative || null,@@ -146,7 +146,7 @@ function shapeCoin(r) {};}-// Stable column projection — explicit so added engine columns never break us and+// Stable column projection: explicit so added engine columns never break us and// missing ones surface as a clean error we can degrade on.// Plain string (not a sql fragment) so this module can load without DATABASE_URL.const COIN_COLS =@@ -175,7 +175,7 @@ async function getCoin(mint, network) {const coin = shapeCoin(row);- // Outcome (labeled after the fact — may not exist yet).+ // Outcome (labeled after the fact: may not exist yet).let outcome = null;try {const [o] = await sql`@@ -301,10 +301,10 @@ async function getLeaderboard({ network, limit }) {// Aggregates the per-coin wallet ledger into a cross-coin reputation per trader,// then labels it. win_rate is real: of the coins this wallet bought, the share// that graduated or pumped (only counted once ≥3 of its coins are labeled).-// smart_money — proven win-rate across enough labeled coins-// whale — large lifetime buy volume-// serial — trades a high number of distinct coins-// creator — has deployed at least one observed coin+// smart_money: proven win-rate across enough labeled coins+// whale : large lifetime buy volume+// serial : trades a high number of distinct coins+// creator : has deployed at least one observed coinasync function getTraders({ network, limit }) {const cap = Math.max(1, Math.min(100, limit || 40));let traders = [];@@ -432,7 +432,7 @@ export default wrap(async (req, res) => {// Caller mistakes are answered as caller mistakes. Everything below this point// reaching the `degraded` boundary means the ENGINE is down, which is what the- // dashboard's "warming up" state is for — a typo must never be reported as an+ // dashboard's "warming up" state is for: a typo must never be reported as an// outage, and an unknown view must never be silently served as the feed.if (mint && !MINT_RE.test(mint)) {return error(res, 400, 'invalid_mint', 'mint must be a base58 pump.fun address');diff --git a/api/users/referrals.js b/api/users/referrals.jsindex 58859ee1d..1bbb5e729 100644--- a/api/users/referrals.js+++ b/api/users/referrals.js@@ -3,15 +3,15 @@ import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { getMembershipCard, getReferredUsers, getReferralFunnel } from '../_lib/referrals.js';-// GET /api/users/referrals — the signed-in user's membership card payload:+// GET /api/users/referrals: the signed-in user's membership card payload:// referral code (lazily minted if absent), referral count + lifetime earnings,// signup position ("member #N"), and a derived score. Also returns a real,// paginated per-referred-user breakdown (who signed up, when, revenue they// generated, and the commission earned) so the affiliate dashboard can show an-// actionable referral table — not just a counter. Powers /dashboard/referrals.+// actionable referral table: not just a counter. Powers /dashboard/referrals.//-// Query params (optional): ?limit (1–100, default 20) & ?offset (>=0) page the-// referred-user list, sorted by revenue generated (desc). ?funnel_days (1–365,+// Query params (optional): ?limit (1-100, default 20) & ?offset (>=0) page the+// referred-user list, sorted by revenue generated (desc). ?funnel_days (1-365,// default 30) sets the lookback for the `funnel` block, which reports the// visit → signup → activation conversion recorded by POST /api/referral/visit.export default wrap(async (req, res) => {diff --git a/src/dashboard-next/pages/referrals.js b/src/dashboard-next/pages/referrals.jsindex 9911932dd..d4e7cbdfd 100644--- a/src/dashboard-next/pages/referrals.js+++ b/src/dashboard-next/pages/referrals.js@@ -1,9 +1,9 @@-// dashboard-next — Referrals.+// dashboard-next: Referrals.//// A 3D, flippable membership card (the centrepiece) plus the referral link,// share actions, and live referral stats. Front shows the member's standing;// back shows a scannable QR for the referral link. Every number is real,-// pulled from /api/users/referrals — no placeholders.+// pulled from /api/users/referrals: no placeholders.import { mountShell } from '../shell.js';import { requireUser, get, put, esc } from '../api.js';@@ -12,7 +12,7 @@ import { toast } from '../../shared/toast.js';const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;-// Canonical referral-code shape — mirrors REFERRAL_CODE_RE in+// Canonical referral-code shape: mirrors REFERRAL_CODE_RE in// api/_lib/referrals.js. The server is authoritative; this gates the editor's// Save button and pre-filters obviously-invalid input before the availability// check fires.@@ -107,7 +107,7 @@ function funnelPanel(funnel) {`;}-/** "06/27" — two years out, the card's notional validity. */+/** "06/27": two years out, the card's notional validity. */function expLabel(memberSince) {const base = memberSince ? new Date(memberSince) : new Date();const exp = new Date(base.getTime());@@ -124,7 +124,7 @@ function memberSinceLabel(memberSince) {return d.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });}-/** "Jun 21, 2026" — full signup date for the referrals table. */+/** "Jun 21, 2026": full signup date for the referrals table. */function fmtDate(value) {if (!value) return '—';const d = new Date(value);@@ -452,7 +452,7 @@ const ICONS = {share: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="15" cy="5" r="2.2"/><circle cx="5" cy="10" r="2.2"/><circle cx="15" cy="15" r="2.2"/><path d="M6.9 8.9l6.2-3M6.9 11.1l6.2 3"/></svg>',};-// ── PNG export — draw the front face to a canvas for a shareable image ────────+// ── PNG export: draw the front face to a canvas for a shareable image ────────function exportCardPNG(card, refUrl) {const W = 1100, H = Math.round(W / 1.74), P = 56;@@ -630,7 +630,7 @@ function wireCard(host, card, refUrl) {apply();};flipBtn.addEventListener('click', flip);- // Tapping the card flips it too — but not when the user is dragging to tilt.+ // Tapping the card flips it too: but not when the user is dragging to tilt.cardEl.addEventListener('click', (e) => {if (cardEl._dragged) { cardEl._dragged = false; return; }if (e.target.closest('a')) return;@@ -794,7 +794,7 @@ function wireCodeEditor(host, card) {const cleaned = input.value.replace(/[^A-Za-z0-9]/g, '').toUpperCase().slice(0, CODE_MAX);if (cleaned !== input.value) {input.value = cleaned;- // Place cursor at end of cleaned value — multi-char strips (e.g.+ // Place cursor at end of cleaned value: multi-char strips (e.g.// paste of "my-code!") may remove more than one character, making// caret - 1 wrong. End-of-field is always safe and expected.input.setSelectionRange(cleaned.length, cleaned.length);@@ -845,7 +845,7 @@ function wireCodeEditor(host, card) {// Every member wears a "mode": user, beta, pro, holder, or three-dimensional.// The card shows the highest one as a pill; this panel shows the full ladder,// which badges you already hold, and what unlocks the rest. Data is real, from-// /api/users/me/tier — holder status is read live from your on-chain $THREE.+// /api/users/me/tier: holder status is read live from your on-chain $THREE.// Where a locked mode is earned, and where to go to get there. Derived modes// link to the surface that unlocks them; granted modes are invite-only.@@ -1086,7 +1086,7 @@ function mountReferralsList(host, refUrl, seed) {if (copyBtn) copyBtn.addEventListener('click', () => copyToClipboard(refUrl));return;}- // Past the last page (e.g. data shrank) — step back.+ // Past the last page (e.g. data shrank): step back.if (state.offset > 0) { go(Math.max(0, state.offset - state.limit)); return; }}diff --git a/tests/api/pump.test.js b/tests/api/pump.test.jsindex 7a61409c0..36aec3568 100644--- a/tests/api/pump.test.js+++ b/tests/api/pump.test.js@@ -1,5 +1,5 @@// Tests for pump.fun integration endpoints. SDKs and Solana RPC are fully-// mocked — no network, no chain. Verifies request/response shapes, auth,+// mocked: no network, no chain. Verifies request/response shapes, auth,// validation, and that the right SDK calls are issued in the right order.import { describe, it, expect, beforeEach, vi } from 'vitest';@@ -32,7 +32,7 @@ vi.mock('../../api/_lib/db.js', () => ({// Any bucket resolves to "allowed". The handlers under test move between buckets// as page-load reads get isolated from write paths (authIp → authedReadIp → …);// enumerating names here just means a silent 500 ("limits.<name> is not a-// function") the next time one is renamed — which is exactly what this mock did.+// function") the next time one is renamed: which is exactly what this mock did.vi.mock('../../api/_lib/rate-limit.js', () => ({limits: new Proxy({}, { get: () => vi.fn(async () => ({ success: true })) }),clientIp: vi.fn(() => '127.0.0.1'),@@ -170,8 +170,8 @@ async function resetPumpMod() {const mintB58 = 'MintPubkey1111111111111111111111111111';const walletB58 = 'WalletPubkey111111111111111111111111111';const ataB58 = 'AtaPubkey1111111111111111111111111111111';-// Long enough to clear the schema's 32-char floor, but not decodable as base58 —-// the shape that used to slip past pubkey validation.+// Long enough to clear the schema's 32-char floor, but not decodable as base58.+// This is the shape that used to slip past pubkey validation.const badPubkey = '0OIl0OIl0OIl0OIl0OIl0OIl0OIl0OIl0OIl';describe('GET /api/pump/balances', () => {@@ -375,7 +375,7 @@ describe('POST /api/pump/buy-confirm (quote-aware trade recording)', () => {expect(v[5]).toBe(USDC_MINT); // quote_mintexpect(v[6]).toBe('USDC'); // quote_symbolexpect(v[7]).toBe('5000000'); // quote_amount = 5 USDC in 6-dec atoms- // sol_amount stays null for a USDC trade — never lands in the lamports column.+ // sol_amount stays null for a USDC trade: never lands in the lamports column.expect(v[4]).toBeNull();});diff --git a/tests/api/purchase-skill-tx-request.test.js b/tests/api/purchase-skill-tx-request.test.jsindex 0419eeef6..66e8b9277 100644--- a/tests/api/purchase-skill-tx-request.test.js+++ b/tests/api/purchase-skill-tx-request.test.js@@ -1,10 +1,10 @@-// Tests for /api/purchase/skill — the Solana Pay TRANSACTION request that a+// Tests for /api/purchase/skill: the Solana Pay TRANSACTION request that a// mobile wallet hits after scanning a skill-purchase QR.//// Runs fully offline: real @solana/web3.js + @solana/spl-token, a fake RPC that// returns a fixed blockhash, and an in-memory skill_purchases row. The two things-// that matter here are (a) the endpoint never invents a purchase — it only serves-// a pending row an authenticated checkout already created — and (b) the built+// that matter here are (a) the endpoint never invents a purchase, it only serves+// a pending row an authenticated checkout already created, and (b) the built// transaction has the exact shape api/_lib/purchase-confirm.js validates: the// reference-carrying creator leg LAST.diff --git a/tests/monetization-service.test.js b/tests/monetization-service.test.jsindex 43701fbc5..0157d93d4 100644--- a/tests/monetization-service.test.js+++ b/tests/monetization-service.test.js@@ -3,16 +3,16 @@// The financial core of monetization lives in three places, none of which had// direct coverage before this suite://-// • api/_lib/fee.js — platform fee split (calculateFee, getFeeBps)-// • api/_lib/monetization.js — recordRevenueEvent (revenue attribution ++// • api/_lib/fee.js : platform fee split (calculateFee, getFeeBps)+// • api/_lib/monetization.js: recordRevenueEvent (revenue attribution +// fee/net split) and getAvailableBalance// (withdrawable-balance aggregation)-// • api/monetization/*.js — the unified REST surface: prices.js (set/list+// • api/monetization/*.js : the unified REST surface: prices.js (set/list// skill prices) and revenue.js (creator sales// aggregation)//-// Money math is unforgiving, so every branch — validation, rounding, the-// owner/non-owner gate, and the earned − pending − withdrawn arithmetic — is+// Money math is unforgiving, so every branch: validation, rounding, the+// owner/non-owner gate, and the earned − pending − withdrawn arithmetic: is// exercised here. The DB client is mocked with a queue-driven `sql` stub// (shared by the directly-called service functions and the HTTP handlers) so// the logic is tested in isolation from Neon, exactly as Prompt 18 specifies.@@ -55,7 +55,7 @@ vi.mock('../api/_lib/rate-limit.js', () => ({limits: {authIp: vi.fn(async () => ({ success: rlState.success })),// Session-scoped reads (api/monetization/revenue.js) moved off the strict- // credential `authIp` bucket onto `authedReadIp` — without it here the+ // credential `authIp` bucket onto `authedReadIp`: without it here the// handler throws "limits.authedReadIp is not a function" and 500s.authedReadIp: vi.fn(async () => ({ success: rlState.success })),publicIp: vi.fn(async () => ({ success: rlState.success })),@@ -198,7 +198,7 @@ describe('recordRevenueEvent', () => {sqlState.queue.push([{ id: 'rev-5' }]);await recordRevenueEvent({ ...baseEvent, intentId: undefined, txHash: undefined });// intent_id is UNIQUE, so distinct direct credits must NOT collide on a- // shared literal — each gets its own synthetic key.+ // shared literal: each gets its own synthetic key.expect(findInsert().values[1]).toMatch(/^direct_[0-9a-f-]{36}$/);});@@ -301,7 +301,7 @@ describe('getAvailableBalance', () => {});});-// ── 4. setSkillPrices — api/monetization/prices.js ──────────────────────────────+// ── 4. setSkillPrices: api/monetization/prices.js ──────────────────────────────describe('prices endpoint (setSkillPrices)', () => {it('lets an owner set a new price and returns 201', async () => {@@ -564,7 +564,7 @@ describe('prices endpoint (setSkillPrices)', () => {});});-// ── 5. getCreatorSalesData — api/monetization/revenue.js ────────────────────────+// ── 5. getCreatorSalesData: api/monetization/revenue.js ────────────────────────describe('revenue endpoint (getCreatorSalesData)', () => {it('aggregates totals, per-skill, and per-day breakdowns', async () => {@@ -726,7 +726,7 @@ describe('revenue endpoint (getCreatorSalesData)', () => {});});-// ── 6. payout wallets — api/monetization/wallet.js ──────────────────────────────+// ── 6. payout wallets: api/monetization/wallet.js ──────────────────────────────describe('wallet endpoint (payout addresses)', () => {const SOL_ADDRESS = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';@@ -898,7 +898,7 @@ describe('wallet endpoint (payout addresses)', () => {});});-// ── 7. withdrawals — api/monetization/withdrawals.js ────────────────────────────+// ── 7. withdrawals: api/monetization/withdrawals.js ────────────────────────────describe('withdrawals endpoint', () => {const SOL_ADDRESS = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';@@ -959,7 +959,7 @@ describe('withdrawals endpoint', () => {});expect(status).toBe(200);- // A NaN limit binds as NULL, which Postgres reads as "no limit" — the page+ // A NaN limit binds as NULL, which Postgres reads as "no limit": the page// size would silently become the whole table.const list = sqlState.calls.find((c) => c.query.includes('agent_withdrawals'));expect(list.values.slice(-2)).toEqual([20, 0]);