Skip to content

Base29/lending-smart-contract

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Collateralized Lending Protocol

A minimal, secure, and well-documented implementation of a collateralized lending protocol built with Solidity and Foundry.

Overview

This protocol allows users to:

  • Deposit ETH as collateral
  • Borrow MockDAI (stablecoin) up to 50% Loan-to-Value (LTV)
  • Have positions liquidated if collateral value falls below 55% threshold
  • Repay debt to reclaim collateral

Key Features

  • Single Asset Collateral: ETH only
  • Single Debt Asset: MockDAI (mock stablecoin)
  • LTV Cap: 50% (5000 basis points)
  • Liquidation Threshold: 55% (5500 basis points)
  • Liquidation Bonus: 5% for liquidators
  • No Interest: Simple lending without interest accrual
  • No Protocol Fees: Zero fees for basic operations

Security Measures

Core Security

  • ReentrancyGuard: All state-changing functions protected against reentrancy attacks
  • CEI Pattern: Checks-Effects-Interactions pattern followed throughout
  • Input Validation: All amounts validated for non-zero values
  • Access Control: Owner-only functions for admin operations
  • Safe Math: Solidity 0.8.x built-in overflow protection

Economic Security

  • Health Factor Monitoring: Positions checked before withdrawals
  • Liquidation Mechanism: Automatic liquidation of underwater positions
  • Price Feed Integration: Configurable price feeds for collateral valuation
  • LTV Limits: Strict borrowing limits enforced

Limitations & Assumptions

  • Mock Price Feed: Uses configurable mock price (replace with Chainlink in production)
  • Single Collateral: Only ETH supported (extensible design)
  • No Interest: Simple lending without interest accrual
  • No Protocol Fees: Zero fees (can be added later)
  • No Upgradeability: Immutable contracts (consider proxy pattern for production)

Project Structure

lending-task/
├── src/
│   ├── CollateralLending.sol      # Main lending contract
│   ├── MockDAI.sol                # Mock stablecoin
│   └── mocks/
│       └── MockPriceFeed.sol      # Mock price oracle
├── test/
│   ├── CollateralLending.t.sol    # Main contract tests
│   └── MockDAI.t.sol              # Token tests
├── script/
│   └── Deploy.s.sol               # Deployment script
├── foundry.toml                   # Foundry configuration
└── README.md                      # This file

Smart Contracts

CollateralLending.sol

Main lending protocol contract with the following key functions:

  • deposit() - Deposit ETH as collateral (~45k gas)
  • withdraw(uint256) - Withdraw ETH collateral (~35k gas)
  • borrow(uint256) - Borrow MockDAI against collateral (~80k gas)
  • repay(uint256) - Repay MockDAI debt (~60k gas)
  • liquidate(address, uint256) - Liquidate underwater position (~90k gas)

MockDAI.sol

Mock stablecoin with mint/burn restricted to lending contract:

  • ERC20 compliant with 18 decimals
  • Mint/burn functions for lending contract only
  • Initial supply: 1,000,000 DAI

MockPriceFeed.sol

Simple price oracle for ETH/USD:

  • Configurable price with 8 decimals
  • Owner can update price (for testing)
  • Returns ETH price in USD

Setup & Installation

Prerequisites

Installation

  1. Clone and setup:
git clone <repository-url>
cd lending-task
forge install
  1. Install dependencies:
forge install OpenZeppelin/openzeppelin-contracts
  1. Compile contracts:
forge build

Testing

Run All Tests

forge test

Run Tests with Verbose Output

forge test -vv

Run Tests with Gas Report

forge test --gas-report

Run Specific Test File

forge test --match-contract CollateralLendingTest

Run Fuzz Tests

forge test --match-test testFuzz

Gas Usage

Key function gas costs (approximate):

  • deposit(): ~45,000 gas
  • withdraw(): ~35,000 gas
  • borrow(): ~80,000 gas
  • repay(): ~60,000 gas
  • liquidate(): ~90,000 gas

Security Analysis

Run Slither Analysis

  1. Install Slither:
pipx install slither-analyzer
  1. Run analysis:
slither .
  1. Run with specific detectors:
slither . --detect reentrancy,uninitialized-state,uninitialized-storage

Manual Security Checklist

  • Reentrancy protection on all state-changing functions
  • Input validation for all parameters
  • Access control on admin functions
  • Safe math operations (Solidity 0.8.x)
  • Health factor checks before withdrawals
  • Liquidation mechanism for underwater positions
  • Comprehensive test coverage
  • Fuzz testing for edge cases

Deployment

Local Development

# Start local node
anvil

# Deploy (in another terminal)
forge script script/Deploy.s.sol --rpc-url http://localhost:8545 --broadcast

Testnet/Mainnet

# Set private key
export PRIVATE_KEY=your_private_key_here

# Deploy to testnet
forge script script/Deploy.s.sol --rpc-url <RPC_URL> --broadcast --verify

Usage Examples

Basic Lending Flow

  1. Deposit ETH as collateral:
lending.deposit{value: 10 ether}();
  1. Borrow MockDAI:
uint256 maxBorrow = lending.maxBorrowableDai(user);
lending.borrow(maxBorrow);
  1. Check position health:
uint256 healthFactor = lending.healthFactor(user);
bool isLiquidatable = lending.isLiquidatable(user);
  1. Repay debt:
lending.repay(repayAmount);
  1. Withdraw collateral:
lending.withdraw(withdrawAmount);

Liquidation Example

// Liquidate underwater position
lending.liquidate(user, debtAmount);

Development

Adding New Features

  1. Interest Accrual: Add interest calculation and accrual mechanism
  2. Protocol Fees: Implement fee collection system
  3. Multiple Collaterals: Extend to support other assets
  4. Real Oracle: Replace MockPriceFeed with Chainlink
  5. Upgradeability: Add proxy pattern for upgradeable contracts

Testing Strategy

  • Unit Tests: Test individual functions
  • Integration Tests: Test complete workflows
  • Fuzz Tests: Test with random inputs
  • Invariant Tests: Test system invariants
  • Gas Tests: Monitor gas usage

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Run security analysis
  6. Submit a pull request

License

MIT License - see LICENSE file for details.

Disclaimer

This is a prototype implementation for educational purposes. Not audited for production use. Use at your own risk.

About

ETH Lending

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published