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
Add usage metering, referral rewards, push/notification prefs, and stage splits
nirholas9db55220536b
diff --git a/api/_lib/activation.js b/api/_lib/activation.jsnew file mode 100644index 000000000..9c95c3b60--- /dev/null+++ b/api/_lib/activation.js@@ -0,0 +1,58 @@+// User activation — the single, idempotent "first win" marker.+//+// Activation is the funnel milestone that separates a signup from a user who+// actually reached value. On three.ws the first win is producing a real 3D+// creation (saving an avatar / claiming a forged model). The first time that+// happens for an account we stamp users.activated_at, emit an `activation` event+// for the growth funnel, and — if the account was referred — pay the two-sided+// referral reward (api/_lib/referral-rewards.js).+//+// markActivated is safe to call from every first-win site: the+// `WHERE activated_at IS NULL` guard makes the stamp, the event, and the reward+// fire exactly once per account no matter how many call sites or concurrent+// requests race. It never throws — activation is a side-effect of the real+// action, never a precondition for it.++import { sql } from './db.js';+import { recordEvent } from './usage.js';+import { grantReferralActivationReward } from './referral-rewards.js';++/**+ * Mark a user activated on their first win. Idempotent: only the first call per+ * user transitions the account; subsequent calls are cheap no-ops.+ *+ * @param {string} userId+ * @param {{ source?: string, meta?: object }} [opts]+ * source — what triggered activation (e.g. 'avatar_create', 'forge_save')+ * @returns {Promise<{ activated: boolean, alreadyActive: boolean }>}+ * activated=true only on the transition that newly activated the account.+ */+export async function markActivated(userId, { source = 'unknown', meta = {} } = {}) {+ if (!userId) return { activated: false, alreadyActive: false };+ try {+ // Atomic set-once: RETURNING is empty when the row was already activated+ // (or doesn't exist), so only the first writer proceeds to side-effects.+ const [row] = await sql`+ update users set activated_at = now()+ where id = ${userId} and deleted_at is null and activated_at is null+ returning id+ `;+ if (!row) return { activated: false, alreadyActive: true };++ recordEvent({+ userId,+ kind: 'activation',+ meta: { source, ...meta },+ });++ // Two-sided referral reward — best-effort, never blocks activation.+ grantReferralActivationReward({ referredUserId: userId }).catch((err) =>+ console.error('[activation] reward failed', err?.message),+ );++ return { activated: true, alreadyActive: false };+ } catch (err) {+ console.error('[activation] markActivated failed', err?.message);+ return { activated: false, alreadyActive: false };+ }+}diff --git a/api/_lib/metering.js b/api/_lib/metering.jsnew file mode 100644index 000000000..2c092ba24--- /dev/null+++ b/api/_lib/metering.js@@ -0,0 +1,269 @@+// Usage metering — the one primitive every priced action calls after it+// succeeds. It writes a single, idempotent row to the usage_events ledger+// (kind='metered') carrying the money the action moved and a back-link to the+// settlement that paid for it. That ledger is what produces receipts, the+// periodic invoice statement, and the reconciliation pass.+//+// WHY ONE PRIMITIVE: before this, a charge settled (token_payments) but nothing+// recorded WHAT was billed in a form a customer can read, audit, and reconcile.+// recordUsage() closes that gap with a single contract every rail shares.+//+// IDEMPOTENCY (the no-double-spend bar): a retried settlement must meter exactly+// once. Every metered row carries an idempotency_key (defaulting to the+// settlement ref) with a UNIQUE partial index; the INSERT uses+// ON CONFLICT DO NOTHING, so a duplicate charge resolves to {metered:false}+// instead of a second ledger line.++import { sql } from './db.js';+import { calculateFee } from './fee.js';+import { CATALOG, POLICY } from './pricing/catalog.js';++const USDC_DECIMALS = 6;++/** Atomic USDC (6dp) → human USD string, e.g. 150000n → "0.15". */+export function atomicsToUsd(atomics) {+ return (Number(atomics || 0) / 10 ** USDC_DECIMALS).toFixed(2);+}++// The platform's cut of a charge, in atomics. For marketplace sales the platform+// takes the fee-bps slice and the rest is the seller's; for consumption/scarcity+// actions (no seller) the platform keeps the whole price.+function platformFeeAtomics({ priceAtomics, policy }) {+ if (policy === POLICY.MARKETPLACE) {+ return calculateFee(priceAtomics).fee;+ }+ return priceAtomics;+}++/**+ * Record one metered usage event. Idempotent on the settlement (or an explicit+ * idempotency key) — a retried charge for the same settlement meters once.+ *+ * @param {object} p+ * @param {string|null} p.userId owning user (nullable for wallet-only charges)+ * @param {string} p.action catalog action id (e.g. 'forge.high')+ * @param {number} [p.units=1] quantity billed+ * @param {number|bigint} p.priceUsdcAtomics gross price in USDC atomics (6dp), discount already applied+ * @param {number|bigint} [p.feeUsdcAtomics] platform cut; derived from the action's policy when omitted+ * @param {number} [p.discountBps=0] holder-tier discount applied to reach the price (0–10000)+ * @param {string} p.settlementRef token_payments.id / tx signature / AWS allocation id+ * @param {'three'|'x402'|'aws'|'card'} [p.settlementKind='three']+ * @param {string|null} [p.agentId] agent attribution, when the charge ran for an agent+ * @param {string} [p.idempotencyKey] overrides the default `${kind}:${settlementRef}` key+ * @param {object} [p.meta] extra audit context (sealed into meta jsonb)+ * @returns {Promise<{ id: number|null, metered: boolean, duplicate: boolean }>}+ */+export async function recordUsage({+ userId = null,+ action,+ units = 1,+ priceUsdcAtomics,+ feeUsdcAtomics,+ discountBps = 0,+ settlementRef,+ settlementKind = 'three',+ agentId = null,+ idempotencyKey,+ meta = {},+}) {+ if (!action || typeof action !== 'string') {+ throw Object.assign(new Error('recordUsage: action is required'), { code: 'meter_bad_action' });+ }+ if (!settlementRef) {+ throw Object.assign(new Error('recordUsage: settlementRef is required'), { code: 'meter_no_settlement' });+ }++ const price = BigInt(Math.max(0, Math.trunc(Number(priceUsdcAtomics) || 0)));+ const policy = CATALOG[action]?.policy ?? POLICY.CONSUMPTION;+ const fee =+ feeUsdcAtomics != null+ ? BigInt(Math.max(0, Math.trunc(Number(feeUsdcAtomics))))+ : BigInt(platformFeeAtomics({ priceAtomics: Number(price), policy }));++ const key = idempotencyKey || `${settlementKind}:${settlementRef}`;+ const u = Math.max(1, Math.trunc(Number(units) || 1));+ const disc = Math.max(0, Math.min(10000, Math.trunc(Number(discountBps) || 0)));++ const [row] = await sql`+ insert into usage_events+ (user_id, agent_id, kind, tool, status, meta,+ meter_action, units, price_usdc_atomics, fee_usdc_atomics,+ discount_bps, settlement_ref, settlement_kind, idempotency_key)+ values+ (${userId}, ${agentId}, 'metered', ${action}, 'ok', ${JSON.stringify(meta || {})}::jsonb,+ ${action}, ${u}, ${price.toString()}, ${fee.toString()},+ ${disc}, ${String(settlementRef)}, ${settlementKind}, ${key})+ on conflict (idempotency_key) do nothing+ returning id+ `;++ if (row) return { id: Number(row.id), metered: true, duplicate: false };+ return { id: null, metered: false, duplicate: true };+}++/**+ * Fire-and-forget metering that never throws — for hot paths that must not fail+ * a settled charge just because the ledger write hiccuped. Logs and swallows.+ * The reconciliation pass catches any settlement that ended up unmetered.+ */+export async function recordUsageSafe(args) {+ try {+ return await recordUsage(args);+ } catch (err) {+ console.error('[metering] recordUsage failed', { action: args?.action, ref: args?.settlementRef, error: err?.message });+ return { id: null, metered: false, duplicate: false, error: err?.message };+ }+}++const LABEL = (action) => CATALOG[action]?.label ?? action;++/**+ * Roll a user's metered usage over a window into an invoice statement: per-action+ * line items plus the statement totals. Every atomic is summed in Postgres+ * (numeric) so the math never drifts. Line totals sum exactly to the statement+ * total — the invariant the tests assert.+ *+ * @returns {Promise<{ period:{from,to}, line_items:Array, totals:object }>}+ */+export async function rollupInvoice({ userId, from, to }) {+ const rows = await sql`+ select+ meter_action as action,+ count(*)::int as count,+ coalesce(sum(units), 0)::bigint as units,+ coalesce(sum(price_usdc_atomics), 0)::numeric as gross_atomics,+ coalesce(sum(fee_usdc_atomics), 0)::numeric as fee_atomics,+ coalesce(round(avg(discount_bps)), 0)::int as discount_bps+ from usage_events+ where user_id = ${userId}+ and kind = 'metered'+ and created_at >= ${from}+ and created_at < ${to}+ group by meter_action+ order by gross_atomics desc+ `;++ let gross = 0n;+ let fee = 0n;+ let count = 0;+ const line_items = rows.map((r) => {+ const g = BigInt(r.gross_atomics);+ const f = BigInt(r.fee_atomics);+ gross += g;+ fee += f;+ count += r.count;+ return {+ action: r.action,+ label: LABEL(r.action),+ count: r.count,+ units: Number(r.units),+ gross_atomics: g.toString(),+ fee_atomics: f.toString(),+ net_atomics: (g - f).toString(),+ gross_usd: atomicsToUsd(g),+ fee_usd: atomicsToUsd(f),+ discount_bps: r.discount_bps,+ };+ });++ return {+ period: { from: from instanceof Date ? from.toISOString() : from, to: to instanceof Date ? to.toISOString() : to },+ line_items,+ totals: {+ charge_count: count,+ gross_atomics: gross.toString(),+ fee_atomics: fee.toString(),+ net_atomics: (gross - fee).toString(),+ gross_usd: atomicsToUsd(gross),+ fee_usd: atomicsToUsd(fee),+ currency: 'USDC',+ },+ };+}++/**+ * A single charge receipt: the metered row joined to its on-chain settlement so+ * the customer sees action, units, price, fee, discount, the settlement tx, and+ * the timestamp. Owner-scoped — a user only reads their own usage.+ *+ * @returns {Promise<object|null>}+ */+export async function getReceipt({ userId, eventId }) {+ const [row] = await sql`+ select+ ue.id, ue.meter_action, ue.units, ue.price_usdc_atomics, ue.fee_usdc_atomics,+ ue.discount_bps, ue.settlement_ref, ue.settlement_kind, ue.created_at,+ tp.tx_signature, tp.network, tp.mint, tp.total_atomics as settled_atomics,+ tp.price_usd as token_price_usd+ from usage_events ue+ left join token_payments tp+ on ue.settlement_kind = 'three' and tp.id::text = ue.settlement_ref+ where ue.id = ${eventId}+ and ue.kind = 'metered'+ and ue.user_id = ${userId}+ `;+ if (!row) return null;++ const gross = BigInt(row.price_usdc_atomics || 0);+ const fee = BigInt(row.fee_usdc_atomics || 0);+ const sig = row.tx_signature;+ return {+ event_id: Number(row.id),+ action: row.meter_action,+ label: LABEL(row.meter_action),+ units: row.units,+ gross_atomics: gross.toString(),+ fee_atomics: fee.toString(),+ net_atomics: (gross - fee).toString(),+ gross_usd: atomicsToUsd(gross),+ fee_usd: atomicsToUsd(fee),+ discount_bps: row.discount_bps,+ discount_percent: row.discount_bps ? (row.discount_bps / 100).toFixed(1) : '0.0',+ settlement: {+ kind: row.settlement_kind,+ ref: row.settlement_ref,+ tx_signature: sig ?? null,+ network: row.network ?? null,+ explorer_url: sig ? `https://solscan.io/tx/${sig}` : null,+ token_price_usd: row.token_price_usd != null ? Number(row.token_price_usd) : null,+ },+ issued_at: row.created_at,+ };+}++/**+ * Reconciliation status for a user (or the whole platform when userId is null):+ * how many metered rows reconcile to a real settlement vs. how many are orphaned.+ * Surfaced on the revenue dashboard so an operator sees "all charges reconciled".+ *+ * A metered row reconciles when its settlement matches a real record:+ * • settlement_kind='three' → a token_payments row with that id+ * • settlement_kind='aws' → an aws_marketplace_metering row with that allocation id+ * • other kinds (x402/card) → treated as reconciled when a ref is present+ *+ * @returns {Promise<{ total:number, reconciled:number, unreconciled:number, by_kind:object }>}+ */+export async function reconciliationStatus({ userId = null } = {}) {+ const scope = userId ? sql`ue.user_id = ${userId}` : sql`true`;+ const [row] = await sql`+ select+ count(*)::int as total,+ count(*) filter (where+ (ue.settlement_kind = 'three' and exists (+ select 1 from token_payments tp where tp.id::text = ue.settlement_ref))+ or (ue.settlement_kind = 'aws' and exists (+ select 1 from aws_marketplace_metering am where am.usage_allocation_id = ue.settlement_ref))+ or (ue.settlement_kind not in ('three','aws') and ue.settlement_ref is not null)+ )::int as reconciled+ from usage_events ue+ where ue.kind = 'metered' and ${scope}+ `;+ const total = row?.total ?? 0;+ const reconciled = row?.reconciled ?? 0;+ return {+ total,+ reconciled,+ unreconciled: total - reconciled,+ all_reconciled: total === reconciled,+ };+}diff --git a/api/_lib/migrations/20260623170000_usage_metering.sql b/api/_lib/migrations/20260623170000_usage_metering.sqlnew file mode 100644index 000000000..b86f42bb0--- /dev/null+++ b/api/_lib/migrations/20260623170000_usage_metering.sql@@ -0,0 +1,58 @@+-- Migration: usage metering — the queryable billing ledger.+-- ============================================================================+-- Every priced action that SUCCEEDS records one usage_event with the money it+-- moved, back-linked to the settlement that paid for it. This is the single+-- ledger that produces receipts, the periodic invoice statement, and the+-- reconciliation pass (usage with no settlement, or a settlement with no usage).+--+-- These columns are ADDITIVE on the existing usage_events table (see+-- migrations/20260605120000_usage_events.sql) and fully idempotent — safe to+-- run repeatedly and against a DB that already has them. Metered rows carry+-- kind='metered'; pre-existing quota/analytics/llm rows are untouched.+--+-- meter_action — the catalog action id charged (e.g. 'forge.high').+-- units — quantity billed (default 1).+-- price_usdc_atomics — gross price in USDC atomics (6 decimals) at charge time,+-- i.e. the holder-discounted price actually quoted.+-- fee_usdc_atomics — the platform's cut in USDC atomics. For consumption /+-- scarcity actions (no seller) the platform keeps the whole+-- price, so fee == price; for marketplace sales fee is the+-- platform-fee-bps portion and (price - fee) is the seller's.+-- discount_bps — the holder-tier discount applied to reach price (0–10000),+-- recorded so a receipt can show "you saved X% by holding".+-- settlement_ref — the settlement this usage is paid by: a token_payments.id+-- (uuid as text), an on-chain tx signature, or an AWS usage+-- allocation id. The reconciliation pass joins on this.+-- settlement_kind — which rail settled it: 'three' | 'x402' | 'aws' | 'card'.+-- idempotency_key — UNIQUE per charge so a retried settlement meters EXACTLY+-- once (no double-billing). Defaults to settlement_ref.+--+-- Money is stored in atomics (bigint), never floats, so statement sums never drift.++alter table usage_events add column if not exists meter_action text;+alter table usage_events add column if not exists units int;+alter table usage_events add column if not exists price_usdc_atomics bigint;+alter table usage_events add column if not exists fee_usdc_atomics bigint;+alter table usage_events add column if not exists discount_bps int;+alter table usage_events add column if not exists settlement_ref text;+alter table usage_events add column if not exists settlement_kind text;+alter table usage_events add column if not exists idempotency_key text;++-- Idempotency: a retried charge for the same settlement must meter once. A+-- partial UNIQUE index (only metered rows carry a key) lets the INSERT use+-- ON CONFLICT (idempotency_key) DO NOTHING as the no-double-spend guarantee+-- without constraining the millions of non-metered analytics/quota rows.+create unique index if not exists usage_events_idem+ on usage_events(idempotency_key)+ where idempotency_key is not null;++-- Reconciliation scans metered rows by settlement_ref to match each against a+-- real token_payments row (or AWS metering ack).+create index if not exists usage_events_settlement+ on usage_events(settlement_ref)+ where settlement_ref is not null;++-- Invoice rollups scan a user's metered rows over a time window.+create index if not exists usage_events_metered_user_time+ on usage_events(user_id, created_at desc)+ where kind = 'metered';diff --git a/api/_lib/migrations/20260628000000_push_and_notification_prefs.sql b/api/_lib/migrations/20260628000000_push_and_notification_prefs.sqlnew file mode 100644index 000000000..5435d612f--- /dev/null+++ b/api/_lib/migrations/20260628000000_push_and_notification_prefs.sql@@ -0,0 +1,89 @@+begin;++-- PWA & notifications (Road to $1B — task 39).+-- ============================================================================+-- Three new surfaces, all keyed off the existing user_notifications pipeline:+--+-- 1. push_subscriptions — Web Push (VAPID) endpoints per device. One row+-- per browser/device that granted notification permission. Sends fan out+-- from api/_lib/notify.js; dead endpoints (404/410) are pruned on send.+--+-- 2. notification_preferences — the unified preference center. One JSONB row+-- per user describing, per category, which channels (in_app/push/email/+-- telegram) are on. Missing keys fall back to code defaults+-- (api/_lib/notify-prefs.js DEFAULTS) so a user with no row gets sensible+-- behaviour and new categories light up without a backfill.+--+-- 3. notification_events — the re-engagement funnel: one row per+-- (notification, channel, event) where event ∈ sent|opened|returned.+-- insertNotification records `sent`; the SW + inbox record `opened`;+-- a push-sourced app open records `returned`. Powers sent→opened→returned+-- analytics so the loop is measured, not guessed.+--+-- 4. newsletter_subscribers — double opt-in marketing list. A POST creates a+-- `pending` row + confirm token (emailed); the confirm link flips it to+-- `confirmed` and adds the contact to the Resend audience. Unsubscribe+-- flips to `unsubscribed` and is honoured on every send.++-- ── 1. push_subscriptions ────────────────────────────────────────────────────+create table if not exists push_subscriptions (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references users(id) on delete cascade,+ endpoint text not null,+ p256dh text not null,+ auth text not null,+ user_agent text,+ created_at timestamptz not null default now(),+ last_seen_at timestamptz not null default now()+);+-- One subscription per push endpoint, globally. A re-subscribe upserts (a user+-- can move a device between accounts; the latest owner wins).+create unique index if not exists push_subscriptions_endpoint+ on push_subscriptions (endpoint);+create index if not exists push_subscriptions_user+ on push_subscriptions (user_id, created_at desc);++-- ── 2. notification_preferences ──────────────────────────────────────────────+create table if not exists notification_preferences (+ user_id uuid primary key references users(id) on delete cascade,+ prefs jsonb not null default '{}'::jsonb,+ updated_at timestamptz not null default now()+);++-- ── 3. notification_events ───────────────────────────────────────────────────+create table if not exists notification_events (+ id bigint generated always as identity primary key,+ notification_id uuid references user_notifications(id) on delete cascade,+ user_id uuid not null references users(id) on delete cascade,+ channel text not null check (channel in ('in_app','push','email','telegram')),+ event text not null check (event in ('sent','opened','returned')),+ meta jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now()+);+create index if not exists notification_events_notif+ on notification_events (notification_id);+create index if not exists notification_events_funnel+ on notification_events (event, channel, created_at desc);+-- A given notification is "opened"/"returned" at most once per channel — the+-- SW can fire notificationclick more than once across tabs.+create unique index if not exists notification_events_once+ on notification_events (notification_id, channel, event)+ where notification_id is not null and event in ('opened','returned');++-- ── 4. newsletter_subscribers ────────────────────────────────────────────────+create table if not exists newsletter_subscribers (+ id uuid primary key default gen_random_uuid(),+ email citext not null unique,+ status text not null default 'pending'+ check (status in ('pending','confirmed','unsubscribed')),+ confirm_token text not null,+ locale text,+ source text,+ created_at timestamptz not null default now(),+ confirmed_at timestamptz,+ unsubbed_at timestamptz+);+create index if not exists newsletter_subscribers_token+ on newsletter_subscribers (confirm_token);++commit;diff --git a/api/_lib/migrations/20260628090000_marketplace_splits.sql b/api/_lib/migrations/20260628090000_marketplace_splits.sqlnew file mode 100644index 000000000..b7e21a9fd--- /dev/null+++ b/api/_lib/migrations/20260628090000_marketplace_splits.sql@@ -0,0 +1,61 @@+-- Multi-collaborator payment splits for marketplace listings.+--+-- A listing (an agent's paid skill) may credit more than one collaborator. The+-- split config lives here; the per-purchase apportionment is recorded in+-- split_distributions so every recipient's exact share is auditable and, in+-- ledger mode, withdrawable. On-chain (0xSplits, EVM) splits store the contract+-- address; the creator-net flows into it on chain and 0xSplits distributes.+-- Single-creator listings have NO row here and pay the creator directly.++CREATE TABLE IF NOT EXISTS listing_splits (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,+ skill text NOT NULL,+ chain text NOT NULL DEFAULT 'solana',+ -- 0xSplits contract address when anchored on chain; NULL ⇒ ledger mode.+ split_address text,+ split_mode text NOT NULL DEFAULT 'ledger' CHECK (split_mode IN ('ledger', 'onchain')),+ -- Owner of a mutable split (can update recipients); NULL ⇒ immutable.+ owner_address text,+ created_by uuid REFERENCES users(id) ON DELETE SET NULL,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ UNIQUE (agent_id, skill)+);++CREATE TABLE IF NOT EXISTS listing_split_recipients (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ split_id uuid NOT NULL REFERENCES listing_splits(id) ON DELETE CASCADE,+ recipient_user_id uuid REFERENCES users(id) ON DELETE SET NULL,+ address text NOT NULL,+ chain text NOT NULL,+ -- Share in basis points; the application enforces Σ share_bps = 10000.+ share_bps integer NOT NULL CHECK (share_bps > 0 AND share_bps <= 10000),+ label text,+ created_at timestamptz NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS idx_split_recipients_split ON listing_split_recipients(split_id);++-- How a confirmed purchase's creator-net was divided. One row per recipient.+-- Unique on (purchase_id, address) so a retried confirm is idempotent — a+-- recipient is credited for a purchase at most once.+CREATE TABLE IF NOT EXISTS split_distributions (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ purchase_id uuid NOT NULL REFERENCES skill_purchases(id) ON DELETE CASCADE,+ split_id uuid NOT NULL REFERENCES listing_splits(id) ON DELETE CASCADE,+ recipient_user_id uuid REFERENCES users(id) ON DELETE SET NULL,+ address text NOT NULL,+ share_bps integer NOT NULL,+ amount bigint NOT NULL CHECK (amount >= 0), -- atomic units+ currency_mint text NOT NULL,+ chain text NOT NULL,+ -- onchain: net flowed into the 0xSplits contract (settled on chain).+ -- ledger: platform-recorded credit the recipient withdraws.+ mode text NOT NULL DEFAULT 'ledger' CHECK (mode IN ('ledger', 'onchain')),+ status text NOT NULL DEFAULT 'accrued' CHECK (status IN ('accrued', 'settled', 'failed')),+ tx_signature text,+ created_at timestamptz NOT NULL DEFAULT now(),+ UNIQUE (purchase_id, address)+);+CREATE INDEX IF NOT EXISTS idx_split_dist_recipient ON split_distributions(recipient_user_id, status);+CREATE INDEX IF NOT EXISTS idx_split_dist_purchase ON split_distributions(purchase_id);diff --git a/api/_lib/migrations/20260628120000_referral_activation.sql b/api/_lib/migrations/20260628120000_referral_activation.sqlnew file mode 100644index 000000000..0f5f647a9--- /dev/null+++ b/api/_lib/migrations/20260628120000_referral_activation.sql@@ -0,0 +1,65 @@+begin;++-- Referral activation rewards + virality funnel instrumentation+-- =============================================================+-- The referral system already attributes signups (users.referred_by_id) and+-- accrues purchase commission (users.referral_earnings_total). This migration+-- adds the two missing halves of a real viral loop:+--+-- 1. ACTIVATION — a single, idempotent "first win" timestamp per user, so the+-- growth funnel can measure who actually reached value, and so a referral+-- can reward BOTH sides the moment a referred user activates (not only when+-- they later spend). The reward itself is paid as platform credits via the+-- existing credit ledger (api/_lib/credits.js, kind='grant',+-- ref_type='referral_activation') — no new balance table needed.+--+-- 2. VISITS — share/referral-link visits, the top of the funnel. Without these+-- the loop's k-factor (signups per sharing user) is unmeasurable. We store a+-- deduped, NON-PII row per (code, hashed-visitor, UTC day) so a single+-- visitor refreshing a link inflates nothing.++-- ── Activation timestamp ───────────────────────────────────────────────────────+-- NULL until the user's first qualifying win (first avatar/3D creation). Set+-- exactly once by api/_lib/activation.js via a `WHERE activated_at IS NULL` guard,+-- so the activation event + referral reward fire a single time per account.+alter table users add column if not exists activated_at timestamptz;++-- Partial index: funnel queries only ever scan activated users, and the set of+-- activated accounts is far smaller than the full users table early on.+create index if not exists users_activated_at_idx+ on users (activated_at)+ where activated_at is not null;++-- Referred-and-activated funnel slice (signup→activation conversion by referrer).+create index if not exists users_referred_activated_idx+ on users (referred_by_id, activated_at)+ where referred_by_id is not null;++-- ── Referral-link visits (top of funnel) ───────────────────────────────────────+-- One row per (code, visitor, day). `visitor_hash` is sha256(ip + ua + code) —+-- never raw IP/UA — so we can dedup and rate-shape without storing PII. The+-- referrer is resolved at write time when the code matches a live user; an+-- unknown/garbage code still records a visit (referrer_user_id NULL) so we can+-- see traffic on dead links too. `day` is the UTC date the writer computes, kept+-- as a real column (not a function index) so the dedup unique index is immutable.+create table if not exists referral_visits (+ id bigserial primary key,+ code text not null,+ referrer_user_id uuid references users(id) on delete set null,+ visitor_hash text not null,+ day date not null,+ created_at timestamptz not null default now()+);++-- Dedup: a given visitor counts once per code per day. Writers use+-- ON CONFLICT DO NOTHING so a refresh/replay is a silent no-op.+create unique index if not exists referral_visits_dedup+ on referral_visits (code, visitor_hash, day);++-- Funnel rollups read visits by referrer over a time window, and by code.+create index if not exists referral_visits_referrer_time_idx+ on referral_visits (referrer_user_id, created_at desc);+create index if not exists referral_visits_code_time_idx+ on referral_visits (code, created_at desc);++commit;diff --git a/api/_lib/notify-prefs.js b/api/_lib/notify-prefs.jsnew file mode 100644index 000000000..3243227e5--- /dev/null+++ b/api/_lib/notify-prefs.js@@ -0,0 +1,235 @@+// Notification preference model — the single source of truth shared by the+// preference-center API, the push fan-out, and the email gating.+//+// A notification has a `type` (e.g. 'skill_purchased'). Types roll up into a+// small set of user-facing CATEGORIES. The user controls, per category, which+// CHANNELS deliver it. Channels: in_app (the bell inbox), push (Web Push),+// email (Resend transactional), telegram (per-account bot alerts).+//+// Preferences are stored sparsely in notification_preferences.prefs as+// { categories: { sales: { push: false }, ... }, telegram_chat_id: '123' }+// Any key a user hasn't touched falls back to DEFAULTS below — so new+// categories light up without a backfill, and a user with no row at all gets+// sensible behaviour.++import { sql } from './db.js';++/** Ordered for display in the preference center. */+export const CATEGORIES = [+ {+ key: 'sales',+ label: 'Sales & earnings',+ description: 'Your launch filled, a skill or asset sold, a tip or payout arrived.',+ },+ {+ key: 'purchases',+ label: 'Your purchases',+ description: 'Receipts and confirmations for things you bought or were gifted.',+ },+ {+ key: 'social',+ label: 'Social & mentions',+ description: 'Your agent was embedded, forked, remixed, or replied to.',+ },+ {+ key: 'irl',+ label: 'In person (IRL)',+ description: 'Someone met, messaged, or paid your agent in the real world.',+ },+ {+ key: 'alerts',+ label: 'Market alerts',+ description: 'Pump.fun rules and token signals you configured.',+ },+ {+ key: 'account',+ label: 'Account & security',+ description: 'Withdrawals, payment issues, and security-sensitive events.',+ },+];++export const CHANNELS = ['in_app', 'push', 'email', 'telegram'];++const CATEGORY_KEYS = new Set(CATEGORIES.map((c) => c.key));++// notification `type` → category. Unmapped types fall back to 'account' so a+// new notification type is never silently undeliverable.+const TYPE_CATEGORY = {+ skill_purchased: 'sales',+ asset_purchased: 'sales',+ sale: 'sales',+ 'payment-earned': 'sales',+ payment_received: 'sales',+ referral_earned: 'sales',+ pump_launch_filled: 'sales',++ skill_purchase_confirmed: 'purchases',+ asset_purchase_confirmed: 'purchases',+ skill_gift_received: 'purchases',+ skill_gift_sent: 'purchases',++ remix: 'social',+ reply: 'social',+ embed: 'social',+ mention: 'social',+ fork: 'social',++ irl_interaction: 'irl',+ irl_reply: 'irl',++ pump_alert: 'alerts',++ withdrawal_completed: 'account',+ withdrawal_failed: 'account',+ payment_mismatch: 'account',+ asset_payment_mismatch: 'account',+ skill_payment_mismatch: 'account',+ security_alert: 'account',+};++export function categoryForType(type) {+ return TYPE_CATEGORY[type] || 'account';+}++// Default channel matrix. in_app is on everywhere (the bell is the baseline).+// push is on by default *for users who have subscribed a device* — a user with+// no push subscription simply never receives one, so defaulting it on is not+// spammy. email defaults on only for money + security; off for the higher-+// frequency social/irl/alerts categories. telegram is always opt-in (needs a+// linked chat id) so it defaults off.+const DEFAULTS = {+ sales: { in_app: true, push: true, email: true, telegram: false },+ purchases: { in_app: true, push: true, email: true, telegram: false },+ social: { in_app: true, push: true, email: false, telegram: false },+ irl: { in_app: true, push: true, email: false, telegram: false },+ alerts: { in_app: true, push: true, email: false, telegram: true },+ account: { in_app: true, push: true, email: true, telegram: false },+};++/** The full default matrix, used to seed the preference-center UI. */+export function defaultMatrix() {+ return JSON.parse(JSON.stringify(DEFAULTS));+}++/**+ * Resolve the effective channel matrix for a user by overlaying their stored+ * sparse prefs onto DEFAULTS. Returns { categories, telegram_chat_id }.+ */+export async function resolvePrefs(userId) {+ let stored = {};+ try {+ const [row] = await sql`+ select prefs from notification_preferences where user_id = ${userId}+ `;+ stored = row?.prefs && typeof row.prefs === 'object' ? row.prefs : {};+ } catch (err) {+ // A missing table or transient DB error must never block delivery — fall+ // back to defaults (in_app + push on) rather than dropping the notice.+ console.error('[notify-prefs] resolve failed:', err.message);+ }+ return mergeWithDefaults(stored);+}++export function mergeWithDefaults(stored) {+ const out = { categories: {}, telegram_chat_id: stored?.telegram_chat_id || null };+ const storedCats = (stored && stored.categories) || {};+ for (const { key } of CATEGORIES) {+ out.categories[key] = { ...DEFAULTS[key], ...(storedCats[key] || {}) };+ }+ return out;+}++/** Is `channel` enabled for the category that `type` belongs to? */+export function channelEnabled(prefs, type, channel) {+ const cat = categoryForType(type);+ const row = prefs?.categories?.[cat];+ if (!row) return DEFAULTS[cat]?.[channel] ?? false;+ return row[channel] !== false && row[channel] != null ? !!row[channel] : DEFAULTS[cat][channel];+}++/**+ * Sanitise an incoming preference body to the known category/channel shape.+ * Anything unrecognised is dropped, so the client can't smuggle arbitrary keys+ * into the JSONB. Returns the sparse object to store.+ */+export function sanitizePrefs(body) {+ const out = { categories: {} };+ const cats = body?.categories;+ if (cats && typeof cats === 'object') {+ for (const [cat, row] of Object.entries(cats)) {+ if (!CATEGORY_KEYS.has(cat) || !row || typeof row !== 'object') continue;+ const clean = {};+ for (const ch of CHANNELS) {+ if (typeof row[ch] === 'boolean') clean[ch] = row[ch];+ }+ if (Object.keys(clean).length) out.categories[cat] = clean;+ }+ }+ if (typeof body?.telegram_chat_id === 'string') {+ const t = body.telegram_chat_id.trim();+ if (/^-?\d{1,20}$/.test(t)) out.telegram_chat_id = t;+ else if (t === '') out.telegram_chat_id = null;+ }+ return out;+}++// ── Push payload shaping ─────────────────────────────────────────────────────+// Build the title/body/url shown in the OS notification from a stored+// notification row. Mirrors the labels in src/notifications.js so the push and+// the in-app inbox read identically. Only $THREE is ever referenced.++const PUSH_COPY = {+ skill_purchased: (p) => ['You made a sale 💵', `Payment received for "${p.skill || 'a skill'}"`],+ skill_purchase_confirmed: (p) => ['Purchase confirmed ✅', `Your purchase of "${p.skill || 'a skill'}" is confirmed`],+ skill_gift_received: (p) => ['You got a gift 🎁', p.from ? `${p.from} gifted you "${p.skill || 'a skill'}"` : `You received "${p.skill || 'a skill'}" as a gift`],+ skill_gift_sent: (p) => ['Gift delivered 🎁', p.to ? `Your gift reached ${p.to}` : 'Your gift was delivered'],+ asset_purchased: (p) => ['You made a sale 💵', `Someone purchased your ${p.item_type || 'asset'}`],+ asset_purchase_confirmed: () => ['Purchase confirmed ✅', 'Your asset purchase is confirmed'],+ referral_earned: () => ['Referral earned 💰', 'You earned a referral commission'],+ 'payment-earned': (p) => ['Payment received 💸', p.actor ? `From ${p.actor}` : 'A payment landed in your account'],+ sale: () => ['You made a sale 🛒', 'Your agent made a sale'],+ pump_launch_filled: (p) => ['Your launch filled 🚀', p.name ? `${p.name} hit its target` : 'Your launch reached its target'],+ embed: () => ['New embed 🔗', 'Your creation was embedded somewhere new'],+ remix: () => ['Remixed 🔄', 'Someone remixed your creation'],+ fork: () => ['Forked 🍴', 'Someone forked your agent'],+ reply: () => ['New reply 💬', 'New reply on your agent'],+ mention: () => ['You were mentioned 📣', 'Your agent was mentioned'],+ irl_interaction: (p) => ['Met in person 📍', p.message ? `“${p.message}”` : 'Someone interacted with your agent in person'],+ irl_reply: (p) => ['Agent replied 💬', p.message ? `“${p.message}”` : 'An agent replied to your message'],+ pump_alert: (p) => ['Market alert 📈', p.summary || 'A token alert you configured just fired'],+ withdrawal_completed: () => ['Withdrawal complete ✅', 'Your withdrawal has been sent'],+ withdrawal_failed: () => ['Withdrawal failed ⚠️', 'A withdrawal could not be completed — tap to review'],+ payment_mismatch: () => ['Payment mismatch ⚠️', 'Check your agent payment settings'],+ asset_payment_mismatch: () => ['Payment mismatch ⚠️', 'Check your agent payment settings'],+ skill_payment_mismatch: () => ['Payment mismatch ⚠️', 'Check your agent payment settings'],+ security_alert: (p) => ['Security alert 🔒', p.message || 'A security-sensitive change was made to your account'],+};++export function pushPayloadFor(type, payload, notificationId) {+ const p = payload || {};+ const fn = PUSH_COPY[type];+ const [title, body] = fn ? fn(p) : ['three.ws', String(type).replace(/_/g, ' ')];+ const url = pushUrlFor(p);+ return {+ title,+ body,+ url,+ tag: type,+ notificationId: notificationId || null,+ // Used by the SW to attribute the 'returned' funnel event.+ category: categoryForType(type),+ };+}++function pushUrlFor(p) {+ const raw = p.link+ || (p.tx_signature ? `https://solscan.io/tx/${encodeURIComponent(p.tx_signature)}` : null)+ || (p.agent_id ? `/agent/${encodeURIComponent(p.agent_id)}` : null)+ || '/dashboard/';+ // Same allowlist as the inbox: same-origin path or absolute http(s).+ if (typeof raw !== 'string') return '/dashboard/';+ const s = raw.trim();+ if (s.startsWith('/') && !s.startsWith('//')) return s;+ if (/^https?:\/\//i.test(s)) return s;+ return '/dashboard/';+}diff --git a/api/_lib/notify.js b/api/_lib/notify.jsindex 10d489fd1..0dfdd2e28 100644--- a/api/_lib/notify.js+++ b/api/_lib/notify.js@@ -1,16 +1,93 @@/**- * Fire-and-forget in-app notification insert.- * Failures are logged, never thrown — callers must not await this for correctness.+ * In-app notification insert + multi-channel fan-out.+ *+ * insertNotification() is the single choke point every notification flows+ * through (sales, purchases, IRL, pump alerts, withdrawals…). It:+ * 1. inserts the in-app row (the bell inbox) — the durable record,+ * 2. records a `sent` funnel event for in_app,+ * 3. fans out to Web Push for the categories the user left enabled,+ * 4. records a `sent` event per push delivery.+ *+ * Every channel is gated by the user's preference center (api/_lib/notify-prefs)+ * so there is no notification a user can't turn off. Failures are logged, never+ * thrown — callers must not depend on this for correctness and need not await.** @param {string} userId- * @param {'payment_received'|'withdrawal_completed'|'withdrawal_failed'} type+ * @param {string} type e.g. 'skill_purchased' (see notify-prefs TYPE_CATEGORY)* @param {object} payload+ * @returns {Promise<{ id: string|null }>}*/import { sql } from './db.js';+import { resolvePrefs, channelEnabled, pushPayloadFor, categoryForType } from './notify-prefs.js';+import { sendPushToUser } from './web-push.js';++export function insertNotification(userId, type, payload = {}) {+ return deliver(userId, type, payload).catch((err) => {+ console.error('[notify] delivery failed:', err.message);+ return { id: null };+ });+}++async function deliver(userId, type, payload) {+ // 1 — durable in-app row.+ let id = null;+ try {+ const [row] = await sql`+ insert into user_notifications (user_id, type, payload)+ values (${userId}, ${type}, ${JSON.stringify(payload)}::jsonb)+ returning id+ `;+ id = row?.id ?? null;+ } catch (err) {+ console.error('[notify] insert failed:', err.message);+ return { id: null };+ }++ // 2 — record the in-app send (the bell is always delivered).+ recordEvent(id, userId, 'in_app', 'sent');++ // 3 + 4 — push fan-out, gated by preferences.+ try {+ const prefs = await resolvePrefs(userId);+ if (channelEnabled(prefs, type, 'push')) {+ const delivered = await sendPushToUser(userId, pushPayloadFor(type, payload, id));+ if (delivered > 0) recordEvent(id, userId, 'push', 'sent', { count: delivered });+ }+ } catch (err) {+ console.error('[notify] push fan-out failed:', err.message);+ }++ return { id };+}-export function insertNotification(userId, type, payload) {+/**+ * Fire-and-forget funnel event. Sent rows are unconstrained (a notification can+ * be sent on several channels); opened/returned are deduped by a partial unique+ * index, so a double notificationclick is idempotent.+ */+export function recordEvent(notificationId, userId, channel, event, meta = {}) {+ if (!userId || !channel || !event) return;sql`- insert into user_notifications (user_id, type, payload)- values (${userId}, ${type}, ${JSON.stringify(payload)}::jsonb)- `.catch((err) => console.error('[notify] insert failed:', err.message));+ insert into notification_events (notification_id, user_id, channel, event, meta)+ values (${notificationId}, ${userId}, ${channel}, ${event}, ${JSON.stringify(meta)}::jsonb)+ on conflict do nothing+ `.catch((err) => console.error('[notify] event insert failed:', err.message));+}++/**+ * Whether a transactional email for `type` should be sent, per the user's+ * preferences. Used by the few endpoints that send category email directly+ * (receipts, sale alerts) so email honours the same off switch as push.+ * Fails open (returns true) on a lookup error — better a wanted receipt than a+ * dropped one.+ */+export async function emailAllowedForType(userId, type) {+ try {+ const prefs = await resolvePrefs(userId);+ return channelEnabled(prefs, type, 'email');+ } catch {+ return true;+ }}++export { categoryForType };diff --git a/api/_lib/pricing/charge-three.js b/api/_lib/pricing/charge-three.jsindex e4ee09a27..46a770abd 100644--- a/api/_lib/pricing/charge-three.js+++ b/api/_lib/pricing/charge-three.js@@ -23,7 +23,37 @@ import {pullFromAllowance,recordAllowancePayment,} from '../token/index.js';-import { catalogEntry, priceForAction, POLICY } from './catalog.js';+import { catalogEntry, priceForAction, POLICY, CATALOG } from './catalog.js';+import { recordUsageSafe } from '../metering.js';++// Meter a SETTLED $THREE charge into the usage ledger. Derives the USDC-atomic+// price and the holder discount actually applied from the (discounted) quote.usd+// vs the catalog's full price, then records one idempotent row keyed by the+// settlement id — so a retried settlement meters exactly once. Never throws, so+// a ledger hiccup can never fail a charge the user already paid for; the+// reconciliation pass catches anything that slips through unmetered.+async function meterSettledCharge({ action, quoteUsd, userId, agentId, settlementRef }) {+ if (!settlementRef) return;+ const full = CATALOG[action]?.usd ?? null;+ const usd = Number(quoteUsd) || 0;+ const priceUsdcAtomics = Math.round(usd * 1_000_000);+ // Recover the discount that was applied to reach the quoted price (fixed-price+ // actions only — variable/marketplace prices carry no holder discount).+ let discountBps = 0;+ if (full != null && full > 0 && usd > 0 && usd < full) {+ discountBps = Math.max(0, Math.min(10000, Math.round((1 - usd / full) * 10000)));+ }+ await recordUsageSafe({+ userId: userId ?? null,+ agentId: agentId ?? null,+ action,+ units: 1,+ priceUsdcAtomics,+ discountBps,+ settlementRef: String(settlementRef),+ settlementKind: 'three',+ });+}// Surfaces that are free forever (the growth funnel). These are NOT catalog// actions — they have no price — but they're listed explicitly so the guardrail@@ -133,6 +163,15 @@ export async function requireThreePayment({userId: user?.id ?? null,network,});+ // Meter the settled charge into the usage ledger (idempotent on the+ // settlement id). result.quote.usd is the holder-discounted price actually+ // quoted; result.payment_id is the token_payments row this usage is paid by.+ await meterSettledCharge({+ action,+ quoteUsd: result?.quote?.usd,+ userId: user?.id ?? null,+ settlementRef: result?.payment_id,+ });return { paid: true, payment: result };}@@ -164,6 +203,14 @@ export async function requireThreePayment({userId: user?.id ?? null,slot: pull.slot,});+ // Meter the allowance-rail charge too — same ledger, same idempotency+ // guarantee (keyed by the token_payments id), so both rails reconcile.+ await meterSettledCharge({+ action,+ quoteUsd: quote.usd,+ userId: user?.id ?? null,+ settlementRef: record.id,+ });return {paid: true,via: 'allowance',diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex c53ea5e0a..b67c80862 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -746,6 +746,20 @@ export const limits = {// of the heaviest avoidable burners. Never critical.notificationsRead: (userId) =>getLimiter('notifications:read', { limit: 120, window: '1 m', local: true }).limit(userId),+ // Web Push subscription register/unregister — one per device install plus the+ // occasional re-subscribe when the browser rotates the endpoint.+ pushSubscribe: (userId) =>+ getLimiter('push:subscribe', { limit: 30, window: '1 h' }).limit(userId),+ // Preference-center writes — debounced client, generous ceiling.+ notifPrefsWrite: (userId) =>+ getLimiter('notif:prefs:write', { limit: 60, window: '1 h' }).limit(userId),+ // Funnel tracking (opened/returned) — high local ceiling; one ping per+ // notification interaction, deduped server-side anyway.+ notifTrack: (userId) =>+ getLimiter('notif:track', { limit: 240, window: '1 m', local: true }).limit(userId),+ // Newsletter confirm/unsubscribe link clicks (token in URL, no auth).+ newsletterConfirmIp: (ip) =>+ getLimiter('newsletter:confirm:ip', { limit: 20, window: '1 h' }).limit(ip),// $THREE token payment layer (api/token/*).// quote: 30 per user per minute — prevents price-polling abuse; each quote// hits a live price feed and signs a HMAC. Generous enough for interactivediff --git a/api/_lib/referral-rewards.js b/api/_lib/referral-rewards.jsnew file mode 100644index 000000000..c149260f3--- /dev/null+++ b/api/_lib/referral-rewards.js@@ -0,0 +1,236 @@+// Two-sided referral activation rewards + viral-funnel math.+//+// The referral system attributes signups (users.referred_by_id) and accrues+// commission on a referred user's confirmed PURCHASES (api/_lib/referrals.js,+// users.referral_earnings_total). That rewards the referrer only when the+// referred user spends money — it does nothing at the activation moment and+// gives the new user no reason to stick.+//+// This module closes that gap: the instant a referred user reaches their first+// win (api/_lib/activation.js → markActivated), BOTH sides are granted platform+// credits toward the paid lanes. Credits ride the existing ledger+// (api/_lib/credits.js, kind='grant', ref_type='referral_activation') so the+// grant is atomic, idempotent, and shows up in the user's credits history with+// no new balance table.+//+// Everything here is best-effort: a reward failure can never break the+// activation it is reacting to. Callers fire-and-forget.++import { createHash } from 'crypto';+import { sql } from './db.js';+import { creditAccount } from './credits.js';+import { recordEvent } from './usage.js';+import { insertNotification } from './notify.js';++// ── Config ─────────────────────────────────────────────────────────────────────+// Reward amounts and abuse caps are env-tunable so growth can dial the loop+// without a redeploy. Defaults are deliberately modest: enough to be felt as a+// real welcome / thank-you, small enough that farming is unprofitable under the+// per-referrer monthly cap.++/**+ * Parse referral-reward config from an env-like object. Pure — no I/O — so the+ * defaults and clamps are unit-testable. Negative or non-finite inputs fall back+ * to the default; amounts are clamped to a sane ceiling so a fat-fingered env+ * var can't mint a fortune.+ *+ * @param {Record<string,string|undefined>} [e]+ * @returns {{ enabled: boolean, referredUsd: number, referrerUsd: number, monthlyCap: number }}+ */+export function parseRewardConfig(e = process.env) {+ const num = (raw, dflt, max) => {+ const v = Number.parseFloat(raw);+ if (!Number.isFinite(v) || v < 0) return dflt;+ return Math.min(v, max);+ };+ const int = (raw, dflt, max) => {+ const v = Number.parseInt(raw, 10);+ if (!Number.isFinite(v) || v < 0) return dflt;+ return Math.min(v, max);+ };+ // Off by default unless explicitly disabled — the loop should run in prod.+ const enabled = String(e.REFERRAL_REWARDS_ENABLED ?? 'true').toLowerCase() !== 'false';+ return {+ enabled,+ referredUsd: num(e.REFERRAL_REFERRED_REWARD_USD, 1.0, 100),+ referrerUsd: num(e.REFERRAL_REFERRER_REWARD_USD, 2.0, 100),+ // Max rewarded activations a single referrer can earn per rolling 30 days.+ // Caps farm-and-burn rings without throttling a genuinely viral member —+ // raise via env for a real influencer.+ monthlyCap: int(e.REFERRAL_ACTIVATION_MONTHLY_CAP, 200, 100_000),+ };+}++// ── Viral funnel math (pure) ─────────────────────────────────────────────────────++/**+ * k-factor: the number of NEW referred signups each sharing user brings in over+ * a window. k > 1 is self-sustaining viral growth. Defined as+ * referred-signups ÷ distinct-sharers (users who drove at least one tracked+ * referral visit in the window). Returns 0 when nobody shared.+ *+ * @param {{ signups: number, sharers: number }} args+ * @returns {number} k, rounded to 3 decimals+ */+export function computeKFactor({ signups, sharers }) {+ const s = Number(signups) || 0;+ const n = Number(sharers) || 0;+ if (n <= 0) return 0;+ return Math.round((s / n) * 1000) / 1000;+}++/**+ * Safe conversion rate (0..1, 3 decimals). 0 when the denominator is 0.+ * @param {number} numerator+ * @param {number} denominator+ * @returns {number}+ */+export function conversionRate(numerator, denominator) {+ const a = Number(numerator) || 0;+ const b = Number(denominator) || 0;+ if (b <= 0) return 0;+ return Math.round((a / b) * 1000) / 1000;+}++/**+ * Deterministic, non-reversible visitor fingerprint for referral-visit dedup.+ * Hashes IP + user-agent + code so the same person hitting the same link is+ * counted once per day — without ever storing the raw IP/UA. Code is folded in+ * so the same visitor on two different links counts as two visits (correct: two+ * distinct shares reached them).+ *+ * @param {{ ip?: string, ua?: string, code: string }} args+ * @returns {string} 64-char hex sha256+ */+export function referralVisitorHash({ ip = '', ua = '', code = '' }) {+ return createHash('sha256')+ .update(`${ip}|${ua}|${String(code).toUpperCase()}`)+ .digest('hex');+}++// ── Reward grant (write side) ────────────────────────────────────────────────────++/**+ * Grant the two-sided activation reward when a referred user reaches their first+ * win. Idempotent and abuse-guarded:+ *+ * • No-op for organic users (no referrer attributed).+ * • The referred-side grant is keyed `referral:activation:referred:<id>` and the+ * referrer-side grant `referral:activation:referrer:<id>` — both keyed on the+ * REFERRED user's id, so each fires exactly once ever (the credit ledger's+ * unique idempotency_key enforces this even under concurrent activations).+ * • Self-referral is structurally impossible (referred_by_id can't be self),+ * but we re-check and skip anyway.+ * • The referrer reward is skipped once they've earned `monthlyCap` activation+ * rewards in the trailing 30 days — farming N throwaway accounts past the cap+ * earns the ring nothing. The referred-side welcome credit still applies (it's+ * one-time per real account and harmless).+ *+ * Never throws — wraps all work so it can't break the activation that triggered+ * it. Returns a summary for logging/telemetry.+ *+ * @param {{ referredUserId: string }} args+ * @returns {Promise<{ granted: boolean, reason?: string, referredCredited?: boolean, referrerCredited?: boolean, referrerCapped?: boolean }>}+ */+export async function grantReferralActivationReward({ referredUserId }) {+ const cfg = parseRewardConfig();+ if (!cfg.enabled) return { granted: false, reason: 'disabled' };+ if (!referredUserId) return { granted: false, reason: 'no_user' };++ try {+ const [user] = await sql`+ select id, referred_by_id, display_name, username+ from users+ where id = ${referredUserId} and deleted_at is null+ `;+ if (!user) return { granted: false, reason: 'user_not_found' };+ if (user.referred_by_id == null) return { granted: false, reason: 'organic' };+ const referrerId = user.referred_by_id;+ if (String(referrerId) === String(referredUserId)) {+ return { granted: false, reason: 'self_referral' };+ }++ const [referrer] = await sql`+ select id, display_name, username from users+ where id = ${referrerId} and deleted_at is null+ `;+ // Referrer deleted/closed since signup — still welcome the new user.+ const referrerLive = !!referrer;++ const referredName = user.display_name || user.username || null;+ const referrerName = referrer?.display_name || referrer?.username || null;++ // 1) Welcome credit for the newly-activated referred user.+ let referredCredited = false;+ if (cfg.referredUsd > 0) {+ const r = await creditAccount({+ userId: referredUserId,+ amountUsd: cfg.referredUsd,+ kind: 'grant',+ action: 'referral.activation',+ refType: 'referral_activation',+ refId: String(referredUserId),+ idempotencyKey: `referral:activation:referred:${referredUserId}`,+ meta: { role: 'referred', referrer_user_id: String(referrerId) },+ });+ referredCredited = !r.replay;+ if (referredCredited) {+ recordEvent({+ userId: referredUserId,+ kind: 'referral_activation',+ meta: { role: 'referred', amount_usd: cfg.referredUsd, referrer_user_id: String(referrerId) },+ });+ insertNotification(referredUserId, 'referral_reward', {+ role: 'referred',+ amount_usd: cfg.referredUsd,+ from_name: referrerName,+ });+ }+ }++ // 2) Thank-you credit for the referrer — capped per rolling 30 days.+ let referrerCredited = false;+ let referrerCapped = false;+ if (referrerLive && cfg.referrerUsd > 0) {+ const [{ count }] = await sql`+ select count(*)::int as count from credit_ledger+ where user_id = ${referrerId}+ and ref_type = 'referral_activation'+ and kind = 'grant'+ and created_at > now() - interval '30 days'+ `;+ if (Number(count) >= cfg.monthlyCap) {+ referrerCapped = true;+ } else {+ const r = await creditAccount({+ userId: referrerId,+ amountUsd: cfg.referrerUsd,+ kind: 'grant',+ action: 'referral.activation',+ refType: 'referral_activation',+ refId: String(referredUserId),+ idempotencyKey: `referral:activation:referrer:${referredUserId}`,+ meta: { role: 'referrer', referred_user_id: String(referredUserId) },+ });+ referrerCredited = !r.replay;+ if (referrerCredited) {+ recordEvent({+ userId: referrerId,+ kind: 'referral_activation',+ meta: { role: 'referrer', amount_usd: cfg.referrerUsd, referred_user_id: String(referredUserId) },+ });+ insertNotification(referrerId, 'referral_reward', {+ role: 'referrer',+ amount_usd: cfg.referrerUsd,+ referred_name: referredName,+ });+ }+ }+ }++ return { granted: referredCredited || referrerCredited, referredCredited, referrerCredited, referrerCapped };+ } catch (err) {+ console.error('[referral-rewards] grant failed', err?.message);+ return { granted: false, reason: 'error' };+ }+}diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 4d7412aee..9424b343a 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -878,6 +878,22 @@ alter table usage_events add column if not exists cost_micro_usd bigint;create index if not exists usage_events_llm_time on usage_events(created_at desc) where kind = 'llm';create index if not exists usage_events_llm_provider_time on usage_events(provider, created_at desc) where kind = 'llm' and provider is not null;+-- Usage metering ledger (see migrations/20260623170000_usage_metering.sql).+-- Money is stored in USDC atomics (6 decimals) as bigint so statement sums never+-- drift. Metered rows carry kind='metered' and an idempotency_key so a retried+-- settlement meters EXACTLY once.+alter table usage_events add column if not exists meter_action text;+alter table usage_events add column if not exists units int;+alter table usage_events add column if not exists price_usdc_atomics bigint;+alter table usage_events add column if not exists fee_usdc_atomics bigint;+alter table usage_events add column if not exists discount_bps int;+alter table usage_events add column if not exists settlement_ref text;+alter table usage_events add column if not exists settlement_kind text;+alter table usage_events add column if not exists idempotency_key text;+create unique index if not exists usage_events_idem on usage_events(idempotency_key) where idempotency_key is not null;+create index if not exists usage_events_settlement on usage_events(settlement_ref) where settlement_ref is not null;+create index if not exists usage_events_metered_user_time on usage_events(user_id, created_at desc) where kind = 'metered';+-- ── agent_registrations_pending — transient prep records for 2-step registration ─────create table if not exists agent_registrations_pending (id uuid primary key default gen_random_uuid(),@@ -1914,3 +1930,61 @@ CREATE INDEX IF NOT EXISTS x_pending_reviews_user_pending-- ── club_tips — backfill amount_atomics ──────────────────────────────────────ALTER TABLE club_tips ADD COLUMN IF NOT EXISTS amount_atomics numeric;++-- ── PWA & notifications (task 39) ────────────────────────────────────────────+-- Web Push endpoints, the unified preference center, the sent→opened→returned+-- funnel, and the double opt-in newsletter list. Full rationale lives in the+-- dated migration 20260628000000_push_and_notification_prefs.sql; mirrored here+-- so a clean schema.sql apply provisions the tables.+create table if not exists push_subscriptions (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references users(id) on delete cascade,+ endpoint text not null,+ p256dh text not null,+ auth text not null,+ user_agent text,+ created_at timestamptz not null default now(),+ last_seen_at timestamptz not null default now()+);+create unique index if not exists push_subscriptions_endpoint+ on push_subscriptions (endpoint);+create index if not exists push_subscriptions_user+ on push_subscriptions (user_id, created_at desc);++create table if not exists notification_preferences (+ user_id uuid primary key references users(id) on delete cascade,+ prefs jsonb not null default '{}'::jsonb,+ updated_at timestamptz not null default now()+);++create table if not exists notification_events (+ id bigint generated always as identity primary key,+ notification_id uuid references user_notifications(id) on delete cascade,+ user_id uuid not null references users(id) on delete cascade,+ channel text not null check (channel in ('in_app','push','email','telegram')),+ event text not null check (event in ('sent','opened','returned')),+ meta jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now()+);+create index if not exists notification_events_notif+ on notification_events (notification_id);+create index if not exists notification_events_funnel+ on notification_events (event, channel, created_at desc);+create unique index if not exists notification_events_once+ on notification_events (notification_id, channel, event)+ where notification_id is not null and event in ('opened','returned');++create table if not exists newsletter_subscribers (+ id uuid primary key default gen_random_uuid(),+ email citext not null unique,+ status text not null default 'pending'+ check (status in ('pending','confirmed','unsubscribed')),+ confirm_token text not null,+ locale text,+ source text,+ created_at timestamptz not null default now(),+ confirmed_at timestamptz,+ unsubbed_at timestamptz+);+create index if not exists newsletter_subscribers_token+ on newsletter_subscribers (confirm_token);diff --git a/api/_lib/splits.js b/api/_lib/splits.jsnew file mode 100644index 000000000..e8691ab82--- /dev/null+++ b/api/_lib/splits.js@@ -0,0 +1,421 @@+// Multi-collaborator payment splits for marketplace listings.+// ---------------------------------------------------------------------------+// A skill or asset can be authored by more than one person. When it sells, each+// collaborator must receive their EXACT share of the creator's net (the amount+// left after the platform fee) — atomically, with no rounding leak and no+// platform custody of the difference.+//+// Two layers, mirroring the rest of the economics lane (fee/royalty/license):+//+// 1. Pure money math (always available, no deps): validate that shares sum to+// 100%, and split an atomic amount across N recipients so the parts sum+// back to the whole EXACTLY (largest-remainder apportionment — every+// leftover atomic is assigned, never floored away). These are the functions+// the tests pin: fee + creator-net = price, and Σ recipient atomics = net.+//+// 2. On-chain routing (EVM, via @0xsplits/splits-sdk): for a multi-party EVM+// listing we resolve/create an immutable 0xSplits contract and use ITS+// address as the listing's payout target, so the creator's net flows on+// chain into the split and 0xSplits distributes to each collaborator —+// trustless, no custody. When the SDK or an EVM signer is unavailable, or+// the listing settles on Solana (0xSplits is EVM-only), the split degrades+// to a recorded ledger ("ledger" mode): each recipient's exact allocation+// is written to `split_distributions` and surfaced on the creator+// dashboard. We NEVER fabricate a split address we did not actually create.+//+// A single-creator listing has no split row at all and pays the creator+// directly — zero split overhead on the common path.++import { isValidEvmAddress, isValidSolanaAddress } from './validate.js';++/** Hard cap on collaborators per listing — a sane bound, not a business limit.+ * 0xSplits itself supports many; this guards a fat-fingered payload. */+export const MAX_SPLIT_RECIPIENTS = 50;++/** Basis-point total a valid split must reach (100.00%). */+export const FULL_SHARE_BPS = 10_000;++// Build an Error carrying an HTTP status + machine code, matching the+// MonetizationService.svcError convention so handlers map it uniformly.+function splitError(status, code, message) {+ return Object.assign(new Error(message), { status, code });+}++/**+ * Validate an address for a chain. `base`/`evm` are EVM-family; `solana` is+ * base58. Returns true/false — callers decide whether to throw.+ */+export function isValidAddressForChain(address, chain) {+ if (!address || typeof address !== 'string') return false;+ if (chain === 'solana') return isValidSolanaAddress(address);+ return isValidEvmAddress(address); // base, evm, and EVM chain aliases+}++/**+ * Normalize + validate a set of split recipients. Accepts shares expressed+ * either as basis points (`share_bps`, integer) or whole/decimal percent+ * (`percent` / `share`), and normalizes everything to integer basis points.+ *+ * Rules (all enforced):+ * • 1..MAX_SPLIT_RECIPIENTS recipients.+ * • Each address is valid for `chain` and unique (case-insensitive).+ * • Each share is a positive integer number of basis points.+ * • Shares sum to EXACTLY 10000 bps (100%).+ *+ * @param {Array<{address:string, share_bps?:number, percent?:number, share?:number,+ * recipient_user_id?:string|null, label?:string|null}>} recipients+ * @param {string} chain - 'solana' | 'base' | 'evm'+ * @returns {Array<{address:string, share_bps:number, recipient_user_id:string|null, label:string|null}>}+ * @throws 400 invalid_split with a precise reason.+ */+export function validateShares(recipients, chain) {+ if (!Array.isArray(recipients) || recipients.length === 0) {+ throw splitError(400, 'invalid_split', 'a split needs at least one recipient');+ }+ if (recipients.length > MAX_SPLIT_RECIPIENTS) {+ throw splitError(400, 'invalid_split', `a split may have at most ${MAX_SPLIT_RECIPIENTS} recipients`);+ }++ const seen = new Set();+ const normalized = recipients.map((r, i) => {+ const address = typeof r?.address === 'string' ? r.address.trim() : '';+ if (!isValidAddressForChain(address, chain)) {+ throw splitError(400, 'invalid_split', `recipient ${i + 1} has an invalid ${chain} address`);+ }+ const key = address.toLowerCase();+ if (seen.has(key)) {+ throw splitError(400, 'invalid_split', `recipient ${address} appears more than once`);+ }+ seen.add(key);++ // Resolve the share to integer basis points. Prefer explicit bps; else+ // accept percent (whole or decimal) and convert with no precision loss+ // for the common 2-decimal case.+ let bps;+ if (r.share_bps != null) {+ bps = Number(r.share_bps);+ } else if (r.percent != null || r.share != null) {+ const pct = Number(r.percent != null ? r.percent : r.share);+ bps = Math.round(pct * 100);+ } else {+ throw splitError(400, 'invalid_split', `recipient ${i + 1} is missing a share`);+ }+ if (!Number.isInteger(bps) || bps <= 0) {+ throw splitError(400, 'invalid_split', `recipient ${i + 1} has an invalid share`);+ }++ return {+ address,+ share_bps: bps,+ recipient_user_id: r.recipient_user_id ?? null,+ label: typeof r.label === 'string' && r.label.trim() ? r.label.trim().slice(0, 80) : null,+ };+ });++ const total = normalized.reduce((s, r) => s + r.share_bps, 0);+ if (total !== FULL_SHARE_BPS) {+ const pct = (total / 100).toFixed(2);+ throw splitError(400, 'invalid_split', `split shares must sum to 100% (got ${pct}%)`);+ }+ return normalized;+}++/**+ * Apportion `totalAtomics` across recipients by their basis-point shares so the+ * parts sum back to the whole EXACTLY. Largest-remainder method: every recipient+ * gets floor(total·bps/10000), then the leftover atomics (total − Σ floors) are+ * handed out one at a time to the recipients with the largest fractional+ * remainder (ties broken by larger share, then original order). No atomic is+ * ever lost or invented — Σ allocations === totalAtomics for any input.+ *+ * @param {bigint|number|string} totalAtomics+ * @param {Array<{share_bps:number}>} recipients - validated (Σ bps === 10000)+ * @returns {Array<T & {amount: bigint}>} same recipients with an exact `amount`+ */+export function allocateAtomics(totalAtomics, recipients) {+ const total = typeof totalAtomics === 'bigint' ? totalAtomics : BigInt(String(totalAtomics ?? '0').split('.')[0]);+ if (total < 0n) throw splitError(400, 'invalid_split', 'cannot split a negative amount');+ if (!recipients?.length) return [];++ const totalBps = BigInt(recipients.reduce((s, r) => s + r.share_bps, 0));+ if (totalBps === 0n) throw splitError(400, 'invalid_split', 'split shares sum to zero');++ // Base (floored) allocation + the remainder for each, both off the same+ // denominator so the apportionment is exact and order-independent.+ let assigned = 0n;+ const parts = recipients.map((r, index) => {+ const numerator = total * BigInt(r.share_bps);+ const base = numerator / totalBps;+ const remainder = numerator % totalBps; // fractional part, scaled by totalBps+ assigned += base;+ return { ...r, amount: base, _remainder: remainder, _index: index };+ });++ // Hand out the leftover atomics to the largest remainders first.+ let leftover = total - assigned;+ const order = [...parts].sort((a, b) => {+ if (a._remainder !== b._remainder) return a._remainder > b._remainder ? -1 : 1;+ if (a.share_bps !== b.share_bps) return b.share_bps - a.share_bps;+ return a._index - b._index;+ });+ for (let i = 0; i < order.length && leftover > 0n; i++) {+ order[i].amount += 1n;+ leftover -= 1n;+ }++ return parts.map(({ _remainder, _index, ...rest }) => rest);+}++/**+ * A buyer-facing description of a proceeds split, e.g. "70 / 30". Pure; used in+ * the purchase quote and on the listing so the buyer sees where money goes.+ *+ * @param {Array<{share_bps:number, label?:string|null, address?:string}>} recipients+ * @returns {{ label: string, recipients: Array<{share_bps:number, percent:number, label:string|null}> }}+ */+export function describeSplit(recipients) {+ const parts = (recipients || []).map((r) => ({+ share_bps: r.share_bps,+ percent: Math.round((r.share_bps / 100) * 100) / 100,+ label: r.label ?? null,+ ...(r.address ? { address: r.address } : {}),+ }));+ const label = parts.map((p) => (Number.isInteger(p.percent) ? String(p.percent) : p.percent.toFixed(2))).join(' / ');+ return { label, recipients: parts };+}++// ── Persistence ────────────────────────────────────────────────────────────++/**+ * Read the active split for a listing, or null when single-creator. Returns the+ * config row plus its ordered recipients.+ *+ * @param {Function} sql - tagged-template client+ * @param {string} agentId+ * @param {string} skill+ * @returns {Promise<null | { id, agent_id, skill, chain, split_address, split_mode,+ * owner_address, recipients: Array<{address, share_bps, recipient_user_id, label}> }>}+ */+export async function resolveListingSplit(sql, agentId, skill) {+ const [cfg] = await sql`+ SELECT id, agent_id, skill, chain, split_address, split_mode, owner_address+ FROM listing_splits+ WHERE agent_id = ${agentId} AND skill = ${skill}+ `;+ if (!cfg) return null;+ const recipients = await sql`+ SELECT address, share_bps, recipient_user_id, label+ FROM listing_split_recipients+ WHERE split_id = ${cfg.id}+ ORDER BY share_bps DESC, created_at ASC+ `;+ if (recipients.length === 0) return null;+ return { ...cfg, recipients };+}++/**+ * Create or replace the split config for a listing in one transaction. Validates+ * shares first (throws on invalid). For EVM listings, best-effort resolves an+ * on-chain 0xSplits address; failure to reach the chain degrades to ledger mode+ * (the allocation is still enforced off-chain) rather than blocking the listing.+ *+ * @param {Function} sql+ * @param {object} o+ * @param {string} o.agentId+ * @param {string} o.skill+ * @param {string} o.chain+ * @param {Array} o.recipients - raw recipients (validated here)+ * @param {string|null} [o.createdBy] - user id setting the split+ * @param {boolean} [o.mutable] - if true, keep an owner who can update the split+ * @returns {Promise<{ split_id:string, split_mode:'onchain'|'ledger', split_address:string|null,+ * recipients:Array }>}+ */+export async function persistListingSplit(sql, { agentId, skill, chain, recipients, createdBy = null, mutable = false }) {+ const normalized = validateShares(recipients, chain);++ // Try to anchor the split on-chain for EVM listings. Never block listing+ // creation on it — a chain/SDK hiccup degrades to a recorded ledger split.+ let splitAddress = null;+ let splitMode = 'ledger';+ let ownerAddress = null;+ if (chain !== 'solana') {+ try {+ const onchain = await createOnchainSplit({ recipients: normalized, chain, mutable });+ if (onchain?.address) {+ splitAddress = onchain.address;+ splitMode = 'onchain';+ ownerAddress = onchain.ownerAddress ?? null;+ }+ } catch (e) {+ console.warn('[splits] on-chain split unavailable, using ledger mode', e?.message);+ }+ }++ const [cfg] = await sql`+ INSERT INTO listing_splits (agent_id, skill, chain, split_address, split_mode, owner_address, created_by)+ VALUES (${agentId}, ${skill}, ${chain}, ${splitAddress}, ${splitMode}, ${ownerAddress}, ${createdBy})+ ON CONFLICT (agent_id, skill) DO UPDATE SET+ chain = EXCLUDED.chain,+ split_address = EXCLUDED.split_address,+ split_mode = EXCLUDED.split_mode,+ owner_address = EXCLUDED.owner_address,+ updated_at = now()+ RETURNING id+ `;+ const splitId = cfg.id;++ // Replace recipients atomically.+ await sql`DELETE FROM listing_split_recipients WHERE split_id = ${splitId}`;+ for (const r of normalized) {+ await sql`+ INSERT INTO listing_split_recipients (split_id, recipient_user_id, address, chain, share_bps, label)+ VALUES (${splitId}, ${r.recipient_user_id}, ${r.address}, ${chain}, ${r.share_bps}, ${r.label})+ `;+ }++ return { split_id: splitId, split_mode: splitMode, split_address: splitAddress, recipients: normalized };+}++/**+ * Remove a listing's split (revert to single-creator). Idempotent.+ */+export async function clearListingSplit(sql, agentId, skill) {+ await sql`DELETE FROM listing_splits WHERE agent_id = ${agentId} AND skill = ${skill}`;+}++/**+ * Record how a confirmed purchase's creator-net was divided among collaborators.+ * Idempotent per (purchase, address) so a retried confirm never double-credits.+ * In "onchain" mode the net already flowed into the 0xSplits contract on chain,+ * so rows are stamped settled (informational, for the dashboard); in "ledger"+ * mode rows are 'accrued' and each recipient withdraws their share via the+ * normal payout flow.+ *+ * @param {Function} sql+ * @param {object} o+ * @param {string} o.purchaseId+ * @param {object} o.split - from resolveListingSplit (has id, split_mode, recipients)+ * @param {bigint|string} o.netAtomics - the creator's net (after platform fee)+ * @param {string} o.currencyMint+ * @param {string} o.chain+ * @returns {Promise<Array<{address, recipient_user_id, share_bps, amount:string, mode, status}>>}+ */+export async function recordSplitDistribution(sql, { purchaseId, split, netAtomics, currencyMint, chain }) {+ const allocations = allocateAtomics(netAtomics, split.recipients);+ const mode = split.split_mode === 'onchain' ? 'onchain' : 'ledger';+ const status = mode === 'onchain' ? 'settled' : 'accrued';++ const out = [];+ for (const a of allocations) {+ await sql`+ INSERT INTO split_distributions+ (purchase_id, split_id, recipient_user_id, address, share_bps, amount, currency_mint, chain, mode, status)+ VALUES+ (${purchaseId}, ${split.id}, ${a.recipient_user_id}, ${a.address}, ${a.share_bps},+ ${a.amount.toString()}, ${currencyMint}, ${chain}, ${mode}, ${status})+ ON CONFLICT (purchase_id, address) DO NOTHING+ `;+ out.push({+ address: a.address,+ recipient_user_id: a.recipient_user_id,+ share_bps: a.share_bps,+ amount: a.amount.toString(),+ mode,+ status,+ });+ }+ return out;+}++// ── On-chain (0xSplits, EVM) ─────────────────────────────────────────────────++const EVM_CHAIN_IDS = { base: 8453, evm: 8453, ethereum: 1, optimism: 10, arbitrum: 42161, polygon: 137 };++/** Resolve a numeric EVM chain id from a chain label, or null. */+export function evmChainIdForSplit(chain) {+ if (typeof chain === 'number') return chain;+ return EVM_CHAIN_IDS[String(chain).toLowerCase()] ?? null;+}++/**+ * Create (or deterministically predict) an immutable 0xSplits contract for a set+ * of recipients on an EVM chain, returning its address. Uses the platform's EVM+ * signer to deploy. Returns null when the SDK, a signer, or the chain is+ * unavailable — the caller then falls back to ledger mode. Pure-read predict is+ * preferred (the immutable split address is deterministic from the recipient+ * set), so the same collaborators always resolve to the same contract.+ *+ * @param {object} o+ * @param {Array<{address:string, share_bps:number}>} o.recipients - validated+ * @param {string} o.chain+ * @param {boolean} [o.mutable]+ * @returns {Promise<{ address:string, ownerAddress:string|null } | null>}+ */+export async function createOnchainSplit({ recipients, chain, mutable = false }) {+ const chainId = evmChainIdForSplit(chain);+ if (!chainId) return null;++ const pk = process.env.EVM_TREASURY_PRIVATE_KEY || process.env.SPLITS_SIGNER_PRIVATE_KEY;+ if (!pk) return null;++ let SplitsClient;+ try {+ ({ SplitsClient } = await import('@0xsplits/splits-sdk'));+ } catch {+ return null; // SDK not resolvable in this environment → ledger mode+ }+ if (!SplitsClient) return null;++ const [{ createPublicClient, http }, { privateKeyToAccount }, viemChains] = await Promise.all([+ import('viem'),+ import('viem/accounts'),+ import('viem/chains'),+ ]);+ const chainMap = {+ 1: viemChains.mainnet, 8453: viemChains.base, 10: viemChains.optimism,+ 42161: viemChains.arbitrum, 137: viemChains.polygon,+ };+ const viemChain = chainMap[chainId];+ if (!viemChain) return null;++ const account = privateKeyToAccount(pk.startsWith('0x') ? pk : `0x${pk}`);+ const rpcUrl = process.env[`EVM_RPC_URL_${chainId}`] || undefined;+ const publicClient = createPublicClient({ chain: viemChain, transport: http(rpcUrl) });+ const { createWalletClient } = await import('viem');+ const walletClient = createWalletClient({ account, chain: viemChain, transport: http(rpcUrl) });++ const client = new SplitsClient({ chainId, publicClient, walletClient }).splitV1;++ // 0xSplits expects percentAllocation as a percentage number summing to 100,+ // with at most a couple of decimals. bps/100 is exact for our integer bps.+ const sdkRecipients = recipients.map((r) => ({ address: r.address, percentAllocation: r.share_bps / 100 }));++ // Immutable split (no controller) is deterministic — predict its address and+ // only deploy if it isn't already on chain.+ const ownerAddress = mutable ? account.address : null;+ if (!mutable) {+ const predicted = await client.predictImmutableSplitAddress({+ recipients: sdkRecipients,+ distributorFeePercent: 0,+ });+ const addr = predicted?.splitAddress || predicted?.address || predicted;+ if (predicted?.splitExists && addr) return { address: addr, ownerAddress: null };+ // Deploy the deterministic immutable split.+ const created = await client.createSplit({+ recipients: sdkRecipients,+ distributorFeePercent: 0,+ controller: undefined,+ });+ const createdAddr = created?.splitId || created?.splitAddress || addr;+ if (createdAddr) return { address: createdAddr, ownerAddress: null };+ return null;+ }++ const created = await client.createSplit({+ recipients: sdkRecipients,+ distributorFeePercent: 0,+ controller: account.address,+ });+ const createdAddr = created?.splitId || created?.splitAddress || null;+ return createdAddr ? { address: createdAddr, ownerAddress } : null;+}diff --git a/api/_lib/stage-split.js b/api/_lib/stage-split.jsnew file mode 100644index 000000000..9a14fa368--- /dev/null+++ b/api/_lib/stage-split.js@@ -0,0 +1,123 @@+// Living Stages — tip settlement validation + split math.+//+// A tip on a live stage is a REAL on-chain settlement: the audience member+// transfers $THREE (or USDC, where the platform's pay path already allows it)+// directly to the host agent's wallet, then POSTs the settlement signature here.+// The full amount lands in the host wallet on-chain; this module computes the+// ACCOUNTING split — the portion the host keeps vs. the portion owed onward to+// the venue/owner per the stage's `tip_split_bps` policy — and the validation+// discipline that keeps a forged "someone tipped 5,000 $THREE" row out of the+// ledger. Everything here is pure + integer-only (atomic units) so the split can+// never drift a lamport and the rules are unit-testable without a DB or a socket.+//+// Mirrors api/irl/interactions.js' pay discipline verbatim (same regexes, same+// allowed mints) — a tip is the same class of caller-asserted money event, so it+// earns the same "no settlement proof, no row" guard. $THREE is the only coin+// this platform promotes; USDC rides only because the existing IRL pay path+// already accepts it for settlement. No new asset is introduced here.++// $THREE — the one and only coin three.ws references.+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+// USDC, the sole other settlement asset the platform's existing pay path accepts.+const USDC_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const USDC_BASE = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913';++// Lowercased lookup so an EVM address compares case-insensitively; the two+// case-sensitive base58 mints are matched verbatim.+const ALLOWED_TIP_MINTS = new Set([THREE_MINT, USDC_SOLANA, USDC_BASE]);++// 0x… EVM tx hash, or base58 Solana signature — the two settlement shapes the+// platform produces. A tip without one of these is never recorded.+const EVM_TX_RE = /^0x[0-9a-fA-F]{64}$/;+const SOL_SIG_RE = /^[1-9A-HJ-NP-Za-km-z]{43,88}$/;++export function isValidTipSignature(sig) {+ return typeof sig === 'string' && (EVM_TX_RE.test(sig) || SOL_SIG_RE.test(sig));+}++export function isAllowedTipMint(mint) {+ if (typeof mint !== 'string' || !mint) return false;+ return ALLOWED_TIP_MINTS.has(mint) || ALLOWED_TIP_MINTS.has(mint.toLowerCase());+}++// Block-explorer deep link for a settlement, picking the chain from the signature+// shape (EVM tx hash → Basescan) or an explicit network hint, defaulting to+// Solscan. Surfaced in the tip event + owner notification so the receipt is one+// tap away.+export function tipExplorerUrl(sig, network) {+ if (!sig) return null;+ const net = String(network || '').toLowerCase();+ if (EVM_TX_RE.test(sig) || net.includes('base') || net.includes('eip155')) {+ return `https://basescan.org/tx/${sig}`;+ }+ return `https://solscan.io/tx/${sig}`;+}++// Default venue cut if a stage hasn't set one: 10% (1000 bps) to the venue/owner,+// 90% to the host. Stages may override per their policy.+export const DEFAULT_TIP_SPLIT_BPS = 1000;+const MAX_BPS = 10_000;++// Coerce a basis-points policy to a sane integer in [0, 10000]. A non-finite or+// out-of-range value falls back to the platform default rather than ever letting+// the venue keep a negative or >100% cut.+export function normalizeSplitBps(bps) {+ const n = Math.trunc(Number(bps));+ if (!Number.isFinite(n) || n < 0 || n > MAX_BPS) return DEFAULT_TIP_SPLIT_BPS;+ return n;+}++// Parse a caller-supplied atomic-unit amount into a positive safe integer, or+// null. Money is integer atomic units end to end (no floats), so a fractional,+// zero, negative, NaN, or overflowing value is rejected outright.+export function parseAtomicAmount(value) {+ const n = typeof value === 'number' ? value : Number(value);+ if (!Number.isInteger(n) || n <= 0 || n > Number.MAX_SAFE_INTEGER) return null;+ return n;+}++/**+ * Split a tip (in atomic units) into the host's credit and the venue's cut.+ *+ * The venue cut is floored so the two parts always sum to exactly the original+ * amount — the rounding remainder is handed to the HOST, never minted out of+ * thin air. Pure integer math: splitTip(x).hostCredit + splitTip(x).venueCut === x+ * for every valid x, which the unit suite asserts across a fuzz range.+ *+ * @param {number} amountAtomic positive integer atomic units (already parsed)+ * @param {number} splitBps venue cut in basis points (0–10000)+ * @returns {{ hostCredit: number, venueCut: number, splitBps: number }}+ */+export function splitTip(amountAtomic, splitBps = DEFAULT_TIP_SPLIT_BPS) {+ const amount = parseAtomicAmount(amountAtomic);+ if (amount === null) throw new Error('splitTip: amount must be a positive integer (atomic units)');+ const bps = normalizeSplitBps(splitBps);+ // Floor the venue cut; the host absorbs the remainder so the parts reconcile+ // to the penny (atomic unit) against the on-chain total.+ const venueCut = Math.floor((amount * bps) / MAX_BPS);+ const hostCredit = amount - venueCut;+ return { hostCredit, venueCut, splitBps: bps };+}++// One place to validate an inbound tip body before it touches the DB. Returns+// either { ok:true, amount, mint, signature, network } or { ok:false, error }.+// Used by POST /api/stage/tip; pure so the rules are tested in isolation.+export function validateTipPayload({ signature, currencyMint, amount, network } = {}) {+ if (!isValidTipSignature(signature)) {+ return { ok: false, error: 'tip requires a valid on-chain settlement signature' };+ }+ if (!isAllowedTipMint(currencyMint)) {+ return { ok: false, error: 'currency_mint must be $THREE or USDC' };+ }+ const parsed = parseAtomicAmount(amount);+ if (parsed === null) {+ return { ok: false, error: 'amount must be a positive integer in atomic units' };+ }+ return {+ ok: true,+ amount: parsed,+ mint: currencyMint,+ signature,+ network: typeof network === 'string' ? network.slice(0, 32) : null,+ };+}diff --git a/api/_lib/web-push.js b/api/_lib/web-push.jsnew file mode 100644index 000000000..0108a9d6e--- /dev/null+++ b/api/_lib/web-push.js@@ -0,0 +1,103 @@+// Web Push (VAPID) delivery. Sends an OS-level notification to every device a+// user has subscribed. Dead endpoints (404/410) are pruned automatically, so+// the push_subscriptions table self-heals as browsers expire subscriptions.+//+// Required env:+// VAPID_PUBLIC_KEY — base64url public key (also exposed to the client)+// VAPID_PRIVATE_KEY — base64url private key (secret)+// VAPID_SUBJECT — mailto: or https: contact (default mailto:[email protected])+//+// Generate a keypair once with: npx web-push generate-vapid-keys+//+// All sends are fire-and-forget — callers never await for correctness.++import { sql } from './db.js';++let _configured = null; // null = not yet attempted, false = unavailable, true = ready+let _webpush = null;++export function vapidPublicKey() {+ return (process.env.VAPID_PUBLIC_KEY || '').trim();+}++export function pushConfigured() {+ return Boolean(vapidPublicKey() && (process.env.VAPID_PRIVATE_KEY || '').trim());+}++// Lazy-load the web-push module + configure VAPID exactly once. Returns the+// configured module, or null when keys are absent (dev / preview deploys) so+// callers degrade to in-app-only without throwing.+async function webpush() {+ if (_configured === false) return null;+ if (_configured === true) return _webpush;+ if (!pushConfigured()) {+ _configured = false;+ return null;+ }+ const mod = await import('web-push');+ _webpush = mod.default || mod;+ _webpush.setVapidDetails(+ (process.env.VAPID_SUBJECT || 'mailto:[email protected]').trim(),+ vapidPublicKey(),+ (process.env.VAPID_PRIVATE_KEY || '').trim(),+ );+ _configured = true;+ return _webpush;+}++/**+ * Send a push payload to every subscription a user has. Returns the number of+ * subscriptions that accepted it. Prunes endpoints the push service reports as+ * gone (404/410). Safe to call when push is unconfigured (returns 0).+ *+ * @param {string} userId+ * @param {{ title: string, body: string, url?: string, tag?: string, notificationId?: string|null, category?: string }} payload+ */+export async function sendPushToUser(userId, payload) {+ const wp = await webpush();+ if (!wp) return 0;++ let subs;+ try {+ subs = await sql`+ select id, endpoint, p256dh, auth+ from push_subscriptions+ where user_id = ${userId}+ `;+ } catch (err) {+ console.error('[web-push] load subscriptions failed:', err.message);+ return 0;+ }+ if (!subs.length) return 0;++ const body = JSON.stringify(payload);+ const dead = [];+ let delivered = 0;++ await Promise.all(+ subs.map(async (s) => {+ const subscription = {+ endpoint: s.endpoint,+ keys: { p256dh: s.p256dh, auth: s.auth },+ };+ try {+ await wp.sendNotification(subscription, body, { TTL: 60 * 60 * 24 });+ delivered++;+ } catch (err) {+ const code = err?.statusCode;+ if (code === 404 || code === 410) {+ dead.push(s.id); // gone — prune+ } else {+ console.error('[web-push] send failed', code || err.message);+ }+ }+ }),+ );++ if (dead.length) {+ sql`delete from push_subscriptions where id = any(${dead})`.catch((e) =>+ console.error('[web-push] prune failed:', e.message),+ );+ }+ return delivered;+}diff --git a/api/avatars/from-forge.js b/api/avatars/from-forge.jsindex 3efd4cc71..7ab4660fb 100644--- a/api/avatars/from-forge.js+++ b/api/avatars/from-forge.js@@ -33,6 +33,7 @@ import { provisionAvatarAgent } from '../_lib/avatar-agent.js';import { maybeAutoRigAvatar } from '../_lib/auto-rig.js';import { limits } from '../_lib/rate-limit.js';import { recordEvent } from '../_lib/usage.js';+import { markActivated } from '../_lib/activation.js';import { env } from '../_lib/env.js';// Match the studio/reconstruct ceiling so a runaway model can't ingest an@@ -188,6 +189,9 @@ export default wrap(async (req, res) => {bytes: buf.length,meta: { source: 'chat-forge-avatar', rigged: Boolean(rigged) },});+ // First win: claimed a forged 3D model as an avatar. Activates the account+ // once and pays the two-sided referral reward when referred. Fire-and-forget.+ queueMicrotask(() => markActivated(auth.userId, { source: 'forge_save', meta: { avatarId: avatar.id } }));const viewUrl = `${env.APP_ORIGIN || ''}/discover/avatar/${avatar.id}`;return json(res, 201, { avatar, view_url: viewUrl });diff --git a/api/avatars/index.js b/api/avatars/index.jsindex b3c0b0402..7f52f8ec7 100644--- a/api/avatars/index.js+++ b/api/avatars/index.js@@ -13,6 +13,7 @@ import { maybeAutoRigAvatar } from '../_lib/auto-rig.js';import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';import { parse, createAvatarBody } from '../_lib/validate.js';import { recordEvent } from '../_lib/usage.js';+import { markActivated } from '../_lib/activation.js';import { dispatchWebhooks } from '../_lib/webhook-dispatch.js';import { z } from 'zod';@@ -170,6 +171,9 @@ async function handleCreate(req, res) {kind: 'upload',bytes: avatar.size_bytes,});+ // First win: a real avatar in hand. Activates the account once (and pays the+ // two-sided referral reward if this user was referred). Fire-and-forget.+ queueMicrotask(() => markActivated(auth.userId, { source: 'avatar_create', meta: { avatarId: avatar.id } }));return json(res, 201, { avatar });}diff --git a/api/billing/invoices.js b/api/billing/invoices.jsnew file mode 100644index 000000000..ecc386123--- /dev/null+++ b/api/billing/invoices.js@@ -0,0 +1,98 @@+// GET /api/billing/invoices — the periodic invoice statement.+//+// Rolls the user's metered usage_events over a period into a statement they can+// read, download, and reconcile against their wallet/card. Every line item+// traces to a settlement ref. Defaults to the current calendar month; accepts an+// explicit window or a `period=YYYY-MM`.+//+// ?period=2026-06 — a calendar month+// ?from=ISO&to=ISO — an explicit window+// ?format=csv — download the line items as CSV (printable PDF is+// produced client-side from the /account/billing page)+//+// Owner-scoped: a user only ever reads their own usage. Session or bearer auth.++import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { cors, json, text, method, wrap, error, rateLimited } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { rollupInvoice, reconciliationStatus, atomicsToUsd } from '../_lib/metering.js';++// Resolve the billing window from the query. Returns { from, to, label }.+function resolveWindow(params) {+ const period = params.get('period');+ if (period && /^\d{4}-\d{2}$/.test(period)) {+ const [y, m] = period.split('-').map(Number);+ const from = new Date(Date.UTC(y, m - 1, 1));+ const to = new Date(Date.UTC(y, m, 1));+ return { from, to, label: period };+ }++ const fromRaw = params.get('from');+ const toRaw = params.get('to');+ if (fromRaw || toRaw) {+ const from = fromRaw ? new Date(fromRaw) : new Date(Date.UTC(1970, 0, 1));+ const to = toRaw ? new Date(toRaw) : new Date();+ if (isNaN(from.getTime()) || isNaN(to.getTime())) return null;+ return { from, to, label: 'custom' };+ }++ // Default: current calendar month (UTC).+ const now = new Date();+ const from = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));+ const to = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1));+ const label = `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, '0')}`;+ return { from, to, label };+}++function toCsv(statement) {+ const head = 'action,label,count,units,gross_usd,fee_usd,discount_bps';+ const rows = statement.line_items.map(+ (l) =>+ `${l.action},"${String(l.label).replace(/"/g, '""')}",${l.count},${l.units},${l.gross_usd},${l.fee_usd},${l.discount_bps}`,+ );+ const total = `TOTAL,,${statement.totals.charge_count},,${statement.totals.gross_usd},${statement.totals.fee_usd},`;+ return [head, ...rows, total].join('\n') + '\n';+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ const userId = session?.id || bearer?.userId;+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.widgetRead(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const window = resolveWindow(params);+ if (!window) return error(res, 400, 'validation_error', 'from/to must be valid ISO-8601 dates');++ const statement = await rollupInvoice({ userId, from: window.from, to: window.to });+ const recon = await reconciliationStatus({ userId });++ if (params.get('format') === 'csv') {+ return text(res, 200, toCsv(statement), {+ 'content-type': 'text/csv; charset=utf-8',+ 'content-disposition': `attachment; filename="three-ws-invoice-${window.label}.csv"`,+ 'cache-control': 'no-store',+ });+ }++ return json(+ res,+ 200,+ {+ invoice: {+ period_label: window.label,+ period: statement.period,+ line_items: statement.line_items,+ totals: { ...statement.totals, net_usd: atomicsToUsd(statement.totals.net_atomics) },+ reconciliation: recon,+ },+ },+ { 'cache-control': 'no-store' },+ );+});diff --git a/api/config.js b/api/config.jsindex b6f203f4a..e2f21eaf1 100644--- a/api/config.js+++ b/api/config.js@@ -2,6 +2,7 @@import { cors, json, method, wrap } from './_lib/http.js';import { resolveProviderName, BYOK_REGEN_PROVIDERS } from './_lib/regen-provider.js';+import { vapidPublicKey, pushConfigured } from './_lib/web-push.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;@@ -38,6 +39,11 @@ export default wrap(async (req, res) => {walletConnectProjectId: process.env.VITE_WALLETCONNECT_PROJECT_ID || '',privyAppId: process.env.VITE_PRIVY_APP_ID || process.env.PRIVY_APP_ID || '',samlEnabled,+ // Web Push: the client needs the VAPID public key to subscribe. Empty+ // string when push isn't configured, which the client reads as "hide the+ // enable-push affordance".+ pushEnabled: pushConfigured(),+ vapidPublicKey: vapidPublicKey(),samlLabel: process.env.SAML_BUTTON_LABEL || 'Single sign-on (SSO)',features: {// avatarReconstruct is always true: BYOK providers (Meshy, Tripo) arediff --git a/api/notifications/preferences.js b/api/notifications/preferences.jsnew file mode 100644index 000000000..73387ab97--- /dev/null+++ b/api/notifications/preferences.js@@ -0,0 +1,73 @@+// Unified notification preference center.+//+// GET /api/notifications/preferences+// → { categories: [...], channels: [...], prefs: {...}, push: {...} }+// the full resolved matrix + metadata the UI renders from.+// PUT /api/notifications/preferences { categories: {...}, telegram_chat_id }+// → persist a sanitised sparse override; unknown keys are dropped.+//+// Defaults live in api/_lib/notify-prefs.js, so a user who has never saved gets+// a sensible matrix and new categories appear automatically.++import { z } from 'zod';+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';+import { requireCsrf } from '../_lib/csrf.js';+import { limits } from '../_lib/rate-limit.js';+import {+ CATEGORIES,+ CHANNELS,+ resolvePrefs,+ sanitizePrefs,+} from '../_lib/notify-prefs.js';++const putBody = z.object({+ categories: z.record(z.record(z.boolean())).optional(),+ telegram_chat_id: z.string().max(24).optional(),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'PUT'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ if (req.method === 'GET') {+ const prefs = await resolvePrefs(user.id);+ const [pushRow] = await sql`+ select count(*)::int as count from push_subscriptions where user_id = ${user.id}+ `;+ return json(res, 200, {+ categories: CATEGORIES,+ channels: CHANNELS,+ prefs,+ push: { subscribed_devices: pushRow?.count ?? 0 },+ });+ }++ if (!(await requireCsrf(req, res, user.id))) return;+ const rl = await limits.notifPrefsWrite(user.id);+ if (!rl.success) return rateLimited(res, rl);++ const body = parseSafe(await readJson(req));+ const clean = sanitizePrefs(body);++ await sql`+ insert into notification_preferences (user_id, prefs, updated_at)+ values (${user.id}, ${JSON.stringify(clean)}::jsonb, now())+ on conflict (user_id) do update set+ prefs = ${JSON.stringify(clean)}::jsonb,+ updated_at = now()+ `;++ return json(res, 200, { ok: true, prefs: await resolvePrefs(user.id) });+});++// Lenient parse: a malformed channel map shouldn't 400 the whole save — the+// sanitiser drops anything unrecognised. Validate only the coarse shape.+function parseSafe(raw) {+ const out = putBody.safeParse(raw);+ return out.success ? out.data : { categories: {} };+}diff --git a/api/pricing.js b/api/pricing.jsnew file mode 100644index 000000000..c919179a1--- /dev/null+++ b/api/pricing.js@@ -0,0 +1,98 @@+// GET /api/pricing — the canonical pricing surface, server-truth.+//+// One endpoint a buyer reads before they spend a cent. It aggregates the THREE+// sources of pricing truth into one shape so the pricing page never hardcodes a+// number:+// • actions — every priced action from the pricing catalog (USD, settled in $THREE)+// • fee — the platform fee rate (api/_lib/fee.js)+// • tiers — the $THREE holder discount ladder (api/_lib/three-tier.js, D1)+// • holder — PERSONALIZED "you hold $THREE, your price": when the caller is+// signed in with a linked wallet, their resolved tier + the+// discounted price of every fixed action. Never blocks on the+// balance read — degrades to the public price on any RPC hiccup.+//+// Public + cacheable for the anonymous shape; the personalized shape is computed+// per-user and sent no-store. No secrets — safe to serve unauthenticated.++import { cors, json, method, wrap } from './_lib/http.js';+import { getSessionUser } from './_lib/auth.js';+import { getFeeBps } from './_lib/fee.js';+import { publicCatalog, priceForAction } from './_lib/pricing/catalog.js';+import { TIERS, resolveUserTier, nextTier } from './_lib/three-tier.js';+import { TOKEN_MINT, TOKEN_SYMBOL } from './_lib/token/config.js';++function tierLadder() {+ return TIERS.map((t) => ({+ level: t.level,+ id: t.id,+ label: t.label,+ min_usd: t.minUsd,+ discount_bps: t.discountBps,+ discount_percent: (t.discountBps / 100).toFixed(t.discountBps % 100 === 0 ? 0 : 1),+ rate_multiplier: t.rateMultiplier,+ perks: t.perks,+ }));+}++// Apply a holder discount to every fixed-price action, mirroring the EXACT clamp+// logic the charge rail uses (priceForAction) so the "your price" shown here is+// the price actually quoted at checkout — never a second, drifting copy.+function personalizedActions(actions, discountBps) {+ return actions.map((a) => {+ if (a.usd == null || discountBps <= 0) return { ...a, your_usd: a.usd };+ try {+ const { usd } = priceForAction(a.id, { discountBps });+ return { ...a, your_usd: usd };+ } catch {+ return { ...a, your_usd: a.usd };+ }+ });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const fee_bps = getFeeBps();+ const actions = publicCatalog();+ const base = {+ currency: { quote: 'USD', settle: TOKEN_SYMBOL, mint: TOKEN_MINT },+ fee: { bps: fee_bps, percent: (fee_bps / 100).toFixed(1) },+ tiers: tierLadder(),+ actions,+ };++ // Personalize when signed in — but never let the balance read fail the page.+ let user = null;+ try {+ user = await getSessionUser(req);+ } catch {+ user = null;+ }++ if (!user) {+ return json(res, 200, { ...base, holder: null }, {+ 'cache-control': 'public, max-age=60, s-maxage=60, stale-while-revalidate=300',+ });+ }++ let holder = null;+ let pricedActions = actions;+ try {+ const { tier, usd, next } = await resolveUserTier(user);+ const nt = next ?? nextTier(tier);+ holder = {+ tier: { level: tier.level, id: tier.id, label: tier.label, discount_bps: tier.discountBps, perks: tier.perks },+ usd_held: Math.round((Number(usd) || 0) * 100) / 100,+ discount_bps: tier.discountBps,+ discount_percent: (tier.discountBps / 100).toFixed(tier.discountBps % 100 === 0 ? 0 : 1),+ next_tier: nt ? { id: nt.id, label: nt.label, min_usd: nt.minUsd, discount_bps: nt.discountBps } : null,+ usd_to_next: nt ? Math.max(0, Math.round((nt.minUsd - (Number(usd) || 0)) * 100) / 100) : 0,+ };+ if (tier.discountBps > 0) pricedActions = personalizedActions(actions, tier.discountBps);+ } catch {+ holder = null;+ }++ return json(res, 200, { ...base, actions: pricedActions, holder }, { 'cache-control': 'no-store' });+});diff --git a/api/push/subscribe.js b/api/push/subscribe.jsnew file mode 100644index 000000000..432e071e5--- /dev/null+++ b/api/push/subscribe.js@@ -0,0 +1,72 @@+// Web Push subscription registry.+//+// POST /api/push/subscribe { subscription: PushSubscriptionJSON }+// → upsert the device's push endpoint for the signed-in user.+// DELETE /api/push/subscribe { endpoint } | { subscription }+// → remove an endpoint (used when the user disables push).+//+// The subscription object is exactly what `pushManager.subscribe()` returns+// (`.toJSON()`): { endpoint, keys: { p256dh, auth } }. Endpoints are unique+// globally — a re-subscribe upserts so the latest owner wins and stale rows+// from a previous account on the same device are reclaimed.++import { z } from 'zod';+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';+import { requireCsrf } from '../_lib/csrf.js';+import { limits } from '../_lib/rate-limit.js';+import { parse } from '../_lib/validate.js';++const subscriptionSchema = z.object({+ endpoint: z.string().url().max(2048),+ keys: z.object({+ p256dh: z.string().min(1).max(256),+ auth: z.string().min(1).max(256),+ }),+});++const postBody = z.object({ subscription: subscriptionSchema });+const deleteBody = z.object({+ endpoint: z.string().url().max(2048).optional(),+ subscription: subscriptionSchema.optional(),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST', 'DELETE'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');+ if (!(await requireCsrf(req, res, user.id))) return;++ const rl = await limits.pushSubscribe(user.id);+ if (!rl.success) return rateLimited(res, rl);++ if (req.method === 'DELETE') {+ const { endpoint, subscription } = parse(deleteBody, await readJson(req));+ const ep = endpoint || subscription?.endpoint;+ if (!ep) return error(res, 400, 'validation_error', 'endpoint required');+ await sql`+ delete from push_subscriptions+ where user_id = ${user.id} and endpoint = ${ep}+ `;+ return json(res, 200, { ok: true });+ }++ const { subscription } = parse(postBody, await readJson(req));+ const ua = String(req.headers['user-agent'] || '').slice(0, 400);++ await sql`+ insert into push_subscriptions (user_id, endpoint, p256dh, auth, user_agent)+ values (${user.id}, ${subscription.endpoint}, ${subscription.keys.p256dh}, ${subscription.keys.auth}, ${ua})+ on conflict (endpoint) do update set+ user_id = excluded.user_id,+ p256dh = excluded.p256dh,+ auth = excluded.auth,+ user_agent = excluded.user_agent,+ last_seen_at = now()+ `;++ return json(res, 201, { ok: true });+});diff --git a/api/x402-checkout.js b/api/x402-checkout.jsindex c6c81933b..a4e5947d3 100644--- a/api/x402-checkout.js+++ b/api/x402-checkout.js@@ -187,6 +187,41 @@ const tipSchema = z.object({amount: z.string().regex(/^\d+$/),});+// Validate one buyer-approved donation against the safety caps. Pure and+// exported so the money-moving rules — well-formed recipient/amount, ≤ 100+// tokens AND ≤ 50× the payment, and recipient ≠ the merchant payout — are+// unit-testable without building a Solana transaction. The handler appends a+// transferChecked only for an `ok` result. Returns exactly one of:+// { skip: true } — zero/negative amount, nothing to send+// { ok: true, to: PublicKey, amount } — validated, ready to route+// { ok: false, code, message } — rejected; caller emits a 400+export function validateTip(tip, { payTo, paymentAmount }) {+ let to;+ try {+ to = new PublicKey(tip.to);+ } catch {+ return { ok: false, code: 'invalid_tip', message: `donation recipient is not a valid address: ${tip.to}` };+ }+ let amount;+ try {+ amount = BigInt(tip.amount);+ } catch {+ return { ok: false, code: 'invalid_tip', message: 'donation amount must be a whole token amount' };+ }+ if (amount <= 0n) return { skip: true };+ if (amount > TIP_ABS_MAX || amount > paymentAmount * 50n) {+ return {+ ok: false,+ code: 'tip_too_large',+ message: 'donation exceeds the safety cap (≤ 100 tokens and ≤ 50× the payment) — check the giving configuration',+ };+ }+ if (to.equals(payTo)) {+ return { ok: false, code: 'invalid_tip', message: 'donation recipient cannot be the payment recipient' };+ }+ return { ok: true, to, amount };+}+export const prepareSchema = z.object({accept: acceptSchema,buyer: solanaAddress,@@ -320,38 +355,17 @@ async function handlePrepare(req, res) {// against the merchant's own payout so a tip can never silently inflate it.if (Array.isArray(tips) && tips.length) {for (const tip of tips) {- let tipTo;- try {- tipTo = new PublicKey(tip.to);- } catch {- return error(res, 400, 'invalid_tip', `donation recipient is not a valid address: ${tip.to}`);- }- let tipAmount;- try {- tipAmount = BigInt(tip.amount);- } catch {- return error(res, 400, 'invalid_tip', 'donation amount must be a whole token amount');- }- if (tipAmount <= 0n) continue; // nothing to send- if (tipAmount > TIP_ABS_MAX || tipAmount > amount * 50n) {- return error(- res,- 400,- 'tip_too_large',- 'donation exceeds the safety cap (≤ 100 tokens and ≤ 50× the payment) — check the giving configuration',- );- }- if (tipTo.equals(payTo)) {- return error(res, 400, 'invalid_tip', 'donation recipient cannot be the payment recipient');- }- const tipAta = getAssociatedTokenAddressSync(mint, tipTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);+ const v = validateTip(tip, { payTo, paymentAmount: amount });+ if (v.skip) continue; // zero/negative amount, nothing to send+ if (!v.ok) return error(res, 400, v.code, v.message);+ const tipAta = getAssociatedTokenAddressSync(mint, v.to, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);if (!(await ataExists(conn, tipAta))) {ixs.push(- createAssociatedTokenAccountIdempotentInstruction(feePayer, tipAta, tipTo, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID),+ createAssociatedTokenAccountIdempotentInstruction(feePayer, tipAta, v.to, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID),);}ixs.push(- createTransferCheckedInstruction(senderAta, mint, tipAta, buyerPubkey, tipAmount, mintDecimals, [], TOKEN_PROGRAM_ID),+ createTransferCheckedInstruction(senderAta, mint, tipAta, buyerPubkey, v.amount, mintDecimals, [], TOKEN_PROGRAM_ID),);}}diff --git a/multiplayer/src/stage-schemas.js b/multiplayer/src/stage-schemas.jsnew file mode 100644index 000000000..467aa6b06--- /dev/null+++ b/multiplayer/src/stage-schemas.js@@ -0,0 +1,126 @@+// Schema definitions for the live-performance world (stage_world room), shared+// between StageRoom (server) and src/stage-net.js (client, bundled by Vite the+// same way it bundles walk's schemas.js).+//+// @colyseus/schema uses delta encoding: only fields that changed since the last+// patch ride the wire, and a late joiner receives the full current set on join.+// This room delta-syncs the AUDIENCE (the `audience` map — privacy-clean, like+// IrlRoom: a session id + chosen display name + avatar + a coarse seat position,+// never a wallet), the HOST's live performance state (current utterance id, beat+// kind, animation cue, caption text), and the live TIP TICKER + leaderboard+// totals. The actual audio is NOT synced state — it rides a timed `utterance`+// broadcast each client renders locally (spatial voice + lip-sync + captions),+// so a viewer with no WebGL still gets captions + the tip economy.+//+// IMPORTANT: append-only. Field indices are positional in @colyseus/schema's+// binary protocol — inserting in the middle shifts every later index and breaks+// clients still connected to an older deployed server. Always add at the end.++import { Schema, MapSchema, ArraySchema, defineTypes } from '@colyseus/schema';++// One audience member present in the venue. Privacy-clean by construction: a+// session id (NOT an account/wallet), an opt-in display name + avatar, and a+// seat position the server assigns on a ring around the stage — never a precise+// client-reported coordinate, so the crowd renders without leaking identity.+export class StageAudience extends Schema {+ constructor() {+ super();+ this.id = '';+ this.name = '';+ this.avatar = '';+ this.x = 0; // assigned seat position (ring around the stage)+ this.z = 0;+ this.vip = false; // tip-gated front-row attention (the host sees these first)+ this.reaction = ''; // last emoji this member fired (transient; cleared after a beat)+ this.reactionTs = 0;+ this.tsServer = 0; // last heartbeat (drives the reaper)+ }+}+defineTypes(StageAudience, {+ id: 'string',+ name: 'string',+ avatar: 'string',+ x: 'float32',+ z: 'float32',+ vip: 'boolean',+ reaction: 'string',+ reactionTs: 'float64',+ tsServer: 'float64',+});++// A live tipper standing on the leaderboard. Synced so every client renders the+// same "biggest tippers" board the host reacts to. `total` is atomic units.+export class StageTipper extends Schema {+ constructor() {+ super();+ this.id = '';+ this.label = '';+ this.total = 0;+ this.count = 0;+ }+}+defineTypes(StageTipper, {+ id: 'string',+ label: 'string',+ total: 'float64', // atomic units; float64 carries the full safe-integer range+ count: 'uint32',+});++// The host's current performance frame. Updated once per beat: every client+// reads `utteranceId`/`caption`/`beat`/`cue` to keep the captions + animation in+// sync with the timed audio broadcast (a late joiner sees the current caption).+export class StageHost extends Schema {+ constructor() {+ super();+ this.agentId = '';+ this.name = '';+ this.avatar = '';+ this.voice = 'nova';+ this.utteranceId = 0; // monotonic; bumps each beat so clients dedupe+ this.beat = ''; // beat kind (opener|tip_shoutout|answer|banter|game)+ this.caption = ''; // the host's current words, as live text (a11y + fallback)+ this.cue = 'idle'; // animation cue (idle|talk|cheer|point|dj)+ this.speaking = false;+ this.startedAtMs = 0;+ }+}+defineTypes(StageHost, {+ agentId: 'string',+ name: 'string',+ avatar: 'string',+ voice: 'string',+ utteranceId: 'uint32',+ beat: 'string',+ caption: 'string',+ cue: 'string',+ speaking: 'boolean',+ startedAtMs: 'float64',+});++export class StageState extends Schema {+ constructor() {+ super();+ this.stageId = '';+ this.title = '';+ this.format = '';+ this.phase = 'preshow'; // preshow | live | between | ended+ this.host = new StageHost();+ this.audience = new MapSchema(); // sessionId → StageAudience+ this.leaderboard = new ArraySchema(); // StageTipper[], highest first+ this.totalTipsAtomic = 0; // running show total (atomic units)+ this.tipCount = 0;+ this.nextShowAt = 0; // epoch ms of the next scheduled show (between/preshow states)+ }+}+defineTypes(StageState, {+ stageId: 'string',+ title: 'string',+ format: 'string',+ phase: 'string',+ host: StageHost,+ audience: { map: StageAudience },+ leaderboard: [StageTipper],+ totalTipsAtomic: 'float64',+ tipCount: 'uint32',+ nextShowAt: 'float64',+});diff --git a/multiplayer/src/stage-show.js b/multiplayer/src/stage-show.jsnew file mode 100644index 000000000..3117740bb--- /dev/null+++ b/multiplayer/src/stage-show.js@@ -0,0 +1,244 @@+// ShowDirector — the pure, Colyseus-free brain-stem of a live stage performance.+//+// The StageRoom (Colyseus) owns sockets, schema, and broadcast; everything it+// DECIDES — which beat the host performs next, who the top tippers are, which+// audience question gets answered, when a tip shoutout pre-empts the banter — is+// computed here, in a dependency-free module that runs (and is tested) without a+// room. This is the same isolation ClashMatch uses: the room is a thin shell over+// a pure director, so the show's logic is unit-testable end to end.+//+// Money is integer atomic units throughout (a tip's amount as it settled on+// chain). The director never touches the chain or the DB — it accumulates the+// already-validated tips the room hands it and ranks them.++// Beat kinds the director can ask the host to perform. The room turns the chosen+// kind + context into a brain prompt; the brain returns the actual words.+export const BEAT = {+ OPENER: 'opener', // first words when the show goes live+ TIP_SHOUTOUT: 'tip_shoutout', // react to a fresh tip — highest priority+ ANSWER: 'answer', // answer a queued audience question+ BANTER: 'banter', // riff / read the room between beats+ GAME: 'game', // run the next round of the show's game/format+};++const MAX_QUESTION_QUEUE = 24; // bound the queue so a flood can't bloat memory+const MAX_PENDING_TIPS = 32; // shoutout backlog cap — oldest dropped if it overflows+const MAX_RECENT_BEATS = 8; // remember the last few beats so the host doesn't loop+const QUESTION_MAX_LEN = 240;++export class ShowDirector {+ /**+ * @param {object} opts+ * @param {string} opts.stageId+ * @param {string} [opts.hostName]+ * @param {string} [opts.format] freeform format label (e.g. 'game show', 'AMA', 'DJ set')+ * @param {number} [opts.startedAt] epoch ms the show went live+ */+ constructor({ stageId, hostName = 'the host', format = 'open mic', startedAt = 0 } = {}) {+ this.stageId = stageId;+ this.hostName = hostName;+ this.format = format;+ this.startedAt = startedAt || 0;++ // Tip ledger — keyed by a stable tipper id (user id, or wallet, or device).+ // Each entry accumulates total atomic units + count so the leaderboard is a+ // single sort. A returning tipper across beats lands on the same row.+ this._tippers = new Map(); // tipperId → { id, label, total, count, lastTs }+ // Fresh tips the host hasn't shouted out yet, oldest first.+ this._pendingTips = [];+ // Audience questions awaiting the host's pick, oldest first.+ this._questionQueue = [];+ this._seenQuestionIds = new Set();+ // Recent beat kinds (most-recent last) so the director can avoid repeating+ // the same filler twice in a row.+ this._recentBeats = [];++ this.totalTipsAtomic = 0;+ this.tipCount = 0;+ this.peakAudience = 0;+ this._spokenOpener = false;+ }++ // ── audience sizing ──────────────────────────────────────────────────────+ noteAudience(size) {+ const n = Number(size);+ if (Number.isFinite(n) && n > this.peakAudience) this.peakAudience = n;+ }++ // ── tips ─────────────────────────────────────────────────────────────────+ /**+ * Record an already-validated, already-settled tip. The room is the trust+ * boundary (it only forwards tips the API verified + deduped by signature);+ * the director assumes each call is a distinct, real settlement and ranks it.+ *+ * @returns {{ tip: object, isNewTopTipper: boolean }}+ */+ ingestTip({ tipperId, label, amount, mint, signature, message = '', ts = 0 }) {+ const amt = Number(amount);+ const safeAmt = Number.isInteger(amt) && amt > 0 ? amt : 0;+ const id = String(tipperId || signature || 'anon').slice(0, 80);+ const cleanLabel = cleanText(label || 'someone', 48) || 'someone';+ const topBefore = this.topTipperId();++ let entry = this._tippers.get(id);+ if (!entry) {+ entry = { id, label: cleanLabel, total: 0, count: 0, lastTs: 0 };+ this._tippers.set(id, entry);+ }+ entry.label = cleanLabel; // a tipper may refine their display name over a show+ entry.total += safeAmt;+ entry.count += 1;+ entry.lastTs = ts;++ this.totalTipsAtomic += safeAmt;+ this.tipCount += 1;++ const tip = {+ tipperId: id,+ label: cleanLabel,+ amount: safeAmt,+ mint: mint || null,+ signature: signature || null,+ message: cleanText(message, 140),+ ts,+ };+ this._pendingTips.push(tip);+ if (this._pendingTips.length > MAX_PENDING_TIPS) this._pendingTips.shift();++ const isNewTopTipper = this.topTipperId() === id && topBefore !== id;+ return { tip, isNewTopTipper };+ }++ hasPendingTip() {+ return this._pendingTips.length > 0;+ }++ // Pull the next tip to shout out (largest pending first — a whale jumps the+ // queue ahead of a dust tip, which is the crowd-pleasing behaviour).+ takePendingTip() {+ if (!this._pendingTips.length) return null;+ let bestIdx = 0;+ for (let i = 1; i < this._pendingTips.length; i++) {+ if (this._pendingTips[i].amount > this._pendingTips[bestIdx].amount) bestIdx = i;+ }+ const [tip] = this._pendingTips.splice(bestIdx, 1);+ return tip;+ }++ topTipperId() {+ let topId = null;+ let topTotal = -1;+ for (const [id, e] of this._tippers) {+ // Tie-break by earliest lastTs so the leaderboard doesn't flip-flop on+ // equal totals (the one who got there first holds the crown).+ if (e.total > topTotal || (e.total === topTotal && topId && e.lastTs < this._tippers.get(topId).lastTs)) {+ topTotal = e.total;+ topId = id;+ }+ }+ return topId;+ }++ /**+ * Ranked leaderboard, highest total first. Ties broken by who reached the+ * total first (earlier lastTs ranks higher). Capped to `limit`.+ */+ leaderboard(limit = 10) {+ return [...this._tippers.values()]+ .sort((a, b) => b.total - a.total || a.lastTs - b.lastTs)+ .slice(0, limit)+ .map((e) => ({ id: e.id, label: e.label, total: e.total, count: e.count }));+ }++ // ── questions ────────────────────────────────────────────────────────────+ /**+ * Queue an audience question. Returns false when the queue is full or the+ * text is empty/duplicate, so the room can tell the asker their question+ * didn't make it (every state designed).+ */+ queueQuestion({ id, from, text, ts = 0 }) {+ const clean = cleanText(text, QUESTION_MAX_LEN);+ if (!clean) return false;+ if (this._questionQueue.length >= MAX_QUESTION_QUEUE) return false;+ const qid = String(id || `${from}:${ts}`).slice(0, 80);+ if (this._seenQuestionIds.has(qid)) return false;+ this._seenQuestionIds.add(qid);+ this._questionQueue.push({ id: qid, from: cleanText(from, 48) || 'someone', text: clean, ts });+ return true;+ }++ hasPendingQuestion() {+ return this._questionQueue.length > 0;+ }++ pendingQuestionCount() {+ return this._questionQueue.length;+ }++ takeQuestion() {+ return this._questionQueue.shift() || null;+ }++ // ── beat selection ───────────────────────────────────────────────────────+ /**+ * Decide the next beat the host should perform. Priority:+ * 1. opener (once, at show start)+ * 2. tip shoutout (a fresh tip is always acknowledged fast — that's the loop)+ * 3. answer a queued question (audience gets the floor)+ * 4. game round / banter, alternating so the show has rhythm+ *+ * Returns { kind, tip?, question? } — the room turns this into a brain prompt.+ * Pure: same inputs → same decision, which the test suite pins.+ */+ nextBeat() {+ if (!this._spokenOpener) {+ return { kind: BEAT.OPENER };+ }+ if (this.hasPendingTip()) {+ return { kind: BEAT.TIP_SHOUTOUT, tip: this.takePendingTip() };+ }+ if (this.hasPendingQuestion()) {+ return { kind: BEAT.ANSWER, question: this.takeQuestion() };+ }+ // No urgent input — alternate game and banter so two fillers never repeat.+ const last = this._recentBeats[this._recentBeats.length - 1];+ const kind = last === BEAT.GAME ? BEAT.BANTER : BEAT.GAME;+ return { kind };+ }++ // Record that a beat was performed (the room calls this after it broadcasts the+ // utterance) so opener fires once and filler alternates.+ markSpoken(kind) {+ if (kind === BEAT.OPENER) this._spokenOpener = true;+ this._recentBeats.push(kind);+ if (this._recentBeats.length > MAX_RECENT_BEATS) this._recentBeats.shift();+ }++ recentBeats() {+ return [...this._recentBeats];+ }++ // A compact snapshot of show standings for the host brain prompt + the client+ // HUD. Returned to the room, never carries raw wallet/device ids beyond the+ // stable tipper key the leaderboard already exposes.+ standings() {+ return {+ format: this.format,+ totalTipsAtomic: this.totalTipsAtomic,+ tipCount: this.tipCount,+ peakAudience: this.peakAudience,+ leaderboard: this.leaderboard(),+ pendingQuestions: this.pendingQuestionCount(),+ };+ }+}++// Collapse arbitrary caller text to a bounded, single-line, control-char-free+// string. Shared by every text field the director stores so nothing unbounded or+// newline-laden reaches a prompt or a broadcast.+function cleanText(v, max) {+ if (typeof v !== 'string') return '';+ // Strip control characters (incl. newlines) so nothing multi-line or unprintable+ // reaches a brain prompt or a broadcast, then collapse whitespace.+ return v.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);+}diff --git a/pages/dashboard-next/creator.html b/pages/dashboard-next/creator.htmlnew file mode 100644index 000000000..7794f5f05--- /dev/null+++ b/pages/dashboard-next/creator.html@@ -0,0 +1,15 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Creator Studio · Dashboard · three.ws</title>+ <meta name="robots" content="noindex" />+ <link rel="icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/dashboard-next/shell.css" />+ </head>+ <body>+ <script type="module" src="/src/dashboard-next/pages/creator.js"></script>+ </body>+</html>diff --git a/src/agent-detail.js b/src/agent-detail.jsindex cb69c1b2e..d8a620735 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -1097,8 +1097,32 @@ async function loadExtraSections(agentId, rec, isOwner) {]);if (actions?.actions?.length) renderActions(actions.actions, agentId);+ else if (isOwner)+ renderOwnerEmptyCard('ad-actions-card', 'ad-actions-list', {+ icon: '⚡',+ title: 'No signed actions yet',+ body: 'Every trade, launch, and skill invocation this agent makes is logged here with a verifiable signature. Give it a strategy or chat with it to get started.',+ ctaHref: `/agents/${encodeURIComponent(agentId)}/studio`,+ ctaText: 'Open agent studio →',+ });if (memory?.entries?.length) renderMemory(memory.entries);+ else if (isOwner)+ renderOwnerEmptyCard('ad-memory-card', 'ad-memory-list', {+ icon: '🧠',+ title: 'No memories yet',+ body: 'This agent builds long-term memory as it works and converses. Start a conversation to seed what it remembers.',+ ctaHref: `/agents/${encodeURIComponent(agentId)}/talk`,+ ctaText: 'Chat with this agent →',+ });if (strategy?.data?.strategy != null) renderStrategy(strategy.data.strategy);+ else if (isOwner)+ renderOwnerEmptyCard('ad-strategy-card', 'ad-strategy', {+ icon: '🎯',+ title: 'No strategy set',+ body: 'Define how this agent trades, allocates, and acts on its own. A strategy turns the wallet above into an autonomous operator.',+ ctaHref: `/agents/${encodeURIComponent(agentId)}/studio`,+ ctaText: 'Set a strategy →',+ });if (reputation && (reputation.count > 0 || reputation.average > 0))renderReputation(reputation);if (embedPolicy) renderEmbedPolicy(embedPolicy);@@ -1529,6 +1553,37 @@ function summarizeActionPayload(p) {return typeof v === 'string' ? `${k}=${v.slice(0, 60)}` : `${k}=${typeof v}`;}+// Designed empty state for owner-only cards (actions / memory / strategy) when a+// fresh agent has no data yet. Public visitors never see these cards; the owner+// gets a clear next step instead of a blank or hidden panel.+function renderOwnerEmptyCard(cardId, bodyId, { icon, title, body, ctaHref, ctaText }) {+ const card = document.getElementById(cardId);+ const target = document.getElementById(bodyId);+ if (!card || !target) return;+ target.style.display = 'none';+ const empty = el(+ 'div',+ {+ class: 'ad-owner-empty',+ style:+ 'display:flex;flex-direction:column;align-items:center;text-align:center;gap:8px;padding:22px 16px;color:var(--ad-muted,#8a8f98)',+ },+ [+ el('div', { style: 'font-size:26px;line-height:1', text: icon }),+ el('div', { style: 'color:#eaeaea;font-size:14px;font-weight:600', text: title }),+ el('div', { style: 'font-size:12.5px;line-height:1.5;max-width:42ch', text: body }),+ el('a', {+ class: 'ad-cta',+ style: 'margin-top:4px',+ href: ctaHref,+ text: ctaText,+ }),+ ],+ );+ card.appendChild(empty);+ card.style.display = '';+}+function renderActions(actions, agentId) {const card = document.getElementById('ad-actions-card');const list = document.getElementById('ad-actions-list');diff --git a/src/analytics.js b/src/analytics.jsindex 97e1daf0a..6c3a8d42d 100644--- a/src/analytics.js+++ b/src/analytics.js@@ -53,6 +53,19 @@ export const ANALYTICS_EVENTS = Object.freeze({/** Swap settled successfully. props: { amount_usd?, tx_short? } */TOKEN_SWAP_SUCCEEDED: 'token_swap_succeeded',+ // ── Upgrade / paywall funnel (ordered — see FUNNELS.upgrade) ─────────────+ /** A holder-gate / paywall upsell was shown at a free-lane limit. props:+ * { feature?, required_tier?, held_tier?, reason?, has_pay_per_use?, pay_per_use_usd? } */+ UPGRADE_GATE_SHOWN: 'upgrade_gate_shown',+ /** User chose the "Get $THREE" path from the gate. props: { feature?, required_tier? } */+ UPGRADE_GET_THREE_CLICKED: 'upgrade_get_three_clicked',+ /** User chose the contextual "Pay per use" path from the gate. props:+ * { feature?, action?, pay_per_use_usd? } */+ UPGRADE_PAY_PER_USE_CLICKED: 'upgrade_pay_per_use_clicked',+ /** The gated action completed after a gate was shown — the conversion. props:+ * { feature?, path: 'hold'|'pay_per_use', usd? } */+ UPGRADE_CONVERTED: 'upgrade_converted',+// ── Engagement ───────────────────────────────────────────────────────────/** Marketplace search/filter used. props: { query_len?, filters? } */MARKETPLACE_SEARCHED: 'marketplace_searched',@@ -63,6 +76,16 @@ export const ANALYTICS_EVENTS = Object.freeze({* so insights group cleanly across surfaces. */SURFACE_OPENED: 'surface_opened',+ // ── Creator monetization funnel (ordered — see FUNNELS.creator) ──────────+ /** Creator dashboard opened / "become a creator" intent. props: { agent_count?, has_prices? } */+ CREATOR_ONBOARDING_STARTED: 'creator_onboarding_started',+ /** A skill price (or pricing rule) was saved. props: { agent_id?, skill?, price_usdc?, gate_type?, is_first? } */+ CREATOR_PRICE_SET: 'creator_price_set',+ /** A payout wallet was configured for an agent. props: { agent_id?, network? } */+ CREATOR_PAYOUT_CONFIGURED: 'creator_payout_configured',+ /** The creator's first observed sale surfaced in the dashboard. props: { agent_id?, revenue_usd? } */+ CREATOR_FIRST_SALE: 'creator_first_sale',+// ── Share (this module's own instrumentation surface) ────────────────────/** Share card flow opened. props: { kind: string, entity_id? } */SHARE_CARD_OPENED: 'share_card_opened',@@ -95,6 +118,25 @@ export const FUNNELS = Object.freeze({ANALYTICS_EVENTS.TOKEN_SWAP_CONFIRMED,ANALYTICS_EVENTS.TOKEN_SWAP_SUCCEEDED,],+ // Supply-side proof: a creator lands on the dashboard, sets a price, wires a+ // payout wallet, and earns. Each step is the lever that turns a viewer into a+ // paid creator — the flywheel three.ws optimizes for.+ creator: [+ ANALYTICS_EVENTS.CREATOR_ONBOARDING_STARTED,+ ANALYTICS_EVENTS.CREATOR_PRICE_SET,+ ANALYTICS_EVENTS.CREATOR_PAYOUT_CONFIGURED,+ ANALYTICS_EVENTS.CREATOR_FIRST_SALE,+ ],+ // Contextual upgrade moment at a free-lane limit → conversion. This array is+ // the primary "hold" path (acquire $THREE, whose acquisition tail is the+ // `three` funnel). The alternate "pay per use" branch is its own catalog event+ // (UPGRADE_PAY_PER_USE_CLICKED) — both branches terminate at UPGRADE_CONVERTED+ // when the gated action finally completes, so conversion is measurable for each.+ upgrade: [+ ANALYTICS_EVENTS.UPGRADE_GATE_SHOWN,+ ANALYTICS_EVENTS.UPGRADE_GET_THREE_CLICKED,+ ANALYTICS_EVENTS.UPGRADE_CONVERTED,+ ],});// ─────────────────────────────────────────────────────────────────────────────diff --git a/src/dashboard-next/nav.js b/src/dashboard-next/nav.jsindex 058cbd2b2..fba6d82b7 100644--- a/src/dashboard-next/nav.js+++ b/src/dashboard-next/nav.js@@ -35,6 +35,7 @@ export const NAV = [{ path: '/dashboard/three-token', label: '$THREE', icon: 'three', group: 'Monetize', tags: ['token', 'utility', 'burn', 'revenue share', 'protocol', '$three', 'economy', 'holders'] },{ path: '/dashboard/holders', label: 'Holders', icon: 'three', group: 'Monetize', tags: ['leaderboard', 'holders', 'rank', 'badge', '$three', 'whale', 'top holders', 'standing'] },{ path: '/dashboard/analytics', label: 'Analytics', icon: 'chart', group: 'Monetize', tags: ['revenue', 'charts', 'metrics', 'funnel', 'performance', 'views', 'engagement'] },+ { path: '/dashboard/creator', label: 'Creator Studio', icon: 'creator', group: 'Monetize', tags: ['creator', 'earnings', 'pricing', 'price', 'payout', 'royalties', 'skill analytics', 'sell', 'income', 'make money', '$three discount'] },{ path: '/dashboard/monetize', label: 'Monetize', icon: 'coin', group: 'Monetize', tags: ['revenue', 'payments', 'subscriptions', 'withdrawals', 'earnings', 'plan', 'billing'] },{ path: '/dashboard/transactions',label: 'Transactions', icon: 'receipt', group: 'Monetize', tags: ['history', 'purchases', 'sales', 'receipts', 'ledger', 'orders', 'spent', 'earned', 'invoice', 'transaction history', 'buys', 'csv'] },{ path: '/dashboard/tokens', label: 'Tokens', icon: 'token', group: 'Monetize', tags: ['pump.fun', 'launch', 'bonding curve', 'royalties', 'trade'] },@@ -77,6 +78,7 @@ export const ICONS = {walk: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="3.6" r="1.6"/><path d="M11 6.2l-2.6 2 .9 3.3M11 6.2l2.2 1.4.6 2.6M9.3 11.5L7 17M12 10.2l1.4 2L15 16"/></svg>',code: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M7 5l-4 5 4 5M13 5l4 5-4 5"/></svg>',coin: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="10" r="6.5"/><path d="M10 6v8M7.5 8h4a1.5 1.5 0 010 3H8.5a1.5 1.5 0 000 3h4"/></svg>',+ creator: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M3 16l2.5-7 3 4 2.5-6 3 9"/><path d="M3 16h13"/><circle cx="15.5" cy="5" r="2"/></svg>',token: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2l2.5 5 5.5.8-4 3.9.9 5.5L10 14.7l-4.9 2.5.9-5.5L2 7.8l5.5-.8L10 2z"/></svg>',portfolio: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="7" width="16" height="11" rx="1.5"/><path d="M6 7V5a4 4 0 018 0v2"/><path d="M2 11h16"/></svg>',user: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="7" r="3.2"/><path d="M4 17a6 6 0 0112 0"/></svg>',diff --git a/src/dashboard-next/pages/creator-helpers.js b/src/dashboard-next/pages/creator-helpers.jsnew file mode 100644index 000000000..1f86cf005--- /dev/null+++ b/src/dashboard-next/pages/creator-helpers.js@@ -0,0 +1,216 @@+// Pure, side-effect-free logic for the Creator Studio page (creator.js).+//+// Kept in its own module so the price-editor math, validation, $THREE-holder+// discount ladder, royalty-ledger grouping, and CSV export are unit-testable+// without booting the page IIFE that mounts the dashboard shell.+//+// The discount tiers mirror api/_lib/three-tier.js (the server is authoritative;+// this is the buyer-facing *preview*). Keep TIER_LADDER in sync with TIERS there.++const USDC_DECIMALS = 1_000_000;++// $THREE-holder discount ladder — mirrors TIERS in api/_lib/three-tier.js.+// discountBps is applied to the listed price to show the buyer-facing price each+// holder tier pays. Member (level 0) pays full price.+export const TIER_LADDER = Object.freeze([+ Object.freeze({ id: 'member', label: 'Member', minUsd: 0, discountBps: 0 }),+ Object.freeze({ id: 'bronze', label: 'Bronze', minUsd: 25, discountBps: 500 }),+ Object.freeze({ id: 'silver', label: 'Silver', minUsd: 100, discountBps: 1000 }),+ Object.freeze({ id: 'gold', label: 'Gold', minUsd: 500, discountBps: 2000 }),+ Object.freeze({ id: 'genesis', label: 'Genesis', minUsd: 2500, discountBps: 3000 }),+]);++export const RULE_TYPES = Object.freeze(['first_n_purchases', 'after_n_purchases', 'time_window']);++/** Convert a human USDC amount (e.g. 1.5) to 6-decimal atomic units. */+export function usdcToAtomic(usdc) {+ const n = Number(usdc);+ if (!Number.isFinite(n) || n < 0) return 0;+ return Math.round(n * USDC_DECIMALS);+}++/** Convert atomic USDC units to a human amount. */+export function atomicToUsdc(atomic) {+ const n = Number(atomic);+ if (!Number.isFinite(n)) return 0;+ return n / USDC_DECIMALS;+}++/**+ * Buyer-facing price after a $THREE-holder discount.+ * @param {number} priceUsdc listed price (human USDC)+ * @param {number} discountBps basis points off (0–10000)+ * @returns {number} discounted price, rounded to 6 decimals (USDC precision)+ */+export function discountedPrice(priceUsdc, discountBps) {+ const p = Number(priceUsdc);+ const bps = Number(discountBps);+ if (!Number.isFinite(p) || p <= 0) return 0;+ if (!Number.isFinite(bps) || bps <= 0) return roundUsdc(p);+ const clamped = Math.min(Math.max(bps, 0), 10_000);+ return roundUsdc(p * (1 - clamped / 10_000));+}++/** Round to USDC's 6-decimal precision, avoiding binary-float dust. */+export function roundUsdc(n) {+ return Math.round(Number(n) * USDC_DECIMALS) / USDC_DECIMALS;+}++/**+ * The price each holder tier pays for a listed price — the real buyer-facing+ * preview (no fake numbers; uses the canonical tier bps).+ * @returns {Array<{ id, label, discountBps, price, saves }>}+ */+export function buyerPriceLadder(priceUsdc) {+ const p = Number(priceUsdc);+ return TIER_LADDER.map((t) => {+ const price = discountedPrice(p, t.discountBps);+ return {+ id: t.id,+ label: t.label,+ discountBps: t.discountBps,+ price,+ saves: roundUsdc(Math.max(0, (Number.isFinite(p) ? p : 0) - price)),+ };+ });+}++/**+ * Validate a per-call price input.+ * @returns {{ ok: boolean, value?: number, error?: string }}+ */+export function validatePrice(raw) {+ if (raw === '' || raw === null || raw === undefined) {+ return { ok: false, error: 'Enter a price.' };+ }+ const n = Number(raw);+ if (!Number.isFinite(n)) return { ok: false, error: 'Price must be a number.' };+ if (n < 0) return { ok: false, error: 'Price cannot be negative.' };+ if (n > 0 && usdcToAtomic(n) < 1) {+ return { ok: false, error: 'Price is below the $0.000001 minimum.' };+ }+ if (n > 1_000_000) return { ok: false, error: 'Price exceeds the $1,000,000 maximum.' };+ return { ok: true, value: roundUsdc(n) };+}++/**+ * Validate a dynamic pricing rule before sending it to+ * /api/agents/:id/pricing-rules. Mirrors the server zod schema.+ * @param {{ rule_type, threshold?, price_usdc?, start_at?, end_at? }} rule+ * @returns {{ ok: boolean, error?: string, payload?: object }}+ */+export function validateRule(rule) {+ if (!rule || !RULE_TYPES.includes(rule.rule_type)) {+ return { ok: false, error: 'Choose a valid rule type.' };+ }+ const priceCheck = validatePrice(rule.price_usdc);+ if (!priceCheck.ok) return { ok: false, error: priceCheck.error };+ if (priceCheck.value <= 0) return { ok: false, error: 'Rule price must be greater than zero.' };++ const payload = {+ rule_type: rule.rule_type,+ price_amount: usdcToAtomic(priceCheck.value),+ };++ if (rule.rule_type === 'time_window') {+ const start = rule.start_at ? new Date(rule.start_at) : null;+ const end = rule.end_at ? new Date(rule.end_at) : null;+ if (!start && !end) return { ok: false, error: 'Set a start or end time for the window.' };+ if (start && isNaN(start.getTime())) return { ok: false, error: 'Invalid start time.' };+ if (end && isNaN(end.getTime())) return { ok: false, error: 'Invalid end time.' };+ if (start && end && end.getTime() <= start.getTime()) {+ return { ok: false, error: 'End time must be after the start time.' };+ }+ if (start) payload.start_at = start.toISOString();+ if (end) payload.end_at = end.toISOString();+ } else {+ const t = Number(rule.threshold);+ if (!Number.isInteger(t) || t < 1) {+ return { ok: false, error: 'Threshold must be a whole number ≥ 1.' };+ }+ payload.threshold = t;+ }+ return { ok: true, payload };+}++/**+ * Mirror of api/_lib/skill-pricing-rules.js resolveSkillPrice — computes the+ * price a buyer pays *right now* given the base price, the active rules, and the+ * current confirmed-sale count. Used to show the real effective price (not a+ * mock) before any $THREE discount.+ * @returns {{ priceUsdc: number, source: string, rule?: object }}+ */+export function effectivePriceNow({ basePriceUsdc, rules = [], saleCount = 0, now = new Date() } = {}) {+ const base = Number(basePriceUsdc) || 0;+ const active = (rules || [])+ .filter((r) => r && r.is_active !== false)+ .slice()+ .sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));++ const t = now instanceof Date ? now : new Date(now);+ for (const rule of active) {+ const rulePrice = atomicToUsdc(rule.price_amount);+ if (rule.rule_type === 'first_n_purchases' && saleCount < Number(rule.threshold)) {+ return { priceUsdc: rulePrice, source: 'first_n_purchases', rule };+ }+ if (rule.rule_type === 'after_n_purchases' && saleCount >= Number(rule.threshold)) {+ return { priceUsdc: rulePrice, source: 'after_n_purchases', rule };+ }+ if (rule.rule_type === 'time_window') {+ const start = rule.start_at ? new Date(rule.start_at) : null;+ const end = rule.end_at ? new Date(rule.end_at) : null;+ const inWindow = (!start || t >= start) && (!end || t <= end);+ if (inWindow) return { priceUsdc: rulePrice, source: 'time_window', rule };+ }+ }+ return { priceUsdc: base, source: 'base' };+}++const LEDGER_STATUSES = Object.freeze(['pending', 'settling', 'settled', 'failed']);++/**+ * Group royalty-ledger entries by settlement state and total each bucket.+ * @param {Array<{ status, price_usd }>} entries+ */+export function groupLedgerByStatus(entries) {+ const buckets = { pending: [], settling: [], settled: [], failed: [] };+ const totals = { pending: 0, settling: 0, settled: 0, failed: 0 };+ for (const e of entries || []) {+ const status = LEDGER_STATUSES.includes(e?.status) ? e.status : 'pending';+ buckets[status].push(e);+ totals[status] += Number(e?.price_usd) || 0;+ }+ 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'];+ 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)),+ csvCell(e?.status || ''),+ ]);+ return [header.map(csvCell).join(','), ...rows.map((r) => r.join(','))].join('\n');+}++function csvCell(v) {+ const s = String(v ?? '');+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;+}++/**+ * Which onboarding step a creator is on — drives the "become a creator → set a+ * price → first sale" path and the funnel events.+ * @returns {'no_agent'|'set_price'|'configure_payout'|'first_sale'|'earning'}+ */+export function funnelStage({ agentCount = 0, priceCount = 0, hasPayout = false, hasSale = false } = {}) {+ if (agentCount <= 0) return 'no_agent';+ if (priceCount <= 0) return 'set_price';+ if (!hasPayout) return 'configure_payout';+ if (!hasSale) return 'first_sale';+ return 'earning';+}diff --git a/src/dashboard-next/pages/creator-helpers.test.js b/src/dashboard-next/pages/creator-helpers.test.jsnew file mode 100644index 000000000..424060ca3--- /dev/null+++ b/src/dashboard-next/pages/creator-helpers.test.js@@ -0,0 +1,184 @@+import { describe, it, expect } from 'vitest';+import {+ usdcToAtomic,+ atomicToUsdc,+ discountedPrice,+ buyerPriceLadder,+ validatePrice,+ validateRule,+ effectivePriceNow,+ groupLedgerByStatus,+ ledgerToCsv,+ funnelStage,+ TIER_LADDER,+} from './creator-helpers.js';++describe('usdcToAtomic / atomicToUsdc', () => {+ it('round-trips through 6-decimal atomic units', () => {+ expect(usdcToAtomic(1.5)).toBe(1_500_000);+ expect(usdcToAtomic(0.000001)).toBe(1);+ expect(atomicToUsdc(1_500_000)).toBe(1.5);+ });+ it('floors junk and negatives to 0', () => {+ expect(usdcToAtomic('nope')).toBe(0);+ expect(usdcToAtomic(-5)).toBe(0);+ expect(atomicToUsdc('x')).toBe(0);+ });+});++describe('discountedPrice — $THREE holder discount', () => {+ it('applies basis-point discounts using the canonical tier rates', () => {+ expect(discountedPrice(10, 0)).toBe(10); // member+ expect(discountedPrice(10, 500)).toBe(9.5); // bronze 5%+ expect(discountedPrice(10, 1000)).toBe(9); // silver 10%+ expect(discountedPrice(10, 2000)).toBe(8); // gold 20%+ expect(discountedPrice(10, 3000)).toBe(7); // genesis 30%+ });+ it('rounds to USDC precision without float dust', () => {+ expect(discountedPrice(0.001, 500)).toBe(0.00095);+ });+ it('returns 0 for non-positive / invalid prices', () => {+ expect(discountedPrice(0, 1000)).toBe(0);+ expect(discountedPrice(-1, 1000)).toBe(0);+ expect(discountedPrice('x', 1000)).toBe(0);+ });+ it('clamps out-of-range bps', () => {+ expect(discountedPrice(10, 20000)).toBe(0); // clamped to 100% off+ expect(discountedPrice(10, -50)).toBe(10); // negative → no discount+ });+});++describe('buyerPriceLadder', () => {+ it('produces a price + savings row for every tier', () => {+ const ladder = buyerPriceLadder(100);+ expect(ladder).toHaveLength(TIER_LADDER.length);+ const genesis = ladder.find((r) => r.id === 'genesis');+ expect(genesis.price).toBe(70);+ expect(genesis.saves).toBe(30);+ const member = ladder.find((r) => r.id === 'member');+ expect(member.price).toBe(100);+ expect(member.saves).toBe(0);+ });+});++describe('validatePrice', () => {+ it('accepts valid prices and rounds to USDC precision', () => {+ expect(validatePrice('1.5')).toEqual({ ok: true, value: 1.5 });+ expect(validatePrice(0)).toEqual({ ok: true, value: 0 });+ });+ it('rejects empties, non-numbers, and negatives', () => {+ expect(validatePrice('').ok).toBe(false);+ expect(validatePrice(null).ok).toBe(false);+ expect(validatePrice('abc').ok).toBe(false);+ expect(validatePrice(-1).ok).toBe(false);+ });+ it('rejects sub-atomic and over-maximum prices', () => {+ expect(validatePrice(0.0000001).ok).toBe(false); // < 1 atomic+ expect(validatePrice(2_000_000).ok).toBe(false);+ });+});++describe('validateRule', () => {+ it('builds a first_n_purchases payload with atomic price', () => {+ const r = validateRule({ rule_type: 'first_n_purchases', threshold: 10, price_usdc: 0.5 });+ expect(r.ok).toBe(true);+ expect(r.payload).toMatchObject({ rule_type: 'first_n_purchases', threshold: 10, price_amount: 500_000 });+ });+ it('requires a whole-number threshold ≥ 1 for count rules', () => {+ expect(validateRule({ rule_type: 'after_n_purchases', threshold: 0, price_usdc: 1 }).ok).toBe(false);+ expect(validateRule({ rule_type: 'after_n_purchases', threshold: 1.5, price_usdc: 1 }).ok).toBe(false);+ });+ it('requires a positive rule price', () => {+ expect(validateRule({ rule_type: 'first_n_purchases', threshold: 5, price_usdc: 0 }).ok).toBe(false);+ });+ it('validates time_window bounds and ISO-normalizes them', () => {+ const start = '2026-01-01T00:00:00.000Z';+ const end = '2026-02-01T00:00:00.000Z';+ const ok = validateRule({ rule_type: 'time_window', price_usdc: 2, start_at: start, end_at: end });+ expect(ok.ok).toBe(true);+ expect(ok.payload.start_at).toBe(start);+ expect(ok.payload.end_at).toBe(end);++ expect(validateRule({ rule_type: 'time_window', price_usdc: 2 }).ok).toBe(false); // no bounds+ expect(validateRule({ rule_type: 'time_window', price_usdc: 2, start_at: end, end_at: start }).ok).toBe(false); // inverted+ });+ it('rejects unknown rule types', () => {+ expect(validateRule({ rule_type: 'bogus', price_usdc: 1 }).ok).toBe(false);+ });+});++describe('effectivePriceNow — mirrors server resolveSkillPrice', () => {+ const base = 1; // 1 USDC base+ it('falls back to base price when no rules match', () => {+ expect(effectivePriceNow({ basePriceUsdc: base, rules: [] })).toMatchObject({ priceUsdc: 1, source: 'base' });+ });+ it('applies first_n_purchases while under threshold', () => {+ const rules = [{ rule_type: 'first_n_purchases', threshold: 5, price_amount: 500_000, is_active: true }];+ expect(effectivePriceNow({ basePriceUsdc: base, rules, saleCount: 2 })).toMatchObject({ priceUsdc: 0.5, source: 'first_n_purchases' });+ expect(effectivePriceNow({ basePriceUsdc: base, rules, saleCount: 5 })).toMatchObject({ priceUsdc: 1, source: 'base' });+ });+ it('applies after_n_purchases once threshold is reached', () => {+ const rules = [{ rule_type: 'after_n_purchases', threshold: 3, price_amount: 2_000_000, is_active: true }];+ expect(effectivePriceNow({ basePriceUsdc: base, rules, saleCount: 3 }).priceUsdc).toBe(2);+ expect(effectivePriceNow({ basePriceUsdc: base, rules, saleCount: 1 }).priceUsdc).toBe(1);+ });+ it('respects time_window bounds and priority order', () => {+ const now = new Date('2026-06-15T12:00:00Z');+ const rules = [+ { rule_type: 'time_window', price_amount: 3_000_000, is_active: true, priority: 0,+ start_at: '2026-06-01T00:00:00Z', end_at: '2026-06-30T00:00:00Z' },+ { rule_type: 'after_n_purchases', threshold: 1, price_amount: 9_000_000, is_active: true, priority: 1 },+ ];+ // priority 0 (window) wins over the also-matching after_n rule+ expect(effectivePriceNow({ basePriceUsdc: base, rules, saleCount: 50, now }).priceUsdc).toBe(3);+ });+ it('ignores inactive rules', () => {+ const rules = [{ rule_type: 'first_n_purchases', threshold: 99, price_amount: 1, is_active: false }];+ expect(effectivePriceNow({ basePriceUsdc: base, rules, saleCount: 0 }).source).toBe('base');+ });+});++describe('groupLedgerByStatus', () => {+ it('buckets entries and totals each settlement state', () => {+ const entries = [+ { status: 'pending', price_usd: 1 },+ { status: 'pending', price_usd: 2 },+ { status: 'settling', price_usd: 4 },+ { status: 'settled', price_usd: 8 },+ { status: 'failed', price_usd: 0.5 },+ { status: 'weird', price_usd: 1 }, // unknown → pending+ ];+ const { buckets, totals } = groupLedgerByStatus(entries);+ expect(totals.pending).toBe(4); // 1 + 2 + 1 (unknown)+ expect(totals.settling).toBe(4);+ expect(totals.settled).toBe(8);+ expect(totals.failed).toBe(0.5);+ expect(buckets.pending).toHaveLength(3);+ });+});++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[1]).toContain('"Do, a thing"');+ expect(lines[1]).toContain('"Agent ""X"""');+ expect(lines[1]).toContain('1.5000');+ });+ it('handles empty input', () => {+ expect(ledgerToCsv([])).toBe('Date,Type,Skill,Agent,Amount (USD),Status');+ });+});++describe('funnelStage', () => {+ it('walks the become-a-creator path', () => {+ expect(funnelStage({ agentCount: 0 })).toBe('no_agent');+ expect(funnelStage({ agentCount: 1, priceCount: 0 })).toBe('set_price');+ expect(funnelStage({ agentCount: 1, priceCount: 2, hasPayout: false })).toBe('configure_payout');+ expect(funnelStage({ agentCount: 1, priceCount: 2, hasPayout: true, hasSale: false })).toBe('first_sale');+ expect(funnelStage({ agentCount: 1, priceCount: 2, hasPayout: true, hasSale: true })).toBe('earning');+ });+});diff --git a/src/forge-studio/forge.js b/src/forge-studio/forge.jsindex 26aaee970..5d1b3e90f 100644--- a/src/forge-studio/forge.js+++ b/src/forge-studio/forge.js@@ -2,7 +2,14 @@import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from '../shared/state-kit.js';import { showSharePanel } from '../shared/share.js';import { stampGlbAttribution } from '../shared/glb-attribution.js';-import { primeTierPass, attachTierPass, getTierPass, getAccess, onGate } from '../three-access.js';+import {+ primeTierPass,+ attachTierPass,+ getTierPass,+ getAccess,+ onGate,+ trackUpgradeConverted,+} from '../three-access.js';import { renderLock, lockStateFromAccess } from '../three-lock.js';import { payForHighGeneration } from './forge-pay.js';import { initWalletButton, getConnectedWalletAddress } from '../wallet.js';@@ -1861,6 +1868,9 @@ function showRateLimited({ retryAfter = 10, unavailable = false, busy = false })// Run a job (text or image/multi-view). `cfg` = { prompt, imageUrls }.async function run(cfg) {+ // Captured before the single-use payment proof is stripped — tells the upgrade+ // funnel conversion which path (pay-per-use vs. hold) closed the loop.+ const wasPaidGeneration = !!cfg.payment;lastJob = cfg;pollAbort = false;currentCreationId = null;@@ -1972,6 +1982,16 @@ async function run(cfg) {if (!(done.preview_image_url ?? job.preview_image_url)) {capturePoster(currentCreationId);}+ // Conversion: if this run followed an upgrade gate, the gated High lane just+ // produced a model — close the upgrade funnel. No-op unless a gate was shown+ // recently, and fires once per gate. Only the High tier is gated.+ if ((done.tier ?? job.tier) === 'high') {+ trackUpgradeConverted({+ feature: 'forge_high',+ path: wasPaidGeneration ? 'pay_per_use' : 'hold',+ usd: wasPaidGeneration ? Number(_highAccess?.pay_per_use?.usd) || undefined : undefined,+ });+ }} catch (err) {if (pollAbort) return;if (err.kind === 'unconfigured') {diff --git a/src/forge.js b/src/forge.jsindex eec3f14eb..91c741dd4 100644--- a/src/forge.js+++ b/src/forge.js@@ -2,7 +2,14 @@import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';import { showSharePanel } from './shared/share.js';import { stampGlbAttribution } from './shared/glb-attribution.js';-import { primeTierPass, attachTierPass, getTierPass, getAccess, onGate } from './three-access.js';+import {+ primeTierPass,+ attachTierPass,+ getTierPass,+ getAccess,+ onGate,+ trackUpgradeConverted,+} from './three-access.js';import { renderLock, lockStateFromAccess } from './three-lock.js';import { payForHighGeneration } from './forge-pay.js';import { initWalletButton, getConnectedWalletAddress } from './wallet.js';@@ -1894,6 +1901,9 @@ function showRateLimited({ retryAfter = 10, unavailable = false, busy = false })// Run a job (text or image/multi-view). `cfg` = { prompt, imageUrls }.async function run(cfg) {stopRateLimitCountdown();+ // Capture before the single-use payment proof is stripped below — it tells the+ // upgrade-funnel conversion which path (pay-per-use vs. hold) closed the loop.+ const wasPaidGeneration = !!cfg.payment;lastJob = cfg;pollAbort = false;currentCreationId = null;@@ -2008,6 +2018,16 @@ async function run(cfg) {if (!(done.preview_image_url ?? job.preview_image_url)) {capturePoster(currentCreationId);}+ // Conversion: if this run followed an upgrade gate, the gated High lane just+ // produced a model — close the upgrade funnel. No-op unless a gate was shown+ // recently, and fires once per gate. Only the High tier is gated.+ if ((done.tier ?? job.tier) === 'high') {+ trackUpgradeConverted({+ feature: 'forge_high',+ path: wasPaidGeneration ? 'pay_per_use' : 'hold',+ usd: wasPaidGeneration ? Number(_highAccess?.pay_per_use?.usd) || undefined : undefined,+ });+ }} catch (err) {if (pollAbort) return;if (err.kind === 'unconfigured') {diff --git a/src/three-access.js b/src/three-access.jsindex 7228d003f..cfc231467 100644--- a/src/three-access.js+++ b/src/three-access.js@@ -29,6 +29,7 @@import { getConnectedWallet, getConnectedWalletAddress } from './wallet.js';import { safeUrl } from './safe-url.js';+import { track, trackFunnelStep, ANALYTICS_EVENTS } from './analytics.js';const ACCESS_TTL_MS = 30_000;// The matrix cache is keyed by identity (the connected wallet, or null for the@@ -357,6 +358,19 @@ export function showThreeGate(gate, opts = {}) {const heldUsd = Number(held.usd) || 0;const reason = gate.reason || (held.level > 0 ? 'insufficient_tier' : '');+ // Conversion telemetry — the gate IS the contextual upgrade moment, so this is+ // the one place every call site's upsell impression + click is measured. Props+ // carry only tier ids/labels and the offered price (no wallet/PII). track() is a+ // no-op when analytics isn't loaded and never throws, so it can't break the modal.+ const gateProps = {+ feature: gate.feature || undefined,+ required_tier: required.id || required.label || undefined,+ held_tier: held.id || held.label || undefined,+ reason: reason || undefined,+ has_pay_per_use: Boolean(gate.pay_per_use),+ pay_per_use_usd: gate.pay_per_use ? Number(gate.pay_per_use.usd) || undefined : undefined,+ };+const sub =reason === 'sign_in'? 'Sign in and link a Solana wallet to check your tier.'@@ -395,9 +409,29 @@ export function showThreeGate(gate, opts = {}) {if (e.target === overlay) close();});overlay.querySelector('#tg-close').addEventListener('click', close);+ // Impression — step 1 of the upgrade funnel. Persist the intent so the eventual+ // conversion attributes even across a navigation to the token page and back.+ markUpgradeIntent(gateProps.feature);+ trackFunnelStep('upgrade', ANALYTICS_EVENTS.UPGRADE_GATE_SHOWN, gateProps);+ // "Get $THREE" — the hold path (step 2). Fire on click before the anchor navigates.+ const getEl = overlay.querySelector('#tg-get');+ if (getEl) {+ getEl.addEventListener('click', () => {+ trackFunnelStep('upgrade', ANALYTICS_EVENTS.UPGRADE_GET_THREE_CLICKED, {+ feature: gateProps.feature,+ required_tier: gateProps.required_tier,+ });+ });+ }const payEl = overlay.querySelector('#tg-pay');if (payEl) {payEl.addEventListener('click', () => {+ // The alternate "pay per use" branch — tracked as its own catalog event.+ track(ANALYTICS_EVENTS.UPGRADE_PAY_PER_USE_CLICKED, {+ feature: gateProps.feature,+ action: gate.pay_per_use?.action || undefined,+ pay_per_use_usd: gateProps.pay_per_use_usd,+ });close();opts.onPayPerUse(gate.pay_per_use);});@@ -437,6 +471,54 @@ export function onGate(payload, opts) {return showThreeGate(payload, opts);}+// ── Upgrade conversion tracking ────────────────────────────────────────────────+// A gate impression is the top of the upgrade funnel; the conversion is the gated+// action finally succeeding — which can happen after the user leaves to acquire+// $THREE and returns (the hold path) or pays inline (pay-per-use). We persist a+// short-lived "intent" in sessionStorage when the gate is shown so the conversion+// can be attributed even across the navigation to the token page and back.+const UPGRADE_INTENT_KEY = 'three:upgrade_intent';+const UPGRADE_INTENT_TTL_MS = 30 * 60_000; // 30 min — long enough for a swap round-trip++function markUpgradeIntent(feature) {+ try {+ sessionStorage.setItem(+ UPGRADE_INTENT_KEY,+ JSON.stringify({ feature: feature || null, at: Date.now() }),+ );+ } catch {+ /* storage unavailable (private mode / embed) — conversion just won't attribute */+ }+}++/**+ * Close the upgrade funnel when a previously-gated action completes. No-op (returns+ * false) unless a gate was shown within the TTL, so it's safe to call on every+ * success of a gateable action — it fires UPGRADE_CONVERTED at most once per gate.+ * @param {{ feature?: string, path?: 'hold'|'pay_per_use', usd?: number }} [info]+ * @returns {boolean} whether the conversion event was emitted.+ */+export function trackUpgradeConverted({ feature, path, usd } = {}) {+ let intent = null;+ try {+ const raw = sessionStorage.getItem(UPGRADE_INTENT_KEY);+ if (raw) intent = JSON.parse(raw);+ } catch {+ return false;+ }+ if (!intent || !(Date.now() - Number(intent.at) < UPGRADE_INTENT_TTL_MS)) return false;+ try {+ sessionStorage.removeItem(UPGRADE_INTENT_KEY); // consume — one conversion per gate+ } catch {+ /* best-effort */+ }+ return trackFunnelStep('upgrade', ANALYTICS_EVENTS.UPGRADE_CONVERTED, {+ feature: feature || intent.feature || undefined,+ path: path || undefined,+ usd: Number(usd) > 0 ? Number(usd) : undefined,+ });+}+// ── Styles ────────────────────────────────────────────────────────────────────function injectStyles() {diff --git a/tests/x402-checkout-prepare.test.js b/tests/x402-checkout-prepare.test.jsindex 92ad9b6e1..542c54b91 100644--- a/tests/x402-checkout-prepare.test.js+++ b/tests/x402-checkout-prepare.test.js@@ -1,7 +1,7 @@import { describe, it, expect } from 'vitest';import { PublicKey } from '@solana/web3.js';-import { acceptSchema, prepareSchema, ataExists, getRecentBlockhash } from '../api/x402-checkout.js';+import { acceptSchema, prepareSchema, ataExists, getRecentBlockhash, validateTip } from '../api/x402-checkout.js';// The 402 challenge's `accept` is built from operator env (X402_PAY_TO_SOLANA /// X402_FEE_PAYER_SOLANA). Those values are pasted into dashboards and routinely@@ -66,6 +66,72 @@ describe('x402-checkout prepareSchema', () => {});});+describe('x402-checkout validateTip — donation safety caps (moves real USDC)', () => {+ const payTo = new PublicKey(PAY_TO);+ // A distinct, valid charity recipient (≠ payTo) for the happy-path cases.+ const CHARITY = FEE_PAYER;++ it('accepts a well-formed donation under the caps, returning typed to/amount', () => {+ const v = validateTip({ to: CHARITY, amount: '1000' }, { payTo, paymentAmount: 10_000n });+ expect(v.ok).toBe(true);+ expect(v.to).toBeInstanceOf(PublicKey);+ expect(v.to.toBase58()).toBe(CHARITY);+ expect(v.amount).toBe(1000n);+ });++ it('skips a zero-amount donation (nothing to send) without erroring', () => {+ const v = validateTip({ to: CHARITY, amount: '0' }, { payTo, paymentAmount: 10_000n });+ expect(v).toEqual({ skip: true });+ });++ it('rejects a donation above the absolute 100-token cap', () => {+ // 100.000001 USDC: over the abs cap, but well under 50× a large payment so+ // the abs cap is the binding rule being exercised here.+ const v = validateTip({ to: CHARITY, amount: '100000001' }, { payTo, paymentAmount: 1_000_000_000n });+ expect(v.ok).toBe(false);+ expect(v.code).toBe('tip_too_large');+ });++ it('rejects a donation above 50× the payment even when under the abs cap', () => {+ // 60k atomics > 50 × 1000 = 50k, and far below the 100-token abs cap.+ const v = validateTip({ to: CHARITY, amount: '60000' }, { payTo, paymentAmount: 1_000n });+ expect(v.ok).toBe(false);+ expect(v.code).toBe('tip_too_large');+ });++ it('rejects a donation routed back to the merchant payout (silent inflation)', () => {+ const v = validateTip({ to: PAY_TO, amount: '1000' }, { payTo, paymentAmount: 10_000n });+ expect(v.ok).toBe(false);+ expect(v.code).toBe('invalid_tip');+ });++ it('rejects a malformed recipient address', () => {+ const v = validateTip({ to: 'not-a-valid-base58-address!!', amount: '1000' }, { payTo, paymentAmount: 10_000n });+ expect(v.ok).toBe(false);+ expect(v.code).toBe('invalid_tip');+ });++ it('rejects a non-numeric donation amount', () => {+ const v = validateTip({ to: CHARITY, amount: 'abc' }, { payTo, paymentAmount: 10_000n });+ expect(v.ok).toBe(false);+ expect(v.code).toBe('invalid_tip');+ });++ it('caps the donation array at 2 entries in prepareSchema', () => {+ expect(() =>+ prepareSchema.parse({+ accept: challengeAccept(),+ buyer: BUYER,+ tips: [+ { to: USDC, amount: '1' },+ { to: USDC, amount: '2' },+ { to: USDC, amount: '3' },+ ],+ }),+ ).toThrow();+ });+});+describe('x402-checkout ataExists — fail-open on a flaky RPC', () => {const ata = new PublicKey('HgwbNyweQUiV5diWJ1a7ocxgzf3AYSLhTpphEYRLujtN');