Skip to content
DeFi (Decentralized Finance) — Explained with Examples

DeFi (Decentralized Finance) — Explained with Examples

DodaTech Updated Jun 15, 2026 8 min read

DeFi (Decentralized Finance) is a blockchain-based financial ecosystem that replaces traditional intermediaries like banks, brokers, and exchanges with smart contracts, enabling permissionless lending, borrowing, trading, and earning interest on cryptocurrency.

Why DeFi Matters

DeFi has grown from $1 billion to over $100 billion in total value locked (TVL). It offers financial services to anyone with an internet connection — no credit check, no bank account, no identity verification. DodaTech monitors DeFi protocols for blockchain security research, understanding smart contract vulnerabilities that inform Durga Antivirus Pro’s threat detection. DeFi represents the most practical application of smart contracts today.

How DeFi Works — The Big Picture

Think of DeFi like a financial theme park. Instead of one bank that does everything, there are specialized attractions. The lending pool is like a community savings fund. The exchange is like a currency booth where prices adjust automatically. The yield farm is like growing crops — you deposit seeds and harvest rewards.

    graph TD
    subgraph DeFi[<b>DeFi Ecosystem</b>]
        Lending[Lending/Borrowing<br/>Aave, Compound]
        DEX[Decentralized Exchange<br/>Uniswap, Curve]
        Yield[Yield Farming<br/>Yearn, Convex]
        Stable[Stablecoins<br/>DAI, USDC]
        Deriv[Derivatives<br/>Synthetix]
    end
    User[User with Wallet] --> Lending
    User --> DEX
    User --> Yield
    User --> Stable
    User --> Deriv

    Lending --> |Deposit| AP[Earn Interest APY]
    Lending --> |Collateral| BL[Take out loan]
    DEX --> |Swap tokens| LP[Provide liquidity]
    DEX --> |Earn fees| LP
    Yield --> |Deposit LP tokens| Farm[Earn yield tokens]
    Yield --> |Harvest| Farm

    style DeFi fill:#3b82f6,color:#fff
  

Lending and Borrowing — Aave and Compound

Aave and Compound are the largest lending protocols. Users deposit assets to earn interest. Borrowers put up collateral (over-collateralized) to take loans.

// Simplified Aave-style lending pool (Solidity)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract SimpleLendingPool {
    mapping(address => mapping(address => uint256)) public deposits;
    mapping(address => uint256) public totalLiquidity;
    mapping(address => uint256) public borrowRate;

    // Deposit asset to earn interest
    function deposit(address asset, uint256 amount) external {
        IERC20(asset).transferFrom(msg.sender, address(this), amount);
        deposits[msg.sender][asset] += amount;
        totalLiquidity[asset] += amount;
        emit Deposited(msg.sender, asset, amount);
    }

    // Borrow requires 150% over-collateralization
    function borrow(address asset, uint256 amount) external {
        uint256 collateralValue = getCollateralValue(msg.sender);
        require(collateralValue >= amount * 150 / 100, "Insufficient collateral");

        IERC20(asset).transfer(msg.sender, amount);
        emit Borrowed(msg.sender, asset, amount);
    }

    event Deposited(address indexed user, address indexed asset, uint256 amount);
    event Borrowed(address indexed user, address indexed asset, uint256 amount);
}
// Interacting with Aave from ethers.js
const { ethers } = require("ethers");

const AAVE_LENDING_POOL = "0x7d2768dE32b0b80b7a3454c06BdAc94a69DDc7A9";
const DAI_ADDRESS = "0x6B175474E89094C44Da98b954EedeAC495271d0F";

async function interactWithAave() {
  const provider = new ethers.providers.JsonRpcProvider("https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY");
  const signer = provider.getSigner();

  const lendingPool = new ethers.Contract(AAVE_LENDING_POOL, LENDING_POOL_ABI, signer);

  // Check your deposit balance
  const userData = await lendingPool.getUserAccountData(signer.address);
  console.log("Total collateral (ETH):", ethers.utils.formatEther(userData.totalCollateralETH));
  console.log("Total debt (ETH):", ethers.utils.formatEther(userData.totalDebtETH));
  console.log("Health factor:", userData.healthFactor.toString());

  // Deposit 100 DAI
  const dai = new ethers.Contract(DAI_ADDRESS, ERC20_ABI, signer);
  const amount = ethers.utils.parseUnits("100", 18);
  await dai.approve(AAVE_LENDING_POOL, amount);
  const tx = await lendingPool.deposit(DAI_ADDRESS, amount, signer.address, 0);
  await tx.wait();
  console.log("Deposited 100 DAI to Aave");
}

interactWithAave();

Expected output:

Total collateral (ETH): 0.5
Total debt (ETH): 0.0
Health factor: 18446744073709551616
Deposited 100 DAI to Aave

