Search code examples
ethereumblockchainsoliditysmartcontracts

Why calldata in solidity?


I'm a bit confused about the purpose of calldata in Solidity functions. We already have the memory keyword to handle data within a function, so why would we need to use calldata? Additionally, it seems that calldata is not considered immutable. Could someone please clarify this for me?

I'm just trying to learn the main concepts of data locations and Calldata just confused me.


Solution

  • Calldata is the input coming from the call of your function. Either from the end user sending a transaction/call to your contract, or from another contract calling yours.

    Because of this, calldata really is immutable

    pragma solidity 0.8.21;
    
    contract MyContract {
        function foo(string calldata someInput) external {
            // error - cannot assign to calldata variable
            someInput = "hello";
        }
    
        function foo2(string memory someInput) external pure {
            // ok
            someInput = "hello";
        }
    }
    

    why would we need to use calldata

    It's often good approach to write your code as restrictive as possible. If the contract doesn't need to modify the input, it doesn't have to have a way to do it.

    It's also cheaper gas-wise. When the function is called with value "a" for example, this value is already stored in calldata. If you accept a memory location, the EVM needs to first copy it from calldata to memory, which costs gas.