The PuppyRaffle.sol uses Solidity compiler version 0.7.6. Any Solidity version before 0.8.0 is prone to Overflow/Underflow vulnerability. Short example - a uint8 x;
can hold 256 values (from 0 - 255). If the calculation results in x
variable to get 260 as value, the extra part will overflow and we will end up with 5 as a result instead of the expected 260 (because 260-255 = 5).
I have two example below to demonstrate the problem of overflow and underflow with versions before 0.8.0, and how to fix it using safemath:
Without SafeMath
:
In the above code,without safeMath
, 20x20 (totalAmountCollected * 20) was 400, but 400 is beyond the limit of uint8, so after going to 255, it went back to 0 and started counting from there. So, 400-255 = 145. 145 was the result of 20x20 in this code. And after dividing it by 100, we got 1.45, which the code showed as 1.
With SafeMath
:
This code didnt suffer from Overflow problem. Because of the safeMath, it was able to calculate 20x20 as 400, and then divided it by 100, to get 4 as result.
Depending on the bits assigned to a variable, and depending on whether the value assigned goes above or below a certain threshold, the code could end up giving unexpected results.
This unexpected OVERFLOW and UNDERFLOW will result in unexpected and wrong calculations, which in turn will result in wrong data being used and presented to the users.
Got suggestions from AI tool phind. Tested the above code (with and without safeMath) on remix.ethereum.org
Modify the code to include SafeMath:
First import SafeMath from openzeppelin:
then add the following line, inside PuppyRaffle Contract:
(can also add safemath for uint8, uint16, etc as per need)
Then modify the require
inside enterRaffle() function
:
Then modify variables (totalAmountCollected
, prizePool
, fee
, and totalFees
) inside selectWinner()
function:
This way, the code is now safe from Overflow/Underflow vulnerabilities.
The contest is live. Earn rewards by submitting a finding.
This is your time to appeal against judgements on your submissions.
Appeals are being carefully reviewed by our judges.