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.

test(community): cover world-gate creator proof and ws-ticket minting end to end

nirholas76f015fd7f6e
diff --git a/prompts/swarm-100/api-community-02.md b/prompts/swarm-100/api-community-02.md
deleted file mode 100644
index c9a9315b8..000000000
--- a/prompts/swarm-100/api-community-02.md
+++ /dev/null
@@ -1,103 +0,0 @@
-# API audit: api/community batch 02 (3 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/community/world-gate.js
-- api/community/worlds.js
-- api/community/ws-ticket.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-community-02.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/community-world-gate-endpoint.test.js b/tests/community-world-gate-endpoint.test.js
new file mode 100644
index 000000000..70da6b79d
--- /dev/null
+++ b/tests/community-world-gate-endpoint.test.js
@@ -0,0 +1,288 @@
+/**
+ * GET/POST /api/community/world-gate endpoint tests.
+ *
+ * The world gate (R24) is the one place a coin creator changes who may enter
+ * their Holders world, so the endpoint's job is to be exact about identity: a
+ * read is public and always states the requirement, a write only lands when the
+ * caller's linked Solana wallet IS the coin's on-chain creator, and every way
+ * that check can fail has its own coded answer the gate UI routes on.
+ *
+ * Storage is the real world-gate lib over the in-memory KV fallback (no
+ * UPSTASH_* in the test env), so the read-after-write assertions exercise the
+ * actual persistence path rather than a stand-in.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+const rl = { ok: true };
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: rl.ok, reset: Date.now() + 60_000 })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+// Session state the handler sees: `wallets` are the caller's linked SVM
+// addresses, `signedIn` is the cookie-level "is there a session at all" answer.
+const session = { signedIn: false, wallets: [], walletError: null };
+const ccConfigured = { value: true };
+vi.mock('../api/_lib/coin-communities.js', async () => {
+ const actual = await vi.importActual('../api/_lib/coin-communities.js');
+ return {
+ ...actual,
+ cc: vi.fn(() => {
+ if (!ccConfigured.value) throw new actual.UnconfiguredError();
+ return {
+ getWallets: async () =>
+ session.walletError
+ ? { data: null, error: session.walletError }
+ : {
+ data: {
+ wallets: session.wallets.map((address) => ({ address, chainType: 'svm' })),
+ },
+ error: null,
+ },
+ };
+ }),
+ hasUserSession: vi.fn(() => session.signedIn),
+ withAuthRefresh: vi.fn(async (req, res, call) => {
+ if (!session.signedIn) return { data: null, error: null, headers: null };
+ const headers = { Authorization: 'Bearer test-session' };
+ const result = await call(headers);
+ return { ...result, headers };
+ }),
+ };
+});
+
+const { readWorldGate, writeWorldGate } = await import('../api/_lib/world-gate.js');
+const { default: handler } = await import('../api/community/world-gate.js');
+
+// Synthetic base58 addresses of the right shape: no real mainnet mint or wallet.
+const MINT = 'THREEsynthetic1111111111111111111111111pump';
+const CREATOR = 'THREEcreator11111111111111111111111111wallet';
+const OTHER = 'THREEother111111111111111111111111111wallet';
+const EVM_MINT = '0x1234567890abcdef1234567890abcdef12345678';
+
+// The pump.fun creator lookup, the handler's one outbound HTTP call.
+const pump = { creator: CREATOR, status: 200 };
+let fetchSpy;
+
+function makeReq(httpMethod, { token = MINT, body } = {}) {
+ const req = {
+ method: httpMethod,
+ url: `/api/community/world-gate${token === null ? '' : `?token=${encodeURIComponent(token)}`}`,
+ headers: { origin: 'https://three.ws' },
+ socket: { remoteAddress: '127.0.0.1' },
+ };
+ if (body !== undefined) {
+ req.headers['content-type'] = 'application/json';
+ req.body = body;
+ }
+ return req;
+}
+function makeRes() {
+ const r = { statusCode: 200, _h: {}, _b: null };
+ r.setHeader = (k, v) => { r._h[k] = v; };
+ r.getHeader = (k) => r._h[k];
+ r.end = (b) => { r._b = b; };
+ r.json = () => JSON.parse(r._b);
+ return r;
+}
+async function call(httpMethod, opts) {
+ const res = makeRes();
+ await handler(makeReq(httpMethod, opts), res);
+ return res;
+}
+
+beforeEach(async () => {
+ rl.ok = true;
+ ccConfigured.value = true;
+ session.signedIn = false;
+ session.wallets = [];
+ session.walletError = null;
+ pump.creator = CREATOR;
+ pump.status = 200;
+ await writeWorldGate(MINT, { minTokens: 0 });
+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (url) => ({
+ ok: pump.status === 200 && String(url).includes(`/coins/${MINT}`),
+ status: pump.status,
+ json: async () => ({ creator: pump.creator }),
+ }));
+});
+afterEach(() => {
+ fetchSpy.mockRestore();
+ vi.clearAllMocks();
+});
+
+describe('GET world-gate', () => {
+ it('reads an ungated world publicly, never cached', async () => {
+ const res = await call('GET');
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data).toEqual({ mint: MINT, gated: false, minTokens: 0, canEdit: false });
+ expect(res._h['cache-control']).toBe('no-store');
+ });
+
+ it('reports a stored threshold', async () => {
+ await writeWorldGate(MINT, { minTokens: 250_000 }, CREATOR);
+ const { data } = (await call('GET')).json();
+ expect(data).toMatchObject({ gated: true, minTokens: 250_000 });
+ });
+
+ it('rejects a malformed token', async () => {
+ const res = await call('GET', { token: 'not-a-mint' });
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error).toBe('validation_error');
+ });
+
+ it('rejects a missing token', async () => {
+ const res = await call('GET', { token: null });
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error).toBe('validation_error');
+ });
+
+ it('grants canEdit to the creator', async () => {
+ session.signedIn = true;
+ session.wallets = [CREATOR];
+ expect((await call('GET')).json().data.canEdit).toBe(true);
+ });
+
+ it('withholds canEdit from a signed-in non-creator', async () => {
+ session.signedIn = true;
+ session.wallets = [OTHER];
+ expect((await call('GET')).json().data.canEdit).toBe(false);
+ });
+
+ it('still serves the requirement when the creator lookup fails', async () => {
+ session.signedIn = true;
+ session.wallets = [CREATOR];
+ pump.status = 502;
+ await writeWorldGate(MINT, { minTokens: 42 }, CREATOR);
+ const { data } = (await call('GET')).json();
+ expect(data).toMatchObject({ gated: true, minTokens: 42, canEdit: false });
+ });
+
+ it('skips the upstream lookups entirely when signed out', async () => {
+ await call('GET');
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST world-gate', () => {
+ it('writes a creator-set threshold and persists it', async () => {
+ session.signedIn = true;
+ session.wallets = [CREATOR];
+ const res = await call('POST', { body: { minTokens: 5000 } });
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data).toEqual({ mint: MINT, gated: true, minTokens: 5000 });
+ expect(await readWorldGate(MINT)).toMatchObject({ minTokens: 5000, setBy: CREATOR });
+ });
+
+ it('clears the gate on minTokens 0', async () => {
+ session.signedIn = true;
+ session.wallets = [CREATOR];
+ await writeWorldGate(MINT, { minTokens: 5000 }, CREATOR);
+ const res = await call('POST', { body: { minTokens: 0 } });
+ expect(res.json().data).toEqual({ mint: MINT, gated: false, minTokens: 0 });
+ expect(await readWorldGate(MINT)).toBeNull();
+ });
+
+ it('recognizes a creator wallet linked after the first few', async () => {
+ session.signedIn = true;
+ session.wallets = [
+ 'THREEw1111111111111111111111111111111wallet',
+ 'THREEw2111111111111111111111111111111wallet',
+ 'THREEw3111111111111111111111111111111wallet',
+ 'THREEw4111111111111111111111111111111wallet',
+ 'THREEw5111111111111111111111111111111wallet',
+ CREATOR,
+ ];
+ const res = await call('POST', { body: { minTokens: 10 } });
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data.minTokens).toBe(10);
+ });
+
+ it('401s without a session', async () => {
+ const res = await call('POST', { body: { minTokens: 1 } });
+ expect(res.statusCode).toBe(401);
+ expect(res.json().error).toBe('auth_required');
+ });
+
+ it('403s a signed-in user with no linked Solana wallet', async () => {
+ session.signedIn = true;
+ session.wallets = [];
+ const res = await call('POST', { body: { minTokens: 1 } });
+ expect(res.statusCode).toBe(403);
+ expect(res.json().error).toBe('wallet_required');
+ });
+
+ it('403s a non-creator and leaves the gate untouched', async () => {
+ session.signedIn = true;
+ session.wallets = [OTHER];
+ const res = await call('POST', { body: { minTokens: 1 } });
+ expect(res.statusCode).toBe(403);
+ expect(res.json().error).toBe('not_creator');
+ expect(await readWorldGate(MINT)).toBeNull();
+ });
+
+ it('502s when the creator cannot be resolved', async () => {
+ session.signedIn = true;
+ session.wallets = [CREATOR];
+ pump.status = 502;
+ const res = await call('POST', { body: { minTokens: 1 } });
+ expect(res.statusCode).toBe(502);
+ expect(res.json().error).toBe('creator_unresolved');
+ });
+
+ it('502s when the wallet read fails upstream', async () => {
+ session.signedIn = true;
+ session.walletError = { message: 'wallets upstream down' };
+ const res = await call('POST', { body: { minTokens: 1 } });
+ expect(res.statusCode).toBe(502);
+ expect(res.json().error).toBe('upstream_error');
+ });
+
+ it('rejects a non-Solana world with a coded, non-retryable answer', async () => {
+ session.signedIn = true;
+ session.wallets = [CREATOR];
+ const res = await call('POST', { token: EVM_MINT, body: { minTokens: 1 } });
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error).toBe('solana_only');
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it('rejects a body that is not JSON', async () => {
+ session.signedIn = true;
+ session.wallets = [CREATOR];
+ const res = await call('POST', { body: 'plain text' });
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error).toBe('validation_error');
+ });
+
+ it('503s when CoinCommunities is unconfigured', async () => {
+ ccConfigured.value = false;
+ const res = await call('POST', { body: { minTokens: 1 } });
+ expect(res.statusCode).toBe(503);
+ expect(res.json().error).toBe('cc_unconfigured');
+ });
+});
+
+describe('transport', () => {
+ it('405s an unsupported method', async () => {
+ const res = await call('DELETE');
+ expect(res.statusCode).toBe(405);
+ expect(res.json().error).toBe('method_not_allowed');
+ });
+
+ it('429s when rate limited', async () => {
+ rl.ok = false;
+ const res = await call('GET');
+ expect(res.statusCode).toBe(429);
+ expect(res.json().error).toBe('rate_limited');
+ });
+
+ it('answers a preflight with the credentialed CORS contract', async () => {
+ const res = makeRes();
+ await handler(makeReq('OPTIONS'), res);
+ expect(res.statusCode).toBe(204);
+ expect(res._h['access-control-allow-methods']).toBe('GET,POST,OPTIONS');
+ expect(res._h['access-control-allow-credentials']).toBe('true');
+ });
+});
diff --git a/tests/community-ws-ticket-endpoint.test.js b/tests/community-ws-ticket-endpoint.test.js
new file mode 100644
index 000000000..8e87a652b
--- /dev/null
+++ b/tests/community-ws-ticket-endpoint.test.js
@@ -0,0 +1,149 @@
+/**
+ * POST /api/community/ws-ticket endpoint tests.
+ *
+ * The ticket is what lets the browser open a realtime socket to
+ * CoinCommunities without ever seeing the server's API key, so the contract
+ * that matters is: a valid coin gets a ticket plus the origin to use it
+ * against, the ticket is never cacheable, and every upstream failure mode
+ * answers with its own code instead of leaking the key path or a stack trace.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+const rl = { ok: true };
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: vi.fn(async () => ({ success: rl.ok, reset: Date.now() + 60_000 })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const upstream = { configured: true, ticket: 'tkt_live_abc123', error: null, calledWith: 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 (!upstream.configured) throw new actual.UnconfiguredError();
+ return {
+ getWsTicket: async (args) => {
+ upstream.calledWith = args;
+ return upstream.error
+ ? { data: null, error: upstream.error }
+ : { data: upstream.ticket ? { ticket: upstream.ticket } : {}, error: null };
+ },
+ };
+ }),
+ };
+});
+
+const { default: handler } = await import('../api/community/ws-ticket.js');
+const { ccBaseUrl } = await import('../api/_lib/coin-communities.js');
+
+// Synthetic base58 mint of the right shape: no real mainnet coin.
+const MINT = 'THREEsynthetic1111111111111111111111111pump';
+
+function makeReq(httpMethod = 'POST', token = MINT) {
+ return {
+ method: httpMethod,
+ url: `/api/community/ws-ticket${token === null ? '' : `?token=${encodeURIComponent(token)}`}`,
+ headers: { origin: 'https://three.ws' },
+ socket: { remoteAddress: '127.0.0.1' },
+ };
+}
+function makeRes() {
+ const r = { statusCode: 200, _h: {}, _b: null };
+ r.setHeader = (k, v) => { r._h[k] = v; };
+ r.getHeader = (k) => r._h[k];
+ r.end = (b) => { r._b = b; };
+ r.json = () => JSON.parse(r._b);
+ return r;
+}
+async function call(httpMethod, token) {
+ const res = makeRes();
+ await handler(makeReq(httpMethod, token), res);
+ return res;
+}
+
+beforeEach(() => {
+ rl.ok = true;
+ upstream.configured = true;
+ upstream.ticket = 'tkt_live_abc123';
+ upstream.error = null;
+ upstream.calledWith = null;
+});
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('POST ws-ticket', () => {
+ it('mints a ticket and names the socket origin', async () => {
+ const res = await call('POST');
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data).toEqual({ ticket: 'tkt_live_abc123', baseUrl: ccBaseUrl() });
+ expect(upstream.calledWith).toEqual({ path: { token_address: MINT } });
+ });
+
+ it('never lets a ticket be cached', async () => {
+ const res = await call('POST');
+ expect(res._h['cache-control']).toBe('no-store');
+ });
+
+ it('rejects a malformed token before any upstream call', async () => {
+ const res = await call('POST', 'not-a-mint');
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error).toBe('validation_error');
+ expect(upstream.calledWith).toBeNull();
+ });
+
+ it('rejects a missing token', async () => {
+ const res = await call('POST', null);
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error).toBe('validation_error');
+ });
+
+ it('503s when CoinCommunities is unconfigured', async () => {
+ upstream.configured = false;
+ const res = await call('POST');
+ expect(res.statusCode).toBe(503);
+ expect(res.json().error).toBe('cc_unconfigured');
+ });
+
+ it('502s on an upstream error, surfacing its message', async () => {
+ upstream.error = { message: 'ticket service down' };
+ const res = await call('POST');
+ expect(res.statusCode).toBe(502);
+ expect(res.json()).toMatchObject({
+ error: 'upstream_error',
+ error_description: 'ticket service down',
+ });
+ });
+
+ it('502s when upstream answers without a ticket', async () => {
+ upstream.ticket = '';
+ const res = await call('POST');
+ expect(res.statusCode).toBe(502);
+ expect(res.json().error).toBe('upstream_error');
+ });
+});
+
+describe('transport', () => {
+ it('405s a GET', async () => {
+ const res = await call('GET');
+ expect(res.statusCode).toBe(405);
+ expect(res.json().error).toBe('method_not_allowed');
+ });
+
+ it('429s when rate limited', async () => {
+ rl.ok = false;
+ const res = await call('POST');
+ expect(res.statusCode).toBe(429);
+ expect(res.json().error).toBe('rate_limited');
+ });
+
+ it('answers a preflight with the POST-only CORS contract', async () => {
+ const res = makeRes();
+ await handler(makeReq('OPTIONS'), res);
+ expect(res.statusCode).toBe(204);
+ expect(res._h['access-control-allow-methods']).toBe('POST,OPTIONS');
+ expect(res._h['access-control-allow-origin']).toBe('https://three.ws');
+ });
+});