Robinhood Chain 測試網 RPC 入門:免 key 讀取、WebSocket 日誌,再切換主網

從 Robinhood Chain 測試網 RPC 開始:公共 RPC URL、免 key 讀取、使用 API key 的 WebSocket 日誌、faucet 存取,以及將同一把 key 切換到主網。

BlockVectra 透過 JSON-RPC 與 WebSocket 提供 Robinhood Chain 測試網(Chain ID 46630),同一把 API key 也可用於 Robinhood Chain 主網。本指南依 Robinhood Chain 測試網入門 範本走過三個步驟:免 key 讀取測試網、以程式化方式建立帳戶並串流日誌,然後將同一把 key 移到主網。端點參數、方法策略與代幣化股票資料,請參閱 Robinhood Chain 指南。

執行範本

git clone https://github.com/blockvectra/robinhood-testnet-starter
cd robinhood-testnet-starter
npm install
npm run typecheck

Node.js 18 或以上。三個指令碼是 npm run step1、npm run step2 與 npm run step3。選用變數(BLOCKVECTRA_API_KEY、WALLET_PRIVATE_KEY)從 shell 讀取;不會自動載入 .env。

步驟 1:免 key 讀取測試網

公共端點 https://api.blockvectra.com/v1/robinhood_testnet/public 提供錢包 JSON-RPC 方法,無需帳戶與 API key。直接查詢 EIP-155 chain ID:

curl -s "https://api.blockvectra.com/v1/robinhood_testnet/public" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"eth_chainId","params":[]}'

回應為 {"jsonrpc":"2.0","id":1,"result":"0xb626"};0xb626 是十六進位 chain ID,十進位為 46630。

範本從 GET /v1/chains 讀取鏈條目並據此建立 viem 用戶端,因此鏈名與 ID 並未寫死。以下節錄自 src/shared.ts:

import { createPublicClient, defineChain, http, webSocket } from "viem";

export const API_BASE = "https://api.blockvectra.com/v1";

export interface ChainEntry {
  chain: string;
  name: string;
  chain_id: number;
  data: boolean;
  ws: boolean;
  subscriptions: string[];
  public?: { url: string };
}

export async function getChain(slug: string): Promise<ChainEntry> {
  const res = await fetch(`${API_BASE}/chains`);
  if (!res.ok) throw new Error(`GET /v1/chains failed: ${res.status}`);
  const { chains } = (await res.json()) as { chains: ChainEntry[] };
  const entry = chains.find((c) => c.chain === slug);
  if (!entry) throw new Error(`${slug} not found in /v1/chains`);
  return entry;
}

export function toViemChain(entry: ChainEntry, rpcUrl: string) {
  return defineChain({
    id: entry.chain_id,
    name: entry.name,
    nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
    rpcUrls: { default: { http: [rpcUrl] } },
  });
}

export function httpClient(entry: ChainEntry, url: string, apiKey?: string) {
  return createPublicClient({
    chain: toViemChain(entry, url),
    transport: http(url, apiKey ? { fetchOptions: { headers: { "x-api-key": apiKey } } } : undefined),
  });
}

export function wsClient(entry: ChainEntry, apiKey: string) {
  const base = "wss://api.blockvectra.com/v1";
  const url = `${base}/${entry.chain}/${apiKey}`;
  return createPublicClient({ chain: toViemChain(entry, url), transport: webSocket(url) });
}

有了該模組,src/step1-public-read.ts 會讀取 chain ID、最新區塊與一個地址餘額:

import { formatEther, type Address } from "viem";
import { API_BASE, getChain, httpClient } from "./shared.js";

const SLUG = "robinhood_testnet";
// Any address works; override with the first CLI argument.
const address = (process.argv[2] ?? "0x0000000000000000000000000000000000000000") as Address;

const chain = await getChain(SLUG);
const client = httpClient(chain, `${API_BASE}/${SLUG}/public`);

const [chainId, blockNumber, balance] = await Promise.all([
  client.getChainId(),
  client.getBlockNumber(),
  client.getBalance({ address }),
]);

console.log(`chain       : ${chain.name} (${SLUG})`);
console.log(`eth_chainId : ${chainId} (0x${chainId.toString(16)})`);
console.log(`block       : ${blockNumber}`);
console.log(`balance     : ${formatEther(balance)} ETH  (${address})`);

步驟 2:以程式化方式建立帳戶並訂閱日誌

src/step2-key-and-logs.ts 在 https://console-api.blockvectra.com/v1 使用錢包(SIWE、EIP-191)登入。首次登入會建立帳戶;用戶端接著建立 API key。新帳戶註冊即得 30,000,000 CU,無需信用卡。

import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
import type { Hex } from "viem";

const CONSOLE_API = "https://console-api.blockvectra.com/v1";
const REF = "gh-robinhood-testnet-starter";

