# ๐Ÿ” Security Best Practices > Comprehensive security checklist for DeFi integration. --- ## ๐Ÿ›ก๏ธ General Security Principles ### ๐Ÿ”’ 1. Access Control - โœ… Use access control modifiers for sensitive functions - โœ… Implement owner/admin roles properly - โœ… Never hardcode private keys or mnemonics - โœ… Use environment variables for sensitive data ### โœ… 2. Input Validation - โœ… Validate all user inputs - โœ… Check for zero addresses - โœ… Validate amounts (no zero, no overflow) - โœ… Check token decimals ### ๐Ÿ”„ 3. Reentrancy Protection - โœ… Use ReentrancyGuard for external calls - โœ… Follow checks-effects-interactions pattern - โœ… Be extra careful with flash loans ### โš ๏ธ 4. Error Handling - โœ… Use require/assert appropriately - โœ… Provide clear error messages - โœ… Handle edge cases - โœ… Test error conditions --- ## ๐Ÿฆ Protocol-Specific Security ### ๐Ÿฆ Aave v3 #### โšก Flash Loans | Check | Status | Description | |-------|--------|-------------| | โš ๏ธ **Critical** | โœ… | Always repay flash loan + premium in `executeOperation` | | โš ๏ธ **Critical** | โœ… | Verify `msg.sender == pool` in `executeOperation` | | โš ๏ธ **Critical** | โœ… | Verify `initiator == address(this)` in `executeOperation` | | โœ… | โœ… | Calculate premium correctly: `amount + premium` | | โœ… | โœ… | Handle multi-asset flash loans carefully | | โœ… | โœ… | Test repayment failure scenarios | #### ๐Ÿ’ฐ Interest Rate Modes | Check | Status | Description | |-------|--------|-------------| | โš ๏ธ **Deprecated** | โœ… | Stable rate borrowing is deprecated in v3.3+ | | โœ… | โœ… | Always use variable rate (mode = 2) for new integrations | | โœ… | โœ… | Understand interest rate risks | #### ๐Ÿ›ก๏ธ Collateral Management - โœ… Check liquidation thresholds - โœ… Monitor health factor - โœ… Handle eMode/isolation mode restrictions - โœ… Verify collateral can be enabled ### ๐Ÿ”„ Uniswap v3 #### ๐Ÿ›ก๏ธ Slippage Protection | Check | Status | Description | |-------|--------|-------------| | โš ๏ธ **Critical** | โœ… | Always set `amountOutMinimum` with slippage tolerance | | โœ… | โœ… | Use TWAP oracles, not spot prices | | โœ… | โœ… | Account for price impact in large swaps | | โœ… | โœ… | Consider using UniswapX for better execution | #### ๐Ÿ”ฎ Oracle Security | Check | Status | Description | |-------|--------|-------------| | โš ๏ธ **Critical** | โœ… | Never use spot prices for critical operations | | โœ… | โœ… | Use TWAP with sufficient observation window | | โœ… | โœ… | Verify observation cardinality | | โœ… | โœ… | Protect against oracle manipulation | #### ๐Ÿ” Permit2 - โœ… Verify signature validity - โœ… Check expiration (deadline) - โœ… Verify nonce (prevent replay) - โœ… Protect against signature theft (verify spender) ### ๐Ÿ”— Protocolink #### โœ… Route Validation - โœ… Verify all logics in the route - โœ… Check token addresses - โœ… Validate amounts - โœ… Verify slippage settings #### โšก Execution - โœ… Check gas estimates - โœ… Handle execution failures - โœ… Verify router address - โœ… Monitor transaction status ### ๐Ÿ›๏ธ Compound III #### ๐Ÿ’ฐ Borrowing | Check | Status | Description | |-------|--------|-------------| | โš ๏ธ **Important** | โœ… | Understand base asset vs collateral | | โœ… | โœ… | Check borrow limits | | โœ… | โœ… | Monitor collateral ratio | | โœ… | โœ… | Handle liquidation risks | --- ## ๐Ÿ“œ Smart Contract Security ### โšก Flash Loan Receivers ```solidity // โœ… Good: Verify caller and initiator function executeOperation( address asset, uint256 amount, uint256 premium, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(pool), "Invalid caller"); require(initiator == address(this), "Invalid initiator"); // Your logic here // โœ… Good: Approve repayment IERC20(asset).approve(address(pool), amount + premium); return true; } ``` ### ๐Ÿ”„ Reentrancy Protection ```solidity // โœ… Good: Use ReentrancyGuard import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract MyContract is ReentrancyGuard { function withdraw() external nonReentrant { // Safe withdrawal logic } } ``` ### ๐Ÿ”’ Access Control ```solidity // โœ… Good: Use access control import "@openzeppelin/contracts/access/Ownable.sol"; contract MyContract is Ownable { function sensitiveFunction() external onlyOwner { // Owner-only logic } } ``` --- ## ๐Ÿงช Testing Security ### ๐Ÿงช Foundry Tests - โœ… Test all edge cases - โœ… Test error conditions - โœ… Test reentrancy attacks - โœ… Test flash loan scenarios - โœ… Test with fork tests - โœ… Test gas limits ### ๐Ÿ“Š Test Coverage - โœ… Unit tests for all functions - โœ… Integration tests - โœ… Fork tests on mainnet - โœ… Fuzz tests for inputs - โœ… Invariant tests --- ## ๐Ÿš€ Deployment Security ### ๐Ÿ” Pre-Deployment - โœ… Get professional security audit - โœ… Review all dependencies - โœ… Test on testnets extensively - โœ… Verify all addresses - โœ… Check contract sizes ### ๐Ÿ” Post-Deployment - โœ… Monitor transactions - โœ… Set up alerts - โœ… Keep private keys secure - โœ… Use multisig for admin functions - โœ… Have an emergency pause mechanism --- ## โš ๏ธ Common Vulnerabilities ### 1. Reentrancy โŒ **Bad**: External call before state update ```solidity function withdraw() external { msg.sender.call{value: balance}(""); balance = 0; // Too late! } ``` โœ… **Good**: State update before external call ```solidity function withdraw() external nonReentrant { uint256 amount = balance; balance = 0; msg.sender.call{value: amount}(""); } ``` ### 2. Integer Overflow โŒ **Bad**: No overflow protection ```solidity uint256 total = amount1 + amount2; ``` โœ… **Good**: Use SafeMath or Solidity 0.8+ ```solidity uint256 total = amount1 + amount2; // Safe in Solidity 0.8+ ``` ### 3. Access Control โŒ **Bad**: No access control ```solidity function withdraw() external { // Anyone can call } ``` โœ… **Good**: Proper access control ```solidity function withdraw() external onlyOwner { // Only owner can call } ``` --- ## ๐Ÿ”— Resources | Resource | Link | |----------|------| | OpenZeppelin Security | [docs.openzeppelin.com](https://docs.openzeppelin.com/contracts/security) | | Consensys Best Practices | [consensys.github.io](https://consensys.github.io/smart-contract-best-practices/) | | Aave Security | [docs.aave.com](https://docs.aave.com/developers/guides/security-best-practices) | | Uniswap Security | [docs.uniswap.org](https://docs.uniswap.org/contracts/v4/concepts/security) | --- ## โœ… Security Audit Checklist Before deploying to production: - [ ] ๐Ÿ” Professional security audit completed - [ ] ๐Ÿ“ฆ All dependencies reviewed - [ ] ๐Ÿ”’ Access control implemented - [ ] ๐Ÿ”„ Reentrancy protection added - [ ] โœ… Input validation implemented - [ ] โš ๏ธ Error handling comprehensive - [ ] ๐Ÿงช Tests cover edge cases - [ ] โ›ฝ Gas optimization reviewed - [ ] โธ๏ธ Emergency pause mechanism - [ ] ๐Ÿ‘ฅ Multisig for admin functions - [ ] ๐Ÿ“Š Monitoring and alerts set up --- ## ๐Ÿšจ Reporting Security Issues If you discover a security vulnerability, please report it responsibly: 1. โ›” **DO NOT** open a public issue 2. ๐Ÿ“ง Email security details to the maintainers 3. โฐ Allow time for the issue to be addressed 4. ๐Ÿ”’ Follow responsible disclosure practices --- ## โš ๏ธ Disclaimer This security guide is for educational purposes. Always get professional security audits before deploying to production. --- ## ๐Ÿ“š Related Documentation - ๐Ÿ“– [Integration Guide](./INTEGRATION_GUIDE.md) - ๐Ÿ”— [Chain Configuration](./CHAIN_CONFIG.md) - ๐Ÿงช [Strategy Testing Guide](./STRATEGY_TESTING.md)