Exercises: Lending, Borrowing, and Yield
Conceptual Exercises
Exercise 1: The Logic of Overcollateralization
A friend who works in traditional banking says: "DeFi lending is absurd. You deposit $150,000 to borrow $100,000. Why not just spend the $100,000 you already have?"
Write a 300-word response explaining three distinct reasons why a crypto holder might prefer to borrow against their assets rather than sell them. For each reason, identify the assumption about the borrower's situation that makes the strategy rational.
Hint: Think about tax events, directional exposure, and composability.
Exercise 2: Interest Rate Curve Design
You are designing the interest rate model for a new lending pool that accepts a volatile, mid-cap token as a borrowable asset. The token has a market cap of $500 million and daily trading volume of $20 million.
(a) Would you set the optimal utilization higher or lower than for a stablecoin pool? Explain your reasoning in terms of liquidity risk.
(b) Would you set Slope2 (the penalty slope above optimal utilization) higher or lower than for a stablecoin pool? Explain what happens if Slope2 is too low for a volatile asset.
(c) What base rate would you choose, and why? Consider the opportunity cost of capital for lenders.
(d) Sketch (by hand or using the Python code) an interest rate curve with your chosen parameters. Label the optimal utilization point and the kink.
Exercise 3: Flash Loan Feasibility Analysis
For each of the following scenarios, explain whether a flash loan could be used to execute the strategy. If yes, outline the steps within the atomic transaction. If no, explain what property of the scenario makes a flash loan insufficient.
(a) Arbitraging a 0.5% price difference on ETH between Uniswap and SushiSwap.
(b) Purchasing a house with a flash loan, since the transaction is repaid within the same block.
(c) Swapping collateral on Aave from WBTC to ETH without closing the position.
(d) Voting on a governance proposal using borrowed governance tokens, then returning them.
(e) Earning yield on a 30-day staking program using flash-borrowed tokens.
Exercise 4: Liquidation Cascade Analysis
Consider a simplified DeFi ecosystem with three borrowers:
| Borrower | Collateral | Collateral Value | Debt | Health Factor |
|---|---|---|---|---|
| Alice | 100 ETH | $250,000 | $200,000 USDC | 1.03 | |
| Bob | 50 ETH | $125,000 | $95,000 USDC | 1.09 | |
| Carol | 200 ETH | $500,000 | $350,000 USDC | 1.18 |
Assume a liquidation threshold of 82.5% and a liquidation penalty of 5%.
(a) ETH drops 5% (from $2,500 to $2,375). Which borrowers are liquidated? Calculate the new health factors.
(b) For each liquidated borrower, calculate how much collateral the liquidator seizes (assuming the liquidator repays 50% of the debt).
(c) The liquidator immediately sells the seized ETH on the open market. Calculate the additional selling pressure in ETH terms. If this selling pressure causes ETH to drop an additional 2%, recalculate health factors for the remaining borrowers.
(d) Explain how this cascade dynamic differs from a bank run in traditional finance.
Exercise 5: Real Yield vs. Inflationary Yield
You are evaluating three DeFi lending protocols for a $100,000 deposit:
Protocol Alpha: - Advertised APY: 12% - Annual protocol revenue: $30M - Annual token emissions to users: $200M - TVL: $2B
Protocol Beta: - Advertised APY: 4% - Annual protocol revenue: $80M - Annual token emissions to users: $5M - TVL: $15B
Protocol Gamma: - Advertised APY: 25% - Annual protocol revenue: $1M - Annual token emissions to users: $50M - TVL: $200M
(a) Calculate the real yield for each protocol.
(b) Rank the protocols by sustainability of their yield. Justify your ranking.
(c) Protocol Gamma's token has dropped 85% in the past 6 months. Explain the likely mechanism behind this decline using the concept of inflationary yield.
(d) A friend says: "Protocol Gamma has a 25% APY — that's amazing! I'm putting all my money there." Write a 200-word response explaining the risks.
Calculation Exercises
Exercise 6: Health Factor Calculations
A borrower deposits 10 ETH (current price: $3,000) and 50,000 USDC as collateral on Aave v3. The parameters are:
| Asset | LTV (Max) | Liquidation Threshold |
|---|---|---|
| ETH | 80% | 82.5% |
| USDC | 77% | 80% |
(a) Calculate the maximum amount the borrower can borrow in DAI.
(b) The borrower borrows $50,000 DAI. Calculate the health factor.
(c) ETH drops to $2,200. Calculate the new health factor.
(d) At what ETH price does the borrower get liquidated? (Assume USDC remains at $1.00 and DAI debt remains at $50,000.)
Exercise 7: Interest Rate Model Computation
A lending pool has the following parameters: - Base Rate: 2% - Optimal Utilization: 80% - Slope1: 6% - Slope2: 150% - Reserve Factor: 15%
(a) Calculate the borrow rate at 50% utilization.
(b) Calculate the borrow rate at 80% utilization (exactly at the kink).
(c) Calculate the borrow rate at 95% utilization.
(d) Calculate the supply rate at each of the three utilization levels above.
(e) The pool currently has $500M in deposits and $400M in borrows. A whale deposits an additional $100M. What happens to: the utilization rate, the borrow rate, and the supply rate? Calculate all three before and after the deposit.
Exercise 8: Liquidation Profit Calculation
A liquidation bot identifies the following position:
- Collateral: 20 ETH at $1,800 = $36,000
- Debt: $32,000 USDC
- Health Factor: 0.928
- Liquidation penalty: 5%
- Maximum liquidation (close factor): 50%
- Gas cost for the transaction: $50
(a) How much debt can the liquidator repay?
(b) How much collateral does the liquidator receive?
(c) What is the liquidator's gross profit?
(d) What is the liquidator's net profit after gas?
(e) After the liquidation, what are the borrower's remaining collateral, remaining debt, and new health factor?
(f) Is the position still liquidatable? If yes, calculate the profit from a second liquidation.
Exercise 9: Flash Loan Arbitrage Profitability
A trader identifies an arbitrage opportunity: - ETH/USDC on Uniswap: $2,498 - ETH/USDC on SushiSwap: $2,506
The trader plans to use an Aave flash loan (0.05% fee) to: 1. Borrow 1,000 ETH from Aave 2. Sell 1,000 ETH for USDC on SushiSwap (0.3% swap fee) 3. Buy ETH with USDC on Uniswap (0.3% swap fee) 4. Repay flash loan + fee
(a) Calculate the gross arbitrage profit (before fees) for 1,000 ETH.
(b) Calculate the flash loan fee.
(c) Calculate the total DEX swap fees.
(d) Estimate gas costs at 200 gwei for a complex multi-step transaction (approximately 500,000 gas).
(e) Calculate the net profit. Is the trade profitable?
(f) At what price difference (in dollars per ETH) does the trade become unprofitable, given the fee structure above?
Applied Exercises
Exercise 10: Protocol Risk Assessment
Choose one of the following DeFi lending protocols: Aave v3, Compound v3, Morpho, Spark (MakerDAO), or Radiant Capital.
Research the protocol and write a risk assessment covering:
(a) Smart contract risk: How many audits has it undergone? Has it ever been exploited? What is the bug bounty size?
(b) Oracle risk: What oracle system does it use? Is it susceptible to manipulation?
(c) Governance risk: How is governance structured? What is the timelock? Has governance ever made a mistake?
(d) Liquidity risk: What is the typical utilization rate for major pools? Has the protocol ever experienced a liquidity crunch?
(e) Systemic risk: What other protocols depend on this one? What would happen to the broader DeFi ecosystem if this protocol failed?
Assign a risk rating (Low/Medium/High/Critical) to each category and justify your assessment with specific evidence.
Exercise 11: Yield Farming Strategy Design
You have $50,000 in USDC and want to earn yield in DeFi. Design two strategies:
Strategy A (Conservative): Single-protocol, no leverage, established protocols only. - Describe the exact steps. - Estimate the APY (distinguishing real yield from token emissions). - List the risks and assign a probability estimate to each.
Strategy B (Aggressive): Multi-protocol, leveraged, yield farming. - Describe the exact steps (including any recursive leverage). - Estimate the APY at current rates. - Calculate the health factor at each layer of leverage. - Identify the liquidation trigger for the overall position. - Explain what happens to the position in a 30% market crash.
Compare the risk-adjusted returns of both strategies.
Exercise 12: Protocol Design Challenge
Design a lending protocol for a specific niche: real-world assets (RWAs) — tokenized treasury bills, real estate, and invoices.
(a) Should the protocol use overcollateralization? Why or why not? If not, what alternative risk management mechanism would you use?
(b) Design an interest rate model. What should the optimal utilization be? Should Slope2 be higher or lower than for crypto-native assets?
(c) How would liquidation work for real-world assets that cannot be sold instantly on a DEX?
(d) Should the protocol support flash loans? Why or why not?
(e) What oracle would provide price feeds for the assets? How would you handle assets that do not trade on public markets?
(f) Identify three risks specific to RWA lending that do not exist in crypto-native lending.
Programming Exercises
Exercise 13: Extend the Interest Rate Model
Using code/interest_rate_model.py as a starting point:
(a) Add a third segment to the interest rate curve — a "critical zone" above 95% utilization where rates increase even faster than Slope2. Implement and visualize the three-segment curve.
(b) Implement a dynamic interest rate model where the optimal utilization point shifts based on recent utilization history (e.g., if utilization has been above optimal for the past 100 blocks, the optimal point increases by 1%).
(c) Simulate 1,000 blocks of supply and demand shocks and plot how the utilization rate and interest rates evolve over time.
Exercise 14: Liquidation Bot Simulation
Using code/liquidation_simulator.py as a starting point:
(a) Add multiple collateral assets (ETH, WBTC, LINK) with different collateral factors and liquidation thresholds.
(b) Simulate a market crash scenario where all assets drop 40% over 100 blocks, with each asset having different volatility.
(c) Implement a "gas market" where liquidation transactions cost gas, and gas prices spike during high-liquidation periods (simulating the Black Thursday dynamic).
(d) Calculate the total bad debt generated when gas prices are too high for liquidations to be profitable.
Exercise 15: Flash Loan Detector
Write a Python script that, given a simplified transaction log, identifies flash loan transactions. A flash loan transaction has the following pattern: - A borrow event and a repay event for the same asset and amount (plus fee) within the same transaction hash. - The time between borrow and repay is zero (same block).
Generate a synthetic transaction log with 1,000 transactions (10% of which are flash loans) and test your detector's precision and recall.
Discussion Questions
Discussion 1: The Ethics of Flash Loan Exploits
Avraham Eisenberg publicly argued that his $114 million manipulation of Mango Markets was a "profitable trading strategy" that operated within the protocol's rules. He was later convicted of fraud.
(a) Was Eisenberg right that he was operating within the protocol's rules? Is "the code is the law" a valid defense?
(b) Where is the line between a legitimate flash loan arbitrage and a flash loan exploit? Propose a definition.
(c) Should DeFi protocols be designed to prevent flash loan attacks, even if doing so reduces capital efficiency? What tradeoffs are involved?
Discussion 2: DeFi Lending and Financial Inclusion
Proponents argue that DeFi lending democratizes access to financial services. Critics argue that overcollateralization makes DeFi lending useless for the people who need loans most — those without existing capital.
(a) Who actually benefits from DeFi lending in its current form? Be specific about the user profile.
(b) Could DeFi lending ever serve undercollateralized borrowers? What would be required? What are the obstacles?
(c) Compare DeFi lending's inclusion claims to the reality of microfinance in developing countries. What lessons apply?
Discussion 3: The Sustainability of Yield
"If you don't know where the yield comes from, you are the yield." — Common crypto saying.
(a) Apply this statement to yield farming. Who is the yield coming from in an inflationary token emission program?
(b) Terra/Luna's Anchor Protocol offered a "guaranteed" 20% APY on stablecoin deposits. Using the real yield framework from this chapter, explain why this was unsustainable and what eventually happened.
(c) Is it possible for a DeFi lending protocol to sustainably offer yields higher than traditional savings accounts (currently 4-5% in the US)? Under what conditions?