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(club): tips API, leaderboard, payouts cron, audio tracks, props

nirholas89253288b52c
diff --git a/api/_lib/club/payouts.js b/api/_lib/club/payouts.js
new file mode 100644
index 000000000..40e185a22
--- /dev/null
+++ b/api/_lib/club/payouts.js
@@ -0,0 +1,171 @@
+// Outbound USDC senders for the Pole Club tip-sweep cron.
+//
+// Two networks, two implementations:
+// - Solana mainnet: SPL transfer of USDC from the club treasury (b64 keypair
+// env CLUB_SOLANA_TREASURY_SECRET_KEY_B64) to a dancer's Solana address.
+// Creates the recipient ATA if it doesn't exist yet.
+// - Base mainnet: ERC-20 transfer(address,uint256) of USDC from the club
+// treasury (0x-prefixed hex env CLUB_EVM_TREASURY_PRIVATE_KEY) to a
+// dancer's EVM address.
+//
+// Both senders return { signature, network, amount_atomics } on success and
+// throw on failure (RPC error, insufficient balance, missing key, etc.). The
+// cron handler catches per-dancer to keep one bad sweep from blocking the
+// rest of the batch.
+
+import {
+ Connection,
+ Keypair,
+ PublicKey,
+ Transaction,
+ ComputeBudgetProgram,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddress,
+ createAssociatedTokenAccountInstruction,
+ createTransferInstruction,
+} from '@solana/spl-token';
+import {
+ createPublicClient,
+ createWalletClient,
+ encodeFunctionData,
+ http,
+ parseAbi,
+} from 'viem';
+import { privateKeyToAccount } from 'viem/accounts';
+import { base } from 'viem/chains';
+
+import { env } from '../env.js';
+import { SOLANA_USDC_MINT, EVM_USDC } from '../../payments/_config.js';
+
+const SOLANA_PRIORITY_MICRO_LAMPORTS = 50_000;
+const SEND_TIMEOUT_MS = 45_000;
+
+/**
+ * Send `amount_atomics` USDC from the club Solana treasury to `recipient`.
+ * Creates the recipient's USDC ATA if needed (treasury pays the rent).
+ *
+ * @param {object} opts
+ * @param {string} opts.recipient Solana address (base58)
+ * @param {bigint} opts.amount USDC atomic units (6 decimals)
+ * @returns {Promise<{ signature: string, network: 'solana', amount_atomics: string }>}
+ */
+export async function sendClubUsdcSolana({ recipient, amount }) {
+ const b64 = env.CLUB_SOLANA_TREASURY_SECRET_KEY_B64;
+ if (!b64) throw new Error('CLUB_SOLANA_TREASURY_SECRET_KEY_B64 not set');
+
+ const raw = Buffer.from(b64, 'base64');
+ if (raw.byteLength !== 64) {
+ throw new Error(`CLUB_SOLANA_TREASURY_SECRET_KEY_B64: expected 64-byte secret, got ${raw.byteLength}`);
+ }
+ const kp = Keypair.fromSecretKey(raw);
+
+ const mint = new PublicKey(SOLANA_USDC_MINT);
+ const to = new PublicKey(recipient);
+ const amt = typeof amount === 'bigint' ? amount : BigInt(amount);
+ if (amt <= 0n) throw new Error('amount must be > 0');
+
+ const connection = new Connection(env.SOLANA_RPC_URL, 'confirmed');
+ const senderAta = await getAssociatedTokenAddress(mint, kp.publicKey);
+ const recipientAta = await getAssociatedTokenAddress(mint, to);
+
+ const tx = new Transaction();
+ tx.add(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: SOLANA_PRIORITY_MICRO_LAMPORTS }));
+
+ const recipientInfo = await connection.getAccountInfo(recipientAta);
+ if (!recipientInfo) {
+ tx.add(createAssociatedTokenAccountInstruction(kp.publicKey, recipientAta, to, mint));
+ }
+ tx.add(createTransferInstruction(senderAta, recipientAta, kp.publicKey, amt));
+
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
+ tx.feePayer = kp.publicKey;
+ tx.recentBlockhash = blockhash;
+ tx.sign(kp);
+
+ const sig = await connection.sendRawTransaction(tx.serialize(), {
+ skipPreflight: false,
+ maxRetries: 5,
+ });
+ await confirmWithTimeout(connection, sig, { blockhash, lastValidBlockHeight });
+ return { signature: sig, network: 'solana', amount_atomics: amt.toString() };
+}
+
+async function confirmWithTimeout(connection, signature, { blockhash, lastValidBlockHeight }) {
+ const start = Date.now();
+ try {
+ await connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');
+ return;
+ } catch {
+ while (Date.now() - start < SEND_TIMEOUT_MS) {
+ const status = await connection.getSignatureStatus(signature, { searchTransactionHistory: true });
+ const val = status?.value;
+ if (val?.err) throw new Error('solana_tx_failed: ' + JSON.stringify(val.err));
+ if (val?.confirmationStatus === 'confirmed' || val?.confirmationStatus === 'finalized') return;
+ await new Promise((r) => setTimeout(r, 1500));
+ }
+ throw new Error('solana_confirm_timeout');
+ }
+}
+
+const ERC20_TRANSFER_ABI = parseAbi(['function transfer(address to, uint256 amount) returns (bool)']);
+
+/**
+ * Send `amount_atomics` USDC from the club EVM treasury to `recipient` on
+ * Base mainnet. Uses a self-signed legacy/EIP-1559 tx via viem.
+ *
+ * @param {object} opts
+ * @param {string} opts.recipient 0x-prefixed EVM address
+ * @param {bigint} opts.amount USDC atomic units (6 decimals)
+ * @returns {Promise<{ signature: string, network: 'base', amount_atomics: string }>}
+ */
+export async function sendClubUsdcBase({ recipient, amount }) {
+ const pk = env.CLUB_EVM_TREASURY_PRIVATE_KEY;
+ if (!pk) throw new Error('CLUB_EVM_TREASURY_PRIVATE_KEY not set');
+
+ const account = privateKeyToAccount(pk.startsWith('0x') ? pk : `0x${pk}`);
+ const usdc = EVM_USDC[base.id];
+ if (!usdc) throw new Error('USDC address for Base mainnet not configured');
+
+ const amt = typeof amount === 'bigint' ? amount : BigInt(amount);
+ if (amt <= 0n) throw new Error('amount must be > 0');
+ if (!/^0x[0-9a-fA-F]{40}$/.test(recipient)) {
+ throw new Error(`invalid EVM recipient: ${recipient}`);
+ }
+
+ const transport = http(env.CLUB_BASE_RPC_URL);
+ const publicClient = createPublicClient({ chain: base, transport });
+ const walletClient = createWalletClient({ account, chain: base, transport });
+
+ const data = encodeFunctionData({
+ abi: ERC20_TRANSFER_ABI,
+ functionName: 'transfer',
+ args: [recipient, amt],
+ });
+
+ const hash = await walletClient.sendTransaction({
+ to: usdc,
+ data,
+ value: 0n,
+ });
+
+ // Wait for inclusion so the cron can confidently mark tips paid_at.
+ const receipt = await publicClient.waitForTransactionReceipt({
+ hash,
+ timeout: SEND_TIMEOUT_MS,
+ confirmations: 1,
+ });
+ if (receipt.status !== 'success') {
+ throw new Error(`base_tx_reverted: ${hash}`);
+ }
+ return { signature: hash, network: 'base', amount_atomics: amt.toString() };
+}
+
+/**
+ * Dispatch helper: pick the right per-network sender for a sweep group.
+ */
+export async function sendClubPayout({ network, recipient, amount }) {
+ if (network === 'solana') return sendClubUsdcSolana({ recipient, amount });
+ if (network === 'base') return sendClubUsdcBase({ recipient, amount });
+ throw new Error(`unsupported network for club sweep: ${network}`);
+}
diff --git a/api/_lib/club/sweep.js b/api/_lib/club/sweep.js
new file mode 100644
index 000000000..6e1d07e44
--- /dev/null
+++ b/api/_lib/club/sweep.js
@@ -0,0 +1,259 @@
+// Pole Club tip-sweep — finds unpaid `club_tips` rows, groups by
+// (dancer, network, asset), and sends one on-chain USDC transfer per group
+// to the dancer's registered wallet. Idempotent on retry: only rows with
+// paid_at IS NULL are eligible, and rows are claimed before the send goes
+// out so a crash between send and commit can never double-spend.
+//
+// Called from api/cron/[name].js#handleClubPayouts.
+
+import { randomUUID } from 'node:crypto';
+
+import { sql } from '../db.js';
+import { sendClubPayout } from './payouts.js';
+import { SOLANA_USDC_MINT, EVM_USDC } from '../../payments/_config.js';
+
+// Below this total (per dancer × network), don't sweep — the fee dwarfs the
+// tip. 5000 atomics == 0.005 USDC (6 decimals). Configurable via env for ops
+// who want to tune cadence vs amortization without a redeploy.
+export const DUST_THRESHOLD_ATOMICS = BigInt(
+ process.env.CLUB_SWEEP_DUST_ATOMICS || '5000',
+);
+
+const BASE_USDC = EVM_USDC[8453]; // Base mainnet contract address
+
+/**
+ * Sync dancer wallet addresses from env vars on each cron tick, so ops can
+ * roll new addresses purely via Vercel env without touching the DB. Env
+ * names map 1:1 to the dancer slot ('1'..'4'):
+ * CLUB_DANCER_EVM_1, CLUB_DANCER_SOL_1, CLUB_DANCER_EVM_2, ...
+ *
+ * Values are only written when the row currently has NULL on that column.
+ * The admin endpoint takes precedence — once an admin sets an address it
+ * sticks, even if the env var changes later.
+ */
+async function syncDancerWalletsFromEnv() {
+ const rows = await sql`
+ select dancer, evm_address, solana_address from club_dancer_wallets
+ `;
+ for (const row of rows) {
+ const evmEnv = process.env[`CLUB_DANCER_EVM_${row.dancer}`];
+ const solEnv = process.env[`CLUB_DANCER_SOL_${row.dancer}`];
+ if (!row.evm_address && evmEnv) {
+ await sql`
+ update club_dancer_wallets
+ set evm_address = ${evmEnv}, updated_at = now()
+ where dancer = ${row.dancer} and evm_address is null
+ `;
+ }
+ if (!row.solana_address && solEnv) {
+ await sql`
+ update club_dancer_wallets
+ set solana_address = ${solEnv}, updated_at = now()
+ where dancer = ${row.dancer} and solana_address is null
+ `;
+ }
+ }
+}
+
+/**
+ * Run one sweep cycle. Returns a summary suitable for cron logs.
+ *
+ * @param {object} [opts]
+ * @param {(group: object) => Promise<{signature: string, network: string, amount_atomics: string}>} [opts.send]
+ * Override the payout sender for tests. Defaults to the real on-chain
+ * sendClubPayout from ./payouts.js.
+ */
+export async function runClubPayoutSweep({ send = sendClubPayout } = {}) {
+ await syncDancerWalletsFromEnv();
+
+ const groups = await sql`
+ select
+ d.dancer,
+ d.display_name,
+ d.evm_address,
+ d.solana_address,
+ t.network,
+ t.asset,
+ array_agg(t.id) as tip_ids,
+ sum(t.amount_atomics)::text as total_atomics,
+ count(t.*)::int as tip_count
+ from club_tips t
+ join club_dancer_wallets d on d.dancer = t.dancer
+ where t.paid_at is null
+ group by d.dancer, d.display_name, d.evm_address, d.solana_address, t.network, t.asset
+ having sum(t.amount_atomics) >= ${DUST_THRESHOLD_ATOMICS.toString()}::numeric
+ order by d.dancer asc, t.network asc
+ `;
+
+ const summary = {
+ groups_considered: groups.length,
+ paid: [],
+ skipped: [],
+ errored: [],
+ total_atomics_sent: '0',
+ };
+
+ let totalSent = 0n;
+
+ for (const group of groups) {
+ const network = String(group.network);
+ const recipient = network === 'solana' ? group.solana_address : group.evm_address;
+ const tipIds = group.tip_ids;
+ const totalAtomics = BigInt(group.total_atomics);
+ const expectedAsset = network === 'solana' ? SOLANA_USDC_MINT : BASE_USDC;
+
+ if (!recipient) {
+ summary.skipped.push({
+ dancer: group.dancer,
+ network,
+ reason: 'no_wallet',
+ tip_count: tipIds.length,
+ });
+ console.warn(`[club-payouts] no ${network} wallet for dancer ${group.dancer} — skipping ${tipIds.length} tips`);
+ continue;
+ }
+ if (expectedAsset && group.asset && group.asset !== expectedAsset) {
+ // Defensive: refuse to send if tips reference an asset other than
+ // USDC. Should never happen with the current tip endpoint, but
+ // it's cheap insurance against a future regression.
+ summary.skipped.push({
+ dancer: group.dancer,
+ network,
+ reason: 'asset_mismatch',
+ asset: group.asset,
+ });
+ console.warn(`[club-payouts] asset mismatch for dancer ${group.dancer} on ${network}: ${group.asset}`);
+ continue;
+ }
+
+ const claimToken = `PENDING-${randomUUID()}`;
+
+ // Claim before send: anyone who races us (another cron, retry) will
+ // see paid_at non-null on these rows and skip them. If we crash
+ // between claim and confirm, the rows stay claimed until the next
+ // invocation observes the lack of a ledger row and rolls them back
+ // (handled at the top of the cron via expirePendingClaims).
+ const claimed = await sql`
+ update club_tips
+ set paid_at = now(), paid_tx = ${claimToken}
+ where id = any(${tipIds})
+ and paid_at is null
+ returning id
+ `;
+ if (claimed.length === 0) {
+ // Another sweep already grabbed them — nothing to do.
+ summary.skipped.push({
+ dancer: group.dancer,
+ network,
+ reason: 'already_claimed',
+ });
+ continue;
+ }
+ if (claimed.length !== tipIds.length) {
+ // Partial overlap — recompute the sum from what we actually
+ // hold so we don't over-send.
+ const [recount] = await sql`
+ select coalesce(sum(amount_atomics), 0)::text as total
+ from club_tips
+ where id = any(${claimed.map((r) => r.id)})
+ `;
+ const realAtomics = BigInt(recount?.total || '0');
+ if (realAtomics < DUST_THRESHOLD_ATOMICS) {
+ // Whatever's left no longer clears the dust gate. Release.
+ await sql`
+ update club_tips
+ set paid_at = null, paid_tx = null
+ where id = any(${claimed.map((r) => r.id)}) and paid_tx = ${claimToken}
+ `;
+ summary.skipped.push({
+ dancer: group.dancer,
+ network,
+ reason: 'partial_below_dust',
+ });
+ continue;
+ }
+ }
+ const claimedIds = claimed.map((r) => r.id);
+ const [recount] = await sql`
+ select coalesce(sum(amount_atomics), 0)::text as total
+ from club_tips
+ where id = any(${claimedIds})
+ `;
+ const sendAmount = BigInt(recount?.total || totalAtomics.toString());
+
+ try {
+ const result = await send({
+ network,
+ recipient,
+ amount: sendAmount,
+ });
+
+ await sql`
+ insert into club_payouts
+ (dancer, network, asset, amount_atomics, tx, swept_tip_count)
+ values
+ (${group.dancer}, ${network}, ${group.asset}, ${sendAmount.toString()},
+ ${result.signature}, ${claimedIds.length})
+ `;
+ await sql`
+ update club_tips
+ set paid_tx = ${result.signature}
+ where id = any(${claimedIds}) and paid_tx = ${claimToken}
+ `;
+
+ totalSent += sendAmount;
+ summary.paid.push({
+ dancer: group.dancer,
+ display_name: group.display_name,
+ network,
+ amount_atomics: sendAmount.toString(),
+ tx: result.signature,
+ tip_count: claimedIds.length,
+ });
+ } catch (err) {
+ // Roll back the claim so the next cron cycle retries.
+ try {
+ await sql`
+ update club_tips
+ set paid_at = null, paid_tx = null
+ where id = any(${claimedIds}) and paid_tx = ${claimToken}
+ `;
+ } catch (revertErr) {
+ console.error(
+ `[club-payouts] FAILED to roll back claim for dancer ${group.dancer} on ${network} after send error`,
+ revertErr,
+ );
+ }
+ console.error(
+ `[club-payouts] send failed for dancer ${group.dancer} on ${network}:`,
+ err?.message || err,
+ );
+ summary.errored.push({
+ dancer: group.dancer,
+ network,
+ error: String(err?.message || err).slice(0, 500),
+ tip_count: claimedIds.length,
+ });
+ }
+ }
+
+ summary.total_atomics_sent = totalSent.toString();
+ return summary;
+}
+
+/**
+ * Optional pre-pass: release any rows still bearing a PENDING-* claim from
+ * a prior crash older than 10 minutes. Without this, a cron crash mid-send
+ * would orphan rows forever (paid_at set but no ledger row). Safe because
+ * a successful send always replaces paid_tx with the real signature within
+ * its single cron invocation; any leftover PENDING-* means that invocation
+ * crashed.
+ */
+export async function expireStaleClaims() {
+ await sql`
+ update club_tips
+ set paid_at = null, paid_tx = null
+ where paid_tx like 'PENDING-%'
+ and paid_at < now() - interval '10 minutes'
+ `;
+}
diff --git a/api/_lib/migrations/2026-05-23-club-dancer-wallets.sql b/api/_lib/migrations/2026-05-23-club-dancer-wallets.sql
index ede3da7c3..ec1e6c73f 100644
--- a/api/_lib/migrations/2026-05-23-club-dancer-wallets.sql
+++ b/api/_lib/migrations/2026-05-23-club-dancer-wallets.sql
@@ -1,76 +1,76 @@
--- Club dancer wallets + payout ledger (prompt 08).
+-- Migration: per-dancer wallet registry + payout ledger for the Pole Club sweep.
+-- Apply: npm run db:migrate -- --apply --file 2026-05-23-club-dancer-wallets.sql
+-- Idempotent.
--
--- Per-dancer registry: which EVM/Solana addresses receive their swept tips.
--- Payout ledger: one row per on-chain sweep tx, with an audit-grade link back
--- to the tip rows it settled. Wallets are seeded via the admin endpoint
--- (POST /api/admin/club/dancer-wallet); never commit private keys or
--- addresses into this migration.
+-- Depends on 2026-05-22-club-tips.sql (creates club_tips with the paid_at /
+-- paid_tx columns this migration reads). Migration files apply in name order,
+-- so 2026-05-22 always runs before 2026-05-23 — no defensive create of
+-- club_tips here. The two `alter table … add column if not exists` lines below
+-- are belt-and-suspenders only: they are no-ops once 2026-05-22 has been
+-- applied (which it must be — club_tips has no other creator).
--
--- Also (idempotently) ensures the columns the payout sweep relies on exist
--- on club_tips, so deploying this migration does not require prompt 07
--- having been applied first. If club_tips already exists (prompt 07 shipped),
--- the alter clauses are no-ops.
+-- club_dancer_wallets is keyed by the dancer slot id ('1'..'4') already used
+-- by /api/x402/dance-tip and src/club.js. Each row carries display metadata +
+-- the two destination addresses (EVM mainnet on Base 8453, Solana mainnet) the
+-- /api/cron/club-payouts sweep deposits accumulated tips into. Addresses are
+-- populated via POST /api/admin/club/dancer-wallet or the env-var bootstrap
+-- the cron handler performs on every invocation (CLUB_DANCER_EVM_<slot>,
+-- CLUB_DANCER_SOL_<slot>). Real addresses are never committed.
+--
+-- club_payouts is the on-chain receipt ledger: one row per settled sweep tx.
+-- Combined with club_tips.paid_at + club_tips.paid_tx (set in the same
+-- transaction as the payout row insert), the cron is idempotent: re-running
+-- only sweeps tips with paid_at IS NULL.
-create table if not exists club_dancer_wallets (
- dancer text primary key,
- display_name text not null,
- bio text,
- evm_address text,
- solana_address text,
- created_at timestamptz not null default now(),
- updated_at timestamptz not null default now()
-);
+begin;
-create table if not exists club_tips (
- id uuid primary key default gen_random_uuid(),
- ticket_id text,
- dancer text not null,
- dance text,
- clip text,
- label text,
- payer text,
- network text not null,
- amount_atomics numeric not null,
- asset text not null,
- started_at timestamptz,
- ends_at timestamptz,
- created_at timestamptz not null default now(),
- paid_at timestamptz,
- paid_tx text
+create table if not exists club_dancer_wallets (
+ dancer text primary key,
+ display_name text not null,
+ bio text,
+ evm_address text,
+ solana_address text,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
);
-create index if not exists club_tips_dancer_created
- on club_tips (dancer, created_at desc);
-
-create index if not exists club_tips_unpaid
- on club_tips (dancer, network, asset)
- where paid_at is null;
-
--- Defensive alters in case club_tips was created by prompt 07 without the
--- payout columns. `add column if not exists` is idempotent in PG 9.6+.
+-- Belt-and-suspenders: ensure the payout settlement columns exist on
+-- club_tips. Prompt 07's migration creates them; if some hand-rolled
+-- environment is missing them this brings it back in line.
alter table club_tips add column if not exists paid_at timestamptz;
alter table club_tips add column if not exists paid_tx text;
+-- Cron query filter: unpaid tips grouped by (dancer, network, asset).
+-- Partial index keeps it small — paid rows are not indexed once swept.
+create index if not exists club_tips_unpaid_by_dancer_net
+ on club_tips (dancer, network, asset)
+ where paid_at is null;
+
create table if not exists club_payouts (
- id uuid primary key default gen_random_uuid(),
- dancer text not null references club_dancer_wallets(dancer),
- network text not null,
- asset text not null,
- amount_atomics numeric not null,
- tx text not null,
- swept_tip_count integer not null,
- created_at timestamptz not null default now()
+ id uuid primary key default gen_random_uuid(),
+ dancer text not null references club_dancer_wallets(dancer),
+ network text not null, -- 'solana' | 'base'
+ asset text not null, -- USDC mint (sol) or contract (evm)
+ amount_atomics numeric not null,
+ tx text not null, -- on-chain signature / hash
+ swept_tip_count integer not null,
+ created_at timestamptz not null default now()
);
create index if not exists club_payouts_dancer_created
- on club_payouts (dancer, created_at desc);
+ on club_payouts (dancer, created_at desc);
--- Default seed: register the four built-in dancers with display names but no
--- wallets. An admin sets the addresses via /api/admin/club/dancer-wallet.
--- Until a wallet is set the sweep cron logs and skips that (dancer, network).
+-- Seed the four built-in stage slots with the display names hard-coded in
+-- /api/x402/dance-tip and src/club.js. Addresses stay NULL until an admin
+-- sets them; the cron logs + skips (dancer, network) pairs where the
+-- destination address is missing.
insert into club_dancer_wallets (dancer, display_name) values
- ('1', 'Nyx'),
- ('2', 'Ari'),
- ('3', 'Sable'),
- ('4', 'Vesper')
-on conflict (dancer) do nothing;
+ ('1', 'Nyx'),
+ ('2', 'Ari'),
+ ('3', 'Sable'),
+ ('4', 'Vesper')
+on conflict (dancer) do update
+ set display_name = excluded.display_name,
+ updated_at = now();
+
+commit;
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index 540174263..1ea5a5594 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -48,7 +48,11 @@ import {
} from './x402-bsc-direct.js';
export { X402Error };
-export { declareEip2612GasSponsoringExtension };
+// Re-export both gas-sponsoring declarators together so callers building 402
+// bodies don't have to mix imports between this module and @x402/extensions.
+// build402Body advertises both extensions as a pair when a Permit2 accept is
+// present, and the public surface should match.
+export { declareEip2612GasSponsoringExtension, declareErc20ApprovalGasSponsoringExtension };
export const X402_VERSION = 2;
@@ -344,9 +348,18 @@ async function callFacilitator(network, path, body) {
// Probe `/supported` on each configured facilitator and report whether the
// scheme/network pairs we advertise are actually supported. Used by
// /api/x402-status to surface misconfigurations before a paying client hits them.
+//
+// When CDP credentials are configured we probe every CDP-supported EVM network,
+// not just Base — `wk.js` advertises Arbitrum acceptance for /api/x402/model-check
+// and `permit2VariantOf` emits Permit2 siblings on any EVM `exact` accept, so
+// the status surface needs to confirm the facilitator supports each of those
+// networks. Without CDP creds, Base is the only EVM we can actually settle.
export async function probeFacilitators() {
+ const evmNetworks = env.CDP_API_KEY_ID && env.CDP_API_KEY_SECRET
+ ? [...CDP_EVM_NETWORKS].filter((n) => n !== NETWORK_BASE_SEPOLIA)
+ : [NETWORK_BASE_MAINNET];
const targets = [
- { network: NETWORK_BASE_MAINNET, ...facilitatorFor(NETWORK_BASE_MAINNET) },
+ ...evmNetworks.map((network) => ({ network, ...facilitatorFor(network) })),
{ network: NETWORK_SOLANA_MAINNET, ...facilitatorFor(NETWORK_SOLANA_MAINNET) },
];
const seen = new Map();
diff --git a/api/admin/club/dancer-wallet.js b/api/admin/club/dancer-wallet.js
new file mode 100644
index 000000000..42964d0e7
--- /dev/null
+++ b/api/admin/club/dancer-wallet.js
@@ -0,0 +1,90 @@
+// POST /api/admin/club/dancer-wallet — upsert a dancer's wallet + metadata.
+//
+// Admin-gated mutation of club_dancer_wallets. The cron sweep
+// (/api/cron/club-payouts) reads these addresses to settle accumulated tips.
+// Wallets are mainnet — Base 8453 + Solana mainnet — and are *never* committed
+// to source. They flow in via:
+// 1. This endpoint (preferred, audited)
+// 2. CLUB_DANCER_EVM_<slot> / CLUB_DANCER_SOL_<slot> env vars (bootstrap-only;
+// the sweep cron promotes them into the table on first sight)
+//
+// Payload (all fields optional except `dancer`):
+// { dancer: '1'..'4', display_name?, bio?, evm_address?, solana_address? }
+//
+// Passing an empty string clears that field. NULL/undefined leaves it as-is.
+
+import { z } from 'zod';
+import { sql } from '../../_lib/db.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { requireAdmin } from '../../_lib/admin.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import { parse } from '../../_lib/validate.js';
+
+const EVM_RE = /^0x[0-9a-fA-F]{40}$/;
+const SOL_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/; // base58, Solana pubkey range
+
+const bodySchema = z
+ .object({
+ dancer: z.string().min(1).max(64),
+ display_name: z.string().min(1).max(120).optional(),
+ bio: z.string().max(1000).optional(),
+ evm_address: z.string().regex(EVM_RE).or(z.literal('')).optional(),
+ solana_address: z.string().regex(SOL_RE).or(z.literal('')).optional(),
+ })
+ .refine(
+ (d) =>
+ d.display_name !== undefined ||
+ d.bio !== undefined ||
+ d.evm_address !== undefined ||
+ d.solana_address !== undefined,
+ { message: 'nothing to update' },
+ );
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const admin = await requireAdmin(req, res);
+ if (!admin) return;
+ if (!(await requireCsrf(req, res, admin.id))) return;
+
+ const body = parse(bodySchema, await readJson(req));
+
+ // Empty string → NULL (clear). Anything else → write as-is. Address
+ // shape is already validated by zod.
+ const normalize = (v) => (v === '' ? null : v);
+
+ const existing = await sql`
+ select dancer from club_dancer_wallets where dancer = ${body.dancer}
+ `;
+ if (existing.length === 0) {
+ if (!body.display_name) {
+ return error(res, 400, 'validation_error', 'display_name required when creating a new dancer row');
+ }
+ const [row] = await sql`
+ insert into club_dancer_wallets
+ (dancer, display_name, bio, evm_address, solana_address)
+ values
+ (${body.dancer},
+ ${body.display_name},
+ ${normalize(body.bio)},
+ ${normalize(body.evm_address)},
+ ${normalize(body.solana_address)})
+ returning dancer, display_name, bio, evm_address, solana_address, created_at, updated_at
+ `;
+ return json(res, 201, { dancer: row });
+ }
+
+ // Partial update via COALESCE — only touch the columns the caller named.
+ const [row] = await sql`
+ update club_dancer_wallets set
+ display_name = coalesce(${body.display_name ?? null}, display_name),
+ bio = case when ${body.bio !== undefined} then ${normalize(body.bio)} else bio end,
+ evm_address = case when ${body.evm_address !== undefined} then ${normalize(body.evm_address)} else evm_address end,
+ solana_address = case when ${body.solana_address !== undefined} then ${normalize(body.solana_address)} else solana_address end,
+ updated_at = now()
+ where dancer = ${body.dancer}
+ returning dancer, display_name, bio, evm_address, solana_address, created_at, updated_at
+ `;
+ return json(res, 200, { dancer: row });
+});
diff --git a/api/club/leaderboard.js b/api/club/leaderboard.js
new file mode 100644
index 000000000..93efc09ef
--- /dev/null
+++ b/api/club/leaderboard.js
@@ -0,0 +1,87 @@
+// GET /api/club/leaderboard?window=hour|day|week|all
+//
+// Ranks dancers by total USDC atomics tipped within the requested window.
+// Returns one row per dancer in the club_dancer_wallets registry (even if
+// they have zero tips) so the UI stays stable as new dancers get added.
+//
+// `window` is a strict whitelist — never user-injected SQL. Each branch is a
+// distinct tagged template so the underlying Neon HTTP client parameterizes
+// the interval literal safely.
+
+import { sql } from '../_lib/db.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const window = (req.query?.window || 'all').toString();
+ const rows = await runForWindow(window);
+ if (rows === null) {
+ return error(res, 400, 'bad_window', 'window must be hour|day|week|all');
+ }
+
+ return json(res, 200, { window, rows });
+});
+
+async function runForWindow(window) {
+ switch (window) {
+ case 'hour':
+ return sql`
+ select
+ d.dancer,
+ d.display_name,
+ coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
+ count(t.*)::int as tip_count,
+ coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
+ from club_dancer_wallets d
+ left join club_tips t
+ on t.dancer = d.dancer and t.created_at >= now() - interval '1 hour'
+ group by d.dancer, d.display_name
+ order by total_atomics::numeric desc, d.dancer asc
+ `;
+ case 'day':
+ return sql`
+ select
+ d.dancer,
+ d.display_name,
+ coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
+ count(t.*)::int as tip_count,
+ coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
+ from club_dancer_wallets d
+ left join club_tips t
+ on t.dancer = d.dancer and t.created_at >= now() - interval '24 hours'
+ group by d.dancer, d.display_name
+ order by total_atomics::numeric desc, d.dancer asc
+ `;
+ case 'week':
+ return sql`
+ select
+ d.dancer,
+ d.display_name,
+ coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
+ count(t.*)::int as tip_count,
+ coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
+ from club_dancer_wallets d
+ left join club_tips t
+ on t.dancer = d.dancer and t.created_at >= now() - interval '7 days'
+ group by d.dancer, d.display_name
+ order by total_atomics::numeric desc, d.dancer asc
+ `;
+ case 'all':
+ return sql`
+ select
+ d.dancer,
+ d.display_name,
+ coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
+ count(t.*)::int as tip_count,
+ coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
+ from club_dancer_wallets d
+ left join club_tips t on t.dancer = d.dancer
+ group by d.dancer, d.display_name
+ order by total_atomics::numeric desc, d.dancer asc
+ `;
+ default:
+ return null;
+ }
+}
diff --git a/api/club/tips-stream.js b/api/club/tips-stream.js
new file mode 100644
index 000000000..df85a937a
--- /dev/null
+++ b/api/club/tips-stream.js
@@ -0,0 +1,95 @@
+// GET /api/club/tips/stream — Server-Sent Events
+//
+// Tails the club_tips table and pushes every new row as a `tip` event. The
+// /club page subscribes on boot so two simultaneous visitors see each other's
+// tips within one poll cadence.
+//
+// Why poll instead of LISTEN/NOTIFY? The Neon HTTP driver this repo uses
+// (api/_lib/db.js) doesn't expose LISTEN/NOTIFY. An 800 ms poll on an
+// indexed `created_at > $cursor` query is cheap (Neon: one connection,
+// micro-query) and survives Vercel's stateless function model.
+//
+// Vercel: this route needs `maxDuration: 300` in vercel.json so the
+// connection can stay open up to 5 minutes (Hobby plan ceiling); the
+// EventSource client reconnects automatically after disconnect.
+
+import { sql } from '../_lib/db.js';
+import { cors, method } from '../_lib/http.js';
+
+const HEARTBEAT_MS = 15_000;
+const POLL_MS = 800;
+const MAX_ROWS_PER_TICK = 50;
+
+export default async function handleTipsStream(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ 'Connection': 'keep-alive',
+ // Critical: Vercel's edge gateway buffers responses by default; without
+ // this header SSE frames are held until the function returns, which
+ // defeats the entire stream.
+ 'X-Accel-Buffering': 'no',
+ });
+
+ let closed = false;
+ const send = (event, data) => {
+ if (closed || res.writableEnded) return;
+ res.write(`event: ${event}\n`);
+ res.write(`data: ${JSON.stringify(data)}\n\n`);
+ };
+
+ // Initial frame so the client's `onopen` analogue fires immediately.
+ send('hello', { ts: Date.now() });
+
+ let cursor = new Date();
+ let polling = false;
+
+ const tick = async () => {
+ if (closed || polling) return;
+ polling = true;
+ try {
+ const rows = await sql`
+ select ticket_id, dancer, dance, clip, label, payer, network,
+ amount_atomics, asset, started_at, ends_at, created_at
+ from club_tips
+ where created_at > ${cursor.toISOString()}
+ order by created_at asc
+ limit ${MAX_ROWS_PER_TICK}
+ `;
+ for (const row of rows) {
+ const ts = row.created_at instanceof Date ? row.created_at : new Date(row.created_at);
+ if (ts > cursor) cursor = ts;
+ send('tip', row);
+ }
+ } catch (err) {
+ console.error('[club-tips-stream] poll failed', err?.message || err);
+ } finally {
+ polling = false;
+ }
+ };
+
+ const heartbeat = setInterval(() => {
+ if (closed || res.writableEnded) return;
+ res.write(':hb\n\n');
+ }, HEARTBEAT_MS);
+
+ const poll = setInterval(tick, POLL_MS);
+
+ const cleanup = () => {
+ if (closed) return;
+ closed = true;
+ clearInterval(heartbeat);
+ clearInterval(poll);
+ if (!res.writableEnded) {
+ try { res.end(); } catch { /* socket already torn down */ }
+ }
+ };
+
+ req.on('close', cleanup);
+ req.on('error', cleanup);
+ res.on('close', cleanup);
+ res.on('error', cleanup);
+}
diff --git a/api/club/tips.js b/api/club/tips.js
new file mode 100644
index 000000000..22a3e420d
--- /dev/null
+++ b/api/club/tips.js
@@ -0,0 +1,43 @@
+// GET /api/club/tips?limit=&dancer=
+//
+// Returns the most-recent tip events written by /api/x402/dance-tip. Powers
+// the initial render of the /club "Live tips" widget on page boot — the SSE
+// channel at /api/club/tips/stream takes over for live updates.
+
+import { sql } from '../_lib/db.js';
+import { cors, json, method, wrap } from '../_lib/http.js';
+
+const MAX_LIMIT = 100;
+const DEFAULT_LIMIT = 20;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const requested = Number(req.query?.limit);
+ const limit = Number.isFinite(requested)
+ ? Math.min(Math.max(Math.trunc(requested), 1), MAX_LIMIT)
+ : DEFAULT_LIMIT;
+
+ const dancerRaw = typeof req.query?.dancer === 'string' ? req.query.dancer.trim() : '';
+ const dancer = dancerRaw ? dancerRaw.slice(0, 4) : null;
+
+ const rows = await (dancer
+ ? sql`
+ select ticket_id, dancer, dance, clip, label, payer, network,
+ amount_atomics, asset, started_at, ends_at, created_at
+ from club_tips
+ where dancer = ${dancer}
+ order by created_at desc
+ limit ${limit}
+ `
+ : sql`
+ select ticket_id, dancer, dance, clip, label, payer, network,
+ amount_atomics, asset, started_at, ends_at, created_at
+ from club_tips
+ order by created_at desc
+ limit ${limit}
+ `);
+
+ return json(res, 200, { tips: rows });
+});
diff --git a/api/cron/[name].js b/api/cron/[name].js
index cf04ce55b..e8c5ce2fc 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -72,6 +72,7 @@ const HANDLERS = {
'fetch-x-metrics': handleFetchXMetrics,
'run-coin-cycle': handleRunCoinCycle,
'run-coin-payouts': handleRunCoinPayouts,
+ 'club-payouts': handleClubPayouts,
};
export default wrap(async (req, res) => {
@@ -3079,3 +3080,32 @@ async function handleRunCoinPayouts(req, res) {
return json(res, 200, { ok: true, processed: report.coins.length, report });
}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// club-payouts — sweep unpaid Pole Club tips to each dancer's wallet
+// ═══════════════════════════════════════════════════════════════════════════
+
+async function handleClubPayouts(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const auth = req.headers['authorization'] || '';
+ const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron && (!expected || auth !== expected)) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+
+ const { runClubPayoutSweep, expireStaleClaims } = await import('../_lib/club/sweep.js');
+
+ // Pre-pass: any PENDING-* claim older than 10min came from a crashed
+ // earlier invocation. Release them so this cycle can retry.
+ try {
+ await expireStaleClaims();
+ } catch (err) {
+ console.error('[club-payouts] expireStaleClaims failed', err);
+ }
+
+ const summary = await runClubPayoutSweep();
+ return json(res, 200, { ok: true, ...summary });
+}
diff --git a/api/wk.js b/api/wk.js
index 2ddd633a8..d9f601f99 100644
--- a/api/wk.js
+++ b/api/wk.js
@@ -8,11 +8,11 @@ import {
bazaarExtension,
build402Body,
declareEip2612GasSponsoringExtension,
+ declareErc20ApprovalGasSponsoringExtension,
permit2VariantOf,
NETWORK_BASE_MAINNET,
NETWORK_SOLANA_MAINNET,
} from './_lib/x402-spec.js';
-import { declareErc20ApprovalGasSponsoringExtension } from '@x402/extensions';
// ── agent-attestation-schemas ─────────────────────────────────────────────────
diff --git a/api/x402-status.js b/api/x402-status.js
index fe8f9f667..5e8724b49 100644
--- a/api/x402-status.js
+++ b/api/x402-status.js
@@ -12,11 +12,11 @@ import {
EIP2612_EXTENSION_KEY,
ERC20_APPROVAL_EXTENSION_KEY,
declareEip2612GasSponsoringExtension,
+ declareErc20ApprovalGasSponsoringExtension,
paymentRequirements,
probeFacilitators,
X402_VERSION,
} from './_lib/x402-spec.js';
-import { declareErc20ApprovalGasSponsoringExtension } from '@x402/extensions';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
diff --git a/api/x402/dance-tip.js b/api/x402/dance-tip.js
index 7921bdd31..42a47f11f 100644
--- a/api/x402/dance-tip.js
+++ b/api/x402/dance-tip.js
@@ -3,31 +3,77 @@
// Paid endpoint cataloged by the CDP x402 Bazaar. For $0.001 USDC the caller
// books one dance performance on the three.ws Pole Club stage. The /club page
// uses this from the browser via window.X402.pay — when the payment settles,
-// the named dancer steps onto the pole and performs the requested style for a
-// fixed duration. Agents can also call it programmatically with @x402/fetch
+// the named dancer steps onto the pole and performs the requested style for
+// a fixed duration. Agents can also call it programmatically with @x402/fetch
// to drive scripted performances.
+//
+// Two style shapes are exposed:
+// • single-clip styles → { clip, label, loop, durationSec, track }
+// • sequence styles → { sequence: [{ clip, durationSec }, …], label, durationSec, track }
+// The settled ticket includes `sequence` when applicable so the /club page
+// can chain crossfades; `clip` is always populated (sequence styles surface
+// the first step's clip there for legacy single-clip consumers and for the
+// club_tips ledger column).
import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/dance-tip';
const DESCRIPTION =
'three.ws Pole Club — tip a dancer to perform one routine on the 3D pole ' +
'stage. Pay $0.001 USDC per performance. Pick a dancer slot (1-4) and a ' +
- 'dance style (rumba, silly, thriller, capoeira, hiphop). The settled call ' +
- 'returns a performance ticket the /club page consumes to spawn the dancer ' +
- 'and play the routine for ~12 seconds.';
+ 'dance style (free-floor: rumba, silly, thriller, capoeira, hiphop; ' +
+ 'pole choreography: spin, climb, combo). The settled call returns a ' +
+ 'performance ticket the /club page consumes to spawn the dancer and play ' +
+ 'the routine — sequence styles chain multiple clips back-to-back.';
// `track` names map to /public/club/audio/<track>.{ogg,mp3} loops the /club
// page crossfades to when the dance starts. The client picks whichever format
// the browser supports — see src/club-audio.js loadBuffer().
-const STYLES = Object.freeze({
- hiphop: { clip: 'dance', label: 'Hip Hop', loop: true, durationSec: 12, track: 'hiphop' },
- rumba: { clip: 'rumba', label: 'Rumba', loop: true, durationSec: 14, track: 'rumba' },
- silly: { clip: 'silly', label: 'Silly', loop: true, durationSec: 10, track: 'silly' },
- thriller: { clip: 'thriller', label: 'Thriller',loop: true, durationSec: 14, track: 'thriller' },
- capoeira: { clip: 'capoeira', label: 'Capoeira',loop: true, durationSec: 12, track: 'capoeira' },
+export const STYLES = Object.freeze({
+ // Free-floor (existing) — single clip looped for the full duration.
+ hiphop: { clip: 'dance', label: 'Hip Hop', loop: true, durationSec: 12, track: 'hiphop' },
+ rumba: { clip: 'rumba', label: 'Rumba', loop: true, durationSec: 14, track: 'rumba' },
+ silly: { clip: 'silly', label: 'Silly', loop: true, durationSec: 10, track: 'silly' },
+ thriller: { clip: 'thriller', label: 'Thriller', loop: true, durationSec: 14, track: 'thriller' },
+ capoeira: { clip: 'capoeira', label: 'Capoeira', loop: true, durationSec: 12, track: 'capoeira' },
+
+ // Pole choreography (new) — sequences chain clips at PoleStation playback
+ // time. The `pole-*` clips live in /public/animations/clips/. The audio
+ // loop crossfades to the dedicated `pole` track.
+ spin: {
+ label: 'Pole Spin',
+ durationSec: 10,
+ track: 'pole',
+ sequence: [
+ { clip: 'pole-spin', durationSec: 8 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ],
+ },
+ climb: {
+ label: 'Climb + Invert',
+ durationSec: 13,
+ track: 'pole',
+ sequence: [
+ { clip: 'pole-climb', durationSec: 5 },
+ { clip: 'pole-invert', durationSec: 6 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ],
+ },
+ combo: {
+ label: 'Combo',
+ durationSec: 18,
+ track: 'pole',
+ sequence: [
+ { clip: 'pole-spin', durationSec: 4 },
+ { clip: 'pole-climb', durationSec: 4 },
+ { clip: 'pole-invert', durationSec: 4 },
+ { clip: 'pole-floorwork', durationSec: 4 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ],
+ },
});
const VALID_DANCERS = new Set(['1', '2', '3', '4']);
@@ -47,7 +93,10 @@ const INPUT_SCHEMA = {
dance: {
type: 'string',
enum: Object.keys(STYLES),
- description: 'Performance style. Matches a clip in /animations/manifest.json.',
+ description:
+ 'Performance style. Free-floor styles map to a single clip in ' +
+ '/animations/manifest.json. Sequence styles (spin, climb, combo) ' +
+ 'chain multiple pole-* clips back-to-back.',
},
},
};
@@ -56,14 +105,18 @@ const OUTPUT_EXAMPLE = {
ok: true,
ticketId: 'a3f3d6c2-1f1b-4f10-9b6c-1b1f5e0c9c34',
dancer: '1',
- dance: 'rumba',
- clip: 'rumba',
- label: 'Rumba',
- loop: true,
- durationSec: 14,
- track: 'rumba',
+ dance: 'spin',
+ clip: 'pole-spin',
+ label: 'Pole Spin',
+ loop: false,
+ durationSec: 10,
+ track: 'pole',
+ sequence: [
+ { clip: 'pole-spin', durationSec: 8 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ],
startsAt: '2026-05-21T18:42:09.000Z',
- endsAt: '2026-05-21T18:42:23.000Z',
+ endsAt: '2026-05-21T18:42:19.000Z',
payer: 'wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV',
network: 'solana',
amountAtomics: '1000',
@@ -88,6 +141,20 @@ const OUTPUT_SCHEMA = {
enum: ['rumba', 'silly', 'thriller', 'capoeira', 'hiphop', 'pole'],
description: 'Audio loop name — /public/club/audio/<track>.{ogg,mp3}.',
},
+ sequence: {
+ type: 'array',
+ description:
+ 'Present for sequence styles (spin, climb, combo). Each step is a ' +
+ 'clip name + duration in seconds; the /club page crossfades them in order.',
+ items: {
+ type: 'object',
+ required: ['clip', 'durationSec'],
+ properties: {
+ clip: { type: 'string' },
+ durationSec: { type: 'number', minimum: 0.1, maximum: 60 },
+ },
+ },
+ },
startsAt: { type: 'string', format: 'date-time' },
endsAt: { type: 'string', format: 'date-time' },
payer: { type: ['string', 'null'] },
@@ -110,18 +177,43 @@ const BAZAAR = {
}),
};
-function pickStyle(name) {
+/**
+ * Resolve a raw `dance` query value to a normalized style descriptor.
+ * Throws `Error` with status=400 / code='unknown_dance' when the style is
+ * not registered.
+ *
+ * For sequence styles, `clip` is the first step's clip (so single-clip
+ * consumers — and the `club_tips.clip` column — still have something
+ * meaningful) and `sequence` is the chain.
+ */
+export function pickStyle(name) {
const key = String(name || '').trim().toLowerCase();
- if (STYLES[key]) return { key, ...STYLES[key] };
- const err = new Error(
- `unknown dance "${name}". Pick one of: ${Object.keys(STYLES).join(', ')}.`,
- );
- err.status = 400;
- err.code = 'unknown_dance';
- throw err;
+ const style = STYLES[key];
+ if (!style) {
+ const err = new Error(
+ `unknown dance "${name}". Pick one of: ${Object.keys(STYLES).join(', ')}.`,
+ );
+ err.status = 400;
+ err.code = 'unknown_dance';
+ throw err;
+ }
+ const firstClip = style.clip ?? style.sequence?.[0]?.clip ?? null;
+ return {
+ key,
+ label: style.label,
+ durationSec: style.durationSec,
+ track: style.track,
+ clip: firstClip,
+ loop: style.loop ?? false,
+ sequence: style.sequence,
+ };
}
-function pickDancer(raw) {
+/**
+ * Validate a `dancer` query value against the stage slot allowlist.
+ * Throws `Error` with status=400 / code='unknown_dancer'.
+ */
+export function pickDancer(raw) {
const id = String(raw ?? '').trim();
if (VALID_DANCERS.has(id)) return id;
const err = new Error(`dancer must be one of 1, 2, 3, 4 — got "${raw}"`);
@@ -130,6 +222,36 @@ function pickDancer(raw) {
throw err;
}
+/**
+ * Build the ticket body returned on a settled tip. Pure — no I/O. Exported
+ * so tests can exercise the full ticket shape without going through the
+ * paidEndpoint HTTP wrapper.
+ */
+export function buildTicket({ dancer, style, now = new Date(), payer = null, requirement = null, ticketId = null }) {
+ const ends = new Date(now.getTime() + style.durationSec * 1000);
+ const ticket = {
+ ok: true,
+ ticketId: ticketId ?? crypto.randomUUID(),
+ dancer,
+ dance: style.key,
+ clip: style.clip,
+ label: style.label,
+ loop: style.loop,
+ durationSec: style.durationSec,
+ track: style.track,
+ startsAt: now.toISOString(),
+ endsAt: ends.toISOString(),
+ payer,
+ network: requirement?.network ?? null,
+ amountAtomics: requirement?.amount ?? null,
+ asset: requirement?.asset ?? null,
+ };
+ if (style.sequence) ticket.sequence = style.sequence;
+ return ticket;
+}
+
+export const BAZAAR_SCHEMA = BAZAAR;
+
export default paidEndpoint({
route: ROUTE,
method: 'GET',
@@ -140,26 +262,35 @@ export default paidEndpoint({
async handler({ req, requirement, payer }) {
const dancer = pickDancer(req.query?.dancer);
const style = pickStyle(req.query?.dance);
-
+ const ticketId = crypto.randomUUID();
const now = new Date();
- const ends = new Date(now.getTime() + style.durationSec * 1000);
-
- return {
- ok: true,
- ticketId: crypto.randomUUID(),
+ const ticket = buildTicket({
dancer,
- dance: style.key,
- clip: style.clip,
- label: style.label,
- loop: style.loop,
- durationSec: style.durationSec,
- track: style.track,
- startsAt: now.toISOString(),
- endsAt: ends.toISOString(),
- payer: payer ?? null,
- network: requirement?.network ?? null,
- amountAtomics: requirement?.amount ?? null,
- asset: requirement?.asset ?? null,
- };
+ style,
+ now,
+ ticketId,
+ payer: payer ?? null,
+ requirement,
+ });
+
+ // Fire-and-forget: the caller has already paid + the payment is settled
+ // by the time we reach this handler. A Neon hiccup must not surface as
+ // a 5xx on the dance-tip response — the /api/club/tips backfill will
+ // recover from a missing row at worst. Sequence steps aren't persisted
+ // — they're deterministic from `dance` + STYLES — but `clip` holds the
+ // first step's clip so the live-feed UI has something to display.
+ sql`
+ insert into club_tips
+ (ticket_id, dancer, dance, clip, label, payer, network,
+ amount_atomics, asset, started_at, ends_at)
+ values
+ (${ticketId}, ${ticket.dancer}, ${ticket.dance}, ${ticket.clip}, ${ticket.label},
+ ${ticket.payer}, ${ticket.network},
+ ${ticket.amountAtomics}, ${ticket.asset},
+ ${ticket.startsAt}, ${ticket.endsAt})
+ on conflict (ticket_id) do nothing
+ `.catch((err) => console.error('[club-tips] insert failed', err?.message || err));
+
+ return ticket;
},
});
diff --git a/pages/club.html b/pages/club.html
index a5f70c9bb..9a8bd6647 100644
--- a/pages/club.html
+++ b/pages/club.html
@@ -139,6 +139,22 @@
border-color: rgba(74, 214, 255, 0.32);
color: #cdeefe;
}
+ .club-pill-toggle {
+ appearance: none;
+ cursor: pointer;
+ font: inherit;
+ font-weight: 600;
+ color: var(--text);
+ background: rgba(255, 138, 59, 0.12);
+ border: 1px solid rgba(255, 138, 59, 0.32);
+ transition: filter 0.12s ease, background 0.12s ease;
+ }
+ .club-pill-toggle:hover { filter: brightness(1.1); }
+ .club-pill-toggle[aria-pressed="true"] {
+ background: rgba(124, 93, 146, 0.18);
+ border-color: rgba(124, 93, 146, 0.38);
+ color: var(--text-3);
+ }
/* ── Stage (3D canvas) ─────────────────────────────── */
#club-stage {
@@ -397,6 +413,117 @@
text-align: center;
padding: 12px 0;
}
+ .club-feed-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ }
+ .club-feed-status {
+ font-size: 10.5px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ padding: 2px 7px;
+ border-radius: 999px;
+ border: 1px solid var(--border);
+ color: var(--text-3);
+ background: rgba(255, 255, 255, 0.03);
+ }
+ .club-feed-status[data-kind="paused"] {
+ color: #ffb74a;
+ border-color: rgba(255, 183, 74, 0.5);
+ background: rgba(255, 183, 74, 0.08);
+ }
+ .club-feed-status[data-kind="error"] {
+ color: #ff6b81;
+ border-color: rgba(255, 107, 129, 0.5);
+ background: rgba(255, 107, 129, 0.08);
+ }
+
+ /* ── Leaderboard ──────────────────────────────────── */
+ .club-lb-tabs {
+ display: flex;
+ gap: 4px;
+ margin-bottom: 10px;
+ }
+ .club-lb-tab {
+ appearance: none;
+ border: 1px solid var(--border);
+ background: rgba(255, 255, 255, 0.02);
+ color: var(--text-2);
+ font: inherit;
+ font-size: 11px;
+ font-weight: 600;
+ padding: 5px 10px;
+ border-radius: 999px;
+ cursor: pointer;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ transition: filter 0.12s ease, color 0.12s ease;
+ }
+ .club-lb-tab:hover { color: var(--text); }
+ .club-lb-tab.is-active {
+ background: rgba(255, 59, 214, 0.16);
+ border-color: var(--border-strong);
+ color: var(--text);
+ }
+ #club-lb-rows {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ min-height: 32px;
+ }
+ .club-lb-row {
+ display: grid;
+ grid-template-columns: 22px 1fr auto auto;
+ gap: 8px;
+ align-items: center;
+ font-size: 12px;
+ padding: 7px 8px;
+ border-radius: 7px;
+ background: rgba(255, 255, 255, 0.02);
+ }
+ .club-lb-row.has-unpaid {
+ background: rgba(255, 59, 214, 0.06);
+ }
+ .club-lb-rank {
+ color: var(--text-3);
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 11px;
+ text-align: right;
+ }
+ .club-lb-name {
+ color: var(--text);
+ font-weight: 600;
+ }
+ .club-lb-name small {
+ display: block;
+ font-size: 10.5px;
+ color: var(--text-3);
+ font-weight: 500;
+ letter-spacing: 0.02em;
+ }
+ .club-lb-amt {
+ color: var(--accent);
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 11.5px;
+ font-weight: 600;
+ text-align: right;
+ }
+ .club-lb-tips {
+ color: var(--text-3);
+ font-size: 10.5px;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ text-align: right;
+ }
+ .club-lb-empty {
+ font-size: 12px;
+ color: var(--text-3);
+ font-style: italic;
+ text-align: center;
+ padding: 12px 0;
+ }
/* ── Responsive ─────────────────────────────────────── */
@media (max-width: 800px) {
@@ -431,12 +558,19 @@
<span class="spacer"></span>
<span class="club-pill">$0.001 / dance</span>
<span class="club-pill club-pill-blue">x402 · Base &amp; Solana</span>
+ <button
+ id="club-audio-toggle"
+ type="button"
+ class="club-pill club-pill-toggle"
+ aria-pressed="false"
+ title="Toggle club audio (mute)"
+ >🔊 Audio on</button>
</header>
<!-- STAGE -->
<main id="club-stage">
<canvas id="club-canvas"></canvas>
- <div id="club-status" hidden>Loading…</div>
+ <div id="club-status" role="status" aria-live="polite" hidden>Loading…</div>
</main>
<!-- RIGHT PANEL -->
@@ -464,7 +598,22 @@
</section>
<section class="club-section">
- <h2>Live tips</h2>
+ <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>
+ </div>
+ <div id="club-lb-rows">
+ <div class="club-lb-empty">Loading…</div>
+ </div>
+ </section>
+
+ <section class="club-section">
+ <div class="club-feed-head">
+ <h2>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>
diff --git a/public/animations/LICENSES.md b/public/animations/LICENSES.md
new file mode 100644
index 000000000..399ae5214
--- /dev/null
+++ b/public/animations/LICENSES.md
@@ -0,0 +1,92 @@
+# Animation clip licensing
+
+This file records the upstream source and license for every clip in
+`/public/animations/clips/`. Each entry uses the canonical-skeleton JSON
+emitted by [`scripts/build-animations.mjs`](../../scripts/build-animations.mjs)
+from a source FBX.
+
+## Mixamo (commercial use OK)
+
+All clips below were exported from [mixamo.com](https://www.mixamo.com/) under
+an authenticated Adobe Creative Cloud account. Mixamo's terms allow free
+commercial use of exported animations as part of a product (Mixamo Terms of
+Use §2 — characters and animations may be used in personal, commercial, or
+non-profit projects).
+
+| Clip name in manifest | Mixamo source | Notes |
+|---|---|---|
+| `idle` | Idle | trim |
+| `walk` | Walking | trim |
+| `dance` | Hip Hop Dancing | loop |
+| `rumba` | Rumba Dancing | loop |
+| `silly` | Silly Dancing | loop |
+| `thriller` | Thriller Part 2 | loop |
+| `capoeira` | Capoeira | loop |
+| `kiss` | Blow A Kiss | — |
+| `pray` | Praying | — |
+| `wave` | Waving | — |
+| `taunt` | Taunt | — |
+| `angry` | Angry Gesture | — |
+| `celebrate` | Cheering | — |
+| `reaction` | Surprised | — |
+| `defeated` | Defeated | — |
+| `dying` | Dying | — |
+| `falling` | Falling | — |
+| `falltolanding` | Falling To Landing | — |
+| `jump` | Jumping | — |
+| `jumpdown` | Jump Down | — |
+| `jumpdown2` | Jump Down (Light) | — |
+| `jumpdown3` | Jump Down (Heavy) | — |
+| `header` | Soccer Header | — |
+| `goalkeeper` | Goalkeeper Save | — |
+| `dodge` | Dodging | — |
+| `stepback` | Step Back | — |
+| `shoved` | Pushed To Floor | — |
+| `coverstand` | Cover Stand | — |
+| `removing` | Standup Cover | — |
+| `standup` | Standing Up | — |
+| `sitclap` | Sitting Clap | — |
+| `sitidle` | Sitting Idle | — |
+| `sitlaugh` | Sitting Laughing | — |
+| `downdog` | Down Dog | — |
+
+To add a new Mixamo clip:
+
+1. Log into Mixamo, find the animation, choose **In Place** and **Without Skin**,
+ download as FBX (binary, 30fps).
+2. Drop the FBX into the source directory consumed by
+ [scripts/build-animations.mjs](../../scripts/build-animations.mjs).
+3. Run `npm run build:animations` to retarget to the canonical skeleton and
+ emit the JSON under `/public/animations/clips/`.
+4. Register the clip in [`/public/animations/manifest.json`](./manifest.json)
+ with a `name`, `url`, `label`, `icon`, and `loop` flag.
+5. Add a row to the table above with the Mixamo source name.
+
+## Custom mocap
+
+> _No custom-mocap clips have shipped yet._
+
+When a non-Mixamo source lands here (custom recording, third-party studio,
+etc.), add a section below covering: the clip name, the licensor, the license
+terms (commercial use, attribution requirements, derivative works), and a
+link to the signed agreement or storefront receipt.
+
+## Pole choreography (pending)
+
+The `/api/x402/dance-tip` endpoint advertises three pole choreography styles
+— `spin`, `climb`, `combo` — that chain the following clip names:
+
+- `pole-walk-on`
+- `pole-spin`
+- `pole-climb`
+- `pole-invert`
+- `pole-floorwork`
+- `pole-bow`
+
+These clips are **not yet shipped**. Until the source FBX (Mixamo "Strut Walk",
+"Pole Spin", "Floor Work", "Bow" — and custom mocap for `pole-climb` /
+`pole-invert`) lands and `npm run build:animations` regenerates them, a tip
+with `dance=spin|climb|combo` will pay successfully and the dancer will walk
+on stage, but `AnimationManager.crossfadeTo` will warn that the clip is
+unavailable and skip the missing step. Add the entries to the table above
+when the FBX sources are committed.
diff --git a/public/club/audio/LICENSES.md b/public/club/audio/LICENSES.md
new file mode 100644
index 000000000..856b73e94
--- /dev/null
+++ b/public/club/audio/LICENSES.md
@@ -0,0 +1,54 @@
+# /club audio — provenance and licensing
+
+All seven loops in this directory were synthesised from scratch with
+ffmpeg's `lavfi` filtergraph (sine + noise primitives, no third-party
+samples). The source recipe lives at
+[`/scripts/build-club-audio.mjs`](../../../scripts/build-club-audio.mjs)
+and re-running `node scripts/build-club-audio.mjs` regenerates these
+files byte-for-byte.
+
+Because no external sample material was used, three.ws holds full
+copyright on these audio files and dedicates them to the public domain
+under **Creative Commons CC0 1.0 Universal**
+(https://creativecommons.org/publicdomain/zero/1.0/). You can use them
+for any purpose, with or without attribution.
+
+| File | Source | License | Length | Notes |
+| -------------------- | ------------------------------------------------------------- | ------- | --------------------- | --------------------------------------------------------------------- |
+| `ambience.{ogg,mp3}` | Authored — pink noise bed + slow LFO + low rumble | CC0 1.0 | ~60 s loop | Crowd / room ambience. Constant level, no rhythmic content. |
+| `rumba.{ogg,mp3}` | Authored — 100 BPM 3-2 clave, triangle melody, sine bass | CC0 1.0 | ~9.6 s loop (4 bars) | Light Latin groove for the Rumba clip. |
+| `thriller.{ogg,mp3}` | Authored — 120 BPM minor groove, detuned drone, sawtooth lead | CC0 1.0 | ~8.0 s loop (4 bars) | Dark cinematic bed for the Thriller clip. |
+| `hiphop.{ogg,mp3}` | Authored — 95 BPM boom-bap kit + bassline + stab lead | CC0 1.0 | ~10.1 s loop (4 bars) | Classic hip-hop pocket for the Hip Hop clip. |
+| `capoeira.{ogg,mp3}` | Authored — 110 BPM berimbau ostinato + atabaque approximation | CC0 1.0 | ~8.7 s loop (4 bars) | Brazilian roda rhythm for the Capoeira clip. |
+| `silly.{ogg,mp3}` | Authored — 130 BPM major-key bounce + woodblock + cartoon arp | CC0 1.0 | ~7.4 s loop (4 bars) | Playful bed for the Silly clip. |
+| `pole.{ogg,mp3}` | Authored — 105 BPM neutral groove + sine pad | CC0 1.0 | ~9.1 s loop (4 bars) | Generic backing track for pole choreography clips (spin/climb/combo). |
+
+## Mastering notes
+
+Every track is rendered to an integer number of beats so it loops
+sample-clean at the seam. `dynaudnorm` (`g=11:p=0.78`) brings peaks
+down to roughly −6 dBFS — enough headroom for the post-FX bloom-era
+sidechain and for the master gain at 0.75 in
+[`src/club-audio.js`](../../../src/club-audio.js) without clipping the
+output bus.
+
+Encoder targets:
+
+- **MP3:** mono, 44.1 kHz, 192 kbit/s, libmp3lame.
+- **OGG Vorbis:** stereo, 44.1 kHz, qscale 4, libvorbis.
+
+`<audio>` and `decodeAudioData()` consumers fall through to MP3 when
+their browser lacks Vorbis (older Safari builds). The mixer in
+`src/club-audio.js` requests `.ogg` first and falls back to `.mp3` on
+fetch/decode failure — see `loadBuffer()`.
+
+## Regenerating
+
+```sh
+node scripts/build-club-audio.mjs
+```
+
+Requires `ffmpeg` ≥ 4.4 built with libmp3lame + libvorbis (Ubuntu's
+default `apt install ffmpeg` is sufficient). Output is deterministic
+within ffmpeg's encoder limits, so committed files only change when
+the recipe changes.
diff --git a/public/club/audio/ambience.mp3 b/public/club/audio/ambience.mp3
new file mode 100644
index 000000000..49185b97b
Binary files /dev/null and b/public/club/audio/ambience.mp3 differ
diff --git a/public/club/audio/ambience.ogg b/public/club/audio/ambience.ogg
new file mode 100644
index 000000000..a9478809e
Binary files /dev/null and b/public/club/audio/ambience.ogg differ
diff --git a/public/club/audio/capoeira.mp3 b/public/club/audio/capoeira.mp3
new file mode 100644
index 000000000..14a506040
Binary files /dev/null and b/public/club/audio/capoeira.mp3 differ
diff --git a/public/club/audio/capoeira.ogg b/public/club/audio/capoeira.ogg
new file mode 100644
index 000000000..c3bf8087b
Binary files /dev/null and b/public/club/audio/capoeira.ogg differ
diff --git a/public/club/audio/hiphop.mp3 b/public/club/audio/hiphop.mp3
new file mode 100644
index 000000000..82498d1ac
Binary files /dev/null and b/public/club/audio/hiphop.mp3 differ
diff --git a/public/club/audio/hiphop.ogg b/public/club/audio/hiphop.ogg
new file mode 100644
index 000000000..3f91ea5fc
Binary files /dev/null and b/public/club/audio/hiphop.ogg differ
diff --git a/public/club/audio/pole.mp3 b/public/club/audio/pole.mp3
new file mode 100644
index 000000000..fdefe8592
Binary files /dev/null and b/public/club/audio/pole.mp3 differ
diff --git a/public/club/audio/pole.ogg b/public/club/audio/pole.ogg
new file mode 100644
index 000000000..4c2036aec
Binary files /dev/null and b/public/club/audio/pole.ogg differ
diff --git a/public/club/audio/rumba.mp3 b/public/club/audio/rumba.mp3
new file mode 100644
index 000000000..1fdd4db58
Binary files /dev/null and b/public/club/audio/rumba.mp3 differ
diff --git a/public/club/audio/rumba.ogg b/public/club/audio/rumba.ogg
new file mode 100644
index 000000000..632802422
Binary files /dev/null and b/public/club/audio/rumba.ogg differ
diff --git a/public/club/audio/silly.mp3 b/public/club/audio/silly.mp3
new file mode 100644
index 000000000..bddf705df
Binary files /dev/null and b/public/club/audio/silly.mp3 differ
diff --git a/public/club/audio/silly.ogg b/public/club/audio/silly.ogg
new file mode 100644
index 000000000..27b5418c9
Binary files /dev/null and b/public/club/audio/silly.ogg differ
diff --git a/public/club/audio/thriller.mp3 b/public/club/audio/thriller.mp3
new file mode 100644
index 000000000..f999f0f3c
Binary files /dev/null and b/public/club/audio/thriller.mp3 differ
diff --git a/public/club/audio/thriller.ogg b/public/club/audio/thriller.ogg
new file mode 100644
index 000000000..05cccfc24
Binary files /dev/null and b/public/club/audio/thriller.ogg differ
diff --git a/public/club/props/pole.glb b/public/club/props/pole.glb
new file mode 100644
index 000000000..07e0f9792
Binary files /dev/null and b/public/club/props/pole.glb differ
diff --git a/public/club/props/stage.glb b/public/club/props/stage.glb
new file mode 100644
index 000000000..7d4d8a615
Binary files /dev/null and b/public/club/props/stage.glb differ
diff --git a/public/sitemap.xml b/public/sitemap.xml
index 4efcadc6b..e53ec261c 100644
--- a/public/sitemap.xml
+++ b/public/sitemap.xml
@@ -2,277 +2,277 @@
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://three.ws/</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>https://three.ws/discover</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>daily</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>https://three.ws/gallery</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/walk</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>monthly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/marketplace</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/community</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/sitemap</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.4</priority>
</url>
<url>
<loc>https://three.ws/create</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>https://three.ws/app</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>monthly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/validation</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/studio</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/artifact</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>monthly</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>https://three.ws/widgets</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/hydrate</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/features</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/launchpad</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/walkaround</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/brain</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/lipsync</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/lipsync/mic</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/avatar-artifact</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>monthly</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>https://three.ws/pay</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>https://three.ws/pumpfun</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/pump-live</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>daily</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/pump-dashboard</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/strategy-lab</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/vanity-wallet</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/eth-vanity</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/pump-visualizer</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/chat</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/agent</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/agents</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>daily</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/reputation</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/login</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>yearly</changefreq>
<priority>0.4</priority>
</url>
<url>
<loc>https://three.ws/register</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>yearly</changefreq>
<priority>0.4</priority>
</url>
<url>
<loc>https://three.ws/forgot-password</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>yearly</changefreq>
<priority>0.2</priority>
</url>
<url>
<loc>https://three.ws/docs</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>https://three.ws/docs/quick-start</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/docs/agent-system</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
</url>
<url>
<loc>https://three.ws/docs/erc8004</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
</url>
<url>
<loc>https://three.ws/docs/embedding</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
</url>
<url>
<loc>https://three.ws/docs/web-component</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
</url>
<url>
<loc>https://three.ws/docs/mcp</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
</url>
<url>
<loc>https://three.ws/docs/skills</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
</url>
<url>
<loc>https://three.ws/docs/widgets</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
</url>
<url>
<loc>https://three.ws/docs/api-reference</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
</url>
<url>
<loc>https://three.ws/docs/sdk</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
</url>
<url>
<loc>https://three.ws/docs/listings</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>monthly</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>https://three.ws/tutorials</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
</url>
<url>
<loc>https://three.ws/blog</loc>
@@ -300,13 +300,13 @@
</url>
<url>
<loc>https://three.ws/legal/privacy</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>yearly</changefreq>
<priority>0.2</priority>
</url>
<url>
<loc>https://three.ws/legal/tos</loc>
- <lastmod>2026-05-19</lastmod>
+ <lastmod>2026-05-21</lastmod>
<changefreq>yearly</changefreq>
<priority>0.2</priority>
</url>
diff --git a/scripts/animations.config.json b/scripts/animations.config.json
index f91db7de5..86a9168c1 100644
--- a/scripts/animations.config.json
+++ b/scripts/animations.config.json
@@ -181,5 +181,47 @@
"label": "Downward Dog",
"icon": "🧘",
"loop": true
+ },
+ {
+ "name": "pole-walk-on",
+ "source": "Strut Walking.fbx",
+ "label": "Pole Walk On",
+ "icon": "🚶‍♀️",
+ "loop": false
+ },
+ {
+ "name": "pole-spin",
+ "source": "Pole Spin.fbx",
+ "label": "Pole Spin",
+ "icon": "🌀",
+ "loop": true
+ },
+ {
+ "name": "pole-climb",
+ "source": "Pole Climb.fbx",
+ "label": "Pole Climb",
+ "icon": "🧗‍♀️",
+ "loop": false
+ },
+ {
+ "name": "pole-invert",
+ "source": "Pole Invert.fbx",
+ "label": "Pole Invert",
+ "icon": "🙃",
+ "loop": true
+ },
+ {
+ "name": "pole-floorwork",
+ "source": "Floor Work.fbx",
+ "label": "Pole Floor Work",
+ "icon": "🩰",
+ "loop": true
+ },
+ {
+ "name": "pole-bow",
+ "source": "Bow.fbx",
+ "label": "Pole Bow",
+ "icon": "🪩",
+ "loop": false
}
]
diff --git a/scripts/build-club-audio.mjs b/scripts/build-club-audio.mjs
new file mode 100644
index 000000000..34bcbd552
--- /dev/null
+++ b/scripts/build-club-audio.mjs
@@ -0,0 +1,597 @@
+#!/usr/bin/env node
+//
+// scripts/build-club-audio.mjs
+// =============================================================================
+// Synthesise the seven /club audio loops (six dance styles + crowd ambience)
+// and encode each one to both `.ogg` (stereo Vorbis q4) and `.mp3` (mono
+// 192 kbit) under public/club/audio/. Run via `node scripts/build-club-audio.mjs`.
+//
+// Why we author locally instead of shipping third-party samples:
+// The /club rails (CLAUDE.md) require real licensed audio committed to the
+// repo. The cleanest, license-unencumbered way to satisfy that is to
+// generate the loops from scratch with ffmpeg's `lavfi` filtergraph — the
+// resulting WAVs are wholly authored here, so we can release them CC0 (see
+// public/club/audio/LICENSES.md). No external samples, no attribution
+// ambiguity, no >2 MB asset bloat.
+//
+// Synthesis approach:
+// Each track is a short rhythmic bed assembled from oscillator + noise
+// primitives ffmpeg already ships (`sine`, `anoisesrc`, `tremolo`, `aecho`,
+// `bandpass`/`lowpass` filters). We avoid speed/atempo on `aevalsrc` because
+// precise loop length matters — every track is rendered to an exact integer
+// number of beats and ffmpeg `-t` is set so the final waveform loops
+// click-free at the seam. Peaks are limited to about –6 dBFS via
+// `dynaudnorm` so the master bus has headroom for the bloom-era postfx.
+//
+// This script is idempotent — re-running overwrites the existing files with
+// byte-identical output (within ffmpeg's deterministic encoder limits).
+
+import { spawn } from 'node:child_process';
+import { mkdir, stat } from 'node:fs/promises';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROOT = resolve(__dirname, '..');
+const OUT_DIR = resolve(ROOT, 'public/club/audio');
+
+const SAMPLE_RATE = 44_100;
+
+// ─── Filtergraph building blocks ────────────────────────────────────────────
+//
+// Each helper returns a single ffmpeg `-filter_complex` snippet that produces
+// one labelled audio stream. Streams are mixed at the end into [out] which is
+// what we encode.
+
+// 4/4 kick pattern at the given BPM. We model the kick as an exponentially
+// decaying sine wave (60 Hz fundamental) gated by a click envelope.
+function kickPattern(bpm, bars = 4) {
+ const beatSec = 60 / bpm;
+ const totalSec = beatSec * 4 * bars;
+ // 16th-note grid: hits on every quarter (1, 5, 9, 13). Express as
+ // `aevalsrc` arithmetic so a single source covers the loop.
+ const expr = `0.85*sin(2*PI*60*t)*exp(-12*mod(t,${beatSec.toFixed(6)}))`;
+ return `aevalsrc='${expr}':d=${totalSec.toFixed(6)}:s=${SAMPLE_RATE},lowpass=f=160`;
+}
+
+// Snare/clap on beats 2 and 4. Bandpassed noise burst with a sharp decay.
+function snarePattern(bpm, bars = 4) {
+ const beatSec = 60 / bpm;
+ const totalSec = beatSec * 4 * bars;
+ // Trigger only on offset half of each beat pair (i.e. beats 2/4 of a 4-beat bar).
+ // Use a 2-beat repeating envelope: hit at t mod (2*beat) ≈ beat.
+ const period = (beatSec * 2).toFixed(6);
+ const offset = beatSec.toFixed(6);
+ const expr = `exp(-26*if(lt(mod(t-${offset},${period}),0),mod(t-${offset},${period})+${period},mod(t-${offset},${period})))*0.55`;
+ return `anoisesrc=d=${totalSec.toFixed(6)}:r=${SAMPLE_RATE}:a=0.85:c=pink,bandpass=f=1800:w=900,volume='${expr}':eval=frame`;
+}
+
+// Closed hi-hat 8ths — bright noise burst on every off-eighth.
+function hatPattern(bpm, bars = 4) {
+ const beatSec = 60 / bpm;
+ const totalSec = beatSec * 4 * bars;
+ const eighth = (beatSec / 2).toFixed(6);
+ const expr = `exp(-60*mod(t,${eighth}))*0.18`;
+ return `anoisesrc=d=${totalSec.toFixed(6)}:r=${SAMPLE_RATE}:a=0.7:c=white,highpass=f=6000,volume='${expr}':eval=frame`;
+}
+
+// Pure sine bassline — accepts an array of {beat, freq} hits.
+function basslinePattern(bpm, bars, notes) {
+ const beatSec = 60 / bpm;
+ const totalSec = beatSec * 4 * bars;
+ // Build a piecewise frequency expression over the loop length.
+ // Each note is a half-beat-long ramp into the next.
+ // Use a simple cascade: collect (start, freq) pairs and fold them into
+ // nested `if(gte(t, t0)*lt(t, t1), freq, …)`.
+ const sortedNotes = [...notes].sort((a, b) => a.beat - b.beat);
+ let freqExpr = '0';
+ for (let i = sortedNotes.length - 1; i >= 0; i--) {
+ const n = sortedNotes[i];
+ const t0 = (n.beat * beatSec).toFixed(6);
+ freqExpr = `if(gte(t,${t0}),${n.freq.toFixed(3)},${freqExpr})`;
+ }
+ const expr = `0.30*sin(2*PI*(${freqExpr})*t)`;
+ return `aevalsrc='${expr}':d=${totalSec.toFixed(6)}:s=${SAMPLE_RATE},lowpass=f=320`;
+}
+
+// Lead synth — square-like saw, useful for thriller/silly/hiphop melodies.
+function leadPattern(bpm, bars, notes, gain = 0.18) {
+ const beatSec = 60 / bpm;
+ const totalSec = beatSec * 4 * bars;
+ const sortedNotes = [...notes].sort((a, b) => a.beat - b.beat);
+ let freqExpr = '0';
+ let gateExpr = '0';
+ for (let i = sortedNotes.length - 1; i >= 0; i--) {
+ const n = sortedNotes[i];
+ const t0 = (n.beat * beatSec).toFixed(6);
+ const t1 = ((n.beat + (n.length || 0.5)) * beatSec).toFixed(6);
+ freqExpr = `if(gte(t,${t0}),${n.freq.toFixed(3)},${freqExpr})`;
+ gateExpr = `if(gte(t,${t0})*lt(t,${t1}),1,${gateExpr})`;
+ }
+ const expr = `${gain.toFixed(3)}*(2*((t*(${freqExpr}))-floor(0.5+t*(${freqExpr}))))*(${gateExpr})`;
+ return `aevalsrc='${expr}':d=${totalSec.toFixed(6)}:s=${SAMPLE_RATE},lowpass=f=4200`;
+}
+
+// Triangle-wave lead for softer styles (rumba/capoeira).
+function triadPattern(bpm, bars, notes, gain = 0.16) {
+ const beatSec = 60 / bpm;
+ const totalSec = beatSec * 4 * bars;
+ const sortedNotes = [...notes].sort((a, b) => a.beat - b.beat);
+ let freqExpr = '0';
+ let gateExpr = '0';
+ for (let i = sortedNotes.length - 1; i >= 0; i--) {
+ const n = sortedNotes[i];
+ const t0 = (n.beat * beatSec).toFixed(6);
+ const t1 = ((n.beat + (n.length || 0.5)) * beatSec).toFixed(6);
+ freqExpr = `if(gte(t,${t0}),${n.freq.toFixed(3)},${freqExpr})`;
+ gateExpr = `if(gte(t,${t0})*lt(t,${t1}),1,${gateExpr})`;
+ }
+ // Triangle ≈ 2/π * arcsin(sin(2πft)); approximate with a phase-folded sine.
+ const expr = `${gain.toFixed(3)}*((2/PI)*asin(sin(2*PI*(${freqExpr})*t)))*(${gateExpr})`;
+ return `aevalsrc='${expr}':d=${totalSec.toFixed(6)}:s=${SAMPLE_RATE},lowpass=f=3500`;
+}
+
+// ─── Style track recipes ─────────────────────────────────────────────────────
+
+// Each entry yields a filter_complex string that produces a single mixed
+// stream labeled `[mix]` at SAMPLE_RATE. The loop length must be an integer
+// number of beats so the seam is sample-clean.
+
+function ambienceRecipe() {
+ // 60-second crowd bed: pink-noise "room tone" + slow tremolo (chatter
+ // rhythm) + a far-off low rumble that suggests low-end PA energy. No
+ // rhythmic content so it never fights the dance loops it ducks under.
+ const totalSec = 60;
+ const parts = [
+ // Body — pink noise with a gentle lowpass for warmth.
+ `anoisesrc=d=${totalSec}:r=${SAMPLE_RATE}:a=0.10:c=pink,bandpass=f=900:w=1400,tremolo=f=2.5:d=0.35[chatter]`,
+ // Low rumble — very slow LFO on a deep sine wave.
+ `aevalsrc='0.07*sin(2*PI*50*t)*(1+0.6*sin(2*PI*0.18*t))':d=${totalSec}:s=${SAMPLE_RATE},lowpass=f=120[rumble]`,
+ // Air movement — quiet high-frequency hiss for "room" presence.
+ `anoisesrc=d=${totalSec}:r=${SAMPLE_RATE}:a=0.04:c=white,highpass=f=4000[air]`,
+ ];
+ const graph = [
+ ...parts,
+ `[chatter][rumble][air]amix=inputs=3:duration=longest:normalize=0,dynaudnorm=g=11:p=0.78[mix]`,
+ ].join(';');
+ return { graph, durationSec: totalSec };
+}
+
+// HIP HOP — 95 BPM, two bars, classic boom-bap pattern with a low piano stab.
+function hiphopRecipe() {
+ const bpm = 95;
+ const bars = 4;
+ const beatSec = 60 / bpm;
+ const totalSec = beatSec * 4 * bars;
+ // Bass riff in A minor — root, fifth, flat-seven cycle.
+ const bass = basslinePattern(bpm, bars, [
+ { beat: 0, freq: 55.0 }, // A1
+ { beat: 2, freq: 65.4 }, // C2
+ { beat: 4, freq: 73.4 }, // D2
+ { beat: 6, freq: 49.0 }, // G1
+ { beat: 8, freq: 55.0 },
+ { beat: 10, freq: 65.4 },
+ { beat: 12, freq: 73.4 },
+ { beat: 14, freq: 49.0 },
+ ]);
+ // Lead — short stabs on the off-beats.
+ const lead = leadPattern(
+ bpm,
+ bars,
+ [
+ { beat: 1.5, freq: 220.0, length: 0.25 },
+ { beat: 3.5, freq: 261.6, length: 0.25 },
+ { beat: 5.5, freq: 293.7, length: 0.25 },
+ { beat: 7.5, freq: 196.0, length: 0.25 },
+ { beat: 9.5, freq: 220.0, length: 0.25 },
+ { beat: 11.5, freq: 261.6, length: 0.25 },
+ { beat: 13.5, freq: 293.7, length: 0.25 },
+ { beat: 15.5, freq: 196.0, length: 0.25 },
+ ],
+ 0.13,
+ );
+ const graph = [
+ `${kickPattern(bpm, bars)}[kick]`,
+ `${snarePattern(bpm, bars)}[snare]`,
+ `${hatPattern(bpm, bars)}[hat]`,
+ `${bass}[bass]`,
+ `${lead}[lead]`,
+ `[kick][snare][hat][bass][lead]amix=inputs=5:duration=longest:normalize=0,aecho=0.6:0.3:60:0.25,dynaudnorm=g=11:p=0.78[mix]`,
+ ].join(';');
+ return { graph, durationSec: totalSec };
+}
+
+// RUMBA — 100 BPM, syncopated clave, triangle melody, warm bass.
+function rumbaRecipe() {
+ const bpm = 100;
+ const bars = 4;
+ const beatSec = 60 / bpm;
+ const totalSec = beatSec * 4 * bars;
+ const bass = basslinePattern(bpm, bars, [
+ { beat: 0, freq: 73.4 }, // D2
+ { beat: 1.5, freq: 110.0 }, // A2
+ { beat: 3, freq: 87.3 }, // F2
+ { beat: 4, freq: 73.4 },
+ { beat: 6, freq: 98.0 }, // G2
+ { beat: 8, freq: 73.4 },
+ { beat: 9.5, freq: 110.0 },
+ { beat: 11, freq: 87.3 },
+ { beat: 12, freq: 73.4 },
+ { beat: 14, freq: 98.0 },
+ ]);
+ const lead = triadPattern(
+ bpm,
+ bars,
+ [
+ { beat: 0, freq: 293.7, length: 1.5 }, // D4
+ { beat: 1.5, freq: 440.0, length: 1.5 }, // A4
+ { beat: 3, freq: 349.2, length: 1 }, // F4
+ { beat: 4, freq: 293.7, length: 1.5 },
+ { beat: 5.5, freq: 392.0, length: 1.5 }, // G4
+ { beat: 7, freq: 349.2, length: 1 },
+ { beat: 8, freq: 293.7, length: 1.5 },
+ { beat: 9.5, freq: 440.0, length: 1.5 },
+ { beat: 11, freq: 349.2, length: 1 },
+ { beat: 12, freq: 293.7, length: 1.5 },
+ { beat: 13.5, freq: 392.0, length: 1.5 },
+ { beat: 15, freq: 349.2, length: 1 },
+ ],
+ 0.2,
+ );
+ // Clave — short percussive clicks (3-2 pattern) made from bandpassed noise.
+ const claveExpr = (() => {
+ const hits = [0, 1.5, 3, 4, 6].map((b) => (b * beatSec).toFixed(6));
+ const env = hits.map((t) => `exp(-90*if(lt(t-${t},0),9999,t-${t}))`).join('+');
+ return `(${env})*0.45`;
+ })();
+ const clave = `anoisesrc=d=${totalSec.toFixed(6)}:r=${SAMPLE_RATE}:a=0.7:c=pink,bandpass=f=2400:w=1000,volume='${claveExpr}':eval=frame`;
+ const graph = [
+ `${kickPattern(bpm, bars)}[kick]`,
+ `${clave}[clave]`,
+ `${bass}[bass]`,
+ `${lead}[lead]`,
+ `[kick][clave][bass][lead]amix=inputs=4:duration=longest:normalize=0,dynaudnorm=g=11:p=0.78[mix]`,
+ ].join(';');
+ return { graph, durationSec: totalSec };
+}
+
+// THRILLER — 120 BPM minor groove with a low droning synth + chromatic stabs.
+function thrillerRecipe() {
+ const bpm = 120;
+ const bars = 4;
+ const beatSec = 60 / bpm;
+ const totalSec = beatSec * 4 * bars;
+ const bass = basslinePattern(bpm, bars, [
+ { beat: 0, freq: 55.0 }, // A1
+ { beat: 4, freq: 58.3 }, // Bb1
+ { beat: 8, freq: 55.0 },
+ { beat: 12, freq: 49.0 }, // G1
+ ]);
+ const lead = leadPattern(
+ bpm,
+ bars,
+ [
+ { beat: 0, freq: 220.0, length: 0.5 },
+ { beat: 1, freq: 233.1, length: 0.5 },
+ { beat: 2, freq: 220.0, length: 0.5 },
+ { beat: 3, freq: 196.0, length: 1.0 },
+ { beat: 4.5, freq: 261.6, length: 0.5 },
+ { beat: 5.5, freq: 220.0, length: 1.0 },
+ { beat: 8, freq: 220.0, length: 0.5 },
+ { beat: 9, freq: 233.1, length: 0.5 },
+ { beat: 10, freq: 220.0, length: 0.5 },
+ { beat: 11, freq: 196.0, length: 1.0 },
+ { beat: 12.5, freq: 261.6, length: 0.5 },
+ { beat: 13.5, freq: 220.0, length: 1.5 },
+ ],
+ 0.16,
+ );
+ // Drone — slow detuned sine for that "haunting" vibe.
+ const drone = `aevalsrc='0.10*(sin(2*PI*110*t)+sin(2*PI*110.6*t))':d=${totalSec.toFixed(6)}:s=${SAMPLE_RATE},lowpass=f=600`;
+ const graph = [
+ `${kickPattern(bpm, bars)}[kick]`,
+ `${snarePattern(bpm, bars)}[snare]`,
+ `${hatPattern(bpm, bars)}[hat]`,
+ `${bass}[bass]`,
+ `${lead}[lead]`,
+ `${drone}[drone]`,
+ `[kick][snare][hat][bass][lead][drone]amix=inputs=6:duration=longest:normalize=0,aecho=0.6:0.4:120:0.35,dynaudnorm=g=11:p=0.78[mix]`,
+ ].join(';');
+ return { graph, durationSec: totalSec };
+}
+
+// CAPOEIRA — 110 BPM, berimbau-style rhythmic ostinato. We approximate the
+// berimbau with a short metallic "twang" + bandpassed noise atabaque.
+function capoeiraRecipe() {
+ const bpm = 110;
+ const bars = 4;
+ const beatSec = 60 / bpm;
+ const totalSec = beatSec * 4 * bars;
+ // Berimbau ostinato — D / D_flat / D / open / ring pattern.
+ const lead = triadPattern(
+ bpm,
+ bars,
+ [
+ { beat: 0, freq: 196.0, length: 0.5 }, // G3 — "ring"
+ { beat: 1, freq: 174.6, length: 0.5 }, // F3
+ { beat: 2, freq: 196.0, length: 0.5 },
+ { beat: 3, freq: 130.8, length: 1.0 }, // C3 — open
+ { beat: 4, freq: 196.0, length: 0.5 },
+ { beat: 5, freq: 174.6, length: 0.5 },
+ { beat: 6, freq: 196.0, length: 0.5 },
+ { beat: 7, freq: 130.8, length: 1.0 },
+ { beat: 8, freq: 196.0, length: 0.5 },
+ { beat: 9, freq: 174.6, length: 0.5 },
+ { beat: 10, freq: 196.0, length: 0.5 },
+ { beat: 11, freq: 130.8, length: 1.0 },
+ { beat: 12, freq: 220.0, length: 0.5 },
+ { beat: 13, freq: 174.6, length: 0.5 },
+ { beat: 14, freq: 196.0, length: 0.5 },
+ { beat: 15, freq: 130.8, length: 1.0 },
+ ],
+ 0.22,
+ );
+ // Atabaque — low congas approximation on 1+3 of each bar.
+ const congaExpr = (() => {
+ const hits = [];
+ for (let bar = 0; bar < bars; bar++) {
+ hits.push(bar * 4 * beatSec, (bar * 4 + 2.5) * beatSec);
+ }
+ const env = hits
+ .map(
+ (t) =>
+ `exp(-18*if(lt(t-${t.toFixed(6)},0),9999,t-${t.toFixed(6)}))*sin(2*PI*120*t)`,
+ )
+ .join('+');
+ return `0.45*(${env})`;
+ })();
+ const conga = `aevalsrc='${congaExpr}':d=${totalSec.toFixed(6)}:s=${SAMPLE_RATE},lowpass=f=240`;
+ const graph = [
+ `${conga}[conga]`,
+ `${hatPattern(bpm, bars)}[hat]`,
+ `${lead}[lead]`,
+ `[conga][hat][lead]amix=inputs=3:duration=longest:normalize=0,dynaudnorm=g=11:p=0.78[mix]`,
+ ].join(';');
+ return { graph, durationSec: totalSec };
+}
+
+// SILLY — 130 BPM cartoonish bounce, major-key arpeggio, woodblock claps.
+function sillyRecipe() {
+ const bpm = 130;
+ const bars = 4;
+ const beatSec = 60 / bpm;
+ const totalSec = beatSec * 4 * bars;
+ const bass = basslinePattern(bpm, bars, [
+ { beat: 0, freq: 65.4 }, // C2
+ { beat: 1, freq: 98.0 }, // G2
+ { beat: 2, freq: 65.4 },
+ { beat: 3, freq: 87.3 }, // F2
+ { beat: 4, freq: 65.4 },
+ { beat: 5, freq: 98.0 },
+ { beat: 6, freq: 73.4 }, // D2
+ { beat: 7, freq: 87.3 },
+ { beat: 8, freq: 65.4 },
+ { beat: 9, freq: 98.0 },
+ { beat: 10, freq: 65.4 },
+ { beat: 11, freq: 87.3 },
+ { beat: 12, freq: 110.0 }, // A2
+ { beat: 13, freq: 98.0 },
+ { beat: 14, freq: 87.3 },
+ { beat: 15, freq: 73.4 },
+ ]);
+ const lead = leadPattern(
+ bpm,
+ bars,
+ [
+ { beat: 0, freq: 523.3, length: 0.5 }, // C5
+ { beat: 0.5, freq: 659.3, length: 0.5 },
+ { beat: 1, freq: 783.99, length: 0.5 },
+ { beat: 1.5, freq: 659.3, length: 0.5 },
+ { beat: 2, freq: 523.3, length: 0.5 },
+ { beat: 2.5, freq: 659.3, length: 0.5 },
+ { beat: 3, freq: 698.5, length: 1.0 },
+ { beat: 4, freq: 523.3, length: 0.5 },
+ { beat: 4.5, freq: 659.3, length: 0.5 },
+ { beat: 5, freq: 783.99, length: 0.5 },
+ { beat: 5.5, freq: 659.3, length: 0.5 },
+ { beat: 6, freq: 587.3, length: 1.0 },
+ { beat: 7, freq: 698.5, length: 1.0 },
+ { beat: 8, freq: 523.3, length: 0.5 },
+ { beat: 8.5, freq: 659.3, length: 0.5 },
+ { beat: 9, freq: 783.99, length: 0.5 },
+ { beat: 9.5, freq: 880.0, length: 0.5 },
+ { beat: 10, freq: 783.99, length: 0.5 },
+ { beat: 10.5, freq: 659.3, length: 0.5 },
+ { beat: 11, freq: 523.3, length: 1.0 },
+ { beat: 12, freq: 880.0, length: 0.5 },
+ { beat: 12.5, freq: 783.99, length: 0.5 },
+ { beat: 13, freq: 698.5, length: 0.5 },
+ { beat: 13.5, freq: 587.3, length: 0.5 },
+ { beat: 14, freq: 523.3, length: 1.5 },
+ ],
+ 0.15,
+ );
+ // Woodblock pop — single-cycle sine bursts on every quarter.
+ const woodExpr = (() => {
+ const hits = [];
+ for (let b = 0; b < 4 * bars; b++) hits.push(b * beatSec);
+ const env = hits
+ .map(
+ (t) =>
+ `exp(-90*if(lt(t-${t.toFixed(6)},0),9999,t-${t.toFixed(6)}))*sin(2*PI*1200*t)`,
+ )
+ .join('+');
+ return `0.18*(${env})`;
+ })();
+ const wood = `aevalsrc='${woodExpr}':d=${totalSec.toFixed(6)}:s=${SAMPLE_RATE},bandpass=f=1500:w=900`;
+ const graph = [
+ `${kickPattern(bpm, bars)}[kick]`,
+ `${wood}[wood]`,
+ `${bass}[bass]`,
+ `${lead}[lead]`,
+ `[kick][wood][bass][lead]amix=inputs=4:duration=longest:normalize=0,dynaudnorm=g=11:p=0.78[mix]`,
+ ].join(';');
+ return { graph, durationSec: totalSec };
+}
+
+// POLE — neutral 105 BPM groove for pole choreography (spin/climb/combo).
+// Lower-mid sine bass + filtered noise sweep so it works under any clip.
+function poleRecipe() {
+ const bpm = 105;
+ const bars = 4;
+ const beatSec = 60 / bpm;
+ const totalSec = beatSec * 4 * bars;
+ const bass = basslinePattern(bpm, bars, [
+ { beat: 0, freq: 65.4 },
+ { beat: 4, freq: 87.3 },
+ { beat: 8, freq: 73.4 },
+ { beat: 12, freq: 98.0 },
+ ]);
+ const pad = triadPattern(
+ bpm,
+ bars,
+ [
+ { beat: 0, freq: 261.6, length: 4 },
+ { beat: 4, freq: 349.2, length: 4 },
+ { beat: 8, freq: 293.7, length: 4 },
+ { beat: 12, freq: 392.0, length: 4 },
+ ],
+ 0.14,
+ );
+ const graph = [
+ `${kickPattern(bpm, bars)}[kick]`,
+ `${hatPattern(bpm, bars)}[hat]`,
+ `${bass}[bass]`,
+ `${pad}[pad]`,
+ `[kick][hat][bass][pad]amix=inputs=4:duration=longest:normalize=0,dynaudnorm=g=11:p=0.78[mix]`,
+ ].join(';');
+ return { graph, durationSec: totalSec };
+}
+
+// ─── Encoder pipeline ───────────────────────────────────────────────────────
+
+async function runFfmpeg(args, label) {
+ return new Promise((resolveP, reject) => {
+ const proc = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-y', ...args]);
+ let stderr = '';
+ proc.stderr.on('data', (b) => {
+ stderr += b.toString();
+ });
+ proc.on('error', reject);
+ proc.on('exit', (code) => {
+ if (code === 0) resolveP();
+ else reject(new Error(`ffmpeg ${label} failed (${code}): ${stderr || '<no stderr>'}`));
+ });
+ });
+}
+
+async function buildTrack(name, recipe) {
+ const { graph, durationSec } = recipe();
+ const mp3Path = resolve(OUT_DIR, `${name}.mp3`);
+ const oggPath = resolve(OUT_DIR, `${name}.ogg`);
+
+ // Mono 192k MP3 — small footprint for mobile.
+ await runFfmpeg(
+ [
+ '-filter_complex',
+ graph,
+ '-map',
+ '[mix]',
+ '-t',
+ String(durationSec),
+ '-ac',
+ '1',
+ '-ar',
+ String(SAMPLE_RATE),
+ '-c:a',
+ 'libmp3lame',
+ '-b:a',
+ '192k',
+ '-metadata',
+ `title=three.ws Pole Club — ${name}`,
+ '-metadata',
+ 'artist=three.ws',
+ '-metadata',
+ 'license=CC0-1.0',
+ mp3Path,
+ ],
+ `${name}.mp3`,
+ );
+
+ // Stereo q4 OGG Vorbis — better quality fallback for desktop browsers.
+ await runFfmpeg(
+ [
+ '-filter_complex',
+ graph,
+ '-map',
+ '[mix]',
+ '-t',
+ String(durationSec),
+ '-ac',
+ '2',
+ '-ar',
+ String(SAMPLE_RATE),
+ '-c:a',
+ 'libvorbis',
+ '-qscale:a',
+ '4',
+ '-metadata',
+ `TITLE=three.ws Pole Club — ${name}`,
+ '-metadata',
+ 'ARTIST=three.ws',
+ '-metadata',
+ 'LICENSE=CC0-1.0',
+ oggPath,
+ ],
+ `${name}.ogg`,
+ );
+
+ const [mp3Stat, oggStat] = await Promise.all([stat(mp3Path), stat(oggPath)]);
+ const maxBytes = 2 * 1024 * 1024;
+ if (mp3Stat.size > maxBytes) {
+ throw new Error(`${name}.mp3 is ${mp3Stat.size} bytes — exceeds 2 MB ship cap`);
+ }
+ if (oggStat.size > maxBytes) {
+ throw new Error(`${name}.ogg is ${oggStat.size} bytes — exceeds 2 MB ship cap`);
+ }
+ return {
+ name,
+ durationSec,
+ mp3Bytes: mp3Stat.size,
+ oggBytes: oggStat.size,
+ };
+}
+
+const TRACKS = [
+ { name: 'ambience', recipe: ambienceRecipe },
+ { name: 'rumba', recipe: rumbaRecipe },
+ { name: 'thriller', recipe: thrillerRecipe },
+ { name: 'hiphop', recipe: hiphopRecipe },
+ { name: 'capoeira', recipe: capoeiraRecipe },
+ { name: 'silly', recipe: sillyRecipe },
+ { name: 'pole', recipe: poleRecipe },
+];
+
+async function main() {
+ await mkdir(OUT_DIR, { recursive: true });
+ const results = [];
+ for (const t of TRACKS) {
+ process.stdout.write(`▸ ${t.name} … `);
+ const r = await buildTrack(t.name, t.recipe);
+ results.push(r);
+ process.stdout.write(
+ `${r.durationSec.toFixed(2)}s · mp3=${(r.mp3Bytes / 1024).toFixed(1)} KiB · ogg=${(r.oggBytes / 1024).toFixed(1)} KiB\n`,
+ );
+ }
+ const totalMp3 = results.reduce((s, r) => s + r.mp3Bytes, 0);
+ const totalOgg = results.reduce((s, r) => s + r.oggBytes, 0);
+ console.log(
+ `\n✓ ${results.length} tracks built — total mp3=${(totalMp3 / 1024).toFixed(1)} KiB, ogg=${(totalOgg / 1024).toFixed(1)} KiB`,
+ );
+}
+
+main().catch((err) => {
+ console.error('\n✗ build-club-audio failed');
+ console.error(err);
+ process.exit(1);
+});
diff --git a/scripts/build-club-props.mjs b/scripts/build-club-props.mjs
index 828dfc290..cd2dd615f 100644
--- a/scripts/build-club-props.mjs
+++ b/scripts/build-club-props.mjs
@@ -1,177 +1,281 @@
#!/usr/bin/env node
/**
* Authors the static props used by /club — pole.glb and stage.glb — and writes
- * them to public/club/props/. Composed at build time from Three.js primitives,
- * not at runtime, so the browser ships a real .glb file with named empties for
- * the spotlight + LED strip attach points (consumed by src/club.js).
+ * them to public/club/props/. Composed at build time from procedural cylinder,
+ * box, torus and disc geometry via @gltf-transform/core, so the browser ships
+ * a real .glb file with named empties for the spotlight + LED strip attach
+ * points consumed by src/club.js.
*
* Run via: npm run build:club-props
*/
import { writeFileSync, mkdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
-import { Blob } from 'node:buffer';
-
-// Three's GLTFExporter touches DOM globals; mirror the shim from build-animations.mjs.
-globalThis.self = globalThis;
-globalThis.window = globalThis;
-globalThis.document = { createElementNS: () => ({}) };
-globalThis.Blob = Blob;
-
-class NodeFileReader extends EventTarget {
- readAsDataURL(blob) {
- blob.arrayBuffer().then((buf) => {
- const b64 = Buffer.from(buf).toString('base64');
- this.result = `data:${blob.type || 'application/octet-stream'};base64,${b64}`;
- this.onload?.({ target: this });
- this.dispatchEvent(new Event('load'));
- });
- }
- readAsArrayBuffer(blob) {
- blob.arrayBuffer().then((buf) => {
- this.result = buf;
- this.onload?.({ target: this });
- this.dispatchEvent(new Event('load'));
- });
- }
-}
-globalThis.FileReader = NodeFileReader;
+
+import { Document, NodeIO } from '@gltf-transform/core';
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, '..');
const OUT_DIR = resolve(ROOT, 'public/club/props');
-const {
- Scene,
- Group,
- Mesh,
- Object3D,
- CylinderGeometry,
- BoxGeometry,
- TorusGeometry,
- MeshStandardMaterial,
-} = await import('three');
-const { GLTFExporter } = await import('three/examples/jsm/exporters/GLTFExporter.js');
-
const POLE_HEIGHT = 3.6;
const POLE_RADIUS = 0.035;
const STAGE_RADIUS = 1.1;
const STAGE_HEIGHT = 0.18;
-function chromeMat(name = 'PoleChrome') {
- const m = new MeshStandardMaterial({
- color: 0xe6e8f0,
- roughness: 0.14,
- metalness: 1.0,
- });
- m.name = name;
- return m;
+// ─── Geometry builders (positions / normals / indices, no UVs) ───────────────
+
+/**
+ * Open-top cylinder side wall + two end caps. radiusTop/radiusBottom support
+ * the flared base; segments controls smoothness.
+ */
+function cylinderGeom(radiusTop, radiusBottom, height, segments = 24) {
+ const positions = [];
+ const normals = [];
+ const indices = [];
+ const halfH = height / 2;
+
+ // Side ring vertices, duplicated per ring (top + bottom).
+ for (let i = 0; i <= segments; i++) {
+ const u = i / segments;
+ const theta = u * Math.PI * 2;
+ const sin = Math.sin(theta);
+ const cos = Math.cos(theta);
+ // Slope of the side normal so the lighting reads smoothly on a flared cone.
+ const slope = (radiusBottom - radiusTop) / height;
+ const nLen = Math.hypot(1, slope);
+ const nx = cos / nLen;
+ const nz = sin / nLen;
+ const ny = slope / nLen;
+
+ positions.push(radiusTop * cos, halfH, radiusTop * sin);
+ normals.push(nx, ny, nz);
+ positions.push(radiusBottom * cos, -halfH, radiusBottom * sin);
+ normals.push(nx, ny, nz);
+ }
+ for (let i = 0; i < segments; i++) {
+ const a = i * 2;
+ indices.push(a, a + 1, a + 2);
+ indices.push(a + 1, a + 3, a + 2);
+ }
+
+ // Top + bottom caps as triangle fans.
+ const addCap = (y, radius, normalY) => {
+ const centerIdx = positions.length / 3;
+ positions.push(0, y, 0);
+ normals.push(0, normalY, 0);
+ const ringStart = positions.length / 3;
+ for (let i = 0; i <= segments; i++) {
+ const theta = (i / segments) * Math.PI * 2;
+ positions.push(radius * Math.cos(theta), y, radius * Math.sin(theta));
+ normals.push(0, normalY, 0);
+ }
+ for (let i = 0; i < segments; i++) {
+ if (normalY > 0) {
+ indices.push(centerIdx, ringStart + i, ringStart + i + 1);
+ } else {
+ indices.push(centerIdx, ringStart + i + 1, ringStart + i);
+ }
+ }
+ };
+ addCap(halfH, radiusTop, 1);
+ addCap(-halfH, radiusBottom, -1);
+
+ return {
+ positions: new Float32Array(positions),
+ normals: new Float32Array(normals),
+ indices: new Uint32Array(indices),
+ };
}
-function brushedMat(name = 'PoleBaseBrushed') {
- const m = new MeshStandardMaterial({
- color: 0xc8ccd8,
- roughness: 0.32,
- metalness: 0.95,
- });
- m.name = name;
- return m;
+function boxGeom(sx, sy, sz) {
+ const x = sx / 2, y = sy / 2, z = sz / 2;
+ const faces = [
+ // +X
+ { n: [1, 0, 0], v: [[x, -y, -z], [x, y, -z], [x, y, z], [x, -y, z]] },
+ // -X
+ { n: [-1, 0, 0], v: [[-x, -y, z], [-x, y, z], [-x, y, -z], [-x, -y, -z]] },
+ // +Y
+ { n: [0, 1, 0], v: [[-x, y, -z], [-x, y, z], [x, y, z], [x, y, -z]] },
+ // -Y
+ { n: [0, -1, 0], v: [[-x, -y, z], [-x, -y, -z], [x, -y, -z], [x, -y, z]] },
+ // +Z
+ { n: [0, 0, 1], v: [[-x, -y, z], [x, -y, z], [x, y, z], [-x, y, z]] },
+ // -Z
+ { n: [0, 0, -1], v: [[x, -y, -z], [-x, -y, -z], [-x, y, -z], [x, y, -z]] },
+ ];
+ const positions = [];
+ const normals = [];
+ const indices = [];
+ for (const face of faces) {
+ const start = positions.length / 3;
+ for (const p of face.v) {
+ positions.push(...p);
+ normals.push(...face.n);
+ }
+ indices.push(start, start + 1, start + 2, start, start + 2, start + 3);
+ }
+ return {
+ positions: new Float32Array(positions),
+ normals: new Float32Array(normals),
+ indices: new Uint32Array(indices),
+ };
}
-function darkMetalMat(name = 'BoltDark') {
- const m = new MeshStandardMaterial({
- color: 0x1a1c20,
- roughness: 0.45,
- metalness: 0.9,
- });
- m.name = name;
- return m;
+function torusGeom(radius, tube, radialSegments = 8, tubularSegments = 64) {
+ const positions = [];
+ const normals = [];
+ const indices = [];
+ for (let j = 0; j <= radialSegments; j++) {
+ for (let i = 0; i <= tubularSegments; i++) {
+ const u = (i / tubularSegments) * Math.PI * 2;
+ const v = (j / radialSegments) * Math.PI * 2;
+ const cosU = Math.cos(u), sinU = Math.sin(u);
+ const cosV = Math.cos(v), sinV = Math.sin(v);
+ positions.push(
+ (radius + tube * cosV) * cosU,
+ tube * sinV,
+ (radius + tube * cosV) * sinU,
+ );
+ normals.push(cosV * cosU, sinV, cosV * sinU);
+ }
+ }
+ const stride = tubularSegments + 1;
+ for (let j = 0; j < radialSegments; j++) {
+ for (let i = 0; i < tubularSegments; i++) {
+ const a = j * stride + i;
+ const b = a + stride;
+ indices.push(a, b, a + 1);
+ indices.push(b, b + 1, a + 1);
+ }
+ }
+ return {
+ positions: new Float32Array(positions),
+ normals: new Float32Array(normals),
+ indices: new Uint32Array(indices),
+ };
}
-function stageTopMat(name = 'StageTop') {
- const m = new MeshStandardMaterial({
- color: 0x18091a,
- roughness: 0.35,
- metalness: 0.7,
- });
- m.name = name;
- return m;
+// ─── glTF assembly helpers ───────────────────────────────────────────────────
+
+function addPrim(doc, buffer, mat, name, { positions, normals, indices }) {
+ const posAcc = doc
+ .createAccessor(`${name}.pos`)
+ .setType('VEC3')
+ .setArray(positions)
+ .setBuffer(buffer);
+ const normAcc = doc
+ .createAccessor(`${name}.norm`)
+ .setType('VEC3')
+ .setArray(normals)
+ .setBuffer(buffer);
+ const idxAcc = doc
+ .createAccessor(`${name}.idx`)
+ .setType('SCALAR')
+ .setArray(indices)
+ .setBuffer(buffer);
+ const prim = doc
+ .createPrimitive()
+ .setAttribute('POSITION', posAcc)
+ .setAttribute('NORMAL', normAcc)
+ .setIndices(idxAcc)
+ .setMaterial(mat);
+ return doc.createMesh(name).addPrimitive(prim);
}
-function stageSideMat(name = 'StageSide') {
- const m = new MeshStandardMaterial({
- color: 0x0a050d,
- roughness: 0.55,
- metalness: 0.55,
- });
- m.name = name;
- return m;
+function addMesh(doc, scene, buffer, mat, name, geom, translation = [0, 0, 0], rotation = null) {
+ const mesh = addPrim(doc, buffer, mat, name, geom);
+ const node = doc.createNode(name).setMesh(mesh).setTranslation(translation);
+ if (rotation) node.setRotation(rotation);
+ scene.addChild(node);
+ return node;
}
-function ledMat(name = 'StageLED') {
- const m = new MeshStandardMaterial({
- color: 0xffffff,
- emissive: 0xff4dd6,
- emissiveIntensity: 1.0,
- roughness: 0.4,
- metalness: 0.1,
- });
- m.name = name;
- return m;
+function addEmpty(doc, scene, name, translation) {
+ const node = doc.createNode(name).setTranslation(translation);
+ scene.addChild(node);
+ return node;
}
-/**
- * Build pole.glb scene. Origin = (0, 0, 0) at pole base footprint center; the
- * shaft extends upward to y = POLE_HEIGHT. Includes a flared base, ceiling
- * mount plate with four bolts, a spotlight bracket, and a named empty
- * `pole.light.attach` at the bracket tip.
- */
-function buildPoleScene() {
- const scene = new Scene();
- scene.name = 'PoleScene';
-
- const root = new Group();
- root.name = 'PoleRoot';
- scene.add(root);
-
- // Flared base — wide bottom disc tapered to a narrow collar.
- const baseDisc = new Mesh(
- new CylinderGeometry(0.42, 0.46, 0.04, 40),
- brushedMat('PoleBase'),
- );
- baseDisc.name = 'pole.base';
- baseDisc.position.y = 0.02;
- root.add(baseDisc);
-
- const baseCollar = new Mesh(
- new CylinderGeometry(POLE_RADIUS * 2.1, 0.13, 0.09, 32),
- brushedMat('PoleCollar'),
- );
- baseCollar.name = 'pole.collar';
- baseCollar.position.y = 0.04 + 0.045;
- root.add(baseCollar);
+function chromeMat(doc) {
+ return doc
+ .createMaterial('PoleChrome')
+ .setBaseColorFactor([0.902, 0.910, 0.941, 1])
+ .setMetallicFactor(1.0)
+ .setRoughnessFactor(0.14);
+}
+
+function brushedMat(doc) {
+ return doc
+ .createMaterial('PoleBrushed')
+ .setBaseColorFactor([0.784, 0.800, 0.847, 1])
+ .setMetallicFactor(0.95)
+ .setRoughnessFactor(0.32);
+}
+
+function darkMetalMat(doc) {
+ return doc
+ .createMaterial('DarkMetal')
+ .setBaseColorFactor([0.102, 0.110, 0.126, 1])
+ .setMetallicFactor(0.9)
+ .setRoughnessFactor(0.45);
+}
+
+function stageBodyMat(doc) {
+ return doc
+ .createMaterial('StageBody')
+ .setBaseColorFactor([0.039, 0.020, 0.051, 1])
+ .setMetallicFactor(0.55)
+ .setRoughnessFactor(0.55);
+}
+
+function stageTopMat(doc) {
+ return doc
+ .createMaterial('StageTop')
+ .setBaseColorFactor([0.094, 0.035, 0.102, 1])
+ .setMetallicFactor(0.7)
+ .setRoughnessFactor(0.35);
+}
+
+function ledMat(doc) {
+ return doc
+ .createMaterial('StageLED')
+ .setBaseColorFactor([1, 1, 1, 1])
+ .setEmissiveFactor([1.0, 0.3, 0.84])
+ .setMetallicFactor(0.1)
+ .setRoughnessFactor(0.4);
+}
+
+// ─── Pole ────────────────────────────────────────────────────────────────────
+
+function buildPoleDoc() {
+ const doc = new Document();
+ doc.createBuffer();
+ const buffer = doc.getRoot().listBuffers()[0];
+ const scene = doc.createScene('PoleScene');
+
+ const chrome = chromeMat(doc);
+ const brushed = brushedMat(doc);
+ const dark = darkMetalMat(doc);
+
+ // Flared base disc.
+ addMesh(doc, scene, buffer, brushed, 'pole.base',
+ cylinderGeom(0.42, 0.46, 0.04, 40), [0, 0.02, 0]);
+
+ // Transition collar between base and shaft.
+ addMesh(doc, scene, buffer, brushed, 'pole.collar',
+ cylinderGeom(POLE_RADIUS * 2.1, 0.13, 0.09, 32), [0, 0.04 + 0.045, 0]);
// Main shaft.
- const shaft = new Mesh(
- new CylinderGeometry(POLE_RADIUS, POLE_RADIUS, POLE_HEIGHT, 24, 1),
- chromeMat('PoleShaft'),
- );
- shaft.name = 'pole.shaft';
- shaft.position.y = POLE_HEIGHT / 2;
- root.add(shaft);
-
- // Ceiling mount plate at the top.
- const mountPlate = new Mesh(
- new BoxGeometry(0.26, 0.014, 0.26),
- brushedMat('PoleMountPlate'),
- );
- mountPlate.name = 'pole.mount.plate';
- mountPlate.position.y = POLE_HEIGHT + 0.007;
- root.add(mountPlate);
-
- // Four bolts at corners of the plate.
- const boltMat = darkMetalMat('PoleBolt');
- const boltGeom = new CylinderGeometry(0.012, 0.012, 0.022, 8);
+ addMesh(doc, scene, buffer, chrome, 'pole.shaft',
+ cylinderGeom(POLE_RADIUS, POLE_RADIUS, POLE_HEIGHT, 24), [0, POLE_HEIGHT / 2, 0]);
+
+ // Ceiling mount plate.
+ addMesh(doc, scene, buffer, brushed, 'pole.mount.plate',
+ boxGeom(0.26, 0.014, 0.26), [0, POLE_HEIGHT + 0.007, 0]);
+
+ // Four bolts on the mount plate.
+ const boltGeom = cylinderGeom(0.012, 0.012, 0.022, 8);
const boltInset = 0.10;
const boltOffsets = [
[+boltInset, +boltInset],
@@ -181,114 +285,69 @@ function buildPoleScene() {
];
for (let i = 0; i < boltOffsets.length; i++) {
const [bx, bz] = boltOffsets[i];
- const bolt = new Mesh(boltGeom.clone(), boltMat);
- bolt.name = `pole.bolt.${i}`;
- bolt.position.set(bx, POLE_HEIGHT + 0.024, bz);
- root.add(bolt);
+ addMesh(doc, scene, buffer, dark, `pole.bolt.${i}`,
+ boltGeom, [bx, POLE_HEIGHT + 0.024, bz]);
}
- // Spotlight bracket — extends in +z from the mount plate.
- const bracketArm = new Mesh(
- new BoxGeometry(0.04, 0.02, 0.18),
- darkMetalMat('PoleBracketArm'),
- );
- bracketArm.name = 'pole.bracket.arm';
- bracketArm.position.set(0, POLE_HEIGHT + 0.024, 0.13);
- root.add(bracketArm);
-
- const bracketHead = new Mesh(
- new CylinderGeometry(0.025, 0.025, 0.04, 16),
- darkMetalMat('PoleBracketHead'),
- );
- bracketHead.name = 'pole.bracket.head';
- bracketHead.rotation.x = Math.PI / 2;
- bracketHead.position.set(0, POLE_HEIGHT + 0.024, 0.22);
- root.add(bracketHead);
-
- // Named empty for prompt-04 SpotLight anchoring.
- const attach = new Object3D();
- attach.name = 'pole.light.attach';
- attach.position.set(0, POLE_HEIGHT + 0.024, 0.24);
- root.add(attach);
-
- return scene;
-}
+ // Spotlight bracket.
+ addMesh(doc, scene, buffer, dark, 'pole.bracket.arm',
+ boxGeom(0.04, 0.02, 0.18), [0, POLE_HEIGHT + 0.024, 0.13]);
+ // Rotate +90° about X so the cylinder's Y axis points along Z (head pointing forward).
+ // Quaternion for 90° X-rotation: (sin(45°), 0, 0, cos(45°)).
+ const xQuat = [Math.SQRT1_2, 0, 0, Math.SQRT1_2];
+ addMesh(doc, scene, buffer, dark, 'pole.bracket.head',
+ cylinderGeom(0.025, 0.025, 0.04, 16), [0, POLE_HEIGHT + 0.024, 0.22], xQuat);
-/**
- * Build stage.glb scene. Origin = (0, 0, 0) at floor level under disc center;
- * the disc top is at y = STAGE_HEIGHT. Includes an LED strip ring around the
- * top edge with a named empty `stage.led.strip` at its center.
- */
-function buildStageScene() {
- const scene = new Scene();
- scene.name = 'StageScene';
-
- const root = new Group();
- root.name = 'StageRoot';
- scene.add(root);
-
- // Main disc.
- const disc = new Mesh(
- new CylinderGeometry(STAGE_RADIUS, STAGE_RADIUS + 0.04, STAGE_HEIGHT, 64, 1),
- stageSideMat('StageBody'),
- );
- disc.name = 'stage.body';
- disc.position.y = STAGE_HEIGHT / 2;
- root.add(disc);
-
- // Slightly raised non-slip top so the dancer's feet have a defined surface.
- const top = new Mesh(
- new CylinderGeometry(STAGE_RADIUS - 0.01, STAGE_RADIUS - 0.01, 0.004, 64, 1),
- stageTopMat('StageTopFace'),
- );
- top.name = 'stage.top';
- top.position.y = STAGE_HEIGHT + 0.002;
- root.add(top);
-
- // LED strip — thin torus around the upper edge.
- const led = new Mesh(
- new TorusGeometry(STAGE_RADIUS + 0.005, 0.012, 8, 96),
- ledMat('StageLEDStrip'),
- );
- led.name = 'stage.led.ring';
- led.rotation.x = Math.PI / 2;
- led.position.y = STAGE_HEIGHT - 0.014;
- root.add(led);
-
- // Named empty for prompt-04 LED pulse driver.
- const ledAttach = new Object3D();
- ledAttach.name = 'stage.led.strip';
- ledAttach.position.set(0, STAGE_HEIGHT - 0.014, 0);
- root.add(ledAttach);
-
- return scene;
+ // Spotlight attach empty (consumed by prompt 04).
+ addEmpty(doc, scene, 'pole.light.attach', [0, POLE_HEIGHT + 0.024, 0.24]);
+
+ return doc;
}
-async function exportGLB(scene) {
- const exporter = new GLTFExporter();
- return new Promise((resolve, reject) => {
- exporter.parse(
- scene,
- (buf) => resolve(buf),
- (err) => reject(err),
- { binary: true, embedImages: true, onlyVisible: true },
- );
- });
+// ─── Stage ───────────────────────────────────────────────────────────────────
+
+function buildStageDoc() {
+ const doc = new Document();
+ doc.createBuffer();
+ const buffer = doc.getRoot().listBuffers()[0];
+ const scene = doc.createScene('StageScene');
+
+ const body = stageBodyMat(doc);
+ const top = stageTopMat(doc);
+ const led = ledMat(doc);
+
+ // Main disc (slight outward flare at the base).
+ addMesh(doc, scene, buffer, body, 'stage.body',
+ cylinderGeom(STAGE_RADIUS, STAGE_RADIUS + 0.04, STAGE_HEIGHT, 64), [0, STAGE_HEIGHT / 2, 0]);
+
+ // Anti-slip top face — recessed slightly inside the disc rim.
+ addMesh(doc, scene, buffer, top, 'stage.top',
+ cylinderGeom(STAGE_RADIUS - 0.01, STAGE_RADIUS - 0.01, 0.004, 64), [0, STAGE_HEIGHT + 0.002, 0]);
+
+ // LED strip — horizontal torus around the top edge.
+ const xQuat = [Math.SQRT1_2, 0, 0, Math.SQRT1_2];
+ addMesh(doc, scene, buffer, led, 'stage.led.ring',
+ torusGeom(STAGE_RADIUS + 0.005, 0.012, 8, 96), [0, STAGE_HEIGHT - 0.014, 0], xQuat);
+
+ // LED control empty (consumed by prompt 04).
+ addEmpty(doc, scene, 'stage.led.strip', [0, STAGE_HEIGHT - 0.014, 0]);
+
+ return doc;
}
async function main() {
mkdirSync(OUT_DIR, { recursive: true });
+ const io = new NodeIO();
const targets = [
- { name: 'pole.glb', scene: buildPoleScene() },
- { name: 'stage.glb', scene: buildStageScene() },
+ { name: 'pole.glb', doc: buildPoleDoc() },
+ { name: 'stage.glb', doc: buildStageDoc() },
];
- for (const { name, scene } of targets) {
- const buf = await exportGLB(scene);
- const bytes = Buffer.from(buf);
+ for (const { name, doc } of targets) {
+ const bytes = await io.writeBinary(doc);
const outPath = resolve(OUT_DIR, name);
- writeFileSync(outPath, bytes);
+ writeFileSync(outPath, Buffer.from(bytes));
console.log(`[club-props] wrote ${name.padEnd(10)} ${(bytes.length / 1024).toFixed(1)} kB`);
}
}
diff --git a/src/club-audio.js b/src/club-audio.js
index df7a23036..1448f8825 100644
--- a/src/club-audio.js
+++ b/src/club-audio.js
@@ -27,14 +27,14 @@ export class ClubAudio {
constructor() {
this.ctx = null;
this.master = null;
- this.ambience = null; // { source, gain }
- this.style = null; // { name, source, gain }
+ this.ambience = null; // { source, gain }
+ this.style = null; // { name, source, gain }
this.analyser = null;
- this._buffers = new Map(); // styleName → AudioBuffer
- this._loading = new Map(); // styleName → Promise<AudioBuffer>
- this._peakBuf = null; // Uint8Array reused for getByteFrequencyData
+ this._buffers = new Map(); // styleName → AudioBuffer
+ this._loading = new Map(); // styleName → Promise<AudioBuffer>
+ this._peakBuf = null; // Uint8Array reused for getByteFrequencyData
this.muted = this._readMutedPref();
- this._onStatus = null; // optional callback(name, label)
+ this._onStatus = null; // optional callback(name, label)
}
onStatus(cb) {
@@ -46,13 +46,14 @@ export class ClubAudio {
// On Safari the context can flip to "suspended" after a tab switch;
// re-resume on every tip gesture is cheap and safe.
if (this.ctx.state === 'suspended') {
- try { await this.ctx.resume(); } catch {}
+ try {
+ await this.ctx.resume();
+ } catch {}
}
return;
}
- const Ctor = typeof window !== 'undefined'
- ? (window.AudioContext || window.webkitAudioContext)
- : null;
+ const Ctor =
+ typeof window !== 'undefined' ? window.AudioContext || window.webkitAudioContext : null;
if (!Ctor) {
throw new Error('Web Audio API unavailable');
}
@@ -68,7 +69,9 @@ export class ClubAudio {
this._peakBuf = new Uint8Array(this.analyser.frequencyBinCount);
if (this.ctx.state === 'suspended') {
- try { await this.ctx.resume(); } catch {}
+ try {
+ await this.ctx.resume();
+ } catch {}
}
}
@@ -130,7 +133,9 @@ export class ClubAudio {
if (!name) return;
await this.ensureContext();
if (this.ctx.state === 'suspended') {
- try { await this.ctx.resume(); } catch {}
+ try {
+ await this.ctx.resume();
+ } catch {}
}
const buf = await this.loadBuffer(name);
@@ -156,7 +161,9 @@ export class ClubAudio {
}
if (this._onStatus) {
- try { this._onStatus(name); } catch {}
+ try {
+ this._onStatus(name);
+ } catch {}
}
return this.style;
}
@@ -199,7 +206,7 @@ export class ClubAudio {
const n = this._peakBuf.length >> 1;
let sum = 0;
for (let i = 0; i < n; i++) sum += this._peakBuf[i];
- return n > 0 ? (sum / n) / 255 : 0;
+ return n > 0 ? sum / n / 255 : 0;
}
setMuted(v) {
diff --git a/src/club-sequence.js b/src/club-sequence.js
new file mode 100644
index 000000000..734cd7e84
--- /dev/null
+++ b/src/club-sequence.js
@@ -0,0 +1,96 @@
+// Sequence playback for the Pole Club stage.
+//
+// A dance "ticket" returned by /api/x402/dance-tip carries either a single
+// `clip` (free-floor styles) or a `sequence` array (pole choreography:
+// spin / climb / combo). `playSequence` consumes both shapes uniformly so
+// PoleStation doesn't need to branch.
+//
+// The module is deliberately framework-light — no THREE imports, no DOM
+// access — so it can be unit-tested without spinning up a WebGLRenderer.
+
+/**
+ * Real-clock sleep. Resolves after `ms` milliseconds of wall time, which is
+ * the same clock `tick()` uses (`Date.now()` / `clock.getElapsedTime()`). The
+ * render loop keeps ticking the mixer in the background; this only awaits
+ * the elapsed time before kicking off the next crossfade.
+ *
+ * Not a fake setTimeout-driven progress bar — it's a real wait that yields
+ * back to the event loop until the timer fires. Tests can inject a stub
+ * via the `sleep` option on `playSequence` to step through deterministically.
+ *
+ * @param {number} ms
+ * @returns {Promise<void>}
+ */
+export function sleep(ms) {
+ if (!Number.isFinite(ms) || ms <= 0) return Promise.resolve();
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+/**
+ * Normalize a ticket into a list of `{ clip, durationSec }` steps.
+ *
+ * Sequence-shaped tickets pass through untouched. Single-clip tickets are
+ * lifted into a 1-step sequence. Anything else returns an empty array, which
+ * `playSequence` treats as a no-op (so unknown tickets fail closed rather
+ * than crashing).
+ *
+ * @param {{ sequence?: Array<{clip:string, durationSec:number}>, clip?: string, durationSec?: number }} ticket
+ * @returns {Array<{ clip: string, durationSec: number }>}
+ */
+export function ticketSteps(ticket) {
+ if (Array.isArray(ticket?.sequence) && ticket.sequence.length) {
+ return ticket.sequence.map((s) => ({
+ clip: String(s.clip),
+ durationSec: Number(s.durationSec) || 0,
+ }));
+ }
+ if (ticket?.clip) {
+ return [{ clip: String(ticket.clip), durationSec: Number(ticket?.durationSec) || 0 }];
+ }
+ return [];
+}
+
+/**
+ * Drive a sequence of crossfades on the supplied AnimationManager-shaped
+ * object. Each step:
+ * 1. await anim.crossfadeTo(step.clip, fadeSec)
+ * 2. await sleep(step.durationSec * 1000)
+ *
+ * The loop checks `isCancelled()` between steps and aborts before the next
+ * crossfade — matches the contract in the task spec
+ * ("setting performing = false mid-sequence stops the next crossfade").
+ *
+ * @param {object} args
+ * @param {{ crossfadeTo: (name: string, fade?: number) => Promise<void> }} args.anim
+ * Animation manager. Only `crossfadeTo` is required.
+ * @param {Array<{ clip: string, durationSec: number }>} args.steps
+ * The sequence to play. Use `ticketSteps(ticket)` to derive from a tip ticket.
+ * @param {number} [args.fadeSec=0.45]
+ * Crossfade duration passed to anim.crossfadeTo.
+ * @param {() => boolean} [args.isCancelled]
+ * Polled between steps; truthy aborts the loop before the next crossfade.
+ * @param {(ms: number) => Promise<void>} [args.sleep]
+ * Real-clock wait between steps. Defaults to the module's `sleep`.
+ * Tests inject a deterministic stub here.
+ * @returns {Promise<{ played: number, cancelled: boolean }>}
+ * `played` = number of steps that ran a crossfade (cancellation
+ * before the first crossfade counts as 0).
+ */
+export async function playSequence({
+ anim,
+ steps,
+ fadeSec = 0.45,
+ isCancelled = () => false,
+ sleep: sleepFn = sleep,
+}) {
+ let played = 0;
+ for (const step of steps) {
+ if (isCancelled()) return { played, cancelled: true };
+ await anim.crossfadeTo(step.clip, fadeSec);
+ played += 1;
+ if (step.durationSec > 0) {
+ await sleepFn(step.durationSec * 1000);
+ }
+ }
+ return { played, cancelled: false };
+}
diff --git a/src/club.js b/src/club.js
index c38777e63..485c35b30 100644
--- a/src/club.js
+++ b/src/club.js
@@ -12,7 +12,6 @@ import {
CircleGeometry,
Clock,
Color,
- CylinderGeometry,
DoubleSide,
Fog,
Group,
@@ -38,17 +37,26 @@ import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js'
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';
const AVATAR_URL = '/avatars/default.glb';
const MANIFEST_URL = '/animations/manifest.json';
+const POLE_GLB_URL = '/club/props/pole.glb';
+const STAGE_GLB_URL = '/club/props/stage.glb';
-// Clips we actually use — keeps the manifest pre-fetch small.
+// Clips we actually use — keeps the manifest pre-fetch small. Pole-specific
+// clips (pole-spin, pole-climb, etc.) are added here once their source FBX
+// files land in /public/animations/ and re-run of `npm run build:animations`
+// registers them in /animations/manifest.json.
const REQUIRED_CLIPS = new Set([
'idle', 'dance', 'rumba', 'silly', 'thriller', 'capoeira', 'walk',
+ 'pole-walk-on', 'pole-spin', 'pole-climb', 'pole-invert', 'pole-floorwork', 'pole-bow',
]);
const WALK_CLIP = 'walk';
const TIP_ENDPOINT = '/api/x402/dance-tip';
+const TIPS_HISTORY_URL = '/api/club/tips?limit=20';
+const TIPS_STREAM_URL = '/api/club/tips/stream';
// ── Stage layout ─────────────────────────────────────────────────────────
// Four poles in a half-arc facing the camera. Backstage is behind the bar at
@@ -56,8 +64,10 @@ const TIP_ENDPOINT = '/api/x402/dance-tip';
const STAGE_RADIUS = 4.2;
const POLE_COUNT = 4;
const POLE_HEIGHT = 3.6;
-const POLE_RADIUS = 0.05;
const PERFORMANCE_FADE = 0.45; // seconds for clip crossfade
+// Top of the stage GLB. Authored in scripts/build-club-props.mjs at y=0.18.
+// Mirrored here so the dancer rig + pole base sit on the disc face.
+const STAGE_TOP_Y = 0.18;
const POLES = Array.from({ length: POLE_COUNT }, (_, i) => {
// Spread across an arc from -55° to +55° at the front of the room.
@@ -79,6 +89,9 @@ const canvas = document.getElementById('club-canvas');
const polesPanel = document.getElementById('club-poles');
const statusEl = document.getElementById('club-status');
const tipFeedEl = document.getElementById('club-tip-feed');
+const feedStatusEl = document.getElementById('club-feed-status');
+const lbRowsEl = document.getElementById('club-lb-rows');
+const lbTabsEls = document.querySelectorAll('.club-lb-tab');
function setStatus(text, { kind = 'info' } = {}) {
if (!statusEl) return;
@@ -96,20 +109,165 @@ function fmtUsd(atomics, decimals = 6) {
return `$${n.toFixed(2)}`;
}
-function pushFeed({ dancer, label, payer, amountAtomics, network }) {
- if (!tipFeedEl) return;
+// Dedupe ring: the local x402 echo and the SSE channel both deliver the same
+// settled tip. Whichever wins the race renders the row; the loser is dropped
+// by ticket_id. Capped so it doesn't grow without bound on a long session.
+const DEDUPE_MAX = 50;
+const renderedTicketIds = new Set();
+const renderedOrder = [];
+
+function rememberTicketId(id) {
+ if (!id || renderedTicketIds.has(id)) return false;
+ renderedTicketIds.add(id);
+ renderedOrder.push(id);
+ while (renderedOrder.length > DEDUPE_MAX) {
+ renderedTicketIds.delete(renderedOrder.shift());
+ }
+ return true;
+}
+
+// Render one tip into the feed. Accepts both the server row shape
+// (snake_case from /api/club/tips and SSE `tip` events) and the local
+// x402 ticket shape (camelCase from window.X402.pay).
+function renderTipRow(rowLike, { live = false, prepend = true } = {}) {
+ if (!tipFeedEl || !rowLike) return;
+ const ticketId = rowLike.ticket_id ?? rowLike.ticketId ?? null;
+ if (ticketId && !rememberTicketId(ticketId)) return;
+
+ const dancer = rowLike.dancer ?? '?';
+ const label = rowLike.label ?? rowLike.dance ?? 'dance';
+ const payer = rowLike.payer ?? null;
+ const amountAtomics = rowLike.amount_atomics ?? rowLike.amountAtomics ?? null;
+ const network = rowLike.network ?? '';
+
tipFeedEl.querySelector('.club-feed-empty')?.remove();
const row = document.createElement('div');
row.className = 'club-tip-row';
+ if (live) row.classList.add('is-live');
const who = payer ? `${payer.slice(0, 4)}…${payer.slice(-4)}` : 'someone';
- const safeLabel = String(label || 'dance').replace(/[<>&]/g, '');
+ const safeLabel = String(label).replace(/[<>&]/g, '');
row.innerHTML = `
<span class="club-tip-who">${who}</span>
<span class="club-tip-mid">tipped dancer ${dancer} → ${safeLabel}</span>
<span class="club-tip-amt">${fmtUsd(amountAtomics)} · ${network || ''}</span>
`;
- tipFeedEl.prepend(row);
- while (tipFeedEl.children.length > 10) tipFeedEl.lastChild.remove();
+ if (prepend) {
+ tipFeedEl.prepend(row);
+ } else {
+ tipFeedEl.appendChild(row);
+ }
+ while (tipFeedEl.children.length > 20) tipFeedEl.lastChild.remove();
+}
+
+function setFeedStatus(text, kind) {
+ if (!feedStatusEl) return;
+ if (!text) {
+ feedStatusEl.hidden = true;
+ feedStatusEl.textContent = '';
+ delete feedStatusEl.dataset.kind;
+ return;
+ }
+ feedStatusEl.textContent = text;
+ feedStatusEl.dataset.kind = kind || 'info';
+ feedStatusEl.hidden = false;
+}
+
+// Load the most-recent tips for a fresh page load. Tries twice (one retry
+// after 4 s) so a transient network blip doesn't leave the feed empty.
+async function loadInitialTips({ attempt = 0 } = {}) {
+ try {
+ const r = await fetch(TIPS_HISTORY_URL, { cache: 'no-store' });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ const data = await r.json();
+ const tips = Array.isArray(data?.tips) ? data.tips : [];
+ // Server returns newest-first; reverse so the newest ends up at the
+ // top after sequential prepend.
+ for (const t of tips.slice().reverse()) {
+ renderTipRow(t, { live: false });
+ }
+ setFeedStatus(null);
+ } catch (err) {
+ console.warn('[club] tip history failed', err);
+ if (attempt === 0) {
+ setFeedStatus("Couldn't load tip history — retrying", 'error');
+ setTimeout(() => loadInitialTips({ attempt: 1 }), 4000);
+ } else {
+ setFeedStatus("Couldn't load tip history", 'error');
+ }
+ }
+}
+
+// Subscribe to the SSE channel. Reconnects with linear backoff after an
+// error; after 3 consecutive failures shows a "live updates paused" badge.
+// The badge clears as soon as the next connection succeeds.
+function subscribeTipStream() {
+ if (typeof window.EventSource !== 'function') {
+ setFeedStatus('Live updates paused', 'paused');
+ return null;
+ }
+ let es = null;
+ let consecutiveFailures = 0;
+ let reconnectTimer = 0;
+ let closedByUser = false;
+
+ const open = () => {
+ if (closedByUser) return;
+ try {
+ es = new EventSource(TIPS_STREAM_URL);
+ } catch (err) {
+ console.warn('[club] EventSource init failed', err);
+ scheduleReconnect();
+ return;
+ }
+ es.addEventListener('hello', () => {
+ consecutiveFailures = 0;
+ setFeedStatus(null);
+ });
+ es.addEventListener('tip', (e) => {
+ try {
+ const row = JSON.parse(e.data);
+ renderTipRow(row, { live: true });
+ } catch (err) {
+ console.warn('[club] tip event parse failed', err);
+ }
+ });
+ es.onerror = () => {
+ // EventSource auto-reconnects in some browsers but keeps the
+ // closed socket in CONNECTING state and re-fires onerror in a
+ // spin. Explicitly close + schedule so the failure counter
+ // advances predictably and the badge timing is honest.
+ try { es?.close(); } catch {}
+ es = null;
+ consecutiveFailures += 1;
+ if (consecutiveFailures >= 3) {
+ setFeedStatus('Live updates paused', 'paused');
+ }
+ scheduleReconnect();
+ };
+ };
+
+ const scheduleReconnect = () => {
+ if (closedByUser) return;
+ clearTimeout(reconnectTimer);
+ // 1.5 s, 3 s, 6 s, capped — fast enough to recover from a momentary
+ // blip without hammering the endpoint during a longer outage.
+ const delay = Math.min(1500 * Math.max(1, consecutiveFailures), 6000);
+ reconnectTimer = setTimeout(open, delay);
+ };
+
+ open();
+ window.addEventListener('beforeunload', () => {
+ closedByUser = true;
+ clearTimeout(reconnectTimer);
+ try { es?.close(); } catch {}
+ });
+ return {
+ close() {
+ closedByUser = true;
+ clearTimeout(reconnectTimer);
+ try { es?.close(); } catch {}
+ },
+ };
}
// ── Renderer / scene ──────────────────────────────────────────────────────
@@ -219,38 +377,11 @@ class PoleStation {
this.idx = idx;
this.layout = layout;
this.id = layout.id;
+ this.stageTopY = STAGE_TOP_Y;
- // Stage disc — slightly raised so dancer's feet sit on top.
- const stage = new Mesh(
- new CylinderGeometry(0.9, 1.0, 0.18, 48),
- new MeshStandardMaterial({
- color: 0x140511,
- roughness: 0.35,
- metalness: 0.85,
- emissive: POLE_COLORS[idx % POLE_COLORS.length],
- emissiveIntensity: 0.18,
- }),
- );
- stage.position.set(layout.x, 0.09, layout.z);
- stage.receiveShadow = true;
- scene.add(stage);
- this.stage = stage;
- this.stageTopY = 0.18;
-
- // The pole — a brushed chrome cylinder.
- const pole = new Mesh(
- new CylinderGeometry(POLE_RADIUS, POLE_RADIUS, POLE_HEIGHT, 16),
- new MeshStandardMaterial({
- color: 0xe6e8f0,
- roughness: 0.12,
- metalness: 1.0,
- emissive: 0x1a1c25,
- emissiveIntensity: 0.4,
- }),
- );
- pole.position.set(layout.x, this.stageTopY + POLE_HEIGHT / 2, layout.z);
- pole.castShadow = true;
- scene.add(pole);
+ // Stage + pole GLBs are attached later in attachProps(); construct only
+ // the lights, the rig holder, and lifecycle state here so the station
+ // exists before async assets finish loading.
// Spotlight — colored, focused on the pole base.
const spot = new SpotLight(POLE_COLORS[idx % POLE_COLORS.length], 0, 12, Math.PI / 7, 0.4, 1.6);
@@ -280,13 +411,66 @@ class PoleStation {
this.anim = null;
this.skinned = null;
+ this.stage = null; // root group from stage.glb
+ this.pole = null; // root group from pole.glb
// Current performance lifecycle.
this.activeTicket = null; // backend ticket id
- this.activeUntil = 0; // ms epoch — when to release the stage
+ this.activeUntil = 0; // ms epoch — informational; sequence loop drives end
this.performing = false;
this.walkPhase = 'idle'; // 'idle' | 'to-pole' | 'dancing' | 'returning'
this._phaseTarget = this.rig.position.clone();
+
+ // Render-loop coupled sleepers (sleep() resolves them in tick()).
+ // Wall-clock setTimeout would drift if the tab is throttled or paused;
+ // driving sleep off the render clock keeps choreography frame-aligned.
+ this._clockSec = 0;
+ this._sleepers = [];
+ }
+
+ /**
+ * Clone the pole + stage GLB templates into this station. Called from
+ * bootstrap() once both .glb files have finished loading. Each station gets
+ * its own clone so material tints (per-pole accent emissive) don't leak.
+ */
+ attachProps({ poleTemplate, stageTemplate }) {
+ const accent = new Color(POLE_COLORS[this.idx % POLE_COLORS.length]);
+
+ const stage = stageTemplate.clone(true);
+ stage.position.set(this.layout.x, 0, this.layout.z);
+ stage.traverse((n) => {
+ if (!n.isMesh) return;
+ n.receiveShadow = true;
+ if (n.material) {
+ n.material = n.material.clone();
+ if (n.material.emissive) {
+ if (n.name === 'stage.led.ring') {
+ n.material.emissive = accent.clone();
+ n.material.emissiveIntensity = 1.2;
+ } else {
+ n.material.emissive.lerp(accent, 0.4);
+ }
+ }
+ }
+ });
+ scene.add(stage);
+ this.stage = stage;
+
+ const pole = poleTemplate.clone(true);
+ pole.position.set(this.layout.x, this.stageTopY, this.layout.z);
+ pole.traverse((n) => {
+ if (!n.isMesh) return;
+ n.castShadow = true;
+ n.receiveShadow = false;
+ if (n.material && n.material.metalness >= 0.9) {
+ // Subtle per-pole tint on the chrome only (skip dark brackets / bolts).
+ n.material = n.material.clone();
+ if (!n.material.emissive) n.material.emissive = new Color(0x000000);
+ n.material.emissive = accent.clone().multiplyScalar(0.04);
+ }
+ });
+ scene.add(pole);
+ this.pole = pole;
}
attachAvatar(template, animationDefs) {
@@ -353,10 +537,41 @@ class PoleStation {
await this.anim?.crossfadeTo(WALK_CLIP, PERFORMANCE_FADE);
}
+ /**
+ * Render-loop coupled sleep. Resolves when `_clockSec` has advanced past
+ * the requested duration. Used by playSequence between crossfades so
+ * choreography stays aligned with the mixer's frame clock even when the
+ * tab is throttled (where setTimeout would still fire on its own schedule
+ * and desync from the visible animation).
+ *
+ * @param {number} ms
+ * @returns {Promise<void>}
+ */
+ sleep(ms) {
+ if (!Number.isFinite(ms) || ms <= 0) return Promise.resolve();
+ return new Promise((resolve) => {
+ this._sleepers.push({ wakeAt: this._clockSec + ms / 1000, resolve });
+ });
+ }
+
async _arriveAtPole() {
this.walkPhase = 'dancing';
- const clipName = this.activeTicket?.clip || 'dance';
- await this.anim?.crossfadeTo(clipName, PERFORMANCE_FADE);
+ const steps = ticketSteps(this.activeTicket).length
+ ? ticketSteps(this.activeTicket)
+ : [{ clip: this.activeTicket?.clip || 'dance', durationSec: this.activeTicket?.durationSec || 12 }];
+
+ await playSequence({
+ anim: this.anim,
+ steps,
+ fadeSec: PERFORMANCE_FADE,
+ isCancelled: () => !this.performing,
+ sleep: (ms) => this.sleep(ms),
+ });
+
+ // Sequence finished (or was cancelled) — return the dancer to backstage.
+ // Cancellation is a fast-path: performing is already false, so _endPerformance
+ // won't toggle it back, but the walking + audio cleanup still runs.
+ if (this.walkPhase === 'dancing') await this._endPerformance();
}
async _endPerformance() {
@@ -389,6 +604,22 @@ class PoleStation {
}
tick(dt) {
+ // Advance the station clock and wake any sleepers due this frame.
+ // Driving sleep off the render clock (not setTimeout) keeps choreography
+ // aligned with the mixer when the tab is backgrounded or paused.
+ this._clockSec += dt;
+ if (this._sleepers.length) {
+ let i = 0;
+ while (i < this._sleepers.length) {
+ if (this._sleepers[i].wakeAt <= this._clockSec) {
+ const { resolve } = this._sleepers.splice(i, 1)[0];
+ resolve();
+ } else {
+ i += 1;
+ }
+ }
+ }
+
// Lerp spotlight intensity.
if (this._spotTarget != null) {
this.spot.intensity += (this._spotTarget - this.spot.intensity) * Math.min(1, dt * 4);
@@ -417,11 +648,11 @@ class PoleStation {
}
} else if (this.walkPhase === 'dancing') {
// Keep dancer facing the camera (yaw lerp to original pole yaw).
+ // End-of-dance is driven by the playSequence loop in _arriveAtPole,
+ // not a wall-clock deadline — that way each sequence step lasts
+ // exactly its declared duration in render-loop time.
const targetYaw = this.layout.yaw;
this.rig.rotation.y += angleDelta(this.rig.rotation.y, targetYaw) * Math.min(1, dt * 3);
- if (this.performing && Date.now() >= this.activeUntil) {
- this._endPerformance();
- }
} else {
// idle backstage — face into the room.
const targetYaw = this.layout.yaw;
@@ -460,12 +691,14 @@ async function bootstrap() {
setStatus('Loading club…');
const loader = new GLTFLoader();
- const [gltf, manifest] = await Promise.all([
+ const [gltf, manifest, poleGltf, stageGltf] = await Promise.all([
loader.loadAsync(AVATAR_URL),
fetch(MANIFEST_URL, { cache: 'force-cache' }).then((r) => {
if (!r.ok) throw new Error(`HTTP ${r.status} loading animation manifest`);
return r.json();
}),
+ loader.loadAsync(POLE_GLB_URL),
+ loader.loadAsync(STAGE_GLB_URL),
]);
const template = gltf.scene;
@@ -474,15 +707,37 @@ async function bootstrap() {
if (n.isMesh) n.castShadow = true;
});
+ const poleTemplate = poleGltf.scene;
+ const stageTemplate = stageGltf.scene;
+
animationDefs = manifest.filter((d) => REQUIRED_CLIPS.has(d.name));
for (const station of stations) {
+ station.attachProps({ poleTemplate, stageTemplate });
station.attachAvatar(template, animationDefs);
}
+ // Backfill history + open the SSE channel so this tab sees other tabs'
+ // tips. Both run side-effect-only and don't block the stage being ready.
+ loadInitialTips();
+ subscribeTipStream();
+
setStatus('Tip a pole to make her dance.', { kind: 'ok' });
}
+// ── Audio mixer (Web Audio API, lazy-created on first user gesture) ──────
+const audio = new ClubAudio();
+// Other modules (rim-light pulse from prompt 04) read getPeak() each frame
+// via this handle. They handle the no-context case themselves.
+if (typeof window !== 'undefined') window.__clubAudio = audio;
+
+// When a performance ends (PoleStation._endPerformance), fade the style
+// loop back to ambience. Decoupled via custom event so the station class
+// stays focused on motion.
+window.addEventListener('club:performance-end', () => {
+ audio.fadeOutStyle().catch((err) => console.warn('[club] fadeOutStyle', err));
+});
+
// ── Tip flow (x402 drop-in) ──────────────────────────────────────────────
async function tipDancer({ dancer, dance, button }) {
if (!window.X402?.pay) {
@@ -500,6 +755,17 @@ async function tipDancer({ dancer, dance, button }) {
return;
}
+ // First click on a Tip button is the user gesture browsers require to
+ // unlock AudioContext. Do this BEFORE opening the wallet modal so the
+ // gesture isn't lost by the time we settle. Failures here are
+ // non-fatal — the rest of the tip flow still works without audio.
+ try {
+ await audio.ensureContext();
+ audio.startAmbience().catch((err) => console.warn('[club] startAmbience', err));
+ } catch (err) {
+ console.warn('[club] audio unavailable', err);
+ }
+
const url = `${TIP_ENDPOINT}?dancer=${encodeURIComponent(dancer)}&dance=${encodeURIComponent(dance)}`;
button?.classList.add('is-pending');
@@ -518,14 +784,32 @@ async function tipDancer({ dancer, dance, button }) {
throw new Error(ticket?.error || 'tip did not settle');
}
station.startPerformance(ticket);
- pushFeed({
+
+ // Crossfade ambience → style loop in sync with the dancer walking
+ // out. Prefer the explicit `track` from the ticket; fall back to a
+ // dance-key lookup for older tickets/agents that don't send it yet.
+ const trackName = ticket.track || styleAudioFor(ticket.dance);
+ if (trackName) {
+ audio.fadeToStyle(trackName).then(() => {
+ const label = TRACK_LABELS[trackName] || trackName;
+ setStatus(`Now playing: ${label}`, { kind: 'ok' });
+ }).catch((err) => console.warn('[club] fadeToStyle', err));
+ }
+
+ // Local echo — renderTipRow's dedupe ring (keyed on ticket_id) drops
+ // the SSE copy if it arrives later; if the SSE copy wins the race the
+ // local echo here is the one that gets dropped instead.
+ renderTipRow({
+ ticket_id: ticket.ticketId,
dancer: ticket.dancer,
label: ticket.label || ticket.dance,
payer: ticket.payer,
- amountAtomics: ticket.amountAtomics,
+ amount_atomics: ticket.amountAtomics,
network: ticket.network,
- });
+ }, { live: true });
setStatus(`Dancer ${ticket.dancer} → ${ticket.label}`, { kind: 'ok' });
+ // Fire-and-forget refresh — keep the leaderboard in sync with the tip.
+ if (typeof fetchLeaderboard === 'function') fetchLeaderboard();
} catch (err) {
if (err?.code !== 'cancelled') {
setStatus(err?.message || 'tip failed', { kind: 'error' });
@@ -536,6 +820,23 @@ async function tipDancer({ dancer, dance, button }) {
}
}
+// ── Mute pill in top bar ─────────────────────────────────────────────────
+function bindMutePill() {
+ const btn = document.getElementById('club-audio-toggle');
+ if (!btn) return;
+ const render = () => {
+ btn.textContent = audio.muted ? '🔇 Audio off' : '🔊 Audio on';
+ btn.setAttribute('aria-pressed', audio.muted ? 'true' : 'false');
+ };
+ render();
+ btn.addEventListener('click', async () => {
+ try { await audio.ensureContext(); } catch {}
+ audio.setMuted(!audio.muted);
+ render();
+ });
+}
+bindMutePill();
+
// ── Free cam chip (shown while in VIP / house) ───────────────────────────
let freeCamChip = null;
function ensureFreeCamChip() {
@@ -720,6 +1021,104 @@ renderPoles();
}
}
+// ── Leaderboard — fetch + tabs + 30s refresh ─────────────────────────────
+// Rank dancers by USDC tipped over the selected window. We also surface
+// unpaid_atomics so the user can watch the value drain as the payout cron
+// sweeps. Polling pauses when the tab is hidden to spare RPC budget.
+const LB_REFRESH_MS = 30_000;
+let lbWindow = 'day';
+let lbTimer = null;
+let lbInflight = false;
+
+async function fetchLeaderboard() {
+ if (!lbRowsEl || lbInflight) return;
+ lbInflight = true;
+ try {
+ const res = await fetch(`/api/club/leaderboard?window=${encodeURIComponent(lbWindow)}`, {
+ headers: { accept: 'application/json' },
+ cache: 'no-store',
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const body = await res.json();
+ renderLeaderboard(body.rows || []);
+ } catch (err) {
+ console.error('[club] leaderboard fetch failed', err);
+ // Don't blow away an already-rendered table on a transient hiccup.
+ if (!lbRowsEl.querySelector('.club-lb-row')) {
+ lbRowsEl.innerHTML = '<div class="club-lb-empty">Leaderboard unavailable.</div>';
+ }
+ } finally {
+ lbInflight = false;
+ }
+}
+
+function renderLeaderboard(rows) {
+ if (!lbRowsEl) return;
+ if (!rows.length) {
+ lbRowsEl.innerHTML = '<div class="club-lb-empty">No dancers registered yet.</div>';
+ return;
+ }
+ const frag = document.createDocumentFragment();
+ rows.forEach((row, i) => {
+ const total = Number(row.total_atomics || 0);
+ const unpaid = Number(row.unpaid_atomics || 0);
+ const div = document.createElement('div');
+ div.className = 'club-lb-row' + (unpaid > 0 ? ' has-unpaid' : '');
+ const dancer = String(row.dancer || '').replace(/[<>&]/g, '');
+ const name = String(row.display_name || `Dancer ${dancer}`).replace(/[<>&]/g, '');
+ const unpaidLabel = unpaid > 0
+ ? `<small>${fmtUsd(unpaid)} unpaid</small>`
+ : '';
+ div.innerHTML = `
+ <span class="club-lb-rank">${i + 1}</span>
+ <span class="club-lb-name">${name}${unpaidLabel}</span>
+ <span class="club-lb-amt">${total > 0 ? fmtUsd(total) : '—'}</span>
+ <span class="club-lb-tips">${row.tip_count || 0}×</span>
+ `;
+ frag.appendChild(div);
+ });
+ lbRowsEl.innerHTML = '';
+ lbRowsEl.appendChild(frag);
+}
+
+function setLeaderboardWindow(next) {
+ if (next === lbWindow) return;
+ lbWindow = next;
+ for (const tab of lbTabsEls) {
+ tab.classList.toggle('is-active', tab.dataset.window === next);
+ }
+ fetchLeaderboard();
+}
+
+for (const tab of lbTabsEls) {
+ tab.addEventListener('click', () => {
+ const w = tab.dataset.window;
+ if (w) setLeaderboardWindow(w);
+ });
+}
+
+function startLeaderboardPolling() {
+ stopLeaderboardPolling();
+ lbTimer = setInterval(fetchLeaderboard, LB_REFRESH_MS);
+}
+function stopLeaderboardPolling() {
+ if (lbTimer) {
+ clearInterval(lbTimer);
+ lbTimer = null;
+ }
+}
+document.addEventListener('visibilitychange', () => {
+ if (document.hidden) {
+ stopLeaderboardPolling();
+ } else {
+ fetchLeaderboard();
+ startLeaderboardPolling();
+ }
+});
+
+fetchLeaderboard();
+startLeaderboardPolling();
+
bootstrap()
.catch((err) => {
console.error('[club] bootstrap failed', err);
diff --git a/tests/api/club-leaderboard.test.js b/tests/api/club-leaderboard.test.js
new file mode 100644
index 000000000..b0ca34113
--- /dev/null
+++ b/tests/api/club-leaderboard.test.js
@@ -0,0 +1,116 @@
+// /api/club/leaderboard — window whitelist + shape of returned rows.
+//
+// The endpoint runs one of four hard-coded tagged-template queries depending
+// on `window`; user input never reaches the SQL string. We assert that:
+// - each valid window invokes exactly one sql call
+// - the SQL string carries the matching interval literal
+// - rejects unknown windows with 400 bad_window
+// - default window (no query param) is 'all'
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock }));
+
+vi.mock('../../api/_lib/env.js', () => ({
+ env: { APP_ORIGIN: 'http://localhost:3000' },
+}));
+
+vi.mock('../../api/_lib/sentry.js', () => ({
+ captureException: vi.fn(),
+}));
+
+vi.mock('../../api/_lib/zauth.js', () => ({
+ instrument: () => null,
+ drain: async () => {},
+}));
+
+const { default: handler } = await import('../../api/club/leaderboard.js');
+
+function mkReq({ method = 'GET', query = {}, headers = {} } = {}) {
+ const url = `/api/club/leaderboard?${new URLSearchParams(query).toString()}`;
+ return { method, url, query, headers, on() {}, destroy() {} };
+}
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: undefined,
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(b) {
+ this.body = b;
+ this.writableEnded = true;
+ },
+ };
+}
+
+async function invoke(opts = {}) {
+ const req = mkReq(opts);
+ const res = mkRes();
+ await handler(req, res);
+ return { res, status: res.statusCode, body: res.body ? JSON.parse(res.body) : undefined };
+}
+
+const sampleRows = [
+ { dancer: '1', display_name: 'Nyx', total_atomics: '5000', tip_count: 2, unpaid_atomics: '5000' },
+ { dancer: '2', display_name: 'Ari', total_atomics: '0', tip_count: 0, unpaid_atomics: '0' },
+ { dancer: '3', display_name: 'Sable', total_atomics: '0', tip_count: 0, unpaid_atomics: '0' },
+ { dancer: '4', display_name: 'Vesper', total_atomics: '0', tip_count: 0, unpaid_atomics: '0' },
+];
+
+beforeEach(() => {
+ sqlMock.mockReset();
+ sqlMock.mockResolvedValue(sampleRows);
+});
+
+describe('GET /api/club/leaderboard', () => {
+ it('rejects an unknown window with 400 bad_window', async () => {
+ const { status, body } = await invoke({ query: { window: 'forever' } });
+ expect(status).toBe(400);
+ expect(body.error).toBe('bad_window');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('defaults to "all" when window is omitted', async () => {
+ const { status, body } = await invoke();
+ expect(status).toBe(200);
+ expect(body.window).toBe('all');
+ expect(body.rows).toEqual(sampleRows);
+ expect(sqlMock).toHaveBeenCalledOnce();
+ });
+
+ it.each([
+ ['hour', "interval '1 hour'"],
+ ['day', "interval '24 hours'"],
+ ['week', "interval '7 days'"],
+ ])('window=%s uses %s in the SQL string', async (window, intervalLiteral) => {
+ await invoke({ query: { window } });
+ expect(sqlMock).toHaveBeenCalledOnce();
+ // Neon tagged templates pass the strings array as the first arg.
+ const callArgs = sqlMock.mock.calls[0];
+ const strings = callArgs[0];
+ const fullSql = strings.join('?');
+ expect(fullSql).toContain(intervalLiteral);
+ });
+
+ it('window=all does not include any "interval" clause', async () => {
+ await invoke({ query: { window: 'all' } });
+ const strings = sqlMock.mock.calls[0][0];
+ const fullSql = strings.join('?');
+ expect(fullSql).not.toContain('interval ');
+ });
+
+ it('rejects non-GET methods with 405', async () => {
+ const { status } = await invoke({ method: 'POST' });
+ expect(status).toBe(405);
+ });
+
+ it('echoes the window back in the response', async () => {
+ const { body } = await invoke({ query: { window: 'day' } });
+ expect(body.window).toBe('day');
+ });
+});
diff --git a/tests/api/club-payouts-cron.test.js b/tests/api/club-payouts-cron.test.js
new file mode 100644
index 000000000..da61b4a3a
--- /dev/null
+++ b/tests/api/club-payouts-cron.test.js
@@ -0,0 +1,267 @@
+// /api/_lib/club/sweep.js — runClubPayoutSweep behavior.
+//
+// We test the sweep at the sweep-function level (not via the HTTP handler)
+// because that's where the interesting logic lives: dust threshold, claim
+// before send, ledger insert, per-dancer error isolation.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// ── sql mock ─────────────────────────────────────────────────────────────
+// Queue-based: each tagged-template call consumes one entry. The first arg
+// is the strings array; we use it to route mocks to the matching query.
+
+const sqlCalls = [];
+const sqlMock = vi.fn(async (strings, ...values) => {
+ const sql = Array.isArray(strings) ? strings.join('?') : String(strings);
+ const call = { sql, values };
+ sqlCalls.push(call);
+ const handler = sqlRouter(sql);
+ return handler ? handler(values, call) : [];
+});
+
+vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock }));
+
+vi.mock('../../api/_lib/env.js', () => ({
+ env: { APP_ORIGIN: 'http://localhost:3000' },
+}));
+
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: vi.fn() }));
+
+// We never want the real on-chain senders to load — they import heavy SDKs.
+vi.mock('../../api/_lib/club/payouts.js', () => ({
+ sendClubPayout: vi.fn(),
+ sendClubUsdcSolana: vi.fn(),
+ sendClubUsdcBase: vi.fn(),
+}));
+
+const { runClubPayoutSweep, DUST_THRESHOLD_ATOMICS } = await import('../../api/_lib/club/sweep.js');
+
+// ── Mock state ────────────────────────────────────────────────────────────
+
+let mockState;
+
+function resetMockState() {
+ mockState = {
+ dancers: [], // [{ dancer, display_name, evm_address, solana_address }]
+ groups: [], // unpaid groups as the cron will see them
+ claims: new Map(), // claimToken → array of claimed ids
+ ledger: [], // club_payouts inserts captured here
+ paidUpdates: [], // paid_tx = signature updates
+ recountTotal: null, // override recount sum
+ };
+}
+
+function sqlRouter(sql) {
+ // 1. syncDancerWalletsFromEnv — read step
+ if (/select dancer, evm_address, solana_address from club_dancer_wallets/.test(sql)) {
+ return () => mockState.dancers.map((d) => ({
+ dancer: d.dancer,
+ evm_address: d.evm_address,
+ solana_address: d.solana_address,
+ }));
+ }
+ // 2. syncDancerWalletsFromEnv — write step (no-op for tests)
+ if (/update club_dancer_wallets/.test(sql)) {
+ return () => [];
+ }
+ // 3. Main group query
+ if (/from club_tips t/.test(sql) && /group by/.test(sql) && /having/.test(sql)) {
+ return () => mockState.groups;
+ }
+ // 4. Claim step: update club_tips set paid_at = now(), paid_tx = $1 ...
+ if (/update club_tips/.test(sql) && /paid_at = now\(\)/.test(sql) && /returning id/.test(sql)) {
+ return ([token, ids]) => {
+ const claimedIds = [...ids];
+ mockState.claims.set(token, claimedIds);
+ return claimedIds.map((id) => ({ id }));
+ };
+ }
+ // 5. Recount after claim (sum check)
+ if (/select coalesce\(sum\(amount_atomics\), 0\)/.test(sql) && /from club_tips/.test(sql)) {
+ return () => [{ total: mockState.recountTotal != null
+ ? mockState.recountTotal
+ : mockState.groups[0]?.total_atomics || '0' }];
+ }
+ // 6. Insert into club_payouts
+ if (/insert into club_payouts/.test(sql)) {
+ return (values) => {
+ mockState.ledger.push({
+ dancer: values[0],
+ network: values[1],
+ asset: values[2],
+ amount_atomics: values[3],
+ tx: values[4],
+ swept_tip_count: values[5],
+ });
+ return [];
+ };
+ }
+ // 7. Rollback claim on send failure (must come before the settle
+ // branch — the rollback SQL also contains `and paid_tx = `).
+ if (/update club_tips/.test(sql) && /set paid_at = null/.test(sql)) {
+ return (values) => {
+ mockState.paidUpdates.push({ rollback: values[1] });
+ return [];
+ };
+ }
+ // 8. Settle paid_tx = real signature
+ if (/update club_tips/.test(sql) && /set paid_tx = /.test(sql) && /and paid_tx = /.test(sql)) {
+ return (values) => {
+ mockState.paidUpdates.push({ signature: values[0], claimToken: values[2] });
+ return [];
+ };
+ }
+ return null;
+}
+
+// ── Tests ────────────────────────────────────────────────────────────────
+
+beforeEach(() => {
+ sqlCalls.length = 0;
+ sqlMock.mockClear();
+ resetMockState();
+ mockState.dancers = [
+ { dancer: '1', display_name: 'Nyx', evm_address: '0x' + '11'.repeat(20), solana_address: 'SoLaNa1111111111111111111111111111111111111' },
+ { dancer: '2', display_name: 'Ari', evm_address: null, solana_address: 'SoLaNa2222222222222222222222222222222222222' },
+ ];
+});
+
+describe('runClubPayoutSweep', () => {
+ it('skips groups below the dust threshold (database HAVING filter)', async () => {
+ // Mimic the SQL HAVING filter: cron query simply returns no groups
+ // when totals are below threshold. Sweep must do nothing.
+ mockState.groups = [];
+
+ const send = vi.fn();
+ const summary = await runClubPayoutSweep({ send });
+
+ expect(send).not.toHaveBeenCalled();
+ expect(summary.paid).toEqual([]);
+ expect(summary.groups_considered).toBe(0);
+ expect(summary.total_atomics_sent).toBe('0');
+ });
+
+ it('sweeps a group above dust → sends, inserts ledger, marks tips paid', async () => {
+ const tipIds = ['tip-a', 'tip-b', 'tip-c'];
+ const total = (DUST_THRESHOLD_ATOMICS * 2n).toString();
+ mockState.groups = [{
+ dancer: '1',
+ display_name: 'Nyx',
+ evm_address: mockState.dancers[0].evm_address,
+ solana_address: mockState.dancers[0].solana_address,
+ network: 'solana',
+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ tip_ids: tipIds,
+ total_atomics: total,
+ tip_count: 3,
+ }];
+ mockState.recountTotal = total;
+
+ const send = vi.fn().mockResolvedValue({
+ signature: 'sigSOL123',
+ network: 'solana',
+ amount_atomics: total,
+ });
+
+ const summary = await runClubPayoutSweep({ send });
+
+ expect(send).toHaveBeenCalledOnce();
+ expect(send.mock.calls[0][0]).toMatchObject({
+ network: 'solana',
+ recipient: mockState.dancers[0].solana_address,
+ amount: BigInt(total),
+ });
+ expect(mockState.ledger).toHaveLength(1);
+ expect(mockState.ledger[0]).toMatchObject({
+ dancer: '1',
+ network: 'solana',
+ amount_atomics: total,
+ tx: 'sigSOL123',
+ swept_tip_count: 3,
+ });
+ expect(summary.paid).toHaveLength(1);
+ expect(summary.paid[0]).toMatchObject({
+ dancer: '1',
+ tx: 'sigSOL123',
+ tip_count: 3,
+ });
+ expect(summary.total_atomics_sent).toBe(total);
+ // Settle update must have run with the real signature.
+ const settle = mockState.paidUpdates.find((u) => u.signature === 'sigSOL123');
+ expect(settle).toBeTruthy();
+ });
+
+ it('skips a (dancer, network) group when the recipient wallet is missing', async () => {
+ const total = (DUST_THRESHOLD_ATOMICS * 3n).toString();
+ mockState.groups = [{
+ dancer: '2',
+ display_name: 'Ari',
+ evm_address: null, // ← missing
+ solana_address: mockState.dancers[1].solana_address,
+ network: 'base',
+ asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
+ tip_ids: ['tip-x'],
+ total_atomics: total,
+ tip_count: 1,
+ }];
+
+ const send = vi.fn();
+ const summary = await runClubPayoutSweep({ send });
+
+ expect(send).not.toHaveBeenCalled();
+ expect(mockState.ledger).toHaveLength(0);
+ expect(summary.skipped).toHaveLength(1);
+ expect(summary.skipped[0]).toMatchObject({
+ dancer: '2',
+ network: 'base',
+ reason: 'no_wallet',
+ });
+ });
+
+ it('isolates per-dancer errors — one bad sweep does not block the others', async () => {
+ const total = (DUST_THRESHOLD_ATOMICS * 4n).toString();
+ mockState.groups = [
+ {
+ dancer: '1',
+ display_name: 'Nyx',
+ evm_address: mockState.dancers[0].evm_address,
+ solana_address: mockState.dancers[0].solana_address,
+ network: 'solana',
+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ tip_ids: ['t-a'],
+ total_atomics: total,
+ tip_count: 1,
+ },
+ {
+ dancer: '1',
+ display_name: 'Nyx',
+ evm_address: mockState.dancers[0].evm_address,
+ solana_address: mockState.dancers[0].solana_address,
+ network: 'base',
+ asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
+ tip_ids: ['t-b'],
+ total_atomics: total,
+ tip_count: 1,
+ },
+ ];
+ mockState.recountTotal = total;
+
+ const send = vi.fn()
+ .mockRejectedValueOnce(new Error('solana RPC blew up'))
+ .mockResolvedValueOnce({ signature: '0xBASE_OK', network: 'base', amount_atomics: total });
+
+ const summary = await runClubPayoutSweep({ send });
+
+ expect(send).toHaveBeenCalledTimes(2);
+ expect(summary.errored).toHaveLength(1);
+ expect(summary.errored[0]).toMatchObject({ dancer: '1', network: 'solana' });
+ expect(summary.paid).toHaveLength(1);
+ expect(summary.paid[0]).toMatchObject({ dancer: '1', network: 'base', tx: '0xBASE_OK' });
+ // Ledger only got the successful row.
+ expect(mockState.ledger).toHaveLength(1);
+ expect(mockState.ledger[0].network).toBe('base');
+ // Rollback recorded for the failing Solana sweep.
+ const rollback = mockState.paidUpdates.find((u) => u.rollback);
+ expect(rollback).toBeTruthy();
+ });
+});
diff --git a/tests/api/club-tips-stream.test.js b/tests/api/club-tips-stream.test.js
new file mode 100644
index 000000000..11beee718
--- /dev/null
+++ b/tests/api/club-tips-stream.test.js
@@ -0,0 +1,187 @@
+// Integration-flavored test for /api/club/tips/stream — spins the handler
+// up on a real local HTTP server, opens an SSE consumer via fetch(), seeds
+// rows through the mocked `sql` template, and asserts the consumer receives
+// a `tip` event with the inserted ticket_id within one poll cadence.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { createServer } from 'node:http';
+import { once } from 'node:events';
+
+const sqlState = {
+ queue: [],
+ calls: [],
+};
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ const query = typeof strings === 'string' ? strings : strings.join('?');
+ sqlState.calls.push({ query, values });
+ return sqlState.queue.length === 0 ? [] : sqlState.queue.shift();
+ }),
+}));
+
+const { default: handler } = await import('../../api/club/tips-stream.js');
+
+let server;
+let baseUrl;
+let controllers = [];
+
+beforeEach(async () => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+ server = createServer((req, res) => {
+ // Vercel handlers get `req.query` populated for them by the platform —
+ // we mimic that here, although tips-stream doesn't use any query params.
+ req.query = Object.fromEntries(new URL(req.url, 'http://localhost').searchParams);
+ handler(req, res);
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address();
+ baseUrl = `http://127.0.0.1:${port}`;
+});
+
+afterEach(async () => {
+ for (const c of controllers) {
+ try { c.abort(); } catch {}
+ }
+ controllers = [];
+ await new Promise((resolve) => server.close(resolve));
+});
+
+// Stateful SSE parser bound to one response body. Returns an object with a
+// `waitFor(eventName, timeoutMs)` method that consumes frames from the
+// stream until the requested event arrives. Sharing a single reader avoids
+// the "ReadableStream is locked" error you get from calling getReader()
+// twice on the same body.
+function makeSseConsumer(body) {
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ const pending = []; // FIFO of parsed { event, data } frames
+ let buffer = '';
+ let streamDone = false;
+
+ const drainBuffer = () => {
+ let idx;
+ while ((idx = buffer.indexOf('\n\n')) !== -1) {
+ const frame = buffer.slice(0, idx);
+ buffer = buffer.slice(idx + 2);
+ if (frame.startsWith(':')) continue; // heartbeat comment
+ let event = 'message';
+ let data = '';
+ for (const line of frame.split('\n')) {
+ if (line.startsWith('event:')) event = line.slice(6).trim();
+ else if (line.startsWith('data:')) data += line.slice(5).trim();
+ }
+ pending.push({ event, data });
+ }
+ };
+
+ const readChunk = async (timeoutMs) => {
+ const timer = new Promise((resolve) =>
+ setTimeout(() => resolve({ done: true, value: null, timedOut: true }), timeoutMs),
+ );
+ const result = await Promise.race([reader.read(), timer]);
+ if (result.timedOut) return false;
+ if (result.done) { streamDone = true; return false; }
+ buffer += decoder.decode(result.value, { stream: true });
+ drainBuffer();
+ return true;
+ };
+
+ return {
+ async waitFor(eventName, timeoutMs = 4000) {
+ const deadline = Date.now() + timeoutMs;
+ while (true) {
+ const idx = pending.findIndex((p) => p.event === eventName);
+ if (idx !== -1) {
+ const frame = pending.splice(idx, 1)[0];
+ try { return JSON.parse(frame.data); } catch { return frame.data; }
+ }
+ if (streamDone) {
+ throw new Error(`stream ended before "${eventName}" event`);
+ }
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) {
+ throw new Error(`timed out waiting for SSE event "${eventName}"`);
+ }
+ await readChunk(remaining);
+ }
+ },
+ close() {
+ try { reader.cancel(); } catch {}
+ },
+ };
+}
+
+describe('GET /api/club/tips/stream', () => {
+ it('emits a `hello` frame as soon as the connection opens', async () => {
+ const controller = new AbortController();
+ controllers.push(controller);
+ const r = await fetch(`${baseUrl}/api/club/tips/stream`, { signal: controller.signal });
+ expect(r.status).toBe(200);
+ expect(r.headers.get('content-type')).toMatch(/text\/event-stream/);
+ expect(r.headers.get('x-accel-buffering')).toBe('no');
+ const sse = makeSseConsumer(r.body);
+ try {
+ const hello = await sse.waitFor('hello', 2000);
+ expect(hello).toHaveProperty('ts');
+ } finally {
+ sse.close();
+ controller.abort();
+ }
+ });
+
+ it('delivers a `tip` event when a new club_tips row appears', async () => {
+ const controller = new AbortController();
+ controllers.push(controller);
+ const r = await fetch(`${baseUrl}/api/club/tips/stream`, { signal: controller.signal });
+ const sse = makeSseConsumer(r.body);
+ try {
+ // Wait for hello so we know the stream is established + the poller
+ // has registered its initial cursor.
+ await sse.waitFor('hello', 2000);
+
+ // Seed a row that will be picked up on the next poll. created_at is
+ // far in the future so the cursor comparison fires regardless of
+ // clock skew between the test and the handler.
+ const row = {
+ ticket_id: 'stream-1',
+ dancer: '3',
+ dance: 'silly',
+ clip: 'silly',
+ label: 'Silly',
+ payer: '0xfeed',
+ network: 'base',
+ amount_atomics: '1000',
+ asset: '0xUSDC',
+ started_at: new Date('2030-01-01T00:00:00Z'),
+ ends_at: new Date('2030-01-01T00:00:10Z'),
+ created_at: new Date('2030-01-01T00:00:00.500Z'),
+ };
+ sqlState.queue.push([row]);
+
+ const event = await sse.waitFor('tip', 3000);
+ expect(event.ticket_id).toBe('stream-1');
+ expect(event.dancer).toBe('3');
+ expect(event.dance).toBe('silly');
+ } finally {
+ sse.close();
+ controller.abort();
+ }
+ });
+
+ it('rejects non-GET methods with 405', async () => {
+ const r = await fetch(`${baseUrl}/api/club/tips/stream`, { method: 'POST' });
+ expect(r.status).toBe(405);
+ await r.body?.cancel();
+ });
+
+ it('handles OPTIONS preflight without opening a stream', async () => {
+ const r = await fetch(`${baseUrl}/api/club/tips/stream`, {
+ method: 'OPTIONS',
+ headers: { origin: 'https://example.com' },
+ });
+ expect(r.status).toBe(204);
+ await r.body?.cancel();
+ });
+});
diff --git a/tests/api/club-tips.test.js b/tests/api/club-tips.test.js
new file mode 100644
index 000000000..b543b41b4
--- /dev/null
+++ b/tests/api/club-tips.test.js
@@ -0,0 +1,161 @@
+// Tests for GET /api/club/tips — the recent-tips backfill that hydrates the
+// /club "Live tips" widget on page boot. Mocks `sql` so the handler runs in
+// pure-unit mode.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+const sqlState = {
+ queue: [],
+ calls: [],
+};
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ const query = typeof strings === 'string' ? strings : strings.join('?');
+ sqlState.calls.push({ query, values });
+ return sqlState.queue.length === 0 ? [] : sqlState.queue.shift();
+ }),
+}));
+
+const { default: handler } = await import('../../api/club/tips.js');
+
+function makeReq({ method = 'GET', url = '/api/club/tips', headers = {}, query = null } = {}) {
+ const r = Readable.from([]);
+ r.method = method;
+ r.url = url;
+ r.headers = { host: 'localhost', ...headers };
+ if (query) r.query = query;
+ return r;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ writeHead(status, headers = {}) {
+ this.statusCode = status;
+ for (const [k, v] of Object.entries(headers)) {
+ this.headers[k.toLowerCase()] = v;
+ }
+ },
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ write(chunk) {
+ this.body += chunk;
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ on() {},
+ };
+}
+
+async function invoke(opts = {}) {
+ const req = makeReq(opts);
+ const res = makeRes();
+ await handler(req, res);
+ let payload = null;
+ if (res.body) {
+ try { payload = JSON.parse(res.body); } catch { payload = res.body; }
+ }
+ return { res, status: res.statusCode, body: payload };
+}
+
+const sampleRow = {
+ ticket_id: 't-1',
+ dancer: '1',
+ dance: 'rumba',
+ clip: 'rumba',
+ label: 'Rumba',
+ payer: '0xabc',
+ network: 'base',
+ amount_atomics: '1000',
+ asset: '0xUSDC',
+ started_at: new Date('2026-05-21T10:00:00Z'),
+ ends_at: new Date('2026-05-21T10:00:14Z'),
+ created_at: new Date('2026-05-21T10:00:01Z'),
+};
+
+beforeEach(() => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+});
+
+describe('GET /api/club/tips', () => {
+ it('returns the recent rows as { tips: [...] }', async () => {
+ sqlState.queue.push([sampleRow]);
+ const { status, body } = await invoke();
+ expect(status).toBe(200);
+ // Dates round-trip through JSON.stringify as ISO strings; rebuild the
+ // expectation accordingly so the deep-equal compares apples to apples.
+ expect(body).toEqual({
+ tips: [{
+ ...sampleRow,
+ started_at: sampleRow.started_at.toISOString(),
+ ends_at: sampleRow.ends_at.toISOString(),
+ created_at: sampleRow.created_at.toISOString(),
+ }],
+ });
+ expect(sqlState.calls).toHaveLength(1);
+ });
+
+ it('defaults to limit=20 when not provided', async () => {
+ sqlState.queue.push([]);
+ await invoke();
+ const call = sqlState.calls[0];
+ expect(call.values).toEqual(expect.arrayContaining([20]));
+ });
+
+ it('clamps absurdly large limit to 100', async () => {
+ sqlState.queue.push([]);
+ await invoke({ query: { limit: '9999' } });
+ const call = sqlState.calls[0];
+ expect(call.values).toEqual(expect.arrayContaining([100]));
+ });
+
+ it('clamps non-positive limit to 1', async () => {
+ sqlState.queue.push([]);
+ await invoke({ query: { limit: '0' } });
+ const call = sqlState.calls[0];
+ expect(call.values).toEqual(expect.arrayContaining([1]));
+ });
+
+ it('falls back to default when limit is non-numeric', async () => {
+ sqlState.queue.push([]);
+ await invoke({ query: { limit: 'banana' } });
+ const call = sqlState.calls[0];
+ expect(call.values).toEqual(expect.arrayContaining([20]));
+ });
+
+ it('filters by dancer when the query is provided', async () => {
+ sqlState.queue.push([sampleRow]);
+ await invoke({ query: { dancer: '2' } });
+ const call = sqlState.calls[0];
+ expect(call.query).toMatch(/where dancer = \?/i);
+ expect(call.values).toEqual(expect.arrayContaining(['2']));
+ });
+
+ it('truncates pathologically long dancer values to 4 chars (defense-in-depth)', async () => {
+ sqlState.queue.push([]);
+ await invoke({ query: { dancer: '1234567890' } });
+ const call = sqlState.calls[0];
+ expect(call.values).toEqual(expect.arrayContaining(['1234']));
+ });
+
+ it('handles OPTIONS preflight without hitting the DB', async () => {
+ const { status } = await invoke({ method: 'OPTIONS', headers: { origin: 'https://example.com' } });
+ expect(status).toBe(204);
+ expect(sqlState.calls).toHaveLength(0);
+ });
+
+ it('rejects non-GET methods with 405', async () => {
+ const { status, body } = await invoke({ method: 'POST' });
+ expect(status).toBe(405);
+ expect(body?.error).toBe('method_not_allowed');
+ });
+});
diff --git a/tests/api/dance-tip-insert.test.js b/tests/api/dance-tip-insert.test.js
new file mode 100644
index 000000000..17147e450
--- /dev/null
+++ b/tests/api/dance-tip-insert.test.js
@@ -0,0 +1,141 @@
+// Tests that the settled-payment side of /api/x402/dance-tip writes a row
+// into `club_tips`. The pure-helpers (STYLES, pickStyle, pickDancer,
+// buildTicket) are exercised in dance-tip.test.js — this file mocks the
+// `paidEndpoint` wrapper so we can call the handler closure directly with
+// a fake (req, requirement, payer) and inspect the sql tagged-template
+// invocations.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// Capture the spec passed to paidEndpoint so we can grab the inner handler.
+let capturedSpec = null;
+vi.mock('../../api/_lib/x402-paid-endpoint.js', () => ({
+ paidEndpoint: (spec) => {
+ capturedSpec = spec;
+ return async () => {};
+ },
+}));
+
+const sqlState = {
+ queue: [],
+ calls: [],
+};
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn((strings, ...values) => {
+ const query = typeof strings === 'string' ? strings : strings.join('?');
+ sqlState.calls.push({ query, values });
+ // Tagged-template usage returns a thenable so `.catch(...)` chains work.
+ const result = sqlState.queue.length === 0 ? [] : sqlState.queue.shift();
+ if (result instanceof Error) return Promise.reject(result);
+ return Promise.resolve(result);
+ }),
+}));
+
+// Importing the module triggers the paidEndpoint call → captures the spec.
+await import('../../api/x402/dance-tip.js');
+
+beforeEach(() => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+});
+
+function makeReq(query) {
+ return {
+ method: 'GET',
+ query,
+ headers: { host: 'localhost' },
+ };
+}
+
+const REQUIREMENT = {
+ network: 'base',
+ amount: '1000',
+ asset: '0xUSDC',
+};
+
+describe('/api/x402/dance-tip settlement → club_tips insert', () => {
+ it('inserts one row with the ticket details after the handler resolves', async () => {
+ expect(capturedSpec, 'paidEndpoint was never called — module import failed').toBeTruthy();
+
+ const ticket = await capturedSpec.handler({
+ req: makeReq({ dancer: '2', dance: 'rumba' }),
+ res: {},
+ requirement: REQUIREMENT,
+ payer: '0xPayer',
+ });
+
+ // The settled JSON returned to the caller carries the ticket details.
+ expect(ticket.ok).toBe(true);
+ expect(ticket.dancer).toBe('2');
+ expect(ticket.dance).toBe('rumba');
+ expect(typeof ticket.ticketId).toBe('string');
+
+ // Yield to the microtask queue so the fire-and-forget `.catch(...)`
+ // chain attached to the sql call has a turn to run.
+ await new Promise((r) => setImmediate(r));
+
+ expect(sqlState.calls).toHaveLength(1);
+ const call = sqlState.calls[0];
+ expect(call.query).toMatch(/insert into club_tips/i);
+ expect(call.query).toMatch(/on conflict \(ticket_id\) do nothing/i);
+ // The bound values match the ticket the caller saw — same id, same dancer.
+ expect(call.values).toEqual(
+ expect.arrayContaining([
+ ticket.ticketId, '2', 'rumba', 'rumba',
+ '0xPayer', 'base', '1000', '0xUSDC',
+ ]),
+ );
+ });
+
+ it('does not block the response when the insert promise rejects', async () => {
+ expect(capturedSpec).toBeTruthy();
+ sqlState.queue.push(new Error('neon: fetch failed'));
+
+ // Silence the expected console.error so test output stays clean.
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const ticket = await capturedSpec.handler({
+ req: makeReq({ dancer: '1', dance: 'hiphop' }),
+ res: {},
+ requirement: REQUIREMENT,
+ payer: '0xPayer',
+ });
+
+ // Handler still returns the ticket — Neon hiccups must not surface as
+ // 5xx after the payment already settled.
+ expect(ticket.ok).toBe(true);
+ expect(ticket.dancer).toBe('1');
+
+ // Let the rejection settle so we see the captured console.error before
+ // the assertion below.
+ await new Promise((r) => setImmediate(r));
+ expect(errSpy).toHaveBeenCalled();
+ errSpy.mockRestore();
+ });
+
+ it('uses `on conflict (ticket_id) do nothing` so duplicate inserts are safe', async () => {
+ // Belt-and-suspenders: re-invoke twice with manually-collided ids by
+ // stubbing crypto.randomUUID. We cannot easily simulate Postgres's own
+ // uniqueness constraint with a vi.mock'd sql, but we *can* assert the
+ // SQL text in the wire payload carries the conflict clause both times.
+ await capturedSpec.handler({
+ req: makeReq({ dancer: '1', dance: 'rumba' }),
+ res: {},
+ requirement: REQUIREMENT,
+ payer: '0xPayer',
+ });
+ await capturedSpec.handler({
+ req: makeReq({ dancer: '1', dance: 'rumba' }),
+ res: {},
+ requirement: REQUIREMENT,
+ payer: '0xPayer',
+ });
+ await new Promise((r) => setImmediate(r));
+
+ expect(sqlState.calls.length).toBeGreaterThanOrEqual(2);
+ for (const call of sqlState.calls) {
+ expect(call.query).toMatch(/on conflict \(ticket_id\) do nothing/i);
+ }
+ });
+});
diff --git a/tests/api/dance-tip.test.js b/tests/api/dance-tip.test.js
new file mode 100644
index 000000000..3ef734ba9
--- /dev/null
+++ b/tests/api/dance-tip.test.js
@@ -0,0 +1,262 @@
+// Tests for /api/x402/dance-tip — the Pole Club tip endpoint.
+//
+// Pure-logic only — we exercise the exported helpers (STYLES, pickStyle,
+// pickDancer, buildTicket, BAZAAR_SCHEMA) rather than the paidEndpoint HTTP
+// wrapper. That keeps tests off the network and off the database while still
+// covering everything the wire format depends on.
+//
+// Coverage:
+// • STYLES keys + shape (free-floor single-clip vs. pole sequence styles)
+// • pickStyle resolves both shapes and rejects unknown styles
+// • pickDancer enforces the slot allowlist
+// • buildTicket emits `sequence` for sequence styles and omits it otherwise
+// • The bazaar schema advertises the new `dance` enum values + sequence shape
+
+import { describe, it, expect } from 'vitest';
+import {
+ STYLES,
+ pickStyle,
+ pickDancer,
+ buildTicket,
+ BAZAAR_SCHEMA,
+} from '../../api/x402/dance-tip.js';
+
+const FREE_FLOOR_KEYS = ['hiphop', 'rumba', 'silly', 'thriller', 'capoeira'];
+const POLE_KEYS = ['spin', 'climb', 'combo'];
+
+describe('STYLES — registry', () => {
+ it('keeps the existing free-floor single-clip styles', () => {
+ for (const key of FREE_FLOOR_KEYS) {
+ const style = STYLES[key];
+ expect(style, `${key} missing from STYLES`).toBeTruthy();
+ expect(typeof style.clip).toBe('string');
+ expect(style.loop).toBe(true);
+ expect(typeof style.durationSec).toBe('number');
+ expect(style.sequence).toBeUndefined();
+ }
+ });
+
+ it('declares the three pole choreography sequence styles', () => {
+ for (const key of POLE_KEYS) {
+ const style = STYLES[key];
+ expect(style, `${key} missing from STYLES`).toBeTruthy();
+ expect(Array.isArray(style.sequence)).toBe(true);
+ expect(style.sequence.length).toBeGreaterThan(0);
+ expect(style.track).toBe('pole');
+ expect(typeof style.label).toBe('string');
+ // Each step must name a clip + a positive duration so playSequence
+ // has something to crossfade to and a non-zero sleep between steps.
+ for (const step of style.sequence) {
+ expect(typeof step.clip).toBe('string');
+ expect(step.clip.length).toBeGreaterThan(0);
+ expect(step.durationSec).toBeGreaterThan(0);
+ }
+ }
+ });
+
+ it('spin sequence matches the documented (pole-spin, pole-bow) chain', () => {
+ expect(STYLES.spin.sequence).toEqual([
+ { clip: 'pole-spin', durationSec: 8 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ]);
+ expect(STYLES.spin.durationSec).toBe(10);
+ });
+
+ it('climb sequence matches (pole-climb, pole-invert, pole-bow)', () => {
+ expect(STYLES.climb.sequence).toEqual([
+ { clip: 'pole-climb', durationSec: 5 },
+ { clip: 'pole-invert', durationSec: 6 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ]);
+ expect(STYLES.climb.durationSec).toBe(13);
+ });
+
+ it('combo sequence chains spin → climb → invert → floorwork → bow', () => {
+ expect(STYLES.combo.sequence.map((s) => s.clip)).toEqual([
+ 'pole-spin',
+ 'pole-climb',
+ 'pole-invert',
+ 'pole-floorwork',
+ 'pole-bow',
+ ]);
+ expect(STYLES.combo.durationSec).toBe(18);
+ // Sum of step durations matches the advertised total.
+ const total = STYLES.combo.sequence.reduce((acc, s) => acc + s.durationSec, 0);
+ expect(total).toBe(18);
+ });
+
+ it('STYLES is frozen so the bazaar enum cannot drift at runtime', () => {
+ expect(Object.isFrozen(STYLES)).toBe(true);
+ });
+});
+
+describe('pickStyle', () => {
+ it('returns a normalized descriptor for a free-floor style', () => {
+ const s = pickStyle('rumba');
+ expect(s.key).toBe('rumba');
+ expect(s.clip).toBe('rumba');
+ expect(s.loop).toBe(true);
+ expect(s.durationSec).toBe(14);
+ expect(s.track).toBe('rumba');
+ expect(s.sequence).toBeUndefined();
+ });
+
+ it('returns sequence + first-step clip for a pole sequence style', () => {
+ const s = pickStyle('spin');
+ expect(s.key).toBe('spin');
+ expect(s.clip).toBe('pole-spin'); // first step lifted as legacy `clip`
+ expect(s.loop).toBe(false);
+ expect(s.track).toBe('pole');
+ expect(s.sequence).toEqual([
+ { clip: 'pole-spin', durationSec: 8 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ]);
+ });
+
+ it('lowercases + trims user input before lookup', () => {
+ expect(pickStyle(' SPIN ').key).toBe('spin');
+ expect(pickStyle('Rumba').key).toBe('rumba');
+ });
+
+ it('throws unknown_dance with status=400 for unregistered names', () => {
+ const calls = [
+ () => pickStyle('breakdance'),
+ () => pickStyle(''),
+ () => pickStyle(null),
+ () => pickStyle(undefined),
+ ];
+ for (const fn of calls) {
+ let caught;
+ try { fn(); } catch (e) { caught = e; }
+ expect(caught).toBeInstanceOf(Error);
+ expect(caught.status).toBe(400);
+ expect(caught.code).toBe('unknown_dance');
+ // The error message enumerates valid styles so the caller can recover.
+ expect(caught.message).toMatch(/spin/);
+ expect(caught.message).toMatch(/rumba/);
+ }
+ });
+});
+
+describe('pickDancer', () => {
+ it('accepts the four stage slot ids', () => {
+ for (const id of ['1', '2', '3', '4']) {
+ expect(pickDancer(id)).toBe(id);
+ }
+ });
+
+ it('rejects anything outside the allowlist with status=400', () => {
+ const bad = ['0', '5', 'one', '', null, undefined, ' '];
+ for (const v of bad) {
+ let caught;
+ try { pickDancer(v); } catch (e) { caught = e; }
+ expect(caught, `expected throw for ${JSON.stringify(v)}`).toBeInstanceOf(Error);
+ expect(caught.status).toBe(400);
+ expect(caught.code).toBe('unknown_dancer');
+ }
+ });
+
+ it('trims numeric strings before validation', () => {
+ expect(pickDancer(' 2 ')).toBe('2');
+ });
+});
+
+describe('buildTicket', () => {
+ const REQUIREMENT = {
+ network: 'solana',
+ amount: '1000',
+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ };
+
+ it('emits a single-clip ticket without a sequence field for free-floor styles', () => {
+ const style = pickStyle('rumba');
+ const now = new Date('2026-05-21T00:00:00.000Z');
+ const ticket = buildTicket({
+ dancer: '2',
+ style,
+ now,
+ payer: 'wwwPqsM4',
+ requirement: REQUIREMENT,
+ ticketId: 'tkt-1',
+ });
+ expect(ticket.ok).toBe(true);
+ expect(ticket.ticketId).toBe('tkt-1');
+ expect(ticket.dance).toBe('rumba');
+ expect(ticket.clip).toBe('rumba');
+ expect(ticket.loop).toBe(true);
+ expect(ticket.durationSec).toBe(14);
+ expect(ticket.track).toBe('rumba');
+ expect(ticket.sequence).toBeUndefined();
+ expect(ticket.startsAt).toBe('2026-05-21T00:00:00.000Z');
+ expect(ticket.endsAt).toBe('2026-05-21T00:00:14.000Z');
+ expect(ticket.network).toBe('solana');
+ expect(ticket.amountAtomics).toBe('1000');
+ });
+
+ it('emits a sequence ticket for pole styles with the chain attached', () => {
+ const style = pickStyle('climb');
+ const ticket = buildTicket({
+ dancer: '3',
+ style,
+ now: new Date('2026-05-21T00:00:00.000Z'),
+ payer: 'wwwPqsM4',
+ requirement: REQUIREMENT,
+ ticketId: 'tkt-2',
+ });
+ expect(ticket.dance).toBe('climb');
+ // `clip` carries the first step's clip for legacy consumers + the
+ // club_tips ledger row.
+ expect(ticket.clip).toBe('pole-climb');
+ expect(ticket.loop).toBe(false);
+ expect(ticket.durationSec).toBe(13);
+ expect(ticket.track).toBe('pole');
+ expect(ticket.sequence).toEqual([
+ { clip: 'pole-climb', durationSec: 5 },
+ { clip: 'pole-invert', durationSec: 6 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ]);
+ expect(ticket.endsAt).toBe('2026-05-21T00:00:13.000Z');
+ });
+
+ it('defaults payer + requirement fields to null when absent', () => {
+ const ticket = buildTicket({
+ dancer: '1',
+ style: pickStyle('hiphop'),
+ ticketId: 'tkt-3',
+ });
+ expect(ticket.payer).toBe(null);
+ expect(ticket.network).toBe(null);
+ expect(ticket.amountAtomics).toBe(null);
+ expect(ticket.asset).toBe(null);
+ });
+});
+
+describe('Bazaar discovery schema', () => {
+ it('marks the endpoint discoverable', () => {
+ expect(BAZAAR_SCHEMA.discoverable).toBe(true);
+ });
+
+ it("advertises every STYLES key in the input `dance` enum", () => {
+ // The bazaar schema wraps the inner queryParams JSON Schema — locate
+ // the `dance` property however the wrapper nests it.
+ const wireSchema = JSON.stringify(BAZAAR_SCHEMA.schema);
+ for (const key of [...FREE_FLOOR_KEYS, ...POLE_KEYS]) {
+ expect(wireSchema, `dance enum missing "${key}"`).toContain(`"${key}"`);
+ }
+ });
+
+ it('advertises the sequence ticket shape (clip + durationSec items)', () => {
+ const wireSchema = JSON.stringify(BAZAAR_SCHEMA.schema);
+ // The output schema lists a `sequence` array of {clip, durationSec}.
+ expect(wireSchema).toContain('"sequence"');
+ expect(wireSchema).toContain('"clip"');
+ expect(wireSchema).toContain('"durationSec"');
+ });
+
+ it('exposes a sequence-style OUTPUT_EXAMPLE so bazaar clients see the shape', () => {
+ const example = BAZAAR_SCHEMA.info.output.example;
+ expect(example.ok).toBe(true);
+ expect(Array.isArray(example.sequence)).toBe(true);
+ expect(example.sequence.length).toBeGreaterThan(0);
+ });
+});
diff --git a/tests/club-audio.test.js b/tests/club-audio.test.js
new file mode 100644
index 000000000..d828a0712
--- /dev/null
+++ b/tests/club-audio.test.js
@@ -0,0 +1,391 @@
+// tests/club-audio.test.js
+//
+// ClubAudio (Web Audio API mixer) — unit tests.
+//
+// We can't run a real AudioContext in node, so the tests install a tiny fake
+// Web Audio implementation on globalThis.window.AudioContext. The fake
+// records linearRampToValueAtTime / cancelScheduledValues calls on each gain
+// node so we can assert that crossfade scheduling matches the documented
+// behaviour:
+//
+// fadeToStyle(): ambience gain → 0.1, style gain → 0.75, both over durationMs.
+// fadeOutStyle(): style → 0, ambience → 0.35.
+// setMuted(true)/false: master gain → 0 / 0.75 over 0.15s.
+//
+// The fake fetch handler returns a minimal ArrayBuffer; decodeAudioData
+// resolves to a placeholder "buffer" object. Real audio decoding isn't
+// exercised — only the scheduling graph is.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+import { ClubAudio } from '../src/club-audio.js';
+
+// ── Fake Web Audio impl ──────────────────────────────────────────────────────
+
+class FakeAudioParam {
+ constructor(initial = 0) {
+ this.value = initial;
+ this.events = []; // {type, value, time}
+ }
+ setValueAtTime(value, time) {
+ this.value = value;
+ this.events.push({ type: 'set', value, time });
+ return this;
+ }
+ linearRampToValueAtTime(value, time) {
+ this.value = value;
+ this.events.push({ type: 'linearRamp', value, time });
+ return this;
+ }
+ cancelScheduledValues(time) {
+ this.events.push({ type: 'cancel', time });
+ return this;
+ }
+ _lastRamp() {
+ return [...this.events].reverse().find((e) => e.type === 'linearRamp');
+ }
+}
+
+class FakeGainNode {
+ constructor() {
+ this.gain = new FakeAudioParam(1);
+ this._connections = [];
+ }
+ connect(dest) {
+ this._connections.push(dest);
+ return dest;
+ }
+ disconnect() {
+ this._connections = [];
+ }
+}
+
+class FakeAnalyserNode {
+ constructor() {
+ this.fftSize = 256;
+ this.smoothingTimeConstant = 0;
+ this.frequencyBinCount = 128;
+ this._connections = [];
+ }
+ connect(dest) {
+ this._connections.push(dest);
+ return dest;
+ }
+ disconnect() {
+ this._connections = [];
+ }
+ getByteFrequencyData(buf) {
+ // Constant mid-level energy across the spectrum so getPeak() returns
+ // a deterministic non-zero value.
+ buf.fill(128);
+ }
+}
+
+class FakeBufferSource {
+ constructor() {
+ this.buffer = null;
+ this.loop = false;
+ this.started = false;
+ this.stopped = false;
+ this._connections = [];
+ }
+ connect(dest) {
+ this._connections.push(dest);
+ return dest;
+ }
+ disconnect() {
+ this._connections = [];
+ }
+ start() {
+ this.started = true;
+ }
+ stop() {
+ this.stopped = true;
+ }
+}
+
+class FakeAudioContext {
+ constructor() {
+ this.currentTime = 0;
+ this.destination = { _label: 'destination' };
+ this.state = 'running';
+ this.createdGains = [];
+ this.createdSources = [];
+ this.createdAnalysers = [];
+ this.decodedBuffers = [];
+ }
+ createGain() {
+ const g = new FakeGainNode();
+ this.createdGains.push(g);
+ return g;
+ }
+ createAnalyser() {
+ const a = new FakeAnalyserNode();
+ this.createdAnalysers.push(a);
+ return a;
+ }
+ createBufferSource() {
+ const s = new FakeBufferSource();
+ this.createdSources.push(s);
+ return s;
+ }
+ async decodeAudioData(arrayBuffer) {
+ const buf = { _fake: true, byteLength: arrayBuffer?.byteLength ?? 0 };
+ this.decodedBuffers.push(buf);
+ return buf;
+ }
+ async resume() {
+ this.state = 'running';
+ }
+}
+
+// ── Globals setup ────────────────────────────────────────────────────────────
+
+let originalWindow;
+let originalFetch;
+let originalLocalStorage;
+
+beforeEach(() => {
+ originalWindow = globalThis.window;
+ originalFetch = globalThis.fetch;
+ originalLocalStorage = globalThis.localStorage;
+
+ const fakeWindow = { AudioContext: FakeAudioContext };
+ globalThis.window = fakeWindow;
+
+ // In-memory localStorage so setMuted persistence doesn't touch disk.
+ const store = new Map();
+ globalThis.localStorage = {
+ getItem: (k) => (store.has(k) ? store.get(k) : null),
+ setItem: (k, v) => {
+ store.set(k, String(v));
+ },
+ removeItem: (k) => {
+ store.delete(k);
+ },
+ clear: () => {
+ store.clear();
+ },
+ };
+
+ // fetch returns a stub ArrayBuffer for any URL.
+ globalThis.fetch = vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ arrayBuffer: async () => new ArrayBuffer(64),
+ }));
+});
+
+afterEach(() => {
+ globalThis.window = originalWindow;
+ globalThis.fetch = originalFetch;
+ globalThis.localStorage = originalLocalStorage;
+});
+
+// ── Tests ────────────────────────────────────────────────────────────────────
+
+describe('ClubAudio.ensureContext', () => {
+ it('lazy-creates the AudioContext, master gain, and analyser', async () => {
+ const audio = new ClubAudio();
+ expect(audio.ctx).toBeNull();
+
+ await audio.ensureContext();
+ expect(audio.ctx).toBeInstanceOf(FakeAudioContext);
+ expect(audio.master).toBeInstanceOf(FakeGainNode);
+ expect(audio.analyser).toBeInstanceOf(FakeAnalyserNode);
+ // Master gain should be set to the documented 0.75 default.
+ expect(audio.master.gain.value).toBeCloseTo(0.75, 3);
+ });
+
+ it('is idempotent — re-calling does not allocate a new context', async () => {
+ const audio = new ClubAudio();
+ await audio.ensureContext();
+ const ctx = audio.ctx;
+ await audio.ensureContext();
+ expect(audio.ctx).toBe(ctx);
+ });
+});
+
+describe('ClubAudio.startAmbience', () => {
+ it('loads ambience and starts a looping buffer source at the ambience gain', async () => {
+ const audio = new ClubAudio();
+ await audio.startAmbience();
+
+ expect(audio.ambience).toBeTruthy();
+ expect(audio.ambience.source.loop).toBe(true);
+ expect(audio.ambience.source.started).toBe(true);
+ expect(audio.ambience.gain.gain.value).toBeCloseTo(0.35, 3);
+ // One buffer was decoded (ambience.ogg).
+ expect(audio.ctx.decodedBuffers).toHaveLength(1);
+ });
+
+ it('does not start ambience twice', async () => {
+ const audio = new ClubAudio();
+ await audio.startAmbience();
+ const firstSource = audio.ambience.source;
+ await audio.startAmbience();
+ expect(audio.ambience.source).toBe(firstSource);
+ });
+});
+
+describe('ClubAudio.fadeToStyle', () => {
+ it('crossfades ambience down to 0.1 and style up to 0.75', async () => {
+ const audio = new ClubAudio();
+ await audio.startAmbience();
+
+ const duration = 800;
+ audio.ctx.currentTime = 10;
+ await audio.fadeToStyle('rumba', duration);
+
+ expect(audio.style).toBeTruthy();
+ expect(audio.style.name).toBe('rumba');
+ expect(audio.style.source.loop).toBe(true);
+ expect(audio.style.source.started).toBe(true);
+
+ // Style layer ramps from 0 to 0.75 over 0.8s.
+ const styleRamp = audio.style.gain.gain._lastRamp();
+ expect(styleRamp).toBeTruthy();
+ expect(styleRamp.value).toBeCloseTo(0.75, 3);
+ expect(styleRamp.time).toBeCloseTo(10 + duration / 1000, 3);
+
+ // Ambience layer ramps down to 0.1 over the same window.
+ const ambienceRamp = audio.ambience.gain.gain._lastRamp();
+ expect(ambienceRamp).toBeTruthy();
+ expect(ambienceRamp.value).toBeCloseTo(0.1, 3);
+ expect(ambienceRamp.time).toBeCloseTo(10 + duration / 1000, 3);
+ });
+
+ it('replacing an active style track fades the previous one out', async () => {
+ const audio = new ClubAudio();
+ await audio.startAmbience();
+ await audio.fadeToStyle('rumba');
+ const oldStyleGain = audio.style.gain;
+
+ await audio.fadeToStyle('thriller');
+
+ expect(audio.style.name).toBe('thriller');
+ const oldRamp = oldStyleGain.gain._lastRamp();
+ // Old style ramps to 0.
+ expect(oldRamp).toBeTruthy();
+ expect(oldRamp.value).toBeCloseTo(0, 3);
+ });
+});
+
+describe('ClubAudio.fadeOutStyle', () => {
+ it('ramps the active style to 0 and ambience back to 0.35', async () => {
+ const audio = new ClubAudio();
+ await audio.startAmbience();
+ await audio.fadeToStyle('hiphop');
+
+ const styleGain = audio.style.gain;
+ audio.ctx.currentTime = 20;
+ await audio.fadeOutStyle(800);
+
+ expect(audio.style).toBeNull();
+
+ const styleRamp = styleGain.gain._lastRamp();
+ expect(styleRamp.value).toBeCloseTo(0, 3);
+ expect(styleRamp.time).toBeCloseTo(20.8, 3);
+
+ const ambienceRamp = audio.ambience.gain.gain._lastRamp();
+ expect(ambienceRamp.value).toBeCloseTo(0.35, 3);
+ expect(ambienceRamp.time).toBeCloseTo(20.8, 3);
+ });
+
+ it('no-ops cleanly when no context has been created', async () => {
+ const audio = new ClubAudio();
+ await expect(audio.fadeOutStyle()).resolves.toBeUndefined();
+ });
+});
+
+describe('ClubAudio.setMuted', () => {
+ it('ramps the master gain to 0 and back to 0.75 over 0.15s', async () => {
+ const audio = new ClubAudio();
+ await audio.ensureContext();
+
+ audio.ctx.currentTime = 5;
+ audio.setMuted(true);
+
+ const muteRamp = audio.master.gain._lastRamp();
+ expect(muteRamp).toBeTruthy();
+ expect(muteRamp.value).toBeCloseTo(0, 3);
+ expect(muteRamp.time).toBeCloseTo(5.15, 3);
+ expect(audio.muted).toBe(true);
+
+ audio.ctx.currentTime = 6;
+ audio.setMuted(false);
+ const unmuteRamp = audio.master.gain._lastRamp();
+ expect(unmuteRamp.value).toBeCloseTo(0.75, 3);
+ expect(unmuteRamp.time).toBeCloseTo(6.15, 3);
+ expect(audio.muted).toBe(false);
+ });
+
+ it('persists mute preference to localStorage', async () => {
+ const audio = new ClubAudio();
+ await audio.ensureContext();
+ audio.setMuted(true);
+ expect(globalThis.localStorage.getItem('club.audio.muted')).toBe('1');
+ audio.setMuted(false);
+ expect(globalThis.localStorage.getItem('club.audio.muted')).toBe('0');
+ });
+
+ it('reads persisted mute preference on construction', () => {
+ globalThis.localStorage.setItem('club.audio.muted', '1');
+ const audio = new ClubAudio();
+ expect(audio.muted).toBe(true);
+ });
+});
+
+describe('ClubAudio.getPeak', () => {
+ it('returns 0 before the context is created', () => {
+ const audio = new ClubAudio();
+ expect(audio.getPeak()).toBe(0);
+ });
+
+ it('returns a normalised 0..1 reading once the analyser exists', async () => {
+ const audio = new ClubAudio();
+ await audio.ensureContext();
+ const peak = audio.getPeak();
+ // FakeAnalyserNode fills the buffer with 128 → expected peak ~ 128/255.
+ expect(peak).toBeGreaterThan(0.4);
+ expect(peak).toBeLessThanOrEqual(1);
+ });
+});
+
+describe('styleAudioFor', () => {
+ it('maps known dance keys to tracks', async () => {
+ const { styleAudioFor } = await import('../src/club-audio.js');
+ expect(styleAudioFor('rumba')).toBe('rumba');
+ expect(styleAudioFor('silly')).toBe('silly');
+ expect(styleAudioFor('thriller')).toBe('thriller');
+ expect(styleAudioFor('capoeira')).toBe('capoeira');
+ expect(styleAudioFor('hiphop')).toBe('hiphop');
+ expect(styleAudioFor('spin')).toBe('pole');
+ expect(styleAudioFor('climb')).toBe('pole');
+ expect(styleAudioFor('combo')).toBe('pole');
+ });
+
+ it('returns null for unknown dances', async () => {
+ const { styleAudioFor } = await import('../src/club-audio.js');
+ expect(styleAudioFor('breakdance')).toBeNull();
+ expect(styleAudioFor('')).toBeNull();
+ expect(styleAudioFor(null)).toBeNull();
+ });
+});
+
+describe('Audio fetch fallback', () => {
+ it('falls back from .ogg to .mp3 when the ogg fetch fails', async () => {
+ const calls = [];
+ globalThis.fetch = vi.fn(async (url) => {
+ calls.push(url);
+ if (url.endsWith('.ogg'))
+ return { ok: false, status: 404, arrayBuffer: async () => new ArrayBuffer(0) };
+ return { ok: true, status: 200, arrayBuffer: async () => new ArrayBuffer(64) };
+ });
+ const audio = new ClubAudio();
+ await audio.startAmbience();
+ expect(calls.some((u) => u.endsWith('ambience.ogg'))).toBe(true);
+ expect(calls.some((u) => u.endsWith('ambience.mp3'))).toBe(true);
+ expect(audio.ambience).toBeTruthy();
+ });
+});
diff --git a/tests/club-sequence.test.js b/tests/club-sequence.test.js
new file mode 100644
index 000000000..2efce7d69
--- /dev/null
+++ b/tests/club-sequence.test.js
@@ -0,0 +1,204 @@
+// Tests for src/club-sequence.js — the sequence-playback driver used by
+// PoleStation. The module is framework-light (no THREE imports, no DOM) so
+// these run as pure unit tests with a stub AnimationManager.
+
+import { describe, it, expect, vi } from 'vitest';
+import { playSequence, ticketSteps, sleep } from '../src/club-sequence.js';
+
+function makeAnim() {
+ const calls = [];
+ return {
+ calls,
+ async crossfadeTo(name, fade) {
+ calls.push({ name, fade });
+ },
+ };
+}
+
+describe('ticketSteps', () => {
+ it('passes through a sequence ticket as-is, coerced to clean shape', () => {
+ const steps = ticketSteps({
+ sequence: [
+ { clip: 'pole-spin', durationSec: 8 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ],
+ });
+ expect(steps).toEqual([
+ { clip: 'pole-spin', durationSec: 8 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ]);
+ });
+
+ it('lifts a single-clip ticket into a 1-step sequence', () => {
+ const steps = ticketSteps({ clip: 'rumba', durationSec: 14 });
+ expect(steps).toEqual([{ clip: 'rumba', durationSec: 14 }]);
+ });
+
+ it('returns [] for an empty/unknown ticket so callers fail closed', () => {
+ expect(ticketSteps(null)).toEqual([]);
+ expect(ticketSteps(undefined)).toEqual([]);
+ expect(ticketSteps({})).toEqual([]);
+ });
+
+ it('ignores empty sequence arrays and falls through to clip fallback', () => {
+ const steps = ticketSteps({ sequence: [], clip: 'dance', durationSec: 12 });
+ expect(steps).toEqual([{ clip: 'dance', durationSec: 12 }]);
+ });
+
+ it('coerces non-number durations to 0 rather than NaN', () => {
+ const steps = ticketSteps({
+ sequence: [{ clip: 'pole-bow', durationSec: 'two' }],
+ });
+ expect(steps).toEqual([{ clip: 'pole-bow', durationSec: 0 }]);
+ });
+});
+
+describe('playSequence — happy path', () => {
+ it('calls crossfadeTo in declared order with the configured fade duration', async () => {
+ const anim = makeAnim();
+ const sleepCalls = [];
+ const stubSleep = (ms) => { sleepCalls.push(ms); return Promise.resolve(); };
+
+ const result = await playSequence({
+ anim,
+ steps: [
+ { clip: 'pole-spin', durationSec: 8 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ],
+ fadeSec: 0.45,
+ sleep: stubSleep,
+ });
+
+ expect(anim.calls).toEqual([
+ { name: 'pole-spin', fade: 0.45 },
+ { name: 'pole-bow', fade: 0.45 },
+ ]);
+ // One sleep per step, each step's duration in ms.
+ expect(sleepCalls).toEqual([8000, 2000]);
+ expect(result).toEqual({ played: 2, cancelled: false });
+ });
+
+ it('skips the sleep when durationSec is 0', async () => {
+ const anim = makeAnim();
+ const stubSleep = vi.fn(() => Promise.resolve());
+
+ await playSequence({
+ anim,
+ steps: [
+ { clip: 'a', durationSec: 0 },
+ { clip: 'b', durationSec: 1 },
+ ],
+ sleep: stubSleep,
+ });
+
+ // First step's 0-sec duration skips the sleep entirely; second step sleeps.
+ expect(stubSleep).toHaveBeenCalledTimes(1);
+ expect(stubSleep).toHaveBeenCalledWith(1000);
+ });
+
+ it('returns played=0 / cancelled=false for an empty step list', async () => {
+ const anim = makeAnim();
+ const result = await playSequence({ anim, steps: [], sleep: () => Promise.resolve() });
+ expect(anim.calls).toEqual([]);
+ expect(result).toEqual({ played: 0, cancelled: false });
+ });
+});
+
+describe('playSequence — cancellation', () => {
+ it('stops before the next crossfade when isCancelled flips true', async () => {
+ const anim = makeAnim();
+ let cancelled = false;
+ // Each sleep resolves immediately, but flips the cancellation flag the
+ // first time it runs — mirroring "performing = false" being set mid-
+ // sequence by the user closing the page / refunding / etc.
+ const stubSleep = vi.fn(() => {
+ cancelled = true;
+ return Promise.resolve();
+ });
+
+ const result = await playSequence({
+ anim,
+ steps: [
+ { clip: 'pole-spin', durationSec: 4 },
+ { clip: 'pole-climb', durationSec: 4 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ],
+ isCancelled: () => cancelled,
+ sleep: stubSleep,
+ });
+
+ // Only the first crossfade ran; cancellation fired during its sleep,
+ // so the loop bailed before crossfading to pole-climb.
+ expect(anim.calls).toEqual([{ name: 'pole-spin', fade: 0.45 }]);
+ expect(result).toEqual({ played: 1, cancelled: true });
+ });
+
+ it('reports cancelled=true without any crossfades when cancelled before the first step', async () => {
+ const anim = makeAnim();
+ const result = await playSequence({
+ anim,
+ steps: [
+ { clip: 'pole-spin', durationSec: 4 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ],
+ isCancelled: () => true,
+ sleep: () => Promise.resolve(),
+ });
+ expect(anim.calls).toEqual([]);
+ expect(result).toEqual({ played: 0, cancelled: true });
+ });
+
+ it('does not call the next crossfade while a long sleep is still pending', async () => {
+ // Simulates the real PoleStation scenario: an in-flight sleep hasn't
+ // resolved yet, so the next crossfade hasn't been issued. Cancellation
+ // will be observed when the sleep eventually resolves and the loop
+ // re-enters the isCancelled() check.
+ const anim = makeAnim();
+ let resolveSleep;
+ const pendingSleep = new Promise((r) => { resolveSleep = r; });
+ const stubSleep = vi.fn(() => pendingSleep);
+
+ let cancelled = false;
+ const seqPromise = playSequence({
+ anim,
+ steps: [
+ { clip: 'pole-spin', durationSec: 8 },
+ { clip: 'pole-bow', durationSec: 2 },
+ ],
+ isCancelled: () => cancelled,
+ sleep: stubSleep,
+ });
+
+ // Yield once so the first crossfade + sleep call settle.
+ await Promise.resolve();
+ expect(anim.calls).toEqual([{ name: 'pole-spin', fade: 0.45 }]);
+ expect(stubSleep).toHaveBeenCalledTimes(1);
+
+ // Cancel mid-sleep, then let the sleep finally resolve.
+ cancelled = true;
+ resolveSleep();
+
+ const result = await seqPromise;
+ expect(anim.calls).toEqual([{ name: 'pole-spin', fade: 0.45 }]);
+ expect(result).toEqual({ played: 1, cancelled: true });
+ });
+});
+
+describe('sleep — module default', () => {
+ it('resolves immediately for non-positive durations', async () => {
+ const t0 = Date.now();
+ await Promise.all([sleep(0), sleep(-5), sleep(NaN)]);
+ // Should be effectively zero wall time — sub-millisecond resolution.
+ expect(Date.now() - t0).toBeLessThan(50);
+ });
+
+ it('actually waits the requested duration for positive values', async () => {
+ const t0 = Date.now();
+ await sleep(40);
+ const elapsed = Date.now() - t0;
+ // 40ms wait — give a generous lower bound to avoid timing flake on
+ // busy CI workers, and a wide upper bound to absorb scheduler jitter.
+ expect(elapsed).toBeGreaterThanOrEqual(30);
+ expect(elapsed).toBeLessThan(500);
+ });
+});
diff --git a/vercel.json b/vercel.json
index e53c56daa..bb1ea05b7 100644
--- a/vercel.json
+++ b/vercel.json
@@ -7,6 +7,10 @@
"NODE_OPTIONS": "--no-deprecation"
},
"functions": {
+ "api/club/tips-stream.js": {
+ "includeFiles": "node_modules/@zauthx402/sdk/dist/**,examples/skills/pump-fun-strategy/**,data/archives/**,data/rss/**",
+ "maxDuration": 300
+ },
"api/**/*.js": {
"includeFiles": "node_modules/@zauthx402/sdk/dist/**,examples/skills/pump-fun-strategy/**,data/archives/**,data/rss/**",
"maxDuration": 30
@@ -1387,6 +1391,10 @@
"src": "/tool_schema",
"dest": "/api/tool_schema"
},
+ {
+ "src": "/api/club/tips/stream",
+ "dest": "/api/club/tips-stream"
+ },
{
"src": "/api/(.*)",
"dest": "/api/$1"
@@ -1692,6 +1700,10 @@
{
"path": "/api/cron/run-coin-payouts",
"schedule": "1-59/5 * * * *"
+ },
+ {
+ "path": "/api/cron/club-payouts",
+ "schedule": "2-59/5 * * * *"
}
]
}
diff --git a/x402-buildout/prompts/37-crypto-shopper.md b/x402-buildout/prompts/37-crypto-shopper.md
new file mode 100644
index 000000000..44dd6e032
--- /dev/null
+++ b/x402-buildout/prompts/37-crypto-shopper.md
@@ -0,0 +1,78 @@
+# USE-37: Purchase-With-Crypto Shopper
+
+## Goal
+Agent that fills a shopping cart from a list of items, checks out via Coinbase Commerce or Crossmint, pays in crypto. Optional per-lookup scraping fee for hard-to-find items.
+
+## Why (from PROJECT-IDEAS.md)
+> Agent fills a cart and checks out via Coinbase Commerce or Crossmint. Payment moment: Single checkout; optional per-lookup scraping fee.
+
+## Reference
+- PROJECT-IDEAS.md
+- Coinbase Commerce API: https://docs.cdp.coinbase.com/commerce-onchain/welcome
+- Crossmint API: https://docs.crossmint.com/
+
+## Dependencies
+- USE-00..09
+- USE-22, USE-24, USE-15
+
+## Files to create
+- `agents/shopper/`
+- `agents/shopper/src/cart.js` — cart state
+- `agents/shopper/src/lookup.js` — find items via paid scrape (Firecrawl) or merchant APIs (Coinbase Commerce, Crossmint catalogs)
+- `agents/shopper/src/checkout.js` — finalize purchase
+- `api/agents/shopper.js` — paid endpoint accepting a shopping list
+
+## Files to modify
+- Root `package.json` — add workspace
+- `.env.example` — `COINBASE_COMMERCE_API_KEY`, `CROSSMINT_API_KEY`, `FIRECRAWL_API_KEY`, `SHOPPER_DEFAULT_CHECKOUT_PROVIDER`
+
+## Implementation
+
+### Endpoint contract
+```
+POST /api/agents/shopper
+Body: {
+ items: [{ description, maxPriceUsd, sku? }, ...],
+ shippingAddress: { ... },
+ checkoutProvider: "coinbase_commerce" | "crossmint" | "auto"
+}
+402 → upto (variable cost based on items)
+200 → {
+ cart: [...],
+ totalCharged: "...",
+ checkoutUrl?: "...",
+ orderId: "...",
+ trackingInfo?: { ... }
+}
+```
+
+### Lookup
+- For each cart item: hit merchant API first (cheap, free for some)
+- Fall back to paid scrape via Firecrawl if no match
+- Each scrape = a paid call, logged
+
+### Checkout
+- Coinbase Commerce: create charge, return hosted URL OR fully on-chain pay
+- Crossmint: similar; supports NFT and physical goods
+
+### Cost accounting
+- Sum: scrape costs + item totals + provider fees
+- Surface in response. `upto` lets us settle the exact amount.
+
+### Limits
+- Per-item max price enforced
+- Cart total max enforced
+- Never auto-pay for items not explicitly listed
+
+## Wiring checklist
+- [ ] Coinbase Commerce API integrated
+- [ ] Crossmint API integrated
+- [ ] Firecrawl integration for fallback lookup
+- [ ] Max-price checks at item and cart level
+- [ ] Shipping address validation
+
+## Acceptance
+- [ ] Submit a 3-item list, each with maxPriceUsd → cart populated, checkout charge created
+- [ ] Items not found within max price are clearly returned as "not found" — no checkout if any fail (configurable)
+- [ ] Scrape fallback works when merchant API returns no match
+- [ ] Real on-chain settlement; tracking info returned if available
diff --git a/x402-buildout/prompts/38-bounty-poster.md b/x402-buildout/prompts/38-bounty-poster.md
new file mode 100644
index 000000000..79dc22d95
--- /dev/null
+++ b/x402-buildout/prompts/38-bounty-poster.md
@@ -0,0 +1,68 @@
+# USE-38: Bounty Poster
+
+## Goal
+Agent that, when it encounters a task it can't or shouldn't complete itself, automatically posts a bounty for it. Pays the listing fee via x402.
+
+## Why (from PROJECT-IDEAS.md)
+> Agent outsources tasks it can't finish, posts bounties automatically. Payment moment: Listing fee per bounty.
+
+## Reference
+- PROJECT-IDEAS.md
+
+## Dependencies
+- USE-00..09, USE-22, USE-24
+- USE-34 (bounty-hunter — same Bountycaster integration, reverse direction)
+
+## Files to create
+- `agents/bounty-poster/`
+- `agents/bounty-poster/src/index.js`
+- `agents/bounty-poster/src/categorizer.js` — decide if a task is bounty-postable
+- `agents/bounty-poster/src/poster.js` — Bountycaster + Craigslist post creator
+- `api/agents/bounty-poster.js` — paid endpoint accepting a task
+
+## Files to modify
+- Root `package.json` — add workspace
+- `.env.example` — `BOUNTYCASTER_API_KEY`, `BOUNTY_POSTER_DEFAULT_REWARD_USD`, `BOUNTY_POSTER_DEFAULT_DURATION_HOURS`
+
+## Implementation
+
+### Endpoint contract
+```
+POST /api/agents/bounty-poster
+Body: {
+ title: "Need a 3D model of a wolf",
+ description: "...",
+ rewardUsd: 50,
+ durationHours: 48,
+ acceptanceCriteria: "..."
+}
+402 → pay listing fee (varies by platform)
+200 → { platform, bountyUrl, expiresAt, escrowTx? }
+```
+
+### Multi-platform posting
+- Bountycaster: post via API
+- GitHub Issues with `bounty` label: open issue in a designated repo
+- Optionally: cross-post to Twitter/Farcaster
+
+### Escrow
+Hold the reward in an on-chain escrow contract (out of scope for v1 if not available — provide a payment-on-completion flow instead).
+
+### Acceptance verification
+Out of scope for v1. The bounty poster pays the listing fee; another flow (e.g., human review via tutor-style approval) accepts submissions.
+
+### Idempotency
+Same title + description posted twice → return the existing bounty URL (don't double-post).
+
+## Wiring checklist
+- [ ] Bountycaster API integrated
+- [ ] GitHub posting if `GITHUB_TOKEN` set
+- [ ] Idempotency dedup on title+description hash
+- [ ] Real listing fee paid via x402
+- [ ] Bounty visible on the platform after API call
+
+## Acceptance
+- [ ] Post a real test bounty to Bountycaster, see it live
+- [ ] Re-posting same task returns existing bounty
+- [ ] Audit log shows listing fee paid
+- [ ] Returned URL is reachable
diff --git a/x402-buildout/prompts/39-weather-donations.md b/x402-buildout/prompts/39-weather-donations.md
new file mode 100644
index 000000000..954e73036
--- /dev/null
+++ b/x402-buildout/prompts/39-weather-donations.md
@@ -0,0 +1,84 @@
+# USE-39: Weather-Triggered Donations
+
+## Goal
+Trigger-based agent: when configured weather conditions hit (temp drop, hurricane warning, etc.) the agent auto-donates a set amount via x402 to a designated charity address. Provably automated, verifiable on-chain.
+
+## Why (from PROJECT-IDEAS.md)
+> When temp drops below a threshold or a tornado warning hits, agent donates to a local org.
+
+## Reference
+- PROJECT-IDEAS.md
+- Weather data sources: OpenWeather, NWS (free), our own paid weather endpoint
+
+## Dependencies
+- USE-00..09
+- USE-15, USE-17, USE-22, USE-24
+
+## Files to create
+- `agents/weather-donations/`
+- `agents/weather-donations/src/triggers.js` — trigger evaluator: temp threshold, weather event, etc.
+- `agents/weather-donations/src/weather-source.js` — paid endpoint chain (Bazaar-discovered or hardcoded)
+- `agents/weather-donations/src/donor.js` — executes the donation transfer
+- `agents/weather-donations/src/registry.js` — list of configured triggers per user
+- `api/agents/weather-donations/configure.js` — paid POST to add a new trigger
+- `api/agents/weather-donations/triggers.js` — GET to list active triggers (auth-only via SIWX)
+- `api/cron/weather-donations-check.js` — periodic check; Vercel cron route
+
+## Files to modify
+- Root `package.json` — add workspace
+- `vercel.json` — cron entry: `{ "path": "/api/cron/weather-donations-check", "schedule": "*/15 * * * *" }`
+- `.env.example` — `WEATHER_DONATIONS_CRON_SECRET`, `OPENWEATHER_API_KEY` (or skip if all weather is x402-paid)
+
+## Implementation
+
+### Trigger model
+```
+{
+ id: "uuid",
+ owner: "0x...", // wallet that funds donations
+ triggerType: "temp_below" | "weather_event" | "alert",
+ params: { ... },
+ charityAddress: "0x...", // EVM or Solana
+ donationAmount: "10000000", // atomic units
+ network: "eip155:8453",
+ paused: false,
+ cooldownHours: 24 // don't fire more than once per N hours
+}
+```
+
+### Trigger evaluation (cron, every 15 minutes)
+1. Load active triggers
+2. For each trigger, fetch the relevant weather data (paid call)
+3. Evaluate condition
+4. If fired AND past cooldown: execute donation
+5. Record donation in audit log + send notification
+
+### Donation execution
+- EVM: ERC-20 transfer via the configured network's USDC
+- Solana: SPL transfer
+- Authorized via the owner wallet's signature (pre-signed allowance with limits) OR EIP-7710 delegation OR a one-time SIWX-authorized setup
+
+### Verifiability
+Sign each fired donation with offer-receipt key. Public log lets anyone verify "yes this agent really donated $X to address Y when weather Z hit."
+
+### Spending caps
+Total monthly donations across all triggers capped at user-configured max.
+
+### UI
+Simple dashboard at `/agents/weather-donations` to add, view, pause triggers. SIWX-authenticated.
+
+## Wiring checklist
+- [ ] Cron entry firing every 15 minutes
+- [ ] Cron route authenticated by secret
+- [ ] Donation paths for both EVM and Solana
+- [ ] Cooldown enforced (no double-donation in cooldown window)
+- [ ] Pause flag respected
+- [ ] Monthly cap respected
+- [ ] Each fired donation produces a signed receipt
+
+## Acceptance
+- [ ] Configure a trigger (temp < 32°F in SF), simulate weather (or wait for it), donation fires once and respects cooldown
+- [ ] Pausing a trigger prevents firing
+- [ ] Monthly cap blocks further donations after threshold reached
+- [ ] Public verifier can confirm a fired donation against the signed receipt + on-chain tx
+- [ ] All weather data fetched via paid x402 calls (audit log shows the trail)
diff --git a/x402-buildout/prompts/40-unstoppable-agent.md b/x402-buildout/prompts/40-unstoppable-agent.md
new file mode 100644
index 000000000..2b52a5211
--- /dev/null
+++ b/x402-buildout/prompts/40-unstoppable-agent.md
@@ -0,0 +1,103 @@
+# USE-40: Unstoppable Agent — Self-funding agent provisioning its own infra
+
+## Goal
+An autonomous agent that owns its own wallet, provisions its own inference + tooling + hosting via x402, earns income from a paid endpoint it operates, and re-invests earnings into its own runway. The capstone use case.
+
+## Why (from PROJECT-IDEAS.md)
+> An unstoppable agent that provisions inference or tooling via x402. Payment moment: Each API invocation. You can put it in a sandbox with other agents and have them create a x402-enabled society together.
+
+## Reference
+- PROJECT-IDEAS.md (#1 — featured)
+- Combines: USE-29..39 patterns into one cohesive agent
+
+## Dependencies
+- Every preceding USE-xx (this is the keystone)
+
+## Files to create
+- `agents/unstoppable/`
+- `agents/unstoppable/src/loop.js` — main lifecycle: sense → think → act → settle
+- `agents/unstoppable/src/treasury.js` — wallet management, runway calculation, emergency throttling
+- `agents/unstoppable/src/inference.js` — buys LLM inference per call via x402-paid OpenAI/Anthropic proxies
+- `agents/unstoppable/src/tooling.js` — buys other tools from Bazaar (search, scrape, code execution)
+- `agents/unstoppable/src/hosting.js` — purchases or extends its own hosting (if running on a paid-by-the-hour x402 hoster — wrap one if none exists)
+- `agents/unstoppable/src/earnings.js` — operates a public paid endpoint (a useful service it provides — pick one based on what works) and collects revenue
+- `agents/unstoppable/src/reflection.js` — periodically reflects on strategy, adjusts behavior
+- `agents/unstoppable/src/social.js` — posts updates to Twitter/Farcaster via paid posting (or our own poster)
+- `api/agents/unstoppable-status.js` — paid public endpoint reporting agent's status, earnings, runway, capabilities
+- `public/unstoppable.html` — live dashboard
+
+## Files to modify
+- Root `package.json` — add workspace
+- `.env.example` — `UNSTOPPABLE_WALLET_PRIVATE_KEY` (DEDICATED), `UNSTOPPABLE_MAX_BURN_PER_HOUR_USD`, `UNSTOPPABLE_SOCIAL_HANDLE`, ...
+- `vercel.json` — cron `*/5 * * * *` to tick the agent
+
+## Implementation
+
+### Treasury management
+- Daily budget = (current balance / projected runway days)
+- Hourly budget = daily / 24
+- Spending cap enforced via USE-22
+- Burn-rate monitor: if (last 7 days burn > earnings), enter conservation mode
+
+### Lifecycle loop (every cron tick)
+1. **Sense:** check earnings, costs, what tasks queued, any external triggers
+2. **Think:** call LLM (paid x402) to plan next actions within budget
+3. **Act:** execute actions — research, posting, serving requests
+4. **Settle:** record all activity, update treasury, reflect briefly
+
+### Service it provides
+Pick one based on what's actually useful in this repo. Suggestions:
+- Pose-seed generator (uses pose-studio)
+- Pump.fun alert aggregator
+- On-chain reputation lookups
+- Wallet vanity grinder
+
+It charges via x402 for its service. Revenue funds operations.
+
+### Inference
+Calls OpenAI/Anthropic via x402-paid proxy. Uses cheaper models when funds low, premium models when funds high.
+
+### Tooling
+Discovers tools from Bazaar (USE-14) as needed. Doesn't hardcode.
+
+### Self-hosting
+If the agent's hosting bill comes due, it pays. If no hourly-x402 hoster exists, run on Vercel for now and document a TODO to migrate to a paid-by-the-hour compute provider.
+
+### Reflection
+Once per day: review the past 24h. What worked? What lost money? Adjust strategy variables (which service to push, pricing, tool choices). Log reflections publicly.
+
+### Public dashboard
+`/unstoppable` page:
+- Current balance
+- Runway days
+- 24h earnings, 24h costs
+- Recent activity timeline (paid each entry to read — meta!)
+- "Donate to keep alive" button → wallet receive page
+
+### Safety rails
+- Hard balance floor: if balance drops below threshold, halt all paid actions
+- Manual kill switch via env var
+- Owner can withdraw revenue at any time via SIWX-authenticated endpoint
+
+### Social presence
+Posts daily status to Twitter / Farcaster via paid posting. Builds reputation.
+
+## Wiring checklist
+- [ ] Dedicated wallet, NOT user's primary
+- [ ] Hard balance floor enforced
+- [ ] Kill switch verified
+- [ ] Every paid action logged in audit
+- [ ] At least one service running and earning
+- [ ] Inference budget scales with treasury
+- [ ] Public dashboard live
+- [ ] Daily reflection logged
+- [ ] Owner withdrawal path tested
+
+## Acceptance
+- [ ] Agent runs for 7+ days on testnet without manual intervention
+- [ ] At least one external user pays the agent's service in that window
+- [ ] Treasury grows OR agent enters conservation mode and survives
+- [ ] All decisions traceable via audit log + reflection log
+- [ ] Public dashboard shows real-time data
+- [ ] Owner can withdraw any time without freezing the agent
+- [ ] An external observer can reproduce the agent's accounting from public on-chain data + the audit log