8

I am new to blockchain.

I have done a little bit research and here's my steps to fetching a list of NFTs owned by certain wallet with web3.js

balance = ERC721.methods.balanceOf(walletAddress).call();
objects = [];

for (i = 0; i < balance; i++) {
    tokens.push(await ERC721.methods.tokenOfOwnerByIndex(walletAddress, i).call());
}

for(i = 0; i < tokens.length; i++){
    objects.push(await ERC721.methods.tokenURI(tokenIdList[i]).call());
}

I can fetch a list of ERC721 token URI with the above methods but the perfomance is really poor. I am wondering how OpenSeas can achieve that with light speed performance on the same feature.

peter169
  • 109
  • 1
  • 1
  • 7

2 Answers2

1

As in most cases, storing or caching the data lowers the load time.

You can store the objects value in DB (such as MongoDB) and update it regularly - if you have a manageable amount of walletAddress items, or just for some high priority items.

You can even subscribe to event logs (in your case the Transfer event) on the token contracts and not have to poll the changes. (Maybe poll just as a fallback in case your subscription fails.)

For the rest of walletAddress items (the lower prioritized), you can cache them in a temporary storage (such as Redis). So the first load is going to be slow (because it's going to load from the external resource - as your current snippet is doing), and the other loads (until the TTL expires) are just going to be loaded from the cache, not hitting the external resource.

Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
-1

this will return all the tokens owned by this wallet in an array without having to loop:

await ERC721.methods.userOwnedTokens.call(walletAddress)

good luck! hope this helped

anthony422
  • 52
  • 4
  • 1
    i don't think i see this as part of the token standard – Shaun Chua Nov 26 '21 at 05:32
  • This methos doesn't exist anywhere in erc-721.. – Kys3r Dec 19 '21 at 10:05
  • 1
    there are multiple new API functions that fetch all owned NFTs of a certain address on different EVM chains, 1- alchemy : https://docs.alchemy.com/docs/how-to-get-all-nfts-owned-by-an-address#:~:text=To%20get%20all%20NFTs%20owned%20by%20an%20address%2C%20use%20the,to%20get%20NFT%20ownership%20data. 2- Moralis : https://docs.moralis.io/moralis-dapp/web3-api/nft-api#getnfts – anthony422 Aug 08 '22 at 09:40