Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(x402): pole-club paid endpoint + Permit2 gasless sibling accepts
nirholasae4eb9dbda02
diff --git a/api/_lib/x402-permit2.js b/api/_lib/x402-permit2.jsnew file mode 100644index 000000000..bcbb9c818--- /dev/null+++ b/api/_lib/x402-permit2.js@@ -0,0 +1,102 @@+// x402 EVM Permit2 helpers — adds a Permit2-flavored acceptance entry and+// advertises the gas-sponsoring extensions that let buyers pay USDC (or any+// ERC-20 we choose to accept) without holding native gas.+//+// Why both extensions:+// • EIP-2612 gas sponsoring — preferred path for tokens that implement+// EIP-2612 (Base USDC v2 does). Client signs an off-chain permit; the+// CDP facilitator submits it on-chain via x402ExactPermit2Proxy.settleWithPermit+// in the same batch as the Permit2 transfer.+// • ERC-20 approval gas sponsoring — universal fallback for any other+// ERC-20. Client signs (but does not broadcast) a raw approve(Permit2,+// MaxUint256) tx; the facilitator broadcasts it atomically before+// calling x402ExactPermit2Proxy.settle.+//+// Both are server-side ADVERTISEMENTS only. Whether they actually fire+// depends on the facilitator we route Base traffic to. CDP supports both+// today; PayAI does not (it only settles EIP-3009). When the resource server+// uses CDP (CDP_API_KEY_ID + CDP_API_KEY_SECRET set), advertise. Otherwise+// keep the 402 body to EIP-3009 only so we don't promise capabilities the+// facilitator won't honor.+//+// We keep the existing EIP-3009 acceptance entry as the FIRST item in+// `accepts[]` so default clients (including our drop-in modal at+// public/x402.js) continue using the simpler gasless EIP-3009 flow. The+// Permit2 entry is appended as a secondary option for agentic clients using+// @x402/evm's ExactEvmScheme, which auto-routes to Permit2 when the+// `assetTransferMethod` extra is present.++import {+ declareEip2612GasSponsoringExtension,+ declareErc20ApprovalGasSponsoringExtension,+} from '@x402/extensions';++import { env } from './env.js';+import { NETWORK_BASE_MAINNET } from './x402-spec.js';++// Canonical Permit2 contract — same address on every EVM chain via CREATE2.+// See https://github.com/Uniswap/permit2 and @x402/evm constants.+export const PERMIT2_ADDRESS = '0x000000000022D473030F116dDEE9F6B43aC78BA3';++// x402ExactPermit2Proxy — vanity 0x4020…0001. Facilitator calls+// settle()/settleWithPermit() on this contract. Buyers don't interact with+// it directly; we just declare it as the Permit2 spender witness target.+export const X402_EXACT_PERMIT2_PROXY_ADDRESS = '0x402085c248EeA27D92E8b30b2C58ed07f9E20001';++// Per-network EIP-2612 domain `version` for the canonical native USDC.+// Used by clients that want to skip an on-chain DOMAIN_SEPARATOR fetch. Base+// USDC (FiatTokenV2_2) is at "2"; Arbitrum native USDC also "2".+const USDC_EIP2612_VERSION_BY_NETWORK = {+ [NETWORK_BASE_MAINNET]: '2',+};++// CDP is the only facilitator we route to that currently settles Permit2 ++// gas-sponsoring. If CDP creds are absent we must NOT advertise these+// extensions — the buyer would sign Permit2 typed-data, send it to our+// PayAI-routed Base endpoint, and the settle call would fail with a clean+// `unsupported_scheme` from PayAI.+export function facilitatorSupportsPermit2GasSponsoring() {+ return Boolean(env.CDP_API_KEY_ID && env.CDP_API_KEY_SECRET);+}++// Build a v2 PaymentRequirements accept entry that uses Permit2 instead of+// EIP-3009. Same `payTo` (the seller wallet) and same `asset` (USDC); just+// flips `extra.assetTransferMethod` so the client routes through the proxy.+//+// The `extra.spender` field is non-standard but harmless — some clients use+// it as a hint for the Permit2 PermitWitnessTransferFrom typed-data, which+// requires the spender (= x402ExactPermit2Proxy) explicitly.+export function buildBaseUsdcPermit2Accept({ priceAtomics, resourceUrl }) {+ if (!env.X402_PAY_TO_BASE) return null;+ const network = NETWORK_BASE_MAINNET;+ return {+ scheme: 'exact',+ network,+ amount: String(priceAtomics),+ maxTimeoutSeconds: 60,+ resource: resourceUrl,+ payTo: env.X402_PAY_TO_BASE,+ asset: env.X402_ASSET_ADDRESS_BASE,+ extra: {+ name: 'USD Coin',+ version: USDC_EIP2612_VERSION_BY_NETWORK[network] || '2',+ decimals: 6,+ assetTransferMethod: 'permit2',+ spender: X402_EXACT_PERMIT2_PROXY_ADDRESS,+ permit2Address: PERMIT2_ADDRESS,+ },+ };+}++// Merged extension declarations advertising both gas-sponsoring extensions.+// Returns the object shape expected at `PaymentRequired.extensions` — keyed+// by extension identifier (`eip2612GasSponsoring`, `erc20ApprovalGasSponsoring`).+// Returns null when the facilitator can't honor them, so callers can spread+// `...(permit2GasSponsoringExtensions() || {})` without conditionals.+export function permit2GasSponsoringExtensions() {+ if (!facilitatorSupportsPermit2GasSponsoring()) return null;+ return {+ ...declareEip2612GasSponsoringExtension(),+ ...declareErc20ApprovalGasSponsoringExtension(),+ };+}diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.jsindex a9562a7c0..1597fff08 100644--- a/api/_lib/x402-spec.js+++ b/api/_lib/x402-spec.js@@ -32,6 +32,10 @@// Server attaches a base64 settlement object as `X-PAYMENT-RESPONSE` on the success reply.import { createCdpAuthHeaders } from '@coinbase/x402';+import {+ EIP2612_GAS_SPONSORING,+ declareEip2612GasSponsoringExtension,+} from '@x402/extensions';import { env } from './env.js';import { X402Error } from './x402-errors.js';@@ -45,6 +49,14 @@ export { X402Error };export const X402_VERSION = 2;+// Extension keys we advertise alongside the bazaar discovery entry. The+// eip2612 gas-sponsoring extension is a non-binding hint to clients: when a+// requirement opts into the Permit2 asset-transfer method, the facilitator+// (CDP's x402ExactPermit2Proxy) accepts an off-chain EIP-2612 permit so the+// payer never broadcasts the Permit2-approval tx themselves. Legacy clients+// stay on the EIP-3009 accept entry (offered first below) and ignore this.+export const EIP2612_EXTENSION_KEY = EIP2612_GAS_SPONSORING.key;+// CAIP-2 network IDs as advertised by Coinbase x402 facilitators (PayAI, CDP).// Solana mainnet's CAIP-2 namespace uses the truncated genesis-block hash.export const NETWORK_BASE_MAINNET = 'eip155:8453';@@ -68,6 +80,36 @@ const CDP_EVM_NETWORKS = new Set([// and the client is responsible for broadcasting the tx + paying gas.const DIRECT_NETWORKS = new Set([NETWORK_BSC_MAINNET]);+// Take a Base/Arbitrum/etc. EIP-3009 accept entry and return a sibling that+// asks the client to use the Permit2 asset-transfer method instead. The+// `assetTransferMethod` field is what @x402/evm's ExactEvmScheme keys on; with+// `supportsEip2612: true` set, the scheme will sign an EIP-2612 permit when+// its Permit2 allowance is insufficient and stuff it into the payment payload+// extensions for the facilitator to submit. Returns null when the source+// accept is not an EVM `exact` entry (BSC direct + Solana fall through to null).+export function permit2VariantOf(accept) {+ if (!accept || accept.scheme !== 'exact') return null;+ if (typeof accept.network !== 'string' || !accept.network.startsWith('eip155:')) return null;+ return {+ ...accept,+ extra: {+ ...(accept.extra || {}),+ assetTransferMethod: 'permit2',+ supportsEip2612: true,+ },+ };+}++// Emit an EIP-3009 accept followed by its Permit2 sibling. EIP-3009 stays+// first so the browser modal in public/x402.js (which only implements+// transferWithAuthorization) keeps selecting it; @x402/* SDK clients can pick+// the Permit2 entry to get gasless Permit2 onboarding via EIP-2612 sponsorship.+function pushEvmAccepts(out, accept) {+ out.push(accept);+ const sibling = permit2VariantOf(accept);+ if (sibling) out.push(sibling);+}+// One v2 PaymentRequirements entry per supported network. Base mainnet first// — agentic.market's validator inspects the first entry for its supported-network// check, and Base is the most broadly recognized option in the Bazaar.@@ -83,7 +125,7 @@ export function paymentRequirements(resourceUrl) {};const out = [];if (env.X402_PAY_TO_BASE) {- out.push({+ pushEvmAccepts(out, {...common,network: NETWORK_BASE_MAINNET,payTo: env.X402_PAY_TO_BASE,@@ -352,20 +394,49 @@ export async function probeFacilitators() {return results;}-// Match the decoded payload to one of the offered requirements (by network).-// Falls back to the first requirement when the payload omits an explicit network field.+// Inspect the payload to determine which asset-transfer method the client+// signed with. EIP-3009 transferWithAuthorization payloads carry+// `payload.authorization`; Permit2 PermitWitnessTransferFrom payloads carry+// `payload.permit2Authorization`. Returns null if the structure is unknown+// (e.g. Solana SPL transfer, BSC direct), in which case the caller falls back+// to the first matching network entry.+function detectAssetTransferMethod(paymentPayload) {+ const inner = paymentPayload?.payload;+ if (!inner || typeof inner !== 'object') return null;+ if (inner.permit2Authorization) return 'permit2';+ if (inner.authorization) return 'eip3009';+ return null;+}++// Match the decoded payload to one of the offered requirements. The match is+// by (network, assetTransferMethod) when we can detect the method from the+// payload shape — needed because we now publish two accept entries per EVM+// network (EIP-3009 first, Permit2 sibling second), and the facilitator's+// /verify call has to receive the same `extra` block the client signed+// against. Falls back to first-match-by-network for non-EVM payloads (Solana+// SPL, BSC direct).function selectRequirement(paymentPayload, allRequirements) {const network = paymentPayload?.network || paymentPayload?.paymentRequirements?.network;+ const method = detectAssetTransferMethod(paymentPayload);+ const matchesMethod = (r) => {+ if (!method) return true;+ const reqMethod = r.extra?.assetTransferMethod || 'eip3009';+ return reqMethod === method;+ };if (network) {- const found = allRequirements.find((r) => r.network === network);+ const found = allRequirements.find((r) => r.network === network && matchesMethod(r));if (!found)throw new X402Error('unsupported_network',- `payment network "${network}" is not offered`,+ `payment network "${network}" (assetTransferMethod="${method || 'unknown'}") is not offered`,402,);return found;}+ if (method) {+ const found = allRequirements.find(matchesMethod);+ if (found) return found;+ }return allRequirements[0];}diff --git a/api/x402/dance-tip.js b/api/x402/dance-tip.jsnew file mode 100644index 000000000..0223b1cb8--- /dev/null+++ b/api/x402/dance-tip.js@@ -0,0 +1,155 @@+// GET /api/x402/dance-tip?dancer=<id>&dance=<style>+//+// 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+// to drive scripted performances.++import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.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.';++const STYLES = Object.freeze({+ hiphop: { clip: 'dance', label: 'Hip Hop', loop: true, durationSec: 12 },+ rumba: { clip: 'rumba', label: 'Rumba', loop: true, durationSec: 14 },+ silly: { clip: 'silly', label: 'Silly', loop: true, durationSec: 10 },+ thriller: { clip: 'thriller', label: 'Thriller',loop: true, durationSec: 14 },+ capoeira: { clip: 'capoeira', label: 'Capoeira',loop: true, durationSec: 12 },+});++const VALID_DANCERS = new Set(['1', '2', '3', '4']);++const INPUT_EXAMPLE = { dancer: '1', dance: 'rumba' };++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['dancer', 'dance'],+ properties: {+ dancer: {+ type: 'string',+ enum: ['1', '2', '3', '4'],+ description: 'Stage slot 1-4 — which dancer should take the pole.',+ },+ dance: {+ type: 'string',+ enum: Object.keys(STYLES),+ description: 'Performance style. Matches a clip in /animations/manifest.json.',+ },+ },+};++const OUTPUT_EXAMPLE = {+ ok: true,+ ticketId: 'a3f3d6c2-1f1b-4f10-9b6c-1b1f5e0c9c34',+ dancer: '1',+ dance: 'rumba',+ clip: 'rumba',+ label: 'Rumba',+ loop: true,+ durationSec: 14,+ startsAt: '2026-05-21T18:42:09.000Z',+ endsAt: '2026-05-21T18:42:23.000Z',+ payer: 'wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV',+ network: 'solana',+ amountAtomics: '1000',+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['ok', 'ticketId', 'dancer', 'dance', 'clip', 'durationSec', 'startsAt', 'endsAt'],+ properties: {+ ok: { type: 'boolean', const: true },+ ticketId: { type: 'string', format: 'uuid' },+ dancer: { type: 'string', enum: ['1', '2', '3', '4'] },+ dance: { type: 'string', enum: Object.keys(STYLES) },+ clip: { type: 'string' },+ label: { type: 'string' },+ loop: { type: 'boolean' },+ durationSec: { type: 'integer', minimum: 1, maximum: 60 },+ startsAt: { type: 'string', format: 'date-time' },+ endsAt: { type: 'string', format: 'date-time' },+ payer: { type: ['string', 'null'] },+ network: { type: ['string', 'null'] },+ amountAtomics: { type: ['string', 'null'] },+ asset: { type: ['string', 'null'] },+ },+};++const BAZAAR = {+ discoverable: true,+ info: {+ input: { type: 'http', method: 'GET', queryParams: INPUT_EXAMPLE },+ output: { type: 'json', example: OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({+ method: 'GET',+ queryParamsSchema: INPUT_SCHEMA,+ outputSchema: OUTPUT_SCHEMA,+ }),+};++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;+}++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}"`);+ err.status = 400;+ err.code = 'unknown_dancer';+ throw err;+}++export default paidEndpoint({+ route: ROUTE,+ method: 'GET',+ priceAtomics: '1000',+ networks: ['base', 'solana'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ async handler({ req, requirement, payer }) {+ const dancer = pickDancer(req.query?.dancer);+ const style = pickStyle(req.query?.dance);++ const now = new Date();+ const ends = new Date(now.getTime() + style.durationSec * 1000);++ return {+ ok: true,+ ticketId: crypto.randomUUID(),+ dancer,+ dance: style.key,+ clip: style.clip,+ label: style.label,+ loop: style.loop,+ durationSec: style.durationSec,+ startsAt: now.toISOString(),+ endsAt: ends.toISOString(),+ payer: payer ?? null,+ network: requirement?.network ?? null,+ amountAtomics: requirement?.amount ?? null,+ asset: requirement?.asset ?? null,+ };+ },+});diff --git a/pages/club.html b/pages/club.htmlnew file mode 100644index 000000000..0d4ed8c9e--- /dev/null+++ b/pages/club.html@@ -0,0 +1,396 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Pole Club · three.ws</title>+ <meta+ name="viewport"+ content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"+ />+ <meta name="author" content="nirholas" />+ <meta+ name="description"+ content="A 3D pole-dancing club where dancers only come out when you send an x402 USDC micro-tip. Pay $0.001 per routine, settled on-chain on Base or Solana."+ />+ <meta name="theme-color" content="#07050b" />+ <link rel="shortcut icon" href="/favicon.ico" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Pole Club · three.ws" />+ <meta+ property="og:description"+ content="Tip a dancer in USDC via x402 — she walks out, takes the pole, performs, returns backstage."+ />+ <meta property="og:url" content="https://three.ws/club" />++ <style>+ :root {+ --bg: #07050b;+ --panel: rgba(16, 8, 22, 0.86);+ --panel-solid: #11071a;+ --border: rgba(255, 80, 200, 0.18);+ --border-strong: rgba(255, 80, 200, 0.34);+ --text: #f4eef8;+ --text-2: #c2a8d8;+ --text-3: #7c5d92;+ --accent: #ff3bd6;+ --accent-2: #4ad6ff;+ --accent-3: #ff8a3b;+ --ok: #4ade80;+ --warn: #fbbf24;+ --danger: #f87171;+ }+ * { box-sizing: border-box; }+ html, body {+ margin: 0;+ padding: 0;+ width: 100%;+ height: 100%;+ background: var(--bg);+ color: var(--text);+ font-family: 'Inter', system-ui, -apple-system, sans-serif;+ -webkit-font-smoothing: antialiased;+ overflow: hidden;+ }++ #club-app {+ position: fixed;+ inset: 0;+ display: grid;+ grid-template-columns: 1fr 320px;+ grid-template-rows: 56px 1fr;+ grid-template-areas:+ "top top"+ "stage right";+ }++ /* ── Top bar ─────────────────────────────────────────── */+ #club-top {+ grid-area: top;+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 0 18px;+ border-bottom: 1px solid var(--border);+ background:+ linear-gradient(180deg, rgba(255, 80, 200, 0.06), transparent 60%),+ rgba(7, 5, 11, 0.92);+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);+ z-index: 10;+ }+ #club-top .brand {+ display: flex;+ align-items: center;+ gap: 10px;+ font-weight: 700;+ font-size: 14.5px;+ letter-spacing: 0.01em;+ color: var(--text);+ }+ #club-top .brand a {+ color: var(--text-2);+ text-decoration: none;+ font-weight: 500;+ font-size: 13px;+ }+ #club-top .brand a:hover { color: var(--text); }+ #club-top .dot {+ width: 9px;+ height: 9px;+ border-radius: 50%;+ background: var(--accent);+ box-shadow:+ 0 0 6px var(--accent),+ 0 0 14px rgba(255, 59, 214, 0.4);+ animation: pulse 1.7s ease-in-out infinite;+ }+ @keyframes pulse {+ 0%, 100% { opacity: 1; transform: scale(1); }+ 50% { opacity: 0.55; transform: scale(0.78); }+ }+ #club-top .sep {+ width: 1px;+ height: 22px;+ background: var(--border);+ margin: 0 2px;+ }+ #club-top .tagline {+ font-size: 12.5px;+ color: var(--text-2);+ }+ #club-top .spacer { flex: 1; }+ .club-pill {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 5px 11px;+ border-radius: 999px;+ font-size: 11.5px;+ font-weight: 600;+ color: var(--text);+ background: rgba(255, 59, 214, 0.12);+ border: 1px solid rgba(255, 59, 214, 0.32);+ }+ .club-pill-blue {+ background: rgba(74, 214, 255, 0.10);+ border-color: rgba(74, 214, 255, 0.32);+ color: #cdeefe;+ }++ /* ── Stage (3D canvas) ─────────────────────────────── */+ #club-stage {+ grid-area: stage;+ position: relative;+ background: #050308;+ overflow: hidden;+ }+ #club-canvas {+ display: block;+ width: 100%;+ height: 100%;+ cursor: grab;+ touch-action: none;+ }+ #club-canvas:active { cursor: grabbing; }+ #club-status {+ position: absolute;+ left: 50%;+ bottom: 18px;+ transform: translateX(-50%);+ background: rgba(7, 5, 11, 0.86);+ border: 1px solid var(--border);+ border-radius: 999px;+ padding: 7px 16px;+ font-size: 12px;+ font-weight: 500;+ color: var(--text);+ pointer-events: none;+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ }+ #club-status[data-kind="error"] { border-color: rgba(248, 113, 113, 0.45); color: #ffd5d5; }+ #club-status[data-kind="warn"] { border-color: rgba(251, 191, 36, 0.45); color: #ffeec2; }+ #club-status[data-kind="ok"] { border-color: rgba(74, 222, 128, 0.45); color: #c7f5d6; }+ #club-status[hidden] { display: none; }++ /* ── Right panel: poles + tip feed ────────────────── */+ #club-right {+ grid-area: right;+ border-left: 1px solid var(--border);+ background: var(--panel-solid);+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ gap: 0;+ }+ .club-section {+ padding: 16px 16px 14px;+ border-bottom: 1px solid var(--border);+ }+ .club-section h2 {+ margin: 0 0 12px;+ font-size: 11px;+ font-weight: 700;+ color: var(--text-3);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ }+ .club-intro {+ font-size: 12.5px;+ line-height: 1.55;+ color: var(--text-2);+ margin: 0 0 10px;+ }+ .club-intro b { color: var(--text); }++ #club-poles {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 8px;+ }+ .club-pole-card {+ border: 1px solid var(--border);+ background: rgba(255, 59, 214, 0.04);+ border-radius: 10px;+ padding: 10px 11px;+ display: flex;+ flex-direction: column;+ gap: 8px;+ }+ .club-pole-head {+ display: flex;+ justify-content: space-between;+ align-items: center;+ font-size: 12px;+ font-weight: 600;+ }+ .club-pole-id { color: var(--accent); letter-spacing: 0.02em; }+ .club-pole-price {+ color: var(--text-3);+ font-size: 10.5px;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ }+ .club-pole-style {+ display: flex;+ flex-direction: column;+ gap: 3px;+ font-size: 10.5px;+ color: var(--text-3);+ letter-spacing: 0.06em;+ text-transform: uppercase;+ }+ .club-pole-select {+ appearance: none;+ background: rgba(0, 0, 0, 0.4);+ border: 1px solid var(--border);+ border-radius: 6px;+ padding: 5px 8px;+ color: var(--text);+ font: inherit;+ font-size: 12px;+ cursor: pointer;+ }+ .club-pole-select:focus {+ outline: none;+ border-color: var(--accent);+ }+ .club-tip-btn {+ appearance: none;+ border: none;+ border-radius: 8px;+ padding: 8px 10px;+ font: inherit;+ font-size: 12px;+ font-weight: 700;+ color: #fff;+ cursor: pointer;+ background: linear-gradient(135deg, var(--accent) 0%, #ff5fda 100%);+ box-shadow:+ 0 4px 12px rgba(255, 59, 214, 0.32),+ inset 0 1px 0 rgba(255, 255, 255, 0.2);+ transition: transform 0.08s ease, filter 0.12s ease;+ }+ .club-tip-btn:hover { filter: brightness(1.08); }+ .club-tip-btn:active { transform: translateY(1px); }+ .club-tip-btn.is-pending {+ background: linear-gradient(135deg, #5a3a78 0%, #6b4d8c 100%);+ box-shadow: none;+ cursor: progress;+ }++ #club-tip-feed {+ display: flex;+ flex-direction: column;+ gap: 4px;+ min-height: 32px;+ }+ .club-tip-row {+ display: grid;+ grid-template-columns: 70px 1fr auto;+ gap: 8px;+ align-items: center;+ font-size: 11.5px;+ padding: 6px 8px;+ border-radius: 7px;+ background: rgba(255, 255, 255, 0.02);+ animation: tipIn 0.32s ease;+ }+ @keyframes tipIn {+ from { transform: translateY(-6px); opacity: 0; }+ to { transform: none; opacity: 1; }+ }+ .club-tip-who {+ color: var(--accent-2);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11px;+ }+ .club-tip-mid { color: var(--text); }+ .club-tip-amt {+ color: var(--text-3);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 10.5px;+ text-align: right;+ }+ .club-feed-empty {+ font-size: 12px;+ color: var(--text-3);+ font-style: italic;+ text-align: center;+ padding: 12px 0;+ }++ /* ── Responsive ─────────────────────────────────────── */+ @media (max-width: 800px) {+ #club-app {+ grid-template-columns: 1fr;+ grid-template-rows: 52px 1fr auto;+ grid-template-areas:+ "top"+ "stage"+ "right";+ }+ #club-right {+ border-left: none;+ border-top: 1px solid var(--border);+ max-height: 45vh;+ }+ }+ </style>+ </head>+ <body>+ <div id="club-app">+ <!-- TOP BAR -->+ <header id="club-top">+ <div class="brand">+ <a href="/" title="three.ws home">three.ws</a>+ <span>/</span>+ <span class="dot" aria-hidden="true"></span>+ <span>Pole Club</span>+ </div>+ <span class="sep"></span>+ <span class="tagline">tip in USDC · she dances</span>+ <span class="spacer"></span>+ <span class="club-pill">$0.001 / dance</span>+ <span class="club-pill club-pill-blue">x402 · Base & Solana</span>+ </header>++ <!-- STAGE -->+ <main id="club-stage">+ <canvas id="club-canvas"></canvas>+ <div id="club-status" hidden>Loading…</div>+ </main>++ <!-- RIGHT PANEL -->+ <aside id="club-right">+ <section class="club-section">+ <h2>How it works</h2>+ <p class="club-intro">+ Four poles, four dancers backstage. Pick a pole, pick a style, hit+ <b>Tip</b>. Your wallet signs a <b>$0.001 USDC</b> x402 payment, the+ server settles it on-chain, the dancer walks out and performs her+ routine. No tip, no dance.+ </p>+ </section>++ <section class="club-section">+ <h2>Poles</h2>+ <div id="club-poles"></div>+ </section>++ <section class="club-section">+ <h2>Live tips</h2>+ <div id="club-tip-feed">+ <div class="club-feed-empty">No tips yet. Be the first.</div>+ </div>+ </section>+ </aside>+ </div>++ <!-- x402 drop-in modal (Phantom/MetaMask wallet flow + 402 retry) -->+ <script type="module" src="/x402.js"></script>+ <script type="module" src="/src/club.js"></script>+ </body>+</html>diff --git a/pages/marketplace.html b/pages/marketplace.htmlindex 41d2287c6..e9339d2a4 100644--- a/pages/marketplace.html+++ b/pages/marketplace.html@@ -182,6 +182,51 @@height: 100%;--poster-color: transparent;background: transparent;+ opacity: 0;+ transition: opacity 0.4s ease;+ }+ .market-hero-slide.mv-loaded model-viewer,+ .market-hero-slide.mv-poster-ready model-viewer {+ opacity: 1;+ }+ /* Always-visible placeholder behind each hero slide so the stage+ shows the avatar's name + initial instead of a black void while+ the GLB streams in (or if it never loads). */+ .market-hero-placeholder {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 14px;+ background:+ radial-gradient(circle at 50% 40%, rgba(125, 211, 252, 0.18), transparent 65%),+ radial-gradient(circle at 50% 90%, rgba(168, 85, 247, 0.12), transparent 70%),+ linear-gradient(180deg, #0b0b10, #050507);+ color: rgba(244, 244, 245, 0.85);+ font-family: 'Space Grotesk', sans-serif;+ pointer-events: none;+ transition: opacity 0.5s ease;+ }+ .market-hero-slide.mv-loaded .market-hero-placeholder {+ opacity: 0;+ }+ .market-hero-placeholder-initial {+ font-size: 96px;+ font-weight: 700;+ line-height: 1;+ background: linear-gradient(180deg, #f4f4f5, #a1a1aa);+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ letter-spacing: -0.04em;+ }+ .market-hero-placeholder-name {+ font-size: 13px;+ letter-spacing: 0.22em;+ text-transform: uppercase;+ color: rgba(161, 161, 170, 0.7);}.market-hero-stage::after {content: '';@@ -331,27 +376,46 @@height: 100%;--poster-color: transparent;background: transparent;+ opacity: 0;+ transition: opacity 0.35s ease;+ }+ .market-card-avatar.mv-loaded .thumb model-viewer,+ .market-card-avatar.mv-poster-ready .thumb model-viewer {+ opacity: 1;}.market-card-avatar .thumb {position: relative;}- .market-card-avatar .thumb-loader {+ /* Name-initial placeholder behind every model-viewer. Visible until+ the GLB renders, so cards never show a blank square while their+ models stream in. */+ .market-card-avatar .thumb .mv-placeholder {position: absolute;inset: 0;display: flex;align-items: center;justify-content: center;background:- radial-gradient(circle at 50% 50%, rgba(125, 211, 252, 0.04), transparent 60%),- linear-gradient(180deg, #050505, #0d0d0d);- color: rgba(255, 255, 255, 0.2);- font-size: 32px;- transition: opacity 0.3s ease;+ radial-gradient(circle at 50% 40%, rgba(125, 211, 252, 0.12), transparent 65%),+ radial-gradient(circle at 50% 95%, rgba(168, 85, 247, 0.08), transparent 70%),+ linear-gradient(180deg, #0a0a0d, #050507);pointer-events: none;+ transition: opacity 0.4s ease;}- .market-card-avatar.loaded .thumb-loader {+ .market-card-avatar.mv-loaded .thumb .mv-placeholder {opacity: 0;}+ .market-card-avatar .thumb .mv-placeholder-initial {+ font-family: 'Space Grotesk', sans-serif;+ font-size: 56px;+ font-weight: 700;+ line-height: 1;+ background: linear-gradient(180deg, #f4f4f5, #71717a);+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ letter-spacing: -0.04em;+ }/* ── Skeleton loading ─────────────────────────────────────────── */@keyframes mk-skeleton-pulse {diff --git a/public/marketplace.css b/public/marketplace.cssindex eebdb7361..28e4f8d4b 100644--- a/public/marketplace.css+++ b/public/marketplace.css@@ -273,6 +273,39 @@ body.market-page {min-height: 200px;}+.market-card-agent .thumb {+ margin: -16px -16px 4px;+ aspect-ratio: 16 / 9;+ background:+ radial-gradient(circle at 50% 40%, rgba(125, 211, 252, 0.12), transparent 65%),+ radial-gradient(circle at 50% 95%, rgba(168, 85, 247, 0.08), transparent 70%),+ linear-gradient(180deg, #0a0a0d, #050507) center/cover no-repeat;+ border-bottom: 1px solid var(--mk-border);+ border-top-left-radius: var(--mk-radius);+ border-top-right-radius: var(--mk-radius);+ position: relative;+ overflow: hidden;+}+.market-card-agent .thumb .mv-placeholder {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ pointer-events: none;+}+.market-card-agent .thumb .mv-placeholder-initial {+ font-family: 'Space Grotesk', sans-serif;+ font-size: 48px;+ font-weight: 700;+ line-height: 1;+ background: linear-gradient(180deg, #f4f4f5, #71717a);+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ letter-spacing: -0.04em;+}+.market-card-agent:hover {border-color: var(--mk-border-2);}diff --git a/scripts/x402-test.mjs b/scripts/x402-test.mjsindex a21bb8c00..281b32108 100644--- a/scripts/x402-test.mjs+++ b/scripts/x402-test.mjs@@ -50,7 +50,11 @@ console.log('Step 2 — signed payload, sig length:', signature.length);const payment = {x402Version: 2,payload: { authorization, signature },- extensions: {},+ // CDP's bazaar indexer reads the discovery extension from+ // paymentPayload.extensions.bazaar — if the client strips it, the+ // facilitator settles the payment but never catalogs the endpoint.+ // Mirror the challenge's extensions verbatim so indexing fires.+ extensions: required.extensions || {},resource: required.resource,accepted: accept,};diff --git a/src/club.js b/src/club.jsnew file mode 100644index 000000000..4d9cc3759--- /dev/null+++ b/src/club.js@@ -0,0 +1,617 @@+// /club — three.ws Pole Club+//+// A dark 3D venue with four pole stages arranged in a half-arc. Each pole has+// a "Tip $0.001 to dance" button bound to /api/x402/dance-tip via the x402+// drop-in modal (window.X402.pay). Once the buyer's USDC settles, the dancer+// for that slot teleports onto their pole and performs the selected routine+// for ~12s, then drifts back to backstage. No tip, no dance.++import {+ AmbientLight,+ Box3,+ CircleGeometry,+ Clock,+ Color,+ CylinderGeometry,+ DoubleSide,+ Fog,+ Group,+ HemisphereLight,+ Mesh,+ MeshBasicMaterial,+ MeshStandardMaterial,+ PerspectiveCamera,+ PlaneGeometry,+ PMREMGenerator,+ PointLight,+ RingGeometry,+ Scene,+ SpotLight,+ SRGBColorSpace,+ Vector3,+ WebGLRenderer,+} from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';+import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';++import { AnimationManager } from './animation-manager.js';++const AVATAR_URL = '/avatars/default.glb';+const MANIFEST_URL = '/animations/manifest.json';++// Clips we actually use — keeps the manifest pre-fetch small.+const REQUIRED_CLIPS = new Set([+ 'idle', 'dance', 'rumba', 'silly', 'thriller', 'capoeira', 'walk',+]);+const WALK_CLIP = 'walk';++const TIP_ENDPOINT = '/api/x402/dance-tip';++// ── Stage layout ─────────────────────────────────────────────────────────+// Four poles in a half-arc facing the camera. Backstage is behind the bar at+// negative Z so dancers visibly walk out before mounting the pole.+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++const POLES = Array.from({ length: POLE_COUNT }, (_, i) => {+ // Spread across an arc from -55° to +55° at the front of the room.+ const t = POLE_COUNT === 1 ? 0.5 : i / (POLE_COUNT - 1);+ const angle = -Math.PI * 0.31 + t * Math.PI * 0.62;+ return {+ id: String(i + 1),+ x: Math.sin(angle) * STAGE_RADIUS,+ z: -Math.cos(angle) * STAGE_RADIUS + 1.4, // shift forward of camera focus+ // Backstage spawn point — same X as pole, deeper into the room.+ backstageX: Math.sin(angle) * (STAGE_RADIUS + 0.6),+ backstageZ: -Math.cos(angle) * (STAGE_RADIUS + 0.6) - 2.4,+ yaw: angle + Math.PI, // face the camera (poles look outward)+ };+});++// ── DOM ───────────────────────────────────────────────────────────────────+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');++function setStatus(text, { kind = 'info' } = {}) {+ if (!statusEl) return;+ statusEl.textContent = text;+ statusEl.dataset.kind = kind;+ statusEl.hidden = false;+ clearTimeout(setStatus._t);+ setStatus._t = setTimeout(() => { statusEl.hidden = true; }, 3500);+}++function fmtUsd(atomics, decimals = 6) {+ if (atomics == null) return '';+ const n = Number(atomics) / 10 ** decimals;+ if (n < 0.01) return `$${n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '')}`;+ return `$${n.toFixed(2)}`;+}++function pushFeed({ dancer, label, payer, amountAtomics, network }) {+ if (!tipFeedEl) return;+ tipFeedEl.querySelector('.club-feed-empty')?.remove();+ const row = document.createElement('div');+ row.className = 'club-tip-row';+ const who = payer ? `${payer.slice(0, 4)}…${payer.slice(-4)}` : 'someone';+ const safeLabel = String(label || 'dance').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();+}++// ── Renderer / scene ──────────────────────────────────────────────────────+const renderer = new WebGLRenderer({ canvas, antialias: true, alpha: false });+renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));+renderer.setSize(window.innerWidth, window.innerHeight, false);+renderer.outputColorSpace = SRGBColorSpace;+renderer.shadowMap.enabled = true;++const scene = new Scene();+scene.background = new Color(0x07050b);+scene.fog = new Fog(0x07050b, 9, 28);++const pmrem = new PMREMGenerator(renderer);+scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.02).texture;++// Soft room light so the avatars aren't pitch black — but kept low so the+// spotlights do the talking.+scene.add(new AmbientLight(0x150b1a, 0.55));+const hemi = new HemisphereLight(0xff6abf, 0x110820, 0.35);+hemi.position.set(0, 6, 0);+scene.add(hemi);++const camera = new PerspectiveCamera(46, window.innerWidth / window.innerHeight, 0.05, 80);+camera.position.set(0, 1.8, 6.0);+camera.lookAt(0, 1.4, -1.5);++// ── Club floor + walls ───────────────────────────────────────────────────+const floor = new Mesh(+ new CircleGeometry(14, 80),+ new MeshStandardMaterial({+ color: 0x12080f,+ roughness: 0.4,+ metalness: 0.65,+ }),+);+floor.rotation.x = -Math.PI / 2;+floor.receiveShadow = true;+scene.add(floor);++// Dance-floor inlay — slightly emissive checker so the room reads as a club,+// not an empty plane.+const danceFloor = new Mesh(+ new CircleGeometry(STAGE_RADIUS + 1.4, 64),+ new MeshStandardMaterial({+ color: 0x1a0a1f,+ roughness: 0.25,+ metalness: 0.85,+ emissive: 0x220a36,+ emissiveIntensity: 0.45,+ }),+);+danceFloor.rotation.x = -Math.PI / 2;+danceFloor.position.y = 0.001;+danceFloor.receiveShadow = true;+scene.add(danceFloor);++// Back wall — gives the room some depth instead of fog going on forever.+const wallMat = new MeshStandardMaterial({+ color: 0x0a050d, roughness: 0.7, metalness: 0.2, side: DoubleSide,+});+const wallBack = new Mesh(new PlaneGeometry(30, 8), wallMat);+wallBack.position.set(0, 4, -10);+scene.add(wallBack);+const wallLeft = new Mesh(new PlaneGeometry(20, 8), wallMat);+wallLeft.position.set(-10, 4, 0);+wallLeft.rotation.y = Math.PI / 2;+scene.add(wallLeft);+const wallRight = new Mesh(new PlaneGeometry(20, 8), wallMat);+wallRight.position.set(10, 4, 0);+wallRight.rotation.y = -Math.PI / 2;+scene.add(wallRight);++// Bar counter behind the dance floor — a long box hint, nothing fancy.+const bar = new Mesh(+ new PlaneGeometry(9, 0.9),+ new MeshStandardMaterial({ color: 0x271425, roughness: 0.4, metalness: 0.7, emissive: 0x10050f, emissiveIntensity: 0.3 }),+);+bar.position.set(0, 0.45, -7.5);+scene.add(bar);++// ── Neon ring around dance floor ─────────────────────────────────────────+const neonRing = new Mesh(+ new RingGeometry(STAGE_RADIUS + 1.35, STAGE_RADIUS + 1.55, 96),+ new MeshBasicMaterial({ color: 0xff2bd6, side: DoubleSide, transparent: true, opacity: 0.85 }),+);+neonRing.rotation.x = -Math.PI / 2;+neonRing.position.y = 0.01;+scene.add(neonRing);+const neonRingOuter = new Mesh(+ new RingGeometry(STAGE_RADIUS + 1.7, STAGE_RADIUS + 1.82, 96),+ new MeshBasicMaterial({ color: 0x4ad6ff, side: DoubleSide, transparent: true, opacity: 0.7 }),+);+neonRingOuter.rotation.x = -Math.PI / 2;+neonRingOuter.position.y = 0.012;+scene.add(neonRingOuter);++// ── Poles + spotlights ───────────────────────────────────────────────────+const POLE_COLORS = [0xff3bd6, 0x4ad6ff, 0xff8a3b, 0x9b5dff];++class PoleStation {+ constructor(idx, layout) {+ this.idx = idx;+ this.layout = layout;+ this.id = layout.id;++ // 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);++ // 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);+ spot.position.set(layout.x, 6.0, layout.z + 0.5);+ spot.target.position.set(layout.x, 0.0, layout.z);+ spot.castShadow = true;+ spot.shadow.mapSize.set(512, 512);+ spot.shadow.bias = -0.0008;+ scene.add(spot);+ scene.add(spot.target);+ this.spot = spot;+ this.spotIdleIntensity = 0.6;+ this.spotActiveIntensity = 12.0;+ spot.intensity = this.spotIdleIntensity;++ // Floor accent point light — sits at the base of the pole.+ const accent = new PointLight(POLE_COLORS[idx % POLE_COLORS.length], 0.4, 4.5, 1.6);+ accent.position.set(layout.x, 0.6, layout.z);+ scene.add(accent);+ this.accent = accent;++ // Dancer rig — placed in backstage. We populate skinned mesh later.+ this.rig = new Group();+ this.rig.position.set(layout.backstageX, 0, layout.backstageZ);+ this.rig.rotation.y = layout.yaw;+ scene.add(this.rig);++ this.anim = null;+ this.skinned = null;++ // Current performance lifecycle.+ this.activeTicket = null; // backend ticket id+ this.activeUntil = 0; // ms epoch — when to release the stage+ this.performing = false;+ this.walkPhase = 'idle'; // 'idle' | 'to-pole' | 'dancing' | 'returning'+ this._phaseTarget = this.rig.position.clone();+ }++ attachAvatar(template, animationDefs) {+ const root = cloneSkinnedScene(template);+ root.traverse((n) => {+ if (!n.isMesh) return;+ n.castShadow = true;+ n.receiveShadow = false;+ if (n.material && 'envMapIntensity' in n.material) {+ n.material = n.material.clone();+ n.material.envMapIntensity = 0.6;+ // Tint each dancer subtly with the pole's accent color so the+ // four are visually distinct even before the spotlight kicks in.+ if (n.material.emissive) {+ n.material.emissive = new Color(POLE_COLORS[this.idx % POLE_COLORS.length]);+ n.material.emissiveIntensity = 0.05;+ }+ }+ });++ // Re-zero the avatar so feet sit at rig y=0.+ const box = new Box3().setFromObject(root);+ root.position.y -= box.min.y;++ this.rig.add(root);+ this.skinned = root;++ this.anim = new AnimationManager();+ this.anim.attach(root);+ this.anim.setAnimationDefs(animationDefs);+ // Lazy-load — first clip request fetches its JSON on demand.+ this.anim.play('idle');+ }++ get backstagePos() {+ return new Vector3(this.layout.backstageX, 0, this.layout.backstageZ);+ }+ get poleBasePos() {+ return new Vector3(this.layout.x, 0, this.layout.z + 0.02);+ }++ async startPerformance(ticket) {+ this.activeTicket = ticket;+ this.performing = true;+ this.activeUntil = Date.now() + (ticket.durationSec || 12) * 1000;+ this.walkPhase = 'to-pole';+ this._phaseTarget = this.poleBasePos;++ // Spotlight ramps up while the dancer walks on stage.+ this._spotTarget = this.spotActiveIntensity;+ this._accentTarget = 2.4;++ // Crossfade idle → walking → dance once the dancer reaches the pole.+ await this.anim?.crossfadeTo(WALK_CLIP, PERFORMANCE_FADE);+ }++ async _arriveAtPole() {+ this.walkPhase = 'dancing';+ const clipName = this.activeTicket?.clip || 'dance';+ await this.anim?.crossfadeTo(clipName, PERFORMANCE_FADE);+ }++ async _endPerformance() {+ this.performing = false;+ this.walkPhase = 'returning';+ this._phaseTarget = this.backstagePos;+ this._spotTarget = this.spotIdleIntensity;+ this._accentTarget = 0.4;+ await this.anim?.crossfadeTo(WALK_CLIP, PERFORMANCE_FADE);+ }++ async _arriveBackstage() {+ this.walkPhase = 'idle';+ this.activeTicket = null;+ this._phaseTarget = this.backstagePos;+ await this.anim?.crossfadeTo('idle', PERFORMANCE_FADE);+ }++ tick(dt) {+ // Lerp spotlight intensity.+ if (this._spotTarget != null) {+ this.spot.intensity += (this._spotTarget - this.spot.intensity) * Math.min(1, dt * 4);+ }+ if (this._accentTarget != null) {+ this.accent.intensity += (this._accentTarget - this.accent.intensity) * Math.min(1, dt * 4);+ }++ // Drive avatar walk between waypoints.+ if (this.walkPhase === 'to-pole' || this.walkPhase === 'returning') {+ const target = this._phaseTarget;+ const dir = new Vector3().subVectors(target, this.rig.position);+ dir.y = 0;+ const dist = dir.length();+ if (dist < 0.04) {+ this.rig.position.copy(target);+ if (this.walkPhase === 'to-pole') this._arriveAtPole();+ else this._arriveBackstage();+ } else {+ dir.normalize();+ const step = Math.min(dist, 1.4 * dt);+ this.rig.position.addScaledVector(dir, step);+ // Face direction of travel.+ const targetYaw = Math.atan2(dir.x, dir.z);+ this.rig.rotation.y += angleDelta(this.rig.rotation.y, targetYaw) * Math.min(1, dt * 6);+ }+ } else if (this.walkPhase === 'dancing') {+ // Keep dancer facing the camera (yaw lerp to original pole yaw).+ 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;+ this.rig.rotation.y += angleDelta(this.rig.rotation.y, targetYaw) * Math.min(1, dt * 1.5);+ }++ this.anim?.update(dt);+ }+}++function angleDelta(from, to) {+ let d = (to - from) % (Math.PI * 2);+ if (d > Math.PI) d -= Math.PI * 2;+ if (d < -Math.PI) d += Math.PI * 2;+ return d;+}++const stations = POLES.map((layout, i) => new PoleStation(i, layout));++// ── Disco / strobe light cycling ─────────────────────────────────────────+// A slowly rotating set of fill lights to keep the room feeling alive even+// when no dancers are out. Kept low-intensity so spotlights still dominate.+const disco = new Group();+scene.add(disco);+const discoColors = [0xff2bd6, 0x4ad6ff, 0xff8a3b, 0x6c4dff];+for (let i = 0; i < 4; i++) {+ const p = new PointLight(discoColors[i], 0.6, 12, 1.4);+ const angle = (i / 4) * Math.PI * 2;+ p.position.set(Math.sin(angle) * 5.5, 4.6, Math.cos(angle) * 5.5 - 1);+ disco.add(p);+}++// ── Avatar template + manifest load ──────────────────────────────────────+let animationDefs = null;+async function bootstrap() {+ setStatus('Loading club…');++ const loader = new GLTFLoader();+ const [gltf, manifest] = 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();+ }),+ ]);++ const template = gltf.scene;+ // Mark all materials as cloneable up front so per-dancer tinting works.+ template.traverse((n) => {+ if (n.isMesh) n.castShadow = true;+ });++ animationDefs = manifest.filter((d) => REQUIRED_CLIPS.has(d.name));++ for (const station of stations) {+ station.attachAvatar(template, animationDefs);+ }++ setStatus('Tip a pole to make her dance.', { kind: 'ok' });+}++// ── Tip flow (x402 drop-in) ──────────────────────────────────────────────+async function tipDancer({ dancer, dance, button }) {+ if (!window.X402?.pay) {+ setStatus('Payment widget still loading — try again in a second.', { kind: 'error' });+ return;+ }++ const station = stations.find((s) => s.id === String(dancer));+ if (!station) {+ setStatus(`No dancer ${dancer} on stage.`, { kind: 'error' });+ return;+ }+ if (station.performing) {+ setStatus(`Dancer ${dancer} is already performing — tip another pole.`, { kind: 'warn' });+ return;+ }++ const url = `${TIP_ENDPOINT}?dancer=${encodeURIComponent(dancer)}&dance=${encodeURIComponent(dance)}`;++ button?.classList.add('is-pending');+ const originalLabel = button?.textContent;+ if (button) button.textContent = 'Open wallet…';++ try {+ const out = await window.X402.pay({+ endpoint: url,+ method: 'GET',+ merchant: 'three.ws Pole Club',+ action: `Tip Dancer ${dancer} — ${dance}`,+ });+ const ticket = out?.result;+ if (!ticket?.ok) {+ throw new Error(ticket?.error || 'tip did not settle');+ }+ station.startPerformance(ticket);+ pushFeed({+ dancer: ticket.dancer,+ label: ticket.label || ticket.dance,+ payer: ticket.payer,+ amountAtomics: ticket.amountAtomics,+ network: ticket.network,+ });+ setStatus(`Dancer ${ticket.dancer} → ${ticket.label}`, { kind: 'ok' });+ } catch (err) {+ if (err?.code !== 'cancelled') {+ setStatus(err?.message || 'tip failed', { kind: 'error' });+ }+ } finally {+ button?.classList.remove('is-pending');+ if (button && originalLabel) button.textContent = originalLabel;+ }+}++// ── Side panel — render pole controls ────────────────────────────────────+const DANCES = [+ { key: 'rumba', label: 'Rumba' },+ { key: 'silly', label: 'Silly' },+ { key: 'thriller', label: 'Thriller' },+ { key: 'capoeira', label: 'Capoeira' },+ { key: 'hiphop', label: 'Hip Hop' },+];++function renderPoles() {+ if (!polesPanel) return;+ polesPanel.innerHTML = '';+ for (const pole of POLES) {+ const card = document.createElement('div');+ card.className = 'club-pole-card';+ card.innerHTML = `+ <div class="club-pole-head">+ <span class="club-pole-id">Pole ${pole.id}</span>+ <span class="club-pole-price">$0.001 USDC</span>+ </div>+ <label class="club-pole-style">+ Style+ <select data-dancer="${pole.id}" class="club-pole-select">+ ${DANCES.map((d) => `<option value="${d.key}">${d.label}</option>`).join('')}+ </select>+ </label>+ <button type="button" class="club-tip-btn" data-dancer="${pole.id}">+ Tip ${pole.id} — make her dance+ </button>+ `;+ polesPanel.appendChild(card);+ }+ polesPanel.addEventListener('click', (e) => {+ const btn = e.target.closest('.club-tip-btn');+ if (!btn) return;+ const dancer = btn.dataset.dancer;+ const select = polesPanel.querySelector(`.club-pole-select[data-dancer="${dancer}"]`);+ const dance = select?.value || 'rumba';+ tipDancer({ dancer, dance, button: btn });+ });+}++// ── Camera orbit on drag ─────────────────────────────────────────────────+let camYaw = 0;+let camPitch = 0.05;+{+ let dragging = false;+ let lastX = 0, lastY = 0, downId = -1;+ canvas.addEventListener('pointerdown', (e) => {+ dragging = true;+ downId = e.pointerId;+ lastX = e.clientX; lastY = e.clientY;+ canvas.setPointerCapture?.(e.pointerId);+ });+ canvas.addEventListener('pointermove', (e) => {+ if (!dragging || e.pointerId !== downId) return;+ const dx = e.clientX - lastX;+ const dy = e.clientY - lastY;+ lastX = e.clientX; lastY = e.clientY;+ camYaw -= dx * 0.004;+ camPitch = Math.max(-0.3, Math.min(0.5, camPitch - dy * 0.003));+ });+ const onUp = (e) => {+ if (e.pointerId !== downId) return;+ dragging = false; downId = -1;+ try { canvas.releasePointerCapture?.(e.pointerId); } catch {}+ };+ canvas.addEventListener('pointerup', onUp);+ canvas.addEventListener('pointercancel', onUp);+}++// ── Resize ────────────────────────────────────────────────────────────────+window.addEventListener('resize', () => {+ renderer.setSize(window.innerWidth, window.innerHeight, false);+ camera.aspect = window.innerWidth / window.innerHeight;+ camera.updateProjectionMatrix();+});++// ── Render loop ──────────────────────────────────────────────────────────+const clock = new Clock();+function animate() {+ const dt = Math.min(clock.getDelta(), 0.066);+ const t = clock.getElapsedTime();++ for (const station of stations) station.tick(dt);++ // Disco light slow swirl.+ disco.rotation.y = t * 0.25;++ // Camera dolly — gentle orbit around the dance floor center.+ const focus = new Vector3(0, 1.2, -1.8);+ const offsetBase = new Vector3(0, 2.2 + camPitch * 2.5, 7.2);+ offsetBase.applyAxisAngle(new Vector3(0, 1, 0), camYaw);+ const target = focus.clone().add(offsetBase);+ camera.position.lerp(target, Math.min(1, dt * 2));+ camera.lookAt(focus);++ renderer.render(scene, camera);+ requestAnimationFrame(animate);+}++renderPoles();+bootstrap()+ .catch((err) => {+ console.error('[club] bootstrap failed', err);+ setStatus(`Club failed to load: ${err.message}`, { kind: 'error' });+ })+ .finally(() => animate());diff --git a/src/marketplace.js b/src/marketplace.jsindex 03acaa22e..acc9cfddf 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -173,37 +173,50 @@ async function _posterSet(key, blob) {}/**- * After renderGrid() sets innerHTML, run this to:- * 1. Apply cached poster blobs (instant thumbnails on repeat visits).- * 2. Attach load-listener to capture + cache poster on first visit.- * 3. Add .mv-loaded class when model loads (triggers CSS shimmer-off + fade-in).+ * Apply lightweight preview behavior to every <model-viewer> inside `root`:+ * 1. Apply cached poster blob (instant thumbnails on repeat visits).+ * 2. Capture + cache poster on first load for next time.+ * 3. Mark the enclosing card/slide .mv-loaded once the GLB renders, so the+ * placeholder gradient behind it fades out.+ *+ * Use `data-src` OR `src` as the cache key — avatar cards lazy-load via+ * data-src and only get src promoted on intersect, but the poster should be+ * visible immediately on render, before the GLB ever starts downloading.*/-async function attachModelViewerBehavior() {- const cards = els.grid.querySelectorAll('.market-card-avatar');- for (const card of cards) {- const mv = card.querySelector('model-viewer');- if (!mv) continue;- const src = mv.getAttribute('src');- if (!src) continue;-- // Apply cached poster immediately (sync path via already-resolved db).- const cached = await _posterGet(src);+async function attachModelViewerBehavior(root = els.grid) {+ if (!root) return;+ const viewers = root.querySelectorAll('model-viewer');+ for (const mv of viewers) {+ if (mv.dataset.posterWired === '1') continue;+ mv.dataset.posterWired = '1';++ const key = mv.dataset.src || mv.getAttribute('src');+ if (!key) continue;++ // The placeholder is the closest ancestor we want to fade once loaded.+ // Cards use .market-card-avatar; hero uses .market-hero-slide; fall back+ // to the model-viewer itself so the .mv-loaded class always lands somewhere.+ const host =+ mv.closest('.market-card-avatar, .market-hero-slide') || mv;++ const cached = await _posterGet(key);if (cached) {mv.setAttribute('poster', URL.createObjectURL(cached));+ host.classList.add('mv-poster-ready');}const onLoad = async () => {- card.classList.add('mv-loaded');+ host.classList.add('mv-loaded');if (!cached) {try {const blob = await mv.generatePosterBlob({ idealAspect: true });- if (blob) await _posterSet(src, blob);+ if (blob) await _posterSet(key, blob);} catch {}}};mv.addEventListener('load', onLoad, { once: true });// model-viewer fires 'poster-dismissed' when it transitions from poster → 3D.- mv.addEventListener('poster-dismissed', () => card.classList.add('mv-loaded'), { once: true });+ mv.addEventListener('poster-dismissed', () => host.classList.add('mv-loaded'), { once: true });}}@@ -567,6 +580,10 @@ function renderHero() {.map((a, i) => `<div class="market-hero-slide${i === state.heroIndex ? ' active' : ''}" data-slot="${i}">+ <div class="market-hero-placeholder" aria-hidden="true">+ <span class="market-hero-placeholder-initial">${escapeHtml(initial(a.name || 'A'))}</span>+ <span class="market-hero-placeholder-name">${escapeHtml(a.name || 'Avatar')}</span>+ </div><model-viewersrc="${escapeHtml(a.glbUrl)}"alt="${escapeHtml(a.name || 'Avatar')}"@@ -583,6 +600,7 @@ function renderHero() {</div>`,).join('');+ attachModelViewerBehavior(stage);// If a hero GLB upstream blocks CORS or 404s, model-viewer logs to console// and shows nothing. Listen for that and remove the broken slide so we// don't show empty stages or pollute the console.@@ -1378,6 +1396,14 @@ function renderSkeletons(n) {return cards;}+// Name-initial placeholder rendered behind every model-viewer preview. Stays+// visible until model-viewer loads (then faded out via .mv-loaded), so cards+// and the hero never show a blank black void while GLBs stream in.+function placeholderHtml(name) {+ const i = escapeHtml(initial(name || 'A'));+ return `<div class="mv-placeholder" aria-hidden="true"><span class="mv-placeholder-initial">${i}</span></div>`;+}+function renderAvatarCard(a, spotlight = false) {const name = escapeHtml(a.name || 'Untitled avatar');const desc = escapeHtml(a.description || '');@@ -1402,7 +1428,7 @@ function renderAvatarCard(a, spotlight = false) {const preview = a.image? `<img src="${escapeHtml(a.image)}" alt="${name}" loading="lazy" decoding="async" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'card-img-fallback'}))" />`: a.glbUrl- ? `<model-viewer+ ? `${placeholderHtml(a.name)}<model-viewerdata-src="${escapeHtml(a.glbUrl)}"alt="${name}"rotation-per-second="14deg"@@ -1415,7 +1441,7 @@ function renderAvatarCard(a, spotlight = false) {tone-mapping="aces"loading="lazy"></model-viewer>`- : `<div class="thumb-fallback">◉</div>`;+ : `<div class="thumb-fallback">${escapeHtml(initial(a.name))}</div>`;const isSpotlight = spotlight || a.featured;const spotlightBadge = isSpotlight ? '<span class="card-featured-badge" title="Featured">⭐</span>' : '';const bmActive = getAvatarBookmarks().has(a.avatarId || '');@@ -1452,7 +1478,14 @@ function renderCard(a) {const avatarBlock = a.thumbnail_url? `<div class="avatar avatar-img" style="background-image:url('${escapeHtml(a.thumbnail_url)}')"></div>`: `<div class="avatar">${escapeHtml(initial(a.name))}</div>`;+ // Lightweight preview strip at the top of the card: uses the linked+ // avatar's thumbnail if there is one, otherwise a styled name-initial+ // gradient so the card never looks visually empty.+ const previewStrip = a.thumbnail_url+ ? `<div class="thumb" style="background-image:url('${escapeHtml(a.thumbnail_url)}')"></div>`+ : `<div class="thumb">${placeholderHtml(a.name)}</div>`;return `<div class="market-card-agent" data-id="${a.id}">+ ${previewStrip}<div class="head">${avatarBlock}<div style="min-width:0;flex:1">@@ -1487,10 +1520,9 @@ function renderOnchainCard(a) {const preview = a.image? `<img src="${escapeHtml(a.image)}" alt="${name}" loading="lazy" decoding="async" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'card-img-fallback'}))" />`: a.glbUrl- ? `<model-viewer- src="${escapeHtml(a.glbUrl)}"+ ? `${placeholderHtml(a.name)}<model-viewer+ data-src="${escapeHtml(a.glbUrl)}"alt="${name}"- auto-rotaterotation-per-second="14deg"interaction-prompt="none"disable-zoom@@ -1502,7 +1534,7 @@ function renderOnchainCard(a) {loading="lazy"reveal="auto"></model-viewer>`- : `<div class="thumb-fallback">⬡</div>`;+ : `<div class="thumb-fallback">${escapeHtml(initial(a.name))}</div>`;return `<div class="market-card-avatar onchain" data-onchain-href="${escapeHtml(href)}"><div class="thumb">${preview}</div><div class="body">diff --git a/vite.config.js b/vite.config.jsindex f0e69b42b..22f9ef271 100644--- a/vite.config.js+++ b/vite.config.js@@ -144,6 +144,7 @@ const appConfig = {'widget-studio': resolve(__dirname, 'pages/widget-studio.html'),walk: resolve(__dirname, 'pages/walk.html'),pose: resolve(__dirname, 'pages/pose.html'),+ club: resolve(__dirname, 'pages/club.html'),studio: resolve(__dirname, 'public/studio/index.html'),reputation: resolve(__dirname, 'public/reputation/index.html'),hydrate: resolve(__dirname, 'public/hydrate/index.html'),@@ -244,6 +245,8 @@ const appConfig = {'/walk/': resolve(root, 'pages/walk.html'),'/pose': resolve(root, 'pages/pose.html'),'/pose/': resolve(root, 'pages/pose.html'),+ '/club': resolve(root, 'pages/club.html'),+ '/club/': resolve(root, 'pages/club.html'),'/walkaround': resolve(root, 'public/demos/walkaround.html'),'/walkaround/': resolve(root, 'public/demos/walkaround.html'),'/brain': resolve(root, 'public/demos/brain.html'),