Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(hood-desk): give any Robinhood Chain wallet a live onchain trading desk

nirholas112eb55aa49a
diff --git a/STRUCTURE.md b/STRUCTURE.md
index fdd66b66e..6ebefe8ba 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -244,7 +244,7 @@ bottom.
| Market surfaces III (protocol/chain/stablecoin detail + fees, DEX volumes, hacks, trending) | Detail pages `→ /protocol/:slug /chain/:name /stablecoin/:id` over [api/defi/protocol.js](api/defi/protocol.js), [api/defi/chain.js](api/defi/chain.js), [api/defi/stablecoin.js](api/defi/stablecoin.js); surfaces `→ /fees /dex-volumes /hacks` over [api/defi/](api/defi) (fees, dex-volumes, hacks over DeFiLlama) + `→ /markets/trending` over [api/coin/trending.js](api/coin/trending.js) (CoinGecko /search/trending); list rows in [src/defi.js](src/defi.js), [src/chains.js](src/chains.js), [src/stablecoins.js](src/stablecoins.js) now deep-link into the detail pages | In-repo | Turns the DeFiLlama list pages into full detail experiences: a protocol page (TVL history + hallmark markers, per-chain breakdown, fees/revenue, funding rounds, methodology), a chain page (TVL + stablecoin + DEX-volume charts, top protocols), a stablecoin page (supply history, per-chain distribution, peg-deviation badge). Plus three new market surfaces — protocol fees & revenue, the DEX-volume leaderboard, and a searchable DeFi hacks database ($16.7B all-time) — and a CoinGecko trending page (most-searched coins/categories/NFTs). All real key-free data, cross-linked. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
| Market detail pages (exchange, category) + DeFi yields | [pages/exchange.html](pages/exchange.html) + [src/exchange-page.js](src/exchange-page.js) `→ /exchange/:id` over [api/coin/exchange.js](api/coin/exchange.js), [pages/category.html](pages/category.html) + [src/category-page.js](src/category-page.js) `→ /category/:id` over [api/coin/category.js](api/coin/category.js) + [api/coin/markets.js](api/coin/markets.js) (`?category=`), [pages/yields.html](pages/yields.html) + [src/yields.js](src/yields.js) `→ /yields` over [api/defi/yields.js](api/defi/yields.js) | In-repo | Rich detail pages that turn list rows into full profiles. Exchange: trust badge, normalized-volume stat, BTC-volume history chart, and a per-pair markets table (spot + derivatives fallback), reached from `/exchanges` and the new Derivatives Exchanges table. Category: rank, sector stats, the full sortable coins table for that sector, and related categories, reached from `/categories`. Yields: an explorer over ~15k live DeFiLlama pools with chain/project/stablecoin/min-TVL filters, APY/TVL sort, URL-synced state, and a per-pool APY+TVL history chart on row expand. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
| Crypto news + archive + markets hub | [pages/markets.html](pages/markets.html) + [src/markets-page.js](src/markets-page.js) `→ /markets`, [pages/markets-news.html](pages/markets-news.html) + [src/markets-news.js](src/markets-news.js) `→ /markets/news`, [pages/news-article.html](pages/news-article.html) + [src/news-article.js](src/news-article.js) `→ /markets/news/article`, [pages/news-archive.html](pages/news-archive.html) + [src/news-archive.js](src/news-archive.js) `→ /markets/archive`, [pages/news-digest.html](pages/news-digest.html) + [src/news-digest.js](src/news-digest.js) `→ /markets/digest`; backend [api/news/](api/news) (feed, article, knowledge, archive, digest, rss, image) over [api/_lib/article-extract.js](api/_lib/article-extract.js) (page→reader→feed→preview ladder) and [api/_lib/news-rights.js](api/_lib/news-rights.js) (publisher rights layer, enforced at every read path), [api/_lib/news-coins.js](api/_lib/news-coins.js) (ticker→live market snapshot), [api/_lib/news-knowledge-store.js](api/_lib/news-knowledge-store.js) (durable `news_knowledge` corpus) + hourly archiver [api/cron/news-archive-append.js](api/cron/news-archive-append.js) over [api/_lib/news.js](api/_lib/news.js) + [api/_lib/news-sources.js](api/_lib/news-sources.js), corpus on `gs://three-ws-news-archive`, purge tooling [scripts/news-takedown-purge.mjs](scripts/news-takedown-purge.mjs) | In-repo | The Markets news wing + front door: /markets/news is “Your briefing”: live news aggregated natively from 197 publisher feeds (Featured/Trending/Saved tabs, breaking ticker, AI briefing card, top-stories hero + rail, search, sentiment, ticker chips, og:image preview resolution for imageless feeds), a rich article reader that shows a bounded lead excerpt plus our own summary/key points/entities/market context and sends the reader to the publisher for the rest (the excerpt cap and any rightsholder takedowns are enforced server-side across the reader, RSS mirror, archive search, and agent knowledge corpus, never just hidden client-side), and renders **live coin cards** (price/24h/7d/sparkline→/coin/:id) for detected tickers, and related coverage. Every read story is recorded to a durable **news knowledge base** (`GET /api/news/knowledge`) that grounds the 3D agents, itself subject to the same excerpt limit. Plus the largest open crypto-news archive (662,047 enriched articles, Sept 2017 → today, EN+中文, GCS-hosted) and the /markets hub aggregating global stats, the top-100 table, breaking news, and every market surface as a hero card. Docs: [docs/coin-pages.md](docs/coin-pages.md), [docs/api-reference.md](docs/api-reference.md), [docs/news-rights.md](docs/news-rights.md) (publisher takedown path) |
-| Robinhood Chain markets + buy flow | Hub + detail pages [pages/markets-robinhood.html](pages/markets-robinhood.html) + [src/markets-robinhood.js](src/markets-robinhood.js) `→ /markets/robinhood`, [pages/robinhood-stock.html](pages/robinhood-stock.html) + [src/robinhood-stock.js](src/robinhood-stock.js) `→ /markets/robinhood/stock/:symbol`, [pages/robinhood-coin.html](pages/robinhood-coin.html) + [src/robinhood-coin.js](src/robinhood-coin.js) `→ /markets/robinhood/coin/:address`, buy flow [src/robinhood-purchase.js](src/robinhood-purchase.js); backend [api/_lib/robinhood.js](api/_lib/robinhood.js) + `api/v1/robinhood/{chain,stocks,stocks-detail,coins,coins-detail,launches}.js` (free) + [api/x402/robinhood-portfolio.js](api/x402/robinhood-portfolio.js) (x402 paid) | In-repo | The 24/7 tokenized-equity board for Robinhood Chain (4663): live Chainlink NAV vs. Uniswap DEX premium for every Stock Token (one multicall, never 95 RPC calls), a memecoin screener across NOXA/The Odyssey launchpads (CoinGecko categories + on-chain launch logs via Blockscout), and chain TVL/gas/block stats. Detail pages add NAV history, holders, transfers, and contract links. Coin pages carry a real buy panel — injected-wallet connect, chain-switch to 4663, live Uniswap v3 `QuoterV2` quote + `SwapRouter02` swap with slippage, LI.FI bridge deep-link; Stock Tokens are display-only (tokenized securities, not offered to US persons) with an eligibility-gated outbound DEX link instead. Paid `portfolio` endpoint returns ERC-8056 `uiMultiplier`-correct holdings. Docs: [docs/robinhood-chain-markets.md](docs/robinhood-chain-markets.md) |
+| Robinhood Chain markets + buy flow | Hub + detail pages [pages/markets-robinhood.html](pages/markets-robinhood.html) + [src/markets-robinhood.js](src/markets-robinhood.js) `→ /markets/robinhood`, [pages/robinhood-stock.html](pages/robinhood-stock.html) + [src/robinhood-stock.js](src/robinhood-stock.js) `→ /markets/robinhood/stock/:symbol`, [pages/robinhood-coin.html](pages/robinhood-coin.html) + [src/robinhood-coin.js](src/robinhood-coin.js) `→ /markets/robinhood/coin/:address`, buy flow [src/robinhood-purchase.js](src/robinhood-purchase.js), wallet desk [pages/hood-desk.html](pages/hood-desk.html) + [src/hood-desk.js](src/hood-desk.js) + [src/hood-desk.css](src/hood-desk.css) `→ /markets/robinhood/desk`; backend [api/_lib/robinhood.js](api/_lib/robinhood.js) + `api/v1/robinhood/{chain,stocks,stocks-detail,coins,coins-detail,launches,desk,wallet}.js` (free, the last two composed for the desk over [api/_lib/robinhood-desk.js](api/_lib/robinhood-desk.js)) + [api/x402/robinhood-portfolio.js](api/x402/robinhood-portfolio.js) (x402 paid) | In-repo | The 24/7 tokenized-equity board for Robinhood Chain (4663): live Chainlink NAV vs. Uniswap DEX premium for every Stock Token (one multicall, never 95 RPC calls), a memecoin screener across NOXA/The Odyssey launchpads (CoinGecko categories + on-chain launch logs via Blockscout), and chain TVL/gas/block stats. Detail pages add NAV history, holders, transfers, and contract links. Coin pages carry a real buy panel: injected-wallet connect, chain-switch to 4663, live Uniswap v3 `QuoterV2` quote + `SwapRouter02` swap with slippage, LI.FI bridge deep-link; Stock Tokens are display-only (tokenized securities, not offered to US persons) with an eligibility-gated outbound DEX link instead. Paid `portfolio` endpoint returns ERC-8056 `uiMultiplier`-correct holdings. The Hood Desk (`/markets/robinhood/desk`) is the wallet-first view of the same chain: paste or connect any address and it loads that wallet's book (native + priced ERC-20 positions), its native balance curve rebuilt from Blockscout's daily and per-transaction feeds (the public RPC is not an archive node), an activity tape that folds token transfers onto the transaction that emitted them, the NAV premium ridge layered by liquidity floor, counterparty flow, and memecoin movers. Read-only and signature-free; the trade ticket reuses the coin pages' swap panel and the Stock Token eligibility gate. Tests: [tests/robinhood-desk.test.js](tests/robinhood-desk.test.js). Docs: [docs/robinhood-chain-markets.md](docs/robinhood-chain-markets.md) |
| Premium Data API pass | [api/premium/](api/premium) + [api/_lib/premium.js](api/_lib/premium.js), dashboards [src/dashboard-next/pages/data-api.js](src/dashboard-next/pages/data-api.js) `→ /dashboard/data-api` + [src/dashboard-next/pages/billing.js](src/dashboard-next/pages/billing.js) `→ /dashboard/billing` | In-repo | Monthly pass in three tiers (Developer $19.99, Pro $99, Enterprise $499 per 30d, tiered rate limits) paid on Solana in $THREE (20% off), SOL, or USDC — replaces per-call x402 on the news archive with an `x402_live_` API key (existing access-control lane) + SIWX browser grants. Quote→sign→verify flow with on-chain balance-delta verification; tables `premium_passes`/`premium_quotes`. Docs: [docs/premium.md](docs/premium.md) |
| Liquidations pulse (/coins) | Collector [services/liquidation-collector/](services/liquidation-collector) (standalone always-on Node service, ported from SperaxOS), proxy [api/coin/liquidations.js](api/coin/liquidations.js) `→ GET /api/coin/liquidations`, UI strip in [src/coins-index.js](src/coins-index.js) `→ /coins` | Live — collector on Cloud Run (`liquidation-collector`, min-instances 1, unthrottled CPU) since 2026-07-10 | Real-time long/short liquidation pain across Binance, Bybit, and OKX public futures WebSocket streams: dominant-side badge (LONG PAIN / SHORT SQUEEZE / BALANCED), 1h long-vs-short bars, and the 3 largest recent liquidations, polled every 30s (pauses on hidden tab). The collector holds long-lived WebSockets so it can't run as a Vercel function — deploy it separately and point `LIQUIDATION_COLLECTOR_URL` at it. No fallback data: the proxy 503s `collector_offline` (never fabricated numbers) when unset or unreachable, and the strip degrades to a quiet single-line offline state. Docs: [docs/api-reference.md#liquidations](docs/api-reference.md#liquidations) |
| BNB Chain campaign hub | [pages/bnb.html](pages/bnb.html) + [src/bnb.js](src/bnb.js) `→ /bnb`, pure helpers [src/bnb-hub-helpers.js](src/bnb-hub-helpers.js), live block-time API [api/bnb/block-time.js](api/bnb/block-time.js) over [api/_lib/bnb/chains.js](api/_lib/bnb/chains.js) `probeBlockTime` | In-repo · hub live, tracks rolling out | The campaign's front door: three feature cards (gasless agent onboarding, on-chain-gated 3D vault, real-time on-chain world), each claim traced to `prompts/bnb-chain/00-CONTEXT.md`'s verified facts (0.45s blocks — never 20k TPS or 250ms finality). Embeds a live block-time widget (real RPC measurement on every load). Each card self-detects liveness via a real HTTP probe against its track's route/API on the running deployment — a 404 renders a designed "coming soon" state, never a dead link — so cards auto-light-up as the sibling tracks below ship: gasless registration `→ /create-agent` + `api/bnb/register-agent.js` (prompt 03), vault `→ /vault` (prompt 12), on-chain world `→ /bnb-latency` (prompt 17) + the Explore on-chain toggle (prompt 16). Campaign root: [prompts/bnb-chain/](prompts/bnb-chain) |
diff --git a/api/_lib/robinhood-desk.js b/api/_lib/robinhood-desk.js
new file mode 100644
index 000000000..0179e0b0f
--- /dev/null
+++ b/api/_lib/robinhood-desk.js
@@ -0,0 +1,340 @@
+// Pure derivations behind the Hood Desk (/markets/robinhood/desk).
+//
+// Everything here is arithmetic over data the callers already fetched from a
+// real upstream (Chainlink multicall, DexScreener, Blockscout, the chain RPC).
+// No I/O, no clock reads beyond what the caller passes in, so every rule the
+// desk renders is unit-testable in isolation. The two endpoints that use it
+// (api/v1/robinhood/desk.js, api/v1/robinhood/wallet.js) own the fetching.
+
+const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
+
+/** Lowercased 0x-address, or null when the input is not one. */
+export function normalizeAddress(value) {
+ const a = String(value || '').trim().toLowerCase();
+ return /^0x[0-9a-f]{40}$/.test(a) ? a : null;
+}
+
+/** Raw atomic integer string to a human unit amount, tolerant of junk input. */
+export function toUnits(raw, decimals) {
+ // Number(null) is 0, which is finite: a null `decimals` (what the indexer
+ // reports for an unverified token) would otherwise divide by 10^0 and print
+ // the raw atomic balance as if it were the real one.
+ if (raw == null || decimals == null) return null;
+ const d = Number(decimals);
+ const n = Number(raw);
+ if (!Number.isFinite(n) || !Number.isFinite(d) || d < 0 || d > 36) return null;
+ return n / 10 ** d;
+}
+
+/**
+ * Liquidity-depth ridge of the Stock Token premium distribution.
+ *
+ * Each layer re-computes the same premium histogram over a progressively
+ * deeper liquidity floor, so the layered ridge answers a real trading question
+ * ("does the NAV spread tighten once you only count pools you can actually
+ * size into?") instead of being a decorative stack of copies. Bins are
+ * symmetric around 0% premium and the tails are clamped into the edge bins so
+ * one broken pool cannot flatten the whole chart.
+ */
+export function premiumRidge(rows, { bins = 41, span = null, layers = 10 } = {}) {
+ const priced = (Array.isArray(rows) ? rows : []).filter(
+ (r) => r && Number.isFinite(r.premiumPct),
+ );
+ // The axis is fitted to the day's actual dispersion rather than pinned to a
+ // constant: Robinhood Chain's Stock Token pools usually sit inside 3% of
+ // NAV, and a fixed wide axis renders every real spread as one spike in the
+ // middle of an empty chart.
+ const widest = priced.reduce((m, r) => Math.max(m, Math.abs(r.premiumPct)), 0);
+ const fitted = Math.min(10, Math.max(1, Math.ceil(widest * 1.3 * 2) / 2));
+ const axis = Number.isFinite(span) && span > 0 ? span : fitted;
+ const width = (axis * 2) / bins;
+ const edges = Array.from({ length: bins }, (_, i) => {
+ const from = -axis + i * width;
+ return { from, to: from + width, center: from + width / 2 };
+ });
+ const binOf = (pct) => {
+ const idx = Math.floor((pct + axis) / width);
+ return Math.min(bins - 1, Math.max(0, idx));
+ };
+
+ const liquidities = priced
+ .map((r) => (Number.isFinite(r.liquidityUsd) ? r.liquidityUsd : 0))
+ .sort((a, b) => a - b);
+ const top = liquidities.length ? liquidities[liquidities.length - 1] : 0;
+ // Floors climb geometrically: liquidity on this chain spans several orders
+ // of magnitude, so linear floors would put every layer in the bottom decile.
+ const floors = Array.from({ length: layers }, (_, i) => {
+ if (i === 0 || top <= 0) return 0;
+ return top * (i / layers) ** 3;
+ });
+
+ const layerRows = floors.map((minLiquidityUsd) => {
+ const kept = priced.filter(
+ (r) => (Number.isFinite(r.liquidityUsd) ? r.liquidityUsd : 0) >= minLiquidityUsd,
+ );
+ const density = new Array(bins).fill(0);
+ for (const r of kept) density[binOf(r.premiumPct)] += 1;
+ return { minLiquidityUsd, count: kept.length, density };
+ });
+
+ const values = priced.map((r) => r.premiumPct).sort((a, b) => a - b);
+ const pick = (q) => (values.length ? values[Math.min(values.length - 1, Math.floor(q * values.length))] : null);
+ const symbols = edges.map((_, i) =>
+ priced.filter((r) => binOf(r.premiumPct) === i).map((r) => r.symbol).slice(0, 12),
+ );
+
+ return {
+ bins: edges,
+ layers: layerRows,
+ symbols,
+ stats: {
+ priced: priced.length,
+ total: Array.isArray(rows) ? rows.length : 0,
+ min: values.length ? values[0] : null,
+ max: values.length ? values[values.length - 1] : null,
+ median: pick(0.5),
+ p10: pick(0.1),
+ p90: pick(0.9),
+ spanPct: axis,
+ },
+ };
+}
+
+/**
+ * The widest NAV dislocations that are actually tradeable: a premium is only
+ * an opportunity if there is a pool deep enough to take size, so rows with no
+ * DEX pair (or a dust pool) are dropped rather than ranked first.
+ */
+export function arbLeaders(rows, { limit = 6, minLiquidityUsd = 2000 } = {}) {
+ return (Array.isArray(rows) ? rows : [])
+ .filter(
+ (r) =>
+ r &&
+ Number.isFinite(r.premiumPct) &&
+ Number.isFinite(r.liquidityUsd) &&
+ r.liquidityUsd >= minLiquidityUsd,
+ )
+ .sort((a, b) => Math.abs(b.premiumPct) - Math.abs(a.premiumPct))
+ .slice(0, limit)
+ .map((r) => ({
+ symbol: r.symbol,
+ name: r.name,
+ address: r.address,
+ premiumPct: r.premiumPct,
+ navPriceUsd: r.navPriceUsd,
+ dexPriceUsd: r.dexPriceUsd,
+ liquidityUsd: r.liquidityUsd,
+ volume24hUsd: r.volume24hUsd,
+ side: r.premiumPct > 0 ? 'dex-rich' : 'dex-cheap',
+ }));
+}
+
+/**
+ * Blockscout coin-balance points to an ascending native-balance series.
+ *
+ * Blockscout returns newest-first and its `value` is the balance AFTER the
+ * transaction, in wei. Series points carry both the native amount and its USD
+ * valuation at the price the caller passes in (a single current price: the
+ * chain exposes no historical ETH price feed, and the client labels the axis
+ * accordingly rather than implying a marked-to-time curve).
+ */
+export function balanceSeries(items, { ethPriceUsd = null, limit = 240 } = {}) {
+ const points = (Array.isArray(items) ? items : [])
+ .map((p) => {
+ const t = Date.parse(p?.block_timestamp || p?.date || '');
+ const eth = toUnits(p?.value, 18);
+ if (!Number.isFinite(t) || eth == null) return null;
+ return {
+ t,
+ eth,
+ usd: Number.isFinite(ethPriceUsd) ? eth * ethPriceUsd : null,
+ block: p?.block_number ?? null,
+ };
+ })
+ .filter(Boolean)
+ // Ties broken by block: several transfers can land inside one 101ms block
+ // timestamp, and the later block carries the balance that is still true.
+ .sort((a, b) => a.t - b.t || (a.block ?? 0) - (b.block ?? 0));
+ // Deduplicate points that share a timestamp (several transfers inside one
+ // 101ms block), keeping the last balance recorded for that instant.
+ const deduped = [];
+ for (const p of points) {
+ if (deduped.length && deduped[deduped.length - 1].t === p.t) deduped[deduped.length - 1] = p;
+ else deduped.push(p);
+ }
+ return deduped.slice(-limit);
+}
+
+/**
+ * One continuous balance curve from the two series Blockscout exposes.
+ *
+ * The per-transaction feed only reaches back ~50 balance-changing transactions
+ * (minutes, for an active wallet), and the by-day feed only keeps ~10 daily
+ * closes. Neither alone is a usable chart: the daily closes carry the older
+ * shape, the per-transaction points carry the live edge, and a daily close is
+ * plotted at the END of its day (or at `now` for today) because that is when
+ * the balance it reports was true.
+ */
+export function mergeBalanceHistory(daily, intraday, { now = Date.now() } = {}) {
+ const intra = Array.isArray(intraday) ? intraday : [];
+ const firstIntraT = intra.length ? intra[0].t : Infinity;
+ const DAY_MS = 86_400_000;
+ const days = (Array.isArray(daily) ? daily : [])
+ .map((p) => ({ ...p, t: Math.min(p.t + DAY_MS - 1000, now) }))
+ .filter((p) => p.t < firstIntraT);
+ return [...days, ...intra];
+}
+
+/** Start/end/delta of a balance series, or nulls when it cannot be measured. */
+export function seriesChange(series) {
+ const s = Array.isArray(series) ? series : [];
+ if (s.length < 2) return { startEth: s[0]?.eth ?? null, endEth: s[s.length - 1]?.eth ?? null, deltaEth: null, pct: null, fromT: s[0]?.t ?? null, toT: s[s.length - 1]?.t ?? null };
+ const startEth = s[0].eth;
+ const endEth = s[s.length - 1].eth;
+ const deltaEth = endEth - startEth;
+ return {
+ startEth,
+ endEth,
+ deltaEth,
+ pct: startEth > 0 ? (deltaEth / startEth) * 100 : null,
+ fromT: s[0].t,
+ toT: s[s.length - 1].t,
+ };
+}
+
+const SWAP_METHODS = /^(swap|exactinput|exactoutput|multicall|execute)/i;
+const CLAIM_METHODS = /^(claim|mint|redeem)/i;
+
+/** Human label + class for one wallet-scoped transaction. */
+export function classifyTransaction(tx, owner) {
+ const me = normalizeAddress(owner);
+ const from = normalizeAddress(tx?.from?.hash);
+ const to = normalizeAddress(tx?.to?.hash);
+ const method = String(tx?.method || '').trim();
+ const value = toUnits(tx?.value, 18) || 0;
+ const types = Array.isArray(tx?.transaction_types) ? tx.transaction_types : [];
+
+ let kind = 'call';
+ if (!to && tx?.created_contract) kind = 'deploy';
+ else if (SWAP_METHODS.test(method) || (types.includes('token_transfer') && types.includes('contract_call'))) kind = 'swap';
+ else if (/^approve/i.test(method)) kind = 'approve';
+ else if (CLAIM_METHODS.test(method)) kind = 'claim';
+ else if (!method && value > 0) kind = from === me ? 'send' : 'receive';
+
+ const counterparty = from === me ? to : from;
+ return {
+ hash: tx?.hash || null,
+ timestamp: tx?.timestamp || null,
+ kind,
+ method: method || (kind === 'send' || kind === 'receive' ? 'transfer' : null),
+ direction: from === me ? 'out' : 'in',
+ counterparty,
+ counterpartyName: (from === me ? tx?.to?.name : tx?.from?.name) || null,
+ valueEth: value || null,
+ feeEth: toUnits(tx?.fee?.value, 18),
+ status: tx?.result === 'success' || tx?.status === 'ok' ? 'ok' : tx?.result || 'pending',
+ block: tx?.block_number ?? tx?.block ?? null,
+ };
+}
+
+/** Human label + class for one wallet-scoped ERC-20/721 transfer. */
+export function classifyTransfer(tr, owner) {
+ const me = normalizeAddress(owner);
+ const from = normalizeAddress(tr?.from?.hash);
+ const to = normalizeAddress(tr?.to?.hash);
+ const decimals = tr?.total?.decimals ?? tr?.token?.decimals ?? 18;
+ const amount = toUnits(tr?.total?.value ?? tr?.value, decimals);
+ const direction = from === me ? 'out' : 'in';
+ let kind = direction === 'out' ? 'send' : 'receive';
+ if (from === ZERO_ADDRESS) kind = 'mint';
+ else if (to === ZERO_ADDRESS) kind = 'burn';
+
+ return {
+ hash: tr?.transaction_hash || tr?.tx_hash || null,
+ timestamp: tr?.timestamp || null,
+ kind,
+ direction,
+ counterparty: direction === 'out' ? to : from,
+ counterpartyName: (direction === 'out' ? tr?.to?.name : tr?.from?.name) || null,
+ token: {
+ address: normalizeAddress(tr?.token?.address_hash || tr?.token?.address),
+ symbol: tr?.token?.symbol || null,
+ name: tr?.token?.name || null,
+ },
+ amount,
+ method: tr?.method || null,
+ status: 'ok',
+ block: tr?.block_number ?? null,
+ };
+}
+
+/**
+ * One time-ordered tape from the transaction and token-transfer feeds.
+ *
+ * A swap shows up in both feeds (one contract call plus its transfers), so
+ * transfers are folded onto the transaction that produced them instead of
+ * printing the same trade twice.
+ */
+export function mergeActivity(transactions, transfers, owner, { limit = 40 } = {}) {
+ const txs = (Array.isArray(transactions) ? transactions : []).map((t) => classifyTransaction(t, owner));
+ const trs = (Array.isArray(transfers) ? transfers : []).map((t) => classifyTransfer(t, owner));
+ const byHash = new Map();
+ for (const tx of txs) {
+ if (tx.hash) byHash.set(tx.hash, { ...tx, tokens: [] });
+ }
+ const orphans = [];
+ for (const tr of trs) {
+ const parent = tr.hash ? byHash.get(tr.hash) : null;
+ const leg = { symbol: tr.token.symbol, address: tr.token.address, amount: tr.amount, direction: tr.direction };
+ if (parent) {
+ if (parent.tokens.length < 4) parent.tokens.push(leg);
+ } else {
+ orphans.push({ ...tr, tokens: [leg] });
+ }
+ }
+ return [...byHash.values(), ...orphans]
+ .sort((a, b) => Date.parse(b.timestamp || 0) - Date.parse(a.timestamp || 0))
+ .slice(0, limit);
+}
+
+/**
+ * Counterparty flow: who this wallet actually trades against, ranked by how
+ * many legs crossed between them. Feeds the flow arcs on the desk.
+ */
+export function counterpartyFlow(events, { limit = 8 } = {}) {
+ const map = new Map();
+ for (const ev of Array.isArray(events) ? events : []) {
+ const addr = normalizeAddress(ev?.counterparty);
+ if (!addr || addr === ZERO_ADDRESS) continue;
+ const row = map.get(addr) || { address: addr, name: ev.counterpartyName || null, inCount: 0, outCount: 0, kinds: {} };
+ if (ev.direction === 'out') row.outCount += 1;
+ else row.inCount += 1;
+ row.kinds[ev.kind] = (row.kinds[ev.kind] || 0) + 1;
+ if (!row.name && ev.counterpartyName) row.name = ev.counterpartyName;
+ map.set(addr, row);
+ }
+ return [...map.values()]
+ .map((r) => ({ ...r, total: r.inCount + r.outCount }))
+ .sort((a, b) => b.total - a.total)
+ .slice(0, limit);
+}
+
+/** Book totals + per-position share of book, highest value first. */
+export function rollupBook(nativeUsd, positions) {
+ const rows = (Array.isArray(positions) ? positions : []).filter(Boolean);
+ const tokensUsd = rows.reduce((sum, p) => sum + (Number.isFinite(p.valueUsd) ? p.valueUsd : 0), 0);
+ const native = Number.isFinite(nativeUsd) ? nativeUsd : 0;
+ const total = native + tokensUsd;
+ const withShare = rows
+ .map((p) => ({ ...p, sharePct: total > 0 && Number.isFinite(p.valueUsd) ? (p.valueUsd / total) * 100 : null }))
+ .sort((a, b) => (b.valueUsd ?? -1) - (a.valueUsd ?? -1));
+ return {
+ bookValueUsd: total,
+ nativeUsd: native,
+ tokensUsd,
+ nativeSharePct: total > 0 ? (native / total) * 100 : null,
+ positions: withShare,
+ positionCount: withShare.length,
+ pricedCount: withShare.filter((p) => Number.isFinite(p.valueUsd)).length,
+ };
+}
diff --git a/api/_lib/robinhood.js b/api/_lib/robinhood.js
index 4b6c848e4..904913aab 100644
--- a/api/_lib/robinhood.js
+++ b/api/_lib/robinhood.js
@@ -261,20 +261,49 @@ export async function feedRoundHistory(feed, count = 24) {
});
}
+// ── Shared cached JSON fetch ───────────────────────────────────────────────
+// Blockscout sits behind Cloudflare bot protection that answers any request
+// carrying a non-browser User-Agent with a 403 interstitial (undici's default
+// UA and a descriptive "three.ws/1.0" UA are both refused; the same URL with a
+// browser UA returns JSON). Every Blockscout-backed field on the Robinhood
+// surfaces (gas prices, ETH price, holders, transfers, wallet balances) read as
+// permanently unavailable until the request identifies as a browser, so the UA
+// is attached here, once, for that host only.
+const BLOCKSCOUT_UA =
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36';
+
// ── DexScreener (chainId "robinhood") ──────────────────────────────────────
async function fetchJson(url, ttl, key, { headers } = {}) {
return cacheWrap(key, ttl, async () => {
- const ctrl = new AbortController();
- const timer = setTimeout(() => ctrl.abort(), 12_000);
- try {
- const res = await fetch(url, { signal: ctrl.signal, headers: { accept: 'application/json', ...headers } });
- if (!res.ok) return { __error: `upstream ${res.status}` };
- return await res.json();
- } catch (err) {
- return { __error: err?.name === 'AbortError' ? 'upstream timeout' : String(err?.message || err) };
- } finally {
- clearTimeout(timer);
+ // Two retries on a 5xx or a transport error before giving up. Blockscout's
+ // address endpoints answer ~1 request in 3 with a bare 500 under load, and
+ // a failure that reaches the cache is pinned for the whole TTL, so the
+ // retry happens INSIDE the cached callback: only a genuinely persistent
+ // outage stores an error.
+ const isBlockscout = String(url).startsWith(BLOCKSCOUT_BASE);
+ const hostHeaders = isBlockscout ? { 'user-agent': BLOCKSCOUT_UA } : {};
+ // Blockscout answers in well under a second when it answers at all, so a
+ // slow attempt there is a dead one: cutting it at 6s keeps three tries
+ // cheaper than a single 12s wait. The other upstreams keep the long
+ // timeout they were tuned for.
+ const perAttemptMs = isBlockscout ? 6_000 : 12_000;
+ let last = { __error: 'upstream unavailable' };
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt) await new Promise((r) => setTimeout(r, 200 * attempt));
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), perAttemptMs);
+ try {
+ const res = await fetch(url, { signal: ctrl.signal, headers: { accept: 'application/json', ...hostHeaders, ...headers } });
+ if (res.ok) return await res.json();
+ last = { __error: `upstream ${res.status}` };
+ if (res.status < 500) return last; // 4xx is an answer, not an outage
+ } catch (err) {
+ last = { __error: err?.name === 'AbortError' ? 'upstream timeout' : String(err?.message || err) };
+ } finally {
+ clearTimeout(timer);
+ }
}
+ return last;
});
}
@@ -400,6 +429,115 @@ export async function blockscoutTransfers(address, limit = 25) {
}));
}
+// ── Blockscout address reads (the Hood Desk's wallet lane) ─────────────────
+// Address-scoped counterparts to the token-scoped readers above. Blockscout is
+// the only lane that can answer these: the public sequencer RPC is not an
+// archive node (eth_getBalance at a past block answers "metadata is not
+// found"), so a wallet's balance history has to come from the indexer.
+
+/** ERC-20 balances held by an address (raw atomic `value` per token). */
+export async function blockscoutAddressTokens(address) {
+ const addr = String(address || '').toLowerCase();
+ if (!/^0x[0-9a-f]{40}$/.test(addr)) return [];
+ const data = await fetchJson(
+ `${BLOCKSCOUT_BASE}/api/v2/addresses/${addr}/token-balances`,
+ 20,
+ `rh:bs:addr:tokens:${addr}`,
+ );
+ return Array.isArray(data) ? data : [];
+}
+
+/** Native-balance points, one per balance-changing transaction (newest first). */
+export async function blockscoutCoinHistory(address) {
+ const addr = String(address || '').toLowerCase();
+ if (!/^0x[0-9a-f]{40}$/.test(addr)) return [];
+ const data = await fetchJson(
+ `${BLOCKSCOUT_BASE}/api/v2/addresses/${addr}/coin-balance-history`,
+ 20,
+ `rh:bs:addr:coinhist:${addr}`,
+ );
+ return Array.isArray(data?.items) ? data.items : [];
+}
+
+/** Daily native-balance closes for the long windows (Blockscout keeps ~10 days). */
+export async function blockscoutCoinHistoryByDay(address) {
+ const addr = String(address || '').toLowerCase();
+ if (!/^0x[0-9a-f]{40}$/.test(addr)) return [];
+ const data = await fetchJson(
+ `${BLOCKSCOUT_BASE}/api/v2/addresses/${addr}/coin-balance-history-by-day`,
+ 60,
+ `rh:bs:addr:coinday:${addr}`,
+ );
+ return Array.isArray(data?.items) ? data.items : [];
+}
+
+/** Recent transactions sent or received by an address (newest first). */
+export async function blockscoutAddressTxs(address, limit = 40) {
+ const addr = String(address || '').toLowerCase();
+ if (!/^0x[0-9a-f]{40}$/.test(addr)) return [];
+ const data = await fetchJson(
+ `${BLOCKSCOUT_BASE}/api/v2/addresses/${addr}/transactions`,
+ 15,
+ `rh:bs:addr:txs:${addr}`,
+ );
+ const items = Array.isArray(data?.items) ? data.items : [];
+ return items.slice(0, limit);
+}
+
+/** Recent token transfers touching an address (newest first). */
+export async function blockscoutAddressTokenTransfers(address, limit = 40) {
+ const addr = String(address || '').toLowerCase();
+ if (!/^0x[0-9a-f]{40}$/.test(addr)) return [];
+ const data = await fetchJson(
+ `${BLOCKSCOUT_BASE}/api/v2/addresses/${addr}/token-transfers`,
+ 15,
+ `rh:bs:addr:transfers:${addr}`,
+ );
+ const items = Array.isArray(data?.items) ? data.items : [];
+ return items.slice(0, limit);
+}
+
+const ERC20_META_ABI = [
+ { type: 'function', name: 'decimals', stateMutability: 'view', inputs: [], outputs: [{ type: 'uint8' }] },
+ { type: 'function', name: 'symbol', stateMutability: 'view', inputs: [], outputs: [{ type: 'string' }] },
+ { type: 'function', name: 'name', stateMutability: 'view', inputs: [], outputs: [{ type: 'string' }] },
+];
+
+/**
+ * On-chain decimals/symbol/name for tokens the indexer has no metadata for.
+ * Unverified launchpad coins are indexed with `decimals: null`, and a balance
+ * divided by a guessed 1e18 is a wrong number on the screen, so the desk asks
+ * the contract itself (one multicall for every unknown token, never one call
+ * per token).
+ */
+export async function erc20Metadata(addresses) {
+ const list = (Array.isArray(addresses) ? addresses : [])
+ .map((a) => String(a || '').toLowerCase())
+ .filter((a, i, arr) => /^0x[0-9a-f]{40}$/.test(a) && arr.indexOf(a) === i);
+ if (!list.length) return {};
+ const client = publicClient(false);
+ const results = await client
+ .multicall({
+ contracts: list.flatMap((address) => [
+ { address, abi: ERC20_META_ABI, functionName: 'decimals' },
+ { address, abi: ERC20_META_ABI, functionName: 'symbol' },
+ { address, abi: ERC20_META_ABI, functionName: 'name' },
+ ]),
+ allowFailure: true,
+ })
+ .catch(() => []);
+ const out = {};
+ for (let i = 0; i < list.length; i++) {
+ const [dec, sym, nam] = [results[i * 3], results[i * 3 + 1], results[i * 3 + 2]];
+ out[list[i]] = {
+ decimals: dec?.status === 'success' ? Number(dec.result) : null,
+ symbol: sym?.status === 'success' ? String(sym.result) : null,
+ name: nam?.status === 'success' ? String(nam.result) : null,
+ };
+ }
+ return out;
+}
+
// ── DefiLlama chain TVL ────────────────────────────────────────────────────
export async function chainTvlHistory() {
const data = await fetchJson(
diff --git a/api/v1/robinhood/desk.js b/api/v1/robinhood/desk.js
new file mode 100644
index 000000000..1a026f6a7
--- /dev/null
+++ b/api/v1/robinhood/desk.js
@@ -0,0 +1,121 @@
+// GET /api/v1/robinhood/desk - the market side of the Hood Desk.
+//
+// Free, keyless. One composed read so the desk boots with a single request
+// instead of five: chain vitals (Blockscout + DefiLlama), the liquidity-depth
+// ridge of Stock Token premium vs Chainlink NAV (one on-chain multicall plus a
+// batched DexScreener snapshot), the widest tradeable dislocations, memecoin
+// movers, and the newest launchpad tokens. The wallet side lives in
+// api/v1/robinhood/wallet.js so this response stays publicly cacheable.
+
+import { defineEndpoint } from '../../_lib/gateway.js';
+import { rateLimited } from '../../_lib/http.js';
+import { limits } from '../../_lib/rate-limit.js';
+import {
+ stockRegistry,
+ chainlinkSnapshot,
+ dexSnapshot,
+ blockscoutStats,
+ chainTvlCurrent,
+ coingeckoCategory,
+ recentLaunches,
+ publicClient,
+ premiumPct,
+ asOf,
+} from '../../_lib/robinhood.js';
+import { premiumRidge, arbLeaders } from '../../_lib/robinhood-desk.js';
+
+const CACHE_CONTROL = 'public, max-age=20, s-maxage=20, stale-while-revalidate=40';
+const DISCLOSURE =
+ 'Stock Tokens are tokenized debt securities issued by Robinhood Assets (Jersey) Ltd and may not be offered, sold, or delivered to US persons. The desk displays them; it never routes an order into one.';
+
+export default defineEndpoint({
+ name: 'v1.robinhood.desk',
+ method: 'GET',
+ auth: 'public',
+ handler: async ({ res, ip }) => {
+ const rl = await limits.robinhoodRead(ip);
+ if (!rl.success) return rateLimited(res, rl, 'Robinhood Chain data is capped at 60 requests/min per IP');
+
+ const reg = stockRegistry();
+ const addresses = reg.tokens.map((t) => t.address);
+ // Every upstream is independent, and each one that fails degrades only
+ // its own panel: the desk renders the vitals it got rather than 500ing
+ // because DefiLlama was slow.
+ const [nav, dex, stats, tvl, blockNumber, launches, memes] = await Promise.all([
+ chainlinkSnapshot().catch(() => ({})),
+ dexSnapshot(addresses).catch(() => ({})),
+ blockscoutStats().catch(() => null),
+ chainTvlCurrent().catch(() => null),
+ publicClient(false).getBlockNumber().then((n) => Number(n)).catch(() => null),
+ recentLaunches({ limit: 8 }).catch(() => []),
+ coingeckoCategory('robinhood-chain-meme', { order: 'volume_desc', perPage: 60 }).catch(() => []),
+ ]);
+
+ const rows = reg.tokens.map((t) => {
+ const addrLc = t.address.toLowerCase();
+ const feed = nav[addrLc] || null;
+ const pair = dex[addrLc] || null;
+ const navPrice = feed?.priceUsd ?? null;
+ const dexPrice = pair?.priceUsd != null ? Number(pair.priceUsd) : null;
+ return {
+ symbol: t.symbol,
+ name: (t.name || '').replace(' • Robinhood Token', ''),
+ address: t.address,
+ navPriceUsd: navPrice,
+ dexPriceUsd: dexPrice,
+ premiumPct: premiumPct(dexPrice, navPrice),
+ liquidityUsd: pair?.liquidity?.usd ?? null,
+ volume24hUsd: pair?.volume?.h24 ?? null,
+ priceChange24hPct: pair?.priceChange?.h24 ?? null,
+ };
+ });
+
+ // CoinGecko returns 168 hourly points per coin; 12 coins of that is most
+ // of the response weight for a rail that draws a 90px sparkline. Every
+ // third point keeps the shape at a quarter of the bytes.
+ const thin = (arr, step = 3) => (Array.isArray(arr) ? arr.filter((_, i) => i % step === 0) : null);
+
+ const movers = memes
+ .map((c) => ({
+ id: c.id,
+ symbol: (c.symbol || '').toUpperCase(),
+ name: c.name,
+ image: c.image || null,
+ priceUsd: c.current_price ?? null,
+ marketCapUsd: c.market_cap ?? null,
+ volume24hUsd: c.total_volume ?? null,
+ change24hPct:
+ c.price_change_percentage_24h_in_currency ?? c.price_change_percentage_24h ?? null,
+ sparkline7d: thin(c.sparkline_in_7d?.price),
+ }))
+ .filter((c) => Number.isFinite(c.change24hPct))
+ .sort((a, b) => Math.abs(b.change24hPct) - Math.abs(a.change24hPct))
+ .slice(0, 12);
+
+ const gasPrices = stats && !stats.__error ? stats.gas_prices || null : null;
+ res.setHeader('cache-control', CACHE_CONTROL);
+ return {
+ chain: {
+ name: 'Robinhood Chain',
+ chainId: 4663,
+ blockHeight: blockNumber ?? (stats?.total_blocks ? Number(stats.total_blocks) : null),
+ averageBlockTimeMs: stats && !stats.__error ? stats.average_block_time ?? null : null,
+ totalTransactions: stats && !stats.__error ? stats.total_transactions ?? null : null,
+ gas: gasPrices
+ ? { slow: gasPrices.slow ?? null, average: gasPrices.average ?? null, fast: gasPrices.fast ?? null, unit: 'gwei' }
+ : null,
+ ethPriceUsd: stats && !stats.__error && stats.coin_price ? Number(stats.coin_price) : null,
+ tvlUsd: tvl ?? null,
+ explorer: 'https://robinhoodchain.blockscout.com',
+ },
+ ridge: premiumRidge(rows),
+ arb: arbLeaders(rows),
+ movers,
+ launches,
+ stockCount: rows.length,
+ disclosure: DISCLOSURE,
+ source: 'chainlink (on-chain) + dexscreener + blockscout + defillama + coingecko',
+ asOf: asOf(),
+ };
+ },
+});
diff --git a/api/v1/robinhood/wallet.js b/api/v1/robinhood/wallet.js
new file mode 100644
index 000000000..2e414ef91
--- /dev/null
+++ b/api/v1/robinhood/wallet.js
@@ -0,0 +1,201 @@
+// GET /api/v1/robinhood/wallet?address=0x… - the wallet side of the Hood Desk.
+//
+// Free, keyless, read-only: any address can be inspected, no signature and no
+// session. One composed read returns the whole book for a Robinhood Chain
+// (4663) wallet:
+//
+// • native ETH balance - chain RPC (eth_getBalance)
+// • ERC-20 positions, priced - Blockscout balances joined to the
+// Chainlink NAV snapshot (Stock Tokens, uiMultiplier-correct per ERC-8056)
+// and to the deepest DexScreener pool (everything else)
+// • native balance history - Blockscout coin-balance history. The
+// public sequencer RPC is not an archive node, so the indexer is the only
+// lane that can answer "what did this wallet hold an hour ago".
+// • activity tape + counterparties - Blockscout transactions folded together
+// with the token transfers they emitted
+//
+// Nothing here is estimated: a token the desk cannot price keeps a null value
+// and is reported as unpriced rather than counted into the book at zero.
+
+import { defineEndpoint } from '../../_lib/gateway.js';
+import { error, rateLimited } from '../../_lib/http.js';
+import { limits } from '../../_lib/rate-limit.js';
+import {
+ publicClient,
+ stockRegistry,
+ chainlinkSnapshot,
+ dexSnapshot,
+ blockscoutStats,
+ blockscoutAddressTokens,
+ blockscoutCoinHistory,
+ blockscoutCoinHistoryByDay,
+ blockscoutAddressTxs,
+ blockscoutAddressTokenTransfers,
+ erc20Metadata,
+ asOf,
+} from '../../_lib/robinhood.js';
+import {
+ normalizeAddress,
+ toUnits,
+ balanceSeries,
+ seriesChange,
+ mergeActivity,
+ mergeBalanceHistory,
+ counterpartyFlow,
+ rollupBook,
+} from '../../_lib/robinhood-desk.js';
+
+const CACHE_CONTROL = 'public, max-age=10, s-maxage=10, stale-while-revalidate=20';
+
+export default defineEndpoint({
+ name: 'v1.robinhood.wallet',
+ method: 'GET',
+ auth: 'public',
+ handler: async ({ res, query, ip }) => {
+ const rl = await limits.robinhoodRead(ip);
+ if (!rl.success) return rateLimited(res, rl, 'Robinhood Chain data is capped at 60 requests/min per IP');
+
+ const address = normalizeAddress(query.address);
+ if (!address) {
+ return error(
+ res,
+ 400,
+ 'invalid_address',
+ 'pass ?address=0x… (a 20-byte Robinhood Chain address)',
+ );
+ }
+
+ const [nativeWei, balances, coinHistory, dayHistory, txs, transfers, stats] = await Promise.all([
+ publicClient(false).getBalance({ address }).then((v) => v.toString()).catch(() => null),
+ blockscoutAddressTokens(address).catch(() => []),
+ blockscoutCoinHistory(address).catch(() => []),
+ blockscoutCoinHistoryByDay(address).catch(() => []),
+ blockscoutAddressTxs(address).catch(() => []),
+ blockscoutAddressTokenTransfers(address).catch(() => []),
+ blockscoutStats().catch(() => null),
+ ]);
+
+ const ethPriceUsd = stats && !stats.__error && stats.coin_price ? Number(stats.coin_price) : null;
+ const held = balances
+ .map((b) => ({
+ address: normalizeAddress(b?.token?.address_hash || b?.token?.address),
+ raw: b?.value ?? null,
+ type: b?.token?.type || 'ERC-20',
+ decimals: b?.token?.decimals != null ? Number(b.token.decimals) : null,
+ symbol: b?.token?.symbol || null,
+ name: b?.token?.name || null,
+ icon: b?.token?.icon_url || null,
+ holders: b?.token?.holders_count != null ? Number(b.token.holders_count) : null,
+ }))
+ .filter((t) => t.address && t.raw && t.type === 'ERC-20');
+
+ // Unverified launchpad coins are indexed without decimals or a symbol.
+ // Ask the contracts directly (one multicall) instead of guessing 18,
+ // which would print a balance off by orders of magnitude.
+ const unknown = held.filter((t) => t.decimals == null || !t.symbol).map((t) => t.address);
+ const [meta, dex] = await Promise.all([
+ erc20Metadata(unknown).catch(() => ({})),
+ dexSnapshot(held.map((t) => t.address)).catch(() => ({})),
+ ]);
+ const stockByAddress = new Map(
+ stockRegistry().tokens.map((t) => [t.address.toLowerCase(), t]),
+ );
+ const nav = held.some((t) => stockByAddress.has(t.address))
+ ? await chainlinkSnapshot().catch(() => ({}))
+ : {};
+
+ const positions = held.map((t) => {
+ const fallback = meta[t.address] || {};
+ const decimals = t.decimals ?? fallback.decimals ?? null;
+ const stock = stockByAddress.get(t.address) || null;
+ const feed = stock ? nav[t.address] || null : null;
+ const pair = dex[t.address] || null;
+
+ // ERC-8056: a Stock Token's true position is raw × uiMultiplier / 1e18,
+ // and its Chainlink NAV is already multiplier-adjusted, so the
+ // multiplier is applied to the balance exactly once and never to the
+ // price.
+ const rawUnits = decimals != null ? toUnits(t.raw, decimals) : null;
+ const multiplier = feed?.uiMultiplier ? Number(feed.uiMultiplier) / 1e18 : 1;
+ const amount = rawUnits != null ? rawUnits * (stock ? multiplier : 1) : null;
+
+ const navPriceUsd = feed?.priceUsd ?? null;
+ const dexPriceUsd = pair?.priceUsd != null ? Number(pair.priceUsd) : null;
+ const priceUsd = navPriceUsd ?? dexPriceUsd;
+ return {
+ address: t.address,
+ symbol: t.symbol || fallback.symbol || pair?.baseToken?.symbol || null,
+ name: t.name || fallback.name || pair?.baseToken?.name || null,
+ icon: t.icon,
+ decimals,
+ rawBalance: String(t.raw),
+ amount,
+ kind: stock ? 'stock' : 'coin',
+ priceUsd,
+ priceSource: navPriceUsd != null ? 'chainlink-nav' : dexPriceUsd != null ? 'dex' : null,
+ navPriceUsd,
+ dexPriceUsd,
+ change24hPct: pair?.priceChange?.h24 ?? null,
+ liquidityUsd: pair?.liquidity?.usd ?? null,
+ valueUsd: amount != null && priceUsd != null ? amount * priceUsd : null,
+ pairUrl: pair?.url || null,
+ holders: t.holders,
+ };
+ });
+
+ const nativeEth = toUnits(nativeWei, 18);
+ const book = rollupBook(
+ nativeEth != null && ethPriceUsd != null ? nativeEth * ethPriceUsd : null,
+ positions,
+ );
+ const intraday = balanceSeries(coinHistory, { ethPriceUsd });
+ const daily = balanceSeries(dayHistory, { ethPriceUsd });
+ const series = mergeBalanceHistory(daily, intraday);
+ const activity = mergeActivity(txs, transfers, address, { limit: 40 });
+
+ // A dusted wallet can hold hundreds of airdropped tokens (218 on one live
+ // address during development, a 112KB response). The book totals count
+ // every one of them; the returned ladder is capped at the deepest 100 by
+ // value, and `positionsTruncated` says so rather than letting a client
+ // believe it has the whole list.
+ const POSITION_CAP = 100;
+ const positionsOut = book.positions.slice(0, POSITION_CAP);
+
+ res.setHeader('cache-control', CACHE_CONTROL);
+ return {
+ address,
+ native: {
+ symbol: 'ETH',
+ balance: nativeEth,
+ balanceWei: nativeWei,
+ valueUsd: nativeEth != null && ethPriceUsd != null ? nativeEth * ethPriceUsd : null,
+ },
+ book: {
+ valueUsd: book.bookValueUsd,
+ nativeUsd: book.nativeUsd,
+ tokensUsd: book.tokensUsd,
+ nativeSharePct: book.nativeSharePct,
+ positionCount: book.positionCount,
+ pricedCount: book.pricedCount,
+ },
+ positions: positionsOut,
+ positionsTruncated: book.positionCount > positionsOut.length,
+ history: {
+ series,
+ intraday,
+ daily,
+ change: seriesChange(series),
+ sessionChange: seriesChange(intraday),
+ // The chain has no historical ETH price feed, so USD points on the
+ // series are the native balance marked at one current price. Said
+ // out loud here so the client can label the axis honestly.
+ usdBasis: ethPriceUsd != null ? { ethPriceUsd, mode: 'current-price' } : null,
+ },
+ activity,
+ counterparties: counterpartyFlow(activity),
+ ethPriceUsd,
+ source: 'chain rpc + blockscout + chainlink (on-chain) + dexscreener',
+ asOf: asOf(),
+ };
+ },
+});
diff --git a/data/changelog.json b/data/changelog.json
index b5fcb7c5c..1cf7b0b2b 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-09-07",
+ "title": "Hood Desk: a live onchain trading desk for any Robinhood Chain wallet",
+ "summary": "Paste a Robinhood Chain address (or connect a wallet) at three.ws/markets/robinhood/desk and the whole book loads: total value in USD, every token you hold priced against its Chainlink NAV feed or its deepest Uniswap pool, a native balance curve rebuilt from the chain's own history, and a live tape of your swaps, transfers and mints that folds each trade into one readable line instead of three. The centrepiece is the NAV premium ridge: the spread between what every tokenized stock is worth and what it actually trades for on the DEX, redrawn once per liquidity floor, so a dislocation that survives to the back rows is one you could really size into. Under it, the widest tradeable gaps, ranked. Reading any wallet is free, keyless and signature-free, so a desk link is a view anyone can open.",
+ "tags": ["feature"],
+ "link": "/markets/robinhood/desk"
+ },
{
"date": "2026-09-07",
"title": "Awesome 3D Agents: a curated list of everything you need to give an AI a body",
diff --git a/data/pages.json b/data/pages.json
index 2e0ea9350..75b181398 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -2345,6 +2345,14 @@
"changefreq": "hourly",
"added": "2026-07-12"
},
+ {
+ "path": "/markets/robinhood/desk",
+ "title": "Hood Desk",
+ "description": "A live onchain trading desk for any Robinhood Chain (4663) wallet: book value, native balance history rebuilt from the indexer, an activity tape of swaps and transfers, positions priced against Chainlink NAV and the deepest Uniswap pool, the NAV premium ridge layered by pool depth, counterparty flow, and memecoin movers.",
+ "priority": 0.7,
+ "changefreq": "hourly",
+ "added": "2026-09-07"
+ },
{
"path": "/markets/news",
"title": "Crypto News",
diff --git a/docs/robinhood-chain-markets.md b/docs/robinhood-chain-markets.md
index 13f66b75a..35a782825 100644
--- a/docs/robinhood-chain-markets.md
+++ b/docs/robinhood-chain-markets.md
@@ -42,6 +42,44 @@ buy path is cleanly ready to enable once an operator affirms eligibility (swap
`mountStockEligibilityGate` for `mountBuyPanel` in `src/robinhood-stock.js` — no other wiring
changes).
+## The Hood Desk
+
+**`/markets/robinhood/desk`** is the wallet-first view of the same chain: paste any Robinhood Chain
+address (or connect an injected wallet, or link to `?address=0x…`) and the desk loads that wallet's
+whole book. Nothing is signed to read it, no key is needed, and any address can be inspected, so a
+link to the desk is a shareable, reproducible view of a wallet.
+
+What it shows:
+
+- **Desk vitals** - book value in USD (native ETH plus every priced ERC-20), the native balance and
+ its change over the window, position count, and a chain gate tile with block height, gas ladder
+ and block time.
+- **Balance history** - the wallet's real native balance curve. The public sequencer RPC is not an
+ archive node (`eth_getBalance` at a past block answers `metadata is not found`), so the curve is
+ rebuilt from Blockscout's two balance feeds: daily closes for the older shape, per-transaction
+ points for the live edge, stitched into one series. USD points are the native balance marked at
+ the current ETH price, and the panel says so rather than implying a marked-to-time curve.
+- **Activity tape** - transactions folded together with the token transfers they emitted, so a swap
+ prints once with its legs instead of three times. Classified into swap / send / receive / mint /
+ burn / approve / claim / deploy, newest first, refreshed every 20s.
+- **NAV premium ridge** - the distribution of Stock Token DEX premium against the Chainlink NAV,
+ redrawn once per liquidity floor. Each layer back is a deeper pool floor, so a spread that
+ survives to the back rows is one you could actually size into. The shaded strip is the "at NAV"
+ band (within 0.5%); the table under it ranks the widest dislocation that still has a tradeable
+ pool behind it.
+- **Position ladder** - every ERC-20 the wallet holds, priced from the Chainlink NAV when it is a
+ Stock Token (ERC-8056 multiplier applied to the balance, never to the price) and from the deepest
+ Uniswap pool otherwise. A token the desk cannot price is shown as `unpriced` and is never counted
+ into the book at zero. Tokens the indexer has no metadata for get their decimals and symbol read
+ from the contract in one multicall, because a balance divided by a guessed `1e18` is a wrong
+ number on the screen.
+- **Counterparty flow** - who this wallet actually crosses with (routers, pools, launchpads,
+ people), ranked by legs.
+- **Movers** - the Robinhood Chain meme category by absolute 24h move, with a 7-day sparkline.
+
+Each position and each row on the arb board opens a trade ticket: the same Uniswap v3 quote-and-swap
+panel the coin pages use for memecoins, and the eligibility gate (never a swap) for Stock Tokens.
+
## API — `/api/v1/robinhood/*`
Free, keyless, real data only:
@@ -54,6 +92,8 @@ Free, keyless, real data only:
| `GET /api/v1/robinhood/coins?category=meme` | Memecoin screener (`category`: `meme` \| `stocks-ecosystem` \| `ecosystem`; `sort`: `market_cap` \| `volume` \| `gainers` \| `losers`) |
| `GET /api/v1/robinhood/coins-detail?address=0x…` | One coin: pools, market stats, holders, transfers, links |
| `GET /api/v1/robinhood/launches` | Recent launches from NOXA + The Odyssey, newest first |
+| `GET /api/v1/robinhood/desk` | The desk's market side in one read: chain vitals, the premium ridge (bins, liquidity layers, percentiles), the widest tradeable dislocations, memecoin movers, recent launches |
+| `GET /api/v1/robinhood/wallet?address=0x…` | The desk's wallet side in one read: native balance, priced ERC-20 positions, book totals, balance history (daily + per-transaction, merged), the activity tape and counterparty flow |
Paid via x402 ($0.002 USDC, Base or Solana):
@@ -77,7 +117,12 @@ math; Chainlink feed prices are already multiplier-adjusted, so they're never re
(`latestRoundData` + `uiMultiplier` + `totalSupply`), cached 20s. Never 95 separate RPC calls.
- **DEX price / liquidity / volume** — [DexScreener](https://dexscreener.com) (`chainId: "robinhood"`),
batched 30 addresses per call for the board.
-- **Holders, transfers, token stats, chain stats** — [Blockscout](https://robinhoodchain.blockscout.com) Pro API.
+- **Holders, transfers, token stats, chain stats, wallet balances and balance history**:
+ [Blockscout](https://robinhoodchain.blockscout.com) Pro API. Two operational notes, both learned
+ the hard way: it sits behind Cloudflare bot protection that answers any non-browser User-Agent
+ with a 403 interstitial (so `api/_lib/robinhood.js` attaches a browser UA for that host only), and
+ its address endpoints intermittently answer a bare 500 under load (so the shared fetch retries
+ twice inside the cache callback, and only a persistent outage is ever cached).
- **Chain TVL** — [DefiLlama](https://defillama.com/chain/robinhood-chain).
- **Memecoin screener** — CoinGecko categories `robinhood-chain-meme`, `robinhood-chain-stocks-ecosystem`, `robinhood-ecosystem`.
- **Recent launches** — decoded on-chain logs from the NOXA and Odyssey launchpad factories
diff --git a/pages/hood-desk.html b/pages/hood-desk.html
new file mode 100644
index 000000000..c6079277a
--- /dev/null
+++ b/pages/hood-desk.html
@@ -0,0 +1,157 @@
+<!doctype html>
+<html lang="en" class="cv-page" data-shell>
+ <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" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Hood Desk · live onchain trading desk for Robinhood Chain · three.ws</title>
+ <meta
+ name="description"
+ content="A live trading desk for any Robinhood Chain (4663) wallet: book value, native balance history, an onchain activity tape, positions priced against Chainlink NAV and Uniswap, the NAV premium ridge, counterparty flow, and memecoin movers. Real onchain data, no API key, no signature."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/markets/robinhood/desk" />
+ <meta property="og:title" content="Hood Desk · live onchain trading desk for Robinhood Chain" />
+ <meta
+ property="og:description"
+ content="Paste any Robinhood Chain address and get its whole book: balance history, activity tape, priced positions, NAV premium ridge and counterparty flow."
+ />
+ <meta
+ property="og:image"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Hood+Desk&amp;d=A+live+onchain+trading+desk+for+Robinhood+Chain+%284663%29%3A+book+value%2C+balance+history%2C+activity+tape%2C+priced+positions+and+the+NAV+premium+ridge&amp;p=%2Fmarkets%2Frobinhood%2Fdesk"
+ />
+ <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="Hood Desk · three.ws" />
+ <meta
+ name="twitter:description"
+ content="A live onchain trading desk for Robinhood Chain: book, tape, positions, NAV premium ridge."
+ />
+ <meta
+ name="twitter:image"
+ content="https://three.ws/api/page-og?s=crypto&amp;t=Hood+Desk&amp;d=A+live+onchain+trading+desk+for+Robinhood+Chain+%284663%29%3A+book+value%2C+balance+history%2C+activity+tape%2C+priced+positions+and+the+NAV+premium+ridge&amp;p=%2Fmarkets%2Frobinhood%2Fdesk"
+ />
+ <meta name="theme-color" content="#09090b" />
+ <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="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/coin-pages.css" />
+ <link rel="stylesheet" href="/src/robinhood.css" />
+ <link rel="stylesheet" href="/src/hood-desk.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="canonical" href="https://three.ws/markets/robinhood/desk" />
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+ <meta property="og:locale" content="en_US" />
+ <meta property="og:image:alt" content="Hood Desk, the live onchain trading desk for Robinhood Chain - three.ws" />
+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebApplication","name":"Hood Desk","applicationCategory":"FinanceApplication","operatingSystem":"Any","description":"A live onchain trading desk for Robinhood Chain (4663): wallet book value, native balance history, activity tape, positions priced against Chainlink NAV and Uniswap, the NAV premium ridge and counterparty flow.","url":"https://three.ws/markets/robinhood/desk","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}]}</script>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="hd-main" id="hd-main">
+ <nav class="cv-crumbs" aria-label="Breadcrumb">
+ <a href="/markets">Markets</a>
+ <span class="sep" aria-hidden="true">/</span>
+ <a href="/markets/robinhood">Robinhood Chain</a>
+ <span class="sep" aria-hidden="true">/</span>
+ <span class="here">Desk</span>
+ </nav>
+
+ <section class="hd-bar" aria-label="Desk status">
+ <h1 class="hd-brand">
+ <span class="hd-brand-mark" aria-hidden="true">◆</span>
+ HOOD DESK
+ <span class="hd-brand-sub" id="hd-brand-sub">/ no wallet</span>
+ </h1>
+ <div class="hd-bar-spacer"></div>
+ <form class="hd-wallet-form" id="hd-wallet-form">
+ <label class="cv-sr-only" for="hd-address">Robinhood Chain wallet address</label>
+ <input
+ class="hd-input"
+ id="hd-address"
+ name="address"
+ type="text"
+ spellcheck="false"
+ autocomplete="off"
+ placeholder="0x… paste any wallet to load its book"
+ aria-describedby="hd-address-help"
+ />
+ <button class="hd-btn hd-btn-accent" type="submit">Load book</button>
+ <button class="hd-btn hd-btn-ghost" type="button" id="hd-connect">Connect wallet</button>
+ </form>
+ <span class="hd-live" id="hd-live" data-state="stale" role="status">
+ <span class="hd-live-dot" aria-hidden="true"></span>
+ <span id="hd-live-text">booting</span>
+ </span>
+ <span class="hd-clock hd-mono" id="hd-clock" aria-label="Session clock">00:00</span>
+ </section>
+ <p class="cv-sr-only" id="hd-address-help">
+ Read-only. Any Robinhood Chain address can be loaded; nothing is signed and no key is
+ needed.
+ </p>
+
+ <div id="hd-alert" hidden></div>
+
+ <section class="hd-stats" id="hd-stats" aria-label="Desk vitals"></section>
+
+ <div class="hd-grid hd-grid-2">
+ <section class="hd-card" id="hd-balance" aria-label="Balance history"></section>
+ <section class="hd-card" id="hd-tape-card" aria-label="Activity tape"></section>
+ </div>
+
+ <section class="hd-card" id="hd-ridge" aria-label="NAV premium ridge"></section>
+
+ <div class="hd-grid hd-grid-2">
+ <section class="hd-card" id="hd-book" aria-label="Positions"></section>
+ <section class="hd-card" id="hd-flow" aria-label="Counterparty flow"></section>
+ </div>
+
+ <section class="hd-card" id="hd-movers" aria-label="Memecoin movers"></section>
+
+ <p class="hd-note" id="hd-updated">
+ Every number on this desk is read live from Robinhood Chain (4663): balances and history
+ from the chain RPC and the Blockscout indexer, Stock Token NAV from the tokens' Chainlink
+ feeds on-chain, coin prices from the deepest Uniswap pool. Stock Tokens are tokenized debt
+ securities issued by Robinhood Assets (Jersey) Ltd and may not be offered, sold, or
+ delivered to US persons; the desk displays them and never routes an order into one.
+ Nothing here is investment advice.
+ </p>
+ </main>
+
+ <dialog class="hd-drawer" id="hd-trade-dialog" aria-labelledby="hd-trade-title">
+ <div class="hd-drawer-head">
+ <h2 id="hd-trade-title">Trade ticket</h2>
+ <div class="hd-bar-spacer"></div>
+ <button class="hd-btn hd-btn-sm hd-btn-ghost" type="button" id="hd-trade-close">Close</button>
+ </div>
+ <div class="hd-drawer-body" id="hd-trade-body"></div>
+ </dialog>
+
+ <script type="module" src="/src/hood-desk.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/i18n.js"></script>
+ </body>
+</html>
diff --git a/pages/markets-robinhood.html b/pages/markets-robinhood.html
index fcf3862ff..32f8abe0a 100644
--- a/pages/markets-robinhood.html
+++ b/pages/markets-robinhood.html
@@ -83,6 +83,11 @@
launches, and chain stats — real on-chain and DeFiLlama data.
</p>
+ <p class="rh-desk-cta">
+ <a class="rh-bridge-link" href="/markets/robinhood/desk">Open the Hood Desk &rarr;</a>
+ <span>Load any wallet on 4663: book value, balance history, the activity tape, priced positions and the NAV premium ridge.</span>
+ </p>
+
<div class="rh-tabs" role="tablist" aria-label="Robinhood Chain views">
<button type="button" class="rh-tab is-active" data-tab="stocks" role="tab" aria-selected="true" id="rh-tab-stocks" data-i18n="markets_robinhood.stocks">Stocks</button>
<button type="button" class="rh-tab" data-tab="coins" role="tab" aria-selected="false" id="rh-tab-coins" data-i18n="markets_robinhood.coins">Coins</button>
diff --git a/src/hood-desk.css b/src/hood-desk.css
new file mode 100644
index 000000000..b3618296b
--- /dev/null
+++ b/src/hood-desk.css
@@ -0,0 +1,612 @@
+/*
+ * Hood Desk (/markets/robinhood/desk) - the live onchain trading desk for
+ * Robinhood Chain (4663).
+ *
+ * Built on the shared coin-pages.css token system, plus one desk-local accent
+ * (Robinhood green) and a terminal type scale: uppercase micro-labels, mono
+ * numerals, hairline rules. Every panel here is a real data surface, so the
+ * chrome stays quiet and the numbers carry the weight.
+ */
+
+:root {
+ --hd-accent: #00a63e;
+ /* Fills and strokes use --hd-accent; anything that renders TEXT uses
+ --hd-accent-text, which clears 4.5:1 on white (the brand green does not,
+ at 3.2:1). The hover fill stays light enough to keep the near-black
+ button label above 4.5:1 against it. */
+ --hd-accent-hover: #00932f;
+ --hd-accent-text: #007a2e;
+ --hd-accent-soft: rgba(0, 200, 5, 0.1);
+ /* The 10px kind chips sit on a tinted ground, where the shared red text
+ token lands at 4.22:1. These two are the same hues, one step darker. */
+ --hd-chip-red: #b3161b;
+ --hd-chip-green: #12652f;
+ --hd-grid: rgba(15, 23, 42, 0.06);
+ --hd-ridge-line: rgba(15, 23, 42, 0.5);
+ --hd-ridge-fill: rgba(255, 255, 255, 0.92);
+}
+
+[data-theme='dark'] {
+ --hd-accent: #22e06a;
+ --hd-accent-hover: #4bf58b;
+ --hd-accent-text: #4bf58b;
+ --hd-chip-red: var(--cv-red-text);
+ --hd-chip-green: var(--cv-green-text);
+ --hd-accent-soft: rgba(34, 224, 106, 0.12);
+ --hd-grid: rgba(255, 255, 255, 0.07);
+ --hd-ridge-line: rgba(226, 232, 240, 0.55);
+ --hd-ridge-fill: rgba(9, 9, 11, 0.9);
+}
+
+.hd-main {
+ max-width: 1440px;
+ margin: 0 auto;
+ padding: 0 var(--cv-content-padding) 4rem;
+}
+
+.hd-mono {
+ font-family: var(--cv-font-mono);
+ font-variant-numeric: tabular-nums;
+}
+
+.hd-label {
+ font-family: var(--cv-font-mono);
+ font-size: 0.6875rem;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--cv-text-3);
+}
+
+.hd-up { color: var(--cv-green-text); }
+.hd-down { color: var(--cv-red-text); }
+.hd-dim { color: var(--cv-text-3); }
+
+/* ── Desk bar ───────────────────────────────────────────────────────────── */
+.hd-bar {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ flex-wrap: wrap;
+ padding: 0.875rem 1.125rem;
+ border: 1px solid var(--cv-border);
+ border-radius: var(--cv-radius-xl);
+ background: var(--cv-surface);
+ box-shadow: var(--cv-shadow-card);
+ margin-bottom: 0.875rem;
+}
+
+.hd-brand {
+ display: flex;
+ align-items: baseline;
+ gap: 0.5rem;
+ font-family: var(--cv-font-mono);
+ font-weight: 700;
+ font-size: 1.0625rem;
+ letter-spacing: 0.02em;
+ color: var(--cv-text);
+ margin: 0;
+}
+
+.hd-brand .hd-brand-mark {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 26px;
+ height: 26px;
+ border-radius: 8px;
+ background: var(--hd-accent);
+ color: #04140a;
+ font-size: 0.875rem;
+ transform: translateY(3px);
+}
+
+.hd-brand .hd-brand-sub {
+ color: var(--hd-accent-text);
+ font-weight: 500;
+ font-size: 0.9375rem;
+}
+
+.hd-bar-spacer { flex: 1 1 auto; }
+
+.hd-live {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.375rem 0.75rem;
+ border-radius: 999px;
+ border: 1px solid var(--hd-accent);
+ background: var(--hd-accent-soft);
+ color: var(--hd-accent-text);
+ font-family: var(--cv-font-mono);
+ font-size: 0.6875rem;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ font-weight: 600;
+}
+
+.hd-live-dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--hd-accent);
+ box-shadow: 0 0 0 0 var(--hd-accent-soft);
+ animation: hd-pulse 2.4s ease-out infinite;
+}
+
+.hd-live[data-state='stale'] {
+ border-color: var(--cv-border-hover);
+ background: var(--cv-surface-3);
+ color: var(--cv-text-3);
+}
+
+.hd-live[data-state='stale'] .hd-live-dot { background: var(--cv-text-3); animation: none; }
+
+@keyframes hd-pulse {
+ 0% { box-shadow: 0 0 0 0 var(--hd-accent-soft); }
+ 70% { box-shadow: 0 0 0 7px transparent; }
+ 100% { box-shadow: 0 0 0 0 transparent; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .hd-live-dot { animation: none; }
+}
+
+.hd-clock {
+ font-family: var(--cv-font-mono);
+ font-size: 0.8125rem;
+ color: var(--cv-text-2);
+ letter-spacing: 0.04em;
+}
+
+.hd-wallet-form {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+}
+
+.hd-input {
+ background: var(--cv-surface-2);
+ border: 1px solid var(--cv-border);
+ border-radius: var(--cv-radius-md);
+ color: var(--cv-text);
+ font-family: var(--cv-font-mono);
+ font-size: 0.8125rem;
+ padding: 0.5rem 0.625rem;
+ width: min(360px, 46vw);
+ transition: border-color 0.15s ease;
+}
+
+.hd-input::placeholder { color: var(--cv-text-3); }
+.hd-input:hover { border-color: var(--cv-border-hover); }
+.hd-input:focus-visible { outline: 2px solid var(--hd-accent); outline-offset: 1px; border-color: transparent; }
+
+.hd-btn {
+ appearance: none;
+ border: 1px solid var(--cv-border);
+ background: var(--cv-surface-2);
+ color: var(--cv-text);
+ border-radius: var(--cv-radius-md);
+ font: inherit;
+ font-size: 0.8125rem;
+ font-weight: 600;
+ padding: 0.5rem 0.875rem;
+ cursor: pointer;
+ transition: background 0.15s ease, border-color 0.15s ease, transform 0.1s ease, color 0.15s ease;
+ white-space: nowrap;
+}
+
+.hd-btn:hover { border-color: var(--cv-border-hover); background: var(--cv-surface-3); }
+.hd-btn:active { transform: translateY(1px); }
+.hd-btn:focus-visible { outline: 2px solid var(--hd-accent); outline-offset: 2px; }
+.hd-btn[disabled] { opacity: 0.55; cursor: not-allowed; }
+
+.hd-btn-accent {
+ background: var(--hd-accent);
+ border-color: var(--hd-accent);
+ color: #04140a;
+}
+
+.hd-btn-accent:hover { background: var(--hd-accent-hover); border-color: var(--hd-accent-hover); color: #04140a; }
+
+.hd-btn-ghost { background: transparent; }
+
+.hd-btn-sm { padding: 0.3125rem 0.625rem; font-size: 0.75rem; }
+
+.hd-addr-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.375rem 0.625rem;
+ border-radius: 999px;
+ border: 1px solid var(--cv-border);
+ background: var(--cv-surface-2);
+ font-family: var(--cv-font-mono);
+ font-size: 0.75rem;
+ color: var(--cv-text);
+}
+
+/* ── Stat strip ─────────────────────────────────────────────────────────── */
+.hd-stats {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
+ gap: 1px;
+ background: var(--cv-border);
+ border: 1px solid var(--cv-border);
+ border-radius: var(--cv-radius-xl);
+ overflow: hidden;
+ margin-bottom: 0.875rem;
+ box-shadow: var(--cv-shadow-card);
+}
+
+.hd-stat {
+ background: var(--cv-surface);
+ padding: 1rem 1.125rem 1.125rem;
+ min-height: 116px;
+ display: flex;
+ flex-direction: column;
+ gap: 0.375rem;
+}
+
+.hd-stat-value {
+ font-family: var(--cv-font-mono);
+ font-size: clamp(1.375rem, 2.4vw, 1.875rem);
+ font-weight: 600;
+ letter-spacing: -0.02em;
+ line-height: 1.1;
+ color: var(--cv-text);
+ font-variant-numeric: tabular-nums;
+}
+
+.hd-stat-value.hd-accent { color: var(--hd-accent-text); }
+.hd-stat-foot { font-size: 0.75rem; color: var(--cv-text-3); font-family: var(--cv-font-mono); }
+
+.hd-gas-ladder { display: flex; gap: 3px; margin-top: 0.125rem; }
+
+.hd-gas-seg {
+ height: 8px;
+ flex: 1 1 0;
+ border-radius: 2px;
+ background: var(--cv-surface-3);
+}
+
+.hd-gas-seg.on { background: var(--hd-accent); }
+
+/* ── Cards + grid ───────────────────────────────────────────────────────── */
+.hd-grid {
+ display: grid;
+ gap: 0.875rem;
+ margin-bottom: 0.875rem;
+}
+
+.hd-grid-2 { grid-template-columns: minmax(0, 1.12fr) minmax(0, 0.88fr); }
+.hd-grid-2-even { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+
+@media (max-width: 1040px) {
+ .hd-grid-2,
+ .hd-grid-2-even { grid-template-columns: minmax(0, 1fr); }
+}
+
+.hd-card {
+ border: 1px solid var(--cv-border);
+ border-radius: var(--cv-radius-xl);
+ background: var(--cv-surface);
+ box-shadow: var(--cv-shadow-card);
+ padding: 1rem 1.125rem 1.125rem;
+ min-width: 0;
+}
+
+.hd-card-head {
+ display: flex;
+ align-items: baseline;
+ gap: 0.625rem;
+ flex-wrap: wrap;
+ margin-bottom: 0.875rem;
+}
+
+.hd-card-title {
+ margin: 0;
+ font-size: 1rem;
+ font-weight: 650;
+ letter-spacing: -0.01em;
+ color: var(--cv-text);
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+.hd-card-title::before {
+ content: '';
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--hd-accent);
+ flex: none;
+}
+
+.hd-card-head .hd-card-meta { margin-left: auto; }
+
+.hd-seg {
+ display: inline-flex;
+ border: 1px solid var(--cv-border);
+ border-radius: 999px;
+ overflow: hidden;
+ background: var(--cv-surface-2);
+}
+
+.hd-seg button {
+ appearance: none;
+ border: 0;
+ background: transparent;
+ color: var(--cv-text-3);
+ font-family: var(--cv-font-mono);
+ font-size: 0.6875rem;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ padding: 0.3125rem 0.625rem;
+ cursor: pointer;
+ transition: background 0.15s ease, color 0.15s ease;
+}
+
+.hd-seg button:hover { color: var(--cv-text); }
+.hd-seg button[aria-pressed='true'] { background: var(--hd-accent); color: #04140a; font-weight: 600; }
+.hd-seg button:focus-visible { outline: 2px solid var(--hd-accent); outline-offset: -2px; }
+
+/* ── Charts ─────────────────────────────────────────────────────────────── */
+.hd-chart-wrap { position: relative; }
+.hd-chart { display: block; width: 100%; height: auto; touch-action: pan-y; }
+.hd-chart-grid line { stroke: var(--hd-grid); stroke-width: 1; }
+.hd-chart-axis { fill: var(--cv-text-3); font-family: var(--cv-font-mono); font-size: 10px; }
+
+.hd-tip {
+ position: absolute;
+ pointer-events: none;
+ z-index: 5;
+ background: var(--cv-surface);
+ border: 1px solid var(--cv-border-hover);
+ border-radius: var(--cv-radius-md);
+ box-shadow: var(--cv-shadow-dropdown);
+ padding: 0.5rem 0.625rem;
+ font-family: var(--cv-font-mono);
+ font-size: 0.75rem;
+ color: var(--cv-text);
+ white-space: nowrap;
+ transform: translate(-50%, -115%);
+ transition: opacity 0.1s ease;
+}
+
+.hd-tip[hidden] { display: none; }
+.hd-tip b { color: var(--hd-accent-text); font-weight: 600; }
+.hd-tip .hd-tip-sub { color: var(--cv-text-3); display: block; margin-top: 2px; }
+
+/* ── Activity tape ──────────────────────────────────────────────────────── */
+.hd-tape { max-height: 320px; overflow-y: auto; margin: -0.25rem -0.25rem 0; padding: 0 0.25rem; list-style: none; }
+.hd-tape-row {
+ display: grid;
+ grid-template-columns: 58px 74px minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 0.625rem;
+ padding: 0.4375rem 0.25rem;
+ border-bottom: 1px solid var(--cv-border);
+ font-family: var(--cv-font-mono);
+ font-size: 0.75rem;
+ color: var(--cv-text-2);
+ text-decoration: none;
+ transition: background 0.12s ease;
+}
+
+.hd-tape li:last-child .hd-tape-row { border-bottom: 0; }
+.hd-tape-row:hover { background: var(--cv-surface-2); }
+.hd-tape-row:focus-visible { outline: 2px solid var(--hd-accent); outline-offset: -2px; border-radius: var(--cv-radius-sm); }
+.hd-tape-row.is-new { animation: hd-flash 1.4s ease-out; }
+
+@keyframes hd-flash {
+ from { background: var(--hd-accent-soft); }
+ to { background: transparent; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .hd-tape-row.is-new { animation: none; }
+}
+
+.hd-kind {
+ text-transform: uppercase;
+ font-size: 0.625rem;
+ letter-spacing: 0.06em;
+ font-weight: 600;
+ padding: 0.125rem 0.375rem;
+ border-radius: var(--cv-radius-sm);
+ text-align: center;
+ background: var(--cv-surface-3);
+ color: var(--cv-text-2);
+}
+
+.hd-kind.swap { background: var(--hd-accent-soft); color: var(--hd-accent-text); }
+.hd-kind.receive, .hd-kind.mint { background: var(--cv-green-soft); color: var(--hd-chip-green); }
+.hd-kind.send, .hd-kind.burn { background: var(--cv-red-soft); color: var(--hd-chip-red); }
+
+.hd-tape-detail { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--cv-text); }
+.hd-tape-right { text-align: right; white-space: nowrap; }
+
+/* ── Ridge ──────────────────────────────────────────────────────────────── */
+.hd-ridge-layout { display: grid; grid-template-columns: 212px minmax(0, 1fr); gap: 1.25rem; }
+
+@media (max-width: 860px) {
+ .hd-ridge-layout { grid-template-columns: minmax(0, 1fr); }
+}
+
+.hd-metric-rail { display: flex; flex-direction: column; gap: 0.75rem; border-right: 1px solid var(--cv-border); padding-right: 1.25rem; }
+
+@media (max-width: 860px) {
+ .hd-metric-rail { border-right: 0; padding-right: 0; border-bottom: 1px solid var(--cv-border); padding-bottom: 1rem; }
+}
+
+.hd-metric { display: flex; align-items: baseline; justify-content: space-between; gap: 0.75rem; }
+.hd-metric .hd-label { min-width: 0; }
+.hd-metric-value { font-family: var(--cv-font-mono); font-size: 0.875rem; font-weight: 600; color: var(--cv-text); font-variant-numeric: tabular-nums; white-space: nowrap; }
+
+.hd-ridge-scroll { overflow-x: auto; -webkit-overflow-scrolling: touch; }
+.hd-ridge-svg { display: block; width: 100%; height: auto; }
+
+/* Below ~700px the ridge's own aspect ratio would squash it to a 140px strip
+ where no layer is readable. Give it a floor width and let the container
+ scroll instead, the same treatment every wide table on the site gets. */
+@media (max-width: 700px) {
+ .hd-ridge-svg { min-width: 620px; }
+}
+.hd-ridge-layer { fill: var(--hd-ridge-fill); stroke: var(--hd-ridge-line); stroke-width: 1; stroke-linejoin: round; }
+.hd-ridge-layer.hot { stroke: var(--hd-accent); }
+.hd-ridge-zero { stroke: var(--cv-text-3); stroke-dasharray: 3 3; stroke-width: 1; }
+.hd-ridge-band { fill: var(--hd-accent-soft); opacity: 0.55; }
+.hd-ridge-hit { fill: transparent; cursor: crosshair; }
+.hd-ridge-hit:hover { fill: rgba(127, 127, 127, 0.08); }
+
+/* ── Book table ─────────────────────────────────────────────────────────── */
+.hd-table { width: 100%; border-collapse: collapse; font-size: 0.8125rem; }
+.hd-table th {
+ text-align: right;
+ font-family: var(--cv-font-mono);
+ font-size: 0.6875rem;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--cv-text-3);
+ font-weight: 500;
+ padding: 0 0.5rem 0.5rem;
+ border-bottom: 1px solid var(--cv-border);
+ white-space: nowrap;
+}
+
+.hd-table th.left, .hd-table td.left { text-align: left; }
+.hd-table td {
+ text-align: right;
+ padding: 0.5rem;
+ border-bottom: 1px solid var(--cv-border);
+ color: var(--cv-text);
+ font-family: var(--cv-font-mono);
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+}
+
+.hd-table tbody tr:last-child td { border-bottom: 0; }
+.hd-table tbody tr { transition: background 0.12s ease; }
+.hd-table tbody tr:hover { background: var(--cv-surface-2); }
+
+.hd-sym { display: flex; align-items: center; gap: 0.5rem; }
+.hd-sym .sym { font-weight: 650; color: var(--cv-text); }
+.hd-sym .tag {
+ font-size: 0.5625rem;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ padding: 0.0625rem 0.3125rem;
+ border-radius: 3px;
+ border: 1px solid var(--cv-border-hover);
+ color: var(--cv-text-3);
+}
+
+.hd-share { position: relative; height: 4px; border-radius: 2px; background: var(--cv-surface-3); margin-top: 5px; overflow: hidden; }
+.hd-share span { position: absolute; inset: 0 auto 0 0; background: var(--hd-accent); border-radius: 2px; }
+
+/* ── Flow ───────────────────────────────────────────────────────────────── */
+.hd-flow-svg { display: block; width: 100%; height: auto; }
+.hd-flow-arc { fill: none; stroke-width: 1.5; opacity: 0.75; transition: opacity 0.15s ease, stroke-width 0.15s ease; }
+.hd-flow-arc.out { stroke: var(--cv-chart-red); }
+.hd-flow-arc.in { stroke: var(--cv-chart-green); }
+.hd-flow-node { fill: var(--cv-surface); stroke: var(--cv-border-hover); }
+.hd-flow-node.self { fill: var(--hd-accent); stroke: var(--hd-accent); }
+.hd-flow-text { fill: var(--cv-text-2); font-family: var(--cv-font-mono); font-size: 10px; }
+.hd-flow-text.strong { fill: var(--cv-text); }
+.hd-flow-row:hover .hd-flow-arc { opacity: 1; stroke-width: 2.5; }
+
+/* ── Movers rail ────────────────────────────────────────────────────────── */
+.hd-rail {
+ display: grid;
+ grid-auto-flow: column;
+ grid-auto-columns: minmax(178px, 1fr);
+ gap: 0.625rem;
+ overflow-x: auto;
+ padding-bottom: 0.375rem;
+ scrollbar-width: thin;
+}
+
+.hd-mover {
+ border: 1px solid var(--cv-border);
+ border-radius: var(--cv-radius-lg);
+ background: var(--cv-surface-2);
+ padding: 0.75rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.375rem;
+ text-decoration: none;
+ color: inherit;
+ transition: border-color 0.15s ease, transform 0.15s ease, box-shadow 0.15s ease;
+}
+
+.hd-mover:hover { border-color: var(--hd-accent); transform: translateY(-2px); box-shadow: var(--cv-shadow-card-hover); }
+.hd-mover:focus-visible { outline: 2px solid var(--hd-accent); outline-offset: 2px; }
+.hd-mover-top { display: flex; align-items: center; gap: 0.5rem; }
+.hd-mover-top img { width: 20px; height: 20px; border-radius: 50%; flex: none; background: var(--cv-surface-3); }
+.hd-mover-sym { font-family: var(--cv-font-mono); font-weight: 650; font-size: 0.8125rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.hd-mover-price { font-family: var(--cv-font-mono); font-size: 0.8125rem; color: var(--cv-text-2); }
+.hd-chg { font-family: var(--cv-font-mono); font-size: 0.75rem; font-weight: 600; margin-left: auto; }
+
+/* ── States ─────────────────────────────────────────────────────────────── */
+.hd-empty {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 0.625rem;
+ padding: 1.5rem 0.25rem;
+ color: var(--cv-text-2);
+ font-size: 0.875rem;
+ line-height: 1.55;
+}
+
+.hd-empty strong { color: var(--cv-text); font-weight: 600; display: block; }
+.hd-empty.center { align-items: center; text-align: center; }
+
+.hd-skel {
+ background: linear-gradient(90deg, var(--cv-surface-3) 25%, var(--cv-surface-2) 50%, var(--cv-surface-3) 75%);
+ background-size: 200% 100%;
+ animation: hd-shimmer 1.4s linear infinite;
+ border-radius: var(--cv-radius-sm);
+}
+
+@keyframes hd-shimmer {
+ from { background-position: 200% 0; }
+ to { background-position: -200% 0; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .hd-skel { animation: none; }
+}
+
+.hd-error {
+ border: 1px solid var(--cv-red);
+ background: var(--cv-red-soft);
+ color: var(--cv-red-text);
+ border-radius: var(--cv-radius-md);
+ padding: 0.75rem 0.875rem;
+ font-size: 0.8125rem;
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ flex-wrap: wrap;
+}
+
+.hd-note { font-size: 0.75rem; color: var(--cv-text-3); line-height: 1.6; margin: 1rem 0 0; }
+
+/* ── Trade drawer ───────────────────────────────────────────────────────── */
+.hd-drawer {
+ border: 1px solid var(--cv-border);
+ border-radius: var(--cv-radius-xl);
+ background: var(--cv-surface);
+ color: var(--cv-text);
+ padding: 0;
+ width: min(420px, calc(100vw - 2rem));
+ box-shadow: var(--cv-shadow-dropdown);
+}
+
+.hd-drawer::backdrop { background: rgba(2, 6, 23, 0.55); backdrop-filter: blur(2px); }
+.hd-drawer-head { display: flex; align-items: center; gap: 0.75rem; padding: 0.875rem 1rem; border-bottom: 1px solid var(--cv-border); }
+.hd-drawer-head h2 { margin: 0; font-size: 0.9375rem; }
+.hd-drawer-body { padding: 1rem; }
diff --git a/src/hood-desk.js b/src/hood-desk.js
new file mode 100644
index 000000000..d3122fc24
--- /dev/null
+++ b/src/hood-desk.js
@@ -0,0 +1,1141 @@
+// /markets/robinhood/desk - Hood Desk, the live onchain trading desk for
+// Robinhood Chain (4663).
+//
+// Two real reads drive everything on the page:
+// /api/v1/robinhood/desk market side (chain vitals, the NAV
+// premium ridge, arb board, movers)
+// /api/v1/robinhood/wallet?address=… wallet side (book, balance history,
+// activity tape, positions, flow)
+//
+// No wallet is required to read the desk and none is ever asked to sign: an
+// address can be pasted, connected from an injected wallet, or linked to with
+// ?address=. The trade ticket is the only place a signature appears, and it is
+// the existing memecoin swap panel (src/robinhood-purchase.js) mounted on
+// demand; Stock Tokens get the eligibility gate instead of a swap.
+
+import { formatUsd, formatPrice, formatPercent, escapeHtml as esc } from './shared/coin-format.js';
+import { sparkline } from './shared/market-table.js';
+import { onPageReady } from './shell/page-lifecycle.js';
+
+// U+2014 as an escape: the house style bans the literal glyph in source.
+const DASH = '\u2014';
+const STORAGE_KEY = 'hood_desk_address';
+const DESK_REFRESH_MS = 30_000;
+const WALLET_REFRESH_MS = 20_000;
+const ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
+
+const state = {
+ address: null,
+ desk: null,
+ deskError: null,
+ wallet: null,
+ walletError: null,
+ loadingWallet: false,
+ range: 'all',
+ showAllPositions: false,
+ seen: new Set(),
+ bootBlock: null,
+ bootedAt: Date.now(),
+ lastTick: null,
+};
+
+// ── data ────────────────────────────────────────────────────────────────────
+async function getJson(url, signal) {
+ const res = await fetch(url, { headers: { accept: 'application/json' }, signal });
+ const body = await res.json().catch(() => null);
+ if (!res.ok) {
+ const err = new Error(body?.error_description || body?.error || `request failed (${res.status})`);
+ err.status = res.status;
+ throw err;
+ }
+ return body?.data ?? body;
+}
+
+function shortAddr(a, head = 6, tail = 4) {
+ if (!a) return DASH;
+ return `${a.slice(0, head)}…${a.slice(-tail)}`;
+}
+
+function fmtEth(n, digits = 4) {
+ if (n == null || !Number.isFinite(n)) return DASH;
+ if (n !== 0 && Math.abs(n) < 0.0001) return `${n.toExponential(2)} ETH`;
+ return `${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: digits })} ETH`;
+}
+
+function fmtAmount(n) {
+ if (n == null || !Number.isFinite(n)) return DASH;
+ const abs = Math.abs(n);
+ if (abs >= 1e9) return `${(n / 1e9).toFixed(2)}B`;
+ if (abs >= 1e6) return `${(n / 1e6).toFixed(2)}M`;
+ if (abs >= 1e3) return `${(n / 1e3).toFixed(2)}K`;
+ if (abs >= 1) return n.toLocaleString('en-US', { maximumFractionDigits: 4 });
+ if (abs === 0) return '0';
+ return n.toPrecision(3);
+}
+
+function signClass(n) {
+ if (n == null || !Number.isFinite(n)) return 'hd-dim';
+ return n >= 0 ? 'hd-up' : 'hd-down';
+}
+
+function explorerAddress(a) {
+ return `https://robinhoodchain.blockscout.com/address/${a}`;
+}
+
+function explorerTx(h) {
+ return `https://robinhoodchain.blockscout.com/tx/${h}`;
+}
+
+// ── generic panel states ────────────────────────────────────────────────────
+function skeleton(height = 180) {
+ return `<div class="hd-skel" style="height:${height}px"></div>`;
+}
+
+function emptyState(title, body, actionLabel, actionId) {
+ return `
+ <div class="hd-empty">
+ <strong>${esc(title)}</strong>
+ <span>${body}</span>
+ ${actionId ? `<button class="hd-btn hd-btn-sm" type="button" data-action="${esc(actionId)}">${esc(actionLabel)}</button>` : ''}
+ </div>`;
+}
+
+function errorState(message, retryId) {
+ return `
+ <div class="hd-error" role="alert">
+ <span>${esc(message)}</span>
+ <button class="hd-btn hd-btn-sm" type="button" data-action="${esc(retryId)}">Retry</button>
+ </div>`;
+}
+
+function cardHead(title, meta = '', extra = '') {
+ return `
+ <div class="hd-card-head">
+ <h2 class="hd-card-title">${esc(title)}</h2>
+ <span class="hd-card-meta hd-label">${meta}</span>
+ ${extra}
+ </div>`;
+}
+
+// ── stat strip ──────────────────────────────────────────────────────────────
+function statTile(label, value, foot, { accent = false, extra = '' } = {}) {
+ return `
+ <div class="hd-stat">
+ <span class="hd-label">${esc(label)}</span>
+ <span class="hd-stat-value${accent ? ' hd-accent' : ''}">${value}</span>
+ <span class="hd-stat-foot">${foot}</span>
+ ${extra}
+ </div>`;
+}
+
+function gasLadder(gas) {
+ if (!gas) return '';
+ const lit = [gas.slow, gas.average, gas.fast].filter((g) => Number.isFinite(g)).length;
+ return `<div class="hd-gas-ladder" aria-hidden="true">${Array.from({ length: 3 })
+ .map((_, i) => `<span class="hd-gas-seg${i < lit ? ' on' : ''}"></span>`)
+ .join('')}</div>`;
+}
+
+function renderStats() {
+ const el = document.getElementById('hd-stats');
+ if (!el) return;
+ const chain = state.desk?.chain || null;
+ const w = state.wallet;
+ const tiles = [];
+
+ if (state.address) {
+ const change = w?.history?.change || null;
+ const pct = change?.pct;
+ tiles.push(
+ statTile(
+ 'Book value / USD',
+ w ? esc(formatUsd(w.book?.valueUsd)) : `<span class="hd-dim">${DASH}</span>`,
+ w
+ ? `${esc(formatUsd(w.book?.tokensUsd))} tokens · ${esc(formatUsd(w.book?.nativeUsd))} native`
+ : 'loading the book',
+ { accent: true },
+ ),
+ statTile(
+ 'Native / ETH',
+ w ? esc(fmtEth(w.native?.balance)) : `<span class="hd-dim">${DASH}</span>`,
+ change && Number.isFinite(pct)
+ ? `<span class="${signClass(pct)}">${esc(formatPercent(pct))}</span> over ${esc(spanLabel(change))}`
+ : 'no balance history indexed yet',
+ ),
+ statTile(
+ 'Positions',
+ w ? String(w.book?.positionCount ?? 0) : `<span class="hd-dim">${DASH}</span>`,
+ w
+ ? `${w.book?.pricedCount ?? 0} priced · top ${esc(w.positions?.[0]?.symbol || DASH)}`
+ : 'ERC-20 balances on 4663',
+ ),
+ );
+ } else {
+ tiles.push(
+ statTile('Chain TVL', esc(formatUsd(chain?.tvlUsd)), 'DefiLlama, Robinhood Chain', { accent: true }),
+ statTile(
+ 'ETH / USD',
+ chain?.ethPriceUsd != null ? esc(formatPrice(chain.ethPriceUsd)) : `<span class="hd-dim">${DASH}</span>`,
+ 'gas token, no native chain token',
+ ),
+ statTile(
+ 'NAV spread',
+ state.desk ? esc(formatPercent(state.desk.ridge?.stats?.median)) : `<span class="hd-dim">${DASH}</span>`,
+ state.desk
+ ? `median premium · ${state.desk.ridge?.stats?.priced ?? 0}/${state.desk.stockCount ?? 0} priced`
+ : 'Chainlink NAV vs Uniswap',
+ ),
+ );
+ }
+
+ tiles.push(
+ statTile(
+ 'Chain gate',
+ chain?.blockHeight != null ? `#${chain.blockHeight.toLocaleString('en-US')}` : `<span class="hd-dim">${DASH}</span>`,
+ chain?.gas
+ ? `gas ${esc(String(chain.gas.average ?? DASH))} gwei avg · ${esc(String(chain.averageBlockTimeMs ?? DASH))}ms blocks`
+ : 'block height',
+ { extra: gasLadder(chain?.gas) },
+ ),
+ );
+
+ el.innerHTML = tiles.join('');
+}
+
+function spanLabel(change) {
+ if (!change?.fromT || !change?.toT) return 'the window';
+ const mins = Math.max(1, Math.round((change.toT - change.fromT) / 60000));
+ if (mins < 90) return `${mins}m`;
+ const hours = Math.round(mins / 60);
+ if (hours < 48) return `${hours}h`;
+ return `${Math.round(hours / 24)}d`;
+}
+
+// ── balance history ─────────────────────────────────────────────────────────
+const RANGES = [
+ { id: '1h', label: '1H', ms: 3_600_000 },
+ { id: '24h', label: '24H', ms: 86_400_000 },
+ { id: 'all', label: 'ALL', ms: Infinity },
+];
+
+function seriesInRange(series, rangeId) {
+ const range = RANGES.find((r) => r.id === rangeId) || RANGES[2];
+ if (!Number.isFinite(range.ms)) return series;
+ const cutoff = Date.now() - range.ms;
+ const windowed = series.filter((p) => p.t >= cutoff);
+ // Never render a one-point line: fall back to the full series rather than
+ // showing an empty chart for a wallet whose last move was days ago.
+ return windowed.length >= 2 ? windowed : series;
+}
+
+function areaChart(series, { width = 780, height = 232 } = {}) {
+ const padL = 58;
+ const padR = 18;
+ const padT = 18;
+ const padB = 26;
+ const xs = series.map((p) => p.t);
+ const ys = series.map((p) => p.eth);
+ const minT = Math.min(...xs);
+ const maxT = Math.max(...xs);
+ const maxY = Math.max(...ys);
+ const rawMin = Math.min(...ys);
+ const spread = maxY - rawMin;
+ const minY = Math.max(0, rawMin - (spread || maxY || 1) * 0.25);
+ const topY = maxY + (spread || maxY || 1) * 0.15;
+ const sx = (t) => padL + ((t - minT) / (maxT - minT || 1)) * (width - padL - padR);
+ const sy = (v) => padT + (1 - (v - minY) / (topY - minY || 1)) * (height - padT - padB);
+
+ const line = series.map((p, i) => `${i ? 'L' : 'M'}${sx(p.t).toFixed(1)} ${sy(p.eth).toFixed(1)}`).join(' ');
+ const area = `${line} L${sx(maxT).toFixed(1)} ${height - padB} L${sx(minT).toFixed(1)} ${height - padB} Z`;
+ const gridYs = [minY, (minY + topY) / 2, topY];
+ const last = series[series.length - 1];
+ const rising = last.eth >= series[0].eth;
+ const stroke = rising ? 'var(--cv-chart-green)' : 'var(--cv-chart-red)';
+
+ return `
+ <svg class="hd-chart" viewBox="0 0 ${width} ${height}" role="img" aria-label="Native ETH balance over time">
+ <defs>
+ <linearGradient id="hd-area" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0%" stop-color="${stroke}" stop-opacity="0.22" />
+ <stop offset="100%" stop-color="${stroke}" stop-opacity="0" />
+ </linearGradient>
+ </defs>
+ <g class="hd-chart-grid">
+ ${gridYs.map((v) => `<line x1="${padL}" x2="${width - padR}" y1="${sy(v).toFixed(1)}" y2="${sy(v).toFixed(1)}" />`).join('')}
+ </g>
+ <g class="hd-chart-axis">
+ ${gridYs
+ .map((v) => `<text x="${padL - 8}" y="${(sy(v) + 3).toFixed(1)}" text-anchor="end">${v.toFixed(4)}</text>`)
+ .join('')}
+ <text x="${padL}" y="${height - 8}">${esc(clockLabel(minT))}</text>
+ <text x="${width - padR}" y="${height - 8}" text-anchor="end">${esc(clockLabel(maxT))}</text>
+ </g>
+ <path d="${area}" fill="url(#hd-area)" />
+ <path d="${line}" fill="none" stroke="${stroke}" stroke-width="1.75" stroke-linejoin="round" stroke-linecap="round" />
+ <line class="hd-crosshair" x1="0" x2="0" y1="${padT}" y2="${height - padB}" stroke="var(--cv-text-3)" stroke-dasharray="3 3" stroke-width="1" opacity="0" />
+ <circle class="hd-cursor" r="3.5" fill="${stroke}" opacity="0" />
+ <circle cx="${sx(last.t).toFixed(1)}" cy="${sy(last.eth).toFixed(1)}" r="4" fill="${stroke}" />
+ </svg>`;
+}
+
+function clockLabel(t) {
+ const d = new Date(t);
+ if (Number.isNaN(d.getTime())) return '';
+ const sameDay = Date.now() - t < 86_400_000;
+ return sameDay
+ ? d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false })
+ : d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
+}
+
+function renderBalance() {
+ const el = document.getElementById('hd-balance');
+ if (!el) return;
+ const ranges = `<div class="hd-seg" role="group" aria-label="Balance window">${RANGES.map(
+ (r) =>
+ `<button type="button" data-range="${r.id}" aria-pressed="${state.range === r.id}">${r.label}</button>`,
+ ).join('')}</div>`;
+
+ if (!state.address) {
+ el.innerHTML =
+ cardHead('Balance history', 'native ETH / 4663') +
+ emptyState(
+ 'No wallet loaded',
+ 'Paste any Robinhood Chain address in the bar above, or connect an injected wallet, and the desk reconstructs its native balance curve from the indexer.',
+ 'Focus the address field',
+ 'focus-address',
+ );
+ return;
+ }
+ if (state.walletError) {
+ el.innerHTML = cardHead('Balance history', 'native ETH / 4663') + errorState(state.walletError, 'reload-wallet');
+ return;
+ }
+ if (!state.wallet) {
+ el.innerHTML = cardHead('Balance history', 'native ETH / 4663') + skeleton(232);
+ return;
+ }
+
+ const series = state.wallet.history?.series || [];
+ if (series.length < 2) {
+ el.innerHTML =
+ cardHead('Balance history', 'native ETH / 4663', ranges) +
+ emptyState(
+ 'No balance history yet',
+ `The indexer has ${series.length} balance point for ${esc(shortAddr(state.address))}. A curve appears as soon as this wallet moves ETH on chain 4663.`,
+ );
+ wireBalance(el);
+ return;
+ }
+
+ const windowed = seriesInRange(series, state.range);
+ const change = {
+ startEth: windowed[0].eth,
+ endEth: windowed[windowed.length - 1].eth,
+ };
+ const delta = change.endEth - change.startEth;
+ const pct = change.startEth > 0 ? (delta / change.startEth) * 100 : null;
+ const usd = state.wallet.history?.usdBasis?.ethPriceUsd;
+
+ el.innerHTML = `
+ ${cardHead('Balance history', `${windowed.length} points`, ranges)}
+ <div class="hd-chart-wrap" id="hd-balance-chart">
+ ${areaChart(windowed)}
+ <div class="hd-tip" id="hd-balance-tip" hidden></div>
+ </div>
+ <div class="hd-metric" style="margin-top:0.75rem">
+ <span class="hd-label">Change over window</span>
+ <span class="hd-metric-value ${signClass(delta)}">${esc(fmtEth(delta))}${
+ pct != null ? ` (${esc(formatPercent(pct))})` : ''
+ }</span>
+ </div>
+ <div class="hd-metric">
+ <span class="hd-label">Marked at</span>
+ <span class="hd-metric-value">${usd != null ? `${esc(formatPrice(usd))} / ETH` : DASH}</span>
+ </div>`;
+ wireBalance(el);
+ wireChartHover(el, windowed);
+}
+
+function wireBalance(root) {
+ root.querySelectorAll('[data-range]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ state.range = btn.dataset.range;
+ renderBalance();
+ });
+ });
+}
+
+function wireChartHover(root, series) {
+ const wrap = root.querySelector('#hd-balance-chart');
+ const svg = wrap?.querySelector('svg');
+ const tip = wrap?.querySelector('#hd-balance-tip');
+ if (!wrap || !svg || !tip) return;
+ const cross = svg.querySelector('.hd-crosshair');
+ const cursor = svg.querySelector('.hd-cursor');
+ const padL = 58;
+ const padR = 18;
+ const vbWidth = 780;
+
+ const move = (ev) => {
+ const rect = wrap.getBoundingClientRect();
+ const x = ((ev.clientX - rect.left) / rect.width) * vbWidth;
+ const ratio = Math.min(1, Math.max(0, (x - padL) / (vbWidth - padL - padR)));
+ const minT = series[0].t;
+ const maxT = series[series.length - 1].t;
+ const target = minT + ratio * (maxT - minT);
+ let best = series[0];
+ for (const p of series) if (Math.abs(p.t - target) < Math.abs(best.t - target)) best = p;
+ const px = padL + ((best.t - minT) / (maxT - minT || 1)) * (vbWidth - padL - padR);
+ cross?.setAttribute('x1', px);
+ cross?.setAttribute('x2', px);
+ cross?.setAttribute('opacity', '0.8');
+ const ys = series.map((p) => p.eth);
+ const maxY = Math.max(...ys);
+ const rawMin = Math.min(...ys);
+ const spread = maxY - rawMin;
+ const minY = Math.max(0, rawMin - (spread || maxY || 1) * 0.25);
+ const topY = maxY + (spread || maxY || 1) * 0.15;
+ const py = 18 + (1 - (best.eth - minY) / (topY - minY || 1)) * (232 - 18 - 26);
+ cursor?.setAttribute('cx', px);
+ cursor?.setAttribute('cy', py);
+ cursor?.setAttribute('opacity', '1');
+ tip.hidden = false;
+ tip.style.left = `${(px / vbWidth) * 100}%`;
+ tip.style.top = `${(py / 232) * 100}%`;
+ tip.innerHTML = `<b>${esc(fmtEth(best.eth, 6))}</b>${
+ best.usd != null ? ` ${esc(formatUsd(best.usd))}` : ''
+ }<span class="hd-tip-sub">${esc(new Date(best.t).toLocaleString('en-US'))}${
+ best.block ? ` · block ${best.block.toLocaleString('en-US')}` : ''
+ }</span>`;
+ };
+
+ wrap.addEventListener('pointermove', move);
+ wrap.addEventListener('pointerleave', () => {
+ tip.hidden = true;
+ cross?.setAttribute('opacity', '0');
+ cursor?.setAttribute('opacity', '0');
+ });
+}
+
+// ── activity tape ───────────────────────────────────────────────────────────
+function tapeLine(ev) {
+ const legs = (ev.tokens || []).filter((t) => t.amount != null);
+ if (legs.length) {
+ return legs
+ .map(
+ (t) =>
+ `<span class="${t.direction === 'out' ? 'hd-down' : 'hd-up'}">${t.direction === 'out' ? '-' : '+'}${esc(
+ fmtAmount(t.amount),
+ )}</span> ${esc(t.symbol || shortAddr(t.address, 5, 3))}`,
+ )
+ .join(' <span class="hd-dim">/</span> ');
+ }
+ if (ev.valueEth) return `${esc(fmtEth(ev.valueEth, 5))}`;
+ if (ev.method) return `<span class="hd-dim">${esc(ev.method)}</span>`;
+ return `<span class="hd-dim">contract call</span>`;
+}
+
+function renderTape() {
+ const el = document.getElementById('hd-tape-card');
+ if (!el) return;
+ if (!state.address) {
+ el.innerHTML =
+ cardHead('Activity tape', 'live / 4663') +
+ emptyState(
+ 'The tape is per wallet',
+ 'Load an address to stream its swaps, transfers, mints and approvals as the chain confirms them (about one block every 100ms).',
+ 'Focus the address field',
+ 'focus-address',
+ );
+ return;
+ }
+ if (state.walletError) {
+ el.innerHTML = cardHead('Activity tape', 'live / 4663') + errorState(state.walletError, 'reload-wallet');
+ return;
+ }
+ if (!state.wallet) {
+ el.innerHTML = cardHead('Activity tape', 'live / 4663') + skeleton(280);
+ return;
+ }
+ const events = state.wallet.activity || [];
+ if (!events.length) {
+ el.innerHTML =
+ cardHead('Activity tape', 'live / 4663') +
+ emptyState(
+ 'No activity on this wallet',
+ `Nothing has touched ${esc(shortAddr(state.address))} on Robinhood Chain yet. The tape fills in as soon as it transacts.`,
+ );
+ return;
+ }
+
+ el.innerHTML = `
+ ${cardHead('Activity tape', `${events.length} events`)}
+ <ul class="hd-tape" id="hd-tape" aria-label="Onchain activity, newest first">
+ ${events
+ .map((ev) => {
+ const fresh = ev.hash && !state.seen.has(ev.hash);
+ return `
+ <li>
+ <a class="hd-tape-row${fresh ? ' is-new' : ''}" href="${esc(explorerTx(ev.hash))}" target="_blank" rel="noopener noreferrer">
+ <span class="hd-dim">${esc(clockLabel(Date.parse(ev.timestamp)))}</span>
+ <span class="hd-kind ${esc(ev.kind)}">${esc(ev.kind)}</span>
+ <span class="hd-tape-detail">${tapeLine(ev)}</span>
+ <span class="hd-tape-right hd-dim">${esc(shortAddr(ev.counterparty, 5, 3))}</span>
+ </a>
+ </li>`;
+ })
+ .join('')}
+ </ul>`;
+ for (const ev of events) if (ev.hash) state.seen.add(ev.hash);
+}
+
+// ── NAV premium ridge ───────────────────────────────────────────────────────
+function ridgeSvg(ridge) {
+ const width = 900;
+ const height = 340;
+ const padL = 26;
+ const padR = 26;
+ const padT = 26;
+ const padB = 40;
+ const bins = ridge.bins || [];
+ const layers = ridge.layers || [];
+ if (!bins.length || !layers.length) return '';
+
+ const skew = 5;
+ const plotW = width - padL - padR - skew * (layers.length - 1);
+ const rowH = (height - padT - padB) / Math.max(1, layers.length + 4);
+ const amp = rowH * 5.5;
+ const maxBin = Math.max(1, ...layers.flatMap((l) => l.density));
+ const bx = (i) => padL + (i / (bins.length - 1)) * plotW;
+ const span = ridge.stats?.spanPct ?? 4;
+ const pctToX = (pct) => padL + ((pct + span) / (span * 2)) * plotW;
+
+ const paths = [];
+ for (let i = layers.length - 1; i >= 0; i--) {
+ const layer = layers[i];
+ const xOff = i * skew;
+ const yBase = padT + (layers.length - 1 - i) * rowH + amp;
+ const pts = layer.density.map((d, b) => [bx(b) + xOff, yBase - (d / maxBin) * amp]);
+ let d = `M${pts[0][0].toFixed(1)} ${yBase.toFixed(1)} L${pts[0][0].toFixed(1)} ${pts[0][1].toFixed(1)}`;
+ for (let p = 1; p < pts.length; p++) {
+ const [x0, y0] = pts[p - 1];
+ const [x1, y1] = pts[p];
+ const mx = (x0 + x1) / 2;
+ d += ` Q${x0.toFixed(1)} ${y0.toFixed(1)} ${mx.toFixed(1)} ${((y0 + y1) / 2).toFixed(1)}`;
+ }
+ const lastPt = pts[pts.length - 1];
+ d += ` L${lastPt[0].toFixed(1)} ${lastPt[1].toFixed(1)} L${lastPt[0].toFixed(1)} ${yBase.toFixed(1)} Z`;
+ paths.push(
+ `<path class="hd-ridge-layer${i === 0 ? ' hot' : ''}" d="${d}"><title>${
+ layer.minLiquidityUsd > 0
+ ? `${layer.count} tokens with pools deeper than ${formatUsd(layer.minLiquidityUsd)}`
+ : `all ${layer.count} priced tokens`
+ }</title></path>`,
+ );
+ }
+
+ const frontBase = padT + (layers.length - 1) * rowH + amp;
+ const ticks = [-span, -span / 2, 0, span / 2, span].map((t) => Number(t.toFixed(2)));
+ const hits = bins
+ .map((b, i) => {
+ const count = layers[0]?.density?.[i] || 0;
+ if (!count) return '';
+ const x = bx(i) - plotW / bins.length / 2;
+ const symbols = (ridge.symbols?.[i] || []).join(' ');
+ return `<rect class="hd-ridge-hit" x="${x.toFixed(1)}" y="${padT}" width="${(plotW / bins.length).toFixed(
+ 1,
+ )}" height="${(frontBase - padT).toFixed(1)}" data-bin="${i}"><title>${count} token${
+ count === 1 ? '' : 's'
+ } at ${b.from.toFixed(2)}% to ${b.to.toFixed(2)}%${symbols ? `: ${symbols}` : ''}</title></rect>`;
+ })
+ .join('');
+
+ // The shaded strip is the "at NAV" band (within half a percent of the feed
+ // price): everything outside it is a dislocation someone can trade against.
+ const fairFrom = pctToX(-0.5);
+ const fairTo = pctToX(0.5);
+ return `
+ <svg class="hd-ridge-svg" viewBox="0 0 ${width} ${height}" role="img" aria-label="Distribution of Stock Token DEX premium against Chainlink NAV, layered by pool depth">
+ <rect class="hd-ridge-band" x="${fairFrom.toFixed(1)}" y="${padT}" width="${Math.max(2, fairTo - fairFrom).toFixed(1)}" height="${(frontBase - padT).toFixed(1)}" />
+ <line class="hd-ridge-zero" x1="${pctToX(0).toFixed(1)}" x2="${pctToX(0).toFixed(1)}" y1="${(frontBase - amp * 1.15).toFixed(1)}" y2="${frontBase.toFixed(1)}" />
+ ${paths.join('')}
+ ${hits}
+ <g class="hd-chart-axis">
+ ${ticks
+ .map(
+ (t) =>
+ `<text x="${pctToX(t).toFixed(1)}" y="${height - 16}" text-anchor="middle">${t > 0 ? '+' : ''}${t}%</text>`,
+ )
+ .join('')}
+ <text x="${padL}" y="${height - 2}">discount / DEX below NAV</text>
+ <text x="${pctToX(0).toFixed(1)}" y="${height - 2}" text-anchor="middle">at NAV, plus or minus 0.5%</text>
+ <text x="${width - padR}" y="${height - 2}" text-anchor="end">premium / DEX above NAV</text>
+ </g>
+ </svg>`;
+}
+
+function renderRidge() {
+ const el = document.getElementById('hd-ridge');
+ if (!el) return;
+ if (state.deskError) {
+ el.innerHTML = cardHead('NAV premium ridge', 'chainlink vs uniswap') + errorState(state.deskError, 'reload-desk');
+ return;
+ }
+ if (!state.desk) {
+ el.innerHTML = cardHead('NAV premium ridge', 'chainlink vs uniswap') + skeleton(300);
+ return;
+ }
+ const ridge = state.desk.ridge || {};
+ const s = ridge.stats || {};
+ if (!s.priced) {
+ el.innerHTML =
+ cardHead('NAV premium ridge', 'chainlink vs uniswap') +
+ emptyState(
+ 'No Stock Token is priced on both sides right now',
+ 'The ridge needs a Chainlink NAV and a live Uniswap pool for the same token. It fills back in as soon as a pool quotes again.',
+ 'Reload market data',
+ 'reload-desk',
+ );
+ return;
+ }
+ const arb = state.desk.arb || [];
+
+ el.innerHTML = `
+ ${cardHead('NAV premium ridge', 'one layer per liquidity floor')}
+ <div class="hd-ridge-layout">
+ <div class="hd-metric-rail">
+ <div class="hd-metric"><span class="hd-label">Priced both sides</span><span class="hd-metric-value">${s.priced} / ${
+ state.desk.stockCount ?? DASH
+ }</span></div>
+ <div class="hd-metric"><span class="hd-label">Median premium</span><span class="hd-metric-value ${signClass(
+ s.median,
+ )}">${esc(formatPercent(s.median))}</span></div>
+ <div class="hd-metric"><span class="hd-label">P10 / P90</span><span class="hd-metric-value">${esc(
+ formatPercent(s.p10),
+ )} / ${esc(formatPercent(s.p90))}</span></div>
+ <div class="hd-metric"><span class="hd-label">Widest</span><span class="hd-metric-value">${esc(
+ formatPercent(s.min),
+ )} / ${esc(formatPercent(s.max))}</span></div>
+ <p class="hd-note" style="margin-top:0.25rem">
+ Each layer redraws the same distribution over a deeper pool floor, so a spread that
+ survives to the back rows is one you could actually size into.
+ </p>
+ </div>
+ <div class="hd-ridge-scroll">
+ ${ridgeSvg(ridge)}
+ </div>
+ </div>
+ ${
+ arb.length
+ ? `<div class="cv-table-wrap" style="margin-top:1rem"><table class="hd-table">
+ <thead><tr>
+ <th class="left">Widest tradeable dislocation</th><th>NAV</th><th>DEX</th><th>Premium</th><th>Liquidity</th><th></th>
+ </tr></thead>
+ <tbody>${arb
+ .map(
+ (r) => `<tr>
+ <td class="left"><a href="/markets/robinhood/stock/${encodeURIComponent(r.symbol)}" class="hd-sym"><span class="sym">${esc(
+ r.symbol,
+ )}</span><span class="tag">${r.side === 'dex-rich' ? 'dex rich' : 'dex cheap'}</span></a></td>
+ <td>${esc(formatPrice(r.navPriceUsd))}</td>
+ <td>${esc(formatPrice(r.dexPriceUsd))}</td>
+ <td class="${signClass(r.premiumPct)}">${esc(formatPercent(r.premiumPct))}</td>
+ <td>${esc(formatUsd(r.liquidityUsd))}</td>
+ <td><button class="hd-btn hd-btn-sm" type="button" data-action="trade" data-address="${esc(
+ r.address,
+ )}" data-symbol="${esc(r.symbol)}" data-kind="stock">Trade</button></td>
+ </tr>`,
+ )
+ .join('')}</tbody></table></div>`
+ : ''
+ }`;
+}
+
+// ── positions ───────────────────────────────────────────────────────────────
+function renderBook() {
+ const el = document.getElementById('hd-book');
+ if (!el) return;
+ if (!state.address) {
+ el.innerHTML =
+ cardHead('Position ladder', 'priced live') +
+ emptyState(
+ 'No book loaded',
+ 'Positions are priced against the Chainlink NAV feed for Stock Tokens and the deepest Uniswap pool for everything else. Load a wallet to see its ladder.',
+ 'Focus the address field',
+ 'focus-address',
+ );
+ return;
+ }
+ if (state.walletError) {
+ el.innerHTML = cardHead('Position ladder', 'priced live') + errorState(state.walletError, 'reload-wallet');
+ return;
+ }
+ if (!state.wallet) {
+ el.innerHTML = cardHead('Position ladder', 'priced live') + skeleton(220);
+ return;
+ }
+ const rows = state.wallet.positions || [];
+ if (!rows.length) {
+ el.innerHTML =
+ cardHead('Position ladder', 'priced live') +
+ emptyState(
+ 'No ERC-20 positions',
+ `${esc(shortAddr(state.address))} holds ${esc(fmtEth(state.wallet.native?.balance))} and no indexed tokens on 4663. Buy a coin from the movers rail below and it lands here.`,
+ );
+ return;
+ }
+
+ // A dusted wallet can hold hundreds of airdropped tokens, and a 200-row table
+ // buries the positions that carry the book. The deepest twelve render first;
+ // the rest are one click away and the count never lies about what is there.
+ const VISIBLE = 12;
+ const shown = state.showAllPositions ? rows : rows.slice(0, VISIBLE);
+ const hidden = rows.length - shown.length;
+ const total = state.wallet.book?.positionCount ?? rows.length;
+
+ el.innerHTML = `
+ ${cardHead(
+ 'Position ladder',
+ `${total} position${total === 1 ? '' : 's'} · ${state.wallet.book?.pricedCount ?? 0} priced`,
+ )}
+ <div class="cv-table-wrap">
+ <table class="hd-table">
+ <thead><tr>
+ <th class="left">Token</th><th>Amount</th><th>Price</th><th>Value</th><th>24h</th><th></th>
+ </tr></thead>
+ <tbody>
+ ${shown
+ .map(
+ (p) => `
+ <tr>
+ <td class="left">
+ <span class="hd-sym"><span class="sym">${esc(p.symbol || shortAddr(p.address, 6, 4))}</span>${
+ p.kind === 'stock' ? '<span class="tag">stock</span>' : ''
+ }${p.priceSource === 'chainlink-nav' ? '<span class="tag">nav</span>' : ''}</span>
+ <span class="hd-share" aria-hidden="true"><span style="width:${Math.max(
+ 2,
+ Math.min(100, p.sharePct || 0),
+ ).toFixed(1)}%"></span></span>
+ </td>
+ <td>${esc(fmtAmount(p.amount))}</td>
+ <td>${p.priceUsd != null ? esc(formatPrice(p.priceUsd)) : `<span class="hd-dim">unpriced</span>`}</td>
+ <td>${p.valueUsd != null ? esc(formatUsd(p.valueUsd)) : DASH}</td>
+ <td class="${signClass(p.change24hPct)}">${esc(formatPercent(p.change24hPct))}</td>
+ <td><button class="hd-btn hd-btn-sm" type="button" data-action="trade" data-address="${esc(
+ p.address,
+ )}" data-symbol="${esc(p.symbol || '')}" data-decimals="${p.decimals ?? 18}" data-kind="${esc(
+ p.kind,
+ )}" data-pair="${esc(p.pairUrl || '')}">Trade</button></td>
+ </tr>`,
+ )
+ .join('')}
+ </tbody>
+ </table>
+ </div>
+ ${
+ hidden > 0
+ ? `<button class="hd-btn hd-btn-sm" type="button" data-action="expand-positions" style="margin-top:0.75rem">Show ${hidden} smaller position${
+ hidden === 1 ? '' : 's'
+ }</button>`
+ : ''
+ }
+ ${
+ state.wallet.positionsTruncated
+ ? `<p class="hd-note">Showing the deepest ${rows.length} of ${total} tokens this wallet holds, by value.</p>`
+ : ''
+ }`;
+}
+
+// ── counterparty flow ───────────────────────────────────────────────────────
+function flowSvg(rows) {
+ const width = 420;
+ const rowH = 26;
+ const height = Math.max(120, rows.length * rowH + 24);
+ const leftX = 34;
+ const rightX = 210;
+ const cy = height / 2;
+ const max = Math.max(...rows.map((r) => r.total), 1);
+
+ return `
+ <svg class="hd-flow-svg" viewBox="0 0 ${width} ${height}" role="img" aria-label="Counterparties this wallet trades against">
+ ${rows
+ .map((r, i) => {
+ const y = 16 + i * rowH;
+ const dominant = r.outCount >= r.inCount ? 'out' : 'in';
+ const w = 1 + (r.total / max) * 2.5;
+ return `
+ <g class="hd-flow-row">
+ <path class="hd-flow-arc ${dominant}" d="M${leftX} ${cy} C${(leftX + rightX) / 2} ${cy} ${
+ (leftX + rightX) / 2
+ } ${y} ${rightX} ${y}" stroke-width="${w.toFixed(2)}" />
+ <circle class="hd-flow-node" cx="${rightX}" cy="${y}" r="3.5" />
+ <text class="hd-flow-text strong" x="${rightX + 10}" y="${y + 3.5}">${esc(shortAddr(r.address, 8, 4))}</text>
+ <text class="hd-flow-text" x="${width - 6}" y="${y + 3.5}" text-anchor="end">${r.outCount}↑ ${r.inCount}↓</text>
+ </g>`;
+ })
+ .join('')}
+ <circle class="hd-flow-node self" cx="${leftX}" cy="${cy}" r="6" />
+ <text class="hd-flow-text strong" x="${leftX}" y="${cy + 22}" text-anchor="middle">you</text>
+ </svg>`;
+}
+
+function renderFlow() {
+ const el = document.getElementById('hd-flow');
+ if (!el) return;
+ if (!state.address) {
+ el.innerHTML =
+ cardHead('Counterparty flow', 'who you trade against') +
+ emptyState(
+ 'No counterparties yet',
+ 'Every leg on the tape has another side: routers, pools, launchpads, people. Load a wallet and the desk ranks them by how much crossed between you.',
+ 'Focus the address field',
+ 'focus-address',
+ );
+ return;
+ }
+ if (state.walletError) {
+ el.innerHTML = cardHead('Counterparty flow', 'who you trade against') + errorState(state.walletError, 'reload-wallet');
+ return;
+ }
+ if (!state.wallet) {
+ el.innerHTML = cardHead('Counterparty flow', 'who you trade against') + skeleton(200);
+ return;
+ }
+ const rows = state.wallet.counterparties || [];
+ if (!rows.length) {
+ el.innerHTML =
+ cardHead('Counterparty flow', 'who you trade against') +
+ emptyState('Nothing has crossed with this wallet', 'Its first swap or transfer draws the first arc here.');
+ return;
+ }
+ el.innerHTML = `
+ ${cardHead('Counterparty flow', `${rows.length} addresses`)}
+ ${flowSvg(rows)}
+ <div class="cv-table-wrap" style="margin-top:0.5rem">
+ <table class="hd-table">
+ <thead><tr><th class="left">Counterparty</th><th>Legs</th><th class="left">Kinds</th></tr></thead>
+ <tbody>
+ ${rows
+ .map(
+ (r) => `<tr>
+ <td class="left"><a href="${esc(explorerAddress(r.address))}" target="_blank" rel="noopener noreferrer">${esc(
+ r.name || shortAddr(r.address, 10, 6),
+ )}</a></td>
+ <td>${r.total}</td>
+ <td class="left hd-dim">${esc(Object.keys(r.kinds || {}).join(', '))}</td>
+ </tr>`,
+ )
+ .join('')}
+ </tbody>
+ </table>
+ </div>`;
+}
+
+// ── movers rail ─────────────────────────────────────────────────────────────
+function renderMovers() {
+ const el = document.getElementById('hd-movers');
+ if (!el) return;
+ if (state.deskError) {
+ el.innerHTML = cardHead('Movers', 'robinhood chain memecoins') + errorState(state.deskError, 'reload-desk');
+ return;
+ }
+ if (!state.desk) {
+ el.innerHTML =
+ cardHead('Movers', 'robinhood chain memecoins') +
+ `<div class="hd-rail">${Array.from({ length: 6 }).map(() => skeleton(96)).join('')}</div>`;
+ return;
+ }
+ const movers = state.desk.movers || [];
+ if (!movers.length) {
+ el.innerHTML =
+ cardHead('Movers', 'robinhood chain memecoins') +
+ emptyState(
+ 'No ranked movers right now',
+ 'The screener ranks the Robinhood Chain meme category by absolute 24h move. It refills on the next upstream refresh.',
+ 'Reload market data',
+ 'reload-desk',
+ );
+ return;
+ }
+ el.innerHTML = `
+ ${cardHead('Movers', `${movers.length} by absolute 24h move`, `<a class="hd-btn hd-btn-sm hd-btn-ghost" href="/markets/robinhood">Full board</a>`)}
+ <div class="hd-rail">
+ ${movers
+ .map(
+ (m) => `
+ <a class="hd-mover" href="https://www.coingecko.com/en/coins/${esc(m.id)}" target="_blank" rel="noopener noreferrer">
+ <span class="hd-mover-top">
+ ${m.image ? `<img src="${esc(m.image)}" alt="" loading="lazy" width="20" height="20" />` : ''}
+ <span class="hd-mover-sym">${esc(m.symbol)}</span>
+ <span class="hd-chg ${signClass(m.change24hPct)}">${esc(formatPercent(m.change24hPct))}</span>
+ </span>
+ <span class="hd-mover-price">${esc(formatPrice(m.priceUsd))}</span>
+ ${sparkline(m.sparkline7d || [])}
+ <span class="hd-label">vol ${esc(formatUsd(m.volume24hUsd))}</span>
+ </a>`,
+ )
+ .join('')}
+ </div>`;
+}
+
+// ── trade ticket ────────────────────────────────────────────────────────────
+async function openTrade(btn) {
+ const dialog = document.getElementById('hd-trade-dialog');
+ const body = document.getElementById('hd-trade-body');
+ const title = document.getElementById('hd-trade-title');
+ if (!dialog || !body) return;
+ const symbol = btn.dataset.symbol || '';
+ title.textContent = symbol ? `Trade ${symbol}` : 'Trade ticket';
+ body.innerHTML = skeleton(160);
+ if (typeof dialog.showModal === 'function') dialog.showModal();
+ else dialog.show();
+ try {
+ // The swap panel pulls viem in with it, so it loads on the first ticket
+ // rather than on every desk boot.
+ const mod = await import('./robinhood-purchase.js');
+ if (btn.dataset.kind === 'stock') {
+ mod.mountStockEligibilityGate(body, {
+ symbol,
+ dexUrl: btn.dataset.pair || `https://dexscreener.com/robinhood/${btn.dataset.address}`,
+ });
+ } else {
+ mod.mountBuyPanel(body, {
+ address: btn.dataset.address,
+ symbol,
+ decimals: Number(btn.dataset.decimals) || 18,
+ });
+ }
+ } catch (err) {
+ body.innerHTML = `<div class="hd-error" role="alert"><span>The trade ticket could not load (${esc(
+ err?.message || 'unknown error',
+ )}). Reload the page and try again, or trade this token from its <a href="/markets/robinhood">market page</a>.</span></div>`;
+ }
+}
+
+// ── loading ─────────────────────────────────────────────────────────────────
+async function loadDesk(signal) {
+ try {
+ state.desk = await getJson('/api/v1/robinhood/desk', signal);
+ state.deskError = null;
+ if (state.bootBlock == null) state.bootBlock = state.desk.chain?.blockHeight ?? null;
+ } catch (err) {
+ if (err.name === 'AbortError') return;
+ state.deskError = err.message || 'market data is unavailable right now';
+ }
+ state.lastTick = Date.now();
+ renderStats();
+ renderRidge();
+ renderMovers();
+ renderLive();
+}
+
+async function loadWallet(signal) {
+ if (!state.address || state.loadingWallet) return;
+ state.loadingWallet = true;
+ try {
+ state.wallet = await getJson(`/api/v1/robinhood/wallet?address=${encodeURIComponent(state.address)}`, signal);
+ state.walletError = null;
+ } catch (err) {
+ if (err.name === 'AbortError') return;
+ state.walletError = err.message || 'this wallet could not be read right now';
+ } finally {
+ state.loadingWallet = false;
+ }
+ renderStats();
+ renderBalance();
+ renderTape();
+ renderBook();
+ renderFlow();
+}
+
+function renderLive() {
+ const pill = document.getElementById('hd-live');
+ const text = document.getElementById('hd-live-text');
+ if (!pill || !text) return;
+ const fresh = state.lastTick && Date.now() - state.lastTick < DESK_REFRESH_MS * 2 && !state.deskError;
+ pill.dataset.state = fresh ? 'live' : 'stale';
+ text.textContent = fresh ? 'live' : state.deskError ? 'offline' : 'booting';
+}
+
+function renderClock() {
+ const el = document.getElementById('hd-clock');
+ if (!el) return;
+ const secs = Math.floor((Date.now() - state.bootedAt) / 1000);
+ const mm = String(Math.floor(secs / 60)).padStart(2, '0');
+ const ss = String(secs % 60).padStart(2, '0');
+ const height = state.desk?.chain?.blockHeight;
+ const blocks = height != null && state.bootBlock != null ? height - state.bootBlock : null;
+ el.textContent = blocks != null && blocks > 0 ? `${mm}:${ss} / +${blocks.toLocaleString('en-US')} blocks` : `${mm}:${ss}`;
+}
+
+function renderIdentity() {
+ const sub = document.getElementById('hd-brand-sub');
+ const input = document.getElementById('hd-address');
+ if (sub) sub.textContent = state.address ? `/ ${shortAddr(state.address)}` : '/ no wallet';
+ if (input && state.address && input.value !== state.address) input.value = state.address;
+}
+
+function setAddress(next, { push = true } = {}) {
+ const addr = String(next || '').trim();
+ if (!ADDRESS_RE.test(addr)) return false;
+ state.address = addr.toLowerCase();
+ state.wallet = null;
+ state.walletError = null;
+ state.seen = new Set();
+ state.showAllPositions = false;
+ try {
+ localStorage.setItem(STORAGE_KEY, state.address);
+ } catch {
+ /* private mode: the address still works for this session */
+ }
+ if (push) {
+ const url = new URL(location.href);
+ url.searchParams.set('address', state.address);
+ history.replaceState(null, '', url);
+ }
+ renderIdentity();
+ renderStats();
+ renderBalance();
+ renderTape();
+ renderBook();
+ renderFlow();
+ return true;
+}
+
+function showAlert(message, kind = 'error') {
+ const el = document.getElementById('hd-alert');
+ if (!el) return;
+ if (!message) {
+ el.hidden = true;
+ el.innerHTML = '';
+ return;
+ }
+ el.hidden = false;
+ el.innerHTML = `<div class="hd-error" role="alert" style="margin-bottom:0.875rem;${
+ kind === 'info' ? 'border-color:var(--cv-border);background:var(--cv-surface-2);color:var(--cv-text-2)' : ''
+ }"><span>${esc(message)}</span></div>`;
+}
+
+async function connectWallet() {
+ const btn = document.getElementById('hd-connect');
+ if (!window.ethereum) {
+ showAlert('No injected wallet found in this browser. Paste an address instead, or install an EVM wallet extension.');
+ return;
+ }
+ btn.disabled = true;
+ try {
+ const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
+ const [addr] = accounts || [];
+ if (!addr) throw new Error('the wallet returned no account');
+ showAlert(null);
+ setAddress(addr);
+ await loadWallet();
+ } catch (err) {
+ showAlert(`Wallet connect failed: ${err?.message || 'unknown error'}`);
+ } finally {
+ btn.disabled = false;
+ }
+}
+
+// ── boot ────────────────────────────────────────────────────────────────────
+function init({ signal }) {
+ state.bootedAt = Date.now();
+ state.desk = null;
+ state.wallet = null;
+ state.deskError = null;
+ state.walletError = null;
+ state.bootBlock = null;
+
+ const params = new URLSearchParams(location.search);
+ let initial = params.get('address');
+ if (!ADDRESS_RE.test(initial || '')) {
+ try {
+ initial = localStorage.getItem(STORAGE_KEY);
+ } catch {
+ initial = null;
+ }
+ }
+ state.address = ADDRESS_RE.test(initial || '') ? initial.toLowerCase() : null;
+
+ renderIdentity();
+ renderStats();
+ renderBalance();
+ renderTape();
+ renderRidge();
+ renderBook();
+ renderFlow();
+ renderMovers();
+ renderClock();
+
+ const form = document.getElementById('hd-address-form') || document.getElementById('hd-wallet-form');
+ form?.addEventListener(
+ 'submit',
+ (ev) => {
+ ev.preventDefault();
+ const input = document.getElementById('hd-address');
+ if (!setAddress(input.value)) {
+ showAlert('That is not a Robinhood Chain address. Paste a 20-byte 0x address.');
+ input.focus();
+ return;
+ }
+ showAlert(null);
+ loadWallet(signal);
+ },
+ { signal },
+ );
+
+ document.getElementById('hd-connect')?.addEventListener('click', connectWallet, { signal });
+ document.getElementById('hd-trade-close')?.addEventListener(
+ 'click',
+ () => document.getElementById('hd-trade-dialog')?.close(),
+ { signal },
+ );
+
+ document.getElementById('hd-main')?.addEventListener(
+ 'click',
+ (ev) => {
+ const btn = ev.target.closest('[data-action]');
+ if (!btn) return;
+ const action = btn.dataset.action;
+ if (action === 'focus-address') document.getElementById('hd-address')?.focus();
+ else if (action === 'reload-desk') {
+ state.deskError = null;
+ renderRidge();
+ renderMovers();
+ loadDesk(signal);
+ } else if (action === 'reload-wallet') {
+ state.walletError = null;
+ renderBalance();
+ renderTape();
+ renderBook();
+ renderFlow();
+ loadWallet(signal);
+ } else if (action === 'expand-positions') {
+ state.showAllPositions = true;
+ renderBook();
+ } else if (action === 'trade') openTrade(btn);
+ },
+ { signal },
+ );
+
+ loadDesk(signal);
+ if (state.address) loadWallet(signal);
+
+ const clockTimer = setInterval(renderClock, 1000);
+ const deskTimer = setInterval(() => {
+ if (document.hidden) return;
+ loadDesk(signal);
+ }, DESK_REFRESH_MS);
+ const walletTimer = setInterval(() => {
+ if (document.hidden || !state.address) return;
+ loadWallet(signal);
+ }, WALLET_REFRESH_MS);
+
+ signal.addEventListener('abort', () => {
+ clearInterval(clockTimer);
+ clearInterval(deskTimer);
+ clearInterval(walletTimer);
+ });
+}
+
+onPageReady(init, { match: (path) => /^\/markets\/robinhood\/desk\/?$/.test(path) });
diff --git a/src/robinhood.css b/src/robinhood.css
index 5176af6e7..a8b00d522 100644
--- a/src/robinhood.css
+++ b/src/robinhood.css
@@ -350,3 +350,22 @@
.rh-bridge-link:focus-visible {
text-decoration: underline;
}
+
+/* Cross-link from the hub to the Hood Desk (/markets/robinhood/desk). */
+.rh-desk-cta {
+ display: flex;
+ align-items: baseline;
+ flex-wrap: wrap;
+ gap: 0.5rem 0.75rem;
+ margin: 0 0 1.25rem;
+ padding: 0.75rem 0.875rem;
+ border: 1px solid var(--cv-border);
+ border-radius: var(--cv-radius-lg);
+ background: var(--cv-surface-2);
+}
+
+.rh-desk-cta span {
+ color: var(--cv-text-2);
+ font-size: 0.8125rem;
+ line-height: 1.5;
+}
diff --git a/tests/robinhood-desk.test.js b/tests/robinhood-desk.test.js
new file mode 100644
index 000000000..8d4ea8e68
--- /dev/null
+++ b/tests/robinhood-desk.test.js
@@ -0,0 +1,342 @@
+// Unit tests for the Hood Desk derivations (api/_lib/robinhood-desk.js).
+//
+// These are the rules the desk renders: how a premium distribution is binned,
+// which dislocations count as tradeable, how Blockscout's two balance feeds
+// become one curve, and how a raw transaction/transfer pair becomes one line on
+// the tape. Every fixture below is shaped like the real upstream payload (field
+// names and raw atomic strings included), because the bugs these guard against
+// were all shape bugs.
+
+import { describe, it, expect } from 'vitest';
+import {
+ normalizeAddress,
+ toUnits,
+ premiumRidge,
+ arbLeaders,
+ balanceSeries,
+ mergeBalanceHistory,
+ seriesChange,
+ classifyTransaction,
+ classifyTransfer,
+ mergeActivity,
+ counterpartyFlow,
+ rollupBook,
+} from '../api/_lib/robinhood-desk.js';
+
+// Synthetic addresses: these tests pin arithmetic and shape, never a real wallet.
+const ME = '0x1111111111111111111111111111111111111111';
+const ROUTER = '0x2222222222222222222222222222222222222222';
+
+describe('normalizeAddress', () => {
+ it('lowercases a checksummed address and rejects everything else', () => {
+ expect(normalizeAddress('0xAbCdEf0000000000000000000000000000000001')).toBe(
+ '0xabcdef0000000000000000000000000000000001',
+ );
+ expect(normalizeAddress('0x123')).toBeNull();
+ expect(normalizeAddress('not an address')).toBeNull();
+ expect(normalizeAddress(null)).toBeNull();
+ });
+});
+
+describe('toUnits', () => {
+ it('divides a raw atomic string by its decimals', () => {
+ expect(toUnits('5000000000000000000', 18)).toBe(5);
+ expect(toUnits('1500000', 6)).toBe(1.5);
+ });
+
+ it('returns null rather than a wrong number when decimals are unknown', () => {
+ // An unverified launchpad token is indexed with decimals: null. Guessing
+ // 18 would print a balance off by orders of magnitude.
+ expect(toUnits('5000000000000000000', null)).toBeNull();
+ expect(toUnits(null, 18)).toBeNull();
+ expect(toUnits('abc', 18)).toBeNull();
+ });
+});
+
+describe('premiumRidge', () => {
+ const rows = [
+ { symbol: 'MU', premiumPct: 2.5, liquidityUsd: 1_600_000 },
+ { symbol: 'AMD', premiumPct: 1.4, liquidityUsd: 730_000 },
+ { symbol: 'SPCX', premiumPct: 1.7, liquidityUsd: 2_500_000 },
+ { symbol: 'NVDA', premiumPct: -0.3, liquidityUsd: 900_000 },
+ { symbol: 'NOPOOL', premiumPct: null, liquidityUsd: null },
+ ];
+
+ it('bins only the tokens priced on both sides', () => {
+ const ridge = premiumRidge(rows);
+ expect(ridge.stats.priced).toBe(4);
+ expect(ridge.stats.total).toBe(5);
+ const front = ridge.layers[0];
+ expect(front.count).toBe(4);
+ expect(front.density.reduce((a, b) => a + b, 0)).toBe(4);
+ });
+
+ it('fits the axis to the day dispersion instead of a fixed span', () => {
+ const tight = premiumRidge([{ symbol: 'A', premiumPct: 0.2, liquidityUsd: 1 }]);
+ expect(tight.stats.spanPct).toBe(1);
+ const wide = premiumRidge([{ symbol: 'A', premiumPct: 6, liquidityUsd: 1 }]);
+ expect(wide.stats.spanPct).toBeGreaterThanOrEqual(6);
+ });
+
+ it('thins each deeper liquidity layer, so the ridge reads as depth', () => {
+ const ridge = premiumRidge(rows);
+ const counts = ridge.layers.map((l) => l.count);
+ expect(counts[0]).toBe(4);
+ for (let i = 1; i < counts.length; i++) expect(counts[i]).toBeLessThanOrEqual(counts[i - 1]);
+ });
+
+ it('clamps an outlier into the edge bin instead of flattening the chart', () => {
+ const ridge = premiumRidge([...rows, { symbol: 'BROKEN', premiumPct: 900, liquidityUsd: 10 }], { span: 4 });
+ expect(ridge.layers[0].density[ridge.bins.length - 1]).toBe(1);
+ expect(ridge.stats.spanPct).toBe(4);
+ });
+
+ it('survives an empty board', () => {
+ const ridge = premiumRidge([]);
+ expect(ridge.stats.priced).toBe(0);
+ expect(ridge.stats.median).toBeNull();
+ expect(ridge.layers.every((l) => l.count === 0)).toBe(true);
+ });
+});
+
+describe('arbLeaders', () => {
+ it('ranks by absolute dislocation and drops pools too thin to trade', () => {
+ const leaders = arbLeaders([
+ { symbol: 'DEEP', premiumPct: 1.2, liquidityUsd: 500_000 },
+ { symbol: 'DUST', premiumPct: 40, liquidityUsd: 12 },
+ { symbol: 'CHEAP', premiumPct: -3.4, liquidityUsd: 90_000 },
+ { symbol: 'NOPOOL', premiumPct: 9, liquidityUsd: null },
+ ]);
+ expect(leaders.map((r) => r.symbol)).toEqual(['CHEAP', 'DEEP']);
+ expect(leaders[0].side).toBe('dex-cheap');
+ expect(leaders[1].side).toBe('dex-rich');
+ });
+});
+
+describe('balanceSeries', () => {
+ const items = [
+ { block_number: 3, block_timestamp: '2026-09-07T20:58:42Z', value: '70710803028246028' },
+ { block_number: 2, block_timestamp: '2026-09-07T20:57:42Z', value: '84300058721425040' },
+ { block_number: 1, block_timestamp: '2026-09-07T20:56:42Z', value: '0' },
+ ];
+
+ it('flips Blockscout newest-first into an ascending ETH curve', () => {
+ const series = balanceSeries(items, { ethPriceUsd: 2000 });
+ expect(series.map((p) => p.block)).toEqual([1, 2, 3]);
+ expect(series[2].eth).toBeCloseTo(0.07071080302824603, 12);
+ expect(series[2].usd).toBeCloseTo(0.07071080302824603 * 2000, 8);
+ });
+
+ it('leaves usd null when no ETH price is available', () => {
+ expect(balanceSeries(items)[0].usd).toBeNull();
+ });
+
+ it('keeps the last balance when several transfers share one timestamp', () => {
+ const series = balanceSeries([
+ { block_number: 2, block_timestamp: '2026-09-07T20:58:42Z', value: '2000000000000000000' },
+ { block_number: 1, block_timestamp: '2026-09-07T20:58:42Z', value: '1000000000000000000' },
+ ]);
+ expect(series).toHaveLength(1);
+ expect(series[0].eth).toBe(2);
+ });
+
+ it('drops unparseable points instead of rendering NaN', () => {
+ expect(balanceSeries([{ block_timestamp: 'never', value: '1' }, { value: null }])).toEqual([]);
+ });
+});
+
+describe('mergeBalanceHistory', () => {
+ it('plots a daily close at the end of its day and stops where the tape starts', () => {
+ const now = Date.parse('2026-09-07T21:00:00Z');
+ const daily = balanceSeries([
+ { date: '2026-09-05', value: '1000000000000000000' },
+ { date: '2026-09-06', value: '2000000000000000000' },
+ { date: '2026-09-07', value: '3000000000000000000' },
+ ]);
+ const intraday = balanceSeries([
+ { block_number: 9, block_timestamp: '2026-09-07T20:58:42Z', value: '3000000000000000000' },
+ ]);
+ const merged = mergeBalanceHistory(daily, intraday, { now });
+ // The 2026-09-07 daily close is dropped: the per-transaction feed already
+ // covers that instant, and plotting both would draw a step backwards.
+ expect(merged).toHaveLength(3);
+ expect(new Date(merged[0].t).toISOString()).toBe('2026-09-05T23:59:59.000Z');
+ expect(merged[merged.length - 1].block).toBe(9);
+ });
+
+ it('returns the daily curve alone when nothing intraday is indexed', () => {
+ const daily = balanceSeries([{ date: '2026-09-06', value: '1000000000000000000' }]);
+ expect(mergeBalanceHistory(daily, [], { now: Date.parse('2026-09-07T00:00:00Z') })).toHaveLength(1);
+ });
+});
+
+describe('seriesChange', () => {
+ it('reports start, end, delta and percentage', () => {
+ const change = seriesChange([
+ { t: 1, eth: 2 },
+ { t: 2, eth: 3 },
+ ]);
+ expect(change.deltaEth).toBe(1);
+ expect(change.pct).toBeCloseTo(50, 6);
+ });
+
+ it('cannot divide by a zero opening balance', () => {
+ const change = seriesChange([
+ { t: 1, eth: 0 },
+ { t: 2, eth: 5 },
+ ]);
+ expect(change.deltaEth).toBe(5);
+ expect(change.pct).toBeNull();
+ });
+
+ it('reports nulls for a one-point series rather than a fake flat line', () => {
+ expect(seriesChange([{ t: 1, eth: 2 }]).deltaEth).toBeNull();
+ });
+});
+
+describe('classifyTransaction', () => {
+ it('reads a router call with token legs as a swap', () => {
+ const ev = classifyTransaction(
+ {
+ hash: '0xabc',
+ method: '0xd04c6983',
+ result: 'success',
+ value: '0',
+ transaction_types: ['contract_call', 'token_transfer'],
+ from: { hash: ME },
+ to: { hash: ROUTER },
+ },
+ ME,
+ );
+ expect(ev.kind).toBe('swap');
+ expect(ev.direction).toBe('out');
+ expect(ev.counterparty).toBe(ROUTER);
+ });
+
+ it('separates a plain send from a plain receive', () => {
+ const out = classifyTransaction({ hash: '0x1', value: '1000000000000000000', from: { hash: ME }, to: { hash: ROUTER } }, ME);
+ const inn = classifyTransaction({ hash: '0x2', value: '1000000000000000000', from: { hash: ROUTER }, to: { hash: ME } }, ME);
+ expect(out.kind).toBe('send');
+ expect(inn.kind).toBe('receive');
+ expect(inn.counterparty).toBe(ROUTER);
+ expect(out.valueEth).toBe(1);
+ });
+
+ it('labels approvals and claims for what they are', () => {
+ expect(classifyTransaction({ hash: '0x3', method: 'approve', from: { hash: ME }, to: { hash: ROUTER } }, ME).kind).toBe('approve');
+ expect(classifyTransaction({ hash: '0x4', method: 'claimFree', from: { hash: ME }, to: { hash: ROUTER } }, ME).kind).toBe('claim');
+ });
+});
+
+describe('classifyTransfer', () => {
+ it('uses the transfer total decimals, not a guessed 18', () => {
+ const ev = classifyTransfer(
+ {
+ transaction_hash: '0xabc',
+ from: { hash: ROUTER },
+ to: { hash: ME },
+ token: { address_hash: '0xAAA0000000000000000000000000000000000001', symbol: 'USDG', decimals: 6 },
+ total: { value: '2500000', decimals: 6 },
+ },
+ ME,
+ );
+ expect(ev.amount).toBe(2.5);
+ expect(ev.direction).toBe('in');
+ expect(ev.kind).toBe('receive');
+ });
+
+ it('calls a transfer out of the zero address a mint', () => {
+ const ev = classifyTransfer(
+ {
+ transaction_hash: '0xd',
+ from: { hash: '0x0000000000000000000000000000000000000000' },
+ to: { hash: ME },
+ token: { address_hash: '0xAAA0000000000000000000000000000000000002', symbol: 'NEW', decimals: 18 },
+ total: { value: '1000000000000000000', decimals: 18 },
+ },
+ ME,
+ );
+ expect(ev.kind).toBe('mint');
+ });
+});
+
+describe('mergeActivity', () => {
+ const tx = {
+ hash: '0xswap',
+ method: 'swapExactETHForTokens',
+ result: 'success',
+ value: '50000000000000000',
+ timestamp: '2026-09-07T20:58:40Z',
+ transaction_types: ['contract_call', 'token_transfer'],
+ from: { hash: ME },
+ to: { hash: ROUTER },
+ };
+ const transfer = {
+ transaction_hash: '0xswap',
+ timestamp: '2026-09-07T20:58:40Z',
+ from: { hash: ROUTER },
+ to: { hash: ME },
+ token: { address_hash: '0xAAA0000000000000000000000000000000000003', symbol: 'MEME', decimals: 18 },
+ total: { value: '27000000000000000000', decimals: 18 },
+ };
+
+ it('folds a swap transfer onto its transaction instead of printing it twice', () => {
+ const tape = mergeActivity([tx], [transfer], ME);
+ expect(tape).toHaveLength(1);
+ expect(tape[0].kind).toBe('swap');
+ expect(tape[0].tokens).toEqual([
+ { symbol: 'MEME', address: '0xaaa0000000000000000000000000000000000003', amount: 27, direction: 'in' },
+ ]);
+ });
+
+ it('keeps a transfer whose transaction is outside the fetched window', () => {
+ const tape = mergeActivity([], [transfer], ME);
+ expect(tape).toHaveLength(1);
+ expect(tape[0].kind).toBe('receive');
+ });
+
+ it('orders the tape newest first and caps it', () => {
+ const older = { ...tx, hash: '0xold', timestamp: '2026-09-07T19:00:00Z' };
+ const tape = mergeActivity([older, tx], [], ME, { limit: 1 });
+ expect(tape).toHaveLength(1);
+ expect(tape[0].hash).toBe('0xswap');
+ });
+});
+
+describe('counterpartyFlow', () => {
+ it('ranks counterparties by legs crossed and splits direction', () => {
+ const rows = counterpartyFlow([
+ { counterparty: ROUTER, direction: 'out', kind: 'swap' },
+ { counterparty: ROUTER, direction: 'out', kind: 'swap' },
+ { counterparty: ROUTER, direction: 'in', kind: 'receive' },
+ { counterparty: '0xAAA0000000000000000000000000000000000004', direction: 'in', kind: 'receive' },
+ { counterparty: '0x0000000000000000000000000000000000000000', direction: 'in', kind: 'mint' },
+ { counterparty: null, direction: 'in', kind: 'call' },
+ ]);
+ expect(rows).toHaveLength(2);
+ expect(rows[0].address).toBe(ROUTER);
+ expect(rows[0].outCount).toBe(2);
+ expect(rows[0].inCount).toBe(1);
+ expect(rows[0].kinds).toEqual({ swap: 2, receive: 1 });
+ });
+});
+
+describe('rollupBook', () => {
+ it('totals native plus priced tokens and shares out the book', () => {
+ const book = rollupBook(100, [
+ { symbol: 'A', valueUsd: 60 },
+ { symbol: 'B', valueUsd: 40 },
+ ]);
+ expect(book.bookValueUsd).toBe(200);
+ expect(book.positions[0].sharePct).toBeCloseTo(30, 6);
+ expect(book.nativeSharePct).toBeCloseTo(50, 6);
+ });
+
+ it('never counts an unpriced token into the book as zero-value truth', () => {
+ const book = rollupBook(100, [{ symbol: 'UNKNOWN', valueUsd: null }]);
+ expect(book.bookValueUsd).toBe(100);
+ expect(book.positionCount).toBe(1);
+ expect(book.pricedCount).toBe(0);
+ expect(book.positions[0].sharePct).toBeNull();
+ });
+});
diff --git a/vercel.json b/vercel.json
index 09b9e17d9..d76a07a09 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1231,6 +1231,10 @@
"src": "/markets/robinhood/?",
"dest": "/markets-robinhood.html"
},
+ {
+ "src": "/markets/robinhood/desk/?",
+ "dest": "/hood-desk.html"
+ },
{
"src": "/markets/robinhood/stock/([A-Za-z0-9.-]{1,10})/?",
"dest": "/robinhood-stock.html"
diff --git a/vite.config.js b/vite.config.js
index 423b58942..fdbd90453 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -811,6 +811,7 @@ const appConfig = {
stablecoin: resolve(__dirname, 'pages/stablecoin.html'),
'markets-trending': resolve(__dirname, 'pages/markets-trending.html'),
'markets-robinhood': resolve(__dirname, 'pages/markets-robinhood.html'),
+ 'hood-desk': resolve(__dirname, 'pages/hood-desk.html'),
fees: resolve(__dirname, 'pages/fees.html'),
'sniper-experiments': resolve(__dirname, 'pages/sniper-experiments.html'),
'dex-volumes': resolve(__dirname, 'pages/dex-volumes.html'),
@@ -1612,6 +1613,8 @@ const appConfig = {
'/markets/': resolve(root, 'pages/markets.html'),
'/markets/robinhood': resolve(root, 'pages/markets-robinhood.html'),
'/markets/robinhood/': resolve(root, 'pages/markets-robinhood.html'),
+ '/markets/robinhood/desk': resolve(root, 'pages/hood-desk.html'),
+ '/markets/robinhood/desk/': resolve(root, 'pages/hood-desk.html'),
'/markets/news': resolve(root, 'pages/markets-news.html'),
'/markets/news/': resolve(root, 'pages/markets-news.html'),
'/markets/digest': resolve(root, 'pages/news-digest.html'),