Skip to content

createServer

createServer(client, serverOptions?): Server<typeof IncomingMessage, typeof ServerResponse>

Creates a lightweight http server for handling requests

Parameters

client

client.account: undefined | Account

The Account of the Client.

client.addChain?

Adds an EVM chain to the wallet.

Example

import { createWalletClient, custom } from 'viem'
import { optimism } from 'viem/chains'
const client = createWalletClient({
transport: custom(window.ethereum),
})
await client.addChain({ chain: optimism })

client.batch?

Flags for batch settings.

client.batch.multicall?: boolean | object

Toggle to enable eth_call multicall aggregation.

client.cacheTime?: number

Time (in ms) that cached data will remain in memory.

client.call?

Executes a new message call immediately without submitting a transaction to the network.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const data = await client.call({
account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',
data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
})

client.ccipRead?: false | object

CCIP Read configuration.

client.chain?: undefined | Chain

Chain for the client.

client.createBlockFilter?

Creates a Filter to listen for new block hashes that can be used with getFilterChanges.

Example

import { createPublicClient, createBlockFilter, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const filter = await createBlockFilter(client)
// { id: "0x345a6572337856574a76364e457a4366", type: 'block' }

client.createContractEventFilter?

Creates a Filter to retrieve event logs that can be used with getFilterChanges or getFilterLogs.

Example

import { createPublicClient, http, parseAbi } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const filter = await client.createContractEventFilter({
abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),
})

client.createEventFilter?

Creates a Filter to listen for new events that can be used with getFilterChanges.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const filter = await client.createEventFilter({
address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',
})

client.createPendingTransactionFilter?

Creates a Filter to listen for new pending transaction hashes that can be used with getFilterChanges.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const filter = await client.createPendingTransactionFilter()
// { id: "0x345a6572337856574a76364e457a4366", type: 'transaction' }

client.deployContract?

Deploys a contract to the network, given bytecode and constructor arguments.

Example

import { createWalletClient, http } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
account: privateKeyToAccount('0x…'),
chain: mainnet,
transport: http(),
})
const hash = await client.deployContract({
abi: [],
account: '0x…,
bytecode: '0x608060405260405161083e38038061083e833981016040819052610...',
})

client.dropTransaction?

Removes a transaction from the mempool.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.dropTransaction({
hash: '0xe58dceb6b20b03965bb678e27d141e151d7d4efc2334c2d6a49b9fac523f7364'
})

client.dumpState?

Serializes the current state (including contracts code, contract’s storage, accounts properties, etc.) into a savable data blob.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.dumpState()

client.estimateContractGas?

Estimates the gas required to successfully execute a contract write function call.

Remarks

Internally, uses a Public Client to call the estimateGas action with ABI-encoded data.

Example

import { createPublicClient, http, parseAbi } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const gas = await client.estimateContractGas({
address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
abi: parseAbi(['function mint() public']),
functionName: 'mint',
account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',
})

client.estimateFeesPerGas?

Returns an estimate for the fees per gas for a transaction to be included in the next block.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const maxPriorityFeePerGas = await client.estimateFeesPerGas()
// { maxFeePerGas: ..., maxPriorityFeePerGas: ... }

client.estimateGas?

Estimates the gas necessary to complete a transaction without submitting it to the network.

Example

import { createPublicClient, http, parseEther } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const gasEstimate = await client.estimateGas({
account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
value: parseEther('1'),
})

client.estimateMaxPriorityFeePerGas?

Returns an estimate for the max priority fee per gas (in wei) for a transaction to be included in the next block.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const maxPriorityFeePerGas = await client.estimateMaxPriorityFeePerGas()
// 10000000n

client.extend?

client.getAddresses?

Returns a list of account addresses owned by the wallet or client.

Example

import { createWalletClient, custom } from 'viem'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
})
const accounts = await client.getAddresses()

client.getAutomine?

Returns the automatic mining status of the node.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
const isAutomining = await client.getAutomine()

client.getBalance?

Returns the balance of an address in wei.

Remarks

You can convert the balance to ether units with formatEther.

const balance = await getBalance(client, {
address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
blockTag: 'safe'
})
const balanceAsEther = formatEther(balance)
// "6.942"

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const balance = await client.getBalance({
address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
})
// 10000000000000000000000n (wei)

