Public Client
A Public Client is an interface to "public" JSON-RPC 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
ts
import { createPublicClient } from 'viem'
Usage
Initialize a Client with your desired Chain (e.g. mainnet
) and Transport (e.g. http
).
ts
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http()
})
Then you can consume Public Actions:
ts
const blockNumber = await client.getBlockNumber()
Parameters
transport
- Type: Transport
The Transport of the Public Client.
ts
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
chain (optional)
- Type: Chain
The Chain of the Public Client.
ts
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
key (optional)
- Type:
string
- Default:
"public"
A key for the Client.
ts
const client = createPublicClient({
chain: mainnet,
key: 'public',
transport: http(),
})
name (optional)
- Type:
string
- Default:
"Public Client"
A name for the Client.
ts
const client = createPublicClient({
chain: mainnet,
name: 'Public Client',
transport: http(),
})
pollingInterval (optional)
- Type:
number
- Default:
4_000
Frequency (in ms) for polling enabled Actions.
ts
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.