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.

Imagine monitoring actually built for developers

Billboard image

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (1)

Collapse
 
block_experts_766a3a21915637 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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay