Blockchain and Web3 course Β· Module 12: Security & Audit
Smart Contract Security
In this lesson6
Welcome to the Watchtower! Atlas here. The final module - and the most important! Security in Web3 is critical, because mistakes can cost millions.
Why is Security So Important?
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β BIGGEST WEB3 HACKS β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β 2016: The DAO Hack - $60M (reentrancy) β
β 2021: Poly Network - $610M (access control) β
β 2022: Ronin Bridge - $625M (private key compromise) β
β 2022: Wormhole - $320M (signature validation) β
β 2023: Euler Finance - $197M (flash loan attack) β
β β
β Smart contracts are IMMUTABLE β
β Bug = permanent loss β
β "Code is law" β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββMost Common Vulnerabilities
1. Reentrancy Attack
// VULNERABLE CODE
contract Vulnerable {
mapping(address => uint256) public balances;
function withdraw() public {
uint256 amount = balances[msg.sender];
(bool success, ) = msg.sender.call{value: amount}("");
require(success);
balances[msg.sender] = 0; // Update AFTER sending!
}
}
// SAFE CODE (Checks-Effects-Interactions)
contract Safe {
mapping(address => uint256) public balances;
function withdraw() public {
uint256 amount = balances[msg.sender];
balances[msg.sender] = 0; // Update BEFORE sending
(bool success, ) = msg.sender.call{value: amount}("");
require(success);
}
}2. Integer Overflow/Underflow
// In Solidity < 0.8.0 without SafeMath:
uint8 x = 255;
x = x + 1; // x = 0 (overflow!)
// In Solidity >= 0.8.0 automatic protection:
uint8 x = 255;
x = x + 1; // Revert!3. Access Control
// NO ACCESS CONTROL
function mint(address to, uint256 amount) public {
_mint(to, amount); // Anyone can mint!
}
// WITH ACCESS CONTROL
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
// Or with OpenZeppelin AccessControl
function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) {
_mint(to, amount);
}OpenZeppelin - Safe Patterns
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
contract SafeContract is Ownable, ReentrancyGuard, Pausable {
function withdraw() public nonReentrant whenNotPaused {
// Safe function
}
function pause() public onlyOwner {
_pause();
}
}Testing Contracts
// Hardhat + Chai
import { expect } from "chai";
import { network } from "hardhat";
const { ethers } = await network.create();
describe("MyToken", function () {
it("Should transfer tokens correctly", async function () {
const [owner, addr1] = await ethers.getSigners();
const Token = await ethers.getContractFactory("MyToken");
const token = await Token.deploy(1000);
await token.transfer(addr1.address, 100);
expect(await token.balanceOf(addr1.address)).to.equal(100);
expect(await token.balanceOf(owner.address)).to.equal(900);
});
it("Should fail if sender doesn't have enough tokens", async function () {
const [owner, addr1] = await ethers.getSigners();
// ...
await expect(
token.connect(addr1).transfer(owner.address, 1)
).to.be.revertedWith("Not enough tokens");
});
});Pre-Deploy Checklist
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SECURITY CHECKLIST β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β [ ] Reentrancy protection (nonReentrant modifier) β
β [ ] Access control (onlyOwner, roles) β
β [ ] Input validation β
β [ ] Integer overflow protection (Solidity 0.8+) β
β [ ] External call safety (check return values) β
β [ ] Proper visibility (public/private/internal) β
β [ ] Events for important state changes β
β [ ] Pausability for emergencies β
β [ ] Comprehensive tests (unit, integration) β
β [ ] Professional audit (for large projects) β
β [ ] Bug bounty program β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββComplete Course Summary
Congratulations! You've completed the journey through the Crypt!
You've learned:
- Blockchain fundamentals
- Cryptography and keys
- Ethereum and EVM
- Ethers.js
- Wallets and transactions
- Solidity and smart contracts
- ERC-20 and ERC-721
- DeFi basics
- Building dApps
- Web3 security
Now you can build your own Web3 projects!
Code for this lesson: index.js
// Common Smart Contract Vulnerabilities
console.log("=== SMART CONTRACT VULNERABILITIES ===\n");
const vulnerabilities = {
"Reentrancy": {
severity: "Critical",
description: "Attacker calls back into contract before state is updated",
example: "The DAO hack - $60M stolen",
prevention: "Use CEI pattern (Checks-Effects-Interactions), ReentrancyGuard"
},
"Integer Overflow/Underflow": {
severity: "High",
description: "Arithmetic operations wrap around",
example: "uint8(255) + 1 = 0",
prevention: "Solidity 0.8+ has built-in checks, SafeMath for older versions"
},
"Access Control": {
severity: "Critical",
description: "Missing or incorrect permission checks",
example: "Anyone can call admin functions",
prevention: "Use Ownable, AccessControl from OpenZeppelin"
},
"Front-running": {
severity: "Medium",
description: "Attacker sees pending tx and submits own tx first",
example: "Sandwich attacks on DEX swaps",
prevention: "Commit-reveal, private mempools (Flashbots)"
},
"Oracle Manipulation": {
severity: "High",
description: "Manipulating price feeds to exploit protocols",
example: "Flash loan + manipulate Uniswap price",
prevention: "TWAP oracles, Chainlink, multiple sources"
},
"Unchecked External Calls": {
severity: "High",
description: "Not checking return values of external calls",
example: "ERC20 transfer returns false but ignored",
prevention: "Always check return values, use SafeERC20"
},
"Denial of Service": {
severity: "Medium",
description: "Making contract unusable",
example: "Unbounded loops, block gas limit",
prevention: "Limit iterations, pagination, pull over push"
},
"Signature Replay": {
severity: "High",
description: "Reusing valid signatures",
example: "Using same permit signature twice",
prevention: "Include nonce, deadline, chainId"
}
};
Object.entries(vulnerabilities).forEach(([name, data]) => {
console.log(`${name} [${data.severity}]`);
console.log(` ${data.description}`);
console.log(` Example: ${data.example}`);
console.log(` Prevention: ${data.prevention}\n`);
});
console.log("Resources:");
console.log(" - SWC Registry (swcregistry.io)");
console.log(" - Rekt News (rekt.news) - hack post-mortems");
console.log(" - Consensys Best Practices");
console.log(" - Trail of Bits guides");
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. A reentrancy attack involves:
2. Front-running in blockchain exploits:
These are 2 of 17 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Complete the test checking access control
- Code editor
Write a modifier checking whether msg.sender == owner
- Code editor
Add the nonReentrant modifier to the function
- Code editor
Fix the code using safe math operations
- Code editor
Implement a role system in the contract
- Vertical ordering
Arrange the professional security audit process:
- Vertical ordering
Arrange the response steps for a smart contract attack:
- Vertical ordering
Arrange the smart contract testing pyramid (from most frequent to least frequent):
- Code editor
Add the ability to stop the contract in an emergency
- Code editor
Rewrite the code from push payments to pull payments
- Code editor
Organize the code according to: checks β effects β interactions
- Code editor
Rewrite the code using safeTransfer/safeTransferFrom
- Code editor
Add security events for monitoring the contract
- Horizontal ordering
What does the correct require syntax look like?
- Horizontal ordering
Arrange the syntax of the onlyOwner modifier:
- Horizontal ordering
How do you use SafeERC20 for a safe transfer?
- Click in order
Click the elements in the order of building a require with an error message:
- Click in order
Click the elements building a test structure in Hardhat/Foundry:
- Click in order
Click the elements building the pause function declaration with modifiers:
- Vertical ordering
Responsible disclosure - arrange the process for reporting a discovered vulnerability:
- Vertical ordering
Arrange the process of upgrading a contract through a proxy:
- Vertical ordering
Arrange the checklist before deploying to mainnet:
- Horizontal ordering
How do you use the nonReentrant modifier?
- Horizontal ordering
Arrange the function with access control:
- Click in order
Click the security checklist items in order (test β mark β testnet β mark β audit β mark):
- Click in order
Click the priorities during a code review in order (access control β reentrancy β math):
Tasks after this lesson
- QuestionQuiz: Reentrancy
- QuestionQuiz: Front-running
- QuestionQuiz: Oracle Manipulation
- QuestionQuiz: Signature Replay
- Coding taskPractice: Test in Hardhat
- Coding taskPractice: onlyOwner Modifier
- Coding taskPractice: ReentrancyGuard
- Coding taskPractice: Safe Math
- Coding taskPractice: Access Control Roles
- Put in orderSorting: Audit Flow
- Put in orderSorting: Incident Response
- Put in orderSorting: Testing Pipeline
- QuestionQuiz: Checks-Effects-Interactions
- QuestionQuiz: delegatecall
- QuestionQuiz: selfdestruct
- Coding taskPractice: Pausable Pattern
- Coding taskPractice: Pull over Push
- Coding taskPractice: Checks-Effects-Interactions
- Coding taskPractice: Safe Transfer
- Coding taskPractice: Event Logging for Security
- Put in orderHorizontal Sorting: require Statement
- Put in orderHorizontal Sorting: Modifier Pattern
- Put in orderHorizontal Sorting: SafeERC20 Usage
- Click in orderClicking: Security Checklist
- Click in orderClicking: Test Structure
- Click in orderClicking: Emergency Response Priority
- QuestionQuiz: nonReentrant
- QuestionQuiz: Hardhat vs Foundry
- QuestionQuiz: Slither
- Put in orderSorting: Vulnerability Disclosure
- Put in orderSorting: Smart Contract Upgrade
- Put in orderSorting: Pre-Deploy Checklist
- Put in orderHorizontal Sorting: ReentrancyGuard
- Put in orderHorizontal Sorting: Access Control Modifier
- Click in orderClicking: Pre-Deploy Checklist Items
- Click in orderClicking: Code Review Priorities
- QuestionQuiz: Access Control
- QuestionQuiz: Integer Overflow
- QuestionQuiz: OpenZeppelin
- QuestionQuiz: private visibility
- QuestionQuiz: Audit
- QuestionQuiz: Bug Bounty
- QuestionQuiz: Pausable
- Project to submitSend Your Project to the Mentor
- ConversationEnd of the Web3 Course