Skip to content

AbiFunction.decodeResult

ABI-decodes a function's result according to the ABI Item's output types (outputs).

Imports

Named
import { AbiFunction } from 'ox'

Examples

import { AbiFunction } from 'ox'
 
const data = '0x000000000000000000000000000000000000000000000000000000000000002a'
 
const totalSupply = AbiFunction.from('function totalSupply() returns (uint256)')
 
const output = AbiFunction.decodeResult(totalSupply, data)
42n

You can extract an ABI Function from a JSON ABI with AbiFunction.fromAbi:

import { Abi, AbiFunction } from 'ox'
 
const data = '0x000000000000000000000000000000000000000000000000000000000000002a'
 
const erc20Abi = Abi.from([...])
const totalSupply = AbiFunction.fromAbi(erc20Abi, 'totalSupply')
 
const output = AbiFunction.decodeResult(totalSupply, data)
42n

End-to-end

Below is an end-to-end example of using AbiFunction.decodeResult to decode the result of a balanceOf contract call on the Wagmi Mint Example contract.

import 'ox/window'
import { Abi, AbiFunction } from 'ox'
 
// 1. Extract the Function from the Contract's ABI.
const abi = Abi.from([
  // ...
  {
    name: 'balanceOf',
    type: 'function',
    inputs: [{ name: 'account', type: 'address' }],
    outputs: [{ name: 'balance', type: 'uint256' }],
    stateMutability: 'view',
  },
  // ...
])
const balanceOf = AbiFunction.fromAbi(abi, 'balanceOf')
 
// 2. Encode the Function Input.
const data = AbiFunction.encodeData(
  balanceOf,
  ['0xd2135CfB216b74109775236E36d4b433F1DF507B']
)
 
// 3. Perform the Contract Call.
const response = await window.ethereum!.request({
  method: 'eth_call',
  params: [
    {
      data,
      to: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',
    },
  ],
})
 
// 4. Decode the Function Output.
const balance = AbiFunction.decodeResult(balanceOf, response)
42n

Definition

function decodeResult<abiFunction, as>(
  abiFunction: abiFunction | AbiFunction,
  data: Hex.Hex,
  options?: decodeResult.Options<as>,
): decodeResult.ReturnType<abiFunction, as>

Source: src/core/AbiFunction.ts

Parameters

abiFunction

  • Type: abiFunction | AbiFunction

ABI Function to decode

data

  • Type: Hex.Hex

ABI-encoded function output

options

  • Type: decodeResult.Options<as>
  • Optional

Decoding options

options.as

  • Type: "Array" | "Object" | as
  • Optional

Whether the decoded values should be returned as an Object or Array.

Return Type

Decoded function output

decodeResult.ReturnType<abiFunction, as>