Skip to content

pranay123-stack/defi-projects

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 

Repository files navigation

DeFi Projects

A comprehensive collection of Decentralized Finance (DeFi) protocol implementations — from fundamental building blocks like token swaps to advanced strategies like flash loan arbitrage, yield optimization, and cross-chain liquidity. Built for deep understanding of DeFi mechanics at the smart contract level.


Table of Contents


Overview

This repository contains production-quality implementations of core DeFi protocols. Each project dives into the economic models, mathematical invariants, and security patterns that power real protocols managing billions in TVL.

What makes this different:

  • Every project includes detailed comments explaining the math and economic reasoning behind the code
  • Mainnet fork tests that interact with live protocols (Aave, Uniswap, Compound)
  • Gas optimization techniques used in production DeFi
  • Comprehensive attack vector analysis and mitigation for each protocol type
  • Foundry-first development with Hardhat support

Why DeFi?

DeFi protocols are the backbone of the on-chain economy. Understanding how they work at the contract level gives you:

  • Deep knowledge of financial engineering on the blockchain
  • Ability to identify vulnerabilities and economic exploits
  • Skills to build, audit, and contribute to real protocols
  • Foundation for MEV research, protocol design, and quantitative DeFi

Tech Stack

Layer Technology
Smart Contracts Solidity 0.8.x
Primary Framework Foundry (Forge, Cast, Anvil, Chisel)
Secondary Framework Hardhat
Math Libraries PRBMath, Solmate, OpenZeppelin Math
Token Standards ERC-20, ERC-4626 (Tokenized Vaults), ERC-3156 (Flash)
Price Feeds Chainlink Oracles, Uniswap V3 TWAP
Frontend Next.js, wagmi, viem, RainbowKit
Indexing The Graph, Alchemy Subgraphs
Testing Forge tests, fuzzing, invariant testing
Networks Ethereum, Arbitrum, Base, Optimism, Polygon

Projects

Core DeFi Primitives

# Project Description Key Concepts
01 ERC-20 Token Factory Deploy custom tokens with minting, burning, pausability, and caps Token standards, access control
02 Token Vesting Linear and cliff-based vesting schedules for team/investor tokens Time-locked releases, cliffs
03 Multi-Token Staking Stake Token A, earn Token B with configurable reward rates Reward distribution math, staking
04 ERC-4626 Tokenized Vault Standard vault interface for yield-bearing tokens Share/asset accounting, EIP-4626
05 Fee-on-Transfer Token Token with built-in transfer tax routed to treasury Deflationary mechanics, tax routing

Lending & Borrowing

# Project Description Key Concepts
06 Simple Lending Pool Deposit collateral, borrow against it, accrue interest Collateral factors, interest models
07 Compound-Style Money Market cToken model with dynamic interest rate curves Utilization rate, jump rate model
08 Aave-Style Lending Protocol aTokens, variable/stable rates, health factor liquidations Health factor, liquidation bonus
09 Liquidation Engine Bot-callable liquidation with bonus incentives Under-collateralization, MEV
10 Isolated Lending Markets Per-pair lending with independent risk parameters Risk isolation, oracle dependency

Decentralized Exchanges

# Project Description Key Concepts
11 Constant Product AMM (x*y=k) Uniswap V2-style AMM with LP tokens and fee collection CPMM invariant, impermanent loss
12 Concentrated Liquidity AMM Uniswap V3-style with tick-based liquidity positions Ticks, ranges, capital efficiency
13 Stable Swap (Curve-Style) Low-slippage swaps for pegged assets using StableSwap invariant Amplification factor, peg stability
14 Order Book DEX On-chain limit order book with matching engine Bid/ask, order matching, gas costs
15 DEX Aggregator (Router) Route trades across multiple pools for best execution Split routing, price impact

Yield Optimization

# Project Description Key Concepts
16 Auto-Compounding Vault Harvest rewards and reinvest automatically for compound growth Harvest frequency, APY vs APR
17 Yield Farm Aggregator Deposit into highest-yield farm, rebalance periodically Strategy selection, gas efficiency
18 Liquidity Mining Program Distribute governance tokens to LPs based on time-weighted stakes Reward per second, boosted rewards
19 Leveraged Yield Farming Borrow to amplify LP positions and farming rewards Leverage ratio, liquidation risk
20 Convex-Style Boost Aggregator Pool governance tokens to boost yields for all participants Vote-escrowed tokens, boost mechanics

