简体   繁体   English

使用 web3.js 获取钱包地址拥有的所有 NFT

[英]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我做了一些研究,这是我使用 web3.js 获取某个钱包拥有的 NFT 列表的步骤

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.我可以使用上述方法获取 ERC721 令牌 URI 列表,但性能确实很差。 I am wondering how OpenSeas can achieve that with light speed performance on the same feature.我想知道 OpenSeas 如何在相同功能上以光速性能实现这一目标。

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.您可以将objects值存储在 DB(例如 MongoDB)中并定期更新 - 如果您有可管理数量的walletAddress项目,或者只是一些高优先级项目。

You can even subscribe to event logs (in your case the Transfer event) on the token contracts and not have to poll the changes.您甚至可以订阅令牌合约上的事件日志(在您的情况下为Transfer事件),而不必轮询更改。 (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).对于walletAddress项(优先级较低)的 rest,您可以将它们缓存在临时存储中(例如 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.所以第一次加载会很慢(因为它将从外部资源加载 - 正如您当前的代码片段所做的那样),而其他加载(直到 TTL 到期)只会从缓存中加载,而不是命中外部资源。

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希望这有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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