---
description: Smart Contract Security
alwaysApply: false
---

# Smart Contract Security

Attack vectors, defense patterns, and audit preparation for smart contracts.

## Common Attack Vectors

### Reentrancy
- External calls allow re-entry before state updates complete
- **Defense**: CEI pattern + `ReentrancyGuard`; update state before external calls

### Flash Loan Manipulation
- Spot prices manipulable within a single transaction
- **Defense**: Use TWAP oracles (e.g., Chainlink, Uniswap TWAP), never spot prices for valuations

### Front-Running / MEV
- Mempool transactions can be observed and exploited
- **Defense**: Commit-reveal schemes, slippage protection (`minAmountOut`), deadlines

### Access Control Bypass
- `tx.origin` can be phished via malicious contracts
- **Defense**: Always use `msg.sender`; prefer role-based access (OpenZeppelin `AccessControl`)

### Denial of Service
- Unbounded loops or push-based payments can be bricked
- **Defense**: Pull-over-push pattern, paginated processing

### Storage Collision (Upgradeable)
- Adding storage variables in wrong position corrupts data
- **Defense**: Append-only storage, use `__gap` arrays to reserve slots

## Security Checklist

### During Development
- Checks-Effects-Interactions on all state-changing functions
- Reentrancy guards, input validation, access control
- Events for all state changes, no floating pragma, no `tx.origin` auth

### Before Deployment
- Slither + Mythril: zero high/medium findings
- Fuzz tests (>100k runs), invariant tests, mainnet fork tests
- External audit completed, bug bounty program ready

### After Deployment
- Monitoring alerts configured, incident response plan documented
- Admin keys on multisig/hardware wallet, gradual rollout

## Audit Preparation

- **Document**: architecture diagram, trust assumptions, access control matrix, known tradeoffs
- **Pre-check common findings**: missing zero-address checks, input validation gaps, centralization risks, missing events, no NatSpec, unsafe external calls

## Anti-Patterns

- Ignoring ERC-20 return values — use `SafeERC20`
- Using `selfdestruct` — avoid unless absolutely necessary
- Assembly without documentation — always explain why
