Skip to content

createMemoryClient

createMemoryClient(options?): object

A local EVM instance running in JavaScript. Similar to Anvil in your browser It wraps the viem public client and test client

Parameters

options?: BaseClientOptions

Returns

object

_tevm

_tevm: object & Eip1193RequestProvider & TevmActionsApi & object

Type declaration

extend()

readonly extend: <TExtension>(decorator) => BaseClient<"fork" | "normal", object & TExtension>

Extends the base client with additional functionality. This enables optimal code splitting and extensibility

Type parameters

TExtension extends Record<string, any>

Parameters

decorator

Returns

BaseClient<"fork" | "normal", object & TExtension>

forkTransport?

optional readonly forkTransport: object

Client to make json rpc requests to a forked node

Example
const client = createMemoryClient({ request: eip1193RequestFn })
forkTransport.request

request: EIP1193RequestFn

getReceiptsManager()

readonly getReceiptsManager: () => Promise<ReceiptsManager>

Interface for querying receipts and historical state

Returns

Promise<ReceiptsManager>

getTxPool()

readonly getTxPool: () => Promise<TxPool>

Gets the pool of pending transactions to be included in next block

Returns

Promise<TxPool>

getVm()

readonly getVm: () => Promise<Vm>

Internal instance of the VM. Can be used for lower level operations. Normally not recomended to use unless building libraries or extensions on top of Tevm.

Returns

Promise<Vm>

impersonatedAccount

readonly impersonatedAccount: undefined | `0x${string}`

The currently impersonated account. This is only used in fork mode

logger

readonly logger: Logger

The logger instance

miningConfig

readonly miningConfig: MiningConfig

The configuration for mining. Defaults to ‘auto'

  • 'auto’ will mine a block on every transaction
  • ’interval’ will mine a block every interval milliseconds
  • ’manual’ will not mine a block automatically and requires a manual call to mineBlock
mode

readonly mode: "fork" | "normal"

The mode the current client is running in fork mode will fetch and cache all state from the block forked from the provided URL normal mode will not fetch any state and will only run the EVM in memory

Example
let client = createMemoryClient()
console.log(client.mode) // 'normal'
client = createMemoryClient({ forkUrl: 'https://mainnet.infura.io/v3/your-api-key' })
console.log(client.mode) // 'fork'
ready()

readonly ready: () => Promise<true>

Returns promise that resulves when the client is ready The client is usable without calling this method but may have extra latency on the first call from initialization

Example
const client = createMemoryClient()
await client.ready()
Returns

Promise<true>

setImpersonatedAccount()

readonly setImpersonatedAccount: (address) => void

Sets the account to impersonate. This will allow the client to act as if it is that account On Ethereum JSON_RPC endpoints. Pass in undefined to stop impersonating

Parameters

address: undefined | `0x${string}`

Returns

void

Type declaration

request

request: EIP1193RequestFn

send

send: TevmJsonRpcRequestHandler

sendBulk

sendBulk: TevmJsonRpcBulkRequestHandler

account

account: undefined

The Account of the Client.

batch?

optional batch: object

Flags for batch settings.

batch.multicall?

optional multicall: boolean | object

Toggle to enable eth_call multicall aggregation.

cacheTime

cacheTime: number

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

call()

call: (parameters) => Promise<CallReturnType>

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

Example

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

Parameters

parameters: CallParameters<undefined | Chain>

Returns

Promise<CallReturnType>

ccipRead?

optional ccipRead: false | object

CCIP Read configuration.

chain

chain: undefined

Chain for the client.

createBlockFilter()

createBlockFilter: () => Promise<object>

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

Example

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

Returns

Promise<object>

id

id: `0x${string}`

request

request: EIP1193RequestFn<readonly [object, object, object]>

type

type: "block"

createContractEventFilter()

createContractEventFilter: <TAbi, TEventName, TArgs, TStrict, TFromBlock, TToBlock>(args) => Promise<CreateContractEventFilterReturnType<TAbi, TEventName, TArgs, TStrict, TFromBlock, TToBlock>>

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

Example

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

Type parameters

TAbi extends Abi | readonly unknown[]

TEventName extends undefined | string

TArgs extends undefined | Record<string, unknown> | readonly unknown[]

TStrict extends undefined | boolean = undefined

TFromBlock extends undefined | bigint | BlockTag = undefined

TToBlock extends undefined | bigint | BlockTag = undefined

Parameters

args: CreateContractEventFilterParameters<TAbi, TEventName, TArgs, TStrict, TFromBlock, TToBlock>

CreateContractEventFilterParameters

Returns

