1

How to find all the NFTs of a certain collection, ERC721 and ERC1155, owned by address ? In ethers.js

update #1

Let's say, I'm an owner of an NFT collection who sells them via my website.

When user comes to my website and logs in with his wallet, won't I be able to find out what NFTs of my collection he's a holder of?


I could upgrade an NFT smart contract if needed.

2 Answers 2

2

This requires indexing the blockchain. This is fairly simple using Moralis APIs. https://docs.moralis.io/web3-data-api/evm/how-to-get-nft-owners-by-an-address

Alternative, you can do this using ethers.js:

const { ethers } = require('ethers');

const networkUrl = 'https://eth-mainnet.your-moralis-server.com/APIKEY';
const provider = new ethers.providers.JsonRpcProvider(networkUrl);
const contractAddress = '0x...'; // Replace with the actual contract address
const abi = [...]; // Replace with the ABI of the ERC721 or ERC1155 contract

const contract = new ethers.Contract(contractAddress, abi, provider);

For ERC721: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/ffceb3cd988874369806139ae9e59d2e2a93daec/contracts/token/ERC721/ERC721.sol#L60

const ownerAddress = '0x...'; // Replace with the owner's address

const balance = await contract.balanceOf(ownerAddress);

For ERC1155: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/ffceb3cd988874369806139ae9e59d2e2a93daec/contracts/token/ERC1155/ERC1155.sol#L78

const ownerAddress = '0x...'; // Replace with the owner's address
const tokenIds = [1, 2, 3]; // Replace with the desired token IDs

const balances = await contract.balanceOfBatch([ownerAddress], tokenIds);

The balance or balances variable will contain the number of NFTs owned by the address. You can then loop through the token IDs.

4
  • Another question: How can an owner of a collection list all the NFTs in it?
    – Camila326
    Jun 5, 2023 at 0:37
  • @lordarora I'm deleting the comment you flagged. If you are affiliated with Moralis, you also need to mention it in your answer.
    – eth
    Jun 10, 2023 at 0:47
  • 1
    if I was I would have but I'll take that as a compliment @eth
    – lordarora
    Jun 11, 2023 at 5:46
  • Another question: How can an owner of a collection list all the NFTs in it?
    – Camila326
    Jun 11, 2023 at 19:28
0

Use a Node as a service that provides additional NFT endpoints. I like to use alchemy. It provides the getNFTsForOwner endpoint that does the job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.