Início rápido com RPC na Robinhood Chain Testnet: leituras sem chave, logs via WebSocket e migração para a mainnet

Comece com o RPC da Robinhood Chain Testnet: URL RPC pública, leituras sem chave, logs via WebSocket com API key, acesso ao faucet e uso da mesma chave na mainnet.

A BlockVectra oferece suporte à Robinhood Chain Testnet (Chain ID 46630) via JSON-RPC e WebSocket, e a mesma API key também funciona na mainnet da Robinhood Chain. Este guia segue o modelo Robinhood Chain Testnet starter em três etapas: ler a testnet sem uma chave, criar uma conta de forma programática e transmitir logs, e depois usar a mesma chave na mainnet. Para parâmetros de endpoint, política de métodos e dados de ações tokenizadas, consulte o guia da Robinhood Chain.

Executar o modelo

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

Node.js 18 ou superior. Os três scripts são npm run step1, npm run step2 e npm run step3. As variáveis opcionais (BLOCKVECTRA_API_KEY, WALLET_PRIVATE_KEY) são lidas do shell; nada carrega o .env automaticamente.

Etapa 1: ler a testnet sem uma chave

O endpoint público https://api.blockvectra.com/v1/robinhood_testnet/public atende métodos JSON-RPC de carteira sem conta e sem API key. Consulte o Chain ID EIP-155 diretamente:

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":[]}'

A resposta é {"jsonrpc":"2.0","id":1,"result":"0xb626"}; 0xb626 é o Chain ID hexadecimal, que corresponde a 46630 em decimal.

O modelo lê a entrada da rede em GET /v1/chains e cria um cliente viem a partir dela, de modo que o nome e o ID da rede não fiquem fixos no código. De 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) });
}

Com esse módulo, src/step1-public-read.ts lê o Chain ID, o bloco mais recente e o saldo de um endereço:

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})`);

Etapa 2: criar uma conta programaticamente e assinar logs

src/step2-key-and-logs.ts faz login com uma carteira (SIWE, EIP-191) em https://console-api.blockvectra.com/v1. O primeiro login cria a conta; em seguida, o cliente cria uma API key. Novas contas recebem 30,000,000 CU no cadastro — sem cartão de crédito.

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());

Se você já tiver uma chave, export BLOCKVECTRA_API_KEY=... pula o cadastro. Sem WALLET_PRIVATE_KEY, o script gera uma carteira descartável na memória e a descarta ao final da execução; defina WALLET_PRIVATE_KEY a partir do seu ambiente local se desejar fazer login novamente na mesma conta.

A URL do WebSocket inclui a chave no caminho: wss://api.blockvectra.com/v1/robinhood_testnet/{api_key}. O modelo verifica a flag ws ativa e a lista subscriptions de GET /v1/chains antes de realizar a assinatura:

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),
});

Todo filtro de assinatura logs deve incluir um address ou um topic0; substitua o endereço de exemplo pelo contrato que você deseja monitorar. Consulte o guia de assinaturas WebSocket para regras de filtro, códigos de encerramento e reconexão.

Etapa 3: alternar a mesma chave para a mainnet

Mudar para a mainnet requer apenas uma palavra: use o slug robinhood_mainnet e a mesma API key. src/step3-mainnet.ts lê o número do bloco na mainnet e chama a Data API para tokens de ações da 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));

O mesmo endpoint de ranking em curl:

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

A Data API está disponível apenas na mainnet: GET /v1/chains retorna data: false para robinhood_testnet e data: true para robinhood_mainnet. Para parâmetros de requisição e estruturas de resposta, consulte o guia de ações tokenizadas.

Consultar limites e recursos pela API

Consulte GET /v1/chains para obter as flags em tempo real jsonrpc, data, ws e subscriptions, os métodos JSON-RPC permitidos, intervalos de blocos para logs, retenção de estado e o endpoint público de cada rede. Consulte GET /v1/plans para preços atuais e limites do plano.

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

Guias relacionados

Próximos passos

Última atualização:

Nesta página