Promise<CreateContractEventFilterReturnType<TAbi, TEventName, TArgs, TStrict, TFromBlock, TToBlock>>

createEventFilter()

createEventFilter: <TAbiEvent, TAbiEvents, TStrict, TFromBlock, TToBlock, _EventName, _Args>(args?) => Promise<{ [K in string | number | symbol]: Filter<“event”, TAbiEvents, _EventName, _Args, TStrict, TFromBlock, TToBlock>[K] }>

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

Example

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

Type parameters

TAbiEvent extends undefined | AbiEvent = undefined

TAbiEvents extends undefined | readonly unknown[] | readonly AbiEvent[] = TAbiEvent extends AbiEvent ? [TAbiEvent<TAbiEvent>] : undefined

TStrict extends undefined | boolean = undefined

TFromBlock extends undefined | bigint | BlockTag = undefined

TToBlock extends undefined | bigint | BlockTag = undefined

_EventName extends undefined | string = MaybeAbiEventName<TAbiEvent>

_Args extends undefined | Record<string, unknown> | readonly unknown[] = undefined

Parameters

args?: CreateEventFilterParameters<TAbiEvent, TAbiEvents, TStrict, TFromBlock, TToBlock, _EventName, _Args>

CreateEventFilterParameters

Returns

Promise<{ [K in string | number | symbol]: Filter<“event”, TAbiEvents, _EventName, _Args, TStrict, TFromBlock, TToBlock>[K] }>

createPendingTransactionFilter()

createPendingTransactionFilter: () => Promise<object>

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

Example

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

Returns

Promise<object>

id

id: `0x${string}`

request

request: EIP1193RequestFn<readonly [object, object, object]>

type

type: "transaction"

dropTransaction()

dropTransaction: (args) => Promise<void>

Removes a transaction from the mempool.

Example

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

Parameters

args: DropTransactionParameters

DropTransactionParameters

Returns

Promise<void>

dumpState()

dumpState: () => Promise<`0x${string}`>

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

Example

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

Returns

Promise<`0x${string}`>

estimateContractGas()

estimateContractGas: <TChain, abi, functionName, args>(args) => Promise<bigint>

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

Remarks

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

Example

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

Type parameters

TChain extends undefined | Chain

abi extends Abi | readonly unknown[]

functionName extends string

args extends unknown

Parameters

args: EstimateContractGasParameters<abi, functionName, args, TChain>

EstimateContractGasParameters

Returns

Promise<bigint>

estimateFeesPerGas()

estimateFeesPerGas: <TChainOverride, TType>(args?) => Promise<EstimateFeesPerGasReturnType>

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

Example

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

Type parameters

TChainOverride extends undefined | Chain = undefined

TType extends FeeValuesType = "eip1559"

Parameters

args?: EstimateFeesPerGasParameters<undefined | Chain, TChainOverride, TType>

Returns

Promise<EstimateFeesPerGasReturnType>

estimateGas()

estimateGas: (args) => Promise<bigint>

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

Example

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

Parameters

args: EstimateGasParameters<undefined | Chain>

EstimateGasParameters

Returns

Promise<bigint>

estimateMaxPriorityFeePerGas()

estimateMaxPriorityFeePerGas: <TChainOverride>(args?) => Promise<bigint>

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

Example

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

Type parameters

TChainOverride extends undefined | Chain = undefined

Parameters

args?

args.chain?: null | TChainOverride

Returns

Promise<bigint>

extend()

extend: <client>(fn) => Client<Transport, undefined, undefined, [object, object, object, object, object], { [K in string | number | symbol]: client[K] } & PublicActions & TestActions & TevmActions>

Type parameters

client extends object & ExactPartial<ExtendableProtectedActions<Transport, undefined, undefined>>

Parameters

fn

Returns

Client<Transport, undefined, undefined, [object, object, object, object, object], { [K in string | number | symbol]: client[K] } & PublicActions & TestActions & TevmActions>

getAutomine()

getAutomine: () => Promise<boolean>

Returns the automatic mining status of the node.

Example

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

Returns

Promise<boolean>

getBalance()

getBalance: (args) => Promise<bigint>

Returns the balance of an address in wei.

Remarks

You can convert the balance to ether units with formatEther.

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

Example

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

Parameters

args: GetBalanceParameters

GetBalanceParameters

Returns

Promise<bigint>

getBlobBaseFee()

getBlobBaseFee: () => Promise<bigint>

Returns the base fee per blob gas in wei.

Example

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

Returns

Promise<bigint>

getBlock()

getBlock: <TIncludeTransactions, TBlockTag>(args?) => Promise<object>

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

Example

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

Type parameters

TIncludeTransactions extends boolean = false

