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.

fix(clash): keep Coin Clash playable without CoinCommunities by seeding rounds from trending

nirholas12c693e48ec7
diff --git a/api/_lib/clash-store.js b/api/_lib/clash-store.js
index e27d905ae..732d7a181 100644
--- a/api/_lib/clash-store.js
+++ b/api/_lib/clash-store.js
@@ -46,6 +46,7 @@ const K = {
momentum: (mint) => `clash:mom:${mint}`, // JSON cached factor
price: (mint) => `clash:px:${mint}`, // JSON { spot, at, base, baseAt }
settled: (epoch) => `clash:settled:${epoch}`, // marker
+ roster: (epoch) => `clash:roster:${epoch}`, // JSON fallback faction cards
record: 'clash:record', // HASH mint → JSON {w,l,battles,power}
};
@@ -249,6 +250,56 @@ export async function setPrice(mint, snap, ttlS) {
mem.s.set(K.price(mint), { value, exp: Date.now() + ttlS * 1000 });
}
+// ─── Fallback roster, frozen per round ───────────────────────────────────────
+// The CoinCommunities roster moves slowly, but the trending feed that stands in
+// for it reorders every few seconds. Re-reading it on every poll would re-pair
+// battles mid-round, so the first instance to need a fallback roster for a round
+// writes it (SET NX) and every instance serves that same roster until the round
+// ends.
+
+function parseRoster(v) {
+ if (v == null) return null;
+ try {
+ const cards = typeof v === 'string' ? JSON.parse(v) : v;
+ return Array.isArray(cards) && cards.length ? cards : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The round's frozen fallback roster, claiming `cards` for it if no instance
+ * has yet. Resolves to whichever roster won.
+ */
+export async function claimRoster(epoch, cards) {
+ const value = JSON.stringify(cards);
+ if (redis) {
+ try {
+ const ok = await redis.set(K.roster(epoch), value, { nx: true, ex: ROUND_TTL_S });
+ if (ok === 'OK' || ok === true) return cards;
+ return parseRoster(await redis.get(K.roster(epoch))) || cards;
+ } catch (err) {
+ redisDegraded(err);
+ }
+ }
+ const held = parseRoster(memValid(K.roster(epoch)));
+ if (held) return held;
+ mem.s.set(K.roster(epoch), { value, exp: Date.now() + ROUND_TTL_S * 1000 });
+ return cards;
+}
+
+/** The round's frozen fallback roster, or null when none was claimed. */
+export async function getRoster(epoch) {
+ if (redis) {
+ try {
+ return parseRoster(await redis.get(K.roster(epoch)));
+ } catch (err) {
+ redisDegraded(err);
+ }
+ }
+ return parseRoster(memValid(K.roster(epoch)));
+}
+
// ─── All-time war record + lazy settlement ───────────────────────────────────
/** All-time records for a set of mints: mint → { w, l, battles, power }. */
diff --git a/api/_lib/coin-communities.js b/api/_lib/coin-communities.js
index 34a8cd43e..4bdfbb5f3 100644
--- a/api/_lib/coin-communities.js
+++ b/api/_lib/coin-communities.js
@@ -15,6 +15,7 @@
import { configureApi, api } from '@coin-communities/sdk/node';
import { normalizeGatewayURL } from '../../src/ipfs.js';
+import { getTrendingSlim } from './pump-trending.js';
// Solana mint addresses — base58, 32–44 chars. Communities are keyed by these.
const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
@@ -254,6 +255,32 @@ export function toWorldCard(c) {
};
}
+/**
+ * The live trending feed as world cards: the failover roster for every surface
+ * that ranks coin communities (the /temporary lobby, Coin Clash) when
+ * CoinCommunities is unconfigured or down. The cards carry `social: false`
+ * because there are no members, posts or likes to show, plus the coin's name
+ * and market cap so a client has a real number to render in their place.
+ * Resolves to null when the trending feed is unavailable too.
+ */
+export async function trendingWorldCards(limit) {
+ const { data } = await getTrendingSlim(limit);
+ if (!data) return null;
+ return data.map((t) => ({
+ token: t.mint,
+ symbol: t.symbol || null,
+ name: t.name || null,
+ image: t.logo || null,
+ chainId: null,
+ members: 0,
+ posts: 0,
+ likes: 0,
+ latestPostAt: null,
+ marketCapUsd: t.usd_market_cap ?? null,
+ social: false,
+ }));
+}
+
/**
* Normalize a Message into the compact shape Town renders (rail rows + bubbles).
* Drops moderation internals the client doesn't need.
diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.js
index d01f7a0ff..3727b8a05 100644
--- a/api/_mcp3d/text-to-image.js
+++ b/api/_mcp3d/text-to-image.js
@@ -430,14 +430,41 @@ async function nimFluxImage(prompt, aspectRatio, seed = 0, { timeoutMs = NIM_TIM
}
const data = await res.json().catch(() => ({}));
- const b64 = data?.artifacts?.[0]?.base64;
+ const artifact = data?.artifacts?.[0];
+ const b64 = artifact?.base64;
if (!b64) throw new Error('nim flux finished but produced no image');
+ // A content filter answers 200 with a solid black frame and says so only in
+ // finishReason. Persisting that frame as the reference sent every 3D backend
+ // an image with no subject in it, and all three crashed on the empty mask
+ // (TRELLIS, Hunyuan3D and TripoSG on 2026-10-08). Hand off to the next lane.
+ const finish = artifact.finishReason ?? artifact.finish_reason;
+ if (finish && finish !== 'SUCCESS') {
+ throw Object.assign(new Error(`nim flux withheld the image (${finish})`), { code: 'safety_blocked' });
+ }
+ if (await isBlankFrame(Buffer.from(b64, 'base64'))) {
+ throw Object.assign(new Error('nim flux returned a blank frame'), { code: 'safety_blocked' });
+ }
return { imageUrl: await persistImageBase64(b64), model: NIM_FLUX_MODEL };
}
// Exhausted retries on a transient status/blip without a terminal verdict.
throw lastErr || new Error('nim flux failed after retries');
}
+// A frame with no subject in it: every channel flat to within a couple of
+// levels, which is what a filtered render looks like whatever color it is
+// filled with. No real reference photo comes close; even a plain-background
+// product shot varies by tens of levels across the subject. An image sharp
+// cannot read is not judged blank here; the 3D backend reports it properly.
+export async function isBlankFrame(bytes) {
+ try {
+ const { default: sharp } = await import('sharp');
+ const { channels } = await sharp(bytes).stats();
+ return channels.length > 0 && channels.every((c) => c.stdev < 2);
+ } catch {
+ return false;
+ }
+}
+
// Background / lighting / composition cues that signal the caller already
// controls the scene. When one is present we leave the prompt untouched;
// otherwise we append cues that steer the image toward a single, evenly-lit
diff --git a/api/clash/[action].js b/api/clash/[action].js
index f8e68c7eb..36f71ed40 100644
--- a/api/clash/[action].js
+++ b/api/clash/[action].js
@@ -20,7 +20,7 @@
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 { cc, toWorldCard, trendingWorldCards, isValidToken, UnconfiguredError } from '../_lib/coin-communities.js';
import { getBalances, solanaMintUsdPrice } from '../_lib/balances.js';
import { verifySiwsSignature } from '../_lib/siws.js';
import {
@@ -53,6 +53,8 @@ import {
getPrice,
setPrice,
settleRound,
+ claimRoster,
+ getRoster,
} from '../_lib/clash-store.js';
const SOL_MINT = 'So11111111111111111111111111111111111111112';
@@ -78,18 +80,43 @@ export default wrap(async (req, res) => {
// 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' });
+// world-cards (token, symbol, image, members, social stats) and their source.
+//
+// Failover: when CoinCommunities is unconfigured (no CC_API_KEY) or its upstream
+// errors, the round is fought between the coins on the live trending feed, in
+// trending order, frozen for the whole round (see claimRoster). Those cards carry
+// `social: false`, so momentum rides on the market alone. The original error
+// surfaces only when the trending feed is down too.
+async function loadFactions(epoch) {
+ let api = null;
+ let upstreamErr = null;
+ try {
+ api = cc();
+ } catch (err) {
+ if (!(err instanceof UnconfiguredError)) throw err;
+ upstreamErr = err;
}
- return (data?.communities ?? [])
- .map(toWorldCard)
- .filter((c) => isValidToken(c.token))
- .sort((a, b) => (b.members || 0) - (a.members || 0))
- .slice(0, MAX_FACTIONS);
+ if (api) {
+ const { data, error: apiErr } = await api.getTopCommunities();
+ if (!apiErr) {
+ const factions = (data?.communities ?? [])
+ .map(toWorldCard)
+ .filter((c) => isValidToken(c.token))
+ .sort((a, b) => (b.members || 0) - (a.members || 0))
+ .slice(0, MAX_FACTIONS);
+ return { factions, source: 'coincommunities' };
+ }
+ upstreamErr = Object.assign(new Error(apiErr.message || 'failed to load communities'), {
+ status: 502,
+ code: 'upstream_error',
+ });
+ }
+
+ const frozen = await getRoster(epoch);
+ if (frozen) return { factions: frozen, source: 'pump-trending' };
+ const cards = (await trendingWorldCards(MAX_FACTIONS).catch(() => null))?.filter((c) => isValidToken(c.token));
+ if (cards?.length) return { factions: await claimRoster(epoch, cards), source: 'pump-trending' };
+ throw upstreamErr;
}
/**
@@ -137,9 +164,13 @@ async function handleState(req, res) {
const rl = await limits.clashStateIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
+ const now = Date.now();
+ const epoch = epochAt(now);
+
let factions;
+ let source;
try {
- factions = await loadFactions();
+ ({ factions, source } = await loadFactions(epoch));
} catch (err) {
if (err instanceof UnconfiguredError) {
return error(res, 503, 'cc_unconfigured', 'CoinCommunities is not configured');
@@ -147,9 +178,6 @@ async function handleState(req, res) {
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
@@ -175,6 +203,8 @@ async function handleState(req, res) {
image: f?.image || null,
members: f?.members || 0,
posts: f?.posts || 0,
+ social: f?.social !== false,
+ marketCapUsd: f?.marketCapUsd ?? null,
priceUsd: f?._priceUsd || 0,
momentum: f?._momentum || 1,
power,
@@ -206,6 +236,7 @@ async function handleState(req, res) {
arena,
bye: bye ? sideOf(bye) : null,
factionCount: factions.length,
+ source,
},
});
}
@@ -350,8 +381,9 @@ async function handleLeaderboard(req, res) {
if (!rl.success) return rateLimited(res, rl);
let factions;
+ let source;
try {
- factions = await loadFactions();
+ ({ factions, source } = await loadFactions(epochAt(Date.now())));
} catch (err) {
if (err instanceof UnconfiguredError) {
return error(res, 503, 'cc_unconfigured', 'CoinCommunities is not configured');
@@ -373,6 +405,8 @@ async function handleLeaderboard(req, res) {
symbol: f?.symbol || null,
image: f?.image || null,
members: f?.members || 0,
+ social: f?.social !== false,
+ marketCapUsd: f?.marketCapUsd ?? null,
...r,
winRate: decided > 0 ? Math.round((r.w / decided) * 100) : null,
};
@@ -387,5 +421,5 @@ async function handleLeaderboard(req, res) {
}
res.setHeader('cache-control', 'public, max-age=15, s-maxage=15, stale-while-revalidate=60');
- return json(res, 200, { data: { board, soldiers } });
+ return json(res, 200, { data: { board, soldiers, source } });
}
diff --git a/api/community/worlds.js b/api/community/worlds.js
index 6966e1bce..10de82f64 100644
--- a/api/community/worlds.js
+++ b/api/community/worlds.js
@@ -11,28 +11,10 @@
// the response is tagged with its `source` so clients can render accordingly.
import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
-import { cc, toWorldCard, UnconfiguredError } from '../_lib/coin-communities.js';
-import { getTrendingSlim } from '../_lib/pump-trending.js';
+import { cc, toWorldCard, trendingWorldCards, UnconfiguredError } from '../_lib/coin-communities.js';
const TRENDING_WORLDS = 24;
-async function trendingWorlds() {
- const { data } = await getTrendingSlim(TRENDING_WORLDS);
- if (!data) return null;
- return data.map((t) => ({
- token: t.mint,
- symbol: t.symbol || null,
- name: t.name || null,
- image: t.logo || null,
- chainId: null,
- members: 0,
- posts: 0,
- likes: 0,
- latestPostAt: null,
- social: false,
- }));
-}
-
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
if (!method(req, res, ['GET'])) return;
@@ -57,7 +39,7 @@ export default wrap(async (req, res) => {
}
}
- const worlds = await trendingWorlds();
+ const worlds = await trendingWorldCards(TRENDING_WORLDS);
if (worlds) {
res.setHeader('cache-control', 'public, max-age=20, s-maxage=20, stale-while-revalidate=60');
return json(res, 200, { data: { worlds, source: 'pump-trending' } });
diff --git a/data/changelog.json b/data/changelog.json
index 7f7592a7c..8f4c395a4 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-10-08",
+ "title": "3D Studio results now hand every agent plain links to the model",
+ "summary": "Every model the free 3D Studio MCP server hands back, whether freshly generated, picked from the asset catalog or saved as a persona, now comes with four plain links, both in the result data and in its first lines of text: a viewer page, the GLB file, a rendered PNG picture and a paste-ready embed snippet. Agents that cannot show a 3D widget, like Grok Bot and other browser agents, can now open, download, share and embed the model directly. A model that is still rendering comes with a viewer link that waits for the job and opens the model the moment it is ready.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/docs/mcp-studio"
+ },
{
"date": "2026-10-08",
"title": "Picking the free Hugging Face engine no longer leaves you stuck when its Spaces are down",
@@ -29069,6 +29078,13 @@
"summary": "Every AI answer on three.ws, from chat to agent brains, the tutor and the fact-checker, now has five more free models to fall back on when the usual ones are busy. NVIDIA's largest open model, Nemotron 3 Ultra, now answers right behind Nemotron 3 Super, with the compact Nemotron 3.5 Lightning further down the line. A second, independent route to the same Nemotron models works with no account at all, and a Gemma 4 model is back in the mix as well. The free NVIDIA and gateway models are now checked against their providers every six hours too, so the team hears the moment one is switched off instead of finding out from a failed answer.",
"tags": ["improvement"],
"link": "/chat"
+ },
+ {
+ "date": "2026-10-08",
+ "title": "Fewer failed 3D generations when the concept image comes back blank",
+ "summary": "Text to 3D first paints a concept image, then sculpts it. When the painting service quietly returned a blank black frame instead of a picture, the studio used it anyway, and every 3D engine then failed because there was nothing in the image to sculpt. The studio now spots a blank or withheld frame and paints the concept with the next image service instead, so those prompts finish as real models.",
+ "tags": ["fix"],
+ "link": "/forge"
}
]
}
diff --git a/docs/clash.md b/docs/clash.md
index 2b739ec3e..d0b323814 100644
--- a/docs/clash.md
+++ b/docs/clash.md
@@ -14,7 +14,7 @@ Coin communities already behave like tribes. Coin Clash gives that tribalism a g
The page (`src/clash.js`) polls `GET /api/clash/state` every 5 seconds (paused while the tab is hidden) and renders the live bracket. There is no websocket; liveness is polling. All five actions route through a single handler, `api/clash/[action].js`, backed by the engine in `api/_lib/clash.js` and an Upstash Redis store (`api/_lib/clash-store.js`) with an in-process fallback.
-**Factions.** Every community loaded from CoinCommunities becomes a faction, ranked strongest-first by member count and capped at `MAX_FACTIONS`. If the community source is unconfigured the API returns `503 cc_unconfigured` and the page shows a designed "temporarily unavailable" state and stops polling.
+**Factions.** Every community loaded from CoinCommunities becomes a faction, ranked strongest-first by member count and capped at `MAX_FACTIONS`. If CoinCommunities is unconfigured or its upstream errors, the round is fought between the coins on the live trending feed instead (`trendingWorldCards()` in `api/_lib/coin-communities.js`), in trending order. That fallback roster is frozen for the whole round (`claimRoster()` in `api/_lib/clash-store.js`), so a feed that reorders between polls cannot re-pair battles mid-round. Both `state` and `leaderboard` tag their response with `source` (`coincommunities` or `pump-trending`), and fallback factions carry `social: false` plus `marketCapUsd`, which the page shows in place of a member count. Only when the trending feed is down too does the API return `503 cc_unconfigured`, and the page then shows a designed "temporarily unavailable" state and stops polling.
**Rounds (epochs).** Battles run on a deterministic global clock: `epoch = floor(now / EPOCH_MS)` with `EPOCH_MS` defaulting to 1 hour. Every serverless instance agrees on the current round without coordination. Matchmaking rotates the member-ranked pool by an epoch-derived hash (so the top seed does not always meet the second) and folds it into adjacent pairs; an odd count gives the lowest seed a bye. The previous round is settled lazily on each `state` read (claimed once via a Redis `SET NX`, so it is idempotent and needs no cron): faction powers are re-read, the bracket is recomputed from the power-ranked pool (so final pairings can differ from the member-ranked view shown live), and each battle is decided on raw power (higher wins, equal draws, both-zero writes no record). Win, loss, draw, and lifetime power fold into a permanent `clash:record` hash.
@@ -67,7 +67,7 @@ Coin Clash is also driveable over MCP through `@three-ws/clash-mcp`: `get_clash_
- **Auth.** Viewing needs no login. Enlisting requires a connected Solana wallet and a message signature; rallying requires a valid war pass.
- **Rate limits.** Enlist and enlist-verify are limited to 20 per 5 minutes per IP; rally is 40 per minute per wallet; state and leaderboard are 120 per minute per IP.
- **Pass expiry.** A war pass lives 30 minutes; after that rally returns `401 pass_invalid` and the client transparently re-enlists if the wallet is still connected. Switching wallets drops the enlistment and prompts a re-enlist.
-- **Empty and degraded states.** Fewer than 2 active communities shows "No battles live right now" with a link to `/communities`; a bye faction is labeled. An unconfigured community source shows a temporarily-unavailable state and stops polling. A request that never reaches the server (offline, blocked fetch) surfaces as a named connection error, "Couldn't reach the battle server", instead of the browser's raw "Failed to fetch". A Redis outage degrades silently to per-instance tallies and still serves 200s.
+- **Empty and degraded states.** Fewer than 2 active communities shows "No battles live right now" with a link to `/communities`; a bye faction is labeled. An unconfigured community source seeds the round from the trending feed (noted above the bracket); only when that feed is down too does the page show a temporarily-unavailable state and stop polling. A request that never reaches the server (offline, blocked fetch) surfaces as a named connection error, "Couldn't reach the battle server", instead of the browser's raw "Failed to fetch". A Redis outage degrades silently to per-instance tallies and still serves 200s.
- **Validation.** Taps must be a positive integer and are clamped to 50 per call. The ambient particle field is skipped under `prefers-reduced-motion`.
## Related
diff --git a/docs/ops/gcp-production.md b/docs/ops/gcp-production.md
index 1780e81e6..d47e80382 100644
--- a/docs/ops/gcp-production.md
+++ b/docs/ops/gcp-production.md
@@ -460,7 +460,7 @@ only on Vercel, was never carried to Cloud Run, and nothing alerted. Restored
| Ops-alert Telegram push | `TELEGRAM_ALERTS_CHAT_ID` | `api/_lib/alerts.js` degrades to table-only (`ops_alerts`): no push notification for treasury-low, balance-floor, or breach alerts. This is why the 10-day Money Pulse flatline never pinged anyone. `TELEGRAM_BOT_TOKEN` survived; only the private ops chat id was lost in the migration. | Owner supplies the private ops chat/DM id (never the public holders' channel) and applies `--update-env-vars TELEGRAM_ALERTS_CHAT_ID=<id>`. |
| Collection authority | `SOLANA_AGENT_COLLECTION_AUTHORITY_KEY` | Agent NFT collection ops can't sign | Intentionally excluded from `scripts/wire-master-wallet.mjs` (on-chain update authority must stay its original wallet). Owner holds the key. |
| R2/S3 storage creds | `S3_ENDPOINT`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_BUCKET`, `S3_PUBLIC_DOMAIN` | `/api/marketplace`, `/api/explore`, `/api/avatars/:id` — every route that resolves an asset URL — 503 `not_configured` | Real values already sit in the repo's `.env.local` (never committed). Apply with `scripts/gcp/apply-s3-env.sh` (needs a human-authed `gcloud auth login` first — the 89-var apply is still blocked on reauth per above). |
-| CoinCommunities API key | `CC_API_KEY` | `/api/clash/state` 503s `cc_unconfigured` (`api/_lib/coin-communities.js`); Town chat renders its designed locked state. `/api/community/worlds` no longer dies: it fails over to the live pump.fun trending feed (`api/_lib/pump-trending.js`) and tags the response `source: "pump-trending"`, so the world picker stays alive. The Play holders gate shows its `unavailable` state ("Holder check is offline") and offers a one-click path into the coin's open world, so a gated world is never a dead end. | Keys are provisioned manually by the CoinCommunities team (their docs say "contact support": no self-serve signup, and the SDK's `business/register` endpoints are not deployed on `api.coin-communities.xyz`). Owner outreach to @CoinComms required; set `CC_API_KEY` (+ optional `CC_SERVER_KEY`/`CC_SERVER_SECRET`) on the Cloud Run service when granted. |
+| CoinCommunities API key | `CC_API_KEY` | Town chat renders its designed locked state. `/api/community/worlds` and `/api/clash/state` + `/api/clash/leaderboard` no longer die: they fail over to the live pump.fun trending feed (`api/_lib/pump-trending.js`) and tag the response `source: "pump-trending"`, so the world picker and the Clash arena stay alive (the Clash roster is frozen per round). The Play holders gate shows its `unavailable` state ("Holder check is offline") and offers a one-click path into the coin's open world, so a gated world is never a dead end. | Keys are provisioned manually by the CoinCommunities team (their docs say "contact support": no self-serve signup, and the SDK's `business/register` endpoints are not deployed on `api.coin-communities.xyz`). Owner outreach to @CoinComms required; set `CC_API_KEY` (+ optional `CC_SERVER_KEY`/`CC_SERVER_SECRET`) on the Cloud Run service when granted. |
| x402 ring payer USDC float | — (not a var: an on-chain balance) | The autonomous loop's payer wallet holds $0 USDC, so every paid call is skipped. Since 2026-07-09 this manifested as ~1 failed settle/minute (`broadcast_failed:Simulation failed`); the loop now skips paid calls instead. Free + monitoring entries are unaffected. | Send USDC to the payer wallet (`X402_SEED_SOLANA_SECRET_BASE58`'s pubkey). Floor is `X402_RING_PAYER_USDC_FLOOR_ATOMIC` (default $5) — fund meaningfully above it or it re-drains. See **x402 ring payer float** below. |
### x402 ring payer float — why an empty wallet used to storm Solana
diff --git a/src/clash.css b/src/clash.css
index 4c7f899cb..157fa03b7 100644
--- a/src/clash.css
+++ b/src/clash.css
@@ -291,6 +291,12 @@
/* The "b" side accents flip to the cool color for clarity */
.cl-side-b .cl-fight.is-mine { background: color-mix(in srgb, var(--accent) 22%, transparent); border-color: var(--accent); }
+.cl-source {
+ margin: 0;
+ text-align: center;
+ color: var(--ink-dim);
+ font: 500 var(--text-sm, 12px) / 1.4 var(--font-body);
+}
.cl-bye {
text-align: center;
color: var(--ink-faint);
diff --git a/src/clash.js b/src/clash.js
index cbb020bae..89f1d127c 100644
--- a/src/clash.js
+++ b/src/clash.js
@@ -71,6 +71,13 @@ function fmtTime(ms) {
}
return `${m}:${String(r).padStart(2, '0')}`;
}
+// A faction's headline stat. Community rosters carry member counts; a round
+// seeded from the trending feed (social: false) has none, so it shows the coin's
+// market cap instead of a misleading "0 members".
+function factionStat(f) {
+ if (f.social === false) return f.marketCapUsd ? `$${fmtNum(f.marketCapUsd)} mcap` : 'trending now';
+ return `${fmtNum(f.members)} members`;
+}
function fmtUsd(n) {
n = Number(n) || 0;
if (n <= 0) return '';
@@ -127,6 +134,11 @@ function renderArena(data) {
const mine = game.enlist?.token || null;
const frag = document.createDocumentFragment();
+ if (data.source === 'pump-trending') {
+ frag.appendChild(
+ el('p', { class: 'cl-source', text: 'This round’s armies are the coins trending on Solana right now, in trending order.' }),
+ );
+ }
for (const bt of data.arena) {
frag.appendChild(battleCard(bt, mine));
}
@@ -146,7 +158,7 @@ function sideBlock(side, which, mine) {
return el('div', { class: `cl-side cl-side-${which}` }, [
avatar(side),
el('span', { class: 'cl-sym', text: side.symbol || short(side.token) }),
- el('span', { class: 'cl-meta', text: `${fmtNum(side.members)} members${side.priceUsd ? ` · ${fmtUsd(side.priceUsd)}` : ''}` }),
+ el('span', { class: 'cl-meta', text: `${factionStat(side)}${side.priceUsd ? ` · ${fmtUsd(side.priceUsd)}` : ''}` }),
el('span', { class: 'cl-rec', html: `<b>${rec.w}W</b> · <i>${rec.l}L</i>` }),
el('button', {
class: `cl-fight${isMine ? ' is-mine' : ''}`,
@@ -282,7 +294,7 @@ async function renderStandings() {
avatar(f),
el('div', {}, [
el('span', { class: 'cl-sym', text: f.symbol || short(f.token) }),
- el('small', { text: `${fmtNum(f.members)} members · ${fmtNum(f.power)} lifetime power` }),
+ el('small', { text: `${factionStat(f)} · ${fmtNum(f.power)} lifetime power` }),
]),
]),
el('span', { class: 'cl-wl', html: `<b>${f.w}W</b> · <i>${f.l}L</i>${f.d ? ` · ${f.d}D` : ''}` }),
diff --git a/tests/clash-roster-failover.test.js b/tests/clash-roster-failover.test.js
new file mode 100644
index 000000000..047bb2751
--- /dev/null
+++ b/tests/clash-roster-failover.test.js
@@ -0,0 +1,142 @@
+/**
+ * Coin Clash roster failover tests.
+ *
+ * /clash must stay playable without a CoinCommunities key: when CC is
+ * unconfigured (or its upstream errors) GET /api/clash/state and
+ * /api/clash/leaderboard seed the round from the live trending feed instead of
+ * answering 503. That roster is frozen for the round, so a trending feed that
+ * reorders between polls cannot re-pair battles mid-round. The original error
+ * envelopes surface only when the trending feed is ALSO unavailable.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+delete process.env.UPSTASH_REDIS_REST_URL;
+delete process.env.UPSTASH_REDIS_REST_TOKEN;
+
+vi.mock('../api/_lib/rate-limit.js', () => {
+ const ok = vi.fn(async () => ({ success: true, reset: Date.now() + 60_000 }));
+ return { limits: { clashStateIp: ok, clashEnlistIp: ok, clashRallyIp: ok }, clientIp: () => '127.0.0.1' };
+});
+
+vi.mock('../api/_lib/balances.js', () => ({
+ getBalances: vi.fn(async () => ({ native: 0, tokens: [] })),
+ solanaMintUsdPrice: vi.fn(async () => 0),
+}));
+
+const ccState = { configured: false, communities: null, apiError: null };
+vi.mock('../api/_lib/coin-communities.js', async () => {
+ const actual = await vi.importActual('../api/_lib/coin-communities.js');
+ return {
+ ...actual,
+ cc: vi.fn(() => {
+ if (!ccState.configured) throw new actual.UnconfiguredError();
+ return {
+ getTopCommunities: async () =>
+ ccState.apiError
+ ? { data: null, error: ccState.apiError }
+ : { data: { communities: ccState.communities ?? [] }, error: null },
+ };
+ }),
+ };
+});
+
+const trending = { data: null };
+vi.mock('../api/_lib/pump-trending.js', () => ({
+ getTrendingSlim: vi.fn(async (limit) => ({ data: trending.data ? trending.data.slice(0, limit) : null, stale: false })),
+}));
+
+const { default: handler } = await import('../api/clash/[action].js');
+
+const mint = (c) => `THREEsynthetic111111111111111111111111${c}`;
+const row = (c, i) => ({
+ mint: mint(c),
+ symbol: `T${c}`,
+ name: `Synthetic ${c}`,
+ logo: null,
+ price_usd: null,
+ usd_market_cap: 1_000_000 * (i + 1),
+ rank: i + 1,
+});
+
+async function call(action) {
+ const res = { statusCode: 200, _h: {} };
+ res.setHeader = (k, v) => {
+ res._h[k] = v;
+ };
+ res.getHeader = (k) => res._h[k];
+ res.end = (b) => {
+ res._b = b;
+ };
+ res.json = () => JSON.parse(res._b);
+ const req = {
+ method: 'GET',
+ url: `/api/clash/${action}`,
+ query: { action },
+ headers: { origin: 'https://three.ws' },
+ socket: { remoteAddress: '127.0.0.1' },
+ };
+ await handler(req, res);
+ return res;
+}
+
+const sideTokens = (data) => data.arena.flatMap((b) => [b.a.token, b.b?.token]).filter(Boolean).sort();
+
+beforeEach(() => {
+ ccState.configured = false;
+ ccState.communities = null;
+ ccState.apiError = null;
+ trending.data = null;
+});
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('clash roster without CoinCommunities', () => {
+ it('seeds the round from trending instead of answering 503', async () => {
+ trending.data = ['A', 'B', 'C', 'D'].map(row);
+ const res = await call('state');
+ expect(res.statusCode).toBe(200);
+ const { data } = res.json();
+ expect(data.source).toBe('pump-trending');
+ expect(data.factionCount).toBe(4);
+ expect(sideTokens(data)).toEqual(['A', 'B', 'C', 'D'].map(mint).sort());
+ const side = data.arena[0].a;
+ expect(side.social).toBe(false);
+ expect(side.marketCapUsd).toBeGreaterThan(0);
+ });
+
+ it('keeps the round roster frozen when trending reorders mid-round', async () => {
+ trending.data = ['E', 'F', 'G', 'H'].map(row);
+ const first = (await call('state')).json().data;
+ trending.data = ['J', 'K', 'L', 'M'].map(row);
+ const second = (await call('state')).json().data;
+ expect(second.epoch).toBe(first.epoch);
+ expect(sideTokens(second)).toEqual(sideTokens(first));
+ });
+
+ it('serves the leaderboard from the same frozen roster', async () => {
+ const res = await call('leaderboard');
+ expect(res.statusCode).toBe(200);
+ const { data } = res.json();
+ expect(data.source).toBe('pump-trending');
+ expect(data.board.length).toBeGreaterThan(0);
+ expect(data.board.every((f) => f.social === false)).toBe(true);
+ });
+});
+
+describe('clash roster with CoinCommunities', () => {
+ it('prefers CC communities and tags them coincommunities', async () => {
+ ccState.configured = true;
+ ccState.communities = [
+ { tokenAddress: mint('N'), tokenSymbol: 'TN', memberCount: 40 },
+ { tokenAddress: mint('P'), tokenSymbol: 'TP', memberCount: 12 },
+ ];
+ const res = await call('state');
+ expect(res.statusCode).toBe(200);
+ const { data } = res.json();
+ expect(data.source).toBe('coincommunities');
+ expect(sideTokens(data)).toEqual([mint('N'), mint('P')].sort());
+ expect(data.arena[0].a.social).toBe(true);
+ });
+});
diff --git a/tests/text-to-image-fallbacks.test.js b/tests/text-to-image-fallbacks.test.js
index 27d3ad728..b0be8d815 100644
--- a/tests/text-to-image-fallbacks.test.js
+++ b/tests/text-to-image-fallbacks.test.js
@@ -96,3 +96,37 @@ describe('the ladder reaches every rung in order', () => {
expect(persisted.calls).toBe(0);
});
});
+
+// On 2026-10-08 NIM FLUX filtered a rocket-booster prompt: HTTP 200, a solid
+// black 1024x1024 JPEG, and the verdict only in finishReason. The black frame
+// became the reference image and TRELLIS, Hunyuan3D and TripoSG all crashed on
+// its empty subject mask. A withheld or blank frame must hand off, not ship.
+describe('a filtered NIM frame never becomes the reference image', () => {
+ const sharp = async () => (await import('sharp')).default;
+ const solid = async (rgb) =>
+ (await sharp())({ create: { width: 64, height: 64, channels: 3, background: rgb } }).jpeg().toBuffer();
+
+ it('falls through when NIM reports a content filter', async () => {
+ const black = await solid({ r: 0, g: 0, b: 0 });
+ lane.nim = () => json(200, { artifacts: [{ base64: black.toString('base64'), finishReason: 'CONTENT_FILTERED' }] });
+ const out = await textToImage('a fox', { budgetMs: 20_000 });
+ expect(out.model).toBe('pollinations/flux');
+ });
+
+ it('falls through on a blank frame even when finishReason claims success', async () => {
+ const black = await solid({ r: 0, g: 0, b: 0 });
+ lane.nim = () => json(200, { artifacts: [{ base64: black.toString('base64'), finishReason: 'SUCCESS' }] });
+ const out = await textToImage('a fox', { budgetMs: 20_000 });
+ expect(out.model).toBe('pollinations/flux');
+ });
+
+ it('still serves a real image from NIM', async () => {
+ const { isBlankFrame } = await import('../api/_mcp3d/text-to-image.js');
+ const s = await sharp();
+ const gradient = await s(Buffer.from(Array.from({ length: 64 * 64 * 3 }, (_, i) => (i * 7) % 256)), { raw: { width: 64, height: 64, channels: 3 } }).jpeg().toBuffer();
+ expect(await isBlankFrame(gradient)).toBe(false);
+ lane.nim = () => json(200, { artifacts: [{ base64: gradient.toString('base64'), finishReason: 'SUCCESS' }] });
+ const out = await textToImage('a fox', { budgetMs: 20_000 });
+ expect(out.model).toBe('black-forest-labs/flux.1-dev');
+ });
+});