Blockchain and Web3 course Β· Module 12: Security & Audit

Smart Contract Security

3 min read Β·
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. 1. A reentrancy attack involves:

  2. 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):

  1. QuestionQuiz: Reentrancy
  2. QuestionQuiz: Front-running
  3. QuestionQuiz: Oracle Manipulation
  4. QuestionQuiz: Signature Replay
  5. Coding taskPractice: Test in Hardhat
  6. Coding taskPractice: onlyOwner Modifier
  7. Coding taskPractice: ReentrancyGuard
  8. Coding taskPractice: Safe Math
  9. Coding taskPractice: Access Control Roles
  10. Put in orderSorting: Audit Flow
  11. Put in orderSorting: Incident Response
  12. Put in orderSorting: Testing Pipeline
  13. QuestionQuiz: Checks-Effects-Interactions
  14. QuestionQuiz: delegatecall
  15. QuestionQuiz: selfdestruct
  16. Coding taskPractice: Pausable Pattern
  17. Coding taskPractice: Pull over Push
  18. Coding taskPractice: Checks-Effects-Interactions
  19. Coding taskPractice: Safe Transfer
  20. Coding taskPractice: Event Logging for Security
  21. Put in orderHorizontal Sorting: require Statement
  22. Put in orderHorizontal Sorting: Modifier Pattern
  23. Put in orderHorizontal Sorting: SafeERC20 Usage
  24. Click in orderClicking: Security Checklist
  25. Click in orderClicking: Test Structure
  26. Click in orderClicking: Emergency Response Priority
  27. QuestionQuiz: nonReentrant
  28. QuestionQuiz: Hardhat vs Foundry
  29. QuestionQuiz: Slither
  30. Put in orderSorting: Vulnerability Disclosure
  31. Put in orderSorting: Smart Contract Upgrade
  32. Put in orderSorting: Pre-Deploy Checklist
  33. Put in orderHorizontal Sorting: ReentrancyGuard
  34. Put in orderHorizontal Sorting: Access Control Modifier
  35. Click in orderClicking: Pre-Deploy Checklist Items
  36. Click in orderClicking: Code Review Priorities
  37. QuestionQuiz: Access Control
  38. QuestionQuiz: Integer Overflow
  39. QuestionQuiz: OpenZeppelin
  40. QuestionQuiz: private visibility
  41. QuestionQuiz: Audit
  42. QuestionQuiz: Bug Bounty
  43. QuestionQuiz: Pausable
  44. Project to submitSend Your Project to the Mentor
  45. ConversationEnd of the Web3 Course