2

I'm analyzing Uniswap V2 core contracts, and have noticed a comment

// overflow is desired

Why overflow is desired?

Because, from my point of view when overflow happens the next line

if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {

never will be true due to wrong timeElapsed.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Nikita Duginets
  • 163
  • 1
  • 6

2 Answers2

1

In:

uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired

Since timeElapsed is unsigned, if an overflow occurs then its value will necessarily be positive, hence the expression timeElapsed > 0 will necessarily evaluate to true.

If you're planning to dive into Solidity code, then you probably want to learn the basic concepts of unsigned integers and Twos Complement.

0

That contract is written in pragma solidity =0.5.16. In this version in order to prevent overflow-underflow errors, it has to have SafeMath library checks which is extra operation so it is an extra cost (solidity automatically checks for overflow underflow after v8.0.0)

    uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired

blockTimestampLast is when those 2 variables are updated

uint public price0CumulativeLast;
uint public price1CumulativeLast;

timeElapsed type is uint32 which represents unsigned integers with values ranging from 0 to 4,294,967,295. To simplify let's say our range is 0-32 and let's say we have those variables

 blockTimestamp=30
 blockTimestampLast=20

Therefore timeElapsed=10

Assume that 10 seconds passed and we did not update price0CumulativeLast and price1CumulativeLast so blockTimestampLast=20. 10 seconds passed, blockTimestampLast did not change we expect that timeElapsed=20

After 10 seconds blockTimestamp will be 30+10=40. since we assume that our range is 0-32, blockTimestamp will be 40-32=8. Now calculate the timeElapsed

timeElapsed = blockTimestamp - blockTimestampLas
            = 8-20 =-12

since we are in 0-32 -12 means 20 seconds. So timeElapsed=20. Since the time difference did not change, overflow is desired in this case.

But imagine a case where you are adding total costs and our range is still 0-32. Now when your total cost is 25 and if you add 10 dollars cost, it will be 35 dollars, in our range it is 3 dollars. So this is not desirable.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202