In Solidity explicit casting from unsigned to signed integer are not protected from overflow that's why you need OZ's safeCast library for casting.
In the function below a uint256
boostAmount
variable was casted to int256
.
First of all explicit casting in solidity is not protected from overflow.
This is casting from uint256 to int256 but in order to use small values I will explain this overflow issue with casting uint8 to int8.
So let's look at the values available in both:
uint8
possible values ranges from 0 to 255
while
int8
possible values ranges from -128 to 127
From the above you can see that it is impossible for int8 to have a value of 129. This means that trying to cast a uint value that is 129 will overflow and result to -127.
Remember the range of values of int8 are -128, -127, -126,.....0.......125, 126, 127
that's why casting 129 will overflow to -127. The same way 128 will overflow to return -128
(note the - sign).
This also means that int8(type(uint8).max) != type(int8).max
Following the same logic above casting a uint256 value boostAmount
to a int256
is not safe and would overflow for some range of values since they both have the same range of possible values.
//Foundry Test
function test_unsafecasting() public {
uint256 testAmount = type(uint256).max;
//This test will fail because the value of casting the above will overflow
assertEq(testAmount, int(testAmount);
}
The test above should fail because after casting testAmount
to int, it will overflow and no more equal to testAmount.
overflow leading to incorrect accounting issues.
Foundry
Use openzeppelin's safeCast library for every casting in the codebase.
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.