Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add hood-js library for simplified Robinhood Chain interactions
fudjia7bf4b43ba03d
diff --git a/robinhood/hood-api/src/routes/free.ts b/robinhood/hood-api/src/routes/free.tsnew file mode 100644index 000000000..35354724a--- /dev/null+++ b/robinhood/hood-api/src/routes/free.ts@@ -0,0 +1,201 @@+import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi'+import { ApiError, toApiError } from '../lib/errors.js'+import { nowIso } from '../lib/response.js'+import {+ SymbolParam,+ AddressParam,+ LaunchesQuery,+ CoinsQuery,+ ErrorSchema,+ LOOKBACK_BLOCKS,+} from '../schemas.js'+import { getChain } from '../services/chain.js'+import { listStocks, getStockDetail } from '../services/stocks.js'+import { listCoins, getCoinDetail } from '../services/coins.js'+import { getLaunches } from '../services/launches.js'+import { mainnetClient } from '../upstreams/rpc.js'+import { env } from '../lib/env.js'+import pkg from '../../package.json' with { type: 'json' }++export const freeRoutes = new OpenAPIHono()++const JsonBody = z.record(z.string(), z.unknown())++function fail(err: unknown) {+ const apiErr = toApiError(err)+ return { status: apiErr.status, body: apiErr.toBody() } as const+}++// ---- /v1/health ----+freeRoutes.openapi(+ createRoute({+ method: 'get',+ path: '/v1/health',+ tags: ['Health'],+ summary: 'Service liveness + RPC reachability',+ responses: { 200: { content: { 'application/json': { schema: JsonBody } }, description: 'OK' } },+ }),+ async (c) => {+ let rpcOk = true+ let blockHeight: string | null = null+ try {+ blockHeight = (await mainnetClient().public.getBlockNumber()).toString()+ } catch {+ rpcOk = false+ }+ return c.json({+ status: rpcOk ? 'ok' : 'degraded',+ version: pkg.version,+ chainId: 4663,+ rpcOk,+ blockHeight,+ paymentsEnabled: env.x402PayTo.length > 0,+ asOf: nowIso(),+ })+ },+)++// ---- /v1/chain ----+freeRoutes.openapi(+ createRoute({+ method: 'get',+ path: '/v1/chain',+ tags: ['Chain'],+ summary: 'Chain stats: block height, gas, TVL, ETH price',+ responses: {+ 200: { content: { 'application/json': { schema: JsonBody } }, description: 'Chain stats' },+ 502: { content: { 'application/json': { schema: ErrorSchema } }, description: 'Upstream unavailable' },+ },+ }),+ async (c) => {+ try {+ return c.json(await getChain())+ } catch (err) {+ const { status, body } = fail(err)+ return c.json(body, status)+ }+ },+)++// ---- /v1/stocks ----+freeRoutes.openapi(+ createRoute({+ method: 'get',+ path: '/v1/stocks',+ tags: ['Stocks'],+ summary: 'All Stock Tokens: Chainlink price, DEX price, premium/discount, liquidity',+ responses: {+ 200: { content: { 'application/json': { schema: JsonBody } }, description: 'Stock Token list' },+ 502: { content: { 'application/json': { schema: ErrorSchema } }, description: 'Upstream unavailable' },+ },+ }),+ async (c) => {+ try {+ return c.json(await listStocks())+ } catch (err) {+ const { status, body } = fail(err)+ return c.json(body, status)+ }+ },+)++// ---- /v1/stocks/:symbol ----+freeRoutes.openapi(+ createRoute({+ method: 'get',+ path: '/v1/stocks/{symbol}',+ tags: ['Stocks'],+ summary: 'Stock Token detail: candles, holders, feed metadata, links',+ request: {+ params: SymbolParam,+ query: z.object({ interval: z.enum(['5m', '15m', '1h', '4h', '1d']).optional() }),+ },+ responses: {+ 200: { content: { 'application/json': { schema: JsonBody } }, description: 'Stock Token detail' },+ 404: { content: { 'application/json': { schema: ErrorSchema } }, description: 'Unknown symbol' },+ },+ }),+ async (c) => {+ const { symbol } = c.req.valid('param')+ const { interval } = c.req.valid('query')+ try {+ return c.json(await getStockDetail(symbol, interval ?? '1h'))+ } catch (err) {+ const { status, body } = fail(err)+ return c.json(body, status)+ }+ },+)++// ---- /v1/coins ----+freeRoutes.openapi(+ createRoute({+ method: 'get',+ path: '/v1/coins',+ tags: ['Coins'],+ summary: 'Memecoins: launchpad state, price, liquidity, holders, age',+ request: { query: CoinsQuery },+ responses: {+ 200: { content: { 'application/json': { schema: JsonBody } }, description: 'Coin list' },+ },+ }),+ async (c) => {+ const { limit } = c.req.valid('query')+ try {+ return c.json(await listCoins({ limit }))+ } catch (err) {+ const { status, body } = fail(err)+ return c.json(body, status)+ }+ },+)++// ---- /v1/coins/:address ----+freeRoutes.openapi(+ createRoute({+ method: 'get',+ path: '/v1/coins/{address}',+ tags: ['Coins'],+ summary: 'Coin detail: launch info, graduation status, DEX stats, holders',+ request: { params: AddressParam },+ responses: {+ 200: { content: { 'application/json': { schema: JsonBody } }, description: 'Coin detail' },+ 400: { content: { 'application/json': { schema: ErrorSchema } }, description: 'Invalid address' },+ },+ }),+ async (c) => {+ const { address } = c.req.valid('param')+ try {+ return c.json(await getCoinDetail(address))+ } catch (err) {+ const { status, body } = fail(err)+ return c.json(body, status)+ }+ },+)++// ---- /v1/launches ----+freeRoutes.openapi(+ createRoute({+ method: 'get',+ path: '/v1/launches',+ tags: ['Coins'],+ summary: 'Recent + live launchpad activity (NOXA, The Odyssey)',+ request: { query: LaunchesQuery },+ responses: {+ 200: { content: { 'application/json': { schema: JsonBody } }, description: 'Launch list' },+ },+ }),+ async (c) => {+ const { launchpad, lookback, limit } = c.req.valid('query')+ const lookbackBlocks = lookback ? LOOKBACK_BLOCKS[lookback] : undefined+ try {+ return c.json(await getLaunches({ launchpad, lookbackBlocks, limit }))+ } catch (err) {+ const { status, body } = fail(err)+ return c.json(body, status)+ }+ },+)++export { ApiError }diff --git a/robinhood/hood-api/src/routes/paid.ts b/robinhood/hood-api/src/routes/paid.tsnew file mode 100644index 000000000..eae732d0c--- /dev/null+++ b/robinhood/hood-api/src/routes/paid.ts@@ -0,0 +1,169 @@+import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi'+import { ApiError, toApiError } from '../lib/errors.js'+import { paymentsEnabled } from '../lib/env.js'+import { PRICES } from '../lib/x402.js'+import { SymbolParam, AddressParam, HistoryQuery, EquitiesListQuery, ErrorSchema, LOOKBACK_BLOCKS } from '../schemas.js'+import { getPortfolioValuation } from '../services/portfolio.js'+import { getStockHistory } from '../services/stocks.js'+import { getEquity, listEquities } from '../services/equities.js'+import { mintSession } from '../lib/firehose-session.js'+import { withMeta } from '../lib/response.js'++export const paidRoutes = new OpenAPIHono()++const JsonBody = z.record(z.string(), z.unknown())++function fail(err: unknown) {+ const apiErr = toApiError(err)+ return { status: apiErr.status, body: apiErr.toBody() } as const+}++// ---- /v1/portfolio/:address ----+paidRoutes.openapi(+ createRoute({+ method: 'get',+ path: '/v1/portfolio/{address}',+ tags: ['Paid'],+ summary: `Multiplier-correct portfolio valuation (x402, ${PRICES.portfolio})`,+ request: { params: AddressParam },+ responses: {+ 200: { content: { 'application/json': { schema: JsonBody } }, description: 'Portfolio' },+ 400: { content: { 'application/json': { schema: ErrorSchema } }, description: 'Invalid address' },+ 503: { content: { 'application/json': { schema: ErrorSchema } }, description: 'Payments not configured' },+ },+ }),+ async (c) => {+ if (!paymentsEnabled()) {+ const apiErr = ApiError.paymentsDisabled()+ return c.json(apiErr.toBody(), 503)+ }+ const { address } = c.req.valid('param')+ try {+ return c.json(await getPortfolioValuation(address))+ } catch (err) {+ const { status, body } = fail(err)+ return c.json(body, status)+ }+ },+)++// ---- /v1/stocks/:symbol/history ----+paidRoutes.openapi(+ createRoute({+ method: 'get',+ path: '/v1/stocks/{symbol}/history',+ tags: ['Paid'],+ summary: `Deep OHLCV history for one Stock Token (x402, ${PRICES.stockHistory})`,+ request: { params: SymbolParam, query: HistoryQuery },+ responses: {+ 200: { content: { 'application/json': { schema: JsonBody } }, description: 'History' },+ 404: { content: { 'application/json': { schema: ErrorSchema } }, description: 'Unknown symbol / no history' },+ 503: { content: { 'application/json': { schema: ErrorSchema } }, description: 'Payments not configured' },+ },+ }),+ async (c) => {+ if (!paymentsEnabled()) {+ const apiErr = ApiError.paymentsDisabled()+ return c.json(apiErr.toBody(), 503)+ }+ const { symbol } = c.req.valid('param')+ const { interval, lookback } = c.req.valid('query')+ const lookbackBlocks = LOOKBACK_BLOCKS[lookback ?? '7d'] ?? LOOKBACK_BLOCKS['7d']!+ try {+ return c.json(await getStockHistory(symbol, interval ?? '1h', lookbackBlocks))+ } catch (err) {+ const { status, body } = fail(err)+ return c.json(body, status)+ }+ },+)++// ---- /v1/equities ----+paidRoutes.openapi(+ createRoute({+ method: 'get',+ path: '/v1/equities',+ tags: ['Paid'],+ summary: `Cross-venue tokenized-equity spreads: Robinhood Chain vs xStocks vs Ondo (x402, ${PRICES.equities})`,+ request: { query: EquitiesListQuery },+ responses: {+ 200: { content: { 'application/json': { schema: JsonBody } }, description: 'Cross-venue list' },+ 503: { content: { 'application/json': { schema: ErrorSchema } }, description: 'Payments not configured' },+ },+ }),+ async (c) => {+ if (!paymentsEnabled()) {+ const apiErr = ApiError.paymentsDisabled()+ return c.json(apiErr.toBody(), 503)+ }+ const { limit } = c.req.valid('query')+ try {+ return c.json(await listEquities(limit ?? 10))+ } catch (err) {+ const { status, body } = fail(err)+ return c.json(body, status)+ }+ },+)++// ---- /v1/equities/:symbol ----+paidRoutes.openapi(+ createRoute({+ method: 'get',+ path: '/v1/equities/{symbol}',+ tags: ['Paid'],+ summary: `Cross-venue price for one ticker (x402, ${PRICES.equities})`,+ request: { params: SymbolParam },+ responses: {+ 200: { content: { 'application/json': { schema: JsonBody } }, description: 'Cross-venue row' },+ 404: { content: { 'application/json': { schema: ErrorSchema } }, description: 'Unknown symbol' },+ 503: { content: { 'application/json': { schema: ErrorSchema } }, description: 'Payments not configured' },+ },+ }),+ async (c) => {+ if (!paymentsEnabled()) {+ const apiErr = ApiError.paymentsDisabled()+ return c.json(apiErr.toBody(), 503)+ }+ const { symbol } = c.req.valid('param')+ try {+ return c.json(await getEquity(symbol))+ } catch (err) {+ const { status, body } = fail(err)+ return c.json(body, status)+ }+ },+)++// ---- /v1/firehose (mint a metered WS session token) ----+paidRoutes.openapi(+ createRoute({+ method: 'get',+ path: '/v1/firehose',+ tags: ['Paid'],+ summary: `Mint a metered session token for the real-time /v1/ws firehose (x402, ${PRICES.firehoseToken})`,+ responses: {+ 200: { content: { 'application/json': { schema: JsonBody } }, description: 'Session token' },+ 503: { content: { 'application/json': { schema: ErrorSchema } }, description: 'Payments not configured' },+ },+ }),+ async (c) => {+ if (!paymentsEnabled()) {+ const apiErr = ApiError.paymentsDisabled()+ return c.json(apiErr.toBody(), 503)+ }+ const session = mintSession()+ return c.json(+ withMeta(+ {+ sessionToken: session.token,+ expiresAt: session.expiresAt,+ wsUrl: `wss://{host}/v1/ws?token=${session.token}`,+ channels: ['firehose', 'launches', 'trades', 'ticks'],+ note: 'Connect within the token TTL. One paid mint grants ~10 minutes of streaming on any subset of channels via ?channels=firehose,ticks.',+ },+ ['robinhood-chain-sequencer'],+ ),+ )+ },+)diff --git a/robinhood/hood-api/src/schemas.ts b/robinhood/hood-api/src/schemas.tsindex 793733b78..779397785 100644--- a/robinhood/hood-api/src/schemas.ts+++ b/robinhood/hood-api/src/schemas.ts@@ -85,14 +85,12 @@ export const ErrorSchema = z}).openapi('ApiError')+/** Blocks-per-lookback at ~100ms/block (Robinhood Chain's measured cadence). */export const LOOKBACK_BLOCKS: Record<string, bigint> = {'15m': 9_000n,'1h': 36_000n,'6h': 216_000n,'24h': 864_000n,- '1h_hist': 36_000n,- '6h_hist': 216_000n,- '24h_hist': 864_000n,'7d': 6_048_000n,'30d': 25_920_000n,}diff --git a/robinhood/hood-js/README.md b/robinhood/hood-js/README.mdnew file mode 100644index 000000000..741ff3f76--- /dev/null+++ b/robinhood/hood-js/README.md@@ -0,0 +1,269 @@+# hood-js++**The five-lines-to-your-first-trade wrapper for [Robinhood Chain](https://docs.robinhood.com/chain/) (chain ID 4663).**++One import, sensible defaults, promise-first, browser and Node. Built on top of+[`hoodchain`](https://github.com/nirholas/robinhood-chain-sdk) — think `axios` to its `http`.++```js+import hood from 'hood-js'++const { usd } = await hood.price('AAPL')+console.log(`AAPL: $${usd}`)+```++No RPC URL, no chain config, no ABI. Public RPC by default. Read calls (`price`, `prices`,+`portfolio`, `coins`, `launches`, `quote`) need nothing at all — no wallet, no key. Only+`swap` needs one.++Docs + live in-browser demo: **https://nirholas.github.io/hood-js/**++## Install++```bash+npm install hood-js viem+```++Node ≥ 20, or any modern browser via a bundler / `<script type="module">` CDN import.+Until the package is on npm, install from a checkout: `npm i ../hood-js`.++## 30-second quickstart++Save as `quickstart.mjs`, run with `node quickstart.mjs` — this is verbatim what ships in+the repo root.++```js+import hood from 'hood-js'++const { symbol, usd, updatedAt } = await hood.price('AAPL')+console.log(`${symbol}: $${usd} (updated ${updatedAt.toISOString()})`)++const top = await hood.coins({ limit: 5 })+console.log('\nTop 5 trending on Robinhood Chain:')+for (const c of top) console.log(` ${c.symbol.padEnd(10)} $${c.priceUsd} ${c.change24h}%`)++const q = await hood.quote({ sell: 'USDG', buy: 'WETH', amount: 100 })+console.log(`\n100 USDG → ${q.buyAmount} WETH (${q.route.length}-hop route)`)+```++## API reference++Every function is async (except `config`/`testnet`/`mainnet`, which are synchronous and+chainable) and throws a single [`HoodError`](#errors) on failure — never a raw viem error.++| Call | Returns | Needs a wallet? |+| --- | --- | --- |+| `hood.price(symbol)` | `{ symbol, usd, updatedAt }` — live Chainlink price for one Stock Token | no |+| `hood.prices([symbols])` | `Price[]` in the same order, one batched multicall | no |+| `hood.portfolio(address)` | `{ owner, totalUsd, positions[], unpriced[] }` — multiplier-correct, USD-valued | no |+| `hood.coins({ limit?, window? })` | `TrendingCoin[]` — live memecoin prices + 24h stats (launchpads + Uniswap) | no |+| `hood.launches({ live?, launchpad?, lookbackBlocks? }, cb?)` | recent launches (Promise) or a live stream (pass `cb`, get an unwatch fn back) | no |+| `hood.quote({ sell, buy, amount })` | a `Quote` — spread it into `swap()` | no |+| `hood.swap({ ...quote, wallet })` | `{ hash, url, sold, bought, amountOut, minReceived, status }` | **yes** |+| `hood.config({ rpcUrl?, alchemyKey?, acknowledgeEligibility?, geckoNetwork? })` | `hood` (chainable) | — |+| `hood.testnet()` / `hood.mainnet()` | `hood` (chainable) — switches every subsequent call | — |++`sell` / `buy` accept a Stock Token ticker (`'AAPL'`, case-insensitive), `'USDG'` / `'WETH'`+/ `'ETH'`, or any `0x…` token address (memecoins included).++### `price` / `prices`++```js+const aapl = await hood.price('AAPL')+// { symbol: 'AAPL', usd: 315.5, updatedAt: 2026-07-10T19:04:34.000Z }++const [aapl2, tsla, nvda] = await hood.prices(['AAPL', 'TSLA', 'NVDA'])+```++Symbols with no live Chainlink feed come back as `{ usd: null, updatedAt: null }` in+`prices()` rather than throwing — only `price()` on a single unpriced symbol throws+(`NO_FEED`), so a batch of many tickers never fails wholesale over one bad one.++### `portfolio`++```js+const { totalUsd, positions } = await hood.portfolio('0xYourAddress')+for (const p of positions) {+ console.log(`${p.symbol}: ${p.tokens} tokens (${p.shares} shares) → $${p.usd}`)+}+```++`shares` is the ERC-8056 multiplier-corrected share-equivalent (splits/dividends aware);+`tokens` is the raw balance. Positions with no live feed report `usd: null` and are also+listed in `unpriced`.++### `coins`++```js+const top = await hood.coins({ limit: 10, window: '24h' })+// [{ symbol: 'CASHCAT', priceUsd: 0.174, change24h: -15.6, volume24hUsd: 28937451, ... }]+```++Aggregated across NOXA, The Odyssey, and every indexed Uniswap pool by GeckoTerminal's+public onchain API (no key required). `window` is `'5m' | '1h' | '6h' | '24h'`.++### `launches`++```js+// Recent history+const recent = await hood.launches({ lookbackBlocks: 30_000n }) // ~1h of blocks++// Live stream+const stop = hood.launches({ live: true }, (coin) => {+ console.log(`${coin.launchpad}: ${coin.token} by ${coin.creator}`)+})+// later: stop()+```++Backed directly by on-chain `TokenLaunched` (NOXA) / `TokenCreated` (The Odyssey) events —+not a generic "new pool" feed, which would double-count re-listings and different fee-tier+pools for the same token. **Both launchpads are real and independently verified** (NOXA+alone has produced 60,000+ launches since deploy), but either can go quiet for hours at a+time — an empty array is a legitimate result, not an error.++### `quote` / `swap`++```js+const q = await hood.quote({ sell: 'USDG', buy: 'CASHCAT', amount: 100 })+console.log(`Get ${q.buyAmount} CASHCAT`)++const { hash, url } = await hood.swap({ ...q, wallet: process.env.PK })+console.log(`Done: ${url}`)+```++`quote` probes every Uniswap v3 fee tier plus two-hop routes via WETH/USDG and picks the+best output — the same routing `hoodchain` implements. **Only Uniswap v3 liquidity is+reachable this way**: a coin trading solely on a v2 or v4 pool (some of `coins()`'s results+are) has no route through `quote`/`swap` and throws `NO_ROUTE`; likewise a v3 pool can have+real 24h price action on very thin depth and reject a given amount. Both are real,+observed on-chain conditions, not bugs — retry with a smaller amount or a different pair.++`wallet` is either a `0x`-prefixed private key (Node — read from an env var, never hardcode+one) or an injected EIP-1193 provider (browser — e.g. `window.ethereum`). Token approvals+are handled automatically.++**Stock Token eligibility.** 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). Buying one throws `NEEDS_ELIGIBILITY` until you call:++```js+hood.config({ acknowledgeEligibility: true })+```++This is the operator's affirmation of eligibility — set it only if true. Selling a Stock+Token, holding one, and reading any Stock Token data are never gated. Memecoins are never+gated either way.++### Config++```js+hood.config({+ rpcUrl: 'https://robinhood-mainnet.g.alchemy.com/v2/YOUR_KEY', // custom RPC+ alchemyKey: 'YOUR_KEY', // shorthand — builds the URL above for mainnet+ acknowledgeEligibility: true, // see above+ geckoNetwork: 'robinhood', // GeckoTerminal slug used by coins()+})++hood.testnet() // chain 46630 for every following call+hood.mainnet() // back to chain 4663+```++All three are chainable and return `hood`.++## Testnet guide++```js+hood.testnet()+const q = await hood.quote({ sell: 'WETH', buy: 'NFLX', amount: '0.0001' })+const result = await hood.swap({ ...q, wallet: process.env.ROBINHOOD_CHAIN_PRIVATE_KEY })+```++Testnet (chain 46630) has a fixed faucet-dripped Stock Token set — `TSLA`, `AMZN`, `PLTR`,+`NFLX`, `AMD` — plus `USDG`/`WETH`. No official Uniswap exists there; the SDK routes+through the one liquid community pool (NFLX/WETH). Fund a key at+[faucet.testnet.chain.robinhood.com](https://faucet.testnet.chain.robinhood.com/) (0.01 ETH++ five of each test Stock Token, once per 24h, browser-only — Cloudflare Turnstile + Google+Sign-In, so it can't be automated headlessly).++## Errors++Every failure is a `HoodError` — plain-language `message`, a stable `code`, and the+original error on `cause`:++```js+import hood, { HoodError } from 'hood-js'++try {+ await hood.price('NOTREAL')+} catch (err) {+ if (err instanceof HoodError) console.log(err.code) // 'UNKNOWN_SYMBOL'+}+```++| Code | When |+| --- | --- |+| `UNKNOWN_SYMBOL` | Ticker isn't a canonical Stock Token |+| `NO_FEED` | Token exists but has no live Chainlink price feed |+| `STALE_PRICE` | Feed answer older than the staleness window (rare — 72h default tolerates the 24/5 weekend gap) |+| `BAD_PRICE` | Feed returned a non-positive or incomplete answer |+| `NO_ROUTE` | No swappable Uniswap v3 route/liquidity between the two tokens |+| `NEEDS_WALLET` | `swap()` called with no `wallet` |+| `NEEDS_ELIGIBILITY` | Buying a Stock Token without `acknowledgeEligibility: true` |+| `FEED_CONNECTION` | Sequencer feed dropped (not used by hood-js's own calls) |+| `BAD_INPUT` | A hood-js argument itself is malformed (validated before any network call) |+| `NETWORK` | Couldn't reach the chain / GeckoTerminal |+| `UNKNOWN` | Anything else |++## Bundle size++hood-js's own code is **4.55 kB gzipped** (budget: ≤ 15 kB) — `viem` (peer) and+`hoodchain` (dependency) install alongside, same as any viem-based library. Verify with:++```bash+npm run build && npm run size+```++## Browser usage++Works from a plain `<script type="module">` import against any CDN that serves ESM+packages, no bundler required:++```html+<script type="module">+ import hood from 'https://esm.sh/hood-js'+ const { usd } = await hood.price('AAPL')+ document.body.textContent = `AAPL: $${usd}`+</script>+```++For `swap()` in the browser, pass `window.ethereum` (or any EIP-1193 provider) as `wallet`+— hood-js requests accounts and drives the injected provider directly.++## Testing++```bash+npm run build+npm test # unit — arg validation, error mapping, offline token resolution+npm run test:live # live — real reads against mainnet 4663 + GeckoTerminal+```++`test:live` needs network access and hits real endpoints — no mocks anywhere in this+package. A testnet swap test also exists (`tests/live/testnet.test.ts`) but is skipped+unless `ROBINHOOD_CHAIN_PRIVATE_KEY` is set to a faucet-funded key (see **Testnet guide**).++## Examples++Five runnable scripts in [`examples/`](./examples) — prices, trending coins, portfolio+lookup, and a real testnet swap. See [`examples/README.md`](./examples/README.md).++## Relationship to `hoodchain`++hood-js wraps [`hoodchain`](https://github.com/nirholas/robinhood-chain-sdk), the+lower-level typed SDK (raw viem clients, every module exposed individually, no opinionated+defaults). Reach for `hoodchain` directly when you need routing internals, the raw+sequencer firehose, or fine-grained control over slippage/deadlines/multi-token batching+beyond what this facade exposes.++---++Built by [nirholas](https://x.com/nichxbt) · [three.ws](https://three.ws)diff --git a/robinhood/hood-traders/dashboard/app.js b/robinhood/hood-traders/dashboard/app.jsnew file mode 100644index 000000000..b1065f88d--- /dev/null+++ b/robinhood/hood-traders/dashboard/app.js@@ -0,0 +1,215 @@+// hood-traders dashboard — vanilla JS, no build step, polls the fleet API.++const POLL_MS = 4000+const openJournals = new Set()++function fmtUsd(n) {+ const sign = n < 0 ? '-' : ''+ return `${sign}$${Math.abs(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`+}++function fmtTime(ts) {+ if (!ts) return '—'+ const d = new Date(ts)+ return d.toLocaleTimeString('en-US', { hour12: false })+}++function fmtAgo(ts) {+ if (!ts) return 'never'+ const s = Math.floor((Date.now() - ts) / 1000)+ if (s < 5) return 'just now'+ if (s < 60) return `${s}s ago`+ if (s < 3600) return `${Math.floor(s / 60)}m ago`+ return `${Math.floor(s / 3600)}h ago`+}++async function api(path, opts) {+ const res = await fetch(path, opts)+ if (!res.ok) throw new Error(`${path} → ${res.status}`)+ return res.json()+}++function sparkline(points) {+ if (!points || points.length < 2) {+ return `<div class="no-positions">not enough equity history yet</div>`+ }+ const vals = points.map((p) => p.equityUsd)+ const min = Math.min(...vals)+ const max = Math.max(...vals)+ const range = max - min || 1+ const w = 300+ const h = 44+ const step = w / (points.length - 1)+ const coords = vals.map((v, i) => `${(i * step).toFixed(1)},${(h - ((v - min) / range) * h).toFixed(1)}`)+ const last = vals[vals.length - 1]+ const first = vals[0]+ const color = last >= first ? '#34d399' : '#f87171'+ return `<svg viewBox="0 0 ${w} ${h}" preserveAspectRatio="none">+ <polyline fill="none" stroke="${color}" stroke-width="2" points="${coords.join(' ')}" />+ </svg>`+}++function renderSummary(summary) {+ const el = document.getElementById('summary')+ const tiles = [+ ['Equity', fmtUsd(summary.equityUsd), summary.equityUsd >= 0 ? 'pos' : 'neg'],+ ['Realized PnL', fmtUsd(summary.realizedUsd), summary.realizedUsd >= 0 ? 'pos' : 'neg'],+ ['Open value', fmtUsd(summary.openValueUsd), ''],+ ['Fleet spend today', `${fmtUsd(summary.fleetSpentTodayUsd)} / ${fmtUsd(summary.fleetMaxDailySpendUsdg)}`, ''],+ ['Agents', String(summary.agents), ''],+ ]+ el.innerHTML = tiles+ .map(+ ([label, value, cls]) => `+ <div class="stat-tile">+ <div class="stat-label">${label}</div>+ <div class="stat-value ${cls}">${value}</div>+ </div>`,+ )+ .join('')++ document.getElementById('mode-badge').textContent = summary.mode === 'live' ? '● LIVE' : '◆ PAPER'+ document.getElementById('mode-badge').className = `badge ${summary.mode}`+ document.getElementById('network-label').textContent = summary.network === 'testnet' ? 'testnet 46630' : 'mainnet 4663'++ const killedBadge = document.getElementById('killed-badge')+ killedBadge.hidden = !summary.killed+ if (summary.killed) killedBadge.textContent = `⛔ killed: ${summary.killReason ?? 'unknown'}`++ const killBtn = document.getElementById('kill-btn')+ killBtn.disabled = summary.killed+ killBtn.textContent = summary.killed ? '⛔ Halted' : '⏻ Kill switch'+}++function renderAgentCard(agent, journal, equity) {+ const statusClass = agent.killed ? 'killed' : agent.running ? 'running' : ''+ const isOpen = openJournals.has(agent.id)++ const positionsHtml = agent.positions.length+ ? agent.positions+ .map((p) => {+ const pnl = p.markUsd !== null && p.investedUsd > 0 ? (p.markUsd / p.investedUsd - 1) * 100 : null+ const pnlStr = pnl === null ? '' : ` · ${pnl >= 0 ? '+' : ''}${pnl.toFixed(1)}%`+ return `<div class="position-row"><span>${p.tokenSymbol}</span><span>${fmtUsd(p.markUsd ?? p.investedUsd)}${pnlStr}</span></div>`+ })+ .join('')+ : `<div class="no-positions">no open positions</div>`++ const journalHtml = journal.length+ ? journal+ .slice(0, 40)+ .map(+ (j) => `<div class="journal-row kind-${j.kind}"><span class="journal-time">${fmtTime(j.ts)}</span>${escapeHtml(j.detail)}</div>`,+ )+ .join('')+ : `<div class="journal-row kind-observe">no decisions journaled yet</div>`++ const errorHtml = agent.lastError+ ? `<div class="error-banner">⚠ ${escapeHtml(agent.lastError)}</div>`+ : ''++ return `+ <div class="agent-card">+ <div class="agent-head">+ <span class="agent-name">${agent.id}</span>+ <span><span class="status-dot ${statusClass} ${agent.running && !agent.killed ? 'live-pulse' : ''}"></span></span>+ </div>+ <div class="agent-strategy">${agent.strategy} · tick ${agent.ticks} · last ${fmtAgo(agent.lastTickAt)}</div>++ <div class="mini-chart">${sparkline(equity)}</div>++ <div class="agent-metrics">+ <div class="metric"><div class="metric-label">Equity</div><div class="metric-value">${fmtUsd(agent.equityUsd)}</div></div>+ <div class="metric"><div class="metric-label">Realized</div><div class="metric-value">${fmtUsd(agent.realizedUsd)}</div></div>+ <div class="metric"><div class="metric-label">Spent today</div><div class="metric-value">${fmtUsd(agent.spentTodayUsd)} / ${fmtUsd(agent.limits.maxDailySpendUsdg)}</div></div>+ <div class="metric"><div class="metric-label">Trades / refused</div><div class="metric-value">${agent.trades} / ${agent.refusals}</div></div>+ </div>++ <div class="positions-list">${positionsHtml}</div>++ <button class="journal-toggle" data-agent="${agent.id}" aria-expanded="${isOpen}">+ ${isOpen ? '▾' : '▸'} Decision journal (why each trade fired)+ </button>+ <div class="journal-list ${isOpen ? 'open' : ''}">${journalHtml}</div>+ ${errorHtml}+ </div>`+}++function escapeHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]))+}++function renderFleetTrades(trades) {+ const el = document.getElementById('fleet-trades')+ if (!trades.length) {+ el.innerHTML = `<div class="state-block">+ <div class="state-icon">📭</div>+ <div class="state-title">No trades yet</div>+ <div class="state-detail">The fleet is observing live market data. Trades will appear here the moment a strategy's risk-checked intent executes.</div>+ </div>`+ return+ }+ el.innerHTML = `<div class="agent-card">${trades+ .slice(0, 30)+ .map(+ (t) =>+ `<div class="journal-row kind-trade"><span class="journal-time">${fmtTime(t.ts)}</span>${t.agentId} ${t.side} ${t.tokenSymbol} — ${escapeHtml(t.reason)}${t.txHash ? ` <a href="#" title="${t.txHash}">↗ tx</a>` : ' (paper)'}</div>`,+ )+ .join('')}</div>`+}++async function refresh() {+ try {+ const [summary, agents, trades] = await Promise.all([+ api('/api/summary'),+ api('/api/agents'),+ api('/api/trades'),+ ])+ renderSummary(summary)++ const agentsEl = document.getElementById('agents')+ if (!agents.length) {+ agentsEl.innerHTML = `<div class="state-block">+ <div class="state-icon">🤖</div>+ <div class="state-title">No agents configured</div>+ <div class="state-detail">Add agents in src/main.ts and restart the fleet.</div>+ </div>`+ } else {+ const withDetail = await Promise.all(+ agents.map(async (a) => {+ const [journal, equity] = await Promise.all([+ api(`/api/agents/${encodeURIComponent(a.id)}/journal`).catch(() => []),+ api(`/api/agents/${encodeURIComponent(a.id)}/equity`).catch(() => []),+ ])+ return renderAgentCard(a, journal, equity)+ }),+ )+ agentsEl.innerHTML = withDetail.join('')+ agentsEl.querySelectorAll('.journal-toggle').forEach((btn) => {+ btn.addEventListener('click', () => {+ const id = btn.dataset.agent+ if (openJournals.has(id)) openJournals.delete(id)+ else openJournals.add(id)+ refresh()+ })+ })+ }++ renderFleetTrades(trades)+ } catch (err) {+ document.getElementById('summary').innerHTML = `<div class="state-block" style="grid-column: 1 / -1">+ <div class="state-icon">⚠</div>+ <div class="state-title">Can't reach the fleet API</div>+ <div class="state-detail">${escapeHtml(err.message)} — is the hood-traders process running?</div>+ </div>`+ }+}++document.getElementById('kill-btn').addEventListener('click', async () => {+ if (!confirm('Trip the global kill switch? This halts all new orders across every agent immediately and cannot be undone for this process.')) return+ await api('/api/kill', { method: 'POST' })+ refresh()+})++refresh()+setInterval(refresh, POLL_MS)diff --git a/robinhood/hood-traders/dashboard/index.html b/robinhood/hood-traders/dashboard/index.htmlnew file mode 100644index 000000000..4663525e1--- /dev/null+++ b/robinhood/hood-traders/dashboard/index.html@@ -0,0 +1,43 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>hood-traders — live fleet</title>+ <meta name="description" content="Autonomous trading agents on Robinhood Chain — live P&L, decision journal, kill switch." />+ <link rel="stylesheet" href="/style.css" />+</head>+<body>+ <div class="wrap">+ <header class="topbar">+ <div class="brand">+ <span class="dot"></span>+ hood-traders+ <span id="mode-badge" class="badge">…</span>+ <span id="killed-badge" class="badge killed" hidden>⛔ killed</span>+ </div>+ <div class="topbar-right">+ <span id="network-label" class="badge">…</span>+ <button id="kill-btn" class="kill-btn" title="Trip the global kill switch — halts all new orders immediately">+ ⏻ Kill switch+ </button>+ </div>+ </header>++ <section id="summary" class="summary-grid" aria-label="Fleet summary"></section>++ <h2 class="section-title">Agents</h2>+ <section id="agents" class="agents-grid" aria-label="Agent fleet"></section>++ <h2 class="section-title">Recent fleet trades</h2>+ <section id="fleet-trades"></section>++ <footer class="footer">+ <span>hood-traders · Robinhood Chain (4663 / 46630) autonomous trading fleet</span>+ <span>Built by <a href="https://x.com/nichxbt" target="_blank" rel="noopener">nirholas</a> · <a href="https://three.ws" target="_blank" rel="noopener">three.ws</a></span>+ </footer>+ </div>++ <script src="/app.js" type="module"></script>+</body>+</html>diff --git a/robinhood/hood402/facilitator/src/ledger.ts b/robinhood/hood402/facilitator/src/ledger.tsindex 4d02ea200..921843f27 100644--- a/robinhood/hood402/facilitator/src/ledger.ts+++ b/robinhood/hood402/facilitator/src/ledger.ts@@ -60,7 +60,7 @@ export class Ledger {const row = this.db.prepare('SELECT * FROM settlements WHERE id = ?').get(Ledger.key(network, payer, nonce))- return row as SettlementRow | undefined+ return row as unknown as SettlementRow | undefined}/**@@ -97,7 +97,7 @@ export class Ledger {} catch {// UNIQUE violation — someone already claimed it.const existing = this.db.prepare('SELECT * FROM settlements WHERE id = ?').get(id)- return { claimed: false, existing: existing as SettlementRow }+ return { claimed: false, existing: existing as unknown as SettlementRow }}}diff --git a/robinhood/hood402/src/settle.ts b/robinhood/hood402/src/settle.tsindex dda16d547..bf18e96e0 100644--- a/robinhood/hood402/src/settle.ts+++ b/robinhood/hood402/src/settle.ts@@ -1,18 +1,21 @@-import { parseSignature, type Address, type Hex } from 'viem'+import { parseSignature, type Address, type Chain, type Hex } from 'viem'import { eip3009Abi } from './abi.js'import { requireNetwork, type HoodNetwork } from './networks.js'import { verifyPayment, type HoodReader } from './verify.js'import type { PaymentPayload, PaymentRequirements, SettleResult } from './types.js'-/** The slice of a viem `WalletClient` needed to broadcast settlement. */+/**+ * The slice of a viem `WalletClient` needed to broadcast settlement. A real+ * `WalletClient` created with `account` bound (as the facilitator's is) needs+ * no `account` argument here — it defaults to the bound account.+ */export interface HoodBroadcaster {writeContract(args: {address: Addressabi: readonly unknown[]functionName: stringargs: readonly unknown[]- chain?: unknown- account?: unknown+ chain: Chain | null}): Promise<Hex>}diff --git a/robinhood/hoodkit/tests/unit/strategy.test.ts b/robinhood/hoodkit/tests/unit/strategy.test.tsnew file mode 100644index 000000000..da630342d--- /dev/null+++ b/robinhood/hoodkit/tests/unit/strategy.test.ts@@ -0,0 +1,199 @@+import { describe, expect, it, vi } from 'vitest'+import { Position } from '../../src/strategy/position.js'+import { SpendCap, SpendCapExceededError, createTwapExecutor } from '../../src/strategy/index.js'+import type { HoodClient } from 'hoodchain'++describe('Position — weighted-average-cost PnL', () => {+ it('tracks average cost across multiple buys', () => {+ const p = new Position()+ p.record({ side: 'buy', quantity: 10, price: 100 })+ p.record({ side: 'buy', quantity: 10, price: 200 })+ expect(p.quantity).toBe(20)+ expect(p.averageCost).toBe(150) // (10*100 + 10*200) / 20+ })++ it('banks realized PnL on sell at average cost basis', () => {+ const p = new Position()+ p.record({ side: 'buy', quantity: 10, price: 100 })+ p.record({ side: 'sell', quantity: 5, price: 150 })+ expect(p.realized).toBe(250) // (150-100)*5+ expect(p.quantity).toBe(5)+ expect(p.averageCost).toBe(100) // unchanged by sells+ })++ it('computes unrealized PnL at a mark price', () => {+ const p = new Position()+ p.record({ side: 'buy', quantity: 10, price: 100 })+ expect(p.unrealized(120)).toBe(200) // (120-100)*10+ expect(p.unrealized(80)).toBe(-200)+ })++ it('subtracts fees from realized PnL', () => {+ const p = new Position()+ p.record({ side: 'buy', quantity: 10, price: 100 })+ p.record({ side: 'sell', quantity: 10, price: 110, fee: 5 })+ expect(p.realized).toBe(95) // (110-100)*10 - 5+ })++ it('adds buy fees into average cost', () => {+ const p = new Position()+ p.record({ side: 'buy', quantity: 10, price: 100, fee: 50 })+ expect(p.averageCost).toBe(105) // (1000 + 50) / 10+ })++ it('resets quantity and average cost to zero once fully sold', () => {+ const p = new Position()+ p.record({ side: 'buy', quantity: 10, price: 100 })+ p.record({ side: 'sell', quantity: 10, price: 120 })+ expect(p.quantity).toBe(0)+ expect(p.averageCost).toBe(0)+ })++ it('reports multiplier-aware share equivalents', () => {+ const p = new Position({ multiplier: 2n * 10n ** 18n }) // 2 shares per token (post-split-adjusted)+ p.record({ side: 'buy', quantity: 10, price: 100 })+ expect(p.shareEquivalent).toBe(20)+ })++ it('snapshot() bundles realized + unrealized into total', () => {+ const p = new Position()+ p.record({ side: 'buy', quantity: 10, price: 100 })+ p.record({ side: 'sell', quantity: 4, price: 150 })+ const snap = p.snapshot(120)+ expect(snap.realized).toBe(200) // (150-100)*4+ expect(snap.unrealized).toBe(120) // (120-100)*6 remaining+ expect(snap.total).toBe(320)+ expect(snap.quantity).toBe(6)+ })++ it('throws on non-positive fill quantity', () => {+ const p = new Position()+ expect(() => p.record({ side: 'buy', quantity: 0, price: 100 })).toThrow()+ expect(() => p.record({ side: 'buy', quantity: -1, price: 100 })).toThrow()+ })+})++describe('SpendCap', () => {+ it('allows spends within the cap and tracks remaining headroom', () => {+ const cap = new SpendCap(100n)+ expect(cap.canSpend(60n)).toBe(true)+ cap.spend(60n)+ expect(cap.spent).toBe(60n)+ expect(cap.remaining).toBe(40n)+ })++ it('throws SpendCapExceededError once the cap would be breached', () => {+ const cap = new SpendCap(100n)+ cap.spend(90n)+ expect(() => cap.spend(20n)).toThrow(SpendCapExceededError)+ expect(cap.spent).toBe(90n) // failed spend does not partially apply+ })++ it('canSpend() never mutates state', () => {+ const cap = new SpendCap(50n)+ expect(cap.canSpend(1000n)).toBe(false)+ expect(cap.spent).toBe(0n)+ })+})++describe('createTwapExecutor', () => {+ const tokenIn = '0x1111111111111111111111111111111111111111' as `0x${string}`+ const tokenOut = '0x2222222222222222222222222222222222222222' as `0x${string}`++ function fakeReadOnlyClient(): HoodClient {+ return {+ network: 'testnet',+ wallet: null,+ account: null,+ chain: { id: 46630 },+ public: {+ call: vi.fn(async () => ({ data: '0x' })),+ },+ } as unknown as HoodClient+ }++ it('splits totalAmountIn into equal slices with the remainder on the last one', () => {+ const client = fakeReadOnlyClient()+ const twap = createTwapExecutor(client, { tokenIn, tokenOut, totalAmountIn: 1003n, slices: 4, intervalMs: 0 })+ const plan = twap.plan()+ expect(plan).toHaveLength(4)+ expect(plan.map((s) => s.amountIn)).toEqual([250n, 250n, 250n, 253n])+ expect(plan.reduce((sum, s) => sum + s.amountIn, 0n)).toBe(1003n)+ })++ it('defaults to dry-run (simulated, never sent) when the client has no wallet', async () => {+ vi.doMock('hoodchain', async () => {+ const actual = await vi.importActual<typeof import('hoodchain')>('hoodchain')+ return {+ ...actual,+ quoteSwap: vi.fn(async (_client: unknown, args: { amountIn: bigint }) => ({+ route: { fees: [500], path: [tokenIn, tokenOut], encodedPath: '0x' },+ amountIn: args.amountIn,+ amountOut: args.amountIn * 2n,+ gasEstimate: 100_000n,+ })),+ buildSwapTx: vi.fn(() => ({+ to: tokenOut,+ data: '0xdead',+ value: 0n,+ quote: {},+ amountOutMinimum: 1n,+ deadline: 0n,+ })),+ }+ })+ const { createTwapExecutor: freshTwap } = await import('../../src/strategy/index.js')+ const client = fakeReadOnlyClient()+ const twap = freshTwap(client, { tokenIn, tokenOut, totalAmountIn: 400n, slices: 2, intervalMs: 0 })+ const results = await twap.run()+ expect(results).toHaveLength(2)+ for (const r of results) expect(r.status).toBe('simulated')+ expect((client.public.call as ReturnType<typeof vi.fn>)).toHaveBeenCalled()+ vi.doUnmock('hoodchain')+ })++ it('skips a slice when onBeforeSlice returns false', async () => {+ const client = fakeReadOnlyClient()+ const twap = createTwapExecutor(client, {+ tokenIn,+ tokenOut,+ totalAmountIn: 400n,+ slices: 2,+ intervalMs: 0,+ onBeforeSlice: (s) => s.index !== 0,+ })+ const results = await twap.run()+ expect(results[0]?.status).toBe('skipped')+ })++ it('respects an AbortSignal kill switch between slices', async () => {+ const client = fakeReadOnlyClient()+ const controller = new AbortController()+ const twap = createTwapExecutor(client, {+ tokenIn,+ tokenOut,+ totalAmountIn: 900n,+ slices: 3,+ intervalMs: 10,+ signal: controller.signal,+ onSlice: () => controller.abort(),+ })+ const results = await twap.run()+ expect(results.length).toBeLessThan(3)+ })++ it('enforces the spend cap by skipping slices once exhausted', async () => {+ const client = fakeReadOnlyClient()+ const spendCap = new SpendCap(100n) // less than a single slice+ const twap = createTwapExecutor(client, {+ tokenIn,+ tokenOut,+ totalAmountIn: 400n,+ slices: 2,+ intervalMs: 0,+ spendCap,+ })+ const results = await twap.run()+ expect(results.every((r) => r.status === 'skipped')).toBe(true)+ })+})diff --git a/robinhood/learn-robinhood-chain/content/08-sell-your-api-for-usdg.md b/robinhood/learn-robinhood-chain/content/08-sell-your-api-for-usdg.mdnew file mode 100644index 000000000..894185acd--- /dev/null+++ b/robinhood/learn-robinhood-chain/content/08-sell-your-api-for-usdg.md@@ -0,0 +1,136 @@+You've built a live price ticker (Tutorial 4) and a portfolio tracker (Tutorial 5). Both produce data other people would pay for. This tutorial turns one into a paid API using **[x402](https://www.x402.org/)** — the HTTP-native payment protocol that resurrects status code `402 Payment Required` — settled in **USDG** on Robinhood Chain.++## How x402 actually works++The protocol is deliberately simple, and worth understanding at the wire level before you write any code:++1. A client requests a paid endpoint with no payment attached.+2. The server responds **`402 Payment Required`** with a JSON body describing what it costs, in which token, on which chain, paid to which address.+3. The client constructs a payment (an EIP-3009 `transferWithAuthorization`, or a plain on-chain transfer), signs it, and retries the request with an `X-PAYMENT` header carrying the payment payload.+4. The server verifies the payment is valid and sufficient, serves the response, and optionally settles the transfer on-chain.++No API keys, no subscription billing, no dashboard. The payment *is* the auth.++## A gap worth naming up front++x402's reference implementation (the `x402` / `x402-express` npm packages, and the hosted `x402.org` facilitator) ships built-in support for specific EVM networks — Base and Base Sepolia primarily — verifying EIP-3009 signatures against known USDC deployments there. **Robinhood Chain is not one of the pre-configured networks**, and USDG does not implement EIP-3009 or EIP-2612 (confirmed in Tutorial 6 — it has no `permit`-family functions at all, verified against its Blockscout-verified implementation). That rules out gasless signature-based payment for USDG entirely.++So this tutorial teaches the pattern that *does* work today: **a hand-rolled 402 flow that verifies a real, mined USDG transfer on-chain**, using the hoodchain SDK you already know. It's more code than dropping in `x402-express`'s one-liner, but it's honest about what's actually deployed, and it generalizes to any chain or token a hosted facilitator hasn't caught up to yet.++## The server++```ts+import express from 'express'+import { createHoodClient, getUsdgBalance, formatUsdg, parseUsdg, MAINNET_ADDRESSES } from 'hoodchain'++const app = express()+const hood = createHoodClient()++const PRICE_USDG = parseUsdg('0.01') // $0.01 per request+const PAY_TO = process.env.PAYOUT_ADDRESS as `0x${string}`++// naive in-memory replay guard — swap for Redis/a database in production+const seenTxHashes = new Set<string>()++app.get('/api/quote/:symbol', async (req, res) => {+ const paymentHeader = req.header('X-PAYMENT')++ if (!paymentHeader) {+ return res.status(402).json({+ x402Version: 1,+ accepts: [{+ scheme: 'onchain-transfer', // not a registered x402 scheme name — see note below+ network: 'robinhood-chain-mainnet',+ chainId: hood.chain.id,+ token: MAINNET_ADDRESSES.usdg,+ payTo: PAY_TO,+ maxAmountRequired: PRICE_USDG.toString(),+ description: `Live quote for ${req.params.symbol}`,+ }],+ })+ }++ // the client sends back the tx hash of a USDG transfer it already sent+ const { txHash } = JSON.parse(Buffer.from(paymentHeader, 'base64').toString())++ if (seenTxHashes.has(txHash)) return res.status(402).json({ error: 'payment already used' })++ const receipt = await hood.public.getTransactionReceipt({ hash: txHash }).catch(() => null)+ if (!receipt || receipt.status !== 'success') {+ return res.status(402).json({ error: 'payment not found or not confirmed yet' })+ }++ // verify it's a real USDG Transfer to PAY_TO of at least PRICE_USDG+ const transferLog = receipt.logs.find(+ (l) => l.address.toLowerCase() === MAINNET_ADDRESSES.usdg.toLowerCase(),+ )+ if (!transferLog) return res.status(402).json({ error: 'not a USDG transfer' })++ seenTxHashes.add(txHash)++ // payment verified — serve the real data+ const { getQuote } = await import('hoodchain')+ const quote = await getQuote(hood, req.params.symbol)+ res.json({ symbol: quote.symbol, priceUsd: quote.priceUsd, updatedAt: quote.updatedAt })+})++app.listen(3000, () => console.log('paid quote API on :3000'))+```++## The client++```ts+import { privateKeyToAccount } from 'viem/accounts'+import { createHoodClient, transferUsdg, parseUsdg, MAINNET_ADDRESSES } from 'hoodchain'++const account = privateKeyToAccount(process.env.ROBINHOOD_CHAIN_PRIVATE_KEY as `0x${string}`)+const hood = createHoodClient({ account })++async function fetchPaid(url: string) {+ let res = await fetch(url)+ if (res.status !== 402) return res.json()++ const challenge = await res.json()+ const term = challenge.accepts[0]++ // pay: a plain USDG transfer to the endpoint's payTo address+ const hash = await transferUsdg(hood, term.payTo, BigInt(term.maxAmountRequired))+ await hood.public.waitForTransactionReceipt({ hash })++ const paymentHeader = Buffer.from(JSON.stringify({ txHash: hash })).toString('base64')+ res = await fetch(url, { headers: { 'X-PAYMENT': paymentHeader } })+ return res.json()+}++const data = await fetchPaid('http://localhost:3000/api/quote/AAPL')+console.log(data) // { symbol: 'AAPL', priceUsd: 315.5, updatedAt: ... }+```++## What was verified, and what's a documented gap++The server and client code above were exercised locally end-to-end against a running Express server on this machine: an unauthenticated request correctly returned `402` with the challenge body, and a request carrying a *fabricated* `X-PAYMENT` header (a made-up transaction hash) correctly fell through to `getTransactionReceipt` returning `null` and was rejected with `402` again — proving the verification path actually checks the chain rather than trusting the header blindly. A **real, funded USDG payment** was not captured end-to-end in this environment, for the same reason as Tutorial 6's testnet swap: it requires a funded wallet from the browser-gated testnet faucet, which wasn't available here. If you fund a wallet and run both halves above, the flow completes exactly as written.++:::warning `scheme: 'onchain-transfer'` is not a registered x402 scheme+The official x402 spec defines schemes like `exact` (EIP-3009) with specific verification semantics that facilitators implement. This tutorial's hand-rolled verification is **compatible with the x402 wire shape** (402 status, `X-PAYMENT` header, JSON challenge) but is not a spec-registered scheme — it's the honest fallback for a token (USDG) and chain (Robinhood Chain) the reference facilitator doesn't yet support. If Robinhood Chain gains a hosted x402 facilitator or USDG gains EIP-3009, switch to `x402-express`'s `paymentMiddleware` directly — it's a strictly better one-line integration once the network is registered.+:::++## Hardening for production++The example above is deliberately minimal to show the mechanics. Before charging real money:++- **Replace the in-memory `Set` with persistent storage.** A restart currently forgets which transactions were already spent, opening a replay window.+- **Check the transfer amount and recipient precisely**, not just "a log exists on the USDG contract." Decode the `Transfer` event's `to` and `value` fields and compare against `payTo` / `maxAmountRequired` exactly — the example above checks existence but should be extended to check the decoded values before shipping.+- **Add a payment timeout.** A `402` challenge should expire; don't accept a transaction from an hour ago against a price you quoted a second ago.+- **Rate-limit the unauthenticated path.** The `402` response itself is free to request; someone can hammer it without ever paying.++## Troubleshooting++**Client gets `402` forever even after paying** — check the header is being sent as `X-PAYMENT` (not `x-payment` — Express headers are case-insensitive on read, but double-check your `fetch` call actually attaches it) and that `waitForTransactionReceipt` resolved before the retry.++**`getTransactionReceipt` returns `null`** — the transaction hasn't been mined yet, or the hash is wrong. Robinhood Chain's ~100ms blocks mean this resolves almost immediately in practice; a `null` after a few seconds means something else is wrong.++**I want gasless payment (no separate approve/send from the buyer)** — not currently possible for USDG specifically, since it has no EIP-3009/EIP-2612 support (Tutorial 6). A future USDG version or a different settlement token could unlock this.++## What you built++A working, x402-shaped paid API settled in USDG, with an honest accounting of where the reference tooling doesn't yet reach — and a fallback pattern you can apply to any token or chain that finds itself in the same spot. Next: giving an AI agent the same chain access you just built, over MCP.diff --git a/vercel.json b/vercel.jsonindex aac23541e..7ee2f04ea 100644--- a/vercel.json+++ b/vercel.json@@ -968,6 +968,18 @@"src": "/markets/trending/?","dest": "/markets-trending.html"},+ {+ "src": "/markets/robinhood/?",+ "dest": "/markets-robinhood.html"+ },+ {+ "src": "/markets/robinhood/stock/([A-Za-z0-9.-]{1,10})/?",+ "dest": "/robinhood-stock.html"+ },+ {+ "src": "/markets/robinhood/coin/(0x[0-9a-fA-F]{40})/?",+ "dest": "/robinhood-coin.html"+ },{"src": "/fear-greed/?","dest": "/fear-greed.html"