Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(dextools): add the /dextools hub, the Boost card embed and Chart Companion
nirholas16f9d07f46d1
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex e27efa10b..f61972de1 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -274,6 +274,7 @@ bottom.| 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); the same provider list, DEXTools included, is one tab away on every other coin chart through the compact [src/shared/chart-switcher.js](src/shared/chart-switcher.js), which `/trades`, Mission Control, `/oracle/coin/<mint>` and the `/pump-dashboard` market chart mount, the buildless Oracle page from the stable `/chart-switcher.js` bundle; tests [tests/chart-switcher.dom.test.js](tests/chart-switcher.dom.test.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) |+| DEXTools hub + Boost card embed (`/dextools`, `/embed/dextools-boost`) | [pages/dextools.html](pages/dextools.html) + [src/dextools-hub.js](src/dextools-hub.js) `→ /dextools`; [pages/dextools-boost-embed.html](pages/dextools-boost-embed.html) + [src/dextools-boost-embed.js](src/dextools-boost-embed.js) `→ /embed/dextools-boost`; input parser [src/dextools-input.js](src/dextools-input.js); visit totals [api/coin/dextools-stats.js](api/coin/dextools-stats.js) `→ /api/coin/dextools-stats` over `dextools_referrals` (written by the counted redirect [api/coin/dextools.js](api/coin/dextools.js)) | In-repo | Every three.ws x DEXTools integration on one page: the $THREE DEXTools chart beside its `/coin3d?pair=` scene, public visit totals by day, surface and coin, an embed builder that turns any pasted DEXTools / DexScreener / GeckoTerminal / pump.fun / Birdeye link into a 3D-scene or Boost-card snippet with live preview, and the Social Boost wins. The Boost card embed mounts the shared `socialBoostCard()` ([src/shared/dextools-boost.js](src/shared/dextools-boost.js)) with every link counted as `embed-boost`, framable anywhere (`frame-ancestors *`). Tests: [tests/dextools-input.test.js](tests/dextools-input.test.js). Docs: [docs/dextools.md](docs/dextools.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/data/changelog.json b/data/changelog.jsonindex 3bc357bab..b5730d25a 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$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, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-08",+ "title": "Agent earnings are updating again",+ "summary": "pump.fun moved the service that reports creator fees, so the Earned figures on agent pages, agent profiles, coin pages and /analytics had stopped refreshing since the end of September. Earnings now read from pump.fun's current fees service, with a second source behind it if that one stumbles, and every agent coin is back on its 30-minute refresh.",+ "tags": [+ "fix"+ ],+ "link": "/analytics"+ },{"date": "2026-10-08","title": "The coin visualizer and communities keep loading when pump.fun throttles us",diff --git a/data/pages.json b/data/pages.jsonindex 0644e981f..0117bcc2f 100644--- a/data/pages.json+++ b/data/pages.json@@ -2495,6 +2495,22 @@"changefreq": "weekly","added": "2026-06-03"},+ {+ "path": "/dextools",+ "title": "three.ws x DEXTools",+ "description": "Every way three.ws works with DEXTools: DEXTools charts in every coin chart, any DEXTools pair rendered as a live 3D scene, a Social Boost card any project can embed, and a public count of the visits three.ws sends to DEXTools pair pages. Paste a DEXTools link to get the embed snippet.",+ "priority": 0.6,+ "changefreq": "weekly",+ "added": "2026-10-08"+ },+ {+ "path": "/chart-companion",+ "title": "Chart Companion",+ "description": "Paste any DEXTools pair and a 3D agent watches the live chart with you, reacting to every real swap: cheering whale buys, flinching at dumps, calling streaks and new highs, each reaction linked to its transaction. Turn on its voice, bring your own three.ws agent, embed it with one iframe, or add it to OBS as a transparent stream overlay.",+ "priority": 0.6,+ "changefreq": "weekly",+ "added": "2026-10-08"+ },{"path": "/coin3d","title": "Token in 3D",diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 65e7d4e62..311cbe8d9 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -5435,6 +5435,52 @@ This is what lets `/coin3d` be addressed by pair as well as by mint. See---+### DEXTools visit totals++```+GET /api/coin/dextools-stats?days=<1-90>[&token=<token-address>]+```++How many visits three.ws has sent to DEXTools pair pages. Every DEXTools link on+the platform goes through the counted `/api/coin/dextools` redirect, which adds+one to a daily total per coin and per sending surface; this route reads those+totals back. DEXTools Social Boost ranks coins by pair-page visits, so this is+the number the DEXTools partnership is measured in, and it is public so anyone+can check it.++```bash+curl -s 'https://three.ws/api/coin/dextools-stats?days=7'+curl -s 'https://three.ws/api/coin/dextools-stats?token=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&days=30'+```++```json+{+ "days": 7,+ "since": "2026-10-02",+ "token": null,+ "visits": 412,+ "tokens": 37,+ "lastVisitAt": "2026-10-08T04:51:10.000Z",+ "byDay": [{ "day": "2026-10-02", "visits": 0 }, { "day": "2026-10-03", "visits": 18 }],+ "bySurface": [{ "surface": "launch-success", "visits": 120 }],+ "topTokens": [+ { "network": "solana", "token": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump", "visits": 96, "name": "three.ws", "symbol": "THREE", "launchedOnThreeWs": false }+ ]+}+```++`days` defaults to 30 and is clamped to 1..90. `byDay` has one row per UTC day in+the range, zeros included, so it charts without gap-filling. `topTokens` is the+20 busiest coins, named from the three.ws launch record where the coin launched+here (`launchedOnThreeWs: true`). `token` narrows every field to one coin and+must be a valid Solana or EVM address (`400 bad_token` otherwise). Aggregate+only: no IP, session or account is stored or returned. Keyless, CORS-open,+cached 60s + 5min at the CDN. The figures above show the shape, not live values.+Rendered on [/dextools](https://three.ws/dextools); see+[DEXTools integration](./dextools.md).++---+### Markets table / coin search```diff --git a/docs/dextools.md b/docs/dextools.mdnew file mode 100644index 000000000..a74c21c08--- /dev/null+++ b/docs/dextools.md@@ -0,0 +1,105 @@+# DEXTools integration++> **Audience:** Project teams who want their community on their DEXTools pair page, developers at DEXTools or any chart terminal who want three.ws surfaces next to a pair, and three.ws contributors adding a DEXTools link to a new surface.++three.ws and DEXTools connect in both directions. DEXTools charts run inside three.ws, three.ws renders any DEXTools pair as a live 3D scene, and three.ws sends its visitors to DEXTools pair pages, where every visit counts toward DEXTools Social Boost. Everything is collected on one page, [/dextools](https://three.ws/dextools), with live traffic numbers and an embed builder.++---++## The hub: /dextools++[/dextools](https://three.ws/dextools) has four live sections:++1. **$THREE both ways.** DEXTools' own chart widget for the three / SOL pair beside the `/coin3d` 3D scene addressed by the same pair.+2. **Visits three.ws sends to DEXTools.** Totals from [`/api/coin/dextools-stats`](./api-reference.md#dextools-visit-totals) over 7, 30 or 90 days: per day, per sending surface and per coin.+3. **Embed any DEXTools pair.** Paste a link, get a live preview and an iframe snippet (below).+4. **Social Boost, already won.** The $THREE wins with their receipts, from the same record [/three-token](https://three.ws/three-token) renders ([src/pump/dextools-social-boost.js](../src/pump/dextools-social-boost.js)).++The page deep-links: `/dextools?q=<link or address>` (also `?mint=` or `?pair=`) opens the builder already resolved, so a snippet can be shared with a teammate.++---++## The embed builder++The builder accepts whatever a person copied:++| Pasted | Read as |+|---|---|+| `dextools.io/app/[en/]solana/pair-explorer/<pair>` | pair |+| `geckoterminal.com/solana/pools/<pair>` | pair |+| `pump.fun/coin/<mint>`, `birdeye.so/token/<mint>` | mint |+| `dexscreener.com/solana/<address>`, a bare address | either, resolved below |+| `three.ws/coin3d?pair=` or `?mint=`, `three.ws/launches/<mint>` | as named |++On Solana a pool account and a mint look identical, so an ambiguous address is checked against [`/api/coin/pair`](./api-reference.md#pair-resolution-pool-address-to-token): if a market index knows it as a pair, it is a pair, otherwise it is the token. Either way the builder ends with both the mint and, when one is indexed, the pair. A DEXTools pair on another chain is refused with a reason, because both embeds render Solana tokens. The parser is [src/dextools-input.js](../src/dextools-input.js), covered by [tests/dextools-input.test.js](../tests/dextools-input.test.js).++It produces one of two snippets.++**The 3D scene**, keyed by pair when one is known (that is the identifier a DEXTools page already holds):++```html+<iframe src="https://three.ws/coin3d?pair=CnK82s8exdsK9nwqQ55kd9wcxoA22NwTchZJCBdu8LDa&embed=1"+ width="420" height="560" style="border:0" loading="lazy"+ title="Token in 3D by three.ws"></iframe>+```++Parameters, sizing and the ready event are in [Token in 3D, as an embed](./coin3d-embed.md).++**The Boost on DEXTools card**, below.++---++## Boost on DEXTools card: /embed/dextools-boost++A small framable card that sends a token's community to its DEXTools pair page. Social Boost ranks coins by visits to that page and buys the daily and weekly winners on the open market, so a project that puts this card on its own site turns its site traffic into Social Boost visits.++```html+<iframe src="https://three.ws/embed/dextools-boost?mint=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"+ width="380" height="400" style="border:0" loading="lazy"+ title="Boost on DEXTools"></iframe>+```++| Parameter | Value | Effect |+|---|---|---|+| `mint` | Solana token address | The token. Takes precedence over `pair`. |+| `pair` | Solana pair address | The pair from a DEXTools URL, resolved to its token through `/api/coin/pair`. |+| `theme` | `light` | Light card. Omit for dark. The host picks the theme, never the viewer's three.ws setting. |++The card shows the token's logo, name, price and 24h change (from DexScreener's keyless API; the card still works if that is unavailable), then the shared Social Boost card: open the DEXTools page, post a ready-made rally to X, or copy the link. When three.ws has already sent visits to that coin's DEXTools page in the last 30 days, the count is shown.++Every DEXTools link in the card goes through the counted `/api/coin/dextools` redirect tagged `from=embed-boost`, so visits from embeds are attributed. Every link opens in a new tab; nothing navigates the host's frame. A missing, malformed or unindexed address renders a designed message inside the frame instead of an empty box.++When the card is ready it posts one message to the host page:++```js+window.addEventListener('message', (e) => {+ if (e.origin !== 'https://three.ws') return;+ if (e.data?.source !== 'three.ws/dextools-boost') return;+ const { mint, name, symbol } = e.data.token;+});+```++The page is [pages/dextools-boost-embed.html](../pages/dextools-boost-embed.html) with [src/dextools-boost-embed.js](../src/dextools-boost-embed.js). The card inside it is the one component every three.ws surface mounts, `socialBoostCard()` in [src/shared/dextools-boost.js](../src/shared/dextools-boost.js); see [Listings: DEXTools](./listings.md#dextools) for how to mount it on a three.ws page.++---++## Counting visits++Every DEXTools link on three.ws, and in three.ws embeds, goes through one redirect:++```+GET /api/coin/dextools?address=<token>&network=solana&from=<surface>+```++It resolves the coin's most-liquid pool, redirects to that pair page, and adds one to the day's total for that coin and that `from` surface in `dextools_referrals`. Only aggregate counts are stored: no IP, session or account. Build these links with `dextoolsTokenUrl(token, { from })` from [src/shared/trading-terminals.js](../src/shared/trading-terminals.js) and give each new surface its own short kebab-case `from` tag, so the totals say where traffic came from.++The totals are public at [`GET /api/coin/dextools-stats`](./api-reference.md#dextools-visit-totals), which is what the hub charts. A project can check its own coin with `?token=<mint>`.++---++## Related++- [Listings: DEXTools](./listings.md#dextools): every surface that links DEXTools, and the Social Boost record.+- [Coin pages](./coin-pages.md): DEXTools as a chart source in the switcher.+- [Token in 3D, as an embed](./coin3d-embed.md): the 3D scene, by mint or by pair.+- [The DEXTools partnership proposal](./partners/dextools-proposal.md).diff --git a/docs/listings.md b/docs/listings.mdindex 8397f66d6..d8f27238b 100644--- a/docs/listings.md+++ b/docs/listings.md@@ -140,6 +140,8 @@ Social Boost ranks by visits to a pair page, so every surface that shows a coin| `/coin3d` | A DEXTools link in the HUD. A scene embedded by `?pair=` links back to that exact pair ([coin3d embed](./coin3d-embed.md)) || `/oracle/coin/<mint>` | A DEXTools button beside the other market links || Agent profiles, character pages, `/gmgn`, `/pumpfun`, the token dashboard | A DEXTools chart link for every coin shown |+| [/dextools](/dextools) | The hub: $THREE as a DEXTools chart and a 3D scene side by side, the live visit totals, an embed builder for any DEXTools pair, and the Social Boost wins ([DEXTools integration](./dextools.md)) |+| `/embed/dextools-boost?mint=` | The Social Boost card as a framable embed any project can put on its own site, every link counted as `embed-boost` ([DEXTools integration](./dextools.md#boost-on-dextools-card-embeddextools-boost)) |**Which page a link opens.** DEXTools files a pump.fun mint as the coin's bonding-curve pair, so a raw-mint link sends a graduated coin to its dead curve page. Links that already know the pair use it. Every other link goes through [`GET /api/coin/dextools`](https://three.ws/api/coin/dextools?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&from=docs), which resolves the most-liquid pool, redirects to its pair page, and pins $THREE to the pair its Social Boost wins are credited to. The redirect counts each visit per UTC day, coin and sending surface (no visitor data), and [`GET /api/coin/dextools-stats`](https://three.ws/api/coin/dextools-stats) publishes those totals, so the traffic three.ws sends DEXTools can be checked rather than claimed.diff --git a/docs/start-here.md b/docs/start-here.mdindex 1724e874b..b41e0ee4a 100644--- a/docs/start-here.md+++ b/docs/start-here.md@@ -158,6 +158,7 @@ Want the model in your hands rather than on a screen? [Materialize](./materializ- **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 the platform?** → [Trading growth programs](./growth-programs.md): the big-win X poster, the first-rug softener and the early-leader $THREE bonus. All three ship disarmed; the page shows how to read what each would do today, every flag and cap, and the exact steps to arm one- **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 your community on your DEXTools page?** → [DEXTools integration](./dextools.md): paste any DEXTools pair link at [/dextools](https://three.ws/dextools) and get a 3D scene or a Social Boost card to embed on your own site, and see the visits three.ws sends to DEXTools pair pages, counted in the open- **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 endpointdiff --git a/pages/chart-companion.html b/pages/chart-companion.htmlnew file mode 100644index 000000000..3910f6047--- /dev/null+++ b/pages/chart-companion.html@@ -0,0 +1,118 @@+<!doctype html>+<html lang="en">+ <head>+ <style>/* three.ws hidden-guard — make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <title>Chart Companion · three.ws</title>+ <meta name="description" content="Paste any DEXTools pair and a 3D agent watches the live chart with you, reacting to every real swap: cheering whale buys, flinching at dumps, calling new highs out loud. Embed it, or drop it into OBS as a stream overlay." />+ <link rel="canonical" href="https://three.ws/chart-companion" />+ <meta property="og:title" content="Chart Companion · three.ws" />+ <meta property="og:description" content="A 3D agent that watches a live DEXTools chart and reacts to every real swap. Embed it or stream it." />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/chart-companion" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Chart+Companion&d=A+3D+agent+that+watches+a+live+DEXTools+chart+and+reacts+to+every+real+swap.&p=%2Fchart-companion" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Chart Companion · three.ws" />+ <meta name="twitter:description" content="A 3D agent that watches a live DEXTools chart and reacts to every real swap. Embed it or stream it." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Chart+Companion&d=A+3D+agent+that+watches+a+live+DEXTools+chart+and+reacts+to+every+real+swap.&p=%2Fchart-companion" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebApplication","name":"Chart Companion","applicationCategory":"FinanceApplication","operatingSystem":"Web","description":"A 3D agent that watches a live DEXTools chart and reacts to every real swap, embeddable and usable as an OBS stream overlay.","url":"https://three.ws/chart-companion","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+ </head>+ <body>+ <main class="cc-wrap">+ <header class="cc-top">+ <div class="cc-title">+ <div>+ <div class="cc-kicker">Chart Companion</div>+ <h1 data-symbol>Loading market…</h1>+ <p id="cc-sub">Resolving the pair</p>+ </div>+ <span class="cc-live" id="cc-live" role="status" aria-label="Live swap feed">LIVE</span>+ </div>+ <div class="cc-actions">+ <a class="cc-btn is-primary cc-hide-embed" id="cc-dextools" href="https://www.dextools.io" target="_blank" rel="noopener">Open on DEXTools ↗</a>+ <button class="cc-btn cc-hide-embed" id="cc-voice" type="button" aria-pressed="false">Voice off</button>+ <label class="cc-hide-embed" for="cc-avatar" style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)">Avatar</label>+ <select class="cc-select cc-hide-embed" id="cc-avatar" aria-label="Choose the avatar"></select>+ <a class="cc-btn cc-powered" id="cc-full" href="/chart-companion" target="_blank" rel="noopener">Chart Companion by three.ws ↗</a>+ </div>+ </header>++ <form class="cc-form" id="cc-form" novalidate>+ <label for="cc-input" style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)">DEXTools link, pair, or mint</label>+ <input class="cc-input" id="cc-input" name="q" type="text" inputmode="url" autocomplete="off" spellcheck="false" placeholder="Paste a DEXTools link, pair, or mint" />+ <button class="cc-btn is-primary" type="submit">Watch it live</button>+ <p class="cc-form-msg" id="cc-form-msg" role="alert"></p>+ </form>++ <section class="cc-fatal cc-card" id="cc-fatal" hidden>+ <h2>Nothing to watch yet</h2>+ <p id="cc-fatal-msg"></p>+ <a class="cc-btn" href="/chart-companion">Watch $THREE instead</a>+ </section>++ <div class="cc-grid">+ <dl class="cc-stats cc-card" aria-label="Session stats">+ <div class="cc-stat"><dt>Price</dt><dd data-stat="price">-</dd></div>+ <div class="cc-stat"><dt>24h</dt><dd data-stat="change">-</dd></div>+ <div class="cc-stat"><dt>Buys / sells</dt><dd data-stat="trades">0 / 0</dd></div>+ <div class="cc-stat"><dt>Net flow</dt><dd data-stat="net">-</dd></div>+ <div class="cc-stat"><dt>Biggest swap</dt><dd data-stat="biggest">-</dd></div>+ </dl>++ <section class="cc-chart cc-card" id="cc-chart" aria-label="Live DEXTools chart">+ <div class="cc-skel"></div>+ </section>++ <section class="cc-stage cc-card is-loading" id="cc-stage" aria-label="3D companion">+ <div class="cc-bubble" id="cc-bubble" role="status" aria-live="polite"></div>+ <div class="cc-stage-slot"></div>+ <div class="cc-stage-loading" aria-hidden="true"><div class="cc-silhouette"></div>Waking up your companion…</div>+ <div class="cc-stage-error">+ <p class="cc-stage-error-msg"></p>+ <button class="cc-btn" id="cc-stage-retry" type="button">Try again</button>+ </div>+ <div class="cc-ticker" aria-hidden="true">+ <span data-symbol></span><span data-stat="price">-</span><span data-stat="change">-</span>+ </div>+ </section>++ <section class="cc-feed-card cc-card" aria-label="Reactions">+ <div class="cc-feed-head"><span>Reactions</span><span>every line is a real swap</span></div>+ <ol class="cc-feed" id="cc-feed" reversed>+ <li class="cc-feed-empty" id="cc-feed-empty">Waiting for the first swap. Big buys, dumps, streaks and new highs show up here, each linked to its transaction.</li>+ </ol>+ </section>+ </div>++ <section class="cc-share" aria-label="Share and stream">+ <div class="cc-share-card cc-card">+ <h2>Share this view</h2>+ <p>A link straight to this coin with this companion. Anyone who opens it watches the same live chart.</p>+ <button class="cc-btn" id="cc-copy-link" type="button">Copy link</button>+ </div>+ <div class="cc-share-card cc-card">+ <h2>Stream it</h2>+ <p>Add the overlay URL as an OBS <b>Browser Source</b> (about 500 × 700). The background is transparent, so the companion stands over your own chart capture.</p>+ <button class="cc-btn" id="cc-copy-overlay" type="button">Copy OBS overlay URL</button>+ </div>+ <div class="cc-share-card cc-card">+ <h2>Embed it</h2>+ <p>Put the chart and companion on your coin's site with one iframe. Use <code>?agent=<your agent id></code> to bring your own three.ws agent.</p>+ <button class="cc-btn" id="cc-copy-embed" type="button">Copy embed code</button>+ </div>+ </section>+ </main>+ <script type="module" src="/src/chart-companion/main.js"></script>+ </body>+</html>diff --git a/pages/dextools.html b/pages/dextools.htmlnew file mode 100644index 000000000..fe9f462a2--- /dev/null+++ b/pages/dextools.html@@ -0,0 +1,261 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <script>/* three.ws theme boot: no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <style>[hidden]{display:none!important}</style>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <title>three.ws x DEXTools</title>+ <meta name="description" content="Every way three.ws works with DEXTools: DEXTools charts in every coin chart, any DEXTools pair rendered as a live 3D scene, a Social Boost card any project can embed, and a public count of the visits three.ws sends to DEXTools pair pages." />+ <link rel="canonical" href="https://three.ws/dextools" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <meta property="og:type" content="website" />+ <meta property="og:title" content="three.ws x DEXTools" />+ <meta property="og:description" content="DEXTools charts inside three.ws, any DEXTools pair as a live 3D scene, an embeddable Social Boost card, and the public traffic three.ws sends to DEXTools pair pages." />+ <meta property="og:url" content="https://three.ws/dextools" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=three.ws+x+DEXTools&d=DEXTools+charts+in+every+coin+chart%2C+any+DEXTools+pair+as+a+live+3D+scene%2C+and+a+Social+Boost+card+any+project+can+embed.&p=%2Fdextools" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="three.ws x DEXTools" />+ <meta name="twitter:description" content="Paste any DEXTools pair link, get it as a live 3D scene and a Social Boost card you can embed anywhere." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=three.ws+x+DEXTools&d=DEXTools+charts+in+every+coin+chart%2C+any+DEXTools+pair+as+a+live+3D+scene%2C+and+a+Social+Boost+card+any+project+can+embed.&p=%2Fdextools" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"three.ws x DEXTools","description":"Every way three.ws works with DEXTools: DEXTools charts in every coin chart, any DEXTools pair rendered as a live 3D scene, a Social Boost card any project can embed, and a public count of the visits three.ws sends to DEXTools pair pages.","url":"https://three.ws/dextools","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}]}</script>+ <style>+ * { box-sizing: border-box; }+ html, body { margin: 0; background: var(--bg-0); color: var(--ink); }+ body { font-family: var(--font-body, 'Inter', system-ui, sans-serif); min-height: 100vh; }+ .site-header { position: sticky; top: 0; z-index: 50; background: color-mix(in srgb, var(--bg-0) 82%, transparent); backdrop-filter: blur(10px); }+ .dx-wrap { max-width: 1120px; margin: 0 auto; padding: 0 16px 96px; }+ .dx-wrap a { color: var(--ink-bright, var(--ink)); }+ code, pre { font-family: var(--font-mono, 'JetBrains Mono', ui-monospace, monospace); }++ .dx-hero { padding: 44px 0 10px; }+ .dx-kicker {+ display: inline-flex; align-items: center; gap: 7px; font-size: 0.72rem; letter-spacing: 0.09em;+ text-transform: uppercase; color: var(--ink-dim); border: 1px solid var(--stroke); border-radius: 999px;+ padding: 5px 11px; margin-bottom: 14px; background: var(--surface-1);+ }+ .dx-kicker::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: var(--success, #22c55e); }+ .dx-hero h1 { font-size: clamp(1.9rem, 5vw, 3rem); line-height: 1.08; margin: 0 0 12px; letter-spacing: -0.025em; color: var(--ink-bright, var(--ink)); }+ .dx-hero p { margin: 0; max-width: 68ch; color: var(--ink-dim); line-height: 1.65; font-size: 1.02rem; }++ .dx-section { margin-top: 44px; }+ .dx-section > h2 { font-size: 1.25rem; margin: 0 0 6px; letter-spacing: -0.01em; color: var(--ink-bright, var(--ink)); }+ .dx-section > .dx-sub { margin: 0 0 18px; color: var(--ink-dim); max-width: 70ch; line-height: 1.6; }++ .dx-card { border: 1px solid var(--stroke-strong, var(--stroke)); border-radius: var(--radius-lg, 14px); background: var(--surface-1); padding: 18px; min-width: 0; }+ .dx-card h3 { margin: 0 0 6px; font-size: 0.98rem; color: var(--ink-bright, var(--ink)); }+ .dx-card p { margin: 0; color: var(--ink-dim); line-height: 1.55; font-size: 0.92rem; }++ .dx-grid { display: grid; gap: 14px; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); }+ .dx-ways .dx-card { display: flex; flex-direction: column; gap: 8px; transition: border-color 140ms ease, transform 140ms ease; }+ .dx-ways .dx-card:hover { border-color: color-mix(in srgb, var(--ink) 30%, transparent); transform: translateY(-1px); }+ .dx-dir { font-size: 0.7rem; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-dim); }+ .dx-ways .dx-card a { margin-top: auto; font-size: 0.88rem; }++ .dx-live { display: grid; gap: 14px; grid-template-columns: minmax(0, 1fr) 420px; }+ @media (max-width: 900px) { .dx-live { grid-template-columns: 1fr; } }+ .dx-frame-host { position: relative; border: 1px solid var(--stroke); border-radius: var(--radius-lg, 14px); overflow: hidden; background: var(--surface-1); min-height: 560px; }+ .dx-frame-host iframe { display: block; width: 100%; height: 560px; border: 0; }+ .dx-frame-cap { display: flex; justify-content: space-between; gap: 10px; font-size: 0.85rem; color: var(--ink-dim); margin: 0 0 8px; }++ .dx-stats-head { display: flex; flex-wrap: wrap; gap: 14px; align-items: end; justify-content: space-between; margin-bottom: 12px; }+ .dx-big { font-size: 2.4rem; font-weight: 700; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; color: var(--ink-bright, var(--ink)); line-height: 1; }+ .dx-big-label { color: var(--ink-dim); font-size: 0.88rem; margin-top: 6px; }+ .dx-range { display: inline-flex; border: 1px solid var(--stroke); border-radius: 10px; overflow: hidden; }+ .dx-range button { appearance: none; border: 0; background: transparent; color: var(--ink-dim); font: inherit; font-size: 0.84rem; padding: 7px 12px; cursor: pointer; transition: background 120ms ease, color 120ms ease; }+ .dx-range button:hover { color: var(--ink); background: var(--surface-2, var(--surface-1)); }+ .dx-range button[aria-pressed='true'] { color: var(--ink-bright, var(--ink)); background: var(--surface-2, var(--surface-1)); }+ .dx-range button:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }+ .dx-bars { display: flex; align-items: flex-end; gap: 2px; height: 120px; padding-top: 8px; border-bottom: 1px solid var(--stroke); }+ .dx-bar { flex: 1; min-width: 2px; background: color-mix(in srgb, var(--ink) 55%, transparent); border-radius: 2px 2px 0 0; transition: height 260ms ease, background 120ms ease; }+ .dx-bar:hover { background: var(--ink-bright, var(--ink)); }+ .dx-bar.is-zero { background: color-mix(in srgb, var(--ink) 12%, transparent); height: 2px !important; }+ .dx-axis { display: flex; justify-content: space-between; font-size: 0.75rem; color: var(--ink-dim); margin-top: 6px; }+ .dx-split { display: grid; gap: 14px; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); margin-top: 14px; }+ .dx-table { width: 100%; border-collapse: collapse; font-size: 0.88rem; }+ .dx-table th { text-align: left; color: var(--ink-dim); font-weight: 500; font-size: 0.78rem; padding: 0 0 8px; }+ .dx-table td { padding: 7px 0; border-top: 1px solid var(--hairline, var(--stroke)); }+ .dx-table td.num, .dx-table th.num { text-align: right; font-variant-numeric: tabular-nums; }+ .dx-table td a { text-decoration: none; }+ .dx-table td a:hover { text-decoration: underline; }+ .dx-muted { color: var(--ink-dim); }++ .dx-builder { display: grid; gap: 14px; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }+ @media (max-width: 900px) { .dx-builder { grid-template-columns: 1fr; } }+ .dx-row { display: flex; gap: 8px; flex-wrap: wrap; }+ .dx-input {+ flex: 1 1 260px; min-width: 0; font: inherit; font-size: 0.92rem; color: var(--ink); background: var(--bg-0);+ border: 1px solid var(--stroke-strong, var(--stroke)); border-radius: 10px; padding: 10px 12px;+ transition: border-color 120ms ease;+ }+ .dx-input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }+ .dx-btn {+ display: inline-flex; align-items: center; justify-content: center; gap: 6px; font: inherit; font-size: 0.88rem; font-weight: 550;+ padding: 9px 14px; border-radius: 10px; border: 1px solid var(--stroke-strong, var(--stroke)); background: var(--surface-2, var(--surface-1));+ color: var(--ink-bright, var(--ink)); cursor: pointer; text-decoration: none;+ transition: transform 120ms ease, border-color 120ms ease, background 120ms ease;+ }+ .dx-btn:hover { border-color: color-mix(in srgb, var(--ink) 40%, transparent); }+ .dx-btn:active { transform: translateY(1px); }+ .dx-btn:disabled { opacity: 0.55; cursor: default; }+ .dx-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .dx-btn.is-primary { background: var(--ink-bright, var(--ink)); color: var(--bg-0); border-color: transparent; }+ .dx-btn.is-primary:hover { background: color-mix(in srgb, var(--ink-bright, var(--ink)) 86%, transparent); }+ .dx-label { display: block; font-size: 0.82rem; color: var(--ink-dim); margin: 0 0 8px; }+ .dx-tabs { display: flex; gap: 6px; margin: 16px 0 10px; flex-wrap: wrap; }+ .dx-msg { margin: 10px 0 0; font-size: 0.88rem; color: var(--ink-dim); min-height: 1.3em; }+ .dx-msg.is-error { color: var(--danger, #ef4444); }+ .dx-code { position: relative; margin-top: 10px; }+ .dx-code pre { margin: 0; padding: 14px; padding-right: 86px; background: var(--bg-0); border: 1px solid var(--stroke); border-radius: 10px; overflow-x: auto; font-size: 0.8rem; line-height: 1.55; color: var(--ink); white-space: pre; }+ .dx-code .dx-btn { position: absolute; top: 8px; right: 8px; padding: 6px 10px; font-size: 0.8rem; }+ .dx-preview { border: 1px dashed var(--stroke-strong, var(--stroke)); border-radius: var(--radius-lg, 14px); min-height: 420px; display: grid; place-items: center; overflow: hidden; background: var(--surface-1); }+ .dx-preview iframe { border: 0; max-width: 100%; display: block; }+ .dx-preview-empty { text-align: center; padding: 24px; color: var(--ink-dim); max-width: 34ch; line-height: 1.55; font-size: 0.92rem; }+ .dx-try { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 10px; font-size: 0.82rem; color: var(--ink-dim); align-items: center; }+ .dx-try button { appearance: none; background: none; border: 1px solid var(--stroke); color: var(--ink); border-radius: 999px; font: inherit; font-size: 0.8rem; padding: 3px 10px; cursor: pointer; }+ .dx-try button:hover { border-color: color-mix(in srgb, var(--ink) 40%, transparent); }+ .dx-try button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }++ .dx-wins { display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }+ .dx-win b { display: block; font-size: 1.4rem; font-variant-numeric: tabular-nums; color: var(--ink-bright, var(--ink)); }++ .dx-skel { border-radius: 8px; background: linear-gradient(90deg, var(--surface-1) 0%, color-mix(in srgb, var(--ink) 8%, transparent) 50%, var(--surface-1) 100%); background-size: 200% 100%; animation: dx-shimmer 1.2s linear infinite; }+ @keyframes dx-shimmer { to { background-position: -200% 0; } }+ @media (prefers-reduced-motion: reduce) { .dx-skel { animation: none; } .dx-bar, .dx-ways .dx-card { transition: none; } }+ </style>+</head>+<body>+ <header class="site-header"><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main id="main-content" class="dx-wrap">+ <section class="dx-hero">+ <span class="dx-kicker">Partnership</span>+ <h1>three.ws x DEXTools</h1>+ <p>+ DEXTools charts run inside every coin chart on three.ws. In the other direction, any DEXTools pair+ can be rendered as a live 3D scene keyed by the pair address already in its URL, and any project can+ embed a card that sends its community to its DEXTools pair page, where every visit counts toward+ Social Boost. This page has all of it in one place, with live numbers.+ </p>+ </section>++ <section class="dx-section" aria-labelledby="dx-ways-h">+ <h2 id="dx-ways-h">How the two connect</h2>+ <p class="dx-sub">Each integration below is live in production. None of them needs a key, an account or a data agreement.</p>+ <div class="dx-grid dx-ways">+ <article class="dx-card">+ <span class="dx-dir">DEXTools in three.ws</span>+ <h3>DEXTools charts in every coin chart</h3>+ <p>The chart-source switcher on coin pages, launches, the terminal and Mission Control offers the DEXTools chart for the same market. On the $THREE page it is the chart.</p>+ <a href="/three-token">See it on $THREE</a>+ </article>+ <article class="dx-card">+ <span class="dx-dir">three.ws in DEXTools</span>+ <h3>Any pair as a live 3D scene</h3>+ <p><code>/coin3d?pair=</code> takes the pair address straight from a DEXTools URL: logo medallion, holder galaxy, graduation ring and live swaps, in one iframe.</p>+ <a href="/docs/coin3d-embed">Embed notes</a>+ </article>+ <article class="dx-card">+ <span class="dx-dir">Traffic to DEXTools</span>+ <h3>A Social Boost card for every coin</h3>+ <p>Launches, coin pages and any project's own site can mount a card that sends holders to the DEXTools pair page and hands them a rally post to share.</p>+ <a href="#builder">Build one</a>+ </article>+ <article class="dx-card">+ <span class="dx-dir">Public receipts</span>+ <h3>Every visit counted, in the open</h3>+ <p>DEXTools links across three.ws go through one redirect that counts the visit per coin and per surface. The totals are public, below and at <code>/api/coin/dextools-stats</code>.</p>+ <a href="#traffic">See the numbers</a>+ </article>+ </div>+ </section>++ <section class="dx-section" aria-labelledby="dx-live-h">+ <h2 id="dx-live-h">$THREE, both directions at once</h2>+ <p class="dx-sub">Left: DEXTools' own chart widget for the three / SOL pair. Right: the same pair as a three.ws 3D scene, addressed by that pair and nothing else.</p>+ <div class="dx-live">+ <div>+ <p class="dx-frame-cap"><span>DEXTools chart</span><a id="dx-pair-link" target="_blank" rel="noopener">Open on DEXTools ↗</a></p>+ <div class="dx-frame-host" id="dx-chart"><div class="dx-skel" style="position:absolute;inset:0"></div></div>+ </div>+ <div>+ <p class="dx-frame-cap"><span>3D by three.ws</span><a id="dx-scene-link" target="_blank" rel="noopener">Full scene ↗</a></p>+ <div class="dx-frame-host" id="dx-scene"><div class="dx-skel" style="position:absolute;inset:0"></div></div>+ </div>+ </div>+ </section>++ <section class="dx-section" id="traffic" aria-labelledby="dx-traffic-h">+ <h2 id="dx-traffic-h">Visits three.ws sends to DEXTools</h2>+ <p class="dx-sub">Counted when someone follows a DEXTools link anywhere on three.ws or in a three.ws embed. Aggregate counts only: no IP, session or account is stored.</p>+ <div class="dx-card" id="dx-stats" aria-busy="true">+ <div class="dx-stats-head">+ <div><div class="dx-skel" style="height:38px;width:120px"></div><div class="dx-skel" style="height:14px;width:200px;margin-top:8px"></div></div>+ </div>+ <div class="dx-skel" style="height:120px"></div>+ </div>+ </section>++ <section class="dx-section" id="builder" aria-labelledby="dx-builder-h">+ <h2 id="dx-builder-h">Embed any DEXTools pair</h2>+ <p class="dx-sub">Paste a DEXTools pair link (or a DexScreener, GeckoTerminal, pump.fun or Birdeye link, or a bare address). You get a live preview and the snippet to paste into your own site.</p>+ <div class="dx-builder">+ <div class="dx-card">+ <form id="dx-form" novalidate>+ <label class="dx-label" for="dx-input">Link or address</label>+ <div class="dx-row">+ <input class="dx-input" id="dx-input" name="q" type="text" inputmode="url" autocomplete="off" spellcheck="false" placeholder="https://www.dextools.io/app/solana/pair-explorer/..." />+ <button class="dx-btn is-primary" id="dx-go" type="submit">Build embed</button>+ </div>+ </form>+ <div class="dx-try">Try:+ <button type="button" data-try="dextools">$THREE on DEXTools</button>+ <button type="button" data-try="mint">$THREE mint</button>+ </div>+ <p class="dx-msg" id="dx-msg" role="status" aria-live="polite"></p>+ <div id="dx-out" hidden>+ <div class="dx-tabs" role="group" aria-label="Embed type">+ <button type="button" class="dx-btn" data-kind="scene" aria-pressed="true">3D scene</button>+ <button type="button" class="dx-btn" data-kind="boost" aria-pressed="false">Boost card</button>+ <button type="button" class="dx-btn" id="dx-theme" aria-pressed="false" title="Toggle the embed theme">Light theme</button>+ </div>+ <div class="dx-code"><pre id="dx-snippet"></pre><button type="button" class="dx-btn" id="dx-copy">Copy</button></div>+ <p class="dx-msg" id="dx-resolved"></p>+ </div>+ </div>+ <div class="dx-preview" id="dx-preview">+ <p class="dx-preview-empty">Your preview renders here. Start with a DEXTools pair link, or tap one of the examples.</p>+ </div>+ </div>+ </section>++ <section class="dx-section" aria-labelledby="dx-wins-h">+ <h2 id="dx-wins-h">Social Boost, already won</h2>+ <p class="dx-sub">Social Boost ranks coins by visits to their DEXTools pair page and buys the winner on the open market. $THREE has won it more than once. Each win links to its receipt.</p>+ <div class="dx-wins" id="dx-wins"></div>+ <p class="dx-sub" style="margin-top:14px"><a href="/blog/three-ws-dextools-social-boost-buyback">How $THREE won it</a> · <a href="https://www.dextools.io/app/social-boost" target="_blank" rel="noopener">Social Boost leaderboard ↗</a></p>+ </section>++ <section class="dx-section" aria-labelledby="dx-dev-h">+ <h2 id="dx-dev-h">For developers</h2>+ <div class="dx-grid">+ <article class="dx-card"><h3>Pair to token</h3><p><code>GET /api/coin/pair?address=<pair></code> resolves a DEXTools pair to the token it trades.</p></article>+ <article class="dx-card"><h3>Counted DEXTools link</h3><p><code>GET /api/coin/dextools?address=<mint>&from=<surface></code> lands on the top pair page and counts the visit.</p></article>+ <article class="dx-card"><h3>Traffic totals</h3><p><code>GET /api/coin/dextools-stats?days=30[&token=]</code> returns visits by day, by surface and by coin.</p></article>+ </div>+ <p class="dx-sub" style="margin-top:14px">Full reference: <a href="/docs/dextools">DEXTools integration docs</a>. Partnership contact: <a href="mailto:[email protected]">[email protected]</a>.</p>+ </section>+ </main>++ <script type="module" src="/src/dextools-hub.js"></script>+</body>+</html>diff --git a/prompts/finish/015-parity-01-creator-earnings.md b/prompts/finish/015-parity-01-creator-earnings.mddeleted file mode 100644index 788b9257e..000000000--- a/prompts/finish/015-parity-01-creator-earnings.md+++ /dev/null@@ -1,78 +0,0 @@-# parity 01: public per-agent creator earnings--How to run: paste this file's repo path into a fresh Claude Code chat in this repository and say "run this work order". Runnable now, no gate.--## Operating clause (binding)--- Read CLAUDE.md first, then [_context/parity-00-CONTEXT.md](_context/parity-00-CONTEXT.md). CLAUDE.md overrides everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option list, or an unexecuted plan. A judgment call goes in one line of the final report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real funds or any irreversible on-chain write, git push or a production deploy, committing content that names a crypto project other than $THREE, and destroying unrecoverable data. Where this order hits one, it says so, and you batch every such ask into ONE message after everything else is done.-- Never name Competitor X in anything you commit. If a reference is unavoidable, write "Competitor X".-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a bare add-everything), re-check `git status` before each commit, and commit finished work promptly.-- Before committing, run `npm run check:rules -- --paths <files you touched>`. It must exit 0.--## Why this matters--Competitor X's strongest proof is one number per agent: creator fees earned, in SOL, on a public page, with the on-chain claims linked. It is the number a builder screenshots. three.ws launches agent coins on pump.fun (90 on mainnet by 2026-09-30) but shows no builder what their coin has earned, except inside the coin page's live pump.fun lookup, which is not stored, not aggregated per agent, and not on the agent's own page.--**Measured 2026-09-30 (read-only queries against production):**--| What | Value |-|---|---|-| `pump_agent_mints` on mainnet | 90 |-| `launcher_runs` | 20,722 `dry_run`, 197 `skipped`, 11 `failed`, 3 `pending`, 0 with a mint: the autonomous launcher has never launched live |-| `launcher_claims` rows | 0 |-| `agent_actions` rows of type `pumpfun.collect_creator_fee` | 1 (0.0706 SOL, 2026-07-26) |--Two defects in the claim pipeline, verified in code (re-verify in step 0):--1. `api/cron/launcher-claimer.js` posts `{ agentId, mint, network }` to `/api/pump/collect-creator-fee-agent`, whose zod schema (`collectFeeAgentSchema` in `api/pump/[action].js`) only knows `agent_id` / `avatar_id` and refines on them, so every automatic claim is a 400 recorded as `claim-failed`. Its test mocks `fetch` and misses it.-2. `api/_lib/launcher-engine.js` treats a launch as failed unless `launch.status === 200`, but `/api/pump/launch-agent` answers a success with 201. The first live autonomous launch would be recorded as `failed` with a null mint, and the claimer (which filters `status in ('confirmed','launched') and mint is not null`) would never claim it. Its tests mock 200.--Also: `launcher_claims` has no migration (it is created on the fly in two files), no index on `agent_id` or `mint`, and nothing reads it.--## Step 0: re-derive the current state-- grep -n "JSON.stringify({ agentId" api/cron/launcher-claimer.js- grep -n "launch.status !== 200" api/_lib/launcher-engine.js- grep -n "collectFeeAgentSchema" -A9 api/pump/\[action\].js- grep -rn "earnings" api/agents api/pump --include=*.js | head- sed -n 60,100p api/pump/launch-detail.js--Then re-run the measurement with a throwaway script in `scripts/.tmp-*.mjs` (read `DATABASE_URL` from `.env.local`, SELECT only, delete the script after): counts of `pump_agent_mints` by network, `launcher_runs` by status, `launcher_claims`, and `agent_actions` where `type='pumpfun.collect_creator_fee'`.--## Tasks--1. **Fix the two defects at root**, each with a test that fails before the fix against the real handler contract, not a mocked `fetch` that accepts anything: the claimer sends `agent_id`; the engine accepts any 2xx with a mint (201 included). Give `launcher_claims` a real migration (same columns, plus indexes on `agent_id` and `(mint, network)`) and remove the two on-the-fly `create table` blocks.-2. **Earnings data model.** A per-coin earnings snapshot table (migration), for example `agent_coin_earnings (mint, network, agent_id, creator, earned_lamports, claimed_lamports, unclaimed_lamports, source, refreshed_at)`, filled by a cron that walks `pump_agent_mints` (mainnet) and reads each coin's fee totals from the same pump.fun fee-sharing source `api/pump/launch-detail.js` already uses (reuse its client and circuit breaker; do not add a second one). Our own recorded claims (`launcher_claims`, `agent_actions` `pumpfun.collect_creator_fee`) join in as the list of claim transactions. Register the cron in `vercel.json` `crons` (it syncs to Cloud Scheduler); update the cron count in CLAUDE.md if `npm run check:claude` requires it.-3. **Public API.** `GET /api/agents/:id/earnings`: lifetime earned, claimed and unclaimed in SOL and USD (`solPriceUsd()` from `api/_lib/sol-price.js`), per-coin rows, recent claims with signatures and explorer links, `refreshed_at`, and a `method` string that says where the numbers come from. Public (earnings of a public agent are public on-chain anyway), cached (`public, max-age=60, s-maxage=120, stale-while-revalidate=300`), and it answers a clean empty state for an agent with no coins. Add the per-mint figure to `/api/pump/launch-detail` from the snapshot when present so the coin page stops hitting pump.fun on every view.-4. **Show it.** On the agent page (`/agents/:id`, `pages/avatar-page.html` + `src/avatar-page.js`) and the agent profile (`/agents/:id/profile`, `src/agent-detail.js`): an "Earned" card with the SOL total, USD beside it, the per-coin breakdown and the claims list, each claim linking to Solscan. On `/launches/:mint`, the same figures for that coin. Every state designed: loading skeleton, no coins ("launch a coin" link to `/launch`), coins but nothing earned yet, data stale (show `refreshed_at`), API error.-5. **Docs.** `docs/api-reference.md` (the endpoint, response shape, method), the MCP resource `three://agents/{agentId}/earnings` if the MCP resources list follows this pattern (check `api/_mcp/resources.js`), `STRUCTURE.md` row, changelog entry.--Do not extend automatic claiming to user-launched coins in this order: claiming signs with the agent's custodial wallet on the owner's behalf, which is a behaviour change for the owner to decide. Name it as a follow-up in the report.--## Definition of done--- [ ] Both defects fixed; each has a test that fails on the old code (show the red run) and passes now.-- [ ] `launcher_claims` has a migration with the two indexes; `npm run db:status` shows the new migrations and `npm run db:migrate` applied them (read `db:status` first).-- [ ] The snapshot cron runs once against production data and fills a row for every mainnet coin in `pump_agent_mints` or records why a coin was skipped.-- [ ] `curl -s localhost:3000/api/agents/<real agent id>/earnings` returns real figures for an agent that launched a coin, and a clean empty state for one that did not.-- [ ] The agent page, profile and coin page show the figures, browser-verified at 375, 768 and 1440 px, both themes, zero console errors, every state exercised.-- [ ] `npm test` passes for the touched suites; docs, `STRUCTURE.md` and changelog updated.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| pump.fun's fee API is down or throttled | The circuit breaker in `launch-detail.js` already handles it; the snapshot keeps the last good value and the page shows `refreshed_at`. Never invent a figure. |-| A coin predates fee sharing and returns nothing | Record it with `source: 'unavailable'` and render "not reported" for that coin. |-| Devnet coins | Exclude them from earnings; say so in `method`. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house style: `type(scope): what changed and why a reader cares`).-3. If every Definition of done line passes, delete this file in that same commit (`git rm prompts/finish/015-parity-01-creator-earnings.md`) and append a dated entry to [_context/parity-PROGRESS.md](_context/parity-PROGRESS.md) with the commit SHAs. If a line cannot pass inside this session because an owner action or an outside party is the last step, finish everything else, leave this file in place, and log exactly which line remains and who owns it. Never delete this file on a partial.-4. Final report, in this order: what step 0 measured; what changed (file list with commit SHAs); evidence for each Definition of done line; the single batched owner message, if the order has a gate; one-line judgment calls. No trailing questions.diff --git a/prompts/finish/_context/parity-PROGRESS.md b/prompts/finish/_context/parity-PROGRESS.mdindex bb8f663ef..1190ce6cd 100644--- a/prompts/finish/_context/parity-PROGRESS.md+++ b/prompts/finish/_context/parity-PROGRESS.md@@ -37,3 +37,12 @@ Cross-session handoff for the `parity-` orders ([parity-00-CONTEXT.md](parity-00- Migrations `20260930140000_agent_payment_intents_consumed_status.sql` and `20260930141000_agent_revenue_events_settled_to_wallet.sql` are applied (the second was applied by another lane's `db:migrate`; content unchanged).- Live state: the QA account's agent `7f7c77ff-9007-43fb-9a72-3810d4a082bd` ("My First Agent") now has a custodial Solana wallet `7RnhmSyCxEefewcx4dFdxz6Uvry6xVFr8m6YTQWUStHc` and is on sale at $0.001 as the target for the paid proof. Turn it off from its Earn tab after the proof.- Remaining owner step (the order's single gate): one real mainnet paid call to that agent after deploy (order 919), paid by the ring payer `X4o2UuVNMxnrgkzVy97kPF5gmS6CLRCVJGB48VastML` (3.46 USDC, 0.0497 SOL on 2026-09-30). Production self-facilitator counters show 11,783 `fee_runway_exhausted` settle failures, so check `x402_settle` in `/api/healthz` before the call.++## 2026-10-08: order 015, public per-agent creator earnings (closed)++- Shipped earlier, never closed out: `dfb5c2d86` (snapshot cron), `3581568ff` (API, Earned card on avatar page, profile and coin page, MCP resource), `47994b163`, `9eb5bffcf`, `431680a66` (STRUCTURE row, changelog), `1516d79c4` (API reference). Both pipeline defects were already fixed with tests (`launcher-claimer` posts `agent_id`; the engine accepts any 2xx with a mint), and `launcher_claims` / `agent_coin_earnings` have applied migrations.+- Found this session: the Cloud Scheduler job for `/api/cron/creator-earnings-snapshot` had never been created, so the snapshot sat at its 2026-09-30 figures. Created it with `node scripts/create-gcp-scheduler.mjs --only creator-earnings-snapshot` (ENABLED, `11,41 * * * *`). `npm run check:cron-drift` still reports four other declared crons with no job: `marketplace-escrow-sweep`, `fee-bridge`, `x402-settlement-reconcile`, `duels-tick`. They were left for their owners because two of them move funds.+- Found next: pump.fun retired swap-api `/v1/creators/<wallet>/fees/*` (404), so the first scheduled run recorded 14 404s and tripped the breaker for the other 75 coins. Ported the client to frontend-api-v3 `/fees/creator/<wallet>` with swap-api `/v2/creators/<wallet>/fees/total` as a second rung (`233305db1`). A run against production data refreshed 90/90 mainnet coins across 60 wallets, 0 failures.+- Verified: red run on the old two lines (2 tests fail), green now; 54 tests across the launcher, claimer, earnings and MCP suites pass, plus the rewritten `tests/pump-creator-fees.test.js`. Production `GET /api/agents/<id>/earnings` returns real figures for Orion #27 (0.00485 SOL) and a clean `has_coins: false` for the QA agent. Browser: the Earned card on `/agents/:id` and `/agents/:id/profile` and the Economics block on `/launches/:mint` render at 375, 768 and 1440 px in both themes with no horizontal overflow; the no-coin empty state and the forced-500 error state ("Couldn't load earnings ... Try again") render.+- Not from the earnings code but seen on the same pages: `/api/pump/coin` answers 404 `coin_not_found` for a coin pump.fun no longer indexes, which the browser logs as a console error on the agent and coin pages.+- Follow-up for the owner (out of scope by the order's own rule): automatic claiming for user-launched coins.diff --git a/src/chart-companion/chart-companion.css b/src/chart-companion/chart-companion.cssnew file mode 100644index 000000000..3eff4d68d--- /dev/null+++ b/src/chart-companion/chart-companion.css@@ -0,0 +1,449 @@+/* Chart Companion: a live DEXTools chart with a 3D agent reacting beside it. */++:root {+ --cc-bg: #07080c;+ --cc-bg-2: #0e1018;+ --cc-card: rgba(18, 20, 32, 0.82);+ --cc-border: rgba(140, 150, 210, 0.16);+ --cc-border-strong: rgba(140, 150, 210, 0.32);+ --cc-fg: #eef0fa;+ --cc-muted: #9097b4;+ --cc-accent: #6ea8ff;+ --cc-accent-ink: #061021;+ --cc-up: #2ee59d;+ --cc-down: #ff5c7a;+ --cc-bubble: #ffffff;+ --cc-bubble-ink: #0b0d14;+ --cc-radius: 14px;+ --cc-gap: 14px;+ --cc-font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Inter, system-ui, sans-serif;+ --cc-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace;+}++:root[data-theme='light'] {+ --cc-bg: #f5f6fb;+ --cc-bg-2: #ffffff;+ --cc-card: rgba(255, 255, 255, 0.92);+ --cc-border: rgba(30, 40, 90, 0.12);+ --cc-border-strong: rgba(30, 40, 90, 0.26);+ --cc-fg: #0e1222;+ --cc-muted: #5a6180;+ --cc-accent: #2563eb;+ --cc-accent-ink: #ffffff;+ --cc-up: #0f9d63;+ --cc-down: #d92d4f;+ --cc-bubble: #0e1222;+ --cc-bubble-ink: #ffffff;+}++* { box-sizing: border-box; }++body {+ margin: 0;+ min-height: 100vh;+ font-family: var(--cc-font);+ color: var(--cc-fg);+ background: radial-gradient(120% 90% at 80% 0%, var(--cc-bg-2) 0%, var(--cc-bg) 60%);+}++body[data-mode='overlay'] {+ background: transparent;+ overflow: hidden;+}++.cc-wrap {+ max-width: 1440px;+ margin: 0 auto;+ padding: 20px 16px 48px;+}++/* ── header ─────────────────────────────────────────────────────────────── */++.cc-top {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: 12px 20px;+ margin-bottom: var(--cc-gap);+}++.cc-title { display: flex; align-items: center; gap: 12px; min-width: 0; }+.cc-title h1 { margin: 0; font-size: clamp(20px, 2.4vw, 28px); letter-spacing: -0.02em; }+.cc-title p { margin: 2px 0 0; color: var(--cc-muted); font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 52ch; }+.cc-kicker { font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--cc-accent); font-weight: 600; }++.cc-live {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 4px 10px;+ border-radius: 999px;+ border: 1px solid var(--cc-border);+ font-size: 11px;+ font-weight: 700;+ letter-spacing: 0.08em;+ color: var(--cc-up);+}+.cc-live::before {+ content: '';+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: currentColor;+ box-shadow: 0 0 0 0 currentColor;+ animation: cc-pulse 1.8s ease-out infinite;+}+.cc-live.is-stale { color: var(--cc-muted); }+.cc-live.is-stale::before { animation: none; }++@keyframes cc-pulse {+ 0% { box-shadow: 0 0 0 0 color-mix(in srgb, currentColor 60%, transparent); }+ 100% { box-shadow: 0 0 0 8px transparent; }+}++.cc-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }++/* ── controls ───────────────────────────────────────────────────────────── */++.cc-btn,+.cc-select {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 6px;+ min-height: 36px;+ padding: 0 14px;+ border-radius: 10px;+ border: 1px solid var(--cc-border-strong);+ background: var(--cc-card);+ color: var(--cc-fg);+ font: 600 13px/1 var(--cc-font);+ text-decoration: none;+ cursor: pointer;+ transition: background 0.15s ease, border-color 0.15s ease, transform 0.08s ease;+}+.cc-btn:hover, .cc-select:hover { border-color: var(--cc-accent); }+.cc-btn:active { transform: translateY(1px); }+.cc-btn:focus-visible, .cc-select:focus-visible, .cc-input:focus-visible, .cc-feed-proof:focus-visible {+ outline: 2px solid var(--cc-accent);+ outline-offset: 2px;+}+.cc-btn.is-primary { background: var(--cc-accent); border-color: var(--cc-accent); color: var(--cc-accent-ink); }+.cc-btn.is-primary:hover { filter: brightness(1.08); }+.cc-btn[aria-pressed='true'] { border-color: var(--cc-up); color: var(--cc-up); }++.cc-form { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: var(--cc-gap); }+.cc-input {+ flex: 1 1 320px;+ min-width: 0;+ min-height: 40px;+ padding: 0 14px;+ border-radius: 10px;+ border: 1px solid var(--cc-border-strong);+ background: var(--cc-card);+ color: var(--cc-fg);+ font: 14px var(--cc-mono);+ transition: border-color 0.15s ease;+}+.cc-input:hover { border-color: var(--cc-accent); }+.cc-input[aria-invalid='true'] { border-color: var(--cc-down); }+.cc-form-msg { flex-basis: 100%; margin: 0; min-height: 1em; font-size: 13px; color: var(--cc-down); }++/* ── layout ─────────────────────────────────────────────────────────────── */++.cc-grid {+ display: grid;+ grid-template-columns: minmax(0, 1fr) 380px;+ grid-template-areas:+ 'stats stats'+ 'chart stage'+ 'chart feed';+ grid-template-rows: auto 380px minmax(0, 1fr);+ gap: var(--cc-gap);+ height: min(860px, calc(100vh - 150px));+ min-height: 640px;+}++.cc-card {+ position: relative;+ border: 1px solid var(--cc-border);+ border-radius: var(--cc-radius);+ background: var(--cc-card);+ overflow: hidden;+}++/* ── stats ──────────────────────────────────────────────────────────────── */++.cc-stats {+ grid-area: stats;+ display: grid;+ grid-template-columns: repeat(5, minmax(0, 1fr));+ gap: 1px;+ background: var(--cc-border);+}+.cc-stat { padding: 12px 16px; background: var(--cc-card); min-width: 0; }+.cc-stat dt { font-size: 11px; color: var(--cc-muted); text-transform: uppercase; letter-spacing: 0.06em; }+.cc-stat dd {+ margin: 4px 0 0;+ font: 600 18px var(--cc-mono);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ font-variant-numeric: tabular-nums;+}+.cc-stat dd[data-tone='up'] { color: var(--cc-up); }+.cc-stat dd[data-tone='down'] { color: var(--cc-down); }+.cc-stat dd.flash { animation: cc-flash 0.6s ease-out; }+@keyframes cc-flash { from { opacity: 0.35; } to { opacity: 1; } }++/* ── chart ──────────────────────────────────────────────────────────────── */++.cc-chart { grid-area: chart; min-height: 420px; }+.cc-chart-frame {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ border: 0;+ opacity: 0;+ transition: opacity 0.35s ease;+}+.cc-chart.is-ready .cc-chart-frame { opacity: 1; }+.cc-chart.is-ready .cc-chart-skel { display: none; }+.cc-chart-state {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 12px;+ padding: 24px;+ text-align: center;+ color: var(--cc-muted);+}+.cc-chart-state p { margin: 0; max-width: 42ch; }+.cc-chart-state .col, .cc-chart-state > div { display: flex; gap: 8px; flex-wrap: wrap; justify-content: center; }++.cc-skel {+ position: absolute;+ inset: 0;+ background: linear-gradient(100deg, transparent 20%, color-mix(in srgb, var(--cc-fg) 6%, transparent) 50%, transparent 80%) var(--cc-card);+ background-size: 220% 100%;+ animation: cc-shimmer 1.4s linear infinite;+}+@keyframes cc-shimmer { from { background-position: 120% 0; } to { background-position: -120% 0; } }++/* ── stage (the avatar) ─────────────────────────────────────────────────── */++.cc-stage {+ grid-area: stage;+ background:+ radial-gradient(60% 55% at 50% 78%, color-mix(in srgb, var(--cc-accent) 22%, transparent) 0%, transparent 70%),+ var(--cc-card);+}+.cc-stage-slot { position: absolute; inset: 0; }+.cc-stage-slot agent-3d { display: block; width: 100%; height: 100%; opacity: 0; transition: opacity 0.5s ease; }+.cc-stage.is-ready .cc-stage-slot agent-3d { opacity: 1; }+.cc-stage-loading, .cc-stage-error {+ position: absolute;+ inset: 0;+ display: none;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 12px;+ padding: 20px;+ text-align: center;+ color: var(--cc-muted);+ font-size: 13px;+}+.cc-stage.is-loading .cc-stage-loading { display: flex; }+.cc-stage.is-error .cc-stage-error { display: flex; }+.cc-silhouette {+ width: 72px;+ height: 150px;+ border-radius: 36px 36px 14px 14px;+ background: color-mix(in srgb, var(--cc-fg) 8%, transparent);+ animation: cc-breathe 1.6s ease-in-out infinite;+}+@keyframes cc-breathe { 50% { opacity: 0.45; transform: scaleY(0.98); } }++.cc-bubble {+ position: absolute;+ top: 14px;+ left: 14px;+ right: 14px;+ z-index: 2;+ padding: 10px 14px;+ border-radius: 14px;+ background: var(--cc-bubble);+ color: var(--cc-bubble-ink);+ font: 700 15px/1.35 var(--cc-font);+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.35);+ opacity: 0;+ transform: translateY(-6px) scale(0.97);+ transform-origin: 50% 100%;+ transition: opacity 0.25s ease, transform 0.25s cubic-bezier(0.2, 0.9, 0.3, 1.3);+ pointer-events: none;+ will-change: transform, opacity;+}+.cc-bubble::after {+ content: '';+ position: absolute;+ bottom: -7px;+ left: 50%;+ width: 14px;+ height: 14px;+ background: inherit;+ transform: translateX(-50%) rotate(45deg);+ border-radius: 2px;+}+.cc-bubble.is-on { opacity: 1; transform: none; }++/* ── feed ───────────────────────────────────────────────────────────────── */++.cc-feed-card { grid-area: feed; display: flex; flex-direction: column; min-height: 220px; }+.cc-feed-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 12px 14px;+ border-bottom: 1px solid var(--cc-border);+ font-size: 12px;+ color: var(--cc-muted);+ text-transform: uppercase;+ letter-spacing: 0.06em;+}+.cc-feed { list-style: none; margin: 0; padding: 4px 0; overflow-y: auto; flex: 1; }+.cc-feed-item {+ display: grid;+ grid-template-columns: 10px minmax(0, 1fr) auto;+ gap: 10px;+ align-items: baseline;+ padding: 9px 14px;+ font-size: 13.5px;+ line-height: 1.35;+ animation: cc-in 0.35s ease-out;+}+.cc-feed-item + .cc-feed-item { border-top: 1px solid var(--cc-border); }+@keyframes cc-in { from { opacity: 0; transform: translateY(-4px); } }+.cc-feed-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--cc-muted); align-self: center; }+.tone-up .cc-feed-dot { background: var(--cc-up); }+.tone-down .cc-feed-dot { background: var(--cc-down); }+.cc-feed-meta { display: inline-flex; gap: 8px; color: var(--cc-muted); font-size: 12px; white-space: nowrap; }+.cc-feed-proof { color: var(--cc-muted); text-decoration: none; border-radius: 4px; }+.cc-feed-proof:hover { color: var(--cc-accent); }+.cc-feed-empty { padding: 28px 18px; color: var(--cc-muted); font-size: 13px; text-align: center; line-height: 1.5; }++/* ── share ──────────────────────────────────────────────────────────────── */++.cc-share {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: var(--cc-gap);+ margin-top: var(--cc-gap);+}+.cc-share-card { padding: 16px; }+.cc-share-card h2 { margin: 0 0 6px; font-size: 15px; }+.cc-share-card p { margin: 0 0 12px; color: var(--cc-muted); font-size: 13px; line-height: 1.5; }+.cc-share-card code { font-family: var(--cc-mono); font-size: 12px; }++/* ── fatal ──────────────────────────────────────────────────────────────── */++.cc-fatal {+ max-width: 560px;+ margin: 8vh auto 0;+ padding: 28px;+ text-align: center;+}+.cc-fatal h2 { margin: 0 0 8px; }+.cc-fatal p { color: var(--cc-muted); margin: 0 0 18px; line-height: 1.5; }+body.is-fatal .cc-grid, body.is-fatal .cc-share { display: none; }++/* ── embed + overlay modes ──────────────────────────────────────────────── */++.cc-powered { display: none; }++body[data-mode='embed'] .cc-wrap { padding: 10px; max-width: none; }+body[data-mode='embed'] .cc-form,+body[data-mode='embed'] .cc-share,+body[data-mode='embed'] .cc-feed-card,+body[data-mode='embed'] .cc-hide-embed { display: none; }+body[data-mode='embed'] .cc-top { margin-bottom: 10px; }+body[data-mode='embed'] .cc-grid {+ grid-template-columns: minmax(0, 1fr) minmax(220px, 32%);+ grid-template-areas: 'stats stats' 'chart stage';+ grid-template-rows: auto minmax(0, 1fr);+ height: calc(100vh - 76px);+ min-height: 0;+}+body[data-mode='embed'] .cc-powered { display: inline-flex; }++body[data-mode='overlay'] .cc-wrap { padding: 0; max-width: none; height: 100vh; }+body[data-mode='overlay'] .cc-top,+body[data-mode='overlay'] .cc-form,+body[data-mode='overlay'] .cc-share,+body[data-mode='overlay'] .cc-feed-card,+body[data-mode='overlay'] .cc-chart,+body[data-mode='overlay'] .cc-stats { display: none; }+body[data-mode='overlay'] .cc-grid { display: block; height: 100vh; min-height: 0; }+body[data-mode='overlay'] .cc-stage { position: absolute; inset: 0; border: 0; border-radius: 0; background: transparent; }+body[data-mode='overlay'] .cc-bubble { font-size: clamp(16px, 4.2vw, 26px); top: 4%; left: 6%; right: 6%; }+body[data-mode='overlay'] .cc-ticker { display: flex; }++.cc-ticker {+ display: none;+ position: absolute;+ left: 50%;+ bottom: 3%;+ transform: translateX(-50%);+ z-index: 2;+ align-items: center;+ gap: 12px;+ padding: 8px 16px;+ border-radius: 999px;+ background: rgba(8, 10, 18, 0.78);+ color: #fff;+ font: 700 clamp(13px, 3.2vw, 18px) var(--cc-mono);+ white-space: nowrap;+}+.cc-ticker [data-tone='up'] { color: #2ee59d; }+.cc-ticker [data-tone='down'] { color: #ff5c7a; }++/* ── responsive ─────────────────────────────────────────────────────────── */++@media (max-width: 1080px) {+ .cc-share { grid-template-columns: 1fr; }+}++@media (max-width: 900px) {+ .cc-grid {+ grid-template-columns: minmax(0, 1fr);+ grid-template-areas: 'stage' 'stats' 'chart' 'feed';+ grid-template-rows: 340px auto 460px 380px;+ height: auto;+ min-height: 0;+ }+ .cc-stats { grid-template-columns: repeat(3, minmax(0, 1fr)); }+ body[data-mode='embed'] .cc-grid {+ grid-template-columns: minmax(0, 1fr);+ grid-template-areas: 'stage' 'chart';+ grid-template-rows: 260px minmax(320px, 1fr);+ height: auto;+ }+ body[data-mode='embed'] .cc-stats { display: none; }+}++@media (max-width: 480px) {+ .cc-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); }+ .cc-stat:last-child { grid-column: span 2; }+ .cc-actions { width: 100%; }+ .cc-actions .cc-btn, .cc-actions .cc-select { flex: 1 1 auto; }+}++@media (prefers-reduced-motion: reduce) {+ .cc-live::before, .cc-skel, .cc-silhouette, .cc-feed-item, .cc-stat dd.flash { animation: none; }+ .cc-bubble { transition: opacity 0.2s ease; transform: none; }+}diff --git a/src/chart-companion/main.js b/src/chart-companion/main.jsnew file mode 100644index 000000000..e80eacc4e--- /dev/null+++ b/src/chart-companion/main.js@@ -0,0 +1,546 @@+// Chart Companion: a live DEXTools chart with a 3D agent beside it that reacts+// to every real swap on the coin.+//+// Data path (all real, all keyless):+// /api/coin/pair pair address -> the token it trades (+ symbol)+// /api/coin/pool token -> its most liquid pool (the chart's pair)+// /api/pump/price-history 15m candles -> 24h range, so "new high" is real+// /api/pump/dex-trades recent swaps, polled -> reactions (./reactor.js)+//+// Three modes from one URL:+// (default) the full page: chart, avatar, live reaction feed, share tools+// ?embed=1 chart + avatar only, framable on any site+// ?overlay=1 avatar + speech bubble on a transparent background, sized for+// an OBS browser source over a streamer's own chart+//+// Addressed like /coin3d: ?pair=<DEXTools pair>, ?mint=<token>, or ?url=<a+// pasted DEXTools link>. With none, it watches $THREE.++import './chart-companion.css';+import { createReactor, fmtUsd, fmtPrice, fmtPct } from './reactor.js';+import { chartEmbedUrls } from '../shared/chart-embeds.js';+import { watchEmbed, embedFallbackNode } from '../shared/embed-guard.js';+import { dextoolsTokenUrl } from '../shared/trading-terminals.js';+import { parseTarget, SOL_RE } from './target.js';++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const POLL_MS = 5000;+const FEED_MAX = 40;+const AGENT_SCRIPT = 'https://three.ws/agent-3d/latest/agent-3d.js';+const CLIP_MANIFEST = '/animations/manifest.json';++/** Humanoid bodies the shared clip library retargets cleanly. */+const AVATARS = {+ default: { label: 'Default', glb: '/avatars/default.glb' },+ michelle: { label: 'Michelle', glb: '/avatars/michelle.glb' },+ 'realistic-female': { label: 'Realistic (F)', glb: '/avatars/realistic-female.glb' },+ 'realistic-male': { label: 'Realistic (M)', glb: '/avatars/realistic-male.glb' },+ mannequin: { label: 'Mannequin', glb: '/avatars/mannequin.glb' },+};++const params = new URLSearchParams(location.search);+const MODE = params.get('overlay') === '1' ? 'overlay' : params.get('embed') === '1' ? 'embed' : 'page';+const AGENT_ID = (params.get('agent') || '').trim();+const AVATAR_KEY = AVATARS[params.get('avatar')] ? params.get('avatar') : 'default';+const REDUCED_MOTION = window.matchMedia('(prefers-reduced-motion: reduce)').matches;++const $ = (sel, root = document) => root.querySelector(sel);++function el(tag, attrs = {}, children = []) {+ const n = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) {+ if (v == null || v === false) continue;+ if (k === 'text') n.textContent = v;+ else if (k === 'class') n.className = v;+ else if (k.startsWith('on')) n.addEventListener(k.slice(2), v);+ else n.setAttribute(k, v === true ? '' : v);+ }+ for (const c of [].concat(children)) if (c != null) n.append(c);+ return n;+}++const short = (a) => (a && a.length > 10 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a || '');++async function getJson(url) {+ const r = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(12_000) });+ if (r.status === 404) return null;+ if (!r.ok) throw Object.assign(new Error(`${url.split('?')[0]} answered ${r.status}`), { status: r.status });+ return r.json();+}++const pairInfo = (pair) => getJson(`/api/coin/pair?address=${encodeURIComponent(pair)}&network=solana`);+const topPool = async (mint) => (await getJson(`/api/coin/pool?address=${encodeURIComponent(mint)}&network=solana`))?.pool || null;++/**+ * @returns {Promise<{ mint: string, pair: string|null, symbol: string, name: string, pairName: string }>}+ */+async function resolveMarket(target) {+ if (target.pair || target.address) {+ const info = await pairInfo(target.pair || target.address);+ if (info?.token?.address) {+ return {+ mint: info.token.address,+ pair: info.pair || target.pair || target.address,+ symbol: info.token.symbol || '',+ name: info.token.name || '',+ pairName: info.pairName || '',+ };+ }+ if (target.pair) throw new Error('No indexed market for that pair yet. A brand-new pair can take a few minutes to appear.');+ }+ const mint = target.mint || target.address;+ const pair = await topPool(mint);+ const info = pair ? await pairInfo(pair).catch(() => null) : null;+ return {+ mint,+ pair,+ symbol: info?.token?.symbol || '',+ name: info?.token?.name || '',+ pairName: info?.pairName || '',+ };+}++function initialTarget() {+ if (params.get('url')) return parseTarget(params.get('url'));+ if (params.get('pair')) {+ const t = parseTarget(params.get('pair'));+ return t.address ? { pair: t.address } : t;+ }+ if (params.get('mint')) return SOL_RE.test(params.get('mint').trim()) ? { mint: params.get('mint').trim() } : { error: 'That mint is not a valid Solana address.' };+ return { mint: THREE_MINT };+}++// ── URLs for sharing ────────────────────────────────────────────────────────++function companionUrl(market, extra = {}) {+ const q = new URLSearchParams();+ if (market.pair) q.set('pair', market.pair);+ else q.set('mint', market.mint);+ if (AGENT_ID) q.set('agent', AGENT_ID);+ else if (AVATAR_KEY !== 'default') q.set('avatar', AVATAR_KEY);+ for (const [k, v] of Object.entries(extra)) q.set(k, v);+ return `${location.origin}/chart-companion?${q}`;+}++// ── the avatar ──────────────────────────────────────────────────────────────++let agentScript = null;+function loadAgentElement() {+ if (customElements.get('agent-3d')) return Promise.resolve();+ agentScript ||= new Promise((resolve, reject) => {+ const s = el('script', { type: 'module', src: AGENT_SCRIPT });+ s.addEventListener('load', resolve);+ s.addEventListener('error', () => reject(new Error('The 3D runtime did not load.')));+ document.head.append(s);+ }).then(() => customElements.whenDefined('agent-3d'));+ return agentScript;+}++async function clipDurations() {+ try {+ const list = await getJson(CLIP_MANIFEST);+ return new Map((list || []).map((c) => [c.name, { ms: (Number(c.duration) || 2) * 1000, loop: !!c.loop }]));+ } catch {+ return new Map();+ }+}++/**+ * Plays reactions on the avatar without letting a burst of trades thrash it:+ * a reaction interrupts only a lower-priority one, and looping clips are+ * ended by hand and settled back to idle.+ */+function createPerformer(host, bubble, { onSpeak }) {+ let agent = null;+ let ready = false;+ let busyUntil = 0;+ let busyPriority = 0;+ let settleTimer = null;+ let bubbleTimer = null;+ let durations = new Map();++ async function mount() {+ host.classList.remove('is-error');+ host.classList.add('is-loading');+ durations = await clipDurations();+ try {+ await loadAgentElement();+ } catch (err) {+ fail(err.message);+ return;+ }+ agent = document.createElement('agent-3d');+ if (AGENT_ID) agent.setAttribute('agent-id', AGENT_ID);+ else agent.setAttribute('body', AVATARS[AVATAR_KEY].glb);+ agent.setAttribute('background', 'transparent');+ agent.setAttribute('eager', '');+ agent.setAttribute('mode', 'inline');+ agent.setAttribute('height', '100%');+ agent.setAttribute('responsive', 'false');+ agent.setAttribute('kiosk', '');+ agent.addEventListener('agent:ready', () => {+ ready = true;+ host.classList.remove('is-loading');+ host.classList.add('is-ready');+ });+ agent.addEventListener('agent:error', () => fail('This avatar could not load. Try another one from the picker.'));+ host.querySelector('.cc-stage-slot').replaceChildren(agent);+ }++ function fail(msg) {+ host.classList.remove('is-loading');+ host.classList.add('is-error');+ $('.cc-stage-error-msg', host).textContent = msg;+ }++ function say(line) {+ bubble.textContent = line;+ bubble.classList.remove('is-on');+ void bubble.offsetWidth; // restart the entrance transition+ bubble.classList.add('is-on');+ clearTimeout(bubbleTimer);+ bubbleTimer = setTimeout(() => bubble.classList.remove('is-on'), 6500);+ }++ /** @returns {boolean} whether the reaction was performed (vs. dropped as noise) */+ function perform(reaction) {+ const now = Date.now();+ if (now < busyUntil && reaction.priority <= busyPriority) return false;+ const d = durations.get(reaction.clip);+ const ms = reaction.holdMs || d?.ms || 2500;+ busyUntil = now + Math.min(ms, 7000);+ busyPriority = reaction.priority;+ say(reaction.line);+ onSpeak(reaction.line);+ if (ready && agent) {+ clearTimeout(settleTimer);+ try {+ agent.playClip(reaction.clip, { fade_ms: 250 });+ if (reaction.emotion) agent.expressEmotion(reaction.emotion[0], reaction.emotion[1]);+ if (reaction.holdMs || d?.loop) settleTimer = setTimeout(() => agent.playClip('idle', { fade_ms: 500 }), ms);+ } catch {+ // A clip the rig cannot take still leaves the line on screen.+ }+ }+ return true;+ }++ function swap(key) {+ const url = new URL(location.href);+ url.searchParams.delete('agent');+ if (key === 'default') url.searchParams.delete('avatar');+ else url.searchParams.set('avatar', key);+ location.assign(url);+ }++ return { mount, perform, swap, get ready() { return ready; } };+}++// ── voice ───────────────────────────────────────────────────────────────────++function createVoice() {+ const supported = 'speechSynthesis' in window;+ let on = supported && params.get('voice') === '1';+ return {+ supported,+ get on() { return on; },+ toggle() {+ on = supported && !on;+ if (!on) speechSynthesis.cancel();+ return on;+ },+ speak(line) {+ if (!on) return;+ speechSynthesis.cancel();+ const u = new SpeechSynthesisUtterance(line);+ u.rate = 1.08;+ u.pitch = 1.05;+ speechSynthesis.speak(u);+ },+ };+}++// ── the DEXTools chart ──────────────────────────────────────────────────────++function mountChart(host, market) {+ const theme = document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark';+ const urls = market.pair && chartEmbedUrls('dextools', { chain: 'solana', token: market.mint, pool: market.pair, theme });+ const openHref = dextoolsTokenUrl(market.mint, { from: 'chart-companion' });+ let cancel = () => {};+ const fail = () => {+ cancel();+ host.classList.remove('is-ready');+ host.replaceChildren(embedFallbackNode({+ name: 'The DEXTools chart',+ href: openHref,+ label: 'Open the chart on DEXTools',+ onRetry: () => mountChart(host, market),+ className: 'cc-chart-state',+ buttonClassName: 'cc-btn',+ }));+ };+ if (!urls) {+ host.replaceChildren(el('div', { class: 'cc-chart-state', role: 'status' }, [+ el('p', { text: 'This coin has no pool to chart yet. The companion still reacts to its swaps as they land.' }),+ el('a', { class: 'cc-btn', href: openHref, target: '_blank', rel: 'noopener', text: 'Check DEXTools ↗' }),+ ]));+ return;+ }+ const frame = el('iframe', {+ class: 'cc-chart-frame',+ src: urls.embed,+ title: `${market.symbol ? `$${market.symbol.toUpperCase()}` : 'Token'} live chart by DEXTools`,+ allow: 'clipboard-write; fullscreen',+ });+ // DEXTools' edge refuses a loopback Referer; every deployed origin sends its own.+ frame.referrerPolicy = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname) ? 'no-referrer' : 'strict-origin-when-cross-origin';+ frame.addEventListener('load', () => { cancel(); host.classList.add('is-ready'); });+ frame.addEventListener('error', fail);+ host.replaceChildren(el('div', { class: 'cc-skel cc-chart-skel' }), frame);+ cancel = watchEmbed(host, { onTimeout: fail });+}++// ── feed + stats ────────────────────────────────────────────────────────────++const KIND_TONE = {+ whaleBuy: 'up', bigBuy: 'up', buyStreak: 'up', newHigh: 'up',+ whaleSell: 'down', bigSell: 'down', sellStreak: 'down',+ greeting: 'neutral', quiet: 'neutral',+};++function timeAgo(ms) {+ const s = Math.max(0, Math.round((Date.now() - ms) / 1000));+ if (s < 60) return `${s}s ago`;+ const m = Math.round(s / 60);+ return m < 60 ? `${m}m ago` : `${Math.round(m / 60)}h ago`;+}++function feedItem(r) {+ const sig = r.trade?.signature;+ return el('li', { class: `cc-feed-item tone-${KIND_TONE[r.kind] || 'neutral'}`, 'data-at': String(r.at) }, [+ el('span', { class: 'cc-feed-dot', 'aria-hidden': 'true' }),+ el('span', { class: 'cc-feed-line', text: r.line }),+ el('span', { class: 'cc-feed-meta' }, [+ el('time', { class: 'cc-feed-time', text: timeAgo(r.at) }),+ sig ? el('a', { class: 'cc-feed-proof', href: `https://solscan.io/tx/${encodeURIComponent(sig)}`, target: '_blank', rel: 'noopener', title: 'See this swap on-chain', text: 'tx ↗' }) : null,+ ]),+ ]);+}++function renderStats(stats) {+ const set = (key, val, tone) => {+ for (const n of document.querySelectorAll(`[data-stat="${key}"]`)) {+ if (n.textContent !== val) {+ n.textContent = val;+ n.classList.remove('flash');+ void n.offsetWidth;+ n.classList.add('flash');+ }+ if (tone !== undefined) n.dataset.tone = tone;+ }+ };+ set('price', stats.lastPrice ? fmtPrice(stats.lastPrice) : '-');+ set('change', stats.change24 == null ? '-' : fmtPct(stats.change24), stats.change24 == null ? '' : stats.change24 >= 0 ? 'up' : 'down');+ set('trades', `${stats.buys} / ${stats.sells}`);+ const net = stats.buyUsd - stats.sellUsd;+ set('net', `${net >= 0 ? '+' : '-'}${fmtUsd(net)}`, net >= 0 ? 'up' : 'down');+ set('biggest', stats.biggest ? `${fmtUsd(stats.biggest.sol_value_usd)} ${stats.biggest.is_buy ? 'buy' : 'sell'}` : '-');+}++// ── page shell ──────────────────────────────────────────────────────────────++async function copy(text, btn) {+ const label = btn.textContent;+ try {+ await navigator.clipboard.writeText(text);+ btn.textContent = 'Copied';+ } catch {+ btn.textContent = 'Copy failed';+ }+ setTimeout(() => { btn.textContent = label; }, 1500);+}++function wireControls(market, voice, performer) {+ const form = $('#cc-form');+ form?.addEventListener('submit', (e) => {+ e.preventDefault();+ const input = $('#cc-input');+ const t = parseTarget(input.value);+ const msg = $('#cc-form-msg');+ if (t.error) {+ msg.textContent = t.error;+ input.setAttribute('aria-invalid', 'true');+ input.focus();+ return;+ }+ const q = new URLSearchParams();+ if (t.pair) q.set('pair', t.pair);+ else q.set('mint', t.address);+ if (params.get('avatar')) q.set('avatar', params.get('avatar'));+ if (AGENT_ID) q.set('agent', AGENT_ID);+ location.assign(`/chart-companion?${q}`);+ });+ $('#cc-input')?.addEventListener('input', (e) => {+ e.target.removeAttribute('aria-invalid');+ $('#cc-form-msg').textContent = '';+ });++ const voiceBtn = $('#cc-voice');+ if (voiceBtn) {+ if (!voice.supported) voiceBtn.hidden = true;+ const paint = () => {+ voiceBtn.setAttribute('aria-pressed', String(voice.on));+ voiceBtn.textContent = voice.on ? 'Voice on' : 'Voice off';+ };+ paint();+ voiceBtn.addEventListener('click', () => { voice.toggle(); paint(); if (voice.on) voice.speak('Voice on. I will call out the big trades.'); });+ }++ const pick = $('#cc-avatar');+ if (pick) {+ for (const [key, a] of Object.entries(AVATARS)) pick.append(el('option', { value: key, text: a.label, selected: !AGENT_ID && key === AVATAR_KEY }));+ if (AGENT_ID) pick.prepend(el('option', { value: '', text: 'Your agent', selected: true }));+ pick.addEventListener('change', () => pick.value && performer.swap(pick.value));+ }++ const dt = $('#cc-dextools');+ if (dt) dt.href = dextoolsTokenUrl(market.mint, { from: 'chart-companion' });++ $('#cc-copy-link')?.addEventListener('click', (e) => copy(companionUrl(market), e.currentTarget));+ $('#cc-copy-overlay')?.addEventListener('click', (e) => copy(companionUrl(market, { overlay: '1' }), e.currentTarget));+ $('#cc-copy-embed')?.addEventListener('click', (e) => copy(+ `<iframe src="${companionUrl(market, { embed: '1' })}" width="960" height="540" style="border:0;border-radius:12px" loading="lazy" allow="clipboard-write; fullscreen" title="Live chart companion by three.ws"></iframe>`,+ e.currentTarget,+ ));+}++function paintIdentity(market) {+ const sym = market.symbol ? `$${market.symbol.toUpperCase()}` : short(market.mint);+ document.title = `${sym} Chart Companion · three.ws`;+ for (const n of document.querySelectorAll('[data-symbol]')) n.textContent = sym;+ const sub = $('#cc-sub');+ if (sub) sub.textContent = [market.name, market.pairName].filter(Boolean).join(' · ') || short(market.mint);+ const input = $('#cc-input');+ if (input && !input.value) input.placeholder = 'Paste a DEXTools link, pair, or mint';+ const full = $('#cc-full');+ if (full) full.href = companionUrl(market);+}++function showFatal(message) {+ document.body.classList.add('is-fatal');+ for (const n of document.querySelectorAll('h1[data-symbol]')) n.textContent = 'Chart Companion';+ $('#cc-sub').textContent = 'A 3D agent that reacts to every real swap';+ $('#cc-live').hidden = true;+ $('#cc-fatal-msg').textContent = message;+ $('#cc-fatal').hidden = false;+ $('#cc-input')?.focus();+}++// ── run ─────────────────────────────────────────────────────────────────────++async function run() {+ document.body.dataset.mode = MODE;+ if (MODE === 'page') {+ const nav = el('script', { src: '/nav.js' });+ document.body.append(nav);+ }++ const target = initialTarget();+ if (target.error) return showFatal(target.error);++ let market;+ try {+ market = await resolveMarket(target);+ } catch (err) {+ return showFatal(err.status === 429+ ? 'Market data is busy right now. Give it a few seconds and reload.'+ : err.message || 'Could not find a market for that address.');+ }+ paintIdentity(market);++ const voice = createVoice();+ const performer = createPerformer($('#cc-stage'), $('#cc-bubble'), { onSpeak: (line) => voice.speak(line) });+ wireControls(market, voice, performer);+ $('#cc-stage-retry')?.addEventListener('click', () => performer.mount());+ if (MODE !== 'overlay') mountChart($('#cc-chart'), market);+ performer.mount();++ const reactor = createReactor({ symbol: market.symbol, now: () => Date.now() });+ const feed = $('#cc-feed');+ const seen = new Set();+ let primed = false;++ const post = (reactions) => {+ for (const r of reactions) {+ if (feed) {+ $('#cc-feed-empty')?.remove();+ feed.prepend(feedItem(r));+ while (feed.children.length > FEED_MAX) feed.lastElementChild.remove();+ }+ }+ const top = reactions[0];+ if (top) performer.perform(top);+ };++ try {+ const hist = await getJson(`/api/pump/price-history?mint=${encodeURIComponent(market.mint)}&interval=15m`);+ reactor.ingestCandles(hist?.data);+ } catch {+ // No candles just means no 24h baseline: the greeting skips the change+ // and "new high" waits for one. Reactions to swaps are unaffected.+ }+ renderStats(reactor.stats);++ const live = $('#cc-live');+ let misses = 0;+ async function poll() {+ try {+ const body = await getJson(`/api/pump/dex-trades?mint=${encodeURIComponent(market.mint)}&limit=40`);+ misses = 0;+ const trades = (body?.trades || []).filter((t) => t.signature && !seen.has(t.signature));+ for (const t of trades) seen.add(t.signature);+ if (seen.size > 4000) {+ const keep = [...seen].slice(-2000);+ seen.clear();+ keep.forEach((s) => seen.add(s));+ }+ if (!primed) {+ // The backlog sizes the tape; it does not get cheered.+ reactor.prime(trades);+ primed = true;+ post([reactor.greeting()]);+ } else if (trades.length) {+ post(reactor.ingestTrades(trades));+ } else {+ const q = reactor.tick();+ if (q) post([q]);+ }+ live?.classList.toggle('is-stale', body?.stale === true);+ renderStats(reactor.stats);+ } catch {+ misses += 1;+ live?.classList.add('is-stale');+ if (misses === 3 && feed && !feed.children.length) {+ feed.replaceChildren(el('li', { class: 'cc-feed-empty', id: 'cc-feed-empty', text: 'Live swaps are unavailable right now. Retrying every few seconds.' }));+ }+ }+ }++ let timer = null;+ const start = () => { if (!timer) { poll(); timer = setInterval(poll, POLL_MS); } };+ const stop = () => { clearInterval(timer); timer = null; };+ document.addEventListener('visibilitychange', () => (document.hidden && MODE !== 'overlay' ? stop() : start()));+ start();++ // Keep "12s ago" honest without re-rendering the feed.+ setInterval(() => {+ for (const n of document.querySelectorAll('.cc-feed-item')) {+ const t = $('.cc-feed-time', n);+ if (t) t.textContent = timeAgo(Number(n.dataset.at));+ }+ }, 15_000);++ if (REDUCED_MOTION) document.body.classList.add('cc-reduced');+}++run();diff --git a/src/chart-companion/reactor.js b/src/chart-companion/reactor.jsnew file mode 100644index 000000000..9fb2bd4fe--- /dev/null+++ b/src/chart-companion/reactor.js@@ -0,0 +1,250 @@+// The Chart Companion's reaction engine: real swaps in, avatar reactions out.+//+// Pure and DOM-free so it can be tested against recorded trade frames. The page+// feeds it every fresh swap from /api/pump/dex-trades and the day's candles from+// /api/pump/price-history; it answers with what the avatar should do (a clip+// from the shared animation library, a facial emotion, and one line to say).+//+// Thresholds are relative to the coin's own tape, never absolute: a $300 buy is+// noise on a coin doing $5M a day and a whale on one doing $20K. A trade is+// "big" or "whale" against the rolling median of recent trade sizes, with a+// dollar floor so a dead tape of $2 trades never cries whale.+//+// Every line is built from the trade that caused it. Nothing here predicts,+// recommends, or invents a number: the companion narrates what just happened.++export const WINDOW = 60; // trades kept for the rolling median+const MIN_SAMPLE = 8; // below this the median is not trusted; floors decide alone+const BIG_MULT = 3;+const WHALE_MULT = 8;+export const BIG_FLOOR_USD = 150;+export const WHALE_FLOOR_USD = 1000;+export const STREAK = 5;+export const QUIET_MS = 120_000;+const HIGH_COOLDOWN_MS = 60_000;++/**+ * What each reaction does. `clip` names a clip in /animations/manifest.json;+ * `holdMs` is set only for looping clips, which the page must end itself.+ * Higher `priority` interrupts lower.+ */+export const REACTION_KINDS = {+ whaleBuy: { priority: 5, clip: 'av-superhero-jump', emotion: ['celebration', 1] },+ whaleSell: { priority: 5, clip: 'defeated', emotion: ['concern', 1] },+ newHigh: { priority: 4, clip: 'av-brag-claps', emotion: ['celebration', 0.9] },+ bigBuy: { priority: 3, clip: 'celebrate', emotion: ['celebration', 0.7] },+ bigSell: { priority: 3, clip: 'facepalm', emotion: ['concern', 0.7] },+ buyStreak: { priority: 2, clip: 'dance', holdMs: 6000, emotion: ['celebration', 0.6] },+ sellStreak: { priority: 2, clip: 'shrug', emotion: ['concern', 0.5] },+ greeting: { priority: 1, clip: 'wave', emotion: ['curiosity', 0.6] },+ quiet: { priority: 1, clip: 'think', emotion: ['patience', 0.5] },+};++const LINES = {+ whaleBuy: [+ (c) => `Whale alert. ${c.usd} buy on ${c.sym}.`,+ (c) => `Somebody just bought ${c.usd} of ${c.sym} in one swap.`,+ (c) => `${c.usd} in a single buy. ${c.sym} has company.`,+ ],+ whaleSell: [+ (c) => `Big exit. ${c.usd} of ${c.sym} just sold.`,+ (c) => `A whale took ${c.usd} off the table.`,+ (c) => `${c.usd} sell on ${c.sym}. That one hurt.`,+ ],+ newHigh: [+ (c) => `${c.sym} just printed a new 24-hour high at ${c.price}.`,+ (c) => `New high of the day for ${c.sym}: ${c.price}.`,+ ],+ bigBuy: [+ (c) => `${c.usd} buy. Nice.`,+ (c) => `Solid ${c.usd} buy on ${c.sym}.`,+ (c) => `Buyer stepping in with ${c.usd}.`,+ ],+ bigSell: [+ (c) => `${c.usd} sell. Somebody blinked.`,+ (c) => `${c.usd} just left ${c.sym}.`,+ (c) => `Seller out for ${c.usd}.`,+ ],+ buyStreak: [+ (c) => `${c.n} buys in a row on ${c.sym}.`,+ (c) => `Buy streak. ${c.n} straight.`,+ ],+ sellStreak: [+ (c) => `${c.n} sells in a row. Rough stretch.`,+ (c) => `Sellers have the last ${c.n} swaps.`,+ ],+ greeting: [+ (c) => (c.change == null+ ? `Watching ${c.sym} live. I will call out every big trade.`+ : `${c.sym} is ${c.change} over 24 hours. I will call out every big trade.`),+ ],+ quiet: [+ (c) => `Quiet on ${c.sym}. Watching the chart.`,+ (c) => `No swaps for a couple of minutes on ${c.sym}.`,+ ],+};++/** "$1.2K", "$430", "$3.4M". */+export function fmtUsd(n) {+ const v = Math.abs(Number(n) || 0);+ if (v >= 1e6) return `$${(v / 1e6).toFixed(v >= 1e7 ? 0 : 1)}M`;+ if (v >= 1e3) return `$${(v / 1e3).toFixed(v >= 1e4 ? 0 : 1)}K`;+ return `$${v.toFixed(0)}`;+}++/** Token price with enough significant digits for sub-cent memecoins. */+export function fmtPrice(p) {+ const v = Number(p);+ if (!Number.isFinite(v) || v <= 0) return '';+ if (v >= 1) return `$${v.toFixed(v >= 100 ? 0 : 2)}`;+ return `$${v.toPrecision(3)}`;+}++/** "+12.4%" / "-3.1%". */+export function fmtPct(p) {+ const v = Number(p);+ if (!Number.isFinite(v)) return '';+ return `${v >= 0 ? '+' : ''}${v.toFixed(Math.abs(v) >= 10 ? 0 : 1)}%`;+}++function median(xs) {+ if (!xs.length) return 0;+ const s = [...xs].sort((a, b) => a - b);+ const m = s.length >> 1;+ return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;+}++/** USD price per token implied by one swap, or null when the trade cannot say. */+export function tradePrice(t) {+ const usd = Number(t?.sol_value_usd);+ const amt = Number(t?.token_amount);+ return usd > 0 && amt > 0 ? usd / amt : null;+}++/**+ * @param {{ symbol?: string, now?: () => number }} [opts]+ */+export function createReactor({ symbol = '', now = () => Date.now() } = {}) {+ const sym = symbol ? `$${String(symbol).replace(/^\$/, '').toUpperCase()}` : 'this coin';+ const sizes = [];+ const lineIdx = {};+ let high24 = null;+ let open24 = null;+ let lastHighAt = -Infinity;+ let lastTradeAt = now();+ let lastQuietAt = -Infinity;+ let streakSide = null;+ let streakLen = 0;+ let streakFired = false;++ const stats = { buys: 0, sells: 0, buyUsd: 0, sellUsd: 0, biggest: null, lastPrice: null, change24: null };++ function react(kind, ctx = {}) {+ const pool = LINES[kind];+ const i = lineIdx[kind] = ((lineIdx[kind] ?? -1) + 1) % pool.length;+ const spec = REACTION_KINDS[kind];+ return {+ kind,+ priority: spec.priority,+ clip: spec.clip,+ holdMs: spec.holdMs || 0,+ emotion: spec.emotion,+ line: pool[i]({ sym, ...ctx }),+ trade: ctx.trade || null,+ at: now(),+ };+ }++ /** Seed the day's range from 15m candles (oldest first, `{ o, h, l, c }`). */+ function ingestCandles(candles) {+ const rows = (Array.isArray(candles) ? candles : []).filter((c) => Number(c?.h) > 0);+ if (!rows.length) return;+ const day = rows.slice(-96); // 96 x 15m = 24h+ high24 = Math.max(...day.map((c) => Number(c.h)));+ open24 = Number(day[0].o) || null;+ const last = Number(day[day.length - 1].c);+ if (last > 0) {+ stats.lastPrice = last;+ stats.change24 = open24 ? ((last - open24) / open24) * 100 : null;+ }+ }++ function greeting() {+ return react('greeting', { change: stats.change24 == null ? null : fmtPct(stats.change24) });+ }++ function classify(t) {+ const usd = Number(t.sol_value_usd) || 0;+ const med = sizes.length >= MIN_SAMPLE ? median(sizes) : 0;+ const ctx = { usd: fmtUsd(usd), trade: t };+ const price = tradePrice(t);+ const out = [];++ if (usd >= Math.max(WHALE_FLOOR_USD, WHALE_MULT * med)) out.push(react(t.is_buy ? 'whaleBuy' : 'whaleSell', ctx));+ else if (usd >= Math.max(BIG_FLOOR_USD, BIG_MULT * med)) out.push(react(t.is_buy ? 'bigBuy' : 'bigSell', ctx));++ if (price != null) {+ stats.lastPrice = price;+ if (open24) stats.change24 = ((price - open24) / open24) * 100;+ if (high24 != null && t.is_buy && price > high24) {+ high24 = price;+ if (now() - lastHighAt >= HIGH_COOLDOWN_MS) {+ lastHighAt = now();+ out.push(react('newHigh', { ...ctx, price: fmtPrice(price) }));+ }+ }+ }++ const side = t.is_buy ? 'buy' : 'sell';+ if (side === streakSide) streakLen += 1;+ else { streakSide = side; streakLen = 1; streakFired = false; }+ if (streakLen >= STREAK && !streakFired) {+ streakFired = true;+ out.push(react(t.is_buy ? 'buyStreak' : 'sellStreak', { ...ctx, n: streakLen }));+ }++ sizes.push(usd);+ if (sizes.length > WINDOW) sizes.shift();+ return out;+ }++ /**+ * Feed fresh swaps (any order). Updates the running stats and returns the+ * reactions they earned, highest priority first.+ */+ function ingestTrades(trades) {+ const fresh = (Array.isArray(trades) ? trades : [])+ .filter((t) => t && Number(t.sol_value_usd) >= 0)+ .sort((a, b) => (a.timestamp || 0) - (b.timestamp || 0));+ const out = [];+ for (const t of fresh) {+ const usd = Number(t.sol_value_usd) || 0;+ if (t.is_buy) { stats.buys += 1; stats.buyUsd += usd; } else { stats.sells += 1; stats.sellUsd += usd; }+ if (!stats.biggest || usd > Number(stats.biggest.sol_value_usd)) stats.biggest = t;+ out.push(...classify(t));+ }+ if (fresh.length) lastTradeAt = now();+ return out.sort((a, b) => b.priority - a.priority);+ }++ /** Called on a timer: a quiet-tape line, at most once per quiet stretch. */+ function tick() {+ const t = now();+ if (t - lastTradeAt < QUIET_MS || lastQuietAt > lastTradeAt) return null;+ lastQuietAt = t;+ return react('quiet');+ }++ /** Prime the size window with history without reacting to it. */+ function prime(trades) {+ for (const t of (Array.isArray(trades) ? trades : []).sort((a, b) => (a.timestamp || 0) - (b.timestamp || 0))) {+ sizes.push(Number(t.sol_value_usd) || 0);+ if (sizes.length > WINDOW) sizes.shift();+ const p = tradePrice(t);+ if (p != null) stats.lastPrice = p;+ }+ lastTradeAt = now();+ }++ return { ingestCandles, ingestTrades, tick, prime, greeting, stats, get symbol() { return sym; } };+}diff --git a/src/chart-companion/target.js b/src/chart-companion/target.jsnew file mode 100644index 000000000..c6de6d786--- /dev/null+++ b/src/chart-companion/target.js@@ -0,0 +1,27 @@+// What a visitor pasted into the Chart Companion, turned into an address query.+//+// A DEXTools link names its chain and pair outright (both the app's+// pair-explorer URL and the widget-chart URL are accepted, with or without the+// locale segment). A bare base58 string could be a pair or a mint; the page+// settles which by asking /api/coin/pair first.++export const SOL_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const DEXTOOLS_URL_RE = /dextools\.io\/(?:app|widget-chart)\/(?:[a-z]{2}\/)?([a-z]+)\/(?:pair-explorer|pe-light)\/([1-9A-HJ-NP-Za-km-z]{32,44}|0x[0-9a-fA-F]{40})/i;++/**+ * @param {string} raw+ * @returns {{ pair: string } | { address: string } | { error: string }}+ */+export function parseTarget(raw) {+ const s = String(raw || '').trim();+ if (!s) return { error: 'Paste a DEXTools pair link, a pair address, or a token mint.' };+ const m = DEXTOOLS_URL_RE.exec(s);+ if (m) {+ if (m[1].toLowerCase() !== 'solana') {+ return { error: 'Live reactions run on Solana pairs. That link is for another chain.' };+ }+ return { pair: m[2] };+ }+ if (SOL_RE.test(s)) return { address: s };+ return { error: 'That does not look like a DEXTools link or a Solana address.' };+}diff --git a/src/dextools-hub.js b/src/dextools-hub.jsnew file mode 100644index 000000000..bea801c77--- /dev/null+++ b/src/dextools-hub.js@@ -0,0 +1,335 @@+// /dextools: the three.ws x DEXTools hub.+//+// Four live pieces, each reading real data:+// 1. $THREE both ways: DEXTools' chart widget for the three / SOL pair beside+// the /coin3d scene keyed by that same pair.+// 2. Traffic: what /api/coin/dextools-stats has counted, by day, by surface+// and by coin, over a range the viewer picks.+// 3. The embed builder: paste a DEXTools (or other terminal) link, resolve it+// to a mint and pair, preview the 3D scene or the Social Boost card, copy+// the snippet.+// 4. The Social Boost wins, from the one record /three-token also renders.++import { chartEmbedUrls } from './shared/chart-embeds.js';+import { watchEmbed, embedFallbackNode } from './shared/embed-guard.js';+import { THREE_MINT } from './shared/pnl-snapshot.js';+import { THREE_DEXTOOLS_PAIR, DEXTOOLS_PAIR_URL, SOCIAL_BOOST_WINS, socialBoostSummary } from './pump/dextools-social-boost.js';+import { parseTokenInput, embedSnippets } from './dextools-input.js';++const $ = (id) => document.getElementById(id);+const esc = (s) =>+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+const shortAddr = (a) => `${a.slice(0, 4)}…${a.slice(-4)}`;+const fmtInt = (n) => Number(n || 0).toLocaleString('en-US');+const fmtUsd0 = (n) => `$${Number(n).toLocaleString('en-US', { maximumFractionDigits: 0 })}`;+const theme = () => (document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark');+const loopback = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname);++// ── 1. $THREE both ways ─────────────────────────────────────────────────────++function mountFrame(host, { src, title, name, href, label }) {+ let cancel = () => {};+ const fail = () => {+ cancel();+ host.replaceChildren(+ embedFallbackNode({+ name,+ href,+ label,+ onRetry: () => mountFrame(host, { src, title, name, href, label }),+ className: 'dx-preview-empty',+ buttonClassName: 'dx-btn',+ }),+ );+ host.style.display = 'grid';+ host.style.placeItems = 'center';+ };+ const skel = document.createElement('div');+ skel.className = 'dx-skel';+ skel.style.cssText = 'position:absolute;inset:0';+ const frame = document.createElement('iframe');+ frame.src = src;+ frame.title = title;+ frame.loading = 'lazy';+ frame.allow = 'clipboard-write; fullscreen';+ // DEXTools' edge refuses a loopback Referer; deployed origins send their own.+ frame.referrerPolicy = loopback ? 'no-referrer' : 'strict-origin-when-cross-origin';+ frame.addEventListener('load', () => {+ cancel();+ skel.remove();+ });+ frame.addEventListener('error', fail);+ cancel = watchEmbed(host, { onTimeout: fail });+ host.replaceChildren(skel, frame);+}++function mountThreeBothWays() {+ const chart = chartEmbedUrls('dextools', { chain: 'solana', token: THREE_MINT, pool: THREE_DEXTOOLS_PAIR, theme: theme() });+ const scene = embedSnippets({ mint: THREE_MINT, pair: THREE_DEXTOOLS_PAIR, origin: location.origin }).scene;+ $('dx-pair-link').href = DEXTOOLS_PAIR_URL;+ $('dx-scene-link').href = `/coin3d?pair=${THREE_DEXTOOLS_PAIR}`;+ mountFrame($('dx-chart'), {+ src: chart.embed,+ title: '$THREE live chart by DEXTools',+ name: 'The DEXTools chart',+ href: DEXTOOLS_PAIR_URL,+ label: 'Open $THREE on DEXTools',+ });+ mountFrame($('dx-scene'), {+ src: scene,+ title: '$THREE in 3D by three.ws',+ name: 'The 3D scene',+ href: `/coin3d?pair=${THREE_DEXTOOLS_PAIR}`,+ label: 'Open the full scene',+ });+}++// ── 2. Traffic ──────────────────────────────────────────────────────────────++const RANGES = [7, 30, 90];+let statsDays = 30;+let statsSeq = 0;++const SURFACE_LABELS = {+ direct: 'Direct link',+ terminals: 'Trading-terminal links',+ 'embed-boost': 'Boost card embed',+};+const surfaceLabel = (s) => SURFACE_LABELS[s] || s.replace(/-/g, ' ').replace(/^\w/, (c) => c.toUpperCase());++function rangeControl() {+ return `<div class="dx-range" role="group" aria-label="Range">${RANGES.map(+ (d) => `<button type="button" data-days="${d}" aria-pressed="${d === statsDays}">${d}d</button>`,+ ).join('')}</div>`;+}++function barsHtml(byDay) {+ const max = Math.max(1, ...byDay.map((d) => d.visits));+ const bars = byDay+ .map((d) => {+ const h = Math.round((d.visits / max) * 100);+ const label = `${d.day}: ${fmtInt(d.visits)} visit${d.visits === 1 ? '' : 's'}`;+ return `<div class="dx-bar${d.visits ? '' : ' is-zero'}" style="height:${h}%" title="${esc(label)}" role="img" aria-label="${esc(label)}"></div>`;+ })+ .join('');+ return `<div class="dx-bars">${bars}</div><div class="dx-axis"><span>${esc(byDay[0]?.day || '')}</span><span>${esc(byDay[byDay.length - 1]?.day || '')}</span></div>`;+}++function tokenRow(t) {+ const name = t.symbol ? `$${t.symbol}` : t.name || shortAddr(t.token);+ const page = t.network === 'solana' ? `/launches/${encodeURIComponent(t.token)}` : null;+ const label = page ? `<a href="${page}">${esc(name)}</a>` : esc(name);+ const sub = t.launchedOnThreeWs ? ' <span class="dx-muted">· launched on three.ws</span>' : '';+ return `<tr><td>${label}${sub}</td><td class="num">${fmtInt(t.visits)}</td></tr>`;+}++function renderStats(data) {+ const box = $('dx-stats');+ box.removeAttribute('aria-busy');+ const head = `+ <div class="dx-stats-head">+ <div>+ <div class="dx-big">${fmtInt(data.visits)}</div>+ <div class="dx-big-label">visits to DEXTools pair pages in the last ${data.days} days, across ${fmtInt(data.tokens)} coin${data.tokens === 1 ? '' : 's'}</div>+ </div>+ ${rangeControl()}+ </div>`;+ if (!data.visits) {+ box.innerHTML = `${head}+ <p class="dx-sub" style="margin:8px 0 0">No visit has been counted in this range yet. Every DEXTools link on three.ws feeds this count, so the first click on a coin page, a launch or a boost card shows up here within a few minutes.</p>+ <div class="dx-row" style="margin-top:12px"><a class="dx-btn" href="#builder">Embed a boost card</a><a class="dx-btn" href="/launches">Browse launches</a></div>`;+ return;+ }+ const surfaces = data.bySurface.map((s) => `<tr><td>${esc(surfaceLabel(s.surface))}</td><td class="num">${fmtInt(s.visits)}</td></tr>`).join('');+ const tokens = data.topTokens.map(tokenRow).join('');+ box.innerHTML = `${head}${barsHtml(data.byDay)}+ <div class="dx-split">+ <table class="dx-table"><thead><tr><th>Sent from</th><th class="num">Visits</th></tr></thead><tbody>${surfaces}</tbody></table>+ <table class="dx-table"><thead><tr><th>Top coins</th><th class="num">Visits</th></tr></thead><tbody>${tokens}</tbody></table>+ </div>+ ${data.lastVisitAt ? `<p class="dx-msg">Last visit counted ${esc(new Date(data.lastVisitAt).toLocaleString())}.</p>` : ''}`;+}++function renderStatsError(message) {+ const box = $('dx-stats');+ box.removeAttribute('aria-busy');+ box.innerHTML = `<p class="dx-msg is-error" style="margin:0 0 10px">${esc(message)}</p><button type="button" class="dx-btn" id="dx-stats-retry">Try again</button>`;+ $('dx-stats-retry').addEventListener('click', loadStats);+}++async function loadStats() {+ const seq = ++statsSeq;+ $('dx-stats').setAttribute('aria-busy', 'true');+ try {+ const r = await fetch(`/api/coin/dextools-stats?days=${statsDays}`, { headers: { accept: 'application/json' } });+ if (seq !== statsSeq) return;+ if (r.status === 429) return renderStatsError('Too many requests just now. Wait a few seconds and try again.');+ if (!r.ok) return renderStatsError(`The traffic counter did not answer (${r.status}).`);+ renderStats(await r.json());+ } catch {+ if (seq === statsSeq) renderStatsError('Could not reach the traffic counter. Check your connection and try again.');+ }+}++$('dx-stats').addEventListener('click', (e) => {+ const b = e.target.closest('[data-days]');+ if (!b) return;+ statsDays = Number(b.dataset.days);+ loadStats();+});++// ── 3. Embed builder ────────────────────────────────────────────────────────++const builder = { mint: null, pair: null, kind: 'scene', light: false, label: '' };++function setMsg(text, isError = false) {+ const m = $('dx-msg');+ m.textContent = text;+ m.classList.toggle('is-error', isError);+}++async function pairLookup(address) {+ const r = await fetch(`/api/coin/pair?address=${encodeURIComponent(address)}&network=solana`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(12_000),+ });+ if (r.status === 404) return null;+ if (!r.ok) throw new Error(`pair lookup ${r.status}`);+ return r.json();+}++async function poolLookup(mint) {+ const r = await fetch(`/api/coin/pool?address=${encodeURIComponent(mint)}&network=solana`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(12_000),+ });+ if (!r.ok) return null;+ return (await r.json())?.pool || null;+}++/** Resolves parsed input to { mint, pair, label }, asking /api/coin/pair whenever a pair is possible. */+async function resolveInput(parsed) {+ if (parsed.kind === 'mint') {+ return { mint: parsed.address, pair: await poolLookup(parsed.address).catch(() => null), label: shortAddr(parsed.address) };+ }+ const market = await pairLookup(parsed.address);+ if (market?.token?.address) {+ return { mint: market.token.address, pair: market.pair || parsed.address, label: market.pairName || market.token.symbol || shortAddr(market.token.address) };+ }+ if (parsed.kind === 'pair') return null;+ // Not a known pair, so the address is the token itself.+ return { mint: parsed.address, pair: await poolLookup(parsed.address).catch(() => null), label: shortAddr(parsed.address) };+}++function renderBuilder() {+ const s = embedSnippets({ mint: builder.mint, pair: builder.pair, theme: builder.light ? 'light' : 'dark' });+ const scene = builder.kind === 'scene';+ $('dx-snippet').textContent = scene ? s.sceneHtml : s.boostHtml;+ for (const b of document.querySelectorAll('[data-kind]')) b.setAttribute('aria-pressed', String(b.dataset.kind === builder.kind));+ const themeBtn = $('dx-theme');+ themeBtn.hidden = scene;+ themeBtn.setAttribute('aria-pressed', String(builder.light));+ $('dx-resolved').textContent = `${builder.label}: mint ${shortAddr(builder.mint)}${builder.pair ? `, pair ${shortAddr(builder.pair)}` : ', no pair indexed yet'}.`;++ // The preview loads the same-origin route so it works on every deployment;+ // the snippet always names production, which is what a host page pastes.+ const local = embedSnippets({ mint: builder.mint, pair: builder.pair, theme: builder.light ? 'light' : 'dark', origin: location.origin });+ const frame = document.createElement('iframe');+ frame.src = scene ? local.scene : local.boost;+ frame.title = scene ? 'Preview: token in 3D' : 'Preview: Boost on DEXTools card';+ frame.width = scene ? '420' : '380';+ frame.height = scene ? '560' : '400';+ frame.loading = 'lazy';+ $('dx-preview').replaceChildren(frame);+ $('dx-out').hidden = false;+}++async function build(raw) {+ const parsed = parseTokenInput(raw);+ if (parsed.error) {+ setMsg(parsed.error, true);+ $('dx-input').focus();+ return;+ }+ const go = $('dx-go');+ go.disabled = true;+ setMsg(`Resolving ${parsed.source === 'address' ? 'the address' : `the ${parsed.source} link`}…`);+ try {+ const out = await resolveInput(parsed);+ if (!out) {+ setMsg('No index knows this pair yet. A brand-new pair appears within minutes of its first trade.', true);+ return;+ }+ Object.assign(builder, out);+ setMsg('');+ renderBuilder();+ try {+ const next = new URL(location.href);+ next.searchParams.set('q', raw.trim());+ next.hash = 'builder';+ history.replaceState(null, '', next);+ } catch {+ /* history is unavailable inside some embedded browsers; the builder still works */+ }+ } catch {+ setMsg('The market index did not answer. This is usually brief, try again in a moment.', true);+ } finally {+ go.disabled = false;+ }+}++$('dx-form').addEventListener('submit', (e) => {+ e.preventDefault();+ build($('dx-input').value);+});+for (const b of document.querySelectorAll('[data-try]')) {+ b.addEventListener('click', () => {+ $('dx-input').value = b.dataset.try === 'mint' ? THREE_MINT : DEXTOOLS_PAIR_URL;+ build($('dx-input').value);+ });+}+for (const b of document.querySelectorAll('[data-kind]')) {+ b.addEventListener('click', () => {+ builder.kind = b.dataset.kind;+ renderBuilder();+ });+}+$('dx-theme').addEventListener('click', () => {+ builder.light = !builder.light;+ renderBuilder();+});+$('dx-copy').addEventListener('click', async (e) => {+ const btn = e.currentTarget;+ try {+ await navigator.clipboard.writeText($('dx-snippet').textContent);+ btn.textContent = 'Copied';+ } catch {+ btn.textContent = 'Select and copy';+ }+ setTimeout(() => (btn.textContent = 'Copy'), 1600);+});++// ── 4. Social Boost wins ────────────────────────────────────────────────────++function renderWins() {+ const { count, totalUsd } = socialBoostSummary(SOCIAL_BOOST_WINS);+ const fmtDate = (iso) => new Date(`${iso}T00:00:00Z`).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', timeZone: 'UTC' });+ $('dx-wins').innerHTML =+ `<article class="dx-card dx-win"><b>${fmtUsd0(totalUsd)}</b><p>of $THREE bought by DEXTools across ${count} wins</p></article>` ++ SOCIAL_BOOST_WINS.map(+ (w) => `<article class="dx-card dx-win"><b>${fmtUsd0(w.prizeUsd)}</b><p>${w.period === 'weekly' ? 'Weekly' : 'Daily'} winner, ${esc(fmtDate(w.date))} · <a href="${esc(w.receipt)}" target="_blank" rel="noopener">Receipt ↗</a></p></article>`,+ ).join('');+}++// ── boot ────────────────────────────────────────────────────────────────────++mountThreeBothWays();+renderWins();+loadStats();++const params = new URLSearchParams(location.search);+const deepLink = params.get('q') || params.get('mint') || params.get('pair');+if (deepLink) {+ $('dx-input').value = deepLink;+ build(deepLink);+}diff --git a/src/dextools-input.js b/src/dextools-input.jsnew file mode 100644index 000000000..b6216094a--- /dev/null+++ b/src/dextools-input.js@@ -0,0 +1,103 @@+// Turns whatever a person pastes into the /dextools embed builder into the+// address it names, and whether that address is known to be a pair or a mint.+//+// People copy from wherever they were looking: a DEXTools pair page, a+// DexScreener or GeckoTerminal page, pump.fun, Birdeye, or the bare address.+// Each of those carries a different identifier in a different place, and only+// some of them say which kind it is:+//+// dextools.io/app/[en/]solana/pair-explorer/<pair> pair+// geckoterminal.com/solana/pools/<pair> pair+// pump.fun/coin/<mint>, pump.fun/<mint> mint+// birdeye.so/token/<mint> mint+// dexscreener.com/solana/<address> either (DexScreener accepts both)+// <address> either+//+// `kind: 'unknown'` is resolved by the caller against /api/coin/pair, which is+// the only honest way to tell a pool account from a mint on Solana.+//+// Dependency-free and DOM-free so it is unit-tested directly.++const SOL_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++/** @typedef {{ address: string, kind: 'pair'|'mint'|'unknown', source: string }} ParsedInput */++function hostOf(url) {+ return url.hostname.replace(/^www\./, '').toLowerCase();+}++/**+ * @param {string} raw+ * @returns {ParsedInput | { error: string }}+ */+export function parseTokenInput(raw) {+ const text = String(raw || '').trim();+ if (!text) return { error: 'Paste a DEXTools link, a pair address or a token address.' };+ if (SOL_RE.test(text)) return { address: text, kind: 'unknown', source: 'address' };++ let url;+ try {+ url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `https://${text}`);+ } catch {+ return { error: 'That is neither a link nor a Solana address.' };+ }+ const host = hostOf(url);+ const parts = url.pathname.split('/').filter(Boolean);+ const pick = (i, kind, source) => {+ const address = parts[i] || '';+ return SOL_RE.test(address) ? { address, kind, source } : { error: `That ${source} link does not end in a Solana address.` };+ };++ if (host === 'dextools.io') {+ // /app/<chain>/pair-explorer/<pair>, with an optional language segment.+ const i = parts.indexOf('pair-explorer');+ if (i < 1) return { error: 'Use the DEXTools pair page link, the one with pair-explorer in it.' };+ if (parts[i - 1] !== 'solana') return { error: 'That DEXTools pair is not on Solana. The 3D scene and boost card render Solana tokens.' };+ return pick(i + 1, 'pair', 'DEXTools');+ }+ if (host === 'geckoterminal.com') {+ if (parts[0] !== 'solana' || parts[1] !== 'pools') return { error: 'Use a Solana pool link from GeckoTerminal.' };+ return pick(2, 'pair', 'GeckoTerminal');+ }+ if (host === 'dexscreener.com') {+ if (parts[0] !== 'solana') return { error: 'That DexScreener market is not on Solana.' };+ return pick(1, 'unknown', 'DexScreener');+ }+ if (host === 'pump.fun') {+ return pick(parts[0] === 'coin' ? 1 : 0, 'mint', 'pump.fun');+ }+ if (host === 'birdeye.so') {+ return pick(parts.indexOf('token') + 1, 'mint', 'Birdeye');+ }+ if (host === 'three.ws') {+ const mint = url.searchParams.get('mint');+ if (mint && SOL_RE.test(mint)) return { address: mint, kind: 'mint', source: 'three.ws' };+ const pair = url.searchParams.get('pair');+ if (pair && SOL_RE.test(pair)) return { address: pair, kind: 'pair', source: 'three.ws' };+ const last = parts[parts.length - 1] || '';+ if (SOL_RE.test(last)) return { address: last, kind: 'mint', source: 'three.ws' };+ }+ return { error: 'Paste a DEXTools, DexScreener, GeckoTerminal, pump.fun or Birdeye link, or a bare address.' };+}++/**+ * The embed URLs and iframe snippets for one resolved token.+ *+ * @param {{ mint: string, pair?: string|null, theme?: 'dark'|'light', origin?: string }} p+ */+export function embedSnippets({ mint, pair = null, theme = 'dark', origin = 'https://three.ws' }) {+ const t = theme === 'light' ? 'light' : 'dark';+ // The 3D scene is keyed by pair when one is known: that is the identifier a+ // DEXTools page already has, so a snippet built here matches one written by hand there.+ const sceneQuery = new URLSearchParams(pair ? { pair, embed: '1' } : { mint, embed: '1' });+ const boostQuery = new URLSearchParams({ mint, ...(t === 'light' ? { theme: t } : {}) });+ const scene = `${origin}/coin3d?${sceneQuery}`;+ const boost = `${origin}/embed/dextools-boost?${boostQuery}`;+ const amp = (s) => s.replace(/&/g, '&');+ return {+ scene,+ boost,+ sceneHtml: `<iframe src="${amp(scene)}"\n width="420" height="560" style="border:0" loading="lazy"\n title="Token in 3D by three.ws"></iframe>`,+ boostHtml: `<iframe src="${amp(boost)}"\n width="380" height="400" style="border:0" loading="lazy"\n title="Boost on DEXTools"></iframe>`,+ };+}diff --git a/tests/chart-companion-reactor.test.js b/tests/chart-companion-reactor.test.jsnew file mode 100644index 000000000..e92d2957e--- /dev/null+++ b/tests/chart-companion-reactor.test.js@@ -0,0 +1,161 @@+// The Chart Companion reaction engine: what the avatar does for each real swap.+//+// The contract: sizes are judged against the coin's own tape (so "whale" means+// something on any coin), dollar floors keep a dead tape quiet, streaks and new+// highs fire once per occurrence, and every line carries the real number that+// caused it.++import { describe, it, expect } from 'vitest';+import {+ createReactor,+ fmtUsd,+ fmtPrice,+ fmtPct,+ tradePrice,+ REACTION_KINDS,+ WHALE_FLOOR_USD,+ BIG_FLOOR_USD,+ QUIET_MS,+ STREAK,+} from '../src/chart-companion/reactor.js';++let seq = 0;+const trade = (usd, isBuy = true, price = 0.0005) => ({+ signature: `sig${++seq}`,+ is_buy: isBuy,+ sol_value_usd: usd,+ token_amount: usd / price,+ timestamp: 1_800_000_000 + seq,+});++function clock(start = 1_000_000) {+ let t = start;+ return { now: () => t, advance: (ms) => { t += ms; } };+}++describe('formatting', () => {+ it('formats dollars compactly', () => {+ expect(fmtUsd(430)).toBe('$430');+ expect(fmtUsd(1234)).toBe('$1.2K');+ expect(fmtUsd(45_000)).toBe('$45K');+ expect(fmtUsd(3_400_000)).toBe('$3.4M');+ });++ it('keeps significant digits on sub-cent prices', () => {+ expect(fmtPrice(0.000465)).toBe('$0.000465');+ expect(fmtPrice(2.5)).toBe('$2.50');+ expect(fmtPrice(0)).toBe('');+ });++ it('signs percentages', () => {+ expect(fmtPct(12.44)).toBe('+12%');+ expect(fmtPct(-3.14)).toBe('-3.1%');+ });++ it('derives a per-token price from a swap, or nothing', () => {+ expect(tradePrice({ sol_value_usd: 100, token_amount: 200_000 })).toBeCloseTo(0.0005);+ expect(tradePrice({ sol_value_usd: 100, token_amount: 0 })).toBeNull();+ });+});++describe('size reactions', () => {+ it('calls a whale only above the floor when the tape is too thin for a median', () => {+ const r = createReactor({ symbol: 'three' });+ expect(r.ingestTrades([trade(WHALE_FLOOR_USD - 1)])[0].kind).toBe('bigBuy');+ const [whale] = r.ingestTrades([trade(WHALE_FLOOR_USD + 500)]);+ expect(whale.kind).toBe('whaleBuy');+ expect(whale.line).toContain('$1.5K');+ expect(whale.line).toContain('$THREE');+ expect(whale.clip).toBe(REACTION_KINDS.whaleBuy.clip);+ });++ it('judges size against the coin\'s own tape once it has a sample', () => {+ const r = createReactor({ symbol: 'big' });+ // A coin whose median swap is $2,000: a $1,500 buy is ordinary.+ r.prime(Array.from({ length: 20 }, () => trade(2000)));+ expect(r.ingestTrades([trade(1500)])).toEqual([]);+ // 8x the median is a whale.+ expect(r.ingestTrades([trade(16_500)])[0].kind).toBe('whaleBuy');+ });++ it('keeps a dead tape of tiny trades silent', () => {+ const r = createReactor();+ r.prime(Array.from({ length: 20 }, () => trade(2)));+ expect(r.ingestTrades([trade(BIG_FLOOR_USD - 1)])).toEqual([]);+ });++ it('reacts to big sells with a sell reaction', () => {+ const r = createReactor();+ const [x] = r.ingestTrades([trade(400, false)]);+ expect(x.kind).toBe('bigSell');+ expect(x.emotion[0]).toBe('concern');+ });++ it('rotates lines so the same kind does not repeat back to back', () => {+ const r = createReactor({ symbol: 'x' });+ const a = r.ingestTrades([trade(300, true)])[0].line;+ const b = r.ingestTrades([trade(300, true)])[0].line;+ expect(a).not.toBe(b);+ });+});++describe('streaks and highs', () => {+ it('fires a buy streak once per streak', () => {+ const r = createReactor();+ const out = r.ingestTrades(Array.from({ length: STREAK + 3 }, () => trade(10)));+ expect(out.filter((x) => x.kind === 'buyStreak')).toHaveLength(1);+ // A sell breaks it; a fresh streak can fire again.+ r.ingestTrades([trade(10, false)]);+ const again = r.ingestTrades(Array.from({ length: STREAK }, () => trade(10)));+ expect(again.map((x) => x.kind)).toContain('buyStreak');+ });++ it('marks a buy above the 24h candle high as a new high, with the price', () => {+ const c = clock();+ const r = createReactor({ symbol: 'three', now: c.now });+ r.ingestCandles([{ o: 0.0004, h: 0.0005, l: 0.0004, c: 0.00045 }]);+ const out = r.ingestTrades([trade(20, true, 0.00055)]);+ const high = out.find((x) => x.kind === 'newHigh');+ expect(high.line).toContain('$0.000550');+ // Within the cooldown a higher print does not fire again.+ expect(r.ingestTrades([trade(20, true, 0.0006)]).find((x) => x.kind === 'newHigh')).toBeUndefined();+ });++ it('orders a frame\'s reactions by priority', () => {+ const r = createReactor();+ r.ingestCandles([{ o: 0.0004, h: 0.0005, l: 0.0004, c: 0.00045 }]);+ const out = r.ingestTrades([trade(5000, true, 0.0009)]);+ expect(out.map((x) => x.kind)).toEqual(['whaleBuy', 'newHigh']);+ });+});++describe('stats, greeting and quiet', () => {+ it('tallies the session', () => {+ const r = createReactor();+ r.ingestTrades([trade(100), trade(50, false), trade(900)]);+ expect(r.stats.buys).toBe(2);+ expect(r.stats.sells).toBe(1);+ expect(r.stats.buyUsd).toBe(1000);+ expect(r.stats.biggest.sol_value_usd).toBe(900);+ });++ it('greets with the real 24h change when candles are in', () => {+ const r = createReactor({ symbol: 'three' });+ r.ingestCandles([{ o: 0.0004, h: 0.0005, l: 0.0004, c: 0.0005 }]);+ expect(r.greeting().line).toContain('+25%');+ expect(createReactor({ symbol: 'x' }).greeting().line).toContain('Watching $X live');+ });++ it('says one quiet line per quiet stretch', () => {+ const c = clock();+ const r = createReactor({ now: c.now });+ expect(r.tick()).toBeNull();+ c.advance(QUIET_MS + 1);+ expect(r.tick().kind).toBe('quiet');+ c.advance(QUIET_MS + 1);+ expect(r.tick()).toBeNull();+ r.ingestTrades([trade(10)]);+ c.advance(QUIET_MS + 1);+ expect(r.tick().kind).toBe('quiet');+ });+});diff --git a/tests/chart-companion-target.test.js b/tests/chart-companion-target.test.jsnew file mode 100644index 000000000..e32b59dba--- /dev/null+++ b/tests/chart-companion-target.test.js@@ -0,0 +1,31 @@+// Chart Companion input: a pasted DEXTools link, pair, or mint becomes a query.++import { describe, it, expect } from 'vitest';+import { parseTarget } from '../src/chart-companion/target.js';++const PAIR = 'CnK82s8exdsK9nwqQ55kd9wcxoA22NwTchZJCBdu8LDa';++describe('parseTarget', () => {+ it('reads the pair out of a DEXTools pair-explorer link, with or without a locale', () => {+ expect(parseTarget(`https://www.dextools.io/app/solana/pair-explorer/${PAIR}`)).toEqual({ pair: PAIR });+ expect(parseTarget(`https://www.dextools.io/app/en/solana/pair-explorer/${PAIR}?t=123`)).toEqual({ pair: PAIR });+ });++ it('reads the pair out of a DEXTools widget-chart link', () => {+ expect(parseTarget(`https://www.dextools.io/widget-chart/en/solana/pe-light/${PAIR}?theme=dark`)).toEqual({ pair: PAIR });+ });++ it('refuses a DEXTools link on another chain with a reason', () => {+ const r = parseTarget('https://www.dextools.io/app/en/ether/pair-explorer/0xa43fe16908251ee70ef74718545e4fe6c5ccec9f');+ expect(r.error).toMatch(/Solana/);+ });++ it('passes a bare Solana address through for the page to classify', () => {+ expect(parseTarget(` ${PAIR} `)).toEqual({ address: PAIR });+ });++ it('explains empty and malformed input', () => {+ expect(parseTarget('').error).toMatch(/Paste/);+ expect(parseTarget('https://example.com/coin').error).toMatch(/does not look like/);+ });+});diff --git a/tests/dextools-input.test.js b/tests/dextools-input.test.jsnew file mode 100644index 000000000..cff74183d--- /dev/null+++ b/tests/dextools-input.test.js@@ -0,0 +1,54 @@+import { describe, it, expect } from 'vitest';+import { parseTokenInput, embedSnippets } from '../src/dextools-input.js';++const PAIR = 'CnK82s8exdsK9nwqQ55kd9wcxoA22NwTchZJCBdu8LDa';+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++describe('parseTokenInput', () => {+ it('reads the pair out of a DEXTools pair page, with or without a language segment', () => {+ expect(parseTokenInput(`https://www.dextools.io/app/solana/pair-explorer/${PAIR}`)).toEqual({ address: PAIR, kind: 'pair', source: 'DEXTools' });+ expect(parseTokenInput(`https://www.dextools.io/app/en/solana/pair-explorer/${PAIR}?t=123`)).toMatchObject({ address: PAIR, kind: 'pair' });+ expect(parseTokenInput(`dextools.io/app/solana/pair-explorer/${PAIR}`)).toMatchObject({ address: PAIR, kind: 'pair' });+ });++ it('refuses a DEXTools pair on another chain with a reason', () => {+ const r = parseTokenInput('https://www.dextools.io/app/ether/pair-explorer/0x0d4a11d5eeaac28ec3f61d100daf4d40471f1852');+ expect(r.error).toMatch(/not on Solana/);+ });++ it('knows which links carry a mint and which carry a pair', () => {+ expect(parseTokenInput(`https://pump.fun/coin/${MINT}`)).toMatchObject({ address: MINT, kind: 'mint' });+ expect(parseTokenInput(`https://pump.fun/${MINT}`)).toMatchObject({ address: MINT, kind: 'mint' });+ expect(parseTokenInput(`https://birdeye.so/token/${MINT}?chain=solana`)).toMatchObject({ address: MINT, kind: 'mint' });+ expect(parseTokenInput(`https://www.geckoterminal.com/solana/pools/${PAIR}`)).toMatchObject({ address: PAIR, kind: 'pair' });+ expect(parseTokenInput(`https://three.ws/coin3d?pair=${PAIR}&embed=1`)).toMatchObject({ address: PAIR, kind: 'pair' });+ expect(parseTokenInput(`https://three.ws/launches/${MINT}`)).toMatchObject({ address: MINT, kind: 'mint' });+ });++ it('leaves ambiguous addresses for the resolver to decide', () => {+ expect(parseTokenInput(` ${PAIR} `)).toEqual({ address: PAIR, kind: 'unknown', source: 'address' });+ expect(parseTokenInput(`https://dexscreener.com/solana/${PAIR}`)).toMatchObject({ address: PAIR, kind: 'unknown' });+ });++ it('explains empty and unrecognised input instead of guessing', () => {+ expect(parseTokenInput('').error).toBeTruthy();+ expect(parseTokenInput('not an address').error).toBeTruthy();+ expect(parseTokenInput('https://example.com/token/abc').error).toBeTruthy();+ expect(parseTokenInput('https://www.dextools.io/app/solana').error).toMatch(/pair-explorer/);+ });+});++describe('embedSnippets', () => {+ it('keys the 3D scene by pair when one is known and the boost card by mint', () => {+ const s = embedSnippets({ mint: MINT, pair: PAIR });+ expect(s.scene).toBe(`https://three.ws/coin3d?pair=${PAIR}&embed=1`);+ expect(s.boost).toBe(`https://three.ws/embed/dextools-boost?mint=${MINT}`);+ expect(s.sceneHtml).toContain(`pair=${PAIR}&embed=1`);+ });++ it('falls back to the mint and carries a light theme through', () => {+ const s = embedSnippets({ mint: MINT, theme: 'light' });+ expect(s.scene).toBe(`https://three.ws/coin3d?mint=${MINT}&embed=1`);+ expect(s.boost).toBe(`https://three.ws/embed/dextools-boost?mint=${MINT}&theme=light`);+ });+});diff --git a/vercel.json b/vercel.jsonindex 2f66fe0e1..41477e24e 100644--- a/vercel.json+++ b/vercel.json@@ -2158,6 +2158,16 @@},"dest": "/embodiment/embed.html"},+ {+ "src": "/embed/dextools-boost/?",+ "headers": {+ "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'; report-uri /api/client-errors",+ "x-content-type-options": "nosniff",+ "referrer-policy": "strict-origin-when-cross-origin",+ "cross-origin-resource-policy": "cross-origin"+ },+ "dest": "/dextools-boost-embed.html"+ },{"src": "/embed/avatar","headers": {@@ -2254,6 +2264,22 @@"src": "/playground/","dest": "/playground.html"},+ {+ "src": "/chart-companion",+ "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": "/chart-companion.html"+ },+ {+ "src": "/chart-companion/",+ "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": "/chart-companion.html"+ },{"src": "/coin3d","headers": {@@ -3257,6 +3283,10 @@"src": "/api/agents/([^/]+)/pumpfun/([^/]+)","dest": "/api/agents/pumpfun/[action]?id=$1&action=$2"},+ {+ "src": "/api/agents/([^/]+)/pons/([^/]+)",+ "dest": "/api/agents/pons/[action]?id=$1&action=$2"+ },{"src": "/api/agents/([^/]+)/embed-policy","dest": "/api/agents/[id]"@@ -5907,6 +5937,14 @@"src": "/inspect/","dest": "/inspect.html"},+ {+ "src": "/dextools",+ "dest": "/dextools.html"+ },+ {+ "src": "/dextools/",+ "dest": "/dextools.html"+ },{"src": "/embed-doctor","dest": "/embed-doctor.html"diff --git a/vite.config.js b/vite.config.jsindex 81c1096b2..83714d339 100644--- a/vite.config.js+++ b/vite.config.js@@ -724,6 +724,9 @@ const appConfig = {glossary: resolve(__dirname, 'pages/glossary.html'),playground: resolve(__dirname, 'pages/playground.html'),coin3d: resolve(__dirname, 'pages/coin3d.html'),+ dextools: resolve(__dirname, 'pages/dextools.html'),+ 'dextools-boost-embed': resolve(__dirname, 'pages/dextools-boost-embed.html'),+ 'chart-companion': resolve(__dirname, 'pages/chart-companion.html'),'hero-demo': resolve(__dirname, 'pages/hero-demo.html'),constellation: resolve(__dirname, 'pages/constellation.html'),embed: resolve(__dirname, 'pages/embed.html'),@@ -1525,6 +1528,8 @@ const appConfig = {'/extension/terms/': resolve(root, 'pages/extension-terms.html'),'/embed/walk': resolve(root, 'pages/embed-walk.html'),'/embed/walk/': resolve(root, 'pages/embed-walk.html'),+ '/embed/dextools-boost': resolve(root, 'pages/dextools-boost-embed.html'),+ '/embed/dextools-boost/': resolve(root, 'pages/dextools-boost-embed.html'),'/paywall': resolve(root, 'public/paywall.html'),'/paywall/': resolve(root, 'public/paywall.html'),'/image-to-3d': resolve(root, 'pages/forge.html'),