Skip to main content

Try it Live

Run ABI examples in the interactive playground

Overview

Abi.encode encodes function calldata (selector + parameters) using a full ABI. It looks up the function by name, then encodes the arguments according to the function inputs.

Quick Start

import { Abi } from '@tevm/voltaire/Abi';
import { Hex } from '@tevm/voltaire/Hex';

const abi = Abi([
  {
    type: 'function',
    name: 'transfer',
    stateMutability: 'nonpayable',
    inputs: [
      { type: 'address', name: 'to' },
      { type: 'uint256', name: 'amount' }
    ],
    outputs: [{ type: 'bool' }]
  }
] as const);

const calldata = abi.encode('transfer', [
  '0x742d35Cc6634C0532925a3b844Bc9e7595f51e3e',
  1000n
]);

const hex = Hex.fromBytes(calldata);

Parameters Only

If you need only the parameters (no selector), use Abi.encodeParameters:
import { Abi } from '@tevm/voltaire/Abi';

const params = [
  { type: 'address' },
  { type: 'uint256' }
] as const;

const encoded = Abi.encodeParameters(params, [
  '0x742d35Cc6634C0532925a3b844Bc9e7595f51e3e',
  1000n
]);

Overloads and Ambiguity

Abi.encode matches by function name. If your ABI contains overloads, select the exact function item:
const signature = 'foo(address,uint256)';
const fn = abi.find(
  (item) =>
    item.type === 'function' &&
    Abi.Function.getSignature(item) === signature
);

const data = Abi.Function.encodeParams(fn, [
  '0x742d35Cc6634C0532925a3b844Bc9e7595f51e3e',
  1n
]);

Error Handling

import { Abi, AbiItemNotFoundError, AbiEncodingError } from '@tevm/voltaire/Abi';

try {
  abi.encode('missingFunction', []);
} catch (error) {
  if (error instanceof AbiItemNotFoundError) {
    console.error('Function not found in ABI');
  }
  if (error instanceof AbiEncodingError) {
    console.error('Invalid parameter value');
  }
}

See Also