TBlockTag extends BlockTag = "latest"

Parameters

args?: GetBlockParameters<TIncludeTransactions, TBlockTag>

GetBlockParameters

Returns

Promise<object>

baseFeePerGas

baseFeePerGas: null | bigint

Base fee per gas

blobGasUsed

blobGasUsed: bigint

Total used blob gas by all transactions in this block

difficulty

difficulty: bigint

Difficulty for this block

excessBlobGas

excessBlobGas: bigint

Excess blob gas

extraData

extraData: `0x${string}`

“Extra data” field of this block

gasLimit

gasLimit: bigint

Maximum gas allowed in this block

gasUsed

gasUsed: bigint

Total used gas by all transactions in this block

hash

hash: TBlockTag extends "pending" ? null : `0x${string}`

Block hash or null if pending

logsBloom

logsBloom: TBlockTag extends "pending" ? null : `0x${string}`

Logs bloom filter or null if pending

miner

miner: `0x${string}`

Address that received this block’s mining rewards

mixHash

mixHash: `0x${string}`

Unique identifier for the block.

nonce

nonce: TBlockTag extends "pending" ? null : `0x${string}`

Proof-of-work hash or null if pending

number

number: TBlockTag extends "pending" ? null : bigint

Block number or null if pending

parentHash

parentHash: `0x${string}`

Parent block hash

receiptsRoot

receiptsRoot: `0x${string}`

Root of the this block’s receipts trie

sealFields

sealFields: `0x${string}`[]

sha3Uncles

sha3Uncles: `0x${string}`

SHA3 of the uncles data in this block

size

size: bigint

Size of this block in bytes

stateRoot

stateRoot: `0x${string}`

Root of this block’s final state trie

timestamp

timestamp: bigint

Unix timestamp of when this block was collated

totalDifficulty

totalDifficulty: null | bigint

Total difficulty of the chain until this block

transactions

transactions: TIncludeTransactions extends true ? (object | object | object | object)[] : `0x${string}`[]

transactionsRoot

transactionsRoot: `0x${string}`

Root of this block’s transaction trie

uncles

uncles: `0x${string}`[]

List of uncle hashes

withdrawals?

optional withdrawals: Withdrawal[]

List of withdrawal objects

withdrawalsRoot?

optional withdrawalsRoot: `0x${string}`

Root of the this block’s withdrawals trie

getBlockNumber()

getBlockNumber: (args?) => Promise<bigint>

Returns the number of the most recent block seen.

Example

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

Parameters

args?: GetBlockNumberParameters

GetBlockNumberParameters

Returns

Promise<bigint>

getBlockTransactionCount()

getBlockTransactionCount: (args?) => Promise<number>

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

Example

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

Parameters

args?: GetBlockTransactionCountParameters

GetBlockTransactionCountParameters

Returns

Promise<number>

getBytecode()

getBytecode: (args) => Promise<GetBytecodeReturnType>

Retrieves the bytecode at an address.

Example

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

Parameters

args: GetBytecodeParameters

GetBytecodeParameters

Returns

Promise<GetBytecodeReturnType>

getChainId()

getChainId: () => Promise<number>

Returns the chain ID associated with the current network.

Example

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

Returns

Promise<number>

getContractEvents()

getContractEvents: <abi, eventName, strict, fromBlock, toBlock>(args) => Promise<GetContractEventsReturnType<abi, eventName, strict, fromBlock, toBlock>>

Returns a list of event logs emitted by a contract.

Example

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

Type parameters

abi extends Abi | readonly unknown[]

eventName extends undefined | string = undefined

strict extends undefined | boolean = undefined

fromBlock extends undefined | bigint | BlockTag = undefined

toBlock extends undefined | bigint | BlockTag = undefined

Parameters

args: GetContractEventsParameters<abi, eventName, strict, fromBlock, toBlock>

Returns

Promise<GetContractEventsReturnType<abi, eventName, strict, fromBlock, toBlock>>

getEnsAddress()

getEnsAddress: (args) => Promise<GetEnsAddressReturnType>

Gets address for ENS name.

Remarks

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

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

Example

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

Parameters

args

GetEnsAddressParameters

args.blockNumber?: bigint

The balance of the account at a block number.

args.blockTag?: BlockTag

The balance of the account at a block tag.

Default

'latest'

args.coinType?: number

ENSIP-9 compliant coinType used to resolve addresses for other chains

args.gatewayUrls?: string[]

Universal Resolver gateway URLs to use for resolving CCIP-read requests.

args.name: string

Name to get the address for.

args.strict?: boolean

Whether or not to throw errors propagated from the ENS Universal Resolver Contract.