Derivatives & Synthetics

# Project Description Key Concepts
21 Perpetual Futures Exchange Long/short perps with funding rate mechanism Funding rate, mark vs index price
22 Options Protocol European-style call/put options with Black-Scholes pricing Greeks, implied volatility, settlement
23 Synthetic Assets Mint synthetic tokens pegged to real-world assets via oracles Collateralization ratio, oracle risk
24 Prediction Market Binary outcome markets with AMM-based pricing Outcome tokens, resolution
25 Interest Rate Swaps Swap variable rate exposure for fixed rate and vice versa Fixed vs variable, swap accounting

Advanced Strategies

# Project Description Key Concepts
26 Flash Loan Arbitrage Atomic arbitrage across DEXs using Aave/Balancer flash loans Zero-capital trades, atomicity
27 Flash Liquidation Bot Liquidate under-collateralized positions using flash-borrowed funds MEV, priority gas auctions
28 MEV Sandwich Detector On-chain detection and protection against sandwich attacks Mempool, frontrunning, slippage
29 Cross-Chain Yield Optimizer Move capital across chains to chase the highest yields Bridge integration, chain comparison
30 Protocol-Owned Liquidity (POL) Treasury-managed liquidity inspired by OlympusDAO bonding Bonding curves, protocol treasury

Protocol Architecture Diagrams

Lending Protocol Flow

Depositor                    Lending Pool                    Borrower
    │                            │                              │
    ├── deposit(token, amt) ────►│                              │
    │◄── mint(aTokens) ─────────┤                              │
    │                            │◄── depositCollateral() ──────┤
    │                            │◄── borrow(token, amt) ───────┤
    │                            ├── transfer(token, amt) ──────►│
    │                            │                              │
    │                            │     [interest accrues...]    │
    │                            │                              │
    │                            │◄── repay(token, amt+interest)┤
    │◄── redeem(aTokens) ───────┤                              │
    │    receive(token + yield)  │                              │

AMM Swap Flow

Trader                       AMM Pool                     Liquidity Provider
   │                            │                              │
   │                            │◄── addLiquidity(A, B) ───────┤
   │                            ├── mint(LP tokens) ───────────►│
   │                            │                              │
   ├── swap(tokenA, amtIn) ────►│                              │
   │                            │  x * y = k (invariant)       │
   │                            │  amtOut = (y * amtIn) /      │
   │                            │           (x + amtIn)        │
   │◄── receive(tokenB, amtOut)─┤  fee accrues to LPs         │
   │                            │                              │
   │                            │◄── removeLiquidity(LP) ──────┤
   │                            ├── return(tokenA, tokenB) ────►│

Flash Loan Arbitrage Flow

Arbitrage Contract           Lending Pool          DEX A          DEX B
       │                         │                   │               │
       ├── flashLoan(token, amt)►│                   │               │
       │◄── transfer(token, amt)─┤                   │               │
       │                         │                   │               │
       ├── swap(token → tokenB) ─────────────────────►               │
       │◄── receive(tokenB) ─────────────────────────┤               │
       │                         │                   │               │
       ├── swap(tokenB → token) ─────────────────────────────────────►
       │◄── receive(token + profit)──────────────────────────────────┤
       │                         │                   │               │
       ├── repay(token + fee) ──►│                   │               │
       │   keep profit           │                   │               │

Repository Structure

defi-projects/
├── 01-erc20-token-factory/
│   ├── src/
│   │   └── TokenFactory.sol
│   ├── test/
│   │   ├── TokenFactory.t.sol
│   │   └── fuzz/
│   ├── script/
│   │   └── Deploy.s.sol
│   ├── foundry.toml
│   └── README.md
├── 02-token-vesting/
│   └── ...
├── ...
├── 26-flash-loan-arbitrage/
│   ├── src/
│   │   ├── FlashArbitrage.sol
│   │   └── interfaces/
│   ├── test/
│   │   └── FlashArbitrage.fork.t.sol   ← mainnet fork test
│   └── ...
├── lib/                    # Shared dependencies (forge install)
│   ├── forge-std/
│   ├── openzeppelin-contracts/
│   └── solmate/
├── interfaces/             # Common DeFi interfaces
│   ├── IUniswapV2Router.sol
│   ├── IAavePool.sol
│   ├── IChainlinkAggregator.sol
│   └── IERC3156FlashLender.sol
├── utils/                  # Shared math and helper libraries
│   ├── FixedPointMath.sol
│   ├── OracleLib.sol
│   └── SwapHelper.sol
└── README.md

