0

I'm using this function in my smart contract. It returns an uint256[] array containing the tokens that the user owns.

 /**
   * @dev Returns all of the tokens that the user owns
   * @return An array of token indices
   */
  function myTokens()
    external
    view
    returns (
      uint256[]
    )
  {
    return ownedTokens[msg.sender];
  }

In my web3 js console log, I get the below.

enter image description here

How do I read that array in my js code? Honestly, I don't understand the entire array. I just want to get the token IDs, which it supposed to return.

I'm expecting something like below as shown in Remix.

enter image description here

Here's my web3 js code.

async function retrieveTokenId(contract, walletAddress) {

  await contract.methods.myTokens().call(function(err, res){
        if(!err){
            console.log(res);
        } else {
            console.log(err);
        }
    });

}
  • can you add the web3 code you used to get the console log? – Sanjay S B May 20 at 12:40
  • I've added the web3 code. I used the exactly the same code for another method call "contract.methods.balanceOf(walletAddress).call(function(err,res){......" and it works fine. That method returns an unit256, not an array. – warnerque May 20 at 12:46
  • if you are using async await, you do not have to pass callbacks. Also the call returns your array. – Sanjay S B May 20 at 12:48
  • Sorry @SanjaySB I don't understand. I'm new to all this. You mean I should remove "async" and "await" from the function above? – warnerque May 20 at 12:51
  • Try const array = await contract.methods.myTokens().call({ from: account }); array will have your array – Sanjay S B May 20 at 12:53
0

Ok, I solved my own problem with the help of https://ethereum.stackexchange.com/users/53608/sanjay-s-b. To display the array, I just need to do the below in my js code.

async function retrieveTokenId(contract, walletAddress) {

    const array = await contract.methods.myTokens().call({
        from: walletAddress
    });

    for (i=0; i < array.length; i++) {
        console.log(array[i]);
    }

    output = JSON.stringify(array, null, 4);
    console.log(output);

}

I could either use a for loop or a JSON.stringify to display the array. Read all about it here, https://medium.com/@timothyrobards/understanding-json-in-javascript-5098876d0915

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.