Storage location:
| Location | Description | Example |
|---|---|---|
| Storage | • Persistent storage that exists between function calls and transactions | |
| • Used for state variables, declared outside of functions | ||
| • high gas costs | ||
| • Data is stored permanently on-chain | ||
| `contract StorageExample { | ||
| uint256 public storedData; // Storage variable |
function setStoredData(uint256 newValue) public {
storedData = newValue; // Modifies storage
}
}| | Memory | • Temporary storage that only exists during function execution • Used for function parameters, return values, and local variables • Much cheaper than storage in terms of gas costs • Data is erased after function completes |function memoryExample(uint[] memory myArray) public pure returns (uint) {
uint[] memory localArray = new uint;
localArray[0] = 1;
return localArray[0];
}| | Calldata | •Read-only temporary storage for function parameters •Only available for external function parameters •cheapest for gas cost •immutable |function calldataExample(uint[] calldata myArray) external pure returns (uint) {
return myArray[0]; // Read from calldata
}` |
Variable scope:
| Scope | Description |
|---|---|
| State Variables | •Declared outside of functions at the contract level |
| •Stored permanently in contract storage | |
| •Accessible by all functions in the contract | |
| •Persist between function calls and transactions | |
| Local Variables | •Declared inside functions |
| •Only accessible within the function they are declared | |
| •Stored in memory and erased after function execution | |
| •Do not persist between function calls | |
| Global Variables | •Special variables provided by Solidity |
| •Accessible anywhere within a contract | |
| •Provide information about the blockchain and transaction | |
•For example: msg.sender |
Mapping is used to store key-value pairs. They function similarly to hash tables in other programming languages
Syntax: mapping(keyType => valueType) visibility variableName;
Key Characteristics:
uint, address, or bytes32. Complex types like arrays or structs are not allowed as keys.uint).Note: