Home > database >  Empty array when calling tokenOfOwnerByIndex solidity
Empty array when calling tokenOfOwnerByIndex solidity

Time:12-29

So, I've created a contract which has method which returns NFTs associated to the caller.

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

Calling it from a script


  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) // []
}

It returns an empty array. I suppose index 0 should work.

CodePudding user response:

You forgot to return the data.

I'm assuming you're using the OpenZeppelin implementation, which returns uint256. So your function should also return uint256.

// added `returns (uint256)`
function getOwnerByIndex(uint index) public view returns (uint256) {

    // added `return`
    return tokenOfOwnerByIndex(address(msg.sender), index);
}

However, the called OpenZeppelin function tokenOfOwnerByIndex() returns the token ID by the specified owner and index. Which is not what the name of your function getOwnerByIndex() suggests.

If you want to return the owner address by token index, you can use the tokenByIndex() to get the token ID, and then ownerOf() to get the owner of the token by its ID.

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