Open this lesson in your favourite AI. It'll walk you through the why, explain the demo, and quiz you on the try-it list.
DeFi is finance rebuilt as on-chain smart contracts: anyone can deposit, anyone can borrow, anyone can compose. The trade-offs are radical — programmatic transparency in exchange for code-level finality. Understanding the model from first principles is the foundation for everything you'll build.
DeFi vs TradFi: same primitives, very different mechanics.
Use these three in order. Each builds on the one before.
In one paragraph, explain DeFi and how it differs from TradFi.
Walk me through how MiniVault tracks pro-rata ownership across many depositors.
Given a malicious actor who first-deposits 1 wei and immediately donates 1000 USDC to inflate the share price, design the protection mechanism (hint: ERC-4626 includes one).
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
// A minimum-viable DeFi vault.
// Anyone deposits USDC, gets shares representing pro-rata ownership.
// No authority can take user funds — only deposit/withdraw logic governs.
contract MiniVault is ERC20 {
using SafeERC20 for IERC20;
IERC20 public immutable asset;
constructor(IERC20 _asset) ERC20("MiniVault Share", "mvUSDC") {
asset = _asset;
}
function deposit(uint256 amount, address receiver) external returns (uint256 shares) {
uint256 totalAssets = asset.balanceOf(address(this));
uint256 totalShares = totalSupply();
shares = totalShares == 0
? amount
: (amount * totalShares) / totalAssets;
asset.safeTransferFrom(msg.sender, address(this), amount);
_mint(receiver, shares);
}
function withdraw(uint256 shares, address receiver) external returns (uint256 amount) {
uint256 totalAssets = asset.balanceOf(address(this));
amount = (shares * totalAssets) / totalSupply();
_burn(msg.sender, shares);
asset.safeTransfer(receiver, amount);
}
}
// Key DeFi properties illustrated:
// - Custody: contract holds funds, not a person or company
// - Pro-rata: shares track ownership precisely
// - Permissionless: no whitelist; anyone can deposit/withdraw
// - Composable: another contract can deposit on a user's behalf