Logo

dev-resources.site

for different kinds of informations.

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

Published at
1/1/2025
Categories
evm
ethereum
web3
appsync
Author
block_experts_766a3a21915637
Categories
4 categories in total
evm
open
ethereum
open
web3
open
appsync
open
Author
28 person written this
block_experts_766a3a21915637
open
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


evm Article's
30 articles in total
Favicon
Ever wonder what happens when you send a transaction on Ethereum? 👀
Favicon
TEEs: The Secret Sauce Making Ethereum Rollups Faster and Simpler
Favicon
How to List Held Tokens by an Address Using the Moralis API
Favicon
Ethereum Transaction Calls and State Changes
Favicon
Creating a Toy Solidity compiler and running it in a Toy EVM
Favicon
The delegatecall Function in Solidity
Favicon
The delegatecall Function in Solidity
Favicon
ERC-4337 Shared Mempool: Official Launch on Ethereum Mainnet, Arbitrum and Optimism
Favicon
Understanding Fallback and Receive Functions in Solidity
Favicon
vyper挺好玩的
Favicon
Understanding EVM(Ethereum Virtual Machine)
Favicon
designing the skeleton
Favicon
building free speech forever
Favicon
I've made Huff docs Simple Storage page simpler for newcomers
Favicon
Polygon Nodes: Types and Usage
Favicon
BasilicaEVM: A modern dApp Stack
Favicon
EVM Reverse Engineering Challenge 0x02
Favicon
EVM Reverse Engineering Challenge 0x03
Favicon
Implementing Earned Value Management EVM in Government Projects
Favicon
EVM Reverse Engineering Challenge 0x01
Favicon
EVM Reverse Engineering Challenge 0x00
Favicon
Monad: Diving Deep into the L1 Choice
Favicon
Confidential Smart Contracts & Building w/Oasis Sapphire
Favicon
How To Setup A Berachain React Native Expo dApp With WalletConnect
Favicon
Chainsight Hands-on: Subscribe to On-Chain Events & Collect
Favicon
Creating a multi-chain voting in 30 minutes with Chainsight
Favicon
Oráculos Descentralizados em Blockchain: Conectando o Mundo Real à Blockchain.
Favicon
Swisstronick's Innovative Use Cases
Favicon
How Binary Heaps Are Utilized In A Leveraged Trading Protocol On EVM
Favicon
Deploy a Smart Contract on Polygon (MATIC)

Featured ones: