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.

feat: add comprehensive SDK wrappers and tools for Robinhood Chain

fudjia7f26abf96da9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4141f02e2..c6c3d9060 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,9 +6,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-07-12
+- **Docs · The autonomous economy** (`/docs/autonomous-economy`) — How the three.ws on-chain treasury funds itself and where every dollar flows: the funding-root and engine wallets, the topup/sweepback loop, the allowlist- and destination-locks that keep money inside platform-owned wallets, and the two leak scanners that audit every signer wallet on-chain every minute — plus how to verify there's no leak yourself.
- **Agent discovery fixed: six paid endpoints were invisible to x402 scanners** — The machine-readable catalog at /openapi.json — what AI agents and x402 scanners like x402scan and AgentCash read to find and pay for three.ws APIs — had six paid endpoints (agent bouncer, verifiable vanity keys, crypto intel, cosmetic purchase, animation download, club cover) accidentally buried inside another entry, making them undiscoverable. All 61 payable routes now list correctly and the document passes the AgentCash discovery validator. The Permit2 gasless-payment demo is now only advertised when its settlement lane is actually live, so agents are never quoted a payment path that can't settle. (`/openapi.json`) `[fix, improvement]`
- **Agent profiles, redesigned** — Agent profile pages got a ground-up redesign. Instead of one endless column of cards, everything is now organized into clear sections — Overview, Capabilities, Economy, Activity, Trust & Identity, Reviews, and Developers — with a sticky navigation bar that follows you as you scroll and hides sections that have nothing to show. The hero is a compact identity band with the live 3D avatar beside the agent's name, description, and actions, and secondary view modes now live in a tidy menu instead of a wall of buttons. Pages are roughly 40% shorter and much easier to scan. Prefer the old look? Every profile keeps a “Classic layout” link that serves the previous design unchanged. (`/agents`) `[improvement, feature]`
+- **AI features can no longer go down when one provider does** — Every AI-powered feature on three.ws (fact checks, agent chat, persona extraction, scene composing) routes through one shared brain that tries free providers first and falls back automatically. That chain just got much deeper: Groq now has a second lane with its own separate quota, OpenRouter gets a zero-credit free lane so an empty account no longer kills it, optional Cerebras and Google AI Studio lanes activate the moment a key is added, and — the anchor — Gemini on the platform's own Google Cloud now backs the whole chain with no third-party quota to exhaust. Previously a rare bad hour where every free tier was exhausted at once could surface an error; now the request rides through. The fact-checker was also corrected to stop favoring a paid key ahead of the free lanes. (`/changelog`) `[improvement, fix, infra]`
- **Oversized x402 payment headers fixed** — Three paid endpoints (vanity, pump launch, agent reputation) mirrored their entire payment challenge — schemas, signed offers and all — into a single HTTP header that grew past 16 KB, the point where proxies and many clients drop or fail to parse the response. The header mirror is now capped at 8 KB: it slims down or steps aside when the challenge is large, while the response body always carries the complete challenge. Payment tooling that reads only headers still gets everything it needs to pay. `[fix]`
+- **Seeker wallet signing fixed before it ever shipped** — Automated testing of the Solana Seeker app in an Android emulator against Solana Mobile's reference wallet caught four bugs in our Mobile Wallet Adapter integration: the app icon was sent in a format the wallet spec rejects, and message signing, transaction signing, and send-transaction all read the wallet's response in the wrong shape. All four are fixed — wallet connect was verified end to end, returning a real public key through the on-device signing flow. `[fix, security]`
+- **The autonomous coin launcher learned taste** — The Memetic Launcher's picks got a full quality overhaul. Its cultural radar was half-blind — the pump.fun intel feed was silenced by a miscalibrated quality bar and generic sector words like 'meme' drowned out actual memes — so most picks fell back to random word-salad names. Now the radar reads live meme culture properly (Know Your Meme, Google Trends, Hacker News, Wikipedia attention, and pump.fun's own breakout data), each launch rides a specific rising narrative, the launcher remembers its recent picks so it never re-mints the same joke, coin descriptions are no longer cut off mid-sentence, and a quality gate refuses to spend real SOL on a filler pick when no genuine signal exists. Launch previews in the user launcher now refresh hourly instead of every minute. (`/launcher`) `[improvement, fix]`
- **The npm package fleet gets a professional-grade overhaul** — All 60 published @three-ws packages were audited end to end — every test suite run, every install verified, every doc checked against the code. The most-used packages gained serious test coverage: the React embed component went from zero tests to 28, agent payment sessions from zero to 29 (fixing two real bugs found along the way, including tool safety-annotations that were silently dropped so clients could not tell read-only tools from destructive ones), and the pump.fun, Brain, IBM Granite, and marketplace MCP servers roughly tripled their suites. READMEs for the five most-downloaded packages were rewritten or corrected to match the code exactly — phantom tools removed, missing tools and required setup documented, error semantics added. Broken metadata (dead homepage links, a missing license file, a stale repository pointer) was fixed across the fleet. `[sdk, improvement, fix]`
- **x402 registration probes now always get a real payment challenge** — Payment directories like x402scan verify an endpoint by poking it without paying and expecting the HTTP 402 payment challenge back. A July registration run rejected 33 three.ws endpoints because probes were answered with the wrong thing: method or input mistakes returned plain errors before the challenge, and per-item priced endpoints (asset downloads, marketplace skills, fact checks) demanded a valid item id before quoting a price. Now any credential-less request on a paid route receives the full 402 challenge — wrong method, missing id, or empty body included — while real paying callers keep strict validation before any money moves. The free crypto-data endpoints under /api/v1/x are now correctly advertised as free in /openapi.json instead of failing paid-endpoint probes, so agents see them for what they are: no-signup data with a pay-as-you-go overflow lane. (`/openapi.json`) `[fix, improvement]`
diff --git a/agents/fact-checker/src/llm-verdict.js b/agents/fact-checker/src/llm-verdict.js
index f3bba40cd..bb13737be 100644
--- a/agents/fact-checker/src/llm-verdict.js
+++ b/agents/fact-checker/src/llm-verdict.js
@@ -10,10 +10,13 @@ import { llmComplete } from '../../../api/_lib/llm.js';
const TIMEOUT_MS = 30_000;
async function callLlm(prompt, maxTokens = 1024) {
+ // No anthropicKey here: passing the SERVER's ANTHROPIC_API_KEY would be
+ // treated as caller BYOK and jump a paid (and routinely dead) key to the
+ // FRONT of the chain, ahead of the free providers. llm.js already appends
+ // the server Anthropic key as a tail backstop on its own.
const { text, usage } = await llmComplete({
user: prompt,
maxTokens,
- anthropicKey: process.env.ANTHROPIC_API_KEY,
timeoutMs: TIMEOUT_MS,
});
return { text, inputTokens: usage?.input || 0, outputTokens: usage?.output || 0 };
diff --git a/api/_lib/env.js b/api/_lib/env.js
index f1e2434ab..e7da66acc 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -514,6 +514,21 @@ export const env = {
return opt('GROQ_API_KEY');
},
+ // Cerebras API key (cloud.cerebras.ai) — free-tier OpenAI-compatible Llama
+ // 3.3 70B inference, extremely fast. Optional rung in the shared LLM chain
+ // (api/_lib/llm.js); when unset the chain simply skips it.
+ get CEREBRAS_API_KEY() {
+ return opt('CEREBRAS_API_KEY');
+ },
+
+ // Google AI Studio key (aistudio.google.com) — free-tier Gemini via its
+ // OpenAI-compatible endpoint. Optional rung in the shared LLM chain;
+ // distinct from the Vertex Gemini lane, which authenticates with the GCP
+ // service account and needs no key here.
+ get GEMINI_API_KEY() {
+ return opt('GEMINI_API_KEY');
+ },
+
// NVIDIA NIM API key (build.nvidia.com) — free OpenAI-compatible inference for
// 100+ hosted models (Nemotron, DeepSeek, Kimi, GLM, Llama 4, Qwen). Used by
// brain/chat as selectable native providers and by the embed we-pay proxy
diff --git a/api/_lib/llm-pricing.js b/api/_lib/llm-pricing.js
index 76b9f6d9b..a9550a437 100644
--- a/api/_lib/llm-pricing.js
+++ b/api/_lib/llm-pricing.js
@@ -23,10 +23,15 @@ const PRICE_PER_MTOK = {
'claude-haiku-4-5': [1, 5],
'gpt-4o-mini': [0.15, 0.6],
'gpt-4o': [2.5, 10],
+ // Vertex Gemini (model id carries the publisher prefix) — billed to the GCP
+ // credit grant, so it's metered like a paid model rather than priced to 0.
+ 'google/gemini-2.5-flash-lite': [0.1, 0.4],
+ 'gemini-2.5-flash-lite': [0.1, 0.4],
};
-// Providers whose marginal cost to the platform is zero (platform-funded keys).
-const FREE_PROVIDERS = new Set(['groq', 'openrouter', 'nvidia']);
+// Providers whose marginal cost to the platform is zero (platform-funded free
+// tiers). vertex-gemini is deliberately NOT here — it draws down GCP credits.
+const FREE_PROVIDERS = new Set(['groq', 'openrouter', 'nvidia', 'cerebras', 'gemini']);
function priceForModel(model) {
if (!model) return null;
@@ -43,9 +48,11 @@ function priceForModel(model) {
// or 0 when the provider is free or the model is unpriced — never null, so the
// caller can always record a numeric cost.
export function costMicroUsd({ provider, model, input = 0, output = 0 } = {}) {
- // Multi-key providers carry a #n suffix (openrouter#2) — strip it so every
- // key of a free provider prices to zero.
- if (provider && FREE_PROVIDERS.has(String(provider).split('#')[0])) return 0;
+ // Provider names carry rung suffixes — '#n' for multi-key (openrouter#2),
+ // ':variant' for same-key model variants (openrouter:free), '#instant' for
+ // the Groq step-down. Strip them so every rung of a free provider prices
+ // to zero.
+ if (provider && FREE_PROVIDERS.has(String(provider).split(/[#:]/)[0])) return 0;
const price = priceForModel(model);
if (!price) return 0;
const [inPerM, outPerM] = price;
diff --git a/api/_lib/llm.js b/api/_lib/llm.js
index 158d38a88..9d4aaa8f9 100644
--- a/api/_lib/llm.js
+++ b/api/_lib/llm.js
@@ -2,12 +2,20 @@
//
// Policy (do not re-implement per endpoint — that is how this drifted before):
//
-// • FREE PROVIDERS FIRST, ALWAYS. Groq, OpenRouter, and NVIDIA NIM are
-// platform-funded free tiers — the server holds those keys and callers use
-// them at zero marginal cost. They form the default chain, tried in order,
-// and every flow must survive on them alone: the paid keys in prod are
+// • FREE PROVIDERS FIRST, ALWAYS. Groq, Cerebras, OpenRouter (paid model,
+// then the :free variant on the same key), Gemini AI Studio, and NVIDIA
+// NIM are platform-funded free tiers — the server holds those keys and
+// callers use them at zero marginal cost. They form the default chain,
+// tried in order, 70B-class models before any capability step-down, and
+// every flow must survive on them alone: the paid keys in prod are
// routinely invalid or out of quota, so a chain that depends on them fails.
//
+// • VERTEX GEMINI IS THE RELIABILITY ANCHOR. When GOOGLE_CLOUD_PROJECT is
+// set (every Cloud Run deploy), Gemini Flash-Lite on Vertex — service
+// account auth, GCP-credit billing, no third-party quota — sits between
+// the free tiers and the paid tail, so exhausting every free quota at
+// once still cannot produce an error.
+//
// • Paid server keys are the LAST-RESORT tier, automatically. When
// ANTHROPIC_API_KEY or OPENAI_API_KEY is configured, those providers are
// appended to the tail of EVERY chain so a request that exhausted the
@@ -35,7 +43,19 @@ import {
} from './vertex-claude.js';
const GROQ_MODEL = 'llama-3.3-70b-versatile';
+// Second Groq rung on a different model: Groq free-tier quotas are PER MODEL,
+// so when the 70B lane is exhausted the instant lane usually still has budget.
+// Smaller model, so it sits at the END of the free section — every 70B-class
+// provider gets tried before the chain steps down in capability.
+const GROQ_INSTANT_MODEL = 'llama-3.1-8b-instant';
+// Same Llama 3.3 70B on Cerebras' free tier (cloud.cerebras.ai) — optional
+// rung, active when CEREBRAS_API_KEY is configured.
+const CEREBRAS_MODEL = 'llama-3.3-70b';
const OPENROUTER_MODEL = 'meta-llama/llama-3.3-70b-instruct';
+// Gemini Flash-Lite: the AI Studio free tier (GEMINI_API_KEY) and the Vertex
+// lane (GCP service account, billed to platform credits) run the same model.
+const GEMINI_MODEL = 'gemini-2.5-flash-lite';
+const VERTEX_GEMINI_MODEL = 'google/gemini-2.5-flash-lite';
// Same Llama 3.3 70B family on NVIDIA NIM (build.nvidia.com) — one free nvapi
// key, OpenAI-compatible, so the chain degrades across providers without
// changing model behavior.
@@ -76,7 +96,9 @@ export async function checkUserLlmSpendCap(userId, { anthropicKey } = {}) {
FROM usage_events
WHERE user_id = ${userId}
AND kind = 'llm'
- AND provider NOT IN ('groq', 'openrouter', 'nvidia')
+ AND provider NOT LIKE 'groq%'
+ AND provider NOT LIKE 'openrouter%'
+ AND provider NOT IN ('nvidia', 'cerebras', 'gemini')
AND created_at > NOW() - INTERVAL '24 hours'
`;
const spent = Number(row?.spent ?? 0);
@@ -145,6 +167,37 @@ function vertexAnthropicProvider(model) {
};
}
+// Gemini on Vertex AI through its OpenAI-compatible endpoint, authenticated
+// with the GCP service account (no API key) and billed to platform credits.
+// Unlike Vertex Claude this needs no Model Garden acceptance — Gemini is
+// first-party on Vertex, so any deployment with GOOGLE_CLOUD_PROJECT and
+// aiplatform access (the Cloud Run SA already drives the image lane) can use
+// it. That makes this the chain's most reliable rung: it survives every
+// third-party free-tier quota reset cycle. Token-exchange failures throw in
+// getHeaders and fall through the chain like any other provider error.
+function vertexGeminiProvider() {
+ const project = process.env.GOOGLE_CLOUD_PROJECT;
+ const location = process.env.GOOGLE_CLOUD_LOCATION_GEMINI || 'global';
+ const host =
+ location === 'global' ? 'aiplatform.googleapis.com' : `${location}-aiplatform.googleapis.com`;
+ return {
+ name: 'vertex-gemini',
+ model: VERTEX_GEMINI_MODEL,
+ url: `https://${host}/v1beta1/projects/${project}/locations/${location}/endpoints/openapi/chat/completions`,
+ getHeaders: vertexRequestHeaders,
+ buildBody: (system, user, maxTokens) => ({
+ model: VERTEX_GEMINI_MODEL,
+ max_tokens: maxTokens,
+ messages: [
+ ...(system ? [{ role: 'system', content: system }] : []),
+ { role: 'user', content: user },
+ ],
+ }),
+ extractText: (r) => r.choices?.[0]?.message?.content || '',
+ extractUsage: (r) => ({ input: r.usage?.prompt_tokens ?? 0, output: r.usage?.completion_tokens ?? 0 }),
+ };
+}
+
function openaiCompatProvider({ name, key, url, model, extraHeaders = {} }) {
return {
name,
@@ -210,10 +263,23 @@ export function providerChain({ anthropicKey, anthropicModel, preferNvidia = fal
model: GROQ_MODEL,
}));
}
+ // Same 70B family on Cerebras' free tier — a distinct quota pool from Groq,
+ // so one provider's daily cap doesn't take the whole 70B class down.
+ if (env.CEREBRAS_API_KEY) {
+ chain.push(openaiCompatProvider({
+ name: 'cerebras',
+ key: env.CEREBRAS_API_KEY,
+ url: 'https://api.cerebras.ai/v1/chat/completions',
+ model: CEREBRAS_MODEL,
+ }));
+ }
// One provider entry per OpenRouter key: when the primary account runs out
// of credits (402) or hits a rate limit, the next key takes over. Fallback
// keys are typically unfunded free-tier accounts, so they get the model's
- // :free variant — the paid model would 402 on them unconditionally.
+ // :free variant — the paid model would 402 on them unconditionally. The
+ // primary key ALSO gets a :free rung right behind its paid rung: an
+ // out-of-credits primary account (the July 2026 prod state) can still serve
+ // the :free variant, so exhausted credits cost one fast 402, not the lane.
const openrouterKeys = [...new Set([env.OPENROUTER_API_KEY, ...env.OPENROUTER_FALLBACK_KEYS].filter(Boolean))];
openrouterKeys.forEach((key, i) => {
chain.push(openaiCompatProvider({
@@ -223,6 +289,15 @@ export function providerChain({ anthropicKey, anthropicModel, preferNvidia = fal
model: i === 0 ? OPENROUTER_MODEL : `${OPENROUTER_MODEL}:free`,
extraHeaders: { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws' },
}));
+ if (i === 0) {
+ chain.push(openaiCompatProvider({
+ name: 'openrouter:free',
+ key,
+ url: 'https://openrouter.ai/api/v1/chat/completions',
+ model: `${OPENROUTER_MODEL}:free`,
+ extraHeaders: { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws' },
+ }));
+ }
});
if (env.NVIDIA_API_KEY) {
chain.push(openaiCompatProvider({
@@ -232,6 +307,33 @@ export function providerChain({ anthropicKey, anthropicModel, preferNvidia = fal
model: NVIDIA_MODEL,
}));
}
+ // Gemini Flash-Lite, twice: the AI Studio free tier when a key is
+ // configured, then the Vertex lane on the GCP service account (billed to
+ // platform credits — effectively free while the credit grant runs, and the
+ // only rung with no third-party quota to exhaust). Both sit after the
+ // 70B-class free rungs and before the capability step-down below.
+ if (env.GEMINI_API_KEY) {
+ chain.push(openaiCompatProvider({
+ name: 'gemini',
+ key: env.GEMINI_API_KEY,
+ url: 'https://generativelanguage.googleapis.com/v1beta/openai/chat/completions',
+ model: GEMINI_MODEL,
+ }));
+ }
+ if (process.env.GOOGLE_CLOUD_PROJECT) {
+ chain.push(vertexGeminiProvider());
+ }
+ // Last free rung: Groq's instant lane. Smaller model (a capability
+ // step-down), but its per-model quota is separate from the 70B lane and it
+ // still beats erroring out or landing on a dead paid key.
+ if (env.GROQ_API_KEY) {
+ chain.push(openaiCompatProvider({
+ name: 'groq#instant',
+ key: env.GROQ_API_KEY,
+ url: 'https://api.groq.com/openai/v1/chat/completions',
+ model: GROQ_INSTANT_MODEL,
+ }));
+ }
// VERTEX_CLAUDE_ENABLED (without PRIMARY): Vertex Claude is a paid-tier
// backstop, tried ahead of first-party Anthropic — GCP credits before a paid
// Anthropic key. Skipped when it already leads (primary) so it's not added
diff --git a/api/wk.js b/api/wk.js
index 1ddf5aea6..6de2dffc4 100644
--- a/api/wk.js
+++ b/api/wk.js
@@ -32,9 +32,13 @@ import {
DATAPOINT_FAMILIES,
DATAPOINT_DEFAULT_ATOMICS,
datapointDescription,
+ allChains,
+ allStablecoins,
} from './_lib/market-data/datapoints.js';
import { fetchMarketsTable } from './_lib/market-fallbacks.js';
import { buildProtocols } from './defi/protocols.js';
+import { loadYieldPools } from './defi/yields.js';
+import { buildExchanges } from './coin/exchanges.js';
import { FORGE_OUTPUT_EXAMPLE } from './_lib/forge-listing.js';
import { listBazaarServices, serviceResourceUrl } from './_lib/agent-paid-services.js';
import { toBazaarDiscovery } from './_lib/service-catalog/index.js';
@@ -502,22 +506,73 @@ async function buildAgentServiceItems(origin) {
}
// Datapoint fabric (/api/x402/d/<family>/<id>/<metric>) — 400k+ addressable
-// single-datapoint endpoints served by one dynamic route. The discovery doc
-// can't (and shouldn't) list them all; it lists a curated slice indexers can
-// surface: every no-id metric (global / gas / fear-greed) plus a
-// runtime-derived set of concrete high-traffic ids (top coins by market cap ×
-// headline metrics, top protocols by TVL × tvl). Ids come from the live
-// cached feeds at render time — nothing here hardcodes a third-party asset —
-// and any upstream hiccup degrades to the static slice (the fabric itself
-// keeps serving every id regardless; /api/x402/d enumerates the full space).
-async function buildDatapointItems(origin) {
+// single-datapoint endpoints served by one dynamic route. Every one already
+// exists and settles; the discovery doc advertises a WIDE enumerated slice so
+// indexers (x402scan, the Bazaar, 402index's well-known reader) surface
+// thousands of concrete datapoint URLs — top coins × every metric, every chain,
+// top protocols / stablecoins / pools / exchanges × their metrics, plus every
+// no-id metric. Ids come from the SAME live cached feeds the paid route resolves
+// against (nothing hardcodes a third-party asset); each slice is best-effort (an
+// upstream hiccup drops only that slice), and the whole result is memoized so a
+// discovery request never triggers a rebuild storm. Set
+// X402_DISCOVERY_DATAPOINTS_WIDE=false to fall back to the small headline slice,
+// or tune any per-family cap via X402_DISCOVERY_<FAMILY>_IDS. The fabric serves
+// every id regardless of what's enumerated here; /api/x402/d walks the full space.
+
+const DP_WIDE = env.X402_DISCOVERY_DATAPOINTS_WIDE !== 'false';
+const dpIntEnv = (key, dflt) => {
+ const n = Number.parseInt(process.env[key] ?? '', 10);
+ return Number.isFinite(n) && n >= 0 ? n : dflt;
+};
+// Per-family enumeration caps (id count). Defaults advertise ~4,800 concrete
+// datapoint endpoints; every id resolves against a cached feed so render stays
+// bounded, and the built array is memoized for DP_TTL_MS.
+const DP_CAPS = {
+ coin: dpIntEnv('X402_DISCOVERY_COIN_IDS', 100),
+ protocol: dpIntEnv('X402_DISCOVERY_PROTOCOL_IDS', 100),
+ chain: dpIntEnv('X402_DISCOVERY_CHAIN_IDS', 150),
+ stablecoin: dpIntEnv('X402_DISCOVERY_STABLECOIN_IDS', 100),
+ pool: dpIntEnv('X402_DISCOVERY_POOL_IDS', 60),
+ exchange: dpIntEnv('X402_DISCOVERY_EXCHANGE_IDS', 60),
+};
+const DP_TTL_MS = dpIntEnv('X402_DISCOVERY_DATAPOINTS_TTL_MS', 900_000); // 15 min
+
+// Coin has 20 metrics; enumerating all × 100 coins alone is 2,000 rows and
+// bloats the doc past what some crawlers ingest. Advertise the high-value
+// headline metrics for coins (breadth of assets matters more than niche metrics
+// like watchlist-users); the fabric still serves every metric for every coin.
+// Every other family enumerates all its metrics (each has ≤7).
+const DP_COIN_METRICS = [
+ 'price', 'market-cap', 'fdv', 'volume-24h', 'change-24h',
+ 'change-7d', 'rank', 'ath', 'atl', 'circulating-supply',
+];
+
+let _dpDiscoveryCache = null; // { origin, items, at }
+
+// A synthetic, schema-shaped example value for a metric, derived from its unit.
+// The datapoint output.example carries the real label/unit; the value is
+// illustrative (all datapoint examples are synthetic by design).
+function datapointExampleValue(metricDef) {
+ const unit = String(metricDef?.unit || '').toLowerCase();
+ if (unit.includes('usd') || unit.includes('$')) return 1234567.89;
+ if (unit.includes('bps')) return -3;
+ if (unit.includes('%') || unit.includes('pct') || unit.includes('percent')) return 2.5;
+ if (
+ unit === '' || unit.includes('text') || unit.includes('label') ||
+ unit.includes('name') || unit.includes('symbol') || unit.includes('class')
+ )
+ return metricDef?.label || 'value';
+ return 42.5;
+}
+
+async function buildDatapointItemsUncached(origin) {
const items = [];
const svc = withService({
serviceName: 'three.ws Datapoints',
tags: ['crypto', 'market-data', 'datapoint', 'x402'],
});
- const push = (family, id, metric, exampleValue) => {
+ const push = (family, id, metric) => {
const familyDef = DATAPOINT_FAMILIES[family];
const metricDef = familyDef.metrics[metric];
const priceAtomics = datapointPriceFor(`datapoint-${family}`, DATAPOINT_DEFAULT_ATOMICS);
@@ -549,7 +604,7 @@ async function buildDatapointItems(origin) {
metric,
label: metricDef.label,
unit: metricDef.unit,
- value: exampleValue,
+ value: datapointExampleValue(metricDef),
as_of: '2026-07-11T00:00:00.000Z',
source: 'three.ws market-data',
},
@@ -558,38 +613,116 @@ async function buildDatapointItems(origin) {
});
};
+ const metricsOf = (family) => Object.keys(DATAPOINT_FAMILIES[family].metrics);
+
// Every metric of the no-id families — static, always present.
for (const family of ['global', 'fear-greed', 'gas']) {
- for (const metric of Object.keys(DATAPOINT_FAMILIES[family].metrics)) {
- push(family, null, metric, metric === 'label' ? 'Greed' : 42.5);
- }
+ for (const metric of metricsOf(family)) push(family, null, metric);
+ }
+
+ // Small headline slice when wide enumeration is disabled — reproduces the
+ // original catalog (top 20 coins × 3 metrics, top 10 protocols × tvl).
+ if (!DP_WIDE) {
+ try {
+ const { rows } = await fetchMarketsTable({ page: 1, perPage: 20, category: '' });
+ for (const row of rows) for (const metric of ['price', 'market-cap', 'change-24h']) if (row.id) push('coin', row.id, metric);
+ } catch (err) { console.error('[wk/x402-discovery] coin slice', err?.message || err); }
+ try {
+ const { protocols } = await buildProtocols();
+ for (const p of protocols.slice(0, 10)) if (p.slug) push('protocol', p.slug, 'tvl');
+ } catch (err) { console.error('[wk/x402-discovery] protocol slice', err?.message || err); }
+ return items;
}
- // Top coins × headline metrics — ids resolved from the live cached table.
+ // ── Wide enumeration: real ids from the cached feeds × every family metric ──
+
+ // Top coins by market cap (CoinGecko markets table, one cached page ≤100).
try {
- const { rows } = await fetchMarketsTable({ page: 1, perPage: 20, category: '' });
- for (const row of rows) {
- for (const metric of ['price', 'market-cap', 'change-24h']) {
- push('coin', row.id, metric, metric === 'price' ? row.price : 42.5);
- }
+ const { rows } = await fetchMarketsTable({ page: 1, perPage: Math.min(DP_CAPS.coin, 100), category: '' });
+ const all = new Set(metricsOf('coin'));
+ const metrics = DP_COIN_METRICS.filter((m) => all.has(m));
+ for (const row of rows.slice(0, DP_CAPS.coin)) {
+ if (!row.id) continue;
+ for (const metric of metrics) push('coin', row.id, metric);
}
- } catch (err) {
- console.error('[wk/x402-discovery] datapoint coin slice unavailable', err?.message || err);
- }
+ } catch (err) { console.error('[wk/x402-discovery] coin slice', err?.message || err); }
- // Top protocols by TVL × tvl — same runtime derivation.
+ // Top protocols by TVL (DeFiLlama).
try {
const { protocols } = await buildProtocols();
- for (const p of protocols.slice(0, 10)) {
- if (p.slug) push('protocol', p.slug, 'tvl', p.tvl);
+ const metrics = metricsOf('protocol');
+ for (const p of protocols.slice(0, DP_CAPS.protocol)) {
+ if (!p.slug) continue;
+ for (const metric of metrics) push('protocol', p.slug, metric);
}
- } catch (err) {
- console.error('[wk/x402-discovery] datapoint protocol slice unavailable', err?.message || err);
- }
+ } catch (err) { console.error('[wk/x402-discovery] protocol slice', err?.message || err); }
+
+ // Every chain (DeFiLlama /v2/chains — ~350, fully enumerable).
+ try {
+ const chains = [...(await allChains()).values()].map((c) => c?.name).filter(Boolean);
+ const metrics = metricsOf('chain');
+ for (const name of chains.slice(0, DP_CAPS.chain)) {
+ for (const metric of metrics) push('chain', name, metric);
+ }
+ } catch (err) { console.error('[wk/x402-discovery] chain slice', err?.message || err); }
+
+ // Top stablecoins by supply (DeFiLlama). The map keys id AND symbol to the
+ // same row — enumerate each once by its canonical id (matches d/index.js).
+ try {
+ const seen = new Set();
+ const ids = [];
+ for (const [key, row] of (await allStablecoins()).entries()) {
+ if (seen.has(row)) continue;
+ seen.add(row);
+ ids.push(/^\d+$/.test(key) ? key : row.symbol || key);
+ if (ids.length >= DP_CAPS.stablecoin) break;
+ }
+ const metrics = metricsOf('stablecoin');
+ for (const id of ids) for (const metric of metrics) push('stablecoin', id, metric);
+ } catch (err) { console.error('[wk/x402-discovery] stablecoin slice', err?.message || err); }
+
+ // Top yield pools by TVL (DeFiLlama yields — pre-sorted TVL desc).
+ try {
+ const { pools } = await loadYieldPools();
+ const metrics = metricsOf('pool');
+ for (const p of pools.slice(0, DP_CAPS.pool)) {
+ if (!p.pool) continue;
+ for (const metric of metrics) push('pool', p.pool, metric);
+ }
+ } catch (err) { console.error('[wk/x402-discovery] pool slice', err?.message || err); }
+
+ // Top exchanges by trust rank (CoinGecko /exchanges).
+ try {
+ const { exchanges } = await buildExchanges();
+ const metrics = metricsOf('exchange');
+ for (const e of exchanges.slice(0, DP_CAPS.exchange)) {
+ if (!e.id) continue;
+ for (const metric of metrics) push('exchange', e.id, metric);
+ }
+ } catch (err) { console.error('[wk/x402-discovery] exchange slice', err?.message || err); }
return items;
}
+// Memoized wrapper: the slice rebuilds at most once per DP_TTL_MS per origin. A
+// total-failure rebuild serves the last good cache (or an empty block) rather
+// than dropping — or hammering upstreams on — every discovery request.
+async function buildDatapointItems(origin) {
+ const now = Date.now();
+ if (_dpDiscoveryCache && _dpDiscoveryCache.origin === origin && now - _dpDiscoveryCache.at < DP_TTL_MS) {
+ return _dpDiscoveryCache.items;
+ }
+ try {
+ const items = await buildDatapointItemsUncached(origin);
+ _dpDiscoveryCache = { origin, items, at: now };
+ return items;
+ } catch (err) {
+ console.error('[wk/x402-discovery] datapoint build failed', err?.message || err);
+ if (_dpDiscoveryCache?.items) return _dpDiscoveryCache.items;
+ return [];
+ }
+}
+
// ── output.example backfill ──────────────────────────────────────────────────
// Indexers (agentic.market / x402scan) render and rank a resource by its
// response example. A resource with no `bazaar.info.output.example` still
diff --git a/data/changelog.json b/data/changelog.json
index 7bbddb784..c707facf8 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,17 @@
{
"$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-07-12",
+ "title": "AI features can no longer go down when one provider does",
+ "summary": "Every AI-powered feature on three.ws (fact checks, agent chat, persona extraction, scene composing) routes through one shared brain that tries free providers first and falls back automatically. That chain just got much deeper: Groq now has a second lane with its own separate quota, OpenRouter gets a zero-credit free lane so an empty account no longer kills it, optional Cerebras and Google AI Studio lanes activate the moment a key is added, and — the anchor — Gemini on the platform's own Google Cloud now backs the whole chain with no third-party quota to exhaust. Previously a rare bad hour where every free tier was exhausted at once could surface an error; now the request rides through. The fact-checker was also corrected to stop favoring a paid key ahead of the free lanes.",
+ "tags": [
+ "improvement",
+ "fix",
+ "infra"
+ ],
+ "link": "/changelog"
+ },
{
"date": "2026-07-12",
"title": "Oversized x402 payment headers fixed",
@@ -13214,6 +13225,25 @@
"feature"
],
"link": "/agents"
+ },
+ {
+ "date": "2026-07-12",
+ "title": "Seeker wallet signing fixed before it ever shipped",
+ "summary": "Automated testing of the Solana Seeker app in an Android emulator against Solana Mobile's reference wallet caught four bugs in our Mobile Wallet Adapter integration: the app icon was sent in a format the wallet spec rejects, and message signing, transaction signing, and send-transaction all read the wallet's response in the wrong shape. All four are fixed — wallet connect was verified end to end, returning a real public key through the on-device signing flow.",
+ "tags": [
+ "fix",
+ "security"
+ ]
+ },
+ {
+ "date": "2026-07-12",
+ "title": "The autonomous coin launcher learned taste",
+ "summary": "The Memetic Launcher's picks got a full quality overhaul. Its cultural radar was half-blind — the pump.fun intel feed was silenced by a miscalibrated quality bar and generic sector words like 'meme' drowned out actual memes — so most picks fell back to random word-salad names. Now the radar reads live meme culture properly (Know Your Meme, Google Trends, Hacker News, Wikipedia attention, and pump.fun's own breakout data), each launch rides a specific rising narrative, the launcher remembers its recent picks so it never re-mints the same joke, coin descriptions are no longer cut off mid-sentence, and a quality gate refuses to spend real SOL on a filler pick when no genuine signal exists. Launch previews in the user launcher now refresh hourly instead of every minute.",
+ "tags": [
+ "improvement",
+ "fix"
+ ],
+ "link": "/launcher"
}
]
}
diff --git a/data/pages.json b/data/pages.json
index 7251d9a36..204a59d31 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -1827,6 +1827,14 @@
"changefreq": "weekly",
"added": "2026-07-07"
},
+ {
+ "path": "/docs/autonomous-economy",
+ "title": "Docs · The autonomous economy",
+ "description": "How the three.ws on-chain treasury funds itself and where every dollar flows: the funding-root and engine wallets, the topup/sweepback loop, the allowlist- and destination-locks that keep money inside platform-owned wallets, and the two leak scanners that audit every signer wallet on-chain every minute — plus how to verify there's no leak yourself.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-07-12"
+ },
{
"path": "/docs/walk",
"title": "Docs · Walk Avatar",
diff --git a/docs/autonomous-economy.md b/docs/autonomous-economy.md
new file mode 100644
index 000000000..ca9d66342
--- /dev/null
+++ b/docs/autonomous-economy.md
@@ -0,0 +1,137 @@
+# The autonomous economy: where the money flows
+
+three.ws runs a small on-chain treasury that funds itself. A single **funding-root**
+wallet tops up a handful of **engine** wallets; those engines do real work — launch
+coins, run buybacks, pay holders, settle agent-to-agent invoices — and any surplus
+sweeps back up to the root. Every wallet is on Solana mainnet, every move is public,
+and the platform **scans its own wallets for leaks every minute**.
+
+This page explains the whole loop in plain language: which wallet does what, how money
+can and cannot move, and how you can verify there's no leak yourself.
+
+Companion docs: [Money map](money-map.md) (which wallet receives each *payment*),
+[Economy master](economy-master.md) (the funding-root subsystem in depth), and the
+[Solana signers runbook](../api/_lib/solana-signers.js) (every signer, its floor, and
+how to fund it).
+
+---
+
+## 1. The wallets
+
+The economy runs on three primary wallets plus a few single-purpose signers. They're
+vanity addresses, so you can recognize them on sight.
+
+| Wallet | Address | Role |
+| ------ | ------- | ---- |
+| **Funding root** | `WwwuGbqHrwF5…T3WwW` | The economy master. Holds the reserve and tops up every other wallet when it drops below its floor. It **only funds** — it never trades, launches, or settles. |
+| **Engine wallet** | `wwwqv…HGUn` | The autonomous engines: pump.fun coin launcher, buyback relayer, reflection/lottery payouts. This is the wallet that *spends* to do work. |
+| **Treasury / receiver** | `wwwww…ccrU` | Receives all inbound x402 payments (`X402_PAY_TO_SOLANA`) and holds platform revenue. |
+| **Ring payer** | `X4o2…astML` | The x402 autonomous payment ring — pays and receives USDC for agent-to-agent settlements. |
+| **a2a-payer** | `Huch…Lmh6Z` | Co-signs agent-to-agent USDC transfers. |
+| **Fee-payer** | `GGf9…5XQj` | Co-signs and pays network fees on x402 settlements. |
+
+Every engine signs from its **own** keypair. No receiver address is hardcoded in the
+app — an unset receiver fails closed rather than routing to a baked-in address.
+
+---
+
+## 2. How money moves (the loop)
+
+```
+ ┌───────────────────────────┐
+ deposits / revenue ─▶│ FUNDING ROOT (Wwwu) │◀── surplus swept back up
+ │ keeps a reserve, funds │◀── revenue consolidated
+ │ engines below floor │
+ └─────┬───────┬───────┬─────┘
+ topup (SOL) │ │ │
+ ▼ ▼ ▼
+ ┌─────────┐ ┌───────┐ ┌──────────┐
+ │ ENGINES │ │TREAS. │ │ a2a / │
+ │ (wwwqv) │ │(wwwww)│ │ fee-payer│
+ └────┬────┘ └───┬───┘ └──────────┘
+ work (launches, │ │ x402 revenue
+ buybacks, payouts) │
+ ▼ ▼
+ DEX / pump.fun / holders (all on-chain, all public)
+```
+
+1. **Topup (down).** Every 30 minutes the `treasury-topup` cron reads each engine
+ wallet's balance and, for any below its floor, sends it SOL from the funding root.
+2. **Work.** The engines spend to do their jobs — launch coins, buy back tokens, pay
+ holders, settle invoices.
+3. **Sweepback (up).** Surplus above each engine's operating float is swept back to the
+ funding root, so the whole fleet cycles through one owner-controlled wallet.
+
+The result is a closed loop: **root → engines → work → surplus → root.**
+
+---
+
+## 3. Why it can't leak (by construction)
+
+Two hard rules are enforced in code, not by convention:
+
+- **Topup is allowlist-locked.** The funding root can only send to a pubkey that
+ resolves from the signer registry (`SOLANA_SIGNERS`). An address not in that registry
+ can never receive a topup — the transfer is rejected before it's built.
+ ([`api/_lib/economy-master.js`](../api/_lib/economy-master.js))
+- **Sweepback is destination-locked.** The sweepback destination is hard-coded to the
+ funding-root address. No request parameter can redirect it.
+ ([`api/_lib/economy-sweepback.js`](../api/_lib/economy-sweepback.js))
+
+Together these mean money can only move **inside the set of wallets the platform owns.**
+
+---
+
+## 4. The platform audits itself for leaks — every minute
+
+You don't have to take rule #3 on faith. Two on-chain scanners run continuously:
+
+- **`wallets-leak-scan`** watches *every* resolvable signer wallet (funding root, coin
+ launcher, treasuries, x402 sponsor/payer, SNS parent, fee-payer, …).
+- **`x402-ring-leak-scan`** watches the x402 ring role wallets specifically.
+
+Each reads new transactions for every wallet and classifies every debit as one of:
+*internal* (to another controlled wallet), *network fee*, *delegation*, or **leak** — a
+transfer to an address outside the controlled universe. Any leak fires a **critical
+alert** with the signature, counterparty, amount, and a rotate-the-key recommendation,
+and records a verdict in `payment_reconciliation`. The scanners are **read-only** — they
+never move funds.
+
+**As of this writing, the scanners have examined 44,122 transactions across all wallets
+and found zero leaks and zero leak verdicts, ever.**
+
+### Verify it yourself
+
+Every wallet above is public. Open any of them in a Solana explorer
+(`https://solscan.io/account/<address>`) and follow the transfers. You'll see SOL move
+between the platform's own wallets, out to DEX programs (Jupiter, PumpSwap) for
+buybacks, and to holder/user wallets for payouts — and back. Nothing to a wallet the
+platform doesn't control.
+
+---
+
+## 5. Reading the numbers (what "spend" really means)
+
+A few things that look alarming in a raw explorer but aren't:
+
+- **Huge token amounts** (millions of "tokens" in a single transaction) are the launched
+ pump.fun coin moving through an AMM pool during a buyback — the coin has a multi-million
+ supply priced in fractions of a cent. It is not millions of dollars.
+- **SOL "leaving" to a DEX** is a swap: the SOL becomes token or USDC value the platform
+ still holds, not money spent.
+- **Failed launches and buybacks** cost only network fees, not their launch budget — the
+ budget is only committed on a successful mint.
+
+The one number that matters for "is anything leaking" is the scanners' leak count. It is
+zero.
+
+---
+
+## Related
+
+- [Money map](money-map.md) — which wallet receives each kind of payment, and the
+ platform's cut.
+- [Economy master](economy-master.md) — the funding-root subsystem, its ledger, and the
+ topup/sweepback crons in depth.
+- [x402 ring economy](x402-ring-economy.md) — how the autonomous payment ring settles
+ USDC between agents.
diff --git a/docs/start-here.md b/docs/start-here.md
index 31a4392b6..0b5f88a8d 100644
--- a/docs/start-here.md
+++ b/docs/start-here.md
@@ -70,6 +70,7 @@ If you're here to create and share agents rather than write code, follow this pa
- **Trading?** → [The trading surfaces](./trading-surfaces.md) maps the solo stack (Radar, Coin Intelligence, Live Trade Feed, Watchlist, Mission Control); [trading arenas](./trading-arenas.md) covers tournaments, the theater, vaults, and swarms; [Oracle](./oracle.md) is the conviction engine underneath all of it
- **Trusting an agent with money?** → [Custody you can verify](./custody.md) — spend limits, freeze, Merkle proof-of-custody, and social recovery; [claim your wallet](./trader-card.md) turns any pump.fun track record into a public, provable Trader Card. Every real-funds feature sits behind the [risk acknowledgment](./risk-acknowledgment.md) — read the [Risk Disclosure](https://three.ws/legal/risk) before committing anything
- **Vetting a counterparty before you pay it?** → [Trust primitives](./trust-primitives.md) — the cross-chain Agent Reputation endpoint scores ANY wallet, mint, or agent id (Solana or EVM) 0–100 from real on-chain evidence, in one paid call, before your agent transacts
+- **Wondering where the platform's money goes?** → [The autonomous economy](./autonomous-economy.md) — how the on-chain treasury funds itself, the funding-root → engines → sweepback loop, the locks that keep every dollar inside platform-owned wallets, and the two leak scanners that audit every wallet on-chain every minute (so far: 44,122 transactions scanned, zero leaks)
- **Your agent needs market data?** → [Market Data API](./market-data-api.md) — the live feeds behind every /markets page (prices, TVL, yields, stablecoins, gas, derivatives, exploits) as 17 pay-per-call x402 endpoints from $0.001 USDC, plus the one-call `market-pulse` bundle; start at the free index [/api/x402/market](https://three.ws/api/x402/market)
- **Listing our services across the x402 ecosystem?** → [x402 distribution](./x402-distribution.md) — the operating playbook for x402scan, the CDP Bazaar, agentic.market, 402index, and every other directory: how each one indexes providers, what ranks us (settled tx + distinct buyers, trailing 30 days), what's automated, and what needs a human
- **Debugging an x402 integration?** → [x402 developer tools](./x402-dev-tools.md) — a free test bench: echo your payment envelope (signatures redacted), debug a failed 402 exchange into an ordered fix list, and verify a receipt's attestation and on-chain settlement, all against a live server without spending anything
diff --git a/prompts/robinhood-chain/02-sdk-simple-wrapper.md b/prompts/robinhood-chain/02-sdk-simple-wrapper.md
new file mode 100644
index 000000000..5d605f4af
--- /dev/null
+++ b/prompts/robinhood-chain/02-sdk-simple-wrapper.md
@@ -0,0 +1,44 @@
+# 02 — Simple wrapper: `hood-js` (five lines to your first trade)
+
+Read `prompts/robinhood-chain/_shared.md` first. Requires Wave 1 (`robinhood/robinhood-chain-sdk/`)
+to exist — install it via `file:../robinhood-chain-sdk` and depend on its npm name.
+
+## Mission
+Build `robinhood/hood-js/` — the "just works" layer over the core SDK, for developers who don't
+want to know what a viem transport is. One import, sensible defaults, promise-first, browser and
+Node. Think `axios` vs `http`. npm name `hood-js` (fallbacks: `hoodjs`, `easyhood`).
+
+## API surface (complete — nothing more, nothing hidden)
+```js
+import hood from 'hood-js'
+
+await hood.price('AAPL') // → { symbol, usd, updatedAt }
+await hood.prices(['AAPL','TSLA','NVDA']) // batched multicall under the hood
+await hood.portfolio('0xabc…') // multiplier-correct, USD-valued positions
+await hood.coins() // trending memecoins w/ price + 24h (launchpads + Uniswap)
+await hood.launches({ live: true }, cb) // stream new launchpad coins
+await hood.quote({ sell: 'USDG', buy: 'CASHCAT', amount: 100 }) // swap quote, no wallet needed
+await hood.swap({ ...quote, wallet }) // execute — wallet = private key env or injected EIP-1193
+hood.testnet() // flip every call to 46630
+```
+- Zero required config. Public RPC default, `hood.config({ rpcUrl, alchemyKey })` optional.
+- Stock Token buy paths require `hood.config({ acknowledgeEligibility: true })` and surface the
+ `_shared.md` disclosure in the thrown error otherwise. Memecoins need nothing.
+- Every function has a one-line JSDoc + a runnable snippet in the README that matches reality.
+
+## Requirements
+- Bundle size budget: ≤ 15 kB gzipped on top of viem (verify with a size check script; print it
+ in the report). Browser build works from a `<script type="module">` CDN-style import.
+- Friendly errors: no raw viem stack traces — wrap into plain-language messages with a `cause`.
+- Vitest: unit (arg validation, formatting) + live (real `hood.price('AAPL')` on mainnet, real
+ testnet `hood.swap` with faucet funds — paste tx hash).
+- `docs/` site per `_shared.md`: landing page IS the pitch — an interactive REPL-style demo where
+ visitors type `hood.price('TSLA')` and see the live answer (client-side, public RPC), a
+ copy-paste quickstart, and the full API table. This page must be beautiful enough to trend on
+ developer X.
+- README: install, 30-second quickstart, API reference table, testnet guide, eligibility note.
+
+## Done checklist
+- [ ] The README quickstart runs verbatim (`node quickstart.mjs`) in a fresh folder.
+- [ ] Live browser demo returns real prices when docs/index.html is opened locally.
+- [ ] Testnet swap tx hash in the report; size budget printed; `npm pack` clean.
diff --git a/prompts/robinhood-chain/03-sdk-advanced-wrapper.md b/prompts/robinhood-chain/03-sdk-advanced-wrapper.md
new file mode 100644
index 000000000..9269922b7
--- /dev/null
+++ b/prompts/robinhood-chain/03-sdk-advanced-wrapper.md
@@ -0,0 +1,50 @@
+# 03 — Advanced toolkit: `hoodkit` (the power-user layer)
+
+Read `prompts/robinhood-chain/_shared.md` first. Requires Wave 1 core SDK
+(`file:../robinhood-chain-sdk` + npm name dep).
+
+## Mission
+Build `robinhood/hoodkit/` — the advanced wrapper for teams building real products on Robinhood
+Chain: streaming, caching, batching, indexing, strategy primitives, React hooks. Where `hood-js`
+hides complexity, `hoodkit` weaponizes it. npm `hoodkit` (fallbacks: `hood-kit`, `hoodchain-kit`).
+
+## Modules
+
+1. **`stream`** — unified real-time layer over the sequencer firehose + RPC log subscriptions:
+ `streamPrices(symbols)`, `streamSwaps({ pool | token })`, `streamLaunches()`,
+ `streamPortfolio(address)`. Backpressure-safe async iterators AND event-emitter forms.
+ Automatic reconnect with resume-from-block gap fill (no silently dropped events — test this
+ by killing the socket mid-stream in an integration test).
+2. **`cache`** — pluggable read-through cache (memory LRU default, Redis adapter interface) with
+ per-datatype TTLs (quotes 2s, registry 1h, multipliers 10m); request coalescing so N
+ concurrent identical reads → 1 RPC call (test with 100 parallel `getQuote`s → assert 1 fetch).
+3. **`batch`** — multicall aggregation with automatic chunking + a `plan()` API that batches
+ arbitrary SDK reads into minimal RPC round-trips.
+4. **`index`** — lightweight local indexer: sync Transfer/Swap/launch events for a token set
+ into SQLite (better-sqlite3), incremental from last synced block, exposing
+ `holders(token)`, `candles(token, interval)` (build OHLCV from swap events — real math,
+ tested against a known pool's Blockscout history), `volume24h(token)`.
+5. **`strategy`** — primitives autonomous agents need (prompt 07 consumes this): position
+ tracker with PnL (realized/unrealized, multiplier-aware for Stock Tokens), TWAP executor
+ (slice a big swap across time with per-slice slippage bounds), price triggers
+ (`onCross(symbol, threshold, cb)`), spend-cap guard, dry-run mode that builds+simulates
+ (`eth_call`) without sending.
+6. **`react`** — `@hoodkit/react` subpath: `useQuote`, `usePortfolio`, `useLaunches`, `useSwap`
+ hooks over the stream/cache layers, SSR-safe, with a small real demo app in `examples/react-demo`
+ (Vite) actually run during verification.
+
+## Requirements
+- Same packaging bar as the core SDK (ESM+CJS, exports map, Node ≥ 20). Keep heavy deps optional:
+ better-sqlite3 and react are optional peer deps; core installs light.
+- Vitest: unit for cache/batch/strategy math; integration: live stream 60s of real mainnet
+ swaps on a busy pool (paste event count), index a real token's last 1000 blocks and assert
+ holder math against Blockscout's holder count (tolerance documented).
+- `docs/` static site per `_shared.md`: landing = live dashboard demo (client-side: streaming
+ prices + latest launches rendered beautifully), guides per module, API reference (typedoc).
+- README: when to use hoodkit vs hood-js vs core SDK (honest decision table).
+
+## Done checklist
+- [ ] Reconnect gap-fill test proves no dropped events.
+- [ ] Coalescing test proves 100→1. Candle math validated against a real pool.
+- [ ] React demo runs (`npm run dev` exercised, screenshot-worthy). `npm pack` clean on both entry points.
+- [ ] Live-stream evidence + indexer-vs-Blockscout comparison in the report.
diff --git a/prompts/robinhood-chain/04-market-data-api.md b/prompts/robinhood-chain/04-market-data-api.md
new file mode 100644
index 000000000..b0cbc308e
--- /dev/null
+++ b/prompts/robinhood-chain/04-market-data-api.md
@@ -0,0 +1,57 @@
+# 04 — Hosted Market Data API: `hood-api` (free tier + x402)
+
+Read `prompts/robinhood-chain/_shared.md` first. Requires Wave 1 core SDK
+(`file:../robinhood-chain-sdk`). Coordinates with prompt 05 (`hood402`) — if its middleware
+exists when you run, consume it; otherwise implement x402 402-challenge handling inline against
+the standard x402 spec and leave a clean seam to swap in `hood402` later.
+
+## Mission
+Build `robinhood/hood-api/` — a deployable REST API service that is the missing market-data
+layer for Robinhood Chain, monetized with x402. Nobody offers this: RWA.xyz is enterprise-paid,
+CoinGecko has no equity semantics. This is the flagship API product.
+
+## Endpoints (all real data, JSON, versioned under `/v1`)
+
+Free (rate-limited by IP, generous):
+- `GET /v1/health`, `GET /v1/chain` — chain stats: block height, gas, TVL (DefiLlama), bridge flows.
+- `GET /v1/stocks` — all Stock Tokens: Chainlink price, DEX price (Uniswap pool mid), premium/
+ discount between the two, uiMultiplier, 24h DEX volume + liquidity (GeckoTerminal/on-chain).
+- `GET /v1/stocks/:symbol` — detail: candles (from hoodkit-style swap-event OHLCV or
+ GeckoTerminal), holders (Blockscout), feed metadata, contract links.
+- `GET /v1/coins` — memecoins: launchpad state (bonding/graduated), price, volume, age, holders.
+- `GET /v1/coins/:address` — detail incl. launch info and graduation status.
+- `GET /v1/launches` — recent + live launchpad activity (NOXA, The Odyssey).
+
+Paid via x402 (USDC on Base + USDG on Robinhood Chain when hood402 lands; price each $0.001–0.01):
+- `GET /v1/portfolio/:address` — multiplier-correct full portfolio with USD valuation + PnL basis.
+- `GET /v1/stocks/:symbol/history` — deep OHLCV history.
+- `GET /v1/equities` — THE unique one: unified cross-issuer tokenized-equity view — same
+ underlying ticker across Robinhood Chain, xStocks (Backed, public no-auth API per their docs)
+ and Ondo GM (Chainlink tokenized-equity feeds): normalized price, venue premium/discount
+ spread, where it's cheapest. Cache upstreams respectfully.
+- `GET /v1/firehose` token + `wss /v1/ws` — real-time stream (launches, big swaps, stock ticks)
+ with metered x402 session auth.
+
+## Requirements
+- Node 20 + Express (or Hono), no framework bloat; strict input validation (zod); per-endpoint
+ cache TTLs; upstream failover (public RPC → Alchemy if `ALCHEMY_KEY` set; CoinGecko →
+ GeckoTerminal → on-chain, in the failover style of three.ws market handlers).
+- Every response includes `source` + `asOf` fields. Errors are structured
+ (`{ error, hint, docs }`) — never a bare 500.
+- OpenAPI 3.1 spec (`openapi.json`) generated and served at `/v1/openapi.json`; docs site renders it.
+- Deploy: `Dockerfile` (distroless, PORT-aware) + Cloud Run instructions + `vercel.json`
+ alternative. Deploy for real only if creds exist; otherwise document exact commands.
+- Tests: vitest with real upstream integration tests (hit your own running server via
+ `npm run dev` in the test, assert real data shapes; no recorded fixtures for the live suite).
+- `docs/` static site per `_shared.md`: landing with LIVE example responses (fetched client-side
+ from the deployed URL if deployed, else rendered from a real captured response with a clear
+ "sample of live output" label — capture it during your run, from the real server), full
+ endpoint reference from the OpenAPI spec, x402 payment walkthrough with a working client
+ snippet, pricing table.
+
+## Done checklist
+- [ ] Local server run exercised: `curl` transcript for every endpoint in the report (real data).
+- [ ] x402 402-challenge → pay → 200 flow proven with a scripted client (testnet/base-sepolia
+ settlement acceptable for the E2E; document the mainnet config).
+- [ ] `/v1/equities` returns a real cross-venue row for at least 3 tickers with venue spreads.
+- [ ] OpenAPI validates; Dockerfile builds; report lists deploy status + owner actions.
diff --git a/prompts/robinhood-chain/05-x402-usdg-rail.md b/prompts/robinhood-chain/05-x402-usdg-rail.md
new file mode 100644
index 000000000..150cde460
--- /dev/null
+++ b/prompts/robinhood-chain/05-x402-usdg-rail.md
@@ -0,0 +1,47 @@
+# 05 — x402 on Robinhood Chain: `hood402` (USDG payment rail)
+
+Read `prompts/robinhood-chain/_shared.md` first. Requires Wave 1 core SDK for chain plumbing.
+
+## Mission
+Build `robinhood/hood402/` — the x402 payment stack for USDG on Robinhood Chain: server
+middleware, client, and facilitator. The only prior art is days old (`project-r0x`, MIT — study
+its facilitator design and the canonical `x402` protocol repo/spec; follow the STANDARD x402
+scheme exactly rather than inventing a variant, so any x402 client interoperates). npm scope:
+`hood402` with subpath exports (fallbacks: `x402-usdg`, `hood-402`).
+
+## Deliverables
+
+1. **Protocol conformance** — implement x402 `exact` scheme for EVM with USDG on chain 4663:
+ verify USDG's EIP-3009/`transferWithAuthorization` or EIP-2612 permit support by READING the
+ verified contract on Blockscout first; build settlement on whichever the contract actually
+ supports (document the finding — this decision is load-bearing). Testnet twin on 46630.
+2. **`hood402/server`** — Express/Hono/Next middleware: `paywall({ price, payTo, network: 'robinhood' })`
+ issuing spec-compliant 402 challenges and verifying/settling via facilitator or self-settle mode.
+3. **`hood402/client`** — fetch wrapper: intercept 402 → sign payment (viem wallet) → retry,
+ with spend caps per origin and a session cache. Works in Node and browser (injected wallet).
+4. **Facilitator service** — `facilitator/` subfolder: verify + settle endpoints per x402 spec,
+ Dockerfile, Cloud Run deploy docs, idempotent settlement with a small SQLite ledger, metrics
+ endpoint. This is what we run in production; keys via env.
+5. **Interop proof** — E2E script: a demo paid endpoint + the client completing a REAL paid
+ request with USDG on testnet 46630 (faucet ETH for gas; if no USDG testnet faucet exists,
+ deploy a mock— NO: deploy nothing fake. If testnet USDG doesn't exist, run the E2E on
+ mainnet with a $0.001 real payment funded from the owner's wallet if creds are present,
+ otherwise prove the full flow up to settlement broadcast in simulation (`eth_call`) and mark
+ settlement as pending-owner-funding in the report. State plainly which path you took.)
+6. **three.ws seam** — a short `INTEGRATION.md` describing exactly how three.ws's existing x402
+ catalog adds `network: robinhood-chain` as an accepted rail using this package (env vars,
+ settlement wallet, facilitator URL). Do not modify three.ws in this prompt.
+
+## Requirements
+- Strict TypeScript, ESM+CJS, vitest unit suite for challenge/verify/settle state machine
+ (malformed payloads, replay, expiry, wrong-chain, underpayment — each a test).
+- `docs/` static site per `_shared.md`: landing explains x402-on-Robinhood-Chain in one screen
+ with an animated request/402/pay/200 diagram (CSS, no video), quickstarts for the three
+ pieces, spec-conformance notes, r0x comparison (fair, factual).
+- README: security model, key handling, spend caps, replay protection.
+
+## Done checklist
+- [ ] USDG settlement mechanism verified from the actual contract, cited by address + Blockscout link.
+- [ ] State-machine tests green; interop E2E evidence per deliverable 5 with the honest path taken.
+- [ ] Facilitator Docker image builds; `npm pack` clean on both packages.
+- [ ] INTEGRATION.md actionable enough that a three.ws agent can wire the rail without research.
diff --git a/prompts/robinhood-chain/06-mcp-servers.md b/prompts/robinhood-chain/06-mcp-servers.md
new file mode 100644
index 000000000..ddddb2517
--- /dev/null
+++ b/prompts/robinhood-chain/06-mcp-servers.md
@@ -0,0 +1,49 @@
+# 06 — MCP servers: `hood-mcp` (chain data + trading for AI agents)
+
+Read `prompts/robinhood-chain/_shared.md` first. Requires Wave 1 core SDK
+(`file:../robinhood-chain-sdk`).
+
+## Mission
+Build `robinhood/hood-mcp/` — production MCP servers for Robinhood Chain. Robinhood's own MCP
+covers only their US brokerage; the chain itself has just two 0-star read-only hobby MCPs.
+Ours is the productized one: full data surface + a guarded trading surface. npm `hood-mcp`
+(fallbacks: `hoodchain-mcp`, `robinhood-chain-mcp-server`).
+
+## Deliverables — two servers, one package
+
+1. **`hood-mcp` (data server, zero-config, read-only)** — stdio + streamable-HTTP transports,
+ built on `@modelcontextprotocol/sdk` (use the current SDK — check npm for the latest major):
+ - `list_stock_tokens`, `get_stock_quote` (Chainlink + DEX price + premium),
+ `get_portfolio` (multiplier-correct), `get_coin` / `list_trending_coins`,
+ `get_recent_launches`, `watch_launches` (streamable), `get_chain_stats`,
+ `search_token` (symbol/name/address via registry + Blockscout).
+ - Every tool: precise JSON schema, one-line description an LLM can route on, real error
+ messages. No API key required — public RPC default, `ALCHEMY_KEY` env optional.
+2. **`hood-mcp/trading` (wallet server, explicitly opt-in)** — separate entry point, requires
+ `ROBINHOOD_CHAIN_PRIVATE_KEY` + `HOOD_MCP_ENABLE_TRADING=1`:
+ - `get_swap_quote`, `execute_swap` (memecoins; Stock Token buys additionally require
+ `HOOD_MCP_ACKNOWLEDGE_ELIGIBILITY=1` per `_shared.md`), `transfer_usdg`, `get_my_portfolio`.
+ - Hard spend caps via `HOOD_MCP_MAX_SPEND_USDG` (per-call and per-session), every mutating
+ tool returns the simulation result and requires a `confirm: true` argument round-trip.
+3. **Registry listings** — prepare (don't submit) the metadata for the MCP registries the
+ ecosystem actually uses (modelcontextprotocol registry `server.json`, Smithery config), plus
+ Claude Desktop / Claude Code / Cursor install snippets in the README — exact, tested JSON.
+4. **Optional x402 monetization seam** — if `robinhood/hood402` exists when you run, add a
+ config flag that paywalls the expensive data tools (history, firehose) using its middleware
+ on the HTTP transport; otherwise leave a documented seam. Free tools stay free either way.
+
+## Requirements
+- Vitest: tool-schema validation tests + a scripted MCP client (SDK's client) exercising every
+ tool for real: data tools against mainnet, trading tools against testnet 46630 with faucet
+ funds — a REAL `execute_swap` round-trip (simulate → confirm → receipt) with tx hash pasted.
+- `docs/` static site per `_shared.md`: landing shows a real Claude Code session transcript
+ (run it yourself with the local server via `claude mcp add`) doing "what's AAPL trading at
+ on-chain and what's the premium?" — the answer with live numbers is the screenshot. Install
+ matrix (Claude Code / Desktop / Cursor / any stdio client), tool reference, safety model page.
+- README: 60-second install per client, both servers, env table, safety model.
+
+## Done checklist
+- [ ] Every tool exercised by the scripted client with real outputs in the report.
+- [ ] Real testnet swap through the trading server (hash in report). Spend-cap + confirm-gate tests green.
+- [ ] Claude Code session actually run against the local build; transcript captured for docs.
+- [ ] `npm pack` clean; registry metadata validates; report lists owner actions (registry submissions).
diff --git a/prompts/robinhood-chain/07-agent-trading.md b/prompts/robinhood-chain/07-agent-trading.md
new file mode 100644
index 000000000..48d8c4b4c
--- /dev/null
+++ b/prompts/robinhood-chain/07-agent-trading.md
@@ -0,0 +1,54 @@
+# 07 — Autonomous trading agents: `hood-traders`
+
+Read `prompts/robinhood-chain/_shared.md` first. Wave 3: requires core SDK; use `hoodkit`'s
+`strategy`/`stream` modules if built (they should be — check `robinhood/hoodkit/`), else the
+core SDK directly with a note in your report.
+
+## Mission
+Build `robinhood/hood-traders/` — a framework + runnable fleet of autonomous agents that trade
+Robinhood Chain memecoins and monitor Stock Token premium/discount, in the spirit of
+three.ws/play/arena (autonomous agents, live P&L, every trade real and signed). This is both a
+real product and the reference app proving the whole stack.
+
+## Deliverables
+
+1. **Agent framework** (`src/framework/`) — an agent = strategy + wallet + risk budget + journal:
+ - Lifecycle: observe (hoodkit streams) → decide (strategy fn) → simulate (`eth_call`) →
+ execute (real swap) → journal (SQLite: every decision, tx, PnL mark).
+ - Risk layer is NOT optional: per-agent `MAX_POSITION_USDG`, `MAX_DAILY_SPEND_USDG`,
+ `MAX_SLIPPAGE_BPS`, global kill switch (SIGINT + `KILL` file + HTTP `/kill`), cooldowns.
+ - Modes: `paper` (default — full pipeline, simulation-only, marked clearly in every output)
+ and `live` (requires `HOOD_TRADERS_LIVE=1` + funded key). Paper mode is a real simulation
+ against live market data, not fake data.
+2. **Three real strategies** (`src/strategies/`) — honest, simple, documented with their edge
+ hypothesis and failure modes; no ML theater:
+ - `launch-sniper` — enter new launchpad coins passing liquidity/holder-distribution filters,
+ exit on take-profit/stop/time.
+ - `momentum` — volume+price breakout entries on graduated coins, trailing stop exits.
+ - `premium-watch` — Stock Token Chainlink-vs-DEX premium tracker that trades the
+ convergence ONLY in eligible configuration (`_shared.md` gate), otherwise alerts-only.
+ Default: alerts-only.
+3. **Live dashboard** (`dashboard/`) — served by the agent process: fleet overview, per-agent
+ equity curve, open positions, decision journal (why each trade fired), kill buttons.
+ Vanilla JS + the design bar from `_shared.md`. This is the demo and the screenshot.
+4. **Deploy** — Dockerfile + Cloud Run (or any always-on host) docs; `docker compose up` runs
+ fleet + dashboard locally in paper mode with zero config.
+
+## Requirements
+- Vitest: risk-layer tests are the priority (cap breach → refusal; kill switch mid-loop;
+ slippage bound; journal integrity). Strategy logic unit-tested on real recorded market
+ snapshots captured during your run (capture them yourself from live data; they're inputs to
+ deterministic tests, not runtime mocks).
+- E2E: run the fleet in paper mode against LIVE mainnet data for ≥ 30 minutes; then execute at
+ least one REAL testnet-46630 trade through the full pipeline (faucet funds) — tx hash in report.
+- `docs/` static site per `_shared.md`: landing = the dashboard aesthetic with a real captured
+ session (clearly labeled paper/live), architecture page (the observe→journal loop), strategy
+ docs with honest risk disclosure, "run your own in 5 minutes" quickstart.
+- README top: prominent risk disclaimer (autonomous trading, real funds, no guarantees) — plain
+ language, not legalese soup.
+
+## Done checklist
+- [ ] 30-min live-data paper session evidence (journal excerpt + dashboard screenshot-worthy state).
+- [ ] Real testnet trade through the full pipeline. Risk tests green. Kill switch proven (test output).
+- [ ] `docker compose up` → working dashboard on first try in a clean checkout.
+- [ ] Report: honest assessment of each strategy's edge hypothesis + owner actions (funding for live).
diff --git a/prompts/robinhood-chain/08-agent-launcher.md b/prompts/robinhood-chain/08-agent-launcher.md
new file mode 100644
index 000000000..a655cc789
--- /dev/null
+++ b/prompts/robinhood-chain/08-agent-launcher.md
@@ -0,0 +1,56 @@
+# 08 — Autonomous coin launcher: `hood-launcher`
+
+Read `prompts/robinhood-chain/_shared.md` first. Wave 3: requires core SDK (`launchpads` module).
+
+## Mission
+Build `robinhood/hood-launcher/` — an autonomous agent (and a human-driven CLI/API around the
+same core) that launches coins on Robinhood Chain end-to-end: concept → name/ticker/description
+→ artwork → deploy on a launchpad (NOXA primary) or direct ERC-20 + Uniswap v3 pool → announce.
+The pump.fun-launcher playbook, ported to chain 4663 — nothing like it exists there yet.
+
+## Deliverables
+
+1. **Launch rails** (`src/rails/`) — research first, then implement what is REAL:
+ - `noxa` rail: reverse-engineer NOXA's verified factory/bonding-curve contracts on Blockscout
+ (creation tx of a recent launch → factory → `create` calldata shape). Implement create +
+ initial-buy. If NOXA has an official API/SDK, prefer it and cite it.
+ - `direct` rail: deploy a clean, audited-pattern ERC-20 (OpenZeppelin v5, fixed supply,
+ no owner mint, renounced) + create/initialize a Uniswap v3 pool + seed LP + burn or lock
+ LP per config. Every contract verified on Blockscout via API as part of the pipeline.
+ - Pick ONE more live launchpad (The Odyssey) only if its contracts are discoverable and
+ verified; otherwise document why it's excluded. Never guess calldata.
+2. **Concept engine** (`src/concept/`) — name/ticker/description/lore generation via the LLM the
+ operator configures (`OPENAI_API_KEY`/`ANTHROPIC_API_KEY` — support both, no proxy of ours),
+ uniqueness check against existing on-chain tickers (registry + Blockscout search), artwork
+ via the three.ws forge free lane (`https://three.ws` public forge/3D endpoints are usable —
+ generate a 3D-render logo; this is our differentiator: every hood-launcher coin ships with a
+ 3D logo GLB + rendered PNG) with a documented plain-image fallback (any image the operator
+ supplies). Config-first: fully deterministic launches (operator supplies everything) must
+ work with zero LLM calls.
+3. **Autonomous mode** (`src/auto/`) — scheduler that watches launch-meta conditions (e.g.
+ trending narratives from the free three.ws crypto-news digest API), proposes a launch,
+ and requires either `AUTO_APPROVE=1` or an operator approve step (HTTP endpoint / CLI
+ confirm). Hard caps: `MAX_LAUNCHES_PER_DAY`, `MAX_SEED_USDG`. Kill switch per prompt 07's bar.
+4. **CLI + API** — `hood-launch` CLI (`hood-launch create --config coin.json --rail noxa`) and a
+ small HTTP API for programmatic use, sharing one core.
+5. **Testnet-first pipeline** — full E2E on 46630: deploy, pool, buy, verify — real tx hashes.
+ Mainnet execution gated behind `LIVE=1` + funding; do not launch anything real on mainnet
+ during the build (a mainnet token launch is an outward-facing, irreversible act — that call
+ is the owner's).
+
+## Requirements
+- Ethics/abuse posture in README: this tool creates real tradeable assets; document operator
+ responsibility, no-impersonation policy (concept engine refuses trademarked/person-named
+ coins — enforce with a checkable denylist + LLM screen), and the caps.
+- Vitest: calldata builders against captured real factory transactions; cap enforcement; ticker
+ uniqueness. E2E on testnet with pasted hashes + Blockscout verification links.
+- `docs/` static site per `_shared.md`: landing shows a real testnet launch walkthrough
+ (concept → 3D logo → live coin on the testnet explorer), rail docs, autonomous-mode guide,
+ safety page.
+
+## Done checklist
+- [ ] NOXA calldata proven against a real historical launch tx (cite it) AND a real testnet
+ execution of whichever rails testnet supports (direct rail at minimum).
+- [ ] A complete testnet coin exists: token + pool + initial buy + verified contract + 3D logo.
+- [ ] Caps/kill/approval tests green. No mainnet launches performed.
+- [ ] Report: rails shipped vs excluded (with evidence), owner actions for mainnet go-live.
diff --git a/prompts/robinhood-chain/09-examples.md b/prompts/robinhood-chain/09-examples.md
new file mode 100644
index 000000000..e1111b0e5
--- /dev/null
+++ b/prompts/robinhood-chain/09-examples.md
@@ -0,0 +1,50 @@
+# 09 — Examples gallery: `robinhood-chain-examples`
+
+Read `prompts/robinhood-chain/_shared.md` first. Wave 3: consumes everything built in Waves 1–2
+(core SDK, hood-js, hoodkit, hood-api, hood402, hood-mcp). Check which siblings exist in
+`robinhood/` and cover what's actually there; note any gaps in the report.
+
+## Mission
+Build `robinhood/robinhood-chain-examples/` — THE examples repo for the chain: the place every
+new Robinhood Chain developer lands from a search. Each example is small, complete, runnable,
+and real. This repo is also our SDK's honesty check — if an example is awkward to write, file
+that as feedback in your report.
+
+## Structure
+```
+examples/
+ 01-read-stock-price/ # viem-only, no SDK — the "hello chain" baseline
+ 02-stock-price-sdk/ # same thing in 3 lines of hoodchain
+ 03-portfolio-valuation/ # multiplier-correct portfolio (the correctness showpiece)
+ 04-swap-memecoin/ # quote + execute on testnet, faucet-funded
+ 05-watch-launches/ # live launchpad stream to console
+ 06-firehose/ # sequencer feed → filtered event stream
+ 07-live-price-webpage/ # single index.html, client-side RPC, ticking prices
+ 08-portfolio-dashboard/ # small Vite app on hoodkit react hooks
+ 09-x402-paid-api-call/ # client paying a hood-api endpoint via hood402
+ 10-x402-sell-your-api/ # 20-line paid endpoint with hood402 middleware
+ 11-mcp-agent-session/ # scripted MCP client driving hood-mcp tools
+ 12-telegram-price-bot/ # grammY bot: /price AAPL, /trending — deployable free-tier
+ 13-launch-a-coin-testnet/ # hood-launcher direct rail on 46630
+ 14-agent-paper-trader/ # minimal hood-traders strategy in paper mode
+```
+Each folder: `README.md` (what it shows, prerequisites, exact run commands, expected output —
+real captured output), minimal deps, `package.json` with a single `npm start`.
+
+## Requirements
+- RUN EVERY EXAMPLE yourself; paste real output snippets into each README. Anything needing
+ funds uses testnet 46630 + faucet. Anything needing keys documents the env var and fails with
+ a helpful message when missing (test that path too).
+- Root README: gallery table (example → concept → difficulty → what it proves) + a
+ "which package do I need?" decision map, consistent with hoodkit's decision table.
+- `docs/` static site per `_shared.md`: gallery landing where example 07's live-price page is
+ EMBEDDED and running (it's client-side — it works on Pages), with per-example pages rendering
+ the READMEs beautifully with syntax highlighting (build-time rendered to static HTML, no
+ client-side markdown fetching).
+- Keep dependencies per example minimal and pinned `^`. No shared root node_modules trickery —
+ each example installs standalone.
+
+## Done checklist
+- [ ] All examples run; captured outputs in READMEs; testnet hashes where applicable.
+- [ ] Gallery site works locally as static files; example 07 lives inside it.
+- [ ] SDK feedback list in the report (rough edges you hit — this feeds fixes upstream).
diff --git a/prompts/robinhood-chain/10-tutorials.md b/prompts/robinhood-chain/10-tutorials.md
new file mode 100644
index 000000000..c9a7e3709
--- /dev/null
+++ b/prompts/robinhood-chain/10-tutorials.md
@@ -0,0 +1,57 @@
+# 10 — Tutorial site: `learn-robinhood-chain`
+
+Read `prompts/robinhood-chain/_shared.md` first. Wave 4 — run LAST: it teaches the finished
+stack. Verify which sibling repos exist in `robinhood/` and teach what's real.
+
+## Mission
+Build `robinhood/learn-robinhood-chain/` — the definitive learning site for building on
+Robinhood Chain, from zero to shipping an autonomous agent. Written tutorials, each verified by
+actually performing it. This is a content product: the writing quality bar is "official docs of
+a top-tier devtools company" (Stripe/Vite-level), and it funnels readers to our SDK, API, and
+MCP at every natural step without being an ad.
+
+## Curriculum (each tutorial = one page, sequential but independently completable)
+
+**Foundations**
+1. What Robinhood Chain actually is — architecture, chain IDs, what's real vs hype (no-token
+ fact, US Stock Token restriction, permissionless deployment). Sourced, linked.
+2. Connect and read the chain in 5 minutes — wallet setup, faucet, first viem read.
+3. Stock Tokens explained for developers — ERC-20 + Chainlink feed + `uiMultiplier()`; the
+ split/dividend trap, with a worked real example showing wrong-vs-right valuation.
+
+**Building**
+4. Your first app: live price ticker (from example 07, expanded with explanation).
+5. Portfolio tracker done right (SDK `getPortfolio`, why naive trackers are wrong).
+6. Swapping on-chain: quotes, slippage, execution on testnet (memecoin path; eligibility
+ sidebar for Stock Tokens).
+7. Streaming the chain: launchpad watcher + sequencer firehose.
+
+**Monetizing & agents**
+8. Sell your API for USDG: x402 + hood402 from zero to first paid request.
+9. Give your AI agent chain access: hood-mcp with Claude Code/Desktop/Cursor — real transcript.
+10. Build an autonomous trading agent: paper-mode hood-traders strategy, risk-first framing.
+11. Launch a coin programmatically (testnet): hood-launcher direct rail, responsibly framed.
+
+**Capstone**
+12. Ship it: deploying your app/API (Pages for static, Cloud Run for servers), going mainnet
+ checklist (funding, keys, caps, monitoring).
+
+## Requirements
+- EVERY tutorial performed by you during the build, on a clean environment; all outputs and tx
+ hashes in the text are real captures. A tutorial you didn't complete doesn't ship.
+- Site: static generator you build or a minimal SSG (plain build script rendering markdown →
+ styled HTML is fine; no heavy framework) outputting to `docs/` per `_shared.md`. Features:
+ sidebar navigation, prev/next, reading time, copy buttons on code blocks, dark/light,
+ search (client-side index — lunr-style or hand-rolled), mobile-perfect.
+- Each page: prerequisites box, "what you'll build" with a real screenshot/output, estimated
+ time, troubleshooting section from errors YOU actually hit.
+- Landing page: curriculum map with progress affordance, one-line pitch, live chain stats strip
+ (client-side RPC — block height, gas, a ticking price).
+- Root README: how to add a tutorial (contributor guide), local preview command.
+
+## Done checklist
+- [ ] 12 tutorials, all performed, all real outputs. Build script produces the site into docs/.
+- [ ] Search works offline; site is beautiful at 320/768/1440; Lighthouse-clean structure
+ (semantic headings, alt text, contrast).
+- [ ] Report: per-tutorial verification note + list of upstream bugs/rough edges found while
+ performing them (feeds fixes to the other repos).
diff --git a/prompts/robinhood-chain/11-toolkit-cli.md b/prompts/robinhood-chain/11-toolkit-cli.md
new file mode 100644
index 000000000..203056dce
--- /dev/null
+++ b/prompts/robinhood-chain/11-toolkit-cli.md
@@ -0,0 +1,49 @@
+# 11 — CLI toolkit: `hood-cli`
+
+Read `prompts/robinhood-chain/_shared.md` first. Wave 2: requires core SDK
+(`file:../robinhood-chain-sdk`).
+
+## Mission
+Build `robinhood/hood-cli/` — the command-line toolkit for Robinhood Chain: the `gh`/`vercel` of
+chain 4663. Instant reads with zero config, guarded writes with a wallet. npm `hood-cli`
+(fallbacks: `hoodchain-cli`, `hood-toolkit`) exposing the `hood` binary (bin fallback `hoodc`
+if a global `hood` conflict is likely — check npm).
+
+## Command surface
+```
+hood price AAPL [--watch] # Chainlink + DEX price + premium, live-updating table
+hood stocks [--sort premium] # full Stock Token board
+hood coins [--new|--trending] # memecoin screener
+hood launches [--follow] # launchpad feed, streaming
+hood portfolio <address> # multiplier-correct positions, USD totals
+hood tx <hash> | hood token <addr> # decoded inspection via Blockscout + RPC
+hood watch <addr|token> # live activity stream for an address/token
+hood swap --sell USDG --buy <token> --amount 100 [--execute] # quote by default; --execute signs
+hood transfer --to <addr> --amount 5 --token USDG
+hood faucet # testnet: request funds, print balances
+hood deploy-token --config coin.json # direct-rail ERC-20 deploy (testnet default)
+hood config [set|get|list] # rpc, alchemy key, wallet, network (mainnet|testnet)
+```
+- Reads need zero setup. Writes need `hood config set wallet` (env/keystore file with password,
+ never plaintext in config) + explicit `--execute`, defaulting to a printed simulation.
+ Stock Token buys additionally require `--acknowledge-eligibility` (with the `_shared.md` note
+ in help text). `--json` on every command for scripting; exit codes meaningful.
+
+## Requirements
+- Node ≥ 20, commander or clipanion, chalk-free custom ANSI styling consistent with the design
+ bar (a CLI has aesthetics too: aligned tables, subtle color semantics — green/red only for
+ numbers, spinners for network waits, graceful narrow-terminal fallback).
+- `--watch`/`--follow` modes render flicker-free (diff-repaint, not clear-screen spam).
+- Errors: human-first message + `--verbose` for the raw cause. Offline/RPC-down states designed.
+- Vitest: command parsing, formatting, guard rails (execute-gate, eligibility-gate, cap flag).
+ E2E script driving the built binary: real mainnet reads + real testnet swap and transfer
+ (faucet funds) — paste session transcript in the report.
+- `docs/` static site per `_shared.md`: landing = animated terminal session (CSS/JS typewriter
+ over a REAL captured session, not invented output), install (`npm i -g`), command reference
+ generated from the CLI's own help definitions (single source of truth), scripting recipes.
+- README: full command reference + quickstart GIF-alternative (the animated session).
+
+## Done checklist
+- [ ] Real transcript evidence for every command (mainnet reads, testnet writes).
+- [ ] `npm pack` clean; `npm i -g ./hood-cli-*.tgz && hood price AAPL` works in a clean shell.
+- [ ] Guard-rail tests green; docs terminal animation uses the real captured session.
diff --git a/prompts/robinhood-chain/12-threews-markets.md b/prompts/robinhood-chain/12-threews-markets.md
new file mode 100644
index 000000000..7ad80046c
--- /dev/null
+++ b/prompts/robinhood-chain/12-threews-markets.md
@@ -0,0 +1,55 @@
+# 12 — three.ws integration: /markets display + purchase
+
+Read `prompts/robinhood-chain/_shared.md` first. Wave 3. THIS PROMPT MODIFIES THE three.ws APP
+(not a standalone repo). All CLAUDE.md rules apply directly — and the COMMIT GATE is absolute:
+build in the working tree, do NOT commit (Robinhood-referencing content needs explicit owner
+approval per commit).
+
+## Mission
+Make three.ws the best place to SEE Robinhood Chain and a working place to BUY its coins:
+a Robinhood Chain section inside our existing /markets surface, detail pages, and a purchase
+flow — following the established patterns (read the neighboring market handlers and pages
+before writing anything; match their style, caching, failover, and design tokens).
+
+## Deliverables
+
+1. **API layer** (`api/v1/robinhood/…` following `api/v1/market/*` conventions):
+ - `stocks.js`, `stocks-detail.js`, `coins.js`, `launches.js`, `chain.js` — same data spec as
+ prompt 04's endpoints. If `robinhood/hood-api/` is deployed, proxy it with failover to
+ direct upstream calls; if not, implement direct (DefiLlama provider already knows chain
+ `robinhood-chain` — extend `api/v1/_providers.js`; CoinGecko categories
+ `robinhood-chain-meme` / stocks-ecosystem; GeckoTerminal pools; Chainlink reads via viem).
+ - Wire routes in `vercel.json` (it's the LIVE route table — follow existing entries), respect
+ the rate-limiter bucket conventions (dedicated bucket, NOT `public:ip` — see
+ play-lobby-429 lesson), and register x402 pricing for the premium endpoints in the
+ existing catalog exactly like current `api/v1` paid endpoints.
+2. **/markets/robinhood hub page** — three tabs: Stocks (24/7 tokenized-equity board: Chainlink
+ price, DEX premium, volume, sparklines), Coins (memecoin screener: new/graduating/trending),
+ Chain (TVL, bridge flows, stats). Reuse the existing markets page components/CSS tokens; add
+ the hub to /markets navigation and `data/pages.json` (path, title, description, added date).
+3. **Detail pages** — `/markets/robinhood/stock/:symbol` and `/markets/robinhood/coin/:address`
+ following the existing markets detail-page pattern (memory: markets detail-page expansion):
+ chart, stats grid, holders, recent trades, contract links (Blockscout), and for stocks the
+ premium/discount history vs Chainlink NAV.
+4. **Purchase flow** — "Buy" on coin detail pages: EVM wallet connect (injected/EIP-6963, match
+ any existing EVM wallet plumbing in the codebase — search before building new), chain-switch
+ helper to 4663 (viem chain def), Uniswap v3 quote + swap with slippage control, bridge
+ deep-link (LI.FI/Relay) for users without funds on 4663. Stock Tokens: DISPLAY-ONLY at
+ launch — show an eligibility-gated "Trade on DEX" outbound link with the disclosure instead
+ of an in-house buy (owner decision pending; leave the buy path cleanly implementable).
+5. **Docs + changelog** — `docs/` entry per the Documentation rules, `data/changelog.json`
+ entry (feature), STRUCTURE.md row for the new surface.
+
+## Requirements
+- Definition of Done from CLAUDE.md in full: dev server run, real browser exercise, zero console
+ errors, all states designed (loading skeletons, empty, error with retry), responsive,
+ accessible, `npm test` green including any new tests (add handler tests following
+ `tests/api/` patterns; remember the rewrite-query test lesson for parameterized routes).
+- Performance: the stocks board must not fan out 95 RPC calls per request — batch via
+ multicall/cached snapshot with a short TTL, consistent with existing market caching.
+
+## Done checklist
+- [ ] Hub + both detail page types live locally with real data; purchase flow executes a real
+ testnet swap (config-flag testnet mode) — evidence in report.
+- [ ] Routes in vercel.json; pages.json + changelog + STRUCTURE.md updated; docs written.
+- [ ] NOTHING committed. Report lists exact files changed for owner review.
diff --git a/prompts/robinhood-chain/13-threews-play.md b/prompts/robinhood-chain/13-threews-play.md
new file mode 100644
index 000000000..50ef154df
--- /dev/null
+++ b/prompts/robinhood-chain/13-threews-play.md
@@ -0,0 +1,51 @@
+# 13 — three.ws integration: /play worlds for Robinhood Chain coins
+
+Read `prompts/robinhood-chain/_shared.md` first. Wave 3. MODIFIES THE three.ws APP — commit gate
+applies: build in the working tree, do NOT commit.
+
+## Mission
+Port the /play formula — "every pump.fun coin gets a deterministic 3D world you walk into as
+your avatar, with live trades animating the space" — to Robinhood Chain coins. Study the
+existing implementation FIRST (the /play feature pages, `multiplayer/` rooms, the pump.fun feed
+plumbing, `three-ws-pump-fun:reactive` skill wiring) and reuse its architecture wholesale; this
+prompt adds a chain, not a new engine.
+
+## Deliverables
+
+1. **Firehose service** — the PumpPortal-equivalent for chain 4663 (nothing like it exists;
+ this is also sellable later): a worker (`workers/robinhood-feed/` following existing worker
+ conventions, with README) that consumes `wss://feed.mainnet.chain.robinhood.com` + RPC logs
+ and emits normalized events — `launch` (NOXA/Odyssey creations), `trade` (launchpad +
+ Uniswap swaps for tracked coins), `graduation` — over an internal WS/SSE endpoint with the
+ same shape our pump feed consumers expect (map fields 1:1 where semantics align; document
+ divergences). Reconnect + gap-fill; SOL-price-style shared USD conversion for ETH/USDG.
+2. **World generation** — deterministic 3D world per Robinhood Chain coin, seeded by its
+ address (reuse the existing deterministic world-gen path for pump coins; same visual system,
+ new chain-flavored palette/skybox variant so RH-chain worlds are recognizably distinct —
+ subtle, tasteful, no Robinhood trademark assets/branding).
+3. **/play surface** — Robinhood Chain coins appear in the /play lobby (own filter/tab beside
+ pump.fun coins), each with its world route; in-world: live trade events animate the space
+ exactly like pump worlds (holders chat, trades ripple), and the coin's stats HUD reads from
+ the prompt-12 API endpoints. Multiplayer via the existing `multiplayer/` room system.
+4. **Stretch (build if the core lands solid, else document as next):** Stock Token "trading
+ floors" — one ambient world per ticker driven by the live Chainlink tape + DEX trades
+ (display-only, no purchase, no geo issue). AAPL's floor at 2am Saturday is the screenshot.
+5. **Docs + changelog + pages.json + STRUCTURE.md** per the Documentation rules; lobby rate
+ limiting uses the dedicated bucket pattern (429-starvation lesson), and mind the /walk
+ WebGL-context-exhaustion lesson if embedding world previews in the lobby.
+
+## Requirements
+- CLAUDE.md Definition of Done in full — dev server, real browser, zero console errors, all
+ states designed. E2E: join a Robinhood coin world locally and observe REAL live trades
+ animating it (pick an active coin; capture the session in the report). Multiplayer smoke:
+ two clients, one room.
+- The firehose worker runs standalone (`npm start` with env-documented config) and has its own
+ tests (event normalization against captured real feed frames — capture during your run).
+- Do not regress pump.fun worlds: existing /play tests stay green; shared code changes get a
+ test.
+
+## Done checklist
+- [ ] Firehose worker: live session evidence (event counts by type over ≥ 10 min).
+- [ ] A Robinhood coin world joinable locally, animated by real trades; lobby tab wired.
+- [ ] Existing /play + `npm test` green. pages.json/changelog/STRUCTURE/docs updated.
+- [ ] NOTHING committed. Report: files changed, deploy steps (worker + Scheduler/Run), stretch status.
diff --git a/public/changelog.json b/public/changelog.json
index a6b66f4aa..e9f62b6ea 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-07-12T03:20:50.207Z",
+ "generated_at": "2026-07-12T03:47:51.388Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-07-12",
+ "type": "launch",
+ "title": "Docs · The autonomous economy",
+ "summary": "How the three.ws on-chain treasury funds itself and where every dollar flows: the funding-root and engine wallets, the topup/sweepback loop, the allowlist- and destination-locks that keep money inside platform-owned wallets, and the two leak scanners that audit every signer wallet on-chain every minute — plus how to verify there's no leak yourself.",
+ "link": "/docs/autonomous-economy",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-07-12",
"type": "update",
@@ -28,6 +38,18 @@
"feature"
]
},
+ {
+ "date": "2026-07-12",
+ "type": "update",
+ "title": "AI features can no longer go down when one provider does",
+ "summary": "Every AI-powered feature on three.ws (fact checks, agent chat, persona extraction, scene composing) routes through one shared brain that tries free providers first and falls back automatically. That chain just got much deeper: Groq now has a second lane with its own separate quota, OpenRouter gets a zero-credit free lane so an empty account no longer kills it, optional Cerebras and Google AI Studio lanes activate the moment a key is added, and — the anchor — Gemini on the platform's own Google Cloud now backs the whole chain with no third-party quota to exhaust. Previously a rare bad hour where every free tier was exhausted at once could surface an error; now the request rides through. The fact-checker was also corrected to stop favoring a paid key ahead of the free lanes.",
+ "link": "/changelog",
+ "tags": [
+ "improvement",
+ "fix",
+ "infra"
+ ]
+ },
{
"date": "2026-07-12",
"type": "update",
@@ -38,6 +60,28 @@
"fix"
]
},
+ {
+ "date": "2026-07-12",
+ "type": "update",
+ "title": "Seeker wallet signing fixed before it ever shipped",
+ "summary": "Automated testing of the Solana Seeker app in an Android emulator against Solana Mobile's reference wallet caught four bugs in our Mobile Wallet Adapter integration: the app icon was sent in a format the wallet spec rejects, and message signing, transaction signing, and send-transaction all read the wallet's response in the wrong shape. All four are fixed — wallet connect was verified end to end, returning a real public key through the on-device signing flow.",
+ "link": null,
+ "tags": [
+ "fix",
+ "security"
+ ]
+ },
+ {
+ "date": "2026-07-12",
+ "type": "update",
+ "title": "The autonomous coin launcher learned taste",
+ "summary": "The Memetic Launcher's picks got a full quality overhaul. Its cultural radar was half-blind — the pump.fun intel feed was silenced by a miscalibrated quality bar and generic sector words like 'meme' drowned out actual memes — so most picks fell back to random word-salad names. Now the radar reads live meme culture properly (Know Your Meme, Google Trends, Hacker News, Wikipedia attention, and pump.fun's own breakout data), each launch rides a specific rising narrative, the launcher remembers its recent picks so it never re-mints the same joke, coin descriptions are no longer cut off mid-sentence, and a quality gate refuses to spend real SOL on a filler pick when no genuine signal exists. Launch previews in the user launcher now refresh hourly instead of every minute.",
+ "link": "/launcher",
+ "tags": [
+ "improvement",
+ "fix"
+ ]
+ },
{
"date": "2026-07-12",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 7ee2dff26..5c3c3b280 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Docs · The autonomous economy</title>
+ <link>https://three.ws/docs/autonomous-economy</link>
+ <guid isPermaLink="false">2026-07-12:Docs · The autonomous economy</guid>
+ <pubDate>Sun, 12 Jul 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>How the three.ws on-chain treasury funds itself and where every dollar flows: the funding-root and engine wallets, the topup/sweepback loop, the allowlist- and destination-locks that keep money inside platform-owned wallets, and the two leak scanners that audit every signer wallet on-chain every minute — plus how to verify there's no leak yourself.</description>
+ </item>
<item>
<title>Agent discovery fixed: six paid endpoints were invisible to x402 scanners</title>
<link>https://three.ws/openapi.json</link>
@@ -22,6 +30,14 @@
<category>improvement</category>
<description>Agent profile pages got a ground-up redesign. Instead of one endless column of cards, everything is now organized into clear sections — Overview, Capabilities, Economy, Activity, Trust &amp; Identity, Reviews, and Developers — with a sticky navigation bar that follows you as you scroll and hides sections that have nothing to show. The hero is a compact identity band with the live 3D avatar beside the agent's name, description, and actions, and secondary view modes now live in a tidy menu instead of a wall of buttons. Pages are roughly 40% shorter and much easier to scan. Prefer the old look? Every profile keeps a “Classic layout” link that serves the previous design unchanged.</description>
</item>
+ <item>
+ <title>AI features can no longer go down when one provider does</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-07-12:AI features can no longer go down when one provider does</guid>
+ <pubDate>Sun, 12 Jul 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Every AI-powered feature on three.ws (fact checks, agent chat, persona extraction, scene composing) routes through one shared brain that tries free providers first and falls back automatically. That chain just got much deeper: Groq now has a second lane with its own separate quota, OpenRouter gets a zero-credit free lane so an empty account no longer kills it, optional Cerebras and Google AI Studio lanes activate the moment a key is added, and — the anchor — Gemini on the platform's own Google Cloud now backs the whole chain with no third-party quota to exhaust. Previously a rare bad hour where every free tier was exhausted at once could surface an error; now the request rides through. The fact-checker was also corrected to stop favoring a paid key ahead of the free lanes.</description>
+ </item>
<item>
<title>Oversized x402 payment headers fixed</title>
<link>https://three.ws/changelog</link>
@@ -30,6 +46,22 @@
<category>fix</category>
<description>Three paid endpoints (vanity, pump launch, agent reputation) mirrored their entire payment challenge — schemas, signed offers and all — into a single HTTP header that grew past 16 KB, the point where proxies and many clients drop or fail to parse the response. The header mirror is now capped at 8 KB: it slims down or steps aside when the challenge is large, while the response body always carries the complete challenge. Payment tooling that reads only headers still gets everything it needs to pay.</description>
</item>
+ <item>
+ <title>Seeker wallet signing fixed before it ever shipped</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-07-12:Seeker wallet signing fixed before it ever shipped</guid>
+ <pubDate>Sun, 12 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Automated testing of the Solana Seeker app in an Android emulator against Solana Mobile's reference wallet caught four bugs in our Mobile Wallet Adapter integration: the app icon was sent in a format the wallet spec rejects, and message signing, transaction signing, and send-transaction all read the wallet's response in the wrong shape. All four are fixed — wallet connect was verified end to end, returning a real public key through the on-device signing flow.</description>
+ </item>
+ <item>
+ <title>The autonomous coin launcher learned taste</title>
+ <link>https://three.ws/launcher</link>
+ <guid isPermaLink="false">2026-07-12:The autonomous coin launcher learned taste</guid>
+ <pubDate>Sun, 12 Jul 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>The Memetic Launcher's picks got a full quality overhaul. Its cultural radar was half-blind — the pump.fun intel feed was silenced by a miscalibrated quality bar and generic sector words like 'meme' drowned out actual memes — so most picks fell back to random word-salad names. Now the radar reads live meme culture properly (Know Your Meme, Google Trends, Hacker News, Wikipedia attention, and pump.fun's own breakout data), each launch rides a specific rising narrative, the launcher remembers its recent picks so it never re-mints the same joke, coin descriptions are no longer cut off mid-sentence, and a quality gate refuses to spend real SOL on a filler pick when no genuine signal exists. Launch previews in the user launcher now refresh hourly instead of every minute.</description>
+ </item>
<item>
<title>The npm package fleet gets a professional-grade overhaul</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 5ebc6a452..e51221bce 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-12T03:20:50.190Z",
+ "generated_at": "2026-07-12T03:47:51.372Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -2227,6 +2227,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/docs/autonomous-economy",
+ "title": "Docs · The autonomous economy",
+ "description": "How the three.ws on-chain treasury funds itself and where every dollar flows: the funding-root and engine wallets, the topup/sweepback loop, the allowlist- and destination-locks that keep money inside platform-owned wallets, and the two leak scanners that audit every signer wallet on-chain every minute — plus how to verify there's no leak yourself.",
+ "added": "2026-07-12",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/docs/walk",
"title": "Docs · Walk Avatar",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index de5aeea70..afe5a95de 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -1364,6 +1364,12 @@ URL: https://three.ws/docs/crypto-api
Developer reference for the free, keyless Crypto Data API bundle: the one-call discovery endpoint (GET /api/crypto), the generated OpenAPI 3.1 spec, and every endpoint's inputs, outputs, states, and curl examples — token snapshots, bonding status, whales, trending, wallet portfolios, and symbol availability.
+### Docs · The autonomous economy
+
+URL: https://three.ws/docs/autonomous-economy
+
+How the three.ws on-chain treasury funds itself and where every dollar flows: the funding-root and engine wallets, the topup/sweepback loop, the allowlist- and destination-locks that keep money inside platform-owned wallets, and the two leak scanners that audit every signer wallet on-chain every minute — plus how to verify there's no leak yourself.
+
### Docs · Walk Avatar
URL: https://three.ws/docs/walk
diff --git a/public/llms.txt b/public/llms.txt
index e17841982..2f5c2f8cd 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -245,6 +245,7 @@ Docs, tutorials, and reference.
- [3D API](https://three.ws/3d): Free, keyless 3D API for AI agents: turn a text prompt into a real GLB model and validate/optimize any glTF/GLB, all from one URL with a live OpenAPI 3.1 spec. Free draft generation and inspection graduate to paid Forge Pro quality tiers and animation-ready Rigged Avatars. No key, no account.
- [Crypto API](https://three.ws/crypto-api): One free, keyless API for on-chain and market data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution — CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC bundled behind one bill. Live provider table rendered from the real registry, generated OpenAPI 3.1 spec, free tier then BYOK, plan, or x402 pay-per-call.
- [Docs · Crypto Data API](https://three.ws/docs/crypto-api): Developer reference for the free, keyless Crypto Data API bundle: the one-call discovery endpoint (GET /api/crypto), the generated OpenAPI 3.1 spec, and every endpoint's inputs, outputs, states, and curl examples — token snapshots, bonding status, whales, trending, wallet portfolios, and symbol availability.
+- [Docs · The autonomous economy](https://three.ws/docs/autonomous-economy): How the three.ws on-chain treasury funds itself and where every dollar flows: the funding-root and engine wallets, the topup/sweepback loop, the allowlist- and destination-locks that keep money inside platform-owned wallets, and the two leak scanners that audit every signer wallet on-chain every minute — plus how to verify there's no leak yourself.
- [Docs · Walk Avatar](https://three.ws/docs/walk): Developer and user documentation for the three.ws walking-avatar system: the /walk page, iframe embeds, the JavaScript SDK, the postMessage event contract, companion mode, analytics, and the Chrome extension.
- [Docs · Start Here](https://three.ws/docs/start-here): Plain-language introduction to three.ws for creators and non-developers — what it is, who it’s for, and where to begin.
- [Docs · Make Your First Agent](https://three.ws/docs/make-your-agent): Step-by-step guide to creating a 3D AI agent in the browser with no code required.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 204591662..2ec34e766 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -65,7 +65,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 423 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 424 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -77,7 +77,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 423 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 424 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -1634,7 +1634,7 @@
<section class="sm-section" id="learn">
<header>
- <h2>Learn<span class="sm-count" data-count>62</span></h2>
+ <h2>Learn<span class="sm-count" data-count>63</span></h2>
<p class="sm-section-desc">Docs, tutorials, and reference.</p>
</header>
<ul class="sm-list">
@@ -1673,6 +1673,13 @@
<span class="sm-desc">Developer reference for the free, keyless Crypto Data API bundle: the one-call discovery endpoint (GET /api/crypto), the generated OpenAPI 3.1 spec, and every endpoint's inputs, outputs, states, and curl examples — token snapshots, bonding status, whales, trending, wallet portfolios, and symbol availability.</span>
</a>
</li>
+ <li>
+ <a href="/docs/autonomous-economy">
+ <span class="sm-title">Docs · The autonomous economy</span>
+ <span class="sm-path">/docs/autonomous-economy</span>
+ <span class="sm-desc">How the three.ws on-chain treasury funds itself and where every dollar flows: the funding-root and engine wallets, the topup/sweepback loop, the allowlist- and destination-locks that keep money inside platform-owned wallets, and the two leak scanners that audit every signer wallet on-chain every minute — plus how to verify there's no leak yourself.</span>
+ </a>
+ </li>
<li>
<a href="/docs/walk">
<span class="sm-title">Docs · Walk Avatar</span>
diff --git a/scripts/emu-mwa-connect-tmp.mjs b/scripts/emu-mwa-connect-tmp.mjs
deleted file mode 100644
index c84fc0e41..000000000
--- a/scripts/emu-mwa-connect-tmp.mjs
+++ /dev/null
@@ -1,23 +0,0 @@
-#!/usr/bin/env node
-// Fire threeWsWallet.connect() inside the TWA (non-blocking) so the MWA
-// association intent launches the wallet app. Result is stashed on
-// window.__mwaResult for a later probe.
-import { chromium } from 'playwright';
-
-const browser = await chromium.connectOverCDP('http://localhost:9222');
-let page = null;
-for (const ctx of browser.contexts()) {
- for (const p of ctx.pages()) {
- if (p.url().includes('three.ws')) { page = p; break; }
- }
-}
-if (!page) { console.error('three.ws page not found'); process.exit(1); }
-
-await page.evaluate(() => {
- window.__mwaResult = window.threeWsWallet
- .connect()
- .then((r) => ({ ok: true, publicKey: r.publicKey?.toBase58?.() || String(r.publicKey) }))
- .catch((e) => ({ ok: false, error: String(e) }));
-});
-console.log('connect() fired');
-await browser.close();
diff --git a/scripts/emu-mwa-patched-tmp.mjs b/scripts/emu-mwa-patched-tmp.mjs
deleted file mode 100644
index dd224b528..000000000
--- a/scripts/emu-mwa-patched-tmp.mjs
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/env node
-// Verify the MWA icon fix in the running emulator TWA without a deploy:
-// 1. unregister the service worker + clear caches (so routing sees requests)
-// 2. intercept JS bundles and hot-patch the absolute identity.icon to relative
-// 3. reload, then fire threeWsWallet.connect() from a real click (user
-// activation is required to launch the solana-wallet:// intent)
-import { chromium } from 'playwright';
-
-const browser = await chromium.connectOverCDP('http://localhost:9222');
-let page = null, ctx = null;
-for (const c of browser.contexts()) {
- for (const p of c.pages()) {
- if (p.url().includes('three.ws')) { page = p; ctx = c; break; }
- }
-}
-if (!page) { console.error('three.ws page not found'); process.exit(1); }
-
-await page.evaluate(async () => {
- const regs = await navigator.serviceWorker.getRegistrations();
- for (const r of regs) await r.unregister();
- for (const k of await caches.keys()) await caches.delete(k);
-});
-console.log('sw + caches cleared');
-
-const NEEDLE = 'https://three.ws/pwa-192x192.png';
-let patched = 0;
-await ctx.route('**/*.js', async (route) => {
- const resp = await route.fetch();
- let body = await resp.text();
- if (body.includes(`icon:"${NEEDLE}"`) || body.includes(`icon: '${NEEDLE}'`)) {
- body = body
- .replaceAll(`icon:"${NEEDLE}"`, 'icon:"/pwa-192x192.png"')
- .replaceAll(`icon: '${NEEDLE}'`, "icon: '/pwa-192x192.png'");
- patched += 1;
- }
- await route.fulfill({ response: resp, body });
-});
-
-await page.reload({ waitUntil: 'domcontentloaded' });
-await page.waitForFunction(() => Boolean(window.threeWsWallet), null, { timeout: 30000 });
-console.log('reloaded, threeWsWallet ready, bundles patched:', patched);
-
-await page.evaluate(() => {
- const btn = document.createElement('button');
- btn.id = '__mwa_test_btn';
- btn.textContent = 'MWA TEST';
- btn.style.cssText = 'position:fixed;top:120px;left:10px;z-index:2147483647;padding:20px;font-size:20px;';
- btn.addEventListener('click', () => {
- window.__mwaResult = window.threeWsWallet
- .connect()
- .then((r) => ({ ok: true, publicKey: r.publicKey?.toBase58?.() || String(r.publicKey) }))
- .catch((e) => ({ ok: false, error: String(e) }));
- });
- document.body.appendChild(btn);
-});
-await page.click('#__mwa_test_btn');
-console.log('connect() fired via real click');
-await browser.close();
diff --git a/scripts/emu-mwa-probe-tmp.mjs b/scripts/emu-mwa-probe-tmp.mjs
deleted file mode 100644
index 4be235d15..000000000
--- a/scripts/emu-mwa-probe-tmp.mjs
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/usr/bin/env node
-// Probe the three.ws TWA running in the emulator via CDP: check the MWA boot
-// state (seeker-detect signals, threeWsWallet presence) inside the real app.
-import { chromium } from 'playwright';
-
-const browser = await chromium.connectOverCDP('http://localhost:9222');
-const contexts = browser.contexts();
-let page = null;
-for (const ctx of contexts) {
- for (const p of ctx.pages()) {
- if (p.url().includes('three.ws')) { page = p; break; }
- }
-}
-if (!page) { console.error('three.ws page not found'); process.exit(1); }
-
-const state = await page.evaluate(() => ({
- url: location.href,
- referrer: document.referrer,
- standalone: window.matchMedia('(display-mode: standalone)').matches,
- fullscreen: window.matchMedia('(display-mode: fullscreen)').matches,
- ua: navigator.userAgent.slice(0, 120),
- hasThreeWsWallet: typeof window.threeWsWallet !== 'undefined',
- windowSolanaSet: typeof window.solana !== 'undefined' && window.solana !== null,
- walletIsThreeWs: Boolean(window.solana?.isThreeWs),
-}));
-console.log(JSON.stringify(state, null, 1));
-await browser.close();
diff --git a/scripts/emu-mwa-result-tmp.mjs b/scripts/emu-mwa-result-tmp.mjs
deleted file mode 100644
index 54611af1a..000000000
--- a/scripts/emu-mwa-result-tmp.mjs
+++ /dev/null
@@ -1,21 +0,0 @@
-#!/usr/bin/env node
-// Read back window.__mwaResult (or report pending) from the TWA page.
-import { chromium } from 'playwright';
-
-const browser = await chromium.connectOverCDP('http://localhost:9222');
-let page = null;
-for (const ctx of browser.contexts()) {
- for (const p of ctx.pages()) {
- if (p.url().includes('three.ws')) { page = p; break; }
- }
-}
-if (!page) { console.error('three.ws page not found'); process.exit(1); }
-
-const result = await page.evaluate(() =>
- Promise.race([
- window.__mwaResult,
- new Promise((r) => setTimeout(() => r({ pending: true }), 3000)),
- ]),
-);
-console.log(JSON.stringify(result, null, 1));
-await browser.close();
diff --git a/scripts/emu-mwa-retry-tmp.mjs b/scripts/emu-mwa-retry-tmp.mjs
deleted file mode 100644
index debe8459b..000000000
--- a/scripts/emu-mwa-retry-tmp.mjs
+++ /dev/null
@@ -1,33 +0,0 @@
-#!/usr/bin/env node
-// Re-fire connect() via the injected button (warm wallet this time), without
-// waiting for the cross-app navigation that made the previous click hang.
-import { chromium } from 'playwright';
-
-const browser = await chromium.connectOverCDP('http://localhost:9222');
-let page = null;
-for (const ctx of browser.contexts()) {
- for (const p of ctx.pages()) {
- if (p.url().includes('three.ws')) { page = p; break; }
- }
-}
-if (!page) { console.error('three.ws page not found'); process.exit(1); }
-
-const hasBtn = await page.evaluate(() => Boolean(document.getElementById('__mwa_test_btn')));
-if (!hasBtn) {
- await page.evaluate(() => {
- const btn = document.createElement('button');
- btn.id = '__mwa_test_btn';
- btn.textContent = 'MWA TEST';
- btn.style.cssText = 'position:fixed;top:120px;left:10px;z-index:2147483647;padding:20px;font-size:20px;';
- btn.addEventListener('click', () => {
- window.__mwaResult = window.threeWsWallet
- .connect()
- .then((r) => ({ ok: true, publicKey: r.publicKey?.toBase58?.() || String(r.publicKey) }))
- .catch((e) => ({ ok: false, error: String(e) }));
- });
- document.body.appendChild(btn);
- });
-}
-await page.click('#__mwa_test_btn', { noWaitAfter: true, timeout: 15000 });
-console.log('connect() re-fired');
-await browser.close();
diff --git a/solana-mobile/src/mwa-wallet.js b/solana-mobile/src/mwa-wallet.js
index 0fafc6415..5996d8395 100644
--- a/solana-mobile/src/mwa-wallet.js
+++ b/solana-mobile/src/mwa-wallet.js
@@ -208,6 +208,11 @@ export class MwaWallet {
* Sign a single Uint8Array message. Mirrors Phantom's
* provider.signMessage(bytes, 'utf8') → { signature: Uint8Array }
* shape.
+ *
+ * The web3js transact() hands the callback an AUGMENTED wallet proxy:
+ * signMessages takes Uint8Array payloads and returns Uint8Array[] of
+ * signed payloads directly (message with the 64-byte ed25519 signature
+ * appended) — NOT the raw protocol's { signed_payloads } envelope.
*/
async signMessage(messageBytes /* , _displayEncoding */) {
await this.#ensureConnected();
@@ -222,15 +227,12 @@ export class MwaWallet {
identity: APP_IDENTITY,
});
this.#applyAuthResult(reauth);
- const out = await wallet.signMessages({
+ const signed = await wallet.signMessages({
addresses: [this.#authResultAddressBase64()],
- payloads: [bytesToBase64(messageBytes)],
+ payloads: [messageBytes],
});
- const first = Array.isArray(out?.signed_payloads) ? out.signed_payloads[0] : null;
- if (typeof first !== 'string') throw new Error('MWA returned no signed payload');
- // `signed_payloads` returns the original message concatenated with
- // the 64-byte ed25519 signature appended at the end.
- const combined = base64ToBytes(first);
+ const combined = Array.isArray(signed) ? signed[0] : null;
+ if (!(combined instanceof Uint8Array)) throw new Error('MWA returned no signed payload');
signatureBytes = combined.slice(combined.length - 64);
});
if (!signatureBytes) throw new Error('MWA signMessage produced no signature');
@@ -252,30 +254,22 @@ export class MwaWallet {
}
await this.#ensureConnected();
const transact = await loadTransact();
- const serialized = transactions.map((tx) => {
- if (typeof tx.serialize === 'function') {
- const bytes = tx.serialize({ requireAllSignatures: false, verifySignatures: false });
- return bytesToBase64(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
- }
- throw new TypeError('Transaction is missing .serialize()');
- });
- let signedBase64 = [];
+ // web3js wallet proxy: signTransactions takes { transactions } of real
+ // web3.js Transaction / VersionedTransaction objects and returns
+ // deserialized signed transaction objects — no manual serialization.
+ let signed = [];
await transact(async (wallet) => {
const reauth = await wallet.reauthorize({
auth_token: this.#authToken,
identity: APP_IDENTITY,
});
this.#applyAuthResult(reauth);
- const out = await wallet.signTransactions({ payloads: serialized });
- signedBase64 = Array.isArray(out?.signed_payloads) ? out.signed_payloads : [];
+ signed = await wallet.signTransactions({ transactions });
});
- if (signedBase64.length !== transactions.length) {
+ if (!Array.isArray(signed) || signed.length !== transactions.length) {
throw new Error('MWA returned mismatched signed transaction count');
}
- return transactions.map((tx, i) => {
- const bytes = base64ToBytes(signedBase64[i]);
- return rehydrateTransaction(tx, bytes);
- });
+ return signed;
}
/**
@@ -286,6 +280,8 @@ export class MwaWallet {
async signAndSendTransaction(transaction, { minContextSlot } = {}) {
await this.#ensureConnected();
const transact = await loadTransact();
+ // web3js wallet proxy: signAndSendTransactions takes { transactions }
+ // and returns base58 signature strings (Phantom-compatible).
let signature = null;
await transact(async (wallet) => {
const reauth = await wallet.reauthorize({
@@ -293,12 +289,11 @@ export class MwaWallet {
identity: APP_IDENTITY,
});
this.#applyAuthResult(reauth);
- const bytes = transaction.serialize({ requireAllSignatures: false, verifySignatures: false });
- const out = await wallet.signAndSendTransactions({
- payloads: [bytesToBase64(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes))],
- options: minContextSlot ? { min_context_slot: minContextSlot } : undefined,
+ const signatures = await wallet.signAndSendTransactions({
+ transactions: [transaction],
+ ...(minContextSlot ? { minContextSlot } : null),
});
- const first = Array.isArray(out?.signatures) ? out.signatures[0] : null;
+ const first = Array.isArray(signatures) ? signatures[0] : null;
if (typeof first !== 'string') throw new Error('MWA returned no signature');
signature = first;
});
@@ -355,18 +350,3 @@ function decodeAccountAddress(rawAddress) {
return addressFromBase64(rawAddress);
}
-function rehydrateTransaction(template, signedBytes) {
- // VersionedTransaction.deserialize lives on the same web3.js entry the
- // caller already imported. We deliberately avoid importing
- // VersionedTransaction here to keep the public surface narrow — instead
- // we let the caller hand us back a constructed transaction and we copy
- // the signatures into it.
- const ctor = template?.constructor;
- if (ctor && typeof ctor.deserialize === 'function') {
- return ctor.deserialize(signedBytes);
- }
- if (ctor && typeof ctor.from === 'function') {
- return ctor.from(signedBytes);
- }
- throw new Error('Cannot rehydrate transaction: unknown constructor');
-}
diff --git a/tests/vertex-claude.test.js b/tests/vertex-claude.test.js
index 2edb134e5..f6f07a845 100644
--- a/tests/vertex-claude.test.js
+++ b/tests/vertex-claude.test.js
@@ -14,9 +14,12 @@ import { providerChain } from '../api/_lib/llm.js';
const TOUCHED = [
'GOOGLE_CLOUD_PROJECT',
'GOOGLE_CLOUD_LOCATION_CLAUDE',
+ 'GOOGLE_CLOUD_LOCATION_GEMINI',
'VERTEX_CLAUDE_ENABLED',
'VERTEX_CLAUDE_PRIMARY',
'GROQ_API_KEY',
+ 'CEREBRAS_API_KEY',
+ 'GEMINI_API_KEY',
'OPENROUTER_API_KEY',
'OPENROUTER_FALLBACK_KEYS',
'NVIDIA_API_KEY',
@@ -161,19 +164,22 @@ describe('providerChain ordering under the four flag combinations', () => {
const names = () => providerChain().map((p) => p.name);
- it('off/off: no vertex lane; byte-identical free-first chain', () => {
- expect(names()).toEqual(['groq', 'anthropic']);
+ // GOOGLE_CLOUD_PROJECT alone (no Claude flags) always contributes the
+ // vertex-gemini reliability rung after the free lanes, plus groq#instant as
+ // the free-tier capability step-down — both precede the paid backstops.
+ it('off/off: no vertex-CLAUDE lane; free lanes → vertex-gemini → step-down → paid tail', () => {
+ expect(names()).toEqual(['groq', 'vertex-gemini', 'groq#instant', 'anthropic']);
});
- it('enabled/off: vertex is a paid backstop AHEAD of first-party anthropic, behind free lanes', () => {
+ it('enabled/off: vertex claude is a paid backstop AHEAD of first-party anthropic, behind free lanes', () => {
process.env.VERTEX_CLAUDE_ENABLED = '1';
const n = names();
- expect(n).toEqual(['groq', 'vertex-anthropic', 'anthropic']);
+ expect(n).toEqual(['groq', 'vertex-gemini', 'groq#instant', 'vertex-anthropic', 'anthropic']);
expect(n.indexOf('groq')).toBeLessThan(n.indexOf('vertex-anthropic'));
expect(n.indexOf('vertex-anthropic')).toBeLessThan(n.indexOf('anthropic'));
});
- it('enabled/primary: vertex LEADS the chain, before the free lanes', () => {
+ it('enabled/primary: vertex claude LEADS the chain, before the free lanes', () => {
process.env.VERTEX_CLAUDE_ENABLED = '1';
process.env.VERTEX_CLAUDE_PRIMARY = '1';
const n = names();
@@ -183,9 +189,9 @@ describe('providerChain ordering under the four flag combinations', () => {
expect(n.filter((x) => x === 'vertex-anthropic')).toHaveLength(1);
});
- it('primary flag alone (enabled unset) leaves the chain unchanged', () => {
+ it('primary flag alone (enabled unset) adds no vertex-claude lane', () => {
process.env.VERTEX_CLAUDE_PRIMARY = '1';
- expect(names()).toEqual(['groq', 'anthropic']);
+ expect(names()).toEqual(['groq', 'vertex-gemini', 'groq#instant', 'anthropic']);
});
it('a caller BYOK key still leads even when vertex is primary', () => {
@@ -196,3 +202,49 @@ describe('providerChain ordering under the four flag combinations', () => {
expect(n[1]).toBe('vertex-anthropic');
});
});
+
+describe('providerChain free-tier resilience rungs', () => {
+ beforeEach(() => {
+ process.env.GROQ_API_KEY = 'g';
+ process.env.OPENROUTER_API_KEY = 'or-primary';
+ process.env.NVIDIA_API_KEY = 'nv';
+ });
+
+ it('the primary OpenRouter key gets a :free-variant rung behind its paid rung', () => {
+ const chain = providerChain();
+ const paid = chain.find((p) => p.name === 'openrouter');
+ const free = chain.find((p) => p.name === 'openrouter:free');
+ expect(paid.model).toBe('meta-llama/llama-3.3-70b-instruct');
+ expect(free.model).toBe('meta-llama/llama-3.3-70b-instruct:free');
+ expect(chain.indexOf(paid)).toBeLessThan(chain.indexOf(free));
+ });
+
+ it('cerebras and gemini rungs appear only when their keys are configured', () => {
+ const before = providerChain().map((p) => p.name);
+ expect(before).not.toContain('cerebras');
+ expect(before).not.toContain('gemini');
+ process.env.CEREBRAS_API_KEY = 'cb';
+ process.env.GEMINI_API_KEY = 'gm';
+ const n = providerChain().map((p) => p.name);
+ // Cerebras is 70B-class: right after groq, before openrouter. AI Studio
+ // Gemini sits after the 70B rungs (nvidia last of them), before the
+ // groq#instant step-down.
+ expect(n.indexOf('groq')).toBeLessThan(n.indexOf('cerebras'));
+ expect(n.indexOf('cerebras')).toBeLessThan(n.indexOf('openrouter'));
+ expect(n.indexOf('nvidia')).toBeLessThan(n.indexOf('gemini'));
+ expect(n.indexOf('gemini')).toBeLessThan(n.indexOf('groq#instant'));
+ });
+
+ it('every 70B-class free rung precedes the groq#instant capability step-down', () => {
+ process.env.OPENROUTER_FALLBACK_KEYS = 'or-fb1,or-fb2';
+ const n = providerChain().map((p) => p.name);
+ const stepDown = n.indexOf('groq#instant');
+ for (const seventyB of ['groq', 'openrouter', 'openrouter:free', 'openrouter#2', 'openrouter#3', 'nvidia']) {
+ expect(n.indexOf(seventyB), `${seventyB} should precede groq#instant`).toBeLessThan(stepDown);
+ }
+ });
+
+ it('without GOOGLE_CLOUD_PROJECT there is no vertex-gemini rung', () => {
+ expect(providerChain().map((p) => p.name)).not.toContain('vertex-gemini');
+ });
+});