client.getBlobBaseFee?

Returns the base fee per blob gas in wei.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
import { getBlobBaseFee } from 'viem/public'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const blobBaseFee = await client.getBlobBaseFee()

client.getBlock?

Returns information about a block at a block number, hash, or tag.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const block = await client.getBlock()

client.getBlockNumber?

Returns the number of the most recent block seen.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const blockNumber = await client.getBlockNumber()
// 69420n

client.getBlockTransactionCount?

Returns the number of Transactions at a block number, hash, or tag.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const count = await client.getBlockTransactionCount()

client.getBytecode?

client.getChainId?: () => Promise<number> & () => Promise<number>

Returns the chain ID associated with the current network.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const chainId = await client.getChainId()
// 1

client.getCode?

Retrieves the bytecode at an address.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const code = await client.getCode({
address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
})

client.getContractEvents?

Returns a list of event logs emitted by a contract.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
import { wagmiAbi } from './abi'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const logs = await client.getContractEvents(client, {
address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
abi: wagmiAbi,
eventName: 'Transfer'
})

client.getEip712Domain?

Reads the EIP-712 domain from a contract, based on the ERC-5267 specification.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const domain = await client.getEip712Domain({
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
})
// {
// domain: {
// name: 'ExampleContract',
// version: '1',
// chainId: 1,
// verifyingContract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
// },
// fields: '0x0f',
// extensions: [],
// }

client.getEnsAddress?

Gets address for ENS name.

Remarks

Calls resolve(bytes, bytes) on ENS Universal Resolver Contract.

Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to normalize ENS names with UTS-46 normalization before passing them to getEnsAddress. You can use the built-in normalize function for this.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
import { normalize } from 'viem/ens'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const ensAddress = await client.getEnsAddress({
name: normalize('wevm.eth'),
})
// '0xd2135CfB216b74109775236E36d4b433F1DF507B'

client.getEnsAvatar?

Gets the avatar of an ENS name.

Remarks

Calls getEnsText with key set to 'avatar'.

Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to normalize ENS names with UTS-46 normalization before passing them to getEnsAddress. You can use the built-in normalize function for this.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
import { normalize } from 'viem/ens'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const ensAvatar = await client.getEnsAvatar({
name: normalize('wevm.eth'),
})
// 'https://ipfs.io/ipfs/Qma8mnp6xV3J2cRNf3mTth5C8nV11CAnceVinc3y8jSbio'

client.getEnsName?

Gets primary name for specified address.

Remarks

Calls reverse(bytes) on ENS Universal Resolver Contract to “reverse resolve” the address to the primary ENS name.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const ensName = await client.getEnsName({
address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',
})
// 'wevm.eth'

client.getEnsResolver?

Gets resolver for ENS name.

Remarks

Calls findResolver(bytes) on ENS Universal Resolver Contract to retrieve the resolver of an ENS name.

Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to normalize ENS names with UTS-46 normalization before passing them to getEnsAddress. You can use the built-in normalize function for this.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
import { normalize } from 'viem/ens'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const resolverAddress = await client.getEnsResolver({
name: normalize('wevm.eth'),
})
// '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41'

client.getEnsText?

Gets a text record for specified ENS name.

Remarks

Calls resolve(bytes, bytes) on ENS Universal Resolver Contract.

Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to normalize ENS names with UTS-46 normalization before passing them to getEnsAddress. You can use the built-in normalize function for this.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
import { normalize } from 'viem/ens'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const twitterRecord = await client.getEnsText({
name: normalize('wevm.eth'),
key: 'com.twitter',
})
// 'wevm_dev'

client.getFeeHistory?

Returns a collection of historical gas information.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const feeHistory = await client.getFeeHistory({
blockCount: 4,
rewardPercentiles: [25, 75],
})

client.getFilterChanges?

Returns a list of logs or hashes based on a Filter since the last time it was called.

Remarks

A Filter can be created from the following actions:

Depending on the type of filter, the return value will be different:

  • If the filter was created with createContractEventFilter or createEventFilter, it returns a list of logs.
  • If the filter was created with createPendingTransactionFilter, it returns a list of transaction hashes.
  • If the filter was created with createBlockFilter, it returns a list of block hashes.

Examples

