【问题标题】:Uniswap PoolAddress.sol error: `TypeError: Explicit type conversion not allowed from "bytes32" to "uint160"`Uniswap PoolAddress.sol 错误:`TypeError:不允许从 \"bytes32\" 到 \"uint160\" 进行显式类型转换`
【发布时间】:2022-11-11 09:17:58
【问题描述】:

这是Uniswap PoolAddress library repo

当我在做一个安全帽项目时,这段代码抛出了错误:

function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
        require(key.token0 < key.token1);

        //*******************this is causing the error***************
        pool = address(
            uint160(
                keccak256(
                    abi.encodePacked(
                        hex'ff',
                        factory,
                        keccak256(abi.encode(key.token0, key.token1, key.fee)),
                        POOL_INIT_CODE_HASH
                    )
                )
            )
        );
    }

我复制了 Remix 上的完整代码,我收到了 pool=address 行的错误:'TypeError: Explicit type conversion not allowed from "bytes32" to "uint160".'

我读了docs

uint160 允许与地址进行显式转换, 整数文字、bytes20 和合约类型。

它也有一个警告,我不明白这是什么意思:

如果将使用较大字节大小的类型转换为地址,则 例如 bytes32,则地址被截断。减少转化 歧义,从 0.4.24 版本开始,编译器会强制你 使截断在转换中显式。举个例子 32 字节值 0x111122223333444455556666777788889999AAAABBBBCCCCDDDDEEEEFFFFCCCC。

您可以使用 address(uint160(bytes20(b))),这会导致 0x111122223333444455556666777788889999aAaa,或者你可以使用 地址(uint160(uint256(b))),导致 0x777788889999AaAAbBbbCcccddDdeeeEfFFfCcCc。

由于文档提到我可以从 bytes20 转换为 int160,我尝试了这个并且错误消息消失了:

function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
        require(key.token0 < key.token1);
        pool = address(

            uint160(
                bytes20(
                keccak256(
                    abi.encodePacked(
                        hex'ff',
                        factory,
                        keccak256(abi.encode(key.token0, key.token1, key.fee)),
                        POOL_INIT_CODE_HASH
                    )
                )
            )
            )
        );
    }

但我不认为从bytes32 转换为bytes20 是一种有效的方法,因为它会删除bytes32 中的一些十六进制值。

【问题讨论】:

    标签: ethereum solidity smartcontracts hardhat uniswap


    【解决方案1】:
    I checked the [hardhat.config.ts][1] of the repo and this is the settings that have implemented:
    
    const DEFAULT_COMPILER_SETTINGS = {
      version: '0.7.6',
      settings: {
        evmVersion: 'istanbul',
        optimizer: {
          enabled: true,
          runs: 1_000_000,
        },
        metadata: {
          bytecodeHash: 'none',
        },
      },
    }
    

    然后将那些应用在

    solidity: {
        compilers: [DEFAULT_COMPILER_SETTINGS],
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2022-09-23
      • 1970-01-01
      • 2017-08-27
      • 1970-01-01
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 2014-06-17
      相关资源
      最近更新 更多