DeFi Protocol Development
Mango Markets, October 2022: an attacker opened a huge MNGO perp position, manipulated the spot price through the same account, raised the token price 10x, borrowed at an inflated collateral rate and withdrew $114M. The oracle took spot price from a single source without TWAP. Not a code bug — an architectural decision that became a vulnerability.
A DeFi protocol is a system of bets that mathematics, oracles, and economic incentives are all set up correctly simultaneously.
Key DeFi Architecture Components
| Protocol Type | Core Mechanic | Main Risk |
|---|---|---|
| DEX (AMM) | x*y=k or concentrated liquidity | Impermanent loss, oracle manipulation |
| Lending | Collateral ratio, liquidation | Bad debt from cascading liquidations |
| Yield aggregator | Auto-compounding strategies | Rug through strategy upgrade |
| Derivatives / Perps | Funding rate, mark price | Liquidation cascades, socialized losses |
| Liquid staking | stETH-style rebasing | Depegging on mass unstake |
Oracles: The Most Common Attack Vector in DeFi
This deserves detailed examination — most major DeFi hacks started here.
Spot Price as Oracle — Not an Option
Uniswap v2 spot price can be shifted with a flash loan in one transaction. The price at block end is all that gets into state, and that's what the oracle reads. Attack schema: borrow via flash loan → buy asset in pool → price spikes 5x → read this price as collateral value → borrow at inflated ratio → sell asset → repay flash loan. Entire cycle in one transaction.
TWAP as Protection and Its Limitations
Uniswap v3 TWAP through observe() averages price over a period (usually 30 minutes). Manipulation requires maintaining the price for several blocks, which is significantly more expensive. But TWAP reacts slowly to legitimate price changes — during sharp market moves this creates an arbitrage window on liquidations.
Chainlink Price Feeds aggregate from multiple independent data providers with a median. Standard for lending protocols. Problem: Chainlink has a heartbeat (1–24 hour updates depending on the pair) and deviation threshold. If price didn't move 0.5%, the feed might not update for 24 hours. In a volatile market this is lag.
Production Protocol Oracle Architecture
Production lending protocol uses two-level verification:
- Primary oracle: Chainlink aggregator
- Verification: Uniswap v3 TWAP for 30 minutes
- If deviation > N% → transaction rejected, pause
This isn't paranoia — it's standard after 2022–2023 attack series.
AMM: From x*y=k to Concentrated Liquidity
Uniswap v2 Mechanics
Constant product formula: x * y = k. Simple, reliable, works for any price ratio. LP tokens ERC-20 — each pool issues its own token proportional to liquidity share. Problem: liquidity spread across the entire price curve from 0 to ∞, most of it never used.
Uniswap v3 and ERC-721 Positions
Concentrated liquidity: LP provides liquidity in a range [priceLow, priceHigh]. Capital efficiency up to 4000x vs v2 for stable pairs. But LP position becomes an ERC-721 token — this breaks all vault strategies written for ERC-20 LP tokens.
Range management is a separate engineering task. Position exits range when price moves, stops earning fees, becomes single-asset. Protocols like Arrakis Finance automatically rebalance. If building a vault over v3, you need either custom range manager or integration with existing solution.
Slippage in v3 is calculated through sqrtPriceX96 — 96-bit fixed-point math. Errors in these calculations on the frontend result in users seeing one slippage but getting another.
Curve and StableSwap
For pairs with close prices (stablecoin/stablecoin, stETH/ETH) Curve uses an invariant combining constant product and constant sum. Less slippage in the peg range. Curve v2 extends to non-pegged pairs via gamma parameter. Contracts in Vyper, code is mathematically dense, harder to audit.
Lending Protocols: Collateral, Liquidation, Bad Debt
LTV and Liquidation Threshold
Loan-to-Value ratio defines maximum loan under collateral. Liquidation threshold is the level where position becomes liquidatable. Difference between them is liquidator buffer. Typical: LTV 75%, liquidation threshold 80%, liquidation bonus 5%. If collateral price falls 20%+, position is open for liquidation.
Problem emerges with cascading liquidations: many positions liquidate simultaneously → liquidators sell collateral → price falls further → next wave of liquidations. LUNA/UST collapse in May 2022 created exactly this cascade in Anchor Protocol.
Bad Debt and Insurance Funds
If collateral devalues faster than liquidators can act, protocol gets bad debt — a position with negative equity. Aave uses Safety Module (staked AAVE) as backstop. Compound used reserves. Without backstop, bad debt socializes through supply token dilution or through depositor mutual netting.
Designing liquidation systems isn't just "add liquidation function." You need to model behavior in stress scenarios: what happens if the only liquidation bot goes down, if gas is so high liquidation isn't profitable, if collateral asset gets delisted.
Flash Loans: Tool, Not Just Weapon
Flash loan is credit borrowed and repaid in one transaction. Aave and dYdX provide them almost free (0.05–0.09% fee). If the loan with fee isn't repaid by end of transaction, the entire transaction reverts.
Legitimate uses: arbitrage between DEX without own capital, liquidation using borrowed collateral, self-liquidation (repay debt with flash, take collateral, repay flash).
When designing DeFi contracts, initially assume any user has unlimited capital for one transaction. This changes threat model completely.
Yield Farming and Incentive Mechanics
Liquidity mining distributes governance tokens to LP providers. Classic problem: mercenary capital. Farmers come for tokens, sell immediately, leave when emission ends. TVL is fictional.
More sustainable mechanics: protocol-owned liquidity via Olympus-style bonding, veToken model like Curve (CRV locked in veCRV gives farming boost + governance), locked staking with penalty for early exit.
Ve-model with poor implementation creates governance concentration with whale holders. Need timelock on gauge weight changes and limits on simultaneous votingPower accumulation.
DeFi Development Stack
Contracts: Solidity 0.8.x, OpenZeppelin 5.x (AccessControl, ReentrancyGuard, Pausable, TimelockController), Solmate for gas-optimized basics, PRBMath for fixed-point math
Oracles: Chainlink (all major networks), Uniswap v3 TWAP, Pyth Network (cross-chain, low latency)
Testing: Foundry with fork tests on mainnet forking (tests against real Uniswap/Aave state), Echidna for invariant fuzzing, Slither
Monitoring: Tenderly (transaction simulation, alerts), OpenZeppelin Defender (automation, monitoring), Forta Network (on-chain threat detection)
DeFi Protocol Development Process
Economic design — tokenomics, incentive model, stress-testing in Python/Excel. Before writing code, understand if the math works.
Contract architecture — interaction schema, interfaces, upgrade points.
Development — iteratively, with mainnet fork tests from the start. Real Uniswap/Chainlink data in tests is mandatory.
Audit — at least two independent auditors for any protocol with anticipated TVL from $1M. Code4rena or Sherlock for bug bounty.
Deployment with multisig — Gnosis Safe 3/5 or 4/7, timelock 48–72 hours on protocol changes.
Timelines
- DEX with AMM (Uniswap v2 fork): 6–10 weeks
- Lending protocol (Aave-style, one collateral): 3–5 months
- Yield aggregator with several strategies: 2–4 months
- Full DeFi protocol with governance: 5–8 months including audit







