Blockchain and Web3 course Β· Module 10: DeFi & Staking
DeFi - Decentralized Finance
In this lesson5
Welcome to the Underground Market! Atlas here. Today you'll learn about DeFi - decentralized finance, meaning exchanges and financial services operating without intermediaries.
What is DeFi?
DeFi (Decentralized Finance) is an ecosystem of financial applications built on blockchain. Instead of banks and exchanges - smart contracts!
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TRADITIONAL FINANCE vs DeFi β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β TRADITIONAL (CeFi) β DECENTRALIZED (DeFi) β
β βββββββββββββββββ β βββββββββββββββββββββ β
β Bank β Smart Contract β
β Business hours β 24/7/365 β
β KYC required β Permissionless β
β Controlled by institution β Controlled by user β
β Requires trust β Trustless (code is law) β
β Slow processing β Fast transactions β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββMain DeFi Categories
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β DeFi ECOSYSTEM β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β DEX (Decentralized Exchange) β
β βββ Uniswap, SushiSwap, Curve β
β β
β Lending/Borrowing β
β βββ Aave, Compound, MakerDAO β
β β
β Stablecoins β
β βββ DAI, USDC, USDT β
β β
β Yield Farming β
β βββ Yearn, Convex β
β β
β Derivatives β
β βββ dYdX, GMX β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββAMM - Automated Market Maker
Traditional exchanges use an order book. DEXes use AMM:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β AMM (Uniswap v2) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Liquidity Pool: ETH/USDC β
β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β ETH: 100 β USDC: 200,000 β β
β β β β β
β β x * y = k (constant product formula) β β
β β 100 * 200,000 = 20,000,000 β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β Price: 200,000 / 100 = 2,000 USDC per ETH β
β β
β Swap: You want to buy 1 ETH β
β New state: 99 ETH, ~202,020 USDC β
β You pay: ~2,020 USDC (slippage!) β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββSwap on Uniswap
import { ethers } from "ethers";
// Uniswap V2 Router
const ROUTER_ABI = [
"function swapExactETHForTokens(uint amountOutMin, address[] path, address to, uint deadline) payable returns (uint[] amounts)",
"function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] path, address to, uint deadline) returns (uint[] amounts)",
"function getAmountsOut(uint amountIn, address[] path) view returns (uint[] amounts)"
];
const router = new ethers.Contract(UNISWAP_ROUTER, ROUTER_ABI, wallet);
// Check price
const amountsOut = await router.getAmountsOut(
ethers.parseEther("1"), // 1 ETH
[WETH_ADDRESS, USDC_ADDRESS]
);
console.log("1 ETH =", ethers.formatUnits(amountsOut[1], 6), "USDC");
// Swap ETH β Token
const tx = await router.swapExactETHForTokens(
amountsOut[1] * 95n / 100n, // min 95% (5% slippage)
[WETH_ADDRESS, USDC_ADDRESS],
myAddress,
Math.floor(Date.now() / 1000) + 60 * 20, // deadline 20 min
{ value: ethers.parseEther("1") }
);
await tx.wait();Summary
- DeFi - finance without intermediaries
- DEX - decentralized exchanges
- AMM - Automated Market Maker
- Liquidity Pools
- Swap on Uniswap
- Slippage and protection
Code for this lesson: index.js
// DeFi Fundamentals - basic concepts
console.log("=== DEFI FUNDAMENTALS ===\n");
const defiConcepts = {
"DEX (Decentralized Exchange)": {
description: "Token exchange without intermediaries",
examples: ["Uniswap", "SushiSwap", "Curve", "Raydium (Solana)"],
mechanism: "AMM (Automated Market Maker)"
},
"Lending/Borrowing": {
description: "Lending and earning on deposits",
examples: ["Aave", "Compound", "MakerDAO"],
mechanism: "Overcollateralized loans"
},
"Yield Farming": {
description: "Optimizing returns from different protocols",
examples: ["Yearn Finance", "Convex", "Beefy"],
mechanism: "Auto-compounding, strategy vaults"
},
"Liquid Staking": {
description: "Staking while maintaining liquidity",
examples: ["Lido (stETH)", "Rocket Pool", "Marinade (Solana)"],
mechanism: "Liquid Staking Derivatives (LSDs)"
},
"Stablecoins": {
description: "Tokens pegged to USD",
examples: ["USDC (fiat-backed)", "DAI (crypto-backed)", "FRAX (algorithmic)"],
mechanism: "Different stabilization mechanisms"
}
};
Object.entries(defiConcepts).forEach(([name, data]) => {
console.log(`${name}`);
console.log(` ${data.description}`);
console.log(` Mechanism: ${data.mechanism}`);
console.log(` Examples: ${data.examples.join(", ")}`);
console.log();
});
console.log("=== KEY METRICS ===\n");
const metrics = {
"TVL (Total Value Locked)": "Total assets in the protocol",
"APY (Annual Percentage Yield)": "Annual return with compounding",
"APR (Annual Percentage Rate)": "Annual return without compounding",
"Impermanent Loss": "Loss from providing liquidity vs HODL",
"Utilization Rate": "% of borrowed funds from the pool"
};
Object.entries(metrics).forEach(([metric, desc]) => {
console.log(` ${metric}: ${desc}`);
});
console.log("\n=== TOP DEFI PROTOCOLS BY TVL ===\n");
const protocols = [
{ name: "Lido", tvl: "$28B", category: "Liquid Staking" },
{ name: "Aave", tvl: "$12B", category: "Lending" },
{ name: "MakerDAO", tvl: "$8B", category: "CDP/Stablecoin" },
{ name: "Uniswap", tvl: "$5B", category: "DEX" },
{ name: "Curve", tvl: "$4B", category: "DEX (Stables)" }
];
protocols.forEach((p, i) => {
console.log(`${i+1}. ${p.name} - ${p.tvl} (${p.category})`);
});
console.log("\nSource: DeFiLlama.com");
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. DeFi (Decentralized Finance) is:
2. DEX (Decentralized Exchange) is:
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 swap code:
- Code editor
Complete the addLiquidity code:
- Code editor
Complete the removeLiquidity code:
- Code editor
Complete the getPrice function:
- Vertical ordering
Arrange the steps of a swap on Uniswap:
- Vertical ordering
Arrange the steps for adding liquidity:
- Horizontal ordering
Arrange the parameters for calling swapExactETHForTokens:
- Horizontal ordering
Arrange the parameters of addLiquidity:
- Click in order
Click in the order of the steps for creating an LP position:
- Click in order
Click in the order of executing the swap:
- Code editor
Complete the executeOperation callback:
- Code editor
Complete the deposit code:
- Code editor
Complete the borrow code:
- Code editor
Complete the repay code:
- Vertical ordering
Arrange the flash loan steps (all in 1 transaction):
- Vertical ordering
Arrange the lending steps (borrowing with collateral):
- Horizontal ordering
Arrange the parameters of flashLoan (Aave):
- Horizontal ordering
Arrange the parameters of deposit (Aave):
- Click in order
Click in the order of the borrowing steps:
- Click in order
Click in the order of checking for liquidation:
- Code editor
Complete the getLatestPrice code:
- Code editor
Complete the calculateRewards function:
- Vertical ordering
Arrange the yield farming steps:
- Horizontal ordering
Arrange the steps for staking LP tokens:
- Click in order
Click in the order of calculating TVL (Total Value Locked):
Tasks after this lesson
- QuestionQuiz: DeFi
- QuestionQuiz: DEX
- QuestionQuiz: AMM
- QuestionQuiz: Liquidity Pool
- Coding taskSwap ETH for USDC
- Coding taskAdding Liquidity
- Coding taskRemoving Liquidity
- Coding taskCalculating Price
- QuestionQuiz: Uniswap
- QuestionQuiz: Slippage
- QuestionQuiz: x * y = k
- QuestionQuiz: LP Tokens
- Put in orderSorting: Swap on Uniswap
- Put in orderSorting: Adding Liquidity
- Put in orderSyntax: swapExactETHForTokens
- Put in orderSyntax: addLiquidity
- Click in orderBuilding: LP Position
- Click in orderBuilding: Swap Flow
- QuestionQuiz: Impermanent Loss
- QuestionQuiz: Flash Loans
- QuestionQuiz: Collateralization
- QuestionQuiz: Oracles
- Coding taskFlash Loan Implementation
- Coding taskLending: Deposit
- Coding taskBorrowing
- Coding taskRepay Loan
- Put in orderSorting: Flash Loan Flow
- Put in orderSorting: Lending Flow
- Put in orderSyntax: flashLoan
- Put in orderSyntax: deposit (lending)
- Click in orderBuilding: Borrow Flow
- Click in orderBuilding: Liquidation Check
- QuestionQuiz: Liquidation
- QuestionQuiz: Concentrated Liquidity
- QuestionQuiz: MEV
- QuestionQuiz: Sandwich Attack
- Coding taskChainlink Price Feed
- Coding taskStaking Rewards
- Put in orderSorting: Yield Farming
- Put in orderSyntax: stake LP
- Click in orderBuilding: TVL Check
- QuestionQuiz: TVL
- Project to submitSend Your Project to the Mentor
- ConversationEnd of Module 10