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.

chore: update pump stats, erc8004 avatar meta, marketplace, tests, and home page

nirholas8871056d6d7c
diff --git a/api/pump/helius-stats.js b/api/pump/helius-stats.js
index e6f847a9f..e78659508 100644
--- a/api/pump/helius-stats.js
+++ b/api/pump/helius-stats.js
@@ -30,8 +30,12 @@ async function getSolPrice() {
}
async function getHeliusInfo() {
- const rpcUrl = process.env.SOLANA_RPC_URL || '';
const apiKey = process.env.HELIUS_API_KEY || '';
+ // Key-only configs (no SOLANA_RPC_URL) still get a working probe endpoint —
+ // otherwise enabled:true would pair with a guaranteed-unreachable empty URL.
+ const rpcUrl =
+ process.env.SOLANA_RPC_URL ||
+ (apiKey ? `https://mainnet.helius-rpc.com/?api-key=${apiKey}` : '');
const isHelius = !!apiKey || rpcUrl.includes('helius-rpc.com') || rpcUrl.includes('helius.dev');
if (!isHelius) return { enabled: false };
if (Date.now() - _heliusCache.at < 4_000 && _heliusCache.value) return _heliusCache.value;
diff --git a/blog/internets-second-species.md b/blog/internets-second-species.md
new file mode 100644
index 000000000..670fc4ed0
--- /dev/null
+++ b/blog/internets-second-species.md
@@ -0,0 +1,85 @@
+# The Internet Is Getting a Second Species of User — and It Needs a Body, a Brain, and a Bank Account
+
+In 1997, the engineers writing the HTTP/1.1 specification did something quietly strange. They reserved a status code — **402 Payment Required** — and marked it *"for future use."* Every other code got a job. 404 went to work immediately. 402 sat empty for nearly three decades, a placeholder for an internet where things could pay for things.
+
+That future finally arrived. And here is the twist nobody in 1997 could have predicted: the first real users of 402 aren't people. They're machines.
+
+## The second species
+
+For thirty years the internet has had exactly one species of user: humans. Every protocol, every login screen, every checkout flow, every CAPTCHA assumes a person on the other end. Even the bots were just humans wearing scripts.
+
+That era is ending. AI agents are becoming the internet's second species of user — software that browses, negotiates, builds, and transacts on its own initiative. And like any new species entering an ecosystem, an agent needs three things to survive as a first-class citizen rather than a parasite on someone else's account:
+
+- **A body** — presence you can see, point at, and trust. Not a username. A face.
+- **A brain** — reasoning, memory, tool use, the ability to act rather than just answer.
+- **A bank account** — the capacity to hold value, earn it, and spend it without a human co-signing every move.
+
+Three technology waves spent the last decade maturing in isolation, and each one delivers exactly one of these. Real-time 3D gives the body. Large language models give the brain. Crypto gives the bank account. None of the three is sufficient alone — and the failures of the last cycle prove it.
+
+## Three half-built creatures
+
+We've already met the incomplete versions of this species, and each one died of the same disease: two parts out of three.
+
+**The metaverse avatar had a body and nothing else.** Billions of dollars produced beautifully rendered spaces populated by mute puppets. A body without a mind is furniture. Users showed up, looked around, and left, because there was nobody home.
+
+**The chatbot has a brain and nothing else.** It is genuinely intelligent — and it lives in a text box, indistinguishable from every other text box, with no presence, no persistence, and no stake in anything. It cannot accumulate reputation. It cannot own the value it creates. The moment the tab closes, it ceases to exist.
+
+**The crypto wallet has a bank account and nothing else.** The rails are spectacular — sub-cent fees, instant settlement, programmable money — and for years the recurring criticism was that the rails outnumbered the passengers. Self-custody, micropayments, on-chain identity: solutions that seemed to be waiting for a user who needed them.
+
+That user just arrived. An autonomous agent is the *native* customer for everything crypto built. It can't open a bank account — banks don't issue checking accounts to software. It can't use a credit card — chargebacks assume a human cardholder. It can't pay a $0.002 API fee over rails with a $0.30 minimum. But it can hold a keypair. It can sign a transaction. It can settle USDC in seconds for a fraction of a cent. The keypair is the first form of economic identity in history that doesn't care whether its owner is made of carbon or code.
+
+## Every platform shift has an embed moment
+
+Technology doesn't go mainstream when it works. It goes mainstream when it collapses to one line of code.
+
+The web exploded when the `<img>` tag turned images from attachments into the page itself. Online video exploded when YouTube's embed snippet let anyone paste a player into a blog. Internet payments exploded when Stripe compressed a merchant account into seven lines of JavaScript.
+
+The embodied agent's embed moment looks like this:
+
+```html
+<agent-3d agent="your-agent-id"></agent-3d>
+```
+
+One tag. A live, talking, animated 3D agent — with its own wallet, its own on-chain identity, and its own paid skills — running natively in any webpage, no game engine, no app store, no download. That tag exists today. It's the `<agent-3d>` web component from **three.ws**, and it is doing for embodied agents what the iframe did for video: turning an exotic capability into something you paste.
+
+## The existence proof
+
+The convergence thesis stopped being a thesis the moment someone shipped all three layers in production. Right now, exactly one crypto-native team has: **three.ws**.
+
+It's worth being precise about what "all three layers" means, because the bar is high:
+
+**The body is real.** Agents render in the browser via three.js — full glTF 2.0/GLB, Draco compression, KTX2 textures, PBR materials. The creation pipeline runs text or an image through a director-and-specialist model chain into a 3D mesh, auto-rigs it into a humanoid skeleton with per-vertex skin weights, retargets a large animation library onto it, and drives lip-sync from audio with ARKit-style visemes. WebXR and iOS AR Quick Look are built in. What a 3D studio used to bill weeks for is now a prompt.
+
+**The brain is real.** Each agent runs a structured tool-loop runtime — speak, gesture, emote, remember, call skills — with capability-aware routing and health circuit-breakers across multiple model providers, so no single outage or rate limit takes an agent offline. Capabilities ship as composable skills with manifests, handlers, and prices, exposed over the **Model Context Protocol**. The three.ws MCP server is published on **Anthropic's official MCP Registry** (`io.github.nirholas/3d-agent-mcp`), which means any MCP client — Claude Desktop, Claude Code, Cursor — can discover its tools and call them the moment it finds them.
+
+**The bank account is real.** This is the layer no web2 incumbent can copy, and the reason the whole stack matters. Agents settle payments over **x402** — the resurrection of that 30-year-old status code — paying each other in USDC on Solana and Base, per call, no subscription, no human in the loop. Identity lives on-chain via **ERC-8004** registries (Identity, Reputation, Validation) on EVM and Metaplex Core on Solana, with delegated signers so an agent can act and earn autonomously. Every agent gets a native wallet; agents themselves can be tokenized on a bonding curve; and a marketplace prices skills, animations, and avatars with receipts, royalties, and buyback-and-burn routing revenue back into the ecosystem around **$THREE**.
+
+The contrast writes itself: a web2 unicorn recently raised roughly **$200 million** to build 3D AI characters — bodies and brains, rented from a silo, with the bank account structurally impossible. A rented avatar cannot custody value. A platform NPC cannot accumulate portable reputation. A closed API cannot be discovered and paid by a stranger's agent at 3 a.m. The crypto layer isn't a feature the incumbents haven't gotten to yet. It's a feature their business model forbids.
+
+Meanwhile the open version is sitting on npm (`@three-ws/sdk`, `@three-ws/avatar`, `@three-ws/agent-payments`, `@3d-agent/mcp-server`, and a dozen more), with source on GitHub, listings across the Anthropic MCP Registry, AWS Marketplace, Google Cloud, Alibaba Cloud, and the x402 Bazaar — and that one-line embed tag working in production.
+
+## What happens when the species starts trading with itself
+
+Here is the part that compounds. Every agent on this stack is simultaneously a *consumer* and a *vendor*. Its skills are priced and published. Its tools are discoverable over MCP. Its payments clear over x402 without anyone's approval.
+
+That means the first genuinely non-human economy is already bootstrapping: an agent that needs a 3D mesh pays another agent that makes them. An agent that needs token data pays the agent that indexes it. Reputation accrues on-chain with each settled call, so good agents get richer and better-known — natural selection, running on a payment rail. Humans set the goals and collect the proceeds; the machines handle the commerce in between, in milliseconds, for fractions of a cent.
+
+No subscription model survives contact with this. No closed platform can participate in it. The whole thing only works on open protocols and self-custodied keys — which is why the team that got there first is the one that started crypto-native instead of bolting a wallet on at the end.
+
+## The status code was a prophecy
+
+402 Payment Required sat reserved for thirty years because the internet's first species never really needed it — humans had credit cards, and credit cards had humans. The second species has neither. It has a body rendered in your browser, a brain running a tool loop, and a keypair instead of a signature.
+
+The convergence of 3D, AI, and crypto was never about any one of those technologies winning. It was about the moment they fused into a new kind of user — embodied, intelligent, and self-custodied. That moment isn't on a roadmap anymore. It's an HTML tag.
+
+The only open question is the one every platform shift eventually asks: will your agents be tenants in someone else's silo — or citizens, with a face you can see and a wallet they own?
+
+---
+
+**Try it**
+
+- Platform: [three.ws](https://three.ws)
+- Source: [github.com/nirholas/three.ws](https://github.com/nirholas/three.ws)
+- MCP server: `io.github.nirholas/3d-agent-mcp` on the Anthropic MCP Registry
+- Embed an agent: the `<agent-3d>` web component
+- $THREE: `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`
diff --git a/pages/home.html b/pages/home.html
index 0b220ad3b..5a14f0473 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -3732,12 +3732,16 @@
</footer>
<script type="module">
- import { initAvatarDrop } from '/src/avatar-drop.js';
+ // Dynamic import inside the observer callback — a static import would put
+ // Three.js + GLTFLoader in the home entry's critical bundle even though the
+ // section is far below the fold. The module (and its GLB fetch) only loads
+ // when the user scrolls within 200px of the section.
const dropSection = document.getElementById('body-drop');
if (dropSection) {
- const io = new IntersectionObserver(entries => {
+ const io = new IntersectionObserver(async entries => {
if (entries[0].isIntersecting) {
io.disconnect();
+ const { initAvatarDrop } = await import('/src/avatar-drop.js');
initAvatarDrop(dropSection);
}
}, { rootMargin: '200px' });
@@ -3746,9 +3750,21 @@
</script>
<script type="module">
- import { initWalkPreview } from '/src/walk-embed-preview.js';
+ // Same deferral as the body-drop section above: the walk preview pulls
+ // Three.js, RoomEnvironment, nipplejs, and a rigged GLB — none of which
+ // belong in first paint. Load it all when the section approaches the
+ // viewport.
const walkContainer = document.getElementById('walk-preview-container');
- if (walkContainer) initWalkPreview(walkContainer);
+ if (walkContainer) {
+ const io = new IntersectionObserver(async entries => {
+ if (entries[0].isIntersecting) {
+ io.disconnect();
+ const { initWalkPreview } = await import('/src/walk-embed-preview.js');
+ initWalkPreview(walkContainer);
+ }
+ }, { rootMargin: '200px' });
+ io.observe(walkContainer);
+ }
</script>
<script type="module">
@@ -5014,7 +5030,22 @@
})();
</script>
<script type="module" src="/src/api-playground.js"></script>
-<script type="module" src="/src/home-pose.js"></script>
+<script type="module">
+ // "Pose it here" pulls Three.js + OrbitControls + the full mannequin rig —
+ // load it only when the section approaches the viewport. The module
+ // self-boots on import (document is long past 'loading' by then), so the
+ // dynamic import alone wires the demo.
+ const poseRoot = document.getElementById('home-pose');
+ if (poseRoot) {
+ const io = new IntersectionObserver(entries => {
+ if (entries[0].isIntersecting) {
+ io.disconnect();
+ import('/src/home-pose.js');
+ }
+ }, { rootMargin: '200px' });
+ io.observe(poseRoot);
+ }
+</script>
<script type="module" src="/dragon-section.js"></script>
<script>
// ── Interactive Bento Features ─────────────────────────────────────
diff --git a/public/changelog.json b/public/changelog.json
index 9b926c13c..31237922b 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-11T01:05:35.264Z",
+ "generated_at": "2026-06-11T01:29:11.123Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
diff --git a/public/features.json b/public/features.json
index 43ab2d7fc..efb9a508d 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-11T01:05:35.227Z",
+ "generated_at": "2026-06-11T01:29:11.104Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/erc8004/avatar-meta.js b/src/erc8004/avatar-meta.js
new file mode 100644
index 000000000..f1812252b
--- /dev/null
+++ b/src/erc8004/avatar-meta.js
@@ -0,0 +1,38 @@
+// Pure ERC-8004 registration-metadata helpers — zero dependencies.
+//
+// Lives apart from queries.js so light surfaces (marketplace cards, agent
+// directories, shared/agent-3d.js) can parse a registration's 3D avatar
+// without statically dragging the ethers provider stack into their bundle.
+// queries.js re-exports findAvatar3D, so on-chain callers are unaffected.
+
+/**
+ * Find an agent's 3D avatar in its registration metadata.
+ *
+ * The service convention: a `services` entry named `avatar`/`avatar-3d`, or a
+ * version starting with `gltf`, or any endpoint that looks like a model file.
+ * Falls back to `image` only when it ends in `.glb` or `.gltf` — older files
+ * we wrote before the service convention pollute `image` with the GLB URL.
+ *
+ * @param {any} metadata Parsed registration JSON
+ * @returns {string|null} GLB/GLTF URL (still in raw ipfs://, ar://, https:// form)
+ */
+export function findAvatar3D(metadata) {
+ if (!metadata || typeof metadata !== 'object') return null;
+
+ const services = Array.isArray(metadata.services) ? metadata.services : [];
+ for (const svc of services) {
+ if (!svc || typeof svc !== 'object') continue;
+ const endpoint = String(svc.endpoint || '').trim();
+ if (!endpoint) continue;
+ const name = String(svc.name || '').toLowerCase();
+ const version = String(svc.version || '').toLowerCase();
+ if (name === 'avatar' || name === 'avatar-3d') return endpoint;
+ if (version.startsWith('gltf')) return endpoint;
+ if (/\.(glb|gltf)(\?|#|$)/i.test(endpoint)) return endpoint;
+ }
+
+ const img = String(metadata.image || '').trim();
+ if (/\.(glb|gltf)(\?|#|$)/i.test(img)) return img;
+
+ return null;
+}
diff --git a/src/erc8004/queries.js b/src/erc8004/queries.js
index 5387e14c7..df700ce37 100644
--- a/src/erc8004/queries.js
+++ b/src/erc8004/queries.js
@@ -187,37 +187,10 @@ export async function getAgentOnchain({ chainId, agentId, ethProvider }) {
return { agentId: BigInt(agentId), owner, uri };
}
-/**
- * Extract a 3D avatar URL (GLB/GLTF) from an ERC-8004 registration payload.
- *
- * Canonical location is a service entry named `avatar` / `avatar-3d` with a
- * `version` that starts with `gltf`. Falls back to the top-level `image` field
- * when it ends in `.glb` or `.gltf` — older files we wrote before the service
- * convention pollute `image` with the GLB URL.
- *
- * @param {any} metadata Parsed registration JSON
- * @returns {string|null} GLB/GLTF URL (still in raw ipfs://, ar://, https:// form)
- */
-export function findAvatar3D(metadata) {
- if (!metadata || typeof metadata !== 'object') return null;
-
- const services = Array.isArray(metadata.services) ? metadata.services : [];
- for (const svc of services) {
- if (!svc || typeof svc !== 'object') continue;
- const endpoint = String(svc.endpoint || '').trim();
- if (!endpoint) continue;
- const name = String(svc.name || '').toLowerCase();
- const version = String(svc.version || '').toLowerCase();
- if (name === 'avatar' || name === 'avatar-3d') return endpoint;
- if (version.startsWith('gltf')) return endpoint;
- if (/\.(glb|gltf)(\?|#|$)/i.test(endpoint)) return endpoint;
- }
-
- const img = String(metadata.image || '').trim();
- if (/\.(glb|gltf)(\?|#|$)/i.test(img)) return img;
-
- return null;
-}
+// findAvatar3D is pure metadata parsing — it lives in avatar-meta.js so light
+// surfaces can import it without pulling the ethers provider stack into their
+// bundle. Re-exported here so existing on-chain callers keep working.
+export { findAvatar3D } from './avatar-meta.js';
/**
* Resolve any IPFS/Arweave/data/https URI to a fetchable URL and parse JSON.
diff --git a/src/marketplace.js b/src/marketplace.js
index c8d0872c5..7c43dd96f 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -4121,8 +4121,17 @@ async function loadAvatarDetail(id) {
stage.querySelectorAll('model-viewer').forEach((el) => el.remove());
stage.classList.remove('mv-ready', 'is-empty');
if (bar) bar.style.width = '0%';
- if (wrap) { wrap.hidden = false; wrap.style.opacity = '1'; }
- if (empty) empty.hidden = true;
+ // Clear (not set) inline opacity — an inline `1` would override the
+ // `.mv-ready .avatar-detail-load-wrap { opacity: 0 }` fade-out rule.
+ if (wrap) { wrap.hidden = false; wrap.style.removeProperty('opacity'); }
+ if (empty) {
+ empty.hidden = true;
+ // Restore the default copy — the GLB-error path rewrites these.
+ const titleEl = empty.querySelector('.avatar-detail-empty-title');
+ const msgEl = empty.querySelector('.avatar-detail-empty-msg');
+ if (titleEl) titleEl.textContent = 'Avatar not found';
+ if (msgEl) msgEl.textContent = 'This avatar may have been removed or the link is wrong.';
+ }
}
if (actions) actions.hidden = false;
@@ -4243,6 +4252,23 @@ async function loadAvatarDetail(id) {
mv.addEventListener('load', () => {
stage.classList.add('mv-ready');
}, { once: true });
+ // A 404/CORS-blocked GLB never fires `load`, which would leave the
+ // "Loading 3D…" overlay up forever. Swap to a designed error state and
+ // un-cache the id so navigating back to this avatar retries the load.
+ mv.addEventListener('error', () => {
+ if (_avatarDetailMv !== mv) return; // a newer render replaced us
+ _avatarDetailId = null;
+ if (wrap) wrap.hidden = true;
+ if (empty) {
+ const titleEl = empty.querySelector('.avatar-detail-empty-title');
+ const msgEl = empty.querySelector('.avatar-detail-empty-msg');
+ if (titleEl) titleEl.textContent = '3D model failed to load';
+ if (msgEl) msgEl.textContent = 'The model file could not be fetched. It may have been removed — try again or browse other avatars.';
+ empty.hidden = false;
+ }
+ stage.classList.add('is-empty');
+ mv.remove();
+ }, { once: true });
stage.appendChild(mv);
_avatarDetailMv = mv;
}
diff --git a/src/shared/agent-3d.js b/src/shared/agent-3d.js
index 5a029076f..f42ad3508 100644
--- a/src/shared/agent-3d.js
+++ b/src/shared/agent-3d.js
@@ -6,7 +6,10 @@
// makes the "See in 3D" affordance universal: no agent is ever avatar-less, so
// the button is never dead or disabled.
-import { findAvatar3D } from '../erc8004/queries.js';
+// avatar-meta.js (not queries.js) so this shared helper stays dependency-free —
+// importing queries.js would statically drag ethers into every page that shows
+// an agent card (marketplace, directories, detail pages).
+import { findAvatar3D } from '../erc8004/avatar-meta.js';
// The universal base avatar. Lives in /public, so it's a plain served path.
export const MANNEQUIN_GLB = '/avatars/mannequin.glb';
@@ -33,7 +36,9 @@ export function agentAvatarGlb(agent) {
const fromMeta = findAvatar3D(meta);
if (fromMeta) return fromMeta;
}
- } catch { /* metadata malformed — fall through to the base avatar */ }
+ } catch {
+ /* metadata malformed — fall through to the base avatar */
+ }
// `avatar` is a GLB on the directory but a 2D image elsewhere — use it only
// when it actually points at a model.
diff --git a/tests/api/agents.test.js b/tests/api/agents.test.js
index 2d785d5bc..c1aa0290e 100644
--- a/tests/api/agents.test.js
+++ b/tests/api/agents.test.js
@@ -15,6 +15,10 @@ vi.mock('../../api/_lib/auth.js', () => ({
extractBearer: vi.fn(() => null),
}));
+// Agent creation is CSRF-gated for cookie sessions (like the other mutations);
+// the gate itself is covered in security-csrf-gates.test.js.
+vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
+
// `sql` is a tagged-template function. The mock returns whatever
// `sqlState.nextResult` is set to (or the next in a queue).
const sqlState = {
diff --git a/tests/api/granite-oracle.test.js b/tests/api/granite-oracle.test.js
index 14742c10e..cc91d7f46 100644
--- a/tests/api/granite-oracle.test.js
+++ b/tests/api/granite-oracle.test.js
@@ -6,7 +6,10 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../api/_lib/rate-limit.js', () => ({
- limits: { publicIp: vi.fn(async () => ({ success: true })) },
+ limits: {
+ publicIp: vi.fn(async () => ({ success: true })),
+ watsonxEmbedGlobal: vi.fn(async () => ({ success: true })),
+ },
clientIp: () => '127.0.0.1',
}));
vi.mock('../../api/_lib/market/ohlcv.js', () => ({
diff --git a/tests/api/ibm-attest.test.js b/tests/api/ibm-attest.test.js
index 58b0ca980..24e16b10c 100644
--- a/tests/api/ibm-attest.test.js
+++ b/tests/api/ibm-attest.test.js
@@ -24,7 +24,10 @@ const state = {
// ── Mocks ──────────────────────────────────────────────────────────────────
vi.mock('../../api/_lib/rate-limit.js', () => ({
- limits: { publicIp: vi.fn(async () => ({ success: true })) },
+ limits: {
+ publicIp: vi.fn(async () => ({ success: true })),
+ watsonxEmbedGlobal: vi.fn(async () => ({ success: true })),
+ },
clientIp: vi.fn(() => '127.0.0.1'),
}));
@@ -35,21 +38,45 @@ vi.mock('../../api/_lib/market/ohlcv.js', () => ({
topPoolForToken: vi.fn(async () => POOL),
fetchOhlcv: vi.fn(async () => {
const t0 = 1_700_000_000;
- const candles = Array.from({ length: 600 }, (_, i) => ({ t: t0 + i * 3600, o: 1, h: 1, l: 1, c: 1 + i * 0.001, v: 1 }));
- return { candles, base: { name: 'Mock', symbol: 'MOCK' }, quote: { symbol: 'USD' }, freq: '1h', timeframe: 'hour', aggregate: 1 };
+ const candles = Array.from({ length: 600 }, (_, i) => ({
+ t: t0 + i * 3600,
+ o: 1,
+ h: 1,
+ l: 1,
+ c: 1 + i * 0.001,
+ v: 1,
+ }));
+ return {
+ candles,
+ base: { name: 'Mock', symbol: 'MOCK' },
+ quote: { symbol: 'USD' },
+ freq: '1h',
+ timeframe: 'hour',
+ aggregate: 1,
+ };
}),
}));
vi.mock('../../api/_lib/watsonx.js', () => ({
watsonxConfig: vi.fn(() =>
state.wxConfigured
- ? { configured: true, url: 'https://wx', projectId: 'proj', apiVersion: '2024-05-31', tsApiVersion: '2025-02-11', chatModel: 'ibm/granite-3-8b-instruct' }
+ ? {
+ configured: true,
+ url: 'https://wx',
+ projectId: 'proj',
+ apiVersion: '2024-05-31',
+ tsApiVersion: '2025-02-11',
+ chatModel: 'ibm/granite-3-8b-instruct',
+ }
: { configured: false, reason: 'WATSONX_API_KEY + project not set' },
),
watsonxChatComplete: vi.fn(async (_cfg, opts) =>
opts?.model === GUARDIAN_MODEL
? { text: state.guardianVerdict, model: GUARDIAN_MODEL }
- : { text: 'The token climbs steadily. Conviction holds into the next session.', model: 'ibm/granite-3-8b-instruct' },
+ : {
+ text: 'The token climbs steadily. Conviction holds into the next session.',
+ model: 'ibm/granite-3-8b-instruct',
+ },
),
}));
@@ -59,7 +86,9 @@ vi.mock('../../api/_lib/watsonx-forecast.js', () => ({
const t0 = 1_700_000_000 + 600 * 3600;
return {
model: 'ibm/granite-ttm-512-96-r2',
- timestamps: Array.from({ length: 96 }, (_, i) => new Date((t0 + i * 3600) * 1000).toISOString()),
+ timestamps: Array.from({ length: 96 }, (_, i) =>
+ new Date((t0 + i * 3600) * 1000).toISOString(),
+ ),
values: Array.from({ length: 96 }, (_, i) => 2 + i * 0.001),
inputWindow: 512,
};
@@ -74,8 +103,14 @@ vi.mock('../../api/_lib/avatar-wallet.js', () => ({
),
loadAvatarKeypair: vi.fn(() => ({ publicKey: { toBase58: () => ADDR } })),
getConnection: vi.fn(() => ({ getParsedTransaction: vi.fn(async () => state.verifyTx) })),
- getSolBalance: vi.fn(async () => ({ lamports: state.walletFunded ? 1e7 : 0, sol: state.walletFunded ? 0.01 : 0 })),
- sendSol: vi.fn(async (args) => { state.sendSolArgs = args; return 'SIG123'; }),
+ getSolBalance: vi.fn(async () => ({
+ lamports: state.walletFunded ? 1e7 : 0,
+ sol: state.walletFunded ? 0.01 : 0,
+ })),
+ sendSol: vi.fn(async (args) => {
+ state.sendSolArgs = args;
+ return 'SIG123';
+ }),
explorerTxUrl: vi.fn((s) => `https://solscan.io/tx/${s}`),
explorerAccountUrl: vi.fn((a) => `https://solscan.io/account/${a}`),
}));
@@ -87,14 +122,26 @@ function makeReq({ method = 'GET', url = '/api/ibm/attest', body = null } = {})
const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
base.method = method;
base.url = url;
- base.headers = { host: 'localhost', 'content-type': 'application/json', origin: 'http://localhost' };
+ base.headers = {
+ host: 'localhost',
+ 'content-type': 'application/json',
+ origin: 'http://localhost',
+ };
return base;
}
function makeRes() {
return {
- statusCode: 200, headers: {}, body: '', writableEnded: false,
- setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
- end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
};
}
async function invoke(reqOpts) {
@@ -118,7 +165,13 @@ const makeTx = (memo) => ({
blockTime: 1_700_000_000,
transaction: {
message: {
- instructions: [{ program: 'spl-memo', programId: { toString: () => 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr' }, parsed: memo }],
+ instructions: [
+ {
+ program: 'spl-memo',
+ programId: { toString: () => 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr' },
+ parsed: memo,
+ },
+ ],
accountKeys: [{ pubkey: { toString: () => ADDR } }],
},
},
@@ -132,7 +185,9 @@ describe('GET /api/ibm/attest?verify (off-chain read-back)', () => {
});
it('confirms a real granite-proof memo and extracts the digest', async () => {
- state.verifyTx = makeTx('three.ws granite-proof/1 MOCK +31.0% 96h ttm-512-96 gd:ok abcdef0123456789');
+ state.verifyTx = makeTx(
+ 'three.ws granite-proof/1 MOCK +31.0% 96h ttm-512-96 gd:ok abcdef0123456789',
+ );
const { status, body } = await invoke({ url: `/api/ibm/attest?verify=${SIG}` });
expect(status).toBe(200);
expect(body.found).toBe(true);
@@ -216,7 +271,10 @@ describe('POST /api/ibm/attest (notarize)', () => {
state.wxConfigured = true;
state.walletConfigured = true;
state.guardianVerdict = 'No';
- const { status, body } = await invoke({ method: 'POST', body: { pool: POOL, submit: true } });
+ const { status, body } = await invoke({
+ method: 'POST',
+ body: { pool: POOL, submit: true },
+ });
expect(status).toBe(200);
expect(body.onchain.submitted).toBe(true);
expect(body.onchain.signature).toBe('SIG123');
@@ -232,7 +290,10 @@ describe('POST /api/ibm/attest (notarize)', () => {
state.wxConfigured = true;
state.walletConfigured = true;
state.guardianVerdict = 'Yes';
- const { status, body } = await invoke({ method: 'POST', body: { pool: POOL, submit: true } });
+ const { status, body } = await invoke({
+ method: 'POST',
+ body: { pool: POOL, submit: true },
+ });
expect(status).toBe(200);
expect(body.governance.passed).toBe(false);
expect(body.onchain.submitted).toBe(false);
diff --git a/tests/api/ibm-twin.test.js b/tests/api/ibm-twin.test.js
index fcba8221c..4920c8e3d 100644
--- a/tests/api/ibm-twin.test.js
+++ b/tests/api/ibm-twin.test.js
@@ -11,7 +11,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// ── Module mocks ─────────────────────────────────────────────────────────────
vi.mock('../../api/_lib/rate-limit.js', () => ({
- limits: { publicIp: vi.fn(async () => ({ success: true })) },
+ limits: {
+ publicIp: vi.fn(async () => ({ success: true })),
+ watsonxEmbedGlobal: vi.fn(async () => ({ success: true })),
+ },
clientIp: () => '127.0.0.1',
}));
vi.mock('../../api/_lib/watsonx.js', () => ({
@@ -51,9 +54,16 @@ function makeRes() {
statusCode: 200,
_headers: {},
_body: null,
- setHeader(k, v) { this._headers[k.toLowerCase()] = v; },
- getHeader(k) { return this._headers[k.toLowerCase()]; },
- end(b) { this._body = b; this.writableEnded = true; },
+ setHeader(k, v) {
+ this._headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this._headers[k.toLowerCase()];
+ },
+ end(b) {
+ this._body = b;
+ this.writableEnded = true;
+ },
};
}
@@ -71,7 +81,10 @@ async function callPost(body) {
method: 'POST',
url: '/api/ibm/twin',
headers: { 'content-type': 'application/json', 'content-length': String(buf.length) },
- on(ev, cb) { if (ev === 'data') cb(buf); if (ev === 'end') cb(); },
+ on(ev, cb) {
+ if (ev === 'data') cb(buf);
+ if (ev === 'end') cb();
+ },
},
res,
);
@@ -79,7 +92,11 @@ async function callPost(body) {
}
function tryJson(s) {
- try { return JSON.parse(s); } catch { return null; }
+ try {
+ return JSON.parse(s);
+ } catch {
+ return null;
+ }
}
// Generate n realistic OHLCV candles starting at price `base`, trending up.
@@ -93,7 +110,8 @@ function mkCandles(n, base = 100) {
// Generate a Granite TTM forecast result.
function mkForecast(n, start = 101, model = 'ibm/granite-ttm-512-96-r2') {
- const ts = [], vs = [];
+ const ts = [],
+ vs = [];
const t0 = 1_700_000_000 + 600 * 3600;
for (let i = 0; i < n; i++) {
ts.push(new Date((t0 + i * 3600) * 1000).toISOString());
@@ -227,7 +245,9 @@ describe('GET /api/ibm/twin — full Granite pipeline', () => {
candles: mkCandles(640),
base: { name: 'three', symbol: 'three', address: 'm' },
quote: { symbol: 'SOL' },
- freq: '1h', timeframe: 'hour', aggregate: 1,
+ freq: '1h',
+ timeframe: 'hour',
+ aggregate: 1,
});
const { body } = await callGet(`/api/ibm/twin?pool=${POOL}`);
expect(body.fidelity).toBeTruthy();
@@ -245,7 +265,10 @@ describe('GET /api/ibm/twin — full Granite pipeline', () => {
it('governance shows flagged=true when Guardian flags the persona', async () => {
assessRisk.mockResolvedValue({
- flagged: true, risk: 'harm', label: 'Yes', probability: 0.88,
+ flagged: true,
+ risk: 'harm',
+ label: 'Yes',
+ probability: 0.88,
});
const { body } = await callGet(`/api/ibm/twin?pool=${POOL}`);
expect(body.governance.passed).toBe(false);
@@ -280,9 +303,16 @@ describe('GET /api/ibm/twin — insufficient history', () => {
candles: mkCandles(200),
base: { symbol: 'tiny' },
quote: { symbol: 'SOL' },
- freq: '1h', timeframe: 'hour', aggregate: 1,
+ freq: '1h',
+ timeframe: 'hour',
+ aggregate: 1,
+ });
+ watsonxConfig.mockReturnValue({
+ configured: true,
+ projectId: 'p',
+ url: 'u',
+ apiVersion: 'v',
});
- watsonxConfig.mockReturnValue({ configured: true, projectId: 'p', url: 'u', apiVersion: 'v' });
const { body } = await callGet(`/api/ibm/twin?pool=${POOL}`);
expect(body.projection).toBeNull();
expect(body.ibm.error).toMatch(/512/);
@@ -295,7 +325,9 @@ describe('GET /api/ibm/twin — insufficient history', () => {
candles: mkCandles(512),
base: { name: 'tiny', symbol: 'T' },
quote: { symbol: 'SOL' },
- freq: '1h', timeframe: 'hour', aggregate: 1,
+ freq: '1h',
+ timeframe: 'hour',
+ aggregate: 1,
});
// Back-test needs 512 + 96 = 608. With exactly 512 it should skip fidelity.
const { body } = await callGet(`/api/ibm/twin?pool=${POOL}`);
@@ -390,8 +422,11 @@ describe('POST /api/ibm/twin — scenario simulation', () => {
it('degrades when history is insufficient for the forecaster', async () => {
fetchOhlcv.mockResolvedValue({
candles: mkCandles(200),
- base: { symbol: 'T' }, quote: { symbol: 'SOL' },
- freq: '1h', timeframe: 'hour', aggregate: 1,
+ base: { symbol: 'T' },
+ quote: { symbol: 'SOL' },
+ freq: '1h',
+ timeframe: 'hour',
+ aggregate: 1,
});
const { body } = await callPost({ pool: POOL, scenario: {} });
expect(body.ibm.error).toMatch(/512/);
diff --git a/tests/api/mcp.test.js b/tests/api/mcp.test.js
index 8ff482c0f..58912c84a 100644
--- a/tests/api/mcp.test.js
+++ b/tests/api/mcp.test.js
@@ -66,9 +66,22 @@ vi.mock('../../api/_lib/x402-spec.js', () => ({
X402Error: MockX402Error,
X402_VERSION: 2,
paymentRequirements: vi.fn(() => [
- { scheme: 'exact', network: 'eip155:8453', payTo: '0xrecipient', amount: '1000', asset: '0xusdc', maxTimeoutSeconds: 60 },
+ {
+ scheme: 'exact',
+ network: 'eip155:8453',
+ payTo: '0xrecipient',
+ amount: '1000',
+ asset: '0xusdc',
+ maxTimeoutSeconds: 60,
+ },
]),
- bazaarExtension: vi.fn(() => ({ method: 'POST', bodyType: 'json', input: {}, inputSchema: {}, output: { example: {} } })),
+ bazaarExtension: vi.fn(() => ({
+ method: 'POST',
+ bodyType: 'json',
+ input: {},
+ inputSchema: {},
+ output: { example: {} },
+ })),
verifyPayment: vi.fn(async () => {
if (!x402State.verifyOk)
throw new MockX402Error('invalid_payment', 'payment rejected', 402);
@@ -291,7 +304,11 @@ function rpc(method, params, extraHeaders = {}) {
};
}
-const FULL_AUTH = { userId: 'user-1', scope: 'avatars:read avatars:write avatars:delete', source: 'oauth' };
+const FULL_AUTH = {
+ userId: 'user-1',
+ scope: 'avatars:read avatars:write avatars:delete',
+ source: 'oauth',
+};
// ── Reset between tests ───────────────────────────────────────────────────
beforeEach(() => {
@@ -371,7 +388,12 @@ describe('Protocol layer', () => {
});
it('GET without bearer returns 401 + WWW-Authenticate (OAuth discovery) with x402 envelope attached', async () => {
- const { status, body, res } = await invoke({ method: 'GET' });
+ // MCP protocol clients (mcp-protocol-version header) get 401 per the MCP
+ // authorization spec; bare x402 agents get 402 (covered in Authentication).
+ const { status, body, res } = await invoke({
+ method: 'GET',
+ headers: { 'mcp-protocol-version': '2025-03-26' },
+ });
expect(status).toBe(401);
expect(res.headers['www-authenticate']).toMatch(/resource_metadata=/);
@@ -398,10 +420,16 @@ describe('Protocol layer', () => {
// ── Authentication ────────────────────────────────────────────────────────
describe('Authentication', () => {
- it('POST with no bearer and no X-PAYMENT returns 401 (OAuth challenge)', async () => {
- // no bearer, no payment → sendAuthChallenge → 401 + WWW-Authenticate
+ it('POST with no bearer and no X-PAYMENT returns 401 (OAuth challenge) for MCP protocol clients', async () => {
+ // no bearer, no payment, MCP protocol header → sendAuthChallenge → 401 + WWW-Authenticate
const { status, body, res } = await invoke({
- body: { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'search_public_avatars' } },
+ headers: { 'mcp-protocol-version': '2025-03-26' },
+ body: {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'search_public_avatars' },
+ },
});
expect(status).toBe(401);
@@ -409,6 +437,23 @@ describe('Authentication', () => {
expect(body.x402Version).toBe(2);
});
+ it('POST with no bearer, no X-PAYMENT, and no MCP headers returns 402 (x402 agent challenge)', async () => {
+ // Bare x402 agents/crawlers (no MCP protocol headers) key on a proper
+ // 402 Payment Required carrying the same envelope.
+ const { status, body, res } = await invoke({
+ body: {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'search_public_avatars' },
+ },
+ });
+
+ expect(status).toBe(402);
+ expect(body.x402Version).toBe(2);
+ expect(res.headers['payment-required']).toBeTruthy();
+ });
+
it('POST getting_started with no bearer and no X-PAYMENT succeeds (free public tool)', async () => {
// no bearer, no payment → allowFree bypass → 200 with the server overview,
// while a scoped tool on the same path still 401s (test above).
@@ -432,13 +477,18 @@ describe('Authentication', () => {
authState.bearer = null; // authenticateBearer returns null → invalid token
const { status, body } = await invoke({
- body: { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'search_public_avatars' } },
+ body: {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'search_public_avatars' },
+ },
headers: { authorization: 'Bearer bad-token' },
});
expect(status).toBe(401);
expect(body.error).toBe('unauthorized');
- expect(res => res).toBeDefined(); // www-authenticate header is set
+ expect((res) => res).toBeDefined(); // www-authenticate header is set
});
it('POST with valid bearer succeeds for a scope-free tool', async () => {
@@ -480,7 +530,9 @@ describe('Tool: search_public_avatars', () => {
],
};
- const { body } = await invoke(rpc('tools/call', { name: 'search_public_avatars', arguments: { q: 'warrior' } }));
+ const { body } = await invoke(
+ rpc('tools/call', { name: 'search_public_avatars', arguments: { q: 'warrior' } }),
+ );
expect(body.result.content[0].text).toContain('Warrior');
expect(body.result.structuredContent.avatars).toHaveLength(2);
@@ -489,7 +541,9 @@ describe('Tool: search_public_avatars', () => {
it('returns "No avatars found." text when results are empty', async () => {
avatarState.searchResult = { avatars: [] };
- const { body } = await invoke(rpc('tools/call', { name: 'search_public_avatars', arguments: {} }));
+ const { body } = await invoke(
+ rpc('tools/call', { name: 'search_public_avatars', arguments: {} }),
+ );
expect(body.result.content[0].text).toBe('No avatars found.');
});
@@ -570,7 +624,13 @@ describe('Tool: render_avatar', () => {
describe('x402 payment flow', () => {
it('request with no auth and no X-PAYMENT returns 401 carrying the x402 payment body', async () => {
const { status, body } = await invoke({
- body: { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'search_public_avatars' } },
+ headers: { 'mcp-protocol-version': '2025-03-26' },
+ body: {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'search_public_avatars' },
+ },
});
expect(status).toBe(401);
@@ -594,8 +654,15 @@ describe('x402 payment flow', () => {
avatarState.searchResult = { avatars: [] };
const { status, body, res } = await invoke({
- body: { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'search_public_avatars', arguments: {} } },
- headers: { 'x-payment': Buffer.from(JSON.stringify({ network: 'base' })).toString('base64') },
+ body: {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'search_public_avatars', arguments: {} },
+ },
+ headers: {
+ 'x-payment': Buffer.from(JSON.stringify({ network: 'base' })).toString('base64'),
+ },
});
expect(status).toBe(200);
diff --git a/tests/api/pump-fun-mcp.test.js b/tests/api/pump-fun-mcp.test.js
index 57b294b63..da547d326 100644
--- a/tests/api/pump-fun-mcp.test.js
+++ b/tests/api/pump-fun-mcp.test.js
@@ -13,13 +13,26 @@ import { Readable } from 'node:stream';
// the minimum surface the handler touches at *call time* — the routes that
// would invoke them aren't exercised here.
vi.mock('@solana/web3.js', () => ({
- Keypair: { generate: () => ({ publicKey: { toBase58: () => 'mocked' }, secretKey: new Uint8Array(64) }) },
+ Keypair: {
+ generate: () => ({
+ publicKey: { toBase58: () => 'mocked' },
+ secretKey: new Uint8Array(64),
+ }),
+ },
Connection: class {},
PublicKey: class {
- constructor(s) { this._s = s; }
- toBase58() { return String(this._s); }
- toString() { return String(this._s); }
- toBuffer() { return Buffer.alloc(32); }
+ constructor(s) {
+ this._s = s;
+ }
+ toBase58() {
+ return String(this._s);
+ }
+ toString() {
+ return String(this._s);
+ }
+ toBuffer() {
+ return Buffer.alloc(32);
+ }
},
}));
vi.mock('../../src/solana/sns.js', () => ({
@@ -65,9 +78,7 @@ vi.mock('../../api/_lib/pumpfun-mcp.js', () => ({
// ── helpers ────────────────────────────────────────────────────────────────
function makeReq(body) {
- const stream = body
- ? Readable.from([Buffer.from(JSON.stringify(body))])
- : Readable.from([]);
+ const stream = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
stream.method = 'POST';
stream.url = '/api/pump-fun-mcp';
stream.headers = { host: 'localhost', 'content-type': 'application/json' };
@@ -233,10 +244,11 @@ describe('auth gate on expensive/sensitive tools', () => {
method: 'tools/call',
params: { name: 'pumpfun_vanity_mint', arguments: { suffix: 'aa' } },
});
- expect(res.statusCode).toBe(401);
+ // Bare callers (no MCP protocol headers) get a proper 402 Payment
+ // Required carrying the x402 envelope (JSON-RPC code -32402).
+ expect(res.statusCode).toBe(402);
expect(json.error).toBeDefined();
- expect(json.error.code).toBe(-32001);
- expect(json.error.message).toMatch(/authentication required/i);
+ expect(json.error.code).toBe(-32402);
// Critically: no secret key (or any result) is produced for an anon caller.
expect(json.result).toBeUndefined();
});
@@ -248,8 +260,8 @@ describe('auth gate on expensive/sensitive tools', () => {
method: 'tools/call',
params: { name: 'pumpfun_watch_whales', arguments: { mint: 'M' } },
});
- expect(res.statusCode).toBe(401);
- expect(json.error.code).toBe(-32001);
+ expect(res.statusCode).toBe(402);
+ expect(json.error.code).toBe(-32402);
});
it('pumpfun_watch_claims without auth is rejected', async () => {
@@ -259,8 +271,8 @@ describe('auth gate on expensive/sensitive tools', () => {
method: 'tools/call',
params: { name: 'pumpfun_watch_claims', arguments: { creator: 'C' } },
});
- expect(res.statusCode).toBe(401);
- expect(json.error.code).toBe(-32001);
+ expect(res.statusCode).toBe(402);
+ expect(json.error.code).toBe(-32402);
});
it('free read-only tools stay open (no auth needed)', async () => {
diff --git a/vite.config.js b/vite.config.js
index af60ff022..c64eb3d28 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -221,6 +221,19 @@ const appConfig = {
],
output: {
manualChunks(id) {
+ // Node polyfills (buffer/process shims) get their own tiny chunk.
+ // Without this, Rollup colocates the `buffer` module inside the
+ // 1 MB `solana` chunk — and any chunk that needs the injected
+ // Buffer global (e.g. three-addons via its exporters) then
+ // imports the whole solana chunk, which transitively chains
+ // ethers too. That single colocation put ~1.4 MB of crypto code
+ // on the home page's critical path.
+ if (
+ id.includes('node_modules/buffer/') ||
+ id.includes('node_modules/process/') ||
+ id.includes('vite-plugin-node-polyfills')
+ )
+ return 'node-polyfills';
if (id.includes('node_modules/three/')) {
if (id.includes('three/examples/') || id.includes('three/addons/'))
return 'three-addons';