Four Types of Storage
- Storage (state variable, saved forever as opposed to only for the tx)
The storage location is permanent data, which means that this data can be accessed into all functions within the contract, just like the hard disk data of computer where all the data gets stored permanently. Keep in mind that storage data location is expensive compared to other data locations.
- Memory (function parameters including return parameters)
The memory location is temporary data and cheaper than the storage location. It can only be accessible within the function. Usually, Memory data is used to save temporary variables for calculation during function execution. Once the function gets executed, its contents are discarded. You can think of it as a RAM of each individual function.
- Calldata (immutable memory,除此等同于memory, more gas efficient)
Calldata is non-modifiable and non-persistent data location where all the passing values to the function are stored. Also, Calldata is the default location of parameters (not return parameters) of external functions.
- Stack
Stack is a non-persistent data maintained by EVM (Ethereum Virtual Machine). EVM uses stack data location to load the variables during execution. Stack location has the limitation up to 1024 levels.
- Rules
- State Variables are always stored in the storage,类似于全局变量,函数内部对变量的调动和修改会影响变量本身的取值
pragma solidity ^0.8.0; contract DataLocation { //storage uint256 public tokenCounter; object = {a: "1"} function create(string memory _svg) public { ... tokenCounter += 1; }
contract DataLocation { uint storage stateVariable; //Expected identifier but got 'storage' uint[] memory stateArray; //Linter: Parse error: extraneous input 'memory' expecting {'from', 'error', 'calldata', 'revert', 'callback', 'override', 'constant', 'immutable', 'leave', 'internal', 'payable', 'private', 'public', 'constructor', 'receive', Identifier} [undefined] }
contract DataLocation { function addUp(uint256 num1,uint256 num2) public pure returns(uint256 result){ return num1 + num2} }
合约内部调用另外合约的四种调用方式
- Call
- Callcode
- Delegatecall
- Staticall
- Take-out