Skip to content
DeFi Deep Dive — AMMs, Lending, Yield Farming & Oracles

DeFi Deep Dive — AMMs, Lending, Yield Farming & Oracles

DodaTech Updated Jun 20, 2026 7 min read

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

Why DeFi Matters

DeFi has over $100 billion in total value locked (TVL). It offers financial services to anyone with an internet connection — no credit checks, no bank accounts, no identity verification. DodaTech’s security research team analyzes DeFi protocol vulnerabilities, applying findings to Durga Antivirus Pro’s smart contract scanning capabilities.

DeFi Architecture

    graph TD
    subgraph DeFi[<b>DeFi Protocol Layers</b>]
        Settlement[Settlement Layer<br/>Ethereum, L2s]
        Asset[Asset Layer<br/>ERC-20, ERC-721]
        Protocol[Protocol Layer<br/>AMM, Lending, Derivatives]
        Aggregator[Aggregator Layer<br/>1inch, Yearn]
        Application[Application Layer<br/>Frontend dApps]
    end

    subgraph KeyProtocols[<b>Key Protocols</b>]
        AMM[AMM<br/>Uniswap, Curve]
        Lending[Lending<br/>Aave, Compound]
        Yield[Yield<br/>Yearn, Convex]
        Oracle[Oracle<br/>Chainlink]
        Insurance[Insurance<br/>Nexus Mutual]
    end

    Settlement --> Asset
    Asset --> Protocol
    Protocol --> Aggregator
    Aggregator --> Application
    Protocol --> KeyProtocols

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

AMMs — Automated Market Makers

Uniswap pioneered the constant product AMM formula: x * y = k.

Uniswap v2 — Constant Product

# uniswap_v2_amm.py
def constant_product_amm(x_reserve, y_reserve, dx):
    """
    x * y = k: product of reserves stays constant.
    When dx tokens go in, dy tokens come out.
    """
    k = x_reserve * y_reserve
    x_new = x_reserve + dx
    y_new = k / x_new
    dy = y_reserve - y_new

    spot_price = y_reserve / x_reserve
    execution_price = dx / dy
    price_impact = (execution_price / spot_price - 1) * 100

    return {
        "input": dx,
        "output": round(dy, 6),
        "execution_price": round(execution_price, 4),
        "price_impact_pct": round(price_impact, 2),
        "new_k": x_new * y_new
    }

pool = {"ETH": 1000, "USDC": 3_000_000}
print(f"Pool: {pool['ETH']} ETH / ${pool['USDC']:,} USDC")
print(f"Spot price: ${pool['USDC']/pool['ETH']:.2f}/ETH\n")

for trade_eth in [1, 10, 100, 300]:
    usdc_in = trade_eth * 3000
    result = constant_product_amm(pool['USDC'], pool['ETH'], usdc_in)
    print(f"Buy {trade_eth} ETH (${usdc_in:,} USDC):")
    print(f"  Output: {result['output']:.4f} ETH")
    print(f"  Price impact: {result['price_impact_pct']}%\n")

Expected output:

Pool: 1000 ETH / $3,000,000 USDC
Spot price: $3000.00/ETH

Buy 1 ETH ($3,000 USDC):
  Output: 0.9990 ETH
  Price impact: 0.1%

Buy 10 ETH ($30,000 USDC):
  Output: 9.9009 ETH
  Price impact: 1.0%

Buy 100 ETH ($300,000 USDC):
  Output: 90.0909 ETH
  Price impact: 10.0%

Buy 300 ETH ($900,000 USDC):
  Output: 230.7692 ETH
  Price impact: 30.0%

Uniswap v3 — Concentrated Liquidity

Uniswap v3 lets LPs concentrate capital within a custom price range, earning higher fees but taking on more risk.

// Uniswap v3 concentrated liquidity position (conceptual)
struct Position {
    uint128 liquidity;  // Liquidity provided
    int24 tickLower;    // Lower price bound
    int24 tickUpper;    // Upper price bound
    uint256 feeGrowthInside;
}

// LP deposits only in range [$2,800, $3,200]
// Capital efficiency: up to 4000x compared to v2

Lending & Borrowing — Aave & Compound

