defi protocols

DeFi protocols deep dive โ€” Uniswap AMM math, Aave lending, and Compound

๐Ÿ“˜ defi-academy · Part 7 of 15 · Module 3 · Protocols
A free, step-by-step course on buying, selling & trading domains. View the full series →
DeFi protocols deep dive โ€” Uniswap AMM math, Aave lending, and Compound
Key takeaways
  • Uniswap uses x*y=k to price trades from liquidity pools โ€” larger trades cause more slippage.
  • Aave lending is pooled and over-collateralized โ€” interest rates adjust algorithmically based on pool utilization.
  • Flash loans let you borrow any amount with zero collateral โ€” repay in the same transaction or everything reverts.

DeFi protocols are not black boxes โ€” they are open-source smart contracts whose logic you can read, verify, and interact with directly. Understanding how Uniswap prices trades, how Aave calculates interest, and how Compound manages collateral is essential for building on or safely using DeFi.

This lesson dissects the three most important DeFi protocol categories with math, code, and practical demos.

Defi Protocols: Uniswap: the constant product AMM

Uniswap uses the constant product formula: x * y = k, where x and y are token reserves and k is a constant.

๐Ÿ”ฌ Demo: AMM swap math step by step
Pool: 100 ETH + 200,000 USDC
k = 100 * 200,000 = 20,000,000

You buy ETH with 1,000 USDC:
  New USDC in pool: 200,000 + 1,000 = 201,000
  New ETH in pool: 20,000,000 / 201,000 = 99.5025
  ETH you receive: 100 - 99.5025 = 0.4975 ETH

  0.3% fee applied first, so actual input = 997 USDC
  New ETH in pool: 20,000,000 / 200,997 = 99.5040
  You get: 0.4960 ETH
  Effective price: $2,016 per ETH (market was $2,000)
  Slippage: 0.8%
// Simplified Uniswap V2 swap logic
function getAmountOut(
    uint amountIn,
    uint reserveIn,
    uint reserveOut
) public pure returns (uint amountOut) {
    uint amountInWithFee = amountIn * 997; // 0.3% fee
    uint numerator = amountInWithFee * reserveOut;
    uint denominator = (reserveIn * 1000) + amountInWithFee;
    amountOut = numerator / denominator;
}
// Get a real swap quote from Uniswap V2 Router
const router = new ethers.Contract(ROUTER_ADDRESS, routerAbi, provider);
const amountsOut = await router.getAmountsOut(
  ethers.parseEther('1.0'), // 1 ETH in
  [WETH_ADDRESS, USDC_ADDRESS]
);
console.log('1 ETH =', ethers.formatUnits(amountsOut[1], 6), 'USDC');

Aave: lending and borrowing

Aave is a pooled lending protocol. Depositors earn interest; borrowers pay it. Rates adjust algorithmically based on pool utilization:

๐Ÿ”ฌ Demo: Aave interaction with ethers.js
// Read Aave V3 market data
const poolAddress = '0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2'; // Aave V3 Pool
const poolAbi = [
  'function getReserveData(address asset) view returns (tuple(uint256 configuration, uint128 liquidityIndex, uint128 currentLiquidityRate, uint128 variableBorrowIndex, uint128 currentVariableBorrowRate, uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, uint16 id, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress, uint128 accruedToTreasury, uint128 unbacked, uint128 isolationModeTotalDebt))'
];

const pool = new ethers.Contract(poolAddress, poolAbi, provider);
const data = await pool.getReserveData(USDC_ADDRESS);

// currentLiquidityRate is in RAY (27 decimals), convert to APY
const supplyRateRay = data.currentLiquidityRate;
const supplyAPY = (Number(supplyRateRay) / 1e27) * 100;
console.log('USDC Supply APY:', supplyAPY.toFixed(2), '%');

Health factor = (collateral value x liquidation threshold) / total debt. Below 1.0 triggers liquidation.

Deposit: 5 ETH at $2,000 = $10,000 collateral
Borrow: $6,000 USDC
Liquidation threshold: 82.5%

Health Factor = ($10,000 x 0.825) / $6,000 = 1.375 (safe)

Liquidation price for ETH:
  (5 x ETH_price x 0.825) / 6,000 = 1.0
  ETH_price = 6,000 / (5 x 0.825) = $1,454.55

Compound: interest rate curves

Compound uses a kinked interest rate model โ€” rates increase slowly up to an optimal utilization point, then spike sharply:

