
DeFi Deep Dive — Part 1: How Decentralised Finance Protocols Actually Work
How DeFi protocols actually work — AMMs, lending, oracles, and yield farming explained from first principles for serious crypto users.
This article was produced with AI assistance and reviewed for accuracy.
Content is for informational purposes only and does not constitute financial advice.
DeFi TVL Peak
Total value locked in DeFi peaked at $180 billion in November 2021 before collapsing to $40 billion in 2022
Uniswap Launch
November 2018 — Uniswap v1 launched, introducing the automated market maker model to DeFi
MakerDAO Age
MakerDAO was founded in 2014 — the oldest DeFi protocol and creator of the DAI stablecoin
Compound Launch
2018 — Compound pioneered algorithmic money markets, allowing permissionless lending and borrowing
Aave TVL
Aave reached over $20 billion TVL at peak — the largest decentralised lending protocol by assets
Flash Loans
Aave introduced flash loans in 2020 — uncollateralised loans that must be borrowed and repaid in a single transaction
DeFi Deep Dive — Part 1: How Decentralised Finance Protocols Actually Work
Decentralised finance (DeFi) rewires core financial services into open-source code that settles on public blockchains. This entry breaks down the moving parts — exchanges, lending, oracles, and yield incentives — so you can understand how the pieces click together and where the risks hide.
1. What DeFi Actually Is
DeFi is a set of financial services run by smart contracts on public blockchains. Users keep control of funds through private keys, and rules are enforced by code rather than a central operator.
That ideal exists on a spectrum. Many protocols can upgrade contracts, pause markets, or adjust parameters via admin keys or DAO governance. Some rely on official front-ends, foundation-run oracles, or multisig-controlled treasuries.
This spectrum matters. A protocol might be fully automated on-chain yet depend on off-chain processes for governance, audits, or legal stewardship. Assessing where a system sits means looking at who can upgrade contracts, how timelocks work, and whether key holders are publicly known.
DeFi differs from centralised finance (CeFi), where a company custodies user assets and runs an internal ledger. On exchanges like Coinbase Advanced or Binance, deposits are pooled, trades are matched off-chain, and withdrawals are processed by the operator. You trust the firm’s solvency and controls.
In DeFi, settlement happens on-chain. Contracts validate collateral, calculate interest, and release funds based on deterministic logic. Disputes are resolved by the network’s consensus, not a support ticket.
Why does DeFi tend to live on Ethereum-style platforms? Because you need general-purpose smart contracts that can store state, perform arithmetic, and call other contracts. For background on these building blocks, see Smart Contracts Explained.
“Composability — the ability for one contract to call another as a building block — is DeFi’s killer feature. Liquidity, credit, and price data can be permissionlessly stitched together into new products.”
This composability produces emergent behaviours. A lending protocol can accept LP tokens from an exchange as collateral. A new app can route orders through an aggregator, then deposit proceeds into a vault, all in one transaction.
Critical insight
Power in DeFi comes from code that other code can trust. When contracts are open, auditable, and callable, the cost to launch new financial primitives drops sharply — but so does the margin for error.
For a primer on concepts and history, refer to DeFi Explained.
2. Automated Market Makers
Traditional exchanges use order books. Traders post bids and asks; a matching engine pairs them by price-time priority. It works well when orders can be updated instantly and cheaply.
On a public chain, that’s difficult. Every order is a transaction that costs gas. Latency between submission and inclusion creates stale quotes and invites predatory strategies. Updating thousands of orders per second is impractical on base layers.
Automated market makers (AMMs) replace the order book with liquidity pools. A simple design is the constant product market maker (CPMM), popularised by Uniswap. Two assets sit in a pool with reserves x and y. The product x × y stays constant, so trades move the price along a curve.
Worked example with the constant product formula:
- Start: 100 ETH and 200,000 USDC in a pool. k = 100 × 200,000 = 20,000,000.
- A trader buys 10 ETH. New ETH reserve x′ = 90.
- To keep k constant, USDC reserve y′ = k / x′ = 20,000,000 / 90 ≈ 222,222.22.
- The trader must add 22,222.22 USDC, so the average price paid is ≈ 2,222.22 per ETH, above the initial 2,000 — that difference is price impact.
Liquidity providers (LPs) deposit token pairs into the pool and receive LP tokens representing their share. Traders pay a fee that accrues to LPs. The trade-off is exposure to “impermanent loss.”
Impermanent loss happens because AMMs rebalance your holdings. If an external market reprices ETH upward, the pool will end up holding relatively less ETH and more USDC. Your position may underperform simply holding the assets.
Numerical illustration for impermanent loss:
- Deposit 10 ETH and 20,000 USDC when ETH is $2,000 (total $40,000).
- If ETH later trades at $4,000, pool reserves shift toward USDC.
- At that price, the pool with k = 200,000 settles around 7.071 ETH and 28,284 USDC for the same share.
- Value ≈ 7.071 × 4,000 + 28,284 ≈ $56,569. Holding without providing liquidity would be $60,000. The gap, before fees, is impermanent loss.
Uniswap v2 kept liquidity uniformly distributed across all prices, which spreads capital thinly. Uniswap v3 introduced concentrated liquidity, letting LPs specify a price range where their funds are active. This improves capital efficiency and fee earnings in active bands, but requires active management.
Concentrated liquidity: power and complexity
Concentrating liquidity tightens spreads but raises operational risk. LPs must rebalance when price escapes their range, or earnings drop to zero while inventory sits idle.
| Feature | AMM DEX | Order Book Exchange |
|---|---|---|
| Price discovery | On-curve via invariant (e.g., x·y = k); reacts to order flow | Discrete bids/asks set by traders and market makers |
| Liquidity provision | Pooled by LPs; passive, with range options on advanced AMMs | Provided by market makers placing quotes at multiple levels |
| Capital efficiency | Lower on simple pools; higher with concentrated ranges | High when quotes are tightly managed off-chain |
| Front-running risk | Susceptible to sandwich attacks around price impact | Lower on centralised engines; higher on on-chain order books |
| Gas cost | Paid by each trader; L2s reduce cost substantially | Off-chain matching avoids gas per order; on-chain settlement varies |
3. Decentralised Lending
Lending protocols create money markets through smart contracts. Users supply assets to earn interest and borrow other assets against posted collateral. Interest rates adjust with utilisation.
MakerDAO issues DAI, a crypto-collateralised stablecoin. Users open a vault, deposit collateral like ETH, and mint DAI against it. If collateral value falls and the vault breaches its required ratio, liquidation auctions sell collateral to repay DAI plus a penalty.
Overcollateralisation is essential in trust-minimised systems. There is no credit check, recourse, or collections department. The only protection against borrower default is excess collateral that can be sold quickly when prices move.
Compound pioneered algorithmic rates. Suppliers receive cTokens that represent their claim on the pool. The cToken-to-underlying exchange rate increases as interest accrues. Borrowers pay a floating rate that rises as utilisation increases.
Aave added a set of features useful to both retail and institutions. Depositors receive aTokens that track their balance and accrue interest. Borrowers can choose variable rates or “stable” rates that adjust slowly. Credit delegation lets a depositor extend a credit line to another address based on an off-chain agreement, while the protocol enforces limits on-chain.
Flash loans are a distinctive primitive. A contract can borrow funds, perform operations like arbitrage or collateral swaps, and repay within the same transaction. If any step fails, the whole transaction reverts and the loan never exists on-chain.
“Flash loans work because transactions are atomic: either every call in the sequence succeeds and state updates, or the chain discards all steps. That all-or-nothing guarantee is unique to blockchains.”
Liquidations keep markets solvent. When a borrower’s “health factor” drops below 1 due to price moves or interest accrual, bots repay part of the debt on their behalf and seize collateral at a discount. Maker uses auctions run by keepers; pool-based lenders use direct swaps to unwind risk.
Critical insight
Most lending yield comes from borrowers paying to access liquidity. If borrow demand dries up or risk parameters are set too loose, yields can fall sharply or losses can occur during market stress.
4. Decentralised Exchanges Beyond AMMs
AMMs dominate spot trading on base layers, but order books thrive where matching can occur off-chain or on faster layers. dYdX used a zk-powered rollup for perpetuals with an off-chain order book and on-chain settlement. Vertex on Arbitrum combines an order book with a virtual AMM for deeper liquidity.
Aggregators like 1inch and ParaSwap route orders across many venues. They split large trades to reduce slippage, consider gas costs, and choose routes that minimise total cost.
| Aspect | DEX | CEX |
|---|---|---|
| Custody | User self-custody with smart contracts | Exchange holds assets on your behalf |
| KYC/Account | Generally permissionless to trade | Account registration and identity checks |
| Slippage | Depends on liquidity and route; AMMs show curve impact | Typically lower for liquid pairs via market makers |
| Gas/Fees | On-chain gas plus protocol fee; lower on L2 | Trading fees only; no gas per order |
| Speed | Block-time bound; L2s and rollups are faster | Millisecond matching via central engine |
| Asset selection | Wide, including long-tail tokens | Curated listings |
MEV (Maximal Extractable Value) looms over all on-chain trading. Because transactions sit in a public mempool before inclusion, sophisticated actors can reorder, insert, or censor transactions to capture value. The classic example is a sandwich attack that brackets a user’s swap with a front-run and a back-run, extracting profit from the user’s price impact.
“The same transparency that guarantees fairness of settlement also exposes intent to adversaries watching the mempool — a fertile ground for MEV and sandwich attacks.”
Reducing on-chain trading risk
- Use L2s or aggregators that support gas-optimised routing and private orderflow.
- Set a tight slippage tolerance on volatile pairs to cap adverse execution.
- Keep cold storage segregated; trade from hot wallets and store long-term funds on hardware devices like Ledger.
5. Yield Farming and Liquidity Mining
In mid-2020, protocols began distributing governance tokens to users who provided liquidity or borrowed and lent. Compound’s COMP distribution in June that year kicked off an arms race. Projects bootstrapped usage by paying tokens on top of fee income.
Here is the basic mechanism. A DEX offers LP tokens to depositors of a pair. A farming contract then pays out extra tokens to addresses that stake those LP tokens. Borrowers on money markets might also receive incentives, effectively turning their net cost into a subsidy when rewards exceed interest.
This can drive explosive growth. As yields spike, capital floods in, deepening liquidity and compressing spreads. Token prices rise when demand for rewards exceeds emissions, making the feedback loop stronger.
The risks are substantial:
- Smart contract risk — farming contracts and vaults add layers of code that can be exploited.
- Impermanent loss — high rewards can mask inventory loss on volatile pairs.
- Token inflation — emissions can overwhelm demand, driving rewards toward zero.
- Rug pulls and admin-key misuse — upgradable contracts can be altered to siphon funds.
Most headline yields are not durable cash flows. They are equity-like emissions used to gain attention and bootstrap usage. When subsidies end, only products that generate genuine fees and interest tend to keep capital.
Mercenary capital vs genuine yield
“Mercenary” liquidity chases emissions and leaves when rewards drop. “Genuine” yield comes from users paying for a service — trading fees, borrow interest, or real-world revenue brought on-chain.
The 2020–2021 period also surfaced concepts like “vampire attacks,” where a new DEX enticed LPs from an incumbent with higher rewards. Incentives shaped liquidity flows as much as product features.
Tax complexity followed quickly. Many jurisdictions treat reward tokens as income when received and taxable events when swapped. Tools like Koinly can help track basis, income, and disposals across wallets and chains.
6. The Oracle Problem
Smart contracts cannot query external data by themselves. That creates a problem for anything that depends on prices, interest benchmarks, or real-world events.
On-chain price feeds are the standard solution. Chainlink popularised decentralised oracle networks that aggregate prices from multiple sources, sign them off-chain, and push updates on-chain when thresholds are met. Contracts then read from a single aggregator that reflects a median or weighted answer.
For volatile markets, protocols may also use time-weighted average price (TWAP) oracles based on AMM prices to resist short-lived spikes. Some combine a primary oracle with a sanity check from a secondary feed.
Why does this matter? If a lending market reads a bad price that overstates collateral value, under-collateralised loans can form. Liquidators might be unable to unwind positions before losses hit the pool. Conversely, an over-conservative oracle can spur wrongful liquidations.
Flash-loan-powered price manipulation has exploited oracle weaknesses. On October 26, 2020, Harvest Finance’s USDC and USDT vaults suffered an exploit that manipulated Curve pool prices within a short window, enabling the attacker to withdraw funds at an artificially favourable rate. Roughly $24 million was drained before the positions were unwound.
“A fast oracle that reads a manipulable pool can be a liability. When a single block contains both the manipulation and the read, the contract never sees the ‘true’ market.”
Designers face a tension between decentralisation, cost, and freshness. Heavily decentralised oracle networks reduce single points of failure but cost more gas and can update more slowly. Cheap, rapid reads from a single DEX pair may be fresh but are easier to manipulate at low liquidity.
Oracle design safeguards
- Use diversified oracle networks with medianization and off-chain reporting.
- Apply TWAPs or liquidity-weighted checks to resist single-block manipulation.
- Add circuit breakers that pause liquidations on outlier moves beyond historical bands.
- For stablecoins, pair price feeds with collateral-specific monitors and caps.
Putting It All Together
DeFi is not one product. It is a stack: tokens, exchanges, lenders, oracles, and incentive layers that interoperate on-chain. Smart contracts make settlement impartial. Composability lets new protocols assemble prior work into fresh designs.
The trade-offs are clear. You swap institutional credit risk for contract and oracle risk. You gain self-custody and auditability, but must manage keys and transaction hygiene. Gas costs fall on you, but so does the ability to permissionlessly access any market.
As this series continues, we will examine risk management, staking systems, and the technical underpinnings that keep blockchains secure at scale. For investors and builders, understanding how each module works — and fails — is the difference between durable participation and being exit liquidity for the next incentive wave.
Frequently Asked Questions
How do DeFi protocols work without banks or traditional financial institutions?+
DeFi protocols replace traditional financial intermediaries with smart contracts that automatically execute transactions based on pre-programmed rules. Users maintain custody of their funds through private keys, whilst blockchain technology ensures transparency and immutability of all transactions. Smart contracts handle everything from token swaps to loan issuance without requiring human intervention or institutional oversight.
What are Automated Market Makers and how do they enable trading?+
Automated Market Makers (AMMs) are smart contracts that create liquidity pools for trading pairs, using mathematical formulas to determine prices based on the ratio of assets in each pool. Instead of matching buyers and sellers like traditional exchanges, AMMs allow traders to swap directly against these pools. Liquidity providers earn fees by depositing equal values of both tokens in a trading pair.
Are DeFi protocols truly decentralised?+
Most DeFi protocols operate on a spectrum of decentralisation rather than being fully decentralised. Many retain admin keys for upgrades, rely on governance tokens for parameter changes, or depend on centralised components like front-ends or oracle feeds. True decentralisation requires examining who controls contract upgrades, how governance works, and what external dependencies exist in the protocol's architecture.
How do DeFi lending protocols calculate interest rates?+
DeFi lending protocols typically use algorithmic interest rate models that adjust rates based on supply and demand dynamics. As utilisation of a lending pool increases, interest rates rise to incentivise more deposits and discourage excessive borrowing. These models often include base rates, multiplier coefficients, and jump rate mechanisms to maintain healthy liquidity levels across different market conditions.
What role do oracles play in DeFi and why are they important?+
Oracles provide external data feeds to smart contracts, particularly price information that DeFi protocols need for accurate valuations. They're critical for lending protocols to determine collateral ratios, DEXes to calculate fair prices, and derivatives platforms to settle contracts. Oracle reliability directly impacts protocol security, as manipulation or failures can trigger liquidations or enable arbitrage attacks against the system.
Recommended Reading
Key Statistics
DeFi TVL Peak
Total value locked in DeFi peaked at $180 billion in November 2021 before collapsing to $40 billion in 2022
Uniswap Launch
November 2018 — Uniswap v1 launched, introducing the automated market maker model to DeFi
MakerDAO Age
MakerDAO was founded in 2014 — the oldest DeFi protocol and creator of the DAI stablecoin
Compound Launch
2018 — Compound pioneered algorithmic money markets, allowing permissionless lending and borrowing
Aave TVL
Aave reached over $20 billion TVL at peak — the largest decentralised lending protocol by assets
Flash Loans
Aave introduced flash loans in 2020 — uncollateralised loans that must be borrowed and repaid in a single transaction

