Home > Blockchain >  TypeError: Explicit type conversion not allowed from "int_const -1" to "uint256"
TypeError: Explicit type conversion not allowed from "int_const -1" to "uint256"

Time:09-18

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?

CodePudding user response:

An unsigned integer, declared with the uint keyword, is a value data type that must be non-negative; that is, its value is greater than or equal to zero.

So you cannot write this uint(-1). value has to be a non-negative integer

uint and uint256 are aliases.

CodePudding user response:

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.

  • Related