为什么这个 Solidity 函数在断言后返回 0



我写了这个函数:

// Function to get an owned token's id by referencing the index of the user's owned tokens.
// ex: user has 5 tokens, tokenOfOwnerByIndex(owner,3) will give the id of the 4th token.
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint _tokenId) {
    // TODO: Make sure this works. Does not appear to throw when _index<balanceOf(_owner), which violates
    //       ERC721 compatibility.
    assert(_index<balanceOf(_owner)); // throw if outside range
    return ownedTokenIds[_owner][_index];
}

当以 2 _index和 balanceOf(_owner( 为 0 的_owner运行时,该函数在 Remix IDE 中返回 0。我的假设是它不会返回任何东西。我的问题是:

A( 为什么断言失败后返回 0?

B( 当我使用上述参数运行它时,如何让它不返回 0?

谢谢沃恩

删除我的另一个答案,因为它不正确。

错误处理条件不会在view函数中冒泡到客户端。它们仅用于恢复区块链上的状态更改交易。对于view函数,处理将停止,并返回指定返回类型的初始 0 值(0 表示 uint,false 表示 bool 等(。

因此,必须在客户端上处理view函数的错误处理。如果您需要能够区分有效的 0 返回值与错误,您可以执行以下操作:

function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint, bool) {
    bool success = _index < balanceOf(_owner);
    return (ownedTokenIds[_owner][_index], success);
}

最新更新