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: add clash API with viewer framing updates
nirholas45b48145a250
diff --git a/api/_lib/clash-store.js b/api/_lib/clash-store.jsnew file mode 100644index 000000000..6253df164--- /dev/null+++ b/api/_lib/clash-store.js@@ -0,0 +1,286 @@+// Coin Clash — persistence.+//+// Battle power is hot, concurrent, and additive: many soldiers across many+// serverless instances tap for the same faction at once. That needs atomic+// increments and ranked reads, so this layer talks to Upstash Redis directly+// (ZINCRBY for faction + member tallies, INCRBY for the per-wallet cap) rather+// than the JSON get/set cache. When Redis is unconfigured — local dev, tests —+// it transparently falls back to an in-process model with the same semantics so+// the game is fully playable on a laptop with no infra.+//+// Keys are namespaced by round (epoch) and expire a few rounds out, so the store+// self-prunes without a sweeper.++import { getRedis } from './redis.js';+import { EPOCH_MS } from './clash.js';++const redis = getRedis();++// Keep finished rounds around briefly for settlement + "last round" display,+// then let them lapse. Records (all-time W/L) never expire.+const ROUND_TTL_S = Math.ceil((EPOCH_MS * 4) / 1000);++const K = {+ factions: (epoch) => `clash:fac:${epoch}`, // ZSET mint → power+ members: (epoch, mint) => `clash:mem:${epoch}:${mint}`, // ZSET wallet → power+ wallet: (epoch, mint, wallet) => `clash:w:${epoch}:${mint}:${wallet}`, // INT cap counter+ momentum: (mint) => `clash:mom:${mint}`, // JSON cached factor+ settled: (epoch) => `clash:settled:${epoch}`, // marker+ record: 'clash:record', // HASH mint → JSON {w,l,battles,power}+};++// ─── In-memory fallback (dev/tests) ──────────────────────────────────────────+const mem = {+ z: new Map(), // key → Map(member → score)+ s: new Map(), // key → { value, exp }+ h: new Map(), // hash key → Map(field → value)+};+function memZ(key) {+ let m = mem.z.get(key);+ if (!m) {+ m = new Map();+ mem.z.set(key, m);+ }+ return m;+}+function memValid(key) {+ const e = mem.s.get(key);+ if (!e) return undefined;+ if (e.exp && Date.now() > e.exp) {+ mem.s.delete(key);+ return undefined;+ }+ return e.value;+}++// ─── Power: faction + member tallies, per-wallet cap ─────────────────────────++/**+ * Atomically add power to a faction and the soldier's standing within it, unless+ * the soldier has already hit their per-round ceiling. Returns the soldier's new+ * cumulative power for the round and whether the cap was reached.+ *+ * @returns {Promise<{ added: number, walletTotal: number, capped: boolean }>}+ */+export async function addPower({ epoch, mint, wallet, amount, walletCap }) {+ const amt = Math.max(0, Math.floor(Number(amount) || 0));+ if (amt <= 0) return { added: 0, walletTotal: 0, capped: false };++ if (redis) {+ const wKey = K.wallet(epoch, mint, wallet);+ // Reserve against the per-wallet ceiling first. INCRBY returns the running+ // total; if this push would breach the cap, clamp the credited amount to+ // whatever headroom remains (possibly zero) and roll the counter back to the+ // cap so it stays truthful.+ const after = await redis.incrby(wKey, amt);+ await redis.expire(wKey, ROUND_TTL_S);+ let credit = amt;+ let capped = false;+ if (after > walletCap) {+ credit = Math.max(0, amt - (after - walletCap));+ capped = true;+ if (credit !== amt) await redis.set(wKey, walletCap, { ex: ROUND_TTL_S });+ }+ if (credit > 0) {+ await redis.zincrby(K.factions(epoch), credit, mint);+ await redis.expire(K.factions(epoch), ROUND_TTL_S);+ await redis.zincrby(K.members(epoch, mint), credit, wallet);+ await redis.expire(K.members(epoch, mint), ROUND_TTL_S);+ }+ return { added: credit, walletTotal: Math.min(after, walletCap), capped };+ }++ // In-memory+ const wKey = K.wallet(epoch, mint, wallet);+ const prev = Number(memValid(wKey) || 0);+ const after = prev + amt;+ let credit = amt;+ let capped = false;+ if (after > walletCap) {+ credit = Math.max(0, walletCap - prev);+ capped = true;+ }+ mem.s.set(wKey, { value: prev + credit, exp: Date.now() + ROUND_TTL_S * 1000 });+ if (credit > 0) {+ const fz = memZ(K.factions(epoch));+ fz.set(mint, (fz.get(mint) || 0) + credit);+ const mz = memZ(K.members(epoch, mint));+ mz.set(wallet, (mz.get(wallet) || 0) + credit);+ }+ return { added: credit, walletTotal: prev + credit, capped };+}++/** A soldier's power so far this round for one faction. */+export async function walletPower({ epoch, mint, wallet }) {+ if (redis) return Number((await redis.get(K.wallet(epoch, mint, wallet))) || 0);+ return Number(memValid(K.wallet(epoch, mint, wallet)) || 0);+}++/** Faction → power map for a round. */+export async function factionPowers(epoch) {+ if (redis) {+ const flat = await redis.zrange(K.factions(epoch), 0, -1, { withScores: true });+ return zflatToMap(flat);+ }+ const out = {};+ for (const [k, v] of memZ(K.factions(epoch))) out[k] = Number(v) || 0;+ return out;+}++/** Top soldiers for a faction this round: [{ wallet, power }] descending. */+export async function topSoldiers({ epoch, mint, limit = 10 }) {+ if (redis) {+ const flat = await redis.zrange(K.members(epoch, mint), 0, limit - 1, {+ rev: true,+ withScores: true,+ });+ return zflatToList(flat);+ }+ const m = memZ(K.members(epoch, mint));+ return [...m.entries()]+ .map(([wallet, power]) => ({ wallet, power: Number(power) || 0 }))+ .sort((a, b) => b.power - a.power)+ .slice(0, limit);+}++// ─── Momentum cache ──────────────────────────────────────────────────────────++export async function getMomentum(mint) {+ if (redis) {+ const v = await redis.get(K.momentum(mint));+ const n = Number(v);+ return Number.isFinite(n) && n > 0 ? n : null;+ }+ const v = memValid(K.momentum(mint));+ return v == null ? null : Number(v);+}+export async function setMomentum(mint, factor, ttlS = 120) {+ if (redis) return void (await redis.set(K.momentum(mint), factor, { ex: ttlS }));+ mem.s.set(K.momentum(mint), { value: factor, exp: Date.now() + ttlS * 1000 });+}++// ─── All-time war record + lazy settlement ───────────────────────────────────++/** All-time records for a set of mints: mint → { w, l, battles, power }. */+export async function getRecords(mints = []) {+ const out = {};+ if (!mints.length) return out;+ if (redis) {+ const raw = await redis.hmget(K.record, ...mints);+ mints.forEach((mint, i) => {+ out[mint] = parseRecord(raw?.[i]);+ });+ return out;+ }+ const h = mem.h.get(K.record) || new Map();+ for (const mint of mints) out[mint] = parseRecord(h.get(mint));+ return out;+}++/**+ * Settle a finished round exactly once. Re-reads the round's faction powers,+ * recomputes the same deterministic bracket, decides each battle on raw power+ * (effort wins, not market cap), and folds win/loss/power into the all-time+ * record. A round marker makes this idempotent across concurrent readers.+ *+ * @param {number} epoch finished round to settle+ * @param {(mints: string[], epoch: number) => { battles: Array<{a:string,b:string|null}> }} matchmakeFn+ * @returns {Promise<{ settled: boolean, results?: Array<object> }>}+ */+export async function settleRound(epoch, matchmakeFn) {+ // Claim the settlement so two concurrent readers don't double-count.+ const claimed = await claimSettle(epoch);+ if (!claimed) return { settled: false };++ const powers = await factionPowers(epoch);+ const ranked = Object.keys(powers).sort((a, b) => (powers[b] || 0) - (powers[a] || 0));+ const { battles } = matchmakeFn(ranked, epoch);++ const results = [];+ for (const { a, b } of battles) {+ if (!b) continue;+ const pa = powers[a] || 0;+ const pb = powers[b] || 0;+ if (pa === 0 && pb === 0) continue; // no-show: nobody fought, no record+ let winner = null;+ let loser = null;+ if (pa > pb) {+ winner = a;+ loser = b;+ } else if (pb > pa) {+ winner = b;+ loser = a;+ }+ await bumpRecord(a, { power: pa, win: winner === a, loss: loser === a, draw: !winner });+ await bumpRecord(b, { power: pb, win: winner === b, loss: loser === b, draw: !winner });+ results.push({ epoch, a, b, powerA: pa, powerB: pb, winner });+ }+ return { settled: true, results };+}++async function claimSettle(epoch) {+ if (redis) {+ // SET NX — first writer wins the settlement.+ const ok = await redis.set(K.settled(epoch), Date.now(), { nx: true, ex: ROUND_TTL_S });+ return ok === 'OK' || ok === true;+ }+ if (memValid(K.settled(epoch))) return false;+ mem.s.set(K.settled(epoch), { value: Date.now(), exp: Date.now() + ROUND_TTL_S * 1000 });+ return true;+}++async function bumpRecord(mint, { power, win, loss, draw }) {+ const cur = (await getRecords([mint]))[mint];+ const next = {+ w: cur.w + (win ? 1 : 0),+ l: cur.l + (loss ? 1 : 0),+ d: cur.d + (draw ? 1 : 0),+ battles: cur.battles + 1,+ power: cur.power + Math.round(power),+ };+ if (redis) {+ await redis.hset(K.record, { [mint]: JSON.stringify(next) });+ } else {+ let h = mem.h.get(K.record);+ if (!h) {+ h = new Map();+ mem.h.set(K.record, h);+ }+ h.set(mint, JSON.stringify(next));+ }+}++// ─── helpers ─────────────────────────────────────────────────────────────────++function parseRecord(raw) {+ const empty = { w: 0, l: 0, d: 0, battles: 0, power: 0 };+ if (!raw) return empty;+ try {+ const v = typeof raw === 'string' ? JSON.parse(raw) : raw;+ return {+ w: Number(v.w) || 0,+ l: Number(v.l) || 0,+ d: Number(v.d) || 0,+ battles: Number(v.battles) || 0,+ power: Number(v.power) || 0,+ };+ } catch {+ return empty;+ }+}++// Upstash zrange withScores returns a flat [member, score, member, score, …].+function zflatToMap(flat) {+ const out = {};+ if (!Array.isArray(flat)) return out;+ for (let i = 0; i + 1 < flat.length; i += 2) out[flat[i]] = Number(flat[i + 1]) || 0;+ return out;+}+function zflatToList(flat) {+ const out = [];+ if (!Array.isArray(flat)) return out;+ for (let i = 0; i + 1 < flat.length; i += 2) {+ out.push({ wallet: flat[i], power: Number(flat[i + 1]) || 0 });+ }+ return out;+}diff --git a/api/_lib/clash.js b/api/_lib/clash.jsnew file mode 100644index 000000000..4e98d3c1b--- /dev/null+++ b/api/_lib/clash.js@@ -0,0 +1,270 @@+// Coin Clash — community battle engine.+//+// Every CoinCommunities community on three.ws is a faction. Holders of a coin+// enlist in that coin's army by proving — wallet signature + live on-chain+// holding of the coin — that they're a real holder, then rally for it in timed+// battles. Two factions are matched per epoch; whichever army accumulates more+// rally power before the clock runs out wins, and the result is written to each+// faction's all-time war record.+//+// This file is the pure engine: deterministic epoch math + matchmaking (so every+// stateless serverless instance agrees on who fights whom without coordination),+// the HMAC war pass the rally endpoint trusts instead of re-running Solana RPC on+// every tap, and the bounded momentum factor that folds a faction's live+// pump.fun + community vigor into its rally power. Persistence lives in+// clash-store.js; the HTTP surface in api/clash/[action].js.++import crypto from 'node:crypto';++// ─── Tunables ────────────────────────────────────────────────────────────────++// Battle round length. A round is long enough for an army to rally and short+// enough that standings resolve while people are watching. One hour by default.+export const EPOCH_MS = Math.max(5 * 60_000, Number(process.env.CLASH_EPOCH_MS) || 60 * 60_000);++// How many top communities enter the bracket each round. Even count → clean+// pairs; an odd active set leaves the lowest-seeded faction with a bye.+export const MAX_FACTIONS = Math.min(32, Math.max(2, Number(process.env.CLASH_MAX_FACTIONS) || 16));++// One tap of the rally is one base power point. Power is the only thing that+// decides a battle — an army's effort, not its market cap.+export const POWER_PER_TAP = 1;++// A single rally POST reports at most this many taps. The client batches taps+// between flushes; anything above this is clamped server-side, so a forged+// payload buys nothing a fast thumb couldn't.+export const MAX_TAPS_PER_RALLY = 50;++// Hard ceiling on one wallet's total power per faction per round. The real+// anti-inflation gate: combined with the per-wallet rally rate limit it bounds+// any single holder's influence so a battle reflects an army, not one scripted+// tab.+export const MAX_POWER_PER_WALLET_EPOCH = Math.max(+ 500,+ Number(process.env.CLASH_MAX_POWER_PER_WALLET) || 5000,+);++// War-pass lifetime. Long enough to rally through a round, short enough that a+// holder who dumps the coin can't keep fighting for it indefinitely on an old+// pass.+const PASS_TTL_S = 30 * 60;++// Enlist challenge lifetime — the wallet must sign and return it within this+// window. Stateless: the challenge carries its own HMAC, so no nonce store.+const CHALLENGE_TTL_S = 5 * 60;++// ─── Secret + HMAC (mirrors holder-pass.js) ─────────────────────────────────++const DEV_SECRET = 'three-ws-clash-dev-secret';+let _warned = false;+function secret() {+ const s = process.env.CLASH_PASS_SECRET || process.env.HOLDER_PASS_SECRET;+ if (s) return s;+ if (process.env.NODE_ENV === 'production') {+ throw new Error(+ '[clash] CLASH_PASS_SECRET (or HOLDER_PASS_SECRET) is required in production — refusing to sign war passes with the dev secret.',+ );+ }+ if (!_warned) {+ _warned = true;+ console.warn(+ '[clash] CLASH_PASS_SECRET is not set — using the insecure dev secret. ' ++ 'Set CLASH_PASS_SECRET in production or war passes can be forged.',+ );+ }+ return DEV_SECRET;+}++function b64url(buf) {+ return Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');+}+function fromB64url(s) {+ return Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');+}+function hmac(body) {+ return b64url(crypto.createHmac('sha256', secret()).update(body).digest());+}+// Constant-time compare so a forged tag can't be teased out by timing.+function safeEq(a, b) {+ const ba = Buffer.from(String(a));+ const bb = Buffer.from(String(b));+ if (ba.length !== bb.length) return false;+ return crypto.timingSafeEqual(ba, bb);+}++// ─── Epoch math + deterministic matchmaking ─────────────────────────────────++/** The round index for an instant. Integer, monotonic, identical on every box. */+export function epochAt(now) {+ return Math.floor(now / EPOCH_MS);+}+/** [start, end) of a round in epoch-ms, and ms left until it ends. */+export function epochWindow(epoch, now) {+ const start = epoch * EPOCH_MS;+ const end = start + EPOCH_MS;+ return { start, end, msLeft: Math.max(0, end - now) };+}++// A cheap deterministic hash of a string → 32-bit unsigned int. Used to derive a+// per-epoch rotation so the same top factions don't draw the same opponent every+// round, without any stored bracket.+function hash32(str) {+ let h = 2166136261;+ for (let i = 0; i < str.length; i++) {+ h ^= str.charCodeAt(i);+ h = Math.imul(h, 16777619);+ }+ return h >>> 0;+}++/**+ * Pair an ordered faction list into battles for a given epoch. Deterministic:+ * the seeding order (caller passes factions already ranked, e.g. by members) is+ * rotated by an epoch-seeded offset so matchups vary round to round, then folded+ * into adjacent pairs. An odd faction count yields one bye.+ *+ * @param {string[]} mints faction mints, pre-ranked (strongest first)+ * @param {number} epoch+ * @returns {{ battles: Array<{ id: string, a: string, b: string|null }>, bye: string|null }}+ */+export function matchmake(mints, epoch) {+ const pool = mints.slice(0, MAX_FACTIONS).filter(Boolean);+ if (pool.length < 2) return { battles: [], bye: pool[0] || null };++ // Rotate the seed order by an epoch-derived offset so #1 doesn't always meet+ // #2. The rotation is deterministic from the epoch and the pool itself.+ const offset = hash32(`${epoch}:${pool.join(',')}`) % pool.length;+ const rotated = pool.slice(offset).concat(pool.slice(0, offset));++ const battles = [];+ let bye = null;+ for (let i = 0; i + 1 < rotated.length; i += 2) {+ const a = rotated[i];+ const b = rotated[i + 1];+ // Stable battle id independent of a/b order so both sides resolve the same+ // key (sorted pair + epoch).+ const id = battleId(epoch, a, b);+ battles.push({ id, a, b });+ }+ if (rotated.length % 2 === 1) bye = rotated[rotated.length - 1];+ return { battles, bye };+}++/** Order-independent battle id for a pair in a round. */+export function battleId(epoch, a, b) {+ const [x, y] = [a, b].sort();+ return `${epoch}:${b64url(hash32(`${x}|${y}`).toString(36)).slice(0, 10)}`;+}++// ─── Momentum factor ─────────────────────────────────────────────────────────++// Live vigor → a bounded rally bonus, so an active community with real on-chain+// and social momentum hits a little harder per tap. Bounded so it flavours a+// battle without letting market cap simply buy the win — effort still dominates.+export const MOMENTUM_MIN = 1.0;+export const MOMENTUM_MAX = 1.5;++/**+ * Derive a faction's momentum multiplier from real signals:+ * · social recency — how recently the community last posted+ * · social mass — member count (log-scaled, so whales don't dominate)+ * · market move — pump.fun 24h-ish price change when available+ * Each contributes a slice of the [MIN,MAX] band. Missing signals contribute 0,+ * never block — a coin with no data just fights at the 1.0 floor.+ *+ * @param {{ members?: number, latestPostAt?: number|string|null, priceChange?: number|null }} s+ */+export function momentumFactor(s = {}) {+ const span = MOMENTUM_MAX - MOMENTUM_MIN;++ // Recency: full credit if posted within the hour, decaying to 0 over a week.+ let recency = 0;+ const last = s.latestPostAt ? new Date(s.latestPostAt).getTime() : 0;+ if (last > 0) {+ const ageH = Math.max(0, (Date.now() - last) / 3_600_000);+ recency = Math.max(0, 1 - ageH / (24 * 7));+ }++ // Mass: log-scaled member count, saturating around 10k members.+ const members = Math.max(0, Number(s.members) || 0);+ const mass = Math.min(1, Math.log10(members + 1) / 4);++ // Market: positive 24h move adds, capped at +50% → full credit.+ let market = 0;+ const ch = Number(s.priceChange);+ if (Number.isFinite(ch) && ch > 0) market = Math.min(1, ch / 50);++ // Weighted blend — social signals lead, market is a smaller flavour.+ const blend = recency * 0.5 + mass * 0.3 + market * 0.2;+ const factor = MOMENTUM_MIN + span * Math.max(0, Math.min(1, blend));+ return Math.round(factor * 1000) / 1000;+}++// ─── Enlist challenge (stateless) ────────────────────────────────────────────++/**+ * Build the human-readable message a holder signs to enlist. It binds the exact+ * wallet + faction + issue time and carries an HMAC tag so the verify step can+ * confirm it's our own un-tampered, unexpired challenge with no nonce store.+ */+export function buildChallenge({ wallet, mint, now }) {+ const iat = Math.floor(now / 1000);+ const core = `three.ws Coin Clash — enlist\nfaction: ${mint}\nsoldier: ${wallet}\nissued: ${iat}`;+ const tag = hmac(`enlist|${mint}|${wallet}|${iat}`);+ const message = `${core}\nnonce: ${tag}`;+ return { message, iat, tag, expiresAt: (iat + CHALLENGE_TTL_S) * 1000 };+}++/** Re-derive and verify a returned challenge belongs to us, matches, is fresh. */+export function verifyChallenge({ message, wallet, mint, now }) {+ if (typeof message !== 'string') return false;+ const m = message.match(/issued:\s*(\d+)\nnonce:\s*([A-Za-z0-9_-]+)\s*$/);+ if (!m) return false;+ const iat = parseInt(m[1], 10);+ const tag = m[2];+ if (!Number.isFinite(iat)) return false;+ if (Math.floor(now / 1000) - iat > CHALLENGE_TTL_S) return false; // expired+ if (iat - Math.floor(now / 1000) > 60) return false; // future-dated+ const expected = hmac(`enlist|${mint}|${wallet}|${iat}`);+ if (!safeEq(tag, expected)) return false;+ // The rebuilt message must equal exactly what we'd have issued — defeats any+ // body tampering that left the tag intact.+ const rebuilt = `three.ws Coin Clash — enlist\nfaction: ${mint}\nsoldier: ${wallet}\nissued: ${iat}\nnonce: ${expected}`;+ return safeEq(message, rebuilt);+}++// ─── War pass ────────────────────────────────────────────────────────────────++/** Seal a verified enlistment into a compact signed pass the rally trusts. */+export function signWarPass({ wallet, mint, amount = 0, usd = 0 }) {+ const now = Math.floor(Date.now() / 1000);+ const payload = {+ wallet,+ mint,+ amount: Math.max(0, Number(amount) || 0),+ usd: Math.round((Number(usd) || 0) * 100) / 100,+ tier: 'clash',+ iat: now,+ exp: now + PASS_TTL_S,+ };+ const body = b64url(JSON.stringify(payload));+ return `${body}.${hmac(body)}`;+}++/** Verify + decode a war pass. Returns the payload, or null if forged/expired. */+export function verifyWarPass(pass) {+ if (typeof pass !== 'string' || pass.indexOf('.') < 0) return null;+ const [body, tag] = pass.split('.');+ if (!body || !tag) return null;+ if (!safeEq(tag, hmac(body))) return null;+ let payload;+ try {+ payload = JSON.parse(fromB64url(body).toString('utf8'));+ } catch {+ return null;+ }+ if (payload?.tier !== 'clash') return null;+ if (!payload.wallet || !payload.mint) return null;+ if (Math.floor(Date.now() / 1000) > Number(payload.exp || 0)) return null;+ return payload;+}diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex b74d2628e..477f260f2 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -623,6 +623,16 @@ export const limits = {oracleTelegramTestIp: (ip) =>getLimiter('oracle:tg-test:ip', { limit: 5, window: '10 m' }).limit(ip),+ // Coin Clash community battles (api/clash/*). enlist verifies a wallet sig ++ // runs a balance read, so cap per IP. rally is the hot tap loop — per wallet,+ // generous enough for furious tapping but bounded so one tab can't flood; the+ // real influence ceiling is the per-wallet power cap in clash-store.js.+ clashEnlistIp: (ip) => getLimiter('clash:enlist:ip', { limit: 20, window: '5 m' }).limit(ip),+ clashRallyWallet: (wallet) =>+ getLimiter('clash:rally:wallet', { limit: 40, window: '1 m' }).limit(wallet),+ clashStateIp: (ip) =>+ getLimiter('clash:state:ip', { limit: 120, window: '1 m', local: true }).limit(ip),+// Oracle follower subscribe/update — write path creates a DB row and will// eventually fan out Telegram messages, so keep post-rate tight.// 10 per hour per IP is enough for manual setup; bots would need more.diff --git a/api/clash/[action].js b/api/clash/[action].jsnew file mode 100644index 000000000..bea9729d9--- /dev/null+++ b/api/clash/[action].js@@ -0,0 +1,364 @@+// Coin Clash — community battle API.+//+// Every CoinCommunities community is a faction; its holders are its army. The+// game loop:+//+// GET state → live bracket for the current round: who fights whom,+// each army's power + momentum, time left, war records.+// POST enlist → issue a wallet-bound challenge for a faction.+// POST enlist-verify → verify the wallet's signature, confirm a live on-chain+// holding of the faction coin (pump.fun-priced), and seal+// a war pass.+// POST rally → spend taps from a war pass as battle power for the+// soldier's faction this round.+// GET leaderboard → all-time faction war records + (optional) a faction's+// top soldiers this round.+//+// Real data throughout: factions + their social stats come from CoinCommunities,+// holdings + momentum from pump.fun/Helius via the shared balances lib, power is+// persisted and ranked in Redis. Nothing here is mocked.++import { cors, json, method, readJson, error, wrap, rateLimited } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { cc, toWorldCard, isValidToken, UnconfiguredError } from '../_lib/coin-communities.js';+import { getBalances, solanaMintUsdPrice } from '../_lib/balances.js';+import { verifySiwsSignature } from '../_lib/siws.js';+import {+ epochAt,+ epochWindow,+ matchmake,+ momentumFactor,+ buildChallenge,+ verifyChallenge,+ signWarPass,+ verifyWarPass,+ EPOCH_MS,+ MAX_FACTIONS,+ MAX_TAPS_PER_RALLY,+ POWER_PER_TAP,+ MAX_POWER_PER_WALLET_EPOCH,+} from '../_lib/clash.js';+import {+ addPower,+ walletPower,+ factionPowers,+ topSoldiers,+ getRecords,+ getMomentum,+ setMomentum,+ settleRound,+} from '../_lib/clash-store.js';++const SOL_MINT = 'So11111111111111111111111111111111111111112';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ const action = req.query?.action;+ switch (action) {+ case 'state':+ return handleState(req, res);+ case 'enlist':+ return handleEnlist(req, res);+ case 'enlist-verify':+ return handleEnlistVerify(req, res);+ case 'rally':+ return handleRally(req, res);+ case 'leaderboard':+ return handleLeaderboard(req, res);+ default:+ return error(res, 404, 'unknown_action', `unknown clash action: ${action || '(none)'}`);+ }+});++// Load the active faction roster from CoinCommunities, ranked strongest-first by+// member count so the bracket seeds deterministically. Returns the normalized+// world-cards (token, symbol, image, members, social stats).+async function loadFactions() {+ const api = cc(); // throws UnconfiguredError → caller maps to 503+ const { data, error: apiErr } = await api.getTopCommunities();+ if (apiErr) {+ throw Object.assign(new Error(apiErr.message || 'failed to load communities'), { status: 502, code: 'upstream_error' });+ }+ return (data?.communities ?? [])+ .map(toWorldCard)+ .filter((c) => isValidToken(c.token))+ .sort((a, b) => (b.members || 0) - (a.members || 0))+ .slice(0, MAX_FACTIONS);+}++// ─── state ───────────────────────────────────────────────────────────────────++async function handleState(req, res) {+ if (!method(req, res, ['GET'])) return;+ const rl = await limits.clashStateIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let factions;+ try {+ factions = await loadFactions();+ } catch (err) {+ if (err instanceof UnconfiguredError) {+ return error(res, 503, 'cc_unconfigured', 'CoinCommunities is not configured');+ }+ if (err.status === 502) return error(res, 502, err.code, err.message);+ throw err;+ }++ const now = Date.now();+ const epoch = epochAt(now);+ const { msLeft, end } = epochWindow(epoch, now);++ // Settle the previous round once (lazy, idempotent) so records stay current+ // without a cron. Best-effort — a settle hiccup never blocks the live read.+ settleRound(epoch - 1, matchmake).catch(() => {});++ const byMint = new Map(factions.map((f) => [f.token, f]));+ const mints = factions.map((f) => f.token);+ const { battles, bye } = matchmake(mints, epoch);++ const [powers, records] = await Promise.all([factionPowers(epoch), getRecords(mints)]);++ // Refresh each faction's momentum factor (bounded vigor bonus) and cache it so+ // the hot rally path can read it cheaply. Derived from real social + market data.+ await Promise.all(+ factions.map(async (f) => {+ let priceChange = null; // best-effort live pump move; absent → social-only+ try {+ const p = await solanaMintUsdPrice(f.token).catch(() => 0);+ f._priceUsd = p || 0;+ } catch {+ /* price is flavour, never fatal */+ }+ const factor = momentumFactor({+ members: f.members,+ latestPostAt: f.latestPostAt,+ priceChange,+ });+ f._momentum = factor;+ setMomentum(f.token, factor, Math.ceil(EPOCH_MS / 1000)).catch(() => {});+ }),+ );++ const sideOf = (mint) => {+ const f = byMint.get(mint);+ const power = Math.round(powers[mint] || 0);+ return {+ token: mint,+ symbol: f?.symbol || null,+ image: f?.image || null,+ members: f?.members || 0,+ posts: f?.posts || 0,+ priceUsd: f?._priceUsd || 0,+ momentum: f?._momentum || 1,+ power,+ record: records[mint] || { w: 0, l: 0, d: 0, battles: 0, power: 0 },+ };+ };++ const arena = battles.map((bt) => {+ const a = sideOf(bt.a);+ const b = bt.b ? sideOf(bt.b) : null;+ const total = a.power + (b?.power || 0);+ return {+ id: bt.id,+ a,+ b,+ // Live share of the round's combined power, for the tug-of-war bar.+ aShare: total > 0 ? a.power / total : 0.5,+ leader: !b ? a.token : a.power === b.power ? null : a.power > b.power ? a.token : b.token,+ };+ });++ res.setHeader('cache-control', 'no-store');+ return json(res, 200, {+ data: {+ epoch,+ endsAt: end,+ msLeft,+ epochMs: EPOCH_MS,+ arena,+ bye: bye ? sideOf(bye) : null,+ factionCount: factions.length,+ },+ });+}++// ─── enlist (issue challenge) ────────────────────────────────────────────────++async function handleEnlist(req, res) {+ if (!method(req, res, ['POST'])) return;+ res.setHeader('cache-control', 'no-store');+ const rl = await limits.clashEnlistIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const body = await readJson(req).catch(() => ({}));+ const token = String(body.token || '');+ const wallet = String(body.wallet || '');+ if (!isValidToken(token)) return error(res, 400, 'validation_error', 'valid faction token required');+ if (!isValidToken(wallet)) return error(res, 400, 'validation_error', 'valid wallet address required');++ const ch = buildChallenge({ wallet, mint: token, now: Date.now() });+ return json(res, 200, { data: { message: ch.message, expiresAt: ch.expiresAt } });+}++// ─── enlist-verify (verify sig + holding → war pass) ─────────────────────────++async function handleEnlistVerify(req, res) {+ if (!method(req, res, ['POST'])) return;+ res.setHeader('cache-control', 'no-store');+ const rl = await limits.clashEnlistIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const body = await readJson(req).catch(() => ({}));+ const token = String(body.token || '');+ const wallet = String(body.wallet || '');+ const message = String(body.message || '');+ const signature = String(body.signature || '');+ if (!isValidToken(token)) return error(res, 400, 'validation_error', 'valid faction token required');+ if (!isValidToken(wallet)) return error(res, 400, 'validation_error', 'valid wallet address required');+ if (!message || !signature) return error(res, 400, 'validation_error', 'message and signature required');++ // 1) The challenge must be our own, un-tampered, fresh, and bound to this+ // exact wallet + faction.+ if (!verifyChallenge({ message, wallet, mint: token, now: Date.now() })) {+ return error(res, 400, 'bad_challenge', 'enlist challenge is invalid or expired — request a new one');+ }++ // 2) The signature must verify against the claimed wallet, proving the caller+ // controls it (so power can't be enlisted on someone else's behalf).+ let sigOk = false;+ try {+ sigOk = verifySiwsSignature(message, signature, wallet);+ } catch {+ sigOk = false;+ }+ if (!sigOk) return error(res, 401, 'bad_signature', 'signature does not match wallet');++ // 3) Confirm a live on-chain holding of the faction coin. This is the token+ // gate: you fight for a coin only if you actually hold it right now.+ let balances;+ try {+ balances = await getBalances({ chain: 'solana', address: wallet });+ } catch (err) {+ const status = err?.status === 503 ? 503 : 502;+ return error(res, status, 'balance_unavailable', 'could not read on-chain balance — try again');+ }+ const holding =+ token === SOL_MINT ? balances?.native : (balances?.tokens ?? []).find((t) => t.mint === token);+ const amount = holding?.amount || 0;+ if (amount <= 0) {+ return json(res, 200, {+ data: { eligible: false, wallet, amount: 0, usd: 0, reason: 'not_a_holder' },+ });+ }++ // Price it for display (fresh bonding-curve coins price at $0 via Jupiter; fall+ // back to the pump.fun curve so a real holder always sees a real number).+ let price = holding?.price || 0;+ if (price <= 0 && token !== SOL_MINT) price = await solanaMintUsdPrice(token).catch(() => 0);+ const usd = Math.round(amount * price * 100) / 100;++ const warPass = signWarPass({ wallet, mint: token, amount, usd });+ return json(res, 200, { data: { eligible: true, wallet, amount, usd, warPass } });+}++// ─── rally (spend taps as battle power) ──────────────────────────────────────++async function handleRally(req, res) {+ if (!method(req, res, ['POST'])) return;+ res.setHeader('cache-control', 'no-store');++ const body = await readJson(req).catch(() => ({}));+ const pass = verifyWarPass(String(body.pass || ''));+ if (!pass) return error(res, 401, 'pass_invalid', 'war pass is missing, forged, or expired — re-enlist');++ const wallet = pass.wallet;+ const mint = pass.mint;++ const rl = await limits.clashRallyWallet(wallet);+ if (!rl.success) return rateLimited(res, rl, 'rallying too fast — pace your taps');++ // Clamp reported taps to the per-call ceiling: a forged count buys nothing a+ // fast thumb couldn't legitimately produce between flushes.+ const taps = Math.max(0, Math.min(MAX_TAPS_PER_RALLY, Math.floor(Number(body.taps) || 0)));+ if (taps <= 0) return error(res, 400, 'validation_error', 'taps must be a positive integer');++ const now = Date.now();+ const epoch = epochAt(now);++ // Fold the faction's cached momentum into power so an active community hits+ // slightly harder per tap. Absent cache → 1.0 (never blocks the rally).+ const momentum = (await getMomentum(mint).catch(() => null)) || 1;+ const power = Math.max(1, Math.round(taps * POWER_PER_TAP * momentum));++ const result = await addPower({+ epoch,+ mint,+ wallet,+ amount: power,+ walletCap: MAX_POWER_PER_WALLET_EPOCH,+ });++ const { msLeft } = epochWindow(epoch, now);+ return json(res, 200, {+ data: {+ epoch,+ mint,+ added: result.added,+ momentum,+ walletPower: result.walletTotal,+ walletCap: MAX_POWER_PER_WALLET_EPOCH,+ capped: result.capped,+ factionPower: Math.round((await factionPowers(epoch))[mint] || 0),+ msLeft,+ },+ });+}++// ─── leaderboard ─────────────────────────────────────────────────────────────++async function handleLeaderboard(req, res) {+ if (!method(req, res, ['GET'])) return;+ const rl = await limits.clashStateIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let factions;+ try {+ factions = await loadFactions();+ } catch (err) {+ if (err instanceof UnconfiguredError) {+ return error(res, 503, 'cc_unconfigured', 'CoinCommunities is not configured');+ }+ if (err.status === 502) return error(res, 502, err.code, err.message);+ throw err;+ }+ const byMint = new Map(factions.map((f) => [f.token, f]));+ const mints = factions.map((f) => f.token);+ const records = await getRecords(mints);++ const board = mints+ .map((mint) => {+ const f = byMint.get(mint);+ const r = records[mint] || { w: 0, l: 0, d: 0, battles: 0, power: 0 };+ const decided = r.w + r.l;+ return {+ token: mint,+ symbol: f?.symbol || null,+ image: f?.image || null,+ members: f?.members || 0,+ ...r,+ winRate: decided > 0 ? Math.round((r.w / decided) * 100) : null,+ };+ })+ .sort((a, b) => b.w - a.w || b.power - a.power);++ // Optional: a single faction's top soldiers this round.+ const mintParam = new URL(req.url, 'http://x').searchParams.get('faction');+ let soldiers = null;+ if (mintParam && isValidToken(mintParam)) {+ soldiers = await topSoldiers({ epoch: epochAt(Date.now()), mint: mintParam, limit: 10 });+ }++ res.setHeader('cache-control', 'public, max-age=15, s-maxage=15, stale-while-revalidate=60');+ return json(res, 200, { data: { board, soldiers } });+}diff --git a/src/viewer.js b/src/viewer.jsindex 919fdb435..57b017fca 100644--- a/src/viewer.js+++ b/src/viewer.js@@ -45,7 +45,7 @@ import { addLights, removeLights } from './viewer/lights.js';import { getCubeMapTexture } from './viewer/environment.js';import { takeScreenshot, captureScreenshot } from './viewer/screenshot.js';import { setClips, playAllClips } from './viewer/animation.js';-import { computeFramingExtent } from './viewer/framing.js';+import { computeFramingExtent, computeFramingWidth } from './viewer/framing.js';import { LightProbeGrid } from './light-probe-grid.js';import { AnimationManager } from './animation-manager.js';import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';@@ -496,7 +496,8 @@ export class Viewer {const extentV = (visH / 2) * PAD_V / usableFrac;const distV = extentV / Math.tan(vFovRad / 2);- const distH = (bbSize.x / 2) * PAD_H / Math.tan(hFovRad / 2);+ const framingWidth = computeFramingWidth(bbSize.x, bbSize.y, framingMode);+ const distH = (framingWidth / 2) * PAD_H / Math.tan(hFovRad / 2);const dist = Math.max(distV, distH);// Center look-at on the usable area: with no panel focusY = baseY;@@ -1056,7 +1057,8 @@ export class Viewer {const extentV = (visH / 2) * PAD_V / usableFrac;const distV = extentV / Math.tan(vFovRad / 2);- const distH = (bbSize.x / 2) * PAD_H / Math.tan(hFovRad / 2);+ const framingWidth = computeFramingWidth(bbSize.x, bbSize.y, framingMode);+ const distH = (framingWidth / 2) * PAD_H / Math.tan(hFovRad / 2);const dist = Math.max(distV, distH);// Center the look-at on the usable area: with no panel focusY=baseY;diff --git a/src/viewer/framing.js b/src/viewer/framing.jsindex b6915e7a9..fb43b4c8c 100644--- a/src/viewer/framing.js+++ b/src/viewer/framing.js@@ -29,3 +29,36 @@ export function computeFramingExtent(bodyHeight, topY, mode = 'full') {}return { visH: bodyHeight, baseY: topY - bodyHeight / 2 };}++/**+ * Effective horizontal extent to frame against, in world units.+ *+ * Camera distance is driven by `max(verticalFit, horizontalFit)`, and the+ * horizontal term reads the bounding-box width. A humanoid's natural standing+ * width (shoulders, arms at the sides) is only ~0.25–0.35× its height, but a+ * rig authored in a T-pose (arms stretched straight out — Mixamo's michelle,+ * xbot, …) measures ~0.85–1.0× its height. Until a retargeted clip lowers the+ * arms, that arms-out box pushes the camera so far back the avatar shrinks to a+ * speck — the "tiny figure stranded at the bottom of the card" bug.+ *+ * In `portrait` mode (a deliberately tight vertical crop for small cards) we cap+ * the width that feeds the distance so an arms-out rest pose can't blow out the+ * frame: the figure fills the card by height and any outstretched arms simply+ * extend past the (overflow-hidden) card edges for the moment before the clip+ * settles them in — vastly better than zooming away from the whole avatar. The+ * cap sits well above any natural standing width, so arms-down bodies (cz,+ * default, every Avaturn/RPM rig) are returned unchanged and never re-framed.+ * `full` mode is untouched: it shows the whole body, so arms-out is acceptable.+ *+ * @param {number} bbWidth bounding-box width in world units+ * @param {number} bodyHeight full bounding-box height in world units+ * @param {'full'|'portrait'} [mode]+ * @returns {number} width to use when computing horizontal camera fit+ */+export function computeFramingWidth(bbWidth, bodyHeight, mode = 'full') {+ if (mode === 'portrait') {+ const MAX_PORTRAIT_WIDTH_FRAC = 0.55; // > any natural standing width, < a T-pose+ return Math.min(bbWidth, bodyHeight * MAX_PORTRAIT_WIDTH_FRAC);+ }+ return bbWidth;+}diff --git a/tests/viewer-framing.test.js b/tests/viewer-framing.test.jsindex b0a254b80..c162967c3 100644--- a/tests/viewer-framing.test.js+++ b/tests/viewer-framing.test.js@@ -8,7 +8,7 @@*/import { describe, it, expect } from 'vitest';-import { computeFramingExtent } from '../src/viewer/framing.js';+import { computeFramingExtent, computeFramingWidth } from '../src/viewer/framing.js';describe('computeFramingExtent — full (default)', () => {it('is the legacy full-body framing: baseY at the vertical centre, full height', () => {@@ -64,3 +64,39 @@ describe('computeFramingExtent — portrait', () => {expect(b.baseY).toBeCloseTo(a.baseY * 2, 9);});});++describe('computeFramingWidth', () => {+ const H = 1.8;++ it('full mode returns the raw width unchanged (whole-body framing is untouched)', () => {+ expect(computeFramingWidth(0.5, H, 'full')).toBe(0.5);+ expect(computeFramingWidth(1.6, H, 'full')).toBe(1.6); // even a T-pose width+ expect(computeFramingWidth(0.5, H)).toBe(0.5); // defaults to full+ });++ it('portrait mode leaves a natural arms-down width unchanged', () => {+ // Real arms-down humanoids are ~0.25–0.35× height — well under the cap.+ const naturalWidth = H * 0.3;+ expect(computeFramingWidth(naturalWidth, H, 'portrait')).toBe(naturalWidth);+ });++ it('portrait mode caps an arms-out T-pose width so it cannot blow out the frame', () => {+ // A Mixamo T-pose measures ~0.85–1.0× height; it must be clamped.+ const tPoseWidth = H * 0.9;+ const capped = computeFramingWidth(tPoseWidth, H, 'portrait');+ expect(capped).toBeLessThan(tPoseWidth);+ expect(capped).toBeCloseTo(H * 0.55, 9);+ });++ it('the cap sits above any natural standing width but below a T-pose', () => {+ // Boundary intent: 0.35 (broad shoulders) passes through; 0.85 (arms out)+ // is clamped. The 0.55 threshold separates them.+ expect(computeFramingWidth(H * 0.35, H, 'portrait')).toBeCloseTo(H * 0.35, 9);+ expect(computeFramingWidth(H * 0.85, H, 'portrait')).toBeCloseTo(H * 0.55, 9);+ });++ it('scales the cap linearly with body height', () => {+ expect(computeFramingWidth(10, 2, 'portrait')).toBeCloseTo(2 * 0.55, 9);+ expect(computeFramingWidth(10, 4, 'portrait')).toBeCloseTo(4 * 0.55, 9);+ });+});