【问题标题】:Empty array when calling tokenOfOwnerByIndex solidity调用 tokenOfOwnerByIndex solidity 时的空数组
【发布时间】:2021-12-28 17:18:15
【问题描述】:

所以,我创建了一个合约,该合约具有返回与调用者关联的 NFT 的方法。

 function getOwnerByIndex(uint index) public view {
    tokenOfOwnerByIndex(address(msg.sender), index);
  }

从脚本调用它


  const NFTContract = await hre.ethers.getContractFactory("NFTContract");
  const nftContract = await NFTContract.deploy();

  await nftContract.deployed();

  console.log("Contract deployed to:", nftContract.address);
  await nftContract.mintToken();
  await nftContract.mintToken();
  const res = await nftContract.getBalanceOf();
  console.log(res) // BigNumber { value: "2" }
  const j = await nftContract.getOwnerByIndex(0);
  console.log(j) // []
}

它返回一个空数组。我想索引 0 应该可以工作。

【问题讨论】:

    标签: javascript ethereum solidity


    【解决方案1】:

    你忘记返回数据了。

    我假设您使用的是 OpenZeppelin implementation,它返回 uint256。所以你的函数也应该返回uint256

    // added `returns (uint256)`
    function getOwnerByIndex(uint index) public view returns (uint256) {
    
        // added `return`
        return tokenOfOwnerByIndex(address(msg.sender), index);
    }
    

    但是,调用的 OpenZeppelin 函数tokenOfOwnerByIndex() 返回指定所有者和索引的令牌 ID。这不是你的函数名称getOwnerByIndex() 所暗示的。

    如果要通过token索引返回owner地址,可以使用tokenByIndex()获取token ID,然后ownerOf()通过token ID获取token的owner。

    function getOwnerByIndex(uint256 index) public view returns (address) {
        uint256 tokenId = tokenByIndex(index);
        address owner = ownerOf(tokenId);
        return owner;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-15
      • 2015-02-14
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 2022-10-16
      • 2020-03-23
      • 1970-01-01
      相关资源
      最近更新 更多