createServer
createServer(
client
,serverOptions
?):Server
<typeofIncomingMessage
, typeofServerResponse
>
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.
- Docs: https://viem.sh/docs/actions/wallet/addChain
- JSON-RPC Methods:
eth_addEthereumChain
Example
• 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.
- Docs: https://viem.sh/docs/actions/public/call
- JSON-RPC Methods:
eth_call
Example
• 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
.
- Docs: https://viem.sh/docs/actions/public/createBlockFilter
- JSON-RPC Methods:
eth_newBlockFilter
Example
• client.createContractEventFilter?
Creates a Filter to retrieve event logs that can be used with getFilterChanges
or getFilterLogs
.
Example
• client.createEventFilter?
Creates a Filter
to listen for new events that can be used with getFilterChanges
.
- Docs: https://viem.sh/docs/actions/public/createEventFilter
- JSON-RPC Methods:
eth_newFilter
Example
• client.createPendingTransactionFilter?
Creates a Filter to listen for new pending transaction hashes that can be used with getFilterChanges
.
- Docs: https://viem.sh/docs/actions/public/createPendingTransactionFilter
- JSON-RPC Methods:
eth_newPendingTransactionFilter
Example
• client.deployContract?
Deploys a contract to the network, given bytecode and constructor arguments.
- Docs: https://viem.sh/docs/contract/deployContract
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/deploying-contracts
Example
• client.dropTransaction?
Removes a transaction from the mempool.
Example
• client.dumpState?
Serializes the current state (including contracts code, contract’s storage, accounts properties, etc.) into a savable data blob.
Example
• 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
• client.estimateFeesPerGas?
Returns an estimate for the fees per gas for a transaction to be included in the next block.
Example
• client.estimateGas?
Estimates the gas necessary to complete a transaction without submitting it to the network.
- Docs: https://viem.sh/docs/actions/public/estimateGas
- JSON-RPC Methods:
eth_estimateGas
Example
• 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
• client.extend?
• client.getAddresses?
Returns a list of account addresses owned by the wallet or client.
- Docs: https://viem.sh/docs/actions/wallet/getAddresses
- JSON-RPC Methods:
eth_accounts
Example
• client.getAutomine?
Returns the automatic mining status of the node.
Example
• client.getBalance?
Returns the balance of an address in wei.
- Docs: https://viem.sh/docs/actions/public/getBalance
- JSON-RPC Methods:
eth_getBalance
Remarks
You can convert the balance to ether units with formatEther
.
Example
• client.getBlobBaseFee?
Returns the base fee per blob gas in wei.
- Docs: https://viem.sh/docs/actions/public/getBlobBaseFee
- JSON-RPC Methods:
eth_blobBaseFee
Example
• client.getBlock?
Returns information about a block at a block number, hash, or tag.
- Docs: https://viem.sh/docs/actions/public/getBlock
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/fetching-blocks
- JSON-RPC Methods:
- Calls
eth_getBlockByNumber
forblockNumber
&blockTag
. - Calls
eth_getBlockByHash
forblockHash
.
- Calls
Example
• client.getBlockNumber?
Returns the number of the most recent block seen.
- Docs: https://viem.sh/docs/actions/public/getBlockNumber
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/fetching-blocks
- JSON-RPC Methods:
eth_blockNumber
Example
• client.getBlockTransactionCount?
Returns the number of Transactions at a block number, hash, or tag.
- Docs: https://viem.sh/docs/actions/public/getBlockTransactionCount
- JSON-RPC Methods:
- Calls
eth_getBlockTransactionCountByNumber
forblockNumber
&blockTag
. - Calls
eth_getBlockTransactionCountByHash
forblockHash
.
- Calls
Example
• client.getBytecode?
• client.getChainId?: () => Promise
<number
> & () => Promise
<number
>
Returns the chain ID associated with the current network.
- Docs: https://viem.sh/docs/actions/public/getChainId
- JSON-RPC Methods:
eth_chainId
Example
• client.getCode?
Retrieves the bytecode at an address.
- Docs: https://viem.sh/docs/contract/getCode
- JSON-RPC Methods:
eth_getCode
Example
• client.getContractEvents?
Returns a list of event logs emitted by a contract.
- Docs: https://viem.sh/docs/actions/public/getContractEvents
- JSON-RPC Methods:
eth_getLogs
Example
• client.getEip712Domain?
Reads the EIP-712 domain from a contract, based on the ERC-5267 specification.
Example
• client.getEnsAddress?
Gets address for ENS name.
- Docs: https://viem.sh/docs/ens/actions/getEnsAddress
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens
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
• client.getEnsAvatar?
Gets the avatar of an ENS name.
- Docs: https://viem.sh/docs/ens/actions/getEnsAvatar
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens
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
• client.getEnsName?
Gets primary name for specified address.
- Docs: https://viem.sh/docs/ens/actions/getEnsName
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens
Remarks
Calls reverse(bytes)
on ENS Universal Resolver Contract to “reverse resolve” the address to the primary ENS name.
Example
• client.getEnsResolver?
Gets resolver for ENS name.
- Docs: https://viem.sh/docs/ens/actions/getEnsResolver
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens
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
• client.getEnsText?
Gets a text record for specified ENS name.
- Docs: https://viem.sh/docs/ens/actions/getEnsResolver
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens
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
• client.getFeeHistory?
Returns a collection of historical gas information.
- Docs: https://viem.sh/docs/actions/public/getFeeHistory
- JSON-RPC Methods:
eth_feeHistory
Example
• client.getFilterChanges?
Returns a list of logs or hashes based on a Filter since the last time it was called.
- Docs: https://viem.sh/docs/actions/public/getFilterChanges
- JSON-RPC Methods:
eth_getFilterChanges
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
orcreateEventFilter
, 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
• client.getFilterLogs?
Returns a list of event logs since the filter was created.
- Docs: https://viem.sh/docs/actions/public/getFilterLogs
- JSON-RPC Methods:
eth_getFilterLogs
Remarks
getFilterLogs
is only compatible with event filters.
Example
• client.getGasPrice?
Returns the current price of gas (in wei).
- Docs: https://viem.sh/docs/actions/public/getGasPrice
- JSON-RPC Methods:
eth_gasPrice
Example
• client.getLogs?
Returns a list of event logs matching the provided parameters.
- Docs: https://viem.sh/docs/actions/public/getLogs
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/filters-and-logs/event-logs
- JSON-RPC Methods:
eth_getLogs
Example
• client.getPermissions?
Gets the wallets current permissions.
- Docs: https://viem.sh/docs/actions/wallet/getPermissions
- JSON-RPC Methods:
wallet_getPermissions
Example
• client.getProof?
Returns the account and storage values of the specified account including the Merkle-proof.
- Docs: https://viem.sh/docs/actions/public/getProof
- JSON-RPC Methods:
- Calls
eth_getProof
- Calls
Example
• client.getStorageAt?
Returns the value from a storage slot at a given address.
- Docs: https://viem.sh/docs/contract/getStorageAt
- JSON-RPC Methods:
eth_getStorageAt
Example
• client.getTransaction?
Returns information about a Transaction given a hash or block identifier.
- Docs: https://viem.sh/docs/actions/public/getTransaction
- Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/fetching-transactions
- JSON-RPC Methods:
eth_getTransactionByHash
Example
• client.getTransactionConfirmations?
Returns the number of blocks passed (confirmations) since the transaction was processed on a block.
- Docs: https://viem.sh/docs/actions/public/getTransactionConfirmations
- Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/fetching-transactions
- JSON-RPC Methods:
eth_getTransactionConfirmations
Example
• client.getTransactionCount?
Returns the number of Transactions an Account has broadcast / sent.
- Docs: https://viem.sh/docs/actions/public/getTransactionCount
- JSON-RPC Methods:
eth_getTransactionCount
Example
• client.getTransactionReceipt?
Returns the Transaction Receipt given a Transaction hash.
- Docs: https://viem.sh/docs/actions/public/getTransactionReceipt
- Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/fetching-transactions
- JSON-RPC Methods:
eth_getTransactionReceipt
Example
• 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
• 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
• 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
• client.increaseTime?
Jump forward in time by the given amount of time, in seconds.
Example
• 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
• client.key?: string
A key for the client.
• client.loadState?
Adds state previously dumped with dumpState
to the current chain.
Example
• client.mine?
Mine a specified number of blocks.
Example
• client.multicall?
Similar to readContract
, but batches up multiple functions on a contract in a single RPC call via the multicall3
contract.
Example
• 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
• client.readContract?
Calls a read-only function on a contract, and returns the response.
- Docs: https://viem.sh/docs/contract/readContract
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/reading-contracts
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
• client.removeBlockTimestampInterval?
Removes setBlockTimestampInterval
if it exists.
Example
• 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.
- Docs: https://viem.sh/docs/actions/wallet/requestAddresses
- JSON-RPC Methods:
eth_requestAccounts
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
• client.requestPermissions?
Requests permissions for a wallet.
- Docs: https://viem.sh/docs/actions/wallet/requestPermissions
- JSON-RPC Methods:
wallet_requestPermissions
Example
• client.reset?
Resets fork back to its original state.
Example
• client.revert?
Revert the state of the blockchain at the current block.
Example
• client.sendRawTransaction?: (args
) => Promise
<`0x${string}`> & (args
) => Promise
<`0x${string}`>
Sends a signed transaction to the network
- Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction
- JSON-RPC Method:
eth_sendRawTransaction
Param
Client to use
Param
SendRawTransactionParameters
Example
• client.sendTransaction?
Creates, signs, and sends a new transaction to the network.
- Docs: https://viem.sh/docs/actions/wallet/sendTransaction
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/sending-transactions
- JSON-RPC Methods:
- JSON-RPC Accounts:
eth_sendTransaction
- Local Accounts:
eth_sendRawTransaction
- JSON-RPC Accounts:
Examples
• 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
• client.setAutomine?
Enables or disables the automatic mining of new blocks with each new transaction submitted to the network.
Example
• client.setBalance?
Modifies the balance of an account.
Example
• client.setBlockGasLimit?
Sets the block’s gas limit.
Example
• client.setBlockTimestampInterval?
Similar to increaseTime
, but sets a block timestamp interval
. The timestamp of future blocks will be computed as lastBlock_timestamp
+ interval
.
Example
• client.setCode?
Modifies the bytecode stored at an account’s address.
Example
• client.setCoinbase?
Sets the coinbase address to be used in new blocks.
Example
• client.setIntervalMining?
Sets the automatic mining interval (in seconds) of blocks. Setting the interval to 0 will disable automatic mining.
Example
• client.setLoggingEnabled?
Enable or disable logging on the test node network.
Example
• 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
• client.setNextBlockBaseFeePerGas?
Sets the next block’s base fee per gas.
Example
• client.setNextBlockTimestamp?
Sets the next block’s timestamp.
Example
• client.setNonce?
Modifies (overrides) the nonce of an account.
Example
• client.setRpcUrl?
Sets the backend RPC URL.
Example
• client.setStorageAt?
Writes to a slot of an account’s storage.
Example
• client.signMessage?
Calculates an Ethereum-specific signature in EIP-191 format: keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))
.
- Docs: https://viem.sh/docs/actions/wallet/signMessage
- JSON-RPC Methods:
- JSON-RPC Accounts:
personal_sign
- Local Accounts: Signs locally. No JSON-RPC request.
- JSON-RPC Accounts:
With the calculated signature, you can:
- use
verifyMessage
to verify the signature, - use
recoverMessageAddress
to recover the signing address from a signature.
Examples
• client.signTransaction?
Signs a transaction.
- Docs: https://viem.sh/docs/actions/wallet/signTransaction
- JSON-RPC Methods:
- JSON-RPC Accounts:
eth_signTransaction
- Local Accounts: Signs locally. No JSON-RPC request.
- JSON-RPC Accounts:
Examples
• client.signTypedData?
Signs typed data and calculates an Ethereum-specific signature in EIP-191 format: keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))
.
- Docs: https://viem.sh/docs/actions/wallet/signTypedData
- JSON-RPC Methods:
- JSON-RPC Accounts:
eth_signTypedData_v4
- Local Accounts: Signs locally. No JSON-RPC request.
- JSON-RPC Accounts:
Examples
• client.simulateContract?
Simulates/validates a contract interaction. This is useful for retrieving return data and revert reasons of contract write functions.
- Docs: https://viem.sh/docs/contract/simulateContract
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/writing-to-contracts
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
• client.snapshot?
Snapshot the state of the blockchain at the current block.
Example
• client.stopImpersonatingAccount?
Stop impersonating an account after having previously used impersonateAccount
.
Example
• client.switchChain?
Switch the target chain in a wallet.
- Docs: https://viem.sh/docs/actions/wallet/switchChain
- JSON-RPC Methods:
eth_switchEthereumChain
Example
• 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
• 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
In addition to making basic calls, you can also do advanced things like:
- Impersonate accounts via passing in
from
,caller
, ororigin
- Set the call depth via
depth
- Create a trace or access list using
createTrace: true
orcreateAccessList: 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
In addition to making basic calls, you can also do advanced things like:
- Impersonate accounts via passing in
from
,caller
, ororigin
- Set the call depth via
depth
- Create a trace or access list using
createTrace: true
orcreateAccessList: 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 toauto
when using createMemoryClient.
Example
• client.tevmDumpState?: DumpStateHandler
Dumps a JSON serializable state from the EVM. This can be useful for persisting and restoring state between processes.
Example
• 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
- GetAccountParams for options reference.
- GetAccountResult for return values reference.
Example
• client.tevmLoadState?: LoadStateHandler
Loads a JSON serializable state into the EVM. This can be useful for persisting and restoring state between processes.
Example
• 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
• 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
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
- SetAccountParams for options reference.
- SetAccountResult for return values reference.
Example
• 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:
-
JSON-RPC Methods:
eth_uninstallFilter
Example
• 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.
- Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt
- Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/sending-transactions
- JSON-RPC Methods:
- Polls
eth_getTransactionReceipt
on each block until it has been processed. - If a Transaction has been replaced:
- Calls
eth_getBlockByNumber
and extracts the transactions - Checks if one of the Transactions is a replacement
- If so, calls
eth_getTransactionReceipt
.
- Calls
- Polls
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. differentmaxFeePerGas
)cancelled
: The Transaction has been cancelled (e.g.value === 0n
)replaced
: The Transaction has been replaced (e.g. differentvalue
ordata
)
Example
• client.watchAsset?
Adds an EVM chain to the wallet.
- Docs: https://viem.sh/docs/actions/wallet/watchAsset
- JSON-RPC Methods:
eth_switchEthereumChain
Example
• client.watchBlockNumber?
Watches and returns incoming block numbers.
- Docs: https://viem.sh/docs/actions/public/watchBlockNumber
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/watching-blocks
- JSON-RPC Methods:
- When
poll: true
, callseth_blockNumber
on a polling interval. - When
poll: false
& WebSocket Transport, uses a WebSocket subscription viaeth_subscribe
and the"newHeads"
event.
- When
Example
• client.watchBlocks?
Watches and returns information for incoming blocks.
- Docs: https://viem.sh/docs/actions/public/watchBlocks
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/watching-blocks
- JSON-RPC Methods:
- When
poll: true
, callseth_getBlockByNumber
on a polling interval. - When
poll: false
& WebSocket Transport, uses a WebSocket subscription viaeth_subscribe
and the"newHeads"
event.
- When
Example
• 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
• client.watchEvent?
Watches and returns emitted Event Logs.
- Docs: https://viem.sh/docs/actions/public/watchEvent
- JSON-RPC Methods:
- RPC Provider supports
eth_newFilter
:- Calls
eth_newFilter
to create a filter (called on initialize). - On a polling interval, it will call
eth_getFilterChanges
.
- Calls
- RPC Provider does not support
eth_newFilter
:- Calls
eth_getLogs
for each block between the polling interval.
- Calls
- RPC Provider supports
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
• client.watchPendingTransactions?
Watches and returns pending transaction hashes.
- Docs: https://viem.sh/docs/actions/public/watchPendingTransactions
- JSON-RPC Methods:
- When
poll: true
- Calls
eth_newPendingTransactionFilter
to initialize the filter. - Calls
eth_getFilterChanges
on a polling interval.
- Calls
- When
poll: false
& WebSocket Transport, uses a WebSocket subscription viaeth_subscribe
and the"newPendingTransactions"
event.
- When
Remarks
This Action will batch up all the pending transactions found within the pollingInterval
, and invoke them via onTransactions
.
Example
• client.writeContract?
Executes a write function on a contract.
- Docs: https://viem.sh/docs/contract/writeContract
- Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/writing-to-contracts
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
• 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
To interact with the HTTP server you can create a Tevm client