async function post<T>(path: string, body: unknown, token?: string): Promise<T> {
  const res = await fetch(`${CONSOLE_API}${path}`, {
    method: "POST",
    headers: { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`${path} failed: ${res.status} ${await res.text()}`);
  return (await res.json()) as T;
}

async function provisionKey(): Promise<string> {
  const pk = (process.env.WALLET_PRIVATE_KEY as Hex | undefined) ?? generatePrivateKey();
  const account = privateKeyToAccount(pk);
  console.log(`wallet: ${account.address}`);

  // SIWE: ask for a challenge, sign it verbatim (EIP-191), log in. A first sign-in creates the account.
  const { message } = await post<{ message: string }>("/auth/siwe/challenge", {
    address: account.address,
    purpose: "login",
  });
  const signature = await account.signMessage({ message });
  const login = await post<{ session: { token: string }; account_created: boolean }>("/auth/siwe/login", {
    message,
    signature,
    ref: REF,
  });
  console.log(`account_created: ${login.account_created}`);

  const created = await post<{ api_key: string }>("/keys", { label: "robinhood-testnet-starter" }, login.session.token);
  return created.api_key;
}

const apiKey = process.env.BLOCKVECTRA_API_KEY?.trim() || (await provisionKey());

如果你已有 key,export BLOCKVECTRA_API_KEY=... 會略過建立帳戶。若未設定 WALLET_PRIVATE_KEY,指令碼會在記憶體中產生一個用完即丟的錢包,並在執行結束時丟棄;如果你想要再次登入同一個帳戶,請從本機環境設定 WALLET_PRIVATE_KEY。

WebSocket URL 會將 key 放在路徑中:wss://api.blockvectra.com/v1/robinhood_testnet/{api_key}。範本會在訂閱前檢查來自 GET /v1/chains 的即時 ws 旗標與 subscriptions 清單:

const chain = await getChain("robinhood_testnet");
if (!chain.ws || !chain.subscriptions.includes("logs")) {
  throw new Error(`robinhood_testnet does not offer a logs subscription in /v1/chains`);
}
console.log(`subscriptions (from /v1/chains): ${chain.subscriptions.join(", ")}`);

const client = wsClient(chain, apiKey);
const stop = client.watchEvent({
  address: "0x1234567890123456789012345678901234567890",
  onLogs: (logs) => {
    for (const l of logs) console.log(`block ${l.blockNumber} ${l.address} topic0=${l.topics[0]}`);
  },
  onError: (e) => console.error("subscription error:", e.message),
});

每個 logs 訂閱篩選器都必須包含 address 或 topic0;請將範例地址取代為你想關注的合約。篩選規則、關閉碼與重新連線,請參閱 WebSocket 訂閱指南。

步驟 3:將同一把 key 切換到主網

切換到主網只需改一個字:使用代稱 robinhood_mainnet 與同一把 API key。src/step3-mainnet.ts 會讀取主網區塊號,並呼叫 Data API 取得 Robinhood 股票代幣:

const apiKey = process.env.BLOCKVECTRA_API_KEY?.trim();
if (!apiKey) throw new Error("Set BLOCKVECTRA_API_KEY (run step 2 first, or create a key in the console).");

const mainnet = await getChain("robinhood_mainnet");

// JSON-RPC with the key: the chain slug changes.
const client = httpClient(mainnet, `${API_BASE}/${mainnet.chain}`, apiKey);
console.log(`mainnet block: ${await client.getBlockNumber()}`);

// Data API: Robinhood stock-token leaderboard (see the Robinhood Chain guide).
const res = await fetch(`${API_BASE}/data/${mainnet.chain}/stocks`, { headers: { "x-api-key": apiKey } });
if (!res.ok) throw new Error(`Data API failed: ${res.status} ${await res.text()}`);
console.log(JSON.stringify(await res.json(), null, 2).slice(0, 2000));

以 curl 呼叫同一個排行榜端點:

curl -s -H "x-api-key: $BLOCKVECTRA_API_KEY" \
  "https://api.blockvectra.com/v1/data/robinhood_mainnet/stocks"

Data API 僅限主網:GET /v1/chains 對 robinhood_testnet 回報 data: false,對 robinhood_mainnet 回報 data: true。請求參數與回應結構,請參閱代幣化股票指南。

從 API 探索限制與能力

讀取 GET /v1/chains 以取得即時的 jsonrpc、data、ws 與 subscriptions 旗標、允許的 JSON-RPC 方法、日誌區塊範圍、狀態保留期間,以及每條鏈的公共端點。讀取 GET /v1/plans 以取得目前價格與方案限制。

curl -s "https://api.blockvectra.com/v1/chains"

相關指南

下一步

最後更新:

本頁目錄