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.
solidity
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) → 0x70a08231ERC-721 ownerOf function
ownerOf(uint256) → 0x6352211eComplex function with array parameter
batch((address,address,uint256,bytes)[]) → 0xc16ae7a44. Source Code
typescript
1// npm install viem
2
3import { keccak256, toBytes, toFunctionSelector } from 'viem';
4
5// Calculate function selector (4 bytes) from function signature
6function getFunctionSelector(functionSignature: string): string {
7 // Hash the function signature with keccak256
8 const hash = keccak256(toBytes(functionSignature));
9
10 // Take first 4 bytes (8 hex characters + 0x)