admin管理员组

文章数量:1406759

I tried to get all token information in my wallet using solana/web3 but I can't get it.

I need token address, token amount, token price, token name, token symbol at least.

How can I get this data?

This is my current code that gets the token mint address and amount.

const getTokenFromTokenAccount = async (tokenAccount) => {
  const Ta = new PublicKey(tokenAccount);
  const AccInfo = await connection.getParsedAccountInfo(Ta, {
    commitment: "confirmed",
  });

  const splData = AccInfo.value?.data;
  let splToken = "";
  if (splData && "parsed" in splData) {
    const parsed = splData.parsed;
    splToken = parsed.info.mint;
    amount = parsed.info.tokenAmount.uiAmount;

    return { mint: splToken, amount: amount };
  }
};

const getAllTokenInfo = async () => {
  const wallet = new PublicKey("pkrQznmnts6q3vDfbDwuaj5JPqGmjiC6gJfx4xcAv5n");
  const tokenProgramId = new PublicKey(
    "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" // SPL TOKEN - TOKEN_PROGRAM_ID
  );
  const token2022ProgramId = new PublicKey(
    "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb" // TOKEN 2022 - TOKEN_PROGRAM_ID
  );

  let tokenAccounts = [];

  const splTokenAccounts = await connection.getTokenAccountsByOwner(wallet, {
    programId: tokenProgramId,
  });
  const token2022Accounts = await connection.getTokenAccountsByOwner(wallet, {
    programId: token2022ProgramId,
  });

  tokenAccounts = [...splTokenAccounts.value, ...token2022Accounts.value];

  let tokenInfoArray = [];
  for (let i = 0; i < tokenAccounts.length; i++) {
    const tokenInfo = await getTokenFromTokenAccount(
      tokenAccounts[i].pubkey.toBase58()
    );
    tokenInfoArray.push(tokenInfo);
  }
  return tokenInfoArray;
};

I tried to get all token information in my wallet using solana/web3 but I can't get it.

I need token address, token amount, token price, token name, token symbol at least.

How can I get this data?

This is my current code that gets the token mint address and amount.

const getTokenFromTokenAccount = async (tokenAccount) => {
  const Ta = new PublicKey(tokenAccount);
  const AccInfo = await connection.getParsedAccountInfo(Ta, {
    commitment: "confirmed",
  });

  const splData = AccInfo.value?.data;
  let splToken = "";
  if (splData && "parsed" in splData) {
    const parsed = splData.parsed;
    splToken = parsed.info.mint;
    amount = parsed.info.tokenAmount.uiAmount;

    return { mint: splToken, amount: amount };
  }
};

const getAllTokenInfo = async () => {
  const wallet = new PublicKey("pkrQznmnts6q3vDfbDwuaj5JPqGmjiC6gJfx4xcAv5n");
  const tokenProgramId = new PublicKey(
    "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" // SPL TOKEN - TOKEN_PROGRAM_ID
  );
  const token2022ProgramId = new PublicKey(
    "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb" // TOKEN 2022 - TOKEN_PROGRAM_ID
  );

  let tokenAccounts = [];

  const splTokenAccounts = await connection.getTokenAccountsByOwner(wallet, {
    programId: tokenProgramId,
  });
  const token2022Accounts = await connection.getTokenAccountsByOwner(wallet, {
    programId: token2022ProgramId,
  });

  tokenAccounts = [...splTokenAccounts.value, ...token2022Accounts.value];

  let tokenInfoArray = [];
  for (let i = 0; i < tokenAccounts.length; i++) {
    const tokenInfo = await getTokenFromTokenAccount(
      tokenAccounts[i].pubkey.toBase58()
    );
    tokenInfoArray.push(tokenInfo);
  }
  return tokenInfoArray;
};
Share asked Mar 5 at 18:21 saburo111saburo111 433 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 3

In general, you can easily get all token list and information in your wallet using your Birdeye API.

Please check this:

const axios = require("axios");
const dotenv = require("dotenv");

dotenv.config();

const BIRDEYE_API_KEY = process.env.BIRDEYE_API_KEY;

