Skip to content

encodeFunctionData

Encodes the function name and parameters into an ABI encoded value (4 byte selector & arguments).

Install

import { encodeFunctionData } from 'viem'

Usage

Below is a very basic example of how to encode a function to calldata.

example.ts
import { encodeFunctionData } from 'viem'
import { wagmiAbi } from './abi.ts'
 
const data = encodeFunctionData({
  abi: wagmiAbi,
  functionName: 'totalSupply'
})

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.ts
import { encodeFunctionData } from 'viem'
import { wagmiAbi } from './abi'
 
const data = encodeFunctionData({
  abi: wagmiAbi,
  functionName: 'balanceOf',
  args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC']
})

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)

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

Hex

ABI encoded data (4byte function selector & arguments).

Parameters

abi

The contract's ABI.

const data = encodeFunctionData({
  abi: wagmiAbi, 
  functionName: 'totalSupply',
})

functionName

  • Type: string

The function to encode from the ABI.

const data = encodeFunctionData({
  abi: wagmiAbi,
  functionName: 'totalSupply', 
})

args (optional)

  • Type: Inferred from ABI.

Arguments to pass to function call.

const data = encodeFunctionData({
  abi: wagmiAbi,
  functionName: 'balanceOf',
  args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'] 
})