Health Factor

The health factor determines if a position can be liquidated. Below 1.0 means your collateral can be seized.

Health FactorStatusRisk
> 2.0SafeLow liquidation risk
1.1 - 2.0ModeratePrice drop could trigger liquidation
1.0ThresholdCollateral exactly equals loan value
< 1.0UnderwaterLiquidation imminent

DEX — Decentralized Exchange (Uniswap)

Uniswap uses an automated market maker (AMM) model instead of traditional order books. Trades happen against liquidity pools using a constant product formula: x * y = k.

# uniswap_amm_simulator.py
def constant_product_amm(x_reserve, y_reserve, x_input):
    """
    Calculate output amount using Uniswap's constant product formula.
    x * y = k (constant)
    """

    k = x_reserve * y_reserve
    x_new = x_reserve + x_input
    y_new = k / x_new
    y_output = y_reserve - y_new

    # Price impact — larger trades move the price more
    price_impact = (x_input / x_reserve) * 100

    return {
        "input_amount": x_input,
        "output_amount": y_output,
        "price_impact_percent": round(price_impact, 2),
        "effective_price": x_input / y_output
    }

# Simulate a swap: buying ETH with USDC
pool = {
    "eth_reserve": 1000,    # 1000 ETH in pool
    "usdc_reserve": 3000000  # 3M USDC in pool
}

print("=== Uniswap AMM Simulation ===")
print(f"Pool: {pool['eth_reserve']} ETH / ${pool['usdc_reserve']:,} USDC")
print(f"Spot price: ${pool['usdc_reserve'] / pool['eth_reserve']:.2f} per ETH\n")

trades = [1, 10, 100, 500]
for trade in trades:
    result = constant_product_amm(pool['usdc_reserve'], pool['eth_reserve'], trade * 3000)
    print(f"Swap ${trade * 3000:,} USDC for ETH:")
    print(f"  Get: {result['output_amount']:.4f} ETH")
    print(f"  Price impact: {result['price_impact_percent']}%")
    print(f"  Effective price: ${result['effective_price']:.2f}/ETH\n")

Expected output:

=== Uniswap AMM Simulation ===
Pool: 1000 ETH / $3,000,000 USDC
Spot price: $3,000.00 per ETH

Swap $3,000 USDC for ETH:
  Get: 0.9990 ETH
  Price impact: 0.1%
  Effective price: $3,003.00/ETH

Swap $30,000 USDC for ETH:
  Get: 9.90 ETH
  Price impact: 1.0%
  Effective price: $3,030.30/ETH

Swap $300,000 USDC for ETH:
  Get: 90.91 ETH
  Price impact: 10.0%
  Effective price: $3,300.00/ETH

Swap $1,500,000 USDC for ETH:
  Get: 333.33 ETH
  Price impact: 50.0%
  Effective price: $4,500.00/ETH

Liquidity Pools — Providing Liquidity for Fees

Liquidity providers (LPs) deposit pairs of tokens into a pool and earn trading fees. Think of it as renting out a currency exchange booth.

// Simplified Uniswap V2-style pair
contract SimpleLiquidityPool {
    uint256 public reserve0;
    uint256 public reserve1;

    function addLiquidity(uint256 amount0, uint256 amount1) external {
        require(amount0 > 0 && amount1 > 0, "Amount must be > 0");
        reserve0 += amount0;
        reserve1 += amount1;
        // Mint LP tokens (simplified)
        _mint(msg.sender, amount0 + amount1);
    }

    function removeLiquidity(uint256 lpTokens) external {
        uint256 amount0 = lpTokens * reserve0 / totalSupply;
        uint256 amount1 = lpTokens * reserve1 / totalSupply;
        reserve0 -= amount0;
        reserve1 -= amount1;
        _burn(msg.sender, lpTokens);
        transferTokens(msg.sender, amount0, amount1);
    }

    function swap(uint256 amountIn, address tokenIn) external returns (uint256) {
        (uint256 r0, uint256 r1) = tokenIn == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
        uint256 amountOut = getAmountOut(amountIn, r0, r1);
        reserve0 = tokenIn == token0 ? r0 + amountIn : r0 - amountOut;
        reserve1 = tokenIn == token1 ? r1 + amountIn : r1 - amountOut;
        transferTokens(msg.sender, amountOut);
        return amountOut;
    }
}

Impermanent Loss: If token prices diverge significantly from when you deposited, you may have been better off holding the tokens outside the pool. This is the main risk for LPs.

Yield Farming — Maximizing Returns

Yield farming is the practice of moving assets between protocols to earn the highest returns, often involving multiple steps.

