CH5-Data Storage and Scope

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

CH6-Array & Struct

CH7-Mapping

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:

Note:

  1. Storage: Mappings can only have the storage data location and are generally used for state variables.
  2. Public Visibility: When declared public, Solidity automatically creates a getter function for the mapping.