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(docs): correct comments for clarity and consistency across multiple files

nirholasdf0b7210a4b2
diff --git a/api/club/tips-stream.js b/api/club/tips-stream.js
index 6b2fc22b2..2f268f89b 100644
--- a/api/club/tips-stream.js
+++ b/api/club/tips-stream.js
@@ -1,4 +1,4 @@
-// GET /api/club/tips/stream — Server-Sent Events
+// GET /api/club/tips/stream: Server-Sent Events
//
// Tails the club_tips table and pushes every new row as a `tip` event. The
// /club page subscribes on boot so two simultaneous visitors see each other's
@@ -12,7 +12,7 @@
// instance regardless of connection count.
//
// ── Adaptive cadence ─────────────────────────────────────────────────────────
-// Tips are bursty — seconds of frenetic activity, then long silences. After
+// Tips are bursty: seconds of frenetic activity, then long silences. After
// IDLE_RAMP_AFTER consecutive empty polls the interval ramps from POLL_MS_MIN
// (800ms) up to POLL_MS_MAX (5s). Any tip row immediately resets the interval
// back to fast. This cuts steady-state Neon reads by ~6× vs fixed 800ms polling.
@@ -28,7 +28,7 @@ import { cors, method } from '../_lib/http.js';
const clients = new Set();
let pollTimer = null;
// Compound cursor (created_at, ticket_id). A plain `created_at >` cursor drops
-// tips that share an identical timestamp at the LIMIT boundary — realistic under
+// tips that share an identical timestamp at the LIMIT boundary, realistic under
// the bursts this stream exists for. The unique ticket_id breaks ties so the
// cursor is strictly monotonic and lossless. Empty id sorts before any ticket.
let sharedCursor = new Date();
diff --git a/api/club/tips.js b/api/club/tips.js
index 22a3e420d..cd6babebd 100644
--- a/api/club/tips.js
+++ b/api/club/tips.js
@@ -1,7 +1,7 @@
// GET /api/club/tips?limit=&dancer=
//
// Returns the most-recent tip events written by /api/x402/dance-tip. Powers
-// the initial render of the /club "Live tips" widget on page boot — the SSE
+// the initial render of the /club "Live tips" widget on page boot; the SSE
// channel at /api/club/tips/stream takes over for live updates.
import { sql } from '../_lib/db.js';
diff --git a/api/cron/x402-seed-cron.js b/api/cron/x402-seed-cron.js
index 40c2c8e65..83ba0dd0f 100644
--- a/api/cron/x402-seed-cron.js
+++ b/api/cron/x402-seed-cron.js
@@ -19,15 +19,14 @@
// X402_SEED_ENABLED set to 'false' to pause (default: enabled)
// X402_SEED_BATCH_SIZE calls per tick (default: 60)
-import { readFileSync } from 'node:fs';
-import bs58 from 'bs58';
-import {
- PublicKey, Keypair, TransactionMessage, VersionedTransaction,
- ComputeBudgetProgram,
-} from '@solana/web3.js';
+// The transactions come from the ONE shared ring payment builder
+// (api/_lib/x402/pay.js), whose nonce-based (priority price, CU limit) spread
+// keeps every batch member byte-distinct; this cron previously carried a forked
+// copy that only accepted base58 keys and priced fees above the ring floor.
+
+import { PublicKey } from '@solana/web3.js';
import {
- getAssociatedTokenAddressSync, createTransferCheckedInstruction,
- createAssociatedTokenAccountIdempotentInstruction,
+ getAssociatedTokenAddressSync,
TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID, getMint,
} from '@solana/spl-token';
@@ -37,6 +36,9 @@ import { getRedis, isRedisAuthError } from '../_lib/redis.js';
import { solanaConnection } from '../_lib/solana/connection.js';
import { logger } from '../_lib/usage.js';
import { SPONSOR_SOL_FLOOR_LAMPORTS } from '../_lib/x402/self-facilitator.js';
+import {
+ loadSeedKeypair, fetchWithTimeout, parseSolanaAccept, buildPaymentTx,
+} from '../_lib/x402/pay.js';
import { readPayerUsdcAtomic } from './x402-autonomous-loop.js';
import { requireCron } from '../_lib/cron-auth.js';
@@ -45,7 +47,6 @@ const log = logger('x402-seed-cron');
const ORIGIN = () => env.APP_ORIGIN || 'https://three.ws';
const USDC_MINT = env.X402_ASSET_MINT_SOLANA;
const SOLANA_RPC = env.SOLANA_RPC_URL;
-const FETCH_TIMEOUT_MS = 20_000;
// Mirror of x402-pay.js FEED_KEY so our seeded payments appear on the /pay feed.
const FEED_KEY = 'x402:pay:feed';
@@ -57,112 +58,10 @@ const STYLES = [
'twerk', 'spin', 'climb', 'combo',
];
-function loadSeedKeypair() {
- // Dedicated seeder key — allows a separate wallet funded only for seeding
- // without touching the shared agent/demo wallet.
- const b58 = process.env.X402_SEED_SOLANA_SECRET_BASE58
- || process.env.X402_AGENT_SOLANA_SECRET_BASE58;
- if (b58) {
- const raw = bs58.decode(b58);
- if (raw.length !== 64) throw new Error(`seed keypair decoded to ${raw.length} bytes; expected 64`);
- return Keypair.fromSecretKey(raw);
- }
- // Local dev fallback — same path x402-pay.js uses.
- if (process.env.NODE_ENV !== 'production') {
- try {
- const arr = JSON.parse(readFileSync('/home/codespace/.config/x402-test-wallets/solana.json', 'utf8'));
- return Keypair.fromSecretKey(Uint8Array.from(arr));
- } catch { /* fall through */ }
- }
- throw new Error('seed keypair not configured (set X402_SEED_SOLANA_SECRET_BASE58)');
-}
-
// Pick a random element from an array.
function pick(arr) { return arr[Math.floor(Math.random() * arr.length)]; }
-// Fetch one JSON endpoint — short timeout, returns { ok, status, body }.
-async function fetchJson(url, opts = {}) {
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
- try {
- const res = await fetch(url, {
- ...opts,
- signal: controller.signal,
- headers: { 'user-agent': 'threews-x402-seed/1.0', ...opts.headers },
- });
- let body = null;
- const ct = res.headers.get('content-type') || '';
- if (ct.includes('application/json')) {
- try { body = await res.json(); } catch { /* non-JSON */ }
- } else {
- const text = await res.text();
- try { body = JSON.parse(text); } catch { body = text; }
- }
- return { ok: res.ok, status: res.status, body };
- } finally {
- clearTimeout(timer);
- }
-}
-
// Parse a 402 challenge body to find the Solana accept entry.
-function parseSolanaAccept(challengeBody) {
- if (!challengeBody || !Array.isArray(challengeBody.accepts)) return null;
- return challengeBody.accepts.find(
- (a) => typeof a?.network === 'string' && a.network.startsWith('solana'),
- ) || null;
-}
-
-// Build and sign a USDC TransferChecked versioned transaction for x402.
-// Caller provides a pre-fetched blockhash and mint to avoid per-call RPCs.
-export function buildPaymentTx({ accept, buyer, blockhash, mintInfo, receiverAtaExists, index = 0 }) {
- const mint = new PublicKey(accept.asset);
- const payTo = new PublicKey(accept.payTo);
- const feePayer = new PublicKey(accept.extra.feePayer);
- const amount = BigInt(accept.amount);
-
- const senderAta = getAssociatedTokenAddressSync(
- mint, buyer.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
- );
- const receiverAta = getAssociatedTokenAddressSync(
- mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
- );
-
- const ixs = [
- ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),
- // The priority fee is what makes each transaction in a batch DISTINCT, and
- // it has to be: every other input (blockhash, amount, accounts, decimals) is
- // identical across the batch, so a fixed price made all N transactions
- // byte-identical. Identical bytes mean one signature, and the paid endpoint
- // derives paymentId by hashing the payment proof, so the whole batch
- // collided on a single id: one call landed and the rest 409'd on
- // writeConflict, while any that raced past the guard hit the chain as a
- // duplicate signature and settled as `broadcast_failed` with empty
- // simulation logs. Measured 2026-07-30: ~40 of 41 calls per tick lost, the
- // single largest source of 4xx on the fleet at 2,403/hour.
- // Cost of the spread is negligible: 60k CU * N microLamports is 0.06*N
- // lamports, so a full batch adds a few lamports in total.
- ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 + index }),
- ];
- if (!receiverAtaExists) {
- ixs.push(createAssociatedTokenAccountIdempotentInstruction(
- feePayer, receiverAta, payTo, mint,
- TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
- ));
- }
- ixs.push(createTransferCheckedInstruction(
- senderAta, mint, receiverAta, buyer.publicKey,
- amount, mintInfo.decimals, [], TOKEN_PROGRAM_ID,
- ));
-
- const message = new TransactionMessage({
- payerKey: feePayer,
- recentBlockhash: blockhash,
- instructions: ixs,
- }).compileToV0Message();
- const vtx = new VersionedTransaction(message);
- vtx.sign([buyer]);
- return Buffer.from(vtx.serialize()).toString('base64');
-}
/**
* Decide what a tick should actually send, from the two wallet balances that
@@ -252,7 +151,9 @@ export default wrapCron(async (req, res) => {
// ── Step 1: probe dance-tip for live payment requirements ─────────────────
const probeUrl = `${origin}/api/x402/dance-tip?dancer=1&dance=hiphop`;
- const probe = await fetchJson(probeUrl);
+ const probe = await fetchWithTimeout(probeUrl, {
+ headers: { 'user-agent': 'threews-x402-seed/1.0' },
+ });
if (probe.status !== 402 || !probe.body) {
return json(res, 200, {
ok: false,
@@ -324,9 +225,11 @@ export default wrapCron(async (req, res) => {
}
// ── Step 3: build the signed transactions (synchronous) ───────────────────
+ // The nonce spread is what makes each batch member a distinct transaction;
+ // see ringFeeConfig in api/_lib/x402/pay.js for why it costs ~nothing.
const affordable = plan.batch;
const txBases = Array.from({ length: affordable }, (_, index) =>
- buildPaymentTx({ accept, buyer, blockhash, mintInfo, receiverAtaExists, index }),
+ buildPaymentTx({ accept, buyer, blockhash, mintInfo, receiverAtaExists, nonce: index }),
);
// ── Step 4: fire all in parallel ──────────────────────────────────────────
@@ -348,9 +251,9 @@ export default wrapCron(async (req, res) => {
payload: { transaction: txBase64 },
})).toString('base64');
- return fetchJson(
+ return fetchWithTimeout(
`${origin}/api/x402/dance-tip?dancer=${dancer}&dance=${style}`,
- { headers: { 'X-PAYMENT': xPayment } },
+ { headers: { 'user-agent': 'threews-x402-seed/1.0', 'X-PAYMENT': xPayment } },
).then((r) => ({ ok: r.ok, status: r.status, dancer, style, ticket: r.body }));
}),
);
diff --git a/public/changelog.json b/public/changelog.json
index c8d7b258a..bb72ee999 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-12T06:29:12.259Z",
+ "generated_at": "2026-08-12T06:35:59.245Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
diff --git a/public/features.json b/public/features.json
index e71756fe5..99d8ead7d 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-12T06:29:12.241Z",
+ "generated_at": "2026-08-12T06:35:59.230Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/api/club-presence.test.js b/tests/api/club-presence.test.js
new file mode 100644
index 000000000..0d4baaf24
--- /dev/null
+++ b/tests/api/club-presence.test.js
@@ -0,0 +1,130 @@
+// Tests for POST /api/club/presence: the in-memory viewer counter behind the
+// /club room liveliness number. The rate limiter is mocked so the handler runs
+// in pure-unit mode; module-level session state persists across tests in this
+// file, so count assertions are relative deltas rather than absolutes.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+const rlState = { success: true };
+const ipState = { ip: '10.0.0.1' };
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { clubPresenceIp: vi.fn(async () => rlState) },
+ clientIp: vi.fn(() => ipState.ip),
+}));
+
+const { default: handler } = await import('../../api/club/presence.js');
+
+function makeReq({ method = 'POST', body = null, headers = {} } = {}) {
+ const chunks = body === null ? [] : [JSON.stringify(body)];
+ const r = Readable.from(chunks);
+ r.method = method;
+ r.url = '/api/club/presence';
+ r.headers = { host: 'localhost', 'content-type': 'application/json', ...headers };
+ return r;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ writeHead(status, headers = {}) {
+ this.statusCode = status;
+ for (const [k, v] of Object.entries(headers)) {
+ this.headers[k.toLowerCase()] = v;
+ }
+ },
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ write(chunk) {
+ this.body += chunk;
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ on() {},
+ };
+}
+
+async function invoke(opts = {}) {
+ const req = makeReq(opts);
+ const res = makeRes();
+ await handler(req, res);
+ let payload = null;
+ if (res.body) {
+ try { payload = JSON.parse(res.body); } catch { payload = res.body; }
+ }
+ return { res, status: res.statusCode, body: payload };
+}
+
+beforeEach(() => {
+ rlState.success = true;
+ // Each test gets its own address so earlier tests' sessions never eat into
+ // the per-IP cap this file's last test exercises.
+ ipState.ip = `10.0.0.${Math.floor(Math.random() * 250) + 1}`;
+});
+
+describe('POST /api/club/presence', () => {
+ it('counts a new session and reports it as counted', async () => {
+ const before = await invoke({ body: { session: 'presence-test-base' } });
+ expect(before.status).toBe(200);
+ const { status, body } = await invoke({ body: { session: 'presence-test-main' } });
+ expect(status).toBe(200);
+ expect(body.count).toBe(before.body.count + 1);
+ expect(body.counted).toBe(true);
+ });
+
+ it('renews an existing session without growing the count', async () => {
+ const first = await invoke({ body: { session: 'presence-test-renew' } });
+ const second = await invoke({ body: { session: 'presence-test-renew' } });
+ expect(second.status).toBe(200);
+ expect(second.body.count).toBe(first.body.count);
+ expect(second.body.counted).toBe(true);
+ });
+
+ it('rejects a missing session id with a 400 JSON error', async () => {
+ const { status, body } = await invoke({ body: {} });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('rejects a non-string session id with a 400 JSON error', async () => {
+ const { status, body } = await invoke({ body: { session: 42 } });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('rejects the wrong method with a 405 JSON error', async () => {
+ const { status, body } = await invoke({ method: 'GET' });
+ expect(status).toBe(405);
+ expect(body.error).toBe('method_not_allowed');
+ });
+
+ it('answers 429 with retry-after when the limiter blocks the IP', async () => {
+ rlState.success = false;
+ // The limiter result carries an absolute epoch-ms reset; Retry-After is
+ // derived from it (api/_lib/http.js setRateLimitHeaders).
+ rlState.reset = Date.now() + 30_000;
+ const { res, status, body } = await invoke({ body: { session: 'presence-test-rl' } });
+ expect(status).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ expect(res.headers['retry-after']).toBe('30');
+ });
+
+ it('caps one address at 12 slots and reports the overflow as not counted', async () => {
+ // Fresh address for this test: the cap counts every live session the IP
+ // holds, including any this file added earlier.
+ ipState.ip = '10.77.77.77';
+ for (let i = 0; i < 12; i++) {
+ const r = await invoke({ body: { session: `presence-test-cap-${i}` } });
+ expect(r.body.counted).toBe(true);
+ }
+ const overflow = await invoke({ body: { session: 'presence-test-cap-12' } });
+ expect(overflow.status).toBe(200);
+ expect(overflow.body.counted).toBe(false);
+ });
+});