Complete Guide to Lending and Borrowing Protocols: A Security Auditor's Perspective
Comprehensive guide to lending and borrowing protocols covering architecture, vulnerabilities, attack vectors, and security best practices from professional auditors with $50B+ TVL at stake.

Complete Guide to Lending and Borrowing Protocols: A Security Auditor's Perspective
Lending and borrowing protocols represent the largest vertical in decentralized finance, with over $50 billion in Total Value Locked (TVL) as of late 2025. These protocols have become fundamental DeFi primitives, enabling users to earn yield on deposited assets and access liquidity without selling their holdings. However, this massive value concentration makes them prime targets for sophisticated attacks—resulting in over $21.3 million lost across major protocols in recent years.
From a security auditor's perspective, lending protocols present unique challenges due to their complex economic mechanisms, oracle dependencies, and intricate state management. This comprehensive guide explores the architecture, vulnerabilities, and security best practices essential for building and auditing secure lending protocols.
Understanding Lending Protocol Fundamentals
At their core, lending protocols facilitate peer-to-pool lending where suppliers deposit assets into liquidity pools and borrowers take loans by providing collateral. The system operates through algorithmic interest rate models that automatically adjust based on supply and demand dynamics.
The basic flow involves lenders depositing crypto assets into smart contract pools, receiving interest-bearing tokens (like aTokens in Aave) representing their deposits. Borrowers then deposit collateral and can borrow up to a predetermined Loan-to-Value (LTV) ratio—typically 70-80% for volatile assets. For example, depositing 1 ETH valued at $2,500 with an 80% LTV allows borrowing $2,000 worth of assets.
Key Terminology and Metrics
Loan-to-Value (LTV) Ratio: The maximum percentage of collateral value that can be borrowed. This ratio is inversely proportional to asset volatility—more stable assets have higher LTV ratios.
Liquidation Threshold: The point at which a borrowing position becomes eligible for liquidation. When collateral value drops and the borrowed amount exceeds this threshold, liquidators can step in to repay debt in exchange for discounted collateral.
Utilization Rate: The ratio of borrowed assets to total supplied assets, calculated as: Utilization = Total Borrowed / Total Supplied. This metric directly influences interest rates in most protocols.
Annual Percentage Yield (APY): The compounded interest earned on supplied assets over one year, dynamically adjusted based on utilization rates and protocol parameters.
Protocol Architecture Types
Modern lending protocols have evolved beyond simple architecture into specialized designs catering to different risk profiles and use cases. Understanding these variations is crucial for comprehensive security analysis.
Collateral-Based Classification
Overcollateralized Lending: The dominant model used by protocols like Aave, Compound, and MakerDAO. Borrowers must provide collateral exceeding loan value, ensuring trustless and permissionless operations without requiring user identity verification. This design protects lenders from default risk through automated liquidation mechanisms.
Undercollateralized Lending: Emerging protocols like Wildcat allow institutional borrowers to secure loans with less collateral than borrowed amounts. These systems rely on reputation, vetting processes, and legal agreements rather than pure overcollateralization, bridging DeFi with traditional credit markets.
Flash Loans (Uncollateralized): Unique to DeFi, flash loans require no upfront collateral but must be borrowed and repaid within a single blockchain transaction. If repayment fails, the entire transaction reverts. Protocols charge small fees (typically 0.05-0.09%) for this service, which has legitimate uses but also enables sophisticated attacks.
Interest Rate Mechanisms
Floating Rates: Most protocols like Aave and Compound employ dynamic rates that adjust automatically based on utilization. High utilization increases both borrow and supply rates, incentivizing more deposits while discouraging borrowing. This creates natural market balance.
Fixed Rates: Protocols like Notional Finance offer predetermined interest rates for specific lending terms, providing stability and predictability for users who want to lock in yields or borrow costs. This reduces volatility but requires more complex interest rate derivative mechanisms.
Liquidity Management Approaches
Pooled Liquidity: Protocols like Fluid aggregate all lending liquidity into unified pools, maximizing capital efficiency. Advanced implementations enable deposited collateral itself to earn yield in lending markets, effectively reducing net borrowing costs for users.
Isolated Markets: Platforms like Silo and Fuse create segregated lending pools for specific assets or asset pairs. This isolation prevents risk contagion—if one market experiences issues, other markets remain unaffected. While potentially less capital-efficient, isolated markets offer superior risk management.
Core Protocol Flow
┌─────────────────────────────────────────────────────────┐
│ LENDING & BORROWING PROTOCOL FLOW │
└─────────────────────────────────────────────────────────┘
┌──────────────────────────────────────────┐
│ LENDER SUPPLIES LIQUIDITY │
│ • Deposit crypto assets to pool │
│ • Receive interest-bearing tokens │
│ • Earn dynamic APY based on util rate │
└──────────────┬───────────────────────────┘
│
▼
┌──────────────────────────────────────────┐
│ LIQUIDITY POOL FORMED │
│ • Assets locked in smart contracts │
│ • Available for borrowing │
│ • Utilization rate calculated │
└──────────────┬───────────────────────────┘
│
▼
┌──────────────────────────────────────────┐
│ BORROWER DEPOSITS COLLATERAL │
│ • Provide assets as security │
│ • Protocol evaluates LTV ratio │
│ • Oracle determines asset values │
└──────────────┬───────────────────────────┘
│
▼
┌──────────────────────────────────────────┐
│ BORROW AGAINST COLLATERAL │
│ • Request loan up to LTV limit │
│ • Smart contract validates solvency │
│ • Borrowed assets transferred │
│ • Interest begins accruing │
└──────────────┬───────────────────────────┘
│
▼
┌──────────────────────────────────────────┐
│ CONTINUOUS HEALTH MONITORING │
│ • Oracle updates asset prices │
│ • Protocol tracks collateral ratios │
│ • Interest compounds over time │
└──────────────┬───────────────────────────┘
│
┌───────┴────────┐
▼ ▼
┌──────────┐ ┌──────────────┐
│ REPAY │ │ LIQUIDATION │
│ • Return│ │ • Health <1 │
│ loan │ │ • Liquidator│
│ • Reclaim │ • Discounted│
│ collateral │ collateral│
└──────────┘ └──────────────┘
Critical Attack Vectors
From thousands of security audits and incident analyses, lending protocols face recurring vulnerability patterns. Understanding these attack vectors is essential for building secure systems.
Oracle Manipulation Attacks
Oracle manipulation represents the most lucrative attack vector in DeFi lending, with attackers artificially inflating collateral values or deflating borrowed asset prices to extract under-collateralized loans. The June 2024 UwU Lend exploit exemplified this, where attackers manipulated price oracles to steal $20 million through flash loan-based price distortion.
The attack mechanism involves using flash loans to temporarily manipulate on-chain liquidity pools that protocols use for pricing. Protocols relying on spot prices from low-liquidity DEX pairs (using getReserves() or balanceOf()) are particularly vulnerable. Even Time-Weighted Average Price (TWAP) oracles can be manipulated when attack costs are lower than potential profits.
The Warp Finance incident demonstrates LP token pricing vulnerabilities. Attackers exploited how the protocol calculated LP token values as [Total Pool TVL] / [LP Tokens Minted]. By manipulating pool reserves through flash loans, they inflated LP token values and borrowed against artificially valued collateral.
Reentrancy Attacks
Reentrancy vulnerabilities in lending protocols often involve hookable tokens like ERC-777, which execute callbacks during transfers. The infamous Fei Rari hack exploited reentrancy through ETH transfer hooks, allowing attackers to borrow recursively before solvency checks were updated.
The attack pattern exploits the gap between when borrowing occurs and when protocol state updates. During ERC-777 token transfer hooks, attackers call the borrow function again before the first borrow completes. Since balances haven't updated yet, LTV checks pass multiple times, enabling massive over-borrowing.
Flash Loan Attacks
Flash loan attacks surged in 2024, comprising 83.3% of eligible DeFi exploits. These attacks combine uncollateralized borrowing with other vulnerabilities like oracle manipulation or protocol logic flaws to drain funds within single transactions.
The Euler Finance exploit in March 2023 resulted in nearly $200 million loss through flash loan-enabled recursive borrowing. Attackers exploited insufficient solvency checks in supplementary functions, demonstrating how flash loans amplify the impact of seemingly minor vulnerabilities.
Defense mechanisms include implementing borrowing caps per transaction, introducing time delays between large operations, and comprehensive solvency validation after every state-changing function. Circuit breakers that pause protocol operations when detecting abnormal patterns provide additional protection.
Governance Attacks
DAO-governed lending protocols face risks from malicious governance proposals that modify risk parameters, whitelist dangerous assets, or change reserve factors. Attackers accumulate governance tokens or exploit voting mechanisms to pass proposals favoring exploitation.
Mitigation strategies include implementing timelocks on parameter changes (typically 24-48 hours), requiring higher quorum thresholds for critical changes, establishing multi-signature safeguards for emergency actions, and creating guardian roles that can veto clearly malicious proposals.
Major Protocol Exploits: Lessons Learned
| Protocol | Date | Loss Amount | Attack Vector | Root Cause |
|---|---|---|---|---|
| Euler Finance | March 2023 | $200 million | Flash loan + Logic error | Missing solvency checks in emergency withdraw |
| UwU Lend | June 2024 | $20 million | Oracle manipulation | Price oracle exploit via flash loans |
| Platypus Finance | February 2023 | $8.5 million | Logic vulnerability | Incomplete solvency validation |
| Fei Rari | April 2022 | $80 million | Reentrancy | ETH transfer hooks exploited |
| Cream Finance | Multiple 2021-2022 | $130+ million | Various (Oracle, Reentrancy) | Multiple vulnerabilities in forks |
Euler Finance - March 2023
Loss: $200 million
Vector: Flash loan + Logic error
Missing solvency checks in emergency withdraw
UwU Lend - June 2024
Loss: $20 million
Vector: Oracle manipulation
Price oracle exploit via flash loans
Fei Rari - April 2022
Loss: $80 million
Vector: Reentrancy
ETH transfer hooks exploited
Cream Finance - 2021-2022
Loss: $130+ million
Vector: Various
Multiple vulnerabilities across different exploits
Security Best Practices for Development
Building secure lending protocols requires systematic application of security principles throughout the development lifecycle. Morpho's security framework provides excellent guidance, emphasizing simplicity, minimal dependencies, and comprehensive testing.
Pre-Build Phase
Minimize Protocol Complexity: Resist feature creep by implementing only essential functionality. Each additional feature exponentially increases the attack surface. Document and justify every design decision, removing features that don't directly serve core protocol objectives.
Avoid Protocol-Level Risk Management: Enshrining oracles or risk management logic at the protocol level creates dangerous dependencies and increases code complexity. Instead, design modular systems where risk parameters can be managed externally or through governance.
Threat Modeling: Conduct comprehensive threat modeling sessions identifying potential attack vectors, adversary capabilities, and worst-case scenarios. Document each threat with mitigation strategies before writing any code.
Build and Test Phase
Comprehensive Testing Strategy: Implement multiple testing layers including unit tests (testing individual functions), integration tests (testing component interactions), fork tests (testing against mainnet state), and invariant testing (ensuring protocol rules never break). Aim for 100% code coverage with meaningful test scenarios.
Formal Verification: For critical components like liquidation engines and interest rate calculations, employ formal verification to mathematically prove correctness. This catches edge cases that traditional testing might miss.
Secure Coding Patterns: Follow the Checks-Effects-Interactions pattern religiously—validate inputs, update state, then make external calls. Utilize well-audited libraries like OpenZeppelin for standard functionality rather than rolling custom implementations.
Pre-Deployment Phase
Multiple Security Audits: Engage at least 2-3 reputable audit firms with specialized expertise in lending protocols. Address all critical and high-severity findings before deployment.
Public Security Review: Before audits, invite trusted security researchers and advisors to review the codebase. External perspectives often identify blind spots that internal teams miss.
Bug Bounty Programs: Implement substantial bug bounty programs through platforms like Immunefi or Code4rena. Offering rewards proportional to severity incentivizes white-hat hackers to find bugs before malicious actors do.
Post-Deployment Phase
Real-Time Monitoring: Deploy comprehensive monitoring systems tracking on-chain activity, unusual liquidations, price deviations, and rapid utilization changes. Services like Forta, Tenderly, and OpenZeppelin Defender provide specialized DeFi monitoring.
Incident Response Plans: Develop detailed incident response procedures covering attack detection, protocol pausing, stakeholder communication, and asset recovery strategies. Partnerships with blockchain analysis firms can assist in tracking stolen funds.
Gradual Deployment: Launch with conservative parameters—lower LTV ratios, smaller borrowing limits, and restricted token whitelists. Gradually increase limits as the protocol proves stability.
Auditor's Checklist
When auditing lending protocols, systematically verify these critical security aspects:
Oracle Security: Verify all price feeds use decentralized oracles like Chainlink with staleness checks and deviation thresholds. Validate LP token and yield-bearing token valuations use manipulation-resistant formulas.
Reentrancy Protection: Audit all external calls for reentrancy vulnerabilities, especially with ERC-777 tokens or ETH transfers. Verify Checks-Effects-Interactions patterns and reentrancy guards on all public/external functions.
Solvency Checks: Confirm comprehensive solvency validation occurs after every state-changing operation—not just primary functions but also emergency functions, callbacks, and admin operations.
Interest Rate Calculations: Validate interest accrual logic for precision loss, overflow/underflow, and edge cases like 100% utilization. Ensure compounding calculations are accurate and gas-efficient.
Liquidation Mechanism: Test liquidation logic under various market conditions including rapid price movements, low liquidity, and gas price spikes. Verify liquidators receive proper incentives without over-penalizing borrowers.
Access Controls: Review all privileged functions for proper access restrictions. Verify governance changes go through timelocks and multi-signature requirements appropriate for protocol value.
Decimal Handling: Meticulously check all arithmetic operations for decimal precision, especially when handling tokens with different decimals (6 for USDC, 18 for ETH).
Flash Loan Resistance: Analyze whether protocol state can be manipulated within single transactions. Consider implementing per-block borrowing caps or requiring multi-block commitments for large operations.
Leading Protocols: Architecture Comparison
| Protocol | Architecture | Interest Rate | Key Innovation | TVL (2025) |
|---|---|---|---|---|
| Aave | Pooled liquidity | Dynamic (utilization-based) | Flash loans, isolation mode, eMode | $20B+ |
| Compound | Pooled liquidity | Dynamic (utilization-based) | cToken model, governance-driven | $5B+ |
| MakerDAO | CDP (Collateralized Debt Position) | Governance-set stability fee | DAI stablecoin minting | $8B+ |
| Morpho | Peer-to-peer matching layer | Optimized P2P rates | Improves rates on Aave/Compound | $2B+ |
| Silo Finance | Isolated markets | Dynamic per-market | Risk isolation, permissionless markets | $100M+ |
Aave
Architecture: Pooled liquidity
Rate: Dynamic (utilization-based)
Innovation: Flash loans, isolation mode
TVL: $20B+
Compound
Architecture: Pooled liquidity
Rate: Dynamic
Innovation: cToken model
TVL: $5B+
MakerDAO
Architecture: CDP model
Rate: Governance-set
Innovation: DAI stablecoin
TVL: $8B+
Emerging Trends and Future Considerations
Cross-Chain Lending: Protocols are expanding beyond single-chain deployments to offer cross-chain borrowing and lending. This introduces new security challenges around bridge security, oracle synchronization across chains, and managing liquidations in multi-chain environments.
Real-World Asset (RWA) Integration: Platforms increasingly tokenize real-world assets like real estate, invoices, and commodities as collateral. This requires new security models bridging on-chain and off-chain verification, legal compliance, and dispute resolution.
Undercollateralized Lending Growth: As DeFi matures, demand grows for undercollateralized and reputation-based lending. Security audits must adapt to evaluate off-chain reputation systems, legal safeguards, and credit scoring mechanisms.
AI-Powered Risk Management: Machine learning models are being integrated for dynamic risk assessment, anomaly detection, and predictive liquidation management. Auditors must understand these systems' decision-making processes and potential manipulation vectors.
Conclusion
Lending and borrowing protocols represent DeFi's most mature and valuable sector, but their complexity and value concentration demand exceptional security rigor. The recurring pattern of exploits—from oracle manipulation to reentrancy and flash loan attacks—demonstrates that security cannot be an afterthought.
Successful protocols prioritize security from the pre-build phase through ongoing post-deployment monitoring. They minimize complexity, undergo multiple comprehensive audits, implement robust monitoring systems, and maintain incident response readiness. For developers building the next generation of lending protocols, learning from past exploits and applying systematic security practices is not optional—it's essential for protecting the billions of dollars users entrust to these systems.
At 0xTeam, our security audits focus on these critical attack vectors, combining automated analysis tools with manual expert review to identify vulnerabilities before they can be exploited. As DeFi continues evolving with cross-chain integration, RWA tokenization, and AI-powered features, security auditing must evolve in parallel—ensuring the next generation of lending protocols builds on solid foundations rather than repeating past mistakes.

.png&w=3840&q=75)





