Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(robinhood): add hood-alerts, Telegram/Discord alerts for Robinhood Chain
nirholasd05065d2e813
diff --git a/robinhood/hood-alerts/.env.example b/robinhood/hood-alerts/.env.examplenew file mode 100644index 000000000..2b67a1904--- /dev/null+++ b/robinhood/hood-alerts/.env.example@@ -0,0 +1,61 @@+# hood-alerts configuration. Copy to .env and fill in what you use.+# Everything is optional: with zero env vars the engine runs with the console+# transport only (alerts printed as structured logs), which is the self-host+# smoke-test mode.++# ---- chain ----+# Custom RPC (e.g. Alchemy: https://robinhood-mainnet.g.alchemy.com/v2/KEY).+# Defaults to the public RPC from viem's official `robinhood` chain definition.+HOOD_ALERTS_RPC_URL=++# ---- storage ----+# SQLite database path (subscriptions, entitlements, dedup, delivery log).+HOOD_ALERTS_DB=./data/hood-alerts.db++# ---- HTTP server ----+# Cloud Run injects PORT. /healthz + the premium x402 endpoints live here.+PORT=8080+# Public base URL of this instance (used in payment challenges + bot replies).+HOOD_ALERTS_PUBLIC_URL=++# ---- Telegram bot ----+# Create with @BotFather -> /newbot. Leave empty to disable the transport.+HOOD_ALERTS_TELEGRAM_TOKEN=++# ---- Discord bot ----+# Create at https://discord.com/developers/applications (Bot token + App ID).+# Leave empty to disable the transport.+HOOD_ALERTS_DISCORD_TOKEN=+HOOD_ALERTS_DISCORD_APP_ID=++# ---- 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 at+# startup until wired to your own facilitator.+HOOD_ALERTS_PREMIUM_RAIL=hood402+# Address that receives premium payments. Premium purchase endpoints stay+# disabled (503 + guidance) until this is set.+HOOD402_PAY_TO=+# Settlement mode A: a hood402 facilitator base URL (recommended; no gas key+# on this box).+HOOD402_FACILITATOR_URL=+# Settlement mode B: self-settle with a gas key. READ THE WARNING in the+# README before putting a key here.+HOOD402_SETTLER_KEY=+# Price + duration of one premium purchase.+HOOD_ALERTS_PREMIUM_PRICE_USDG=5+HOOD_ALERTS_PREMIUM_DAYS=30++# ---- detector tuning (defaults shown) ----+# Floor below which whale trades are not even emitted engine-side (USD).+HOOD_ALERTS_WHALE_FLOOR_USD=1000+# Default per-subscription whale threshold when none is given (USD).+HOOD_ALERTS_WHALE_DEFAULT_USD=5000+# Price-move window (seconds) and default threshold (percent).+HOOD_ALERTS_PRICE_WINDOW_S=900+HOOD_ALERTS_PRICE_DEFAULT_PCT=2+# Stock premium/discount poll interval (seconds) and default threshold (%).+HOOD_ALERTS_PREMIUM_POLL_S=60+HOOD_ALERTS_PREMIUM_DEFAULT_PCT=2+# Liquidity-pull default threshold (percent of pool quote reserves).+HOOD_ALERTS_RUG_DEFAULT_PCT=30diff --git a/robinhood/hood-alerts/.gitignore b/robinhood/hood-alerts/.gitignorenew file mode 100644index 000000000..370b2290e--- /dev/null+++ b/robinhood/hood-alerts/.gitignore@@ -0,0 +1,12 @@+node_modules/+dist/+data/+*.db+*.db-journal+*.db-wal+*.db-shm+.env+.env.*+!.env.example+*.tgz+*.logdiff --git a/robinhood/hood-alerts/LICENSE b/robinhood/hood-alerts/LICENSEnew file mode 100644index 000000000..dff21b7f4--- /dev/null+++ b/robinhood/hood-alerts/LICENSE@@ -0,0 +1,20 @@+Copyright 2026 nirholas++All rights reserved.++This software is proprietary and may not be used, copied, modified, distributed,+translated, or made available to any third party without the express written+permission of the copyright owner.++No rights are granted by implication, estoppel, or otherwise. Use of this+software is subject to the terms of a separate license agreement with the+copyright owner.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.++IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY CLAIM, DAMAGES, OR+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,+ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/robinhood/hood-alerts/README.md b/robinhood/hood-alerts/README.mdnew file mode 100644index 000000000..c6b279583--- /dev/null+++ b/robinhood/hood-alerts/README.md@@ -0,0 +1,233 @@+# hood-alerts++[](./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.++## What it detects++| Detector | Topic | Source |+| --- | --- | --- |+| New token launch | `launches` (`launches:noxa`, `launches:odyssey`) | NOXA (instant Uniswap v3 pool) and The Odyssey (bonding curve) |+| Bonding-curve graduation | `graduations` | Odyssey curve fills and migrates to a locked Uniswap v3 pool |+| Whale trades | `whales`, or per-token `token:0x…` | Odyssey curve trades and Uniswap v3 swaps, chain-wide, threshold in USD |+| Stock Token price moves | `stock:SYMBOL` | Chainlink feed, rolling window, signed percent change |+| On-chain premium/discount (the arb signal) | `premiums` (premium tier) | DEX mid vs Chainlink feed, hysteresis ladder at 1/2/3/5/10/20/50% |+| Holder milestones | per-token `token:0x…` | Blockscout `token_holders_count`, crossing 10 through 100,000 |+| Liquidity-pull rug warning | `rugs` (premium tier), or per-token `token:0x…` | tracked pool's quote-side (USDG/WETH) reserves dropping sharply |++Every event is deduped per fingerprint before it reaches a subscriber, routed through a+premium/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`.++## Quickstart (self-host)++```sh+npm install+npm run dev # tsx watch, console transport only if no bot tokens are set+```++With zero environment variables the engine still runs: detectors connect to the public Robinhood+Chain RPC, alerts print as structured JSON log lines (the console transport), and `/healthz` comes+up on `:8080`. That is the self-host smoke-test mode. Copy `.env.example` to `.env` and fill in a+Telegram and/or Discord bot token to go live on those platforms; see `.env.example` for every+variable, defaults, and what each detector threshold controls.++```sh+npm run build # tsc -> dist/+npm start # node dist/src/index.js+```++### Creating the bots++- **Telegram**: message [@BotFather](https://t.me/BotFather), `/newbot`, paste the token into+ `HOOD_ALERTS_TELEGRAM_TOKEN`. The bot registers its command list on startup.+- **Discord**: create an application at the+ [Developer Portal](https://discord.com/developers/applications), add a bot, copy the bot token+ into `HOOD_ALERTS_DISCORD_TOKEN` and the application id into `HOOD_ALERTS_DISCORD_APP_ID`. Slash+ commands register (guild-visible immediately) on startup.++Leaving either token unset disables that transport; the engine and the console transport keep+running regardless.++## Bot commands++Both bots share one command router (`src/commands/commands.ts`), so the UX is identical modulo+native slash-command vs `/command arg` syntax:++```+watch <what> [threshold]+ launches every new token (add noxa/odyssey to filter)+ graduations Odyssey curves migrating to Uniswap v3+ whales [usd] trades >= usd, chain-wide (default 5000)+ premiums [pct] Stock Token DEX premium/discount vs Chainlink (premium tier)+ rugs [pct] liquidity-pull rug warnings (premium tier)+ <TICKER> a Stock Token: price moves + premium crossings (e.g. TSLA)+ <0x address> a memecoin: whale trades, graduation, holders, liquidity++unwatch <what|all> stop watching+list your subscriptions+threshold <what> <n> change a subscription's threshold+digest on|off [min] batch alerts into digests (default 60 min)+quiet <from> <to> quiet hours in UTC (e.g. quiet 22 7); quiet off+premium premium status + how to upgrade+help this message+```++In a group chat or server, `watch`, `unwatch`, `threshold`, `digest`, and `quiet` are restricted to+admins; `list`, `premium`, and `help` are open to everyone.++## Free vs premium++| | Free | Premium |+| --- | --- | --- |+| Subscriptions | 3 | Unlimited |+| Delivery | Batched to at most one immediate alert per 60s; extras fold into a digest | Real-time, subject only to quiet hours / digest mode you set |+| `premiums` (Stock Token arb signal) | Not available | Included |+| `rugs` (liquidity-pull warning) | Not available | Included |+| Price | Free | `HOOD_ALERTS_PREMIUM_PRICE_USDG` (default 5) USDG for `HOOD_ALERTS_PREMIUM_DAYS` (default 30) days |++Premium is paid on Robinhood Chain via **x402** using [`hood402`](../hood402) (USDG,+EIP-3009 `transferWithAuthorization`, chain 4663). The bot's `premium` command hands back a+`POST /premium/activate?platform=...&chat=...` URL: the first request gets a 402 challenge with+payment instructions, and any x402 client (`hood402`, `x402-fetch`) that can sign a USDG+authorization completes the purchase. The entitlement never activates before the transfer settles+on-chain, so a signature alone buys nothing.++Purchases stay disabled (`503` + setup instructions) until the instance sets `HOOD402_PAY_TO` and+either `HOOD402_FACILITATOR_URL` (delegates verification and settlement, no gas key on this box) or+`HOOD402_SETTLER_KEY` (this instance broadcasts the settlement itself). See `.env.example` for both+modes.++## HTTP API++The same process that runs the bots serves a small Hono app on `PORT` (default 8080):++| Endpoint | Method | Returns |+| --- | --- | --- |+| `/` | 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/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++`src/engine/gate.ts` and `src/engine/topics.ts` have no I/O and are safe to import standalone, for+example to preview how a threshold will gate before wiring a subscription:++```ts+import { gate } from './src/engine/gate.js'+import { resolveWatchTarget, parseTopic } from './src/engine/topics.js'++const target = resolveWatchTarget('whales') // { ok: true, topic: 'whales' }+if (target.ok) {+ const topic = parseTopic(target.topic) // { kind: 'whales' }+ const decision = gate(+ { premium: false, digest: false, quietStart: null, quietEnd: null, lastDeliveredAt: null, deliveredLastMinute: 0 },+ Math.floor(Date.now() / 1000),+ )+ console.log(topic, decision) // { kind: 'whales' } { action: 'deliver' }+}+```++A threshold typed after the target (`watch whales 10000`) is parsed separately by+`Commands.watch()`, not by `resolveWatchTarget` itself.++The package does not ship a public library entry point today (`main`/`bin` both point at the CLI+process in `src/index.ts`, which starts the bots and the HTTP server and does not export anything);+importing from `src/` as above works in this checkout but is not a published API contract.++## Configuration++Every variable, its default, and what it controls: [`.env.example`](.env.example). Highlights:++- `HOOD_ALERTS_RPC_URL` — custom RPC; defaults to viem's public `robinhood` chain RPC.+- `HOOD_ALERTS_DB` — SQLite path (subscriptions, entitlements, dedup, delivery log). `:memory:`+ works for tests.+- `HOOD_ALERTS_WHALE_FLOOR_USD` / `HOOD_ALERTS_WHALE_DEFAULT_USD` — engine-side emission floor vs.+ the default per-subscription threshold.+- `HOOD_ALERTS_PRICE_WINDOW_S` / `HOOD_ALERTS_PRICE_DEFAULT_PCT` — Chainlink rolling-window move+ detector.+- `HOOD_ALERTS_PREMIUM_POLL_S` / `HOOD_ALERTS_PREMIUM_DEFAULT_PCT` — Stock Token arb poll cadence+ and default ladder entry.+- `HOOD_ALERTS_RUG_DEFAULT_PCT` — default liquidity-pull threshold (percent of quote reserves).++## Development++```sh+npm install+npm run typecheck # tsc --noEmit, strict + exactOptionalPropertyTypes+npm test # vitest: dedup/rate-limit gate, digest batching, topic parsing and+ # matching, event fingerprinting/TTL, alert card rendering, config+ # loading, the command router, and the subscriber/entitlement/delivery+ # repositories — all offline, no chain or bot credentials required+npm run build # tsc -> dist/+```++`npm run test:live` and `npm run probe` exercise the live detector set against real Robinhood Chain+RPC and, for `probe`, the console transport; they need real network access and are not part of the+offline unit suite above.++### Local sibling packages++`hood402`, `hoodkit`, and `hoodchain` are consumed as `file:` dependencies of the other Robinhood+Chain repos in this workspace (`../hood402`, `../hoodkit`, `../robinhood-chain-sdk`) rather than+their published npm versions, so a change to any of them is picked up on the next `npm install`+here. Keep `viem` pinned to the exact version those sibling packages resolve (currently `2.55.1`):+a newer patch on only one side of a `file:` link makes viem's structural types for `Chain` and+`WalletClient` diverge across the two copies and breaks the type check in `src/premium/paywall.ts`+and `src/index.ts`.++## Architecture notes++- **Console transport is not a fallback, it's the smoke-test mode.** With no bot tokens configured+ the engine still ingests real chain events and logs every alert/digest as structured JSON; that+ is how a fresh self-host proves the pipeline works before touching Telegram or Discord.+- **The entitlement never activates before settlement.** `PremiumPaywall.activate()` calls+ `hood402`'s verify-then-settle flow and only writes the entitlement row after the on-chain+ transfer succeeds.+- **Digest buffering is in-memory by design.** A restart loses at most one pending batch, never a+ subscription (subscriptions and the delivery log are in SQLite); `AlertEngine.stop()` flushes+ every buffered digest before shutdown.+- **Auto-tracked pools expire; watched pools do not.** A NOXA/Odyssey launch or graduation starts a+ 24h rug-watch on its pool automatically; a user `watch 0x…` keeps that pool's liquidity monitor+ running indefinitely.++## Repo layout++```+src/index.ts CLI entry: wires config, db, engine, detectors, transports, HTTP server+src/config.ts environment -> validated Config+src/server.ts Hono app: /, /healthz, /premium/status, /premium/activate+src/engine/ event types, dedup fingerprinting, topic parsing/matching, the+ digest buffer, the delivery gate, and the live detector set+src/engine/detectors/ pure per-signal detectors (price move, premium ladder, holder+ milestones, liquidity pull, whale classification) plus live.ts,+ which wires them to hoodchain/hoodkit streams+src/db/ better-sqlite3 repositories: subscribers, entitlements, deliveries+src/premium/paywall.ts the hood402 x402 purchase flow+src/transports/ Telegram (grammY), Discord (discord.js), and console transports+src/commands/commands.ts the shared, platform-neutral command router+src/format/cards.ts alert -> platform-neutral card -> per-platform rendering+tests/ vitest unit suite (see Development above)+```++## Notes++- **Stock Tokens.** Stock Tokens are tokenized debt securities (issuer: Robinhood Assets (Jersey)+ Ltd) and may not be offered, sold, or delivered to US persons (additional limits: Canada, UK,+ Switzerland). hood-alerts only ever displays price/premium data derived from public Chainlink+ feeds and DEX pools; it never facilitates acquiring a Stock Token.+- Liquidity-pull alerts are an early warning, not proof of a rug: always check the pool before+ acting on one.+- Not affiliated with Robinhood Markets, Inc.++## License++Proprietary, all rights reserved. See [LICENSE](./LICENSE).++Built by [nirholas](https://x.com/nichxbt) · [three.ws](https://three.ws)diff --git a/robinhood/hood-alerts/package-lock.json b/robinhood/hood-alerts/package-lock.jsonnew file mode 100644index 000000000..c6af25ca2--- /dev/null+++ b/robinhood/hood-alerts/package-lock.json@@ -0,0 +1,2944 @@+{+ "name": "hood-alerts",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "hood-alerts",+ "version": "0.1.0",+ "license": "MIT",+ "dependencies": {+ "@hono/node-server": "^1.14.0",+ "better-sqlite3": "^12.11.0",+ "discord.js": "^14.27.0",+ "grammy": "^1.44.0",+ "hono": "^4.12.0",+ "hood402": "file:../hood402",+ "hoodchain": "file:../robinhood-chain-sdk",+ "hoodkit": "file:../hoodkit",+ "pino": "^10.3.0",+ "viem": "2.55.1"+ },+ "bin": {+ "hood-alerts": "dist/src/index.js"+ },+ "devDependencies": {+ "@types/better-sqlite3": "^7.6.13",+ "@types/node": "^24.0.0",+ "tsx": "^4.20.0",+ "typescript": "^5.9.0",+ "vitest": "^3.2.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "../hood402": {+ "version": "0.1.0",+ "license": "Apache-2.0",+ "devDependencies": {+ "@types/express": "^4.17.21",+ "express": "^4.21.2",+ "tsup": "^8.3.5",+ "tsx": "^4.19.2",+ "typescript": "^5.7.2",+ "viem": "^2.55.0",+ "vitest": "^2.1.8"+ },+ "engines": {+ "node": ">=20"+ },+ "peerDependencies": {+ "viem": "^2.55.0"+ }+ },+ "../hoodkit": {+ "version": "0.1.0",+ "license": "Apache-2.0",+ "devDependencies": {+ "@types/better-sqlite3": "^7.6.0",+ "@types/node": "^24.0.0",+ "@types/react": "^19.0.0",+ "@types/ws": "^8.18.0",+ "better-sqlite3": "^12.0.0",+ "hoodchain": "file:../robinhood-chain-sdk",+ "react": "^19.0.0",+ "tsup": "^8.5.0",+ "typedoc": "^0.28.0",+ "typescript": "^5.9.0",+ "viem": "^2.55.0",+ "vitest": "^3.2.0",+ "ws": "^8.18.0"+ },+ "engines": {+ "node": ">=20"+ },+ "peerDependencies": {+ "better-sqlite3": ">=11",+ "hoodchain": "^0.1.0",+ "react": ">=18",+ "viem": "^2.55.0",+ "ws": "^8.18.0"+ },+ "peerDependenciesMeta": {+ "better-sqlite3": {+ "optional": true+ },+ "react": {+ "optional": true+ },+ "ws": {+ "optional": true+ }+ }+ },+ "../robinhood-chain-sdk": {+ "name": "hoodchain",+ "version": "0.1.1",+ "license": "SEE LICENSE IN LICENSE",+ "devDependencies": {+ "@types/node": "^24.0.0",+ "@types/ws": "^8.18.0",+ "tsup": "^8.5.0",+ "typedoc": "^0.28.0",+ "typescript": "^5.9.0",+ "viem": "^2.55.0",+ "vitest": "^3.2.0",+ "ws": "^8.18.0"+ },+ "engines": {+ "node": ">=20"+ },+ "peerDependencies": {+ "viem": "^2.55.0",+ "ws": "^8.18.0"+ },+ "peerDependenciesMeta": {+ "ws": {+ "optional": true+ }+ }+ },+ "node_modules/@adraffy/ens-normalize": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz",+ "integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==",+ "license": "MIT"+ },+ "node_modules/@discordjs/builders": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz",+ "integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@discordjs/formatters": "^0.6.2",+ "@discordjs/util": "^1.2.0",+ "@sapphire/shapeshift": "^4.0.0",+ "discord-api-types": "^0.38.40",+ "fast-deep-equal": "^3.1.3",+ "ts-mixer": "^6.0.4",+ "tslib": "^2.6.3"+ },+ "engines": {+ "node": ">=16.11.0"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/collection": {+ "version": "1.5.3",+ "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz",+ "integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=16.11.0"+ }+ },+ "node_modules/@discordjs/formatters": {+ "version": "0.6.2",+ "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.2.tgz",+ "integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "discord-api-types": "^0.38.33"+ },+ "engines": {+ "node": ">=16.11.0"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/rest": {+ "version": "2.6.2",+ "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.2.tgz",+ "integrity": "sha512-c5HI3hJuRWWrnpyCZAUYfIUTAEv9weX4tE2UfDqtM3ztizdKE9RFEf3G5IWhPyO+kPldUDpGv02XJAQzdUTC9Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@discordjs/collection": "^2.1.1",+ "@discordjs/util": "^1.2.0",+ "@sapphire/async-queue": "^1.5.3",+ "@sapphire/snowflake": "^3.5.5",+ "@vladfrangu/async_event_emitter": "^2.4.6",+ "discord-api-types": "^0.38.49",+ "magic-bytes.js": "^1.13.0",+ "tslib": "^2.6.3",+ "undici": "^6.27.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/rest/node_modules/@discordjs/collection": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",+ "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/util": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz",+ "integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==",+ "license": "Apache-2.0",+ "dependencies": {+ "discord-api-types": "^0.38.33"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/ws": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.3.tgz",+ "integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@discordjs/collection": "^2.1.0",+ "@discordjs/rest": "^2.5.1",+ "@discordjs/util": "^1.1.0",+ "@sapphire/async-queue": "^1.5.2",+ "@types/ws": "^8.5.10",+ "@vladfrangu/async_event_emitter": "^2.2.4",+ "discord-api-types": "^0.38.1",+ "tslib": "^2.6.2",+ "ws": "^8.17.0"+ },+ "engines": {+ "node": ">=16.11.0"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@discordjs/ws/node_modules/@discordjs/collection": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",+ "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",+ "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",+ "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",+ "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",+ "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",+ "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",+ "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",+ "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",+ "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",+ "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",+ "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",+ "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",+ "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",+ "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",+ "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",+ "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",+ "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",+ "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",+ "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",+ "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",+ "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",+ "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",+ "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",+ "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",+ "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",+ "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",+ "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@grammyjs/types": {+ "version": "3.28.0",+ "resolved": "https://registry.npmjs.org/@grammyjs/types/-/types-3.28.0.tgz",+ "integrity": "sha512-4JvXCdxRZHCje0M4gHzLwtB4bLno3WD28xd8CNfk4POWIu73BFnSvGeW6OQ5gPem4eYTEwkD9yDaXssixl6tMQ==",+ "license": "MIT"+ },+ "node_modules/@hono/node-server": {+ "version": "1.19.14",+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz",+ "integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==",+ "license": "MIT",+ "engines": {+ "node": ">=18.14.1"+ },+ "peerDependencies": {+ "hono": "^4"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@noble/ciphers": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",+ "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",+ "license": "MIT",+ "engines": {+ "node": "^14.21.3 || >=16"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@noble/curves": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz",+ "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==",+ "license": "MIT",+ "dependencies": {+ "@noble/hashes": "1.8.0"+ },+ "engines": {+ "node": "^14.21.3 || >=16"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@noble/hashes": {+ "version": "1.8.0",+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",+ "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",+ "license": "MIT",+ "engines": {+ "node": "^14.21.3 || >=16"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@pinojs/redact": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",+ "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==",+ "license": "MIT"+ },+ "node_modules/@rollup/rollup-android-arm-eabi": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.2.tgz",+ "integrity": "sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-android-arm64": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.2.tgz",+ "integrity": "sha512-BaH7BllCACHoH1LguOU56UItGfUWjujlO65kS9LAodViaN4bwIKd7oeW/ZHJ/4ljr/7MIiENnNy3HJ0zXv8Zkw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-darwin-arm64": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.2.tgz",+ "integrity": "sha512-v39RCCvj4He82I9sFmk+M1VZ0PLM9sfsLVikjfx2hYBNALhrrOR2D3JjQA6AhlaSOgcR+RzrKY7e1+bT6SUO/A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-darwin-x64": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.2.tgz",+ "integrity": "sha512-yl0y2vq3S3lHeuXhEdss6TWfKW8vkujImO12tn4ZkG/4oghr09LvdYm2RElVjokTQiUvDUGXLGsYeLqUMCKpGA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-arm64": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.2.tgz",+ "integrity": "sha512-tT4pvt4qXD+vEoezupCWi+a1F0vvDiksiHc+PxRlYTOH1I6/X4id9jPxTP+Fg+545euaFT1jJVs4CEdHZAU1vw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-x64": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.2.tgz",+ "integrity": "sha512-6nU5F2wCW+qvCBhTn1pdIU3bzsIoF7EUwsCDRxilWGprQR6yd508YnH9+OKFCwpfS8pjZqDUmnCAr7exax0XCg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.2.tgz",+ "integrity": "sha512-n1GJHPOvpIfhi3TmrCeh6S6URt9BFCt0KQE3qvexyGCTAKpR4Lg+eWvNZEqu7epxwus/8ElT3hacYEucm49SZg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.2.tgz",+ "integrity": "sha512-JqgflS8wEB+UXV/vS1RpRbifGBeN4D5lz8D8oOFbFZw4vedvdOgCFAjfBmIMdW3yL10XpQQ0Ambepw6MXrhOnA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-gnu": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.2.tgz",+ "integrity": "sha512-wnFJkogWvN4jm/hQRF2UBaeUmk20j5+DmHvoyWii2b8HJDyvz1MF2OU/6ynXt2KR63rbZLWkFpoytpdc/yBuSA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-musl": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.2.tgz",+ "integrity": "sha512-HVu2bp0zhvJ8xHEV9+UUs7S90VadmBSY3LcIMvozbPo4AuMGDWlz3ymHLHZPX4hR67TKTt8Qp5PJ5RBg/i+RMQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-loong64-gnu": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.2.tgz",+ "integrity": "sha512-mQqqAV8QaoSgr9I2fKDLY2BAVvmKjWoGiu/cSYQonsLvtqwEn1E4QYfnCOcp5zoEqNhsDYin1s6jx/VJmrxlZg==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-loong64-musl": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.2.tgz",+ "integrity": "sha512-IxKLoxCQ2IWi6bT2akyDUBGsOImDKB+sPp4EsTmwFQ/fMwpCKm8uLSSgP/Kx/QYUgKis6SEZ5/Nlhup0DIA0PQ==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.2.tgz",+ "integrity": "sha512-Mk5ha2RQSgyFfmYYLkBpPnUk8D8FriBxesO1u9O75X0mHgXL1UQcH5Itl2lurWL2tj0RxV9b9tJgipac0hRY9A==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-ppc64-musl": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.2.tgz",+ "integrity": "sha512-CjvEnqJL/0/TQ3TXX3OPIJ/kmBellrWd4heXUmHeJlTnmwjKpSJzoehLaL6Xk0ZnMHBu9dZuFADNOrtjF4v+2w==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.2.tgz",+ "integrity": "sha512-1SiZbzwdkaDURsew/tSOrooKiYy7EQGT6m8ufavAi9NEyQb/6VuIxFXAL1fqa4iZe3g4NbNk4P7J32z2tw5Mgg==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-musl": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.2.tgz",+ "integrity": "sha512-nQts12zJ3NQRoE6uYljOH89v7szzLDvG2JD/vsX+vGXU8w/At1GowTZ5/7qeFQ8m7L55rpR8Okugnuo5bgjy2Q==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-s390x-gnu": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.2.tgz",+ "integrity": "sha512-E9/ll019jhPIJgpzfZoIkBGhcz+kKNgVWYRY0zr9srBdPPFVpvOKW8VaJKUbeK+eZXyQF9ltME+Kk6affeaPgg==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-gnu": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.2.tgz",+ "integrity": "sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-musl": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.2.tgz",+ "integrity": "sha512-uNN83XxQrRAh/w0/pmAfibcwyb6YWt4gP+dpnQKPVJshAloQ785ii8CT8ZCIxkGg9opVsvAlGhFitSm6D1Jjpg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-openbsd-x64": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.2.tgz",+ "integrity": "sha512-srjEIxSH3LRnJN6THczDHWQplqEMFiAJrTab0msUryh9kwNpkICf3Ea6q6MN/2cZwRFUNx5w+h6Hpi4QuHS6Zg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ]+ },+ "node_modules/@rollup/rollup-openharmony-arm64": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.2.tgz",+ "integrity": "sha512-8hOJnxgbyObnCm5AlRA3A931xX19xq80RjVTKgJOvEKWqJruP/Uf12IbAOaDjjEXYRewwHLfmF0YRIdK3OwKWA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ]+ },+ "node_modules/@rollup/rollup-win32-arm64-msvc": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.2.tgz",+ "integrity": "sha512-mmF4AY1i0hG/bLWUctUq59gtmgaSIRa3cu/A3JFRp/sCNEme2bgDEiDS22P9FbnJB8NJNF4jPJiSP5RHQpUTDg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-ia32-msvc": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.2.tgz",+ "integrity": "sha512-DZgkknc6jhHrk46V25vbAM0zZkyP0nSDkJB8/dRkLTxv470dOmWDqGoEJl/9A0dFfS7yE3REOwNDxpHwSLSt0Q==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-gnu": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.2.tgz",+ "integrity": "sha512-T6xr6ucWSFto+VGajA8YH26LdpHRuP4YLHEKAtCWvJDOlnmWcDZVCI2Jmjr+IFHDlt2zRaTAKE4tfjTaWLgJBg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-msvc": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.2.tgz",+ "integrity": "sha512-BfzEnDJOt9T8M989/lA37EcJgat01wLRnoi5dQf3QzOH7jzpqTAzdDbVfRljVr5r+jzKqpbHeyOfAaXxAd0PAA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@sapphire/async-queue": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz",+ "integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==",+ "license": "MIT",+ "engines": {+ "node": ">=v14.0.0",+ "npm": ">=7.0.0"+ }+ },+ "node_modules/@sapphire/shapeshift": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz",+ "integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "lodash": "^4.17.21"+ },+ "engines": {+ "node": ">=v16"+ }+ },+ "node_modules/@sapphire/snowflake": {+ "version": "3.5.5",+ "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz",+ "integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==",+ "license": "MIT",+ "engines": {+ "node": ">=v14.0.0",+ "npm": ">=7.0.0"+ }+ },+ "node_modules/@scure/base": {+ "version": "1.2.6",+ "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz",+ "integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==",+ "license": "MIT",+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@scure/bip32": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.7.0.tgz",+ "integrity": "sha512-E4FFX/N3f4B80AKWp5dP6ow+flD1LQZo/w8UnLGYZO674jS6YnYeepycOOksv+vLPSpgN35wgKgy+ybfTb2SMw==",+ "license": "MIT",+ "dependencies": {+ "@noble/curves": "~1.9.0",+ "@noble/hashes": "~1.8.0",+ "@scure/base": "~1.2.5"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@scure/bip39": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.6.0.tgz",+ "integrity": "sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A==",+ "license": "MIT",+ "dependencies": {+ "@noble/hashes": "~1.8.0",+ "@scure/base": "~1.2.5"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@types/better-sqlite3": {+ "version": "7.6.13",+ "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz",+ "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/chai": {+ "version": "5.2.3",+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/deep-eql": "*",+ "assertion-error": "^2.0.1"+ }+ },+ "node_modules/@types/deep-eql": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/estree": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/node": {+ "version": "24.13.3",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz",+ "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",+ "license": "MIT",+ "dependencies": {+ "undici-types": "~7.18.0"+ }+ },+ "node_modules/@types/ws": {+ "version": "8.18.1",+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@vitest/expect": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.7.tgz",+ "integrity": "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/chai": "^5.2.2",+ "@vitest/spy": "3.2.7",+ "@vitest/utils": "3.2.7",+ "chai": "^5.2.0",+ "tinyrainbow": "^2.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/mocker": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz",+ "integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/spy": "3.2.7",+ "estree-walker": "^3.0.3",+ "magic-string": "^0.30.17"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "msw": "^2.4.9",+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"+ },+ "peerDependenciesMeta": {+ "msw": {+ "optional": true+ },+ "vite": {+ "optional": true+ }+ }+ },+ "node_modules/@vitest/pretty-format": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz",+ "integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyrainbow": "^2.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/runner": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.7.tgz",+ "integrity": "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/utils": "3.2.7",+ "pathe": "^2.0.3",+ "strip-literal": "^3.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/snapshot": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.7.tgz",+ "integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "3.2.7",+ "magic-string": "^0.30.17",+ "pathe": "^2.0.3"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/spy": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz",+ "integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyspy": "^4.0.3"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/utils": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.7.tgz",+ "integrity": "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "3.2.7",+ "loupe": "^3.1.4",+ "tinyrainbow": "^2.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vladfrangu/async_event_emitter": {+ "version": "2.4.7",+ "resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.7.tgz",+ "integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==",+ "license": "MIT",+ "engines": {+ "node": ">=v14.0.0",+ "npm": ">=7.0.0"+ }+ },+ "node_modules/abitype": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.2.3.tgz",+ "integrity": "sha512-Ofer5QUnuUdTFsBRwARMoWKOH1ND5ehwYhJ3OJ/BQO+StkwQjHw0XyVh4vDttzHB7QOFhPHa/o413PJ82gU/Tg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/wevm"+ },+ "peerDependencies": {+ "typescript": ">=5.0.4",+ "zod": "^3.22.0 || ^4.0.0"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ },+ "zod": {+ "optional": true+ }+ }+ },+ "node_modules/abort-controller": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",+ "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",+ "license": "MIT",+ "dependencies": {+ "event-target-shim": "^5.0.0"+ },+ "engines": {+ "node": ">=6.5"+ }+ },+ "node_modules/assertion-error": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/atomic-sleep": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",+ "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==",+ "license": "MIT",+ "engines": {+ "node": ">=8.0.0"+ }+ },+ "node_modules/base64-js": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/better-sqlite3": {+ "version": "12.11.1",+ "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.11.1.tgz",+ "integrity": "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "bindings": "^1.5.0",+ "prebuild-install": "^7.1.1"+ },+ "engines": {+ "node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x"+ }+ },+ "node_modules/bindings": {+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",+ "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",+ "license": "MIT",+ "dependencies": {+ "file-uri-to-path": "1.0.0"+ }+ },+ "node_modules/bl": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",+ "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",+ "license": "MIT",+ "dependencies": {+ "buffer": "^5.5.0",+ "inherits": "^2.0.4",+ "readable-stream": "^3.4.0"+ }+ },+ "node_modules/buffer": {+ "version": "5.7.1",+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",+ "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "base64-js": "^1.3.1",+ "ieee754": "^1.1.13"+ }+ },+ "node_modules/cac": {+ "version": "6.7.14",+ "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",+ "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/chai": {+ "version": "5.3.3",+ "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",+ "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "assertion-error": "^2.0.1",+ "check-error": "^2.1.1",+ "deep-eql": "^5.0.1",+ "loupe": "^3.1.0",+ "pathval": "^2.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/check-error": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",+ "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 16"+ }+ },+ "node_modules/chownr": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",+ "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",+ "license": "ISC"+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/decompress-response": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",+ "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",+ "license": "MIT",+ "dependencies": {+ "mimic-response": "^3.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/deep-eql": {+ "version": "5.0.2",+ "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",+ "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/deep-extend": {+ "version": "0.6.0",+ "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",+ "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",+ "license": "MIT",+ "engines": {+ "node": ">=4.0.0"+ }+ },+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/discord-api-types": {+ "version": "0.38.50",+ "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.50.tgz",+ "integrity": "sha512-J2n/bpIETX3DQ6AJ7/0xbsTLmYiJQtO/LKcXKC1YDbB56OUwtDbdXOFE8Q4g8jVGHBR2VAy1+D4ngaIgkMNV9w==",+ "license": "MIT",+ "workspaces": [+ "scripts/actions/documentation"+ ]+ },+ "node_modules/discord.js": {+ "version": "14.27.0",+ "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.27.0.tgz",+ "integrity": "sha512-qHbFlFG2N7y3LjPySYsL6A1+BnX6bkTVgo842EX0CqVPk/KTMwZkojPHEXKsQUpWZNyz5BISNHK1cPpQw0+m4A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@discordjs/builders": "^1.14.1",+ "@discordjs/collection": "1.5.3",+ "@discordjs/formatters": "^0.6.2",+ "@discordjs/rest": "^2.6.2",+ "@discordjs/util": "^1.2.0",+ "@discordjs/ws": "^1.2.3",+ "@sapphire/snowflake": "3.5.5",+ "discord-api-types": "^0.38.49",+ "fast-deep-equal": "3.1.3",+ "lodash.snakecase": "4.1.1",+ "magic-bytes.js": "^1.13.0",+ "tslib": "^2.6.3",+ "undici": "^6.27.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/discordjs/discord.js?sponsor"+ }+ },+ "node_modules/end-of-stream": {+ "version": "1.4.5",+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",+ "license": "MIT",+ "dependencies": {+ "once": "^1.4.0"+ }+ },+ "node_modules/es-module-lexer": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",+ "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/esbuild": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",+ "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.28.1",+ "@esbuild/android-arm": "0.28.1",+ "@esbuild/android-arm64": "0.28.1",+ "@esbuild/android-x64": "0.28.1",+ "@esbuild/darwin-arm64": "0.28.1",+ "@esbuild/darwin-x64": "0.28.1",+ "@esbuild/freebsd-arm64": "0.28.1",+ "@esbuild/freebsd-x64": "0.28.1",+ "@esbuild/linux-arm": "0.28.1",+ "@esbuild/linux-arm64": "0.28.1",+ "@esbuild/linux-ia32": "0.28.1",+ "@esbuild/linux-loong64": "0.28.1",+ "@esbuild/linux-mips64el": "0.28.1",+ "@esbuild/linux-ppc64": "0.28.1",+ "@esbuild/linux-riscv64": "0.28.1",+ "@esbuild/linux-s390x": "0.28.1",+ "@esbuild/linux-x64": "0.28.1",+ "@esbuild/netbsd-arm64": "0.28.1",+ "@esbuild/netbsd-x64": "0.28.1",+ "@esbuild/openbsd-arm64": "0.28.1",+ "@esbuild/openbsd-x64": "0.28.1",+ "@esbuild/openharmony-arm64": "0.28.1",+ "@esbuild/sunos-x64": "0.28.1",+ "@esbuild/win32-arm64": "0.28.1",+ "@esbuild/win32-ia32": "0.28.1",+ "@esbuild/win32-x64": "0.28.1"+ }+ },+ "node_modules/estree-walker": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0"+ }+ },+ "node_modules/event-target-shim": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",+ "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/eventemitter3": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz",+ "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==",+ "license": "MIT"+ },+ "node_modules/expand-template": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",+ "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",+ "license": "(MIT OR WTFPL)",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/expect-type": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "license": "MIT"+ },+ "node_modules/fdir": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12.0.0"+ },+ "peerDependencies": {+ "picomatch": "^3 || ^4"+ },+ "peerDependenciesMeta": {+ "picomatch": {+ "optional": true+ }+ }+ },+ "node_modules/file-uri-to-path": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",+ "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",+ "license": "MIT"+ },+ "node_modules/fs-constants": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",+ "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",+ "license": "MIT"+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/github-from-package": {+ "version": "0.0.0",+ "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",+ "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==",+ "license": "MIT"+ },+ "node_modules/grammy": {+ "version": "1.44.0",+ "resolved": "https://registry.npmjs.org/grammy/-/grammy-1.44.0.tgz",+ "integrity": "sha512-gGVykS5+c5f1tPV97LuU6IDRMawE2NzpwM9pNz58HQ35IZXDnYL3VOLvNzYognPSeBIOSzQXRu5w96V0aY8y8A==",+ "license": "MIT",+ "dependencies": {+ "@grammyjs/types": "3.28.0",+ "abort-controller": "^3.0.0",+ "debug": "^4.4.3",+ "node-fetch": "^2.7.0"+ },+ "engines": {+ "node": "^12.20.0 || >=14.13.1"+ }+ },+ "node_modules/hono": {+ "version": "4.12.30",+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.30.tgz",+ "integrity": "sha512-emn+JoJjrN9YTpRDS5it/UI2SO9BAE37T6I3d963RxcZ81G9A4pr2SZTEiiaiKbzx+NKRg5BZ89fCL7gCJCUog==",+ "license": "MIT",+ "engines": {+ "node": ">=16.9.0"+ }+ },+ "node_modules/hood402": {+ "resolved": "../hood402",+ "link": true+ },+ "node_modules/hoodchain": {+ "resolved": "../robinhood-chain-sdk",+ "link": true+ },+ "node_modules/hoodkit": {+ "resolved": "../hoodkit",+ "link": true+ },+ "node_modules/ieee754": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },+ "node_modules/ini": {+ "version": "1.3.8",+ "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",+ "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",+ "license": "ISC"+ },+ "node_modules/isows": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/isows/-/isows-1.0.7.tgz",+ "integrity": "sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/wevm"+ }+ ],+ "license": "MIT",+ "peerDependencies": {+ "ws": "*"+ }+ },+ "node_modules/js-tokens": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz",+ "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/lodash": {+ "version": "4.18.1",+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",+ "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",+ "license": "MIT"+ },+ "node_modules/lodash.snakecase": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz",+ "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==",+ "license": "MIT"+ },+ "node_modules/loupe": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",+ "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/magic-bytes.js": {+ "version": "1.13.0",+ "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.0.tgz",+ "integrity": "sha512-afO2mnxW7GDTXMm5/AoN1WuOcdoKhtgXjIvHmobqTD1grNplhGdv3PFOyjCVmrnOZBIT/gD/koDKpYG+0mvHcg==",+ "license": "MIT"+ },+ "node_modules/magic-string": {+ "version": "0.30.21",+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.5"+ }+ },+ "node_modules/mimic-response": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",+ "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/minimist": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/mkdirp-classic": {+ "version": "0.5.3",+ "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",+ "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",+ "license": "MIT"+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/nanoid": {+ "version": "3.3.16",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",+ "integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/napi-build-utils": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",+ "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==",+ "license": "MIT"+ },+ "node_modules/node-abi": {+ "version": "3.94.0",+ "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.94.0.tgz",+ "integrity": "sha512-W5ZNO5KRPB5TkYmGVD9F6YqhsglXJzE6etpbmT+f6EQElhiX/UTG551cnsRGvLG3fyZEg9HwaDmNmj5nwJ4z9g==",+ "license": "MIT",+ "dependencies": {+ "semver": "^7.3.5"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/node-fetch": {+ "version": "2.7.0",+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",+ "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",+ "license": "MIT",+ "dependencies": {+ "whatwg-url": "^5.0.0"+ },+ "engines": {+ "node": "4.x || >=6.0.0"+ },+ "peerDependencies": {+ "encoding": "^0.1.0"+ },+ "peerDependenciesMeta": {+ "encoding": {+ "optional": true+ }+ }+ },+ "node_modules/on-exit-leak-free": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",+ "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==",+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },+ "node_modules/ox": {+ "version": "0.14.30",+ "resolved": "https://registry.npmjs.org/ox/-/ox-0.14.30.tgz",+ "integrity": "sha512-LI11uu+8iiM1B3CLckgd++YF1a0A2k5wDoM9ZeQMiL21BOzQs6L//BLS6hb1HSEKCyycdDIQLsVQx9MjpcC0hA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/wevm"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@adraffy/ens-normalize": "^1.11.0",+ "@noble/ciphers": "^1.3.0",+ "@noble/curves": "1.9.1",+ "@noble/hashes": "^1.8.0",+ "@scure/bip32": "^1.7.0",+ "@scure/bip39": "^1.6.0",+ "abitype": "^1.2.3",+ "eventemitter3": "5.0.1"+ },+ "peerDependencies": {+ "typescript": ">=5.4.0"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ }+ },+ "node_modules/pathe": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/pathval": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",+ "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 14.16"+ }+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/picomatch": {+ "version": "4.0.5",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",+ "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/pino": {+ "version": "10.3.1",+ "resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz",+ "integrity": "sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==",+ "license": "MIT",+ "dependencies": {+ "@pinojs/redact": "^0.4.0",+ "atomic-sleep": "^1.0.0",+ "on-exit-leak-free": "^2.1.0",+ "pino-abstract-transport": "^3.0.0",+ "pino-std-serializers": "^7.0.0",+ "process-warning": "^5.0.0",+ "quick-format-unescaped": "^4.0.3",+ "real-require": "^0.2.0",+ "safe-stable-stringify": "^2.3.1",+ "sonic-boom": "^4.0.1",+ "thread-stream": "^4.0.0"+ },+ "bin": {+ "pino": "bin.js"+ }+ },+ "node_modules/pino-abstract-transport": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz",+ "integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==",+ "license": "MIT",+ "dependencies": {+ "split2": "^4.0.0"+ }+ },+ "node_modules/pino-std-serializers": {+ "version": "7.1.0",+ "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz",+ "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==",+ "license": "MIT"+ },+ "node_modules/postcss": {+ "version": "8.5.19",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.19.tgz",+ "integrity": "sha512-Mz8SaolMd8nB+G13WkORcxQKHZ/NE4xXevtkJHVuG+guo9/wYKlIMTKAqGdEmYOXR2ijPjTYNHssizdaVSUNdQ==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.12",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/prebuild-install": {+ "version": "7.1.3",+ "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",+ "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",+ "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.",+ "license": "MIT",+ "dependencies": {+ "detect-libc": "^2.0.0",+ "expand-template": "^2.0.3",+ "github-from-package": "0.0.0",+ "minimist": "^1.2.3",+ "mkdirp-classic": "^0.5.3",+ "napi-build-utils": "^2.0.0",+ "node-abi": "^3.3.0",+ "pump": "^3.0.0",+ "rc": "^1.2.7",+ "simple-get": "^4.0.0",+ "tar-fs": "^2.0.0",+ "tunnel-agent": "^0.6.0"+ },+ "bin": {+ "prebuild-install": "bin.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/process-warning": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz",+ "integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "MIT"+ },+ "node_modules/pump": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",+ "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",+ "license": "MIT",+ "dependencies": {+ "end-of-stream": "^1.1.0",+ "once": "^1.3.1"+ }+ },+ "node_modules/quick-format-unescaped": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",+ "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==",+ "license": "MIT"+ },+ "node_modules/rc": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",+ "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",+ "license": "(BSD-2-Clause OR MIT OR Apache-2.0)",+ "dependencies": {+ "deep-extend": "^0.6.0",+ "ini": "~1.3.0",+ "minimist": "^1.2.0",+ "strip-json-comments": "~2.0.1"+ },+ "bin": {+ "rc": "cli.js"+ }+ },+ "node_modules/readable-stream": {+ "version": "3.6.2",+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",+ "license": "MIT",+ "dependencies": {+ "inherits": "^2.0.3",+ "string_decoder": "^1.1.1",+ "util-deprecate": "^1.0.1"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/real-require": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",+ "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==",+ "license": "MIT",+ "engines": {+ "node": ">= 12.13.0"+ }+ },+ "node_modules/rollup": {+ "version": "4.62.2",+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz",+ "integrity": "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/estree": "1.0.9"+ },+ "bin": {+ "rollup": "dist/bin/rollup"+ },+ "engines": {+ "node": ">=18.0.0",+ "npm": ">=8.0.0"+ },+ "optionalDependencies": {+ "@rollup/rollup-android-arm-eabi": "4.62.2",+ "@rollup/rollup-android-arm64": "4.62.2",+ "@rollup/rollup-darwin-arm64": "4.62.2",+ "@rollup/rollup-darwin-x64": "4.62.2",+ "@rollup/rollup-freebsd-arm64": "4.62.2",+ "@rollup/rollup-freebsd-x64": "4.62.2",+ "@rollup/rollup-linux-arm-gnueabihf": "4.62.2",+ "@rollup/rollup-linux-arm-musleabihf": "4.62.2",+ "@rollup/rollup-linux-arm64-gnu": "4.62.2",+ "@rollup/rollup-linux-arm64-musl": "4.62.2",+ "@rollup/rollup-linux-loong64-gnu": "4.62.2",+ "@rollup/rollup-linux-loong64-musl": "4.62.2",+ "@rollup/rollup-linux-ppc64-gnu": "4.62.2",+ "@rollup/rollup-linux-ppc64-musl": "4.62.2",+ "@rollup/rollup-linux-riscv64-gnu": "4.62.2",+ "@rollup/rollup-linux-riscv64-musl": "4.62.2",+ "@rollup/rollup-linux-s390x-gnu": "4.62.2",+ "@rollup/rollup-linux-x64-gnu": "4.62.2",+ "@rollup/rollup-linux-x64-musl": "4.62.2",+ "@rollup/rollup-openbsd-x64": "4.62.2",+ "@rollup/rollup-openharmony-arm64": "4.62.2",+ "@rollup/rollup-win32-arm64-msvc": "4.62.2",+ "@rollup/rollup-win32-ia32-msvc": "4.62.2",+ "@rollup/rollup-win32-x64-gnu": "4.62.2",+ "@rollup/rollup-win32-x64-msvc": "4.62.2",+ "fsevents": "~2.3.2"+ }+ },+ "node_modules/safe-buffer": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/safe-stable-stringify": {+ "version": "2.5.0",+ "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",+ "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/siginfo": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/simple-concat": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",+ "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/simple-get": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",+ "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "decompress-response": "^6.0.0",+ "once": "^1.3.1",+ "simple-concat": "^1.0.0"+ }+ },+ "node_modules/sonic-boom": {+ "version": "4.2.1",+ "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz",+ "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==",+ "license": "MIT",+ "dependencies": {+ "atomic-sleep": "^1.0.0"+ }+ },+ "node_modules/source-map-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/split2": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",+ "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",+ "license": "ISC",+ "engines": {+ "node": ">= 10.x"+ }+ },+ "node_modules/stackback": {+ "version": "0.0.2",+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/std-env": {+ "version": "3.10.0",+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",+ "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/string_decoder": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",+ "license": "MIT",+ "dependencies": {+ "safe-buffer": "~5.2.0"+ }+ },+ "node_modules/strip-json-comments": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",+ "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/strip-literal": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz",+ "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "js-tokens": "^9.0.1"+ },+ "funding": {+ "url": "https://github.com/sponsors/antfu"+ }+ },+ "node_modules/tar-fs": {+ "version": "2.1.5",+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz",+ "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==",+ "license": "MIT",+ "dependencies": {+ "chownr": "^1.1.1",+ "mkdirp-classic": "^0.5.2",+ "pump": "^3.0.0",+ "tar-stream": "^2.1.4"+ }+ },+ "node_modules/tar-stream": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",+ "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",+ "license": "MIT",+ "dependencies": {+ "bl": "^4.0.3",+ "end-of-stream": "^1.4.1",+ "fs-constants": "^1.0.0",+ "inherits": "^2.0.3",+ "readable-stream": "^3.1.1"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/thread-stream": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz",+ "integrity": "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==",+ "license": "MIT",+ "dependencies": {+ "real-require": "^1.0.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/thread-stream/node_modules/real-require": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz",+ "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==",+ "license": "MIT"+ },+ "node_modules/tinybench": {+ "version": "2.9.0",+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tinyexec": {+ "version": "0.3.2",+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",+ "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tinyglobby": {+ "version": "0.2.17",+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fdir": "^6.5.0",+ "picomatch": "^4.0.4"+ },+ "engines": {+ "node": ">=12.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/SuperchupuDev"+ }+ },+ "node_modules/tinypool": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",+ "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.0.0 || >=20.0.0"+ }+ },+ "node_modules/tinyrainbow": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz",+ "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/tinyspy": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz",+ "integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/tr46": {+ "version": "0.0.3",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",+ "license": "MIT"+ },+ "node_modules/ts-mixer": {+ "version": "6.0.4",+ "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",+ "integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==",+ "license": "MIT"+ },+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "license": "0BSD"+ },+ "node_modules/tsx": {+ "version": "4.23.1",+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.1.tgz",+ "integrity": "sha512-GQHnkIfxyx1wYCOS/wonik5MVRZU9hi1TEZmzGZSCJB1y9YgoZ8H6itNE/u4suE+yLmOzuE4E5S4TZ/ZX2wcWQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "esbuild": "~0.28.0"+ },+ "bin": {+ "tsx": "dist/cli.mjs"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ }+ },+ "node_modules/tunnel-agent": {+ "version": "0.6.0",+ "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",+ "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",+ "license": "Apache-2.0",+ "dependencies": {+ "safe-buffer": "^5.0.1"+ },+ "engines": {+ "node": "*"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "devOptional": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici": {+ "version": "6.27.0",+ "resolved": "https://registry.npmjs.org/undici/-/undici-6.27.0.tgz",+ "integrity": "sha512-YmfV3YnEDzXRC5lZ2jWtWWHKGUm1zIt8AhesR1tens+HTNv+YZlN/dp6G727LOvMJ8xjP9Be7Y2Sdr96LDm+pg==",+ "license": "MIT",+ "engines": {+ "node": ">=18.17"+ }+ },+ "node_modules/undici-types": {+ "version": "7.18.2",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",+ "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",+ "license": "MIT"+ },+ "node_modules/util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",+ "license": "MIT"+ },+ "node_modules/viem": {+ "version": "2.55.1",+ "resolved": "https://registry.npmjs.org/viem/-/viem-2.55.1.tgz",+ "integrity": "sha512-sajvEmONS3dEDFh0jKXGugTU8ImyGoIV3sEHSWNRhgkH484v/+6DjZAplRhcdeqNV/VBxOs/l3raOG4NaXvX9A==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/wevm"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@noble/curves": "1.9.1",+ "@noble/hashes": "1.8.0",+ "@scure/bip32": "1.7.0",+ "@scure/bip39": "1.6.0",+ "abitype": "1.2.3",+ "isows": "1.0.7",+ "ox": "0.14.30",+ "ws": "8.21.0"+ },+ "peerDependencies": {+ "typescript": ">=5.0.4"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ }+ },+ "node_modules/viem/node_modules/ws": {+ "version": "8.21.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "node_modules/vite": {+ "version": "7.3.6",+ "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz",+ "integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "esbuild": "^0.27.0 || ^0.28.0",+ "fdir": "^6.5.0",+ "picomatch": "^4.0.3",+ "postcss": "^8.5.6",+ "rollup": "^4.43.0",+ "tinyglobby": "^0.2.15"+ },+ "bin": {+ "vite": "bin/vite.js"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "funding": {+ "url": "https://github.com/vitejs/vite?sponsor=1"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ },+ "peerDependencies": {+ "@types/node": "^20.19.0 || >=22.12.0",+ "jiti": ">=1.21.0",+ "less": "^4.0.0",+ "lightningcss": "^1.21.0",+ "sass": "^1.70.0",+ "sass-embedded": "^1.70.0",+ "stylus": ">=0.54.8",+ "sugarss": "^5.0.0",+ "terser": "^5.16.0",+ "tsx": "^4.8.1",+ "yaml": "^2.4.2"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ },+ "jiti": {+ "optional": true+ },+ "less": {+ "optional": true+ },+ "lightningcss": {+ "optional": true+ },+ "sass": {+ "optional": true+ },+ "sass-embedded": {+ "optional": true+ },+ "stylus": {+ "optional": true+ },+ "sugarss": {+ "optional": true+ },+ "terser": {+ "optional": true+ },+ "tsx": {+ "optional": true+ },+ "yaml": {+ "optional": true+ }+ }+ },+ "node_modules/vite-node": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz",+ "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "cac": "^6.7.14",+ "debug": "^4.4.1",+ "es-module-lexer": "^1.7.0",+ "pathe": "^2.0.3",+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"+ },+ "bin": {+ "vite-node": "vite-node.mjs"+ },+ "engines": {+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/vitest": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz",+ "integrity": "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/chai": "^5.2.2",+ "@vitest/expect": "3.2.7",+ "@vitest/mocker": "3.2.7",+ "@vitest/pretty-format": "^3.2.7",+ "@vitest/runner": "3.2.7",+ "@vitest/snapshot": "3.2.7",+ "@vitest/spy": "3.2.7",+ "@vitest/utils": "3.2.7",+ "chai": "^5.2.0",+ "debug": "^4.4.1",+ "expect-type": "^1.2.1",+ "magic-string": "^0.30.17",+ "pathe": "^2.0.3",+ "picomatch": "^4.0.2",+ "std-env": "^3.9.0",+ "tinybench": "^2.9.0",+ "tinyexec": "^0.3.2",+ "tinyglobby": "^0.2.14",+ "tinypool": "^1.1.1",+ "tinyrainbow": "^2.0.0",+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0",+ "vite-node": "3.2.4",+ "why-is-node-running": "^2.3.0"+ },+ "bin": {+ "vitest": "vitest.mjs"+ },+ "engines": {+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "@edge-runtime/vm": "*",+ "@types/debug": "^4.1.12",+ "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",+ "@vitest/browser": "3.2.7",+ "@vitest/ui": "3.2.7",+ "happy-dom": "*",+ "jsdom": "*"+ },+ "peerDependenciesMeta": {+ "@edge-runtime/vm": {+ "optional": true+ },+ "@types/debug": {+ "optional": true+ },+ "@types/node": {+ "optional": true+ },+ "@vitest/browser": {+ "optional": true+ },+ "@vitest/ui": {+ "optional": true+ },+ "happy-dom": {+ "optional": true+ },+ "jsdom": {+ "optional": true+ }+ }+ },+ "node_modules/webidl-conversions": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",+ "license": "BSD-2-Clause"+ },+ "node_modules/whatwg-url": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",+ "license": "MIT",+ "dependencies": {+ "tr46": "~0.0.3",+ "webidl-conversions": "^3.0.0"+ }+ },+ "node_modules/why-is-node-running": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "siginfo": "^2.0.0",+ "stackback": "0.0.2"+ },+ "bin": {+ "why-is-node-running": "cli.js"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "license": "ISC"+ },+ "node_modules/ws": {+ "version": "8.21.1",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.1.tgz",+ "integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ }+ }+}diff --git a/robinhood/hood-alerts/package.json b/robinhood/hood-alerts/package.jsonnew file mode 100644index 000000000..5f8df8566--- /dev/null+++ b/robinhood/hood-alerts/package.json@@ -0,0 +1,82 @@+{+ "name": "hood-alerts",+ "version": "0.1.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",+ "robinhood-chain",+ "alerts",+ "telegram-bot",+ "discord-bot",+ "memecoin",+ "stock-tokens",+ "x402",+ "usdg",+ "whale-alerts"+ ],+ "license": "SEE LICENSE IN LICENSE",+ "author": "nirholas (https://x.com/nichxbt)",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/hood-alerts.git"+ },+ "homepage": "https://nirholas.github.io/hood-alerts/",+ "bugs": {+ "url": "https://github.com/nirholas/hood-alerts/issues"+ },+ "type": "module",+ "engines": {+ "node": ">=20"+ },+ "sideEffects": false,+ "main": "./dist/src/index.js",+ "types": "./dist/src/index.d.ts",+ "bin": {+ "hood-alerts": "./dist/src/index.js"+ },+ "exports": {+ ".": {+ "types": "./dist/src/index.d.ts",+ "import": "./dist/src/index.js"+ },+ "./package.json": "./package.json"+ },+ "files": [+ "dist",+ "README.md",+ "LICENSE",+ ".env.example",+ "Dockerfile"+ ],+ "scripts": {+ "dev": "tsx watch src/index.ts",+ "start": "node dist/src/index.js",+ "build": "tsc -p tsconfig.json",+ "typecheck": "tsc --noEmit",+ "test": "vitest run tests --exclude 'tests/live/**'",+ "test:live": "vitest run tests/live --testTimeout 180000",+ "capture-fixtures": "tsx scripts/capture-fixtures.ts",+ "probe": "tsx scripts/live-probe.ts",+ "grant-premium": "tsx scripts/grant-premium.ts",+ "prepublishOnly": "npm run build"+ },+ "dependencies": {+ "@hono/node-server": "^1.14.0",+ "better-sqlite3": "^12.11.0",+ "discord.js": "^14.27.0",+ "grammy": "^1.44.0",+ "hono": "^4.12.0",+ "hood402": "file:../hood402",+ "hoodchain": "file:../robinhood-chain-sdk",+ "hoodkit": "file:../hoodkit",+ "pino": "^10.3.0",+ "viem": "2.55.1"+ },+ "devDependencies": {+ "@types/better-sqlite3": "^7.6.13",+ "@types/node": "^24.0.0",+ "tsx": "^4.20.0",+ "typescript": "^5.9.0",+ "vitest": "^3.2.0"+ }+}diff --git a/robinhood/hood-alerts/scripts/capture-fixtures.ts b/robinhood/hood-alerts/scripts/capture-fixtures.tsnew file mode 100644index 000000000..d80d173c1--- /dev/null+++ b/robinhood/hood-alerts/scripts/capture-fixtures.ts@@ -0,0 +1,154 @@+#!/usr/bin/env tsx+/**+ * Capture real Robinhood Chain (mainnet 4663) event streams into+ * tests/fixtures/*.json so the detector unit tests run against genuine+ * on-chain data, not invented samples. Re-run to refresh:+ *+ * npm run capture-fixtures+ *+ * Everything read here is public and read-only. bigints serialize as strings+ * (see the `replacer`); the tests re-hydrate them.+ */+import { mkdirSync, writeFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'+import {+ ODYSSEY_ADDRESSES,+ createHoodClient,+ listPricedStockTokens,+ odysseyTradedEvent,+ watchCurveTrades,+ MAINNET_ADDRESSES,+ type CurveTrade,+} from 'hoodchain'+import { discoverPools, streamPrices, streamSwaps, type PoolInfo, type PriceTick, type SwapEvent } from 'hoodkit'+import type { Address } from 'viem'++const FIXTURES = join(dirname(fileURLToPath(import.meta.url)), '..', 'tests', 'fixtures')++const replacer = (_key: string, value: unknown): unknown => (typeof value === 'bigint' ? value.toString() : value)++function writeFixture(name: string, data: unknown): void {+ mkdirSync(FIXTURES, { recursive: true })+ writeFileSync(join(FIXTURES, name), `${JSON.stringify(data, replacer, 2)}\n`)+ console.log(`wrote tests/fixtures/${name}`)+}++async function ethUsdFromBlockscout(): Promise<number | null> {+ try {+ const res = await fetch('https://robinhoodchain.blockscout.com/api/v2/stats', { headers: { accept: 'application/json' } })+ if (!res.ok) return null+ const body = (await res.json()) as { coin_price?: string | null }+ const p = body.coin_price ? Number(body.coin_price) : NaN+ return Number.isFinite(p) && p > 0 ? p : null+ } catch {+ return null+ }+}++async function captureSwaps(client: ReturnType<typeof createHoodClient>): Promise<void> {+ const bn = await client.public.getBlockNumber()+ const stocks = listPricedStockTokens()+ const collected: Array<{ poolInfo: PoolInfo; symbol: string; token: Address; swaps: SwapEvent[] }> = []+ let total = 0+ for (const stock of stocks) {+ if (total >= 12) break+ const pools = await discoverPools(client, stock.address).catch(() => [] as PoolInfo[])+ if (pools.length === 0) continue+ const stream = await streamSwaps(client, { token: stock.address }, { fromBlock: bn - 300_000n, chunkSize: 10_000n })+ const swaps: SwapEvent[] = []+ stream.on('data', (s) => swaps.push(s))+ await new Promise((r) => setTimeout(r, 9000))+ stream.close()+ if (swaps.length > 0) {+ const info = pools.find((p) => swaps.some((s) => s.pool.toLowerCase() === p.pool.toLowerCase())) ?? pools[0]+ collected.push({ poolInfo: info as PoolInfo, symbol: stock.symbol, token: stock.address, swaps: swaps.slice(-8) })+ total += swaps.length+ console.log(` ${stock.symbol}: ${swaps.length} swaps captured`)+ }+ }+ const ethUsd = await ethUsdFromBlockscout()+ writeFixture('swaps.json', {+ capturedAt: new Date().toISOString(),+ chainId: 4663,+ blockNumber: bn.toString(),+ weth: MAINNET_ADDRESSES.weth,+ usdg: MAINNET_ADDRESSES.usdg,+ ethUsd,+ pools: collected,+ })+}++async function capturePrices(client: ReturnType<typeof createHoodClient>): Promise<void> {+ const stocks = listPricedStockTokens()+ const symbols = stocks.map((s) => s.symbol)+ const stream = streamPrices(client, symbols)+ const ticks = new Map<string, PriceTick>()+ stream.on('data', (t) => ticks.set(t.symbol, t))+ await new Promise((r) => setTimeout(r, 8000))+ stream.close()+ const snapshot = [...ticks.values()].map((t) => ({ symbol: t.symbol, priceUsd: t.priceUsd, feed: t.feed, roundId: t.roundId.toString(), updatedAt: t.updatedAt }))+ writeFixture('prices.json', { capturedAt: new Date().toISOString(), chainId: 4663, count: snapshot.length, prices: snapshot })+}++async function captureCurveTrades(client: ReturnType<typeof createHoodClient>): Promise<void> {+ const bn = await client.public.getBlockNumber()+ const factories = [ODYSSEY_ADDRESSES.bondingCurveFactory, ODYSSEY_ADDRESSES.reflectionFactory, ODYSSEY_ADDRESSES.legacyFactory]+ const trades: CurveTrade[] = []+ // Historical scan of the Odyssey `Traded` event across recent chunks.+ const span = 400_000n+ const chunk = 20_000n+ for (let from = bn - span; from <= bn && trades.length < 8; from += chunk) {+ const to = from + chunk - 1n > bn ? bn : from + chunk - 1n+ for (const factory of factories) {+ const logs = await client.public+ .getLogs({ address: factory, event: odysseyTradedEvent, fromBlock: from, toBlock: to })+ .catch(() => [])+ for (const log of logs) {+ const a = log.args as { token?: Address; trader?: Address; isBuy?: boolean; tokenAmount?: bigint; ethAmount?: bigint; fee?: bigint }+ if (!a.token || !a.trader || a.tokenAmount === undefined) continue+ trades.push({+ launchpad: 'odyssey',+ token: a.token,+ trader: a.trader,+ isBuy: Boolean(a.isBuy),+ tokenAmount: a.tokenAmount,+ quoteAmount: a.ethAmount ?? 0n,+ fee: a.fee ?? 0n,+ blockNumber: log.blockNumber,+ transactionHash: log.transactionHash,+ })+ if (trades.length >= 8) break+ }+ }+ }+ // If the historical scan came up empty, listen live for a short window.+ if (trades.length === 0) {+ const stop = watchCurveTrades(client, (t) => trades.push(t))+ await new Promise((r) => setTimeout(r, 12_000))+ stop()+ }+ const ethUsd = await ethUsdFromBlockscout()+ writeFixture('curve-trades.json', {+ capturedAt: new Date().toISOString(),+ chainId: 4663,+ ethUsd,+ note: trades.length === 0 ? 'No Odyssey bonding-curve trades in the captured window; launchpad was idle.' : undefined,+ trades,+ })+}++async function main(): Promise<void> {+ const client = createHoodClient({})+ console.log('capturing real mainnet 4663 fixtures...')+ await capturePrices(client)+ await captureSwaps(client)+ await captureCurveTrades(client)+ console.log('done')+ process.exit(0)+}++main().catch((error) => {+ console.error('capture failed:', error)+ process.exit(1)+})diff --git a/robinhood/hood-alerts/src/commands/commands.ts b/robinhood/hood-alerts/src/commands/commands.tsnew file mode 100644index 000000000..9f88ccdce--- /dev/null+++ b/robinhood/hood-alerts/src/commands/commands.ts@@ -0,0 +1,275 @@+import type { Config } from '../config.js'+import type { EntitlementRepo } from '../db/entitlements.js'+import type { Platform, SubscriberRepo } from '../db/subscribers.js'+import { defaultThreshold, parseTopic, PREMIUM_TOPICS, resolveWatchTarget } from '../engine/topics.js'++/** Free tier allows this many concurrent subscriptions. */+export const FREE_MAX_SUBSCRIPTIONS = 3++/** Who is issuing the command, resolved by the transport. */+export interface CommandContext {+ platform: Platform+ chatId: string+ chatTitle?: string+ /** Group chats restrict config commands to admins. */+ isGroup: boolean+ isAdmin: boolean+}++/** Platform-neutral reply; transports handle their own markup/escaping. */+export interface CommandReply {+ text: string+}++export interface CommandDeps {+ subscribers: SubscriberRepo+ entitlements: EntitlementRepo+ config: Config+ /** Called after any change to token: watches (detector lifecycle sync). */+ notifyWatchChange: () => void+}++const HELP = `hood-alerts: real-time Robinhood Chain alerts.++watch <what> [threshold]+ launches every new token (add noxa/odyssey to filter)+ graduations Odyssey curves migrating to Uniswap v3+ whales [usd] trades >= usd, chain-wide (default 5000)+ premiums [pct] Stock Token DEX premium/discount vs Chainlink (premium tier)+ rugs [pct] liquidity-pull rug warnings (premium tier)+ <TICKER> a Stock Token: price moves + premium crossings (e.g. TSLA)+ <0x address> a memecoin: whale trades, graduation, holders, liquidity++unwatch <what|all> stop watching+list your subscriptions+threshold <what> <n> change a subscription's threshold+digest on|off [min] batch alerts into digests (default 60 min)+quiet <from> <to> quiet hours in UTC (e.g. quiet 22 7); quiet off+premium premium status + how to upgrade+help this message++Free tier: ${FREE_MAX_SUBSCRIPTIONS} subscriptions, alerts batched to 60s.+Premium: unlimited, real-time, plus the premiums + rugs detectors.`++function requireAdmin(ctx: CommandContext): CommandReply | null {+ if (ctx.isGroup && !ctx.isAdmin) {+ return { text: 'Only group admins can change alert settings here.' }+ }+ return null+}++function describeTopic(topic: string, threshold: number | null): string {+ const parsed = parseTopic(topic)+ if (!parsed) return topic+ switch (parsed.kind) {+ case 'launches':+ return parsed.launchpad ? `launches (${parsed.launchpad})` : 'launches (all launchpads)'+ case 'graduations':+ return 'graduations'+ case 'whales':+ return `whales >= $${(threshold ?? 0).toLocaleString('en-US')}`+ case 'premiums':+ return `stock premium/discount >= ${threshold ?? 0}%`+ case 'rugs':+ return `liquidity pulls >= ${threshold ?? 0}%`+ case 'token':+ return `token ${parsed.address.slice(0, 6)}…${parsed.address.slice(-4)} (whales >= $${(threshold ?? 0).toLocaleString('en-US')}, graduation, holders, liquidity)`+ case 'stock':+ return `${parsed.symbol} (moves/premium >= ${threshold ?? 0}%)`+ }+}++/**+ * The shared command router. Both bots parse their native command format into+ * (command, args) and call this; replies render per platform. Keeping it pure+ * and platform-free is what makes the whole UX unit-testable offline.+ */+export class Commands {+ constructor(private readonly deps: CommandDeps) {}++ handle(ctx: CommandContext, command: string, args: string[]): CommandReply {+ switch (command) {+ case 'start':+ return {+ text:+ 'This bot alerts on Robinhood Chain activity: launches, graduations, whale trades, ' ++ 'Stock Token price moves, on-chain premium/discount arbitrage, holder milestones, and ' ++ 'liquidity pulls.\n\nYou watch nothing yet. Try: watch launches\nFull reference: help',+ }+ case 'help':+ return { text: HELP }+ case 'watch':+ return requireAdmin(ctx) ?? this.watch(ctx, args)+ case 'unwatch':+ return requireAdmin(ctx) ?? this.unwatch(ctx, args)+ case 'list':+ return this.list(ctx)+ case 'threshold':+ return requireAdmin(ctx) ?? this.threshold(ctx, args)+ case 'digest':+ return requireAdmin(ctx) ?? this.digest(ctx, args)+ case 'quiet':+ return requireAdmin(ctx) ?? this.quiet(ctx, args)+ case 'premium':+ return this.premium(ctx)+ default:+ return { text: `Unknown command "${command}". Try: help` }+ }+ }++ private watch(ctx: CommandContext, args: string[]): CommandReply {+ if (args.length === 0) {+ return { text: 'What should I watch? Examples:\nwatch launches\nwatch whales 10000\nwatch TSLA\nwatch 0x… (a token address)\nSee: help' }+ }+ const first = args[0] as string+ const second = args[1]+ // "watch launches noxa" sugar+ const target = (first.toLowerCase() === 'launches' && (second === 'noxa' || second === 'odyssey'))+ ? `launches:${second}`+ : first+ const resolved = resolveWatchTarget(target)+ if (!resolved.ok) return { text: resolved.error }+ const topic = resolved.topic+ const parsed = parseTopic(topic)+ if (!parsed) return { text: `Cannot watch "${first}".` }++ const premium = this.deps.entitlements.isPremium(ctx.platform, ctx.chatId)+ if (PREMIUM_TOPICS.has(topic) && !premium) {+ return {+ text:+ `"${topic}" is a premium detector (the ${topic === 'premiums' ? 'Stock Token arbitrage signal' : 'rug early-warning'}). ` ++ 'Upgrade with: premium',+ }+ }+ const subscriber = this.deps.subscribers.ensure(ctx.platform, ctx.chatId, ctx.chatTitle)+ if (!premium && this.deps.subscribers.count(subscriber.id) >= FREE_MAX_SUBSCRIPTIONS) {+ return {+ text:+ `Free tier is capped at ${FREE_MAX_SUBSCRIPTIONS} subscriptions. ` ++ 'Unwatch something (unwatch <what>) or go unlimited with: premium',+ }+ }++ const d = this.deps.config.detectors+ const thresholdArg = Number(target === first ? second : args[2])+ const threshold = Number.isFinite(thresholdArg) && thresholdArg > 0+ ? thresholdArg+ : defaultThreshold(parsed, {+ whaleUsd: d.whaleDefaultUsd,+ premiumPct: d.premiumDefaultPct,+ rugPct: d.rugDefaultPct,+ pricePct: d.priceDefaultPct,+ })+ this.deps.subscribers.subscribe(subscriber.id, topic, threshold)+ if (parsed.kind === 'token') this.deps.notifyWatchChange()+ return { text: `Watching ${describeTopic(topic, threshold)}.` }+ }++ private unwatch(ctx: CommandContext, args: string[]): CommandReply {+ const subscriber = this.deps.subscribers.get(ctx.platform, ctx.chatId)+ if (!subscriber || this.deps.subscribers.count(subscriber.id) === 0) {+ return { text: 'You watch nothing yet. Try: watch launches' }+ }+ if (args.length === 0) return { text: 'Unwatch what? Use: unwatch <what> or unwatch all (see list)' }+ if ((args[0] as string).toLowerCase() === 'all') {+ const n = this.deps.subscribers.unsubscribeAll(subscriber.id)+ this.deps.notifyWatchChange()+ return { text: `Removed ${n} subscription${n === 1 ? '' : 's'}.` }+ }+ const resolved = resolveWatchTarget(args[0] as string)+ if (!resolved.ok) return { text: resolved.error }+ const removed = this.deps.subscribers.unsubscribe(subscriber.id, resolved.topic)+ if (!removed) return { text: `You were not watching ${args[0]}. See: list` }+ if (parseTopic(resolved.topic)?.kind === 'token') this.deps.notifyWatchChange()+ return { text: `Stopped watching ${describeTopic(resolved.topic, null)}.` }+ }++ private list(ctx: CommandContext): CommandReply {+ const subscriber = this.deps.subscribers.get(ctx.platform, ctx.chatId)+ const subs = subscriber ? this.deps.subscribers.list(subscriber.id) : []+ if (subs.length === 0) {+ return { text: 'You watch nothing yet. Try: watch launches\nOr: watch whales 10000, watch TSLA' }+ }+ const premium = this.deps.entitlements.isPremium(ctx.platform, ctx.chatId)+ const lines = subs.map((s, i) => `${i + 1}. ${describeTopic(s.topic, s.threshold)}`)+ const s = subscriber as NonNullable<typeof subscriber>+ const settings = [+ premium ? 'tier: premium' : `tier: free (${subs.length}/${FREE_MAX_SUBSCRIPTIONS})`,+ s.digest ? `digest: every ${Math.round(s.digestIntervalS / 60)}m` : 'digest: off',+ s.quietStart !== null && s.quietEnd !== null ? `quiet: ${s.quietStart}:00-${s.quietEnd}:00 UTC` : 'quiet: off',+ ]+ return { text: `Watching:\n${lines.join('\n')}\n\n${settings.join(' · ')}` }+ }++ private threshold(ctx: CommandContext, args: string[]): CommandReply {+ if (args.length < 2) return { text: 'Usage: threshold <what> <value>. Example: threshold whales 25000' }+ const subscriber = this.deps.subscribers.get(ctx.platform, ctx.chatId)+ if (!subscriber) return { text: 'You watch nothing yet. Try: watch launches' }+ const resolved = resolveWatchTarget(args[0] as string)+ if (!resolved.ok) return { text: resolved.error }+ const value = Number(args[1])+ if (!Number.isFinite(value) || value <= 0) return { text: `"${args[1]}" is not a positive number.` }+ const ok = this.deps.subscribers.setThreshold(subscriber.id, resolved.topic, value)+ if (!ok) return { text: `You are not watching ${args[0]}. Watch it first: watch ${args[0]} ${value}` }+ return { text: `Updated: ${describeTopic(resolved.topic, value)}.` }+ }++ private digest(ctx: CommandContext, args: string[]): CommandReply {+ const mode = (args[0] ?? '').toLowerCase()+ if (mode !== 'on' && mode !== 'off') return { text: 'Usage: digest on [minutes] or digest off' }+ const subscriber = this.deps.subscribers.ensure(ctx.platform, ctx.chatId, ctx.chatTitle)+ if (mode === 'off') {+ this.deps.subscribers.setDigest(subscriber.id, false)+ return { text: 'Digest off: alerts deliver as they happen (60s batching on the free tier).' }+ }+ const minutes = Number(args[1] ?? 60)+ if (!Number.isFinite(minutes) || minutes < 1 || minutes > 24 * 60) {+ return { text: 'Digest interval must be 1-1440 minutes.' }+ }+ this.deps.subscribers.setDigest(subscriber.id, true, Math.round(minutes) * 60)+ return { text: `Digest on: alerts batch every ${Math.round(minutes)} minutes.` }+ }++ private quiet(ctx: CommandContext, args: string[]): CommandReply {+ const subscriber = this.deps.subscribers.ensure(ctx.platform, ctx.chatId, ctx.chatTitle)+ if ((args[0] ?? '').toLowerCase() === 'off') {+ this.deps.subscribers.setQuietHours(subscriber.id, null, null)+ return { text: 'Quiet hours off.' }+ }+ const start = Number(args[0])+ const end = Number(args[1])+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || start > 23 || end < 0 || end > 23) {+ return { text: 'Usage: quiet <from> <to> in UTC hours 0-23 (e.g. quiet 22 7), or quiet off' }+ }+ this.deps.subscribers.setQuietHours(subscriber.id, start, end)+ return { text: `Quiet hours set: ${start}:00-${end}:00 UTC. Alerts batch and deliver after.` }+ }++ private premium(ctx: CommandContext): CommandReply {+ const { config } = this.deps+ const remaining = this.deps.entitlements.remainingS(ctx.platform, ctx.chatId)+ const status =+ remaining > 0+ ? `Premium active: ${Math.ceil(remaining / 86_400)} day${remaining > 86_400 ? 's' : ''} left.`+ : 'You are on the free tier.'+ const purchasable = config.payTo !== null && (config.facilitatorUrl !== null || config.settlerKey !== null)+ if (!purchasable) {+ return {+ text:+ `${status}\n\nPremium purchases are not configured on this instance. ` ++ 'Self-hosters: set HOOD402_PAY_TO plus a facilitator or settler key (see the self-host guide).',+ }+ }+ const url = `${config.publicUrl}/premium/activate?platform=${ctx.platform}&chat=${encodeURIComponent(ctx.chatId)}`+ return {+ text:+ `${status}\n\nPremium: unlimited subscriptions, real-time delivery, plus the Stock Token ` ++ `arbitrage (premiums) and rug early-warning (rugs) detectors.\n` ++ `Price: ${config.premiumPriceUsdg} USDG for ${config.premiumDays} days, paid on Robinhood Chain via x402.\n\n` ++ `Pay with any x402 client (hood402, x402-fetch):\nPOST ${url}\n` ++ `The endpoint answers 402 with payment instructions; your client signs a USDG ` ++ `transferWithAuthorization and premium activates the moment it settles.\n` ++ `Guide: https://nirholas.github.io/hood-alerts/premium.html`,+ }+ }+}diff --git a/robinhood/hood-alerts/src/config.ts b/robinhood/hood-alerts/src/config.tsnew file mode 100644index 000000000..c0d91697f--- /dev/null+++ b/robinhood/hood-alerts/src/config.ts@@ -0,0 +1,108 @@+import type { Address } from 'viem'++/** Runtime configuration, resolved once from the environment at startup. */+export interface Config {+ /** Custom RPC URL, or undefined for viem's public default. */+ rpcUrl: string | undefined+ /** SQLite database file path. */+ dbPath: string+ /** HTTP port for /healthz + premium endpoints. */+ port: number+ /** Public base URL of this instance (payment challenges, bot replies). */+ publicUrl: string+ /** Telegram bot token, or null to disable the transport. */+ telegramToken: string | null+ /** Discord bot token + application id, or null to disable the transport. */+ discordToken: string | null+ discordAppId: string | null+ /** Premium rail. Only `hood402` is implemented end-to-end. */+ premiumRail: 'hood402'+ /** Receiving address for premium payments (null = purchases disabled). */+ payTo: Address | null+ /** hood402 facilitator base URL (settlement mode A). */+ facilitatorUrl: string | null+ /** Gas key for self-settlement (settlement mode B). */+ settlerKey: `0x${string}` | null+ /** Premium price in USDG (human string) and entitlement duration in days. */+ premiumPriceUsdg: string+ premiumDays: number+ detectors: DetectorConfig+}++/** Tunable detector thresholds. */+export interface DetectorConfig {+ /** Engine-side floor for whale trade emission (USD). */+ whaleFloorUsd: number+ /** Default per-subscription whale threshold (USD). */+ whaleDefaultUsd: number+ /** Rolling window for price-move detection (seconds). */+ priceWindowS: number+ /** Default price-move threshold (percent). */+ priceDefaultPct: number+ /** Stock premium/discount poll interval (seconds). */+ premiumPollS: number+ /** Default premium/discount threshold (percent). */+ premiumDefaultPct: number+ /** Default liquidity-pull threshold (percent of quote reserves). */+ rugDefaultPct: number+}++function num(name: string, fallback: number): number {+ const raw = process.env[name]+ if (raw === undefined || raw === '') return fallback+ const value = Number(raw)+ if (!Number.isFinite(value) || value <= 0) {+ throw new Error(`${name} must be a positive number, got "${raw}"`)+ }+ return value+}++function str(name: string): string | null {+ const raw = process.env[name]+ return raw === undefined || raw.trim() === '' ? null : raw.trim()+}++/** Load and validate configuration from the environment. */+export function loadConfig(): Config {+ const rail = str('HOOD_ALERTS_PREMIUM_RAIL') ?? 'hood402'+ if (rail !== 'hood402') {+ throw new Error(+ `HOOD_ALERTS_PREMIUM_RAIL="${rail}" is not implemented. Only "hood402" (USDG on ` ++ 'Robinhood Chain) settles end-to-end in this build; see README "Premium rails" ' ++ 'for wiring an x402 USDC facilitator instead.',+ )+ }+ const payToRaw = str('HOOD402_PAY_TO')+ if (payToRaw && !/^0x[0-9a-fA-F]{40}$/.test(payToRaw)) {+ throw new Error(`HOOD402_PAY_TO must be a 0x address, got "${payToRaw}"`)+ }+ const settlerRaw = str('HOOD402_SETTLER_KEY')+ 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 port = Math.floor(num('PORT', 8080))+ return {+ rpcUrl: str('HOOD_ALERTS_RPC_URL') ?? undefined,+ dbPath: str('HOOD_ALERTS_DB') ?? './data/hood-alerts.db',+ port,+ publicUrl: str('HOOD_ALERTS_PUBLIC_URL') ?? `http://localhost:${port}`,+ telegramToken: str('HOOD_ALERTS_TELEGRAM_TOKEN'),+ discordToken: str('HOOD_ALERTS_DISCORD_TOKEN'),+ discordAppId: str('HOOD_ALERTS_DISCORD_APP_ID'),+ premiumRail: 'hood402',+ payTo: (payToRaw as Address | null) ?? null,+ facilitatorUrl: str('HOOD402_FACILITATOR_URL'),+ settlerKey: (settlerRaw as `0x${string}` | null) ?? null,+ premiumPriceUsdg: String(num('HOOD_ALERTS_PREMIUM_PRICE_USDG', 5)),+ premiumDays: num('HOOD_ALERTS_PREMIUM_DAYS', 30),+ detectors: {+ whaleFloorUsd: num('HOOD_ALERTS_WHALE_FLOOR_USD', 1000),+ whaleDefaultUsd: num('HOOD_ALERTS_WHALE_DEFAULT_USD', 5000),+ priceWindowS: num('HOOD_ALERTS_PRICE_WINDOW_S', 900),+ priceDefaultPct: num('HOOD_ALERTS_PRICE_DEFAULT_PCT', 2),+ premiumPollS: num('HOOD_ALERTS_PREMIUM_POLL_S', 60),+ premiumDefaultPct: num('HOOD_ALERTS_PREMIUM_DEFAULT_PCT', 2),+ rugDefaultPct: num('HOOD_ALERTS_RUG_DEFAULT_PCT', 30),+ },+ }+}diff --git a/robinhood/hood-alerts/src/db/deliveries.ts b/robinhood/hood-alerts/src/db/deliveries.tsnew file mode 100644index 000000000..65001890e--- /dev/null+++ b/robinhood/hood-alerts/src/db/deliveries.ts@@ -0,0 +1,44 @@+import type { Db } from './index.js'++/** Delivery log + persisted dedup state. */+export class DeliveryRepo {+ constructor(+ private readonly db: Db,+ private readonly now: () => number = () => Math.floor(Date.now() / 1000),+ ) {}++ /**+ * Atomically claim a fingerprint. Returns true the FIRST time a fingerprint+ * is seen inside its TTL; false for duplicates. Expired rows are reclaimed.+ */+ claimFingerprint(fingerprint: string, ttlS: number): boolean {+ const now = this.now()+ this.db.prepare('DELETE FROM dedup WHERE expires_at <= ?').run(now)+ const res = this.db+ .prepare('INSERT OR IGNORE INTO dedup (fingerprint, first_seen, expires_at) VALUES (?, ?, ?)')+ .run(fingerprint, now, now + ttlS)+ return res.changes > 0+ }++ logDelivery(subscriberId: number, fingerprint: string, status: 'sent' | 'failed' | 'digested', detail?: string): void {+ this.db+ .prepare('INSERT INTO deliveries (subscriber_id, fingerprint, delivered_at, status, detail) VALUES (?, ?, ?, ?, ?)')+ .run(subscriberId, fingerprint, this.now(), status, detail ?? null)+ }++ /** Deliveries in the trailing `windowS` seconds for one subscriber. */+ recentCount(subscriberId: number, windowS: number): number {+ const row = this.db+ .prepare('SELECT COUNT(*) AS n FROM deliveries WHERE subscriber_id = ? AND delivered_at > ? AND status = ?')+ .get(subscriberId, this.now() - windowS, 'sent') as { n: number }+ return row.n+ }++ /** Unix seconds of the most recent successful delivery, or null. */+ lastDeliveredAt(subscriberId: number): number | null {+ const row = this.db+ .prepare('SELECT MAX(delivered_at) AS t FROM deliveries WHERE subscriber_id = ? AND status = ?')+ .get(subscriberId, 'sent') as { t: number | null }+ return row.t+ }+}diff --git a/robinhood/hood-alerts/src/db/entitlements.ts b/robinhood/hood-alerts/src/db/entitlements.tsnew file mode 100644index 000000000..6f618ca91--- /dev/null+++ b/robinhood/hood-alerts/src/db/entitlements.ts@@ -0,0 +1,107 @@+import type { Db } from './index.js'+import type { Platform } from './subscribers.js'++/** An active or expired premium entitlement. */+export interface Entitlement {+ platform: Platform+ chatId: string+ tier: 'premium'+ activatedAt: number+ expiresAt: number+ paymentTx: string | null+ payer: string | null+}++interface Row {+ platform: Platform+ chat_id: string+ tier: 'premium'+ activated_at: number+ expires_at: number+ payment_tx: string | null+ payer: string | null+}++function toEntitlement(r: Row): Entitlement {+ return {+ platform: r.platform,+ chatId: r.chat_id,+ tier: r.tier,+ activatedAt: r.activated_at,+ expiresAt: r.expires_at,+ paymentTx: r.payment_tx,+ payer: r.payer,+ }+}++/**+ * The premium entitlement state machine. States, per (platform, chat):+ *+ * free ──activate(payment)──> active(expires_at)+ * active ──activate(payment)──> active(expires_at + duration) [extension]+ * active ──clock passes expires_at──> expired (== free)+ * any ──revoke──> free+ *+ * Expiry is evaluated lazily against the clock; there is no cron.+ */+export class EntitlementRepo {+ constructor(+ private readonly db: Db,+ private readonly now: () => number = () => Math.floor(Date.now() / 1000),+ ) {}++ /** Activate or extend premium. Extensions stack on the remaining time. */+ activate(+ platform: Platform,+ chatId: string,+ durationS: number,+ payment?: { tx?: string; payer?: string },+ ): Entitlement {+ const now = this.now()+ const current = this.getRaw(platform, chatId)+ const base = current && current.expires_at > now ? current.expires_at : now+ const expiresAt = base + durationS+ this.db+ .prepare(+ 'INSERT INTO entitlements (platform, chat_id, tier, activated_at, expires_at, payment_tx, payer) ' ++ "VALUES (?, ?, 'premium', ?, ?, ?, ?) " ++ 'ON CONFLICT (platform, chat_id) DO UPDATE SET ' ++ 'activated_at = excluded.activated_at, expires_at = excluded.expires_at, ' ++ 'payment_tx = COALESCE(excluded.payment_tx, entitlements.payment_tx), ' ++ 'payer = COALESCE(excluded.payer, entitlements.payer)',+ )+ .run(platform, chatId, now, expiresAt, payment?.tx ?? null, payment?.payer ?? null)+ return this.get(platform, chatId) as Entitlement+ }++ /** Drop back to free immediately. */+ revoke(platform: Platform, chatId: string): boolean {+ return this.db.prepare('DELETE FROM entitlements WHERE platform = ? AND chat_id = ?').run(platform, chatId).changes > 0+ }++ private getRaw(platform: Platform, chatId: string): Row | null {+ const row = this.db+ .prepare('SELECT * FROM entitlements WHERE platform = ? AND chat_id = ?')+ .get(platform, chatId) as Row | undefined+ return row ?? null+ }++ /** The stored entitlement, expired or not. Null when never purchased. */+ get(platform: Platform, chatId: string): Entitlement | null {+ const row = this.getRaw(platform, chatId)+ return row ? toEntitlement(row) : null+ }++ /** True while the entitlement clock has not run out. */+ isPremium(platform: Platform, chatId: string): boolean {+ const row = this.getRaw(platform, chatId)+ return row !== null && row.expires_at > this.now()+ }++ /** Seconds of premium remaining (0 when free/expired). */+ remainingS(platform: Platform, chatId: string): number {+ const row = this.getRaw(platform, chatId)+ if (!row) return 0+ return Math.max(0, row.expires_at - this.now())+ }+}diff --git a/robinhood/hood-alerts/src/db/index.ts b/robinhood/hood-alerts/src/db/index.tsnew file mode 100644index 000000000..8e112bfe4--- /dev/null+++ b/robinhood/hood-alerts/src/db/index.ts@@ -0,0 +1,65 @@+import Database from 'better-sqlite3'+import { mkdirSync } from 'node:fs'+import { dirname } from 'node:path'++export type Db = Database.Database++const SCHEMA = `+CREATE TABLE IF NOT EXISTS subscribers (+ id INTEGER PRIMARY KEY,+ platform TEXT NOT NULL CHECK (platform IN ('telegram', 'discord', 'console')),+ chat_id TEXT NOT NULL,+ title TEXT,+ digest INTEGER NOT NULL DEFAULT 0,+ digest_interval_s INTEGER NOT NULL DEFAULT 3600,+ quiet_start INTEGER,+ quiet_end INTEGER,+ created_at INTEGER NOT NULL,+ UNIQUE (platform, chat_id)+);+CREATE TABLE IF NOT EXISTS subscriptions (+ id INTEGER PRIMARY KEY,+ subscriber_id INTEGER NOT NULL REFERENCES subscribers(id) ON DELETE CASCADE,+ topic TEXT NOT NULL,+ threshold REAL,+ created_at INTEGER NOT NULL,+ UNIQUE (subscriber_id, topic)+);+CREATE INDEX IF NOT EXISTS idx_subscriptions_topic ON subscriptions(topic);+CREATE TABLE IF NOT EXISTS entitlements (+ id INTEGER PRIMARY KEY,+ platform TEXT NOT NULL,+ chat_id TEXT NOT NULL,+ tier TEXT NOT NULL DEFAULT 'premium',+ activated_at INTEGER NOT NULL,+ expires_at INTEGER NOT NULL,+ payment_tx TEXT,+ payer TEXT,+ UNIQUE (platform, chat_id)+);+CREATE TABLE IF NOT EXISTS dedup (+ fingerprint TEXT PRIMARY KEY,+ first_seen INTEGER NOT NULL,+ expires_at INTEGER NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_dedup_expires ON dedup(expires_at);+CREATE TABLE IF NOT EXISTS deliveries (+ id INTEGER PRIMARY KEY,+ subscriber_id INTEGER NOT NULL,+ fingerprint TEXT NOT NULL,+ delivered_at INTEGER NOT NULL,+ status TEXT NOT NULL,+ detail TEXT+);+CREATE INDEX IF NOT EXISTS idx_deliveries_subscriber ON deliveries(subscriber_id, delivered_at);+`++/** Open (and migrate) the SQLite database. `:memory:` works for tests. */+export function openDb(path: string): Db {+ if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true })+ const db = new Database(path)+ db.pragma('journal_mode = WAL')+ db.pragma('foreign_keys = ON')+ db.exec(SCHEMA)+ return db+}diff --git a/robinhood/hood-alerts/src/db/subscribers.ts b/robinhood/hood-alerts/src/db/subscribers.tsnew file mode 100644index 000000000..063838ee3--- /dev/null+++ b/robinhood/hood-alerts/src/db/subscribers.ts@@ -0,0 +1,184 @@+import type { Db } from './index.js'++export type Platform = 'telegram' | 'discord' | 'console'++export interface Subscriber {+ id: number+ platform: Platform+ chatId: string+ title: string | null+ digest: boolean+ digestIntervalS: number+ quietStart: number | null+ quietEnd: number | null+ createdAt: number+}++export interface Subscription {+ id: number+ subscriberId: number+ topic: string+ threshold: number | null+ createdAt: number+}++interface SubscriberRow {+ id: number+ platform: Platform+ chat_id: string+ title: string | null+ digest: number+ digest_interval_s: number+ quiet_start: number | null+ quiet_end: number | null+ created_at: number+}++interface SubscriptionRow {+ id: number+ subscriber_id: number+ topic: string+ threshold: number | null+ created_at: number+}++function toSubscriber(r: SubscriberRow): Subscriber {+ return {+ id: r.id,+ platform: r.platform,+ chatId: r.chat_id,+ title: r.title,+ digest: r.digest === 1,+ digestIntervalS: r.digest_interval_s,+ quietStart: r.quiet_start,+ quietEnd: r.quiet_end,+ createdAt: r.created_at,+ }+}++function toSubscription(r: SubscriptionRow): Subscription {+ return {+ id: r.id,+ subscriberId: r.subscriber_id,+ topic: r.topic,+ threshold: r.threshold,+ createdAt: r.created_at,+ }+}++/** Subscriptions + subscriber settings repository. */+export class SubscriberRepo {+ constructor(private readonly db: Db) {}++ /** Find or create the subscriber for a chat. */+ ensure(platform: Platform, chatId: string, title?: string): Subscriber {+ const now = Math.floor(Date.now() / 1000)+ this.db+ .prepare(+ 'INSERT INTO subscribers (platform, chat_id, title, created_at) VALUES (?, ?, ?, ?) ' ++ 'ON CONFLICT (platform, chat_id) DO UPDATE SET title = COALESCE(excluded.title, subscribers.title)',+ )+ .run(platform, chatId, title ?? null, now)+ const row = this.db+ .prepare('SELECT * FROM subscribers WHERE platform = ? AND chat_id = ?')+ .get(platform, chatId) as SubscriberRow+ return toSubscriber(row)+ }++ get(platform: Platform, chatId: string): Subscriber | null {+ const row = this.db+ .prepare('SELECT * FROM subscribers WHERE platform = ? AND chat_id = ?')+ .get(platform, chatId) as SubscriberRow | undefined+ return row ? toSubscriber(row) : null+ }++ byId(id: number): Subscriber | null {+ const row = this.db.prepare('SELECT * FROM subscribers WHERE id = ?').get(id) as SubscriberRow | undefined+ return row ? toSubscriber(row) : null+ }++ setDigest(subscriberId: number, on: boolean, intervalS?: number): void {+ if (intervalS !== undefined) {+ this.db+ .prepare('UPDATE subscribers SET digest = ?, digest_interval_s = ? WHERE id = ?')+ .run(on ? 1 : 0, intervalS, subscriberId)+ } else {+ this.db.prepare('UPDATE subscribers SET digest = ? WHERE id = ?').run(on ? 1 : 0, subscriberId)+ }+ }++ setQuietHours(subscriberId: number, start: number | null, end: number | null): void {+ this.db.prepare('UPDATE subscribers SET quiet_start = ?, quiet_end = ? WHERE id = ?').run(start, end, subscriberId)+ }++ subscribe(subscriberId: number, topic: string, threshold: number | null): Subscription {+ const now = Math.floor(Date.now() / 1000)+ this.db+ .prepare(+ 'INSERT INTO subscriptions (subscriber_id, topic, threshold, created_at) VALUES (?, ?, ?, ?) ' ++ 'ON CONFLICT (subscriber_id, topic) DO UPDATE SET threshold = excluded.threshold',+ )+ .run(subscriberId, topic, threshold, now)+ const row = this.db+ .prepare('SELECT * FROM subscriptions WHERE subscriber_id = ? AND topic = ?')+ .get(subscriberId, topic) as SubscriptionRow+ return toSubscription(row)+ }++ unsubscribe(subscriberId: number, topic: string): boolean {+ const res = this.db.prepare('DELETE FROM subscriptions WHERE subscriber_id = ? AND topic = ?').run(subscriberId, topic)+ return res.changes > 0+ }++ unsubscribeAll(subscriberId: number): number {+ return this.db.prepare('DELETE FROM subscriptions WHERE subscriber_id = ?').run(subscriberId).changes+ }++ setThreshold(subscriberId: number, topic: string, threshold: number): boolean {+ const res = this.db+ .prepare('UPDATE subscriptions SET threshold = ? WHERE subscriber_id = ? AND topic = ?')+ .run(threshold, subscriberId, topic)+ return res.changes > 0+ }++ list(subscriberId: number): Subscription[] {+ const rows = this.db+ .prepare('SELECT * FROM subscriptions WHERE subscriber_id = ? ORDER BY created_at')+ .all(subscriberId) as SubscriptionRow[]+ return rows.map(toSubscription)+ }++ count(subscriberId: number): number {+ const row = this.db+ .prepare('SELECT COUNT(*) AS n FROM subscriptions WHERE subscriber_id = ?')+ .get(subscriberId) as { n: number }+ return row.n+ }++ /** Every subscription, joined with its subscriber, for engine routing. */+ allWithSubscribers(): Array<{ subscription: Subscription; subscriber: Subscriber }> {+ const rows = this.db+ .prepare(+ 'SELECT s.id AS sub_id, s.subscriber_id, s.topic, s.threshold, s.created_at AS sub_created, ' ++ 'u.id, u.platform, u.chat_id, u.title, u.digest, u.digest_interval_s, u.quiet_start, u.quiet_end, u.created_at ' ++ 'FROM subscriptions s JOIN subscribers u ON u.id = s.subscriber_id',+ )+ .all() as Array<SubscriberRow & { sub_id: number; subscriber_id: number; topic: string; threshold: number | null; sub_created: number }>+ return rows.map((r) => ({+ subscription: {+ id: r.sub_id,+ subscriberId: r.subscriber_id,+ topic: r.topic,+ threshold: r.threshold,+ createdAt: r.sub_created,+ },+ subscriber: toSubscriber(r),+ }))+ }++ /** Distinct topics with at least one subscription (drives detector lifecycles). */+ activeTopics(): string[] {+ const rows = this.db.prepare('SELECT DISTINCT topic FROM subscriptions').all() as Array<{ topic: string }>+ return rows.map((r) => r.topic)+ }+}diff --git a/robinhood/hood-alerts/src/engine/detectors/holders.ts b/robinhood/hood-alerts/src/engine/detectors/holders.tsnew file mode 100644index 000000000..286b8e48a--- /dev/null+++ b/robinhood/hood-alerts/src/engine/detectors/holders.ts@@ -0,0 +1,35 @@+import type { Address } from 'viem'+import type { HolderMilestoneEvent } from '../events.js'++/** Milestones a token's holder count can cross (ascending). */+export const HOLDER_MILESTONES = [10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10_000, 25_000, 50_000, 100_000] as const++/**+ * Holder-count milestone detector. Feed it periodic counts (Blockscout+ * `token_holders_count`); it emits the highest newly-crossed milestone.+ * The first observation seeds the baseline without alerting, so subscribing+ * to an established token does not replay its whole history.+ */+export class HolderMilestones {+ private readonly lastCount = new Map<string, number>()++ update(token: Address, count: number, atS: number): HolderMilestoneEvent | null {+ if (!Number.isFinite(count) || count < 0) return null+ const key = token.toLowerCase()+ const previous = this.lastCount.get(key)+ this.lastCount.set(key, count)+ if (previous === undefined) return null++ let crossed: number | null = null+ for (const m of HOLDER_MILESTONES) {+ if (previous < m && count >= m) crossed = m+ }+ if (crossed === null) return null+ return { type: 'holders', token, symbol: null, milestone: crossed, count, at: atS }+ }++ /** Forget a token (unwatched). */+ forget(token: Address): void {+ this.lastCount.delete(token.toLowerCase())+ }+}diff --git a/robinhood/hood-alerts/src/engine/detectors/liquidity.ts b/robinhood/hood-alerts/src/engine/detectors/liquidity.tsnew file mode 100644index 000000000..b8655b098--- /dev/null+++ b/robinhood/hood-alerts/src/engine/detectors/liquidity.ts@@ -0,0 +1,73 @@+import type { Address } from 'viem'+import type { LiquidityPullEvent } from '../events.js'++interface PoolState {+ token: Address | null+ quoteAsset: 'USDG' | 'WETH'+ /** Trailing samples of the pool's quote-side reserves in USD. */+ samples: Array<{ at: number; usd: number }>+}++/**+ * Rug early-warning: watches the quote-token reserves (USDG or WETH, valued in+ * USD) of tracked pools. A drop of `minEmitPct` percent from the trailing-window+ * maximum emits a {@link LiquidityPullEvent}; the baseline then resets to the+ * post-drop level so one pull alerts once. Balance polling catches every exit+ * path (burn + collect, direct transfers) without decoding position NFTs.+ */+export class LiquidityMonitor {+ private readonly pools = new Map<string, PoolState>()++ constructor(+ private readonly windowS: number,+ private readonly minEmitPct: number,+ /** Ignore pools below this many quote-USD (dust pools "rug" on noise). */+ private readonly minPoolUsd = 500,+ ) {}++ track(pool: Address, token: Address | null, quoteAsset: 'USDG' | 'WETH'): void {+ const key = pool.toLowerCase()+ if (!this.pools.has(key)) this.pools.set(key, { token, quoteAsset, samples: [] })+ }++ untrack(pool: Address): void {+ this.pools.delete(pool.toLowerCase())+ }++ tracked(): Address[] {+ return [...this.pools.keys()] as Address[]+ }++ quoteAssetOf(pool: Address): 'USDG' | 'WETH' | null {+ return this.pools.get(pool.toLowerCase())?.quoteAsset ?? null+ }++ update(pool: Address, quoteUsd: number, atS: number): LiquidityPullEvent | null {+ const state = this.pools.get(pool.toLowerCase())+ if (!state || !Number.isFinite(quoteUsd) || quoteUsd < 0) return null++ const cutoff = atS - this.windowS+ state.samples = state.samples.filter((s) => s.at >= cutoff)++ const peak = state.samples.reduce((max, s) => Math.max(max, s.usd), 0)+ state.samples.push({ at: atS, usd: quoteUsd })++ if (peak < this.minPoolUsd) return null+ const droppedPct = ((peak - quoteUsd) / peak) * 100+ if (droppedPct < this.minEmitPct) return null++ // Reset the baseline so the same pull does not re-alert every poll.+ state.samples = [{ at: atS, usd: quoteUsd }]+ return {+ type: 'liquidity_pull',+ token: state.token,+ symbol: null,+ pool,+ quoteAsset: state.quoteAsset,+ droppedPct,+ beforeUsd: peak,+ afterUsd: quoteUsd,+ at: atS,+ }+ }+}diff --git a/robinhood/hood-alerts/src/engine/detectors/live.ts b/robinhood/hood-alerts/src/engine/detectors/live.tsnew file mode 100644index 000000000..e88ec6be0--- /dev/null+++ b/robinhood/hood-alerts/src/engine/detectors/live.ts@@ -0,0 +1,436 @@+import {+ MAINNET_ADDRESSES,+ MAINNET_EXPLORER_URL,+ erc20Abi,+ listPricedStockTokens,+ uniswapV3PoolAbi,+ watchCurveTrades,+ watchGraduations,+ type HoodClient,+} from 'hoodchain'+import { discoverPools, sqrtPriceX96ToPrice, streamLaunches, streamPrices, streamSwaps, type PoolInfo, type Stream, type SwapEvent } from 'hoodkit'+import type { Address } from 'viem'+import { logger } from '../../logger.js'+import type { DetectorConfig } from '../../config.js'+import type { AlertEvent } from '../events.js'+import { EthPrice } from '../eth-price.js'+import { TokenMetaCache } from '../token-meta.js'+import { HolderMilestones } from './holders.js'+import { LiquidityMonitor } from './liquidity.js'+import { PremiumLadder } from './premium-ladder.js'+import { PriceMoveTracker } from './prices.js'+import { classifyCurveTrade, classifySwap } from './whale-classify.js'++const nowS = (): number => Math.floor(Date.now() / 1000)++interface StockPool {+ symbol: string+ token: Address+ pool: Address+ stockIs0: boolean+ decimals0: number+ decimals1: number+ quoteAsset: 'USDG' | 'WETH'+}++/**+ * The live detector set: every stream and poller that turns raw Robinhood+ * Chain state into {@link AlertEvent}s. One instance feeds the whole engine;+ * subscriber fan-out happens downstream.+ */+export class LiveDetectors {+ readonly ethPrice: EthPrice+ readonly meta: TokenMetaCache+ private readonly priceTracker: PriceMoveTracker+ private readonly premiumLadder = new PremiumLadder()+ private readonly holderMilestones = new HolderMilestones()+ private readonly liquidity: LiquidityMonitor++ private stops: Array<() => void> = []+ private timers: Array<ReturnType<typeof setInterval>> = []+ private swapStreams = new Map<string, Stream<SwapEvent>>()+ private watchedTokens = new Set<string>()+ /** Auto-tracked pools (from launches/graduations) expire; watched pools do not. */+ private poolExpiry = new Map<string, number | null>()+ private stockPools: StockPool[] = []+ private lastFeedUsd = new Map<string, number>()+ private running = false+ /** Diagnostics for /healthz. */+ lastEventAt: number | null = null+ eventCounts: Record<string, number> = {}++ constructor(+ private readonly client: HoodClient,+ private readonly cfg: DetectorConfig,+ private readonly emit: (event: AlertEvent) => void,+ ) {+ this.ethPrice = new EthPrice(client)+ this.meta = new TokenMetaCache(client)+ this.priceTracker = new PriceMoveTracker(cfg.priceWindowS, 1)+ this.liquidity = new LiquidityMonitor(1800, Math.min(cfg.rugDefaultPct, 20))+ }++ private push(event: AlertEvent): void {+ this.lastEventAt = nowS()+ this.eventCounts[event.type] = (this.eventCounts[event.type] ?? 0) + 1+ this.emit(event)+ }++ async start(): Promise<void> {+ if (this.running) return+ this.running = true+ this.startLaunches()+ this.startGraduations()+ this.startCurveWhales()+ this.startPrices()+ await this.refreshStockPools().catch((error) => logger.warn({ err: String(error) }, 'initial stock pool discovery failed'))+ this.timers.push(setInterval(() => void this.refreshStockPools().catch(() => undefined), 3_600_000))+ this.timers.push(setInterval(() => void this.pollPremiums().catch((e) => logger.warn({ err: String(e) }, 'premium poll failed')), this.cfg.premiumPollS * 1000))+ this.timers.push(setInterval(() => void this.pollLiquidity().catch((e) => logger.warn({ err: String(e) }, 'liquidity poll failed')), 60_000))+ this.timers.push(setInterval(() => void this.pollHolders().catch((e) => logger.warn({ err: String(e) }, 'holder poll failed')), 120_000))+ logger.info('live detectors started')+ }++ stop(): void {+ this.running = false+ for (const stop of this.stops) stop()+ this.stops = []+ for (const t of this.timers) clearInterval(t)+ this.timers = []+ for (const s of this.swapStreams.values()) s.close()+ this.swapStreams.clear()+ logger.info('live detectors stopped')+ }++ // ---- launches -----------------------------------------------------------++ private startLaunches(): void {+ const stream = streamLaunches(this.client)+ stream.on('data', (launch) => {+ void (async () => {+ const meta = await this.meta.get(launch.token)+ this.push({+ type: 'launch',+ launchpad: launch.launchpad,+ token: launch.token,+ symbol: meta.symbol,+ name: meta.name,+ creator: launch.creator,+ pool: launch.pool,+ blockNumber: launch.blockNumber,+ transactionHash: launch.transactionHash,+ at: nowS(),+ })+ // NOXA lists instantly on a v3 pool: rug-watch it for 24h.+ if (launch.pool) await this.autoTrackPool(launch.pool, launch.token)+ })().catch((error) => logger.warn({ err: String(error) }, 'launch handling failed'))+ })+ stream.on('error', (error) => logger.warn({ err: String(error) }, 'launch stream error (auto-retrying)'))+ this.stops.push(() => stream.close())+ }++ // ---- graduations --------------------------------------------------------++ private startGraduations(): void {+ const unwatch = watchGraduations(this.client, (g) => {+ void (async () => {+ const meta = await this.meta.get(g.token)+ this.push({+ type: 'graduation',+ token: g.token,+ symbol: meta.symbol,+ name: meta.name,+ pool: g.pool,+ blockNumber: g.blockNumber,+ transactionHash: g.transactionHash,+ at: nowS(),+ })+ await this.autoTrackPool(g.pool, g.token)+ })().catch((error) => logger.warn({ err: String(error) }, 'graduation handling failed'))+ }, { onError: (error) => logger.warn({ err: String(error) }, 'graduation watcher error (auto-retrying)') })+ this.stops.push(unwatch)+ }++ // ---- whales: Odyssey curve (chain-wide) ---------------------------------++ private startCurveWhales(): void {+ const unwatch = watchCurveTrades(this.client, (trade) => {+ void (async () => {+ const eth = await this.ethPrice.get()+ if (eth === null) return+ const event = classifyCurveTrade(trade, eth, this.cfg.whaleFloorUsd, nowS())+ if (!event) return+ const meta = await this.meta.get(event.token)+ this.push({ ...event, symbol: meta.symbol })+ })().catch((error) => logger.warn({ err: String(error) }, 'curve trade handling failed'))+ }, { onError: (error) => logger.warn({ err: String(error) }, 'curve trade watcher error (auto-retrying)') })+ this.stops.push(unwatch)+ }++ // ---- whales: Uniswap v3 (per watched token) -----------------------------++ /** Reconcile per-token swap streams + holder/liquidity tracking with the watch list. */+ async syncWatchedTokens(tokens: Address[]): Promise<void> {+ const next = new Set(tokens.map((t) => t.toLowerCase()))+ for (const existing of [...this.swapStreams.keys()]) {+ if (!next.has(existing)) {+ this.swapStreams.get(existing)?.close()+ this.swapStreams.delete(existing)+ this.watchedTokens.delete(existing)+ this.holderMilestones.forget(existing as Address)+ }+ }+ for (const token of next) {+ if (this.swapStreams.has(token)) continue+ this.watchedTokens.add(token)+ try {+ const pools = await discoverPools(this.client, token as Address)+ for (const info of pools) {+ const quote = this.quoteAssetOf(info)+ if (quote) {+ this.liquidity.track(info.pool, token as Address, quote)+ this.poolExpiry.set(info.pool.toLowerCase(), null)+ }+ }+ if (pools.length === 0) continue+ const stream = await streamSwaps(this.client, { token: token as Address })+ stream.on('data', (swap) => {+ void this.handleWatchedSwap(swap, pools).catch((error) =>+ logger.warn({ err: String(error) }, 'watched swap handling failed'),+ )+ })+ stream.on('error', (error) => logger.warn({ err: String(error), token }, 'swap stream error (auto-retrying)'))+ this.swapStreams.set(token, stream)+ } catch (error) {+ logger.warn({ err: String(error), token }, 'failed to start swap stream for watched token')+ }+ }+ }++ private async handleWatchedSwap(swap: SwapEvent, pools: PoolInfo[]): Promise<void> {+ const info = pools.find((p) => p.pool.toLowerCase() === swap.pool.toLowerCase())+ if (!info) return+ const eth = (await this.ethPrice.get()) ?? 0+ const event = classifySwap(+ swap,+ info,+ { weth: MAINNET_ADDRESSES.weth, usdg: MAINNET_ADDRESSES.usdg },+ eth,+ this.cfg.whaleFloorUsd,+ nowS(),+ )+ if (!event) return+ const meta = await this.meta.get(event.token)+ this.push({ ...event, symbol: meta.symbol })+ }++ private quoteAssetOf(info: PoolInfo): 'USDG' | 'WETH' | null {+ const weth = MAINNET_ADDRESSES.weth.toLowerCase()+ const usdg = MAINNET_ADDRESSES.usdg.toLowerCase()+ if (info.token0.toLowerCase() === usdg || info.token1.toLowerCase() === usdg) return 'USDG'+ if (info.token0.toLowerCase() === weth || info.token1.toLowerCase() === weth) return 'WETH'+ return null+ }++ // ---- Stock Token prices (Chainlink) -------------------------------------++ private startPrices(): void {+ const stream = streamPrices(this.client)+ stream.on('data', (tick) => {+ this.lastFeedUsd.set(tick.symbol, tick.priceUsd)+ const event = this.priceTracker.update(tick.symbol, tick.priceUsd, nowS())+ if (event) this.push(event)+ })+ stream.on('error', (error) => logger.warn({ err: String(error) }, 'price stream error (auto-retrying)'))+ this.stops.push(() => stream.close())+ }++ // ---- Stock Token premium/discount (the arb signal) ----------------------++ /** Discover the deepest USDG/WETH pool per priced Stock Token (hourly). */+ private async refreshStockPools(): Promise<void> {+ const stocks = listPricedStockTokens()+ const found: StockPool[] = []+ const concurrency = 5+ for (let i = 0; i < stocks.length; i += concurrency) {+ const batch = stocks.slice(i, i + concurrency)+ const results = await Promise.all(+ batch.map(async (stock) => {+ try {+ const pools = await discoverPools(this.client, stock.address)+ const candidates = pools+ .map((p) => ({ info: p, quote: this.quoteAssetOf(p) }))+ .filter((c): c is { info: PoolInfo; quote: 'USDG' | 'WETH' } => c.quote !== null)+ if (candidates.length === 0) return null+ // Deepest = largest quote reserves.+ const balances = await this.client.public.multicall({+ contracts: candidates.map((c) => ({+ address: (c.quote === 'USDG' ? MAINNET_ADDRESSES.usdg : MAINNET_ADDRESSES.weth) as Address,+ abi: erc20Abi,+ functionName: 'balanceOf' as const,+ args: [c.info.pool] as const,+ })),+ allowFailure: true,+ })+ let best: { c: (typeof candidates)[number]; scaled: number } | null = null+ const eth = (await this.ethPrice.get()) ?? 0+ candidates.forEach((c, j) => {+ const res = balances[j]+ if (!res || res.status !== 'success') return+ const decimals = c.quote === 'USDG' ? 6 : 18+ const human = Number(res.result as bigint) / 10 ** decimals+ const usd = c.quote === 'USDG' ? human : human * eth+ if (!best || usd > best.scaled) best = { c, scaled: usd }+ })+ if (!best) return null+ const chosen = best as { c: { info: PoolInfo; quote: 'USDG' | 'WETH' }; scaled: number }+ if (chosen.scaled < 100) return null // ignore dust pools: no real arb signal+ const { info, quote } = chosen.c+ return {+ symbol: stock.symbol,+ token: stock.address,+ pool: info.pool,+ stockIs0: info.token0.toLowerCase() === stock.address.toLowerCase(),+ decimals0: info.decimals0,+ decimals1: info.decimals1,+ quoteAsset: quote,+ } satisfies StockPool+ } catch {+ return null+ }+ }),+ )+ for (const r of results) if (r) found.push(r)+ }+ this.stockPools = found+ logger.info({ pools: found.length }, 'stock premium pools discovered')+ }++ private async pollPremiums(): Promise<void> {+ if (this.stockPools.length === 0) return+ const slots = await this.client.public.multicall({+ contracts: this.stockPools.map((p) => ({+ address: p.pool,+ abi: uniswapV3PoolAbi,+ functionName: 'slot0' as const,+ })),+ allowFailure: true,+ })+ const eth = await this.ethPrice.get()+ const at = nowS()+ slots.forEach((res, i) => {+ const p = this.stockPools[i]+ if (!p || res.status !== 'success') return+ const [sqrtPriceX96] = res.result as readonly [bigint, number, number, number, number, number, boolean]+ const spot0In1 = sqrtPriceX96ToPrice(sqrtPriceX96, p.decimals0, p.decimals1)+ if (spot0In1 <= 0) return+ const stockInQuote = p.stockIs0 ? spot0In1 : 1 / spot0In1+ const dexUsd = p.quoteAsset === 'USDG' ? stockInQuote : eth !== null ? stockInQuote * eth : null+ const feedUsd = this.lastFeedUsd.get(p.symbol)+ if (dexUsd === null || feedUsd === undefined) return+ const event = this.premiumLadder.update(p.symbol, p.token, p.pool, dexUsd, feedUsd, at)+ if (event) this.push(event)+ })+ }++ // ---- liquidity pulls ----------------------------------------------------++ private async autoTrackPool(pool: Address, token: Address): Promise<void> {+ try {+ const [token0, token1] = await this.client.public.multicall({+ contracts: [+ { address: pool, abi: poolTokensAbi, functionName: 'token0' },+ { address: pool, abi: poolTokensAbi, functionName: 'token1' },+ ],+ allowFailure: false,+ })+ const weth = MAINNET_ADDRESSES.weth.toLowerCase()+ const usdg = MAINNET_ADDRESSES.usdg.toLowerCase()+ let quote: 'USDG' | 'WETH' | null = null+ if (token0.toLowerCase() === usdg || token1.toLowerCase() === usdg) quote = 'USDG'+ else if (token0.toLowerCase() === weth || token1.toLowerCase() === weth) quote = 'WETH'+ if (!quote) return+ this.liquidity.track(pool, token, quote)+ if (this.poolExpiry.get(pool.toLowerCase()) !== null) {+ this.poolExpiry.set(pool.toLowerCase(), nowS() + 24 * 3600)+ }+ } catch (error) {+ logger.warn({ err: String(error), pool }, 'auto-track pool failed')+ }+ }++ private async pollLiquidity(): Promise<void> {+ const at = nowS()+ // Prune expired auto-tracked pools.+ for (const [pool, expiry] of this.poolExpiry) {+ if (expiry !== null && expiry <= at) {+ this.liquidity.untrack(pool as Address)+ this.poolExpiry.delete(pool)+ }+ }+ const pools = this.liquidity.tracked()+ if (pools.length === 0) return+ const eth = await this.ethPrice.get()+ const reads = pools.map((pool) => {+ const quote = this.liquidity.quoteAssetOf(pool) as 'USDG' | 'WETH'+ return {+ pool,+ quote,+ contract: {+ address: (quote === 'USDG' ? MAINNET_ADDRESSES.usdg : MAINNET_ADDRESSES.weth) as Address,+ abi: erc20Abi,+ functionName: 'balanceOf' as const,+ args: [pool] as const,+ },+ }+ })+ const balances = await this.client.public.multicall({+ contracts: reads.map((r) => r.contract),+ allowFailure: true,+ })+ for (let i = 0; i < reads.length; i++) {+ const read = reads[i]+ const res = balances[i]+ if (!read || !res || res.status !== 'success') continue+ const decimals = read.quote === 'USDG' ? 6 : 18+ const human = Number(res.result as bigint) / 10 ** decimals+ const usd = read.quote === 'USDG' ? human : eth !== null ? human * eth : null+ if (usd === null) continue+ const event = this.liquidity.update(read.pool, usd, at)+ if (event) {+ const meta = event.token ? await this.meta.get(event.token) : { symbol: null, name: null }+ this.push({ ...event, symbol: meta.symbol })+ }+ }+ }++ // ---- holder milestones (Blockscout counters) ----------------------------++ private async pollHolders(): Promise<void> {+ const at = nowS()+ for (const token of this.watchedTokens) {+ try {+ const res = await fetch(`${MAINNET_EXPLORER_URL}/api/v2/tokens/${token}/counters`, {+ signal: AbortSignal.timeout(10_000),+ headers: { accept: 'application/json' },+ })+ if (!res.ok) continue+ const body = (await res.json()) as { token_holders_count?: string }+ const count = Number(body.token_holders_count ?? NaN)+ if (!Number.isFinite(count)) continue+ const event = this.holderMilestones.update(token as Address, count, at)+ if (event) {+ const meta = await this.meta.get(event.token)+ this.push({ ...event, symbol: meta.symbol })+ }+ } catch {+ // transient explorer failures are fine; next poll retries+ }+ }+ }+}++const poolTokensAbi = [+ { type: 'function', name: 'token0', stateMutability: 'view', inputs: [], outputs: [{ type: 'address' }] },+ { type: 'function', name: 'token1', stateMutability: 'view', inputs: [], outputs: [{ type: 'address' }] },+] as constdiff --git a/robinhood/hood-alerts/src/engine/detectors/premium-ladder.ts b/robinhood/hood-alerts/src/engine/detectors/premium-ladder.tsnew file mode 100644index 000000000..f8a73440c--- /dev/null+++ b/robinhood/hood-alerts/src/engine/detectors/premium-ladder.ts@@ -0,0 +1,65 @@+import type { Address } from 'viem'+import type { PremiumEvent } from '../events.js'++/** Rungs (absolute percent) at which premium/discount crossings emit. */+export const PREMIUM_LADDER = [1, 2, 3, 5, 10, 20, 50] as const++interface ArmState {+ /** Highest rung currently alerted, per direction. Re-arms when premium falls below it. */+ premium: number+ discount: number+}++/**+ * Ladder-crossing detector for the Stock Token arb signal. Each update+ * compares the DEX mid to the Chainlink feed; when |premium| crosses a rung+ * upward it emits once and stays silent until the value falls back below that+ * rung (hysteresis), so a premium oscillating around a threshold does not spam.+ */+export class PremiumLadder {+ private readonly armed = new Map<string, ArmState>()++ update(symbol: string, token: Address, pool: Address, dexUsd: number, feedUsd: number, atS: number): PremiumEvent | null {+ if (!Number.isFinite(dexUsd) || !Number.isFinite(feedUsd) || dexUsd <= 0 || feedUsd <= 0) return null+ const premiumPct = ((dexUsd - feedUsd) / feedUsd) * 100+ const direction: 'premium' | 'discount' = premiumPct >= 0 ? 'premium' : 'discount'+ const abs = Math.abs(premiumPct)++ const state = this.armed.get(symbol) ?? { premium: 0, discount: 0 }++ // Re-arm rungs the value has fallen below, both directions.+ if (abs < state.premium && direction === 'premium') state.premium = highestRungBelow(abs)+ if (abs < state.discount && direction === 'discount') state.discount = highestRungBelow(abs)+ if (direction === 'premium' && state.discount !== 0) state.discount = 0+ if (direction === 'discount' && state.premium !== 0) state.premium = 0++ const alerted = direction === 'premium' ? state.premium : state.discount+ let crossed: number | null = null+ for (const rung of PREMIUM_LADDER) {+ if (abs >= rung && rung > alerted) crossed = rung+ }+ this.armed.set(symbol, state)+ if (crossed === null) return null++ if (direction === 'premium') state.premium = crossed+ else state.discount = crossed+ return {+ type: 'premium',+ symbol,+ token,+ premiumPct,+ level: crossed,+ direction,+ dexUsd,+ feedUsd,+ pool,+ at: atS,+ }+ }+}++function highestRungBelow(abs: number): number {+ let out = 0+ for (const rung of PREMIUM_LADDER) if (abs >= rung) out = rung+ return out+}diff --git a/robinhood/hood-alerts/src/engine/detectors/prices.ts b/robinhood/hood-alerts/src/engine/detectors/prices.tsnew file mode 100644index 000000000..839835e7b--- /dev/null+++ b/robinhood/hood-alerts/src/engine/detectors/prices.ts@@ -0,0 +1,50 @@+import type { PriceMoveEvent } from '../events.js'++interface Sample {+ at: number+ priceUsd: number+}++/**+ * Rolling-window price-move detector. Feed it every Chainlink tick; it emits a+ * {@link PriceMoveEvent} when the change from the oldest in-window sample+ * exceeds `minEmitPct`. After an emit the window resets to the current price,+ * so the same leg never re-alerts; a continuing move alerts again only after+ * moving `minEmitPct` further. Pure logic, unit-tested on captured feed data.+ */+export class PriceMoveTracker {+ private readonly samples = new Map<string, Sample[]>()++ constructor(+ private readonly windowS: number,+ private readonly minEmitPct: number,+ ) {}++ update(symbol: string, priceUsd: number, atS: number): PriceMoveEvent | null {+ if (!Number.isFinite(priceUsd) || priceUsd <= 0) return null+ const list = this.samples.get(symbol) ?? []+ // Evict out-of-window samples.+ const cutoff = atS - this.windowS+ while (list.length > 0 && (list[0] as Sample).at < cutoff) list.shift()++ if (list.length > 0) {+ const oldest = list[0] as Sample+ const pct = ((priceUsd - oldest.priceUsd) / oldest.priceUsd) * 100+ if (Math.abs(pct) >= this.minEmitPct) {+ this.samples.set(symbol, [{ at: atS, priceUsd }])+ return {+ type: 'price_move',+ symbol,+ pct,+ fromUsd: oldest.priceUsd,+ toUsd: priceUsd,+ windowS: this.windowS,+ at: atS,+ }+ }+ }+ list.push({ at: atS, priceUsd })+ this.samples.set(symbol, list)+ return null+ }+}diff --git a/robinhood/hood-alerts/src/engine/detectors/whale-classify.ts b/robinhood/hood-alerts/src/engine/detectors/whale-classify.tsnew file mode 100644index 000000000..3eb9d94a9--- /dev/null+++ b/robinhood/hood-alerts/src/engine/detectors/whale-classify.ts@@ -0,0 +1,83 @@+import { formatUnits, type Address, type Hash } from 'viem'+import type { CurveTrade } from 'hoodchain'+import type { PoolInfo, SwapEvent } from 'hoodkit'+import type { WhaleEvent } from '../events.js'++/**+ * Pure whale classifiers, unit-tested against captured real trades.+ * The live wiring (log cursors) lives in detectors/live.ts.+ */++/** Classify an Odyssey bonding-curve trade. Quote is native ETH (wei). */+export function classifyCurveTrade(+ trade: Pick<CurveTrade, 'token' | 'trader' | 'isBuy' | 'quoteAmount' | 'blockNumber' | 'transactionHash'>,+ ethUsd: number,+ floorUsd: number,+ atS: number,+): WhaleEvent | null {+ if (!Number.isFinite(ethUsd) || ethUsd <= 0) return null+ const usd = Number(formatUnits(trade.quoteAmount, 18)) * ethUsd+ if (usd < floorUsd) return null+ return {+ type: 'whale',+ source: 'odyssey-curve',+ token: trade.token,+ symbol: null,+ side: trade.isBuy ? 'buy' : 'sell',+ usd,+ trader: trade.trader,+ blockNumber: trade.blockNumber,+ transactionHash: trade.transactionHash,+ at: atS,+ }+}++/**+ * Classify a Uniswap v3 swap on a pool whose quote side is WETH or USDG.+ * `base` is the non-quote token (the coin being traded).+ */+export function classifySwap(+ swap: Pick<SwapEvent, 'amount0' | 'amount1' | 'volume0' | 'volume1' | 'recipient' | 'blockNumber' | 'transactionHash'>,+ info: Pick<PoolInfo, 'token0' | 'token1'>,+ quote: { weth: Address; usdg: Address },+ ethUsd: number,+ floorUsd: number,+ atS: number,+): WhaleEvent | null {+ const t0 = info.token0.toLowerCase()+ const t1 = info.token1.toLowerCase()+ const weth = quote.weth.toLowerCase()+ const usdg = quote.usdg.toLowerCase()++ let quoteSide: 0 | 1 | null = null+ let quoteAsset: 'WETH' | 'USDG' | null = null+ if (t1 === weth || t1 === usdg) {+ quoteSide = 1+ quoteAsset = t1 === weth ? 'WETH' : 'USDG'+ } else if (t0 === weth || t0 === usdg) {+ quoteSide = 0+ quoteAsset = t0 === weth ? 'WETH' : 'USDG'+ }+ if (quoteSide === null || quoteAsset === null) return null+ if (quoteAsset === 'WETH' && (!Number.isFinite(ethUsd) || ethUsd <= 0)) return null++ const quoteVolume = quoteSide === 0 ? swap.volume0 : swap.volume1+ const usd = quoteAsset === 'USDG' ? quoteVolume : quoteVolume * ethUsd+ if (usd < floorUsd) return null++ const base = (quoteSide === 0 ? info.token1 : info.token0) as Address+ // The trader bought the base token when the pool paid the base side out.+ const baseAmount = quoteSide === 0 ? swap.amount1 : swap.amount0+ return {+ type: 'whale',+ source: 'uniswap-v3',+ token: base,+ symbol: null,+ side: baseAmount < 0n ? 'buy' : 'sell',+ usd,+ trader: swap.recipient,+ blockNumber: swap.blockNumber,+ transactionHash: swap.transactionHash as Hash,+ at: atS,+ }+}diff --git a/robinhood/hood-alerts/src/engine/digest.ts b/robinhood/hood-alerts/src/engine/digest.tsnew file mode 100644index 000000000..7e437fa21--- /dev/null+++ b/robinhood/hood-alerts/src/engine/digest.ts@@ -0,0 +1,65 @@+import type { AlertEvent } from './events.js'++/** One buffered alert awaiting a digest flush. */+export interface BufferedAlert {+ event: AlertEvent+ fingerprint: string+ bufferedAt: number+}++interface Bucket {+ alerts: BufferedAlert[]+ /** Unix seconds when this bucket becomes flushable. */+ notBefore: number+}++/**+ * Per-subscriber digest buffers. Alerts gated into digest mode (or deferred by+ * quiet hours / free-tier granularity) accumulate here; `drain(now)` returns+ * every bucket whose flush time has arrived. In-memory by design: the delivery+ * log records what was actually sent, and a restart loses at most one pending+ * batch, never a subscription.+ */+export class DigestBuffer {+ private readonly buckets = new Map<number, Bucket>()++ /** Queue an alert for `subscriberId`, flushable after `delayS` seconds. */+ add(subscriberId: number, alert: BufferedAlert, delayS: number, nowS: number): void {+ const existing = this.buckets.get(subscriberId)+ if (existing) {+ existing.alerts.push(alert)+ // A shorter delay (e.g. free-granularity 60s vs digest 3600s) wins so+ // the batch is not held hostage by the longest deferral.+ existing.notBefore = Math.min(existing.notBefore, nowS + delayS)+ return+ }+ this.buckets.set(subscriberId, { alerts: [alert], notBefore: nowS + delayS })+ }++ /** Number of alerts currently buffered for a subscriber. */+ pending(subscriberId: number): number {+ return this.buckets.get(subscriberId)?.alerts.length ?? 0+ }++ /** Remove and return every due bucket. */+ drain(nowS: number): Array<{ subscriberId: number; alerts: BufferedAlert[] }> {+ const due: Array<{ subscriberId: number; alerts: BufferedAlert[] }> = []+ for (const [subscriberId, bucket] of this.buckets) {+ if (bucket.notBefore <= nowS && bucket.alerts.length > 0) {+ due.push({ subscriberId, alerts: bucket.alerts })+ this.buckets.delete(subscriberId)+ }+ }+ return due+ }++ /** Remove and return everything, due or not (shutdown flush). */+ drainAll(): Array<{ subscriberId: number; alerts: BufferedAlert[] }> {+ const all: Array<{ subscriberId: number; alerts: BufferedAlert[] }> = []+ for (const [subscriberId, bucket] of this.buckets) {+ if (bucket.alerts.length > 0) all.push({ subscriberId, alerts: bucket.alerts })+ }+ this.buckets.clear()+ return all+ }+}diff --git a/robinhood/hood-alerts/src/engine/engine.ts b/robinhood/hood-alerts/src/engine/engine.tsnew file mode 100644index 000000000..285ab9bc9--- /dev/null+++ b/robinhood/hood-alerts/src/engine/engine.ts@@ -0,0 +1,186 @@+import type { Address } from 'viem'+import { logger } from '../logger.js'+import type { DetectorConfig } from '../config.js'+import type { Db } from '../db/index.js'+import { DeliveryRepo } from '../db/deliveries.js'+import { EntitlementRepo } from '../db/entitlements.js'+import { SubscriberRepo, type Subscriber } from '../db/subscribers.js'+import type { Transport } from '../transports/types.js'+import { dedupTtlSeconds, fingerprint, type AlertEvent } from './events.js'+import { DigestBuffer, type BufferedAlert } from './digest.js'+import { FREE_MIN_INTERVAL_S, gate } from './gate.js'+import { matches, parseTopic } from './topics.js'++const nowS = (): number => Math.floor(Date.now() / 1000)++/**+ * The alert engine: one event stream in, per-subscriber deliveries out.+ * Detector events pass dedup, subscription routing, tier/quiet/digest gating,+ * and rate limiting before reaching a transport. Every delivery is logged.+ */+export class AlertEngine {+ readonly subscribers: SubscriberRepo+ readonly entitlements: EntitlementRepo+ readonly deliveries: DeliveryRepo+ private readonly digestBuffer = new DigestBuffer()+ private readonly transports = new Map<string, Transport>()+ private flushTimer: ReturnType<typeof setInterval> | null = null+ private onWatchedTokensChanged: ((tokens: Address[]) => void) | null = null+ /** Ring of recent events for /healthz and diagnostics. */+ readonly recent: AlertEvent[] = []++ constructor(+ db: Db,+ private readonly cfg: DetectorConfig,+ ) {+ this.subscribers = new SubscriberRepo(db)+ this.entitlements = new EntitlementRepo(db)+ this.deliveries = new DeliveryRepo(db)+ }++ registerTransport(transport: Transport): void {+ this.transports.set(transport.platform, transport)+ }++ /** Called whenever the set of `token:0x…` watches changes. */+ onTokenWatches(cb: (tokens: Address[]) => void): void {+ this.onWatchedTokensChanged = cb+ cb(this.watchedTokens())+ }++ /** Tokens with at least one `token:` subscription. */+ watchedTokens(): Address[] {+ const tokens = new Set<string>()+ for (const topic of this.subscribers.activeTopics()) {+ const parsed = parseTopic(topic)+ if (parsed?.kind === 'token') tokens.add(parsed.address)+ }+ return [...tokens] as Address[]+ }++ /** Notify detectors after a watch/unwatch that touches token topics. */+ notifyWatchChange(): void {+ this.onWatchedTokensChanged?.(this.watchedTokens())+ }++ start(): void {+ this.flushTimer = setInterval(() => {+ this.flushDigests().catch((error) => logger.error({ err: String(error) }, 'digest flush failed'))+ }, 15_000)+ }++ async stop(): Promise<void> {+ if (this.flushTimer) clearInterval(this.flushTimer)+ this.flushTimer = null+ // Final flush so buffered alerts are not silently lost on shutdown.+ const all = this.digestBuffer.drainAll()+ for (const bucket of all) await this.deliverDigest(bucket.subscriberId, bucket.alerts)+ }++ /** Ingest one detector event. Synchronous decisions, async deliveries. */+ ingest(event: AlertEvent): void {+ const fp = fingerprint(event)+ if (!this.deliveries.claimFingerprint(fp, dedupTtlSeconds(event))) return++ this.recent.push(event)+ if (this.recent.length > 100) this.recent.shift()++ const now = nowS()+ for (const { subscription, subscriber } of this.subscribers.allWithSubscribers()) {+ const parsed = parseTopic(subscription.topic)+ if (!parsed) continue+ const premium = this.entitlements.isPremium(subscriber.platform, subscriber.chatId)+ // Premium-only topics stop matching when the entitlement lapses.+ if ((parsed.kind === 'premiums' || parsed.kind === 'rugs') && !premium) continue+ if (!matches(parsed, subscription.threshold, event)) continue++ const decision = gate(+ {+ premium,+ digest: subscriber.digest,+ quietStart: subscriber.quietStart,+ quietEnd: subscriber.quietEnd,+ lastDeliveredAt: this.deliveries.lastDeliveredAt(subscriber.id),+ deliveredLastMinute: this.deliveries.recentCount(subscriber.id, 60),+ },+ now,+ )+ const buffered: BufferedAlert = { event, fingerprint: fp, bufferedAt: now }+ if (decision.action === 'deliver') {+ void this.deliver(subscriber, event, fp)+ } else if (decision.action === 'digest') {+ const delayS =+ decision.reason === 'digest-mode'+ ? subscriber.digestIntervalS+ : decision.reason === 'quiet-hours'+ ? 900 // re-check quiet window every 15 min; gate re-applies on flush+ : FREE_MIN_INTERVAL_S+ this.digestBuffer.add(subscriber.id, buffered, delayS, now)+ this.deliveries.logDelivery(subscriber.id, fp, 'digested', decision.reason)+ } else {+ logger.warn({ subscriber: subscriber.id, fp }, 'alert dropped: rate limited')+ }+ }+ }++ private async deliver(subscriber: Subscriber, event: AlertEvent, fp: string): Promise<void> {+ const transport = this.transports.get(subscriber.platform)+ if (!transport) {+ this.deliveries.logDelivery(subscriber.id, fp, 'failed', `no transport for ${subscriber.platform}`)+ return+ }+ try {+ await transport.sendAlert(subscriber.chatId, event)+ this.deliveries.logDelivery(subscriber.id, fp, 'sent')+ } catch (error) {+ this.deliveries.logDelivery(subscriber.id, fp, 'failed', String(error))+ logger.error({ err: String(error), subscriber: subscriber.id }, 'alert delivery failed')+ }+ }++ private async flushDigests(): Promise<void> {+ const now = nowS()+ for (const bucket of this.digestBuffer.drain(now)) {+ const subscriber = this.subscribers.byId(bucket.subscriberId)+ if (!subscriber) continue+ // Still inside quiet hours? Re-buffer for another 15 minutes.+ const decision = gate(+ {+ premium: this.entitlements.isPremium(subscriber.platform, subscriber.chatId),+ digest: false,+ quietStart: subscriber.quietStart,+ quietEnd: subscriber.quietEnd,+ lastDeliveredAt: null,+ deliveredLastMinute: this.deliveries.recentCount(subscriber.id, 60),+ },+ now,+ )+ if (decision.action === 'digest') {+ for (const alert of bucket.alerts) this.digestBuffer.add(subscriber.id, alert, 900, now)+ continue+ }+ await this.deliverDigest(bucket.subscriberId, bucket.alerts)+ }+ }++ private async deliverDigest(subscriberId: number, alerts: BufferedAlert[]): Promise<void> {+ const subscriber = this.subscribers.byId(subscriberId)+ if (!subscriber || alerts.length === 0) return+ const transport = this.transports.get(subscriber.platform)+ if (!transport) return+ try {+ if (alerts.length === 1 && alerts[0]) {+ await transport.sendAlert(subscriber.chatId, alerts[0].event)+ } else {+ await transport.sendDigest(+ subscriber.chatId,+ alerts.map((a) => a.event),+ )+ }+ for (const a of alerts) this.deliveries.logDelivery(subscriberId, a.fingerprint, 'sent', 'digest')+ } catch (error) {+ for (const a of alerts) this.deliveries.logDelivery(subscriberId, a.fingerprint, 'failed', String(error))+ logger.error({ err: String(error), subscriber: subscriberId }, 'digest delivery failed')+ }+ }+}diff --git a/robinhood/hood-alerts/src/engine/eth-price.ts b/robinhood/hood-alerts/src/engine/eth-price.tsnew file mode 100644index 000000000..19c415b1c--- /dev/null+++ b/robinhood/hood-alerts/src/engine/eth-price.ts@@ -0,0 +1,85 @@+import { MAINNET_ADDRESSES, MAINNET_EXPLORER_URL, uniswapV3PoolAbi, type HoodClient } from 'hoodchain'+import { discoverPools, sqrtPriceX96ToPrice } from 'hoodkit'+import { logger } from '../logger.js'++/**+ * ETH/USD provider: Blockscout chain stats first (one HTTP call, cached),+ * falling back to the on-chain WETH/USDG Uniswap v3 pool spot when the+ * explorer API is unavailable. Whale sizing and WETH-pool valuation both+ * depend on this number.+ */+export class EthPrice {+ private value: number | null = null+ private fetchedAt = 0+ private pool: { address: `0x${string}`; wethIs0: boolean; decimals0: number; decimals1: number } | null = null++ constructor(+ private readonly client: HoodClient,+ private readonly ttlS = 60,+ ) {}++ async get(): Promise<number | null> {+ const now = Math.floor(Date.now() / 1000)+ if (this.value !== null && now - this.fetchedAt < this.ttlS) return this.value++ const fromStats = await this.fromBlockscout()+ if (fromStats !== null) {+ this.value = fromStats+ this.fetchedAt = now+ return fromStats+ }+ const fromPool = await this.fromPool()+ if (fromPool !== null) {+ this.value = fromPool+ this.fetchedAt = now+ }+ return fromPool ?? this.value+ }++ private async fromBlockscout(): Promise<number | null> {+ try {+ const res = await fetch(`${MAINNET_EXPLORER_URL}/api/v2/stats`, {+ signal: AbortSignal.timeout(10_000),+ headers: { accept: 'application/json' },+ })+ if (!res.ok) return null+ const body = (await res.json()) as { coin_price?: string | null }+ const price = body.coin_price ? Number(body.coin_price) : NaN+ return Number.isFinite(price) && price > 0 ? price : null+ } catch (error) {+ logger.warn({ err: String(error) }, 'blockscout stats unavailable, falling back to WETH/USDG pool')+ return null+ }+ }++ private async fromPool(): Promise<number | null> {+ try {+ if (!this.pool) {+ const pools = await discoverPools(this.client, MAINNET_ADDRESSES.weth)+ const usdgPool = pools.find(+ (p) =>+ p.token0.toLowerCase() === MAINNET_ADDRESSES.usdg.toLowerCase() ||+ p.token1.toLowerCase() === MAINNET_ADDRESSES.usdg.toLowerCase(),+ )+ if (!usdgPool) return null+ this.pool = {+ address: usdgPool.pool,+ wethIs0: usdgPool.token0.toLowerCase() === MAINNET_ADDRESSES.weth.toLowerCase(),+ decimals0: usdgPool.decimals0,+ decimals1: usdgPool.decimals1,+ }+ }+ const [sqrtPriceX96] = await this.client.public.readContract({+ address: this.pool.address,+ abi: uniswapV3PoolAbi,+ functionName: 'slot0',+ })+ const price0In1 = sqrtPriceX96ToPrice(sqrtPriceX96, this.pool.decimals0, this.pool.decimals1)+ if (price0In1 <= 0) return null+ return this.pool.wethIs0 ? price0In1 : 1 / price0In1+ } catch (error) {+ logger.warn({ err: String(error) }, 'WETH/USDG pool ETH price read failed')+ return null+ }+ }+}diff --git a/robinhood/hood-alerts/src/engine/events.ts b/robinhood/hood-alerts/src/engine/events.tsnew file mode 100644index 000000000..8517dba9f--- /dev/null+++ b/robinhood/hood-alerts/src/engine/events.ts@@ -0,0 +1,144 @@+import type { Address, Hash } from 'viem'++/** Which launchpad an event came from. */+export type Launchpad = 'noxa' | 'odyssey'++/** A new token launch on NOXA or The Odyssey. */+export interface LaunchEvent {+ type: 'launch'+ launchpad: Launchpad+ token: Address+ symbol: string | null+ name: string | null+ creator: Address+ /** Uniswap v3 pool (immediate for NOXA; null while an Odyssey curve fills). */+ pool: Address | null+ blockNumber: bigint+ transactionHash: Hash+ at: number+}++/** An Odyssey bonding curve filled and migrated to a locked Uniswap v3 pool. */+export interface GraduationEvent {+ type: 'graduation'+ token: Address+ symbol: string | null+ name: string | null+ pool: Address+ blockNumber: bigint+ transactionHash: Hash+ at: number+}++/** A trade at or above the whale USD floor. */+export interface WhaleEvent {+ type: 'whale'+ source: 'odyssey-curve' | 'uniswap-v3'+ token: Address+ symbol: string | null+ side: 'buy' | 'sell'+ usd: number+ trader: Address+ blockNumber: bigint+ transactionHash: Hash+ at: number+}++/** A Stock Token Chainlink price moved beyond a ladder rung within the window. */+export interface PriceMoveEvent {+ type: 'price_move'+ symbol: string+ /** Signed percent change over the window. */+ pct: number+ fromUsd: number+ toUsd: number+ windowS: number+ at: number+}++/** DEX price crossed a premium/discount rung vs the Chainlink feed. */+export interface PremiumEvent {+ type: 'premium'+ symbol: string+ token: Address+ /** Signed premium percent: positive = DEX trades above Chainlink. */+ premiumPct: number+ /** The ladder rung crossed (absolute percent). */+ level: number+ direction: 'premium' | 'discount'+ dexUsd: number+ feedUsd: number+ pool: Address+ at: number+}++/** A token's holder count crossed a milestone. */+export interface HolderMilestoneEvent {+ type: 'holders'+ token: Address+ symbol: string | null+ milestone: number+ count: number+ at: number+}++/** Pool quote reserves dropped sharply: the rug early-warning. */+export interface LiquidityPullEvent {+ type: 'liquidity_pull'+ token: Address | null+ symbol: string | null+ pool: Address+ quoteAsset: 'USDG' | 'WETH'+ droppedPct: number+ beforeUsd: number+ afterUsd: number+ at: number+}++/** Any alert the engine can route. */+export type AlertEvent =+ | LaunchEvent+ | GraduationEvent+ | WhaleEvent+ | PriceMoveEvent+ | PremiumEvent+ | HolderMilestoneEvent+ | LiquidityPullEvent++/** Stable dedup fingerprint for an event. */+export function fingerprint(e: AlertEvent): string {+ switch (e.type) {+ case 'launch':+ return `launch:${e.transactionHash}:${e.token.toLowerCase()}`+ case 'graduation':+ return `grad:${e.token.toLowerCase()}`+ case 'whale':+ return `whale:${e.transactionHash}:${e.token.toLowerCase()}:${e.usd.toFixed(0)}`+ case 'price_move':+ return `price:${e.symbol}:${e.at}`+ case 'premium':+ return `premium:${e.symbol}:${e.direction}:${e.level}`+ case 'holders':+ return `holders:${e.token.toLowerCase()}:${e.milestone}`+ case 'liquidity_pull':+ return `liq:${e.pool.toLowerCase()}`+ }+}++/** How long a fingerprint blocks re-delivery, per event type (seconds). */+export function dedupTtlSeconds(e: AlertEvent): number {+ switch (e.type) {+ case 'launch':+ case 'graduation':+ case 'whale':+ return 7 * 24 * 3600+ case 'price_move':+ return 24 * 3600+ case 'premium':+ return 6 * 3600+ case 'holders':+ return 30 * 24 * 3600+ case 'liquidity_pull':+ return 3600+ }+}diff --git a/robinhood/hood-alerts/src/engine/gate.ts b/robinhood/hood-alerts/src/engine/gate.tsnew file mode 100644index 000000000..5f3e2bb98--- /dev/null+++ b/robinhood/hood-alerts/src/engine/gate.ts@@ -0,0 +1,53 @@+/**+ * Per-subscriber delivery gating: token-bucket rate limiting, quiet hours,+ * digest mode, and the free-tier minimum granularity. Pure logic, injectable+ * clock, unit-tested against the state machine in tests/dedup-gate.test.ts.+ */++export interface GateInput {+ /** Is the subscriber premium right now? */+ premium: boolean+ /** Has the subscriber turned digest mode on? */+ digest: boolean+ /** Quiet hours in the subscriber's configured UTC hours, or null. */+ quietStart: number | null+ quietEnd: number | null+ /** Unix seconds of this subscriber's last immediate delivery. */+ lastDeliveredAt: number | null+ /** Deliveries in the last 60s (for the burst bucket). */+ deliveredLastMinute: number+}++export type GateDecision =+ | { action: 'deliver' }+ | { action: 'digest'; reason: 'digest-mode' | 'quiet-hours' | 'free-granularity' }+ | { action: 'drop'; reason: 'rate-limited' }++/** Free tier: at most one immediate delivery per 60s; extras fold into a batch. */+export const FREE_MIN_INTERVAL_S = 60+/** Hard per-subscriber burst cap (platform API safety), premium included. */+export const MAX_PER_MINUTE = 20++/** Is `hourUtc` inside the [start, end) quiet window? Handles wrap-around. */+export function inQuietHours(hourUtc: number, start: number | null, end: number | null): boolean {+ if (start === null || end === null || start === end) return false+ if (start < end) return hourUtc >= start && hourUtc < end+ return hourUtc >= start || hourUtc < end+}++/** Decide how to handle one matched alert for one subscriber. */+export function gate(input: GateInput, nowS: number): GateDecision {+ if (input.deliveredLastMinute >= MAX_PER_MINUTE) return { action: 'drop', reason: 'rate-limited' }++ const hourUtc = Math.floor((nowS % 86_400) / 3600)+ if (inQuietHours(hourUtc, input.quietStart, input.quietEnd)) {+ return { action: 'digest', reason: 'quiet-hours' }+ }+ if (input.digest) return { action: 'digest', reason: 'digest-mode' }++ if (!input.premium) {+ const last = input.lastDeliveredAt ?? 0+ if (nowS - last < FREE_MIN_INTERVAL_S) return { action: 'digest', reason: 'free-granularity' }+ }+ return { action: 'deliver' }+}diff --git a/robinhood/hood-alerts/src/engine/token-meta.ts b/robinhood/hood-alerts/src/engine/token-meta.tsnew file mode 100644index 000000000..9155ed233--- /dev/null+++ b/robinhood/hood-alerts/src/engine/token-meta.ts@@ -0,0 +1,46 @@+import { erc20Abi, type HoodClient } from 'hoodchain'+import type { Address } from 'viem'++export interface TokenMeta {+ symbol: string | null+ name: string | null+}++/**+ * Symbol/name cache for arbitrary ERC-20s (launchpad coins are not in the+ * Stock Token registry). Failures cache as nulls so a broken token does not+ * hammer the RPC on every event.+ */+export class TokenMetaCache {+ private readonly cache = new Map<string, TokenMeta>()++ constructor(private readonly client: HoodClient) {}++ async get(token: Address): Promise<TokenMeta> {+ const key = token.toLowerCase()+ const hit = this.cache.get(key)+ if (hit) return hit+ let meta: TokenMeta = { symbol: null, name: null }+ try {+ const [symbol, name] = await this.client.public.multicall({+ contracts: [+ { address: token, abi: erc20Abi, functionName: 'symbol' },+ { address: token, abi: erc20Abi, functionName: 'name' },+ ],+ allowFailure: true,+ })+ meta = {+ symbol: symbol.status === 'success' ? String(symbol.result).slice(0, 32) : null,+ name: name.status === 'success' ? String(name.result).slice(0, 64) : null,+ }+ } catch {+ // keep nulls+ }+ this.cache.set(key, meta)+ if (this.cache.size > 5000) {+ const first = this.cache.keys().next().value+ if (first) this.cache.delete(first)+ }+ return meta+ }+}diff --git a/robinhood/hood-alerts/src/engine/topics.ts b/robinhood/hood-alerts/src/engine/topics.tsnew file mode 100644index 000000000..6da321cf7--- /dev/null+++ b/robinhood/hood-alerts/src/engine/topics.ts@@ -0,0 +1,132 @@+import { isStockTokenSymbol } from 'hoodchain'+import type { AlertEvent } from './events.js'++/**+ * Subscription topics:+ *+ * - `launches` / `launches:noxa` / `launches:odyssey` — new token launches+ * - `graduations` — Odyssey curves migrating to Uniswap v3+ * - `whales` — trades >= threshold USD, chain-wide (threshold = USD)+ * - `premiums` — Stock Token DEX premium/discount vs Chainlink (threshold = %, premium tier)+ * - `rugs` — liquidity pulls (threshold = % of quote reserves, premium tier)+ * - `token:0x…` — per-token: whales, graduation, holders, liquidity pulls+ * - `stock:SYMBOL` — per-stock: price moves + premium/discount crossings+ */+export type ParsedTopic =+ | { kind: 'launches'; launchpad: 'noxa' | 'odyssey' | null }+ | { kind: 'graduations' }+ | { kind: 'whales' }+ | { kind: 'premiums' }+ | { kind: 'rugs' }+ | { kind: 'token'; address: `0x${string}` }+ | { kind: 'stock'; symbol: string }++/** Topics only premium subscribers may watch. */+export const PREMIUM_TOPICS = new Set(['premiums', 'rugs'])++/** Parse a stored topic string. Returns null for unknown/corrupt topics. */+export function parseTopic(topic: string): ParsedTopic | null {+ if (topic === 'launches') return { kind: 'launches', launchpad: null }+ if (topic === 'launches:noxa') return { kind: 'launches', launchpad: 'noxa' }+ if (topic === 'launches:odyssey') return { kind: 'launches', launchpad: 'odyssey' }+ if (topic === 'graduations') return { kind: 'graduations' }+ if (topic === 'whales') return { kind: 'whales' }+ if (topic === 'premiums') return { kind: 'premiums' }+ if (topic === 'rugs') return { kind: 'rugs' }+ if (topic.startsWith('token:')) {+ const address = topic.slice(6)+ if (/^0x[0-9a-f]{40}$/.test(address)) return { kind: 'token', address: address as `0x${string}` }+ return null+ }+ if (topic.startsWith('stock:')) {+ const symbol = topic.slice(6)+ if (/^[A-Z0-9.]{1,12}$/.test(symbol)) return { kind: 'stock', symbol }+ return null+ }+ return null+}++/**+ * Resolve a user-typed watch target into a canonical topic string.+ * Accepts: launches[:pad], graduations, whales, premiums, rugs, a 0x address,+ * or a Stock Token ticker.+ */+export type ResolvedTarget = { ok: true; topic: string } | { ok: false; error: string }++export function resolveWatchTarget(input: string): ResolvedTarget {+ const raw = input.trim()+ const lower = raw.toLowerCase()+ if (['launches', 'launch'].includes(lower)) return { ok: true, topic: 'launches' }+ if (lower === 'launches:noxa' || lower === 'noxa') return { ok: true, topic: 'launches:noxa' }+ if (lower === 'launches:odyssey' || lower === 'odyssey') return { ok: true, topic: 'launches:odyssey' }+ if (['graduations', 'graduation', 'grads'].includes(lower)) return { ok: true, topic: 'graduations' }+ if (['whales', 'whale'].includes(lower)) return { ok: true, topic: 'whales' }+ if (['premiums', 'premium', 'arb', 'arbs'].includes(lower)) return { ok: true, topic: 'premiums' }+ if (['rugs', 'rug', 'liquidity'].includes(lower)) return { ok: true, topic: 'rugs' }+ if (/^0x[0-9a-fA-F]{40}$/.test(raw)) return { ok: true, topic: `token:${raw.toLowerCase()}` }+ const symbol = raw.toUpperCase()+ if (/^[A-Z0-9.]{1,12}$/.test(symbol)) {+ if (isStockTokenSymbol(symbol)) return { ok: true, topic: `stock:${symbol}` }+ return {+ ok: false,+ error:+ `"${symbol}" is not a Robinhood Chain Stock Token ticker. ` ++ 'To watch a memecoin, use its contract address (0x…).',+ }+ }+ return { ok: false, error: `Cannot watch "${raw}". Try launches, graduations, whales, premiums, rugs, a ticker, or a 0x address.` }+}++/** Default threshold for a topic (null = no threshold semantics). */+export function defaultThreshold(+ topic: ParsedTopic,+ defaults: { whaleUsd: number; premiumPct: number; rugPct: number; pricePct: number },+): number | null {+ switch (topic.kind) {+ case 'whales':+ return defaults.whaleUsd+ case 'premiums':+ return defaults.premiumPct+ case 'rugs':+ return defaults.rugPct+ case 'stock':+ return defaults.pricePct+ case 'token':+ return defaults.whaleUsd+ default:+ return null+ }+}++/**+ * Does `event` match a subscription on `topic` with `threshold`?+ * Threshold semantics: whales/token = min USD; premiums/stock = min percent;+ * rugs = min dropped percent.+ */+export function matches(topic: ParsedTopic, threshold: number | null, event: AlertEvent): boolean {+ switch (topic.kind) {+ case 'launches':+ return event.type === 'launch' && (topic.launchpad === null || event.launchpad === topic.launchpad)+ case 'graduations':+ return event.type === 'graduation'+ case 'whales':+ return event.type === 'whale' && event.usd >= (threshold ?? 0)+ case 'premiums':+ return event.type === 'premium' && Math.abs(event.premiumPct) >= (threshold ?? 0)+ case 'rugs':+ return event.type === 'liquidity_pull' && event.droppedPct >= (threshold ?? 0)+ case 'token': {+ const addr = topic.address+ if (event.type === 'whale') return event.token.toLowerCase() === addr && event.usd >= (threshold ?? 0)+ if (event.type === 'graduation') return event.token.toLowerCase() === addr+ if (event.type === 'holders') return event.token.toLowerCase() === addr+ if (event.type === 'liquidity_pull') return event.token?.toLowerCase() === addr+ return false+ }+ case 'stock': {+ if (event.type === 'price_move') return event.symbol === topic.symbol && Math.abs(event.pct) >= (threshold ?? 0)+ if (event.type === 'premium') return event.symbol === topic.symbol && Math.abs(event.premiumPct) >= (threshold ?? 0)+ return false+ }+ }+}diff --git a/robinhood/hood-alerts/src/format/cards.ts b/robinhood/hood-alerts/src/format/cards.tsnew file mode 100644index 000000000..3e457e1de--- /dev/null+++ b/robinhood/hood-alerts/src/format/cards.ts@@ -0,0 +1,178 @@+import { MAINNET_EXPLORER_URL } from 'hoodchain'+import type { AlertEvent } from '../engine/events.js'++/** A platform-neutral alert card; each transport renders it natively. */+export interface AlertCard {+ emojiless: true+ title: string+ lines: string[]+ links: Array<{ label: string; url: string }>+ severity: 'info' | 'notice' | 'warning'+}++const MARKETS = 'https://three.ws/markets/robinhood'++export function usd(n: number): string {+ if (n >= 1_000_000) return `$${(n / 1_000_000).toFixed(2)}M`+ if (n >= 1_000) return `$${(n / 1_000).toFixed(1)}k`+ return `$${n.toFixed(2)}`+}++export function short(addr: string): string {+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`+}++function tokenLabel(symbol: string | null, token: string): string {+ return symbol ? `${symbol} (${short(token)})` : short(token)+}++function coinLinks(token: string, tx?: string): AlertCard['links'] {+ const links = [+ { label: 'Chart', url: `${MARKETS}/coin/${token}` },+ { label: 'Token', url: `${MAINNET_EXPLORER_URL}/token/${token}` },+ ]+ if (tx) links.push({ label: 'Tx', url: `${MAINNET_EXPLORER_URL}/tx/${tx}` })+ return links+}++/** Render any engine event into a card. */+export function toCard(e: AlertEvent): AlertCard {+ switch (e.type) {+ case 'launch': {+ const pad = e.launchpad === 'noxa' ? 'NOXA (instant v3 pool)' : 'The Odyssey (bonding curve)'+ return {+ emojiless: true,+ severity: 'info',+ title: `New launch: ${e.symbol ?? short(e.token)}`,+ lines: [+ ...(e.name ? [e.name] : []),+ `Launchpad: ${pad}`,+ `Creator: ${short(e.creator)}`,+ ...(e.pool ? [`Pool: ${short(e.pool)}`] : ['Trading on the curve until graduation']),+ `Block ${e.blockNumber}`,+ ],+ links: coinLinks(e.token, e.transactionHash),+ }+ }+ case 'graduation':+ return {+ emojiless: true,+ severity: 'notice',+ title: `Graduated: ${e.symbol ?? short(e.token)}`,+ lines: [+ ...(e.name ? [e.name] : []),+ 'Odyssey curve filled; liquidity migrated to a locked Uniswap v3 pool.',+ `Pool: ${short(e.pool)}`,+ ],+ links: coinLinks(e.token, e.transactionHash),+ }+ case 'whale':+ return {+ emojiless: true,+ severity: 'notice',+ title: `Whale ${e.side}: ${usd(e.usd)} of ${e.symbol ?? short(e.token)}`,+ lines: [+ `Venue: ${e.source === 'odyssey-curve' ? 'Odyssey bonding curve' : 'Uniswap v3'}`,+ `Trader: ${short(e.trader)}`,+ `Block ${e.blockNumber}`,+ ],+ links: [+ ...coinLinks(e.token, e.transactionHash),+ { label: 'Trader', url: `${MAINNET_EXPLORER_URL}/address/${e.trader}` },+ ],+ }+ case 'price_move': {+ const dir = e.pct >= 0 ? 'up' : 'down'+ return {+ emojiless: true,+ severity: 'info',+ title: `${e.symbol} ${dir} ${Math.abs(e.pct).toFixed(2)}% in ${Math.round(e.windowS / 60)}m`,+ lines: [`$${e.fromUsd.toFixed(2)} -> $${e.toUsd.toFixed(2)} (Chainlink, 24/5 feed)`],+ links: [{ label: 'Chart', url: `${MARKETS}/stock/${e.symbol}` }],+ }+ }+ case 'premium': {+ const word = e.direction === 'premium' ? 'premium' : 'discount'+ return {+ emojiless: true,+ severity: 'notice',+ title: `${e.symbol} trades at a ${Math.abs(e.premiumPct).toFixed(2)}% ${word} on-chain`,+ lines: [+ `DEX mid: $${e.dexUsd.toFixed(2)} vs Chainlink: $${e.feedUsd.toFixed(2)}`,+ e.direction === 'premium'+ ? 'On-chain buyers are paying above the oracle price.'+ : 'The token trades below its oracle price on-chain.',+ `Pool: ${short(e.pool)}`,+ ],+ links: [+ { label: 'Chart', url: `${MARKETS}/stock/${e.symbol}` },+ { label: 'Pool', url: `${MAINNET_EXPLORER_URL}/address/${e.pool}` },+ ],+ }+ }+ case 'holders':+ return {+ emojiless: true,+ severity: 'info',+ title: `${e.symbol ?? short(e.token)} crossed ${e.milestone.toLocaleString('en-US')} holders`,+ lines: [`Now at ${e.count.toLocaleString('en-US')} holders.`],+ links: coinLinks(e.token),+ }+ case 'liquidity_pull':+ return {+ emojiless: true,+ severity: 'warning',+ title: `Liquidity pull: ${tokenLabel(e.symbol, e.token ?? e.pool)}`,+ lines: [+ `${e.quoteAsset} reserves dropped ${e.droppedPct.toFixed(1)}% (${usd(e.beforeUsd)} -> ${usd(e.afterUsd)}).`,+ 'This is an early rug warning, not proof; check the pool before acting.',+ ],+ links: [+ { label: 'Pool', url: `${MAINNET_EXPLORER_URL}/address/${e.pool}` },+ ...(e.token ? coinLinks(e.token) : []),+ ],+ }+ }+}++function escapeHtml(s: string): string {+ return s.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')+}++/** Telegram HTML rendering of a card. */+export function cardToTelegramHtml(card: AlertCard): string {+ const links = card.links.map((l) => `<a href="${l.url}">${escapeHtml(l.label)}</a>`).join(' · ')+ return [`<b>${escapeHtml(card.title)}</b>`, ...card.lines.map(escapeHtml), links].join('\n')+}++/** Plain-text rendering (console transport + logs). */+export function cardToText(card: AlertCard): string {+ return [card.title, ...card.lines, ...card.links.map((l) => `${l.label}: ${l.url}`)].join('\n')+}++/** Discord embed data for a card (matches discord.js APIEmbed). */+export function cardToDiscordEmbed(card: AlertCard): {+ title: string+ description: string+ color: number+ footer: { text: string }+} {+ const color = card.severity === 'warning' ? 0xe5484d : card.severity === 'notice' ? 0x30a46c : 0x5b5bd6+ const links = card.links.map((l) => `[${l.label}](${l.url})`).join(' · ')+ return {+ title: card.title,+ description: [...card.lines, '', links].join('\n'),+ color,+ footer: { text: 'hood-alerts · Robinhood Chain 4663' },+ }+}++/** 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)+ return {+ title: `Digest: ${events.length} alert${events.length === 1 ? '' : 's'}`,+ cards,+ omitted: Math.max(0, events.length - 10),+ }+}diff --git a/robinhood/hood-alerts/src/index.ts b/robinhood/hood-alerts/src/index.tsnew file mode 100644index 000000000..c705a4a96--- /dev/null+++ b/robinhood/hood-alerts/src/index.ts@@ -0,0 +1,76 @@+#!/usr/bin/env node+import { serve } from '@hono/node-server'+import { createHoodClient } from 'hoodchain'+import { loadConfig } from './config.js'+import { logger } from './logger.js'+import { openDb } from './db/index.js'+import { AlertEngine } from './engine/engine.js'+import { LiveDetectors } from './engine/detectors/live.js'+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 type { Transport } from './transports/types.js'+import { PremiumPaywall } from './premium/paywall.js'+import { buildApp } from './server.js'++async function main(): Promise<void> {+ const config = loadConfig()+ const db = openDb(config.dbPath)+ const client = createHoodClient(config.rpcUrl ? { rpcUrl: config.rpcUrl } : {})++ const engine = new AlertEngine(db, config.detectors)+ const detectors = new LiveDetectors(client, config.detectors, (event) => engine.ingest(event))+ engine.onTokenWatches((tokens) => {+ void detectors.syncWatchedTokens(tokens).catch((error) => logger.error({ err: String(error) }, 'token watch sync failed'))+ })++ const commands = new Commands({+ subscribers: engine.subscribers,+ entitlements: engine.entitlements,+ config,+ notifyWatchChange: () => engine.notifyWatchChange(),+ })++ const transports: Transport[] = [new ConsoleTransport()]+ if (config.telegramToken) transports.push(new TelegramTransport(config.telegramToken, commands))+ else logger.warn('HOOD_ALERTS_TELEGRAM_TOKEN not set: telegram transport disabled')+ if (config.discordToken && config.discordAppId) transports.push(new DiscordTransport(config.discordToken, config.discordAppId, commands))+ else logger.warn('HOOD_ALERTS_DISCORD_TOKEN/APP_ID not set: discord transport disabled')++ for (const t of transports) {+ engine.registerTransport(t)+ await t.start()+ }++ const paywall = new PremiumPaywall(config, engine.entitlements)+ if (!paywall.enabled) logger.warn('premium purchases disabled (set HOOD402_PAY_TO + facilitator or settler key)')++ engine.start()+ await detectors.start()++ const app = buildApp({ config, engine, detectors, paywall, startedAt: Math.floor(Date.now() / 1000) })+ const server = serve({ fetch: app.fetch, port: config.port }, (info) =>+ logger.info({ port: info.port }, 'http server listening'),+ )++ let shuttingDown = false+ const shutdown = async (signal: string): Promise<void> => {+ if (shuttingDown) return+ shuttingDown = true+ logger.info({ signal }, 'shutting down')+ server.close()+ detectors.stop()+ await engine.stop() // flushes pending digests+ for (const t of transports) await t.stop().catch(() => undefined)+ db.close()+ process.exit(0)+ }+ process.on('SIGINT', () => void shutdown('SIGINT'))+ process.on('SIGTERM', () => void shutdown('SIGTERM'))+}++main().catch((error) => {+ logger.fatal({ err: String(error?.stack ?? error) }, 'fatal startup error')+ process.exit(1)+})diff --git a/robinhood/hood-alerts/src/logger.ts b/robinhood/hood-alerts/src/logger.tsnew file mode 100644index 000000000..5b9d02990--- /dev/null+++ b/robinhood/hood-alerts/src/logger.ts@@ -0,0 +1,19 @@+import { pino } from 'pino'++/**+ * Structured JSON logger. Cloud Run ingests stdout JSON lines natively;+ * `severity` is mapped so log levels surface correctly in Cloud Logging.+ */+export const logger = pino({+ level: process.env.LOG_LEVEL ?? 'info',+ base: { service: 'hood-alerts' },+ formatters: {+ level(label) {+ const severity =+ { trace: 'DEBUG', debug: 'DEBUG', info: 'INFO', warn: 'WARNING', error: 'ERROR', fatal: 'CRITICAL' }[+ label+ ] ?? 'DEFAULT'+ return { level: label, severity }+ },+ },+})diff --git a/robinhood/hood-alerts/src/premium/paywall.ts b/robinhood/hood-alerts/src/premium/paywall.tsnew file mode 100644index 000000000..ef0f62d60--- /dev/null+++ b/robinhood/hood-alerts/src/premium/paywall.ts@@ -0,0 +1,122 @@+import { createPublicClient, createWalletClient, http, type Address } from 'viem'+import { privateKeyToAccount } from 'viem/accounts'+import { robinhood } from 'viem/chains'+import type { HoodBroadcaster, HoodConfirmer } from 'hood402'+import { PaywallEngine } from 'hood402/server'+import type { Config } from '../config.js'+import type { EntitlementRepo } from '../db/entitlements.js'+import type { Platform } from '../db/subscribers.js'++/** Outcome of a premium activation attempt. */+export type ActivationResult =+ | { status: 402; body: unknown }+ | { status: 200; body: unknown; settlementHeader: string }+ | { status: 503; body: unknown }++/**+ * The premium purchase flow on the hood402 rail (x402 `exact`/EIP-3009 USDG+ * on Robinhood Chain): a 402 challenge, verification, ON-CHAIN settlement,+ * and only then the entitlement flip. The entitlement never activates before+ * the USDG transfer settles, so a signature alone buys nothing.+ *+ * Settlement modes (from config):+ * - facilitator: HOOD402_FACILITATOR_URL delegates verify+settle (no gas key here)+ * - self-settle: HOOD402_SETTLER_KEY broadcasts `transferWithAuthorization` itself+ */+export class PremiumPaywall {+ private readonly engine: PaywallEngine | null++ constructor(+ private readonly config: Config,+ private readonly entitlements: EntitlementRepo,+ ) {+ this.engine = this.buildEngine()+ }++ /** True when this instance can actually sell premium. */+ get enabled(): boolean {+ return this.engine !== null+ }++ private buildEngine(): PaywallEngine | null {+ const { payTo, facilitatorUrl, settlerKey, premiumPriceUsdg, premiumDays } = this.config+ if (!payTo) return null+ const base = {+ price: premiumPriceUsdg,+ payTo,+ network: 'robinhood',+ description: `hood-alerts premium: ${premiumDays} days of unlimited real-time alerts`,+ }+ if (facilitatorUrl) return new PaywallEngine({ ...base, facilitator: facilitatorUrl })+ if (settlerKey) {+ const account = privateKeyToAccount(settlerKey)+ const transport = http(this.config.rpcUrl)+ const reader = createPublicClient({ chain: robinhood, transport })+ const wallet = createWalletClient({ chain: robinhood, transport, account })+ // hood402 is a local file: link with its own pinned viem; the client+ // identities differ only at compile time (patch-level viem skew), so the+ // structurally-correct clients are bridged to hood402's expected types.+ return new PaywallEngine({+ ...base,+ wallet: wallet as unknown as HoodBroadcaster,+ account: account.address as Address,+ reader: reader as unknown as HoodConfirmer,+ })+ }+ return null+ }++ /**+ * Handle one activation request. `paymentHeader` is the raw `X-PAYMENT`+ * value (undefined on the first, unpaid request, which earns the 402+ * challenge with full payment instructions).+ */+ async activate(+ platform: Platform,+ chatId: string,+ paymentHeader: string | undefined,+ resourceUrl: string,+ ): Promise<ActivationResult> {+ if (!this.engine) {+ return {+ status: 503,+ body: {+ error: 'premium purchases are not configured on this instance',+ fix: 'set HOOD402_PAY_TO plus HOOD402_FACILITATOR_URL or HOOD402_SETTLER_KEY',+ docs: 'https://nirholas.github.io/hood-alerts/self-host.html',+ },+ }+ }+ const auth = await this.engine.authorize(paymentHeader, resourceUrl)+ if (!auth.ok) return { status: 402, body: auth.body }++ const settlement = await this.engine.settle(auth.payload, auth.requirements)+ if (!settlement.success) {+ return {+ status: 402,+ body: {+ x402Version: 1,+ accepts: [auth.requirements],+ error: settlement.errorReason ?? 'settlement failed',+ },+ }+ }++ const entitlement = this.entitlements.activate(platform, chatId, this.config.premiumDays * 86_400, {+ ...(settlement.transaction ? { tx: settlement.transaction } : {}),+ ...(settlement.payer ? { payer: settlement.payer } : {}),+ })+ return {+ status: 200,+ settlementHeader: this.engine.settlementHeader(settlement),+ body: {+ activated: true,+ platform,+ chat: chatId,+ tier: 'premium',+ expiresAt: new Date(entitlement.expiresAt * 1000).toISOString(),+ transaction: settlement.transaction ?? null,+ },+ }+ }+}diff --git a/robinhood/hood-alerts/src/server.ts b/robinhood/hood-alerts/src/server.tsnew file mode 100644index 000000000..5f4e952e5--- /dev/null+++ b/robinhood/hood-alerts/src/server.ts@@ -0,0 +1,73 @@+import { Hono } from 'hono'+import { PAYMENT_HEADER } from 'hood402'+import type { Config } from './config.js'+import type { AlertEngine } from './engine/engine.js'+import type { LiveDetectors } from './engine/detectors/live.js'+import type { PremiumPaywall } from './premium/paywall.js'+import type { Platform } from './db/subscribers.js'++export interface ServerDeps {+ config: Config+ engine: AlertEngine+ detectors: LiveDetectors+ paywall: PremiumPaywall+ startedAt: number+}++/** Build the HTTP app: health, premium status, and the x402 activation endpoint. */+export function buildApp(deps: ServerDeps): Hono {+ const app = new Hono()++ app.get('/', (c) =>+ c.json({+ service: 'hood-alerts',+ chain: 4663,+ docs: 'https://nirholas.github.io/hood-alerts/',+ endpoints: ['/healthz', '/premium/status', '/premium/activate'],+ }),+ )++ app.get('/healthz', (c) => {+ const lastEventAt = deps.detectors.lastEventAt+ return c.json({+ ok: true,+ uptimeS: Math.floor(Date.now() / 1000) - deps.startedAt,+ lastEventAt: lastEventAt ? new Date(lastEventAt * 1000).toISOString() : null,+ eventCounts: deps.detectors.eventCounts,+ premiumPurchases: deps.paywall.enabled,+ })+ })++ 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+ return { 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)+ const entitlement = deps.engine.entitlements.get(target.platform, target.chat)+ const remaining = deps.engine.entitlements.remainingS(target.platform, target.chat)+ return c.json({+ platform: target.platform,+ chat: target.chat,+ tier: remaining > 0 ? 'premium' : 'free',+ expiresAt: entitlement && remaining > 0 ? new Date(entitlement.expiresAt * 1000).toISOString() : null,+ })+ })++ app.post('/premium/activate', async (c) => {+ const target = validTarget(c)+ if (!target) return c.json({ error: 'pass ?platform=telegram|discord&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)+ return c.json(result.body as Record<string, unknown>, 200)+ }+ return c.json(result.body as Record<string, unknown>, result.status)+ })++ return app+}diff --git a/robinhood/hood-alerts/src/transports/console.ts b/robinhood/hood-alerts/src/transports/console.tsnew file mode 100644index 000000000..7da11037f--- /dev/null+++ b/robinhood/hood-alerts/src/transports/console.ts@@ -0,0 +1,33 @@+import { logger } from '../logger.js'+import type { AlertEvent } from '../engine/events.js'+import { cardToText, digestCards, toCard } from '../format/cards.js'+import type { Transport } from './types.js'++/**+ * The console transport: alerts print as structured log lines. This is the+ * zero-config self-host smoke mode and what `npm run probe` uses to prove+ * live detection without any bot token.+ */+export class ConsoleTransport implements Transport {+ readonly platform = 'console' as const++ async sendAlert(chatId: string, event: AlertEvent): Promise<void> {+ logger.info({ chatId, alert: cardToText(toCard(event)), eventType: event.type }, 'alert')+ }++ async sendDigest(chatId: string, events: AlertEvent[]): Promise<void> {+ const digest = digestCards(events)+ logger.info(+ { chatId, title: digest.title, alerts: digest.cards.map(cardToText), omitted: digest.omitted },+ 'digest',+ )+ }++ async start(): Promise<void> {+ logger.info('console transport active (no bot tokens configured)')+ }++ async stop(): Promise<void> {+ // nothing to close+ }+}diff --git a/robinhood/hood-alerts/src/transports/discord.ts b/robinhood/hood-alerts/src/transports/discord.tsnew file mode 100644index 000000000..9ba78f234--- /dev/null+++ b/robinhood/hood-alerts/src/transports/discord.ts@@ -0,0 +1,162 @@+import {+ ChatInputCommandInteraction,+ Client,+ GatewayIntentBits,+ PermissionFlagsBits,+ REST,+ Routes,+ SlashCommandBuilder,+ type SlashCommandOptionsOnlyBuilder,+ type TextBasedChannel,+} from 'discord.js'+import { logger } from '../logger.js'+import type { Commands } from '../commands/commands.js'+import type { AlertEvent } from '../engine/events.js'+import { cardToDiscordEmbed, digestCards, toCard } from '../format/cards.js'+import type { Transport } from './types.js'++/**+ * Slash-command definitions, exported so tests can validate the registration+ * JSON offline (discord.js builders throw on invalid definitions at build+ * time, which is the platform's local validation path).+ */+export function buildSlashCommands(): Array<SlashCommandBuilder | SlashCommandOptionsOnlyBuilder> {+ const watch = new SlashCommandBuilder()+ .setName('watch')+ .setDescription('Watch launches, whales, a Stock Token ticker, or a token address')+ .addStringOption((o) =>+ o+ .setName('what')+ .setDescription('launches | graduations | whales | premiums | rugs | TSLA | 0x…')+ .setRequired(true),+ )+ .addNumberOption((o) => o.setName('threshold').setDescription('USD for whales/tokens, percent for premiums/rugs/stocks'))+ const unwatch = new SlashCommandBuilder()+ .setName('unwatch')+ .setDescription('Stop watching something')+ .addStringOption((o) => o.setName('what').setDescription('The watch target, or "all"').setRequired(true))+ const list = new SlashCommandBuilder().setName('list').setDescription('Your subscriptions and settings')+ const threshold = new SlashCommandBuilder()+ .setName('threshold')+ .setDescription('Change a subscription threshold')+ .addStringOption((o) => o.setName('what').setDescription('The watch target').setRequired(true))+ .addNumberOption((o) => o.setName('value').setDescription('New threshold').setRequired(true))+ const digest = new SlashCommandBuilder()+ .setName('digest')+ .setDescription('Batch alerts into periodic digests')+ .addStringOption((o) =>+ o.setName('mode').setDescription('on or off').setRequired(true).addChoices({ name: 'on', value: 'on' }, { name: 'off', value: 'off' }),+ )+ .addIntegerOption((o) => o.setName('minutes').setDescription('Digest interval in minutes (default 60)'))+ const quiet = new SlashCommandBuilder()+ .setName('quiet')+ .setDescription('Quiet hours in UTC (alerts batch and deliver after)')+ .addIntegerOption((o) => o.setName('from').setDescription('Start hour UTC 0-23'))+ .addIntegerOption((o) => o.setName('to').setDescription('End hour UTC 0-23'))+ .addStringOption((o) => o.setName('mode').setDescription('"off" to disable').addChoices({ name: 'off', value: 'off' }))+ const premium = new SlashCommandBuilder().setName('premium').setDescription('Premium status and upgrade')+ const help = new SlashCommandBuilder().setName('help').setDescription('Full command reference')+ return [watch, unwatch, list, threshold, digest, quiet, premium, help]+}++/** Map a Discord interaction onto the shared (command, args) shape. */+export function interactionToCommand(i: ChatInputCommandInteraction): { command: string; args: string[] } {+ const name = i.commandName+ const args: string[] = []+ if (name === 'watch') {+ args.push(i.options.getString('what', true))+ const t = i.options.getNumber('threshold')+ if (t !== null) args.push(String(t))+ } else if (name === 'unwatch') {+ args.push(i.options.getString('what', true))+ } else if (name === 'threshold') {+ args.push(i.options.getString('what', true), String(i.options.getNumber('value', true)))+ } else if (name === 'digest') {+ args.push(i.options.getString('mode', true))+ const m = i.options.getInteger('minutes')+ if (m !== null) args.push(String(m))+ } else if (name === 'quiet') {+ const mode = i.options.getString('mode')+ if (mode === 'off') args.push('off')+ else {+ const from = i.options.getInteger('from')+ const to = i.options.getInteger('to')+ if (from !== null) args.push(String(from))+ if (to !== null) args.push(String(to))+ }+ }+ return { command: name, args }+}++export class DiscordTransport implements Transport {+ readonly platform = 'discord' as const+ private readonly client: Client+ private readonly rest: REST++ constructor(+ private readonly token: string,+ private readonly appId: string,+ commands: Commands,+ ) {+ this.client = new Client({ intents: [GatewayIntentBits.Guilds] })+ this.rest = new REST({ version: '10' }).setToken(token)++ this.client.on('interactionCreate', async (interaction) => {+ if (!interaction.isChatInputCommand()) return+ try {+ const { command, args } = interactionToCommand(interaction)+ const isAdmin =+ interaction.inGuild() === false ||+ interaction.memberPermissions?.has(PermissionFlagsBits.ManageGuild) === true+ const reply = commands.handle(+ {+ platform: 'discord',+ chatId: interaction.channelId,+ ...(interaction.guild ? { chatTitle: interaction.guild.name } : {}),+ isGroup: interaction.inGuild(),+ isAdmin,+ },+ command,+ args,+ )+ await interaction.reply({ content: reply.text, ephemeral: command === 'premium' })+ } catch (error) {+ logger.error({ err: String(error) }, 'discord interaction failed')+ if (interaction.isRepliable() && !interaction.replied) {+ await interaction.reply({ content: 'Something went wrong handling that command. Try again.', ephemeral: true }).catch(() => undefined)+ }+ }+ })+ this.client.on('error', (error) => logger.error({ err: String(error) }, 'discord client error'))+ }++ private async channel(chatId: string): Promise<TextBasedChannel> {+ const ch = await this.client.channels.fetch(chatId)+ if (!ch || !ch.isTextBased() || !('send' in ch)) throw new Error(`channel ${chatId} is not sendable`)+ return ch+ }++ async sendAlert(chatId: string, event: AlertEvent): Promise<void> {+ const ch = await this.channel(chatId)+ if ('send' in ch) await ch.send({ embeds: [cardToDiscordEmbed(toCard(event))] })+ }++ async sendDigest(chatId: string, events: AlertEvent[]): Promise<void> {+ const digest = digestCards(events)+ const ch = await this.channel(chatId)+ const embeds = digest.cards.slice(0, 10).map(cardToDiscordEmbed)+ const content = digest.omitted > 0 ? `${digest.title} (${digest.omitted} omitted)` : digest.title+ if ('send' in ch) await ch.send({ content, embeds })+ }++ async start(): Promise<void> {+ const body = buildSlashCommands().map((c) => c.toJSON())+ await this.rest.put(Routes.applicationCommands(this.appId), { body })+ await this.client.login(this.token)+ logger.info({ appId: this.appId }, 'discord bot online')+ }++ async stop(): Promise<void> {+ await this.client.destroy()+ }+}diff --git a/robinhood/hood-alerts/src/transports/telegram.ts b/robinhood/hood-alerts/src/transports/telegram.tsnew file mode 100644index 000000000..be6d3db24--- /dev/null+++ b/robinhood/hood-alerts/src/transports/telegram.ts@@ -0,0 +1,117 @@+import { Bot, type Context } from 'grammy'+import { logger } from '../logger.js'+import type { Commands } from '../commands/commands.js'+import type { AlertEvent } from '../engine/events.js'+import { cardToTelegramHtml, digestCards, toCard } from '../format/cards.js'+import type { Transport } from './types.js'++const COMMANDS = ['start', 'help', 'watch', 'unwatch', 'list', 'threshold', 'digest', 'quiet', 'premium'] as const++const COMMAND_DESCRIPTIONS: Record<(typeof COMMANDS)[number], string> = {+ start: 'What this bot does',+ help: 'Full command reference',+ watch: 'Watch launches, whales, a ticker, or a token address',+ unwatch: 'Stop watching something (or all)',+ list: 'Your subscriptions and settings',+ threshold: 'Change a subscription threshold',+ digest: 'Batch alerts into digests: digest on 60',+ quiet: 'Quiet hours in UTC: quiet 22 7',+ premium: 'Premium status and upgrade',+}++/**+ * Telegram transport (grammY, long polling). Group chats restrict config+ * commands to admins; alerts render as HTML cards with preview disabled.+ *+ * `buildTelegramBot` is separated from the transport so tests can exercise the+ * full update-handling path offline via `bot.handleUpdate()` with an api+ * transformer capturing outgoing calls (grammY's documented testing pattern).+ */+export function buildTelegramBot(token: string, commands: Commands): Bot {+ const bot = new Bot(token)++ const isAdmin = async (ctx: Context): Promise<boolean> => {+ if (ctx.chat?.type === 'private') return true+ if (!ctx.chat || !ctx.from) return false+ try {+ const member = await ctx.getChatMember(ctx.from.id)+ return member.status === 'administrator' || member.status === 'creator'+ } catch {+ return false+ }+ }++ for (const command of COMMANDS) {+ bot.command(command, async (ctx) => {+ const args = (ctx.match ?? '').trim().split(/\s+/).filter(Boolean)+ const reply = commands.handle(+ {+ platform: 'telegram',+ chatId: String(ctx.chat.id),+ ...(ctx.chat.type === 'private'+ ? ctx.from?.username+ ? { chatTitle: ctx.from.username }+ : {}+ : { chatTitle: ctx.chat.title }),+ isGroup: ctx.chat.type !== 'private',+ isAdmin: await isAdmin(ctx),+ },+ command,+ args,+ )+ await ctx.reply(reply.text, { link_preview_options: { is_disabled: true } })+ })+ }++ // Unknown slash commands get help, not silence.+ bot.on('message:text', async (ctx) => {+ const text = ctx.message.text+ if (!text.startsWith('/')) return+ const name = text.slice(1).split(/[\s@]/)[0] ?? ''+ if ((COMMANDS as readonly string[]).includes(name)) return+ await ctx.reply(`Unknown command /${name}. Try /help`)+ })++ bot.catch((err) => logger.error({ err: String(err.error) }, 'telegram update error'))+ return bot+}++export class TelegramTransport implements Transport {+ readonly platform = 'telegram' as const+ private readonly bot: Bot++ constructor(token: string, commands: Commands) {+ this.bot = buildTelegramBot(token, commands)+ }++ async sendAlert(chatId: string, event: AlertEvent): Promise<void> {+ await this.bot.api.sendMessage(chatId, cardToTelegramHtml(toCard(event)), {+ parse_mode: 'HTML',+ link_preview_options: { is_disabled: true },+ })+ }++ async sendDigest(chatId: string, events: AlertEvent[]): Promise<void> {+ const digest = digestCards(events)+ const blocks = digest.cards.map(cardToTelegramHtml)+ const omitted = digest.omitted > 0 ? `\n\n…and ${digest.omitted} more.` : ''+ await this.bot.api.sendMessage(chatId, `<b>${digest.title}</b>\n\n${blocks.join('\n\n')}${omitted}`, {+ parse_mode: 'HTML',+ link_preview_options: { is_disabled: true },+ })+ }++ async start(): Promise<void> {+ await this.bot.api.setMyCommands(+ COMMANDS.map((c) => ({ command: c, description: COMMAND_DESCRIPTIONS[c] })),+ )+ // Long polling in the background; runner errors restart via bot.start's internals.+ void this.bot.start({+ onStart: (me) => logger.info({ username: me.username }, 'telegram bot online'),+ })+ }++ async stop(): Promise<void> {+ await this.bot.stop()+ }+}diff --git a/robinhood/hood-alerts/src/transports/types.ts b/robinhood/hood-alerts/src/transports/types.tsnew file mode 100644index 000000000..192b6eff5--- /dev/null+++ b/robinhood/hood-alerts/src/transports/types.ts@@ -0,0 +1,15 @@+import type { Platform } from '../db/subscribers.js'+import type { AlertEvent } from '../engine/events.js'++/** A delivery channel: Telegram, Discord, or the console (self-host smoke mode). */+export interface Transport {+ readonly platform: Platform+ /** Deliver one alert to a chat/channel. Throws on failure (engine logs it). */+ sendAlert(chatId: string, event: AlertEvent): Promise<void>+ /** Deliver a batched digest. */+ sendDigest(chatId: string, events: AlertEvent[]): Promise<void>+ /** Start receiving commands (long-poll/gateway). */+ start(): Promise<void>+ /** Graceful shutdown. */+ stop(): Promise<void>+}diff --git a/robinhood/hood-alerts/tests/cards.test.ts b/robinhood/hood-alerts/tests/cards.test.tsnew file mode 100644index 000000000..bd39aa7eb--- /dev/null+++ b/robinhood/hood-alerts/tests/cards.test.ts@@ -0,0 +1,140 @@+import { describe, expect, it } from 'vitest'+import { cardToDiscordEmbed, cardToText, cardToTelegramHtml, digestCards, short, toCard, usd } from '../src/format/cards.js'+import type { AlertEvent } from '../src/engine/events.js'++const TOKEN = '0x1234567890123456789012345678901234567890' as `0x${string}`++describe('usd', () => {+ it('formats millions, thousands, and small amounts', () => {+ expect(usd(2_500_000)).toBe('$2.50M')+ expect(usd(5_400)).toBe('$5.4k')+ expect(usd(42.5)).toBe('$42.50')+ })+})++describe('short', () => {+ it('elides the middle of an address', () => {+ expect(short(TOKEN)).toBe('0x1234…7890')+ })+})++describe('toCard', () => {+ it('renders a launch event', () => {+ const e: AlertEvent = { type: 'launch', launchpad: 'noxa', token: TOKEN, symbol: 'FOO', name: 'Foo Coin', creator: TOKEN, pool: TOKEN, blockNumber: 5n, transactionHash: '0xabc', at: 0 }+ const card = toCard(e)+ expect(card.severity).toBe('info')+ expect(card.title).toBe('New launch: FOO')+ expect(card.lines).toContain('Foo Coin')+ expect(card.lines).toContain('Launchpad: NOXA (instant v3 pool)')+ expect(card.lines.some((l) => l.startsWith('Pool:'))).toBe(true)+ expect(card.links.find((l) => l.label === 'Tx')?.url).toContain('0xabc')+ })++ it('renders a launch with no pool as still-curving', () => {+ const e: AlertEvent = { type: 'launch', launchpad: 'odyssey', token: TOKEN, symbol: null, name: null, creator: TOKEN, pool: null, blockNumber: 1n, transactionHash: '0x1', at: 0 }+ const card = toCard(e)+ expect(card.title).toBe(`New launch: ${short(TOKEN)}`)+ expect(card.lines).toContain('Trading on the curve until graduation')+ })++ it('renders a graduation event', () => {+ const e: AlertEvent = { type: 'graduation', token: TOKEN, symbol: 'FOO', name: null, pool: TOKEN, blockNumber: 1n, transactionHash: '0x1', at: 0 }+ const card = toCard(e)+ expect(card.severity).toBe('notice')+ expect(card.title).toBe('Graduated: FOO')+ })++ it('renders a whale event with usd and venue formatting', () => {+ const e: AlertEvent = { type: 'whale', source: 'odyssey-curve', token: TOKEN, symbol: 'FOO', side: 'sell', usd: 12_500, trader: TOKEN, blockNumber: 1n, transactionHash: '0x1', at: 0 }+ const card = toCard(e)+ expect(card.title).toBe('Whale sell: $12.5k of FOO')+ expect(card.lines).toContain('Venue: Odyssey bonding curve')+ expect(card.links.some((l) => l.label === 'Trader')).toBe(true)+ })++ it('renders a price_move event, up and down', () => {+ const up: AlertEvent = { type: 'price_move', symbol: 'TSLA', pct: 3.456, fromUsd: 100, toUsd: 103.456, windowS: 900, at: 0 }+ const down: AlertEvent = { type: 'price_move', symbol: 'TSLA', pct: -3.456, fromUsd: 103.456, toUsd: 100, windowS: 900, at: 0 }+ expect(toCard(up).title).toBe('TSLA up 3.46% in 15m')+ expect(toCard(down).title).toBe('TSLA down 3.46% in 15m')+ })++ it('renders a premium event, premium and discount', () => {+ const premium: AlertEvent = { type: 'premium', symbol: 'TSLA', token: TOKEN, premiumPct: 4.2, level: 4, direction: 'premium', dexUsd: 104.2, feedUsd: 100, pool: TOKEN, at: 0 }+ const discount: AlertEvent = { type: 'premium', symbol: 'TSLA', token: TOKEN, premiumPct: -4.2, level: 4, direction: 'discount', dexUsd: 95.8, feedUsd: 100, pool: TOKEN, at: 0 }+ expect(toCard(premium).title).toBe('TSLA trades at a 4.20% premium on-chain')+ expect(toCard(discount).title).toBe('TSLA trades at a 4.20% discount on-chain')+ expect(toCard(discount).lines[1]).toMatch(/below its oracle price/)+ })++ it('renders a holders event with locale-formatted counts', () => {+ const e: AlertEvent = { type: 'holders', token: TOKEN, symbol: 'FOO', milestone: 10_000, count: 10_042, at: 0 }+ const card = toCard(e)+ expect(card.title).toBe('FOO crossed 10,000 holders')+ expect(card.lines).toEqual(['Now at 10,042 holders.'])+ })++ it('renders a liquidity_pull event, with and without a known token', () => {+ const withToken: AlertEvent = { type: 'liquidity_pull', token: TOKEN, symbol: 'FOO', pool: TOKEN, quoteAsset: 'USDG', droppedPct: 42.3, beforeUsd: 100_000, afterUsd: 57_700, at: 0 }+ const card = toCard(withToken)+ expect(card.severity).toBe('warning')+ expect(card.title).toBe(`Liquidity pull: FOO (${short(TOKEN)})`)+ expect(card.lines[0]).toContain('USDG reserves dropped 42.3%')+ expect(card.links.some((l) => l.label === 'Token')).toBe(true)++ const withoutToken: AlertEvent = { type: 'liquidity_pull', token: null, symbol: null, pool: TOKEN, quoteAsset: 'WETH', droppedPct: 10, beforeUsd: 1, afterUsd: 0.9, at: 0 }+ const card2 = toCard(withoutToken)+ expect(card2.title).toBe(`Liquidity pull: ${short(TOKEN)}`)+ expect(card2.links.some((l) => l.label === 'Token')).toBe(false)+ })+})++describe('cardToText / cardToTelegramHtml / cardToDiscordEmbed', () => {+ const card = toCard({ type: 'graduation', token: TOKEN, symbol: 'FOO', name: null, pool: TOKEN, blockNumber: 1n, transactionHash: '0x1', at: 0 })++ it('cardToText joins title, lines, and labeled links', () => {+ const text = cardToText(card)+ expect(text.startsWith('Graduated: FOO\n')).toBe(true)+ expect(text).toContain('Chart: ')+ })++ it('cardToTelegramHtml bolds the title and escapes HTML', () => {+ const unsafe = toCard({ type: 'holders', token: TOKEN, symbol: '<Foo & Bar>', milestone: 1, count: 1, at: 0 })+ const html = cardToTelegramHtml(unsafe)+ expect(html).toContain('<b><Foo & Bar> crossed 1 holders</b>')+ expect(html).not.toContain('<Foo & Bar>')+ })++ it('cardToDiscordEmbed maps severity to color and formats markdown links', () => {+ const warning = toCard({ type: 'liquidity_pull', token: null, symbol: null, pool: TOKEN, quoteAsset: 'USDG', droppedPct: 50, beforeUsd: 2, afterUsd: 1, at: 0 })+ const embed = cardToDiscordEmbed(warning)+ expect(embed.color).toBe(0xe5484d)+ expect(embed.footer).toEqual({ text: 'hood-alerts · Robinhood Chain 4663' })+ expect(embed.description).toContain(`[Pool](`)++ const notice = cardToDiscordEmbed(card)+ expect(notice.color).toBe(0x30a46c)+ const info = cardToDiscordEmbed(toCard({ type: 'holders', token: TOKEN, symbol: null, milestone: 1, count: 1, at: 0 }))+ expect(info.color).toBe(0x5b5bd6)+ })+})++describe('digestCards', () => {+ function holdersEvent(i: number): AlertEvent {+ return { type: 'holders', token: TOKEN, symbol: `T${i}`, milestone: i, count: i, at: 0 }+ }++ it('titles by count and caps rendered cards at 10 with an omitted count', () => {+ const events = Array.from({ length: 13 }, (_, i) => holdersEvent(i))+ const digest = digestCards(events)+ expect(digest.title).toBe('Digest: 13 alerts')+ expect(digest.cards).toHaveLength(10)+ expect(digest.omitted).toBe(3)+ })++ it('uses singular phrasing for exactly one alert and omits nothing under 10', () => {+ const digest = digestCards([holdersEvent(1)])+ expect(digest.title).toBe('Digest: 1 alert')+ expect(digest.omitted).toBe(0)+ })+})diff --git a/robinhood/hood-alerts/tests/commands.test.ts b/robinhood/hood-alerts/tests/commands.test.tsnew file mode 100644index 000000000..565452bf9--- /dev/null+++ b/robinhood/hood-alerts/tests/commands.test.ts@@ -0,0 +1,327 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { openDb, type Db } from '../src/db/index.js'+import { EntitlementRepo } from '../src/db/entitlements.js'+import { SubscriberRepo } from '../src/db/subscribers.js'+import { Commands, FREE_MAX_SUBSCRIPTIONS, type CommandContext } from '../src/commands/commands.js'+import type { Config } from '../src/config.js'++function makeConfig(overrides: Partial<Config> = {}): Config {+ return {+ rpcUrl: undefined,+ dbPath: ':memory:',+ port: 8080,+ publicUrl: 'http://localhost:8080',+ telegramToken: null,+ discordToken: null,+ discordAppId: null,+ premiumRail: 'hood402',+ payTo: null,+ facilitatorUrl: null,+ settlerKey: null,+ premiumPriceUsdg: '5',+ premiumDays: 30,+ detectors: {+ whaleFloorUsd: 1000,+ whaleDefaultUsd: 5000,+ priceWindowS: 900,+ priceDefaultPct: 2,+ premiumPollS: 60,+ premiumDefaultPct: 2,+ rugDefaultPct: 30,+ },+ ...overrides,+ }+}++function ctx(overrides: Partial<CommandContext> = {}): CommandContext {+ return { platform: 'telegram', chatId: 'chat-1', isGroup: false, isAdmin: false, ...overrides }+}++let db: Db+let subscribers: SubscriberRepo+let entitlements: EntitlementRepo+let notified: number+let commands: Commands++function build(configOverrides: Partial<Config> = {}): Commands {+ return new Commands({+ subscribers,+ entitlements,+ config: makeConfig(configOverrides),+ notifyWatchChange: () => {+ notified += 1+ },+ })+}++beforeEach(() => {+ db = openDb(':memory:')+ subscribers = new SubscriberRepo(db)+ entitlements = new EntitlementRepo(db)+ notified = 0+ commands = build()+})++afterEach(() => {+ db.close()+})++describe('Commands.handle: start/help/unknown', () => {+ it('start greets and points at help', () => {+ expect(commands.handle(ctx(), 'start', []).text).toMatch(/You watch nothing yet/)+ })++ it('help lists every command and the free tier cap', () => {+ const text = commands.handle(ctx(), 'help', []).text+ expect(text).toContain('watch <what>')+ expect(text).toContain(`Free tier: ${FREE_MAX_SUBSCRIPTIONS} subscriptions`)+ })++ it('an unknown command points at help', () => {+ expect(commands.handle(ctx(), 'nonsense', []).text).toBe('Unknown command "nonsense". Try: help')+ })+})++describe('Commands.handle: watch', () => {+ it('prompts with examples when called with no args', () => {+ expect(commands.handle(ctx(), 'watch', []).text).toMatch(/What should I watch/)+ })++ it('subscribes to a fixed topic with its default threshold', () => {+ const reply = commands.handle(ctx(), 'watch', ['whales'])+ expect(reply.text).toBe('Watching whales >= $5,000.')+ const s = subscribers.get('telegram', 'chat-1')+ expect(s).not.toBeNull()+ expect(subscribers.list(s!.id)).toEqual([expect.objectContaining({ topic: 'whales', threshold: 5000 })])+ })++ it('accepts an explicit threshold', () => {+ const reply = commands.handle(ctx(), 'watch', ['whales', '25000'])+ expect(reply.text).toBe('Watching whales >= $25,000.')+ })++ it('applies the "watch launches noxa/odyssey" sugar', () => {+ expect(commands.handle(ctx(), 'watch', ['launches', 'noxa']).text).toBe('Watching launches (noxa).')+ const s = subscribers.get('telegram', 'chat-1')!+ expect(subscribers.list(s.id)[0]?.topic).toBe('launches:noxa')+ })++ it('rejects an unwatchable target with the resolver error', () => {+ const reply = commands.handle(ctx(), 'watch', ['!!!'])+ expect(reply.text).toMatch(/Cannot watch/)+ })++ it('gates premium-only topics for free-tier subscribers', () => {+ const reply = commands.handle(ctx(), 'watch', ['premiums'])+ expect(reply.text).toMatch(/premium detector/)+ expect(reply.text).toMatch(/Stock Token arbitrage signal/)+ const s = subscribers.get('telegram', 'chat-1')+ expect(s).toBeNull() // never got as far as ensure()+ })++ it('allows a premium subscriber to watch a premium-only topic', () => {+ entitlements.activate('telegram', 'chat-1', 86_400)+ const reply = commands.handle(ctx(), 'watch', ['rugs'])+ expect(reply.text).toBe('Watching liquidity pulls >= 30%.')+ })++ it('caps free-tier subscriptions at FREE_MAX_SUBSCRIPTIONS', () => {+ commands.handle(ctx(), 'watch', ['whales'])+ commands.handle(ctx(), 'watch', ['launches'])+ commands.handle(ctx(), 'watch', ['graduations'])+ const reply = commands.handle(ctx(), 'watch', ['TSLA'])+ expect(reply.text).toMatch(/Free tier is capped at 3 subscriptions/)+ })++ it('premium subscribers are not capped', () => {+ entitlements.activate('telegram', 'chat-1', 86_400)+ commands.handle(ctx(), 'watch', ['whales'])+ commands.handle(ctx(), 'watch', ['launches'])+ commands.handle(ctx(), 'watch', ['graduations'])+ const reply = commands.handle(ctx(), 'watch', ['TSLA'])+ expect(reply.text).toBe('Watching TSLA (moves/premium >= 2%).')+ })++ it('watching a token topic notifies the watch-change callback', () => {+ const addr = '0x1234567890123456789012345678901234567890'+ commands.handle(ctx(), 'watch', [addr])+ expect(notified).toBe(1)+ })++ it('watching a non-token topic does not notify', () => {+ commands.handle(ctx(), 'watch', ['whales'])+ expect(notified).toBe(0)+ })++ it('requires admin in a group chat', () => {+ const reply = commands.handle(ctx({ isGroup: true, isAdmin: false }), 'watch', ['whales'])+ expect(reply.text).toBe('Only group admins can change alert settings here.')+ })++ it('allows a group admin', () => {+ const reply = commands.handle(ctx({ isGroup: true, isAdmin: true }), 'watch', ['whales'])+ expect(reply.text).toBe('Watching whales >= $5,000.')+ })+})++describe('Commands.handle: unwatch', () => {+ it('says nothing watched yet if the subscriber has never subscribed', () => {+ expect(commands.handle(ctx(), 'unwatch', ['whales']).text).toMatch(/You watch nothing yet/)+ })++ it('prompts for a target when called with no args and something is watched', () => {+ commands.handle(ctx(), 'watch', ['whales'])+ expect(commands.handle(ctx(), 'unwatch', []).text).toMatch(/Unwatch what\?/)+ })++ it('removes a specific subscription', () => {+ commands.handle(ctx(), 'watch', ['whales'])+ const reply = commands.handle(ctx(), 'unwatch', ['whales'])+ expect(reply.text).toBe('Stopped watching whales >= $0.')+ })++ it('reports when the target was never watched', () => {+ commands.handle(ctx(), 'watch', ['whales'])+ const reply = commands.handle(ctx(), 'unwatch', ['launches'])+ expect(reply.text).toMatch(/You were not watching launches/)+ })++ it('unwatch all removes everything and reports the count', () => {+ commands.handle(ctx(), 'watch', ['whales'])+ commands.handle(ctx(), 'watch', ['launches'])+ const reply = commands.handle(ctx(), 'unwatch', ['all'])+ expect(reply.text).toBe('Removed 2 subscriptions.')+ expect(commands.handle(ctx(), 'list', []).text).toMatch(/You watch nothing yet/)+ })++ it('unwatching a token topic notifies the watch-change callback', () => {+ const addr = '0x1234567890123456789012345678901234567890'+ commands.handle(ctx(), 'watch', [addr])+ notified = 0+ commands.handle(ctx(), 'unwatch', [addr])+ expect(notified).toBe(1)+ })+})++describe('Commands.handle: list', () => {+ it('reports nothing watched for a fresh chat', () => {+ expect(commands.handle(ctx(), 'list', []).text).toMatch(/You watch nothing yet/)+ })++ it('lists subscriptions with tier/digest/quiet settings', () => {+ commands.handle(ctx(), 'watch', ['whales', '5000'])+ const reply = commands.handle(ctx(), 'list', [])+ expect(reply.text).toContain('1. whales >= $5,000')+ expect(reply.text).toContain('tier: free (1/3)')+ expect(reply.text).toContain('digest: off')+ expect(reply.text).toContain('quiet: off')+ })++ it('reflects premium tier and custom digest/quiet settings', () => {+ entitlements.activate('telegram', 'chat-1', 86_400)+ commands.handle(ctx(), 'watch', ['whales'])+ commands.handle(ctx(), 'digest', ['on', '90'])+ commands.handle(ctx(), 'quiet', ['22', '7'])+ const reply = commands.handle(ctx(), 'list', [])+ expect(reply.text).toContain('tier: premium')+ expect(reply.text).toContain('digest: every 90m')+ expect(reply.text).toContain('quiet: 22:00-7:00 UTC')+ })+})++describe('Commands.handle: threshold', () => {+ it('requires two args', () => {+ expect(commands.handle(ctx(), 'threshold', ['whales']).text).toMatch(/Usage: threshold/)+ })++ it('errors when the subscriber has no subscriptions at all', () => {+ expect(commands.handle(ctx(), 'threshold', ['whales', '1']).text).toMatch(/You watch nothing yet/)+ })++ it('errors on a non-positive value', () => {+ commands.handle(ctx(), 'watch', ['whales'])+ expect(commands.handle(ctx(), 'threshold', ['whales', '-5']).text).toBe('"-5" is not a positive number.')+ })++ it('errors when not watching that specific target', () => {+ commands.handle(ctx(), 'watch', ['whales'])+ expect(commands.handle(ctx(), 'threshold', ['launches', '1']).text).toMatch(/You are not watching launches/)+ })++ it('updates an existing subscription threshold', () => {+ commands.handle(ctx(), 'watch', ['whales'])+ const reply = commands.handle(ctx(), 'threshold', ['whales', '99000'])+ expect(reply.text).toBe('Updated: whales >= $99,000.')+ })+})++describe('Commands.handle: digest', () => {+ it('rejects an invalid mode', () => {+ expect(commands.handle(ctx(), 'digest', ['maybe']).text).toMatch(/Usage: digest on/)+ })++ it('turns digest on with a default of 60 minutes', () => {+ expect(commands.handle(ctx(), 'digest', ['on']).text).toBe('Digest on: alerts batch every 60 minutes.')+ })++ it('turns digest on with a custom interval', () => {+ expect(commands.handle(ctx(), 'digest', ['on', '15']).text).toBe('Digest on: alerts batch every 15 minutes.')+ })++ it('rejects an out-of-range interval', () => {+ expect(commands.handle(ctx(), 'digest', ['on', '0']).text).toMatch(/1-1440 minutes/)+ expect(commands.handle(ctx(), 'digest', ['on', '1441']).text).toMatch(/1-1440 minutes/)+ })++ it('turns digest off', () => {+ commands.handle(ctx(), 'digest', ['on'])+ expect(commands.handle(ctx(), 'digest', ['off']).text).toMatch(/Digest off/)+ })+})++describe('Commands.handle: quiet', () => {+ it('sets a quiet window', () => {+ expect(commands.handle(ctx(), 'quiet', ['22', '7']).text).toBe('Quiet hours set: 22:00-7:00 UTC. Alerts batch and deliver after.')+ })++ it('rejects an out-of-range or non-integer hour', () => {+ expect(commands.handle(ctx(), 'quiet', ['24', '7']).text).toMatch(/Usage: quiet/)+ expect(commands.handle(ctx(), 'quiet', ['a', '7']).text).toMatch(/Usage: quiet/)+ })++ it('turns quiet hours off', () => {+ commands.handle(ctx(), 'quiet', ['22', '7'])+ expect(commands.handle(ctx(), 'quiet', ['off']).text).toBe('Quiet hours off.')+ })+})++describe('Commands.handle: premium', () => {+ it('reports free tier and unconfigured purchases by default', () => {+ const reply = commands.handle(ctx(), 'premium', [])+ expect(reply.text).toMatch(/You are on the free tier/)+ expect(reply.text).toMatch(/not configured on this instance/)+ })++ it('reports remaining days when active', () => {+ entitlements.activate('telegram', 'chat-1', 3 * 86_400)+ const reply = commands.handle(ctx(), 'premium', [])+ expect(reply.text).toMatch(/Premium active: 3 days left/)+ })++ it('gives purchase instructions when a facilitator is configured', () => {+ commands = build({ payTo: '0x4022de2D36C334E73C7a108805Cea11C0564f402', facilitatorUrl: 'https://facilitator.example' })+ const reply = commands.handle(ctx(), 'premium', [])+ expect(reply.text).toMatch(/POST http:\/\/localhost:8080\/premium\/activate\?platform=telegram&chat=chat-1/)+ expect(reply.text).toMatch(/5 USDG for 30 days/)+ })++ it('gives purchase instructions when a settler key is configured', () => {+ commands = build({ payTo: '0x4022de2D36C334E73C7a108805Cea11C0564f402', settlerKey: '0xdeadbeef' as `0x${string}` })+ expect(commands.handle(ctx(), 'premium', []).text).toMatch(/POST /)+ })++ it('premium status is readable without admin rights in a group', () => {+ const reply = commands.handle(ctx({ isGroup: true, isAdmin: false }), 'premium', [])+ expect(reply.text).toMatch(/free tier/)+ })+})diff --git a/robinhood/hood-alerts/tests/config.test.ts b/robinhood/hood-alerts/tests/config.test.tsnew file mode 100644index 000000000..1e3bc5b09--- /dev/null+++ b/robinhood/hood-alerts/tests/config.test.ts@@ -0,0 +1,117 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { loadConfig } from '../src/config.js'++const ENV_KEYS = [+ 'HOOD_ALERTS_RPC_URL',+ 'HOOD_ALERTS_DB',+ 'PORT',+ 'HOOD_ALERTS_PUBLIC_URL',+ 'HOOD_ALERTS_TELEGRAM_TOKEN',+ 'HOOD_ALERTS_DISCORD_TOKEN',+ 'HOOD_ALERTS_DISCORD_APP_ID',+ 'HOOD_ALERTS_PREMIUM_RAIL',+ 'HOOD402_PAY_TO',+ 'HOOD402_FACILITATOR_URL',+ 'HOOD402_SETTLER_KEY',+ 'HOOD_ALERTS_PREMIUM_PRICE_USDG',+ 'HOOD_ALERTS_PREMIUM_DAYS',+ 'HOOD_ALERTS_WHALE_FLOOR_USD',+ 'HOOD_ALERTS_WHALE_DEFAULT_USD',+ 'HOOD_ALERTS_PRICE_WINDOW_S',+ 'HOOD_ALERTS_PRICE_DEFAULT_PCT',+ 'HOOD_ALERTS_PREMIUM_POLL_S',+ 'HOOD_ALERTS_PREMIUM_DEFAULT_PCT',+ 'HOOD_ALERTS_RUG_DEFAULT_PCT',+]++let saved: Record<string, string | undefined> = {}++beforeEach(() => {+ saved = {}+ for (const key of ENV_KEYS) {+ saved[key] = process.env[key]+ delete process.env[key]+ }+})++afterEach(() => {+ for (const key of ENV_KEYS) {+ if (saved[key] === undefined) delete process.env[key]+ else process.env[key] = saved[key]+ }+})++describe('loadConfig', () => {+ it('resolves sane defaults with zero env vars set', () => {+ const config = loadConfig()+ expect(config.rpcUrl).toBeUndefined()+ expect(config.dbPath).toBe('./data/hood-alerts.db')+ expect(config.port).toBe(8080)+ expect(config.publicUrl).toBe('http://localhost:8080')+ expect(config.telegramToken).toBeNull()+ expect(config.discordToken).toBeNull()+ expect(config.premiumRail).toBe('hood402')+ expect(config.payTo).toBeNull()+ expect(config.premiumPriceUsdg).toBe('5')+ expect(config.premiumDays).toBe(30)+ expect(config.detectors).toEqual({+ whaleFloorUsd: 1000,+ whaleDefaultUsd: 5000,+ priceWindowS: 900,+ priceDefaultPct: 2,+ premiumPollS: 60,+ premiumDefaultPct: 2,+ rugDefaultPct: 30,+ })+ })++ it('derives publicUrl from a custom port when not explicitly set', () => {+ process.env.PORT = '9090'+ expect(loadConfig().publicUrl).toBe('http://localhost:9090')+ })++ it('an explicit publicUrl overrides the derived default', () => {+ process.env.HOOD_ALERTS_PUBLIC_URL = 'https://alerts.example.com'+ expect(loadConfig().publicUrl).toBe('https://alerts.example.com')+ })++ it('rejects a premium rail other than hood402', () => {+ process.env.HOOD_ALERTS_PREMIUM_RAIL = 'x402-usdc'+ expect(() => loadConfig()).toThrow(/not implemented/)+ })++ it('rejects a malformed HOOD402_PAY_TO', () => {+ process.env.HOOD402_PAY_TO = 'not-an-address'+ expect(() => loadConfig()).toThrow(/HOOD402_PAY_TO must be a 0x address/)+ })++ it('accepts a well-formed HOOD402_PAY_TO', () => {+ process.env.HOOD402_PAY_TO = '0x4022de2D36C334E73C7a108805Cea11C0564f402'+ expect(loadConfig().payTo).toBe('0x4022de2D36C334E73C7a108805Cea11C0564f402')+ })++ it('rejects a malformed HOOD402_SETTLER_KEY', () => {+ process.env.HOOD402_SETTLER_KEY = '0xdead'+ expect(() => loadConfig()).toThrow(/HOOD402_SETTLER_KEY must be a 0x-prefixed 32-byte hex private key/)+ })++ it('rejects a non-positive numeric env var', () => {+ process.env.HOOD_ALERTS_WHALE_FLOOR_USD = '-5'+ expect(() => loadConfig()).toThrow(/must be a positive number/)+ process.env.HOOD_ALERTS_WHALE_FLOOR_USD = 'not-a-number'+ expect(() => loadConfig()).toThrow(/must be a positive number/)+ })++ it('treats an empty string env var as unset (falls back to default)', () => {+ process.env.HOOD_ALERTS_DB = ''+ expect(loadConfig().dbPath).toBe('./data/hood-alerts.db')+ })++ it('reads through custom detector tuning', () => {+ process.env.HOOD_ALERTS_WHALE_FLOOR_USD = '2500'+ process.env.HOOD_ALERTS_RUG_DEFAULT_PCT = '15'+ const config = loadConfig()+ expect(config.detectors.whaleFloorUsd).toBe(2500)+ expect(config.detectors.rugDefaultPct).toBe(15)+ })+})diff --git a/robinhood/hood-alerts/tests/console-transport.test.ts b/robinhood/hood-alerts/tests/console-transport.test.tsnew file mode 100644index 000000000..9307f585d--- /dev/null+++ b/robinhood/hood-alerts/tests/console-transport.test.ts@@ -0,0 +1,56 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { ConsoleTransport } from '../src/transports/console.js'+import { logger } from '../src/logger.js'+import type { AlertEvent } from '../src/engine/events.js'++const TOKEN = '0x1234567890123456789012345678901234567890' as `0x${string}`++function whaleEvent(): AlertEvent {+ return { type: 'whale', source: 'uniswap-v3', token: TOKEN, symbol: 'X', side: 'buy', usd: 6000, trader: TOKEN, blockNumber: 1n, transactionHash: '0x1', at: 0 }+}++describe('ConsoleTransport', () => {+ let infoSpy: ReturnType<typeof vi.spyOn>++ beforeEach(() => {+ infoSpy = vi.spyOn(logger, 'info').mockImplementation(() => logger)+ })++ afterEach(() => {+ infoSpy.mockRestore()+ })++ it('has the console platform', () => {+ expect(new ConsoleTransport().platform).toBe('console')+ })++ it('sendAlert logs the rendered card text with chat and event type', async () => {+ const t = new ConsoleTransport()+ await t.sendAlert('chat-1', whaleEvent())+ expect(infoSpy).toHaveBeenCalledTimes(1)+ const [payload, message] = infoSpy.mock.calls[0] as [Record<string, unknown>, string]+ expect(message).toBe('alert')+ expect(payload.chatId).toBe('chat-1')+ expect(payload.eventType).toBe('whale')+ expect(payload.alert).toContain('Whale buy: $6.0k of X')+ })++ it('sendDigest logs a digest with per-alert lines and an omitted count', async () => {+ const t = new ConsoleTransport()+ const events = Array.from({ length: 12 }, () => whaleEvent())+ await t.sendDigest('chat-1', events)+ const [payload, message] = infoSpy.mock.calls[0] as [Record<string, unknown>, string]+ expect(message).toBe('digest')+ expect(payload.chatId).toBe('chat-1')+ expect(payload.title).toBe('Digest: 12 alerts')+ expect(payload.omitted).toBe(2)+ expect(Array.isArray(payload.alerts)).toBe(true)+ expect((payload.alerts as string[])).toHaveLength(10)+ })++ it('start and stop resolve without throwing', async () => {+ const t = new ConsoleTransport()+ await expect(t.start()).resolves.toBeUndefined()+ await expect(t.stop()).resolves.toBeUndefined()+ })+})diff --git a/robinhood/hood-alerts/tests/db-deliveries.test.ts b/robinhood/hood-alerts/tests/db-deliveries.test.tsnew file mode 100644index 000000000..343df8118--- /dev/null+++ b/robinhood/hood-alerts/tests/db-deliveries.test.ts@@ -0,0 +1,78 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { openDb, type Db } from '../src/db/index.js'+import { SubscriberRepo } from '../src/db/subscribers.js'+import { DeliveryRepo } from '../src/db/deliveries.js'++let db: Db+let clock = 1_700_000_000+const now = (): number => clock+let repo: DeliveryRepo+let subscriberId: number++beforeEach(() => {+ db = openDb(':memory:')+ clock = 1_700_000_000+ repo = new DeliveryRepo(db, now)+ subscriberId = new SubscriberRepo(db).ensure('telegram', 'chat-1').id+})++afterEach(() => {+ db.close()+})++describe('DeliveryRepo.claimFingerprint', () => {+ it('claims a fresh fingerprint and rejects the same one again within its TTL', () => {+ expect(repo.claimFingerprint('fp-1', 3600)).toBe(true)+ expect(repo.claimFingerprint('fp-1', 3600)).toBe(false)+ })++ it('reclaims a fingerprint once its TTL has expired', () => {+ expect(repo.claimFingerprint('fp-1', 60)).toBe(true)+ clock += 61+ expect(repo.claimFingerprint('fp-1', 60)).toBe(true)+ })++ it('treats distinct fingerprints independently', () => {+ expect(repo.claimFingerprint('fp-1', 3600)).toBe(true)+ expect(repo.claimFingerprint('fp-2', 3600)).toBe(true)+ })+})++describe('DeliveryRepo delivery log', () => {+ it('logDelivery records a row queryable by recentCount', () => {+ repo.logDelivery(subscriberId, 'fp-1', 'sent')+ expect(repo.recentCount(subscriberId, 60)).toBe(1)+ })++ it('recentCount only counts "sent" status within the window', () => {+ repo.logDelivery(subscriberId, 'fp-1', 'sent')+ repo.logDelivery(subscriberId, 'fp-2', 'failed')+ repo.logDelivery(subscriberId, 'fp-3', 'digested')+ expect(repo.recentCount(subscriberId, 60)).toBe(1)+ })++ it('recentCount excludes deliveries outside the trailing window', () => {+ repo.logDelivery(subscriberId, 'fp-1', 'sent')+ clock += 120+ expect(repo.recentCount(subscriberId, 60)).toBe(0)+ expect(repo.recentCount(subscriberId, 300)).toBe(1)+ })++ it('lastDeliveredAt returns null with no sent deliveries, and the max timestamp otherwise', () => {+ expect(repo.lastDeliveredAt(subscriberId)).toBeNull()+ repo.logDelivery(subscriberId, 'fp-1', 'sent')+ clock += 10+ repo.logDelivery(subscriberId, 'fp-2', 'sent')+ expect(repo.lastDeliveredAt(subscriberId)).toBe(clock)+ })++ it('lastDeliveredAt ignores non-sent statuses', () => {+ repo.logDelivery(subscriberId, 'fp-1', 'failed')+ expect(repo.lastDeliveredAt(subscriberId)).toBeNull()+ })++ it('keeps subscribers independent', () => {+ repo.logDelivery(subscriberId, 'fp-1', 'sent')+ expect(repo.recentCount(999, 60)).toBe(0)+ })+})diff --git a/robinhood/hood-alerts/tests/db-entitlements.test.ts b/robinhood/hood-alerts/tests/db-entitlements.test.tsnew file mode 100644index 000000000..7486a4e7f--- /dev/null+++ b/robinhood/hood-alerts/tests/db-entitlements.test.ts@@ -0,0 +1,92 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { openDb, type Db } from '../src/db/index.js'+import { EntitlementRepo } from '../src/db/entitlements.js'++let db: Db+let clock = 1_700_000_000+const now = (): number => clock++let repo: EntitlementRepo++beforeEach(() => {+ db = openDb(':memory:')+ clock = 1_700_000_000+ repo = new EntitlementRepo(db, now)+})++afterEach(() => {+ db.close()+})++describe('EntitlementRepo', () => {+ it('is free before any activation', () => {+ expect(repo.get('telegram', 'chat-1')).toBeNull()+ expect(repo.isPremium('telegram', 'chat-1')).toBe(false)+ expect(repo.remainingS('telegram', 'chat-1')).toBe(0)+ })++ it('activate grants premium for the given duration', () => {+ const e = repo.activate('telegram', 'chat-1', 30 * 86_400)+ expect(e.tier).toBe('premium')+ expect(e.expiresAt).toBe(clock + 30 * 86_400)+ expect(repo.isPremium('telegram', 'chat-1')).toBe(true)+ expect(repo.remainingS('telegram', 'chat-1')).toBe(30 * 86_400)+ })++ it('records payment tx and payer when provided', () => {+ const e = repo.activate('telegram', 'chat-1', 86_400, { tx: '0xabc', payer: '0xdef' })+ expect(e.paymentTx).toBe('0xabc')+ expect(e.payer).toBe('0xdef')+ })++ it('stacks an extension on top of remaining time while still active', () => {+ repo.activate('telegram', 'chat-1', 10 * 86_400)+ clock += 3 * 86_400 // 7 days remain+ const extended = repo.activate('telegram', 'chat-1', 5 * 86_400)+ // base = current expiry (10 days from original activation), + 5 more days+ expect(extended.expiresAt).toBe(1_700_000_000 + 10 * 86_400 + 5 * 86_400)+ })++ it('does not stack on top of an already-expired entitlement (starts from now)', () => {+ repo.activate('telegram', 'chat-1', 1 * 86_400)+ clock += 2 * 86_400 // expired 1 day ago+ const reactivated = repo.activate('telegram', 'chat-1', 5 * 86_400)+ expect(reactivated.expiresAt).toBe(clock + 5 * 86_400)+ })++ it('preserves payment_tx/payer on a renewal that supplies none', () => {+ repo.activate('telegram', 'chat-1', 10 * 86_400, { tx: '0xabc', payer: '0xdef' })+ const renewed = repo.activate('telegram', 'chat-1', 10 * 86_400)+ expect(renewed.paymentTx).toBe('0xabc')+ expect(renewed.payer).toBe('0xdef')+ })++ it('isPremium flips to false once the clock passes expiry', () => {+ repo.activate('telegram', 'chat-1', 100)+ expect(repo.isPremium('telegram', 'chat-1')).toBe(true)+ clock += 101+ expect(repo.isPremium('telegram', 'chat-1')).toBe(false)+ expect(repo.remainingS('telegram', 'chat-1')).toBe(0)+ })++ it('revoke drops back to free and reports whether a row existed', () => {+ repo.activate('telegram', 'chat-1', 86_400)+ expect(repo.revoke('telegram', 'chat-1')).toBe(true)+ expect(repo.isPremium('telegram', 'chat-1')).toBe(false)+ expect(repo.revoke('telegram', 'chat-1')).toBe(false)+ })++ it('keeps platforms independent for the same chat id', () => {+ repo.activate('telegram', 'chat-1', 86_400)+ expect(repo.isPremium('telegram', 'chat-1')).toBe(true)+ expect(repo.isPremium('discord', 'chat-1')).toBe(false)+ })++ it('get returns the stored entitlement even after it expires', () => {+ repo.activate('telegram', 'chat-1', 10)+ clock += 20+ const e = repo.get('telegram', 'chat-1')+ expect(e).not.toBeNull()+ expect(repo.isPremium('telegram', 'chat-1')).toBe(false)+ })+})diff --git a/robinhood/hood-alerts/tests/db-subscribers.test.ts b/robinhood/hood-alerts/tests/db-subscribers.test.tsnew file mode 100644index 000000000..bd1fa7e08--- /dev/null+++ b/robinhood/hood-alerts/tests/db-subscribers.test.ts@@ -0,0 +1,139 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { openDb, type Db } from '../src/db/index.js'+import { SubscriberRepo } from '../src/db/subscribers.js'++let db: Db+let repo: SubscriberRepo++beforeEach(() => {+ db = openDb(':memory:')+ repo = new SubscriberRepo(db)+})++afterEach(() => {+ db.close()+})++describe('SubscriberRepo.ensure/get/byId', () => {+ it('creates a subscriber on first ensure and returns the same row after', () => {+ const first = repo.ensure('telegram', 'chat-1', 'My Chat')+ expect(first.platform).toBe('telegram')+ expect(first.chatId).toBe('chat-1')+ expect(first.title).toBe('My Chat')+ expect(first.digest).toBe(false)+ expect(first.quietStart).toBeNull()++ const second = repo.ensure('telegram', 'chat-1')+ expect(second.id).toBe(first.id)+ })++ it('preserves the existing title when ensure is called without one', () => {+ repo.ensure('telegram', 'chat-1', 'Original')+ const again = repo.ensure('telegram', 'chat-1')+ expect(again.title).toBe('Original')+ })++ it('keeps platforms independent for the same chat id', () => {+ const tg = repo.ensure('telegram', 'chat-1')+ const dc = repo.ensure('discord', 'chat-1')+ expect(tg.id).not.toBe(dc.id)+ })++ it('get returns null for an unknown chat', () => {+ expect(repo.get('telegram', 'nope')).toBeNull()+ })++ it('byId returns null for an unknown id', () => {+ expect(repo.byId(999)).toBeNull()+ })+})++describe('SubscriberRepo settings', () => {+ it('setDigest toggles on/off and optionally sets the interval', () => {+ const s = repo.ensure('telegram', 'chat-1')+ repo.setDigest(s.id, true, 1800)+ expect(repo.byId(s.id)).toMatchObject({ digest: true, digestIntervalS: 1800 })+ repo.setDigest(s.id, false)+ expect(repo.byId(s.id)).toMatchObject({ digest: false, digestIntervalS: 1800 })+ })++ it('setQuietHours stores and clears the window', () => {+ const s = repo.ensure('telegram', 'chat-1')+ repo.setQuietHours(s.id, 22, 7)+ expect(repo.byId(s.id)).toMatchObject({ quietStart: 22, quietEnd: 7 })+ repo.setQuietHours(s.id, null, null)+ expect(repo.byId(s.id)).toMatchObject({ quietStart: null, quietEnd: null })+ })+})++describe('SubscriberRepo subscriptions', () => {+ it('subscribe creates, and re-subscribing updates the threshold instead of duplicating', () => {+ const s = repo.ensure('telegram', 'chat-1')+ repo.subscribe(s.id, 'whales', 5000)+ repo.subscribe(s.id, 'whales', 10_000)+ const subs = repo.list(s.id)+ expect(subs).toHaveLength(1)+ expect(subs[0]?.threshold).toBe(10_000)+ })++ it('unsubscribe removes a subscription and reports whether it existed', () => {+ const s = repo.ensure('telegram', 'chat-1')+ repo.subscribe(s.id, 'whales', 5000)+ expect(repo.unsubscribe(s.id, 'whales')).toBe(true)+ expect(repo.unsubscribe(s.id, 'whales')).toBe(false)+ expect(repo.list(s.id)).toHaveLength(0)+ })++ it('unsubscribeAll removes every subscription and returns the count removed', () => {+ const s = repo.ensure('telegram', 'chat-1')+ repo.subscribe(s.id, 'whales', 5000)+ repo.subscribe(s.id, 'launches', null)+ expect(repo.unsubscribeAll(s.id)).toBe(2)+ expect(repo.count(s.id)).toBe(0)+ })++ it('setThreshold updates only an existing subscription', () => {+ const s = repo.ensure('telegram', 'chat-1')+ expect(repo.setThreshold(s.id, 'whales', 9000)).toBe(false)+ repo.subscribe(s.id, 'whales', 5000)+ expect(repo.setThreshold(s.id, 'whales', 9000)).toBe(true)+ expect(repo.list(s.id)[0]?.threshold).toBe(9000)+ })++ it('list orders subscriptions by creation time and count matches it', () => {+ const s = repo.ensure('telegram', 'chat-1')+ repo.subscribe(s.id, 'launches', null)+ repo.subscribe(s.id, 'whales', 5000)+ const subs = repo.list(s.id)+ expect(subs.map((x) => x.topic)).toEqual(['launches', 'whales'])+ expect(repo.count(s.id)).toBe(2)+ })++ it('allWithSubscribers joins every subscription to its subscriber', () => {+ const a = repo.ensure('telegram', 'chat-a')+ const b = repo.ensure('discord', 'chat-b')+ repo.subscribe(a.id, 'whales', 5000)+ repo.subscribe(b.id, 'launches', null)+ const rows = repo.allWithSubscribers()+ expect(rows).toHaveLength(2)+ const forA = rows.find((r) => r.subscriber.id === a.id)+ expect(forA?.subscription.topic).toBe('whales')+ expect(forA?.subscriber.platform).toBe('telegram')+ })++ it('activeTopics returns distinct topics across all subscribers', () => {+ const a = repo.ensure('telegram', 'chat-a')+ const b = repo.ensure('discord', 'chat-b')+ repo.subscribe(a.id, 'whales', 5000)+ repo.subscribe(b.id, 'whales', 8000)+ repo.subscribe(b.id, 'launches', null)+ expect(repo.activeTopics().sort()).toEqual(['launches', 'whales'])+ })++ it('cascades subscription deletion when the subscriber row is deleted', () => {+ const s = repo.ensure('telegram', 'chat-1')+ repo.subscribe(s.id, 'whales', 5000)+ db.prepare('DELETE FROM subscribers WHERE id = ?').run(s.id)+ expect(repo.list(s.id)).toHaveLength(0)+ })+})diff --git a/robinhood/hood-alerts/tests/digest.test.ts b/robinhood/hood-alerts/tests/digest.test.tsnew file mode 100644index 000000000..2bfd577de--- /dev/null+++ b/robinhood/hood-alerts/tests/digest.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from 'vitest'+import { DigestBuffer, type BufferedAlert } from '../src/engine/digest.js'+import type { AlertEvent } from '../src/engine/events.js'++function alert(at: number): BufferedAlert {+ const event = { type: 'graduation', token: '0xabc', symbol: 'X', name: null, pool: '0xdef', blockNumber: 1n, transactionHash: '0x1', at } as unknown as AlertEvent+ return { event, fingerprint: `grad:${at}`, bufferedAt: at }+}++describe('DigestBuffer', () => {+ it('reports zero pending for an unknown subscriber', () => {+ const buf = new DigestBuffer()+ expect(buf.pending(1)).toBe(0)+ })++ it('accumulates alerts for the same subscriber', () => {+ const buf = new DigestBuffer()+ buf.add(1, alert(100), 60, 100)+ buf.add(1, alert(101), 60, 101)+ expect(buf.pending(1)).toBe(2)+ })++ it('keeps subscribers independent', () => {+ const buf = new DigestBuffer()+ buf.add(1, alert(100), 60, 100)+ buf.add(2, alert(100), 60, 100)+ expect(buf.pending(1)).toBe(1)+ expect(buf.pending(2)).toBe(1)+ })++ it('drain returns nothing before notBefore', () => {+ const buf = new DigestBuffer()+ buf.add(1, alert(100), 60, 100)+ expect(buf.drain(159)).toEqual([])+ expect(buf.pending(1)).toBe(1)+ })++ it('drain returns and clears a bucket once due', () => {+ const buf = new DigestBuffer()+ buf.add(1, alert(100), 60, 100)+ const due = buf.drain(160)+ expect(due).toHaveLength(1)+ expect(due[0]?.subscriberId).toBe(1)+ expect(due[0]?.alerts).toHaveLength(1)+ expect(buf.pending(1)).toBe(0)+ })++ it('a shorter delay on a later add wins (batch is not held hostage)', () => {+ const buf = new DigestBuffer()+ buf.add(1, alert(100), 3600, 100) // notBefore = 3700+ buf.add(1, alert(200), 60, 200) // notBefore = min(3700, 260) = 260+ expect(buf.drain(259)).toEqual([])+ const due = buf.drain(260)+ expect(due).toHaveLength(1)+ expect(due[0]?.alerts).toHaveLength(2)+ })++ it('drainAll returns every bucket regardless of notBefore', () => {+ const buf = new DigestBuffer()+ buf.add(1, alert(100), 3600, 100)+ buf.add(2, alert(100), 7200, 100)+ const all = buf.drainAll()+ expect(all).toHaveLength(2)+ expect(buf.pending(1)).toBe(0)+ expect(buf.pending(2)).toBe(0)+ })++ it('drain only returns due buckets, leaving others buffered', () => {+ const buf = new DigestBuffer()+ buf.add(1, alert(100), 60, 100) // due at 160+ buf.add(2, alert(100), 3600, 100) // due at 3700+ const due = buf.drain(160)+ expect(due.map((d) => d.subscriberId)).toEqual([1])+ expect(buf.pending(2)).toBe(1)+ })+})diff --git a/robinhood/hood-alerts/tests/engine.test.ts b/robinhood/hood-alerts/tests/engine.test.tsnew file mode 100644index 000000000..48586a1ce--- /dev/null+++ b/robinhood/hood-alerts/tests/engine.test.ts@@ -0,0 +1,189 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { openDb, type Db } from '../src/db/index.js'+import { AlertEngine } from '../src/engine/engine.js'+import type { DetectorConfig } from '../src/config.js'+import type { AlertEvent } from '../src/engine/events.js'+import type { Transport } from '../src/transports/types.js'++const DETECTORS: DetectorConfig = {+ whaleFloorUsd: 1000,+ whaleDefaultUsd: 5000,+ priceWindowS: 900,+ priceDefaultPct: 2,+ premiumPollS: 60,+ premiumDefaultPct: 2,+ rugDefaultPct: 30,+}++const TOKEN = '0x1234567890123456789012345678901234567890' as `0x${string}`++function whaleEvent(usd: number, token: `0x${string}` = TOKEN, at = 0): AlertEvent {+ return { type: 'whale', source: 'uniswap-v3', token, symbol: 'X', side: 'buy', usd, trader: TOKEN, blockNumber: 1n, transactionHash: `0x${usd}`, at }+}++class FakeTransport implements Transport {+ readonly platform = 'telegram' as const+ alerts: Array<{ chatId: string; event: AlertEvent }> = []+ digests: Array<{ chatId: string; events: AlertEvent[] }> = []+ async sendAlert(chatId: string, event: AlertEvent): Promise<void> {+ this.alerts.push({ chatId, event })+ }+ async sendDigest(chatId: string, events: AlertEvent[]): Promise<void> {+ this.digests.push({ chatId, events })+ }+ async start(): Promise<void> {}+ async stop(): Promise<void> {}+}++let db: Db+let engine: AlertEngine+let transport: FakeTransport++beforeEach(() => {+ db = openDb(':memory:')+ engine = new AlertEngine(db, DETECTORS)+ transport = new FakeTransport()+ engine.registerTransport(transport)+})++afterEach(() => {+ db.close()+})++describe('AlertEngine.ingest: routing + delivery', () => {+ it('delivers to a matching subscriber immediately', async () => {+ const s = engine.subscribers.ensure('telegram', 'chat-1')+ engine.subscribers.subscribe(s.id, 'whales', 5000)+ engine.ingest(whaleEvent(6000))+ await vi.waitFor(() => expect(transport.alerts).toHaveLength(1))+ expect(transport.alerts[0]?.chatId).toBe('chat-1')+ })++ it('does not deliver when the event does not clear the threshold', async () => {+ const s = engine.subscribers.ensure('telegram', 'chat-1')+ engine.subscribers.subscribe(s.id, 'whales', 5000)+ engine.ingest(whaleEvent(1000))+ await new Promise((r) => setTimeout(r, 10))+ expect(transport.alerts).toHaveLength(0)+ })++ it('does not deliver to subscribers on other topics', async () => {+ const s = engine.subscribers.ensure('telegram', 'chat-1')+ engine.subscribers.subscribe(s.id, 'launches', null)+ engine.ingest(whaleEvent(6000))+ await new Promise((r) => setTimeout(r, 10))+ expect(transport.alerts).toHaveLength(0)+ })++ it('logs a delivery failure when no transport is registered for the platform', async () => {+ const discordSub = engine.subscribers.ensure('discord', 'chat-2')+ engine.subscribers.subscribe(discordSub.id, 'whales', 5000)+ engine.ingest(whaleEvent(6000))+ await new Promise((r) => setTimeout(r, 10))+ expect(engine.deliveries.recentCount(discordSub.id, 3600)).toBe(0)+ })++ it('deduplicates identical events by fingerprint', async () => {+ const s = engine.subscribers.ensure('telegram', 'chat-1')+ engine.subscribers.subscribe(s.id, 'whales', 5000)+ const event = whaleEvent(6000)+ engine.ingest(event)+ engine.ingest(event) // same fingerprint: dropped before routing+ await vi.waitFor(() => expect(transport.alerts.length).toBeGreaterThan(0))+ await new Promise((r) => setTimeout(r, 10))+ expect(transport.alerts).toHaveLength(1)+ })++ it('premium-only topics stop matching once the entitlement lapses', async () => {+ const s = engine.subscribers.ensure('telegram', 'chat-1')+ engine.subscribers.subscribe(s.id, 'rugs', 30)+ // never activated premium+ const pull: AlertEvent = { type: 'liquidity_pull', token: TOKEN, symbol: 'X', pool: TOKEN, quoteAsset: 'USDG', droppedPct: 50, beforeUsd: 100, afterUsd: 50, at: 0 }+ engine.ingest(pull)+ await new Promise((r) => setTimeout(r, 10))+ expect(transport.alerts).toHaveLength(0)+ })++ it('delivers premium-only topics once the subscriber is entitled', async () => {+ const s = engine.subscribers.ensure('telegram', 'chat-1')+ engine.entitlements.activate('telegram', 'chat-1', 86_400)+ engine.subscribers.subscribe(s.id, 'rugs', 30)+ const pull: AlertEvent = { type: 'liquidity_pull', token: TOKEN, symbol: 'X', pool: TOKEN, quoteAsset: 'USDG', droppedPct: 50, beforeUsd: 100, afterUsd: 50, at: 0 }+ engine.ingest(pull)+ await vi.waitFor(() => expect(transport.alerts).toHaveLength(1))+ })++ it('fans a single event out to every matching subscriber', async () => {+ const a = engine.subscribers.ensure('telegram', 'chat-a')+ engine.subscribers.subscribe(a.id, 'whales', 5000)+ const b = engine.subscribers.ensure('telegram', 'chat-b')+ engine.subscribers.subscribe(b.id, 'whales', 1000)+ engine.ingest(whaleEvent(6000))+ await vi.waitFor(() => expect(transport.alerts).toHaveLength(2))+ expect(transport.alerts.map((a) => a.chatId).sort()).toEqual(['chat-a', 'chat-b'])+ })+})++describe('AlertEngine.ingest: gating into digest', () => {+ it('buffers into a digest for a subscriber with digest mode on, instead of delivering immediately', async () => {+ const s = engine.subscribers.ensure('telegram', 'chat-1')+ engine.subscribers.subscribe(s.id, 'whales', 5000)+ engine.subscribers.setDigest(s.id, true, 3600)+ engine.ingest(whaleEvent(6000))+ await new Promise((r) => setTimeout(r, 10))+ expect(transport.alerts).toHaveLength(0)+ expect(transport.digests).toHaveLength(0) // not flushed yet (flush runs on a 15s timer)+ })++ it('enforces free-tier granularity: a second immediate alert within 60s digests instead', async () => {+ const s = engine.subscribers.ensure('telegram', 'chat-1')+ engine.subscribers.subscribe(s.id, 'whales', 1000)+ engine.ingest(whaleEvent(2000))+ await vi.waitFor(() => expect(transport.alerts).toHaveLength(1))+ engine.ingest(whaleEvent(3000))+ await new Promise((r) => setTimeout(r, 10))+ // second alert should not have delivered immediately (still within FREE_MIN_INTERVAL_S)+ expect(transport.alerts).toHaveLength(1)+ })+})++describe('AlertEngine.watchedTokens / notifyWatchChange', () => {+ it('returns the distinct set of token: watches', () => {+ const s = engine.subscribers.ensure('telegram', 'chat-1')+ engine.subscribers.subscribe(s.id, `token:${TOKEN}`, 5000)+ engine.subscribers.subscribe(s.id, 'whales', 5000)+ expect(engine.watchedTokens()).toEqual([TOKEN])+ })++ it('onTokenWatches fires immediately with the current set, and again on notifyWatchChange', () => {+ const seen: Array<readonly string[]> = []+ engine.onTokenWatches((tokens) => seen.push(tokens))+ expect(seen).toEqual([[]])+ const s = engine.subscribers.ensure('telegram', 'chat-1')+ engine.subscribers.subscribe(s.id, `token:${TOKEN}`, 5000)+ engine.notifyWatchChange()+ expect(seen).toEqual([[], [TOKEN]])+ })+})++describe('AlertEngine.stop', () => {+ it('flushes any pending digest buffers on shutdown', async () => {+ const s = engine.subscribers.ensure('telegram', 'chat-1')+ engine.subscribers.subscribe(s.id, 'whales', 5000)+ engine.subscribers.setDigest(s.id, true, 3600)+ engine.ingest(whaleEvent(6000))+ await new Promise((r) => setTimeout(r, 10))+ expect(transport.alerts).toHaveLength(0)+ await engine.stop()+ expect(transport.alerts).toHaveLength(1) // sole buffered alert flushes as a single sendAlert+ })+})++describe('AlertEngine.recent', () => {+ it('keeps a ring buffer of the most recent 100 events', () => {+ const s = engine.subscribers.ensure('telegram', 'chat-1')+ engine.subscribers.subscribe(s.id, 'whales', 0)+ for (let i = 0; i < 105; i++) engine.ingest(whaleEvent(1000 + i, TOKEN, i))+ expect(engine.recent).toHaveLength(100)+ })+})diff --git a/robinhood/hood-alerts/tests/eth-price.test.ts b/robinhood/hood-alerts/tests/eth-price.test.tsnew file mode 100644index 000000000..9fffbb085--- /dev/null+++ b/robinhood/hood-alerts/tests/eth-price.test.ts@@ -0,0 +1,59 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { EthPrice } from '../src/engine/eth-price.js'+import { logger } from '../src/logger.js'+import type { HoodClient } from 'hoodchain'++function fakeClient(): HoodClient {+ return { public: {} } as unknown as HoodClient+}++const originalFetch = global.fetch++beforeEach(() => {+ vi.spyOn(logger, 'warn').mockImplementation(() => logger)+})++afterEach(() => {+ global.fetch = originalFetch+ vi.restoreAllMocks()+})++describe('EthPrice', () => {+ it('returns the Blockscout coin_price on a successful fetch', async () => {+ global.fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ coin_price: '3123.45' }) }) as unknown as typeof fetch+ const price = new EthPrice(fakeClient())+ expect(await price.get()).toBe(3123.45)+ })++ it('caches the value within the TTL, avoiding a second fetch', async () => {+ const fetchSpy = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ coin_price: '3000' }) })+ global.fetch = fetchSpy as unknown as typeof fetch+ const price = new EthPrice(fakeClient(), 60)+ await price.get()+ await price.get()+ expect(fetchSpy).toHaveBeenCalledTimes(1)+ })++ it('falls back to the cached value if the pool read also fails after a network error', async () => {+ global.fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ coin_price: '3000' }) }) as unknown as typeof fetch+ const price = new EthPrice(fakeClient(), 0) // TTL 0: always refetch+ expect(await price.get()).toBe(3000)++ global.fetch = vi.fn().mockRejectedValue(new Error('network down')) as unknown as typeof fetch+ // pool fallback will also throw (fakeClient has no working public.readContract), so the+ // last known cached value should be returned instead of null.+ expect(await price.get()).toBe(3000)+ })++ it('returns null when there is no cached value and both sources fail', async () => {+ global.fetch = vi.fn().mockResolvedValue({ ok: false }) as unknown as typeof fetch+ const price = new EthPrice(fakeClient())+ expect(await price.get()).toBeNull()+ })++ it('treats a non-numeric or non-positive coin_price as unavailable', async () => {+ global.fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ coin_price: 'not-a-number' }) }) as unknown as typeof fetch+ const price = new EthPrice(fakeClient())+ expect(await price.get()).toBeNull()+ })+})diff --git a/robinhood/hood-alerts/tests/events.test.ts b/robinhood/hood-alerts/tests/events.test.tsnew file mode 100644index 000000000..e53a19136--- /dev/null+++ b/robinhood/hood-alerts/tests/events.test.ts@@ -0,0 +1,80 @@+import { describe, expect, it } from 'vitest'+import { dedupTtlSeconds, fingerprint, type AlertEvent } from '../src/engine/events.js'++const TOKEN = '0x1234567890123456789012345678901234567890'++describe('fingerprint', () => {+ it('is stable and lowercases the token for launch/whale', () => {+ const launch: AlertEvent = {+ type: 'launch',+ launchpad: 'noxa',+ token: TOKEN.toUpperCase() as `0x${string}`,+ symbol: 'X',+ name: null,+ creator: TOKEN as `0x${string}`,+ pool: null,+ blockNumber: 1n,+ transactionHash: '0xabc',+ at: 0,+ }+ expect(fingerprint(launch)).toBe(`launch:0xabc:${TOKEN.toLowerCase()}`)+ })++ it('distinguishes graduation by token', () => {+ const grad = (token: string): AlertEvent => ({ type: 'graduation', token: token as `0x${string}`, symbol: null, name: null, pool: TOKEN as `0x${string}`, blockNumber: 1n, transactionHash: '0x1', at: 0 })+ expect(fingerprint(grad(TOKEN))).toBe(`grad:${TOKEN.toLowerCase()}`)+ expect(fingerprint(grad(TOKEN))).not.toBe(fingerprint(grad('0x0000000000000000000000000000000000dead')))+ })++ it('rounds the whale usd amount into the fingerprint so near-identical trades still dedup', () => {+ const whale = (usd: number): AlertEvent => ({ type: 'whale', source: 'uniswap-v3', token: TOKEN as `0x${string}`, symbol: null, side: 'buy', usd, trader: TOKEN as `0x${string}`, blockNumber: 1n, transactionHash: '0xabc', at: 0 })+ expect(fingerprint(whale(5000.4))).toBe(fingerprint(whale(5000.2)))+ expect(fingerprint(whale(5000))).not.toBe(fingerprint(whale(5001)))+ })++ it('keys price_move by symbol and timestamp', () => {+ const move: AlertEvent = { type: 'price_move', symbol: 'TSLA', pct: 5, fromUsd: 1, toUsd: 1.05, windowS: 900, at: 123 }+ expect(fingerprint(move)).toBe('price:TSLA:123')+ })++ it('keys premium by symbol, direction and rung', () => {+ const premium: AlertEvent = { type: 'premium', symbol: 'TSLA', token: TOKEN as `0x${string}`, premiumPct: 3, level: 2, direction: 'premium', dexUsd: 1, feedUsd: 1, pool: TOKEN as `0x${string}`, at: 0 }+ expect(fingerprint(premium)).toBe('premium:TSLA:premium:2')+ })++ it('keys holders by token and milestone', () => {+ const holders: AlertEvent = { type: 'holders', token: TOKEN as `0x${string}`, symbol: null, milestone: 1000, count: 1001, at: 0 }+ expect(fingerprint(holders)).toBe(`holders:${TOKEN.toLowerCase()}:1000`)+ })++ it('keys liquidity_pull by pool only', () => {+ const pull: AlertEvent = { type: 'liquidity_pull', token: null, symbol: null, pool: TOKEN.toUpperCase() as `0x${string}`, quoteAsset: 'USDG', droppedPct: 40, beforeUsd: 100, afterUsd: 60, at: 0 }+ expect(fingerprint(pull)).toBe(`liq:${TOKEN.toLowerCase()}`)+ })+})++describe('dedupTtlSeconds', () => {+ it('gives launches, graduations, and whales a 7-day window', () => {+ const week = 7 * 24 * 3600+ const launch: AlertEvent = { type: 'launch', launchpad: 'noxa', token: TOKEN as `0x${string}`, symbol: null, name: null, creator: TOKEN as `0x${string}`, pool: null, blockNumber: 1n, transactionHash: '0x1', at: 0 }+ const grad: AlertEvent = { type: 'graduation', token: TOKEN as `0x${string}`, symbol: null, name: null, pool: TOKEN as `0x${string}`, blockNumber: 1n, transactionHash: '0x1', at: 0 }+ const whale: AlertEvent = { type: 'whale', source: 'uniswap-v3', token: TOKEN as `0x${string}`, symbol: null, side: 'buy', usd: 1, trader: TOKEN as `0x${string}`, blockNumber: 1n, transactionHash: '0x1', at: 0 }+ expect(dedupTtlSeconds(launch)).toBe(week)+ expect(dedupTtlSeconds(grad)).toBe(week)+ expect(dedupTtlSeconds(whale)).toBe(week)+ })++ it('gives price_move a 1-day window and premium a 6-hour window', () => {+ const move: AlertEvent = { type: 'price_move', symbol: 'TSLA', pct: 1, fromUsd: 1, toUsd: 1, windowS: 900, at: 0 }+ const premium: AlertEvent = { type: 'premium', symbol: 'TSLA', token: TOKEN as `0x${string}`, premiumPct: 1, level: 1, direction: 'premium', dexUsd: 1, feedUsd: 1, pool: TOKEN as `0x${string}`, at: 0 }+ expect(dedupTtlSeconds(move)).toBe(24 * 3600)+ expect(dedupTtlSeconds(premium)).toBe(6 * 3600)+ })++ it('gives holders a 30-day window and liquidity_pull a 1-hour window', () => {+ const holders: AlertEvent = { type: 'holders', token: TOKEN as `0x${string}`, symbol: null, milestone: 1, count: 1, at: 0 }+ const pull: AlertEvent = { type: 'liquidity_pull', token: null, symbol: null, pool: TOKEN as `0x${string}`, quoteAsset: 'USDG', droppedPct: 1, beforeUsd: 1, afterUsd: 1, at: 0 }+ expect(dedupTtlSeconds(holders)).toBe(30 * 24 * 3600)+ expect(dedupTtlSeconds(pull)).toBe(3600)+ })+})diff --git a/robinhood/hood-alerts/tests/fixtures/curve-trades.json b/robinhood/hood-alerts/tests/fixtures/curve-trades.jsonnew file mode 100644index 000000000..b4e239efd--- /dev/null+++ b/robinhood/hood-alerts/tests/fixtures/curve-trades.json@@ -0,0 +1,95 @@+{+ "capturedAt": "2026-07-16T17:02:47.527Z",+ "chainId": 4663,+ "ethUsd": 1877.94,+ "trades": [+ {+ "launchpad": "odyssey",+ "token": "0x6b21b4567EfAd992B65f8a92457B45a74ed59486",+ "trader": "0x6A85b75E240D67783Ea85375be5E0f5BF3697051",+ "isBuy": true,+ "tokenAmount": "21546882935256",+ "quoteAmount": "0",+ "fee": "3838099598115792",+ "blockNumber": "11022832",+ "transactionHash": "0xefad0bfc174d9b11237a845ab71ab0ae889845a252dfd59002e5efc3b43cc25a"+ },+ {+ "launchpad": "odyssey",+ "token": "0x6b21b4567EfAd992B65f8a92457B45a74ed59486",+ "trader": "0x6Fe4054eB7Df2a752132dD1DDEA919921A3CccB7",+ "isBuy": true,+ "tokenAmount": "8748016421282",+ "quoteAmount": "0",+ "fee": "1702756204700920",+ "blockNumber": "11025696",+ "transactionHash": "0x0c5ce7566a997a178b223b84a6cab83ff9e5a8ecb2b24f2274b263233f57a729"+ },+ {+ "launchpad": "odyssey",+ "token": "0x6b21b4567EfAd992B65f8a92457B45a74ed59486",+ "trader": "0x7B70E60Cd3806907AF0F4aEe47FF597f47EBF3CE",+ "isBuy": true,+ "tokenAmount": "11136388196935",+ "quoteAmount": "0",+ "fee": "2304221708117811",+ "blockNumber": "11090913",+ "transactionHash": "0x9815c87a9a7a69a0c54b787fecd9fab849f90c3e717385a7231549eec3cbf1b7"+ },+ {+ "launchpad": "odyssey",+ "token": "0x6b21b4567EfAd992B65f8a92457B45a74ed59486",+ "trader": "0x7B70E60Cd3806907AF0F4aEe47FF597f47EBF3CE",+ "isBuy": false,+ "tokenAmount": "11136388196935",+ "quoteAmount": "0",+ "fee": "2304221708117810",+ "blockNumber": "11105367",+ "transactionHash": "0xf1f4b5bd8918d1bb94f466428a2bf9c75df07e60f96ffe076aafa492dc676750"+ },+ {+ "launchpad": "odyssey",+ "token": "0x6b21b4567EfAd992B65f8a92457B45a74ed59486",+ "trader": "0x6977109374fc923213CE42f9c5809DCe1066f4B3",+ "isBuy": true,+ "tokenAmount": "1369028774047",+ "quoteAmount": "0",+ "fee": "274760716446507",+ "blockNumber": "11109989",+ "transactionHash": "0xa876d7706717db7f18c73c17278ca7833eafa5a213323b51f99dace233dae17e"+ },+ {+ "launchpad": "odyssey",+ "token": "0x6b21b4567EfAd992B65f8a92457B45a74ed59486",+ "trader": "0x130F46a76Bf1D89Cc45Eb9Ad97Cb3370863492DB",+ "isBuy": true,+ "tokenAmount": "286876861731",+ "quoteAmount": "0",+ "fee": "57868780834698",+ "blockNumber": "11122837",+ "transactionHash": "0x741c7c8fcbf4e9571a645331d3fc765c80362b30e1c5b8155ff87c85b86a7702"+ },+ {+ "launchpad": "odyssey",+ "token": "0xEdD60AB7a13B98233ef0D5D108215a88a9aB6fcd",+ "trader": "0xfe28285fd95Bc897bc3E4c4566088698611aF8aD",+ "isBuy": true,+ "tokenAmount": "1878326387753",+ "quoteAmount": "0",+ "fee": "66761093754723",+ "blockNumber": "11159252",+ "transactionHash": "0xfeb7a468aabb4fd7d018e160acf13c0c3c50c6716f44eadabb65448d7f6ccb31"+ },+ {+ "launchpad": "odyssey",+ "token": "0x6b21b4567EfAd992B65f8a92457B45a74ed59486",+ "trader": "0xC50723b547d1337667493Af50B1a8Ea856Ef66B4",+ "isBuy": true,+ "tokenAmount": "17851557670618",+ "quoteAmount": "0",+ "fee": "3813628921339757",+ "blockNumber": "11155901",+ "transactionHash": "0x6ba554fc0d91835fbb951332c4e17f785f696a68baa78cb6c7b9cc2f6d778ab7"+ }+ ]+}diff --git a/robinhood/hood-alerts/tests/fixtures/prices.json b/robinhood/hood-alerts/tests/fixtures/prices.jsonnew file mode 100644index 000000000..b0220b5aa--- /dev/null+++ b/robinhood/hood-alerts/tests/fixtures/prices.json@@ -0,0 +1,245 @@+{+ "capturedAt": "2026-07-16T17:00:55.408Z",+ "chainId": 4663,+ "count": 34,+ "prices": [+ {+ "symbol": "AAPL",+ "priceUsd": 331.48485,+ "feed": "0x6B22A786bAa607d76728168703a39Ea9C99f2cD0",+ "roundId": "18446744073709551825",+ "updatedAt": 1784216858+ },+ {+ "symbol": "AMD",+ "priceUsd": 502.475,+ "feed": "0x943A29E7ae51A4798823ca9eEd2ed533B2A22C72",+ "roundId": "18446744073709552638",+ "updatedAt": 1784220982+ },+ {+ "symbol": "AMZN",+ "priceUsd": 255.43425,+ "feed": "0xD5a1508ceD74c084eBf3cBe853e2C968fB2a651C",+ "roundId": "18446744073709551887",+ "updatedAt": 1784213513+ },+ {+ "symbol": "ASML",+ "priceUsd": 1807.4,+ "feed": "0xB4106147E8cce40b7d46124090d373A71b70f87D",+ "roundId": "18446744073709552361",+ "updatedAt": 1784218227+ },+ {+ "symbol": "BABA",+ "priceUsd": 118.47,+ "feed": "0x62Cc8F9b5f56a33c9C8A60c8B92779f523c4E984",+ "roundId": "18446744073709552261",+ "updatedAt": 1784217394+ },+ {+ "symbol": "CLSK",+ "priceUsd": 13.175,+ "feed": "0x810c12D3a554Bc47fd39597Fe3b3AAC4941F50eF",+ "roundId": "18446744073709553290",+ "updatedAt": 1784221066+ },+ {+ "symbol": "COIN",+ "priceUsd": 164.4236,+ "feed": "0xA3a468A452940B7D6b69991207B508c609a98Ef2",+ "roundId": "18446744073709552523",+ "updatedAt": 1784221185+ },+ {+ "symbol": "CRCL",+ "priceUsd": 62.46,+ "feed": "0x6652eDf64bA3731C4F2D3ce821A0Fb1f1f6b482a",+ "roundId": "18446744073709552928",+ "updatedAt": 1784220922+ },+ {+ "symbol": "CRWV",+ "priceUsd": 73.6776,+ "feed": "0xe1b3aABCAFAd1c94708dc1367dcfF8Aa4407487C",+ "roundId": "18446744073709552788",+ "updatedAt": 1784220975+ },+ {+ "symbol": "EWY",+ "priceUsd": 164.59345,+ "feed": "0xEFdf54610B62A7753Ec30bDc380847c12D32e1D1",+ "roundId": "18446744073709552959",+ "updatedAt": 1784221008+ },+ {+ "symbol": "GME",+ "priceUsd": 22.225,+ "feed": "0x27C71df6A64fB476468EdF256CF72c038baB5B67",+ "roundId": "18446744073709551834",+ "updatedAt": 1784220705+ },+ {+ "symbol": "GOOGL",+ "priceUsd": 372.0727,+ "feed": "0xF6f373a037c30F0e5010d854385cA89185AE638b",+ "roundId": "18446744073709551878",+ "updatedAt": 1784220785+ },+ {+ "symbol": "INTC",+ "priceUsd": 96.98695,+ "feed": "0x3f390C5C24628Ac7C489515402235FeAD71D1913",+ "roundId": "18446744073709553042",+ "updatedAt": 1784220941+ },+ {+ "symbol": "IONQ",+ "priceUsd": 35.51595,+ "feed": "0x22EfeC4919baf55F360E0EDee4AbEB26DE4971eb",+ "roundId": "18446744073709552920",+ "updatedAt": 1784220951+ },+ {+ "symbol": "META",+ "priceUsd": 669.24,+ "feed": "0x7C38C00C30BEe9378381E7B6135d7283356D71b1",+ "roundId": "18446744073709552004",+ "updatedAt": 1784218822+ },+ {+ "symbol": "MSFT",+ "priceUsd": 403.01,+ "feed": "0x45C3C877C15E6BA2EBB19eA114Ea508d14C1Af2E",+ "roundId": "18446744073709551881",+ "updatedAt": 1784220475+ },+ {+ "symbol": "MSTR",+ "priceUsd": 94.41655,+ "feed": "0x396118bdFB181e6240E74D243F266B061c0edc3D",+ "roundId": "18446744073709553174",+ "updatedAt": 1784220698+ },+ {+ "symbol": "MU",+ "priceUsd": 852.77,+ "feed": "0x425EEFdCf05ed6526C3cE61Af99429A228a6d596",+ "roundId": "18446744073709553686",+ "updatedAt": 1784220994+ },+ {+ "symbol": "NBIS",+ "priceUsd": 176.093,+ "feed": "0xE1D87B116Ba0fe898998f1D140339D1fA1E09705",+ "roundId": "18446744073709553619",+ "updatedAt": 1784221049+ },+ {+ "symbol": "NVDA",+ "priceUsd": 207.2811,+ "feed": "0x379EC4f7C378F34a1B47E4F3cbeBCbAC3E8E9F15",+ "roundId": "18446744073709551961",+ "updatedAt": 1784215916+ },+ {+ "symbol": "ORCL",+ "priceUsd": 126.3172,+ "feed": "0x0e6a64a2B58A6693a531E6c555f3A5d042eEA844",+ "roundId": "18446744073709552202",+ "updatedAt": 1784218644+ },+ {+ "symbol": "PLTR",+ "priceUsd": 134.17,+ "feed": "0x820ABedFF239034956B7A9d2F0a331f9F075eB4c",+ "roundId": "18446744073709552298",+ "updatedAt": 1784221007+ },+ {+ "symbol": "QQQ",+ "priceUsd": 707.8,+ "feed": "0x80901d846d5D7B030F26B480776EE3b29374C2ae",+ "roundId": "18446744073709551752",+ "updatedAt": 1784218404+ },+ {+ "symbol": "RGTI",+ "priceUsd": 14.285,+ "feed": "0x2A045cF1C49c61c166C036d2f06FA2D2d984f765",+ "roundId": "18446744073709552969",+ "updatedAt": 1784220303+ },+ {+ "symbol": "RKLB",+ "priceUsd": 67.235,+ "feed": "0x045477BF65Aef6f4F2386ad0164579e48381CC74",+ "roundId": "18446744073709553118",+ "updatedAt": 1784221159+ },+ {+ "symbol": "SGOV",+ "priceUsd": 100.65101945,+ "feed": "0xa0DF4ee0fFf975306345875E3548Fcc519577A11",+ "roundId": "18446744073709551629",+ "updatedAt": 1784160054+ },+ {+ "symbol": "SLV",+ "priceUsd": 50.645,+ "feed": "0x209b73908e92Ae021826eD79609845451Ecba2ce",+ "roundId": "18446744073709552173",+ "updatedAt": 1784218418+ },+ {+ "symbol": "SNDK",+ "priceUsd": 1450.88,+ "feed": "0xfb133Fa4B7b385802B693a293606682Df47109A3",+ "roundId": "18446744073709554132",+ "updatedAt": 1784220992+ },+ {+ "symbol": "SPCX",+ "priceUsd": 133.23215,+ "feed": "0xB265810950ba6c5C0Ff821c9963014a56fD8Bffb",+ "roundId": "18446744073709552742",+ "updatedAt": 1784220968+ },+ {+ "symbol": "SPY",+ "priceUsd": 753.34505,+ "feed": "0x319724394D3A0e3669269846abE664Cd621f9f6A",+ "roundId": "18446744073709551659",+ "updatedAt": 1784214441+ },+ {+ "symbol": "TSLA",+ "priceUsd": 389.245,+ "feed": "0x4A1166a659A55625345e9515b32adECea5547C38",+ "roundId": "18446744073709551990",+ "updatedAt": 1784218313+ },+ {+ "symbol": "TSM",+ "priceUsd": 406.96045,+ "feed": "0x874cF94aa8eC88Fd9560094dD065f2fB3E41Fc2F",+ "roundId": "18446744073709552232",+ "updatedAt": 1784220995+ },+ {+ "symbol": "USAR",+ "priceUsd": 15.825,+ "feed": "0xA994d3684e8400A6c8078226925779FdeE682DD9",+ "roundId": "18446744073709552100",+ "updatedAt": 1784221013+ },+ {+ "symbol": "USO",+ "priceUsd": 119.144,+ "feed": "0x75a9c76Ef439e2C7c2E5a34Ab105EcFe3766431c",+ "roundId": "18446744073709552062",+ "updatedAt": 1784220953+ }+ ]+}diff --git a/robinhood/hood-alerts/tests/fixtures/swaps.json b/robinhood/hood-alerts/tests/fixtures/swaps.jsonnew file mode 100644index 000000000..93361ff1b--- /dev/null+++ b/robinhood/hood-alerts/tests/fixtures/swaps.json@@ -0,0 +1,264 @@+{+ "capturedAt": "2026-07-16T17:02:44.955Z",+ "chainId": 4663,+ "blockNumber": "11420552",+ "weth": "0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73",+ "usdg": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",+ "ethUsd": 1878.41,+ "pools": [+ {+ "poolInfo": {+ "pool": "0xedb22516B14Eb2d1C86927Db373B0E8bF70F5cD1",+ "token0": "0x47F93d52cBeC7C6D2CfC080e154002370a60dAEA",+ "token1": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",+ "fee": 10000,+ "decimals0": 18,+ "decimals1": 6+ },+ "symbol": "ASML",+ "token": "0x47F93d52cBeC7C6D2CfC080e154002370a60dAEA",+ "swaps": [+ {+ "pool": "0xedb22516B14Eb2d1C86927Db373B0E8bF70F5cD1",+ "amount0": "-27640481476808011",+ "amount1": "49950000",+ "buysToken0": true,+ "price": 1807.132051658036,+ "volume0": 0.02764048147680801,+ "volume1": 49.95,+ "spotPrice": 1791.5433571722144,+ "sqrtPriceX96": "3353460886356986625902581",+ "liquidity": "843088264141760",+ "tick": -201412,+ "blockNumber": "11380008",+ "logIndex": 23,+ "transactionHash": "0x2bba7438da99b28872c1f2b3795049cf9be1d1a7c4185fdcfe18d7ccc0a53912",+ "sender": "0xC94135b63772b91D79d0A2DaAb2a8801f32359bD",+ "recipient": "0xC94135b63772b91D79d0A2DaAb2a8801f32359bD"+ }+ ]+ },+ {+ "poolInfo": {+ "pool": "0xbc44b11f569d3FEEd9B4088F5A3fC569D2E3c77F",+ "token0": "0x558378E000D634A36593E338eBacdd6207640EfE",+ "token1": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",+ "fee": 10000,+ "decimals0": 18,+ "decimals1": 6+ },+ "symbol": "IONQ",+ "token": "0x558378E000D634A36593E338eBacdd6207640EfE",+ "swaps": [+ {+ "pool": "0xbc44b11f569d3FEEd9B4088F5A3fC569D2E3c77F",+ "amount0": "-20000000000000000",+ "amount1": "932814",+ "buysToken0": true,+ "price": 46.6407,+ "volume0": 0.02,+ "volume1": 0.932814,+ "spotPrice": 46.17544493405735,+ "sqrtPriceX96": "538375301743888990091266",+ "liquidity": "5049185190871963",+ "tick": -237998,+ "blockNumber": "11310357",+ "logIndex": 6,+ "transactionHash": "0x1aec13612ffd0ded6c4a83018fb553edd34822a7cd96f1dd6422daed91f033dd",+ "sender": "0xCaf681a66D020601342297493863E78C959E5cb2",+ "recipient": "0xD47A7eb5DA840F168E29C0a8711B4b73ECb243C5"+ }+ ]+ },+ {+ "poolInfo": {+ "pool": "0x0DDA7C6A2ccE72aBbFA88394aFe407fF98417448",+ "token0": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",+ "token1": "0x9D9c6684F596F66a64C030B93A886D51Fd4D7931",+ "fee": 10000,+ "decimals0": 6,+ "decimals1": 18+ },+ "symbol": "NBIS",+ "token": "0x9D9c6684F596F66a64C030B93A886D51Fd4D7931",+ "swaps": [+ {+ "pool": "0x0DDA7C6A2ccE72aBbFA88394aFe407fF98417448",+ "amount0": "19760629",+ "amount1": "-95979205861407660",+ "buysToken0": false,+ "price": 0.00485709264929814,+ "volume0": 19.760629,+ "volume1": 0.09597920586140767,+ "spotPrice": 0.004829765808607421,+ "sqrtPriceX96": "5506081305131709066431327719439196",+ "liquidity": "87319624929163",+ "tick": 222991,+ "blockNumber": "11329604",+ "logIndex": 37,+ "transactionHash": "0x60b4b7054834d7b7889a4a1e3075b8b847e473179d3fa2c0c71605c68376e8b1",+ "sender": "0xe72688F7d25D7318B9A81F21EdDa640CA948c83B",+ "recipient": "0x377Dc7E37963eB1679F01BDF93F6640B414D61DA"+ }+ ]+ },+ {+ "poolInfo": {+ "pool": "0xB944cec30Bd4175855215D767ADC81F39e5f7E2B",+ "token0": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",+ "token1": "0xd0601CE157Db5bdC3162BbaC2a2C8aF5320D9EEC",+ "fee": 3000,+ "decimals0": 6,+ "decimals1": 18+ },+ "symbol": "NVDA",+ "token": "0xd0601CE157Db5bdC3162BbaC2a2C8aF5320D9EEC",+ "swaps": [+ {+ "pool": "0xB944cec30Bd4175855215D767ADC81F39e5f7E2B",+ "amount0": "-18027954",+ "amount1": "87230916795535261",+ "buysToken0": true,+ "price": 0.004838647624435655,+ "volume0": 18.027954,+ "volume1": 0.08723091679553527,+ "spotPrice": 0.0048262476623677185,+ "sqrtPriceX96": "5504075542437105932839660128965973",+ "liquidity": "2855162145518691",+ "tick": 222984,+ "blockNumber": "11387409",+ "logIndex": 7,+ "transactionHash": "0x5af41bde62926b306a6debd4c441a0529109b0a7ea6e15164df756d30cd003a9",+ "sender": "0x8F10B468b06c6FD214B65F87778827F7D113f996",+ "recipient": "0x8F10B468b06c6FD214B65F87778827F7D113f996"+ },+ {+ "pool": "0xB944cec30Bd4175855215D767ADC81F39e5f7E2B",+ "amount0": "-3378578",+ "amount1": "16356267864837552",+ "buysToken0": true,+ "price": 0.004841169232984277,+ "volume0": 3.378578,+ "volume1": 0.016356267864837553,+ "spotPrice": 0.004827041261611937,+ "sqrtPriceX96": "5504528052435322482280152795259391",+ "liquidity": "2855162145518691",+ "tick": 222986,+ "blockNumber": "11393715",+ "logIndex": 7,+ "transactionHash": "0xaa69b3dd49bcdad748c10bb5221aa6ecf3d2351a4b834c3d0cc9ec16f2566481",+ "sender": "0x8F10B468b06c6FD214B65F87778827F7D113f996",+ "recipient": "0x8F10B468b06c6FD214B65F87778827F7D113f996"+ },+ {+ "pool": "0xB944cec30Bd4175855215D767ADC81F39e5f7E2B",+ "amount0": "-12358830",+ "amount1": "59854091424195833",+ "buysToken0": true,+ "price": 0.004843022472531448,+ "volume0": 12.35883,+ "volume1": 0.05985409142419583,+ "spotPrice": 0.00482994591318553,+ "sqrtPriceX96": "5506183966548947512707070043526470",+ "liquidity": "2855162145518691",+ "tick": 222992,+ "blockNumber": "11398011",+ "logIndex": 47,+ "transactionHash": "0x0abce89530a45b48e2c2e1bbc5c2379a0c51b3d762f4f23f87065c56e1cc56f1",+ "sender": "0xC94135b63772b91D79d0A2DaAb2a8801f32359bD",+ "recipient": "0xC94135b63772b91D79d0A2DaAb2a8801f32359bD"+ },+ {+ "pool": "0xB944cec30Bd4175855215D767ADC81F39e5f7E2B",+ "amount0": "-2003821",+ "amount1": "9707943880557922",+ "buysToken0": true,+ "price": 0.004844716110150519,+ "volume0": 2.003821,+ "volume1": 0.009707943880557922,+ "spotPrice": 0.004830417111100022,+ "sqrtPriceX96": "5506452545035456742871430198921248",+ "liquidity": "2855162145518691",+ "tick": 222993,+ "blockNumber": "11403585",+ "logIndex": 7,+ "transactionHash": "0xa708a87d26eddf06944d8a517bfa0b4ec57b0e3f816e0da11e9b4a4652ea9390",+ "sender": "0x2a7F3d7486641C77600b9b9256132755c8AEBB4F",+ "recipient": "0xE58b3089dF6667fBf99b75595a1671BaF6797D6d"+ },+ {+ "pool": "0xB944cec30Bd4175855215D767ADC81F39e5f7E2B",+ "amount0": "-4850456",+ "amount1": "23503002884103144",+ "buysToken0": true,+ "price": 0.0048455243969027124,+ "volume0": 4.850456,+ "volume1": 0.023503002884103143,+ "spotPrice": 0.004831557979862283,+ "sqrtPriceX96": "5507102775508634109036687957152888",+ "liquidity": "2855162145518691",+ "tick": 222995,+ "blockNumber": "11413835",+ "logIndex": 10,+ "transactionHash": "0xb955cb60709c64ac46e23476eb9459a5d5c9a3ef545cedb6368ab425792e903f",+ "sender": "0xCaf681a66D020601342297493863E78C959E5cb2",+ "recipient": "0x832bF06223e7114FdEBf4F371dAf1c4063d677ec"+ },+ {+ "pool": "0xB944cec30Bd4175855215D767ADC81F39e5f7E2B",+ "amount0": "2000000",+ "amount1": "-9633658952903963",+ "buysToken0": false,+ "price": 0.004816829476451982,+ "volume0": 2,+ "volume1": 0.009633658952903964,+ "spotPrice": 0.004831088925107118,+ "sqrtPriceX96": "5506835450201619360273482563559834",+ "liquidity": "2855162145518691",+ "tick": 222994,+ "blockNumber": "11415775",+ "logIndex": 48,+ "transactionHash": "0x5843c8ade3cbb8d7f6787041bc6c78d6ef232f684013b26dcf80c05483fdf5cf",+ "sender": "0x8876789976dEcBfCbBbe364623C63652db8C0904",+ "recipient": "0x320656660Ab220725408F6A347768549BF04C650"+ },+ {+ "pool": "0xB944cec30Bd4175855215D767ADC81F39e5f7E2B",+ "amount0": "3746144",+ "amount1": "-18042017756732411",+ "buysToken0": false,+ "price": 0.004816157028862855,+ "volume0": 3.746144,+ "volume1": 0.018042017756732413,+ "spotPrice": 0.004830210535683125,+ "sqrtPriceX96": "5506334800556498783093135303350512",+ "liquidity": "2855162145518691",+ "tick": 222992,+ "blockNumber": "11420000",+ "logIndex": 20,+ "transactionHash": "0xecbd93a6c00adfc9819a50633de9458164435dba2f16e2f42664b94b6a461925",+ "sender": "0xCaf681a66D020601342297493863E78C959E5cb2",+ "recipient": "0xd7460251F0f008Ca7a97d888aaf408C227d8c224"+ },+ {+ "pool": "0xB944cec30Bd4175855215D767ADC81F39e5f7E2B",+ "amount0": "492412",+ "amount1": "-2371284432464588",+ "buysToken0": false,+ "price": 0.0048156511873483744,+ "volume0": 0.492412,+ "volume1": 0.002371284432464588,+ "spotPrice": 0.004830095093826095,+ "sqrtPriceX96": "5506268999562086705991418915376599",+ "liquidity": "2855162145518691",+ "tick": 222992,+ "blockNumber": "11420206",+ "logIndex": 7,+ "transactionHash": "0x238b43dab4257ebdfc80bb3e572110a98f22f942c9da71770a400591755afcf0",+ "sender": "0x8876789976dEcBfCbBbe364623C63652db8C0904",+ "recipient": "0xF45E322a96774E21addaccc39793ea2CB6917cF4"+ }+ ]+ }+ ]+}diff --git a/robinhood/hood-alerts/tests/gate.test.ts b/robinhood/hood-alerts/tests/gate.test.tsnew file mode 100644index 000000000..6c3709412--- /dev/null+++ b/robinhood/hood-alerts/tests/gate.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from 'vitest'+import { FREE_MIN_INTERVAL_S, MAX_PER_MINUTE, gate, inQuietHours } from '../src/engine/gate.js'++describe('inQuietHours', () => {+ it('returns false when either bound is null', () => {+ expect(inQuietHours(3, null, 7)).toBe(false)+ expect(inQuietHours(3, 22, null)).toBe(false)+ })++ it('returns false when start equals end (no window)', () => {+ expect(inQuietHours(5, 8, 8)).toBe(false)+ })++ it('handles a same-day window', () => {+ expect(inQuietHours(9, 8, 17)).toBe(true)+ expect(inQuietHours(8, 8, 17)).toBe(true)+ expect(inQuietHours(17, 8, 17)).toBe(false)+ expect(inQuietHours(7, 8, 17)).toBe(false)+ })++ it('handles a wrap-around window (e.g. 22 -> 7)', () => {+ expect(inQuietHours(23, 22, 7)).toBe(true)+ expect(inQuietHours(22, 22, 7)).toBe(true)+ expect(inQuietHours(3, 22, 7)).toBe(true)+ expect(inQuietHours(6, 22, 7)).toBe(true)+ expect(inQuietHours(7, 22, 7)).toBe(false)+ expect(inQuietHours(12, 22, 7)).toBe(false)+ })+})++describe('gate', () => {+ const base = {+ premium: false,+ digest: false,+ quietStart: null,+ quietEnd: null,+ lastDeliveredAt: null,+ deliveredLastMinute: 0,+ }++ it('delivers immediately when nothing gates it', () => {+ expect(gate(base, 1_700_000_000)).toEqual({ action: 'deliver' })+ })++ it('drops when the per-minute burst cap is hit, before any other check', () => {+ const input = { ...base, premium: true, deliveredLastMinute: MAX_PER_MINUTE }+ expect(gate(input, 1_700_000_000)).toEqual({ action: 'drop', reason: 'rate-limited' })+ })++ it('digests during quiet hours even for premium subscribers', () => {+ // 1_700_000_000 is a Tuesday; hourUtc = floor((t % 86400) / 3600)+ const nowS = 1_700_000_000+ const hourUtc = Math.floor((nowS % 86_400) / 3600)+ const input = { ...base, premium: true, quietStart: hourUtc, quietEnd: (hourUtc + 1) % 24 }+ expect(gate(input, nowS)).toEqual({ action: 'digest', reason: 'quiet-hours' })+ })++ it('digests when the subscriber has digest mode on', () => {+ const input = { ...base, premium: true, digest: true }+ expect(gate(input, 1_700_000_000)).toEqual({ action: 'digest', reason: 'digest-mode' })+ })++ it('enforces free-tier minimum granularity between deliveries', () => {+ const nowS = 1_700_000_000+ const input = { ...base, lastDeliveredAt: nowS - (FREE_MIN_INTERVAL_S - 1) }+ expect(gate(input, nowS)).toEqual({ action: 'digest', reason: 'free-granularity' })+ })++ it('allows a free-tier delivery once the granularity window has passed', () => {+ const nowS = 1_700_000_000+ const input = { ...base, lastDeliveredAt: nowS - FREE_MIN_INTERVAL_S }+ expect(gate(input, nowS)).toEqual({ action: 'deliver' })+ })++ it('never applies free-granularity to premium subscribers', () => {+ const nowS = 1_700_000_000+ const input = { ...base, premium: true, lastDeliveredAt: nowS }+ expect(gate(input, nowS)).toEqual({ action: 'deliver' })+ })++ it('quiet-hours takes priority over digest-mode', () => {+ const nowS = 1_700_000_000+ const hourUtc = Math.floor((nowS % 86_400) / 3600)+ const input = { ...base, digest: true, quietStart: hourUtc, quietEnd: (hourUtc + 1) % 24 }+ expect(gate(input, nowS)).toEqual({ action: 'digest', reason: 'quiet-hours' })+ })+})diff --git a/robinhood/hood-alerts/tests/paywall.test.ts b/robinhood/hood-alerts/tests/paywall.test.tsnew file mode 100644index 000000000..0b7f4cd63--- /dev/null+++ b/robinhood/hood-alerts/tests/paywall.test.ts@@ -0,0 +1,90 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { openDb, type Db } from '../src/db/index.js'+import { EntitlementRepo } from '../src/db/entitlements.js'+import { PremiumPaywall } from '../src/premium/paywall.js'+import type { Config } from '../src/config.js'++const DETECTORS = {+ whaleFloorUsd: 1000,+ whaleDefaultUsd: 5000,+ priceWindowS: 900,+ priceDefaultPct: 2,+ premiumPollS: 60,+ premiumDefaultPct: 2,+ rugDefaultPct: 30,+}++function makeConfig(overrides: Partial<Config> = {}): Config {+ return {+ rpcUrl: undefined,+ dbPath: ':memory:',+ port: 8080,+ publicUrl: 'http://localhost:8080',+ telegramToken: null,+ discordToken: null,+ discordAppId: null,+ premiumRail: 'hood402',+ payTo: null,+ facilitatorUrl: null,+ settlerKey: null,+ premiumPriceUsdg: '5',+ premiumDays: 30,+ detectors: DETECTORS,+ ...overrides,+ }+}++let db: Db+let entitlements: EntitlementRepo++beforeEach(() => {+ db = openDb(':memory:')+ entitlements = new EntitlementRepo(db)+})++afterEach(() => {+ db.close()+})++describe('PremiumPaywall.enabled', () => {+ it('is disabled with no payTo configured', () => {+ const paywall = new PremiumPaywall(makeConfig(), entitlements)+ expect(paywall.enabled).toBe(false)+ })++ it('is disabled with a payTo but neither a facilitator nor a settler key', () => {+ const paywall = new PremiumPaywall(makeConfig({ payTo: '0x4022de2D36C334E73C7a108805Cea11C0564f402' }), entitlements)+ expect(paywall.enabled).toBe(false)+ })++ it('is enabled with a payTo and a facilitator URL', () => {+ const paywall = new PremiumPaywall(+ makeConfig({ payTo: '0x4022de2D36C334E73C7a108805Cea11C0564f402', facilitatorUrl: 'https://facilitator.example' }),+ entitlements,+ )+ expect(paywall.enabled).toBe(true)+ })+})++describe('PremiumPaywall.activate: unconfigured instance', () => {+ it('returns 503 with setup guidance and never touches entitlements', async () => {+ const paywall = new PremiumPaywall(makeConfig(), entitlements)+ const result = await paywall.activate('telegram', 'chat-1', undefined, 'http://localhost:8080/premium/activate')+ expect(result.status).toBe(503)+ if (result.status !== 503) throw new Error('unreachable')+ expect(result.body).toMatchObject({ error: expect.stringContaining('not configured') })+ expect(entitlements.isPremium('telegram', 'chat-1')).toBe(false)+ })+})++describe('PremiumPaywall.activate: configured instance, unpaid request', () => {+ it('returns a 402 challenge on the first (unpaid) request', async () => {+ const paywall = new PremiumPaywall(+ makeConfig({ payTo: '0x4022de2D36C334E73C7a108805Cea11C0564f402', facilitatorUrl: 'https://facilitator.example' }),+ entitlements,+ )+ const result = await paywall.activate('telegram', 'chat-1', undefined, 'http://localhost:8080/premium/activate?platform=telegram&chat=chat-1')+ expect(result.status).toBe(402)+ expect(entitlements.isPremium('telegram', 'chat-1')).toBe(false)+ })+})diff --git a/robinhood/hood-alerts/tests/server.test.ts b/robinhood/hood-alerts/tests/server.test.tsnew file mode 100644index 000000000..f2e50d578--- /dev/null+++ b/robinhood/hood-alerts/tests/server.test.ts@@ -0,0 +1,161 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { openDb, type Db } from '../src/db/index.js'+import { AlertEngine } from '../src/engine/engine.js'+import { buildApp } from '../src/server.js'+import type { Config } from '../src/config.js'+import type { DetectorConfig } from '../src/config.js'+import type { LiveDetectors } from '../src/engine/detectors/live.js'+import type { PremiumPaywall } from '../src/premium/paywall.js'+import type { ActivationResult } from '../src/premium/paywall.js'++const DETECTORS: DetectorConfig = {+ whaleFloorUsd: 1000,+ whaleDefaultUsd: 5000,+ priceWindowS: 900,+ priceDefaultPct: 2,+ premiumPollS: 60,+ premiumDefaultPct: 2,+ rugDefaultPct: 30,+}++function makeConfig(): Config {+ return {+ rpcUrl: undefined,+ dbPath: ':memory:',+ port: 8080,+ publicUrl: 'http://localhost:8080',+ telegramToken: null,+ discordToken: null,+ discordAppId: null,+ premiumRail: 'hood402',+ payTo: null,+ facilitatorUrl: null,+ settlerKey: null,+ premiumPriceUsdg: '5',+ premiumDays: 30,+ detectors: DETECTORS,+ }+}++function fakeDetectors(overrides: Partial<{ lastEventAt: number | null; eventCounts: Record<string, number> }> = {}): LiveDetectors {+ return {+ lastEventAt: overrides.lastEventAt ?? null,+ eventCounts: overrides.eventCounts ?? {},+ } as unknown as LiveDetectors+}++function fakePaywall(enabled: boolean, activate?: (...args: unknown[]) => Promise<ActivationResult>): PremiumPaywall {+ return {+ enabled,+ activate: activate ?? (async () => ({ status: 503, body: { error: 'not configured' } })),+ } as unknown as PremiumPaywall+}++let db: Db+let engine: AlertEngine++beforeEach(() => {+ db = openDb(':memory:')+ engine = new AlertEngine(db, DETECTORS)+})++afterEach(() => {+ db.close()+})++describe('GET /', () => {+ it('describes the service', async () => {+ const app = buildApp({ config: makeConfig(), engine, detectors: fakeDetectors(), paywall: fakePaywall(false), startedAt: 0 })+ const res = await app.request('/')+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body).toMatchObject({ service: 'hood-alerts', chain: 4663 })+ })+})++describe('GET /healthz', () => {+ it('reports uptime, last event time, and event counts', async () => {+ const app = buildApp({+ config: makeConfig(),+ engine,+ detectors: fakeDetectors({ lastEventAt: 1_700_000_000, eventCounts: { whale: 3 } }),+ paywall: fakePaywall(true),+ startedAt: 1_699_999_000,+ })+ const res = await app.request('/healthz')+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body.ok).toBe(true)+ expect(body.lastEventAt).toBe(new Date(1_700_000_000 * 1000).toISOString())+ expect(body.eventCounts).toEqual({ whale: 3 })+ expect(body.premiumPurchases).toBe(true)+ })++ it('reports lastEventAt as null when nothing has been ingested yet', async () => {+ const app = buildApp({ config: makeConfig(), engine, detectors: fakeDetectors(), paywall: fakePaywall(false), startedAt: 0 })+ const res = await app.request('/healthz')+ const body = await res.json()+ expect(body.lastEventAt).toBeNull()+ })+})++describe('GET /premium/status', () => {+ it('rejects a missing or invalid platform/chat', async () => {+ const app = buildApp({ config: makeConfig(), engine, detectors: fakeDetectors(), paywall: fakePaywall(false), startedAt: 0 })+ const res = await app.request('/premium/status')+ expect(res.status).toBe(400)+ const res2 = await app.request('/premium/status?platform=bogus&chat=x')+ expect(res2.status).toBe(400)+ })++ it('reports free tier for an unentitled chat', async () => {+ const app = buildApp({ config: makeConfig(), engine, detectors: fakeDetectors(), paywall: fakePaywall(false), startedAt: 0 })+ const res = await app.request('/premium/status?platform=telegram&chat=chat-1')+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body).toEqual({ platform: 'telegram', chat: 'chat-1', tier: 'free', expiresAt: null })+ })++ it('reports premium tier with an expiry for an entitled chat', async () => {+ engine.entitlements.activate('telegram', 'chat-1', 86_400)+ const app = buildApp({ config: makeConfig(), engine, detectors: fakeDetectors(), paywall: fakePaywall(false), startedAt: 0 })+ const res = await app.request('/premium/status?platform=telegram&chat=chat-1')+ const body = await res.json()+ expect(body.tier).toBe('premium')+ expect(body.expiresAt).not.toBeNull()+ })+})++describe('POST /premium/activate', () => {+ it('rejects a missing or invalid platform/chat', async () => {+ const app = buildApp({ config: makeConfig(), engine, detectors: fakeDetectors(), paywall: fakePaywall(false), startedAt: 0 })+ const res = await app.request('/premium/activate', { method: 'POST' })+ expect(res.status).toBe(400)+ })++ it('proxies a non-200 paywall result straight through with its status', async () => {+ const paywall = fakePaywall(false, async () => ({ status: 503, body: { error: 'not configured' } }))+ const app = buildApp({ config: makeConfig(), engine, detectors: fakeDetectors(), paywall, startedAt: 0 })+ const res = await app.request('/premium/activate?platform=telegram&chat=chat-1', { method: 'POST' })+ expect(res.status).toBe(503)+ const body = await res.json()+ expect(body.error).toBe('not configured')+ })++ it('proxies a 402 challenge through with its body', async () => {+ const paywall = fakePaywall(true, async () => ({ status: 402, body: { x402Version: 1, accepts: [] } }))+ const app = buildApp({ config: makeConfig(), engine, detectors: fakeDetectors(), paywall, startedAt: 0 })+ const res = await app.request('/premium/activate?platform=telegram&chat=chat-1', { method: 'POST' })+ expect(res.status).toBe(402)+ })++ it('sets the settlement header and returns 200 on success', async () => {+ const paywall = fakePaywall(true, async () => ({ status: 200, body: { activated: true }, settlementHeader: 'settlement-abc' }))+ const app = buildApp({ config: makeConfig(), engine, detectors: fakeDetectors(), paywall, startedAt: 0 })+ const res = await app.request('/premium/activate?platform=telegram&chat=chat-1', { method: 'POST' })+ expect(res.status).toBe(200)+ expect(res.headers.get('x-payment-response')).toBe('settlement-abc')+ const body = await res.json()+ expect(body.activated).toBe(true)+ })+})diff --git a/robinhood/hood-alerts/tests/token-meta.test.ts b/robinhood/hood-alerts/tests/token-meta.test.tsnew file mode 100644index 000000000..dd76247fd--- /dev/null+++ b/robinhood/hood-alerts/tests/token-meta.test.ts@@ -0,0 +1,60 @@+import { describe, expect, it, vi } from 'vitest'+import { TokenMetaCache } from '../src/engine/token-meta.js'+import type { HoodClient } from 'hoodchain'+import type { Address } from 'viem'++const TOKEN = '0x1234567890123456789012345678901234567890' as Address++function fakeClient(multicall: (args: unknown) => Promise<unknown>): HoodClient {+ return { public: { multicall } } as unknown as HoodClient+}++describe('TokenMetaCache', () => {+ it('returns symbol and name on a successful multicall', async () => {+ const multicall = vi.fn().mockResolvedValue([+ { status: 'success', result: 'FOO' },+ { status: 'success', result: 'Foo Coin' },+ ])+ const cache = new TokenMetaCache(fakeClient(multicall))+ expect(await cache.get(TOKEN)).toEqual({ symbol: 'FOO', name: 'Foo Coin' })+ })++ it('caches by lowercased address and only calls multicall once', async () => {+ const multicall = vi.fn().mockResolvedValue([+ { status: 'success', result: 'FOO' },+ { status: 'success', result: 'Foo Coin' },+ ])+ const cache = new TokenMetaCache(fakeClient(multicall))+ await cache.get(TOKEN)+ await cache.get(TOKEN.toUpperCase() as Address)+ expect(multicall).toHaveBeenCalledTimes(1)+ })++ it('returns nulls for a failed call leg without throwing', async () => {+ const multicall = vi.fn().mockResolvedValue([+ { status: 'failure' },+ { status: 'success', result: 'Foo Coin' },+ ])+ const cache = new TokenMetaCache(fakeClient(multicall))+ expect(await cache.get(TOKEN)).toEqual({ symbol: null, name: 'Foo Coin' })+ })++ it('caches nulls when the whole multicall throws, so a broken token is not retried', async () => {+ const multicall = vi.fn().mockRejectedValue(new Error('rpc down'))+ const cache = new TokenMetaCache(fakeClient(multicall))+ expect(await cache.get(TOKEN)).toEqual({ symbol: null, name: null })+ await cache.get(TOKEN)+ expect(multicall).toHaveBeenCalledTimes(1)+ })++ it('truncates an oversized symbol/name to their max lengths', async () => {+ const multicall = vi.fn().mockResolvedValue([+ { status: 'success', result: 'X'.repeat(50) },+ { status: 'success', result: 'Y'.repeat(100) },+ ])+ const cache = new TokenMetaCache(fakeClient(multicall))+ const meta = await cache.get(TOKEN)+ expect(meta.symbol).toHaveLength(32)+ expect(meta.name).toHaveLength(64)+ })+})diff --git a/robinhood/hood-alerts/tests/topics.test.ts b/robinhood/hood-alerts/tests/topics.test.tsnew file mode 100644index 000000000..5ea244d2d--- /dev/null+++ b/robinhood/hood-alerts/tests/topics.test.ts@@ -0,0 +1,185 @@+import { describe, expect, it } from 'vitest'+import { defaultThreshold, matches, parseTopic, resolveWatchTarget, PREMIUM_TOPICS } from '../src/engine/topics.js'+import type { AlertEvent } from '../src/engine/events.js'++describe('parseTopic', () => {+ it('parses the fixed topics', () => {+ expect(parseTopic('launches')).toEqual({ kind: 'launches', launchpad: null })+ expect(parseTopic('launches:noxa')).toEqual({ kind: 'launches', launchpad: 'noxa' })+ expect(parseTopic('launches:odyssey')).toEqual({ kind: 'launches', launchpad: 'odyssey' })+ expect(parseTopic('graduations')).toEqual({ kind: 'graduations' })+ expect(parseTopic('whales')).toEqual({ kind: 'whales' })+ expect(parseTopic('premiums')).toEqual({ kind: 'premiums' })+ expect(parseTopic('rugs')).toEqual({ kind: 'rugs' })+ })++ it('parses a token topic from a lowercase 0x address', () => {+ const addr = '0x1234567890123456789012345678901234567890'+ expect(parseTopic(`token:${addr}`)).toEqual({ kind: 'token', address: addr })+ })++ it('rejects a token topic with an uppercase or malformed address', () => {+ expect(parseTopic('token:0x1234567890123456789012345678901234567890'.toUpperCase())).toBeNull()+ expect(parseTopic('token:0xnotanaddress')).toBeNull()+ })++ it('parses a stock topic', () => {+ expect(parseTopic('stock:TSLA')).toEqual({ kind: 'stock', symbol: 'TSLA' })+ expect(parseTopic('stock:AAPL.X')).toEqual({ kind: 'stock', symbol: 'AAPL.X' })+ })++ it('rejects an unknown or malformed topic', () => {+ expect(parseTopic('bogus')).toBeNull()+ expect(parseTopic('stock:')).toBeNull()+ expect(parseTopic('stock:lowercase')).toBeNull()+ })+})++describe('resolveWatchTarget', () => {+ it('resolves the fixed keywords, case-insensitively', () => {+ expect(resolveWatchTarget('Launches')).toEqual({ ok: true, topic: 'launches' })+ expect(resolveWatchTarget('launch')).toEqual({ ok: true, topic: 'launches' })+ expect(resolveWatchTarget('NOXA')).toEqual({ ok: true, topic: 'launches:noxa' })+ expect(resolveWatchTarget('odyssey')).toEqual({ ok: true, topic: 'launches:odyssey' })+ expect(resolveWatchTarget('grads')).toEqual({ ok: true, topic: 'graduations' })+ expect(resolveWatchTarget('whale')).toEqual({ ok: true, topic: 'whales' })+ expect(resolveWatchTarget('arb')).toEqual({ ok: true, topic: 'premiums' })+ expect(resolveWatchTarget('liquidity')).toEqual({ ok: true, topic: 'rugs' })+ })++ it('resolves a 0x address to a lowercased token topic', () => {+ const addr = '0xABCDEF1234567890ABCDEF1234567890ABCDEF12'+ expect(resolveWatchTarget(addr)).toEqual({ ok: true, topic: `token:${addr.toLowerCase()}` })+ })++ it('resolves a known Stock Token ticker, uppercased', () => {+ expect(resolveWatchTarget('tsla')).toEqual({ ok: true, topic: 'stock:TSLA' })+ })++ it('errors on a ticker-shaped string that is not a real Stock Token', () => {+ const result = resolveWatchTarget('NOTREAL')+ expect(result.ok).toBe(false)+ if (result.ok) throw new Error('unreachable')+ expect(result.error).toMatch(/not a Robinhood Chain Stock Token ticker/)+ })++ it('errors on garbage input', () => {+ const result = resolveWatchTarget('!!! not valid !!!')+ expect(result.ok).toBe(false)+ if (result.ok) throw new Error('unreachable')+ expect(result.error).toMatch(/Cannot watch/)+ })++ it('trims whitespace before resolving', () => {+ expect(resolveWatchTarget(' launches ')).toEqual({ ok: true, topic: 'launches' })+ })+})++describe('PREMIUM_TOPICS', () => {+ it('gates exactly premiums and rugs', () => {+ expect(PREMIUM_TOPICS.has('premiums')).toBe(true)+ expect(PREMIUM_TOPICS.has('rugs')).toBe(true)+ expect(PREMIUM_TOPICS.has('whales')).toBe(false)+ expect(PREMIUM_TOPICS.has('launches')).toBe(false)+ })+})++describe('defaultThreshold', () => {+ const defaults = { whaleUsd: 5000, premiumPct: 2, rugPct: 30, pricePct: 2 }++ it('returns the right default per topic kind', () => {+ expect(defaultThreshold({ kind: 'whales' }, defaults)).toBe(5000)+ expect(defaultThreshold({ kind: 'premiums' }, defaults)).toBe(2)+ expect(defaultThreshold({ kind: 'rugs' }, defaults)).toBe(30)+ expect(defaultThreshold({ kind: 'stock', symbol: 'TSLA' }, defaults)).toBe(2)+ expect(defaultThreshold({ kind: 'token', address: '0xabc' as `0x${string}` }, defaults)).toBe(5000)+ })++ it('returns null for topics with no threshold semantics', () => {+ expect(defaultThreshold({ kind: 'launches', launchpad: null }, defaults)).toBeNull()+ expect(defaultThreshold({ kind: 'graduations' }, defaults)).toBeNull()+ })+})++describe('matches', () => {+ const TOKEN = '0x1234567890123456789012345678901234567890' as `0x${string}`+ const OTHER_TOKEN = '0x0000000000000000000000000000000000dead' as `0x${string}`++ function launchEvent(launchpad: 'noxa' | 'odyssey'): AlertEvent {+ return {+ type: 'launch',+ launchpad,+ token: TOKEN,+ symbol: 'X',+ name: null,+ creator: TOKEN,+ pool: null,+ blockNumber: 1n,+ transactionHash: '0x1',+ at: 0,+ }+ }++ it('launches matches any launchpad when unfiltered, and filters when set', () => {+ expect(matches({ kind: 'launches', launchpad: null }, null, launchEvent('noxa'))).toBe(true)+ expect(matches({ kind: 'launches', launchpad: 'noxa' }, null, launchEvent('noxa'))).toBe(true)+ expect(matches({ kind: 'launches', launchpad: 'odyssey' }, null, launchEvent('noxa'))).toBe(false)+ })++ it('graduations matches only graduation events', () => {+ const grad: AlertEvent = { type: 'graduation', token: TOKEN, symbol: null, name: null, pool: TOKEN, blockNumber: 1n, transactionHash: '0x1', at: 0 }+ expect(matches({ kind: 'graduations' }, null, grad)).toBe(true)+ expect(matches({ kind: 'graduations' }, null, launchEvent('noxa'))).toBe(false)+ })++ it('whales matches on type and threshold', () => {+ const whale: AlertEvent = { type: 'whale', source: 'uniswap-v3', token: TOKEN, symbol: null, side: 'buy', usd: 6000, trader: TOKEN, blockNumber: 1n, transactionHash: '0x1', at: 0 }+ expect(matches({ kind: 'whales' }, 5000, whale)).toBe(true)+ expect(matches({ kind: 'whales' }, 7000, whale)).toBe(false)+ expect(matches({ kind: 'whales' }, null, whale)).toBe(true)+ expect(matches({ kind: 'launches', launchpad: null }, null, whale)).toBe(false)+ })++ it('premiums matches on the absolute percent', () => {+ const premium = (pct: number): AlertEvent => ({+ type: 'premium',+ symbol: 'TSLA',+ token: TOKEN,+ premiumPct: pct,+ level: Math.abs(pct),+ direction: pct >= 0 ? 'premium' : 'discount',+ dexUsd: 100,+ feedUsd: 98,+ pool: TOKEN,+ at: 0,+ })+ expect(matches({ kind: 'premiums' }, 2, premium(-3))).toBe(true)+ expect(matches({ kind: 'premiums' }, 2, premium(3))).toBe(true)+ expect(matches({ kind: 'premiums' }, 5, premium(3))).toBe(false)+ })++ it('rugs matches on dropped percent', () => {+ const pull: AlertEvent = { type: 'liquidity_pull', token: TOKEN, symbol: null, pool: TOKEN, quoteAsset: 'USDG', droppedPct: 40, beforeUsd: 100, afterUsd: 60, at: 0 }+ expect(matches({ kind: 'rugs' }, 30, pull)).toBe(true)+ expect(matches({ kind: 'rugs' }, 50, pull)).toBe(false)+ })++ it('token matches by address across event kinds it applies to', () => {+ const whale: AlertEvent = { type: 'whale', source: 'uniswap-v3', token: TOKEN, symbol: null, side: 'buy', usd: 100, trader: TOKEN, blockNumber: 1n, transactionHash: '0x1', at: 0 }+ const otherWhale: AlertEvent = { ...whale, token: OTHER_TOKEN }+ const holders: AlertEvent = { type: 'holders', token: TOKEN, symbol: null, milestone: 100, count: 101, at: 0 }+ const priceMove: AlertEvent = { type: 'price_move', symbol: 'TSLA', pct: 5, fromUsd: 1, toUsd: 1.05, windowS: 900, at: 0 }++ expect(matches({ kind: 'token', address: TOKEN }, 0, whale)).toBe(true)+ expect(matches({ kind: 'token', address: TOKEN }, 0, otherWhale)).toBe(false)+ expect(matches({ kind: 'token', address: TOKEN }, null, holders)).toBe(true)+ expect(matches({ kind: 'token', address: TOKEN }, null, priceMove)).toBe(false)+ })++ it('stock matches by symbol for price_move and premium', () => {+ const priceMove: AlertEvent = { type: 'price_move', symbol: 'TSLA', pct: -3, fromUsd: 100, toUsd: 97, windowS: 900, at: 0 }+ expect(matches({ kind: 'stock', symbol: 'TSLA' }, 2, priceMove)).toBe(true)+ expect(matches({ kind: 'stock', symbol: 'AAPL' }, 2, priceMove)).toBe(false)+ expect(matches({ kind: 'stock', symbol: 'TSLA' }, 5, priceMove)).toBe(false)+ })+})diff --git a/robinhood/hood-alerts/tsconfig.json b/robinhood/hood-alerts/tsconfig.jsonnew file mode 100644index 000000000..d3e10f0c3--- /dev/null+++ b/robinhood/hood-alerts/tsconfig.json@@ -0,0 +1,23 @@+{+ "compilerOptions": {+ "target": "ES2023",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "lib": ["ES2023"],+ "outDir": "dist",+ "rootDir": ".",+ "declaration": true,+ "sourceMap": true,+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "noImplicitOverride": true,+ "exactOptionalPropertyTypes": true,+ "forceConsistentCasingInFileNames": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "resolveJsonModule": true,+ "types": ["node"]+ },+ "include": ["src/**/*.ts", "scripts/**/*.ts"],+ "exclude": ["node_modules", "dist", "tests", "docs", "examples"]+}diff --git a/robinhood/hood-alerts/vitest.config.ts b/robinhood/hood-alerts/vitest.config.tsnew file mode 100644index 000000000..1029dc44a--- /dev/null+++ b/robinhood/hood-alerts/vitest.config.ts@@ -0,0 +1,9 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ include: ['tests/**/*.test.ts'],+ exclude: ['tests/live/**', 'node_modules/**'],+ testTimeout: 20_000,+ },+})