Abstract
Optional
batch?: { multicall?: boolean | { batchSize?: number; wait?: number } }Flags for batch settings.
Optional
multicall?: boolean | { batchSize?: number; wait?: number }Toggle to enable eth_call
multicall aggregation.
Time (in ms) that cached data will remain in memory.
Optional
ccipRead?: CCIP Read configuration.
Chain for the client.
A key for the client.
A name for the client.
Frequency (in ms) for polling enabled actions & events. Defaults to 4_000 milliseconds.
Request function wrapped with friendly error handling
The RPC transport
The type of client.
A unique ID for the client.
Executes a new message call immediately without submitting a transaction to the network.
eth_call
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',
})
Creates an EIP-2930 access list that you can include in a transaction.
eth_createAccessList
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const data = await client.createAccessList({
data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
})
Creates a Filter to listen for new block hashes that can be used with getFilterChanges
.
eth_newBlockFilter
Creates a Filter to retrieve event logs that can be used with getFilterChanges
or getFilterLogs
.
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)']),
})
Creates a Filter
to listen for new events that can be used with getFilterChanges
.
eth_newFilter
Creates a Filter to listen for new pending transaction hashes that can be used with getFilterChanges
.
eth_newPendingTransactionFilter
Estimates the gas required to successfully execute a contract write function call.
Internally, uses a Public Client to call the estimateGas
action with ABI-encoded data
.
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',
})
Estimates the gas necessary to complete a transaction without submitting it to the network.
eth_estimateGas
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'),
})
Returns the balance of an address in wei.
eth_getBalance
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"
Returns the base fee per blob gas in wei.
eth_blobBaseFee
Returns information about a block at a block number, hash, or tag.
eth_getBlockByNumber
for blockNumber
& blockTag
.eth_getBlockByHash
for blockHash
.Returns the number of the most recent block seen.
Returns the number of Transactions at a block number, hash, or tag.
eth_getBlockTransactionCountByNumber
for blockNumber
& blockTag
.eth_getBlockTransactionCountByHash
for blockHash
.Returns the chain ID associated with the current network.
eth_chainId
Retrieves the bytecode at an address.
eth_getCode
Returns a list of event logs emitted by a contract.
eth_getLogs
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'
})
Reads the EIP-712 domain from a contract, based on the ERC-5267 specification.
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: [],
// }
Gets address for ENS name.
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.
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'
Gets the avatar of an ENS name.
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.
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'
Gets primary name for specified address.
Gets resolver for ENS name.
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.
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'
Gets a text record for specified ENS name.
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.
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'
Returns a collection of historical gas information.
eth_feeHistory
Returns an estimate for the fees per gas for a transaction to be included in the next block.
Returns a list of logs or hashes based on a Filter since the last time it was called.
eth_getFilterChanges
A Filter can be created from the following actions:
Depending on the type of filter, the return value will be different:
createContractEventFilter
or createEventFilter
, it returns a list of logs.createPendingTransactionFilter
, it returns a list of transaction hashes.createBlockFilter
, it returns a list of block hashes.// 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 })
Returns a list of event logs since the filter was created.
eth_getFilterLogs
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 })
Returns the current price of gas (in wei).
eth_gasPrice
Returns a list of event logs matching the provided parameters.
eth_getLogs
Returns the account and storage values of the specified account including the Merkle-proof.
eth_getProof
Returns an estimate for the max priority fee per gas (in wei) for a transaction to be included in the next block.
Returns the value from a storage slot at a given address.
eth_getStorageAt
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),
})
Returns information about a Transaction given a hash or block identifier.
Returns the number of blocks passed (confirmations) since the transaction was processed on a block.
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const confirmations = await client.getTransactionConfirmations({
hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',
})
Returns the number of Transactions an Account has broadcast / sent.
eth_getTransactionCount
Returns the Transaction Receipt given a Transaction hash.
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const transactionReceipt = await client.getTransactionReceipt({
hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',
})
Similar to readContract
, but batches up multiple functions on a contract in a single RPC call via the multicall3
contract.
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' }]
Prepares a transaction request for signing.
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,
})
Calls a read-only function on a contract, and returns the response.
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
.
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
Sends a signed transaction to the network
eth_sendRawTransaction
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'
})
Simulates a set of calls on block(s) with optional block and state overrides.
import { createPublicClient, http, parseEther } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const result = await client.simulate({
blocks: [{
blockOverrides: {
number: 69420n,
},
calls: [{
{
account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',
data: '0xdeadbeef',
to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
},
{
account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',
to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
value: parseEther('1'),
},
}],
stateOverrides: [{
address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',
balance: parseEther('10'),
}],
}]
})
Simulates/validates a contract interaction. This is useful for retrieving return data and revert reasons of contract write functions.
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
.
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',
})
Verify that a message was signed by the provided address.
Compatible with Smart Contract Accounts & Externally Owned Accounts via ERC-6492.
Verify that typed data was signed by the provided address.
Destroys a Filter that was created from one of the following Actions:
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.
eth_getTransactionReceipt
on each block until it has been processed.eth_getBlockByNumber
and extracts the transactionseth_getTransactionReceipt
.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
)import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
const transactionReceipt = await client.waitForTransactionReceipt({
hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',
})
Watches and returns incoming block numbers.
poll: true
, calls eth_blockNumber
on a polling interval.poll: false
& WebSocket Transport, uses a WebSocket subscription via eth_subscribe
and the "newHeads"
event.Watches and returns information for incoming blocks.
poll: true
, calls eth_getBlockByNumber
on a polling interval.poll: false
& WebSocket Transport, uses a WebSocket subscription via eth_subscribe
and the "newHeads"
event.Watches and returns emitted contract event logs.
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.
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),
})
Watches and returns emitted Event Logs.
eth_newFilter
:
eth_newFilter
to create a filter (called on initialize).eth_getFilterChanges
.eth_newFilter
:
eth_getLogs
for each block between the polling interval.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.
Watches and returns pending transaction hashes.
poll: true
eth_newPendingTransactionFilter
to initialize the filter.eth_getFilterChanges
on a polling interval.poll: false
& WebSocket Transport, uses a WebSocket subscription via eth_subscribe
and the "newPendingTransactions"
event.This Action will batch up all the pending transactions found within the pollingInterval
, and invoke them via onTransactions
.
The Account of the Client.
Optional
batch?: { multicall?: boolean | { batchSize?: number; wait?: number } }Flags for batch settings.
Optional
multicall?: boolean | { batchSize?: number; wait?: number }Toggle to enable eth_call
multicall aggregation.
Time (in ms) that cached data will remain in memory.
Optional
ccipRead?: CCIP Read configuration.
Chain for the client.
A key for the client.
A name for the client.
Frequency (in ms) for polling enabled actions & events. Defaults to 4_000 milliseconds.
Request function wrapped with friendly error handling
The RPC transport
The type of client.
A unique ID for the client.
Adds an EVM chain to the wallet.
eth_addEthereumChain
Deploys a contract to the network, given bytecode and constructor arguments.
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...',
})
Returns a list of account addresses owned by the wallet or client.
eth_accounts
Returns the chain ID associated with the current network.
eth_chainId
Gets the wallets current permissions.
wallet_getPermissions
Prepares a transaction request for signing.
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,
})
Requests a list of accounts managed by a wallet.
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.
Requests permissions for a wallet.
wallet_requestPermissions
Sends a signed transaction to the network
eth_sendRawTransaction
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'
})
Creates, signs, and sends a new transaction to the network.
eth_sendTransaction
eth_sendRawTransaction
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,
})
Calculates an Ethereum-specific signature in EIP-191 format: keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))
.
personal_sign
With the calculated signature, you can:
verifyMessage
to verify the signature,recoverMessageAddress
to recover the signing address from a signature.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',
})
Signs a transaction.
eth_signTransaction
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)
Signs typed data and calculates an Ethereum-specific signature in EIP-191 format: keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))
.
eth_signTypedData_v4
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!',
},
})
Switch the target chain in a wallet.
eth_switchEthereumChain
Adds an EVM chain to the wallet.
eth_switchEthereumChain
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',
},
})
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.
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)
Retrieves campaigns associated with a specific pool address
The address of the pool to get campaigns for
Chain ID where the pool exists
Promise resolving to an array of campaigns associated with the pool
Retrieves claim proofs for a user that can be used to claim rewards
Address of the user to get proofs for
Chain ID where the claims exist
Optional
campaignId: numberOptional campaign ID to filter claims
Promise resolving to claim proof data with pagination support
Retrieves historical claim data for a specific pool
Chain ID where the pool exists
Address or identifier of the pool
Optional
user: `0x${string}`Optional user address to filter claims
Promise resolving to paginated claim history data
Gets a comprehensive summary of a user's reward status
Address of the user
Chain ID to check rewards on
Optional
campaignId: numberOptional campaign ID to filter rewards
Number of decimals for formatting (default: 18)
Promise resolving to reward summary with both native and formatted values
Claims rewards from the smart rewarder contract
Parameters required for claiming rewards
Promise resolving to transaction hash if successful
This method handles the low-level interaction with the smart contract. For a higher-level interface, consider using claimCampaignRewards instead.
// Get claim proofs
const claimProofs = await smartRewards.getClaimProofs(userAddress, chainId, campaignId);
// Get smart rewarder contract
const rewarders = await smartRewards.getSmartRewarderContracts();
const rewarder = rewarders.data?.find(r => r.chainId === chainId);
if (claimProofs.data && rewarder) {
// Prepare claim data
const claimData = smartRewards.prepareClaimData(claimProofs.data);
claimData.rewarderAddress = rewarder.address as Address;
// Claim rewards
const tx = await smartRewards.claimReward(claimData);
}
Helper function to prepare claim data from claim proofs
The claim proofs response from getClaimProofs
ClaimRewardParams object ready for use with claimReward
This helper function transforms the claim proofs into the format required by the smart contract. Note that the returned object's rewarderAddress is empty and must be set before using with claimReward.
// Get claim proofs and rewarder contract
const proofs = await smartRewards.getClaimProofs(userAddress, chainId);
const rewarders = await smartRewards.getSmartRewarderContracts();
const rewarder = rewarders.data?.find(r => r.chainId === chainId);
if (proofs.data && rewarder) {
// Prepare the claim data
const claimData = smartRewards.prepareClaimData(proofs.data);
// Set the rewarder address (required)
claimData.rewarderAddress = rewarder.address as Address;
// Now the data is ready for claiming
const tx = await smartRewards.claimReward(claimData);
}
Convenience function to handle the entire claim process
The address of the user claiming rewards
The chain ID where the campaign exists
Optional
campaignId: numberOptional campaign ID to filter claims
Transaction hash if successful, or error details if failed
Prepares the claim rewards campaign object with all necessary data for contract interaction
The address of the user claiming rewards
The chain ID where the campaign exists
Optional
campaignId: numberOptional campaign ID to filter claims
Promise resolving to an object containing all necessary data for claiming rewards
// Get the prepared claim data
const claimData = await smartRewards.prepareClaimRewardsCampaign(userAddress, chainId, campaignId);
if (claimData.success) {
// Use the data with your own contract interaction methods
const { address, abi, functionName, args } = claimData.data;
// Execute the contract call using your preferred method
}
The Account of the Client.