讀取鏈上資料
使用 polkadot-api 讀取鏈上帳戶餘額,並透過純整數運算完成代幣精度換算,避免浮點數精度遺失。
前置條件: 已安裝 polkadot-api@3.3.0 並產生 d9 描述檔(參閱 產生 PAPI 3 描述檔),以及一個已驗證創世雜湊的 RPC 位址。
1. 讀取帳戶餘額
Section titled “1. 讀取帳戶餘額”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); // 在最新最終確認區塊上讀取,確保狀態一致 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,最小單位 }; } finally { client.destroy(); }}驗證: 回傳的 freeBalance 為最小單位表示的 bigint,可使用第 2 步中的輔助函式格式化顯示。
2. 換算代幣金額
Section titled “2. 換算代幣金額”| 代幣 | 小數位 |
|---|---|
| D9(原生代幣) | 12 |
| USDT、Energy、Bandwidth(Pallet 資產) | 6 |
新增 src/amount.ts,用於在可讀十進位字串與鏈上 bigint 最小單位之間轉換。切勿使用浮點數處理鏈上金額。
export function parseAmount(text: string, decimals: number): bigint { const trimmed = text.trim(); if (!/^\d+(\.\d+)?$/.test(trimmed)) { throw new Error("金額必須為非負十進位數"); } const [whole, fraction = ""] = trimmed.split("."); if (fraction.length > decimals) { throw new Error(`金額最多支援 ${decimals} 位小數`); } 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();}使用範例:
import { formatAmount, parseAmount } from "./amount";
parseAmount("1.25", 12); // D9: 1250000000000nformatAmount(1250000000000n, 12); // D9: "1.25"parseAmount("5.5", 6); // USDT: 5500000n驗證: formatAmount(parseAmount("1.25", 12), 12) 回傳 "1.25"。
| 錯誤訊息 | 處理方式 |
|---|---|
金額必須為非負十進位數 |
僅輸入數字與最多一個小數點,例如 "1.25"。 |
金額最多支援 N 位小數 |
移除多餘小數位(D9 最多 12 位,USDT 最多 6 位)。 |