// Blocks
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const filter = await client.createBlockFilter()
const hashes = await client.getFilterChanges({ filter })
// Contract Events
import { createPublicClient, http, parseAbi } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const filter = await client.createContractEventFilter({
address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),
eventName: 'Transfer',
})
const logs = await client.getFilterChanges({ filter })
// Raw Events
import { createPublicClient, http, parseAbiItem } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const filter = await client.createEventFilter({
address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),
})
const logs = await client.getFilterChanges({ filter })
// Transactions
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const filter = await client.createPendingTransactionFilter()
const hashes = await client.getFilterChanges({ filter })

client.getFilterLogs?

Returns a list of event logs since the filter was created.

Remarks

getFilterLogs is only compatible with event filters.

Example

import { createPublicClient, http, parseAbiItem } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const filter = await client.createEventFilter({
address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),
})
const logs = await client.getFilterLogs({ filter })

client.getGasPrice?

Returns the current price of gas (in wei).

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const gasPrice = await client.getGasPrice()

client.getLogs?

Returns a list of event logs matching the provided parameters.

Example

import { createPublicClient, http, parseAbiItem } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const logs = await client.getLogs()

client.getPermissions?

Gets the wallets current permissions.

Example

import { createWalletClient, custom } from 'viem'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
})
const permissions = await client.getPermissions()

client.getProof?

Returns the account and storage values of the specified account including the Merkle-proof.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const block = await client.getProof({
address: '0x...',
storageKeys: ['0x...'],
})

client.getStorageAt?

Returns the value from a storage slot at a given address.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
import { getStorageAt } from 'viem/contract'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const code = await client.getStorageAt({
address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
slot: toHex(0),
})

client.getTransaction?

Returns information about a Transaction given a hash or block identifier.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const transaction = await client.getTransaction({
hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',
})

client.getTransactionConfirmations?

Returns the number of blocks passed (confirmations) since the transaction was processed on a block.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const confirmations = await client.getTransactionConfirmations({
hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',
})

client.getTransactionCount?

Returns the number of Transactions an Account has broadcast / sent.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const transactionCount = await client.getTransactionCount({
address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
})

client.getTransactionReceipt?

Returns the Transaction Receipt given a Transaction hash.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const transactionReceipt = await client.getTransactionReceipt({
hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',
})

client.getTxpoolContent?

Returns the details of all transactions currently pending for inclusion in the next block(s), as well as the ones that are being scheduled for future execution only.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
const content = await client.getTxpoolContent()

client.getTxpoolStatus?

Returns a summary of all the transactions currently pending for inclusion in the next block(s), as well as the ones that are being scheduled for future execution only.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
const status = await client.getTxpoolStatus()

client.impersonateAccount?

Impersonate an account or contract address. This lets you send transactions from that account even if you don’t have access to its private key.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.impersonateAccount({
address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
})

client.increaseTime?

Jump forward in time by the given amount of time, in seconds.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.increaseTime({
seconds: 420,
})

client.inspectTxpool?

Returns a summary of all the transactions currently pending for inclusion in the next block(s), as well as the ones that are being scheduled for future execution only.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
const data = await client.inspectTxpool()

client.key?: string

A key for the client.

client.loadState?

Adds state previously dumped with dumpState to the current chain.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.loadState({ state: '0x...' })

client.mine?

Mine a specified number of blocks.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.mine({ blocks: 1 })

client.multicall?

Similar to readContract, but batches up multiple functions on a contract in a single RPC call via the multicall3 contract.

Example

import { createPublicClient, http, parseAbi } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const abi = parseAbi([
'function balanceOf(address) view returns (uint256)',
'function totalSupply() view returns (uint256)',
])
const result = await client.multicall({
contracts: [
{
address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
abi,
functionName: 'balanceOf',
args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],
},
{
address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
abi,
functionName: 'totalSupply',
},
],
})
// [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]

client.name?: string

A name for the client.

client.pollingInterval?: number

Frequency (in ms) for polling enabled actions & events. Defaults to 4_000 milliseconds.

