【问题标题】:TypeError: Explicit type conversion not allowed from "int_const -1" to "uint256"TypeError:不允许从 \"int_const -1\" 到 \"uint256\" 的显式类型转换
【发布时间】:2022-09-23 11:10:41
【问题描述】:

我正在尝试编译WETH.sol found on Ethereum mainnet,它是使用非常旧的版本(0.4.x)编译的。我将编译器版本更改为 ^0.8.0 并收到以下错误消息。

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;
        }

我该如何纠正这个错误?

    标签: node.js ethereum solidity


    【解决方案1】:

    使用 uint 关键字声明的无符号整数是值数据 必须为非负数的类型;即它的值大于或 等于零。

    所以你不能写这个uint(-1)。 value 必须是非负整数

    uintuint256 是别名。

    【讨论】:

    • 1)如果我将 -1 更改为零(0),它将解决问题。但是会影响合同的履行吗? 2) 智能合约链接如下:etherscan.io/token/…
    【解决方案2】:

    在 0.8 之前的 Solidity 版本中,编译器不会保护您免受下溢(或上溢)的影响。所以uint(-1) 会下溢给你最大的uint

    获取最大uint 值的最佳做法是type(uint).max

    代码 sn-p 正在检查无限批准。当获得无限批准时,通常假设不需要减少津贴。这将节省一些不需要调整存储的气体。

    因此,要升级代码 sn-p,只需将 uint(-1) 替换为 type(uint).max

    【讨论】:

    • 是否与放置 Zero(0) 而不是 uint(-1) 相同?
    • 我更新了答案以解释所需的更改。
    猜你喜欢
    • 2022-11-22
    • 2022-11-11
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 2015-09-26
    • 1970-01-01
    相关资源
    最近更新 更多