The DeFi Protocol Landscape: What You're Building Against

Decentralised Finance protocols replace traditional financial intermediaries (banks, exchanges, brokers) with self-executing smart contracts. The four primary DeFi categories — DEX (decentralised exchanges), lending/borrowing protocols, yield aggregators, and derivatives platforms — have collectively processed over $500 billion in transaction volume and represent the most technically complex category of smart contract development.

Building a DeFi protocol means building financial infrastructure. The engineering standards must reflect that: correctness over cleverness, security over features, and simplicity over complexity wherever possible.

The exploit landscape: DeFi protocols lost $2.1 billion to exploits in 2024. 60% of exploits were from smart contract vulnerabilities (reentrancy, access control, arithmetic). 30% were from economic/oracle attacks (price manipulation, flash loans). 10% were from private key compromise. This guide addresses the first 90%.

AMM Architecture: Building a Decentralised Exchange

Automated Market Makers (AMMs) replaced order books with mathematical pricing curves. The dominant model — Uniswap's constant product formula (x * y = k) — sets the price of an asset based on the ratio of two token reserves in a pool.

Core AMM components to implement:

  • Liquidity pool contract: Holds reserves of two tokens. Issues LP tokens representing a proportional share of the pool to liquidity providers.
  • Swap function: Takes input token amount, calculates output using the invariant curve (minus fee), updates reserves, emits Swap event.
  • Add/remove liquidity: Calculates correct ratio to maintain current price, mints/burns LP tokens proportionally.
  • Fee mechanism: Typically 0.3% of swap value, distributed to LP token holders proportionally on withdrawal.

Concentrated liquidity (Uniswap v3 model): Allows LPs to concentrate capital within a price range rather than across the infinite 0→∞ curve. More capital-efficient but more complex — LPs need to actively manage ranges as prices move.

Lending Protocol Architecture

Lending protocols (Aave, Compound model) allow users to deposit assets as collateral and borrow other assets against that collateral. The core challenge is overcollateralisation and liquidation logic — ensuring bad debt never accumulates.

Key lending protocol mechanics:

  • Collateral factor: Each asset has a collateral factor (e.g., ETH = 80%) determining how much can be borrowed against it. Lower for volatile assets.
  • Health factor: (Collateral × Collateral Factor) / Total Debt. Borrowing is allowed while health factor > 1. Liquidation is triggered when health factor < 1.
  • Liquidation mechanism: When undercollateralised, liquidators repay a portion of the debt and receive the collateral at a discount (liquidation bonus). This incentivises liquidators while protecting the protocol from bad debt.
  • Interest rate model: Utilisation-based dynamic interest rates — rates increase as pool utilisation increases, incentivising repayment and attracting new deposits.

Economic Attack Vectors: The Hardest Security Challenges

Economic attacks exploit the financial logic of the protocol rather than code bugs. They're often technically valid transactions that violate the protocol's intended economic assumptions.

Flash loan attacks: An attacker borrows a large amount (uncollateralised) within a single transaction, uses it to manipulate prices or exploit protocol logic, and repays the loan — all before the transaction ends. Prevention: use time-weighted price feeds (TWAPs) rather than spot prices, add checks for large one-block price movements, implement delay mechanisms for sensitive operations.

Oracle manipulation: If a protocol uses a DEX spot price as an oracle, an attacker with enough capital can temporarily move the price (by swapping), trigger a protocol action at the manipulated price, then reverse the price movement. Prevention: use Chainlink decentralised oracles for all external price feeds; never use a single on-chain DEX as a price oracle.

Sandwich attacks: Front-running user swaps by placing a buy order before and a sell order after, profiting from the price impact of the victim's trade. Mitigation: slippage limits that revert if price moves beyond threshold; MEV protection via Flashbots or similar.

Simulation testing: Every DeFi protocol should be tested against simulated economic attack scenarios before mainnet deployment. Tools like Foundry's forge test with mainnet forking allow testing flash loan scenarios against real on-chain state.

The DeFi Audit and Launch Process

DeFi protocols require more rigorous auditing than standard smart contracts due to the financial risk and complexity of economic interactions.

Pre-audit requirements:

  • 100% test coverage with specific economic attack scenario tests
  • Slither and Aderyn static analysis — zero high/critical findings
  • Internal security review by a developer not on the implementation team
  • Complete documentation: architecture diagrams, economic assumptions, invariants the protocol relies on

Audit process: Two independent audits from reputable firms (not the same firm reviewing twice). First audit findings reviewed and fixed; second audit verifies fixes and reviews the complete codebase. Total audit cost for a medium-complexity DeFi protocol: £40,000–£150,000.

Post-audit launch: Deploy on testnet with real-world scenario testing. Establish a bug bounty programme (Immunefi) with rewards proportional to protocol TVL. Launch with TVL caps — limit total deposits for the first 30–90 days while monitoring for unexpected behaviour. Gradual capacity increase as confidence builds.