# yield_farming_analyzer.py
def analyze_yield_farm(protocol, apy, tvl, risk_score):
    """
    Evaluate a yield farming opportunity.
    risk_score: 1 (lowest risk) to 10 (highest)
    """

    risk_adjusted_return = apy / risk_score
    impermanent_loss_risk = "High" if risk_score > 7 else "Moderate" if risk_score > 4 else "Low"

    print(f"=== Yield Farm Analysis ===")
    print(f"Protocol: {protocol}")
    print(f"APY: {apy:.1f}%")
    print(f"TVL: ${tvl:,.0f}")
    print(f"Risk score: {risk_score}/10")
    print(f"Risk-adjusted return: {risk_adjusted_return:.1f}")
    print(f"Impermanent loss risk: {impermanent_loss_risk}")

    if risk_score >= 8:
        print("WARNING: High risk! Audited? Team doxxed? TVL trending up?")
    if tvl < 100000:
        print("WARNING: Low TVL — potential rug pull or manipulation risk")

    print(f"\nRecommendation:", end=" ")
    if risk_adjusted_return > 5 and tvl > 1000000:
        print("Consider allocating (moderate position)")
    elif risk_adjusted_return > 2:
        print("Small position only (1-2% of portfolio)")
    else:
        print("Avoid — risk-adjusted return too low")

analyze_yield_farm("Aave USDC", 4.5, 8500000000, 2)
analyze_yield_farm("NewFarmToken-WETH Farm", 450, 250000, 9)

Expected output:

=== Yield Farm Analysis ===
Protocol: Aave USDC
APY: 4.5%
TVL: $8,500,000,000
Risk score: 2/10
Risk-adjusted return: 2.2
Impermanent loss risk: Low

Recommendation: Consider allocating (moderate position)

=== Yield Farm Analysis ===
Protocol: NewFarmToken-WETH Farm
APY: 450.0%
TVL: $250,000
Risk score: 9/10
Risk-adjusted return: 50.0
Impermanent loss risk: High
WARNING: High risk! Audited? Team doxxed? TVL trending up?
WARNING: Low TVL — potential rug pull or manipulation risk

Recommendation: Avoid — risk-adjusted return too low

Smart Contract Risks

Flash Loans

Flash loans let you borrow millions instantly with no collateral, as long as you repay in the same transaction. They’re used for arbitrage but also for attacks.

Notable DeFi hacks:

  • Poly Network ($610M, 2021): Exploited cross-chain contract logic
  • Wormhole ($325M, 2022): Signature verification bypass
  • Ronin ($620M, 2022): Private key compromise of validation nodes
  • Various flash loan attacks: Oracle manipulation leading to price manipulation

Rug Pulls

A rug pull is when developers abandon a project after taking user funds. Warning signs include anonymous teams, unaudited code, and suspiciously high yields.

Common Mistakes

  1. Not understanding impermanent loss: Providing liquidity without knowing how price divergence affects returns can lead to losses even with fee income.
  2. Ignoring gas costs on Ethereum: Frequent transactions, especially during high gas, can eat all profits. Use Layer 2s or optimize timing.
  3. Farming unaudited protocols: High APY is usually a warning, not an opportunity. If the contract hasn’t been audited by a top firm, it’s gambling.
  4. Borrowing at max loan-to-value: The tiniest price dip triggers liquidation + 5-13% penalty. Keep health factor above 2.0.
  5. Not revoking token approvals: If you approve a contract to spend your tokens, it can drain them even after you stop using the protocol. Use revoke.cash.

Practice Questions

  1. What is the constant product formula used by Uniswap?
  2. What is over-collateralization in DeFi lending?
  3. What is impermanent loss?
  4. How does a flash loan work?
  5. What is total value locked (TVL)?

Answers:

  1. x * y = k — the product of token reserves remains constant during swaps. This determines the output amount and price.
  2. Borrowers must deposit more collateral than the loan value (typically 150%). Essential for uncollateralized lending in a trustless system.
  3. When token prices diverge from your deposit ratio, you would have been better off holding. The lost potential profit is “impermanent” if prices return to the original ratio.
  4. A flash loan lets you borrow any amount with no collateral, provided you repay within the same transaction. If you can’t repay, the entire transaction reverts.
  5. TVL is the total value of assets deposited in a DeFi protocol. Higher TVL indicates more trust and liquidity. Always check TVL trends before participating.

Mini Project: DeFi Portfolio Tracker

Build a simple Python script that:

  1. Connects to Ethereum via an RPC provider (Infura/Alchemy)
  2. Fetches your wallet’s deposits on Aave or Compound
  3. Calculates your current APY earnings
  4. Checks your health factor on lending protocols
  5. Estimates impermanent loss on any Uniswap LP positions
  6. Generates a risk report for each position

This is similar to how DodaTech’s research team monitors DeFi positions for security analysis and vulnerability research.

Related topics: Ethereum, Smart Contracts, Layer 2, NFTs, Web3

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro