DSCEngine advanced testing

A critical exploration of Fuzz and Invariant Testing with Foundry - Analyze the shortcomings of basic unit tests and understand the necessity of fuzz and invariant testing. Learn Foundry's stateless (Fuzz Tests) and stateful (Invariant Tests) approaches to automatically find complex bugs and sequence-dependent vulnerabilities.

Solidity Developer

Advanced Foundry

1. DeFi introduction
A foundational introduction to Introduction to Decentralized Finance (DeFi) - Explore the core principles of Decentralized Finance, contrasting it with TradFi and covering key protocol types like lending, DEXs, and stablecoins. Understand essential concepts like TVL, gas fees, L2s, MEV, and prepare for the course's advanced stablecoin project. Duration: 10min
2. Project code walkthrough
A targeted approach to Improving Fuzz Testing Efficiency with Handlers - Reduce reverted transactions in fuzz tests by implementing Foundry Handler contracts. Learn how Handlers prepare valid call sequences, enabling stricter `fail_on_revert = true` and more effective bug discovery. Duration: 4min
3. Introduction to stablecoins
Gain insights into stablecoins, their types, significance in DeFi, and the roles they play in maintaining economic stability in digital finance. Duration: 29min
4. DecentralizedStableCoin.sol
An essential setup guide to Building the DSCEngine: Core Logic for Your Stablecoin - Begin constructing the `DSCEngine.sol` contract, the engine powering the stablecoin. Learn file structure setup, Natspec documentation best practices, the vital role of overcollateralization, and define the key function signatures including liquidation. Duration: 15min
5. Project setup - DSCEngine
A detailed walkthrough to Implementing the depositCollateral Function - Build the core user interaction function for depositing collateral, incorporating custom errors, modifiers for input validation, and price feed integration for token allowlisting. Securely handle state updates and external ERC20 transfers using ReentrancyGuard and the Checks-Effects-Interactions pattern. Duration: 11min
6. Create the deposit collateral function
A technical breakdown to Implementing the mintDSC Function - Construct the `mintDSC` function, track user debt, and implement the critical Health Factor check for overcollateralization. Develop the necessary helper functions to calculate total collateral USD value using Chainlink Price Feeds, focusing on correct decimal handling. Duration: 19min
7. Quiz 7 Quiz
Questions: 11
8. Creating the mint function
A detailed guide to Implementing Health Factor and Liquidation Logic in DSCEngine - Implement the critical Health Factor calculation in Solidity, handling precision and over-collateralization via a Liquidation Threshold. Build the `_revertIfHealthFactorIsBroken` check using custom errors to safeguard the DSCEngine protocol against under-collateralized positions. Duration: 17min
9. Creating and retrieving the health factor
A detailed explanation to Implementing the DSC Minting Logic in DSCEngine - See how DSCEngine interacts with the DecentralizedStableCoin contract to mint tokens via an onlyOwner function. Implement the external call, ensuring health factor compliance and robust error handling for minting failures. Duration: 7min
10. Finish the mint function
A practical walkthrough to Creating a Foundry Deployment Script - Build a robust Foundry script to deploy DSC and DSCEngine contracts, incorporating a Helper Config pattern for seamless Sepolia/Anvil deployment. Handle mock contracts locally and transfer crucial ownership post-deployment. Duration: 2min
11. Creating the deployment script
A foundational primer to Unit Testing Smart Contracts with Foundry - Grasp the importance of testing while developing, walk through setting up a test environment using `setUp` and deployment scripts, and learn to implement unit tests covering both success cases and expected reverts using Foundry cheatcodes. Duration: 15min
12. Test the DSCEngine smart contract
A focused lesson to Streamlining User Experience: Atomic Collateral Deposit and DSC Minting - Improve user interaction and ensure transaction integrity by combining collateral deposit and DSC minting into a single atomic function. Explore the implementation details, including the critical change from `external` to `public` visibility for internal calls. Duration: 12min
13. Quiz 13 Quiz
Questions: 6
14. Create the depositAndMint function
A practical guide to Implementing Core DSCEngine Functions - Step through the `redeemCollateral`, `burnDsc`, and `redeemCollateralForDsc` functions, focusing on health factor maintenance, secure token interactions, and combining user actions atomically. Duration: 3min
15. Create the redeem collateral function
A practical implementation guide to Understanding the Liquidation Mechanism in the DSC Engine - Learn the core concepts behind stablecoin liquidations, including health factor checks and liquidator incentives crucial for protocol stability. Walk through coding the `liquidate` function, focusing on bonus calculations, price feed usage, and the CEI security pattern. Duration: 12min
16. Setup liquidations
A detailed explanation to Refactoring DSCEngine for Liquidation Functionality - Understand why `msg.sender`-based functions are insufficient for liquidations and refactor `redeemCollateral` and `burnDsc` using internal helpers. Enable liquidators to manage collateral and burn DSC on behalf of undercollateralized users. Duration: 17min
17. Refactor liquidations
A detailed approach to Testing DSCEngine Functionality with Foundry - Utilize Foundry to measure initial test coverage, then write targeted unit tests for the constructor, price conversions, and `depositCollateral`, employing test modifiers and refactoring for testability to achieve comprehensive coverage. Duration: 13min
18. DSCEngine advanced testing
A critical exploration of Fuzz and Invariant Testing with Foundry - Analyze the shortcomings of basic unit tests and understand the necessity of fuzz and invariant testing. Learn Foundry's stateless (Fuzz Tests) and stateful (Invariant Tests) approaches to automatically find complex bugs and sequence-dependent vulnerabilities. Duration: 17min
19. Quiz 25 Quiz
Questions: 8
20. Create the fuzz tests handler pt.1
An in-depth exploration of Invariant Testing in Foundry - Discover how stateful fuzz testing verifies smart contract properties that must always remain true using Foundry's fuzzer. Contrast the basic, often inefficient Open Testing approach with the more precise and powerful Handler-Based strategy for effective bug discovery. Duration: 14min
21. Create the fuzz tests handler pt.2
A high-level overview to Introduction to the Decentralized Stablecoin Codebase - Explore the DSC architecture, focusing on the `DecentralizedStableCoin` token and `DSCEngine` logic contracts. Understand key mechanisms like collateralization, liquidation, price feeds, and the project's Foundry testing strategy. Duration: 20min
22. Defi Handler Deposit Collateral
A practical guide to Expanding Fuzz Tests: Handling Collateral Redemption - Learn how to extend Foundry invariant tests by adding a new `redeemCollateral` handler function. Understand state-aware input bounding using `bound`, handling zero-amount edge cases, and the impact of `fail_on_revert` on debugging. Duration: 18min
23. Create the collateral redeem handler
A focused lesson on Extending Invariant Tests: Adding a Mint Function Handler - Improve invariant test coverage by adding a `mintDsc` function handler in Foundry. Understand how to implement both loose and strict input narrowing strategies based on `fail_on_revert`. Duration: 6min
24. Create the mint handler
A practical guide to Diagnosing Passing Foundry Fuzz Tests - Learn to debug invariant tests that pass despite suspicious logs, focusing on verifying handler execution using ghost variables. Refine handler logic to account for fuzzer randomness and ensure realistic state simulation. Duration: 6min
25. Debugging the fuzz tests handler
An essential guide to Handling Price Feeds in Foundry Invariant Tests - Learn how to use Foundry's Handler contract to simulate external price feed interactions in invariant tests. Discover how testing with mock oracles reveals critical risks associated with price volatility. Duration: 9min
26. Quiz 25 Quiz
Questions: 9
27. Create the price feed handler
An essential guide to OracleLib for Stale Price Checks - Explore the critical risks of using stale oracle data in DeFi protocols and understand how `OracleLib` mitigates them. Learn to implement this Solidity library to wrap Chainlink calls, enforce freshness via timeouts, and halt operations safely when prices are outdated. Duration: 8min
28. Manage your oracles connections
A foundational guide to Note on Smart Contract Audit Preparedness - Emphasize the vital importance of preparing for smart contract audits before any mainnet launch. Review key best practices and resources like the Nascent checklist as a prelude to deeper security dives. Duration: 9min
29. Preparing your protocol for an audit
An advanced walkthrough to Building and Testing a DeFi Stablecoin - Synthesize core DeFi concepts to build a complex, algorithmic, collateralized stablecoin using Foundry. Utilize advanced testing techniques like fuzz and invariant testing to ensure the protocol's economic stability and robustness. Duration: 2min
30. Section recap
A comprehensive overview to Lens Protocol: Building the Decentralized Social Layer for Web3 - Learn about Lens Protocol, the decentralized and composable social infrastructure for Web3. Understand its core NFT-based primitives, powerful extensibility through custom modules, and how developers can build upon its social graph. Duration: 4min
31. Bonus: introduction to Lens Protocol
A foundational walkthrough to Setting Up the Decentralized Stablecoin Project with Foundry - Initialize a new Foundry project, outline core design principles for a decentralized stablecoin (DSC), and configure OpenZeppelin dependencies. Implement the basic `DecentralizedStableCoin` ERC20 token contract with `Ownable` access control for minting and burning. Duration: 3min
32. Quiz 32 Quiz
Questions: 10

Course Overview

About the course

What you'll learn

Advanced smart contract development

How to develop a stablecoin

How to develop a DeFi protocol

How to develop a DAO

Advanced smart contracts testing

Fuzz testing

Manual verification

Course Description

Who is this course for?

  • Engineers
  • Smart Contract Security researchers

Potential Careers

Web3 Developer Relations

$85,000 - $125,000 (avg. salary)

Web3 developer

$60,000 - $150,000 (avg. salary)

Smart Contract Engineer

$100,000 - $150,000 (avg. salary)

Smart Contract Auditor

$100,000 - $200,000 (avg. salary)

Security researcher

$49,999 - $120,000 (avg. salary)

Meet your instructors

Patrick Collins

Patrick Collins

Founder at Cyfrin

Web3 engineer, educator, and Cyfrin co-founder. Patrick's smart contract development and security courses have helped hundreds of thousands of engineers kickstarting their careers into web3.

Guest lecturers:

Juliette Chevalier

Juliette Chevalier

Lead Developer relations at Aragon

Ciara Nightingale

Ciara Nightingale

Developer relations at Cyfrin

Vasiliy Gualoto

Vasiliy Gualoto

Developer relations at ThirdWeb

Nader Dabit

Nader Dabit

Director of developer relations at EigenLayer

Ally Haire

Ally Haire

Developer relations at Protocol Labs

Harrison

Harrison

Founder at GasliteGG

Vitto Rivabella

Vitto Rivabella

CPO at Cyfrin

Last updated on May 12, 2025