DEV Community

Cover image for How to List Held Tokens by an Address Using the Moralis API
Block Experts
Block Experts

Posted on

How to List Held Tokens by an Address Using the Moralis API

If you're working on a dApp or any blockchain project, you may want to fetch the tokens and NFTs held by a specific address. Using the Moralis API or any other solution. In this article, we’ll walk through a simple implementation in TypeScript that lists all ERC-20 tokens and NFTs held by a wallet address.

Prerequisites

  1. Node.js Installed: Make sure you have Node.js installed on your system.
  2. Moralis API Key: Sign up at Moralis to get your free API key.
  3. Project Setup: Create a new project and install the Moralis package.
npm install moralis
Enter fullscreen mode Exit fullscreen mode

Code to Fetch Wallet Assets

Below is the complete implementation to fetch ERC-20 tokens and NFTs using Moralis.

Importing Dependencies

We use the Moralis SDK to interact with blockchain data. Start by importing the required package and defining the types for token balances and NFTs:

import Moralis from "moralis";

export interface TokenBalance {
    tokenAddress: string;
    name: string;
    symbol: string;
    balance: string;
    decimals: number;
}

export interface NFT {
    tokenAddress: string;
    tokenId: string;
    metadata: string | null;
    name: string;
    symbol: string;
}

interface WalletAssets {
    erc20Tokens: TokenBalance[];
    nfts: NFT[];
}
Enter fullscreen mode Exit fullscreen mode

Fetching Tokens and NFTs

Here’s the main function to fetch wallet assets:

export async function getWalletAssets(address: string, chainId: number): Promise<WalletAssets> {

    if (!Moralis.Core.isStarted) {
        await Moralis.start({
            apiKey: MORALIS_API_KEY, // Replace with your Moralis API key
        });
    }

    // Fetch ERC-20 Tokens Or any EVM compatible ERC20
    const erc20Response = await Moralis.EvmApi.token.getWalletTokenBalances({ address, chain: chainId });
    const erc20Tokens: TokenBalance[] = erc20Response.raw.map((token: any) => ({
        tokenAddress: token.token_address,
        name: token.name,
        symbol: token.symbol,
        balance: token.balance,
        decimals: token.decimals,
    }));

    // Fetch NFTs Or any EVM compatible NFT
    const nftResponse = await Moralis.EvmApi.nft.getWalletNFTs({ address });
    const nfts: NFT[] = nftResponse.raw.result.map((nft: any) => ({
        tokenAddress: nft.token_address,
        tokenId: nft.token_id,
        metadata: nft.metadata,
        name: nft.name,
        symbol: nft.symbol,
    }));

    return { erc20Tokens, nfts };
}
Enter fullscreen mode Exit fullscreen mode

Example Usage

To use this function, provide a wallet address and a chain ID. For instance:

(async () => {
    const address = "0xYourWalletAddressHere"; // Replace with the wallet address
    const chainId = 1; // Ethereum Mainnet

    try {
        const assets = await getWalletAssets(address, chainId);
        console.log("ERC-20 Tokens:", assets.erc20Tokens);
        console.log("NFTs:", assets.nfts);
    } catch (error) {
        console.error("Error fetching wallet assets:", error);
    }
})();
Enter fullscreen mode Exit fullscreen mode

Breakdown of the Code

1. Initializing Moralis

Before using any Moralis API methods, ensure the SDK is initialized with your API key:

if (!Moralis.Core.isStarted) {
    await Moralis.start({
        apiKey: process.env.NEXT_PUBLIC_MORALIS_APP_KEY,
    });
}
Enter fullscreen mode Exit fullscreen mode

2. Fetching ERC-20 Tokens

The getWalletTokenBalances method retrieves the list of ERC-20 tokens held by the address:

const erc20Response = await Moralis.EvmApi.token.getWalletTokenBalances({ address, chain: chainId });
Enter fullscreen mode Exit fullscreen mode

3. Fetching NFTs

Similarly, the getWalletNFTs method retrieves the NFTs owned by the address:

const nftResponse = await Moralis.EvmApi.nft.getWalletNFTs({ address });
Enter fullscreen mode Exit fullscreen mode

4. Mapping the Data

Both responses are mapped into the TokenBalance and NFT types, ensuring clean and type-safe outputs.

Conclusion

With just a few lines of code, you can list all tokens and NFTs held by an address using Moralis. This method works seamlessly with Ethereum and other EVM-compatible blockchains supported by Moralis. The flexibility and simplicity of the Moralis API make it an excellent choice for developers building blockchain-based applications.

Have you tried fetching wallet data using Moralis or any other API or by filtering the transfer events which require a lot of resources? Share your experience or ask questions in the comments below!


🌟 Useful Tools for Blockchain Developers


Top comments (0)