Lesson 3 of 3 Compiling Smart Contracts

ABI Encoding and Function Selectors

Every contract call is a sequence of bytes built by the ABI encoding rules. This lesson explains function selectors, how arguments are encoded, how events and errors use the same scheme, and the encoding functions available in Solidity and web3.js.

Learning outcomes

After completing this lesson, you will be able to:

  • Calculate how a function selector is derived.
  • Describe how arguments are ABI-encoded.
  • Describe how events and errors are encoded.
  • Choose between abi.encode, abi.encodePacked and abi.encodeCall.

Function selectors

The calldata of a function call begins with a four-byte function selector, which the contract uses to decide which function to run. The selector is the first four bytes of the Keccak-256 hash of the function's canonical signature: its name followed by the parameter types in parentheses, with no spaces, no parameter names, no return types and canonical type names.

SignatureSelector
transfer(address,uint256)0xa9059cbb
balanceOf(address)0x70a08231
approve(address,uint256)0x095ea7b3
transferFrom(address,address,uint256)0x23b872dd

Writing transfer(address, uint) or transfer(address to,uint256 amount) produces a different, wrong hash. Two different signatures can, rarely, share a selector; the compiler rejects such clashes within one contract, but they matter in proxies, where the proxy's own functions could clash with the implementation's.

The following diagram builds the calldata for a transfer call.

How calldata is built for a function call. The canonical signature is the function name and parameter types, with no spaces, parameter names or return types, such as transfer(address,uint256). The selector is the first four bytes of its Keccak-256 hash, 0xa9059cbb. The calldata is the selector followed by the ABI-encoded arguments, each padded to 32 bytes. A signature written with spaces or parameter names gives a different, wrong selector.
The selector routes the call; the arguments follow in 32-byte words.
Sort into groups

Canonical signatures

Exam skills 2.3.3

Decide whether each string is a canonical signature that hashes to the correct selector.

Log in to try this activity Interactive activities are free with an account.

Encoding arguments

After the selector come the arguments, encoded in 32-byte words. Static types, such as uint256, address, bool and bytes32, are padded to one word each. Dynamic types, such as string, bytes and dynamic arrays, are represented in the head by an offset pointing to the tail, where their length and contents are stored.

transfer(0x70997970C51812dc3A010C7d01b50e0d17dc79C8, 1000)

a9059cbb                                                          selector
00000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8  address, left-padded
00000000000000000000000000000000000000000000000000000000000003e8  1000 in hex

Return values are encoded the same way, without a selector, and constructor arguments are appended to the creation bytecode in the same format.

Fill in the number

Sizing calldata

Exam skills 2.3.3

Work out the size of ABI-encoded calldata.

Log in to try this activity Interactive activities are free with an account.

Events and errors

Events use the same building blocks. Topic 0 of a log is the full 32-byte Keccak-256 hash of the event signature, for example Transfer(address,address,uint256); each indexed parameter is another topic; and non-indexed parameters are ABI-encoded in the log's data. Indexed dynamic values, such as strings, are stored as their hash, so the original value cannot be recovered from the topic.

Custom errors are encoded like function calls: a four-byte selector from the error signature followed by encoded arguments. require with a message produces the built-in Error(string) error (selector 0x08c379a0), and failed assertions and arithmetic errors produce Panic(uint256) (selector 0x4e487b71).

Match the pairs

Recognising encoded data

Exam skills 2.3.3

Match each piece of encoded data with what it identifies.

Log in to try this activity Interactive activities are free with an account.

Encoding functions

The following table lists the encoding functions available on chain and off chain.

FunctionWhereProduces
abi.encode(...)SolidityStandard ABI encoding of the values
abi.encodePacked(...)SolidityTightly packed, non-standard encoding without padding
abi.encodeWithSelector / encodeWithSignatureSoliditySelector plus encoded arguments
abi.encodeCall(f, (args))SolidityType-checked selector plus arguments
abi.decode(data, (types))SolidityDecoded values
web3.eth.abi.encodeFunctionSignatureweb3.jsThe four-byte selector
web3.eth.abi.encodeFunctionCallweb3.jsComplete calldata for a function call
web3.eth.abi.encodeEventSignatureweb3.jsThe 32-byte topic 0 of an event

Packed encoding collisions

abi.encodePacked of two or more dynamic values can be ambiguous: ("ab", "c") and ("a", "bc") pack to the same bytes. Hashing such packed data to create identifiers or signature messages can let an attacker forge a collision. Use abi.encode for hashing multiple dynamic values.

Scenario questions

Choosing an encoding function

Exam skills 2.3.3

Pick the encoding function that fits each task.

Log in to try this activity Interactive activities are free with an account.
Worked example

Decoding a transaction

A block explorer shows a transaction to a token contract with input data starting 0x095ea7b3. The contract is not verified. What did the sender most likely do?

0x095ea7b3 is the selector of approve(address,uint256), so the sender most likely granted an allowance: the next 32 bytes are the spender and the following 32 bytes the amount. Public selector databases map selectors to known signatures, which is how explorers label calls to unverified contracts, although a matching selector does not prove the function's behaviour.

Worked example

A wrong signature

A script computes a selector with web3.eth.abi.encodeFunctionSignature("transfer(address to, uint amount)") and sends the call. The transaction reverts or hits the fallback function. Why?

The signature is not canonical: it contains parameter names, spaces and the alias uint. The correct string is transfer(address,uint256), which hashes to 0xa9059cbb. Passing the function's ABI fragment instead of a hand-written string avoids this class of error.

Check yourself

What string is hashed to get the selector of function approve(address spender, uint amount)?

Show answer

approve(address,uint256): the name and canonical parameter types, with no spaces, no parameter names and uint expanded to uint256. The selector is the first four bytes of its Keccak-256 hash.

Exam Tips

Remember for the exam

  • Selector = first 4 bytes of keccak256 of the canonical signature (no spaces, names or aliases).
  • Arguments are encoded in 32-byte words; dynamic types use offsets.
  • Event topic 0 is the full hash of the event signature; indexed values become topics.
  • Use abi.encode, not abi.encodePacked, when hashing several dynamic values.