SimpleStorage: Your First Smart Contract

The SimpleStorage contract is often the first smart contract that developers write when learning Solidity. It demonstrates fundamental concepts like state variables, functions, and storage while remaining easy to understand.
Contract Overview
This contract does exactly what its name suggests: it stores a number on the blockchain. While simple, it introduces several key concepts that are essential for understanding smart contracts:
- State variables and storage
- Public variables and getter functions
- Function visibility and modifiers
- Basic contract interaction
The Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract SimpleStorage {
uint public storedNumber;
// Store a number
function set(uint _num) public {
storedNumber = _num;
}
// Retrieve the stored number
function get() public view returns (uint) {
return storedNumber;
}
}Breaking It Down
1. License and Version
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;Every Solidity file should start with a license identifier and a pragma directive. The pragma specifies which Solidity version to use (^0.8.20 means "0.8.20 or higher, but less than 0.9.0").
2. State Variable
uint public storedNumber;This line declares a state variable that will be stored on the blockchain:
uint: An unsigned integer (can only store positive numbers)public: Automatically creates a getter functionstoredNumber: The name of our variable
3. Set Function
function set(uint _num) public {
storedNumber = _num;
}This function allows anyone to update the stored number:
public: Makes the function callable by anyoneuint _num: Takes a number as input- Updates the state variable with the new value
4. Get Function
function get() public view returns (uint) {
return storedNumber;
}This function retrieves the stored number:
view: Indicates this function doesn't modify statereturns (uint): Specifies the return type- Note: This function is actually redundant since we made
storedNumberpublic
Key Concepts
State Variables
Variables declared outside functions are stored on the blockchain. They persist between transactions and cost gas to modify.
Function Visibility
public functions can be called by anyone. Other options include private, internal, and external.
View Functions
Functions marked as view don't modify state and are free to call (they don't require a transaction).
Public Variables
When a state variable is declared as public, Solidity automatically generates a getter function for it.
Next Steps
While this contract is simple, it's a great foundation for learning more complex concepts:
- Add access control to restrict who can set the number
- Store multiple numbers using arrays or mappings
- Add events to track changes
- Implement more complex data structures
#SmartContracts #Solidity #Ethereum #Web3 #Blockchain #Development #Tutorial