Lending protocols let users deposit assets to earn interest and borrow by over-collateralizing.

// aave_lending_analysis.js
const { ethers } = require("ethers");

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

    const AAVE_POOL = "0x7d2768dE32b0b80b7a3454c06BdAc94a69DDc7A9";
    const poolABI = ["function getUserAccountData(address) view returns (uint256,uint256,uint256,uint256,uint256,uint256)"];

    const pool = new ethers.Contract(AAVE_POOL, poolABI, provider);

    const user = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"; // vitalik.eth
    const data = await pool.getUserAccountData(user);

    const totalCollateral = ethers.utils.formatEther(data.totalCollateralETH);
    const totalDebt = ethers.utils.formatEther(data.totalDebtETH);
    const healthFactor = data.healthFactor.toString();

    console.log("=== Aave Position Analysis ===");
    console.log(`Total Collateral: ${totalCollateral} ETH`);
    console.log(`Total Debt: ${totalDebt} ETH`);
    console.log(`Health Factor: ${healthFactor}`);

    if (parseFloat(healthFactor) > 2.0) {
        console.log("Status: SAFE — Health factor above 2.0");
    } else if (parseFloat(healthFactor) > 1.0) {
        console.log("Status: WARNING — Liquidation risk if price drops");
    } else {
        console.log("Status: LIQUIDATION IMMINENT");
    }
}

analyzeAavePosition();

Expected output:

=== Aave Position Analysis ===
Total Collateral: 1234.5 ETH
Total Debt: 100.0 ETH
Health Factor: 18446744073709551616
Status: SAFE — Health factor above 2.0

Interest Rate Model

Aave and Compound use utilization-based interest rates:

Utilization Rate = Total Borrowed / Total Deposited