args.universalResolverAddress?: `0x${string}`

Address of ENS Universal Resolver Contract.

Returns

Promise<GetEnsAddressReturnType>

getEnsAvatar()

getEnsAvatar: (args) => Promise<GetEnsAvatarReturnType>

Gets the avatar of an ENS name.

Remarks

Calls getEnsText with key set to 'avatar'.

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

Example

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

Parameters

args

GetEnsAvatarParameters

args.assetGatewayUrls?: AssetGatewayUrls

Gateway urls to resolve IPFS and/or Arweave assets.

args.blockNumber?: bigint

The balance of the account at a block number.

args.blockTag?: BlockTag

The balance of the account at a block tag.

Default

'latest'

args.gatewayUrls?: string[]

Universal Resolver gateway URLs to use for resolving CCIP-read requests.

args.name: string

ENS name to get Text for.

args.strict?: boolean

Whether or not to throw errors propagated from the ENS Universal Resolver Contract.

args.universalResolverAddress?: `0x${string}`

Address of ENS Universal Resolver Contract.

Returns

Promise<GetEnsAvatarReturnType>

getEnsName()

getEnsName: (args) => Promise<GetEnsNameReturnType>

Gets primary name for specified address.

Remarks

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

Example

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

Parameters

args

GetEnsNameParameters

args.address: `0x${string}`

Address to get ENS name for.

args.blockNumber?: bigint

The balance of the account at a block number.

args.blockTag?: BlockTag

The balance of the account at a block tag.

Default

'latest'

args.gatewayUrls?: string[]

Universal Resolver gateway URLs to use for resolving CCIP-read requests.

args.strict?: boolean

Whether or not to throw errors propagated from the ENS Universal Resolver Contract.

args.universalResolverAddress?: `0x${string}`

Address of ENS Universal Resolver Contract.

Returns

Promise<GetEnsNameReturnType>

getEnsResolver()

getEnsResolver: (args) => Promise<`0x${string}`>

Gets resolver for ENS name.

Remarks

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

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

Example

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

Parameters

args

GetEnsResolverParameters

args.blockNumber?: bigint

The balance of the account at a block number.

args.blockTag?: BlockTag

The balance of the account at a block tag.

Default

'latest'

args.name: string

Name to get the address for.

args.universalResolverAddress?: `0x${string}`

Address of ENS Universal Resolver Contract.

Returns

Promise<`0x${string}`>

getEnsText()

getEnsText: (args) => Promise<GetEnsTextReturnType>

Gets a text record for specified ENS name.

Remarks

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

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

Example

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

Parameters

args

GetEnsTextParameters

args.blockNumber?: bigint

The balance of the account at a block number.

args.blockTag?: BlockTag

The balance of the account at a block tag.

Default

'latest'

args.gatewayUrls?: string[]

Universal Resolver gateway URLs to use for resolving CCIP-read requests.

args.key: string

Text record to retrieve.

args.name: string

ENS name to get Text for.

args.strict?: boolean

Whether or not to throw errors propagated from the ENS Universal Resolver Contract.

args.universalResolverAddress?: `0x${string}`

Address of ENS Universal Resolver Contract.

Returns

Promise<GetEnsTextReturnType>

getFeeHistory()

getFeeHistory: (args) => Promise<GetFeeHistoryReturnType>

Returns a collection of historical gas information.

Example

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

Parameters

args: GetFeeHistoryParameters

GetFeeHistoryParameters

Returns

Promise<GetFeeHistoryReturnType>

getFilterChanges()

getFilterChanges: <TFilterType, TAbi, TEventName, TStrict, TFromBlock, TToBlock>(args) => Promise<GetFilterChangesReturnType<TFilterType, TAbi, TEventName, TStrict, TFromBlock, TToBlock>>

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

Remarks

A Filter can be created from the following actions:

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

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

Examples

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

Type parameters

TFilterType extends FilterType

TAbi extends undefined | Abi | readonly unknown[]

TEventName extends undefined | string

TStrict extends undefined | boolean = undefined

TFromBlock extends undefined | bigint | BlockTag = undefined

TToBlock extends undefined | bigint | BlockTag = undefined

Parameters

args: GetFilterChangesParameters<TFilterType, TAbi, TEventName, TStrict, TFromBlock, TToBlock>

GetFilterChangesParameters

Returns

Promise<GetFilterChangesReturnType<TFilterType, TAbi, TEventName, TStrict, TFromBlock, TToBlock>>

getFilterLogs()

getFilterLogs: <TAbi, TEventName, TStrict, TFromBlock, TToBlock>(args) => Promise<GetFilterLogsReturnType<TAbi, TEventName, TStrict, TFromBlock, TToBlock>>

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

