Convert Function to Function Selector

Generates the function selector (4 byte encoding) for a given function definition.


1. What is a function selector?

The function selector is a 4 byte identifier for functions in Solidity.

2. How does it work?

How is the function selector calculated?

The function selector is given by turning a function into a signature, hashing the signature with keccak256, and taking the first 4 bytes. An example and function follows below on how to derive the function selector.

1function toSelector(string memory signature) internal pure returns (bytes4) {
2    return bytes4(keccak256(signature));
3}

Reversing the operation from function selector to function is not as straight-forward. Instead, we suggest the reversal to use the Ethereum Signature Database.

3. Examples

ERC-20 balanceOf function

balanceOf(address)0x70a08231

ERC-721 ownerOf function

ownerOf(uint256)0x6352211e

Complex function with array parameter

batch((address,address,uint256,bytes)[])0xc16ae7a4

References