I’ve recently been re-learning solidity, consolidating the details, and writing a “Solidity Minimalist Primer” for beginners to use (programming guys can find another tutorial), updated 1-3 times a week.
All code and tutorials are open source at github:github.com/AmazingAng/WTFSolidity
When we call a function of a smart contract, the first 4 bytes of the bytecode sent are the selector. In this talk, we’ll cover what a selector is and how to use it.
msg.data is a global variable in Solidity with the value of full calldata (the bytecode that calls the function).
In the following code, we can use the Log event to output the calldata that calls the mint function:
When the parameter is 0x2c44b726ADF1963cA47Af88B284C06f30380fC78, the output calldata is
This messy bytecode can be broken down into two parts:
In fact, calldata tells the smart contract which function I want to call and what the parameters are.
A selector is defined as the first 4 bytes of the hash of the function signature, so what is a function signature?
In fact, in Lecture 21, we briefly introduced the function signature, which is “function name (comma-separated parameter type)”. For example, the function signature for mint in the code above is “mint(address)”. In smart contracts, different functions have different function signatures, so we can determine which function to call through the function signature.
Note that in the function signature, uint and int should be written as uint256 and int256.
Let’s write a function to verify that the selector of the mint function is 0x6a627842. You can run the following function and see the result.
We can use the selector to call the target function. For example, if I want to call the mint function, I just need to use abi.encodeWithSelector to encode the selector and parameters of the mint function and pass it to the call function:
In the log, we can see that the mint function is successfully called and the Log event is output.
In this talk, we introduced what a function selector is, how it relates to msg.data, function signatures, and how to use it to call an objective function.