Remarks

getFilterLogs is only compatible with event filters.

Example

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

Type parameters

TAbi extends undefined | Abi | readonly unknown[]

TEventName extends undefined | string

TStrict extends undefined | boolean = undefined

TFromBlock extends undefined | bigint | BlockTag = undefined

TToBlock extends undefined | bigint | BlockTag = undefined

Parameters

args: GetFilterLogsParameters<TAbi, TEventName, TStrict, TFromBlock, TToBlock>

GetFilterLogsParameters

Returns

Promise<GetFilterLogsReturnType<TAbi, TEventName, TStrict, TFromBlock, TToBlock>>

getGasPrice()

getGasPrice: () => Promise<bigint>

Returns the current price of gas (in wei).

Example

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

Returns

Promise<bigint>

getLogs()

getLogs: <TAbiEvent, TAbiEvents, TStrict, TFromBlock, TToBlock>(args?) => Promise<GetLogsReturnType<TAbiEvent, TAbiEvents, TStrict, TFromBlock, TToBlock>>

Returns a list of event logs matching the provided parameters.

Example

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

Type parameters

TAbiEvent extends undefined | AbiEvent = undefined

TAbiEvents extends undefined | readonly unknown[] | readonly AbiEvent[] = TAbiEvent extends AbiEvent ? [TAbiEvent<TAbiEvent>] : undefined

TStrict extends undefined | boolean = undefined

TFromBlock extends undefined | bigint | BlockTag = undefined

TToBlock extends undefined | bigint | BlockTag = undefined

Parameters

args?: GetLogsParameters<TAbiEvent, TAbiEvents, TStrict, TFromBlock, TToBlock>

GetLogsParameters

Returns

Promise<GetLogsReturnType<TAbiEvent, TAbiEvents, TStrict, TFromBlock, TToBlock>>

getProof()

getProof: (args) => Promise<GetProofReturnType>

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

Example

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

Parameters

args: GetProofParameters

Returns

Promise<GetProofReturnType>

getStorageAt()

getStorageAt: (args) => Promise<GetStorageAtReturnType>

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

Example

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

Parameters

args: GetStorageAtParameters

GetStorageAtParameters

Returns

Promise<GetStorageAtReturnType>

getTransaction()

getTransaction: <TBlockTag>(args) => Promise<object | object | object | object>

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

Example

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

Type parameters

TBlockTag extends BlockTag = "latest"

Parameters

args: GetTransactionParameters<TBlockTag>

GetTransactionParameters

Returns

Promise<object | object | object | object>

getTransactionConfirmations()

getTransactionConfirmations: (args) => Promise<bigint>

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

Example

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

Parameters

args: GetTransactionConfirmationsParameters<undefined | Chain>

GetTransactionConfirmationsParameters

Returns

Promise<bigint>

getTransactionCount()

getTransactionCount: (args) => Promise<number>

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

Example

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

Parameters

args: GetTransactionCountParameters

GetTransactionCountParameters

Returns

Promise<number>

getTransactionReceipt()

getTransactionReceipt: (args) => Promise<TransactionReceipt>

Returns the Transaction Receipt given a Transaction hash.

Example

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

Parameters

args: GetTransactionReceiptParameters

GetTransactionReceiptParameters

Returns

Promise<TransactionReceipt>

getTxpoolContent()

getTxpoolContent: () => Promise<GetTxpoolContentReturnType>

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

Example

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

Returns

Promise<GetTxpoolContentReturnType>

getTxpoolStatus()

getTxpoolStatus: () => Promise<GetTxpoolStatusReturnType>

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

Example

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

Returns

Promise<GetTxpoolStatusReturnType>

impersonateAccount()

impersonateAccount: (args) => Promise<void>

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

Example

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

Parameters

args: ImpersonateAccountParameters

ImpersonateAccountParameters

Returns

Promise<void>

increaseTime()

increaseTime: (args) => Promise<`0x${string}`>

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

Example

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

Parameters

args: IncreaseTimeParameters

– IncreaseTimeParameters

Returns

Promise<`0x${string}`>

inspectTxpool()

inspectTxpool: () => Promise<InspectTxpoolReturnType>

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

Example

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

Returns

Promise<InspectTxpoolReturnType>

key

key: string

A key for the client.

loadState()

loadState: (args) => Promise<void>

Adds state previously dumped with dumpState to the current chain.

Example

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

Parameters

args: LoadStateParameters

Returns

Promise<void>

mine()

mine: (args) => Promise<void>

Mine a specified number of blocks.

Example

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

Parameters

