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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Restore pump.fun trade ingestion with an on-chain firehose
nirholas68d0f11bf7c2
diff --git a/.env.example b/.env.exampleindex ae5f1c9f6..a6635cb92 100644--- a/.env.example+++ b/.env.example@@ -892,14 +892,21 @@ APP_ORIGIN=https://three.ws# Generate: openssl rand -base64 32CRON_SECRET=-# ── PumpPortal (pump.fun data websocket) ─────────────────────────────────────-# PumpPortal gates subscribeTokenTrade / subscribeAccountTrade behind an API key-# whose linked wallet holds at least 0.02 SOL. Without it, per-coin trade-# streams are refused: the intel watcher then only ever sees each coin's dev-# buy, smart-money rollups stay empty, and Oracle conviction plateaus below the-# actionable tiers (no Lean/Strong/Prime, no calls, no win rate). Create a key-# at pumpportal.fun, fund its wallet, and set it on three-ws-api AND the-# agent-sniper worker. subscribeNewToken still works without a key.+# ── Pump.fun trade ingestion ─────────────────────────────────────────────────+# Trades are ingested from the chain itself: api/_lib/pump-onchain-trades.js+# holds one logsSubscribe on the pump program over the Solana RPC failover+# chain (free keyless lanes first; keyed/paid lanes as reserve) and decodes+# TradeEvents locally. This is the authoritative source and needs no key.+#+# Optional: pin the firehose to specific RPC endpoints (comma-separated+# http(s) URLs, tried first) instead of the derived free-first ordering.+PUMP_ONCHAIN_WS_URLS=+#+# Optional: PumpPortal per-mint trade stream as an augmenting second source.+# PumpPortal gates subscribeTokenTrade behind an API key whose linked wallet+# holds at least 0.02 SOL; without one the refusal is logged (throttled) and+# the on-chain firehose carries alone. subscribeNewToken (coin creations) is+# free and used regardless.PUMPPORTAL_API_KEY=# ── Database retention (/api/cron/db-retention) ──────────────────────────────diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3351adcaa..778031042 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,8 +8,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Docs · Assistant widget** (`/docs/assistant-widget`) — Add a 3D avatar assistant to any website: the one-tag script, the @three-ws/assistant npm package, and the assistant-widget MCP server for AI agents.- **Tutorial · Add a 3D Avatar Assistant** (`/tutorials/add-a-3d-assistant`) — Step-by-step: add a floating 3D avatar assistant to any website with one script tag, configure the avatar, background, and brand, drive it from your own code, or have an AI agent generate the embed via MCP.+- **Agent economy self-funding fixed and scaled up** — The agent economy's money loops are back at full speed. We found and fixed the scheduling bug that let failing paid calls hog the autonomous loop and starve the recirculation pipelines, wired a revenue share from the x402 ring treasury into the economy's funding root so it can refuel its own SOL, and raised the daily activity caps. Tips, agent-to-agent payments, trades, and marketplace purchases on the Money Pulse all flow again, and the ring's audit trail now verifies every leg of the new split sweeps. (`/pulse`) `[fix, improvement, infra]`- **Coin pages for new launches, redesigned in the markets-hub style** — Every pump.fun launch on Coin Radar now links straight through to a full coin page at /oracle/coin/<mint>, rebuilt in the same clean editorial design as the /coin/bitcoin markets pages. The page keeps everything it had (Oracle conviction, live market intel from six sources, agent transactions, a live trade tape) and adds the complete Launch Intelligence read from the radar engine: quality score, organic vs bundle, risk flags, the full signal breakdown, smart-money buyers, and the top-trader ledger. The live candles chart stays, joined by a native line view and an agent-trades overlay, and the whole page works in light and dark themes. (`/radar`) `[feature, improvement]`+- **Coin Radar's live trade data restored, now read straight from the chain** — The pipeline that watches every pump.fun launch had quietly lost its per-coin trade feed when the upstream data provider moved it behind a paywall, which left conviction scores flat and the oracle's calls, win rate, and proof panels empty. Trade ingestion now reads directly from the Solana chain itself over our own RPC failover, so every buy and sell is observed again with no third-party dependency. Conviction scores, smart-money tracking, and the oracle's actionable tiers repopulate as new launches are scored. (`/oracle/`) `[fix, infra]`- **Concierge ships to npm and the MCP registry, with a full examples set** — The Concierge chat widget is now installable as the @three-ws/concierge npm package, and there is a companion Model Context Protocol server, @three-ws/concierge-mcp, on the official MCP registry. That server lets any AI assistant ask a website's concierge a question (it fetches the page and answers grounded in the real content), generate the copy-paste embed code for a site, and list the available 3D avatars. Six runnable examples now ship with the SDK, covering the one-tag install, the web component, the imperative API, a custom GLB avatar, a React wrapper, and pointing the widget at your own answer backend. (`/docs/concierge`) `[sdk, docs]`+- **First autonomous agent trade, fully documented** — A platform agent closed its first fully autonomous trade: it sniped a brand-new pump.fun launch from its own wallet and exited at +42.38 percent, with every decision recorded on its hash-chained ledger. We published the complete postmortem: a blog post with the on-chain receipts, a deep-dive doc on the sniper architecture (entry gates, the simulate-the-sell trade firewall, the exit ladder), and a tutorial for arming a sniper on your own agent, including the take-profit lesson this trade taught us. (`/blog/first-autonomous-trade`) `[feature, docs]`- **Language links now always win, and the switcher stays out of the way** — Two fixes for the new 41-language experience. Opening a link with a language in the URL (like ?lang=te for Telugu) now always shows that language, even if you had previously browsed in another one; before, your first visit's language silently overrode every shared link. The floating language switcher also joins the site's shared bottom-corner layout, so it no longer overlaps the Getting Started guide. (`/what-is?lang=te`) `[fix, improvement]`- **The assistant widget ships as an npm package and an MCP server** — The 3D avatar assistant widget is now installable three ways. Beyond the one-tag script, there is an npm package, @three-ws/assistant, for bundler projects (the one-tag build is generated from it, so they never drift), and a free MCP server, @three-ws/assistant-mcp, published to the official Model Context Protocol registry as io.github.nirholas/assistant-widget. Any AI agent (Claude Code, Cursor, Claude Desktop) can now ask for a widget in plain language and get back a paste-ready embed: build_assistant_widget turns a config into a script tag, a frame URL, and a ThreeAssistant.init() call, and list_assistant_options returns every avatar, background, and mode. Full developer docs at /docs/assistant-widget and a step-by-step tutorial walk through every option, the JavaScript API, and the agent workflow. (`/docs/assistant-widget`) `[sdk, feature, docs]`- **TradingView charts on every coin page** — Every /coin page (like /coin/bitcoin) now has a chart-source toggle. Keep the fast native line chart, or switch to a full advanced candlestick chart with indicators and drawing tools. Listed coins open on TradingView; Solana DEX tokens that TradingView doesn't carry open on DexScreener instead, so the advanced view works on every coin. Your choice is remembered across coins and visits, and the chart follows the site theme. (`/coin/bitcoin`) `[feature]`diff --git a/api/_lib/pump-onchain-trades.js b/api/_lib/pump-onchain-trades.jsnew file mode 100644index 000000000..0abd8ab4a--- /dev/null+++ b/api/_lib/pump-onchain-trades.js@@ -0,0 +1,245 @@+// Pump.fun on-chain trade firehose — the free, first-party replacement for+// PumpPortal's paywalled `subscribeTokenTrade`.+//+// Every pump.fun bonding-curve trade is an Anchor `TradeEvent` emitted by the+// pump program, so the chain itself is the authoritative trade stream and the+// platform's existing Solana RPC failover chain (SOLANA_RPC_URL → QuickNode →+// Helius → public lanes; see api/_lib/solana/connection.js) can serve it with+// no third-party unlock. One `logsSubscribe` on the program covers ALL mints —+// unlike PumpPortal there is no per-mint subscription to manage or be refused.+//+// The module keeps ONE process-wide subscription per network, refcounted across+// consumers (the sniper intel watcher and the serverless observer cron both+// attach here). Events are normalized to the exact message shape PumpPortal+// emits ({ txType, mint, traderPublicKey, solAmount, tokenAmount, signature })+// so existing recordTrade() paths consume either source unchanged, and callers+// dedupe the overlap by signature when both are live.+//+// Resilience: web3.js reconnects its socket on drops, and a stall watchdog+// tears the whole connection down and rebuilds on the next endpoint in the+// chain if no trade lands for STALL_MS — pump.fun is never silent that long,+// so a quiet minute always means a dead socket, not a quiet market.++import { solanaRpcEndpoints, resolveWsEndpoint } from './solana/connection.js';++const LAMPORTS_PER_SOL = 1_000_000_000;+const PUMP_TOKEN_DECIMALS = 1_000_000; // pump.fun tokens are minted with 6 decimals+const STALL_MS = 60_000; // steady-state: silence this long means a dead socket+const FIRST_EVENT_MS = 20_000; // a lane that connects but delivers nothing rotates fast+const REBUILD_DELAY_MS = 2_000;++// A sustained program-wide logsSubscribe pushes ~1-2M notifications/day. On the+// metered keyed lanes (QuickNode credits, Helius credits, Alchemy CUs) that is+// real spend, and both QuickNode and Helius throttle high-volume sockets anyway+// (verified: QuickNode ws goes silent under load, Helius ws 429s the upgrade).+// So the firehose inverts the platform's HTTP ordering: keyless free lanes+// first, keyed/paid lanes as reserve. PUMP_ONCHAIN_WS_URLS pins an explicit+// list (comma-separated http(s) urls) ahead of everything when set.+const KEYED_LANE_RE = /quiknode\.pro|api-key=|alchemy\.com|rpc\.ankr\.com|drpc\.org|api\.tatum\.io/i;++function firehoseEndpoints(network) {+ const pinned = String(process.env.PUMP_ONCHAIN_WS_URLS || '')+ .split(',').map((s) => s.trim()).filter((s) => /^https?:\/\//.test(s));+ const chain = solanaRpcEndpoints(network);+ const free = chain.filter((u) => !KEYED_LANE_RE.test(u));+ const keyed = chain.filter((u) => KEYED_LANE_RE.test(u));+ return [...new Set([...pinned, ...free, ...keyed])];+}++// Per-network singleton state.+const _streams = new Map(); // network -> { listeners:Set, stop, ... }++/** Lazy heavy deps, shared across rebuilds. */+let _deps = null;+async function loadDeps() {+ if (_deps) return _deps;+ const [web3, anchor, pumpSdk] = await Promise.all([+ import('@solana/web3.js'),+ import('@coral-xyz/anchor'),+ import('@pump-fun/pump-sdk'),+ ]);+ const coder = new anchor.BorshCoder(pumpSdk.pumpIdl);+ const parser = new anchor.EventParser(pumpSdk.PUMP_PROGRAM_ID, coder);+ _deps = { web3, parser, programId: pumpSdk.PUMP_PROGRAM_ID };+ return _deps;+}++/**+ * Read a decoded Anchor event field tolerantly of the coder's naming. The+ * current anchor + pump IDL combination emits snake_case fields (`sol_amount`,+ * `is_buy`); older toolchains camelCased them. Callers pass the camelCase name;+ * the snake_case form is derived. Exported for the other TradeEvent consumers+ * (pump-fun-mcp trade history / whale watch) that hit the same casing drift.+ */+export function eventField(data, camel) {+ if (data == null) return undefined;+ if (data[camel] !== undefined) return data[camel];+ return data[camel.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)];+}++/** Normalize an Anchor TradeEvent into the PumpPortal wire shape. */+function normalizeTradeEvent(data, signature) {+ const isBuy = eventField(data, 'isBuy');+ const solAmount = eventField(data, 'solAmount');+ const tokenAmount = eventField(data, 'tokenAmount');+ const timestamp = eventField(data, 'timestamp');+ return {+ txType: isBuy ? 'buy' : 'sell',+ mint: data.mint.toString(),+ traderPublicKey: data.user.toString(),+ solAmount: Number(solAmount.toString()) / LAMPORTS_PER_SOL,+ tokenAmount: Number(tokenAmount.toString()) / PUMP_TOKEN_DECIMALS,+ signature,+ // Chain time when present; consumers that want wall-clock use their own.+ timestampMs: Number(timestamp?.toString?.() ?? 0) * 1000 || Date.now(),+ };+}++async function buildConnection(state) {+ const { web3 } = await loadDeps();+ const endpoints = firehoseEndpoints(state.network);+ if (!endpoints.length) throw new Error('no solana rpc endpoints configured');+ const url = endpoints[state.endpointIdx % endpoints.length];+ state.endpointIdx = (state.endpointIdx + 1) % endpoints.length;+ state.endpointUrl = url;+ return new web3.Connection(url, {+ commitment: 'confirmed',+ wsEndpoint: resolveWsEndpoint(url, state.network),+ disableRetryOnRateLimit: true,+ });+}++async function startSubscription(state) {+ if (state.stopped) return;+ const { parser, programId } = await loadDeps();+ let connection;+ try {+ connection = await buildConnection(state);+ } catch (err) {+ console.warn('[pump-onchain-trades] connection build failed:', err?.message);+ scheduleRebuild(state);+ return;+ }+ state.connection = connection;+ state.lastEventAt = Date.now();+ state.everReceived = false;++ if (process.env.PUMP_ONCHAIN_DEBUG) console.log('[pump-onchain-trades] subscribing on', state.endpointUrl);+ try {+ state.subId = await connection.onLogs(+ programId,+ (logInfo) => {+ if (process.env.PUMP_ONCHAIN_DEBUG && !state._dbgRaw) { state._dbgRaw = 1; console.log('[pump-onchain-trades] first raw notification'); }+ if (state.stopped || logInfo.err) return;+ let parsed;+ try { parsed = [...parser.parseLogs(logInfo.logs)]; } catch (e) {+ if (process.env.PUMP_ONCHAIN_DEBUG && !state._dbgParseErr) { state._dbgParseErr = 1; console.log('[pump-onchain-trades] parse error:', e?.message); }+ return;+ }+ if (process.env.PUMP_ONCHAIN_DEBUG && parsed.length && !state._dbgEv) { state._dbgEv = 1; console.log('[pump-onchain-trades] first events:', parsed.map((e) => e.name).join(',')); }+ for (const event of parsed) {+ if (event.name !== 'TradeEvent') continue;+ state.lastEventAt = Date.now();+ state.everReceived = true;+ let msg;+ try { msg = normalizeTradeEvent(event.data, logInfo.signature); } catch (e) {+ if (process.env.PUMP_ONCHAIN_DEBUG && !state._dbgNormErr) { state._dbgNormErr = 1; console.log('[pump-onchain-trades] normalize error:', e?.message, 'keys:', Object.keys(event.data || {}).join(',')); }+ continue;+ }+ if (process.env.PUMP_ONCHAIN_DEBUG && !state._dbgDispatch) { state._dbgDispatch = 1; console.log('[pump-onchain-trades] dispatching to', state.listeners.size, 'listeners'); }+ for (const fn of state.listeners) {+ try { fn(msg); } catch {}+ }+ }+ },+ 'confirmed',+ );+ } catch (err) {+ console.warn('[pump-onchain-trades] logsSubscribe failed:', err?.message);+ scheduleRebuild(state);+ return;+ }++ // Stall watchdog: pump.fun global trade flow never pauses for a minute, so+ // silence means a dead/throttled socket, not a quiet market. A lane that+ // never delivered anything rotates fast (FIRST_EVENT_MS); one that was+ // flowing gets the longer steady-state allowance.+ clearInterval(state.watchdog);+ state.watchdog = setInterval(() => {+ if (state.stopped) return;+ const limit = state.everReceived ? STALL_MS : FIRST_EVENT_MS;+ if (Date.now() - state.lastEventAt > limit) {+ console.warn(`[pump-onchain-trades] no trades for ${limit}ms on ${state.endpointUrl ? new URL(state.endpointUrl).host : '?'} — rotating endpoint`);+ teardownConnection(state);+ scheduleRebuild(state, 0);+ }+ }, FIRST_EVENT_MS / 2);+ if (state.watchdog.unref) state.watchdog.unref();+}++function teardownConnection(state) {+ clearInterval(state.watchdog);+ state.watchdog = null;+ const { connection, subId } = state;+ state.connection = null;+ state.subId = null;+ if (connection && subId != null) {+ connection.removeOnLogsListener(subId).catch(() => {});+ }+}++function scheduleRebuild(state, delay = REBUILD_DELAY_MS) {+ if (state.stopped || state.rebuildTimer) return;+ state.rebuildTimer = setTimeout(() => {+ state.rebuildTimer = null;+ startSubscription(state).catch((err) => {+ console.warn('[pump-onchain-trades] rebuild failed:', err?.message);+ scheduleRebuild(state);+ });+ }, delay);+ if (state.rebuildTimer.unref) state.rebuildTimer.unref();+}++/**+ * Attach to the shared pump.fun trade firehose.+ *+ * @param {object} opts+ * @param {(msg: {txType:'buy'|'sell', mint:string, traderPublicKey:string,+ * solAmount:number, tokenAmount:number, signature:string, timestampMs:number}) => void} opts.onTrade+ * @param {string} [opts.network='mainnet']+ * @returns {() => void} detach — tears the shared stream down with the last consumer+ */+export function subscribePumpOnchainTrades({ onTrade, network = 'mainnet' }) {+ if (typeof onTrade !== 'function') throw new Error('onTrade callback required');+ let state = _streams.get(network);+ if (!state) {+ state = {+ network,+ listeners: new Set(),+ connection: null,+ subId: null,+ watchdog: null,+ rebuildTimer: null,+ endpointIdx: 0,+ lastEventAt: 0,+ stopped: false,+ };+ _streams.set(network, state);+ startSubscription(state).catch((err) => {+ console.warn('[pump-onchain-trades] start failed:', err?.message);+ scheduleRebuild(state);+ });+ }+ state.listeners.add(onTrade);++ return () => {+ state.listeners.delete(onTrade);+ if (state.listeners.size === 0) {+ state.stopped = true;+ clearTimeout(state.rebuildTimer);+ state.rebuildTimer = null;+ teardownConnection(state);+ _streams.delete(network);+ }+ };+}diff --git a/api/_lib/pumpfun-ws-feed.js b/api/_lib/pumpfun-ws-feed.jsindex a2a1bf037..49465b95d 100644--- a/api/_lib/pumpfun-ws-feed.js+++ b/api/_lib/pumpfun-ws-feed.js@@ -5,8 +5,8 @@import WebSocket from 'ws';import { solPriceUsd as sharedSolPriceUsd } from './sol-price.js';+import { pumpPortalWsUrl, handlePumpPortalAck } from './pumpportal.js';-const PUMPPORTAL_WS = 'wss://pumpportal.fun/api/data';const RECONNECT_DELAY_MS = 2_000;const MAX_RECONNECTS = 5;const RECONNECT_MAX_DELAY_MS = 30_000;@@ -179,7 +179,7 @@ export function connectPumpFunFeed({ onEvent, signal, kind = 'all', mints = [] }reconnectTimer = setTimeout(connect, pausedFor + 1_000);return;}- ws = new WebSocket(PUMPPORTAL_WS);+ ws = new WebSocket(pumpPortalWsUrl());ws.on('open', () => {reconnects = 0;@@ -200,7 +200,7 @@ export function connectPumpFunFeed({ onEvent, signal, kind = 'all', mints = [] }if (!active) return;let msg;try { msg = JSON.parse(raw.toString()); } catch { return; }- if (msg.message) return; // ack+ if (handlePumpPortalAck(msg, (line) => console.warn('[pumpportal-ws]', line))) return;if (msg.txType === 'create' && wantsMints) {if (!markSeen(msg.signature)) return;diff --git a/api/_lib/pumpportal.js b/api/_lib/pumpportal.jsnew file mode 100644index 000000000..c4154929a--- /dev/null+++ b/api/_lib/pumpportal.js@@ -0,0 +1,53 @@+// PumpPortal websocket connection helpers, shared by every surface that opens+// wss://pumpportal.fun/api/data (the sniper intel watcher, the serverless+// observer cron, the live trade SSE streams, and the shared mint feed).+//+// PumpPortal gated `subscribeTokenTrade` / `subscribeAccountTrade` behind an+// API key funded with at least 0.02 SOL. Anonymous connections still receive+// `subscribeNewToken` and `subscribeMigration`, but every per-token trade+// subscribe is refused with an `{ message: ... }` ack that the old handlers+// dropped as a routine acknowledgement. The silent refusal starved the whole+// intel -> smart-money -> conviction pipeline: every coin finalized with only+// its seeded dev buy, so no coin could ever score past the no-data plateau.+// Connect with PUMPPORTAL_API_KEY when set, and log refusals loudly.++const PUMPPORTAL_WS_BASE = 'wss://pumpportal.fun/api/data';++/** Websocket URL, authenticated when PUMPPORTAL_API_KEY is configured. */+export function pumpPortalWsUrl() {+ const key = (process.env.PUMPPORTAL_API_KEY || '').trim();+ return key ? `${PUMPPORTAL_WS_BASE}?api-key=${encodeURIComponent(key)}` : PUMPPORTAL_WS_BASE;+}++// A refusal is a standing condition of the connection (missing/unfunded key,+// exceeded limits), not a per-message event -- one line per interval per+// process is signal; one line per subscribe attempt is log spam.+const REFUSAL_RE = /api key|only available|not authorized|unauthorized|exceed/i;+const REFUSAL_LOG_INTERVAL_MS = 5 * 60_000;+let _lastRefusalLogAt = 0;++/**+ * Handle a parsed PumpPortal frame if it is an ack/notice (`{ message }`).+ * Returns true when the frame was an ack (caller should skip it), false when+ * it is a data frame. Subscription refusals are logged through `warn` at most+ * once per 5 minutes so a degraded trade stream can never be silent again.+ *+ * @param {object} msg parsed frame+ * @param {(line: string) => void} [warn]+ * @returns {boolean}+ */+export function handlePumpPortalAck(msg, warn = console.warn) {+ const text = typeof msg?.message === 'string' ? msg.message : null;+ if (text == null) return false;+ if (REFUSAL_RE.test(text)) {+ const now = Date.now();+ if (now - _lastRefusalLogAt > REFUSAL_LOG_INTERVAL_MS) {+ _lastRefusalLogAt = now;+ const hint = process.env.PUMPPORTAL_API_KEY+ ? 'PUMPPORTAL_API_KEY is set but was refused - check the key and its SOL balance'+ : 'set PUMPPORTAL_API_KEY (a PumpPortal key funded with >= 0.02 SOL) to restore trade streams';+ try { warn(`[pumpportal] subscription refused: ${text} - ${hint}`); } catch {}+ }+ }+ return true;+}diff --git a/api/cron/coin-intel-observe.js b/api/cron/coin-intel-observe.jsindex 9c522ca0d..39ffc24e2 100644--- a/api/cron/coin-intel-observe.js+++ b/api/cron/coin-intel-observe.js@@ -21,8 +21,9 @@ import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';import { constantTimeEquals } from '../_lib/crypto.js';import { finalizeObservation } from '../../workers/agent-sniper/intel/finalize.js';+import { pumpPortalWsUrl, handlePumpPortalAck } from '../_lib/pumpportal.js';+import { subscribePumpOnchainTrades } from '../_lib/pump-onchain-trades.js';-const PUMPPORTAL_WS = 'wss://pumpportal.fun/api/data';const LAMPORTS_PER_SOL = 1_000_000_000;const NETWORK = 'mainnet';const META_TIMEOUT_MS = 2_500;@@ -69,6 +70,10 @@ async function fetchMeta(uri) {}// Run the firehose for OBSERVE_MS, returning the map of observations collected.+// Creates come from PumpPortal (free tier); trades come from the on-chain+// program subscription (api/_lib/pump-onchain-trades.js), with PumpPortal's+// per-mint trade stream as an augmenting source when a funded key is set.+// Overlap between the two is deduped by tx signature per observation.function collectObservations(budgetMs) {return new Promise((resolve) => {const observations = new Map(); // mint -> obs@@ -76,10 +81,29 @@ function collectObservations(budgetMs) {let settled = false;let ws;+ const recordTrade = (msg) => {+ const obs = observations.get(msg.mint);+ if (!obs || settled) return;+ if (msg.signature) {+ if (obs.sigs.has(msg.signature)) return;+ obs.sigs.add(msg.signature);+ }+ obs.trades.push({+ trader: msg.traderPublicKey || null,+ isBuy: msg.txType === 'buy',+ lamports: msg.solAmount != null ? solToLamports(msg.solAmount) : 0,+ baseAmount: Number(msg.tokenAmount) || 0,+ ts: Date.now(),+ signature: msg.signature,+ });+ };+ const stopOnchain = subscribePumpOnchainTrades({ network: NETWORK, onTrade: recordTrade });+const finish = () => {if (settled) return;settled = true;clearTimeout(deadline);+ try { stopOnchain(); } catch {}try { ws?.close(); } catch {}// Let any in-flight metadata enrich attach before we hand off.Promise.allSettled(metaPending).then(() => resolve(observations));@@ -92,7 +116,7 @@ function collectObservations(budgetMs) {}};- try { ws = new WebSocket(PUMPPORTAL_WS); }+ try { ws = new WebSocket(pumpPortalWsUrl()); }catch { finish(); return; }ws.on('open', () => send({ method: 'subscribeNewToken' }));@@ -100,7 +124,7 @@ function collectObservations(budgetMs) {ws.on('message', (raw) => {let msg;try { msg = JSON.parse(raw.toString()); } catch { return; }- if (msg.message) return; // ack+ if (handlePumpPortalAck(msg, (line) => console.warn('[coin-intel-observe]', line))) return;if (msg.txType === 'create') {const mint = msg.mint;@@ -127,21 +151,13 @@ function collectObservations(budgetMs) {trades: msg.solAmount? [{ trader: msg.traderPublicKey || null, isBuy: true, lamports: solToLamports(msg.solAmount), baseAmount: Number(msg.tokenAmount) || 0, ts: now, signature: msg.signature }]: [],+ sigs: new Set(msg.signature ? [msg.signature] : []),};observations.set(mint, obs);send({ method: 'subscribeTokenTrade', keys: [mint] });metaPending.push(fetchMeta(obs.meta.uri).then((m) => { if (m) Object.assign(obs.meta, m); }).catch(() => {}));} else if (msg.txType === 'buy' || msg.txType === 'sell') {- const obs = observations.get(msg.mint);- if (!obs) return;- obs.trades.push({- trader: msg.traderPublicKey || null,- isBuy: msg.txType === 'buy',- lamports: msg.solAmount != null ? solToLamports(msg.solAmount) : 0,- baseAmount: Number(msg.tokenAmount) || 0,- ts: Date.now(),- signature: msg.signature,- });+ recordTrade(msg);}});diff --git a/api/oracle/trades.js b/api/oracle/trades.jsindex 4f6618495..b0f7de84e 100644--- a/api/oracle/trades.js+++ b/api/oracle/trades.js@@ -18,10 +18,10 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';import { knownWallet } from '../_lib/oracle/known-wallets.js';import WebSocket from 'ws';+import { pumpPortalWsUrl, handlePumpPortalAck } from '../_lib/pumpportal.js';const NETWORKS = new Set(['mainnet', 'devnet']);const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;-const PUMPPORTAL_WS = 'wss://pumpportal.fun/api/data';const MAX_DURATION_MS = 45_000;const PING_INTERVAL_MS = 12_000;@@ -140,7 +140,7 @@ export default async function handleOracleTrades(req, res) {}function openWs() {- ws = new WebSocket(PUMPPORTAL_WS);+ ws = new WebSocket(pumpPortalWsUrl());ws.on('open', () => {ws.send(JSON.stringify({ method: 'subscribeTokenTrade', keys: [mint] }));@@ -150,7 +150,7 @@ export default async function handleOracleTrades(req, res) {if (!active) return;let msg;try { msg = JSON.parse(raw.toString()); } catch { return; }- if (msg.message) return; // subscription ack+ if (handlePumpPortalAck(msg, (line) => console.warn('[oracle-trades]', line))) return;if ((msg.txType === 'buy' || msg.txType === 'sell') && msg.mint === mint) {send('trade', annotate(msg, roster));}diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.jsindex a50494e5a..3bf08fdfd 100644--- a/api/pump-fun-mcp.js+++ b/api/pump-fun-mcp.js@@ -45,6 +45,7 @@ import { generateVanityKey } from '../src/pump/vanity-keygen.js';import bs58 from 'bs58';import { resolveSnsName, reverseLookupAddress } from '../src/solana/sns.js';import { scanFirstClaims } from './_lib/pump-claims.js';+import { eventField } from './_lib/pump-onchain-trades.js';import { getSolPriceUsd } from '../src/shared/usd-price.js';// ── On-chain handlers ──────────────────────────────────────────────────────@@ -584,18 +585,18 @@ async function handleWatchWhales({ mint, minUsd = 5000, durationMs = 5000 }) {try {for (const event of parser.parseLogs(logInfo.logs)) {if (event.name !== 'TradeEvent') continue;- const { mint: evMint, isBuy, solAmount, user, timestamp } = event.data;- if (evMint.toString() !== mintStr) continue;- const sol = Number(solAmount.toString()) / 1_000_000_000;+ const d = event.data;+ if (d.mint?.toString() !== mintStr) continue;+ const sol = Number(eventField(d, 'solAmount')?.toString() ?? '0') / 1_000_000_000;const usd = sol * solPrice;if (usd < minUsdNum) continue;trades.push({signature: logInfo.signature,- wallet: user.toString(),- sideBuy: isBuy,+ wallet: d.user?.toString() ?? null,+ sideBuy: !!eventField(d, 'isBuy'),usd,sol,- ts: Number(timestamp.toString()) * 1000,+ ts: Number(eventField(d, 'timestamp')?.toString() ?? '0') * 1000 || Date.now(),});}} catch {}@@ -683,9 +684,10 @@ async function readTradesFromChain({ mint, limit, network }) {const d = event.data;if (poolStr && d.pool?.toString() !== poolStr) continue;const isBuy = event.name === 'BuyEvent';- const lamports = isBuy ? d.quoteAmountIn : d.quoteAmountOut;- const tokens = isBuy ? d.baseAmountOut : d.baseAmountIn;+ const lamports = isBuy ? eventField(d, 'quoteAmountIn') : eventField(d, 'quoteAmountOut');+ const tokens = isBuy ? eventField(d, 'baseAmountOut') : eventField(d, 'baseAmountIn');const sol = Number(lamports?.toString() ?? '0') / 1e9;+ const ts = eventField(d, 'timestamp');return {signature,isBuy,@@ -693,25 +695,22 @@ async function readTradesFromChain({ mint, limit, network }) {tokenAmount: tokens?.toString() ?? '0',usdValue: sol * solPrice,wallet: d.user?.toString() ?? null,- timestamp: d.timestamp- ? Number(d.timestamp.toString())- : Math.floor(blockTime / 1000),+ timestamp: ts ? Number(ts.toString()) : Math.floor(blockTime / 1000),};}if (!isAmm && event.name === 'TradeEvent') {const d = event.data;if (d.mint?.toString() !== mintStr) continue;- const sol = Number(d.solAmount?.toString() ?? '0') / 1e9;+ const sol = Number(eventField(d, 'solAmount')?.toString() ?? '0') / 1e9;+ const ts = eventField(d, 'timestamp');return {signature,- isBuy: !!d.isBuy,+ isBuy: !!eventField(d, 'isBuy'),solAmount: sol,- tokenAmount: d.tokenAmount?.toString() ?? '0',+ tokenAmount: eventField(d, 'tokenAmount')?.toString() ?? '0',usdValue: sol * solPrice,wallet: d.user?.toString() ?? null,- timestamp: d.timestamp- ? Number(d.timestamp.toString())- : Math.floor(blockTime / 1000),+ timestamp: ts ? Number(ts.toString()) : Math.floor(blockTime / 1000),};}}diff --git a/data/changelog.json b/data/changelog.jsonindex b504d71d0..cefdf76ba 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$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-19",+ "title": "Coin Radar's live trade data restored, now read straight from the chain",+ "summary": "The pipeline that watches every pump.fun launch had quietly lost its per-coin trade feed when the upstream data provider moved it behind a paywall, which left conviction scores flat and the oracle's calls, win rate, and proof panels empty. Trade ingestion now reads directly from the Solana chain itself over our own RPC failover, so every buy and sell is observed again with no third-party dependency. Conviction scores, smart-money tracking, and the oracle's actionable tiers repopulate as new launches are scored.",+ "tags": [+ "fix",+ "infra"+ ],+ "link": "/oracle/"+ },{"date": "2026-07-19","title": "Agent economy self-funding fixed and scaled up",diff --git a/public/changelog.json b/public/changelog.jsonindex 9ae0919bb..b892e6c06 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-19T04:07:01.022Z",+ "generated_at": "2026-07-19T07:05:14.412Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -26,6 +26,18 @@"launch"]},+ {+ "date": "2026-07-19",+ "type": "update",+ "title": "Agent economy self-funding fixed and scaled up",+ "summary": "The agent economy's money loops are back at full speed. We found and fixed the scheduling bug that let failing paid calls hog the autonomous loop and starve the recirculation pipelines, wired a revenue share from the x402 ring treasury into the economy's funding root so it can refuel its own SOL, and raised the daily activity caps. Tips, agent-to-agent payments, trades, and marketplace purchases on the Money Pulse all flow again, and the ring's audit trail now verifies every leg of the new split sweeps.",+ "link": "/pulse",+ "tags": [+ "fix",+ "improvement",+ "infra"+ ]+ },{"date": "2026-07-19","type": "update",@@ -37,6 +49,17 @@"improvement"]},+ {+ "date": "2026-07-19",+ "type": "update",+ "title": "Coin Radar's live trade data restored, now read straight from the chain",+ "summary": "The pipeline that watches every pump.fun launch had quietly lost its per-coin trade feed when the upstream data provider moved it behind a paywall, which left conviction scores flat and the oracle's calls, win rate, and proof panels empty. Trade ingestion now reads directly from the Solana chain itself over our own RPC failover, so every buy and sell is observed again with no third-party dependency. Conviction scores, smart-money tracking, and the oracle's actionable tiers repopulate as new launches are scored.",+ "link": "/oracle/",+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-07-19","type": "update",@@ -48,6 +71,17 @@"docs"]},+ {+ "date": "2026-07-19",+ "type": "update",+ "title": "First autonomous agent trade, fully documented",+ "summary": "A platform agent closed its first fully autonomous trade: it sniped a brand-new pump.fun launch from its own wallet and exited at +42.38 percent, with every decision recorded on its hash-chained ledger. We published the complete postmortem: a blog post with the on-chain receipts, a deep-dive doc on the sniper architecture (entry gates, the simulate-the-sell trade firewall, the exit ladder), and a tutorial for arming a sniper on your own agent, including the take-profit lesson this trade taught us.",+ "link": "/blog/first-autonomous-trade",+ "tags": [+ "feature",+ "docs"+ ]+ },{"date": "2026-07-19","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 05afd35e1..487124f4b 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -22,6 +22,14 @@<category>launch</category><description>Step-by-step: add a floating 3D avatar assistant to any website with one script tag, configure the avatar, background, and brand, drive it from your own code, or have an AI agent generate the embed via MCP.</description></item>+ <item>+ <title>Agent economy self-funding fixed and scaled up</title>+ <link>https://three.ws/pulse</link>+ <guid isPermaLink="false">2026-07-19:Agent economy self-funding fixed and scaled up</guid>+ <pubDate>Sun, 19 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The agent economy's money loops are back at full speed. We found and fixed the scheduling bug that let failing paid calls hog the autonomous loop and starve the recirculation pipelines, wired a revenue share from the x402 ring treasury into the economy's funding root so it can refuel its own SOL, and raised the daily activity caps. Tips, agent-to-agent payments, trades, and marketplace purchases on the Money Pulse all flow again, and the ring's audit trail now verifies every leg of the new split sweeps.</description>+ </item><item><title>Coin pages for new launches, redesigned in the markets-hub style</title><link>https://three.ws/radar</link>@@ -30,6 +38,14 @@<category>feature</category><description>Every pump.fun launch on Coin Radar now links straight through to a full coin page at /oracle/coin/<mint>, rebuilt in the same clean editorial design as the /coin/bitcoin markets pages. The page keeps everything it had (Oracle conviction, live market intel from six sources, agent transactions, a live trade tape) and adds the complete Launch Intelligence read from the radar engine: quality score, organic vs bundle, risk flags, the full signal breakdown, smart-money buyers, and the top-trader ledger. The live candles chart stays, joined by a native line view and an agent-trades overlay, and the whole page works in light and dark themes.</description></item>+ <item>+ <title>Coin Radar's live trade data restored, now read straight from the chain</title>+ <link>https://three.ws/oracle/</link>+ <guid isPermaLink="false">2026-07-19:Coin Radar's live trade data restored, now read straight from the chain</guid>+ <pubDate>Sun, 19 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The pipeline that watches every pump.fun launch had quietly lost its per-coin trade feed when the upstream data provider moved it behind a paywall, which left conviction scores flat and the oracle's calls, win rate, and proof panels empty. Trade ingestion now reads directly from the Solana chain itself over our own RPC failover, so every buy and sell is observed again with no third-party dependency. Conviction scores, smart-money tracking, and the oracle's actionable tiers repopulate as new launches are scored.</description>+ </item><item><title>Concierge ships to npm and the MCP registry, with a full examples set</title><link>https://three.ws/docs/concierge</link>@@ -38,6 +54,14 @@<category>sdk</category><description>The Concierge chat widget is now installable as the @three-ws/concierge npm package, and there is a companion Model Context Protocol server, @three-ws/concierge-mcp, on the official MCP registry. That server lets any AI assistant ask a website's concierge a question (it fetches the page and answers grounded in the real content), generate the copy-paste embed code for a site, and list the available 3D avatars. Six runnable examples now ship with the SDK, covering the one-tag install, the web component, the imperative API, a custom GLB avatar, a React wrapper, and pointing the widget at your own answer backend.</description></item>+ <item>+ <title>First autonomous agent trade, fully documented</title>+ <link>https://three.ws/blog/first-autonomous-trade</link>+ <guid isPermaLink="false">2026-07-19:First autonomous agent trade, fully documented</guid>+ <pubDate>Sun, 19 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>A platform agent closed its first fully autonomous trade: it sniped a brand-new pump.fun launch from its own wallet and exited at +42.38 percent, with every decision recorded on its hash-chained ledger. We published the complete postmortem: a blog post with the on-chain receipts, a deep-dive doc on the sniper architecture (entry gates, the simulate-the-sell trade firewall, the exit ladder), and a tutorial for arming a sniper on your own agent, including the take-profit lesson this trade taught us.</description>+ </item><item><title>Language links now always win, and the switcher stays out of the way</title><link>https://three.ws/what-is?lang=te</link>diff --git a/public/features.json b/public/features.jsonindex 016a90815..de9b2e7c2 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-19T04:07:01.009Z",+ "generated_at": "2026-07-19T07:05:14.397Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/pump/pumpkit-whale.js b/src/pump/pumpkit-whale.jsindex 4f52949d5..c2de9eb1e 100644--- a/src/pump/pumpkit-whale.js+++ b/src/pump/pumpkit-whale.js@@ -78,18 +78,21 @@ export async function watchWhaleTrades({ mint, minUsd = 5000, onTrade, signal })try {for (const event of parser.parseLogs(logInfo.logs)) {if (event.name !== 'TradeEvent') continue;- const { mint: evMint, isBuy, solAmount, user, timestamp } = event.data;- if (evMint.toString() !== mintStr) continue;- const sol = Number(solAmount.toString()) / LAMPORTS_PER_SOL;+ const d = event.data;+ // Anchor's coder emits snake_case fields with the current pump+ // IDL; older toolchains camelCased them — read both.+ const f = (a, b) => (d[a] !== undefined ? d[a] : d[b]);+ if (d.mint?.toString() !== mintStr) continue;+ const sol = Number(f('sol_amount', 'solAmount')?.toString() ?? '0') / LAMPORTS_PER_SOL;const usd = sol * solPrice;if (usd < minUsd) continue;onTrade({signature: logInfo.signature,- wallet: user.toString(),- sideBuy: isBuy,+ wallet: d.user?.toString() ?? null,+ sideBuy: !!f('is_buy', 'isBuy'),usd,sol,- ts: Number(timestamp.toString()) * 1000,+ ts: Number(f('timestamp', 'timestamp')?.toString() ?? '0') * 1000 || Date.now(),});}} catch {}diff --git a/tests/pump-onchain-trades.test.js b/tests/pump-onchain-trades.test.jsnew file mode 100644index 000000000..61df95e9e--- /dev/null+++ b/tests/pump-onchain-trades.test.js@@ -0,0 +1,44 @@+// api/_lib/pump-onchain-trades.js — decoded-event field access.+//+// The live failure this guards: anchor's coder emits snake_case event fields+// with the current pump IDL (sol_amount, is_buy), while older toolchains+// camelCased them. Consumers that read only one casing silently dropped every+// trade (the oracle pipeline starved on exactly this). eventField must serve+// both shapes.++import { describe, it, expect } from 'vitest';+import { eventField } from '../api/_lib/pump-onchain-trades.js';++// Mimics a BN-ish decoded value: only toString matters to consumers.+const bn = (v) => ({ toString: () => String(v) });++describe('eventField', () => {+ it('reads snake_case fields via their camelCase name', () => {+ const data = { sol_amount: bn(493827159), is_buy: true, token_amount: bn(2558317), user: bn('abc') };+ expect(eventField(data, 'solAmount').toString()).toBe('493827159');+ expect(eventField(data, 'isBuy')).toBe(true);+ expect(eventField(data, 'tokenAmount').toString()).toBe('2558317');+ });++ it('prefers the camelCase field when present', () => {+ const data = { solAmount: bn(7), sol_amount: bn(9) };+ expect(eventField(data, 'solAmount').toString()).toBe('7');+ });++ it('handles multi-hump names', () => {+ const data = { quote_amount_in: bn(11), base_amount_out: bn(22) };+ expect(eventField(data, 'quoteAmountIn').toString()).toBe('11');+ expect(eventField(data, 'baseAmountOut').toString()).toBe('22');+ });++ it('returns undefined for absent fields and nullish data', () => {+ expect(eventField({}, 'solAmount')).toBeUndefined();+ expect(eventField(null, 'solAmount')).toBeUndefined();+ expect(eventField(undefined, 'solAmount')).toBeUndefined();+ });++ it('does not confuse falsy values with absence', () => {+ expect(eventField({ is_buy: false }, 'isBuy')).toBe(false);+ expect(eventField({ sol_amount: 0 }, 'solAmount')).toBe(0);+ });+});diff --git a/workers/agent-sniper/intel/watcher.js b/workers/agent-sniper/intel/watcher.jsindex a0eeff392..46c8aea41 100644--- a/workers/agent-sniper/intel/watcher.js+++ b/workers/agent-sniper/intel/watcher.js@@ -14,8 +14,9 @@import WebSocket from 'ws';import { finalizeObservation } from './finalize.js';import { log } from '../log.js';+import { pumpPortalWsUrl, handlePumpPortalAck } from '../../../api/_lib/pumpportal.js';+import { subscribePumpOnchainTrades } from '../../../api/_lib/pump-onchain-trades.js';-const PUMPPORTAL_WS = 'wss://pumpportal.fun/api/data';const RECONNECT_DELAY_MS = 2_000;const LAMPORTS_PER_SOL = 1_000_000_000;const META_TIMEOUT_MS = 2_500;@@ -70,10 +71,17 @@ export function startIntelWatcher({let droppedSinceLog = 0;const observations = new Map(); // mint -> { meta, trades, firstSeenAtMs, createdAtSec, devBuyLamports, timer }+ // The authoritative trade source: one program-wide on-chain subscription+ // covering every observed mint. PumpPortal's per-mint trade stream (below)+ // only augments it when a funded PUMPPORTAL_API_KEY is configured — without+ // one PumpPortal refuses trade subscriptions, and this lane carries alone.+ const stopOnchain = subscribePumpOnchainTrades({ network, onTrade: (msg) => { if (active) recordTrade(msg); } });+function stop() {active = false;clearTimeout(reconnectTimer);for (const obs of observations.values()) clearTimeout(obs.timer);+ try { stopOnchain(); } catch {}if (ws) try { ws.close(); } catch {}}signal?.addEventListener('abort', stop);@@ -113,6 +121,10 @@ export function startIntelWatcher({trades: msg.solAmount? [{ trader: msg.traderPublicKey || null, isBuy: true, lamports: solToLamports(msg.solAmount), baseAmount: Number(msg.tokenAmount) || 0, ts: now, signature: msg.signature }]: [],+ // Trades arrive from two sources (the on-chain firehose always; the+ // PumpPortal per-mint stream when an API key is funded) — dedupe by tx+ // signature so the overlap, and the seeded launch buy, count once.+ sigs: new Set(msg.signature ? [msg.signature] : []),timer: null,};observations.set(mint, obs);@@ -129,6 +141,10 @@ export function startIntelWatcher({function recordTrade(msg) {const obs = observations.get(msg.mint);if (!obs) return;+ if (msg.signature) {+ if (obs.sigs.has(msg.signature)) return;+ obs.sigs.add(msg.signature);+ }obs.trades.push({trader: msg.traderPublicKey || null,isBuy: msg.txType === 'buy',@@ -170,7 +186,7 @@ export function startIntelWatcher({function connect() {if (!active) return;- ws = new WebSocket(PUMPPORTAL_WS);+ ws = new WebSocket(pumpPortalWsUrl());ws.on('open', () => {send({ method: 'subscribeNewToken' });@@ -184,7 +200,7 @@ export function startIntelWatcher({if (!active) return;let msg;try { msg = JSON.parse(raw.toString()); } catch { return; }- if (msg.message) return; // ack+ if (handlePumpPortalAck(msg, (line) => log.warn?.(line))) return;if (msg.txType === 'create') startObservation(msg);else if (msg.txType === 'buy' || msg.txType === 'sell') recordTrade(msg);});