Calldata

calldata is a special data location in Solidity that is used to pass arguments to a function when it is called. When a function is called externally, the arguments passed to it are stored in the calldata area of the transaction data. This is a read-only area of memory that contains the function call parameters.

In contrast to memory and storage, which are used to store data within a function or contract, calldata is used to store function arguments when calling the function from outside the contract. Since calldata is read-only, it is a cheaper and more efficient way to pass arguments to functions compared to copying data to memory or storage.

Here's an example of a function that takes a bytes parameter and reads the first 32 bytes of the bytes data:

pragma solidity ^0.8.0;

contract CalldataExample {
    function readFirst32Bytes(bytes calldata data) external pure returns (bytes32) {
        require(data.length >= 32, "Input data must be at least 32 bytes long");
        bytes32 result;
        assembly {
            result := mload(add(data, 32))
        }
        return result;
    }
}

In this example, the calldata keyword is used to specify that the data parameter is a reference to the input data passed to the function. The assembly block is used to read the first 32 bytes of the data parameter using the mload opcode. The resulting 32-byte value is returned from the function as a bytes32 value.

Last updated