Connect to peaq over RPC and read an account balance

A hands-on guide to making your first peaq JSON-RPC calls: connect to a peaq endpoint, read a native balance, handle common failures, and understand where RPC stops and indexing begins.

This guide answers one concrete question: how do I make a working JSON-RPC call against peaq from a Node.js 18+ script and read an account's native balance? You will send an eth_getBalance request to a peaq RPC endpoint, print the result, and handle the failure modes you will actually hit (bad endpoint, wrong network, rate limiting, malformed address). It also draws a clear line between RPC access and indexing, because confusing the two is the most common source of wasted debugging time.

What you need before the first call

peaq is an EVM-compatible network, so the JSON-RPC surface you already know from Ethereum tooling applies: eth_chainId, eth_blockNumber, eth_getBalance, eth_call, and so on. You do not need a special SDK to start; curl or Node's built-in fetch is enough.

You need an HTTP(S) RPC endpoint for peaq. Endpoints are provider-specific, so do not hardcode one you found in a random snippet. Get a current endpoint from a provider's peaq network page — for example the OnFinality peaq network page lists the network and how to obtain an endpoint. Treat the URL as configuration, not as a constant in your source.

  • Node.js 18+ (global fetch is available) or curl
  • A peaq RPC endpoint URL from a provider you trust
  • A peaq address you want to inspect (any valid 0x-prefixed address works for a read)
  • Awareness that reads are free of state changes — you are not signing anything
bash
# Confirm your toolchain before writing code
node --version   # expect v18.x or newer
curl --version

If node --version prints something below 18, upgrade before continuing — the examples rely on global fetch.

Make the first call: chain ID and block number

Before reading a balance, confirm you are actually talking to peaq. eth_chainId returns the chain identifier as a hex string; eth_blockNumber returns the latest block height. Both are cheap and tell you immediately whether the endpoint is alive and pointed at the network you expect.

Set your endpoint in an environment variable so you never commit it. The script below sends a JSON-RPC POST with the standard {jsonrpc, method, params, id} envelope and checks the HTTP status before parsing.

  • Always verify eth_chainId first — it catches wrong-network mistakes early
  • Check response.ok before calling .json()
  • JSON-RPC errors arrive with HTTP 200 and an error object, so inspect the body too
JavaScript · Node.js
// peaq-rpc-check.mjs  (Node.js 18+)
const RPC_URL = process.env.PEAQ_RPC_URL;
if (!RPC_URL) {
  console.error('Set PEAQ_RPC_URL to a peaq HTTP RPC endpoint.');
  process.exit(1);
}

async function rpc(method, params = []) {
  const res = await fetch(RPC_URL, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
  });

  if (!res.ok) {
    throw new Error(`HTTP ${res.status} ${res.statusText}`);
  }

  const body = await res.json();
  if (body.error) {
    throw new Error(`RPC error ${body.error.code}: ${body.error.message}`);
  }
  return body.result;
}

try {
  const chainId = await rpc('eth_chainId');
  const blockNumber = await rpc('eth_blockNumber');
  console.log('chainId:', chainId, '(', parseInt(chainId, 16), ')');
  console.log('latest block:', parseInt(blockNumber, 16));
} catch (err) {
  console.error('RPC check failed:', err.message);
  process.exit(1);
}

Run it with PEAQ_RPC_URL="https://your-endpoint" node peaq-rpc-check.mjs. The expected result is a hex chainId with its decimal form, plus a decimal block number that increases over time.

If you get an HTTP 4xx/5xx, the endpoint or path is wrong. If you get an RPC error, read the message — it usually names the problem. If the block number never changes, you may be pointed at a stale or wrong endpoint.

Read a native balance

eth_getBalance takes an address and a block tag. Use "latest" for the current balance. The result is a hex string in wei (the smallest unit), so convert it before displaying. JavaScript numbers lose precision above 2^53, so use BigInt rather than parseInt.

This is a pure read: no key, no signature, no gas. That makes it a safe first integration step before you touch anything that writes state.

  • Pass the address as the first param and "latest" as the second
  • Convert with BigInt(result) and format with the chain's decimals
  • Never use parseInt on a wei value — it silently truncates
