Skip to main content

Using the ABICoder Class

The ABICoder class is a powerful utility for encoding and decoding data to interact with OP_NET smart contracts. It simplifies generating function selectors, encoding input parameters, and decoding returned data, ensuring seamless communication with OP_NET contracts.


Overview of the ABICoder Class

The ABICoder class is part of the @btc-vision/transaction library and supports the following functionalities:

  • Encoding function selectors
  • Decoding contract return data
  • Encoding complex data types for calldata

Supported Data Types

The ABICoder supports a wide range of data types defined in the ABIDataTypes enumeration:

export declare enum ABIDataTypes {
UINT8 = "UINT8",
UINT16 = "UINT16",
UINT32 = "UINT32",
UINT64 = "UINT64",
UINT128 = "UINT128",
UINT256 = "UINT256",
BOOL = "BOOL",
ADDRESS = "ADDRESS",
STRING = "STRING",
BYTES32 = "BYTES32",
TUPLE = "TUPLE",
BYTES = "BYTES",
ADDRESS_UINT256_TUPLE = "ADDRESS_UINT256_TUPLE",
ARRAY_OF_ADDRESSES = "ARRAY_OF_ADDRESSES",
ARRAY_OF_UINT256 = "ARRAY_OF_UINT256",
ARRAY_OF_UINT128 = "ARRAY_OF_UINT128",
ARRAY_OF_UINT64 = "ARRAY_OF_UINT64",
ARRAY_OF_UINT32 = "ARRAY_OF_UINT32",
ARRAY_OF_UINT16 = "ARRAY_OF_UINT16",
ARRAY_OF_UINT8 = "ARRAY_OF_UINT8",
ARRAY_OF_STRING = "ARRAY_OF_STRING",
ARRAY_OF_BYTES = "ARRAY_OF_BYTES",
}

Key Methods in ABICoder

1. encodeSelector

Generates a hexadecimal function selector based on the function name. The selector uniquely identifies a contract function.

encodeSelector(selectorIdentifier: string): string;

Example:

import { ABICoder } from "@btc-vision/transaction";

const abiCoder = new ABICoder();
const selector = abiCoder.encodeSelector("mint");
console.log("Hex Selector:", selector); // Outputs the hex representation of the mint function selector

2. numericSelectorToHex

Converts a numeric selector into a hexadecimal representation.

numericSelectorToHex(selector: number): string;

Example:

const numericSelector = 12345;
const hexSelector = abiCoder.numericSelectorToHex(numericSelector);
console.log("Hexadecimal Selector:", hexSelector);

3. decodeData

Decodes data returned from a contract based on specified ABI types.

decodeData(data: Uint8Array, types: ABIDataTypes[]): unknown[];

Example:

const returnedData = new Uint8Array([...]); // Replace with actual data
const decoded = abiCoder.decodeData(returnedData, [ABIDataTypes.UINT256, ABIDataTypes.ADDRESS]);
console.log("Decoded Data:", decoded);

Best Practices

  • Ensure the data types used in encoding and decoding match the contract's ABI definitions.
  • Store frequently used selectors (e.g., mint, transfer) in constants for consistency and reduced overhead.
  • Always simulate transactions to verify the correctness of your decoding logic before deploying to mainnet.

What’s Next?

Learn how to create custom calldata for OP_NET contracts and optimize interactions: