getNftsForContractIterator - SDK

Fetches all NFTs for a given contract address and yields them in an async iterable. This method returns the full NFTs in the contract and pages through all page keys until all NFTs have been fetched.

Don’t have an API key?

Start using this method in your app today.

Description

Fetches all NFTs for a given contract address and yields them in an async iterable.

This method returns the full NFTs in the contract and pages through all page keys until all NFTs have been fetched. To get all NFTs without their associated metadata, use the options parameter by setting omitMetadata to true in the body of the request.

Parameters

NameTypeDescription
contractAddressstringThe contract address of the NFT contract.
optionsobjectThe optional parameters to use for the request.

options parameters

PropertyTypeDescription
pageKey?stringOptional page key from an existing OwnedBaseNftsResponse or OwnedNftsResponse to use for pagination.
pageSize?numberSets the total number of NFTs to return in the response. It defaults to 100. Maximum page size is 100.
omitMetadata?booleanOptional boolean flag to omit NFT metadata. Defaults to false.
tokenUriTimeoutInMsnumberNo set timeout by default - When metadata is requested, this parameter is the timeout (in milliseconds) for the website hosting the metadata to respond. If you want only to access the cache and not live fetch any metadata for cache misses, then set this value to 0.

Response

PropertyTypeDescription
AsyncIterable<BaseNft | Nft>objectThe NFTs for the contract

Nft response properties

PropertyTypeDescription
contractobjectThe NFT's underlying contract and relevant contract metadata.

Parameters in the contract include:

1. address: string The address of the NFT contract.
2. tokenType: object The type of the token in the contract
3. name: string The name of the contract.
4. symbol: string The symbol of the contract.
5. totalSupply?: string The number of NFTs in the contract as an integer string. This field is only available on ERC-721 contracts.
6. openSeaMetadata: object OpenSea's metadata for the contract.
7. contractDeployer?: string The address that deployed the NFT contract.
8. deployedBlockNumber?: numberThe block number the NFT contract deployed in.
9. isSpam: boolean Whether the NFT contract is marked as spam.
10. spamClassifications: arrray Potential reasons why an NFT Contract was classified as spam.
tokenIdstringThe unique identifier of the token. This could be in hexadecimal or decimal format.
tokenTypestringThe type of NFT, e.g.,ERC721, ERC1155, UNKNOWN
namestringThe NFT name.
descriptionstringThe NFT description.
timeLastUpdatedstringWhen the NFT was last updated in the blockchain. Represented in ISO-8601 format.
rawobjectThe raw metadata for the NFT based on the metadata URI on the NFT contract.

1. tokenUri?: string: The raw token URI on the NFT contract.
2. metadata: string: The raw metadata parsed from the raw token URI.
3. error?: string: Error message if the raw metadata could not be fetched.
tokenUristringURIs for accessing the NFT's metadata blob.
imageobjectMedia URLs and information for the NFT. Parameters in this object include:

1. cachedUrl: string: URL of the image stored in Alchemy's cache.
2. thumbnailUrl: string: URL of a thumbnail-sized image.
3. pngUrl: string: URL of the image in png format.
4. contentType: string: The type of the media image.
acquiredAtobjectTime at which the user most recently acquired the NFT. Only available when specifying orderBy: NftOrdering.TRANSFERTIME in the request.

1. blockTimestamp?: string: Timestamp of the block at which an NFT was last acquired.
2. blockNumber?: number: Block number of the block at which an NFT was last acquired.
collectionobjectCollection metadata for the NFT, if available. Parameters include:

1. name: string: The name of the collection.
2. slug?: string: The OpenSea human-readable slug of the collection.
3. externalUrl?: string: The external URL for the collection.
4. bannerImageUrl?: string: The banner image URL for the collection.
mintobjectMint information for the NFT. Parameters include:

1. mintAddress?: string: The address that the NFT was minted to.
2. blockNumber?: number: The block number that the NFT was minted on.
3. timestamp?: string: The timestamp the NFT was minted on.
4. transactionHash?: string: The transaction hash of the transaction that minted the NFT.

BaseNft response properties

Alchemy's representation of an NFT that doesn't contain metadata. The BaseNft object does not hold any metadata information and only contains the NFT contract and token ID. This is gotten by setting the options omitMetadata parameter to true.

PropertyTypeDescription
contractAddressstringThe contract address of the NFT.
tokenIdstringThe NFT token ID as an integer string.

Example Request and Response

Prerequisite: You will need to install the Alchemy SDK before making requests with it.

The commands for installing it using npm or yarn are given below:

npm install alchemy-sdk@latest
yarn add alchemy-sdk@latest

Request

// Imports the Alchemy SDK
const { Alchemy, Network } = require("alchemy-sdk");

// Configures the Alchemy SDK
const config = {
    apiKey: "alchemy-replit", // Replace with your API key
    network: Network.ETH_MAINNET, // Replace with your network
};

// Creates an Alchemy object instance with the config to use for making requests
const alchemy = new Alchemy(config);

const main = async () => {
    // define the contract address whose NFTs you want to fetch
    const contractAddress = "0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D";

    // create an async generator function that uses the getNftsForContractIterator method
    async function getNftsForContract() {
        try {
            let nfts = [];
            // Get the async iterable for the contract's NFTs.
            const nftsIterable = alchemy.nft.getNftsForContractIterator(contractAddress);

            // Iterate over the NFTs and add them to the nfts array.
            for await (const nft of nftsIterable) {
                nfts.push(nft);
            }

            // Log the NFTs.
            console.log(nfts);
        } catch (error) {
            console.log(error);
        }
    }

    // call the async generator function
    getNftsForContract();

};