client.prepareTransactionRequest?: <request, chainOverride, accountOverride>(args) => Promise<{ [K in string | number | symbol]: (UnionRequiredBy<Extract<(…) & (…) & (…), (…) extends (…) ? (…) : (…)> & Object, ParameterTypeToParameters<(…)[(…)] extends readonly (…)[] ? (…)[(…)] : (…) | (…) | (…) | (…) | (…) | (…)>> & (unknown extends request[“kzg”] ? Object : Pick<request, “kzg”>))[K] }> & <request, chainOverride, accountOverride>(args) => Promise<{ [K in string | number | symbol]: (UnionRequiredBy<Extract<(…) & (…) & (…), (…) extends (…) ? (…) : (…)> & Object, ParameterTypeToParameters<(…)[(…)] extends readonly (…)[] ? (…)[(…)] : (…) | (…) | (…) | (…) | (…) | (…)>> & (unknown extends request[“kzg”] ? Object : Pick<request, “kzg”>))[K] }>

Prepares a transaction request for signing.

Param

PrepareTransactionRequestParameters

Examples

import { createWalletClient, custom } from 'viem'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
})
const request = await client.prepareTransactionRequest({
account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
to: '0x0000000000000000000000000000000000000000',
value: 1n,
})
// Account Hoisting
import { createWalletClient, http } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
account: privateKeyToAccount('0x…'),
chain: mainnet,
transport: custom(window.ethereum),
})
const request = await client.prepareTransactionRequest({
to: '0x0000000000000000000000000000000000000000',
value: 1n,
})

client.readContract?

Calls a read-only function on a contract, and returns the response.

Remarks

A “read-only” function (constant function) on a Solidity contract is denoted by a view or pure keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.

Internally, uses a Public Client to call the call action with ABI-encoded data.

Example

import { createPublicClient, http, parseAbi } from 'viem'
import { mainnet } from 'viem/chains'
import { readContract } from 'viem/contract'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const result = await client.readContract({
address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
abi: parseAbi(['function balanceOf(address) view returns (uint256)']),
functionName: 'balanceOf',
args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],
})
// 424122n

client.removeBlockTimestampInterval?

Removes setBlockTimestampInterval if it exists.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
import { removeBlockTimestampInterval } from 'viem/test'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.removeBlockTimestampInterval()

client.request?: EIP1193RequestFn<[object, object, object, object, object]>

Request function wrapped with friendly error handling

client.requestAddresses?

Requests a list of accounts managed by a wallet.

Sends a request to the wallet, asking for permission to access the user’s accounts. After the user accepts the request, it will return a list of accounts (addresses).

This API can be useful for dapps that need to access the user’s accounts in order to execute transactions or interact with smart contracts.

Example

import { createWalletClient, custom } from 'viem'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
})
const accounts = await client.requestAddresses()

client.requestPermissions?

Requests permissions for a wallet.

Example

import { createWalletClient, custom } from 'viem'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
})
const permissions = await client.requestPermissions({
eth_accounts: {}
})

client.reset?

Resets fork back to its original state.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.reset({ blockNumber: 69420n })

client.revert?

Revert the state of the blockchain at the current block.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.revert({ id: '0x…' })

client.sendRawTransaction?: (args) => Promise<`0x${string}`> & (args) => Promise<`0x${string}`>

Sends a signed transaction to the network

Param

Client to use

Param

SendRawTransactionParameters

Example

import { createWalletClient, custom } from 'viem'
import { mainnet } from 'viem/chains'
import { sendRawTransaction } from 'viem/wallet'
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
})
const hash = await client.sendRawTransaction({
serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'
})

client.sendTransaction?

Creates, signs, and sends a new transaction to the network.

Examples

import { createWalletClient, custom } from 'viem'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
})
const hash = await client.sendTransaction({
account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
value: 1000000000000000000n,
})
// Account Hoisting
import { createWalletClient, http } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
account: privateKeyToAccount('0x…'),
chain: mainnet,
transport: http(),
})
const hash = await client.sendTransaction({
to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
value: 1000000000000000000n,
})

client.sendUnsignedTransaction?

Returns the details of all transactions currently pending for inclusion in the next block(s), as well as the ones that are being scheduled for future execution only.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
const hash = await client.sendUnsignedTransaction({
from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',
to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
value: 1000000000000000000n,
})

client.setAutomine?

Enables or disables the automatic mining of new blocks with each new transaction submitted to the network.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.setAutomine()

client.setBalance?

Modifies the balance of an account.

Example

import { createTestClient, http, parseEther } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.setBalance({
address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',
value: parseEther('1'),
})

client.setBlockGasLimit?