When utilization < 80%: Low rates (1-5% APY)
When utilization > 80%: Rates spike (10-50%+ APY)
When utilization = 100%: Max rate (can't borrow more)

Yield Farming — Maximizing Returns

Yield farming moves assets between protocols to chase the highest returns.

# yield_farm_calculator.py
def analyze_yield_farm(protocol, apy, tvl, audit_score, team_doxxed):
    """
    Evaluate a yield farming opportunity.
    audit_score: 1 (unaudited) to 10 (multiple top audits)
    """
    risk_score = 10 - audit_score
    if not team_doxxed:
        risk_score += 3
    if tvl < 1_000_000:
        risk_score += 2

    risk_adjusted_apy = apy / risk_score if risk_score > 0 else apy

    print(f"\n{'='*50}")
    print(f"Yield Farm: {protocol}")
    print(f"{'='*50}")
    print(f"APY: {apy:.1f}%")
    print(f"TVL: ${tvl:,.0f}")
    print(f"Audit score: {audit_score}/10")
    print(f"Team doxxed: {team_doxxed}")
    print(f"Risk score: {risk_score}/15")
    print(f"Risk-adjusted APY: {risk_adjusted_apy:.1f}%")

    if risk_score >= 10:
        print("VERDICT: AVOID — Extremely high risk")
    elif risk_score >= 7:
        print("VERDICT: SPECULATIVE — Small position only")
    elif risk_score >= 4:
        print("VERDICT: MODERATE — Consider with caution")
    else:
        print("VERDICT: SAFE — Acceptable risk-reward")

analyze_yield_farm("Aave USDC", 4.5, 8_500_000_000, 9, True)
analyze_yield_farm("ShitFarm Token", 850, 150_000, 1, False)
analyze_yield_farm("Curve stETH", 6.2, 2_100_000_000, 8, True)

Expected output:

==================================================
Yield Farm: Aave USDC
==================================================
APY: 4.5%
TVL: $8,500,000,000
Audit score: 9/10
Team doxxed: True
Risk score: 1/15
Risk-adjusted APY: 4.5%
VERDICT: SAFE — Acceptable risk-reward

==================================================
Yield Farm: ShitFarm Token
==================================================
APY: 850.0%
TVL: $150,000
Audit score: 1/10
Team doxxed: False
Risk score: 12/15
Risk-adjusted APY: 70.8%
VERDICT: AVOID — Extremely high risk

Impermanent Loss — The LP’s Hidden Tax

Impermanent loss happens when token prices diverge from your deposit ratio. The wider the divergence, the larger the loss.

Price ChangeIL vs HODL
±25%~1% loss
±50%~6% loss
±75%~13% loss
±90%~23% loss
±99%~45% loss

Formula: IL = 2 * sqrt(price_ratio) / (1 + price_ratio) - 1

Oracles — Chainlink

Oracles bring real-world data (prices, weather, scores) on-chain. Chainlink is the dominant oracle network.

// Using Chainlink price feed
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceConsumer {
    AggregatorV3Interface internal priceFeed;

    constructor() {
        // ETH/USD price feed on Ethereum mainnet
        priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
    }

    function getLatestPrice() public view returns (int256) {
        (, int256 price, , , ) = priceFeed.latestRoundData();
        return price; // Returns price with 8 decimals (e.g., 300000000000 = $3000.00)
    }

    function getFormattedPrice() public view returns (string memory) {
        int256 price = getLatestPrice();
        uint256 formatted = uint256(price) / 10**8;
        // Returns "$3000" for current ETH price
        return string(abi.encodePacked("$", uintToString(formatted)));
    }
}

DeFi Insurance — Nexus Mutual

DeFi insurance protects against smart contract failures, hacks, and stablecoin de-pegs. Nexus Mutual is a mutual insurance pool.

Cover types: Smart contract risk (covers hacks), Custody risk (covers exchange failures), Yield token risk (covers de-pegs).

Common Mistakes

  1. Not understanding impermanent loss: Providing liquidity without knowing how price divergence affects returns can lead to net losses even with fee income.
  2. Borrowing at max LTV: The tiniest price dip triggers liquidation with a 5-13% penalty. Keep health factor above 2.0.
  3. Farming unaudited protocols: High APY is a warning sign, not an opportunity. If a top firm hasn’t audited the contract, it’s gambling.
  4. Ignoring oracle risk: If a price oracle is manipulated (flash loan attacks), your position can be liquidated unfairly.
  5. Not revoking token approvals: Approvals persist until revoked. A compromised contract can drain your tokens years later.
  6. Chasing yields without considering TVL trends: Declining TVL means LPs are exiting — often a leading indicator of trouble.

Practice Questions

  1. How does Uniswap’s constant product formula determine token output?
  2. What is a health factor and when does liquidation occur?
  3. Why is impermanent loss called “impermanent”?
  4. What role do oracles play in DeFi lending?
  5. How does concentrated liquidity in Uniswap v3 differ from v2?

Answers:

  1. x * y = k — The product of reserves is constant. When you add x tokens (dx), the pool calculates new y reserves: y_new = k / (x + dx). Output = y - y_new.
  2. Health factor = collateral_value / (borrowed_value * liquidation_threshold). Below 1.0, liquidators seize collateral.
  3. If prices return to the original ratio, the loss disappears. It’s only permanent if you withdraw during divergence.
  4. Oracles provide real-time asset prices used to calculate collateral value, health factors, and liquidation thresholds. Manipulated oracles can drain lending pools.
  5. v2 distributes liquidity across 0 to ∞. v3 concentrates in custom ranges. Capital efficiency up to 4000x but positions can go 100% out of range.

Challenge: Calculate impermanent loss for a 50/50 ETH/USDC LP position when ETH price doubles. Use the formula IL = 2*sqrt(r)/(1+r) - 1 where r is the price ratio.

FAQ

What is TVL in DeFi?
Total Value Locked — the total value of assets deposited in a protocol. Higher TVL indicates more trust and liquidity. Always check TVL trends.
How do flash loan attacks work?
Flash loans let you borrow millions without collateral as long as you repay in the same transaction. Attackers use them to manipulate oracle prices, draining lending pools.
Is DeFi safe?
DeFi carries smart contract risk, oracle risk, liquidation risk, and regulatory risk. Never invest more than you can afford to lose. Use audited protocols with proven track records.
What is the best DeFi strategy for beginners?
Start by depositing stablecoins (USDC, DAI) on Aave for 3-5% APY. Understand the mechanics before attempting yield farming or liquidity provision.

What’s Next

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro