solidity--function selector
https://solidity-by-example.org/function-selector/
When a function is called, the first 4 bytes of
calldata
This 4 bytes is called a function selector.
Take for example, this code below. It uses
calltransferaddr
调用函数时,前 4 个字节
calldata
这 4 个字节称为函数选择器。
The first 4 bytes returned from
abi.encodeWithSignature(....)
Perhaps you can save a tiny amount of gas if you precompute and inline the function selector in your code?
Here is how the function selector is computed.
例如,下面的这段代码。 它用
calltransferaddr
addr.call(abi.encodeWithSignature("transfer(address,uint256)", 0xSomeAddress, 123))
从返回的前 4 个字节
abi.encodeWithSignature(....)
如果您在代码中预先计算并内联函数选择器,也许您可以节省少量气体?
以下是函数选择器的计算方式。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
contract FunctionSelector {
/*
"transfer(address,uint256)"
0xa9059cbb
"transferFrom(address,address,uint256)"
0x23b872dd
*/
function getSelector(string calldata _func) external pure returns (bytes4) {
return bytes4(keccak256(bytes(_func)));
}
}