Lesson 03 of 25
Your First Smart Contract
Write, compile, and deploy a SimpleStorage contract step-by-step.
BeginnerThe SimpleStorage Contract
Let's build a contract that stores and retrieves a number. This covers the core lifecycle: write → compile → deploy → interact.
Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
// State variable — stored permanently on the blockchain
uint256 private storedNumber;
// Write to storage (costs gas)
function store(uint256 _number) public {
storedNumber = _number;
}
// Read from storage (free — view function)
function retrieve() public view returns (uint256) {
return storedNumber;
}
}
Understanding the Code
Let's break down each part:
// SPDX-License-Identifier: MIT— Required license comment. Use MIT for open-source.pragma solidity ^0.8.0;— Accept compiler versions 0.8.0 and above (but not 0.9.0).uint256 private storedNumber;— A state variable that persists on the blockchain.public view returns (uint256)—viewmeans the function reads but doesn't write state.
Deploying in Remix
- Paste the contract into a new file in Remix
- Go to the Solidity Compiler tab and click Compile
- Go to Deploy & Run Transactions
- Select JavaScript VM (London) as the environment
- Click Deploy
- Expand the deployed contract and call
store(42) - Call
retrieve()— you should see42returned
Adding a Constructor
Constructors run once at deployment time. Use them to set initial state.
Solidity
contract SimpleStorage {
uint256 private storedNumber;
address public owner;
// Constructor runs once at deployment
constructor(uint256 _initialValue) {
storedNumber = _initialValue;
owner = msg.sender; // the deploying address
}
function store(uint256 _number) public {
storedNumber = _number;
}
function retrieve() public view returns (uint256) {
return storedNumber;
}
}