Sets the block’s gas limit.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.setBlockGasLimit({ gasLimit: 420_000n })

client.setBlockTimestampInterval?

Similar to increaseTime, but sets a block timestamp interval. The timestamp of future blocks will be computed as lastBlock_timestamp + interval.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.setBlockTimestampInterval({ interval: 5 })

client.setCode?

Modifies the bytecode stored at an account’s address.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.setCode({
address: '0xe846c6fcf817734ca4527b28ccb4aea2b6663c79',
bytecode: '0x60806040526000600355600019600955600c80546001600160a01b031916737a250d5630b4cf539739df…',
})

client.setCoinbase?

Sets the coinbase address to be used in new blocks.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.setCoinbase({
address: '0xe846c6fcf817734ca4527b28ccb4aea2b6663c79',
})

client.setIntervalMining?

Sets the automatic mining interval (in seconds) of blocks. Setting the interval to 0 will disable automatic mining.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.setIntervalMining({ interval: 5 })

client.setLoggingEnabled?

Enable or disable logging on the test node network.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.setLoggingEnabled()

client.setMinGasPrice?

Change the minimum gas price accepted by the network (in wei).

Note: setMinGasPrice can only be used on clients that do not have EIP-1559 enabled.

Example

import { createTestClient, http, parseGwei } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.setMinGasPrice({
gasPrice: parseGwei('20'),
})

client.setNextBlockBaseFeePerGas?

Sets the next block’s base fee per gas.

Example

import { createTestClient, http, parseGwei } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.setNextBlockBaseFeePerGas({
baseFeePerGas: parseGwei('20'),
})

client.setNextBlockTimestamp?

Sets the next block’s timestamp.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.setNextBlockTimestamp({ timestamp: 1671744314n })

client.setNonce?

Modifies (overrides) the nonce of an account.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.setNonce({
address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',
nonce: 420,
})

client.setRpcUrl?

Sets the backend RPC URL.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.setRpcUrl('https://eth-mainnet.g.alchemy.com/v2')

client.setStorageAt?

Writes to a slot of an account’s storage.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.setStorageAt({
address: '0xe846c6fcf817734ca4527b28ccb4aea2b6663c79',
index: 2,
value: '0x0000000000000000000000000000000000000000000000000000000000000069',
})

client.signMessage?

Calculates an Ethereum-specific signature in EIP-191 format: keccak256("\x19Ethereum Signed Message:\n" + len(message) + message)).

With the calculated signature, you can:

Examples

import { createWalletClient, custom } from 'viem'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
})
const signature = await client.signMessage({
account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
message: 'hello world',
})
// Account Hoisting
import { createWalletClient, http } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
account: privateKeyToAccount('0x…'),
chain: mainnet,
transport: http(),
})
const signature = await client.signMessage({
message: 'hello world',
})

client.signTransaction?

Signs a transaction.

Examples

import { createWalletClient, custom } from 'viem'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
})
const request = await client.prepareTransactionRequest({
account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
to: '0x0000000000000000000000000000000000000000',
value: 1n,
})
const signature = await client.signTransaction(request)
// Account Hoisting
import { createWalletClient, http } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
account: privateKeyToAccount('0x…'),
chain: mainnet,
transport: custom(window.ethereum),
})
const request = await client.prepareTransactionRequest({
to: '0x0000000000000000000000000000000000000000',
value: 1n,
})
const signature = await client.signTransaction(request)

client.signTypedData?

Signs typed data and calculates an Ethereum-specific signature in EIP-191 format: keccak256("\x19Ethereum Signed Message:\n" + len(message) + message)).

Examples

import { createWalletClient, custom } from 'viem'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
})
const signature = await client.signTypedData({
account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
domain: {
name: 'Ether Mail',
version: '1',
chainId: 1,
verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC',
},
types: {
Person: [
{ name: 'name', type: 'string' },
{ name: 'wallet', type: 'address' },
],
Mail: [
{ name: 'from', type: 'Person' },
{ name: 'to', type: 'Person' },
{ name: 'contents', type: 'string' },
],
},
primaryType: 'Mail',
message: {
from: {
name: 'Cow',
wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826',
},
to: {
name: 'Bob',
wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB',
},
contents: 'Hello, Bob!',
},
})
// Account Hoisting
import { createWalletClient, http } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
account: privateKeyToAccount('0x…'),
chain: mainnet,
transport: http(),
})
const signature = await client.signTypedData({
domain: {
name: 'Ether Mail',
version: '1',
chainId: 1,
verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC',
},
types: {
Person: [
{ name: 'name', type: 'string' },
{ name: 'wallet', type: 'address' },
],
Mail: [
{ name: 'from', type: 'Person' },
{ name: 'to', type: 'Person' },
{ name: 'contents', type: 'string' },
],
},
primaryType: 'Mail',
message: {
from: {
name: 'Cow',
wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826',
},
to: {
name: 'Bob',
wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB',
},
contents: 'Hello, Bob!',
},
})