args: MineParameters

– MineParameters

Returns

Promise<void>

multicall()

multicall: <contracts, allowFailure>(args) => Promise<MulticallReturnType<contracts, allowFailure>>

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

Example

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

Type parameters

contracts extends readonly unknown[]

allowFailure extends boolean = true

Parameters

args: MulticallParameters<contracts, allowFailure>

MulticallParameters

Returns

Promise<MulticallReturnType<contracts, allowFailure>>

name

name: string

A name for the client.

pollingInterval

pollingInterval: number

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

prepareTransactionRequest()

prepareTransactionRequest: <TRequest, TChainOverride, TAccountOverride>(args) => Promise<{ [K in string | number | symbol]: (UnionRequiredBy<Extract<UnionOmit<(…), (…)> & ((…) extends (…) ? (…) : (…)) & ((…) extends (…) ? (…) : (…)), IsNever<(…)> extends true ? unknown : ExactPartial<(…)>> & Object, ParameterTypeToParameters<TRequest[“parameters”] extends readonly PrepareTransactionRequestParameterType[] ? any[any][number] : “gas” | “nonce” | “blobVersionedHashes” | “chainId” | “type” | “fees”>> & (unknown extends TRequest[“kzg”] ? Object : Pick<TRequest, “kzg”>))[K] }>

Prepares a transaction request for signing.

Examples

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

Type parameters

TRequest extends Omit<object, "from"> | Omit<object, "from"> | Omit<object, "from"> | Omit<object, "from"> & object & object

TChainOverride extends undefined | Chain = undefined

TAccountOverride extends undefined | `0x${string}` | Account = undefined

Parameters

args: PrepareTransactionRequestParameters<undefined | Chain, undefined | Account, TChainOverride, TAccountOverride, TRequest>

PrepareTransactionRequestParameters

Returns

Promise<{ [K in string | number | symbol]: (UnionRequiredBy<Extract<UnionOmit<(…), (…)> & ((…) extends (…) ? (…) : (…)) & ((…) extends (…) ? (…) : (…)), IsNever<(…)> extends true ? unknown : ExactPartial<(…)>> & Object, ParameterTypeToParameters<TRequest[“parameters”] extends readonly PrepareTransactionRequestParameterType[] ? any[any][number] : “gas” | “nonce” | “blobVersionedHashes” | “chainId” | “type” | “fees”>> & (unknown extends TRequest[“kzg”] ? Object : Pick<TRequest, “kzg”>))[K] }>

readContract()

readContract: <abi, functionName, args>(args) => Promise<ReadContractReturnType<abi, functionName, args>>

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

Remarks

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

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

Example

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

Type parameters

abi extends Abi | readonly unknown[]

functionName extends string

args extends unknown

Parameters

args: ReadContractParameters<abi, functionName, args>

ReadContractParameters

Returns

Promise<ReadContractReturnType<abi, functionName, args>>

removeBlockTimestampInterval()

removeBlockTimestampInterval: () => Promise<void>

Removes setBlockTimestampInterval if it exists.

Example

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

Returns

Promise<void>

request

request: EIP1193RequestFn<[object, object, object, object, object]>

Request function wrapped with friendly error handling

reset()

reset: (args?) => Promise<void>

Resets fork back to its original state.

Example

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

Parameters

args?: ResetParameters

– ResetParameters

Returns

Promise<void>

revert()

revert: (args) => Promise<void>

Revert the state of the blockchain at the current block.

Example

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

Parameters

args: RevertParameters

– RevertParameters

Returns

Promise<void>

sendRawTransaction()

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

Sends a signed transaction to the network

Example

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

Parameters

args: SendRawTransactionParameters

Returns

Promise<`0x${string}`>

sendUnsignedTransaction()

sendUnsignedTransaction: <TChain>(args) => Promise<`0x${string}`>

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

Example

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

Type parameters

TChain extends undefined | Chain

Parameters

args: SendUnsignedTransactionParameters<TChain>

– SendUnsignedTransactionParameters

Returns

Promise<`0x${string}`>

setAutomine()

setAutomine: (args) => Promise<void>

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

Example

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

Parameters

args: boolean

Returns

Promise<void>

setBalance()

setBalance: (args) => Promise<void>

Modifies the balance of an account.

Example

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

Parameters

args: SetBalanceParameters

– SetBalanceParameters

Returns

Promise<void>

setBlockGasLimit()

setBlockGasLimit: (args) => Promise<void>

Sets the block’s gas limit.

Example

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

Parameters

args: SetBlockGasLimitParameters

– SetBlockGasLimitParameters

Returns

Promise<void>

setBlockTimestampInterval()

