4

I'm trying to get all the NFTs in a collection that a wallet owns, but I only achieved get all the NFTs of a collection, or all the NFTs of a wallet (multi collections).

import { useConnection, useWallet } from "@solana/wallet-adapter-react"
import { Metaplex, walletAdapterIdentity } from "@metaplex-foundation/js"

...

const walletAdapter = useWallet()
const { connection } = useConnection()
const metaplex = Metaplex.make(connection).use(walletAdapterIdentity(walletAdapter))

// Get all NFTs of my collection
const candyMachine = await metaplex
   .candyMachinesV2()
   .findByAddress({ address: new PublicKey(candyMachineAddress) })

// Get all NFTs of wallet (My collection and others)
const walletNFTs = await metaplex
   .nfts()
   .findAllByOwner({ owner: wallet.publicKey })

Is this filter possible? I was exploring Metaplex SDK, but I didn't find this type of filter.

Thanks!

4 Answers 4

1

Try filtering for a collection address, something like the following

   // using metaplex SDK to fetch all NFTs of connected wallet
    const nfts = await metaplex
      .nfts()
      .findAllByOwner({ owner: wallet.publicKey })
     

    // filter for nfts in "collection"
    let nft = []
    for (let i = 0; i < nfts.length; i++) {
      if (nfts[i].collection?.address.toString() == collectionAddress.toString()) {
        nft.push(nfts[i])
      }
    }
1
  • Yes, this could work. But I wonder if there is a way to get this NFTs without a custom filter. If the user has hundreds of NFTs, I need to get all of them to show a few. I was finding a more performance way. It seems Metaplex doesn't have a method to this. Commented Jan 14, 2023 at 21:48
1

You can now achieve this using the DAS API on your RPC provider (although not sure if every RPC provider supports it). Use the searchAssets method with ownerAddress and grouping params.

Here's an example payload to POST to your RPC endpoint:

{
    "jsonrpc": "2.0",
    "id": "my-id",
    "method": "searchAssets",
    "params": {
        "ownerAddress": "GsXriSHaN6PK4oeP9W8kXqYHJS8JX3Hac7PUABKuWbrK",
        "grouping": [
            "collection",
            "BUjZjAS2vbbb65g7Z1Ca9ZRVYoJscURG5L3AkVvHP9ac"
        ],
        "page": 1,
        "limit": 500
    }
}
0

This returns an array of Metadata object that has a collection field. You can filter the NFTs that match the collection you're looking for.

const walletNFTs = await metaplex
   .nfts()
   .findAllByOwner({ owner: wallet.publicKey })
1
  • As I said in the other comment, this way it works. However, it is not very performant. Commented Jan 14, 2023 at 21:51
0

Try using the Alchemy getnfts method. It gives all the NFTs for a wallet. https://docs.alchemy.com/reference/getnfts

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.