17

I tried to edit this function according to my smart contract but I couldn't understand this function. I read the docs already. can someone explain this to me with more details and examples? Thank you.

1 Answer 1

21

A function selector is the first 4 bytes in the hash of the function's prototype.

A function prototype is defined as the function's name and its argument types by order.

It allows you, for example, to call a function without knowing its exact return-value type:

bytes4 private constant FUNC_SELECTOR = bytes4(keccak256("someFunc(address,uint256)"));

function func(address _contract, address _param1, uint256 _param2) view returns (uint256, uint256) {
    bytes memory data = abi.encodeWithSelector(FUNC_SELECTOR, _param1, _param2);
    (bool success, bytes memory returnData) = address(_contract).staticcall(data);
    if (success) {
        if (returnData.length == 64)
            return abi.decode(returnData, (uint256, uint256));
        if (returnData.length == 32)
            return (abi.decode(returnData, (uint256)), 0);
    }
    return (0, 0);
}

More generally, it allows you to call a function by its string name (similarly to reflection in Java).

2
  • but how is any different from abi.encodePacked(FUNC_SELECTOR, _param1, _param2)?
    – axwell
    Oct 13, 2021 at 18:02
  • @axwell It encodes the parameter, starting from second and then after encoding, it prepends the 4bytes ( which is the function selector) on it. abi.encodePacked doesn't do this. It does a packed encoding of all arguments combined
    – 0xAnon
    Mar 4, 2022 at 17:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.