client.simulateContract?

Simulates/validates a contract interaction. This is useful for retrieving return data and revert reasons of contract write functions.

Remarks

This function does not require gas to execute and does not change the state of the blockchain. It is almost identical to readContract, but also supports contract write functions.

Internally, uses a Public Client to call the call action with ABI-encoded data.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const result = await client.simulateContract({
address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
abi: parseAbi(['function mint(uint32) view returns (uint32)']),
functionName: 'mint',
args: ['69420'],
account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
})

client.snapshot?

Snapshot the state of the blockchain at the current block.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
import { snapshot } from 'viem/test'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.snapshot()

client.stopImpersonatingAccount?

Stop impersonating an account after having previously used impersonateAccount.

Example

import { createTestClient, http } from 'viem'
import { foundry } from 'viem/chains'
import { stopImpersonatingAccount } from 'viem/test'
const client = createTestClient({
mode: 'anvil',
chain: 'foundry',
transport: http(),
})
await client.stopImpersonatingAccount({
address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',
})

client.switchChain?

Switch the target chain in a wallet.

Example

import { createWalletClient, custom } from 'viem'
import { mainnet, optimism } from 'viem/chains'
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
})
await client.switchChain({ id: optimism.id })

client.tevm?: object & EIP1193Events & object & Eip1193RequestProvider

Low level access to TEVM can be accessed via tevm. These APIs are not guaranteed to be stable.

See

TevmNode

Example

import { createMemoryClient } from 'tevm'
const memoryClient = createMemoryClient()
// low level access to the TEVM VM, blockchain, EVM, stateManager, mempool, receiptsManager and more are available
const vm = await memoryClient.tevm.getVm()
vm.runBlock(...)
const { blockchain, evm, stateManager } = vm
blockchain.addBlock(...)
evm.runCall(...)
stateManager.putAccount(...)
const mempool = await memoryClient.tevm.getTxPool()
const receiptsManager = await memoryClient.tevm.getReceiptsManager()

client.tevmCall?: CallHandler

A powerful low level API for executing calls and sending transactions. See CallParams for options reference. See CallResult for return values reference. Remember, you must set createTransaction: true to send a transaction. Otherwise, it will be a call. You must also mine the transaction before it updates the canonical head state. This can be avoided by setting mining mode to auto when using createMemoryClient.

Example

import { createMemoryClient } from 'tevm'
import { ERC20 } from 'tevm/contract'
const client = createMemoryClient()
const token = ERC20.withAddress(`0x${'0721'.repeat(10)}`)
await client.setAccount(token)
const balance = await client.tevmCall({
to: token.address,
data: encodeFunctionData(token.read.balanceOf, [token.address]),
})

In addition to making basic calls, you can also do advanced things like:

  • Impersonate accounts via passing in from, caller, or origin
  • Set the call depth via depth
  • Create a trace or access list using createTrace: true or createAccessList: true
  • Send as a transaction with createTransaction: true For all options see CallParams

client.tevmContract?: ContractHandler

A powerful low level API for calling contracts. Similar to tevmCall but takes care of encoding and decoding data, revert messages, etc. See ContractParams for options reference. See ContractResult for return values reference. Remember, you must set createTransaction: true to send a transaction. Otherwise, it will be a call. You must also mine the transaction before it updates the canonical head state. This can be avoided by setting mining mode to auto when using createMemoryClient.

Example

import { createMemoryClient } from 'tevm'
import { ERC20 } from './MyERC721.sol'
const client = createMemoryClient()
const token = ERC20.withAddress(`0x${'0721'.repeat(10)}`)
await client.setAccount(token)
const balance = await client.tevmContract({
contract: token,
method: token.read.balanceOf,
args: [token.address],
})

