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(),
})

batch (optional) โ€‹

Flags for batch settings.

batch.multicall (optional) โ€‹

  • Type: boolean | MulticallBatchOptions
  • Default: false

Toggle to enable eth_call multicall aggregation.

ts
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.

ts
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.

ts
const client = createPublicClient({
  batch: {
    multicall: {
      wait: 16, 
    },
  },
  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.