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: market ohlcv, agents, ibm oracle, play builds, cosmetics + community-net updates

nirholas95241fc2b1a4
diff --git a/api/_lib/market/ohlcv.js b/api/_lib/market/ohlcv.js
index f5ce86d1a..d98d2b61d 100644
--- a/api/_lib/market/ohlcv.js
+++ b/api/_lib/market/ohlcv.js
@@ -20,21 +20,40 @@ async function gecko(path) {
const hit = cache.get(url);
if (hit && hit.expiresAt > now) return hit.value;
+ // One bounded retry on a 429 with backoff before giving up — GeckoTerminal's
+ // free tier throttles bursts, and a short wait usually clears it well within
+ // the function budget. Preserves 429 as the thrown status (not a generic 502)
+ // so the caller can map it to a retryable response instead of a hard error.
let res;
- try {
- res = await fetch(url, {
- headers: { accept: 'application/json', 'user-agent': UA },
- signal: AbortSignal.timeout(12_000),
+ let lastStatus = 502;
+ for (let attempt = 0; attempt < 2; attempt++) {
+ try {
+ res = await fetch(url, {
+ headers: { accept: 'application/json', 'user-agent': UA },
+ signal: AbortSignal.timeout(12_000),
+ });
+ } catch (e) {
+ throw Object.assign(new Error(`GeckoTerminal unreachable: ${e.message}`), {
+ status: 502,
+ });
+ }
+ if (res.ok) break;
+ lastStatus = res.status;
+ const text = await res.text();
+ if (res.status === 429 && attempt === 0) {
+ await new Promise((r) => setTimeout(r, 600));
+ continue; // retry once
+ }
+ throw Object.assign(new Error(`GeckoTerminal ${res.status}: ${text.slice(0, 160)}`), {
+ status: res.status === 404 ? 404 : res.status === 429 ? 429 : 502,
});
- } catch (e) {
- throw Object.assign(new Error(`GeckoTerminal unreachable: ${e.message}`), { status: 502 });
}
- const text = await res.text();
- if (!res.ok) {
- throw Object.assign(new Error(`GeckoTerminal ${res.status}: ${text.slice(0, 160)}`), {
- status: res.status === 404 ? 404 : 502,
+ if (!res || !res.ok) {
+ throw Object.assign(new Error(`GeckoTerminal ${lastStatus}`), {
+ status: lastStatus === 404 ? 404 : lastStatus === 429 ? 429 : 502,
});
}
+ const text = await res.text();
let json;
try {
json = JSON.parse(text);
diff --git a/api/_lib/migrations/20260605120000_usage_events.sql b/api/_lib/migrations/20260605120000_usage_events.sql
new file mode 100644
index 000000000..343240815
--- /dev/null
+++ b/api/_lib/migrations/20260605120000_usage_events.sql
@@ -0,0 +1,33 @@
+-- usage_events — quota / analytics / billing event log.
+--
+-- This table is defined in api/_lib/schema.sql but the production migration
+-- runner (scripts/run-migrations.mjs) only applies api/_lib/migrations/*.sql,
+-- so a prod DB provisioned purely from the migration stream never received it.
+-- That surfaced as `NeonDbError: relation "usage_events" does not exist`
+-- (code 42P01) on /api/agents/[id] and every billing/usage read.
+--
+-- This migration reconciles the drift: it (re)creates the table, its indexes,
+-- and the additive agent_id column exactly as schema.sql declares them. Fully
+-- idempotent — safe to run against a DB that already has the table.
+
+create table if not exists usage_events (
+ id bigserial primary key,
+ user_id uuid references users(id) on delete set null,
+ api_key_id uuid references api_keys(id) on delete set null,
+ client_id text references oauth_clients(client_id) on delete set null,
+ avatar_id uuid references avatars(id) on delete set null,
+ kind text not null,
+ tool text,
+ status text not null default 'ok',
+ bytes bigint,
+ latency_ms int,
+ meta jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists usage_events_user_time on usage_events(user_id, created_at desc);
+create index if not exists usage_events_kind_time on usage_events(kind, created_at desc);
+
+-- Additive: agent attribution (see schema.sql "Additive migrations for usage_events").
+alter table usage_events add column if not exists agent_id uuid references agent_identities(id) on delete set null;
+create index if not exists usage_events_agent_time on usage_events(agent_id, created_at desc) where agent_id is not null;
diff --git a/api/agents.js b/api/agents.js
index ac3f1a61e..bc47ad865 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -346,12 +346,20 @@ export async function handleGetOne(req, res, id) {
await healStaleAvatarId(row);
- const [chatRow] = await sql`
- SELECT COUNT(*)::int AS total
- FROM usage_events
- WHERE agent_id = ${id} AND kind = 'llm'
- `;
- row.chat_count = chatRow?.total ?? 0;
+ // chat_count is supplementary decoration on the agent record — never let
+ // a usage-stats query failure (e.g. usage_events not yet migrated, code
+ // 42P01) take down the whole agent fetch. Degrade to 0.
+ try {
+ const [chatRow] = await sql`
+ SELECT COUNT(*)::int AS total
+ FROM usage_events
+ WHERE agent_id = ${id} AND kind = 'llm'
+ `;
+ row.chat_count = chatRow?.total ?? 0;
+ } catch (err) {
+ console.warn('[agents] chat_count usage_events query failed, defaulting to 0:', err?.message);
+ row.chat_count = 0;
+ }
// Public fields if not owner; full record if owner. Auth on a public GET
// is best-effort — anonymous viewers still get the public projection.
diff --git a/api/brain/chat.js b/api/brain/chat.js
index 5a5f7b63e..e8288a7f6 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -183,11 +183,17 @@ const PROVIDERS = {
};
function openrouter() {
- return createOpenAI({
+ const provider = createOpenAI({
apiKey: env.OPENROUTER_API_KEY,
baseURL: 'https://openrouter.ai/api/v1',
headers: { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws brain' },
});
+ // OpenRouter (like every OpenAI-*compatible* backend) implements the Chat
+ // Completions API, NOT OpenAI's newer Responses API. The AI SDK's callable
+ // default `provider(id)` builds a Responses-API model, which OpenRouter
+ // rejects ("Invalid Responses API request" / "unsupported content types").
+ // Force the chat-completions surface so every routed model actually answers.
+ return (modelId) => provider.chat(modelId);
}
// Stream IBM Granite (watsonx.ai) to the page using the same SSE protocol as
diff --git a/api/ibm/oracle.js b/api/ibm/oracle.js
index 49438e056..1aceb52e0 100644
--- a/api/ibm/oracle.js
+++ b/api/ibm/oracle.js
@@ -52,6 +52,19 @@ async function narrate(cfg, { name, symbol, currentPrice, stats }) {
return { text: (text || '').trim(), model, usage };
}
+// Map a GeckoTerminal upstream failure (ohlcv.js attaches the real .status) to
+// a clean client response instead of an unhandled 500. A 429 becomes a
+// retryable 503; 404 passes through; everything else is a 502 bad-gateway.
+function marketUpstreamError(res, err) {
+ const upstream = err?.status;
+ const status = upstream === 429 ? 503 : upstream === 404 ? 404 : 502;
+ const code =
+ status === 503 ? 'upstream_rate_limited' : status === 404 ? 'pool_not_found' : 'upstream_error';
+ return error(res, status, code, `market data upstream: ${err?.message || 'unavailable'}`, {
+ retryable: status === 503,
+ });
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
@@ -63,8 +76,12 @@ export default wrap(async (req, res) => {
// ── Picker: trending Solana pools ────────────────────────────────────────
if (params.get('list') === 'trending') {
- const pools = await trendingPools('solana', 8);
- return json(res, 200, { pools }, { 'cache-control': 'public, max-age=30, s-maxage=60' });
+ try {
+ const pools = await trendingPools('solana', 8);
+ return json(res, 200, { pools }, { 'cache-control': 'public, max-age=30, s-maxage=60' });
+ } catch (err) {
+ return marketUpstreamError(res, err);
+ }
}
// ── Resolve the pool to forecast ─────────────────────────────────────────
@@ -73,7 +90,11 @@ export default wrap(async (req, res) => {
const token = (params.get('token') || '').trim();
if (!pool && token) {
if (!isBase58(token)) return error(res, 400, 'bad_token', 'token must be a base58 mint');
- pool = await topPoolForToken(token, network);
+ try {
+ pool = await topPoolForToken(token, network);
+ } catch (err) {
+ return marketUpstreamError(res, err);
+ }
}
if (!pool || !isBase58(pool)) {
return error(
@@ -90,13 +111,18 @@ export default wrap(async (req, res) => {
const aggregate = Math.max(1, Math.min(60, parseInt(params.get('aggregate') || '1', 10) || 1));
// ── Real candles (keyless, always returned) ──────────────────────────────
- const { candles, base, quote, freq } = await fetchOhlcv({
- pool,
- network,
- timeframe,
- aggregate,
- limit: 1000,
- });
+ let candles, base, quote, freq;
+ try {
+ ({ candles, base, quote, freq } = await fetchOhlcv({
+ pool,
+ network,
+ timeframe,
+ aggregate,
+ limit: 1000,
+ }));
+ } catch (err) {
+ return marketUpstreamError(res, err);
+ }
if (candles.length < 64) {
return error(
res,
diff --git a/api/play/builds.js b/api/play/builds.js
index 2ec526d26..9a48db7bd 100644
--- a/api/play/builds.js
+++ b/api/play/builds.js
@@ -57,7 +57,10 @@ export default wrap(async (req, res) => {
const rl = await limits.buildPublishIp(clientIp(req));
if (!rl.success) return error(res, 429, 'rate_limited', 'sharing too fast — try again shortly');
- const parsed = publishSchema.safeParse(await readJson(req, MAX_THUMB_CHARS + 2048).catch(() => null));
+ // Read a little past the thumb cap so a modestly-oversized screenshot is
+ // rejected by the schema (a clean 413) rather than the raw byte limit, while
+ // a truly enormous body is still refused before it's fully buffered.
+ const parsed = publishSchema.safeParse(await readJson(req, Math.round(MAX_THUMB_CHARS * 1.5)).catch(() => null));
if (!parsed.success) {
const tooBig = parsed.error?.issues?.some((i) => /too large/.test(i.message));
if (tooBig) return error(res, 413, 'thumb_too_large', 'screenshot too large to share');
diff --git a/public/login.html b/public/login.html
index 9b68b1ce8..b94090b41 100644
--- a/public/login.html
+++ b/public/login.html
@@ -802,7 +802,7 @@
setFieldError(passwordInput, passwordErr, 'Enter your password.');
bad = true;
}
- if (bad) { window.__avatarDisapprove?.(); return; }
+ if (bad) { window.__avatarReact?.(); return; }
btn.disabled = true;
btn.textContent = 'Signing in…';
@@ -840,7 +840,7 @@
setFieldError(passwordInput, passwordErr, e2.message);
btn.disabled = false;
btn.textContent = 'Sign in';
- window.__avatarDisapprove?.();
+ window.__avatarFall?.();
}
});
@@ -855,7 +855,7 @@
const agent = await createAgentUI({
canvas: document.getElementById('avatar-canvas'),
- clips: ['idle', 'walk', 'covereyes', 'reaction', 'silly', 'defeated', 'angry', 'facepalm'],
+ clips: ['idle', 'covereyes', 'facepalm', 'falltolanding', 'standup', 'dance'],
subclips: {
covereyes: { start: 0, end: 48, fps: 30 },
},
@@ -891,18 +891,44 @@
field.addEventListener('blur', uncoverEyes);
});
- const pickFail = agent.pickFrom(['reaction', 'defeated', 'angry', 'facepalm']);
- window.__avatarDisapprove = function () {
- const pick = pickFail();
- agent.play(pick, { loop: false });
- const dur = agent.clip(pick) * 1000;
+ // Settle back to a resting pose after a one-shot reaction. If the
+ // user is still in a credential field, the eyes stay shielded;
+ // otherwise the avatar relaxes to idle.
+ function settle() {
+ const active = document.activeElement;
+ if (active && credentialFields.includes(active)) coverEyes();
+ else agent.play('idle', { loop: true });
+ }
+
+ // Empty field — a quick facepalm nudge, no full collapse.
+ window.__avatarReact = function () {
+ agent.faceFront();
+ agent.play('facepalm', { loop: false });
+ const dur = agent.clip('facepalm') * 1000;
setTimeout(() => {
- if (agent.currentClip === pick) agent.play('idle', { loop: true });
+ if (agent.currentClip === 'facepalm') settle();
}, dur - 150);
};
+ // Wrong credentials — the avatar topples to the ground, lies there
+ // a beat, then picks itself back up.
+ window.__avatarFall = function () {
+ agent.faceFront();
+ agent.play('falltolanding', {
+ loop: false,
+ hold: true,
+ onComplete: () => {
+ setTimeout(() => {
+ agent.play('standup', { loop: false, onComplete: settle });
+ }, 650);
+ },
+ });
+ };
+
+ // Successful sign-in — a happy dance while we redirect.
window.__avatarCelebrate = function () {
- agent.play('silly', { loop: true });
+ agent.faceFront();
+ agent.play('dance', { loop: true });
};
</script>
<script src="/brand.js" defer></script>
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index b89bd0fe0..920b7cec1 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -30,6 +30,7 @@ import {
VoxelWorld, createBuildHud, parseKey, keyOf, MAX_BLOCKS, BLOCK,
COMPOSITE_PIECES, compositeCells, MAX_COMPOSITE_CELLS,
} from './build-voxels.js';
+import { WorldObjects, PropGhost, PROP_CATALOG, DEFAULT_PROP, propDef } from './world-objects.js';
import { normalizeGatewayURL } from '../ipfs.js';
import {
loadManifest, getEmoteDefs, resolveAvatarUrl, buildAvatar, playEmoteClip,
@@ -273,6 +274,12 @@ export class CoinCommunities {
// quarter-turn rotation (0–3) applied to it. Both drive the ghost preview.
this.buildPiece = null;
this.buildRot = 0;
+ // R18 props: which placeable prop is armed (null = voxel layer active), its
+ // quarter-turn rotation, and current scale. When a prop is armed, build clicks
+ // place free-standing objects through the R01 object channel instead of voxels.
+ this.buildProp = null;
+ this.buildPropRot = 0;
+ this.buildPropScale = 1;
this.buildHud = createBuildHud({
onToggle: (on) => this._onBuildToggle(on),
onPick: (i) => { this.buildType = i; this._refreshGhost(); },
@@ -765,6 +772,16 @@ export class CoinCommunities {
// anything unowned.
cosmetics: getPlayCosmetics(),
});
+ // Generic networked-object layer for this coin (R02): mirrors the server's
+ // authoritative `objects` map into the scene — build props (R18), and any
+ // future ball/pickup — interpolated like the avatars. Delete-own keys on the
+ // net's ownership check. Built per world; disposed alongside voxels on leave.
+ this.worldObjects = new WorldObjects(this.scene, this.net, {
+ isMine: (obj) => !!this.net?.ownsObject(obj),
+ });
+ this.propGhost = new PropGhost(this.scene);
+ this.net.on('objectReject', ({ reason }) => this._onObjectReject(reason));
+
if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));
this.net.on('status', ({ status }) => {
this.ui.setStatus(status);
@@ -1126,6 +1143,8 @@ export class CoinCommunities {
if (this._oracleRibbon) { this._oracleRibbon.dispose(); this._oracleRibbon = null; }
if (this._reactor) { this._reactor.dispose(); this._reactor = null; }
if (this.voxels) { this.voxels.dispose(); this.voxels = null; }
+ if (this.worldObjects) { this.worldObjects.dispose(); this.worldObjects = null; }
+ if (this.propGhost) { this.propGhost.dispose(); this.propGhost = null; }
this._cancelLongPress();
clearTimeout(this._onboardTimer);
this._undoStack = []; // history is per-world; don't carry edits across coins
@@ -1137,7 +1156,9 @@ export class CoinCommunities {
// Reset the structures toolbar back to single-block and close any open
// share / featured surfaces — they're scoped to the world we're leaving.
this.buildPiece = null; this.buildRot = 0;
+ this.buildProp = null; this.buildPropRot = 0; this.buildPropScale = 1;
this.ui.setBuildPiece(null);
+ this.ui.setPropSelected(null);
this.ui.setBuildToolsVisible(false);
this.ui.closeShareSheet();
this.ui.closeFeatured();
@@ -1367,10 +1388,10 @@ export class CoinCommunities {
this.buildHud.select(k === '0' ? 9 : Number(k) - 1);
return;
}
- // R rotates the armed composite piece a quarter-turn while building.
- if (k === 'r' && this.buildHud.active && this.buildPiece) {
+ // R rotates the armed prop or composite piece a quarter-turn while building.
+ if (k === 'r' && this.buildHud.active && (this.buildProp || this.buildPiece)) {
e.preventDefault();
- this._rotateBuild();
+ if (this.buildProp) this._rotateProp(); else this._rotateBuild();
return;
}
// E watches the Agent Exchange round when standing near the agents in
@@ -1499,7 +1520,11 @@ export class CoinCommunities {
// single-player (no server) we apply the edit straight to the local voxel layer
// — same result on screen, just not synced or persisted.
_buildAt(clientX, clientY, forceRemove) {
- if (!this.voxels || this.phase !== 'world' || !this._buildableConnection()) return;
+ if (this.phase !== 'world' || !this._buildableConnection()) return;
+ // Prop layer (R18): a click places a free-standing object; right-click / hold
+ // deletes one you own. Routed before the voxel path so the two never collide.
+ if (this.buildProp) { this._buildPropAt(clientX, clientY, forceRemove); return; }
+ if (!this.voxels) return;
const target = this.voxels.raycast(this._pointerRay(clientX, clientY));
if (!target) return;
const removing = forceRemove || this.buildHud.mode === 'remove';
@@ -1674,6 +1699,7 @@ export class CoinCommunities {
// Move the ghost cursor to whatever the pointer aims at, tinted by intent
// (green place / red break / amber blocked).
_updateGhost(clientX, clientY) {
+ if (this.buildProp) { this._updatePropGhost(clientX, clientY); return; }
if (!this.voxels) return;
const target = this.voxels.raycast(this._pointerRay(clientX, clientY));
if (!target) { this.voxels.hideGhost(); this.voxels.hideFootprint(); return; }
@@ -1784,7 +1810,12 @@ export class CoinCommunities {
// The structures toolbar (composite pieces + rotate + share + featured) lives
// or dies with build mode.
this.ui.setBuildToolsVisible(on);
- if (!on) { this.voxels?.hideGhost(); this.voxels?.hideFootprint(); this.canvas.style.cursor = ''; return; }
+ this.ui.setPropPaletteVisible(on);
+ if (!on) {
+ this.voxels?.hideGhost(); this.voxels?.hideFootprint();
+ this.propGhost?.hide(); this.canvas.style.cursor = '';
+ return;
+ }
const touch = typeof matchMedia === 'function' && matchMedia('(hover: none), (pointer: coarse)').matches;
const solo = this.net?.status !== 'online';
const how = touch
@@ -1988,6 +2019,7 @@ export class CoinCommunities {
this.localAnim?.update(dt);
this.localCosmetics?.tick(dt);
for (const [, r] of this.remotes) r.tick(dt);
+ this.worldObjects?.update();
this._updateLabels();
this._updateVoice();
this.playSystems?.tick(dt);
diff --git a/src/game/community-net.js b/src/game/community-net.js
index dea07e3bc..c49fd6580 100644
--- a/src/game/community-net.js
+++ b/src/game/community-net.js
@@ -146,6 +146,13 @@ export class CommunityNet {
vehicleChange: new Set(), // (vehicle, id) — its transform/driver changed
vehicleRemove: new Set(), // (id) — a vehicle left the world
vehicle: new Set(), // ({event, id, ...}) — enter/exit/deny ack for our request
+ // Generic world objects (R01/R02): the shared `objects` channel — balls,
+ // build props, pickups. add/change/remove mirror the player callbacks; the
+ // live schema object is passed through so the manager reads current fields.
+ objectAdd: new Set(), // (obj, id) — an object appeared (spawned or restored)
+ objectChange: new Set(), // (obj, id) — its transform/owner changed
+ objectRemove: new Set(), // (id) — an object left the world
+ objectReject: new Set(), // ({reason}) — server refused a spawn (world/player full)
};
this.ping = null; // smoothed RTT in ms, null until the first echo
this._pingSentAt = 0; // perf-clock stamp of the last move awaiting an echo
@@ -273,6 +280,10 @@ export class CommunityNet {
// Vehicles: the server's targeted reply to our enter/exit request (grant,
// drop point, or denial). World transforms arrive via the state callbacks.
this.room.onMessage('vehicle', (msg) => this._emit('vehicle', msg || {}));
+ // Generic world objects (R01): the server replies here when it refuses a
+ // spawn (the room is full, or we've hit our per-player object cap) so the
+ // build HUD can explain why a placed prop never appeared.
+ this.room.onMessage('obj:reject', (msg) => this._emit('objectReject', msg || {}));
const $ = getStateCallbacks(this.room);
const $state = $(this.room.state);
@@ -328,6 +339,20 @@ export class CommunityNet {
$vehicles.onRemove((_v, id) => this._emit('vehicleRemove', id));
}
+ // Generic world objects (R01): the server is authoritative for every object,
+ // so the scene is driven entirely by these state callbacks — local spawn/
+ // move/remove only *send*; the object appears when the server echoes it back.
+ // onAdd fires for the full persisted set (durable props, R17) at join and for
+ // each new spawn. Optional field (older servers omit it) — guarded like blocks.
+ const $objects = $state?.objects;
+ if ($objects) {
+ $objects.onAdd((obj, id) => {
+ this._emit('objectAdd', obj, id);
+ $(obj).onChange(() => this._emit('objectChange', obj, id));
+ });
+ $objects.onRemove((_o, id) => this._emit('objectRemove', id));
+ }
+
// Durability flag for this world's build (Redis-backed vs memory-only).
// Set once at room creation; listen so the HUD reflects it as soon as the
// first state patch lands and if it ever degrades mid-session.
@@ -471,6 +496,48 @@ export class CommunityNet {
this._lastVSyncAt = now;
this.room.send('vsync', state);
}
+ // Generic world objects (R01/R02). These only *request* the change; the object
+ // appears/moves/disappears when the server echoes its authoritative `objects`
+ // state back (see the objectAdd/Change/Remove wiring above). The server assigns
+ // ownership, mints/clamps ids, and bounds-clamps the transform — the client
+ // never trusts its own optimistic copy. x/y/z must be finite or the server drops
+ // the spawn, so we guard here too and skip a malformed send.
+ spawnObject(kind, opts = {}) {
+ if (!this.room) return;
+ const { x, y, z } = opts;
+ if (![x, y, z].every(Number.isFinite)) return;
+ const msg = { kind: String(kind || ''), x, y, z };
+ if (typeof opts.type === 'string') msg.type = opts.type;
+ if (typeof opts.id === 'string') msg.id = opts.id;
+ if (Number.isFinite(opts.yaw)) msg.yaw = opts.yaw;
+ if (Number.isFinite(opts.scale)) msg.scale = opts.scale;
+ if (Number.isFinite(opts.vx)) msg.vx = opts.vx;
+ if (Number.isFinite(opts.vy)) msg.vy = opts.vy;
+ if (Number.isFinite(opts.vz)) msg.vz = opts.vz;
+ this.room.send('obj:spawn', msg);
+ }
+ updateObject(id, transform = {}) {
+ if (!this.room || typeof id !== 'string') return;
+ const msg = { id };
+ for (const k of ['x', 'y', 'z', 'yaw', 'scale', 'vx', 'vy', 'vz']) {
+ if (Number.isFinite(transform[k])) msg[k] = transform[k];
+ }
+ this.room.send('obj:update', msg);
+ }
+ removeObject(id) {
+ if (!this.room || typeof id !== 'string') return;
+ this.room.send('obj:remove', { id });
+ }
+ // Does an object's server-assigned ownerId belong to THIS client? The server keys
+ // ownership on the verified account when signed in, else the persisted economy id,
+ // else the session id (WalkRoom._ownerKey) — match all three so delete-own works
+ // in gated, un-gated, and guest sessions alike.
+ ownsObject(obj) {
+ const owner = obj?.ownerId;
+ if (!owner) return false;
+ return owner === this.account || owner === this.pid || owner === this.sessionId;
+ }
+
// Adopt a refreshed play pass. Store it so the next reconnect (after a drop)
// uses the fresh credential, AND push it to the live session so the server can
// extend this connection's bound expiry — otherwise the server's per-minute
diff --git a/src/game/world-objects.js b/src/game/world-objects.js
new file mode 100644
index 000000000..bdc0f9e59
--- /dev/null
+++ b/src/game/world-objects.js
@@ -0,0 +1,429 @@
+// world-objects.js — generic networked world-object manager for /play (R02).
+//
+// Mirrors the server's authoritative `objects` MapSchema (R01) into the 3D scene:
+// one Three.js node per object, interpolated smoothly each frame (the same
+// REMOTE_LERP feel as remote avatars), disposed cleanly on remove/teardown.
+//
+// The manager is deliberately FEATURE-AGNOSTIC. It knows nothing about balls,
+// props or pickups — a feature registers a mesh factory for its `kind` via
+// `WorldObjects.registerKind(kind, factory)` and this file just instantiates,
+// lerps and disposes. R18 (build props) registers the 'block'/'prop' factory
+// from PROP_CATALOG below; R05 (the physics ball) registers 'ball' the same way.
+//
+// Wire protocol (R01, see multiplayer/src/rooms/WalkRoom.js):
+// obj:spawn { id?, type?, kind?, x, y, z, yaw?, scale?, vx?, vy?, vz? }
+// obj:update { id, x?, y?, z?, yaw?, scale?, vx?, vy?, vz? }
+// obj:remove { id }
+// The server assigns ownerId, clamps bounds/scale, mints ids and persists durable
+// props; the client only sends intents and renders what the state echoes back.
+
+import {
+ Group, Vector3, Box3,
+ Mesh, BoxGeometry, CylinderGeometry, ConeGeometry, SphereGeometry,
+ MeshStandardMaterial, MeshBasicMaterial,
+ EdgesGeometry, LineSegments, LineBasicMaterial, Color,
+} from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { log } from '../shared/log.js';
+
+// Same lerp constant RemotePlayer uses, so objects glide between server updates
+// with exactly the same feel as the avatars around them.
+const REMOTE_LERP = 0.18;
+const YAW_LERP = 0.25;
+
+// ── kind registry ──────────────────────────────────────────────────────────
+// kind → factory(obj) ⇒ Object3D. A feature owns its factory; the manager owns
+// the lifecycle. Unknown kinds fall back to a neutral box so an object always
+// renders something real rather than vanishing.
+const KIND_FACTORIES = new Map();
+
+function neutralBox() {
+ const m = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial({ color: 0x8b93a7, roughness: 0.85 }));
+ m.castShadow = true; m.receiveShadow = true;
+ m.position.y = 0.5; // base at origin
+ m.userData.ownGeo = true;
+ return m;
+}
+
+// ── prop catalog (R18) ───────────────────────────────────────────────────────
+// The placeable build palette: procedural primitives built from real three.js
+// geometry (no external asset, no async) plus a couple of real GLB props reused
+// from the club set. Every prop is authored with its BASE at the origin (y=0) so
+// a placement snaps flush onto the ground. `foot` is the half-extent (metres)
+// used for the snap grid and the GLB ghost proxy; `glb` props load + clone a
+// shared template. Order is the palette order.
+export const PROP_CATALOG = [
+ { id: 'crate', name: 'Crate', icon: '📦', foot: 0.75, build: () => propCrate() },
+ { id: 'barrel', name: 'Barrel', icon: '🛢️', foot: 0.55, build: () => propBarrel() },
+ { id: 'planter', name: 'Planter', icon: '🪴', foot: 0.6, build: () => propPlanter() },
+ { id: 'lamp', name: 'Lamp', icon: '💡', foot: 0.35, build: () => propLamp() },
+ { id: 'bench', name: 'Bench', icon: '🪑', foot: 1.0, build: () => propBench() },
+ { id: 'pillar', name: 'Pillar', icon: '🏛️', foot: 0.5, build: () => propPillar() },
+ { id: 'arch', name: 'Arch', icon: '🚪', foot: 1.1, build: () => propArch() },
+ { id: 'ramp', name: 'Ramp', icon: '📐', foot: 1.0, build: () => propRamp() },
+ { id: 'sign', name: 'Sign', icon: '🪧', foot: 0.6, build: () => propSign() },
+ { id: 'crystal', name: 'Crystal', icon: '🔮', foot: 0.5, build: () => propCrystal() },
+ { id: 'stage', name: 'Stage', icon: '🎤', foot: 1.6, glb: '/club/props/stage.glb', fitH: 1.1 },
+ { id: 'pole', name: 'Pole', icon: '🎚️', foot: 0.35, glb: '/club/props/pole.glb', fitH: 3.0 },
+];
+const PROP_BY_ID = new Map(PROP_CATALOG.map((p) => [p.id, p]));
+export function propDef(type) { return PROP_BY_ID.get(type) || null; }
+export const DEFAULT_PROP = PROP_CATALOG[0].id;
+
+// ── procedural prop builders (base at y=0) ───────────────────────────────────
+function std(color, opts = {}) {
+ const m = new MeshStandardMaterial({ color, roughness: opts.roughness ?? 0.85, metalness: opts.metalness ?? 0 });
+ if (opts.emissive !== undefined) { m.emissive = new Color(opts.emissive); m.emissiveIntensity = opts.emissiveIntensity ?? 0.6; }
+ return m;
+}
+// Build a mesh with its geometry shifted so `baseY` (default the box's bottom)
+// rests on y=0, tag it for shadows + disposal, and return it.
+function part(geometry, material, y = 0) {
+ const m = new Mesh(geometry, material);
+ m.position.y = y;
+ m.castShadow = true; m.receiveShadow = true;
+ m.userData.ownGeo = true;
+ return m;
+}
+function groupOf(...parts) {
+ const g = new Group();
+ for (const p of parts) g.add(p);
+ return g;
+}
+
+function propCrate() {
+ const body = part(new BoxGeometry(1.4, 1.4, 1.4), std(0xb07f43, { roughness: 0.9 }), 0.7);
+ const trim = part(new BoxGeometry(1.45, 0.16, 1.45), std(0x7a5226), 1.42);
+ return groupOf(body, trim);
+}
+function propBarrel() {
+ const body = part(new CylinderGeometry(0.52, 0.52, 1.2, 18), std(0x9a6a3c), 0.6);
+ const band1 = part(new CylinderGeometry(0.55, 0.55, 0.1, 18), std(0x53381f), 0.32);
+ const band2 = part(new CylinderGeometry(0.55, 0.55, 0.1, 18), std(0x53381f), 0.88);
+ return groupOf(body, band1, band2);
+}
+function propPlanter() {
+ const pot = part(new CylinderGeometry(0.55, 0.42, 0.6, 16), std(0x8a5a36), 0.3);
+ const soil = part(new CylinderGeometry(0.5, 0.5, 0.08, 16), std(0x2e1f12), 0.6);
+ const bush = part(new SphereGeometry(0.55, 14, 12), std(0x4f9a45, { roughness: 1 }), 1.05);
+ return groupOf(pot, soil, bush);
+}
+function propLamp() {
+ const base = part(new CylinderGeometry(0.28, 0.32, 0.18, 16), std(0x2b2f38, { metalness: 0.4, roughness: 0.5 }), 0.09);
+ const post = part(new CylinderGeometry(0.07, 0.08, 2.6, 12), std(0x33373f, { metalness: 0.5, roughness: 0.4 }), 1.4);
+ const head = part(new SphereGeometry(0.26, 16, 14), std(0xffe7a8, { emissive: 0xffcf5c, emissiveIntensity: 1.1 }), 2.7);
+ return groupOf(base, post, head);
+}
+function propBench() {
+ const seat = part(new BoxGeometry(2.0, 0.14, 0.6), std(0xb07f43), 0.55);
+ const back = part(new BoxGeometry(2.0, 0.5, 0.12), std(0xb07f43), 0.85);
+ const l1 = part(new BoxGeometry(0.14, 0.55, 0.55), std(0x4a4f59, { metalness: 0.4 }), 0.28);
+ const l2 = l1.clone(); l2.position.x = 0.85; l1.position.x = -0.85;
+ l2.userData.ownGeo = false; // clone shares l1's geometry/material — dispose once
+ return groupOf(seat, back, l1, l2);
+}
+function propPillar() {
+ const base = part(new BoxGeometry(1.0, 0.2, 1.0), std(0xcfd3da), 0.1);
+ const shaft = part(new CylinderGeometry(0.34, 0.4, 2.6, 20), std(0xe2e5ea, { roughness: 0.7 }), 1.5);
+ const cap = part(new BoxGeometry(0.95, 0.2, 0.95), std(0xcfd3da), 2.9);
+ return groupOf(base, shaft, cap);
+}
+function propArch() {
+ const left = part(new BoxGeometry(0.4, 2.6, 0.5), std(0xb5483a), 1.3); left.position.x = -1.0;
+ const right = left.clone(); right.position.x = 1.0; right.userData.ownGeo = false;
+ const top = part(new BoxGeometry(2.4, 0.45, 0.5), std(0xb5483a), 2.82);
+ return groupOf(left, right, top);
+}
+function propRamp() {
+ const m = part(new BoxGeometry(1.8, 0.16, 1.8), std(0x9aa0a8), 0); // pivot handled below
+ // Tilt the slab into a ramp and lift it so the low edge meets the ground.
+ m.rotation.x = -Math.PI / 9;
+ m.position.y = 0.45;
+ return groupOf(m);
+}
+function propSign() {
+ const post = part(new CylinderGeometry(0.08, 0.08, 2.0, 10), std(0x6b4a2c), 1.0);
+ const board = part(new BoxGeometry(1.1, 0.7, 0.1), std(0xf0e6cf, { roughness: 0.8 }), 1.7);
+ const arrow = part(new ConeGeometry(0.18, 0.3, 4), std(0x2af0e0, { emissive: 0x2af0e0, emissiveIntensity: 0.7 }), 1.7);
+ arrow.rotation.z = -Math.PI / 2; arrow.position.x = 0.7;
+ return groupOf(post, board, arrow);
+}
+function propCrystal() {
+ const c = part(new ConeGeometry(0.45, 1.6, 6), std(0x9ad8ff, { emissive: 0x2af0e0, emissiveIntensity: 0.9, roughness: 0.2, metalness: 0.1 }), 0.8);
+ const c2 = part(new ConeGeometry(0.22, 0.9, 6), std(0x9ad8ff, { emissive: 0x2af0e0, emissiveIntensity: 0.9, roughness: 0.2 }), 0.45);
+ c2.position.set(0.4, 0, 0.2);
+ return groupOf(c, c2);
+}
+
+// ── GLB template cache (shared geometry/materials across instances) ──────────
+const _gltf = new GLTFLoader();
+const _glbCache = new Map(); // url → { template, waiters:[] }
+
+function loadTemplate(url) {
+ let rec = _glbCache.get(url);
+ if (rec) return rec;
+ rec = { template: null, waiters: [] };
+ _glbCache.set(url, rec);
+ _gltf.load(url, (gltf) => {
+ const root = gltf.scene;
+ root.traverse((o) => { if (o.isMesh) { o.castShadow = true; o.receiveShadow = true; } });
+ rec.template = root;
+ for (const w of rec.waiters.splice(0)) { try { w(root); } catch (e) { log.warn('[world-objects] glb waiter threw', e); } }
+ }, undefined, (err) => log.warn('[world-objects] GLB load failed', url, err?.message || err));
+ return rec;
+}
+
+// Fit a node so it stands `fitH` metres tall with its base on y=0 and centred in
+// xz — GLB authoring varies wildly, so normalise every prop to a predictable size.
+function fitNode(node, fitH) {
+ const box = new Box3().setFromObject(node);
+ if (!box.isEmpty()) {
+ const size = box.getSize(new Vector3());
+ const s = size.y > 1e-4 ? fitH / size.y : 1;
+ node.scale.setScalar(s);
+ const box2 = new Box3().setFromObject(node);
+ const c = box2.getCenter(new Vector3());
+ node.position.x -= c.x;
+ node.position.z -= c.z;
+ node.position.y -= box2.min.y;
+ }
+ return node;
+}
+
+// Instance a GLB prop into `holder`. Shares the template's geometry/materials via
+// clone(true), so the meshes are tagged shared (never disposed — they belong to
+// the cached template). If the template is still loading, attaches when it lands.
+function instanceGLB(def, holder) {
+ const place = (tpl) => {
+ const inst = tpl.clone(true);
+ fitNode(inst, def.fitH || 1.5);
+ inst.traverse((o) => { o.userData.shared = true; });
+ holder.add(inst);
+ };
+ const rec = loadTemplate(def.glb);
+ if (rec.template) place(rec.template);
+ else rec.waiters.push(place);
+}
+
+// Build the scene node for a prop `type` (the catalog id). Procedural props are
+// synchronous; GLB props attach a placeholder-free holder that populates on load.
+function buildProp(type) {
+ const def = propDef(type);
+ if (!def) return neutralBox();
+ if (def.build) return def.build();
+ const holder = new Group();
+ instanceGLB(def, holder);
+ return holder;
+}
+
+// Register the build-prop factory for the durable kinds R18 places. Both 'block'
+// and 'prop' persist server-side (R17); the factory reads obj.type to pick the
+// catalog entry, so one factory covers the whole palette.
+function buildPropFactory(obj) { return buildProp(obj.type); }
+KIND_FACTORIES.set('block', buildPropFactory);
+KIND_FACTORIES.set('prop', buildPropFactory);
+
+// Recursively dispose a node's owned resources. GLB-clone meshes (userData.shared)
+// share the cached template's geometry/materials and are skipped; procedural
+// meshes (userData.ownGeo) own theirs and are freed.
+function disposeNode(node) {
+ node.traverse((o) => {
+ if (!o.isMesh) return;
+ if (o.userData.shared || o.userData.ownGeo === false) return;
+ o.geometry?.dispose?.();
+ const mat = o.material;
+ if (Array.isArray(mat)) mat.forEach((m) => m?.dispose?.());
+ else mat?.dispose?.();
+ });
+}
+
+// ── manager ──────────────────────────────────────────────────────────────────
+export class WorldObjects {
+ static registerKind(kind, factory) { KIND_FACTORIES.set(kind, factory); }
+
+ /**
+ * @param {THREE.Scene} scene
+ * @param {import('./community-net.js').CommunityNet} net
+ * @param {object} [opts]
+ * @param {(obj)=>boolean} [opts.isMine] does this client own the object? (delete-own)
+ */
+ constructor(scene, net, opts = {}) {
+ this.scene = scene;
+ this.net = net;
+ this._isMine = typeof opts.isMine === 'function' ? opts.isMine : () => false;
+ this.entries = new Map(); // id → { node, tx,ty,tz,tyaw,tscale, ownerId, kind, type, mine }
+ this._offs = [
+ net.on('objectAdd', (obj, id) => this._add(obj, id)),
+ net.on('objectChange', (obj, id) => this._change(obj, id)),
+ net.on('objectRemove', (id) => this._remove(id)),
+ ];
+ }
+
+ get count() { return this.entries.size; }
+ ownedCount() { let n = 0; for (const e of this.entries.values()) if (e.mine) n++; return n; }
+
+ _factory(kind) { return KIND_FACTORIES.get(kind) || neutralBox; }
+
+ _add(obj, id) {
+ if (this.entries.has(id)) { this._change(obj, id); return; }
+ const holder = new Group();
+ holder.name = `wo:${id}`;
+ let node;
+ try { node = this._factory(obj.kind)(obj) || neutralBox(); }
+ catch (e) { log.warn('[world-objects] factory threw for kind', obj.kind, e); node = neutralBox(); }
+ holder.add(node);
+ const mine = !!this._isMine(obj);
+ // Tag the whole subtree so a raycast hit maps back to this object's id/owner.
+ holder.traverse((o) => { o.userData.objId = id; o.userData.objOwner = obj.ownerId; });
+ holder.position.set(obj.x, obj.y, obj.z);
+ holder.rotation.y = obj.yaw || 0;
+ const scale = obj.scale || 1;
+ holder.scale.setScalar(scale);
+ this.scene.add(holder);
+ this.entries.set(id, {
+ node: holder,
+ tx: obj.x, ty: obj.y, tz: obj.z, tyaw: obj.yaw || 0, tscale: scale,
+ ownerId: obj.ownerId, kind: obj.kind, type: obj.type, mine,
+ });
+ }
+
+ _change(obj, id) {
+ const e = this.entries.get(id);
+ if (!e) { this._add(obj, id); return; }
+ e.tx = obj.x; e.ty = obj.y; e.tz = obj.z; e.tyaw = obj.yaw || 0; e.tscale = obj.scale || 1;
+ if (obj.ownerId !== e.ownerId) {
+ e.ownerId = obj.ownerId;
+ e.mine = !!this._isMine(obj);
+ e.node.traverse((o) => { o.userData.objOwner = obj.ownerId; });
+ }
+ }
+
+ _remove(id) {
+ const e = this.entries.get(id);
+ if (!e) return;
+ this.scene.remove(e.node);
+ disposeNode(e.node);
+ this.entries.delete(id);
+ }
+
+ // Frame interpolation — same fixed-factor glide as RemotePlayer (dt unused, the
+ // factor is tuned for the ~60fps render loop and the server's update cadence).
+ update() {
+ for (const e of this.entries.values()) {
+ const n = e.node;
+ n.position.x += (e.tx - n.position.x) * REMOTE_LERP;
+ n.position.y += (e.ty - n.position.y) * REMOTE_LERP;
+ n.position.z += (e.tz - n.position.z) * REMOTE_LERP;
+ let d = e.tyaw - n.rotation.y;
+ while (d > Math.PI) d -= Math.PI * 2;
+ while (d < -Math.PI) d += Math.PI * 2;
+ n.rotation.y += d * YAW_LERP;
+ const s = n.scale.x + (e.tscale - n.scale.x) * REMOTE_LERP;
+ n.scale.setScalar(s);
+ }
+ }
+
+ // Scene nodes of objects THIS client owns — the only ones delete-own may target
+ // (full server-side ownership is enforced in R19; this is the client-side offer).
+ ownedNodes(out = []) {
+ out.length = 0;
+ for (const e of this.entries.values()) if (e.mine) out.push(e.node);
+ return out;
+ }
+
+ // Resolve a raycast hit object back to its world-object id (walks up to the
+ // tagged subtree root), or null if the hit isn't one of our objects.
+ idForHit(object) {
+ let o = object;
+ while (o) { if (o.userData && o.userData.objId) return o.userData.objId; o = o.parent; }
+ return null;
+ }
+
+ dispose() {
+ for (const off of this._offs) { try { off(); } catch { /* already detached */ } }
+ this._offs = [];
+ for (const e of this.entries.values()) { this.scene.remove(e.node); disposeNode(e.node); }
+ this.entries.clear();
+ }
+}
+
+// ── prop placement ghost (R18) ───────────────────────────────────────────────
+// A translucent preview of the selected prop at the snapped placement pose, tinted
+// green (valid) or red (blocked). Procedural props ghost full-fidelity; GLB props
+// ghost as a translucent footprint box (sized from the catalog) so the preview is
+// always immediate and never waits on an async load mid-aim.
+const GHOST_GOOD = 0x66ff8c;
+const GHOST_BAD = 0xff5a5a;
+
+export class PropGhost {
+ constructor(scene) {
+ this.scene = scene;
+ this.group = new Group();
+ this.group.visible = false;
+ scene.add(this.group);
+ this._type = null;
+ this._valid = true;
+ this._fill = new MeshBasicMaterial({ color: GHOST_GOOD, transparent: true, opacity: 0.34, depthWrite: false });
+ this._lineMat = new LineBasicMaterial({ color: GHOST_GOOD, transparent: true, opacity: 0.95 });
+ }
+
+ setType(type) {
+ if (type === this._type) return;
+ this._type = type;
+ this._clearChildren();
+ if (!type) { this.hide(); return; }
+ const def = propDef(type);
+ if (def && def.build) {
+ // Full-fidelity translucent clone of the procedural prop.
+ const node = def.build();
+ node.traverse((o) => { if (o.isMesh) o.material = this._fill; });
+ this.group.add(node);
+ } else if (def) {
+ // GLB prop → a translucent footprint box + wire outline, sized from `foot`.
+ const f = def.foot || 0.6;
+ const h = def.fitH || 1.5;
+ const geo = new BoxGeometry(f * 2, h, f * 2);
+ const box = new Mesh(geo, this._fill);
+ box.position.y = h / 2;
+ box.userData.ownGeo = true;
+ const edges = new LineSegments(new EdgesGeometry(geo), this._lineMat);
+ edges.position.y = h / 2;
+ edges.userData.ownGeo = true;
+ this.group.add(box, edges);
+ }
+ }
+
+ setPose(x, y, z, yaw, scale = 1) {
+ this.group.position.set(x, y, z);
+ this.group.rotation.y = yaw;
+ this.group.scale.setScalar(scale);
+ }
+
+ setValid(valid) {
+ if (valid === this._valid) return;
+ this._valid = valid;
+ const hex = valid ? GHOST_GOOD : GHOST_BAD;
+ this._fill.color.setHex(hex);
+ this._lineMat.color.setHex(hex);
+ }
+
+ show() { this.group.visible = true; }
+ hide() { this.group.visible = false; }
+
+ _clearChildren() {
+ for (const child of this.group.children.slice()) {
+ this.group.remove(child);
+ child.traverse?.((o) => {
+ if (o.isMesh && o.userData.ownGeo) o.geometry?.dispose?.();
+ if (o.isLineSegments && o.userData.ownGeo) o.geometry?.dispose?.();
+ });
+ }
+ }
+
+ dispose() {
+ this._clearChildren();
+ this.scene.remove(this.group);
+ this._fill.dispose();
+ this._lineMat.dispose();
+ }
+}
diff --git a/tests/cosmetics-economy.test.js b/tests/cosmetics-economy.test.js
new file mode 100644
index 000000000..bfe68edbc
--- /dev/null
+++ b/tests/cosmetics-economy.test.js
@@ -0,0 +1,187 @@
+// Coverage for the R25 cosmetic creator-revenue-split economy
+// (api/_lib/cosmetics-economy.js):
+//
+// • split config: clamp to the platform ceiling + the exact signed message
+// • recordSaleAndSplit: the creator-cut math, idempotency on (account,cosmetic),
+// the REAL on-chain payout call, and fail-open behaviour when untied
+// • setSplitConfig: signature-gated, creator-only authorization
+// • leaderboard: rarity-weighted scarcity ordering
+//
+// The Neon `sql` tag, the Solana USDC transfer, and the ed25519 verify are mocked
+// so the money path is exercised deterministically without a DB or a funded wallet
+// (the on-chain transfer itself is verified against the real rail on deploy).
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// ── mocks ────────────────────────────────────────────────────────────────────
+
+// A tiny tagged-template `sql` stand-in: tests push handlers that return rows. FIFO.
+const sqlCalls = [];
+let sqlHandlers = [];
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (strings, ...values) => {
+ const text = strings.join('?').replace(/\s+/g, ' ').trim();
+ sqlCalls.push({ text, values });
+ const h = sqlHandlers.shift();
+ return Promise.resolve(h ? h(text, values) : []);
+ },
+}));
+
+const transferMock = vi.fn();
+vi.mock('../api/_lib/solana-transfer.js', () => ({
+ transferSolanaUSDC: (...args) => transferMock(...args),
+}));
+
+let sigValid = true;
+vi.mock('../api/_lib/siws.js', () => ({ verifySiwsSignature: () => sigValid }));
+
+// Coin lookup miss by default so config falls through to the explicit override path.
+vi.mock('../api/_lib/coin/index.js', () => ({ loadCoinByMint: async () => null }));
+
+// Neutralize the on-chain pump.fun creator fallback so resolution is deterministic
+// (no live RPC): an account-info miss makes resolveOnchainPumpCreator return null.
+vi.mock('../api/_lib/pump.js', () => ({
+ getConnection: () => ({ getAccountInfo: async () => null }),
+}));
+
+const {
+ clampCreatorBps, splitConfigMessage, recordSaleAndSplit, setSplitConfig,
+ cosmeticsLeaderboard, MAX_CREATOR_BPS, DEFAULT_CREATOR_BPS,
+} = await import('../api/_lib/cosmetics-economy.js');
+
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const CREATOR = 'WwW9dwK7iY5cT9aZ8h6n3v2Q1rT4uYpL5mN6oP7qR8s';
+const BUYER = '8h6n3v2Q1rT4uYpL5mN6oP7qR8sWwW9dwK7iY5cT9aZ';
+
+beforeEach(() => {
+ sqlCalls.length = 0;
+ sqlHandlers = [];
+ transferMock.mockReset();
+ sigValid = true;
+ process.env.DATABASE_URL = 'postgres://test';
+ process.env.COSMETIC_SPLIT_TREASURY_SECRET_KEY_B64 = Buffer.alloc(64, 7).toString('base64');
+});
+
+describe('split config bounds + message', () => {
+ it('clamps the creator share to the platform ceiling', () => {
+ expect(clampCreatorBps(99999)).toBe(MAX_CREATOR_BPS);
+ expect(clampCreatorBps(-5)).toBe(0);
+ expect(clampCreatorBps(3000)).toBe(3000);
+ expect(clampCreatorBps('nope')).toBe(DEFAULT_CREATOR_BPS);
+ });
+
+ it('binds the signed message to the mint + bps + timestamp', () => {
+ const msg = splitConfigMessage({ mint: MINT, bps: 5000, ts: 1700000000 });
+ expect(msg).toContain(MINT);
+ expect(msg).toContain('5000 bps');
+ expect(msg).toContain('1700000000');
+ });
+});
+
+describe('recordSaleAndSplit — creator cut + payout', () => {
+ it('computes the creator cut, records it, and pays out on-chain', async () => {
+ sqlHandlers.push(() => [{ mint: MINT, creator_wallet: CREATOR, split_bps: 6000, updated_at: null }]); // getSplitConfig
+ sqlHandlers.push(() => [{ id: 'sale-1' }]); // insert sale
+ sqlHandlers.push(() => []); // markPayout update
+ transferMock.mockResolvedValue('payout-sig-123');
+
+ const out = await recordSaleAndSplit({
+ account: BUYER, cosmeticId: 'skin-midnight', payerWallet: BUYER,
+ payerNetwork: 'solana', asset: 'USDC', priceAtomics: '3000000', mint: MINT,
+ });
+
+ expect(out.recorded).toBe(true);
+ expect(out.creatorWallet).toBe(CREATOR);
+ expect(out.creatorBps).toBe(6000);
+ expect(out.creatorCutAtomics).toBe('1800000'); // 60% of 3,000,000
+ expect(out.payoutStatus).toBe('paid');
+ expect(out.payoutTx).toBe('payout-sig-123');
+ expect(transferMock).toHaveBeenCalledTimes(1);
+ const arg = transferMock.mock.calls[0][0];
+ expect(arg.toAddress).toBe(CREATOR);
+ expect(String(arg.amount)).toBe('1800000');
+ });
+
+ it('is idempotent: a conflicting (already-recorded) sale never re-pays', async () => {
+ sqlHandlers.push(() => [{ mint: MINT, creator_wallet: CREATOR, split_bps: 5000, updated_at: null }]);
+ sqlHandlers.push(() => []); // insert → conflict, no row returned
+ const out = await recordSaleAndSplit({
+ account: BUYER, cosmeticId: 'skin-midnight', payerWallet: BUYER,
+ payerNetwork: 'solana', asset: 'USDC', priceAtomics: '3000000', mint: MINT,
+ });
+ expect(out).toEqual({ recorded: true, alreadyRecorded: true });
+ expect(transferMock).not.toHaveBeenCalled();
+ });
+
+ it('records an untied sale (no coin) with no creator leg or payout', async () => {
+ sqlHandlers.push(() => [{ id: 'sale-2' }]); // insert only
+ const out = await recordSaleAndSplit({
+ account: BUYER, cosmeticId: 'skin-midnight', payerWallet: BUYER,
+ payerNetwork: 'base', asset: 'USDC', priceAtomics: '3000000', mint: null,
+ });
+ expect(out.recorded).toBe(true);
+ expect(out.creatorWallet).toBeNull();
+ expect(transferMock).not.toHaveBeenCalled();
+ });
+
+ it('never pays a creator out of their own purchase', async () => {
+ sqlHandlers.push(() => [{ mint: MINT, creator_wallet: CREATOR, split_bps: 5000, updated_at: null }]);
+ sqlHandlers.push(() => [{ id: 'sale-3' }]);
+ const out = await recordSaleAndSplit({
+ account: CREATOR, cosmeticId: 'skin-midnight', payerWallet: CREATOR,
+ payerNetwork: 'solana', asset: 'USDC', priceAtomics: '3000000', mint: MINT,
+ });
+ expect(out.creatorWallet).toBeNull();
+ expect(transferMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('setSplitConfig — authorization', () => {
+ it('rejects when no creator can be established for the coin', async () => {
+ sqlHandlers.push(() => []); // resolveCreatorWallet: config miss
+ sqlHandlers.push(() => []); // agent_identities miss (coin/index + pump mocked empty)
+ await expect(setSplitConfig({
+ mint: MINT, bps: 4000, ts: Math.floor(Date.now() / 1000), signature: 'sig', signer: BUYER,
+ })).rejects.toMatchObject({ code: 'no_creator' });
+ });
+
+ it('accepts a valid signature from the creator and upserts the share', async () => {
+ sqlHandlers.push(() => [{ creator_wallet: CREATOR }]); // resolveCreatorWallet → config override
+ sqlHandlers.push(() => []); // upsert
+ sqlHandlers.push(() => [{ mint: MINT, creator_wallet: CREATOR, split_bps: 4000, updated_at: new Date().toISOString() }]); // read-back
+ sigValid = true;
+ const cfg = await setSplitConfig({
+ mint: MINT, bps: 4000, ts: Math.floor(Date.now() / 1000), signature: 'good', signer: CREATOR,
+ });
+ expect(cfg.splitBps).toBe(4000);
+ expect(cfg.creatorWallet).toBe(CREATOR);
+ });
+
+ it('rejects a bad signature', async () => {
+ sqlHandlers.push(() => [{ creator_wallet: CREATOR }]); // resolve → creator
+ sigValid = false;
+ await expect(setSplitConfig({
+ mint: MINT, bps: 4000, ts: Math.floor(Date.now() / 1000), signature: 'bad', signer: CREATOR,
+ })).rejects.toMatchObject({ code: 'bad_signature' });
+ });
+});
+
+describe('cosmeticsLeaderboard — rarest fits ordering', () => {
+ it('ranks scarcer fits first and tallies flex scores', async () => {
+ sqlHandlers.push(() => [
+ { cosmetic_id: 'skin-midnight', account: BUYER, any_mint: MINT }, // legendary, 1 owner
+ { cosmetic_id: 'skin-crimson', account: BUYER, any_mint: MINT }, // rare
+ { cosmetic_id: 'skin-crimson', account: CREATOR, any_mint: MINT }, // rare, 2 owners total
+ ]);
+ sqlHandlers.push(() => []); // topCreators
+ sqlHandlers.push(() => []); // recent
+ const board = await cosmeticsLeaderboard({ limit: 12 });
+ expect(board.rarestFits[0].cosmeticId).toBe('skin-midnight');
+ expect(board.rarestFits[0].owners).toBe(1);
+ expect(board.rarestFits[1].cosmeticId).toBe('skin-crimson');
+ expect(board.rarestFits[1].owners).toBe(2);
+ const top = board.topCollectors.find((c) => c.account === BUYER);
+ expect(top.flexScore).toBe(44); // legendary(40) + rare(4)
+ expect(top.fits).toBe(2);
+ });
+});