0

It is common for calldata to be encoded as bytes calldata when developing contracts in Solidity.

I need to extract the function selector from such a bytes var. What's the best way to load the first 4 bytes?

2

Most gas-efficient way is to use inline assembly:

function foo(bytes calldata data) external payable {
    bytes4 selector;
    assembly {
        selector := calldataload(data.offset)
    }
    // ...
}

The offset suffix is a special property that we need to use in inline assembly to be able to read high-level storage variables.

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.