Solidity Exercises
Time to practise! Each exercise has a starter playground that compiles and runs as-is, printing a placeholder result so you can see the expected format. Replace the TODO parts, press Run, and compare your output with the "Expected" lines. If you get stuck, open the solution, but try for a few minutes first.
| # | Exercise | Topics |
|---|---|---|
| 1 | Sum of even numbers | loops, pure functions |
| 2 | Safe percentage | integer math, require |
| 3 | Guest list | mappings, custom errors |
| 4 | Simple vault | payable, msg.value, sending ether |
| 5 | Onlyowner pause switch | modifiers, events |
| 6 | Shape areas | interfaces, inheritance |
| 7 | Voting with users | structs, arrays, helper contracts |
1. Sum of even numbers
Write sumEvens(n) that returns the sum of all even numbers from 1 to n (inclusive).
Expected: sumEvens(10) = 30 and sumEvens(7) = 12.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Main {
function sumEvens(uint256 n) public pure returns (uint256 total) {
// TODO: loop from 1 to n and add the even numbers
n;
total = 0;
}
function main() external pure {
console.log("sumEvens(10) =", sumEvens(10));
console.log("sumEvens(7) =", sumEvens(7));
}
}sumEvens(10) = 0
sumEvens(7) = 0
Show solution
function sumEvens(uint256 n) public pure returns (uint256 total) {
for (uint256 i = 2; i <= n; i += 2) {
total += i;
}
}2. Safe percentage
Write percentOf(amount, bps) that returns amount × bps / 10000 (bps = basis points). It must revert with "bps above 100%" if bps > 10000. Multiply before dividing.
Expected: percentOf(1999, 250) = 49, then main() failed: reverted with reason: bps above 100%.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Main {
function percentOf(uint256 amount, uint256 bps) public pure returns (uint256) {
// TODO: validate bps and compute the result
amount; bps;
return 0;
}
function main() external pure {
console.log("percentOf(1999, 250) =", percentOf(1999, 250));
percentOf(100, 20000);
}
}percentOf(1999, 250) = 0
Show solution
function percentOf(uint256 amount, uint256 bps) public pure returns (uint256) {
require(bps <= 10_000, "bps above 100%");
return amount * bps / 10_000;
}3. Guest list
Complete GuestList: invite(address) adds a guest and reverts with the custom error AlreadyInvited(guest) if the guest is already on the list; count tracks the number of guests.
Expected: guests: 2, bob invited? true, then main() failed: custom error AlreadyInvited(0x0000000000000000000000000000000000000B0b).
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract GuestList {
error AlreadyInvited(address guest);
mapping(address => bool) public invited;
uint256 public count;
function invite(address guest) external {
// TODO: revert if already invited, otherwise record the guest and increase count
guest;
}
}
contract Main {
function main() external {
GuestList list = new GuestList();
list.invite(address(0xA11CE));
list.invite(address(0xB0B));
console.log("guests:", list.count());
console.log("bob invited?", list.invited(address(0xB0B)));
list.invite(address(0xB0B));
}
}guests: 0
bob invited? false
Show solution
function invite(address guest) external {
if (invited[guest]) revert AlreadyInvited(guest);
invited[guest] = true;
count += 1;
}4. Simple vault
Complete Vault so that deposit() is payable and records msg.value per sender, and withdraw(amount) sends ether back with call, following checks-effects-interactions. The Saver helper plays a user.
Expected: saver balance in vault: 3, vault holds: 3, after withdrawing 2: saver got back: 2, vault holds: 1.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Vault {
mapping(address => uint256) public balances;
function deposit() external payable {
// TODO: record msg.value for msg.sender
}
function withdraw(uint256 amount) external {
// TODO: check the balance, update it, then send `amount` with call
amount;
}
}
contract Saver {
receive() external payable {}
function save(Vault v) external payable { v.deposit{value: msg.value}(); }
function take(Vault v, uint256 amount) external { v.withdraw(amount); }
}
contract Main {
constructor() payable {}
function main() external {
Vault vault = new Vault();
Saver saver = new Saver();
saver.save{value: 3 ether}(vault);
console.log("saver balance in vault:", vault.balances(address(saver)) / 1 ether);
console.log("vault holds:", address(vault).balance / 1 ether);
saver.take(vault, 2 ether);
console.log("saver got back:", address(saver).balance / 1 ether);
console.log("vault holds:", address(vault).balance / 1 ether);
}
}saver balance in vault: 0
vault holds: 3
saver got back: 0
vault holds: 3
Show solution
function deposit() external payable {
balances[msg.sender] += msg.value;
}
function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount, "insufficient");
balances[msg.sender] -= amount;
(bool ok, ) = payable(msg.sender).call{value: amount}("");
require(ok, "transfer failed");
}5. Pause switch
Write a modifier onlyOwner and a modifier whenNotPaused, and use them: setPaused(bool) is owner-only and emits PausedChanged(bool paused); doWork() only runs when not paused.
Expected: work done: 1, then main() failed: reverted with reason: paused. (The PausedChanged event is not listed, because events are only printed when main() succeeds and a revert discards them.)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Machine {
address public owner = msg.sender;
bool public paused;
uint256 public workDone;
event PausedChanged(bool paused);
// TODO: modifier onlyOwner, modifier whenNotPaused
function setPaused(bool p) external { // TODO: owner only, emit the event
paused = p;
}
function doWork() external { // TODO: only when not paused
workDone += 1;
}
}
contract Main {
function main() external {
Machine m = new Machine();
m.doWork();
console.log("work done:", m.workDone());
m.setPaused(true);
m.doWork();
}
}work done: 1
Show solution
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
modifier whenNotPaused() {
require(!paused, "paused");
_;
}
function setPaused(bool p) external onlyOwner {
paused = p;
emit PausedChanged(p);
}
function doWork() external whenNotPaused {
workDone += 1;
}6. Shape areas
Implement the IShape interface in Rectangle and Square. Square should inherit from Rectangle and pass its side twice to the parent constructor.
Expected: rectangle area: 24, square area: 49, total: 73.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
interface IShape {
function area() external view returns (uint256);
}
contract Rectangle is IShape {
uint256 public immutable width;
uint256 public immutable height;
constructor(uint256 w, uint256 h) {
width = w;
height = h;
}
function area() external view returns (uint256) {
return 0; // TODO
}
}
contract Square is Rectangle {
constructor(uint256 side) Rectangle(side, 0) {} // TODO: pass the right values
}
contract Main {
function main() external {
IShape[] memory shapes = new IShape[](2);
shapes[0] = new Rectangle(4, 6);
shapes[1] = new Square(7);
console.log("rectangle area:", shapes[0].area());
console.log("square area:", shapes[1].area());
console.log("total:", shapes[0].area() + shapes[1].area());
}
}rectangle area: 0
square area: 0
total: 0
Show solution
function area() external view returns (uint256) {
return width * height;
}
contract Square is Rectangle {
constructor(uint256 side) Rectangle(side, side) {}
}7. Voting with users
Complete Poll.vote(uint256 option): each address may vote once (require(!hasVoted[msg.sender], "already voted")), the option must exist, and the vote is counted in options[option].votes. Write winner() returning the name of the option with most votes. Three Voter helper contracts play the users.
Expected: Tea: 2, Coffee: 1, winner: Tea, then main() failed: reverted with reason: already voted.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Poll {
struct Option { string name; uint256 votes; }
Option[] public options;
mapping(address => bool) public hasVoted;
constructor() {
options.push(Option("Tea", 0));
options.push(Option("Coffee", 0));
}
function vote(uint256 option) external {
// TODO: one vote per address, option must exist, count the vote
option;
}
function winner() external view returns (string memory) {
// TODO: find the option with the most votes
return options[0].name;
}
}
contract Voter {
function vote(Poll p, uint256 option) external { p.vote(option); }
}
contract Main {
function main() external {
Poll poll = new Poll();
Voter a = new Voter();
Voter b = new Voter();
Voter c = new Voter();
a.vote(poll, 0);
b.vote(poll, 1);
c.vote(poll, 0);
(string memory n0, uint256 v0) = poll.options(0);
(string memory n1, uint256 v1) = poll.options(1);
console.log(string.concat(n0, ":"), v0);
console.log(string.concat(n1, ":"), v1);
console.log("winner:", poll.winner());
a.vote(poll, 1);
}
}Tea: 0
Coffee: 0
winner: Tea
Show solution
function vote(uint256 option) external {
require(!hasVoted[msg.sender], "already voted");
require(option < options.length, "no such option");
hasVoted[msg.sender] = true;
options[option].votes += 1;
}
function winner() external view returns (string memory) {
uint256 best = 0;
for (uint256 i = 1; i < options.length; i++) {
if (options[i].votes > options[best].votes) best = i;
}
return options[best].name;
}Test yourself
In exercise 4, why is the balance reduced before the ether is sent?
- To save gas
- To follow checks-effects-interactions and prevent reentrancy
- Because
callrequires it - It doesn't matter
In exercise 7, how are several users simulated?
- With different private keys
- By deploying
Voterhelper contracts; each has its own address asmsg.sender - By changing
tx.origin - By calling
votewith an address argument