[SOLVED] Any way to search for token ID in searchNFTs?

Is there any way to use this to search by token ID?

I’m trying:
chain: polygon
addresses: 0x67f4732266c7300cca593c814d46bee72e40659f
q: 444818

I’ve tried all the different filters but no luck. Token ID is returned in the data for other searches and it’s also in the metadata.

I could use getTokenIdMetadata to get the exact result but this is for a search bar so I’d have to compare the search string against a regex to check for all numbers so it gets a bit tricky.

If the tokenId is inside the metadata (this is often the case), then you can search for that id that way using the q search parameter. Otherwise you will have to search the results manually for that tokenId.

searchNFTs q parameter doesn’t work for token IDs when I try it.

I had to create a function to check if the search term is a number 1-999999 which assumes it’s a token ID then I use that to conditionally run a different function for the getTokenIdMetadata endpoint.

export default function containsTokenId(str: string): boolean {
  const regex =
    /^([1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9][0-9])$/;
  return regex.test(str);
}
const getSearch = async (search: string) => {
  try {
    const isTokenId = containsTokenId(search);

    if (isTokenId) {
      const queryOptions = {
          token_address: '0x.......',
          chain: 'polygon',
      };

      const options = {
          method: 'GET',
          headers: {
            accept: 'application/json',
            'X-API-Key': web3ApiKey,
          },
      };

      const url = new URL(
          `https://deep-index.moralis.io/api/v2/nft/${queryOptions.token_address}/${search}?chain=${queryOptions.chain}&format=decimal`
      );

      const res = await fetch(url, options);
      const response = await res.json();
      return response;
    }
  } catch (err) {
      console.error(err);
  }
};

You can use getTokenIdMetadata if you know the exact token id

What examples did you try?

It seems reliable using the name filter, or using name or global with another term related to the collection you’re searching (required for a tokenId below 100 but should be done anyway as there are a lot of tokens with the same ids below 10,000).

But since it’s a search against metadata, it would also include any unrelated NFTs that happen to use the same number/term, this is where you would apply additional filtering with the results.

I was mistaken, the token ID wasn’t in the metadata. It’s only in the results returned by the query.

I did a check to see if the search term is a number and used getTokenIdMetadata if it is.

I also use a debounce on the search bar to wait for the user to finish input so it’s not calling the API for every character.

function containsTokenId(str: string): boolean {
  const regex =
    /^([1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9][0-9])$/;
  return regex.test(str);
}

const searchNFT = async () => {
    try {
      if (search === '') {
        return;
      }

      const isTokenId = containsTokenId(search);

      // Moralis: getTokenIdMetadata
      if (isTokenId) {
        const queryOptions: {
          token_address: string;
          chain: string;
        } = {
          token_address: `${process.env.NEXT_PUBLIC_ADRESSS}`,
          chain: `${process.env.NEXT_PUBLIC_CHAIN}`,
        };

        const options = {
          method: 'GET',
          headers: {
            accept: 'application/json',
            'X-API-Key': web3ApiKey,
          },
        };

        const url = new URL(
          `https://deep-index.moralis.io/api/v2/nft/${queryOptions.token_address}/${search}?chain=${queryOptions.chain}&format=decimal`
        );

        const res = await fetch(url, options);

        if (!res.ok) {
          const message = `An error has occured: ${res.status}`;
          throw new Error(message);
        }

        const response = await res.json();
        const nft = response;

        const arr = [];
        arr.push(nft);

        return arr;
      }

      // Moralis: searchNFTs
      const queryOptions: {
        token_address: string;
        chain: string;
      } = {
        token_address: `${process.env.NEXT_PUBLIC_ADRESSS}`,
        chain: `${process.env.NEXT_PUBLIC_CHAIN}`,
      };

      const options = {
        method: 'GET',
        headers: {
          accept: 'application/json',
          'X-API-Key': web3ApiKey,
        },
      };

      const url = new URL(
        `https://deep-index.moralis.io/api/v2/nft/search?chain=${queryOptions.chain}&format=decimal&q=${search}&filter=name&addresses=${queryOptions.token_address}&token_address=${queryOptions.token_address}`
      );

      const res = await fetch(url, options);

      if (!res.ok) {
        const message = `An error has occured: ${res.status}`;
        throw new Error(message);
      }

      const response = await res.json();
      const nfts = response.result;

      return nfts;
    } catch (err) {
      console.error(err);
    }
  };