Public Client โ
A Public Client is an interface to "public" JSON-RPC API methods such as retrieving block numbers, transactions, reading from smart contracts, etc through Public Actions.
The createPublicClient
function sets up a Public Client with a given Transport configured for a Chain.
Import โ
import { createPublicClient } from 'viem'
Usage โ
Initialize a Client with your desired Chain (e.g. mainnet
) and Transport (e.g. http
).
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http()
})
Then you can consume Public Actions:
const blockNumber = await client.getBlockNumber()
Parameters โ
transport โ
- Type: Transport
The Transport of the Public Client.
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
chain (optional) โ
- Type: Chain
The Chain of the Public Client.
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
batch (optional) โ
Flags for batch settings.
batch.multicall (optional) โ
- Type:
boolean | MulticallBatchOptions
- Default:
false
Toggle to enable eth_call
multicall aggregation.
const client = createPublicClient({
batch: {
multicall: true,
},
chain: mainnet,
transport: http(),
})
batch.multicall.batchSize (optional) โ
- Type:
number
- Default:
1_024
The maximum size (in bytes) for each multicall (aggregate3
) calldata chunk.
const client = createPublicClient({
batch: {
multicall: {
batchSize: 512,
},
},
chain: mainnet,
transport: http(),
})
batch.multicall.wait (optional) โ
- Type:
number
- Default:
16
The maximum number of milliseconds to wait before sending a batch.
const client = createPublicClient({
batch: {
multicall: {
wait: 16,
},
},
chain: mainnet,
transport: http(),
})
key (optional) โ
- Type:
string
- Default:
"public"
A key for the Client.
const client = createPublicClient({
chain: mainnet,
key: 'public',
transport: http(),
})
name (optional) โ
- Type:
string
- Default:
"Public Client"
A name for the Client.
const client = createPublicClient({
chain: mainnet,
name: 'Public Client',
transport: http(),
})
pollingInterval (optional) โ
- Type:
number
- Default:
4_000
Frequency (in ms) for polling enabled Actions.
const client = createPublicClient({
chain: mainnet,
pollingInterval: 10_000,
transport: http(),
})
Live Example โ
Check out the usage of createPublicClient
in the live Public Client Example below.