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): route every DEXTools link through a counted /api/coin/dextools redirect and add the Social Boost card
nirholasc8194af068a8
diff --git a/api/_lib/migrations/20261008120000_dextools_referrals.sql b/api/_lib/migrations/20261008120000_dextools_referrals.sqlnew file mode 100644index 000000000..c8704cead--- /dev/null+++ b/api/_lib/migrations/20261008120000_dextools_referrals.sql@@ -0,0 +1,22 @@+-- Migration: count the visits three.ws sends to DEXTools pair pages.+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261008120000_dextools_referrals.sql+-- Idempotent.+--+-- DEXTools Social Boost ranks tokens by visits to their pair page, so the+-- traffic three.ws routes there is the number the partnership is measured in.+-- Every DEXTools link on the platform goes through GET /api/coin/dextools, which+-- resolves the token's top pool, redirects to its pair page, and bumps one row+-- here per (UTC day, network, token, surface). Aggregated, never per-visitor:+-- no IP, no session, no user id is stored.++create table if not exists dextools_referrals (+ day date not null,+ network text not null,+ token text not null,+ surface text not null,+ visits integer not null default 0,+ last_at timestamptz not null default now(),+ primary key (day, network, token, surface)+);++create index if not exists dextools_referrals_token_idx on dextools_referrals (token, day desc);diff --git a/api/_lib/oracle/market.js b/api/_lib/oracle/market.jsindex 9c4011d38..21a238fff 100644--- a/api/_lib/oracle/market.js+++ b/api/_lib/oracle/market.js@@ -30,7 +30,8 @@ import { cacheGet, cacheSet } from '../cache.js';import { createCache } from '../mem-cache.js';import { fetchRugcheckSummary } from '../rugcheck.js';import { bondingProgressPct } from '../pump-bonding.js';-import { gmgnTokenUrl } from '../../../src/shared/trading-terminals.js';+import { gmgnTokenUrl, dextoolsTokenUrl } from '../../../src/shared/trading-terminals.js';+import { dextoolsUrl } from '../../../src/shared/dextools.js';const DEXSCREENER = 'https://api.dexscreener.com/latest/dex/tokens';const PUMP_V3 = 'https://frontend-api-v3.pump.fun';@@ -372,6 +373,10 @@ export function mergeMarketSources(mint, network, p, fetchedAt) {twitter: pick(linkOrder, 'links.twitter'),telegram: pick(linkOrder, 'links.telegram'),dexscreener: dex?.pairs?.[0]?.url || `https://dexscreener.com/solana/${mint}`,+ // The most-liquid pair when DexScreener named one (Social Boost credits a+ // specific pair page), else the counted resolver: a raw mint would land a+ // graduated pump.fun coin on its dead bonding-curve page.+ dextools: dextoolsUrl(dex?.pairs?.[0]?.pair_address) || dextoolsTokenUrl(mint, { from: 'oracle' }),gmgn: gmgnTokenUrl(mint),geckoterminal: `https://www.geckoterminal.com/solana/pools/${mint}`,birdeye: `https://birdeye.so/token/${mint}?chain=solana`,diff --git a/api/_lib/three-brand.js b/api/_lib/three-brand.jsindex e84a1dfe6..ea9ac5390 100644--- a/api/_lib/three-brand.js+++ b/api/_lib/three-brand.js@@ -19,7 +19,9 @@*/import { env } from './env.js';-import { gmgnTokenUrl, axiomTokenUrl, padreTokenUrl, fomoTokenUrl } from '../../src/shared/trading-terminals.js';+import { gmgnTokenUrl, axiomTokenUrl, padreTokenUrl, fomoTokenUrl, dextoolsTokenUrl } from '../../src/shared/trading-terminals.js';+import { THREE_MINT } from './stage-split.js';+import { DEXTOOLS_PAIR_URL } from '../../src/pump/dextools-social-boost.js';// ── Canonical brand ──────────────────────────────────────────────────────────@@ -56,6 +58,9 @@ export function threeTokenLinks(mint = threeTokenMint()) {solscan: `https://solscan.io/token/${mint}`,phantom: `https://phantom.com/tokens/solana/${mint}`,dexscreener: `https://dexscreener.com/solana/${mint}`,+ // The $THREE pair DEXTools tracks (and credits Social Boost visits to);+ // any other mint (devnet/test override) goes through the resolver.+ dextools: mint === THREE_MINT ? DEXTOOLS_PAIR_URL : dextoolsTokenUrl(mint, { from: 'three-brand' }),coingecko: 'https://www.coingecko.com/en/coins/three-ws',// Trading terminals. GMGN's carries our referral inline; the other three// have no documented deep-link referral form, so they stay clean deepdiff --git a/api/coin/dextools-stats.js b/api/coin/dextools-stats.jsnew file mode 100644index 000000000..88422f2ce--- /dev/null+++ b/api/coin/dextools-stats.js@@ -0,0 +1,128 @@+// GET /api/coin/dextools-stats?days=<1-90>[&token=<token-address>]+// ---------------------------------------------------------------------------+// How many visits three.ws has sent to DEXTools pair pages, read from the+// aggregate counter /api/coin/dextools bumps on every redirect.+//+// DEXTools Social Boost ranks tokens by visits to their pair page, so this is+// the number the DEXTools partnership is measured in, and it is public on+// purpose: the /dextools hub renders it, and anyone (DEXTools included) can+// check the traffic claim instead of taking it on faith.+//+// Aggregate only. The table holds a count per (UTC day, network, token,+// surface) and nothing about who clicked. `token` narrows every breakdown to+// one coin, which is what a project embedding the boost card wants to see.++import { cors, method, wrap, json, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';+import { env } from '../_lib/env.js';++const SOL_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const EVM_RE = /^0x[0-9a-fA-F]{40}$/;+const DEFAULT_DAYS = 30;+const MAX_DAYS = 90;+const TOP_TOKENS = 20;++/** Every UTC day from `since` through today, so a quiet day reads as 0, not a gap. */+function dayRange(days) {+ const out = [];+ const today = new Date();+ today.setUTCHours(0, 0, 0, 0);+ for (let i = days - 1; i >= 0; i--) {+ out.push(new Date(today.getTime() - i * 86_400_000).toISOString().slice(0, 10));+ }+ return out;+}++const isoDay = (d) => (d instanceof Date ? d.toISOString().slice(0, 10) : String(d).slice(0, 10));++async function readStats(days, token) {+ const since = dayRange(days)[0];+ const tok = token || null;+ const [byDay, bySurface, topTokens, totals] = await Promise.all([+ sql`+ select day, sum(visits)::int as visits+ from dextools_referrals+ where day >= ${since}::date and (${tok}::text is null or token = ${tok})+ group by day+ `,+ sql`+ select surface, sum(visits)::int as visits+ from dextools_referrals+ where day >= ${since}::date and (${tok}::text is null or token = ${tok})+ group by surface+ order by visits desc+ `,+ sql`+ select r.network, r.token, sum(r.visits)::int as visits, m.name, m.symbol+ from dextools_referrals r+ left join pump_agent_mints m+ on m.mint = r.token and m.network = 'mainnet' and r.network = 'solana'+ where r.day >= ${since}::date and (${tok}::text is null or r.token = ${tok})+ group by r.network, r.token, m.name, m.symbol+ order by visits desc+ limit ${TOP_TOKENS}+ `,+ sql`+ select coalesce(sum(visits), 0)::int as visits,+ count(distinct token)::int as tokens,+ max(last_at) as last_at+ from dextools_referrals+ where day >= ${since}::date and (${tok}::text is null or token = ${tok})+ `,+ ]);+ return { since, byDay, bySurface, topTokens, totals: totals[0] };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.marketDataIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const daysRaw = Number.parseInt(params.get('days') || '', 10);+ const days = Number.isFinite(daysRaw) ? Math.min(MAX_DAYS, Math.max(1, daysRaw)) : DEFAULT_DAYS;+ const token = (params.get('token') || '').trim();+ if (token && !SOL_RE.test(token) && !EVM_RE.test(token)) {+ return error(res, 400, 'bad_token', 'token is not a valid Solana or EVM token address');+ }++ let stats;+ try {+ stats = await readStats(days, token);+ } catch (err) {+ // The counter table ships in its own migration. Before it is applied no+ // visit has been counted, which is exactly what zero rows say.+ if (err?.code !== '42P01') throw err;+ stats = { since: dayRange(days)[0], byDay: [], bySurface: [], topTokens: [], totals: { visits: 0, tokens: 0, last_at: null } };+ }++ const counts = new Map(stats.byDay.map((r) => [isoDay(r.day), r.visits]));+ const threeMint = env.THREE_TOKEN_MINT;++ return json(+ res,+ 200,+ {+ days,+ since: stats.since,+ token: token || null,+ visits: stats.totals.visits,+ tokens: stats.totals.tokens,+ lastVisitAt: stats.totals.last_at ? new Date(stats.totals.last_at).toISOString() : null,+ byDay: dayRange(days).map((day) => ({ day, visits: counts.get(day) || 0 })),+ bySurface: stats.bySurface.map((r) => ({ surface: r.surface, visits: r.visits })),+ topTokens: stats.topTokens.map((r) => ({+ network: r.network,+ token: r.token,+ visits: r.visits,+ name: r.token === threeMint ? 'three.ws' : r.name || null,+ symbol: r.token === threeMint ? 'THREE' : r.symbol || null,+ launchedOnThreeWs: r.name != null,+ })),+ },+ { 'cache-control': 'public, max-age=60, s-maxage=300, stale-while-revalidate=600' },+ );+});diff --git a/api/coin/dextools.js b/api/coin/dextools.jsnew file mode 100644index 000000000..30bcb916c--- /dev/null+++ b/api/coin/dextools.js@@ -0,0 +1,108 @@+// GET /api/coin/dextools?address=<token-address>[&network=<geckoterminal-network>][&from=<surface>]+// ---------------------------------------------------------------------------+// One link that lands on a token's DEXTools pair page, from anywhere on+// three.ws. DEXTools keys a market by its pool account, three.ws keys+// everything by mint, and a list of coins cannot afford a pool lookup per row+// just to render an anchor. So every DEXTools link points here instead: this+// resolves the most-liquid pool through the same keyless chain /api/coin/pool+// uses (the same keyless failover chain the chart switcher resolves pools+// with), and 302s to the pair page.+//+// Each redirect also bumps an aggregate counter in `dextools_referrals`, keyed+// by UTC day, token and the surface that sent the visit (`from`). Social Boost+// ranks by pair-page visits, so this is the number the DEXTools partnership is+// measured in. Counting never blocks the redirect: a DB outage still lands the+// visitor on DEXTools.+//+// A token with no resolvable pool still lands on DEXTools, on the pair-explorer+// route keyed by the token itself. For a bonding-curve launch DEXTools files the+// mint as the curve's own pair (checked 2026-10-08), which is the live market for+// a coin that has not graduated, and the very case where no pool resolves yet.+// A graduated coin must go through the pool lookup: its mint page is the dead+// curve.+//+// $THREE is pinned to the pair DEXTools tracks it under and credited its Social+// Boost wins to (a three / SOL pool), not the deeper pool a liquidity ranking+// picks, so every visit we send counts on the board we won.++import { cors, method, wrap, error, redirect, rateLimited, reportServerError } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { topPoolForToken } from '../_lib/market/ohlcv.js';+import { sql, isDbUnavailableError } from '../_lib/db.js';+import { THREE_DEXTOOLS_PAIR } from '../../src/pump/dextools-social-boost.js';++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++/** Tokens whose DEXTools pair is fixed rather than resolved by liquidity. */+const PINNED_PAIRS = { [`solana:${THREE_MINT}`]: THREE_DEXTOOLS_PAIR };++// GeckoTerminal network id (what /api/coin/pool takes) -> DEXTools chain slug.+const DEXTOOLS_CHAIN = {+ solana: 'solana',+ eth: 'ether',+ base: 'base',+ bsc: 'bnb',+ polygon_pos: 'polygon',+ arbitrum: 'arbitrum',+ optimism: 'optimism',+ avax: 'avalanche',+};++const SOL_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const EVM_RE = /^0x[0-9a-fA-F]{40}$/;+const SURFACE_RE = /^[a-z0-9-]{1,40}$/;++export function dextoolsPairUrl(network, pairOrToken) {+ return `https://www.dextools.io/app/${DEXTOOLS_CHAIN[network]}/pair-explorer/${encodeURIComponent(pairOrToken)}`;+}++async function resolvePool(address, network) {+ const pinned = PINNED_PAIRS[`${network}:${address}`];+ if (pinned) return pinned;+ try {+ return (await topPoolForToken(address, network)) || null;+ } catch {+ // No pool, a throttle, or an outage all end the same way for a visitor:+ // the token-keyed page (see the header). The chart switcher is where a+ // missing pool is worth explaining; a link just has to land.+ return null;+ }+}++async function countReferral(network, token, surface) {+ try {+ await sql`+ insert into dextools_referrals (day, network, token, surface, visits)+ values ((now() at time zone 'utc')::date, ${network}, ${token}, ${surface}, 1)+ on conflict (day, network, token, surface)+ do update set visits = dextools_referrals.visits + 1, last_at = now()+ `;+ } catch (err) {+ if (!isDbUnavailableError(err)) reportServerError(err, { code: 'dextools_referral_count', context: { network, surface } });+ }+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.marketDataIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const address = (params.get('address') || '').trim();+ const network = (params.get('network') || 'solana').trim();+ const fromRaw = (params.get('from') || '').trim().toLowerCase();+ const surface = SURFACE_RE.test(fromRaw) ? fromRaw : 'direct';++ if (!DEXTOOLS_CHAIN[network]) {+ return error(res, 400, 'bad_network', 'network must be a supported GeckoTerminal network id');+ }+ const wellFormed = network === 'solana' ? SOL_RE.test(address) : EVM_RE.test(address);+ if (!wellFormed) {+ return error(res, 400, 'bad_address', 'address is not a valid token address for the network');+ }++ const [pool] = await Promise.all([resolvePool(address, network), countReferral(network, address, surface)]);+ return redirect(res, dextoolsPairUrl(network, pool || address));+});diff --git a/api/oracle-share.js b/api/oracle-share.jsindex 90419f3ac..27c7f5ee8 100644--- a/api/oracle-share.js+++ b/api/oracle-share.js@@ -328,7 +328,7 @@ function heroHtml({ mint, row, pump, origin }) {const actions = `<div class="cv-pills oc-actions"><a class="cv-pill" href="${esc(pumpUrl(mint))}" target="_blank" rel="noopener">pump.fun ↗</a>- ${terminalLinks(mint).map((t) => `<a class="cv-pill" href="${esc(t.url)}" target="_blank" rel="noopener">${esc(t.label)} ↗</a>`).join('\n\t\t')}+ ${terminalLinks(mint, { from: 'oracle-share' }).map((t) => `<a class="cv-pill" href="${esc(t.url)}" target="_blank" rel="noopener">${esc(t.label)} ↗</a>`).join('\n\t\t')}<a class="cv-pill" href="https://solscan.io/token/${esc(mint)}" target="_blank" rel="noopener">Solscan ↗</a><a class="cv-pill" href="/coin3d?mint=${encodeURIComponent(mint)}" title="Open the full 3D coin profile">View in 3D</a><a class="cv-pill" href="/launches/${esc(mint)}">Launch details</a>diff --git a/public/dashboard/tokens.html b/public/dashboard/tokens.htmlindex 0d1c14eb4..7a97d90df 100644--- a/public/dashboard/tokens.html+++ b/public/dashboard/tokens.html@@ -107,6 +107,7 @@<div class="dash-row">${token.pumpfun_url ? `<a class="dash-btn primary" href="${escapeHtml(token.pumpfun_url)}" target="_blank" rel="noopener">Pump.fun ↗</a>` : ''}${token.explorer_url ? `<a class="dash-btn" href="${escapeHtml(token.explorer_url)}" target="_blank" rel="noopener">Explorer ↗</a>` : ''}+ <a class="dash-btn" href="https://three.ws/api/coin/dextools?address=${encodeURIComponent(token.mint)}&network=solana&from=dashboard-tokens" target="_blank" rel="noopener">DEXTools ↗</a><a class="dash-btn" href="https://dexscreener.com/solana/${encodeURIComponent(token.mint)}" target="_blank" rel="noopener">DEX Screener ↗</a><a class="dash-btn" href="https://birdeye.so/token/${encodeURIComponent(token.mint)}?chain=solana" target="_blank" rel="noopener">Birdeye ↗</a></div>diff --git a/public/gmgn.html b/public/gmgn.htmlindex aedace154..5b550a656 100644--- a/public/gmgn.html+++ b/public/gmgn.html@@ -347,7 +347,7 @@</footer><script type="module">- import { gmgnTokenUrl } from '/src/shared/trading-terminals.js';+ import { gmgnTokenUrl, dextoolsTokenUrl } from '/src/shared/trading-terminals.js';const $ = (id) => document.getElementById(id);const url = new URL(location.href);@@ -518,6 +518,8 @@? `https://dexscreener.com/${dexChains[chain] || 'solana'}/${escHtml(addr)}`: escHtml(gmgnTokenUrl(addr, chain));const linkLabel = isDex ? 'DexScreener' : 'GMGN';+ const dtNetworks = { sol: 'solana', eth: 'eth', base: 'base', bsc: 'bsc' };+ const dtLink = dtNetworks[chain] ? escHtml(dextoolsTokenUrl(addr, { network: dtNetworks[chain], from: 'gmgn-feed' })) : '';const txnHtml = isDex && ev.txns_h1_buys != null? `<div class="ev-stat"><span class="lbl">Buys 1h</span><span class="val up">${ev.txns_h1_buys}</span></div><div class="ev-stat"><span class="lbl">Sells 1h</span><span class="val dn">${ev.txns_h1_sells ?? 0}</span></div>`@@ -544,6 +546,7 @@<div class="ev-time">${new Date(ev.timestamp * 1000).toLocaleTimeString()} ·${addr ? `<a class="ev-link" href="${linkBase}" target="_blank" rel="noopener">View on ${linkLabel} ↗</a>` : ''}+ ${addr && dtLink ? `<a class="ev-link" href="${dtLink}" target="_blank" rel="noopener">DEXTools ↗</a>` : ''}</div>`;return div;}diff --git a/public/pumpfun.html b/public/pumpfun.htmlindex c57ea32ac..7e07cc510 100644--- a/public/pumpfun.html+++ b/public/pumpfun.html@@ -2031,6 +2031,7 @@<a href="https://pump.fun/${evt.mint}" target="_blank" rel="noopener">pump</a><a href="https://rugcheck.xyz/tokens/${evt.mint}" target="_blank" rel="noopener">rugcheck</a><a href="https://birdeye.so/token/${evt.mint}?chain=solana" target="_blank" rel="noopener">birdeye</a>+ <a href="https://three.ws/api/coin/dextools?address=${encodeURIComponent(evt.mint)}&network=solana&from=pumpfun-live" target="_blank" rel="noopener">dextools</a></div>`;card.innerHTML = title + body + links;diff --git a/src/agent-detail.js b/src/agent-detail.jsindex 47cf50f4f..d19d914db 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -11,7 +11,7 @@import { onchainBadgeEl } from './shared/onchain-badge.js';import { walletChipEl } from './shared/agent-wallet-chip.js';import { mountMoneyPulse } from './shared/money-pulse.js';-import { gmgnTokenUrl } from './shared/trading-terminals.js';+import { gmgnTokenUrl, dextoolsTokenUrl } from './shared/trading-terminals.js';import { mountMirrorPanel } from './shared/agent-mirror-panel.js';import { mountStrategyPanel } from './shared/agent-strategy-panel.js';import { mountPatronagePanel } from './shared/agent-patronage.js';@@ -3050,7 +3050,7 @@ export function normalize(rec, avatar) {});services.push({type: 'chart',- url: `https://dexscreener.com/solana/${rec.token.mint}`,+ url: dextoolsTokenUrl(rec.token.mint, { from: 'agent-detail' }),});}diff --git a/src/character.js b/src/character.jsindex 977d63a17..2a84ee070 100644--- a/src/character.js+++ b/src/character.js@@ -12,7 +12,7 @@ import { hydrateAvatarWallet } from './shared/wallet-aura.js';import './ui-juice.css';import { countUp } from './ui-juice.js';import { fetchFirstOrNull } from './shared/failover-fetch.js';-import { gmgnTokenUrl } from './shared/trading-terminals.js';+import { gmgnTokenUrl, dextoolsTokenUrl } from './shared/trading-terminals.js';let chNetWorthAura = null;@@ -233,7 +233,7 @@ function buildTokenHtml(symbol, mint, marketCapUsd, priceUsd, change24h, holders}const tradeUrl = mint ? gmgnTokenUrl(mint) : '#';- const chartUrl = mint ? `https://birdeye.so/token/${mint}?chain=solana` : '#';+ const chartUrl = mint ? dextoolsTokenUrl(mint, { from: 'character' }) : '#';const metaItems = [];if (holders) metaItems.push({ label: 'Holders', val: formatNum(holders) });@@ -259,7 +259,7 @@ function buildTokenHtml(symbol, mint, marketCapUsd, priceUsd, change24h, holders</div><div class="ch-token-actions"><a class="ch-trade-btn" href="${tradeUrl}" target="_blank" rel="noopener">Trade</a>- <a class="ch-chart-btn" href="${chartUrl}" target="_blank" rel="noopener" title="View chart">+ <a class="ch-chart-btn" href="${chartUrl}" target="_blank" rel="noopener" title="View chart on DEXTools" aria-label="View chart on DEXTools"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 3v18h18"/><path d="M18.5 8L13 13.5 8.5 10 3 15"/>@@ -306,9 +306,7 @@ async function renderToken(agent) {}const tradeUrl = mint ? gmgnTokenUrl(mint) : '#';- const chartUrl = mint- ? `https://birdeye.so/token/${mint}?chain=solana`- : '#';+ const chartUrl = mint ? dextoolsTokenUrl(mint, { from: 'character' }) : '#';const metaItems = [];if (holders) metaItems.push({ label: 'Holders', val: formatNum(holders) });diff --git a/src/coin3d/main.js b/src/coin3d/main.jsindex 7dd7f9c9c..679224703 100644--- a/src/coin3d/main.js+++ b/src/coin3d/main.js@@ -58,6 +58,8 @@ import {} from 'three';import { OrbitControls } from 'three/addons/controls/OrbitControls.js';import { fetchFirstOrNull } from '../shared/failover-fetch.js';+import { dextoolsUrl } from '../shared/dextools.js';+import { dextoolsTokenUrl } from '../shared/trading-terminals.js';import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from '../shared/cinematic-render.js';import { resolveURI, IPFS_GATEWAYS } from '../ipfs.js';@@ -92,6 +94,16 @@ function fullPageUrl() {return mint ? `/coin3d?mint=${encodeURIComponent(mint)}` : '/coin3d';}+// The coin's DEXTools pair page. A scene addressed by `pair` (how a DEX+// terminal embeds it) links back to that exact pair, which is the page Social+// Boost credits. A mint-addressed scene goes through the counted resolver: a+// raw mint would land a graduated coin on its dead bonding-curve page.+function dextoolsHudLink(mintAddr) {+ if (network !== 'mainnet' || !isPlausibleMint(mintAddr)) return '';+ const href = (pair && dextoolsUrl(pair)) || dextoolsTokenUrl(mintAddr, { from: embedded ? 'coin3d-embed' : 'coin3d' });+ return `<a class="hud-link" href="${escapeHtml(href)}" target="_blank" rel="noopener">DEXTools ↗</a>`;+}+/*** Resolve a pool/pair address to the mint it trades, through /api/coin/pair.*@@ -1069,6 +1081,7 @@ function renderHud(s) {<div class="hud-links">${s.mint ? `<button id="c3d-watch" class="c3d-watch-btn" type="button" aria-pressed="${watching}">${watching ? '★ Watching' : '☆ Watch'}</button>` : ''}<a class="hud-link" href="https://pump.fun/coin/${encodeURIComponent(s.mint)}" target="_blank" rel="noopener">pump.fun ↗</a>+ ${dextoolsHudLink(s.mint)}<a class="hud-link" href="/launches">All launches →</a>${s.mint ? `<a class="hud-link" href="/communities/${encodeURIComponent(s.mint)}">3D world →</a>` : ''}<a class="hud-link" href="/launch">Launch your own →</a>diff --git a/src/dashboard-next/pages/three-token.js b/src/dashboard-next/pages/three-token.jsindex 12f30e2d5..1da471928 100644--- a/src/dashboard-next/pages/three-token.js+++ b/src/dashboard-next/pages/three-token.js@@ -1158,7 +1158,7 @@ function renderTokenInfo() {<div style="margin-top:12px"><div style="font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--dn-dim,#8a8a9c);margin-bottom:6px">Trade $THREE on</div><div style="display:flex;gap:8px;flex-wrap:wrap">- ${terminalLinks(THREE_MINT).map((t) => `+ ${terminalLinks(THREE_MINT, { from: 'dashboard-three' }).map((t) => `<a class="dn-btn" href="${esc(t.url)}" target="_blank" rel="noopener" style="font-size:12.5px">${esc(t.label)} ↗</a>diff --git a/src/launch-detail.js b/src/launch-detail.jsindex d734fef30..37e674226 100644--- a/src/launch-detail.js+++ b/src/launch-detail.js@@ -41,8 +41,9 @@ import { walletChipEl } from './shared/agent-wallet-chip.js';import { proxiedImageURL } from './ipfs.js';import { agentAvatarGlb, hasCustomAvatar, seeInWorldHref } from './shared/agent-3d.js';import { resolveDevR2Url } from './shared/dev-r2-proxy.js';-import { terminalLinks } from './shared/trading-terminals.js';+import { terminalLinks, dextoolsTokenUrl } from './shared/trading-terminals.js';import { CHART_EMBEDS, chartEmbedUrls, resolveChartPool } from './shared/chart-embeds.js';+import { socialBoostCard } from './shared/dextools-boost.js';import { watchEmbed, embedFallbackNode, DEFAULT_EMBED_TIMEOUT_MS } from './shared/embed-guard.js';import { mountPriceChart } from './mission-control/chart.js';import { flashValue, rippleOnce, liveDot, setLiveDot } from './ui-juice.js';@@ -898,7 +899,7 @@ function terminalLinksEl() {return el('div',{ class: 'ld-chart-terminals' },- terminalLinks(state.mint).map((t) =>+ terminalLinks(state.mint, { from: 'launch-detail' }).map((t) =>el('a', {class: 'ld-chart-terminal',href: t.url,@@ -1842,7 +1843,22 @@ function renderActions() {const body = el('div', { class: 'ld-action-grid' }, buttons);const foot = el('a', { class: 'ld-actions-foot', href: '/watchlist', text: 'View your watchlist →' });- section(target, 'Take action', el('div', {}, [body, foot]));+ // Social Boost credits a specific pair page, so link the pool the DEXTools+ // chart already resolved when there is one. Otherwise go through the counted+ // /api/coin/dextools redirect, which resolves the top pool and attributes+ // the visit to this page.+ const dtPool = state.chartPools.dextools?.indexed ? state.chartPools.dextools.pool : null;+ const boost = isDevnet+ ? null+ : socialBoostCard({+ mint,+ pair: dtPool,+ href: dtPool ? undefined : dextoolsTokenUrl(mint, { from: 'launch-detail-boost' }),+ symbol,+ buttonClass: 'ld-btn ld-btn-ghost',+ primaryClass: 'ld-btn ld-btn-primary',+ });+ section(target, 'Take action', el('div', {}, [body, boost, foot]));}// ════════════════════════════════════════════════════════════════════════════diff --git a/src/launch/launch-page.js b/src/launch/launch-page.jsindex 1b628a942..6537b92dd 100644--- a/src/launch/launch-page.js+++ b/src/launch/launch-page.js@@ -18,6 +18,8 @@import './launch-page.css';import { ensureRiskAck } from '../shared/risk-ack.js';import { ensureModelViewer } from '../shared/model-viewer-loader.js';+import { dextoolsTokenUrl } from '../shared/trading-terminals.js';+import { socialBoostCard } from '../shared/dextools-boost.js';import {DESCRIPTION_MAX,DEV_BUY_PRESETS,@@ -1160,12 +1162,24 @@ function showSuccess({ mint, signature, agent, fee }) {<div class="lx-actions"><a class="lx-btn" href="/launches/${esc(mint)}">Coin page</a><a class="lx-btn" href="https://pump.fun/coin/${esc(mint)}" target="_blank" rel="noopener">pump.fun</a>+ <a class="lx-btn" href="${esc(dextoolsTokenUrl(mint, { from: 'launch-success' }))}" target="_blank" rel="noopener">DEXTools</a><a class="lx-btn" href="/agents/${esc(agent?.agent_id || agent?.id || '')}">Agent page</a><a class="lx-btn" href="https://solscan.io/tx/${esc(signature || '')}" target="_blank" rel="noopener">Transaction</a><a class="lx-btn is-primary is-wide" href="https://x.com/intent/post?text=${encodeURIComponent(post)}" target="_blank" rel="noopener">Share on X</a><button type="button" class="lx-btn is-wide" id="ok-another">Launch another</button></div>+ <div id="ok-boost"></div><p class="lx-hint" style="margin-top:14px;text-align:center">Creator rewards build up as people trade. Claim them any time under My coins.</p>`;+ const boost = socialBoostCard({ mint, symbol, href: dextoolsTokenUrl(mint, { from: 'launch-success-boost' }), buttonClass: 'lx-btn', primaryClass: 'lx-btn is-primary' });+ if (boost) {+ boost.append(Object.assign(document.createElement('p'), {+ className: 'dtb-lead',+ textContent: 'A coin this new can take a few minutes to appear on DEXTools. The link works now and fills in once DEXTools indexes the first trades.',+ }));+ $('#ok-boost').replaceWith(boost);+ } else {+ $('#ok-boost').remove();+ }$('#ok-copy').addEventListener('click', (e) => copyText(mint, e.currentTarget));$('#ok-another').addEventListener('click', () => {$('#lx-dialog').close();diff --git a/src/oracle.js b/src/oracle.jsindex 681f84289..bd41b830d 100644--- a/src/oracle.js+++ b/src/oracle.js@@ -2349,6 +2349,7 @@ function renderMarket(m) {const lk = m.links || {};const linkBtns = [lk.gmgn ? `<a class="dr-act" href="${esc(lk.gmgn)}" target="_blank" rel="noopener">GMGN ↗</a>` : '',+ lk.dextools ? `<a class="dr-act" href="${esc(lk.dextools)}" target="_blank" rel="noopener">DEXTools ↗</a>` : '',lk.dexscreener ? `<a class="dr-act" href="${esc(lk.dexscreener)}" target="_blank" rel="noopener">DexScreener ↗</a>` : '',lk.geckoterminal ? `<a class="dr-act" href="${esc(lk.geckoterminal)}" target="_blank" rel="noopener">GeckoTerminal ↗</a>` : '',lk.birdeye ? `<a class="dr-act" href="${esc(lk.birdeye)}" target="_blank" rel="noopener">Birdeye ↗</a>` : '',diff --git a/src/shared/dextools-boost.css b/src/shared/dextools-boost.cssnew file mode 100644index 000000000..09ffb2f3b--- /dev/null+++ b/src/shared/dextools-boost.css@@ -0,0 +1,70 @@+/* "Rally on DEXTools" Social Boost card (src/shared/dextools-boost.js).+ Colors derive from the host's text color so the card reads correctly on any+ surface, light or dark; buttons use the host page's own classes. */+.dtb {+ margin-top: 16px;+ padding: 16px;+ border: 1px solid color-mix(in srgb, currentColor 14%, transparent);+ border-radius: 12px;+ background: color-mix(in srgb, currentColor 4%, transparent);+ text-align: left;+ animation: dtb-in 220ms ease-out both;+}+@keyframes dtb-in {+ from { opacity: 0; transform: translateY(4px); }+ to { opacity: 1; transform: none; }+}+@media (prefers-reduced-motion: reduce) {+ .dtb { animation: none; }+}+.dtb-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ flex-wrap: wrap;+}+.dtb-title {+ margin: 0;+ font-size: 15px;+ font-weight: 600;+ line-height: 1.3;+}+.dtb-pill {+ font-size: 11px;+ letter-spacing: 0.02em;+ padding: 3px 9px;+ border-radius: 999px;+ border: 1px solid color-mix(in srgb, currentColor 22%, transparent);+ color: inherit;+ opacity: 0.8;+ text-decoration: none;+ transition: opacity 150ms ease, border-color 150ms ease;+}+.dtb-pill:hover { opacity: 1; border-color: color-mix(in srgb, currentColor 45%, transparent); }+.dtb-pill:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; opacity: 1; }+.dtb-lead,+.dtb-proof {+ margin: 8px 0 0;+ font-size: 13px;+ line-height: 1.5;+ opacity: 0.78;+}+.dtb-proof a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }+.dtb-proof a:hover { opacity: 1; }+.dtb-proof a:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; border-radius: 2px; }+.dtb-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ margin-top: 12px;+}+.dtb-actions > * { flex: 1 1 auto; justify-content: center; text-align: center; }+.dtb-status {+ display: block;+ min-height: 1em;+ margin-top: 6px;+ font-size: 12px;+ opacity: 0.75;+ overflow-wrap: anywhere;+}diff --git a/src/shared/dextools-boost.js b/src/shared/dextools-boost.jsnew file mode 100644index 000000000..1ae27f598--- /dev/null+++ b/src/shared/dextools-boost.js@@ -0,0 +1,96 @@+// "Rally on DEXTools": the Social Boost card any coin surface can mount.+//+// DEXTools Social Boost ranks tokens by daily and weekly visits to their+// DEXTools pair page and buys the winner on the open market. A coin launched on+// three.ws has a community that already lands on three.ws; this card turns that+// traffic into Social Boost visits by sending holders to the coin's DEXTools+// page and giving them a ready-made post to bring their own followers along.+//+// Mounted by the launch success screen (/launch) and every coin page+// (/launches/<mint>). Markup only: buttons take the host page's own classes,+// the way embedFallbackNode() does, so the card matches whatever it sits in.++import './dextools-boost.css';+import { dextoolsUrl, socialBoostRallyIntent, SOCIAL_BOOST_URL } from './dextools.js';+import { SOCIAL_BOOST_WINS, socialBoostSummary, SOCIAL_BOOST_STORY_PATH } from '../pump/dextools-social-boost.js';++const COPIED_MS = 1600;++function node(tag, attrs = {}, children = []) {+ const n = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) {+ if (v == null) continue;+ if (k === 'text') n.textContent = v;+ else if (k.startsWith('on')) n.addEventListener(k.slice(2), v);+ else n.setAttribute(k, v);+ }+ for (const c of children) if (c) n.append(c);+ return n;+}++/**+ * Build the card. Returns null when the address is not a valid token or pair+ * for the chain, so a caller can mount it unconditionally.+ *+ * @param {object} p+ * @param {string} p.mint token address+ * @param {string} [p.pair] pool/pair address, when known (Social Boost credits a specific pair page)+ * @param {string} [p.symbol]+ * @param {string} [p.chain='solana']+ * @param {string} [p.href] link to use instead of the direct pair page, e.g. the counted+ * /api/coin/dextools redirect (dextoolsTokenUrl) so the visit is attributed+ * @param {string} [p.buttonClass] host page's secondary button class+ * @param {string} [p.primaryClass] host page's primary button class+ * @returns {HTMLElement|null}+ */+export function socialBoostCard({ mint, pair, symbol, chain = 'solana', href, buttonClass = '', primaryClass = '' }) {+ const direct = dextoolsUrl(pair || mint, chain) || dextoolsUrl(mint, chain);+ if (!direct) return null;+ const url = href || direct;+ const sym = String(symbol || '').replace(/^\$/, '').trim();+ const tag = sym ? `$${sym}` : 'this coin';+ const { count, totalUsd } = socialBoostSummary(SOCIAL_BOOST_WINS);+ const status = node('span', { class: 'dtb-status', role: 'status', 'aria-live': 'polite' });++ const copyBtn = node('button', {+ type: 'button',+ class: buttonClass,+ text: 'Copy DEXTools link',+ onclick: async (e) => {+ const btn = e.currentTarget;+ try {+ await navigator.clipboard.writeText(url);+ status.textContent = 'DEXTools link copied.';+ } catch {+ status.textContent = `Copy blocked by the browser. The link is ${url}`;+ return;+ }+ btn.disabled = true;+ setTimeout(() => {+ btn.disabled = false;+ status.textContent = '';+ }, COPIED_MS);+ },+ });++ return node('section', { class: 'dtb', 'aria-label': `Rally ${tag} on DEXTools` }, [+ node('div', { class: 'dtb-head' }, [+ node('h3', { class: 'dtb-title', text: `Rally ${tag} on DEXTools` }),+ node('a', { class: 'dtb-pill', href: SOCIAL_BOOST_URL, target: '_blank', rel: 'noopener', text: 'Social Boost ↗' }),+ ]),+ node('p', {+ class: 'dtb-lead',+ text: `DEXTools Social Boost ranks coins by visits to their DEXTools pair page, daily and weekly, and buys the winner on the open market. Every holder you send there counts.`,+ }),+ node('p', { class: 'dtb-proof' }, [+ document.createTextNode(`$THREE has won it ${count} times, $${totalUsd.toLocaleString('en-US')} in buybacks. `),+ node('a', { href: SOCIAL_BOOST_STORY_PATH, text: 'How it worked' }),+ ]),+ node('div', { class: 'dtb-actions' }, [+ node('a', { class: primaryClass, href: url, target: '_blank', rel: 'noopener', text: 'Open on DEXTools ↗' }),+ node('a', { class: buttonClass, href: socialBoostRallyIntent({ symbol: sym, url }), target: '_blank', rel: 'noopener', text: 'Rally on X ↗' }),+ copyBtn,+ ]),+ status,+ ]);+}diff --git a/src/shared/dextools.js b/src/shared/dextools.jsnew file mode 100644index 000000000..8811b9d03--- /dev/null+++ b/src/shared/dextools.js@@ -0,0 +1,73 @@+// DEXTools links and the Social Boost rally, in one dependency-free place.+//+// Imported by browser bundles (launch flow, coin pages, coin3d, widgets) and by+// the API layer (oracle market links, the $THREE link set), so it imports+// nothing and touches no DOM.+//+// Why DEXTools gets its own module instead of one more line per surface:+// DEXTools Social Boost ranks tokens by daily and weekly visits to their pair+// page and buys the winning token on the open market ($THREE has won it three+// times, see src/pump/dextools-social-boost.js). Every link a three.ws surface+// sends to a DEXTools pair page is a visit that counts for that coin, so the+// URL shape and the rally copy live here once and every surface sends the same+// visitor to the same page.+//+// URL shape, checked against DEXTools' own edge on 2026-10-08:+// https://www.dextools.io/app/<chain>/pair-explorer/<address>+// `address` should be a pool (pair) address. DEXTools also accepts a mint+// there, but it files a pump.fun mint as the coin's bonding-curve pair (pair ==+// mint), so a raw-mint link lands a graduated coin on its dead curve page+// instead of its live pool. Only pass a mint for a coin still on its curve+// (a fresh launch). A surface that knows only the mint of a coin that may have+// graduated should link through dextoolsTokenUrl() in trading-terminals.js,+// which resolves the top pool server-side and counts the visit.+// The `/app/en/...` form 301s to this one, so the canonical form is used here.++const SOL_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const EVM_RE = /^0x[0-9a-fA-F]{40}$/;++/** three.ws chain id → DEXTools URL slug. Solana leads. */+export const DEXTOOLS_CHAIN_SLUGS = {+ solana: 'solana',+ ethereum: 'ether',+ base: 'base',+ 'binance-smart-chain': 'bnb',+ bsc: 'bnb',+ 'polygon-pos': 'polygon',+ 'arbitrum-one': 'arbitrum',+ 'optimistic-ethereum': 'optimism',+ avalanche: 'avalanche',+};++export const SOCIAL_BOOST_URL = 'https://www.dextools.io/app/social-boost';++/**+ * The DEXTools pair page for a pair address or a token mint.+ * @param {string} address pool/pair address (preferred) or token address+ * @param {string} [chain='solana'] three.ws chain id (see DEXTOOLS_CHAIN_SLUGS)+ * @returns {string|null} null when the address is malformed for the chain+ */+export function dextoolsUrl(address, chain = 'solana') {+ const slug = DEXTOOLS_CHAIN_SLUGS[chain];+ const a = typeof address === 'string' ? address.trim() : '';+ if (!slug || !a) return null;+ const ok = slug === 'solana' ? SOL_RE.test(a) : EVM_RE.test(a);+ return ok ? `https://www.dextools.io/app/${slug}/pair-explorer/${encodeURIComponent(a)}` : null;+}++/**+ * The post a holder shares to send their community to the coin's DEXTools+ * page. Plain text, ready for an X intent or a Telegram message. The DEXTools+ * link goes last so X renders its card.+ * @param {{ symbol?: string, url: string }} p+ */+export function socialBoostRallyText({ symbol, url }) {+ const sym = String(symbol || '').replace(/^\$/, '').trim();+ const tag = sym ? `$${sym}` : 'This coin';+ return `${tag} is on DEXTools. Every visit to the pair page counts toward DEXTools Social Boost, and the winner gets a buyback.\n\nGo look at the chart:\n${url}`;+}++/** X compose URL for the rally post. */+export function socialBoostRallyIntent(p) {+ return `https://x.com/intent/post?text=${encodeURIComponent(socialBoostRallyText(p))}`;+}diff --git a/src/shared/trading-terminals.js b/src/shared/trading-terminals.jsindex 01133dfef..711890dba 100644--- a/src/shared/trading-terminals.js+++ b/src/shared/trading-terminals.js@@ -7,6 +7,10 @@//// Which terminals accept a referral on a token deep link, per their own docs://+// DEXTools no code. Its deep link goes through three.ws' /api/coin/dextools+// resolver instead, which counts every visit we send (Social Boost+// ranks on pair-page visits). See dextoolsTokenUrl().+//// GMGN yes. https://docs.gmgn.ai/index/referral-link documents// `gmgn.ai/{chain}/token/{code}_{contract}` and// `gmgn.ai/{chain}/address/{code}_{wallet}`, so the deep link and the@@ -91,8 +95,26 @@ export function referralUrl(platform) {return `https://fomo.family/r/${code}`;}+/**+ * DEXTools pair page for a token, through three.ws' own resolver. DEXTools keys+ * a market by pool account and a token list has only mints, so the link goes to+ * /api/coin/dextools, which resolves the top pool, redirects to its pair page,+ * and counts the visit against `from` (the surface that sent it). DEXTools+ * Social Boost ranks tokens by pair-page visits, so those counts are what the+ * DEXTools partnership is measured in. Absolute, because the same link renders+ * in embeds, widgets on other origins, bot messages and MCP tool output.+ *+ * @param {string} token+ * @param {{ network?: string, from?: string }} [opts] network is a GeckoTerminal+ * network id ('solana', 'eth', 'base', 'bsc', ...), the same set /api/coin/pool takes.+ */+export function dextoolsTokenUrl(token, { network = 'solana', from = 'terminals' } = {}) {+ return `https://three.ws/api/coin/dextools?${new URLSearchParams({ address: String(token), network, from })}`;+}+/** Display names, by terminal key. */export const TERMINAL_LABELS = {+ dextools: 'DEXTools',gmgn: 'GMGN',axiom: 'Axiom',padre: 'Padre',@@ -119,11 +141,17 @@ export function referralOffers() {}/**- * Token deep links for every terminal we link, in display order.+ * Token deep links for every terminal we link, in display order. DEXTools leads:+ * it is the chart terminal three.ws partners with, and its link carries the+ * per-surface visit count (see dextoolsTokenUrl).+ *+ * @param {string} mint+ * @param {{ from?: string }} [opts] the surface rendering the links, for DEXTools attribution* @returns {{ key: string, label: string, short: string, url: string }[]}*/-export function terminalLinks(mint) {+export function terminalLinks(mint, { from = 'terminals' } = {}) {return [+ { key: 'dextools', label: 'DEXTools', short: 'DXT', url: dextoolsTokenUrl(mint, { from }) },{ key: 'axiom', label: 'Axiom', short: 'AXI', url: axiomTokenUrl(mint) },{ key: 'gmgn', label: 'GMGN', short: 'GMG', url: gmgnTokenUrl(mint) },{ key: 'padre', label: 'Padre', short: 'PDR', url: padreTokenUrl(mint) },diff --git a/src/widgets/pumpfun-feed.js b/src/widgets/pumpfun-feed.jsindex f18471f70..f122f265c 100644--- a/src/widgets/pumpfun-feed.js+++ b/src/widgets/pumpfun-feed.js@@ -496,7 +496,7 @@ function renderGraduation(ev) {: '';const toolAbbr = mint? [- ...terminalLinks(mint).map((t) => [t.short, t.url]),+ ...terminalLinks(mint, { from: 'pumpfun-feed' }).map((t) => [t.short, t.url]),['PHO', `https://photon-sol.tinyastro.io/en/lp/${mint}`],['BLX', `https://bullx.io/terminal?chainId=1399811149&address=${mint}`],].map(([l, u]) => `<a href="${attrEsc(u)}" target="_blank" rel="noopener" style="color:#888888">${l}</a>`).join('⋅')diff --git a/tests/api/coin-dextools.test.js b/tests/api/coin-dextools.test.jsnew file mode 100644index 000000000..f615277a2--- /dev/null+++ b/tests/api/coin-dextools.test.js@@ -0,0 +1,127 @@+// /api/coin/dextools: every DEXTools link on three.ws lands on the right pair+// page, and every landing is counted.+//+// The contract is "a visitor always reaches DEXTools": a resolved pool goes to+// its pair page, an unresolvable one goes to the token-keyed pair-explorer+// route DEXTools resolves itself, and a dead database never blocks the+// redirect. The counter row is what the DEXTools partnership is measured in, so+// its key (network, token, surface) is part of the contract too.++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: () => {} }));+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { marketDataIp: async () => ({ success: true }) },+ clientIp: () => '203.0.113.1',+}));++let topPoolForToken = vi.fn();+vi.mock('../../api/_lib/market/ohlcv.js', () => ({+ topPoolForToken: (...a) => topPoolForToken(...a),+}));++let sqlCalls = [];+let sqlImpl = async () => [];+vi.mock('../../api/_lib/db.js', () => ({+ sql: (strings, ...values) => {+ sqlCalls.push({ text: strings.join('?'), values });+ return sqlImpl();+ },+ isDbUnavailableError: (err) => err?.code === 'db_unavailable',+}));++const handler = (await import('../../api/coin/dextools.js')).default;++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const THREE_PAIR = 'CnK82s8exdsK9nwqQ55kd9wcxoA22NwTchZJCBdu8LDa';+// Clearly synthetic, so the generic path is exercised without a real third-party mint.+const SOL_TOKEN = 'THREEsynthetic1111111111111111111111111111';+const SOL_POOL = 'THREEsyntheticPoo11111111111111111111111111';+const EVM_TOKEN = '0x1234567890abcdef1234567890abcdef12345678';+const EVM_POOL = '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd';++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(body) { this._body = body; },+ };+}+async function call(query) {+ const res = makeRes();+ await handler({ url: `/api/coin/dextools?${query}`, method: 'GET', headers: {} }, res);+ return res;+}++describe('/api/coin/dextools', () => {+ beforeEach(() => {+ topPoolForToken = vi.fn();+ sqlCalls = [];+ sqlImpl = async () => [];+ });++ it('redirects a Solana mint to its top pool on DEXTools and counts the visit', async () => {+ topPoolForToken.mockResolvedValue(SOL_POOL);+ const res = await call(`address=${SOL_TOKEN}&from=launch-detail`);+ expect(res.statusCode).toBe(302);+ expect(res.getHeader('location')).toBe(`https://www.dextools.io/app/solana/pair-explorer/${SOL_POOL}`);+ expect(res.getHeader('cache-control')).toBe('no-store');+ expect(topPoolForToken).toHaveBeenCalledWith(SOL_TOKEN, 'solana');+ expect(sqlCalls).toHaveLength(1);+ expect(sqlCalls[0].text).toMatch(/insert into dextools_referrals/);+ expect(sqlCalls[0].values).toEqual(['solana', SOL_TOKEN, 'launch-detail']);+ });++ it('pins $THREE to the pair its Social Boost wins were credited to', async () => {+ topPoolForToken.mockResolvedValue(SOL_POOL);+ const res = await call(`address=${THREE_MINT}&from=three-token`);+ expect(res.getHeader('location')).toBe(`https://www.dextools.io/app/solana/pair-explorer/${THREE_PAIR}`);+ expect(topPoolForToken).not.toHaveBeenCalled();+ expect(sqlCalls[0].values).toEqual(['solana', THREE_MINT, 'three-token']);+ });++ it('maps EVM networks to DEXTools chain slugs', async () => {+ topPoolForToken.mockResolvedValue(EVM_POOL);+ const eth = await call(`address=${EVM_TOKEN}&network=eth`);+ expect(eth.getHeader('location')).toBe(`https://www.dextools.io/app/ether/pair-explorer/${EVM_POOL}`);+ const bsc = await call(`address=${EVM_TOKEN}&network=bsc`);+ expect(bsc.getHeader('location')).toBe(`https://www.dextools.io/app/bnb/pair-explorer/${EVM_POOL}`);+ });++ it('still lands on DEXTools, keyed by the token, when no pool resolves', async () => {+ topPoolForToken.mockRejectedValue(Object.assign(new Error('no pool'), { status: 404 }));+ const res = await call(`address=${SOL_TOKEN}`);+ expect(res.statusCode).toBe(302);+ expect(res.getHeader('location')).toBe(`https://www.dextools.io/app/solana/pair-explorer/${SOL_TOKEN}`);+ });++ it('never blocks the redirect on a database failure', async () => {+ topPoolForToken.mockResolvedValue(THREE_PAIR);+ sqlImpl = async () => { throw Object.assign(new Error('down'), { code: 'db_unavailable' }); };+ const res = await call(`address=${THREE_MINT}`);+ expect(res.statusCode).toBe(302);+ expect(res.getHeader('location')).toContain(THREE_PAIR);+ });++ it('files an unrecognised surface label under "direct"', async () => {+ topPoolForToken.mockResolvedValue(THREE_PAIR);+ await call(`address=${THREE_MINT}&from=${encodeURIComponent('<script>')}`);+ expect(sqlCalls[0].values[2]).toBe('direct');+ });++ it('rejects a malformed address before any lookup', async () => {+ const res = await call('address=not-a-mint');+ expect(res.statusCode).toBe(400);+ expect(topPoolForToken).not.toHaveBeenCalled();+ expect(sqlCalls).toHaveLength(0);+ });++ it('rejects an unknown network', async () => {+ const res = await call(`address=${THREE_MINT}&network=tron`);+ expect(res.statusCode).toBe(400);+ });+});diff --git a/tests/dextools-boost.dom.test.js b/tests/dextools-boost.dom.test.jsnew file mode 100644index 000000000..63d620332--- /dev/null+++ b/tests/dextools-boost.dom.test.js@@ -0,0 +1,104 @@+// @vitest-environment jsdom+//+// DEXTools links and the "Rally on DEXTools" Social Boost card.+//+// What is pinned:+// 1. dextoolsUrl() emits DEXTools' canonical pair-explorer form (the /app/en/+// form 301s to it) and refuses an address that is malformed for the chain,+// so no surface renders a dead DEXTools link.+// 2. The rally post ends with the DEXTools link, so X renders its card.+// 3. The card prefers the pair page over the mint (Social Boost credits a+// specific pair), honors a caller's counted `href` on every outbound link,+// takes the host page's own button classes, and renders nothing for an+// address it cannot link.++import { describe, it, expect } from 'vitest';+import { dextoolsUrl, socialBoostRallyText, socialBoostRallyIntent, SOCIAL_BOOST_URL } from '../src/shared/dextools.js';+import { socialBoostCard } from '../src/shared/dextools-boost.js';+import { SOCIAL_BOOST_WINS, SOCIAL_BOOST_STORY_PATH } from '../src/pump/dextools-social-boost.js';++const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const PAIR = 'CnK82s8exdsK9nwqQ55kd9wcxoA22NwTchZJCBdu8LDa';+const EVM = '0x' + 'ab'.repeat(20);++describe('dextoolsUrl', () => {+ it('builds the canonical Solana pair-explorer URL for a pair or a mint', () => {+ expect(dextoolsUrl(PAIR)).toBe(`https://www.dextools.io/app/solana/pair-explorer/${PAIR}`);+ expect(dextoolsUrl(MINT)).toBe(`https://www.dextools.io/app/solana/pair-explorer/${MINT}`);+ });++ it('maps three.ws chain ids to DEXTools slugs', () => {+ expect(dextoolsUrl(EVM, 'ethereum')).toBe(`https://www.dextools.io/app/ether/pair-explorer/${EVM}`);+ expect(dextoolsUrl(EVM, 'binance-smart-chain')).toContain('/app/bnb/');+ expect(dextoolsUrl(EVM, 'base')).toContain('/app/base/');+ });++ it('refuses malformed, cross-chain and unknown-chain input', () => {+ expect(dextoolsUrl('')).toBeNull();+ expect(dextoolsUrl(undefined)).toBeNull();+ expect(dextoolsUrl('not a mint')).toBeNull();+ expect(dextoolsUrl(EVM, 'solana')).toBeNull();+ expect(dextoolsUrl(MINT, 'ethereum')).toBeNull();+ expect(dextoolsUrl(MINT, 'dogechain')).toBeNull();+ });+});++describe('Social Boost rally post', () => {+ it('names the coin and ends with the DEXTools link', () => {+ const url = dextoolsUrl(PAIR);+ const text = socialBoostRallyText({ symbol: '$THREE', url });+ expect(text.startsWith('$THREE is on DEXTools.')).toBe(true);+ expect(text.endsWith(url)).toBe(true);+ });++ it('encodes the post into an X compose intent', () => {+ const url = dextoolsUrl(PAIR);+ const intent = new URL(socialBoostRallyIntent({ symbol: 'THREE', url }));+ expect(intent.origin + intent.pathname).toBe('https://x.com/intent/post');+ expect(intent.searchParams.get('text')).toBe(socialBoostRallyText({ symbol: 'THREE', url }));+ });+});++describe('socialBoostCard', () => {+ const hrefs = (card) => [...card.querySelectorAll('a')].map((a) => a.getAttribute('href'));++ it('links the pair page when the pair is known, and the leaderboard and story', () => {+ const card = socialBoostCard({ mint: MINT, pair: PAIR, symbol: 'three' });+ const links = hrefs(card);+ expect(links).toContain(dextoolsUrl(PAIR));+ expect(links).not.toContain(dextoolsUrl(MINT));+ expect(links).toContain(SOCIAL_BOOST_URL);+ expect(links).toContain(SOCIAL_BOOST_STORY_PATH);+ expect(card.querySelector('.dtb-title').textContent).toBe('Rally $three on DEXTools');+ });++ it('falls back to the mint when no pair is known', () => {+ expect(hrefs(socialBoostCard({ mint: MINT }))).toContain(dextoolsUrl(MINT));+ });++ it('sends the open link and the rally post through a caller-supplied counted href', () => {+ const counted = `https://three.ws/api/coin/dextools?address=${MINT}&network=solana&from=test`;+ const card = socialBoostCard({ mint: MINT, symbol: 'THREE', href: counted });+ const links = hrefs(card);+ expect(links).toContain(counted);+ expect(links).toContain(socialBoostRallyIntent({ symbol: 'THREE', url: counted }));+ });++ it('states the $THREE record from the one Social Boost source', () => {+ const card = socialBoostCard({ mint: MINT });+ expect(card.querySelector('.dtb-proof').textContent).toContain(`won it ${SOCIAL_BOOST_WINS.length} times`);+ });++ it('wears the host page button classes', () => {+ const card = socialBoostCard({ mint: MINT, buttonClass: 'host-btn', primaryClass: 'host-btn primary' });+ const [open, rally, copy] = card.querySelector('.dtb-actions').children;+ expect(open.className).toBe('host-btn primary');+ expect(rally.className).toBe('host-btn');+ expect(copy.className).toBe('host-btn');+ expect(copy.getAttribute('type')).toBe('button');+ });++ it('renders nothing for an address it cannot link', () => {+ expect(socialBoostCard({ mint: 'nope' })).toBeNull();+ });+});diff --git a/tests/trading-terminals.test.js b/tests/trading-terminals.test.jsindex b14e2dc5e..0349498f6 100644--- a/tests/trading-terminals.test.js+++ b/tests/trading-terminals.test.js@@ -121,7 +121,7 @@ describe('referralOffers', () => {describe('terminalLinks', () => {it('covers every terminal with a label, short code and url', () => {const links = terminalLinks(MINT);- expect(links.map((t) => t.key)).toEqual(['axiom', 'gmgn', 'padre', 'fomo']);+ expect(links.map((t) => t.key)).toEqual(['dextools', 'axiom', 'gmgn', 'padre', 'fomo']);for (const t of links) {expect(t.label).toBe(TERMINAL_LABELS[t.key]);expect(t.short).toHaveLength(3);@@ -134,6 +134,15 @@ describe('terminalLinks', () => {expect(withCode.map((t) => t.key)).toEqual(['gmgn']);});+ it('sends DEXTools through the counted three.ws resolver, attributed to the caller', () => {+ const dt = terminalLinks(MINT, { from: 'launch-detail' }).find((t) => t.key === 'dextools');+ const url = new URL(dt.url);+ expect(url.origin + url.pathname).toBe('https://three.ws/api/coin/dextools');+ expect(url.searchParams.get('address')).toBe(MINT);+ expect(url.searchParams.get('network')).toBe('solana');+ expect(url.searchParams.get('from')).toBe('launch-detail');+ });+it('escapes a mint containing url-unsafe characters', () => {const links = terminalLinks('abc/def?x=1');for (const t of links) {