Introduction
Based on our experience auditing hundreds of DeFi protocols, we've compiled the essential security practices that every protocol should implement. These practices can prevent the majority of exploits we see in the wild.
1. Robust Access Control
Implement defense-in-depth access control with timelocks for sensitive operations.
AccessControl.sol
// Use OpenZeppelin's AccessControl with timelockscontract SecureProtocol is AccessControl, TimelockController { bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); // Sensitive functions require timelock function setFeeRate(uint256 newRate) external onlyRole(ADMIN_ROLE) { require(newRate <= MAX_FEE, "Fee too high"); _scheduleOperation( abi.encodeCall(this._setFeeRate, (newRate)), TIMELOCK_DELAY ); }}2. Oracle Security
- Use TWAP (Time-Weighted Average Price) instead of spot prices
- Implement multiple oracle sources with deviation checks
- Add circuit breakers for extreme price movements
- Consider Chainlink or other battle-tested oracle solutions
Over 60% of DeFi exploits in 2023 involved oracle manipulation. Never rely on single-block prices.
3. Reentrancy Protection
ReentrancyGuard.sol
// Always use checks-effects-interactions patternfunction withdraw(uint256 amount) external nonReentrant { // Checks require(balances[msg.sender] >= amount, "Insufficient balance"); // Effects (state changes BEFORE external calls) balances[msg.sender] -= amount; // Interactions (external calls LAST) (bool success, ) = msg.sender.call{value: amount}(""); require(success, "Transfer failed");}Access Control
Defense-in-depth with timelocks
Oracle Security
TWAP and multiple sources
Reentrancy
Checks-effects-interactions pattern
Audit Everything
Professional audits before mainnet
