0

I have a smart contract with a custom token which holds some data. The Token data is defined in a struct and stored in an array:

struct Token {
    string text;
    uint256 value;
}

Token[] public _token;

On my web page I want to display all the tokens of the current user. Therefore I have a function in my smart contract which fetches all tokenIds of the given address. That function is really quick, but when I want to retrieve all Tokens from the Token[] array with the ids I get from the previous function it lasts very long! Especially if the user has many tokens...

To fetch all the tokens of the user I iterate over all tokenIds and perform the following request:

const token= await this.tokenContract.methods._token(tokenId).call();

Does anybody has an idea how to speed up the retrieval?

wero026
  • 221
  • 3
  • 11
  • Not sure if relevant, but this might help: https://ethereum.stackexchange.com/questions/17312/solidity-can-you-return-dynamic-arrays-in-a-function – Itération 122442 May 19 '20 at 14:27

1 Answers1

0

If you know the current number of tokens in your contract, then you can use Javascript's native asynchronous infrastructure:

const tokenIds = [...Array(numOfTokens).keys()];
const promises = tokenIds.map(tokenId => this.tokenContract.methods._token(tokenIds).call());
const tokens = await Promise.all(promises);

If you don't know the current number of tokens in your contract, then you can add in the contract a function which returns it:

function getNumOfTokens() public view returns (uint256) {
    return _token.length;
}
goodvibration
  • 26,003
  • 5
  • 46
  • 86