DEV Community

Cover image for Integer Overflow and Underflow
Penelope Jones
Penelope Jones

Posted on

Integer Overflow and Underflow

I encountered a problem with integer overflow and underflow while subtracting two numbers in Solidity, which caused unexpected results. To address this, I used Solidity version 0.8.0 and above, which has built-in safety checks to prevent such issues. Here's the solution I implemented:

  • Use Solidity 0.8.0 or higher, which has built-in checks for overflow and underflow.
  • Alternatively, use libraries like OpenZeppelin's SafeMath for earlier versions.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract OverflowExample {
    function safeSubtract(uint256 a, uint256 b) public pure returns (uint256) {
        require(a >= b, "Underflow detected");
        return a - b;
    }
}

Enter fullscreen mode Exit fullscreen mode

Discover how NFTs are transforming industries worldwide, empowering artists and enabling innovative gaming ecosystems. Create, trade, and monetize unique digital assets with tailored NFT solutions designed for security, scalability, and endless possibilities. Explore NFT Token Development now!

Top comments (0)