Query peaq Network Balances and Chain State from Node.js over RPC
A hands-on guide to connecting a Node.js 18+ script to the peaq network blockchain over JSON-RPC, reading account balances and chain metadata, and handling the failure modes you will actually hit.
This guide answers one concrete question: how do I read live state from the peaq network blockchain in a Node.js script without an SDK, and what do I do when the call fails? You will connect to a peaq RPC endpoint, fetch the chain name and an account balance, and add retry and error handling. The key distinction to keep in mind: RPC lets you read current chain state and submit transactions, but it is not an indexer. If you need historical queries, aggregations, or filtered event lookups, that is an indexing problem, not an RPC problem.
Step 1: Get a peaq RPC endpoint
peaq is a Substrate-based network, so its JSON-RPC surface follows the standard Substrate method set (for example system_chain, chain_getHeader, and state_getStorage). You need an HTTP(S) endpoint that speaks this protocol. You can review the network at the peaq network page on OnFinality to see how peaq is listed alongside other supported networks, and use the RPC Assistant to work out which endpoint and method combination fits your task.
Do not hardcode an endpoint you found in a random tutorial. Treat the endpoint as configuration (an environment variable) so you can switch providers or move between a public endpoint and a dedicated one without editing code. This guide never assumes a specific URL, latency figure, or rate limit; those depend on the endpoint you choose, and you should measure them yourself against your own workload.
- peaq uses Substrate-style JSON-RPC methods, not Ethereum JSON-RPC methods
- Store the endpoint in an environment variable, not in source code
- RPC reads current state; it does not give you historical or aggregated queries
# .env
export PEAQ_RPC_URL="https://your-peaq-endpoint.example"
# Node.js 18+ has global fetch, so no extra HTTP library is required
node --version # expect v18.x or newerIf node --version prints something below v18, upgrade before continuing; the example relies on the built-in fetch.
Step 2: Read chain metadata and an account balance
Start with a cheap, read-only call to confirm connectivity: system_chain returns the chain name. Then read an account's balance. On Substrate chains, balances live in storage, so the general-purpose way to read them is state_getStorage with the storage key for System.Account at the given account. Building that key by hand requires SCALE encoding and blake2 hashing, which is error-prone. A simpler and more robust approach for a first script is to use a light client library such as @polkadot/api, which encodes the storage key for you and still talks to the same RPC endpoint.
The example below uses @polkadot/api for the balance read but keeps a raw fetch call for system_chain so you can see both layers. Both hit the same endpoint; the library is just doing the encoding.
system_chainis the fastest connectivity check- Balance reads on Substrate chains go through storage, so use a library to encode keys
- Keep raw JSON-RPC available for debugging when a library call misbehaves
// balance.js — Node.js 18+
import { ApiPromise, WsProvider } from '@polkadot/api';
const HTTP_URL = process.env.PEAQ_RPC_URL;
const WS_URL = process.env.PEAQ_WS_URL; // optional websocket endpoint
const ADDRESS = process.env.PEAQ_ADDRESS;
if (!HTTP_URL || !ADDRESS) {
console.error('Set PEAQ_RPC_URL and PEAQ_ADDRESS');
process.exit(1);
}
async function rpc(method, params = []) {
const res = await fetch(HTTP_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}`);
const json = await res.json();
if (json.error) throw new Error(`${json.error.code}: ${json.error.message}`);
return json.result;
}
async function main() {
const chain = await rpc('system_chain');
console.log('Connected to chain:', chain);
if (!WS_URL) {
console.log('No PEAQ_WS_URL set; skipping balance read.');
return;
}
const api = await ApiPromise.create({ provider: new WsProvider(WS_URL) });
try {
const { data } = await api.query.system.account(ADDRESS);
console.log('Free balance:', data.free.toString());
console.log('Reserved:', data.reserved.toString());
} finally {
await api.disconnect();
}
}
main().catch((err) => {
console.error('Failed:', err.message);
process.exit(1);
});Expected result: a line like Connected to chain: <chain name> followed by a free balance in the chain's base units. The exact chain name and balance depend on the endpoint and account you supply, so do not compare against a number from this article.
If you only have an HTTP endpoint, the script still proves connectivity via system_chain and tells you it is skipping the balance read rather than failing silently.
Step 3: Handle the failures you will actually see
RPC calls fail in a small number of predictable ways: the endpoint is unreachable, the endpoint returns a JSON-RPC error object, the endpoint rate-limits you, or the method is not exposed. The script above already distinguishes an HTTP failure from a JSON-RPC error. Add a bounded retry with backoff for transient network errors, but do not retry a JSON-RPC error that indicates a bad request, because it will fail the same way every time.
If you need to know how your chosen endpoint behaves under your real load, measure it: run a loop of system_chain calls at your expected rate and record success rate and latency percentiles yourself. Do not rely on any provider's marketing numbers, including ones you might assume from a network listing.
- Retry transient network and 5xx errors with exponential backoff and a cap
- Do not retry deterministic JSON-RPC errors such as invalid params
- Measure latency and success rate against your own endpoint and workload
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 transient = /HTTP 5\d\d|ECONNRESET|ETIMEDOUT|fetch failed/.test(err.message);
if (!transient) throw err; // deterministic error, fail fast
const delay = 250 * 2 ** i;
console.warn(`Retry ${i + 1} after ${delay}ms: ${err.message}`);
await new Promise((r) => setTimeout(r, delay));
}
}
throw lastErr;
}Expected result: transient failures are retried up to three times with growing delays; a malformed request throws immediately so you can fix the call instead of hammering the endpoint.
Step 4: Know when RPC is the wrong tool
Everything above reads current state. If your task is "show every transfer to this account over the last 30 days" or "count how many times a pallet event fired this week," RPC is the wrong tool: you would have to scan blocks yourself and store the results, which is exactly what an indexer does. SubQuery is built for that pattern, and the OnFinality Learn library is a reasonable place to read up on indexing concepts before you build one.
A practical rule: use RPC for point reads and transaction submission; use an indexer for history, aggregation, and filtered event queries. Mixing them up is the most common source of slow, fragile scripts.
- RPC: current state, single-account reads, submitting extrinsics
- Indexer: historical queries, aggregations, event filtering
- If you find yourself looping over block numbers to build a history, switch to indexing