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(coin3d): make the 3D token scene embeddable and address it by pair as well as mint

ni3af9c600fe9e28
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 65596491f..2b7a12b79 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -262,10 +262,12 @@ bottom.
| Real-funds agreements (signature gate) | dialog [public/risk-ack.js](public/risk-ack.js), app wrapper [src/shared/risk-ack.js](src/shared/risk-ack.js), server enforcement [api/_lib/real-funds-agreement.js](api/_lib/real-funds-agreement.js), sign/status endpoint [api/legal/risk-ack.js](api/legal/risk-ack.js), review page [public/legal/agreements.html](public/legal/agreements.html) `→ /legal/agreements`, documents [public/legal/tos.html](public/legal/tos.html), [public/legal/risk.html](public/legal/risk.html), [public/legal/agent-wallet.html](public/legal/agent-wallet.html) `→ /legal/agent-wallet`, coverage guard [tests/real-funds-agreement-coverage.test.js](tests/real-funds-agreement-coverage.test.js) | In-repo | Before any real-funds action (deposit address reveal, tip, trade, snipe, withdraw, send, swap, launch, x402, onramp, autopilot arm) a person signs the Terms of Service, Risk Disclosure, and Agent Wallet Agreement: one checkbox per document, eligibility and no-liability attestations, and a typed-name e-signature. Signatures land append-only in `legal_signatures` with document versions and text fingerprints. Every custodial money endpoint calls `requireRealFundsAgreement()`, which answers `403 risk_ack_required` for unsigned accounts (session and API key alike); devnet exempt. See [docs/risk-acknowledgment.md](docs/risk-acknowledgment.md) |
| Global markets + coin detail pages | [pages/coins.html](pages/coins.html) + [src/coins-index.js](src/coins-index.js) `→ /coins`, [pages/coin.html](pages/coin.html) + [src/coin-page.js](src/coin-page.js) `→ /coin/:id`, backend [api/coin/](api/coin) (detail, tickers, ohlc, pool, markets, news, global over [api/_lib/coingecko.js](api/_lib/coingecko.js)) | In-repo | CoinGecko-style markets index (global stats bar, sortable top-coins table, search, sparklines) + a rich detail page per coin: interactive chart with a source switcher (native CoinGecko line chart, TradingView advanced candlesticks, or the DexScreener / GeckoTerminal on-chain terminal — each shown only when it can chart the coin; GeckoTerminal's pool resolved via [api/coin/pool.js](api/coin/pool.js)), 1h→1y price-performance matrix, market-stats grid, circulating/max supply bar with Mcap/FDV ratio, ATH/ATL with drawdown & recovery multiple, community sentiment vote split, community + developer (GitHub) activity grids, a paginated exchange-listings table (`api/coin/tickers`, ±2% depth + trust) linking into exchange detail, related news, and full link pills (site/social/whitepaper/forum/chat/explorers). Design adopted from cryptocurrency.cv; accepts CoinGecko slugs or Solana mints. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
| Global Intel Globe (`/globe`) | Page [pages/globe.html](pages/globe.html) `-> /globe`, renderer [src/globe-intel.js](src/globe-intel.js), pure logic [src/globe-intel-core.js](src/globe-intel-core.js), styles [src/globe-intel.css](src/globe-intel.css); API [api/globe/intel.js](api/globe/intel.js) over [api/_lib/globe-sources.js](api/_lib/globe-sources.js) and [api/_lib/globe-centroids.js](api/_lib/globe-centroids.js); ingest [api/cron/globe-ingest.js](api/cron/globe-ingest.js) -> `globe_events`; reference set [data/globe-reference.json](data/globe-reference.json), geometry baked by [scripts/build-globe-geometry.mjs](scripts/build-globe-geometry.mjs) into [public/data/globe-land.json](public/data/globe-land.json) + [data/country-centroids.json](data/country-centroids.json) | Live | **A 3D globe of what is happening on Earth right now.** Eleven layers on one sphere: armed conflict, force posture and sanctions classified out of the GDELT 2.0 event stream by CAMEO code, attention hotspots computed from them, natural events (USGS, NASA EONET, GDACS), severe weather (GDACS), national internet outages (Georgia Tech IODA), economic stress (World Bank), and the reference geography that gives the live layers meaning: overseas military bases, nuclear sites, and maritime chokepoints that score themselves against the live feed rather than sitting still. Every upstream is keyless, so the page works on a fresh clone. GDELT publishes one file every 15 minutes and no queryable history (its GEO 2.0 API 404s for every query), so the 24h/7d/30d control is only honest because the cron keeps the window in Postgres; each layer reports the span it actually covered and the panel prints "Covers 15h so far" rather than implying a week. A dead upstream renders as a named layer with its reason, never as an empty globe. Camera, zoom, projection, range and layer selection all live in the URL, so any view is a shareable link. Globe and flat map are the same geometry lerped between two projections, written into `position` rather than a vertex shader so every marker stays pickable in both. Docs: [docs/globe.md](docs/globe.md). Tests: [tests/globe-intel-core.test.js](tests/globe-intel-core.test.js), [tests/globe-sources.test.js](tests/globe-sources.test.js) |
+| Token in 3D (`/coin3d`, embeddable) | [pages/coin3d.html](pages/coin3d.html) + [src/coin3d/main.js](src/coin3d/main.js) `→ /coin3d`; pair bridge [api/coin/pair.js](api/coin/pair.js) `→ /api/coin/pair` over `tokenForPool()` in [api/_lib/market/ohlcv.js](api/_lib/market/ohlcv.js) | In-repo | Any Solana token as a live 3D scene: logo medallion, holder galaxy sized by balance, graduation ring, and a tape of real swaps, all from on-chain and live market data, degrading to a data view where WebGL is unavailable. Addressable two ways: `?mint=` (what three.ws keys tokens by) or `?pair=` (what every DEX terminal keys a market by), resolved through `/api/coin/pair`, the inverse of [api/coin/pool.js](api/coin/pool.js). `?embed=1` plus `frame-ancestors *` on the route make it framable on any site, with one attribution link as its only added chrome. Tests: [tests/api/coin-pair.test.js](tests/api/coin-pair.test.js) (route contract), [tests/api/coin-pair-resolver.test.js](tests/api/coin-pair-resolver.test.js) (the resolver and its fallback). Docs: [docs/coin3d-embed.md](docs/coin3d-embed.md) |
| Market tools (heatmap, sentiment, gas, compare) | [pages/heatmap.html](pages/heatmap.html) + [src/heatmap.js](src/heatmap.js) `→ /heatmap`, [pages/fear-greed.html](pages/fear-greed.html) + [src/fear-greed.js](src/fear-greed.js) `→ /fear-greed`, [pages/gas.html](pages/gas.html) + [src/gas.js](src/gas.js) `→ /gas`, [pages/compare.html](pages/compare.html) + [src/compare.js](src/compare.js) `→ /compare`; backend [api/coin/fear-greed.js](api/coin/fear-greed.js), [api/coin/gas.js](api/coin/gas.js) | In-repo | Four tools extending Markets, same design system: treemap heatmap (market-cap-sized tiles), Fear & Greed gauge + history, live Ethereum gas tracker (keyless `eth_feeHistory`), and up-to-4-coin compare (overlay perf + stats). All real key-free data; cross-linked from the markets table. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
| Market tools II (screener, categories, exchanges, derivatives, converter, DeFi, chains, stablecoins) | Pages+JS `→ /screener /categories /exchanges /derivatives /converter /defi /chains /stablecoins`; backend [api/coin/](api/coin) (categories, exchanges, derivatives, rates) over CoinGecko + [api/defi/](api/defi) (protocols, chains, stablecoins) over DeFiLlama | In-repo | Eight more Markets tools, same design system: token screener + category rankings + exchange/derivatives tables + crypto⇄fiat converter (CoinGecko), plus a DeFiLlama trio — DeFi TVL by protocol, chains by TVL, stablecoins with peg health. All real key-free data; cross-linked from the markets table. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
| Market surfaces III (protocol/chain/stablecoin detail + fees, DEX volumes, hacks, trending) | Detail pages `→ /protocol/:slug /chain/:name /stablecoin/:id` over [api/defi/protocol.js](api/defi/protocol.js), [api/defi/chain.js](api/defi/chain.js), [api/defi/stablecoin.js](api/defi/stablecoin.js); surfaces `→ /fees /dex-volumes /hacks` over [api/defi/](api/defi) (fees, dex-volumes, hacks over DeFiLlama) + `→ /markets/trending` over [api/coin/trending.js](api/coin/trending.js) (CoinGecko /search/trending); list rows in [src/defi.js](src/defi.js), [src/chains.js](src/chains.js), [src/stablecoins.js](src/stablecoins.js) now deep-link into the detail pages | In-repo | Turns the DeFiLlama list pages into full detail experiences: a protocol page (TVL history + hallmark markers, per-chain breakdown, fees/revenue, funding rounds, methodology), a chain page (TVL + stablecoin + DEX-volume charts, top protocols), a stablecoin page (supply history, per-chain distribution, peg-deviation badge). Plus three new market surfaces — protocol fees & revenue, the DEX-volume leaderboard, and a searchable DeFi hacks database ($16.7B all-time) — and a CoinGecko trending page (most-searched coins/categories/NFTs). All real key-free data, cross-linked. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
| Market detail pages (exchange, category) + DeFi yields | [pages/exchange.html](pages/exchange.html) + [src/exchange-page.js](src/exchange-page.js) `→ /exchange/:id` over [api/coin/exchange.js](api/coin/exchange.js), [pages/category.html](pages/category.html) + [src/category-page.js](src/category-page.js) `→ /category/:id` over [api/coin/category.js](api/coin/category.js) + [api/coin/markets.js](api/coin/markets.js) (`?category=`), [pages/yields.html](pages/yields.html) + [src/yields.js](src/yields.js) `→ /yields` over [api/defi/yields.js](api/defi/yields.js) | In-repo | Rich detail pages that turn list rows into full profiles. Exchange: trust badge, normalized-volume stat, BTC-volume history chart, and a per-pair markets table (spot + derivatives fallback), reached from `/exchanges` and the new Derivatives Exchanges table. Category: rank, sector stats, the full sortable coins table for that sector, and related categories, reached from `/categories`. Yields: an explorer over ~15k live DeFiLlama pools with chain/project/stablecoin/min-TVL filters, APY/TVL sort, URL-synced state, and a per-pool APY+TVL history chart on row expand. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
+| Perpetual contract detail page | [pages/derivative.html](pages/derivative.html) + [src/derivative-page.js](src/derivative-page.js) + [src/derivative-page.css](src/derivative-page.css) `→ /derivative/:venue/:symbol` over [api/coin/derivative.js](api/coin/derivative.js); slug helper [src/shared/derivative-slug.js](src/shared/derivative-slug.js) vendored to [api/_lib/derivative-slug.js](api/_lib/derivative-slug.js); venue directory [api/_lib/derivative-venues.js](api/_lib/derivative-venues.js) | In-repo | Every row of `/derivatives` now opens a full contract page instead of dead-ending in the table: mark price against its own index and the basis between them, the funding rate turned into what a position you size yourself pays per interval, per day and per year, open interest and volume with the contract's rank across every venue listing that underlying, the underlying's spot chart, and a cross-venue funding table with callouts for the cheapest venue to hold a long, the best paid venue to hold a short, the funding spread and price dispersion (liquid venues only). Also reached from the contracts table on a derivatives venue's `/exchange/:id` profile. Tests: [tests/api/derivative-contract.test.js](tests/api/derivative-contract.test.js). Docs: [docs/coin-pages.md](docs/coin-pages.md) |
| Crypto news + archive + markets hub | [pages/markets.html](pages/markets.html) + [src/markets-page.js](src/markets-page.js) `→ /markets`, [pages/markets-news.html](pages/markets-news.html) + [src/markets-news.js](src/markets-news.js) `→ /markets/news`, [pages/news-article.html](pages/news-article.html) + [src/news-article.js](src/news-article.js) `→ /markets/news/article`, [pages/news-archive.html](pages/news-archive.html) + [src/news-archive.js](src/news-archive.js) `→ /markets/archive`, [pages/news-digest.html](pages/news-digest.html) + [src/news-digest.js](src/news-digest.js) `→ /markets/digest`; backend [api/news/](api/news) (feed, article, knowledge, archive, digest, rss, image) over [api/_lib/article-extract.js](api/_lib/article-extract.js) (page→reader→feed→preview ladder) and [api/_lib/news-rights.js](api/_lib/news-rights.js) (publisher rights layer, enforced at every read path), [api/_lib/news-coins.js](api/_lib/news-coins.js) (ticker→live market snapshot), [api/_lib/news-knowledge-store.js](api/_lib/news-knowledge-store.js) (durable `news_knowledge` corpus) + hourly archiver [api/cron/news-archive-append.js](api/cron/news-archive-append.js) over [api/_lib/news.js](api/_lib/news.js) + [api/_lib/news-sources.js](api/_lib/news-sources.js), corpus on `gs://three-ws-news-archive`, purge tooling [scripts/news-takedown-purge.mjs](scripts/news-takedown-purge.mjs) | In-repo | The Markets news wing + front door: /markets/news is “Your briefing”: live news aggregated natively from 197 publisher feeds (Featured/Trending/Saved tabs, breaking ticker, AI briefing card, top-stories hero + rail, search, sentiment, ticker chips, og:image preview resolution for imageless feeds), a rich article reader that shows a bounded lead excerpt plus our own summary/key points/entities/market context and sends the reader to the publisher for the rest (the excerpt cap and any rightsholder takedowns are enforced server-side across the reader, RSS mirror, archive search, and agent knowledge corpus, never just hidden client-side), and renders **live coin cards** (price/24h/7d/sparkline→/coin/:id) for detected tickers, and related coverage. Every read story is recorded to a durable **news knowledge base** (`GET /api/news/knowledge`) that grounds the 3D agents, itself subject to the same excerpt limit. Plus the largest open crypto-news archive (662,047 enriched articles, Sept 2017 → today, EN+中文, GCS-hosted) and the /markets hub aggregating global stats, the top-100 table, breaking news, and every market surface as a hero card. Docs: [docs/coin-pages.md](docs/coin-pages.md), [docs/api-reference.md](docs/api-reference.md), [docs/news-rights.md](docs/news-rights.md) (publisher takedown path) |
| Robinhood Chain markets + buy flow | Hub + detail pages [pages/markets-robinhood.html](pages/markets-robinhood.html) + [src/markets-robinhood.js](src/markets-robinhood.js) `→ /markets/robinhood`, [pages/robinhood-stock.html](pages/robinhood-stock.html) + [src/robinhood-stock.js](src/robinhood-stock.js) `→ /markets/robinhood/stock/:symbol`, [pages/robinhood-coin.html](pages/robinhood-coin.html) + [src/robinhood-coin.js](src/robinhood-coin.js) `→ /markets/robinhood/coin/:address`, buy flow [src/robinhood-purchase.js](src/robinhood-purchase.js), wallet desk [pages/hood-desk.html](pages/hood-desk.html) + [src/hood-desk.js](src/hood-desk.js) + [src/hood-desk.css](src/hood-desk.css) `→ /markets/robinhood/desk`; backend [api/_lib/robinhood.js](api/_lib/robinhood.js) + `api/v1/robinhood/{chain,stocks,stocks-detail,coins,coins-detail,launches,desk,wallet}.js` (free, the last two composed for the desk over [api/_lib/robinhood-desk.js](api/_lib/robinhood-desk.js)) + [api/x402/robinhood-portfolio.js](api/x402/robinhood-portfolio.js) (x402 paid) | In-repo | The 24/7 tokenized-equity board for Robinhood Chain (4663): live Chainlink NAV vs. Uniswap DEX premium for every Stock Token (one multicall, never 95 RPC calls), a memecoin screener across NOXA/The Odyssey launchpads (CoinGecko categories + on-chain launch logs via Blockscout), and chain TVL/gas/block stats. Detail pages add NAV history, holders, transfers, and contract links. Coin pages carry a real buy panel: injected-wallet connect, chain-switch to 4663, live Uniswap v3 `QuoterV2` quote + `SwapRouter02` swap with slippage, LI.FI bridge deep-link; Stock Tokens are display-only (tokenized securities, not offered to US persons) with an eligibility-gated outbound DEX link instead. Paid `portfolio` endpoint returns ERC-8056 `uiMultiplier`-correct holdings. The Hood Desk (`/markets/robinhood/desk`) is the wallet-first view of the same chain: paste or connect any address and it loads that wallet's book (native + priced ERC-20 positions), its native balance curve rebuilt from Blockscout's daily and per-transaction feeds (the public RPC is not an archive node), an activity tape that folds token transfers onto the transaction that emitted them, the NAV premium ridge layered by liquidity floor, counterparty flow, and memecoin movers. Read-only and signature-free; the trade ticket reuses the coin pages' swap panel and the Stock Token eligibility gate. Tests: [tests/robinhood-desk.test.js](tests/robinhood-desk.test.js) (the derivations) and [tests/e2e/hood-desk.spec.js](tests/e2e/hood-desk.spec.js) (the panels, the empty states, the ladder collapse and the trade ticket). Docs: [docs/robinhood-chain-markets.md](docs/robinhood-chain-markets.md) |
| $THREE launchpad (native bonding curve) | Page [pages/three-launchpad.html](pages/three-launchpad.html) + [src/three-launchpad/](src/three-launchpad) `→ /three-launchpad`; backend [api/_lib/native-launch/](api/_lib/native-launch) + [api/native-launch/[action].js](api/native-launch/%5Baction%5D.js); lane toggle in [public/studio/launch-panel.js](public/studio/launch-panel.js); config + devnet scripts `scripts/native-launchpad-*.mjs` | In-repo · code-complete, mainnet config creation owner-gated (about 0.006 SOL) | Solana. Every coin launched on the lane is quoted in $THREE on Meteora's Dynamic Bonding Curve: buys are made with $THREE, creators earn 50% of the 1% fee in $THREE, and graduation (60M $THREE market cap, about 12.3M $THREE raised) locks 100% of LP in a DAMM v2 pool against $THREE. Public buy and sell via `swap-prep`, no session needed. Verified by a keyless mainnet simulation that creates the config and a $THREE-quoted pool against the live program. Docs: [docs/native-launchpad.md](docs/native-launchpad.md) |
diff --git a/api/_lib/market/ohlcv.js b/api/_lib/market/ohlcv.js
index 3195d2d21..bfc531427 100644
--- a/api/_lib/market/ohlcv.js
+++ b/api/_lib/market/ohlcv.js
@@ -23,6 +23,7 @@ import { cexCandleProviders } from '../cex-public.js';
const BASE = 'https://api.geckoterminal.com/api/v2';
const BIRDEYE_BASE = 'https://public-api.birdeye.so';
const DEXSCREENER_TOKENS = 'https://api.dexscreener.com/latest/dex/tokens';
+const DEXSCREENER_PAIRS = 'https://api.dexscreener.com/latest/dex/pairs';
const UA = 'three.ws-granite-oracle/1.0';
// Small in-memory cache: GeckoTerminal's free tier is ~30 req/min and candle
@@ -43,9 +44,20 @@ const TRENDING_FRESH_S = 60;
// NOT retried.
const MAX_ATTEMPTS = 3;
-// DexScreener chain slug for a GeckoTerminal network id. The two agree for the
-// networks this oracle serves; anything else maps to itself.
-const DEX_CHAIN_BY_NETWORK = { solana: 'solana', eth: 'ethereum', base: 'base', bsc: 'bsc' };
+// DexScreener chain slug for a GeckoTerminal network id. The two disagree on
+// four of the eight networks served here, and an identity fallback quietly
+// asked DexScreener for chain "polygon_pos" (which it has never heard of), so
+// every rung-2 lookup on those chains missed rather than failing loudly.
+const DEX_CHAIN_BY_NETWORK = {
+ solana: 'solana',
+ eth: 'ethereum',
+ base: 'base',
+ bsc: 'bsc',
+ polygon_pos: 'polygon',
+ arbitrum: 'arbitrum',
+ optimism: 'optimism',
+ avax: 'avalanche',
+};
const num = (v) => {
const n = Number(v);
@@ -199,6 +211,96 @@ export async function topPoolForToken(mint, network = 'solana') {
);
}
+// ── The inverse lookup: pool address -> the token that pool trades ───────────
+//
+// Every rung above answers "where does this token trade". This one answers the
+// question a partner surface asks instead: a chart terminal names a market by
+// its PAIR address, not by a mint, so a link or an embed arriving from one
+// carries the pool and nothing else. Resolving it here means an embed can be
+// keyed by whatever identifier the host page already has.
+
+const tokenRef = (address, meta = {}) =>
+ address ? { address, name: meta.name || null, symbol: meta.symbol || null } : null;
+
+// Rung 2: DexScreener's own record for the pair. It carries base and quote
+// token metadata inline, so it answers the whole shape in one call.
+function dexscreenerPairProvider(pool, network) {
+ const chain = DEX_CHAIN_BY_NETWORK[network];
+ if (!chain) return null;
+ return {
+ name: 'dexscreener-pair',
+ url: `${DEXSCREENER_PAIRS}/${chain}/${encodeURIComponent(pool)}`,
+ parse: async (r) => {
+ const data = await r.json();
+ const pair = (Array.isArray(data?.pairs) ? data.pairs : [])[0] || data?.pair || null;
+ if (!pair?.baseToken?.address) return null;
+ return {
+ pool: pair.pairAddress || pool,
+ token: tokenRef(pair.baseToken.address, pair.baseToken),
+ quote: tokenRef(pair.quoteToken?.address, pair.quoteToken || {}),
+ dex: pair.dexId || null,
+ pairName:
+ pair.baseToken.symbol && pair.quoteToken?.symbol
+ ? `${pair.baseToken.symbol} / ${pair.quoteToken.symbol}`
+ : null,
+ };
+ },
+ };
+}
+
+async function tokenForPoolLive(pool, network) {
+ let geckoErr = null;
+ try {
+ // include= is what carries the token names and symbols; without it the
+ // relationships hold ids only and the caller would have to re-fetch both.
+ const json = await gecko(`/networks/${network}/pools/${pool}?include=base_token,quote_token`);
+ const d = json?.data;
+ const baseId = d?.relationships?.base_token?.data?.id;
+ const address = bareId(baseId);
+ if (address) {
+ const included = new Map((json.included || []).map((i) => [i.id, i.attributes || {}]));
+ const quoteId = d.relationships?.quote_token?.data?.id;
+ return {
+ pool: d.attributes?.address || bareId(d.id),
+ token: tokenRef(address, included.get(baseId) || {}),
+ quote: tokenRef(bareId(quoteId), included.get(quoteId) || {}),
+ // The dex id is NOT network-prefixed ("raydium", "pumpswap"), so it
+ // must not go through bareId(): that would cut "pump_fun" to "fun".
+ dex: d.relationships?.dex?.data?.id || null,
+ pairName: d.attributes?.name || null,
+ };
+ }
+ geckoErr = tagged(`no base token for pool ${pool}`, 404);
+ } catch (e) {
+ geckoErr = e;
+ }
+ // GeckoTerminal has not indexed the pool, or is down. A young pump.fun pair
+ // is exactly this case, and it is the case a partner embed hits most.
+ const provider = dexscreenerPairProvider(pool, network);
+ const hit = provider
+ ? await fetchFirstOrNull([provider], { timeoutMs: 6000, label: `pool-token:${pool}` })
+ : null;
+ if (hit) return hit;
+ throw geckoErr;
+}
+
+/**
+ * The token a pool trades, from its pool (pair) address.
+ *
+ * @param {string} pool On-chain pool/pair account address.
+ * @param {string} network GeckoTerminal network id.
+ * @returns {Promise<{ pool: string, token: {address,name,symbol}, quote: object|null, dex: string|null, pairName: string|null }>}
+ * @throws {Error & { status: number }} 404 when no source knows the pool.
+ */
+export async function tokenForPool(pool, network = 'solana') {
+ return cacheWrapLastGood(
+ `ohlcv:pooltoken:v1:${network}:${pool}`,
+ POOL_FRESH_S,
+ () => tokenForPoolLive(pool, network),
+ { staleTtlSeconds: LKG_STALE_S },
+ );
+}
+
function normalizeTrending(json, limit) {
return (json?.data || []).slice(0, limit).map((p) => {
const a = p.attributes || {};
diff --git a/api/coin/pair.js b/api/coin/pair.js
new file mode 100644
index 000000000..d33dea7b9
--- /dev/null
+++ b/api/coin/pair.js
@@ -0,0 +1,63 @@
+// GET /api/coin/pair?address=<pool-address>&network=<geckoterminal-network>
+// ---------------------------------------------------------------------------
+// The inverse of /api/coin/pool: hand it the PAIR address a chart terminal uses
+// to name a market, get back the token that pair trades.
+//
+// Every DEX terminal (DEXTools, DexScreener, GeckoTerminal) keys a market by its
+// pool account, so a link, a widget parameter or an embed arriving from one
+// carries a pair and no mint. three.ws keys everything by mint. This endpoint is
+// the bridge, which is what lets /coin3d be embedded straight into a pair page
+// with the identifier that page already has.
+//
+// Keyless and CORS-open on purpose: a partner's page calls it from the browser.
+// Real data only: GeckoTerminal first, DexScreener for a pair GeckoTerminal has
+// not indexed yet (which is every young pump.fun pair), and a last-good tier
+// behind both. A pool nobody knows is a 404, never an invented token.
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { tokenForPool } from '../_lib/market/ohlcv.js';
+
+// Same network set /api/coin/pool accepts, so the two directions stay symmetric.
+const NETWORKS = new Set(['solana', 'eth', 'base', 'bsc', 'polygon_pos', 'arbitrum', 'optimism', 'avax']);
+
+const SOL_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const EVM_RE = /^0x[0-9a-fA-F]{40}$/;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.marketDataIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, 'http://x').searchParams;
+ const address = (params.get('address') || '').trim();
+ const network = (params.get('network') || 'solana').trim();
+
+ if (!NETWORKS.has(network)) {
+ return error(res, 400, 'bad_network', 'network must be a supported GeckoTerminal network id');
+ }
+ // A pool account is addressed exactly like a token on the same chain, so the
+ // same shape check applies and a malformed value never reaches upstream.
+ const wellFormed = network === 'solana' ? SOL_RE.test(address) : EVM_RE.test(address);
+ if (!wellFormed) {
+ return error(res, 400, 'bad_address', 'address is not a valid pool address for the network');
+ }
+
+ try {
+ const { pool, ...market } = await tokenForPool(address, network);
+ return json(
+ res,
+ 200,
+ { network, pair: pool || address, ...market },
+ { 'cache-control': 'public, max-age=60, s-maxage=300, stale-while-revalidate=600' },
+ );
+ } catch (err) {
+ // A pair no source has indexed is a normal outcome, not a fault: the
+ // caller shows "we can't render this market yet" rather than a dead frame.
+ if (err?.status === 404) return error(res, 404, 'no_pair', 'no indexed market found for this pool address');
+ if (err?.status === 429) return error(res, 429, 'rate_limited', 'pair source is throttled, retry shortly');
+ return error(res, 502, 'upstream_error', 'pair source is temporarily unavailable');
+ }
+});
diff --git a/data/changelog.json b/data/changelog.json
index 373aea66a..658983cd4 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-09-20",
+ "title": "Put any token's 3D scene on your own site, keyed by the pair address you already have",
+ "summary": "Token in 3D is now embeddable anywhere with a single iframe, and it accepts two identifiers instead of one. Chart terminals, launchpads and wallets name a market by its pair (pool) address, while three.ws keys tokens by mint, so /coin3d now takes ?pair= as well as ?mint= and resolves the rest itself through a new public endpoint, /api/coin/pair. Add ?embed=1 and the scene drops the chrome your own page owns, keeps one attribution link, and sends its links to a new tab instead of navigating your frame. Free, keyless, and no account: paste the iframe and it renders the live medallion, holder galaxy, graduation ring and real trade tape for that market.",
+ "tags": [
+ "feature",
+ "sdk"
+ ],
+ "link": "/docs/coin3d-embed"
+ },
{
"date": "2026-09-20",
"title": "A launchpad where every coin is bought with $THREE",
diff --git a/data/pages.json b/data/pages.json
index dc2a71ae3..22cf3ec1c 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -2382,7 +2382,7 @@
{
"path": "/coin3d",
"title": "Token in 3D",
- "description": "Any pump.fun token as a live 3D scene: a spinning coin medallion with the token's logo, top holders as a galaxy sized by balance, and a graduation ring tracking bonding-curve progress.",
+ "description": "Any pump.fun token as a live 3D scene: a spinning coin medallion with the token's logo, top holders as a galaxy sized by balance, and a graduation ring tracking bonding-curve progress. Address it by mint or by the pair address a chart terminal uses, and embed it on any site with one iframe.",
"priority": 0.5,
"changefreq": "weekly",
"added": "2026-06-02"
@@ -3086,6 +3086,14 @@
"changefreq": "monthly",
"added": "2026-07-30"
},
+ {
+ "path": "/docs/coin3d-embed",
+ "title": "Docs · Token in 3D, as an embed",
+ "description": "Put a live 3D view of any Solana market on your own page with one iframe, keyed by the mint or by the pair address your chart already uses. Covers the pair-to-token bridge, the parameters, sizing, the designed failure states, and driving the scene from the host page.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-09-20"
+ },
{
"path": "/docs/coin-wars",
"title": "Docs · Coin Wars",
@@ -6484,6 +6492,20 @@
"added": "2026-07-31",
"indexable": false
},
+ {
+ "path": "/prompts.json",
+ "title": "prompts.json",
+ "description": "The prompt library as structured data: categories, setup tiers, tags, and every prompt with what it returns.",
+ "indexable": false,
+ "added": "2026-09-20"
+ },
+ {
+ "path": "/prompts.txt",
+ "title": "prompts.txt",
+ "description": "The prompt library as plain text, for piping straight into an assistant.",
+ "indexable": false,
+ "added": "2026-09-20"
+ },
{
"path": "/llms.txt",
"title": "llms.txt",
diff --git a/docs/coin3d-embed.md b/docs/coin3d-embed.md
new file mode 100644
index 000000000..dbe83ea76
--- /dev/null
+++ b/docs/coin3d-embed.md
@@ -0,0 +1,109 @@
+# Token in 3D, as an embed
+
+> **Audience:** Developers at a chart terminal, launchpad, wallet, or token page who want a live 3D view of a market beside their own data. Also the three.ws side, for how the pair-to-mint bridge works.
+
+[`/coin3d`](https://three.ws/coin3d) renders any Solana token as a live 3D scene: a coin medallion carrying the token's logo, its top holders as a galaxy sized by balance, a graduation ring tracking bonding-curve progress, and a tape of real swaps as they land. Every number in it is read from chain and from live market sources.
+
+It is also framable anywhere, keyed by **either** identifier you already have:
+
+```html
+<!-- by mint, if your page knows the token -->
+<iframe src="https://three.ws/coin3d?mint=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&embed=1"
+ width="420" height="560" style="border:0" loading="lazy"
+ title="$THREE in 3D"></iframe>
+
+<!-- by pair, if your page knows the market -->
+<iframe src="https://three.ws/coin3d?pair=CnK82s8exdsK9nwqQ55kd9wcxoA22NwTchZJCBdu8LDa&embed=1"
+ width="420" height="560" style="border:0" loading="lazy"
+ title="three / SOL in 3D"></iframe>
+```
+
+No key, no account, no registration. Both snippets above render the same live scene.
+
+---
+
+## Why `pair` exists
+
+A chart terminal does not think in mints. It thinks in markets, and it names a market by the **pair address**: the on-chain pool account. DEXTools, DexScreener and GeckoTerminal all key their own widgets that way, so the identifier sitting in a pair page's URL is a pool, not a token.
+
+three.ws keys everything by mint. Requiring a partner to resolve mint-from-pool before it can embed anything is a real integration cost, and it is a lookup we already do in the other direction, so `?pair=` accepts the pool and resolves it here.
+
+The resolution is [`GET /api/coin/pair`](./api-reference.md#pair-resolution-pool-address-to-token), which is public and usable on its own:
+
+```bash
+curl -s 'https://three.ws/api/coin/pair?address=CnK82s8exdsK9nwqQ55kd9wcxoA22NwTchZJCBdu8LDa'
+```
+
+```json
+{
+ "network": "solana",
+ "pair": "CnK82s8exdsK9nwqQ55kd9wcxoA22NwTchZJCBdu8LDa",
+ "token": { "address": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump", "name": "three.ws", "symbol": "three" },
+ "quote": { "address": "So11111111111111111111111111111111111111112", "name": "Wrapped SOL", "symbol": "SOL" },
+ "dex": "meteora",
+ "pairName": "three / SOL"
+}
+```
+
+GeckoTerminal answers first and DexScreener covers a pair GeckoTerminal has not indexed, which is every pair for its first few minutes. That matters for a launchpad: the window where a coin is most looked at is exactly the window the primary index is still empty for.
+
+`/coin3d` itself renders Solana tokens, so the embed resolves pairs on Solana. The endpoint behind it serves the eight networks `/api/coin/pool` serves.
+
+---
+
+## Parameters
+
+| Parameter | Value | Effect |
+|---|---|---|
+| `mint` | Solana mint address | Renders that token. Takes precedence over `pair`. |
+| `pair` | Solana pool/pair address | Resolves to the token that pool trades, then renders it. |
+| `embed` | `1` | Embed chrome: drops the orbit hint and the locale control the host page owns, adds one attribution link back to the full scene, and sends every outbound link to a new tab instead of navigating your frame. |
+| `network` | `devnet` | Reads bonding-curve state from devnet. Omit for mainnet. |
+
+With neither `mint` nor `pair`, an `embed=1` frame renders a designed "no token selected" panel rather than the standalone page's search-and-browse landing, which is the wrong thing to put inside someone else's panel.
+
+---
+
+## Sizing and behaviour
+
+- **Minimum useful size is about 320x420.** The data HUD reflows down to 320px wide; below that the scene is the only thing worth showing.
+- **The scene degrades, it does not fail.** Where WebGL is unavailable (old device, disabled, lost context) the canvas is dropped and the HUD, sparkline and live trade tape keep working as a data view.
+- **Sources fail independently.** Holder scan, oracle conviction, market figures and coin intel each load after first paint and fill in when they land; a slow one never holds the frame on a spinner.
+- **`loading="lazy"` is safe.** The embed's own load watchdog only starts its clock once the frame is actually on screen.
+
+Every failure mode has a designed state inside the frame: an unresolvable pair says so and offers a way out, a malformed address says what was wrong with it, and a token no source knows says that rather than drawing an empty scene.
+
+---
+
+## Knowing when the scene is up
+
+An embed on your own origin is cross-origin to three.ws, so your page cannot read into the frame. In embed mode the frame posts its ready event out instead:
+
+```js
+window.addEventListener('message', (e) => {
+ if (e.origin !== 'https://three.ws') return;
+ if (e.data?.source !== 'three.ws/coin3d') return;
+ const { token, sceneOk } = e.data; // token: { mint, name, symbol }
+ // sceneOk is false when WebGL was unavailable and the frame fell back to
+ // its data view, so a host that wants to hide its 3D panel in that case can.
+});
+```
+
+The message fires once, after the token resolves and the scene is built. It carries the resolved mint, which is useful when you embedded by `pair` and want the token identity your own page did not have.
+
+A **same-origin** host (three.ws pages embedding their own scene) can also listen for the `coin3d:ready` DOM event on the frame's window and read `frame.contentWindow.__coin3d` for the live `renderer`, `scene`, `camera` and `controls`. Neither is reachable cross-origin.
+
+---
+
+## Attribution
+
+Embed mode renders one small "3D by three.ws" link in the bottom-right corner, opening the full scene for that token in a new tab. It is the only chrome the embed adds. Leave it in place.
+
+---
+
+## Related
+
+- [Token in 3D](https://three.ws/coin3d): the standalone page.
+- [API reference: pair resolution](./api-reference.md#pair-resolution-pool-address-to-token) and [pool resolution](./api-reference.md#on-chain-pool-resolution): the two directions of the same lookup.
+- [Coin pages](./coin-pages.md): the chart terminals three.ws embeds in the other direction, on `/coin/:id` and `/launches/:mint`.
+- [Share & embed](./share-and-embed.md), [Embedding guide](./embedding.md): embedding agents and avatars rather than markets.
diff --git a/docs/nav.json b/docs/nav.json
index 9bb459b37..155a8ce6d 100644
--- a/docs/nav.json
+++ b/docs/nav.json
@@ -453,6 +453,10 @@
"label": "Coin & market pages",
"path": "coin-pages"
},
+ {
+ "label": "Token in 3D, as an embed",
+ "path": "coin3d-embed"
+ },
{
"label": "Agent Sniper",
"path": "agent-sniper"
diff --git a/docs/start-here.md b/docs/start-here.md
index 73703fc26..124cc7d44 100644
--- a/docs/start-here.md
+++ b/docs/start-here.md
@@ -147,6 +147,7 @@ Want the model in your hands rather than on a screen? [Materialize](./materializ
- **Found a coin and want to act on it now?** → [Fork a trade](./fork-trade.md): one tap on any coin across the Radar, the Live Trade Feed, the Smart Money Radar, or a ghost-copy replay opens the real pump.fun trade panel for it, pre-filled with the size being forked and signed by your own wallet. No custody, no delegated key, the same safety firewall as every other trade surface, and a `?fork=` link so a coin can travel to X or Telegram and open the panel on arrival
- **Not ready to risk money on a trader yet?** → [Ghost-copy](./ghost-copy.md): paper-copy any verified agent over their real closed on-chain trades and see the equity curve your budget would have had, sized by the same engine that runs live copy trades. No wallet, no signature, no account, and every trade your budget could not reach is listed with the reason
- **Have an audience of your own?** → [The trader card](./trader-card-embed.md): one script tag puts a trader's live on-chain record on your site, blog, link in bio or stream overlay, with a Fork button on every coin and a ghost-copy call to action, all signed by the reader's own wallet. It carries your referral code, holds no funds and asks for no key
+- **Running a chart page, a launchpad or a wallet?** → [Token in 3D, as an embed](./coin3d-embed.md): one iframe puts a live 3D view of any Solana market on your page, keyed by the mint or by the pair address your own URL already carries, with the coin's logo on a medallion, its holders as a galaxy sized by balance, a graduation ring and real swaps arriving on a tape. Free, keyless, no account, and it degrades to a data view where WebGL is unavailable
- **Want to know what just changed on the board?** → [Rivalries](./rivalries.md): every trader on the arena leaderboard is paired with the one directly above them and labelled an overtake, a debut or a standing chase, with the profit both sides settled in the last 24 hours as the reason. Worked out by rebuilding what the board said at the cutoff from the trade timestamps, so it reaches back over history already recorded and never disagrees with the leaderboard
- **Watching identities land on-chain?** → [On-chain deployments](./deployments.md): the live feed of agent identities registering on-chain as it happens, Solana Metaplex Core mints alongside ERC-8004 registrations across 15 EVM chains, with chain footprint and capability stats
- **Building against the API?** → [The developer platform](./developer-platform.md): API keys, usage metrics, signed webhooks, the one-call MCP connection test, and the public tool and skills catalogs, with a runnable example per endpoint
diff --git a/pages/coin3d.html b/pages/coin3d.html
index 11dee7120..408d3966f 100644
--- a/pages/coin3d.html
+++ b/pages/coin3d.html
@@ -177,6 +177,63 @@
opacity: 0.7;
}
+ /* Embed mode (?embed=1): the host page owns the chrome around this
+ frame, so the orbit hint goes and a single attribution link stays.
+ The locale FAB goes with it: it is the host page's decision, and it
+ lands in the same bottom-right corner as the attribution. */
+ [data-embed] .hint,
+ [data-embed] .twx-i18n-fab {
+ display: none;
+ }
+ .c3d-attrib {
+ position: fixed;
+ right: max(10px, env(safe-area-inset-right));
+ bottom: max(10px, env(safe-area-inset-bottom));
+ display: inline-flex;
+ gap: 5px;
+ align-items: baseline;
+ padding: 5px 10px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ background: var(--card);
+ backdrop-filter: blur(8px);
+ color: var(--muted);
+ font-size: 11px;
+ letter-spacing: 0.03em;
+ text-decoration: none;
+ opacity: 0.75;
+ transition:
+ opacity 160ms ease,
+ transform 160ms ease,
+ border-color 160ms ease;
+ }
+ .c3d-attrib b {
+ color: var(--fg);
+ font-weight: 600;
+ }
+ .c3d-attrib:hover,
+ .c3d-attrib:focus-visible {
+ opacity: 1;
+ transform: translateY(-1px);
+ border-color: var(--accent);
+ }
+ .c3d-attrib:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .c3d-attrib:active {
+ transform: translateY(0);
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .c3d-attrib {
+ transition: none;
+ }
+ .c3d-attrib:hover,
+ .c3d-attrib:focus-visible {
+ transform: none;
+ }
+ }
+
/* Status overlay (loading / error / empty) */
#status {
position: fixed;
diff --git a/src/coin3d/main.js b/src/coin3d/main.js
index 5b573a751..7dd7f9c9c 100644
--- a/src/coin3d/main.js
+++ b/src/coin3d/main.js
@@ -71,13 +71,55 @@ const hud = document.getElementById('hud');
const statusEl = document.getElementById('status');
// ── URL params ──────────────────────────────────────────────────────────────
+// `mint` is not const: a scene can also be addressed by `pair`, the pool account
+// a DEX terminal names its markets by, and that is resolved to a mint on boot.
const params = new URLSearchParams(location.search);
-const mint = (params.get('mint') || '').trim();
+let mint = (params.get('mint') || '').trim();
+const pair = (params.get('pair') || '').trim();
const network = params.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+// Embed mode: this page is inside someone else's frame. It drops the orbit hint
+// for the host's own chrome, keeps an attribution link back to three.ws, and
+// sends every outbound link to a new tab instead of navigating the frame.
+const embedded = params.get('embed') === '1';
+
const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
const isPlausibleMint = (s) => BASE58_RE.test(String(s || '').trim());
+// The canonical full-page URL for whatever this scene is showing, used by the
+// attribution link and by every "open on three.ws" action in embed mode.
+function fullPageUrl() {
+ return mint ? `/coin3d?mint=${encodeURIComponent(mint)}` : '/coin3d';
+}
+
+/**
+ * Resolve a pool/pair address to the mint it trades, through /api/coin/pair.
+ *
+ * DEX terminals key a market by its pool account, so an embed dropped onto a
+ * pair page has the pair and no mint. Errors are tagged so the caller can tell
+ * "this pair is not indexed anywhere" apart from "we could not ask".
+ *
+ * @param {string} pool
+ * @returns {Promise<string>} the base token mint
+ */
+async function mintForPair(pool) {
+ let res;
+ try {
+ res = await fetch(`/api/coin/pair?address=${encodeURIComponent(pool)}&network=solana`, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(12_000),
+ });
+ } catch {
+ throw Object.assign(new Error('Could not reach the market index.'), { transport: true });
+ }
+ if (res.status === 404) throw new Error('No indexed market for this pair address.');
+ if (!res.ok) throw Object.assign(new Error(`Market index returned ${res.status}.`), { transport: true });
+ const data = await res.json();
+ const address = data?.token?.address;
+ if (!isPlausibleMint(address)) throw new Error('That pair does not trade a Solana token.');
+ return address;
+}
+
// ── MCP client (JSON-RPC over the public read-only endpoint) ─────────────────
let rpcId = 0;
// Every call is bounded. An RPC provider that accepts the socket and then
@@ -1257,8 +1299,118 @@ function setPageTitle(text) {
document.title = text;
}
+// The embed's own empty state. The marketing landing (a search box and a
+// launches grid) is the wrong thing to put inside a partner's panel, so a frame
+// that arrives without a token says what it needs instead.
+function renderEmbedEmpty() {
+ setStatus(
+ 'empty',
+ 'No token selected',
+ 'Add ?mint= or ?pair= to this embed URL to render a token in 3D.',
+ { href: '/coin3d', label: 'Open three.ws' },
+ );
+}
+
+// Persistent attribution inside someone else's page: who rendered this, and a
+// way out to the full scene. Only in embed mode; the standalone page has nav.
+//
+// Called on entering embed mode and again once a token resolves, so the link
+// exists in EVERY state (loading, empty, error, populated) rather than only on
+// the path where a scene came up, and points at that token once there is one.
+function mountAttribution() {
+ const a = document.querySelector('.c3d-attrib') || document.createElement('a');
+ a.className = 'c3d-attrib';
+ a.href = fullPageUrl();
+ a.target = '_blank';
+ a.rel = 'noopener';
+ a.title = mint ? 'Open this token in 3D on three.ws' : 'Open three.ws';
+ a.innerHTML = '<span>3D by</span><b>three.ws</b>';
+ if (!a.isConnected) document.body.appendChild(a);
+}
+
+// Every link this page renders (HUD links, the oracle pill, status actions)
+// must leave the host's frame rather than navigate it to a full three.ws page.
+//
+// The anchors are written by several innerHTML renders that run at different
+// times, and some land long after first paint (the oracle pill, the trade tape),
+// so stamping the render sites would leave whichever one is added next behind.
+// `<base target="_blank">` looks like the one-line answer and is not: Chromium
+// does not apply it to these links, and a frame clicked straight through to
+// /launches with it in place. So the rule is enforced on the DOM itself.
+function keepLinksOutOfFrame() {
+ const stamp = (el) => {
+ if (!el.matches?.('a[href]:not([target])')) return;
+ el.target = '_blank';
+ el.rel = el.rel ? `${el.rel} noopener` : 'noopener';
+ };
+ const stampTree = (root) => {
+ if (root.nodeType !== 1) return;
+ stamp(root);
+ for (const a of root.querySelectorAll('a[href]:not([target])')) stamp(a);
+ };
+ stampTree(document.documentElement);
+ new MutationObserver((records) => {
+ for (const r of records) for (const node of r.addedNodes) stampTree(node);
+ }).observe(document.body, { childList: true, subtree: true });
+}
+
+// Tell the host page the scene is up. Same-origin hosts can read `__coin3d`
+// directly; a cross-origin one (the normal case for a partner embed) cannot
+// touch the frame at all, so the payload it is allowed to act on is posted out.
+// Only the public snapshot fields travel, and the host is free to ignore it.
+function announceReady(snapshot, sceneOk) {
+ const detail = { snapshot, sceneOk };
+ dispatchEvent(new CustomEvent('coin3d:ready', { detail }));
+ if (!embedded || parent === window) return;
+ parent.postMessage(
+ {
+ source: 'three.ws/coin3d',
+ type: 'coin3d:ready',
+ sceneOk,
+ token: {
+ mint,
+ name: snapshot.name || null,
+ symbol: snapshot.symbol || null,
+ },
+ },
+ '*',
+ );
+}
+
async function main() {
+ if (embedded) {
+ document.documentElement.setAttribute('data-embed', '1');
+ keepLinksOutOfFrame();
+ mountAttribution();
+ }
+
+ // A pair address is the identifier a DEX terminal has; resolve it to the
+ // mint everything downstream is keyed by before any of it runs.
+ if (!mint && pair) {
+ if (!isPlausibleMint(pair)) {
+ setStatus('error', 'Invalid pair address', `"${pair}" is not a valid Solana pool address.`, {
+ href: '/coin3d',
+ label: 'Try another token',
+ });
+ return;
+ }
+ setStatus('loading', 'Resolving market…', 'Looking up the token this pair trades.');
+ try {
+ mint = await mintForPair(pair);
+ } catch (err) {
+ setStatus('error', "Couldn't resolve this pair", err.message, {
+ href: '/coin3d',
+ label: 'Open three.ws',
+ });
+ return;
+ }
+ }
+
if (!mint) {
+ if (embedded) {
+ renderEmbedEmpty();
+ return;
+ }
renderLanding();
return;
}
@@ -1328,10 +1480,14 @@ async function main() {
// Refresh market figures periodically so price/volume stay live.
marketTimer = setInterval(() => fetchMarket(mint).then(applyMarket), 60_000);
+ // Re-point the attribution now the token is known (it was mounted at boot so
+ // the loading and error states carry it too).
+ if (embedded) mountAttribution();
+
// Expose the live scene for embedders and host pages (e.g. to react to the
// loaded snapshot or drive the camera from the outside).
window.__coin3d = { renderer, scene, camera, controls, snapshot, sceneOk };
- dispatchEvent(new CustomEvent('coin3d:ready', { detail: { snapshot, sceneOk } }));
+ announceReady(snapshot, sceneOk);
}
// When WebGL can't render, hide the dead canvas and explain it — but the HUD,
diff --git a/tests/api/coin-pair-resolver.test.js b/tests/api/coin-pair-resolver.test.js
new file mode 100644
index 000000000..66e179998
--- /dev/null
+++ b/tests/api/coin-pair-resolver.test.js
@@ -0,0 +1,134 @@
+// tokenForPool(): the pair -> token resolver behind /api/coin/pair.
+//
+// Three things are pinned here, each of them a real trap rather than an
+// implementation detail:
+//
+// 1. The dex id must NOT go through bareId(). Every token relationship id
+// GeckoTerminal returns is network-prefixed ("solana_<mint>") and the
+// module strips that prefix; the dex relationship is NOT prefixed, so
+// running it through the same helper silently turns "pump_fun" into "fun".
+// 2. The DexScreener rung has to carry the whole answer. GeckoTerminal does
+// not index a pair for its first minutes of life, which is exactly the
+// window a freshly launched coin is being looked at in, so the fallback is
+// the common path for new pairs rather than an outage-only one.
+// 3. A miss everywhere keeps GeckoTerminal's 404 verdict, so the route can
+// tell "no such market" apart from "we could not ask".
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../../api/_lib/cache.js', () => ({
+ cacheWrapLastGood: async (_key, _ttl, load) => load(),
+}));
+
+const fetchUpstream = vi.fn();
+vi.mock('../../api/_lib/upstream-fetch.js', () => ({
+ fetchUpstream: (...a) => fetchUpstream(...a),
+}));
+
+const { tokenForPool } = await import('../../api/_lib/market/ohlcv.js');
+
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const WSOL = 'So11111111111111111111111111111111111111112';
+
+const geckoOk = (body) => ({ text: async () => JSON.stringify(body) });
+const tagged = (status) => Object.assign(new Error(`GeckoTerminal ${status}`), { status });
+
+// A trimmed capture of GeckoTerminal's pool response, include= and all.
+function geckoPool({ pool, dex }) {
+ return {
+ data: {
+ id: `solana_${pool}`,
+ attributes: { address: pool, name: 'three / SOL' },
+ relationships: {
+ base_token: { data: { id: `solana_${MINT}` } },
+ quote_token: { data: { id: `solana_${WSOL}` } },
+ dex: { data: { id: dex } },
+ },
+ },
+ included: [
+ { id: `solana_${MINT}`, attributes: { name: 'three.ws', symbol: 'three' } },
+ { id: `solana_${WSOL}`, attributes: { name: 'Wrapped SOL', symbol: 'SOL' } },
+ ],
+ };
+}
+
+describe('tokenForPool', () => {
+ beforeEach(() => {
+ fetchUpstream.mockReset();
+ globalThis.fetch = vi.fn(async () => new Response('{}', { status: 404 }));
+ });
+
+ it('resolves the base token, the quote and their metadata from one call', async () => {
+ const pool = 'CnK82s8exdsK9nwqQ55kd9wcxoA22NwTchZJCBdu8LDa';
+ fetchUpstream.mockResolvedValue(geckoOk(geckoPool({ pool, dex: 'meteora' })));
+
+ const market = await tokenForPool(pool, 'solana');
+ expect(market.pool).toBe(pool);
+ expect(market.token).toEqual({ address: MINT, name: 'three.ws', symbol: 'three' });
+ expect(market.quote.symbol).toBe('SOL');
+ expect(market.pairName).toBe('three / SOL');
+ // The metadata is only there because the request asks for it.
+ expect(fetchUpstream.mock.calls[0][0]).toContain('include=base_token,quote_token');
+ });
+
+ it('keeps an underscored dex id whole', async () => {
+ const pool = 'THREEsynthetic1111111111111111111111111pair1';
+ fetchUpstream.mockResolvedValue(geckoOk(geckoPool({ pool, dex: 'pump_fun' })));
+
+ const market = await tokenForPool(pool, 'solana');
+ expect(market.dex).toBe('pump_fun');
+ });
+
+ it('falls back to DexScreener for a pair GeckoTerminal has not indexed', async () => {
+ const pool = 'THREEsynthetic1111111111111111111111111pair2';
+ fetchUpstream.mockRejectedValue(tagged(404));
+ globalThis.fetch = vi.fn(
+ async () =>
+ new Response(
+ JSON.stringify({
+ pairs: [
+ {
+ chainId: 'solana',
+ dexId: 'raydium',
+ pairAddress: pool,
+ baseToken: { address: MINT, name: 'three.ws', symbol: 'three' },
+ quoteToken: { address: WSOL, name: 'Wrapped SOL', symbol: 'SOL' },
+ },
+ ],
+ }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ ),
+ );
+
+ const market = await tokenForPool(pool, 'solana');
+ expect(market.token.address).toBe(MINT);
+ expect(market.dex).toBe('raydium');
+ expect(market.pairName).toBe('three / SOL');
+ expect(globalThis.fetch.mock.calls[0][0]).toContain('/latest/dex/pairs/solana/');
+ });
+
+ it('asks DexScreener for its own chain slug, not GeckoTerminal’s', async () => {
+ // "polygon_pos" is a GeckoTerminal id DexScreener has never heard of. An
+ // identity fallback made every rung-2 lookup on this chain a silent miss.
+ const pool = '0xabcdef0123456789abcdef0123456789abcdef01';
+ fetchUpstream.mockRejectedValue(tagged(404));
+ globalThis.fetch = vi.fn(async () => new Response('{}', { status: 404 }));
+
+ await expect(tokenForPool(pool, 'polygon_pos')).rejects.toThrow();
+ expect(globalThis.fetch.mock.calls[0][0]).toContain('/latest/dex/pairs/polygon/');
+ });
+
+ it('keeps the 404 verdict when no source knows the pool', async () => {
+ const pool = 'THREEsynthetic1111111111111111111111111pair3';
+ fetchUpstream.mockRejectedValue(tagged(404));
+
+ await expect(tokenForPool(pool, 'solana')).rejects.toMatchObject({ status: 404 });
+ });
+
+ it('surfaces an outage as 502 rather than pretending the pool is unknown', async () => {
+ const pool = 'THREEsynthetic1111111111111111111111111pair4';
+ fetchUpstream.mockRejectedValue(tagged(503));
+
+ await expect(tokenForPool(pool, 'solana')).rejects.toMatchObject({ status: 502 });
+ });
+});
diff --git a/tests/api/coin-pair.test.js b/tests/api/coin-pair.test.js
new file mode 100644
index 000000000..f6741b895
--- /dev/null
+++ b/tests/api/coin-pair.test.js
@@ -0,0 +1,146 @@
+// /api/coin/pair: the pool-address -> token bridge, and its status contract.
+//
+// This route exists so a surface that names a market by its PAIR address (every
+// DEX terminal does) can address a three.ws scene. The status mapping is the
+// whole contract for an embed: a pair nothing has indexed is a 404 the embed
+// renders as "we can't draw this market yet", a throttle is a 429 it retries,
+// and anything else is a 502. An embed that got a 500 would sit on a dead frame
+// inside somebody else's page, which is the failure this pins shut.
+//
+// The validation cases matter for the same reason: the address arrives from a
+// third-party page's URL, so a malformed one is rejected at the boundary and
+// never reaches upstream.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: () => {} }));
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { marketDataIp: async () => ({ success: true }) },
+ clientIp: () => '203.0.113.1',
+}));
+
+// Re-created per test rather than cleared: clearing a vitest mock detaches the
+// rejection tracking on its promise result, so a rejected lane surfaces as an
+// unhandled rejection even though the handler awaited and caught it.
+let tokenForPool = vi.fn();
+vi.mock('../../api/_lib/market/ohlcv.js', () => ({
+ tokenForPool: (...a) => tokenForPool(...a),
+}));
+
+const pair = (await import('../../api/coin/pair.js')).default;
+
+// The real three / SOL pool, the one DEXTools keys $THREE under.
+const THREE_PAIR = 'CnK82s8exdsK9nwqQ55kd9wcxoA22NwTchZJCBdu8LDa';
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const EVM_PAIR = '0x1234567890abcdef1234567890abcdef12345678';
+
+const market = {
+ pool: THREE_PAIR,
+ token: { address: THREE_MINT, name: 'three.ws', symbol: 'three' },
+ quote: { address: 'So11111111111111111111111111111111111111112', name: 'Wrapped SOL', symbol: 'SOL' },
+ dex: 'meteora',
+ pairName: 'three / SOL',
+};
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ setHeader(k, v) {
+ this._h[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this._h[k.toLowerCase()];
+ },
+ end(body) {
+ this._body = body;
+ },
+ };
+}
+async function call(query) {
+ const res = makeRes();
+ await pair({ url: `/api/coin/pair?${query}`, method: 'GET', headers: {} }, res);
+ return { res, body: JSON.parse(res._body) };
+}
+
+describe('/api/coin/pair', () => {
+ beforeEach(() => {
+ tokenForPool = vi.fn();
+ });
+
+ it('resolves a Solana pool address to the token it trades', async () => {
+ tokenForPool.mockResolvedValue(market);
+ const { res, body } = await call(`address=${THREE_PAIR}&network=solana`);
+ expect(res.statusCode).toBe(200);
+ expect(body.pair).toBe(THREE_PAIR);
+ expect(body.token.address).toBe(THREE_MINT);
+ expect(body.token.symbol).toBe('three');
+ expect(body.quote.symbol).toBe('SOL');
+ expect(body.dex).toBe('meteora');
+ // `pool` is renamed to `pair` on the way out: callers of this route hold a
+ // pair address, and answering with a second name for it invites confusion
+ // with /api/coin/pool, which means the opposite direction.
+ expect(body).not.toHaveProperty('pool');
+ });
+
+ it('is CORS-open and cacheable, because partner pages call it from the browser', async () => {
+ tokenForPool.mockResolvedValue(market);
+ const { res } = await call(`address=${THREE_PAIR}&network=solana`);
+ expect(res.getHeader('access-control-allow-origin')).toBe('*');
+ expect(res.getHeader('cache-control')).toContain('s-maxage=300');
+ });
+
+ it('defaults to Solana, the home chain', async () => {
+ tokenForPool.mockResolvedValue(market);
+ const { res } = await call(`address=${THREE_PAIR}`);
+ expect(res.statusCode).toBe(200);
+ expect(tokenForPool).toHaveBeenCalledWith(THREE_PAIR, 'solana');
+ });
+
+ it('accepts an EVM pool address on an EVM network', async () => {
+ tokenForPool.mockResolvedValue({ ...market, pool: EVM_PAIR });
+ const { res } = await call(`address=${EVM_PAIR}&network=base`);
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('rejects an address that is the wrong shape for the network', async () => {
+ const evmOnSolana = await call(`address=${EVM_PAIR}&network=solana`);
+ expect(evmOnSolana.res.statusCode).toBe(400);
+ expect(evmOnSolana.body.error).toBe('bad_address');
+
+ const solOnBase = await call(`address=${THREE_PAIR}&network=base`);
+ expect(solOnBase.res.statusCode).toBe(400);
+ expect(tokenForPool).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unsupported network', async () => {
+ const { res, body } = await call(`address=${THREE_PAIR}&network=dogechain`);
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('bad_network');
+ expect(tokenForPool).not.toHaveBeenCalled();
+ });
+
+ it('answers 404 for a pool no source has indexed', async () => {
+ tokenForPool.mockRejectedValue(Object.assign(new Error('nope'), { status: 404 }));
+ const { res, body } = await call(`address=${THREE_PAIR}&network=solana`);
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('no_pair');
+ });
+
+ it('passes a throttle through as 429 so the caller can retry', async () => {
+ tokenForPool.mockRejectedValue(Object.assign(new Error('slow down'), { status: 429 }));
+ const { res, body } = await call(`address=${THREE_PAIR}&network=solana`);
+ expect(res.statusCode).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ });
+
+ it('maps an untagged failure to 502, never a 500', async () => {
+ // AbortSignal.timeout rejects with a DOMException carrying no `status`.
+ tokenForPool.mockRejectedValue(new Error('socket hang up'));
+ const { res, body } = await call(`address=${THREE_PAIR}&network=solana`);
+ expect(res.statusCode).toBe(502);
+ expect(body.error).toBe('upstream_error');
+ });
+});
diff --git a/vercel.json b/vercel.json
index f7aea978a..c72b3080a 100644
--- a/vercel.json
+++ b/vercel.json
@@ -2168,10 +2168,18 @@
},
{
"src": "/coin3d",
+ "headers": {
+ "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://ajax.googleapis.com https://3d-agent.vercel.app https://three.ws; worker-src 'self' blob:; report-uri /api/client-errors",
+ "cross-origin-resource-policy": "cross-origin"
+ },
"dest": "/coin3d.html"
},
{
"src": "/coin3d/",
+ "headers": {
+ "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://ajax.googleapis.com https://3d-agent.vercel.app https://three.ws; worker-src 'self' blob:; report-uri /api/client-errors",
+ "cross-origin-resource-policy": "cross-origin"
+ },
"dest": "/coin3d.html"
},
{