DEV Community

Mahima Thacker
Mahima Thacker

Posted on

OverFlow and UnderFlow causes in Solidity

In Solidity, arithmetic overflow and underflow were common issues before version 0.8.0.

Here's a quick overview of UnderFlow and OverFlow:

What is Overflow and Underflow?

Overflow:

When you add 1 to the maximum value of a uint8 (255), it exceeds the range (0-255). Solidity doesn't store values beyond 255, so it wraps back to 0.

Have a look at a function called overflow from the attached image, and the result you will get is 0

Image description

Underflow:

When you subtract 1 from the minimum value of a uint8 (0), it goes below the range (negative values aren't allowed). Solidity wraps back to 255.

so this is what we get when we call the function underflow from an image

Image description

But in Solidity 0.8.0 or Above it reverts with an error (overflow/underflow checks are enabled).

Why Does This Matter?

Overflow and underflow could lead to severe vulnerabilities in smart contracts, especially in financial calculations.

How to Prevent This? 🕵‍♀️

  • Use Solidity 0.8.0 or above, where overflow/underflow checks are built-in.
  • For older versions, use libraries like OpenZeppelin’s SafeMath.
  • Test edge cases to ensure safety in arithmetic operations.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (1)

Collapse
 
blockexperts profile image
Block Experts •

Hello,
I want just to add that its possible to disable the check by wrapping the instruction that cause overflow or underflow between unchecked{ instruction } to optimize gas whether there will be no overflow/underflow possible.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay