Skill 2.3.3

Explain ABI encoding and function selectors

Key Concepts

A function call's calldata starts with a four-byte function selector: the first four bytes of the Keccak-256 hash of the canonical signature, for example keccak256("transfer(address,uint256)") starts with a9059cbb. The signature uses the function name and parameter types only, with no spaces, no parameter names and canonical type names such as uint256.

The arguments follow, ABI-encoded in 32-byte words: static types such as address and uint256 occupy one word each, and dynamic types such as string and arrays are encoded as an offset followed by length and data. Events use the same scheme: topic 0 is the Keccak-256 hash of the event signature, indexed parameters are further topics and the rest is in the log data. Custom errors are encoded like function calls with their own selector.

In Solidity, abi.encode produces standard encoding, abi.encodePacked a compact non-standard encoding, and abi.encodeCall a type-checked function call. web3.js provides web3.eth.abi.encodeFunctionSignature and encodeFunctionCall for the same purposes.