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.

Coin chart: switchable CoinGecko / TradingView / DexScreener / GeckoTerminal

nirholas6f0ae4143e98
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 778031042..4a9cff65e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **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]`
+- **Switch any coin chart between CoinGecko, TradingView, DexScreener, and GeckoTerminal** — The chart on every /coin page now has a source switcher. Start on the fast native CoinGecko line chart, then flip to TradingView's advanced candlesticks, or to the DexScreener or GeckoTerminal on-chain terminal for the token's live DEX pair. Each option only appears when it can actually chart that coin, your pick is remembered across coins and visits, and every view follows the site theme. (`/coin/bitcoin`) `[feature, 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/STRUCTURE.md b/STRUCTURE.md
index 074834a62..769621c0e 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -107,7 +107,7 @@ bottom.
| Autonomous trading experiment | policy [scripts/trading-experiment-setup.mjs](scripts/trading-experiment-setup.mjs), laddered exit [workers/agent-sniper/exit-logic.js](workers/agent-sniper/exit-logic.js) (`decideLadderedExit`), no-Mayhem gate [workers/agent-sniper/mayhem-gate.js](workers/agent-sniper/mayhem-gate.js), journal [workers/agent-sniper/journal.js](workers/agent-sniper/journal.js) → [api/sniper/journal.js](api/sniper/journal.js) | In-repo | One agent, ~10 SOL, newer pump.fun launches ($10k–$100k mcap, no Mayhem). Take-initials-at-2× laddered exit keeps a moon bag (never a 100% exit up), hard stop-loss underneath. Every decision journaled with its reasoning. UI-funded, simulate-first. See [docs/trading-experiment.md](docs/trading-experiment.md) |
| Trading Copilot (conversational) | client [src/agent-copilot.js](src/agent-copilot.js), hub tab [src/agent-wallet-hub/tabs/copilot.js](src/agent-wallet-hub/tabs/copilot.js), server [api/agents/copilot.js](api/agents/copilot.js) `→ POST /api/agents/:id/copilot` (SSE) | In-repo | Owner-only chat over an agent's Solana wallet: text/voice in, markdown replies, live **data cards** (portfolio, firewall, quote, smart-money, intel) and **confirm-before-execute** trade/limits cards. Read-only tools run server-side; state-changing intents return as proposals the browser re-quotes and runs through the existing spend guards + firewall + custody audit. Slash commands, copy/regenerate, localStorage persistence. See [docs/trading-copilot.md](docs/trading-copilot.md) |
| Real-funds risk acknowledgment | gate [public/risk-ack.js](public/risk-ack.js) `→ /legal/risk`, app wrapper [src/shared/risk-ack.js](src/shared/risk-ack.js), record endpoint [api/legal/risk-ack.js](api/legal/risk-ack.js), disclosure [public/legal/risk.html](public/legal/risk.html) | In-repo | Versioned, once-per-browser acceptance dialog every money-committing surface awaits before executing (trade, snipe, withdraw, swap, launch, x402, onramp — devnet exempt). Acceptances persist in `audit_log` (`risk-ack-accept`). 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, 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, 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 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) |
| 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) |
diff --git a/api/coin/pool.js b/api/coin/pool.js
new file mode 100644
index 000000000..8b14699c7
--- /dev/null
+++ b/api/coin/pool.js
@@ -0,0 +1,57 @@
+// GET /api/coin/pool?address=<token-address>&network=<geckoterminal-network>
+// ---------------------------------------------------------------------------
+// Resolves the most-liquid on-chain pool for a token on a GeckoTerminal-indexed
+// network, so the /coin/:id page can mount the GeckoTerminal chart embed (which
+// is keyed by pool address, not by token). Thin wrapper over the shared keyless
+// topPoolForToken() helper — real data, cached, never fabricated. Response is
+// cached 60s in-process + 5min at the CDN so repeat views and the CDN shield the
+// upstream free-tier rate limit.
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { topPoolForToken } from '../_lib/market/ohlcv.js';
+
+// The GeckoTerminal network ids the /coin page's CHAIN_MAP can emit. Solana is
+// the home chain; the rest are the majors both DEX terminals index.
+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');
+ }
+ // Reject at the boundary so a malformed address 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 token address for the network');
+ }
+
+ try {
+ const pool = await topPoolForToken(address, network);
+ return json(
+ res,
+ 200,
+ { network, address, pool },
+ { 'cache-control': 'public, max-age=60, s-maxage=300, stale-while-revalidate=600' },
+ );
+ } catch (err) {
+ // A coin with no indexed pool is a normal outcome (404), not an error;
+ // throttles and outages surface their true status so the client can
+ // fall back to the "open on GeckoTerminal" link without a false chart.
+ if (err.status === 404) return error(res, 404, 'no_pool', 'no on-chain pool found for this token');
+ if (err.status === 429) return error(res, 429, 'rate_limited', 'pool source is throttled, retry shortly');
+ return error(res, 502, 'upstream_error', 'pool source is temporarily unavailable');
+ }
+});
diff --git a/data/changelog.json b/data/changelog.json
index cefdf76ba..71a9171b3 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": "Switch any coin chart between CoinGecko, TradingView, DexScreener, and GeckoTerminal",
+ "summary": "The chart on every /coin page now has a source switcher. Start on the fast native CoinGecko line chart, then flip to TradingView's advanced candlesticks, or to the DexScreener or GeckoTerminal on-chain terminal for the token's live DEX pair. Each option only appears when it can actually chart that coin, your pick is remembered across coins and visits, and every view follows the site theme.",
+ "tags": [
+ "feature",
+ "improvement"
+ ],
+ "link": "/coin/bitcoin"
+ },
{
"date": "2026-07-19",
"title": "Coin Radar's live trade data restored, now read straight from the chain",
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 558bb23ee..dc5a269c6 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -2804,6 +2804,24 @@ beyond).
---
+### On-chain pool resolution
+
+```
+GET /api/coin/pool?address=<token-address>&network=<gecko-network>
+```
+
+Resolves a token's most-liquid on-chain pool, so the coin page can mount the
+GeckoTerminal chart embed (which is keyed by pool address, not token). `network`
+is a GeckoTerminal network id (`solana`, `eth`, `base`, `bsc`, `polygon_pos`,
+`arbitrum`, `optimism`, `avax`); `address` is the token mint (Solana) or
+contract (EVM), validated per-network at the boundary. Returns
+`{ "network", "address", "pool" }`. A token with no indexed pool returns `404`
+(`no_pool`); upstream throttles surface as `429`, outages as `502` — the client
+falls back to an "open on GeckoTerminal" link rather than a fabricated chart.
+Cached 60s in-process + 5min at the CDN.
+
+---
+
### Markets table / coin search
```
diff --git a/docs/coin-pages.md b/docs/coin-pages.md
index e77021892..2e6641b04 100644
--- a/docs/coin-pages.md
+++ b/docs/coin-pages.md
@@ -38,8 +38,21 @@ editorial serif headings, hairline borders, mono numerals, light/dark themes.
- **Header** — icon, name, symbol, market-cap-rank badge, live price, and
24h / 7d / 30d change chips, plus the coin's categories.
-- **Interactive chart** — SVG line chart across 24H / 7D / 30D / 90D / 1Y with
- a crosshair tooltip showing exact price and time.
+- **Interactive chart with a source switcher** — the default is a lightweight
+ native SVG line chart across 24H / 7D / 30D / 90D / 1Y (data by CoinGecko)
+ with a crosshair tooltip showing exact price and time. A pill switcher next
+ to the time ranges swaps in a full third-party terminal, and each option only
+ appears when it can actually chart the coin:
+ - **CoinGecko** — the native line chart (always available).
+ - **TradingView** — the advanced candlestick widget (indicators, drawing
+ tools), for any coin with a ticker symbol.
+ - **DexScreener** — the on-chain terminal keyed by the token's contract
+ address, for coins with a Solana mint or a supported EVM contract.
+ - **GeckoTerminal** — the on-chain terminal keyed by the token's most-liquid
+ pool, resolved server-side via `GET /api/coin/pool` (below).
+
+ The picked source is remembered across coins and visits (localStorage
+ `tws_coin_chart_source`), and the embeds follow the site's light/dark theme.
- **Price performance matrix** — colored 1h / 24h / 7d / 14d / 30d / 60d /
200d / 1y change cells, so the whole return curve is legible at a glance.
- **Market stats** — market cap, 24h volume, circulating/total supply,
diff --git a/pages/coin.html b/pages/coin.html
index 8b8d8afb6..21d97bb70 100644
--- a/pages/coin.html
+++ b/pages/coin.html
@@ -49,6 +49,8 @@
gap: 0.5rem 0.75rem;
}
.cv-chart-modes {
+ display: flex;
+ flex-wrap: wrap;
border: 1px solid var(--cv-border);
border-radius: var(--cv-radius);
background: var(--cv-surface-2);
diff --git a/public/changelog.json b/public/changelog.json
index b892e6c06..ddd957db7 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-19T07:05:14.412Z",
+ "generated_at": "2026-07-19T07:06:32.397Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -93,6 +93,17 @@
"improvement"
]
},
+ {
+ "date": "2026-07-19",
+ "type": "update",
+ "title": "Switch any coin chart between CoinGecko, TradingView, DexScreener, and GeckoTerminal",
+ "summary": "The chart on every /coin page now has a source switcher. Start on the fast native CoinGecko line chart, then flip to TradingView's advanced candlesticks, or to the DexScreener or GeckoTerminal on-chain terminal for the token's live DEX pair. Each option only appears when it can actually chart that coin, your pick is remembered across coins and visits, and every view follows the site theme.",
+ "link": "/coin/bitcoin",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-07-19",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 487124f4b..cab355e8d 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -70,6 +70,14 @@
<category>fix</category>
<description>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.</description>
</item>
+ <item>
+ <title>Switch any coin chart between CoinGecko, TradingView, DexScreener, and GeckoTerminal</title>
+ <link>https://three.ws/coin/bitcoin</link>
+ <guid isPermaLink="false">2026-07-19:Switch any coin chart between CoinGecko, TradingView, DexScreener, and GeckoTerminal</guid>
+ <pubDate>Sun, 19 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The chart on every /coin page now has a source switcher. Start on the fast native CoinGecko line chart, then flip to TradingView's advanced candlesticks, or to the DexScreener or GeckoTerminal on-chain terminal for the token's live DEX pair. Each option only appears when it can actually chart that coin, your pick is remembered across coins and visits, and every view follows the site theme.</description>
+ </item>
<item>
<title>The assistant widget ships as an npm package and an MCP server</title>
<link>https://three.ws/docs/assistant-widget</link>
diff --git a/src/coin-page.js b/src/coin-page.js
index d3ba70e46..98839ff79 100644
--- a/src/coin-page.js
+++ b/src/coin-page.js
@@ -112,23 +112,32 @@ function renderHead(coin) {
// ── Chart ───────────────────────────────────────────────────────────────────
-// The chart panel offers two sources: the native SVG line chart (default, zero
-// third-party weight) and a full candlestick "advanced" chart, lazy-mounted
-// only when the user switches to it. The advanced provider is chosen per coin —
-// TradingView for exchange-listed coins, DexScreener for Solana DEX tokens
-// TradingView doesn't carry — so "advanced" never lands on an unchartable
-// symbol. The simple/advanced choice persists across coins and visits.
-const CHART_MODE_KEY = 'tws_coin_chart_mode';
-
-function storedChartMode() {
- try {
- return localStorage.getItem(CHART_MODE_KEY) === 'advanced' ? 'advanced' : 'simple';
- } catch {
- return 'simple';
- }
-}
-
-const chartState = { days: 30, series: [], loading: true, error: null, mode: storedChartMode() };
+// The chart panel is a multi-source switcher. CoinGecko powers the default,
+// zero-dependency native line chart (with the time-range selector); the other
+// sources lazy-mount a full third-party terminal in an iframe only when picked:
+// • TradingView — advanced candlestick widget, for coins with a ticker.
+// • DexScreener — on-chain terminal keyed by the token address (all chains).
+// • GeckoTerminal — on-chain terminal keyed by the token's most-liquid pool.
+// Each source is offered only when it can actually render for the coin, so the
+// switcher never lands on a dead chart. The picked source persists across coins.
+const CHART_SOURCE_KEY = 'tws_coin_chart_source';
+
+// CoinGecko asset-platform id → the chain slug DexScreener and the network id
+// GeckoTerminal use for the same chain. Solana leads (home chain); the rest are
+// the majors both terminals index. A platform without a mapping is not offered
+// an on-chain chart.
+const CHAIN_MAP = {
+ solana: { ds: 'solana', gt: 'solana', evm: false },
+ ethereum: { ds: 'ethereum', gt: 'eth', evm: true },
+ base: { ds: 'base', gt: 'base', evm: true },
+ 'binance-smart-chain': { ds: 'bsc', gt: 'bsc', evm: true },
+ 'polygon-pos': { ds: 'polygon', gt: 'polygon_pos', evm: true },
+ 'arbitrum-one': { ds: 'arbitrum', gt: 'arbitrum', evm: true },
+ 'optimistic-ethereum': { ds: 'optimism', gt: 'optimism', evm: true },
+ avalanche: { ds: 'avalanche', gt: 'avax', evm: true },
+};
+
+const EVM_RE = /^0x[0-9a-fA-F]{40}$/;
// TradingView resolves an unprefixed BASE+QUOTE pair (e.g. BTCUSD) to its
// top-liquidity listing, so no exchange mapping table is needed.
@@ -137,38 +146,87 @@ function tvSymbol(coin) {
return sym && /^[A-Z0-9]{1,15}$/.test(sym) ? `${sym}USD` : null;
}
-// Pick the advanced-chart provider best suited to this coin. A Solana DEX token
-// (has a mint, isn't a top-ranked major) charts on DexScreener's terminal keyed
-// by the mint — it resolves the most-liquid pair itself and covers coins that
-// never reach a TradingView-listed exchange. Everything with a real ticker
-// charts on TradingView. Returns null when neither fits (no chartable identity).
-function advancedProvider(coin) {
- const raw = coin.platforms?.solana;
- const mint = raw && MINT_RE.test(raw) ? raw : null;
- const symbol = tvSymbol(coin);
- const major = coin.rank != null && coin.rank <= 300;
- if (mint && !major) return { kind: 'dexscreener', mint, label: 'DexScreener' };
- if (symbol) return { kind: 'tradingview', symbol, label: 'TradingView' };
- if (mint) return { kind: 'dexscreener', mint, label: 'DexScreener' };
+// The coin's on-chain identity for the DEX terminals: a contract address plus
+// the per-provider chain slugs. Solana is preferred when present (home chain);
+// otherwise the first platform whose address is well-formed for a mapped chain.
+function onchainRef(coin) {
+ const entries = Object.entries(coin.platforms || {});
+ const ordered = entries.sort(([a], [b]) => (a === 'solana' ? -1 : b === 'solana' ? 1 : 0));
+ for (const [platform, address] of ordered) {
+ const m = CHAIN_MAP[platform];
+ if (!m || typeof address !== 'string') continue;
+ const addr = address.trim();
+ const valid = m.evm ? EVM_RE.test(addr) : MINT_RE.test(addr);
+ if (valid) return { platform, address: addr, ds: m.ds, gt: m.gt };
+ }
return null;
}
+// The switchable chart sources, in tab order. `available` gates whether a tab
+// shows for a given coin; `kind` selects the render path in renderChart.
+const CHART_SOURCES = [
+ { id: 'coingecko', label: 'CoinGecko', kind: 'native', available: () => true },
+ { id: 'tradingview', label: 'TradingView', kind: 'tradingview', available: (c) => tvSymbol(c) != null },
+ { id: 'dexscreener', label: 'DexScreener', kind: 'dexscreener', available: (c) => onchainRef(c) != null },
+ { id: 'geckoterminal', label: 'GeckoTerminal', kind: 'geckoterminal', available: (c) => onchainRef(c) != null },
+];
+
+function availableSources(coin) {
+ return CHART_SOURCES.filter((s) => s.available(coin));
+}
+
+function storedChartSource() {
+ try {
+ return localStorage.getItem(CHART_SOURCE_KEY) || 'coingecko';
+ } catch {
+ return 'coingecko';
+ }
+}
+
+const chartState = {
+ days: 30,
+ series: [],
+ loading: true,
+ error: null,
+ source: storedChartSource(),
+ // GeckoTerminal pool resolution is async, resolved once per coin.
+ gtPool: null,
+ gtState: 'idle', // idle | loading | ready | error
+};
+
+// The source actually rendered for this coin: the stored preference when it's
+// available here, else the CoinGecko native chart (always available).
+function resolvedSource(coin) {
+ const avail = availableSources(coin);
+ return avail.find((s) => s.id === chartState.source) || avail[0];
+}
+
function chartTheme() {
return document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark';
}
let themeObserver = null;
-// Both embeds bake the theme in at mount time, so a live theme switch has to
-// re-mount. Registered once; only fires while the advanced chart is showing.
+// The iframe terminals bake the theme in at mount time, so a live theme switch
+// re-renders whichever embed is showing. Registered once.
function ensureThemeRemount(coin) {
if (themeObserver) return;
themeObserver = new MutationObserver(() => {
- if (chartState.mode === 'advanced') renderChart(coin);
+ if (resolvedSource(coin).kind !== 'native') renderChart(coin);
});
themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
}
+function iframeEl(src, title) {
+ const iframe = document.createElement('iframe');
+ iframe.src = src;
+ iframe.title = title;
+ iframe.loading = 'lazy';
+ iframe.allow = 'clipboard-write';
+ iframe.style.cssText = 'width:100%;height:100%;border:0;display:block';
+ return iframe;
+}
+
function mountTradingView(host, symbol) {
const container = document.createElement('div');
container.className = 'tradingview-widget-container';
@@ -197,7 +255,7 @@ function mountTradingView(host, symbol) {
host.replaceChildren(container);
}
-function mountDexScreener(host, mint) {
+function mountDexScreener(host, ref) {
const t = chartTheme();
const p = new URLSearchParams({
embed: '1',
@@ -208,35 +266,56 @@ function mountDexScreener(host, mint) {
interval: '15',
info: '0',
});
- const iframe = document.createElement('iframe');
- iframe.src = `https://dexscreener.com/solana/${encodeURIComponent(mint)}?${p}`;
- iframe.title = 'DexScreener chart';
- iframe.loading = 'lazy';
- iframe.allow = 'clipboard-write';
- iframe.style.cssText = 'width:100%;height:100%;border:0;display:block';
- host.replaceChildren(iframe);
+ host.replaceChildren(
+ iframeEl(`https://dexscreener.com/${ref.ds}/${encodeURIComponent(ref.address)}?${p}`, 'DexScreener chart'),
+ );
}
-function mountAdvanced(coin) {
- const host = $('cv-adv');
- const prov = advancedProvider(coin);
- if (!host || !prov) return;
- if (prov.kind === 'tradingview') mountTradingView(host, prov.symbol);
- else mountDexScreener(host, prov.mint);
- ensureThemeRemount(coin);
+function mountGeckoTerminal(host, ref, pool) {
+ const p = new URLSearchParams({
+ embed: '1',
+ info: '0',
+ swaps: '0',
+ grayscale: '0',
+ light_chart: chartTheme() === 'light' ? '1' : '0',
+ });
+ host.replaceChildren(
+ iframeEl(`https://www.geckoterminal.com/${ref.gt}/pools/${encodeURIComponent(pool)}?${p}`, 'GeckoTerminal chart'),
+ );
+}
+
+// GeckoTerminal embeds are keyed by pool, not token, so resolve the most-liquid
+// pool once via our cached proxy, then mount. State drives the loading/error UI.
+async function loadGtPool(coin, ref) {
+ if (chartState.gtState === 'loading') return;
+ chartState.gtState = 'loading';
+ renderChart(coin);
+ try {
+ const { pool } = await getJson(
+ `/api/coin/pool?address=${encodeURIComponent(ref.address)}&network=${encodeURIComponent(ref.gt)}`,
+ );
+ if (!pool) throw new Error('no pool');
+ chartState.gtPool = pool;
+ chartState.gtState = 'ready';
+ } catch {
+ chartState.gtPool = null;
+ chartState.gtState = 'error';
+ }
+ renderChart(coin);
}
-function setChartMode(coin, mode) {
- if (mode === chartState.mode) return;
- chartState.mode = mode;
+function setChartSource(coin, id) {
+ if (id === chartState.source) return;
+ chartState.source = id;
try {
- localStorage.setItem(CHART_MODE_KEY, mode);
+ localStorage.setItem(CHART_SOURCE_KEY, id);
} catch {
- // Private browsing: the toggle still works for this page view.
+ // Private browsing: the switch still works for this page view.
}
renderChart(coin);
- // Entering native mode with no data yet loads it on demand.
- if (mode === 'simple' && !chartState.series.length && !chartState.loading) loadChart(coin);
+ const src = resolvedSource(coin);
+ // Entering the native chart with no data yet loads it on demand.
+ if (src.kind === 'native' && !chartState.series.length && !chartState.loading) loadChart(coin);
}
const CHART_W = 800;
@@ -271,74 +350,32 @@ function chartGeometry(series) {
function renderChart(coin) {
const el = $('cv-chart');
- const { days, series, loading, error, mode } = chartState;
- const prov = advancedProvider(coin);
- const adv = mode === 'advanced' && prov != null;
+ const { days, series, loading, error } = chartState;
+ const sources = availableSources(coin);
+ const active = resolvedSource(coin);
+ const native = active.kind === 'native';
- const rangeBtns = adv
- ? ''
- : TIME_RANGES.map(
+ const rangeBtns = native
+ ? TIME_RANGES.map(
(r) =>
`<button type="button" class="cv-range-btn" data-days="${r.days}" aria-pressed="${r.days === days}">${r.label}</button>`,
- ).join('');
-
- const modeBtns = prov
- ? `<div class="cv-ranges cv-chart-modes" role="group" aria-label="Chart source">
- <button type="button" class="cv-range-btn" data-mode="simple" aria-pressed="${!adv}">Line</button>
- <button type="button" class="cv-range-btn" data-mode="advanced" aria-pressed="${adv}">${esc(prov.label)}</button>
- </div>`
+ ).join('')
: '';
- let body;
- if (adv) {
- const credit =
- prov.kind === 'tradingview'
- ? `<a href="https://www.tradingview.com/symbols/${esc(prov.symbol)}/" target="_blank" rel="noopener nofollow noreferrer">${esc(coin.symbol || coin.name)} chart by TradingView ↗</a>`
- : `<a href="https://dexscreener.com/solana/${esc(prov.mint)}" target="_blank" rel="noopener nofollow noreferrer">Open in DexScreener ↗</a>`;
- body = `
- <div class="cv-adv-wrap" id="cv-adv" aria-label="${esc(prov.label)} chart for ${esc(coin.name)}"></div>
- <p class="cv-tv-credit">${credit}</p>`;
- } else if (loading) {
- body = '<div class="cv-chart-state"><span class="cv-spinner" aria-hidden="true"></span>Loading chart…</div>';
- } else if (error || series.length < 2) {
- body = '<div class="cv-chart-state">Chart data unavailable</div>';
- } else {
- const g = chartGeometry(series);
- const color = g.up ? 'var(--cv-chart-green)' : 'var(--cv-chart-red)';
- const steps = 4;
- const h = CHART_H - PAD.top - PAD.bottom;
- const yLabels = Array.from({ length: steps + 1 }, (_, i) => {
- const price = g.min + (g.range * i) / steps;
- const y = PAD.top + h - (i / steps) * h;
- return `<g><line x1="${PAD.left}" y1="${y}" x2="${CHART_W - PAD.right}" y2="${y}" stroke="var(--cv-border)" stroke-width="0.5" stroke-dasharray="4 4" opacity="0.5"/><text x="${CHART_W - PAD.right + 8}" y="${y + 4}" font-size="10" fill="var(--cv-text-3)">${esc(formatPrice(price))}</text></g>`;
- }).join('');
- body = `
- <div class="cv-chart-area">
- <svg viewBox="0 0 ${CHART_W} ${CHART_H}" role="img"
- aria-label="Price chart for ${esc(coin.name)} over ${days} day${days > 1 ? 's' : ''}. Change: ${esc(formatPercent(g.changePct))}">
- <defs>
- <linearGradient id="cv-grad" x1="0" x2="0" y1="0" y2="1">
- <stop offset="0%" stop-color="${color}" stop-opacity="0.2"/>
- <stop offset="100%" stop-color="${color}" stop-opacity="0.02"/>
- </linearGradient>
- </defs>
- ${yLabels}
- <path d="${g.area}" fill="url(#cv-grad)"/>
- <path d="${g.line}" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
- <g id="cv-crosshair" hidden>
- <line id="cv-cross-line" x1="0" y1="${PAD.top}" x2="0" y2="${CHART_H - PAD.bottom}" stroke="var(--cv-text-3)" stroke-width="0.5" stroke-dasharray="3 3"/>
- <circle id="cv-cross-dot" r="4" fill="${color}" stroke="var(--cv-surface)" stroke-width="2"/>
- </g>
- </svg>
- <div class="cv-chart-tip" id="cv-tip" hidden>
- <p class="p cv-mono" id="cv-tip-price"></p>
- <p class="d" id="cv-tip-date"></p>
- </div>
- </div>`;
- }
+ const sourceBtns =
+ sources.length > 1
+ ? `<div class="cv-ranges cv-chart-modes" role="group" aria-label="Chart source">${sources
+ .map(
+ (s) =>
+ `<button type="button" class="cv-range-btn" data-source="${s.id}" aria-pressed="${s.id === active.id}">${esc(s.label)}</button>`,
+ )
+ .join('')}</div>`
+ : '';
+
+ const body = native ? nativeChartBody(coin) : embedChartBody(coin, active);
const pct =
- !adv && !loading && !error && series.length >= 2
+ native && !loading && !error && series.length >= 2
? (() => {
const g = chartGeometry(series);
return `<span class="pct ${g.up ? 'cv-up' : 'cv-down'} cv-mono">${esc(formatPercent(g.changePct))}</span>`;
@@ -351,7 +388,7 @@ function renderChart(coin) {
<div class="left"><span class="title">Price Chart</span>${pct}</div>
<div class="cv-chart-controls">
${rangeBtns ? `<div class="cv-ranges" role="group" aria-label="Chart time range">${rangeBtns}</div>` : ''}
- ${modeBtns}
+ ${sourceBtns}
</div>
</div>
${body}
@@ -365,12 +402,106 @@ function renderChart(coin) {
loadChart(coin);
});
});
- el.querySelectorAll('.cv-range-btn[data-mode]').forEach((btn) => {
- btn.addEventListener('click', () => setChartMode(coin, btn.dataset.mode));
+ el.querySelectorAll('.cv-range-btn[data-source]').forEach((btn) => {
+ btn.addEventListener('click', () => setChartSource(coin, btn.dataset.source));
});
- if (adv) mountAdvanced(coin);
- else wireChartPointer();
+ if (native) wireChartPointer();
+ else mountActiveEmbed(coin, active);
+}
+
+// The native (CoinGecko) line chart body: loading, error, or the SVG series.
+function nativeChartBody(coin) {
+ const { days, series, loading, error } = chartState;
+ if (loading) {
+ return '<div class="cv-chart-state"><span class="cv-spinner" aria-hidden="true"></span>Loading chart…</div>';
+ }
+ if (error || series.length < 2) {
+ return '<div class="cv-chart-state">Chart data unavailable</div>';
+ }
+ const g = chartGeometry(series);
+ const color = g.up ? 'var(--cv-chart-green)' : 'var(--cv-chart-red)';
+ const steps = 4;
+ const h = CHART_H - PAD.top - PAD.bottom;
+ const yLabels = Array.from({ length: steps + 1 }, (_, i) => {
+ const price = g.min + (g.range * i) / steps;
+ const y = PAD.top + h - (i / steps) * h;
+ return `<g><line x1="${PAD.left}" y1="${y}" x2="${CHART_W - PAD.right}" y2="${y}" stroke="var(--cv-border)" stroke-width="0.5" stroke-dasharray="4 4" opacity="0.5"/><text x="${CHART_W - PAD.right + 8}" y="${y + 4}" font-size="10" fill="var(--cv-text-3)">${esc(formatPrice(price))}</text></g>`;
+ }).join('');
+ return `
+ <div class="cv-chart-area">
+ <svg viewBox="0 0 ${CHART_W} ${CHART_H}" role="img"
+ aria-label="Price chart for ${esc(coin.name)} over ${days} day${days > 1 ? 's' : ''}. Change: ${esc(formatPercent(g.changePct))}">
+ <defs>
+ <linearGradient id="cv-grad" x1="0" x2="0" y1="0" y2="1">
+ <stop offset="0%" stop-color="${color}" stop-opacity="0.2"/>
+ <stop offset="100%" stop-color="${color}" stop-opacity="0.02"/>
+ </linearGradient>
+ </defs>
+ ${yLabels}
+ <path d="${g.area}" fill="url(#cv-grad)"/>
+ <path d="${g.line}" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
+ <g id="cv-crosshair" hidden>
+ <line id="cv-cross-line" x1="0" y1="${PAD.top}" x2="0" y2="${CHART_H - PAD.bottom}" stroke="var(--cv-text-3)" stroke-width="0.5" stroke-dasharray="3 3"/>
+ <circle id="cv-cross-dot" r="4" fill="${color}" stroke="var(--cv-surface)" stroke-width="2"/>
+ </g>
+ </svg>
+ <div class="cv-chart-tip" id="cv-tip" hidden>
+ <p class="p cv-mono" id="cv-tip-price"></p>
+ <p class="d" id="cv-tip-date"></p>
+ </div>
+ </div>`;
+}
+
+// The iframe-terminal body for a non-native source: the mount target + an
+// attribution/open link, or GeckoTerminal's loading/error states while its pool
+// resolves. `cv-adv` is present only when an iframe should mount.
+function embedChartBody(coin, source) {
+ if (source.kind === 'tradingview') {
+ const sym = tvSymbol(coin);
+ const credit = `<a href="https://www.tradingview.com/symbols/${esc(sym)}/" target="_blank" rel="noopener nofollow noreferrer">${esc(coin.symbol || coin.name)} chart by TradingView ↗</a>`;
+ return `<div class="cv-adv-wrap" id="cv-adv" aria-label="TradingView chart for ${esc(coin.name)}"></div><p class="cv-tv-credit">${credit}</p>`;
+ }
+ const ref = onchainRef(coin);
+ if (!ref) return '<div class="cv-chart-state">Chart data unavailable</div>';
+ if (source.kind === 'dexscreener') {
+ const credit = `<a href="https://dexscreener.com/${esc(ref.ds)}/${esc(ref.address)}" target="_blank" rel="noopener nofollow noreferrer">Open in DexScreener ↗</a>`;
+ return `<div class="cv-adv-wrap" id="cv-adv" aria-label="DexScreener chart for ${esc(coin.name)}"></div><p class="cv-tv-credit">${credit}</p>`;
+ }
+ // geckoterminal
+ const openLink = `<a href="https://www.geckoterminal.com/${esc(ref.gt)}/tokens/${esc(ref.address)}" target="_blank" rel="noopener nofollow noreferrer">Open in GeckoTerminal ↗</a>`;
+ if (chartState.gtState === 'error') {
+ return `<div class="cv-chart-state">On-chain chart unavailable · ${openLink}</div>`;
+ }
+ if (chartState.gtState !== 'ready' || !chartState.gtPool) {
+ return '<div class="cv-chart-state"><span class="cv-spinner" aria-hidden="true"></span>Loading GeckoTerminal…</div>';
+ }
+ return `<div class="cv-adv-wrap" id="cv-adv" aria-label="GeckoTerminal chart for ${esc(coin.name)}"></div><p class="cv-tv-credit">${openLink}</p>`;
+}
+
+// Mount the iframe for the active non-native source into #cv-adv. GeckoTerminal
+// first resolves its pool (kicking off the async fetch on the idle→loading
+// transition); the other terminals mount synchronously.
+function mountActiveEmbed(coin, source) {
+ ensureThemeRemount(coin);
+ if (source.kind === 'tradingview') {
+ mountTradingView($('cv-adv'), tvSymbol(coin));
+ return;
+ }
+ const ref = onchainRef(coin);
+ if (!ref) return;
+ if (source.kind === 'dexscreener') {
+ mountDexScreener($('cv-adv'), ref);
+ return;
+ }
+ // geckoterminal
+ if (chartState.gtState === 'idle') {
+ loadGtPool(coin, ref);
+ return;
+ }
+ if (chartState.gtState === 'ready' && chartState.gtPool) {
+ mountGeckoTerminal($('cv-adv'), ref, chartState.gtPool);
+ }
}
function wireChartPointer() {
@@ -939,14 +1070,13 @@ async function main() {
upd.textContent = `Last updated: ${new Date(coin.last_updated).toLocaleString()}`;
}
// Chart, markets, and news stream in independently of the core profile.
- // A remembered "advanced" preference mounts the candlestick embed directly
- // and defers the native OHLC fetch until the user switches back.
- if (chartState.mode === 'advanced' && advancedProvider(coin)) {
+ // A remembered non-CoinGecko source mounts its terminal directly and defers
+ // the native OHLC fetch until the user switches back to the CoinGecko chart.
+ if (resolvedSource(coin).kind === 'native') {
+ loadChart(coin);
+ } else {
chartState.loading = false;
renderChart(coin);
- } else {
- chartState.mode = 'simple';
- loadChart(coin);
}
loadMarkets(coin);
loadNews(coin);