To survive, you must adopt an adversarial mindset. This article explores the core principles of defensive Solidity programming to help you build battle-hardened contracts.
1. The Checks-Effects-Interactions Pattern
This is the most fundamental rule for preventing Reentrancy attacks. Most major DeFi hacks occur because a contract interacts with an external entity before it finishes updating its own internal state.
The Wrong Way (Vulnerable):
function withdraw(uint _amount) public {
require(balances[msg.sender] >= _amount);
(bool success, ) = msg.sender.call{value: _amount}(""); // Interaction
require(success);
balances[msg.sender] -= _amount; // Effect (Too late!)
}
The Defensive Way:
function withdraw(uint _amount) public {
// 1. Checks
require(balances[msg.sender] >= _amount, "Insufficient balance");
// 2. Effects
balances[msg.sender] -= _amount;
// 3. Interactions
(bool success, ) = msg.sender.call{value: _amount}("");
require(success, "Transfer failed");
}
By updating the balance before sending the Ether, you ensure that if the receiver tries to call withdraw again recursively, the check will fail.
2. Use require for Robust Input Validation
Assume every user is providing malicious data. Validate everything: array lengths, address non-zero checks, and mathematical boundaries.
-
- Sanitize Addresses: Ensure
address(0)is not being passed if it can lead to burned funds.
- Sanitize Addresses: Ensure
-
- Validate Ranges: If a function accepts a percentage,
require(percent <= 100).
- Validate Ranges: If a function accepts a percentage,
-
- Explicit Errors: Since Solidity 0.8.4, use
errorandrevertfor gas-efficient, descriptive error handling.
- Explicit Errors: Since Solidity 0.8.4, use
3. Access Control: Don’t Talk to Strangers
Not every function should be public. Use the Principle of Least Privilege. If a function is only used internally, mark it private or internal.
Ownable or AccessControl. Avoid writing your own permission logic from scratch.
import "@openzeppelin/contracts/access/Ownable.sol";
contract SecureVault is Ownable {
function emergencyWithdraw() public onlyOwner {
// Only the admin can execute this
}
}
4. The “Pull” over “Push” Payment Pattern
Sending Ether or tokens to multiple addresses in a single transaction is a recipe for disaster. If one recipient is a malicious contract that reverts upon receiving funds, the entire transaction will fail (a Denial of Service attack).
Defensive Strategy: Instead of “pushing” funds to users, create a “pull” system where users must call a function to claim their own balance individually.
5. Guard Against Arithmetic Overflows
Before Solidity 0.8.0, developers had to use SafeMath. While 0.8.x has built-in overflow/underflow checks, you should still be cautious when using unchecked blocks for gas optimization. Only use unchecked when you are 100% mathematically certain an overflow cannot occur.
6. Beware of Gas Limit DoS
Loops in Solidity are dangerous. If you iterate over a dynamic array (like a list of all users), that array might eventually grow so large that the function exceeds the block gas limit, rendering the contract unusable.
The Fix: Avoid unbounded loops. Use mapping-based architectures or pagination for large data sets.
Conclusion: Security is a Process
Coding defensively means accepting that your code will be poked, prodded, and attacked. Beyond writing clean code, you should:
-
- Run static analysis tools like Slither and Mythril.
-
- Write comprehensive unit tests with 100% branch coverage.
-
- Get a professional third-party audit before moving significant value.
In Solidity, “good enough” is an invitation for disaster. Code like everyone is out to get you—because in the world of public blockchains, they usually are.