I am trying to compile WETH.sol found on Ethereum mainnet, which was compiled using a very old version (0.4.x). I changed the compiler version to ^0.8.0 and got the following error message.
TypeError: Explicit type conversion not allowed from "int_const -1" to "uint256".
--> contracts/WETH9.sol:78:64:
|
78 | if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {}
| ^^^^^^^^
Error HH600: Compilation failed
**The code is as follows.**
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
How can I correct this error?
In versions of solidity prior to 0.8, the compiler does not protect you against underflows (or overflows). So uint(-1) would underflow to give you the max uint.
The best practice to grab the max uint value is type(uint).max.
The code snippet is checking for an infinite approval. When an infinite approval has been given, it's common to assume the allowance doesn't need to be decreased. This will save some gas from not needing to adjust storage.
So to upgrade the code snippet, it suffices to replace uint(-1) by type(uint).max.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With