In order to do it without using the likes of Moralis. You need:
- An RPC node
- The contract address
- The wallet address
- The contract ABI
Then you can write a function like this:
async function getNFTsOfOwner() {
const contract = new ethers.Contract(contractAddress, erc721ABI, provider);
const balance = await contract.balanceOf(ownerAddress); //Returns the number of tokens owned by the address
let tokenIds = [];
for(let i = 0; i < balance.toNumber(); i++) {
const tokenId = await contract.tokenOfOwnerByIndex(ownerAddress, i); //Get the token ID based on the index from the balanceOf call
tokenIds.push(tokenId.toString());
}
console.log(`Token IDs owned by ${ownerAddress}: ${tokenIds}`);
}
At the end of this, you will have all token IDs in the tokenIds
array. If you want the metadata for the tokens you're going to need to call the tokenURI()
function for each token ID, call the URI and retrieve the metadata for each token.
It's quite a lot of work but definitely doable. If you do change your mind here is how you would do it with the Moralis getWalletNFTs endpoint.
const response = await Moralis.EvmApi.nft.getWalletNFTs({
"chain": "0x1",
"format": "decimal",
"tokenAddresses": [
"INSERT COLLECTION ADDRESS"
],
"mediaItems": false,
"address": "0xd8da6bf26964af9d7eed9e03e53415d37aa96045"
});
This would give you all NFTs with all the metadata, attributes and images directly in the response.
Disclaimer, I work at Moralis.