setBlockTimestampInterval: (args) => Promise<void>

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

Example

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

Parameters

args: SetBlockTimestampIntervalParameters

– SetBlockTimestampIntervalParameters

Returns

Promise<void>

setCode()

setCode: (args) => Promise<void>

Modifies the bytecode stored at an account’s address.

Example

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

Parameters

args: SetCodeParameters

– SetCodeParameters

Returns

Promise<void>

setCoinbase()

setCoinbase: (args) => Promise<void>

Sets the coinbase address to be used in new blocks.

Example

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

Parameters

args: SetCoinbaseParameters

– SetCoinbaseParameters

Returns

Promise<void>

setIntervalMining()

setIntervalMining: (args) => Promise<void>

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

Example

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

Parameters

args: SetIntervalMiningParameters

– SetIntervalMiningParameters

Returns

Promise<void>

setLoggingEnabled()

setLoggingEnabled: (args) => Promise<void>

Enable or disable logging on the test node network.

Example

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

Parameters

args: boolean

Returns

Promise<void>

setMinGasPrice()

setMinGasPrice: (args) => Promise<void>

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

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

Example

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

Parameters

args: SetMinGasPriceParameters

– SetBlockGasLimitParameters

Returns

Promise<void>

setNextBlockBaseFeePerGas()

setNextBlockBaseFeePerGas: (args) => Promise<void>

Sets the next block’s base fee per gas.

Example

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

Parameters

args: SetNextBlockBaseFeePerGasParameters

– SetNextBlockBaseFeePerGasParameters

Returns

Promise<void>

setNextBlockTimestamp()

setNextBlockTimestamp: (args) => Promise<void>

Sets the next block’s timestamp.

Example

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

Parameters

args: SetNextBlockTimestampParameters

– SetNextBlockTimestampParameters

Returns

Promise<void>

setNonce()

setNonce: (args) => Promise<void>

Modifies (overrides) the nonce of an account.

Example

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

Parameters

args: SetNonceParameters

– SetNonceParameters

Returns

Promise<void>

setRpcUrl()

setRpcUrl: (args) => Promise<void>

Sets the backend RPC URL.

Example

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

Parameters

args: string

Returns

Promise<void>

setStorageAt()

setStorageAt: (args) => Promise<void>

Writes to a slot of an account’s storage.

Example

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

Parameters

args: SetStorageAtParameters

– SetStorageAtParameters

Returns

Promise<void>

simulateContract()

simulateContract: <abi, functionName, args, chainOverride, accountOverride>(args) => Promise<SimulateContractReturnType<abi, functionName, args, undefined | Chain, undefined | Account, chainOverride, accountOverride>>

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

Remarks

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

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

Example

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

Type parameters

abi extends Abi | readonly unknown[]

functionName extends string

args extends unknown

chainOverride extends undefined | Chain

accountOverride extends undefined | `0x${string}` | Account = undefined

Parameters

args: SimulateContractParameters<abi, functionName, args, undefined | Chain, chainOverride, accountOverride>

SimulateContractParameters

Returns

Promise<SimulateContractReturnType<abi, functionName, args, undefined | Chain, undefined | Account, chainOverride, accountOverride>>

snapshot()

snapshot: () => Promise<`0x${string}`>

Snapshot the state of the blockchain at the current block.

Example

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

Returns

Promise<`0x${string}`>

stopImpersonatingAccount()

stopImpersonatingAccount: (args) => Promise<void>

Stop impersonating an account after having previously used impersonateAccount.

Example

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

Parameters

args: StopImpersonatingAccountParameters

– StopImpersonatingAccountParameters

Returns

Promise<void>

tevmCall

tevmCall: CallHandler

tevmContract

tevmContract: ContractHandler

tevmDeploy

tevmDeploy: DeployHandler

tevmDumpState

tevmDumpState: DumpStateHandler

tevmForkUrl?

optional tevmForkUrl: string

tevmGetAccount

tevmGetAccount: GetAccountHandler

tevmLoadState

tevmLoadState: LoadStateHandler

tevmMine

tevmMine: MineHandler

tevmReady()

tevmReady: () => Promise<true>

Returns

Promise<true>

tevmScript

tevmScript: ScriptHandler

tevmSetAccount

tevmSetAccount: SetAccountHandler

transport

transport: TransportConfig<string, EIP1193RequestFn> & Record<string, any>

The RPC transport

type

type: string

The type of client.

uid

uid: string

A unique ID for the client.

uninstallFilter()

uninstallFilter: (args) => Promise<boolean>

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

Example

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

Parameters

args: UninstallFilterParameters

UninstallFilterParameters

Returns

