# Table of Contents - [decodeAbiParameters · Viem](#decodeabiparameters-viem) - [parseAbi · Viem](#parseabi-viem) - [parseAbiParameter · Viem](#parseabiparameter-viem) - [getAbiItem · Viem](#getabiitem-viem) - [encodePacked · Viem](#encodepacked-viem) - [parseAbiItem · Viem](#parseabiitem-viem) - [parseAbiParameters · Viem](#parseabiparameters-viem) - [encodeAbiParameters · Viem](#encodeabiparameters-viem) - [privateKeyToAccount · Viem](#privatekeytoaccount-viem) - [JSON-RPC Account · Viem](#json-rpc-account-viem) - [createNonceManager · Viem](#createnoncemanager-viem) - [signMessage (Local Account) · Viem](#signmessage-local-account-viem) - [toAccount · Viem](#toaccount-viem) - [mnemonicToAccount · Viem](#mnemonictoaccount-viem) - [hdKeyToAccount · Viem](#hdkeytoaccount-viem) - [createAccessList · Viem](#createaccesslist-viem) - [Local Accounts (Private Key, Mnemonic, etc) · Viem](#local-accounts-private-key-mnemonic-etc-viem) - [signTypedData (Local Account) · Viem](#signtypeddata-local-account-viem) - [signTransaction (Local Account) · Viem](#signtransaction-local-account-viem) - [createBlockFilter · Viem](#createblockfilter-viem) - [createPendingTransactionFilter · Viem](#creatependingtransactionfilter-viem) - [getBlobBaseFee · Viem](#getblobbasefee-viem) - [estimateFeesPerGas · Viem](#estimatefeespergas-viem) - [getBalance · Viem](#getbalance-viem) - [estimateMaxPriorityFeePerGas · Viem](#estimatemaxpriorityfeepergas-viem) - [verifyHash · Viem](#verifyhash-viem) - [getChainId · Viem](#getchainid-viem) - [getBlockNumber · Viem](#getblocknumber-viem) - [getBlock · Viem](#getblock-viem) - [getBlockTransactionCount · Viem](#getblocktransactioncount-viem) - [getGasPrice · Viem](#getgasprice-viem) - [getFeeHistory · Viem](#getfeehistory-viem) - [getFilterLogs · Viem](#getfilterlogs-viem) - [getEip712Domain · Viem](#geteip712domain-viem) - [Introduction to Public Actions · Viem](#introduction-to-public-actions-viem) - [Introduction to Clients & Transports · Viem](#introduction-to-clients-transports-viem) - [dumpState · Viem](#dumpstate-viem) - [dropTransaction · Viem](#droptransaction-viem) - [getTxpoolContent · Viem](#gettxpoolcontent-viem) - [Chains · Viem](#chains-viem) - [Fees · Viem](#fees-viem) - [Platform Compatibility · Viem](#platform-compatibility-viem) - [getAutomine · Viem](#getautomine-viem) - [getTxpoolStatus · Viem](#gettxpoolstatus-viem) - [getTransactionReceipt · Viem](#gettransactionreceipt-viem) - [getTransactionCount · Viem](#gettransactioncount-viem) - [Introduction to Test Actions · Viem](#introduction-to-test-actions-viem) - [loadState · Viem](#loadstate-viem) - [Introduction to Wallet Actions · Viem](#introduction-to-wallet-actions-viem) - [getProof · Viem](#getproof-viem) - [increaseTime · Viem](#increasetime-viem) - [removeBlockTimestampInterval · Viem](#removeblocktimestampinterval-viem) - [getAddresses · Viem](#getaddresses-viem) - [requestPermissions · Viem](#requestpermissions-viem) - [ZKsync · Viem](#zksync-viem) - [getTransactionConfirmations · Viem](#gettransactionconfirmations-viem) - [impersonateAccount · Viem](#impersonateaccount-viem) - [mine · Viem](#mine-viem) - [getCallsStatus · Viem](#getcallsstatus-viem) - [requestAddresses · Viem](#requestaddresses-viem) - [uninstallFilter · Viem](#uninstallfilter-viem) - [reset · Viem](#reset-viem) - [estimateGas · Viem](#estimategas-viem) - [getTransaction · Viem](#gettransaction-viem) - [setBalance · Viem](#setbalance-viem) - [revert · Viem](#revert-viem) - [setBlockGasLimit · Viem](#setblockgaslimit-viem) - [setAutomine · Viem](#setautomine-viem) - [getCapabilities · Viem](#getcapabilities-viem) - [addChain · Viem](#addchain-viem) - [setBlockTimestampInterval · Viem](#setblocktimestampinterval-viem) - [setCode · Viem](#setcode-viem) - [sendRawTransactionSync · Viem](#sendrawtransactionsync-viem) - [Serializers · Viem](#serializers-viem) - [snapshot · Viem](#snapshot-viem) - [IPC Transport · Viem](#ipc-transport-viem) - [inspectTxpool · Viem](#inspecttxpool-viem) - [setLoggingEnabled · Viem](#setloggingenabled-viem) - [Why Viem](#why-viem) - [showCallsStatus · Viem](#showcallsstatus-viem) - [getFilterChanges · Viem](#getfilterchanges-viem) - [setNextBlockTimestamp · Viem](#setnextblocktimestamp-viem) - [setRpcUrl · Viem](#setrpcurl-viem) - [setCoinbase · Viem](#setcoinbase-viem) - [sendUnsignedTransaction · Viem](#sendunsignedtransaction-viem) - [setNextBlockBaseFeePerGas · Viem](#setnextblockbasefeepergas-viem) - [switchChain · Viem](#switchchain-viem) - [WebSocket Transport · Viem](#websocket-transport-viem) - [Installation · Viem](#installation-viem) - [setIntervalMining · Viem](#setintervalmining-viem) - [stopImpersonatingAccount · Viem](#stopimpersonatingaccount-viem) - [setMinGasPrice · Viem](#setmingasprice-viem) - [setNonce · Viem](#setnonce-viem) - [Celo · Viem](#celo-viem) - [fromBase58 · Viem](#frombase58-viem) - [fromBase64 · Viem](#frombase64-viem) - [EIP-7702 Overview · Viem](#eip-7702-overview-viem) - [labelhash · Viem](#labelhash-viem) - [Formatters · Viem](#formatters-viem) - [Error Handling · Viem](#error-handling-viem) - [defineKzg · Viem](#definekzg-viem) - [waitForTransactionReceipt · Viem](#waitfortransactionreceipt-viem) - [namehash · Viem](#namehash-viem) - [generateSiweNonce · Viem](#generatesiwenonce-viem) - [Types · Viem](#types-viem) - [Frequently Asked Questions · Viem](#frequently-asked-questions-viem) - [HTTP Transport · Viem](#http-transport-viem) - [toBase64 · Viem](#tobase64-viem) - [getEnsResolver · Viem](#getensresolver-viem) - [hashAuthorization · Viem](#hashauthorization-viem) - [Terms · Viem](#terms-viem) - [Getting Started · Viem](#getting-started-viem) - [Custom Transport · Viem](#custom-transport-viem) - [normalize · Viem](#normalize-viem) - [getEnsAvatar · Viem](#getensavatar-viem) - [parseSiweMessage · Viem](#parsesiwemessage-viem) - [getEnsText · Viem](#getenstext-viem) - [getEnsName · Viem](#getensname-viem) - [validateSiweMessage · Viem](#validatesiwemessage-viem) - [Fallback Transport · Viem](#fallback-transport-viem) - [Blob Transactions · Viem](#blob-transactions-viem) - [recoverAuthorizationAddress · Viem](#recoverauthorizationaddress-viem) - [Test Client · Viem](#test-client-viem) - [verifyMessage · Viem](#verifymessage-viem) - [getEnsAddress · Viem](#getensaddress-viem) - [getPermissions · Viem](#getpermissions-viem) - [Build your own Client · Viem](#build-your-own-client-viem) - [toBase58 · Viem](#tobase58-viem) - [Errors · Viem](#errors-viem) - [verifyAuthorization · Viem](#verifyauthorization-viem) - [decodeErrorResult · Viem](#decodeerrorresult-viem) - [watchBlockNumber · Viem](#watchblocknumber-viem) - [getCode · Viem](#getcode-viem) - [waitForCallsStatus · Viem](#waitforcallsstatus-viem) - [createEventFilter · Viem](#createeventfilter-viem) - [prepareAuthorization · Viem](#prepareauthorization-viem) - [signMessage · Viem](#signmessage-viem) - [decodeDeployData · Viem](#decodedeploydata-viem) - [encodeDeployData · Viem](#encodedeploydata-viem) - [deployContract · Viem](#deploycontract-viem) - [getStorageAt · Viem](#getstorageat-viem) - [watchPendingTransactions · Viem](#watchpendingtransactions-viem) - [decodeFunctionData · Viem](#decodefunctiondata-viem) - [encodeEventTopics · Viem](#encodeeventtopics-viem) - [encodeErrorResult · Viem](#encodeerrorresult-viem) - [decodeFunctionResult · Viem](#decodefunctionresult-viem) - [encodeFunctionData · Viem](#encodefunctiondata-viem) - [verifySiweMessage · Viem](#verifysiwemessage-viem) - [setStorageAt · Viem](#setstorageat-viem) - [decodeEventLog · Viem](#decodeeventlog-viem) - [encodeFunctionResult · Viem](#encodefunctionresult-viem) - [signAuthorization · Viem](#signauthorization-viem) - [Migration Guide · Viem](#migration-guide-viem) - [Contract Instances · Viem](#contract-instances-viem) - [call · Viem](#call-viem) - [getLogs · Viem](#getlogs-viem) - [createContractEventFilter · Viem](#createcontracteventfilter-viem) - [multicall · Viem](#multicall-viem) - [watchContractEvent · Viem](#watchcontractevent-viem) - [sendCallsSync · Viem](#sendcallssync-viem) - [watchAsset · Viem](#watchasset-viem) - [watchBlocks · Viem](#watchblocks-viem) - [estimateContractGas · Viem](#estimatecontractgas-viem) - [getContractEvents · Viem](#getcontractevents-viem) - [createSiweMessage · Viem](#createsiwemessage-viem) - [sendRawTransaction · Viem](#sendrawtransaction-viem) - [readContract · Viem](#readcontract-viem) - [TypeScript · Viem](#typescript-viem) - [parseEventLogs · Viem](#parseeventlogs-viem) - [writeContract · Viem](#writecontract-viem) - [writeContractSync · Viem](#writecontractsync-viem) - [sendTransactionSync · Viem](#sendtransactionsync-viem) - [signTransaction · Viem](#signtransaction-viem) - [sendTransaction · Viem](#sendtransaction-viem) - [Contract Writes with EIP-7702 · Viem](#contract-writes-with-eip-7702-viem) - [Sending Transactions with EIP-7702 · Viem](#sending-transactions-with-eip-7702-viem) - [Wallet Client · Viem](#wallet-client-viem) - [Public Client · Viem](#public-client-viem) - [simulateBlocks · Viem](#simulateblocks-viem) - [sendCalls · Viem](#sendcalls-viem) - [signTypedData · Viem](#signtypeddata-viem) - [simulateContract · Viem](#simulatecontract-viem) - [concat · Viem](#concat-viem) - [formatUnits · Viem](#formatunits-viem) - [formatGwei · Viem](#formatgwei-viem) - [compactSignatureToSignature · Viem](#compactsignaturetosignature-viem) - [extractChain · Viem](#extractchain-viem) - [parseEther · Viem](#parseether-viem) - [isAddressEqual · Viem](#isaddressequal-viem) - [fromRlp · Viem](#fromrlp-viem) - [hashMessage · Viem](#hashmessage-viem) - [formatEther · Viem](#formatether-viem) - [isBytes · Viem](#isbytes-viem) - [fromBlobs · Viem](#fromblobs-viem) - [parseGwei · Viem](#parsegwei-viem) - [pad · Viem](#pad-viem) - [parseErc6492Signature · Viem](#parseerc6492signature-viem) - [recoverAddress · Viem](#recoveraddress-viem) - [isHash · Viem](#ishash-viem) - [isAddress · Viem](#isaddress-viem) - [keccak256 · Viem](#keccak256-viem) - [getAddress · Viem](#getaddress-viem) - [parseUnits · Viem](#parseunits-viem) - [isErc6492Signature · Viem](#iserc6492signature-viem) - [isHex · Viem](#ishex-viem) - [recoverPublicKey · Viem](#recoverpublickey-viem) - [parseTransaction · Viem](#parsetransaction-viem) - [parseSignature · Viem](#parsesignature-viem) - [parseCompactSignature · Viem](#parsecompactsignature-viem) - [size · Viem](#size-viem) --- # decodeAbiParameters · Viem [Skip to content](https://viem.sh/docs/abi/decodeAbiParameters#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... Ctrl K On this page Copy page for AI decodeAbiParameters =================== Decodes ABI encoded data. Decodes ABI encoded data using the [ABI specification](https://solidity.readthedocs.io/en/latest/abi-spec) , given a set of ABI parameters (`inputs`/`outputs`) and the encoded ABI data. The `decodeAbiParameters` function is used by the other contract decoding utilities (ie. `decodeFunctionData`, `decodeEventLog`, etc). Install[](https://viem.sh/docs/abi/decodeAbiParameters#install) ---------------------------------------------------------------- import { decodeAbiParameters } from 'viem' Usage[](https://viem.sh/docs/abi/decodeAbiParameters#usage) ------------------------------------------------------------ The `decodeAbiParameters` function takes in two parameters: * a set of ABI Parameters (`params`), that can be in the shape of the `inputs` or `outputs` attribute of an ABI Item. * the ABI encoded data (`data`) that correspond to the given `params`. import { decodeAbiParameters } from 'viem' const values = decodeAbiParameters( [\ { name: 'x', type: 'string' },\ { name: 'y', type: 'uint' },\ { name: 'z', type: 'bool' }\ ], '0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000', ) // ['wagmi', 420n, true] ### Human Readable[](https://viem.sh/docs/abi/decodeAbiParameters#human-readable) You can also pass in [Human Readable](https://viem.sh/docs/glossary/terms#human-readable-abi) parameters with the [`parseAbiParameters` utility](https://viem.sh/docs/abi/parseAbiParameters) . import { decodeAbiParameters, parseAbiParameters } from 'viem' const values = decodeAbiParameters( parseAbiParameters('string x, uint y, bool z'), '0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000' ) // ['wagmi', 420n, true] Return Value[](https://viem.sh/docs/abi/decodeAbiParameters#return-value) -------------------------------------------------------------------------- The decoded data. Type is inferred from the ABI. Parameters[](https://viem.sh/docs/abi/decodeAbiParameters#parameters) ---------------------------------------------------------------------- ### params[](https://viem.sh/docs/abi/decodeAbiParameters#params) * **Type**: `[AbiParameter[]](https://viem.sh/docs/glossary/types#abiparameter) ` The set of ABI parameters to decode against `data`, in the shape of the `inputs` or `outputs` attribute of an ABI event/function. These parameters must include valid [ABI types](https://docs.soliditylang.org/en/develop/abi-spec#types) . const values = decodeAbiParameters( [{ name: 'x', type: 'uint32' }], '0x0000000000000000000000000000000000000000000000000000000000010f2c', ) ### data[](https://viem.sh/docs/abi/decodeAbiParameters#data) * **Type:** `[Hex](https://viem.sh/docs/glossary/types#hex) ` The ABI encoded data. const values = decodeAbiParameters( [{ name: 'x', type: 'uint32' }], '0x0000000000000000000000000000000000000000000000000000000000010f2c', ) More Examples[](https://viem.sh/docs/abi/decodeAbiParameters#more-examples) ---------------------------------------------------------------------------- ### Simple struct[](https://viem.sh/docs/abi/decodeAbiParameters#simple-struct) example.tsabi.tsExample.sol import { abi } from './abi' const values = decodeAbiParameters( abi[0].outputs, '0x00000000000000000000000000000000000000000000000000000000000001a40000000000000000000000000000000000000000000000000000000000000001000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac', ) // { x: 420n, y: true, z: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC' } ### Simple bytes[](https://viem.sh/docs/abi/decodeAbiParameters#simple-bytes) A simple `bytes` that contains an ABI-encoded `uint256` value. example.tsExample.sol const values = decodeAbiParameters( [\ { name: "response", type: "bytes" },\ ], '0x' + '0000000000000000000000000000000000000000000000000000000000000020' + // offset pointer '0000000000000000000000000000000000000000000000000000000000000020' + // length '0000000000000000000000000000000000000000000000000000000000000001', // data ) // 0x0000000000000000000000000000000000000000000000000000000000000001 [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/abi/decodeAbiParameters.md) Last updated: 02/15/2026, 09:17 PM Copy page for AI Ask AI... Ctrl I --- # parseAbi · Viem [Skip to content](https://viem.sh/docs/abi/parseAbi#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... Ctrl K On this page Copy page for AI parseAbi ======== Parses human-readable ABI into JSON `[Abi](https://viem.sh/docs/glossary/types#abi) `. Re-exported from [ABIType](https://abitype.dev/api/human#parseabi-1) . Import[](https://viem.sh/docs/abi/parseAbi#import) --------------------------------------------------- import { parseAbi } from 'viem' Usage[](https://viem.sh/docs/abi/parseAbi#usage) ------------------------------------------------- import { parseAbi } from 'viem' const abi = parseAbi([\ // ^? const abi: readonly [{ name: "balanceOf"; type: "function"; stateMutability:...\ 'function balanceOf(address owner) view returns (uint256)',\ 'event Transfer(address indexed from, address indexed to, uint256 amount)',\ ])\ \ Returns[](https://viem.sh/docs/abi/parseAbi#returns)\ \ -----------------------------------------------------\ \ `[Abi](https://viem.sh/docs/glossary/types#abi) `\ \ The JSON ABI.\ \ Parameters[](https://viem.sh/docs/abi/parseAbi#parameters)\ \ -----------------------------------------------------------\ \ ### signatures[](https://viem.sh/docs/abi/parseAbi#signatures)\ \ * **Type:** `string[]`\ \ Human-readable ABI.\ \ import { parseAbi } from 'viem'\ \ const abi = parseAbi([\ // ^? const abi: readonly [{ name: "balanceOf"; type: "function"; stateMutability:...\ 'function balanceOf(address owner) view returns (uint256)',\ 'event Transfer(address indexed from, address indexed to, uint256 amount)',\ ])\ \ [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/abi/parseAbi.md)\ \ Last updated: 02/15/2026, 09:17 PM\ \ Copy page for AI\ \ Ask AI...\ \ Ctrl\ \ I --- # parseAbiParameter · Viem [Skip to content](https://viem.sh/docs/abi/parseAbiParameter#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K parseAbiParameter ================= Parses human-readable ABI parameter into `[AbiParameter](https://viem.sh/docs/glossary/types#abiparameter) `. Re-exported from [ABIType](https://abitype.dev/api/human#parseabiparameter-1) . Import[](https://viem.sh/docs/abi/parseAbiParameter#import) ------------------------------------------------------------ import { parseAbiParameter } from 'viem' Usage[](https://viem.sh/docs/abi/parseAbiParameter#usage) ---------------------------------------------------------- import { parseAbiParameter } from 'viem' const abiParameter = parseAbiParameter('address from') // ^? const abiParameter: { type: "address"; name: "from"; } Returns[](https://viem.sh/docs/abi/parseAbiParameter#returns) -------------------------------------------------------------- `[Abi](https://viem.sh/docs/glossary/types#abi) ` Parsed ABI parameter. Parameters[](https://viem.sh/docs/abi/parseAbiParameter#parameters) -------------------------------------------------------------------- ### signature[](https://viem.sh/docs/abi/parseAbiParameter#signature) * **Type:** `string | string[]` Human-Readable ABI parameter. import { parseAbiParameter } from 'viem' const abiParameter = parseAbiParameter([\ // ^? const abiParameter: { type: "tuple"; components: [{ type: "string"; name:...\ 'Baz bar',\ 'struct Baz { string name; }',\ ])\ \ [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/abi/parseAbiParameter.md)\ \ Copy page for AI\ \ Ask AI...\ \ ⌘\ \ I --- # getAbiItem · Viem [Skip to content](https://viem.sh/docs/abi/getAbiItem#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getAbiItem ========== Retrieves an item from the ABI. Import[](https://viem.sh/docs/abi/getAbiItem#import) ----------------------------------------------------- import { getAbiItem } from 'viem' Usage[](https://viem.sh/docs/abi/getAbiItem#usage) --------------------------------------------------- import { getAbiItem } from 'viem' const encodedData = getAbiItem({ abi: [\ { \ name: 'x', \ type: 'function', \ inputs: [{ type: 'uint256' }], \ outputs: [],\ stateMutability: 'payable'\ },\ { \ name: 'y', \ type: 'event', \ inputs: [{ type: 'address' }], \ outputs: [{ type: 'uint256' }],\ stateMutability: 'view'\ },\ { \ name: 'z', \ type: 'function', \ inputs: [{ type: 'string' }],\ outputs: [{ type: 'uint256' }],\ stateMutability: 'view'\ }\ ], name: 'y', }) /** * { * name: 'y', * type: 'event', * inputs: [{ type: 'address' }], * outputs: [{ type: 'uint256' }], * stateMutability: 'view' * } */ Returns[](https://viem.sh/docs/abi/getAbiItem#returns) ------------------------------------------------------- `AbiItem` The ABI item. Parameters[](https://viem.sh/docs/abi/getAbiItem#parameters) ------------------------------------------------------------- ### abi[](https://viem.sh/docs/abi/getAbiItem#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const encodedData = getAbiItem({ abi: [...], name: 'x', }) ### name[](https://viem.sh/docs/abi/getAbiItem#name) * **Type:** `string` Name of the ABI item to extract. const encodedData = getAbiItem({ abi: [...], name: 'x', }) You can also provide the ABI item's 4byte selector: const encodedData = getAbiItem({ abi: [...], name: '0x70a08231', }) ### args (optional)[](https://viem.sh/docs/abi/getAbiItem#args-optional) * **Type:** Inferred. Optional arguments to identify function overrides. const encodedData = getAbiItem({ abi: [...], name: 'y', args: ['0x0000000000000000000000000000000000000000'], }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/abi/getAbiItem.md) Copy page for AI Ask AI... ⌘ I --- # encodePacked · Viem [Skip to content](https://viem.sh/docs/abi/encodePacked#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K encodePacked ============ Generates [ABI non-standard packed encoded data](https://docs.soliditylang.org/en/v0.8.18/abi-spec#non-standard-packed-mode) given a set of solidity types compatible with packed encoding. Import[](https://viem.sh/docs/abi/encodePacked#import) ------------------------------------------------------- import { encodePacked } from 'viem' Usage[](https://viem.sh/docs/abi/encodePacked#usage) ----------------------------------------------------- encodePacked( ['address', 'string', 'bytes16[]'], [\ '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', \ 'hello world',\ ['0xdeadbeefdeadbeefdeadbeefdeadbeef', '0xcafebabecafebabecafebabecafebabe']\ ] ) // 0xd8da6bf26964af9d7eed9e03e53415d37aa9604568656c6c6f20776f726c64deadbeefdeadbeefdeadbeefdeadbeef00000000000000000000000000000000cafebabecafebabecafebabecafebabe00000000000000000000000000000000 Returns[](https://viem.sh/docs/abi/encodePacked#returns) --------------------------------------------------------- `[Hex](https://viem.sh/docs/glossary/types#hex) ` The encoded packed data. Parameters[](https://viem.sh/docs/abi/encodePacked#parameters) --------------------------------------------------------------- ### types[](https://viem.sh/docs/abi/encodePacked#types) * **Type**: `PackedAbiType[]` Set of ABI types to pack encode. encodePacked( ['address', 'string', 'bytes16[]'], [\ '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', \ 'hello world',\ ['0xdeadbeefdeadbeefdeadbeefdeadbeef', '0xcafebabecafebabecafebabecafebabe']\ ] ) ### values[](https://viem.sh/docs/abi/encodePacked#values) * **Type**: `[AbiParametersToPrimitiveTypes](https://viem.sh/docs/glossary/terms#abiparameterstoprimitivetypes) ` The set of primitive values that correspond to the ABI types defined in `types`. encodePacked( ['address', 'string', 'bytes16[]'], [ \ '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', \ 'hello world',\ ['0xdeadbeefdeadbeefdeadbeefdeadbeef', '0xcafebabecafebabecafebabecafebabe']\ ] ) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/abi/encodePacked.md) Copy page for AI Ask AI... ⌘ I --- # parseAbiItem · Viem [Skip to content](https://viem.sh/docs/abi/parseAbiItem#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K parseAbiItem ============ Parses human-readable ABI item (e.g. error, event, function) into ABI item. Re-exported from [ABIType](https://abitype.dev/api/human#parseabiitem-1) . Import[](https://viem.sh/docs/abi/parseAbiItem#import) ------------------------------------------------------- import { parseAbiItem } from 'viem' Usage[](https://viem.sh/docs/abi/parseAbiItem#usage) ----------------------------------------------------- import { parseAbiItem } from 'viem' const abiItem = parseAbiItem( // ^? const abiItem: { name: "balanceOf"; type: "function"; stateMutability: "view";... 'function balanceOf(address owner) view returns (uint256)', ) Returns[](https://viem.sh/docs/abi/parseAbiItem#returns) --------------------------------------------------------- `[Abi](https://viem.sh/docs/glossary/types#abi) ` Parsed ABI item. Parameters[](https://viem.sh/docs/abi/parseAbiItem#parameters) --------------------------------------------------------------- ### signatures[](https://viem.sh/docs/abi/parseAbiItem#signatures) * **Type:** `string[]` Human-Readable ABI item. import { parseAbiItem } from 'viem' const abiItem = parseAbiItem([\ // ^? const abiItem: { name: "foo"; type: "function"; stateMutability: "view"; inputs:...\ 'function foo(Baz bar) view returns (string)',\ 'struct Baz { string name; }',\ ]) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/abi/parseAbiItem.md) Copy page for AI Ask AI... ⌘ I --- # parseAbiParameters · Viem [Skip to content](https://viem.sh/docs/abi/parseAbiParameters#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K parseAbiParameters ================== Parses human-readable ABI parameters into [`AbiParameter`s](https://viem.sh/docs/glossary/types#abiparameter) . Re-exported from [ABIType](https://abitype.dev/api/human#parseabiparameters-1) . Import[](https://viem.sh/docs/abi/parseAbiParameters#import) ------------------------------------------------------------- import { parseAbiParameters } from 'viem' Usage[](https://viem.sh/docs/abi/parseAbiParameters#usage) ----------------------------------------------------------- import { parseAbiParameters } from 'viem' const abiParameters = parseAbiParameters( // ^? const abiParameters: [{ type: "address"; name: "from"; }, { type: "address";...\ 'address from, address to, uint256 amount',\ )\ \ Returns[](https://viem.sh/docs/abi/parseAbiParameters#returns)\ \ ---------------------------------------------------------------\ \ `[Abi](https://viem.sh/docs/glossary/types#abi) `\ \ Parsed ABI parameters.\ \ Parameters[](https://viem.sh/docs/abi/parseAbiParameters#parameters)\ \ ---------------------------------------------------------------------\ \ ### params[](https://viem.sh/docs/abi/parseAbiParameters#params)\ \ * **Type:** `string | string[]`\ \ Human-Readable ABI parameters.\ \ import { parseAbiParameters } from 'viem'\ \ const abiParameters = parseAbiParameters([\ // ^? const abiParameters: [{ type: "tuple"; components: [{ type: "string"; name:...\ 'Baz bar',\ 'struct Baz { string name; }',\ ])\ \ [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/abi/parseAbiParameters.md)\ \ Copy page for AI\ \ Ask AI...\ \ ⌘\ \ I --- # encodeAbiParameters · Viem [Skip to content](https://viem.sh/docs/abi/encodeAbiParameters#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K encodeAbiParameters =================== Generates ABI encoded data using the [ABI specification](https://docs.soliditylang.org/en/latest/abi-spec.html) , given a set of ABI parameters (`inputs`/`outputs`) and their corresponding values. The `encodeAbiParameters` function is used by the other contract encoding utilities (ie. `encodeFunctionData`, `encodeEventTopics`, etc). Import[](https://viem.sh/docs/abi/encodeAbiParameters#import) -------------------------------------------------------------- import { encodeAbiParameters } from 'viem' Usage[](https://viem.sh/docs/abi/encodeAbiParameters#usage) ------------------------------------------------------------ The `encodeAbiParameters` function takes in two parameters: * a set of ABI Parameters (`params`), that can be in the shape of the `inputs` or `outputs` attribute of an ABI Item. * a set of values (`values`) that correspond to the given `params`. import { encodeAbiParameters } from 'viem' const encodedData = encodeAbiParameters( [\ { name: 'x', type: 'string' },\ { name: 'y', type: 'uint' },\ { name: 'z', type: 'bool' }\ ], ['wagmi', 420n, true] ) // 0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000 ### Human Readable[](https://viem.sh/docs/abi/encodeAbiParameters#human-readable) You can also pass in [Human Readable](https://viem.sh/docs/glossary/terms#human-readable-abi) parameters with the [`parseAbiParameters` utility](https://viem.sh/docs/abi/parseAbiParameters) . import { encodeAbiParameters, parseAbiParameters } from 'viem' const encodedData = encodeAbiParameters( parseAbiParameters('string x, uint y, bool z'), ['wagmi', 420n, true] ) // 0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000 Returns[](https://viem.sh/docs/abi/encodeAbiParameters#returns) ---------------------------------------------------------------- `[Hex](https://viem.sh/docs/glossary/types#hex) ` The ABI encoded data. Parameters[](https://viem.sh/docs/abi/encodeAbiParameters#parameters) ---------------------------------------------------------------------- ### params[](https://viem.sh/docs/abi/encodeAbiParameters#params) * **Type**: `[AbiParameter[]](https://viem.sh/docs/glossary/terms#abiparameter) ` The set of ABI parameters to encode, in the shape of the `inputs` or `outputs` attribute of an ABI event/function. These parameters must include valid [ABI types](https://docs.soliditylang.org/en/develop/abi-spec#types) . encodeAbiParameters( [{ name: 'x', type: 'uint32' }], [69420] ) ### values[](https://viem.sh/docs/abi/encodeAbiParameters#values) * **Type**: `[AbiParametersToPrimitiveTypes](https://viem.sh/docs/glossary/terms#abiparameterstoprimitivetypes) ` The set of primitive values that correspond to the ABI types defined in `params`. encodeAbiParameters( [{ name: 'x', type: 'uint32' }], [69420] ) More Examples[](https://viem.sh/docs/abi/encodeAbiParameters#more-examples) ---------------------------------------------------------------------------- ### Simple struct[](https://viem.sh/docs/abi/encodeAbiParameters#simple-struct) example.tsabi.tsExample.sol import { abi } from './abi' const encodedData = encodeAbiParameters( abi[0].inputs, [{\ x: 420n,\ y: true,\ z: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ }], ) // 0x00000000000000000000000000000000000000000000000000000000000001a40000000000000000000000000000000000000000000000000000000000000001000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/abi/encodeAbiParameters.md) Copy page for AI Ask AI... ⌘ I --- # privateKeyToAccount · Viem [Skip to content](https://viem.sh/docs/accounts/local/privateKeyToAccount#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K privateKeyToAccount =================== A function to create a Private Key Account. A Private Key Account is an interface that has the ability to sign transactions and messages with a given private key. Import[](https://viem.sh/docs/accounts/local/privateKeyToAccount#import) ------------------------------------------------------------------------- import { privateKeyToAccount } from 'viem/accounts' Usage[](https://viem.sh/docs/accounts/local/privateKeyToAccount#usage) ----------------------------------------------------------------------- To initialize a Private Key Account, you will need to pass a private key to `privateKeyToAccount`: import { createWalletClient, http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' const account = privateKeyToAccount('0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80') const client = createWalletClient({ account, chain: mainnet, transport: http() }) > Note: the above is a valid private key, but it is not a "real" private key. Please do not use it for anything other than testing. ### Generating Private Keys[](https://viem.sh/docs/accounts/local/privateKeyToAccount#generating-private-keys) You can generate a random private key using the `generatePrivateKey` function: import { generatePrivateKey } from 'viem/accounts' const privateKey = generatePrivateKey() Parameters[](https://viem.sh/docs/accounts/local/privateKeyToAccount#parameters) --------------------------------------------------------------------------------- ### privateKey[](https://viem.sh/docs/accounts/local/privateKeyToAccount#privatekey) * **Type:** `Hex` The private key to use for the Account. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/accounts/local/privateKeyToAccount.md) Copy page for AI Ask AI... ⌘ I --- # JSON-RPC Account · Viem [Skip to content](https://viem.sh/docs/accounts/jsonRpc#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K JSON-RPC Account ================ A function to create a JSON-RPC Account. A JSON-RPC Account is an Account whose signing keys are stored on the external Wallet. It **defers** signing of transactions & messages to the target Wallet over JSON-RPC. An example of such Wallet could be a Browser Extension Wallet, or Mobile Wallet over WalletConnect. Usage[](https://viem.sh/docs/accounts/jsonRpc#usage) ----------------------------------------------------- A JSON-RPC Account can just be initialized as an [Address](https://viem.sh/docs/glossary/types#address) string. In the usage below, we are extracting the address from a Browser Extension Wallet (e.g. MetaMask) with the `window.ethereum` Provider via `eth_requestAccounts`: import 'viem/window' import { createWalletClient, custom } from 'viem' import { mainnet } from 'viem/chains' const [address] = await window.ethereum.request({ method: 'eth_requestAccounts' }) const client = createWalletClient({ account: address, chain: mainnet, transport: custom(window.ethereum!) }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/accounts/jsonRpc.md) Copy page for AI Ask AI... ⌘ I --- # createNonceManager · Viem [Skip to content](https://viem.sh/docs/accounts/local/createNonceManager#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K createNonceManager ================== Creates a Nonce Manager for automatic nonce generation Creates a new Nonce Manager instance to be used with a [Local Account](https://viem.sh/docs/accounts/local) . The Nonce Manager is used to automatically manage & generate nonces for transactions. Import[](https://viem.sh/docs/accounts/local/createNonceManager#import) ------------------------------------------------------------------------ import { createNonceManager } from 'viem/nonce' Usage[](https://viem.sh/docs/accounts/local/createNonceManager#usage) ---------------------------------------------------------------------- A Nonce Manager can be instantiated with the `createNonceManager` function with a provided `source`. The example below demonstrates how to create a Nonce Manager with a JSON-RPC source (ie. uses `eth_getTransactionCount` as the source of truth). import { createNonceManager, jsonRpc } from 'viem/nonce' const nonceManager = createNonceManager({ source: jsonRpc() }) ### Integration with Local Accounts[](https://viem.sh/docs/accounts/local/createNonceManager#integration-with-local-accounts) A `nonceManager` can be passed as an option to [Local Accounts](https://viem.sh/docs/accounts/local) to automatically manage nonces for transactions. example.tsconfig.ts import { privateKeyToAccount, nonceManager } from 'viem/accounts' import { client } from './config' const account = privateKeyToAccount('0x...', { nonceManager }) const hashes = await Promise.all([ \ ↓ nonce = 0 client.sendTransaction({ account, \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('0.1'), \ }), \ ↓ nonce = 1 client.sendTransaction({ account, \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('0.2'), \ }), \ ]) Return Type[](https://viem.sh/docs/accounts/local/createNonceManager#return-type) ---------------------------------------------------------------------------------- `NonceManager` The Nonce Manager. Parameters[](https://viem.sh/docs/accounts/local/createNonceManager#parameters) -------------------------------------------------------------------------------- ### source[](https://viem.sh/docs/accounts/local/createNonceManager#source) * **Type:** `NonceManagerSource` The source of truth for the Nonce Manager. Available sources: * `jsonRpc` import { createNonceManager, jsonRpc } from 'viem/nonce' const nonceManager = createNonceManager({ source: jsonRpc() }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/accounts/local/createNonceManager.md) Copy page for AI Ask AI... ⌘ I --- # signMessage (Local Account) · Viem [Skip to content](https://viem.sh/docs/accounts/local/signMessage#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K signMessage (Local Account) =========================== Signs a message with the Account's private key. Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191) : `keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))`. With the calculated signature, you can: * use `[verifyMessage](https://viem.sh/docs/utilities/verifyMessage) ` to verify the signature, * use `[recoverMessageAddress](https://viem.sh/docs/utilities/recoverMessageAddress) ` to recover the signing address from a signature. Usage[](https://viem.sh/docs/accounts/local/signMessage#usage) --------------------------------------------------------------- import { privateKeyToAccount } from 'viem/accounts' const account = privateKeyToAccount('0x...') const signature = await account.signMessage({ // Hex data representation of message. message: { raw: '0x68656c6c6f20776f726c64' }, }) Output: "0xa461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b" Returns[](https://viem.sh/docs/accounts/local/signMessage#returns) ------------------------------------------------------------------- `[Hex](https://viem.sh/docs/glossary/types#hex) ` The signed message. Parameters[](https://viem.sh/docs/accounts/local/signMessage#parameters) ------------------------------------------------------------------------- ### message[](https://viem.sh/docs/accounts/local/signMessage#message) * **Type:** `string | { raw: Hex | ByteArray }` Message to sign. By default, viem signs the UTF-8 representation of the message. const signature = await account.signMessage({ message: 'hello world', }) To sign the data representation of the message, you can use the `raw` attribute. const signature = await account.signMessage({ message: { raw: '0x68656c6c6f20776f726c64' }, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/accounts/local/signMessage.md) Copy page for AI Ask AI... ⌘ I --- # toAccount · Viem [Skip to content](https://viem.sh/docs/accounts/local/toAccount#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K toAccount ========= A function to create a Custom Account. Creates an Account from a custom signing implementation Import[](https://viem.sh/docs/accounts/local/toAccount#import) --------------------------------------------------------------- import { toAccount } from 'viem/accounts' Usage[](https://viem.sh/docs/accounts/local/toAccount#usage) ------------------------------------------------------------- import { signMessage, signTransaction, signTypedData, privateKeyToAddress, toAccount } from 'viem/accounts' const privateKey = '0x...' const account = toAccount({ address: getAddress(privateKey), async signMessage({ message }) { return signMessage({ message, privateKey }) }, async signTransaction(transaction, { serializer }) { return signTransaction({ privateKey, transaction, serializer }) }, async signTypedData(typedData) { return signTypedData({ ...typedData, privateKey }) }, }) Parameters[](https://viem.sh/docs/accounts/local/toAccount#parameters) ----------------------------------------------------------------------- ### address[](https://viem.sh/docs/accounts/local/toAccount#address) * **Type:** `Address` The Address of the Account. const account = toAccount({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', async signMessage({ message }) { return signMessage({ message, privateKey }) }, async signTransaction(transaction, { serializer }) { return signTransaction({ privateKey, transaction, serializer }) }, async signTypedData(typedData) { return signTypedData({ ...typedData, privateKey }) }, }) ### signMessage[](https://viem.sh/docs/accounts/local/toAccount#signmessage) Function to sign a message in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191) . const account = toAccount({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', async signMessage({ message }) { return signMessage({ message, privateKey }) }, async signTransaction(transaction, { serializer }) { return signTransaction({ privateKey, transaction, serializer }) }, async signTypedData(typedData) { return signTypedData({ ...typedData, privateKey }) }, }) ### signTransaction[](https://viem.sh/docs/accounts/local/toAccount#signtransaction) Function to sign a transaction. const account = toAccount({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', async signMessage({ message }) { return signMessage({ message, privateKey }) }, async signTransaction(transaction, { serializer }) { return signTransaction({ privateKey, transaction, serializer }) }, async signTypedData(typedData) { return signTypedData({ ...typedData, privateKey }) }, }) ### signTypedData[](https://viem.sh/docs/accounts/local/toAccount#signtypeddata) Function to sign [EIP-712](https://eips.ethereum.org/EIPS/eip-712) typed data. const account = toAccount({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', async signMessage({ message }) { return signMessage({ message, privateKey }) }, async signTransaction(transaction, { serializer }) { return signTransaction({ privateKey, transaction, serializer }) }, async signTypedData(typedData) { return signTypedData({ ...typedData, privateKey }) }, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/accounts/local/toAccount.md) Copy page for AI Ask AI... ⌘ I --- # mnemonicToAccount · Viem [Skip to content](https://viem.sh/docs/accounts/local/mnemonicToAccount#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K mnemonicToAccount ================= A function to create a Mnemonic Account. A Mnemonic Account is a [Hierarchical Deterministic (HD) Account](https://viem.sh/docs/accounts/local/hdKeyToAccount) that is derived from a [BIP-39 mnemonic phrase](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) and an optional HD path. It has the ability to sign transactions and messages with the private key derived from the HD Node. Import[](https://viem.sh/docs/accounts/local/mnemonicToAccount#import) ----------------------------------------------------------------------- import { mnemonicToAccount } from 'viem/accounts' Usage[](https://viem.sh/docs/accounts/local/mnemonicToAccount#usage) --------------------------------------------------------------------- To initialize a Mnemonic Account, you will need to pass a mnemonic phrase to `mnemonicToAccount`: import { createWalletClient, http } from 'viem' import { mnemonicToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' const account = mnemonicToAccount('legal winner thank year wave sausage worth useful legal winner thank yellow') const client = createWalletClient({ account, chain: mainnet, transport: http() }) > Note: the above is a valid mnemonic, but it is not a "real" mnemonic. Please do not use it for anything other than testing. ### Generating Mnemonics[](https://viem.sh/docs/accounts/local/mnemonicToAccount#generating-mnemonics) You can generate a random BIP-39 mnemonic using the `generateMnemonic` function with a wordlist: import { english, generateMnemonic } from 'viem/accounts' const mnemonic = generateMnemonic(english) Available wordlists: * `czech` * `english` * `french` * `italian` * `japanese` * `korean` * `portuguese` * `simplifiedChinese` * `spanish` * `traditionalChinese` Parameters[](https://viem.sh/docs/accounts/local/mnemonicToAccount#parameters) ------------------------------------------------------------------------------- ### mnemonic[](https://viem.sh/docs/accounts/local/mnemonicToAccount#mnemonic) * **Type:** `string` The BIP-39 mnemonic phrase. const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow' ) ### options.passphrase[](https://viem.sh/docs/accounts/local/mnemonicToAccount#optionspassphrase) * **Type:** `string` The BIP-39 passphrase. import { mnemonicToAccount } from 'viem/accounts' // ---cut--- const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow', { passphrase: 'passphrase' } ) ### options.accountIndex[](https://viem.sh/docs/accounts/local/mnemonicToAccount#optionsaccountindex) * **Type:** `number` * **Default:** `0` The account index to use in the path (`"m/44'/60'/${accountIndex}'/0/0"`) to derive a private key. const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow', { accountIndex: 1 } ) ### options.addressIndex[](https://viem.sh/docs/accounts/local/mnemonicToAccount#optionsaddressindex) * **Type:** `number` * **Default:** `0` The address index to use in the path (`"m/44'/60'/0'/0/${addressIndex}"`) to derive a private key. const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow', { accountIndex: 1, addressIndex: 6 } ) ### options.changeIndex[](https://viem.sh/docs/accounts/local/mnemonicToAccount#optionschangeindex) * **Type:** `number` * **Default:** `0` The change index to use in the path (`"m/44'/60'/0'/${changeIndex}/0"`) to derive a private key. const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow', { accountIndex: 1, addressIndex: 6, changeIndex: 2 } ) ### options.path[](https://viem.sh/docs/accounts/local/mnemonicToAccount#optionspath) * **Type:** `"m/44'/60'/${string}"` The HD path to use to derive a private key. const account = mnemonicToAccount( 'legal winner thank year wave sausage worth useful legal winner thank yellow', { path: "m/44'/60'/5'/0/2" } ) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/accounts/local/mnemonicToAccount.md) Copy page for AI Ask AI... ⌘ I --- # hdKeyToAccount · Viem [Skip to content](https://viem.sh/docs/accounts/local/hdKeyToAccount#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K hdKeyToAccount ============== A function to create a Hierarchical Deterministic (HD) Account. A [Hierarchical Deterministic (HD)](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#abstract) Account is derived from a [HD Key](https://github.com/paulmillr/scure-bip32#usage) and an optional HD path. It has the ability to sign transactions and messages with the private key derived from the HD Node. Import[](https://viem.sh/docs/accounts/local/hdKeyToAccount#import) -------------------------------------------------------------------- import { HDKey, hdKeyToAccount } from 'viem/accounts' > Note: viem [re-exports `HDKey`](https://github.com/paulmillr/scure-bip32#usage) > from `@scure/bip32`. Usage[](https://viem.sh/docs/accounts/local/hdKeyToAccount#usage) ------------------------------------------------------------------ To initialize a HD Account, you will need to pass a [`HDKey` instance](https://github.com/paulmillr/scure-bip32#usage) to `hdKeyToAccount`. The `HDKey` instance comes with a few static methods to derive a HD Key: * `fromMasterSeed` * `fromExtendedKey` * `fromJSON` import { createWalletClient, http } from 'viem' import { HDKey, hdKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' const hdKey = HDKey.fromMasterSeed(...) const hdKey = HDKey.fromExtendedKey(...) const hdKey = HDKey.fromJSON({ xpriv: ... }) const account = hdKeyToAccount(hdKey) const client = createWalletClient({ account, chain: mainnet, transport: http(), }) Parameters[](https://viem.sh/docs/accounts/local/hdKeyToAccount#parameters) ---------------------------------------------------------------------------- ### hdKey[](https://viem.sh/docs/accounts/local/hdKeyToAccount#hdkey) * **Type:** `string` The BIP-39 mnemonic phrase. const hdKey = HDKey.fromMasterSeed(...) const account = hdKeyToAccount( hdKey, ) ### options.accountIndex[](https://viem.sh/docs/accounts/local/hdKeyToAccount#optionsaccountindex) * **Type:** `number` * **Default:** `0` The account index to use in the path (`"m/44'/60'/${accountIndex}'/0/0"`) to derive a private key. const hdKey = HDKey.fromMasterSeed(...) const account = hdKeyToAccount( hdKey, { accountIndex: 1 } ) ### options.addressIndex[](https://viem.sh/docs/accounts/local/hdKeyToAccount#optionsaddressindex) * **Type:** `number` * **Default:** `0` The address index to use in the path (`"m/44'/60'/0'/0/${addressIndex}"`) to derive a private key. const hdKey = HDKey.fromMasterSeed(...) const account = hdKeyToAccount( hdKey, { accountIndex: 1, addressIndex: 6 } ) ### options.changeIndex[](https://viem.sh/docs/accounts/local/hdKeyToAccount#optionschangeindex) * **Type:** `number` * **Default:** `0` The change index to use in the path (`"m/44'/60'/0'/${changeIndex}/0"`) to derive a private key. const hdKey = HDKey.fromMasterSeed(...) const account = hdKeyToAccount( hdKey, { accountIndex: 1, addressIndex: 6, changeIndex: 2 } ) ### options.path[](https://viem.sh/docs/accounts/local/hdKeyToAccount#optionspath) * **Type:** `"m/44'/60'/${string}"` The HD path to use to derive a private key. const hdKey = HDKey.fromMasterSeed(...) const account = hdKeyToAccount( hdKey, { path: "m/44'/60'/5'/0/2" } ) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/accounts/local/hdKeyToAccount.md) Copy page for AI Ask AI... ⌘ I --- # createAccessList · Viem [Skip to content](https://viem.sh/docs/actions/public/createAccessList#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K createAccessList ================ Creates an [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) access list based on a transaction request. Usage[](https://viem.sh/docs/actions/public/createAccessList#usage) -------------------------------------------------------------------- example.tsconfig.ts import { account, publicClient } from './config' const result = await publicClient.createAccessList({ data: '0xdeadbeef', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) Returns[](https://viem.sh/docs/actions/public/createAccessList#returns) ------------------------------------------------------------------------ `{ accessList: AccessList, gasUsed: bigint }` The access list and gas used. Parameters[](https://viem.sh/docs/actions/public/createAccessList#parameters) ------------------------------------------------------------------------------ ### account (optional)[](https://viem.sh/docs/actions/public/createAccessList#account-optional) * **Type:** `Account | Address` The Account to create an access list for. import { parseEther } from 'viem' const result = await publicClient.createAccessList({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xdeadbeef', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) ### blockNumber (optional)[](https://viem.sh/docs/actions/public/createAccessList#blocknumber-optional) * **Type:** `number` Block number to create an access list for. import { parseEther } from 'viem' const result = await publicClient.createAccessList({ blockNumber: 15121123n, data: '0xdeadbeef', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) ### blockTag (optional)[](https://viem.sh/docs/actions/public/createAccessList#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` Block tag to create an access list for. import { parseEther } from 'viem' const result = await publicClient.createAccessList({ blockTag: 'safe', account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xdeadbeef', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### data (optional)[](https://viem.sh/docs/actions/public/createAccessList#data-optional) * **Type:** `0x${string}` Contract function selector with encoded arguments. import { parseEther } from 'viem' const result = await publicClient.createAccessList({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xdeadbeef', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) ### gasPrice (optional)[](https://viem.sh/docs/actions/public/createAccessList#gasprice-optional) * **Type:** `bigint` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction) . import { parseEther, parseGwei } from 'viem' const result = await publicClient.createAccessList({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xdeadbeef', gasPrice: parseGwei('20'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) ### maxFeePerGas (optional)[](https://viem.sh/docs/actions/public/createAccessList#maxfeepergas-optional) * **Type:** `bigint` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) import { parseEther, parseGwei } from 'viem' const result = await publicClient.createAccessList({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xdeadbeef', maxFeePerGas: parseGwei('20'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) ### maxPriorityFeePerGas (optional)[](https://viem.sh/docs/actions/public/createAccessList#maxpriorityfeepergas-optional) * **Type:** `bigint` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) import { parseEther, parseGwei } from 'viem' const result = await publicClient.createAccessList({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xdeadbeef', maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) ### to (optional)[](https://viem.sh/docs/actions/public/createAccessList#to-optional) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` Transaction recipient. import { parseEther } from 'viem' const result = await publicClient.createAccessList({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xdeadbeef', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### value (optional)[](https://viem.sh/docs/actions/public/createAccessList#value-optional) * **Type:** `bigint` Value (in wei) sent with this transaction. import { parseEther } from 'viem' const result = await publicClient.createAccessList({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xdeadbeef', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/createAccessList.md) Copy page for AI Ask AI... ⌘ I --- # Local Accounts (Private Key, Mnemonic, etc) · Viem [Skip to content](https://viem.sh/docs/accounts/local#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Local Accounts (Private Key, Mnemonic, etc) =========================================== A Local Account is an Account whose signing keys are stored on the consuming user's machine. It performs signing of transactions & messages with a private key **before** broadcasting the transaction or message over JSON-RPC. There are three types of Local Accounts in viem: * [Private Key Account](https://viem.sh/docs/accounts/local/privateKeyToAccount) * [Mnemonic Account](https://viem.sh/docs/accounts/local/mnemonicToAccount) * [Hierarchical Deterministic (HD) Account](https://viem.sh/docs/accounts/local/hdKeyToAccount) Instantiation[](https://viem.sh/docs/accounts/local#instantiation) ------------------------------------------------------------------- ### 1\. Initialize a Wallet Client[](https://viem.sh/docs/accounts/local#1-initialize-a-wallet-client) Before we set up our Account and start consuming Wallet Actions, we will need to set up our Wallet Client with the [`http` Transport](https://viem.sh/docs/clients/transports/http) : import { createWalletClient, http } from 'viem' import { mainnet } from 'viem/chains' const client = createWalletClient({ chain: mainnet, transport: http() }) ### 2\. Set up your Local Account[](https://viem.sh/docs/accounts/local#2-set-up-your-local-account) Next, we will instantiate a Private Key Account using `privateKeyToAccount`: import { createWalletClient, http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' const client = createWalletClient({ chain: mainnet, transport: http() }) const account = privateKeyToAccount('0x...') ### 3\. Consume [Wallet Actions](https://viem.sh/docs/actions/wallet/introduction) [](https://viem.sh/docs/accounts/local#3-consume-wallet-actions) Now you can use that Account within Wallet Actions that need a signature from the user: import { createWalletClient, http, parseEther } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' const client = createWalletClient({ chain: mainnet, transport: http() }) const account = privateKeyToAccount('0x...') const hash = await client.sendTransaction({ account, to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', value: parseEther('0.001') }) ### 4\. Optional: Hoist the Account[](https://viem.sh/docs/accounts/local#4-optional-hoist-the-account) If you do not wish to pass an account around to every Action that requires an `account`, you can also hoist the account into the Wallet Client. import { createWalletClient, http, parseEther } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' const account = privateKeyToAccount('0x...') const client = createWalletClient({ account, chain: mainnet, transport: http() }) const hash = await client.sendTransaction({ account, to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', value: parseEther('0.001') }) ### 5\. Optional: Extend with Public Actions[](https://viem.sh/docs/accounts/local#5-optional-extend-with-public-actions) When using a Local Account, you may be finding yourself using a [Public Client](https://viem.sh/docs/clients/public) instantiated with the same parameters (`transport`, `chain`, etc) as your Wallet Client. In this case, you can extend your Wallet Client with [Public Actions](https://viem.sh/docs/actions/public/introduction) to avoid having to handle multiple Clients. import { createWalletClient, http, publicActions } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' const account = privateKeyToAccount('0x...') const client = createWalletClient({ account, chain: mainnet, transport: http() }).extend(publicActions) const { request } = await client.simulateContract({ ... }) // Public Action const hash = await client.writeContract(request) // Wallet Action [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/accounts/local.md) Copy page for AI Ask AI... ⌘ I --- # signTypedData (Local Account) · Viem [Skip to content](https://viem.sh/docs/accounts/local/signTypedData#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K signTypedData (Local Account) ============================= Signs typed data with the Account's private key. Signs typed data and calculates an Ethereum-specific signature in [https://eips.ethereum.org/EIPS/eip-712](https://eips.ethereum.org/EIPS/eip-712) : `sign(keccak256("\x19\x01" ‖ domainSeparator ‖ hashStruct(message)))` Usage[](https://viem.sh/docs/accounts/local/signTypedData#usage) ----------------------------------------------------------------- example.tsdata.ts import { privateKeyToAccount } from 'viem/accounts' import { domain, types } from './data' const account = privateKeyToAccount('0x...') const signature = await account.signTypedData({ domain, types, primaryType: 'Mail', message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) Returns[](https://viem.sh/docs/accounts/local/signTypedData#returns) --------------------------------------------------------------------- `0x${string}` The signed data. Parameters[](https://viem.sh/docs/accounts/local/signTypedData#parameters) --------------------------------------------------------------------------- ### domain[](https://viem.sh/docs/accounts/local/signTypedData#domain) **Type:** `TypedDataDomain` The typed data domain. const signature = await account.signTypedData({ domain: { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', }, types, primaryType: 'Mail', message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ### types[](https://viem.sh/docs/accounts/local/signTypedData#types) The type definitions for the typed data. const signature = await account.signTypedData({ domain, 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!', }, }) ### primaryType[](https://viem.sh/docs/accounts/local/signTypedData#primarytype) **Type:** Inferred `string`. The primary type to extract from `types` and use in `value`. const signature = await account.signTypedData({ domain, 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!', }, }) ### message[](https://viem.sh/docs/accounts/local/signTypedData#message) **Type:** Inferred from `types` & `primaryType`. const signature = await account.signTypedData({ domain, 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!', }, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/accounts/local/signTypedData.md) Copy page for AI Ask AI... ⌘ I --- # signTransaction (Local Account) · Viem [Skip to content](https://viem.sh/docs/accounts/local/signTransaction#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K signTransaction (Local Account) =============================== Signs a transaction with the Account's private key. Signs a transaction with the Account's private key. Usage[](https://viem.sh/docs/accounts/local/signTransaction#usage) ------------------------------------------------------------------- import { parseGwei } from 'viem' import { privateKeyToAccount } from 'viem/accounts' const account = privateKeyToAccount('0x...') const signature = await account.signTransaction({ chainId: 1, maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('3'), gas: 21000n, nonce: 69, to: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' }) Output: "0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33" ### Custom serializer[](https://viem.sh/docs/accounts/local/signTransaction#custom-serializer) viem has a built-in serializer for **Legacy**, **EIP-2930** (`0x01`) and **EIP-1559** (`0x02`) transaction types. If you would like to serialize on another transaction type that viem does not support internally, you can pass a custom serializer. import { parseGwei } from 'viem' import { privateKeyToAccount } from 'viem/accounts' const account = privateKeyToAccount('0x...') const signature = await account.signTransaction({ maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('3'), gas: 21000n, nonce: 69, to: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' }, { serializer(transaction) { const { chainId, nonce, // ... } = transaction return concatHex([\ '0x69',\ toRlp([\ toHex(chainId),\ nonce ? toHex(nonce) : '0x',\ // ...\ ]),\ ]) } }) Returns[](https://viem.sh/docs/accounts/local/signTransaction#returns) ----------------------------------------------------------------------- `[Hex](https://viem.sh/docs/glossary/types#Hex) ` The signed transaction. Parameters[](https://viem.sh/docs/accounts/local/signTransaction#parameters) ----------------------------------------------------------------------------- ### accessList (optional)[](https://viem.sh/docs/accounts/local/signTransaction#accesslist-optional) * **Type:** `[AccessList](https://viem.sh/docs/glossary/types#accesslist) ` The access list. const signature = await account.signTransaction({ accessList: [ \ {\ address: '0x1',\ storageKeys: ['0x1'],\ },\ ], chainId: 1, }) ### authorizationList (optional)[](https://viem.sh/docs/accounts/local/signTransaction#authorizationlist-optional) * **Type:** `AuthorizationList` Signed EIP-7702 Authorization list. const authorization = await account.signAuthorization({ contractAddress: '0x...', chainId: 1, nonce: 1, }) const signature = await account.signTransaction({ authorizationList: [authorization], chainId: 1, }) ### blobs (optional)[](https://viem.sh/docs/accounts/local/signTransaction#blobs-optional) * **Type:** `Hex[]` Blobs for [Blob Transactions](https://viem.sh/docs/guides/blob-transactions) . import * as cKzg from 'c-kzg' import { toBlobs, setupKzg, stringToHex } from 'viem' import { mainnetTrustedSetupPath } from 'viem/node' const kzg = setupKzg(cKzg, mainnetTrustedSetupPath) const hash = await account.signTransaction({ blobs: toBlobs({ data: stringToHex('blobby blob!') }), kzg, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) ### chainId (optional)[](https://viem.sh/docs/accounts/local/signTransaction#chainid-optional) * **Type:** `number` The chain ID. const signature = await account.signTransaction({ chainId: 1, }) ### data (optional)[](https://viem.sh/docs/accounts/local/signTransaction#data-optional) * **Type:** `0x${string}` Transaction data. const signature = await account.signTransaction({ data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2' }) ### gas (optional)[](https://viem.sh/docs/accounts/local/signTransaction#gas-optional) * **Type:** `bigint` The gas limit for the transaction. const signature = await account.signTransaction({ gas: 69420n, }) ### gasPrice (optional)[](https://viem.sh/docs/accounts/local/signTransaction#gasprice-optional) * **Type:** `bigint` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction) . const signature = await account.signTransaction({ gasPrice: parseGwei('20'), }) ### kzg (optional)[](https://viem.sh/docs/accounts/local/signTransaction#kzg-optional) * **Type:** `KZG` KZG implementation for [Blob Transactions](https://viem.sh/docs/guides/blob-transactions) . See `[setupKzg](https://viem.sh/docs/utilities/setupKzg) ` for more information. import * as cKzg from 'c-kzg' import { toBlobs, setupKzg, stringToHex } from 'viem' import { mainnetTrustedSetupPath } from 'viem/node' const kzg = setupKzg(cKzg, mainnetTrustedSetupPath) const signature = await account.signTransaction({ blobs: toBlobs({ data: stringToHex('blobby blob!') }), kzg, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) ### maxFeePerGas (optional)[](https://viem.sh/docs/accounts/local/signTransaction#maxfeepergas-optional) * **Type:** `bigint` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) const signature = await account.signTransaction({ chainId: 1, maxFeePerGas: parseGwei('20'), }) ### maxPriorityFeePerGas (optional)[](https://viem.sh/docs/accounts/local/signTransaction#maxpriorityfeepergas-optional) * **Type:** `bigint` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) const signature = await account.signTransaction({ chainId: 1, maxPriorityFeePerGas: parseGwei('3'), }) ### nonce (optional)[](https://viem.sh/docs/accounts/local/signTransaction#nonce-optional) * **Type:** `number` Unique number identifying this transaction. const signature = await account.signTransaction({ nonce: 69 }) ### to (optional)[](https://viem.sh/docs/accounts/local/signTransaction#to-optional) * **Type:** `Address` The transaction recipient. const signature = await account.signTransaction({ to: '0x...' }) ### type (optional)[](https://viem.sh/docs/accounts/local/signTransaction#type-optional) * **Type:** `"legacy" | "eip2930" | "eip1559"` The transaction type. const signature = await account.signTransaction({ type: 'eip1559' }) ### value (optional)[](https://viem.sh/docs/accounts/local/signTransaction#value-optional) * **Type:** `bigint` Value in wei sent with this transaction. const signature = await account.signTransaction({ value: parseEther('1'), }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/accounts/local/signTransaction.md) Copy page for AI Ask AI... ⌘ I --- # createBlockFilter · Viem [Skip to content](https://viem.sh/docs/actions/public/createBlockFilter#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K createBlockFilter ================= An Action for creating a new Block Filter. Creates a Filter to listen for new block hashes that can be used with `[getFilterChanges](https://viem.sh/docs/actions/public/getFilterChanges) `. Usage[](https://viem.sh/docs/actions/public/createBlockFilter#usage) --------------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const filter = await publicClient.createBlockFilter() { id: "0x345a6572337856574a76364e457a4366", type: 'block' } Returns[](https://viem.sh/docs/actions/public/createBlockFilter#returns) ------------------------------------------------------------------------- `[Filter](https://viem.sh/docs/glossary/types#filter) ` JSON-RPC Methods[](https://viem.sh/docs/actions/public/createBlockFilter#json-rpc-methods) ------------------------------------------------------------------------------------------- `[eth_newBlockFilter](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newBlockFilter) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/createBlockFilter.md) Copy page for AI Ask AI... ⌘ I --- # createPendingTransactionFilter · Viem [Skip to content](https://viem.sh/docs/actions/public/createPendingTransactionFilter#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K createPendingTransactionFilter ============================== An Action for creating a new pending transaction filter. Creates a Filter to listen for new pending transaction hashes that can be used with `[getFilterChanges](https://viem.sh/docs/actions/public/getFilterChanges) `. Usage[](https://viem.sh/docs/actions/public/createPendingTransactionFilter#usage) ---------------------------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const filter = await publicClient.createPendingTransactionFilter() Output: { id: "0x345a6572337856574a76364e457a4366", type: 'transaction' } Returns[](https://viem.sh/docs/actions/public/createPendingTransactionFilter#returns) -------------------------------------------------------------------------------------- `[Filter](https://viem.sh/docs/glossary/types#filter) ` JSON-RPC Methods[](https://viem.sh/docs/actions/public/createPendingTransactionFilter#json-rpc-methods) -------------------------------------------------------------------------------------------------------- `[eth_newPendingTransactionFilter](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/createPendingTransactionFilter.md) Copy page for AI Ask AI... ⌘ I --- # getBlobBaseFee · Viem [Skip to content](https://viem.sh/docs/actions/public/getBlobBaseFee#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getBlobBaseFee ============== Returns the current blob base fee (in wei). Usage[](https://viem.sh/docs/actions/public/getBlobBaseFee#usage) ------------------------------------------------------------------ example.tsclient.ts import { publicClient } from './client' const baseFee = await publicClient.getBlobBaseFee() Returns[](https://viem.sh/docs/actions/public/getBlobBaseFee#returns) ---------------------------------------------------------------------- `bigint` the blob base fee (in wei). JSON-RPC Method[](https://viem.sh/docs/actions/public/getBlobBaseFee#json-rpc-method) -------------------------------------------------------------------------------------- `[eth_blobBaseFee](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getBlobBaseFee.md) Copy page for AI Ask AI... ⌘ I --- # estimateFeesPerGas · Viem [Skip to content](https://viem.sh/docs/actions/public/estimateFeesPerGas#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K estimateFeesPerGas ================== Returns an estimate for the fees per gas (in wei) for a transaction to be likely included in the next block. If `[chain.fees.estimateFeesPerGas](https://viem.sh/docs/actions/public/estimateFeesPerGas) ` is set on the [Client Chain](https://viem.sh/docs/clients/public#chain-optional) or [override Chain](https://viem.sh/docs/actions/public/estimateFeesPerGas#chain-optional) , it will use the returned value. Otherwise, for EIP-1559 Transactions, viem will estimate the fees using a combination of the block's base fee per gas (to derive `maxFeePerGas`) + the [`estimateMaxPriorityFeePerGas` Action](https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas) (to derive `maxPriorityFeePerGas`). For Legacy Transactions, viem will estimate the fee based on the gas price (via the [`getGasPrice` Action](https://viem.sh/docs/actions/public/getGasPrice) ). Usage[](https://viem.sh/docs/actions/public/estimateFeesPerGas#usage) ---------------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const { maxFeePerGas, maxPriorityFeePerGas } = await publicClient.estimateFeesPerGas() } const { gasPrice } = await publicClient.estimateFeesPerGas({ type: 'legacy' }) { gasPrice: 15_000_000_000n } Returns[](https://viem.sh/docs/actions/public/estimateFeesPerGas#returns) -------------------------------------------------------------------------- `[FeeValues](https://viem.sh/docs/glossary/types#feevalues) ` An estimate (in wei) for the fees per gas. Parameters[](https://viem.sh/docs/actions/public/estimateFeesPerGas#parameters) -------------------------------------------------------------------------------- ### chain (optional)[](https://viem.sh/docs/actions/public/estimateFeesPerGas#chain-optional) * **Type:** [Chain](https://viem.sh/docs/glossary/types#chain) * **Default:** `[client.chain](https://viem.sh/docs/clients/public#chain-optional) ` Optional Chain override. Used to infer the fees per gas from `[chain.fees.estimateFeesPerGas](https://viem.sh/docs/actions/public/estimateFeesPerGas) `. import { optimism } from 'viem/chains' const { maxFeePerGas, maxPriorityFeePerGas } = await publicClient.estimateFeesPerGas({ chain: optimism }) ### type (optional)[](https://viem.sh/docs/actions/public/estimateFeesPerGas#type-optional) * **Type:** `"legacy" | "eip1559"` * **Default:** `"eip1559"` const { gasPrice } = await publicClient.estimateFeesPerGas({ type: 'legacy' }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/estimateFeesPerGas.md) Copy page for AI Ask AI... ⌘ I --- # getBalance · Viem [Skip to content](https://viem.sh/docs/actions/public/getBalance#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getBalance ========== Returns the balance of an address in wei. Usage[](https://viem.sh/docs/actions/public/getBalance#usage) -------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const balance = await publicClient.getBalance({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', }) > 10000000000000000000000n (wei) Returns[](https://viem.sh/docs/actions/public/getBalance#returns) ------------------------------------------------------------------ `bigint` The balance of the address in wei. Parameters[](https://viem.sh/docs/actions/public/getBalance#parameters) ------------------------------------------------------------------------ ### address[](https://viem.sh/docs/actions/public/getBalance#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The address of the account. const balance = await publicClient.getBalance({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', }) ### blockNumber (optional)[](https://viem.sh/docs/actions/public/getBalance#blocknumber-optional) * **Type:** `bigint` The balance of the account at a block number. const balance = await publicClient.getBalance({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', blockNumber: 69420n }) ### blockTag (optional)[](https://viem.sh/docs/actions/public/getBalance#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` The balance of the account at a block tag. const balance = await publicClient.getBalance({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', blockTag: 'safe' }) Tips[](https://viem.sh/docs/actions/public/getBalance#tips) ------------------------------------------------------------ * You can convert the balance to ether units with `[formatEther](https://viem.sh/docs/utilities/formatEther) `. import { formatEther } from 'viem' const balance = await publicClient.getBalance({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', blockTag: 'safe' }) const balanceAsEther = formatEther(balance) // "6.942" JSON-RPC Method[](https://viem.sh/docs/actions/public/getBalance#json-rpc-method) ---------------------------------------------------------------------------------- `[eth_getBalance](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getBalance.md) Copy page for AI Ask AI... ⌘ I --- # estimateMaxPriorityFeePerGas · Viem [Skip to content](https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K estimateMaxPriorityFeePerGas ============================ Returns an estimate for the max priority fee per gas (in wei) for a transaction to be likely included in the next block. If `[chain.fees.defaultPriorityFee](https://viem.sh/docs/chains/fees#feesdefaultpriorityfee) ` is set on the [Client Chain](https://viem.sh/docs/clients/public#chain-optional) or [override Chain](https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas#chain-optional) , it will use that value. Otherwise, the Action will either call `[eth_maxPriorityFeePerGas](https://github.com/ethereum/execution-apis/blob/fe8e13c288c592ec154ce25c534e26cb7ce0530d/src/eth/fee_market.yaml#L9-L16) ` (if supported) or manually calculate the max priority fee per gas based on the current block base fee per gas + gas price. Usage[](https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas#usage) -------------------------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const maxPriorityFeePerGas = await publicClient.estimateMaxPriorityFeePerGas() Output: 1_000_000_000n Returns[](https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas#returns) ------------------------------------------------------------------------------------ `bigint` An estimate (in wei) for the max priority fee per gas. Parameters[](https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas#parameters) ------------------------------------------------------------------------------------------ ### chain (optional)[](https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas#chain-optional) * **Type:** [Chain](https://viem.sh/docs/glossary/types#chain) * **Default:** `[client.chain](https://viem.sh/docs/clients/public#chain-optional) ` Optional Chain override. Used to infer the default `maxPriorityFeePerGas` from `[chain.fees.defaultPriorityFee](https://viem.sh/docs/chains/fees#feesdefaultpriorityfee) `. import { optimism } from 'viem/chains' const maxPriorityFeePerGas = await publicClient.estimateMaxPriorityFeePerGas({ chain: optimism }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/estimateMaxPriorityFeePerGas.md) Copy page for AI Ask AI... ⌘ I --- # verifyHash · Viem [Skip to content](https://viem.sh/docs/actions/public/verifyHash#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K verifyHash ========== Verify that a hash (digest) was signed by the provided address. Supports verification of: * **Externally Owned Accounts** * **Smart Contract Accounts:** * **Deployed** (via [ERC-1271](https://eips.ethereum.org/EIPS/eip-1271) ) * **Pre-deployed** (via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492) ) * **Pre-delegated** (via [ERC-8010](https://github.com/ethereum/ERCs/pull/1186) ) Usage[](https://viem.sh/docs/actions/public/verifyHash#usage) -------------------------------------------------------------- example.tsclient.ts import { account, publicClient } from './client' const valid = await publicClient.verifyHash({ address: account.address, hash: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', signature: '0x...', }) true Returns[](https://viem.sh/docs/actions/public/verifyHash#returns) ------------------------------------------------------------------ `boolean` Whether the signed hash is valid for the given address. Parameters[](https://viem.sh/docs/actions/public/verifyHash#parameters) ------------------------------------------------------------------------ ### address[](https://viem.sh/docs/actions/public/verifyHash#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The Ethereum address that signed the original hash. const valid = await publicClient.verifyHash({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', hash: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ### hash[](https://viem.sh/docs/actions/public/verifyHash#hash) * **Type:** `string` The hash to be verified. const valid = await publicClient.verifyHash({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', hash: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ### signature[](https://viem.sh/docs/actions/public/verifyHash#signature) * **Type:** `Hex | ByteArray | Signature` The signature that was generated by signing the hash with the address's signer. const valid = await publicClient.verifyHash({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', hash: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ### blockNumber (optional)[](https://viem.sh/docs/actions/public/verifyHash#blocknumber-optional) * **Type:** `bigint` Only used when verifying a message that was signed by a Smart Contract Account. The block number to check if the contract was already deployed. const valid = await publicClient.verifyHash({ blockNumber: 42069n, address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', hash: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ### blockTag (optional)[](https://viem.sh/docs/actions/public/verifyHash#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` Only used when verifying a message that was signed by a Smart Contract Account. The block tag to check if the contract was already deployed. const valid = await publicClient.verifyHash({ blockTag: 'safe', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', hash: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/verifyHash.md) Copy page for AI Ask AI... ⌘ I --- # getChainId · Viem [Skip to content](https://viem.sh/docs/actions/public/getChainId#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getChainId ========== Returns the chain ID associated with the current network Usage[](https://viem.sh/docs/actions/public/getChainId#usage) -------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const chainId = await publicClient.getChainId() 1 Returns[](https://viem.sh/docs/actions/public/getChainId#returns) ------------------------------------------------------------------ `number` The current chain ID. JSON-RPC Method[](https://viem.sh/docs/actions/public/getChainId#json-rpc-method) ---------------------------------------------------------------------------------- * Calls `[eth_chainId](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid) `. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getChainId.md) Copy page for AI Ask AI... ⌘ I --- # getBlockNumber · Viem [Skip to content](https://viem.sh/docs/actions/public/getBlockNumber#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getBlockNumber ============== Returns the number of the most recent block seen. Usage[](https://viem.sh/docs/actions/public/getBlockNumber#usage) ------------------------------------------------------------------ example.tsclient.ts import { publicClient } from './client' const blockNumber = await publicClient.getBlockNumber() Output: 69420n Returns[](https://viem.sh/docs/actions/public/getBlockNumber#returns) ---------------------------------------------------------------------- `bigint` The number of the block. Parameters[](https://viem.sh/docs/actions/public/getBlockNumber#parameters) ---------------------------------------------------------------------------- ### cacheTime (optional)[](https://viem.sh/docs/actions/public/getBlockNumber#cachetime-optional) * **Type:** `number` * **Default:** [Client's `cacheTime`](https://viem.sh/docs/clients/public#cachetime-optional) Time (in ms) that cached block number will remain in memory. const block = await publicClient.getBlockNumber({ cacheTime: 4_000 }) By default, block numbers are cached for the period of the [Client's `cacheTime`](https://viem.sh/docs/clients/public#cacheTime-optional) . * Setting a value of above zero will make block number remain in the cache for that period. * Setting a value of `0` will disable the cache, and always retrieve a fresh block number. Example[](https://viem.sh/docs/actions/public/getBlockNumber#example) ---------------------------------------------------------------------- Check out the usage of `getBlockNumber` in the live [Fetching Blocks Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks) below. JSON-RPC Method[](https://viem.sh/docs/actions/public/getBlockNumber#json-rpc-method) -------------------------------------------------------------------------------------- `[eth_blockNumber](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getBlockNumber.md) Copy page for AI Ask AI... ⌘ I --- # getBlock · Viem [Skip to content](https://viem.sh/docs/actions/public/getBlock#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getBlock ======== Returns information about a block at a block number, hash or tag. Usage[](https://viem.sh/docs/actions/public/getBlock#usage) ------------------------------------------------------------ example.tsclient.ts import { publicClient } from './client' const block = await publicClient.getBlock() } Returns[](https://viem.sh/docs/actions/public/getBlock#returns) ---------------------------------------------------------------- `[Block](https://viem.sh/docs/glossary/types#block) ` Information about the block. Parameters[](https://viem.sh/docs/actions/public/getBlock#parameters) ---------------------------------------------------------------------- ### blockHash (optional)[](https://viem.sh/docs/actions/public/getBlock#blockhash-optional) * **Type:** `[Hash](https://viem.sh/docs/glossary/types#hash) ` Information at a given block hash. const block = await publicClient.getBlock({ blockHash: '0x89644bbd5c8d682a2e9611170e6c1f02573d866d286f006cbf517eec7254ec2d' }) ### blockNumber (optional)[](https://viem.sh/docs/actions/public/getBlock#blocknumber-optional) * **Type:** `bigint` Information at a given block number. const block = await publicClient.getBlock({ blockNumber: 42069n }) ### blockTag (optional)[](https://viem.sh/docs/actions/public/getBlock#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` Information at a given block tag. const block = await publicClient.getBlock({ blockTag: 'safe' }) ### includeTransactions (optional)[](https://viem.sh/docs/actions/public/getBlock#includetransactions-optional) * **Type:** `boolean` Whether or not to include transactions (as a structured array of `Transaction` objects). const block = await publicClient.getBlock({ includeTransactions: true }) Example[](https://viem.sh/docs/actions/public/getBlock#example) ---------------------------------------------------------------- Check out the usage of `getBlock` in the live [Fetching Blocks Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks) below. JSON-RPC Method[](https://viem.sh/docs/actions/public/getBlock#json-rpc-method) -------------------------------------------------------------------------------- * Calls `[eth_getBlockByNumber](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) ` for `blockNumber` & `blockTag`. * Calls `[eth_getBlockByHash](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbyhash) ` for `blockHash`. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getBlock.md) Copy page for AI Ask AI... ⌘ I --- # getBlockTransactionCount · Viem [Skip to content](https://viem.sh/docs/actions/public/getBlockTransactionCount#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getBlockTransactionCount ======================== Returns the number of Transactions at a block number, hash or tag. Usage[](https://viem.sh/docs/actions/public/getBlockTransactionCount#usage) ---------------------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const count = await publicClient.getBlockTransactionCount() Output: 23 Returns[](https://viem.sh/docs/actions/public/getBlockTransactionCount#returns) -------------------------------------------------------------------------------- `number` The block transaction count. Parameters[](https://viem.sh/docs/actions/public/getBlockTransactionCount#parameters) -------------------------------------------------------------------------------------- ### blockHash (optional)[](https://viem.sh/docs/actions/public/getBlockTransactionCount#blockhash-optional) * **Type:** `[Hash](https://viem.sh/docs/glossary/types#hash) ` Count at a given block hash. const count = await publicClient.getBlockTransactionCount({ blockHash: '0x89644bbd5c8d682a2e9611170e6c1f02573d866d286f006cbf517eec7254ec2d' }) ### blockNumber (optional)[](https://viem.sh/docs/actions/public/getBlockTransactionCount#blocknumber-optional) * **Type:** `bigint` Count at a given block number. const block = await publicClient.getBlockTransactionCount({ blockNumber: 42069n }) ### blockTag (optional)[](https://viem.sh/docs/actions/public/getBlockTransactionCount#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` Count at a given block tag. const block = await publicClient.getBlockTransactionCount({ blockTag: 'safe' }) JSON-RPC Method[](https://viem.sh/docs/actions/public/getBlockTransactionCount#json-rpc-method) ------------------------------------------------------------------------------------------------ * Calls `[eth_getBlockTransactionCountByNumber](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber) ` for `blockNumber` & `blockTag`. * Calls `[eth_getBlockTransactionCountByHash](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash) ` for `blockHash`. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getBlockTransactionCount.md) Copy page for AI Ask AI... ⌘ I --- # getGasPrice · Viem [Skip to content](https://viem.sh/docs/actions/public/getGasPrice#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getGasPrice =========== Returns the current price of gas (in wei). Usage[](https://viem.sh/docs/actions/public/getGasPrice#usage) --------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const gasPrice = await publicClient.getGasPrice() Returns[](https://viem.sh/docs/actions/public/getGasPrice#returns) ------------------------------------------------------------------- `bigint` The gas price (in wei). JSON-RPC Method[](https://viem.sh/docs/actions/public/getGasPrice#json-rpc-method) ----------------------------------------------------------------------------------- `[eth_gasPrice](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getGasPrice.md) Copy page for AI Ask AI... ⌘ I --- # getFeeHistory · Viem [Skip to content](https://viem.sh/docs/actions/public/getFeeHistory#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getFeeHistory ============= Returns a collection of historical gas information. Usage[](https://viem.sh/docs/actions/public/getFeeHistory#usage) ----------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const feeHistory = await publicClient.getFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] }) Returns[](https://viem.sh/docs/actions/public/getFeeHistory#returns) --------------------------------------------------------------------- `[FeeHistory](https://viem.sh/docs/glossary/types#feehistory) ` The fee history. Parameters[](https://viem.sh/docs/actions/public/getFeeHistory#parameters) --------------------------------------------------------------------------- ### blockCount[](https://viem.sh/docs/actions/public/getFeeHistory#blockcount) * **Type:** `number` Number of blocks in the requested range. Between 1 and 1024 blocks can be requested in a single query. Less than requested may be returned if not all blocks are available. const feeHistory = await publicClient.getFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] }) ### rewardPercentiles[](https://viem.sh/docs/actions/public/getFeeHistory#rewardpercentiles) * **Type:** `number[]` A monotonically increasing list of percentile values to sample from each block's effective priority fees per gas in ascending order, weighted by gas used. const feeHistory = await publicClient.getFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] }) ### blockNumber (optional)[](https://viem.sh/docs/actions/public/getFeeHistory#blocknumber-optional) * **Type:** `number` Highest number block of the requested range. const feeHistory = await publicClient.getFeeHistory({ blockCount: 4, blockNumber: 1551231n, rewardPercentiles: [25, 75] }) ### blockTag (optional)[](https://viem.sh/docs/actions/public/getFeeHistory#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` Highest number block of the requested range. const feeHistory = await publicClient.getFeeHistory({ blockCount: 4, blockTag: 'safe', rewardPercentiles: [25, 75] }) JSON-RPC Method[](https://viem.sh/docs/actions/public/getFeeHistory#json-rpc-method) ------------------------------------------------------------------------------------- * Calls `[eth_feeHistory](https://docs.alchemy.com/reference/eth-feehistory) `. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getFeeHistory.md) Copy page for AI Ask AI... ⌘ I --- # getFilterLogs · Viem [Skip to content](https://viem.sh/docs/actions/public/getFilterLogs#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getFilterLogs ============= Returns a list of **event** logs since the filter was created. Note: `getFilterLogs` is only compatible with **event filters**. Usage[](https://viem.sh/docs/actions/public/getFilterLogs#usage) ----------------------------------------------------------------- example.tsclient.ts import { parseAbiItem } from 'viem' import { publicClient } from './client' const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'), }) const logs = await publicClient.getFilterLogs({ filter }) [{ ... }, { ... }, { ... }] Returns[](https://viem.sh/docs/actions/public/getFilterLogs#returns) --------------------------------------------------------------------- `[Log[]](https://viem.sh/docs/glossary/types#log) ` A list of event logs. Parameters[](https://viem.sh/docs/actions/public/getFilterLogs#parameters) --------------------------------------------------------------------------- ### filter[](https://viem.sh/docs/actions/public/getFilterLogs#filter) * **Type:** `[Filter](https://viem.sh/docs/glossary/types#filter) ` An **event** filter. const filter = await publicClient.createEventFilter() const logs = await publicClient.getFilterChanges({ filter, }) JSON-RPC Method[](https://viem.sh/docs/actions/public/getFilterLogs#json-rpc-method) ------------------------------------------------------------------------------------- `[eth_getFilterLogs](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterlogs) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getFilterLogs.md) Copy page for AI Ask AI... ⌘ I --- # getEip712Domain · Viem [Skip to content](https://viem.sh/docs/actions/public/getEip712Domain#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getEip712Domain =============== Reads the EIP-712 domain from a contract, based on the [ERC-5267 specification](https://eips.ethereum.org/EIPS/eip-5267) . Usage[](https://viem.sh/docs/actions/public/getEip712Domain#usage) ------------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const { domain, extensions, fields } = await publicClient.getEip712Domain({ address: '0x57ba3ec8df619d4d243ce439551cce713bb17411', }) ### Counterfactual Call[](https://viem.sh/docs/actions/public/getEip712Domain#counterfactual-call) It is possible to read the EIP-712 domain on a contract that **has not been deployed** by providing deployment factory (`factory` + `factoryData`) parameters: example.tsclient.ts import { factory, publicClient } from './config' const { domain, extensions, fields } = await publicClient.getEip712Domain({ address: '0x57ba3ec8df619d4d243ce439551cce713bb17411', factory: factory.address, factoryData: encodeFunctionData({ abi: factory.abi, functionName: 'createAccount', args: ['0x0000000000000000000000000000000000000000', 0n] }), }) Returns[](https://viem.sh/docs/actions/public/getEip712Domain#returns) ----------------------------------------------------------------------- `GetEip712DomainReturnType` The EIP-712 domain (`domain`) for the contract, with `fields` and `extensions`, as per [ERC-5267](https://eips.ethereum.org/EIPS/eip-5267) . Parameters[](https://viem.sh/docs/actions/public/getEip712Domain#parameters) ----------------------------------------------------------------------------- ### address[](https://viem.sh/docs/actions/public/getEip712Domain#address) * **Type:** `string` The address of the contract to read the EIP-712 domain from. const result = await publicClient.getEip712Domain({ address: '0x57ba3ec8df619d4d243ce439551cce713bb17411', }) ### factory (optional)[](https://viem.sh/docs/actions/public/getEip712Domain#factory-optional) * **Type:** Contract deployment factory address (ie. Create2 factory, Smart Account factory, etc). const result = await publicClient.getEip712Domain({ address: '0x57ba3ec8df619d4d243ce439551cce713bb17411', factory: '0xE8Df82fA4E10e6A12a9Dab552bceA2acd26De9bb', factoryData: '0xdeadbeef', }) ### factoryData (optional)[](https://viem.sh/docs/actions/public/getEip712Domain#factorydata-optional) * **Type:** Calldata to execute on the factory to deploy the contract. const result = await publicClient.getEip712Domain({ address: '0x57ba3ec8df619d4d243ce439551cce713bb17411', factory: '0xE8Df82fA4E10e6A12a9Dab552bceA2acd26De9bb', factoryData: '0xdeadbeef', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getEip712Domain.md) Copy page for AI Ask AI... ⌘ I --- # Introduction to Public Actions · Viem [Skip to content](https://viem.sh/docs/actions/public/introduction#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Introduction to Public Actions ============================== A brief introduction on what Public Actions are in viem. A Public Action is an action that maps one-to-one with a "public" Ethereum RPC method (`eth_blockNumber`, `eth_getBalance`, etc). They are used with a [Public Client](https://viem.sh/docs/clients/public) . Public Actions do not require any special permissions nor do they provide signing capabilities to the user. Examples of Public Actions include [getting the balance of an account](https://viem.sh/docs/actions/public/getBalance) , [retrieving the details of a specific transaction](https://viem.sh/docs/actions/public/getTransactionReceipt) , and [getting the current block number](https://viem.sh/docs/actions/public/getBlockNumber) of the network. Public Actions provide a simple and secure way to access public data on the Ethereum blockchain. They are widely used by dapps and other applications that need to retrieve information about transactions, accounts, blocks and other data on the network. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/introduction.md) Copy page for AI Ask AI... ⌘ I --- # Introduction to Clients & Transports · Viem [Skip to content](https://viem.sh/docs/clients/intro#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Introduction to Clients & Transports ==================================== A brief introduction to Clients & Transports. Clients[](https://viem.sh/docs/clients/intro#clients) ------------------------------------------------------ A **Client** provides access to a subset of **Actions**. > A **Client** in the context of viem is similar to an [Ethers.js Provider](https://docs.ethers.org/v5/api/providers/) > . There are three types of **Clients** in viem: * A [Public Client](https://viem.sh/docs/clients/public) which provides access to [Public Actions](https://viem.sh/docs/actions/public/introduction) , such as `getBlockNumber` and `getBalance`. * A [Wallet Client](https://viem.sh/docs/clients/wallet) which provides access to [Wallet Actions](https://viem.sh/docs/actions/wallet/introduction) , such as `sendTransaction` and `signMessage`. * A [Test Client](https://viem.sh/docs/clients/test) which provides access to [Test Actions](https://viem.sh/docs/actions/test/introduction) , such as `mine` and `impersonate`. Transports[](https://viem.sh/docs/clients/intro#transports) ------------------------------------------------------------ A **Client** is instantiated with a **Transport**, which is the intermediary layer that is responsible for executing outgoing requests (ie. RPC requests). There are three types of Transports in viem: * A [HTTP Transport](https://viem.sh/docs/clients/transports/http) that executes requests via a HTTP JSON-RPC API. * A [WebSocket Transport](https://viem.sh/docs/clients/transports/websocket) that executes requests via a WebSocket JSON-RPC API. * A [Custom Transport](https://viem.sh/docs/clients/transports/custom) that executes requests via an [EIP-1193 `request` function](https://eips.ethereum.org/EIPS/eip-1193) . [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/clients/intro.md) Copy page for AI Ask AI... ⌘ I --- # dumpState · Viem [Skip to content](https://viem.sh/docs/actions/test/dumpState#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K dumpState ========= Serializes the current state (including contracts code, contract's storage, accounts properties, etc.) into a savable data blob. Usage[](https://viem.sh/docs/actions/test/dumpState#usage) ----------------------------------------------------------- example.tsclient.ts import { testClient } from './client' const state = await testClient.dumpState() // 0x1f8b08000000000000ffad934d8e1c310885ef52eb5e003660e636184c3651b7949948915a7df7b8934ded6bbcc23fe2f3e3c1f3f088c7effbd7e7f1f13ce00ff60c35939e4e016352131bb3658bd0f046682dcd98dfafef8f7bace3036ec7f49ffe2fde190817da82b0e9933abcd7713be291ffaf77fcf9f5f8e53ff6f6f97addde4cced6dd8b3b89e6d4d468a2a3d93e537480fd15713933f12a73ebc2b106ae561c59bae1d152784733c067f1dc49479d987295d9a2f7c8cc296e00e534797026d94ed312a9bc93b5192726d155a882999a42300ea48ce680109a80936141a2be0d8f7182f6cb4a0d4a6d96ac49d16b2834e1a5836dd0c242c0b5751ac8d9d1cb4a4d65b97620594ac2dc77a159cbb9ab349f096fedee76828ecb4cdb20d044679e1124c6c1633a4acda639d026f81ea96f15eab0963a76ca3d2f81b58705fbea3e4a59761b11f8769ce0046d5799d5ac5216a37b8e51523d96f81c839476fb54d53422393bda94af505fafbf9d0612379c040000 Return Type[](https://viem.sh/docs/actions/test/dumpState#return-type) ----------------------------------------------------------------------- `Hex` The state as a data blob. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/dumpState.md) Copy page for AI Ask AI... ⌘ I --- # dropTransaction · Viem [Skip to content](https://viem.sh/docs/actions/test/dropTransaction#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K dropTransaction =============== Remove a transaction from the mempool. Usage[](https://viem.sh/docs/actions/test/dropTransaction#usage) ----------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.dropTransaction({ hash: '0xe58dceb6b20b03965bb678e27d141e151d7d4efc2334c2d6a49b9fac523f7364' }) Parameters[](https://viem.sh/docs/actions/test/dropTransaction#parameters) --------------------------------------------------------------------------- ### hash[](https://viem.sh/docs/actions/test/dropTransaction#hash) * **Type:** `[Hash](https://viem.sh/docs/glossary/types#hash) ` The hash of the transaction. await testClient.dropTransaction({ hash: '0xe58dceb6b20b03965bb678e27d141e151d7d4efc2334c2d6a49b9fac523f7364', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/dropTransaction.md) Copy page for AI Ask AI... ⌘ I --- # getTxpoolContent · Viem [Skip to content](https://viem.sh/docs/actions/test/getTxpoolContent#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K 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. [Read more](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-txpool) . Usage[](https://viem.sh/docs/actions/test/getTxpoolContent#usage) ------------------------------------------------------------------ example.tsclient.ts import { testClient } from './client' const content = await testClient.getTxpoolContent() Returns[](https://viem.sh/docs/actions/test/getTxpoolContent#returns) ---------------------------------------------------------------------- Transaction pool content. [See here](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-txpool) . [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/getTxpoolContent.md) Copy page for AI Ask AI... ⌘ I --- # Chains · Viem [Skip to content](https://viem.sh/docs/chains/introduction#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Chains ====== The `viem/chains` entrypoint contains references to popular EVM-compatible chains such as: Polygon, Optimism, Avalanche, Base, Zora, and more. Usage[](https://viem.sh/docs/chains/introduction#usage) -------------------------------------------------------- Import your chain from the entrypoint and use them in the consuming viem code: import { createPublicClient, http } from 'viem' import { zora } from 'viem/chains' const client = createPublicClient({ chain: zora, transport: http() }) [See here for a list of supported chains](https://github.com/wagmi-dev/viem/tree/main/src/chains/index.ts) . > Want to add a chain that's not listed in viem? Read the [Contributing Guide](https://github.com/wagmi-dev/viem/blob/main/.github/CONTRIBUTING.md#chains) > , and then open a Pull Request with your chain. Custom Chains[](https://viem.sh/docs/chains/introduction#custom-chains) ------------------------------------------------------------------------ You can also extend viem to support other EVM-compatible chains by building your own chain object that inherits the `Chain` type. import { defineChain } from 'viem' export const zora = defineChain({ id: 7777777, name: 'Zora', nativeCurrency: { decimals: 18, name: 'Ether', symbol: 'ETH', }, rpcUrls: { default: { http: ['https://rpc.zora.energy'], webSocket: ['wss://rpc.zora.energy'], }, }, blockExplorers: { default: { name: 'Explorer', url: 'https://explorer.zora.energy' }, }, contracts: { multicall3: { address: '0xcA11bde05977b3631167028862bE2a173976CA11', blockCreated: 5882, }, }, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/chains/introduction.md) Copy page for AI Ask AI... ⌘ I --- # Fees · Viem [Skip to content](https://viem.sh/docs/chains/fees#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Fees ==== Configure chain-based fee data in Viem You can modify how fees are derived by using the `fees` property on the Chain. Usage[](https://viem.sh/docs/chains/fees#usage) ------------------------------------------------ import { defineChain } from 'viem' export const example = defineChain({ /* ... */ fees: { baseFeeMultiplier: 1.2, defaultPriorityFee: parseGwei('0.01'), } }) API[](https://viem.sh/docs/chains/fees#api) -------------------------------------------- ### `fees.baseFeeMultiplier`[](https://viem.sh/docs/chains/fees#feesbasefeemultiplier) * **Type**: `number` * **Default**: `1.2` The fee multiplier to use to account for fee fluctuations. Used in the [`estimateFeesPerGas` Action](https://viem.sh/docs/actions/public/estimateFeesPerGas) against the latest block's base fee per gas to derive a final `maxFeePerGas` (EIP-1193), or gas price to derive a final `gasPrice` (Legacy). **Parameters** * `block`: The latest block. * `client`: The Client instance. * `request`: The transaction request (if exists). import { defineChain } from 'viem' const example = defineChain({ /* ... */ fees: { baseFeeMultiplier: 1.2, // or async baseFeeMultiplier({ block, request }) { // some async work return // ... }, }, }) ### `fees.defaultPriorityFee`[](https://viem.sh/docs/chains/fees#feesdefaultpriorityfee) * **Type**: `number | ((args: FeesFnParameters) => Promise | bigint)` The default `maxPriorityFeePerGas` to use when a priority fee is not defined upon sending a transaction. Also overrides the return value in the [`estimateMaxPriorityFeePerGas` Action](https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas) and `maxPriorityFeePerGas` value in `[estimateFeesPerGas](https://viem.sh/docs/actions/public/estimateFeesPerGas) `. **Parameters** * `block`: The latest block. * `client`: The Client instance. * `request`: The transaction request (if exists). import { defineChain } from 'viem' const example = defineChain({ /* ... */ fees: { defaultPriorityFee: parseGwei('0.01'), // or async defaultPriorityFee({ block, request }) { // some async work return // ... }, }, }) ### `fees.estimateFeesPerGas`[](https://viem.sh/docs/chains/fees#feesestimatefeespergas) * **Type**: `(args: FeesFnParameters) => Promise` Allows customization of fee per gas values (ie. `maxFeePerGas`, `maxPriorityFeePerGas`, `gasPrice`). Also overrides the return value in `[estimateFeesPerGas](https://viem.sh/docs/actions/public/estimateFeesPerGas) `. **Parameters** * `block`: The latest block. * `client`: The Client instance. * `multiply`: A function to apply the `baseFeeMultiplier` to the provided value. * `request`: The transaction request (if exists). * `type`: The transaction type (ie. `legacy` or `eip1559`). import { defineChain } from 'viem' const example = defineChain({ /* ... */ fees: { async estimateFeesPerGas({ client, multiply, type }) { const gasPrice = // ... const baseFeePerGas = // ... const maxPriorityFeePerGas = // ... if (type === 'legacy') return { gasPrice: multiply(gasPrice) } return { maxFeePerGas: multiply(baseFeePerGas) + maxPriorityFeePerGas, maxPriorityFeePerGas }, }, }, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/chains/fees.md) Copy page for AI Ask AI... ⌘ I --- # Platform Compatibility · Viem [Skip to content](https://viem.sh/docs/compatibility#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Platform Compatibility ====================== Platforms compatible with Viem **Viem supports all modern browsers (Chrome, Edge, Firefox, etc) & runtime environments (Node 18+, Deno, Bun, etc).** Viem uses modern EcmaScript features such as: * `[BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) ` * `[fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) ` * Error `[cause](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause) ` * TextEncoder `[encode](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/encode) ` You can check support for these features on [Can I use...](https://caniuse.com/) Polyfills[](https://viem.sh/docs/compatibility#polyfills) ---------------------------------------------------------- If your platform does not support one of the required features, it is also possible to import a polyfill. ### `fetch`[](https://viem.sh/docs/compatibility#fetch) * [isomorphic-unfetch](https://github.com/developit/unfetch/tree/main/packages/isomorphic-unfetch) * [node-fetch](https://github.com/node-fetch/node-fetch#providing-global-access) ### Error `cause`[](https://viem.sh/docs/compatibility#error-cause) * [core-js](https://github.com/zloirock/core-js) ### `TextEncoder`[](https://viem.sh/docs/compatibility#textencoder) * [FastestSmallestTextEncoderDecoder](https://github.com/anonyco/FastestSmallestTextEncoderDecoder) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/compatibility.mdx) Copy page for AI Ask AI... ⌘ I --- # getAutomine · Viem [Skip to content](https://viem.sh/docs/actions/test/getAutomine#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getAutomine =========== Returns the automatic mining status of the node. Usage[](https://viem.sh/docs/actions/test/getAutomine#usage) ------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' const isAutomining = await testClient.getAutomine() Returns[](https://viem.sh/docs/actions/test/getAutomine#returns) ----------------------------------------------------------------- `boolean` Whether or not the node is auto mining. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/getAutomine.md) Copy page for AI Ask AI... ⌘ I --- # getTxpoolStatus · Viem [Skip to content](https://viem.sh/docs/actions/test/getTxpoolStatus#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K 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. [Read more](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-txpool) . Usage[](https://viem.sh/docs/actions/test/getTxpoolStatus#usage) ----------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' const status = await testClient.getTxpoolStatus() Returns[](https://viem.sh/docs/actions/test/getTxpoolStatus#returns) --------------------------------------------------------------------- Transaction pool status. [See here](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-txpool) . [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/getTxpoolStatus.md) Copy page for AI Ask AI... ⌘ I --- # getTransactionReceipt · Viem [Skip to content](https://viem.sh/docs/actions/public/getTransactionReceipt#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getTransactionReceipt ===================== Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. Usage[](https://viem.sh/docs/actions/public/getTransactionReceipt#usage) ------------------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const transaction = await publicClient.getTransactionReceipt({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d' }) } Returns[](https://viem.sh/docs/actions/public/getTransactionReceipt#returns) ----------------------------------------------------------------------------- `[TransactionReceipt](https://viem.sh/docs/glossary/types#transactionreceipt) ` The transaction receipt. Parameters[](https://viem.sh/docs/actions/public/getTransactionReceipt#parameters) ----------------------------------------------------------------------------------- ### hash[](https://viem.sh/docs/actions/public/getTransactionReceipt#hash) * **Type:** `'0x${string}'` A transaction hash. const transaction = await publicClient.getTransactionReceipt({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d' }) Example[](https://viem.sh/docs/actions/public/getTransactionReceipt#example) ----------------------------------------------------------------------------- Check out the usage of `getTransactionReceipt` in the live [Fetching Transactions Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions) below. JSON-RPC Method[](https://viem.sh/docs/actions/public/getTransactionReceipt#json-rpc-method) --------------------------------------------------------------------------------------------- `[eth_getTransactionReceipt](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getTransactionReceipt.md) Copy page for AI Ask AI... ⌘ I --- # getTransactionCount · Viem [Skip to content](https://viem.sh/docs/actions/public/getTransactionCount#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getTransactionCount =================== Returns the number of [Transactions](https://viem.sh/docs/glossary/terms#transaction) an Account has broadcast / sent. Usage[](https://viem.sh/docs/actions/public/getTransactionCount#usage) ----------------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const transactionCount = await publicClient.getTransactionCount({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', }) > 420 Returns[](https://viem.sh/docs/actions/public/getTransactionCount#returns) --------------------------------------------------------------------------- `number` The number of transactions an account has sent. Parameters[](https://viem.sh/docs/actions/public/getTransactionCount#parameters) --------------------------------------------------------------------------------- ### address[](https://viem.sh/docs/actions/public/getTransactionCount#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The address of the account. const transactionCount = await publicClient.getTransactionCount({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', }) ### blockNumber (optional)[](https://viem.sh/docs/actions/public/getTransactionCount#blocknumber-optional) * **Type:** `bigint` Get the count at a block number. const transactionCount = await publicClient.getTransactionCount({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', blockNumber: 69420n }) ### blockTag (optional)[](https://viem.sh/docs/actions/public/getTransactionCount#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` Get the count at a block tag. const transactionCount = await publicClient.getTransactionCount({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', blockTag: 'safe' }) Notes[](https://viem.sh/docs/actions/public/getTransactionCount#notes) ----------------------------------------------------------------------- * The transaction count of an account can also be used as a nonce. JSON-RPC Method[](https://viem.sh/docs/actions/public/getTransactionCount#json-rpc-method) ------------------------------------------------------------------------------------------- `[eth_getTransactionCount](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactioncount) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getTransactionCount.md) Copy page for AI Ask AI... ⌘ I --- # Introduction to Test Actions · Viem [Skip to content](https://viem.sh/docs/actions/test/introduction#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Introduction to Test Actions ============================ A brief introduction on what Test Actions are in viem. Test Actions are actions that map one-to-one with "test" Ethereum RPC methods (`evm_mine`, `anvil_setBalance`, `anvil_impersonate`, etc). They are used with a [Test Client](https://viem.sh/docs/clients/test) . Test Actions are used for testing and simulation purposes. Examples of Test Actions include [mining a block](https://viem.sh/docs/actions/test/mine) , [setting the balance of an account](https://viem.sh/docs/actions/test/setBalance) , and [impersonating accounts](https://viem.sh/docs/actions/test/impersonateAccount) . Test Actions are an essential part of viem, as they provide a way to test and simulate different scenarios on the Ethereum network. They are commonly used by developers who are building dapps and other applications that need to be tested before they are deployed to the network. By using Test Actions, developers can test the behavior of their applications in a controlled environment, without the need for a real balance or real users. This makes it easier to identify and fix bugs, and it ensures that the application will work as expected when it is deployed to the network. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/introduction.md) Copy page for AI Ask AI... ⌘ I --- # loadState · Viem [Skip to content](https://viem.sh/docs/actions/test/loadState#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K loadState ========= Adds state previously dumped with `dumpState` to the current chain. Usage[](https://viem.sh/docs/actions/test/loadState#usage) ----------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.loadState({ state: '0x1f8b08000000000000ffad934d8e1c310885ef52eb5e003660e636184c3651b7949948915a7df7b8934ded6bbcc23fe2f3e3c1f3f088c7effbd7e7f1f13ce00ff60c35939e4e016352131bb3658bd0f046682dcd98dfafef8f7bace3036ec7f49ffe2fde190817da82b0e9933abcd7713be291ffaf77fcf9f5f8e53ff6f6f97addde4cced6dd8b3b89e6d4d468a2a3d93e537480fd15713933f12a73ebc2b106ae561c59bae1d152784733c067f1dc49479d987295d9a2f7c8cc296e00e534797026d94ed312a9bc93b5192726d155a882999a42300ea48ce680109a80936141a2be0d8f7182f6cb4a0d4a6d96ac49d16b2834e1a5836dd0c242c0b5751ac8d9d1cb4a4d65b97620594ac2dc77a159cbb9ab349f096fedee76828ecb4cdb20d044679e1124c6c1633a4acda639d026f81ea96f15eab0963a76ca3d2f81b58705fbea3e4a59761b11f8769ce0046d5799d5ac5216a37b8e51523d96f81c839476fb54d53422393bda94af505fafbf9d0612379c040000' }) Parameters[](https://viem.sh/docs/actions/test/loadState#parameters) --------------------------------------------------------------------- ### state[](https://viem.sh/docs/actions/test/loadState#state) * **Type:** `Hex` The state as a data blob. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/loadState.md) Copy page for AI Ask AI... ⌘ I --- # Introduction to Wallet Actions · Viem [Skip to content](https://viem.sh/docs/actions/wallet/introduction#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Introduction to Wallet Actions ============================== A brief introduction to Wallet Actions in viem. Wallet Actions are actions that map one-to-one with a "wallet" or "signable" Ethereum RPC method (`eth_requestAccounts`, `eth_sendTransaction`, etc). They are used with a [Wallet Client](https://viem.sh/docs/clients/wallet) . Wallet Actions require special permissions and provide signing capabilities. Examples of Wallet Actions include [retrieving the user's account addresses](https://viem.sh/docs/actions/wallet/getAddresses) , [sending a transaction](https://viem.sh/docs/actions/wallet/sendTransaction) , and [signing a message](https://viem.sh/docs/actions/wallet/signMessage) . Wallet Actions provide a secure and flexible way to access the user's accounts and perform actions on the Ethereum network. They are commonly used by dapps and other applications that need to execute transactions, interact with smart contracts, or sign messages. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/introduction.md) Copy page for AI Ask AI... ⌘ I --- # getProof · Viem [Skip to content](https://viem.sh/docs/actions/public/getProof#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getProof ======== Returns the account and storage values of the specified account including the Merkle-proof. Usage[](https://viem.sh/docs/actions/public/getProof#usage) ------------------------------------------------------------ example.tsclient.ts import { publicClient } from './client' const proof = await publicClient.getProof({ address: '0x4200000000000000000000000000000000000016', storageKeys: [\ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99',\ ], }) Returns[](https://viem.sh/docs/actions/public/getProof#returns) ---------------------------------------------------------------- `Proof` Proof data. Parameters[](https://viem.sh/docs/actions/public/getProof#parameters) ---------------------------------------------------------------------- ### address[](https://viem.sh/docs/actions/public/getProof#address) * **Type:** `bigint` Account address. const proof = await publicClient.getProof({ address: '0x4200000000000000000000000000000000000016', storageKeys: [\ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99',\ ], blockNumber: 42069n }) ### storageKeys[](https://viem.sh/docs/actions/public/getProof#storagekeys) * **Type:** `Hash[]` Array of storage-keys that should be proofed and included. const proof = await publicClient.getProof({ address: '0x4200000000000000000000000000000000000016', storageKeys: [ \ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99',\ ], blockNumber: 42069n }) ### blockNumber (optional)[](https://viem.sh/docs/actions/public/getProof#blocknumber-optional) * **Type:** `bigint` Proof at a given block number. const proof = await publicClient.getProof({ address: '0x4200000000000000000000000000000000000016', storageKeys: [\ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99',\ ], blockNumber: 42069n }) ### blockTag (optional)[](https://viem.sh/docs/actions/public/getProof#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` Proof at a given block tag. const proof = await publicClient.getProof({ address: '0x4200000000000000000000000000000000000016', storageKeys: [\ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99',\ ], blockTag: 'latest' }) JSON-RPC Method[](https://viem.sh/docs/actions/public/getProof#json-rpc-method) -------------------------------------------------------------------------------- * Calls `[eth_getProof](https://eips.ethereum.org/EIPS/eip-1186) `. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getProof.md) Copy page for AI Ask AI... ⌘ I --- # increaseTime · Viem [Skip to content](https://viem.sh/docs/actions/test/increaseTime#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K increaseTime ============ Jump forward in time by the given amount of time, in seconds. Usage[](https://viem.sh/docs/actions/test/increaseTime#usage) -------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.increaseTime({ seconds: 420, }) Parameters[](https://viem.sh/docs/actions/test/increaseTime#parameters) ------------------------------------------------------------------------ ### seconds[](https://viem.sh/docs/actions/test/increaseTime#seconds) * **Type:** `number` The amount of seconds to jump forward in time. await testClient.increaseTime({ seconds: 20, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/increaseTime.md) Copy page for AI Ask AI... ⌘ I --- # removeBlockTimestampInterval · Viem [Skip to content](https://viem.sh/docs/actions/test/removeBlockTimestampInterval#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K removeBlockTimestampInterval ============================ Removes `[setBlockTimestampInterval](https://viem.sh/docs/actions/test/setBlockTimestampInterval) ` if it exists. Usage[](https://viem.sh/docs/actions/test/removeBlockTimestampInterval#usage) ------------------------------------------------------------------------------ example.tsclient.ts import { testClient } from './client' await testClient.removeBlockTimestampInterval() [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/removeBlockTimestampInterval.md) Copy page for AI Ask AI... ⌘ I --- # getAddresses · Viem [Skip to content](https://viem.sh/docs/actions/wallet/getAddresses#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getAddresses ============ Returns a list of account addresses owned by the wallet or client. Usage[](https://viem.sh/docs/actions/wallet/getAddresses#usage) ---------------------------------------------------------------- example.tsclient.ts import { walletClient } from './client' const accounts = await walletClient.getAddresses() // ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] Returns[](https://viem.sh/docs/actions/wallet/getAddresses#returns) -------------------------------------------------------------------- `[Address[]](https://viem.sh/docs/glossary/types#address) ` A list of checksummed addresses. JSON-RPC Methods[](https://viem.sh/docs/actions/wallet/getAddresses#json-rpc-methods) -------------------------------------------------------------------------------------- `[eth_accounts](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_accounts) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/getAddresses.md) Copy page for AI Ask AI... ⌘ I --- # requestPermissions · Viem [Skip to content](https://viem.sh/docs/actions/wallet/requestPermissions#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K requestPermissions ================== Requests permissions for a wallet. Usage[](https://viem.sh/docs/actions/wallet/requestPermissions#usage) ---------------------------------------------------------------------- example.tsclient.ts import { walletClient } from './client' const permissions = await walletClient.requestPermissions({ eth_accounts: {} }) Returns[](https://viem.sh/docs/actions/wallet/requestPermissions#returns) -------------------------------------------------------------------------- `[WalletPermission[]](https://viem.sh/docs/glossary/types#walletpermission) ` The wallet permissions. JSON-RPC Methods[](https://viem.sh/docs/actions/wallet/requestPermissions#json-rpc-methods) -------------------------------------------------------------------------------------------- `[wallet_requestPermissions](https://eips.ethereum.org/EIPS/eip-2255) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/requestPermissions.md) Copy page for AI Ask AI... ⌘ I --- # ZKsync · Viem [Skip to content](https://viem.sh/docs/chains/zksync#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K ZKsync ====== Integrating with ZKsync in Viem Viem provides first-class support for chains implemented on [ZKsync](https://zksync.io/) . Chains[](https://viem.sh/docs/chains/zksync#chains) ---------------------------------------------------- The following Viem chains are implemented on ZKsync: import { zksync, zksyncSepoliaTestnet, } from 'viem/chains' ### Configuration[](https://viem.sh/docs/chains/zksync#configuration) Viem exports ZKsync's chain [formatters](https://viem.sh/docs/chains/formatters) & [serializers](https://viem.sh/docs/chains/serializers) via `chainConfig`. This is useful if you need to define another chain which is implemented on ZKsync. import { defineChain } from 'viem' import { chainConfig } from 'viem/zksync' export const zkSyncExample = defineChain({ ...chainConfig, name: 'ZKsync Example', // ... }) Utilities[](https://viem.sh/docs/chains/zksync#utilities) ---------------------------------------------------------- ### `serializeTransaction`[](https://viem.sh/docs/chains/zksync#serializetransaction) Serializes a transaction object. Supports EIP-712, EIP-1559, EIP-2930, and Legacy transactions. ZKsync-flavored version of [Viem's `serializeTransaction`](https://viem.sh/docs/utilities/serializeTransaction) . #### Parameters[](https://viem.sh/docs/chains/zksync#parameters) * `transaction` (`TransactionSerializable`): The transaction object to serialize. * `signature` (`Signature`): Optional signature to include. import { serializeTransaction } from 'viem/zksync' const serialized = serializeTransaction({ chainId: 1, gas: 21001n, maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), nonce: 69, paymaster: '0x4B5DF730c2e6b28E17013A1485E5d9BC41Efe021', paymasterInput: '0x8c5a344500000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000', to: '0x1234512345123451234512345123451234512345', type: 'eip712', value: parseEther('0.01'), }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/chains/zksync.md) Copy page for AI Ask AI... ⌘ I --- # getTransactionConfirmations · Viem [Skip to content](https://viem.sh/docs/actions/public/getTransactionConfirmations#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getTransactionConfirmations =========================== Returns the number of blocks passed (confirmations) since the transaction was processed on a block. Usage[](https://viem.sh/docs/actions/public/getTransactionConfirmations#usage) ------------------------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const transactionReceipt = await publicClient.getTransactionReceipt({ hash: '...' }) const confirmations = await publicClient.getTransactionConfirmations({ transactionReceipt }) // 15n You can also fetch confirmations by Transaction hash: example.tsclient.ts import { publicClient } from './client' const confirmations = await publicClient.getTransactionConfirmations({ hash: '0x...' }) 15n Returns[](https://viem.sh/docs/actions/public/getTransactionConfirmations#returns) ----------------------------------------------------------------------------------- `bigint` The number of blocks passed since the transaction was processed. If confirmations is `0`, then the Transaction has not been confirmed & processed yet. Parameters[](https://viem.sh/docs/actions/public/getTransactionConfirmations#parameters) ----------------------------------------------------------------------------------------- ### transactionReceipt[](https://viem.sh/docs/actions/public/getTransactionConfirmations#transactionreceipt) * **Type:** `[TransactionReceipt](https://viem.sh/docs/glossary/types#transactionreceipt) ` The transaction receipt. const balance = await publicClient.getTransactionConfirmations({ transactionReceipt: { ... }, }) ### hash[](https://viem.sh/docs/actions/public/getTransactionConfirmations#hash) * **Type:** `[Hash](https://viem.sh/docs/glossary/types#hash) ` The hash of the transaction. const balance = await publicClient.getTransactionConfirmations({ hash: '0x...' }) Example[](https://viem.sh/docs/actions/public/getTransactionConfirmations#example) ----------------------------------------------------------------------------------- Check out the usage of `getTransactionConfirmations` in the live [Fetching Transactions Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions) below. JSON-RPC Method[](https://viem.sh/docs/actions/public/getTransactionConfirmations#json-rpc-method) --------------------------------------------------------------------------------------------------- `[eth_getTransactionConfirmations](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionConfirmations) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getTransactionConfirmations.md) Copy page for AI Ask AI... ⌘ I --- # impersonateAccount · Viem [Skip to content](https://viem.sh/docs/actions/test/impersonateAccount#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K 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. Usage[](https://viem.sh/docs/actions/test/impersonateAccount#usage) -------------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.impersonateAccount({ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC' }) Parameters[](https://viem.sh/docs/actions/test/impersonateAccount#parameters) ------------------------------------------------------------------------------ ### address[](https://viem.sh/docs/actions/test/impersonateAccount#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The address of the target account. await testClient.impersonateAccount({ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/impersonateAccount.md) Copy page for AI Ask AI... ⌘ I --- # mine · Viem [Skip to content](https://viem.sh/docs/actions/test/mine#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K mine ==== Mine a specified number of blocks. Usage[](https://viem.sh/docs/actions/test/mine#usage) ------------------------------------------------------ example.tsclient.ts import { testClient } from './client' await testClient.mine({ blocks: 1, }) Parameters[](https://viem.sh/docs/actions/test/mine#parameters) ---------------------------------------------------------------- ### blocks[](https://viem.sh/docs/actions/test/mine#blocks) * **Type:** `number` Number of blocks to mine. await testClient.mine({ blocks: 1, }) ### interval (optional)[](https://viem.sh/docs/actions/test/mine#interval-optional) * **Type:** `number` * **Default:** `1` Interval between each block in seconds. await testClient.mine({ blocks: 10, interval: 4 }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/mine.md) Copy page for AI Ask AI... ⌘ I --- # getCallsStatus · Viem [Skip to content](https://viem.sh/docs/actions/wallet/getCallsStatus#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getCallsStatus ============== Returns the status of a call batch that was sent via `sendCalls`. [Read more](https://eips.ethereum.org/EIPS/eip-5792#wallet_getcallsstatus) Usage[](https://viem.sh/docs/actions/wallet/getCallsStatus#usage) ------------------------------------------------------------------ example.tsconfig.ts import { walletClient } from './config' const result = await walletClient.getCallsStatus({ id: '0x1234567890abcdef', }) } Returns[](https://viem.sh/docs/actions/wallet/getCallsStatus#returns) ---------------------------------------------------------------------- `WalletGetCallsStatusReturnType` Status of the calls. Parameters[](https://viem.sh/docs/actions/wallet/getCallsStatus#parameters) ---------------------------------------------------------------------------- ### id[](https://viem.sh/docs/actions/wallet/getCallsStatus#id) * **Type:** `string` Identifier of the call batch. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/getCallsStatus.mdx) Copy page for AI Ask AI... ⌘ I --- # requestAddresses · Viem [Skip to content](https://viem.sh/docs/actions/wallet/requestAddresses#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K requestAddresses ================ Requests a list of accounts managed by a wallet. `requestAddresses` 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. Usage[](https://viem.sh/docs/actions/wallet/requestAddresses#usage) -------------------------------------------------------------------- example.tsclient.ts import { walletClient } from './client' const accounts = await walletClient.requestAddresses() // ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] Returns[](https://viem.sh/docs/actions/wallet/requestAddresses#returns) ------------------------------------------------------------------------ `[Address[]](https://viem.sh/docs/glossary/types#address) ` JSON-RPC Methods[](https://viem.sh/docs/actions/wallet/requestAddresses#json-rpc-methods) ------------------------------------------------------------------------------------------ `[eth_requestAccounts](https://eips.ethereum.org/EIPS/eip-1102) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/requestAddresses.md) Copy page for AI Ask AI... ⌘ I --- # uninstallFilter · Viem [Skip to content](https://viem.sh/docs/actions/public/uninstallFilter#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K uninstallFilter =============== Destroys a `[Filter](https://viem.sh/docs/glossary/types#filter) ` that was created from one of the following Actions: * `[createBlockFilter](https://viem.sh/docs/actions/public/createBlockFilter) ` * `[createEventFilter](https://viem.sh/docs/actions/public/createEventFilter) ` * `[createPendingTransactionFilter](https://viem.sh/docs/actions/public/createPendingTransactionFilter) ` Usage[](https://viem.sh/docs/actions/public/uninstallFilter#usage) ------------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const filter = await publicClient.createPendingTransactionFilter() const uninstalled = await publicClient.uninstallFilter({ filter }) // true Returns[](https://viem.sh/docs/actions/public/uninstallFilter#returns) ----------------------------------------------------------------------- `boolean` A boolean indicating if the Filter was successfully uninstalled. Parameters[](https://viem.sh/docs/actions/public/uninstallFilter#parameters) ----------------------------------------------------------------------------- ### filter[](https://viem.sh/docs/actions/public/uninstallFilter#filter) * **Type:** `[Filter](https://viem.sh/docs/glossary/terms#filter) ` A created filter. const filter = await publicClient.createPendingTransactionFilter() const uninstalled = await publicClient.uninstallFilter({ filter, }) JSON-RPC Method[](https://viem.sh/docs/actions/public/uninstallFilter#json-rpc-method) --------------------------------------------------------------------------------------- `[eth_uninstallFilter](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_uninstallFilter) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/uninstallFilter.md) Copy page for AI Ask AI... ⌘ I --- # reset · Viem [Skip to content](https://viem.sh/docs/actions/test/reset#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K reset ===== Resets the fork back to its original state. Usage[](https://viem.sh/docs/actions/test/reset#usage) ------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.reset() Parameters[](https://viem.sh/docs/actions/test/reset#parameters) ----------------------------------------------------------------- ### blockNumber (optional)[](https://viem.sh/docs/actions/test/reset#blocknumber-optional) * **Type:** `bigint` Resets the fork to a given block number. await testClient.reset({ blockNumber: 69420n, jsonRpcUrl: 'https://1.rpc.thirdweb.com' }) ### jsonRpcUrl (optional)[](https://viem.sh/docs/actions/test/reset#jsonrpcurl-optional) * **Type:** `string` Resets the fork with a given JSON RPC URL. await testClient.reset({ blockNumber: 69420n, jsonRpcUrl: 'https://1.rpc.thirdweb.com' }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/reset.md) Copy page for AI Ask AI... ⌘ I --- # estimateGas · Viem [Skip to content](https://viem.sh/docs/actions/public/estimateGas#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K estimateGas =========== An Action for estimating gas for a transaction. Estimates the gas necessary to complete a transaction without submitting it to the network. Usage[](https://viem.sh/docs/actions/public/estimateGas#usage) --------------------------------------------------------------- example.tsconfig.ts import { account, publicClient } from './config' const gas = await publicClient.estimateGas({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) Returns[](https://viem.sh/docs/actions/public/estimateGas#returns) ------------------------------------------------------------------- `bigint` The gas estimate (in gas). Parameters[](https://viem.sh/docs/actions/public/estimateGas#parameters) ------------------------------------------------------------------------- ### account[](https://viem.sh/docs/actions/public/estimateGas#account) * **Type:** `Account | Address` The Account to estimate gas from. Accepts a [JSON-RPC Account](https://viem.sh/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . import { parseEther } from 'viem' const gas = await publicClient.estimateGas({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### data (optional)[](https://viem.sh/docs/actions/public/estimateGas#data-optional) * **Type:** `0x${string}` Contract code or a hashed method call with encoded args which can be generated using [encodeFunctionData](https://viem.sh/docs/contract/encodeFunctionData) . import { parseEther } from 'viem' const gas = await publicClient.estimateGas({ data: '0x...', account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### gasPrice (optional)[](https://viem.sh/docs/actions/public/estimateGas#gasprice-optional) * **Type:** `bigint` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction) . import { parseEther, parseGwei } from 'viem' const gas = await publicClient.estimateGas({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', gasPrice: parseGwei('20'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### maxFeePerGas (optional)[](https://viem.sh/docs/actions/public/estimateGas#maxfeepergas-optional) * **Type:** `bigint` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) import { parseEther, parseGwei } from 'viem' const gas = await publicClient.estimateGas({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', maxFeePerGas: parseGwei('20'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### maxPriorityFeePerGas (optional)[](https://viem.sh/docs/actions/public/estimateGas#maxpriorityfeepergas-optional) * **Type:** `bigint` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) import { parseEther, parseGwei } from 'viem' const gas = await publicClient.estimateGas({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### to (optional)[](https://viem.sh/docs/actions/public/estimateGas#to-optional) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` Transaction recipient. import { parseEther } from 'viem' const gas = await publicClient.estimateGas({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### value (optional)[](https://viem.sh/docs/actions/public/estimateGas#value-optional) * **Type:** `bigint` Value (in wei) sent with this transaction. import { parseEther } from 'viem' const gas = await publicClient.estimateGas({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### blockNumber (optional)[](https://viem.sh/docs/actions/public/estimateGas#blocknumber-optional) * **Type:** `number` The block number to perform the gas estimate against. import { parseEther } from 'viem' const gas = await publicClient.estimateGas({ blockNumber: 15121123n, account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### blockTag (optional)[](https://viem.sh/docs/actions/public/estimateGas#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` The block tag to perform the gas estimate against. import { parseEther } from 'viem' const gas = await publicClient.estimateGas({ blockTag: 'safe', account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### stateOverride (optional)[](https://viem.sh/docs/actions/public/estimateGas#stateoverride-optional) * **Type:** `[StateOverride](https://viem.sh/docs/glossary/types#stateoverride) ` The state override set is an optional address-to-state mapping, where each entry specifies some state to be ephemerally overridden prior to executing the call. const data = await publicClient.estimateGas({ account, data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', stateOverride: [ \ { \ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ balance: parseEther('1'), \ stateDiff: [ \ { \ slot: '0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0', \ value: '0x00000000000000000000000000000000000000000000000000000000000001a4', \ }, \ ], \ } \ ], }) JSON-RPC Methods[](https://viem.sh/docs/actions/public/estimateGas#json-rpc-methods) ------------------------------------------------------------------------------------- `[eth_estimateGas](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/estimateGas.md) Copy page for AI Ask AI... ⌘ I --- # getTransaction · Viem [Skip to content](https://viem.sh/docs/actions/public/getTransaction#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getTransaction ============== Returns information about a [Transaction](https://viem.sh/docs/glossary/terms#transaction) given a hash or block identifier. Usage[](https://viem.sh/docs/actions/public/getTransaction#usage) ------------------------------------------------------------------ example.tsclient.ts import { publicClient } from './client' const transaction = await publicClient.getTransaction({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d' }) } Returns[](https://viem.sh/docs/actions/public/getTransaction#returns) ---------------------------------------------------------------------- `[Transaction](https://viem.sh/docs/glossary/types#transaction) ` The transaction information. Parameters[](https://viem.sh/docs/actions/public/getTransaction#parameters) ---------------------------------------------------------------------------- ### hash (optional)[](https://viem.sh/docs/actions/public/getTransaction#hash-optional) * **Type:** `'0x${string}'` Get information about a transaction given a transaction hash. const transaction = await publicClient.getTransaction({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d' }) ### blockHash (optional)[](https://viem.sh/docs/actions/public/getTransaction#blockhash-optional) * **Type:** `'0x${string}'` Get information about a transaction given a block hash (and index). const transaction = await publicClient.getTransaction({ blockHash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', index: 0 }) ### blockNumber (optional)[](https://viem.sh/docs/actions/public/getTransaction#blocknumber-optional) * **Type:** `'0x${string}'` Get information about a transaction given a block number (and index). const transaction = await publicClient.getTransaction({ blockNumber: 69420n, index: 0 }) ### blockTag (optional)[](https://viem.sh/docs/actions/public/getTransaction#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` Get information about a transaction given a block tag (and index). const transaction = await publicClient.getTransaction({ blockTag: 'safe', index: 0 }) ### index (optional)[](https://viem.sh/docs/actions/public/getTransaction#index-optional) * **Type:** `number` An index to be used with a block identifier (number, hash or tag). const transaction = await publicClient.getTransaction({ blockTag: 'safe', index: 0 }) Example[](https://viem.sh/docs/actions/public/getTransaction#example) ---------------------------------------------------------------------- Check out the usage of `getTransaction` in the live [Fetching Transactions Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions) below. JSON-RPC Method[](https://viem.sh/docs/actions/public/getTransaction#json-rpc-method) -------------------------------------------------------------------------------------- `[eth_getTransactionByHash](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionByHash) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getTransaction.md) Copy page for AI Ask AI... ⌘ I --- # setBalance · Viem [Skip to content](https://viem.sh/docs/actions/test/setBalance#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K setBalance ========== Modifies the balance of an account. Usage[](https://viem.sh/docs/actions/test/setBalance#usage) ------------------------------------------------------------ example.tsclient.ts import { parseEther } from 'viem' import { testClient } from './client' await testClient.setBalance({ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', value: parseEther('1') }) Parameters[](https://viem.sh/docs/actions/test/setBalance#parameters) ---------------------------------------------------------------------- ### address[](https://viem.sh/docs/actions/test/setBalance#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The address of the target account. await testClient.setBalance({ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', value: parseEther('1') }) ### value (optional)[](https://viem.sh/docs/actions/test/setBalance#value-optional) * **Type:** `bigint` The value (in wei) to set. await testClient.setBalance({ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', value: 1000000000000000000n }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/setBalance.md) Copy page for AI Ask AI... ⌘ I --- # revert · Viem [Skip to content](https://viem.sh/docs/actions/test/revert#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K revert ====== Revert the state of the blockchain at the current block. Usage[](https://viem.sh/docs/actions/test/revert#usage) -------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.revert({ id: '0x...' }) Parameters[](https://viem.sh/docs/actions/test/revert#parameters) ------------------------------------------------------------------ ### id[](https://viem.sh/docs/actions/test/revert#id) * **Type:** `"0x${string}"` The snapshot ID. await testClient.revert({ id: '0x...' }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/revert.md) Copy page for AI Ask AI... ⌘ I --- # setBlockGasLimit · Viem [Skip to content](https://viem.sh/docs/actions/test/setBlockGasLimit#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K setBlockGasLimit ================ Sets the block's gas limit. Usage[](https://viem.sh/docs/actions/test/setBlockGasLimit#usage) ------------------------------------------------------------------ example.tsclient.ts import { testClient } from './client' await testClient.setBlockGasLimit({ gasLimit: 420_000n }) Parameters[](https://viem.sh/docs/actions/test/setBlockGasLimit#parameters) ---------------------------------------------------------------------------- ### gasLimit[](https://viem.sh/docs/actions/test/setBlockGasLimit#gaslimit) * **Type:** `bigint` The gas limit. await testClient.setBlockGasLimit({ gasLimit: 420_000n }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/setBlockGasLimit.md) Copy page for AI Ask AI... ⌘ I --- # setAutomine · Viem [Skip to content](https://viem.sh/docs/actions/test/setAutomine#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K setAutomine =========== Enables or disables the automatic mining of new blocks with each new transaction submitted to the network. Usage[](https://viem.sh/docs/actions/test/setAutomine#usage) ------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.setAutomine(true) Parameters[](https://viem.sh/docs/actions/test/setAutomine#parameters) ----------------------------------------------------------------------- ### enabled[](https://viem.sh/docs/actions/test/setAutomine#enabled) * **Type:** `boolean` await testClient.setAutomine(false) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/setAutomine.md) Copy page for AI Ask AI... ⌘ I --- # getCapabilities · Viem [Skip to content](https://viem.sh/docs/actions/wallet/getCapabilities#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getCapabilities =============== Extract capabilities (grouped by chain ID) that a connected wallet supports (e.g. paymasters, session keys, etc). [Read more](https://github.com/ethereum/EIPs/blob/815028dc634463e1716fc5ce44c019a6040f0bef/EIPS/eip-5792.md#wallet_getcapabilities) Usage[](https://viem.sh/docs/actions/wallet/getCapabilities#usage) ------------------------------------------------------------------- example.tsconfig.ts import { account, walletClient } from './config' const capabilities = await walletClient.getCapabilities({ account, }) } ### Account Hoisting[](https://viem.sh/docs/actions/wallet/getCapabilities#account-hoisting) If you do not wish to pass an `account` to every `getCapabilities`, you can also hoist the Account on the Wallet Client (see `config.ts`). [Learn more](https://viem.sh/docs/clients/wallet#account) . example.tsconfig.ts import { walletClient } from './config' const capabilities = await walletClient.getCapabilities() Returns[](https://viem.sh/docs/actions/wallet/getCapabilities#returns) ----------------------------------------------------------------------- `WalletCapabilities` Capabilities of the wallet. Parameters[](https://viem.sh/docs/actions/wallet/getCapabilities#parameters) ----------------------------------------------------------------------------- ### account[](https://viem.sh/docs/actions/wallet/getCapabilities#account) * **Type:** `Address` The account to get capabilities for. example.ts const capabilities = await walletClient.getCapabilities({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', }) ### chainId[](https://viem.sh/docs/actions/wallet/getCapabilities#chainid) * **Type:** `number` The chain ID to get capabilities for. example.ts const capabilities = await walletClient.getCapabilities({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', chainId: 8453, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/getCapabilities.mdx) Copy page for AI Ask AI... ⌘ I --- # addChain · Viem [Skip to content](https://viem.sh/docs/actions/wallet/addChain#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K addChain ======== Adds an EVM chain to the wallet. Usage[](https://viem.sh/docs/actions/wallet/addChain#usage) ------------------------------------------------------------ example.tsclient.ts import { avalanche } from 'viem/chains' import { walletClient } from './client' await walletClient.addChain({ chain: avalanche }) Parameters[](https://viem.sh/docs/actions/wallet/addChain#parameters) ---------------------------------------------------------------------- ### chain[](https://viem.sh/docs/actions/wallet/addChain#chain) * **Type:** `[Chain](https://viem.sh/docs/glossary/types#chain) ` The chain to add to the wallet. JSON-RPC Methods[](https://viem.sh/docs/actions/wallet/addChain#json-rpc-methods) ---------------------------------------------------------------------------------- `[wallet_addEtherereumChain](https://eips.ethereum.org/EIPS/eip-3085) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/addChain.md) Copy page for AI Ask AI... ⌘ I --- # setBlockTimestampInterval · Viem [Skip to content](https://viem.sh/docs/actions/test/setBlockTimestampInterval#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K setBlockTimestampInterval ========================= Similar to `[increaseTime](https://viem.sh/docs/actions/test/increaseTime) `, but sets a block timestamp `interval`. The timestamp of future blocks will be computed as `lastBlock_timestamp` + `interval`. Usage[](https://viem.sh/docs/actions/test/setBlockTimestampInterval#usage) --------------------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.setBlockTimestampInterval({ interval: 5 }) Parameters[](https://viem.sh/docs/actions/test/setBlockTimestampInterval#parameters) ------------------------------------------------------------------------------------- ### interval[](https://viem.sh/docs/actions/test/setBlockTimestampInterval#interval) * **Type:** `number` await testClient.setBlockTimestampInterval({ interval: 1 }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/setBlockTimestampInterval.md) Copy page for AI Ask AI... ⌘ I --- # setCode · Viem [Skip to content](https://viem.sh/docs/actions/test/setCode#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K setCode ======= Modifies the bytecode stored at an account's address. Usage[](https://viem.sh/docs/actions/test/setCode#usage) --------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.setCode({ address: '0xe846c6fcf817734ca4527b28ccb4aea2b6663c79', bytecode: '0x60806040526000600355600019600955600c80546001600160a01b031916737a250d5630b4cf539739df...' }) Parameters[](https://viem.sh/docs/actions/test/setCode#parameters) ------------------------------------------------------------------- ### address[](https://viem.sh/docs/actions/test/setCode#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The account address. await testClient.setCode({ address: '0xe846c6fcf817734ca4527b28ccb4aea2b6663c79', bytecode: '0x60806040526000600355600019600955600c80546001600160a01b031916737a250d5630b4cf539739df...' }) ### bytecode[](https://viem.sh/docs/actions/test/setCode#bytecode) * **Type:** `[Hex](https://viem.sh/docs/glossary/types#hex) ` The stored bytecode. await testClient.setCode({ address: '0xe846c6fcf817734ca4527b28ccb4aea2b6663c79', bytecode: '0x60806040526000600355600019600955600c80546001600160a01b031916737a250d5630b4cf539739df...' }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/setCode.md) Copy page for AI Ask AI... ⌘ I --- # sendRawTransactionSync · Viem [Skip to content](https://viem.sh/docs/actions/wallet/sendRawTransactionSync#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K sendRawTransactionSync ====================== Sends a **signed** transaction to the network, and waits for the transaction to be included in a block. Usage[](https://viem.sh/docs/actions/wallet/sendRawTransactionSync#usage) -------------------------------------------------------------------------- example.tsconfig.ts import { account, walletClient } from './config' const request = await walletClient.prepareTransactionRequest({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) const serializedTransaction = await walletClient.signTransaction(request) const receipt = await walletClient.sendRawTransactionSync({ serializedTransaction }) Returns[](https://viem.sh/docs/actions/wallet/sendRawTransactionSync#returns) ------------------------------------------------------------------------------ `[TransactionReceipt](https://viem.sh/docs/glossary/types#transaction-receipt) ` The [Transaction receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) . Parameters[](https://viem.sh/docs/actions/wallet/sendRawTransactionSync#parameters) ------------------------------------------------------------------------------------ ### serializedTransaction[](https://viem.sh/docs/actions/wallet/sendRawTransactionSync#serializedtransaction) * **Type:** `Hex` The signed serialized transaction. const signature = await walletClient.sendRawTransaction({ serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33' }) ### throwOnReceiptRevert (optional)[](https://viem.sh/docs/actions/wallet/sendRawTransactionSync#throwonreceiptrevert-optional) * **Type:** `boolean` Whether to throw an error if the transaction was detected as reverted. const receipt = await walletClient.sendRawTransactionSync({ serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33', throwOnReceiptRevert: true }) ### timeout (optional)[](https://viem.sh/docs/actions/wallet/sendRawTransactionSync#timeout-optional) * **Type:** `number` Timeout for the transaction to be included in a block. const receipt = await walletClient.sendRawTransactionSync({ serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33', timeout: 20_000 }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/sendRawTransactionSync.md) Copy page for AI Ask AI... ⌘ I --- # Serializers · Viem [Skip to content](https://viem.sh/docs/chains/serializers#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Serializers =========== Configure chain-based serializers in Viem Usage[](https://viem.sh/docs/chains/serializers#usage) ------------------------------------------------------- import { defineChain, serializeTransaction } from 'viem' const example = defineChain({ /* ... */ serializers: { transaction(transaction, signature) { return serializeTransaction(transaction, signature) }, }, }) API[](https://viem.sh/docs/chains/serializers#api) --------------------------------------------------- ### `serializers.transaction`[](https://viem.sh/docs/chains/serializers#serializerstransaction) * **Type**: `(transaction: Transaction, signature?: Signature) => "0x${string}"` You can modify how Transactions are serialized by using the `serializers.transaction` property on the Chain. **Parameters** * `transaction`: The transaction to serialize. * `signature`: The transaction signature (if exists). import { defineChain, serializeTransaction } from 'viem' const example = defineChain({ /* ... */ serializers: { transaction(transaction, signature) { return serializeTransaction(transaction, signature) }, }, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/chains/serializers.md) Copy page for AI Ask AI... ⌘ I --- # snapshot · Viem [Skip to content](https://viem.sh/docs/actions/test/snapshot#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K snapshot ======== Snapshot the state of the blockchain at the current block. Usage[](https://viem.sh/docs/actions/test/snapshot#usage) ---------------------------------------------------------- example.tsclient.ts import { testClient } from './client' const id = await testClient.snapshot() Returns[](https://viem.sh/docs/actions/test/snapshot#returns) -------------------------------------------------------------- ID of the snapshot that was created. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/snapshot.md) Copy page for AI Ask AI... ⌘ I --- # IPC Transport · Viem [Skip to content](https://viem.sh/docs/clients/transports/ipc#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K IPC Transport ============= A function to create an IPC Transport for a Client The `ipc` Transport connects to a JSON-RPC API via IPC (inter-process communication). Import[](https://viem.sh/docs/clients/transports/ipc#import) ------------------------------------------------------------- import { ipc } from 'viem/node' Usage[](https://viem.sh/docs/clients/transports/ipc#usage) ----------------------------------------------------------- import { createPublicClient } from 'viem' import { ipc } from 'viem/node' import { mainnet } from 'viem/chains' const client = createPublicClient({ chain: mainnet, transport: ipc('/tmp/reth.ipc'), }) Parameters[](https://viem.sh/docs/clients/transports/ipc#parameters) --------------------------------------------------------------------- ### path[](https://viem.sh/docs/clients/transports/ipc#path) * **Type:** `string` IPC Path the transport should connect to. const transport = ipc('/tmp/reth.ipc') ### key (optional)[](https://viem.sh/docs/clients/transports/ipc#key-optional) * **Type:** `string` * **Default:** `"ipc"` A key for the Transport. const transport = ipc('/tmp/reth.ipc', { key: 'reth-ipc', }) ### methods (optional)[](https://viem.sh/docs/clients/transports/ipc#methods-optional) * **Type:** `{ include?: string[], exclude?: string[] }` Methods to include or exclude from sending RPC requests. const transport = ipc('/tmp/reth.ipc', { methods: { include: ['eth_sendTransaction', 'eth_signTypedData_v4'], }, }) ### name (optional)[](https://viem.sh/docs/clients/transports/ipc#name-optional) * **Type:** `string` * **Default:** `"IPC JSON-RPC"` A name for the Transport const transport = ipc('/tmp/reth.ipc', { name: 'Reth IPC', }) ### reconnect (optional)[](https://viem.sh/docs/clients/transports/ipc#reconnect-optional) * **Type:** `boolean | { maxAttempts?: number, delay?: number }` * **Default:** `true` Whether or not to attempt to reconnect on socket failure. const transport = ipc('/tmp/reth.ipc', { reconnect: false, }) #### reconnect.attempts (optional)[](https://viem.sh/docs/clients/transports/ipc#reconnectattempts-optional) * **Type:** `number` * **Default:** `5` The max number of times to attempt to reconnect. const transport = ipc('/tmp/reth.ipc', { reconnect: { attempts: 10, } }) #### reconnect.delay (optional)[](https://viem.sh/docs/clients/transports/ipc#reconnectdelay-optional) * **Type:** `number` * **Default:** `2_000` Retry delay (in ms) between reconnect attempts. const transport = ipc('/tmp/reth.ipc', { reconnect: { delay: 1_000, } }) ### retryCount (optional)[](https://viem.sh/docs/clients/transports/ipc#retrycount-optional) * **Type:** `number` * **Default:** `3` The max number of times to retry when a request fails. const transport = ipc('/tmp/reth.ipc', { retryCount: 5, }) ### retryDelay (optional)[](https://viem.sh/docs/clients/transports/ipc#retrydelay-optional) * **Type:** `number` * **Default:** `150` The base delay (in ms) between retries. By default, the Transport will use [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff) (`~~(1 << count) * retryDelay`), which means the time between retries is not constant. const transport = ipc('/tmp/reth.ipc', { retryDelay: 100, }) ### timeout (optional)[](https://viem.sh/docs/clients/transports/ipc#timeout-optional) * **Type:** `number` * **Default:** `10_000` The timeout for async IPC requests. const transport = ipc('/tmp/reth.ipc', { timeout: 60_000, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/clients/transports/ipc.md) Copy page for AI Ask AI... ⌘ I --- # inspectTxpool · Viem [Skip to content](https://viem.sh/docs/actions/test/inspectTxpool#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K 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. [Read more](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-txpool) . Usage[](https://viem.sh/docs/actions/test/inspectTxpool#usage) --------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' const data = await testClient.inspectTxpool() Returns[](https://viem.sh/docs/actions/test/inspectTxpool#returns) ------------------------------------------------------------------- Transaction pool inspection data. [See here](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-txpool) . [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/inspectTxpool.md) Copy page for AI Ask AI... ⌘ I --- # setLoggingEnabled · Viem [Skip to content](https://viem.sh/docs/actions/test/setLoggingEnabled#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K setLoggingEnabled ================= Enable or disable logging on the test node network. Usage[](https://viem.sh/docs/actions/test/setLoggingEnabled#usage) ------------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.setLoggingEnabled(true) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/setLoggingEnabled.md) Copy page for AI Ask AI... ⌘ I --- # Why Viem [Skip to content](https://viem.sh/docs/introduction#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Why Viem ======== A brief preamble on why we built Viem The Problems[](https://viem.sh/docs/introduction#the-problems) --------------------------------------------------------------- The current state of low-level Ethereum interface abstractions lack in at least one of the following four areas: **developer experience**, **stability**, **bundle size** and/or **performance** — a quadrilemma. As the authors of [wagmi](https://wagmi.sh/) , a popular React Hooks library for Ethereum, we struggled to work with the existing low-level TypeScript Ethereum libraries. We wanted to provide the users of wagmi with the best possible developer experience, but we were limited by the underlying technologies wagmi was built on. We knew an _always_ stable, predictable implementation with a tiny bundle size and performant modules was paramount to interacting with the world's largest blockchain ecosystem. So we created **viem**: a TypeScript Interface for Ethereum that provides low-level stateless primitives for interacting with Ethereum. An alternative to ethers.js and web3.js with a focus on reliability, efficiency, and excellent developer experience. Developer Experience[](https://viem.sh/docs/introduction#developer-experience) ------------------------------------------------------------------------------- viem delivers a great developer experience through modular and composable APIs, comprehensive documentation, and automatic type safety and inference. It provides developers with intuitive building blocks to build their Ethereum apps and libraries. While viem's APIs may be more verbose than alternative libraries, we believe this is the right trade-off as it makes viem's modular building blocks extremely flexible. Easy to move around, change, and remove. It also allows the developers to better understand Ethereum concepts as well as understand _what_ and _why_ certain properties are being passed through. Learning how to use viem is a great way to learn how to interact with Ethereum in general. We aim to provide extensive API documentation and usage for _every_ module in viem. viem uses a [documentation](https://gist.github.com/zsup/9434452) and [test driven](https://en.wikipedia.org/wiki/Test-driven_development#:~:text=Test%2Ddriven%20development%20(TDD),software%20against%20all%20test%20cases.) development approach to building modules, which leads to predictable and stable APIs. viem also provides consumers with [strongly typed APIs](https://viem.sh/docs/typescript) , allowing consumers to get the best possible experience through [autocomplete](https://twitter.com/awkweb/status/1555678944770367493) , [type inference](https://twitter.com/_jxom/status/1570244174502588417?s=20) , as well as static validation. Stability[](https://viem.sh/docs/introduction#stability) --------------------------------------------------------- Stability is a fundamental principle for viem. As the authors of [wagmi](https://wagmi.sh/) , we have many organizations, large and small, that rely heavily on the library and expect it to be entirely stable for their users. viem takes the following steps to ensure stability: * We run our test suite against a forked Ethereum node * We aim for complete test coverage and test all potential behavioral cases * We build deterministic and pure APIs Bundle Size[](https://viem.sh/docs/introduction#bundle-size) ------------------------------------------------------------- Maintaining a low bundle size is critical when building web applications. End users should not be required to download a module of over 100kB in order to interact with Ethereum. On a slow 3G mobile network loading a 100kB library would take at least **two seconds** (plus additional time to establish an HTTP connection). Furthermore, viem is tree-shakable, meaning only the modules you use are included in your final bundle. ![](https://viem.sh/bench-bundlesize.svg) Performance[](https://viem.sh/docs/introduction#performance) ------------------------------------------------------------- In addition to the fast load times mentioned above, viem further tunes performance by only executing heavy asynchronous tasks when required and optimized encoding/parsing algorithms. The benchmarks speak for themselves: ![](https://viem.sh/bench-isaddress.svg)![](https://viem.sh/bench-parseabi.svg)![](https://viem.sh/bench-encodeabi.svg) Opinions & Escape Hatches[](https://viem.sh/docs/introduction#opinions--escape-hatches) ---------------------------------------------------------------------------------------- Unlike other low-level interfaces that impose opinions on consumers, viem enables consumers to choose their opinions while still maintaining sensible and secure defaults. This allows consumers to create their own opinionated implementations, such as [wagmi](https://wagmi.sh/) , without the need for tedious workarounds. * * * **viem** will help developers build with a higher level of accuracy and correctness through type safety and developer experience. It will also integrate extremely well with [wagmi](https://wagmi.sh/) so folks can start using it without much upfront switching cost. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/introduction.mdx) Copy page for AI Ask AI... ⌘ I --- # showCallsStatus · Viem [Skip to content](https://viem.sh/docs/actions/wallet/showCallsStatus#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K showCallsStatus =============== Requests for the wallet to show information about a call batch that was sent via `sendCalls`. [Read more.](https://github.com/ethereum/EIPs/blob/1663ea2e7a683285f977eda51c32cec86553f585/EIPS/eip-5792.md#wallet_showcallsstatus) Usage[](https://viem.sh/docs/actions/wallet/showCallsStatus#usage) ------------------------------------------------------------------- example.tsconfig.ts import { walletClient } from './config' await walletClient.showCallsStatus({ id: '0x1234567890abcdef', }) Returns[](https://viem.sh/docs/actions/wallet/showCallsStatus#returns) ----------------------------------------------------------------------- `void` Parameters[](https://viem.sh/docs/actions/wallet/showCallsStatus#parameters) ----------------------------------------------------------------------------- ### id[](https://viem.sh/docs/actions/wallet/showCallsStatus#id) * **Type:** `string` Identifier of the call batch. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/showCallsStatus.mdx) Copy page for AI Ask AI... ⌘ I --- # getFilterChanges · Viem [Skip to content](https://viem.sh/docs/actions/public/getFilterChanges#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getFilterChanges ================ Returns a list of logs or hashes based on a [Filter](https://viem.sh/docs/glossary/terms#filter) since the last time it was called. A Filter can be created from the following actions: * `[createBlockFilter](https://viem.sh/docs/actions/public/createBlockFilter) ` * `[createContractEventFilter](https://viem.sh/docs/contract/createContractEventFilter) ` * `[createEventFilter](https://viem.sh/docs/actions/public/createEventFilter) ` * `[createPendingTransactionFilter](https://viem.sh/docs/actions/public/createPendingTransactionFilter) ` Usage[](https://viem.sh/docs/actions/public/getFilterChanges#usage) -------------------------------------------------------------------- ### Blocks[](https://viem.sh/docs/actions/public/getFilterChanges#blocks) example.tsclient.ts import { publicClient } from './client' const filter = await publicClient.createBlockFilter() const hashes = await publicClient.getFilterChanges({ filter }) Output: ["0x10d86dc08ac2f18f00ef0daf7998dcc8673cbcf1f1501eeb2fac1afd2f851128", ...] ### Contract Events[](https://viem.sh/docs/actions/public/getFilterChanges#contract-events) example.tsclient.ts import { publicClient } from './client' const filter = await publicClient.createContractEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', abi: wagmiAbi, eventName: 'Transfer' }) const logs = await publicClient.getFilterChanges({ filter }) Output: [{ ... }, { ... }, { ... }] ### Raw Events[](https://viem.sh/docs/actions/public/getFilterChanges#raw-events) example.tsclient.ts import { parseAbiItem } from 'viem' import { publicClient } from './client' const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'), }) const logs = await publicClient.getFilterChanges({ filter }) Output: [{ ... }, { ... }, { ... }] ### Transactions[](https://viem.sh/docs/actions/public/getFilterChanges#transactions) example.tsclient.ts import { publicClient } from './client' const filter = await publicClient.createPendingTransactionFilter() const hashes = await publicClient.getFilterChanges({ filter }) Output: ["0x89b3aa1c01ca4da5d15eca9fab459d062db5c0c9b76609acb0741901f01f6d19", ...] Returns[](https://viem.sh/docs/actions/public/getFilterChanges#returns) ------------------------------------------------------------------------ `[Log[]](https://viem.sh/docs/glossary/types#log) ` If the filter was created with `createContractEventFilter` or `createEventFilter`, it returns a list of logs. **OR** `"0x${string}"[]` If the filter was created with `createPendingTransactionFilter`, it returns a list of transaction hashes. **OR** `"0x${string}"[]` If the filter was created with `createBlockFilter`, it returns a list of block hashes. Parameters[](https://viem.sh/docs/actions/public/getFilterChanges#parameters) ------------------------------------------------------------------------------ ### filter[](https://viem.sh/docs/actions/public/getFilterChanges#filter) * **Type:** `[Filter](https://viem.sh/docs/glossary/types#filter) ` A created filter. const filter = await publicClient.createPendingTransactionFilter() const logs = await publicClient.getFilterChanges({ filter, }) JSON-RPC Method[](https://viem.sh/docs/actions/public/getFilterChanges#json-rpc-method) ---------------------------------------------------------------------------------------- * Calls `[eth_getFilterChanges](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges) `. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getFilterChanges.md) Copy page for AI Ask AI... ⌘ I --- # setNextBlockTimestamp · Viem [Skip to content](https://viem.sh/docs/actions/test/setNextBlockTimestamp#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K setNextBlockTimestamp ===================== Sets the next block's timestamp. Usage[](https://viem.sh/docs/actions/test/setNextBlockTimestamp#usage) ----------------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.setNextBlockTimestamp({ timestamp: 1671744314n }) Parameters[](https://viem.sh/docs/actions/test/setNextBlockTimestamp#parameters) --------------------------------------------------------------------------------- ### timestamp[](https://viem.sh/docs/actions/test/setNextBlockTimestamp#timestamp) * **Type:** `bigint` await testClient.setNextBlockTimestamp({ timestamp: 1671744314n }) Notes[](https://viem.sh/docs/actions/test/setNextBlockTimestamp#notes) ----------------------------------------------------------------------- * The next Block `timestamp` cannot be lesser than the current Block `timestamp`. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/setNextBlockTimestamp.md) Copy page for AI Ask AI... ⌘ I --- # setRpcUrl · Viem [Skip to content](https://viem.sh/docs/actions/test/setRpcUrl#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K setRpcUrl ========= Sets the backend RPC URL. Usage[](https://viem.sh/docs/actions/test/setRpcUrl#usage) ----------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.setRpcUrl('https://eth-mainnet.g.alchemy.com/v2') [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/setRpcUrl.md) Copy page for AI Ask AI... ⌘ I --- # setCoinbase · Viem [Skip to content](https://viem.sh/docs/actions/test/setCoinbase#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K setCoinbase =========== Sets the coinbase address to be used in new blocks. Usage[](https://viem.sh/docs/actions/test/setCoinbase#usage) ------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.setCoinbase({ address: '0xe846c6fcf817734ca4527b28ccb4aea2b6663c79', }) Parameters[](https://viem.sh/docs/actions/test/setCoinbase#parameters) ----------------------------------------------------------------------- ### address[](https://viem.sh/docs/actions/test/setCoinbase#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The coinbase address. await testClient.setCoinbase({ address: '0xe846c6fcf817734ca4527b28ccb4aea2b6663c79', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/setCoinbase.md) Copy page for AI Ask AI... ⌘ I --- # sendUnsignedTransaction · Viem [Skip to content](https://viem.sh/docs/actions/test/sendUnsignedTransaction#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K sendUnsignedTransaction ======================= Executes a transaction regardless of the signature. Usage[](https://viem.sh/docs/actions/test/sendUnsignedTransaction#usage) ------------------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' const hash = await testClient.sendUnsignedTransaction({ from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) // '0x...' Returns[](https://viem.sh/docs/actions/test/sendUnsignedTransaction#returns) ----------------------------------------------------------------------------- `[Hash](https://viem.sh/docs/glossary/types#hash) ` The transaction hash. Parameters[](https://viem.sh/docs/actions/test/sendUnsignedTransaction#parameters) ----------------------------------------------------------------------------------- ### from[](https://viem.sh/docs/actions/test/sendUnsignedTransaction#from) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The Transaction sender. const hash = await testClient.sendUnsignedTransaction({ from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) ### to[](https://viem.sh/docs/actions/test/sendUnsignedTransaction#to) * **Type:** `number` The transaction recipient or contract address. const hash = await testClient.sendUnsignedTransaction({ from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n, nonce: 69 }) ### accessList (optional)[](https://viem.sh/docs/actions/test/sendUnsignedTransaction#accesslist-optional) * **Type:** `[AccessList](https://viem.sh/docs/glossary/types#accesslist) ` The access list. const data = await testClient.sendUnsignedTransaction({ accessList: [ \ {\ address: '0x1',\ storageKeys: ['0x1'],\ },\ ], from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### data (optional)[](https://viem.sh/docs/actions/test/sendUnsignedTransaction#data-optional) * **Type:** `0x${string}` A contract hashed method call with encoded args. const hash = await testClient.sendUnsignedTransaction({ data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) ### gasPrice (optional)[](https://viem.sh/docs/actions/test/sendUnsignedTransaction#gasprice-optional) * **Type:** `bigint` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction) . const hash = await testClient.sendUnsignedTransaction({ from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', gasPrice: parseGwei('20'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### maxFeePerGas (optional)[](https://viem.sh/docs/actions/test/sendUnsignedTransaction#maxfeepergas-optional) * **Type:** `bigint` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) const hash = await testClient.sendUnsignedTransaction({ from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', maxFeePerGas: parseGwei('20'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### maxPriorityFeePerGas (optional)[](https://viem.sh/docs/actions/test/sendUnsignedTransaction#maxpriorityfeepergas-optional) * **Type:** `bigint` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) const hash = await testClient.sendUnsignedTransaction({ from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### nonce (optional)[](https://viem.sh/docs/actions/test/sendUnsignedTransaction#nonce-optional) * **Type:** `number` Unique number identifying this transaction. const hash = await testClient.sendUnsignedTransaction({ from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n, nonce: 69 }) ### value (optional)[](https://viem.sh/docs/actions/test/sendUnsignedTransaction#value-optional) * **Type:** `number` Value in wei sent with this transaction. const hash = await testClient.sendUnsignedTransaction({ from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), nonce: 69 }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/sendUnsignedTransaction.md) Copy page for AI Ask AI... ⌘ I --- # setNextBlockBaseFeePerGas · Viem [Skip to content](https://viem.sh/docs/actions/test/setNextBlockBaseFeePerGas#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K setNextBlockBaseFeePerGas ========================= Sets the next block's base fee per gas. Usage[](https://viem.sh/docs/actions/test/setNextBlockBaseFeePerGas#usage) --------------------------------------------------------------------------- example.tsclient.ts import { parseGwei } from 'viem' import { testClient } from './client' await testClient.setNextBlockBaseFeePerGas({ baseFeePerGas: parseGwei('20') }) Parameters[](https://viem.sh/docs/actions/test/setNextBlockBaseFeePerGas#parameters) ------------------------------------------------------------------------------------- ### baseFeePerGas[](https://viem.sh/docs/actions/test/setNextBlockBaseFeePerGas#basefeepergas) * **Type:** `bigint` Base fee per gas. await testClient.setNextBlockBaseFeePerGas({ baseFeePerGas: parseGwei('30') }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/setNextBlockBaseFeePerGas.md) Copy page for AI Ask AI... ⌘ I --- # switchChain · Viem [Skip to content](https://viem.sh/docs/actions/wallet/switchChain#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K switchChain =========== Switch the target chain in a wallet. Usage[](https://viem.sh/docs/actions/wallet/switchChain#usage) --------------------------------------------------------------- example.tsclient.ts import { avalanche } from 'viem/chains' import { walletClient } from './client' await walletClient.switchChain({ id: avalanche.id }) Parameters[](https://viem.sh/docs/actions/wallet/switchChain#parameters) ------------------------------------------------------------------------- ### id[](https://viem.sh/docs/actions/wallet/switchChain#id) * **Type:** `number` The Chain ID. JSON-RPC Methods[](https://viem.sh/docs/actions/wallet/switchChain#json-rpc-methods) ------------------------------------------------------------------------------------- `[wallet_switchEthereumChain](https://eips.ethereum.org/EIPS/eip-3326) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/switchChain.md) Copy page for AI Ask AI... ⌘ I --- # WebSocket Transport · Viem [Skip to content](https://viem.sh/docs/clients/transports/websocket#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K WebSocket Transport =================== A function to create a WebSocket Transport for a Client The `webSocket` Transport connects to a JSON-RPC API via a WebSocket. Import[](https://viem.sh/docs/clients/transports/websocket#import) ------------------------------------------------------------------- import { webSocket } from 'viem' Usage[](https://viem.sh/docs/clients/transports/websocket#usage) ----------------------------------------------------------------- import { createPublicClient, webSocket } from 'viem' import { mainnet } from 'viem/chains' const client = createPublicClient({ chain: mainnet, transport: webSocket('wss://1.rpc.thirdweb.com/...'), }) Parameters[](https://viem.sh/docs/clients/transports/websocket#parameters) --------------------------------------------------------------------------- ### url[](https://viem.sh/docs/clients/transports/websocket#url) * **Type:** `string` URL of the JSON-RPC API. const transport = webSocket('wss://1.rpc.thirdweb.com/...') ### keepAlive (optional)[](https://viem.sh/docs/clients/transports/websocket#keepalive-optional) * **Type:** `boolean | { interval?: number }` * **Default:** `true` Whether or not to send keep-alive ping messages. const transport = webSocket('wss://1.rpc.thirdweb.com/...', { keepAlive: { interval: 1_000 }, }) ### key (optional)[](https://viem.sh/docs/clients/transports/websocket#key-optional) * **Type:** `string` * **Default:** `"webSocket"` A key for the Transport. const transport = webSocket('wss://1.rpc.thirdweb.com/...', { key: 'alchemy', }) ### methods (optional)[](https://viem.sh/docs/clients/transports/websocket#methods-optional) * **Type:** `{ include?: string[], exclude?: string[] }` Methods to include or exclude from sending RPC requests. const transport = webSocket('wss://1.rpc.thirdweb.com/...', { methods: { include: ['eth_sendTransaction', 'eth_signTypedData_v4'], }, }) ### name (optional)[](https://viem.sh/docs/clients/transports/websocket#name-optional) * **Type:** `string` * **Default:** `"WebSocket JSON-RPC"` A name for the Transport const transport = webSocket('wss://1.rpc.thirdweb.com/...', { name: 'Alchemy WebSocket Provider', }) ### reconnect (optional)[](https://viem.sh/docs/clients/transports/websocket#reconnect-optional) * **Type:** `boolean | { maxAttempts?: number, delay?: number }` * **Default:** `true` Whether or not to attempt to reconnect on socket failure. const transport = webSocket('wss://1.rpc.thirdweb.com/...', { reconnect: false, }) #### reconnect.attempts (optional)[](https://viem.sh/docs/clients/transports/websocket#reconnectattempts-optional) * **Type:** `number` * **Default:** `5` The max number of times to attempt to reconnect. const transport = webSocket('wss://1.rpc.thirdweb.com/...', { reconnect: { attempts: 10, } }) #### reconnect.delay (optional)[](https://viem.sh/docs/clients/transports/websocket#reconnectdelay-optional) * **Type:** `number` * **Default:** `2_000` Retry delay (in ms) between reconnect attempts. const transport = webSocket('wss://1.rpc.thirdweb.com/...', { reconnect: { delay: 1_000, } }) ### retryCount (optional)[](https://viem.sh/docs/clients/transports/websocket#retrycount-optional) * **Type:** `number` * **Default:** `3` The max number of times to retry when a request fails. const transport = webSocket('wss://1.rpc.thirdweb.com/...', { retryCount: 5, }) ### retryDelay (optional)[](https://viem.sh/docs/clients/transports/websocket#retrydelay-optional) * **Type:** `number` * **Default:** `150` The base delay (in ms) between retries. By default, the Transport will use [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff) (`~~(1 << count) * retryDelay`), which means the time between retries is not constant. const transport = webSocket('wss://1.rpc.thirdweb.com/...', { retryDelay: 100, }) ### timeout (optional)[](https://viem.sh/docs/clients/transports/websocket#timeout-optional) * **Type:** `number` * **Default:** `10_000` The timeout for async WebSocket requests. const transport = webSocket('wss://1.rpc.thirdweb.com/...', { timeout: 60_000, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/clients/transports/websocket.md) Copy page for AI Ask AI... ⌘ I --- # Installation · Viem [Skip to content](https://viem.sh/docs/installation#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Installation ============ Install Viem via your package manager, a ` Using Unreleased Commits[](https://viem.sh/docs/installation#using-unreleased-commits) --------------------------------------------------------------------------------------- If you can't wait for a new release to test the latest features, you can either install from the `canary` tag (tracks the `[main](https://github.com/wevm/viem/tree/main) ` branch). Or clone the [Viem repo](https://github.com/wevm/viem) to your local machine, build, and link it yourself. gh repo clone wevm/viem cd viem pnpm install pnpm build pnpm link --global Then go to the project where you are using Viem and run `pnpm link --global viem` (or the package manager that you used to link Viem globally). Security[](https://viem.sh/docs/installation#security) ------------------------------------------------------- Ethereum-related projects are often targeted in attacks to steal users' assets. Make sure you follow security best-practices for your project. Some quick things to get started. * Pin package versions, upgrade mindfully, and inspect lockfile changes to minimize the risk of [supply-chain attacks](https://nodejs.org/en/guides/security/#supply-chain-attacks) . * Install the [Socket Security](https://socket.dev/) [GitHub App](https://github.com/apps/socket-security) to help detect and block supply-chain attacks. * Add a [Content Security Policy](https://cheatsheetseries.owasp.org/cheatsheets/Content_Security_Policy_Cheat_Sheet.html) to defend against external scripts running in your app. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/installation.mdx) Copy page for AI Ask AI... ⌘ I --- # setIntervalMining · Viem [Skip to content](https://viem.sh/docs/actions/test/setIntervalMining#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K setIntervalMining ================= Sets the automatic mining interval (in seconds) of blocks. Setting the interval to `0` will disable automatic mining. Usage[](https://viem.sh/docs/actions/test/setIntervalMining#usage) ------------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.setIntervalMining({ interval: 5 }) Parameters[](https://viem.sh/docs/actions/test/setIntervalMining#parameters) ----------------------------------------------------------------------------- ### interval[](https://viem.sh/docs/actions/test/setIntervalMining#interval) * **Type:** `number` The mining interval (in seconds). Setting the interval to `0` will disable automatic mining. await testClient.setIntervalMining({ interval: 5 }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/setIntervalMining.md) Copy page for AI Ask AI... ⌘ I --- # stopImpersonatingAccount · Viem [Skip to content](https://viem.sh/docs/actions/test/stopImpersonatingAccount#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K stopImpersonatingAccount ======================== Stop impersonating an account after having previously used `[impersonateAccount](https://viem.sh/docs/actions/test/impersonateAccount) `. Usage[](https://viem.sh/docs/actions/test/stopImpersonatingAccount#usage) -------------------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.stopImpersonatingAccount({ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC' }) Parameters[](https://viem.sh/docs/actions/test/stopImpersonatingAccount#parameters) ------------------------------------------------------------------------------------ ### address[](https://viem.sh/docs/actions/test/stopImpersonatingAccount#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The address of the target account. await testClient.stopImpersonatingAccount({ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/stopImpersonatingAccount.md) Copy page for AI Ask AI... ⌘ I --- # setMinGasPrice · Viem [Skip to content](https://viem.sh/docs/actions/test/setMinGasPrice#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K 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. Usage[](https://viem.sh/docs/actions/test/setMinGasPrice#usage) ---------------------------------------------------------------- example.tsclient.ts import { parseGwei } from 'viem' import { testClient } from './client' await testClient.setMinGasPrice({ gasPrice: parseGwei('20'), }) Parameters[](https://viem.sh/docs/actions/test/setMinGasPrice#parameters) -------------------------------------------------------------------------- ### gasPrice[](https://viem.sh/docs/actions/test/setMinGasPrice#gasprice) * **Type:** `bigint` The gas price (in wei). await testClient.setMinGasPrice({ gasPrice: parseGwei('20'), }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/setMinGasPrice.md) Copy page for AI Ask AI... ⌘ I --- # setNonce · Viem [Skip to content](https://viem.sh/docs/actions/test/setNonce#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K setNonce ======== Modifies (overrides) the nonce of an account. Usage[](https://viem.sh/docs/actions/test/setNonce#usage) ---------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.setNonce({ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', nonce: 420 }) Parameters[](https://viem.sh/docs/actions/test/setNonce#parameters) -------------------------------------------------------------------- ### address[](https://viem.sh/docs/actions/test/setNonce#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The address of the target account. await testClient.setNonce({ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', nonce: 420 }) ### nonce (optional)[](https://viem.sh/docs/actions/test/setNonce#nonce-optional) * **Type:** `number` The nonce. await testClient.setNonce({ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', nonce: 420 }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/setNonce.md) Copy page for AI Ask AI... ⌘ I --- # Celo · Viem [Skip to content](https://viem.sh/docs/chains/celo#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Celo ==== Integrating with Celo in Viem Viem provides first-class support for chains implemented on [Celo](https://celo.org/) . Chains[](https://viem.sh/docs/chains/celo#chains) -------------------------------------------------- The following Viem chains are implemented on Celo: import { celo, celoSepolia } from 'viem/chains' ### Configuration[](https://viem.sh/docs/chains/celo#configuration) Viem exports Celo's chain [formatters](https://viem.sh/docs/chains/formatters) & [serializers](https://viem.sh/docs/chains/serializers) via `chainConfig`. This is useful if you need to define another chain which is implemented on Celo. import { defineChain } from 'viem' import { chainConfig } from 'viem/celo' export const celoExample = defineChain({ ...chainConfig, name: 'Celo Example', // ... }) Utilities[](https://viem.sh/docs/chains/celo#utilities) -------------------------------------------------------- ### `parseTransaction`[](https://viem.sh/docs/chains/celo#parsetransaction) Parses a serialized RLP-encoded transaction. Supports signed & unsigned CIP-64, EIP-1559, EIP-2930 and Legacy Transactions. Celo-flavored version of [Viem's `parseTransaction`](https://viem.sh/docs/utilities/parseTransaction) . #### Parameters[](https://viem.sh/docs/chains/celo#parameters) * `serializedTransaction` (`Hex`): The serialized transaction. import { parseTransaction } from 'viem/celo' const transaction = parseTransaction('0x7cf84682a4ec80847735940084773594008094765de816845861e75a25fca122bb6898b8b1282a808094f39fd6e51aad88f6f4ce6ab8827279cfffb92266880de0b6b3a764000080c0') ### `serializeTransaction`[](https://viem.sh/docs/chains/celo#serializetransaction) Serializes a transaction object. Supports CIP-64, EIP-1559, EIP-2930, and Legacy transactions. Celo-flavored version of [Viem's `serializeTransaction`](https://viem.sh/docs/utilities/serializeTransaction) . #### Parameters[](https://viem.sh/docs/chains/celo#parameters-1) * `transaction` (`TransactionSerializable`): The transaction object to serialize. * `signature` (`Signature`): Optional signature to include. import { serializeTransaction } from 'viem/celo' const serialized = serializeTransaction({ chainId: 42220, gas: 21001n, feeCurrency: "0x2F25deB3848C207fc8E0c34035B3Ba7fC157602B" // whitelisted adapter for USDC maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), nonce: 69, to: '0x1234512345123451234512345123451234512345', value: parseEther('0.01'), }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/chains/celo.md) Copy page for AI Ask AI... ⌘ I --- # fromBase58 · Viem [Skip to content](https://viem.sh/docs/utilities/fromBase58#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K fromBase58 ========== Coming soon. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/fromBase58.md) Copy page for AI Ask AI... ⌘ I --- # fromBase64 · Viem [Skip to content](https://viem.sh/docs/utilities/fromBase64#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K fromBase64 ========== Coming soon. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/fromBase64.md) Copy page for AI Ask AI... ⌘ I --- # EIP-7702 Overview · Viem [Skip to content](https://viem.sh/docs/eip7702#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K EIP-7702 Overview ================= EIP-7702 is a proposal to add a new Transaction type to allow an EOA to designate a Smart Contract as its "implementation". The main difference between an EIP-7702 Transaction and other transactions is the inclusion of a **"authorization list"** property, a set of `(chain_id, contract_address, nonce, y_parity, r, s)` tuples that depict what Contracts should be delegated onto the Externally Owned Account. Applications of EIP-7702 include: * **Batching**: allowing multiple operations from the same user in one atomic transaction. One common example is an ERC-20 approval followed by spending that approval, a common workflow in DEXes that requires two transactions today. Advanced use cases of batching occasionally involve dependencies: the output of the first operation is part of the input to the second operation. * **Sponsorship**: account X pays for a transaction on behalf of account Y. Account X could be paid in some other ERC-20 for this service, or it could be an application operator including the transactions of its users for free. * **Privilege de-escalation**: users can sign sub-keys, and give them specific permissions that are much weaker than global access to the account. For example, you could imagine a permission to spend ERC-20 tokens but not ETH, or to spend up to 1% of total balance per day, or to interact only with a specific application. Next Steps[](https://viem.sh/docs/eip7702#next-steps) ------------------------------------------------------ * [Contract Writes](https://viem.sh/docs/eip7702/contract-writes) * [Sending Transactions](https://viem.sh/docs/eip7702/sending-transactions) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/eip7702.mdx) Copy page for AI Ask AI... ⌘ I --- # labelhash · Viem [Skip to content](https://viem.sh/docs/ens/utilities/labelhash#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K labelhash ========= Hashes ENS label. Import[](https://viem.sh/docs/ens/utilities/labelhash#import) -------------------------------------------------------------- import { labelhash, normalize } from 'viem/ens' Usage[](https://viem.sh/docs/ens/utilities/labelhash#usage) ------------------------------------------------------------ import { labelhash, normalize } from 'viem/ens' labelhash(normalize('awkweb')) // '0x7aaad03ddcacc63166440f59c14a1a2c97ee381014b59c58f55b49ab05f31a38' Returns[](https://viem.sh/docs/ens/utilities/labelhash#returns) ---------------------------------------------------------------- `string` The hashed ENS label. Parameters[](https://viem.sh/docs/ens/utilities/labelhash#parameters) ---------------------------------------------------------------------- ### name[](https://viem.sh/docs/ens/utilities/labelhash#name) * **Type:** `string` A ENS label. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/ens/utilities/labelhash.md) Copy page for AI Ask AI... ⌘ I --- # Formatters · Viem [Skip to content](https://viem.sh/docs/chains/formatters#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Formatters ========== Configure chain-based formatters in Viem You can modify how Blocks & Transactions are formatted by using the `formatters` property on the Chain. This is useful for chains that have a different Block or Transaction structure than Mainnet (e.g. Celo & OP Stack chains). Usage[](https://viem.sh/docs/chains/formatters#usage) ------------------------------------------------------ import { defineBlock, defineChain, defineTransaction, defineTransactionReceipt, defineTransactionRequest } from 'viem' export const example = defineChain({ /* ... */ formatters: { block: defineBlock(/* ... */), transaction: defineTransaction(/* ... */), transactionReceipt: defineTransactionReceipt(/* ... */), transactionRequest: defineTransactionRequest(/* ... */), } }) API[](https://viem.sh/docs/chains/formatters#api) -------------------------------------------------- ### `formatters.block`[](https://viem.sh/docs/chains/formatters#formattersblock) You can modify how Blocks are formatted by using the `formatters.block` property on the Chain. You can either pass in the Block overrides, or the whole Block itself to the `format` function of `defineBlock`. You can also exclude certain properties with `exclude`. import { defineBlock, defineChain, hexToBigInt } from 'viem' type RpcBlockOverrides = { secondaryFee: `0x${string}` } type BlockOverrides = { secondaryFee: bigint } const example = defineChain({ /* ... */ formatters: { block: defineBlock({ exclude: ['difficulty'], format(args: RpcBlockOverrides): BlockOverrides { return { secondaryFee: hexToBigInt(args.secondaryFee) } }, }), }, }) const block = await client.getBlock() // ^? { ..., difficulty: never, secondaryFee: bigint, ... } ### `formatters.transaction`[](https://viem.sh/docs/chains/formatters#formatterstransaction) You can modify how Transactions are formatted by using the `formatters.transaction` property on the Chain. You can either pass in the Transaction overrides, or the whole Transaction itself to the `format` function of `defineTransaction`. You can also exclude certain properties with `exclude`. import { defineTransaction, defineChain, hexToBigInt } from 'viem' type RpcTransactionOverrides = { mint: `0x${string}` } type TransactionOverrides = { mint: bigint } const example = defineChain({ /* ... */ formatters: { transaction: defineTransaction({ exclude: ['gasPrice'], format(args: RpcTransactionOverrides): TransactionOverrides { return { mint: hexToBigInt(args.mint) } }, }), }, }) const transaction = await client.getTransaction({ hash: '0x...' }) // ^? { ..., gasPrice: never, mint: bigint, ... } ### `formatters.transactionReceipt`[](https://viem.sh/docs/chains/formatters#formatterstransactionreceipt) You can modify how Transaction Receipts are formatted by using the `formatters.transactionReceipt` property on the Chain. You can either pass in the Transaction Receipt overrides, or the whole Transaction Receipt itself to the `format` function of `defineTransactionReceipt`. You can also exclude certain properties with `exclude`. import { defineTransactionReceipt, defineChain, hexToBigInt } from 'viem' type RpcTransactionReceiptOverrides = { l1Fee: `0x${string}` } type TransactionReceiptOverrides = { l1Fee: bigint } const example = defineChain({ /* ... */ formatters: { transactionReceipt: defineTransactionReceipt({ exclude: ['effectiveGasPrice'], format(args: RpcTransactionReceiptOverrides): TransactionReceiptOverrides { return { l1Fee: hexToBigInt(args.l1Fee) } }, }), }, }) const receipt = await client.getTransactionReceipt({ hash: '0x...' }) // ^? { ..., effectiveGasPrice: never, l1Fee: bigint, ... } ### `formatters.transactionRequest`[](https://viem.sh/docs/chains/formatters#formatterstransactionrequest) You can modify how Transaction Requests are formatted by using the `formatters.transactionRequest` property on the Chain. You can either pass in the Transaction Request overrides, or the whole Transaction Request itself to the `format` function of `defineTransactionRequest`. You can also exclude certain properties with `exclude`. import { defineTransactionRequest, defineChain, hexToBigInt } from 'viem' type RpcTransactionRequestOverrides = { secondaryFee: `0x${string}` } type TransactionRequestOverrides = { secondaryFee: bigint } const example = defineChain({ /* ... */ formatters: { transactionRequest: defineTransactionRequest({ exclude: ['effectiveGasPrice'], format(args: TransactionRequestOverrides): RpcTransactionRequestOverrides { return { secondaryFee: numberToHex(args.secondaryFee) } }, }), }, }) const receipt = await client.getTransactionReceipt({ hash: '0x...' }) // ^? { ..., effectiveGasPrice: never, l1Fee: bigint, ... } [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/chains/formatters.md) Copy page for AI Ask AI... ⌘ I --- # Error Handling · Viem [Skip to content](https://viem.sh/docs/error-handling#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Error Handling ============== Every module in viem exports an accompanying error type which you can use to strongly type your `catch` statements. These types come in the form of `ErrorType`. For example, the `getBlockNumber` action exports a `GetBlockNumberErrorType` type. Unfortunately, [TypeScript doesn't have an abstraction for typed exceptions](https://github.com/microsoft/TypeScript/issues/13219) , so the most pragmatic & vanilla approach would be to explicitly cast error types in the `catch` statement. example.tsclient.ts import { type GetBlockNumberErrorType } from 'viem' import { client } from './client' try { const blockNumber = await client.getBlockNumber() } catch (e) { const error = e as GetBlockNumberErrorType error.name if (error.name === 'InternalRpcError') error.code if (error.name === 'HttpRequestError') { error.headers error.status } } [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/error-handling.mdx) Copy page for AI Ask AI... ⌘ I --- # defineKzg · Viem [Skip to content](https://viem.sh/docs/utilities/defineKzg#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K defineKzg ========= Defines a [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844) compatible [KZG interface](https://notes.ethereum.org/@vbuterin/proto_danksharding_faq#How-%E2%80%9Ccomplicated%E2%80%9D-and-%E2%80%9Cnew%E2%80%9D-is-KZG) . The KZG interface is used in the blob transaction signing process to generate KZG commitments & proofs. `defineKzg` accepts a KZG interface that implements two functions: * `blobToKzgCommitment`: A function that takes a blob and returns it's KZG commitment. * `computeBlobKzgProof`: A function that takes a blob and it's commitment, and returns the KZG proof. A couple of KZG implementations we recommend are: * [c-kzg](https://github.com/ethereum/c-kzg-4844) : Node.js bindings to c-kzg. * [kzg-wasm](https://github.com/ethereumjs/kzg-wasm) : WebAssembly bindings to c-kzg. Import[](https://viem.sh/docs/utilities/defineKzg#import) ---------------------------------------------------------- import { defineKzg } from 'viem' Usage[](https://viem.sh/docs/utilities/defineKzg#usage) -------------------------------------------------------- import * as cKzg from 'c-kzg' import { defineKzg } from 'viem' import { mainnetTrustedSetupPath } from 'viem/node' cKzg.loadTrustedSetup(mainnetTrustedSetupPath) const kzg = defineKzg(cKzg) Returns[](https://viem.sh/docs/utilities/defineKzg#returns) ------------------------------------------------------------ `Kzg` The KZG interface. Parameters[](https://viem.sh/docs/utilities/defineKzg#parameters) ------------------------------------------------------------------ ### blobToKzgCommitment[](https://viem.sh/docs/utilities/defineKzg#blobtokzgcommitment) * **Type:** `(blob: ByteArray) => ByteArray` Convert a blob to a KZG commitment. ### computeBlobKzgProof[](https://viem.sh/docs/utilities/defineKzg#computeblobkzgproof) * **Type:** `(blob: ByteArray, commitment: ByteArray) => ByteArray` Given a blob, return the KZG proof that is used to verify it against the commitment. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/defineKzg.md) Copy page for AI Ask AI... ⌘ I --- # waitForTransactionReceipt · Viem [Skip to content](https://viem.sh/docs/actions/public/waitForTransactionReceipt#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K waitForTransactionReceipt ========================= Waits for the [Transaction](https://viem.sh/docs/glossary/terms#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) . The `waitForTransactionReceipt` action additionally supports Replacement detection (e.g. sped up Transactions). Usage[](https://viem.sh/docs/actions/public/waitForTransactionReceipt#usage) ----------------------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const transaction = await publicClient.waitForTransactionReceipt( { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d' } ) } Returns[](https://viem.sh/docs/actions/public/waitForTransactionReceipt#returns) --------------------------------------------------------------------------------- `[TransactionReceipt](https://viem.sh/docs/glossary/types#transactionreceipt) ` The transaction receipt. Parameters[](https://viem.sh/docs/actions/public/waitForTransactionReceipt#parameters) --------------------------------------------------------------------------------------- ### confirmations (optional)[](https://viem.sh/docs/actions/public/waitForTransactionReceipt#confirmations-optional) * **Type:** `number` * **Default:** `1` The number of confirmations (blocks that have passed) to wait before resolving. const transaction = await publicClient.waitForTransactionReceipt( { confirmations: 5, hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d' } ) ### onReplaced (optional)[](https://viem.sh/docs/actions/public/waitForTransactionReceipt#onreplaced-optional) * **Type:** `({ reason: 'replaced' | 'repriced' | 'cancelled', replacedTransaction: Transaction, transaction: Transaction, transactionReceipt: TransactionReceipt }) => void` Optional callback to emit if the transaction has been replaced. const transaction = await publicClient.waitForTransactionReceipt( { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', onReplaced: replacement => console.log(replacement) } ) ### pollingInterval (optional)[](https://viem.sh/docs/actions/public/waitForTransactionReceipt#pollinginterval-optional) * **Type:** `number` Polling frequency (in ms). Defaults to the Client's `pollingInterval` config. const transaction = await publicClient.waitForTransactionReceipt( { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', pollingInterval: 12_000, } ) ### retryCount (optional)[](https://viem.sh/docs/actions/public/waitForTransactionReceipt#retrycount-optional) * **Type:** `number` * **Default:** `6` Number of times to retry if the transaction or block is not found. const transaction = await publicClient.waitForTransactionReceipt( { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', retryCount: 3, } ) ### retryDelay (optional)[](https://viem.sh/docs/actions/public/waitForTransactionReceipt#retrydelay-optional) * **Type:** `number | (({ count: number; error: Error }) => number)` * **Default:** `({ count }) => ~~(1 << count) * 200` (exponential backoff) Time to wait (in ms) between retries. const transaction = await publicClient.waitForTransactionReceipt( { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', retryDelay: 10_000, } ) ### timeout (optional)[](https://viem.sh/docs/actions/public/waitForTransactionReceipt#timeout-optional) * **Type:** `number` * **Default:** `180_000` Optional timeout (in milliseconds) to wait before stopping polling. const transaction = await publicClient.waitForTransactionReceipt( { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', timeout: 60_000, } ) ### Notes[](https://viem.sh/docs/actions/public/waitForTransactionReceipt#notes) * 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 (ie. different `maxFeePerGas`) * `cancelled`: The Transaction has been cancelled (ie. `value === 0n`) * `replaced`: The Transaction has been replaced (ie. different `value` or `data`) Live Example[](https://viem.sh/docs/actions/public/waitForTransactionReceipt#live-example) ------------------------------------------------------------------------------------------- Check out the usage of `waitForTransactionReceipt` in the live [Sending Transactions Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_sending-transactions) below. JSON-RPC Methods[](https://viem.sh/docs/actions/public/waitForTransactionReceipt#json-rpc-methods) --------------------------------------------------------------------------------------------------- * Polls `[eth_getTransactionReceipt](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) ` on each block until it has been processed. * If a Transaction has been replaced: * Calls `[eth_getBlockByNumber](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) ` and extracts the transactions * Checks if one of the Transactions is a replacement * If so, calls `[eth_getTransactionReceipt](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) `. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/waitForTransactionReceipt.md) Copy page for AI Ask AI... ⌘ I --- # namehash · Viem [Skip to content](https://viem.sh/docs/ens/utilities/namehash#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K namehash ======== Hashes ENS name. Import[](https://viem.sh/docs/ens/utilities/namehash#import) ------------------------------------------------------------- import { namehash, normalize } from 'viem/ens' Usage[](https://viem.sh/docs/ens/utilities/namehash#usage) ----------------------------------------------------------- import { namehash, normalize } from 'viem/ens' namehash('wevm.eth') // '0xf246651c1b9a6b141d19c2604e9a58f567973833990f830d882534a747801359' Returns[](https://viem.sh/docs/ens/utilities/namehash#returns) --------------------------------------------------------------- `string` The hashed ENS name. Parameters[](https://viem.sh/docs/ens/utilities/namehash#parameters) --------------------------------------------------------------------- ### name[](https://viem.sh/docs/ens/utilities/namehash#name) * **Type:** `string` A ENS name. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/ens/utilities/namehash.md) Copy page for AI Ask AI... ⌘ I --- # generateSiweNonce · Viem [Skip to content](https://viem.sh/docs/siwe/utilities/generateSiweNonce#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K generateSiweNonce ================= Generates random [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) nonce. Import[](https://viem.sh/docs/siwe/utilities/generateSiweNonce#import) ----------------------------------------------------------------------- import { generateSiweNonce } from 'viem/siwe' Usage[](https://viem.sh/docs/siwe/utilities/generateSiweNonce#usage) --------------------------------------------------------------------- import { generateSiweNonce } from 'viem/siwe' const nonce = generateSiweNonce() Returns[](https://viem.sh/docs/siwe/utilities/generateSiweNonce#returns) ------------------------------------------------------------------------- `string` A randomly generated EIP-4361 nonce. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/siwe/utilities/generateSiweNonce.md) Copy page for AI Ask AI... ⌘ I --- # Types · Viem [Skip to content](https://viem.sh/docs/glossary/types#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Types ===== Glossary of Types in viem. `Abi`[](https://viem.sh/docs/glossary/types#abi) ------------------------------------------------- Type matching the [Contract ABI Specification](https://docs.soliditylang.org/en/latest/abi-spec.html#json) Re-exported from [ABIType](https://abitype.dev/api/types#abi) . `AbiError`[](https://viem.sh/docs/glossary/types#abierror) ----------------------------------------------------------- ABI [Error](https://docs.soliditylang.org/en/latest/abi-spec#errors) type. Re-exported from [ABIType](https://abitype.dev/api/types#abierror) . `AbiEvent`[](https://viem.sh/docs/glossary/types#abievent) ----------------------------------------------------------- ABI [Event](https://docs.soliditylang.org/en/latest/abi-spec#events) type. Re-exported from [ABIType](https://abitype.dev/api/types#abievent) . `AbiFunction`[](https://viem.sh/docs/glossary/types#abifunction) ----------------------------------------------------------------- ABI [Function](https://docs.soliditylang.org/en/latest/abi-spec#argument-encoding) type. Re-exported from [ABIType](https://abitype.dev/api/types#abifunction) . `AbiParameter`[](https://viem.sh/docs/glossary/types#abiparameter) ------------------------------------------------------------------- `inputs` and `outputs` item for ABI functions, events, and errors. Re-exported from [ABIType](https://abitype.dev/api/types#abiparameter) . `AbiParameterToPrimitiveTypes`[](https://viem.sh/docs/glossary/types#abiparametertoprimitivetypes) --------------------------------------------------------------------------------------------------- Converts `AbiParameter` to corresponding TypeScript primitive type. [See more](https://abitype.dev/api/utilities#abiparametertoprimitivetype) `AbiParametersToPrimitiveTypes`[](https://viem.sh/docs/glossary/types#abiparameterstoprimitivetypes) ----------------------------------------------------------------------------------------------------- Converts array of `AbiParameter` to corresponding TypeScript primitive types. [See more](https://abitype.dev/api/utilities#abiparameterstoprimitivetypes) `AccessList`[](https://viem.sh/docs/glossary/types#accesslist) --------------------------------------------------------------- An access list. `Address`[](https://viem.sh/docs/glossary/types#address) --------------------------------------------------------- An address. Re-exported from [ABIType](https://abitype.dev/api/types#address) . `Block`[](https://viem.sh/docs/glossary/types#block) ----------------------------------------------------- A type for a [Block](https://viem.sh/docs/glossary/terms#block) . [See Type](https://github.com/wevm/viem/blob/main/src/types/block.ts) `Chain`[](https://viem.sh/docs/glossary/types#chain) ----------------------------------------------------- A type for a [Chain](https://viem.sh/docs/glossary/terms#chain) . [See Type](https://github.com/wevm/viem/blob/main/src/types/chain.ts) `CompactSignature`[](https://viem.sh/docs/glossary/types#compactsignature) --------------------------------------------------------------------------- A type for [EIP-2098](https://eips.ethereum.org/EIPS/eip-2098) compact signatures. [See Type](https://github.com/wevm/viem/blob/main/src/types/misc.ts) `FeeHistory`[](https://viem.sh/docs/glossary/types#feehistory) --------------------------------------------------------------- A type for fee history. [See Type](https://github.com/wevm/viem/blob/main/src/types/fee.ts) `FeeValues`[](https://viem.sh/docs/glossary/types#feevalues) ------------------------------------------------------------- A type for fee values. [See Type](https://github.com/wevm/viem/blob/main/src/types/fee.ts) `Filter`[](https://viem.sh/docs/glossary/types#filter) ------------------------------------------------------- A type for a [Filter](https://viem.sh/docs/glossary/terms#filter) . [See Type](https://github.com/wevm/viem/blob/main/src/types/filter.ts) `Hash`[](https://viem.sh/docs/glossary/types#hash) --------------------------------------------------- Type for a hashed value – a "0x"-prefixed string: `"0x${string}"` `Hex`[](https://viem.sh/docs/glossary/types#hex) ------------------------------------------------- Type for a hex value – a "0x"-prefixed string: `"0x${string}"` `Log`[](https://viem.sh/docs/glossary/types#log) ------------------------------------------------- A type for [Event Logs](https://viem.sh/docs/glossary/terms#event-log) . [See Type](https://github.com/wevm/viem/blob/main/src/types/log.ts) `Signature`[](https://viem.sh/docs/glossary/types#signature) ------------------------------------------------------------- A type for a structured signature. [See Type](https://github.com/wevm/viem/blob/main/src/types/misc.ts) `Transaction`[](https://viem.sh/docs/glossary/types#transaction) ----------------------------------------------------------------- A type for [Transactions](https://viem.sh/docs/glossary/terms#transaction) . [See Type](https://github.com/wevm/viem/blob/main/src/types/transaction.ts) `TransactionReceipt`[](https://viem.sh/docs/glossary/types#transactionreceipt) ------------------------------------------------------------------------------- A type for [Transaction Receipts](https://viem.sh/docs/glossary/terms#transaction-receipt) . [See Type](https://github.com/wevm/viem/blob/main/src/types/transaction.ts) `Transport`[](https://viem.sh/docs/glossary/types#transport) ------------------------------------------------------------- A type for [Transports](https://viem.sh/docs/glossary/terms#transports) . [See Type](https://github.com/wevm/viem/blob/main/src/clients/transports/createTransport.ts) `WalletPermission`[](https://viem.sh/docs/glossary/types#walletpermission) --------------------------------------------------------------------------- A type for wallet (JSON-RPC Account) permissions. [See Type](https://github.com/wevm/viem/blob/main/src/types/eip1193.ts) `TransactionSerializedEIP1559`[](https://viem.sh/docs/glossary/types#transactionserializedeip1559) --------------------------------------------------------------------------------------------------- EIP-1559 transaction hex value – a "0x02"-prefixed string: `"0x02${string}"` `TransactionSerializedEIP2930`[](https://viem.sh/docs/glossary/types#transactionserializedeip2930) --------------------------------------------------------------------------------------------------- EIP-2930 transaction hex value – a "0x01"-prefixed string: `"0x01${string}"` `TransactionSerializedLegacy`[](https://viem.sh/docs/glossary/types#transactionserializedlegacy) ------------------------------------------------------------------------------------------------- Legacy transaction hex value – a "0x"-prefixed string: `"0x${string}"` `TransactionType`[](https://viem.sh/docs/glossary/types#transactiontype) ------------------------------------------------------------------------- All types of transactions. `"eip1559" | "eip2930" | "eip4844" | "eip7702" | "legacy"` `TransactionRequest`[](https://viem.sh/docs/glossary/types#transactionrequest) ------------------------------------------------------------------------------- A type for all transaction requests. [See Type](https://github.com/wevm/viem/blob/main/src/types/transaction.ts) . `StateOverride`[](https://viem.sh/docs/glossary/types#stateoverride) --------------------------------------------------------------------- A type defining state overrides for `eth_call` method. [See more](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-eth#eth-call) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/glossary/types.md) Copy page for AI Ask AI... ⌘ I --- # Frequently Asked Questions · Viem [Skip to content](https://viem.sh/docs/faq#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Frequently Asked Questions ========================== Frequently asked questions related to viem. **TL;DR: viem tries to avoid creating unnecessary abstractions on top of existing systems.** Feel free to add to this document if you notice frequently asked questions that are not covered here. Why use the terms "Wallet" & "Account" instead of "Signer"[](https://viem.sh/docs/faq#why-use-the-terms-wallet--account-instead-of-signer) ------------------------------------------------------------------------------------------------------------------------------------------- viem attempts to align to the "Wallet" and "Account" [terminology on Ethereum.org](https://ethereum.org/en/glossary/) . The term "Signer" was adapted from ethers.js. Let's clear up on some terms before we dive in. * Wallet: An application or interface that holds Account(s). * Account: An object that represents an address, balance, nonce, and optional storage and code. * Private Key: Proves ownership of an Account, and can sign messages & transactions. In the context of viem, a Wallet Client is an interface that can hold an Account. The Account may or may not hold a Private Key. In viem, there are two types of Accounts: * Local Account: can **synchronously & directly** sign messages and transactions using its Private Key. A signature is guaranteed. * JSON-RPC Account: **asynchronously requests** signing of messages and transactions from the target Wallet over JSON-RPC (e.g. Browser Extension or WalletConnect). The target Wallet holds the Account & Private Key. A signature is not guaranteed (the target Wallet may not have permitted the Account, or the Wallet may have rejected the request). We do not use the term "Signer" because there are noticeable behavioral differences between signing locally and signing over JSON-RPC. Why are contract function `args` with fully-named inputs represented as unnamed tuple types instead of object types?[](https://viem.sh/docs/faq#why-are-contract-function-args-with-fully-named-inputs-represented-as-unnamed-tuple-types-instead-of-object-types) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Let's look at an example! Suppose I have the following function in my contract: function transferFrom(address sender, address recipient, uint256 amount) returns (bool) All the inputs are named (`sender`, `recipient`, and `amount`) so I might be tempted to represent the parameters as the following TypeScript type: type Args = { sender: `0x${string}`; recipient: `0x${string}`; amount: bigint; } This improves developer experience a bit because now I can see the names of the parameters in my editor. import { createWalletClient, parseAbi } from 'viem' const client = createWalletClient(…) client.writeContract({ address: '0x…', abi: parseAbi([\ 'function transferFrom(address sender, address recipient, uint256 amount) returns (bool)',\ ]), functionName: 'transferFrom', args: { sender: '0x…', recipient: '0x…', amount: 100n, }, }) However, this only works if all the inputs are named (some compilers will strip names from inputs). If any of the inputs are unnamed, then you'll have to use a tuple instead: client.writeContract({ address: '0x…', abi: parseAbi([\ 'function transferFrom(address, address, uint256) returns (bool)',\ ]), functionName: 'transferFrom', args: ['0x…', '0x…', 100n], }) This can get even more complicated when a function has overloads: function safeTransferFrom(address, address, uint256) {} function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) {} In this case, the type of the overload parameters start to diverge from each other: type Args = | [`0x${string}`, `0x${string}`, bigint] | { from: `0x${string}`; to: `0x${string}`; tokenId: bigint; data: string; } If you want to switch between the two overloads in your code, you'll need to completely change the type instead of just adding or removing a single positional argument from the end. (Objects also don't enforce type-level ordering so you can put them in whatever order you want. This would also mean that viem would also need to internally validate order during runtime, adding some extra overhead.) client.writeContract({ address: '0x…', abi: parseAbi([\ 'function safeTransferFrom(address, address, uint256)',\ 'function safeTransferFrom(address from, address to, uint256 tokenId, bytes data)',\ ]), functionName: 'safeTransferFrom', - args: ['0x…', '0x…', 100n], + args: { + from: '0x…', + to: '0x…', + tokenId: 100n, + data: '0x…', + }, }) Even though overloads are an edge case, it would be sufficiently [astonishing](https://en.wikipedia.org/wiki/Principle_of_least_astonishment) to come across this behavior. So what's the best way to represent `args`? Well, they are positional at the contract-level so it makes sense to represent them that way in viem too. Not all is lost when it comes to developer experience though! Tuple types in TypeScript can have [names](https://www.typescriptlang.org/play?ts=4.0.2#example/named-tuples) attached to them: type Args = [from: `0x${string}`, to: `0x${string}`, tokenId: bigint] These names show up in your editor so you get nice developer experience when using autocomplete, etc. Unfortunately, TypeScript doesn't support dynamic named tuples right now, but we are watching [this issue](https://github.com/microsoft/TypeScript/issues/44939) closely and once it is implemented, we will add it to viem. In the meantime, hang tight! Why is a contract function return type returning an array instead of an object?[](https://viem.sh/docs/faq#why-is-a-contract-function-return-type-returning-an-array-instead-of-an-object) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Suppose your ABI looks like this: [\ {\ inputs: [],\ name: "latestRoundData",\ outputs: [\ { name: "roundId", type: "uint80" },\ { name: "answer", type: "int256" },\ { name: "startedAt", type: "uint256" },\ { name: "updatedAt", type: "uint256" },\ { name: "answeredInRound", type: "uint80" },\ ],\ stateMutability: "view",\ type: "function",\ }\ ] You might be confused why the following does not return an object: import { createPublicClient, parseAbi } from 'viem' const client = createPublicClient(…) const res = await client.readContract({ address: '0x…', abi: […], // abi from above functionName: 'latestRoundData', }) res // ^? const res: [bigint, bigint, bigint, bigint, bigint] This is expected. `"latestRoundData"` `outputs` is an array of types, so you get an array of decoded values as the return type. viem only maps explicitly typed tuples as objects Why does viem follow this approach? Here is the contract function definition for `latestRoundData` with two different return types: function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); struct Data { uint80 roundId; uint256 answer; uint256 startedAt; uint256 updatedAt; uint80 answeredInRound } function latestRoundData() external view returns (Data data); The first function returns a set of five items, so viem maps it to an array. The reason why we don't convert it to an object is because things get ambiguous when we come to decode structs. How do you determine the difference between a "return" tuple (first function) and a "struct" tuple (second function). Another reason is that folks might expect it to be an array (because it is a set of return items). Other libraries, like ethers, mitigate this by returning a hybrid Array/Object type, but that kind of type is not serializable in JavaScript, and viem prefers to not try and "hack" JavaScript types. Why doesn't Wallet Client support public actions?[](https://viem.sh/docs/faq#why-doesnt-wallet-client-support-public-actions) ------------------------------------------------------------------------------------------------------------------------------ Wallet Client doesn't support public actions because wallet providers (Injected `window.ethereum`, WalletConnect v2, etc.) may not provide a large majority of "node"/"public" RPC methods like `eth_call`, `eth_newFilter`, `eth_getLogs`, etc. This is because these methods are not required for a wallet provider to function properly. For example, a wallet provider may only support `eth_sendTransaction` and `eth_sign` and nothing else. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/faq.mdx) Copy page for AI Ask AI... ⌘ I --- # HTTP Transport · Viem [Skip to content](https://viem.sh/docs/clients/transports/http#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K HTTP Transport ============== A function to create a HTTP Transport for a Client The `http` Transport connects to a JSON-RPC API via HTTP. Import[](https://viem.sh/docs/clients/transports/http#import) -------------------------------------------------------------- import { http } from 'viem' Usage[](https://viem.sh/docs/clients/transports/http#usage) ------------------------------------------------------------ import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' const client = createPublicClient({ chain: mainnet, transport: http('https://1.rpc.thirdweb.com/...'), }) ### Batch JSON-RPC[](https://viem.sh/docs/clients/transports/http#batch-json-rpc) The `http` Transport supports Batch JSON-RPC. This means that multiple JSON-RPC requests can be sent in a single HTTP request. The Transport will batch up Actions over a given period and execute them in a single Batch JSON-RPC HTTP request. By default, this period is a [zero delay](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop#zero_delays) meaning that the batch request will be executed at the end of the current [JavaScript message queue](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop#queue) . Consumers can specify a custom time period `wait` (in ms). You can enable Batch JSON-RPC by setting the `batch` flag to `true`: const transport = http('https://1.rpc.thirdweb.com/...', { batch: true }) Now when you invoke Actions, the `http` Transport will batch and send over those requests at the end of the message queue (or custom time period) in a single Batch JSON-RPC HTTP request: // The below will send a single Batch JSON-RPC HTTP request to the RPC Provider. const [blockNumber, balance, ensName] = await Promise.all([\ client.getBlockNumber(),\ client.getBalance({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B' }),\ client.getEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B' }),\ ]) Parameters[](https://viem.sh/docs/clients/transports/http#parameters) ---------------------------------------------------------------------- ### url (optional)[](https://viem.sh/docs/clients/transports/http#url-optional) * **Type:** `string` * **Default:** `chain.rpcUrls.default.http[0]` URL of the JSON-RPC API. const transport = http('https://1.rpc.thirdweb.com/...') ### batch (optional)[](https://viem.sh/docs/clients/transports/http#batch-optional) * **Type:** `boolean | BatchOptions` * **Default:** `false` Toggle to enable Batch JSON-RPC const transport = http('https://1.rpc.thirdweb.com/...', { batch: true }) ### batch.batchSize (optional)[](https://viem.sh/docs/clients/transports/http#batchbatchsize-optional) * **Type:** `number` * **Default:** `1_000` The maximum number of JSON-RPC requests to send in a batch. const transport = http('https://1.rpc.thirdweb.com/...', { batch: { batchSize: 2_000 } }) ### batch.wait (optional)[](https://viem.sh/docs/clients/transports/http#batchwait-optional) * **Type:** `number` * **Default:** `0` ([zero delay](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop#zero_delays) ) The maximum number of milliseconds to wait before sending a batch. const transport = http('https://1.rpc.thirdweb.com/...', { batch: { wait: 16 } }) ### fetchOptions (optional)[](https://viem.sh/docs/clients/transports/http#fetchoptions-optional) * **Type:** `[RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/fetch) ` [Fetch options](https://developer.mozilla.org/en-US/docs/Web/API/fetch) to pass to the internal `fetch` function. Useful for passing auth headers or cache options. const transport = http('https://1.rpc.thirdweb.com/...', { fetchOptions: { headers: { 'Authorization': 'Bearer ...' } } }) ### key (optional)[](https://viem.sh/docs/clients/transports/http#key-optional) * **Type:** `string` * **Default:** `"http"` A key for the Transport. const transport = http('https://1.rpc.thirdweb.com/...', { key: 'alchemy', }) ### methods (optional)[](https://viem.sh/docs/clients/transports/http#methods-optional) * **Type:** `{ include?: string[], exclude?: string[] }` Methods to include or exclude from sending RPC requests. const transport = http('https://1.rpc.thirdweb.com/...', { methods: { include: ['eth_sendTransaction', 'eth_signTypedData_v4'], }, }) ### name (optional)[](https://viem.sh/docs/clients/transports/http#name-optional) * **Type:** `string` * **Default:** `"HTTP JSON-RPC"` A name for the Transport const transport = http('https://1.rpc.thirdweb.com/...', { name: 'Alchemy HTTP Provider', }) ### onFetchRequest (optional)[](https://viem.sh/docs/clients/transports/http#onfetchrequest-optional) * **Type:** `(request: Request) => void` A callback to handle the fetch request. Useful for logging or debugging. const transport = http('https://1.rpc.thirdweb.com/...', { onFetchRequest(request) { console.log(request) } }) ### onFetchResponse (optional)[](https://viem.sh/docs/clients/transports/http#onfetchresponse-optional) * **Type:** `(response: Response) => void` A callback to handle the fetch response. Useful for logging or debugging. const transport = http('https://1.rpc.thirdweb.com/...', { onFetchResponse(response) { console.log(response) } }) ### retryCount (optional)[](https://viem.sh/docs/clients/transports/http#retrycount-optional) * **Type:** `number` * **Default:** `3` The max number of times to retry when a request fails. const transport = http('https://1.rpc.thirdweb.com/...', { retryCount: 5, }) ### retryDelay (optional)[](https://viem.sh/docs/clients/transports/http#retrydelay-optional) * **Type:** `number` * **Default:** `150` The base delay (in ms) between retries. By default, the Transport will use [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff) (`~~(1 << count) * retryDelay`), which means the time between retries is not constant. const transport = http('https://1.rpc.thirdweb.com/...', { retryDelay: 100, }) ### timeout (optional)[](https://viem.sh/docs/clients/transports/http#timeout-optional) * **Type:** `number` * **Default:** `10_000` The timeout for requests. const transport = http('https://1.rpc.thirdweb.com/...', { timeout: 60_000, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/clients/transports/http.md) Copy page for AI Ask AI... ⌘ I --- # toBase64 · Viem [Skip to content](https://viem.sh/docs/utilities/toBase64#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K toBase64 ======== Coming soon. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/toBase64.md) Copy page for AI Ask AI... ⌘ I --- # getEnsResolver · Viem [Skip to content](https://viem.sh/docs/ens/actions/getEnsResolver#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getEnsResolver ============== Gets resolver for ENS name. Calls `findResolver(bytes)` on ENS Universal Resolver Contract to retrieve the resolver of an ENS name. Usage[](https://viem.sh/docs/ens/actions/getEnsResolver#usage) --------------------------------------------------------------- example.tsclient.ts import { normalize } from 'viem/ens' import { publicClient } from './client' const resolverAddress = await publicClient.getEnsResolver({ name: normalize('wevm.eth'), }) // '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41' Returns[](https://viem.sh/docs/ens/actions/getEnsResolver#returns) ------------------------------------------------------------------- `[Address](https://viem.sh/docs/glossary/types#address) ` The address of the resolver. Parameters[](https://viem.sh/docs/ens/actions/getEnsResolver#parameters) ------------------------------------------------------------------------- ### name[](https://viem.sh/docs/ens/actions/getEnsResolver#name) * **Type:** `string` Name to get the address for. const ensName = await publicClient.getEnsResolver({ name: normalize('wevm.eth'), }) ### blockNumber (optional)[](https://viem.sh/docs/ens/actions/getEnsResolver#blocknumber-optional) * **Type:** `number` The block number to perform the read against. const ensName = await publicClient.getEnsResolver({ name: normalize('wevm.eth'), blockNumber: 15121123n, }) ### blockTag (optional)[](https://viem.sh/docs/ens/actions/getEnsResolver#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` The block tag to perform the read against. const ensName = await publicClient.getEnsResolver({ name: normalize('wevm.eth'), blockTag: 'safe', }) ### universalResolverAddress (optional)[](https://viem.sh/docs/ens/actions/getEnsResolver#universalresolveraddress-optional) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` * **Default:** `client.chain.contracts.ensUniversalResolver.address` Address of ENS Universal Resolver Contract. const ensName = await publicClient.getEnsResolver({ name: normalize('wevm.eth'), universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/ens/actions/getEnsResolver.md) Copy page for AI Ask AI... ⌘ I --- # hashAuthorization · Viem [Skip to content](https://viem.sh/docs/eip7702/hashAuthorization#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K hashAuthorization ================= Calculates an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702) : `keccak256('0x05' || rlp([chain_id, address, nonce]))`. Import[](https://viem.sh/docs/eip7702/hashAuthorization#import) ---------------------------------------------------------------- import { hashAuthorization } from 'viem/utils' Usage[](https://viem.sh/docs/eip7702/hashAuthorization#usage) -------------------------------------------------------------- import { hashAuthorization } from 'viem/utils' hashAuthorization({ contractAddress: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', chainId: 1, nonce: 0, }) // 0xd428ed36e6098e46b40a4cb99b83b930b0ca1f054f40b5996589eda33c295663 Returns[](https://viem.sh/docs/eip7702/hashAuthorization#returns) ------------------------------------------------------------------ `[Hash](https://viem.sh/docs/glossary/types#hash) ` The hashed Authorization. Parameters[](https://viem.sh/docs/eip7702/hashAuthorization#parameters) ------------------------------------------------------------------------ ### address[](https://viem.sh/docs/eip7702/hashAuthorization#address) * **Type:** `Address` Address of the contract to set as code for the Authority. import { hashAuthorization } from 'viem/utils' hashAuthorization({ contractAddress: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', chainId: 1, nonce: 0, }) ### chainId[](https://viem.sh/docs/eip7702/hashAuthorization#chainid) * **Type:** `number` Chain ID to authorize. import { hashAuthorization } from 'viem/utils' hashAuthorization({ contractAddress: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', chainId: 1, nonce: 0, }) ### nonce[](https://viem.sh/docs/eip7702/hashAuthorization#nonce) * **Type:** `number` Nonce of the Authority to authorize. import { hashAuthorization } from 'viem/utils' hashAuthorization({ contractAddress: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', chainId: 1, nonce: 0, }) ### to[](https://viem.sh/docs/eip7702/hashAuthorization#to) * **Type:** `"hex" | "bytes"` * **Default:** `"hex"` Output format. import { hashAuthorization } from 'viem/utils' hashAuthorization({ contractAddress: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', chainId: 1, nonce: 0, to: 'bytes', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/eip7702/hashAuthorization.md) Copy page for AI Ask AI... ⌘ I --- # Terms · Viem [Skip to content](https://viem.sh/docs/glossary/terms#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Terms ===== Glossary of Terms in viem. Block[](https://viem.sh/docs/glossary/terms#block) --------------------------------------------------- A block is a bundled unit of information that include an ordered list of transactions and consensus-related information. Blocks are proposed by proof-of-stake validators, at which point they are shared across the entire peer-to-peer network, where they can easily be independently verified by all other nodes. Consensus rules govern what contents of a block are considered valid, and any invalid blocks are disregarded by the network. The ordering of these blocks and the transactions therein create a deterministic chain of events with the end representing the current state of the network. Chain[](https://viem.sh/docs/glossary/terms#chain) --------------------------------------------------- A Chain refers to a specific blockchain network or protocol that maintains a decentralized, distributed ledger of transactions and other data. Each Chain has its own rules, consensus mechanism, and native cryptocurrency (if any). Examples of Chains include: Ethereum Mainnet, Polygon, Optimism, Avalanche, Binance Smart Chain, etc. EIP-1559 Transaction[](https://viem.sh/docs/glossary/terms#eip-1559-transaction) --------------------------------------------------------------------------------- EIP-1559 is an Ethereum Improvement Proposal that was implemented in August 2021 as part of the London hard fork. It introduced a new transaction format for Ethereum transactions, which is referred to as an EIP-1559 transaction (aka "transaction type 2"). When a user creates an EIP-1559 transaction, they specify the maximum fee they are willing to pay (`maxFeePerGas`) as well as a tip (`maxPriorityFeePerGas`) to incentivize the miner. The actual fee paid by the user is then determined by the network based on the current demand for block space and the priority of the transaction. Event Log[](https://viem.sh/docs/glossary/terms#event-log) ----------------------------------------------------------- An Event Log is a record of an event emitted by a smart contract. Events are a type of function in a smart contract that can be triggered by specific actions or conditions, and they can be used to notify dapps of changes on the network. [See more](https://ethereum.org/en/developers/docs/smart-contracts/anatomy/#events-and-logs) Filter[](https://viem.sh/docs/glossary/terms#filter) ----------------------------------------------------- In Ethereum, a filter is a mechanism used to query the Ethereum blockchain for specific events or information. There are three types of filters in Ethereum: 1. Block filters - these filters allow users to monitor the blockchain for new blocks that have been added. 2. Pending Transaction filters - these filters allow users to monitor the blockchain for new pending transactions in the mempool. 3. Event filters - these filters allow users to monitor the blockchain for specific events emitted by smart contracts, such as a token transfer. When a filter is created, it returns a filter ID, which can be used to retrieve the results of the filter at a later time. Users can then periodically poll the filter for new events or changes that match the filter criteria. Human-Readable ABI[](https://viem.sh/docs/glossary/terms#human-readable-abi) ----------------------------------------------------------------------------- Human-Readable ABIs compress JSON ABIs into signatures that are nicer to read and less verbose to write. For more info, check out the [ABIType](https://abitype.dev/api/human) docs. Legacy Transaction[](https://viem.sh/docs/glossary/terms#legacy-transaction) ----------------------------------------------------------------------------- A Legacy Transaction in Ethereum refers to a transaction that was created using an older version of Ethereum's transaction format, known as "transaction type 0". This transaction format was used prior to the introduction of the EIP-1559 upgrade, which was implemented in August 2021. Non-conforming Log[](https://viem.sh/docs/glossary/terms#non-conforming-log) ----------------------------------------------------------------------------- A non-conforming log is a log where its `topics` & `data` do not match the **indexed** & **non-indexed** arguments on the `event`. `topics` correspond to **indexed** arguments, while `data` corresponds to **non-indexed** arguments. For example, here is an event definition that has 3 indexed arguments & 1 non-indexed arguments: event Transfer( bool indexed foo, uint256 baz, string indexed bar, boolean indexed barry ) A conforming log for the above signature would be: const log = { ... data: '0x 00...23c346 // ✅ non-indexed argument (baz) ', topics: [\ '0xdd...23b3ef', // event signature\ '0x00...000001', // ✅ indexed argument (foo)\ '0xae...e1cc58', // ✅ indexed argument (bar)\ '0x00...000000', // ✅ indexed argument (barry)\ ], ... } A non-conforming log for the above signature would be: const log = { ... data: '0x 00...23c346 // ✅ non-indexed argument (baz) 00...ae0000 // ❌ indexed argument (bar) 00...000001 // ❌ indexed argument (barry) ', topics: [\ '0xdd...23b3ef', // event signature\ '0x00...b92266', // ✅ indexed argument (foo)\ ], ... } A non-conforming log can arise when another contract could be using the same event signature, but with a different number of indexed & non-indexed arguments. For example, the definition for the above log would be: event Transfer( bool indexed foo, uint256 baz, string bar, boolean barry ) Transaction[](https://viem.sh/docs/glossary/terms#transaction) --------------------------------------------------------------- A transaction is a message sent by an Account requesting to perform an action on the Ethereum blockchain. Transactions can be used to transfer Ether between accounts, execute smart contract code, deploy smart contracts, etc. Transaction Receipt[](https://viem.sh/docs/glossary/terms#transaction-receipt) ------------------------------------------------------------------------------- A Transaction Receipt is a record of the result of a specific transaction on the Ethereum blockchain. When a transaction is submitted to the Ethereum network, it is processed by miners and included in a block. Once the block is added to the blockchain, a transaction receipt is generated and stored on the blockchain. A transaction receipt contains information about the transaction, including: * The transaction hash: a unique identifier for the transaction. * The block number and block hash: the block in which the transaction was included. * The gas used: the amount of gas consumed by the transaction. * The status of the transaction: "success" if the transaction was executed, otherwise "reverted" if the transaction reverted. * The logs generated by the transaction: any log events generated by the smart contract during the transaction execution. Transport[](https://viem.sh/docs/glossary/terms#transport) ----------------------------------------------------------- A Transport is the intermediary layer that is responsible for executing outgoing requests (ie. RPC requests) in viem. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/glossary/terms.md) Copy page for AI Ask AI... ⌘ I --- # Getting Started · Viem [Skip to content](https://viem.sh/docs/getting-started#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Getting Started =============== Get started with viem in just a few lines of code. Overview[](https://viem.sh/docs/getting-started#overview) ---------------------------------------------------------- viem is a TypeScript interface for Ethereum that provides low-level stateless primitives for interacting with Ethereum. viem is focused on developer experience, stability, bundle size, and performance: * **Developer experience** Automatic [type safety and inference](https://viem.sh/docs/typescript) , comprehensive documentation, composable APIs. * **Stability** Test suite runs against forked Ethereum networks, complete [test coverage](https://app.codecov.io/gh/wevm/viem) . * **Bundle size** Tree-shakable lightweight modules. * **Performance** Optimized encoding/parsing, async tasks only when necessary. You can learn more about the rationale behind the project in the [Why viem](https://viem.sh/docs/introduction) section. Installation[](https://viem.sh/docs/getting-started#installation) ------------------------------------------------------------------ Quick Start[](https://viem.sh/docs/getting-started#quick-start) ---------------------------------------------------------------- ### 1\. Set up your Client & Transport[](https://viem.sh/docs/getting-started#1-set-up-your-client--transport) Firstly, set up your [Client](https://viem.sh/docs/clients/intro) with a desired [Transport](https://viem.sh/docs/clients/intro) & [Chain](https://viem.sh/docs/chains/introduction) . import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' const client = createPublicClient({ chain: mainnet, transport: http(), }) ### 2\. Consume Actions[](https://viem.sh/docs/getting-started#2-consume-actions) Now that you have a Client set up, you can now interact with Ethereum and consume [Actions](https://viem.sh/docs/actions/public/introduction) ! import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' const client = createPublicClient({ chain: mainnet, transport: http(), }) const blockNumber = await client.getBlockNumber() Live example[](https://viem.sh/docs/getting-started#live-example) ------------------------------------------------------------------ [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/getting-started.mdx) Copy page for AI Ask AI... ⌘ I --- # Custom Transport · Viem [Skip to content](https://viem.sh/docs/clients/transports/custom#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Custom Transport ================ A function to create a Custom Transport for a Client The `custom` Transport accepts an [EIP-1193 `request` function](https://eips.ethereum.org/EIPS/eip-1193#request-1) as a parameter. This transport is useful for integrating with injected wallets, wallets that provide an EIP-1193 provider (eg. WalletConnect or Coinbase SDK), or even providing your own custom `request` function. Import[](https://viem.sh/docs/clients/transports/custom#import) ---------------------------------------------------------------- import { custom } from 'viem' Usage[](https://viem.sh/docs/clients/transports/custom#usage) -------------------------------------------------------------- You can use any [EIP-1193 compatible](https://eips.ethereum.org/EIPS/eip-1193) Ethereum Provider with the `custom` Transport: import { createWalletClient, custom } from 'viem' import { mainnet } from 'viem/chains' const client = createWalletClient({ chain: mainnet, transport: custom(window.ethereum!) }) Or you can define your own: import { createWalletClient, custom } from 'viem' import { mainnet } from 'viem/chains' import { customRpc } from './rpc' const client = createWalletClient({ chain: mainnet, transport: custom({ async request({ method, params }) { const response = await customRpc.request(method, params) return response } }) }) Parameters[](https://viem.sh/docs/clients/transports/custom#parameters) ------------------------------------------------------------------------ ### provider[](https://viem.sh/docs/clients/transports/custom#provider) * **Type:** `custom` An [EIP-1193 `request` function](https://eips.ethereum.org/EIPS/eip-1193#request) function. import { customRpc } from './rpc' const transport = custom({ async request({ method, params }) { const response = await customRpc.request(method, params) return response } }) ### key (optional)[](https://viem.sh/docs/clients/transports/custom#key-optional) * **Type:** `string` * **Default:** `"custom"` A key for the Transport. const transport = custom( window.ethereum!, { key: 'windowProvider', } ) ### name (optional)[](https://viem.sh/docs/clients/transports/custom#name-optional) * **Type:** `string` * **Default:** `"Ethereum Provider"` A name for the Transport const transport = custom( window.ethereum!, { name: 'Window Ethereum Provider', } ) ### retryCount (optional)[](https://viem.sh/docs/clients/transports/custom#retrycount-optional) * **Type:** `number` * **Default:** `3` The max number of times to retry when a request fails. const transport = custom(window.ethereum!, { retryCount: 5, }) ### retryDelay (optional)[](https://viem.sh/docs/clients/transports/custom#retrydelay-optional) * **Type:** `number` * **Default:** `150` The base delay (in ms) between retries. By default, the Transport will use [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff) (`~~(1 << count) * retryDelay`), which means the time between retries is not constant. const transport = custom(window.ethereum!, { retryDelay: 100, }) Gotchas[](https://viem.sh/docs/clients/transports/custom#gotchas) ------------------------------------------------------------------ * If you are pairing the `custom` Transport with a [Public Client](https://viem.sh/docs/clients/public) , ensure that your provider supports [Public Actions](https://viem.sh/docs/actions/public/introduction) . [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/clients/transports/custom.md) Copy page for AI Ask AI... ⌘ I --- # normalize · Viem [Skip to content](https://viem.sh/docs/ens/utilities/normalize#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K normalize ========= Normalizes ENS name to [UTS51](https://unicode.org/reports/tr51) and [ENSIP-15](https://github.com/ensdomains/docs/blob/9edf9443de4333a0ea7ec658a870672d5d180d53/ens-improvement-proposals/ensip-15-normalization-standard.md) . Internally uses `[@adraffy/ens-normalize](https://github.com/adraffy/ens-normalize.js) `. Import[](https://viem.sh/docs/ens/utilities/normalize#import) -------------------------------------------------------------- import { normalize } from 'viem/ens' Usage[](https://viem.sh/docs/ens/utilities/normalize#usage) ------------------------------------------------------------ import { normalize } from 'viem/ens' normalize('wagmi-d𝝣v.eth') // 'wagmi-dξv.eth' Returns[](https://viem.sh/docs/ens/utilities/normalize#returns) ---------------------------------------------------------------- `string` The normalized ENS label. Parameters[](https://viem.sh/docs/ens/utilities/normalize#parameters) ---------------------------------------------------------------------- ### name[](https://viem.sh/docs/ens/utilities/normalize#name) * **Type:** `string` A ENS name. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/ens/utilities/normalize.md) Copy page for AI Ask AI... ⌘ I --- # getEnsAvatar · Viem [Skip to content](https://viem.sh/docs/ens/actions/getEnsAvatar#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getEnsAvatar ============ Gets the avatar of an ENS name. Calls `[getEnsText](https://viem.sh/docs/ens/actions/getEnsText) ` with `key` set to `'avatar'`. Usage[](https://viem.sh/docs/ens/actions/getEnsAvatar#usage) ------------------------------------------------------------- example.tsclient.ts import { normalize } from 'viem/ens' import { publicClient } from './client' const ensText = await publicClient.getEnsAvatar({ name: normalize('wevm.eth'), }) // 'https://ipfs.io/ipfs/Qma8mnp6xV3J2cRNf3mTth5C8nV11CAnceVinc3y8jSbio' Returns[](https://viem.sh/docs/ens/actions/getEnsAvatar#returns) ----------------------------------------------------------------- `string | null` The avatar URI for ENS name. Returns `null` if the avatar cannot be resolved from the ENS name. Parameters[](https://viem.sh/docs/ens/actions/getEnsAvatar#parameters) ----------------------------------------------------------------------- ### name[](https://viem.sh/docs/ens/actions/getEnsAvatar#name) * **Type:** `string` ENS name to get Text for. const ensText = await publicClient.getEnsAvatar({ name: normalize('wevm.eth'), }) ### assetGatewayUrls (optional)[](https://viem.sh/docs/ens/actions/getEnsAvatar#assetgatewayurls-optional) * **Type:** `{ ipfs?: string; arweave?: string }` Gateway urls to resolve IPFS and/or Arweave assets. const ensText = await publicClient.getEnsAvatar({ name: normalize('wevm.eth'), assetGatewayUrls: { ipfs: 'https://cloudflare-ipfs.com' } }) ### blockNumber (optional)[](https://viem.sh/docs/ens/actions/getEnsAvatar#blocknumber-optional) * **Type:** `number` The block number to perform the read against. const ensText = await publicClient.getEnsAvatar({ name: normalize('wevm.eth'), blockNumber: 15121123n, }) ### blockTag (optional)[](https://viem.sh/docs/ens/actions/getEnsAvatar#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` The block tag to perform the read against. const ensText = await publicClient.getEnsAvatar({ name: normalize('wevm.eth'), blockTag: 'safe', }) ### gatewayUrls (optional)[](https://viem.sh/docs/ens/actions/getEnsAvatar#gatewayurls-optional) * **Type:** `string[]` A set of Universal Resolver gateways, used for resolving CCIP-Read requests made through the ENS Universal Resolver Contract. const ensText = await publicClient.getEnsAvatar({ name: normalize('wevm.eth'), gatewayUrls: ["https://ccip.ens.xyz"], }) ### strict (optional)[](https://viem.sh/docs/ens/actions/getEnsAvatar#strict-optional) * **Type:** `boolean` * **Default:** `false` A boolean value that when set to true will strictly propagate all ENS Universal Resolver Contract errors. const ensText = await publicClient.getEnsAvatar({ name: normalize('wevm.eth'), strict: true, }) ### universalResolverAddress (optional)[](https://viem.sh/docs/ens/actions/getEnsAvatar#universalresolveraddress-optional) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` * **Default:** `client.chain.contracts.ensUniversalResolver.address` Address of ENS Universal Resolver Contract. const ensText = await publicClient.getEnsAvatar({ name: normalize('wevm.eth'), universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/ens/actions/getEnsAvatar.md) Copy page for AI Ask AI... ⌘ I --- # parseSiweMessage · Viem [Skip to content](https://viem.sh/docs/siwe/utilities/parseSiweMessage#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K parseSiweMessage ================ Parses [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message into message fields object. Import[](https://viem.sh/docs/siwe/utilities/parseSiweMessage#import) ---------------------------------------------------------------------- import { parseSiweMessage } from 'viem/siwe' Usage[](https://viem.sh/docs/siwe/utilities/parseSiweMessage#usage) -------------------------------------------------------------------- import { parseSiweMessage } from 'viem/siwe' const message = `example.com wants you to sign in with your Ethereum account: 0xA0Cf798816D4b9b9866b5330EEa46a18382f251e I accept the ExampleOrg Terms of Service: https://example.com/tos URI: https://example.com/path Version: 1 Chain ID: 1 Nonce: foobarbaz Issued At: 2023-02-01T00:00:00.000Z` const fields = parseSiweMessage(message) fields.address Returns[](https://viem.sh/docs/siwe/utilities/parseSiweMessage#returns) ------------------------------------------------------------------------ `SiweMessage` EIP-4361 fields object Parameters[](https://viem.sh/docs/siwe/utilities/parseSiweMessage#parameters) ------------------------------------------------------------------------------ ### message[](https://viem.sh/docs/siwe/utilities/parseSiweMessage#message) * **Type:** `string` EIP-4361 formatted message [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/siwe/utilities/parseSiweMessage.md) Copy page for AI Ask AI... ⌘ I --- # getEnsText · Viem [Skip to content](https://viem.sh/docs/ens/actions/getEnsText#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getEnsText ========== Gets a text record for specified ENS name. Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract. Usage[](https://viem.sh/docs/ens/actions/getEnsText#usage) ----------------------------------------------------------- example.tsclient.ts import { normalize } from 'viem/ens' import { publicClient } from './client' const ensText = await publicClient.getEnsText({ name: normalize('wevm.eth'), key: 'com.twitter', }) // 'wevm_dev' Returns[](https://viem.sh/docs/ens/actions/getEnsText#returns) --------------------------------------------------------------- `string | null` The text record for ENS name. Returns `null` if name does not have text assigned. Parameters[](https://viem.sh/docs/ens/actions/getEnsText#parameters) --------------------------------------------------------------------- ### name[](https://viem.sh/docs/ens/actions/getEnsText#name) * **Type:** `string` ENS name to get Text for. const ensText = await publicClient.getEnsText({ name: normalize('wevm.eth'), key: 'com.twitter', }) ### key[](https://viem.sh/docs/ens/actions/getEnsText#key) * **Type:** `string` ENS key to get Text for. const ensText = await publicClient.getEnsText({ name: normalize('wevm.eth'), key: 'com.twitter', }) ### blockNumber (optional)[](https://viem.sh/docs/ens/actions/getEnsText#blocknumber-optional) * **Type:** `number` The block number to perform the read against. const ensText = await publicClient.getEnsText({ name: normalize('wevm.eth'), key: 'com.twitter', blockNumber: 15121123n, }) ### blockTag (optional)[](https://viem.sh/docs/ens/actions/getEnsText#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` The block tag to perform the read against. const ensText = await publicClient.getEnsText({ name: normalize('wevm.eth'), key: 'com.twitter', blockTag: 'safe', }) ### gatewayUrls (optional)[](https://viem.sh/docs/ens/actions/getEnsText#gatewayurls-optional) * **Type:** `string[]` A set of Universal Resolver gateways, used for resolving CCIP-Read requests made through the ENS Universal Resolver Contract. const ensText = await publicClient.getEnsText({ name: normalize('wevm.eth'), key: 'com.twitter', gatewayUrls: ["https://ccip.ens.xyz"], }) ### strict (optional)[](https://viem.sh/docs/ens/actions/getEnsText#strict-optional) * **Type:** `boolean` * **Default:** `false` A boolean value that when set to true will strictly propagate all ENS Universal Resolver Contract errors. const ensText = await publicClient.getEnsText({ name: normalize('wevm.eth'), key: 'com.twitter', strict: true, }) ### universalResolverAddress (optional)[](https://viem.sh/docs/ens/actions/getEnsText#universalresolveraddress-optional) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` * **Default:** `client.chain.contracts.ensUniversalResolver.address` Address of ENS Universal Resolver Contract. const ensText = await publicClient.getEnsText({ name: normalize('wevm.eth'), key: 'com.twitter', universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/ens/actions/getEnsText.md) Copy page for AI Ask AI... ⌘ I --- # getEnsName · Viem [Skip to content](https://viem.sh/docs/ens/actions/getEnsName#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getEnsName ========== Gets primary name for specified address. Calls `reverse(bytes)` on ENS Universal Resolver Contract to "reverse resolve" the address to the primary ENS name. Usage[](https://viem.sh/docs/ens/actions/getEnsName#usage) ----------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const ensName = await publicClient.getEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', }) // 'wevm.eth' ### Chain-specific Resolution[](https://viem.sh/docs/ens/actions/getEnsName#chain-specific-resolution) `getEnsName` also supports chain-specific name resolution via [ENSIP-19](https://docs.ens.domains/ensip/19/) . In order to use chain-specific resolution, you must: 1. Ensure your client is configured with `mainnet` (or another L1 that supports ENS Universal Resolver) 2. Pass a `coinType` parameter to `getEnsName` (as seen in `example.ts`) import { createPublicClient, http, toCoinType } from 'viem' import { mainnet, base } from 'viem/chains' export const publicClient = createPublicClient({ chain: mainnet, transport: http() }) const ensName = await publicClient.getEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', coinType: toCoinType(base.id), }) // 'wevm.eth' Returns[](https://viem.sh/docs/ens/actions/getEnsName#returns) --------------------------------------------------------------- `string` The primary ENS name for the address. Returns `null` if address does not have primary name assigned. Parameters[](https://viem.sh/docs/ens/actions/getEnsName#parameters) --------------------------------------------------------------------- ### address[](https://viem.sh/docs/ens/actions/getEnsName#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` Address to get primary ENS name for. const ensName = await publicClient.getEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', }) ### blockNumber (optional)[](https://viem.sh/docs/ens/actions/getEnsName#blocknumber-optional) * **Type:** `number` The block number to perform the read against. const ensName = await publicClient.getEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', blockNumber: 15121123n, }) ### blockTag (optional)[](https://viem.sh/docs/ens/actions/getEnsName#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` The block tag to perform the read against. const ensName = await publicClient.getEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', blockTag: 'safe', }) ### coinType (optional)[](https://viem.sh/docs/ens/actions/getEnsName#cointype-optional) * **Type:** `bigint` ENSIP-9 compliant coinType (chain) to get ENS name for. import { base } from 'viem/chains' const ensName = await publicClient.getEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', coinType: toCoinType(base.id), }) ### gatewayUrls (optional)[](https://viem.sh/docs/ens/actions/getEnsName#gatewayurls-optional) * **Type:** `string[]` A set of Universal Resolver gateways, used for resolving CCIP-Read requests made through the ENS Universal Resolver Contract. const ensName = await publicClient.getEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', gatewayUrls: ["https://ccip.ens.xyz"], }) ### strict (optional)[](https://viem.sh/docs/ens/actions/getEnsName#strict-optional) * **Type:** `boolean` * **Default:** `false` A boolean value that when set to true will strictly propagate all ENS Universal Resolver Contract errors. const ensName = await publicClient.getEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', strict: true, }) ### universalResolverAddress (optional)[](https://viem.sh/docs/ens/actions/getEnsName#universalresolveraddress-optional) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` * **Default:** `client.chain.contracts.ensUniversalResolver.address` Address of ENS Universal Resolver Contract. const ensName = await publicClient.getEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', }) Live Example[](https://viem.sh/docs/ens/actions/getEnsName#live-example) ------------------------------------------------------------------------- Check out the usage of `getEnsName` in the live [ENS Examples](https://stackblitz.com/github/wevm/viem/tree/main/examples/ens) below. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/ens/actions/getEnsName.md) Copy page for AI Ask AI... ⌘ I --- # validateSiweMessage · Viem [Skip to content](https://viem.sh/docs/siwe/utilities/validateSiweMessage#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K validateSiweMessage =================== Validates [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) message. Import[](https://viem.sh/docs/siwe/utilities/validateSiweMessage#import) ------------------------------------------------------------------------- import { validateSiweMessage } from 'viem/siwe' Usage[](https://viem.sh/docs/siwe/utilities/validateSiweMessage#usage) ----------------------------------------------------------------------- import { validateSiweMessage } from 'viem/siwe' const valid = validateSiweMessage({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', message: { address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', }, }) Returns[](https://viem.sh/docs/siwe/utilities/validateSiweMessage#returns) --------------------------------------------------------------------------- `boolean` Whether the message fields are valid. Parameters[](https://viem.sh/docs/siwe/utilities/validateSiweMessage#parameters) --------------------------------------------------------------------------------- ### message[](https://viem.sh/docs/siwe/utilities/validateSiweMessage#message) * **Type:** `Partial` EIP-4361 message fields. ### address (optional)[](https://viem.sh/docs/siwe/utilities/validateSiweMessage#address-optional) * **Type:** `string` Ethereum address to check against. ### domain (optional)[](https://viem.sh/docs/siwe/utilities/validateSiweMessage#domain-optional) * **Type:** `string` [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against. ### nonce (optional)[](https://viem.sh/docs/siwe/utilities/validateSiweMessage#nonce-optional) * **Type:** `string` Random string to check against. ### scheme (optional)[](https://viem.sh/docs/siwe/utilities/validateSiweMessage#scheme-optional) * **Type:** `string` [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against. ### time (optional)[](https://viem.sh/docs/siwe/utilities/validateSiweMessage#time-optional) * **Type:** `Date` * **Default:** `new Date()` Current time to check optional `[expirationTime](http://localhost:5173/docs/siwe/utilities/createSiweMessage#expirationtime-optional) ` and `[notBefore](https://viem.sh/docs/siwe/utilities/createSiweMessage#notbefore-optional) ` message fields. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/siwe/utilities/validateSiweMessage.md) Copy page for AI Ask AI... ⌘ I --- # Fallback Transport · Viem [Skip to content](https://viem.sh/docs/clients/transports/fallback#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Fallback Transport ================== A function to create a Fallback Transport for a Client The `fallback` Transport consumes **multiple** Transports. If a Transport request fails, it will fall back to the next one in the list. Import[](https://viem.sh/docs/clients/transports/fallback#import) ------------------------------------------------------------------ import { fallback } from 'viem' Usage[](https://viem.sh/docs/clients/transports/fallback#usage) ---------------------------------------------------------------- import { createPublicClient, fallback, http } from 'viem' import { mainnet } from 'viem/chains' const client = createPublicClient({ chain: mainnet, transport: fallback([ \ http('https://1.rpc.thirdweb.com/...'), \ http('https://mainnet.infura.io/v3/...') \ ]), }) ### Transport Ranking[](https://viem.sh/docs/clients/transports/fallback#transport-ranking) Transport Ranking enables each of the Transports passed to the `fallback` Transport are automatically ranked based on their **latency** & **stability** via a weighted moving score algorithm. Every 10 seconds (`interval`), the `fallback` Transport will ping each transport in the list. For the past 10 pings (`sampleCount`), they will be ranked based on if they responded (stability) and how fast they responded (latency). The algorithm applies a weight of `0.7` to the stability score, and a weight of `0.3` to the latency score to derive the final score which it is ranked on. The Transport that has the best latency & stability score over the sample period is prioritized first. You can turn on automated ranking with the `rank` option: const client = createPublicClient({ chain: mainnet, transport: fallback([ \ http('https://1.rpc.thirdweb.com/...'), \ http('https://mainnet.infura.io/v3/...') \ ], { rank: true }), }) You can also modify the default rank config: const client = createPublicClient({ chain: mainnet, transport: fallback( [\ http('https://1.rpc.thirdweb.com/...'), \ http('https://mainnet.infura.io/v3/...') \ ], { rank: { interval: 60_000, sampleCount: 5, timeout: 500, weights: { latency: 0.3, stability: 0.7 } } } ), }) Parameters[](https://viem.sh/docs/clients/transports/fallback#parameters) -------------------------------------------------------------------------- ### rank (optional)[](https://viem.sh/docs/clients/transports/fallback#rank-optional) * **Type:** `boolean | RankOptions` * **Default:** `false` Whether or not to automatically rank the Transports based on their latency & stability. Set to `false` to disable automatic ranking. const transport = fallback([thirdweb, infura], { rank: false, }) ### rank.interval (optional)[](https://viem.sh/docs/clients/transports/fallback#rankinterval-optional) * **Type:** `number` * **Default:** `client.pollingInterval` The polling interval (in ms) at which the ranker should ping the RPC URL. const transport = fallback([thirdweb, infura], { rank: { interval: 5_000 }, }) ### rank.ping (optional)[](https://viem.sh/docs/clients/transports/fallback#rankping-optional) * **Type:** `({ transport }: { transport: Transport }) => Promise` * **Default:** `({ transport }) => transport.request({ method: 'net_listening' })` Function to call to ping the Transport. Defaults to calling the `net_listening` method to check if the Transport is online. const transport = fallback([thirdweb, infura], { rank: { ping: ({ transport }) => transport.request({ method: 'eth_blockNumber' }) }, }) ### rank.sampleCount (optional)[](https://viem.sh/docs/clients/transports/fallback#ranksamplecount-optional) * **Type:** `number` * **Default:** `10` The number of previous samples to perform ranking on. const transport = fallback([thirdweb, infura], { rank: { sampleCount: 10 }, }) ### rank.timeout (optional)[](https://viem.sh/docs/clients/transports/fallback#ranktimeout-optional) * **Type:** `number` * **Default:** `1_000` Timeout when sampling transports. const transport = fallback([thirdweb, infura], { rank: { timeout: 500 }, }) ### rank.weights.latency (optional)[](https://viem.sh/docs/clients/transports/fallback#rankweightslatency-optional) * **Type:** `number` * **Default:** `0.3` The weight to apply to the latency score. The weight is proportional to the other values in the `weights` object. const transport = fallback([thirdweb, infura], { rank: { weights: { latency: 0.4, stability: 0.6 } }, }) ### rank.weights.stability (optional)[](https://viem.sh/docs/clients/transports/fallback#rankweightsstability-optional) * **Type:** `number` * **Default:** `0.7` The weight to apply to the stability score. The weight is proportional to the other values in the `weights` object. const transport = fallback([thirdweb, infura], { rank: { weights: { latency: 0.4, stability: 0.6 } }, }) ### retryCount (optional)[](https://viem.sh/docs/clients/transports/fallback#retrycount-optional) * **Type:** `number` * **Default:** `3` The max number of times to retry when a request fails. > Note: The fallback will first try all the Transports before retrying. const transport = fallback([thirdweb, infura], { retryCount: 5, }) ### retryDelay (optional)[](https://viem.sh/docs/clients/transports/fallback#retrydelay-optional) * **Type:** `number` * **Default:** `150` The base delay (in ms) between retries. By default, the Transport will use [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff) (`~~(1 << count) * retryDelay`), which means the time between retries is not constant. const transport = fallback([thirdweb, infura], { retryDelay: 100, }) ### shouldThrow (optional)[](https://viem.sh/docs/clients/transports/fallback#shouldthrow-optional) * **Type:** `function` Whether the `fallback` Transport should immediately throw an error, or continue and try the next Transport. const transport = fallback([thirdweb, infura], { shouldThrow: (err: Error) => { return err.message.includes('sad times') }, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/clients/transports/fallback.md) Copy page for AI Ask AI... ⌘ I --- # Blob Transactions · Viem [Skip to content](https://viem.sh/docs/guides/blob-transactions#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Blob Transactions ================= Sending your first Blob Transaction with Viem. Blob Transactions are a new type of transaction in Ethereum (introduced in [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844) ) that allows you to broadcast BLObs (Binary Large Objects) to the Ethereum network. Blob Transactions are like any other transaction, but with the added ability to carry a payload of Blobs. Blobs are extremely larger than regular calldata (~128kB), however unlike regular calldata, they are not accessible on the EVM. The EVM can only view the commitments of the blobs. Blobs are also transient, and only last for 4096 epochs (approx. 18 days). To read more on Blob Transactions and EIP-4844, check out these resources: * [EIP-4844 Spec](https://eips.ethereum.org/EIPS/eip-4844) * [EIP-4844 Website](https://www.eip4844.com/#faq) * [EIP-4844 FAQ](https://notes.ethereum.org/@vbuterin/proto_danksharding_faq#Proto-Danksharding-FAQ) In this guide, we will walk you through how to send your first Blob Transaction with Viem. Set up Client[](https://viem.sh/docs/guides/blob-transactions#set-up-client) ----------------------------------------------------------------------------- We will first set up our Viem Client. Let's create a `client.ts` file that holds our Client. client.ts import { createWalletClient, http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' export const account = privateKeyToAccount('0x...') export const client = createWalletClient({ account, chain: mainnet, transport: http() }) Install KZG bindings[](https://viem.sh/docs/guides/blob-transactions#install-kzg-bindings) ------------------------------------------------------------------------------------------- Next, we will need to install some KZG bindings. KZG will be used to compute the commitments of the blobs, and generate proofs from the blobs & commitments. The commitments and proofs are needed to serialize and sign the Blob Transaction before we send it off. A couple of KZG implementations we recommend are: * [c-kzg](https://github.com/ethereum/c-kzg-4844) : Node.js bindings to c-kzg. * [kzg-wasm](https://github.com/ethereumjs/kzg-wasm) : WebAssembly bindings to c-kzg. Set up KZG interface[](https://viem.sh/docs/guides/blob-transactions#set-up-kzg-interface) ------------------------------------------------------------------------------------------- After that, we will need to hook up the KZG bindings to Viem. Let's create a `kzg.ts` file that holds our KZG interface. kzg.tsclient.ts import * as cKzg from 'c-kzg' import { setupKzg } from 'viem' import { mainnetTrustedSetupPath } from 'viem/node' export const kzg = setupKzg(cKzg, mainnetTrustedSetupPath) Send Blob Transaction[](https://viem.sh/docs/guides/blob-transactions#send-blob-transaction) --------------------------------------------------------------------------------------------- Now that we have our Client and KZG interface set up, we can send our first Blob Transaction. For demonstration purposes, we will construct a blob with a simple string: `"hello world"`, and send it to the zero address. example.tskzg.tsclient.ts import { parseGwei, stringToHex, toBlobs } from 'viem' import { account, client } from './client' import { kzg } from './kzg' const blobs = toBlobs({ data: stringToHex('hello world') }) const hash = await client.sendTransaction({ blobs, kzg, maxFeePerBlobGas: parseGwei('30'), to: '0x0000000000000000000000000000000000000000', }) That's it![](https://viem.sh/docs/guides/blob-transactions#thats-it) --------------------------------------------------------------------- You've just sent your first Blob Transaction with Viem. With the `hash` you received in Step 4, you can now track your Blob Transaction on a blob explorer like [Blobscan](https://blobscan.com/) . [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/guides/blob-transactions.md) Copy page for AI Ask AI... ⌘ I --- # recoverAuthorizationAddress · Viem [Skip to content](https://viem.sh/docs/eip7702/recoverAuthorizationAddress#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K recoverAuthorizationAddress =========================== Recovers the original signing address from a signed Authorization object. Import[](https://viem.sh/docs/eip7702/recoverAuthorizationAddress#import) -------------------------------------------------------------------------- import { recoverAuthorizationAddress } from 'viem/utils' Usage[](https://viem.sh/docs/eip7702/recoverAuthorizationAddress#usage) ------------------------------------------------------------------------ example.tsclient.ts import { privateKeyToAccount } from 'viem/accounts' import { recoverAuthorizationAddress } from 'viem/utils' import { walletClient } from './client' const eoa = privateKeyToAccount('0x...') const authorization = await walletClient.signAuthorization({ account: eoa, authorization: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2' }) const address = await recoverAuthorizationAddress({ authorization, }) Returns[](https://viem.sh/docs/eip7702/recoverAuthorizationAddress#returns) ---------------------------------------------------------------------------- `Address` The address that signed the Authorization object. Parameters[](https://viem.sh/docs/eip7702/recoverAuthorizationAddress#parameters) ---------------------------------------------------------------------------------- ### authorization[](https://viem.sh/docs/eip7702/recoverAuthorizationAddress#authorization) * **Type:** `Authorization | SignedAuthorization` The Authorization object that was signed. const authorization = await walletClient.signAuthorization({ authorization: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2' }) const address = await recoverAuthorizationAddress({ authorization, }) ### signature[](https://viem.sh/docs/eip7702/recoverAuthorizationAddress#signature) * **Type:** `Hex | ByteArray | Signature | SignedAuthorization` The signature that was generated by signing the Authorization object with the address's private key. const signature = await walletClient.signAuthorization({ contractAddress: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', chainId: 1, nonce: 0, }) const address = await recoverAuthorizationAddress({ authorization: { contractAddress: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', chainId: 1, nonce: 0, }, signature, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/eip7702/recoverAuthorizationAddress.md) Copy page for AI Ask AI... ⌘ I --- # Test Client · Viem [Skip to content](https://viem.sh/docs/clients/test#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Test Client =========== A function to create a Test Client A Test Client is an interface to "test" JSON-RPC API methods accessible through a local Ethereum test node such as [Anvil](https://getfoundry.sh/anvil/overview) or [Hardhat](https://hardhat.org/) such as mining blocks, impersonating accounts, setting fees, etc through [Test Actions](https://viem.sh/docs/actions/test/introduction) . The `createTestClient` function sets up a Test RPC Client with a given [Transport](https://viem.sh/docs/clients/intro) . Import[](https://viem.sh/docs/clients/test#import) --------------------------------------------------- import { createTestClient } from 'viem' Usage[](https://viem.sh/docs/clients/test#usage) ------------------------------------------------- Initialize a Client with your desired [Chain](https://viem.sh/docs/chains/introduction) , [Transport](https://viem.sh/docs/clients/intro) (e.g. `http`) and [mode](https://viem.sh/docs/clients/test#mode) (e.g. `"anvil"`). import { createTestClient, http } from 'viem' import { foundry } from 'viem/chains' const client = createTestClient({ chain: foundry, mode: 'anvil', transport: http(), }) Then you can consume [Test Actions](https://viem.sh/docs/actions/test/introduction) : const mine = await client.mine({ blocks: 1 }) ### Extending with Public & Wallet Actions[](https://viem.sh/docs/clients/test#extending-with-public--wallet-actions) When interacting with a Ethereum test node, you may also find yourself wanting to interact with [Public Actions](https://viem.sh/docs/actions/public/introduction) and [Wallet Actions](https://viem.sh/docs/actions/wallet/introduction) with the same `chain` and `transport`. Instead of creating three different Clients, you can instead just extend the Test Client with those actions: import { createTestClient, http, publicActions, walletActions } from 'viem' import { foundry } from 'viem/chains' const client = createTestClient({ chain: foundry, mode: 'anvil', transport: http(), }) .extend(publicActions) .extend(walletActions) const blockNumber = await client.getBlockNumber() // Public Action const hash = await client.sendTransaction({ ... }) // Wallet Action const mine = await client.mine({ blocks: 1 }) // Test Action Parameters[](https://viem.sh/docs/clients/test#parameters) ----------------------------------------------------------- ### mode[](https://viem.sh/docs/clients/test#mode) * **Type:** `"anvil" | "hardhat" | "ganache"` Mode of the Test Client. const client = createTestClient({ chain: foundry, mode: 'anvil', transport: http(), }) ### transport[](https://viem.sh/docs/clients/test#transport) * **Type:** [Transport](https://viem.sh/docs/glossary/types#transport) [Transport](https://viem.sh/docs/clients/intro) of the Test Client. const client = createTestClient({ chain: foundry, mode: 'anvil', transport: http(), }) ### account (optional)[](https://viem.sh/docs/clients/test#account-optional) * **Type:** `Account | Address` The Account to use for the Client. This will be used for Actions that require an `account` as an argument. Accepts a [JSON-RPC Account](https://viem.sh/docs/accounts/jsonRpc) or [Local Account (Private Key, etc)](https://viem.sh/docs/accounts/local/privateKeyToAccount) . import { privateKeyToAccount } from 'viem/accounts' const client = createTestClient({ account: privateKeyToAccount('0x...'), chain: foundry, mode: 'anvil', transport: http(), }) ### chain (optional)[](https://viem.sh/docs/clients/test#chain-optional) * **Type:** [Chain](https://viem.sh/docs/glossary/types#chain) [Chain](https://viem.sh/docs/chains/introduction) of the Test Client. const client = createTestClient({ chain: foundry, mode: 'anvil', transport: http(), }) ### cacheTime (optional)[](https://viem.sh/docs/clients/test#cachetime-optional) * **Type:** `number` * **Default:** `client.pollingInterval` Time (in ms) that cached data will remain in memory. const client = createTestClient({ cacheTime: 10_000, chain: foundry, mode: 'anvil', transport: http(), }) ### name (optional)[](https://viem.sh/docs/clients/test#name-optional) * **Type:** `string` * **Default:** `"Test Client"` A name for the Client. const client = createTestClient({ chain: foundry, mode: 'anvil', name: 'Anvil Client', transport: http(), }) ### pollingInterval (optional)[](https://viem.sh/docs/clients/test#pollinginterval-optional) * **Type:** `number` * **Default:** `4_000` Frequency (in ms) for polling enabled Actions. const client = createTestClient({ chain: foundry, mode: 'anvil', pollingInterval: 10_000, transport: http(), }) ### rpcSchema (optional)[](https://viem.sh/docs/clients/test#rpcschema-optional) * **Type:** `RpcSchema` * **Default:** `TestRpcSchema` Typed JSON-RPC schema for the client. import { createTestClient, http } from 'viem' import { foundry } from 'viem/chains' // @noErrors // ---cut--- import { rpcSchema } from 'viem' type CustomRpcSchema = [{ \ Method: 'eth_wagmi', \ Parameters: [string] \ ReturnType: string\ }] const client = createTestClient({ chain: foundry, rpcSchema: rpcSchema(), transport: http() }) const result = await client.request({ method: 'eth_wa // [!code focus] // ^| params: ['hello'], }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/clients/test.md) Copy page for AI Ask AI... ⌘ I --- # verifyMessage · Viem [Skip to content](https://viem.sh/docs/actions/public/verifyMessage#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K verifyMessage ============= Verify that a message was signed by the provided address. Supports verification of: * **Externally Owned Accounts** * **Smart Contract Accounts:** * **Deployed** (via [ERC-1271](https://eips.ethereum.org/EIPS/eip-1271) ) * **Pre-deployed** (via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492) ) * **Pre-delegated** (via [ERC-8010](https://github.com/ethereum/ERCs/pull/1186) ) Usage[](https://viem.sh/docs/actions/public/verifyMessage#usage) ----------------------------------------------------------------- example.tsclient.ts import { account, walletClient, publicClient } from './client' const signature = await walletClient.signMessage({ account, message: 'hello world', }) const valid = await publicClient.verifyMessage({ address: account.address, message: 'hello world', signature, }) true Returns[](https://viem.sh/docs/actions/public/verifyMessage#returns) --------------------------------------------------------------------- `boolean` Whether the signed message is valid for the given address. Parameters[](https://viem.sh/docs/actions/public/verifyMessage#parameters) --------------------------------------------------------------------------- ### address[](https://viem.sh/docs/actions/public/verifyMessage#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The Ethereum address that signed the original message. const valid = await publicClient.verifyMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ### message[](https://viem.sh/docs/actions/public/verifyMessage#message) * **Type:** `string` The message to be verified. By default, viem verifies the UTF-8 representation of the message. const valid = await publicClient.verifyMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) To verify the data representation of the message, you can use the `raw` attribute. const valid = await publicClient.verifyMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: { raw: '0x68656c6c6f20776f726c64' }, signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ### signature[](https://viem.sh/docs/actions/public/verifyMessage#signature) * **Type:** `Hex | ByteArray | Signature` The signature that was generated by signing the message with the address's signer. const valid = await publicClient.verifyMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/verifyMessage.md) Copy page for AI Ask AI... ⌘ I --- # getEnsAddress · Viem [Skip to content](https://viem.sh/docs/ens/actions/getEnsAddress#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getEnsAddress ============= Gets address for ENS name. Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract to resolve the ENS name to address. Usage[](https://viem.sh/docs/ens/actions/getEnsAddress#usage) -------------------------------------------------------------- example.tsclient.ts import { normalize } from 'viem/ens' import { publicClient } from './client' const ensAddress = await publicClient.getEnsAddress({ name: normalize('wevm.eth'), }) // '0xd2135CfB216b74109775236E36d4b433F1DF507B' ### Chain-specific Resolution[](https://viem.sh/docs/ens/actions/getEnsAddress#chain-specific-resolution) `getEnsAddress` also supports chain-specific address resolution via [ENSIP-19](https://docs.ens.domains/ensip/19/) . In order to use chain-specific resolution, you must: 1. Ensure your client is configured with `mainnet` (or another L1 that supports ENS Universal Resolver) 2. Pass a `coinType` parameter to `getEnsAddress` (as seen in `example.ts`) import { createPublicClient, http } from 'viem' import { mainnet, base } from 'viem/chains' import { normalize, toCoinType } from 'viem/ens' export const publicClient = createPublicClient({ chain: mainnet, transport: http() }) const ensAddress = await publicClient.getEnsAddress({ name: normalize('wevm.eth'), coinType: toCoinType(base.id), }) // '0xd2135CfB216b74109775236E36d4b433F1DF507B' Returns[](https://viem.sh/docs/ens/actions/getEnsAddress#returns) ------------------------------------------------------------------ `[Address](https://viem.sh/docs/glossary/types#address) ` The address that resolves to provided ENS name. Returns `null` if ENS name does not resolve to address. Parameters[](https://viem.sh/docs/ens/actions/getEnsAddress#parameters) ------------------------------------------------------------------------ ### name[](https://viem.sh/docs/ens/actions/getEnsAddress#name) * **Type:** `string` Name to get the address for. const ensAddress = await publicClient.getEnsAddress({ name: normalize('wevm.eth'), }) ### blockNumber (optional)[](https://viem.sh/docs/ens/actions/getEnsAddress#blocknumber-optional) * **Type:** `number` The block number to perform the read against. const ensAddress = await publicClient.getEnsAddress({ name: normalize('wevm.eth'), blockNumber: 15121123n, }) ### blockTag (optional)[](https://viem.sh/docs/ens/actions/getEnsAddress#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` The block tag to perform the read against. const ensAddress = await publicClient.getEnsAddress({ name: normalize('wevm.eth'), blockTag: 'safe', }) ### coinType (optional)[](https://viem.sh/docs/ens/actions/getEnsAddress#cointype-optional) * **Type:** `number` The [ENSIP-9](https://docs.ens.domains/ens-improvement-proposals/ensip-9-multichain-address-resolution) coin type (chain) to fetch the address for import { base } from 'viem/chains' const ensAddress = await publicClient.getEnsAddress({ name: normalize('wevm.eth'), coinType: toCoinType(base.id), }) ### gatewayUrls (optional)[](https://viem.sh/docs/ens/actions/getEnsAddress#gatewayurls-optional) * **Type:** `string[]` A set of Universal Resolver gateways, used for resolving CCIP-Read requests made through the ENS Universal Resolver Contract. const ensAddress = await publicClient.getEnsAddress({ name: normalize('wevm.eth'), gatewayUrls: ["https://ccip.ens.xyz"], }) ### strict (optional)[](https://viem.sh/docs/ens/actions/getEnsAddress#strict-optional) * **Type:** `boolean` * **Default:** `false` A boolean value that when set to true will strictly propagate all ENS Universal Resolver Contract errors. const ensAddress = await publicClient.getEnsAddress({ name: normalize('wevm.eth'), strict: true, }) ### universalResolverAddress (optional)[](https://viem.sh/docs/ens/actions/getEnsAddress#universalresolveraddress-optional) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` * **Default:** `client.chain.contracts.ensUniversalResolver.address` Address of ENS Universal Resolver Contract. const ensAddress = await publicClient.getEnsAddress({ name: normalize('wevm.eth'), universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', }) Live Example[](https://viem.sh/docs/ens/actions/getEnsAddress#live-example) ---------------------------------------------------------------------------- Check out the usage of `getEnsAddress` in the live [ENS Examples](https://stackblitz.com/github/wevm/viem/tree/main/examples/ens) below. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/ens/actions/getEnsAddress.md) Copy page for AI Ask AI... ⌘ I --- # getPermissions · Viem [Skip to content](https://viem.sh/docs/actions/wallet/getPermissions#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getPermissions ============== Gets the wallets current permissions. Usage[](https://viem.sh/docs/actions/wallet/getPermissions#usage) ------------------------------------------------------------------ example.tsclient.ts import { walletClient } from './client' const permissions = await walletClient.getPermissions() Returns[](https://viem.sh/docs/actions/wallet/getPermissions#returns) ---------------------------------------------------------------------- `[WalletPermission[]](https://viem.sh/docs/glossary/types#walletpermission) ` The wallet permissions. JSON-RPC Methods[](https://viem.sh/docs/actions/wallet/getPermissions#json-rpc-methods) ---------------------------------------------------------------------------------------- `[wallet_getPermissions](https://eips.ethereum.org/EIPS/eip-2255) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/getPermissions.md) Copy page for AI Ask AI... ⌘ I --- # Build your own Client · Viem [Skip to content](https://viem.sh/docs/clients/custom#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Build your own Client ===================== You can build your own viem Client by using the `createClient` function and optionally extending (`.extend`) it – this is how viem's internal Clients ([Public](https://viem.sh/docs/clients/public) , [Wallet](https://viem.sh/docs/clients/wallet) , and [Test](https://viem.sh/docs/clients/test) ) are built. Building your own Client is useful if you have specific requirements for how the Client should behave, and if you want to extend that Client with custom functionality (ie. create a [geth Debug](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug) Client). The `createClient` function sets up a base viem Client with a given [Transport](https://viem.sh/docs/clients/intro) configured with a [Chain](https://viem.sh/docs/chains/introduction) . After that, you can extend the Client with custom properties (that could be Actions or other configuration). Import[](https://viem.sh/docs/clients/custom#import) ----------------------------------------------------- import { createClient } from 'viem' Usage[](https://viem.sh/docs/clients/custom#usage) --------------------------------------------------- Initialize a Client with your desired [Chain](https://viem.sh/docs/chains/introduction) (e.g. `mainnet`) and [Transport](https://viem.sh/docs/clients/intro) (e.g. `http`). import { createClient, http } from 'viem' import { mainnet } from 'viem/chains' const client = createClient({ chain: mainnet, transport: http() }) Next, you can either [extend your Client with Actions or configuration](https://viem.sh/docs/clients/custom#extending-with-actions-or-configuration) , or you can use it as-is for the purpose of [maximizing tree-shaking in your app](https://viem.sh/docs/clients/custom#tree-shaking) . ### Extending with Actions or configuration[](https://viem.sh/docs/clients/custom#extending-with-actions-or-configuration) You can extend your Client with custom Actions or configuration by using the `.extend` function. Below is a naive implementation of implementing a [geth Debug](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug) Client with a `traceCall` Action that uses the `debug_traceCall` RPC method. import { createClient, http, formatTransactionRequest, type CallParameters } from 'viem' import { mainnet } from 'viem/chains' const debugClient = createClient({ chain: mainnet, transport: http(), }).extend(client => ({ // ... async traceCall(args: CallParameters) { return client.request({ method: 'debug_traceCall', params: [formatTransactionRequest(args), 'latest', {}] }) }, // ... })) const response = await debugClient.traceCall({ account: '0xdeadbeef29292929192939494959594933929292', to: '0xde929f939d939d393f939393f93939f393929023', gas: 69420n, data: '0xf00d4b5d00000000000000000000000001291230982139282304923482304912923823920000000000000000000000001293123098123928310239129839291010293810' }) // { failed: false, gas: 69420, returnValue: '...', structLogs: [] } For a more succinct implementation of using `.extend`, check out viem's [Public Client implementation](https://github.com/wagmi-dev/viem/blob/29c053f5069a5b44e3791972c221368a2c71a254/src/clients/createPublicClient.ts#L48-L68) extended with [Public Actions](https://github.com/wagmi-dev/viem/blob/29c053f5069a5b44e3791972c221368a2c71a254/src/clients/decorators/public.ts#L1377-L1425) . ### Tree-shaking[](https://viem.sh/docs/clients/custom#tree-shaking) You can use the Client as-is, with no decorated Actions, to maximize tree-shaking in your app. This is useful if you are pedantic about bundle size and want to only include the Actions you use. In the example below, instead of calling `getBlock` from the Public Client, we are importing the Action directly from `viem` and then injecting our Client as the first parameter to the Action. import { createClient, http } from 'viem' import { mainnet } from 'viem/chains' import { getBlock, sendTransaction } from 'viem/actions' const client = createClient({ chain: mainnet, transport: http() }) const blockNumber = await getBlock(client, { blockTag: 'latest' }) const hash = await sendTransaction(client, { ... }) Parameters[](https://viem.sh/docs/clients/custom#parameters) ------------------------------------------------------------- ### transport[](https://viem.sh/docs/clients/custom#transport) * **Type:** [Transport](https://viem.sh/docs/glossary/types#transport) The [Transport](https://viem.sh/docs/clients/intro) of the Public Client. const client = createClient({ chain: mainnet, transport: http(), }) ### account (optional)[](https://viem.sh/docs/clients/custom#account-optional) * **Type:** `Account | Address` The Account to use for the Client. This will be used for Actions that require an `account` as an argument. Accepts a [JSON-RPC Account](https://viem.sh/docs/accounts/jsonRpc) or [Local Account (Private Key, etc)](https://viem.sh/docs/accounts/local/privateKeyToAccount) . import { privateKeyToAccount } from 'viem/accounts' const client = createClient({ account: privateKeyToAccount('0x...'), chain: mainnet, transport: http(), }) ### chain (optional)[](https://viem.sh/docs/clients/custom#chain-optional) * **Type:** [Chain](https://viem.sh/docs/glossary/types#chain) The [Chain](https://viem.sh/docs/chains/introduction) of the Public Client. const client = createClient({ chain: mainnet, transport: http(), }) ### batch (optional)[](https://viem.sh/docs/clients/custom#batch-optional) Flags for batch settings. ### batch.multicall (optional)[](https://viem.sh/docs/clients/custom#batchmulticall-optional) * **Type:** `boolean | MulticallBatchOptions` * **Default:** `false` Toggle to enable `eth_call` multicall aggregation. const client = createClient({ batch: { multicall: true, }, chain: mainnet, transport: http(), }) ### batch.multicall.batchSize (optional)[](https://viem.sh/docs/clients/custom#batchmulticallbatchsize-optional) * **Type:** `number` * **Default:** `1_024` The maximum size (in bytes) for each multicall (`aggregate3`) calldata chunk. > Note: Some RPC Providers limit the amount of calldata that can be sent in a single request. It is best to check with your RPC Provider to see if there are any calldata size limits to `eth_call` requests. const client = createClient({ batch: { multicall: { batchSize: 512, }, }, chain: mainnet, transport: http(), }) ### batch.multicall.wait (optional)[](https://viem.sh/docs/clients/custom#batchmulticallwait-optional) * **Type:** `number` * **Default:** `0` ([zero delay](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop#zero_delays) ) The maximum number of milliseconds to wait before sending a batch. const client = createClient({ batch: { multicall: { wait: 16, }, }, chain: mainnet, transport: http(), }) ### key (optional)[](https://viem.sh/docs/clients/custom#key-optional) * **Type:** `string` * **Default:** `"public"` A key for the Client. const client = createClient({ chain: mainnet, key: 'public', transport: http(), }) ### name (optional)[](https://viem.sh/docs/clients/custom#name-optional) * **Type:** `string` * **Default:** `"Public Client"` A name for the Client. const client = createClient({ chain: mainnet, name: 'Public Client', transport: http(), }) ### pollingInterval (optional)[](https://viem.sh/docs/clients/custom#pollinginterval-optional) * **Type:** `number` * **Default:** `4_000` Frequency (in ms) for polling enabled Actions. const client = createClient({ chain: mainnet, pollingInterval: 10_000, transport: http(), }) ### rpcSchema (optional)[](https://viem.sh/docs/clients/custom#rpcschema-optional) * **Type:** `RpcSchema` * **Default:** `WalletRpcSchema` Typed JSON-RPC schema for the client. import { createClient, http } from 'viem' import { mainnet } from 'viem/chains' // @noErrors // ---cut--- import { rpcSchema } from 'viem' type CustomRpcSchema = [{ \ Method: 'eth_wagmi', \ Parameters: [string] \ ReturnType: string\ }] const client = createClient({ chain: mainnet, rpcSchema: rpcSchema(), transport: http() }) const result = await client.request({ method: 'eth_wa // [!code focus] // ^| params: ['hello'], }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/clients/custom.md) Copy page for AI Ask AI... ⌘ I --- # toBase58 · Viem [Skip to content](https://viem.sh/docs/utilities/toBase58#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K toBase58 ======== Coming soon. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/toBase58.md) Copy page for AI Ask AI... ⌘ I --- # Errors · Viem [Skip to content](https://viem.sh/docs/glossary/errors#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Errors ====== Glossary of Errors in viem. All errors in viem extend the `[BaseError](https://github.com/wevm/viem/blob/main/src/errors/base.ts) `. ABI[](https://viem.sh/docs/glossary/errors#abi) ------------------------------------------------ ### `AbiConstructorNotFoundError`[](https://viem.sh/docs/glossary/errors#abiconstructornotfounderror) ### `AbiConstructorParamsNotFoundError`[](https://viem.sh/docs/glossary/errors#abiconstructorparamsnotfounderror) ### `AbiDecodingDataSizeInvalidError`[](https://viem.sh/docs/glossary/errors#abidecodingdatasizeinvaliderror) ### `AbiDecodingDataSizeTooSmallError`[](https://viem.sh/docs/glossary/errors#abidecodingdatasizetoosmallerror) ### `AbiDecodingZeroDataError`[](https://viem.sh/docs/glossary/errors#abidecodingzerodataerror) ### `AbiEncodingArrayLengthMismatchError`[](https://viem.sh/docs/glossary/errors#abiencodingarraylengthmismatcherror) ### `AbiEncodingBytesSizeMismatchError`[](https://viem.sh/docs/glossary/errors#abiencodingbytessizemismatcherror) ### `AbiEncodingLengthMismatchError`[](https://viem.sh/docs/glossary/errors#abiencodinglengthmismatcherror) ### `AbiErrorInputsNotFoundError`[](https://viem.sh/docs/glossary/errors#abierrorinputsnotfounderror) ### `AbiErrorNotFoundError`[](https://viem.sh/docs/glossary/errors#abierrornotfounderror) ### `AbiErrorSignatureNotFoundError`[](https://viem.sh/docs/glossary/errors#abierrorsignaturenotfounderror) ### `AbiEventNotFoundError`[](https://viem.sh/docs/glossary/errors#abieventnotfounderror) ### `AbiEventSignatureEmptyTopicsError`[](https://viem.sh/docs/glossary/errors#abieventsignatureemptytopicserror) ### `AbiEventSignatureNotFoundError`[](https://viem.sh/docs/glossary/errors#abieventsignaturenotfounderror) ### `AbiFunctionNotFoundError`[](https://viem.sh/docs/glossary/errors#abifunctionnotfounderror) ### `AbiFunctionOutputsNotFoundError`[](https://viem.sh/docs/glossary/errors#abifunctionoutputsnotfounderror) ### `AbiFunctionSignatureNotFoundError`[](https://viem.sh/docs/glossary/errors#abifunctionsignaturenotfounderror) ### `BytesSizeMismatchError`[](https://viem.sh/docs/glossary/errors#bytessizemismatcherror) ### `DecodeLogTopicsMismatch`[](https://viem.sh/docs/glossary/errors#decodelogtopicsmismatch) ### `InvalidAbiDecodingTypeError`[](https://viem.sh/docs/glossary/errors#invalidabidecodingtypeerror) ### `InvalidAbiEncodingTypeError`[](https://viem.sh/docs/glossary/errors#invalidabiencodingtypeerror) ### `InvalidArrayError`[](https://viem.sh/docs/glossary/errors#invalidarrayerror) ### `InvalidDefinitionTypeError`[](https://viem.sh/docs/glossary/errors#invaliddefinitiontypeerror) ### `UnsupportedPackedAbiType`[](https://viem.sh/docs/glossary/errors#unsupportedpackedabitype) Account[](https://viem.sh/docs/glossary/errors#account) -------------------------------------------------------- ### `AccountNotFoundError`[](https://viem.sh/docs/glossary/errors#accountnotfounderror) When no account is provided to an action that requires an account. Address[](https://viem.sh/docs/glossary/errors#address) -------------------------------------------------------- ### `InvalidAddressError`[](https://viem.sh/docs/glossary/errors#invalidaddresserror) When address is invalid. Block[](https://viem.sh/docs/glossary/errors#block) ---------------------------------------------------- ### `BlockNotFoundError`[](https://viem.sh/docs/glossary/errors#blocknotfounderror) Chain[](https://viem.sh/docs/glossary/errors#chain) ---------------------------------------------------- ### `ChainDoesNotSupportContract`[](https://viem.sh/docs/glossary/errors#chaindoesnotsupportcontract) ### `ChainMismatchError`[](https://viem.sh/docs/glossary/errors#chainmismatcherror) ### `ChainNotFoundError`[](https://viem.sh/docs/glossary/errors#chainnotfounderror) ### `ClientChainNotConfiguredError`[](https://viem.sh/docs/glossary/errors#clientchainnotconfigurederror) ### `InvalidChainIdError`[](https://viem.sh/docs/glossary/errors#invalidchainiderror) Contract[](https://viem.sh/docs/glossary/errors#contract) ---------------------------------------------------------- ### `CallExecutionError`[](https://viem.sh/docs/glossary/errors#callexecutionerror) ### `ContractFunctionExecutionError`[](https://viem.sh/docs/glossary/errors#contractfunctionexecutionerror) ### `ContractFunctionRevertedError`[](https://viem.sh/docs/glossary/errors#contractfunctionrevertederror) ### `ContractFunctionZeroDataError`[](https://viem.sh/docs/glossary/errors#contractfunctionzerodataerror) ### `RawContractError`[](https://viem.sh/docs/glossary/errors#rawcontracterror) Data[](https://viem.sh/docs/glossary/errors#data) -------------------------------------------------- ### `SizeExceedsPaddingSizeError`[](https://viem.sh/docs/glossary/errors#sizeexceedspaddingsizeerror) Encoding[](https://viem.sh/docs/glossary/errors#encoding) ---------------------------------------------------------- ### `DataLengthTooLongError`[](https://viem.sh/docs/glossary/errors#datalengthtoolongerror) ### `DataLengthTooShortError`[](https://viem.sh/docs/glossary/errors#datalengthtooshorterror) ### `IntegerOutOfRangeError`[](https://viem.sh/docs/glossary/errors#integeroutofrangeerror) ### `InvalidBytesBooleanError`[](https://viem.sh/docs/glossary/errors#invalidbytesbooleanerror) ### `InvalidHexBooleanError`[](https://viem.sh/docs/glossary/errors#invalidhexbooleanerror) ### `InvalidHexValueError`[](https://viem.sh/docs/glossary/errors#invalidhexvalueerror) ### `OffsetOutOfBoundsError`[](https://viem.sh/docs/glossary/errors#offsetoutofboundserror) ### `SizeOverflowError`[](https://viem.sh/docs/glossary/errors#sizeoverflowerror) ENS[](https://viem.sh/docs/glossary/errors#ens) ------------------------------------------------ ### `EnsAvatarInvalidMetadataError`[](https://viem.sh/docs/glossary/errors#ensavatarinvalidmetadataerror) ### `EnsAvatarInvalidNftUriError`[](https://viem.sh/docs/glossary/errors#ensavatarinvalidnfturierror) ### `EnsAvatarUnsupportedNamespaceError`[](https://viem.sh/docs/glossary/errors#ensavatarunsupportednamespaceerror) ### `EnsAvatarUriResolutionError`[](https://viem.sh/docs/glossary/errors#ensavataruriresolutionerror) Estimate Gas[](https://viem.sh/docs/glossary/errors#estimate-gas) ------------------------------------------------------------------ ### `EstimateGasExecutionError`[](https://viem.sh/docs/glossary/errors#estimategasexecutionerror) Log[](https://viem.sh/docs/glossary/errors#log) ------------------------------------------------ ### `FilterTypeNotSupportedError`[](https://viem.sh/docs/glossary/errors#filtertypenotsupportederror) Node[](https://viem.sh/docs/glossary/errors#node) -------------------------------------------------- ### `ExecutionRevertedError`[](https://viem.sh/docs/glossary/errors#executionrevertederror) ### `FeeCapTooHighError`[](https://viem.sh/docs/glossary/errors#feecaptoohigherror) ### `FeeCapTooLowError`[](https://viem.sh/docs/glossary/errors#feecaptoolowerror) ### `InsufficientFundsError`[](https://viem.sh/docs/glossary/errors#insufficientfundserror) ### `IntrinsicGasTooHighError`[](https://viem.sh/docs/glossary/errors#intrinsicgastoohigherror) ### `IntrinsicGasTooLowError`[](https://viem.sh/docs/glossary/errors#intrinsicgastoolowerror) ### `NonceMaxValueError`[](https://viem.sh/docs/glossary/errors#noncemaxvalueerror) ### `NonceTooHighError`[](https://viem.sh/docs/glossary/errors#noncetoohigherror) ### `NonceTooLowError`[](https://viem.sh/docs/glossary/errors#noncetoolowerror) ### `TipAboveFeeCapError`[](https://viem.sh/docs/glossary/errors#tipabovefeecaperror) ### `TransactionTypeNotSupportedError`[](https://viem.sh/docs/glossary/errors#transactiontypenotsupportederror) ### `UnknownNodeError`[](https://viem.sh/docs/glossary/errors#unknownnodeerror) Request[](https://viem.sh/docs/glossary/errors#request) -------------------------------------------------------- ### `HttpRequestError`[](https://viem.sh/docs/glossary/errors#httprequesterror) ### `RpcRequestError`[](https://viem.sh/docs/glossary/errors#rpcrequesterror) ### `TimeoutError`[](https://viem.sh/docs/glossary/errors#timeouterror) ### `WebSocketRequestError`[](https://viem.sh/docs/glossary/errors#websocketrequesterror) RPC[](https://viem.sh/docs/glossary/errors#rpc) ------------------------------------------------ ### `ChainDisconnectedError`[](https://viem.sh/docs/glossary/errors#chaindisconnectederror) ### `InternalRpcError`[](https://viem.sh/docs/glossary/errors#internalrpcerror) ### `InvalidInputRpcError`[](https://viem.sh/docs/glossary/errors#invalidinputrpcerror) ### `InvalidParamsRpcError`[](https://viem.sh/docs/glossary/errors#invalidparamsrpcerror) ### `InvalidRequestRpcError`[](https://viem.sh/docs/glossary/errors#invalidrequestrpcerror) ### `JsonRpcVersionUnsupportedError`[](https://viem.sh/docs/glossary/errors#jsonrpcversionunsupportederror) ### `LimitExceededRpcError`[](https://viem.sh/docs/glossary/errors#limitexceededrpcerror) ### `MethodNotFoundRpcError`[](https://viem.sh/docs/glossary/errors#methodnotfoundrpcerror) ### `MethodNotSupportedRpcError`[](https://viem.sh/docs/glossary/errors#methodnotsupportedrpcerror) ### `ParseRpcError`[](https://viem.sh/docs/glossary/errors#parserpcerror) ### `ProviderDisconnectedError`[](https://viem.sh/docs/glossary/errors#providerdisconnectederror) ### `ProviderRpcError`[](https://viem.sh/docs/glossary/errors#providerrpcerror) ### `ResourceNotFoundRpcError`[](https://viem.sh/docs/glossary/errors#resourcenotfoundrpcerror) ### `ResourceUnavailableRpcError`[](https://viem.sh/docs/glossary/errors#resourceunavailablerpcerror) ### `RpcError`[](https://viem.sh/docs/glossary/errors#rpcerror) ### `SwitchChainError`[](https://viem.sh/docs/glossary/errors#switchchainerror) ### `TransactionRejectedRpcError`[](https://viem.sh/docs/glossary/errors#transactionrejectedrpcerror) ### `UnauthorizedProviderError`[](https://viem.sh/docs/glossary/errors#unauthorizedprovidererror) ### `UnknownRpcError`[](https://viem.sh/docs/glossary/errors#unknownrpcerror) ### `UnsupportedProviderMethodError`[](https://viem.sh/docs/glossary/errors#unsupportedprovidermethoderror) ### `UserRejectedRequestError`[](https://viem.sh/docs/glossary/errors#userrejectedrequesterror) SIWE[](https://viem.sh/docs/glossary/errors#siwe) -------------------------------------------------- ### CreateSiweMessageErrorType[](https://viem.sh/docs/glossary/errors#createsiwemessageerrortype) ### SiweInvalidMessageFieldErrorType[](https://viem.sh/docs/glossary/errors#siweinvalidmessagefielderrortype) ### VerifySiweMessageErrorType[](https://viem.sh/docs/glossary/errors#verifysiwemessageerrortype) Transaction[](https://viem.sh/docs/glossary/errors#transaction) ---------------------------------------------------------------- ### `FeeConflictError`[](https://viem.sh/docs/glossary/errors#feeconflicterror) ### `InvalidLegacyVError`[](https://viem.sh/docs/glossary/errors#invalidlegacyverror) ### `InvalidSerializableTransactionError`[](https://viem.sh/docs/glossary/errors#invalidserializabletransactionerror) ### `InvalidSerializedTransactionError`[](https://viem.sh/docs/glossary/errors#invalidserializedtransactionerror) ### `InvalidSerializedTransactionTypeError`[](https://viem.sh/docs/glossary/errors#invalidserializedtransactiontypeerror) ### `InvalidStorageKeySizeError`[](https://viem.sh/docs/glossary/errors#invalidstoragekeysizeerror) ### `TransactionExecutionError`[](https://viem.sh/docs/glossary/errors#transactionexecutionerror) ### `TransactionNotFoundError`[](https://viem.sh/docs/glossary/errors#transactionnotfounderror) ### `TransactionReceiptNotFoundError`[](https://viem.sh/docs/glossary/errors#transactionreceiptnotfounderror) ### `WaitForTransactionReceiptTimeoutError`[](https://viem.sh/docs/glossary/errors#waitfortransactionreceipttimeouterror) Transport[](https://viem.sh/docs/glossary/errors#transport) ------------------------------------------------------------ ### `UrlRequiredError`[](https://viem.sh/docs/glossary/errors#urlrequirederror) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/glossary/errors.md) Copy page for AI Ask AI... ⌘ I --- # verifyAuthorization · Viem [Skip to content](https://viem.sh/docs/eip7702/verifyAuthorization#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K verifyAuthorization =================== Verifies that an Authorization object was signed by the provided address. Import[](https://viem.sh/docs/eip7702/verifyAuthorization#import) ------------------------------------------------------------------ import { verifyAuthorization } from 'viem/utils' Usage[](https://viem.sh/docs/eip7702/verifyAuthorization#usage) ---------------------------------------------------------------- example.tsclient.ts import { privateKeyToAccount } from 'viem/accounts' import { verifyAuthorization } from 'viem/utils' import { walletClient } from './client' const eoa = privateKeyToAccount('0x...') const authorization = await walletClient.signAuthorization({ account: eoa, authorization: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2' }) const valid = await verifyAuthorization({ address: eoa.address, authorization, }) Returns[](https://viem.sh/docs/eip7702/verifyAuthorization#returns) -------------------------------------------------------------------- `boolean` Whether the signature is valid for the provided Authorization object. Parameters[](https://viem.sh/docs/eip7702/verifyAuthorization#parameters) -------------------------------------------------------------------------- ### address[](https://viem.sh/docs/eip7702/verifyAuthorization#address) * **Type:** `Address` The address that signed the Authorization object. const valid = await verifyAuthorization({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', authorization, }) ### authorization[](https://viem.sh/docs/eip7702/verifyAuthorization#authorization) * **Type:** `Authorization | SignedAuthorization` The Authorization object to be verified. const authorization = await walletClient.signAuthorization({ authorization: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2' }) const valid = await verifyAuthorization({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', authorization, }) ### signature[](https://viem.sh/docs/eip7702/verifyAuthorization#signature) * **Type:** `Hex | ByteArray | Signature | SignedAuthorization` The signature that was generated by signing the Authorization object with the address's private key. const signature = await walletClient.signAuthorization({ authorization: { address: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', chainId: 1, nonce: 0, } }) const valid = await verifyAuthorization({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', authorization: { address: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', chainId: 1, nonce: 0, }, signature, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/eip7702/verifyAuthorization.md) Copy page for AI Ask AI... ⌘ I --- # decodeErrorResult · Viem [Skip to content](https://viem.sh/docs/contract/decodeErrorResult#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K decodeErrorResult ================= Decodes reverted error from a contract function call. Install[](https://viem.sh/docs/contract/decodeErrorResult#install) ------------------------------------------------------------------- import { decodeErrorResult } from 'viem' Usage[](https://viem.sh/docs/contract/decodeErrorResult#usage) --------------------------------------------------------------- example.tsabi.ts import { decodeErrorResult } from 'viem' import { wagmiAbi } from './abi.ts' const value = decodeErrorResult({ abi: wagmiAbi, data: '0xb758934b000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b68656c6c6f20776f726c64000000000000000000000000000000000000000000' }) // { errorName: 'InvalidTokenError', args: ['sold out'] } Return Value[](https://viem.sh/docs/contract/decodeErrorResult#return-value) ----------------------------------------------------------------------------- The decoded error. Parameters[](https://viem.sh/docs/contract/decodeErrorResult#parameters) ------------------------------------------------------------------------- ### abi[](https://viem.sh/docs/contract/decodeErrorResult#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const value = decodeErrorResult({ abi: wagmiAbi, data: '0xb758934b000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b68656c6c6f20776f726c64000000000000000000000000000000000000000000' }) ### data[](https://viem.sh/docs/contract/decodeErrorResult#data) * **Type:** `[Hex](https://viem.sh/docs/glossary/types#hex) ` The calldata. const value = decodeErrorResult({ abi: wagmiAbi, data: '0xb758934b000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b68656c6c6f20776f726c64000000000000000000000000000000000000000000' }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/decodeErrorResult.md) Copy page for AI Ask AI... ⌘ I --- # watchBlockNumber · Viem [Skip to content](https://viem.sh/docs/actions/public/watchBlockNumber#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K watchBlockNumber ================ Watches and returns incoming block numbers. Usage[](https://viem.sh/docs/actions/public/watchBlockNumber#usage) -------------------------------------------------------------------- Pass through your Public Client, along with a listener. example.tsclient.ts import { publicClient } from './client' const unwatch = publicClient.watchBlockNumber( { onBlockNumber: blockNumber => console.log(blockNumber) } ) > 69422n Listener[](https://viem.sh/docs/actions/public/watchBlockNumber#listener) -------------------------------------------------------------------------- `(blockNumber: bigint) => void` The block number. Returns[](https://viem.sh/docs/actions/public/watchBlockNumber#returns) ------------------------------------------------------------------------ `UnwatchFn` A function that can be invoked to stop watching for new block numbers. Parameters[](https://viem.sh/docs/actions/public/watchBlockNumber#parameters) ------------------------------------------------------------------------------ ### emitMissed (optional)[](https://viem.sh/docs/actions/public/watchBlockNumber#emitmissed-optional) * **Type:** `boolean` * **Default:** `false` Whether or not to emit missed block numbers to the callback. Missed block numbers may occur in instances where internet connection is lost, or the block time is lesser than the [polling interval](https://viem.sh/docs/clients/public#pollinginterval-optional) of the client. const unwatch = publicClient.watchBlockNumber( { emitMissed: true, onBlockNumber: blockNumber => console.log(blockNumber), } ) ### emitOnBegin (optional)[](https://viem.sh/docs/actions/public/watchBlockNumber#emitonbegin-optional) * **Type:** `boolean` * **Default:** `false` Whether or not to emit the latest block number to the callback when the subscription opens. const unwatch = publicClient.watchBlockNumber( { emitOnBegin: true, onBlockNumber: blockNumber => console.log(blockNumber), } ) ### poll (optional)[](https://viem.sh/docs/actions/public/watchBlockNumber#poll-optional) * **Type:** `boolean` * **Default:** `false` for WebSocket Transports, `true` for non-WebSocket Transports Whether or not to use a polling mechanism to check for new block numbers instead of a WebSocket subscription. This option is only configurable for Clients with a [WebSocket Transport](https://viem.sh/docs/clients/transports/websocket) . import { createPublicClient, webSocket } from 'viem' import { mainnet } from 'viem/chains' const publicClient = createPublicClient({ chain: mainnet, transport: webSocket() }) const unwatch = publicClient.watchBlockNumber( { onBlockNumber: blockNumber => console.log(blockNumber), poll: true, } ) ### pollingInterval (optional)[](https://viem.sh/docs/actions/public/watchBlockNumber#pollinginterval-optional) * **Type:** `number` Polling frequency (in ms). Defaults to Client's `pollingInterval` config. const unwatch = publicClient.watchBlockNumber( { onBlockNumber: blockNumber => console.log(blockNumber), pollingInterval: 12_000, } ) Example[](https://viem.sh/docs/actions/public/watchBlockNumber#example) ------------------------------------------------------------------------ Check out the usage of `watchBlockNumber` in the live [Watch Block Numbers Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks) below. JSON-RPC Methods[](https://viem.sh/docs/actions/public/watchBlockNumber#json-rpc-methods) ------------------------------------------------------------------------------------------ * When `poll: true`, calls `[eth_blockNumber](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) ` on a polling interval. * When `poll: false` & WebSocket Transport, uses a WebSocket subscription via `[eth_subscribe](https://docs.alchemy.com/reference/eth-subscribe-polygon) ` and the `"newHeads"` event. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/watchBlockNumber.md) Copy page for AI Ask AI... ⌘ I --- # getCode · Viem [Skip to content](https://viem.sh/docs/contract/getCode#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getCode ======= Retrieves the bytecode at an address. Usage[](https://viem.sh/docs/contract/getCode#usage) ----------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const bytecode = await publicClient.getCode({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) Return Value[](https://viem.sh/docs/contract/getCode#return-value) ------------------------------------------------------------------- `[Hex](https://viem.sh/docs/glossary/types#hex) ` | `undefined` The contract's bytecode, or `undefined` if no bytecode is found at the address. Parameters[](https://viem.sh/docs/contract/getCode#parameters) --------------------------------------------------------------- ### address[](https://viem.sh/docs/contract/getCode#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The contract address. const bytecode = await publicClient.getCode({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) ### blockNumber (optional)[](https://viem.sh/docs/contract/getCode#blocknumber-optional) * **Type:** `number` The block number to perform the bytecode read against. const bytecode = await publicClient.getCode({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', blockNumber: 15121123n, }) ### blockTag (optional)[](https://viem.sh/docs/contract/getCode#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` The block tag to perform the bytecode read against. const bytecode = await publicClient.getCode({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', blockTag: 'safe', }) JSON-RPC Method[](https://viem.sh/docs/contract/getCode#json-rpc-method) ------------------------------------------------------------------------- `[eth_getCode](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getcode) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/getCode.md) Copy page for AI Ask AI... ⌘ I --- # waitForCallsStatus · Viem [Skip to content](https://viem.sh/docs/actions/wallet/waitForCallsStatus#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K waitForCallsStatus ================== Waits for a call batch to be confirmed & included on a [Block](https://viem.sh/docs/glossary/terms#block) before returning the status & receipts. Usage[](https://viem.sh/docs/actions/wallet/waitForCallsStatus#usage) ---------------------------------------------------------------------- example.tsconfig.ts import { parseEther } from 'viem' import { account, walletClient } from './config' const { id } = await walletClient.sendCalls({ account, calls: [{\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ }], }) const result = await walletClient.waitForCallsStatus({ id, }) } Returns[](https://viem.sh/docs/actions/wallet/waitForCallsStatus#returns) -------------------------------------------------------------------------- `WaitForCallsStatusReturnType` Status and receipts of the calls. Parameters[](https://viem.sh/docs/actions/wallet/waitForCallsStatus#parameters) -------------------------------------------------------------------------------- ### id[](https://viem.sh/docs/actions/wallet/waitForCallsStatus#id) * **Type:** `string` Identifier of the call batch. const result = await walletClient.waitForCallsStatus({ id: '0xdeadbeef', }) ### pollingInterval[](https://viem.sh/docs/actions/wallet/waitForCallsStatus#pollinginterval) * **Type:** `number` * **Default:** `client.pollingInterval` Polling interval in milliseconds. const result = await walletClient.waitForCallsStatus({ id: '0xdeadbeef', pollingInterval: 1_000, }) ### retryCount[](https://viem.sh/docs/actions/wallet/waitForCallsStatus#retrycount) * **Type:** `number` * **Default:** `4` Number of times to retry if the call bundle fails. const result = await walletClient.waitForCallsStatus({ id: '0xdeadbeef', retryCount: 10, }) ### retryDelay[](https://viem.sh/docs/actions/wallet/waitForCallsStatus#retrydelay) * **Type:** `number` * **Default:** `({ count }) => ~~(1 << count) * 200` Time to wait (in ms) between retries. const result = await walletClient.waitForCallsStatus({ id: '0xdeadbeef', retryDelay: 1_000, }) ### status[](https://viem.sh/docs/actions/wallet/waitForCallsStatus#status) * **Type:** `(parameters: { statusCode: number, status: string | undefined }) => boolean` * **Default:** `(parameters) => parameters.statusCode >= 200` Status to wait for. Defaults to non-pending status codes (`>=200`). const result = await walletClient.waitForCallsStatus({ id: '0xdeadbeef', status: ({ status }) => status === 'success', }) ### throwOnFailure[](https://viem.sh/docs/actions/wallet/waitForCallsStatus#throwonfailure) * **Type:** `boolean` * **Default:** `false` Whether to throw an error if the call bundle fails. const result = await walletClient.waitForCallsStatus({ id: '0xdeadbeef', throwOnFailure: true, }) ### timeout[](https://viem.sh/docs/actions/wallet/waitForCallsStatus#timeout) * **Type:** `number` * **Default:** `60_000` Timeout in milliseconds before `waitForCallsStatus` stops polling. const result = await walletClient.waitForCallsStatus({ id: '0xdeadbeef', timeout: 10_000, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/waitForCallsStatus.mdx) Copy page for AI Ask AI... ⌘ I --- # createEventFilter · Viem [Skip to content](https://viem.sh/docs/actions/public/createEventFilter#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K createEventFilter ================= An Action for creating a new Event Filter. Creates a Filter to listen for new events that can be used with `[getFilterChanges](https://viem.sh/docs/actions/public/getFilterChanges) `. Usage[](https://viem.sh/docs/actions/public/createEventFilter#usage) --------------------------------------------------------------------- By default, an Event Filter with no arguments will query for/listen to all events. example.tsclient.ts import { publicClient } from './client' const filter = await publicClient.createEventFilter() { id: "0x345a6572337856574a76364e457a4366", type: 'event' } Scoping[](https://viem.sh/docs/actions/public/createEventFilter#scoping) ------------------------------------------------------------------------- You can also scope a Filter to a set of given attributes (listed below). ### Address[](https://viem.sh/docs/actions/public/createEventFilter#address) A Filter can be scoped to an **address**: example.tsclient.ts import { publicClient } from './client' const filter = await publicClient.createEventFilter({ address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2' }) ### Event[](https://viem.sh/docs/actions/public/createEventFilter#event) A Filter can be scoped to an **event**. The `event` argument takes in an event in ABI format – we have a [`parseAbiItem` utility](https://viem.sh/docs/abi/parseAbiItem) that you can use to convert from a human-readable event signature → ABI. example.tsclient.ts import { parseAbiItem } from 'viem' import { publicClient } from './client' const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), }) By default, `event` accepts the `[AbiEvent](https://viem.sh/docs/glossary/types#abievent) ` type: example.tsclient.ts import { publicClient } from './client' const filter = await publicClient.createEventFilter(publicClient, { address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: { name: 'Transfer', inputs: [\ { type: 'address', indexed: true, name: 'from' },\ { type: 'address', indexed: true, name: 'to' },\ { type: 'uint256', indexed: false, name: 'value' }\ ] } }) ### Arguments[](https://viem.sh/docs/actions/public/createEventFilter#arguments) A Filter can be scoped to given **_indexed_ arguments**: import { parseAbiItem } from 'viem' const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' } }) Only indexed arguments in `event` are candidates for `args`. A Filter Argument can also be an array to indicate that other values can exist in the position: import { parseAbiItem } from 'viem' const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), args: { // '0xd8da...' OR '0xa5cc...' OR '0xa152...' from: [\ '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', \ '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac',\ '0xa152f8bb749c55e9943a3a0a3111d18ee2b3f94e',\ ], } }) ### Block Range[](https://viem.sh/docs/actions/public/createEventFilter#block-range) A Filter can be scoped to a **block range**: import { parseAbiItem } from 'viem' const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), fromBlock: 16330000n, toBlock: 16330050n }) ### Multiple Events[](https://viem.sh/docs/actions/public/createEventFilter#multiple-events) A Filter can be scoped to **multiple events**: import { parseAbi } from 'viem' const filter = await publicClient.createEventFilter({ events: parseAbi([ \ 'event Approval(address indexed owner, address indexed sender, uint256 value)',\ 'event Transfer(address indexed from, address indexed to, uint256 value)',\ ]), }) Note: A Filter scoped to multiple events cannot be also scoped with [indexed arguments](https://viem.sh/docs/actions/public/createEventFilter#arguments) (`args`). ### Strict Mode[](https://viem.sh/docs/actions/public/createEventFilter#strict-mode) By default, `createEventFilter` will include logs that [do not conform](https://viem.sh/docs/glossary/terms#non-conforming-log) to the indexed & non-indexed arguments on the `event`. viem will not return a value for arguments that do not conform to the ABI, thus, some arguments on `args` may be undefined. import { parseAbiItem } from 'viem' const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), }) const logs = await publicClient.getFilterLogs({ filter }) logs[0].args You can turn on `strict` mode to only return logs that conform to the indexed & non-indexed arguments on the `event`, meaning that `args` will always be defined. The trade-off is that non-conforming logs will be filtered out. import { parseAbiItem } from 'viem' const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), strict: true }) const logs = await publicClient.getFilterLogs({ filter }) logs[0].args Returns[](https://viem.sh/docs/actions/public/createEventFilter#returns) ------------------------------------------------------------------------- `[Filter](https://viem.sh/docs/glossary/types#filter) ` Parameters[](https://viem.sh/docs/actions/public/createEventFilter#parameters) ------------------------------------------------------------------------------- ### address (optional)[](https://viem.sh/docs/actions/public/createEventFilter#address-optional) * **Type:** `Address | Address[]` The contract address or a list of addresses from which Logs should originate. const filter = await publicClient.createEventFilter({ address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2' }) ### event (optional)[](https://viem.sh/docs/actions/public/createEventFilter#event-optional) * **Type:** `[AbiEvent](https://viem.sh/docs/glossary/types#abievent) ` The event in ABI format. A [`parseAbiItem` utility](https://viem.sh/docs/abi/parseAbiItem) is exported from viem that converts from a human-readable event signature → ABI. import { parseAbiItem } from 'viem' const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), }) ### args (optional)[](https://viem.sh/docs/actions/public/createEventFilter#args-optional) * **Type:** Inferred. A list of _indexed_ event arguments. import { parseAbiItem } from 'viem' const filter = await publicClient.createEventFilter({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' } }) ### fromBlock (optional)[](https://viem.sh/docs/actions/public/createEventFilter#fromblock-optional) * **Type:** `bigint` Block to start querying/listening from. const filter = await publicClient.createEventFilter({ fromBlock: 69420n }) ### toBlock (optional)[](https://viem.sh/docs/actions/public/createEventFilter#toblock-optional) * **Type:** `bigint` Block to query/listen until. const filter = await publicClient.createEventFilter({ toBlock: 70120n }) JSON-RPC Methods[](https://viem.sh/docs/actions/public/createEventFilter#json-rpc-methods) ------------------------------------------------------------------------------------------- `[eth_newFilter](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/createEventFilter.md) Copy page for AI Ask AI... ⌘ I --- # prepareAuthorization · Viem [Skip to content](https://viem.sh/docs/eip7702/prepareAuthorization#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K prepareAuthorization ==================== Prepares an [EIP-7702 Authorization](https://eips.ethereum.org/EIPS/eip-7702) for signing. This Action will fill the required fields of the Authorization object if they are not provided (e.g. `nonce` and `chainId`). With the prepared Authorization object, you can use `[signAuthorization](https://viem.sh/docs/eip7702/signAuthorization) ` to sign over it. Usage[](https://viem.sh/docs/eip7702/prepareAuthorization#usage) ----------------------------------------------------------------- example.tsclient.ts import { walletClient } from './client' const authorization = await walletClient.prepareAuthorization({ contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) } const signedAuthorization = await walletClient.signAuthorization(authorization) ### Explicit Scoping[](https://viem.sh/docs/eip7702/prepareAuthorization#explicit-scoping) We can explicitly set a `nonce` and/or `chainId` by supplying them as parameters: example.tsclient.ts import { walletClient } from './client' const authorization = await walletClient.prepareAuthorization({ contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', chainId: 10, }) } const signedAuthorization = await walletClient.signAuthorization(authorization) Returns[](https://viem.sh/docs/eip7702/prepareAuthorization#returns) --------------------------------------------------------------------- `Authorization` A prepared & unsigned Authorization object. Parameters[](https://viem.sh/docs/eip7702/prepareAuthorization#parameters) --------------------------------------------------------------------------- ### account[](https://viem.sh/docs/eip7702/prepareAuthorization#account) * **Type:** `Account` Account to use to prepare the Authorization object. Accepts a [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . import { privateKeyToAccount } from 'viem/accounts' import { walletClient } from './client' const authorization = await walletClient.prepareAuthorization({ account: privateKeyToAccount('0x...'), contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2' }) ### chainId (optional)[](https://viem.sh/docs/eip7702/prepareAuthorization#chainid-optional) * **Type:** `Address` * **Default:** `client.chain.id` or Network chain ID The Chain ID to scope the Authorization to. If set to zero (`0`), then the Authorization will be valid on all chains. import { privateKeyToAccount } from 'viem/accounts' import { walletClient } from './client' const authorization = await walletClient.prepareAuthorization({ account: privateKeyToAccount('0x...'), contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', chainId: 1, }) ### contractAddress[](https://viem.sh/docs/eip7702/prepareAuthorization#contractaddress) * **Type:** `Address` The target Contract to designate onto the Account. import { privateKeyToAccount } from 'viem/accounts' import { walletClient } from './client' const authorization = await walletClient.prepareAuthorization({ account: privateKeyToAccount('0x...'), contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2' }) ### executor (optional)[](https://viem.sh/docs/eip7702/prepareAuthorization#executor-optional) * **Type:** `'self' | undefined` Whether the EIP-7702 Transaction will be executed by the Account that signed the Authorization. If not specified, it will be assumed that the EIP-7702 Transaction will be executed by another Account (ie. a relayer Account). import { privateKeyToAccount } from 'viem/accounts' import { walletClient } from './client' const authorization = await walletClient.prepareAuthorization({ account: privateKeyToAccount('0x...'), contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', executor: 'self', }) ### nonce (optional)[](https://viem.sh/docs/eip7702/prepareAuthorization#nonce-optional) * **Type:** `Address` * **Default:** Account's next available nonce. The nonce to scope the Authorization to. import { privateKeyToAccount } from 'viem/accounts' import { walletClient } from './client' const authorization = await walletClient.prepareAuthorization({ account: privateKeyToAccount('0x...'), contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', nonce: 69, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/eip7702/prepareAuthorization.md) Copy page for AI Ask AI... ⌘ I --- # signMessage · Viem [Skip to content](https://viem.sh/docs/actions/wallet/signMessage#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K signMessage =========== Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191) : `keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))`. With the calculated signature, you can: * use `[verifyMessage](https://viem.sh/docs/utilities/verifyMessage) ` to verify the signature, * use `[recoverMessageAddress](https://viem.sh/docs/utilities/recoverMessageAddress) ` to recover the signing address from a signature. Usage[](https://viem.sh/docs/actions/wallet/signMessage#usage) --------------------------------------------------------------- example.tsconfig.ts import { account, walletClient } from './config' const signature_1 = await walletClient.signMessage({ account, message: 'hello world', }) Output: "0xa461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b"const signature_2 = await walletClient.signMessage({ account, // Hex data representation of message. message: { raw: '0x68656c6c6f20776f726c64' }, }) Output: "0xa461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b" ### Account Hoisting[](https://viem.sh/docs/actions/wallet/signMessage#account-hoisting) If you do not wish to pass an `account` to every `signMessage`, you can also hoist the Account on the Wallet Client (see `config.ts`). [Learn more](https://viem.sh/docs/clients/wallet#withaccount) . example.tsconfig.ts (JSON-RPC Account)config.ts (Local Account) import { walletClient } from './config' const signature = await walletClient.signMessage({ message: 'hello world', }) "0xa461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b" Returns[](https://viem.sh/docs/actions/wallet/signMessage#returns) ------------------------------------------------------------------- `[Hex](https://viem.sh/docs/glossary/types#hex) ` The signed message. Parameters[](https://viem.sh/docs/actions/wallet/signMessage#parameters) ------------------------------------------------------------------------- ### account[](https://viem.sh/docs/actions/wallet/signMessage#account) * **Type:** `Account | Address` Account to use for signing. Accepts a [JSON-RPC Account](https://viem.sh/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . const signature = await walletClient.signMessage({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', }) ### message[](https://viem.sh/docs/actions/wallet/signMessage#message) * **Type:** `string | { raw: Hex | ByteArray }` Message to sign. By default, viem signs the UTF-8 representation of the message. const signature = await walletClient.signMessage({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', }) To sign the data representation of the message, you can use the `raw` attribute. const signature = await walletClient.signMessage({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: { raw: '0x68656c6c6f20776f726c64' }, }) JSON-RPC Methods[](https://viem.sh/docs/actions/wallet/signMessage#json-rpc-methods) ------------------------------------------------------------------------------------- * JSON-RPC Accounts: * `[personal_sign](https://docs.metamask.io/guide/signing-data#personal-sign) ` * Local Accounts * Signs locally. No JSON-RPC request. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/signMessage.md) Copy page for AI Ask AI... ⌘ I --- # decodeDeployData · Viem [Skip to content](https://viem.sh/docs/contract/decodeDeployData#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K decodeDeployData ================ Decodes ABI encoded deploy data (bytecode & arguments). The opposite of `[encodeDeployData](https://viem.sh/docs/contract/encodeDeployData) `. Install[](https://viem.sh/docs/contract/decodeDeployData#install) ------------------------------------------------------------------ import { decodeDeployData } from 'viem' Usage[](https://viem.sh/docs/contract/decodeDeployData#usage) -------------------------------------------------------------- example.tsabi.ts import { decodeDeployData } from 'viem' import { wagmiAbi } from './abi.ts' const { args } = decodeDeployData({ abi: wagmiAbi, bytecode: '0x6080604052348015600f57600080fd5b50603f80601d6000396000f3fe6080604052600080fdfea2646970667358221220116554d4ba29ee08da9e97dc54ff9a2a65d67a648140d616fc225a25ff08c86364736f6c63430008070033', data: '0x6080604052348015600f57600080fd5b50603f80601d6000396000f3fe6080604052600080fdfea2646970667358221220116554d4ba29ee08da9e97dc54ff9a2a65d67a648140d616fc225a25ff08c86364736f6c634300080700330000000000000000000000000000000000000000000000000000000000010f2c' }) // { args: [69420n], bytecode: '0x6080604...' } Return Value[](https://viem.sh/docs/contract/decodeDeployData#return-value) ---------------------------------------------------------------------------- { args: unknown[] | undefined; bytecode: Hex; } Decoded deploy data. Parameters[](https://viem.sh/docs/contract/decodeDeployData#parameters) ------------------------------------------------------------------------ ### abi[](https://viem.sh/docs/contract/decodeDeployData#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const { args } = decodeDeployData({ abi: wagmiAbi, bytecode: '0x6080604052348015600f57600080fd5b50603f80601d6000396000f3fe6080604052600080fdfea2646970667358221220116554d4ba29ee08da9e97dc54ff9a2a65d67a648140d616fc225a25ff08c86364736f6c63430008070033', data: '0x6080604052348015600f57600080fd5b50603f80601d6000396000f3fe6080604052600080fdfea2646970667358221220116554d4ba29ee08da9e97dc54ff9a2a65d67a648140d616fc225a25ff08c86364736f6c634300080700330000000000000000000000000000000000000000000000000000000000010f2c' }) ### bytecode[](https://viem.sh/docs/contract/decodeDeployData#bytecode) * **Type:** `[Hex](https://viem.sh/docs/glossary/types#hex) ` Contract bytecode. const { args } = decodeDeployData({ abi: wagmiAbi, bytecode: '0x6080604052348015600f57600080fd5b50603f80601d6000396000f3fe6080604052600080fdfea2646970667358221220116554d4ba29ee08da9e97dc54ff9a2a65d67a648140d616fc225a25ff08c86364736f6c63430008070033', data: '0x6080604052348015600f57600080fd5b50603f80601d6000396000f3fe6080604052600080fdfea2646970667358221220116554d4ba29ee08da9e97dc54ff9a2a65d67a648140d616fc225a25ff08c86364736f6c634300080700330000000000000000000000000000000000000000000000000000000000010f2c' }) ### data[](https://viem.sh/docs/contract/decodeDeployData#data) * **Type:** `[Hex](https://viem.sh/docs/glossary/types#hex) ` The encoded calldata. const { args } = decodeDeployData({ abi: wagmiAbi, bytecode: '0x6080604052348015600f57600080fd5b50603f80601d6000396000f3fe6080604052600080fdfea2646970667358221220116554d4ba29ee08da9e97dc54ff9a2a65d67a648140d616fc225a25ff08c86364736f6c63430008070033', data: '0x6080604052348015600f57600080fd5b50603f80601d6000396000f3fe6080604052600080fdfea2646970667358221220116554d4ba29ee08da9e97dc54ff9a2a65d67a648140d616fc225a25ff08c86364736f6c634300080700330000000000000000000000000000000000000000000000000000000000010f2c' }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/decodeDeployData.md) Copy page for AI Ask AI... ⌘ I --- # encodeDeployData · Viem [Skip to content](https://viem.sh/docs/contract/encodeDeployData#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K encodeDeployData ================ Encodes deploy data (bytecode & constructor args) into an ABI encoded value. Install[](https://viem.sh/docs/contract/encodeDeployData#install) ------------------------------------------------------------------ import { encodeDeployData } from 'viem' Usage[](https://viem.sh/docs/contract/encodeDeployData#usage) -------------------------------------------------------------- Below is a very basic example of how to encode deploy data. example.tsabi.ts import { encodeDeployData } from 'viem' import { wagmiAbi } from './abi.ts' const data = encodeDeployData({ abi: wagmiAbi, bytecode: '0x608060405260405161083e38038061083e833981016040819052610...' }) // 0x608060405260405161083e38038061083e833981016040819052610... ### Passing Arguments[](https://viem.sh/docs/contract/encodeDeployData#passing-arguments) If your constructor requires argument(s), you can pass them through with the `args` attribute. TypeScript types for `args` will be inferred from the constructor & ABI, to guard you from inserting the wrong values. For example, the `constructor` below requires an **address** argument, and it is typed as `["0x${string}"]`. example.tsabi.ts import { encodeDeployData } from 'viem' import { wagmiAbi } from './abi' const data = encodeDeployData({ abi: wagmiAbi, bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] }) // 0x608060405260405161083e38038061083e833981016040819052610...00000000000000000000000000000000a5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC Return Value[](https://viem.sh/docs/contract/encodeDeployData#return-value) ---------------------------------------------------------------------------- `[Hex](https://viem.sh/docs/glossary/types#hex) ` ABI encoded data (bytecode & constructor arguments). Parameters[](https://viem.sh/docs/contract/encodeDeployData#parameters) ------------------------------------------------------------------------ ### abi[](https://viem.sh/docs/contract/encodeDeployData#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const data = encodeDeployData({ abi: wagmiAbi, bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] }) ### bytecode[](https://viem.sh/docs/contract/encodeDeployData#bytecode) * **Type:** `[Hex](https://viem.sh/docs/glossary/types#hex) ` Contract bytecode. const data = encodeDeployData({ abi: wagmiAbi, bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] }) ### args (optional)[](https://viem.sh/docs/contract/encodeDeployData#args-optional) * **Type:** Inferred from ABI. Arguments to pass to function call. const data = encodeDeployData({ abi: wagmiAbi, bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/encodeDeployData.md) Copy page for AI Ask AI... ⌘ I --- # deployContract · Viem [Skip to content](https://viem.sh/docs/contract/deployContract#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K deployContract ============== Deploys a contract to the network, given bytecode & constructor arguments. Usage[](https://viem.sh/docs/contract/deployContract#usage) ------------------------------------------------------------ example.tsabi.tsclient.ts import { wagmiAbi } from './abi' import { account, walletClient } from './config' const hash = await walletClient.deployContract({ abi, account, bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', }) ### Deploying with Constructor Args[](https://viem.sh/docs/contract/deployContract#deploying-with-constructor-args) example.tsabi.tsclient.ts import { deployContract } from 'viem' import { wagmiAbi } from './abi' import { account, walletClient } from './config' const hash = await walletClient.deployContract({ abi, account, args: [69420], bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', }) Returns[](https://viem.sh/docs/contract/deployContract#returns) ---------------------------------------------------------------- `[Hash](https://viem.sh/docs/glossary/types#hash) ` The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. Parameters[](https://viem.sh/docs/contract/deployContract#parameters) ---------------------------------------------------------------------- ### abi[](https://viem.sh/docs/contract/deployContract#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const hash = await walletClient.deployContract({ abi: wagmiAbi, account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', }) ### account[](https://viem.sh/docs/contract/deployContract#account) * **Type:** `Account | Address` The Account to deploy the contract from. Accepts a [JSON-RPC Account](https://viem.sh/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . const hash = await walletClient.deployContract({ abi: wagmiAbi, account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', }) ### bytecode[](https://viem.sh/docs/contract/deployContract#bytecode) * **Type:** `[Hex](https://viem.sh/docs/glossary/types#hex) ` The contract's bytecode. const hash = await walletClient.deployContract({ abi: wagmiAbi, account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', }) ### args (if required)[](https://viem.sh/docs/contract/deployContract#args-if-required) * **Type:** Inferred from ABI. Constructor arguments to call upon deployment. const hash = await walletClient.deployContract({ abi: wagmiAbi, account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', args: [69] }) Live Example[](https://viem.sh/docs/contract/deployContract#live-example) -------------------------------------------------------------------------- Check out the usage of `deployContract` in the live [Deploying Contracts Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_deploying-contracts) below. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/deployContract.md) Copy page for AI Ask AI... ⌘ I --- # getStorageAt · Viem [Skip to content](https://viem.sh/docs/contract/getStorageAt#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getStorageAt ============ Returns the value from a storage slot at a given address. Usage[](https://viem.sh/docs/contract/getStorageAt#usage) ---------------------------------------------------------- example.tsclient.ts import { toHex } from 'viem' import { wagmiAbi } from './abi' import { publicClient } from './client' const data = await publicClient.getStorageAt({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: toHex(0) }) Return Value[](https://viem.sh/docs/contract/getStorageAt#return-value) ------------------------------------------------------------------------ `[Hex](https://viem.sh/docs/glossary/types#hex) ` The value of the storage slot. Parameters[](https://viem.sh/docs/contract/getStorageAt#parameters) -------------------------------------------------------------------- ### address[](https://viem.sh/docs/contract/getStorageAt#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The contract address. const data = await publicClient.getStorageAt({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: toHex(0) }) ### slot[](https://viem.sh/docs/contract/getStorageAt#slot) * **Type**: `[Hex](https://viem.sh/docs/glossary/types#hex) ` The storage position (as a hex encoded value). const data = await publicClient.getStorageAt({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: toHex(0) }) ### blockNumber (optional)[](https://viem.sh/docs/contract/getStorageAt#blocknumber-optional) * **Type:** `number` The block number to perform the storage slot read against. const bytecode = await publicClient.getStorageAt({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: toHex(0), blockNumber: 15121123n, }) ### blockTag (optional)[](https://viem.sh/docs/contract/getStorageAt#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` The block tag to perform the storage slot read against. const bytecode = await publicClient.getStorageAt({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: toHex(0), blockTag: 'safe', }) JSON-RPC Method[](https://viem.sh/docs/contract/getStorageAt#json-rpc-method) ------------------------------------------------------------------------------ `[eth_getStorageAt](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/getStorageAt.md) Copy page for AI Ask AI... ⌘ I --- # watchPendingTransactions · Viem [Skip to content](https://viem.sh/docs/actions/public/watchPendingTransactions#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K watchPendingTransactions ======================== Watches and returns pending transaction hashes. This Action will batch up all the pending transactions found within the `[pollingInterval](https://viem.sh/docs/actions/public/watchPendingTransactions#pollinginterval-optional) `, and invoke them via `[onTransactions](https://viem.sh/docs/actions/public/watchPendingTransactions#ontransactions) `. Usage[](https://viem.sh/docs/actions/public/watchPendingTransactions#usage) ---------------------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' const unwatch = publicClient.watchPendingTransactions( { onTransactions: hashes => console.log(hashes) } ) > ['0x...', '0x...', '0x...', ...] Returns[](https://viem.sh/docs/actions/public/watchPendingTransactions#returns) -------------------------------------------------------------------------------- `UnwatchFn` A function that can be invoked to stop watching for new pending transaction hashes. Parameters[](https://viem.sh/docs/actions/public/watchPendingTransactions#parameters) -------------------------------------------------------------------------------------- ### onTransactions[](https://viem.sh/docs/actions/public/watchPendingTransactions#ontransactions) * **Type:** `(hashes: '0x${string}'[]) => void` The new pending transaction hashes. const unwatch = publicClient.watchPendingTransactions( { onTransactions: hashes => console.log(hashes) } ) ### batch (optional)[](https://viem.sh/docs/actions/public/watchPendingTransactions#batch-optional) * **Type:** `boolean` * **Default:** `true` Whether or not to batch the transaction hashes between polling intervals. const unwatch = publicClient.watchPendingTransactions( { batch: false, onTransactions: hashes => console.log(hashes), } ) ### onError (optional)[](https://viem.sh/docs/actions/public/watchPendingTransactions#onerror-optional) * **Type:** `(error: Error) => void` Error thrown from listening for new pending transactions. const unwatch = publicClient.watchPendingTransactions( { onError: error => console.log(error), onTransactions: hashes => console.log(hashes), } ) ### poll (optional)[](https://viem.sh/docs/actions/public/watchPendingTransactions#poll-optional) * **Type:** `boolean` * **Default:** `false` for WebSocket Clients, `true` for non-WebSocket Clients Whether or not to use a polling mechanism to check for new pending transactions instead of a WebSocket subscription. This option is only configurable for Clients with a [WebSocket Transport](https://viem.sh/docs/clients/transports/websocket) . import { createPublicClient, webSocket } from 'viem' import { mainnet } from 'viem/chains' const publicClient = createPublicClient({ chain: mainnet, transport: webSocket() }) const unwatch = publicClient.watchPendingTransactions( { onTransactions: transactions => console.log(transactions), poll: true, } ) ### pollingInterval (optional)[](https://viem.sh/docs/actions/public/watchPendingTransactions#pollinginterval-optional) * **Type:** `number` Polling frequency (in ms). Defaults to the Client's `pollingInterval` config. const unwatch = publicClient.watchPendingTransactions( { pollingInterval: 1_000, onTransactions: hashes => console.log(hashes), } ) JSON-RPC Methods[](https://viem.sh/docs/actions/public/watchPendingTransactions#json-rpc-methods) -------------------------------------------------------------------------------------------------- * When `poll: true` * Calls `[eth_newPendingTransactionFilter](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) ` to initialize the filter. * Calls `[eth_getFilterChanges](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getFilterChanges) ` on a polling interval. * When `poll: false` & WebSocket Transport, uses a WebSocket subscription via `[eth_subscribe](https://docs.alchemy.com/reference/eth-subscribe-polygon) ` and the `"newPendingTransactions"` event. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/watchPendingTransactions.md) Copy page for AI Ask AI... ⌘ I --- # decodeFunctionData · Viem [Skip to content](https://viem.sh/docs/contract/decodeFunctionData#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K decodeFunctionData ================== Decodes ABI encoded data (4 byte selector & arguments) into a function name and arguments. The opposite of `[encodeFunctionData](https://viem.sh/docs/contract/encodeFunctionData) `. Install[](https://viem.sh/docs/contract/decodeFunctionData#install) -------------------------------------------------------------------- import { decodeFunctionData } from 'viem' Usage[](https://viem.sh/docs/contract/decodeFunctionData#usage) ---------------------------------------------------------------- Below is a very basic example of how to decode a function to calldata. example.tsabi.ts import { decodeFunctionData } from 'viem' import { wagmiAbi } from './abi.ts' const { functionName } = decodeFunctionData({ abi: wagmiAbi, data: '0x18160ddd' }) // { functionName: 'totalSupply' } ### Extracting Arguments[](https://viem.sh/docs/contract/decodeFunctionData#extracting-arguments) If your calldata includes argument(s) after the 4byte function signature, you can extract them with the `args` return value. example.tsabi.ts import { decodeFunctionData } from 'viem' import { wagmiAbi } from './abi' const { functionName, args } = decodeFunctionData({ abi: wagmiAbi, data: '0x70a08231000000000000000000000000fba3912ca04dd458c843e2ee08967fc04f3579c2' }) // { functionName: 'balanceOf', args: ["0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2"] } Return Value[](https://viem.sh/docs/contract/decodeFunctionData#return-value) ------------------------------------------------------------------------------ { functionName: string; args: unknown[] | undefined; } Decoded ABI function data. ### functionName[](https://viem.sh/docs/contract/decodeFunctionData#functionname) * **Type**: `string` The decoded function name. ### args[](https://viem.sh/docs/contract/decodeFunctionData#args) * **Type**: `unknown[] | undefined` The decoded function arguments. Parameters[](https://viem.sh/docs/contract/decodeFunctionData#parameters) -------------------------------------------------------------------------- ### abi[](https://viem.sh/docs/contract/decodeFunctionData#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const { functionName } = decodeFunctionData({ abi: wagmiAbi, data: '0x18160ddd' }) ### data[](https://viem.sh/docs/contract/decodeFunctionData#data) * **Type:** `[Hex](https://viem.sh/docs/glossary/types#hex) ` The encoded calldata. const { functionName } = decodeFunctionData({ abi: wagmiAbi, data: '0x18160ddd' }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/decodeFunctionData.md) Copy page for AI Ask AI... ⌘ I --- # encodeEventTopics · Viem [Skip to content](https://viem.sh/docs/contract/encodeEventTopics#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K encodeEventTopics ================= Encodes an event (with optional arguments) into filter topics. Install[](https://viem.sh/docs/contract/encodeEventTopics#install) ------------------------------------------------------------------- import { encodeEventTopics } from 'viem' Usage[](https://viem.sh/docs/contract/encodeEventTopics#usage) --------------------------------------------------------------- Below is a very basic example of how to encode event topics without arguments. example.tsabi.ts import { encodeEventTopics } from 'viem' import { wagmiAbi } from './abi.ts' const topics = encodeEventTopics({ abi: wagmiAbi, eventName: 'Transfer' }) // ["0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0"] ### Passing Arguments[](https://viem.sh/docs/contract/encodeEventTopics#passing-arguments) If your event has indexed parameters, you can pass their values through with the `args` attribute. TypeScript types for `args` will be inferred from the event name & ABI, to guard you from inserting the wrong values. For example, the `Transfer` event below accepts an **address** argument for the `from` and `to` attributes, and it is typed as `"0x${string}"`. example.tsabi.ts import { encodeEventTopics } from 'viem' const topics = encodeEventTopics({ abi: wagmiAbi, eventName: 'Transfer' args: { from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' } }) // ["0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0", "0x00000000000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266", "0x0000000000000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8"] ### Without `eventName`[](https://viem.sh/docs/contract/encodeEventTopics#without-eventname) If your `abi` contains only one ABI item, you can omit the `eventName` (it becomes optional): import { encodeEventTopics } from 'viem' const abiItem = { inputs: [\ {\ indexed: true,\ name: 'from',\ type: 'address',\ },\ { indexed: true, name: 'to', type: 'address' },\ {\ indexed: false,\ name: 'value',\ type: 'uint256',\ },\ ], name: 'Transfer', type: 'event', } const topics = encodeEventTopics({ abi: [abiItem], eventName: 'Transfer' }) // ["0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0"] Return Value[](https://viem.sh/docs/contract/encodeEventTopics#return-value) ----------------------------------------------------------------------------- Encoded topics. Parameters[](https://viem.sh/docs/contract/encodeEventTopics#parameters) ------------------------------------------------------------------------- ### abi[](https://viem.sh/docs/contract/encodeEventTopics#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const data = encodeEventTopics({ abi: wagmiAbi, functionName: 'Transfer', }) ### eventName[](https://viem.sh/docs/contract/encodeEventTopics#eventname) * **Type:** `string` Name of the event. const data = encodeEventTopics({ abi: wagmiAbi, eventName: 'Transfer', }) ### args (optional)[](https://viem.sh/docs/contract/encodeEventTopics#args-optional) * **Type:** `string` A list of _indexed_ event arguments. const data = encodeEventTopics({ abi: wagmiAbi, eventName: 'Transfer', args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' } }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/encodeEventTopics.md) Copy page for AI Ask AI... ⌘ I --- # encodeErrorResult · Viem [Skip to content](https://viem.sh/docs/contract/encodeErrorResult#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K encodeErrorResult ================= Encodes a reverted error from a function call. The opposite of `[decodeErrorResult](https://viem.sh/docs/contract/decodeErrorResult) `. Install[](https://viem.sh/docs/contract/encodeErrorResult#install) ------------------------------------------------------------------- import { encodeErrorResult } from 'viem' Usage[](https://viem.sh/docs/contract/encodeErrorResult#usage) --------------------------------------------------------------- example.tsabi.ts import { decodeErrorResult } from 'viem' import { wagmiAbi } from './abi.ts' const value = encodeErrorResult({ abi: wagmiAbi, errorName: 'InvalidTokenError', args: ['sold out'] }) // 0xb758934b000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b68656c6c6f20776f726c64000000000000000000000000000000000000000000 ### Without `errorName`[](https://viem.sh/docs/contract/encodeErrorResult#without-errorname) If your `abi` contains only one ABI item, you can omit the `errorName` (it becomes optional): import { decodeErrorResult } from 'viem' const abiItem = { inputs: [{ name: 'reason', type: 'string' }], name: 'InvalidTokenError', type: 'error' } const value = encodeErrorResult({ abi: [abiItem], errorName: 'InvalidTokenError', args: ['sold out'] }) // 0xb758934b000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b68656c6c6f20776f726c64000000000000000000000000000000000000000000 Return Value[](https://viem.sh/docs/contract/encodeErrorResult#return-value) ----------------------------------------------------------------------------- `[Hex](https://viem.sh/docs/glossary/types#hex) ` The encoded error. Parameters[](https://viem.sh/docs/contract/encodeErrorResult#parameters) ------------------------------------------------------------------------- ### abi[](https://viem.sh/docs/contract/encodeErrorResult#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const value = decodeErrorResult({ abi: wagmiAbi, errorName: 'InvalidTokenError', args: ['sold out'] }) ### errorName[](https://viem.sh/docs/contract/encodeErrorResult#errorname) * **Type:** `string` The error name on the ABI. const value = encodeErrorResult({ abi: wagmiAbi, errorName: 'InvalidTokenError', args: ['sold out'] }) ### args (optional)[](https://viem.sh/docs/contract/encodeErrorResult#args-optional) * **Type:** Inferred. Arguments (if required) to pass to the error. const value = encodeErrorResult({ abi: wagmiAbi, errorName: 'InvalidTokenError', args: ['sold out'] }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/encodeErrorResult.md) Copy page for AI Ask AI... ⌘ I --- # decodeFunctionResult · Viem [Skip to content](https://viem.sh/docs/contract/decodeFunctionResult#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K decodeFunctionResult ==================== Decodes the result of a function call on a contract. Install[](https://viem.sh/docs/contract/decodeFunctionResult#install) ---------------------------------------------------------------------- import { decodeFunctionResult } from 'viem' Usage[](https://viem.sh/docs/contract/decodeFunctionResult#usage) ------------------------------------------------------------------ Given an ABI (`abi`) and a function (`functionName`), pass through the encoded calldata (`data`) to retrieve the decoded value: example.tsabi.ts import { decodeFunctionResult } from 'viem' import { wagmiAbi } from './abi.ts' const value = decodeFunctionResult({ abi: wagmiAbi, functionName: 'ownerOf', data: '0x000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac' }) // '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' ### Without `functionName`[](https://viem.sh/docs/contract/decodeFunctionResult#without-functionname) If your `abi` contains only one ABI item, you can omit the `functionName` (it becomes optional): example.tsabi.ts import { decodeFunctionResult } from 'viem' import { abiItem } from './abi.ts' const value = decodeFunctionResult({ abi: [abiItem], functionName: 'ownerOf', data: '0x000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac' }) // '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' ### A more complex example[](https://viem.sh/docs/contract/decodeFunctionResult#a-more-complex-example) example.tsabi.ts import { decodeFunctionResult } from 'viem' const value = decodeFunctionResult({ abi: wagmiAbi, functionName: 'getInfo', data: '0x000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac0000000000000000000000000000000000000000000000000000000000010f2c0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac0000000000000000000000000000000000000000000000000000000000000045' }) /** * { * foo: { * sender: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', * x: 69420n, * y: true * }, * sender: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', * z: 69 * } */ Return Value[](https://viem.sh/docs/contract/decodeFunctionResult#return-value) -------------------------------------------------------------------------------- The decoded data. Type is inferred from the ABI. Parameters[](https://viem.sh/docs/contract/decodeFunctionResult#parameters) ---------------------------------------------------------------------------- ### abi[](https://viem.sh/docs/contract/decodeFunctionResult#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const value = decodeFunctionResult({ abi: wagmiAbi, functionName: 'ownerOf', data: '0x000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac' }) ### functionName[](https://viem.sh/docs/contract/decodeFunctionResult#functionname) * **Type:** `string` The function to encode from the ABI. const value = decodeFunctionResult({ abi: wagmiAbi, functionName: 'ownerOf', data: '0x000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac' }) ### data[](https://viem.sh/docs/contract/decodeFunctionResult#data) * **Type:** `[Hex](https://viem.sh/docs/glossary/types#hex) ` The calldata. const value = decodeFunctionResult({ abi: wagmiAbi, functionName: 'ownerOf', data: '0x000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac' }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/decodeFunctionResult.md) Copy page for AI Ask AI... ⌘ I --- # encodeFunctionData · Viem [Skip to content](https://viem.sh/docs/contract/encodeFunctionData#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K encodeFunctionData ================== Encodes the function name and parameters into an ABI encoded value (4 byte selector & arguments). Install[](https://viem.sh/docs/contract/encodeFunctionData#install) -------------------------------------------------------------------- import { encodeFunctionData } from 'viem' Usage[](https://viem.sh/docs/contract/encodeFunctionData#usage) ---------------------------------------------------------------- Below is a very basic example of how to encode a function to calldata. example.tsabi.ts import { encodeFunctionData } from 'viem' import { wagmiAbi } from './abi.ts' const data = encodeFunctionData({ abi: wagmiAbi, functionName: 'totalSupply' }) ### Passing Arguments[](https://viem.sh/docs/contract/encodeFunctionData#passing-arguments) If your function requires argument(s), you can pass them through with the `args` attribute. TypeScript types for `args` will be inferred from the function name & ABI, to guard you from inserting the wrong values. For example, the `balanceOf` function name below requires an **address** argument, and it is typed as `["0x${string}"]`. example.tsabi.ts import { encodeFunctionData } from 'viem' import { wagmiAbi } from './abi' const data = encodeFunctionData({ abi: wagmiAbi, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] }) ### Without `functionName`[](https://viem.sh/docs/contract/encodeFunctionData#without-functionname) If your `abi` contains only one ABI item, you can omit the `functionName` (it becomes optional): import { encodeFunctionData } from 'viem' const abiItem = { inputs: [{ name: 'owner', type: 'address' }], name: 'balanceOf', outputs: [{ name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', } const data = encodeFunctionData({ abi: [abiItem], functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] }) ### Preparation (Performance Optimization)[](https://viem.sh/docs/contract/encodeFunctionData#preparation-performance-optimization) If you are calling the same function multiple times, you can prepare the function selector once and reuse it. import { prepareEncodeFunctionData, encodeFunctionData } from 'viem' const transfer = prepareEncodeFunctionData({ abi: erc20Abi, functionName: 'transfer', }) for (const address of addresses) { const data = encodeFunctionData({ ...transfer, args: [address, 69420n], }) } Return Value[](https://viem.sh/docs/contract/encodeFunctionData#return-value) ------------------------------------------------------------------------------ `[Hex](https://viem.sh/docs/glossary/types#hex) ` ABI encoded data (4byte function selector & arguments). Parameters[](https://viem.sh/docs/contract/encodeFunctionData#parameters) -------------------------------------------------------------------------- ### abi[](https://viem.sh/docs/contract/encodeFunctionData#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const data = encodeFunctionData({ abi: wagmiAbi, functionName: 'totalSupply', }) ### functionName[](https://viem.sh/docs/contract/encodeFunctionData#functionname) * **Type:** `string` The function to encode from the ABI. const data = encodeFunctionData({ abi: wagmiAbi, functionName: 'totalSupply', }) ### args (optional)[](https://viem.sh/docs/contract/encodeFunctionData#args-optional) * **Type:** Inferred from ABI. Arguments to pass to function call. const data = encodeFunctionData({ abi: wagmiAbi, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/encodeFunctionData.md) Copy page for AI Ask AI... ⌘ I --- # verifySiweMessage · Viem [Skip to content](https://viem.sh/docs/siwe/actions/verifySiweMessage#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K verifySiweMessage ================= Verifies [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message was signed. See `[createSiweMessage](https://viem.sh/docs/siwe/utilities/createSiweMessage) ` for info on how to create a EIP-4361 formatted message. Usage[](https://viem.sh/docs/siwe/actions/verifySiweMessage#usage) ------------------------------------------------------------------- example.tsclient.tsmessage.ts import { account, walletClient, publicClient } from './client' import { message } from './message' const signature = await walletClient.signMessage({ account, message }) const valid = await publicClient.verifySiweMessage({ message, signature, }) true Returns[](https://viem.sh/docs/siwe/actions/verifySiweMessage#returns) ----------------------------------------------------------------------- `boolean` Whether the signed message is valid for the given address. Parameters[](https://viem.sh/docs/siwe/actions/verifySiweMessage#parameters) ----------------------------------------------------------------------------- ### message[](https://viem.sh/docs/siwe/actions/verifySiweMessage#message) * **Type:** `string` [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message to be verified. const valid = await publicClient.verifySiweMessage({ message: createSiweMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', chainId: 1, domain: 'example.com', nonce: generateSiweNonce(), uri: 'https://example.com/path', version: '1', }), signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ### signature[](https://viem.sh/docs/siwe/actions/verifySiweMessage#signature) * **Type:** `Hex` The signature that was generated by signing the message with the address's signer. const valid = await publicClient.verifySiweMessage({ message, signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ### address (optional)[](https://viem.sh/docs/siwe/actions/verifySiweMessage#address-optional) * **Type:** `Address` Ethereum address to check against. const valid = await publicClient.verifySiweMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message, signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ### blockNumber (optional)[](https://viem.sh/docs/siwe/actions/verifySiweMessage#blocknumber-optional) * **Type:** `number` Only used when verifying a message that was signed by a Smart Contract Account. The block number to check if the contract was already deployed. const valid = await publicClient.verifySiweMessage({ blockNumber: 42069n, message, signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ### blockTag (optional)[](https://viem.sh/docs/siwe/actions/verifySiweMessage#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` Only used when verifying a message that was signed by a Smart Contract Account. The block tag to check if the contract was already deployed. const valid = await publicClient.verifySiweMessage({ blockTag: 'safe', message, signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ### domain (optional)[](https://viem.sh/docs/siwe/actions/verifySiweMessage#domain-optional) * **Type:** `string` [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against. const valid = await publicClient.verifySiweMessage({ domain: 'viem.sh', message, signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ### nonce (optional)[](https://viem.sh/docs/siwe/actions/verifySiweMessage#nonce-optional) * **Type:** `string` Random string to check against. const valid = await publicClient.verifySiweMessage({ nonce: generateSiweNonce(), message, signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ### scheme (optional)[](https://viem.sh/docs/siwe/actions/verifySiweMessage#scheme-optional) * **Type:** `string` [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against. const valid = await publicClient.verifySiweMessage({ scheme: 'https', message, signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ### time (optional)[](https://viem.sh/docs/siwe/actions/verifySiweMessage#time-optional) * **Type:** `Date` * **Default:** `new Date()` Current time to check optional `[expirationTime](https://viem.sh/docs/siwe/utilities/createSiweMessage#expirationtime-optional) ` and `[notBefore](https://viem.sh/docs/siwe/utilities/createSiweMessage#notbefore-optional) ` message fields. const valid = await publicClient.verifySiweMessage({ time: new Date(), message, signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/siwe/actions/verifySiweMessage.md) Copy page for AI Ask AI... ⌘ I --- # setStorageAt · Viem [Skip to content](https://viem.sh/docs/actions/test/setStorageAt#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K setStorageAt ============ Writes to a slot of an account's storage. Usage[](https://viem.sh/docs/actions/test/setStorageAt#usage) -------------------------------------------------------------- example.tsclient.ts import { testClient } from './client' await testClient.setStorageAt({ address: '0xe846c6fcf817734ca4527b28ccb4aea2b6663c79', index: 2, value: '0x0000000000000000000000000000000000000000000000000000000000000069' }) Parameters[](https://viem.sh/docs/actions/test/setStorageAt#parameters) ------------------------------------------------------------------------ ### address[](https://viem.sh/docs/actions/test/setStorageAt#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The account address. await testClient.setStorageAt({ address: '0xe846c6fcf817734ca4527b28ccb4aea2b6663c79', index: 2, value: '0x0000000000000000000000000000000000000000000000000000000000000069' }) ### index[](https://viem.sh/docs/actions/test/setStorageAt#index) * **Type:** `number | Hash` The storage slot (index). Can either be a number or hash value. await testClient.setStorageAt({ address: '0xe846c6fcf817734ca4527b28ccb4aea2b6663c79', index: '0xa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb49', value: '0x0000000000000000000000000000000000000000000000000000000000000069' }) ### value[](https://viem.sh/docs/actions/test/setStorageAt#value) * **Type:** `number` The value to store as a 32 byte hex string. await testClient.setStorageAt({ address: '0xe846c6fcf817734ca4527b28ccb4aea2b6663c79', index: 2, value: '0x0000000000000000000000000000000000000000000000000000000000000069' }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/test/setStorageAt.md) Copy page for AI Ask AI... ⌘ I --- # decodeEventLog · Viem [Skip to content](https://viem.sh/docs/contract/decodeEventLog#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K decodeEventLog ============== Decodes ABI encoded event topics & data (from an [Event Log](https://viem.sh/docs/glossary/terms#event-log) ) into an event name and structured arguments (both indexed & non-indexed). Install[](https://viem.sh/docs/contract/decodeEventLog#install) ---------------------------------------------------------------- import { decodeEventLog } from 'viem' Usage[](https://viem.sh/docs/contract/decodeEventLog#usage) ------------------------------------------------------------ example.tsabi.ts import { decodeEventLog } from 'viem' import { wagmiAbi } from './abi.ts' const topics = decodeEventLog({ abi: wagmiAbi, data: '0x0000000000000000000000000000000000000000000000000000000000000001', topics: [\ '0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0', \ '0x00000000000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266', \ '0x0000000000000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8'\ ] }) /** * { * eventName: 'Transfer', * args: { * from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' * value: 1n * } * } */ ### Partial Decode[](https://viem.sh/docs/contract/decodeEventLog#partial-decode) By default, if the `topics` and `data` does not conform to the ABI (a mismatch between the number of indexed/non-indexed arguments), `decodeEventLog` will throw an error. For example, the following will throw an error as there is a mismatch in non-`indexed` arguments & `data` length. decodeEventLog({ abi: parseAbi(['event Transfer(address indexed, address, uint256)']), // `data` should be 64 bytes, but is only 32 bytes. data: '0x0000000000000000000000000000000000000000000000000000000000000001', topics: [\ '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',\ '0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266',\ ] }) // [DecodeLogDataMismatch]: Data size of 32 bytes is too small for non-indexed event parameters. It is possible for `decodeEventLog` to try and partially decode the Log, this can be done by setting the `strict` argument to `false`: decodeEventLog({ abi: parseAbi(['event Transfer(address indexed, address, uint256)']), data: '0x0000000000000000000000000000000000000000000000000000000000000001', topics: [\ '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',\ '0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266',\ ], strict: false }) /** * { * eventName: 'Transfer', * args: ['0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266'] * } */ Return Value[](https://viem.sh/docs/contract/decodeEventLog#return-value) -------------------------------------------------------------------------- { eventName: string; args: Inferred; } Decoded ABI event topics. Parameters[](https://viem.sh/docs/contract/decodeEventLog#parameters) ---------------------------------------------------------------------- ### abi[](https://viem.sh/docs/contract/decodeEventLog#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const topics = decodeEventLog({ abi: wagmiAbi, data: '0x0000000000000000000000000000000000000000000000000000000000000001', topics: [\ '0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0', \ '0x00000000000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266', \ '0x0000000000000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8'\ ] }) ### topics[](https://viem.sh/docs/contract/decodeEventLog#topics) * **Type:** `[Hex, ...(Hex | Hex[] | null)[]]` A set of topics (encoded indexed args) from the [Event Log](https://viem.sh/docs/glossary/terms#event-log) . const topics = decodeEventLog({ abi: wagmiAbi, data: '0x0000000000000000000000000000000000000000000000000000000000000001', topics: [ \ '0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0', \ '0x00000000000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266', \ '0x0000000000000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8'\ ] }) ### data (optional)[](https://viem.sh/docs/contract/decodeEventLog#data-optional) * **Type:** `string` The data (encoded non-indexed args) from the [Event Log](https://viem.sh/docs/glossary/terms#event-log) . const topics = decodeEventLog({ abi: wagmiAbi, data: '0x0000000000000000000000000000000000000000000000000000000000000001', topics: [\ '0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0', \ '0x00000000000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266', \ '0x0000000000000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8'\ ] }) ### eventName (optional)[](https://viem.sh/docs/contract/decodeEventLog#eventname-optional) * **Type:** `string` An event name from the ABI. Provide an `eventName` to infer the return type of `decodeEventLog`. const topics = decodeEventLog({ abi: wagmiAbi, eventName: 'Transfer', topics: [\ '0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0', \ '0x00000000000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266', \ '0x0000000000000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8'\ ] }) ### strict (optional)[](https://viem.sh/docs/contract/decodeEventLog#strict-optional) * **Type:** `boolean` * **Default:** `true` If `true`, `decodeEventLog` will throw an error if the `data` & `topics` lengths to not conform to the event on the ABI. If `false`, `decodeEventLog` will try and [partially decode](https://viem.sh/docs/contract/decodeEventLog#partial-decode) . const topics = decodeEventLog({ abi: wagmiAbi, strict: false, topics: [\ '0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0', \ '0x00000000000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266', \ '0x0000000000000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8'\ ] }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/decodeEventLog.md) Copy page for AI Ask AI... ⌘ I --- # encodeFunctionResult · Viem [Skip to content](https://viem.sh/docs/contract/encodeFunctionResult#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K encodeFunctionResult ==================== Encodes structured return data into ABI encoded data. It is the opposite of `[decodeFunctionResult](https://viem.sh/docs/contract/decodeFunctionResult) `. Install[](https://viem.sh/docs/contract/encodeFunctionResult#install) ---------------------------------------------------------------------- import { encodeFunctionResult } from 'viem'; Usage[](https://viem.sh/docs/contract/encodeFunctionResult#usage) ------------------------------------------------------------------ Given an ABI (`abi`) and a function (`functionName`), pass through the values (`values`) to encode: example.tsabi.ts import { encodeFunctionResult } from 'viem'; import { wagmiAbi } from './abi.ts' const data = encodeFunctionResult({ abi: wagmiAbi, functionName: 'ownerOf', result: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac', }); // '0x000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac' ### A more complex example[](https://viem.sh/docs/contract/encodeFunctionResult#a-more-complex-example) example.tsabi.ts import { decodeFunctionResult } from 'viem' const data = decodeFunctionResult({ abi: wagmiAbi, functionName: 'getInfo', result: { foo: { sender: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', x: 69420n, y: true }, sender: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', z: 69 } }) // 0x000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac0000000000000000000000000000000000000000000000000000000000010f2c0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac0000000000000000000000000000000000000000000000000000000000000045 ### Without `functionName`[](https://viem.sh/docs/contract/encodeFunctionResult#without-functionname) If your `abi` contains only one ABI item, you can omit the `functionName` (it becomes optional): import { encodeFunctionResult } from 'viem'; const abiItem = { inputs: [{ name: 'owner', type: 'address' }], name: 'balanceOf', outputs: [{ name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', } const data = encodeFunctionResult({ abi: wagmiAbi, functionName: 'ownerOf', result: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac', }); // '0x000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac' Return Value[](https://viem.sh/docs/contract/encodeFunctionResult#return-value) -------------------------------------------------------------------------------- The decoded data. Type is inferred from the ABI. Parameters[](https://viem.sh/docs/contract/encodeFunctionResult#parameters) ---------------------------------------------------------------------------- ### abi[](https://viem.sh/docs/contract/encodeFunctionResult#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const data = encodeFunctionResult({ abi: wagmiAbi, functionName: 'ownerOf', result: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac', }); ### functionName[](https://viem.sh/docs/contract/encodeFunctionResult#functionname) * **Type:** `string` The function to encode from the ABI. const data = encodeFunctionResult({ abi: wagmiAbi, functionName: 'ownerOf', result: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac', }); ### values[](https://viem.sh/docs/contract/encodeFunctionResult#values) * **Type**: `[Hex](https://viem.sh/docs/glossary/types#hex) ` Return values to encode. const data = encodeFunctionResult({ abi: wagmiAbi, functionName: 'ownerOf', result: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac', }); [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/encodeFunctionResult.md) Copy page for AI Ask AI... ⌘ I --- # signAuthorization · Viem [Skip to content](https://viem.sh/docs/eip7702/signAuthorization#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K signAuthorization ================= Signs an [EIP-7702 Authorization](https://eips.ethereum.org/EIPS/eip-7702) . The signed Authorization can be used in Transaction APIs like `[sendTransaction](https://viem.sh/docs/actions/wallet/sendTransaction#authorizationlist-optional) ` and `[writeContract](https://viem.sh/docs/contract/writeContract#authorizationlist-optional) ` to delegate an authorized Contract onto an Account. Usage[](https://viem.sh/docs/eip7702/signAuthorization#usage) -------------------------------------------------------------- A Contract can be authorized by supplying a `contractAddress`. By default, it will be signed over the Account's next available Nonce and the current Chain ID. You can also [explicitly set the `nonce` and `chainId`](https://viem.sh/docs/eip7702/signAuthorization#scoping) . example.tsclient.ts import { privateKeyToAccount } from 'viem/accounts' import { walletClient } from './client' const eoa = privateKeyToAccount('0x...') const authorization = await walletClient.signAuthorization({ account: eoa, contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) } const hash = await walletClient.sendTransaction({ authorizationList: [authorization], data: '0xdeadbeef', to: eoa.address, }) ### Explicit Scoping[](https://viem.sh/docs/eip7702/signAuthorization#explicit-scoping) We can explicitly sign over a provided `nonce` and/or `chainId` by supplying them as parameters: example.tsclient.ts import { walletClient } from './client' const eoa = privateKeyToAccount('0x...') const authorization = await walletClient.signAuthorization({ account: eoa, contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', chainId: 10, nonce: 420, }) } const hash = await walletClient.sendTransaction({ authorizationList: [authorization], data: '0xdeadbeef', to: eoa.address, }) Returns[](https://viem.sh/docs/eip7702/signAuthorization#returns) ------------------------------------------------------------------ `SignedAuthorization` A signed Authorization object. Parameters[](https://viem.sh/docs/eip7702/signAuthorization#parameters) ------------------------------------------------------------------------ ### account[](https://viem.sh/docs/eip7702/signAuthorization#account) * **Type:** `Account` Account to use for delegation. Accepts a [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . import { privateKeyToAccount } from 'viem/accounts' import { walletClient } from './client' const authorization = await walletClient.signAuthorization({ account: privateKeyToAccount('0x...'), contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2' }) ### chainId (optional)[](https://viem.sh/docs/eip7702/signAuthorization#chainid-optional) * **Type:** `Address` * **Default:** `client.chain.id` or Network chain ID The Chain ID to scope the Authorization to. import { privateKeyToAccount } from 'viem/accounts' import { walletClient } from './client' const authorization = await walletClient.signAuthorization({ account: privateKeyToAccount('0x...'), contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', chainId: 1, }) ### contractAddress[](https://viem.sh/docs/eip7702/signAuthorization#contractaddress) * **Type:** `Address` The target Contract to delegate to the Account. import { privateKeyToAccount } from 'viem/accounts' import { walletClient } from './client' const authorization = await walletClient.signAuthorization({ account: privateKeyToAccount('0x...'), contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2' }) ### executor (optional)[](https://viem.sh/docs/eip7702/signAuthorization#executor-optional) * **Type:** `'self' | undefined` Whether the EIP-7702 Transaction will be executed by the Account that signed the Authorization. If not specified, it will be assumed that the EIP-7702 Transaction will be executed by another Account (ie. a relayer Account). import { privateKeyToAccount } from 'viem/accounts' import { walletClient } from './client' const authorization = await walletClient.signAuthorization({ account: privateKeyToAccount('0x...'), contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', executor: 'self', }) ### nonce (optional)[](https://viem.sh/docs/eip7702/signAuthorization#nonce-optional) * **Type:** `Address` * **Default:** Account's next available nonce. The nonce to scope the Authorization to. import { privateKeyToAccount } from 'viem/accounts' import { walletClient } from './client' const authorization = await walletClient.signAuthorization({ account: privateKeyToAccount('0x...'), contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', nonce: 69, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/eip7702/signAuthorization.md) Copy page for AI Ask AI... ⌘ I --- # Migration Guide · Viem [Skip to content](https://viem.sh/docs/migration-guide#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Migration Guide =============== If you are coming from an earlier version of `viem`, you will need to make sure to update the following APIs listed below. 2.x.x Breaking changes[](https://viem.sh/docs/migration-guide#2xx-breaking-changes) ------------------------------------------------------------------------------------ The 2.x.x release includes very minor breaking changes to the Contract Instances API, entrypoints, chain modules, and miscellaneous actions + utilities listed below. Not ready to migrate? [Head to the 1.x.x docs.](https://v1.viem.sh/) ### Actions: Modified `getContract` Client API[](https://viem.sh/docs/migration-guide#actions-modified-getcontract-client-api) The `publicClient` and `walletClient` parameters of the `getContract` API has been removed in favour of `client` to support Client's that [extend](https://viem.sh/docs/clients/wallet#optional-extend-with-public-actions) (ie. [a Wallet Client extended with Public Actions](https://viem.sh/docs/clients/wallet#optional-extend-with-public-actions) ). [Read more.](https://viem.sh/docs/contract/getContract) import { getContract } from 'viem' import { publicClient, walletClient } from './client' const contract = getContract({ abi, address, publicClient, walletClient, client: { public: publicClient, wallet: walletClient, } }) ### Removed entrypoints[](https://viem.sh/docs/migration-guide#removed-entrypoints) The following entrypoints have been removed: * `viem/abi` * `viem/contract` * `viem/public` * `viem/test` * `viem/wallet` You can import the entrypoints directly from `viem`: import { encodeAbiParameters } from 'viem/abi' import { getContract } from 'viem/contract' import { getBlock } from 'viem/public' import { mine } from 'viem/test' import { sendTransaction } from 'viem/wallet' import { encodeAbiParameters, getContract, getBlock, mine, sendTransaction, } from 'viem' ### Moved chain-specific exports in `viem/chains/utils`[](https://viem.sh/docs/migration-guide#moved-chain-specific-exports-in-viemchainsutils) Chain-specific exports in `viem/chains/utils` have been moved to `viem/{celo|op-stack|zksync}`: import { parseTransactionCelo, parseTransaction serializeTransactionCelo, serializeTransaction // ... } from 'viem/chains/utils' } from 'viem/celo' import { // ... } from 'viem/chains/utils' } from 'viem/op-stack' import { parseTransactionZkSync, parseTransaction, serializeTransactionZkSync, serializeTransaction, // ... } from 'viem/chains/utils' } from 'viem/zksync' ### Actions: `getBlockNumber`[](https://viem.sh/docs/migration-guide#actions-getblocknumber) The `maxAge` parameter has been removed in favor of `cacheTime`. const blockNumber = await client.getBlockNumber({ maxAge: 84_600 cacheTime: 84_600 }) ### Actions: `OnLogFn` & `OnLogParameter` types[](https://viem.sh/docs/migration-guide#actions-onlogfn--onlogparameter-types) The `OnLogFn` & `OnLogParameter` types have been renamed. import { OnLogFn, WatchEventOnLogsFn, OnLogParameter, WatchEventOnLogsParameter, } from 'viem' ### Actions: `prepareRequest`[](https://viem.sh/docs/migration-guide#actions-preparerequest) The `prepareRequest` Action has been renamed to `prepareTransactionRequest` and moved to `viem/actions` entrypoint. import { prepareRequest, prepareTransactionRequest, } from 'viem' } from 'viem/actions' ### Actions: `SimulateContractParameters` & `SimulateContractReturnType` types[](https://viem.sh/docs/migration-guide#actions-simulatecontractparameters--simulatecontractreturntype-types) Note the following breaking generic slot changes: type SimulateContractParameters< TAbi, TFunctionName, TArgs, // Args added to Slot 2 TChain, TChainOverride, TAccountOverride, > type SimulateContractReturnType< TAbi, TFunctionName, TArgs, // Args added to Slot 2 TChain, TAccount, // Account added to Slot 4 TChainOverride, TAccountOverride, > ### Utilities: Removed `extractFunctionParts`, `extractFunctionName`, `extractFunctionParams`, `extractFunctionType`[](https://viem.sh/docs/migration-guide#utilities-removed-extractfunctionparts-extractfunctionname-extractfunctionparams-extractfunctiontype) The `extractFunctionParts`, `extractFunctionName`, `extractFunctionParams`, `extractFunctionType` utility functions have been removed. You can use the [`parseAbiItem` utility function from abitype](https://abitype.dev/api/human#parseabiitem-1) instead. ### Utilities: Renamed `bytesToBigint`[](https://viem.sh/docs/migration-guide#utilities-renamed-bytestobigint) The `bytesToBigint` utility function has been renamed to `bytesToBigInt`. import { bytesToBigint, bytesToBigInt, } from 'viem' ### Utilities: Renamed chain types[](https://viem.sh/docs/migration-guide#utilities-renamed-chain-types) The following chain types have been renamed: import { Formatter, ChainFormatter, Formatters, ChainFormatters, Serializers, ChainSerializers, ExtractFormatterExclude, ExtractChainFormatterExclude, ExtractFormatterParameters, ExtractChainFormatterParameters, ExtractFormatterReturnType, ExtractChainFormatterReturnType, } from 'viem' ### Utilities: `isAddress` & `getAddress` perform checksum validation[](https://viem.sh/docs/migration-guide#utilities-isaddress--getaddress-perform-checksum-validation) The `isAddress` utility function now performs checksum validation by default. To opt-out of this behavior, you can pass `strict: false` or lowercase the address. import { isAddress } from 'viem' isAddress('0xa5cc3c03994db5b0d9a5eEdD10Cabab0813678ac', { strict: false }) isAddress( '0xa5cc3c03994db5b0d9a5eEdD10Cabab0813678ac'.toLowerCase() ) 1.x.x Breaking changes[](https://viem.sh/docs/migration-guide#1xx-breaking-changes) ------------------------------------------------------------------------------------ The 1.x.x release only includes very minor changes to the behavior in event log decoding, and removes the redundant ethers.js Wallet Adapter. If you do not directly use these APIs, you do not need to update any of your code for this version. ### Removed `ethersWalletToAccount`[](https://viem.sh/docs/migration-guide#removed-etherswallettoaccount) The `ethersWalletToAccount` adapter has been removed. This adapter was introduced when viem did not have Private Key & HD Accounts. Since 0.2, viem provides all the utilities needed to create and import [Private Key](https://viem.sh/docs/accounts/local/privateKeyToAccount) & [HD Accounts](https://viem.sh/docs/accounts/local/mnemonicToAccount) . If you still need it, you can copy + paste the [old implementation](https://github.com/wevm/viem/blob/a9a71507032db896295fa1f3fa2dd6c2bdc85137/src/adapters/ethers.ts) . ### `logIndex` & `transactionIndex` on Logs[](https://viem.sh/docs/migration-guide#logindex--transactionindex-on-logs) `logIndex` & `transactionIndex` on `Log` now return a `number` instead of a `bigint`. const log: Log = { ... logIndex: 1n, logIndex: 1, transactionIndex: 1n, transactionIndex: 1, ... } ### Minor: `decodeEventLog` behavior change[](https://viem.sh/docs/migration-guide#minor-decodeeventlog-behavior-change) `decodeEventLog` no longer attempts to partially decode events. If the Log does not conform to the ABI (mismatch between the number of indexed/non-indexed arguments to topics/data), it will throw an error. For example, the following Log will throw an error as there is a mismatch in non-`indexed` arguments & `data` length. decodeEventLog({ abi: parseAbi(['event Transfer(address indexed, address, uint256)']), // `data` should be 64 bytes, but is only 32 bytes. data: '0x0000000000000000000000000000000000000000000000000000000000000001' topics: [\ '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',\ '0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266',\ ] }) Previously, the above would only decode the `indexed` arguments. If you would like to partially decode event logs (previous behavior), you can turn off `strict` mode: decodeEventLog({ abi: parseAbi(['event Transfer(address indexed, address, uint256)']), data: '0x0000000000000000000000000000000000000000000000000000000000000001' topics: [\ '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',\ '0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266',\ ], strict: false }) 0.3.x Breaking changes[](https://viem.sh/docs/migration-guide#03x-breaking-changes) ------------------------------------------------------------------------------------ The 0.3.x release only includes breaking changes around RPC errors. If you do not directly use the APIs listed below, you do not need to update any of your code for this version. ### Renamed `RequestError` to `RpcError`[](https://viem.sh/docs/migration-guide#renamed-requesterror-to-rpcerror) `RequestError` was renamed `RpcError` for clarity. import { RequestError } from 'viem' import { RpcError } from 'viem' throw new RequestError(new Error('An error occurred.')) throw new RpcError(new Error('An error occurred.')) ### Removed `RpcRequestError`[](https://viem.sh/docs/migration-guide#removed-rpcrequesterror) `RpcRequestError` was removed. Use `RpcError` instead. import { RpcRequestError } from 'viem' import { RpcError } from 'viem' throw new RpcRequestError(new Error('An error occurred.')) throw new RpcError(new Error('An error occurred.')) ### Renamed `RpcError` to `RpcRequestError`[](https://viem.sh/docs/migration-guide#renamed-rpcerror-to-rpcrequesterror) `RpcError` was renamed `RpcRequestError` for consistency. import { RpcError } from 'viem' import { RpcRequestError } from 'viem' const err = new RpcError({ const err = new RpcRequestError({ body: { foo: 'bar' }, error: { code: 420, message: 'Error' }, url: 'https://example-rpc.com', }) 0.2.x Breaking changes[](https://viem.sh/docs/migration-guide#02x-breaking-changes) ------------------------------------------------------------------------------------ ### `chain` is required for `sendTransaction`, `writeContract`, `deployContract`[](https://viem.sh/docs/migration-guide#chain-is-required-for-sendtransaction-writecontract-deploycontract) A chain is now required for the `sendTransaction`, `writeContract`, `deployContract` Actions. You can hoist the Chain on the Client: import { createWalletClient, custom, getAccount } from 'viem' import { mainnet } from 'viem/chains' export const walletClient = createWalletClient({ chain: mainnet, transport: custom(window.ethereum) }) const account = getAccount('0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266') const hash = await walletClient.sendTransaction({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) Alternatively, you can pass the Chain directly to the Action: import { createWalletClient, custom, getAccount } from 'viem' import { mainnet } from 'viem/chains' export const walletClient = createWalletClient({ chain: mainnet, transport: custom(window.ethereum) }) const account = getAccount('0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266') const hash = await walletClient.sendTransaction({ account, chain: mainnet, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) ### `recoverAddress`, `recoverMessageAddress`, `verifyMessage` are now async[](https://viem.sh/docs/migration-guide#recoveraddress-recovermessageaddress-verifymessage-are-now-async) The following functions are now `async` functions instead of synchronous functions: * `recoverAddress` * `recoverMessageAddress` * `verifyMessage` import { recoverMessageAddress } from 'viem' recoverMessageAddress({ message: 'hello world', signature: '0x...' }) await recoverMessageAddress({ message: 'hello world', signature: '0x...' }) ### `assertChain` removed from `sendTransaction`[](https://viem.sh/docs/migration-guide#assertchain-removed-from-sendtransaction) Removed `assertChain` argument on `sendTransaction`, `writeContract` & `deployContract`. If you wish to bypass the chain check (not recommended unless for testing purposes), you can pass `chain: null`. await walletClient.sendTransaction({ assertChain: false, chain: null, ... }) ### `getAccount` removed[](https://viem.sh/docs/migration-guide#getaccount-removed) Removed the `getAccount` function. #### For JSON-RPC Accounts, use the address itself.[](https://viem.sh/docs/migration-guide#for-json-rpc-accounts-use-the-address-itself) You can now pass the address directly to the `account` option. import { createWalletClient, custom } from 'viem' import { mainnet } from 'viem/chains' const address = '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2' const client = createWalletClient({ account: getAccount(address), account: address, chain: mainnet, transport: custom(window.ethereum) }) #### For Ethers Wallet Adapter, use `ethersWalletToAccount`.[](https://viem.sh/docs/migration-guide#for-ethers-wallet-adapter-use-etherswallettoaccount) If you were using the Ethers Wallet adapter, you can use the `ethersWalletToAccount` function. > Note: viem 0.2.0 now has a [Private Key](https://viem.sh/docs/accounts/local/privateKeyToAccount) > & [Mnemonic Account](https://viem.sh/docs/accounts/local/mnemonicToAccount) > implementation. You probably do not need this adapter anymore. This adapter may be removed in a future version. import { createWalletClient, custom } from 'viem' import { mainnet } from 'viem/chains' import { getAccount } from 'viem/ethers' import { ethersWalletToAccount } from 'viem/ethers' import { Wallet } from 'ethers' const account = getAccount(new Wallet('0x...')) const account = ethersWalletToAccount(new Wallet('0x...')) const client = createWalletClient({ account, chain: mainnet, transport: custom(window.ethereum) }) #### For Local Accounts, use `toAccount`.[](https://viem.sh/docs/migration-guide#for-local-accounts-use-toaccount) If you are using a custom signing implementation, you can use the `toAccount` function. import { createWalletClient, http, getAccount } from 'viem' import { createWalletClient, http } from 'viem' import { toAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' import { getAddress, signMessage, signTransaction } from './sign-utils' const privateKey = '0x...' const account = getAccount({ const account = toAccount({ address: getAddress(privateKey), signMessage(message) { return signMessage(message, privateKey) }, signTransaction(transaction) { return signTransaction(transaction, privateKey) }, signTypedData(typedData) { return signTypedData(typedData, privateKey) } }) const client = createWalletClient({ account, chain: mainnet, transport: http() }) ### `data` renamed in `signMessage`[](https://viem.sh/docs/migration-guide#data-renamed-in-signmessage) Renamed the `data` parameter in `signMessage` to `message`. walletClient.signMessage({ data: 'hello world', message: 'hello world', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/migration-guide.mdx) Copy page for AI Ask AI... ⌘ I --- # Contract Instances · Viem [Skip to content](https://viem.sh/docs/contract/getContract#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Contract Instances ================== A Contract Instance is a type-safe interface for performing contract-related actions with a specific ABI and address, created by the `getContract` function. Import[](https://viem.sh/docs/contract/getContract#import) ----------------------------------------------------------- import { getContract } from 'viem' Usage[](https://viem.sh/docs/contract/getContract#usage) --------------------------------------------------------- You can create a Contract Instance with the `getContract` function by passing in a [ABI](https://viem.sh/docs/glossary/types#abi) , address, and [Public](https://viem.sh/docs/clients/public) and/or [Wallet Client](https://viem.sh/docs/clients/wallet) . Once created, you can call contract methods, fetch for events, listen to events, etc. example.tsclient.tsabi.ts import { getContract } from 'viem' import { wagmiAbi } from './abi' import { publicClient, walletClient } from './client' // 1. Create contract instance const contract = getContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, // 1a. Insert a single client client: publicClient, // 1b. Or public and/or wallet clients client: { public: publicClient, wallet: walletClient } }) // 2. Call contract methods, fetch events, listen to events, etc. const result = await contract.read.totalSupply() const logs = await contract.getEvents.Transfer() const unwatch = contract.watchEvent.Transfer( { from: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e' }, { onLogs(logs) { console.log(logs) } } ) Using Contract Instances can make it easier to work with contracts if you don't want to pass the `abi` and `address` properties every time you perform contract actions, e.g. `[readContract](https://viem.sh/docs/contract/readContract) `, `[writeContract](https://viem.sh/docs/contract/writeContract) `, `[estimateContractGas](https://viem.sh/docs/contract/estimateContractGas) `, etc. Switch between the tabs below to see the difference between standalone Contract Actions and Contract Instance Actions: contract-instance.tscontract-actions.ts import { getContract } from 'viem' import { wagmiAbi } from './abi' import { publicClient, walletClient } from './client' const contract = getContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, client: { public: publicClient, wallet: walletClient, } }) const balance = await contract.read.balanceOf([\ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ ]) const hash = await contract.write.mint([69420]) const logs = await contract.getEvents.Transfer() const unwatch = contract.watchEvent.Transfer( { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' }, { onLogs: logs => console.log(logs) } ) Return Value[](https://viem.sh/docs/contract/getContract#return-value) ----------------------------------------------------------------------- Contract instance object. Type is inferred. Depending on if you create a contract instance with a Public Client, Wallet Client, or both, the methods available on the contract instance will vary. #### With Public Client[](https://viem.sh/docs/contract/getContract#with-public-client) If you pass in a `[publicClient](https://viem.sh/docs/clients/public) `, the following methods are available: * `[createEventFilter](https://viem.sh/docs/contract/createContractEventFilter) ` * `[estimateGas](https://viem.sh/docs/contract/estimateContractGas) ` * `[getEvents](https://viem.sh/docs/contract/getContractEvents) ` * `[read](https://viem.sh/docs/contract/readContract) ` * `[simulate](https://viem.sh/docs/contract/simulateContract) ` * `[watchEvent](https://viem.sh/docs/contract/watchContractEvent) ` #### With Wallet Client[](https://viem.sh/docs/contract/getContract#with-wallet-client) If you pass in a `[walletClient](https://viem.sh/docs/clients/wallet) `, the following methods are available: * `[estimateGas](https://viem.sh/docs/contract/estimateContractGas) ` * `[write](https://viem.sh/docs/contract/writeContract) ` #### Calling methods[](https://viem.sh/docs/contract/getContract#calling-methods) If you are using [TypeScript](https://viem.sh/docs/typescript) with viem, your editor will be able to provide autocomplete suggestions for the methods available on the contract instance, as well as the arguments and other options for each method. In general, contract instance methods follow the following format: // function contract.(estimateGas|read|simulate|write).(functionName)(args, options) // event contract.(createEventFilter|getEvents|watchEvent).(eventName)(args, options) If the contract function/event you are using does not accept arguments (e.g. function has no inputs, event has no indexed inputs), then you can omit the `args` parameter so `options` is the first and only parameter. Parameters[](https://viem.sh/docs/contract/getContract#parameters) ------------------------------------------------------------------- ### address[](https://viem.sh/docs/contract/getContract#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The contract address. const contract = getContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, client: publicClient }) ### abi[](https://viem.sh/docs/contract/getContract#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const contract = getContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, client: publicClient }) ### client[](https://viem.sh/docs/contract/getContract#client) * **Type:** `[Client | { public: Client; wallet: Client }](https://viem.sh/docs/clients/public) ` The Client used for performing [contract actions](https://viem.sh/docs/contract/getContract#return-value) . const contract = getContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, client: publicClient, }) You can also pass in multiple clients (ie. a Wallet Client and a Public Client): const contract = getContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, client: { public: publicClient, wallet: walletClient }, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/getContract.md) Copy page for AI Ask AI... ⌘ I --- # call · Viem [Skip to content](https://viem.sh/docs/actions/public/call#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K call ==== An Action for executing a new message call. Executes a new message call immediately without submitting a transaction to the network. Usage[](https://viem.sh/docs/actions/public/call#usage) -------------------------------------------------------- example.tsconfig.ts import { account, publicClient } from './config' const data = await publicClient.call({ account, data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### Deployless Calls[](https://viem.sh/docs/actions/public/call#deployless-calls) It is possible to call a function on a contract that has not been deployed yet. For instance, we may want to call a function on an [ERC-4337 Smart Account](https://eips.ethereum.org/EIPS/eip-4337) contract which has not been deployed. Viem offers two ways of performing a Deployless Call, via: * [Bytecode](https://viem.sh/docs/actions/public/call#bytecode) * a [Deploy Factory](https://viem.sh/docs/actions/public/call#deploy-factory) : "temporarily deploys" a contract with a provided [Deploy Factory](https://docs.alchemy.com/docs/create2-an-alternative-to-deriving-contract-addresses#create2-contract-factory) , and calls the function on the deployed contract. #### Bytecode[](https://viem.sh/docs/actions/public/call#bytecode) The example below demonstrates how we can utilize a Deployless Call **via Bytecode** to call the `name` function on the [Wagmi Example ERC721 contract](https://etherscan.io/address/0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2#code) which has not been deployed: example.tsconfig.ts import { encodeFunctionData, parseAbi } from 'viem' import { publicClient } from './config' const data = await publicClient.call({ // Bytecode of the contract. Accessible here: https://etherscan.io/address/0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2#code code: '0x...', // Function to call on the contract. data: encodeFunctionData({ abi: parseAbi(['function name() view returns (string)']), functionName: 'name' }), }) #### Deploy Factory[](https://viem.sh/docs/actions/public/call#deploy-factory) The example below demonstrates how we can utilize a Deployless Call **via a [Deploy Factory](https://docs.alchemy.com/docs/create2-an-alternative-to-deriving-contract-addresses#create2-contract-factory) ** to call the `entryPoint` function on an [ERC-4337 Smart Account](https://eips.ethereum.org/EIPS/eip-4337) which has not been deployed: example.tsconfig.ts import { encodeFunctionData, parseAbi } from 'viem' import { owner, publicClient } from './config' const data = await publicClient.call({ // Address of the contract deployer (e.g. Smart Account Factory). factory: '0xE8Df82fA4E10e6A12a9Dab552bceA2acd26De9bb', // Function to execute on the factory to deploy the contract. factoryData: encodeFunctionData({ abi: parseAbi(['function createAccount(address owner, uint256 salt)']), functionName: 'createAccount', args: [owner, 0n], }), // Function to call on the contract (e.g. Smart Account contract). data: encodeFunctionData({ abi: parseAbi(['function entryPoint() view returns (address)']), functionName: 'entryPoint' }), // Address of the contract. to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) Returns[](https://viem.sh/docs/actions/public/call#returns) ------------------------------------------------------------ `0x${string}` The call data. Parameters[](https://viem.sh/docs/actions/public/call#parameters) ------------------------------------------------------------------ ### account[](https://viem.sh/docs/actions/public/call#account) * **Type:** `Account | Address` The Account to call from. Accepts a [JSON-RPC Account](https://viem.sh/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . const data = await publicClient.call({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### data[](https://viem.sh/docs/actions/public/call#data) * **Type:** `0x${string}` A contract hashed method call with encoded args. const data = await publicClient.call({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### to[](https://viem.sh/docs/actions/public/call#to) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The contract address or recipient. const data = await publicClient.call({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### accessList (optional)[](https://viem.sh/docs/actions/public/call#accesslist-optional) * **Type:** `[AccessList](https://viem.sh/docs/glossary/types#accesslist) ` The access list. const data = await publicClient.call({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', accessList: [ \ {\ address: '0x1',\ storageKeys: ['0x1'],\ },\ ], data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### blockNumber (optional)[](https://viem.sh/docs/actions/public/call#blocknumber-optional) * **Type:** `number` The block number to perform the call against. const data = await publicClient.call({ blockNumber: 15121123n, account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### blockTag (optional)[](https://viem.sh/docs/actions/public/call#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` The block tag to perform the call against. const data = await publicClient.call({ blockTag: 'safe', account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### code (optional)[](https://viem.sh/docs/actions/public/call#code-optional) * **Type:** Bytecode to perform the call against. const data = await publicClient.call({ code: '0x...', data: '0xdeadbeef', }) ### factory (optional)[](https://viem.sh/docs/actions/public/call#factory-optional) * **Type:** Contract deployment factory address (ie. Create2 factory, Smart Account factory, etc). const data = await publicClient.call({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', factory: '0x0000000000ffe8b47b3e2130213b802212439497', factoryData: '0xdeadbeef', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### factoryData (optional)[](https://viem.sh/docs/actions/public/call#factorydata-optional) * **Type:** Calldata to execute on the factory to deploy the contract. const data = await publicClient.call({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', factory: '0x0000000000ffe8b47b3e2130213b802212439497', factoryData: '0xdeadbeef', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### gas (optional)[](https://viem.sh/docs/actions/public/call#gas-optional) * **Type:** `bigint` The gas provided for transaction execution. const data = await publicClient.call({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', gas: 1_000_000n, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### gasPrice (optional)[](https://viem.sh/docs/actions/public/call#gasprice-optional) * **Type:** `bigint` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction) . import { parseGwei } from 'viem' const data = await publicClient.call({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', gasPrice: parseGwei('20'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### maxFeePerGas (optional)[](https://viem.sh/docs/actions/public/call#maxfeepergas-optional) * **Type:** `bigint` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) . import { parseGwei } from 'viem' const data = await publicClient.call({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', maxFeePerGas: parseGwei('20'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### maxPriorityFeePerGas (optional)[](https://viem.sh/docs/actions/public/call#maxpriorityfeepergas-optional) * **Type:** `bigint` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) . import { parseGwei } from 'viem' const data = await publicClient.call({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### nonce (optional)[](https://viem.sh/docs/actions/public/call#nonce-optional) * **Type:** `bigint` Unique number identifying this transaction. const data = await publicClient.call({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', nonce: 420, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### stateOverride (optional)[](https://viem.sh/docs/actions/public/call#stateoverride-optional) * **Type:** `[StateOverride](https://viem.sh/docs/glossary/types#stateoverride) ` The state override set is an optional address-to-state mapping, where each entry specifies some state to be ephemerally overridden prior to executing the call. const data = await publicClient.call({ account, data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', stateOverride: [ \ { \ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ balance: parseEther('1'), \ stateDiff: [ \ { \ slot: '0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0', \ value: '0x00000000000000000000000000000000000000000000000000000000000001a4', \ }, \ ], \ } \ ], }) ### value (optional)[](https://viem.sh/docs/actions/public/call#value-optional) * **Type:** `bigint` Value (in wei) sent with this transaction. import { parseEther } from 'viem' const data = await publicClient.call({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) JSON-RPC Methods[](https://viem.sh/docs/actions/public/call#json-rpc-methods) ------------------------------------------------------------------------------ `[eth_call](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_call) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/call.md) Copy page for AI Ask AI... ⌘ I --- # getLogs · Viem [Skip to content](https://viem.sh/docs/actions/public/getLogs#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getLogs ======= Returns a list of **event** logs matching the provided parameters. Usage[](https://viem.sh/docs/actions/public/getLogs#usage) ----------------------------------------------------------- By default, `getLogs` returns all events. In practice, you must use scoping to filter for specific events. example.tsclient.ts import { publicClient } from './client' const logs = await publicClient.getLogs() Output: [{ ... }, { ... }, { ... }] Scoping[](https://viem.sh/docs/actions/public/getLogs#scoping) --------------------------------------------------------------- You can also scope to a set of given attributes. example.tsclient.ts import { parseAbiItem } from 'viem' import { publicClient } from './client' const logs = await publicClient.getLogs({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256)'), args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' }, fromBlock: 16330000n, toBlock: 16330050n }) By default, `event` accepts the `[AbiEvent](https://viem.sh/docs/glossary/types#abievent) ` type: example.tsclient.ts import { publicClient } from './client' const logs = await publicClient.getLogs(publicClient, { address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: { name: 'Transfer', inputs: [\ { type: 'address', indexed: true, name: 'from' },\ { type: 'address', indexed: true, name: 'to' },\ { type: 'uint256', indexed: false, name: 'value' }\ ] }, args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' }, fromBlock: 16330000n, toBlock: 16330050n }) ### Address[](https://viem.sh/docs/actions/public/getLogs#address) Logs can be scoped to an **address**: example.tsclient.ts import { publicClient } from './client' const logs = await publicClient.getLogs({ address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2' }) ### Event[](https://viem.sh/docs/actions/public/getLogs#event) Logs can be scoped to an **event**. The `event` argument takes in an event in ABI format – we have a [`parseAbiItem` utility](https://viem.sh/docs/abi/parseAbiItem) that you can use to convert from a human-readable event signature → ABI. example.tsclient.ts import { parseAbiItem } from 'viem' import { publicClient } from './client' const logs = await publicClient.getLogs({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), }) ### Arguments[](https://viem.sh/docs/actions/public/getLogs#arguments) Logs can be scoped to given **_indexed_ arguments**: import { parseAbiItem } from 'viem' const logs = await publicClient.getLogs({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' } }) Only indexed arguments in `event` are candidates for `args`. An argument can also be an array to indicate that other values can exist in the position: import { parseAbiItem } from 'viem' const logs = await publicClient.getLogs({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), args: { // '0xd8da...' OR '0xa5cc...' OR '0xa152...' from: [\ '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', \ '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac',\ '0xa152f8bb749c55e9943a3a0a3111d18ee2b3f94e',\ ], } }) ### Block Range[](https://viem.sh/docs/actions/public/getLogs#block-range) Logs can be scoped to a **block range**: import { parseAbiItem } from 'viem' const logs = await publicClient.getLogs({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), fromBlock: 16330000n, toBlock: 16330050n }) ### Multiple Events[](https://viem.sh/docs/actions/public/getLogs#multiple-events) Logs can be scoped to **multiple events**: import { parseAbi } from 'viem' const logs = await publicClient.getLogs({ events: parseAbi([ \ 'event Approval(address indexed owner, address indexed sender, uint256 value)',\ 'event Transfer(address indexed from, address indexed to, uint256 value)',\ ]), }) Note: Logs scoped to multiple events cannot be also scoped with [indexed arguments](https://viem.sh/docs/actions/public/getLogs#arguments) (`args`). ### Strict Mode[](https://viem.sh/docs/actions/public/getLogs#strict-mode) By default, `getLogs` will include logs that [do not conform](https://viem.sh/docs/glossary/terms#non-conforming-log) to the indexed & non-indexed arguments on the `event`. viem will not return a value for arguments that do not conform to the ABI, thus, some arguments on `args` may be undefined. import { parseAbiItem } from 'viem' const logs = await publicClient.getLogs({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)') }) logs[0].args You can turn on `strict` mode to only return logs that conform to the indexed & non-indexed arguments on the `event`, meaning that `args` will always be defined. The trade-off is that non-conforming logs will be filtered out. import { parseAbiItem } from 'viem' const logs = await publicClient.getLogs({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), strict: true }) logs[0].args Returns[](https://viem.sh/docs/actions/public/getLogs#returns) --------------------------------------------------------------- `[Log[]](https://viem.sh/docs/glossary/types#log) ` A list of event logs. Parameters[](https://viem.sh/docs/actions/public/getLogs#parameters) --------------------------------------------------------------------- ### address[](https://viem.sh/docs/actions/public/getLogs#address-1) * **Type:** `[Address | Address[]](https://viem.sh/docs/glossary/types#address) ` A contract address or a list of contract addresses. Only logs originating from the contract(s) will be included in the result. const logs = await publicClient.getLogs({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', }) ### event[](https://viem.sh/docs/actions/public/getLogs#event-1) * **Type:** `[AbiEvent](https://viem.sh/docs/glossary/types#abievent) ` The event in ABI format. A [`parseAbiItem` utility](https://viem.sh/docs/abi/parseAbiItem) is exported from viem that converts from a human-readable event signature → ABI. import { parseAbiItem } from 'viem' const logs = await publicClient.getLogs({ event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), }) ### args[](https://viem.sh/docs/actions/public/getLogs#args) * **Type:** Inferred. A list of _indexed_ event arguments. import { parseAbiItem } from 'viem' const logs = await publicClient.getLogs({ event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'), args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' }, }) ### fromBlock[](https://viem.sh/docs/actions/public/getLogs#fromblock) * **Type:** `bigint | 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` Block to start including logs from. Mutually exclusive with `blockHash`. const filter = await publicClient.createEventFilter({ fromBlock: 69420n }) ### toBlock[](https://viem.sh/docs/actions/public/getLogs#toblock) * **Type:** `bigint | 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` Block to stop including logs from. Mutually exclusive with `blockHash`. const filter = await publicClient.createEventFilter({ toBlock: 70120n }) ### blockHash[](https://viem.sh/docs/actions/public/getLogs#blockhash) * **Type:** `'0x${string}'` Block hash to include logs from. Mutually exclusive with `fromBlock`/`toBlock`. const logs = await publicClient.getLogs({ blockHash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d' }) Live Example[](https://viem.sh/docs/actions/public/getLogs#live-example) ------------------------------------------------------------------------- Check out the usage of `getLogs` in the live [Event Logs Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/logs_event-logs) below. JSON-RPC Method[](https://viem.sh/docs/actions/public/getLogs#json-rpc-method) ------------------------------------------------------------------------------- `[eth_getLogs](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/getLogs.md) Copy page for AI Ask AI... ⌘ I --- # createContractEventFilter · Viem [Skip to content](https://viem.sh/docs/contract/createContractEventFilter#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K createContractEventFilter ========================= Creates a Filter to retrieve contract event logs. Creates a Filter to retrieve event logs that can be used with `[getFilterChanges](https://viem.sh/docs/actions/public/getFilterChanges) ` or `[getFilterLogs](https://viem.sh/docs/actions/public/getFilterLogs) `. Usage[](https://viem.sh/docs/contract/createContractEventFilter#usage) ----------------------------------------------------------------------- By default, an Event Filter with an ABI (`abi`) will retrieve events defined on the ABI. example.tsabi.tsclient.ts import { publicClient } from './client' import { wagmiAbi } from './abi' const filter = await publicClient.createContractEventFilter({ abi: wagmiAbi }) /** * { * abi: [...], * id: '0x345a6572337856574a76364e457a4366', * type: 'event' * } */ Scoping[](https://viem.sh/docs/contract/createContractEventFilter#scoping) --------------------------------------------------------------------------- You can also scope a Filter to a set of given attributes (listed below). ### Address[](https://viem.sh/docs/contract/createContractEventFilter#address) A Filter can be scoped to an **address**: const filter = await publicClient.createContractEventFilter({ abi: wagmiAbi, address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2' }) ### Event[](https://viem.sh/docs/contract/createContractEventFilter#event) A Filter can be scoped to an **event**: const filter = await publicClient.createContractEventFilter({ abi: wagmiAbi, address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2', eventName: 'Transfer' }) ### Arguments[](https://viem.sh/docs/contract/createContractEventFilter#arguments) A Filter can be scoped to given **_indexed_ arguments**: const filter = await publicClient.createContractEventFilter({ abi: wagmiAbi, address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2', eventName: 'Transfer', args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' } }) Only indexed arguments in `event` are candidates for `args`. A Filter Argument can also be an array to indicate that other values can exist in the position: const filter = await publicClient.createContractEventFilter({ abi: wagmiAbi, address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2', eventName: 'Transfer', args: { // '0xd8da...' OR '0xa5cc...' OR '0xa152...' from: [\ '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', \ '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac',\ '0xa152f8bb749c55e9943a3a0a3111d18ee2b3f94e',\ ], } }) ### Block Range[](https://viem.sh/docs/contract/createContractEventFilter#block-range) A Filter can be scoped to a **block range**: const filter = await publicClient.createContractEventFilter({ abi: wagmiAbi, address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2', eventName: 'Transfer', fromBlock: 16330000n, toBlock: 16330050n }) ### Strict Mode[](https://viem.sh/docs/contract/createContractEventFilter#strict-mode) By default, `createContractEventFilter` will include logs that [do not conform](https://viem.sh/docs/glossary/terms#non-conforming-log) to the indexed & non-indexed arguments on the `event`. viem will not return a value for arguments that do not conform to the ABI, thus, some arguments on `args` may be undefined. const filter = await publicClient.createContractEventFilter({ eventName: 'Transfer', }) const logs = await publicClient.getFilterLogs({ filter }) logs[0].args // ^? { address?: Address, to?: Address, value?: bigint } You can turn on `strict` mode to only return logs that conform to the indexed & non-indexed arguments on the `event`, meaning that `args` will always be defined. The trade-off is that non-conforming logs will be filtered out. const filter = await publicClient.createContractEventFilter({ eventName: 'Transfer', strict: true }) const logs = await publicClient.getFilterLogs({ filter }) logs[0].args // ^? { address: Address, to: Address, value: bigint } Returns[](https://viem.sh/docs/contract/createContractEventFilter#returns) --------------------------------------------------------------------------- `[Filter](https://viem.sh/docs/glossary/types#filter) ` Parameters[](https://viem.sh/docs/contract/createContractEventFilter#parameters) --------------------------------------------------------------------------------- ### abi[](https://viem.sh/docs/contract/createContractEventFilter#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const filter = await publicClient.createContractEventFilter({ abi: wagmiAbi, }) ### address (optional)[](https://viem.sh/docs/contract/createContractEventFilter#address-optional) * **Type:** `Address | Address[]` The contract address or a list of addresses from which Logs should originate. If no addresses are provided, then it will query all events matching the event signatures on the ABI. const filter = await publicClient.createContractEventFilter({ abi: wagmiAbi, address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2' }) ### eventName (optional)[](https://viem.sh/docs/contract/createContractEventFilter#eventname-optional) * **Type:** `string` The event name. const filter = await publicClient.createContractEventFilter({ abi: wagmiAbi, eventName: 'Transfer' }) ### args (optional)[](https://viem.sh/docs/contract/createContractEventFilter#args-optional) * **Type:** Inferred. A list of _indexed_ event arguments. const filter = await publicClient.createContractEventFilter({ abi: wagmiAbi, eventName: 'Transfer', args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' } }) ### fromBlock (optional)[](https://viem.sh/docs/contract/createContractEventFilter#fromblock-optional) * **Type:** `bigint` Block to start querying/listening from. const filter = await publicClient.createContractEventFilter({ abi: wagmiAbi, fromBlock: 69420n }) ### toBlock (optional)[](https://viem.sh/docs/contract/createContractEventFilter#toblock-optional) * **Type:** `bigint` Block to query/listen until. const filter = await publicClient.createContractEventFilter({ abi: wagmiAbi, toBlock: 70120n }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/createContractEventFilter.md) Copy page for AI Ask AI... ⌘ I --- # multicall · Viem [Skip to content](https://viem.sh/docs/contract/multicall#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K multicall ========= Batches up multiple functions on a contract in a single call. Similar to `[readContract](https://viem.sh/docs/contract/readContract) `, but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall) . Usage[](https://viem.sh/docs/contract/multicall#usage) ------------------------------------------------------- example.tsabi.tsclient.ts import { publicClient } from './client' import { wagmiAbi } from './abi' const wagmiContract = { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi } as const const results = await publicClient.multicall({ contracts: [\ {\ ...wagmiContract,\ functionName: 'totalSupply',\ },\ {\ ...wagmiContract,\ functionName: 'ownerOf',\ args: [69420n]\ },\ {\ ...wagmiContract,\ functionName: 'mint'\ }\ ] }) /** * [\ * { result: 424122n, status: 'success' },\ * { result: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b', status: 'success' },\ * { error: [ContractFunctionExecutionError: ...], status: 'failure' }\ * ] */ Return Value[](https://viem.sh/docs/contract/multicall#return-value) --------------------------------------------------------------------- `({ data: , status: 'success' } | { error: string, status: 'reverted' })[]` An array of results with accompanying status. Additionally, when `[allowFailure](https://viem.sh/docs/contract/multicall#allowfailure-optional) ` is set to `false`, it directly returns an array of inferred data: `()[]` Parameters[](https://viem.sh/docs/contract/multicall#parameters) ----------------------------------------------------------------- ### contracts.address[](https://viem.sh/docs/contract/multicall#contractsaddress) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The contract address. const results = await publicClient.multicall({ contracts: [\ {\ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', \ abi: wagmiAbi,\ functionName: 'totalSupply',\ },\ ...\ ] }) ### contracts.abi[](https://viem.sh/docs/contract/multicall#contractsabi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract ABI. const results = await publicClient.multicall({ contracts: [\ {\ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi: wagmiAbi, \ functionName: 'totalSupply',\ },\ ...\ ] }) ### contracts.functionName[](https://viem.sh/docs/contract/multicall#contractsfunctionname) * **Type**: `string` The function name to call. const results = await publicClient.multicall({ contracts: [\ {\ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi: wagmiAbi,\ functionName: 'totalSupply', \ },\ ...\ ] }) ### contracts.args (optional)[](https://viem.sh/docs/contract/multicall#contractsargs-optional) * **Type:** Inferred from ABI. Arguments to pass to function call. const results = await publicClient.multicall({ contracts: [\ {\ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi: wagmiAbi,\ functionName: 'balanceOf',\ args: ['0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b'] \ },\ ...\ ] }) ### account (optional)[](https://viem.sh/docs/contract/multicall#account-optional) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The account to perform the multicall against. const results = await publicClient.multicall({ account: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', contracts: [\ ...\ ], }) ### allowFailure (optional)[](https://viem.sh/docs/contract/multicall#allowfailure-optional) * **Type:** `boolean` * **Default:** `true` Whether or not the `multicall` function should throw if a call reverts. If set to `true` (default), and a call reverts, then `multicall` will fail silently and its error will be logged in the `results` array. const results = await publicClient.multicall({ contracts: [\ {\ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi: wagmiAbi,\ functionName: 'totalSupply',\ },\ ...\ ], allowFailure: false }) ### batchSize (optional)[](https://viem.sh/docs/contract/multicall#batchsize-optional) * **Type:** `number` * **Default:** `[client.batch.multicall.batchSize](https://viem.sh/docs/clients/public#batch-multicall-batchsize-optional) ` (if set) or `1024` The maximum size (in bytes) for each calldata chunk. Set to `0` to disable the size limit. > Note: Some RPC Providers limit the amount of calldata (`data`) that can be sent in a single `eth_call` request. It is best to check with your RPC Provider to see if there are any calldata size limits to `eth_call` requests. const results = await publicClient.multicall({ contracts: [\ {\ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi: wagmiAbi,\ functionName: 'totalSupply',\ },\ ...\ ], batchSize: 4096 // 4kB }) ### blockNumber (optional)[](https://viem.sh/docs/contract/multicall#blocknumber-optional) * **Type:** `number` The block number to perform the read against. const results = await publicClient.multicall({ contracts: [\ {\ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi: wagmiAbi,\ functionName: 'totalSupply',\ },\ ...\ ], blockNumber: 15121123n, }) ### deployless (optional)[](https://viem.sh/docs/contract/multicall#deployless-optional) * **Type:** `boolean` * **Default:** `false` Enable deployless multicall. const results = await publicClient.multicall({ contracts: [\ {\ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi: wagmiAbi,\ functionName: 'totalSupply',\ },\ ...\ ], deployless: true }) ### multicallAddress (optional)[](https://viem.sh/docs/contract/multicall#multicalladdress-optional) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` * **Default:** `client.chain.contracts.multicall3.address` Address of Multicall Contract. const results = await publicClient.multicall({ contracts: [\ {\ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi: wagmiAbi,\ functionName: 'totalSupply',\ },\ ...\ ], multicallAddress: '0xca11bde05977b3631167028862be2a173976ca11' }) ### stateOverride (optional)[](https://viem.sh/docs/contract/multicall#stateoverride-optional) * **Type:** `[StateOverride](https://viem.sh/docs/glossary/types#stateoverride) ` The state override set is an optional address-to-state mapping, where each entry specifies some state to be ephemerally overridden prior to executing the call. const data = await publicClient.multicall({ contracts: [\ {\ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi: wagmiAbi,\ functionName: 'totalSupply',\ },\ ...\ ], stateOverride: [ \ { \ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ balance: parseEther('1'), \ stateDiff: [ \ { \ slot: '0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0', \ value: '0x00000000000000000000000000000000000000000000000000000000000001a4', \ }, \ ], \ } \ ], }) Live Example[](https://viem.sh/docs/contract/multicall#live-example) --------------------------------------------------------------------- Check out the usage of `multicall` in the live [Multicall Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_multicall) below. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/multicall.md) Copy page for AI Ask AI... ⌘ I --- # watchContractEvent · Viem [Skip to content](https://viem.sh/docs/contract/watchContractEvent#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K watchContractEvent ================== Watches and returns emitted contract event logs. This Action will batch up all the event logs found within the `[pollingInterval](https://viem.sh/docs/contract/watchContractEvent#pollinginterval-optional) `, and invoke them via `[onLogs](https://viem.sh/docs/contract/watchContractEvent#onlogs) `. `watchContractEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (ie. `eth_newFilter`), then `watchContractEvent` will fall back to using `[getLogs](https://viem.sh/docs/actions/public/getLogs) ` instead. Usage[](https://viem.sh/docs/contract/watchContractEvent#usage) ---------------------------------------------------------------- example.tsclient.ts import { publicClient } from './client' import { wagmiAbi } from './abi' const unwatch = publicClient.watchContractEvent({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, onLogs: logs => console.log(logs) }) // > [{ ... }, { ... }, { ... }] // > [{ ... }, { ... }] // > [{ ... }, { ... }, { ... }, { ... }] ### Scoping to an Event Name[](https://viem.sh/docs/contract/watchContractEvent#scoping-to-an-event-name) You can scope to an event on the given ABI. example.tsabi.tsclient.ts import { publicClient } from './client' import { wagmiAbi } from './abi' const unwatch = publicClient.watchContractEvent({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, eventName: 'Transfer', onLogs: logs => console.log(logs) }) // > [{ ... }, { ... }, { ... }] // > [{ ... }, { ... }] // > [{ ... }, { ... }, { ... }, { ... }] ### Scoping to Event Arguments[](https://viem.sh/docs/contract/watchContractEvent#scoping-to-event-arguments) You can scope to given **indexed event arguments**. In the example below, we want to filter out `Transfer`s that were sent by the address `"0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b"`. > Only **`indexed`** arguments on the event ABI are candidates for `args` (see `abi.ts`). example.tsabi.tsclient.ts import { publicClient } from './client' import { wagmiAbi } from './abi' const unwatch = publicClient.watchContractEvent({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, eventName: 'Transfer', args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' }, onLogs: logs => console.log(logs) }) // > [{ ... }, { ... }, { ... }] // > [{ ... }, { ... }] // > [{ ... }, { ... }, { ... }, { ... }] Returns[](https://viem.sh/docs/contract/watchContractEvent#returns) -------------------------------------------------------------------- `UnwatchFn` A function that can be invoked to stop watching for new event logs. Arguments[](https://viem.sh/docs/contract/watchContractEvent#arguments) ------------------------------------------------------------------------ ### abi[](https://viem.sh/docs/contract/watchContractEvent#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const unwatch = publicClient.watchContractEvent({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, onLogs: logs => console.log(logs) }) ### onLogs[](https://viem.sh/docs/contract/watchContractEvent#onlogs) * **Type:** `(Log[]) => void` The new event logs. const unwatch = publicClient.watchContractEvent({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, onLogs: logs => console.log(logs) }) ### address (optional)[](https://viem.sh/docs/contract/watchContractEvent#address-optional) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The contract address. If no address is provided, then it will emit all events matching the event signatures on the ABI. const unwatch = publicClient.watchContractEvent({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, onLogs: logs => console.log(logs) }) ### args (optional)[](https://viem.sh/docs/contract/watchContractEvent#args-optional) * **Type:** Inferred from ABI. Event arguments to filter logs. const unwatch = publicClient.watchContractEvent({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, eventName: 'Transfer', args: ['0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b'], onLogs: logs => console.log(logs) }) ### eventName (optional)[](https://viem.sh/docs/contract/watchContractEvent#eventname-optional) * **Type:** `string` An event name to filter logs. const unwatch = publicClient.watchContractEvent({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, eventName: 'Transfer', onLogs: logs => console.log(logs) }) ### batch (optional)[](https://viem.sh/docs/contract/watchContractEvent#batch-optional) * **Type:** `boolean` * **Default:** `true` Whether or not to batch logs between polling intervals. const unwatch = publicClient.watchContractEvent({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, batch: false, onLogs: logs => console.log(logs) }) ### onError (optional)[](https://viem.sh/docs/contract/watchContractEvent#onerror-optional) * **Type:** `(error: Error) => void` Error thrown from listening for new event logs. const unwatch = publicClient.watchContractEvent({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, onError: error => console.log(error), onLogs: logs => console.log(logs) }) ### poll (optional)[](https://viem.sh/docs/contract/watchContractEvent#poll-optional) * **Type:** `boolean` * **Default:** `false` for WebSocket Clients, `true` for non-WebSocket Clients Whether or not to use a polling mechanism to check for new logs instead of a WebSocket subscription. This option is only configurable for Clients with a [WebSocket Transport](https://viem.sh/docs/clients/transports/websocket) . import { createPublicClient, webSocket } from 'viem' import { mainnet } from 'viem/chains' const publicClient = createPublicClient({ chain: mainnet, transport: webSocket() }) const unwatch = publicClient.watchContractEvent( { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, poll: true, } ) ### pollingInterval (optional)[](https://viem.sh/docs/contract/watchContractEvent#pollinginterval-optional) * **Type:** `number` Polling frequency (in ms). Defaults to the Client's `pollingInterval` config. const unwatch = publicClient.watchContractEvent({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, pollingInterval: 1_000, onLogs: logs => console.log(logs) }) ### fromBlock (optional)[](https://viem.sh/docs/contract/watchContractEvent#fromblock-optional) * **Type:** `bigint` The block number to start listening for logs from. const unwatch = publicClient.watchContractEvent({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, onLogs: logs => console.log(logs), fromBlock: 1n }) JSON-RPC Methods[](https://viem.sh/docs/contract/watchContractEvent#json-rpc-methods) -------------------------------------------------------------------------------------- **When poll `true` and RPC Provider supports `eth_newFilter`:** * Calls `[eth_newFilter](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) ` to create a filter (called on initialize). * On a polling interval, it will call `[eth_getFilterChanges](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges) `. **When poll `true` RPC Provider does not support `eth_newFilter`:** * Calls `[eth_getLogs](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs) ` for each block between the polling interval. **When poll `false` and WebSocket Transport:** * Uses a WebSocket subscription via `eth_subscribe` and the "logs" event. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/watchContractEvent.md) Copy page for AI Ask AI... ⌘ I --- # sendCallsSync · Viem [Skip to content](https://viem.sh/docs/actions/wallet/sendCallsSync#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K sendCallsSync ============= Requests for the wallet to sign and broadcast a batch of calls to the network, and waits for the calls to be included in a block. [Read more](https://eips.ethereum.org/EIPS/eip-5792#wallet_sendcalls) Usage[](https://viem.sh/docs/actions/wallet/sendCallsSync#usage) ----------------------------------------------------------------- example.tsconfig.ts import { parseEther } from 'viem' import { account, walletClient } from './config' const status = await walletClient.sendCallsSync({ account, calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], }) Notes: * `account` and `chain` are top level properties as all calls should be sent by the same account and chain. * Properties of `calls` items are only those shared by all transaction types (e.g. `data`, `to`, `value`). The Wallet should handle other required properties like gas & fees. * [Read `wallet_sendCalls` on EIP-5792.](https://eips.ethereum.org/EIPS/eip-5792#wallet_sendcalls) ### Account Hoisting[](https://viem.sh/docs/actions/wallet/sendCallsSync#account-hoisting) If you do not wish to pass an `account` to every `sendCalls`, you can also hoist the Account on the Wallet Client (see `config.ts`). [Learn more](https://viem.sh/docs/clients/wallet#account) . example.tsconfig.ts import { walletClient } from './config' const status = await walletClient.sendCallsSync({ calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], }) ### Contract Calls[](https://viem.sh/docs/actions/wallet/sendCallsSync#contract-calls) The `calls` property also accepts **Contract Calls**, and can be used via the `abi`, `functionName`, and `args` properties. example.tsabi.tsconfig.ts import { parseAbi } from 'viem' import { walletClient } from './config' const abi = parseAbi([\ 'function approve(address, uint256) returns (bool)',\ 'function transferFrom(address, address, uint256) returns (bool)',\ ]) const status = await walletClient.sendCallsSync({ calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ to: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi,\ functionName: 'approve',\ args: [\ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ 100n\ ],\ },\ {\ to: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi,\ functionName: 'transferFrom',\ args: [\ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ '0x0000000000000000000000000000000000000000',\ 100n\ ],\ },\ ], }) ### Compatibility Fallback[](https://viem.sh/docs/actions/wallet/sendCallsSync#compatibility-fallback) If the Wallet does not support EIP-5792 and `wallet_sendCalls`, passing the `experimental_fallback` flag to `sendCalls` will allow Viem to fall back to executing the calls sequentially via `eth_sendTransaction`. example.tsconfig.ts import { parseEther } from 'viem' import { account, walletClient } from './config' const status = await walletClient.sendCallsSync({ account, calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], experimental_fallback: true, }) Returns[](https://viem.sh/docs/actions/wallet/sendCallsSync#returns) --------------------------------------------------------------------- `WalletGetCallsStatusReturnType` Status of the calls. Parameters[](https://viem.sh/docs/actions/wallet/sendCallsSync#parameters) --------------------------------------------------------------------------- ### account[](https://viem.sh/docs/actions/wallet/sendCallsSync#account) * **Type:** `Account | Address | null` The Account to sign & broadcast the call from. If set to `null`, it is assumed that the wallet will handle filling the sender of the calls. Accepts a [JSON-RPC Account](https://viem.sh/docs/clients/wallet#json-rpc-accounts) . import { walletClient } from './config' const status = await walletClient.sendCallsSync({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], }) ### chain[](https://viem.sh/docs/actions/wallet/sendCallsSync#chain) * **Type:** `[Chain](https://viem.sh/docs/glossary/types#chain) ` * **Default:** `walletClient.chain` The target chain to broadcast the calls. import { mainnet } from 'viem/chains' import { walletClient } from './config' const status = await walletClient.sendCallsSync({ chain: mainnet, calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], }) ### calls[](https://viem.sh/docs/actions/wallet/sendCallsSync#calls) * **Type:** `Call[]` An array of calls to be signed and broadcasted. import { mainnet } from 'viem/chains' import { walletClient } from './config' const status = await walletClient.sendCallsSync({ chain: mainnet, calls: [ \ { \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('1') \ }, \ { \ data: '0xdeadbeef', \ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ }, \ ], }) #### calls.data[](https://viem.sh/docs/actions/wallet/sendCallsSync#callsdata) * **Type:** `Hex` Calldata to broadcast (typically a contract function selector with encoded arguments, or contract deployment bytecode). import { mainnet } from 'viem/chains' import { walletClient } from './config' const status = await walletClient.sendCallsSync({ chain: mainnet, calls: [ \ { \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('1') \ }, \ { \ data: '0xdeadbeef', \ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], }) When calling functions on contracts, it may be more convenient to pass in a [Contract Call](https://viem.sh/docs/actions/wallet/sendCallsSync#contract-calls) , providing the the `abi`, `functionName`, and `args` properties which will then be encoded into the appropriate `calls.data`. import { parseAbi } from 'viem' import { walletClient } from './config' const abi = parseAbi([\ 'function approve(address, uint256) returns (bool)',\ ]) const status = await walletClient.sendCallsSync({ calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ to: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi, \ functionName: 'approve',\ args: [\ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ 100n\ ],\ }\ ], }) #### calls.to[](https://viem.sh/docs/actions/wallet/sendCallsSync#callsto) * **Type:** `Address` Recipient address of the call. import { mainnet } from 'viem/chains' import { walletClient } from './config' const status = await walletClient.sendCallsSync({ chain: mainnet, calls: [ \ { \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('1') \ }, \ { \ data: '0xdeadbeef', \ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ },\ ], }) #### calls.value[](https://viem.sh/docs/actions/wallet/sendCallsSync#callsvalue) * **Type:** `Address` Value to send with the call. import { mainnet } from 'viem/chains' import { walletClient } from './config' const status = await walletClient.sendCallsSync({ chain: mainnet, calls: [ \ { \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('1') \ }, \ { \ data: '0xdeadbeef', \ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], }) #### calls.dataSuffix[](https://viem.sh/docs/actions/wallet/sendCallsSync#callsdatasuffix) * **Type:** Hex Data to append to the end of the calldata. Useful for adding a "domain" tag. example.ts const status = await walletClient.sendCallsSync({ calls: [\ {\ to: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi,\ functionName: 'approve',\ args: [\ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ 100n\ ],\ dataSuffix: '0xdeadbeef'\ }\ ], }) ### capabilities[](https://viem.sh/docs/actions/wallet/sendCallsSync#capabilities) * **Type:** `WalletCapabilities` Capability metadata for the calls (e.g. specifying a paymaster). import { walletClient } from './config' const status = await walletClient.sendCallsSync({ calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], capabilities: { paymasterService: { url: 'https://...' } } }) ### forceAtomic[](https://viem.sh/docs/actions/wallet/sendCallsSync#forceatomic) * **Type:** `boolean` * **Default:** `false` Force the calls to be executed atomically. [See more](https://eips.ethereum.org/EIPS/eip-5792#call-execution-atomicity) import { walletClient } from './config' const status = await walletClient.sendCallsSync({ calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], forceAtomic: true, }) ### id[](https://viem.sh/docs/actions/wallet/sendCallsSync#id) * **Type:** `string` Attribute the call batch with an identifier. import { walletClient } from './config' const status = await walletClient.sendCallsSync({ calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], id: '', }) ### pollingInterval (optional)[](https://viem.sh/docs/actions/wallet/sendCallsSync#pollinginterval-optional) * **Type:** `number` * **Default:** `walletClient.pollingInterval` The polling interval to poll for the calls status. import { walletClient } from './config' const status = await walletClient.sendCallsSync({ calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], pollingInterval: 1_000, }) ### timeout (optional)[](https://viem.sh/docs/actions/wallet/sendCallsSync#timeout-optional) * **Type:** `number` * **Default:** `chain.blockTime * 3` The timeout to wait for the calls status. import { walletClient } from './config' const status = await walletClient.sendCallsSync({ calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ ], timeout: 20_000, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/sendCallsSync.mdx) Copy page for AI Ask AI... ⌘ I --- # watchAsset · Viem [Skip to content](https://viem.sh/docs/actions/wallet/watchAsset#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K watchAsset ========== Requests that the user tracks the token in their wallet. Returns a boolean indicating if the token was successfully added. Usage[](https://viem.sh/docs/actions/wallet/watchAsset#usage) -------------------------------------------------------------- example.tsclient.ts import { walletClient } from './client' const success = await walletClient.watchAsset({ type: 'ERC20', options: { address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', decimals: 18, symbol: 'WETH', }, }) Returns[](https://viem.sh/docs/actions/wallet/watchAsset#returns) ------------------------------------------------------------------ `boolean` Boolean indicating if the token was successfully added. Parameters[](https://viem.sh/docs/actions/wallet/watchAsset#parameters) ------------------------------------------------------------------------ ### type[](https://viem.sh/docs/actions/wallet/watchAsset#type) * **Type:** `string` Token type. import { createWalletClient, custom } from 'viem' import { mainnet } from 'viem/chains' export const walletClient = createWalletClient({ chain: mainnet, transport: custom(window.ethereum!), }) // ---cut-- const success = await walletClient.watchAsset({ type: 'ERC20', options: { address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', decimals: 18, symbol: 'WETH', }, }); ### options.address[](https://viem.sh/docs/actions/wallet/watchAsset#optionsaddress) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The address of the token contract. const success = await walletClient.watchAsset({ type: 'ERC20', options: { address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', decimals: 18, symbol: 'WETH', }, }); ### options.decimals[](https://viem.sh/docs/actions/wallet/watchAsset#optionsdecimals) * **Type:** `number` The number of token decimals. const success = await walletClient.watchAsset({ type: 'ERC20', options: { address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', decimals: 18, symbol: 'WETH', }, }); ### options.symbol[](https://viem.sh/docs/actions/wallet/watchAsset#optionssymbol) * **Type:** `string` A ticker symbol or shorthand, up to 11 characters. const success = await walletClient.watchAsset({ type: 'ERC20', options: { address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', decimals: 18, symbol: 'WETH', } }) ### options.image[](https://viem.sh/docs/actions/wallet/watchAsset#optionsimage) * **Type:** `string` A string url of the token logo. const success = await walletClient.watchAsset({ type: 'ERC20', options: { address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', decimals: 18, symbol: 'WETH', image: 'https://weth.com/icon.png', } }) JSON-RPC Methods[](https://viem.sh/docs/actions/wallet/watchAsset#json-rpc-methods) ------------------------------------------------------------------------------------ `[wallet_watchAsset](https://eips.ethereum.org/EIPS/eip-747) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/watchAsset.md) Copy page for AI Ask AI... ⌘ I --- # watchBlocks · Viem [Skip to content](https://viem.sh/docs/actions/public/watchBlocks#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K watchBlocks =========== Watches and returns information for incoming blocks. Usage[](https://viem.sh/docs/actions/public/watchBlocks#usage) --------------------------------------------------------------- Pass through your Public Client, along with a listener. example.tsclient.ts import { publicClient } from './client' const unwatch = publicClient.watchBlocks( { onBlock: block => console.log(block) } ) } } Returns[](https://viem.sh/docs/actions/public/watchBlocks#returns) ------------------------------------------------------------------- `UnwatchFn` A function that can be invoked to stop watching for new blocks. Parameters[](https://viem.sh/docs/actions/public/watchBlocks#parameters) ------------------------------------------------------------------------- ### onBlock[](https://viem.sh/docs/actions/public/watchBlocks#onblock) * **Type:** `(block: Block) => void` The block information. const unwatch = publicClient.watchBlocks( { onBlock: block => console.log(block) } ) ### onError (optional)[](https://viem.sh/docs/actions/public/watchBlocks#onerror-optional) * **Type:** `(error: Error) => void` Error thrown from getting a block. const unwatch = publicClient.watchBlocks( { onBlock: block => console.log(block), onError: error => console.log(error) } ) ### blockTag (optional)[](https://viem.sh/docs/actions/public/watchBlocks#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` Watch for new blocks on a given tag. const unwatch = publicClient.watchBlocks( { blockTag: 'safe', onBlock: block => console.log(block), } ) ### emitMissed (optional)[](https://viem.sh/docs/actions/public/watchBlocks#emitmissed-optional) * **Type:** `boolean` * **Default:** `false` Whether or not to emit missed blocks to the callback. Missed blocks may occur in instances where internet connection is lost, or the block time is lesser than the [polling interval](https://viem.sh/docs/clients/public#pollinginterval-optional) of the client. const unwatch = publicClient.watchBlocks( { emitMissed: true, onBlock: block => console.log(block), } ) ### emitOnBegin (optional)[](https://viem.sh/docs/actions/public/watchBlocks#emitonbegin-optional) * **Type:** `boolean` * **Default:** `false` Whether or not to emit the block to the callback when the subscription opens. const unwatch = publicClient.watchBlocks( { emitOnBegin: true, onBlock: block => console.log(block), } ) ### includeTransactions (optional)[](https://viem.sh/docs/actions/public/watchBlocks#includetransactions-optional) * **Type:** `boolean` Whether or not to include transactions (as a structured array of `Transaction` objects). const unwatch = publicClient.watchBlocks( { includeTransactions: true, onBlock: block => console.log(block), } ) ### poll (optional)[](https://viem.sh/docs/actions/public/watchBlocks#poll-optional) * **Type:** `boolean` * **Default:** `false` for WebSocket Clients, `true` for non-WebSocket Clients Whether or not to use a polling mechanism to check for new blocks instead of a WebSocket subscription. This option is only configurable for Clients with a [WebSocket Transport](https://viem.sh/docs/clients/transports/websocket) . import { createPublicClient, webSocket } from 'viem' import { mainnet } from 'viem/chains' const publicClient = createPublicClient({ chain: mainnet, transport: webSocket() }) const unwatch = publicClient.watchBlocks( { onBlock: block => console.log(block), poll: true, } ) ### pollingInterval (optional)[](https://viem.sh/docs/actions/public/watchBlocks#pollinginterval-optional) * **Type:** `number` Polling frequency (in ms). Defaults to the Client's `pollingInterval` config. const unwatch = publicClient.watchBlocks( { onBlock: block => console.log(block), pollingInterval: 1_000, } ) Example[](https://viem.sh/docs/actions/public/watchBlocks#example) ------------------------------------------------------------------- Check out the usage of `watchBlocks` in the live [Watch Blocks Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks) below. JSON-RPC Methods[](https://viem.sh/docs/actions/public/watchBlocks#json-rpc-methods) ------------------------------------------------------------------------------------- * When `poll: true`, calls `[eth_getBlockByNumber](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getBlockByNumber) ` on a polling interval. * When `poll: false` & WebSocket Transport, uses a WebSocket subscription via `[eth_subscribe](https://docs.alchemy.com/reference/eth-subscribe-polygon) ` and the `"newHeads"` event. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/watchBlocks.md) Copy page for AI Ask AI... ⌘ I --- # estimateContractGas · Viem [Skip to content](https://viem.sh/docs/contract/estimateContractGas#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K estimateContractGas =================== Estimates the gas required to successfully execute a contract write function call. Internally, `estimateContractGas` uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`estimateGas` action](https://viem.sh/docs/actions/public/estimateGas) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData) . Usage[](https://viem.sh/docs/contract/estimateContractGas#usage) ----------------------------------------------------------------- Below is a very basic example of how to estimate gas (with no arguments). The `mint` function accepts no arguments, and returns a token ID. example.tsabi.tsconfig.ts import { account, publicClient } from './config' import { wagmiAbi } from './abi' const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account, }) // 69420n ### Passing Arguments[](https://viem.sh/docs/contract/estimateContractGas#passing-arguments) If your function requires argument(s), you can pass them through with the `args` attribute. TypeScript types for `args` will be inferred from the function name & ABI, to guard you from inserting the wrong values. For example, the `mint` function name below requires a **tokenId** argument, and it is typed as `[number]`. example.tsabi.tsconfig.ts import { account, publicClient } from './config' import { wagmiAbi } from './abi' const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account, }) // 69420n Return Value[](https://viem.sh/docs/contract/estimateContractGas#return-value) ------------------------------------------------------------------------------- `bigint` The gas estimate. Parameters[](https://viem.sh/docs/contract/estimateContractGas#parameters) --------------------------------------------------------------------------- ### address[](https://viem.sh/docs/contract/estimateContractGas#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The contract address. const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account, }) ### abi[](https://viem.sh/docs/contract/estimateContractGas#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account, }) ### functionName[](https://viem.sh/docs/contract/estimateContractGas#functionname) * **Type:** `string` A function to extract from the ABI. const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account, }) ### account[](https://viem.sh/docs/contract/estimateContractGas#account) * **Type:** `Account | Address` The Account to estimate gas from. Accepts a [JSON-RPC Account](https://viem.sh/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' }) ### accessList (optional)[](https://viem.sh/docs/contract/estimateContractGas#accesslist-optional) * **Type:** `[AccessList](https://viem.sh/docs/glossary/types#accesslist) ` The access list. const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], accessList: [{ \ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\ storageKeys: ['0x1'],\ }], account, }) ### args (optional)[](https://viem.sh/docs/contract/estimateContractGas#args-optional) * **Type:** Inferred from ABI. Arguments to pass to function call. const gas = await publicClient.estimateContractGas({ address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: wagmiAbi, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], account, }) ### dataSuffix (optional)[](https://viem.sh/docs/contract/estimateContractGas#datasuffix-optional) * **Type:** `Hex` Data to append to the end of the calldata. Useful for adding a ["domain" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f) . const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], dataSuffix: '0xdeadbeef' }) ### gasPrice (optional)[](https://viem.sh/docs/contract/estimateContractGas#gasprice-optional) * **Type:** `bigint` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction) . const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account, gasPrice: parseGwei('20'), }) ### maxFeePerGas (optional)[](https://viem.sh/docs/contract/estimateContractGas#maxfeepergas-optional) * **Type:** `bigint` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account, maxFeePerGas: parseGwei('20'), }) ### maxPriorityFeePerGas (optional)[](https://viem.sh/docs/contract/estimateContractGas#maxpriorityfeepergas-optional) * **Type:** `bigint` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account, maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), }) ### nonce (optional)[](https://viem.sh/docs/contract/estimateContractGas#nonce-optional) * **Type:** `number` Unique number identifying this transaction. const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account, nonce: 69 }) ### value (optional)[](https://viem.sh/docs/contract/estimateContractGas#value-optional) * **Type:** `number` Value in wei sent with this transaction. const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account, value: parseEther('1') }) ### blockNumber (optional)[](https://viem.sh/docs/contract/estimateContractGas#blocknumber-optional) * **Type:** `number` The block number to perform the read against. const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account, blockNumber: 15121123n, }) ### blockTag (optional)[](https://viem.sh/docs/contract/estimateContractGas#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` The block tag to perform the read against. const gas = await publicClient.estimateContractGas({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account, blockTag: 'safe', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/estimateContractGas.md) Copy page for AI Ask AI... ⌘ I --- # getContractEvents · Viem [Skip to content](https://viem.sh/docs/contract/getContractEvents#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getContractEvents ================= Returns a list of contract **event logs** matching the provided parameters. Usage[](https://viem.sh/docs/contract/getContractEvents#usage) --------------------------------------------------------------- By default, `getContractEvents` returns all matched events on the ABI. In practice, you must use scoping to filter for specific events. example.tsabi.tsclient.ts import { publicClient } from './client' import { erc20Abi } from './abi' // Fetch event logs for every event on every ERC-20 contract. const logs = await publicClient.getContractEvents({ abi: erc20Abi }) // [{ ... }, { ... }, { ... }] Scoping[](https://viem.sh/docs/contract/getContractEvents#scoping) ------------------------------------------------------------------- You can also scope to a set of given attributes. example.tsabi.tsclient.ts import { parseAbiItem } from 'viem' import { publicClient } from './client' import { erc20Abi } from './abi' const usdcContractAddress = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48' const logs = await publicClient.getContractEvents({ address: usdcContractAddress, abi: erc20Abi, eventName: 'Transfer', args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' }, fromBlock: 16330000n, toBlock: 16330050n }) ### Address[](https://viem.sh/docs/contract/getContractEvents#address) Logs can be scoped to an **address**: example.tsabi.tsclient.ts import { publicClient } from './client' import { erc20Abi } from './abi' const logs = await publicClient.getContractEvents({ abi: erc20Abi, address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2', }) ### Event[](https://viem.sh/docs/contract/getContractEvents#event) Logs can be scoped to an **event**. example.tsabi.tsclient.ts import { parseAbiItem } from 'viem' import { publicClient } from './client' import { erc20Abi } from './abi' const logs = await publicClient.getContractEvents({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', abi: erc20Abi, eventName: 'Transfer', }) ### Arguments[](https://viem.sh/docs/contract/getContractEvents#arguments) Logs can be scoped to given **_indexed_ arguments**: const logs = await publicClient.getContractEvents({ abi: erc20Abi, address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', eventName: 'Transfer', args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' } }) Only indexed arguments in `event` are candidates for `args`. An argument can also be an array to indicate that other values can exist in the position: const logs = await publicClient.getContractEvents({ abi: erc20Abi, address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', eventName: 'Transfer', args: { // '0xd8da...' OR '0xa5cc...' OR '0xa152...' from: [\ '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', \ '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac',\ '0xa152f8bb749c55e9943a3a0a3111d18ee2b3f94e',\ ], } }) ### Block Range[](https://viem.sh/docs/contract/getContractEvents#block-range) Logs can be scoped to a **block range**: const logs = await publicClient.getContractEvents({ abi: erc20Abi, address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', eventName: 'Transfer', fromBlock: 16330000n, toBlock: 16330050n }) ### Strict Mode[](https://viem.sh/docs/contract/getContractEvents#strict-mode) By default, `getContractEvents` will include logs that [do not conform](https://viem.sh/docs/glossary/terms#non-conforming-log) to the indexed & non-indexed arguments on the `event`. viem will not return a value for arguments that do not conform to the ABI, thus, some arguments on `args` may be undefined. const logs = await publicClient.getContractEvents({ abi: erc20Abi, eventName: 'Transfer', }) logs[0].args // ^? { address?: Address, to?: Address, value?: bigint } You can turn on `strict` mode to only return logs that conform to the indexed & non-indexed arguments on the `event`, meaning that `args` will always be defined. The trade-off is that non-conforming logs will be filtered out. const logs = await publicClient.getContractEvents({ abi: erc20Abi, eventName: 'Transfer', strict: true }) logs[0].args // ^? { address: Address, to: Address, value: bigint } Returns[](https://viem.sh/docs/contract/getContractEvents#returns) ------------------------------------------------------------------- `[Log[]](https://viem.sh/docs/glossary/types#log) ` A list of event logs. Parameters[](https://viem.sh/docs/contract/getContractEvents#parameters) ------------------------------------------------------------------------- ### abi[](https://viem.sh/docs/contract/getContractEvents#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const logs = await publicClient.getContractEvents({ abi: erc20Abi, }) ### address[](https://viem.sh/docs/contract/getContractEvents#address-1) * **Type:** `[Address | Address[]](https://viem.sh/docs/glossary/types#address) ` A contract address or a list of contract addresses. Only logs originating from the contract(s) will be included in the result. const logs = await publicClient.getContractEvents({ abi: erc20Abi, address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', }) ### eventName[](https://viem.sh/docs/contract/getContractEvents#eventname) * **Type:** `string` An event name on the `abi`. const logs = await publicClient.getContractEvents({ abi: erc20Abi, eventName: 'Transfer' }) ### args[](https://viem.sh/docs/contract/getContractEvents#args) * **Type:** Inferred. A list of _indexed_ event arguments. const logs = await publicClient.getContractEvents({ abi: erc20Abi, eventName: 'Transfer', args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac' }, }) ### fromBlock[](https://viem.sh/docs/contract/getContractEvents#fromblock) * **Type:** `bigint | 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` Block to start including logs from. Mutually exclusive with `blockHash`. const filter = await publicClient.getContractEvents({ abi: erc20Abi, fromBlock: 69420n }) ### toBlock[](https://viem.sh/docs/contract/getContractEvents#toblock) * **Type:** `bigint | 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` Block to stop including logs from. Mutually exclusive with `blockHash`. const filter = await publicClient.getContractEvents({ abi: erc20Abi, toBlock: 70120n }) ### blockHash[](https://viem.sh/docs/contract/getContractEvents#blockhash) * **Type:** `'0x${string}'` Block hash to include logs from. Mutually exclusive with `fromBlock`/`toBlock`. const logs = await publicClient.getContractEvents({ abi: erc20Abi, blockHash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d' }) JSON-RPC Method[](https://viem.sh/docs/contract/getContractEvents#json-rpc-method) ----------------------------------------------------------------------------------- `[eth_getLogs](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getLogs) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/getContractEvents.md) Copy page for AI Ask AI... ⌘ I --- # createSiweMessage · Viem [Skip to content](https://viem.sh/docs/siwe/utilities/createSiweMessage#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K createSiweMessage ================= Creates [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message. Import[](https://viem.sh/docs/siwe/utilities/createSiweMessage#import) ----------------------------------------------------------------------- import { createSiweMessage } from 'viem/siwe' Usage[](https://viem.sh/docs/siwe/utilities/createSiweMessage#usage) --------------------------------------------------------------------- import { createSiweMessage } from 'viem/siwe' const message = createSiweMessage({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', }) Returns[](https://viem.sh/docs/siwe/utilities/createSiweMessage#returns) ------------------------------------------------------------------------- `string` EIP-4361 formatted message. Parameters[](https://viem.sh/docs/siwe/utilities/createSiweMessage#parameters) ------------------------------------------------------------------------------- ### address[](https://viem.sh/docs/siwe/utilities/createSiweMessage#address) * **Type:** `Address` The Ethereum address performing the signing. import { createSiweMessage } from 'viem/siwe' const message = createSiweMessage({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', }) ### chainId[](https://viem.sh/docs/siwe/utilities/createSiweMessage#chainid) * **Type:** `number` The [EIP-155](https://eips.ethereum.org/EIPS/eip-155) Chain ID to which the session is bound. import { createSiweMessage } from 'viem/siwe' const message = createSiweMessage({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', }) ### domain[](https://viem.sh/docs/siwe/utilities/createSiweMessage#domain) * **Type:** `string` [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority that is requesting the signing. import { createSiweMessage } from 'viem/siwe' const message = createSiweMessage({ address: '0xa0cf798816d4b9b9866b5330eea46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', }) ### nonce[](https://viem.sh/docs/siwe/utilities/createSiweMessage#nonce) * **Type:** `string` A random string typically chosen by the relying party and used to prevent replay attacks. import { createSiweMessage } from 'viem/siwe' const message = createSiweMessage({ address: '0xa0cf798816d4b9b9866b5330eea46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', }) ### uri[](https://viem.sh/docs/siwe/utilities/createSiweMessage#uri) * **Type:** `string` [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) URI referring to the resource that is the subject of the signing (as in the subject of a claim). import { createSiweMessage } from 'viem/siwe' const message = createSiweMessage({ address: '0xa0cf798816d4b9b9866b5330eea46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', }) ### version[](https://viem.sh/docs/siwe/utilities/createSiweMessage#version) * **Type:** `'1'` The current version of the SIWE Message. import { createSiweMessage } from 'viem/siwe' const message = createSiweMessage({ address: '0xa0cf798816d4b9b9866b5330eea46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', }) ### expirationTime (optional)[](https://viem.sh/docs/siwe/utilities/createSiweMessage#expirationtime-optional) * **Type:** `Date` Time when the signed authentication message is no longer valid. import { createSiweMessage } from 'viem/siwe' const message = createSiweMessage({ address: '0xa0cf798816d4b9b9866b5330eea46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', expirationTime: new Date(), }) ### issuedAt (optional)[](https://viem.sh/docs/siwe/utilities/createSiweMessage#issuedat-optional) * **Type:** `Date` Time when the message was generated, typically the current time. import { createSiweMessage } from 'viem/siwe' const message = createSiweMessage({ address: '0xa0cf798816d4b9b9866b5330eea46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', issuedAt: new Date(), }) ### notBefore (optional)[](https://viem.sh/docs/siwe/utilities/createSiweMessage#notbefore-optional) * **Type:** `Date` Time when the signed authentication message will become valid. import { createSiweMessage } from 'viem/siwe' const message = createSiweMessage({ address: '0xa0cf798816d4b9b9866b5330eea46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', notBefore: new Date(), }) ### requestId (optional)[](https://viem.sh/docs/siwe/utilities/createSiweMessage#requestid-optional) * **Type:** `string` A system-specific identifier that may be used to uniquely refer to the sign-in request. import { createSiweMessage } from 'viem/siwe' const message = createSiweMessage({ address: '0xa0cf798816d4b9b9866b5330eea46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', requestId: '123e4567-e89b-12d3-a456-426614174000', }) ### resources (optional)[](https://viem.sh/docs/siwe/utilities/createSiweMessage#resources-optional) * **Type:** `string[]` A list of information or references to information the user wishes to have resolved as part of authentication by the relying party. import { createSiweMessage } from 'viem/siwe' const message = createSiweMessage({ address: '0xa0cf798816d4b9b9866b5330eea46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', resources: [ \ 'https://example.com/foo', \ 'https://example.com/bar', \ 'https://example.com/baz', \ ], }) ### scheme (optional)[](https://viem.sh/docs/siwe/utilities/createSiweMessage#scheme-optional) * **Type:** `string` [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme of the origin of the request. import { createSiweMessage } from 'viem/siwe' const message = createSiweMessage({ address: '0xa0cf798816d4b9b9866b5330eea46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', scheme: 'https', }) ### statement (optional)[](https://viem.sh/docs/siwe/utilities/createSiweMessage#statement-optional) * **Type:** `string` A human-readable ASCII assertion that the user will sign. import { createSiweMessage } from 'viem/siwe' const message = createSiweMessage({ address: '0xa0cf798816d4b9b9866b5330eea46a18382f251e', chainId: 1, domain: 'example.com', nonce: 'foobarbaz', uri: 'https://example.com/path', version: '1', statement: 'I accept the ExampleOrg Terms of Service: https://example.com/tos', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/siwe/utilities/createSiweMessage.md) Copy page for AI Ask AI... ⌘ I --- # sendRawTransaction · Viem [Skip to content](https://viem.sh/docs/actions/wallet/sendRawTransaction#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K sendRawTransaction ================== Sends a **signed** transaction to the network. Can be used with both [Public Clients](https://viem.sh/docs/clients/public) and [Wallet Clients](https://viem.sh/docs/clients/wallet) Usage[](https://viem.sh/docs/actions/wallet/sendRawTransaction#usage) ---------------------------------------------------------------------- example.tsconfig.ts import { account, walletClient } from './config' const request = await walletClient.prepareTransactionRequest({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) const serializedTransaction = await walletClient.signTransaction(request) const hash = await walletClient.sendRawTransaction({ serializedTransaction }) Returns[](https://viem.sh/docs/actions/wallet/sendRawTransaction#returns) -------------------------------------------------------------------------- `[Hash](https://viem.sh/docs/glossary/types#hash) ` The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. Parameters[](https://viem.sh/docs/actions/wallet/sendRawTransaction#parameters) -------------------------------------------------------------------------------- ### serializedTransaction[](https://viem.sh/docs/actions/wallet/sendRawTransaction#serializedtransaction) * **Type:** `Hex` The signed serialized transaction. const signature = await walletClient.sendRawTransaction({ serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33' }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/sendRawTransaction.md) Copy page for AI Ask AI... ⌘ I --- # readContract · Viem [Skip to content](https://viem.sh/docs/contract/readContract#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K readContract ============ 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, `readContract` uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData) . Usage[](https://viem.sh/docs/contract/readContract#usage) ---------------------------------------------------------- Below is a very basic example of how to call a read-only function on a contract (with no arguments). example.tsabi.tsclient.ts import { publicClient } from './client' import { wagmiAbi } from './abi' const data = await publicClient.readContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'totalSupply', }) // 69420n ### Passing Arguments[](https://viem.sh/docs/contract/readContract#passing-arguments) If your function requires argument(s), you can pass them through with the `args` attribute. TypeScript types for `args` will be inferred from the function name & ABI, to guard you from inserting the wrong values. For example, the `balanceOf` function name below requires an **address** argument, and it is typed as `["0x${string}"]`. example.tsabi.tsclient.ts import { publicClient } from './client' import { wagmiAbi } from './abi' const data = await publicClient.readContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] }) ### Deployless Reads[](https://viem.sh/docs/contract/readContract#deployless-reads) It is possible to call a function on a contract that has not been deployed yet. For instance, we may want to call a function on an [ERC-4337 Smart Account](https://eips.ethereum.org/EIPS/eip-4337) contract which has not been deployed. Viem offers two ways of performing a Deployless Call, via: * [Bytecode](https://viem.sh/docs/contract/readContract#bytecode) * a [Deploy Factory](https://viem.sh/docs/contract/readContract#deploy-factory) : "temporarily deploys" a contract with a provided [Deploy Factory](https://docs.alchemy.com/docs/create2-an-alternative-to-deriving-contract-addresses#create2-contract-factory) , and calls the function on the deployed contract. #### Bytecode[](https://viem.sh/docs/contract/readContract#bytecode) The example below demonstrates how we can utilize a Deployless Call **via Bytecode** to call the `name` function on the [Wagmi Example ERC721 contract](https://etherscan.io/address/0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2#code) which has not been deployed: example.tsconfig.ts import { parseAbi } from 'viem' import { publicClient } from './config' const data = await publicClient.readContract({ abi: parseAbi(['function name() view returns (string)']), code: '0x...', // Accessible here: https://etherscan.io/address/0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2#code functionName: 'name' }) #### Deploy Factory[](https://viem.sh/docs/contract/readContract#deploy-factory) The example below demonstrates how we can utilize a Deployless Call **via a [Deploy Factory](https://docs.alchemy.com/docs/create2-an-alternative-to-deriving-contract-addresses#create2-contract-factory) ** to call the `entryPoint` function on an [ERC-4337 Smart Account](https://eips.ethereum.org/EIPS/eip-4337) which has not been deployed: example.tsconfig.ts import { encodeFunctionData, parseAbi } from 'viem' import { account, publicClient } from './config' const data = await publicClient.readContract({ // Address of the Smart Account deployer (factory). factory: '0xE8Df82fA4E10e6A12a9Dab552bceA2acd26De9bb', // Function to execute on the factory to deploy the Smart Account. factoryData: encodeFunctionData({ abi: parseAbi(['function createAccount(address owner, uint256 salt)']), functionName: 'createAccount', args: [account, 0n], }), // Function to call on the Smart Account. abi: account.abi, address: account.address, functionName: 'entryPoint', }) Return Value[](https://viem.sh/docs/contract/readContract#return-value) ------------------------------------------------------------------------ The response from the contract. Type is inferred. Parameters[](https://viem.sh/docs/contract/readContract#parameters) -------------------------------------------------------------------- ### address[](https://viem.sh/docs/contract/readContract#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The contract address. const data = await publicClient.readContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'totalSupply', }) ### abi[](https://viem.sh/docs/contract/readContract#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const data = await publicClient.readContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'totalSupply', }) ### functionName[](https://viem.sh/docs/contract/readContract#functionname) * **Type:** `string` A function to extract from the ABI. const data = await publicClient.readContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'totalSupply', }) ### args (optional)[](https://viem.sh/docs/contract/readContract#args-optional) * **Type:** Inferred from ABI. Arguments to pass to function call. const data = await publicClient.readContract({ address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: wagmiAbi, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] }) ### account (optional)[](https://viem.sh/docs/contract/readContract#account-optional) * **Type:** `Account | Address` Optional Account sender override. Accepts a [JSON-RPC Account](https://viem.sh/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . const data = await publicClient.readContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'totalSupply', account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' }) ### blockNumber (optional)[](https://viem.sh/docs/contract/readContract#blocknumber-optional) * **Type:** `number` The block number to perform the read against. const data = await publicClient.readContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'totalSupply', blockNumber: 15121123n, }) ### blockTag (optional)[](https://viem.sh/docs/contract/readContract#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` The block tag to perform the read against. const data = await publicClient.readContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'totalSupply', blockTag: 'safe', }) ### factory (optional)[](https://viem.sh/docs/contract/readContract#factory-optional) * **Type:** Contract deployment factory address (ie. Create2 factory, Smart Account factory, etc). const data = await publicClient.readContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'totalSupply', factory: '0x0000000000ffe8b47b3e2130213b802212439497', factoryData: '0xdeadbeef', }) ### factoryData (optional)[](https://viem.sh/docs/contract/readContract#factorydata-optional) * **Type:** Calldata to execute on the factory to deploy the contract. const data = await publicClient.readContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'totalSupply', factory: '0x0000000000ffe8b47b3e2130213b802212439497', factoryData: '0xdeadbeef', }) ### stateOverride (optional)[](https://viem.sh/docs/contract/readContract#stateoverride-optional) * **Type:** `[StateOverride](https://viem.sh/docs/glossary/types#stateoverride) ` The state override set is an optional address-to-state mapping, where each entry specifies some state to be ephemerally overridden prior to executing the call. const data = await publicClient.readContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'totalSupply', stateOverride: [ \ { \ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ balance: parseEther('1'), \ stateDiff: [ \ { \ slot: '0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0', \ value: '0x00000000000000000000000000000000000000000000000000000000000001a4', \ }, \ ], \ } \ ], }) Live Example[](https://viem.sh/docs/contract/readContract#live-example) ------------------------------------------------------------------------ Check out the usage of `readContract` in the live [Reading Contracts Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_reading-contracts) below. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/readContract.md) Copy page for AI Ask AI... ⌘ I --- # TypeScript · Viem [Skip to content](https://viem.sh/docs/typescript#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K TypeScript ========== TypeScript support for Viem viem is designed to be as type-safe as possible! Things to keep in mind: * Types currently require using TypeScript v5.0.4 or greater. * Changes to types in this repository are considered non-breaking and are usually released as patch semver changes (otherwise every type enhancement would be a major version!). * It is highly recommended that you lock your `viem` package version to a specific patch release and upgrade with the expectation that types may be fixed or upgraded between any release. * The non-type-related public API of `viem` still follows semver very strictly. To ensure everything works correctly, make sure that your `tsconfig.json` has `[strict](https://www.typescriptlang.org/tsconfig#strict) ` mode set to `true`: tsconfig.json { "compilerOptions": { "strict": true } } Type Inference[](https://viem.sh/docs/typescript#type-inference) ----------------------------------------------------------------- viem can infer types based on [ABI](https://docs.soliditylang.org/en/v0.8.24/abi-spec.html#json) and [EIP-712](https://eips.ethereum.org/EIPS/eip-712) Typed Data definitions (powered by [ABIType](https://abitype.dev/) ), giving you full end-to-end type-safety from your contracts to your frontend and incredible developer experience (e.g. autocomplete ABI function names and catch misspellings, strongly-typed ABI function arguments, etc.). For this to work, you must either add [const assertions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4#const-assertions) to specific configuration parameters (more info on those below) or **define them inline**. For example, `[readContract](https://viem.sh/docs/contract/readContract) `'s `abi` configuration parameter: const abi = [{ \ type: 'function', \ name: 'balanceOf', \ stateMutability: 'view', \ inputs: [{ type: 'address' }], \ outputs: [{ type: 'uint256' }], \ }] as const ↑ const assertion const result = client.readContract({ address: '0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c', abi, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] }) ↓ defined inlineconst result = client.readContract({ address: '0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c', abi: [{ \ type: 'function', \ name: 'balanceOf', \ stateMutability: 'view', \ inputs: [{ type: 'address' }], \ outputs: [{ type: 'uint256' }], \ }], functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] }) If type inference isn't working, it's likely you forgot to add a `const` assertion or define the configuration parameter inline. ### Contract ABIs[](https://viem.sh/docs/typescript#contract-abis) The following actions and utilities support type inference when you add a const assertion to `abi` or define `abi` inline: #### Actions[](https://viem.sh/docs/typescript#actions) * `[createEventFilter](https://viem.sh/docs/actions/public/createEventFilter) ` * `[watchEvent](https://viem.sh/docs/actions/public/watchEvent) ` * `[createContractEventFilter](https://viem.sh/docs/contract/createContractEventFilter) ` * `[deployContract](https://viem.sh/docs/contract/deployContract) ` * `[estimateContractGas](https://viem.sh/docs/contract/estimateContractGas) ` * `[multicall](https://viem.sh/docs/contract/multicall) ` * `[readContract](https://viem.sh/docs/contract/readContract) ` * `[simulateContract](https://viem.sh/docs/contract/simulateContract) ` * `[writeContract](https://viem.sh/docs/contract/writeContract) ` * `[watchContractEvent](https://viem.sh/docs/contract/watchContractEvent) ` #### Utilities[](https://viem.sh/docs/typescript#utilities) * [`decodeEventLog`](https://viem.sh/docs/contract/decodeEventLog) * [`decodeFunctionResult`](https://viem.sh/docs/contract/decodeFunctionResult) * [`encodeDeployData`](https://viem.sh/docs/contract/encodeDeployData) * [`encodeErrorResult`](https://viem.sh/docs/contract/encodeErrorResult) * [`encodeEventTopics`](https://viem.sh/docs/contract/encodeEventTopics) * [`encodeFunctionData`](https://viem.sh/docs/contract/encodeFunctionData) * [`encodeFunctionResult`](https://viem.sh/docs/contract/encodeFunctionResult) * [`getAbiItem`](https://viem.sh/docs/abi/getAbiItem) For example, `readContract`: const result = await client.readContract({ address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', abi: erc20Abi, functionName: 'balanceOf', // ↑ Notice how "transfer" is not included since it is not a "read" function args: ['0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c'], }) ### EIP-712 Typed Data[](https://viem.sh/docs/typescript#eip-712-typed-data) Adding a const assertion to `types` or defining `types` inline adds type inference to `[signTypedData](https://viem.sh/docs/actions/wallet/signTypedData) `'s `value` configuration parameter: const result = 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!', }, }) ### Other[](https://viem.sh/docs/typescript#other) The following utilities support type inference when you use const assertions or define arguments inline: * [`decodeAbiParameters`](https://viem.sh/docs/abi/decodeAbiParameters) * [`encodeAbiParameters`](https://viem.sh/docs/abi/encodeAbiParameters) * [`encodePacked`](https://viem.sh/docs/abi/encodePacked) * [`parseAbi`](https://viem.sh/docs/abi/parseAbi) * [`parseAbiItem`](https://viem.sh/docs/abi/parseAbiItem) * [`parseAbiParameter`](https://viem.sh/docs/abi/parseAbiParameter) * [`parseAbiParameters`](https://viem.sh/docs/abi/parseAbiParameters) Configuring Internal Types[](https://viem.sh/docs/typescript#configuring-internal-types) ----------------------------------------------------------------------------------------- For advanced use-cases, you may want to configure viem's internal types. Most of viem's types relating to ABIs and EIP-712 Typed Data are powered by [ABIType](https://abitype.dev/) . See ABIType's [documentation](https://abitype.dev/config) for more info on how to configure types. `window` Polyfill[](https://viem.sh/docs/typescript#window-polyfill) --------------------------------------------------------------------- By importing the `viem/window` Polyfill, the global `window.ethereum` will typed as an `[EIP1193Provider](https://github.com/wagmi-dev/viem/blob/4bdbf15be0d61b52a195e11c97201e707fb616cc/src/types/eip1193.ts#L24-L26) ` (including a fully-typed `request` function & typed events). // @noErrors import 'viem/window'; const hash = await window.ethereum.request({ method: 'e // ^| }) const hash = await window.ethereum.request({ method: 'eth_getTransactionByHash', params: [\ // ^?\ })\ \ [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/typescript.mdx)\ \ Copy page for AI\ \ Ask AI...\ \ ⌘\ \ I --- # parseEventLogs · Viem [Skip to content](https://viem.sh/docs/contract/parseEventLogs#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K parseEventLogs ============== Extracts & decodes logs matching the provided `abi` (and optional `eventName`) from a set of opaque logs. Useful for decoding logs on Transaction Receipts. Install[](https://viem.sh/docs/contract/parseEventLogs#install) ---------------------------------------------------------------- import { parseEventLogs } from 'viem' Usage[](https://viem.sh/docs/contract/parseEventLogs#usage) ------------------------------------------------------------ example.tsabi.tsclient.ts import { parseEventLogs } from 'viem' import { erc20Abi } from './abi' import { client } from './client' const receipt = await getTransactionReceipt(client, { hash: '0xec23b2ba4bc59ba61554507c1b1bc91649e6586eb2dd00c728e8ed0db8bb37ea', }) const logs = parseEventLogs({ abi: erc20Abi, logs: receipt.logs, }) // [\ // { args: { ... }, eventName: 'Transfer', logIndex: 3 ... }, \ // { args: { ... }, eventName: 'Approval', logIndex: 5 ... },\ // ...\ // ] ### Scoping to Event Name(s)[](https://viem.sh/docs/contract/parseEventLogs#scoping-to-event-names) You can scope the logs to a specific event name by providing the `eventName` argument: example.tsabi.tsclient.ts import { parseEventLogs } from 'viem' import { erc20Abi } from './abi' import { client } from './client' const receipt = await getTransactionReceipt(client, { hash: '0xec23b2ba4bc59ba61554507c1b1bc91649e6586eb2dd00c728e8ed0db8bb37ea', }) const logs = parseEventLogs({ abi: erc20Abi, eventName: 'Transfer', logs: receipt.logs, }) // [\ // { args: { ... }, eventName: 'Transfer', logIndex: 3, ... }, \ // { args: { ... }, eventName: 'Transfer', logIndex: 7, ... },\ // ...\ // ] You can also pass an array to scope multiple event names: example.tsabi.tsclient.ts import { parseEventLogs } from 'viem' import { erc20Abi } from './abi' import { client } from './client' const receipt = await getTransactionReceipt(client, { hash: '0xec23b2ba4bc59ba61554507c1b1bc91649e6586eb2dd00c728e8ed0db8bb37ea', }) const logs = parseEventLogs({ abi: erc20Abi, eventName: ['Transfer', 'Approval'], logs: receipt.logs, }) // [\ // { args: { ... }, eventName: 'Transfer', logIndex: 3, ... }, \ // { args: { ... }, eventName: 'Approval', logIndex: 5, ... }, \ // { args: { ... }, eventName: 'Transfer', logIndex: 7, ... },\ // ...\ // ] ### Scoping to Arguments[](https://viem.sh/docs/contract/parseEventLogs#scoping-to-arguments) You can scope the logs to arguments by providing the `args` argument: example.tsabi.tsclient.ts import { parseEventLogs } from 'viem' import { erc20Abi } from './abi' import { client } from './client' const receipt = await getTransactionReceipt(client, { hash: '0xec23b2ba4bc59ba61554507c1b1bc91649e6586eb2dd00c728e8ed0db8bb37ea', }) const logs = parseEventLogs({ abi: erc20Abi, args: { from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', }, logs: receipt.logs, }) // [\ // { args: { from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', ... }, eventName: '...', logIndex: 3, ... }, \ // { args: { from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', ... }, eventName: '...', logIndex: 7, ... },\ // ...\ // ] You can also pass an array to scope multiple values of an argument: example.tsabi.tsclient.ts import { parseEventLogs } from 'viem' import { erc20Abi } from './abi' import { client } from './client' const receipt = await getTransactionReceipt(client, { hash: '0xec23b2ba4bc59ba61554507c1b1bc91649e6586eb2dd00c728e8ed0db8bb37ea', }) const logs = parseEventLogs({ abi: erc20Abi, args: { from: [ \ '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', \ '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', \ ], }, logs: receipt.logs, }) // [\ // { args: { from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', ... }, eventName: '...', logIndex: 3, ... }, \ // { args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', ... }, eventName: '...', logIndex: 7, ... },\ // ...\ // ] ### Partial Decode[](https://viem.sh/docs/contract/parseEventLogs#partial-decode) By default, if the `topics` and `data` does not conform to the ABI (a mismatch between the number of indexed/non-indexed arguments), `parseEventLogs` will not return return the decoded log. For example, the following will not return the nonconforming log as there is a mismatch in non-`indexed` arguments & `data` length. parseEventLogs({ abi: parseAbi(['event Transfer(address indexed, address, uint256)']), logs: [{\ // `data` should be 64 bytes, but is only 32 bytes.\ data: '0x0000000000000000000000000000000000000000000000000000000000000001', \ topics: [\ '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',\ '0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266',\ ]\ // ...\ }] }) // [] It is possible for `parseEventLogs` to try and partially decode the Log, this can be done by setting the `strict` argument to `false`: parseEventLogs({ abi: parseAbi(['event Transfer(address indexed, address, uint256)']), logs: [{\ data: '0x0000000000000000000000000000000000000000000000000000000000000001',\ topics: [\ '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',\ '0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266',\ ]\ // ...\ }] strict: false }) /** * [\ * {\ * eventName: 'Transfer',\ * args: ['0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266'],\ * blockNumber: 42069420n,\ * logIndex: 69,\ * ...\ * }\ * ] */ Return Value[](https://viem.sh/docs/contract/parseEventLogs#return-value) -------------------------------------------------------------------------- `Log[]` Decoded logs. Parameters[](https://viem.sh/docs/contract/parseEventLogs#parameters) ---------------------------------------------------------------------- ### abi[](https://viem.sh/docs/contract/parseEventLogs#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const topics = parseEventLogs({ abi: wagmiAbi, logs: [{\ blockNumber: 69420n,\ data: '0x0000000000000000000000000000000000000000000000000000000000000001',\ logIndex: 1,\ topics: [\ '0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0', \ '0x00000000000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266', \ '0x0000000000000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8'\ ]\ // ...\ }] }) ### logs[](https://viem.sh/docs/contract/parseEventLogs#logs) * **Type:** `Log[]` An array of logs to parse. const topics = parseEventLogs({ abi: wagmiAbi, logs: [{ \ blockNumber: 69420n, \ data: '0x0000000000000000000000000000000000000000000000000000000000000001', \ logIndex: 1, \ topics: [ \ '0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0', \ '0x00000000000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266', \ '0x0000000000000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8'\ ] \ // ...\ }] }) ### args (optional)[](https://viem.sh/docs/contract/parseEventLogs#args-optional) * **Type:** `{ [property: string]: string | string[] | null }` Arguments to scope the logs to. const topics = parseEventLogs({ abi: wagmiAbi, args: { from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', }, logs: [{\ blockNumber: 69420n,\ data: '0x0000000000000000000000000000000000000000000000000000000000000001',\ logIndex: 1,\ topics: [\ '0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0', \ '0x00000000000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266', \ '0x0000000000000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8'\ ]\ // ...\ }] }) ### eventName (optional)[](https://viem.sh/docs/contract/parseEventLogs#eventname-optional) * **Type:** `string` An event name from the ABI. const topics = parseEventLogs({ abi: wagmiAbi, eventName: 'Transfer', logs: [{\ blockNumber: 69420n,\ data: '0x0000000000000000000000000000000000000000000000000000000000000001',\ logIndex: 1,\ topics: [\ '0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0', \ '0x00000000000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266', \ '0x0000000000000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8'\ ]\ // ...\ }] }) ### strict (optional)[](https://viem.sh/docs/contract/parseEventLogs#strict-optional) * **Type:** `boolean` * **Default:** `true` If `true`, `parseEventLogs` will not return [nonconforming logs](https://viem.sh/docs/contract/parseEventLogs#partial-decode) . If `false`, `parseEventLogs` will try and [partially decode](https://viem.sh/docs/contract/parseEventLogs#partial-decode) nonconforming logs. const topics = parseEventLogs({ abi: wagmiAbi, eventName: 'Transfer', logs: [{\ blockNumber: 69420n,\ data: '0x0000000000000000000000000000000000000000000000000000000000000001',\ logIndex: 1,\ topics: [\ '0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0', \ '0x00000000000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266', \ '0x0000000000000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8'\ ]\ // ...\ }], strict: false }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/parseEventLogs.md) Copy page for AI Ask AI... ⌘ I --- # writeContract · Viem [Skip to content](https://viem.sh/docs/contract/writeContract#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K 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](https://viem.sh/docs/glossary/terms) is needed to be broadcast in order to change the state. Internally, `writeContract` uses a [Wallet Client](https://viem.sh/docs/clients/wallet) to call the [`sendTransaction` action](https://viem.sh/docs/actions/wallet/sendTransaction) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData) . Usage[](https://viem.sh/docs/contract/writeContract#usage) ----------------------------------------------------------- Below is a very basic example of how to execute a write function on a contract (with no arguments). While you can use `writeContract` [by itself](https://viem.sh/docs/contract/writeContract#standalone) , it is highly recommended to pair it with `[simulateContract](https://viem.sh/docs/contract/simulateContract) ` to validate that the contract write will execute without errors. example.tsabi.tsconfig.ts import { account, publicClient, walletClient } from './config' import { wagmiAbi } from './abi' const { request } = await publicClient.simulateContract({ account, address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', }) await walletClient.writeContract(request) ### Passing Arguments[](https://viem.sh/docs/contract/writeContract#passing-arguments) If your function requires argument(s), you can pass them through with the `args` attribute. TypeScript types for `args` will be inferred from the function name & ABI, to guard you from inserting the wrong values. For example, the `mint` function name below requires a **tokenId** argument, and it is typed as `[number]`. example.tsabi.tsconfig.ts import { account, walletClient } from './client' import { wagmiAbi } from './abi' const { request } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account }) await walletClient.writeContract(request) ### Standalone[](https://viem.sh/docs/contract/writeContract#standalone) If you don't need to perform validation on the contract write, you can also use it by itself: example.tsabi.tsconfig.ts import { account, walletClient } from './config' import { wagmiAbi } from './abi' await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account, }) Return Value[](https://viem.sh/docs/contract/writeContract#return-value) ------------------------------------------------------------------------- `[Hash](https://viem.sh/docs/glossary/types#hash) ` A [Transaction Hash](https://viem.sh/docs/glossary/terms#hash) . Unlike `[readContract](https://viem.sh/docs/contract/readContract) `, `writeContract` only returns a [Transaction Hash](https://viem.sh/docs/glossary/terms#hash) . If you would like to retrieve the return data of a write function, you can use the [`simulateContract` action](https://viem.sh/docs/contract/simulateContract) – this action does not execute a transaction, and does not require gas (it is very similar to `readContract`). Parameters[](https://viem.sh/docs/contract/writeContract#parameters) --------------------------------------------------------------------- ### address[](https://viem.sh/docs/contract/writeContract#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The contract address. await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420] }) ### abi[](https://viem.sh/docs/contract/writeContract#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420] }) ### functionName[](https://viem.sh/docs/contract/writeContract#functionname) * **Type:** `string` A function to extract from the ABI. await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420] }) ### account[](https://viem.sh/docs/contract/writeContract#account) * **Type:** `Account | Address | null` The Account to write to the contract from. Accepts a [JSON-RPC Account (or Address)](https://viem.sh/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . If set to `null`, it is assumed that the transport will handle the filling the sender of the transaction. await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' }) ### accessList (optional)[](https://viem.sh/docs/contract/writeContract#accesslist-optional) * **Type:** `[AccessList](https://viem.sh/docs/glossary/types#accesslist) ` The access list. await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], accessList: [{ \ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\ storageKeys: ['0x1'],\ }], }) ### authorizationList (optional)[](https://viem.sh/docs/contract/writeContract#authorizationlist-optional) * **Type:** `AuthorizationList` Signed EIP-7702 Authorization list. const authorization = await walletClient.signAuthorization({ contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) await walletClient.writeContract({ address: account.address, abi: wagmiAbi, functionName: 'mint', args: [69420], authorizationList: [authorization], }) ### args (optional)[](https://viem.sh/docs/contract/writeContract#args-optional) * **Type:** Inferred from ABI. Arguments to pass to function call. await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420] }) ### chain (optional)[](https://viem.sh/docs/contract/writeContract#chain-optional) * **Type:** `[Chain](https://viem.sh/docs/glossary/types#chain) ` * **Default:** `walletClient.chain` The target chain. If there is a mismatch between the wallet's current chain & the target chain, an error will be thrown. The chain is also used to infer its request type (e.g. the Celo chain has a `gatewayFee` that you can pass through to `sendTransaction`). import { optimism } from 'viem/chains' await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], chain: optimism, }) ### dataSuffix[](https://viem.sh/docs/contract/writeContract#datasuffix) * **Type:** `Hex` Data to append to the end of the calldata. Useful for adding a ["domain" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f) . await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], dataSuffix: '0xdeadbeef' }) ### gas (optional)[](https://viem.sh/docs/contract/writeContract#gas-optional) * **Type:** `bigint` The gas limit for the transaction. Note that passing a gas limit also skips the gas estimation step. await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], gas: 69420n, }) ### gasPrice (optional)[](https://viem.sh/docs/contract/writeContract#gasprice-optional) * **Type:** `bigint` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction) . await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], gasPrice: parseGwei('20'), }) ### maxFeePerGas (optional)[](https://viem.sh/docs/contract/writeContract#maxfeepergas-optional) * **Type:** `bigint` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], maxFeePerGas: parseGwei('20'), }) ### maxPriorityFeePerGas (optional)[](https://viem.sh/docs/contract/writeContract#maxpriorityfeepergas-optional) * **Type:** `bigint` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), }) ### nonce (optional)[](https://viem.sh/docs/contract/writeContract#nonce-optional) * **Type:** `number` Unique number identifying this transaction. await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], nonce: 69 }) ### value (optional)[](https://viem.sh/docs/contract/writeContract#value-optional) * **Type:** `number` Value in wei sent with this transaction. await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], value: parseEther('1') }) Live Example[](https://viem.sh/docs/contract/writeContract#live-example) ------------------------------------------------------------------------- Check out the usage of `writeContract` in the live [Writing to Contracts Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_writing-to-contracts) below. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/writeContract.md) Copy page for AI Ask AI... ⌘ I --- # writeContractSync · Viem [Skip to content](https://viem.sh/docs/contract/writeContractSync#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K writeContractSync ================= Executes a write function on a contract, and waits for the transaction to be included in a block. Returns the transaction receipt. 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](https://viem.sh/docs/glossary/terms) is needed to be broadcast in order to change the state. Internally, `writeContractSync` uses a [Wallet Client](https://viem.sh/docs/clients/wallet) to call the [`sendTransactionSync` action](https://viem.sh/docs/actions/wallet/sendTransactionSync) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData) . Usage[](https://viem.sh/docs/contract/writeContractSync#usage) --------------------------------------------------------------- Below is a very basic example of how to execute a write function on a contract (with no arguments). While you can use `writeContractSync` [by itself](https://viem.sh/docs/contract/writeContractSync#standalone) , it is highly recommended to pair it with `[simulateContract](https://viem.sh/docs/contract/simulateContract) ` to validate that the contract write will execute without errors. example.tsabi.tsconfig.ts import { account, publicClient, walletClient } from './config' import { wagmiAbi } from './abi' const { request } = await publicClient.simulateContract({ account, address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', }) const receipt = await walletClient.writeContractSync(request) ### Passing Arguments[](https://viem.sh/docs/contract/writeContractSync#passing-arguments) If your function requires argument(s), you can pass them through with the `args` attribute. TypeScript types for `args` will be inferred from the function name & ABI, to guard you from inserting the wrong values. For example, the `mint` function name below requires a **tokenId** argument, and it is typed as `[number]`. example.tsabi.tsconfig.ts import { account, walletClient } from './client' import { wagmiAbi } from './abi' const { request } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account }) const receipt = await walletClient.writeContractSync(request) ### Standalone[](https://viem.sh/docs/contract/writeContractSync#standalone) If you don't need to perform validation on the contract write, you can also use it by itself: example.tsabi.tsconfig.ts import { account, walletClient } from './config' import { wagmiAbi } from './abi' const receipt = await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account, }) Return Value[](https://viem.sh/docs/contract/writeContractSync#return-value) ----------------------------------------------------------------------------- `[TransactionReceipt](https://viem.sh/docs/glossary/types#transaction-receipt) ` A [Transaction receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) . Parameters[](https://viem.sh/docs/contract/writeContractSync#parameters) ------------------------------------------------------------------------- ### address[](https://viem.sh/docs/contract/writeContractSync#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The contract address. await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420] }) ### abi[](https://viem.sh/docs/contract/writeContractSync#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420] }) ### functionName[](https://viem.sh/docs/contract/writeContractSync#functionname) * **Type:** `string` A function to extract from the ABI. await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420] }) ### account[](https://viem.sh/docs/contract/writeContractSync#account) * **Type:** `Account | Address | null` The Account to write to the contract from. Accepts a [JSON-RPC Account (or Address)](https://viem.sh/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . If set to `null`, it is assumed that the transport will handle the filling the sender of the transaction. await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' }) ### accessList (optional)[](https://viem.sh/docs/contract/writeContractSync#accesslist-optional) * **Type:** `[AccessList](https://viem.sh/docs/glossary/types#accesslist) ` The access list. await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], accessList: [{ \ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\ storageKeys: ['0x1'],\ }], }) ### authorizationList (optional)[](https://viem.sh/docs/contract/writeContractSync#authorizationlist-optional) * **Type:** `AuthorizationList` Signed EIP-7702 Authorization list. const authorization = await walletClient.signAuthorization({ contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) await walletClient.writeContractSync({ address: account.address, abi: wagmiAbi, functionName: 'mint', args: [69420], authorizationList: [authorization], }) ### args (optional)[](https://viem.sh/docs/contract/writeContractSync#args-optional) * **Type:** Inferred from ABI. Arguments to pass to function call. await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420] }) ### chain (optional)[](https://viem.sh/docs/contract/writeContractSync#chain-optional) * **Type:** `[Chain](https://viem.sh/docs/glossary/types#chain) ` * **Default:** `walletClient.chain` The target chain. If there is a mismatch between the wallet's current chain & the target chain, an error will be thrown. The chain is also used to infer its request type (e.g. the Celo chain has a `gatewayFee` that you can pass through to `sendTransactionSync`). import { optimism } from 'viem/chains' await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], chain: optimism, }) ### dataSuffix[](https://viem.sh/docs/contract/writeContractSync#datasuffix) * **Type:** `Hex` Data to append to the end of the calldata. Useful for adding a ["domain" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f) . await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], dataSuffix: '0xdeadbeef' }) ### gas (optional)[](https://viem.sh/docs/contract/writeContractSync#gas-optional) * **Type:** `bigint` The gas limit for the transaction. Note that passing a gas limit also skips the gas estimation step. await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], gas: 69420n, }) ### gasPrice (optional)[](https://viem.sh/docs/contract/writeContractSync#gasprice-optional) * **Type:** `bigint` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction) . await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], gasPrice: parseGwei('20'), }) ### maxFeePerGas (optional)[](https://viem.sh/docs/contract/writeContractSync#maxfeepergas-optional) * **Type:** `bigint` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], maxFeePerGas: parseGwei('20'), }) ### maxPriorityFeePerGas (optional)[](https://viem.sh/docs/contract/writeContractSync#maxpriorityfeepergas-optional) * **Type:** `bigint` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), }) ### nonce (optional)[](https://viem.sh/docs/contract/writeContractSync#nonce-optional) * **Type:** `number` Unique number identifying this transaction. await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], nonce: 69 }) ### pollingInterval (optional)[](https://viem.sh/docs/contract/writeContractSync#pollinginterval-optional) * **Type:** `number` * **Default:** `walletClient.pollingInterval` The polling interval to poll for the transaction receipt. await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], pollingInterval: 1_000 }) ### throwOnReceiptRevert (optional)[](https://viem.sh/docs/contract/writeContractSync#throwonreceiptrevert-optional) * **Type:** `boolean` Whether to throw an error if the transaction was detected as reverted. await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], throwOnReceiptRevert: true }) ### timeout (optional)[](https://viem.sh/docs/contract/writeContractSync#timeout-optional) * **Type:** `number` * **Default:** `chain.blockTime * 3` The timeout to wait for the transaction receipt. await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], timeout: 20_000 }) ### value (optional)[](https://viem.sh/docs/contract/writeContractSync#value-optional) * **Type:** `number` Value in wei sent with this transaction. await walletClient.writeContractSync({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], value: parseEther('1') }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/writeContractSync.md) Copy page for AI Ask AI... ⌘ I --- # sendTransactionSync · Viem [Skip to content](https://viem.sh/docs/actions/wallet/sendTransactionSync#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K sendTransactionSync =================== Creates, signs, and sends a new transaction to the network, and waits for the transaction to be included in a block. Returns the transaction receipt. Usage[](https://viem.sh/docs/actions/wallet/sendTransactionSync#usage) ----------------------------------------------------------------------- example.tsconfig.ts import { account, walletClient } from './config' const receipt = await walletClient.sendTransactionSync({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) ### Account Hoisting[](https://viem.sh/docs/actions/wallet/sendTransactionSync#account-hoisting) If you do not wish to pass an `account` to every `sendTransaction`, you can also hoist the Account on the Wallet Client (see `config.ts`). [Learn more](https://viem.sh/docs/clients/wallet#account) . example.tsconfig.ts (JSON-RPC Account)config.ts (Local Account) import { walletClient } from './config' const receipt = await walletClient.sendTransactionSync({ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) Returns[](https://viem.sh/docs/actions/wallet/sendTransactionSync#returns) --------------------------------------------------------------------------- `[TransactionReceipt](https://viem.sh/docs/glossary/types#transaction-receipt) ` The [Transaction receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) . Parameters[](https://viem.sh/docs/actions/wallet/sendTransactionSync#parameters) --------------------------------------------------------------------------------- ### account[](https://viem.sh/docs/actions/wallet/sendTransactionSync#account) * **Type:** `Account | Address | null` The Account to send the transaction from. Accepts a [JSON-RPC Account](https://viem.sh/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . If set to `null`, it is assumed that the transport will handle filling the sender of the transaction. const receipt = await walletClient.sendTransactionSync({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) ### to[](https://viem.sh/docs/actions/wallet/sendTransactionSync#to) * **Type:** `0x${string}` The transaction recipient or contract address. const receipt = await walletClient.sendTransactionSync({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n, nonce: 69 }) ### accessList (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#accesslist-optional) * **Type:** `[AccessList](https://viem.sh/docs/glossary/types#accesslist) ` The access list. const receipt = await walletClient.sendTransactionSync({ accessList: [ \ {\ address: '0x1',\ storageKeys: ['0x1'],\ },\ ], account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### authorizationList (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#authorizationlist-optional) * **Type:** `AuthorizationList` Signed EIP-7702 Authorization list. const authorization = await walletClient.signAuthorization({ account, contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) const receipt = await walletClient.sendTransactionSync({ account, authorizationList: [authorization], data: '0xdeadbeef', to: account.address, }) ### blobs (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#blobs-optional) * **Type:** `Hex[]` Blobs for [Blob Transactions](https://viem.sh/docs/guides/blob-transactions) . import * as cKzg from 'c-kzg' import { toBlobs, setupKzg, stringToHex } from 'viem' import { mainnetTrustedSetupPath } from 'viem/node' const kzg = setupKzg(cKzg, mainnetTrustedSetupPath) const receipt = await walletClient.sendTransactionSync({ account, blobs: toBlobs({ data: stringToHex('blobby blob!') }), kzg, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) ### chain (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#chain-optional) * **Type:** `[Chain](https://viem.sh/docs/glossary/types#chain) ` * **Default:** `walletClient.chain` The target chain. If there is a mismatch between the wallet's current chain & the target chain, an error will be thrown. The chain is also used to infer its request type (e.g. the Celo chain has a `gatewayFee` that you can pass through to `sendTransactionSync`). import { optimism } from 'viem/chains' const receipt = await walletClient.sendTransactionSync({ chain: optimism, account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) ### data (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#data-optional) * **Type:** `0x${string}` A contract hashed method call with encoded args. const receipt = await walletClient.sendTransactionSync({ data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) ### gas (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#gas-optional) * **Type:** `bigint` The gas limit of the transaction. If missing, it will be estimated. const receipt = await walletClient.sendTransactionSync({ account, gas: 21000n, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### gasPrice (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#gasprice-optional) * **Type:** `bigint` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction) . const receipt = await walletClient.sendTransactionSync({ account, gasPrice: parseGwei('20'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### kzg (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#kzg-optional) * **Type:** `KZG` KZG implementation for [Blob Transactions](https://viem.sh/docs/guides/blob-transactions) . See `[setupKzg](https://viem.sh/docs/utilities/setupKzg) ` for more information. import * as cKzg from 'c-kzg' import { toBlobs, setupKzg, stringToHex } from 'viem' import { mainnetTrustedSetupPath } from 'viem/node' const kzg = setupKzg(cKzg, mainnetTrustedSetupPath) const receipt = await walletClient.sendTransactionSync({ account, blobs: toBlobs({ data: stringToHex('blobby blob!') }), kzg, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) ### maxFeePerGas (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#maxfeepergas-optional) * **Type:** `bigint` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) const receipt = await walletClient.sendTransactionSync({ account, maxFeePerGas: parseGwei('20'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### maxPriorityFeePerGas (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#maxpriorityfeepergas-optional) * **Type:** `bigint` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) const receipt = await walletClient.sendTransactionSync({ account, maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### nonce (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#nonce-optional) * **Type:** `number` Unique number identifying this transaction. const receipt = await walletClient.sendTransactionSync({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n, nonce: 69 }) ### pollingInterval (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#pollinginterval-optional) * **Type:** `number` * **Default:** `walletClient.pollingInterval` The polling interval to poll for the transaction receipt. const receipt = await walletClient.sendTransactionSync({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n, nonce: 69, pollingInterval: 1_000 }) ### throwOnReceiptRevert (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#throwonreceiptrevert-optional) * **Type:** `boolean` Whether to throw an error if the transaction was detected as reverted. const receipt = await walletClient.sendTransactionSync({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n, nonce: 69, throwOnReceiptRevert: true }) ### timeout (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#timeout-optional) * **Type:** `number` * **Default:** `chain.blockTime * 3` The timeout to wait for the transaction receipt. const receipt = await walletClient.sendTransactionSync({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n, nonce: 69, timeout: 20_000 }) ### value (optional)[](https://viem.sh/docs/actions/wallet/sendTransactionSync#value-optional) * **Type:** `bigint` Value in wei sent with this transaction. const receipt = await walletClient.sendTransactionSync({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), nonce: 69 }) Tips[](https://viem.sh/docs/actions/wallet/sendTransactionSync#tips) --------------------------------------------------------------------- * For dapps: When using this action, it is assumed that the user has connected to their wallet (e.g. given permission for the dapp to access their accounts via `[requestAddresses](https://viem.sh/docs/actions/wallet/requestAddresses) `). You can also check if the user has granted access to their accounts via `[getAddresses](https://viem.sh/docs/actions/wallet/getAddresses) ` JSON-RPC Methods[](https://viem.sh/docs/actions/wallet/sendTransactionSync#json-rpc-methods) --------------------------------------------------------------------------------------------- * JSON-RPC Accounts: * `[eth_sendTransaction](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction) ` * Local Accounts: * `eth_sendRawTransactionSync` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/sendTransactionSync.md) Copy page for AI Ask AI... ⌘ I --- # signTransaction · Viem [Skip to content](https://viem.sh/docs/actions/wallet/signTransaction#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K signTransaction =============== Signs a transaction. Usage[](https://viem.sh/docs/actions/wallet/signTransaction#usage) ------------------------------------------------------------------- example.tsconfig.ts import { account, walletClient } from './config' const request = await walletClient.prepareTransactionRequest({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) const signature = await walletClient.signTransaction(request) // 0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33 const hash = await walletClient.sendRawTransaction(signature) ### Account Hoisting[](https://viem.sh/docs/actions/wallet/signTransaction#account-hoisting) If you do not wish to pass an `account` to every `prepareTransactionRequest`, you can also hoist the Account on the Wallet Client (see `config.ts`). [Learn more](https://viem.sh/docs/clients/wallet#account) . example.tsconfig.ts (JSON-RPC Account)config.ts (Local Account) import { walletClient } from './config' const request = await walletClient.prepareTransactionRequest({ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) const signature = await walletClient.signTransaction(request) // 0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33 const hash = await walletClient.sendRawTransaction(signature) Returns[](https://viem.sh/docs/actions/wallet/signTransaction#returns) ----------------------------------------------------------------------- `[Hex](https://viem.sh/docs/glossary/types#hex) ` The signed serialized transaction. Parameters[](https://viem.sh/docs/actions/wallet/signTransaction#parameters) ----------------------------------------------------------------------------- ### account[](https://viem.sh/docs/actions/wallet/signTransaction#account) * **Type:** `Account | Address` The Account to send the transaction from. Accepts a [JSON-RPC Account](https://viem.sh/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . const signature = await walletClient.signTransaction({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) ### to[](https://viem.sh/docs/actions/wallet/signTransaction#to) * **Type:** `0x${string}` The transaction recipient or contract address. const signature = await walletClient.signTransaction({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n, nonce: 69 }) ### accessList (optional)[](https://viem.sh/docs/actions/wallet/signTransaction#accesslist-optional) * **Type:** `[AccessList](https://viem.sh/docs/glossary/types#accesslist) ` The access list. const signature = await walletClient.signTransaction({ accessList: [ \ {\ address: '0x1',\ storageKeys: ['0x1'],\ },\ ], account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### authorizationList (optional)[](https://viem.sh/docs/actions/wallet/signTransaction#authorizationlist-optional) * **Type:** `AuthorizationList` Signed EIP-7702 Authorization list. const authorization = await walletClient.signAuthorization({ account, contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) const signature = await walletClient.signTransaction({ account, authorizationList: [authorization], data: '0xdeadbeef', to: account.address, }) ### blobs (optional)[](https://viem.sh/docs/actions/wallet/signTransaction#blobs-optional) * **Type:** `Hex[]` Blobs for [Blob Transactions](https://viem.sh/docs/guides/blob-transactions) . import * as cKzg from 'c-kzg' import { toBlobs, setupKzg, stringToHex } from 'viem' import { mainnetTrustedSetupPath } from 'viem/node' const kzg = setupKzg(cKzg, mainnetTrustedSetupPath) const hash = await walletClient.signTransaction({ account, blobs: toBlobs({ data: stringToHex('blobby blob!') }), kzg, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) ### chain (optional)[](https://viem.sh/docs/actions/wallet/signTransaction#chain-optional) * **Type:** `[Chain](https://viem.sh/docs/glossary/types#chain) ` * **Default:** `walletClient.chain` The target chain. If there is a mismatch between the wallet's current chain & the target chain, an error will be thrown. The chain is also used to infer its request type (e.g. the Celo chain has a `gatewayFee` that you can pass through to `signTransaction`). import { optimism } from 'viem/chains' const signature = await walletClient.signTransaction({ chain: optimism, account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) ### data (optional)[](https://viem.sh/docs/actions/wallet/signTransaction#data-optional) * **Type:** `0x${string}` A contract hashed method call with encoded args. const signature = await walletClient.signTransaction({ data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) ### gas (optional)[](https://viem.sh/docs/actions/wallet/signTransaction#gas-optional) * **Type:** `bigint` The gas limit of the transaction. If missing, it will be estimated. const signature = await walletClient.signTransaction({ account, gas: 21000n, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### gasPrice (optional)[](https://viem.sh/docs/actions/wallet/signTransaction#gasprice-optional) * **Type:** `bigint` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction) . const signature = await walletClient.signTransaction({ account, gasPrice: parseGwei('20'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### kzg (optional)[](https://viem.sh/docs/actions/wallet/signTransaction#kzg-optional) * **Type:** `KZG` KZG implementation for [Blob Transactions](https://viem.sh/docs/guides/blob-transactions) . See `[setupKzg](https://viem.sh/docs/utilities/setupKzg) ` for more information. import * as cKzg from 'c-kzg' import { toBlobs, setupKzg, stringToHex } from 'viem' import { mainnetTrustedSetupPath } from 'viem/node' const kzg = setupKzg(cKzg, mainnetTrustedSetupPath) const signature = await walletClient.signTransaction({ account, blobs: toBlobs({ data: stringToHex('blobby blob!') }), kzg, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) ### maxFeePerGas (optional)[](https://viem.sh/docs/actions/wallet/signTransaction#maxfeepergas-optional) * **Type:** `bigint` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) const signature = await walletClient.signTransaction({ account, maxFeePerGas: parseGwei('20'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### maxPriorityFeePerGas (optional)[](https://viem.sh/docs/actions/wallet/signTransaction#maxpriorityfeepergas-optional) * **Type:** `bigint` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) const signature = await walletClient.signTransaction({ account, maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### nonce (optional)[](https://viem.sh/docs/actions/wallet/signTransaction#nonce-optional) * **Type:** `number` Unique number identifying this transaction. const signature = await walletClient.signTransaction({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n, nonce: 69 }) ### value (optional)[](https://viem.sh/docs/actions/wallet/signTransaction#value-optional) * **Type:** `bigint` Value in wei sent with this transaction. const signature = await walletClient.signTransaction({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), nonce: 69 }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/signTransaction.md) Copy page for AI Ask AI... ⌘ I --- # sendTransaction · Viem [Skip to content](https://viem.sh/docs/actions/wallet/sendTransaction#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K sendTransaction =============== Creates, signs, and sends a new transaction to the network. Usage[](https://viem.sh/docs/actions/wallet/sendTransaction#usage) ------------------------------------------------------------------- example.tsconfig.ts import { account, walletClient } from './config' const hash = await walletClient.sendTransaction({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) // '0x...' ### Account Hoisting[](https://viem.sh/docs/actions/wallet/sendTransaction#account-hoisting) If you do not wish to pass an `account` to every `sendTransaction`, you can also hoist the Account on the Wallet Client (see `config.ts`). [Learn more](https://viem.sh/docs/clients/wallet#account) . example.tsconfig.ts (JSON-RPC Account)config.ts (Local Account) import { walletClient } from './config' const hash = await walletClient.sendTransaction({ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) // '0x...' Returns[](https://viem.sh/docs/actions/wallet/sendTransaction#returns) ----------------------------------------------------------------------- `[Hash](https://viem.sh/docs/glossary/types#hash) ` The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. Parameters[](https://viem.sh/docs/actions/wallet/sendTransaction#parameters) ----------------------------------------------------------------------------- ### account[](https://viem.sh/docs/actions/wallet/sendTransaction#account) * **Type:** `Account | Address | null` The Account to send the transaction from. Accepts a [JSON-RPC Account](https://viem.sh/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . If set to `null`, it is assumed that the transport will handle filling the sender of the transaction. const hash = await walletClient.sendTransaction({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) ### to[](https://viem.sh/docs/actions/wallet/sendTransaction#to) * **Type:** `0x${string}` The transaction recipient or contract address. const hash = await walletClient.sendTransaction({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n, nonce: 69 }) ### accessList (optional)[](https://viem.sh/docs/actions/wallet/sendTransaction#accesslist-optional) * **Type:** `[AccessList](https://viem.sh/docs/glossary/types#accesslist) ` The access list. const hash = await walletClient.sendTransaction({ accessList: [ \ {\ address: '0x1',\ storageKeys: ['0x1'],\ },\ ], account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ### authorizationList (optional)[](https://viem.sh/docs/actions/wallet/sendTransaction#authorizationlist-optional) * **Type:** `AuthorizationList` Signed EIP-7702 Authorization list. const authorization = await walletClient.signAuthorization({ account, contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) const hash = await walletClient.sendTransaction({ account, authorizationList: [authorization], data: '0xdeadbeef', to: account.address, }) ### blobs (optional)[](https://viem.sh/docs/actions/wallet/sendTransaction#blobs-optional) * **Type:** `Hex[]` Blobs for [Blob Transactions](https://viem.sh/docs/guides/blob-transactions) . import * as cKzg from 'c-kzg' import { toBlobs, setupKzg, stringToHex } from 'viem' import { mainnetTrustedSetupPath } from 'viem/node' const kzg = setupKzg(cKzg, mainnetTrustedSetupPath) const hash = await walletClient.sendTransaction({ account, blobs: toBlobs({ data: stringToHex('blobby blob!') }), kzg, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) ### chain (optional)[](https://viem.sh/docs/actions/wallet/sendTransaction#chain-optional) * **Type:** `[Chain](https://viem.sh/docs/glossary/types#chain) ` * **Default:** `walletClient.chain` The target chain. If there is a mismatch between the wallet's current chain & the target chain, an error will be thrown. The chain is also used to infer its request type (e.g. the Celo chain has a `gatewayFee` that you can pass through to `sendTransaction`). import { optimism } from 'viem/chains' const hash = await walletClient.sendTransaction({ chain: optimism, account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) ### data (optional)[](https://viem.sh/docs/actions/wallet/sendTransaction#data-optional) * **Type:** `0x${string}` A contract hashed method call with encoded args. const hash = await walletClient.sendTransaction({ data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }) ### gas (optional)[](https://viem.sh/docs/actions/wallet/sendTransaction#gas-optional) * **Type:** `bigint` The gas limit of the transaction. If missing, it will be estimated. const hash = await walletClient.sendTransaction({ account, gas: 21000n, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### gasPrice (optional)[](https://viem.sh/docs/actions/wallet/sendTransaction#gasprice-optional) * **Type:** `bigint` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction) . const hash = await walletClient.sendTransaction({ account, gasPrice: parseGwei('20'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### kzg (optional)[](https://viem.sh/docs/actions/wallet/sendTransaction#kzg-optional) * **Type:** `KZG` KZG implementation for [Blob Transactions](https://viem.sh/docs/guides/blob-transactions) . See `[setupKzg](https://viem.sh/docs/utilities/setupKzg) ` for more information. import * as cKzg from 'c-kzg' import { toBlobs, setupKzg, stringToHex } from 'viem' import { mainnetTrustedSetupPath } from 'viem/node' const kzg = setupKzg(cKzg, mainnetTrustedSetupPath) const hash = await walletClient.sendTransaction({ account, blobs: toBlobs({ data: stringToHex('blobby blob!') }), kzg, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8' }) ### maxFeePerGas (optional)[](https://viem.sh/docs/actions/wallet/sendTransaction#maxfeepergas-optional) * **Type:** `bigint` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) const hash = await walletClient.sendTransaction({ account, maxFeePerGas: parseGwei('20'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### maxPriorityFeePerGas (optional)[](https://viem.sh/docs/actions/wallet/sendTransaction#maxpriorityfeepergas-optional) * **Type:** `bigint` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) const hash = await walletClient.sendTransaction({ account, maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }) ### nonce (optional)[](https://viem.sh/docs/actions/wallet/sendTransaction#nonce-optional) * **Type:** `number` Unique number identifying this transaction. const hash = await walletClient.sendTransaction({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n, nonce: 69 }) ### value (optional)[](https://viem.sh/docs/actions/wallet/sendTransaction#value-optional) * **Type:** `bigint` Value in wei sent with this transaction. const hash = await walletClient.sendTransaction({ account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), nonce: 69 }) Tips[](https://viem.sh/docs/actions/wallet/sendTransaction#tips) ----------------------------------------------------------------- * For dapps: When using this action, it is assumed that the user has connected to their wallet (e.g. given permission for the dapp to access their accounts via `[requestAddresses](https://viem.sh/docs/actions/wallet/requestAddresses) `). You can also check if the user has granted access to their accounts via `[getAddresses](https://viem.sh/docs/actions/wallet/getAddresses) ` Live Example[](https://viem.sh/docs/actions/wallet/sendTransaction#live-example) --------------------------------------------------------------------------------- Check out the usage of `sendTransaction` in the live [Sending Transactions Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_sending-transactions) below. JSON-RPC Methods[](https://viem.sh/docs/actions/wallet/sendTransaction#json-rpc-methods) ----------------------------------------------------------------------------------------- * JSON-RPC Accounts: * `[eth_sendTransaction](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction) ` * Local Accounts: * `[eth_sendRawTransaction](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendrawtransaction) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/sendTransaction.md) Copy page for AI Ask AI... ⌘ I --- # Contract Writes with EIP-7702 · Viem [Skip to content](https://viem.sh/docs/eip7702/contract-writes#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Contract Writes with EIP-7702 ============================= The guide below demonstrates how to perform Contract Writes with EIP-7702 to invoke Contract functions on an Externally Owned Account (EOA). Overview[](https://viem.sh/docs/eip7702/contract-writes#overview) ------------------------------------------------------------------ Here is an end-to-end overview of how to perform a Contract Write to send a batch of Calls. We will break it down into [Steps](https://viem.sh/docs/eip7702/contract-writes#steps) below. example.tsconfig.tscontract.tsDelegation.sol import { privateKeyToAccount } from 'viem/accounts' import { walletClient } from './config' import { abi, contractAddress } from './contract' const eoa = privateKeyToAccount('0x...') // 1. Authorize designation of the Contract onto the EOA. const authorization = await walletClient.signAuthorization({ account: eoa, contractAddress, }) // 2. Designate the Contract on the EOA, and invoke the // `initialize` function. const hash = await walletClient.writeContract({ abi, address: eoa.address, authorizationList: [authorization], // ↑ 3. Pass the Authorization as a parameter. functionName: 'initialize', }) Steps[](https://viem.sh/docs/eip7702/contract-writes#steps) ------------------------------------------------------------ ### 1\. Set up Smart Contract[](https://viem.sh/docs/eip7702/contract-writes#1-set-up-smart-contract) We will need to set up a Smart Contract to designate on the Account. For the purposes of this guide, we will [create](https://book.getfoundry.sh/reference/forge/forge-init) and [deploy](https://book.getfoundry.sh/forge/deploying) a simple demonstration `Delegation.sol` contract, however, you can use any existing deployed contract. Firstly, [deploy a Contract](https://book.getfoundry.sh/forge/deploying) to the Network with the following source: Delegation.sol pragma solidity ^0.8.20; contract Delegation { event Log(string message); function initialize() external payable { emit Log('Hello, world!'); } function ping() external pure { emit Log('Pong!'); } } ### 2\. Set up Client & Account[](https://viem.sh/docs/eip7702/contract-writes#2-set-up-client--account) Next, we will need to set up a Client and a "Relay Account" that will be responsible for executing the EIP-7702 Contract Write. config.ts import { createWalletClient, http } from 'viem' import { sepolia } from 'viem/chains' import { privateKeyToAccount } from 'viem/accounts' export const relay = privateKeyToAccount('0x...') export const walletClient = createWalletClient({ account: relay, chain: sepolia, transport: http(), }) ### 3\. Authorize Contract Designation[](https://viem.sh/docs/eip7702/contract-writes#3-authorize-contract-designation) We will need to sign an Authorization to designate the Contract to the Account. In the example below, we are instantiating an existing EOA (`account`) and using it to sign the Authorization – this will be the Account that will be used for delegation. example.tscontract.tsconfig.ts import { walletClient } from './config' import { contractAddress } from './contract' const eoa = privateKeyToAccount('0x...') const authorization = await walletClient.signAuthorization({ account: eoa, contractAddress, }) ### 4\. Execute Contract Write[](https://viem.sh/docs/eip7702/contract-writes#4-execute-contract-write) We can now designate the Contract on the Account (and execute the `initialize` function) by sending an EIP-7702 Contract Write. example.tscontract.tsconfig.ts import { walletClient } from './config' import { abi, contractAddress } from './contract' const eoa = privateKeyToAccount('0x...') const authorization = await walletClient.signAuthorization({ account: eoa, contractAddress, }) const hash = await walletClient.writeContract({ abi, address: eoa.address, authorizationList: [authorization], functionName: 'initialize', }) ### 5\. (Optional) Interact with the Delegated Account[](https://viem.sh/docs/eip7702/contract-writes#5-optional-interact-with-the-delegated-account) Now that we have designated a Contract onto the Account, we can interact with it by invoking its functions. Note that we no longer need to use an Authorization! example.tscontract.tsconfig.ts import { walletClient } from './config' import { abi } from './contract' const eoa = privateKeyToAccount('0x...') const hash = await walletClient.writeContract({ abi, address: eoa.address, functionName: 'ping', }) ### Note: Self-executing EIP-7702[](https://viem.sh/docs/eip7702/contract-writes#note-self-executing-eip-7702) If the signer of the Authorization (ie. the EOA) is also executing the Transaction, you will need to pass `executor: 'self'` to `signAuthorization`. This is because `authorization.nonce` must be incremented by 1 over `transaction.nonce`, so we will need to hint to `signAuthorization` that this is the case. example.tsconfig.tscontract.ts import { walletClient } from './config' import { abi, contractAddress } from './contract' const authorization = await walletClient.signAuthorization({ account: eoa, contractAddress, executor: 'self', }) const hash = await walletClient.writeContract({ abi, address: eoa.address, address: walletClient.account.address, authorizationList: [authorization], functionName: 'initialize', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/eip7702/contract-writes.md) Copy page for AI Ask AI... ⌘ I --- # Sending Transactions with EIP-7702 · Viem [Skip to content](https://viem.sh/docs/eip7702/sending-transactions#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Sending Transactions with EIP-7702 ================================== The guide below demonstrates how to send EIP-7702 Transactions to invoke Contract functions on an Externally Owned Account (EOA). Overview[](https://viem.sh/docs/eip7702/sending-transactions#overview) ----------------------------------------------------------------------- Here is an end-to-end overview of how to execute an EIP-7702 Transaction to emit a simple event on the EOA's designated contract. We will break it down into [Steps](https://viem.sh/docs/eip7702/sending-transactions#steps) below. example.tsconfig.tscontract.tsDelegation.sol import { encodeFunctionData } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { walletClient } from './config' import { abi, contractAddress } from './contract' const eoa = privateKeyToAccount('0x...') // 1. Authorize designation of the Contract onto the EOA. const authorization = await walletClient.signAuthorization({ account: eoa, contractAddress, }) // 2. Designate the Contract on the EOA, and invoke the // `initialize` function. const hash = await walletClient.sendTransaction({ authorizationList: [authorization], // ↑ 3. Pass the Authorization as a parameter. data: encodeFunctionData({ abi, functionName: 'initialize', }), to: eoa.address, }) Steps[](https://viem.sh/docs/eip7702/sending-transactions#steps) ----------------------------------------------------------------- ### 1\. Set up Smart Contract[](https://viem.sh/docs/eip7702/sending-transactions#1-set-up-smart-contract) We will need to set up a Smart Contract to designate on the Account. For the purposes of this guide, we will [create](https://book.getfoundry.sh/reference/forge/forge-init) and [deploy](https://book.getfoundry.sh/forge/deploying) a simple demonstration `Delegation.sol` contract, however, you can use any existing deployed contract. Firstly, [deploy a Contract](https://book.getfoundry.sh/forge/deploying) to the Network with the following source: Delegation.sol pragma solidity ^0.8.20; contract Delegation { event Log(string message); function initialize() external payable { emit Log('Hello, world!'); } function ping() external pure { emit Log('Pong!'); } } ### 2\. Set up Client & Account[](https://viem.sh/docs/eip7702/sending-transactions#2-set-up-client--account) Next, we will need to set up a Client and a "Relay Account" that will be responsible for executing the EIP-7702 Transaction. config.ts import { createWalletClient, http } from 'viem' import { sepolia } from 'viem/chains' import { privateKeyToAccount } from 'viem/accounts' export const relay = privateKeyToAccount('0x...') export const walletClient = createWalletClient({ account: relay, chain: sepolia, transport: http(), }) ### 3\. Authorize Contract Designation[](https://viem.sh/docs/eip7702/sending-transactions#3-authorize-contract-designation) We will need to sign an Authorization to designate the Contract to the Account. In the example below, we are instantiating an existing EOA (`account`) and using it to sign the Authorization – this will be the Account that will be used for delegation. example.tscontract.tsconfig.ts import { walletClient } from './config' import { contractAddress } from './contract' const eoa = privateKeyToAccount('0x...') const authorization = await walletClient.signAuthorization({ account: eoa, contractAddress, }) ### 4\. Execute Transaction[](https://viem.sh/docs/eip7702/sending-transactions#4-execute-transaction) We can now designate the Contract on the Account (and execute the `initialize` function) by sending an EIP-7702 Transaction. example.tscontract.tsconfig.ts import { encodeFunctionData } from 'viem' import { walletClient } from './config' import { contractAddress } from './contract' const eoa = privateKeyToAccount('0x...') const authorization = await walletClient.signAuthorization({ account: eoa, contractAddress, }) const hash = await walletClient.sendTransaction({ authorizationList: [authorization], data: encodeFunctionData({ abi, functionName: 'initialize', }), to: eoa.address, }) ### 5\. (Optional) Interact with the Delegated Account[](https://viem.sh/docs/eip7702/sending-transactions#5-optional-interact-with-the-delegated-account) Now that we have designated a Contract onto the Account, we can interact with it by invoking its functions. Note that we no longer need to use an Authorization! example.tscontract.tsconfig.ts import { encodeFunctionData } from 'viem' import { walletClient } from './config' const eoa = privateKeyToAccount('0x...') const hash = await walletClient.sendTransaction({ data: encodeFunctionData({ abi, functionName: 'ping', }), to: eoa.address, }) ### Note: Self-executing EIP-7702[](https://viem.sh/docs/eip7702/sending-transactions#note-self-executing-eip-7702) If the signer of the Authorization (ie. the EOA) is also executing the Transaction, you will need to pass `executor: 'self'` to `signAuthorization`. This is because `authorization.nonce` must be incremented by 1 over `transaction.nonce`, so we will need to hint to `signAuthorization` that this is the case. example.tsconfig.tscontract.ts import { encodeFunctionData } from 'viem' import { walletClient } from './config' import { contractAddress } from './contract' const authorization = await walletClient.signAuthorization({ account: eoa, contractAddress, executor: 'self', }) const hash = await walletClient.sendTransaction({ authorizationList: [authorization], data: encodeFunctionData({ abi, functionName: 'initialize', }), to: eoa.address, to: walletClient.account.address, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/eip7702/sending-transactions.md) Copy page for AI Ask AI... ⌘ I --- # Wallet Client · Viem [Skip to content](https://viem.sh/docs/clients/wallet#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Wallet Client ============= A function to create a Wallet Client. A Wallet Client is an interface to interact with [Ethereum Account(s)](https://ethereum.org/en/glossary/#account) and provides the ability to retrieve accounts, execute transactions, sign messages, etc through [Wallet Actions](https://viem.sh/docs/actions/wallet/introduction) . The `createWalletClient` function sets up a Wallet Client with a given [Transport](https://viem.sh/docs/clients/intro) . The Wallet Client supports signing over: * [JSON-RPC Accounts](https://viem.sh/docs/clients/wallet#json-rpc-accounts) (e.g. Browser Extension Wallets, WalletConnect, etc.). * [Local Accounts](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) (e.g. private key/mnemonic wallets). Import[](https://viem.sh/docs/clients/wallet#import) ----------------------------------------------------- import { createWalletClient } from 'viem' JSON-RPC Accounts[](https://viem.sh/docs/clients/wallet#json-rpc-accounts) --------------------------------------------------------------------------- A [JSON-RPC Account](https://viem.sh/docs/accounts/jsonRpc) **defers** signing of transactions & messages to the target Wallet over JSON-RPC. An example could be sending a transaction via a Browser Extension Wallet (e.g. MetaMask) with the `window.ethereum` Provider. Below is an example of how you can set up a JSON-RPC Account. #### 1: Initialize a Wallet Client[](https://viem.sh/docs/clients/wallet#1-initialize-a-wallet-client) Before we set up our Account and start consuming Wallet Actions, we will need to set up our Wallet Client with the [`custom` Transport](https://viem.sh/docs/clients/transports/custom) , where we will pass in the `window.ethereum` Provider: import { createWalletClient, custom } from 'viem' import { mainnet } from 'viem/chains' const client = createWalletClient({ chain: mainnet, transport: custom(window.ethereum!) }) #### 2: Set up your JSON-RPC Account[](https://viem.sh/docs/clients/wallet#2-set-up-your-json-rpc-account) We will want to retrieve an address that we can access in our Wallet (e.g. MetaMask). import { createWalletClient, custom } from 'viem' import { mainnet } from 'viem/chains' const client = createWalletClient({ chain: mainnet, transport: custom(window.ethereum!) }) const [address] = await client.getAddresses() // or: const [address] = await client.requestAddresses() > Note: Some Wallets (like MetaMask) may require you to request access to Account addresses via `[client.requestAddresses](https://viem.sh/docs/actions/wallet/requestAddresses) ` first. #### 3: Consume [Wallet Actions](https://viem.sh/docs/actions/wallet/introduction) [](https://viem.sh/docs/clients/wallet#3-consume-wallet-actions) Now you can use that address within Wallet Actions that require a signature from the user: import { createWalletClient, custom, parseEther } from 'viem' import { mainnet } from 'viem/chains' const client = createWalletClient({ chain: mainnet, transport: custom(window.ethereum!) }) const [address] = await client.getAddresses() const hash = await client.sendTransaction({ account: address, to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', value: parseEther('0.001') }) #### Optional: Hoist the Account[](https://viem.sh/docs/clients/wallet#optional-hoist-the-account) If you do not wish to pass an account around to every Action that requires an `account`, you can also hoist the account into the Wallet Client. import { createWalletClient, http, parseEther } from 'viem' import { mainnet } from 'viem/chains' const [account] = await window.ethereum!.request({ method: 'eth_requestAccounts' }) const client = createWalletClient({ account, chain: mainnet, transport: http() }) const hash = await client.sendTransaction({ account, to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', value: parseEther('0.001') }) Local Accounts (Private Key, Mnemonic, etc)[](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) --------------------------------------------------------------------------------------------------------------------------- A Local Account performs signing of transactions & messages with a private key **before** executing a method over JSON-RPC. There are three types of Local Accounts in viem: * [Private Key Account](https://viem.sh/docs/accounts/local/privateKeyToAccount) * [Mnemonic Account](https://viem.sh/docs/accounts/local/mnemonicToAccount) * [Hierarchical Deterministic (HD) Account](https://viem.sh/docs/accounts/local/hdKeyToAccount) Below are the steps to integrate a **Private Key Account**, but the same steps can be applied to **Mnemonic & HD Accounts**. #### 1: Initialize a Wallet Client[](https://viem.sh/docs/clients/wallet#1-initialize-a-wallet-client-1) Before we set up our Account and start consuming Wallet Actions, we will need to set up our Wallet Client with the [`http` Transport](https://viem.sh/docs/clients/transports/http) : import { createWalletClient, http } from 'viem' import { mainnet } from 'viem/chains' const client = createWalletClient({ chain: mainnet, transport: http() }) #### 2: Set up your Local Account[](https://viem.sh/docs/clients/wallet#2-set-up-your-local-account) Next, we will instantiate a Private Key Account using `privateKeyToAccount`: import { createWalletClient, http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' const client = createWalletClient({ chain: mainnet, transport: http() }) const account = privateKeyToAccount('0x...') #### 3: Consume [Wallet Actions](https://viem.sh/docs/actions/wallet/introduction) [](https://viem.sh/docs/clients/wallet#3-consume-wallet-actions-1) Now you can use that Account within Wallet Actions that need a signature from the user: import { createWalletClient, http, parseEther } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' const client = createWalletClient({ chain: mainnet, transport: http() }) const account = privateKeyToAccount('0x...') const hash = await client.sendTransaction({ account, to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', value: parseEther('0.001') }) #### Optional: Hoist the Account[](https://viem.sh/docs/clients/wallet#optional-hoist-the-account-1) If you do not wish to pass an account around to every Action that requires an `account`, you can also hoist the account into the Wallet Client. import { createWalletClient, http, parseEther } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' const account = privateKeyToAccount('0x...') const client = createWalletClient({ account, chain: mainnet, transport: http() }) const hash = await client.sendTransaction({ account, to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', value: parseEther('0.001') }) #### Optional: Extend with Public Actions[](https://viem.sh/docs/clients/wallet#optional-extend-with-public-actions) When using a Local Account, you may be finding yourself using a [Public Client](https://viem.sh/docs/clients/public) instantiated with the same parameters (`transport`, `chain`, etc) as your Wallet Client. In this case, you can extend your Wallet Client with [Public Actions](https://viem.sh/docs/actions/public/introduction) to avoid having to handle multiple Clients. import { createWalletClient, http, publicActions } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' const account = privateKeyToAccount('0x...') const client = createWalletClient({ account, chain: mainnet, transport: http() }).extend(publicActions) // [!code ++] const { request } = await client.simulateContract({ ... }) // Public Action const hash = await client.writeContract(request) // Wallet Action Parameters[](https://viem.sh/docs/clients/wallet#parameters) ------------------------------------------------------------- ### account (optional)[](https://viem.sh/docs/clients/wallet#account-optional) * **Type:** `Account | Address` The Account to use for the Wallet Client. This will be used for Actions that require an `account` as an argument. Accepts a [JSON-RPC Account](https://viem.sh/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . import { createWalletClient, custom, parseEther } from 'viem' import { mainnet } from 'viem/chains' const client = createWalletClient({ account: '0x...', chain: mainnet, transport: custom(window.ethereum!) }) const hash = await client.sendTransaction({ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', value: parseEther('0.001') }) ### chain (optional)[](https://viem.sh/docs/clients/wallet#chain-optional) * **Type:** [Chain](https://viem.sh/docs/glossary/types#chain) The [Chain](https://viem.sh/docs/chains/introduction) of the Wallet Client. Used in the `[sendTransaction](https://viem.sh/docs/actions/wallet/sendTransaction) ` & `[writeContract](https://viem.sh/docs/contract/writeContract) ` Actions to assert that the chain matches the wallet's active chain. const client = createWalletClient({ chain: mainnet, transport: custom(window.ethereum!) }) ### cacheTime (optional)[](https://viem.sh/docs/clients/wallet#cachetime-optional) * **Type:** `number` * **Default:** `client.pollingInterval` Time (in ms) that cached data will remain in memory. const client = createWalletClient({ cacheTime: 10_000, chain: mainnet, transport: custom(window.ethereum!) }) ### ccipRead (optional)[](https://viem.sh/docs/clients/wallet#ccipread-optional) * **Type:** `(parameters: CcipRequestParameters) => Promise | false` * **Default:** `true` [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration. CCIP Read is enabled by default, but if set to `false`, the client will not support offchain CCIP lookups. const client = createWalletClient({ ccipRead: false, transport: custom(window.ethereum!) }) ### ccipRead.request (optional)[](https://viem.sh/docs/clients/wallet#ccipreadrequest-optional) * **Type:** `(parameters: CcipRequestParameters) => Promise` A function that will be called to make the [offchain CCIP lookup request](https://eips.ethereum.org/EIPS/eip-3668#client-lookup-protocol) . const client = createWalletClient({ ccipRead: { async request({ data, sender, urls }) { // ... } }, transport: custom(window.ethereum!) }) ### key (optional)[](https://viem.sh/docs/clients/wallet#key-optional) * **Type:** `string` * **Default:** `"wallet"` A key for the Client. const client = createWalletClient({ key: 'foo', transport: custom(window.ethereum!) }) ### name (optional)[](https://viem.sh/docs/clients/wallet#name-optional) * **Type:** `string` * **Default:** `"Wallet Client"` A name for the Client. const client = createWalletClient({ name: 'Foo Wallet Client', transport: custom(window.ethereum!) }) ### pollingInterval (optional)[](https://viem.sh/docs/clients/wallet#pollinginterval-optional) * **Type:** `number` * **Default:** `4_000` Frequency (in ms) for polling enabled Actions. const client = createWalletClient({ pollingInterval: 10_000, transport: custom(window.ethereum!) }) ### rpcSchema (optional)[](https://viem.sh/docs/clients/wallet#rpcschema-optional) * **Type:** `RpcSchema` * **Default:** `WalletRpcSchema` Typed JSON-RPC schema for the client. import 'viem/window' import { createWalletClient, custom } from 'viem' // @noErrors // ---cut--- import { rpcSchema } from 'viem' type CustomRpcSchema = [{ \ Method: 'eth_wagmi', \ Parameters: [string] \ ReturnType: string\ }] const client = createWalletClient({ rpcSchema: rpcSchema(), transport: custom(window.ethereum!) }) const result = await client.request({ method: 'eth_wa // [!code focus] // ^| params: ['hello'], }) ### dataSuffix (optional)[](https://viem.sh/docs/clients/wallet#datasuffix-optional) * **Type:** `Hex | { value: Hex; required?: boolean }` Data to append to the end of transaction calldata. Useful for adding [transaction attribution](https://oxlib.sh/ercs/erc8021/Attribution) . When a simple hex string is provided, the suffix is appended on a best-effort basis. When using the object form with `required: true`, transactions will fail if the suffix cannot be appended. Applies to `sendTransaction`, `sendTransactionSync`, `sendCalls`, `simulateContract`, and `estimateContractGas` actions. const client = createWalletClient({ dataSuffix: '0xdeadbeef', transport: custom(window.ethereum!) }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/clients/wallet.md) Copy page for AI Ask AI... ⌘ I --- # Public Client · Viem [Skip to content](https://viem.sh/docs/clients/public#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K Public Client ============= A function to create a Public Client A Public Client is an interface to "public" [JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/) methods such as retrieving block numbers, transactions, reading from smart contracts, etc through [Public Actions](https://viem.sh/docs/actions/public/introduction) . The `createPublicClient` function sets up a Public Client with a given [Transport](https://viem.sh/docs/clients/intro) configured for a [Chain](https://viem.sh/docs/chains/introduction) . Import[](https://viem.sh/docs/clients/public#import) ----------------------------------------------------- import { createPublicClient } from 'viem' Usage[](https://viem.sh/docs/clients/public#usage) --------------------------------------------------- Initialize a Client with your desired [Chain](https://viem.sh/docs/chains/introduction) (e.g. `mainnet`) and [Transport](https://viem.sh/docs/clients/intro) (e.g. `http`). import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' const publicClient = createPublicClient({ chain: mainnet, transport: http() }) Then you can consume [Public Actions](https://viem.sh/docs/actions/public/introduction) : const blockNumber = await publicClient.getBlockNumber() Optimization[](https://viem.sh/docs/clients/public#optimization) ----------------------------------------------------------------- The Public Client also supports [`eth_call` Aggregation](https://viem.sh/docs/clients/public#multicall) for improved performance. ### `eth_call` Aggregation (via Multicall)[](https://viem.sh/docs/clients/public#eth_call-aggregation-via-multicall) The Public Client supports the aggregation of `eth_call` requests into a single multicall (`aggregate3`) request. This means for every Action that utilizes an `eth_call` request (ie. `readContract`), the Public Client will batch the requests (over a timed period) and send it to the RPC Provider in a single multicall request. This can dramatically improve network performance, and decrease the amount of [Compute Units (CU)](https://docs.alchemy.com/reference/compute-units) used by RPC Providers like Alchemy, Infura, etc. The Public Client schedules the aggregation of `eth_call` requests over a given time period. By default, it executes the batch request at the end of the current [JavaScript message queue](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop#queue) (a [zero delay](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop#zero_delays) ), however, consumers can specify a custom `wait` period (in ms). You can enable `eth_call` aggregation by setting the `batch.multicall` flag to `true`: const publicClient = createPublicClient({ batch: { multicall: true, }, chain: mainnet, transport: http(), }) > You can also [customize the `multicall` options](https://viem.sh/docs/clients/public#batchmulticallbatchsize-optional) > . Now, when you start to utilize `readContract` Actions, the Public Client will batch and send over those requests at the end of the message queue (or custom time period) in a single `eth_call` multicall request: example.tsclient.tsabi.ts import { getContract } from 'viem' import { abi } from './abi' import { publicClient } from './client' const contract = getContract({ address, abi, client: publicClient }) // The below will send a single request to the RPC Provider. const [name, totalSupply, symbol, balance] = await Promise.all([\ contract.read.name(),\ contract.read.totalSupply(),\ contract.read.symbol(),\ contract.read.balanceOf([address]),\ ]) > Read more on [Contract Instances](https://viem.sh/docs/contract/getContract) > . Parameters[](https://viem.sh/docs/clients/public#parameters) ------------------------------------------------------------- ### transport[](https://viem.sh/docs/clients/public#transport) * **Type:** [Transport](https://viem.sh/docs/glossary/types#transport) The [Transport](https://viem.sh/docs/clients/intro) of the Public Client. const publicClient = createPublicClient({ chain: mainnet, transport: http(), }) ### chain (optional)[](https://viem.sh/docs/clients/public#chain-optional) * **Type:** [Chain](https://viem.sh/docs/glossary/types#chain) The [Chain](https://viem.sh/docs/chains/introduction) of the Public Client. const publicClient = createPublicClient({ chain: mainnet, transport: http(), }) ### batch (optional)[](https://viem.sh/docs/clients/public#batch-optional) Flags for batch settings. ### batch.multicall (optional)[](https://viem.sh/docs/clients/public#batchmulticall-optional) * **Type:** `boolean | MulticallBatchOptions` * **Default:** `false` Toggle to enable `eth_call` multicall aggregation. const publicClient = createPublicClient({ batch: { multicall: true, }, chain: mainnet, transport: http(), }) ### batch.multicall.batchSize (optional)[](https://viem.sh/docs/clients/public#batchmulticallbatchsize-optional) * **Type:** `number` * **Default:** `1_024` The maximum size (in bytes) for each multicall (`aggregate3`) calldata chunk. > Note: Some RPC Providers limit the amount of calldata that can be sent in a single request. It is best to check with your RPC Provider to see if there are any calldata size limits to `eth_call` requests. const publicClient = createPublicClient({ batch: { multicall: { batchSize: 512, }, }, chain: mainnet, transport: http(), }) ### batch.multicall.deployless (optional)[](https://viem.sh/docs/clients/public#batchmulticalldeployless-optional) * **Type:** `boolean` * **Default:** `false` Enable deployless multicall. const publicClient = createPublicClient({ batch: { multicall: { deployless: true, }, }, chain: mainnet, transport: http(), }) ### batch.multicall.wait (optional)[](https://viem.sh/docs/clients/public#batchmulticallwait-optional) * **Type:** `number` * **Default:** `0` ([zero delay](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop#zero_delays) ) The maximum number of milliseconds to wait before sending a batch. const publicClient = createPublicClient({ batch: { multicall: { wait: 16, }, }, chain: mainnet, transport: http(), }) ### cacheTime (optional)[](https://viem.sh/docs/clients/public#cachetime-optional) * **Type:** `number` * **Default:** `client.pollingInterval` Time (in ms) that cached data will remain in memory. const publicClient = createPublicClient({ cacheTime: 10_000, chain: mainnet, transport: http(), }) ### ccipRead (optional)[](https://viem.sh/docs/clients/public#ccipread-optional) * **Type:** `(parameters: CcipRequestParameters) => Promise | false` * **Default:** `true` [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration. CCIP Read is enabled by default, but if set to `false`, the client will not support offchain CCIP lookups. const publicClient = createPublicClient({ ccipRead: false, chain: mainnet, transport: http(), }) ### ccipRead.request (optional)[](https://viem.sh/docs/clients/public#ccipreadrequest-optional) * **Type:** `(parameters: CcipRequestParameters) => Promise` A function that will be called to make the [offchain CCIP lookup request](https://eips.ethereum.org/EIPS/eip-3668#client-lookup-protocol) . const publicClient = createPublicClient({ ccipRead: { async request({ data, sender, urls }) { // ... } }, chain: mainnet, transport: http(), }) ### experimental\_blockTag (optional)[](https://viem.sh/docs/clients/public#experimental_blocktag-optional) * **Type:** `BlockTag` * **Default:** `'latest'` The default block tag to use for Actions. This will be used as the default block tag for the following Actions: * `call` * `estimateGas` * `getBalance` * `getBlock` * `simulateBlocks` * `waitForTransactionReceipt` * `watchBlocks` const publicClient = createPublicClient({ experimental_blockTag: 'pending', chain: mainnet, transport: http(), }) ### key (optional)[](https://viem.sh/docs/clients/public#key-optional) * **Type:** `string` * **Default:** `"public"` A key for the Client. const publicClient = createPublicClient({ chain: mainnet, key: 'public', transport: http(), }) ### name (optional)[](https://viem.sh/docs/clients/public#name-optional) * **Type:** `string` * **Default:** `"Public Client"` A name for the Client. const publicClient = createPublicClient({ chain: mainnet, name: 'Public Client', transport: http(), }) ### pollingInterval (optional)[](https://viem.sh/docs/clients/public#pollinginterval-optional) * **Type:** `number` * **Default:** `4_000` Frequency (in ms) for polling enabled Actions. const publicClient = createPublicClient({ chain: mainnet, pollingInterval: 10_000, transport: http(), }) ### rpcSchema (optional)[](https://viem.sh/docs/clients/public#rpcschema-optional) * **Type:** `RpcSchema` * **Default:** `PublicRpcSchema` Typed JSON-RPC schema for the client. import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' // @noErrors // ---cut--- import { rpcSchema } from 'viem' type CustomRpcSchema = [{ \ Method: 'eth_wagmi', \ Parameters: [string] \ ReturnType: string\ }] const publicClient = createPublicClient({ chain: mainnet, rpcSchema: rpcSchema(), transport: http(), }) const result = await publicClient.request({ method: 'eth_wa // [!code focus] // ^| params: ['hello'], }) ### dataSuffix (optional)[](https://viem.sh/docs/clients/public#datasuffix-optional) * **Type:** `Hex | { value: Hex; required?: boolean }` Data to append to the end of transaction calldata. Useful for adding [transaction attribution](https://oxlib.sh/ercs/erc8021/Attribution) . When a simple hex string is provided, the suffix is appended on a best-effort basis. When using the object form with `required: true`, transactions will fail if the suffix cannot be appended. Applies to `simulateContract` and `estimateContractGas` actions. For transaction-sending actions like `sendTransaction`, see [Wallet Client](https://viem.sh/docs/clients/wallet#datasuffix-optional) . const publicClient = createPublicClient({ chain: mainnet, dataSuffix: '0xdeadbeef', transport: http(), }) Live Example[](https://viem.sh/docs/clients/public#live-example) ----------------------------------------------------------------- Check out the usage of `createPublicClient` in the live [Public Client Example](https://stackblitz.com/github/wagmi-dev/viem/tree/main/examples/clients_public-client) below. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/clients/public.md) Copy page for AI Ask AI... ⌘ I --- # simulateBlocks · Viem [Skip to content](https://viem.sh/docs/actions/public/simulateBlocks#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K simulateBlocks ============== Simulates a set of calls on block(s) with optional block and state overrides. Internally uses the [`eth_simulateV1` JSON-RPC method](https://github.com/ethereum/execution-apis/pull/484) . Usage[](https://viem.sh/docs/actions/public/simulateBlocks#usage) ------------------------------------------------------------------ example.tsconfig.ts import { parseEther } from 'viem' import { client } from './config' const result = await client.simulateBlocks({ blocks: [{\ blockOverrides: {\ number: 69420n,\ },\ calls: [\ {\ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\ to: '0xcb98643b8786950F0461f3B0edf99D88F274574D',\ value: parseEther('2'),\ },\ {\ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1'),\ },\ ],\ stateOverrides: [{\ address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\ balance: parseEther('10'),\ }],\ }] }) ### Contract Calls[](https://viem.sh/docs/actions/public/simulateBlocks#contract-calls) The `calls` property also accepts **Contract Calls**, and can be used via the `abi`, `functionName`, and `args` properties. example.tsconfig.ts import { parseAbi, parseEther } from 'viem' import { client } from './config' const abi = parseAbi([\ 'function approve(address, uint256) returns (bool)',\ 'function transferFrom(address, address, uint256) returns (bool)',\ ]) const result = await client.simulateBlocks({ blocks: [{\ calls: [\ {\ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\ to: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi,\ functionName: 'approve',\ args: [\ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ 100n\ ],\ },\ {\ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\ to: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi,\ functionName: 'transferFrom',\ args: [\ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ '0x0000000000000000000000000000000000000000',\ 100n\ ],\ },\ ],\ }] }) Return Value[](https://viem.sh/docs/actions/public/simulateBlocks#return-value) -------------------------------------------------------------------------------- `SimulateBlocksReturnType` Simulation results. Parameters[](https://viem.sh/docs/actions/public/simulateBlocks#parameters) ---------------------------------------------------------------------------- ### blocks[](https://viem.sh/docs/actions/public/simulateBlocks#blocks) Blocks to simulate. ### blocks.calls[](https://viem.sh/docs/actions/public/simulateBlocks#blockscalls) * **Type:** `TransactionRequest[]` Calls to simulate. Each call can consist of transaction request properties. const result = await client.simulateBlocks({ blocks: [{\ blockOverrides: {\ number: 69420n,\ },\ calls: [ \ { \ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929', \ data: '0xdeadbeef', \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ }, \ { \ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929', \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('1'), \ }, \ ], \ stateOverrides: [{\ address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\ balance: parseEther('10'),\ }],\ }] }) ### blocks.blockOverrides[](https://viem.sh/docs/actions/public/simulateBlocks#blocksblockoverrides) * **Type:** `BlockOverrides` Values to override on the block. const result = await client.simulateBlocks({ blocks: [{\ blockOverrides: { \ number: 69420n, \ }, \ calls: [ \ { \ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929', \ data: '0xdeadbeef', \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ }, \ { \ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929', \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('1'), \ }, \ ], \ stateOverrides: [{\ address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\ balance: parseEther('10'),\ }],\ }] }) ### blocks.stateOverrides[](https://viem.sh/docs/actions/public/simulateBlocks#blocksstateoverrides) * **Type:** `StateOverride` State overrides. const result = await client.simulateBlocks({ blocks: [{\ blockOverrides: {\ number: 69420n,\ },\ calls: [ \ { \ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929', \ data: '0xdeadbeef', \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ }, \ { \ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929', \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('1'), \ }, \ ], \ stateOverrides: [{ \ address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929', \ balance: parseEther('10'), \ }], \ }] }) ### returnFullTransactions[](https://viem.sh/docs/actions/public/simulateBlocks#returnfulltransactions) * **Type:** `boolean` Whether to return the full transactions. const result = await client.simulateBlocks({ blocks: [{\ blockOverrides: {\ number: 69420n,\ },\ calls: [ \ { \ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929', \ data: '0xdeadbeef', \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ }, \ { \ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929', \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('1'), \ }, \ ], \ stateOverrides: [{\ address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\ balance: parseEther('10'),\ }],\ }], returnFullTransactions: true, }) ### traceTransfers[](https://viem.sh/docs/actions/public/simulateBlocks#tracetransfers) * **Type:** `boolean` Whether to trace transfers. const result = await client.simulateBlocks({ blocks: [{\ blockOverrides: {\ number: 69420n,\ },\ calls: [ \ { \ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929', \ data: '0xdeadbeef', \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ }, \ { \ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929', \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('1'), \ }, \ ], \ stateOverrides: [{\ address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\ balance: parseEther('10'),\ }],\ }], traceTransfers: true, }) ### validation[](https://viem.sh/docs/actions/public/simulateBlocks#validation) * **Type:** `boolean` Whether to enable validation mode. const result = await client.simulateBlocks({ blocks: [{\ blockOverrides: {\ number: 69420n,\ },\ calls: [ \ { \ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929', \ data: '0xdeadbeef', \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ }, \ { \ from: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929', \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('1'), \ }, \ ], \ stateOverrides: [{\ address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\ balance: parseEther('10'),\ }],\ }], validation: true, }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/public/simulateBlocks.md) Copy page for AI Ask AI... ⌘ I --- # sendCalls · Viem [Skip to content](https://viem.sh/docs/actions/wallet/sendCalls#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K sendCalls ========= Requests for the wallet to sign and broadcast a batch of calls to the network. [Read more](https://eips.ethereum.org/EIPS/eip-5792#wallet_sendcalls) Usage[](https://viem.sh/docs/actions/wallet/sendCalls#usage) ------------------------------------------------------------- example.tsconfig.ts import { parseEther } from 'viem' import { account, walletClient } from './config' const { id } = await walletClient.sendCalls({ account, calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], }) Notes: * `account` and `chain` are top level properties as all calls should be sent by the same account and chain. * Properties of `calls` items are only those shared by all transaction types (e.g. `data`, `to`, `value`). The Wallet should handle other required properties like gas & fees. * [Read `wallet_sendCalls` on EIP-5792.](https://eips.ethereum.org/EIPS/eip-5792#wallet_sendcalls) ### Account Hoisting[](https://viem.sh/docs/actions/wallet/sendCalls#account-hoisting) If you do not wish to pass an `account` to every `sendCalls`, you can also hoist the Account on the Wallet Client (see `config.ts`). [Learn more](https://viem.sh/docs/clients/wallet#account) . example.tsconfig.ts import { walletClient } from './config' const { id } = await walletClient.sendCalls({ calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], }) ### Contract Calls[](https://viem.sh/docs/actions/wallet/sendCalls#contract-calls) The `calls` property also accepts **Contract Calls**, and can be used via the `abi`, `functionName`, and `args` properties. example.tsabi.tsconfig.ts import { parseAbi } from 'viem' import { walletClient } from './config' const abi = parseAbi([\ 'function approve(address, uint256) returns (bool)',\ 'function transferFrom(address, address, uint256) returns (bool)',\ ]) const { id } = await walletClient.sendCalls({ calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ to: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi,\ functionName: 'approve',\ args: [\ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ 100n\ ],\ },\ {\ to: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi,\ functionName: 'transferFrom',\ args: [\ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ '0x0000000000000000000000000000000000000000',\ 100n\ ],\ },\ ], }) ### Compatibility Fallback[](https://viem.sh/docs/actions/wallet/sendCalls#compatibility-fallback) If the Wallet does not support EIP-5792 and `wallet_sendCalls`, passing the `experimental_fallback` flag to `sendCalls` will allow Viem to fall back to executing the calls sequentially via `eth_sendTransaction`. example.tsconfig.ts import { parseEther } from 'viem' import { account, walletClient } from './config' const { id } = await walletClient.sendCalls({ account, calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], experimental_fallback: true, }) Returns[](https://viem.sh/docs/actions/wallet/sendCalls#returns) ----------------------------------------------------------------- `{ id: string, capabilities?: WalletCapabilities }` The identifier can be any arbitrary string. The only requirement is that for a given session, consumers should be able to call `getCallsStatus` with this identifier to retrieve a batch call status and call receipts. Parameters[](https://viem.sh/docs/actions/wallet/sendCalls#parameters) ----------------------------------------------------------------------- ### account[](https://viem.sh/docs/actions/wallet/sendCalls#account) * **Type:** `Account | Address | null` The Account to sign & broadcast the call from. If set to `null`, it is assumed that the wallet will handle filling the sender of the calls. Accepts a [JSON-RPC Account](https://viem.sh/docs/clients/wallet#json-rpc-accounts) . import { walletClient } from './config' const { id } = await walletClient.sendCalls({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], }) ### chain[](https://viem.sh/docs/actions/wallet/sendCalls#chain) * **Type:** `[Chain](https://viem.sh/docs/glossary/types#chain) ` * **Default:** `walletClient.chain` The target chain to broadcast the calls. import { mainnet } from 'viem/chains' import { walletClient } from './config' const { id } = await walletClient.sendCalls({ chain: mainnet, calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], }) ### calls[](https://viem.sh/docs/actions/wallet/sendCalls#calls) * **Type:** `Call[]` An array of calls to be signed and broadcasted. import { mainnet } from 'viem/chains' import { walletClient } from './config' const { id } = await walletClient.sendCalls({ chain: mainnet, calls: [ \ { \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('1') \ }, \ { \ data: '0xdeadbeef', \ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ }, \ ], }) #### calls.data[](https://viem.sh/docs/actions/wallet/sendCalls#callsdata) * **Type:** `Hex` Calldata to broadcast (typically a contract function selector with encoded arguments, or contract deployment bytecode). import { mainnet } from 'viem/chains' import { walletClient } from './config' const { id } = await walletClient.sendCalls({ chain: mainnet, calls: [ \ { \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('1') \ }, \ { \ data: '0xdeadbeef', \ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], }) When calling functions on contracts, it may be more convenient to pass in a [Contract Call](https://viem.sh/docs/actions/wallet/sendCalls#contract-calls) , providing the the `abi`, `functionName`, and `args` properties which will then be encoded into the appropriate `calls.data`. import { parseAbi } from 'viem' import { walletClient } from './config' const abi = parseAbi([\ 'function approve(address, uint256) returns (bool)',\ ]) const { id } = await walletClient.sendCalls({ calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ to: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi, \ functionName: 'approve',\ args: [\ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ 100n\ ],\ }\ ], }) #### calls.to[](https://viem.sh/docs/actions/wallet/sendCalls#callsto) * **Type:** `Address` Recipient address of the call. import { mainnet } from 'viem/chains' import { walletClient } from './config' const { id } = await walletClient.sendCalls({ chain: mainnet, calls: [ \ { \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('1') \ }, \ { \ data: '0xdeadbeef', \ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ },\ ], }) #### calls.value[](https://viem.sh/docs/actions/wallet/sendCalls#callsvalue) * **Type:** `Address` Value to send with the call. import { mainnet } from 'viem/chains' import { walletClient } from './config' const { id } = await walletClient.sendCalls({ chain: mainnet, calls: [ \ { \ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', \ value: parseEther('1') \ }, \ { \ data: '0xdeadbeef', \ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], }) #### calls.dataSuffix[](https://viem.sh/docs/actions/wallet/sendCalls#callsdatasuffix) * **Type:** Hex Data to append to the end of the calldata. Useful for adding a "domain" tag. example.ts const { id } = await walletClient.sendCalls({ calls: [\ {\ to: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\ abi,\ functionName: 'approve',\ args: [\ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ 100n\ ],\ dataSuffix: '0xdeadbeef'\ }\ ], }) ### capabilities[](https://viem.sh/docs/actions/wallet/sendCalls#capabilities) * **Type:** `WalletCapabilities` Capability metadata for the calls (e.g. specifying a paymaster). import { walletClient } from './config' const { id } = await walletClient.sendCalls({ calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], capabilities: { paymasterService: { url: 'https://...' } } }) ### forceAtomic[](https://viem.sh/docs/actions/wallet/sendCalls#forceatomic) * **Type:** `boolean` * **Default:** `false` Force the calls to be executed atomically. [See more](https://eips.ethereum.org/EIPS/eip-5792#call-execution-atomicity) import { walletClient } from './config' const { id } = await walletClient.sendCalls({ calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], forceAtomic: true, }) ### id[](https://viem.sh/docs/actions/wallet/sendCalls#id) * **Type:** `string` Attribute the call batch with an identifier. import { walletClient } from './config' const { id } = await walletClient.sendCalls({ calls: [\ {\ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\ value: parseEther('1')\ },\ {\ data: '0xdeadbeef',\ to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\ },\ ], id: '', }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/sendCalls.mdx) Copy page for AI Ask AI... ⌘ I --- # signTypedData · Viem [Skip to content](https://viem.sh/docs/actions/wallet/signTypedData#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K signTypedData ============= Signs typed data and calculates an Ethereum-specific signature in [https://eips.ethereum.org/EIPS/eip-712](https://eips.ethereum.org/EIPS/eip-712) : `sign(keccak256("\x19\x01" ‖ domainSeparator ‖ hashStruct(message)))` Usage[](https://viem.sh/docs/actions/wallet/signTypedData#usage) ----------------------------------------------------------------- example.tsdata.tsconfig.ts import { account, walletClient } from './config' import { domain, types } from './data' const signature = await walletClient.signTypedData({ account, domain, types, primaryType: 'Mail', message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ### Account Hoisting[](https://viem.sh/docs/actions/wallet/signTypedData#account-hoisting) If you do not wish to pass an `account` to every `signTypedData`, you can also hoist the Account on the Wallet Client (see `config.ts`). [Learn more](https://viem.sh/docs/clients/wallet#withaccount) . example.tsdata.tsconfig.ts (JSON-RPC Account)config.ts (Local Account) import { walletClient } from './config' import { domain, types } from './data' const signature = await walletClient.signTypedData({ domain, types, primaryType: 'Mail', message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) Returns[](https://viem.sh/docs/actions/wallet/signTypedData#returns) --------------------------------------------------------------------- `0x${string}` The signed data. Parameters[](https://viem.sh/docs/actions/wallet/signTypedData#parameters) --------------------------------------------------------------------------- ### account[](https://viem.sh/docs/actions/wallet/signTypedData#account) * **Type:** `Account | Address` The Account to use for signing. Accepts a [JSON-RPC Account](https://viem.sh/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . const signature = await walletClient.signTypedData({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', 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!', }, }) ### domain[](https://viem.sh/docs/actions/wallet/signTypedData#domain) **Type:** `TypedDataDomain` The typed data domain. const signature = await walletClient.signTypedData({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', 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!', }, }) ### types[](https://viem.sh/docs/actions/wallet/signTypedData#types) The type definitions for the typed data. const signature = await walletClient.signTypedData({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', 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!', }, }) ### primaryType[](https://viem.sh/docs/actions/wallet/signTypedData#primarytype) **Type:** Inferred `string`. The primary type to extract from `types` and use in `value`. const signature = await walletClient.signTypedData({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', 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!', }, }) ### message[](https://viem.sh/docs/actions/wallet/signTypedData#message) **Type:** Inferred from `types` & `primaryType`. const signature = await walletClient.signTypedData({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', 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!', }, }) Live Example[](https://viem.sh/docs/actions/wallet/signTypedData#live-example) ------------------------------------------------------------------------------- Check out the usage of `signTypedData` in the live [Sign Typed Data Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/signing_typed-data) below. JSON-RPC Methods[](https://viem.sh/docs/actions/wallet/signTypedData#json-rpc-methods) --------------------------------------------------------------------------------------- * JSON-RPC Accounts: * `[eth_signTypedData_v4](https://docs.metamask.io/guide/signing-data#signtypeddata-v4) ` * Local Accounts * Signs locally. No JSON-RPC request. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/actions/wallet/signTypedData.md) Copy page for AI Ask AI... ⌘ I --- # simulateContract · Viem [Skip to content](https://viem.sh/docs/contract/simulateContract#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K simulateContract ================ Simulates & validates a contract interaction. The `simulateContract` function **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](https://viem.sh/docs/contract/readContract) `, but also supports contract write functions. Internally, `simulateContract` uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData) . Usage[](https://viem.sh/docs/contract/simulateContract#usage) -------------------------------------------------------------- Below is a very basic example of how to simulate a write function on a contract (with no arguments). The `mint` function accepts no arguments, and returns a token ID. example.tsabi.tsconfig.ts import { account, publicClient } from './config' import { wagmiAbi } from './abi' const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account, }) ### Passing Arguments[](https://viem.sh/docs/contract/simulateContract#passing-arguments) If your function requires argument(s), you can pass them through with the `args` attribute. TypeScript types for `args` will be inferred from the function name & ABI, to guard you from inserting the wrong values. For example, the `mint` function name below requires a **tokenId** argument, and it is typed as `[number]`. example.tsabi.tsconfig.ts import { account, publicClient } from './config' import { wagmiAbi } from './abi' const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account, }) ### Pairing with `writeContract`[](https://viem.sh/docs/contract/simulateContract#pairing-with-writecontract) The `simulateContract` function also pairs well with `writeContract`. In the example below, we are **validating** if the contract write will be successful via `simulateContract`. If no errors are thrown, then we are all good. After that, we perform a contract write to execute the transaction. example.tsabi.tsconfig.ts import { account, walletClient, publicClient } from './config' import { wagmiAbi } from './abi' const { request } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account, }) const hash = await walletClient.writeContract(request) ### Handling Custom Errors[](https://viem.sh/docs/contract/simulateContract#handling-custom-errors) In the example below, we are **catching** a [custom error](https://blog.soliditylang.org/2021/04/21/custom-errors/) thrown by the `simulateContract`. It is important to include the custom error item in the contract `abi`. You can access the custom error through the `data` attribute of the error: example.tsabi.tsWagmiExample.solconfig.ts import { BaseError, ContractFunctionRevertedError } from 'viem'; import { account, walletClient, publicClient } from './config' import { wagmiAbi } from './abi' try { await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account, }) } catch (err) { if (err instanceof BaseError) { const revertError = err.walk(err => err instanceof ContractFunctionRevertedError) if (revertError instanceof ContractFunctionRevertedError) { const errorName = revertError.data?.errorName ?? '' // do something with `errorName` } } } ### State Overrides[](https://viem.sh/docs/contract/simulateContract#state-overrides) When using `simulateContract`, there sometimes needs to be an initial state change to make the transaction pass. A common use case would be an approval. For that, there are [state overrides](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-eth#eth-call) . In the example below, we are simulating sending a token on behalf of another user. To do this, we need to modify the state of the token contract to have maximum approve from the token owner. example.tscontract.tsconfig.ts import { account, publicClient } from './config' import { abi, address } from './contract' // Allowance slot: A 32 bytes hex string representing the allowance slot of the sender. const allowanceSlot = '0x....' // Max allowance: A 32 bytes hex string representing the maximum allowance (2^256 - 1) const maxAllowance = numberToHex(maxUint256) const { result } = await publicClient.simulateContract({ abi, address, account, functionName: 'transferFrom', args: [\ '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', \ account.address, \ 69420n\ ], stateOverride: [ \ { \ // modifying the state of the token contract\ address, \ stateDiff: [ \ { \ slot: allowanceSlot, \ value: maxAllowance, \ }, \ ], \ }, \ ], }) console.log(result) Output: true Return Value[](https://viem.sh/docs/contract/simulateContract#return-value) ---------------------------------------------------------------------------- The simulation result and write request. Type is inferred. Parameters[](https://viem.sh/docs/contract/simulateContract#parameters) ------------------------------------------------------------------------ ### address[](https://viem.sh/docs/contract/simulateContract#address) * **Type:** `[Address](https://viem.sh/docs/glossary/types#address) ` The contract address. const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' }) ### abi[](https://viem.sh/docs/contract/simulateContract#abi) * **Type:** `[Abi](https://viem.sh/docs/glossary/types#abi) ` The contract's ABI. const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' }) ### functionName[](https://viem.sh/docs/contract/simulateContract#functionname) * **Type:** `string` A function to extract from the ABI. const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' }) ### account[](https://viem.sh/docs/contract/simulateContract#account) * **Type:** `Account | Address | null` The Account to simulate the contract method from. Accepts a [JSON-RPC Account](https://viem.sh/docs/clients/wallet#json-rpc-accounts) or [Local Account (Private Key, etc)](https://viem.sh/docs/clients/wallet#local-accounts-private-key-mnemonic-etc) . If set to `null`, it is assumed that the transport will handle the filling the sender of the transaction. const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' }) ### accessList (optional)[](https://viem.sh/docs/contract/simulateContract#accesslist-optional) * **Type:** `[AccessList](https://viem.sh/docs/glossary/types#accesslist) ` The access list. const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], accessList: [{ \ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\ storageKeys: ['0x1'],\ }], account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' }) ### authorizationList (optional)[](https://viem.sh/docs/contract/simulateContract#authorizationlist-optional) * **Type:** `AuthorizationList` Signed EIP-7702 Authorization list. const authorization = await walletClient.signAuthorization({ contractAddress: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) const { result } = await publicClient.simulateContract({ address: account.address, abi: wagmiAbi, functionName: 'mint', args: [69420], authorizationList: [authorization], }) ### args (optional)[](https://viem.sh/docs/contract/simulateContract#args-optional) * **Type:** Inferred from ABI. Arguments to pass to function call. const { result } = await publicClient.simulateContract({ address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: wagmiAbi, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' }) ### blockNumber (optional)[](https://viem.sh/docs/contract/simulateContract#blocknumber-optional) * **Type:** `number` The block number to perform the read against. const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' blockNumber: 15121123n, }) ### blockTag (optional)[](https://viem.sh/docs/contract/simulateContract#blocktag-optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` The block tag to perform the read against. const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' blockTag: 'safe', }) ### dataSuffix (optional)[](https://viem.sh/docs/contract/simulateContract#datasuffix-optional) * **Type:** `Hex` Data to append to the end of the calldata. Useful for adding a ["domain" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f) . const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], dataSuffix: '0xdeadbeef' }) ### gas (optional)[](https://viem.sh/docs/contract/simulateContract#gas-optional) * **Type:** `bigint` The gas limit for the transaction. await walletClient.writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], gas: 69420n, }) ### gasPrice (optional)[](https://viem.sh/docs/contract/simulateContract#gasprice-optional) * **Type:** `bigint` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction) . const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' gasPrice: parseGwei('20'), }) ### maxFeePerGas (optional)[](https://viem.sh/docs/contract/simulateContract#maxfeepergas-optional) * **Type:** `bigint` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' maxFeePerGas: parseGwei('20'), }) ### maxPriorityFeePerGas (optional)[](https://viem.sh/docs/contract/simulateContract#maxpriorityfeepergas-optional) * **Type:** `bigint` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction) const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), }) ### nonce (optional)[](https://viem.sh/docs/contract/simulateContract#nonce-optional) * **Type:** `number` Unique number identifying this transaction. const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' nonce: 69 }) ### stateOverride (optional)[](https://viem.sh/docs/contract/simulateContract#stateoverride-optional) * **Type:** `[StateOverride](https://viem.sh/docs/glossary/types#stateoverride) ` The state override set is an optional address-to-state mapping, where each entry specifies some state to be ephemerally overridden prior to executing the call. > Note: By using state overrides, you simulate the contract based on a fake state. Using this is useful for testing purposes, but making a transaction based on the returned `request` object might fail regardless of the simulation result. const data = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' stateOverride: [ \ { \ address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', \ balance: parseEther('1'), \ stateDiff: [ \ { \ slot: '0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0', \ value: '0x00000000000000000000000000000000000000000000000000000000000001a4', \ }, \ ], \ } \ ], }) ### value (optional)[](https://viem.sh/docs/contract/simulateContract#value-optional) * **Type:** `number` Value in wei sent with this transaction. const { result } = await publicClient.simulateContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: wagmiAbi, functionName: 'mint', args: [69420], account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' value: parseEther('1') }) Live Example[](https://viem.sh/docs/contract/simulateContract#live-example) ---------------------------------------------------------------------------- Check out the usage of `simulateContract` in the live [Writing to Contracts Example](https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_writing-to-contracts) below. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/contract/simulateContract.md) Copy page for AI Ask AI... ⌘ I --- # concat · Viem [Skip to content](https://viem.sh/docs/utilities/concat#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K concat ====== Concatenates a set of hex values or byte arrays. Install[](https://viem.sh/docs/utilities/concat#install) --------------------------------------------------------- import { concat } from 'viem' Usage[](https://viem.sh/docs/utilities/concat#usage) ----------------------------------------------------- import { concat } from 'viem' concat(['0x00000069', '0x00000420']) // 0x0000006900000420 concat([new Uint8Array([69]), new Uint8Array([420])]) // Uint8Array [69, 420] Returns[](https://viem.sh/docs/utilities/concat#returns) --------------------------------------------------------- `Hex | ByteArray` The concatenated value. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/concat.md) Copy page for AI Ask AI... ⌘ I --- # formatUnits · Viem [Skip to content](https://viem.sh/docs/utilities/formatUnits#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K formatUnits =========== Divides a number by a given exponent of base 10 (10exponent), and formats it into a string representation of the number. Import[](https://viem.sh/docs/utilities/formatUnits#import) ------------------------------------------------------------ import { formatUnits } from 'viem' Usage[](https://viem.sh/docs/utilities/formatUnits#usage) ---------------------------------------------------------- import { formatUnits } from 'viem' formatUnits(420000000000n, 9) // '420' Returns[](https://viem.sh/docs/utilities/formatUnits#returns) -------------------------------------------------------------- `string` Parameters[](https://viem.sh/docs/utilities/formatUnits#parameters) -------------------------------------------------------------------- ### value[](https://viem.sh/docs/utilities/formatUnits#value) * **Type:** `bigint` The number to divide. ### exponent[](https://viem.sh/docs/utilities/formatUnits#exponent) * **Type:** `number` The exponent. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/formatUnits.md) Copy page for AI Ask AI... ⌘ I --- # formatGwei · Viem [Skip to content](https://viem.sh/docs/utilities/formatGwei#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K formatGwei ========== Converts numerical wei to a string representation of gwei. Import[](https://viem.sh/docs/utilities/formatGwei#import) ----------------------------------------------------------- import { formatGwei } from 'viem' Usage[](https://viem.sh/docs/utilities/formatGwei#usage) --------------------------------------------------------- import { formatGwei } from 'viem' formatGwei(1000000000n) // '1' Returns[](https://viem.sh/docs/utilities/formatGwei#returns) ------------------------------------------------------------- `string` Parameters[](https://viem.sh/docs/utilities/formatGwei#parameters) ------------------------------------------------------------------- ### value[](https://viem.sh/docs/utilities/formatGwei#value) * **Type:** `bigint` The wei value. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/formatGwei.md) Copy page for AI Ask AI... ⌘ I --- # compactSignatureToSignature · Viem [Skip to content](https://viem.sh/docs/utilities/compactSignatureToSignature#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K compactSignatureToSignature =========================== Parses a [EIP-2098](https://eips.ethereum.org/EIPS/eip-2098) compact signature into signature format. Import[](https://viem.sh/docs/utilities/compactSignatureToSignature#import) ---------------------------------------------------------------------------- import { compactSignatureToSignature } from 'viem' Usage[](https://viem.sh/docs/utilities/compactSignatureToSignature#usage) -------------------------------------------------------------------------- import { compactSignatureToSignature } from 'viem' compactSignatureToSignature({ r: '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90', yParityAndS: '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064', }) // { // r: '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90', // s: '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064', // yParity: 0, // } Returns[](https://viem.sh/docs/utilities/compactSignatureToSignature#returns) ------------------------------------------------------------------------------ `[Signature](https://viem.sh/docs/glossary/types#signature) ` The signature. Parameters[](https://viem.sh/docs/utilities/compactSignatureToSignature#parameters) ------------------------------------------------------------------------------------ ### compactSignature[](https://viem.sh/docs/utilities/compactSignatureToSignature#compactsignature) The compact signature. * **Type:** `[CompactSignature](https://viem.sh/docs/glossary/types#CompactSignature) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/compactSignatureToSignature.md) Copy page for AI Ask AI... ⌘ I --- # extractChain · Viem [Skip to content](https://viem.sh/docs/utilities/extractChain#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K extractChain ============ Extracts a type-safe chain by ID from a set of chains. Usage[](https://viem.sh/docs/utilities/extractChain#usage) ----------------------------------------------------------- import { extractChain } from 'viem' import { mainnet, base, optimism, zora } from 'viem/chains' const optimism = extractChain({ chains: [mainnet, base, optimism, zora], id: 10, }) optimism.id // ^? (property) id: 10 optimism.name // ^? (property) name: "OP Mainnet" It is also possible to use **all chains** from the `viem/chains` module: import { extractChain } from 'viem' import { mainnet, base, optimism, zora } from 'viem/chains' import * as chains from 'viem/chains' const optimism = extractChain({ chains: [mainnet, base, optimism, zora], chains: Object.values(chains), id: 10, }) optimism.id // ^? (property) id: 10 optimism.name // ^? (property) name: "OP Mainnet" Returns[](https://viem.sh/docs/utilities/extractChain#returns) --------------------------------------------------------------- * **Type:** `Chain` (inferred) The extracted chain. Parameters[](https://viem.sh/docs/utilities/extractChain#parameters) --------------------------------------------------------------------- ### chains[](https://viem.sh/docs/utilities/extractChain#chains) * **Type:** `readonly Chain[]` The set of chains where the chain will be extracted from. ### id[](https://viem.sh/docs/utilities/extractChain#id) * **Type:** `number` The ID of the chain to extract. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/extractChain.md) Copy page for AI Ask AI... ⌘ I --- # parseEther · Viem [Skip to content](https://viem.sh/docs/utilities/parseEther#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K parseEther ========== Converts a string representation of ether to numerical wei. Import[](https://viem.sh/docs/utilities/parseEther#import) ----------------------------------------------------------- import { parseEther } from 'viem' Usage[](https://viem.sh/docs/utilities/parseEther#usage) --------------------------------------------------------- import { parseEther } from 'viem' parseEther('420') // 420000000000000000000n Returns[](https://viem.sh/docs/utilities/parseEther#returns) ------------------------------------------------------------- `bigint` Parameters[](https://viem.sh/docs/utilities/parseEther#parameters) ------------------------------------------------------------------- ### value[](https://viem.sh/docs/utilities/parseEther#value) * **Type:** `string` The string representation of ether. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/parseEther.md) Copy page for AI Ask AI... ⌘ I --- # isAddressEqual · Viem [Skip to content](https://viem.sh/docs/utilities/isAddressEqual#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K isAddressEqual ============== Checks if the given addresses (checksummed) are equal. Import[](https://viem.sh/docs/utilities/isAddressEqual#import) --------------------------------------------------------------- import { isAddressEqual } from 'viem' Usage[](https://viem.sh/docs/utilities/isAddressEqual#usage) ------------------------------------------------------------- import { isAddressEqual } from 'viem' isAddressEqual('0xa5cc3c03994db5b0d9a5eEdD10Cabab0813678ac', '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC') // true Returns[](https://viem.sh/docs/utilities/isAddressEqual#returns) ----------------------------------------------------------------- `boolean` Whether or not the addresses are equal. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/isAddressEqual.md) Copy page for AI Ask AI... ⌘ I --- # fromRlp · Viem [Skip to content](https://viem.sh/docs/utilities/fromRlp#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K fromRlp ======= Decodes a [Recursive-Length Prefix (RLP)](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp) value into a decoded hex value or byte array. Import[](https://viem.sh/docs/utilities/fromRlp#import) -------------------------------------------------------- import { fromRlp } from 'viem' Usage[](https://viem.sh/docs/utilities/fromRlp#usage) ------------------------------------------------------ import { fromRlp } from 'viem' fromRlp('0x850123456789', 'hex') // "0x123456789" fromRlp('0xc67f7f838081e8', 'hex') // ['0x7f', '0x7f', '0x8081e8'] fromRlp('0x89010203040506070809', 'bytes') // Uint8Array [1, 2, 3, 4, 5, 6, 7, 8, 9] fromRlp(new Uint8Array ([133, 1, 35, 69, 103, 137]), 'hex') // "0x123456789" Returns[](https://viem.sh/docs/utilities/fromRlp#returns) ---------------------------------------------------------- `Hex | ByteArray` The hex value or byte array. Parameters[](https://viem.sh/docs/utilities/fromRlp#parameters) ---------------------------------------------------------------- ### value[](https://viem.sh/docs/utilities/fromRlp#value) * **Type:** `Hex | ByteArray` The RLP value to decode. ### to[](https://viem.sh/docs/utilities/fromRlp#to) * **Type:** `"bytes" | "hex"` The output type. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/fromRlp.md) Copy page for AI Ask AI... ⌘ I --- # hashMessage · Viem [Skip to content](https://viem.sh/docs/utilities/hashMessage#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K hashMessage =========== Calculates an Ethereum-specific hash in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191) : `keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))`. Import[](https://viem.sh/docs/utilities/hashMessage#import) ------------------------------------------------------------ import { hashMessage } from 'viem' Usage[](https://viem.sh/docs/utilities/hashMessage#usage) ---------------------------------------------------------- import { hashMessage } from 'viem' hashMessage('hello world') // 0xd9eba16ed0ecae432b71fe008c98cc872bb4cc214d3220a36f365326cf807d68 // Hash a hex data value. hashMessage({ raw: '0x68656c6c6f20776f726c64' }) // 0xd9eba16ed0ecae432b71fe008c98cc872bb4cc214d3220a36f365326cf807d68 // Hash a bytes data value. hashMessage({ raw: Uint8Array.from([\ 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100,\ ])}) // 0xd9eba16ed0ecae432b71fe008c98cc872bb4cc214d3220a36f365326cf807d68 Returns[](https://viem.sh/docs/utilities/hashMessage#returns) -------------------------------------------------------------- `[Hex](https://viem.sh/docs/glossary/types#hex) ` The hashed message. Parameters[](https://viem.sh/docs/utilities/hashMessage#parameters) -------------------------------------------------------------------- ### message[](https://viem.sh/docs/utilities/hashMessage#message) Message to hash. * **Type:** `string | { raw: Hex | ByteArray }` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/hashMessage.md) Copy page for AI Ask AI... ⌘ I --- # formatEther · Viem [Skip to content](https://viem.sh/docs/utilities/formatEther#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K formatEther =========== Converts numerical wei to a string representation of ether. Import[](https://viem.sh/docs/utilities/formatEther#import) ------------------------------------------------------------ import { formatEther } from 'viem' Usage[](https://viem.sh/docs/utilities/formatEther#usage) ---------------------------------------------------------- import { formatEther } from 'viem' formatEther(1000000000000000000n) // '1' Returns[](https://viem.sh/docs/utilities/formatEther#returns) -------------------------------------------------------------- `string` Parameters[](https://viem.sh/docs/utilities/formatEther#parameters) -------------------------------------------------------------------- ### value[](https://viem.sh/docs/utilities/formatEther#value) * **Type:** `bigint` The wei value. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/formatEther.md) Copy page for AI Ask AI... ⌘ I --- # isBytes · Viem [Skip to content](https://viem.sh/docs/utilities/isBytes#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K isBytes ======= Checks whether the value is a byte array or not. Install[](https://viem.sh/docs/utilities/isBytes#install) ---------------------------------------------------------- import { isBytes } from 'viem' Usage[](https://viem.sh/docs/utilities/isBytes#usage) ------------------------------------------------------ import { isBytes } from 'viem' isBytes(new Uint8Array([1, 69, 420])) // true isBytes([1, 69, 420]) // false Returns[](https://viem.sh/docs/utilities/isBytes#returns) ---------------------------------------------------------- `boolean` Returns truthy is the value is a byte array. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/isBytes.md) Copy page for AI Ask AI... ⌘ I --- # fromBlobs · Viem [Skip to content](https://viem.sh/docs/utilities/fromBlobs#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K fromBlobs ========= Transforms Viem-shaped blobs into the originating data. Import[](https://viem.sh/docs/utilities/fromBlobs#import) ---------------------------------------------------------- import { fromBlobs } from 'viem' Usage[](https://viem.sh/docs/utilities/fromBlobs#usage) -------------------------------------------------------- example.ts import { fromBlobs } from 'viem' const data = fromBlobs({ blobs: ['0x...'] }) Returns[](https://viem.sh/docs/utilities/fromBlobs#returns) ------------------------------------------------------------ `Hex | ByteArray` Data extracted from blobs. Parameters[](https://viem.sh/docs/utilities/fromBlobs#parameters) ------------------------------------------------------------------ ### blobs[](https://viem.sh/docs/utilities/fromBlobs#blobs) * **Type:** `Hex[] | ByteArray[]` Transforms blobs into the originating data. import { fromBlobs } from 'viem' const data = fromBlobs({ blobs: ['0x...'] }) ### to[](https://viem.sh/docs/utilities/fromBlobs#to) * **Type:** `"bytes" | "hex"` The output type. import { fromBlobs } from 'viem' const data = fromBlobs({ blobs: ['0x...'], to: 'bytes' }) data [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/fromBlobs.md) Copy page for AI Ask AI... ⌘ I --- # parseGwei · Viem [Skip to content](https://viem.sh/docs/utilities/parseGwei#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K parseGwei ========= Converts a string representation of gwei to numerical wei. Import[](https://viem.sh/docs/utilities/parseGwei#import) ---------------------------------------------------------- import { parseGwei } from 'viem' Usage[](https://viem.sh/docs/utilities/parseGwei#usage) -------------------------------------------------------- import { parseGwei } from 'viem' parseGwei('420') // 420000000000n Returns[](https://viem.sh/docs/utilities/parseGwei#returns) ------------------------------------------------------------ `bigint` Parameters[](https://viem.sh/docs/utilities/parseGwei#parameters) ------------------------------------------------------------------ ### value[](https://viem.sh/docs/utilities/parseGwei#value) * **Type:** `string` The string representation of gwei. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/parseGwei.md) Copy page for AI Ask AI... ⌘ I --- # pad · Viem [Skip to content](https://viem.sh/docs/utilities/pad#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K pad === Pads a hex value or byte array with leading or trailing zeros. Install[](https://viem.sh/docs/utilities/pad#install) ------------------------------------------------------ import { pad } from 'viem' Usage[](https://viem.sh/docs/utilities/pad#usage) -------------------------------------------------- By default, `pad` will pad a value with leading zeros up to 32 bytes (64 hex chars). import { pad } from 'viem' pad('0xa4e12a45') // 0x00000000000000000000000000000000000000000000000000000000a4e12a45 pad(new Uint8Array([1, 122, 51, 123])) // Uint8Array [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,122,51,123] Returns[](https://viem.sh/docs/utilities/pad#returns) ------------------------------------------------------ `Hex | ByteArray` The value with padded zeros. Parameters[](https://viem.sh/docs/utilities/pad#parameters) ------------------------------------------------------------ ### dir[](https://viem.sh/docs/utilities/pad#dir) * **Type:** `"left" | "right"` * **Default:** `"left"` The direction in which to pad the zeros – either leading (left), or trailing (right). pad('0xa4e12a45', { dir: 'right' }) // 0xa4e12a4500000000000000000000000000000000000000000000000000000000 ### size[](https://viem.sh/docs/utilities/pad#size) * **Type:** `number` * **Default:** `32` Size (in bytes) of the targeted value. pad('0xa4e12a45', { size: 16 }) // 0x000000000000000000000000a4e12a45 [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/pad.md) Copy page for AI Ask AI... ⌘ I --- # parseErc6492Signature · Viem [Skip to content](https://viem.sh/docs/utilities/parseErc6492Signature#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K parseErc6492Signature ===================== Parses a hex-formatted [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492) flavoured signature. If the signature is not in ERC-6492 format, then the underlying (original) signature is returned. Import[](https://viem.sh/docs/utilities/parseErc6492Signature#import) ---------------------------------------------------------------------- import { parseErc6492Signature } from 'viem/utils' Usage[](https://viem.sh/docs/utilities/parseErc6492Signature#usage) -------------------------------------------------------------------- import { parseErc6492Signature } from 'viem/utils' const { address, data, signature, } = parseErc6492Signature('0x000000000000000000000000cafebabecafebabecafebabecafebabecafebabe000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000004deadbeef000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000041a461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b000000000000000000000000000000000000000000000000000000000000006492649264926492649264926492649264926492649264926492649264926492') /** * { * address: '0xCafEBAbECAFEbAbEcaFEbabECAfebAbEcAFEBaBe', * data: '0xdeadbeef', * signature: '0xa461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b' * } */ Returns[](https://viem.sh/docs/utilities/parseErc6492Signature#returns) ------------------------------------------------------------------------ `ParseErc6492SignatureReturnType` The ERC-6492 signature components. Parameters[](https://viem.sh/docs/utilities/parseErc6492Signature#parameters) ------------------------------------------------------------------------------ ### signature[](https://viem.sh/docs/utilities/parseErc6492Signature#signature) * **Type:** `[Hex](https://viem.sh/docs/glossary/types#hex) ` The ERC-6492 signature in hex format. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/parseErc6492Signature.md) Copy page for AI Ask AI... ⌘ I --- # recoverAddress · Viem [Skip to content](https://viem.sh/docs/utilities/recoverAddress#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K recoverAddress ============== Recovers the original signing address from a hash & signature. Usage[](https://viem.sh/docs/utilities/recoverAddress#usage) ------------------------------------------------------------- example.ts import { recoverAddress } from 'viem' const address = await recoverAddress({ hash: '0xd9eba16ed0ecae432b71fe008c98cc872bb4cc214d3220a36f365326cf807d68', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c' }) // 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 Returns[](https://viem.sh/docs/utilities/recoverAddress#returns) ----------------------------------------------------------------- `[Address](https://viem.sh/docs/glossary/types#address) ` The signing address. Parameters[](https://viem.sh/docs/utilities/recoverAddress#parameters) ----------------------------------------------------------------------- ### hash[](https://viem.sh/docs/utilities/recoverAddress#hash) * **Type:** `string` The hash that was signed. const address = await recoverAddress({ hash: '0xd9eba16ed0ecae432b71fe008c98cc872bb4cc214d3220a36f365326cf807d68', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c' }) ### signature[](https://viem.sh/docs/utilities/recoverAddress#signature) * **Type:** `Hex | ByteArray | Signature` The signature of the hash. const address = await recoverAddress({ hash: '0xd9eba16ed0ecae432b71fe008c98cc872bb4cc214d3220a36f365326cf807d68', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c' }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/recoverAddress.md) Copy page for AI Ask AI... ⌘ I --- # isHash · Viem [Skip to content](https://viem.sh/docs/utilities/isHash#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K isHash ====== Checks if a string is a valid 32-byte hex hash. Import[](https://viem.sh/docs/utilities/isHash#import) ------------------------------------------------------- import { isHash } from 'viem' Usage[](https://viem.sh/docs/utilities/isHash#usage) ----------------------------------------------------- import { isHash } from 'viem' isHash('0xd9eba16ed0ecae432b71fe008c98cc872bb4cc214d3220a36f365326cf807d68') // true isHash('0xa5cc3c03994db5b0d9a5eEdD10Cabab0813678ac') // false Returns[](https://viem.sh/docs/utilities/isHash#returns) --------------------------------------------------------- `boolean` Whether the string is a valid 32-byte hex hash. Parameters[](https://viem.sh/docs/utilities/isHash#parameters) --------------------------------------------------------------- ### hash[](https://viem.sh/docs/utilities/isHash#hash) The string to check. * **Type:** `string` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/isHash.md) Copy page for AI Ask AI... ⌘ I --- # isAddress · Viem [Skip to content](https://viem.sh/docs/utilities/isAddress#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K isAddress ========= Checks if the address is valid. By default, it also verifies whether the address is in checksum format. Import[](https://viem.sh/docs/utilities/isAddress#import) ---------------------------------------------------------- import { isAddress } from 'viem' Usage[](https://viem.sh/docs/utilities/isAddress#usage) -------------------------------------------------------- import { isAddress } from 'viem' isAddress('0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC') // true Returns[](https://viem.sh/docs/utilities/isAddress#returns) ------------------------------------------------------------ `boolean` Whether or not the address is valid. Parameters[](https://viem.sh/docs/utilities/isAddress#parameters) ------------------------------------------------------------------ ### address[](https://viem.sh/docs/utilities/isAddress#address) * **Type:** `string` An Ethereum address. ### options.strict (optional)[](https://viem.sh/docs/utilities/isAddress#optionsstrict-optional) * **Type:** `boolean` * **Default:** `true` Enables strict mode. If enabled, it also verifies whether the address is in checksum format. isAddress('0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac', { strict: false }) // true isAddress('0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac', { strict: true }) // false isAddress('lol', { strict: false }) // false [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/isAddress.md) Copy page for AI Ask AI... ⌘ I --- # keccak256 · Viem [Skip to content](https://viem.sh/docs/utilities/keccak256#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K keccak256 ========= Calculates the [Keccak256](https://en.wikipedia.org/wiki/SHA-3) hash of a byte array or hex value. This function is a re-export of `keccak_256` from `[@noble/hashes](https://github.com/paulmillr/noble-hashes) ` – an audited & minimal JS hashing library. Install[](https://viem.sh/docs/utilities/keccak256#install) ------------------------------------------------------------ import { keccak256 } from 'viem' Usage[](https://viem.sh/docs/utilities/keccak256#usage) -------------------------------------------------------- import { keccak256 } from 'viem' keccak256(new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]) // 0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0 keccak256('0xdeadbeef') // 0xd4fd4e189132273036449fc9e11198c739161b4c0116a9a2dccdfa1c492006f1 // hash utf-8 string keccak256(toHex('hello world')) // 0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0 Returns[](https://viem.sh/docs/utilities/keccak256#returns) ------------------------------------------------------------ `Hex | ByteArray` The hashed value. Parameters[](https://viem.sh/docs/utilities/keccak256#parameters) ------------------------------------------------------------------ ### value[](https://viem.sh/docs/utilities/keccak256#value) * **Type:** `Hex | ByteArray` The hex value or byte array to hash. ### to[](https://viem.sh/docs/utilities/keccak256#to) * **Type:** `"bytes" | "hex"` * **Default:** `"hex"` The output type. import { keccak256 } from 'viem' keccak256( new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33], 'bytes' ) // Uint8Array [62, 162, 241, 208, 171, 243, 252, 102, 207, 41, 238, 187, 112, 203, 212, 231, 254, 118, 46, 248, 160, 155, 204, 6, 200, 237, 246, 65, 35, 10, 254, 192] [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/keccak256.md) Copy page for AI Ask AI... ⌘ I --- # getAddress · Viem [Skip to content](https://viem.sh/docs/utilities/getAddress#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K getAddress ========== Converts an address into an address that is [checksum encoded](https://eips.ethereum.org/EIPS/eip-55) . Supports [EIP-1191](https://eips.ethereum.org/EIPS/eip-1191) . Import[](https://viem.sh/docs/utilities/getAddress#import) ----------------------------------------------------------- import { getAddress } from 'viem' Usage[](https://viem.sh/docs/utilities/getAddress#usage) --------------------------------------------------------- import { getAddress } from 'viem' getAddress('0xa5cc3c03994db5b0d9a5eEdD10Cabab0813678ac') // '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC' Returns[](https://viem.sh/docs/utilities/getAddress#returns) ------------------------------------------------------------- `[Address](https://viem.sh/docs/glossary/types#address) ` The checksummed address. Parameters[](https://viem.sh/docs/utilities/getAddress#parameters) ------------------------------------------------------------------- ### address[](https://viem.sh/docs/utilities/getAddress#address) * **Type:** `string` An Ethereum address. ### chainId (optional)[](https://viem.sh/docs/utilities/getAddress#chainid-optional) * **Type:** `number` The chain ID of the network the address is on. Complies to [EIP-1191](https://eips.ethereum.org/EIPS/eip-1191) . [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/getAddress.md) Copy page for AI Ask AI... ⌘ I --- # parseUnits · Viem [Skip to content](https://viem.sh/docs/utilities/parseUnits#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K parseUnits ========== Multiplies a string representation of a number by a given exponent of base 10 (10exponent). Import[](https://viem.sh/docs/utilities/parseUnits#import) ----------------------------------------------------------- import { parseUnits } from 'viem' Usage[](https://viem.sh/docs/utilities/parseUnits#usage) --------------------------------------------------------- import { parseUnits } from 'viem' parseUnits('420', 9) // 420000000000n Returns[](https://viem.sh/docs/utilities/parseUnits#returns) ------------------------------------------------------------- `bigint` Parameters[](https://viem.sh/docs/utilities/parseUnits#parameters) ------------------------------------------------------------------- ### value[](https://viem.sh/docs/utilities/parseUnits#value) * **Type:** `string` The string representation of the number to multiply. ### exponent[](https://viem.sh/docs/utilities/parseUnits#exponent) * **Type:** `number` The exponent. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/parseUnits.md) Copy page for AI Ask AI... ⌘ I --- # isErc6492Signature · Viem [Skip to content](https://viem.sh/docs/utilities/isErc6492Signature#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K isErc6492Signature ================== Checks whether the signature is in [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492) format. Import[](https://viem.sh/docs/utilities/isErc6492Signature#import) ------------------------------------------------------------------- import { isErc6492Signature } from 'viem/utils' Usage[](https://viem.sh/docs/utilities/isErc6492Signature#usage) ----------------------------------------------------------------- import { isErc6492Signature } from 'viem/utils' const result = isErc6492Signature('0x000000000000000000000000cafebabecafebabecafebabecafebabecafebabe000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000004deadbeef000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000041a461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b000000000000000000000000000000000000000000000000000000000000006492649264926492649264926492649264926492649264926492649264926492') Returns[](https://viem.sh/docs/utilities/isErc6492Signature#returns) --------------------------------------------------------------------- `boolean` Whether the signature is in ERC-6492 format. Parameters[](https://viem.sh/docs/utilities/isErc6492Signature#parameters) --------------------------------------------------------------------------- ### signature[](https://viem.sh/docs/utilities/isErc6492Signature#signature) * **Type:** `[Hex](https://viem.sh/docs/glossary/types#hex) ` The signature to check. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/isErc6492Signature.md) Copy page for AI Ask AI... ⌘ I --- # isHex · Viem [Skip to content](https://viem.sh/docs/utilities/isHex#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K isHex ===== Checks whether the value is a hex value or not. Install[](https://viem.sh/docs/utilities/isHex#install) -------------------------------------------------------- import { isHex } from 'viem' Usage[](https://viem.sh/docs/utilities/isHex#usage) ---------------------------------------------------- import { isHex } from 'viem' isHex('0x1a4') // true isHex('0x1a4z') isHex('foo') // false Returns[](https://viem.sh/docs/utilities/isHex#returns) -------------------------------------------------------- `boolean` Returns truthy is the value is a hex value. Parameters[](https://viem.sh/docs/utilities/isHex#parameters) -------------------------------------------------------------- ### value[](https://viem.sh/docs/utilities/isHex#value) * **Type:** `unknown` The value to check. isHex( '0x1a4' ) // true ### options.strict[](https://viem.sh/docs/utilities/isHex#optionsstrict) * **Type:** `boolean` * **Default:** `true` When enabled, checks if the value strictly consists of only hex characters (`"0x[0-9a-fA-F]*"`). When disabled, checks if the value loosely matches hex format (`value.startsWith('0x')`). isHex('0xlol', { strict: false }) // true isHex('0xlol', { strict: true }) // false isHex('lol', { strict: false }) // false [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/isHex.md) Copy page for AI Ask AI... ⌘ I --- # recoverPublicKey · Viem [Skip to content](https://viem.sh/docs/utilities/recoverPublicKey#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K recoverPublicKey ================ Recovers the original signing 64-byte public key from a hash & signature. Usage[](https://viem.sh/docs/utilities/recoverPublicKey#usage) --------------------------------------------------------------- example.ts import { recoverPublicKey } from 'viem' const publicKey = await recoverPublicKey({ hash: '0xd9eba16ed0ecae432b71fe008c98cc872bb4cc214d3220a36f365326cf807d68', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c' }) // 0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5 Returns[](https://viem.sh/docs/utilities/recoverPublicKey#returns) ------------------------------------------------------------------- `[Hex](https://viem.sh/docs/glossary/types#hex) ` The signing public key. Parameters[](https://viem.sh/docs/utilities/recoverPublicKey#parameters) ------------------------------------------------------------------------- ### hash[](https://viem.sh/docs/utilities/recoverPublicKey#hash) * **Type:** `string` The hash that was signed. const publicKey = await recoverPublicKey({ hash: '0xd9eba16ed0ecae432b71fe008c98cc872bb4cc214d3220a36f365326cf807d68', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c' }) ### signature[](https://viem.sh/docs/utilities/recoverPublicKey#signature) * **Type:** `Hex | ByteArray | Signature` The signature of the hash. const publicKey = await recoverPublicKey({ hash: '0xd9eba16ed0ecae432b71fe008c98cc872bb4cc214d3220a36f365326cf807d68', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c' }) [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/recoverPublicKey.md) Copy page for AI Ask AI... ⌘ I --- # parseTransaction · Viem [Skip to content](https://viem.sh/docs/utilities/parseTransaction#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K parseTransaction ================ Parses a serialized RLP-encoded transaction. Supports signed & unsigned EIP-1559, EIP-2930 and Legacy Transactions. Import[](https://viem.sh/docs/utilities/parseTransaction#import) ----------------------------------------------------------------- import { parseTransaction } from 'viem' Usage[](https://viem.sh/docs/utilities/parseTransaction#usage) --------------------------------------------------------------- import { parseTransaction } from 'viem' const transaction = parseTransaction('0x02ef0182031184773594008477359400809470997970c51812dc3a010c7d01b50e0d17dc79c8880de0b6b3a764000080c0') Returns[](https://viem.sh/docs/utilities/parseTransaction#returns) ------------------------------------------------------------------- `TransactionSerializable` The parsed transaction object. Parameters[](https://viem.sh/docs/utilities/parseTransaction#parameters) ------------------------------------------------------------------------- ### serializedTransaction[](https://viem.sh/docs/utilities/parseTransaction#serializedtransaction) * **Type:** `Hex` The serialized transaction. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/parseTransaction.md) Copy page for AI Ask AI... ⌘ I --- # parseSignature · Viem [Skip to content](https://viem.sh/docs/utilities/parseSignature#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K parseSignature ============== Parses a hex formatted signature into a structured ("split") signature. Import[](https://viem.sh/docs/utilities/parseSignature#import) --------------------------------------------------------------- import { parseSignature } from 'viem' Usage[](https://viem.sh/docs/utilities/parseSignature#usage) ------------------------------------------------------------- import { parseSignature } from 'viem' parseSignature('0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c') /** * { * r: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf', * s: '0x4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8', * yParity: 1 * } */ Returns[](https://viem.sh/docs/utilities/parseSignature#returns) ----------------------------------------------------------------- `[Signature](https://viem.sh/docs/glossary/types#signature) ` The structured ("split") signature. Parameters[](https://viem.sh/docs/utilities/parseSignature#parameters) ----------------------------------------------------------------------- ### signatureHex[](https://viem.sh/docs/utilities/parseSignature#signaturehex) The signature in hex format. * **Type:** `[Hex](https://viem.sh/docs/glossary/types#hex) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/parseSignature.md) Copy page for AI Ask AI... ⌘ I --- # parseCompactSignature · Viem [Skip to content](https://viem.sh/docs/utilities/parseCompactSignature#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K parseCompactSignature ===================== Parses a hex formatted compact signature into a structured ("split") compact signature. Import[](https://viem.sh/docs/utilities/parseCompactSignature#import) ---------------------------------------------------------------------- import { parseCompactSignature } from 'viem' Usage[](https://viem.sh/docs/utilities/parseCompactSignature#usage) -------------------------------------------------------------------- import { parseCompactSignature } from 'viem' parseCompactSignature('0x9328da16089fcba9bececa81663203989f2df5fe1faa6291a45381c81bd17f76939c6d6b623b42da56557e5e734a43dc83345ddfadec52cbe24d0cc64f550793') /** * { * r: '0x9328da16089fcba9bececa81663203989f2df5fe1faa6291a45381c81bd17f76', * yParityAndS: '0x939c6d6b623b42da56557e5e734a43dc83345ddfadec52cbe24d0cc64f550793' * } */ Returns[](https://viem.sh/docs/utilities/parseCompactSignature#returns) ------------------------------------------------------------------------ `[CompactSignature](https://viem.sh/docs/glossary/types#compactsignature) ` The structured ("split") compact signature. Parameters[](https://viem.sh/docs/utilities/parseCompactSignature#parameters) ------------------------------------------------------------------------------ ### signatureHex[](https://viem.sh/docs/utilities/parseCompactSignature#signaturehex) The compact signature in hex format. * **Type:** `[Hex](https://viem.sh/docs/glossary/types#hex) ` [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/parseCompactSignature.md) Copy page for AI Ask AI... ⌘ I --- # size · Viem [Skip to content](https://viem.sh/docs/utilities/size#vocs-content) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) [![Logo](https://viem.sh/icon-light.png)![Logo](https://viem.sh/icon-dark.png)](https://viem.sh/) Search... ⌘ K size ==== Retrieves the size of the value (in bytes). Install[](https://viem.sh/docs/utilities/size#install) ------------------------------------------------------- import { size } from 'viem' Usage[](https://viem.sh/docs/utilities/size#usage) --------------------------------------------------- import { size } from 'viem' size('0xa4') // 1 size('0xa4e12a45') // 4 size(new Uint8Array([1, 122, 51, 123])) // 4 Returns[](https://viem.sh/docs/utilities/size#returns) ------------------------------------------------------- `number` The size of the value (in bytes). Parameters[](https://viem.sh/docs/utilities/size#parameters) ------------------------------------------------------------- ### value[](https://viem.sh/docs/utilities/size#value) * **Type:** `[Hex](https://viem.sh/docs/glossary/types#hex) ` | `ByteArray` The value (hex or byte array) to retrieve the size of. [Suggest changes to this page](https://github.com/wevm/viem/edit/main/site/pages/docs/utilities/size.md) Copy page for AI Ask AI... ⌘ I ---