Skip to content
On this page

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 โ€‹

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 โ€‹

The Transport of the Public Client.

ts
const client = createPublicClient({
  chain: mainnet,
  transport: http(), 
})

chain (optional) โ€‹

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.

Released under the MIT License.