Skip to content

encodeFunctionResult

Encodes structured return data into ABI encoded data. It is the opposite of decodeFunctionResult.

Install

import { encodeFunctionResult } from 'viem';

Usage

Given an ABI (abi) and a function (functionName), pass through the values (values) to encode:

example.ts
import { encodeFunctionResult } from 'viem';
import { wagmiAbi } from './abi.ts'
 
const data = encodeFunctionResult({
  abi: wagmiAbi,
  functionName: 'ownerOf',
  value: ['0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac'],
});
// '0x000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac'

A more complex example

example.ts
import { decodeFunctionResult } from 'viem'
 
const data = decodeFunctionResult({
  abi: wagmiAbi,
  functionName: 'getInfo',
  value: [
    {
      foo: {
        sender: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',
        x: 69420n,
        y: true
      },
      sender: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',
      z: 69
    }
  ]
})
// 0x000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac0000000000000000000000000000000000000000000000000000000000010f2c0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac0000000000000000000000000000000000000000000000000000000000000045

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', 
  value: ['0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac'],
});
// '0x000000000000000000000000a5cc3c03994db5b0d9a5eedd10cabab0813678ac'

Return Value

The decoded data. Type is inferred from the ABI.

Parameters

abi

The contract's ABI.

const data = encodeFunctionResult({
  abi: wagmiAbi, 
  functionName: 'ownerOf',
  value: ['0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac'],
});

functionName

  • Type: string

The function to encode from the ABI.

const data = encodeFunctionResult({
  abi: wagmiAbi,
  functionName: 'ownerOf', 
  value: ['0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac'],
});

values

Return values to encode.

const data = encodeFunctionResult({
  abi: wagmiAbi,
  functionName: 'ownerOf',
  value: ['0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac'], 
});