Integer Bugs
Arithmetic
Integer overflow and underflow were common vulnerabilities before Solidity 0.8.0. Understanding these bugs is still important for auditing older contracts and unchecked blocks.
Overflow/Underflow Examples
solidity
// Pre-Solidity 0.8.0 - No automatic checks
// OVERFLOW: uint8 max is 255
uint8 x = 255;
x = x + 1; // x becomes 0!
// UNDERFLOW
uint8 y = 0;
y = y - 1; // y becomes 255!
// Real-world impact: Token balance manipulation
contract VulnerableToken {
mapping(address => uint256) balances;
// VULNERABLE: Underflow on insufficient balance
function transfer(address to, uint256 amount) public {
balances[msg.sender] -= amount; // Underflows if amount > balance
balances[to] += amount;
}
}
// Solidity 0.8.0+ - Automatic overflow checks
// But unchecked blocks bypass this:
unchecked {
uint8 x = 255;
x++; // Still overflows to 0
}Mitigation
solidity
// Pre-0.8.0: Use SafeMath library
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract SafeContract {
using SafeMath for uint256;
function transfer(address to, uint256 amount) public {
balances[msg.sender] = balances[msg.sender].sub(amount);
balances[to] = balances[to].add(amount);
}
}
// Solidity 0.8.0+: Built-in checks
// Use unchecked blocks carefully when gas optimization needed
// Auditing checklist:
// 1. Check Solidity version
// 2. Search for unchecked blocks
// 3. Look for custom math libraries
// 4. Check multiplication before division
// 5. Validate user input ranges