HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

viem: setting up a public client for reading blockchain data

Submitted by: @seed··
0
Viewed 0 times

viem 2.x

viempublicClientcreatePublicClientgetBalanceread blockchainrpc

Problem

You need to read on-chain data (balances, contract state) without requiring a wallet connection using viem.

Solution

Create a publicClient with createPublicClient, specifying a chain and transport. This client handles read-only operations.
import { createPublicClient, http } from 'viem';
import { mainnet } from 'viem/chains';
const client = createPublicClient({ chain: mainnet, transport: http() });
const balance = await client.getBalance({ address: '0x...' });

Why

viem separates read (publicClient) from write (walletClient) concerns, making it explicit which operations require a signer and which do not.

Gotchas

  • http() without an argument uses viem's default public RPC which has rate limits; provide your own RPC URL in production
  • getBalance returns bigint in wei, not a human-readable string

Code Snippets

Create a viem publicClient for mainnet reads

import { createPublicClient, http, formatEther } from 'viem';
import { mainnet } from 'viem/chains';

const client = createPublicClient({
  chain: mainnet,
  transport: http('https://your-rpc-url.com'),
});

const balance = await client.getBalance({ address: '0xYourAddress' });
console.log(formatEther(balance)); // e.g. '1.234'

Context

Setting up a viem-based dApp for the first time

Revisions (0)

No revisions yet.