Robinhood Chain 測試網 RPC 入門:免 key 讀取、WebSocket 日誌,再切換主網
從 Robinhood Chain 測試網 RPC 開始接入:先用公開端點免 key 讀取鏈 ID、最新區塊與餘額,再用錢包簽章建立帳戶、取得金鑰並訂閱日誌,最後把同一把 key 切到主網呼叫股票排行榜端點。
BlockVectra 透過 JSON-RPC 與 WebSocket 提供 Robinhood Chain 測試網(Chain ID 46630),同一把 API key 也可用於 Robinhood Chain 主網。本指南依 Robinhood Chain 測試網入門 範本走過三個步驟:免 key 讀取測試網、以程式化方式建立帳戶並串流日誌,然後將同一把 key 移到主網。端點參數、方法策略與代幣化股票資料,請參閱 Robinhood Chain 指南。
本指南中的 RPC 端點由 BlockVectra 提供;Robinhood 自己的公共 RPC 與網路參數請參閱官方連線文件。
執行範本
git clone https://github.com/blockvectra/robinhood-testnet-starter
cd robinhood-testnet-starter
npm install
npm run typecheckNode.js 18 或以上。三個指令碼是 npm run step1、npm run step2 與 npm run step3。選用變數(BLOCKVECTRA_API_KEY、WALLET_PRIVATE_KEY)從 shell 讀取;不會自動載入 .env。
以單一指令執行完整流程
npm run walkthroughnpm run walkthrough 會先免 key 讀取測試網,再訂閱過濾日誌 30 秒,隨後用同一把 API key 讀取主網 RPC 與 Data API。BLOCKVECTRA_API_KEY 非空時會重複使用該 key,並略過登入與建立 key;否則若未提供 WALLET_PRIVATE_KEY,首次執行會在 .agent-wallet.json 儲存專用登入錢包,之後重跑會重複使用該帳戶,而沒有 key 時每次執行仍會建立新的伺服器端金鑰。訂閱前,請將 src/step2-key-and-logs.ts 中的範例合約地址替換為你要觀察的合約。
該指令會在同一個程序內把 key 傳給主網讀取,因此不需要從遮罩後的輸出複製 key。若免 key 讀取失敗,就不會登入。若訂閱未確認,或訂閱期間發生錯誤,指令會以非 0 狀態結束,且不會繼續主網讀取。約 30 秒內沒有符合條件的事件,本身不算失敗;要確認事件有送達,必須收到符合條件的通知。
步驟 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 是正的安全整數,再與 eth_chainId 比對;比對相符後才會讀取區塊與地址餘額。若數值無效或鏈 ID 不符,會以非 0 狀態結束,npm run walkthrough 也會在登入前停止:
import { formatEther, type Address } from "viem";
import { API_BASE, getChain, httpClient } from "./shared.js";
// Step 1: no account, no key. Read Robinhood Chain Testnet through the public endpoint.
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);
if (!Number.isSafeInteger(chain.chain_id) || chain.chain_id <= 0) {
throw new Error(
`invalid catalog chain_id for ${SLUG}: expected a positive safe integer, got ${String(chain.chain_id)}`,
);
}
const client = httpClient(chain, `${API_BASE}/${SLUG}/public`);
// Confirm the network before any other read.
const chainId = await client.getChainId();
if (chainId !== chain.chain_id) {
throw new Error(
`chain ID mismatch for ${SLUG}: expected ${chain.chain_id} (catalog), actual ${chainId} (eth_chainId)`,
);
}
const [blockNumber, balance] = await Promise.all([
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 { loadOrCreateWallet } from "./wallet.js";
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 { account } = loadOrCreateWallet({
walletFile: ".agent-wallet.json",
privateKey: process.env.WALLET_PRIVATE_KEY,
});
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());BLOCKVECTRA_API_KEY 非空時,步驟 2 會略過登入,也不會讀取或建立錢包檔案。否則優先使用 WALLET_PRIVATE_KEY;值無效時會直接停止,不會改讀錢包檔案。未提供時,首次執行會在目前工作目錄的 .agent-wallet.json 儲存專用登入錢包,之後在同一目錄重跑會重複使用同一身分;該錢包首次登入時才會建立帳戶。實作請見 src/wallet.ts。
該檔案包含明文私鑰,首次建立時權限設為 POSIX 0600,且符合 *wallet*.json,因此 Git 會忽略它。請保護並備份它,不要提交,不要把私鑰放在命令列,也不要使用持有資金的錢包。身分損壞、無效、無法讀取或無法寫入時,步驟 2 會在 SIWE challenge 前停止,不覆寫檔案,也不改用新身分;walkthrough 仍會先執行步驟 1 的公開讀取。沒有現有 API key 時,每次執行都會建立新的伺服器端金鑰,key 不會自動撤銷,重複使用帳戶身分也不等於重複使用 key。
WebSocket URL 會將 key 放在路徑中:wss://api.blockvectra.com/v1/robinhood_testnet/{api_key}。範本會在訂閱前檢查來自 GET /v1/chains 的即時 ws 旗標與 subscriptions 清單:
在此儲存庫中執行範本的訂閱實作。只有 eth_subscribe 傳回訂閱 ID 後才開始 30 秒視窗,結束時還要求 eth_unsubscribe 傳回 true。連線或訂閱錯誤、取消訂閱失敗都會阻止連續流程進入主網;僅有空白日誌視窗不能證明訂閱成功。
npm run step2每個 logs 訂閱篩選器都必須包含 address 或 topic0;請將範例地址取代為你想關注的合約。篩選規則、關閉碼與重新連線,請參閱 WebSocket 訂閱指南。
步驟 3:將同一把 key 切換到主網
npm run walkthrough 會在同一個程序內,把步驟 2 取得或重複使用的同一把 key 傳給主網讀取。單獨執行 npm run step3 時,需要在 BLOCKVECTRA_API_KEY 中提供既有的 API key;單獨執行的步驟 2 不會設定父層 shell 的環境。主網代稱是 robinhood_mainnet。下方是以 RPC 讀取區塊、並以 Data API 讀取股票代幣鏈上活動的片段,並非股票報價:
const apiKey = process.env.BLOCKVECTRA_API_KEY?.trim();
if (!apiKey) {
throw new Error(
"Set BLOCKVECTRA_API_KEY to an existing API key (create one in the console), " +
"or run `npm run walkthrough` to get a key and use it for the mainnet read in one process.",
);
}
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"相關指南
- 尋找測試網 RPC URL 與限制。
- 發送交易前,先從測試網 faucet 領取測試 ETH。
下一步
最後更新: