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
hood-traders/hood-alerts/hood-cli: LLM strategist, X transport, setup wizard
nirholas7d50a72484fb
diff --git a/robinhood/hood-alerts/.env.example b/robinhood/hood-alerts/.env.exampleindex 2b67a1904..b252cb6d5 100644--- a/robinhood/hood-alerts/.env.example+++ b/robinhood/hood-alerts/.env.example@@ -28,6 +28,35 @@ HOOD_ALERTS_TELEGRAM_TOKEN=HOOD_ALERTS_DISCORD_TOKEN=HOOD_ALERTS_DISCORD_APP_ID=+# ---- X (Twitter) auto-posting: pick ONE mode ----+# Leave empty to disable. X has no inbound bot (no watch/unwatch DMs), so what+# it posts is fixed at startup via HOOD_ALERTS_X_TOPICS below.+HOOD_ALERTS_X_MODE= # official | xactions++# official mode: the real X API v2, POST /2/tweets, OAuth1 user context.+# Requires a developer.x.com app with a posting-capable tier (check current+# pricing at https://developer.x.com/en/portal/products/buy before relying on+# this; it has changed before and may change again). Create an app, generate+# a consumer key/secret, then generate an access token/secret with+# read+write permissions.+HOOD_ALERTS_X_API_KEY=+HOOD_ALERTS_X_API_SECRET=+HOOD_ALERTS_X_ACCESS_TOKEN=+HOOD_ALERTS_X_ACCESS_SECRET=++# xactions mode: free, self-hosted browser-automation posting via your own X+# session cookie instead of the official API. See+# https://github.com/nirholas/XActions to run your own instance. Not the+# official API: carries ToS risk. Posting is async (queued, not confirmed+# synchronously).+HOOD_ALERTS_XACTIONS_URL=+HOOD_ALERTS_XACTIONS_TOKEN=++# Topics the X broadcast auto-posts (comma-separated; parsed the same way a+# `watch` command target is). Premium-tier topics (premiums, rugs) only post+# if the x/public subscriber has been granted premium (see grant-premium).+HOOD_ALERTS_X_TOPICS=launches,graduations,whales+# ---- premium (x402 USDG on Robinhood Chain via hood402) ----# Rail selector. `hood402` (USDG on chain 4663) is implemented end-to-end.# `x402-usdc` is a documented alternative (see README) and is rejected atdiff --git a/robinhood/hood-alerts/README.md b/robinhood/hood-alerts/README.mdindex 4507a3718..48aa0083f 100644--- a/robinhood/hood-alerts/README.md+++ b/robinhood/hood-alerts/README.md@@ -2,10 +2,10 @@[](./LICENSE)-The alert layer for **Robinhood Chain** (chain ID 4663): Telegram and Discord bots backed by one-shared detection engine that watches launches, graduations, whale trades, Stock Token price moves,-on-chain premium/discount arbitrage, holder milestones, and liquidity-pull rug warnings. Free tier-plus x402 USDG premium.+The alert layer for **Robinhood Chain** (chain ID 4663): Telegram and Discord bots, plus optional+X (Twitter) auto-posting, backed by one shared detection engine that watches launches, graduations,+whale trades, Stock Token price moves, on-chain premium/discount arbitrage, holder milestones, and+liquidity-pull rug warnings. Free tier plus x402 USDG premium.## What it detects@@ -21,8 +21,8 @@ plus x402 USDG premium.Every event is deduped per fingerprint before it reaches a subscriber, routed through apremium/quiet-hours/digest gate, and rendered as a platform-native card (Telegram HTML, Discord-embed, or a structured console log line) with links back to the chain explorer and-`three.ws/markets/robinhood`.+embed, a compact X post, or a structured console log line) with links back to the chain explorer+and `three.ws/markets/robinhood`.## Quickstart (self-host)@@ -54,6 +54,43 @@ npm start # node dist/src/index.jsLeaving either token unset disables that transport; the engine and the console transport keeprunning regardless.+### X (Twitter)++X is a broadcast-only transport: there is no inbound bot, so you cannot DM the account and get a+reply the way you can with Telegram or Discord. What it auto-posts is fixed at startup by+`HOOD_ALERTS_X_TOPICS` (default `launches,graduations,whales`) instead of `watch`/`unwatch`+commands, parsed through the same topic resolver the bots use. Pick exactly **one** of two modes+via `HOOD_ALERTS_X_MODE`; see `.env.example` for the full variable list.++**`official`**: the real X API v2, `POST /2/tweets`, signed with your own developer app's OAuth1+user-context credentials. This is the normal, ToS-compliant path, and it costs money: X gates+posting behind a paid API tier. Check current pricing at+[developer.x.com/en/portal/products/buy](https://developer.x.com/en/portal/products/buy) before+relying on it; it has changed before and can change again.++Setup: create an app at the [developer portal](https://developer.x.com/en/portal), generate a+consumer key/secret (`HOOD_ALERTS_X_API_KEY` / `HOOD_ALERTS_X_API_SECRET`), then generate an+access token/secret with **read and write** permissions (`HOOD_ALERTS_X_ACCESS_TOKEN` /+`HOOD_ALERTS_X_ACCESS_SECRET`). All four are required; hood-alerts signs every request itself with+Node's built-in `crypto` (HMAC-SHA1 per RFC 5849), no extra dependency.++**`xactions`**: posts through a self-hosted [XActions](https://github.com/nirholas/XActions)+instance instead of the official API: browser-automation driving your own X session cookie. Free,+no developer account, no paid tier. This is **not** the official API and carries real ToS risk;+run it on an account you are prepared to lose if X acts on that. Point `HOOD_ALERTS_XACTIONS_URL`+at your running instance and `HOOD_ALERTS_XACTIONS_TOKEN` at its bearer token. Posting is+async/job-queued: hood-alerts treats a 2xx from `POST {url}/api/posting/tweet` as "accepted", not+"delivered", and logs that delivery is not confirmed synchronously (the real xactions API responds+`{ operationId, status: "queued" }`, not a tweet id).++Both modes fail loudly: a configured mode missing any required credential logs a warning and+disables the X transport (Telegram, Discord, and the console transport keep running) instead of+crashing the process. Every X post is compacted to fit X's 280-character limit: title, the single+most important line, and the first link; only the text portion truncates, never the URL. Digests+(too many alerts to post individually) post the single most significant event plus a `(+N more)`+count, and log the full summarized batch, so nothing is silently dropped from the record even+though it is dropped from the post itself.+## Bot commandsBoth bots share one command router (`src/commands/commands.ts`), so the UX is identical modulo@@ -111,7 +148,7 @@ The same process that runs the bots serves a small Hono app on `PORT` (default 8| --- | --- | --- || `/` | GET | service metadata and endpoint list || `/healthz` | GET | uptime, last detector event time, per-event-type counts, whether premium purchases are enabled |-| `/premium/status?platform=telegram\|discord\|console&chat=<id>` | GET | `{ tier: 'free' \| 'premium', expiresAt }` for that chat |+| `/premium/status?platform=telegram\|discord\|console\|x&chat=<id>` | GET | `{ tier: 'free' \| 'premium', expiresAt }` for that chat || `/premium/activate?platform=...&chat=...` | POST | the x402 purchase flow: 402 challenge, then 200 + entitlement once payment settles |## Example: reading the alert engine's pure logic directly@@ -248,7 +285,8 @@ src/engine/detectors/ pure per-signal detectors (price move, premium laddwhich wires them to hoodchain/hoodkit streamssrc/db/ better-sqlite3 repositories: subscribers, entitlements, deliveriessrc/premium/paywall.ts the hood402 x402 purchase flow-src/transports/ Telegram (grammY), Discord (discord.js), and console transports+src/transports/ Telegram (grammY), Discord (discord.js), X (OAuth1 API v2 or self-+ hosted xactions), and console transportssrc/commands/commands.ts the shared, platform-neutral command routersrc/format/cards.ts alert -> platform-neutral card -> per-platform renderingtests/ vitest unit suite + tests/fixtures (real captured chain events) +diff --git a/robinhood/hood-alerts/docs/index.html b/robinhood/hood-alerts/docs/index.htmlindex df02acee3..f515b6c51 100644--- a/robinhood/hood-alerts/docs/index.html+++ b/robinhood/hood-alerts/docs/index.html@@ -4,7 +4,7 @@<meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>hood-alerts · Robinhood Chain alert bots</title>- <meta name="description" content="Real-time Telegram and Discord alerts for Robinhood Chain (4663): memecoin launches, graduations, whale trades, Stock Token price moves, on-chain premium/discount arbitrage, holder milestones, and liquidity-pull rug warnings." />+ <meta name="description" content="Real-time Telegram, Discord, and X (Twitter) alerts for Robinhood Chain (4663): memecoin launches, graduations, whale trades, Stock Token price moves, on-chain premium/discount arbitrage, holder milestones, and liquidity-pull rug warnings." /><link rel="preconnect" href="https://rpc.mainnet.chain.robinhood.com" /><link rel="stylesheet" href="styles.css" /></head>@@ -25,7 +25,7 @@<div class="wrap"><span class="chip"><span class="live"></span> Live · Robinhood Chain · ID 4663</span><h1>Alerts for the chain that<br /><span class="grad">never sleeps.</span></h1>- <p class="sub">Telegram and Discord bots that watch Robinhood Chain in real time: launches, graduations, whale trades, Stock Token moves, on-chain premium/discount arbitrage, holder milestones, and liquidity-pull rug warnings.</p>+ <p class="sub">Telegram and Discord bots, plus auto-posting to X (Twitter), that watch Robinhood Chain in real time: launches, graduations, whale trades, Stock Token moves, on-chain premium/discount arbitrage, holder milestones, and liquidity-pull rug warnings.</p><div class="cta"><a class="btn primary" href="commands.html">See the commands</a><a class="btn ghost" href="#live">Watch it live ↓</a>@@ -102,6 +102,7 @@<div class="feat"><span class="tag">group</span><h3>Group-chat ready</h3><p>Add the bot to a Telegram group or Discord server; config commands are admin-only, alerts land for everyone.</p></div><div class="feat"><span class="tag">premium</span><h3>Arb and rug detectors</h3><p>The Stock Token premium/discount signal and the liquidity-pull rug warning are the premium tier. Free tier covers launches, whales, and moves.</p></div><div class="feat"><span class="tag">host</span><h3>One container</h3><p>Engine plus both bots plus a health endpoint in a single process. Deploy to Cloud Run with min-instances 1 and go.</p></div>+ <div class="feat"><span class="tag">broadcast</span><h3>X (Twitter), your choice of mode</h3><p>Official X API v2 (OAuth1, your own developer app) or a free self-hosted <a href="https://github.com/nirholas/XActions" target="_blank" rel="noopener">xactions</a> instance — pick whichever fits, config-driven topics, no code changes.</p></div></div></div></section>diff --git a/robinhood/hood-alerts/docs/self-host.html b/robinhood/hood-alerts/docs/self-host.htmlindex 8fb2d80aa..2f5dcabf8 100644--- a/robinhood/hood-alerts/docs/self-host.html+++ b/robinhood/hood-alerts/docs/self-host.html@@ -42,6 +42,9 @@ npm run probe -- --token 0xTOKEN --seconds 300</code></pre><tbody><tr><td><code>HOOD_ALERTS_TELEGRAM_TOKEN</code></td><td>Message <a href="https://t.me/BotFather" target="_blank" rel="noopener">@BotFather</a>, run <code>/newbot</code>, copy the token.</td></tr><tr><td><code>HOOD_ALERTS_DISCORD_TOKEN</code><br /><code>HOOD_ALERTS_DISCORD_APP_ID</code></td><td>Create an app at the <a href="https://discord.com/developers/applications" target="_blank" rel="noopener">Discord Developer Portal</a>; copy the Bot token and Application ID. Invite it with <code>applications.commands</code> + <code>bot</code> scopes.</td></tr>+ <tr><td><code>HOOD_ALERTS_X_MODE=official</code><br /><code>HOOD_ALERTS_X_API_KEY</code> / <code>_API_SECRET</code> / <code>_ACCESS_TOKEN</code> / <code>_ACCESS_SECRET</code></td><td>X API v2 (OAuth1, user-context). Create an app at <a href="https://developer.x.com" target="_blank" rel="noopener">developer.x.com</a> with read+write access, copy the four credentials. Needs a posting-capable API tier — check current pricing there.</td></tr>+ <tr><td><code>HOOD_ALERTS_X_MODE=xactions</code><br /><code>HOOD_ALERTS_XACTIONS_URL</code> / <code>_XACTIONS_TOKEN</code></td><td>Free, self-hosted alternative: point at your own running <a href="https://github.com/nirholas/XActions" target="_blank" rel="noopener">xactions</a> instance. Browser-session automation, not the official API — ToS risk, delivery isn't confirmed synchronously.</td></tr>+ <tr><td><code>HOOD_ALERTS_X_TOPICS</code></td><td>Comma-separated topics to auto-post (default <code>launches,graduations,whales</code>). No inbound X bot, so this is fixed at startup, not set via a chat command.</td></tr></tbody></table><p>Each transport is optional: set only the tokens you want. The others stay disabled and log a warning.</p>diff --git a/robinhood/hood-alerts/package.json b/robinhood/hood-alerts/package.jsonindex de0500a6d..cc274c105 100644--- a/robinhood/hood-alerts/package.json+++ b/robinhood/hood-alerts/package.json@@ -1,6 +1,6 @@{"name": "hood-alerts",- "version": "0.1.0",+ "version": "0.2.0","description": "The alert layer for Robinhood Chain (chain ID 4663): Telegram + Discord bots and a shared detection engine for memecoin launches, graduations, whale trades, price moves, Stock Token premium/discount arbitrage, holder milestones, and liquidity-pull rug warnings. Free tier + x402 USDG premium.","keywords": ["robinhood",diff --git a/robinhood/hood-alerts/scripts/grant-premium.ts b/robinhood/hood-alerts/scripts/grant-premium.tsindex ef98100b3..63d523feb 100644--- a/robinhood/hood-alerts/scripts/grant-premium.ts+++ b/robinhood/hood-alerts/scripts/grant-premium.ts@@ -8,6 +8,7 @@* npm run grant-premium -- grant telegram 123456789 --days 30* npm run grant-premium -- status discord 987654321* npm run grant-premium -- revoke telegram 123456789+ * npm run grant-premium -- grant x public --days 30 # the X broadcast subscriber** The database path follows HOOD_ALERTS_DB (default ./data/hood-alerts.db).*/@@ -22,7 +23,7 @@ function fail(message: string): never {process.exit(1)}-const PLATFORMS: Platform[] = ['telegram', 'discord', 'console']+const PLATFORMS: Platform[] = ['telegram', 'discord', 'console', 'x']function flag(name: string): string | undefined {const i = process.argv.indexOf(`--${name}`)@@ -32,7 +33,7 @@ function flag(name: string): string | undefined {function main(): void {const [action, platform, chat] = process.argv.slice(2)if (!action || !['grant', 'revoke', 'status'].includes(action)) {- fail('Usage: grant-premium <grant|revoke|status> <telegram|discord|console> <chatId> [--days 30]')+ fail('Usage: grant-premium <grant|revoke|status> <telegram|discord|console|x> <chatId> [--days 30]')}if (!platform || !PLATFORMS.includes(platform as Platform)) fail(`platform must be one of ${PLATFORMS.join(', ')}`)if (!chat) fail('chatId is required')diff --git a/robinhood/hood-alerts/src/config.ts b/robinhood/hood-alerts/src/config.tsindex c0d91697f..aa9eee3ae 100644--- a/robinhood/hood-alerts/src/config.ts+++ b/robinhood/hood-alerts/src/config.ts@@ -15,6 +15,27 @@ export interface Config {/** Discord bot token + application id, or null to disable the transport. */discordToken: string | nulldiscordAppId: string | null+ /**+ * X (Twitter) delivery mode, or undefined to disable the transport.+ * `official` posts through the real X API v2 (OAuth1, paid tier). `xactions`+ * posts through a self-hosted https://github.com/nirholas/XActions instance+ * (free, cookie-session automation, ToS risk). Set at most one.+ */+ xMode: 'official' | 'xactions' | undefined+ /** official mode: X API v2 OAuth1 user-context credentials (developer.x.com). */+ xApiKey: string | null+ xApiSecret: string | null+ xAccessToken: string | null+ xAccessSecret: string | null+ /** xactions mode: base URL and bearer token of a self-hosted xactions instance. */+ xactionsUrl: string | null+ xactionsToken: string | null+ /**+ * Topics the X broadcast auto-posts, resolved the same way a `watch`+ * command would parse them. X has no inbound bot, so this is fixed at+ * startup instead of user-driven.+ */+ xTopics: string[]/** Premium rail. Only `hood402` is implemented end-to-end. */premiumRail: 'hood402'/** Receiving address for premium payments (null = purchases disabled). */@@ -80,6 +101,10 @@ export function loadConfig(): Config {if (settlerRaw && !/^0x[0-9a-fA-F]{64}$/.test(settlerRaw)) {throw new Error('HOOD402_SETTLER_KEY must be a 0x-prefixed 32-byte hex private key')}+ const xModeRaw = str('HOOD_ALERTS_X_MODE')+ if (xModeRaw !== null && xModeRaw !== 'official' && xModeRaw !== 'xactions') {+ throw new Error(`HOOD_ALERTS_X_MODE must be "official" or "xactions", got "${xModeRaw}"`)+ }const port = Math.floor(num('PORT', 8080))return {rpcUrl: str('HOOD_ALERTS_RPC_URL') ?? undefined,@@ -89,6 +114,17 @@ export function loadConfig(): Config {telegramToken: str('HOOD_ALERTS_TELEGRAM_TOKEN'),discordToken: str('HOOD_ALERTS_DISCORD_TOKEN'),discordAppId: str('HOOD_ALERTS_DISCORD_APP_ID'),+ xMode: xModeRaw ?? undefined,+ xApiKey: str('HOOD_ALERTS_X_API_KEY'),+ xApiSecret: str('HOOD_ALERTS_X_API_SECRET'),+ xAccessToken: str('HOOD_ALERTS_X_ACCESS_TOKEN'),+ xAccessSecret: str('HOOD_ALERTS_X_ACCESS_SECRET'),+ xactionsUrl: str('HOOD_ALERTS_XACTIONS_URL'),+ xactionsToken: str('HOOD_ALERTS_XACTIONS_TOKEN'),+ xTopics: (str('HOOD_ALERTS_X_TOPICS') ?? 'launches,graduations,whales')+ .split(',')+ .map((t) => t.trim())+ .filter(Boolean),premiumRail: 'hood402',payTo: (payToRaw as Address | null) ?? null,facilitatorUrl: str('HOOD402_FACILITATOR_URL'),diff --git a/robinhood/hood-alerts/src/db/index.ts b/robinhood/hood-alerts/src/db/index.tsindex 8e112bfe4..cbd548859 100644--- a/robinhood/hood-alerts/src/db/index.ts+++ b/robinhood/hood-alerts/src/db/index.ts@@ -7,7 +7,7 @@ export type Db = Database.Databaseconst SCHEMA = `CREATE TABLE IF NOT EXISTS subscribers (id INTEGER PRIMARY KEY,- platform TEXT NOT NULL CHECK (platform IN ('telegram', 'discord', 'console')),+ platform TEXT NOT NULL CHECK (platform IN ('telegram', 'discord', 'console', 'x')),chat_id TEXT NOT NULL,title TEXT,digest INTEGER NOT NULL DEFAULT 0,diff --git a/robinhood/hood-alerts/src/db/subscribers.ts b/robinhood/hood-alerts/src/db/subscribers.tsindex 063838ee3..f1e75079b 100644--- a/robinhood/hood-alerts/src/db/subscribers.ts+++ b/robinhood/hood-alerts/src/db/subscribers.ts@@ -1,6 +1,6 @@import type { Db } from './index.js'-export type Platform = 'telegram' | 'discord' | 'console'+export type Platform = 'telegram' | 'discord' | 'console' | 'x'export interface Subscriber {id: numberdiff --git a/robinhood/hood-alerts/src/format/cards.ts b/robinhood/hood-alerts/src/format/cards.tsindex 3e457e1de..6ead8b1c6 100644--- a/robinhood/hood-alerts/src/format/cards.ts+++ b/robinhood/hood-alerts/src/format/cards.ts@@ -167,6 +167,45 @@ export function cardToDiscordEmbed(card: AlertCard): {}}+/** X (Twitter)'s post character limit. Assumes no paid long-post tier. */+export const X_POST_LIMIT = 280++/**+ * Compose title + one line + one link into an X post, truncating only the+ * text portion (never the URL) to fit `X_POST_LIMIT`.+ */+function composeXPost(title: string, line: string | undefined, link: AlertCard['links'][number] | undefined, suffix = ''): string {+ const linkPart = link ? ` ${link.url}` : ''+ const budget = X_POST_LIMIT - linkPart.length - suffix.length+ const body = line ? `${title}: ${line}` : title+ const text = body.length <= budget ? body : `${body.slice(0, Math.max(0, budget - 1))}…`+ return `${text}${suffix}${linkPart}`+}++/** X (Twitter) post rendering: title, the single most important line, and the first link. */+export function cardToXPost(card: AlertCard): string {+ return composeXPost(card.title, card.lines[0], card.links[0])+}++/**+ * X digest rendering: X has no room for a multi-item card list, so this posts+ * the single most significant event (by severity: warning, then notice, then+ * info) plus a "+N more" count. Nothing is silently dropped from the batch,+ * only from the post itself; callers should log the full summarized list.+ */+export function cardToXDigestPost(events: AlertEvent[]): string {+ const severityRank: Record<AlertCard['severity'], number> = { warning: 0, notice: 1, info: 2 }+ let best: AlertCard | null = null+ for (const e of events) {+ const card = toCard(e)+ if (!best || severityRank[card.severity] < severityRank[best.severity]) best = card+ }+ if (!best) return ''+ const more = events.length - 1+ const suffix = more > 0 ? ` (+${more} more)` : ''+ return composeXPost(best.title, best.lines[0], best.links[0], suffix)+}+/** A compact digest rendering: one block per event, capped. */export function digestCards(events: AlertEvent[]): { title: string; cards: AlertCard[]; omitted: number } {const cards = events.slice(0, 10).map(toCard)diff --git a/robinhood/hood-alerts/src/index.ts b/robinhood/hood-alerts/src/index.tsindex c705a4a96..845e35592 100644--- a/robinhood/hood-alerts/src/index.ts+++ b/robinhood/hood-alerts/src/index.ts@@ -10,8 +10,10 @@ import { Commands } from './commands/commands.js'import { ConsoleTransport } from './transports/console.js'import { TelegramTransport } from './transports/telegram.js'import { DiscordTransport } from './transports/discord.js'+import { XTransport, type XTransportConfig } from './transports/x.js'import type { Transport } from './transports/types.js'import { PremiumPaywall } from './premium/paywall.js'+import { defaultThreshold, parseTopic, PREMIUM_TOPICS, resolveWatchTarget } from './engine/topics.js'import { buildApp } from './server.js'async function main(): Promise<void> {@@ -43,6 +45,68 @@ async function main(): Promise<void> {await t.start()}+ // X (Twitter) is wired separately: it has no inbound bot (no watch/unwatch+ // DMs), so topics are config-driven instead of command-driven, and a+ // failed start() here only disables this one optional transport (never+ // crashes the process; Telegram/Discord/console keep running).+ if (config.xMode === 'official' || config.xMode === 'xactions') {+ const xConfig: XTransportConfig | null =+ config.xMode === 'official'+ ? config.xApiKey && config.xApiSecret && config.xAccessToken && config.xAccessSecret+ ? { mode: 'official', apiKey: config.xApiKey, apiSecret: config.xApiSecret, accessToken: config.xAccessToken, accessSecret: config.xAccessSecret }+ : null+ : config.xactionsUrl && config.xactionsToken+ ? { mode: 'xactions', xactionsUrl: config.xactionsUrl, xactionsToken: config.xactionsToken }+ : null+ if (!xConfig) {+ logger.warn(+ config.xMode === 'official'+ ? 'HOOD_ALERTS_X_MODE=official but HOOD_ALERTS_X_API_KEY/_API_SECRET/_ACCESS_TOKEN/_ACCESS_SECRET are not all set: x transport disabled'+ : 'HOOD_ALERTS_X_MODE=xactions but HOOD_ALERTS_XACTIONS_URL/_XACTIONS_TOKEN are not both set: x transport disabled',+ )+ } else {+ const x = new XTransport(xConfig)+ try {+ await x.start()+ engine.registerTransport(x)+ transports.push(x)++ // No inbound bot to run `watch` commands, so pre-register the+ // broadcast subscriber and subscribe it to HOOD_ALERTS_X_TOPICS the+ // same way Commands.watch() would: resolve each entry through the+ // real topic parser/threshold defaults, and reuse SubscriberRepo+ // directly rather than inventing a parallel subscription path.+ const xSubscriber = engine.subscribers.ensure('x', 'public', 'X broadcast')+ const xPremium = engine.entitlements.isPremium('x', 'public')+ for (const raw of config.xTopics) {+ const resolved = resolveWatchTarget(raw)+ if (!resolved.ok) {+ logger.warn({ topic: raw, error: resolved.error }, 'HOOD_ALERTS_X_TOPICS: skipping unrecognized topic')+ continue+ }+ if (PREMIUM_TOPICS.has(resolved.topic) && !xPremium) {+ logger.warn({ topic: raw }, 'HOOD_ALERTS_X_TOPICS: skipping premium-tier topic (x/public is not premium)')+ continue+ }+ const parsed = parseTopic(resolved.topic)+ const threshold = parsed+ ? defaultThreshold(parsed, {+ whaleUsd: config.detectors.whaleDefaultUsd,+ premiumPct: config.detectors.premiumDefaultPct,+ rugPct: config.detectors.rugDefaultPct,+ pricePct: config.detectors.priceDefaultPct,+ })+ : null+ engine.subscribers.subscribe(xSubscriber.id, resolved.topic, threshold)+ if (parsed?.kind === 'token') engine.notifyWatchChange()+ }+ logger.info({ mode: config.xMode, topics: config.xTopics }, 'x transport online')+ } catch (error) {+ logger.warn({ err: String(error) }, 'x transport failed to start: x transport disabled')+ }+ }+ }+const paywall = new PremiumPaywall(config, engine.entitlements)if (!paywall.enabled) logger.warn('premium purchases disabled (set HOOD402_PAY_TO + facilitator or settler key)')diff --git a/robinhood/hood-alerts/src/server.ts b/robinhood/hood-alerts/src/server.tsindex 5f4e952e5..1eb9f21be 100644--- a/robinhood/hood-alerts/src/server.ts+++ b/robinhood/hood-alerts/src/server.ts@@ -41,13 +41,18 @@ export function buildApp(deps: ServerDeps): Hono {const validTarget = (c: { req: { query(k: string): string | undefined } }): { platform: Platform; chat: string } | null => {const platform = c.req.query('platform')const chat = c.req.query('chat')- if ((platform !== 'telegram' && platform !== 'discord' && platform !== 'console') || !chat || chat.length > 64) return null+ if (+ (platform !== 'telegram' && platform !== 'discord' && platform !== 'console' && platform !== 'x') ||+ !chat ||+ chat.length > 64+ )+ return nullreturn { platform, chat }}app.get('/premium/status', (c) => {const target = validTarget(c)- if (!target) return c.json({ error: 'pass ?platform=telegram|discord&chat=<chat id>' }, 400)+ if (!target) return c.json({ error: 'pass ?platform=telegram|discord|x&chat=<chat id>' }, 400)const entitlement = deps.engine.entitlements.get(target.platform, target.chat)const remaining = deps.engine.entitlements.remainingS(target.platform, target.chat)return c.json({@@ -60,7 +65,7 @@ export function buildApp(deps: ServerDeps): Hono {app.post('/premium/activate', async (c) => {const target = validTarget(c)- if (!target) return c.json({ error: 'pass ?platform=telegram|discord&chat=<chat id>' }, 400)+ if (!target) return c.json({ error: 'pass ?platform=telegram|discord|x&chat=<chat id>' }, 400)const result = await deps.paywall.activate(target.platform, target.chat, c.req.header(PAYMENT_HEADER), c.req.url)if (result.status === 200) {c.header('X-PAYMENT-RESPONSE', result.settlementHeader)diff --git a/robinhood/hood-alerts/src/transports/x.ts b/robinhood/hood-alerts/src/transports/x.tsnew file mode 100644index 000000000..bcaf578f5--- /dev/null+++ b/robinhood/hood-alerts/src/transports/x.ts@@ -0,0 +1,193 @@+import { createHmac, randomBytes } from 'node:crypto'+import { logger } from '../logger.js'+import type { AlertEvent } from '../engine/events.js'+import { cardToXDigestPost, cardToXPost, toCard } from '../format/cards.js'+import type { Transport } from './types.js'++/** Which mode a self-hosted instance picked for X posting. */+export type XMode = 'official' | 'xactions'++export interface XTransportConfig {+ mode: XMode+ // official mode: X API v2 OAuth1 user-context credentials.+ apiKey?: string+ apiSecret?: string+ accessToken?: string+ accessSecret?: string+ // xactions mode: a self-hosted https://github.com/nirholas/XActions instance.+ xactionsUrl?: string+ xactionsToken?: string+}++interface OAuth1Credentials {+ consumerKey: string+ consumerSecret: string+ token: string+ tokenSecret: string+}++/** RFC 3986 percent-encoding: stricter than encodeURIComponent (also escapes !*'()). */+function percentEncode(value: string): string {+ return encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)+}++/**+ * Build an OAuth 1.0a `Authorization` header per RFC 5849 for one HTTP+ * request, HMAC-SHA1 signed with the user's access token secret. X's v2+ * tweet-creation endpoint requires this (user-context OAuth1); app-only+ * bearer tokens cannot post. No extra dependency: Node's `crypto` module is+ * enough for HMAC-SHA1 and base64.+ *+ * `timestamp`/`nonceValue` are injectable so tests can assert a deterministic+ * signature; real callers should omit them and get fresh values every+ * request (OAuth1 treats a reused nonce+timestamp pair as a replay).+ */+export function buildOAuth1Header(+ method: string,+ url: string,+ creds: OAuth1Credentials,+ extraParams: Record<string, string> = {},+ timestamp: number = Math.floor(Date.now() / 1000),+ nonceValue: string = randomBytes(16).toString('hex'),+): string {+ const oauthParams: Record<string, string> = {+ oauth_consumer_key: creds.consumerKey,+ oauth_nonce: nonceValue,+ oauth_signature_method: 'HMAC-SHA1',+ oauth_timestamp: String(timestamp),+ oauth_token: creds.token,+ oauth_version: '1.0',+ }++ const signingParams = { ...oauthParams, ...extraParams }+ const paramString = Object.keys(signingParams)+ .sort()+ .map((key) => `${percentEncode(key)}=${percentEncode(signingParams[key] as string)}`)+ .join('&')+ const baseString = `${method.toUpperCase()}&${percentEncode(url)}&${percentEncode(paramString)}`+ const signingKey = `${percentEncode(creds.consumerSecret)}&${percentEncode(creds.tokenSecret)}`+ const signature = createHmac('sha1', signingKey).update(baseString).digest('base64')++ const headerParams: Record<string, string> = { ...oauthParams, oauth_signature: signature }+ return (+ 'OAuth ' ++ Object.keys(headerParams)+ .sort()+ .map((key) => `${percentEncode(key)}="${percentEncode(headerParams[key] as string)}"`)+ .join(', ')+ )+}++/**+ * The X (Twitter) transport. Push-only: there is no inbound command bot (an+ * X broadcast account cannot DM back the way Telegram/Discord bots do), so+ * `start()`/`stop()` do no long-lived connection work, just credential+ * validation. Two modes, chosen once at startup by `cfg.mode`:+ *+ * - `official`: the real X API v2 (`POST /2/tweets`), OAuth1-signed with the+ * user's own developer app credentials. ToS-compliant, costs money at X's+ * paid API tiers.+ * - `xactions`: a self-hosted https://github.com/nirholas/XActions instance,+ * posting via a browser-automation-driven X session instead of the+ * official API. Free, but carries ToS risk, and posting is queued/async+ * rather than confirmed synchronously.+ */+export class XTransport implements Transport {+ readonly platform = 'x' as const++ constructor(private readonly cfg: XTransportConfig) {}++ async start(): Promise<void> {+ if (this.cfg.mode === 'official') {+ const missing: string[] = []+ if (!this.cfg.apiKey) missing.push('HOOD_ALERTS_X_API_KEY')+ if (!this.cfg.apiSecret) missing.push('HOOD_ALERTS_X_API_SECRET')+ if (!this.cfg.accessToken) missing.push('HOOD_ALERTS_X_ACCESS_TOKEN')+ if (!this.cfg.accessSecret) missing.push('HOOD_ALERTS_X_ACCESS_SECRET')+ if (missing.length > 0) {+ throw new Error(`x transport (official mode) is missing required env var(s): ${missing.join(', ')}`)+ }+ logger.info('x transport active (official API v2, OAuth1 user context)')+ return+ }+ const missing: string[] = []+ if (!this.cfg.xactionsUrl) missing.push('HOOD_ALERTS_XACTIONS_URL')+ if (!this.cfg.xactionsToken) missing.push('HOOD_ALERTS_XACTIONS_TOKEN')+ if (missing.length > 0) {+ throw new Error(`x transport (xactions mode) is missing required env var(s): ${missing.join(', ')}`)+ }+ logger.info({ url: this.cfg.xactionsUrl }, 'x transport active (self-hosted xactions, ToS risk: not the official API)')+ }++ async stop(): Promise<void> {+ // stateless HTTP posting; nothing to close+ }++ async sendAlert(chatId: string, event: AlertEvent): Promise<void> {+ const text = cardToXPost(toCard(event))+ const result = await this.post(text)+ logger.info({ chatId, eventType: event.type, ...result }, 'x post sent')+ }++ async sendDigest(chatId: string, events: AlertEvent[]): Promise<void> {+ const text = cardToXDigestPost(events)+ const result = await this.post(text)+ logger.info(+ { chatId, count: events.length, summarized: events.map((e) => e.type), ...result },+ 'x digest sent (posted the most significant event only; see "summarized" for the full batch)',+ )+ }++ private async post(text: string): Promise<{ id?: string; queued?: boolean }> {+ return this.cfg.mode === 'official' ? this.postOfficial(text) : this.postXactions(text)+ }++ private async postOfficial(text: string): Promise<{ id: string }> {+ const url = 'https://api.twitter.com/2/tweets'+ const creds: OAuth1Credentials = {+ consumerKey: this.cfg.apiKey as string,+ consumerSecret: this.cfg.apiSecret as string,+ token: this.cfg.accessToken as string,+ tokenSecret: this.cfg.accessSecret as string,+ }+ const res = await fetch(url, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ authorization: buildOAuth1Header('POST', url, creds),+ },+ body: JSON.stringify({ text }),+ signal: AbortSignal.timeout(15_000),+ })+ if (!res.ok) {+ const detail = await res.text().catch(() => '')+ throw new Error(`X API POST /2/tweets failed: ${res.status} ${res.statusText} ${detail.slice(0, 300)}`)+ }+ const body = (await res.json()) as { data?: { id?: string } }+ const id = body.data?.id+ if (!id) throw new Error(`X API POST /2/tweets returned no tweet id: ${JSON.stringify(body).slice(0, 300)}`)+ return { id }+ }++ private async postXactions(text: string): Promise<{ queued: true }> {+ const url = `${this.cfg.xactionsUrl}/api/posting/tweet`+ const res = await fetch(url, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ authorization: `Bearer ${this.cfg.xactionsToken}`,+ },+ body: JSON.stringify({ text }),+ signal: AbortSignal.timeout(15_000),+ })+ if (!res.ok) {+ const detail = await res.text().catch(() => '')+ throw new Error(`xactions POST /api/posting/tweet failed: ${res.status} ${res.statusText} ${detail.slice(0, 300)}`)+ }+ // xactions queues the post through a browser-automation session; a 2xx+ // here means accepted, not delivered. It does not confirm the tweet+ // actually landed the way the official API's tweet id does.+ logger.info({ url }, 'x post queued via xactions: delivery is not confirmed synchronously')+ return { queued: true }+ }+}diff --git a/robinhood/hood-alerts/tests/cards.test.ts b/robinhood/hood-alerts/tests/cards.test.tsindex bd39aa7eb..3423846e0 100644--- a/robinhood/hood-alerts/tests/cards.test.ts+++ b/robinhood/hood-alerts/tests/cards.test.ts@@ -1,5 +1,16 @@import { describe, expect, it } from 'vitest'-import { cardToDiscordEmbed, cardToText, cardToTelegramHtml, digestCards, short, toCard, usd } from '../src/format/cards.js'+import {+ cardToDiscordEmbed,+ cardToText,+ cardToTelegramHtml,+ cardToXDigestPost,+ cardToXPost,+ digestCards,+ short,+ toCard,+ usd,+ X_POST_LIMIT,+} from '../src/format/cards.js'import type { AlertEvent } from '../src/engine/events.js'const TOKEN = '0x1234567890123456789012345678901234567890' as `0x${string}`@@ -119,6 +130,71 @@ describe('cardToText / cardToTelegramHtml / cardToDiscordEmbed', () => {})})+describe('cardToXPost', () => {+ it('fits a normal card comfortably under the limit and includes the link', () => {+ const e: AlertEvent = { type: 'graduation', token: TOKEN, symbol: 'FOO', name: null, pool: TOKEN, blockNumber: 1n, transactionHash: '0x1', at: 0 }+ const post = cardToXPost(toCard(e))+ expect(post.length).toBeLessThanOrEqual(X_POST_LIMIT)+ expect(post).toContain('Graduated: FOO')+ expect(post.endsWith(toCard(e).links[0]?.url ?? '')).toBe(true)+ })++ it('truncates long text with an ellipsis but never truncates the URL', () => {+ const e: AlertEvent = {+ type: 'launch',+ launchpad: 'noxa',+ token: TOKEN,+ symbol: 'FOO',+ name: 'A'.repeat(400),+ creator: TOKEN,+ pool: TOKEN,+ blockNumber: 5n,+ transactionHash: '0xabc',+ at: 0,+ }+ const card = toCard(e)+ const post = cardToXPost(card)+ const url = card.links[0]?.url as string+ expect(post.length).toBeLessThanOrEqual(X_POST_LIMIT)+ expect(post).toContain('…')+ expect(post.endsWith(url)).toBe(true)+ expect(post).toContain(url) // the full, un-truncated URL is present verbatim+ })++ it('renders a card with no links (title + line only) under the limit', () => {+ const card = { emojiless: true as const, title: 'Short title', lines: ['one line'], links: [], severity: 'info' as const }+ const post = cardToXPost(card)+ expect(post).toBe('Short title: one line')+ expect(post.length).toBeLessThanOrEqual(X_POST_LIMIT)+ })+})++describe('cardToXDigestPost', () => {+ function launchEvent(i: number): AlertEvent {+ return { type: 'launch', launchpad: 'noxa', token: TOKEN, symbol: `T${i}`, name: null, creator: TOKEN, pool: TOKEN, blockNumber: BigInt(i), transactionHash: '0x1', at: 0 }+ }+ function liquidityPullEvent(): AlertEvent {+ return { type: 'liquidity_pull', token: TOKEN, symbol: 'RUG', pool: TOKEN, quoteAsset: 'USDG', droppedPct: 80, beforeUsd: 100_000, afterUsd: 20_000, at: 0 }+ }++ it('picks the highest-severity event and appends a "+N more" count', () => {+ const events = [launchEvent(1), launchEvent(2), liquidityPullEvent(), launchEvent(3)]+ const post = cardToXDigestPost(events)+ expect(post).toContain('Liquidity pull: RUG')+ expect(post).toContain('(+3 more)')+ expect(post.length).toBeLessThanOrEqual(X_POST_LIMIT)+ })++ it('omits the "+N more" suffix for a single event', () => {+ const post = cardToXDigestPost([launchEvent(1)])+ expect(post).not.toContain('more)')+ })++ it('returns an empty string for an empty batch rather than throwing', () => {+ expect(cardToXDigestPost([])).toBe('')+ })+})+describe('digestCards', () => {function holdersEvent(i: number): AlertEvent {return { type: 'holders', token: TOKEN, symbol: `T${i}`, milestone: i, count: i, at: 0 }diff --git a/robinhood/hood-alerts/tests/commands.test.ts b/robinhood/hood-alerts/tests/commands.test.tsindex 565452bf9..c73391c69 100644--- a/robinhood/hood-alerts/tests/commands.test.ts+++ b/robinhood/hood-alerts/tests/commands.test.ts@@ -14,6 +14,14 @@ function makeConfig(overrides: Partial<Config> = {}): Config {telegramToken: null,discordToken: null,discordAppId: null,+ xMode: undefined,+ xApiKey: null,+ xApiSecret: null,+ xAccessToken: null,+ xAccessSecret: null,+ xactionsUrl: null,+ xactionsToken: null,+ xTopics: [],premiumRail: 'hood402',payTo: null,facilitatorUrl: null,diff --git a/robinhood/hood-alerts/tests/config.test.ts b/robinhood/hood-alerts/tests/config.test.tsindex 1e3bc5b09..6f30f7239 100644--- a/robinhood/hood-alerts/tests/config.test.ts+++ b/robinhood/hood-alerts/tests/config.test.ts@@ -9,6 +9,14 @@ const ENV_KEYS = ['HOOD_ALERTS_TELEGRAM_TOKEN','HOOD_ALERTS_DISCORD_TOKEN','HOOD_ALERTS_DISCORD_APP_ID',+ 'HOOD_ALERTS_X_MODE',+ 'HOOD_ALERTS_X_API_KEY',+ 'HOOD_ALERTS_X_API_SECRET',+ 'HOOD_ALERTS_X_ACCESS_TOKEN',+ 'HOOD_ALERTS_X_ACCESS_SECRET',+ 'HOOD_ALERTS_XACTIONS_URL',+ 'HOOD_ALERTS_XACTIONS_TOKEN',+ 'HOOD_ALERTS_X_TOPICS','HOOD_ALERTS_PREMIUM_RAIL','HOOD402_PAY_TO','HOOD402_FACILITATOR_URL',@@ -50,6 +58,10 @@ describe('loadConfig', () => {expect(config.publicUrl).toBe('http://localhost:8080')expect(config.telegramToken).toBeNull()expect(config.discordToken).toBeNull()+ expect(config.xMode).toBeUndefined()+ expect(config.xApiKey).toBeNull()+ expect(config.xactionsUrl).toBeNull()+ expect(config.xTopics).toEqual(['launches', 'graduations', 'whales'])expect(config.premiumRail).toBe('hood402')expect(config.payTo).toBeNull()expect(config.premiumPriceUsdg).toBe('5')@@ -107,6 +119,23 @@ describe('loadConfig', () => {expect(loadConfig().dbPath).toBe('./data/hood-alerts.db')})+ it('accepts a well-formed HOOD_ALERTS_X_MODE', () => {+ process.env.HOOD_ALERTS_X_MODE = 'official'+ expect(loadConfig().xMode).toBe('official')+ process.env.HOOD_ALERTS_X_MODE = 'xactions'+ expect(loadConfig().xMode).toBe('xactions')+ })++ it('rejects an unrecognized HOOD_ALERTS_X_MODE', () => {+ process.env.HOOD_ALERTS_X_MODE = 'bluesky'+ expect(() => loadConfig()).toThrow(/HOOD_ALERTS_X_MODE must be "official" or "xactions"/)+ })++ it('splits and trims HOOD_ALERTS_X_TOPICS, dropping empty entries', () => {+ process.env.HOOD_ALERTS_X_TOPICS = ' launches, whales ,,premiums '+ expect(loadConfig().xTopics).toEqual(['launches', 'whales', 'premiums'])+ })+it('reads through custom detector tuning', () => {process.env.HOOD_ALERTS_WHALE_FLOOR_USD = '2500'process.env.HOOD_ALERTS_RUG_DEFAULT_PCT = '15'diff --git a/robinhood/hood-alerts/tests/paywall.test.ts b/robinhood/hood-alerts/tests/paywall.test.tsindex 0b7f4cd63..0be2db265 100644--- a/robinhood/hood-alerts/tests/paywall.test.ts+++ b/robinhood/hood-alerts/tests/paywall.test.ts@@ -23,6 +23,14 @@ function makeConfig(overrides: Partial<Config> = {}): Config {telegramToken: null,discordToken: null,discordAppId: null,+ xMode: undefined,+ xApiKey: null,+ xApiSecret: null,+ xAccessToken: null,+ xAccessSecret: null,+ xactionsUrl: null,+ xactionsToken: null,+ xTopics: [],premiumRail: 'hood402',payTo: null,facilitatorUrl: null,diff --git a/robinhood/hood-alerts/tests/server.test.ts b/robinhood/hood-alerts/tests/server.test.tsindex f2e50d578..cdfad100a 100644--- a/robinhood/hood-alerts/tests/server.test.ts+++ b/robinhood/hood-alerts/tests/server.test.ts@@ -27,6 +27,14 @@ function makeConfig(): Config {telegramToken: null,discordToken: null,discordAppId: null,+ xMode: undefined,+ xApiKey: null,+ xApiSecret: null,+ xAccessToken: null,+ xAccessSecret: null,+ xactionsUrl: null,+ xactionsToken: null,+ xTopics: [],premiumRail: 'hood402',payTo: null,facilitatorUrl: null,diff --git a/robinhood/hood-alerts/tests/x-transport.test.ts b/robinhood/hood-alerts/tests/x-transport.test.tsnew file mode 100644index 000000000..fc5b784d8--- /dev/null+++ b/robinhood/hood-alerts/tests/x-transport.test.ts@@ -0,0 +1,200 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { buildOAuth1Header, XTransport, type XTransportConfig } from '../src/transports/x.js'+import { logger } from '../src/logger.js'+import type { AlertEvent } from '../src/engine/events.js'++const TOKEN = '0x1234567890123456789012345678901234567890' as `0x${string}`++const OFFICIAL_CFG: XTransportConfig = {+ mode: 'official',+ apiKey: 'consumer-key',+ apiSecret: 'consumer-secret',+ accessToken: 'access-token',+ accessSecret: 'access-secret',+}++const XACTIONS_CFG: XTransportConfig = {+ mode: 'xactions',+ xactionsUrl: 'https://xactions.example.com',+ xactionsToken: 'bearer-token',+}++function whaleEvent(): AlertEvent {+ return {+ type: 'whale',+ source: 'uniswap-v3',+ token: TOKEN,+ symbol: 'FOO',+ side: 'buy',+ usd: 12_000,+ trader: TOKEN,+ blockNumber: 1n,+ transactionHash: '0x1',+ at: 0,+ }+}++const originalFetch = global.fetch+let infoSpy: ReturnType<typeof vi.spyOn>++beforeEach(() => {+ infoSpy = vi.spyOn(logger, 'info').mockImplementation(() => logger)+ vi.spyOn(logger, 'warn').mockImplementation(() => logger)+})++afterEach(() => {+ global.fetch = originalFetch+ vi.restoreAllMocks()+})++describe('buildOAuth1Header', () => {+ const creds = { consumerKey: 'ck', consumerSecret: 'cs', token: 'tk', tokenSecret: 'ts' }++ it('produces a well-formed Authorization header with every required OAuth1 field', () => {+ const header = buildOAuth1Header('POST', 'https://api.twitter.com/2/tweets', creds, {}, 1_700_000_000, 'fixed-nonce')+ expect(header.startsWith('OAuth ')).toBe(true)+ for (const key of ['oauth_consumer_key', 'oauth_nonce', 'oauth_signature_method', 'oauth_signature', 'oauth_timestamp', 'oauth_token', 'oauth_version']) {+ expect(header).toContain(`${key}="`)+ }+ expect(header).toContain('oauth_signature_method="HMAC-SHA1"')+ expect(header).toContain('oauth_version="1.0"')+ expect(header).toContain('oauth_consumer_key="ck"')+ expect(header).toContain('oauth_token="tk"')+ expect(header).toContain('oauth_timestamp="1700000000"')+ expect(header).toContain('oauth_nonce="fixed-nonce"')+ })++ it('is deterministic for the same method/url/creds/timestamp/nonce', () => {+ const a = buildOAuth1Header('POST', 'https://api.twitter.com/2/tweets', creds, {}, 1_700_000_000, 'fixed-nonce')+ const b = buildOAuth1Header('POST', 'https://api.twitter.com/2/tweets', creds, {}, 1_700_000_000, 'fixed-nonce')+ expect(a).toBe(b)+ })++ it('changes the signature when the URL changes (proves the base string is bound to the request)', () => {+ const a = buildOAuth1Header('POST', 'https://api.twitter.com/2/tweets', creds, {}, 1_700_000_000, 'fixed-nonce')+ const b = buildOAuth1Header('POST', 'https://api.twitter.com/2/other', creds, {}, 1_700_000_000, 'fixed-nonce')+ expect(a).not.toBe(b)+ })++ it('percent-encodes reserved characters in credential values', () => {+ const weirdCreds = { consumerKey: 'ck !*()', consumerSecret: 'cs', token: 'tk', tokenSecret: 'ts' }+ const header = buildOAuth1Header('POST', 'https://api.twitter.com/2/tweets', weirdCreds, {}, 1_700_000_000, 'n')+ expect(header).not.toContain('oauth_consumer_key="ck !*()"')+ expect(header).toContain('oauth_consumer_key="ck%20%21%2A%28%29"')+ })+})++describe('XTransport.start', () => {+ it('has the x platform', () => {+ expect(new XTransport(OFFICIAL_CFG).platform).toBe('x')+ })++ it('resolves when official mode has all four credentials', async () => {+ await expect(new XTransport(OFFICIAL_CFG).start()).resolves.toBeUndefined()+ })++ it('throws naming every missing credential in official mode', async () => {+ const t = new XTransport({ mode: 'official' })+ await expect(t.start()).rejects.toThrow(+ /HOOD_ALERTS_X_API_KEY.*HOOD_ALERTS_X_API_SECRET.*HOOD_ALERTS_X_ACCESS_TOKEN.*HOOD_ALERTS_X_ACCESS_SECRET/s,+ )+ })++ it('throws naming only the one missing official credential', async () => {+ const t = new XTransport({ ...OFFICIAL_CFG, accessSecret: undefined })+ let message = ''+ try {+ await t.start()+ } catch (error) {+ message = String((error as Error).message)+ }+ expect(message).toContain('HOOD_ALERTS_X_ACCESS_SECRET')+ expect(message).not.toContain('HOOD_ALERTS_X_API_KEY')+ })++ it('resolves when xactions mode has both url and token', async () => {+ await expect(new XTransport(XACTIONS_CFG).start()).resolves.toBeUndefined()+ })++ it('throws naming every missing credential in xactions mode', async () => {+ const t = new XTransport({ mode: 'xactions' })+ await expect(t.start()).rejects.toThrow(/HOOD_ALERTS_XACTIONS_URL.*HOOD_ALERTS_XACTIONS_TOKEN/s)+ })+})++describe('XTransport.sendAlert (official mode)', () => {+ it('POSTs to /2/tweets with an OAuth1 Authorization header and a compact body', async () => {+ const fetchSpy = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: { id: 'tweet-1' } }) })+ global.fetch = fetchSpy as unknown as typeof fetch+ const t = new XTransport(OFFICIAL_CFG)+ await t.sendAlert('public', whaleEvent())++ expect(fetchSpy).toHaveBeenCalledTimes(1)+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit]+ expect(url).toBe('https://api.twitter.com/2/tweets')+ expect(init.method).toBe('POST')+ const headers = init.headers as Record<string, string>+ expect(headers.authorization.startsWith('OAuth ')).toBe(true)+ expect(headers['content-type']).toBe('application/json')+ const body = JSON.parse(init.body as string) as { text: string }+ expect(body.text).toContain('Whale buy')+ expect(body.text.length).toBeLessThanOrEqual(280)+ })++ it('throws a diagnosable error on a non-2xx response', async () => {+ global.fetch = vi.fn().mockResolvedValue({ ok: false, status: 403, statusText: 'Forbidden', text: async () => '{"detail":"not enough scope"}' }) as unknown as typeof fetch+ const t = new XTransport(OFFICIAL_CFG)+ await expect(t.sendAlert('public', whaleEvent())).rejects.toThrow(/403.*not enough scope/s)+ })++ it('throws when the response has no tweet id', async () => {+ global.fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }) as unknown as typeof fetch+ const t = new XTransport(OFFICIAL_CFG)+ await expect(t.sendAlert('public', whaleEvent())).rejects.toThrow(/no tweet id/)+ })+})++describe('XTransport.sendAlert / sendDigest (xactions mode)', () => {+ it('POSTs to {url}/api/posting/tweet with a bearer token and treats 2xx as queued', async () => {+ const fetchSpy = vi.fn().mockResolvedValue({ ok: true, status: 200 })+ global.fetch = fetchSpy as unknown as typeof fetch+ const t = new XTransport(XACTIONS_CFG)+ await t.sendAlert('public', whaleEvent())++ expect(fetchSpy).toHaveBeenCalledTimes(1)+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit]+ expect(url).toBe('https://xactions.example.com/api/posting/tweet')+ const headers = init.headers as Record<string, string>+ expect(headers.authorization).toBe('Bearer bearer-token')+ })++ it('logs that xactions delivery is not confirmed synchronously', async () => {+ global.fetch = vi.fn().mockResolvedValue({ ok: true, status: 200 }) as unknown as typeof fetch+ const t = new XTransport(XACTIONS_CFG)+ await t.sendAlert('public', whaleEvent())+ expect(infoSpy.mock.calls.some((c) => String(c[1] ?? '').includes('not confirmed synchronously'))).toBe(true)+ })++ it('throws a diagnosable error on a non-2xx response', async () => {+ global.fetch = vi.fn().mockResolvedValue({ ok: false, status: 503, statusText: 'Service Unavailable', text: async () => 'upstream down' }) as unknown as typeof fetch+ const t = new XTransport(XACTIONS_CFG)+ await expect(t.sendAlert('public', whaleEvent())).rejects.toThrow(/503.*upstream down/s)+ })++ it('sendDigest posts the most significant event with a summarized-count log', async () => {+ const fetchSpy = vi.fn().mockResolvedValue({ ok: true, status: 200 })+ global.fetch = fetchSpy as unknown as typeof fetch+ const t = new XTransport(XACTIONS_CFG)+ const events = [whaleEvent(), whaleEvent(), whaleEvent()]+ await t.sendDigest('public', events)++ expect(fetchSpy).toHaveBeenCalledTimes(1)+ const [, init] = fetchSpy.mock.calls[0] as [string, RequestInit]+ const body = JSON.parse(init.body as string) as { text: string }+ expect(body.text).toContain('(+2 more)')++ const digestLog = infoSpy.mock.calls.find((c) => String(c[1] ?? '').includes('x digest sent'))+ expect(digestLog).toBeDefined()+ expect((digestLog?.[0] as Record<string, unknown>).count).toBe(3)+ })+})diff --git a/robinhood/hood-cli/README.md b/robinhood/hood-cli/README.mdindex bc469a18a..c550fb7ef 100644--- a/robinhood/hood-cli/README.md+++ b/robinhood/hood-cli/README.md@@ -351,6 +351,29 @@ AES-256-GCM keystore (scrypt KDF, Node's built-in `crypto` — the same primitivWeb3 Secret Storage spec) to `~/.config/hood/keystore.json`. The private key never touches theconfig file or plaintext disk.+### `hood init`++The one-command onboarding wizard for the whole trading stack: this CLI's wallet, the+[`hood-traders`](https://github.com/nirholas/hood-traders) `llm-strategist` (bring your own key —+Claude, OpenAI, Groq, or OpenRouter), and the [`hood-alerts`](https://github.com/nirholas/hood-alerts)+Telegram bot / Discord bot / X (Twitter) auto-posting. Every step is optional — skip anything you+don't need with `n` or Enter.++```bash+hood init+```++It writes `hood-traders.env` and `hood-alerts.env` into the current directory (`--out <dir>` to+choose another). Copy each into the matching package as `.env` and run it:++```bash+cp hood-traders.env hood-traders/.env && cd hood-traders && npx hood-traders+cp hood-alerts.env hood-alerts/.env && cd hood-alerts && npx hood-alerts+```++Needs an interactive terminal (secrets are typed, not passed as flags) — in CI or a non-interactive+shell, copy `hood-traders/.env.example` and `hood-alerts/.env.example` by hand instead.+## Wallet & signingEvery write command (`swap --execute`, `transfer`, `deploy-token --execute`, `config setdiff --git a/robinhood/hood-cli/docs/commands-data.json b/robinhood/hood-cli/docs/commands-data.jsonindex 54d80962f..971cc2265 100644--- a/robinhood/hood-cli/docs/commands-data.json+++ b/robinhood/hood-cli/docs/commands-data.json@@ -1,6 +1,6 @@{- "generatedAt": "2026-07-12T13:59:00.458Z",- "root": "Usage: hood [options] [command]\n\nThe command-line toolkit for Robinhood Chain (4663) — instant reads, guarded\nwrites.\n\nOptions:\n -v, --version output the version number\n --json machine-readable JSON output\n --network <net> mainnet | testnet (default: \"mainnet\")\n --rpc <url> override the RPC endpoint\n --verbose show raw error causes\n --yes skip interactive confirmation on writes (still\n requires --execute)\n --acknowledge-eligibility affirm Stock Token acquisition eligibility\n (non-US/CA/UK/CH)\n --no-color disable ANSI colour\n -h, --help display help for command\n\nCommands:\n price [options] <symbol> Chainlink oracle price + DEX price + premium\n for a Stock Token\n stocks [options] The full Stock Token board with live Chainlink\n prices\n coins [options] Memecoin screener — newest or trending\n launches\n launches [options] Recent memecoin launches from NOXA and The\n Odyssey\n portfolio [options] <address> Multiplier-correct Stock Token positions + USD\n totals for an address\n tx <hash> Decode a transaction: status, transfers, gas,\n method\n token <address> Inspect a token: metadata, supply, multiplier,\n price\n watch [options] <addrOrToken> Live activity stream for an address or a token\n (ERC-20 transfers + native ETH)\n swap [options] Quote (default) or execute a Uniswap v3 swap\n between two tokens\n transfer [options] Send ETH or an ERC-20 token to an address\n faucet Print testnet faucet instructions + current\n testnet balances\n deploy-token [options] Deploy a fixed-supply ERC-20 from a JSON\n config (direct-rail, no launchpad)\n config Manage hood-cli settings (rpc, wallet,\n network)\n help [command] display help for command",+ "generatedAt": "2026-07-20T22:56:46.393Z",+ "root": "Usage: hood [options] [command]\n\nThe command-line toolkit for Robinhood Chain (4663) — instant reads, guarded\nwrites.\n\nOptions:\n -v, --version output the version number\n --json machine-readable JSON output\n --network <net> mainnet | testnet (default: \"mainnet\")\n --rpc <url> override the RPC endpoint\n --verbose show raw error causes\n --yes skip interactive confirmation on writes (still\n requires --execute)\n --acknowledge-eligibility affirm Stock Token acquisition eligibility\n (non-US/CA/UK/CH)\n --no-color disable ANSI colour\n -h, --help display help for command\n\nCommands:\n price [options] <symbol> Chainlink oracle price + DEX price + premium\n for a Stock Token\n stocks [options] The full Stock Token board with live Chainlink\n prices\n coins [options] Memecoin screener — newest or trending\n launches\n launches [options] Recent memecoin launches from NOXA and The\n Odyssey\n portfolio [options] <address> Multiplier-correct Stock Token positions + USD\n totals for an address\n tx <hash> Decode a transaction: status, transfers, gas,\n method\n token <address> Inspect a token: metadata, supply, multiplier,\n price\n watch [options] <addrOrToken> Live activity stream for an address or a token\n (ERC-20 transfers + native ETH)\n swap [options] Quote (default) or execute a Uniswap v3 swap\n between two tokens\n transfer [options] Send ETH or an ERC-20 token to an address\n faucet Print testnet faucet instructions + current\n testnet balances\n deploy-token [options] Deploy a fixed-supply ERC-20 from a JSON\n config (direct-rail, no launchpad)\n config Manage hood-cli settings (rpc, wallet,\n network)\n init [options] interactive setup wizard: wallet, LLM key\n (hood-traders), and Telegram/X (hood-alerts)\n help [command] display help for command","commands": [{"name": "price",@@ -53,6 +53,10 @@{"name": "config","help": "Usage: hood config [options] [command]\n\nManage hood-cli settings (rpc, wallet, network)\n\nOptions:\n -h, --help display help for command\n\nCommands:\n set <key> [value] set a config value (network, rpc, testnetRpc, alchemyKey,\n maxSpendUsd, wallet)\n get <key> print one config value\n list print the full config (secrets masked)\n help [command] display help for command"+ },+ {+ "name": "init",+ "help": "Usage: hood init [options]\n\ninteractive setup wizard: wallet, LLM key (hood-traders), and Telegram/X\n(hood-alerts)\n\nOptions:\n --out <dir> directory to write hood-traders.env / hood-alerts.env into\n (default: \".\")\n -h, --help display help for command"}]}diff --git a/robinhood/hood-cli/docs/commands.html b/robinhood/hood-cli/docs/commands.htmlindex 366ca6718..76047b17d 100644--- a/robinhood/hood-cli/docs/commands.html+++ b/robinhood/hood-cli/docs/commands.html@@ -36,13 +36,13 @@</main><footer class="wrap">- <p>Generated 2026-07-12. MIT licensed. Built by <a href="https://x.com/nichxbt">nirholas</a> · <a href="https://three.ws">three.ws</a>.</p>+ <p>Generated 2026-07-20. MIT licensed. Built by <a href="https://x.com/nichxbt">nirholas</a> · <a href="https://three.ws">three.ws</a>.</p></footer><script id="commands-data" type="application/json">{- "generatedAt": "2026-07-12T13:59:00.458Z",- "root": "Usage: hood [options] [command]\n\nThe command-line toolkit for Robinhood Chain (4663) — instant reads, guarded\nwrites.\n\nOptions:\n -v, --version output the version number\n --json machine-readable JSON output\n --network <net> mainnet | testnet (default: \"mainnet\")\n --rpc <url> override the RPC endpoint\n --verbose show raw error causes\n --yes skip interactive confirmation on writes (still\n requires --execute)\n --acknowledge-eligibility affirm Stock Token acquisition eligibility\n (non-US/CA/UK/CH)\n --no-color disable ANSI colour\n -h, --help display help for command\n\nCommands:\n price [options] <symbol> Chainlink oracle price + DEX price + premium\n for a Stock Token\n stocks [options] The full Stock Token board with live Chainlink\n prices\n coins [options] Memecoin screener — newest or trending\n launches\n launches [options] Recent memecoin launches from NOXA and The\n Odyssey\n portfolio [options] <address> Multiplier-correct Stock Token positions + USD\n totals for an address\n tx <hash> Decode a transaction: status, transfers, gas,\n method\n token <address> Inspect a token: metadata, supply, multiplier,\n price\n watch [options] <addrOrToken> Live activity stream for an address or a token\n (ERC-20 transfers + native ETH)\n swap [options] Quote (default) or execute a Uniswap v3 swap\n between two tokens\n transfer [options] Send ETH or an ERC-20 token to an address\n faucet Print testnet faucet instructions + current\n testnet balances\n deploy-token [options] Deploy a fixed-supply ERC-20 from a JSON\n config (direct-rail, no launchpad)\n config Manage hood-cli settings (rpc, wallet,\n network)\n help [command] display help for command",+ "generatedAt": "2026-07-20T22:56:46.393Z",+ "root": "Usage: hood [options] [command]\n\nThe command-line toolkit for Robinhood Chain (4663) — instant reads, guarded\nwrites.\n\nOptions:\n -v, --version output the version number\n --json machine-readable JSON output\n --network <net> mainnet | testnet (default: \"mainnet\")\n --rpc <url> override the RPC endpoint\n --verbose show raw error causes\n --yes skip interactive confirmation on writes (still\n requires --execute)\n --acknowledge-eligibility affirm Stock Token acquisition eligibility\n (non-US/CA/UK/CH)\n --no-color disable ANSI colour\n -h, --help display help for command\n\nCommands:\n price [options] <symbol> Chainlink oracle price + DEX price + premium\n for a Stock Token\n stocks [options] The full Stock Token board with live Chainlink\n prices\n coins [options] Memecoin screener — newest or trending\n launches\n launches [options] Recent memecoin launches from NOXA and The\n Odyssey\n portfolio [options] <address> Multiplier-correct Stock Token positions + USD\n totals for an address\n tx <hash> Decode a transaction: status, transfers, gas,\n method\n token <address> Inspect a token: metadata, supply, multiplier,\n price\n watch [options] <addrOrToken> Live activity stream for an address or a token\n (ERC-20 transfers + native ETH)\n swap [options] Quote (default) or execute a Uniswap v3 swap\n between two tokens\n transfer [options] Send ETH or an ERC-20 token to an address\n faucet Print testnet faucet instructions + current\n testnet balances\n deploy-token [options] Deploy a fixed-supply ERC-20 from a JSON\n config (direct-rail, no launchpad)\n config Manage hood-cli settings (rpc, wallet,\n network)\n init [options] interactive setup wizard: wallet, LLM key\n (hood-traders), and Telegram/X (hood-alerts)\n help [command] display help for command","commands": [{"name": "price",@@ -95,6 +95,10 @@{"name": "config","help": "Usage: hood config [options] [command]\n\nManage hood-cli settings (rpc, wallet, network)\n\nOptions:\n -h, --help display help for command\n\nCommands:\n set <key> [value] set a config value (network, rpc, testnetRpc, alchemyKey,\n maxSpendUsd, wallet)\n get <key> print one config value\n list print the full config (secrets masked)\n help [command] display help for command"+ },+ {+ "name": "init",+ "help": "Usage: hood init [options]\n\ninteractive setup wizard: wallet, LLM key (hood-traders), and Telegram/X\n(hood-alerts)\n\nOptions:\n --out <dir> directory to write hood-traders.env / hood-alerts.env into\n (default: \".\")\n -h, --help display help for command"}]}diff --git a/robinhood/hood-cli/docs/index.html b/robinhood/hood-cli/docs/index.htmlindex 9233094cc..87a94de80 100644--- a/robinhood/hood-cli/docs/index.html+++ b/robinhood/hood-cli/docs/index.html@@ -112,32 +112,32 @@ hood swap --sell USDG --buy WETH --amount 100 --execute</code></pre><script id="session-data" type="application/json">{- "capturedAt": "2026-07-12T13:54:03.577Z",+ "capturedAt": "2026-07-20T22:56:35.608Z","chain": "Robinhood Chain mainnet (4663)","frames": [{"prompt": "hood price AAPL",- "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mAAPL\u001b[22m \u001b[2m· Robinhood Chain mainnet\u001b[22m\n\u001b[2mOracle\u001b[22m \u001b[1m$315.50\u001b[22m\n\u001b[2mUpdated\u001b[22m \u001b[2m1d 18h ago\u001b[22m\n\u001b[2mDEX\u001b[22m \u001b[2mno pool\u001b[22m\n\u001b[2mPremium\u001b[22m \u001b[2m—\u001b[22m\n\u001b[2mToken\u001b[22m \u001b[90m0xaF3D…93f9\u001b[39m"+ "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mAAPL\u001b[22m \u001b[2m· Robinhood Chain mainnet\u001b[22m\n\u001b[2mOracle\u001b[22m \u001b[1m$326.49\u001b[22m\n\u001b[2mUpdated\u001b[22m \u001b[2m3h 0m ago\u001b[22m\n\u001b[2mDEX\u001b[22m $308.85\n\u001b[2mPremium\u001b[22m \u001b[31m-5.40%\u001b[39m\n\u001b[2mToken\u001b[22m \u001b[90m0xaF3D…93f9\u001b[39m"},{"prompt": "hood stocks --sort premium --dex --limit 6",- "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mStock Tokens\u001b[22m \u001b[2m· mainnet · 6 shown · 6 priced\u001b[22m\n\u001b[2mSYMBOL\u001b[22m \u001b[2mPRICE\u001b[22m \u001b[2mDEX\u001b[22m \u001b[2mPREMIUM\u001b[22m \u001b[2mAGE\u001b[22m \u001b[2mNAME\u001b[22m \u001b[2mADDRESS\u001b[22m \n\u001b[90m────────────────────────────────────────────────────────────────────────────────\u001b[39m\n\u001b[1mCLSK\u001b[22m $12.86 $15.51 \u001b[32m+20.58%\u001b[39m \u001b[2m1d 17h\u001b[22m \u001b[2mCleanSpark\u001b[22m \u001b[90m0xcBB9…Cee3\u001b[39m\n\u001b[1mIONQ\u001b[22m $43.08 $49.44 \u001b[32m+14.76%\u001b[39m \u001b[2m1d 18h\u001b[22m \u001b[2mIonQ\u001b[22m \u001b[90m0x5583…0EfE\u001b[39m\n\u001b[1mNBIS\u001b[22m $219.24 $248.41 \u001b[32m+13.31%\u001b[39m \u001b[2m1d 17h\u001b[22m \u001b[2mNebius Group\u001b[22m \u001b[90m0x9D9c…7931\u001b[39m\n\u001b[1mRGTI\u001b[22m $16.57 $18.57 \u001b[32m+12.06%\u001b[39m \u001b[2m1d 17h\u001b[22m \u001b[2mRigetti Computing\u001b[22m \u001b[90m0x2843…97Ba\u001b[39m\n\u001b[1mEWY\u001b[22m $183.77 $199.36 \u001b[32m+8.48%\u001b[39m \u001b[2m1d 20h\u001b[22m \u001b[2miShares MSCI South Kore…\u001b[22m \u001b[90m0x7f0a…13Fc\u001b[39m\n\u001b[1mTSM\u001b[22m $434.37 $424.15 \u001b[31m-2.35%\u001b[39m \u001b[2m1d 17h\u001b[22m \u001b[2mTaiwan Semiconductor Ma…\u001b[22m \u001b[90m0x58Ff…e7AA\u001b[39m"+ "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mStock Tokens\u001b[22m \u001b[2m· mainnet · 6 shown · 6 priced\u001b[22m\n\u001b[2mSYMBOL\u001b[22m \u001b[2mPRICE\u001b[22m \u001b[2mDEX\u001b[22m \u001b[2mPREMIUM\u001b[22m \u001b[2mAGE\u001b[22m \u001b[2mNAME\u001b[22m \u001b[2mADDRESS\u001b[22m \n\u001b[90m────────────────────────────────────────────────────────────────────────────────\u001b[39m\n\u001b[1mCLSK\u001b[22m $14.43 $14.67 \u001b[32m+1.65%\u001b[39m \u001b[2m2h 50m\u001b[22m \u001b[2mCleanSpark\u001b[22m \u001b[90m0xcBB9…Cee3\u001b[39m\n\u001b[1mTSM\u001b[22m $401.94 $398.48 \u001b[31m-0.86%\u001b[39m \u001b[2m4h 10m\u001b[22m \u001b[2mTaiwan Semiconductor Ma…\u001b[22m \u001b[90m0x58Ff…e7AA\u001b[39m\n\u001b[1mSLV\u001b[22m $50.97 $50.28 \u001b[31m-1.36%\u001b[39m \u001b[2m2h 59m\u001b[22m \u001b[2miShares Silver Trust\u001b[22m \u001b[90m0x411e…D89f\u001b[39m\n\u001b[1mAMZN\u001b[22m $249.88 $241.73 \u001b[31m-3.26%\u001b[39m \u001b[2m4h 15m\u001b[22m \u001b[2mAmazon\u001b[22m \u001b[90m0x12f1…bF54\u001b[39m\n\u001b[1mQQQ\u001b[22m $697.50 $672.03 \u001b[31m-3.65%\u001b[39m \u001b[2m3h 52m\u001b[22m \u001b[2mInvesco QQQ\u001b[22m \u001b[90m0xD5f3…de68\u001b[39m\n\u001b[1mAAPL\u001b[22m $326.49 $308.85 \u001b[31m-5.40%\u001b[39m \u001b[2m3h 0m\u001b[22m \u001b[2mApple\u001b[22m \u001b[90m0xaF3D…93f9\u001b[39m"},{"prompt": "hood launches --lookback 2000000 --limit 5 --names",- "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mLaunches\u001b[22m \u001b[2m· mainnet · 5\u001b[22m\n \u001b[2mBLOCK\u001b[22m \u001b[2mPAD\u001b[22m \u001b[2mTOKEN\u001b[22m \u001b[2mADDRESS\u001b[22m \u001b[2mCREATOR\u001b[22m \u001b[2mPOOL\u001b[22m \n\u001b[90m──────────────────────────────────────────────────────────────────\u001b[39m\n\u001b[2m#6880646\u001b[22m \u001b[38;5;79mNOXA\u001b[39m \u001b[1mdoginhood\u001b[22m \u001b[90m0x955b…6B44\u001b[39m \u001b[90m0x4Ba0…bdc2\u001b[39m \u001b[90m0xEFD7…6272\u001b[39m\n\u001b[2m#6880627\u001b[22m \u001b[38;5;79mNOXA\u001b[39m \u001b[1mDEBTCAT\u001b[22m \u001b[90m0x5dDf…9C05\u001b[39m \u001b[90m0xf1e6…762C\u001b[39m \u001b[90m0x7D58…132c\u001b[39m\n\u001b[2m#6880442\u001b[22m \u001b[38;5;79mNOXA\u001b[39m \u001b[1mTURWIMA\u001b[22m \u001b[90m0x7349…BDdD\u001b[39m \u001b[90m0x7A23…6B55\u001b[39m \u001b[90m0xE825…C1Bc\u001b[39m\n\u001b[2m#6880408\u001b[22m \u001b[38;5;79mNOXA\u001b[39m \u001b[1mHOODMAXXING\u001b[22m \u001b[90m0x2AE3…23cF\u001b[39m \u001b[90m0xAF02…5689\u001b[39m \u001b[90m0x68e7…5Ad4\u001b[39m\n\u001b[2m#6880399\u001b[22m \u001b[38;5;79mNOXA\u001b[39m \u001b[1mcashcoin\u001b[22m \u001b[90m0x3bcd…C9A6\u001b[39m \u001b[90m0xa732…CC87\u001b[39m \u001b[90m0x4ab0…a86d\u001b[39m"+ "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mLaunches\u001b[22m \u001b[2m· mainnet · 0\u001b[22m\n\u001b[2mNo launches in the scanned window. Widen it with --lookback, or --follow to stream new ones.\u001b[22m"},{"prompt": "hood portfolio 0x9701fb0aDe1E269c8f64Ec0C7b3cfADB31A13A52",- "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mPortfolio\u001b[22m \u001b[2m· 0x9701…3A52 · mainnet\u001b[22m\n\u001b[2mETH\u001b[22m 0.003784\n\u001b[2mUSDG\u001b[22m $0.0550\n\u001b[2mStocks\u001b[22m $0.00\n\u001b[2mTotal\u001b[22m \u001b[1m$0.0550\u001b[22m\n\n\u001b[2mNo Stock Token positions. Fund with `hood swap --sell USDG --buy <ticker>`.\u001b[22m"+ "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mPortfolio\u001b[22m \u001b[2m· 0x9701…3A52 · mainnet\u001b[22m\n\u001b[2mETH\u001b[22m 0.003625\n\u001b[2mUSDG\u001b[22m $0.0550\n\u001b[2mStocks\u001b[22m $0.00\n\u001b[2mTotal\u001b[22m \u001b[1m$0.0550\u001b[22m\n\n\u001b[2mNo Stock Token positions. Fund with `hood swap --sell USDG --buy <ticker>`.\u001b[22m"},{"prompt": "hood swap --sell USDG --buy WETH --amount 250",- "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mSwap quote\u001b[22m \u001b[2m· mainnet · add --execute to send\u001b[22m\n\u001b[2mSell\u001b[22m \u001b[1m250\u001b[22m USDG\n\u001b[2mBuy\u001b[22m \u001b[1m~0.138501866807990729\u001b[22m WETH\n\u001b[2mMin. received\u001b[22m \u001b[2m0.137809357473950775 WETH (0.50% slippage)\u001b[22m\n\u001b[2mRate\u001b[22m 1 USDG ≈ 0.000554 WETH\n\u001b[2mRoute\u001b[22m \u001b[2mdirect pool\u001b[22m"+ "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mSwap quote\u001b[22m \u001b[2m· mainnet · add --execute to send\u001b[22m\n\u001b[2mSell\u001b[22m \u001b[1m250\u001b[22m USDG\n\u001b[2mBuy\u001b[22m \u001b[1m~0.131861675469726043\u001b[22m WETH\n\u001b[2mMin. received\u001b[22m \u001b[2m0.131202367092377412 WETH (0.50% slippage)\u001b[22m\n\u001b[2mRate\u001b[22m 1 USDG ≈ 0.000527 WETH\n\u001b[2mRoute\u001b[22m \u001b[2mdirect pool\u001b[22m"},{"prompt": "hood tx 0x870a3bee3070f10e3c4f34271cfde70fd5aa0dc2eade6f07d01ae6c9a00285bd",- "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mTransaction\u001b[22m \u001b[2m0x870a…85bd\u001b[22m \u001b[32m● success\u001b[39m\n\u001b[2mFrom\u001b[22m \u001b[90m0xdf65…c23e\u001b[39m\n\u001b[2mTo\u001b[22m \u001b[90m0xd9ec…fccb\u001b[39m\n\u001b[2mValue\u001b[22m \u001b[1m0.0505 ETH\u001b[22m\n\u001b[2mMethod\u001b[22m \u001b[1m0x686399cb\u001b[22m\n\u001b[2mBlock\u001b[22m #5843692\n\u001b[2mWhen\u001b[22m \u001b[2m2026-07-10 05:54:38Z\u001b[22m\n\u001b[2mGas used\u001b[22m \u001b[2m6,845,934 @ 0.0485 gwei\u001b[22m\n\u001b[2mFee\u001b[22m 0.00033229 ETH\n\u001b[2mExplorer\u001b[22m \u001b[90mhttps://robinhoodchain.blockscout.com/tx/0x870a3bee3070f10e3c4f34271cfde70fd5aa0dc2eade6f07d01ae6c9a00285bd\u001b[39m\n\n\u001b[2mToken transfers\u001b[22m\n \u001b[90m0x0000…0000\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0xD9eC…FCcB\u001b[39m \u001b[1m1000000000\u001b[22m \u001b[38;5;79m💎👐\u001b[39m\n \u001b[90m0xD9eC…FCcB\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0x872B…14E7\u001b[39m \u001b[1m999999999.999999\u001b[22m \u001b[38;5;79m💎👐\u001b[39m\n \u001b[90m0x872B…14E7\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0xdF65…C23e\u001b[39m \u001b[1m35227361.211893\u001b[22m \u001b[38;5;79m💎👐\u001b[39m\n \u001b[90m0x0000…0000\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0xCaf6…5cb2\u001b[39m \u001b[1m0.05\u001b[22m \u001b[38;5;79mWETH\u001b[39m\n \u001b[90m0xCaf6…5cb2\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0x872B…14E7\u001b[39m \u001b[1m0.05\u001b[22m \u001b[38;5;79mWETH\u001b[39m"+ "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mTransaction\u001b[22m \u001b[2m0x870a…85bd\u001b[22m \u001b[32m● success\u001b[39m\n\u001b[2mFrom\u001b[22m \u001b[90m0xdf65…c23e\u001b[39m\n\u001b[2mTo\u001b[22m \u001b[90m0xd9ec…fccb\u001b[39m\n\u001b[2mValue\u001b[22m \u001b[1m0.0505 ETH\u001b[22m\n\u001b[2mMethod\u001b[22m \u001b[2m—\u001b[22m\n\u001b[2mBlock\u001b[22m #5843692\n\u001b[2mWhen\u001b[22m \u001b[2m2026-07-10 05:54:38Z\u001b[22m\n\u001b[2mGas used\u001b[22m \u001b[2m6,845,934 @ 0.0485 gwei\u001b[22m\n\u001b[2mFee\u001b[22m 0.00033229 ETH\n\u001b[2mExplorer\u001b[22m \u001b[90mhttps://robinhoodchain.blockscout.com/tx/0x870a3bee3070f10e3c4f34271cfde70fd5aa0dc2eade6f07d01ae6c9a00285bd\u001b[39m\n\n\u001b[2mToken transfers\u001b[22m\n \u001b[90m0x0000…0000\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0xD9eC…FCcB\u001b[39m \u001b[1m1000000000\u001b[22m \u001b[38;5;79m💎👐\u001b[39m\n \u001b[90m0xD9eC…FCcB\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0x872B…14E7\u001b[39m \u001b[1m999999999.999999\u001b[22m \u001b[38;5;79m💎👐\u001b[39m\n \u001b[90m0x872B…14E7\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0xdF65…C23e\u001b[39m \u001b[1m35227361.211893\u001b[22m \u001b[38;5;79m💎👐\u001b[39m\n \u001b[90m0x0000…0000\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0xCaf6…5cb2\u001b[39m \u001b[1m0.05\u001b[22m \u001b[38;5;79mWETH\u001b[39m\n \u001b[90m0xCaf6…5cb2\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0x872B…14E7\u001b[39m \u001b[1m0.05\u001b[22m \u001b[38;5;79mWETH\u001b[39m"}]}diff --git a/robinhood/hood-cli/docs/session.json b/robinhood/hood-cli/docs/session.jsonindex a03b70bae..e6e4ac3e2 100644--- a/robinhood/hood-cli/docs/session.json+++ b/robinhood/hood-cli/docs/session.json@@ -1,30 +1,30 @@{- "capturedAt": "2026-07-12T13:54:03.577Z",+ "capturedAt": "2026-07-20T22:56:35.608Z","chain": "Robinhood Chain mainnet (4663)","frames": [{"prompt": "hood price AAPL",- "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mAAPL\u001b[22m \u001b[2m· Robinhood Chain mainnet\u001b[22m\n\u001b[2mOracle\u001b[22m \u001b[1m$315.50\u001b[22m\n\u001b[2mUpdated\u001b[22m \u001b[2m1d 18h ago\u001b[22m\n\u001b[2mDEX\u001b[22m \u001b[2mno pool\u001b[22m\n\u001b[2mPremium\u001b[22m \u001b[2m—\u001b[22m\n\u001b[2mToken\u001b[22m \u001b[90m0xaF3D…93f9\u001b[39m"+ "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mAAPL\u001b[22m \u001b[2m· Robinhood Chain mainnet\u001b[22m\n\u001b[2mOracle\u001b[22m \u001b[1m$326.49\u001b[22m\n\u001b[2mUpdated\u001b[22m \u001b[2m3h 0m ago\u001b[22m\n\u001b[2mDEX\u001b[22m $308.85\n\u001b[2mPremium\u001b[22m \u001b[31m-5.40%\u001b[39m\n\u001b[2mToken\u001b[22m \u001b[90m0xaF3D…93f9\u001b[39m"},{"prompt": "hood stocks --sort premium --dex --limit 6",- "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mStock Tokens\u001b[22m \u001b[2m· mainnet · 6 shown · 6 priced\u001b[22m\n\u001b[2mSYMBOL\u001b[22m \u001b[2mPRICE\u001b[22m \u001b[2mDEX\u001b[22m \u001b[2mPREMIUM\u001b[22m \u001b[2mAGE\u001b[22m \u001b[2mNAME\u001b[22m \u001b[2mADDRESS\u001b[22m \n\u001b[90m────────────────────────────────────────────────────────────────────────────────\u001b[39m\n\u001b[1mCLSK\u001b[22m $12.86 $15.51 \u001b[32m+20.58%\u001b[39m \u001b[2m1d 17h\u001b[22m \u001b[2mCleanSpark\u001b[22m \u001b[90m0xcBB9…Cee3\u001b[39m\n\u001b[1mIONQ\u001b[22m $43.08 $49.44 \u001b[32m+14.76%\u001b[39m \u001b[2m1d 18h\u001b[22m \u001b[2mIonQ\u001b[22m \u001b[90m0x5583…0EfE\u001b[39m\n\u001b[1mNBIS\u001b[22m $219.24 $248.41 \u001b[32m+13.31%\u001b[39m \u001b[2m1d 17h\u001b[22m \u001b[2mNebius Group\u001b[22m \u001b[90m0x9D9c…7931\u001b[39m\n\u001b[1mRGTI\u001b[22m $16.57 $18.57 \u001b[32m+12.06%\u001b[39m \u001b[2m1d 17h\u001b[22m \u001b[2mRigetti Computing\u001b[22m \u001b[90m0x2843…97Ba\u001b[39m\n\u001b[1mEWY\u001b[22m $183.77 $199.36 \u001b[32m+8.48%\u001b[39m \u001b[2m1d 20h\u001b[22m \u001b[2miShares MSCI South Kore…\u001b[22m \u001b[90m0x7f0a…13Fc\u001b[39m\n\u001b[1mTSM\u001b[22m $434.37 $424.15 \u001b[31m-2.35%\u001b[39m \u001b[2m1d 17h\u001b[22m \u001b[2mTaiwan Semiconductor Ma…\u001b[22m \u001b[90m0x58Ff…e7AA\u001b[39m"+ "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mStock Tokens\u001b[22m \u001b[2m· mainnet · 6 shown · 6 priced\u001b[22m\n\u001b[2mSYMBOL\u001b[22m \u001b[2mPRICE\u001b[22m \u001b[2mDEX\u001b[22m \u001b[2mPREMIUM\u001b[22m \u001b[2mAGE\u001b[22m \u001b[2mNAME\u001b[22m \u001b[2mADDRESS\u001b[22m \n\u001b[90m────────────────────────────────────────────────────────────────────────────────\u001b[39m\n\u001b[1mCLSK\u001b[22m $14.43 $14.67 \u001b[32m+1.65%\u001b[39m \u001b[2m2h 50m\u001b[22m \u001b[2mCleanSpark\u001b[22m \u001b[90m0xcBB9…Cee3\u001b[39m\n\u001b[1mTSM\u001b[22m $401.94 $398.48 \u001b[31m-0.86%\u001b[39m \u001b[2m4h 10m\u001b[22m \u001b[2mTaiwan Semiconductor Ma…\u001b[22m \u001b[90m0x58Ff…e7AA\u001b[39m\n\u001b[1mSLV\u001b[22m $50.97 $50.28 \u001b[31m-1.36%\u001b[39m \u001b[2m2h 59m\u001b[22m \u001b[2miShares Silver Trust\u001b[22m \u001b[90m0x411e…D89f\u001b[39m\n\u001b[1mAMZN\u001b[22m $249.88 $241.73 \u001b[31m-3.26%\u001b[39m \u001b[2m4h 15m\u001b[22m \u001b[2mAmazon\u001b[22m \u001b[90m0x12f1…bF54\u001b[39m\n\u001b[1mQQQ\u001b[22m $697.50 $672.03 \u001b[31m-3.65%\u001b[39m \u001b[2m3h 52m\u001b[22m \u001b[2mInvesco QQQ\u001b[22m \u001b[90m0xD5f3…de68\u001b[39m\n\u001b[1mAAPL\u001b[22m $326.49 $308.85 \u001b[31m-5.40%\u001b[39m \u001b[2m3h 0m\u001b[22m \u001b[2mApple\u001b[22m \u001b[90m0xaF3D…93f9\u001b[39m"},{"prompt": "hood launches --lookback 2000000 --limit 5 --names",- "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mLaunches\u001b[22m \u001b[2m· mainnet · 5\u001b[22m\n \u001b[2mBLOCK\u001b[22m \u001b[2mPAD\u001b[22m \u001b[2mTOKEN\u001b[22m \u001b[2mADDRESS\u001b[22m \u001b[2mCREATOR\u001b[22m \u001b[2mPOOL\u001b[22m \n\u001b[90m──────────────────────────────────────────────────────────────────\u001b[39m\n\u001b[2m#6880646\u001b[22m \u001b[38;5;79mNOXA\u001b[39m \u001b[1mdoginhood\u001b[22m \u001b[90m0x955b…6B44\u001b[39m \u001b[90m0x4Ba0…bdc2\u001b[39m \u001b[90m0xEFD7…6272\u001b[39m\n\u001b[2m#6880627\u001b[22m \u001b[38;5;79mNOXA\u001b[39m \u001b[1mDEBTCAT\u001b[22m \u001b[90m0x5dDf…9C05\u001b[39m \u001b[90m0xf1e6…762C\u001b[39m \u001b[90m0x7D58…132c\u001b[39m\n\u001b[2m#6880442\u001b[22m \u001b[38;5;79mNOXA\u001b[39m \u001b[1mTURWIMA\u001b[22m \u001b[90m0x7349…BDdD\u001b[39m \u001b[90m0x7A23…6B55\u001b[39m \u001b[90m0xE825…C1Bc\u001b[39m\n\u001b[2m#6880408\u001b[22m \u001b[38;5;79mNOXA\u001b[39m \u001b[1mHOODMAXXING\u001b[22m \u001b[90m0x2AE3…23cF\u001b[39m \u001b[90m0xAF02…5689\u001b[39m \u001b[90m0x68e7…5Ad4\u001b[39m\n\u001b[2m#6880399\u001b[22m \u001b[38;5;79mNOXA\u001b[39m \u001b[1mcashcoin\u001b[22m \u001b[90m0x3bcd…C9A6\u001b[39m \u001b[90m0xa732…CC87\u001b[39m \u001b[90m0x4ab0…a86d\u001b[39m"+ "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mLaunches\u001b[22m \u001b[2m· mainnet · 0\u001b[22m\n\u001b[2mNo launches in the scanned window. Widen it with --lookback, or --follow to stream new ones.\u001b[22m"},{"prompt": "hood portfolio 0x9701fb0aDe1E269c8f64Ec0C7b3cfADB31A13A52",- "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mPortfolio\u001b[22m \u001b[2m· 0x9701…3A52 · mainnet\u001b[22m\n\u001b[2mETH\u001b[22m 0.003784\n\u001b[2mUSDG\u001b[22m $0.0550\n\u001b[2mStocks\u001b[22m $0.00\n\u001b[2mTotal\u001b[22m \u001b[1m$0.0550\u001b[22m\n\n\u001b[2mNo Stock Token positions. Fund with `hood swap --sell USDG --buy <ticker>`.\u001b[22m"+ "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mPortfolio\u001b[22m \u001b[2m· 0x9701…3A52 · mainnet\u001b[22m\n\u001b[2mETH\u001b[22m 0.003625\n\u001b[2mUSDG\u001b[22m $0.0550\n\u001b[2mStocks\u001b[22m $0.00\n\u001b[2mTotal\u001b[22m \u001b[1m$0.0550\u001b[22m\n\n\u001b[2mNo Stock Token positions. Fund with `hood swap --sell USDG --buy <ticker>`.\u001b[22m"},{"prompt": "hood swap --sell USDG --buy WETH --amount 250",- "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mSwap quote\u001b[22m \u001b[2m· mainnet · add --execute to send\u001b[22m\n\u001b[2mSell\u001b[22m \u001b[1m250\u001b[22m USDG\n\u001b[2mBuy\u001b[22m \u001b[1m~0.138501866807990729\u001b[22m WETH\n\u001b[2mMin. received\u001b[22m \u001b[2m0.137809357473950775 WETH (0.50% slippage)\u001b[22m\n\u001b[2mRate\u001b[22m 1 USDG ≈ 0.000554 WETH\n\u001b[2mRoute\u001b[22m \u001b[2mdirect pool\u001b[22m"+ "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mSwap quote\u001b[22m \u001b[2m· mainnet · add --execute to send\u001b[22m\n\u001b[2mSell\u001b[22m \u001b[1m250\u001b[22m USDG\n\u001b[2mBuy\u001b[22m \u001b[1m~0.131861675469726043\u001b[22m WETH\n\u001b[2mMin. received\u001b[22m \u001b[2m0.131202367092377412 WETH (0.50% slippage)\u001b[22m\n\u001b[2mRate\u001b[22m 1 USDG ≈ 0.000527 WETH\n\u001b[2mRoute\u001b[22m \u001b[2mdirect pool\u001b[22m"},{"prompt": "hood tx 0x870a3bee3070f10e3c4f34271cfde70fd5aa0dc2eade6f07d01ae6c9a00285bd",- "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mTransaction\u001b[22m \u001b[2m0x870a…85bd\u001b[22m \u001b[32m● success\u001b[39m\n\u001b[2mFrom\u001b[22m \u001b[90m0xdf65…c23e\u001b[39m\n\u001b[2mTo\u001b[22m \u001b[90m0xd9ec…fccb\u001b[39m\n\u001b[2mValue\u001b[22m \u001b[1m0.0505 ETH\u001b[22m\n\u001b[2mMethod\u001b[22m \u001b[1m0x686399cb\u001b[22m\n\u001b[2mBlock\u001b[22m #5843692\n\u001b[2mWhen\u001b[22m \u001b[2m2026-07-10 05:54:38Z\u001b[22m\n\u001b[2mGas used\u001b[22m \u001b[2m6,845,934 @ 0.0485 gwei\u001b[22m\n\u001b[2mFee\u001b[22m 0.00033229 ETH\n\u001b[2mExplorer\u001b[22m \u001b[90mhttps://robinhoodchain.blockscout.com/tx/0x870a3bee3070f10e3c4f34271cfde70fd5aa0dc2eade6f07d01ae6c9a00285bd\u001b[39m\n\n\u001b[2mToken transfers\u001b[22m\n \u001b[90m0x0000…0000\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0xD9eC…FCcB\u001b[39m \u001b[1m1000000000\u001b[22m \u001b[38;5;79m💎👐\u001b[39m\n \u001b[90m0xD9eC…FCcB\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0x872B…14E7\u001b[39m \u001b[1m999999999.999999\u001b[22m \u001b[38;5;79m💎👐\u001b[39m\n \u001b[90m0x872B…14E7\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0xdF65…C23e\u001b[39m \u001b[1m35227361.211893\u001b[22m \u001b[38;5;79m💎👐\u001b[39m\n \u001b[90m0x0000…0000\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0xCaf6…5cb2\u001b[39m \u001b[1m0.05\u001b[22m \u001b[38;5;79mWETH\u001b[39m\n \u001b[90m0xCaf6…5cb2\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0x872B…14E7\u001b[39m \u001b[1m0.05\u001b[22m \u001b[38;5;79mWETH\u001b[39m"+ "output": "\u001b[38;5;79m◈\u001b[39m \u001b[1mTransaction\u001b[22m \u001b[2m0x870a…85bd\u001b[22m \u001b[32m● success\u001b[39m\n\u001b[2mFrom\u001b[22m \u001b[90m0xdf65…c23e\u001b[39m\n\u001b[2mTo\u001b[22m \u001b[90m0xd9ec…fccb\u001b[39m\n\u001b[2mValue\u001b[22m \u001b[1m0.0505 ETH\u001b[22m\n\u001b[2mMethod\u001b[22m \u001b[2m—\u001b[22m\n\u001b[2mBlock\u001b[22m #5843692\n\u001b[2mWhen\u001b[22m \u001b[2m2026-07-10 05:54:38Z\u001b[22m\n\u001b[2mGas used\u001b[22m \u001b[2m6,845,934 @ 0.0485 gwei\u001b[22m\n\u001b[2mFee\u001b[22m 0.00033229 ETH\n\u001b[2mExplorer\u001b[22m \u001b[90mhttps://robinhoodchain.blockscout.com/tx/0x870a3bee3070f10e3c4f34271cfde70fd5aa0dc2eade6f07d01ae6c9a00285bd\u001b[39m\n\n\u001b[2mToken transfers\u001b[22m\n \u001b[90m0x0000…0000\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0xD9eC…FCcB\u001b[39m \u001b[1m1000000000\u001b[22m \u001b[38;5;79m💎👐\u001b[39m\n \u001b[90m0xD9eC…FCcB\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0x872B…14E7\u001b[39m \u001b[1m999999999.999999\u001b[22m \u001b[38;5;79m💎👐\u001b[39m\n \u001b[90m0x872B…14E7\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0xdF65…C23e\u001b[39m \u001b[1m35227361.211893\u001b[22m \u001b[38;5;79m💎👐\u001b[39m\n \u001b[90m0x0000…0000\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0xCaf6…5cb2\u001b[39m \u001b[1m0.05\u001b[22m \u001b[38;5;79mWETH\u001b[39m\n \u001b[90m0xCaf6…5cb2\u001b[39m \u001b[2m→\u001b[22m \u001b[90m0x872B…14E7\u001b[39m \u001b[1m0.05\u001b[22m \u001b[38;5;79mWETH\u001b[39m"}]}diff --git a/robinhood/hood-cli/package-lock.json b/robinhood/hood-cli/package-lock.jsonindex c0e3f521f..6d7501541 100644--- a/robinhood/hood-cli/package-lock.json+++ b/robinhood/hood-cli/package-lock.json@@ -7,7 +7,7 @@"": {"name": "hood-cli","version": "0.1.0",- "license": "Apache-2.0",+ "license": "SEE LICENSE IN LICENSE","dependencies": {"commander": "^12.1.0","hoodchain": "^0.1.1",diff --git a/robinhood/hood-cli/package.json b/robinhood/hood-cli/package.jsonindex 39cf60563..ac5ec0ab6 100644--- a/robinhood/hood-cli/package.json+++ b/robinhood/hood-cli/package.json@@ -1,6 +1,6 @@{"name": "hood-cli",- "version": "0.1.0",+ "version": "0.2.0","description": "The command-line toolkit for Robinhood Chain (chain 4663): instant reads with zero config, guarded writes with a wallet. Prices, portfolios, launches, swaps, transfers — the gh/vercel of Robinhood Chain.","keywords": ["robinhood",diff --git a/robinhood/hood-cli/src/commands/config.ts b/robinhood/hood-cli/src/commands/config.tsindex ebeffc539..35b78e1bc 100644--- a/robinhood/hood-cli/src/commands/config.ts+++ b/robinhood/hood-cli/src/commands/config.ts@@ -68,7 +68,7 @@ export function configCommand(): Command {return cmd}-async function setWallet(json: boolean, assumeYes: boolean): Promise<void> {+export async function setWallet(json: boolean, assumeYes: boolean): Promise<void> {const config = loadConfig()const keystorePath = config.walletKeystore ?? defaultKeystorePath()diff --git a/robinhood/hood-cli/src/commands/init.ts b/robinhood/hood-cli/src/commands/init.tsnew file mode 100644index 000000000..2605ecb15--- /dev/null+++ b/robinhood/hood-cli/src/commands/init.ts@@ -0,0 +1,197 @@+/**+ * `hood init` — the one-command onboarding wizard for the whole Robinhood+ * Chain trading stack: this CLI's wallet, hood-traders' bring-your-own-key+ * LLM strategist, and hood-alerts' Telegram bot + X (Twitter) auto-posting.+ *+ * hood-cli itself never runs a trading fleet or an alert bot — those are the+ * separate `hood-traders` and `hood-alerts` packages/processes. This wizard's+ * job is to collect the handful of choices and secrets those two packages+ * need and write them out as ready-to-use `.env` files, so getting the whole+ * stack running is "answer some questions, then `npx hood-traders` /+ * `npx hood-alerts`" instead of hand-editing two `.env.example` files.+ */+import { existsSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { Command } from 'commander'+import { loadConfig } from '../config.js'+import { setWallet } from './config.js'+import { canPrompt, confirm, promptLine, readPassword } from '../prompt.js'+import { printJson, printHuman, note } from '../output.js'+import { accent, bold, dim, green } from '../ui/ansi.js'+import { guardError } from '../errors.js'++const LLM_PROVIDERS = ['anthropic', 'openai', 'groq', 'openrouter'] as const+type LlmProvider = (typeof LLM_PROVIDERS)[number]++export interface InitAnswers {+ walletAddress?: string+ llmProvider?: LlmProvider+ llmApiKey?: string+ telegramToken?: string+ discordToken?: string+ discordAppId?: string+ xMode?: 'official' | 'xactions'+ xApiKey?: string+ xApiSecret?: string+ xAccessToken?: string+ xAccessSecret?: string+ xactionsUrl?: string+ xactionsToken?: string+}++/**+ * Render the `hood-traders` and `hood-alerts` `.env` file contents from+ * collected answers. Pure and side-effect-free so it's unit-testable without+ * a TTY — the wizard's IO (prompting, writing files) stays a thin shell+ * around this.+ */+export function buildEnvFiles(answers: InitAnswers): { traderEnv: string; alertsEnv: string } {+ const traderLines = [+ '# Generated by `hood init` — see hood-traders/.env.example for every option.',+ 'HOOD_NETWORK=mainnet',+ 'HOOD_TRADERS_LIVE=0 # flip to 1 (and set ROBINHOOD_CHAIN_PRIVATE_KEY) only when you are ready to trade real funds',+ ]+ if (answers.llmProvider && answers.llmApiKey) {+ traderLines.push('', '# llm-strategist', `HOOD_LLM_PROVIDER=${answers.llmProvider}`, `HOOD_LLM_API_KEY=${answers.llmApiKey}`)+ }++ const alertsLines = ['# Generated by `hood init` — see hood-alerts/.env.example for every option.']+ if (answers.telegramToken) {+ alertsLines.push('', '# Telegram', `HOOD_ALERTS_TELEGRAM_TOKEN=${answers.telegramToken}`)+ }+ if (answers.discordToken) {+ alertsLines.push('', '# Discord', `HOOD_ALERTS_DISCORD_TOKEN=${answers.discordToken}`, `HOOD_ALERTS_DISCORD_APP_ID=${answers.discordAppId ?? ''}`)+ }+ if (answers.xMode) {+ alertsLines.push('', '# X (Twitter)', `HOOD_ALERTS_X_MODE=${answers.xMode}`)+ if (answers.xMode === 'official') {+ alertsLines.push(+ `HOOD_ALERTS_X_API_KEY=${answers.xApiKey ?? ''}`,+ `HOOD_ALERTS_X_API_SECRET=${answers.xApiSecret ?? ''}`,+ `HOOD_ALERTS_X_ACCESS_TOKEN=${answers.xAccessToken ?? ''}`,+ `HOOD_ALERTS_X_ACCESS_SECRET=${answers.xAccessSecret ?? ''}`,+ )+ } else {+ alertsLines.push(`HOOD_ALERTS_XACTIONS_URL=${answers.xactionsUrl ?? ''}`, `HOOD_ALERTS_XACTIONS_TOKEN=${answers.xactionsToken ?? ''}`)+ }+ }++ return { traderEnv: traderLines.join('\n') + '\n', alertsEnv: alertsLines.join('\n') + '\n' }+}++export function initCommand(): Command {+ const cmd = new Command('init')+ .description('interactive setup wizard: wallet, LLM key (hood-traders), and Telegram/X (hood-alerts)')+ .option('--out <dir>', 'directory to write hood-traders.env / hood-alerts.env into', '.')+ .action(async (opts: { out: string }, _command, command) => {+ const json = !!command?.optsWithGlobals?.().json+ const assumeYes = !!command?.optsWithGlobals?.().yes+ await runInit(opts.out, json, assumeYes)+ })+ return cmd+}++async function runInit(outDir: string, json: boolean, assumeYes: boolean): Promise<void> {+ if (!canPrompt()) {+ throw guardError(+ 'hood init needs an interactive terminal.',+ 'Copy hood-traders/.env.example and hood-alerts/.env.example by hand instead, or re-run in a real TTY.',+ )+ }++ printHuman(`${accent('◈')} ${bold('hood init')} — set up the Robinhood Chain trading stack\n${dim('Every step below is optional; press Enter (or answer "n") to skip anything you don\'t need yet.')}\n`)++ const answers: InitAnswers = {}++ // ── 1. wallet ────────────────────────────────────────────────────────────+ const existing = loadConfig()+ if (existing.walletAddress) {+ note(`Wallet already configured: ${existing.walletAddress}`)+ answers.walletAddress = existing.walletAddress+ } else if (await confirm('Set up a local wallet now? (needed only for LIVE trading — skip to stay read-only/paper mode)')) {+ await setWallet(false, assumeYes)+ answers.walletAddress = loadConfig().walletAddress+ }++ // ── 2. llm-strategist (hood-traders) ────────────────────────────────────+ if (await confirm('Configure the llm-strategist for hood-traders? (bring your own key — Claude, OpenAI, Groq, or OpenRouter)')) {+ const providerAnswer = (+ await promptLine('Which provider — anthropic / openai / groq / openrouter?', undefined, 'anthropic')+ ).toLowerCase()+ if (!LLM_PROVIDERS.includes(providerAnswer as LlmProvider)) {+ throw guardError(`"${providerAnswer}" is not one of: ${LLM_PROVIDERS.join(', ')}.`)+ }+ answers.llmProvider = providerAnswer as LlmProvider+ answers.llmApiKey = await readPassword(`${answers.llmProvider} API key:`, 'HOOD_LLM_API_KEY')+ }++ // ── 3. hood-alerts: Telegram ─────────────────────────────────────────────+ if (await confirm('Set up the hood-alerts Telegram bot? (real-time launch/whale/premium feed)')) {+ note('Message @BotFather on Telegram, run /newbot, then paste the token below.')+ answers.telegramToken = await readPassword('Telegram bot token:', 'HOOD_ALERTS_TELEGRAM_TOKEN')+ }++ // ── 4. hood-alerts: Discord ──────────────────────────────────────────────+ if (await confirm('Set up the hood-alerts Discord bot too?')) {+ note('Create an app + bot at https://discord.com/developers/applications.')+ answers.discordToken = await readPassword('Discord bot token:', 'HOOD_ALERTS_DISCORD_TOKEN')+ answers.discordAppId = await promptLine('Discord application id:', 'HOOD_ALERTS_DISCORD_APP_ID')+ }++ // ── 5. hood-alerts: X (Twitter) ──────────────────────────────────────────+ if (await confirm('Set up X (Twitter) auto-posting for hood-alerts?')) {+ const mode = (await promptLine('Mode — "official" (X API v2, needs a paid developer tier) or "xactions" (free, self-hosted)?', undefined, 'official')).toLowerCase()+ if (mode !== 'official' && mode !== 'xactions') throw guardError('Mode must be "official" or "xactions".')+ answers.xMode = mode+ if (mode === 'official') {+ note('developer.x.com → your app → Keys and tokens. Needs read+write access token permissions.')+ answers.xApiKey = await readPassword('X API key (consumer key):', 'HOOD_ALERTS_X_API_KEY')+ answers.xApiSecret = await readPassword('X API secret (consumer secret):', 'HOOD_ALERTS_X_API_SECRET')+ answers.xAccessToken = await readPassword('X access token:', 'HOOD_ALERTS_X_ACCESS_TOKEN')+ answers.xAccessSecret = await readPassword('X access token secret:', 'HOOD_ALERTS_X_ACCESS_SECRET')+ } else {+ note('Point this at your own running xactions instance: https://github.com/nirholas/XActions')+ answers.xactionsUrl = await promptLine('xactions instance URL:', 'HOOD_ALERTS_XACTIONS_URL')+ answers.xactionsToken = await readPassword('xactions auth token:', 'HOOD_ALERTS_XACTIONS_TOKEN')+ }+ }++ // ── write ────────────────────────────────────────────────────────────────+ const { traderEnv, alertsEnv } = buildEnvFiles(answers)+ const traderPath = join(outDir, 'hood-traders.env')+ const alertsPath = join(outDir, 'hood-alerts.env')++ if (existsSync(traderPath) && !assumeYes && !(await confirm(`${traderPath} already exists. Overwrite it?`))) {+ throw guardError('hood init cancelled.')+ }+ if (existsSync(alertsPath) && !assumeYes && !(await confirm(`${alertsPath} already exists. Overwrite it?`))) {+ throw guardError('hood init cancelled.')+ }+ writeFileSync(traderPath, traderEnv, { mode: 0o600 })+ writeFileSync(alertsPath, alertsEnv, { mode: 0o600 })++ const summary = {+ ok: true,+ wallet: answers.walletAddress ?? null,+ llmProvider: answers.llmProvider ?? null,+ telegram: !!answers.telegramToken,+ discord: !!answers.discordToken,+ xMode: answers.xMode ?? null,+ traderEnv: traderPath,+ alertsEnv: alertsPath,+ }++ if (json) {+ printJson(summary)+ return+ }++ printHuman(+ `\n${green('✓')} Wrote ${bold(traderPath)} and ${bold(alertsPath)}\n\n` ++ `${dim('Next steps:')}\n` ++ ` ${dim('# run the trading fleet (paper mode by default — no funds move)')}\n` ++ ` cp ${traderPath} hood-traders/.env && cd hood-traders && npx hood-traders\n\n` ++ ` ${dim('# run the alert bot / real-time feed')}\n` ++ ` cp ${alertsPath} hood-alerts/.env && cd hood-alerts && npx hood-alerts\n`,+ )+}diff --git a/robinhood/hood-cli/src/program.ts b/robinhood/hood-cli/src/program.tsindex 49dc797c6..a8be16845 100644--- a/robinhood/hood-cli/src/program.ts+++ b/robinhood/hood-cli/src/program.ts@@ -20,6 +20,7 @@ import { transferCommand } from './commands/transfer.js'import { faucetCommand } from './commands/faucet.js'import { deployTokenCommand } from './commands/deploy-token.js'import { configCommand } from './commands/config.js'+import { initCommand } from './commands/init.js'function readVersion(): string {const here = dirname(fileURLToPath(import.meta.url))@@ -60,6 +61,7 @@ export function createProgram(): Command {program.addCommand(faucetCommand())program.addCommand(deployTokenCommand())program.addCommand(configCommand())+ program.addCommand(initCommand())return program}diff --git a/robinhood/hood-cli/src/prompt.ts b/robinhood/hood-cli/src/prompt.tsindex 1a069785e..ede3306d2 100644--- a/robinhood/hood-cli/src/prompt.ts+++ b/robinhood/hood-cli/src/prompt.ts@@ -32,6 +32,29 @@ export async function confirm(question: string): Promise<boolean> {}}+/**+ * Ask a free-text question, echoing the input (not a secret). Falls back to+ * the env var when provided. Returns `fallback` (default `''`) on an empty+ * answer.+ */+export async function promptLine(question: string, envVar?: string, fallback = ''): Promise<string> {+ const fromEnv = envVar ? process.env[envVar] : undefined+ if (fromEnv) return fromEnv+ if (!canPrompt()) {+ throw guardError('An interactive answer is required.', envVar ? `Set ${envVar} or run in an interactive terminal.` : 'Run in an interactive terminal.')+ }+ const rl = createInterface({ input: process.stdin, output: process.stderr })+ try {+ const answer = await new Promise<string>((resolve) => {+ rl.question(`${yellow('?')} ${bold(question)} `, resolve)+ })+ const trimmed = answer.trim()+ return trimmed.length > 0 ? trimmed : fallback+ } finally {+ rl.close()+ }+}+/*** Read a password without echoing it. Falls back to the env var when provided* so automation never has to type into a TTY.diff --git a/robinhood/hood-cli/tests/unit/init.test.ts b/robinhood/hood-cli/tests/unit/init.test.tsnew file mode 100644index 000000000..c9209d9c8--- /dev/null+++ b/robinhood/hood-cli/tests/unit/init.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest'+import { buildEnvFiles, initCommand } from '../../src/commands/init.js'++describe('init command wiring', () => {+ it('registers a --out option defaulting to the current directory', () => {+ const cmd = initCommand()+ const out = cmd.options.find((o) => o.long === '--out')+ expect(out).toBeDefined()+ expect(out!.defaultValue).toBe('.')+ })+})++describe('buildEnvFiles', () => {+ it('writes a minimal hood-traders.env with paper mode when nothing else is configured', () => {+ const { traderEnv } = buildEnvFiles({})+ expect(traderEnv).toMatch(/HOOD_TRADERS_LIVE=0/)+ expect(traderEnv).not.toMatch(/HOOD_LLM_PROVIDER/)+ })++ it('includes LLM provider + key only when both are set', () => {+ const { traderEnv } = buildEnvFiles({ llmProvider: 'anthropic', llmApiKey: 'sk-ant-test' })+ expect(traderEnv).toMatch(/HOOD_LLM_PROVIDER=anthropic/)+ expect(traderEnv).toMatch(/HOOD_LLM_API_KEY=sk-ant-test/)+ })++ it('writes an empty-ish hood-alerts.env when nothing is configured', () => {+ const { alertsEnv } = buildEnvFiles({})+ expect(alertsEnv).not.toMatch(/HOOD_ALERTS_TELEGRAM_TOKEN=/)+ expect(alertsEnv).not.toMatch(/HOOD_ALERTS_X_MODE=/)+ })++ it('includes Telegram token when set', () => {+ const { alertsEnv } = buildEnvFiles({ telegramToken: '123:abc' })+ expect(alertsEnv).toMatch(/HOOD_ALERTS_TELEGRAM_TOKEN=123:abc/)+ })++ it('includes official X credentials under official mode', () => {+ const { alertsEnv } = buildEnvFiles({+ xMode: 'official',+ xApiKey: 'k',+ xApiSecret: 's',+ xAccessToken: 't',+ xAccessSecret: 'ts',+ })+ expect(alertsEnv).toMatch(/HOOD_ALERTS_X_MODE=official/)+ expect(alertsEnv).toMatch(/HOOD_ALERTS_X_API_KEY=k/)+ expect(alertsEnv).toMatch(/HOOD_ALERTS_X_ACCESS_SECRET=ts/)+ expect(alertsEnv).not.toMatch(/XACTIONS_URL/)+ })++ it('includes xactions credentials under xactions mode, not official X keys', () => {+ const { alertsEnv } = buildEnvFiles({ xMode: 'xactions', xactionsUrl: 'https://example.com', xactionsToken: 'tok' })+ expect(alertsEnv).toMatch(/HOOD_ALERTS_X_MODE=xactions/)+ expect(alertsEnv).toMatch(/HOOD_ALERTS_XACTIONS_URL=https:\/\/example\.com/)+ expect(alertsEnv).not.toMatch(/HOOD_ALERTS_X_API_KEY/)+ })+})diff --git a/robinhood/hood-cli/tests/unit/program.test.ts b/robinhood/hood-cli/tests/unit/program.test.tsindex 1c1111f6d..09ef79fc8 100644--- a/robinhood/hood-cli/tests/unit/program.test.ts+++ b/robinhood/hood-cli/tests/unit/program.test.ts@@ -34,6 +34,7 @@ describe('global flags — eligibility + confirmation gates', () => {'config','deploy-token','faucet',+ 'init','launches','portfolio','price',diff --git a/robinhood/hood-traders/.env.example b/robinhood/hood-traders/.env.exampleindex 38a0d4e37..d4cabfeea 100644--- a/robinhood/hood-traders/.env.example+++ b/robinhood/hood-traders/.env.example@@ -38,3 +38,19 @@ AGENT_MAX_POSITION_USDG=50AGENT_MAX_DAILY_SPEND_USDG=100AGENT_MAX_SLIPPAGE_BPS=100AGENT_COOLDOWN_SECONDS=60++# ── llm-strategist (OPTIONAL — the strategy is simply not added to the fleet+# unless BOTH vars below are set). Bring your own key: pick exactly ONE+# provider. Every LLM verdict still passes through the same risk engine as+# every other strategy — an LLM proposes, it never executes directly.+# provider: anthropic | openai | groq | openrouter+HOOD_LLM_PROVIDER=+HOOD_LLM_API_KEY=+# Optional. Falls back to a sane per-provider default when unset (see+# src/framework/llm.ts DEFAULT_MODELS) — set this if that default ever goes+# stale for your provider, or to pick a stronger/cheaper model.+HOOD_LLM_MODEL=+# Minimum LLM-stated confidence (0-1) required to actually place the trade.+HOOD_LLM_MIN_CONFIDENCE=0.6+# Per-call timeout before the judge is treated as failed (skips the candidate).+HOOD_LLM_TIMEOUT_MS=9000diff --git a/robinhood/hood-traders/README.md b/robinhood/hood-traders/README.mdindex 596d9946f..3b859af5c 100644--- a/robinhood/hood-traders/README.md+++ b/robinhood/hood-traders/README.md@@ -26,8 +26,11 @@ drop-in change confined to `src/framework/market.ts`.- **Framework** (`src/framework/`): agent = strategy + wallet + risk budget + journal. Every tickruns observe → decide → simulate (a real Uniswap v3 `eth_call`) → risk-check (fail-closed) →execute → journal.-- **Three strategies** (`src/strategies/`): `launch-sniper`, `momentum`, `premium-watch` — each- with an honestly documented edge hypothesis and failure modes (see [Strategies](#strategies)).+- **Four strategies** (`src/strategies/`): `launch-sniper`, `momentum`, `premium-watch`, and+ `llm-strategist` — each with an honestly documented edge hypothesis and failure modes (see+ [Strategies](#strategies)). `llm-strategist` is optional and bring-your-own-key: point it at+ Claude, OpenAI, Groq, or OpenRouter and it judges launches the other strategies discover, using+ the same real on-chain signals, subject to the exact same risk engine as everything else.- **Live dashboard** (`dashboard/`): fleet overview, per-agent equity curve, open positions, thefull decision journal (why each trade fired — or didn't), and a kill button.- **Risk layer** (`src/framework/risk.ts`): per-agent position cap, daily spend cap, fleet-wide@@ -92,7 +95,7 @@ these tokenized debt securities (issuer: Robinhood Assets (Jersey) Ltd). Without## ArchitectureSee [`docs/architecture.html`](docs/architecture.html) for the full observe → decide → simulate →-risk-check → execute → journal diagram, and how the three strategies plug into it. Short version:+risk-check → execute → journal diagram, and how the four strategies plug into it. Short version:```Market (hoodchain SDK, live RPC)@@ -122,10 +125,31 @@ Full docs with live examples: [`docs/strategies.html`](docs/strategies.html). Su| `launch-sniper` | Opening-minutes volatility on new launches is real; discipline (round-trip + deployer-concentration filters, mechanical exits) harvests a slice of it. | Most new launches go to zero — the stop loss fires often; this is negative-carry unless winners cover losers. || `momentum` | Tokens that survive to graduation and then break out on price reflect real demand, not launch-day noise. | Breakouts on thin pools are trivially fakeable by one wallet; price-only signal has no depth check. || `premium-watch` | Stock Token pools are thin and drift from the Chainlink oracle; buying the discount captures reversion. **Alerts-only by default** — trading requires explicit eligibility + opt-in. | A premium/discount can be *correct* (DEX reacting to news the ≤24h Chainlink heartbeat hasn't caught yet); fading it loses on purpose. No shorting primitive exists. |+| `llm-strategist` | An LLM (bring your own key) weighs the same round-trip-retention and deployer-concentration signals `launch-sniper` checks mechanically, holistically instead of against fixed cutoffs, and only trades above a confidence threshold. **Disabled unless configured** — see below. | LLM confidence is not calibrated probability; a confidently wrong verdict trades identically to a confidently right one. On-chain data reaching the prompt is attacker-controlled, so the brief is numbers-only by design. One provider, no fallback. |Every strategy exposes its `meta.edge` / `meta.failureModes` at runtime (`strategy.meta`) — thedashboard and docs pull the live values, not a stale copy.+### `llm-strategist` setup++Disabled by default — the fleet runs the other three strategies with zero LLM config. To enable it,+set exactly one provider in `.env`:++```sh+# any ONE of:+HOOD_LLM_PROVIDER=anthropic HOOD_LLM_API_KEY=sk-ant-...+HOOD_LLM_PROVIDER=openai HOOD_LLM_API_KEY=sk-...+HOOD_LLM_PROVIDER=groq HOOD_LLM_API_KEY=gsk_...+HOOD_LLM_PROVIDER=openrouter HOOD_LLM_API_KEY=sk-or-...+```++`HOOD_LLM_MODEL` is optional — each provider has a sane default (see+[`src/framework/llm.ts`](src/framework/llm.ts)); set it if a default ever goes stale or you want a+stronger/cheaper model. `HOOD_LLM_MIN_CONFIDENCE` (default `0.6`) is the minimum LLM-stated+confidence required to actually place a trade — everything below that is logged to the decision+journal as an alert, not a trade. Every LLM API call costs money regardless of verdict; a launch+storm inflates spend with nothing to show for it if you set the confidence bar too low.+## ConfigurationAll of `.env.example` is optional for paper mode. Key knobs:@@ -143,6 +167,11 @@ All of `.env.example` is optional for paper mode. Key knobs:| `AGENT_COOLDOWN_SECONDS` | `60` | Minimum gap between an agent's trades || `KILL_FILE` | `./KILL` | Drop a file here to halt the fleet immediately || `DASHBOARD_PORT` | `4670` | Dashboard + API port |+| `HOOD_LLM_PROVIDER` | *(unset)* | `anthropic`\|`openai`\|`groq`\|`openrouter` — enables `llm-strategist` when set with `HOOD_LLM_API_KEY` |+| `HOOD_LLM_API_KEY` | *(unset)* | Your own key for the chosen provider |+| `HOOD_LLM_MODEL` | *(per-provider default)* | Override the model id |+| `HOOD_LLM_MIN_CONFIDENCE` | `0.6` | Minimum LLM confidence to trade, else it's alert-only |+| `HOOD_LLM_TIMEOUT_MS` | `9000` | Per-call timeout before the judge is treated as failed |## Kill switchdiff --git a/robinhood/hood-traders/docs/index.html b/robinhood/hood-traders/docs/index.htmlindex 8296fd062..29bb68c9f 100644--- a/robinhood/hood-traders/docs/index.html+++ b/robinhood/hood-traders/docs/index.html@@ -4,7 +4,7 @@<meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>hood-traders — autonomous trading agents for Robinhood Chain</title>- <meta name="description" content="A framework and runnable fleet of autonomous agents that trade Robinhood Chain memecoins and watch Stock Token premium/discount. Real risk caps, real signed swaps, live decision journal." />+ <meta name="description" content="A framework and runnable fleet of autonomous agents that trade Robinhood Chain memecoins and watch Stock Token premium/discount — including an optional bring-your-own-key LLM strategist (Claude, OpenAI, Groq, or OpenRouter). Real risk caps, real signed swaps, live decision journal." /><link rel="icon" href="data:image/svg+xml,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%2032%2032%27%3E%3Cdefs%3E%3ClinearGradient%20id%3D%27g%27%20x1%3D%270%27%20y1%3D%270%27%20x2%3D%271%27%20y2%3D%271%27%3E%3Cstop%20offset%3D%270%27%20stop-color%3D%27%236d5ef8%27%2F%3E%3Cstop%20offset%3D%271%27%20stop-color%3D%27%232fd0e0%27%2F%3E%3C%2FlinearGradient%3E%3C%2Fdefs%3E%3Ccircle%20cx%3D%2716%27%20cy%3D%2716%27%20r%3D%2713%27%20fill%3D%27url(%23g)%27%2F%3E%3C%2Fsvg%3E" /><link rel="stylesheet" href="style.css" /></head>@@ -32,7 +32,8 @@A framework + runnable fleet: strategy + wallet + risk budget + journal. Every tick observeslive market data, simulates the fill with a real Uniswap v3 <code>eth_call</code>, checksevery risk cap before anything executes, and journals the decision — trade or refusal —- into SQLite. Three honest strategies ship out of the box.+ into SQLite. Four honest strategies ship out of the box, including an optional+ bring-your-own-key LLM strategist.</p><div class="cta-row"><a class="btn primary" href="quickstart.html">Run your own fleet →</a>@@ -66,7 +67,7 @@</section><section>- <h2>Three strategies, honestly documented</h2>+ <h2>Four strategies, honestly documented</h2><div class="card-grid"><div class="card"><h3>launch-sniper</h3>@@ -92,6 +93,14 @@<li>No shorting primitive — only discounts are ever tradeable</li></ul></div>+ <div class="card">+ <h3>llm-strategist <span class="badge" style="margin-left:.4em">optional</span></h3>+ <p class="edge">Bring your own key (Claude, OpenAI, Groq, or OpenRouter) — an LLM weighs the same on-chain signals launch-sniper checks mechanically, holistically instead of against fixed cutoffs.</p>+ <ul>+ <li>Disabled unless <code>HOOD_LLM_PROVIDER</code> + <code>HOOD_LLM_API_KEY</code> are set</li>+ <li>Stated confidence is not calibrated probability — trades exactly like a rule when it clears the bar</li>+ </ul>+ </div></div><p><a href="strategies.html">Full strategy docs with live examples →</a></p></section>diff --git a/robinhood/hood-traders/docs/strategies.html b/robinhood/hood-traders/docs/strategies.htmlindex af3b0df27..cdee0d44c 100644--- a/robinhood/hood-traders/docs/strategies.html+++ b/robinhood/hood-traders/docs/strategies.html@@ -4,7 +4,7 @@<meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Strategies — hood-traders</title>- <meta name="description" content="Honest edge hypotheses and failure modes for launch-sniper, momentum, and premium-watch." />+ <meta name="description" content="Honest edge hypotheses and failure modes for launch-sniper, momentum, premium-watch, and the bring-your-own-key llm-strategist." /><link rel="icon" href="data:image/svg+xml,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%2032%2032%27%3E%3Cdefs%3E%3ClinearGradient%20id%3D%27g%27%20x1%3D%270%27%20y1%3D%270%27%20x2%3D%271%27%20y2%3D%271%27%3E%3Cstop%20offset%3D%270%27%20stop-color%3D%27%236d5ef8%27%2F%3E%3Cstop%20offset%3D%271%27%20stop-color%3D%27%232fd0e0%27%2F%3E%3C%2FlinearGradient%3E%3C%2Fdefs%3E%3Ccircle%20cx%3D%2716%27%20cy%3D%2716%27%20r%3D%2713%27%20fill%3D%27url(%23g)%27%2F%3E%3C%2Fsvg%3E" /><link rel="stylesheet" href="style.css" /></head>@@ -23,9 +23,10 @@<div class="wrap"><h1>Strategies</h1><p class="lede">- Three simple, honestly documented strategies. No ML theater — every entry/exit rule is- readable in one file, and every strategy's <code>meta.edge</code> / <code>meta.failureModes</code>- is a live object on the class, not a comment that can drift from the code.+ Four honestly documented strategies. No ML theater — every entry/exit rule is readable in one+ file, and every strategy's <code>meta.edge</code> / <code>meta.failureModes</code> is a live+ object on the class, not a comment that can drift from the code. Three are pure rule-based+ code; the fourth, <code>llm-strategist</code>, is opt-in and bring-your-own-key.</p><h2>launch-sniper</h2>@@ -114,6 +115,46 @@<li>Chainlink staleness (weekend gap, feed outage) can masquerade as a discount when the oracle, not the pool, is stale.</li></ul>+ <h2>llm-strategist <span class="badge">optional, bring your own key</span></h2>+ <p><code>src/strategies/llm-strategist.ts</code> · quote token: WETH · disabled unless configured</p>+ <p><strong>Edge hypothesis:</strong> <code>launch-sniper</code>'s filters are fixed cutoffs applied+ independently — a launch either clears every threshold or it doesn't. An LLM can weigh the same+ real on-chain signals (round-trip retention, deployer concentration) holistically instead, and+ may make better marginal calls on launches that are close to the line. It sees nothing+ <code>launch-sniper</code> can't — same inputs, a different judgment function.</p>++ <div class="callout warn">+ <strong>Bring your own key.</strong> Set <code>HOOD_LLM_PROVIDER</code> (<code>anthropic</code> |+ <code>openai</code> | <code>groq</code> | <code>openrouter</code>) and <code>HOOD_LLM_API_KEY</code>+ to enable it — unset, the fleet simply runs the other three strategies. Every verdict still+ passes through the exact same risk engine as every other strategy; an LLM proposes an intent,+ it never executes one directly.+ </div>++ <h3>Signal</h3>+ <p>For each new launch, the strategy computes the same buy→sell round-trip retention and+ deployer-supply-concentration numbers <code>launch-sniper</code> uses, sends them (numbers+ only — no free-text on-chain fields, to limit prompt-injection surface) to the configured LLM+ with a strict JSON-only verdict contract, and parses the response with a tolerant extractor+ that throws on anything malformed.</p>+ <h3>Entry</h3>+ <p>Trades only when the verdict is <code>{"buy": true}</code> <strong>and</strong>+ <code>confidence >= HOOD_LLM_MIN_CONFIDENCE</code> (default 0.6). Everything else — a+ <code>buy:false</code> verdict, low confidence, a malformed response, or a provider timeout —+ is logged to the decision journal as an alert, never a trade.</p>+ <h3>Exits</h3>+ <ul>+ <li>Take-profit / stop-loss / time-exit — identical bands to <code>launch-sniper</code></li>+ </ul>+ <h3>Failure modes</h3>+ <ul>+ <li>LLM confidence is not calibrated probability — a confidently wrong verdict trades exactly like a confidently right one.</li>+ <li>On-chain data reaching the prompt is attacker-controlled; only numeric signals are included today specifically to limit prompt-injection surface.</li>+ <li>LLM round-trip latency means this strategy reacts to a launch after <code>launch-sniper</code> already has (or hasn't).</li>+ <li>Every judged launch costs a real LLM API call regardless of verdict — a launch storm inflates spend with nothing to show for it.</li>+ <li>One configured provider, no fallback chain — a provider outage means zero coverage until it recovers.</li>+ </ul>+<footer class="footer"><span>hood-traders · Robinhood Chain autonomous trading fleet</span><span>Built by <a href="https://x.com/nichxbt" target="_blank" rel="noopener">nirholas</a> · <a href="https://three.ws" target="_blank" rel="noopener">three.ws</a></span>diff --git a/robinhood/hood-traders/package-lock.json b/robinhood/hood-traders/package-lock.jsonindex ab26ce0fe..51fdc750b 100644--- a/robinhood/hood-traders/package-lock.json+++ b/robinhood/hood-traders/package-lock.json@@ -7,7 +7,7 @@"": {"name": "hood-traders","version": "0.1.0",- "license": "Apache-2.0",+ "license": "SEE LICENSE IN LICENSE","dependencies": {"better-sqlite3": "^11.8.0","hoodchain": "^0.1.1",diff --git a/robinhood/hood-traders/package.json b/robinhood/hood-traders/package.jsonindex ec16e541f..b56de39d7 100644--- a/robinhood/hood-traders/package.json+++ b/robinhood/hood-traders/package.json@@ -1,6 +1,6 @@{"name": "hood-traders",- "version": "0.1.0",+ "version": "0.2.0","description": "A framework and runnable fleet of autonomous agents that trade Robinhood Chain (4663) memecoins and watch Stock Token premium/discount — real quotes, real risk caps, real signed swaps, live P&L dashboard.","keywords": ["robinhood-chain",diff --git a/robinhood/hood-traders/src/framework/config.ts b/robinhood/hood-traders/src/framework/config.tsindex 7c1adcfbe..8b29b0ba4 100644--- a/robinhood/hood-traders/src/framework/config.ts+++ b/robinhood/hood-traders/src/framework/config.ts@@ -1,5 +1,6 @@import type { HoodNetwork } from 'hoodchain'import type { Mode, RiskLimits } from './types.js'+import type { LlmClientConfig, LlmProvider } from './llm.js'/** Fleet-wide configuration resolved from the environment. */export interface FleetConfig {@@ -68,3 +69,38 @@ export function loadFleetConfig(env: NodeJS.ProcessEnv = process.env): FleetConf},}}++const LLM_PROVIDERS: readonly LlmProvider[] = ['anthropic', 'openai', 'groq', 'openrouter']++/**+ * Resolve LLM config for {@link LlmStrategist} from the environment. Returns+ * `null` when `HOOD_LLM_PROVIDER` or `HOOD_LLM_API_KEY` is unset — the+ * strategy is optional and simply isn't added to the fleet in that case (see+ * main.ts). Throws only when `HOOD_LLM_PROVIDER` is set to an unrecognized+ * value, since that is very likely a typo the operator would want to know+ * about immediately rather than silently running without the strategy.+ */+export function loadLlmConfig(env: NodeJS.ProcessEnv = process.env): LlmClientConfig | null {+ const provider = env.HOOD_LLM_PROVIDER+ const apiKey = env.HOOD_LLM_API_KEY+ if (!provider && !apiKey) return null+ if (!provider || !apiKey) {+ throw new Error(+ 'hood-traders config.ts: HOOD_LLM_PROVIDER and HOOD_LLM_API_KEY must both be set to enable llm-strategist (or both left unset to disable it).',+ )+ }+ if (!LLM_PROVIDERS.includes(provider as LlmProvider)) {+ throw new Error(`hood-traders config.ts: HOOD_LLM_PROVIDER="${provider}" is not one of ${LLM_PROVIDERS.join(', ')}`)+ }+ return {+ provider: provider as LlmProvider,+ apiKey,+ model: env.HOOD_LLM_MODEL || undefined,+ timeoutMs: num('HOOD_LLM_TIMEOUT_MS', 9000),+ }+}++/** Minimum LLM confidence required to convert a `buy` verdict into a trade. */+export function loadLlmMinConfidence(env: NodeJS.ProcessEnv = process.env): number {+ return num('HOOD_LLM_MIN_CONFIDENCE', 0.6)+}diff --git a/robinhood/hood-traders/src/framework/llm.ts b/robinhood/hood-traders/src/framework/llm.tsnew file mode 100644index 000000000..2b1721d5e--- /dev/null+++ b/robinhood/hood-traders/src/framework/llm.ts@@ -0,0 +1,197 @@+/**+ * Multi-provider LLM client for {@link LlmStrategist}. Bring your own key: the+ * operator picks exactly one of Anthropic Claude, OpenAI, Groq, or OpenRouter+ * via env config (see {@link loadLlmConfig} in ./config.js) and this module+ * speaks that provider's HTTP API directly with `fetch` — no SDK dependency,+ * matching the rest of this package (better-sqlite3, hoodchain, viem, ws are+ * the only runtime deps).+ *+ * The verdict contract is strict on purpose: a strategy that trades real money+ * must never trust free-text from an LLM. Every provider is prompted to return+ * ONLY a JSON object; the response is parsed with a tolerant extractor (finds+ * the first `{...}` blob, so a model that wraps the JSON in a sentence still+ * works) and validated field-by-field. A malformed or missing verdict throws —+ * the caller (LlmStrategist.tick) treats that as "skip this candidate, alert",+ * never as an implicit buy or an implicit skip-silently.+ */++export type LlmProvider = 'anthropic' | 'openai' | 'groq' | 'openrouter'++export interface LlmClientConfig {+ provider: LlmProvider+ apiKey: string+ /** Falls back to a sane per-provider default (see {@link DEFAULT_MODELS}) when unset. */+ model?: string+ /** Abort the request after this many ms. Default 9000. */+ timeoutMs?: number+}++export interface LlmVerdict {+ buy: boolean+ /** Clamped to [0, 1]. */+ confidence: number+ thesis: string+}++/**+ * Default model per provider. Anthropic and OpenRouter defaults are stable+ * (a dated snapshot and an auto-router, respectively). OpenAI/Groq model+ * catalogs move faster — `HOOD_LLM_MODEL` overrides any of these; if a default+ * ever goes stale the provider call fails with a clear "check HOOD_LLM_MODEL"+ * error (see {@link callProvider}) rather than a silent misroute.+ */+const DEFAULT_MODELS: Record<LlmProvider, string> = {+ anthropic: 'claude-haiku-4-5-20251001',+ openai: 'gpt-4o-mini',+ groq: 'llama-3.3-70b-versatile',+ openrouter: 'openrouter/auto',+}++const SYSTEM_PROMPT = [+ 'You are a risk-averse trading analyst judging a brand-new token launch on Robinhood Chain,',+ 'a 24/7 permissionless DEX environment where most launches are worthless or scams.',+ 'You will be given real on-chain facts about one launch: its launchpad, whether a buy-then-sell',+ 'round trip retains value (a honeypot signal), and what fraction of supply the deployer wallet',+ 'still holds (a rug-risk signal). You have no access to socials, team identity, or any off-chain',+ 'information — judge only from what is given.',+ '',+ 'Reply with ONLY a single JSON object, no prose before or after it, matching exactly:',+ '{"buy": boolean, "confidence": number between 0 and 1, "thesis": "one sentence"}',+ '',+ '"buy" should be true only when the facts given suggest this is unusually clean for a brand-new',+ 'launch (high retention, low deployer concentration) — most launches should get buy:false.',+ '"confidence" reflects how sure you are in that judgment given how thin the available signal is.',+].join('\n')++/** Ask the configured LLM to judge a launch brief. Throws on any failure (timeout, HTTP error, malformed verdict). */+export async function judgeLaunch(cfg: LlmClientConfig, brief: string): Promise<LlmVerdict> {+ const model = cfg.model || DEFAULT_MODELS[cfg.provider]+ const timeoutMs = cfg.timeoutMs ?? 9000+ const controller = new AbortController()+ const timer = setTimeout(() => controller.abort(), timeoutMs)+ try {+ const text = await callProvider(cfg.provider, cfg.apiKey, model, brief, controller.signal)+ return parseVerdict(text)+ } catch (err) {+ if (err instanceof Error && err.name === 'AbortError') {+ throw new Error(`hood-traders llm.ts: ${cfg.provider} request timed out after ${timeoutMs}ms`)+ }+ throw err+ } finally {+ clearTimeout(timer)+ }+}++async function callProvider(+ provider: LlmProvider,+ apiKey: string,+ model: string,+ brief: string,+ signal: AbortSignal,+): Promise<string> {+ if (provider === 'anthropic') {+ const res = await fetch('https://api.anthropic.com/v1/messages', {+ method: 'POST',+ signal,+ headers: {+ 'content-type': 'application/json',+ 'x-api-key': apiKey,+ 'anthropic-version': '2023-06-01',+ },+ body: JSON.stringify({+ model,+ max_tokens: 300,+ system: SYSTEM_PROMPT,+ messages: [{ role: 'user', content: brief }],+ }),+ })+ const body = await res.text()+ if (!res.ok) throw providerError('anthropic', model, res.status, body)+ const data = JSON.parse(body) as { content?: { text?: string }[] }+ const text = data.content?.[0]?.text+ if (!text) throw new Error(`hood-traders llm.ts: anthropic response had no content text: ${body.slice(0, 300)}`)+ return text+ }++ // openai, groq, and openrouter all speak the OpenAI chat-completions shape.+ const { url, extraHeaders } = openAiCompatibleEndpoint(provider)+ const res = await fetch(url, {+ method: 'POST',+ signal,+ headers: {+ 'content-type': 'application/json',+ authorization: `Bearer ${apiKey}`,+ ...extraHeaders,+ },+ body: JSON.stringify({+ model,+ max_tokens: 300,+ messages: [+ { role: 'system', content: SYSTEM_PROMPT },+ { role: 'user', content: brief },+ ],+ }),+ })+ const body = await res.text()+ if (!res.ok) throw providerError(provider, model, res.status, body)+ const data = JSON.parse(body) as { choices?: { message?: { content?: string } }[] }+ const text = data.choices?.[0]?.message?.content+ if (!text) throw new Error(`hood-traders llm.ts: ${provider} response had no message content: ${body.slice(0, 300)}`)+ return text+}++function openAiCompatibleEndpoint(provider: 'openai' | 'groq' | 'openrouter'): {+ url: string+ extraHeaders: Record<string, string>+} {+ switch (provider) {+ case 'openai':+ return { url: 'https://api.openai.com/v1/chat/completions', extraHeaders: {} }+ case 'groq':+ return { url: 'https://api.groq.com/openai/v1/chat/completions', extraHeaders: {} }+ case 'openrouter':+ return {+ url: 'https://openrouter.ai/api/v1/chat/completions',+ extraHeaders: {+ 'HTTP-Referer': 'https://github.com/nirholas/hood-traders',+ 'X-Title': 'hood-traders',+ },+ }+ }+}++function providerError(provider: LlmProvider, model: string, status: number, body: string): Error {+ return new Error(+ `hood-traders llm.ts: ${provider} rejected request (HTTP ${status}, model="${model}"). ` ++ `If this is a model-not-found error, set HOOD_LLM_MODEL to a current model id for this provider. ` ++ `Response: ${body.slice(0, 300)}`,+ )+}++/** Extract the first `{...}` blob from `text` and validate it as an {@link LlmVerdict}. Throws on any mismatch. */+export function parseVerdict(text: string): LlmVerdict {+ const match = text.match(/\{[\s\S]*\}/)+ if (!match) throw new Error(`hood-traders llm.ts: no JSON object found in LLM response: ${text.slice(0, 300)}`)+ let raw: unknown+ try {+ raw = JSON.parse(match[0])+ } catch (err) {+ throw new Error(`hood-traders llm.ts: LLM response JSON did not parse: ${(err as Error).message}`)+ }+ if (typeof raw !== 'object' || raw === null) {+ throw new Error('hood-traders llm.ts: LLM verdict was not a JSON object')+ }+ const v = raw as Record<string, unknown>+ if (typeof v.buy !== 'boolean') {+ throw new Error(`hood-traders llm.ts: LLM verdict missing boolean "buy": ${JSON.stringify(v)}`)+ }+ if (typeof v.thesis !== 'string' || v.thesis.trim().length === 0) {+ throw new Error(`hood-traders llm.ts: LLM verdict missing non-empty "thesis": ${JSON.stringify(v)}`)+ }+ const confidenceRaw = typeof v.confidence === 'number' ? v.confidence : Number(v.confidence)+ if (!Number.isFinite(confidenceRaw)) {+ throw new Error(`hood-traders llm.ts: LLM verdict has non-numeric "confidence": ${JSON.stringify(v)}`)+ }+ const confidence = Math.min(1, Math.max(0, confidenceRaw))+ return { buy: v.buy, confidence, thesis: v.thesis.trim() }+}diff --git a/robinhood/hood-traders/src/index.ts b/robinhood/hood-traders/src/index.tsindex 879b942c4..5a3f3f9fc 100644--- a/robinhood/hood-traders/src/index.ts+++ b/robinhood/hood-traders/src/index.ts@@ -3,7 +3,7 @@ export { Agent } from './framework/agent.js'export type { AgentOptions } from './framework/agent.js'export { Fleet } from './framework/fleet.js'export type { AgentSpec, FleetSummary } from './framework/fleet.js'-export { loadFleetConfig } from './framework/config.js'+export { loadFleetConfig, loadLlmConfig, loadLlmMinConfidence } from './framework/config.js'export type { FleetConfig } from './framework/config.js'export { Journal } from './framework/journal.js'export { KillSwitch } from './framework/kill.js'@@ -39,6 +39,12 @@ export { Momentum } from './strategies/momentum.js'export type { MomentumParams } from './strategies/momentum.js'export { PremiumWatch } from './strategies/premium-watch.js'export type { PremiumWatchParams } from './strategies/premium-watch.js'+export { LlmStrategist } from './strategies/llm-strategist.js'+export type { LlmStrategistParams } from './strategies/llm-strategist.js'++// LLM client (bring your own key — Claude, OpenAI, Groq, or OpenRouter)+export { judgeLaunch, parseVerdict } from './framework/llm.js'+export type { LlmProvider, LlmClientConfig, LlmVerdict } from './framework/llm.js'// Dashboard serverexport { createDashboardServer } from './server/dashboard.js'diff --git a/robinhood/hood-traders/src/main.ts b/robinhood/hood-traders/src/main.tsindex 94e9c0a29..9a07a95ef 100644--- a/robinhood/hood-traders/src/main.ts+++ b/robinhood/hood-traders/src/main.ts@@ -1,10 +1,11 @@import { join } from 'node:path'import { fileURLToPath } from 'node:url'-import { loadFleetConfig } from './framework/config.js'+import { loadFleetConfig, loadLlmConfig, loadLlmMinConfidence } from './framework/config.js'import { Fleet } from './framework/fleet.js'import { LaunchSniper } from './strategies/launch-sniper.js'import { Momentum } from './strategies/momentum.js'import { PremiumWatch } from './strategies/premium-watch.js'+import { LlmStrategist } from './strategies/llm-strategist.js'import { createDashboardServer } from './server/dashboard.js'// main.ts sits at a stable one-level depth in both trees: src/main.ts (tsx,@@ -16,19 +17,34 @@ async function main(): Promise<void> {const config = loadFleetConfig()const fleet = new Fleet(config)+ const agentIds = ['sniper-1', 'momentum-1', 'premium-1']fleet.addAgents([{ id: 'sniper-1', strategy: new LaunchSniper(), tickIntervalMs: 4000 },{ id: 'momentum-1', strategy: new Momentum(), tickIntervalMs: 15000 },{ id: 'premium-1', strategy: new PremiumWatch(), tickIntervalMs: 30000 },])+ const llm = loadLlmConfig()+ if (llm) {+ fleet.addAgents([+ {+ id: 'llm-1',+ strategy: new LlmStrategist({ llm, minConfidence: loadLlmMinConfidence() }),+ tickIntervalMs: 20000,+ },+ ])+ agentIds.push('llm-1')+ } else {+ console.warn('HOOD_LLM_PROVIDER/HOOD_LLM_API_KEY not set: llm-strategist disabled (the other 3 strategies still run).')+ }+const banner = ['─'.repeat(60),' hood-traders — Robinhood Chain autonomous fleet','─'.repeat(60),` network : ${config.network} (${config.network === 'testnet' ? 46630 : 4663})`,` mode : ${config.mode.toUpperCase()}${config.mode === 'paper' ? ' (simulation only, no real funds move)' : ' (REAL FUNDS — swaps will be signed and broadcast)'}`,- ` agents : sniper-1, momentum-1, premium-1`,+ ` agents : ${agentIds.join(', ')}`,` fleet cap : $${config.fleetMaxDailySpendUsdg}/day`,` dashboard : http://localhost:${config.dashboardPort}`,` kill file : ${config.killFile}`,diff --git a/robinhood/hood-traders/src/strategies/llm-strategist.ts b/robinhood/hood-traders/src/strategies/llm-strategist.tsnew file mode 100644index 000000000..96dbf8bb4--- /dev/null+++ b/robinhood/hood-traders/src/strategies/llm-strategist.ts@@ -0,0 +1,245 @@+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'+import { judgeLaunch, type LlmClientConfig, type LlmVerdict } from '../framework/llm.js'++/** Tunables for {@link LlmStrategist}. */+export interface LlmStrategistParams {+ llm: LlmClientConfig+ /** WETH spent per entry when the LLM says buy. */+ 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+ /** Minimum LLM confidence required to convert a `buy` verdict into an Intent. */+ minConfidence: number+ /** Only consider launches at most this many seconds old when first seen. */+ maxLaunchAgeSeconds: number+}++const DEFAULTS: Omit<LlmStrategistParams, 'llm'> = {+ entryWeth: 0.01,+ takeProfitPct: 0.6,+ stopLossPct: 0.35,+ maxHoldSeconds: 30 * 60,+ minConfidence: 0.6,+ maxLaunchAgeSeconds: 5 * 60,+}++interface Candidate {+ launch: Launch+ seenAt: number+}++/**+ * llm-strategist — an LLM (bring your own key: Claude, OpenAI, Groq, or+ * OpenRouter) judges each new launch from the same real on-chain signals+ * launch-sniper uses mechanically (round-trip retention, deployer+ * concentration), instead of applying fixed threshold cutoffs.+ *+ * EDGE HYPOTHESIS: launch-sniper's hard cutoffs treat every signal+ * independently — a launch either clears every threshold or it doesn't. A+ * model can weigh weak, correlated signals holistically (e.g. "retention is+ * only okay but deployer concentration is very low" vs "retention is great+ * but deployer concentration is borderline") and may make better marginal+ * calls than a fixed rule. It cannot see anything launch-sniper can't — same+ * inputs, different judgment function.+ *+ * FAILURE MODES: an LLM can be confidently wrong — high stated confidence is+ * not calibrated probability, and this strategy trusts it anyway once it+ * clears `minConfidence`. On-chain metadata (token/creator addresses, launch+ * names if ever added to the brief) is attacker-controlled input reaching the+ * model — a prompt-injection payload disguised as a token name could attempt+ * to manipulate the verdict; the current brief only includes numeric signals+ * for this reason, but any future addition of free-text on-chain fields to+ * the brief must be treated as untrusted. LLM latency means this strategy+ * reacts slower than launch-sniper to the same launch. Every LLM call costs+ * money regardless of verdict; a launch storm inflates API spend with no+ * trading to show for it. A single configured provider has no fallback — a+ * provider outage silently means zero coverage for the outage's duration.+ */+export class LlmStrategist implements Strategy {+ readonly id = 'llm-strategist'+ readonly title = 'LLM Strategist'+ readonly quote = 'weth' as const+ private readonly p: LlmStrategistParams+ private readonly queue: Candidate[] = []+ private readonly seen = new Set<string>()+ private readonly judged = new Set<string>()+ private unwatch: (() => void) | null = null++ constructor(params: Partial<Omit<LlmStrategistParams, 'llm'>> & { llm: LlmClientConfig }) {+ this.p = { ...DEFAULTS, ...params }+ }++ get meta(): StrategyMeta {+ return {+ edge:+ 'An LLM (bring your own key) weighs the same real on-chain launch signals launch-sniper checks ' ++ 'mechanically — buy/sell round-trip retention and deployer supply concentration — holistically ' ++ 'instead of against fixed cutoffs, and only trades when its stated confidence clears a threshold.',+ failureModes: [+ 'LLM confidence is not calibrated probability — a confidently wrong verdict trades exactly like a confidently right one.',+ 'On-chain data reaching the prompt is attacker-controlled; only numeric signals are included today specifically to limit prompt-injection surface.',+ 'LLM round-trip latency means this strategy reacts to a launch after launch-sniper already has (or hasn’t).',+ 'Every judged launch costs a real LLM API call regardless of verdict — a launch storm inflates spend with nothing to show for it.',+ 'One configured provider, no fallback chain — a provider outage means zero coverage until it recovers.',+ ],+ params: { ...this.p, llm: { ...this.p.llm, apiKey: this.p.llm.apiKey ? '<redacted>' : '' } },+ }+ }++ start(ctx: StrategyStartContext): void {+ 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(`llm-strategist: new launch queued: ${launch.launchpad} ${launch.token}`, { creator: launch.creator })+ },+ { onError: (e) => ctx.log(`llm-strategist: 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 candidate judged per tick ───────────────────────────────────────+ const candidate = this.queue.shift()+ if (candidate) {+ const key = candidate.launch.token.toLowerCase()+ if (!this.judged.has(key)) {+ this.judged.add(key)+ const result = await this.evaluate(ctx, candidate)+ if (result.intent) intents.push(result.intent)+ if (result.alert) alerts.push(result.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: `llm-strategist: skip ${launch.token}: stale (${Math.round(ageSec)}s old)`, meta: {} } }+ }+ if (ctx.positions.some((p) => p.token.toLowerCase() === launch.token.toLowerCase())) return {}++ const amountIn = parseEther(String(this.p.entryWeth))++ const buyQuote = await ctx.market.quoteBuy(ctx.quoteToken, launch.token, amountIn)+ if (!buyQuote || buyQuote.amountOut <= 0n) {+ return { alert: { level: 'info', message: `llm-strategist: skip ${launch.token}: no liquid Uniswap route`, meta: { launchpad: launch.launchpad } } }+ }+ const sellQuote = await ctx.market.quoteSell(launch.token, ctx.quoteToken, buyQuote.amountOut)+ const retention = sellQuote && sellQuote.amountOut > 0n ? Number(sellQuote.amountOut) / Number(amountIn) : 0+ const deployerPct = await this.deployerConcentration(ctx, launch)++ const brief = [+ `Launchpad: ${launch.launchpad}`,+ `Round-trip retention (buy then immediately sell back): ${(retention * 100).toFixed(1)}% of input value returned.`,+ `Deployer wallet holds: ${deployerPct === null ? 'unknown (could not read on-chain balance)' : (deployerPct * 100).toFixed(1) + '% of total supply'}.`,+ `Age since first seen: ${Math.round(ageSec)} seconds.`,+ ].join('\n')++ let verdict: LlmVerdict+ try {+ verdict = await judgeLaunch(this.p.llm, brief)+ } catch (err) {+ return {+ alert: {+ level: 'warn',+ message: `llm-strategist: skip ${launch.token}: LLM judge failed — ${(err as Error).message}`,+ meta: { launchpad: launch.launchpad },+ },+ }+ }++ if (!verdict.buy || verdict.confidence < this.p.minConfidence) {+ return {+ alert: {+ level: 'info',+ message: `llm-strategist: skip ${launch.token}: verdict buy=${verdict.buy} confidence=${verdict.confidence.toFixed(2)} — ${verdict.thesis}`,+ meta: { retention, deployerPct, verdict },+ },+ }+ }++ return {+ intent: {+ side: 'buy',+ token: launch.token,+ tokenSymbol: shortToken(launch.token),+ amountIn,+ quoteToken: ctx.quoteToken,+ quoteSymbol: ctx.quoteSymbol,+ reason: `LLM (${this.p.llm.provider}, confidence ${verdict.confidence.toFixed(2)}): ${verdict.thesis}`,+ meta: { launchpad: launch.launchpad, deployerPct, retention, llmProvider: this.p.llm.provider, confidence: verdict.confidence },+ },+ }+ }++ 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/hood-traders/tests/unit/llm-strategist.test.ts b/robinhood/hood-traders/tests/unit/llm-strategist.test.tsnew file mode 100644index 000000000..03957fd21--- /dev/null+++ b/robinhood/hood-traders/tests/unit/llm-strategist.test.ts@@ -0,0 +1,195 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { parseEther, type Address } from 'viem'+import { LlmStrategist } from '../../src/strategies/llm-strategist.js'+import { parseVerdict, judgeLaunch } from '../../src/framework/llm.js'+import type { Market } from '../../src/framework/market.js'+import type { StrategyTickContext } from '../../src/framework/strategy.js'+import { FakeMarket } from './helpers/fake-market.js'++const TOKEN_A = '0x2222222222222222222222222222222222222b' as Address+const CREATOR = '0x3333333333333333333333333333333333333c' as Address+const WETH = '0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73' as Address++function ctxFor(market: FakeMarket, now: number): StrategyTickContext {+ return {+ market: market as unknown as Market,+ positions: [],+ now,+ quoteToken: WETH,+ quoteSymbol: 'WETH',+ quoteDecimals: 18,+ log: () => {},+ }+}++function seeded(strategist: LlmStrategist, launch: { token: Address; creator: Address; launchpad: 'noxa' | 'odyssey'; pool: Address | null }) {+ ;(strategist as unknown as { queue: { launch: typeof launch; seenAt: number }[] }).queue.push({+ launch: { ...launch, blockNumber: 1n, transactionHash: '0xdead' as `0x${string}` },+ seenAt: Date.now(),+ })+}++describe('parseVerdict', () => {+ it('parses a clean JSON object', () => {+ const v = parseVerdict('{"buy": true, "confidence": 0.8, "thesis": "clean retention, low deployer share"}')+ expect(v).toEqual({ buy: true, confidence: 0.8, thesis: 'clean retention, low deployer share' })+ })++ it('extracts JSON embedded in surrounding prose', () => {+ const v = parseVerdict('Sure, here is my verdict:\n{"buy": false, "confidence": 0.3, "thesis": "thin liquidity"}\nHope that helps!')+ expect(v.buy).toBe(false)+ expect(v.confidence).toBe(0.3)+ })++ it('clamps out-of-range confidence into [0, 1]', () => {+ expect(parseVerdict('{"buy": true, "confidence": 1.4, "thesis": "x"}').confidence).toBe(1)+ expect(parseVerdict('{"buy": true, "confidence": -0.2, "thesis": "x"}').confidence).toBe(0)+ })++ it('throws on missing JSON entirely', () => {+ expect(() => parseVerdict('no json here')).toThrow(/no JSON object/)+ })++ it('throws when "buy" is not a boolean', () => {+ expect(() => parseVerdict('{"buy": "yes", "confidence": 0.5, "thesis": "x"}')).toThrow(/missing boolean "buy"/)+ })++ it('throws when "thesis" is missing or empty', () => {+ expect(() => parseVerdict('{"buy": true, "confidence": 0.5, "thesis": ""}')).toThrow(/non-empty "thesis"/)+ })+})++describe('judgeLaunch — provider dispatch', () => {+ const originalFetch = global.fetch++ afterEach(() => {+ global.fetch = originalFetch+ })++ it('calls the Anthropic Messages API and parses its response shape', async () => {+ const fetchMock = vi.fn(async (url: string) => {+ expect(url).toBe('https://api.anthropic.com/v1/messages')+ return new Response(JSON.stringify({ content: [{ text: '{"buy": true, "confidence": 0.9, "thesis": "great"}' }] }), { status: 200 })+ })+ global.fetch = fetchMock as unknown as typeof fetch++ const verdict = await judgeLaunch({ provider: 'anthropic', apiKey: 'test-key' }, 'brief')+ expect(verdict.buy).toBe(true)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ })++ it('calls the OpenAI-compatible chat-completions shape for openai/groq/openrouter', async () => {+ const fetchMock = vi.fn(async (url: string) => {+ expect(url).toBe('https://api.groq.com/openai/v1/chat/completions')+ return new Response(JSON.stringify({ choices: [{ message: { content: '{"buy": false, "confidence": 0.2, "thesis": "skip"}' } }] }), { status: 200 })+ })+ global.fetch = fetchMock as unknown as typeof fetch++ const verdict = await judgeLaunch({ provider: 'groq', apiKey: 'test-key' }, 'brief')+ expect(verdict.buy).toBe(false)+ })++ it('throws a descriptive error on a non-2xx response', async () => {+ global.fetch = vi.fn(async () => new Response('model not found', { status: 404 })) as unknown as typeof fetch+ await expect(judgeLaunch({ provider: 'openai', apiKey: 'test-key' }, 'brief')).rejects.toThrow(/HOOD_LLM_MODEL/)+ })+})++describe('LlmStrategist.tick', () => {+ let fetchMock: ReturnType<typeof vi.fn>+ const originalFetch = global.fetch++ beforeEach(() => {+ fetchMock = vi.fn()+ global.fetch = fetchMock as unknown as typeof fetch+ })+ afterEach(() => {+ global.fetch = originalFetch+ })++ function verdictResponse(buy: boolean, confidence: number, thesis = 'because') {+ return new Response(JSON.stringify({ content: [{ text: JSON.stringify({ buy, confidence, thesis }) }] }), { status: 200 })+ }++ it('turns a high-confidence buy verdict into a buy Intent', async () => {+ fetchMock.mockResolvedValueOnce(verdictResponse(true, 0.9, 'clean signals'))+ const strategist = new LlmStrategist({ llm: { provider: 'anthropic', apiKey: 'k' }, minConfidence: 0.6, entryWeth: 0.01 })+ const market = new FakeMarket()+ const amountIn = parseEther('0.01')+ market.buyRoutes.set(TOKEN_A.toLowerCase(), parseEther('1000'))+ market.sellRoutes.set(TOKEN_A.toLowerCase(), (amountIn * 98n) / 100n)+ market.multicallResults = [parseEther('1000'), parseEther('10')]+ seeded(strategist, { token: TOKEN_A, creator: CREATOR, launchpad: 'noxa', pool: TOKEN_A })++ const decision = await strategist.tick(ctxFor(market, Date.now()))+ expect(decision.intents).toHaveLength(1)+ expect(decision.intents[0]?.side).toBe('buy')+ expect(decision.intents[0]?.reason).toMatch(/clean signals/)+ })++ it('does not trade a buy verdict below minConfidence', async () => {+ fetchMock.mockResolvedValueOnce(verdictResponse(true, 0.4, 'marginal'))+ const strategist = new LlmStrategist({ llm: { provider: 'anthropic', apiKey: 'k' }, minConfidence: 0.6 })+ const market = new FakeMarket()+ const amountIn = parseEther('0.01')+ market.buyRoutes.set(TOKEN_A.toLowerCase(), parseEther('1000'))+ market.sellRoutes.set(TOKEN_A.toLowerCase(), (amountIn * 98n) / 100n)+ market.multicallResults = [parseEther('1000'), parseEther('10')]+ seeded(strategist, { token: TOKEN_A, creator: CREATOR, launchpad: 'noxa', pool: TOKEN_A })++ const decision = await strategist.tick(ctxFor(market, Date.now()))+ expect(decision.intents).toHaveLength(0)+ expect(decision.alerts[0]?.message).toMatch(/confidence=0.40/)+ })++ it('does not trade a buy:false verdict regardless of confidence', async () => {+ fetchMock.mockResolvedValueOnce(verdictResponse(false, 0.95, 'looks like a rug'))+ const strategist = new LlmStrategist({ llm: { provider: 'anthropic', apiKey: 'k' }, minConfidence: 0.6 })+ const market = new FakeMarket()+ const amountIn = parseEther('0.01')+ market.buyRoutes.set(TOKEN_A.toLowerCase(), parseEther('1000'))+ market.sellRoutes.set(TOKEN_A.toLowerCase(), (amountIn * 98n) / 100n)+ market.multicallResults = [parseEther('1000'), parseEther('10')]+ seeded(strategist, { token: TOKEN_A, creator: CREATOR, launchpad: 'noxa', pool: TOKEN_A })++ const decision = await strategist.tick(ctxFor(market, Date.now()))+ expect(decision.intents).toHaveLength(0)+ })++ it('alerts (never throws) when the LLM call fails', async () => {+ fetchMock.mockResolvedValueOnce(new Response('rate limited', { status: 429 }))+ const strategist = new LlmStrategist({ llm: { provider: 'anthropic', apiKey: 'k' } })+ const market = new FakeMarket()+ const amountIn = parseEther('0.01')+ market.buyRoutes.set(TOKEN_A.toLowerCase(), parseEther('1000'))+ market.sellRoutes.set(TOKEN_A.toLowerCase(), (amountIn * 98n) / 100n)+ market.multicallResults = [parseEther('1000'), parseEther('10')]+ seeded(strategist, { token: TOKEN_A, creator: CREATOR, launchpad: 'noxa', pool: TOKEN_A })++ const decision = await strategist.tick(ctxFor(market, Date.now()))+ expect(decision.intents).toHaveLength(0)+ expect(decision.alerts[0]?.message).toMatch(/LLM judge failed/)+ })++ it('skips a launch with no liquid Uniswap route without calling the LLM', async () => {+ const strategist = new LlmStrategist({ llm: { provider: 'anthropic', apiKey: 'k' } })+ const market = new FakeMarket()+ seeded(strategist, { token: TOKEN_A, creator: CREATOR, launchpad: 'odyssey', pool: null })++ const decision = await strategist.tick(ctxFor(market, Date.now()))+ expect(decision.intents).toHaveLength(0)+ expect(decision.alerts[0]?.message).toMatch(/no liquid Uniswap route/)+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('reports its edge hypothesis and failure modes (documentation contract)', () => {+ const strategist = new LlmStrategist({ llm: { provider: 'anthropic', apiKey: 'k' } })+ expect(strategist.meta.edge.length).toBeGreaterThan(20)+ expect(strategist.meta.failureModes.length).toBeGreaterThanOrEqual(3)+ })++ it('never leaks the API key through meta()', () => {+ const strategist = new LlmStrategist({ llm: { provider: 'anthropic', apiKey: 'super-secret-key' } })+ expect(JSON.stringify(strategist.meta)).not.toMatch(/super-secret-key/)+ })+})