【问题标题】:Solidity try catch to detect an address typeSolidity try catch 检测地址类型
【发布时间】:2022-11-22 09:59:17
【问题描述】:

我不确定是否理解 try / catch 中的 solidity。下面的代码故意写错了,错误应该被捕获了吧?

function GetTest() external view returns (string memory)  {
        
        address _token_addr = 0x0000000000000000000000000000000000000000;
        console.log("here");
        ERC721 candidateContract = ERC721(_token_addr);
        try candidateContract.supportsInterface(0x80ac58cd) {

              console.log("try");
        }
        catch
        {
              console.log("catch");
        }
        return "";
}

捕获错误并检查地址是否具有预期类型(令牌、地址、合同)的方法是什么?

【问题讨论】:

    标签: try-catch blockchain ethereum solidity smartcontracts


    【解决方案1】:

    try/catch 语句允许您对失败的外部调用做出反应 和合同创建电话

    当您调用candidateContract.supportsInterface(0x80ac58cd)时,如果此函数恢复,您将捕获错误。例如,如果您部署那些 testCatchERC165 合约

    contract testCatch{
        function GetTest() public view returns (string memory)  {
            // this is the address of deployed ERC165 contract down below
            address _token_addr = 0x406AB5033423Dcb6391Ac9eEEad73294FA82Cfbc;
           
            ERC165 candidateContract = ERC165(_token_addr);
            try candidateContract.supportsInterface(0x80ac58cd) {
    
                 return "tried";
            }
            catch
            {
                  return "catch";
            }  
    }
    
    }
    interface IERC165 {
        function supportsInterface(bytes4 interfaceId) external view returns (bool);
    }
     
    // this contract originally was abstract but I removed it to be able to deploy
    contract ERC165 is IERC165 {
        function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
            // this require will fail
            require(2==3,"wrong calculation");
            return interfaceId == type(IERC165).interfaceId;
        }
    }
    

    当你调用 GetTest() 函数时,它会因为 require(2==3,"wrong calculation") 行而恢复

    但是,如果您从 ERC165 合同中删除了 require 行,

    contract ERC165 is IERC165 {
        function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
            return interfaceId == type(IERC165).interfaceId;
        }
    }
    

    而如果你把这个bytes4“0x80ac58cd”改成错误的bytes4“0x80ac5ccc”,如果你调用这个函数,catch就不会CATCH了。因为 supportsInterface 函数不会还原任何东西。所以 try 块中的代码将运行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      相关资源
      最近更新 更多