Skip to Content
Playground@core · Balances

Read Balance

Query native CFX and ERC-20 token balances using EspaceClient, ERC20_ABI, and EVM_TESTNET from @cfxdevkit/core.

Edit the address constant to check any wallet.

network:Testnet· chain 71
import { EspaceClient, EVM_TESTNET, ERC20_ABI, formatUnits } from '@cfxdevkit/core'

const client = new EspaceClient({
chainId: EVM_TESTNET.id,
rpcUrl:  EVM_TESTNET.rpcUrls.default.http[0],
})

// ── Native CFX balances ──────────────────────────────────────────────────────
const ADDRS = [
'0x85d80245dc02f5A89589e1f19c5c718E405B56AA',
'0x0000000000000000000000000000000000000000',
]

// ── ERC-20 token balance ─────────────────────────────────────────────────────
// WCFX (Wrapped CFX) on Conflux eSpace testnet
const WCFX   = '0x2ED3dddae5B2F321AF0806181FBFA6D049Be47d8'
const HOLDER = '0x85d80245dc02f5A89589e1f19c5c718E405B56AA'

;(async () => {
// getBalance() calls eth_getBalance and returns a formatted CFX string
console.log('-- CFX Balances --')
for (const addr of ADDRS) {
  const cfx = await client.getBalance(addr)
  console.log(addr.slice(0, 12) + '...  ' + Number(cfx).toFixed(6) + ' CFX')
}

// Batch-read token metadata and holder balance in one round-trip
const [name, symbol, decimals, raw] = await Promise.all([
  client.publicClient.readContract({ address: WCFX, abi: ERC20_ABI, functionName: 'name' }),
  client.publicClient.readContract({ address: WCFX, abi: ERC20_ABI, functionName: 'symbol' }),
  client.publicClient.readContract({ address: WCFX, abi: ERC20_ABI, functionName: 'decimals' }),
  client.publicClient.readContract({ address: WCFX, abi: ERC20_ABI, functionName: 'balanceOf', args: [HOLDER] }),
])

console.log('-- Token Balance --')
console.log('Token   : ' + name + ' (' + symbol + ')')
console.log('Decimals: ' + decimals)
console.log('Balance : ' + formatUnits(raw, decimals) + ' ' + symbol)
})().catch(console.error)


How it works

  1. getBalance(address) calls eth_getBalance and returns an already-formatted CFX string.
  2. ERC20_ABI from @cfxdevkit/core covers all standard ERC-20 functions.
  3. client.publicClient.readContract(...) is the underlying viem call for any view function.
  4. Batch multiple reads with Promise.all to cut round-trips.
Last updated on