At Raka's Shirt Shop's gift table, every customer may take one free sticker. A careful clerk crosses the name off first, then hands over the sticker. A clerk who hands over the sticker first can be fooled by a customer who asks again before the name is crossed off. A contract has the same problem, with more at stake: it is public, anyone can call any function with any input, and after deploy its code can't be fixed. Smart contract security means making sure a contract does only what it promises, even when whoever calls it means harm. This lesson is the defender's side: each bug class, how to recognise it, its fix, and a test that proves the fix, all on toy contracts on a local chain.
Access control: who may do it
The most common and costliest bug (number 1 in the OWASP Smart Contract Top 10:2026) is an important function with no guard. If RakaPoints's earn had no onlyOwner, anyone could mint PTS for themselves. With onlyOwner, Dinda is refused with OwnableUnauthorizedAccount(Dinda), and a test in the Testing lesson proves it. If Raka has several cashiers, use roles:
contract RakaPointsCashier is ERC20, AccessControl {
bytes32 public constant CASHIER_ROLE = keccak256("CASHIER_ROLE");
constructor() ERC20("Raka Points", "PTS") {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender); // Raka: may add and remove cashiers
}
function earn(address customer, uint256 cents) external onlyRole(CASHIER_ROLE) {
_mint(customer, (cents / 100) * 10 ** 18);
}
}
On the local chain, Raka himself calls earn and is refused: AccessControlUnauthorizedAccount(0xf39F...2266, 0xff3317e1...a3fe). The admin is not a cashier; he has to grantRole(CASHIER_ROLE, ...) first. Once Yoga has that role, earn from Yoga succeeds.
Reentrancy
Reentrancy happens when a contract calls outside code before it has finished updating its state, and that outside code calls the same function back. The classic case is sending ETH (The DAO, 2016). In Raka's world the path is _safeMint: when the receiver is a contract, ERC-721 calls the receiver's onERC721Received. That is an external call.
// VULNERABLE TOY for practice: don't deploy
function claim() external {
if (hasClaimed[msg.sender]) revert AlreadyClaimed(); // checks
_safeMint(msg.sender, ++totalClaimed); // interaction: calls the receiver
hasClaimed[msg.sender] = true; // effects: too late
}
The fix is the Checks-Effects-Interactions (CEI) pattern: check, update state, only then call out. An extra layer is nonReentrant from OpenZeppelin 5.6.1. Use ReentrancyGuardTransient (EIP-1153 transient storage); the storage-based ReentrancyGuard is marked deprecated and will be replaced in v6.
function claim() external nonReentrant {
if (hasClaimed[msg.sender]) revert AlreadyClaimed(); // checks
hasClaimed[msg.sender] = true; // effects first
_safeMint(msg.sender, ++totalClaimed); // interaction last
}
The test uses a test double ReentrantReceiver, a receiving contract that calls claim() once more from onERC721Received:
Security: reentrancy through _safeMint
✔ vulnerable version: one address gets 2 stickers
✔ CEI fix: the second claim is refused with AlreadyClaimed
✔ CEI fix + nonReentrant: refused with ReentrancyGuardReentrantCall
✔ an ordinary customer can still claim once
So in the vulnerable version one address gets 2 stickers, and a receiver that keeps calling back could get more. In the CEI version the second call reverts, and that revert cancels the whole transaction: the receiver gets nothing.
Unchecked external calls
ERC-20's transfer and transferFrom return a bool. OpenZeppelin reverts on failure, but some older tokens just return false. A contract that ignores it hands out free vouchers:
points.transferFrom(msg.sender, address(this), 100e18); // VULNERABLE: return value ignored
points.safeTransferFrom(msg.sender, address(this), 100e18); // using SafeERC20 for IERC20
With a fake token that always answers false, the vulnerable version adds a voucher even though no token moved; the SafeERC20 version reverts SafeERC20FailedOperation(token). The same goes for (bool ok, ) = to.call{value: x}(""): always check ok.
Numbers: overflow, unchecked, casts
Since Solidity 0.8, 5 - 10 on a uint8 reverts: Arithmetic operation resulted in underflow or overflow. Two gaps remain, and both were shown on the local chain:
- inside
unchecked { },5 - 10becomes 251 with no error; - an explicit cast isn't checked:
uint8(300)becomes 44. UseSafeCast.toUint8(300), which revertsSafeCastOverflowedUintDowncast(8, 300).
tx.origin is not msg.sender
tx.origin is the account that signed the transaction; msg.sender is the direct caller. require(tx.origin == owner) passes for any contract Raka calls, including a malicious one that then calls withdraw() in Raka's name. Use msg.sender (or onlyOwner, which uses msg.sender).
Front-running and the approve race
Transactions wait in the mempool before entering a block, and others can get ahead of them. The ERC-20 lesson showed PointsSwap taking 90 PTS while Dinda lowered her allowance from 70 to 20. OpenZeppelin 5 removed increaseAllowance, so the defences are: approve the amount you'll use right before using it, lower to 0 before changing it, or permit (ERC-2612, ERC20Permit): an exact allowance with a deadline, signed at the moment of use. For swaps, use minOut and a deadline (the DeFi lesson).
Oracle manipulation
A contract that reads a price from a pool's reserves can be fooled within one transaction: in the DeFi lesson PTS's price in the toy pool moved from 50 to 199.70 MILL. Use an oracle price feed or a TWAP, check the data's age, and set sane limits.
Tools and process
Slither 0.11.6 (static analysis) finds the reentrancy in the vulnerable version and nothing in the CEI version:
$ slither contracts/security/FreeSticker.sol --solc-remaps "@openzeppelin/=node_modules/@openzeppelin/" --detect reentrancy-no-eth,reentrancy-benign,reentrancy-events
Detector: reentrancy-no-eth
Reentrancy in FreeSticker.claim() (contracts/security/FreeSticker.sol#15-19):
External calls:
- _safeMint(msg.sender,++ totalClaimed) (contracts/security/FreeSticker.sol#17)
...
State variables written after the call(s):
- hasClaimed[msg.sender] = true (contracts/security/FreeSticker.sol#18)
Careful: with --filter-paths node_modules this finding disappears, because its call path runs through OpenZeppelin's code. For VulnerablePointsSwap, Slither flags unchecked-transfer and tx-origin. Other tools: Mythril (symbolic execution; its last release is 0.24.8, March 2024), fuzzing and invariant tests with Foundry or Echidna, then an outside audit and a bug bounty after deploy. The SWC Registry that old tutorials quote has not been maintained since 2020 and points to the EEA EthTrust Security Levels; an actively maintained list is, for example, the OWASP Smart Contract Top 10:2026.
⚠️ Holes that most often slip past review
- Admin functions with no guard. Every function that mints, withdraws or changes the rules needs
onlyOwneror a role, plus a test proving others are refused. - Calling out before updating state.
_safeMint, ERC-721'ssafeTransferFromand sending ETH can all run the receiver's code. CEI first,nonReentrantas a second layer. - Trusting tools alone. Slither misses logic bugs and can be blinded by a filter; tests, review and an audit are still needed.
- Assuming 0.8 guards every number.
uncheckedand explicit casts aren't checked. - Using
tx.origin == msg.senderas a guard. Since EIP-7702 (Pectra, May 2025), an EOA can run contract code. So this check no longer proves the caller is a plain account without code, and it does not stop reentrancy.msg.sender.code.length == 0cannot be trusted for this either. Use CEI andnonReentrant.
TL;DR: Guard every important function with onlyOwner or onlyRole (access control, number 1 in the OWASP Smart Contract Top 10:2026). Reentrancy: a contract calls outside code before updating its state and gets called back; fix it with Checks-Effects-Interactions (update state before the external call) and nonReentrant from ReentrancyGuardTransient. Check external call results (SafeERC20, ok from call). Remember that unchecked and casts aren't checked (uint8(300) = 44; use SafeCast). Use msg.sender, not tx.origin. Counter front-running with small approvals, permit, minOut and a deadline, and oracle manipulation with a price feed or a TWAP. Prove every fix with a test that fails on the vulnerable version and passes on the safe one, run Slither without a blinding filter, then audit and run a bug bounty. The SWC Registry hasn't been maintained since 2020.
⚡ Guard every important function
Meaning: The most common and costliest bug: an important function with no guard. Use onlyOwner or a role (onlyRole), then prove with a test that others are refused.
⚡ Reentrancy: called back before it's done
Meaning: A contract calls outside code before it has finished updating its state, and that outside code calls the same function back. In Raka's world the path is _safeMint, which calls the receiver's onERC721Received.
⚡ Checks-Effects-Interactions
Write:
function claim() external nonReentrant {
if (hasClaimed[msg.sender]) revert AlreadyClaimed(); // checks
hasClaimed[msg.sender] = true; // effects first
_safeMint(msg.sender, ++totalClaimed); // interaction last
}
Meaning: Check, update state, only then call out. A callback that comes back finds the new state and is refused. nonReentrant is the second layer.
⚡ Solidity 0.8 doesn't guard every number
Guess first: in Solidity 0.8, what does uint8(300) become?
44, with no error. Explicit casts aren't checked. Use SafeCast.toUint8(300), which reverts.
Meaning: Inside unchecked { } the overflow check is off too: 5 - 10 on a uint8 becomes 251.