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(demo): clamp junk page sizes, meter the wallet reader, and wire the lottery share card

nirholas1089ad98b71a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 94715f5f1..b235fc3db 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **The developer dashboard's x402 earnings finally show your real revenue**: The Usage tab on /dashboard/developers has an x402 Payments figure. It read zero for everyone, always, no matter how many paid calls your checkout products had settled: the query behind it looked for columns that do not exist on the receipts table, and the failure was swallowed so the panel reported a confident 0 instead of an error. It now counts settled checkout calls against the products you own and reports both the payment count and the gross in USDC. The rest of the panel got the same treatment: if one of its numbers cannot be read, the response says so by name instead of quietly showing zero. Two more fixes rode along on the developer endpoints: a mistyped webhook or API-key id now comes back as a clean not-found rather than a server error, and registering a webhook for an event type that does not exist is rejected with the list of valid ones instead of silently creating a webhook subscribed to nothing. (`/dashboard/developers`) `[fix, improvement]`
- **The Forge can now federate GPU work to the Livepeer decentralized compute network**: Text-to-3D jobs start by painting a reference image, and that GPU step can now run on the Livepeer network instead of our own lanes, behind a flag, with the same request shape and the same verification our own workers get (safety screening plus byte-level image checks before anything is stored). It ships dark: our measured probe found Livepeer's free public gateway dead at the DNS edge, so the lane goes live only after a funded Studio key lands and clears a 20-job latency, cost, and success comparison run by the new bench script. The full record and the expansion criteria are in the operator docs. `[feature, infra]`
- **The free trending and whale feeds stop going blank under their own traffic**: Ask the trending feed for the 5-minute, 1-hour and 24-hour view back to back and the last two used to come back empty, blaming an upstream outage that was not happening. The cause was our own request volume: each call pulled the trade history of twenty pump.fun coins, and three calls in a row hit pump.fun's rate limiter, which then refused everything for a while. Both feeds now read pump.fun through one shared, short-lived cache, so every window and every caller reuses a single set of pulls instead of re-fetching the same coins, and a repeat call answers in milliseconds. When the limiter does bite, the whale feed serves the last successful pull and marks it stale instead of pretending the market is empty. A token nobody is trading now also reports an honest empty result rather than a false feed-down warning. (`/docs/crypto-api`) `[fix, improvement]`
+- **The lottery demo now shows its own pot in shared previews, and the agent trade demo stopped stalling**: Three repairs to the demo pages. When someone shared the lottery and reflection demo, the preview card was the generic three.ws logo, even though a card built for that page already existed and drew the live lottery pot, the reflection pot and the number of eligible holders. Shared links now show that card, so a preview says what the pot is standing at instead of showing a logo. The two-agent trading demo used to sit through just over two seconds of deliberate pauses that existed only to make the exchange look slower; those are gone, and the steps now appear as the real work behind them finishes. Asking the demo API for a nonsense number of results, such as a page size of zero, a negative number, or a word, returned a server error instead of an answer; those requests now fall back to a sensible page size and return data. The wallet-status reader behind the trading demo is also rate limited now, the same as every other public read on the page, so one caller cannot exhaust the Solana connection everyone shares. (`/demo/coin`) `[fix, improvement]`
- **The open inference network's node endpoints answer again**: The three endpoints an inference node uses to join the network and do work (register, claim a job, submit a result) were unreachable. Two of them pointed at internal files that are not where they looked, so any call returned a server error, and all three asked for a rate-limit budget that was never defined, which would have turned every request away as if the caller had flooded us. Node operators can register, poll for jobs, and submit results as documented. `[fix, infra]`
- **The photo-to-avatar lane is now sized for the 10,000 avatars per day launch target**: The service that turns your selfies into a rigged 3D avatar was measured under real load and one number mattered: it was configured so the autoscaler could never see how busy it was. The service answers each request in milliseconds and does the real work in the background, so the scaling signal looked idle while its processors ground away, and no amount of extra quota would ever have added capacity. The configuration is fixed, and the lane then proved the roadmap's launch target for real: a sustained ten-minute run at the full 10,000-avatars-per-day rate finished every job, with the typical avatar ready in about six seconds and the slowest in under nine. The capacity is there when launch day brings the crowd. `[improvement, infra]`
- **The public custody anchor lookup answers a bad epoch instead of erroring out**: Anyone can look up the on-chain anchor for a Proof-of-Custody epoch at /api/custody/anchor. Ask it for an epoch number too large to be a real round and it used to fail with an internal server error, which reads like the custody service is down rather than like a typo in the request. It now answers a plain "that is not a valid epoch" for malformed input, keeps 404 for an epoch that has not happened yet, and reads the newest epoch with a single lookup instead of pulling the whole integrity aggregate it then threw away. (`/integrity`) `[fix, improvement]`
diff --git a/api/demo/coin/[action].js b/api/demo/coin/[action].js
index 97fb6b71d..4252da498 100644
--- a/api/demo/coin/[action].js
+++ b/api/demo/coin/[action].js
@@ -18,6 +18,7 @@
import { sql } from '../../_lib/db.js';
import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';
+import { parseLimit } from '../../_lib/http-params.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { listActiveCoins, loadCoinByMint } from '../../_lib/coin/index.js';
@@ -198,7 +199,7 @@ async function handleHolder(req, res) {
async function handleHistory(req, res) {
const { coin, err } = await resolveCoin(req);
if (err) return error(res, 404, err, err.replace(/_/g, ' '));
- const limit = Math.min(parseInt(req.query?.limit || '20', 10), 100);
+ const limit = parseLimit(req.query, { fallback: 20, max: 100 });
const fees = await sql`
select payload, tx_signature, created_at
@@ -258,7 +259,7 @@ async function handleHistory(req, res) {
async function handleEvents(req, res) {
const { coin, err } = await resolveCoin(req);
if (err) return error(res, 404, err, err.replace(/_/g, ' '));
- const limit = Math.min(parseInt(req.query?.limit || '50', 10), 200);
+ const limit = parseLimit(req.query, { fallback: 50, max: 200 });
const kind = req.query?.kind?.toString() || null;
const rows = kind
@@ -290,7 +291,7 @@ async function handleEvents(req, res) {
async function handleWinners(req, res) {
const { coin, err } = await resolveCoin(req);
if (err) return error(res, 404, err, err.replace(/_/g, ' '));
- const limit = Math.min(parseInt(req.query?.limit || '20', 10), 100);
+ const limit = parseLimit(req.query, { fallback: 20, max: 100 });
const rows = await sql`
select draw_id, drand_round, pot_lamports::text as pot, winner_wallet,
drand_randomness, tx_signature, status, created_at, paid_at
@@ -318,7 +319,7 @@ async function handleWinners(req, res) {
async function handleHolders(req, res) {
const { coin, err } = await resolveCoin(req);
if (err) return error(res, 404, err, err.replace(/_/g, ' '));
- const limit = Math.min(parseInt(req.query?.limit || '50', 10), 500);
+ const limit = parseLimit(req.query, { fallback: 50, max: 500 });
const rows = await sql`
select wallet, balance::text as balance,
accrued_reflection_lamports::text as accrued,
diff --git a/api/demo/coin/og.js b/api/demo/coin/og.js
index 8e4b179c5..0b2c4771c 100644
--- a/api/demo/coin/og.js
+++ b/api/demo/coin/og.js
@@ -18,7 +18,7 @@ import { ImageResponse } from '@vercel/og';
import { sql } from '../../_lib/db.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { setRateLimitHeaders } from '../../_lib/http.js';
+import { setRateLimitHeaders, wrap } from '../../_lib/http.js';
import { loadCoinByMint, listActiveCoins } from '../../_lib/coin/index.js';
const WIDTH = 1200;
@@ -416,16 +416,23 @@ function imageResponseFor(node, { immutable }) {
}
async function sendImageResponse(res, imageResponse) {
- // Convert Web Response → Node ServerResponse. Headers first, then stream the body.
+ // Convert Web Response → Node ServerResponse. Render the body FIRST: satori can
+ // throw mid-render, and once headers are on the wire the fallback card below can
+ // no longer be substituted (ERR_HTTP_HEADERS_SENT). Buffering first keeps the
+ // failure recoverable.
+ const ab = await imageResponse.arrayBuffer();
+ if (res.headersSent || res.writableEnded) {
+ if (!res.writableEnded) res.end();
+ return;
+ }
for (const [key, value] of imageResponse.headers.entries()) {
res.setHeader(key, value);
}
- const ab = await imageResponse.arrayBuffer();
res.statusCode = imageResponse.status;
res.end(Buffer.from(ab));
}
-export default async function handler(req, res) {
+export default wrap(async (req, res) => {
// CORS for cross-origin embeds (Discord, X, etc. fetch OG images server-side
// but a permissive header doesn't hurt and makes browser-side <img> tags work).
if (req.method === 'OPTIONS') {
@@ -461,7 +468,9 @@ export default async function handler(req, res) {
const drawId = url.searchParams.get('draw') || undefined;
try {
- const coin = mint || (await listActiveCoins()).length === 1 ? await resolveCoin(mint) : null;
+ // resolveCoin already handles both cases (explicit mint, or the single-active-coin
+ // default) and returns null when neither resolves, so it is the whole condition.
+ const coin = await resolveCoin(mint);
if (!coin) {
return sendImageResponse(res, imageResponseFor(brandCard(), { immutable: false }));
}
@@ -498,8 +507,7 @@ export default async function handler(req, res) {
} catch (err) {
// Never let an OG image fail open — fall back to the brand card so
// share previews still look intentional rather than broken-image grey.
- res.statusCode = 200;
- await sendImageResponse(res, imageResponseFor(brandCard(), { immutable: false }));
console.error('[og] render failed:', err?.message || err);
+ await sendImageResponse(res, imageResponseFor(brandCard(), { immutable: false }));
}
-}
+});
diff --git a/api/demo/economy.js b/api/demo/economy.js
index 2db80d3f3..a7032fbc3 100644
--- a/api/demo/economy.js
+++ b/api/demo/economy.js
@@ -25,7 +25,7 @@ import {
LAMPORTS_PER_SOL,
} from '../_lib/avatar-wallet.js';
import { trendingPools } from '../_lib/market/ohlcv.js';
-import { cors, wrap, error } from '../_lib/http.js';
+import { cors, wrap, error, json, rateLimited } from '../_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -109,44 +109,39 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
const url = new URL(req.url, 'http://x');
+ const wantsStatus = url.searchParams.get('status') === '1';
+ const wantsTrade = url.searchParams.get('trade') === '1';
+ if (!wantsStatus && !wantsTrade) {
+ return error(res, 400, 'validation_error', 'use ?status=1 or ?trade=1');
+ }
+
+ // Meter BOTH branches before either runs. Status is not free: it fans out to two
+ // Solana RPC balance reads plus a SOL price lookup on every call, so leaving it
+ // unmetered let any anonymous caller amplify traffic onto our RPC quota. Same
+ // 60/min/IP budget as /api/demo/coin/*.
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
const cfgA = agentAConfig();
const cfgB = agentBConfig();
// ── STATUS: wallet snapshots ──────────────────────────────────────────
- if (url.searchParams.get('status') === '1') {
+ if (wantsStatus) {
const [a, b] = await Promise.all([walletSnapshot(cfgA), walletSnapshot(cfgB)]);
- res.writeHead(200, {
- 'content-type': 'application/json',
- 'access-control-allow-origin': '*',
- });
- res.end(JSON.stringify({ agentA: a, agentB: b, tradeSol: TRADE_SOL }));
- return;
+ return json(res, 200, { agentA: a, agentB: b, tradeSol: TRADE_SOL });
}
// ── TRADE: SSE stream ─────────────────────────────────────────────────
- if (url.searchParams.get('trade') !== '1') {
- res.writeHead(400, { 'content-type': 'application/json' });
- res.end(JSON.stringify({ error: 'use ?status=1 or ?trade=1' }));
- return;
- }
-
// The trade branch signs + sends a REAL on-chain SOL transfer from the
// platform-held trader wallet — never expose that to anonymous callers.
// Read-only callers use ?status=1; the trade stream requires a session
- // cookie or bearer token on top of the per-IP limit below.
+ // cookie or bearer token on top of the per-IP limit above.
const sessionUser = await getSessionUser(req);
const bearerUser = sessionUser ? null : await authenticateBearer(extractBearer(req));
if (!sessionUser && !bearerUser) {
return error(res, 401, 'unauthorized', 'sign in to run the agent-economy trade demo');
}
- const rl = await limits.publicIp(clientIp(req));
- if (!rl.success) {
- res.writeHead(429, { 'content-type': 'application/json' });
- res.end(JSON.stringify({ error: 'rate_limited' }));
- return;
- }
-
sseHeaders(res);
// Phase 1: Agent B initiates request
@@ -155,8 +150,6 @@ export default wrap(async (req, res) => {
text: `Trader agent requesting Solana market intelligence from Oracle. Preparing payment of ${TRADE_SOL} SOL.`,
});
- await delay(900);
-
// Phase 2: payment
let paid = false;
let demoMode = false;
@@ -211,8 +204,6 @@ export default wrap(async (req, res) => {
}
}
- await delay(600);
-
// Phase 3: Oracle fetches + delivers data
emit(res, 'fetching', {
agent: 'A',
@@ -228,16 +219,12 @@ export default wrap(async (req, res) => {
return;
}
- await delay(400);
-
emit(res, 'delivering', {
agent: 'A',
markets,
text: `Oracle delivering ${markets.length} live market signals to Trader.`,
});
- await delay(300);
-
emit(res, 'done', {
markets,
tradeSol: TRADE_SOL,
@@ -250,7 +237,3 @@ export default wrap(async (req, res) => {
res.end();
});
-
-function delay(ms) {
- return new Promise((r) => setTimeout(r, ms));
-}
diff --git a/data/changelog.json b/data/changelog.json
index c823fad84..cd05e41fc 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,25 @@
{
"$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. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-08-12",
+ "title": "Dashboard settings saved at the same moment no longer overwrite each other",
+ "summary": "Your dashboard preferences are kept on the server as well as in the browser, so they follow you to a new device. Several parts of the dashboard save into that one record independently: finishing a guided tour, the walk page saving where you left off, and the settings form saving a toggle or a default network. The server used to read the whole record, merge the new value in, and write the record back, which meant two of those saves landing together would each write a copy of what they had read and the later one would erase the earlier one. Loading the dashboard can fire three of them within the same second, so a tour would reappear or a toggle would quietly revert. The merge now happens inside the database write itself, so every save keeps its own value regardless of what else is being saved at the same instant. Measured on the fix: eight preferences saved simultaneously kept two of eight before, and all eight after. The 16 KB ceiling on stored preferences is unchanged and is now enforced by that same write.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/dashboard/settings"
+ },
+ {
+ "date": "2026-08-12",
+ "title": "The lottery demo now shows its own pot in shared previews, and the agent trade demo stopped stalling",
+ "summary": "Three repairs to the demo pages. When someone shared the lottery and reflection demo, the preview card was the generic three.ws logo, even though a card built for that page already existed and drew the live lottery pot, the reflection pot and the number of eligible holders. Shared links now show that card, so a preview says what the pot is standing at instead of showing a logo. The two-agent trading demo used to sit through just over two seconds of deliberate pauses that existed only to make the exchange look slower; those are gone, and the steps now appear as the real work behind them finishes. Asking the demo API for a nonsense number of results, such as a page size of zero, a negative number, or a word, returned a server error instead of an answer; those requests now fall back to a sensible page size and return data. The wallet-status reader behind the trading demo is also rate limited now, the same as every other public read on the page, so one caller cannot exhaust the Solana connection everyone shares.",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/demo/coin"
+ },
{
"date": "2026-08-12",
"title": "A shared coin-world link now opens a world with the coin's name on it",
diff --git a/prompts/swarm-100/api-demo-01.md b/prompts/swarm-100/api-demo-01.md
deleted file mode 100644
index 03b4145b0..000000000
--- a/prompts/swarm-100/api-demo-01.md
+++ /dev/null
@@ -1,103 +0,0 @@
-# API audit: api/demo batch 01 (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/demo/coin/[action].js
-- api/demo/coin/og.js
-- api/demo/economy.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-demo-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/public/changelog.json b/public/changelog.json
index 22a144a1d..39f5c4447 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-12T23:17:14.448Z",
+ "generated_at": "2026-08-12T23:29:07.966Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -145,6 +145,17 @@
"improvement"
]
},
+ {
+ "date": "2026-08-12",
+ "type": "update",
+ "title": "The lottery demo now shows its own pot in shared previews, and the agent trade demo stopped stalling",
+ "summary": "Three repairs to the demo pages. When someone shared the lottery and reflection demo, the preview card was the generic three.ws logo, even though a card built for that page already existed and drew the live lottery pot, the reflection pot and the number of eligible holders. Shared links now show that card, so a preview says what the pot is standing at instead of showing a logo. The two-agent trading demo used to sit through just over two seconds of deliberate pauses that existed only to make the exchange look slower; those are gone, and the steps now appear as the real work behind them finishes. Asking the demo API for a nonsense number of results, such as a page size of zero, a negative number, or a word, returned a server error instead of an answer; those requests now fall back to a sensible page size and return data. The wallet-status reader behind the trading demo is also rate limited now, the same as every other public read on the page, so one caller cannot exhaust the Solana connection everyone shares.",
+ "link": "/demo/coin",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-08-12",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 9b7e957fc..fbca3034f 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -110,6 +110,14 @@
<category>fix</category>
<description>Ask the trending feed for the 5-minute, 1-hour and 24-hour view back to back and the last two used to come back empty, blaming an upstream outage that was not happening. The cause was our own request volume: each call pulled the trade history of twenty pump.fun coins, and three calls in a row hit pump.fun's rate limiter, which then refused everything for a while. Both feeds now read pump.fun through one shared, short-lived cache, so every window and every caller reuses a single set of pulls instead of re-fetching the same coins, and a repeat call answers in milliseconds. When the limiter does bite, the whale feed serves the last successful pull and marks it stale instead of pretending the market is empty. A token nobody is trading now also reports an honest empty result rather than a false feed-down warning.</description>
</item>
+ <item>
+ <title>The lottery demo now shows its own pot in shared previews, and the agent trade demo stopped stalling</title>
+ <link>https://three.ws/demo/coin</link>
+ <guid isPermaLink="false">2026-08-12:The lottery demo now shows its own pot in shared previews, and the agent trade demo stopped stalling</guid>
+ <pubDate>Wed, 12 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Three repairs to the demo pages. When someone shared the lottery and reflection demo, the preview card was the generic three.ws logo, even though a card built for that page already existed and drew the live lottery pot, the reflection pot and the number of eligible holders. Shared links now show that card, so a preview says what the pot is standing at instead of showing a logo. The two-agent trading demo used to sit through just over two seconds of deliberate pauses that existed only to make the exchange look slower; those are gone, and the steps now appear as the real work behind them finishes. Asking the demo API for a nonsense number of results, such as a page size of zero, a negative number, or a word, returned a server error instead of an answer; those requests now fall back to a sensible page size and return data. The wallet-status reader behind the trading demo is also rate limited now, the same as every other public read on the page, so one caller cannot exhaust the Solana connection everyone shares.</description>
+ </item>
<item>
<title>The open inference network's node endpoints answer again</title>
<link>https://three.ws/changelog</link>
diff --git a/public/demo/coin/index.html b/public/demo/coin/index.html
index 7886e6f9f..0a95a2603 100644
--- a/public/demo/coin/index.html
+++ b/public/demo/coin/index.html
@@ -11,12 +11,12 @@
<meta property="og:description" content="Under test on three.ws — hourly lottery + passive SOL reflection. Production launch TBD." data-i18n-attr="content:demo_coin_index.meta_og_description"/>
<meta property="og:type" content="website" />
<meta property="og:url" content="https://three.ws/demo/coin" />
- <meta property="og:image" content="https://three.ws/3d.png" />
+ <meta property="og:image" content="https://three.ws/api/demo/coin/og" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@trythreews" />
<meta name="twitter:title" content="Demo · Lottery + Reflection · three.ws" data-i18n-attr="content:demo_coin_index.meta_twitter_title"/>
<meta name="twitter:description" content="Under test on three.ws — hourly lottery + passive SOL reflection. Production launch TBD." data-i18n-attr="content:demo_coin_index.meta_twitter_description"/>
- <meta name="twitter:image" content="https://three.ws/3d.png" />
+ <meta name="twitter:image" content="https://three.ws/api/demo/coin/og" />
<link rel="icon" href="/favicon.ico" />
<link rel="stylesheet" href="/style.css" />
<link rel="stylesheet" href="/nav.css" />
diff --git a/tests/demo-coin-api.test.js b/tests/demo-coin-api.test.js
new file mode 100644
index 000000000..6ff128083
--- /dev/null
+++ b/tests/demo-coin-api.test.js
@@ -0,0 +1,198 @@
+// Regression cover for the /api/demo/* handlers.
+//
+// Three defects motivated these tests, all of them invisible until a caller
+// supplied input the happy path never produced:
+//
+// 1. `?limit=abc` parsed to NaN and `?limit=-5` / `?limit=0` passed straight
+// through, so each reached the SQL LIMIT clause as an invalid value and
+// turned a malformed query string into a 500 instead of a 4xx.
+// 2. The OG card resolved the active coin twice per render (a ternary whose
+// `||` bound looser than its `===`), doubling the DB round-trips on every
+// social-scraper hit of the un-parameterised brand card.
+// 3. /api/demo/economy?status=1 returned before the rate limiter ran, leaving
+// two Solana RPC balance reads plus a price lookup unmetered per request.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const MINT = 'THREEsynthetic1111111111111111111111111111';
+
+// Captures every tagged-template query the handlers issue, with the interpolated
+// values, so a test can assert what actually reached the LIMIT clause.
+const queries = [];
+const rows = [];
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (strings, ...values) => {
+ queries.push({ text: strings.join('?'), values });
+ return Promise.resolve(rows.shift() ?? []);
+ },
+}));
+
+const listActiveCoins = vi.fn();
+const loadCoinByMint = vi.fn();
+vi.mock('../api/_lib/coin/index.js', () => ({
+ listActiveCoins: (...a) => listActiveCoins(...a),
+ loadCoinByMint: (...a) => loadCoinByMint(...a),
+}));
+
+const publicIp = vi.fn(async () => ({ success: true, limit: 60, remaining: 59, reset: Date.now() + 60_000 }));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: (...a) => publicIp(...a) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const { default: action } = await import('../api/demo/coin/[action].js');
+
+const COIN = {
+ id: 7,
+ mint: MINT,
+ symbol: 'THREE',
+ name: 'three.ws demo',
+ network: 'solana',
+ is_live: true,
+ min_holder_balance: '1000',
+ draw_interval_seconds: 3600,
+ reflection_interval_seconds: 600,
+ lottery_pot_lamports: '5000000000',
+ reflection_pot_lamports: '2500000000',
+ ops_pot_lamports: '100000000',
+ total_claimed_lamports: '7600000000',
+ lottery_bps: 5000,
+ reflection_bps: 4000,
+ ops_bps: 1000,
+};
+
+function mkReq(query = {}) {
+ return { method: 'GET', url: '/api/demo/coin/x', headers: {}, query };
+}
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: undefined,
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ writeHead(code, hdrs) {
+ this.statusCode = code;
+ Object.assign(this.headers, hdrs || {});
+ return this;
+ },
+ end(b) {
+ this.body = b;
+ this.writableEnded = true;
+ this.headersSent = true;
+ },
+ };
+}
+const payload = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+// The value the handler handed to the SQL LIMIT clause, from the last query issued.
+const lastLimit = () => queries.at(-1).values.at(-1);
+
+beforeEach(() => {
+ queries.length = 0;
+ rows.length = 0;
+ listActiveCoins.mockReset().mockResolvedValue([COIN]);
+ loadCoinByMint.mockReset().mockResolvedValue(COIN);
+ publicIp.mockClear();
+});
+
+describe('GET /api/demo/coin/:action limit handling', () => {
+ // Each row is [querystring limit, expected value reaching SQL].
+ // Non-numeric and out-of-range input must land on a usable integer, never
+ // NaN / 0 / a negative, all three of which make Postgres reject the query.
+ it.each([
+ ['abc', 20],
+ ['-5', 1],
+ ['0', 1],
+ ['', 20],
+ [undefined, 20],
+ ['9999', 100],
+ ['25', 25],
+ ])('winners?limit=%s clamps to %s', async (limit, expected) => {
+ rows.push([]);
+ const res = mkRes();
+ await action(mkReq({ action: 'winners', mint: MINT, ...(limit === undefined ? {} : { limit }) }), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(lastLimit()).toBe(expected);
+ expect(Number.isSafeInteger(lastLimit())).toBe(true);
+ expect(lastLimit()).toBeGreaterThan(0);
+ });
+
+ it('applies each action its own maximum', async () => {
+ // holders allows up to 500, events up to 200. A shared cap would silently
+ // truncate the holder table on a page that legitimately asks for more.
+ rows.push([]);
+ await action(mkReq({ action: 'holders', mint: MINT, limit: '9999' }), mkRes());
+ expect(lastLimit()).toBe(500);
+
+ rows.push([]);
+ await action(mkReq({ action: 'events', mint: MINT, limit: '9999' }), mkRes());
+ expect(lastLimit()).toBe(200);
+ });
+
+ it('never lets a junk limit reach SQL on any paginated action', async () => {
+ for (const act of ['history', 'events', 'winners', 'holders']) {
+ queries.length = 0;
+ rows.push([], [], []);
+ const res = mkRes();
+ await action(mkReq({ action: act, mint: MINT, limit: 'not-a-number' }), res);
+ expect(res.statusCode, act).toBe(200);
+ for (const q of queries) {
+ const v = q.values.at(-1);
+ expect(Number.isSafeInteger(v), `${act}: ${v}`).toBe(true);
+ expect(v, act).toBeGreaterThan(0);
+ }
+ }
+ });
+});
+
+describe('GET /api/demo/coin/:action routing and errors', () => {
+ it('404s an unknown action without touching the database', async () => {
+ const res = mkRes();
+ await action(mkReq({ action: 'definitely-not-an-action' }), res);
+ expect(res.statusCode).toBe(404);
+ expect(payload(res).error).toBe('not_found');
+ expect(queries).toHaveLength(0);
+ });
+
+ it('405s a non-GET method', async () => {
+ const res = mkRes();
+ const req = mkReq({ action: 'state' });
+ req.method = 'POST';
+ await action(req, res);
+ expect(res.statusCode).toBe(405);
+ expect(payload(res).error).toBe('method_not_allowed');
+ });
+
+ it('404s with a JSON envelope when no coin resolves', async () => {
+ loadCoinByMint.mockResolvedValue(null);
+ const res = mkRes();
+ await action(mkReq({ action: 'state', mint: MINT }), res);
+ expect(res.statusCode).toBe(404);
+ expect(payload(res)).toMatchObject({ error: 'coin_not_found' });
+ });
+
+ it('400s a holder lookup with no wallet', async () => {
+ const res = mkRes();
+ await action(mkReq({ action: 'holder', mint: MINT }), res);
+ expect(res.statusCode).toBe(400);
+ expect(payload(res).error).toBe('validation_error');
+ });
+
+ it('429s with a Retry-After when the limiter rejects, before any query', async () => {
+ publicIp.mockResolvedValueOnce({ success: false, limit: 60, remaining: 0, reset: Date.now() + 30_000 });
+ const res = mkRes();
+ await action(mkReq({ action: 'state', mint: MINT }), res);
+ expect(res.statusCode).toBe(429);
+ expect(payload(res).error).toBe('rate_limited');
+ expect(res.getHeader('retry-after')).toBeDefined();
+ expect(queries).toHaveLength(0);
+ });
+});
diff --git a/tests/demo-og-economy.test.js b/tests/demo-og-economy.test.js
new file mode 100644
index 000000000..4311def1d
--- /dev/null
+++ b/tests/demo-og-economy.test.js
@@ -0,0 +1,280 @@
+// Regression cover for the two remaining /api/demo/* handlers.
+//
+// api/demo/coin/og.js: the brand card resolved the active coin twice. The
+// condition read `mint || (await listActiveCoins()).length === 1 ? ... : null`,
+// where `||` binds looser than `===`, so the guard ran listActiveCoins() and
+// then resolveCoin() ran it again. Every un-parameterised share-card hit (the
+// common case, since social scrapers fetch the bare URL) paid for two queries.
+//
+// api/demo/economy.js: `?status=1` returned before the rate limiter, so the
+// branch that fans out to two Solana RPC balance reads plus a SOL price lookup
+// was reachable without limit by any anonymous caller.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const MINT = 'THREEsynthetic1111111111111111111111111111';
+const ORACLE = 'ORACLEaddr11111111111111111111111111111111';
+const TRADER = 'TRADERaddr11111111111111111111111111111111';
+
+// ── Shared doubles ─────────────────────────────────────────────────────────
+
+vi.mock('@vercel/og', () => ({
+ ImageResponse: class {
+ constructor(node, opts) {
+ this.node = node;
+ this.status = 200;
+ this.headers = new Map(Object.entries({ 'content-type': 'image/png', ...(opts?.headers || {}) }));
+ }
+ async arrayBuffer() {
+ return new Uint8Array([0x89, 0x50, 0x4e, 0x47]).buffer;
+ }
+ },
+}));
+
+const sqlCalls = [];
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (strings, ...values) => {
+ sqlCalls.push({ text: strings.join('?'), values });
+ return Promise.resolve([{ eligible: 3 }]);
+ },
+}));
+
+const listActiveCoins = vi.fn();
+const loadCoinByMint = vi.fn();
+vi.mock('../api/_lib/coin/index.js', () => ({
+ listActiveCoins: (...a) => listActiveCoins(...a),
+ loadCoinByMint: (...a) => loadCoinByMint(...a),
+}));
+
+const publicIp = vi.fn(async () => ({ success: true, limit: 60, remaining: 59, reset: Date.now() + 60_000 }));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: (...a) => publicIp(...a) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const getSolBalance = vi.fn(async () => ({ sol: 1.5, lamports: 1_500_000_000 }));
+const sendSol = vi.fn(async () => 'SIGNATURE_SHOULD_NEVER_BE_REACHED');
+vi.mock('../api/_lib/avatar-wallet.js', () => ({
+ avatarWalletConfig: () => ({ configured: true, address: ORACLE, explorer: `https://solscan.io/account/${ORACLE}` }),
+ loadAvatarKeypair: () => ({ publicKey: { toBase58: () => TRADER } }),
+ getConnection: () => ({}),
+ getSolBalance: (...a) => getSolBalance(...a),
+ solUsdPrice: async () => 75,
+ sendSol: (...a) => sendSol(...a),
+ explorerTxUrl: (s) => `https://solscan.io/tx/${s}`,
+ explorerAccountUrl: (a) => `https://solscan.io/account/${a}`,
+ LAMPORTS_PER_SOL: 1_000_000_000,
+}));
+
+const trendingPools = vi.fn(async () => [{ name: 'SOL/USDC', priceUsd: 75, change24h: 1.2, pool: 'pool1' }]);
+vi.mock('../api/_lib/market/ohlcv.js', () => ({ trendingPools: (...a) => trendingPools(...a) }));
+
+const getSessionUser = vi.fn(async () => null);
+const authenticateBearer = vi.fn(async () => null);
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUser(...a),
+ authenticateBearer: (...a) => authenticateBearer(...a),
+ extractBearer: (req) => (req.headers?.authorization || '').replace(/^Bearer /, '') || null,
+}));
+
+const { default: og } = await import('../api/demo/coin/og.js');
+const { default: economy } = await import('../api/demo/economy.js');
+
+const COIN = {
+ id: 7,
+ mint: MINT,
+ symbol: 'THREE',
+ min_holder_balance: '1000',
+ lottery_pot_lamports: '5000000000',
+ reflection_pot_lamports: '2500000000',
+};
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ chunks: [],
+ body: undefined,
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ writeHead(code, hdrs) {
+ this.statusCode = code;
+ Object.assign(this.headers, hdrs || {});
+ this.headersSent = true;
+ return this;
+ },
+ write(c) {
+ this.chunks.push(String(c));
+ this.headersSent = true;
+ return true;
+ },
+ end(b) {
+ if (b !== undefined) this.body = b;
+ this.writableEnded = true;
+ this.headersSent = true;
+ },
+ };
+}
+const payload = (res) => {
+ if (res.body === undefined) return undefined;
+ try {
+ return JSON.parse(res.body);
+ } catch {
+ return undefined;
+ }
+};
+
+beforeEach(() => {
+ // Production currently leaves this unset, which routes the trade stream down the
+ // demo_mode branch (covered by its own case below). Set it here so the paid path
+ // is exercised too, since that is the branch that signs a real transfer.
+ process.env.AGENT_B_WALLET_SECRET = 'test-trader-secret';
+ sqlCalls.length = 0;
+ listActiveCoins.mockReset().mockResolvedValue([COIN]);
+ loadCoinByMint.mockReset().mockResolvedValue(COIN);
+ publicIp.mockClear();
+ getSolBalance.mockClear();
+ sendSol.mockClear();
+ trendingPools.mockClear();
+ getSessionUser.mockReset().mockResolvedValue(null);
+ authenticateBearer.mockReset().mockResolvedValue(null);
+});
+
+describe('GET /api/demo/coin/og', () => {
+ const mkReq = (qs = '') => ({ method: 'GET', url: `/api/demo/coin/og${qs}`, headers: {} });
+
+ it('resolves the active coin exactly once when no mint is supplied', async () => {
+ const res = mkRes();
+ await og(mkReq(), res);
+ expect(res.statusCode).toBe(200);
+ // The pre-fix ternary called this twice for a single render.
+ expect(listActiveCoins).toHaveBeenCalledTimes(1);
+ });
+
+ it('renders a PNG with a short cache for the live state card', async () => {
+ const res = mkRes();
+ await og(mkReq(`?mint=${MINT}`), res);
+ expect(res.statusCode).toBe(200);
+ expect(res.getHeader('content-type')).toBe('image/png');
+ expect(res.getHeader('cache-control')).toContain('max-age=30');
+ expect(Buffer.isBuffer(res.body)).toBe(true);
+ });
+
+ it('falls back to the brand card instead of erroring when the coin lookup throws', async () => {
+ loadCoinByMint.mockRejectedValue(new Error('db unreachable'));
+ const res = mkRes();
+ await og(mkReq(`?mint=${MINT}`), res);
+ expect(res.statusCode).toBe(200);
+ expect(res.getHeader('content-type')).toBe('image/png');
+ });
+
+ it('405s a non-GET and 204s a preflight', async () => {
+ const post = mkRes();
+ await og({ ...mkReq(), method: 'POST' }, post);
+ expect(post.statusCode).toBe(405);
+
+ const preflight = mkRes();
+ await og({ ...mkReq(), method: 'OPTIONS' }, preflight);
+ expect(preflight.statusCode).toBe(204);
+ });
+
+ it('429s a rate-limited scraper before rendering or querying', async () => {
+ publicIp.mockResolvedValueOnce({ success: false, limit: 60, remaining: 0, reset: Date.now() + 30_000 });
+ const res = mkRes();
+ await og(mkReq(), res);
+ expect(res.statusCode).toBe(429);
+ expect(payload(res).error).toBe('rate_limited');
+ expect(res.getHeader('retry-after')).toBeDefined();
+ expect(sqlCalls).toHaveLength(0);
+ });
+});
+
+describe('GET /api/demo/economy', () => {
+ const mkReq = (qs = '', headers = {}) => ({ method: 'GET', url: `/api/demo/economy${qs}`, headers });
+
+ it('meters ?status=1 through the rate limiter', async () => {
+ const res = mkRes();
+ await economy(mkReq('?status=1'), res);
+ expect(res.statusCode).toBe(200);
+ // Pre-fix this branch returned before the limiter ever ran.
+ expect(publicIp).toHaveBeenCalledTimes(1);
+ expect(payload(res)).toMatchObject({ tradeSol: 0.001 });
+ });
+
+ it('429s ?status=1 when the limiter rejects, without hitting Solana RPC', async () => {
+ publicIp.mockResolvedValueOnce({ success: false, limit: 60, remaining: 0, reset: Date.now() + 30_000 });
+ const res = mkRes();
+ await economy(mkReq('?status=1'), res);
+ expect(res.statusCode).toBe(429);
+ expect(payload(res).error).toBe('rate_limited');
+ expect(getSolBalance).not.toHaveBeenCalled();
+ });
+
+ it('400s with a JSON error envelope when neither mode is requested', async () => {
+ const res = mkRes();
+ await economy(mkReq(''), res);
+ expect(res.statusCode).toBe(400);
+ expect(payload(res)).toMatchObject({ error: 'validation_error' });
+ });
+
+ it('401s an anonymous ?trade=1 without signing anything', async () => {
+ const res = mkRes();
+ await economy(mkReq('?trade=1'), res);
+ expect(res.statusCode).toBe(401);
+ expect(payload(res).error).toBe('unauthorized');
+ // The spend path must be unreachable for an unauthenticated caller.
+ expect(sendSol).not.toHaveBeenCalled();
+ });
+
+ it('streams the trade lifecycle for a signed-in caller with no artificial pacing', async () => {
+ getSessionUser.mockResolvedValue({ id: 'user-1' });
+ const started = Date.now();
+ const res = mkRes();
+ await economy(mkReq('?trade=1'), res);
+ const elapsed = Date.now() - started;
+
+ const stream = res.chunks.join('');
+ expect(stream).toContain('event: thinking');
+ expect(stream).toContain('event: paying');
+ expect(stream).toContain('event: done');
+ expect(sendSol).toHaveBeenCalledTimes(1);
+ expect(trendingPools).toHaveBeenCalledTimes(1);
+ // The handler used to sit on 2.2s of setTimeout pacing between events.
+ expect(elapsed).toBeLessThan(500);
+ });
+
+ it('streams demo_mode with real market data when the trader wallet is unconfigured', async () => {
+ // This is production's current state: AGENT_B_WALLET_SECRET is not set on the
+ // Cloud Run service, so no payment can occur. The stream must say so plainly
+ // and still deliver real market data rather than inventing a settlement.
+ delete process.env.AGENT_B_WALLET_SECRET;
+ getSessionUser.mockResolvedValue({ id: 'user-1' });
+ const res = mkRes();
+ await economy(mkReq('?trade=1'), res);
+
+ const stream = res.chunks.join('');
+ expect(stream).toContain('event: demo_mode');
+ expect(sendSol).not.toHaveBeenCalled();
+ expect(trendingPools).toHaveBeenCalledTimes(1);
+ const done = JSON.parse(stream.split('event: done\ndata: ')[1].split('\n')[0]);
+ expect(done).toMatchObject({ paid: false, demo: true });
+ expect(done.markets).toHaveLength(1);
+ });
+
+ it('reports an underfunded trader wallet instead of attempting the transfer', async () => {
+ getSessionUser.mockResolvedValue({ id: 'user-1' });
+ getSolBalance.mockResolvedValue({ sol: 0, lamports: 0 });
+ const res = mkRes();
+ await economy(mkReq('?trade=1'), res);
+
+ const stream = res.chunks.join('');
+ expect(stream).toContain('underfunded');
+ expect(sendSol).not.toHaveBeenCalled();
+ });
+});