2

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.

4

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).

| improve this answer | |
  • thanks for the feedback! – Erzo Oct 5 at 9:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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