Skip to content
Last updated: March 11, 2025

SCWE-047: Integer Overflows and Underflows

Stable Version v0.0.1

This content is in the version-(v0.0.1) and still under active development, so it is subject to change any time (e.g. structure, IDs, content, URLs, etc.).

Send Feedback

Relationships

Description

Integer overflows and underflows occur when arithmetic operations exceed the bounds of the integer data type, causing the value to "wrap around" to an unexpected number.

Remediation

  • Use Solidity 0.8.0 or later: Leverage the compiler’s built-in overflow and underflow checks.
  • Apply SafeMath libraries: Use libraries like OpenZeppelin’s SafeMath for versions before 0.8.0.

Examples

Vulnerable Contract Example

pragma solidity ^0.4.0;

contract Vulnerable {
    uint8 public totalSupply;

    function addTokens(uint8 _value) public {
        totalSupply += _value; // May overflow
    }

    function subtractTokens(uint8 _value) public {
        totalSupply -= _value; // May underflow
    }
}

Fixed Contract Example

pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";

contract Secure {
    using SafeMath for uint8;
    uint8 public totalSupply;

    function addTokens(uint8 _value) public {
        totalSupply = totalSupply.add(_value);
    }

    function subtractTokens(uint8 _value) public {
        totalSupply = totalSupply.sub(_value);
    }
}