async function getTokenOverview(tokenAddress) {
  const res = await axios.get(
    "https://public-api.birdeye.so/defi/token_overview",
    {
      params: { address: tokenAddress },
      headers: {
        accept: "application/json",
        "x-chain": "solana",
        "x-api-key": BIRDEYE_API_KEY,
      },
    }
  );
  if (res.data?.success) {
    return res.data?.data;
  } else {
    return null;
  }
}


async function getWalletTokenList(walletAddress) {
  const res = await axios.get(
    "https://public-api.birdeye.so/v1/wallet/token_list",
    {
      params: { wallet: walletAddress },
      headers: {
        accept: "application/json",
        "x-chain": "solana",
        "x-api-key": BIRDEYE_API_KEY,
      },
    }
  );
  if (res.data?.success) {
    return res.data?.data;
  } else {
    return null;
  }
}

module.exports = {
  getTokenOverview,
  getWalletTokenList,
}

Also, tokenPrice varies slightly from DEX to DEX.

I hope this helps you.

For the token name and symbol, you will get them from the metadata. For the price, you should use any third-party API to fetch the token price based on the respective pool data. Here is a modified code that will help you.

import { Connection, PublicKey, clusterApiUrl } from '@solana/web3.js';
import fetch from 'node-fetch';

// Initialize connection
const connection = new Connection(clusterApiUrl('mainnet-beta'), 'confirmed');

// Function to fetch token metadata from Jupiter API
async function getTokenMetadata(mintAddress) {
    try {
        // Jupiter token list API - provides comprehensive Solana token data
        const response = await fetch('https://token.jup.ag/all');
        const tokenList = await response.json();

        // Find the token in the list
        const tokenInfo = tokenList.find(
            (token) => token.address === mintAddress
        );

        if (tokenInfo) {
            return {
                name: tokenInfo.name,
                symbol: tokenInfo.symbol,
                logoURI: tokenInfo.logoURI,
                decimals: tokenInfo.decimals,
            };
        }

        // If token is not found in Jupiter, try the Solana token list
        try {
            const solResponse = await fetch(
                'https://cdn.jsdelivr/gh/solana-labs/token-list@main/src/tokens/solana.tokenlist.json'
            );
            const solTokenList = await solResponse.json();

            const solTokenInfo = solTokenList.tokens.find(
                (token) => token.address === mintAddress
            );

            if (solTokenInfo) {
                return {
                    name: solTokenInfo.name,
                    symbol: solTokenInfo.symbol,
                    logoURI: solTokenInfo.logoURI,
                    decimals: solTokenInfo.decimals,
                };
            }
        } catch (err) {
            console.log(`Solana token list fetch failed: ${err.message}`);
        }

        // For tokens not in either list, fetch token supply to at least get decimals
        try {
            const tokenSupply = await connection.getTokenSupply(
                new PublicKey(mintAddress)
            );
            const decimals = tokenSupply.value.decimals;

            // Attempt to fetch from Birdeye
            try {
                const birdeyeResponse = await fetch(
                    `https://public-api.birdeye.so/public/tokenlist/solana?address=${mintAddress}`
                );
                const birdeyeData = await birdeyeResponse.json();

                if (birdeyeData.success && birdeyeData.data.length > 0) {
                    const tokenData = birdeyeData.data[0];
                    return {
                        name:
                            tokenData.name ||
                            `Token ${mintAddress.slice(0, 8)}...`,
                        symbol: tokenData.symbol || 'UNKNOWN',
                        logoURI: tokenData.logoURI || null,
                        decimals: decimals,
                    };
                }
            } catch (birdErr) {
                console.log(`Birdeye fetch failed: ${birdErr.message}`);
            }

            return {
                name: `Token ${mintAddress.slice(0, 8)}...`,
                symbol: 'UNKNOWN',
                logoURI: null,
                decimals: decimals,
            };
        } catch (err) {
            console.log(`Token supply fetch failed: ${err.message}`);
        }

        // Default fallback
        return {
            name: `Token ${mintAddress.slice(0, 8)}...`,
            symbol: 'UNKNOWN',
            logoURI: null,
            decimals: 0,
        };
    } catch (error) {
        console.error(`Error in getTokenMetadata for ${mintAddress}:`, error);
        return {
            name: mintAddress.slice(0, 10) + '...',
            symbol: 'UNKNOWN',
            logoURI: null,
            decimals: 0,
        };
    }
}

