Working with NFTs

Prerequisite: erc721ABI JSON file

Retrieve user NFT list

To retrieve all NFTs held in user wallet, you need a third-party tool or API.

In this example, we use Nansen API's GET /address/portfolio endpoint.

const options = {method: 'GET', headers: {accept: 'application/json'}};

fetch('https://api.nansen.ai/v1/address/portfolio', options)
  .then(res => res.json())
  .then(res => console.log(res))
  .catch(err => console.error(err));

Retrieve user NFT details

Once you know the NFT's smart-contract address (using the code above), you can get all its metadata:

import erc721ABI from './ERC721ABI.json';

const contractAddress = '0xYourNFTAddress'; // Replace with the actual contract address

async function getNFTMetadata(tokenId) {
    const tokenURI = await client.readContract({
        address: contractAddress, // Contract address of the NFT
        abi: erc721ABI,
        functionName: 'tokenURI', // Standard ERC-721 function to get metadata uri
        args: [tokenId], // User's address whose balance you want to check
    });

    const metadataResponse = await fetch(tokenURI);
    const metadata = await metadataResponse.json();
    console.log(metadata);
}

// Example usage: Get metadata for a specific token (e.g., token ID 1)
getNFTMetadata(1);

Retrieve user NFT balance

This code will allow you to check how many NFTs from a specific collection a user holds.

It is much lighted than the "Retrieve user NFT list" example that uses Nansen shown above.

import erc721ABI from './ERC721ABI.json';

async function getNFTBalance() {
  const balance = await client.readContract({
    address: '0xYourNFTAddress', // Replace with the actual NFT contract address
    abi: erc721ABI,
    functionName: 'balanceOf', // Standard ERC-721 function to get balance
    args: ['0xUserWalletAddress'], // User's address whose NFT balance you want to check
  });
  return balance.toString();
}

// Example usage
getNFTBalance().then(console.log);

Last updated