Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add sequencer firehose example and live price webpage
fudjia1d455515c323
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex c9a0e3ffb..4d933cee1 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -578,15 +578,6 @@ export const limits = {// zauth's paid x402 endpoint and each GET polls a scan session; cap per IP// so one caller can't use the proxy as a relay to hammer their upstream.zauthScanIp: (ip) => getLimiter('zauthscan:ip', { limit: 30, window: '1 m' }).limit(ip),- // Robinhood Chain market data (api/v1/robinhood/*). Every response is served- // from a short-TTL snapshot cache (cacheWrap), so this only gates cache-miss- // origin work — a multicall sweep over the 95 Stock Tokens or a DefiLlama /- // CoinGecko fetch. Its OWN bucket (never public:ip — the play-lobby-429- // lesson) so a busy board never drains the shared read budget other pages- // need. Generous for an interactive board + detail views; `local` (per- // instance) because it only bounds scripted scraping of cache-fronted reads,- // and a distributed Redis command per poll is what drained the Upstash quota.- robinhoodIp: (ip) => getLimiter('robinhood:ip', { limit: 120, window: '1 m', local: true }).limit(ip),// aixbt intelligence bridge (api/aixbt/*). Each call may fall through to the// upstream aixbt REST API, which is rate-limited per key — cap per IP so one// caller can't drain the shared key's budget. Reads are cached, so this isdiff --git a/api/_lib/robinhood.js b/api/_lib/robinhood.jsindex b717234d1..374ec76ea 100644--- a/api/_lib/robinhood.js+++ b/api/_lib/robinhood.js@@ -187,6 +187,64 @@ export async function chainlinkSnapshot() {});}+const GET_ROUND_DATA_ABI = [+ {+ type: 'function',+ name: 'getRoundData',+ stateMutability: 'view',+ inputs: [{ name: '_roundId', type: 'uint80' }],+ outputs: [+ { name: 'roundId', type: 'uint80' },+ { name: 'answer', type: 'int256' },+ { name: 'startedAt', type: 'uint256' },+ { name: 'updatedAt', type: 'uint256' },+ { name: 'answeredInRound', type: 'uint80' },+ ],+ },+];++/**+ * Recent Chainlink NAV history for one feed — the last `count` rounds ending at+ * the current latestRound, read in ONE multicall. Chainlink packs round IDs as+ * (phaseId << 64) | aggregatorRound, so decrementing stays inside the current+ * phase for a short window. Returns [{ roundId, priceUsd, updatedAt }] oldest+ * first; failed/empty rounds are dropped. Cached 60s.+ */+export async function feedRoundHistory(feed, count = 24) {+ const addr = String(feed || '').toLowerCase();+ if (!/^0x[0-9a-f]{40}$/.test(addr)) return [];+ return cacheWrap(`rh:feed:hist:${addr}:${count}`, 60, async () => {+ const client = publicClient(false);+ let latest;+ try {+ latest = await client.readContract({ address: feed, abi: AGGREGATOR_ABI, functionName: 'latestRoundData' });+ } catch {+ return [];+ }+ const latestId = latest[0];+ const ids = [];+ for (let i = BigInt(count) - 1n; i >= 0n; i--) {+ const id = latestId - i;+ if (id <= 0n) continue;+ ids.push(id);+ }+ const results = await client.multicall({+ contracts: ids.map((id) => ({ address: feed, abi: GET_ROUND_DATA_ABI, functionName: 'getRoundData', args: [id] })),+ allowFailure: true,+ });+ const out = [];+ for (let i = 0; i < results.length; i++) {+ const r = results[i];+ if (r?.status !== 'success') continue;+ const answer = r.result[1];+ const updatedAt = Number(r.result[3]);+ if (answer == null || !updatedAt) continue;+ out.push({ roundId: ids[i].toString(), priceUsd: Number(answer) / 10 ** FEED_DECIMALS, updatedAt });+ }+ return out;+ });+}+// ── DexScreener (chainId "robinhood") ──────────────────────────────────────async function fetchJson(url, ttl, key, { headers } = {}) {return cacheWrap(key, ttl, async () => {diff --git a/api/_lib/robinhood/handler-util.js b/api/_lib/robinhood/handler-util.jsnew file mode 100644index 000000000..f4b6e55a5--- /dev/null+++ b/api/_lib/robinhood/handler-util.js@@ -0,0 +1,25 @@+// Shared bits for the api/v1/robinhood/* handlers: network parsing and the+// dedicated per-IP rate-limit gate (the play-lobby-429 lesson — a busy board+// gets its OWN bucket instead of draining the shared read budget).++import { fail } from '../gateway.js';+import { limits, clientIp } from '../rate-limit.js';++/** Resolve the ?network= param to 'mainnet' | 'testnet' (default mainnet). */+export function resolveNetwork(query) {+ const n = String(query.network || 'mainnet').toLowerCase();+ if (n === 'testnet' || n === '46630') return 'testnet';+ if (n === 'mainnet' || n === '4663' || n === '') return 'mainnet';+ fail(400, 'invalid_network', 'network must be "mainnet" or "testnet"');+ return 'mainnet';+}++/** Enforce the dedicated robinhood bucket; 429 with Retry-After on trip. */+export async function gateRobinhood(ctx) {+ const ip = ctx.ip || clientIp(ctx.req);+ const rl = await limits.robinhoodIp(ip);+ if (!rl.success) {+ const retry = Math.max(1, Math.ceil((rl.reset - Date.now()) / 1000));+ fail(429, 'rate_limited', `Robinhood market data is busy — retry in ${retry}s`);+ }+}diff --git a/api/v1/robinhood/chain.js b/api/v1/robinhood/chain.jsnew file mode 100644index 000000000..e0d8c564e--- /dev/null+++ b/api/v1/robinhood/chain.js@@ -0,0 +1,70 @@+// GET /api/v1/robinhood/chain — Robinhood Chain (4663) stats.+//+// Free, keyless. Real data: block height + gas (Blockscout), TVL now + 90-day+// history (DefiLlama /chain/robinhood-chain). Cached upstream (15s stats, 120s+// TVL), dedicated per-IP bucket. Robinhood Chain is a permissionless Arbitrum+// Orbit L2 (ETH gas, ~100ms blocks); it has NO native chain token.++import { defineEndpoint } from '../../_lib/gateway.js';+import { rateLimited } from '../../_lib/http.js';+import { limits } from '../../_lib/rate-limit.js';+import {+ blockscoutStats,+ chainTvlCurrent,+ chainTvlHistory,+ publicClient,+ asOf,+} from '../../_lib/robinhood.js';++const CACHE_CONTROL = 'public, max-age=15, s-maxage=15, stale-while-revalidate=30';++export default defineEndpoint({+ name: 'v1.robinhood.chain',+ 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 [stats, tvl, tvlHistory, blockNumber] = await Promise.all([+ blockscoutStats(),+ chainTvlCurrent(),+ chainTvlHistory(),+ publicClient(false)+ .getBlockNumber()+ .then((n) => Number(n))+ .catch(() => null),+ ]);++ const gas = stats && !stats.__error ? stats.gas_prices || null : null;+ res.setHeader('cache-control', CACHE_CONTROL);+ return {+ chain: {+ name: 'Robinhood Chain',+ chainId: 4663,+ type: 'Arbitrum Orbit L2',+ gasToken: 'ETH',+ nativeChainToken: null,+ explorer: 'https://robinhoodchain.blockscout.com',+ rpc: 'https://rpc.mainnet.chain.robinhood.com',+ },+ 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,+ totalAddresses: stats && !stats.__error ? stats.total_addresses ?? null : null,+ gas: gas+ ? {+ slow: gas.slow ?? null,+ average: gas.average ?? null,+ fast: gas.fast ?? null,+ unit: 'gwei',+ }+ : null,+ ethPriceUsd: stats && !stats.__error && stats.coin_price ? Number(stats.coin_price) : null,+ tvlUsd: tvl ?? null,+ tvlHistory,+ source: 'blockscout + defillama',+ asOf: asOf(),+ };+ },+});diff --git a/api/v1/robinhood/coins-detail.js b/api/v1/robinhood/coins-detail.jsnew file mode 100644index 000000000..ffdb24b94--- /dev/null+++ b/api/v1/robinhood/coins-detail.js@@ -0,0 +1,88 @@+// GET /api/v1/robinhood/coins-detail?address=0x… — one Robinhood-chain coin.+//+// Free, keyless. DexScreener (price, market cap, FDV, liquidity, 24h volume,+// txns, price-change windows, age, deepest pool) + Blockscout (holders count,+// supply, recent holders + transfers). Non-security token — no eligibility gate.++import { defineEndpoint, fail } from '../../_lib/gateway.js';+import { rateLimited } from '../../_lib/http.js';+import { limits } from '../../_lib/rate-limit.js';+import {+ dexPairsForToken,+ blockscoutToken,+ blockscoutHolders,+ blockscoutTransfers,+ BLOCKSCOUT_BASE,+ asOf,+} from '../../_lib/robinhood.js';++const CACHE_CONTROL = 'public, max-age=30, s-maxage=30, stale-while-revalidate=45';+const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;++export default defineEndpoint({+ name: 'v1.robinhood.coins-detail',+ 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 = String(query.address || '').trim();+ if (!ADDR_RE.test(address)) fail(400, 'validation_error', 'pass ?address=<0x… token address>');++ const [pairs, bsToken, holders, transfers] = await Promise.all([+ dexPairsForToken(address),+ blockscoutToken(address),+ blockscoutHolders(address, 25),+ blockscoutTransfers(address, 25),+ ]);++ if (!pairs.length && !bsToken) {+ fail(404, 'not_found', 'no Robinhood-chain market or token record found for that address');+ }++ const best = pairs[0] || null;+ res.setHeader('cache-control', CACHE_CONTROL);+ return {+ address,+ symbol: (best?.baseToken?.symbol || bsToken?.symbol || '').toUpperCase() || null,+ name: best?.baseToken?.name || bsToken?.name || null,+ iconUrl: bsToken?.icon_url || (best?.info?.imageUrl ?? null),+ market: best+ ? {+ priceUsd: best.priceUsd != null ? Number(best.priceUsd) : null,+ marketCapUsd: best.marketCap ?? null,+ fdvUsd: best.fdv ?? null,+ liquidityUsd: best.liquidity?.usd ?? null,+ volume24hUsd: best.volume?.h24 ?? null,+ priceChange: best.priceChange || null,+ txns24h: best.txns?.h24 || null,+ pairCreatedAt: best.pairCreatedAt ?? null,+ dexId: best.dexId ?? null,+ pairAddress: best.pairAddress ?? null,+ quoteSymbol: best.quoteToken?.symbol ?? null,+ url: best.url || null,+ }+ : null,+ pools: pairs.map((p) => ({+ dexId: p.dexId,+ pairAddress: p.pairAddress,+ quoteSymbol: p.quoteToken?.symbol ?? null,+ priceUsd: p.priceUsd != null ? Number(p.priceUsd) : null,+ liquidityUsd: p.liquidity?.usd ?? null,+ volume24hUsd: p.volume?.h24 ?? null,+ })),+ holdersCount: bsToken?.holders_count != null ? Number(bsToken.holders_count) : null,+ totalSupply: bsToken?.total_supply ?? null,+ decimals: bsToken?.decimals != null ? Number(bsToken.decimals) : null,+ holders,+ recentTransfers: transfers,+ links: {+ explorer: `${BLOCKSCOUT_BASE}/token/${address}`,+ dex: best?.url || null,+ },+ source: 'dexscreener + blockscout',+ asOf: asOf(),+ };+ },+});diff --git a/api/v1/robinhood/coins.js b/api/v1/robinhood/coins.jsnew file mode 100644index 000000000..72a8b6773--- /dev/null+++ b/api/v1/robinhood/coins.js@@ -0,0 +1,66 @@+// GET /api/v1/robinhood/coins — Robinhood Chain memecoin screener.+//+// Free, keyless. Two lenses:+// ?category=meme|stocks-ecosystem|ecosystem (default meme)+// ?sort=market_cap|volume|gainers|losers (default market_cap)+// Primary source is the CoinGecko category ("Robinhood Chain Meme" /+// "Robinhood Chain Stocks Ecosystem") — real price, market cap, 24h/7d change,+// and a 7-day sparkline per coin. No eligibility restriction: these are+// non-security tokens.++import { defineEndpoint } from '../../_lib/gateway.js';+import { rateLimited } from '../../_lib/http.js';+import { limits } from '../../_lib/rate-limit.js';+import { coingeckoCategory, asOf } from '../../_lib/robinhood.js';++const CACHE_CONTROL = 'public, max-age=45, s-maxage=45, stale-while-revalidate=60';+const CATEGORIES = {+ meme: 'robinhood-chain-meme',+ 'stocks-ecosystem': 'robinhood-chain-stocks-ecosystem',+ ecosystem: 'robinhood-ecosystem',+};++export default defineEndpoint({+ name: 'v1.robinhood.coins',+ 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 catKey = CATEGORIES[String(query.category || 'meme')] ? String(query.category || 'meme') : 'meme';+ const sort = String(query.sort || 'market_cap');+ const order = sort === 'volume' ? 'volume_desc' : 'market_cap_desc';+ const raw = await coingeckoCategory(CATEGORIES[catKey], { order, perPage: 100 });++ let coins = raw.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,+ marketCapRank: c.market_cap_rank ?? null,+ volume24hUsd: c.total_volume ?? null,+ priceChange24hPct: c.price_change_percentage_24h_in_currency ?? c.price_change_percentage_24h ?? null,+ priceChange7dPct: c.price_change_percentage_7d_in_currency ?? null,+ sparkline7d: Array.isArray(c.sparkline_in_7d?.price) ? c.sparkline_in_7d.price : null,+ ath: c.ath ?? null,+ athChangePct: c.ath_change_percentage ?? null,+ }));++ if (sort === 'gainers') coins.sort((a, b) => (b.priceChange24hPct ?? -Infinity) - (a.priceChange24hPct ?? -Infinity));+ else if (sort === 'losers') coins.sort((a, b) => (a.priceChange24hPct ?? Infinity) - (b.priceChange24hPct ?? Infinity));++ res.setHeader('cache-control', CACHE_CONTROL);+ return {+ coins,+ count: coins.length,+ category: catKey,+ categoryLabel: { meme: 'Robinhood Chain Meme', 'stocks-ecosystem': 'Robinhood Chain Stocks Ecosystem', ecosystem: 'Robinhood Ecosystem' }[catKey],+ sort,+ source: 'coingecko',+ asOf: asOf(),+ };+ },+});diff --git a/api/v1/robinhood/launches.js b/api/v1/robinhood/launches.jsnew file mode 100644index 000000000..a0c5e3b5d--- /dev/null+++ b/api/v1/robinhood/launches.js@@ -0,0 +1,63 @@+// GET /api/v1/robinhood/launches — recent launchpad activity on Robinhood Chain.+//+// Free, keyless. Newest token launches from the NOXA (instant Uniswap v3) and+// The Odyssey (bonding-curve) launchpads, read from Blockscout's decoded-log+// API (TokenLaunched / TokenCreated), then enriched with DexScreener market+// data where a pool already exists. Newest first.++import { defineEndpoint } from '../../_lib/gateway.js';+import { rateLimited } from '../../_lib/http.js';+import { limits } from '../../_lib/rate-limit.js';+import { recentLaunches, dexSnapshot, BLOCKSCOUT_BASE, asOf } from '../../_lib/robinhood.js';++const CACHE_CONTROL = 'public, max-age=30, s-maxage=30, stale-while-revalidate=45';++export default defineEndpoint({+ name: 'v1.robinhood.launches',+ 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 limit = Math.min(60, Math.max(1, Number(query.limit) || 40));+ const launches = await recentLaunches({ limit });+ const dex = await dexSnapshot(launches.map((l) => l.token));++ const enriched = launches.map((l) => {+ const pair = dex[l.token.toLowerCase()] || null;+ return {+ launchpad: l.launchpad,+ type: l.type,+ token: l.token,+ deployer: l.deployer,+ block: l.block,+ txHash: l.txHash,+ timestamp: l.timestamp,+ symbol: pair?.baseToken?.symbol || null,+ name: pair?.baseToken?.name || null,+ priceUsd: pair?.priceUsd != null ? Number(pair.priceUsd) : null,+ marketCapUsd: pair?.marketCap ?? null,+ liquidityUsd: pair?.liquidity?.usd ?? null,+ volume24hUsd: pair?.volume?.h24 ?? null,+ hasMarket: Boolean(pair),+ links: {+ token: `${BLOCKSCOUT_BASE}/token/${l.token}`,+ tx: l.txHash ? `${BLOCKSCOUT_BASE}/tx/${l.txHash}` : null,+ },+ };+ });++ res.setHeader('cache-control', CACHE_CONTROL);+ return {+ launches: enriched,+ count: enriched.length,+ launchpads: [+ { name: 'NOXA', style: 'instant', url: 'https://fun.noxa.fi' },+ { name: 'The Odyssey', style: 'bonding-curve', url: 'https://theodyssey.fun' },+ ],+ source: 'blockscout (on-chain logs) + dexscreener',+ asOf: asOf(),+ };+ },+});diff --git a/api/v1/robinhood/stocks-detail.js b/api/v1/robinhood/stocks-detail.jsnew file mode 100644index 000000000..c1c0a1a65--- /dev/null+++ b/api/v1/robinhood/stocks-detail.js@@ -0,0 +1,100 @@+// GET /api/v1/robinhood/stocks-detail?symbol=AAPL — one Stock Token in depth.+//+// Free, keyless. Chainlink NAV (current + recent round history), all DEX pairs,+// premium/discount, uiMultiplier, holders + recent transfers (Blockscout), feed+// metadata, and contract links. Display-only — carries the eligibility+// disclosure; the acquisition gate lives on the purchase flow, never here.++import { defineEndpoint, fail } from '../../_lib/gateway.js';+import { rateLimited } from '../../_lib/http.js';+import { limits } from '../../_lib/rate-limit.js';+import {+ findStock,+ chainlinkSnapshot,+ dexPairsForToken,+ feedRoundHistory,+ blockscoutToken,+ blockscoutHolders,+ blockscoutTransfers,+ premiumPct,+ BLOCKSCOUT_BASE,+ asOf,+} from '../../_lib/robinhood.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. Data is display-only.';++export default defineEndpoint({+ name: 'v1.robinhood.stocks-detail',+ 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 symbol = String(query.symbol || '').trim();+ if (!symbol) fail(400, 'validation_error', 'pass ?symbol=<ticker>, e.g. ?symbol=AAPL');+ const token = findStock(symbol);+ if (!token) fail(404, 'not_found', `no Robinhood Stock Token with symbol "${symbol}"`);++ const addrLc = token.address.toLowerCase();+ const [snap, pairs, navHistory, bsToken, holders, transfers] = await Promise.all([+ chainlinkSnapshot(),+ dexPairsForToken(token.address),+ token.feed ? feedRoundHistory(token.feed, 24) : Promise.resolve([]),+ blockscoutToken(token.address),+ blockscoutHolders(token.address, 25),+ blockscoutTransfers(token.address, 25),+ ]);++ const feed = snap[addrLc] || null;+ const best = pairs[0] || null;+ const navPrice = feed?.priceUsd ?? null;+ const dexPrice = best?.priceUsd != null ? Number(best.priceUsd) : null;++ res.setHeader('cache-control', CACHE_CONTROL);+ return {+ symbol: token.symbol,+ name: token.name,+ address: token.address,+ decimals: token.decimals,+ nav: {+ feed: token.feed || null,+ priceUsd: navPrice,+ updatedAt: feed?.updatedAt ?? null,+ decimals: 8,+ history: navHistory,+ },+ dex: {+ priceUsd: dexPrice,+ premiumPct: premiumPct(dexPrice, navPrice),+ pairs: pairs.map((p) => ({+ dexId: p.dexId,+ pairAddress: p.pairAddress,+ quoteSymbol: p.quoteToken?.symbol ?? null,+ priceUsd: p.priceUsd != null ? Number(p.priceUsd) : null,+ liquidityUsd: p.liquidity?.usd ?? null,+ volume24hUsd: p.volume?.h24 ?? null,+ priceChange: p.priceChange || null,+ url: p.url || null,+ })),+ },+ uiMultiplier: feed?.uiMultiplier ?? token.uiMultiplierAtGeneration ?? null,+ totalSupply: feed?.totalSupply ?? null,+ holdersCount: bsToken?.holders_count != null ? Number(bsToken.holders_count) : null,+ circulatingMarketCapUsd: bsToken?.circulating_market_cap != null ? Number(bsToken.circulating_market_cap) : null,+ iconUrl: bsToken?.icon_url || null,+ holders,+ recentTransfers: transfers,+ links: {+ explorer: `${BLOCKSCOUT_BASE}/token/${token.address}`,+ feed: token.feed ? `${BLOCKSCOUT_BASE}/address/${token.feed}` : null,+ dex: best?.url || null,+ },+ disclosure: DISCLOSURE,+ source: 'chainlink (on-chain) + dexscreener + blockscout',+ asOf: asOf(),+ };+ },+});diff --git a/api/v1/robinhood/stocks.js b/api/v1/robinhood/stocks.jsnew file mode 100644index 000000000..6f183d5d8--- /dev/null+++ b/api/v1/robinhood/stocks.js@@ -0,0 +1,87 @@+// GET /api/v1/robinhood/stocks — the 24/7 tokenized-equity board.+//+// Free, keyless. For every Stock Token in the registry: Chainlink NAV price+// (one on-chain multicall — the anti-fan-out snapshot, not 95 eth_calls), the+// deepest DEX mid price (DexScreener, batched 30 addresses/call), the+// premium/discount between them, uiMultiplier, 24h DEX volume + liquidity.+//+// Legal line: Stock Tokens are tokenized debt securities (issuer: Robinhood+// Assets (Jersey) Ltd), not offered/sold to US persons. Displaying data is+// unrestricted — this endpoint is display-only. The eligibility gate lives on+// any acquisition flow, never here.++import { defineEndpoint } from '../../_lib/gateway.js';+import { rateLimited } from '../../_lib/http.js';+import { limits } from '../../_lib/rate-limit.js';+import {+ stockRegistry,+ chainlinkSnapshot,+ dexSnapshot,+ premiumPct,+ asOf,+} from '../../_lib/robinhood.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. Data is display-only.';++export default defineEndpoint({+ name: 'v1.robinhood.stocks',+ 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 reg = stockRegistry();+ const addresses = reg.tokens.map((t) => t.address);+ const [nav, dex] = await Promise.all([chainlinkSnapshot(), dexSnapshot(addresses)]);++ let 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,+ address: t.address,+ decimals: t.decimals,+ feed: t.feed || null,+ navPriceUsd: navPrice,+ navUpdatedAt: feed?.updatedAt ?? null,+ dexPriceUsd: dexPrice,+ dexId: pair?.dexId ?? null,+ pairAddress: pair?.pairAddress ?? null,+ quoteSymbol: pair?.quoteToken?.symbol ?? null,+ premiumPct: premiumPct(dexPrice, navPrice),+ uiMultiplier: feed?.uiMultiplier ?? t.uiMultiplierAtGeneration ?? null,+ volume24hUsd: pair?.volume?.h24 ?? null,+ liquidityUsd: pair?.liquidity?.usd ?? null,+ priceChange24hPct: pair?.priceChange?.h24 ?? null,+ };+ });++ // Optional filters/sorting for the board.+ const q = String(query.q || '').trim().toLowerCase();+ if (q) rows = rows.filter((r) => r.symbol.toLowerCase().includes(q) || r.name.toLowerCase().includes(q));+ const sort = String(query.sort || 'symbol');+ const dir = query.dir === 'asc' ? 1 : -1;+ const key = { volume: 'volume24hUsd', liquidity: 'liquidityUsd', premium: 'premiumPct', price: 'navPriceUsd', symbol: 'symbol' }[sort] || 'symbol';+ rows.sort((a, b) => {+ if (key === 'symbol') return a.symbol.localeCompare(b.symbol) * (query.dir === 'desc' ? -1 : 1);+ return ((b[key] ?? -Infinity) - (a[key] ?? -Infinity)) * dir;+ });++ res.setHeader('cache-control', CACHE_CONTROL);+ return {+ stocks: rows,+ count: rows.length,+ feedCount: reg.feedCount,+ disclosure: DISCLOSURE,+ source: 'chainlink (on-chain) + dexscreener',+ asOf: asOf(),+ };+ },+});diff --git a/robinhood/hood-api/src/lib/pmap.ts b/robinhood/hood-api/src/lib/pmap.tsnew file mode 100644index 000000000..a9f13cf70--- /dev/null+++ b/robinhood/hood-api/src/lib/pmap.ts@@ -0,0 +1,13 @@+/** Map over items with bounded concurrency, preserving input order. */+export async function pMap<T, R>(items: T[], limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]> {+ const results = new Array<R>(items.length)+ let cursor = 0+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {+ while (cursor < items.length) {+ const i = cursor+++ results[i] = await fn(items[i] as T, i)+ }+ })+ await Promise.all(workers)+ return results+}diff --git a/robinhood/hood-api/src/services/coins.ts b/robinhood/hood-api/src/services/coins.tsnew file mode 100644index 000000000..fd9275163--- /dev/null+++ b/robinhood/hood-api/src/services/coins.ts@@ -0,0 +1,135 @@+import { getAddress, isAddress, type Address } from 'viem'+import { getRecentLaunches, type Launch } from 'hoodchain'+import { cached, TTL } from '../lib/cache.js'+import { ApiError } from '../lib/errors.js'+import { pMap } from '../lib/pmap.js'+import { SOURCE, withMeta } from '../lib/response.js'+import { mainnetClient } from '../upstreams/rpc.js'+import { getBulkDexStats, getDexStats } from '../upstreams/dex.js'+import * as blockscout from '../upstreams/blockscout.js'+import { getChain, ethPriceUsd } from './chain.js'+import { COINS_LOOKBACK } from './launches.js'++/**+ * Memecoins launched via NOXA and The Odyssey. The universe is the set of+ * recently-launched tokens; graduation status is derived on-chain (a token+ * with a live Uniswap v3 pool has graduated/lists instantly; one without is+ * still on its bonding curve).+ */++export async function listCoins(opts: { limit?: number } = {}) {+ const limit = Math.min(Math.max(opts.limit ?? 25, 1), 60)+ return cached(`coins:list:${limit}`, TTL.coins, async () => {+ const client = mainnetClient()+ const [chain, eth] = await Promise.all([getChain(), ethPriceUsd()])+ const latest = BigInt(chain.blockHeight)+ const msPerBlock = chain.avgBlockTimeMs ?? 100++ const launches = await getRecentLaunches(client, { lookbackBlocks: COINS_LOOKBACK })+ // Newest first, unique by token, capped.+ const seen = new Set<string>()+ const unique: Launch[] = []+ for (const l of launches.sort((a, b) => (a.blockNumber < b.blockNumber ? 1 : -1))) {+ const k = l.token.toLowerCase()+ if (seen.has(k)) continue+ seen.add(k)+ unique.push(l)+ if (unique.length >= limit) break+ }++ const dex = await getBulkDexStats(client, unique.map((l) => l.token as Address), eth)+ const holders = await pMap(unique, 6, async (l) => {+ const c = await blockscout.getTokenCounters(l.token).catch(() => null)+ return c ? Number(c.token_holders_count) : null+ })++ const coins = unique.map((l, i) => {+ const d = dex.get(l.token.toLowerCase())+ const graduated = Boolean(d?.pool) || l.pool !== null+ const ageSeconds = latest > l.blockNumber ? Math.round((Number(latest - l.blockNumber) * msPerBlock) / 1000) : 0+ return {+ token: l.token,+ launchpad: l.launchpad,+ creator: l.creator,+ status: graduated ? ('graduated' as const) : ('bonding' as const),+ dexPriceUsd: d?.priceUsd ?? null,+ liquidityUsd: d?.liquidityUsd ?? null,+ pool: d?.pool ?? l.pool ?? null,+ feeTier: d?.feeTier ?? null,+ holders: holders[i] ?? null,+ ageSeconds,+ launchBlock: l.blockNumber.toString(),+ links: { token: blockscout.tokenLink(l.token), creator: blockscout.addressLink(l.creator) },+ }+ })++ return withMeta(+ { count: coins.length, lookbackBlocks: COINS_LOOKBACK.toString(), coins },+ [SOURCE.noxa, SOURCE.odyssey, SOURCE.uniswap, SOURCE.blockscout],+ )+ })+}++export async function getCoinDetail(addressRaw: string) {+ if (!isAddress(addressRaw)) {+ throw ApiError.badRequest(`"${addressRaw}" is not a valid contract address.`, 'invalid_address')+ }+ const address = getAddress(addressRaw)+ return cached(`coins:detail:${address.toLowerCase()}`, TTL.coinDetail, async () => {+ const client = mainnetClient()+ const [chain, eth] = await Promise.all([getChain(), ethPriceUsd()])+ const latest = BigInt(chain.blockHeight)+ const msPerBlock = chain.avgBlockTimeMs ?? 100++ const [token, counters, dex, launches] = await Promise.all([+ blockscout.getToken(address),+ blockscout.getTokenCounters(address).catch(() => null),+ getDexStats(client, address, eth).catch(() => null),+ getRecentLaunches(client, { lookbackBlocks: 1_500_000n }).catch(() => [] as Launch[]),+ ])++ const launch = launches.find((l) => l.token.toLowerCase() === address.toLowerCase()) ?? null+ const graduated = Boolean(dex?.pool) || Boolean(launch?.pool)+ const ageSeconds =+ launch && latest > launch.blockNumber+ ? Math.round((Number(latest - launch.blockNumber) * msPerBlock) / 1000)+ : null++ return withMeta(+ {+ address,+ name: token?.name ?? null,+ symbol: token?.symbol ?? null,+ decimals: token?.decimals ? Number(token.decimals) : null,+ totalSupply: token?.total_supply ?? null,+ status: graduated ? 'graduated' : launch ? 'bonding' : 'unknown',+ launch: launch+ ? {+ launchpad: launch.launchpad,+ creator: launch.creator,+ launchBlock: launch.blockNumber.toString(),+ transactionHash: launch.transactionHash,+ ageSeconds,+ tx: blockscout.txLink(launch.transactionHash),+ }+ : null,+ dex: dex+ ? {+ priceUsd: dex.priceUsd,+ pool: dex.pool,+ feeTier: dex.feeTier,+ quoteAsset: dex.quoteAsset,+ liquidityUsd: dex.liquidityUsd,+ }+ : null,+ holders: counters ? Number(counters.token_holders_count) : null,+ transfersCount: counters ? Number(counters.transfers_count) : null,+ links: {+ token: blockscout.tokenLink(address),+ pool: dex?.pool ? blockscout.addressLink(dex.pool) : null,+ },+ },+ [SOURCE.blockscout, SOURCE.uniswap, SOURCE.rpc],+ )+ })+}diff --git a/robinhood/hood-api/src/services/launches.ts b/robinhood/hood-api/src/services/launches.tsnew file mode 100644index 000000000..80a7b56a9--- /dev/null+++ b/robinhood/hood-api/src/services/launches.ts@@ -0,0 +1,78 @@+import { type Address } from 'viem'+import { getRecentLaunches, type Launch, type LaunchpadName } from 'hoodchain'+import { cached, TTL } from '../lib/cache.js'+import { SOURCE, withMeta } from '../lib/response.js'+import { mainnetClient } from '../upstreams/rpc.js'+import * as blockscout from '../upstreams/blockscout.js'+import { getChain } from './chain.js'++/** Default lookback for launch scans (~1h at 100ms blocks). */+const DEFAULT_LOOKBACK = 30_000n+/** Extended lookback for the coin universe (~7h). */+export const COINS_LOOKBACK = 200_000n++export interface EnrichedLaunch {+ launchpad: LaunchpadName+ token: Address+ creator: Address+ pool: Address | null+ launchBlock: string+ ageSeconds: number | null+ transactionHash: string+ links: { token: string; creator: string; tx: string }+}++async function ageFromBlock(launchBlock: bigint): Promise<number | null> {+ const chain = await getChain()+ const latest = BigInt(chain.blockHeight)+ const msPerBlock = chain.avgBlockTimeMs ?? 100+ if (latest <= launchBlock) return 0+ return Math.round((Number(latest - launchBlock) * msPerBlock) / 1000)+}++export function enrich(l: Launch, latest: bigint, msPerBlock: number): EnrichedLaunch {+ const ageSeconds = latest > l.blockNumber ? Math.round((Number(latest - l.blockNumber) * msPerBlock) / 1000) : 0+ return {+ launchpad: l.launchpad,+ token: l.token,+ creator: l.creator,+ pool: l.pool,+ launchBlock: l.blockNumber.toString(),+ ageSeconds,+ transactionHash: l.transactionHash,+ links: {+ token: blockscout.tokenLink(l.token),+ creator: blockscout.addressLink(l.creator),+ tx: blockscout.txLink(l.transactionHash),+ },+ }+}++/** Recent + live launchpad activity (NOXA, The Odyssey). */+export async function getLaunches(opts: { lookbackBlocks?: bigint; launchpad?: LaunchpadName; limit?: number } = {}) {+ const lookback = opts.lookbackBlocks ?? DEFAULT_LOOKBACK+ const limit = Math.min(Math.max(opts.limit ?? 50, 1), 200)+ const key = `launches:${lookback}:${opts.launchpad ?? 'all'}:${limit}`+ return cached(key, TTL.launches, async () => {+ const client = mainnetClient()+ const chain = await getChain()+ const latest = BigInt(chain.blockHeight)+ const msPerBlock = chain.avgBlockTimeMs ?? 100++ const launches = await getRecentLaunches(client, { lookbackBlocks: lookback, launchpad: opts.launchpad })+ const sorted = launches.sort((a, b) => (a.blockNumber < b.blockNumber ? 1 : -1)).slice(0, limit)+ const rows = sorted.map((l) => enrich(l, latest, msPerBlock))++ return withMeta(+ {+ count: rows.length,+ lookbackBlocks: lookback.toString(),+ launchpads: opts.launchpad ? [opts.launchpad] : ['noxa', 'odyssey'],+ launches: rows,+ },+ [SOURCE.noxa, SOURCE.odyssey, SOURCE.rpc],+ )+ })+}++export { ageFromBlock }diff --git a/robinhood/hood-api/src/services/portfolio.ts b/robinhood/hood-api/src/services/portfolio.tsnew file mode 100644index 000000000..4539481ea--- /dev/null+++ b/robinhood/hood-api/src/services/portfolio.ts@@ -0,0 +1,59 @@+import { getAddress, isAddress, type Address } from 'viem'+import { getPortfolio } from 'hoodchain'+import { cached, TTL } from '../lib/cache.js'+import { ApiError } from '../lib/errors.js'+import { SOURCE, withMeta } from '../lib/response.js'+import { mainnetClient } from '../upstreams/rpc.js'+import * as blockscout from '../upstreams/blockscout.js'++/**+ * Multiplier-correct portfolio valuation for any address (paid).+ *+ * Two numbers per position that generic trackers get wrong:+ * - USD value = balance × Chainlink price (the feed is already+ * multiplier-adjusted, so the multiplier is NOT applied to value).+ * - Share equivalent = balance × uiMultiplier ÷ 1e18 (raw balances understate+ * holdings after splits/reinvested dividends).+ *+ * `basis` documents the valuation model. True realized/unrealized PnL requires+ * per-trade entry prices, which are not derivable from balances alone; those+ * fields are surfaced as `null` with an explicit note rather than guessed.+ */+export async function getPortfolioValuation(addressRaw: string) {+ if (!isAddress(addressRaw)) {+ throw ApiError.badRequest(`"${addressRaw}" is not a valid address.`, 'invalid_address')+ }+ const address = getAddress(addressRaw)+ return cached(`portfolio:${address.toLowerCase()}`, TTL.portfolio, async () => {+ const p = await getPortfolio(mainnetClient(), address as Address)+ return withMeta(+ {+ owner: address,+ totalUsd: p.totalUsd,+ positionCount: p.positions.length,+ unpricedSymbols: p.unpricedSymbols,+ positions: p.positions.map((pos) => ({+ symbol: pos.symbol,+ address: pos.address,+ balance: pos.balance.toString(),+ balanceTokens: pos.balanceTokens,+ uiMultiplier: (Number(pos.uiMultiplier) / 1e18).toString(),+ shareEquivalent: pos.shareEquivalent,+ priceUsd: pos.quote?.priceUsd ?? null,+ valueUsd: pos.valueUsd,+ costBasisUsd: null,+ unrealizedPnlUsd: null,+ link: blockscout.tokenLink(pos.address),+ })),+ basis: {+ valuation: 'balanceTokens * chainlinkPriceUsd (feed is multiplier-adjusted; multiplier not re-applied to value)',+ shareEquivalent: 'balance * uiMultiplier / 1e18',+ costBasis:+ 'null — realized/unrealized PnL needs per-trade entry prices, which balances alone do not provide. ' ++ 'Feed a trade history to compute PnL client-side using priceUsd as the current mark.',+ },+ },+ [SOURCE.registry, SOURCE.chainlink, SOURCE.rpc],+ )+ })+}diff --git a/robinhood/hood-api/src/services/stocks.ts b/robinhood/hood-api/src/services/stocks.tsnew file mode 100644index 000000000..d5dd797a4--- /dev/null+++ b/robinhood/hood-api/src/services/stocks.ts@@ -0,0 +1,194 @@+import { formatUnits, type Address } from 'viem'+import {+ getQuote,+ getStockToken,+ listStockTokens,+ MAINNET_EXPLORER_URL,+ type StockQuote,+} from 'hoodchain'+import { cached, TTL } from '../lib/cache.js'+import { ApiError, toApiError } from '../lib/errors.js'+import { SOURCE, withMeta } from '../lib/response.js'+import { mainnetClient } from '../upstreams/rpc.js'+import { ethPriceUsd } from './chain.js'+import { getBulkDexStats, getCandles, getDexStats, type DexStats } from '../upstreams/dex.js'+import * as blockscout from '../upstreams/blockscout.js'++function premium(dexUsd: number | null, chainlinkUsd: number | null): number | null {+ if (dexUsd === null || chainlinkUsd === null || chainlinkUsd === 0) return null+ return (dexUsd - chainlinkUsd) / chainlinkUsd+}++async function safeQuote(symbol: string): Promise<StockQuote | null> {+ try {+ return await getQuote(mainnetClient(), symbol)+ } catch {+ return null // stale/absent feed -> unpriced, not an error+ }+}++function multiplierFloat(scaled: string): number {+ return Number(formatUnits(BigInt(scaled), 18))+}++/** All Stock Tokens with Chainlink price, DEX mid, premium/discount, liquidity, multiplier. */+export async function listStocks() {+ return cached('stocks:list', TTL.stocks, async () => {+ const client = mainnetClient()+ const tokens = listStockTokens()+ const priced = tokens.filter((t) => t.feed !== null)++ const [quotes, eth] = await Promise.all([+ Promise.all(priced.map((t) => safeQuote(t.symbol))),+ ethPriceUsd(),+ ])+ const quoteBySymbol = new Map<string, StockQuote | null>()+ priced.forEach((t, i) => quoteBySymbol.set(t.symbol, quotes[i] ?? null))++ const dex = await getBulkDexStats(client, tokens.map((t) => t.address as Address), eth)++ const rows = tokens.map((t) => {+ const q = quoteBySymbol.get(t.symbol) ?? null+ const d = dex.get(t.address.toLowerCase()) ?? emptyDex()+ return {+ symbol: t.symbol,+ name: t.name,+ address: t.address,+ decimals: t.decimals,+ chainlinkPriceUsd: q?.priceUsd ?? null,+ feedUpdatedAt: q ? new Date(q.updatedAt * 1000).toISOString() : null,+ dexPriceUsd: d.priceUsd,+ premiumDiscount: premium(d.priceUsd, q?.priceUsd ?? null),+ uiMultiplier: multiplierFloat(t.uiMultiplierAtGeneration),+ liquidityUsd: d.liquidityUsd,+ pool: d.pool,+ feeTier: d.feeTier,+ hasFeed: t.feed !== null,+ }+ })++ const withDex = rows.filter((r) => r.dexPriceUsd !== null).length+ return withMeta(+ {+ count: rows.length,+ pricedCount: priced.length,+ dexPricedCount: withDex,+ stocks: rows,+ note:+ 'Per-token 24h DEX volume and OHLCV candles are on the detail endpoint (/v1/stocks/{symbol}); ' ++ 'reconstructing them for every token per request would hammer the public RPC.',+ },+ [SOURCE.registry, SOURCE.chainlink, SOURCE.uniswap],+ )+ })+}++function emptyDex(): DexStats {+ return { priceUsd: null, pool: null, feeTier: null, quoteAsset: null, liquidityUsd: null }+}++/** One Stock Token in depth: price, DEX stats, 24h volume, holders, feed + links. */+export async function getStockDetail(symbolRaw: string, interval: string) {+ const token = (() => {+ try {+ return getStockToken(symbolRaw)+ } catch {+ throw ApiError.unknownSymbol(symbolRaw)+ }+ })()++ return cached(`stocks:detail:${token.symbol}:${interval}`, TTL.stockDetail, async () => {+ const client = mainnetClient()+ const eth = await ethPriceUsd()++ const [quote, dex, counters, candles] = await Promise.all([+ safeQuote(token.symbol),+ getDexStats(client, token.address as Address, eth).catch(() => emptyDex()),+ blockscout.getTokenCounters(token.address).catch(() => null),+ getCandles(client, token.address as Address, eth, { interval, lookbackBlocks: 900_000n }).catch(() => null),+ ])++ const source = [SOURCE.registry, SOURCE.chainlink, SOURCE.uniswap]+ if (counters) source.push(SOURCE.blockscout)++ return withMeta(+ {+ symbol: token.symbol,+ name: token.name,+ address: token.address,+ decimals: token.decimals,+ uiMultiplier: multiplierFloat(token.uiMultiplierAtGeneration),+ chainlink: quote+ ? {+ priceUsd: quote.priceUsd,+ feed: quote.feed,+ roundId: quote.roundId.toString(),+ updatedAt: new Date(quote.updatedAt * 1000).toISOString(),+ ageSeconds: quote.ageSeconds,+ }+ : null,+ dex: {+ priceUsd: dex.priceUsd,+ pool: dex.pool,+ feeTier: dex.feeTier,+ quoteAsset: dex.quoteAsset,+ liquidityUsd: dex.liquidityUsd,+ volume24hUsd: candles?.volumeUsd ?? null,+ },+ premiumDiscount: premium(dex.priceUsd, quote?.priceUsd ?? null),+ candles: candles+ ? { interval: candles.interval, fromBlock: candles.fromBlock, toBlock: candles.toBlock, series: candles.candles }+ : null,+ holders: counters ? Number(counters.token_holders_count) : null,+ transfersCount: counters ? Number(counters.transfers_count) : null,+ links: {+ token: blockscout.tokenLink(token.address),+ feed: token.feed ? `${MAINNET_EXPLORER_URL}/address/${token.feed}` : null,+ pool: dex.pool ? blockscout.addressLink(dex.pool) : null,+ },+ },+ source,+ )+ })+}++/** Deep OHLCV history for one token (paid endpoint). */+export async function getStockHistory(symbolRaw: string, interval: string, lookbackBlocks: bigint) {+ const token = (() => {+ try {+ return getStockToken(symbolRaw)+ } catch {+ throw ApiError.unknownSymbol(symbolRaw)+ }+ })()++ return cached(`stocks:history:${token.symbol}:${interval}:${lookbackBlocks}`, TTL.history, async () => {+ const client = mainnetClient()+ const eth = await ethPriceUsd()+ try {+ const candles = await getCandles(client, token.address as Address, eth, { interval, lookbackBlocks })+ if (!candles) {+ throw ApiError.notFound(+ `${token.symbol} has no Uniswap v3 pool with trade history on Robinhood Chain yet.`,+ 'no_dex_history',+ )+ }+ return withMeta(+ {+ symbol: token.symbol,+ address: token.address,+ pool: candles.pool,+ quoteAsset: candles.quoteAsset,+ interval: candles.interval,+ fromBlock: candles.fromBlock,+ toBlock: candles.toBlock,+ volumeUsd: candles.volumeUsd,+ candles: candles.candles,+ },+ [SOURCE.uniswap, SOURCE.rpc],+ )+ } catch (err) {+ throw toApiError(err)+ }+ })+}diff --git a/robinhood/hood-api/src/upstreams/dex.ts b/robinhood/hood-api/src/upstreams/dex.tsindex abb346cdc..f085f2e89 100644--- a/robinhood/hood-api/src/upstreams/dex.ts+++ b/robinhood/hood-api/src/upstreams/dex.ts@@ -135,6 +135,106 @@ export async function getDexStats(}}+const ZERO = '0x0000000000000000000000000000000000000000'++/**+ * Bulk DEX stats for many tokens in a bounded number of RPC round-trips:+ * one multicall discovers every token/USDG and token/WETH pool across fee+ * tiers, one multicall reads their reserves, then a mid-price is quoted only+ * for tokens that actually have a pool. This is what list endpoints use — it+ * never does per-token pool discovery.+ */+export async function getBulkDexStats(+ client: HoodClient,+ tokens: Address[],+ ethPriceUsd: number | null,+): Promise<Map<string, DexStats>> {+ const out = new Map<string, DexStats>()+ for (const t of tokens) {+ out.set(t.toLowerCase(), { priceUsd: null, pool: null, feeTier: null, quoteAsset: null, liquidityUsd: null })+ }+ if (tokens.length === 0) return out++ const quotes: Array<{ quote: 'USDG' | 'WETH'; quoteToken: Address }> = [+ { quote: 'USDG', quoteToken: USDG },+ { quote: 'WETH', quoteToken: WETH },+ ]+ const probes = tokens.flatMap((token) =>+ V3_FEE_TIERS.flatMap((fee) => quotes.map((q) => ({ token, fee, quote: q.quote, quoteToken: q.quoteToken }))),+ )++ const poolResults = await client.public.multicall({+ contracts: probes.map((p) => ({+ address: FACTORY,+ abi: uniswapV3FactoryAbi,+ functionName: 'getPool' as const,+ args: [p.token, p.quoteToken, p.fee] as const,+ })),+ allowFailure: true,+ })++ const found: Array<{ token: Address; pool: Address; fee: number; quote: 'USDG' | 'WETH'; quoteToken: Address }> = []+ poolResults.forEach((r, i) => {+ if (r.status === 'success' && r.result && (r.result as Address) !== ZERO) {+ const p = probes[i]!+ found.push({ token: p.token, pool: r.result as Address, fee: p.fee, quote: p.quote, quoteToken: p.quoteToken })+ }+ })+ if (found.length === 0) return out++ const reserves = await client.public.multicall({+ contracts: found.map((f) => ({+ address: f.quoteToken,+ abi: erc20Abi,+ functionName: 'balanceOf' as const,+ args: [f.pool] as const,+ })),+ allowFailure: false,+ })++ // Deepest pool per token by USD-valued quote reserve.+ const bestPerToken = new Map<string, { pool: Address; fee: number; quote: 'USDG' | 'WETH'; quoteBalUsd: number }>()+ found.forEach((f, i) => {+ const dec = f.quote === 'USDG' ? 6 : 18+ const amt = Number(formatUnits(reserves[i] as bigint, dec))+ const usd = f.quote === 'USDG' ? amt : amt * (ethPriceUsd ?? 0)+ const key = f.token.toLowerCase()+ const prev = bestPerToken.get(key)+ if (!prev || usd > prev.quoteBalUsd) {+ bestPerToken.set(key, { pool: f.pool, fee: f.fee, quote: f.quote, quoteBalUsd: usd })+ }+ })++ // Mid price for each token that has a pool (concurrent; viem batches the quoter calls).+ const priced = [...bestPerToken.keys()]+ const prices = await Promise.all(+ priced.map(async (key) => {+ try {+ const q = await quoteSwap(client, {+ tokenIn: key as Address,+ tokenOut: USDG,+ amountIn: parseUnits('1', 18),+ })+ return [key, Number(formatUnits(q.amountOut, 6))] as const+ } catch {+ return [key, null] as const+ }+ }),+ )+ const priceMap = new Map(prices)++ for (const [key, best] of bestPerToken) {+ out.set(key, {+ priceUsd: priceMap.get(key) ?? null,+ pool: best.pool,+ feeTier: best.fee,+ quoteAsset: best.quote,+ liquidityUsd: best.quoteBalUsd > 0 ? best.quoteBalUsd * 2 : null,+ })+ }+ return out+}+export interface Candle {/** Bucket start, unix seconds. */t: numberdiff --git a/robinhood/hood-cli/src/commands/coins.ts b/robinhood/hood-cli/src/commands/coins.tsnew file mode 100644index 000000000..99c9b207f--- /dev/null+++ b/robinhood/hood-cli/src/commands/coins.ts@@ -0,0 +1,167 @@+import { Command } from 'commander'+import { formatEther, type Address } from 'viem'+import {+ getRecentLaunches,+ erc20Abi,+ ODYSSEY_ADDRESSES,+ odysseyTradedEvent,+ type Launch,+} from 'hoodchain'+import { runWith } from '../action.js'+import type { Context } from '../context.js'+import { printResult } from '../output.js'+import { renderTable, type Column } from '../ui/table.js'+import { withSpinner } from '../ui/spinner.js'+import { accent, bold, dim, gray, green } from '../ui/ansi.js'+import { addr, num } from '../format.js'+import { usageError } from '../errors.js'+import { pMap } from '../pmap.js'++const ODYSSEY_FACTORIES: Address[] = [+ ODYSSEY_ADDRESSES.bondingCurveFactory,+ ODYSSEY_ADDRESSES.reflectionFactory,+ ODYSSEY_ADDRESSES.instantFactory,+]++interface CoinRow {+ token: string+ symbol: string+ creator: string | null+ pool: string | null+ block: string+ trades: number | null+ volumeEth: number | null+}++export function coinsCommand(): Command {+ return new Command('coins')+ .description('Memecoin screener — newest or trending launches')+ .option('--new', 'newest launches (default)', false)+ .option('--trending', 'rank by bonding-curve trade activity', false)+ .option('--lookback <blocks>', 'blocks to scan', '50000')+ .option('--limit <n>', 'rows to show', '20')+ .option('--names', 'resolve token symbols on-chain', false)+ .action((opts, command) =>+ runWith(command, async (ctx) => {+ await coins(ctx, opts)+ }),+ )+}++interface CoinsOpts {+ new: boolean+ trending: boolean+ lookback: string+ limit: string+ names: boolean+}++async function coins(ctx: Context, opts: CoinsOpts): Promise<void> {+ if (ctx.network !== 'mainnet') throw usageError('The launchpads live on mainnet — run without --network testnet.')+ const client = ctx.read()+ const limit = Math.max(1, Number(opts.limit) || 20)+ const lookback = BigInt(opts.lookback || '50000')+ const trending = opts.trending++ const rows = trending+ ? await withSpinner('Ranking by curve activity…', () => trendingRows(ctx, lookback, limit, opts.names))+ : await withSpinner('Fetching newest launches…', () => newRows(ctx, lookback, limit, opts.names))++ printResult(+ { network: ctx.network, mode: trending ? 'trending' : 'new', count: rows.length, coins: rows },+ () => renderScreener(rows, trending),+ ctx.json,+ )+}++async function newRows(ctx: Context, lookback: bigint, limit: number, names: boolean): Promise<CoinRow[]> {+ const launches = await getRecentLaunches(ctx.read(), { lookbackBlocks: lookback })+ const recent = launches.slice(-limit).reverse()+ return pMap(recent, (l) => launchToRow(ctx, l, names), names ? 8 : 1)+}++async function trendingRows(ctx: Context, lookback: bigint, limit: number, names: boolean): Promise<CoinRow[]> {+ const client = ctx.read()+ const latest = await client.public.getBlockNumber()+ const fromBlock = latest > lookback ? latest - lookback : 0n+ const chunk = 10_000n++ const agg = new Map<string, { trades: number; volume: bigint; lastBlock: bigint }>()+ for (let start = fromBlock; start <= latest; start += chunk) {+ const end = start + chunk - 1n > latest ? latest : start + chunk - 1n+ const logs = await client.public.getLogs({+ address: ODYSSEY_FACTORIES,+ event: odysseyTradedEvent,+ fromBlock: start,+ toBlock: end,+ })+ for (const log of logs) {+ const token = (log.args.token as Address).toLowerCase()+ const quote = (log.args.quoteAmount as bigint) ?? 0n+ const prev = agg.get(token) ?? { trades: 0, volume: 0n, lastBlock: 0n }+ prev.trades += 1+ prev.volume += quote+ if (log.blockNumber > prev.lastBlock) prev.lastBlock = log.blockNumber+ agg.set(token, prev)+ }+ }++ const ranked = [...agg.entries()]+ .map(([token, v]) => ({ token, ...v }))+ .sort((a, b) => (b.trades !== a.trades ? b.trades - a.trades : b.volume > a.volume ? 1 : -1))+ .slice(0, limit)++ return pMap(+ ranked,+ async (r): Promise<CoinRow> => ({+ token: r.token,+ symbol: names ? await symbolOf(ctx, r.token as Address) : '',+ creator: null,+ pool: null,+ block: r.lastBlock.toString(),+ trades: r.trades,+ volumeEth: Number(formatEther(r.volume)),+ }),+ names ? 8 : 1,+ )+}++async function launchToRow(ctx: Context, l: Launch, names: boolean): Promise<CoinRow> {+ return {+ token: l.token,+ symbol: names ? await symbolOf(ctx, l.token) : '',+ creator: l.creator,+ pool: l.pool,+ block: l.blockNumber.toString(),+ trades: null,+ volumeEth: null,+ }+}++function symbolOf(ctx: Context, token: Address): Promise<string> {+ return ctx+ .read()+ .public.readContract({ address: token, abi: erc20Abi, functionName: 'symbol' })+ .then((s) => String(s))+ .catch(() => '')+}++function renderScreener(rows: CoinRow[], trending: boolean): string {+ const header = `${accent('◈')} ${bold(trending ? 'Trending coins' : 'New coins')} ${dim('· ' + rows.length)}`+ if (rows.length === 0) {+ return `${header}\n${dim(trending ? 'No curve trades in the scanned window.' : 'No launches in the scanned window — widen --lookback.')}`+ }+ const columns: Column<CoinRow>[] = [+ { header: 'TOKEN', priority: 100, cell: (r) => (r.symbol ? bold(r.symbol) : gray(addr(r.token as Address))) },+ { header: 'ADDRESS', priority: 50, cell: (r) => gray(addr(r.token as Address)) },+ ]+ if (trending) {+ columns.push({ header: 'TRADES', align: 'right', priority: 95, cell: (r) => green(String(r.trades)) })+ columns.push({ header: 'VOL (ETH)', align: 'right', priority: 90, cell: (r) => num(r.volumeEth ?? 0, 4) })+ } else {+ columns.push({ header: 'CREATOR', priority: 40, cell: (r) => (r.creator ? gray(addr(r.creator as Address)) : dim('—')) })+ columns.push({ header: 'POOL', priority: 30, cell: (r) => (r.pool ? gray(addr(r.pool as Address)) : dim('curve')) })+ }+ columns.push({ header: 'BLOCK', align: 'right', priority: 20, cell: (r) => dim('#' + r.block) })+ return `${header}\n${renderTable(rows, columns)}`+}diff --git a/robinhood/hood-cli/src/commands/launches.ts b/robinhood/hood-cli/src/commands/launches.tsnew file mode 100644index 000000000..77d3d0afc--- /dev/null+++ b/robinhood/hood-cli/src/commands/launches.ts@@ -0,0 +1,141 @@+import { Command } from 'commander'+import { getRecentLaunches, watchLaunches, erc20Abi, type Launch, type LaunchpadName } from 'hoodchain'+import type { Address } from 'viem'+import { runWith } from '../action.js'+import type { Context } from '../context.js'+import { printResult } from '../output.js'+import { renderTable, type Column } from '../ui/table.js'+import { withSpinner } from '../ui/spinner.js'+import { liveRegion } from '../ui/live.js'+import { accent, bold, dim, gray, green } from '../ui/ansi.js'+import { addr } from '../format.js'+import { usageError } from '../errors.js'+import { pMap } from '../pmap.js'++interface LaunchRow {+ launchpad: LaunchpadName+ token: string+ symbol: string+ creator: string+ pool: string | null+ block: string+ tx: string+}++export function launchesCommand(): Command {+ return new Command('launches')+ .description('Recent memecoin launches from NOXA and The Odyssey')+ .option('--follow', 'stream new launches live', false)+ .option('--launchpad <name>', 'noxa | odyssey (default: both)')+ .option('--lookback <blocks>', 'blocks to scan for the snapshot', '30000')+ .option('--limit <n>', 'max rows in the snapshot', '25')+ .option('--names', 'resolve each token symbol on-chain', false)+ .action((opts, command) =>+ runWith(command, async (ctx) => {+ await launches(ctx, opts)+ }),+ )+}++interface LaunchesOpts {+ follow: boolean+ launchpad?: string+ lookback: string+ limit: string+ names: boolean+}++function validLaunchpad(v?: string): LaunchpadName | undefined {+ if (!v) return undefined+ if (v !== 'noxa' && v !== 'odyssey') throw usageError('--launchpad must be "noxa" or "odyssey".')+ return v+}++async function launches(ctx: Context, opts: LaunchesOpts): Promise<void> {+ const client = ctx.read()+ const launchpad = validLaunchpad(opts.launchpad)++ if (opts.follow) {+ if (ctx.network !== 'mainnet') throw usageError('Launch watching runs on mainnet (the launchpads are mainnet-only).')+ await follow(ctx, launchpad, opts.names)+ return+ }++ const raw = await withSpinner('Scanning launchpad logs…', () =>+ getRecentLaunches(client, { lookbackBlocks: BigInt(opts.lookback || '30000'), launchpad }),+ )+ const recent = raw.slice(-Math.max(1, Number(opts.limit) || 25)).reverse()+ const rows = await withSpinner('Building feed…', () =>+ pMap(recent, (l) => toRow(ctx, l, opts.names), opts.names ? 8 : 1),+ )++ printResult(+ { network: ctx.network, count: rows.length, launches: rows },+ () => renderFeed(rows, ctx.network),+ ctx.json,+ )+}++async function toRow(ctx: Context, l: Launch, resolveNames: boolean): Promise<LaunchRow> {+ let symbol = ''+ if (resolveNames) {+ symbol = await ctx+ .read()+ .public.readContract({ address: l.token, abi: erc20Abi, functionName: 'symbol' })+ .then((s) => String(s))+ .catch(() => '')+ }+ return {+ launchpad: l.launchpad,+ token: l.token,+ symbol,+ creator: l.creator,+ pool: l.pool,+ block: l.blockNumber.toString(),+ tx: l.transactionHash,+ }+}++async function follow(ctx: Context, launchpad: LaunchpadName | undefined, resolveNames: boolean): Promise<void> {+ const client = ctx.read()+ process.stderr.write(dim(`Watching ${launchpad ?? 'NOXA + Odyssey'} for new launches — Ctrl-C to stop\n`))+ const unwatch = watchLaunches(+ client,+ (l) => {+ void toRow(ctx, l, resolveNames).then((r) => {+ if (ctx.json) {+ process.stdout.write(JSON.stringify(r) + '\n')+ } else {+ const name = r.symbol ? bold(r.symbol) + ' ' : ''+ process.stdout.write(+ `${green('▲')} ${dim(r.launchpad.padEnd(7))} ${name}${gray(addr(r.token as Address))} ${dim('by')} ${gray(addr(r.creator as Address))} ${dim('#' + r.block)}\n`,+ )+ }+ })+ },+ { launchpad, onError: (e) => process.stderr.write(dim(`(watch retry: ${e.message})\n`)) },+ )+ const shutdown = () => {+ unwatch()+ process.exit(0)+ }+ process.on('SIGINT', shutdown)+ process.on('SIGTERM', shutdown)+ await new Promise(() => {})+}++function renderFeed(rows: LaunchRow[], network: string): string {+ const header = `${accent('◈')} ${bold('Launches')} ${dim(`· ${network} · ${rows.length}`)}`+ if (rows.length === 0) {+ return `${header}\n${dim('No launches in the scanned window. Widen it with --lookback, or --follow to stream new ones.')}`+ }+ const columns: Column<LaunchRow>[] = [+ { header: 'BLOCK', align: 'right', priority: 90, cell: (r) => dim('#' + r.block) },+ { header: 'PAD', priority: 100, cell: (r) => (r.launchpad === 'noxa' ? accent('NOXA') : bold('Odyssey')) },+ { header: 'TOKEN', priority: 95, cell: (r) => (r.symbol ? bold(r.symbol) : gray(addr(r.token as Address))) },+ { header: 'ADDRESS', priority: 50, cell: (r) => gray(addr(r.token as Address)) },+ { header: 'CREATOR', priority: 40, cell: (r) => gray(addr(r.creator as Address)) },+ { header: 'POOL', priority: 30, cell: (r) => (r.pool ? gray(addr(r.pool as Address)) : dim('curve')) },+ ]+ return `${header}\n${renderTable(rows, columns)}`+}diff --git a/robinhood/hood-cli/src/commands/portfolio.ts b/robinhood/hood-cli/src/commands/portfolio.tsnew file mode 100644index 000000000..8c4c2b8c3--- /dev/null+++ b/robinhood/hood-cli/src/commands/portfolio.ts@@ -0,0 +1,104 @@+import { Command } from 'commander'+import { formatEther, getAddress, isAddress, type Address } from 'viem'+import { getPortfolio, getUsdgBalance, formatUsdg, type StockPosition } from 'hoodchain'+import { runWith } from '../action.js'+import type { Context } from '../context.js'+import { printResult } from '../output.js'+import { renderTable, renderKeyValue, type Column } from '../ui/table.js'+import { withSpinner } from '../ui/spinner.js'+import { accent, bold, dim, gray } from '../ui/ansi.js'+import { usd, num, addr } from '../format.js'+import { usageError } from '../errors.js'++export function portfolioCommand(): Command {+ return new Command('portfolio')+ .description('Multiplier-correct Stock Token positions + USD totals for an address')+ .argument('<address>', 'wallet address to inspect')+ .option('--max-age <seconds>', 'max acceptable Chainlink answer age')+ .action((address: string, opts, command) =>+ runWith(command, async (ctx) => {+ await portfolio(ctx, address, opts)+ }),+ )+}++async function portfolio(ctx: Context, address: string, opts: { maxAge?: string }): Promise<void> {+ if (!isAddress(address)) throw usageError(`"${address}" is not a valid address.`)+ const owner = getAddress(address)+ const client = ctx.read()+ const maxAgeSeconds = opts.maxAge ? Number(opts.maxAge) : undefined++ const { port, usdg, eth } = await withSpinner(`Reading ${addr(owner)}…`, async () => {+ const [port, usdg, eth] = await Promise.all([+ getPortfolio(client, owner, maxAgeSeconds ? { maxAgeSeconds } : {}),+ getUsdgBalance(client, owner),+ client.public.getBalance({ address: owner }),+ ])+ return { port, usdg, eth }+ })++ const held = port.positions.filter((p) => p.balance > 0n)+ const usdgFloat = Number(formatUsdg(usdg))+ const grandTotal = port.totalUsd + usdgFloat++ const json = {+ owner,+ network: ctx.network,+ eth: formatEther(eth),+ usdg: formatUsdg(usdg),+ stockValueUsd: port.totalUsd,+ totalUsd: grandTotal,+ unpricedSymbols: port.unpricedSymbols,+ positions: held.map((p) => ({+ symbol: p.symbol,+ address: p.address,+ balance: p.balanceTokens,+ shareEquivalent: p.shareEquivalent,+ priceUsd: p.quote?.priceUsd ?? null,+ valueUsd: p.valueUsd,+ })),+ }++ printResult(json, () => renderPortfolio(owner, held, eth, usdgFloat, port.totalUsd, grandTotal, port.unpricedSymbols, ctx.network), ctx.json)+}++function renderPortfolio(+ owner: Address,+ held: StockPosition[],+ eth: bigint,+ usdg: number,+ stockUsd: number,+ total: number,+ unpriced: string[],+ network: string,+): string {+ const header = `${accent('◈')} ${bold('Portfolio')} ${dim('· ' + addr(owner) + ' · ' + network)}`++ const summary = renderKeyValue(+ [+ ['ETH', num(Number(formatEther(eth)), 6)],+ ['USDG', usd(usdg)],+ ['Stocks', usd(stockUsd)],+ ['Total', bold(usd(total))],+ ],+ { labelWidth: 7 },+ )++ if (held.length === 0) {+ return `${header}\n${summary}\n\n${dim('No Stock Token positions. Fund with `hood swap --sell USDG --buy <ticker>`.')}`+ }++ const sorted = [...held].sort((a, b) => (b.valueUsd ?? -1) - (a.valueUsd ?? -1))+ const columns: Column<StockPosition>[] = [+ { header: 'SYMBOL', priority: 100, cell: (p) => bold(p.symbol) },+ { header: 'BALANCE', align: 'right', priority: 90, cell: (p) => num(p.balanceTokens, 4) },+ { header: 'SHARES', align: 'right', priority: 60, cell: (p) => num(p.shareEquivalent, 4) },+ { header: 'PRICE', align: 'right', priority: 70, cell: (p) => (p.quote ? usd(p.quote.priceUsd) : dim('—')) },+ { header: 'VALUE', align: 'right', priority: 95, cell: (p) => (p.valueUsd !== null ? bold(usd(p.valueUsd)) : dim('unpriced')) },+ { header: 'ADDRESS', priority: 20, cell: (p) => gray(addr(p.address)) },+ ]++ const footNote =+ unpriced.length > 0 ? '\n' + dim(`Unpriced (no fresh feed): ${unpriced.join(', ')}`) : ''+ return `${header}\n${summary}\n\n${renderTable(sorted, columns)}${footNote}`+}diff --git a/robinhood/hood-cli/src/commands/stocks.ts b/robinhood/hood-cli/src/commands/stocks.tsnew file mode 100644index 000000000..dca88cc44--- /dev/null+++ b/robinhood/hood-cli/src/commands/stocks.ts@@ -0,0 +1,111 @@+import { Command } from 'commander'+import { listStockTokens, listPricedStockTokens, type StockToken } from 'hoodchain'+import { runWith } from '../action.js'+import type { Context } from '../context.js'+import { getOracleQuote, getDexPriceUsd } from '../prices.js'+import { printResult } from '../output.js'+import { renderTable, type Column } from '../ui/table.js'+import { withSpinner } from '../ui/spinner.js'+import { accent, bold, dim, gray, truncate } from '../ui/ansi.js'+import { usd, pct, age, addr, num } from '../format.js'+import { usageError } from '../errors.js'+import { pMap } from '../pmap.js'++type SortKey = 'symbol' | 'price' | 'premium'++interface StockRow {+ symbol: string+ name: string+ address: string+ oracleUsd: number | null+ ageSeconds: number | null+ dexUsd: number | null+ premium: number | null+}++export function stocksCommand(): Command {+ return new Command('stocks')+ .description('The full Stock Token board with live Chainlink prices')+ .option('--sort <key>', 'sort by symbol | price | premium (premium implies --dex)', 'symbol')+ .option('--dex', 'also probe Uniswap for DEX price + premium (slower)', false)+ .option('--priced', 'only tokens with a live Chainlink feed', false)+ .option('--limit <n>', 'show at most n rows')+ .action((opts, command) =>+ runWith(command, async (ctx) => {+ await stocks(ctx, opts)+ }),+ )+}++interface StocksOpts {+ sort: string+ dex: boolean+ priced: boolean+ limit?: string+}++async function stocks(ctx: Context, opts: StocksOpts): Promise<void> {+ const sort = opts.sort as SortKey+ if (!['symbol', 'price', 'premium'].includes(sort)) {+ throw usageError(`--sort must be one of: symbol, price, premium (got "${opts.sort}").`)+ }+ const withDex = opts.dex || sort === 'premium'+ const client = ctx.read()+ const tokens: StockToken[] = opts.priced || sort === 'premium' ? listPricedStockTokens() : listStockTokens()++ const rows = await withSpinner(+ withDex ? `Pricing ${tokens.length} tokens (oracle + DEX)…` : `Pricing ${tokens.length} tokens…`,+ () =>+ pMap(+ tokens,+ async (t): Promise<StockRow> => {+ const oracle = t.feed ? await getOracleQuote(client, t.symbol) : null+ const dexUsd = withDex ? await getDexPriceUsd(client, t.address, t.decimals) : null+ const premium = oracle && dexUsd ? (dexUsd - oracle.priceUsd) / oracle.priceUsd : null+ return {+ symbol: t.symbol,+ name: t.name.replace(/\s*•\s*Robinhood Token$/, ''),+ address: t.address,+ oracleUsd: oracle?.priceUsd ?? null,+ ageSeconds: oracle?.ageSeconds ?? null,+ dexUsd,+ premium,+ }+ },+ withDex ? 6 : 16,+ ),+ )++ sortRows(rows, sort)+ const limited = opts.limit ? rows.slice(0, Math.max(0, Number(opts.limit))) : rows++ printResult(+ { network: ctx.network, count: limited.length, tokens: limited },+ () => renderBoard(limited, withDex, ctx.network),+ ctx.json,+ )+}++function sortRows(rows: StockRow[], sort: SortKey): void {+ if (sort === 'symbol') rows.sort((a, b) => a.symbol.localeCompare(b.symbol))+ else if (sort === 'price') rows.sort((a, b) => (b.oracleUsd ?? -1) - (a.oracleUsd ?? -1))+ else rows.sort((a, b) => (b.premium ?? -Infinity) - (a.premium ?? -Infinity))+}++function renderBoard(rows: StockRow[], withDex: boolean, network: string): string {+ const columns: Column<StockRow>[] = [+ { header: 'SYMBOL', cell: (r) => bold(r.symbol), priority: 100 },+ { header: 'PRICE', align: 'right', priority: 90, cell: (r) => (r.oracleUsd !== null ? usd(r.oracleUsd) : dim('—')) },+ { header: 'AGE', align: 'right', priority: 40, cell: (r) => (r.ageSeconds !== null ? dim(age(r.ageSeconds)) : dim('—')) },+ { header: 'NAME', priority: 20, cell: (r) => dim(truncate(r.name, 24)) },+ ]+ if (withDex) {+ columns.splice(2, 0, { header: 'DEX', align: 'right', priority: 70, cell: (r) => (r.dexUsd !== null ? usd(r.dexUsd) : dim('—')) })+ columns.splice(3, 0, { header: 'PREMIUM', align: 'right', priority: 80, cell: (r) => (r.premium !== null ? pct(r.premium) : dim('—')) })+ }+ columns.push({ header: 'ADDRESS', priority: 10, cell: (r) => gray(addr(r.address as `0x${string}`)) })++ const priced = rows.filter((r) => r.oracleUsd !== null).length+ const header = `${accent('◈')} ${bold('Stock Tokens')} ${dim(`· ${network} · ${rows.length} shown · ${priced} priced`)}`+ return `${header}\n${renderTable(rows, columns)}`+}diff --git a/robinhood/hood-cli/src/commands/tx.ts b/robinhood/hood-cli/src/commands/tx.tsnew file mode 100644index 000000000..5ec64a92b--- /dev/null+++ b/robinhood/hood-cli/src/commands/tx.ts@@ -0,0 +1,124 @@+import { Command } from 'commander'+import { decodeEventLog, formatEther, formatGwei, isHash, type Address, type Hash } from 'viem'+import { erc20Abi, getStockTokenByAddress } from 'hoodchain'+import { runWith } from '../action.js'+import type { Context } from '../context.js'+import { printResult } from '../output.js'+import { renderKeyValue } from '../ui/table.js'+import { withSpinner } from '../ui/spinner.js'+import { accent, bold, dim, gray, green, red } from '../ui/ansi.js'+import { addr, num, tokenAmount, timestamp } from '../format.js'+import { fetchTx, txUrl } from '../blockscout.js'+import { notFoundError, usageError } from '../errors.js'++interface TransferLine {+ token: Address+ symbol: string | null+ from: Address+ to: Address+ value: string+}++export function txCommand(): Command {+ return new Command('tx')+ .description('Decode a transaction: status, transfers, gas, method')+ .argument('<hash>', 'transaction hash')+ .action((hash: string, _opts, command) =>+ runWith(command, async (ctx) => {+ await tx(ctx, hash)+ }),+ )+}++async function tx(ctx: Context, hash: string): Promise<void> {+ if (!isHash(hash)) throw usageError(`"${hash}" is not a 32-byte transaction hash.`)+ const client = ctx.read()++ const { transaction, receipt, block, meta } = await withSpinner('Fetching transaction…', async () => {+ const transaction = await client.public.getTransaction({ hash: hash as Hash }).catch(() => null)+ if (!transaction) throw notFoundError(`No transaction ${hash} on ${ctx.network}.`)+ const [receipt, meta] = await Promise.all([+ client.public.getTransactionReceipt({ hash: hash as Hash }).catch(() => null),+ fetchTx(ctx.network, hash),+ ])+ const block = receipt+ ? await client.public.getBlock({ blockNumber: receipt.blockNumber }).catch(() => null)+ : null+ return { transaction, receipt, block, meta }+ })++ const transfers: TransferLine[] = []+ for (const log of receipt?.logs ?? []) {+ try {+ const decoded = decodeEventLog({ abi: erc20Abi, data: log.data, topics: log.topics })+ if (decoded.eventName !== 'Transfer') continue+ const args = decoded.args as unknown as { from: Address; to: Address; value: bigint }+ const known = ctx.network === 'mainnet' ? getStockTokenByAddress(log.address) : null+ transfers.push({+ token: log.address,+ symbol: known?.symbol ?? null,+ from: args.from,+ to: args.to,+ value: known ? tokenAmount(args.value, known.decimals) : args.value.toString(),+ })+ } catch {+ /* not an ERC-20 Transfer — skip */+ }+ }++ const status = receipt ? (receipt.status === 'success' ? 'success' : 'reverted') : 'pending'+ const gasUsed = receipt?.gasUsed ?? 0n+ const gasPrice = receipt?.effectiveGasPrice ?? transaction.gasPrice ?? 0n+ const feeEth = formatEther(gasUsed * gasPrice)++ const json = {+ hash,+ network: ctx.network,+ status,+ block: receipt?.blockNumber?.toString() ?? null,+ timestamp: block ? Number(block.timestamp) : null,+ from: transaction.from,+ to: transaction.to,+ valueEth: formatEther(transaction.value),+ nonce: transaction.nonce,+ method: meta?.decoded_input?.method_call ?? meta?.method ?? null,+ gasUsed: gasUsed.toString(),+ gasPriceGwei: formatGwei(gasPrice),+ feeEth,+ transfers,+ explorer: txUrl(ctx.network, hash),+ }++ printResult(json, () => renderTx(json, status, transfers), ctx.json)+}++function renderTx(+ j: { hash: string; from: Address | null; to: Address | null; valueEth: string; nonce: number; method: string | null; block: string | null; timestamp: number | null; gasUsed: string; gasPriceGwei: string; feeEth: string; explorer: string },+ status: string,+ transfers: TransferLine[],+): string {+ const statusBadge = status === 'success' ? green('● success') : status === 'reverted' ? red('● reverted') : dim('● pending')+ const header = `${accent('◈')} ${bold('Transaction')} ${dim(addr(j.hash as `0x${string}`))} ${statusBadge}`++ const pairs: [string, string][] = [+ ['From', gray(j.from ? addr(j.from) : '—')],+ ['To', gray(j.to ? addr(j.to) : dim('contract creation'))],+ ['Value', j.valueEth === '0' ? dim('0 ETH') : bold(num(Number(j.valueEth), 8) + ' ETH')],+ ['Method', j.method ? bold(j.method) : dim('—')],+ ['Block', j.block ? '#' + j.block : dim('pending')],+ ['When', j.timestamp ? dim(timestamp(j.timestamp)) : dim('—')],+ ['Gas used', dim(num(Number(j.gasUsed), 0) + ` @ ${num(Number(j.gasPriceGwei), 4)} gwei`)],+ ['Fee', num(Number(j.feeEth), 8) + ' ETH'],+ ['Explorer', gray(j.explorer)],+ ]++ let out = `${header}\n${renderKeyValue(pairs, { labelWidth: 9 })}`+ if (transfers.length) {+ const lines = transfers.map(+ (t) =>+ ` ${gray(addr(t.from))} ${dim('→')} ${gray(addr(t.to))} ${bold(t.value)} ${t.symbol ? accent(t.symbol) : gray(addr(t.token))}`,+ )+ out += `\n\n${dim('Token transfers')}\n${lines.join('\n')}`+ }+ return out+}diff --git a/robinhood/hood-cli/src/pmap.ts b/robinhood/hood-cli/src/pmap.tsnew file mode 100644index 000000000..99033e18a--- /dev/null+++ b/robinhood/hood-cli/src/pmap.ts@@ -0,0 +1,23 @@+/**+ * Bounded-concurrency async map. Keeps the public RPC happy (no 500-call+ * bursts) while still running work in parallel. Preserves input order.+ */+export async function pMap<In, Out>(+ items: readonly In[],+ mapper: (item: In, index: number) => Promise<Out>,+ concurrency = 8,+): Promise<Out[]> {+ const results = new Array<Out>(items.length)+ let cursor = 0+ const limit = Math.max(1, Math.min(concurrency, items.length || 1))++ async function worker(): Promise<void> {+ while (cursor < items.length) {+ const index = cursor+++ results[index] = await mapper(items[index] as In, index)+ }+ }++ await Promise.all(Array.from({ length: limit }, worker))+ return results+}diff --git a/robinhood/hood-js/src/coins.ts b/robinhood/hood-js/src/coins.tsindex 85721dbd0..2aa2a0fc6 100644--- a/robinhood/hood-js/src/coins.ts+++ b/robinhood/hood-js/src/coins.ts@@ -1,8 +1,12 @@import { HoodError, toHoodError } from './errors.js'import { geckoNetwork } from './state.js'-/** One trending coin returned by {@link coins}. */-export interface TrendingCoin {+/**+ * A coin as reported by GeckoTerminal's public onchain index for Robinhood+ * Chain — the same provider that already covers chain 4663. Used by both+ * {@link coins} (trending) and {@link import('./index').launches} (new pools).+ */+export interface Coin {/** Base-token ticker, e.g. `"HOODBOT"`. */symbol: string/** Human name of the pool pairing, e.g. `"HOODBOT / WETH 1%"`. */@@ -29,6 +33,11 @@ export interface TrendingCoin {url: string}+/** Alias for {@link Coin} in trending contexts. */+export type TrendingCoin = Coin+/** Alias for {@link Coin} in new-launch contexts. */+export type NewCoin = Coin+/** Options for {@link coins}. */export interface CoinsOptions {/** Max coins to return. @defaultValue `20` */@@ -76,33 +85,24 @@ function num(value: string | null | undefined): number | null {}/**- * Trending memecoins on Robinhood Chain, aggregated across the launchpad- * (NOXA / The Odyssey) and Uniswap pools by GeckoTerminal's public onchain- * index — the same data provider that already covers chain 4663. Returns- * live USD price, 24h change, volume, and liquidity. No key, no wallet.- *- * @example- * ```js- * const top = await hood.coins()- * for (const c of top) console.log(c.symbol, `$${c.priceUsd}`, `${c.change24h}%`)- * ```+ * Fetch a page of pools from a GeckoTerminal onchain endpoint and map them to+ * {@link Coin}s. Shared by {@link coins} and the new-pools discovery used by+ * {@link import('./index').launches}.*/-export async function coins(options: CoinsOptions = {}): Promise<TrendingCoin[]> {- const limit = options.limit ?? 20- const window = options.window ?? '24h'- const timeoutMs = options.timeoutMs ?? 10_000+export async function fetchPools(+ endpoint: 'trending_pools' | 'new_pools',+ params: Record<string, string>,+ timeoutMs: number,+): Promise<Coin[]> {const network = geckoNetwork()-- const url = `${GECKO_BASE}/networks/${network}/trending_pools?include=base_token,dex&duration=${window}&page=1`+ const query = new URLSearchParams({ include: 'base_token,dex', page: '1', ...params }).toString()+ const url = `${GECKO_BASE}/networks/${network}/${endpoint}?${query}`const controller = new AbortController()const timer = setTimeout(() => controller.abort(), timeoutMs)let res: Responsetry {- res = await fetch(url, {- headers: { accept: 'application/json' },- signal: controller.signal,- })+ res = await fetch(url, { headers: { accept: 'application/json' }, signal: controller.signal })} catch (err) {throw toHoodError(err)} finally {@@ -111,25 +111,24 @@ export async function coins(options: CoinsOptions = {}): Promise<TrendingCoin[]>if (res.status === 429) {throw new HoodError(- 'GeckoTerminal is rate-limiting trending-coin requests (free tier is ~30/min). Slow down or add your own API key upstream.',+ 'GeckoTerminal is rate-limiting requests (free tier is ~30/min). Slow down or add your own API key upstream.','NETWORK',)}if (!res.ok) {throw new HoodError(- `Couldn't load trending coins for network "${network}" (HTTP ${res.status}). If Robinhood Chain isn't indexed yet, set hood.config({ geckoNetwork }) to the correct slug.`,+ `Couldn't load ${endpoint} for network "${network}" (HTTP ${res.status}). If Robinhood Chain isn't indexed yet, set hood.config({ geckoNetwork }) to the correct slug.`,'NETWORK',)}const body = (await res.json()) as { data?: GeckoPool[]; included?: GeckoIncluded[] }- const pools = body.data ?? []const tokenById = new Map<string, GeckoIncluded>()for (const inc of body.included ?? []) {if (inc.type === 'token') tokenById.set(inc.id, inc)}- return pools.slice(0, limit).map((pool): TrendingCoin => {+ return (body.data ?? []).map((pool): Coin => {const a = pool.attributesconst baseId = pool.relationships?.base_token?.data?.idconst base = baseId ? tokenById.get(baseId) : undefined@@ -149,3 +148,29 @@ export async function coins(options: CoinsOptions = {}): Promise<TrendingCoin[]>}})}++/**+ * Trending memecoins on Robinhood Chain, aggregated across the launchpad and+ * Uniswap pools by GeckoTerminal's public onchain index. Returns live USD+ * price, 24h change, volume, and liquidity. No key, no wallet.+ *+ * @example+ * ```js+ * const top = await hood.coins()+ * for (const c of top) console.log(c.symbol, `$${c.priceUsd}`, `${c.change24h}%`)+ * ```+ */+export async function coins(options: CoinsOptions = {}): Promise<TrendingCoin[]> {+ const limit = options.limit ?? 20+ const list = await fetchPools(+ 'trending_pools',+ { duration: options.window ?? '24h' },+ options.timeoutMs ?? 10_000,+ )+ return list.slice(0, limit)+}++/** Fetch the newest pools (freshest launches first). */+export async function fetchNewCoins(timeoutMs: number): Promise<NewCoin[]> {+ return fetchPools('new_pools', {}, timeoutMs)+}diff --git a/robinhood/hood-launcher/src/rails/addresses.ts b/robinhood/hood-launcher/src/rails/addresses.tsnew file mode 100644index 000000000..c0cc22e7a--- /dev/null+++ b/robinhood/hood-launcher/src/rails/addresses.ts@@ -0,0 +1,89 @@+import type { Address } from 'viem'++/**+ * Launchpad + DEX addresses used by the rails.+ *+ * Every mainnet address here was verified during this build:+ * - NOXA `launchFactory` was cross-checked by reading its live on-chain+ * config (`getDexConfig(0)` returns the exact Uniswap v3 factory / position+ * manager / router below, `launchFee()` = 0.0005 ETH, `getLaunchConfig(0)`+ * pairs against WETH at the 1% tier). The Uniswap addresses match+ * `hoodchain`'s `MAINNET_ADDRESSES`.+ * - The Odyssey factories were confirmed as the real token deployers via+ * Blockscout `getcontractcreation` on tokens they produced.+ */++/** NOXA "NOXA Fun" launcher (mainnet 4663). Instant Uniswap-v3 listing. */+export const NOXA = {+ launchFactory: '0xD9eC2db5f3D1b236843925949fe5bd8a3836FCcB' as Address,+ locker: '0x7F03effbd7ceB22A3f80Dd468f67eF27826acD85' as Address,+ feeRouter: '0x9eFdC1A8e6E94f16A228e44f3025E1f346EE0417' as Address,+ /** First block with factory activity — lower bound for historical scans. */+ deployBlock: 61688n,+} as const++/** The Odyssey launchpad factories (mainnet 4663). */+export const ODYSSEY = {+ /** Native-ETH bonding-curve factory. `createToken`-shaped, initial buy is a separate call. */+ bondingCurveFactory: '0xEb3FeeD2716cF0eEAda05B22e67424794e1f5a80' as Address,+ /** Instant-list factory — one tx deploys + seeds a pool; initial buy folds into `msg.value`. */+ instantFactory: '0xD7601cEe401306fdea5833c6898181D9c770F800' as Address,+ /** Variant that pays reflections in a reward token (create shape unverified — not enabled). */+ reflectionFactory: '0x6Ce85c4b7cE12903E5867652C265bCcce57f935F' as Address,+ robinLock: '0x5B41D59Fa0ce65750bc64e06D85bC999084493CD' as Address,+ legacyFactory: '0xAf9f3ce1d34909F59E88c23027f89d5807B0F915' as Address,+} as const++/**+ * Proven 4-byte selectors for The Odyssey. No verified ABI exists on-chain for+ * any Odyssey factory, so the rails pin *selectors* (structure recovered from+ * real txs) rather than function names. Each is proven against a cited+ * historical transaction in `tests/unit/odyssey-calldata.test.ts`.+ */+export const ODYSSEY_SELECTORS = {+ /** instant `f(string name, string symbol, uint256 buyAmount)` payable, msg.value == buyAmount. */+ instantCreate: '0x548eb31b' as const,+ /** bonding `f(string name, string symbol, uint256 threshold, uint256 reserved)` value 0. */+ bondingCreate: '0x56f698a3' as const,+ /** bonding `f(address token, uint256 minTokensOut)` payable — the initial buy. */+ bondingBuy: '0xcce7ec13' as const,+} as const++/**+ * Constant tail params observed in EVERY sampled Odyssey bonding `createToken`+ * call (`0.5e18`, `0`). Semantics are not source-verified; the rail replays the+ * observed constants rather than guessing new values.+ */+export const ODYSSEY_BONDING_CONSTANTS = {+ threshold: 500_000_000_000_000_000n, // 0.5e18+ reserved: 0n,+} as const++/** Uniswap v3 periphery on mainnet 4663 (used by the direct rail). */+export const MAINNET_UNISWAP = {+ weth: '0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73' as Address,+ usdg: '0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168' as Address,+ factory: '0x1f7d7550B1b028f7571E69A784071F0205FD2EfA' as Address,+ positionManager: '0x73991a25C818Bf1f1128dEAaB1492D45638DE0D3' as Address,+ swapRouter02: '0xCaf681a66D020601342297493863E78C959E5cb2' as Address,+} as const++/** Uniswap v3 periphery on the community testnet 46630 deployment. */+export const TESTNET_UNISWAP = {+ weth: '0x7943e237c7F95DA44E0301572D358911207852Fa' as Address,+ usdg: '0x7E955252E15c84f5768B83c41a71F9eba181802F' as Address,+ factory: '0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865' as Address,+ positionManager: '0x46A15B0b27311cedF172AB29E4f4766fbE7F4364' as Address,+ swapRouter: '0x1b81D678ffb9C0263b24A97847620C99d213eB14' as Address,+} as const++/** Uniswap v3 fee tiers as basis points → tickSpacing. */+export const V3_TICK_SPACINGS: Record<number, number> = {+ 100: 1,+ 500: 10,+ 3000: 60,+ 10000: 200,+}++/** The dead address LP NFTs / tokens are burned to. */+export const BURN_ADDRESS = '0x000000000000000000000000000000000000dEaD' as Addressdiff --git a/robinhood/hood-launcher/src/rails/types.ts b/robinhood/hood-launcher/src/rails/types.tsnew file mode 100644index 000000000..c6fe43267--- /dev/null+++ b/robinhood/hood-launcher/src/rails/types.ts@@ -0,0 +1,128 @@+import type { Address, Hash, Hex } from 'viem'+import type { HoodClient, HoodNetwork } from 'hoodchain'++/** The launch rails hood-launcher ships. */+export type RailName = 'noxa' | 'odyssey' | 'direct'++/** Social links attached to a launch (all optional). */+export interface Socials {+ telegram?: string+ twitter?: string+ discord?: string+ website?: string+ farcaster?: string+}++/**+ * The rail-agnostic description of a coin to launch. The concept engine and+ * config both resolve down to this shape before any rail runs.+ */+export interface LaunchInput {+ /** Token name, e.g. "We are so back". */+ name: string+ /** Ticker, e.g. "BACK". Uppercased, no `$`. */+ symbol: string+ /** One-line description / lore. May be empty. */+ description: string+ /**+ * The coin's logo, as a URI. hood-launcher's differentiator is a 3D GLB+ * logo generated on the three.ws free forge lane; any image/GLB/IPFS URI the+ * operator supplies works too.+ */+ logoUri: string+ socials: Socials+ /**+ * Native ETH to spend on the creator's initial buy, in wei. `0n` = launch+ * with no initial buy. On rails where the initial buy is a separate step+ * (Odyssey bonding), this seeds that step.+ */+ initialBuyWei: bigint+ /** Optional 32-byte salt for deterministic addresses (NOXA). Random if omitted. */+ salt?: Hex+}++/** Options that tune the direct rail's ERC-20 + pool. */+export interface DirectRailOptions {+ /** Total fixed supply, in whole tokens (18 decimals applied). @defaultValue `1_000_000_000` */+ totalSupply?: bigint+ /** Uniswap v3 fee tier in bps for the seeded pool. @defaultValue `10000` (1%) */+ feeTier?: number+ /** Native ETH (wei) to seed as the pool's paired liquidity. */+ seedWethWei: bigint+ /** Fraction (bps) of total supply to deposit as the token side of the LP. @defaultValue `10000` (100%) */+ lpSupplyBps?: number+ /** What to do with the LP position NFT after seeding. @defaultValue `'burn'` */+ lpDisposition?: 'burn' | 'lock' | 'keep'+}++/** Everything a rail needs at call time. */+export interface RailContext {+ client: HoodClient+ /** Direct-rail knobs; ignored by launchpad rails. */+ direct?: DirectRailOptions+}++/** Result of a read-only rail preflight. */+export interface RailPreflight {+ rail: RailName+ network: HoodNetwork+ /** True when a launch can proceed right now. */+ ready: boolean+ /** Human-readable blockers when `ready` is false. */+ blockers: string[]+ /** Protocol fee charged by the rail, in wei (launch fee; excludes the initial buy). */+ protocolFeeWei: bigint+ /** Total native ETH the launch tx will require = protocol fee + initial buy + seed. */+ estimatedValueWei: bigint+ /** The token the new coin will be paired against (WETH / USDG / native). */+ pairToken?: Address+}++/** A built, not-yet-sent launch, suitable for simulation and inspection. */+export interface RailPlan {+ rail: RailName+ /** One or more ordered transactions the launch requires. */+ steps: RailStep[]+ preflight: RailPreflight+}++/** A single unsigned transaction in a launch plan. */+export interface RailStep {+ label: string+ to: Address+ data: Hex+ value: bigint+}++/** The outcome of a completed launch. */+export interface RailLaunch {+ rail: RailName+ network: HoodNetwork+ /** The new token's contract address. */+ token: Address+ /** The Uniswap v3 pool, when one exists immediately (null for pure bonding curves pre-graduation). */+ pool: Address | null+ /** Every transaction hash the launch sent, in order. */+ transactionHashes: Hash[]+ /** The primary launch tx hash (token creation). */+ launchTx: Hash+ /** Native ETH spent in total (fees + buy + seed), in wei. */+ spentWei: bigint+ /** Explorer links for the token + launch tx. */+ explorer: { token: string; launchTx: string }+ /** Rail-specific extras (positionId, pairToken, restrictionsEndBlock, …). */+ extra: Record<string, string>+}++/** The interface every rail implements. */+export interface Rail {+ readonly name: RailName+ /** Networks this rail can run on. */+ readonly networks: readonly HoodNetwork[]+ /** Read-only: is the rail launchable now, and what will it cost? */+ preflight(ctx: RailContext, input: LaunchInput): Promise<RailPreflight>+ /** Build the ordered, unsigned transactions (for simulation / dry-run). */+ plan(ctx: RailContext, input: LaunchInput): Promise<RailPlan>+ /** Sign, send, confirm, and resolve the launched token + pool. */+ launch(ctx: RailContext, input: LaunchInput): Promise<RailLaunch>+}diff --git a/robinhood/hood-mcp/src/register-trading.ts b/robinhood/hood-mcp/src/register-trading.tsindex f11abbb0a..e32e9739b 100644--- a/robinhood/hood-mcp/src/register-trading.ts+++ b/robinhood/hood-mcp/src/register-trading.ts@@ -235,16 +235,26 @@ export function registerTradingTools(const bps = slippageBps ?? 50const minOut = (quote.amountOut * BigInt(10_000 - bps)) / 10_000n- // Gate 2: value the spend and enforce caps. Fail closed if unvaluable.+ // Gate 2: value the spend and enforce caps. On mainnet, fail closed if+ // the spend cannot be valued (real money — never spend an unvaluable+ // asset under an automated cap). On testnet, assets are valueless play+ // money with no USD price, so an unvaluable spend counts as $0 notional+ // and the confirm gate below remains the real guard.const usd = await valueInUsd(client, ti, amountInRaw)+ let usdForCap: numberif (usd === null) {- return toError(- `Cannot value ${amountIn} ${ti.symbol} in USD (no price route), so the spend cap cannot be enforced.`,- 'Swaps whose input has no USDG price route are blocked for safety.',- )+ if (network === 'mainnet') {+ return toError(+ `Cannot value ${amountIn} ${ti.symbol} in USD (no price route), so the spend cap cannot be enforced.`,+ 'Swaps whose input has no USDG price route are blocked for safety on mainnet.',+ )+ }+ usdForCap = 0+ } else {+ usdForCap = usd}try {- ledger.assertWithinCaps(usd)+ ledger.assertWithinCaps(usdForCap)} catch (capErr) {return toError(errMessage(capErr))}@@ -254,7 +264,8 @@ export function registerTradingTools(network,from: walletAddress,spend: `${amountIn} ${ti.symbol}`,- spendValueUsd: round(usd, 4),+ spendValueUsd: usd === null ? null : round(usd, 4),+ spendValueNote: usd === null ? 'testnet — no USD price available' : undefined,receiveEstimate: `${formatUnits(quote.amountOut, to.decimals)} ${to.symbol}`,minReceived: `${formatUnits(minOut, to.decimals)} ${to.symbol}`,route: quote.route.path,diff --git a/robinhood/hood-traders/src/framework/agent.ts b/robinhood/hood-traders/src/framework/agent.tsnew file mode 100644index 000000000..1c7753c6f--- /dev/null+++ b/robinhood/hood-traders/src/framework/agent.ts@@ -0,0 +1,430 @@+import { formatUnits, type Account, type Address, type Hash } from 'viem'+import { buildSwapTx, ensureApproval, type SwapQuote } from 'hoodchain'+import type { Journal } from './journal.js'+import type { Market } from './market.js'+import { RiskEngine, utcDayStart } from './risk.js'+import type { KillSwitch } from './kill.js'+import type { Strategy } from './strategy.js'+import type {+ AgentStatus,+ Decision,+ Intent,+ Mode,+ Position,+ RiskLimits,+ TradeRecord,+} from './types.js'++/** Everything an {@link Agent} is constructed with. */+export interface AgentOptions {+ id: string+ strategy: Strategy+ market: Market+ limits: RiskLimits+ journal: Journal+ kill: KillSwitch+ mode: Mode+ /** Account for live execution; null in paper mode. */+ account: Account | null+ fleetMaxDailySpendUsdg: number+ /** Fleet-wide spend accessor + reporter, so the agent respects the global cap. */+ fleetSpentTodayUsd: () => number+ reportFleetSpend: (usd: number) => void+ /** Milliseconds between decision ticks. */+ tickIntervalMs: number+ /** Injected clock, for tests. Defaults to `Date.now`. */+ clock?: () => number+}++const DUST = 1_000n // token smallest-units below which a position is considered closed++/**+ * An autonomous trading agent = strategy + wallet + risk budget + journal.+ *+ * Each tick runs the full pipeline: observe (the strategy reads the {@link+ * Market}) → decide (the strategy returns intents) → simulate (a real QuoterV2+ * `eth_call`) → risk-check (the {@link RiskEngine}, fail-closed) → execute+ * (paper: record the simulated fill; live: sign the swap) → journal (every+ * decision, refusal, trade, and equity mark). The strategy proposes; the agent+ * disposes, and never lets an intent skip the risk gate.+ */+export class Agent {+ readonly id: string+ readonly strategy: Strategy+ readonly mode: Mode+ private readonly market: Market+ private readonly risk: RiskEngine+ private readonly journal: Journal+ private readonly kill: KillSwitch+ private readonly account: Account | null+ private readonly opts: AgentOptions+ private readonly clock: () => number++ private readonly positions = new Map<string, Position>()+ private lastTradeAt: number | null = null+ private realizedUsd = 0+ private spentTodayUsd = 0+ private spentDay = 0+ private ticks = 0+ private trades = 0+ private refusals = 0+ private lastTickAt: number | null = null+ private lastError: string | null = null+ private timer: ReturnType<typeof setTimeout> | null = null+ private running = false+ private ticking = false++ constructor(opts: AgentOptions) {+ this.opts = opts+ this.id = opts.id+ this.strategy = opts.strategy+ this.mode = opts.mode+ this.market = opts.market+ this.risk = new RiskEngine(opts.limits)+ this.journal = opts.journal+ this.kill = opts.kill+ this.account = opts.account+ this.clock = opts.clock ?? Date.now+ }++ /** Begin the tick loop and wire the strategy's stream subscriptions. */+ async start(): Promise<void> {+ if (this.running) return+ this.running = true+ const log = (message: string, meta: Record<string, unknown> = {}) =>+ this.journal.recordDecision({ agentId: this.id, ts: this.clock(), kind: 'observe', detail: message, meta })+ await this.strategy.start?.({ market: this.market, log })+ this.kill.onKill((reason) => log(`kill switch tripped: ${reason} — halting new orders`))+ this.scheduleTick()+ }++ /** Stop the loop and the strategy's subscriptions. */+ stop(): void {+ this.running = false+ if (this.timer) clearTimeout(this.timer)+ this.timer = null+ this.strategy.stop?.()+ }++ private scheduleTick(): void {+ if (!this.running) return+ this.timer = setTimeout(async () => {+ await this.tick()+ this.scheduleTick()+ }, this.opts.tickIntervalMs)+ this.timer.unref?.()+ }++ /** Run one full pipeline pass. Safe to call directly (used by tests). */+ async tick(): Promise<void> {+ if (this.ticking) return+ this.ticking = true+ const now = this.clock()+ try {+ this.rolloverDay(now)+ await this.markPositions(now)++ if (this.kill.isKilled()) {+ // Halted: still mark equity so the curve shows the freeze, but propose nothing.+ this.recordEquity(now)+ this.ticks+++ this.lastTickAt = now+ return+ }++ const decision = await this.decide(now)+ for (const alert of decision.alerts) {+ this.journal.recordDecision({+ agentId: this.id,+ ts: now,+ kind: 'alert',+ detail: `[${alert.level}] ${alert.message}`,+ meta: alert.meta ?? {},+ })+ }+ for (const intent of decision.intents) {+ await this.processIntent(intent, now)+ }++ this.recordEquity(now)+ this.ticks+++ this.lastTickAt = now+ this.lastError = null+ } catch (err) {+ this.lastError = err instanceof Error ? err.message : String(err)+ this.journal.recordDecision({+ agentId: this.id,+ ts: now,+ kind: 'observe',+ detail: `tick error: ${this.lastError}`,+ meta: {},+ })+ } finally {+ this.ticking = false+ }+ }++ private async decide(now: number): Promise<Decision> {+ const { quoteToken, quoteSymbol, quoteDecimals } = this.quoteInfo()+ return this.strategy.tick({+ market: this.market,+ positions: [...this.positions.values()],+ now,+ quoteToken,+ quoteSymbol,+ quoteDecimals,+ log: (message, meta = {}) =>+ this.journal.recordDecision({ agentId: this.id, ts: now, kind: 'observe', detail: message, meta }),+ })+ }++ private quoteInfo(): { quoteToken: Address; quoteSymbol: string; quoteDecimals: number } {+ if (this.strategy.quote === 'weth') {+ return { quoteToken: this.market.weth, quoteSymbol: 'WETH', quoteDecimals: 18 }+ }+ return { quoteToken: this.market.usdg, quoteSymbol: 'USDG', quoteDecimals: this.market.usdgDecimals }+ }++ private async processIntent(intent: Intent, now: number): Promise<void> {+ const refuse = (reason: string, detail: string, meta: Record<string, unknown> = {}) => {+ this.refusals+++ this.journal.recordDecision({+ agentId: this.id,+ ts: now,+ kind: 'refused',+ detail: `${intent.side} ${intent.tokenSymbol}: ${detail}`,+ meta: { reason, intentReason: intent.reason, ...meta },+ })+ }++ const quoteToken = intent.quoteToken+ const quoteDecimals = intent.quoteSymbol === 'USDG' ? this.market.usdgDecimals : 18++ // ── simulate (real eth_call against live pools) ────────────────────────────+ let sim: SwapQuote | null+ if (intent.side === 'buy') {+ sim = await this.market.quoteBuy(quoteToken, intent.token, intent.amountIn)+ } else {+ sim = await this.market.quoteSell(intent.token, quoteToken, intent.amountIn)+ }+ if (!sim || sim.amountOut <= 0n) {+ refuse('no_route', 'no liquid route to simulate the fill')+ return+ }++ // ── notional in USD ────────────────────────────────────────────────────────+ const ethUsd = intent.quoteSymbol === 'WETH' ? await this.market.ethUsd(30_000, now) : 1+ if (ethUsd === null) {+ refuse('no_route', 'cannot price ETH to enforce USD caps')+ return+ }+ let notionalUsd: number+ if (intent.side === 'buy') {+ notionalUsd = Number(formatUnits(intent.amountIn, quoteDecimals)) * ethUsd+ } else {+ notionalUsd = Number(formatUnits(sim.amountOut, quoteDecimals)) * ethUsd+ }++ // ── position accounting for the cap ────────────────────────────────────────+ const existing = this.positions.get(intent.token.toLowerCase())+ if (intent.side === 'sell') {+ if (!existing || existing.amount < intent.amountIn - DUST) {+ refuse('insufficient_balance', 'position too small to sell requested amount')+ return+ }+ }+ const positionUsdAfter = intent.side === 'buy' ? (existing?.investedUsd ?? 0) + notionalUsd : 0++ // ── slippage bound ─────────────────────────────────────────────────────────+ const slippageBps = Math.min(intent.maxSlippageBps ?? this.risk.riskLimits.maxSlippageBps, 10_000)+ const minOut = (sim.amountOut * BigInt(10_000 - slippageBps)) / 10_000n++ // ── risk gate (fail closed) ────────────────────────────────────────────────+ const verdict = this.risk.check({+ side: intent.side,+ notionalUsd,+ positionUsdAfter,+ spentTodayUsd: this.spentTodayUsd,+ fleetSpentTodayUsd: this.opts.fleetSpentTodayUsd(),+ lastTradeAt: this.lastTradeAt,+ slippageBps,+ killed: this.kill.isKilled(),+ now,+ fleetMaxDailySpendUsdg: this.opts.fleetMaxDailySpendUsdg,+ })+ if (!verdict.ok) {+ refuse(verdict.reason ?? 'refused', verdict.detail, { notionalUsd: round(notionalUsd) })+ return+ }++ // ── execute ────────────────────────────────────────────────────────────────+ let txHash: Hash | null = null+ let amountOut = sim.amountOut+ if (this.mode === 'live') {+ const executed = await this.executeLive(intent, sim, slippageBps)+ if (!executed) {+ refuse('no_route', 'live execution failed (see logs)')+ return+ }+ txHash = executed.hash+ amountOut = executed.amountOutMinimum // conservative floor actually received ≥ this+ }++ // ── journal + book-keeping ──────────────────────────────────────────────────+ const trade: TradeRecord = {+ agentId: this.id,+ mode: this.mode,+ ts: now,+ side: intent.side,+ token: intent.token,+ tokenSymbol: intent.tokenSymbol,+ quoteToken,+ quoteSymbol: intent.quoteSymbol,+ amountIn: intent.amountIn,+ amountOut,+ txHash,+ reason: intent.reason,+ slippageBps,+ gasEstimate: sim.gasEstimate,+ meta: { ...(intent.meta ?? {}), notionalUsd: round(notionalUsd), minOut: minOut.toString() },+ }+ this.journal.recordTrade(trade)+ this.trades+++ this.lastTradeAt = now+ this.applyFill(intent, amountOut, notionalUsd, now)+ if (intent.side === 'buy') {+ this.spentTodayUsd += notionalUsd+ this.opts.reportFleetSpend(notionalUsd)+ }+ }++ private async executeLive(+ intent: Intent,+ sim: SwapQuote,+ slippageBps: number,+ ): Promise<{ hash: Hash; amountOutMinimum: bigint } | null> {+ if (!this.account) return null+ try {+ const tx = buildSwapTx(this.market.client, sim, { slippageBps })+ await ensureApproval(this.market.client, intent.side === 'buy' ? intent.quoteToken : intent.token, intent.amountIn)+ const hash = await this.market.client.wallet!.sendTransaction({+ to: tx.to,+ data: tx.data,+ value: tx.value,+ account: this.account,+ chain: this.market.client.chain,+ })+ await this.market.client.public.waitForTransactionReceipt({ hash })+ return { hash, amountOutMinimum: tx.amountOutMinimum }+ } catch (err) {+ this.lastError = err instanceof Error ? err.message : String(err)+ return null+ }+ }++ private applyFill(intent: Intent, amountOut: bigint, notionalUsd: number, now: number): void {+ const key = intent.token.toLowerCase()+ const existing = this.positions.get(key)+ if (intent.side === 'buy') {+ if (existing) {+ existing.amount += amountOut+ existing.costBasis += intent.amountIn+ existing.investedUsd += notionalUsd+ } else {+ this.positions.set(key, {+ token: intent.token,+ tokenSymbol: intent.tokenSymbol,+ amount: amountOut,+ costBasis: intent.amountIn,+ investedUsd: notionalUsd,+ quoteToken: intent.quoteToken,+ quoteSymbol: intent.quoteSymbol,+ openedAt: now,+ markUsd: null,+ meta: intent.meta ?? {},+ })+ }+ return+ }+ // sell: realize PnL on the sold fraction+ if (!existing) return+ const sellAmount = intent.amountIn > existing.amount ? existing.amount : intent.amountIn+ const fraction = existing.amount > 0n ? Number(sellAmount) / Number(existing.amount) : 1+ const costFractionUsd = existing.investedUsd * fraction+ this.realizedUsd += notionalUsd - costFractionUsd+ existing.amount -= sellAmount+ existing.costBasis -= BigInt(Math.floor(Number(existing.costBasis) * fraction))+ existing.investedUsd -= costFractionUsd+ if (existing.amount <= DUST) this.positions.delete(key)+ }++ /** Mark every open position to its live exit value (a real sell-side quote). */+ private async markPositions(now: number): Promise<void> {+ for (const pos of this.positions.values()) {+ const q = await this.market.quoteSell(pos.token, pos.quoteToken, pos.amount)+ if (!q) {+ pos.markUsd = null+ continue+ }+ const quoteDecimals = pos.quoteSymbol === 'USDG' ? this.market.usdgDecimals : 18+ const ethUsd = pos.quoteSymbol === 'WETH' ? await this.market.ethUsd(30_000, now) : 1+ if (ethUsd === null) {+ pos.markUsd = null+ continue+ }+ pos.markUsd = Number(formatUnits(q.amountOut, quoteDecimals)) * ethUsd+ }+ }++ private openValueUsd(): number {+ let sum = 0+ for (const pos of this.positions.values()) sum += pos.markUsd ?? pos.investedUsd+ return sum+ }++ private recordEquity(now: number): void {+ const openValueUsd = this.openValueUsd()+ this.journal.recordEquity({+ agentId: this.id,+ ts: now,+ realizedUsd: round(this.realizedUsd),+ openValueUsd: round(openValueUsd),+ equityUsd: round(this.realizedUsd + openValueUsd),+ })+ }++ private rolloverDay(now: number): void {+ const day = utcDayStart(now)+ if (day !== this.spentDay) {+ this.spentDay = day+ this.spentTodayUsd = 0+ }+ }++ /** Live status snapshot for the dashboard API. */+ status(): AgentStatus {+ const openValueUsd = this.openValueUsd()+ return {+ id: this.id,+ strategy: this.strategy.id,+ mode: this.mode,+ running: this.running,+ killed: this.kill.isKilled(),+ limits: this.risk.riskLimits,+ spentTodayUsd: round(this.spentTodayUsd),+ realizedUsd: round(this.realizedUsd),+ openValueUsd: round(openValueUsd),+ equityUsd: round(this.realizedUsd + openValueUsd),+ positions: [...this.positions.values()],+ lastTickAt: this.lastTickAt,+ lastError: this.lastError,+ ticks: this.ticks,+ trades: this.trades,+ refusals: this.refusals,+ }+ }+}++function round(n: number): number {+ return Math.round(n * 1e6) / 1e6+}diff --git a/robinhood/hood-traders/src/framework/fleet.ts b/robinhood/hood-traders/src/framework/fleet.tsnew file mode 100644index 000000000..19eba7c55--- /dev/null+++ b/robinhood/hood-traders/src/framework/fleet.ts@@ -0,0 +1,145 @@+import { privateKeyToAccount } from 'viem/accounts'+import type { Account } from 'viem'+import { Agent } from './agent.js'+import type { FleetConfig } from './config.js'+import { Journal } from './journal.js'+import { KillSwitch } from './kill.js'+import { Market } from './market.js'+import { utcDayStart } from './risk.js'+import type { Strategy } from './strategy.js'+import type { AgentStatus, Mode, RiskLimits } from './types.js'++/** Definition of one agent within a fleet. */+export interface AgentSpec {+ id: string+ strategy: Strategy+ /** Overrides merged over the fleet default limits. */+ limits?: Partial<RiskLimits>+ tickIntervalMs?: number+}++/** Aggregate fleet numbers for the dashboard header. */+export interface FleetSummary {+ network: string+ mode: Mode+ killed: boolean+ killReason: string | null+ fleetSpentTodayUsd: number+ fleetMaxDailySpendUsdg: number+ realizedUsd: number+ openValueUsd: number+ equityUsd: number+ agents: number+ startedAt: number+}++/**+ * The fleet: owns the shared market client, journal, and kill switch, then runs+ * a set of agents against them and tracks the global daily-spend budget. It is+ * the process-level object the dashboard server reads and the kill switch acts+ * on.+ */+export class Fleet {+ readonly config: FleetConfig+ readonly journal: Journal+ readonly kill: KillSwitch+ readonly market: Market+ private readonly account: Account | null+ private readonly agents: Agent[] = []+ private fleetSpentTodayUsd = 0+ private spentDay = 0+ private startedAt = 0++ constructor(config: FleetConfig) {+ this.config = config+ this.account = config.privateKey ? privateKeyToAccount(config.privateKey) : null+ this.journal = new Journal(config.dbPath)+ this.kill = new KillSwitch(config.killFile)+ this.market = new Market(config, this.account ?? undefined)+ }++ /** Build agents from specs. */+ addAgents(specs: AgentSpec[]): void {+ for (const spec of specs) {+ const limits: RiskLimits = { ...this.config.defaultLimits, ...spec.limits }+ this.agents.push(+ new Agent({+ id: spec.id,+ strategy: spec.strategy,+ market: this.market,+ limits,+ journal: this.journal,+ kill: this.kill,+ mode: this.config.mode,+ account: this.account,+ fleetMaxDailySpendUsdg: this.config.fleetMaxDailySpendUsdg,+ fleetSpentTodayUsd: () => this.currentFleetSpend(),+ reportFleetSpend: (usd) => this.recordFleetSpend(usd),+ tickIntervalMs: spec.tickIntervalMs ?? 5000,+ }),+ )+ }+ }++ private currentFleetSpend(now = Date.now()): number {+ const day = utcDayStart(now)+ if (day !== this.spentDay) {+ this.spentDay = day+ this.fleetSpentTodayUsd = 0+ }+ return this.fleetSpentTodayUsd+ }++ private recordFleetSpend(usd: number): void {+ this.currentFleetSpend()+ this.fleetSpentTodayUsd += usd+ }++ /** Arm the kill switch and start every agent's loop. */+ async start(): Promise<void> {+ this.startedAt = Date.now()+ this.kill.arm()+ await Promise.all(this.agents.map((a) => a.start()))+ }++ /** Stop all agents (kill switch stays tripped if it was). */+ stop(): void {+ for (const a of this.agents) a.stop()+ }++ /** Trip the kill switch — halts new orders across the fleet. */+ tripKill(reason: string): void {+ this.kill.trip(reason)+ }++ agentStatuses(): AgentStatus[] {+ return this.agents.map((a) => a.status())+ }++ summary(): FleetSummary {+ const statuses = this.agentStatuses()+ return {+ network: this.config.network,+ mode: this.config.mode,+ killed: this.kill.isKilled(),+ killReason: this.kill.killReason(),+ fleetSpentTodayUsd: round(this.currentFleetSpend()),+ fleetMaxDailySpendUsdg: this.config.fleetMaxDailySpendUsdg,+ realizedUsd: round(statuses.reduce((s, a) => s + a.realizedUsd, 0)),+ openValueUsd: round(statuses.reduce((s, a) => s + a.openValueUsd, 0)),+ equityUsd: round(statuses.reduce((s, a) => s + a.equityUsd, 0)),+ agents: this.agents.length,+ startedAt: this.startedAt,+ }+ }++ close(): void {+ this.stop()+ this.kill.dispose()+ this.journal.close()+ }+}++function round(n: number): number {+ return Math.round(n * 1e6) / 1e6+}diff --git a/robinhood/hood-traders/src/strategies/launch-sniper.ts b/robinhood/hood-traders/src/strategies/launch-sniper.tsnew file mode 100644index 000000000..de38b2871--- /dev/null+++ b/robinhood/hood-traders/src/strategies/launch-sniper.ts@@ -0,0 +1,229 @@+import { erc20Abi, watchLaunches, type Launch } from 'hoodchain'+import { formatUnits, parseEther, type Address } from 'viem'+import type {+ Strategy,+ StrategyMeta,+ StrategyStartContext,+ StrategyTickContext,+} from '../framework/strategy.js'+import type { Decision, Intent, Alert } from '../framework/types.js'++/** Tunables for {@link LaunchSniper}. */+export interface LaunchSniperParams {+ /** WETH spent per entry. */+ entryWeth: number+ /** Take profit as a fraction (0.5 = +50%). */+ takeProfitPct: number+ /** Stop loss as a fraction (0.3 = -30%). */+ stopLossPct: number+ /** Force-exit a position after this many seconds regardless of PnL. */+ maxHoldSeconds: number+ /** Reject a launch if the deployer still holds more than this fraction of supply. */+ maxDeployerPct: number+ /** Reject if an immediate buy→sell round trip would lose more than this fraction (honeypot/thin-pool guard). */+ maxRoundTripLossPct: number+ /** Only consider launches at most this many seconds old when first seen. */+ maxLaunchAgeSeconds: number+}++const DEFAULTS: LaunchSniperParams = {+ entryWeth: 0.01,+ takeProfitPct: 0.6,+ stopLossPct: 0.35,+ maxHoldSeconds: 30 * 60,+ maxDeployerPct: 0.15,+ maxRoundTripLossPct: 0.35,+ maxLaunchAgeSeconds: 5 * 60,+}++interface Candidate {+ launch: Launch+ seenAt: number+}++/**+ * launch-sniper — enter brand-new launchpad coins that clear objective safety+ * filters, then exit on take-profit, stop, or a hard time limit.+ *+ * EDGE HYPOTHESIS: the first minutes after a NOXA instant-listing are the most+ * information-rich and most volatile window a memecoin ever has. A disciplined+ * buyer who (a) only touches tokens that are actually round-trippable (not+ * honeypots) and whose deployer is not sitting on the supply, and (b) exits+ * mechanically instead of falling in love, harvests a slice of that opening+ * volatility. The edge is speed + discipline, not prediction.+ *+ * FAILURE MODES: most new launches go to zero — the stop loss WILL fire often+ * and the strategy is negative-carry unless the winners pay for the losers.+ * Honeypots evolve (sell-tax toggled AFTER you buy); the round-trip check only+ * sees the state at entry. Odyssey tokens on the bonding curve have no Uniswap+ * pool yet, so they are skipped until graduation — this strategy is really a+ * NOXA/graduated-pool sniper. Paper fills assume the QuoterV2 mid; a real+ * sniper competes with faster bots and eats worse fills.+ */+export class LaunchSniper implements Strategy {+ readonly id = 'launch-sniper'+ readonly title = 'Launch Sniper'+ readonly quote = 'weth' as const+ private readonly p: LaunchSniperParams+ private readonly queue: Candidate[] = []+ private readonly seen = new Set<string>()+ private unwatch: (() => void) | null = null++ constructor(params: Partial<LaunchSniperParams> = {}) {+ this.p = { ...DEFAULTS, ...params }+ }++ get meta(): StrategyMeta {+ return {+ edge:+ 'Harvest opening-minutes volatility of freshly launched memecoins by buying only round-trippable, ' ++ 'non-deployer-heavy launches and exiting mechanically on TP/stop/time.',+ failureModes: [+ 'Most launches trend to zero — the stop loss fires frequently; profitability depends on winners covering losers.',+ 'Honeypots can enable a sell tax AFTER entry; the entry-time round-trip check cannot see that.',+ 'Odyssey bonding-curve tokens have no Uniswap pool pre-graduation and are skipped (this is effectively a NOXA sniper).',+ 'Paper fills use the QuoterV2 mid; live, faster bots win the best fills and you eat slippage.',+ ],+ params: { ...this.p },+ }+ }++ start(ctx: StrategyStartContext): void {+ // Real-time launch subscription across NOXA + The Odyssey.+ this.unwatch = watchLaunches(+ ctx.market.client,+ (launch) => {+ const key = launch.token.toLowerCase()+ if (this.seen.has(key)) return+ this.seen.add(key)+ this.queue.push({ launch, seenAt: Date.now() })+ ctx.log(`new launch queued: ${launch.launchpad} ${launch.token}`, { creator: launch.creator })+ },+ { onError: (e) => ctx.log(`launch watcher error: ${e.message}`) },+ )+ }++ stop(): void {+ this.unwatch?.()+ this.unwatch = null+ }++ async tick(ctx: StrategyTickContext): Promise<Decision> {+ const intents: Intent[] = []+ const alerts: Alert[] = []++ // ── exits first (protect open risk before taking on more) ──────────────────+ for (const pos of ctx.positions) {+ const ageSec = (ctx.now - pos.openedAt) / 1000+ const pnlPct = pos.markUsd !== null && pos.investedUsd > 0 ? pos.markUsd / pos.investedUsd - 1 : null+ let exitReason: string | null = null+ if (pnlPct !== null && pnlPct >= this.p.takeProfitPct) exitReason = `take-profit ${(pnlPct * 100).toFixed(1)}%`+ else if (pnlPct !== null && pnlPct <= -this.p.stopLossPct) exitReason = `stop-loss ${(pnlPct * 100).toFixed(1)}%`+ else if (ageSec >= this.p.maxHoldSeconds) exitReason = `time-exit ${Math.round(ageSec)}s held`+ if (exitReason) {+ intents.push({+ side: 'sell',+ token: pos.token,+ tokenSymbol: pos.tokenSymbol,+ amountIn: pos.amount,+ quoteToken: pos.quoteToken,+ quoteSymbol: pos.quoteSymbol,+ reason: exitReason,+ meta: { pnlPct },+ })+ }+ }++ // ── one new entry per tick (evaluate the oldest queued candidate) ──────────+ const candidate = this.queue.shift()+ if (candidate) {+ const decisionOrReject = await this.evaluate(ctx, candidate)+ if (decisionOrReject.intent) intents.push(decisionOrReject.intent)+ else if (decisionOrReject.alert) alerts.push(decisionOrReject.alert)+ }++ return { intents, alerts }+ }++ private async evaluate(+ ctx: StrategyTickContext,+ candidate: Candidate,+ ): Promise<{ intent?: Intent; alert?: Alert }> {+ const { launch } = candidate+ const ageSec = (ctx.now - candidate.seenAt) / 1000+ if (ageSec > this.p.maxLaunchAgeSeconds) {+ return { alert: { level: 'info', message: `skip ${launch.token}: stale (${Math.round(ageSec)}s old)`, meta: {} } }+ }+ // already holding it?+ if (ctx.positions.some((p) => p.token.toLowerCase() === launch.token.toLowerCase())) return {}++ const amountIn = parseEther(String(this.p.entryWeth))++ // Filter 1 — route exists (Odyssey pre-graduation tokens fail here and are skipped).+ const buyQuote = await ctx.market.quoteBuy(ctx.quoteToken, launch.token, amountIn)+ if (!buyQuote || buyQuote.amountOut <= 0n) {+ return { alert: { level: 'info', message: `skip ${launch.token}: no liquid Uniswap route`, meta: { launchpad: launch.launchpad } } }+ }++ // Filter 2 — round-trip retention (honeypot / thin-pool guard).+ const sellQuote = await ctx.market.quoteSell(launch.token, ctx.quoteToken, buyQuote.amountOut)+ if (!sellQuote || sellQuote.amountOut <= 0n) {+ return { alert: { level: 'warn', message: `skip ${launch.token}: cannot sell back (honeypot?)`, meta: {} } }+ }+ const retention = Number(sellQuote.amountOut) / Number(amountIn)+ if (1 - retention > this.p.maxRoundTripLossPct) {+ return {+ alert: {+ level: 'warn',+ message: `skip ${launch.token}: round-trip loss ${((1 - retention) * 100).toFixed(1)}% > ${(this.p.maxRoundTripLossPct * 100).toFixed(0)}%`,+ meta: { retention },+ },+ }+ }++ // Filter 3 — deployer concentration.+ const deployerPct = await this.deployerConcentration(ctx, launch)+ if (deployerPct !== null && deployerPct > this.p.maxDeployerPct) {+ return {+ alert: {+ level: 'warn',+ message: `skip ${launch.token}: deployer holds ${(deployerPct * 100).toFixed(1)}% > ${(this.p.maxDeployerPct * 100).toFixed(0)}%`,+ meta: { deployerPct },+ },+ }+ }++ return {+ intent: {+ side: 'buy',+ token: launch.token,+ tokenSymbol: shortToken(launch.token),+ amountIn,+ quoteToken: ctx.quoteToken,+ quoteSymbol: ctx.quoteSymbol,+ reason: `sniped ${launch.launchpad} launch — retention ${(retention * 100).toFixed(1)}%, deployer ${deployerPct === null ? 'n/a' : (deployerPct * 100).toFixed(1) + '%'}`,+ meta: { launchpad: launch.launchpad, deployerPct, retention },+ },+ }+ }++ private async deployerConcentration(ctx: StrategyTickContext, launch: Launch): Promise<number | null> {+ try {+ const [supply, bal] = await ctx.market.client.public.multicall({+ contracts: [+ { address: launch.token, abi: erc20Abi, functionName: 'totalSupply' as const },+ { address: launch.token, abi: erc20Abi, functionName: 'balanceOf' as const, args: [launch.creator] as const },+ ],+ allowFailure: false,+ })+ if ((supply as bigint) === 0n) return null+ return Number(formatUnits((bal as bigint) * 10_000n / (supply as bigint), 4))+ } catch {+ return null+ }+ }+}++function shortToken(addr: Address): string {+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`+}diff --git a/robinhood/hood402/facilitator/package.json b/robinhood/hood402/facilitator/package.jsonnew file mode 100644index 000000000..be9bbd047--- /dev/null+++ b/robinhood/hood402/facilitator/package.json@@ -0,0 +1,34 @@+{+ "name": "hood402-facilitator",+ "version": "0.1.0",+ "description": "Self-hostable x402 facilitator for USDG on Robinhood Chain — verify + settle endpoints, idempotent SQLite ledger, metrics. Built on the hood402 protocol package.",+ "keywords": ["x402", "facilitator", "robinhood-chain", "usdg", "eip-3009"],+ "license": "MIT",+ "author": "nirholas (https://x.com/nichxbt)",+ "type": "module",+ "engines": {+ "node": ">=22"+ },+ "bin": {+ "hood402-facilitator": "./dist/index.js"+ },+ "main": "./dist/server.js",+ "files": ["dist", "README.md"],+ "scripts": {+ "build": "tsc -p tsconfig.json",+ "dev": "tsx watch src/index.ts",+ "start": "node --no-warnings=ExperimentalWarning dist/index.js",+ "typecheck": "tsc --noEmit"+ },+ "dependencies": {+ "express": "^4.21.2",+ "hood402": "file:..",+ "viem": "^2.55.0"+ },+ "devDependencies": {+ "@types/express": "^4.17.21",+ "@types/node": "^22.10.2",+ "tsx": "^4.19.2",+ "typescript": "^5.7.2"+ }+}diff --git a/robinhood/hood402/facilitator/src/config.ts b/robinhood/hood402/facilitator/src/config.tsnew file mode 100644index 000000000..7b77a1f38--- /dev/null+++ b/robinhood/hood402/facilitator/src/config.ts@@ -0,0 +1,68 @@+import {+ createPublicClient,+ createWalletClient,+ http,+ type PublicClient,+ type WalletClient,+} from 'viem'+import { privateKeyToAccount } from 'viem/accounts'+import { NETWORKS, requireNetwork, type HoodNetwork } from 'hood402'++export interface NetworkRuntime {+ net: HoodNetwork+ publicClient: PublicClient+ walletClient: WalletClient+}++export interface FacilitatorConfig {+ port: number+ ledgerPath: string+ signerAddress: `0x${string}`+ runtimes: Map<string, NetworkRuntime>+}++function rpcFor(net: HoodNetwork): string {+ const key = net.testnet ? 'ROBINHOOD_TESTNET_RPC_URL' : 'ROBINHOOD_RPC_URL'+ return process.env[key] ?? net.rpcUrl+}++/** Load configuration from the environment, building a viem runtime per network. */+export function loadConfig(env: NodeJS.ProcessEnv = process.env): FacilitatorConfig {+ const pk = env['FACILITATOR_PRIVATE_KEY']+ if (!pk || !/^0x[0-9a-fA-F]{64}$/.test(pk)) {+ throw new Error(+ 'hood402-facilitator: FACILITATOR_PRIVATE_KEY must be a 0x-prefixed 32-byte hex private key',+ )+ }+ const account = privateKeyToAccount(pk as `0x${string}`)++ const requested = (env['FACILITATOR_NETWORKS'] ?? 'robinhood,robinhood-testnet')+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean)++ const runtimes = new Map<string, NetworkRuntime>()+ for (const id of requested) {+ const net = requireNetwork(id)+ if (runtimes.has(net.id)) continue+ const rpc = rpcFor(net)+ const publicClient = createPublicClient({ chain: net.chain, transport: http(rpc) })+ const walletClient = createWalletClient({ account, chain: net.chain, transport: http(rpc) })+ runtimes.set(net.id, { net, publicClient, walletClient })+ }+ if (runtimes.size === 0) {+ throw new Error('hood402-facilitator: no networks configured (set FACILITATOR_NETWORKS)')+ }++ return {+ port: Number(env['PORT'] ?? 4021),+ ledgerPath: env['LEDGER_PATH'] ?? './data/hood402-ledger.sqlite',+ signerAddress: account.address,+ runtimes,+ }+}++/** All networks the facilitator can settle on, for `/supported`. */+export function supportedNetworks(): readonly HoodNetwork[] {+ return NETWORKS+}diff --git a/robinhood/hood402/facilitator/src/ledger.ts b/robinhood/hood402/facilitator/src/ledger.tsnew file mode 100644index 000000000..4d02ea200--- /dev/null+++ b/robinhood/hood402/facilitator/src/ledger.ts@@ -0,0 +1,139 @@+import { DatabaseSync } from 'node:sqlite'+import { mkdirSync } from 'node:fs'+import { dirname } from 'node:path'++export type SettlementStatus = 'pending' | 'settled' | 'failed'++export interface SettlementRow {+ id: string+ network: string+ payer: string+ pay_to: string+ amount: string+ nonce: string+ tx_hash: string | null+ status: SettlementStatus+ reason: string | null+ created_at: number+ updated_at: number+}++/**+ * Idempotent settlement ledger backed by SQLite (`node:sqlite`, no native+ * dependency). The unique key `(network, payer, nonce)` maps 1:1 to an EIP-3009+ * authorization, so a retried `/settle` for the same signed payment returns the+ * original transaction instead of broadcasting twice.+ */+export class Ledger {+ private readonly db: DatabaseSync++ constructor(path: string, clock: () => number = () => Date.now()) {+ if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true })+ this.db = new DatabaseSync(path)+ this.clock = clock+ this.db.exec(`+ CREATE TABLE IF NOT EXISTS settlements (+ id TEXT PRIMARY KEY,+ network TEXT NOT NULL,+ payer TEXT NOT NULL,+ pay_to TEXT NOT NULL,+ amount TEXT NOT NULL,+ nonce TEXT NOT NULL,+ tx_hash TEXT,+ status TEXT NOT NULL,+ reason TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ UNIQUE (network, payer, nonce)+ );+ CREATE INDEX IF NOT EXISTS idx_settlements_status ON settlements(status);+ `)+ }++ private readonly clock: () => number++ static key(network: string, payer: string, nonce: string): string {+ return `${network}:${payer.toLowerCase()}:${nonce.toLowerCase()}`+ }++ find(network: string, payer: string, nonce: string): SettlementRow | undefined {+ const row = this.db+ .prepare('SELECT * FROM settlements WHERE id = ?')+ .get(Ledger.key(network, payer, nonce))+ return row as SettlementRow | undefined+ }++ /**+ * Atomically claim a settlement slot. Returns `{ claimed: true }` if this+ * caller now owns the broadcast, or `{ claimed: false, existing }` if another+ * request already recorded this authorization.+ */+ claim(input: {+ network: string+ payer: string+ payTo: string+ amount: string+ nonce: string+ }): { claimed: true } | { claimed: false; existing: SettlementRow } {+ const id = Ledger.key(input.network, input.payer, input.nonce)+ const now = this.clock()+ try {+ this.db+ .prepare(+ `INSERT INTO settlements (id, network, payer, pay_to, amount, nonce, tx_hash, status, reason, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, NULL, 'pending', NULL, ?, ?)`,+ )+ .run(+ id,+ input.network,+ input.payer.toLowerCase(),+ input.payTo.toLowerCase(),+ input.amount,+ input.nonce.toLowerCase(),+ now,+ now,+ )+ return { claimed: true }+ } catch {+ // UNIQUE violation — someone already claimed it.+ const existing = this.db.prepare('SELECT * FROM settlements WHERE id = ?').get(id)+ return { claimed: false, existing: existing as SettlementRow }+ }+ }++ markSettled(network: string, payer: string, nonce: string, txHash: string): void {+ this.db+ .prepare(+ `UPDATE settlements SET status = 'settled', tx_hash = ?, reason = NULL, updated_at = ? WHERE id = ?`,+ )+ .run(txHash, this.clock(), Ledger.key(network, payer, nonce))+ }++ markFailed(network: string, payer: string, nonce: string, reason: string): void {+ this.db+ .prepare(`UPDATE settlements SET status = 'failed', reason = ?, updated_at = ? WHERE id = ?`)+ .run(reason, this.clock(), Ledger.key(network, payer, nonce))+ }++ /** Aggregate counters for the metrics endpoint. */+ counts(): Record<SettlementStatus, number> {+ const rows = this.db+ .prepare('SELECT status, COUNT(*) as n FROM settlements GROUP BY status')+ .all() as Array<{ status: SettlementStatus; n: number }>+ const out: Record<SettlementStatus, number> = { pending: 0, settled: 0, failed: 0 }+ for (const r of rows) out[r.status] = r.n+ return out+ }++ /** Total USDG settled, in atomic units, as a string. */+ totalSettledAtomic(): string {+ const row = this.db+ .prepare(`SELECT COALESCE(SUM(CAST(amount AS INTEGER)), 0) as total FROM settlements WHERE status = 'settled'`)+ .get() as { total: number | bigint }+ return String(row.total)+ }++ close(): void {+ this.db.close()+ }+}diff --git a/robinhood/hood402/facilitator/tsconfig.json b/robinhood/hood402/facilitator/tsconfig.jsonnew file mode 100644index 000000000..fcd5b78d2--- /dev/null+++ b/robinhood/hood402/facilitator/tsconfig.json@@ -0,0 +1,18 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "lib": ["ES2022"],+ "strict": true,+ "exactOptionalPropertyTypes": true,+ "noUncheckedIndexedAccess": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "declaration": false,+ "outDir": "dist",+ "rootDir": "src",+ "types": ["node"]+ },+ "include": ["src"]+}diff --git a/robinhood/hood402/src/client/index.ts b/robinhood/hood402/src/client/index.tsnew file mode 100644index 000000000..181f98327--- /dev/null+++ b/robinhood/hood402/src/client/index.ts@@ -0,0 +1,277 @@+/**+ * hood402/client — a fetch wrapper that pays x402 challenges automatically.+ *+ * On a 402 it selects a USDG requirement, signs an EIP-3009+ * `TransferWithAuthorization` (gasless — the facilitator pays gas), and retries+ * with the `X-PAYMENT` header. Enforces a hard per-origin spend cap and caches+ * discovered prices so repeat calls skip the extra round-trip.+ *+ * Works in Node and the browser: pass a viem `LocalAccount` (private key) or a+ * `WalletClient` wired to an injected wallet.+ */+import {+ formatUnits,+ getAddress,+ parseUnits,+ type Account,+ type Address,+ type Hex,+ type TypedDataDomain,+ type WalletClient,+} from 'viem'+import { requireNetwork, type HoodNetwork } from '../networks.js'+import { SpendCapExceededError } from '../errors.js'+import { PAYMENT_HEADER, PAYMENT_RESPONSE_HEADER } from '../challenge.js'+import { decodeSettlementHeader, encodePaymentHeader } from '../scheme/encoding.js'+import {+ TRANSFER_WITH_AUTHORIZATION_TYPES,+ randomNonce,+ usdgDomain,+} from '../scheme/exact.js'+import type {+ ExactEvmAuthorization,+ PaymentPayload,+ PaymentRequiredResponse,+ PaymentRequirements,+ SettleResult,+} from '../types.js'+import { SCHEME, X402_VERSION } from '../types.js'++/** A minimal typed-data signer. A viem `LocalAccount` satisfies this directly. */+export interface Signer {+ address: Address+ signTypedData(params: {+ domain: TypedDataDomain+ types: typeof TRANSFER_WITH_AUTHORIZATION_TYPES+ primaryType: 'TransferWithAuthorization'+ message: ExactEvmAuthorization & { value: bigint; validAfter: bigint; validBefore: bigint }+ }): Promise<Hex>+}++/** Build a {@link Signer} from a viem `LocalAccount`. */+export function fromAccount(account: Account & { signTypedData: Signer['signTypedData'] }): Signer {+ return { address: getAddress(account.address), signTypedData: (p) => account.signTypedData(p) }+}++/** Build a {@link Signer} from a viem `WalletClient` (e.g. an injected wallet). */+export function fromWalletClient(client: WalletClient, address: Address): Signer {+ return {+ address: getAddress(address),+ signTypedData: (p) =>+ client.signTypedData({+ account: address,+ domain: p.domain,+ types: p.types,+ primaryType: p.primaryType,+ message: p.message,+ }) as Promise<Hex>,+ }+}++export interface Hood402ClientOptions {+ /** The wallet that signs payments. */+ signer: Signer+ /** Hard cap on total spend per origin, in USDG (default `"1.00"`). */+ maxSpendPerOrigin?: string+ /** Only pay on these networks (default: all Robinhood networks). */+ allowedNetworks?: string[]+ /** Underlying fetch (defaults to the global). */+ fetch?: typeof fetch+ /** Validity window of a signed authorization, in seconds (default 300). */+ validitySeconds?: number+ /** Injectable clock (unix seconds) for tests. */+ now?: () => number+}++/** The result of a paid request: the response plus the settlement receipt. */+export interface PaidResponse {+ response: Response+ /** Decoded `X-PAYMENT-RESPONSE`, present when a payment was made. */+ settlement?: SettleResult+ /** Whether a payment was actually required and made. */+ paid: boolean+}++function originOf(url: string): string {+ try {+ return new URL(url).origin+ } catch {+ return url+ }+}++export class Hood402Client {+ private readonly signer: Signer+ private readonly capAtomicPerOrigin: Map<string, bigint> = new Map()+ private readonly spentPerOrigin: Map<string, bigint> = new Map()+ private readonly priceCache: Map<string, PaymentRequirements> = new Map()+ private readonly allowed: Set<string> | undefined+ private readonly fetchImpl: typeof fetch+ private readonly validitySeconds: number+ private readonly now: () => number+ private readonly capHuman: string++ constructor(opts: Hood402ClientOptions) {+ this.signer = opts.signer+ this.capHuman = opts.maxSpendPerOrigin ?? '1.00'+ this.allowed = opts.allowedNetworks ? new Set(opts.allowedNetworks) : undefined+ this.fetchImpl = opts.fetch ?? fetch+ this.validitySeconds = opts.validitySeconds ?? 300+ this.now = opts.now ?? (() => Math.floor(Date.now() / 1000))+ }++ /** Total USDG spent so far against an origin (human string). */+ spent(origin: string): string {+ return formatUnits(this.spentPerOrigin.get(originOf(origin)) ?? 0n, 6)+ }++ private capAtomic(origin: string, net: HoodNetwork): bigint {+ const existing = this.capAtomicPerOrigin.get(origin)+ if (existing !== undefined) return existing+ const cap = parseUnits(this.capHuman, net.usdgDecimals)+ this.capAtomicPerOrigin.set(origin, cap)+ return cap+ }++ private selectRequirement(accepts: PaymentRequirements[]): {+ req: PaymentRequirements+ net: HoodNetwork+ } | null {+ for (const req of accepts) {+ if (req.scheme !== SCHEME) continue+ const net = requireNetworkSafe(req.network)+ if (!net) continue+ if (this.allowed && !this.allowed.has(net.id)) continue+ return { req, net }+ }+ return null+ }++ /** Sign a payment payload for a requirement (does not send it). */+ async sign(req: PaymentRequirements): Promise<PaymentPayload> {+ const net = requireNetwork(req.network)+ const now = this.now()+ const authorization: ExactEvmAuthorization = {+ from: this.signer.address,+ to: getAddress(req.payTo),+ value: req.maxAmountRequired,+ validAfter: String(now - 5),+ validBefore: String(now + this.validitySeconds),+ nonce: randomNonce(),+ }+ const domain = usdgDomain(net)+ const signature = await this.signer.signTypedData({+ domain,+ types: TRANSFER_WITH_AUTHORIZATION_TYPES,+ primaryType: 'TransferWithAuthorization',+ message: {+ ...authorization,+ value: BigInt(authorization.value),+ validAfter: BigInt(authorization.validAfter),+ validBefore: BigInt(authorization.validBefore),+ },+ })+ return {+ x402Version: X402_VERSION,+ scheme: SCHEME,+ network: net.id,+ payload: { signature, authorization },+ }+ }++ private enforceCap(origin: string, net: HoodNetwork, value: bigint): void {+ const cap = this.capAtomic(origin, net)+ const spent = this.spentPerOrigin.get(origin) ?? 0n+ if (spent + value > cap) {+ throw new SpendCapExceededError(+ origin,+ formatUnits(value, net.usdgDecimals),+ formatUnits(cap, net.usdgDecimals),+ )+ }+ }++ /**+ * fetch()-compatible call that transparently pays a 402. Returns the final+ * `Response`. Use {@link fetchWithReceipt} to also get the settlement receipt.+ */+ async fetch(input: string | URL, init?: RequestInit): Promise<Response> {+ return (await this.fetchWithReceipt(input, init)).response+ }++ /** Like {@link fetch} but returns the settlement receipt alongside the response. */+ async fetchWithReceipt(input: string | URL, init?: RequestInit): Promise<PaidResponse> {+ const url = typeof input === 'string' ? input : input.toString()+ const origin = originOf(url)++ // Pre-flight: if we've priced this resource before, pay up front.+ const cached = this.priceCache.get(url)+ if (cached) {+ const paid = await this.payAndSend(url, init, [cached], origin)+ if (paid) return paid+ }++ const res = await this.fetchImpl(url, init)+ if (res.status !== 402) return { response: res, paid: false }++ const body = (await res.clone().json().catch(() => null)) as PaymentRequiredResponse | null+ if (!body || !Array.isArray(body.accepts)) return { response: res, paid: false }++ const paid = await this.payAndSend(url, init, body.accepts, origin)+ return paid ?? { response: res, paid: false }+ }++ private async payAndSend(+ url: string,+ init: RequestInit | undefined,+ accepts: PaymentRequirements[],+ origin: string,+ ): Promise<PaidResponse | null> {+ const selected = this.selectRequirement(accepts)+ if (!selected) return null+ const { req, net } = selected++ const value = BigInt(req.maxAmountRequired)+ this.enforceCap(origin, net, value)++ const payload = await this.sign(req)+ const headers = new Headers(init?.headers)+ headers.set(PAYMENT_HEADER, encodePaymentHeader(payload))++ const response = await this.fetchImpl(url, { ...init, headers })++ // Only count spend + cache the price when the paid request actually succeeded.+ if (response.ok) {+ this.spentPerOrigin.set(origin, (this.spentPerOrigin.get(origin) ?? 0n) + value)+ this.priceCache.set(url, req)+ }++ const settlement =+ decodeSettlementHeader(response.headers.get(PAYMENT_RESPONSE_HEADER)) ?? undefined+ return {+ response,+ paid: response.ok,+ ...(settlement ? { settlement } : {}),+ }+ }+}++function requireNetworkSafe(id: string): HoodNetwork | undefined {+ try {+ return requireNetwork(id)+ } catch {+ return undefined+ }+}++/**+ * Convenience: wrap a fetch implementation so all calls transparently pay.+ * Returns a `fetch`-compatible function.+ */+export function wrapFetch(opts: Hood402ClientOptions): typeof fetch {+ const client = new Hood402Client(opts)+ return ((input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : input+ return client.fetch(url, init)+ }) as typeof fetch+}diff --git a/robinhood/hoodkit/src/react/index.ts b/robinhood/hoodkit/src/react/index.tsnew file mode 100644index 000000000..2c4ce4d57--- /dev/null+++ b/robinhood/hoodkit/src/react/index.ts@@ -0,0 +1,256 @@+import {+ createContext,+ createElement,+ useCallback,+ useContext,+ useEffect,+ useRef,+ useState,+ type ReactNode,+} from 'react'+import type { Address } from 'viem'+import {+ getPortfolio,+ quoteSwap,+ executeSwap,+ type HoodClient,+ type Launch,+ type Portfolio,+ type SwapQuote,+} from 'hoodchain'+import { streamPrices, streamLaunches, type PriceTick } from '../stream/index.js'++/**+ * `hoodkit/react` — SSR-safe React hooks over the streaming + read layers.+ *+ * All subscriptions run inside `useEffect`, so hooks render inert on the server+ * and hydrate on the client. Provide a client via {@link HoodProvider} once, or+ * pass `{ client }` to any hook to override.+ *+ * @packageDocumentation+ */++const HoodContext = createContext<HoodClient | null>(null)++/** Provides a {@link HoodClient} to the hook tree. */+export function HoodProvider(props: { client: HoodClient; children: ReactNode }): ReactNode {+ return createElement(HoodContext.Provider, { value: props.client }, props.children)+}++/** Resolve the active client from an explicit override or the {@link HoodProvider}. */+export function useHoodClient(explicit?: HoodClient): HoodClient {+ const ctx = useContext(HoodContext)+ const client = explicit ?? ctx+ if (!client) {+ throw new Error('hoodkit/react: wrap your app in <HoodProvider client={...}> or pass { client } to the hook')+ }+ return client+}++/** Shared async-state shape returned by the read hooks. */+export interface AsyncState<T> {+ data: T | null+ isLoading: boolean+ error: Error | null+}++/** Options accepted by every hook: an optional client override. */+export interface HookOptions {+ client?: HoodClient+}++/**+ * Live Chainlink price for one Stock Token. Updates whenever the feed's round+ * advances. Returns `{ data, isLoading, error }`.+ *+ * @example+ * ```tsx+ * const { data } = useQuote('AAPL')+ * return <span>{data ? `$${data.priceUsd.toFixed(2)}` : '—'}</span>+ * ```+ */+export function useQuote(symbol: string, options: HookOptions & { pollingIntervalMs?: number } = {}): AsyncState<PriceTick> {+ const client = useHoodClient(options.client)+ const [state, setState] = useState<AsyncState<PriceTick>>({ data: null, isLoading: true, error: null })++ useEffect(() => {+ if (!symbol) return+ let active = true+ const stream = streamPrices(client, [symbol], { pollingIntervalMs: options.pollingIntervalMs })+ const offData = stream.on('data', (tick) => {+ if (active) setState({ data: tick, isLoading: false, error: null })+ })+ const offError = stream.on('error', (error) => {+ if (active) setState((s) => ({ ...s, isLoading: false, error }))+ })+ return () => {+ active = false+ offData()+ offError()+ stream.close()+ }+ }, [client, symbol, options.pollingIntervalMs])++ return state+}++/**+ * A wallet's Stock Token portfolio, multiplier-correct. Auto-refreshes on an+ * interval; returns `{ data, isLoading, error, refetch }`.+ */+export function usePortfolio(+ address: Address | undefined,+ options: HookOptions & { refetchIntervalMs?: number } = {},+): AsyncState<Portfolio> & { refetch: () => void } {+ const client = useHoodClient(options.client)+ const [state, setState] = useState<AsyncState<Portfolio>>({ data: null, isLoading: Boolean(address), error: null })+ const [nonce, setNonce] = useState(0)+ const refetch = useCallback(() => setNonce((n) => n + 1), [])++ useEffect(() => {+ if (!address) {+ setState({ data: null, isLoading: false, error: null })+ return+ }+ let active = true+ setState((s) => ({ ...s, isLoading: true }))+ getPortfolio(client, address)+ .then((data) => active && setState({ data, isLoading: false, error: null }))+ .catch((error: Error) => active && setState((s) => ({ ...s, isLoading: false, error })))++ const interval = options.refetchIntervalMs+ ? setInterval(() => {+ getPortfolio(client, address)+ .then((data) => active && setState({ data, isLoading: false, error: null }))+ .catch((error: Error) => active && setState((s) => ({ ...s, error })))+ }, options.refetchIntervalMs)+ : null++ return () => {+ active = false+ if (interval) clearInterval(interval)+ }+ }, [client, address, options.refetchIntervalMs, nonce])++ return { ...state, refetch }+}++/**+ * Live launch feed from NOXA + The Odyssey, newest first, capped at `limit`.+ *+ * @example+ * ```tsx+ * const { launches } = useLaunches({ limit: 20 })+ * ```+ */+export function useLaunches(options: HookOptions & { limit?: number } = {}): { launches: Launch[]; isLoading: boolean; error: Error | null } {+ const client = useHoodClient(options.client)+ const limit = options.limit ?? 50+ const [launches, setLaunches] = useState<Launch[]>([])+ const [isLoading, setIsLoading] = useState(true)+ const [error, setError] = useState<Error | null>(null)++ useEffect(() => {+ let active = true+ const stream = streamLaunches(client)+ const offData = stream.on('data', (launch) => {+ if (!active) return+ setIsLoading(false)+ setLaunches((prev) => [launch, ...prev].slice(0, limit))+ })+ const offError = stream.on('error', (e) => {+ if (active) setError(e)+ })+ return () => {+ active = false+ offData()+ offError()+ stream.close()+ }+ }, [client, limit])++ return { launches, isLoading, error }+}++/** State + actions returned by {@link useSwap}. */+export interface UseSwapResult {+ quote: SwapQuote | null+ isQuoting: boolean+ isSwapping: boolean+ error: Error | null+ txHash: `0x${string}` | null+ /** Fetch a quote for the given swap. */+ getQuote: (args: { tokenIn: Address; tokenOut: Address; amountIn: bigint }) => Promise<SwapQuote | null>+ /** Execute the swap (requires a wallet-backed client). */+ swap: (+ args: { tokenIn: Address; tokenOut: Address; amountIn: bigint },+ swapOptions?: { slippageBps?: number },+ ) => Promise<`0x${string}` | null>+ /** Reset quote/error/tx state. */+ reset: () => void+}++/**+ * A swap action hook: `getQuote` to preview and `swap` to execute. Execution+ * requires a wallet-backed client and, for Stock Token *outputs*, that the+ * client was created with `acknowledgeStockTokenEligibility: true`.+ */+export function useSwap(options: HookOptions = {}): UseSwapResult {+ const client = useHoodClient(options.client)+ const [quote, setQuote] = useState<SwapQuote | null>(null)+ const [isQuoting, setIsQuoting] = useState(false)+ const [isSwapping, setIsSwapping] = useState(false)+ const [error, setError] = useState<Error | null>(null)+ const [txHash, setTxHash] = useState<`0x${string}` | null>(null)+ const mounted = useRef(true)+ useEffect(() => {+ mounted.current = true+ return () => {+ mounted.current = false+ }+ }, [])++ const getQuote = useCallback<UseSwapResult['getQuote']>(+ async (args) => {+ setIsQuoting(true)+ setError(null)+ try {+ const q = await quoteSwap(client, args)+ if (mounted.current) setQuote(q)+ return q+ } catch (e) {+ if (mounted.current) setError(e as Error)+ return null+ } finally {+ if (mounted.current) setIsQuoting(false)+ }+ },+ [client],+ )++ const swap = useCallback<UseSwapResult['swap']>(+ async (args, swapOptions) => {+ setIsSwapping(true)+ setError(null)+ try {+ const { hash } = await executeSwap(client, args, swapOptions)+ if (mounted.current) setTxHash(hash)+ return hash+ } catch (e) {+ if (mounted.current) setError(e as Error)+ return null+ } finally {+ if (mounted.current) setIsSwapping(false)+ }+ },+ [client],+ )++ const reset = useCallback(() => {+ setQuote(null)+ setError(null)+ setTxHash(null)+ }, [])++ return { quote, isQuoting, isSwapping, error, txHash, getQuote, swap, reset }+}diff --git a/robinhood/hoodkit/src/strategy/index.ts b/robinhood/hoodkit/src/strategy/index.tsnew file mode 100644index 000000000..c2223e5e2--- /dev/null+++ b/robinhood/hoodkit/src/strategy/index.ts@@ -0,0 +1,288 @@+import { type Address, type Hash } from 'viem'+import {+ buildSwapTx,+ ensureApproval,+ quoteSwap,+ type HoodClient,+ type SwapQuote,+} from 'hoodchain'+import { streamPrices, type PriceTick, type StreamPollOptions } from '../stream/index.js'++export { Position } from './position.js'+export type { Fill, PnlSnapshot } from './position.js'++/** Thrown when an action would exceed a {@link SpendCap}. */+export class SpendCapExceededError extends Error {+ constructor(+ readonly attempted: bigint,+ readonly remaining: bigint,+ ) {+ super(`spend cap exceeded: attempted ${attempted}, only ${remaining} remaining`)+ this.name = 'SpendCapExceededError'+ }+}++/**+ * A hard cumulative spend limit in the raw units of one token. Every spending+ * primitive here consults a `SpendCap`; once the cap is hit, further spends+ * throw {@link SpendCapExceededError} rather than silently proceeding.+ */+export class SpendCap {+ private spentAmount = 0n+ constructor(readonly cap: bigint) {+ if (cap < 0n) throw new Error('cap must be non-negative')+ }+ /** Amount spent so far. */+ get spent(): bigint {+ return this.spentAmount+ }+ /** Remaining headroom. */+ get remaining(): bigint {+ return this.cap > this.spentAmount ? this.cap - this.spentAmount : 0n+ }+ /** `true` if `amount` still fits under the cap. */+ canSpend(amount: bigint): boolean {+ return this.spentAmount + amount <= this.cap+ }+ /** Reserve `amount`, or throw if it would breach the cap. */+ spend(amount: bigint): void {+ if (!this.canSpend(amount)) throw new SpendCapExceededError(amount, this.remaining)+ this.spentAmount += amount+ }+}++/** Direction of a price crossing. */+export type CrossDirection = 'up' | 'down' | 'any'++/** A fired price-cross event. */+export interface CrossEvent {+ symbol: string+ threshold: number+ direction: 'up' | 'down'+ price: number+ previous: number+}++/**+ * Fire callbacks when Stock Token prices cross thresholds. Wraps+ * {@link streamPrices}; tracks the last price per symbol and emits a+ * {@link CrossEvent} each time a configured threshold is crossed.+ *+ * @example+ * ```ts+ * const triggers = createPriceTriggers(hood)+ * triggers.onCross('AAPL', 250, 'up', (e) => console.log('AAPL broke $250', e.price))+ * // later: triggers.stop()+ * ```+ */+export interface PriceTriggers {+ /** Register a threshold crossing callback. Returns an unsubscribe fn. */+ onCross(symbol: string, threshold: number, direction: CrossDirection, callback: (event: CrossEvent) => void): () => void+ /** Stop the underlying price stream and clear all triggers. */+ stop(): void+}++interface Trigger {+ symbol: string+ threshold: number+ direction: CrossDirection+ callback: (event: CrossEvent) => void+}++/** Create a {@link PriceTriggers} controller over live Stock Token prices. */+export function createPriceTriggers(client: HoodClient, options: StreamPollOptions = {}): PriceTriggers {+ const triggers = new Set<Trigger>()+ const last = new Map<string, number>()+ let stream: ReturnType<typeof streamPrices> | null = null++ function ensureStream(): void {+ if (stream) return+ const symbols = [...new Set([...triggers].map((t) => t.symbol.toUpperCase()))]+ stream = streamPrices(client, symbols, options)+ stream.on('data', (tick: PriceTick) => {+ const prev = last.get(tick.symbol)+ last.set(tick.symbol, tick.priceUsd)+ if (prev === undefined) return+ for (const trigger of triggers) {+ if (trigger.symbol.toUpperCase() !== tick.symbol.toUpperCase()) continue+ const crossedUp = prev < trigger.threshold && tick.priceUsd >= trigger.threshold+ const crossedDown = prev > trigger.threshold && tick.priceUsd <= trigger.threshold+ if ((trigger.direction === 'up' || trigger.direction === 'any') && crossedUp) {+ trigger.callback({ symbol: tick.symbol, threshold: trigger.threshold, direction: 'up', price: tick.priceUsd, previous: prev })+ } else if ((trigger.direction === 'down' || trigger.direction === 'any') && crossedDown) {+ trigger.callback({ symbol: tick.symbol, threshold: trigger.threshold, direction: 'down', price: tick.priceUsd, previous: prev })+ }+ }+ })+ }++ return {+ onCross(symbol, threshold, direction, callback) {+ const trigger: Trigger = { symbol, threshold, direction, callback }+ triggers.add(trigger)+ // Restart the stream so a newly-referenced symbol is polled.+ if (stream) {+ stream.close()+ stream = null+ }+ ensureStream()+ return () => triggers.delete(trigger)+ },+ stop() {+ stream?.close()+ stream = null+ triggers.clear()+ },+ }+}++/** Configuration for a {@link TwapExecutor}. */+export interface TwapConfig {+ tokenIn: Address+ tokenOut: Address+ /** Total input amount to work, in `tokenIn` raw units. */+ totalAmountIn: bigint+ /** Number of equal slices. @defaultValue `4` */+ slices?: number+ /** Delay between slices in ms. @defaultValue `60_000` */+ intervalMs?: number+ /** Per-slice slippage tolerance in basis points. @defaultValue `50` */+ slippageBps?: number+ /** Hard spend cap on `tokenIn`. Defaults to `totalAmountIn`. */+ spendCap?: SpendCap+ /** Kill switch — abort between slices. */+ signal?: AbortSignal+ /**+ * When `true`, quote + build + `eth_call` simulate each slice WITHOUT sending.+ * Defaults to `true` unless the client has a wallet. Set `false` explicitly to+ * send real transactions.+ */+ dryRun?: boolean+ /** Called before each slice; return `false` to skip it. */+ onBeforeSlice?: (slice: TwapSlicePlan) => boolean | Promise<boolean>+ /** Called after each slice with its result. */+ onSlice?: (result: TwapSliceResult) => void+}++/** The plan for one TWAP slice. */+export interface TwapSlicePlan {+ index: number+ total: number+ amountIn: bigint+}++/** The outcome of one TWAP slice. */+export interface TwapSliceResult extends TwapSlicePlan {+ status: 'sent' | 'simulated' | 'skipped' | 'failed'+ quote?: SwapQuote+ amountOutMinimum?: bigint+ hash?: Hash+ error?: string+}++const sleep = (ms: number, signal?: AbortSignal) =>+ new Promise<void>((resolve, reject) => {+ if (signal?.aborted) return reject(new Error('aborted'))+ const timer = setTimeout(resolve, ms)+ signal?.addEventListener('abort', () => {+ clearTimeout(timer)+ reject(new Error('aborted'))+ }, { once: true })+ })++/**+ * Execute a large swap as a Time-Weighted Average Price schedule: split+ * `totalAmountIn` into equal slices spaced `intervalMs` apart, each quoted and+ * slippage-bounded independently. Enforces a hard {@link SpendCap}, honors an+ * `AbortSignal` kill switch between slices, and defaults to **dry-run**+ * (simulate via `eth_call`, send nothing) until you opt into live execution.+ *+ * @example Dry-run a 1000-USDG TWAP over 5 slices+ * ```ts+ * const twap = createTwapExecutor(hood, {+ * tokenIn: usdg, tokenOut: weth, totalAmountIn: parseUsdg('1000'), slices: 5,+ * })+ * const results = await twap.run() // dryRun defaults on with no wallet+ * ```+ */+export interface TwapExecutor {+ /** The slice schedule that will be worked. */+ plan(): TwapSlicePlan[]+ /** Work the schedule; resolves with each slice's result. */+ run(): Promise<TwapSliceResult[]>+}++/** Create a {@link TwapExecutor}. */+export function createTwapExecutor(client: HoodClient, config: TwapConfig): TwapExecutor {+ const slices = Math.max(1, config.slices ?? 4)+ const intervalMs = config.intervalMs ?? 60_000+ const slippageBps = config.slippageBps ?? 50+ const spendCap = config.spendCap ?? new SpendCap(config.totalAmountIn)+ const dryRun = config.dryRun ?? client.wallet === null++ const base = config.totalAmountIn / BigInt(slices)+ const remainder = config.totalAmountIn - base * BigInt(slices)++ function buildPlan(): TwapSlicePlan[] {+ const out: TwapSlicePlan[] = []+ for (let i = 0; i < slices; i++) {+ // Put the rounding remainder on the last slice so the sum is exact.+ const amountIn = i === slices - 1 ? base + remainder : base+ out.push({ index: i, total: slices, amountIn })+ }+ return out+ }++ async function executeSlice(planItem: TwapSlicePlan): Promise<TwapSliceResult> {+ const { index, total, amountIn } = planItem+ try {+ if (config.onBeforeSlice) {+ const proceed = await config.onBeforeSlice(planItem)+ if (!proceed) return { index, total, amountIn, status: 'skipped' }+ }+ if (!spendCap.canSpend(amountIn)) {+ return { index, total, amountIn, status: 'skipped', error: 'spend cap reached' }+ }++ const quote = await quoteSwap(client, { tokenIn: config.tokenIn, tokenOut: config.tokenOut, amountIn })+ const tx = buildSwapTx(client, quote, { slippageBps })++ if (dryRun) {+ // Simulate via eth_call — no state change, no signature.+ await client.public.call({ to: tx.to, data: tx.data, value: tx.value, account: client.account ?? undefined })+ return { index, total, amountIn, status: 'simulated', quote, amountOutMinimum: tx.amountOutMinimum }+ }++ if (!client.wallet || !client.account) throw new Error('live TWAP requires a wallet account on the client')+ await ensureApproval(client, config.tokenIn, amountIn)+ const hash = await client.wallet.sendTransaction({ to: tx.to, data: tx.data, value: tx.value, account: client.account, chain: client.chain })+ await client.public.waitForTransactionReceipt({ hash })+ spendCap.spend(amountIn)+ return { index, total, amountIn, status: 'sent', quote, amountOutMinimum: tx.amountOutMinimum, hash }+ } catch (error) {+ return { index, total, amountIn, status: 'failed', error: error instanceof Error ? error.message : String(error) }+ }+ }++ return {+ plan: buildPlan,+ async run() {+ const plan = buildPlan()+ const results: TwapSliceResult[] = []+ for (let i = 0; i < plan.length; i++) {+ if (config.signal?.aborted) break+ const result = await executeSlice(plan[i] as TwapSlicePlan)+ results.push(result)+ config.onSlice?.(result)+ if (i < plan.length - 1) {+ try {+ await sleep(intervalMs, config.signal)+ } catch {+ break // aborted+ }+ }+ }+ return results+ },+ }+}diff --git a/robinhood/hoodkit/src/strategy/position.ts b/robinhood/hoodkit/src/strategy/position.tsnew file mode 100644index 000000000..49a56884f--- /dev/null+++ b/robinhood/hoodkit/src/strategy/position.ts@@ -0,0 +1,109 @@+/** A single fill fed into a {@link Position}. */+export interface Fill {+ side: 'buy' | 'sell'+ /** Token quantity filled (human units). */+ quantity: number+ /** Execution price per token, in the quote asset (e.g. USD). */+ price: number+ /** Fee paid in the quote asset. @defaultValue `0` */+ fee?: number+ /** Unix seconds. Optional; used only for reporting. */+ timestamp?: number+}++/** A point-in-time PnL snapshot. */+export interface PnlSnapshot {+ quantity: number+ /** Weighted-average cost per token (quote asset). */+ averageCost: number+ /** Realized PnL banked from sells so far (quote asset, fees included). */+ realized: number+ /** Unrealized PnL at `markPrice`. */+ unrealized: number+ /** Position market value at `markPrice`. */+ marketValue: number+ /** realized + unrealized. */+ total: number+ /** Share-equivalent quantity if a multiplier was supplied (else equals `quantity`). */+ shareEquivalent: number+}++/**+ * A multiplier-aware position tracker with weighted-average-cost PnL.+ *+ * PnL is computed in the **quote asset per token**. Robinhood's Chainlink feeds+ * are total-return (already multiplier-adjusted), so comparing average cost per+ * token to the current per-token price is corporate-action correct without+ * re-applying `uiMultiplier` — a reinvested dividend shows up as a price move,+ * captured in unrealized PnL. The multiplier is used only to report+ * share-equivalent quantity.+ */+export class Position {+ private qty = 0+ private avgCost = 0+ private realizedPnl = 0+ /** 1e18-scaled ERC-8056 multiplier for share-equivalent reporting. */+ multiplier: bigint++ constructor(options: { multiplier?: bigint } = {}) {+ this.multiplier = options.multiplier ?? 10n ** 18n+ }++ /** Apply a fill, updating average cost (buys) or banking realized PnL (sells). */+ record(fill: Fill): void {+ const fee = fill.fee ?? 0+ if (fill.quantity <= 0) throw new Error('fill.quantity must be positive')+ if (fill.side === 'buy') {+ const cost = this.avgCost * this.qty + fill.price * fill.quantity + fee+ this.qty += fill.quantity+ this.avgCost = this.qty > 0 ? cost / this.qty : 0+ } else {+ const sold = Math.min(fill.quantity, this.qty)+ this.realizedPnl += (fill.price - this.avgCost) * sold - fee+ this.qty -= sold+ if (this.qty <= 1e-12) {+ this.qty = 0+ this.avgCost = 0+ }+ }+ }++ /** Current token quantity. */+ get quantity(): number {+ return this.qty+ }++ /** Weighted-average cost per token. */+ get averageCost(): number {+ return this.avgCost+ }++ /** Realized PnL banked so far. */+ get realized(): number {+ return this.realizedPnl+ }++ /** Share-equivalent quantity given the current multiplier. */+ get shareEquivalent(): number {+ return (this.qty * Number(this.multiplier)) / 1e18+ }++ /** Unrealized PnL at `markPrice`. */+ unrealized(markPrice: number): number {+ return (markPrice - this.avgCost) * this.qty+ }++ /** Full PnL snapshot at `markPrice`. */+ snapshot(markPrice: number): PnlSnapshot {+ const unrealized = this.unrealized(markPrice)+ return {+ quantity: this.qty,+ averageCost: this.avgCost,+ realized: this.realizedPnl,+ unrealized,+ marketValue: markPrice * this.qty,+ total: this.realizedPnl + unrealized,+ shareEquivalent: this.shareEquivalent,+ }+ }+}diff --git a/robinhood/learn-robinhood-chain/content/01-what-is-robinhood-chain.md b/robinhood/learn-robinhood-chain/content/01-what-is-robinhood-chain.mdnew file mode 100644index 000000000..9bd206ead--- /dev/null+++ b/robinhood/learn-robinhood-chain/content/01-what-is-robinhood-chain.md@@ -0,0 +1,89 @@+Robinhood Chain launched its mainnet on July 1, 2026. In the weeks since, the amount of confident, wrong information written about it has been remarkable. This page is the antidote: the architecture, the chain IDs, and — more importantly — the three facts that every newcomer gets backwards.++Everything here is sourced. Where a claim matters, it links to the [official docs](https://docs.robinhood.com/chain/) or to something you can verify on-chain yourself in the next tutorial.++## The one-paragraph version++Robinhood Chain is a **permissionless [Arbitrum Orbit](https://docs.arbitrum.io/launch-orbit-chain/orbit-gentle-introduction) Layer 2** that settles to Ethereum, posts its data as blobs, and pays gas in **ETH**. Blocks land in roughly 100 milliseconds. It supports [ERC-4337](https://eips.ethereum.org/EIPS/eip-4337) account abstraction. Its headline feature is ~95 **Stock Tokens** — tokenized US equities, each a plain ERC-20 with a Chainlink price feed — plus **USDG**, a dollar stablecoin. That's the whole chain in one breath. The rest of this page is the fine print, and the fine print is where the money and the mistakes are.++## Architecture, precisely++| Property | Value |+| --- | --- |+| Type | Arbitrum Orbit L2 (Nitro stack) |+| Settlement | Ethereum mainnet |+| Data availability | Blobs (EIP-4844) |+| Gas token | **ETH** (not a chain-native token) |+| Block time | ~100 ms |+| Account abstraction | ERC-4337 supported |+| Multicall3 | `0xca11bde05977b3631167028862be2a173976ca11` (canonical) |++Because it's a standard Nitro Orbit chain, **your existing Ethereum tooling just works** — viem, ethers, wagmi, Foundry, Hardhat. There is no exotic SDK you're forced to adopt, no bespoke RPC dialect. That is the single most important practical fact for a developer, and it's why the rest of this course is mostly "normal EVM development, applied well."++### The two networks++You will use both. Reads and demos happen on mainnet; anything that writes, you rehearse on testnet first.++| | Mainnet | Testnet |+| --- | --- | --- |+| Chain ID | **4663** | **46630** |+| RPC | `https://rpc.mainnet.chain.robinhood.com` | `https://rpc.testnet.chain.robinhood.com` |+| Explorer | [robinhoodchain.blockscout.com](https://robinhoodchain.blockscout.com) | [explorer.testnet.chain.robinhood.com](https://explorer.testnet.chain.robinhood.com) |+| Sequencer feed | `wss://feed.mainnet.chain.robinhood.com` | — |+| Faucet | — | [faucet.testnet.chain.robinhood.com](https://faucet.testnet.chain.robinhood.com/) |++:::tip viem ships the chain definitions+As of `[email protected]`, both networks are built in: `import { robinhood, robinhoodTestnet } from 'viem/chains'`. **Never hand-roll the chain config** — you'll get the multicall address or the block explorer wrong and spend an afternoon debugging it. Let viem do it.+:::++## The three facts everyone gets wrong++### 1. There is no chain token. Gas is ETH.++Search social media and you'll find people trading "the Robinhood Chain token," quoting its price, and posting its contract address. **It does not exist.** Robinhood Chain pays gas in bridged ETH, exactly like Arbitrum One or Base. There is no native gas token and no official chain coin.++Anyone showing you a "$HOOD chain token" contract is showing you a memecoin someone permissionlessly deployed *on* the chain — which is allowed and common (see Tutorial 7) — not a token *of* the chain. Internalize this now; it will save you from a scam later.++### 2. Stock Tokens may not be sold to US persons.++This is the fact with legal teeth. Stock Tokens are **tokenized debt securities**, issued by *Robinhood Assets (Jersey) Ltd*. They **may not be offered, sold, or delivered to US persons**, with additional restrictions for Canada, the UK, and Switzerland.++The critical nuance for developers:++- **The restriction is legal and front-end enforced — not enforced at the contract level.** The ERC-20 contracts will happily transfer to anyone. Compliance is your responsibility as the operator of any interface or agent.+- **Reading and displaying Stock Token data is unrestricted.** Prices, supply, someone's holdings — all fair game. Most of this course is reads, and none of it is gated.+- **Any flow that *acquires* a Stock Token needs an eligibility gate.** A buy button, a swap that outputs a Stock Token, an agent that accumulates one — those require a clear disclosure and a geo/eligibility gate, defaulting to *off*.++You'll see this enforced in code in Tutorial 6: the [hoodchain](https://github.com/nirholas/robinhood-chain-sdk) SDK throws a `StockTokenEligibilityError` on any swap that acquires a Stock Token until the operator explicitly affirms eligibility. That default-closed posture is the pattern to copy.++:::warning Not financial or legal advice+This is educational material about a blockchain's mechanics. It is not investment advice, and it is not legal advice about your eligibility. If you operate an interface, get real counsel on your obligations.+:::++### 3. Anyone can deploy. The chain is permissionless.++Robinhood issues the Stock Tokens and runs the sequencer, but the chain itself is open. Anyone can deploy a contract, launch a memecoin, or stand up a DEX pool — and people have. There are already two memecoin launchpads (NOXA and The Odyssey), the full Uniswap v3 stack, 1inch, a zero-fee stock DEX (Arcus), a perps venue (Lighter), and Morpho for lending.++This is why "what's on Robinhood Chain" is a moving target and why on-chain data — token names, memos, listing text — is **untrusted input**. Treat it exactly like user input from the open internet: never render it without escaping, and never let it drive a spend. Tutorial 7 shows you how to read this firehose safely.++## What's actually live++A quick, non-exhaustive map so you know the terrain:++- **Assets** — ~95 Stock Tokens (ERC-20, 18 decimals, one Chainlink feed each) and **USDG** (Paxos Global Dollar, **6 decimals**, no EIP-2612 permit).+- **DEXes / DeFi** — Uniswap v2/v3/v4 + UniswapX (the primary public liquidity), 1inch, Arcus (zero-fee stock DEX), Lighter (perps), Morpho (lending).+- **Launchpads** — NOXA ("NOXA Fun") and The Odyssey, both pump.fun-style, graduating liquidity to Uniswap v3.+- **Data providers** — DefiLlama (`/chain/robinhood-chain`), CoinGecko, GeckoTerminal, Dune, Goldsky, and the Blockscout Pro API already index the chain.++## Where to get canonical addresses++When you need a verified contract address — a Stock Token, USDG, a router — there is exactly one right source order:++1. **[docs.robinhood.com/chain/contracts](https://docs.robinhood.com/chain/contracts)** — the official registry for Stock Token and USDG addresses.+2. **Verify it resolves on Blockscout** before you ship it. An address in a blog post (including this one) is a lead, not a source of truth.++The [hoodchain SDK](https://github.com/nirholas/robinhood-chain-sdk) does this work for you: it ships a checked-in registry of all 95 Stock Tokens, each verified on-chain against the shared `Stock` beacon and mapped to its Chainlink feed, regenerable with one command. You'll use it from Tutorial 2 onward so you never hand-type an address.++## You now know more than most++You understand the architecture, both chain IDs, the no-token fact, the US-person restriction, and that the chain is permissionless and its on-chain data untrusted. That's the mental model. Next, you'll prove the architecture is real by reading the live chain yourself — in about five minutes.diff --git a/robinhood/learn-robinhood-chain/content/02-connect-and-read.md b/robinhood/learn-robinhood-chain/content/02-connect-and-read.mdnew file mode 100644index 000000000..93e8942ee--- /dev/null+++ b/robinhood/learn-robinhood-chain/content/02-connect-and-read.md@@ -0,0 +1,129 @@+Talk is cheap. In the next five minutes you'll connect to Robinhood Chain and pull real data off it — the current block height, the chain ID, and the gas price — with about fifteen lines of code. No wallet, no funds, no signup. Reads are free and public.++## Add the network to a wallet (optional, 60 seconds)++You don't need a wallet for reads, but if you want to poke around a block explorer with a browser wallet, add the network manually. In MetaMask: **Settings → Networks → Add network → Add manually**, then:++```text+Network name: Robinhood Chain+RPC URL: https://rpc.mainnet.chain.robinhood.com+Chain ID: 4663+Currency symbol: ETH+Block explorer: https://robinhoodchain.blockscout.com+```++For anything that spends, use **testnet** (chain ID `46630`, RPC `https://rpc.testnet.chain.robinhood.com`) and claim funds from the [faucet](https://faucet.testnet.chain.robinhood.com/) first.++:::warning The faucet needs a real browser+The testnet faucet is behind Cloudflare Turnstile and Google Sign-In — it can't be scripted. It drips 0.01 ETH plus five of each test Stock Token (TSLA, AMZN, PLTR, NFLX, AMD) per 24 hours. Claim once, up front, and reuse that wallet for every write tutorial. There's also a [Chainlink faucet](https://faucets.chain.link/robinhood-testnet) for testnet LINK/ETH.+:::++## Read the chain with raw JSON-RPC (zero dependencies)++Before any library, prove the RPC is real with nothing but `curl`. This asks the node for its chain ID:++```bash+curl -s https://rpc.mainnet.chain.robinhood.com \+ -H 'content-type: application/json' \+ -d '{"jsonrpc":"2.0","id":1,"method":"eth_chainId","params":[]}'+```++```json+{"jsonrpc":"2.0","id":1,"result":"0x1237"}+```++`0x1237` is `4663` in decimal — the mainnet chain ID. The chain is answering. That's the entire foundation of everything that follows.++:::tip You just saw the landing page's secret+The live stats strip on this site's [home page](../) is doing exactly this — plain `fetch` calls to that same RPC from your browser. Read-only chain access needs no backend, no key, and no SDK. That property is why so much of this course runs client-side.+:::++## Read the chain with viem++`curl` is fine for a sanity check; for real work you want typed results and helpers. Install viem:++```bash+npm init -y+npm install viem+npm pkg set type=module+```++Create `read.ts` (or `.mjs`) and paste:++```ts+import { createPublicClient, http, formatGwei } from 'viem'+import { robinhood } from 'viem/chains'++const client = createPublicClient({+ chain: robinhood, // viem's official chain def — chain ID 4663+ transport: http(), // uses the public RPC from the chain def+})++const [blockNumber, gasPrice, chainId] = await Promise.all([+ client.getBlockNumber(),+ client.getGasPrice(),+ client.getChainId(),+])++console.log(`chain id ${chainId}`)+console.log(`block height ${blockNumber}`)+console.log(`gas price ${formatGwei(gasPrice)} gwei`)+```++Run it:++```bash+npx tsx read.ts+```++```text+chain id 4663+block height 7727411+gas price 0.01 gwei+```++That block number was live when this tutorial was written; yours will be higher, because Robinhood Chain produces a new block roughly every 100 milliseconds. Do the math: **that's on the order of half a million blocks a day.** Keep it in mind when you scan historical logs later — "the last hour" is tens of thousands of blocks.++## Use a faster RPC (when the public one isn't enough)++The public RPC is perfect for learning and light apps, but it rate-limits. The moment you're scanning large block ranges or serving users, move to a dedicated endpoint. Alchemy is the recommended provider:++```ts+const client = createPublicClient({+ chain: robinhood,+ transport: http(`https://robinhood-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_KEY}`),+})+```++You'll feel the difference immediately in Tutorial 7 when scanning launchpad history — the public RPC will return `429 Too Many Requests` on a wide scan; a dedicated key won't.++## Skip the boilerplate: the hoodchain client++Everything above is standard viem. As your app grows you'll want the batteries-included client from the [hoodchain SDK](https://github.com/nirholas/robinhood-chain-sdk) — it wraps viem with multicall batching on by default, both networks pre-wired, and an optional wallet:++```bash+npm install hoodchain viem+```++```ts+import { createHoodClient } from 'hoodchain'++const hood = createHoodClient() // mainnet 4663, public RPC, multicall batching on+console.log('block', await hood.public.getBlockNumber())+```++`hood.public` is a normal viem `PublicClient`, so nothing you learned is wasted — the SDK just removes the setup. From the next tutorial on, we use `createHoodClient` because it also knows about Stock Tokens, feeds, and swaps, which raw viem does not. When you need to drop to the metal, `hood.public` and `hood.wallet` are right there.++## Troubleshooting++**`Cannot use import statement outside a module`** — add `"type": "module"` to your `package.json` (`npm pkg set type=module`), or use the `.mjs` extension.++**`fetch failed` / `ECONNREFUSED`** — check the RPC URL for a typo; it's `rpc.mainnet.chain.robinhood.com`, no port, HTTPS. Confirm you have network access with the `curl` command above.++**`npx tsx` is slow the first time** — `tsx` is being downloaded. Install it once (`npm i -D tsx`) to make subsequent runs instant.++**The block number looks *huge* / grows while you watch** — that's correct. ~100 ms blocks. It's a feature, not a bug.++## What you learned++You connected to Robinhood Chain three ways — raw `curl`, plain viem, and the hoodchain client — and read live data with each. You know reads are free and keyless, why block numbers are enormous, and when to upgrade off the public RPC. Next, the one concept that makes Stock Tokens different from every other ERC-20 you've touched.diff --git a/robinhood/learn-robinhood-chain/content/03-stock-tokens-explained.md b/robinhood/learn-robinhood-chain/content/03-stock-tokens-explained.mdnew file mode 100644index 000000000..c5f1959c5--- /dev/null+++ b/robinhood/learn-robinhood-chain/content/03-stock-tokens-explained.md@@ -0,0 +1,101 @@+If you remember one page from this course, make it this one. Stock Tokens look like ordinary ERC-20s, and 95% of the time they behave like ordinary ERC-20s. It's the other 5% — corporate actions like splits and dividends — that quietly breaks naive integrations and reports the wrong dollar value to a user. Here's exactly how they work, and the one worked example that makes the trap impossible to fall into.++## Anatomy of a Stock Token++A canonical Stock Token on Robinhood Chain is three things bolted together:++1. **A plain ERC-20**, 18 decimals. `balanceOf`, `transfer`, `approve` — all the usual methods, nothing surprising.+2. **A Chainlink price feed** — a separate contract, one per token, exposing `latestRoundData()` and answering with an **8-decimal** USD price.+3. **An [ERC-8056](https://eips.ethereum.org/) `uiMultiplier()`** — a single function returning a `1e18`-scaled ratio that encodes every corporate action the underlying stock has had.++Every canonical Stock Token proxies to one shared `Stock` beacon contract, which is how the [hoodchain SDK](https://github.com/nirholas/robinhood-chain-sdk) verifies that an address is a *real* Stock Token and not a lookalike: it checks the EIP-1967 beacon slot points at that one shared beacon.++## The multiplier, and why it exists++Stocks split. They pay dividends. A traditional token would handle a 2-for-1 split by *rebasing* — doubling everyone's balance overnight. Rebasing tokens are notoriously hostile to integrators: your cached balances silently go wrong, and every DeFi protocol that holds the token has to special-case it.++Robinhood Chain took the other path. **Balances never change from corporate actions.** Instead, `uiMultiplier()` moves. It's the shares-per-token ratio, scaled by `1e18`:++- `1000000000000000000` (i.e. `1e18`) → 1 token represents 1 share. This is the starting state for every token.+- After a reinvested dividend or a split adjustment, it rises above `1e18`. Your token balance is unchanged; each token now represents *more than one share* of economic exposure.++So a Stock Token has **two different quantities** you can ask about, and they answer different questions:++| Quantity | Formula | Answers |+| --- | --- | --- |+| Token balance | `balanceOf(you)` | "How many tokens do I hold?" |+| Share-equivalent | `balance × uiMultiplier ÷ 1e18` | "How many shares of the stock is that?" |++## The trap: which number do you multiply by the price?++Here's where integrations break. You have a token balance, a multiplier, and a Chainlink price. To get a USD value, which do you multiply?++The instinct — and it's wrong — is: *shares × price*. That is, `balance × multiplier × price`. It feels right ("value = number of shares times price per share"), and it produces a number that looks plausible. After a corporate action, it is **too high**, because you've counted the multiplier twice.++**The reason:** Robinhood's Chainlink feeds are **already multiplier-adjusted**. The feed for a Stock Token returns the total-return price of *one token*, not the price of one underlying share. The corporate action is baked into the feed answer. So:++:::danger The rule, memorize it+**USD value = token balance × feed price. Nothing else.**+The feed price already includes the multiplier. Applying `uiMultiplier` to the *value* double-counts every split and dividend. Use `uiMultiplier` only to report **share-equivalents** to a human — never in a valuation.+:::++## A worked example++Suppose a token has had a corporate action, so its multiplier is `1.5e18` (each token now represents 1.5 shares). You hold 10 tokens. The Chainlink feed answers `20000000000` — that's `$200.00` at 8 decimals, and remember, that's the price of one *token*.++**Wrong (double-counts the multiplier):**++```ts+const shares = balance * multiplier / 10n ** 18n // 10 × 1.5 = 15 "shares"+const wrongUsd = shares * feedPriceUsd // 15 × $200 = $3,000 ❌+```++**Right (feed price is per token, already adjusted):**++```ts+const rightUsd = balanceTokens * feedPriceUsd // 10 × $200 = $2,000 ✅+```++The wrong version overstates the position by exactly the multiplier — a 50% error here. On a real portfolio dashboard that's the difference between a user trusting your app and closing it forever. And the share count itself is still useful — you'd show "10 tokens ≈ 15 shares" as context — you just don't put it in the dollar math.++:::tip The feed answer isn't stale on weekends — it's closed+Stock feeds update 24/5, following market hours. Read one on a Saturday and its `updatedAt` will be Friday's close. That is **not** a stale feed; it's a closed market. A staleness check with a one-hour window will reject every weekend read. Use a window that tolerates the weekend gap (~72 hours), and tighten it only during market hours if you need to. The hoodchain SDK defaults to a 72-hour window for exactly this reason.+:::++## Doing it correctly, with the SDK++The [hoodchain SDK](https://github.com/nirholas/robinhood-chain-sdk) encodes all of the above so you don't have to. Here's the whole thing, correct by construction:++```ts+import { createHoodClient, getQuote, getMultiplier } from 'hoodchain'++const hood = createHoodClient()++// getQuote returns the multiplier-adjusted price of ONE TOKEN+const quote = await getQuote(hood, 'AAPL', { maxAgeSeconds: 7 * 24 * 60 * 60 })+console.log(`AAPL token price: $${quote.priceUsd}`) // e.g. $315.50++// getMultiplier is the shares-per-token ratio — for display, not valuation+const m = await getMultiplier(hood, 'AAPL')+console.log(`1 AAPL token = ${Number(m) / 1e18} shares`) // e.g. 1.0+```++`getQuote` also runs the staleness guard, validates the answer is positive and the round is complete, and throws a typed `StaleFeedError` / `InvalidFeedAnswerError` / `FeedNotFoundError` you can catch precisely. `getPortfolio` (Tutorial 5) applies the valuation rule across every holding and even cross-checks its share math against the token's own on-chain `balanceOfUI()`.++## Not every token has a feed++There are 95 Stock Tokens on-chain but Chainlink's public directory currently lists feeds for a **subset** — 34 at the time of writing. A token without a feed can still have its balance read; it just can't be priced on-chain. The SDK models this honestly: `listPricedStockTokens()` returns only the priceable ones, and `getQuote` on an unpriced token throws `FeedNotFoundError` rather than inventing a number. When you build the portfolio tracker, you'll see unpriced holdings reported as such — never as `$0`, which would be a lie.++## Troubleshooting++**My USD total is way too high after a split** — you're multiplying by `uiMultiplier` somewhere in the value path. Remove it. Value is `balance × feed price`, full stop.++**`StaleFeedError` on a weekend** — expected. Widen `maxAgeSeconds` to cover the weekend (e.g. `7 * 24 * 60 * 60`). The market is closed, not the feed broken.++**`FeedNotFoundError`** — that token has no Chainlink feed. Read its balance, but don't try to price it. Use `listPricedStockTokens()` to see what *can* be priced.++**My "share count" and "token count" differ and I expected them equal** — that token has had a corporate action, so its multiplier is above `1e18`. That divergence is the whole point of the design; both numbers are correct, they just answer different questions.++## What you learned++You now understand the one thing that makes Robinhood Chain integrations subtly hard: the multiplier, the two quantities it produces, and the ironclad rule that valuation uses the feed price alone. You also know feeds are 24/5 and that not every token is priceable. With this, you're ready to build — starting with a live price ticker.diff --git a/robinhood/learn-robinhood-chain/content/04-live-price-ticker.md b/robinhood/learn-robinhood-chain/content/04-live-price-ticker.mdnew file mode 100644index 000000000..db8281737--- /dev/null+++ b/robinhood/learn-robinhood-chain/content/04-live-price-ticker.md@@ -0,0 +1,113 @@+Time to build something that runs. A live price ticker is the "hello world" of market data: it reads prices, formats them, and refreshes. By the end you'll have a terminal that streams multiplier-adjusted Chainlink quotes for any Stock Token — and you'll have handled the two things beginners skip, staleness and unpriced tokens.++## The naive version (and why we won't ship it)++You *could* read a Chainlink feed directly and print the answer:++```ts+import { createHoodClient } from 'hoodchain'+const hood = createHoodClient()+const [, answer] = await hood.public.readContract({+ address: '0x6B22A786bAa607d76728168703a39Ea9C99f2cD0', // AAPL feed+ abi: [{ name: 'latestRoundData', type: 'function', stateMutability: 'view', inputs: [],+ outputs: [{type:'uint80'},{type:'int256'},{type:'uint256'},{type:'uint256'},{type:'uint80'}] }],+ functionName: 'latestRoundData',+})+console.log(Number(answer) / 1e8)+```++This works, but it hardcodes an address, ignores whether the round is complete, and will happily print a price from a feed that hasn't updated in a month. We can do better in the same number of lines.++## The real ticker++`getQuote` from the [hoodchain SDK](https://github.com/nirholas/robinhood-chain-sdk) does the address lookup, the multiplier-correct interpretation, the staleness guard, and the answer validation. Create `ticker.ts`:++```ts+import { createHoodClient, getQuote, listPricedStockTokens, FeedNotFoundError, StaleFeedError } from 'hoodchain'++const hood = createHoodClient()++// symbols from argv, or a sensible default set+const symbols = process.argv.slice(2).length ? process.argv.slice(2) : ['AAPL', 'TSLA', 'NVDA', 'SPY']++// stock feeds update 24/5 — a week-wide window means weekend runs don't throw+const maxAgeSeconds = 7 * 24 * 60 * 60++async function tick() {+ const rows = await Promise.all(+ symbols.map(async (symbol) => {+ try {+ const q = await getQuote(hood, symbol, { maxAgeSeconds })+ const age = (q.ageSeconds / 3600).toFixed(1)+ return `${symbol.padEnd(6)} $${q.priceUsd.toFixed(2).padStart(10)} (feed ${age}h old)`+ } catch (e) {+ if (e instanceof FeedNotFoundError) return `${symbol.padEnd(6)} ${'no feed'.padStart(11)}`+ if (e instanceof StaleFeedError) return `${symbol.padEnd(6)} ${'stale'.padStart(11)}`+ return `${symbol.padEnd(6)} ${'error'.padStart(11)}`+ }+ }),+ )+ // redraw in place+ process.stdout.write('\x1b[2J\x1b[H')+ console.log(`Robinhood Chain — ${listPricedStockTokens().length} priced Stock Tokens · ${new Date().toLocaleTimeString()}\n`)+ console.log(rows.join('\n'))+}++await tick()+setInterval(tick, 15_000) // feeds don't move every second; 15s is plenty+```++Run it:++```bash+npx tsx ticker.ts AAPL TSLA NVDA SPY+```++```text+Robinhood Chain — 34 priced Stock Tokens · 12:18:41 PM++AAPL $ 315.50 (feed 41.2h old)+TSLA $ 407.82 (feed 40.4h old)+NVDA $ 210.19 (feed 44.0h old)+SPY $ 753.62 (feed 44.1h old)+```++Those are real prices, pulled live while writing this. The feed ages are ~40 hours because this run happened over a weekend — the market was closed, the feeds paused, and our 7-day window correctly accepted them instead of throwing. That's the staleness handling from Tutorial 3, doing its job in production.++:::tip Every design decision here is deliberate+- **15-second interval, not 1s.** Chainlink stock feeds update on the order of minutes to hours, gated by a heartbeat and a deviation threshold. Polling every second just wastes RPC calls to see the same number.+- **`Promise.all`, not a loop.** All symbols are fetched concurrently; the ticker's latency is one RPC round-trip, not N of them.+- **Typed catches.** `FeedNotFoundError` and `StaleFeedError` are distinct outcomes with distinct UI — "no feed" is permanent, "stale" is temporary. Never collapse them into a generic "error."+:::++## Add the multiplier, for context++Users like to see share-equivalents. Remember the Tutorial 3 rule: the multiplier is for *display*, never for the dollar math. Add it as a separate column:++```ts+import { getMultiplier } from 'hoodchain'++const [q, m] = await Promise.all([getQuote(hood, symbol, { maxAgeSeconds }), getMultiplier(hood, symbol)])+const shares = m === null ? 'n/a' : (Number(m) / 1e18).toFixed(4)+console.log(`${symbol} $${q.priceUsd.toFixed(2)} (1 token = ${shares} shares)`)+```++For the mega-cap tickers above, the multiplier is `1.0000` — no corporate action since the token launched. When one does have a split or dividend, this column is where you'd surface it, while your USD math stays untouched.++## A browser version (no backend needed)++Everything here works client-side too — that's how this site's [home-page ticker](../) runs. In a browser you'd skip the SDK's Node bits and hit the RPC with `fetch`, decoding `latestRoundData()` yourself (the answer is the second 32-byte word of the response). The [`ticker.js`](https://github.com/nirholas/learn-robinhood-chain/blob/main/assets/ticker.js) on this very site is a complete, dependency-free reference for that — read it if you want the raw JSON-RPC version.++## Troubleshooting++**Every symbol prints `stale`** — your `maxAgeSeconds` is too tight for the current time (weekend/holiday). Widen it. During market hours you can go as tight as the feed's heartbeat.++**`UnknownSymbolError`** — the ticker you passed isn't in the registry. Symbols are case-insensitive tickers as listed on-chain. Run `listStockTokens()` to see all 95, or `listPricedStockTokens()` for the priceable ones.++**Screen flicker on redraw** — the `\x1b[2J\x1b[H` clear-and-home is crude but portable. For a polished TUI, reach for a library like `blessed` or `ink`; for a learning ticker, the escape codes are fine.++**`429 Too Many Requests`** — you're on the public RPC and polling too hard, or running several scripts at once. Raise the interval or switch to an Alchemy endpoint (Tutorial 2).++## What you built++A real, live, multiplier-correct price ticker with proper staleness and unpriced-token handling — the market-data foundation every other app in this course builds on. Next, we take reads a step further: valuing an entire portfolio in a single call, and getting it *right* where naive trackers get it wrong.diff --git a/robinhood/robinhood-chain-examples/examples/06-firehose/README.md b/robinhood/robinhood-chain-examples/examples/06-firehose/README.mdnew file mode 100644index 000000000..6efdbdf69--- /dev/null+++ b/robinhood/robinhood-chain-examples/examples/06-firehose/README.md@@ -0,0 +1,47 @@+# 06 · Sequencer firehose++Decode Robinhood Chain's Arbitrum Nitro **sequencer feed** into a live+transaction stream. `subscribeFeed` connects to+`wss://feed.mainnet.chain.robinhood.com`, unpacks each Nitro L2 message (signed+tx and batch kinds), and hands you viem-parsed transactions **~100–300ms before+they are queryable over RPC** — the earliest possible view of chain activity.+Reads only; auto-reconnects with backoff.++**What it proves:** the firehose is real, unauthenticated, and high-throughput,+and the SDK turns raw Nitro frames into typed transactions with an optional+address filter.++## Prerequisites++- Node ≥ 20 (uses the built-in `WebSocket`; on older Node the SDK falls back to+ the `ws` peer dependency, which this example installs).++## Run++```bash+npm install && npm install ../../../robinhood-chain-sdk+npm start # 15s of everything+node index.js 30 0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168 # 30s, USDG txs only+node index.js 0 # stream forever (Ctrl-C)+```++## Expected output++```+Connecting to the sequencer firehose…+Connected. Decoding L2 messages as they stream…++ seq 7732546 0x3ea23f6c10d1c645… to 0x0000000071727de22e5e9d8baf0edac6f37da032+ seq 7732547 0xc3b210eb2dabac05… to 0x65050a9b7e5075a2ba5ced7b1b64ee66262c40dc 0.000010 ETH+ seq 7732548 0x338a90b4a1305e7f… to 0x48190f1560e60cac0107f2fe9625daf85b058c4c 0.018535 ETH+ ...+1168 frames, 6712 transactions decoded.+```++That's **6,712 transactions in 12 seconds** off one socket. The first line's+recipient `0x0000…da032` is the ERC-4337 EntryPoint v0.7 — account-abstraction+traffic shows up here just like everything else.++---++Built by [nirholas](https://x.com/nichxbt) · [three.ws](https://three.ws)diff --git a/robinhood/robinhood-chain-examples/examples/07-live-price-webpage/README.md b/robinhood/robinhood-chain-examples/examples/07-live-price-webpage/README.mdnew file mode 100644index 000000000..d8db28d03--- /dev/null+++ b/robinhood/robinhood-chain-examples/examples/07-live-price-webpage/README.md@@ -0,0 +1,54 @@+# 07 · Live price webpage (client-side, no backend)++A single `index.html` that shows **live Chainlink prices for 11 Stock Tokens**,+read entirely in the browser via JSON-RPC `eth_call` against the public+Robinhood Chain RPC. No backend, no build step, no API key, **no dependencies**+— which is exactly why it runs on GitHub Pages and is embedded, running, in this+repo's [docs gallery](../../docs/index.html).++**What it proves:** read-only chain calls work straight from a static page.+Prices tick every 15s with up/down flash, per-card answer age, and designed+loading / error / empty states.++## Prerequisites++- A browser. Node ≥ 20 only if you want the convenience `npm start` server.++## Run++```bash+npm start # → http://localhost:8007 (zero-dep node:http server)+# — or just —+open index.html # the page is fully self-contained+```++## What you see++A responsive grid of price cards:++| Symbol | Price | Age |+| ------ | ------ | ------ |+| AAPL | $315.50 | updated 1.6d ago |+| TSLA | $407.82 | updated 1.6d ago |+| NVDA | $210.19 | updated 1.8d ago |+| … | … | … |++(Live values captured from the RPC while building — all 11 feeds returned real+prices: AAPL 315.50, TSLA 407.82, NVDA 210.19, MSFT 384.69, AMZN 245.57, GOOGL+356.72, META 670.67, AMD 558.21, COIN 159.43, PLTR 126.56, SPCX 145.72.)++The status pill reads `live · chain 4663 · 11/11 feeds · every 15s` when+healthy, and flips to a red `RPC unreachable — retrying` state if every read+fails. The 15s answer ages reflect the 24/5 feed schedule (weekend reads are a+day or two old — expected, not a bug).++## How it works (the whole trick)++`latestRoundData()` has selector `0xfeaf968c` and returns five 32-byte words;+the price is word #1 (`int256`, 8 decimals) and the timestamp is word #3. The+page hard-codes the 11 feed addresses from the `hoodchain` registry and decodes+the answer with three lines of `BigInt` math — no ABI library needed.++---++Built by [nirholas](https://x.com/nichxbt) · [three.ws](https://three.ws)diff --git a/robinhood/robinhood-chain-examples/examples/07-live-price-webpage/index.html b/robinhood/robinhood-chain-examples/examples/07-live-price-webpage/index.htmlnew file mode 100644index 000000000..4aaf84d15--- /dev/null+++ b/robinhood/robinhood-chain-examples/examples/07-live-price-webpage/index.html@@ -0,0 +1,218 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Robinhood Chain · Live Stock Token Prices</title>+ <meta name="description" content="Live Chainlink prices for Robinhood Chain Stock Tokens, read client-side from the public RPC. No backend, no build step." />+ <style>+ :root {+ --bg: #0a0b0f;+ --panel: #14161d;+ --panel-2: #191c25;+ --line: #262a36;+ --text: #e8eaf0;+ --muted: #8b90a0;+ --accent-a: #6d5efc;+ --accent-b: #21d4a8;+ --up: #21d4a8;+ --down: #ff5a7a;+ --radius: 14px;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; }+ body {+ background: radial-gradient(1200px 600px at 70% -10%, #1a1330 0%, var(--bg) 55%) fixed;+ color: var(--text);+ font: 15px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;+ -webkit-font-smoothing: antialiased;+ min-height: 100vh;+ }+ .wrap { max-width: 1080px; margin: 0 auto; padding: 40px 20px 64px; }+ header { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; flex-wrap: wrap; }+ h1 {+ font-size: 22px; margin: 0; letter-spacing: -0.02em;+ background: linear-gradient(90deg, var(--accent-a), var(--accent-b));+ -webkit-background-clip: text; background-clip: text; color: transparent;+ }+ .sub { color: var(--muted); font-size: 13px; margin-top: 6px; }+ .status {+ display: inline-flex; align-items: center; gap: 8px; font-size: 12px; color: var(--muted);+ border: 1px solid var(--line); border-radius: 999px; padding: 6px 12px; background: var(--panel);+ }+ .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--muted); }+ .dot.live { background: var(--up); box-shadow: 0 0 0 0 rgba(33,212,168,0.7); animation: pulse 2s infinite; }+ .dot.err { background: var(--down); }+ @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(33,212,168,0.5); } 70% { box-shadow: 0 0 0 7px rgba(33,212,168,0); } 100% { box-shadow: 0 0 0 0 rgba(33,212,168,0); } }+ .grid {+ margin-top: 28px; display: grid; gap: 14px;+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));+ }+ .card {+ background: linear-gradient(180deg, var(--panel-2), var(--panel));+ border: 1px solid var(--line); border-radius: var(--radius); padding: 18px 18px 16px;+ transition: border-color 0.2s ease, transform 0.2s ease;+ }+ .card:focus-within, .card:hover { border-color: #3a3f52; transform: translateY(-2px); }+ .card .sym { font-weight: 650; letter-spacing: 0.02em; font-size: 15px; }+ .card .name { color: var(--muted); font-size: 12px; margin-top: 2px; height: 16px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .card .price { font-size: 27px; font-variant-numeric: tabular-nums; margin-top: 14px; letter-spacing: -0.02em; }+ .card .price.flash-up { animation: flashUp 0.7s ease; }+ .card .price.flash-down { animation: flashDown 0.7s ease; }+ @keyframes flashUp { 0% { color: var(--up); } 100% { color: var(--text); } }+ @keyframes flashDown { 0% { color: var(--down); } 100% { color: var(--text); } }+ .card .meta { margin-top: 10px; font-size: 11px; color: var(--muted); font-variant-numeric: tabular-nums; }+ .card.skeleton .price, .card.skeleton .name { color: transparent; background: linear-gradient(90deg, #1d2029, #23272f, #1d2029); background-size: 200% 100%; border-radius: 6px; animation: shimmer 1.4s infinite; }+ @keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }+ .card.error .price { font-size: 15px; color: var(--down); }+ footer { margin-top: 40px; color: var(--muted); font-size: 12px; border-top: 1px solid var(--line); padding-top: 18px; }+ a { color: #9b8dff; text-decoration: none; }+ a:hover { text-decoration: underline; }+ code { background: var(--panel); border: 1px solid var(--line); border-radius: 6px; padding: 1px 6px; font-size: 12px; }+ </style>+ </head>+ <body>+ <div class="wrap">+ <header>+ <div>+ <h1>Robinhood Chain · Live Stock Token Prices</h1>+ <div class="sub">Chainlink feeds read client-side from the public RPC. No backend, no build step, no API key.</div>+ </div>+ <div class="status" id="status" role="status" aria-live="polite">+ <span class="dot" id="dot"></span><span id="statusText">connecting…</span>+ </div>+ </header>++ <div class="grid" id="grid" aria-label="Stock Token prices"></div>++ <footer>+ Prices are the token's total-return Chainlink answer (already+ corporate-action adjusted). Feeds follow US market hours 24/5, so a+ weekend answer can be a day or two old — the age is shown per card.+ Stock Tokens are tokenized debt securities and may not be offered to US+ persons; this page displays data only.+ <br /><br />+ Built by <a href="https://x.com/nichxbt">nirholas</a> ·+ <a href="https://three.ws">three.ws</a> · powered by the+ <a href="https://github.com/nirholas/robinhood-chain-sdk">hoodchain</a> registry+ </footer>+ </div>++ <script type="module">+ // --- config (self-contained: real feed addresses from the hoodchain registry) ---+ const RPC = 'https://rpc.mainnet.chain.robinhood.com'+ const CHAIN_ID = 4663+ const REFRESH_MS = 15000+ // AggregatorV3Interface.latestRoundData() selector.+ const SELECTOR = '0xfeaf968c'+ const FEEDS = [+ { sym: 'AAPL', name: 'Apple', feed: '0x6B22A786bAa607d76728168703a39Ea9C99f2cD0' },+ { sym: 'TSLA', name: 'Tesla', feed: '0x4A1166a659A55625345e9515b32adECea5547C38' },+ { sym: 'NVDA', name: 'NVIDIA', feed: '0x379EC4f7C378F34a1B47E4F3cbeBCbAC3E8E9F15' },+ { sym: 'MSFT', name: 'Microsoft', feed: '0x45C3C877C15E6BA2EBB19eA114Ea508d14C1Af2E' },+ { sym: 'AMZN', name: 'Amazon', feed: '0xD5a1508ceD74c084eBf3cBe853e2C968fB2a651C' },+ { sym: 'GOOGL', name: 'Alphabet', feed: '0xF6f373a037c30F0e5010d854385cA89185AE638b' },+ { sym: 'META', name: 'Meta Platforms', feed: '0x7C38C00C30BEe9378381E7B6135d7283356D71b1' },+ { sym: 'AMD', name: 'Advanced Micro Devices', feed: '0x943A29E7ae51A4798823ca9eEd2ed533B2A22C72' },+ { sym: 'COIN', name: 'Coinbase', feed: '0xA3a468A452940B7D6b69991207B508c609a98Ef2' },+ { sym: 'PLTR', name: 'Palantir', feed: '0x820ABedFF239034956B7A9d2F0a331f9F075eB4c' },+ { sym: 'SPCX', name: 'SpaceX (private)', feed: '0xB265810950ba6c5C0Ff821c9963014a56fD8Bffb' },+ ]++ const grid = document.getElementById('grid')+ const dot = document.getElementById('dot')+ const statusText = document.getElementById('statusText')+ const last = new Map()++ // Render skeleton cards up front (designed loading state).+ for (const f of FEEDS) {+ const el = document.createElement('div')+ el.className = 'card skeleton'+ el.id = `card-${f.sym}`+ el.tabIndex = 0+ el.innerHTML =+ `<div class="sym">${f.sym}</div><div class="name">${f.name}</div>` ++ `<div class="price">$000.00</div><div class="meta">loading…</div>`+ grid.appendChild(el)+ }++ function setStatus(kind, text) {+ dot.className = 'dot' + (kind ? ' ' + kind : '')+ statusText.textContent = text+ }++ // Decode int256 answer (word[1]) and updatedAt (word[3]) from a 5-word return.+ function decode(result) {+ const hex = result.slice(2)+ if (hex.length < 64 * 4) throw new Error('short return')+ const answer = BigInt('0x' + hex.slice(64, 128))+ const updatedAt = Number(BigInt('0x' + hex.slice(192, 256)))+ return { price: Number(answer) / 1e8, updatedAt }+ }++ async function readFeed(f) {+ const res = await fetch(RPC, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0', id: 1, method: 'eth_call',+ params: [{ to: f.feed, data: SELECTOR }, 'latest'],+ }),+ })+ const json = await res.json()+ if (json.error) throw new Error(json.error.message)+ return decode(json.result)+ }++ function ageLabel(updatedAt) {+ const s = Math.max(0, Math.floor(Date.now() / 1000) - updatedAt)+ if (s < 90) return `${s}s ago`+ if (s < 5400) return `${Math.round(s / 60)}m ago`+ if (s < 172800) return `${(s / 3600).toFixed(1)}h ago`+ return `${(s / 86400).toFixed(1)}d ago`+ }++ function paint(f, data) {+ const el = document.getElementById(`card-${f.sym}`)+ el.className = 'card'+ const priceEl = document.createElement('div')+ priceEl.className = 'price'+ const prev = last.get(f.sym)+ priceEl.textContent = `$${data.price.toFixed(2)}`+ if (prev !== undefined && data.price !== prev) {+ priceEl.classList.add(data.price > prev ? 'flash-up' : 'flash-down')+ }+ last.set(f.sym, data.price)+ el.innerHTML = `<div class="sym">${f.sym}</div><div class="name">${f.name}</div>`+ el.appendChild(priceEl)+ const meta = document.createElement('div')+ meta.className = 'meta'+ meta.textContent = `updated ${ageLabel(data.updatedAt)}`+ el.appendChild(meta)+ }++ function paintError(f, message) {+ const el = document.getElementById(`card-${f.sym}`)+ el.className = 'card error'+ el.innerHTML =+ `<div class="sym">${f.sym}</div><div class="name">${f.name}</div>` ++ `<div class="price">unavailable</div><div class="meta">${message}</div>`+ }++ let ok = 0+ async function refresh() {+ const results = await Promise.allSettled(FEEDS.map(readFeed))+ ok = 0+ results.forEach((r, i) => {+ if (r.status === 'fulfilled') { paint(FEEDS[i], r.value); ok++ }+ else paintError(FEEDS[i], r.reason?.message ?? 'read failed')+ })+ if (ok === 0) setStatus('err', 'RPC unreachable — retrying')+ else setStatus('live', `live · chain ${CHAIN_ID} · ${ok}/${FEEDS.length} feeds · every ${REFRESH_MS / 1000}s`)+ }++ refresh()+ setInterval(refresh, REFRESH_MS)+ </script>+ </body>+</html>diff --git a/robinhood/robinhood-chain-examples/examples/07-live-price-webpage/package.json b/robinhood/robinhood-chain-examples/examples/07-live-price-webpage/package.jsonnew file mode 100644index 000000000..22bb42c85--- /dev/null+++ b/robinhood/robinhood-chain-examples/examples/07-live-price-webpage/package.json@@ -0,0 +1,13 @@+{+ "name": "rh-example-07-live-price-webpage",+ "version": "0.1.0",+ "private": true,+ "type": "module",+ "description": "Single-file client-side webpage showing live Robinhood Chain Stock Token prices.",+ "scripts": {+ "start": "node serve.js"+ },+ "engines": {+ "node": ">=20"+ }+}diff --git a/robinhood/robinhood-chain-examples/examples/07-live-price-webpage/serve.js b/robinhood/robinhood-chain-examples/examples/07-live-price-webpage/serve.jsnew file mode 100644index 000000000..e7e88e52a--- /dev/null+++ b/robinhood/robinhood-chain-examples/examples/07-live-price-webpage/serve.js@@ -0,0 +1,24 @@+/**+ * Zero-dependency static server for index.html — just so `npm start` works.+ * The page itself needs no server: opening index.html in a browser (or hosting+ * it on GitHub Pages) works identically, because every read is a client-side+ * JSON-RPC call to the public Robinhood Chain RPC.+ */+import { createServer } from 'node:http'+import { readFile } from 'node:fs/promises'+import { fileURLToPath } from 'node:url'+import { dirname, join } from 'node:path'++const dir = dirname(fileURLToPath(import.meta.url))+const port = Number(process.env.PORT) || 8007++createServer(async (req, res) => {+ const path = req.url === '/' ? '/index.html' : req.url+ try {+ const body = await readFile(join(dir, path.split('?')[0]))+ res.writeHead(200, { 'content-type': path.endsWith('.html') ? 'text/html' : 'text/plain' })+ res.end(body)+ } catch {+ res.writeHead(404).end('not found')+ }+}).listen(port, () => console.log(`Live prices → http://localhost:${port}`))diff --git a/workers/robinhood-feed/index.js b/workers/robinhood-feed/index.jsnew file mode 100644index 000000000..cce758946--- /dev/null+++ b/workers/robinhood-feed/index.js@@ -0,0 +1,27 @@+// robinhood-feed entry point. Starts the firehose orchestrator and the+// HTTP/WS/SSE server, wires them together, and shuts down cleanly on SIGINT.++import { config } from './src/config.js';+import { startFirehose } from './src/feed.js';+import { createServer } from './src/server.js';++let onEventRef = () => {};+const firehose = startFirehose((ev) => onEventRef(ev));+const { server, onEvent } = createServer(firehose);+onEventRef = onEvent;++server.listen(config.port, () => {+ console.log(`[robinhood-feed] ${config.network} · listening on :${config.port}`);+ console.log(`[robinhood-feed] rpc=${config.rpcUrl}`);+ console.log(`[robinhood-feed] feed=${config.useFeed ? config.feedUrl : 'disabled'}`);+ console.log('[robinhood-feed] SSE /events · WS /ws · status /healthz');+});++function shutdown(sig) {+ console.log(`[robinhood-feed] ${sig} — shutting down`);+ try { firehose.stop(); } catch { /* ignore */ }+ server.close(() => process.exit(0));+ setTimeout(() => process.exit(0), 3_000).unref();+}+process.on('SIGINT', () => shutdown('SIGINT'));+process.on('SIGTERM', () => shutdown('SIGTERM'));diff --git a/workers/robinhood-feed/package-lock.json b/workers/robinhood-feed/package-lock.jsonnew file mode 100644index 000000000..01983997b--- /dev/null+++ b/workers/robinhood-feed/package-lock.json@@ -0,0 +1,253 @@+{+ "name": "robinhood-feed",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "robinhood-feed",+ "version": "0.1.0",+ "license": "MIT",+ "dependencies": {+ "hoodchain": "file:../../robinhood/robinhood-chain-sdk",+ "viem": "^2.55.0",+ "ws": "^8.18.0"+ }+ },+ "../../robinhood/robinhood-chain-sdk": {+ "name": "hoodchain",+ "version": "0.1.0",+ "license": "MIT",+ "devDependencies": {+ "@types/node": "^24.0.0",+ "@types/ws": "^8.18.0",+ "tsup": "^8.5.0",+ "typedoc": "^0.28.0",+ "typescript": "^5.9.0",+ "viem": "^2.55.0",+ "vitest": "^3.2.0",+ "ws": "^8.18.0"+ },+ "engines": {+ "node": ">=20"+ },+ "peerDependencies": {+ "viem": "^2.55.0",+ "ws": "^8.18.0"+ },+ "peerDependenciesMeta": {+ "ws": {+ "optional": true+ }+ }+ },+ "node_modules/@adraffy/ens-normalize": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz",+ "integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==",+ "license": "MIT"+ },+ "node_modules/@noble/ciphers": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",+ "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",+ "license": "MIT",+ "engines": {+ "node": "^14.21.3 || >=16"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@noble/curves": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz",+ "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==",+ "license": "MIT",+ "dependencies": {+ "@noble/hashes": "1.8.0"+ },+ "engines": {+ "node": "^14.21.3 || >=16"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@noble/hashes": {+ "version": "1.8.0",+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",+ "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",+ "license": "MIT",+ "engines": {+ "node": "^14.21.3 || >=16"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@scure/base": {+ "version": "1.2.6",+ "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz",+ "integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==",+ "license": "MIT",+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@scure/bip32": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.7.0.tgz",+ "integrity": "sha512-E4FFX/N3f4B80AKWp5dP6ow+flD1LQZo/w8UnLGYZO674jS6YnYeepycOOksv+vLPSpgN35wgKgy+ybfTb2SMw==",+ "license": "MIT",+ "dependencies": {+ "@noble/curves": "~1.9.0",+ "@noble/hashes": "~1.8.0",+ "@scure/base": "~1.2.5"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@scure/bip39": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.6.0.tgz",+ "integrity": "sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A==",+ "license": "MIT",+ "dependencies": {+ "@noble/hashes": "~1.8.0",+ "@scure/base": "~1.2.5"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/abitype": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.2.3.tgz",+ "integrity": "sha512-Ofer5QUnuUdTFsBRwARMoWKOH1ND5ehwYhJ3OJ/BQO+StkwQjHw0XyVh4vDttzHB7QOFhPHa/o413PJ82gU/Tg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/wevm"+ },+ "peerDependencies": {+ "typescript": ">=5.0.4",+ "zod": "^3.22.0 || ^4.0.0"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ },+ "zod": {+ "optional": true+ }+ }+ },+ "node_modules/eventemitter3": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz",+ "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==",+ "license": "MIT"+ },+ "node_modules/hoodchain": {+ "resolved": "../../robinhood/robinhood-chain-sdk",+ "link": true+ },+ "node_modules/isows": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/isows/-/isows-1.0.7.tgz",+ "integrity": "sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/wevm"+ }+ ],+ "license": "MIT",+ "peerDependencies": {+ "ws": "*"+ }+ },+ "node_modules/ox": {+ "version": "0.14.30",+ "resolved": "https://registry.npmjs.org/ox/-/ox-0.14.30.tgz",+ "integrity": "sha512-LI11uu+8iiM1B3CLckgd++YF1a0A2k5wDoM9ZeQMiL21BOzQs6L//BLS6hb1HSEKCyycdDIQLsVQx9MjpcC0hA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/wevm"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@adraffy/ens-normalize": "^1.11.0",+ "@noble/ciphers": "^1.3.0",+ "@noble/curves": "1.9.1",+ "@noble/hashes": "^1.8.0",+ "@scure/bip32": "^1.7.0",+ "@scure/bip39": "^1.6.0",+ "abitype": "^1.2.3",+ "eventemitter3": "5.0.1"+ },+ "peerDependencies": {+ "typescript": ">=5.4.0"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ }+ },+ "node_modules/viem": {+ "version": "2.55.1",+ "resolved": "https://registry.npmjs.org/viem/-/viem-2.55.1.tgz",+ "integrity": "sha512-sajvEmONS3dEDFh0jKXGugTU8ImyGoIV3sEHSWNRhgkH484v/+6DjZAplRhcdeqNV/VBxOs/l3raOG4NaXvX9A==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/wevm"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@noble/curves": "1.9.1",+ "@noble/hashes": "1.8.0",+ "@scure/bip32": "1.7.0",+ "@scure/bip39": "1.6.0",+ "abitype": "1.2.3",+ "isows": "1.0.7",+ "ox": "0.14.30",+ "ws": "8.21.0"+ },+ "peerDependencies": {+ "typescript": ">=5.0.4"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ }+ },+ "node_modules/ws": {+ "version": "8.21.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ }+ }+}diff --git a/workers/robinhood-feed/src/server.js b/workers/robinhood-feed/src/server.jsnew file mode 100644index 000000000..c681d9e91--- /dev/null+++ b/workers/robinhood-feed/src/server.js@@ -0,0 +1,140 @@+// HTTP + WebSocket server. Fans normalized firehose events out to WS and SSE+// subscribers and keeps a small replay buffer so a fresh subscriber sees recent+// history instead of a blank feed — mirroring the three.ws pump SSE endpoints.+//+// Endpoints:+// GET /healthz → { ok, uptime, subscribers, buffer, firehose }+// GET /recent?kind=&limit= → JSON snapshot of the replay buffer+// GET /events?kinds=launch,... → SSE stream (text/event-stream)+// WS /ws?kinds=launch,... → same events over a WebSocket+// GET / → tiny status page++import http from 'node:http';+import { WebSocketServer } from 'ws';+import { config } from './config.js';++const KINDS = ['launch', 'trade', 'graduation'];++function parseKinds(url) {+ const raw = new URL(url, 'http://x').searchParams.get('kinds');+ if (!raw) return new Set(KINDS);+ const want = raw.split(',').map((s) => s.trim()).filter((k) => KINDS.includes(k));+ return new Set(want.length ? want : KINDS);+}++export function createServer(firehose) {+ const startedAt = Date.now();+ const buffer = { launch: [], trade: [], graduation: [] };+ const sseClients = new Set(); // { res, kinds }++ function pushBuffer(kind, data) {+ const arr = buffer[kind];+ if (!arr) return;+ const sig = data.tx_signature || data.signature;+ if (sig && arr.some((e) => (e.tx_signature || e.signature) === sig && e.mint === data.mint)) return;+ arr.unshift(data);+ while (arr.length > config.bufferLimit) arr.pop();+ }++ function recent({ kind = 'all', limit = 20 } = {}) {+ const cap = Math.max(1, Math.min(200, limit | 0 || 20));+ const kinds = kind === 'all' ? KINDS : KINDS.includes(kind) ? [kind] : [];+ const out = [];+ for (const k of kinds) for (const d of buffer[k]) out.push({ kind: k, data: d });+ out.sort((a, b) => (b.data.timestamp || 0) - (a.data.timestamp || 0));+ return out.slice(0, cap);+ }++ // Firehose → buffer + fan-out.+ function onEvent(ev) {+ if (ev.kind !== 'status') pushBuffer(ev.kind, ev.data);+ const line = `data: ${JSON.stringify(ev)}\n\n`;+ for (const c of sseClients) {+ if (ev.kind === 'status' || c.kinds.has(ev.kind)) {+ try { c.res.write(line); } catch { /* dropped below on close */ }+ }+ }+ const msg = JSON.stringify(ev);+ for (const ws of wss.clients) {+ if (ws.readyState !== ws.OPEN) continue;+ if (ev.kind === 'status' || ws._kinds?.has(ev.kind)) {+ try { ws.send(msg); } catch { /* ignore */ }+ }+ }+ }++ const server = http.createServer((req, res) => {+ const { pathname } = new URL(req.url, 'http://x');+ res.setHeader('access-control-allow-origin', '*');++ if (pathname === '/healthz') {+ return json(res, 200, {+ ok: true,+ network: config.network,+ uptime_s: Math.round((Date.now() - startedAt) / 1000),+ subscribers: { sse: sseClients.size, ws: wss.clients.size },+ buffer: { launch: buffer.launch.length, trade: buffer.trade.length, graduation: buffer.graduation.length },+ firehose: firehose.health(),+ });+ }++ if (pathname === '/recent') {+ const sp = new URL(req.url, 'http://x').searchParams;+ return json(res, 200, { events: recent({ kind: sp.get('kind') || 'all', limit: Number(sp.get('limit')) || 20 }) });+ }++ if (pathname === '/events') {+ res.writeHead(200, {+ 'content-type': 'text/event-stream',+ 'cache-control': 'no-cache, no-transform',+ connection: 'keep-alive',+ });+ const client = { res, kinds: parseKinds(req.url) };+ sseClients.add(client);+ // Replay recent history immediately.+ for (const ev of recent({ kind: 'all', limit: config.bufferLimit }).reverse()) {+ if (client.kinds.has(ev.kind)) res.write(`data: ${JSON.stringify({ ...ev, replay: true })}\n\n`);+ }+ res.write(`data: ${JSON.stringify({ kind: 'status', data: { level: 'info', src: 'sse', message: 'connected' } })}\n\n`);+ const ka = setInterval(() => { try { res.write(': ping\n\n'); } catch { /* ignore */ } }, 20_000);+ req.on('close', () => { clearInterval(ka); sseClients.delete(client); });+ return undefined;+ }++ if (pathname === '/') {+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });+ return res.end(statusPage());+ }++ return json(res, 404, { error: 'not found' });+ });++ const wss = new WebSocketServer({ server, path: '/ws' });+ wss.on('connection', (ws, req) => {+ ws._kinds = parseKinds(req.url);+ for (const ev of recent({ kind: 'all', limit: config.bufferLimit }).reverse()) {+ if (ws._kinds.has(ev.kind)) { try { ws.send(JSON.stringify({ ...ev, replay: true })); } catch { /* ignore */ } }+ }+ });++ return { server, onEvent, recent };+}++function json(res, code, body) {+ res.writeHead(code, { 'content-type': 'application/json' });+ res.end(JSON.stringify(body));+}++function statusPage() {+ return `<!doctype html><html><head><meta charset=utf-8><title>robinhood-feed</title>+<style>body{background:#0b0d10;color:#e6e8eb;font:14px/1.6 ui-monospace,monospace;margin:0;padding:40px;max-width:720px}+h1{font-size:18px;color:#5fd08a}a{color:#7aa2f7}code{background:#161a1f;padding:2px 6px;border-radius:4px}</style></head>+<body><h1>robinhood-feed · Robinhood Chain firehose</h1>+<p>Normalized launches, trades and graduations from NOXA + The Odyssey + Uniswap v3.</p>+<ul>+<li><a href="/healthz">/healthz</a> — status JSON</li>+<li><a href="/recent">/recent</a> — replay-buffer snapshot (<code>?kind=trade&limit=20</code>)</li>+<li><code>/events</code> — SSE stream (<code>?kinds=launch,trade,graduation</code>)</li>+<li><code>/ws</code> — WebSocket stream (same events)</li>+</ul></body></html>`;+}