Skip to content

AbiFunction.encodeData

ABI-encodes function arguments (inputs), prefixed with the 4 byte function selector.

Imports

Named
import { AbiFunction } from 'ox'

Examples

import { AbiFunction } from 'ox'
 
const approve = AbiFunction.from('function approve(address, uint256)')
 
const data = AbiFunction.encodeData(
  approve,
  ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]
)
'0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'

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

import { Abi, AbiFunction } from 'ox'
 
const erc20Abi = Abi.from([...])
const approve = AbiFunction.fromAbi(erc20Abi, 'approve')
 
const data = AbiFunction.encodeData(
  approve,
  ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]
)
'0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'

End-to-end

Below is an end-to-end example of using AbiFunction.encodeData to encode the input 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)

Definition

function encodeData<abiFunction>(
  abiFunction: abiFunction | AbiFunction,
  args: encodeData.Args<abiFunction>,
): Hex.Hex

Source: src/AbiFunction.ts

Parameters

abiFunction

  • Type: abiFunction | AbiFunction

ABI Function to encode

args

  • Type: encodeData.Args<abiFunction>

Function arguments

Return Type

ABI-encoded function name and arguments

Hex.Hex