# คู่มือเริ่มต้นสำหรับ Robinhood Chain Testnet RPC: การอ่านแบบไม่ใช้คีย์, Log บน WebSocket แล้วต่อด้วย Mainnet

> Source: https://docs.blockvectra.com/th/guides/robinhood-testnet-starter/

BlockVectra ให้บริการ Robinhood Chain Testnet (chain ID 46630) ผ่าน JSON-RPC และ WebSocket และ API key เดียวกันนี้ยังใช้งานบน Robinhood Chain mainnet ได้ด้วย คู่มือนี้จะพาทำตามเทมเพลต [Robinhood Chain Testnet starter](https://github.com/blockvectra/robinhood-testnet-starter?ref=docs-testnet-starter) ผ่าน 3 ขั้นตอน: อ่าน testnet โดยไม่ต้องใช้คีย์, เปิดบัญชีแบบเป็นโปรแกรมและสตรีม log, จากนั้นย้ายคีย์เดียวกันไปยัง mainnet สำหรับพารามิเตอร์ endpoint, นโยบายเมธอด และข้อมูลโทเค็นหุ้น โปรดดู [คู่มือ Robinhood Chain](https://docs.blockvectra.com/en/guides/robinhood-chain/)

## รันเทมเพลต

```bash
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`) จะอ่านจากเชลล์ โดยไม่มีการโหลดไฟล์ `.env` โดยอัตโนมัติ

## ขั้นตอนที่ 1: อ่าน Testnet โดยไม่ต้องใช้คีย์

public endpoint `https://api.blockvectra.com/v1/robinhood_testnet/public` ให้บริการเมธอดกระเป๋าเงิน JSON-RPC โดยไม่ต้องมีบัญชีและไม่ต้องมี API key สามารถสืบค้น EIP-155 chain ID ได้โดยตรง:

```bash
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`:

```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, บล็อกล่าสุด และยอดคงเหลือของที่อยู่:

```ts
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: เปิดบัญชีแบบเป็นโปรแกรมและสมัครรับข้อมูล Log

`src/step2-key-and-logs.ts` เข้าสู่ระบบด้วยกระเป๋าเงิน (SIWE, EIP-191) ที่ `https://console-api.blockvectra.com/v1` การเข้าสู่ระบบครั้งแรกจะสร้างบัญชี จากนั้นไคลเอนต์จะสร้าง API key บัญชีใหม่รับ 30,000,000 CU เมื่อลงทะเบียน — ไม่ต้องใช้บัตรเครดิต

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

หากคุณมีคีย์อยู่แล้ว การทำ `export BLOCKVECTRA_API_KEY=...` จะข้ามขั้นตอนการลงทะเบียน หากไม่มี `WALLET_PRIVATE_KEY` สคริปต์จะสร้างกระเป๋าเงินชั่วคราวในหน่วยความจำและทิ้งไปเมื่อการรันสิ้นสุดลง; ให้ตั้งค่า `WALLET_PRIVATE_KEY` จากสภาพแวดล้อมภายในเครื่องของคุณหากคุณต้องการเข้าสู่ระบบบัญชีเดิมอีกครั้ง

URL ของ WebSocket จะวางคีย์ไว้ในพาธ: `wss://api.blockvectra.com/v1/robinhood_testnet/{api_key}` เทมเพลตจะตรวจสอบแฟล็ก `ws` แบบเรียลไทม์และรายการ `subscriptions` จาก `GET /v1/chains` ก่อนที่จะทำการสมัครรับข้อมูล:

```ts
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](https://docs.blockvectra.com/en/guides/websocket-subscriptions/) สำหรับกฎการกรอง, รหัสการปิด และการเชื่อมต่อใหม่

## ขั้นตอนที่ 3: สลับคีย์เดียวกันไปยัง Mainnet

Mainnet เปลี่ยนเพียงคำเดียว: ใช้สลัก `robinhood_mainnet` และใช้ API key เดิม `src/step3-mainnet.ts` จะอ่านหมายเลขบล็อกของ mainnet และเรียก Data API สำหรับโทเค็นหุ้น Robinhood:

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

endpoint กระดานผู้นำเดียวกันในรูปแบบ curl:

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

Data API ใช้ได้เฉพาะบน mainnet เท่านั้น: `GET /v1/chains` จะรายงาน `data: false` สำหรับ `robinhood_testnet` และ `data: true` สำหรับ `robinhood_mainnet` สำหรับพารามิเตอร์คำขอและ response envelope โปรดดู [คู่มือโทเค็นหุ้น](https://docs.blockvectra.com/en/guides/stocks/)

## ค้นหาขีดจำกัดและความสามารถจาก API

อ่าน `GET /v1/chains` สำหรับแฟล็ก `jsonrpc`, `data`, `ws` และ `subscriptions` แบบเรียลไทม์, เมธอด JSON-RPC ที่อนุญาต, ช่วงบล็อกของ log, การเก็บรักษาสถานะ และ public endpoint ของแต่ละเชน อ่าน `GET /v1/plans` สำหรับราคาและขีดจำกัดของแผนบริการในปัจจุบัน

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

## คู่มือที่เกี่ยวข้อง

* [ค้นหา testnet RPC URL และขีดจำกัด](https://blockvectra.com/en/chains/robinhood_testnet/)
* [ขอรับ test ETH จาก testnet faucet](https://docs.blockvectra.com/en/guides/robinhood-testnet-faucet/) ก่อนส่งธุรกรรม

## ขั้นตอนถัดไป

* [เรียกดูไดเรกทอรีชุดข้อมูล](https://blockvectra.com/en/data/) เพื่อดูทุกชุดข้อมูลที่ BlockVectra จัดทำดัชนี
* [ดูแพ็กเกจฟรีและการกำหนดราคา](https://blockvectra.com/en/pricing/#free) เพื่อตรวจสอบสิ่งที่รวมอยู่ในบัญชีของคุณ
* [เข้าสู่ระบบคอนโซล](https://console.blockvectra.com/login/?next=%2Fkeys%2F) เพื่อสร้าง API key