In addition to making basic calls, you can also do advanced things like:

  • Impersonate accounts via passing in from, caller, or origin
  • Set the call depth via depth
  • Create a trace or access list using createTrace: true or createAccessList: true
  • Send as a transaction with createTransaction: true For all options see ContractParams

client.tevmDeploy?: DeployHandler

Deploys a contract to the EVM with encoded constructor arguments. Extends tevmCall so it supports all advanced options.

See

  • DeployParams for options reference.
  • DeployResult for return values reference. Remember, you must set createTransaction: true to send a transaction. Otherwise, it will be a call. You must also mine the transaction before it updates the canonical head state. This can be avoided by setting mining mode to auto when using createMemoryClient.

Example

import { createMemoryClient } from 'tevm'
import { ERC20 } from './MyERC721.sol'
const client = createMemoryClient()
const token = ERC20.withAddress(`0x${'0721'.repeat(10)}`)
const deploymentResult = await client.tevmDeploy({
abi: token.abi,
bytecode: token.bytecode,
args: ['TokenName', 18, 'SYMBOL'],
})
console.log(deploymentResult.createdAddress)

client.tevmDumpState?: DumpStateHandler

Dumps a JSON serializable state from the EVM. This can be useful for persisting and restoring state between processes.

Example

import { createMemoryClient } from 'tevm'
import fs from 'fs'
const client = createMemoryClient()
const state = await client.tevmDumpState()
fs.writeFileSync('state.json', JSON.stringify(state))

client.tevmGetAccount?: GetAccountHandler

Gets the account state of an account. It does not return the storage state by default but can if returnStorage is set to true. In forked mode, the storage is only the storage TEVM has cached and may not represent all the on-chain storage.

See

Example

import { createMemoryClient } from 'tevm'
const client = createMemoryClient()
const account = await client.tevmGetAccount({
address: `0x${'0000'.repeat(10)}`,
returnStorage: true,
})

client.tevmLoadState?: LoadStateHandler

Loads a JSON serializable state into the EVM. This can be useful for persisting and restoring state between processes.

Example

import { createMemoryClient } from 'tevm'
import fs from 'fs'
const client = createMemoryClient()
const state = fs.readFileSync('state.json', 'utf8')
await client.tevmLoadState(state)

client.tevmMine?: MineHandler

Mines a new block with all pending transactions. In manual mode you must call this manually before the canonical head state is updated.

Example

import { createMemoryClient } from 'tevm'
const client = createMemoryClient()
await client.tevmMine()

client.tevmReady?

Returns a promise that resolves when the TEVM is ready. This is not needed to explicitly be called as all actions will wait for the TEVM to be ready.

Example

import { createMemoryClient } from 'tevm'
const client = createMemoryClient()
await client.tevmReady()

Same as calling client.tevm.ready()

client.tevmSetAccount?: SetAccountHandler

Sets any property of an account including its balance, nonce, contract deployedBytecode, contract state, and more.

See

Example

import { createMemoryClient, numberToHex } from 'tevm'
import { SimpleContract } from 'tevm/contract'
const client = createMemoryClient()
await client.tevmSetAccount({
address: `0x${'0123'.repeat(10)}`,
balance: 100n,
nonce: 1n,
deployedBytecode: SimpleContract.deployedBytecode,
state: {
[`0x${'0'.repeat(64)}`]: numberToHex(420n),
}
})

client.transport?: TransportConfig<string> & object

The RPC transport

client.type?: string

The type of client.

client.uid?: string

A unique ID for the client.

client.uninstallFilter?

Destroys a Filter that was created from one of the following Actions:

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
import { createPendingTransactionFilter, uninstallFilter } from 'viem/public'
const filter = await client.createPendingTransactionFilter()
const uninstalled = await client.uninstallFilter({ filter })
// true

client.verifyMessage?

Verify that a message was signed by the provided address.

Compatible with Smart Contract Accounts & Externally Owned Accounts via ERC-6492.

client.verifySiweMessage?

Verifies EIP-4361 formatted message was signed.

Compatible with Smart Contract Accounts & Externally Owned Accounts via ERC-6492.

client.verifyTypedData?

Verify that typed data was signed by the provided address.

client.waitForTransactionReceipt?