// Function to fetch token price from multiple sources
async function getTokenPrice(mintAddress, symbol) {
    try {
        // Try Birdeye API first (public endpoint, no API key required for basic data)
        try {
            const birdeyeResponse = await fetch(
                `https://public-api.birdeye.so/public/price?address=${mintAddress}`
            );
            const birdeyeData = await birdeyeResponse.json();

            if (
                birdeyeData.success &&
                birdeyeData.data &&
                birdeyeData.data.value
            ) {
                return birdeyeData.data.value;
            }
        } catch (birdErr) {
            console.log(`Birdeye price fetch failed: ${birdErr.message}`);
        }

        // Try CoinGecko as fallback for well-known tokens
        if (symbol && symbol !== 'UNKNOWN') {
            try {
                // Common mappings for well-known tokens
                const commonMappings = {
                    SOL: 'solana',
                    USDC: 'usd-coin',
                    USDT: 'tether',
                    ETH: 'ethereum',
                    BTC: 'bitcoin',
                    BONK: 'bonk',
                    JUP: 'jupiter',
                    RAY: 'raydium',
                    SRM: 'serum',
                };

                const coinId = commonMappings[symbol] || symbol.toLowerCase();

                const geckoResponse = await fetch(
                    `https://api.coingecko/api/v3/simple/price?ids=${coinId}&vs_currencies=usd`
                );
                const geckoData = await geckoResponse.json();

                if (geckoData[coinId] && geckoData[coinId].usd) {
                    return geckoData[coinId].usd;
                }
            } catch (geckoErr) {
                console.log(
                    `CoinGecko price fetch failed: ${geckoErr.message}`
                );
            }
        }

        // Hardcoded fallbacks for very common tokens
        const knownTokens = {
            So11111111111111111111111111111111111111112: 100.5, // SOL (example price)
            EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: 1.0, // USDC
            Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB: 1.0, // USDT
        };

        if (knownTokens[mintAddress]) {
            return knownTokens[mintAddress];
        }

        return null; // Price not available
    } catch (error) {
        console.error(`Error fetching price for ${mintAddress}:`, error);
        return null;
    }
}

// Function to get all token information
const getAllTokenInfo = async () => {
    try {
        const wallet = new PublicKey(
            'pkrQznmnts6q3vDfbDwuaj5JPqGmjiC6gJfx4xcAv5n'
        );
        const tokenProgramId = new PublicKey(
            'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' // SPL TOKEN - TOKEN_PROGRAM_ID
        );
        const token2022ProgramId = new PublicKey(
            'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' // TOKEN 2022 - TOKEN_PROGRAM_ID
        );

        // Get parsed SPL token accounts
        const parsedSplTokenAccounts =
            await connection.getParsedTokenAccountsByOwner(wallet, {
                programId: tokenProgramId,
            });
        console.log(
            `Found ${
                parsedSplTokenAccounts.value?.length || 0
            } SPL token accounts`
        );

        // Get Token-2022 accounts
        const token2022Accounts = await connection.getTokenAccountsByOwner(
            wallet,
            {
                programId: token2022ProgramId,
            }
        );
        console.log(
            `Found ${token2022Accounts.value?.length || 0} Token-2022 accounts`
        );

        let tokenInfoArray = [];

        // Process SPL token accounts with the parsed data
        for (const item of parsedSplTokenAccounts.value || []) {
            if (!item || !item.pubkey || !item.account) {
                console.log('Found an invalid token account entry:', item);
                continue;
            }

            const { pubkey, account } = item;
            const accountData = account.data;

            if (accountData && accountData.parsed && accountData.parsed.info) {
                const tokenAmount = accountData.parsed.info.tokenAmount;
                const mint = accountData.parsed.info.mint;
                const amount = tokenAmount.uiAmount || 0;

                // Get token metadata
                const metadata = await getTokenMetadata(mint);

                console.log(metadata);
                console.log('=============================================');
                console.log(
                    `Fetched metadata for ${mint}: ${metadata.name} (${metadata.symbol})`
                );

                // Get token price
                const price = await getTokenPrice(mint, metadata.symbol);
                console.log(`Fetched price for ${metadata.symbol}: ${price}`);

                tokenInfoArray.push({
                    address: pubkey.toBase58(),
                    mint: mint,
                    amount: amount,
                    name: metadata.name,
                    symbol: metadata.symbol,
                    decimals: metadata.decimals,
                    price: price || 'Unknown',
                    value: price ? price * amount : 'Unknown',
                    logoURI: metadata.logoURI,
                });
            }
        }

        // Process Token-2022 accounts
        for (let i = 0; i < (token2022Accounts.value?.length || 0); i++) {
            if (
                !token2022Accounts.value[i] ||
                !token2022Accounts.value[i].pubkey
            ) {
                console.log(
                    'Found an invalid Token-2022 account entry:',
                    token2022Accounts.value[i]
                );
                continue;
            }

            const tokenInfo = await getTokenFromTokenAccount(
                token2022Accounts.value[i].pubkey.toBase58()
            );

            if (tokenInfo) {
                // Get token metadata
                const metadata = await getTokenMetadata(tokenInfo.mint);
                console.log(
                    `Fetched metadata for ${tokenInfo.mint}: ${metadata.name} (${metadata.symbol})`
                );

                // Get token price
                const price = await getTokenPrice(
                    tokenInfo.mint,
                    metadata.symbol
                );
                console.log(`Fetched price for ${metadata.symbol}: ${price}`);

                tokenInfoArray.push({
                    address: token2022Accounts.value[i].pubkey.toBase58(),
                    mint: tokenInfo.mint,
                    amount: tokenInfo.amount,
                    name: metadata.name,
                    symbol: metadata.symbol,
                    decimals: metadata.decimals,
                    price: price || 'Unknown',
                    value: price ? price * tokenInfo.amount : 'Unknown',
                    logoURI: metadata.logoURI,
                });
            }
        }

        return tokenInfoArray;
    } catch (error) {
        console.error('Error in getAllTokenInfo:', error);
        return [];
    }
};

