Public Client
A function to create a 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 { } from 'viem'Usage
Initialize a Client with your desired Chain (e.g. mainnet) and Transport (e.g. http).
import { , } from 'viem'
import { } from 'viem/chains'
const = ({
: ,
: ()
})Then you can consume Public Actions:
const = await .getBlockNumber() Optimization
The Public Client also supports eth_call Aggregation for improved performance.
eth_call Aggregation (via Multicall)
The Public Client supports the aggregation of eth_call requests into a single multicall (aggregate3) request.
This means for every Action that utilizes an eth_call request (ie. readContract), the Public Client will batch the requests (over a timed period) and send it to the RPC Provider in a single multicall request. This can dramatically improve network performance, and decrease the amount of Compute Units (CU) used by RPC Providers like Alchemy, Infura, etc.
The Public Client schedules the aggregation of eth_call requests over a given time period. By default, it executes the batch request at the end of the current JavaScript message queue (a zero delay), however, consumers can specify a custom wait period (in ms).
You can enable eth_call aggregation by setting the batch.multicall flag to true:
const = ({
: {
: true,
},
: ,
: (),
})You can also customize the
multicalloptions.
Now, when you start to utilize readContract Actions, the Public Client will batch and send over those requests at the end of the message queue (or custom time period) in a single eth_call multicall request:
import { } from 'viem'
import { } from './abi'
import { } from './client'
const = ({ , , : })
// The below will send a single request to the RPC Provider.
const [, , , ] = await .([
.read.name(),
.read.totalSupply(),
.read.symbol(),
.read.balanceOf([]),
])Read more on Contract Instances.
Parameters
transport
- Type: Transport
The Transport of the Public Client.
const = ({
: ,
: (),
})chain (optional)
- Type: Chain
The Chain of the Public Client.
const = ({
: ,
: (),
})batch (optional)
Flags for batch settings.
batch.multicall (optional)
- Type:
boolean | MulticallBatchOptions - Default:
false
Toggle to enable eth_call multicall aggregation.
const = ({
: {
: true,
},
: ,
: (),
})batch.multicall.batchSize (optional)
- Type:
number - Default:
1_024
The maximum size (in bytes) for each multicall (aggregate3) calldata chunk.
Note: Some RPC Providers limit the amount of calldata that can be sent in a single request. It is best to check with your RPC Provider to see if there are any calldata size limits to
eth_callrequests.
const = ({
: {
: {
: 512,
},
},
: ,
: (),
})batch.multicall.deployless (optional)
- Type:
boolean - Default:
false
Enable deployless multicall.
const = ({
: {
: {
: true,
},
},
: ,
: (),
})batch.multicall.wait (optional)
- Type:
number - Default:
0(zero delay)
The maximum number of milliseconds to wait before sending a batch.
const = ({
: {
: {
: 16,
},
},
: ,
: (),
})cacheTime (optional)
- Type:
number - Default:
client.pollingInterval
Time (in ms) that cached data will remain in memory.
const = ({
: 10_000,
: ,
: (),
})ccipRead (optional)
- Type:
(parameters: CcipRequestParameters) => Promise<CcipRequestReturnType> | false - Default:
true
CCIP Read configuration.
CCIP Read is enabled by default, but if set to false, the client will not support offchain CCIP lookups.
const = ({
: false,
: ,
: (),
})ccipRead.request (optional)
- Type:
(parameters: CcipRequestParameters) => Promise<CcipRequestReturnType>
A function that will be called to make the offchain CCIP lookup request.
const = ({
: {
async ({ , , }) {
// ...
}
},
: ,
: (),
})experimental_blockTag (optional)
- Type:
BlockTag - Default:
'latest'
The default block tag to use for Actions.
This will be used as the default block tag for the following Actions:
callestimateGasgetBalancegetBlocksimulateBlockswaitForTransactionReceiptwatchBlocks
const = ({
: 'pending',
: ,
: (),
})key (optional)
- Type:
string - Default:
"public"
A key for the Client.
const = ({
: ,
: 'public',
: (),
})name (optional)
- Type:
string - Default:
"Public Client"
A name for the Client.
const = ({
: ,
: 'Public Client',
: (),
})pollingInterval (optional)
- Type:
number - Default:
4_000
Frequency (in ms) for polling enabled Actions.
const = ({
: ,
: 10_000,
: (),
})rpcSchema (optional)
- Type:
RpcSchema - Default:
PublicRpcSchema
Typed JSON-RPC schema for the client.
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
// @noErrors
// ---cut---
import { rpcSchema } from 'viem'
type CustomRpcSchema = [{
Method: 'eth_wagmi',
Parameters: [string]
ReturnType: string
}]
const publicClient = createPublicClient({
chain: mainnet,
rpcSchema: rpcSchema<CustomRpcSchema>(),
transport: http(),
})
const result = await publicClient.request({
method: 'eth_wa // [!code focus]
// ^|
params: ['hello'],
}) dataSuffix (optional)
- Type:
Hex | { value: Hex; required?: boolean }
Data to append to the end of transaction calldata. Useful for adding transaction attribution.
When a simple hex string is provided, the suffix is appended on a best-effort basis. When using the object form with required: true, transactions will fail if the suffix cannot be appended.
Applies to simulateContract and estimateContractGas actions. For transaction-sending actions like sendTransaction, see Wallet Client.
const = ({
: ,
: '0xdeadbeef',
: (),
})Live Example
Check out the usage of createPublicClient in the live Public Client Example below.