I came across a tweet which tells there are few scenarios in which Integer Overflow/Underflow are possible in Solidity ^0.8.0? Do you know how?
Asked
Active
Viewed 341 times
1
-
Does this answer your question? Revert reason for arithmetic overflows in Solidity v0.8 – Paul Razvan Berg Sep 05 '22 at 12:57
1 Answers
2
Well, yes. If you use assembly or the unchecked keyword you can get an overflow/underflow.
Check this simple code I created:
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Counter {
mapping(address => uint256) public balances;
constructor() {
balances[msg.sender] = 0;
}
function underflow_assembly() public pure returns(uint256) {
uint256 n = 0;
assembly {
n := sub(n, 1)
}
// n now is equal to 115792089237316195423570985008687907853269984665640564039457584007913129639935
return n;
}
function underflow_unchecked() public pure returns(uint256) {
uint256 n = 0;
unchecked {
n--;
}
// n now is equal to 115792089237316195423570985008687907853269984665640564039457584007913129639935
return n;
}
// reverts
function no_underflow() public pure returns(uint256) {
uint256 n = 0;
n--;
return n;
}
// reverts
function balanceUnderflow() public {
balances[msg.sender] -= 1;
}
}
With Solidity version ^0.8.0, you cannot get underflow/overflow unless you use the unchecked keyword or use assembly.
Jeremy Then
- 4,599
- 3
- 5
- 28