简体   繁体   中英

Fetch all NFTs owned by wallet address with web3.js

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM