defi-attack-patterns

DeFi attack pattern playbook. Use when analyzing flash loan attacks, price oracle manipulation, MEV sandwich attacks, governance exploits, bridge vulnerabilities, and token standard edge cases in decentralized finance protocols.

By yaklang · 2,957 installs

npx skills add yaklang/hack-skills --skill defi-attack-patterns

Source repository · Upstream listing

SKILL: DeFi Attack Patterns — Expert Attack Playbook AI LOAD INSTRUCTION : Expert DeFi exploitation techniques. Covers flash loan mechanics, oracle manipulation (spot vs TWAP), MEV extraction (sandwich, JIT, liquidation), precision loss attacks, governance exploits, bridge vulnerabilities, and token standard pitfalls. Base models often miss the single transaction atomicity constraint of flash loans and the distinction between spot price and TWAP manipulation. 0. RELATED ROUTING [smart contract vulnerabilities](../smart contract vulnerabilities/SKILL.md) for underlying Solidity vulnerability patterns (reentrancy, integer overflow, delegatecall) [deserialization insecure](../deserialization insecure/SKILL.md) when targeting off chain bridge relayer or indexer infrastructure 1. FLASH LOAN ATTACKS 1.1 Mechanism Flash loans provide uncollateralized borrowing within a single transaction. The entire borrow → use → repay cycle must complete atomically; if repayment fails, the transaction reverts as if nothing happened. Provider Max Amount Fee Aave V3 Pool liquidity per asset 0.05% (can be 0 for approved borrowers) dYdX Pool liquidity 0 (uses internal balance manipulation) Uniswap V3 Pool liquidity per pair 0.3% (swap fee tier) Balancer Pool liquidity Protocol configurable 1.2 Price Oracle Manipulation Key insight : protocols using AMM spot reserves ( getReserves() ) as price oracles are vulnerable. Must use TWAP or external oracle (Chainlink). 1.3 Liquidity Pool Drain via Reentrancy Flash borrow → deposit into pool → trigger reentrancy during callback → withdraw more than deposited → repay loan. Exploits the combination of flash loan capital with reentrancy in pool accounting logic. 1.4 Governance Flash Borrow Defense: snapshot based voting (Compound Governor Bravo), timelocks, minimum proposal period. 2. PRICE ORACLE MANIPULATION 2.1 Spot Price vs TWAP Oracle Type Manipulation Cost Time Window Spot price ( getReserves() ) Single large swap (flash loanable) Same transaction TWAP (Time Weighted Average) Sustained multi block manipulation Multiple blocks (expensive) Chainlink aggregator Compromise ≥ majority of oracle nodes Practically infeasible 2.2 AMM Manipulation Flow 2.3 Chainlink Oracle Staleness If oracle is stale (network congestion, L2 sequencer down), price can be hours old → arbitrage against stale price. L2 Sequencer Risk : If Arbitrum/Optimism sequencer is down, Chainlink prices freeze. When it comes back, prices jump → mass liquidations at wrong prices. 3. MEV (MAXIMAL EXTRACTABLE VALUE) 3.1 Sandwich Attack 3.2 JIT (Just In Time) Liquidity 3.3 Liquidation MEV 3.4 MEV Protection Mechanisms Mechanism How It Works Flashbots Protect Sends tx to private mempool; only block builder sees it MEV Blocker RPC endpoint that routes through MEV aware relayers Cow Protocol (batch auction) Batch matching eliminates ordering advantage Encrypted mempools Threshold encryption; decrypt only at block build time MEV Share User captures portion of MEV extracted from their tx 4. PRECISION LOSS EXPLOITATION 4.1 Rounding Errors in Token Calculations Solidity has no floating point. Integer division truncates: If totalAssets is very large relative to depositAmount totalShares , result rounds to 0 → depositor gets no shares but pool keeps the deposit. 4.2 First Depositor / Vault Inflation Attack Defenses: Mint dead shares on first deposit (OpenZeppelin ERC4626 offset) Require minimum initial deposit Internal accounting with virtual offset 4.3 Dust Attack via Precision Truncation Repeated small operations where each truncation loses 1 wei. Accumulate across thousands of operations → material loss. 5. GOVERNANCE ATTACKS 5.1 Flash Loan Governance Borrow governance tokens → vote → return. Only works if protocol doesn't snapshot balances before voting. 5.2 Timelock Bypass Vector Method Timelock set to 0 Admin can execute proposals instantly emergencyExecute function Bypasses timelock for "emergencies" Guardian/multisig override Single point of failure Proposal cancellation by attacker Front run with cancel if threshold met 5.3 Quorum Manipulation 6. BRIDGE EXPLOITS 6.1 Common Bridge Attack Vectors Vector Example Signature verification bypass Ronin Bridge ($624M) — compromised 5/9 validators Message replay Replay deposit proof on multiple chains Fake deposit proof Submit proof for non existent L1 deposit Validator collusion Compromised majority of bridge validators Smart contract bug Wormhole ($320M) — uninitialized guardian set Upgradeable proxy exploit Attacker gains upgrade authority → swap implementation 6.2 Cross Chain Message Verification 7. TOKEN STANDARD EDGE CASES 7.1 ERC 20 Approval Front Running Defense: approve(0) first, then approve(newAmount) . Or use increaseAllowance/decreaseAllowance . 7.2 ERC 777 Reentrancy via Hooks ERC 777 tokens call tokensReceived() hook on the recipient before completing the transfer → classic reentrancy vector. 7.3 Fee on Transfer Tokens Tokens that deduct a fee on each transfer. Protocol receives less than amount : 7.4 Rebasing Tokens Tokens that automatically adjust balances (e.g., Aave aTokens, stETH). Protocols holding rebasing tokens may have accounting mismatches if they cache balances. 8. NOTABLE DEFI EXPLOITS REFERENCE Exploit Date Loss Primary Vector Ronin Bridge Mar 2022 $624M Compromised validator keys Wormhole Feb 2022 $320M Signature verification bug Beanstalk Apr 2022 $182M Flash loan governance Mango Markets Oct 2022 $114M Oracle manipulation Euler Finance Mar 2023 $197M Donation attack + liquidation logic Curve (reentrancy) Jul 2023 $73M Vyper compiler reentrancy bug 9. DECISION TREE