JavaScript · Node.js
// peaq-balance.mjs  (Node.js 18+)
const RPC_URL = process.env.PEAQ_RPC_URL;
const ADDRESS = process.argv[2];

if (!RPC_URL || !ADDRESS) {
  console.error('Usage: PEAQ_RPC_URL=... node peaq-balance.mjs 0xYourAddress');
  process.exit(1);
}
if (!/^0x[0-9a-fA-F]{40}$/.test(ADDRESS)) {
  console.error('That does not look like a 0x-prefixed 20-byte address.');
  process.exit(1);
}

async function rpc(method, params = []) {
  const res = await fetch(RPC_URL, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
  });
  if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
  const body = await res.json();
  if (body.error) throw new Error(`RPC error ${body.error.code}: ${body.error.message}`);
  return body.result;
}

try {
  const weiHex = await rpc('eth_getBalance', [ADDRESS, 'latest']);
  const wei = BigInt(weiHex);
  // Confirm the native token's decimals from the network docs before formatting.
  const DECIMALS = 18;
  const whole = wei / 10n ** BigInt(DECIMALS);
  const frac = (wei % 10n ** BigInt(DECIMALS)).toString().padStart(DECIMALS, '0');
  console.log(`${ADDRESS} balance: ${whole}.${frac}`);
} catch (err) {
  console.error('Balance read failed:', err.message);
  process.exit(1);
}

Expected result: a line like 0xabc... balance: 12.340000000000000000. A zero balance prints 0.000... — that is a valid answer, not an error.

Confirm the native token's decimal places from the peaq network documentation rather than assuming 18; adjust DECIMALS if the docs say otherwise. The formatting logic is unchanged either way.

Handle the failures you will actually hit

Most first-call problems are not exotic. They are a missing environment variable, a malformed address, an endpoint that returns an error object, or a provider throttling you. Handle each explicitly so the error message tells you what to fix.

Rate limiting deserves a note: providers apply their own limits, and you should not assume a specific throughput. If you see repeated 429s, add backoff and reduce concurrency. To find your real ceiling, measure it — send a controlled burst of eth_blockNumber calls and record how many succeed per second against your own endpoint. That number is yours, not a published guarantee.

  • Validate the address shape before spending a request
  • Distinguish transport errors (HTTP status) from protocol errors (error object)
  • On 429 or 5xx, retry with exponential backoff and a cap
  • Log the method name with every error so failures are traceable
JavaScript · Node.js
async function rpcWithRetry(method, params = [], attempts = 3) {
  let lastErr;
  for (let i = 0; i < attempts; i++) {
    try {
      return await rpc(method, params);
    } catch (err) {
      lastErr = err;
      const retryable = /HTTP (429|5\d\d)/.test(err.message);
      if (!retryable || i === attempts - 1) break;
      const wait = 250 * 2 ** i;
      console.warn(`${method} failed (${err.message}); retrying in ${wait}ms`);
      await new Promise((r) => setTimeout(r, wait));
    }
  }
  throw new Error(`${method} failed after retries: ${lastErr.message}`);
}

Do not retry on a protocol error like an invalid address — retrying will not change the outcome. Retry only on transport-level signals such as 429 and 5xx.

RPC access is not indexing

RPC gives you point reads against current or historical chain state: a balance now, a block by number, a contract call result. It is excellent for that. It is not a query engine. If you need "every transfer to this address last month," "all holders of a token," or an aggregate across many blocks, issuing RPC calls in a loop is the wrong tool — you would be paginating blocks yourself and rebuilding an index by hand.

That is the job of an indexer: it ingests blocks and events into a queryable store so you can ask structured questions. Keep the two layers separate in your architecture. Use RPC for live reads and transaction submission; use an indexer for historical and aggregate queries. If you are new to the distinction, the OnFinality Learn library covers these building blocks, and the RPC Assistant is a practical next step for shaping and testing requests before you wire them into code.

  • RPC: single-state reads, block lookups, eth_call, sending transactions
  • Indexing: historical scans, event filtering, aggregates, dashboards
  • Do not loop RPC calls to reconstruct history — index it instead
  • Keep endpoint config in the environment so you can swap providers without code changes

A useful rule: if your question starts with "all" or "over time," you probably want an indexer, not an RPC loop.