// Function to get token information from a token account
const getTokenFromTokenAccount = async (tokenAccount) => {
    try {
        const Ta = new PublicKey(tokenAccount);
        const AccInfo = await connection.getParsedAccountInfo(Ta, {
            commitment: 'confirmed',
        });

        const splData = AccInfo.value?.data;
        let splToken = '';
        let amount = 0;

        if (splData && 'parsed' in splData) {
            const parsed = splData.parsed;
            if (parsed && parsed.info && parsed.info.mint) {
                splToken = parsed.info.mint;
                amount = parsed.info.tokenAmount?.uiAmount || 0;
                return { mint: splToken, amount: amount };
            }
        }

        console.log(`Could not parse data for token account: ${tokenAccount}`);
        return { mint: 'unknown', amount: 0 };
    } catch (error) {
        console.error(`Error fetching token account ${tokenAccount}:`, error);
        return { mint: 'error', amount: 0 };
    }
};

// Run the function
(async () => {
    try {
        console.log('Fetching token information...');
        const allTokens = await getAllTokenInfo();
        console.log(`Retrieved information for ${allTokens.length} tokens`);

        // Display token information
        allTokens.forEach((token, index) => {
            console.log(`\nToken ${index + 1}:`);
            console.log(`Name: ${token.name}`);
            console.log(`Symbol: ${token.symbol}`);
            console.log(`Address: ${token.address}`);
            console.log(`Mint: ${token.mint}`);
            console.log(`Amount: ${token.amount}`);
            console.log(`Decimals: ${token.decimals}`);
            console.log(
                `Price: ${
                    typeof token.price === 'number'
                        ? `$${token.price.toFixed(4)}`
                        : token.price
                }`
            );
            console.log(
                `Value: ${
                    typeof token.value === 'number'
                        ? `$${token.value.toFixed(2)}`
                        : token.value
                }`
            );
            if (token.logoURI) {
                console.log(`Logo: ${token.logoURI}`);
            }
        });

        // Calculate total portfolio value
        const totalValue = allTokens.reduce((total, token) => {
            if (typeof token.value === 'number') {
                return total + token.value;
            }
            return total;
        }, 0);

        console.log(`\nTotal Portfolio Value: $${totalValue.toFixed(2)}`);
    } catch (error) {
        console.error('Error running the script:', error);
    }
})();

本文标签: javascriptHow can I get all token information in my Solana walletStack Overflow