Read the Chain
Query on-chain account balances using polkadot-api and convert token amounts without floating-point precision loss.
Prerequisites: polkadot-api@3.3.0 with generated d9 descriptors (see Generate PAPI 3 descriptors) and a verified RPC URL.
1. Read an account balance
Section titled “1. Read an account balance”import { createClient } from "polkadot-api";import { getWsProvider } from "polkadot-api/ws";import { d9, getMetadata } from "@polkadot-api/descriptors";import { toChainAddress } from "@d9-network/dapp-connector/protocol";
export async function readFreeBalance(rpcUrl: string, userAddress: string) { const client = createClient(getWsProvider(rpcUrl), { getMetadata }); try { const api = client.getTypedApi(d9); // Query at the latest finalized block for consistent state const finalized = await client.getFinalizedBlock(); const account = await api.query.System.Account.getValue( toChainAddress(userAddress), { at: finalized.hash }, ); return { blockNumber: finalized.number, blockHash: finalized.hash, freeBalance: account.data.free, // bigint, raw units }; } finally { client.destroy(); }}Verify: freeBalance is returned as a bigint in raw units. Format it for display using the helper in step 2.
2. Convert token amounts
Section titled “2. Convert token amounts”| Token | Decimals |
|---|---|
| D9 (native) | 12 |
| USDT, Energy, Bandwidth (pallet assets) | 6 |
Create src/amount.ts to convert between human-readable decimal strings and on-chain bigint values. Never use floating-point numbers for on-chain amounts.
export function parseAmount(text: string, decimals: number): bigint { const trimmed = text.trim(); if (!/^\d+(\.\d+)?$/.test(trimmed)) { throw new Error("Amount must be a non-negative decimal number"); } const [whole, fraction = ""] = trimmed.split("."); if (fraction.length > decimals) { throw new Error(`Amount supports at most ${decimals} decimal places`); } return BigInt(whole + fraction.padEnd(decimals, "0"));}
export function formatAmount(raw: bigint, decimals: number): string { const base = 10n ** BigInt(decimals); const whole = raw / base; const fraction = (raw % base).toString().padStart(decimals, "0").replace(/0+$/, ""); return fraction ? `${whole}.${fraction}` : whole.toString();}Example usage:
import { formatAmount, parseAmount } from "./amount";
parseAmount("1.25", 12); // D9: 1250000000000nformatAmount(1250000000000n, 12); // D9: "1.25"parseAmount("5.5", 6); // USDT: 5500000nVerify: formatAmount(parseAmount("1.25", 12), 12) returns "1.25".
Common errors
Section titled “Common errors”| Error | Resolution |
|---|---|
Amount must be a non-negative decimal number |
Pass digits with at most one decimal point, such as "1.25". |
Amount supports at most N decimal places |
Trim excess decimal digits (D9 supports up to 12; USDT supports up to 6). |
