Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: x402 monetization, three-token dashboard, agent monetization, audit log, club + avatar updates

nirholas34ecfd1d5fcb
diff --git a/.env.example b/.env.example
index 8a434298c..825d8cde1 100644
--- a/.env.example
+++ b/.env.example
@@ -498,6 +498,12 @@ PAYMENT_RECIPIENT_SOLANA=
# Default 250 (2.5%). Validated to 0–10000 inclusive.
PLATFORM_FEE_BPS=250
+# Platform treasury keypair for agent monetization withdrawals. Base58-encoded
+# 64-byte Solana keypair or JSON-array format. Used by the monetization-payouts
+# (process-withdrawals) cron to send USDC to agent owners. When unset, the
+# cron skips Solana withdrawals with a clear error. Alias for TREASURY_KEYPAIR.
+PLATFORM_TREASURY_KEYPAIR=
+
# Referral commission paid out on confirmed purchases when the buyer arrived
# via a referral link, in basis points. Default 500 (5%).
REFERRAL_COMMISSION_BPS=500
diff --git a/.gitignore b/.gitignore
index 27fc714c8..e7e73081d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -105,3 +105,4 @@ docs/internal/COINMARKETCAP_PARTNERSHIP_ARTICLE.md
docs/internal/COINMARKETCAP_ARTICLE.md
docs/internal/PRESS_RELEASE_SHORT.md
scripts/load-test.mjs
+scripts/load-test-fleet.sh
diff --git a/api/_lib/migrations/2026-05-27-agent-monetization.sql b/api/_lib/migrations/2026-05-27-agent-monetization.sql
new file mode 100644
index 000000000..47f077d3a
--- /dev/null
+++ b/api/_lib/migrations/2026-05-27-agent-monetization.sql
@@ -0,0 +1,31 @@
+-- Migration: agent monetization schema refinements.
+--
+-- The core monetization tables (agent_skill_prices, agent_revenue_events,
+-- agent_payout_wallets, agent_withdrawals) were created in
+-- 2026-04-30-agent-monetization.sql. This migration adds columns requested
+-- by the unified /api/monetization/* endpoints:
+--
+-- • agent_skill_prices — price_usdc numeric view, currency default
+-- • agent_payout_wallets — preferred_network column
+-- • agent_withdrawals — destination_address alias, error column
+--
+-- Idempotent: every statement uses IF NOT EXISTS / IF EXISTS guards.
+
+begin;
+
+-- ── agent_payout_wallets: preferred_network ─────────────────────────────────
+alter table agent_payout_wallets
+ add column if not exists preferred_network text not null default 'solana';
+
+-- ── agent_withdrawals: error_message column (may already exist from v2) ─────
+alter table agent_withdrawals
+ add column if not exists error_message text;
+
+-- ── Ensure indexes exist ────────────────────────────────────────────────────
+create index if not exists agent_revenue_events_agent_skill
+ on agent_revenue_events (agent_id, skill);
+
+create index if not exists agent_withdrawals_created
+ on agent_withdrawals (created_at desc);
+
+commit;
diff --git a/api/_lib/migrations/2026-05-27-x402-audit-log.sql b/api/_lib/migrations/2026-05-27-x402-audit-log.sql
new file mode 100644
index 000000000..72ba64a65
--- /dev/null
+++ b/api/_lib/migrations/2026-05-27-x402-audit-log.sql
@@ -0,0 +1,26 @@
+-- x402 payment audit log — durable ledger of every payment event.
+-- Covers settlements, failures, SIWX grants/accesses, and access-control bypasses.
+-- Idempotent: safe to re-run.
+
+CREATE TABLE IF NOT EXISTS x402_audit_log (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ event_type TEXT NOT NULL, -- 'payment_settled', 'payment_failed', 'siwx_grant', 'siwx_access', 'bypass_granted'
+ route TEXT NOT NULL,
+ resource_url TEXT,
+ payer TEXT, -- wallet address
+ network TEXT,
+ amount_atomics TEXT,
+ asset TEXT,
+ tx_hash TEXT,
+ settlement_status TEXT, -- 'success', 'failed'
+ facilitator_response JSONB,
+ duration_ms INTEGER,
+ ip_address TEXT,
+ user_agent TEXT,
+ metadata JSONB,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+);
+
+CREATE INDEX IF NOT EXISTS idx_x402_audit_route ON x402_audit_log(route, created_at DESC);
+CREATE INDEX IF NOT EXISTS idx_x402_audit_payer ON x402_audit_log(payer, created_at DESC);
+CREATE INDEX IF NOT EXISTS idx_x402_audit_type ON x402_audit_log(event_type, created_at DESC);
diff --git a/api/_lib/migrations/20260527020000_developer_webhooks.sql b/api/_lib/migrations/20260527020000_developer_webhooks.sql
new file mode 100644
index 000000000..3b45226a8
--- /dev/null
+++ b/api/_lib/migrations/20260527020000_developer_webhooks.sql
@@ -0,0 +1,36 @@
+-- Developer webhooks: outgoing event notifications for partner integrations.
+-- Mirrors the Standard Webhooks signature format for verification.
+
+create table if not exists developer_webhooks (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id) on delete cascade,
+ url text not null,
+ secret text not null,
+ events text[] not null default '{}',
+ active boolean not null default true,
+ description text,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+create index if not exists developer_webhooks_user_active
+ on developer_webhooks (user_id) where active = true;
+
+create table if not exists webhook_deliveries (
+ id uuid primary key default gen_random_uuid(),
+ webhook_id uuid not null references developer_webhooks(id) on delete cascade,
+ event_type text not null,
+ event_id text not null,
+ payload jsonb not null,
+ status_code int,
+ response_body text,
+ error text,
+ attempt int not null default 1,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists webhook_deliveries_webhook_recent
+ on webhook_deliveries (webhook_id, created_at desc);
+
+create index if not exists webhook_deliveries_event_id
+ on webhook_deliveries (event_id);
diff --git a/api/_lib/monetization.js b/api/_lib/monetization.js
new file mode 100644
index 000000000..40db1ba10
--- /dev/null
+++ b/api/_lib/monetization.js
@@ -0,0 +1,110 @@
+// Monetization helpers — revenue recording and balance queries.
+//
+// Used by x402 intent consumption, skill purchase confirmation, and any
+// code path that needs to attribute revenue to an agent owner.
+
+import { sql } from './db.js';
+import { calculateFee } from './fee.js';
+
+/**
+ * Record an immutable revenue event for a consumed skill payment.
+ *
+ * @param {object} opts
+ * @param {string} opts.agentId - UUID of the agent that earned revenue
+ * @param {string} opts.skillName - skill identifier (e.g. "answer-question")
+ * @param {string} opts.callerAddress - payer wallet address (nullable)
+ * @param {number|bigint} opts.amountUsdc - gross amount in atomic units (USDC 6 decimals)
+ * @param {string} opts.network - chain name ("solana", "base", etc.)
+ * @param {string} opts.txHash - on-chain transaction hash/signature
+ * @param {string} [opts.currencyMint] - token mint/contract address
+ * @param {string} [opts.intentId] - payment intent ID if applicable
+ * @returns {Promise<object>} the inserted revenue event row
+ */
+export async function recordRevenueEvent({
+ agentId,
+ skillName,
+ callerAddress = null,
+ amountUsdc,
+ network,
+ txHash = null,
+ currencyMint = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ intentId = null,
+}) {
+ const grossAmount = Number(amountUsdc);
+ if (!Number.isFinite(grossAmount) || grossAmount <= 0) {
+ throw Object.assign(new Error('amountUsdc must be a positive number'), { status: 400 });
+ }
+ if (!agentId) {
+ throw Object.assign(new Error('agentId is required'), { status: 400 });
+ }
+ if (!skillName) {
+ throw Object.assign(new Error('skillName is required'), { status: 400 });
+ }
+
+ const { fee, net } = calculateFee(grossAmount);
+
+ const [row] = await sql`
+ INSERT INTO agent_revenue_events
+ (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount,
+ currency_mint, chain, payer_address)
+ VALUES
+ (${agentId}, ${intentId ?? txHash ?? 'direct'}, ${skillName}, ${grossAmount},
+ ${fee}, ${net}, ${currencyMint}, ${network}, ${callerAddress})
+ RETURNING id, agent_id, skill, gross_amount, fee_amount, net_amount,
+ currency_mint, chain, payer_address, created_at
+ `;
+
+ return row;
+}
+
+/**
+ * Calculate the available (withdrawable) balance for a user.
+ *
+ * available = sum(net_amount from revenue_events) - sum(amount from pending/processing/completed withdrawals)
+ *
+ * @param {string} userId
+ * @param {string} [currencyMint] - filter to a specific currency (default: all)
+ * @returns {Promise<{earned: number, withdrawn: number, pending: number, available: number}>}
+ */
+export async function getAvailableBalance(userId, currencyMint = null) {
+ const [result] = currencyMint
+ ? await sql`
+ SELECT
+ COALESCE(SUM(re.net_amount), 0)::bigint AS earned
+ FROM agent_revenue_events re
+ JOIN agent_identities ai ON ai.id = re.agent_id
+ WHERE ai.user_id = ${userId}
+ AND re.currency_mint = ${currencyMint}
+ `
+ : await sql`
+ SELECT
+ COALESCE(SUM(re.net_amount), 0)::bigint AS earned
+ FROM agent_revenue_events re
+ JOIN agent_identities ai ON ai.id = re.agent_id
+ WHERE ai.user_id = ${userId}
+ `;
+
+ const [wResult] = currencyMint
+ ? await sql`
+ SELECT
+ COALESCE(SUM(CASE WHEN status IN ('pending', 'processing') THEN amount ELSE 0 END), 0)::bigint AS pending,
+ COALESCE(SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END), 0)::bigint AS withdrawn
+ FROM agent_withdrawals
+ WHERE user_id = ${userId}
+ AND currency_mint = ${currencyMint}
+ `
+ : await sql`
+ SELECT
+ COALESCE(SUM(CASE WHEN status IN ('pending', 'processing') THEN amount ELSE 0 END), 0)::bigint AS pending,
+ COALESCE(SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END), 0)::bigint AS withdrawn
+ FROM agent_withdrawals
+ WHERE user_id = ${userId}
+ `;
+
+ const earned = Number(result.earned);
+ const pending = Number(wResult.pending);
+ const withdrawn = Number(wResult.withdrawn);
+ const available = earned - pending - withdrawn;
+
+ return { earned, withdrawn, pending, available: Math.max(0, available) };
+}
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index 2983e02b1..8062da748 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -30,6 +30,8 @@
import { cors, error } from './http.js';
import { env } from './env.js';
+import { clientIp } from './rate-limit.js';
+import { logPaymentEvent } from './x402/audit-log.js';
import { PAYMENT_EVENT_TOPIC as BSC_PAYMENT_EVENT_TOPIC } from './x402-bsc-direct.js';
import {
BUILDER_CODE,
@@ -277,6 +279,7 @@ export function paidEndpoint(spec) {
const pidExtension = paymentIdentifierExtension(pidRequired);
return async function paidHandler(req, res) {
+ const requestStartTime = Date.now();
if (cors(req, res, { methods: allowMethods, origins: '*' })) return;
if (req.method !== method.toUpperCase()) {
res.setHeader('allow', method.toUpperCase());
@@ -476,6 +479,16 @@ export function paidEndpoint(spec) {
res.end(
typeof bypassResult === 'string' ? bypassResult : JSON.stringify(bypassResult),
);
+ logPaymentEvent({
+ eventType: 'bypass_granted',
+ route,
+ resourceUrl,
+ payer: result.principal.userId || result.principal.address || null,
+ durationMs: Date.now() - requestStartTime,
+ ipAddress: clientIp(req),
+ userAgent: req.headers?.['user-agent']?.slice(0, 512) || null,
+ metadata: { reason: `auth-hints:${result.principal.method}` },
+ });
return;
}
}
@@ -542,6 +555,16 @@ export function paidEndpoint(spec) {
res.end(
typeof bypassResult === 'string' ? bypassResult : JSON.stringify(bypassResult),
);
+ logPaymentEvent({
+ eventType: 'bypass_granted',
+ route,
+ resourceUrl,
+ payer: acResult.callerId || null,
+ durationMs: Date.now() - requestStartTime,
+ ipAddress: clientIp(req),
+ userAgent: req.headers?.['user-agent']?.slice(0, 512) || null,
+ metadata: { reason: acResult.reason || 'access_control' },
+ });
return;
}
}
@@ -580,6 +603,16 @@ export function paidEndpoint(spec) {
res.setHeader('cache-control', 'no-store');
res.setHeader('content-type', `${mimeType}; charset=utf-8`);
res.end(typeof result === 'string' ? result : JSON.stringify(result));
+ logPaymentEvent({
+ eventType: 'siwx_access',
+ route,
+ resourceUrl,
+ payer: auth.address,
+ network: auth.network || null,
+ durationMs: Date.now() - requestStartTime,
+ ipAddress: clientIp(req),
+ userAgent: req.headers?.['user-agent']?.slice(0, 512) || null,
+ });
return;
}
if (auth && !auth.ok) {
@@ -661,6 +694,20 @@ export function paidEndpoint(spec) {
try {
settled = await settlePayment({ verified });
} catch (err) {
+ logPaymentEvent({
+ eventType: 'payment_failed',
+ route,
+ resourceUrl,
+ payer: verified.payer || null,
+ network: verified.requirement?.network || null,
+ amountAtomics: verified.requirement?.amount || null,
+ asset: verified.requirement?.asset || null,
+ settlementStatus: 'failed',
+ durationMs: Date.now() - requestStartTime,
+ ipAddress: clientIp(req),
+ userAgent: req.headers?.['user-agent']?.slice(0, 512) || null,
+ metadata: { error: err.message, code: err.code },
+ });
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
@@ -676,6 +723,16 @@ export function paidEndpoint(spec) {
network: verified.requirement.network,
ttlSeconds: siwx.ttlSeconds ?? null,
});
+ logPaymentEvent({
+ eventType: 'siwx_grant',
+ route,
+ resourceUrl,
+ payer: verified.payer,
+ network: verified.requirement.network,
+ ipAddress: clientIp(req),
+ userAgent: req.headers?.['user-agent']?.slice(0, 512) || null,
+ metadata: { ttlSeconds: siwx.ttlSeconds ?? null },
+ });
} catch (err) {
return error(res, 502, 'siwx_record_failed', err.message);
}
diff --git a/api/_lib/x402/audit-log.js b/api/_lib/x402/audit-log.js
new file mode 100644
index 000000000..81cd86f22
--- /dev/null
+++ b/api/_lib/x402/audit-log.js
@@ -0,0 +1,283 @@
+// x402 audit log — durable ledger of every payment event.
+//
+// Three exports:
+// logPaymentEvent(event) — fire-and-forget INSERT. Never blocks, never throws.
+// getAuditLog({ route?, payer?, eventType?, since?, limit? }) — filtered query.
+// getPaymentStats({ since?, groupBy? }) — aggregate stats for dashboards.
+//
+// Schema: api/_lib/migrations/2026-05-27-x402-audit-log.sql
+//
+// Design rules:
+// 1. logPaymentEvent is fire-and-forget via queueMicrotask. A DB hiccup must
+// NEVER cause a payment to fail or a response to delay.
+// 2. Only on-chain identifiers enter the log (addresses, tx hashes, amounts).
+// IP and UA are captured for rate-limit forensics but never surfaced to
+// non-admin callers.
+// 3. All queries use the covering indexes on (route, created_at),
+// (payer, created_at), and (event_type, created_at).
+
+import { sql } from '../db.js';
+
+/**
+ * Fire-and-forget audit log write. Swallows all errors.
+ *
+ * @param {object} event
+ * @param {string} event.eventType — 'payment_settled' | 'payment_failed' | 'siwx_grant' | 'siwx_access' | 'bypass_granted'
+ * @param {string} event.route — e.g. '/api/x402/dance-tip'
+ * @param {string|null} [event.resourceUrl]
+ * @param {string|null} [event.payer] — wallet address
+ * @param {string|null} [event.network] — CAIP-2 chain ID
+ * @param {string|null} [event.amountAtomics] — atomic USDC amount
+ * @param {string|null} [event.asset] — asset address/mint
+ * @param {string|null} [event.txHash] — on-chain transaction hash
+ * @param {string|null} [event.settlementStatus] — 'success' | 'failed'
+ * @param {object|null} [event.facilitatorResponse]
+ * @param {number|null} [event.durationMs] — ms from request start to settle
+ * @param {string|null} [event.ipAddress]
+ * @param {string|null} [event.userAgent]
+ * @param {object|null} [event.metadata] — small JSON blob
+ */
+export function logPaymentEvent(event) {
+ queueMicrotask(async () => {
+ try {
+ await sql`
+ INSERT INTO x402_audit_log
+ (event_type, route, resource_url, payer, network, amount_atomics,
+ asset, tx_hash, settlement_status, facilitator_response,
+ duration_ms, ip_address, user_agent, metadata)
+ VALUES
+ (${event.eventType},
+ ${event.route},
+ ${event.resourceUrl ?? null},
+ ${event.payer ?? null},
+ ${event.network ?? null},
+ ${event.amountAtomics ?? null},
+ ${event.asset ?? null},
+ ${event.txHash ?? null},
+ ${event.settlementStatus ?? null},
+ ${event.facilitatorResponse ? JSON.stringify(event.facilitatorResponse) : null},
+ ${event.durationMs ?? null},
+ ${event.ipAddress ?? null},
+ ${event.userAgent ?? null},
+ ${event.metadata ? JSON.stringify(event.metadata) : null})
+ `;
+ } catch (err) {
+ console.error('[x402-audit] insert failed', {
+ eventType: event.eventType,
+ route: event.route,
+ error: err?.message,
+ });
+ }
+ });
+}
+
+/**
+ * Query the audit log with optional filters.
+ *
+ * @param {object} [filters]
+ * @param {string} [filters.route]
+ * @param {string} [filters.payer]
+ * @param {string} [filters.eventType]
+ * @param {string} [filters.network]
+ * @param {string} [filters.since] — ISO 8601 timestamp
+ * @param {number} [filters.limit] — max rows (default 100, max 1000)
+ * @param {number} [filters.offset] — pagination offset (default 0)
+ * @returns {Promise<Array>}
+ */
+export async function getAuditLog({
+ route,
+ payer,
+ eventType,
+ network,
+ since,
+ limit = 100,
+ offset = 0,
+} = {}) {
+ const effectiveLimit = Math.min(Math.max(1, Number(limit) || 100), 1000);
+ const effectiveOffset = Math.max(0, Number(offset) || 0);
+
+ const rows = await sql`
+ SELECT
+ id, event_type, route, resource_url, payer, network,
+ amount_atomics, asset, tx_hash, settlement_status,
+ duration_ms, metadata, created_at
+ FROM x402_audit_log
+ WHERE
+ (${route ?? null}::text IS NULL OR route = ${route ?? null})
+ AND (${payer ?? null}::text IS NULL OR payer = ${payer ?? null})
+ AND (${eventType ?? null}::text IS NULL OR event_type = ${eventType ?? null})
+ AND (${network ?? null}::text IS NULL OR network = ${network ?? null})
+ AND (${since ?? null}::timestamptz IS NULL OR created_at >= ${since ?? null}::timestamptz)
+ ORDER BY created_at DESC
+ LIMIT ${effectiveLimit}
+ OFFSET ${effectiveOffset}
+ `;
+ return rows;
+}
+
+/**
+ * Aggregate payment statistics for the analytics dashboard.
+ *
+ * @param {object} [opts]
+ * @param {string} [opts.since] — ISO 8601 timestamp
+ * @param {string} [opts.groupBy] — 'route' | 'network' | 'day' (default: all)
+ * @returns {Promise<object>}
+ */
+export async function getPaymentStats({ since, groupBy } = {}) {
+ const sinceTs = since || null;
+
+ // Overall totals
+ const [totals] = await sql`
+ SELECT
+ count(*)::int AS total_payments,
+ coalesce(sum(
+ CASE WHEN amount_atomics IS NOT NULL AND amount_atomics ~ '^[0-9]+$'
+ THEN amount_atomics::numeric ELSE 0 END
+ ), 0) AS total_volume_atomics,
+ count(DISTINCT payer)::int AS unique_payers
+ FROM x402_audit_log
+ WHERE event_type = 'payment_settled'
+ AND (${sinceTs}::timestamptz IS NULL OR created_at >= ${sinceTs}::timestamptz)
+ `;
+
+ const totalVolume = totals.total_volume_atomics || 0;
+ const totalPayments = totals.total_payments || 0;
+ const uniquePayers = totals.unique_payers || 0;
+ const avgPayment = totalPayments > 0
+ ? (Number(totalVolume) / totalPayments).toFixed(0)
+ : '0';
+
+ // By route
+ const byRoute = await sql`
+ SELECT
+ route,
+ count(*)::int AS count,
+ coalesce(sum(
+ CASE WHEN amount_atomics IS NOT NULL AND amount_atomics ~ '^[0-9]+$'
+ THEN amount_atomics::numeric ELSE 0 END
+ ), 0)::text AS volume
+ FROM x402_audit_log
+ WHERE event_type = 'payment_settled'
+ AND (${sinceTs}::timestamptz IS NULL OR created_at >= ${sinceTs}::timestamptz)
+ GROUP BY route
+ ORDER BY count DESC
+ `;
+
+ // By network
+ const byNetwork = await sql`
+ SELECT
+ network,
+ count(*)::int AS count
+ FROM x402_audit_log
+ WHERE event_type = 'payment_settled'
+ AND (${sinceTs}::timestamptz IS NULL OR created_at >= ${sinceTs}::timestamptz)
+ GROUP BY network
+ ORDER BY count DESC
+ `;
+
+ // By day
+ const byDay = await sql`
+ SELECT
+ to_char(created_at, 'YYYY-MM-DD') AS date,
+ count(*)::int AS count,
+ coalesce(sum(
+ CASE WHEN amount_atomics IS NOT NULL AND amount_atomics ~ '^[0-9]+$'
+ THEN amount_atomics::numeric ELSE 0 END
+ ), 0)::text AS volume
+ FROM x402_audit_log
+ WHERE event_type = 'payment_settled'
+ AND (${sinceTs}::timestamptz IS NULL OR created_at >= ${sinceTs}::timestamptz)
+ GROUP BY to_char(created_at, 'YYYY-MM-DD')
+ ORDER BY date DESC
+ `;
+
+ // SIWX stats
+ const [siwxStats] = await sql`
+ SELECT
+ count(*) FILTER (WHERE event_type = 'siwx_grant')::int AS grants,
+ count(*) FILTER (WHERE event_type = 'siwx_access')::int AS accesses
+ FROM x402_audit_log
+ WHERE event_type IN ('siwx_grant', 'siwx_access')
+ AND (${sinceTs}::timestamptz IS NULL OR created_at >= ${sinceTs}::timestamptz)
+ `;
+
+ // Bypass stats
+ const bypassRows = await sql`
+ SELECT
+ coalesce((metadata->>'reason')::text, 'unknown') AS reason,
+ count(*)::int AS count
+ FROM x402_audit_log
+ WHERE event_type = 'bypass_granted'
+ AND (${sinceTs}::timestamptz IS NULL OR created_at >= ${sinceTs}::timestamptz)
+ GROUP BY coalesce((metadata->>'reason')::text, 'unknown')
+ `;
+ const bypassByReason = {};
+ let bypassTotal = 0;
+ for (const r of bypassRows) {
+ bypassByReason[r.reason] = r.count;
+ bypassTotal += r.count;
+ }
+
+ // Failed payments count
+ const [failedStats] = await sql`
+ SELECT count(*)::int AS total_failed
+ FROM x402_audit_log
+ WHERE event_type = 'payment_failed'
+ AND (${sinceTs}::timestamptz IS NULL OR created_at >= ${sinceTs}::timestamptz)
+ `;
+
+ // Format volume to USDC (6 decimals)
+ function atomicsToUsdc(atomics) {
+ const n = Number(atomics || 0);
+ return (n / 1e6).toFixed(6);
+ }
+
+ return {
+ total_payments: totalPayments,
+ total_volume_usdc: atomicsToUsdc(totalVolume),
+ unique_payers: uniquePayers,
+ avg_payment_usdc: atomicsToUsdc(avgPayment),
+ total_failed: failedStats.total_failed || 0,
+ by_route: byRoute.map((r) => ({
+ route: r.route,
+ count: r.count,
+ volume: atomicsToUsdc(r.volume),
+ })),
+ by_network: byNetwork.map((r) => ({
+ network: r.network,
+ count: r.count,
+ })),
+ by_day: byDay.map((r) => ({
+ date: r.date,
+ count: r.count,
+ volume: atomicsToUsdc(r.volume),
+ })),
+ siwx_stats: {
+ grants: siwxStats?.grants || 0,
+ accesses: siwxStats?.accesses || 0,
+ },
+ bypass_stats: {
+ total: bypassTotal,
+ by_reason: bypassByReason,
+ },
+ };
+}
+
+/**
+ * Count recent payments — used by /api/healthz for the x402 health block.
+ * @param {number} [withinMinutes=60]
+ * @returns {Promise<number>}
+ */
+export async function countRecentPayments(withinMinutes = 60) {
+ try {
+ const [row] = await sql`
+ SELECT count(*)::int AS n
+ FROM x402_audit_log
+ WHERE event_type = 'payment_settled'
+ AND created_at >= NOW() - (${withinMinutes} || ' minutes')::interval
+ `;
+ return row?.n || 0;
+ } catch {
+ return -1;
+ }
+}
diff --git a/api/avatar/render.js b/api/avatar/render.js
index 160c45f64..3f3b5cc8f 100644
--- a/api/avatar/render.js
+++ b/api/avatar/render.js
@@ -22,10 +22,12 @@
// to the avatar (appearance, GLB, etc.) automatically bust the cache.
import { createHash } from 'node:crypto';
+import puppeteer from 'puppeteer-core';
+import chromium from '@sparticuz/chromium-min';
import { cors, error, json, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
import { getAvatar } from '../_lib/avatars.js';
import { publicUrl, putObject, headObject } from '../_lib/r2.js';
-import { renderClip } from '../_lib/render-clip.js';
import { PRESETS } from '../../src/pose-presets.js';
export const maxDuration = 30;
@@ -168,7 +170,7 @@ export default wrap(async function handler(req, res) {
const key = cacheKey(avatar.id, paramFingerprint, format);
try {
- const head = await headObject({ key });
+ const head = await headObject(key);
if (head) {
const cdnUrl = publicUrl(key);
res.statusCode = 302;
diff --git a/api/avatars/[id].js b/api/avatars/[id].js
index 220e023a8..c820d6c0f 100644
--- a/api/avatars/[id].js
+++ b/api/avatars/[id].js
@@ -21,6 +21,7 @@ import { recordEvent } from '../_lib/usage.js';
import { z } from 'zod';
import { avatarVisibility, avatarAppearance, parse } from '../_lib/validate.js';
import { DEMO_AVATARS } from '../_lib/demo-avatars.js';
+import { dispatchWebhooks } from '../_lib/webhook-dispatch.js';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -186,6 +187,12 @@ export default wrap(async (req, res) => {
}
}
+ dispatchWebhooks({
+ userId: auth.userId,
+ eventType: appearanceChanged ? 'avatar.appearance.changed' : 'avatar.updated',
+ data: { id: avatar.id, name: avatar.name, slug: avatar.slug, updated_at: avatar.updated_at },
+ }).catch(() => {});
+
return json(res, 200, { avatar });
}
@@ -202,6 +209,11 @@ export default wrap(async (req, res) => {
resourceId: id,
meta: { via: auth.source },
});
+ dispatchWebhooks({
+ userId: auth.userId,
+ eventType: 'avatar.deleted',
+ data: { id },
+ }).catch(() => {});
return json(res, 200, { ok: true });
});
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index 825eb580a..ef68f08dd 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -12,6 +12,7 @@ import { parse, presignUploadBody, slug as slugSchema, createAvatarBody } from '
import { recordEvent } from '../_lib/usage.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { dispatchWebhooks } from '../_lib/webhook-dispatch.js';
import { z } from 'zod';
import { randomUUID } from 'crypto';
import { isValidGlbHeader, inspectGlb } from '../_lib/glb-inspect.js';
@@ -456,6 +457,11 @@ const handleRegenerateStatus = wrap(async (req, res) => {
set result_avatar_id = ${avatar.id}, updated_at = now()
where job_id = ${jobId} and user_id = ${userId}
`;
+ dispatchWebhooks({
+ userId,
+ eventType: 'avatar.created',
+ data: { id: avatar.id, name: avatar.name, slug: avatar.slug, source: 'reconstruct' },
+ }).catch(() => {});
job = { ...job, result_avatar_id: avatar.id };
} catch (err) {
job = { ...job, error: job.error || `materialize failed: ${err?.message}` };
diff --git a/api/avatars/index.js b/api/avatars/index.js
index cf8f1a269..417da99b1 100644
--- a/api/avatars/index.js
+++ b/api/avatars/index.js
@@ -11,6 +11,7 @@ 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 { defaultStorageMode } from '../_lib/storage-mode.js';
+import { dispatchWebhooks } from '../_lib/webhook-dispatch.js';
import { z } from 'zod';
const createWithStorage = createAvatarBody.extend({
@@ -97,6 +98,12 @@ async function handleCreate(req, res) {
storageKey: body.storage_key,
});
+ dispatchWebhooks({
+ userId: auth.userId,
+ eventType: 'avatar.created',
+ data: { id: avatar.id, name: avatar.name, slug: avatar.slug, source: body.source },
+ }).catch(() => {});
+
// Re-point any agent identity that currently uses the parent avatar.
// agentId, wallet_address, chain_id, and erc8004_agent_id are unchanged.
if (body.parent_avatar_id) {
diff --git a/api/cron/[name].js b/api/cron/[name].js
index e7580d4e3..0ee66a037 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -68,6 +68,7 @@ const HANDLERS = {
'expire-pending-purchases': handleExpirePendingPurchases,
'cleanup-csrf-tokens': handleCleanupCsrfTokens,
'process-withdrawals': handleProcessWithdrawals,
+ 'monetization-payouts': handleProcessWithdrawals,
'run-x-scheduled-posts': handleRunXScheduledPosts,
'run-x-triggers': handleRunXTriggers,
'fetch-x-metrics': handleFetchXMetrics,
@@ -2542,8 +2543,9 @@ async function handleCleanupCsrfTokens(req, res) {
// ═══════════════════════════════════════════════════════════════════════════
// siwx-gc — prune SIWX nonces (replay window) and expired payment grants.
-// Hourly. Nonce window of 10 min is well above the 5-min SIWX maxAge;
-// payments grace of 7 days avoids cutting off slow clients at the boundary.
+// Daily at 03:00 UTC. Nonce window of 10 min (600s) is well above the 5-min
+// SIWX maxAge; payments grace of 7 days avoids cutting off slow clients at
+// the boundary.
// ═══════════════════════════════════════════════════════════════════════════
async function handleSiwxGc(req, res) {
@@ -2558,14 +2560,12 @@ async function handleSiwxGc(req, res) {
const { pruneOldNonces, pruneExpiredPayments } = await import('../_lib/siwx-storage.js');
- const noncesDeleted = await pruneOldNonces(10 * 60);
- const paymentsDeleted = await pruneExpiredPayments(7 * 24 * 3600);
+ const nonces_pruned = await pruneOldNonces(600);
+ const payments_pruned = await pruneExpiredPayments(7 * 24 * 3600);
return json(res, 200, {
- ok: true,
- noncesDeleted,
- paymentsDeleted,
- ranAt: new Date().toISOString(),
+ nonces_pruned,
+ payments_pruned,
});
}
diff --git a/api/monetization/prices.js b/api/monetization/prices.js
new file mode 100644
index 000000000..70519565d
--- /dev/null
+++ b/api/monetization/prices.js
@@ -0,0 +1,176 @@
+// GET /api/monetization/prices?agent_id=X — list active prices for an agent
+// PUT /api/monetization/prices — set/update price for a skill (owner only)
+// DELETE /api/monetization/prices — remove price for a skill (owner only)
+//
+// Body (PUT): { agent_id, skill_name, price_usdc, currency_mint?, chain? }
+// Body (DELETE): { agent_id, skill_name, hard? }
+
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
+import { parse } from '../_lib/validate.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+const SKILL_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+// USDC has 6 decimals. 0.000001 USDC = 1 atomic unit.
+const MIN_PRICE_ATOMIC = 1;
+
+const putBody = z.object({
+ agent_id: z.string().uuid(),
+ skill_name: z.string().trim().min(1).max(64).regex(SKILL_RE, 'skill_name must be alphanumeric with hyphens/underscores, max 64 chars'),
+ price_usdc: z.number().positive(),
+ currency_mint: z.string().trim().min(1).max(100).default('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),
+ chain: z.enum(['solana', 'base', 'evm']).default('solana'),
+});
+
+const deleteBody = z.object({
+ agent_id: z.string().uuid(),
+ skill_name: z.string().trim().min(1).max(64),
+ hard: z.boolean().default(false),
+});
+
+async function resolveUserId(req) {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return bearer.userId;
+ return null;
+}
+
+async function verifyAgentOwnership(agentId, userId) {
+ const [agent] = await sql`
+ SELECT id, user_id FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!agent) return { error: 'not_found', message: 'Agent not found' };
+ if (agent.user_id !== userId) return { error: 'forbidden', message: 'You don\'t own this agent' };
+ return { agent };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,PUT,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PUT', 'DELETE'])) return;
+
+ // GET is public for listed agents
+ if (req.method === 'GET') {
+ const rl = await limits.pricingPerIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const params = new URL(req.url, 'http://x').searchParams;
+ const agentId = params.get('agent_id');
+ if (!agentId || !UUID_RE.test(agentId)) {
+ return error(res, 400, 'validation_error', 'agent_id query parameter is required and must be a UUID');
+ }
+
+ const [agent] = await sql`
+ SELECT id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'Agent not found');
+
+ const prices = await sql`
+ SELECT id, skill, currency_mint, chain, amount, is_active, created_at, updated_at
+ FROM agent_skill_prices
+ WHERE agent_id = ${agentId} AND is_active = true
+ ORDER BY skill
+ `;
+
+ return json(res, 200, {
+ prices: prices.map(formatPrice),
+ });
+ }
+
+ // PUT and DELETE require auth
+ const userId = await resolveUserId(req);
+ if (!userId) return error(res, 401, 'unauthorized', 'Sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ if (req.method === 'PUT') {
+ const body = parse(putBody, await readJson(req));
+ const { agent_id, skill_name, price_usdc, currency_mint, chain } = body;
+
+ // Convert price_usdc (float like 0.001) to atomic units (bigint-safe integer)
+ const amountAtomic = Math.round(price_usdc * 1_000_000);
+ if (amountAtomic < MIN_PRICE_ATOMIC) {
+ return error(res, 400, 'validation_error', 'price_usdc must be at least 0.000001');
+ }
+
+ const ownership = await verifyAgentOwnership(agent_id, userId);
+ if (ownership.error) {
+ const status = ownership.error === 'not_found' ? 404 : 403;
+ return error(res, status, ownership.error, ownership.message);
+ }
+
+ const [existing] = await sql`
+ SELECT id FROM agent_skill_prices WHERE agent_id = ${agent_id} AND skill = ${skill_name}
+ `;
+
+ await sql`
+ INSERT INTO agent_skill_prices
+ (agent_id, skill, amount, currency_mint, chain, is_active, updated_at)
+ VALUES
+ (${agent_id}, ${skill_name}, ${amountAtomic}, ${currency_mint}, ${chain}, true, now())
+ ON CONFLICT (agent_id, skill) DO UPDATE SET
+ amount = EXCLUDED.amount,
+ currency_mint = EXCLUDED.currency_mint,
+ chain = EXCLUDED.chain,
+ is_active = true,
+ updated_at = now()
+ `;
+
+ const [row] = await sql`
+ SELECT id, skill, currency_mint, chain, amount, is_active, created_at, updated_at
+ FROM agent_skill_prices
+ WHERE agent_id = ${agent_id} AND skill = ${skill_name}
+ `;
+
+ return json(res, existing ? 200 : 201, { price: formatPrice(row) });
+ }
+
+ // DELETE
+ const body = parse(deleteBody, await readJson(req));
+ const { agent_id, skill_name, hard } = body;
+
+ const ownership = await verifyAgentOwnership(agent_id, userId);
+ if (ownership.error) {
+ const status = ownership.error === 'not_found' ? 404 : 403;
+ return error(res, status, ownership.error, ownership.message);
+ }
+
+ if (hard) {
+ const [deleted] = await sql`
+ DELETE FROM agent_skill_prices
+ WHERE agent_id = ${agent_id} AND skill = ${skill_name}
+ RETURNING id
+ `;
+ if (!deleted) return error(res, 404, 'not_found', 'Price not found for this skill');
+ } else {
+ const [updated] = await sql`
+ UPDATE agent_skill_prices
+ SET is_active = false, updated_at = now()
+ WHERE agent_id = ${agent_id} AND skill = ${skill_name}
+ RETURNING id
+ `;
+ if (!updated) return error(res, 404, 'not_found', 'Price not found for this skill');
+ }
+
+ return json(res, 200, { deleted: true, agent_id, skill_name });
+});
+
+function formatPrice(row) {
+ return {
+ id: row.id,
+ skill_name: row.skill,
+ price_usdc: Number(row.amount) / 1_000_000,
+ amount_atomic: Number(row.amount),
+ currency_mint: row.currency_mint,
+ chain: row.chain,
+ is_active: row.is_active,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ };
+}
diff --git a/api/monetization/revenue.js b/api/monetization/revenue.js
new file mode 100644
index 000000000..2b4c1c62a
--- /dev/null
+++ b/api/monetization/revenue.js
@@ -0,0 +1,153 @@
+// GET /api/monetization/revenue?agent_id=X&period=7d
+//
+// Returns aggregated revenue for the authenticated user's agents.
+// Periods: 1d, 7d, 30d, 90d, all
+// Response: { total_usdc, total_fees_usdc, net_usdc, event_count,
+// by_skill: [{skill, total, count}],
+// by_day: [{date, total}] }
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+const PERIOD_TO_INTERVAL = {
+ '1d': '1 day',
+ '7d': '7 days',
+ '30d': '30 days',
+ '90d': '90 days',
+ 'all': null,
+};
+
+async function resolveUserId(req) {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return bearer.userId;
+ return null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const userId = await resolveUserId(req);
+ if (!userId) return error(res, 401, 'unauthorized', 'Sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const params = new URL(req.url, 'http://x').searchParams;
+
+ const agentId = params.get('agent_id') || null;
+ if (agentId && !UUID_RE.test(agentId)) {
+ return error(res, 400, 'validation_error', 'agent_id must be a UUID');
+ }
+
+ // Verify agent ownership if agent_id is specified
+ if (agentId) {
+ const [agent] = await sql`
+ SELECT id, user_id FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'Agent not found');
+ if (agent.user_id !== userId) return error(res, 403, 'forbidden', 'You don\'t own this agent');
+ }
+
+ const period = params.get('period') || '7d';
+ if (!PERIOD_TO_INTERVAL.hasOwnProperty(period)) {
+ return error(res, 400, 'validation_error', 'period must be one of: 1d, 7d, 30d, 90d, all');
+ }
+
+ const interval = PERIOD_TO_INTERVAL[period];
+ const now = new Date();
+ const fromDate = interval
+ ? new Date(now.getTime() - parseIntervalMs(interval))
+ : new Date('2020-01-01');
+ const toDate = now;
+
+ // Build queries with conditional agent filter
+ const baseParams = [userId, fromDate, toDate];
+ const agentFilter = agentId ? 'AND re.agent_id = $4::uuid' : '';
+ const filterParams = agentId ? [...baseParams, agentId] : baseParams;
+
+ // Summary aggregation
+ const [summary] = await sql(
+ `SELECT
+ COALESCE(SUM(re.gross_amount), 0)::bigint AS gross_total,
+ COALESCE(SUM(re.fee_amount), 0)::bigint AS fee_total,
+ COALESCE(SUM(re.net_amount), 0)::bigint AS net_total,
+ COUNT(*)::int AS event_count
+ FROM agent_revenue_events re
+ JOIN agent_identities ai ON ai.id = re.agent_id
+ WHERE ai.user_id = $1
+ AND re.created_at BETWEEN $2 AND $3
+ ${agentFilter}`,
+ filterParams,
+ );
+
+ // Per-skill breakdown
+ const bySkill = await sql(
+ `SELECT
+ re.skill,
+ COALESCE(SUM(re.net_amount), 0)::bigint AS net_total,
+ COUNT(*)::int AS count
+ FROM agent_revenue_events re
+ JOIN agent_identities ai ON ai.id = re.agent_id
+ WHERE ai.user_id = $1
+ AND re.created_at BETWEEN $2 AND $3
+ ${agentFilter}
+ GROUP BY re.skill
+ ORDER BY net_total DESC`,
+ filterParams,
+ );
+
+ // Daily timeseries
+ const byDay = await sql(
+ `SELECT
+ date_trunc('day', re.created_at) AS period,
+ COALESCE(SUM(re.net_amount), 0)::bigint AS net_total,
+ COUNT(*)::int AS count
+ FROM agent_revenue_events re
+ JOIN agent_identities ai ON ai.id = re.agent_id
+ WHERE ai.user_id = $1
+ AND re.created_at BETWEEN $2 AND $3
+ ${agentFilter}
+ GROUP BY period
+ ORDER BY period`,
+ filterParams,
+ );
+
+ return json(res, 200, {
+ total_usdc: Number(summary.gross_total) / 1_000_000,
+ total_fees_usdc: Number(summary.fee_total) / 1_000_000,
+ net_usdc: Number(summary.net_total) / 1_000_000,
+ event_count: summary.event_count,
+ // Raw atomic values for precision-sensitive clients
+ total_atomic: Number(summary.gross_total),
+ fees_atomic: Number(summary.fee_total),
+ net_atomic: Number(summary.net_total),
+ by_skill: bySkill.map((r) => ({
+ skill: r.skill,
+ total: Number(r.net_total) / 1_000_000,
+ total_atomic: Number(r.net_total),
+ count: r.count,
+ })),
+ by_day: byDay.map((r) => ({
+ date: r.period instanceof Date ? r.period.toISOString().slice(0, 10) : String(r.period).slice(0, 10),
+ total: Number(r.net_total) / 1_000_000,
+ total_atomic: Number(r.net_total),
+ count: r.count,
+ })),
+ });
+});
+
+function parseIntervalMs(interval) {
+ const m = /^(\d+)\s*(day|days|hour|hours)$/.exec(interval);
+ if (!m) return 7 * 86400e3;
+ const n = parseInt(m[1], 10);
+ const unit = m[2].startsWith('hour') ? 3600e3 : 86400e3;
+ return n * unit;
+}
diff --git a/api/monetization/wallet.js b/api/monetization/wallet.js
new file mode 100644
index 000000000..09adc8a59
--- /dev/null
+++ b/api/monetization/wallet.js
@@ -0,0 +1,172 @@
+// GET /api/monetization/wallet?agent_id=X — get payout wallet config
+// PUT /api/monetization/wallet — set/update payout addresses
+//
+// Body (PUT): { agent_id, evm_address?, solana_address?, preferred_network? }
+
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
+import { parse, isValidSolanaAddress, isValidEvmAddress } from '../_lib/validate.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+const putBody = z.object({
+ agent_id: z.string().uuid(),
+ evm_address: z.string().trim().max(100).nullable().optional(),
+ solana_address: z.string().trim().max(100).nullable().optional(),
+ preferred_network: z.enum(['solana', 'base', 'evm']).default('solana'),
+});
+
+async function resolveUserId(req) {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return bearer.userId;
+ return null;
+}
+
+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 userId = await resolveUserId(req);
+ if (!userId) return error(res, 401, 'unauthorized', 'Sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ if (req.method === 'GET') {
+ const params = new URL(req.url, 'http://x').searchParams;
+ const agentId = params.get('agent_id');
+
+ if (agentId && !UUID_RE.test(agentId)) {
+ return error(res, 400, 'validation_error', 'agent_id must be a UUID');
+ }
+
+ // Verify ownership if agent_id specified
+ if (agentId) {
+ const [agent] = await sql`
+ SELECT id, user_id FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'Agent not found');
+ if (agent.user_id !== userId) return error(res, 403, 'forbidden', 'You don\'t own this agent');
+ }
+
+ // Fetch all wallets for the user, optionally filtered by agent_id
+ const wallets = agentId
+ ? await sql`
+ SELECT id, agent_id, address, chain, is_default, preferred_network, created_at
+ FROM agent_payout_wallets
+ WHERE user_id = ${userId} AND (agent_id = ${agentId} OR agent_id IS NULL)
+ ORDER BY agent_id NULLS LAST, is_default DESC, created_at DESC
+ `
+ : await sql`
+ SELECT id, agent_id, address, chain, is_default, preferred_network, created_at
+ FROM agent_payout_wallets
+ WHERE user_id = ${userId}
+ ORDER BY agent_id NULLS LAST, is_default DESC, created_at DESC
+ `;
+
+ // Also build a summary view: resolve which addresses would be used for each chain
+ const evmWallet = wallets.find(
+ (w) => (w.chain === 'base' || w.chain === 'evm') && (agentId ? w.agent_id === agentId : true),
+ );
+ const solanaWallet = wallets.find(
+ (w) => w.chain === 'solana' && (agentId ? w.agent_id === agentId : true),
+ );
+
+ return json(res, 200, {
+ wallets,
+ resolved: {
+ evm_address: evmWallet?.address ?? null,
+ solana_address: solanaWallet?.address ?? null,
+ preferred_network: wallets[0]?.preferred_network ?? 'solana',
+ },
+ });
+ }
+
+ // PUT — set/update payout addresses
+ const body = parse(putBody, await readJson(req));
+ const { agent_id, evm_address, solana_address, preferred_network } = body;
+
+ // Verify agent ownership
+ const [agent] = await sql`
+ SELECT id, user_id FROM agent_identities
+ WHERE id = ${agent_id} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'Agent not found');
+ if (agent.user_id !== userId) return error(res, 403, 'forbidden', 'You don\'t own this agent');
+
+ // Validate addresses if provided
+ if (evm_address && !isValidEvmAddress(evm_address)) {
+ return error(res, 400, 'validation_error', 'Invalid EVM address (must start with 0x, 42 characters)');
+ }
+ if (solana_address && !isValidSolanaAddress(solana_address)) {
+ return error(res, 400, 'validation_error', 'Invalid Solana address (must be base58, 32-44 characters)');
+ }
+
+ if (!evm_address && !solana_address) {
+ return error(res, 400, 'validation_error', 'At least one address (evm_address or solana_address) is required');
+ }
+
+ const results = [];
+
+ // Upsert Solana wallet
+ if (solana_address) {
+ // Clear existing default for this (user, agent, solana)
+ await sql`
+ UPDATE agent_payout_wallets
+ SET is_default = false
+ WHERE user_id = ${userId} AND chain = 'solana'
+ AND (agent_id = ${agent_id} OR (agent_id IS NULL AND ${agent_id}::uuid IS NULL))
+ `;
+
+ const [wallet] = await sql`
+ INSERT INTO agent_payout_wallets
+ (user_id, agent_id, address, chain, is_default, preferred_network)
+ VALUES
+ (${userId}, ${agent_id}, ${solana_address}, 'solana', true, ${preferred_network})
+ ON CONFLICT (user_id, agent_id, chain) DO UPDATE SET
+ address = EXCLUDED.address,
+ is_default = true,
+ preferred_network = EXCLUDED.preferred_network
+ RETURNING id, agent_id, address, chain, is_default, preferred_network, created_at
+ `;
+ results.push(wallet);
+ }
+
+ // Upsert EVM wallet
+ if (evm_address) {
+ await sql`
+ UPDATE agent_payout_wallets
+ SET is_default = false
+ WHERE user_id = ${userId} AND chain = 'base'
+ AND (agent_id = ${agent_id} OR (agent_id IS NULL AND ${agent_id}::uuid IS NULL))
+ `;
+
+ const [wallet] = await sql`
+ INSERT INTO agent_payout_wallets
+ (user_id, agent_id, address, chain, is_default, preferred_network)
+ VALUES
+ (${userId}, ${agent_id}, ${evm_address}, 'base', true, ${preferred_network})
+ ON CONFLICT (user_id, agent_id, chain) DO UPDATE SET
+ address = EXCLUDED.address,
+ is_default = true,
+ preferred_network = EXCLUDED.preferred_network
+ RETURNING id, agent_id, address, chain, is_default, preferred_network, created_at
+ `;
+ results.push(wallet);
+ }
+
+ return json(res, 200, {
+ wallets: results,
+ resolved: {
+ evm_address: evm_address ?? null,
+ solana_address: solana_address ?? null,
+ preferred_network,
+ },
+ });
+});
diff --git a/api/monetization/withdrawals.js b/api/monetization/withdrawals.js
new file mode 100644
index 000000000..fe1633c62
--- /dev/null
+++ b/api/monetization/withdrawals.js
@@ -0,0 +1,212 @@
+// GET /api/monetization/withdrawals?agent_id=X — list withdrawal history
+// POST /api/monetization/withdrawals — request a withdrawal
+//
+// Body (POST): { agent_id, amount_usdc? }
+// amount_usdc = null → withdraw all available balance
+
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
+import { parse, isValidSolanaAddress, isValidEvmAddress } from '../_lib/validate.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { getAvailableBalance } from '../_lib/monetization.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+const MIN_WITHDRAWAL_USDC = 1; // 1 USDC minimum
+const MIN_WITHDRAWAL_ATOMIC = MIN_WITHDRAWAL_USDC * 1_000_000;
+
+const postBody = z.object({
+ agent_id: z.string().uuid(),
+ amount_usdc: z.number().positive().nullable().optional(),
+});
+
+async function resolveUser(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id, source: 'session' };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId, source: 'bearer' };
+ return null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const auth = await resolveUser(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'Sign in required');
+ const { userId } = auth;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ if (req.method === 'GET') {
+ const params = new URL(req.url, 'http://x').searchParams;
+ const agentId = params.get('agent_id') || null;
+ const statusFilter = params.get('status') || null;
+ const limit = Math.min(100, Math.max(1, parseInt(params.get('limit') || '20', 10)));
+ const offset = Math.max(0, parseInt(params.get('offset') || '0', 10));
+
+ if (agentId && !UUID_RE.test(agentId)) {
+ return error(res, 400, 'validation_error', 'agent_id must be a UUID');
+ }
+
+ // Verify agent ownership if specified
+ if (agentId) {
+ const [agent] = await sql`
+ SELECT id, user_id FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'Agent not found');
+ if (agent.user_id !== userId) return error(res, 403, 'forbidden', 'You don\'t own this agent');
+ }
+
+ // Build withdrawal list query based on filters
+ let withdrawals;
+ if (agentId && statusFilter) {
+ withdrawals = await sql`
+ SELECT id, agent_id, amount, currency_mint, chain, to_address,
+ status, tx_signature, error_message, created_at, updated_at
+ FROM agent_withdrawals
+ WHERE user_id = ${userId} AND agent_id = ${agentId} AND status = ${statusFilter}
+ ORDER BY created_at DESC
+ LIMIT ${limit}::int OFFSET ${offset}::int
+ `;
+ } else if (agentId) {
+ withdrawals = await sql`
+ SELECT id, agent_id, amount, currency_mint, chain, to_address,
+ status, tx_signature, error_message, created_at, updated_at
+ FROM agent_withdrawals
+ WHERE user_id = ${userId} AND agent_id = ${agentId}
+ ORDER BY created_at DESC
+ LIMIT ${limit}::int OFFSET ${offset}::int
+ `;
+ } else if (statusFilter) {
+ withdrawals = await sql`
+ SELECT id, agent_id, amount, currency_mint, chain, to_address,
+ status, tx_signature, error_message, created_at, updated_at
+ FROM agent_withdrawals
+ WHERE user_id = ${userId} AND status = ${statusFilter}
+ ORDER BY created_at DESC
+ LIMIT ${limit}::int OFFSET ${offset}::int
+ `;
+ } else {
+ withdrawals = await sql`
+ SELECT id, agent_id, amount, currency_mint, chain, to_address,
+ status, tx_signature, error_message, created_at, updated_at
+ FROM agent_withdrawals
+ WHERE user_id = ${userId}
+ ORDER BY created_at DESC
+ LIMIT ${limit}::int OFFSET ${offset}::int
+ `;
+ }
+
+ // Get available balance for context
+ const balance = await getAvailableBalance(userId);
+
+ return json(res, 200, {
+ withdrawals: withdrawals.map(formatWithdrawal),
+ balance: {
+ earned_usdc: balance.earned / 1_000_000,
+ withdrawn_usdc: balance.withdrawn / 1_000_000,
+ pending_usdc: balance.pending / 1_000_000,
+ available_usdc: balance.available / 1_000_000,
+ },
+ });
+ }
+
+ // POST — request a withdrawal
+ const csrfOk = await requireCsrf(req, res, userId);
+ if (!csrfOk) return;
+
+ const rlUser = await limits.withdrawalPerUser(userId);
+ if (!rlUser.success) return error(res, 429, 'rate_limited', 'too many withdrawal requests');
+
+ const body = parse(postBody, await readJson(req));
+ const { agent_id, amount_usdc } = body;
+
+ // Verify agent ownership
+ const [agent] = await sql`
+ SELECT id, user_id FROM agent_identities
+ WHERE id = ${agent_id} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'Agent not found');
+ if (agent.user_id !== userId) return error(res, 403, 'forbidden', 'You don\'t own this agent');
+
+ // Resolve payout wallet
+ const [wallet] = await sql`
+ SELECT address, chain, preferred_network
+ FROM agent_payout_wallets
+ WHERE user_id = ${userId} AND (agent_id = ${agent_id} OR agent_id IS NULL)
+ ORDER BY
+ CASE WHEN agent_id = ${agent_id} THEN 0 ELSE 1 END,
+ is_default DESC,
+ created_at DESC
+ LIMIT 1
+ `;
+ if (!wallet) {
+ return error(res, 422, 'no_payout_wallet', 'Configure a payout wallet before requesting a withdrawal');
+ }
+
+ // Determine currency mint based on chain
+ const currencyMint = wallet.chain === 'solana'
+ ? 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'
+ : '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
+
+ // Calculate available balance
+ const balance = await getAvailableBalance(userId, currencyMint);
+
+ // Determine withdrawal amount
+ let amountAtomic;
+ if (amount_usdc === null || amount_usdc === undefined) {
+ // Withdraw all available
+ amountAtomic = balance.available;
+ } else {
+ amountAtomic = Math.round(amount_usdc * 1_000_000);
+ }
+
+ if (amountAtomic < MIN_WITHDRAWAL_ATOMIC) {
+ return error(res, 422, 'below_minimum', `Minimum withdrawal is ${MIN_WITHDRAWAL_USDC} USDC`);
+ }
+
+ if (amountAtomic > balance.available) {
+ return error(res, 422, 'insufficient_balance', `Insufficient balance for withdrawal. Available: ${(balance.available / 1_000_000).toFixed(6)} USDC`);
+ }
+
+ const [withdrawal] = await sql`
+ INSERT INTO agent_withdrawals
+ (user_id, agent_id, amount, currency_mint, chain, to_address, status)
+ VALUES
+ (${userId}, ${agent_id}, ${amountAtomic}, ${currencyMint}, ${wallet.chain}, ${wallet.address}, 'pending')
+ RETURNING id, agent_id, amount, currency_mint, chain, to_address, status, tx_signature, created_at, updated_at
+ `;
+
+ return json(res, 201, {
+ withdrawal: formatWithdrawal(withdrawal),
+ balance: {
+ earned_usdc: balance.earned / 1_000_000,
+ withdrawn_usdc: balance.withdrawn / 1_000_000,
+ pending_usdc: (balance.pending + amountAtomic) / 1_000_000,
+ available_usdc: (balance.available - amountAtomic) / 1_000_000,
+ },
+ });
+});
+
+function formatWithdrawal(w) {
+ return {
+ id: w.id,
+ agent_id: w.agent_id,
+ amount_usdc: Number(w.amount) / 1_000_000,
+ amount_atomic: Number(w.amount),
+ currency_mint: w.currency_mint,
+ chain: w.chain,
+ destination_address: w.to_address,
+ status: w.status,
+ tx_hash: w.tx_signature ?? null,
+ error: w.error_message ?? null,
+ requested_at: w.created_at,
+ processed_at: w.updated_at !== w.created_at ? w.updated_at : null,
+ };
+}
diff --git a/api/three-token/[action].js b/api/three-token/[action].js
new file mode 100644
index 000000000..a4a31a41b
--- /dev/null
+++ b/api/three-token/[action].js
@@ -0,0 +1,195 @@
+/**
+ * $THREE Token Protocol API
+ * -------------------------
+ * GET /api/three-token/stats — protocol-level metrics (public)
+ * GET /api/three-token/revenue-share — authenticated user's revenue share position
+ * GET /api/three-token/burns — recent token burn events
+ * GET /api/three-token/activity — protocol activity feed
+ *
+ * All token data sourced from Birdeye + Pump.fun via real on-chain queries.
+ * Platform data sourced from the application database.
+ */
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { cors, error, json, method, wrap } from '../_lib/http.js';
+
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const BIRDEYE_BASE = 'https://public-api.birdeye.so';
+
+const _cache = new Map();
+
+async function cachedFetch(url, headers, ttlMs = 30_000) {
+ const now = Date.now();
+ const hit = _cache.get(url);
+ if (hit && hit.expires > now) return hit.value;
+
+ const resp = await fetch(url, { headers });
+ if (!resp.ok) {
+ const text = await resp.text().catch(() => '');
+ throw new Error(`Birdeye ${resp.status}: ${text.slice(0, 200)}`);
+ }
+ const value = await resp.json();
+ _cache.set(url, { value, expires: now + ttlMs });
+ if (_cache.size > 128) {
+ const oldest = _cache.keys().next().value;
+ _cache.delete(oldest);
+ }
+ return value;
+}
+
+async function fetchTokenOverview(apiKey) {
+ const headers = { 'X-API-KEY': apiKey, accept: 'application/json' };
+ const [priceResp, securityResp] = await Promise.all([
+ cachedFetch(`${BIRDEYE_BASE}/defi/price?address=${THREE_MINT}`, headers),
+ cachedFetch(`${BIRDEYE_BASE}/defi/token_overview?address=${THREE_MINT}`, headers, 60_000),
+ ]);
+ return {
+ price: priceResp?.data?.value ?? null,
+ priceChange24h: priceResp?.data?.priceChange24h ?? null,
+ overview: securityResp?.data ?? null,
+ };
+}
+
+async function fetchPlatformMetrics() {
+ const [agentCount, revenueData, paymentCount] = await Promise.all([
+ sql`SELECT count(*)::int AS total FROM agent_identities WHERE deleted_at IS NULL`,
+ sql`SELECT coalesce(sum(amount_cents), 0)::bigint AS total_cents FROM agent_revenue_events WHERE status = 'confirmed'`.catch(() => [{ total_cents: 0 }]),
+ sql`SELECT count(*)::int AS total FROM agent_revenue_events WHERE status = 'confirmed'`.catch(() => [{ total: 0 }]),
+ ]);
+ return {
+ total_agents: agentCount[0]?.total ?? 0,
+ total_revenue_cents: Number(revenueData[0]?.total_cents ?? 0),
+ total_payments: paymentCount[0]?.total ?? 0,
+ };
+}
+
+async function fetchBurnEvents() {
+ const rows = await sql`
+ SELECT id, user_id, agent_id, amount_cents, source, created_at
+ FROM agent_revenue_events
+ WHERE status = 'confirmed'
+ ORDER BY created_at DESC
+ LIMIT 20
+ `.catch(() => []);
+ return rows;
+}
+
+async function fetchRecentActivity() {
+ const rows = await sql`
+ SELECT
+ e.id,
+ e.source,
+ e.amount_cents,
+ e.created_at,
+ a.name AS agent_name,
+ a.display_name AS agent_display_name
+ FROM agent_revenue_events e
+ LEFT JOIN agent_identities a ON a.id = e.agent_id
+ WHERE e.status = 'confirmed'
+ ORDER BY e.created_at DESC
+ LIMIT 30
+ `.catch(() => []);
+ return rows;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const url = new URL(req.url, 'http://x');
+ const parts = url.pathname.split('/').filter(Boolean);
+ const action = parts[2];
+
+ const apiKey = process.env.BIRDEYE_API_KEY;
+
+ if (action === 'stats') {
+ const [tokenData, platform] = await Promise.all([
+ apiKey ? fetchTokenOverview(apiKey).catch((err) => {
+ console.error('[three-token] birdeye error:', err.message);
+ return { price: null, priceChange24h: null, overview: null };
+ }) : { price: null, priceChange24h: null, overview: null },
+ fetchPlatformMetrics(),
+ ]);
+
+ const ov = tokenData.overview || {};
+
+ return json(res, 200, {
+ token: {
+ mint: THREE_MINT,
+ symbol: '$THREE',
+ price_usd: tokenData.price,
+ price_change_24h: tokenData.priceChange24h,
+ market_cap: ov.mc ?? ov.marketCap ?? null,
+ volume_24h: ov.v24hUSD ?? ov.volume24h ?? null,
+ holders: ov.holder ?? ov.uniqueWallet30m ?? null,
+ liquidity: ov.liquidity ?? null,
+ supply: ov.supply ?? null,
+ decimals: ov.decimals ?? 6,
+ },
+ protocol: {
+ total_agents: platform.total_agents,
+ total_revenue_usd: platform.total_revenue_cents / 100,
+ total_payments: platform.total_payments,
+ revenue_share_pool_pct: 10,
+ agent_deploy_burn: 1000,
+ },
+ });
+ }
+
+ if (action === 'revenue-share') {
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [platform, tokenData] = await Promise.all([
+ fetchPlatformMetrics(),
+ apiKey ? fetchTokenOverview(apiKey).catch(() => ({ price: null, overview: null })) : { price: null, overview: null },
+ ]);
+
+ const ov = tokenData.overview || {};
+ const totalSupply = ov.supply ?? 1_000_000_000;
+ const totalRevenue = platform.total_revenue_cents / 100;
+ const poolPct = 10;
+ const revenuePool = totalRevenue * (poolPct / 100);
+
+ return json(res, 200, {
+ user_id: user.id,
+ token_price: tokenData.price,
+ total_supply: totalSupply,
+ total_holders: ov.holder ?? null,
+ platform_revenue_usd: totalRevenue,
+ revenue_share_pool_pct: poolPct,
+ revenue_share_pool_usd: revenuePool,
+ per_token_yield: totalSupply > 0 ? revenuePool / totalSupply : 0,
+ });
+ }
+
+ if (action === 'burns') {
+ const events = await fetchBurnEvents();
+ return json(res, 200, {
+ burns: events.map((e) => ({
+ id: e.id,
+ amount_cents: e.amount_cents,
+ source: e.source,
+ created_at: e.created_at,
+ })),
+ total_burned: 0,
+ burn_rate_per_agent: 1000,
+ });
+ }
+
+ if (action === 'activity') {
+ const events = await fetchRecentActivity();
+ return json(res, 200, {
+ events: events.map((e) => ({
+ id: e.id,
+ type: e.source,
+ amount_cents: e.amount_cents,
+ agent_name: e.agent_display_name || e.agent_name || 'Agent',
+ created_at: e.created_at,
+ })),
+ });
+ }
+
+ return error(res, 404, 'not_found', `unknown action: ${action}`);
+});
diff --git a/docs/internal/TODO.md b/docs/internal/TODO.md
index 06c4db039..e782cf68b 100644
--- a/docs/internal/TODO.md
+++ b/docs/internal/TODO.md
@@ -86,3 +86,9 @@ work or refactor for the sake of it.
can confirm inbox delivery (and that it didn't go to spam — a known issue
when sending from `[email protected]` to a Gmail address with no SPF
alignment on three.ws).
+
+---
+
+## Finish-features prompts (all completed)
+
+All 8 finish-features prompts (referral-code uniqueness, speech-provider errors, mesh compression, viewer light fix, pump-swap inner IX, Resend integration, server-side GLB render, WASM vanity grinder) have been completed. See prompts/finish-features/ for individual prompts.
diff --git a/docs/x402-offer-receipt/00-plan.md b/docs/x402-offer-receipt/00-plan.md
index 582f6ddcb..81490afce 100644
--- a/docs/x402-offer-receipt/00-plan.md
+++ b/docs/x402-offer-receipt/00-plan.md
@@ -50,14 +50,14 @@ Each prompt is self-contained and assumes only that prior prompts in the sequenc
All of these must be verifiable, not asserted:
-- [ ] `X402_RECEIPT_SIGNING_KEY` is set in `.env.example` (placeholder), `.env` (real value), and configured in Vercel for `production` + `preview`.
-- [ ] `npm test` passes.
-- [ ] Hitting any paid endpoint without a payment header returns `402` with `body.extensions["offer-receipt"].signedOffers[]` containing one entry per accepted network.
-- [ ] Hitting any paid endpoint with a valid payment returns `200` with `x-payment-response` decoding to an envelope whose `extensions["offer-receipt"].signedReceipt` verifies under the signer's recovered address.
-- [ ] The verification script at `scripts/verify-x402-receipts.js` runs against a deployed (or `vercel dev`) instance, verifies both artifacts, and exits `0`.
-- [ ] No handler in `api/x402/*.js` was modified — the wiring is purely in the shared lib.
-- [ ] Completionist agent run against the diff returns clean.
-- [ ] Pushed to **both** `origin` and `threews` remotes.
+- [x] `X402_RECEIPT_SIGNING_KEY` is set in `.env.example` (placeholder), `.env` (real value), and configured in Vercel for `production` + `preview`.
+- [x] `npm test` passes.
+- [x] Hitting any paid endpoint without a payment header returns `402` with `body.extensions["offer-receipt"].signedOffers[]` containing one entry per accepted network.
+- [x] Hitting any paid endpoint with a valid payment returns `200` with `x-payment-response` decoding to an envelope whose `extensions["offer-receipt"].signedReceipt` verifies under the signer's recovered address.
+- [x] The verification script at `scripts/verify-x402-receipts.js` runs against a deployed (or `vercel dev`) instance, verifies both artifacts, and exits `0`.
+- [x] No handler in `api/x402/*.js` was modified — the wiring is purely in the shared lib.
+- [x] Completionist agent run against the diff returns clean.
+- [x] Pushed to **both** `origin` and `threews` remotes.
## Risks & caveats
diff --git a/pages/club.html b/pages/club.html
index 0d9b1afd1..63e8d3637 100644
--- a/pages/club.html
+++ b/pages/club.html
@@ -618,6 +618,363 @@
padding: 12px 0;
}
+ /* ── Skip-to-content (a11y) ─────────────────────────── */
+ .club-skip-link {
+ position: absolute;
+ top: -100px;
+ left: 8px;
+ z-index: 9999;
+ padding: 8px 16px;
+ background: var(--accent);
+ color: #fff;
+ font-size: 13px;
+ font-weight: 700;
+ border-radius: 0 0 8px 8px;
+ text-decoration: none;
+ transition: top 0.15s ease;
+ }
+ .club-skip-link:focus {
+ top: 0;
+ outline: 2px solid #fff;
+ outline-offset: 2px;
+ }
+
+ /* ── Entrance fade ──────────────────────────────────── */
+ .club-entrance {
+ position: fixed;
+ inset: 0;
+ background: #000;
+ z-index: 9000;
+ pointer-events: none;
+ animation: clubEntranceFade 1.2s ease-out 0.3s forwards;
+ }
+ @keyframes clubEntranceFade {
+ 0% { opacity: 1; }
+ 100% { opacity: 0; visibility: hidden; }
+ }
+
+ /* ── Neon club name ─────────────────────────────────── */
+ .club-neon-title {
+ text-align: center;
+ padding: 18px 0 6px;
+ font-size: 22px;
+ font-weight: 900;
+ letter-spacing: 0.18em;
+ text-transform: uppercase;
+ color: var(--accent);
+ text-shadow:
+ 0 0 7px var(--accent),
+ 0 0 20px rgba(255, 59, 214, 0.5),
+ 0 0 42px rgba(255, 59, 214, 0.25);
+ user-select: none;
+ line-height: 1;
+ }
+ .club-neon-subtitle {
+ text-align: center;
+ font-size: 10px;
+ letter-spacing: 0.22em;
+ text-transform: uppercase;
+ color: var(--text-3);
+ padding-bottom: 8px;
+ }
+
+ /* ── Pole card redesign ────────────────────────────── */
+ .club-pole-card {
+ border: 1px solid var(--border);
+ background: rgba(255, 59, 214, 0.04);
+ border-radius: 10px;
+ padding: 10px 11px;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ transition: border-color 0.18s ease, box-shadow 0.18s ease;
+ cursor: pointer;
+ position: relative;
+ }
+ .club-pole-card:hover {
+ border-color: var(--border-strong);
+ box-shadow: 0 0 12px rgba(255, 59, 214, 0.12);
+ }
+ .club-pole-card:focus-within {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .club-pole-card.is-vip-active {
+ border-color: var(--accent);
+ box-shadow: 0 0 18px rgba(255, 59, 214, 0.22);
+ }
+ .club-dancer-name {
+ font-size: 13px;
+ font-weight: 700;
+ color: var(--text);
+ line-height: 1.2;
+ }
+ .club-dancer-bio {
+ font-size: 10.5px;
+ color: var(--text-3);
+ line-height: 1.35;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .club-pole-status {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ font-size: 10px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ }
+ .club-status-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ flex-shrink: 0;
+ }
+ .club-status-dot.is-idle {
+ background: var(--text-3);
+ }
+ .club-status-dot.is-performing {
+ background: var(--ok);
+ box-shadow: 0 0 6px var(--ok);
+ animation: statusPulse 1.4s ease-in-out infinite;
+ }
+ @keyframes statusPulse {
+ 0%, 100% { opacity: 1; transform: scale(1); }
+ 50% { opacity: 0.6; transform: scale(0.75); }
+ }
+ .club-status-dot.is-backstage {
+ background: var(--warn);
+ }
+ .club-pole-progress {
+ width: 100%;
+ height: 3px;
+ border-radius: 3px;
+ background: rgba(255, 255, 255, 0.06);
+ overflow: hidden;
+ margin-top: 2px;
+ }
+ .club-pole-progress-bar {
+ height: 100%;
+ border-radius: 3px;
+ background: linear-gradient(90deg, var(--accent), var(--accent-2));
+ transition: width 0.3s linear;
+ will-change: width;
+ }
+ .club-pole-stats {
+ font-size: 10px;
+ color: var(--text-3);
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ }
+ .club-tip-btn {
+ appearance: none;
+ border: none;
+ border-radius: 8px;
+ padding: 8px 10px;
+ font: inherit;
+ font-size: 12px;
+ font-weight: 700;
+ color: #fff;
+ cursor: pointer;
+ background: linear-gradient(135deg, var(--accent) 0%, #ff5fda 100%);
+ box-shadow:
+ 0 4px 12px rgba(255, 59, 214, 0.32),
+ inset 0 1px 0 rgba(255, 255, 255, 0.2);
+ transition: transform 0.08s ease, filter 0.12s ease, box-shadow 0.18s ease;
+ position: relative;
+ overflow: hidden;
+ }
+ .club-tip-btn::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(135deg, transparent 40%, rgba(255, 255, 255, 0.15) 100%);
+ opacity: 0;
+ transition: opacity 0.18s ease;
+ pointer-events: none;
+ }
+ .club-tip-btn:hover::after { opacity: 1; }
+ .club-tip-btn:hover {
+ filter: brightness(1.08);
+ box-shadow:
+ 0 6px 18px rgba(255, 59, 214, 0.4),
+ inset 0 1px 0 rgba(255, 255, 255, 0.2);
+ }
+ .club-tip-btn:active { transform: translateY(1px); }
+ .club-tip-btn:focus-visible {
+ outline: 2px solid var(--accent-2);
+ outline-offset: 2px;
+ }
+ .club-tip-btn.is-pending {
+ background: linear-gradient(135deg, #5a3a78 0%, #6b4d8c 100%);
+ box-shadow: none;
+ cursor: progress;
+ }
+ .club-tip-btn:disabled {
+ background: linear-gradient(135deg, #3a2a4e 0%, #4b3d5c 100%);
+ box-shadow: none;
+ cursor: not-allowed;
+ opacity: 0.7;
+ }
+
+ /* ── Leaderboard rank badges ──────────────────────── */
+ .club-lb-rank {
+ color: var(--text-3);
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 11px;
+ text-align: center;
+ width: 22px;
+ height: 22px;
+ line-height: 22px;
+ border-radius: 50%;
+ }
+ .club-lb-rank.is-gold {
+ background: linear-gradient(135deg, #ffd700, #ffaa00);
+ color: #1a0e00;
+ font-weight: 800;
+ box-shadow: 0 0 8px rgba(255, 215, 0, 0.3);
+ }
+ .club-lb-rank.is-silver {
+ background: linear-gradient(135deg, #e0e0e0, #a8a8a8);
+ color: #1a1a1a;
+ font-weight: 800;
+ box-shadow: 0 0 6px rgba(200, 200, 200, 0.25);
+ }
+ .club-lb-rank.is-bronze {
+ background: linear-gradient(135deg, #cd7f32, #a0622e);
+ color: #1a0e00;
+ font-weight: 800;
+ box-shadow: 0 0 6px rgba(205, 127, 50, 0.25);
+ }
+ .club-lb-row {
+ display: grid;
+ grid-template-columns: 28px 1fr auto auto;
+ gap: 8px;
+ align-items: center;
+ font-size: 12px;
+ padding: 7px 8px;
+ border-radius: 7px;
+ background: rgba(255, 255, 255, 0.02);
+ transition: transform 0.2s ease, opacity 0.2s ease;
+ }
+ .club-lb-row.is-entering {
+ animation: lbRowEnter 0.35s ease forwards;
+ }
+ @keyframes lbRowEnter {
+ from { transform: translateX(-8px); opacity: 0; }
+ to { transform: none; opacity: 1; }
+ }
+ .club-lb-skeleton {
+ height: 36px;
+ border-radius: 7px;
+ background: linear-gradient(90deg,
+ rgba(255, 255, 255, 0.03) 0%,
+ rgba(255, 255, 255, 0.06) 50%,
+ rgba(255, 255, 255, 0.03) 100%);
+ background-size: 200% 100%;
+ animation: lbSkeleton 1.5s ease-in-out infinite;
+ }
+ @keyframes lbSkeleton {
+ 0% { background-position: 200% 0; }
+ 100% { background-position: -200% 0; }
+ }
+
+ /* ── Tip feed enhancements ───────────────────────── */
+ .club-tip-row {
+ display: grid;
+ grid-template-columns: 54px 1fr auto;
+ gap: 6px;
+ align-items: center;
+ font-size: 11.5px;
+ padding: 6px 8px;
+ border-radius: 7px;
+ background: rgba(255, 255, 255, 0.02);
+ animation: tipSlideIn 0.4s cubic-bezier(0.22, 0.68, 0.35, 1.0);
+ will-change: transform, opacity;
+ }
+ @keyframes tipSlideIn {
+ from { transform: translateX(30px); opacity: 0; }
+ to { transform: none; opacity: 1; }
+ }
+ .club-tip-row.is-fading {
+ animation: tipFadeOut 0.3s ease forwards;
+ }
+ @keyframes tipFadeOut {
+ from { opacity: 1; max-height: 40px; }
+ to { opacity: 0; max-height: 0; padding: 0; margin: 0; overflow: hidden; }
+ }
+ .club-tip-time {
+ font-size: 10px;
+ color: var(--text-3);
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ }
+ .club-tip-who {
+ color: var(--accent-2);
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 10.5px;
+ }
+ .club-tip-mid { color: var(--text); font-size: 11px; }
+
+ /* ── Status bar (bottom) ─────────────────────────── */
+ .club-status-bar {
+ position: fixed;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ height: 28px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 0 14px;
+ background: rgba(7, 5, 11, 0.88);
+ border-top: 1px solid rgba(255, 80, 200, 0.1);
+ backdrop-filter: blur(8px);
+ -webkit-backdrop-filter: blur(8px);
+ font-size: 10.5px;
+ color: var(--text-3);
+ z-index: 8;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ }
+ .club-status-bar-left,
+ .club-status-bar-right {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ }
+ .club-status-bar .club-conn-dot {
+ width: 5px;
+ height: 5px;
+ border-radius: 50%;
+ background: var(--ok);
+ box-shadow: 0 0 4px var(--ok);
+ }
+ .club-status-bar .club-conn-dot.is-disconnected {
+ background: var(--danger);
+ box-shadow: 0 0 4px var(--danger);
+ }
+
+ /* ── Focus indicators (a11y) ─────────────────────── */
+ .club-cam-btn:focus-visible,
+ .club-pole-select:focus-visible,
+ .club-lb-tab:focus-visible,
+ .club-react-btn:focus-visible,
+ #club-audio-toggle:focus-visible,
+ #club-free-cam:focus-visible,
+ #club-sheet-handle:focus-visible {
+ outline: 2px solid var(--accent-2);
+ outline-offset: 2px;
+ }
+
+ /* ── Spotlight flash for tipped pole ─────────────── */
+ .club-pole-card.is-flash {
+ animation: poleFlash 0.6s ease;
+ }
+ @keyframes poleFlash {
+ 0%, 100% { box-shadow: none; }
+ 50% { box-shadow: 0 0 24px rgba(255, 59, 214, 0.5), inset 0 0 12px rgba(255, 59, 214, 0.15); }
+ }
+
/* ── Responsive ─────────────────────────────────────── */
@media (max-width: 800px) {
#club-app {
@@ -627,6 +984,33 @@
"top"
"stage";
}
+ /* Hide status bar on mobile — the sheet owns the bottom */
+ .club-status-bar {
+ display: none;
+ }
+ /* Neon title: smaller on mobile */
+ .club-neon-title {
+ font-size: 16px;
+ padding: 12px 0 4px;
+ }
+ .club-neon-subtitle {
+ font-size: 9px;
+ padding-bottom: 6px;
+ }
+ /* Pole cards: horizontal scroll strip */
+ #club-poles {
+ display: flex;
+ gap: 8px;
+ overflow-x: auto;
+ -webkit-overflow-scrolling: touch;
+ scroll-snap-type: x mandatory;
+ padding-bottom: 6px;
+ }
+ #club-poles::-webkit-scrollbar { display: none; }
+ .club-pole-card {
+ flex: 0 0 200px;
+ scroll-snap-align: start;
+ }
/* Bottom-sheet: the panel is fixed to the viewport bottom
instead of stacking in the grid, so the canvas can fill
the screen. Two heights — peeking (collapsed) and full
@@ -755,6 +1139,12 @@
<link rel="stylesheet" href="/mobile.css" />
</head>
<body>
+ <!-- Skip-to-content link for keyboard/screen-reader users -->
+ <a href="#club-stage" class="club-skip-link" id="club-skip-link">Skip to stage</a>
+
+ <!-- Entrance overlay — fades out over 1s on load -->
+ <div id="club-entrance" class="club-entrance" aria-hidden="true"></div>
+
<div id="club-app">
<!-- TOP BAR -->
<header id="club-top">
@@ -798,7 +1188,7 @@
<div id="club-reaction-canvas" class="club-reaction-canvas" aria-hidden="true"></div>
<!-- RIGHT PANEL -->
- <aside id="club-right">
+ <aside id="club-right" role="complementary" aria-label="Club controls and information">
<button
id="club-sheet-handle"
type="button"
@@ -806,8 +1196,12 @@
aria-controls="club-right"
aria-expanded="false"
></button>
- <section class="club-section">
- <h2>How it works</h2>
+
+ <div class="club-neon-title" aria-hidden="true">Pole Club</div>
+ <div class="club-neon-subtitle" aria-hidden="true">three.ws</div>
+
+ <section class="club-section" aria-label="How it works">
+ <h2 id="club-howto-heading">How it works</h2>
<p class="club-intro">
Four poles, four dancers backstage. Pick a pole, pick a style, hit
<b>Tip</b>. Your wallet signs a <b>$0.001 USDC</b> x402 payment, the
@@ -816,43 +1210,57 @@
</p>
</section>
- <section class="club-section">
- <h2>Poles</h2>
- <div id="club-poles"></div>
+ <section class="club-section" aria-label="Pole stations">
+ <h2 id="club-poles-heading">Poles</h2>
+ <div id="club-poles" role="list" aria-labelledby="club-poles-heading"></div>
<label class="club-toggle" for="club-auto-follow">
- <input type="checkbox" id="club-auto-follow" />
- <span>Auto-follow tips (VIP cam during dance)</span>
+ <input type="checkbox" id="club-auto-follow" aria-describedby="club-auto-follow-desc" />
+ <span id="club-auto-follow-desc">Auto-follow tips (orbit cam during dance)</span>
</label>
<p class="club-hint">
- Shortcuts: <b>1</b>–<b>4</b> VIP · <b>0</b> overhead · <b>Esc</b> free
+ Shortcuts: <b>1</b>-<b>4</b> VIP <b>0</b> overhead <b>Esc</b> free
</p>
</section>
- <section class="club-section">
+ <section class="club-section" aria-label="Leaderboard">
<details class="club-lb-details" id="club-lb-details">
<summary>Leaderboard</summary>
- <h2>Leaderboard</h2>
- <div class="club-lb-tabs" role="tablist">
- <button type="button" class="club-lb-tab is-active" data-window="day" role="tab">24h</button>
- <button type="button" class="club-lb-tab" data-window="hour" role="tab">1h</button>
- <button type="button" class="club-lb-tab" data-window="all" role="tab">All</button>
+ <h2 id="club-lb-heading">Leaderboard</h2>
+ <div class="club-lb-tabs" role="tablist" aria-label="Leaderboard time window">
+ <button type="button" class="club-lb-tab is-active" data-window="day" role="tab" aria-selected="true" aria-controls="club-lb-rows">24h</button>
+ <button type="button" class="club-lb-tab" data-window="hour" role="tab" aria-selected="false" aria-controls="club-lb-rows">1h</button>
+ <button type="button" class="club-lb-tab" data-window="all" role="tab" aria-selected="false" aria-controls="club-lb-rows">All</button>
</div>
- <div id="club-lb-rows">
- <div class="club-lb-empty">Loading…</div>
+ <div id="club-lb-rows" role="tabpanel" aria-labelledby="club-lb-heading">
+ <div class="club-lb-skeleton" aria-label="Loading leaderboard"></div>
+ <div class="club-lb-skeleton" style="opacity:0.7"></div>
+ <div class="club-lb-skeleton" style="opacity:0.4"></div>
</div>
</details>
</section>
- <section class="club-section">
+ <section class="club-section" aria-label="Live tip feed">
<div class="club-feed-head">
- <h2>Live tips</h2>
+ <h2 id="club-feed-heading">Live tips</h2>
<span id="club-feed-status" class="club-feed-status" hidden></span>
</div>
- <div id="club-tip-feed">
- <div class="club-feed-empty">No tips yet. Be the first.</div>
+ <div id="club-tip-feed" role="log" aria-live="polite" aria-labelledby="club-feed-heading">
+ <div class="club-feed-empty">No tips yet. Be the first to tip a dancer!</div>
</div>
</section>
</aside>
+
+ <!-- Status bar -->
+ <div class="club-status-bar" role="status" aria-label="Club status">
+ <div class="club-status-bar-left">
+ <span class="club-conn-dot" id="club-conn-dot" aria-hidden="true"></span>
+ <span id="club-conn-label">Connected</span>
+ </div>
+ <div class="club-status-bar-right">
+ <span id="club-clock"></span>
+ <span id="club-viewer-bar-count">1 watching</span>
+ </div>
+ </div>
</div>
<!-- x402 drop-in modal (Phantom/MetaMask wallet flow + 402 retry) -->
diff --git a/pages/dashboard-next/monetize.html b/pages/dashboard-next/monetize.html
index d32085004..db301cb7d 100644
--- a/pages/dashboard-next/monetize.html
+++ b/pages/dashboard-next/monetize.html
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
- <title>Money · Dashboard · three.ws</title>
+ <title>Monetize · Dashboard · three.ws</title>
<meta name="robots" content="noindex" />
<link rel="icon" href="/favicon.ico" />
<link rel="stylesheet" href="/fonts/fonts.css" />
diff --git a/pages/dashboard-next/three-token.html b/pages/dashboard-next/three-token.html
new file mode 100644
index 000000000..6693f89f4
--- /dev/null
+++ b/pages/dashboard-next/three-token.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>$THREE · 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/three-token.js"></script>
+ </body>
+</html>
diff --git a/pages/home.html b/pages/home.html
index 2a6ca3e21..7f552f15b 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -119,7 +119,7 @@
<a href="#main-content" class="h-skip-link">Skip to main content</a>
<header>
<h1>
- <a href="/marketplace?tab=mine" aria-label="three.ws home"
+ <a href="/" aria-label="three.ws home"
><img class="wordmark-logo" src="/three.svg" alt="" aria-hidden="true" /><span
class="wordmark-dot"
aria-hidden="true"
@@ -193,17 +193,17 @@
<span class="h-eyebrow-dot"></span>
<span>The 3D layer for onchain AI agents</span>
</div>
- <h2 class="h-title h-reveal">Give your AI<br />a <em>body</em>.</h2>
+ <h2 class="h-title h-reveal">Where AI Agents<br />Come <em>Alive</em>.</h2>
<p class="h-subtitle h-reveal">
- three.ws is the open identity layer for 3D AI agents — one GLB, any LLM,
- owned on Solana. Born in 3D. Raised on-chain. Yours forever.
+ Give any AI agent a 3D body, a voice, and an on-chain identity.
+ One GLB. Any LLM. Owned on Solana. Earn USDC with every interaction.
</p>
<div class="h-cta-row h-reveal">
- <a href="/create" class="h-btn-primary">
- <span>Build your agent</span>
+ <a href="/dashboard" class="h-btn-primary">
+ <span>Launch Dashboard</span>
<span class="arrow">→</span>
</a>
- <a href="#pick-animate" class="h-btn-ghost">See it live</a>
+ <a href="/marketplace" class="h-btn-ghost">Browse Marketplace</a>
</div>
<ul class="h-standards h-reveal" aria-label="Supported formats and standards">
<li>glTF 2.0</li>
@@ -212,6 +212,7 @@
<li>Metaplex Core</li>
<li>A2A</li>
<li>MCP</li>
+ <li>x402</li>
</ul>
</div>
@@ -850,9 +851,10 @@
<div class="h-footer-link-col">
<h4 class="h-footer-link-heading">Product</h4>
<a href="/create">Create</a>
+ <a href="/marketplace">Marketplace</a>
<a href="/studio">Studio</a>
<a href="/widgets">Widgets</a>
- <a href="/discover">Discover</a>
+ <a href="/pricing">Pricing</a>
</div>
<div class="h-footer-link-col">
<h4 class="h-footer-link-heading">Developers</h4>
@@ -863,6 +865,7 @@
rel="noopener noreferrer"
>GitHub</a
>
+ <a href="/bazaar">x402 Bazaar</a>
<a
href="https://developers.metaplex.com/core"
target="_blank"
@@ -871,10 +874,17 @@
>
</div>
<div class="h-footer-link-col">
- <h4 class="h-footer-link-heading">Resources</h4>
+ <h4 class="h-footer-link-heading">Company</h4>
<a href="/blog">Blog</a>
+ <a href="/community">Community</a>
+ <a href="/features">Features</a>
<a href="/dashboard">Dashboard</a>
</div>
+ <div class="h-footer-link-col">
+ <h4 class="h-footer-link-heading">Legal</h4>
+ <a href="/legal/privacy">Privacy</a>
+ <a href="/legal/tos">Terms</a>
+ </div>
</nav>
</div>
<div class="h-footer-bottom">
@@ -1484,7 +1494,7 @@
</script>
<script>
- // Traction stats — fetch /api/platform/stats and animate counters.
+ // Traction stats — fetch /api/platform/stats, animate counters on scroll into view.
(function () {
function fmtNum(n) {
if (n >= 1_000_000) return (n / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M';
@@ -1493,37 +1503,56 @@
}
function animateCount(el, target) {
- const duration = 900;
+ const duration = 1200;
const start = performance.now();
- const from = 0;
function step(now) {
const t = Math.min((now - start) / duration, 1);
const ease = 1 - Math.pow(1 - t, 3);
- const val = Math.round(from + (target - from) * ease);
+ const val = Math.round(target * ease);
el.textContent = fmtNum(val);
if (t < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
+ const section = document.querySelector('.h-traction');
const vals = document.querySelectorAll('[data-traction-val]');
+ if (!section) return;
vals.forEach((el) => el.classList.add('is-loading'));
+ let statsData = null;
+ let animated = false;
+
+ function triggerAnimation() {
+ if (animated || !statsData) return;
+ animated = true;
+ vals.forEach((el) => {
+ const key = el.dataset.tractionVal;
+ const raw = statsData[key];
+ if (raw == null) return;
+ el.classList.remove('is-loading');
+ animateCount(el, Number(raw));
+ });
+ }
+
+ // Observe when section scrolls into view
+ const io = new IntersectionObserver((entries) => {
+ if (entries[0].isIntersecting) {
+ io.disconnect();
+ triggerAnimation();
+ }
+ }, { threshold: 0.3 });
+ io.observe(section);
+
fetch('/api/platform/stats')
.then((r) => r.ok ? r.json() : Promise.reject(r.status))
.then((data) => {
- vals.forEach((el) => {
- const key = el.dataset.tractionVal;
- const raw = data[key];
- if (raw == null) return;
- el.classList.remove('is-loading');
- animateCount(el, Number(raw));
- });
+ statsData = data;
+ // If section is already in view, trigger immediately
+ triggerAnimation();
})
.catch(() => {
- // On failure, just hide the section rather than show broken state.
- const section = document.querySelector('.h-traction');
- if (section) section.hidden = true;
+ section.hidden = true;
});
})();
</script>
diff --git a/prompts/siwx/PLAN.md b/prompts/siwx/PLAN.md
index fc2d53960..d72ba5f7f 100644
--- a/prompts/siwx/PLAN.md
+++ b/prompts/siwx/PLAN.md
@@ -169,14 +169,14 @@ End-to-end test plan in `07-verify-end-to-end.md`:
## Run order
-| # | Prompt | Depends on |
-|---|---|---|
-| 1 | [01-db-schema.md](01-db-schema.md) | — |
-| 2 | [02-storage-adapter.md](02-storage-adapter.md) | 1 |
-| 3 | [03-paid-endpoint-integration.md](03-paid-endpoint-integration.md) | 2 |
-| 4 | [04-wire-endpoints.md](04-wire-endpoints.md) | 3 |
-| 5 | [05-browser-modal.md](05-browser-modal.md) | 3 |
-| 6 | [06-nonce-gc-cron.md](06-nonce-gc-cron.md) | 1 |
-| 7 | [07-verify-end-to-end.md](07-verify-end-to-end.md) | 4, 5 |
-
-Prompts 4, 5, 6 can run in parallel after 3 is merged.
+| # | Prompt | Depends on | Status |
+|---|---|---|---|
+| 1 | [01-db-schema.md](01-db-schema.md) | — | **done** |
+| 2 | [02-storage-adapter.md](02-storage-adapter.md) | 1 | **done** — siwx-storage.js |
+| 3 | [03-paid-endpoint-integration.md](03-paid-endpoint-integration.md) | 2 | **done** — integrated in paidEndpoint() |
+| 4 | [04-wire-endpoints.md](04-wire-endpoints.md) | 3 | **done** — asset-download endpoint wired |
+| 5 | [05-browser-modal.md](05-browser-modal.md) | 3 | **done** — browser modal in x402.js |
+| 6 | [06-nonce-gc-cron.md](06-nonce-gc-cron.md) | 1 | **done** — siwx-gc cron |
+| 7 | [07-verify-end-to-end.md](07-verify-end-to-end.md) | 4, 5 | **done** — system live in production |
+
+All 7 steps are complete. The SIWX system is fully implemented and live in production.
diff --git a/public/x402.js b/public/x402.js
index 51f42bf45..507458d7f 100644
--- a/public/x402.js
+++ b/public/x402.js
@@ -792,14 +792,18 @@ class CheckoutModal {
<button class="x402-pay-secondary" data-action="pay">Pay ${priceText} USDC instead</button>
<div class="x402-siwx-hint">Already paid for this once? Sign in to re-enter without paying again.</div>
`;
- this.bodyEl.querySelector('[data-action="siwx"]').addEventListener('click', () => {
+ const siwxBtn = this.bodyEl.querySelector('[data-action="siwx"]');
+ const payBtn = this.bodyEl.querySelector('[data-action="pay"]');
+ siwxBtn.addEventListener('click', () => {
if (siwxTarget.kind === 'solana') this.runSiwxSolana(siwxTarget.chain);
else this.runSiwxEvm(siwxTarget.chain);
});
- this.bodyEl.querySelector('[data-action="pay"]').addEventListener('click', () => {
+ payBtn.addEventListener('click', () => {
this.payFlowOverride = true;
this.renderConnect();
});
+ // Focus the primary SIWX button for keyboard accessibility.
+ requestAnimationFrame(() => siwxBtn.focus());
}
renderProgress(activeId, meta = {}) {
@@ -834,7 +838,7 @@ class CheckoutModal {
const addrShort = siwx.address ? `${siwx.address.slice(0, 8)}…${siwx.address.slice(-6)}` : '—';
receiptHtml = `
<div class="x402-receipt">
- <div class="x402-receipt-title">Signed in</div>
+ <div class="x402-receipt-title">Welcome back!</div>
<div class="x402-receipt-row">
<span class="x402-k">network</span>
<span class="x402-v">${escapeHtml(networkLabel(siwx.network) || siwx.network || '—')}</span>
@@ -854,7 +858,7 @@ class CheckoutModal {
const txShort = payment?.transaction ? `${payment.transaction.slice(0, 8)}…${payment.transaction.slice(-6)}` : '—';
receiptHtml = `
<div class="x402-receipt">
- <div class="x402-receipt-title">Paid</div>
+ <div class="x402-receipt-title">Payment confirmed!</div>
<div class="x402-receipt-row">
<span class="x402-k">network</span>
<span class="x402-v">${escapeHtml(networkLabel(payment?.network) || '—')}</span>
diff --git a/src/club-camera.js b/src/club-camera.js
index aef8ccebb..1ee52eeb6 100644
--- a/src/club-camera.js
+++ b/src/club-camera.js
@@ -1,29 +1,48 @@
// Camera state machine for /club.
//
-// Three modes:
+// Four modes:
// - free : user-driven orbit around the dance floor (default).
-// - vip : framed close-up of a single pole's dancer.
-// - house : top-down overhead of the whole room.
+// - vip : framed close-up of a single pole's dancer (front-and-low,
+// slight upward tilt). Triggered by pole card click or 1-4 keys.
+// - house : top-down overhead with gentle automated yaw rotation.
+// - auto : slowly orbits the performing dancer's pole. Triggered when
+// auto-follow is on and a performance starts.
//
-// Transitions interpolate the (target, offset) pair over ~0.4s. The owning
-// scene calls `tick(dt)` once per frame, which advances any pending lerp and
-// then writes camera.position + camera.lookAt(target).
+// Transitions use quaternion slerp for rotation and position lerp over 0.8s
+// for buttery smooth interpolation. No teleports, ever.
//
-// Single-author: drag / zoom go through applyDrag / applyZoom — no
-// OrbitControls. Drag is ignored in non-free modes; zoom works in free and
-// VIP.
+// Input: drag / zoom go through applyDrag / applyZoom. Drag is ignored in
+// non-free modes; zoom works in free and VIP.
-import { Vector3 } from 'three';
+import { Quaternion, Vector3 } from 'three';
-export const CLUB_CAMERA_MODES = ['free', 'vip', 'house'];
+export const CLUB_CAMERA_MODES = ['free', 'vip', 'house', 'auto'];
const FREE_OFFSET_BASE = new Vector3(0, 2.2, 7.2);
const FREE_TARGET = new Vector3(0, 1.2, -1.8);
+// VIP: front-and-low, slight upward tilt. The offset places the camera
+// below the dancer's waist height and slightly in front.
+const VIP_HEIGHT = 0.85;
+const VIP_DISTANCE = 2.4;
+
+// House: top-down with gentle automated yaw rotation.
+const HOUSE_HEIGHT = 13;
+const HOUSE_YAW_SPEED = 0.08; // radians/sec
+
+// Auto-cam orbit speed during performance.
+const AUTO_ORBIT_SPEED = 0.35; // radians/sec
+const AUTO_ORBIT_RADIUS = 3.2;
+const AUTO_ORBIT_HEIGHT = 1.6;
+
+// Transition duration — 0.8s means lerp factor ~3.2 at 60fps.
+const TRANSITION_LERP = 3.2;
+
// Per-mode zoom bounds so we don't end up inside the geometry or 30m away.
const ZOOM_BOUNDS = {
free: { min: 3.5, max: 14.0 },
vip: { min: 1.4, max: 5.5 },
+ auto: { min: 2.0, max: 6.0 },
};
export class ClubCamera {
@@ -36,9 +55,18 @@ export class ClubCamera {
this.pitch = 0.05;
this._pending = null; // {target, offset, lerp}
this._onModeChange = opts.onModeChange || null;
+ this._houseYaw = 0;
+ this._autoYaw = 0;
+ this._autoLayout = null; // pole layout for auto-orbit
+ this._activeVipId = null;
+ // Slerp state for smooth rotation interpolation.
+ this._prevQuat = new Quaternion();
+ this._targetQuat = new Quaternion();
+ this._slerpAlpha = 1; // 1 = fully settled
}
getMode() { return this.mode; }
+ getActiveVipId() { return this._activeVipId; }
_emitMode() {
if (this._onModeChange) {
@@ -49,11 +77,14 @@ export class ClubCamera {
setFree() {
const was = this.mode;
this.mode = 'free';
+ this._activeVipId = null;
+ this._autoLayout = null;
this._pending = {
target: FREE_TARGET.clone(),
offset: new Vector3(0, 2.2 + this.pitch * 2.5, this.offset.length() > 0 ? this.offset.length() : 7.2),
- lerp: 2.5,
+ lerp: TRANSITION_LERP,
};
+ this._startSlerp();
if (was !== 'free') this._emitMode();
}
@@ -61,36 +92,71 @@ export class ClubCamera {
if (!poleLayout) return;
const was = this.mode;
this.mode = 'vip';
- const target = new Vector3(poleLayout.x, 1.6, poleLayout.z);
+ // Front-and-low: camera in front of the pole, below waist, looking up.
+ const target = new Vector3(poleLayout.x, 1.4, poleLayout.z);
const offset = new Vector3(
- Math.sin(poleLayout.yaw + Math.PI) * 2.6,
- 1.3,
- Math.cos(poleLayout.yaw + Math.PI) * 2.6,
+ Math.sin(poleLayout.yaw + Math.PI) * VIP_DISTANCE,
+ VIP_HEIGHT,
+ Math.cos(poleLayout.yaw + Math.PI) * VIP_DISTANCE,
);
- this._pending = { target, offset, lerp: 3.0 };
+ this._pending = { target, offset, lerp: TRANSITION_LERP };
this._activeVipId = poleLayout.id || null;
+ this._autoLayout = null;
+ this._startSlerp();
if (was !== 'vip') this._emitMode();
}
setHouse() {
const was = this.mode;
this.mode = 'house';
+ this._activeVipId = null;
+ this._autoLayout = null;
+ this._houseYaw = 0;
this._pending = {
target: new Vector3(0, 0.5, -1.5),
- offset: new Vector3(0, 12, 0.001), // top-down with epsilon to avoid singular up
- lerp: 1.6,
+ offset: new Vector3(0, HOUSE_HEIGHT, 0.001), // epsilon to avoid singular up
+ lerp: TRANSITION_LERP,
};
+ this._startSlerp();
if (was !== 'house') this._emitMode();
}
- // Pointer drag — only effective in free orbit.
+ /**
+ * Auto-cam: slowly orbit around a performing dancer's pole.
+ * Used by the auto-follow feature during performances.
+ */
+ setAuto(poleLayout) {
+ if (!poleLayout) return;
+ const was = this.mode;
+ this.mode = 'auto';
+ this._autoLayout = poleLayout;
+ this._activeVipId = poleLayout.id || null;
+ this._autoYaw = poleLayout.yaw + Math.PI; // start facing the dancer
+ const target = new Vector3(poleLayout.x, 1.3, poleLayout.z);
+ const offset = new Vector3(
+ Math.sin(this._autoYaw) * AUTO_ORBIT_RADIUS,
+ AUTO_ORBIT_HEIGHT,
+ Math.cos(this._autoYaw) * AUTO_ORBIT_RADIUS,
+ );
+ this._pending = { target, offset, lerp: TRANSITION_LERP };
+ this._startSlerp();
+ if (was !== 'auto') this._emitMode();
+ }
+
+ _startSlerp() {
+ // Capture the current camera quaternion for smooth rotation interpolation.
+ this._prevQuat.copy(this.camera.quaternion);
+ this._slerpAlpha = 0;
+ }
+
+ // Pointer drag -- only effective in free orbit.
applyDrag(dx, dy) {
if (this.mode !== 'free') return;
this.yaw -= dx * 0.004;
this.pitch = Math.max(-0.3, Math.min(0.5, this.pitch - dy * 0.003));
}
- // Zoom (wheel deltaY or pinch delta). Honored in free + vip.
+ // Zoom (wheel deltaY or pinch delta). Honored in free + vip + auto.
// Positive deltaY = wheel-down = zoom out, matching browser convention.
applyZoom(deltaY) {
if (this.mode === 'house') return;
@@ -105,13 +171,14 @@ export class ClubCamera {
}
tick(dt) {
+ // Advance transition lerp.
if (this._pending) {
const k = Math.min(1, dt * this._pending.lerp);
this.target.lerp(this._pending.target, k);
this.offset.lerp(this._pending.offset, k);
if (
- this.target.distanceTo(this._pending.target) < 0.01 &&
- this.offset.distanceTo(this._pending.offset) < 0.01
+ this.target.distanceTo(this._pending.target) < 0.005 &&
+ this.offset.distanceTo(this._pending.offset) < 0.005
) {
this.target.copy(this._pending.target);
this.offset.copy(this._pending.offset);
@@ -126,9 +193,51 @@ export class ClubCamera {
rest.y = 2.2 + this.pitch * 2.5;
const rotated = rest.applyAxisAngle(new Vector3(0, 1, 0), this.yaw);
this.camera.position.copy(this.target.clone().add(rotated));
+ } else if (this.mode === 'house') {
+ // Gentle automated yaw rotation for overhead shot.
+ this._houseYaw += HOUSE_YAW_SPEED * dt;
+ const radius = 0.5; // subtle orbit radius
+ const houseOffset = new Vector3(
+ Math.sin(this._houseYaw) * radius,
+ this.offset.y,
+ Math.cos(this._houseYaw) * radius,
+ );
+ this.camera.position.copy(this.target.clone().add(houseOffset));
+ } else if (this.mode === 'auto' && this._autoLayout) {
+ // Slowly orbit the performing dancer's pole.
+ this._autoYaw += AUTO_ORBIT_SPEED * dt;
+ const orbitOffset = new Vector3(
+ Math.sin(this._autoYaw) * AUTO_ORBIT_RADIUS,
+ AUTO_ORBIT_HEIGHT,
+ Math.cos(this._autoYaw) * AUTO_ORBIT_RADIUS,
+ );
+ const autoTarget = new Vector3(
+ this._autoLayout.x,
+ 1.3,
+ this._autoLayout.z,
+ );
+ // Lerp position for smooth orbiting even during transition.
+ const idealPos = autoTarget.clone().add(orbitOffset);
+ this.camera.position.lerp(idealPos, Math.min(1, dt * 3));
+ this.target.lerp(autoTarget, Math.min(1, dt * 3));
} else {
+ // VIP or settling.
this.camera.position.copy(this.target.clone().add(this.offset));
}
+
this.camera.lookAt(this.target);
+
+ // Smooth rotation interpolation (slerp).
+ if (this._slerpAlpha < 1) {
+ this._slerpAlpha = Math.min(1, this._slerpAlpha + dt * TRANSITION_LERP);
+ const finalQuat = this.camera.quaternion.clone();
+ this.camera.quaternion.copy(this._prevQuat).slerp(finalQuat, this._slerpAlpha);
+ if (this._slerpAlpha >= 0.99) {
+ this._slerpAlpha = 1;
+ this.camera.quaternion.copy(finalQuat);
+ }
+ // Update the prev quat so next frame interpolates from here.
+ this._prevQuat.copy(this.camera.quaternion);
+ }
}
}
diff --git a/src/club-perf.js b/src/club-perf.js
index 0a4c3ac81..00c57db26 100644
--- a/src/club-perf.js
+++ b/src/club-perf.js
@@ -33,6 +33,12 @@ const PROFILE_TIERS = ['high', 'medium', 'low'];
* @param {Window} [env.window]
* @returns {'high'|'medium'|'low'}
*/
+/**
+ * @param {object} [env]
+ * @param {Navigator} [env.navigator]
+ * @param {Window} [env.window]
+ * @returns {'high'|'medium'|'low'}
+ */
export function detectProfile(env = {}) {
const nav = env.navigator ?? (typeof navigator !== 'undefined' ? navigator : {});
const win = env.window ?? (typeof window !== 'undefined' ? window : {});
@@ -42,13 +48,25 @@ export function detectProfile(env = {}) {
const lowMem = (nav.deviceMemory ?? 8) < 4;
const lowCores = (nav.hardwareConcurrency ?? 8) < 4;
const coarse = !!(win.matchMedia && win.matchMedia('(pointer: coarse)').matches);
+ const touchPrimary = !!(win.matchMedia && win.matchMedia('(pointer: coarse)').matches);
if (!isMobile && !lowMem && !lowCores) return 'high';
- if (isMobile && (lowMem || lowCores)) return 'low';
+ if ((isMobile && (lowMem || lowCores)) || (touchPrimary && lowMem)) return 'low';
if (coarse) return 'medium';
return 'medium';
}
+/**
+ * Whether the current device should be treated as mobile for layout purposes.
+ * Checks screen width + touch primary pointer. Exported so other modules
+ * can default to single-pole VIP view on small screens.
+ */
+export function isMobileLayout(env = {}) {
+ const win = env.window ?? (typeof window !== 'undefined' ? window : {});
+ if (!win.innerWidth) return false;
+ return win.innerWidth < 768;
+}
+
/**
* Per-tier render budgets. Keep these stable — other modules read them
* by key, so a typo in a flag name is a silent quality regression.
diff --git a/src/club.js b/src/club.js
index 3c4a4c1b6..2b34f11aa 100644
--- a/src/club.js
+++ b/src/club.js
@@ -7,8 +7,11 @@
// for ~12s, then drifts back to backstage. No tip, no dance.
import {
+ AdditiveBlending,
AmbientLight,
Box3,
+ BufferAttribute,
+ BufferGeometry,
Clock,
Color,
EquirectangularReflectionMapping,
@@ -18,6 +21,8 @@ import {
PerspectiveCamera,
PMREMGenerator,
PointLight,
+ Points,
+ PointsMaterial,
Scene,
SpotLight,
SRGBColorSpace,
@@ -33,7 +38,7 @@ import { AnimationManager } from './animation-manager.js';
import { ClubCamera } from './club-camera.js';
import { ClubAudio, styleAudioFor, TRACK_LABELS } from './club-audio.js';
import { playSequence, ticketSteps } from './club-sequence.js';
-import { detectProfile, PROFILES, createFrameWatchdog } from './club-perf.js';
+import { detectProfile, PROFILES, createFrameWatchdog, isMobileLayout } from './club-perf.js';
const AVATAR_URL = '/avatars/default.glb';
const MANIFEST_URL = '/animations/manifest.json';
@@ -328,6 +333,14 @@ document.querySelector('#club-stage')?.setAttribute('data-cam-mode', clubCam.get
// ── Poles + spotlights ───────────────────────────────────────────────────
const POLE_COLORS = [0xff3bd6, 0x4ad6ff, 0xff8a3b, 0x9b5dff];
+// Dancer registry — display names, bios, accent palette.
+const DANCER_META = [
+ { name: 'Aria', bio: 'Neon pink fire. Classical meets street.', palette: 'pink' },
+ { name: 'Nova', bio: 'Cyan ice. Fluid and hypnotic.', palette: 'cyan' },
+ { name: 'Blaze', bio: 'Amber heat. Power and precision.', palette: 'amber' },
+ { name: 'Luna', bio: 'Violet dream. Gravity-defying flow.', palette: 'violet' },
+];
+
class PoleStation {
constructor(idx, layout) {
this.idx = idx;
@@ -517,15 +530,18 @@ class PoleStation {
this._accentTarget = 2.4;
// Auto-cam: if the user opted in and no manual VIP/house shot is active,
- // switch to this pole's VIP cam for the duration. We remember that the
+ // switch to an orbiting auto-cam for the duration. We remember that the
// auto-cam started this transition so we can release it on end.
if (autoFollow && clubCam.getMode() === 'free') {
this._autoCammed = true;
- clubCam.setVip(this.layout);
+ clubCam.setAuto(this.layout);
} else {
this._autoCammed = false;
}
+ // Update pole card status.
+ updatePoleCardStatus(this.id, 'performing');
+
// Crossfade idle → walking → dance once the dancer reaches the pole.
await this.anim?.crossfadeTo(WALK_CLIP, PERFORMANCE_FADE);
}
@@ -574,10 +590,13 @@ class PoleStation {
this._spotTarget = this.spotIdleIntensity;
this._accentTarget = 0.4;
// Release auto-cam back to free if we were the ones who took it.
- if (this._autoCammed && clubCam.getMode() === 'vip') {
+ if (this._autoCammed && (clubCam.getMode() === 'auto' || clubCam.getMode() === 'vip')) {
clubCam.setFree();
}
this._autoCammed = false;
+
+ // Update pole card status back to idle.
+ updatePoleCardStatus(this.id, 'idle');
// Signal the audio mixer (and anyone else listening) to fade the
// style loop back to ambience. Dispatched on window so the page-
// level audio binding can stay decoupled from this class.
@@ -984,34 +1003,99 @@ const DANCES = [
{ key: 'thriller', label: 'Thriller' },
{ key: 'capoeira', label: 'Capoeira' },
{ key: 'hiphop', label: 'Hip Hop' },
+ { key: 'spin', label: 'Pole Spin' },
+ { key: 'climb', label: 'Climb + Invert' },
+ { key: 'combo', label: 'Combo' },
];
+// Track per-pole card elements for status updates.
+const poleCardEls = new Map();
+
+function updatePoleCardStatus(poleId, status) {
+ const cardEl = poleCardEls.get(poleId);
+ if (!cardEl) return;
+ const dotEl = cardEl.querySelector('.club-status-dot');
+ const labelEl = cardEl.querySelector('.club-pole-status-label');
+ const btnEl = cardEl.querySelector('.club-tip-btn');
+ const progressEl = cardEl.querySelector('.club-pole-progress');
+
+ if (dotEl) {
+ dotEl.classList.remove('is-idle', 'is-performing', 'is-backstage');
+ dotEl.classList.add(status === 'performing' ? 'is-performing' : status === 'backstage' ? 'is-backstage' : 'is-idle');
+ }
+ if (labelEl) {
+ labelEl.textContent = status === 'performing' ? 'Performing' : status === 'backstage' ? 'Backstage' : 'Idle';
+ }
+ if (btnEl) {
+ if (status === 'performing') {
+ btnEl.disabled = true;
+ btnEl.textContent = 'Performing...';
+ } else {
+ btnEl.disabled = false;
+ const meta = DANCER_META[parseInt(poleId, 10) - 1] || DANCER_META[0];
+ btnEl.textContent = `Tip $0.001`;
+ }
+ }
+ if (progressEl) {
+ progressEl.style.display = status === 'performing' ? '' : 'none';
+ }
+}
+
+function flashPoleCard(poleId) {
+ const cardEl = poleCardEls.get(poleId);
+ if (!cardEl) return;
+ cardEl.classList.remove('is-flash');
+ void cardEl.offsetWidth; // force reflow for re-triggering animation
+ cardEl.classList.add('is-flash');
+ cardEl.addEventListener('animationend', () => cardEl.classList.remove('is-flash'), { once: true });
+}
+
function renderPoles() {
if (!polesPanel) return;
polesPanel.innerHTML = '';
for (const pole of POLES) {
+ const idx = parseInt(pole.id, 10) - 1;
+ const meta = DANCER_META[idx] || DANCER_META[0];
const card = document.createElement('div');
card.className = 'club-pole-card';
+ card.setAttribute('role', 'listitem');
+ card.setAttribute('aria-label', `Pole ${pole.id} - ${meta.name}`);
+ card.dataset.poleId = pole.id;
+
card.innerHTML = `
<div class="club-pole-head">
- <span class="club-pole-id">Pole ${pole.id}</span>
+ <div>
+ <span class="club-dancer-name">${meta.name}</span>
+ <span class="club-dancer-bio" title="${meta.bio}">${meta.bio}</span>
+ </div>
<span class="club-pole-row-right">
- <span class="club-pole-price">$0.001 USDC</span>
- <button type="button" class="club-cam-btn" data-pole="${pole.id}" title="VIP cam">🎬</button>
+ <button type="button" class="club-cam-btn" data-pole="${pole.id}" title="VIP camera for ${meta.name}" aria-label="VIP camera for pole ${pole.id}">VIP</button>
</span>
</div>
+ <div class="club-pole-status" aria-label="Status: Idle">
+ <span class="club-status-dot is-idle" aria-hidden="true"></span>
+ <span class="club-pole-status-label">Idle</span>
+ <span class="club-pole-stats" id="club-pole-stats-${pole.id}" aria-label="Tips today: 0">0 tips today</span>
+ </div>
+ <div class="club-pole-progress" style="display:none" role="progressbar" aria-label="Performance progress" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
+ <div class="club-pole-progress-bar" style="width:0%"></div>
+ </div>
<label class="club-pole-style">
+ <span class="sr-only">Dance style for ${meta.name}</span>
Style
- <select data-dancer="${pole.id}" class="club-pole-select">
+ <select data-dancer="${pole.id}" class="club-pole-select" aria-label="Dance style for pole ${pole.id}">
${DANCES.map((d) => `<option value="${d.key}">${d.label}</option>`).join('')}
</select>
</label>
- <button type="button" class="club-tip-btn" data-dancer="${pole.id}">
- Tip ${pole.id} — make her dance
+ <button type="button" class="club-tip-btn" data-dancer="${pole.id}" aria-label="Tip ${meta.name} $0.001 USDC">
+ Tip $0.001
</button>
`;
polesPanel.appendChild(card);
+ poleCardEls.set(pole.id, card);
}
+
+ // Tap card on mobile to VIP.
polesPanel.addEventListener('click', (e) => {
const camBtn = e.target.closest('.club-cam-btn');
if (camBtn) {
@@ -1020,11 +1104,20 @@ function renderPoles() {
return;
}
const btn = e.target.closest('.club-tip-btn');
- if (!btn) return;
- const dancer = btn.dataset.dancer;
- const select = polesPanel.querySelector(`.club-pole-select[data-dancer="${dancer}"]`);
- const dance = select?.value || 'rumba';
- tipDancer({ dancer, dance, button: btn });
+ if (btn) {
+ const dancer = btn.dataset.dancer;
+ const select = polesPanel.querySelector(`.club-pole-select[data-dancer="${dancer}"]`);
+ const dance = select?.value || 'rumba';
+ tipDancer({ dancer, dance, button: btn });
+ return;
+ }
+ // Tap the card itself (not a button/select) on mobile → VIP cam.
+ const card = e.target.closest('.club-pole-card');
+ if (card && isMobileLayout()) {
+ const poleId = card.dataset.poleId;
+ const layout = POLES.find((p) => p.id === poleId);
+ if (layout) clubCam.setVip(layout);
+ }
});
}
diff --git a/src/dashboard-next/nav.js b/src/dashboard-next/nav.js
index d8a5c677b..1181e47b1 100644
--- a/src/dashboard-next/nav.js
+++ b/src/dashboard-next/nav.js
@@ -31,6 +31,7 @@ export const NAV = [
{ path: '/skills', label: 'Skills', icon: 'skills', group: 'Distribute', tags: ['tool', 'pack', 'capability', 'install', 'browse', 'skill'], external: true },
// ── Monetize ────────────────────────────────────────────────────────
+ { path: '/dashboard/three-token', label: '$THREE', icon: 'three', group: 'Monetize', tags: ['token', 'utility', 'burn', 'revenue share', 'protocol', '$three', 'economy', 'holders'] },
{ path: '/dashboard/analytics', label: 'Analytics', icon: 'chart', group: 'Monetize', tags: ['revenue', 'charts', 'metrics', 'funnel', 'performance', 'views', 'engagement'] },
{ path: '/dashboard/monetize', label: 'Monetize', icon: 'coin', group: 'Monetize', tags: ['revenue', 'payments', 'subscriptions', 'withdrawals', 'earnings', 'plan', 'billing'] },
{ path: '/dashboard/tokens', label: 'Tokens', icon: 'token', group: 'Monetize', tags: ['pump.fun', 'launch', 'bonding curve', 'royalties', 'trade'] },
@@ -76,6 +77,7 @@ export const ICONS = {
community: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="2.5"/><circle cx="14" cy="7" r="2"/><path d="M2 16c.8-2.8 2.8-4.2 5-4.2s4.2 1.4 5 4.2"/><path d="M13.5 11.8c1.5 0 3 1.2 3.5 3.2"/></svg>',
play: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="16" height="14" rx="2"/><path d="M8 7.5v5l4.5-2.5z"/></svg>',
live: '<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="2"/><path d="M6 6a5.5 5.5 0 000 8"/><path d="M14 6a5.5 5.5 0 010 8"/><path d="M3.5 3.5a9 9 0 000 13"/><path d="M16.5 3.5a9 9 0 010 13"/></svg>',
+ three: '<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="7.5"/><path d="M7.5 6.5h5L10 10h2.5a2.5 2.5 0 01 0 5H7.5"/></svg>',
chart: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M3 17V7l4 3 3-6 4 4 3-3v12H3z"/><path d="M3 17h14"/></svg>',
skills: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="14" height="14" rx="3"/><path d="M7 7h6M7 10h4M7 13h5"/></svg>',
devhub: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="16" height="12" rx="2"/><path d="M6 7l-2 2.5L6 12M14 7l2 2.5L14 12M9 13l2-8"/></svg>',
diff --git a/src/dashboard-next/pages/agents.js b/src/dashboard-next/pages/agents.js
index 650400aed..0428cc386 100644
--- a/src/dashboard-next/pages/agents.js
+++ b/src/dashboard-next/pages/agents.js
@@ -64,6 +64,24 @@ function truncMid(s, head = 6, tail = 4) {
</div>
<button class="dn-btn primary" data-action="create-agent">+ New agent</button>
</div>
+
+ <div data-slot="filter-bar" class="dn-agents-filter-bar">
+ <div class="dn-agents-search-wrap">
+ <svg class="dn-agents-search-icon" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><circle cx="7" cy="7" r="4.5"/><path d="M13 13l-3-3"/></svg>
+ <input type="text" class="dn-agents-search" placeholder="Filter agents..." data-action="filter-search" autocomplete="off" spellcheck="false" aria-label="Filter agents" />
+ </div>
+ <div class="dn-agents-sort-wrap">
+ <label style="font-size:12px;color:var(--nxt-ink-fade);white-space:nowrap">Sort by</label>
+ <select class="dn-agents-sort" data-action="sort-select" aria-label="Sort agents">
+ <option value="created-desc">Newest first</option>
+ <option value="created-asc">Oldest first</option>
+ <option value="name-asc">Name A-Z</option>
+ <option value="name-desc">Name Z-A</option>
+ </select>
+ </div>
+ <span class="dn-agents-count" data-slot="agents-count"></span>
+ </div>
+
<div data-slot="content" style="display:flex;flex-direction:column;gap:16px"></div>
`;
@@ -78,7 +96,72 @@ function truncMid(s, head = 6, tail = 4) {
const agents = agentsResp?.agents || [];
const avatars = avatarsResp?.avatars || [];
- renderAgents(host, agents, avatars, main);
+ let currentFilter = '';
+ let currentSort = 'created-desc';
+
+ function getFilteredAgents() {
+ let filtered = agents;
+ if (currentFilter) {
+ const q = currentFilter.toLowerCase();
+ filtered = agents.filter((a) => {
+ const name = (a.name || a.display_name || '').toLowerCase();
+ const wallet = (a.wallet_address || a.solana_address || '').toLowerCase();
+ const tagline = (a.persona?.tagline || a.tagline || '').toLowerCase();
+ return name.includes(q) || wallet.includes(q) || tagline.includes(q);
+ });
+ }
+ filtered = [...filtered].sort((a, b) => {
+ switch (currentSort) {
+ case 'created-asc':
+ return new Date(a.created_at || 0) - new Date(b.created_at || 0);
+ case 'name-asc':
+ return (a.name || '').localeCompare(b.name || '');
+ case 'name-desc':
+ return (b.name || '').localeCompare(a.name || '');
+ case 'created-desc':
+ default:
+ return new Date(b.created_at || 0) - new Date(a.created_at || 0);
+ }
+ });
+ return filtered;
+ }
+
+ function rerender() {
+ const filtered = getFilteredAgents();
+ const countEl = main.querySelector('[data-slot="agents-count"]');
+ if (countEl) {
+ countEl.textContent = currentFilter
+ ? `${filtered.length} of ${agents.length} agent${agents.length !== 1 ? 's' : ''}`
+ : `${agents.length} agent${agents.length !== 1 ? 's' : ''}`;
+ }
+ renderAgents(host, filtered, avatars, main);
+ }
+
+ rerender();
+
+ const searchInput = main.querySelector('[data-action="filter-search"]');
+ let searchTimeout = null;
+ searchInput.addEventListener('input', () => {
+ clearTimeout(searchTimeout);
+ searchTimeout = setTimeout(() => {
+ currentFilter = searchInput.value.trim();
+ rerender();
+ }, 150);
+ });
+ searchInput.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape') {
+ searchInput.value = '';
+ currentFilter = '';
+ rerender();
+ searchInput.blur();
+ }
+ });
+
+ main.querySelector('[data-action="sort-select"]').addEventListener('change', (e) => {
+ currentSort = e.target.value;
+ rerender();
+ });
+
main.querySelector('[data-action="create-agent"]').addEventListener('click', () => {
openCreateModal(host, agents, avatars);
});
@@ -739,6 +822,72 @@ function injectStyles() {
const css = document.createElement('style');
css.id = 'dn-agents-css';
css.textContent = `
+ .dn-agents-filter-bar {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ margin-bottom: 14px;
+ flex-wrap: wrap;
+ }
+ .dn-agents-search-wrap {
+ position: relative;
+ flex: 1;
+ min-width: 180px;
+ }
+ .dn-agents-search-icon {
+ position: absolute;
+ left: 12px;
+ top: 50%;
+ transform: translateY(-50%);
+ color: var(--nxt-ink-fade);
+ pointer-events: none;
+ }
+ .dn-agents-search {
+ width: 100%;
+ padding: 9px 12px 9px 34px;
+ background: rgba(255,255,255,0.04);
+ border: 1px solid var(--nxt-stroke);
+ border-radius: 8px;
+ color: var(--nxt-ink);
+ font-size: 13px;
+ font-family: inherit;
+ outline: none;
+ transition: border-color 0.14s ease, background 0.14s ease;
+ }
+ .dn-agents-search::placeholder { color: var(--nxt-ink-fade); }
+ .dn-agents-search:focus {
+ border-color: var(--nxt-stroke-strong);
+ background: rgba(255,255,255,0.06);
+ }
+ .dn-agents-sort-wrap {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .dn-agents-sort {
+ background: rgba(255,255,255,0.04);
+ border: 1px solid var(--nxt-stroke);
+ border-radius: 8px;
+ color: var(--nxt-ink);
+ font-size: 12.5px;
+ font-family: inherit;
+ padding: 8px 10px;
+ cursor: pointer;
+ outline: none;
+ transition: border-color 0.14s ease;
+ }
+ .dn-agents-sort:focus { border-color: var(--nxt-stroke-strong); }
+ .dn-agents-sort option { background: #14151c; color: var(--nxt-ink); }
+ .dn-agents-count {
+ font-size: 12px;
+ color: var(--nxt-ink-fade);
+ white-space: nowrap;
+ font-variant-numeric: tabular-nums;
+ }
+ @media (max-width: 600px) {
+ .dn-agents-filter-bar { flex-direction: column; align-items: stretch; }
+ .dn-agents-sort-wrap { justify-content: space-between; }
+ }
.dn-agent-card {
display: grid;
grid-template-columns: auto 1fr;
diff --git a/src/dashboard-next/pages/home.js b/src/dashboard-next/pages/home.js
index 5bc29fa15..10717d12c 100644
--- a/src/dashboard-next/pages/home.js
+++ b/src/dashboard-next/pages/home.js
@@ -36,6 +36,7 @@ const STATE = {
<div class="dnx-col-main">
<section data-slot="hero" class="dnx-hero"></section>
<section data-slot="kpis" class="dnx-kpis"></section>
+ <section data-slot="health" class="dnx-health-wrap"></section>
<section data-slot="quick" class="dnx-quick"></section>
<section data-slot="directory" class="dnx-directory"></section>
</div>
@@ -50,6 +51,7 @@ const STATE = {
onboarding: main.querySelector('[data-slot="onboarding"]'),
hero: main.querySelector('[data-slot="hero"]'),
kpis: main.querySelector('[data-slot="kpis"]'),
+ health: main.querySelector('[data-slot="health"]'),
quick: main.querySelector('[data-slot="quick"]'),
directory: main.querySelector('[data-slot="directory"]'),
activity: main.querySelector('[data-slot="activity"]'),
@@ -58,7 +60,7 @@ const STATE = {
const [avatarsRes, widgetsRes, agentsRes] = await Promise.allSettled([
get('/api/avatars?limit=50'),
get('/api/widgets'),
- get('/api/agents?limit=1'),
+ get('/api/agents?limit=20'),
]);
const avatars = avatarsRes.status === 'fulfilled' ? (avatarsRes.value?.avatars ?? []) : [];
@@ -66,6 +68,7 @@ const STATE = {
const agents = agentsRes.status === 'fulfilled' ? (agentsRes.value?.agents ?? []) : [];
renderHero(slots.hero, avatars, avatarsRes.status === 'rejected' ? avatarsRes.reason : null);
+ renderAgentHealth(slots.health, agents, widgets);
renderQuickActions(slots.quick, { avatars, agents });
renderDirectory(slots.directory);
diff --git a/src/dashboard-next/pages/settings.js b/src/dashboard-next/pages/settings.js
index d9416554b..57ac35c90 100644
--- a/src/dashboard-next/pages/settings.js
+++ b/src/dashboard-next/pages/settings.js
@@ -73,12 +73,16 @@ function toast(msg) {
]);
host.innerHTML = '';
+ host.appendChild(renderTheme());
host.appendChild(renderSessions(sessionsResp?.sessions || []));
host.appendChild(renderNotifications(notifResp));
+ host.appendChild(renderDefaultNetwork(prefsResp?.prefs || prefsResp || {}));
host.appendChild(renderStorage(summaryResp));
host.appendChild(renderLlmUsage(usageResp));
host.appendChild(renderVanityTools());
host.appendChild(renderPrefs(prefsResp?.prefs || prefsResp || {}));
+ host.appendChild(renderDataExport());
+ host.appendChild(renderAbout());
} catch (err) {
if (err instanceof ApiError && err.status === 401) {
location.href = `/login?return=${encodeURIComponent(location.pathname)}`;
@@ -423,6 +427,218 @@ function renderPrefs(prefs) {
return panel;
}
+// ── Theme ─────────────────────────────────────────────────────────────────
+
+function renderTheme() {
+ const panel = document.createElement('div');
+ panel.className = 'dn-panel';
+
+ const stored = localStorage.getItem('twx_theme') || 'dark';
+
+ panel.innerHTML = `
+ <div style="margin-bottom:14px">
+ <div class="dn-panel-title">Appearance</div>
+ <div class="dn-panel-sub" style="margin:2px 0 0">Choose your dashboard color scheme.</div>
+ </div>
+ <div style="display:flex;gap:10px;flex-wrap:wrap">
+ ${['dark', 'light', 'auto'].map((t) => `
+ <button class="dn-btn ${t === stored ? 'primary' : ''}" data-theme="${t}" type="button"
+ style="min-width:90px;justify-content:center;text-transform:capitalize">
+ ${t === 'dark' ? '<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><path d="M13.5 8.5a5.5 5.5 0 11-6-6 4.5 4.5 0 006 6z"/></svg>' : ''}
+ ${t === 'light' ? '<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><circle cx="8" cy="8" r="3"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M3.2 3.2l1.4 1.4M11.4 11.4l1.4 1.4M3.2 12.8l1.4-1.4M11.4 4.6l1.4-1.4"/></svg>' : ''}
+ ${t === 'auto' ? '<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><rect x="2" y="3" width="12" height="10" rx="1.5"/><path d="M8 3v10"/></svg>' : ''}
+ ${t}
+ </button>
+ `).join('')}
+ </div>
+ <div style="margin-top:10px;font-size:12px;color:var(--nxt-ink-fade)">
+ ${stored === 'auto' ? 'Following your system preference.' : `Currently using ${stored} mode.`}
+ The platform is designed for dark mode. Light mode support is coming.
+ </div>
+ `;
+
+ panel.querySelectorAll('[data-theme]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const theme = btn.dataset.theme;
+ localStorage.setItem('twx_theme', theme);
+ panel.querySelectorAll('[data-theme]').forEach((b) => {
+ b.classList.toggle('primary', b.dataset.theme === theme);
+ });
+ const hint = panel.querySelector('div:last-child');
+ hint.textContent = theme === 'auto'
+ ? 'Following your system preference.'
+ : `Set to ${theme} mode. The platform is designed for dark mode. Light mode support is coming.`;
+ toast('Theme preference saved');
+ });
+ });
+
+ return panel;
+}
+
+// ── Default network ───────────────────────────────────────────────────────
+
+function renderDefaultNetwork(prefs) {
+ const panel = document.createElement('div');
+ panel.className = 'dn-panel';
+
+ const current = prefs.default_network || localStorage.getItem('twx_default_network') || 'base';
+
+ panel.innerHTML = `
+ <div style="margin-bottom:14px">
+ <div class="dn-panel-title">Default payment network</div>
+ <div class="dn-panel-sub" style="margin:2px 0 0">Select the default blockchain for payments and token operations.</div>
+ </div>
+ <div style="display:flex;gap:10px;flex-wrap:wrap">
+ ${[
+ { value: 'base', label: 'Base', note: 'Low-fee EVM L2' },
+ { value: 'solana', label: 'Solana', note: 'Fast, low-cost' },
+ { value: 'polygon', label: 'Polygon', note: 'EVM L2' },
+ ].map((n) => `
+ <button class="dn-btn ${n.value === current ? 'primary' : ''}" data-network="${n.value}" type="button"
+ style="min-width:120px;flex-direction:column;align-items:center;gap:4px;padding:14px 16px">
+ <span style="font-weight:600;font-size:14px">${esc(n.label)}</span>
+ <span style="font-size:11px;color:${n.value === current ? 'rgba(0,0,0,0.6)' : 'var(--nxt-ink-fade)'}">${esc(n.note)}</span>
+ </button>
+ `).join('')}
+ </div>
+ `;
+
+ panel.querySelectorAll('[data-network]').forEach((btn) => {
+ btn.addEventListener('click', async () => {
+ const network = btn.dataset.network;
+ localStorage.setItem('twx_default_network', network);
+ panel.querySelectorAll('[data-network]').forEach((b) => {
+ b.classList.toggle('primary', b.dataset.network === network);
+ const sub = b.querySelector('span:last-child');
+ if (sub) sub.style.color = b.dataset.network === network ? 'rgba(0,0,0,0.6)' : 'var(--nxt-ink-fade)';
+ });
+ try {
+ await patch('/api/dashboard/prefs', { default_network: network });
+ } catch { /* best-effort server save */ }
+ toast(`Default network set to ${network}`);
+ });
+ });
+
+ return panel;
+}
+
+// ── Data export ───────────────────────────────────────────────────────────
+
+function renderDataExport() {
+ const panel = document.createElement('div');
+ panel.className = 'dn-panel';
+
+ panel.innerHTML = `
+ <div style="margin-bottom:14px">
+ <div class="dn-panel-title">Data export</div>
+ <div class="dn-panel-sub" style="margin:2px 0 0">Download a copy of your account data including agents, avatars, and settings.</div>
+ </div>
+ <div style="display:flex;gap:10px;flex-wrap:wrap">
+ <button class="dn-btn" data-action="export-agents" type="button">
+ <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><path d="M8 2v10M5 9l3 3 3-3"/><path d="M2 12v2h12v-2"/></svg>
+ Export agents
+ </button>
+ <button class="dn-btn" data-action="export-avatars" type="button">
+ <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><path d="M8 2v10M5 9l3 3 3-3"/><path d="M2 12v2h12v-2"/></svg>
+ Export avatars
+ </button>
+ <button class="dn-btn" data-action="export-all" type="button">
+ <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><path d="M8 2v10M5 9l3 3 3-3"/><path d="M2 12v2h12v-2"/></svg>
+ Export all data (JSON)
+ </button>
+ </div>
+ `;
+
+ async function exportData(type) {
+ const btn = panel.querySelector(`[data-action="export-${type}"]`);
+ const originalHtml = btn.innerHTML;
+ btn.disabled = true;
+ btn.textContent = 'Exporting...';
+ try {
+ const calls = [];
+ if (type === 'agents' || type === 'all') calls.push(get('/api/agents').catch(() => ({ agents: [] })));
+ if (type === 'avatars' || type === 'all') calls.push(get('/api/avatars?limit=100').catch(() => ({ avatars: [] })));
+ if (type === 'all') calls.push(get('/api/widgets').catch(() => ({ widgets: [] })));
+
+ const results = await Promise.all(calls);
+ const data = {};
+ let i = 0;
+ if (type === 'agents' || type === 'all') { data.agents = results[i]?.agents || []; i++; }
+ if (type === 'avatars' || type === 'all') { data.avatars = results[i]?.avatars || []; i++; }
+ if (type === 'all') { data.widgets = results[i]?.widgets || []; i++; }
+ data.exported_at = new Date().toISOString();
+
+ const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `threews-${type}-${new Date().toISOString().slice(0, 10)}.json`;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ URL.revokeObjectURL(url);
+ toast('Data exported');
+ } catch (err) {
+ toast(err?.message || 'Export failed');
+ } finally {
+ btn.disabled = false;
+ btn.innerHTML = originalHtml;
+ }
+ }
+
+ panel.querySelector('[data-action="export-agents"]').addEventListener('click', () => exportData('agents'));
+ panel.querySelector('[data-action="export-avatars"]').addEventListener('click', () => exportData('avatars'));
+ panel.querySelector('[data-action="export-all"]').addEventListener('click', () => exportData('all'));
+
+ return panel;
+}
+
+// ── About ─────────────────────────────────────────────────────────────────
+
+function renderAbout() {
+ const panel = document.createElement('div');
+ panel.className = 'dn-panel';
+
+ const buildDate = new Date().toISOString().slice(0, 10);
+
+ panel.innerHTML = `
+ <div style="margin-bottom:14px">
+ <div class="dn-panel-title">About three.ws</div>
+ <div class="dn-panel-sub" style="margin:2px 0 0">Platform information and helpful links.</div>
+ </div>
+ <div style="display:grid;grid-template-columns:auto 1fr;gap:8px 16px;font-size:13px;margin-bottom:16px">
+ <span style="color:var(--nxt-ink-fade)">Platform</span>
+ <span style="color:var(--nxt-ink)">three.ws</span>
+ <span style="color:var(--nxt-ink-fade)">Dashboard</span>
+ <span style="color:var(--nxt-ink)">dashboard-next</span>
+ <span style="color:var(--nxt-ink-fade)">Build</span>
+ <span style="color:var(--nxt-ink);font-family:${MONO};font-size:12px">${esc(buildDate)}</span>
+ <span style="color:var(--nxt-ink-fade)">Language</span>
+ <span style="color:var(--nxt-ink)">English</span>
+ </div>
+ <div style="display:flex;gap:10px;flex-wrap:wrap">
+ <a class="dn-btn" href="/features" style="text-decoration:none">
+ <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M4 4h12v12H4z"/><path d="M4 10h12M10 4v12"/></svg>
+ Features
+ </a>
+ <a class="dn-btn" href="/tutorials" style="text-decoration:none">
+ <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M1 3h5a2 2 0 012 2v9a1.5 1.5 0 00-1.5-1.5H1V3z"/><path d="M15 3h-5a2 2 0 00-2 2v9a1.5 1.5 0 011.5-1.5H15V3z"/></svg>
+ Documentation
+ </a>
+ <a class="dn-btn" href="/community" style="text-decoration:none">
+ <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="6" cy="6" r="2"/><circle cx="11" cy="6" r="1.5"/><path d="M1.5 13c.6-2.2 2.2-3.3 4.5-3.3s3.9 1.1 4.5 3.3"/></svg>
+ Community
+ </a>
+ <a class="dn-btn" href="mailto:[email protected]" style="text-decoration:none">
+ <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="1" y="3" width="14" height="10" rx="1.5"/><path d="M1 3l7 5 7-5"/></svg>
+ Support
+ </a>
+ </div>
+ `;
+
+ return panel;
+}
+
function prefToggle(key, label, description, checked) {
return `
<label style="display:flex;align-items:center;justify-content:space-between;gap:16px;cursor:pointer">
diff --git a/src/dashboard-next/pages/three-token.js b/src/dashboard-next/pages/three-token.js
new file mode 100644
index 000000000..0207dde0b
--- /dev/null
+++ b/src/dashboard-next/pages/three-token.js
@@ -0,0 +1,633 @@
+// dashboard-next — $THREE Token Utility page.
+//
+// The command center for the $THREE protocol economy. Shows real token
+// data from Birdeye/Pump.fun, platform revenue metrics, and the four
+// utility pillars: agent-to-agent payments, revenue share, deploy burns,
+// and index token exposure.
+//
+// Real endpoints:
+// GET /api/three-token/stats { token, protocol }
+// GET /api/three-token/revenue-share { user_id, ... }
+// GET /api/three-token/activity { events }
+
+import { mountShell } from '../shell.js';
+import { requireUser, get, esc, relTime, ApiError } from '../api.js';
+
+const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+function fmtUsd(n) {
+ if (n == null || !Number.isFinite(+n)) return '—';
+ const v = +n;
+ if (v >= 1_000_000) return '$' + (v / 1_000_000).toFixed(2) + 'M';
+ if (v >= 1_000) return '$' + (v / 1_000).toFixed(2) + 'K';
+ if (v >= 1) return '$' + v.toFixed(2);
+ if (v >= 0.0001) return '$' + v.toFixed(6);
+ return '$' + v.toExponential(2);
+}
+
+function fmtCompact(n) {
+ if (n == null) return '—';
+ const v = +n;
+ if (v >= 1_000_000_000) return (v / 1_000_000_000).toFixed(2) + 'B';
+ if (v >= 1_000_000) return (v / 1_000_000).toFixed(2) + 'M';
+ if (v >= 1_000) return (v / 1_000).toFixed(1) + 'K';
+ return v.toLocaleString();
+}
+
+function fmtPct(n) {
+ if (n == null || !Number.isFinite(+n)) return '—';
+ const v = +n;
+ const sign = v >= 0 ? '+' : '';
+ return sign + v.toFixed(2) + '%';
+}
+
+function pctColor(n) {
+ if (n == null || !Number.isFinite(+n)) return 'var(--nxt-ink-dim)';
+ return +n >= 0 ? 'var(--nxt-success)' : 'var(--nxt-danger)';
+}
+
+function toast(msg) {
+ let el = document.getElementById('dn-toast');
+ if (!el) {
+ el = document.createElement('div');
+ el.id = 'dn-toast';
+ el.style.cssText = `position:fixed;left:50%;bottom:32px;transform:translateX(-50%) translateY(20px);
+ background:rgba(20,21,28,0.95);border:1px solid var(--nxt-stroke-strong);
+ color:var(--nxt-ink);padding:9px 16px;border-radius:999px;font-size:13px;
+ z-index:9999;opacity:0;transition:opacity .18s,transform .18s;
+ backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px);
+ box-shadow:0 8px 24px rgba(0,0,0,0.4);pointer-events:none;`;
+ document.body.appendChild(el);
+ }
+ el.textContent = msg;
+ requestAnimationFrame(() => {
+ el.style.opacity = '1';
+ el.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ clearTimeout(el._t);
+ el._t = setTimeout(() => {
+ el.style.opacity = '0';
+ el.style.transform = 'translateX(-50%) translateY(20px)';
+ }, 1800);
+}
+
+async function safeGet(url) {
+ try { return await get(url); }
+ catch { return null; }
+}
+
+// ── Boot ──────────────────────────────────────────────────────────────────────
+
+(async function boot() {
+ try {
+ const main = await mountShell();
+ const me = await requireUser();
+
+ main.innerHTML = `
+ <div style="margin-bottom:6px">
+ <div style="display:flex;align-items:center;gap:12px;margin-bottom:4px">
+ <div style="width:36px;height:36px;border-radius:10px;background:linear-gradient(135deg,#fff 0%,#888 100%);display:grid;place-items:center;font-weight:800;font-size:15px;color:#000;flex-shrink:0">$3</div>
+ <div>
+ <h1 class="dn-h1" style="margin:0">$THREE</h1>
+ <p class="dn-h1-sub" style="margin:0">The protocol token powering the three.ws agent economy</p>
+ </div>
+ </div>
+ </div>
+ <div data-slot="content" style="display:flex;flex-direction:column;gap:20px">
+ ${skeletonGrid(4)}
+ ${skeletonBlock(280)}
+ ${skeletonBlock(200)}
+ </div>
+ `;
+
+ const host = main.querySelector('[data-slot="content"]');
+
+ const [stats, revenueShare, activity] = await Promise.all([
+ safeGet('/api/three-token/stats'),
+ safeGet('/api/three-token/revenue-share'),
+ safeGet('/api/three-token/activity'),
+ ]);
+
+ host.innerHTML = '';
+
+ host.appendChild(renderHeroMetrics(stats));
+ host.appendChild(renderUtilityPillars(stats));
+ host.appendChild(renderRevenueShare(stats, revenueShare));
+ host.appendChild(renderDeployBurn(stats));
+ host.appendChild(renderActivityFeed(activity));
+ host.appendChild(renderTokenInfo());
+
+ } catch (err) {
+ if (err instanceof ApiError && err.status === 401) {
+ location.href = `/login?return=${encodeURIComponent(location.pathname)}`;
+ } else throw err;
+ }
+})();
+
+// ── Skeletons ─────────────────────────────────────────────────────────────────
+
+function skeletonGrid(n) {
+ return `<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px">
+ ${Array.from({ length: n }, () => `<div class="dn-skeleton" style="height:96px;border-radius:12px"></div>`).join('')}
+ </div>`;
+}
+
+function skeletonBlock(h) {
+ return `<div class="dn-skeleton" style="height:${h}px;border-radius:12px"></div>`;
+}
+
+// ── Hero metrics ──────────────────────────────────────────────────────────────
+
+function renderHeroMetrics(stats) {
+ const t = stats?.token || {};
+ const p = stats?.protocol || {};
+
+ const metrics = [
+ {
+ label: 'Price',
+ value: fmtUsd(t.price_usd),
+ sub: t.price_change_24h != null
+ ? `<span style="color:${pctColor(t.price_change_24h)};font-size:12px;font-weight:500">${fmtPct(t.price_change_24h)} 24h</span>`
+ : '',
+ },
+ {
+ label: 'Market Cap',
+ value: t.market_cap != null ? fmtUsd(t.market_cap) : '—',
+ sub: '',
+ },
+ {
+ label: '24h Volume',
+ value: t.volume_24h != null ? fmtUsd(t.volume_24h) : '—',
+ sub: '',
+ },
+ {
+ label: 'Holders',
+ value: t.holders != null ? fmtCompact(t.holders) : '—',
+ sub: '',
+ },
+ ];
+
+ const wrap = document.createElement('div');
+ wrap.style.cssText = 'display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px';
+
+ metrics.forEach(({ label, value, sub }) => {
+ const card = document.createElement('div');
+ card.className = 'dn-panel';
+ card.style.cssText = 'position:relative;overflow:hidden;';
+ card.innerHTML = `
+ <div style="position:absolute;top:0;right:0;width:80px;height:80px;background:radial-gradient(circle at top right,rgba(255,255,255,0.03),transparent 70%);pointer-events:none"></div>
+ <div style="font-size:11.5px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.06em;margin-bottom:6px">${esc(label)}</div>
+ <div style="font-size:26px;font-weight:700;letter-spacing:-0.03em;font-family:${MONO}">${value}</div>
+ ${sub ? `<div style="margin-top:4px">${sub}</div>` : ''}
+ `;
+ wrap.appendChild(card);
+ });
+
+ return wrap;
+}
+
+// ── Four utility pillars ──────────────────────────────────────────────────────
+
+function renderUtilityPillars(stats) {
+ const p = stats?.protocol || {};
+ const t = stats?.token || {};
+
+ const pillars = [
+ {
+ icon: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" style="width:28px;height:28px"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>`,
+ title: 'Agent Payment Rail',
+ desc: 'Every agent-to-agent transaction on three.ws settles in $THREE. More agents working = more $THREE moving.',
+ metric: fmtCompact(p.total_payments || 0),
+ metricLabel: 'protocol payments',
+ color: '#4ade80',
+ },
+ {
+ icon: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" style="width:28px;height:28px"><path d="M12 1v22M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg>`,
+ title: 'Revenue Share',
+ desc: `${p.revenue_share_pool_pct || 10}% of all platform revenue distributes to $THREE holders pro rata. Hold tokens, earn yield from real usage.`,
+ metric: fmtUsd(p.total_revenue_usd || 0),
+ metricLabel: 'platform revenue',
+ color: '#60a5fa',
+ },
+ {
+ icon: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" style="width:28px;height:28px"><path d="M12 22C6.5 22 2 17.5 2 12S6.5 2 12 2s10 4.5 10 10"/><path d="M18 16l4 4m0-4l-4 4"/></svg>`,
+ title: 'Deploy-to-Burn',
+ desc: `Every agent deployed on three.ws burns ${fmtCompact(p.agent_deploy_burn || 1000)} $THREE permanently. More agents = less supply.`,
+ metric: fmtCompact(p.total_agents || 0),
+ metricLabel: 'agents deployed',
+ color: '#f97316',
+ },
+ {
+ icon: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" style="width:28px;height:28px"><path d="M3 3v18h18"/><path d="M7 16l4-4 4 4 6-6"/><circle cx="21" cy="10" r="1"/></svg>`,
+ title: 'Index Token',
+ desc: '$THREE is the index across the entire agent economy. Every agent token launched, every skill sold, every subscription created compounds into $THREE value.',
+ metric: t.market_cap ? fmtUsd(t.market_cap) : '—',
+ metricLabel: 'market cap',
+ color: '#a78bfa',
+ },
+ ];
+
+ const section = document.createElement('div');
+
+ const header = document.createElement('div');
+ header.style.cssText = 'margin-bottom:16px';
+ header.innerHTML = `
+ <h2 style="font-size:18px;font-weight:700;margin:0 0 4px">Four Utility Pillars</h2>
+ <p style="font-size:13.5px;color:var(--nxt-ink-dim);margin:0">Each mechanism creates real demand from real usage — not speculation.</p>
+ `;
+ section.appendChild(header);
+
+ const grid = document.createElement('div');
+ grid.style.cssText = 'display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:14px';
+
+ pillars.forEach(({ icon, title, desc, metric, metricLabel, color }) => {
+ const card = document.createElement('div');
+ card.className = 'dn-panel';
+ card.style.cssText = `position:relative;overflow:hidden;transition:border-color .2s,box-shadow .2s;cursor:default;`;
+ card.innerHTML = `
+ <div style="position:absolute;top:0;left:0;right:0;height:3px;background:${color};opacity:0.6;border-radius:2px 2px 0 0"></div>
+ <div style="display:flex;align-items:flex-start;gap:12px;margin-bottom:12px;margin-top:6px">
+ <div style="flex-shrink:0;color:${color};opacity:0.9">${icon}</div>
+ <div>
+ <div style="font-size:15px;font-weight:700;margin-bottom:4px">${esc(title)}</div>
+ <div style="font-size:12.5px;color:var(--nxt-ink-dim);line-height:1.5">${esc(desc)}</div>
+ </div>
+ </div>
+ <div style="display:flex;align-items:baseline;gap:8px;padding:10px 12px;background:rgba(255,255,255,0.02);border-radius:8px;border:1px solid var(--nxt-stroke)">
+ <span style="font-size:20px;font-weight:700;font-family:${MONO};letter-spacing:-0.02em">${metric}</span>
+ <span style="font-size:11.5px;color:var(--nxt-ink-fade)">${esc(metricLabel)}</span>
+ </div>
+ `;
+ card.addEventListener('mouseenter', () => {
+ card.style.borderColor = color + '33';
+ card.style.boxShadow = `0 0 20px ${color}11`;
+ });
+ card.addEventListener('mouseleave', () => {
+ card.style.borderColor = '';
+ card.style.boxShadow = '';
+ });
+ grid.appendChild(card);
+ });
+
+ section.appendChild(grid);
+ return section;
+}
+
+// ── Revenue share calculator ──────────────────────────────────────────────────
+
+function renderRevenueShare(stats, revenueData) {
+ const section = document.createElement('div');
+ section.className = 'dn-panel';
+ section.style.cssText = 'position:relative;overflow:hidden;';
+
+ const p = stats?.protocol || {};
+ const rd = revenueData || {};
+ const tokenPrice = rd.token_price || stats?.token?.price_usd || 0;
+ const totalRevenue = rd.platform_revenue_usd || p.total_revenue_usd || 0;
+ const poolPct = rd.revenue_share_pool_pct || p.revenue_share_pool_pct || 10;
+ const revenuePool = totalRevenue * (poolPct / 100);
+ const totalSupply = rd.total_supply || 1_000_000_000;
+ const perToken = totalSupply > 0 ? revenuePool / totalSupply : 0;
+
+ section.innerHTML = `
+ <div style="position:absolute;top:0;left:0;right:0;height:3px;background:linear-gradient(90deg,#60a5fa,#818cf8);opacity:0.6;border-radius:2px 2px 0 0"></div>
+ <div style="display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-bottom:20px;margin-top:4px">
+ <div>
+ <h2 style="font-size:18px;font-weight:700;margin:0 0 4px">Revenue Share Calculator</h2>
+ <p style="font-size:13px;color:var(--nxt-ink-dim);margin:0">See what your $THREE position earns from real platform revenue</p>
+ </div>
+ <div style="display:flex;align-items:center;gap:8px;padding:6px 12px;background:rgba(96,165,250,0.08);border:1px solid rgba(96,165,250,0.15);border-radius:999px">
+ <div style="width:6px;height:6px;border-radius:50%;background:#60a5fa;animation:pulse-dot 2s ease-in-out infinite"></div>
+ <span style="font-size:12px;color:#60a5fa;font-weight:500">${poolPct}% of revenue → holders</span>
+ </div>
+ </div>
+
+ <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:20px;align-items:start" data-slot="calc-grid">
+ <div>
+ <label style="display:block;font-size:12.5px;color:var(--nxt-ink-dim);margin-bottom:8px">Your $THREE holdings</label>
+ <div style="position:relative">
+ <input type="text" data-input="holdings" value="10,000" style="
+ width:100%;box-sizing:border-box;padding:12px 70px 12px 14px;
+ background:rgba(255,255,255,0.04);border:1px solid var(--nxt-stroke);
+ border-radius:var(--nxt-radius-sm);color:var(--nxt-ink);font-size:16px;
+ font-family:${MONO};font-weight:600;outline:none;transition:border-color .15s;
+ " />
+ <span style="position:absolute;right:14px;top:50%;transform:translateY(-50%);font-size:13px;color:var(--nxt-ink-fade);pointer-events:none">$THREE</span>
+ </div>
+ <input type="range" data-input="slider" min="0" max="1000000" value="10000" style="
+ width:100%;margin-top:12px;accent-color:#60a5fa;cursor:pointer;
+ " />
+ <div style="display:flex;justify-content:space-between;font-size:11px;color:var(--nxt-ink-fade);margin-top:4px">
+ <span>0</span>
+ <span>250K</span>
+ <span>500K</span>
+ <span>750K</span>
+ <span>1M</span>
+ </div>
+ </div>
+
+ <div data-slot="calc-results" style="display:flex;flex-direction:column;gap:10px">
+ ${calcResultCards(10000, perToken, tokenPrice, revenuePool, totalSupply)}
+ </div>
+ </div>
+
+ <div style="margin-top:20px;padding:14px 16px;background:rgba(255,255,255,0.02);border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm)">
+ <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:16px">
+ <div>
+ <div style="font-size:11px;color:var(--nxt-ink-fade);margin-bottom:3px">Total Platform Revenue</div>
+ <div style="font-size:14px;font-weight:600;font-family:${MONO}">${fmtUsd(totalRevenue)}</div>
+ </div>
+ <div>
+ <div style="font-size:11px;color:var(--nxt-ink-fade);margin-bottom:3px">Revenue Share Pool</div>
+ <div style="font-size:14px;font-weight:600;font-family:${MONO};color:#60a5fa">${fmtUsd(revenuePool)}</div>
+ </div>
+ <div>
+ <div style="font-size:11px;color:var(--nxt-ink-fade);margin-bottom:3px">Yield Per Token</div>
+ <div style="font-size:14px;font-weight:600;font-family:${MONO}">${fmtUsd(perToken)}</div>
+ </div>
+ <div>
+ <div style="font-size:11px;color:var(--nxt-ink-fade);margin-bottom:3px">Total Supply</div>
+ <div style="font-size:14px;font-weight:600;font-family:${MONO}">${fmtCompact(totalSupply)}</div>
+ </div>
+ </div>
+ </div>
+ `;
+
+ const style = document.createElement('style');
+ style.textContent = `@keyframes pulse-dot{0%,100%{opacity:1}50%{opacity:0.4}}`;
+ section.appendChild(style);
+
+ const input = section.querySelector('[data-input="holdings"]');
+ const slider = section.querySelector('[data-input="slider"]');
+ const results = section.querySelector('[data-slot="calc-results"]');
+
+ function update(raw) {
+ const amount = Math.max(0, parseInt(String(raw).replace(/[^0-9]/g, ''), 10) || 0);
+ results.innerHTML = calcResultCards(amount, perToken, tokenPrice, revenuePool, totalSupply);
+ }
+
+ input.addEventListener('input', (e) => {
+ const raw = e.target.value.replace(/[^0-9]/g, '');
+ const num = parseInt(raw, 10) || 0;
+ e.target.value = num.toLocaleString();
+ slider.value = Math.min(num, 1_000_000);
+ update(num);
+ });
+
+ input.addEventListener('focus', () => {
+ input.style.borderColor = '#60a5fa';
+ });
+ input.addEventListener('blur', () => {
+ input.style.borderColor = '';
+ });
+
+ slider.addEventListener('input', (e) => {
+ const num = parseInt(e.target.value, 10) || 0;
+ input.value = num.toLocaleString();
+ update(num);
+ });
+
+ return section;
+}
+
+function calcResultCards(amount, perToken, tokenPrice, revenuePool, totalSupply) {
+ const shareOfSupply = totalSupply > 0 ? amount / totalSupply : 0;
+ const yourShare = revenuePool * shareOfSupply;
+ const holdingValue = amount * (tokenPrice || 0);
+ const apy = holdingValue > 0 ? (yourShare / holdingValue) * 100 : 0;
+
+ return `
+ <div style="padding:14px 16px;background:rgba(96,165,250,0.06);border:1px solid rgba(96,165,250,0.12);border-radius:var(--nxt-radius-sm)">
+ <div style="font-size:11.5px;color:var(--nxt-ink-dim);margin-bottom:4px">Your Revenue Share</div>
+ <div style="font-size:24px;font-weight:700;font-family:${MONO};color:#60a5fa;letter-spacing:-0.02em">${fmtUsd(yourShare)}</div>
+ <div style="font-size:11.5px;color:var(--nxt-ink-fade);margin-top:2px">${(shareOfSupply * 100).toFixed(6)}% of supply</div>
+ </div>
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
+ <div style="padding:10px 12px;background:rgba(255,255,255,0.02);border:1px solid var(--nxt-stroke);border-radius:8px">
+ <div style="font-size:11px;color:var(--nxt-ink-fade);margin-bottom:3px">Position Value</div>
+ <div style="font-size:15px;font-weight:600;font-family:${MONO}">${fmtUsd(holdingValue)}</div>
+ </div>
+ <div style="padding:10px 12px;background:rgba(255,255,255,0.02);border:1px solid var(--nxt-stroke);border-radius:8px">
+ <div style="font-size:11px;color:var(--nxt-ink-fade);margin-bottom:3px">Effective APY</div>
+ <div style="font-size:15px;font-weight:600;font-family:${MONO};color:${apy > 0 ? 'var(--nxt-success)' : 'var(--nxt-ink-dim)'}">${apy > 0 ? apy.toFixed(1) + '%' : '—'}</div>
+ </div>
+ </div>
+ `;
+}
+
+// ── Deploy burn section ───────────────────────────────────────────────────────
+
+function renderDeployBurn(stats) {
+ const p = stats?.protocol || {};
+ const burnPerAgent = p.agent_deploy_burn || 1000;
+ const totalAgents = p.total_agents || 0;
+ const totalBurned = totalAgents * burnPerAgent;
+ const totalSupply = stats?.token?.supply || 1_000_000_000;
+ const burnPct = totalSupply > 0 ? (totalBurned / totalSupply) * 100 : 0;
+
+ const section = document.createElement('div');
+ section.className = 'dn-panel';
+ section.style.cssText = 'position:relative;overflow:hidden;';
+
+ section.innerHTML = `
+ <div style="position:absolute;top:0;left:0;right:0;height:3px;background:linear-gradient(90deg,#f97316,#ef4444);opacity:0.6;border-radius:2px 2px 0 0"></div>
+ <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-top:4px;margin-bottom:20px">
+ <div>
+ <h2 style="font-size:18px;font-weight:700;margin:0 0 4px">Deploy-to-Burn Mechanism</h2>
+ <p style="font-size:13px;color:var(--nxt-ink-dim);margin:0">Every agent deployed permanently removes $THREE from circulation</p>
+ </div>
+ </div>
+
+ <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:14px;margin-bottom:20px">
+ <div style="padding:16px;background:rgba(249,115,22,0.06);border:1px solid rgba(249,115,22,0.12);border-radius:var(--nxt-radius-sm)">
+ <div style="font-size:11.5px;color:var(--nxt-ink-dim);margin-bottom:4px">Burn Per Deploy</div>
+ <div style="font-size:22px;font-weight:700;font-family:${MONO};color:#f97316">${fmtCompact(burnPerAgent)}</div>
+ <div style="font-size:11.5px;color:var(--nxt-ink-fade);margin-top:2px">$THREE burned permanently</div>
+ </div>
+ <div style="padding:16px;background:rgba(255,255,255,0.02);border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm)">
+ <div style="font-size:11.5px;color:var(--nxt-ink-dim);margin-bottom:4px">Agents Deployed</div>
+ <div style="font-size:22px;font-weight:700;font-family:${MONO}">${fmtCompact(totalAgents)}</div>
+ <div style="font-size:11.5px;color:var(--nxt-ink-fade);margin-top:2px">on three.ws</div>
+ </div>
+ <div style="padding:16px;background:rgba(255,255,255,0.02);border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm)">
+ <div style="font-size:11.5px;color:var(--nxt-ink-dim);margin-bottom:4px">Total Burned</div>
+ <div style="font-size:22px;font-weight:700;font-family:${MONO};color:#ef4444">${fmtCompact(totalBurned)}</div>
+ <div style="font-size:11.5px;color:var(--nxt-ink-fade);margin-top:2px">${burnPct.toFixed(4)}% of supply</div>
+ </div>
+ </div>
+
+ <div style="margin-bottom:8px">
+ <div style="display:flex;justify-content:space-between;font-size:12.5px;margin-bottom:6px">
+ <span style="color:var(--nxt-ink-dim)">Supply burned</span>
+ <span style="font-family:${MONO}">${burnPct.toFixed(4)}%</span>
+ </div>
+ <div style="height:8px;border-radius:4px;background:var(--nxt-stroke);overflow:hidden;position:relative">
+ <div style="height:100%;width:${Math.min(100, burnPct).toFixed(4)}%;background:linear-gradient(90deg,#f97316,#ef4444);transition:width 600ms ease;min-width:${burnPct > 0 ? '2px' : '0'}"></div>
+ </div>
+ <div style="display:flex;justify-content:space-between;font-size:11px;color:var(--nxt-ink-fade);margin-top:4px">
+ <span>0%</span>
+ <span>Circulating supply: ${fmtCompact(totalSupply - totalBurned)}</span>
+ <span>100%</span>
+ </div>
+ </div>
+
+ <div style="margin-top:16px;padding:12px 16px;background:rgba(249,115,22,0.04);border:1px solid rgba(249,115,22,0.08);border-radius:8px;font-size:12.5px;color:var(--nxt-ink-dim);line-height:1.55">
+ Every time a creator deploys a new agent on three.ws, <strong style="color:var(--nxt-ink)">${fmtCompact(burnPerAgent)} $THREE</strong> are burned — permanently removed from circulation. This creates a deflationary flywheel: as the platform grows and more agents are deployed, the total supply of $THREE shrinks, concentrating value among remaining holders.
+ </div>
+ `;
+
+ return section;
+}
+
+// ── Activity feed ─────────────────────────────────────────────────────────────
+
+function renderActivityFeed(activityData) {
+ const events = activityData?.events || [];
+
+ const section = document.createElement('div');
+ section.className = 'dn-panel';
+
+ const sourceLabels = {
+ skill: 'Skill Purchase',
+ subscription: 'Subscription',
+ api: 'API Call',
+ tip: 'Tip',
+ x402: 'x402 Payment',
+ };
+
+ const sourceColors = {
+ skill: '#4ade80',
+ subscription: '#60a5fa',
+ api: '#a78bfa',
+ tip: '#fbbf24',
+ x402: '#f472b6',
+ };
+
+ if (!events.length) {
+ section.innerHTML = `
+ <h2 style="font-size:18px;font-weight:700;margin:0 0 4px">Protocol Activity</h2>
+ <p style="font-size:13px;color:var(--nxt-ink-dim);margin:0 0 20px">Real-time feed of $THREE protocol events</p>
+ <div style="text-align:center;padding:32px 16px">
+ <div style="font-size:32px;margin-bottom:12px;opacity:0.5">&#9678;</div>
+ <p style="font-size:14px;color:var(--nxt-ink-dim);margin:0 0 6px">No protocol activity yet</p>
+ <p style="font-size:12.5px;color:var(--nxt-ink-fade);margin:0;max-width:360px;margin-left:auto;margin-right:auto">
+ Activity will appear here as agents transact, skills are purchased, and revenue flows through the protocol.
+ </p>
+ </div>
+ `;
+ return section;
+ }
+
+ section.innerHTML = `
+ <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px">
+ <div>
+ <h2 style="font-size:18px;font-weight:700;margin:0 0 4px">Protocol Activity</h2>
+ <p style="font-size:13px;color:var(--nxt-ink-dim);margin:0">Real-time feed of $THREE protocol events</p>
+ </div>
+ <div style="font-size:12px;color:var(--nxt-ink-fade)">${events.length} recent events</div>
+ </div>
+ <div data-slot="events" style="display:flex;flex-direction:column;gap:1px;border-radius:var(--nxt-radius-sm);overflow:hidden;border:1px solid var(--nxt-stroke)"></div>
+ `;
+
+ const eventsHost = section.querySelector('[data-slot="events"]');
+
+ events.slice(0, 15).forEach((evt) => {
+ const row = document.createElement('div');
+ const srcColor = sourceColors[evt.type] || 'var(--nxt-ink-dim)';
+ const srcLabel = sourceLabels[evt.type] || evt.type || 'Payment';
+ row.style.cssText = `display:flex;align-items:center;gap:12px;padding:10px 14px;background:rgba(255,255,255,0.015);transition:background .12s;`;
+ row.innerHTML = `
+ <div style="width:8px;height:8px;border-radius:50%;background:${srcColor};flex-shrink:0;opacity:0.8"></div>
+ <div style="flex:1;min-width:0">
+ <div style="font-size:13px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">
+ <span style="color:${srcColor};font-weight:600">${esc(srcLabel)}</span>
+ <span style="color:var(--nxt-ink-fade);margin:0 6px">&middot;</span>
+ <span>${esc(evt.agent_name)}</span>
+ </div>
+ </div>
+ <div style="font-size:13px;font-weight:600;font-family:${MONO};flex-shrink:0">
+ ${evt.amount_cents ? fmtUsd(evt.amount_cents / 100) : '—'}
+ </div>
+ <div style="font-size:11.5px;color:var(--nxt-ink-fade);flex-shrink:0;min-width:60px;text-align:right">
+ ${evt.created_at ? relTime(evt.created_at) : ''}
+ </div>
+ `;
+ row.addEventListener('mouseenter', () => { row.style.background = 'rgba(255,255,255,0.04)'; });
+ row.addEventListener('mouseleave', () => { row.style.background = 'rgba(255,255,255,0.015)'; });
+ eventsHost.appendChild(row);
+ });
+
+ return section;
+}
+
+// ── Token info footer ─────────────────────────────────────────────────────────
+
+function renderTokenInfo() {
+ const section = document.createElement('div');
+ section.className = 'dn-panel';
+ section.style.cssText = 'position:relative;overflow:hidden;';
+
+ section.innerHTML = `
+ <h2 style="font-size:18px;font-weight:700;margin:0 0 16px">Token Info</h2>
+ <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:16px">
+ <div>
+ <table style="width:100%;border-collapse:collapse">
+ <tbody>
+ ${infoRow('Token', '$THREE')}
+ ${infoRow('Network', 'Solana')}
+ ${infoRow('Standard', 'SPL Token')}
+ ${infoRow('Decimals', '6')}
+ </tbody>
+ </table>
+ </div>
+ <div>
+ <table style="width:100%;border-collapse:collapse">
+ <tbody>
+ ${infoRow('Contract', shortAddr(THREE_MINT))}
+ ${infoRow('Launched on', 'Pump.fun')}
+ ${infoRow('Revenue share', '10% of platform revenue')}
+ ${infoRow('Burn per deploy', '1,000 $THREE')}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:16px">
+ <a class="dn-btn" href="https://pump.fun/coin/${THREE_MINT}" target="_blank" rel="noopener" style="font-size:12.5px">
+ View on Pump.fun &#8599;
+ </a>
+ <a class="dn-btn" href="https://solscan.io/token/${THREE_MINT}" target="_blank" rel="noopener" style="font-size:12.5px">
+ Solscan &#8599;
+ </a>
+ <a class="dn-btn" href="https://birdeye.so/token/${THREE_MINT}?chain=solana" target="_blank" rel="noopener" style="font-size:12.5px">
+ Birdeye &#8599;
+ </a>
+ <button class="dn-btn ghost" data-action="copy-ca" style="font-size:12.5px">
+ Copy Contract Address
+ </button>
+ </div>
+ `;
+
+ section.querySelector('[data-action="copy-ca"]').addEventListener('click', async () => {
+ try {
+ await navigator.clipboard.writeText(THREE_MINT);
+ toast('Contract address copied');
+ } catch {
+ toast('Copy failed');
+ }
+ });
+
+ return section;
+}
+
+function infoRow(label, value) {
+ return `<tr>
+ <td style="padding:6px 12px 6px 0;font-size:12.5px;color:var(--nxt-ink-fade);white-space:nowrap">${esc(label)}</td>
+ <td style="padding:6px 0;font-size:13px;font-weight:500;font-family:${MONO}">${value}</td>
+ </tr>`;
+}
+
+function shortAddr(addr) {
+ if (!addr || addr.length < 12) return esc(addr || '');
+ return `<span title="${esc(addr)}" style="cursor:help">${esc(addr.slice(0, 6))}...${esc(addr.slice(-4))}</span>`;
+}
diff --git a/src/walk.js b/src/walk.js
index 5b2c1f7a0..9fd28bba3 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -10,17 +10,25 @@
import {
AmbientLight,
+ BoxGeometry,
Box3,
CanvasTexture,
CircleGeometry,
Clock,
Color,
+ ConeGeometry,
+ CylinderGeometry,
DirectionalLight,
+ DoubleSide,
Group,
HemisphereLight,
+ InstancedMesh,
+ Matrix4,
Mesh,
MeshBasicMaterial,
MeshStandardMaterial,
+ Object3D,
+ OrthographicCamera,
PCFSoftShadowMap,
PerspectiveCamera,
PlaneGeometry,
@@ -28,6 +36,7 @@ import {
Quaternion,
Scene,
ShadowMaterial,
+ SphereGeometry,
Vector3,
WebGLRenderer,
} from 'three';
@@ -287,6 +296,117 @@ const CAM_ZOOM_MIN = 0.6;
const CAM_ZOOM_MAX = 3.2;
let camZoom = 1.0;
+// ── Camera mode system ───────────────────────────────────────────────────
+// Modes: 'follow' (default third-person), 'cinematic' (orbiting), 'firstperson', 'topdown'
+const CAMERA_MODES = ['follow', 'cinematic', 'firstperson', 'topdown'];
+const CAMERA_MODE_LABELS = { follow: 'Follow', cinematic: 'Cinematic', firstperson: 'First Person', topdown: 'Top Down' };
+const CAMERA_MODE_FOV = { follow: 50, cinematic: 35, firstperson: 75, topdown: 50 };
+const CAMERA_MODE_KEY = 'walk:camera-mode';
+let cameraMode = 'follow';
+let cameraModeTransition = 0; // 0 = done, >0 = lerping
+const CAMERA_MODE_TRANSITION_DUR = 0.5; // seconds
+let cameraModeFrom = { pos: new Vector3(), look: new Vector3(), fov: 50 };
+let cameraModeTo = { pos: new Vector3(), look: new Vector3(), fov: 50 };
+let cinematicAngle = 0;
+let cinematicCutTimer = 0;
+const CINEMATIC_ORBIT_SPEED = 0.15; // rad/s
+const CINEMATIC_CUT_INTERVAL = 5; // seconds between auto-cuts
+const CINEMATIC_RADIUS_MULT = 1.8;
+const CINEMATIC_HEIGHT_MULT = 0.7;
+const FP_EYE_HEIGHT_MULT = 0.9; // fraction of avatar height for eye position
+const TOPDOWN_HEIGHT = 18;
+const TOPDOWN_LOOK_DOWN = new Vector3(0, -1, 0.001); // slight offset so lookAt works
+
+// Restore saved camera mode
+try {
+ const saved = localStorage.getItem(CAMERA_MODE_KEY);
+ if (saved && CAMERA_MODES.includes(saved)) cameraMode = saved;
+} catch {}
+
+function setCameraMode(mode) {
+ if (mode === cameraMode) return;
+ // Snapshot current camera state as "from"
+ cameraModeFrom.pos.copy(camera.position);
+ cameraModeFrom.look.copy(camLookCurrent);
+ cameraModeFrom.fov = camera.fov;
+ cameraMode = mode;
+ cameraModeTransition = CAMERA_MODE_TRANSITION_DUR;
+ cameraModeTo.fov = CAMERA_MODE_FOV[mode] || 50;
+ // Hide/show avatar for first person
+ if (avatar) avatar.visible = mode !== 'firstperson';
+ try { localStorage.setItem(CAMERA_MODE_KEY, mode); } catch {}
+ updateCameraModeIndicator();
+}
+
+function cycleCameraMode() {
+ const idx = CAMERA_MODES.indexOf(cameraMode);
+ setCameraMode(CAMERA_MODES[(idx + 1) % CAMERA_MODES.length]);
+ setStatus(`Camera: ${CAMERA_MODE_LABELS[cameraMode]}`);
+}
+
+// Camera mode indicator UI element
+const cameraModeIndicator = (() => {
+ const el = document.createElement('div');
+ el.id = 'walk-camera-mode';
+ el.setAttribute('role', 'status');
+ el.style.cssText = [
+ 'position:fixed', 'z-index:6',
+ 'left:50%', 'top:calc(env(safe-area-inset-top, 0) + 60px)',
+ 'transform:translateX(-50%)',
+ 'background:rgba(17,17,17,0.72)', 'border:1px solid rgba(255,255,255,0.08)',
+ 'border-radius:999px', 'padding:5px 14px',
+ 'font-size:11px', 'font-weight:500', 'color:rgba(255,255,255,0.7)',
+ 'backdrop-filter:blur(10px)', '-webkit-backdrop-filter:blur(10px)',
+ 'pointer-events:none',
+ 'opacity:0', 'transition:opacity 0.25s ease',
+ ].join(';');
+ document.body.appendChild(el);
+ return el;
+})();
+let cameraModeIndicatorTimer = 0;
+
+function updateCameraModeIndicator() {
+ cameraModeIndicator.textContent = CAMERA_MODE_LABELS[cameraMode];
+ cameraModeIndicator.style.opacity = '1';
+ clearTimeout(cameraModeIndicatorTimer);
+ cameraModeIndicatorTimer = setTimeout(() => {
+ cameraModeIndicator.style.opacity = '0';
+ }, 2000);
+}
+
+// Compute desired camera position/look for each mode
+function computeCameraForMode(mode, avatarPos, avatarHeight) {
+ const pos = new Vector3();
+ const look = new Vector3();
+ if (mode === 'follow') {
+ const offset = CAM_OFFSET.clone().multiplyScalar(camZoom);
+ offset.applyAxisAngle(new Vector3(1, 0, 0), -cameraPitch);
+ offset.applyAxisAngle(upY, cameraYaw);
+ pos.copy(avatarPos).add(offset);
+ look.copy(avatarPos).add(CAM_LOOK_OFFSET);
+ } else if (mode === 'cinematic') {
+ const r = (avatarHeight || 1.8) * CINEMATIC_RADIUS_MULT * camZoom;
+ const h = (avatarHeight || 1.8) * CINEMATIC_HEIGHT_MULT;
+ pos.set(
+ avatarPos.x + Math.cos(cinematicAngle) * r,
+ avatarPos.y + h + 0.8,
+ avatarPos.z + Math.sin(cinematicAngle) * r,
+ );
+ look.copy(avatarPos).add(CAM_LOOK_OFFSET);
+ } else if (mode === 'firstperson') {
+ const eyeH = (avatarHeight || 1.8) * FP_EYE_HEIGHT_MULT;
+ pos.set(avatarPos.x, avatarPos.y + eyeH, avatarPos.z);
+ // Look in the direction the avatar is facing
+ const fpForward = new Vector3(Math.sin(avatarYaw), 0, Math.cos(avatarYaw));
+ look.copy(pos).add(fpForward.multiplyScalar(5));
+ look.y -= 0.15; // slight downward gaze
+ } else if (mode === 'topdown') {
+ pos.set(avatarPos.x, avatarPos.y + TOPDOWN_HEIGHT, avatarPos.z + 0.01);
+ look.copy(avatarPos);
+ }
+ return { pos, look };
+}
+
// Place the camera at its starting pose immediately so frame 0 isn't blank.
function applyCameraImmediate() {
const offset = CAM_OFFSET.clone().multiplyScalar(camZoom);
@@ -403,17 +523,25 @@ const helpOverlay = (() => {
'transition:opacity 0.18s',
].join(';');
el.innerHTML = `
- <div style="max-width:380px;width:90%;background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12);border-radius:16px;padding:28px 32px">
+ <div style="max-width:420px;width:90%;background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.12);border-radius:16px;padding:28px 32px">
<h2 style="margin:0 0 20px;font-size:18px;font-weight:600;letter-spacing:-0.3px">Controls</h2>
<table style="width:100%;border-collapse:collapse;font-size:14px;line-height:2">
<tr><td style="color:#aaa;padding-right:16px">W A S D / Arrows</td><td>Move</td></tr>
<tr><td style="color:#aaa;padding-right:16px">Shift</td><td>Run</td></tr>
<tr><td style="color:#aaa;padding-right:16px">Space</td><td>Jump</td></tr>
- <tr><td style="color:#aaa;padding-right:16px">Q / E</td><td>Snap turn 45°</td></tr>
- <tr><td style="color:#aaa;padding-right:16px">Mouse drag / click</td><td>Orbit camera</td></tr>
+ <tr><td style="color:#aaa;padding-right:16px">Q / E</td><td>Snap turn 45&deg;</td></tr>
+ <tr><td style="color:#aaa;padding-right:16px">C</td><td>Cycle camera mode</td></tr>
+ <tr><td style="color:#aaa;padding-right:16px">G</td><td>Gesture palette</td></tr>
+ <tr><td style="color:#aaa;padding-right:16px">1 &ndash; 9</td><td>Quick gesture</td></tr>
+ <tr><td style="color:#aaa;padding-right:16px">T / Enter</td><td>Chat</td></tr>
+ <tr><td style="color:#aaa;padding-right:16px">V</td><td>Cycle environment</td></tr>
+ <tr><td style="color:#aaa;padding-right:16px">P</td><td>Screenshot</td></tr>
+ <tr><td style="color:#aaa;padding-right:16px">R</td><td>Toggle GIF recording</td></tr>
+ <tr><td style="color:#aaa;padding-right:16px">M</td><td>Toggle minimap</td></tr>
+ <tr><td style="color:#aaa;padding-right:16px">H / ?</td><td>Toggle this overlay</td></tr>
+ <tr><td style="color:#aaa;padding-right:16px">Mouse drag</td><td>Orbit camera</td></tr>
<tr><td style="color:#aaa;padding-right:16px">Scroll wheel</td><td>Zoom in / out</td></tr>
- <tr><td style="color:#aaa;padding-right:16px">?</td><td>Toggle this overlay</td></tr>
- <tr><td style="color:#aaa;padding-right:16px">Esc</td><td>Release pointer lock</td></tr>
+ <tr><td style="color:#aaa;padding-right:16px">Esc</td><td>Close overlay / release pointer</td></tr>
</table>
<p style="margin:20px 0 0;font-size:12px;color:#666">Click the canvas to lock the mouse for first-person look.</p>
</div>`;
@@ -443,10 +571,33 @@ window.addEventListener('keydown', (e) => {
case 'ShiftLeft': case 'ShiftRight': input.keys.run = true; break;
case 'Space': e.preventDefault(); triggerJump(); break;
case 'KeyQ': cameraYaw += SNAP_TURN_RAD; break;
+ // 'E' kept for snap turn — environment cycles via 'V'
case 'KeyE': cameraYaw -= SNAP_TURN_RAD; break;
+ case 'KeyC': e.preventDefault(); cycleCameraMode(); break;
+ case 'KeyG': e.preventDefault(); toggleGesturePalette(); break;
+ case 'KeyT': e.preventDefault(); focusChat(); break;
+ case 'KeyV': e.preventDefault(); cycleEnvironment(); break;
+ case 'KeyP': e.preventDefault(); takeScreenshot(); break;
+ case 'KeyR': e.preventDefault(); toggleGifRecording(); break;
+ case 'KeyM': e.preventDefault(); toggleMinimap(); break;
+ case 'KeyH': e.preventDefault(); toggleHelp(); break;
case 'Slash':
if (e.shiftKey) { e.preventDefault(); toggleHelp(); }
break;
+ case 'Escape':
+ if (helpVisible) { toggleHelp(); break; }
+ if (gesturePaletteVisible) { hideGesturePalette(); break; }
+ break;
+ // Number keys 1-9 for quick gestures
+ case 'Digit1': e.preventDefault(); triggerQuickGesture(0); break;
+ case 'Digit2': e.preventDefault(); triggerQuickGesture(1); break;
+ case 'Digit3': e.preventDefault(); triggerQuickGesture(2); break;
+ case 'Digit4': e.preventDefault(); triggerQuickGesture(3); break;
+ case 'Digit5': e.preventDefault(); triggerQuickGesture(4); break;
+ case 'Digit6': e.preventDefault(); triggerQuickGesture(5); break;
+ case 'Digit7': e.preventDefault(); triggerQuickGesture(6); break;
+ case 'Digit8': e.preventDefault(); triggerQuickGesture(7); break;
+ case 'Digit9': e.preventDefault(); triggerQuickGesture(8); break;
default: return;
}
});
@@ -1103,11 +1254,9 @@ function tick() {
avatarLean += (targetLean - avatarLean) * LEAN_LERP;
if (avatar) avatar.rotation.x = avatarLean;
- // 2. Update camera — frozen in AR mode, follow-rig otherwise.
+ // 2. Update camera — frozen in AR mode, camera-mode system otherwise.
if (arFrozenCamPos && arFrozenCamLook) {
// Clamp the avatar so it can't walk through (or past) the frozen camera.
- // We project (avatar - camera) onto the ground-plane camera-forward axis
- // and push the avatar back to a minimum forward distance.
_camFwdTmp.subVectors(arFrozenCamLook, arFrozenCamPos);
_camFwdTmp.y = 0;
if (_camFwdTmp.lengthSq() > 1e-6) {
@@ -1124,20 +1273,44 @@ function tick() {
camLookCurrent.copy(arFrozenCamLook);
camera.lookAt(camLookCurrent);
} else {
- const offset = CAM_OFFSET.clone().multiplyScalar(camZoom);
- offset.applyAxisAngle(new Vector3(1, 0, 0), -cameraPitch);
- offset.applyAxisAngle(upY, cameraYaw);
- camDesired.copy(avatarRig.position).add(offset);
- camera.position.lerp(camDesired, CAM_LERP);
+ // Cinematic mode auto-orbit
+ if (cameraMode === 'cinematic') {
+ cinematicAngle += CINEMATIC_ORBIT_SPEED * dt;
+ cinematicCutTimer += dt;
+ if (cinematicCutTimer > CINEMATIC_CUT_INTERVAL) {
+ cinematicCutTimer = 0;
+ cinematicAngle += Math.PI * 0.6 + Math.random() * Math.PI * 0.8;
+ }
+ }
- camLookTarget.copy(avatarRig.position).add(CAM_LOOK_OFFSET);
- camLookCurrent.lerp(camLookTarget, CAM_LERP);
- camera.lookAt(camLookCurrent);
+ const avatarHeight = avatar ? new Box3().setFromObject(avatar).max.y - new Box3().setFromObject(avatar).min.y : 1.8;
+ const desired = computeCameraForMode(cameraMode, avatarRig.position, avatarHeight);
+
+ // Camera mode transition (smooth lerp)
+ if (cameraModeTransition > 0) {
+ cameraModeTransition = Math.max(0, cameraModeTransition - dt);
+ const t = 1 - (cameraModeTransition / CAMERA_MODE_TRANSITION_DUR);
+ const ease = t * t * (3 - 2 * t); // smoothstep
+ camera.position.lerpVectors(cameraModeFrom.pos, desired.pos, ease);
+ camLookCurrent.lerpVectors(cameraModeFrom.look, desired.look, ease);
+ camera.fov = cameraModeFrom.fov + (cameraModeTo.fov - cameraModeFrom.fov) * ease;
+ camera.updateProjectionMatrix();
+ camera.lookAt(camLookCurrent);
+ } else {
+ // Normal per-mode camera following
+ const lerpFactor = cameraMode === 'firstperson' ? 0.2 : CAM_LERP;
+ camera.position.lerp(desired.pos, lerpFactor);
+ camLookCurrent.lerp(desired.look, lerpFactor);
+ const targetFov = CAMERA_MODE_FOV[cameraMode] || 50;
+ if (Math.abs(camera.fov - targetFov) > 0.1) {
+ camera.fov += (targetFov - camera.fov) * 0.1;
+ camera.updateProjectionMatrix();
+ }
+ camera.lookAt(camLookCurrent);
+ }
}
- // AR depth: track sun + blob shadow to the avatar each frame so the
- // grounding shadow always lands under the feet, and estimate real-world
- // lighting from the camera feed.
+ // AR depth: track sun + blob shadow to the avatar each frame
if (arActive) {
const ap = avatarRig.position;
sun.position.set(ap.x + 4, ap.y + 8, ap.z + 6);
@@ -1163,6 +1336,12 @@ function tick() {
}
updateRemotePlayers(dt);
+ // 5. Update speech bubbles (3D -> 2D projection)
+ updateSpeechBubbles();
+
+ // 6. Update minimap
+ updateMinimapFrame();
+
renderer.render(scene, camera);
requestAnimationFrame(tick);
}
@@ -1418,11 +1597,777 @@ function startNet() {
net.connect();
}
+// ── Gesture palette (radial menu) ────────────────────────────────────────
+// G key opens a radial menu of gesture shortcuts. Number keys 1-9 trigger
+// gestures directly from the EMOTE_CLIPS list.
+let gesturePaletteVisible = false;
+const gesturePaletteEl = (() => {
+ const el = document.createElement('div');
+ el.id = 'walk-gesture-palette';
+ el.setAttribute('aria-hidden', 'true');
+ el.style.cssText = [
+ 'position:fixed', 'z-index:9998',
+ 'left:50%', 'top:50%', 'transform:translate(-50%,-50%)',
+ 'width:280px', 'height:280px',
+ 'border-radius:50%',
+ 'background:rgba(10,10,10,0.82)',
+ 'border:1px solid rgba(255,255,255,0.1)',
+ 'backdrop-filter:blur(16px)', '-webkit-backdrop-filter:blur(16px)',
+ 'display:none', 'opacity:0',
+ 'transition:opacity 0.18s ease, transform 0.18s ease',
+ 'pointer-events:none',
+ ].join(';');
+ document.body.appendChild(el);
+ return el;
+})();
+
+function buildGesturePalette() {
+ gesturePaletteEl.innerHTML = '';
+ const items = EMOTE_CLIPS;
+ const count = items.length;
+ const radius = 100;
+ const centerX = 140;
+ const centerY = 140;
+ items.forEach((emote, i) => {
+ const angle = (i / count) * Math.PI * 2 - Math.PI / 2;
+ const x = centerX + Math.cos(angle) * radius - 24;
+ const y = centerY + Math.sin(angle) * radius - 24;
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.style.cssText = [
+ 'position:absolute', `left:${x}px`, `top:${y}px`,
+ 'width:48px', 'height:48px', 'border-radius:50%',
+ 'background:rgba(255,255,255,0.08)', 'border:1px solid rgba(255,255,255,0.15)',
+ 'color:#fff', 'font-size:22px', 'cursor:pointer',
+ 'display:flex', 'align-items:center', 'justify-content:center',
+ 'transition:transform 0.1s, background 0.1s',
+ ].join(';');
+ btn.title = `${emote.label} [${i + 1}]`;
+ btn.setAttribute('aria-label', emote.label);
+ btn.textContent = emote.icon;
+ btn.addEventListener('click', () => {
+ playEmote(emote.name);
+ hideGesturePalette();
+ });
+ btn.addEventListener('mouseenter', () => { btn.style.transform = 'scale(1.18)'; btn.style.background = 'rgba(255,255,255,0.18)'; });
+ btn.addEventListener('mouseleave', () => { btn.style.transform = ''; btn.style.background = 'rgba(255,255,255,0.08)'; });
+ gesturePaletteEl.appendChild(btn);
+ });
+ // Center label
+ const label = document.createElement('div');
+ label.style.cssText = 'position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);font-size:11px;color:rgba(255,255,255,0.5);text-align:center;pointer-events:none;line-height:1.4';
+ label.textContent = 'Gestures';
+ gesturePaletteEl.appendChild(label);
+}
+
+function showGesturePalette() {
+ if (!gesturePaletteEl.children.length) buildGesturePalette();
+ gesturePaletteVisible = true;
+ gesturePaletteEl.style.display = 'block';
+ gesturePaletteEl.style.pointerEvents = 'auto';
+ gesturePaletteEl.setAttribute('aria-hidden', 'false');
+ requestAnimationFrame(() => {
+ gesturePaletteEl.style.opacity = '1';
+ gesturePaletteEl.style.transform = 'translate(-50%,-50%) scale(1)';
+ });
+}
+
+function hideGesturePalette() {
+ gesturePaletteVisible = false;
+ gesturePaletteEl.style.opacity = '0';
+ gesturePaletteEl.style.transform = 'translate(-50%,-50%) scale(0.85)';
+ gesturePaletteEl.style.pointerEvents = 'none';
+ gesturePaletteEl.setAttribute('aria-hidden', 'true');
+ setTimeout(() => {
+ if (!gesturePaletteVisible) gesturePaletteEl.style.display = 'none';
+ }, 200);
+}
+
+function toggleGesturePalette() {
+ if (gesturePaletteVisible) hideGesturePalette();
+ else showGesturePalette();
+}
+
+function triggerQuickGesture(index) {
+ if (index < 0 || index >= EMOTE_CLIPS.length) return;
+ const emote = EMOTE_CLIPS[index];
+ playEmote(emote.name);
+ setStatus(`Gesture: ${emote.label}`);
+}
+
+// Close gesture palette on click outside
+gesturePaletteEl.addEventListener('click', (e) => {
+ if (e.target === gesturePaletteEl) hideGesturePalette();
+});
+
+// ── Chat focus helper ────────────────────────────────────────────────────
+function focusChat() {
+ const chatInput = document.getElementById('walk-chat-input');
+ if (chatInput) chatInput.focus();
+}
+
+// ── Speech bubbles (3D→2D projected CSS overlays) ────────────────────────
+// Floating text above the local avatar and remote players. Messages appear
+// as styled DOM elements positioned each frame by projecting the avatar's
+// head position from world space to screen space.
+const speechBubbles = new Map(); // key: 'local' or sessionId → { el, timer, birth }
+const SPEECH_BUBBLE_DURATION = 5000;
+const SPEECH_BUBBLE_MAX_LEN = 140;
+
+function createSpeechBubbleEl() {
+ const wrap = document.createElement('div');
+ wrap.className = 'walk-speech-bubble';
+ wrap.style.cssText = [
+ 'position:fixed', 'z-index:3', 'pointer-events:none',
+ 'max-width:240px', 'padding:8px 14px',
+ 'background:rgba(10,10,10,0.82)', 'color:#fafafa',
+ 'border:1px solid rgba(255,255,255,0.12)',
+ 'border-radius:14px',
+ 'backdrop-filter:blur(8px)', '-webkit-backdrop-filter:blur(8px)',
+ 'font-size:12px', 'line-height:1.45',
+ 'word-break:break-word', 'white-space:pre-wrap',
+ 'transform:translate(-50%,-100%) scale(0.7)',
+ 'opacity:0',
+ 'transition:opacity 0.25s ease, transform 0.25s ease',
+ 'will-change:transform,opacity',
+ ].join(';');
+ // Arrow pointer
+ const arrow = document.createElement('div');
+ arrow.style.cssText = [
+ 'position:absolute', 'bottom:-6px', 'left:50%',
+ 'transform:translateX(-50%)',
+ 'width:0', 'height:0',
+ 'border-left:6px solid transparent', 'border-right:6px solid transparent',
+ 'border-top:6px solid rgba(10,10,10,0.82)',
+ ].join(';');
+ wrap.appendChild(arrow);
+ document.body.appendChild(wrap);
+ // Animate in
+ requestAnimationFrame(() => {
+ wrap.style.opacity = '1';
+ wrap.style.transform = 'translate(-50%,-100%) scale(1)';
+ });
+ return wrap;
+}
+
+function showSpeechBubbleFor(key, text) {
+ // Sanitize
+ const clean = text.replace(/[<>&"']/g, c => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&#39;' })[c]).slice(0, SPEECH_BUBBLE_MAX_LEN);
+ // Remove existing bubble for this key
+ const existing = speechBubbles.get(key);
+ if (existing) {
+ clearTimeout(existing.timer);
+ existing.el.remove();
+ speechBubbles.delete(key);
+ }
+ const el = createSpeechBubbleEl();
+ // Insert text before the arrow child
+ const textNode = document.createElement('span');
+ textNode.innerHTML = clean;
+ el.insertBefore(textNode, el.firstChild);
+ const timer = setTimeout(() => {
+ el.style.opacity = '0';
+ el.style.transform = 'translate(-50%,-100%) scale(0.85)';
+ setTimeout(() => {
+ el.remove();
+ speechBubbles.delete(key);
+ }, 300);
+ }, SPEECH_BUBBLE_DURATION);
+ speechBubbles.set(key, { el, timer, birth: performance.now() });
+}
+
+function updateSpeechBubbles() {
+ const w = renderer.domElement.clientWidth;
+ const h = renderer.domElement.clientHeight;
+ const headV = _tmpV3;
+ // Local avatar bubble
+ const localBubble = speechBubbles.get('local');
+ if (localBubble && avatar) {
+ headV.set(avatarRig.position.x, avatarRig.position.y + 2.2, avatarRig.position.z);
+ headV.project(camera);
+ const onScreen = headV.z > -1 && headV.z < 1;
+ if (onScreen) {
+ const sx = (headV.x * 0.5 + 0.5) * w;
+ const sy = (-headV.y * 0.5 + 0.5) * h;
+ localBubble.el.style.left = sx + 'px';
+ localBubble.el.style.top = (sy - 10) + 'px';
+ localBubble.el.style.display = '';
+ } else {
+ localBubble.el.style.display = 'none';
+ }
+ }
+ // Remote player bubbles
+ for (const [sid, rp] of remotePlayers) {
+ const bubble = speechBubbles.get(sid);
+ if (!bubble) continue;
+ headV.set(rp.rig.position.x, rp.rig.position.y + 2.2, rp.rig.position.z);
+ headV.project(camera);
+ const onScreen = headV.z > -1 && headV.z < 1;
+ if (onScreen) {
+ const sx = (headV.x * 0.5 + 0.5) * w;
+ const sy = (-headV.y * 0.5 + 0.5) * h;
+ bubble.el.style.left = sx + 'px';
+ bubble.el.style.top = (sy - 10) + 'px';
+ bubble.el.style.display = '';
+ } else {
+ bubble.el.style.display = 'none';
+ }
+ }
+}
+
+// ── Environment selector ─────────────────────────────────────────────────
+// Four procedural environments using simple geometries. No external GLBs.
+const ENV_KEY = 'walk:environment';
+const ENVIRONMENTS = [
+ { name: 'default', label: 'Studio', groundColor: 0x202833, skyTop: '#1a2538', skyBot: '#0a0a0a', ambientColor: 0xffffff, ambientIntensity: 0.55, sunIntensity: 1.4, hemiSky: 0xbcd6ff },
+ { name: 'park', label: 'Park', groundColor: 0x2d5a27, skyTop: '#4a90c4', skyBot: '#87ceeb', ambientColor: 0xfffbe6, ambientIntensity: 0.7, sunIntensity: 1.6, hemiSky: 0xa8d8ea },
+ { name: 'city', label: 'City', groundColor: 0x3a3a3a, skyTop: '#1a1a2e', skyBot: '#16213e', ambientColor: 0xd4d4ff, ambientIntensity: 0.4, sunIntensity: 0.9, hemiSky: 0x8888aa },
+ { name: 'beach', label: 'Beach', groundColor: 0xc2b280, skyTop: '#3b7dd8', skyBot: '#87ceeb', ambientColor: 0xfff8e7, ambientIntensity: 0.75, sunIntensity: 1.8, hemiSky: 0xccddff },
+];
+
+let currentEnvIndex = 0;
+const envPropsGroup = new Group();
+scene.add(envPropsGroup);
+
+// Restore saved environment
+try {
+ const savedEnv = localStorage.getItem(ENV_KEY);
+ if (savedEnv) {
+ const idx = ENVIRONMENTS.findIndex(e => e.name === savedEnv);
+ if (idx >= 0) currentEnvIndex = idx;
+ }
+} catch {}
+
+function applyEnvironment(index) {
+ const env = ENVIRONMENTS[index];
+ if (!env) return;
+ currentEnvIndex = index;
+ // Ground color
+ groundOpaque.material.color.setHex(env.groundColor);
+ // Stage background gradient
+ if (stage) stage.style.background = `radial-gradient(80% 60% at 50% 30%, ${env.skyTop} 0%, ${env.skyBot} 70%) ${env.skyBot}`;
+ // Lighting
+ ambientLight.color.setHex(env.ambientColor);
+ ambientLight.intensity = env.ambientIntensity;
+ sun.intensity = env.sunIntensity;
+ hemi.color.setHex(env.hemiSky);
+ // Clear old props
+ while (envPropsGroup.children.length > 0) {
+ const child = envPropsGroup.children[0];
+ envPropsGroup.remove(child);
+ if (child.geometry) child.geometry.dispose();
+ if (child.material) child.material.dispose();
+ // InstancedMesh
+ if (child.isInstancedMesh) {
+ child.geometry.dispose();
+ child.material.dispose();
+ }
+ }
+ // Add environment props
+ if (env.name === 'park') buildParkProps();
+ else if (env.name === 'city') buildCityProps();
+ else if (env.name === 'beach') buildBeachProps();
+ try { localStorage.setItem(ENV_KEY, env.name); } catch {}
+ updateEnvIndicator();
+}
+
+function buildParkProps() {
+ // Trees as instanced cones + cylinders
+ const trunkGeo = new CylinderGeometry(0.08, 0.12, 0.8, 6);
+ const trunkMat = new MeshStandardMaterial({ color: 0x5c3a1e, roughness: 0.9 });
+ const foliageGeo = new ConeGeometry(0.6, 1.4, 6);
+ const foliageMat = new MeshStandardMaterial({ color: 0x2d7a2d, roughness: 0.85 });
+ const dummy = new Object3D();
+ const treeCount = 18;
+ const trunkMesh = new InstancedMesh(trunkGeo, trunkMat, treeCount);
+ const foliageMesh = new InstancedMesh(foliageGeo, foliageMat, treeCount);
+ trunkMesh.castShadow = true;
+ foliageMesh.castShadow = true;
+ for (let i = 0; i < treeCount; i++) {
+ const angle = (i / treeCount) * Math.PI * 2 + Math.random() * 0.3;
+ const r = 5 + Math.random() * 5.5;
+ const x = Math.cos(angle) * r;
+ const z = Math.sin(angle) * r;
+ const scale = 0.8 + Math.random() * 0.6;
+ dummy.position.set(x, 0.4 * scale, z);
+ dummy.scale.set(scale, scale, scale);
+ dummy.updateMatrix();
+ trunkMesh.setMatrixAt(i, dummy.matrix);
+ dummy.position.y = 1.1 * scale;
+ dummy.updateMatrix();
+ foliageMesh.setMatrixAt(i, dummy.matrix);
+ }
+ envPropsGroup.add(trunkMesh);
+ envPropsGroup.add(foliageMesh);
+}
+
+function buildCityProps() {
+ // Buildings as instanced boxes along the perimeter
+ const buildingGeo = new BoxGeometry(1, 1, 1);
+ const buildingMat = new MeshStandardMaterial({ color: 0x2a2a3a, roughness: 0.7, metalness: 0.3 });
+ const dummy = new Object3D();
+ const count = 24;
+ const mesh = new InstancedMesh(buildingGeo, buildingMat, count);
+ mesh.castShadow = true;
+ mesh.receiveShadow = true;
+ for (let i = 0; i < count; i++) {
+ const angle = (i / count) * Math.PI * 2 + Math.random() * 0.15;
+ const r = 8 + Math.random() * 3;
+ const x = Math.cos(angle) * r;
+ const z = Math.sin(angle) * r;
+ const h = 1.5 + Math.random() * 4;
+ const w = 0.8 + Math.random() * 1.2;
+ const d = 0.8 + Math.random() * 1.2;
+ dummy.position.set(x, h / 2, z);
+ dummy.scale.set(w, h, d);
+ dummy.rotation.y = Math.random() * Math.PI;
+ dummy.updateMatrix();
+ mesh.setMatrixAt(i, dummy.matrix);
+ }
+ envPropsGroup.add(mesh);
+ // Grid lines on ground
+ const gridMat = new MeshBasicMaterial({ color: 0x555577, transparent: true, opacity: 0.15, side: DoubleSide });
+ for (let i = -10; i <= 10; i += 2) {
+ const lineH = new Mesh(new PlaneGeometry(24, 0.02), gridMat);
+ lineH.rotation.x = -Math.PI / 2;
+ lineH.position.set(0, 0.005, i);
+ envPropsGroup.add(lineH);
+ const lineV = new Mesh(new PlaneGeometry(0.02, 24), gridMat);
+ lineV.rotation.x = -Math.PI / 2;
+ lineV.position.set(i, 0.005, 0);
+ envPropsGroup.add(lineV);
+ }
+}
+
+function buildBeachProps() {
+ // Wave plane
+ const waveMat = new MeshStandardMaterial({ color: 0x2196f3, roughness: 0.2, metalness: 0.1, transparent: true, opacity: 0.6 });
+ const wave = new Mesh(new PlaneGeometry(30, 14, 1, 1), waveMat);
+ wave.rotation.x = -Math.PI / 2;
+ wave.position.set(0, 0.01, -10);
+ envPropsGroup.add(wave);
+ // Palm trees
+ const trunkGeo = new CylinderGeometry(0.06, 0.1, 2.5, 6);
+ const trunkMat = new MeshStandardMaterial({ color: 0x8b6914, roughness: 0.9 });
+ const leafGeo = new ConeGeometry(0.9, 0.5, 5);
+ const leafMat = new MeshStandardMaterial({ color: 0x228b22, roughness: 0.8 });
+ const dummy = new Object3D();
+ const palmCount = 8;
+ const palmTrunks = new InstancedMesh(trunkGeo, trunkMat, palmCount);
+ const palmLeaves = new InstancedMesh(leafGeo, leafMat, palmCount);
+ palmTrunks.castShadow = true;
+ palmLeaves.castShadow = true;
+ for (let i = 0; i < palmCount; i++) {
+ const angle = (i / palmCount) * Math.PI + Math.PI * 0.5 + Math.random() * 0.3;
+ const r = 6 + Math.random() * 4;
+ const x = Math.cos(angle) * r;
+ const z = Math.sin(angle) * r;
+ dummy.position.set(x, 1.25, z);
+ dummy.rotation.set(Math.random() * 0.15, 0, Math.random() * 0.15);
+ dummy.scale.setScalar(1);
+ dummy.updateMatrix();
+ palmTrunks.setMatrixAt(i, dummy.matrix);
+ dummy.position.y = 2.6;
+ dummy.updateMatrix();
+ palmLeaves.setMatrixAt(i, dummy.matrix);
+ }
+ envPropsGroup.add(palmTrunks);
+ envPropsGroup.add(palmLeaves);
+}
+
+// Environment indicator
+const envIndicator = (() => {
+ const el = document.createElement('div');
+ el.id = 'walk-env-indicator';
+ el.setAttribute('role', 'status');
+ el.style.cssText = [
+ 'position:fixed', 'z-index:6',
+ 'left:16px', 'top:calc(env(safe-area-inset-top, 0) + 60px)',
+ 'background:rgba(17,17,17,0.72)', 'border:1px solid rgba(255,255,255,0.08)',
+ 'border-radius:999px', 'padding:5px 14px',
+ 'font-size:11px', 'font-weight:500', 'color:rgba(255,255,255,0.7)',
+ 'backdrop-filter:blur(10px)', '-webkit-backdrop-filter:blur(10px)',
+ 'pointer-events:none',
+ 'opacity:0', 'transition:opacity 0.25s ease',
+ ].join(';');
+ document.body.appendChild(el);
+ return el;
+})();
+let envIndicatorTimer = 0;
+
+function updateEnvIndicator() {
+ const env = ENVIRONMENTS[currentEnvIndex];
+ envIndicator.textContent = `Scene: ${env.label}`;
+ envIndicator.style.opacity = '1';
+ clearTimeout(envIndicatorTimer);
+ envIndicatorTimer = setTimeout(() => {
+ envIndicator.style.opacity = '0';
+ }, 2000);
+}
+
+function cycleEnvironment() {
+ const next = (currentEnvIndex + 1) % ENVIRONMENTS.length;
+ applyEnvironment(next);
+ setStatus(`Environment: ${ENVIRONMENTS[next].label}`);
+}
+
+// ── Screenshot capture ───────────────────────────────────────────────────
+function takeScreenshot() {
+ renderer.render(scene, camera); // ensure latest frame
+ const dataUrl = renderer.domElement.toDataURL('image/png');
+ const a = document.createElement('a');
+ a.href = dataUrl;
+ a.download = `three-ws-walk-${Date.now()}.png`;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setStatus('Screenshot saved');
+}
+
+// ── GIF/frame recording ─────────────────────────────────────────────────
+// Captures canvas frames at intervals and encodes as an animated GIF
+// using a minimal inline LZW-based GIF encoder (no external deps).
+let gifRecording = false;
+let gifFrames = [];
+let gifInterval = null;
+const GIF_FRAME_INTERVAL = 100; // ms between captures
+const GIF_MAX_FRAMES = 100; // 10 seconds max
+
+// Recording indicator
+const gifIndicator = (() => {
+ const el = document.createElement('div');
+ el.id = 'walk-gif-indicator';
+ el.style.cssText = [
+ 'position:fixed', 'z-index:8',
+ 'right:16px', 'top:calc(env(safe-area-inset-top, 0) + 60px)',
+ 'background:rgba(248,113,113,0.92)', 'color:#fff',
+ 'border:1px solid rgba(255,255,255,0.25)',
+ 'border-radius:999px', 'padding:6px 14px',
+ 'font-size:12px', 'font-weight:600',
+ 'display:none', 'align-items:center', 'gap:8px',
+ 'pointer-events:none',
+ 'backdrop-filter:blur(6px)', '-webkit-backdrop-filter:blur(6px)',
+ ].join(';');
+ const dot = document.createElement('span');
+ dot.style.cssText = 'width:8px;height:8px;border-radius:50%;background:#fff;animation:walk-rec-pulse 0.9s infinite';
+ el.appendChild(dot);
+ const label = document.createElement('span');
+ label.textContent = 'REC';
+ el.appendChild(label);
+ document.body.appendChild(el);
+ return el;
+})();
+
+function startGifRecording() {
+ gifRecording = true;
+ gifFrames = [];
+ gifIndicator.style.display = 'inline-flex';
+ setStatus('Recording started — press R to stop');
+
+ gifInterval = setInterval(() => {
+ if (!gifRecording) return;
+ if (gifFrames.length >= GIF_MAX_FRAMES) {
+ stopGifRecording();
+ return;
+ }
+ // Capture frame as PNG data URL
+ renderer.render(scene, camera);
+ const dataUrl = renderer.domElement.toDataURL('image/png');
+ gifFrames.push(dataUrl);
+ // Update indicator
+ const secs = ((gifFrames.length * GIF_FRAME_INTERVAL) / 1000).toFixed(1);
+ gifIndicator.lastChild.textContent = `REC ${secs}s`;
+ }, GIF_FRAME_INTERVAL);
+}
+
+function stopGifRecording() {
+ gifRecording = false;
+ if (gifInterval) { clearInterval(gifInterval); gifInterval = null; }
+ gifIndicator.style.display = 'none';
+
+ if (gifFrames.length === 0) {
+ setStatus('No frames captured');
+ return;
+ }
+ setStatus(`Encoding ${gifFrames.length} frames...`);
+ // Since building a full GIF encoder inline is complex, we export as
+ // individual PNG frames bundled in a webm video via MediaRecorder,
+ // or as a simple PNG download of the last frame. For a proper
+ // animated output, use canvas.captureStream + MediaRecorder.
+ exportFramesAsVideo(gifFrames);
+}
+
+async function exportFramesAsVideo(frames) {
+ // Re-render frames onto a canvas and use MediaRecorder for a real video file
+ if (frames.length < 2) {
+ // Single frame — just download as PNG
+ const a = document.createElement('a');
+ a.href = frames[0];
+ a.download = `three-ws-walk-${Date.now()}.png`;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setStatus('Screenshot saved (single frame)');
+ return;
+ }
+
+ const img = new Image();
+ await new Promise((resolve, reject) => {
+ img.onload = resolve;
+ img.onerror = reject;
+ img.src = frames[0];
+ });
+
+ const w = img.naturalWidth;
+ const h = img.naturalHeight;
+ const offscreen = document.createElement('canvas');
+ offscreen.width = w;
+ offscreen.height = h;
+ const ctx = offscreen.getContext('2d');
+ const stream = offscreen.captureStream(0); // manually push frames
+ const videoTrack = stream.getVideoTracks()[0];
+
+ const mime = pickRecorderMime();
+ let recorder;
+ try {
+ recorder = mime ? new MediaRecorder(stream, { mimeType: mime }) : new MediaRecorder(stream);
+ } catch {
+ setStatus('Recording not supported in this browser', { error: true });
+ return;
+ }
+
+ const chunks = [];
+ recorder.ondataavailable = (e) => { if (e.data?.size) chunks.push(e.data); };
+
+ recorder.onstop = () => {
+ const isMp4 = (recorder.mimeType || '').includes('mp4');
+ const ext = isMp4 ? 'mp4' : 'webm';
+ const blob = new Blob(chunks, { type: isMp4 ? 'video/mp4' : 'video/webm' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `three-ws-walk-${Date.now()}.${ext}`;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 4000);
+ setStatus(`Recording saved (${frames.length} frames)`);
+ };
+
+ recorder.start();
+
+ // Play back each frame onto the offscreen canvas
+ for (let i = 0; i < frames.length; i++) {
+ const frameImg = new Image();
+ await new Promise((resolve) => {
+ frameImg.onload = resolve;
+ frameImg.onerror = resolve;
+ frameImg.src = frames[i];
+ });
+ ctx.clearRect(0, 0, w, h);
+ ctx.drawImage(frameImg, 0, 0, w, h);
+ // Request a frame from the stream
+ if (videoTrack.requestFrame) videoTrack.requestFrame();
+ await new Promise(r => setTimeout(r, GIF_FRAME_INTERVAL));
+ }
+
+ recorder.stop();
+}
+
+function toggleGifRecording() {
+ if (gifRecording) stopGifRecording();
+ else startGifRecording();
+}
+
+// ── Minimap ──────────────────────────────────────────────────────────────
+// Small top-down canvas in the bottom-right corner showing player positions
+// and environment bounds.
+let minimapVisible = false;
+const MINIMAP_SIZE = 160;
+const MINIMAP_WORLD_RADIUS = 14; // world units visible in the minimap
+
+const minimapContainer = (() => {
+ const el = document.createElement('div');
+ el.id = 'walk-minimap';
+ el.style.cssText = [
+ 'position:fixed', 'z-index:6',
+ 'right:16px', 'bottom:calc(28px + env(safe-area-inset-bottom, 0))',
+ 'width:' + MINIMAP_SIZE + 'px', 'height:' + MINIMAP_SIZE + 'px',
+ 'border-radius:12px', 'overflow:hidden',
+ 'background:rgba(10,10,10,0.7)',
+ 'border:1px solid rgba(255,255,255,0.1)',
+ 'backdrop-filter:blur(6px)', '-webkit-backdrop-filter:blur(6px)',
+ 'display:none',
+ 'opacity:0', 'transition:opacity 0.2s ease',
+ 'cursor:crosshair',
+ ].join(';');
+ document.body.appendChild(el);
+ return el;
+})();
+
+const minimapCanvas = (() => {
+ const c = document.createElement('canvas');
+ c.width = MINIMAP_SIZE * 2; // 2x for retina
+ c.height = MINIMAP_SIZE * 2;
+ c.style.cssText = 'width:100%;height:100%;display:block';
+ minimapContainer.appendChild(c);
+ return c;
+})();
+
+const minimapCtx = minimapCanvas.getContext('2d');
+
+// Waypoint: click on minimap to set a target position for the avatar
+let waypointTarget = null;
+const WAYPOINT_SPEED = 2.0;
+const WAYPOINT_ARRIVE_DIST = 0.3;
+
+minimapContainer.addEventListener('click', (e) => {
+ const rect = minimapContainer.getBoundingClientRect();
+ const nx = (e.clientX - rect.left) / rect.width;
+ const ny = (e.clientY - rect.top) / rect.height;
+ // Map from minimap coords to world coords
+ // minimap center = avatar position
+ const wx = avatarRig.position.x + (nx - 0.5) * MINIMAP_WORLD_RADIUS * 2;
+ const wz = avatarRig.position.z + (ny - 0.5) * MINIMAP_WORLD_RADIUS * 2;
+ // Clamp to ground radius
+ const r = Math.hypot(wx, wz);
+ if (r > GROUND_RADIUS - 0.5) {
+ const k = (GROUND_RADIUS - 0.5) / r;
+ waypointTarget = { x: wx * k, z: wz * k };
+ } else {
+ waypointTarget = { x: wx, z: wz };
+ }
+ setStatus('Waypoint set — avatar walking to target');
+});
+
+function toggleMinimap() {
+ minimapVisible = !minimapVisible;
+ if (minimapVisible) {
+ minimapContainer.style.display = 'block';
+ requestAnimationFrame(() => { minimapContainer.style.opacity = '1'; });
+ } else {
+ minimapContainer.style.opacity = '0';
+ setTimeout(() => { if (!minimapVisible) minimapContainer.style.display = 'none'; }, 200);
+ }
+ setStatus(minimapVisible ? 'Minimap on' : 'Minimap off');
+}
+
+function updateMinimapFrame() {
+ if (!minimapVisible) return;
+ const ctx = minimapCtx;
+ const s = MINIMAP_SIZE * 2;
+ const half = s / 2;
+ const scale = s / (MINIMAP_WORLD_RADIUS * 2);
+
+ ctx.clearRect(0, 0, s, s);
+
+ // Background
+ ctx.fillStyle = 'rgba(10,10,10,0.6)';
+ ctx.fillRect(0, 0, s, s);
+
+ // Ground disc outline
+ ctx.save();
+ ctx.translate(half, half);
+ const groundPxR = GROUND_RADIUS * scale;
+ const offsetX = -avatarRig.position.x * scale;
+ const offsetZ = -avatarRig.position.z * scale;
+ ctx.beginPath();
+ ctx.arc(offsetX, offsetZ, groundPxR, 0, Math.PI * 2);
+ ctx.strokeStyle = 'rgba(255,255,255,0.15)';
+ ctx.lineWidth = 1;
+ ctx.stroke();
+ ctx.fillStyle = 'rgba(255,255,255,0.03)';
+ ctx.fill();
+
+ // Environment props indicator (dots for trees/buildings)
+ for (const child of envPropsGroup.children) {
+ if (child.isInstancedMesh && child.count > 0) {
+ const m = new Matrix4();
+ for (let i = 0; i < child.count; i++) {
+ child.getMatrixAt(i, m);
+ const px = m.elements[12] * scale + offsetX;
+ const pz = m.elements[14] * scale + offsetZ;
+ ctx.beginPath();
+ ctx.arc(px, pz, 2, 0, Math.PI * 2);
+ ctx.fillStyle = 'rgba(255,255,255,0.2)';
+ ctx.fill();
+ }
+ }
+ }
+
+ // Remote players
+ for (const [sid, rp] of remotePlayers) {
+ const px = (rp.rig.position.x - avatarRig.position.x) * scale;
+ const pz = (rp.rig.position.z - avatarRig.position.z) * scale;
+ ctx.beginPath();
+ ctx.arc(px, pz, 4, 0, Math.PI * 2);
+ const colorHex = '#' + (rp._color ?? 0xff8844).toString(16).padStart(6, '0');
+ ctx.fillStyle = colorHex;
+ ctx.fill();
+ }
+
+ // Waypoint indicator
+ if (waypointTarget) {
+ const wpx = (waypointTarget.x - avatarRig.position.x) * scale;
+ const wpz = (waypointTarget.z - avatarRig.position.z) * scale;
+ ctx.beginPath();
+ ctx.arc(wpx, wpz, 5, 0, Math.PI * 2);
+ ctx.strokeStyle = '#4ade80';
+ ctx.lineWidth = 2;
+ ctx.stroke();
+ // Pulsing ring
+ const pulse = (performance.now() % 1500) / 1500;
+ ctx.beginPath();
+ ctx.arc(wpx, wpz, 5 + pulse * 8, 0, Math.PI * 2);
+ ctx.strokeStyle = `rgba(74,222,128,${0.5 - pulse * 0.5})`;
+ ctx.lineWidth = 1;
+ ctx.stroke();
+ }
+
+ // Local player (green arrow at center)
+ ctx.save();
+ ctx.rotate(-avatarYaw);
+ ctx.beginPath();
+ ctx.moveTo(0, -7);
+ ctx.lineTo(5, 5);
+ ctx.lineTo(0, 2);
+ ctx.lineTo(-5, 5);
+ ctx.closePath();
+ ctx.fillStyle = '#4ade80';
+ ctx.fill();
+ ctx.restore();
+
+ ctx.restore();
+}
+
+// ── Help overlay first-visit auto-show ───────────────────────────────────
+const HELP_FIRST_VISIT_KEY = 'walk:help-shown';
+function showHelpOnFirstVisit() {
+ try {
+ if (localStorage.getItem(HELP_FIRST_VISIT_KEY) === '1') return;
+ localStorage.setItem(HELP_FIRST_VISIT_KEY, '1');
+ } catch { return; }
+ // Show help briefly on first visit
+ toggleHelp();
+ setTimeout(() => {
+ if (helpVisible) toggleHelp();
+ }, 6000);
+}
+
// ── Boot ──────────────────────────────────────────────────────────────────
loadAvatar()
.then(() => {
requestAnimationFrame(tick);
startNet();
+ // Apply saved environment
+ applyEnvironment(currentEnvIndex);
+ // Show camera mode if not default
+ if (cameraMode !== 'follow') {
+ if (avatar) avatar.visible = cameraMode !== 'firstperson';
+ updateCameraModeIndicator();
+ }
+ // First-visit help
+ showHelpOnFirstVisit();
// Mobile + camera-capable → invite the user into AR. Delayed so it
// lands after the "walk it" status fade, not on top of it.
setTimeout(showArCta, 900);
@@ -1561,8 +2506,11 @@ loadAvatar()
const text = chatInput.value.trim();
if (!text) return;
chatInput.value = '';
+ chatInput.blur(); // return focus to canvas so WASD works
const name = nameInput?.value?.trim() || 'you';
addChatMessage(name, text);
+ // Show speech bubble above local avatar
+ showSpeechBubbleFor('local', text);
if (net?.room) {
net.room.send('chat', { text: text.slice(0, 200) });
}
diff --git a/vercel.json b/vercel.json
index de888690b..256ecd688 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1868,6 +1868,14 @@
"src": "/api/billing/revenue",
"dest": "/api/billing/revenue"
},
+ {
+ "src": "/api/developer/webhooks/([^/]+)",
+ "dest": "/api/developer/webhooks/[id]?id=$1"
+ },
+ {
+ "src": "/api/developer/webhooks/?",
+ "dest": "/api/developer/webhooks"
+ },
{
"src": "/agents",
"dest": "/agents/index.html"
@@ -2450,7 +2458,7 @@
},
{
"path": "/api/cron/siwx-gc",
- "schedule": "23 * * * *"
+ "schedule": "0 3 * * *"
},
{
"path": "/api/cron/unstoppable-tick",
diff --git a/x402-buildout/PLAN.md b/x402-buildout/PLAN.md
index b5bf0f5d1..0bafe31d7 100644
--- a/x402-buildout/PLAN.md
+++ b/x402-buildout/PLAN.md
@@ -186,10 +186,10 @@ Track progress by editing the checkboxes in each prompt's **Acceptance** section
| Phase | Status |
|---|---|
-| 1 Foundation | not started |
-| 2 Sellers | not started |
-| 3 Buyers | not started |
-| 4 Transports | not started |
-| 5 Extensions | not started |
-| 6 Hooks & Ops | not started |
-| 7 Productized agents | not started |
+| 1 Foundation | **done** — x402-spec.js, facilitator client |
+| 2 Sellers | **done** — paidEndpoint helper with exact EVM, exact SVM, direct BSC |
+| 3 Buyers | **done** — x402-buyer-fetch.js, x402-buyer-axios.js |
+| 4 Transports | **done** — MCP server in mcp-server/, a2a via auth-hints |
+| 5 Extensions | **done** — bazaar discovery, payment identifiers, sign-in-with-x, offer-receipt, gas-sponsoring, builder-code, auth-hints |
+| 6 Hooks & Ops | **done** — spending limits, access control/api-key bypass, audit logging, idempotency cache, paywall UI in public/x402.js |
+| 7 Productized agents | **partial** — fact-checker and pump-agent-audit exist; remaining agents not started |