๐Ÿ”ฌ Demo: Compound interest rate model
// Simplified Compound-style interest rate model
contract InterestRateModel {
    uint256 public baseRate = 2e16;        // 2% base
    uint256 public multiplier = 10e16;     // 10% slope before kink
    uint256 public jumpMultiplier = 200e16; // 200% slope after kink
    uint256 public kink = 80e16;           // 80% utilization

    function getSupplyRate(
        uint256 cash,        // available liquidity
        uint256 borrows,     // total borrowed
        uint256 reserves     // protocol reserves
    ) public view returns (uint256) {
        uint256 utilization = borrows * 1e18 / (cash + borrows - reserves);
        uint256 borrowRate;

        if (utilization <= kink) {
            borrowRate = baseRate + (utilization * multiplier / 1e18);
        } else {
            uint256 normalRate = baseRate + (kink * multiplier / 1e18);
            uint256 excess = utilization - kink;
            borrowRate = normalRate + (excess * jumpMultiplier / 1e18);
        }

        // Supply rate = borrow rate * utilization * (1 - reserve factor)
        return borrowRate * utilization / 1e18 * 90 / 100;
    }
}

The kink creates urgency: when utilization exceeds 80%, borrow rates spike dramatically to attract depositors and discourage excess borrowing. This self-regulating mechanism keeps pools solvent.

Explore Crypto Trading

Cryptocurrency trading is one of the fastest-growing financial markets โ€” open 24/7, globally accessible, and full of opportunity for those who learn the fundamentals first.

  • Trade spot, futures & copy-trading on one platform
  • Start with as little as $10 โ€” practice risk-free on the testnet
  • Built-in TradingView charts, grid bots & DCA tools

Free Crypto Trading Academy → ยท Domain Trading Academy →

Flash loans: borrow millions with zero collateral

Flash loans let you borrow any amount with no collateral, as long as you repay in the same transaction:

๐Ÿ”ฌ Demo: Flash loan execution flow
// Aave V3 flash loan receiver
import "@aave/v3-core/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol";

contract MyFlashLoan is FlashLoanSimpleReceiverBase {
    constructor(address poolProvider)
        FlashLoanSimpleReceiverBase(IPoolAddressesProvider(poolProvider))
    {}

    function executeOperation(
        address asset,
        uint256 amount,
        uint256 premium, // flash loan fee (~0.05%)
        address initiator,
        bytes calldata params
    ) external override returns (bool) {
        // You now have `amount` of `asset` in this contract
        // Do something profitable: arbitrage, liquidation, collateral swap

        // Example: buy low on DEX A, sell high on DEX B
        // uint256 profit = arbitrage(asset, amount);

        // Repay loan + fee
        uint256 amountOwed = amount + premium;
        IERC20(asset).approve(address(POOL), amountOwed);
        return true;
        // If you cannot repay, the ENTIRE transaction reverts
    }

    function requestFlashLoan(address asset, uint256 amount) external {
        POOL.flashLoanSimple(address(this), asset, amount, "", 0);
    }
}

Flash loans are unique to DeFi โ€” impossible in traditional finance. They enable trustless arbitrage, instant collateral swaps, and efficient liquidations.

When evaluating defi protocols, start with the fundamentals: what problem it solves, who it serves, and how it compares to the alternatives buyers consider first.

Start with the fundamentals. Define who you are serving, the single outcome you want, and the budget you are comfortable committing before you compare any options.

A practical rule is to favour clarity over cleverness. The choice that is easiest to understand, spell, remember and act on tends to win over the long run.

Context changes the answer. What is optimal for a fast-moving startup is rarely optimal for an established brand, so weigh your own stage, market and ambitions.

Avoid the common mistakes: rushing the decision, copying competitors blindly, and ignoring the total cost of ownership beyond the very first year of use.

Think in terms of trade-offs rather than a single perfect answer. Every option trades memorability, cost, reach and flexibility in a slightly different mix.

Document your reasoning. Writing down why you chose one path makes it far easier to revisit the decision later and to explain it to partners and investors.

Test with real people. A quick check with a handful of your actual customers will surface problems that no amount of internal debate ever reveals.

WSOT 2026: Squad Leader Slots Are Open โ€” Up to $128,000 per Leader

Join Now

Frequently asked questions

How does Uniswap V3 differ from V2?

V3 introduces concentrated liquidity โ€” LPs choose specific price ranges instead of providing liquidity across the entire curve. This dramatically improves capital efficiency but adds complexity. A narrow range earns more fees per dollar but goes out of range if the price moves significantly.

What happens during an Aave liquidation?

When your health factor drops below 1.0, a liquidator repays up to 50% of your debt and receives your collateral at a 5-10% discount. You keep the borrowed amount but lose a chunk of collateral. Maintain a health factor above 1.5 for safety.

Free Courses โ€” Learn New Skills

No sign-up · No fees · Learn at your own pace

Start Trading

Trade crypto and premium domains โ€” digital assets with real opportunities.

Find your name on Atom

DominantBrand curates the best premium, brandable names from Atom.com — the marketplace with a free AI appraisal, a USPTO trademark check, and secure escrow. Every listing even ships with a designed logo.

Browse Domains