Getting Started

Prerequisites

  • Foundry — Install via curl -L https://foundry.paradigm.xyz | bash && foundryup
  • Node.js >= 18.x (for Hardhat-based projects and frontends)
  • Git
  • An RPC provider account (Alchemy or Infura)

Quick Start

# Clone the repository
git clone https://github.com/pranay123-stack/defi-projects.git
cd defi-projects

# Navigate to a project
cd 11-constant-product-amm

# Install dependencies
forge install

# Build
forge build

# Run tests
forge test -vvv

Environment Setup

cp .env.example .env
# RPC Endpoints
MAINNET_RPC_URL=https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY
SEPOLIA_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY
ARBITRUM_RPC_URL=https://arb-mainnet.g.alchemy.com/v2/YOUR_KEY

# Deployment
PRIVATE_KEY=your_deployer_private_key
ETHERSCAN_API_KEY=your_etherscan_api_key

# Fork Testing
FORK_BLOCK_NUMBER=19000000

Never commit private keys. Use a dedicated deployer wallet with minimal funds on testnets.


Development Workflow

Foundry Commands

# Compile contracts
forge build

# Run all tests
forge test

# Run specific test file
forge test --match-path test/AMM.t.sol

# Run specific test function
forge test --match-test testSwapExactInput -vvvv

# Watch mode (re-run on file change)
forge test --watch

# Interactive Solidity REPL
chisel

Interacting with Deployed Contracts

# Read a public variable
cast call 0xContractAddress "totalSupply()" --rpc-url $SEPOLIA_RPC_URL

# Send a transaction
cast send 0xContractAddress "deposit(uint256)" 1000000 --rpc-url $SEPOLIA_RPC_URL --private-key $PRIVATE_KEY

# Decode calldata
cast 4byte-decode 0xa9059cbb...

# Get current gas price
cast gas-price --rpc-url $MAINNET_RPC_URL

Testing

Test Categories

Each project includes multiple levels of testing:

# Unit Tests — individual function behavior
forge test --match-path "test/unit/*"

# Integration Tests — multi-contract interactions
forge test --match-path "test/integration/*"

# Fuzz Tests — randomized inputs to find edge cases
forge test --match-path "test/fuzz/*"

# Invariant Tests — protocol-level invariants that must always hold
forge test --match-path "test/invariant/*"

# Fork Tests — test against live mainnet state
forge test --match-path "test/fork/*" --fork-url $MAINNET_RPC_URL

Example Invariants

// AMM: product of reserves must never decrease (minus fees)
function invariant_productNeverDecreases() public {
    uint256 product = pool.reserve0() * pool.reserve1();
    assertGe(product, lastProduct);
}

// Lending: total borrows must never exceed total deposits
function invariant_borrowsLtDeposits() public {
    assertLe(pool.totalBorrows(), pool.totalDeposits());
}

// Vault: share price must be monotonically non-decreasing
function invariant_sharePriceNonDecreasing() public {
    uint256 currentPrice = vault.convertToAssets(1e18);
    assertGe(currentPrice, lastSharePrice);
}

Mainnet Fork Testing

Fork testing is critical for DeFi — it lets you interact with real deployed contracts:

# Fork Ethereum mainnet at a specific block
forge test --fork-url $MAINNET_RPC_URL --fork-block-number 19000000 -vvv

# Example: test flash loan against live Aave V3
forge test --match-test testFlashLoanAaveV3 --fork-url $MAINNET_RPC_URL

Why fork testing matters:

  • Verify your contracts interact correctly with Uniswap, Aave, Compound, etc.
  • Test liquidation logic against real position data
  • Simulate arbitrage with actual on-chain liquidity
  • Pinning to a block number ensures reproducible tests

Gas Optimization

DeFi contracts are gas-sensitive. Techniques used across projects:

# Generate gas report
forge test --gas-report

# Snapshot gas usage
forge snapshot

# Compare gas changes
forge snapshot --diff

Optimization patterns applied:

  • immutable and constant for values set once
  • Packed storage slots (order struct fields by size)
  • unchecked blocks where overflow is mathematically impossible
  • calldata instead of memory for read-only function parameters
  • Minimal proxy (EIP-1167) clones for factory patterns
  • Custom errors instead of revert strings
  • Bitmap-based accounting for gas-efficient state tracking

Security

Common DeFi Attack Vectors Covered

Attack Mitigation Projects
Reentrancy CEI pattern, ReentrancyGuard All
Flash loan manipulation TWAP oracles, multi-block price checks 06-10, 26
Oracle manipulation Chainlink + fallback, staleness checks 06-10, 21-23
Sandwich attacks Slippage protection, deadline parameters 11-15
Price manipulation Time-weighted prices, liquidity depth checks 11-15, 21
Governance attacks Time-locks, quorum requirements, vote escrow 20
Rounding errors Round in protocol's favor, minimum amounts All
Donation attacks (ERC4626) Virtual shares/assets offset 04, 16-17

Audit Checklist

Each project README includes a security section covering:

  • Reentrancy protection on all external calls
  • Access control on privileged functions
  • Oracle freshness and fallback checks
  • Slippage and deadline protection
  • Integer overflow/underflow safety
  • Front-running resistance
  • Flash loan attack resistance
  • Proper event emissions for off-chain tracking

Disclaimer: These are educational implementations. Always get a professional audit before deploying with real funds.


Deployment

Deploy to Testnet

# Using Foundry
forge script script/Deploy.s.sol:DeployScript \
  --rpc-url $SEPOLIA_RPC_URL \
  --broadcast \
  --verify \
  --etherscan-api-key $ETHERSCAN_API_KEY

# Dry run first (simulation)
forge script script/Deploy.s.sol:DeployScript \
  --rpc-url $SEPOLIA_RPC_URL \
  --simulate

Supported Networks

Network Chain ID RPC Variable Explorer
Ethereum 1 MAINNET_RPC_URL etherscan.io
Sepolia 11155111 SEPOLIA_RPC_URL sepolia.etherscan.io
Arbitrum One 42161 ARBITRUM_RPC_URL arbiscan.io
Base 8453 BASE_RPC_URL basescan.org
Optimism 10 OPTIMISM_RPC_URL optimistic.etherscan.io
Polygon 137 POLYGON_RPC_URL polygonscan.com

Key DeFi Concepts

A quick reference for the financial and mathematical concepts used:

Concept Description
TVL Total Value Locked — sum of all assets deposited in a protocol
APR vs APY APR = simple rate; APY = compounded rate. APY = (1 + APR/n)^n - 1
Impermanent Loss Loss from providing liquidity vs. holding; occurs when prices diverge
Collateral Factor Max % of collateral value you can borrow (e.g., 75%)
Health Factor Collateral value / borrow value — liquidation triggers when < 1
Utilization Rate Borrowed / Total deposits — drives interest rate curves
Slippage Difference between expected and executed price in a swap
TWAP Time-Weighted Average Price — resistant to single-block manipulation
Flash Loan Uncollateralized loan that must be repaid within the same transaction
Liquidation Forced repayment of under-collateralized loan with bonus to liquidator
Bonding Curve Mathematical curve that determines price based on supply
Vote Escrow (ve) Lock tokens for governance power; longer lock = more weight

Resources

Protocol Documentation:

Development:

Security & Auditing:

Research & Learning:


Contributing

Contributions are welcome! Whether it's a new protocol implementation, a test improvement, or a bug fix:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/new-protocol)
  3. Follow the existing project structure
  4. Include comprehensive tests (unit + fuzz + invariant)
  5. Add a README.md with math explanations and security notes
  6. Submit a pull request

License

This repository is licensed under the MIT License.


DeFi is financial infrastructure as code. Build it. Break it. Understand it.

About

Comprehensive DeFi protocol implementations — AMMs, lending, yield vaults, flash loans, derivatives, and advanced strategies

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors