Overflow and underflow are common arithmetic errors that occur when values exceed or drop below their storage limits.
In Solidity versions before 0.8.0, these errors could result in unexpected behavior without throwing an error.
However, starting with Solidity 0.8.0, these operations automatically revert on overflow or underflow. Nevertheless, itβs important to understand these errors, especially when working with older contracts or specific arithmetic cases where unchecked math is used for optimization.
Game
What if a user added an amount to addToBalance that exceeds the uint256 limit?
// SPDX-License-Identifier: MIT// Open me in VSCode and really think before opening the hints!// Add @audit tags wherever suspicious// Go to the solidity docs to complete missing knowledge of what's happening here// Solve by drafting a fix!pragmasolidity ^0.7.0;contract OverflowUnderflowGame {uint256public totalSupply =1000;mapping(address=>uint256) public balances;functionaddToBalance(uint256 amount) public { balances[msg.sender] += amount; }functionsubtractFromBalance(uint256 amount) public { balances[msg.sender] -= amount; }}
Solidity versions before 0.8.0, adding a large number to balances[msg.sender] might cause it to wrap around to zero or another small number, creating an overflow.
The SafeMath library from OpenZeppelin can be used to prevent overflow and underflow in Solidity <0.8.0