Simple Explanation of Integer Overflow in Smart Contracts
An integer overflow vulnerability happens when a number variable in Solidity exceeds its maximum value or goes below its minimum value, causing it to "wrap around" and behave unexpectedly.
How It Works:
In Solidity, integers have a fixed size (e.g.,
uint8
,uint256
).uint8
: Can store values from0
to255
.uint256
: Can store values from0
to2^256 - 1
.
Overflow:
If you add to a number that’s already at its maximum value, it wraps back to
0
.- Example:
uint8 x = 255; x = x + 1;
→x
becomes0
.
- Example:
Underflow:
If you subtract from a number at its minimum value, it wraps back to the maximum value.
- Example:
uint8 x = 0; x = x - 1;
→x
becomes255
.
- Example:
Why It’s Dangerous:
Attackers can exploit this to manipulate calculations and bypass restrictions in smart contracts.
Example:
solidityCopyEditcontract Vulnerable {
uint8 public balance = 255;
function add(uint8 _amount) public {
balance += _amount; // Overflow occurs if _amount > 0
}
}
What Happens:
If someone calls
add(1)
, thebalance
wraps around to0
instead of increasing further.This can lead to broken logic or financial losses.
How to Prevent It:
Use SafeMath Library:
Before Solidity 0.8, you could use the
SafeMath
library to prevent overflows.It reverts the transaction if an overflow or underflow occurs.
Upgrade to Solidity 0.8+:
- Solidity 0.8+ has built-in overflow and underflow checks. If an operation causes an overflow/underflow, the transaction automatically reverts.