Smart Contract Security
The Importance of Smart Contract Security
Smart contracts are difficult to modify once deployed, and bugs lead directly to fund losses. The principle that "code is law" also means mistakes become law.
Reality:
- 2022 DeFi hack damages: $3B+
- Most major hacks were smart contract vulnerabilities
- Even audited protocols got hacked
Major Vulnerability Types
1. Reentrancy Attack
Description: The same function is called again during an external call before state is updated.
Mechanism:
1. Attacker requests withdrawal
2. Contract sends ETH (external call)
3. In attacker's receive(), request withdrawal again
4. Balance not yet updated, so withdrawal succeeds again
5. Repeat
Historical case:
- The DAO Hack (2016): $60M, caused Ethereum hard fork
Defense:
- Use ReentrancyGuard
- Check-Effects-Interactions pattern
- Update state before external calls
2. Integer Overflow/Underflow
Description: Numbers exceed max/min values resulting in unintended values.
Example:
uint8 balance = 255;
balance = balance + 1; // Overflow → 0
Defense:
- Solidity 0.8.0+: Automatic checks
- SafeMath library (earlier versions)
3. Access Control Errors
Description: Missing permission checks on sensitive functions.
Examples:
- Admin-only functions callable by anyone
- Initialization functions re-callable
Defense:
- onlyOwner, onlyAdmin modifiers
- Role-based access control
4. Oracle Manipulation
Description: Manipulating price oracles for unfair profits.
Mechanism:
- Acquire large funds via flash loan
- Large swap on DEX → Price distortion
- Execute favorable trades on other protocols with distorted price
- Restore original state
Cases:
- Harvest Finance: $34M
- Cream Finance: $130M
Defense:
- TWAP (Time-Weighted Average Price)
- External oracles like Chainlink
- Price change limits
5. Front-running
Description: Seeing transactions waiting in mempool and executing first.
Types:
- Sandwich attacks
- Liquidation front-running
- Arbitrage front-running
Defense:
- Slippage settings
- Private mempools like Flashbots
- Commit-reveal schemes
6. Logic Errors
Description: Code doesn't work as intended.
Examples:
- Conditional statement errors
- Calculation mistakes
- Unhandled edge cases
Case:
- Compound bug (2021): $80M incorrectly distributed
Defense:
- Thorough testing
- Formal verification
- Multiple audits
7. Flash Loan Attacks
Description: Complex attacks utilizing flash loans.
Uses:
- Oracle manipulation
- Governance attacks
- Arbitrage exploitation
Defense:
- Snapshot-based voting
- Avoid single-block price dependency
- Rate limiting
8. Signature-Related Vulnerabilities
Description: Signature verification errors, replay attacks.
Case:
- Wormhole: $320M loss due to signature verification bypass
Defense:
- EIP-712 structured signatures
- Use nonces
- Include chain ID
Audits
What is an Audit
Security experts review smart contract code to find vulnerabilities.
Major Audit Firms
| Firm | Characteristics |
|---|---|
| Trail of Bits | Top tier, expensive |
| OpenZeppelin | Industry standard, extensive experience |
| Consensys Diligence | Ethereum specialists |
| Certik | Fast audits, some controversy |
| Halborn | Relatively new |
| Spearbit | Distributed audit network |
Audit Process
- Scope definition: Which contracts to review
- Automated analysis: Run static analysis tools
- Manual review: Expert code review
- Results report: Vulnerabilities and recommendations
- Remediation and re-review: Fix issues and verify
Reading Audit Reports
Severity classification:
- Critical: Possible fund loss, fix immediately
- High: Serious functional issues
- Medium: Potential problems
- Low: Minor issues
- Informational: Improvement suggestions
Things to check:
- All Critical/High issues resolved
- Audit scope matches deployed code
- Audit timing matches current code
Limitations of Audits
Even audited protocols can be hacked:
| Protocol | Audited | Damage |
|---|---|---|
| Wormhole | Yes | $320M |
| Ronin | Yes | $625M |
| Nomad | Yes | $190M |
Reasons:
- Not 100% guarantee
- New vulnerabilities after upgrades
- Business logic errors
- Complex protocol interactions
Security Verification Methods
1. Verify Audits
Check:
- At least 1 audit
- Reputable audit firm
- Audit report published
- Critical/High issues resolved
- Current code matches audited code
2. Code Verification
Etherscan check:
- Is code Verified
- For proxy contracts, implementation contract too
Source verification:
- Code published on GitHub
- Matches deployed code
3. TVL and Operating Period
Lindy effect:
- Longer operation = Higher probability of safety
- More funds locked = More verified
Standards:
- TVL $100M+: Relatively safe
- Operating 1 year+: Sufficient verification period
- However, past success doesn't guarantee future
4. Bug Bounty
Check:
- Bug bounty program existence
- Reward size (should be proportional to fund size)
- Platform use like Immunefi
5. Upgradeability
Immutable contracts:
- Cannot upgrade
- Cannot introduce new vulnerabilities
- Cannot fix bugs either
Upgradeable:
- Uses proxy pattern
- Admin can change logic
- Convenient but risky
Check:
- Is it a proxy contract
- Who has admin rights
- Is there a timelock
6. Admin Privileges
Check:
- List of admin functions
- Multisig status
- Timelock duration
Warning signs:
- Single EOA admin
- Unlimited token minting rights
- Emergency exit functions (admin only)
Tools and Resources
Analysis Tools
- Slither: Static analysis
- Mythril: Symbolic execution
- Echidna: Fuzzing tests
- Tenderly: Simulation
Monitoring
- Forta: Real-time threat detection
- Blocknative: Mempool monitoring
- OpenZeppelin Defender: Automated response
Resources
- SWC Registry: Vulnerability classification
- Rekt.news: Hack case analysis
- Immunefi: Bug bounties
User Perspective Checklist
Before Protocol Participation
- Verify audit report
- Verify code on Etherscan
- Check TVL and operating period
- Check admin privileges
- Bug bounty status
- Community reputation
During Transactions
- Correct contract address
- Verify approval amount
- Understand transaction contents
- Simulate if possible
Ongoing
- Follow protocol news
- Check upgrade announcements
- Monitor for anomalies
Summary
Smart contract security is a core risk of DeFi, with various vulnerabilities including reentrancy attacks, oracle manipulation, and access control errors. Audits are essential but don't guarantee 100% safety, as many audited protocols have been hacked. Users should comprehensively review audit reports, code verification, TVL/operating period, admin privileges, and bug bounties. Immutable contracts are safer than upgradeable ones in some aspects, but there's a tradeoff that bugs also cannot be fixed.
Next article: DeFi Insurance - Methods of Risk Transfer