Waits for the Transaction to be included on a Block (one confirmation), and then returns the Transaction Receipt. If the Transaction reverts, then the action will throw an error.

Remarks

The waitForTransactionReceipt action additionally supports Replacement detection (e.g. sped up Transactions).

Transactions can be replaced when a user modifies their transaction in their wallet (to speed up or cancel). Transactions are replaced when they are sent from the same nonce.

There are 3 types of Transaction Replacement reasons:

  • repriced: The gas price has been modified (e.g. different maxFeePerGas)
  • cancelled: The Transaction has been cancelled (e.g. value === 0n)
  • replaced: The Transaction has been replaced (e.g. different value or data)

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const transactionReceipt = await client.waitForTransactionReceipt({
hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',
})

client.watchAsset?

Adds an EVM chain to the wallet.

Example

import { createWalletClient, custom } from 'viem'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
})
const success = await client.watchAsset({
type: 'ERC20',
options: {
address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
decimals: 18,
symbol: 'WETH',
},
})

client.watchBlockNumber?

Watches and returns incoming block numbers.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const unwatch = await client.watchBlockNumber({
onBlockNumber: (blockNumber) => console.log(blockNumber),
})

client.watchBlocks?

Watches and returns information for incoming blocks.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const unwatch = await client.watchBlocks({
onBlock: (block) => console.log(block),
})

client.watchContractEvent?

Watches and returns emitted contract event logs.

Remarks

This Action will batch up all the event logs found within the pollingInterval, and invoke them via onLogs.

watchContractEvent will attempt to create an Event Filter and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. eth_newFilter), then watchContractEvent will fall back to using getLogs instead.

Example

import { createPublicClient, http, parseAbi } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const unwatch = client.watchContractEvent({
address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
abi: parseAbi(['event Transfer(address indexed from, address indexed to, uint256 value)']),
eventName: 'Transfer',
args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },
onLogs: (logs) => console.log(logs),
})

client.watchEvent?

Watches and returns emitted Event Logs.

Remarks

This Action will batch up all the Event Logs found within the pollingInterval, and invoke them via onLogs.

watchEvent will attempt to create an Event Filter and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. eth_newFilter), then watchEvent will fall back to using getLogs instead.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const unwatch = client.watchEvent({
onLogs: (logs) => console.log(logs),
})

client.watchPendingTransactions?

Watches and returns pending transaction hashes.

Remarks

This Action will batch up all the pending transactions found within the pollingInterval, and invoke them via onTransactions.

Example

import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const unwatch = await client.watchPendingTransactions({
onTransactions: (hashes) => console.log(hashes),
})

client.writeContract?

Executes a write function on a contract.

A “write” function on a Solidity contract modifies the state of the blockchain. These types of functions require gas to be executed, and hence a Transaction is needed to be broadcast in order to change the state.

Internally, uses a Wallet Client to call the sendTransaction action with ABI-encoded data.

Warning: The write internally sends a transaction – it does not validate if the contract write will succeed (the contract may throw an error). It is highly recommended to simulate the contract write with contract.simulate before you execute it.

Examples

import { createWalletClient, custom, parseAbi } from 'viem'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
})
const hash = await client.writeContract({
address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
abi: parseAbi(['function mint(uint32 tokenId) nonpayable']),
functionName: 'mint',
args: [69420],
})
// With Validation
import { createWalletClient, custom, parseAbi } from 'viem'
import { mainnet } from 'viem/chains'
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
})
const { request } = await client.simulateContract({
address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
abi: parseAbi(['function mint(uint32 tokenId) nonpayable']),
functionName: 'mint',
args: [69420],
}
const hash = await client.writeContract(request)

serverOptions?: ServerOptions<typeof IncomingMessage, typeof ServerResponse> = {}

Optional options to pass to the http server

Returns

Server<typeof IncomingMessage, typeof ServerResponse>

To use pass in the Tevm[‘request’] request handler

Throws

Examples

import { createMemoryClient } from 'tevm'
import { createServer } from 'tevm/server'
const tevm = createMemoryClient()
const server = createServer({
request: tevm.request,
})
server.listen(8080, () => console.log('listening on 8080'))

To interact with the HTTP server you can create a Tevm client

import { createTevmClient } from '@tevm/client'
const client = createTevmClient()

Defined in

packages/server/src/createServer.js:32