Function Selector
When you make a call to a function in an Ethereum smart contract, you need a way to specify which function you want to call. This is done using the function selector.
How is the Function Selector Determined?
Signature of the Function:
First, we get the "signature" of the function.
This signature is composed of the function name followed by its parameter types inside parentheses.
For instance, if you have a function
transfer(address,uint256)
, its signature would be"transfer(address,uint256)"
.
Keccak-256 Hash:
Next, this signature is hashed using the Keccak-256 hash function.
Keccak-256 is a specific cryptographic hashing function used widely in Ethereum.
First Four Bytes:
From the hash obtained in the previous step, only the first four bytes are taken.
These bytes are in big-endian format, which means the most significant byte comes first.
This resulting four-byte value is the function selector. When you make a call to the contract, the Ethereum Virtual Machine (EVM) uses this selector to determine which function in the contract you're referring to.
Notes:
Return Type Is Not Included:
When computing the signature of the function for the selector, the return type of the function is ignored.
This is a design choice in Solidity. When you have two functions with the same name and parameters but different return types (overloaded functions), they are still considered the same function in terms of call resolution. This makes the process of determining which function to call straightforward and not dependent on context.
ABI JSON Description:
While the function selector doesn't care about return types, the ABI's JSON description does.
The ABI (Application Binary Interface) describes how to interact with a contract, and it contains details about both inputs (function arguments) and outputs (return values). So, when you look at the ABI, you'll see a comprehensive view of the contract's functions, including their return types.
In simpler terms, when you want to "call" a function in a smart contract, you use a special "code" (the function selector) that uniquely identifies that function. This "code" is created by taking the name of the function and its parameters, hashing it, and then grabbing the first four bytes of that hash. This system ensures that every unique function has its own unique identifier, making interaction with contracts efficient and precise.
Last updated