Solidity Intermediate Introduction
Solidity Intermediate builds bigger contracts from beginner pieces. Each lesson adds one new idea to pieces you already know.
A child reuses its parent's functions
Savings inherits from Vault. It gains deposit without rewriting it.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Vault {
uint256 public balance;
function deposit(uint256 amount) public {
balance += amount;
}
}
contract Savings is Vault {
function addBonus() public {
deposit(10);
}
}A modifier checks the caller first
The onlyOwner modifier guards setLimit. Only the owner can change the limit.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract OwnedVault {
address public owner;
uint256 public limit;
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
function setLimit(uint256 newLimit) public onlyOwner {
limit = newLimit;
}
}An event announces each deposit
Deposit writes a Deposited entry to the log. The log holds one entry after one deposit.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract LoggedVault {
uint256 public balance;
event Deposited(uint256 amount);
function deposit(uint256 amount) public {
balance += amount;
emit Deposited(amount);
}
}Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Vault {
uint256 public balance;
function deposit(uint256 amount) public {
balance += amount;
}
}
contract MemberVault is Vault {
address public owner;
event Deposited(uint256 amount);
event Withdrawn(uint256 amount);
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
function depositWithEvent(uint256 amount) public {
deposit(amount);
emit Deposited(amount);
}
function withdraw(uint256 amount) public onlyOwner {
require(amount <= balance, "too much");
balance -= amount;
emit Withdrawn(amount);
}
}Key points
- Inheritance: A child contract reuses a parent contract's functions and state.
- Modifiers: A modifier is a reusable check that runs before a function body.
- Events: An event is a public announcement a contract writes to its log.
- Combination: Small pieces combine into one contract that holds a balance, checks the caller, and reports each deposit.
- New ideas: Each later lesson introduces exactly one new idea at a time.
In this example, Vault holds the balance and the deposit function. MemberVault inherits from Vault and adds an owner, an onlyOwner modifier, and two events. depositWithEvent reuses the inherited deposit and then announces the deposit. withdraw is guarded by onlyOwner and reduces the balance.
Note
A contract that combines pieces still follows the same beginner rules for each piece.
Try it Yourself
Edit the code, then press Run.
Running is simulated Β· Remix IDE
Exercise
A child contract inherits from a parent. Which of the parent's pieces does the child gain?