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): make faction momentum track a real price move and stop re-pricing the arena on every poll

nirholas63921c9c7a95
diff --git a/api/clash/[action].js b/api/clash/[action].js
index 8e0af8313..f8e68c7eb 100644
--- a/api/clash/[action].js
+++ b/api/clash/[action].js
@@ -380,9 +380,9 @@ async function handleLeaderboard(req, res) {
.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');
+ const mintParam = req.query?.faction;
let soldiers = null;
- if (mintParam && isValidToken(mintParam)) {
+ if (isValidToken(mintParam)) {
soldiers = await topSoldiers({ epoch: epochAt(Date.now()), mint: mintParam, limit: 10 });
}
diff --git a/docs/clash.md b/docs/clash.md
index 0ddf5d608..8d2df6429 100644
--- a/docs/clash.md
+++ b/docs/clash.md
@@ -18,7 +18,7 @@ The page (`src/clash.js`) polls `GET /api/clash/state` every 5 seconds (paused w
**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.
-**Momentum.** Each faction carries a bounded vigor bonus between 1.0 and 1.5, blended from social recency, member mass, and a positive pump.fun price move. Missing signals contribute nothing and never block a rally.
+**Momentum.** Each faction carries a bounded vigor bonus between 1.0 and 1.5, blended from social recency, member mass, and a positive price move. The price move is measured from the platform's own samples: each `state` read refreshes a faction's spot price at most once a minute (shared across the fleet through Redis, so an open tab polling every 5 seconds never re-prices anything), and each snapshot keeps a baseline that rolls forward once a day, so the move a faction is credited for spans at most 24 hours. Prices come from Jupiter with the pump.fun bonding curve as failover. Missing signals contribute nothing and never block a rally: a mint nothing can price simply fights on its social signals.
## Token-gating and enlistment
diff --git a/prompts/swarm-100/api-clash-01.md b/prompts/swarm-100/api-clash-01.md
deleted file mode 100644
index 9c426f246..000000000
--- a/prompts/swarm-100/api-clash-01.md
+++ /dev/null
@@ -1,101 +0,0 @@
-# API audit: api/clash batch 01 (1 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/clash/[action].js
-
-For every routed handler:
-
-1. Exercise it with curl against the local server: the success path returns
- real data with the correct status; malformed input returns a 4xx JSON
- error, never a stack trace or an HTML error page; auth is enforced where
- the code intends it; CORS matches neighboring handlers.
-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
- responses, no unfinished markers. Errors are handled at the boundary and
- internal code trusts itself.
-3. Do not spend funds or sign anything on-chain while probing. Payment and
- trading handlers get their validation and error paths exercised, never a
- live settlement.
-
-For every internal (non-routed) module:
-
-4. Something must import it; if nothing does, delete it as dead code (verify
- with a repo-wide grep first).
-5. Its main path and one failure path must be covered in tests/; add the
- missing test if not.
-
-## Definition of done
-
-- [ ] Every listed file has recorded evidence: a curl transcript for routed
- handlers, a passing test or a deletion for internal modules.
-- [ ] Zero hard-rule violations remain in these files.
-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
- exits 0.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/api-clash-01.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/tests/clash-engine.test.js b/tests/clash-engine.test.js
new file mode 100644
index 000000000..3146e3bb7
--- /dev/null
+++ b/tests/clash-engine.test.js
@@ -0,0 +1,226 @@
+// Coin Clash engine (api/_lib/clash.js) - the pure math every stateless
+// instance has to agree on, plus the two secrets the HTTP surface trusts.
+//
+// Matchmaking is derived, not stored: if two boxes disagree on the bracket for
+// a round, one of them settles the wrong battle. The enlist challenge and the
+// war pass are the only things standing between a rally and a forged one, so
+// their tamper paths matter as much as their happy paths.
+import { describe, it, expect } from 'vitest';
+import {
+ epochAt,
+ epochWindow,
+ matchmake,
+ battleId,
+ momentumFactor,
+ buildChallenge,
+ verifyChallenge,
+ signWarPass,
+ verifyWarPass,
+ priceIsStale,
+ rollPrice,
+ priceChangePct,
+ PRICE_SPOT_TTL_MS,
+ PRICE_BASELINE_MS,
+ EPOCH_MS,
+ MOMENTUM_MIN,
+ MOMENTUM_MAX,
+} from '../api/_lib/clash.js';
+
+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const WALLET = '8puvqEvxasTqFWoYT5eVVMDB5Bx7F3ANBuHorJyGYQnz';
+
+describe('epoch math', () => {
+ it('is monotonic and partitions time into fixed rounds', () => {
+ const t = epochAt(1_700_000_000_000) * EPOCH_MS; // aligned to a round start
+ expect(epochAt(t + EPOCH_MS)).toBe(epochAt(t) + 1);
+ expect(epochAt(t)).toBe(epochAt(t + EPOCH_MS - 1));
+ });
+
+ it('reports the window and the time left inside it', () => {
+ const epoch = epochAt(Date.now());
+ const start = epoch * EPOCH_MS;
+ const { end, msLeft } = epochWindow(epoch, start + 1000);
+ expect(end).toBe(start + EPOCH_MS);
+ expect(msLeft).toBe(EPOCH_MS - 1000);
+ });
+
+ it('clamps msLeft at zero once the round is over', () => {
+ const epoch = epochAt(Date.now());
+ expect(epochWindow(epoch, epoch * EPOCH_MS + EPOCH_MS * 2).msLeft).toBe(0);
+ });
+});
+
+describe('matchmaking', () => {
+ const pool = ['a', 'b', 'c', 'd', 'e', 'f'];
+
+ it('is deterministic for a given roster and round', () => {
+ expect(matchmake(pool, 99)).toEqual(matchmake(pool, 99));
+ });
+
+ it('pairs everyone exactly once with no bye on an even roster', () => {
+ const { battles, bye } = matchmake(pool, 7);
+ expect(bye).toBeNull();
+ expect(battles).toHaveLength(3);
+ expect(battles.flatMap((b) => [b.a, b.b]).sort()).toEqual([...pool].sort());
+ });
+
+ it('leaves exactly one faction with a bye on an odd roster', () => {
+ const { battles, bye } = matchmake(pool.slice(0, 5), 7);
+ expect(bye).toBeTruthy();
+ expect(battles.flatMap((b) => [b.a, b.b])).not.toContain(bye);
+ });
+
+ it('rotates matchups across rounds instead of freezing one bracket', () => {
+ const seen = new Set();
+ for (let e = 0; e < 20; e++) {
+ seen.add(JSON.stringify(matchmake(pool, e).battles.map((b) => b.id)));
+ }
+ expect(seen.size).toBeGreaterThan(1);
+ });
+
+ it('a roster too small to fight yields no battles', () => {
+ expect(matchmake(['solo'], 1)).toEqual({ battles: [], bye: 'solo' });
+ expect(matchmake([], 1)).toEqual({ battles: [], bye: null });
+ });
+
+ it('battle ids are order-independent so both sides resolve the same key', () => {
+ expect(battleId(5, 'a', 'b')).toBe(battleId(5, 'b', 'a'));
+ expect(battleId(5, 'a', 'b')).not.toBe(battleId(6, 'a', 'b'));
+ });
+});
+
+describe('momentum factor', () => {
+ it('a faction with no signals fights at the floor', () => {
+ expect(momentumFactor({})).toBe(MOMENTUM_MIN);
+ });
+
+ it('stays inside the band even when every signal is maxed', () => {
+ const f = momentumFactor({ members: 1e9, latestPostAt: Date.now(), priceChange: 5000 });
+ expect(f).toBeLessThanOrEqual(MOMENTUM_MAX);
+ expect(f).toBeGreaterThan(MOMENTUM_MIN);
+ });
+
+ it('a live market move raises the factor', () => {
+ const base = { members: 500, latestPostAt: Date.now() };
+ expect(momentumFactor({ ...base, priceChange: 40 })).toBeGreaterThan(momentumFactor(base));
+ });
+
+ it('a dump never drags a faction below the floor', () => {
+ expect(momentumFactor({ priceChange: -90 })).toBe(MOMENTUM_MIN);
+ });
+
+ it('a stale community loses its recency credit', () => {
+ const old = Date.now() - 30 * 24 * 3_600_000;
+ expect(momentumFactor({ latestPostAt: old })).toBeLessThan(
+ momentumFactor({ latestPostAt: Date.now() }),
+ );
+ });
+});
+
+describe('price snapshot', () => {
+ const now = 1_700_000_000_000;
+
+ it('treats a missing or aged snapshot as stale', () => {
+ expect(priceIsStale(null, now)).toBe(true);
+ expect(priceIsStale({ spot: 1, at: now - PRICE_SPOT_TTL_MS }, now)).toBe(true);
+ expect(priceIsStale({ spot: 1, at: now - 1 }, now)).toBe(false);
+ });
+
+ it('seeds the baseline on the first priced sample, so the first move is flat', () => {
+ const snap = rollPrice(null, 0.004, now);
+ expect(snap).toEqual({ spot: 0.004, at: now, base: 0.004, baseAt: now });
+ expect(priceChangePct(snap)).toBe(0);
+ });
+
+ it('measures a later spot against the retained baseline', () => {
+ const seeded = rollPrice(null, 2, now);
+ const later = rollPrice(seeded, 3, now + PRICE_SPOT_TTL_MS);
+ expect(later.base).toBe(2);
+ expect(priceChangePct(later)).toBeCloseTo(50, 6);
+ });
+
+ it('rolls the baseline forward once it is a day old', () => {
+ const seeded = rollPrice(null, 2, now);
+ const rolled = rollPrice(seeded, 3, now + PRICE_BASELINE_MS);
+ expect(rolled.base).toBe(3);
+ expect(rolled.baseAt).toBe(now + PRICE_BASELINE_MS);
+ expect(priceChangePct(rolled)).toBe(0);
+ });
+
+ it('an unpriceable mint keeps no baseline and reports no move', () => {
+ const snap = rollPrice(null, 0, now);
+ expect(snap.base).toBe(0);
+ expect(priceChangePct(snap)).toBeNull();
+ expect(priceChangePct(null)).toBeNull();
+ });
+});
+
+describe('enlist challenge', () => {
+ const now = Date.now();
+
+ it('round-trips a challenge bound to one wallet and one faction', () => {
+ const { message } = buildChallenge({ wallet: WALLET, mint: THREE, now });
+ expect(verifyChallenge({ message, wallet: WALLET, mint: THREE, now })).toBe(true);
+ });
+
+ it('rejects a challenge replayed for another wallet or another faction', () => {
+ const { message } = buildChallenge({ wallet: WALLET, mint: THREE, now });
+ expect(verifyChallenge({ message, wallet: 'someoneElse', mint: THREE, now })).toBe(false);
+ expect(verifyChallenge({ message, wallet: WALLET, mint: 'OtherMint', now })).toBe(false);
+ });
+
+ it('rejects a tampered body even when the tag is left intact', () => {
+ const { message } = buildChallenge({ wallet: WALLET, mint: THREE, now });
+ const tampered = message.replace('soldier:', 'soldiers:');
+ expect(verifyChallenge({ message: tampered, wallet: WALLET, mint: THREE, now })).toBe(false);
+ });
+
+ it('rejects an expired challenge and a future-dated one', () => {
+ const { message } = buildChallenge({ wallet: WALLET, mint: THREE, now });
+ expect(verifyChallenge({ message, wallet: WALLET, mint: THREE, now: now + 6 * 60_000 })).toBe(false);
+ expect(verifyChallenge({ message, wallet: WALLET, mint: THREE, now: now - 5 * 60_000 })).toBe(false);
+ });
+
+ it('rejects anything that is not one of our messages', () => {
+ expect(verifyChallenge({ message: 'sign this', wallet: WALLET, mint: THREE, now })).toBe(false);
+ expect(verifyChallenge({ message: null, wallet: WALLET, mint: THREE, now })).toBe(false);
+ });
+});
+
+describe('war pass', () => {
+ it('round-trips the enlistment the rally path needs', () => {
+ const pass = signWarPass({ wallet: WALLET, mint: THREE, amount: 1234.5, usd: 9.129 });
+ expect(verifyWarPass(pass)).toMatchObject({
+ wallet: WALLET,
+ mint: THREE,
+ amount: 1234.5,
+ usd: 9.13,
+ tier: 'clash',
+ });
+ });
+
+ it('rejects a forged tag, a swapped body, and structural junk', () => {
+ const pass = signWarPass({ wallet: WALLET, mint: THREE });
+ const [body] = pass.split('.');
+ expect(verifyWarPass(`${body}.notthetag`)).toBeNull();
+ expect(verifyWarPass(`X${pass.slice(1)}`)).toBeNull();
+ expect(verifyWarPass('nodot')).toBeNull();
+ expect(verifyWarPass('')).toBeNull();
+ expect(verifyWarPass(null)).toBeNull();
+ });
+
+ it('rejects a pass re-tagged for another surface', () => {
+ const pass = signWarPass({ wallet: WALLET, mint: THREE });
+ const [body, tag] = pass.split('.');
+ const payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
+ const swapped = Buffer.from(JSON.stringify({ ...payload, tier: 'holder' })).toString('base64url');
+ expect(verifyWarPass(`${swapped}.${tag}`)).toBeNull();
+ });
+
+ it('seals an expiry so a dumped holder cannot rally forever', () => {
+ const pass = signWarPass({ wallet: WALLET, mint: THREE });
+ const payload = verifyWarPass(pass);
+ expect(payload.exp).toBeGreaterThan(Math.floor(Date.now() / 1000));
+ expect(payload.exp - payload.iat).toBe(30 * 60);
+ });
+});
diff --git a/tests/clash-store-resilience.test.js b/tests/clash-store-resilience.test.js
index 8b2c63fe8..9c780b79d 100644
--- a/tests/clash-store-resilience.test.js
+++ b/tests/clash-store-resilience.test.js
@@ -11,7 +11,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const boom = () => Promise.reject(Object.assign(new Error('fetch failed'), { name: 'TypeError' }));
const throwingRedis = {
incrby: boom, expire: boom, set: boom, get: boom,
- zincrby: boom, zrange: boom, hmget: boom, hset: boom,
+ zincrby: boom, zrange: boom, zscore: boom, hmget: boom, hset: boom,
};
vi.mock('../api/_lib/redis.js', () => ({ getRedis: () => throwingRedis }));
@@ -47,6 +47,19 @@ describe('clash-store resilience under a Redis outage', () => {
await expect(store.setMomentum(MINT, 1.2)).resolves.toBeUndefined();
});
+ it('factionPower degrades to zero instead of throwing', async () => {
+ await expect(store.factionPower(42, MINT)).resolves.toBe(0);
+ });
+
+ it('the price snapshot degrades to a cache miss and an absorbed write', async () => {
+ await expect(store.getPrice(MINT)).resolves.toBeNull();
+ await expect(
+ store.setPrice(MINT, { spot: 1, at: 2, base: 1, baseAt: 2 }, 60),
+ ).resolves.toBeUndefined();
+ // The write landed in the in-memory model, so the next read still answers.
+ await expect(store.getPrice(MINT)).resolves.toEqual({ spot: 1, at: 2, base: 1, baseAt: 2 });
+ });
+
it('addPower falls back to the in-memory tally instead of throwing', async () => {
const r = await store.addPower({ epoch: 42, mint: MINT, wallet: MINT, amount: 5, walletCap: 100 });
expect(r.added).toBe(5);