A production-grade Solana DeFi lending protocol clone inspired by Kamino Finance's K-Lend, built with Anchor 0.30+ and following February 2026 best practices.
- Overview
- Features
- Architecture
- Interest Rate Model
- Liquidation Mechanics
- Installation
- Building & Testing
- Deployment
- Contact
This project implements a complete DeFi lending protocol for Solana, similar to Kamino Finance's K-Lend. It enables users to:
- Supply assets to earn interest via yield-bearing tokens
- Borrow assets against collateral with dynamic interest rates
- Liquidate unhealthy positions at a discount
- Create isolated markets with custom parameters (LTV, liquidation threshold, oracle)
- Automate yield through vault strategies
- Modular Markets: Each asset has its own isolated lending market with configurable parameters
- Dynamic Interest Rates: Utilization-based rates that adjust automatically
- Yield-Bearing Tokens: Supply tokens accrue interest automatically
- Health Factor: Real-time collateralization ratio monitoring
- Permissionless Liquidation: Anyone can liquidate unhealthy positions
- Vault Strategies: Automated yield optimization across multiple markets
-
Market Creation
- Create isolated lending markets for any SPL token
- Configurable LTV ratios (up to 80%)
- Custom liquidation thresholds (85-90%)
- Oracle integration (Pyth or custom)
-
Supply & Earn
- Supply assets to markets
- Receive yield-bearing tokens (supply tokens)
- Automatic interest accrual
- Withdraw anytime (subject to health factor)
-
Borrow Against Collateral
- Borrow up to LTV limit (e.g., 75% of collateral value)
- Dynamic interest rates based on utilization
- Health factor monitoring
- Repay anytime to reduce debt
-
Liquidation
- Permissionless liquidation of unhealthy positions
- Liquidation bonus (5% discount) for liquidators
- Seize collateral at favorable rates
- Protects protocol solvency
-
Vault Strategies
- Conservative: Low risk, stable yields
- Balanced: Moderate risk/reward
- Aggressive: Higher risk, higher yields
- Automatic rebalancing across markets
- ✅ Anchor framework best practices
- ✅ PDA-based account management
- ✅ Health factor checks on all operations
- ✅ Oracle staleness validation
- ✅ Math overflow protection
- ✅ Reentrancy protection via Anchor's account model
- ✅ Custom error types for clear failure cases
solana-defi-lending-protocol/
├── programs/
│ └── solana-defi-lending-protocol/
│ └── src/
│ ├── lib.rs # Program entry point
│ ├── state.rs # Account structs
│ ├── errors.rs # Error definitions
│ ├── constants.rs # Protocol constants
│ ├── math.rs # Interest & health calculations
│ └── instructions/
│ ├── mod.rs
│ ├── initialize.rs # Initialize protocol
│ ├── market.rs # Create markets
│ ├── supply.rs # Supply assets
│ ├── borrow.rs # Borrow assets
│ ├── repay.rs # Repay debt
│ ├── withdraw.rs # Withdraw supply
│ ├── liquidate.rs # Liquidate positions
│ └── vault.rs # Vault operations
└── tests/
└── solana-defi-lending-protocol.ts
- PDA:
[b"global_config"] - Fields:
authority: Protocol authoritytreasury: Treasury PDA for feesprotocol_fee_bps: Protocol fee (5% = 500 bps)market_count: Total markets createdtreasury_bump: Treasury PDA bump
- PDA:
[b"market", asset_mint] - Fields:
market_id: Unique market identifierasset_mint: Underlying asset mintsupply_mint: Yield-bearing token mintreserve_vault: Vault holding supplied assetsoracle: Price oracle accountltv_bps: Loan-to-value ratio (e.g., 7500 = 75%)liquidation_threshold_bps: Liquidation threshold (e.g., 8500 = 85%)total_supplied: Total assets supplied (with interest)total_borrowed: Total assets borrowed (with interest)total_supply_tokens: Total supply tokens mintedcumulative_borrow_rate: For interest accrualcumulative_supply_rate: For interest accruallast_accrual_timestamp: Last interest accrual time
- PDA:
[b"borrow_position", user, market] - Fields:
user: Borrower addressmarket: Market addressborrowed_amount: Principal borrowedcumulative_borrow_rate_snapshot: Rate when borrowedcreated_at: Position creation timelast_updated: Last update time
- PDA:
[b"vault", owner] - Fields:
owner: Vault ownerstrategy: Strategy type (0=Conservative, 1=Balanced, 2=Aggressive)total_assets: Assets under managementallocations: Market allocation percentageslast_rebalance: Last rebalance timerebalance_threshold_bps: Rebalance trigger threshold
1. Initialize Protocol
└─> Creates GlobalConfig and Treasury PDAs
2. Create Market
└─> Creates Market account with config
└─> Sets up reserve vault and supply mint
3. Supply Assets
└─> Transfer assets to reserve vault
└─> Mint supply tokens to user
└─> Update total_supplied
4. Borrow Assets
└─> Check health factor
└─> Transfer assets from reserve
└─> Create/update borrow position
└─> Update total_borrowed
5. Repay Debt
└─> Transfer assets to reserve
└─> Update borrow position
└─> Update total_borrowed
6. Withdraw Supply
└─> Check health factor
└─> Burn supply tokens
└─> Transfer assets from reserve
└─> Update total_supplied
7. Liquidate
└─> Verify health factor < threshold
└─> Repay debt at discount
└─> Seize collateral with bonus
└─> Update both markets
The protocol uses a piecewise linear interest rate model based on utilization:
Utilization = Total Borrowed / Total Supplied
Below Optimal Utilization (≤80%):
borrow_rate = base_rate + slope1 * (utilization / optimal_utilization)
Above Optimal Utilization (>80%):
borrow_rate = base_rate + slope1 + slope2 * ((utilization - optimal) / (1 - optimal))
supply_rate = borrow_rate * utilization * (1 - protocol_fee)
- Base Rate: ~2% APY (634,195,839 per second)
- Slope 1: ~10% APY per 10% utilization (below optimal)
- Slope 2: ~100% APY per 10% utilization (above optimal)
- Optimal Utilization: 80%
- Protocol Fee: 5% of interest
Interest accrues continuously using compound interest:
new_amount = old_amount * (1 + rate_per_second) ^ seconds_elapsed
For on-chain efficiency, simplified to:
new_amount = old_amount * (1 + rate * seconds / scale)
Health factor determines if a position can be liquidated:
Health Factor = (Collateral Value * Liquidation Threshold) / Total Borrowed Value
- Health Factor > 1.0: Position is safe
- Health Factor < 1.0: Position can be liquidated
- Detection: Health factor drops below threshold (1.0)
- Liquidation: Anyone can repay debt and seize collateral
- Bonus: Liquidator receives 5% discount on seized collateral
- Protection: Protocol remains solvent
collateral_seized = debt_repaid * (1 + liquidation_bonus) * (collateral_price / borrow_price)
Where:
liquidation_bonus= 5% (500 basis points)- Prices from oracles
- User borrows 100 USDC against 150 SOL collateral
- SOL price drops → Health factor < 1.0
- Liquidator repays 100 USDC
- Receives ~105 USDC worth of SOL (5% bonus)
- Rust 1.70+
- Solana CLI 1.18+
- Anchor CLI 0.30+
- Node.js 18+ and Yarn/npm
-
Clone the repository
git clone <repository-url> cd Solana-DeFi-Lending-Protocol
-
Install Anchor
cargo install --git https://github.com/coral-xyz/anchor avm --locked --force avm install latest avm use latest
-
Install dependencies
anchor build cd tests && yarn install
anchor buildThis will:
- Compile the Rust program
- Generate the IDL
- Create the program binary
anchor testOr run tests with verbose output:
anchor test --skip-local-validator-
Start local validator
solana-test-validator
-
Deploy program
anchor deploy
-
Run tests
anchor test --skip-local-validator
The test suite includes:
- ✅ Protocol initialization
- ✅ Market creation
- ✅ Supply operations
- ✅ Borrow operations
- ✅ Repay operations
- ✅ Withdraw operations
- ✅ Liquidation scenarios
- ✅ Interest accrual over time
- ✅ Health factor calculations
-
Set Solana CLI to devnet
solana config set --url devnet -
Airdrop SOL (if needed)
solana airdrop 2 <your-wallet-address>
-
Update program ID
- Generate new keypair:
solana-keygen new -o target/deploy/solana_defi_lending_protocol-keypair.json - Update
declare_id!inlib.rs - Update
Anchor.tomlwith new program ID
- Generate new keypair:
-
Build and deploy
anchor build anchor deploy
-
Set Solana CLI to mainnet
solana config set --url mainnet-beta -
Build for mainnet
anchor build
-
Deploy (requires sufficient SOL)
anchor deploy
-
Verify deployment
solana program show <program-id>
-
Initialize protocol
- Call
initializeinstruction with protocol authority - Sets up GlobalConfig and Treasury PDAs
- Call
-
Create markets
- Call
create_marketfor each asset - Configure LTV, liquidation threshold, oracle
- Call
-
Verify setup
- Check GlobalConfig account
- Verify markets are created correctly
- Test supply/borrow operations
- Telegram: https://t.me/codiiman
- Twitter: https://x.com/codiiman_