SolidityIn

ABI encoding and function selectors

Lesson 22 of 40 · EVM

Contracts talk through call data, a block of bytes. The first four bytes, called the function selector, say which function to run. The rest are the arguments, encoded using the ABI rules and padded to 32 bytes each.

The selector is the first four bytes of the keccak256 hash of the function signature, written as the name and parameter types with no spaces, for example transfer(address,uint256). That is how the contract finds the right code, and why two functions with the same signature cannot exist.

Events and errors use the same idea. An event's first topic is the hash of its signature, and a custom error is identified by a four-byte selector. This is how tools decode logs and failures using only the ABI.

You can build call data yourself and send it with a low-level call. Prefer abi.encodeCall, which checks argument types at compile time. Low-level calls do not revert automatically when the target fails, so always check the success flag.

contract Selectors {
    event Ping(address indexed who, uint256 n);

    function ping(address who, uint256 n) external {
        emit Ping(who, n);
    }
    function pingSelector() external pure returns (bytes4) {
        return bytes4(keccak256("ping(address,uint256)"));
    }
    function eventTopic() external pure returns (bytes32) {
        return keccak256("Ping(address,uint256)");
    }
    function encodeIt(address who, uint256 n) external pure returns (bytes memory) {
        return abi.encodeCall(Selectors.ping, (who, n));
    }
    function callSelf(address who, uint256 n) external returns (bool ok) {
        (ok, ) = address(this).call(abi.encodeCall(Selectors.ping, (who, n)));
    }
}

Try it yourself

In Remix, call pingSelector and compare it with the first four bytes of the data returned by encodeIt. Then call callSelf and find the Ping event in the logs.

Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.

Quick check: How is a function selector made?