Solidity – How to Determine Storage of Value-Type Function Arguments

calldatadata-typesmemorysoliditystorage

When we define a function, say test(uint256 val). I would presume val would be implicitly defined in memory. But what if we change the funtion visibility modifier, does that change the location of where val is defined?

I'm interested in 3 function visibility modifiers, public, internal, and external and their effect on the location where val would exist. I'm also interested in whether it would make a difference if we access the function internally or externally, given that the function visibility modifier is set. Does it make a difference if, say the function is defined as external and we try to access it internally from the same contract code vs if we access it externally from another contract or from an EOA?

Best Answer

Arguments passed to external and public functions are passed to the contract via calldata, if called from outside the contract (a transaction). They are not directly modifiable; (they are copied in memory if needed).

The function visibility does not change the storage position

https://docs.soliditylang.org/en/v0.8.7/introduction-to-smart-contracts.html?highlight=storage#storage-memory-and-the-stack

[...], the called contract (which can be the same as the caller) will receive a freshly cleared instance of memory and has access to the call payload - which will be provided in a separate area called the calldata.[...]

to check this you can create a simple contract with a function in remix like

    function asd(uint256 value) public pure returns(uint256) {
        value = value +100;
        return value;
    }

and by debugging the transaction you can see in the left-side memory panel that the value is copied to memory


unless specified by storage keyword, variables created inside functions are created in memory and are obviously not persistent between different transactions.

-- if, for example a contract function defines a new variable and then calls another function passing that variable as an argument, it will be read from memory, because it is where it was created originally.

Related Topic