main();

Response

[
    {
    "contract": {
        "address": "0xe785E82358879F061BC3dcAC6f0444462D4b5330",
        "name": "World Of Women",
        "symbol": "WOW",
        "totalSupply": "10000",
        "tokenType": "ERC721",
        "contractDeployer": "0xc9b6321dc216D91E626E9BAA61b06B0E4d55bdb1",
        "deployedBlockNumber": 12907782,
        "openSeaMetadata": {
            "floorPrice": 0.6021,
            "collectionName": "World of Women",
            "collectionSlug": "world-of-women-nft",
            "safelistRequestStatus": "verified",
            "imageUrl": "https://i.seadn.io/gcs/files/8604de2d9aaec98dd389e3af1b1a14b6.gif?w=500&auto=format",
            "description": "World of Women is a collection of 10,000 NFTs that gives you full access to our network of artists, creators, entrepreneurs, and executives who are championing diversity and equal opportunity on the blockchain.\n\nCreated and illustrated by Yam Karkai (@ykarkai), World of Women has made prominent appearances at Christie's, The New Yorker and Billboard.\n\nJoin us to receive exclusive access to NFT drops, experiences, and much more.\n\nThe Time is WoW.",
            "externalUrl": "http://worldofwomen.art",
            "twitterUsername": "worldofwomennft",
            "discordUrl": "https://discord.gg/worldofwomen",
            "bannerImageUrl": "https://i.seadn.io/gae/GHhptRLebBOWOy8kfXpYCVqsqdes-1-6I_jbuRnGTHHW6TD63CtciH75Dotfu2u8v6EmkWt-tjhkFRVLxRUwgMfKqqy5W24AolJayeo?w=500&auto=format",
            "lastIngestedAt": "2023-09-18T12:28:27.000Z"
        },
        "spamClassifications": []
    },
    "tokenId": "44",
    "tokenType": "ERC721",
    "name": "WoW #44",
    "tokenUri": "https://alchemy.mypinata.cloud/ipfs/QmTNBQDbggLZdKF1fRgWnXsnRikd52zL5ciNu769g9JoUP/44",
    "image": {
        "cachedUrl": "https://nft-cdn.alchemy.com/eth-mainnet/9316855d8f60a32cd44aa71f07cd7dc1",
        "thumbnailUrl": "https://res.cloudinary.com/alchemyapi/image/upload/thumbnailv2/eth-mainnet/9316855d8f60a32cd44aa71f07cd7dc1",
        "pngUrl": "https://res.cloudinary.com/alchemyapi/image/upload/convert-png/eth-mainnet/9316855d8f60a32cd44aa71f07cd7dc1",
        "contentType": "image/png",
        "size": 105117,
        "originalUrl": "https://ipfs.io/ipfs/QmUkdJKCsV8ixm2eDLJGosH8Bntwwx942YXxfuF9yXPBzi"
    },
    "raw": {
        "tokenUri": "ipfs://QmTNBQDbggLZdKF1fRgWnXsnRikd52zL5ciNu769g9JoUP/44",
        "metadata": {
            "name": "WoW #44",
            "image": "ipfs://QmUkdJKCsV8ixm2eDLJGosH8Bntwwx942YXxfuF9yXPBzi",
            "attributes": [
                {
                    "value": "Green Orange",
                    "trait_type": "Background"
                },
                {
                    "value": "Slight Smile",
                    "trait_type": "Mouth"
                },
                {
                    "value": "Purple",
                    "trait_type": "Lips Color"
                }
            ]
        }
    },
    "collection": {
        "name": "World of Women",
        "slug": "world-of-women-nft",
        "externalUrl": "http://worldofwomen.art",
        "bannerImageUrl": "https://i.seadn.io/gae/GHhptRLebBOWOy8kfXpYCVqsqdes-1-6I_jbuRnGTHHW6TD63CtciH75Dotfu2u8v6EmkWt-tjhkFRVLxRUwgMfKqqy5W24AolJayeo?w=500&auto=format"
    },
    "mint": {},
    "timeLastUpdated": "2023-09-18T13:25:41.833Z"
 }
]

Code Sandbox

You can test out the getNftsForContractIterator method using the code sandbox below:

Use Cases

Here are some potential use cases for the getNftsForContractIterator method:

  • Marketplace platforms: Marketplace platforms that enable buying and selling of NFTs often require the ability to search for specific NFTs based on contract addresses. The getNftsForContractIterator method can be used to retrieve all NFTs associated with a given contract, allowing users to browse and search for NFTs from a particular collection.

  • Wallet applications: Wallet applications that support NFTs may need to display all the NFTs owned by a user for a particular contract. The getNftsForContractIterator method can be used to retrieve all NFTs associated with a specific contract that is owned by a given address.

  • NFT explorer tools: NFT explorer tools allow users to browse and search for NFTs on the blockchain. These tools often require the ability to query the blockchain for NFTs associated with a specific contract. The getNftsForContractIterator method can be used to retrieve all NFTs associated with a given contract, which can then be displayed and searched through an explorer tool.

Related Methods

ReadMe