Getting the list of nfts the address owns is not so easy
When we build a NFT marketplace service, we need to list nfts that the user, here the address have. But actually there is no such a sufficient way to gather them.
Today, I would like to show you a sample implementation of listing nfts logic with Etherscan API and Nodejs (Typescript).
Requirements as follows;
- Register and issue API key -> https://etherscan.io/apis
- Gather ERC-721 Transfer Events -> https://docs.etherscan.io/api-endpoints/accounts#get-a-list-of-erc721-token-transfer-events-by-address
In this example, we have done this in a simple way using the Etherscan API. Etherscan APIs are really useful and easy to use when you want to collect Ethereum event log data. But of course you can build your own Ethereum Node and collect data from them :>
Firstly, we have to say that the only way to view the nfts that an address has is to collect all erc-721 forwarding history data for that address and find it out by filtering out the nfts that have not been forwarded to other addresses. That’s why we need to collect transfer event data.
Let’s start coding!
Typescript sample implementations
0. Read API doc!
- Declare Event History Type.
2. API call logic (Recursive)
In this example, the function above takes two arguments, the first is the address to be checked for nfts, and the last is for recursive pagination. As you can see in the API docs, Etherscan API requires some pagination related parameters, and to collect all data, we need to call API recursively.
3. Filtering data
After gathering data, we need to filter them to find out which the address currently have and which are already transferred to the other. In this example, we use lodash library to calculate easily. Reduce function reduces
collection to a value which is the accumulated result of running each element in
iteratee, where each successive invocation is supplied the return value of the previous. We make a object, which key consists of contract address and tokenId, which is unique, and the value is just a number (maybe boolean flag is better). If the token is transferred to the address, increment the number, and if the token is transferred to the other address, decrement the number. Thus we can list nfts which the address currently owns.
By using the Etherscan API to filter the event data of the transfer event, we were finally able to list the nfts owned by that address. To get a list of NFTs owned by that address, by retrieving transfer events and filtering them, is not intuitive, but once implemented it is easy to understand. I hope you enjoyed this article and got some tips of NFTs!
example nft listing website: