A decentralized, overcollateralized stablecoin system with algorithmic stability, oracle-based pricing, and automated liquidations.
- Address:
0xd12b6e24De84c67Fa34C2BdeE264fdb66cc9Ae45 - Etherscan: https://sepolia.etherscan.io/address/0xd12b6e24De84c67Fa34C2BdeE264fdb66cc9Ae45
- Address:
0x76c339DD1BDaeEeb1380C38B66a88b7Fb17921fD - Etherscan: https://sepolia.etherscan.io/address/0x76c339DD1BDaeEeb1380C38B66a88b7Fb17921fD
- WETH:
0x7b79995e5f793a07Bc00c21412e50Ecae098E7f9(Sepolia) - WBTC:
0x92f3B59a79bFf5dc60c0d59eA13a44D082B2bdFC(Sepolia)
This protocol implements a USD-pegged stablecoin (DSC) backed by cryptocurrency collateral (WETH & WBTC). Users can deposit collateral to mint stablecoins while maintaining a healthy collateralization ratio. The system features automated liquidation mechanisms to ensure protocol solvency.
- Overcollateralized: Minimum 200% collateralization ratio (50% LTV)
- Multi-Collateral: Supports WETH and WBTC as collateral assets
- Oracle-Powered: Chainlink price feeds for real-time asset pricing
- Liquidation System: Incentivized liquidations to maintain protocol health
- Algorithmic Stability: No governance, fully algorithmic peg maintenance
┌─────────────────────────────────────────────────┐
│ │
│ User deposits WETH/WBTC → Mints DSC │
│ Maintains health factor > 1.0 │
│ Can redeem collateral or burn DSC │
│ │
└─────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────┐
│ DSCEngine (Core Logic) │
│ • Collateral management │
│ • DSC minting/burning │
│ • Health factor calculations │
│ • Liquidation logic │
└─────────────────────────────────────────────────┘
│ │
▼ ▼
┌──────────────────┐ ┌──────────────────────┐
│ OracleLib │ │ DecentralizedStable │
│ (Price Feeds) │ │ Coin (ERC20) │
│ • Stale checks │ │ • Mint/Burn │
│ • USD conversion│ │ • Access control │
└──────────────────┘ └──────────────────────┘
The core protocol logic handling:
- Collateral deposits and withdrawals
- DSC minting and burning
- Health factor calculations
- Liquidation mechanics
- Position management
ERC20 implementation of the stablecoin with:
- Mintable/burnable by DSCEngine only
- Standard ERC20 functionality
- Access control for minting/burning
Library for Chainlink oracle interactions:
- Stale price detection (3-hour timeout)
- USD value conversions
- Price feed validation
git clone https://github.com/yourusername/foundry-defi-stablecoin
cd foundry-defi-stablecoin
forge installforge build# Run all tests
forge test
# Run with verbosity
forge test -vvv
# Run specific test file
forge test --match-path test/DSCEngineTest.t.sol
# Run coverage report
forge coverageThis project implements a comprehensive testing approach:
- 86.15% line coverage
- 88.44% statement coverage
- 23 unit tests covering all core functionality
- Handler-based invariant testing with 16,384+ fuzz calls
Comprehensive tests covering:
- Collateral deposits and redemptions
- DSC minting and burning
- Health factor calculations
- Liquidation scenarios
- Edge cases and failure modes
Critical protocol properties verified:
- Protocol Overcollateralization:
totalCollateralValue >= totalDebtValue - Getter Functions: All view functions never revert
- Handler-guided fuzzing: Realistic state transitions only
Guides the fuzzer through valid protocol interactions:
- Deposits only approved collateral
- Mints DSC respecting health factors
- Redeems collateral within safe limits
- Tracks ghost variables for invariant verification
// 1. Approve collateral token
IERC20(weth).approve(address(dscEngine), amount);
// 2. Deposit and mint in one transaction
dscEngine.depositCollateralAndMintDsc(
wethAddress,
collateralAmount,
dscToMint
);Health factor determines if a position is safe from liquidation:
healthFactor = (collateralValue * LIQUIDATION_THRESHOLD) / totalDscMinted
- Health factor > 1.0: Position is safe
- Health factor < 1.0: Position can be liquidated
- Minimum collateralization: 200% (50% LTV)
Anyone can liquidate undercollateralized positions:
dscEngine.liquidate(
collateralAddress,
userToLiquidate,
debtToCover
);Liquidators receive:
- The debt amount in collateral
- 10% liquidation bonus
- Helps maintain protocol solvency
# Start local Anvil chain
anvil
# Deploy (in new terminal)
forge script script/DeployDSC.s.sol --rpc-url http://localhost:8545 --broadcastforge script script/DeployDSC.s.sol \
--rpc-url $SEPOLIA_RPC_URL \
--private-key $PRIVATE_KEY \
--broadcast \
--verify \
--etherscan-api-key $ETHERSCAN_API_KEY- ✅ Reentrancy guards on state-changing functions
- ✅ Oracle staleness checks (3-hour timeout)
- ✅ Health factor enforcement before all operations
- ✅ Collateral validation (only approved assets)
- ✅ Zero-amount checks
- ✅ Overcollateralization requirements
- Oracle dependency (relies on Chainlink price feeds)
- Liquidation relies on external actors (MEV risk)
- No governance mechanism (fully algorithmic)
- Limited to two collateral types (WETH, WBTC)
- Solidity ^0.8.19: Smart contract language
- Foundry: Development framework and testing
- Chainlink: Decentralized oracle network
- OpenZeppelin: Battle-tested contract libraries
- Efficient storage patterns
- Minimal external calls
- Batch operations where possible
- View functions for off-chain calculations
foundry-defi-stablecoin/
├── src/
│ ├── DSCEngine.sol # Core protocol logic
│ ├── DecentralizedStableCoin.sol # ERC20 stablecoin
│ └── libraries/
│ └── OracleLib.sol # Oracle helper library
├── script/
│ ├── DeployDSC.s.sol # Deployment script
│ └── HelperConfig.s.sol # Network configurations
├── test/
│ ├── DSCEngineTest.t.sol # Unit tests
│ ├── fuzz/
│ │ ├── Handler.t.sol # Fuzz handler
│ │ ├── Invariants.t.sol # Invariant tests
│ │ └── OpenInvariantsTest.t.sol
│ └── mocks/ # Mock contracts for testing
└── foundry.toml # Foundry configuration
This project was built as part of learning DeFi protocol development. Key concepts implemented:
- Overcollateralized stablecoin mechanics
- Oracle integration and staleness checks
- Liquidation systems and incentives
- Handler-based invariant testing
- Foundry testing frameworks
MIT License - see LICENSE file for details
- Patrick Collins - Cyfrin Updraft course
- Foundry Book
- MakerDAO - Inspiration for stablecoin mechanics
- Encode Club - Bootcamp education
- GitHub: @usetech-nick
- Twitter: @Nishant18335767
- LinkedIn: Nishant Kumar