---
description: DeFi patterns—token standards (ERC-20, 721, 1155, 4626), AMM/lending concepts, oracles, MEV/slippage protection. Security and composability.
alwaysApply: false
---

# DeFi Protocol Patterns

Guidelines for DeFi-oriented contracts and integrations.

## Token Standards

- **ERC-20**: Fungible; balance, transfer, approve. Use OpenZeppelin; add extensions (burn, pausable, permit) as needed.
- **ERC-721**: Non-fungible; tokenId, ownerOf, transfer. Use for NFTs and soulbound where appropriate.
- **ERC-1155**: Multi-token; id + amount; batch operations. Use for games or mixed fungible/non-fungible.
- **ERC-4626**: Vault standard; shares and assets; deposit/withdraw/mint/redeem. Use for yield-bearing tokens.

## Security Patterns

- **CEI**: Checks-Effects-Interactions; update state before external calls; use ReentrancyGuard for external calls that can reenter.
- **Input validation**: Zero address, zero amount, allowed token/list; revert with custom errors.
- **Access control**: Role-based (e.g. OpenZeppelin AccessControl); avoid tx.origin for auth.
- **Oracles**: Prefer TWAP or time-weighted feeds; check staleness and sanity; don’t use spot price alone for value transfers (manipulable).
- **Slippage and deadline**: User passes minAmountOut (or minReceived) and deadline; revert if not met. Protects against MEV and front-running.

## MEV and Front-Running

- **Slippage**: Always minOut (or maxIn) in swaps and liquidity ops.
- **Deadline**: Expiry timestamp so tx can’t be held and executed at worse price.
- **Commit-reveal**: For sensitive ordering, consider commit-reveal schemes to hide intent until execution.
- **Pull over push**: Prefer user pulling funds (withdraw) over contract pushing (avoids DoS and reentrancy patterns).

## Composability

- **Interfaces**: Rely on standard interfaces (IERC20, etc.) and well-known protocols so others can integrate.
- **Events**: Emit for all state changes that off-chain indexers or UIs need.
- **No unbounded loops**: Paginate or cap iterations; avoid DoS by gas exhaustion.

## Definition of Done (DeFi Contract)

- [ ] Uses CEI and reentrancy protection; input validation and custom errors.
- [ ] Oracle and pricing use TWAP or validated feeds; slippage and deadline on user-facing ops.
- [ ] Events and interfaces documented; no unbounded loops on user-controlled input.

## Common Pitfalls

- **Spot price for value** - Use TWAP or oracle with staleness check; never trust single-block spot for large value.
- **Missing slippage** - Every swap/liquidity action should have minOut/maxIn and deadline.
- **Push payments** - Prefer pull (withdraw) to avoid reentrancy and DoS.