Promise<boolean>

verifyMessage()

verifyMessage: (args) => Promise<boolean>

Verify that a message was signed by the provided address.

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

Parameters

args

args.address: `0x${string}`

The address that signed the original message.

args.blockNumber?: bigint

The balance of the account at a block number.

args.blockTag?: BlockTag

The balance of the account at a block tag.

Default

'latest'

args.message: SignableMessage

The message to be verified.

args.signature: `0x${string}` | Uint8Array | Signature

The signature that was generated by signing the message with the address’s private key.

Returns

Promise<boolean>

verifySiweMessage()

verifySiweMessage: (args) => Promise<boolean>

Verifies EIP-4361 formatted message was signed.

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

Parameters

args

args.address?: `0x${string}`

Ethereum address to check against.

args.blockNumber?: bigint

The balance of the account at a block number.

args.blockTag?: BlockTag

The balance of the account at a block tag.

Default

'latest'

args.domain?: string

RFC 3986 authority to check against.

args.message: string

EIP-4361 formatted message.

args.nonce?: string

Random string to check against.

args.scheme?: string

RFC 3986 URI scheme to check against.

args.signature: `0x${string}`

Signature to check against.

args.time?: Date

Current time to check optional expirationTime and notBefore fields.

Default

new Date()

Returns

Promise<boolean>

verifyTypedData()

verifyTypedData: (args) => Promise<boolean>

Verify that typed data was signed by the provided address.

Parameters

args: VerifyTypedDataParameters

Returns

Promise<boolean>

waitForTransactionReceipt()

waitForTransactionReceipt: (args) => Promise<TransactionReceipt>

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

Remarks

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

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

There are 3 types of Transaction Replacement reasons:

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

Example

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

Parameters

args: WaitForTransactionReceiptParameters<undefined | Chain>

WaitForTransactionReceiptParameters

Returns

Promise<TransactionReceipt>

watchBlockNumber()

watchBlockNumber: (args) => WatchBlockNumberReturnType

Watches and returns incoming block numbers.

Example

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

Parameters

args: WatchBlockNumberParameters

WatchBlockNumberParameters

Returns

WatchBlockNumberReturnType

watchBlocks()

watchBlocks: <TIncludeTransactions, TBlockTag>(args) => WatchBlocksReturnType

Watches and returns information for incoming blocks.

Example

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

Type parameters

TIncludeTransactions extends boolean = false

TBlockTag extends BlockTag = "latest"

Parameters

args: WatchBlocksParameters<Transport, undefined | Chain, TIncludeTransactions, TBlockTag>

WatchBlocksParameters

Returns

WatchBlocksReturnType

watchContractEvent()

watchContractEvent: <TAbi, TEventName, TStrict>(args) => WatchContractEventReturnType

Watches and returns emitted contract event logs.

Remarks

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

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

Example

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

Type parameters

TAbi extends Abi | readonly unknown[]

TEventName extends string

TStrict extends undefined | boolean = undefined

Parameters

args: WatchContractEventParameters<TAbi, TEventName, TStrict, Transport>

WatchContractEventParameters

Returns

WatchContractEventReturnType

watchEvent()

watchEvent: <TAbiEvent, TAbiEvents, TStrict>(args) => WatchEventReturnType

Watches and returns emitted Event Logs.

Remarks

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

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

Example

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

Type parameters

TAbiEvent extends undefined | AbiEvent = undefined

TAbiEvents extends undefined | readonly unknown[] | readonly AbiEvent[] = TAbiEvent extends AbiEvent ? [TAbiEvent<TAbiEvent>] : undefined

TStrict extends undefined | boolean = undefined

Parameters

args: WatchEventParameters<TAbiEvent, TAbiEvents, TStrict, Transport>

WatchEventParameters

Returns

WatchEventReturnType

watchPendingTransactions()

watchPendingTransactions: (args) => WatchPendingTransactionsReturnType

Watches and returns pending transaction hashes.

Remarks

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

Example

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

Parameters

args: WatchPendingTransactionsParameters<Transport>

WatchPendingTransactionsParameters

Returns

WatchPendingTransactionsReturnType

Example

import { createMemoryClient } from "tevm"
import { MyERC721 } from './MyERC721.sol'
const tevm = createMemoryClient({
fork: {
transport: http("https://mainnet.optimism.io")({}),
},
})
const address = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',
await tevm.runContractCall(
MyERC721.write.mint({
caller: address,
}),
)
const balance = await tevm.runContractCall(
MyERC721.read.balanceOf({
caller: address,
}),
)
console.log(balance) // 1n

Source

packages/memory-client/src/createMemoryClient.js:39