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(radar): fork a leader's open position straight into the live trade panel
nirholas95e411caaa9f
diff --git a/pages/radar.html b/pages/radar.htmlindex 769948eea..44d73ce1d 100644--- a/pages/radar.html+++ b/pages/radar.html@@ -3,6 +3,7 @@<head><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" />+ <script src="/referral-capture.js"></script><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title data-i18n="radar.meta_title">Coin Radar — live pump.fun launch intelligence · three.ws</title><metadiff --git a/pages/trades.html b/pages/trades.htmlindex 6c7b4fcbc..3931c9cf8 100644--- a/pages/trades.html+++ b/pages/trades.html@@ -3,6 +3,7 @@<head><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" />+ <script src="/referral-capture.js"></script><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title data-i18n="trades.meta_title">Trade Terminal · three.ws</title><metadiff --git a/src/fork-trade.js b/src/fork-trade.jsnew file mode 100644index 000000000..2913cf15f--- /dev/null+++ b/src/fork-trade.js@@ -0,0 +1,230 @@+/**+ * Fork a trade: the one-tap "do what they just did" action.+ *+ * A leaderboard says who is good. A ghost-copy replay says what their edge+ * would have done to your budget. Neither one lets you act. Fork closes that+ * gap everywhere a coin is rendered: one tap opens the real pump.fun trade+ * panel (src/game/coin-buy.js) for that exact mint, pre-filled with the size+ * being forked, and the user's own wallet signs it. Nothing here custodies,+ * delegates, or auto-executes: the fork is a pre-filled intent, the human is+ * still the signer.+ *+ * Three pieces, so any surface can adopt it in a few lines:+ *+ * forkButton(...) → markup for template-rendered surfaces (innerHTML)+ * mountForkLinks(root) → one delegated listener for every [data-fork-mint]+ * initFork() → the above, plus the ?fork=<mint> deep link+ *+ * The deep link is what makes a fork travel. Any shared artifact (a PnL card, a+ * Telegram post, an X reply) can carry `?fork=<mint>&fork_size=<sol>` back to a+ * page that calls initFork(), and the trade panel opens on arrival with the+ * referrer's code already parked by /referral-capture.js. That is the whole+ * viral unit: not "follow me", but "do what I just did, right now".+ *+ * The heavy Solana + pump SDKs live behind a dynamic import, so a page that+ * merely renders fork buttons never pays for them until one is clicked.+ */++import { toast } from './shared/toast.js';++export const FORK_PARAM = 'fork';+export const FORK_SIZE_PARAM = 'fork_size';++// A forked size arrives from a link a stranger wrote, so it is clamped before+// it is ever shown as an amount. The user still reviews and signs, but a link+// must not be able to pre-fill a life-changing number and hope for a fat+// finger. Forks are "match their conviction", not "wire your net worth".+export const MAX_FORK_SOL = 10;++const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++/** @param {unknown} v @returns {boolean} true when v looks like a base58 mint. */+export function isMint(v) {+ return typeof v === 'string' && MINT_RE.test(v);+}++/**+ * Coerce an untrusted fork size into a usable SOL amount.+ * @param {unknown} raw+ * @returns {number|null} a positive amount capped at MAX_FORK_SOL, else null.+ */+export function clampForkSize(raw) {+ const n = Number(raw);+ if (!Number.isFinite(n) || n <= 0) return null;+ // Four decimals is the finest size the trade panel quotes in; rounding here+ // stops 0.30000000000000004 landing in the amount input.+ return Number(Math.min(n, MAX_FORK_SOL).toFixed(4));+}++/**+ * Build the fork query string for a trade.+ * @param {{mint:string, size?:number|string}} trade+ * @param {string} [base] path the link should land on (default: this page).+ * @returns {string} e.g. `/trades?fork=<mint>&fork_size=0.5`+ */+export function forkPath(trade, base) {+ if (!isMint(trade?.mint)) return '';+ const path = base || location.pathname;+ const q = new URLSearchParams();+ q.set(FORK_PARAM, trade.mint);+ const size = clampForkSize(trade.size);+ if (size != null) q.set(FORK_SIZE_PARAM, String(size));+ return `${path}?${q}`;+}++// The viewer's referral code, fetched once per page. Signed-out visitors have+// none, which is not an error: they simply share a bare fork link.+let refCodeP = null;+function referralCode() {+ if (!refCodeP) {+ refCodeP = fetch('/api/users/referrals', { credentials: 'include', headers: { accept: 'application/json' } })+ .then((r) => (r.ok ? r.json() : null))+ .then((card) => card?.referral_code || card?.code || card?.referralCode || null)+ .catch(() => null);+ }+ return refCodeP;+}++/**+ * The absolute, shareable fork URL, carrying the sharer's referral code when+ * they have one so the loop pays whoever spread it.+ * @param {{mint:string, size?:number|string}} trade+ * @param {{base?:string}} [opts]+ * @returns {Promise<string>}+ */+export async function forkShareUrl(trade, { base } = {}) {+ const path = forkPath(trade, base);+ if (!path) return '';+ const url = new URL(path, location.origin);+ const ref = await referralCode();+ if (ref) url.searchParams.set('ref', ref);+ return url.toString();+}++/**+ * Open the real trade panel for a coin, pre-filled with the forked size.+ * @param {{mint:string, symbol?:string, name?:string, image?:string, size?:number|string}} trade+ * @returns {Promise<boolean>} false when the panel could not be loaded.+ */+export async function openFork(trade) {+ if (!isMint(trade?.mint)) return false;+ try {+ const { openBuyModal } = await import('./game/coin-buy.js');+ openBuyModal(+ { mint: trade.mint, symbol: trade.symbol, name: trade.name, image: trade.image },+ { mode: 'buy', amount: clampForkSize(trade.size) ?? undefined },+ );+ return true;+ } catch {+ toast('Could not open the trade panel. Trade this coin on pump.fun instead.', { variant: 'error' });+ return false;+ }+}++const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));++/**+ * Markup for a fork button, for the surfaces that render with innerHTML.+ * DOM-built surfaces should use forkAttrs() and set the attributes directly.+ * @param {{mint:string, symbol?:string, name?:string, size?:number|string}} trade+ * @param {{label?:string, className?:string, share?:boolean, title?:string}} [opts]+ * @returns {string}+ */+export function forkButton(trade, opts = {}) {+ if (!isMint(trade?.mint)) return '';+ const size = clampForkSize(trade.size);+ const sym = trade.symbol ? `$${String(trade.symbol).toUpperCase()}` : 'this coin';+ const label = opts.label || (size != null ? `Fork ${size} SOL` : 'Fork trade');+ const aria = opts.share+ ? `Share a fork link for ${sym}`+ : `Fork this trade: buy ${sym}${size != null ? ` with ${size} SOL` : ''} from your own wallet`;+ return `<button type="button" class="${esc(opts.className || 'fork-btn')}"${opts.share ? ' data-fork-share="1"' : ''}` ++ ` data-fork-mint="${esc(trade.mint)}"` ++ (trade.symbol ? ` data-fork-symbol="${esc(trade.symbol)}"` : '') ++ (trade.name ? ` data-fork-name="${esc(trade.name)}"` : '') ++ (size != null ? ` data-fork-size="${esc(size)}"` : '') ++ ` aria-label="${esc(aria)}"${opts.title ? ` title="${esc(opts.title)}"` : ''}>${esc(label)}</button>`;+}++/**+ * Read a fork trade off an element's data attributes.+ * @param {Element} el+ * @returns {{mint:string, symbol?:string, name?:string, image?:string, size?:number}|null}+ */+export function forkFromEl(el) {+ const mint = el?.getAttribute?.('data-fork-mint');+ if (!isMint(mint)) return null;+ return {+ mint,+ symbol: el.getAttribute('data-fork-symbol') || undefined,+ name: el.getAttribute('data-fork-name') || undefined,+ image: el.getAttribute('data-fork-image') || undefined,+ size: clampForkSize(el.getAttribute('data-fork-size')) ?? undefined,+ };+}++const mounted = new WeakSet();++/**+ * Delegate every [data-fork-mint] click inside `root` to the trade panel, and+ * every [data-fork-share] click to the share sheet. Idempotent per root, so a+ * surface that re-renders its rows can call it as often as it likes.+ * @param {Document|Element} [root]+ */+export function mountForkLinks(root = document) {+ if (mounted.has(root)) return;+ mounted.add(root);+ root.addEventListener('click', async (e) => {+ const el = e.target instanceof Element ? e.target.closest('[data-fork-mint]') : null;+ if (!el || !root.contains(el)) return;+ const trade = forkFromEl(el);+ if (!trade) return;+ e.preventDefault();+ e.stopPropagation();+ if (el.hasAttribute('data-fork-share')) {+ const url = await forkShareUrl(trade);+ if (!url) return;+ const sym = trade.symbol ? `$${String(trade.symbol).toUpperCase()}` : 'this coin';+ const { showSharePanel } = await import('./shared/share.js');+ showSharePanel({+ kind: 'fork',+ id: trade.mint,+ title: `Fork this ${sym} trade`,+ description: 'One tap opens the real pump.fun trade, pre-filled. Their wallet signs it, not ours.',+ shareText: `Forking ${sym} on three.ws${trade.size ? ` at ${trade.size} SOL` : ''}`,+ shareUrl: url,+ }, el);+ return;+ }+ await openFork(trade);+ });+}++/**+ * Consume a `?fork=<mint>` deep link: open the trade panel for it and strip the+ * fork params from the URL so a refresh (or a back-navigation) does not reopen+ * a panel the user already dismissed. Every other param, `ref` included, stays.+ * @returns {boolean} true when a fork link was present and honored.+ */+export function consumeForkLink() {+ const q = new URLSearchParams(location.search);+ const mint = q.get(FORK_PARAM);+ if (!isMint(mint)) return false;+ const size = clampForkSize(q.get(FORK_SIZE_PARAM));+ q.delete(FORK_PARAM);+ q.delete(FORK_SIZE_PARAM);+ const rest = q.toString();+ history.replaceState(null, '', location.pathname + (rest ? `?${rest}` : '') + location.hash);+ openFork({ mint, size: size ?? undefined });+ return true;+}++/**+ * Everything a page needs in one call: delegated fork buttons plus the deep+ * link. Safe to call before the rows exist, since the listener is delegated.+ * @param {{root?: Document|Element, deepLink?: boolean}} [opts]+ */+export function initFork({ root = document, deepLink = true } = {}) {+ mountForkLinks(root);+ if (deepLink) consumeForkLink();+}diff --git a/src/game/coin-buy.js b/src/game/coin-buy.jsindex 2380d1def..b52f209ba 100644--- a/src/game/coin-buy.js+++ b/src/game/coin-buy.js@@ -112,22 +112,27 @@ function friendlyTradeError(err, mode = 'buy') {}/**- * Open the trade modal for a coin. Idempotent — a second call refocuses the- * existing modal instead of stacking. Opens in Buy mode; the user can switch to- * Sell inside the modal.+ * Open the trade modal for a coin. A second call for the SAME coin refocuses+ * the open modal instead of stacking; a call for a DIFFERENT coin replaces it,+ * so a forked trade never leaves the user staring at the previous coin's panel.+ * Opens in Buy mode; the user can switch to Sell inside the modal.* @param {{mint:string, name?:string, symbol?:string, image?:string}} coin- * @param {{mode?: 'buy'|'sell'}} [opts]+ * @param {{mode?: 'buy'|'sell', amount?: number}} [opts] `amount` pre-fills the+ * buy input (SOL), which is how a forked trade carries its size across.*/export function openBuyModal(coin, opts = {}) {if (!coin?.mint) return;- if (_open) { _open.focus(); return; }- _open = new TradeModal(coin, opts.mode === 'sell' ? 'sell' : 'buy');+ if (_open) {+ if (_open.coin?.mint === coin.mint) { _open.focus(); return; }+ _open.close();+ }+ _open = new TradeModal(coin, opts.mode === 'sell' ? 'sell' : 'buy', opts);}export { openBuyModal as openTradeModal };class TradeModal {- constructor(coin, mode = 'buy') {+ constructor(coin, mode = 'buy', opts = {}) {this.coin = coin;this.symPlain = coin.symbol ? '$' + coin.symbol.toUpperCase() : '';this.sym = coin.symbol ? '$' + coin.symbol.toUpperCase() : 'this coin';@@ -137,6 +142,12 @@ class TradeModal {// coin renders identically to the original widget with no flicker.this.denom = SOL_DENOM;this.amount = mode === 'buy' ? SOL_DENOM.presets[0] : 0;+ // A forked trade opens pre-filled with the size it is forking. It is only+ // honoured for SOL-denominated buys: if the coin turns out to price in+ // USDC, _detectDenom falls back to the USDC preset, because a SOL number+ // means nothing against a USDC curve.+ const preset = Number(opts.amount);+ if (mode === 'buy' && Number.isFinite(preset) && preset > 0) this.amount = preset;this._sellMax = false;this.slippageBps = DEFAULT_SLIPPAGE_BPS;this.busy = false;diff --git a/src/radar.css b/src/radar.cssindex 470a86ebf..142a02341 100644--- a/src/radar.css+++ b/src/radar.css@@ -379,6 +379,20 @@.rc-detail:active { transform: translateY(1px); }.rc-detail:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: 2px; }+/* Fork: the radar's one live action. Opens the real pump.fun trade panel for+ this coin (src/fork-trade.js); the visitor's own wallet signs it. Accented so+ it reads as the action among the read-only links beside it. */+.rc-fork {+ font-size: var(--text-sm); font-weight: var(--weight-semibold); color: var(--ink);+ background: color-mix(in srgb, var(--accent) 16%, transparent);+ border: 1px solid color-mix(in srgb, var(--accent) 45%, var(--stroke));+ border-radius: var(--radius-md); padding: var(--space-2xs) var(--space-sm); cursor: pointer;+ transition: background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard);+}+.rc-fork:hover { background: color-mix(in srgb, var(--accent) 28%, transparent); border-color: var(--accent); }+.rc-fork:active { transform: translateY(1px); }+.rc-fork:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: 2px; }+.rc-watch {font-size: var(--text-md); line-height: 1; padding: var(--space-2xs) var(--space-xs);background: var(--surface-2); border: 1px solid var(--stroke); border-radius: var(--radius-md);diff --git a/src/radar.js b/src/radar.jsindex 3759c20c2..9274df0be 100644--- a/src/radar.js+++ b/src/radar.js@@ -13,6 +13,7 @@// ════════════════════════════════════════════════════════════════════════════import { createLogger } from './shared/log.js';+import { initFork, openFork } from './fork-trade.js';const log = createLogger('radar');@@ -923,7 +924,25 @@ function renderCard(coin) {watchBtn.title = nowWatched ? 'Remove from watchlist' : 'Add to watchlist';});- foot.append(scan, detail, watchBtn);+ // Fork: the one action on an otherwise read-only card. Opens the real trade+ // panel for this coin; the visitor's own wallet signs. Mainnet only, since a+ // devnet coin has no market to buy into.+ const forkBtn = coin.network === 'devnet' ? null : el('button', 'rc-fork', 'Fork');+ if (forkBtn) {+ forkBtn.type = 'button';+ const sym = coin.symbol ? `$${String(coin.symbol).toUpperCase()}` : 'this coin';+ forkBtn.setAttribute('aria-label', `Fork this trade: buy ${sym} from your own wallet`);+ forkBtn.title = `Buy ${sym} from your own wallet`;+ // Bound directly rather than via fork-trade's delegation: the card itself+ // listens for clicks to open the quick-view drawer, so this has to stop+ // the event at the button, which a document-level delegate never sees.+ forkBtn.addEventListener('click', (e) => {+ e.stopPropagation();+ openFork({ mint: coin.mint, symbol: coin.symbol, name: coin.name, image: coin.image_uri });+ });+ }++ foot.append(scan, detail, ...(forkBtn ? [forkBtn] : []), watchBtn);card.append(foot);if (isNew) requestAnimationFrame(() => card.classList.remove('is-enter'));@@ -1679,6 +1698,9 @@ function renderWalletLedger(coin) {export function mountRadar(mountEl) {root = mountEl;readUrl();+ // An inbound ?fork=<mint> link opens the real trade panel on arrival. Runs+ // before the first writeUrl() rewrites the query string.+ initFork();render();fetchFeed();fetchPulse();diff --git a/src/trades-detail.js b/src/trades-detail.jsindex 10b287b23..9c04c1590 100644--- a/src/trades-detail.js+++ b/src/trades-detail.js@@ -28,6 +28,7 @@ import { mountBondingCurve } from './widgets/bonding-curve.js';import { mountBubblemap } from './trades-bubblemap.js';import { mountTradeTape } from './trades-tape.js';import { escapeHtml, compact, shortAddr, relTime, identicon } from './trader-format.js';+import { forkButton } from './fork-trade.js';const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';@@ -675,6 +676,8 @@ function shell({ mint, network, sym, name, img, isThree, exit }) {<p class="dd-desc" data-host="desc" hidden></p></div><div class="dd-hero-actions">+ ${forkButton({ mint, symbol: sym, name }, { label: 'Fork trade', className: 'dd-btn dd-btn--primary', title: 'Buy this coin from your own wallet' })}+ ${forkButton({ mint, symbol: sym, name }, { label: 'Share ↗', className: 'dd-btn', share: true, title: 'Share a one-tap fork link for this coin' })}<a href="https://pump.fun/${escapeHtml(mint)}" target="_blank" rel="noopener" class="dd-btn">pump.fun ↗</a><a href="/oracle/coin/${encodeURIComponent(mint)}" class="dd-btn dd-btn--oracle">Oracle ↗</a></div>diff --git a/src/trades.js b/src/trades.jsindex a9297656d..59edf8610 100644--- a/src/trades.js+++ b/src/trades.js@@ -20,6 +20,7 @@import { mountDetail } from './trades-detail.js';import { escapeHtml, compact, shortAddr, relTime } from './trader-format.js';+import { initFork, FORK_PARAM } from './fork-trade.js';const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;@@ -55,6 +56,7 @@ function init() {// Open the deep-dive immediately so the terminal is never an empty void —// the URL mint if present, otherwise the platform coin.select(state.selected || THREE_MINT, state.selected ? null : threeSeed(), { push: false });+ initFork();feedTimer = setInterval(() => loadFeed(false), FEED_REFRESH_MS);pulseTimer = setInterval(loadPulse, PULSE_REFRESH_MS);window.addEventListener('beforeunload', teardown);@@ -73,7 +75,10 @@ function threeSeed() {// ── URL ───────────────────────────────────────────────────────────────────────function readUrl() {const p = new URL(location.href).searchParams;- const m = p.get('mint') || p.get('coin');+ // `?fork=<mint>` is an inbound fork link (see src/fork-trade.js). It selects+ // the coin here as well as opening the trade panel, so the visitor lands on+ // the full deep-dive behind the panel rather than a terminal showing $THREE.+ const m = p.get('mint') || p.get('coin') || p.get(FORK_PARAM);if (m && MINT_RE.test(m)) state.selected = m;if (p.get('network') === 'devnet') state.network = 'devnet';if (p.get('tab') === 'exits') state.tab = 'exits';diff --git a/tests/fork-trade.test.js b/tests/fork-trade.test.jsnew file mode 100644index 000000000..7d210a794--- /dev/null+++ b/tests/fork-trade.test.js@@ -0,0 +1,148 @@+// @vitest-environment jsdom+//+// Fork a trade: the one-tap "do what they just did" action shared by every+// coin surface (/trades, /ghost-copy, /radar).+//+// Two properties matter enough to pin. First, a fork size arrives inside a link+// a stranger wrote, so it must be clamped and sanitised before it is ever+// pre-filled as an amount: a link must not be able to seed a life-changing+// number and hope for a fat finger. Second, a fork link has to survive the trip+// through X or Telegram and still open the right panel on arrival, which means+// the deep link is parsed, honoured exactly once, and stripped from the URL+// without taking the referral code with it.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import {+ isMint,+ clampForkSize,+ forkPath,+ forkButton,+ forkFromEl,+ consumeForkLink,+ MAX_FORK_SOL,+ FORK_PARAM,+ FORK_SIZE_PARAM,+} from '../src/fork-trade.js';++// A synthetic, clearly-placeholder mint: never a real third-party coin.+const MINT = 'THREEsynthetic1111111111111111111111111111';++const openBuyModal = vi.fn();+vi.mock('../src/game/coin-buy.js', () => ({ openBuyModal: (...a) => openBuyModal(...a) }));++function goTo(search) {+ window.history.replaceState(null, '', `/radar${search}`);+}++describe('mint validation', () => {+ it('accepts a base58 mint and rejects everything else', () => {+ expect(isMint(MINT)).toBe(true);+ expect(isMint('')).toBe(false);+ expect(isMint(null)).toBe(false);+ expect(isMint('not a mint')).toBe(false);+ // base58 excludes 0, O, I and l, so an address carrying them is not one.+ expect(isMint('0OIl'.repeat(9))).toBe(false);+ expect(isMint(`${MINT}${MINT}`)).toBe(false);+ });+});++describe('fork size clamping', () => {+ it('keeps a sane size', () => {+ expect(clampForkSize(0.5)).toBe(0.5);+ expect(clampForkSize('1.25')).toBe(1.25);+ });++ it('caps a hostile size at the ceiling rather than pre-filling it', () => {+ expect(clampForkSize(9_999)).toBe(MAX_FORK_SOL);+ expect(clampForkSize(String(Number.MAX_SAFE_INTEGER))).toBe(MAX_FORK_SOL);+ });++ it('rejects a size that is not a positive number', () => {+ for (const bad of [0, -1, 'abc', '', null, undefined, NaN, Infinity, {}]) {+ expect(clampForkSize(bad)).toBeNull();+ }+ });++ it('rounds to the precision the trade panel actually quotes in', () => {+ expect(clampForkSize(0.1 + 0.2)).toBe(0.3);+ expect(clampForkSize(0.123456789)).toBe(0.1235);+ });+});++describe('fork links', () => {+ it('builds a link carrying the mint and the clamped size', () => {+ const url = new URL(forkPath({ mint: MINT, size: 0.5 }, '/trades'), 'https://three.ws');+ expect(url.pathname).toBe('/trades');+ expect(url.searchParams.get(FORK_PARAM)).toBe(MINT);+ expect(url.searchParams.get(FORK_SIZE_PARAM)).toBe('0.5');+ });++ it('omits the size when there is none to carry', () => {+ const url = new URL(forkPath({ mint: MINT }, '/trades'), 'https://three.ws');+ expect(url.searchParams.has(FORK_SIZE_PARAM)).toBe(false);+ });++ it('refuses to build a link for a non-mint', () => {+ expect(forkPath({ mint: 'nope' }, '/trades')).toBe('');+ });+});++describe('fork button markup', () => {+ it('labels itself with the size it forks and escapes what it is handed', () => {+ const html = forkButton({ mint: MINT, symbol: '"><script>x</script>', size: 0.5 });+ expect(html).toContain('Fork 0.5 SOL');+ expect(html).not.toContain('<script>');+ expect(html).toContain('<script>');+ });++ it('renders nothing for a row with no valid mint', () => {+ expect(forkButton({ mint: null })).toBe('');+ });++ it('round-trips through the data attributes it writes', () => {+ document.body.innerHTML = forkButton({ mint: MINT, symbol: 'TICKER', name: 'Ticker', size: 99_999 });+ const trade = forkFromEl(document.querySelector('[data-fork-mint]'));+ expect(trade).toEqual({ mint: MINT, symbol: 'TICKER', name: 'Ticker', image: undefined, size: MAX_FORK_SOL });+ });+});++describe('the ?fork= deep link', () => {+ beforeEach(() => { openBuyModal.mockClear(); });++ it('opens the trade panel at the forked size and strips only the fork params', async () => {+ goTo(`?${FORK_PARAM}=${MINT}&${FORK_SIZE_PARAM}=0.5&ref=ABC123&view=list`);+ expect(consumeForkLink()).toBe(true);+ await vi.waitFor(() => expect(openBuyModal).toHaveBeenCalledTimes(1));+ expect(openBuyModal).toHaveBeenCalledWith(+ expect.objectContaining({ mint: MINT }),+ expect.objectContaining({ mode: 'buy', amount: 0.5 }),+ );+ const after = new URL(window.location.href);+ expect(after.searchParams.has(FORK_PARAM)).toBe(false);+ expect(after.searchParams.has(FORK_SIZE_PARAM)).toBe(false);+ // The referral code is what pays whoever shared the fork, and the view is+ // the visitor's own state. Neither is ours to drop.+ expect(after.searchParams.get('ref')).toBe('ABC123');+ expect(after.searchParams.get('view')).toBe('list');+ });++ it('is honoured once, so a refresh does not reopen a dismissed panel', async () => {+ goTo(`?${FORK_PARAM}=${MINT}`);+ expect(consumeForkLink()).toBe(true);+ await vi.waitFor(() => expect(openBuyModal).toHaveBeenCalledTimes(1));+ expect(consumeForkLink()).toBe(false);+ expect(openBuyModal).toHaveBeenCalledTimes(1);+ });++ it('ignores a link whose mint is junk', () => {+ goTo('?fork=javascript:alert(1)');+ expect(consumeForkLink()).toBe(false);+ expect(openBuyModal).not.toHaveBeenCalled();+ });++ it('does nothing on a page reached without a fork link', () => {+ goTo('?view=grid');+ expect(consumeForkLink()).toBe(false);+ expect(window.location.search).toBe('?view=grid');+ });+});