Solana check all spl token balances of a wallet

I’m using solana json rpc api to check a wallet’s token balance from my javascript app. I have used the function for it like this

const getTokenBalance = async (walletAddress, tokenMintAddress) => {
  const response = await axios({
    url: `https://api.mainnet-beta.solana.com`,
    method: "post",
    headers: { "Content-Type": "application/json" },
    data: {
      jsonrpc: "2.0",
      id: 1,
      method: "getTokenAccountsByOwner",
      params: [
        walletAddress,
        {
          mint: tokenMintAddress,
        },
        {
          encoding: "jsonParsed",
        },
      ],
    },
  });
  if (
    Array.isArray(response?.data?.result?.value) &&
    response?.data?.result?.value?.length > 0 &&
    response?.data?.result?.value[0]?.account?.data?.parsed?.info?.tokenAmount
      ?.amount > 0
  ) {
    return (
      Number(
        response?.data?.result?.value[0]?.account?.data?.parsed?.info
          ?.tokenAmount?.amount
      ) / 1000000000
    );
  } else {
    return 0;
  }
};

However I want to get all the token balance by one call instead of asking a token balance by giving a mint address for every token out there which makes my api respond like 10 minutes, is there any friendly way to do that?

I saw Covalent api can do it for checking ethereum wallet balance, wonder how they can do it

Answer

Most of the standard RPC accept batch requests, you should be able to send an array of all the requests you want, note that response will be an array as well.

// For example

const response = await axios({
    url: `https://api.mainnet-beta.solana.com`,
    method: "post",
    headers: { "Content-Type": "application/json" },
    data: [
        {
          jsonrpc: "2.0",
          id: 1,
          method: "getTokenAccountsByOwner",
          params: [
            walletAddress,
            {
              mint: tokenMintAddress,
            },
            {
              encoding: "jsonParsed",
            },
          ],
        },
        {
          jsonrpc: "2.0",
          id: 1,
          method: "getTokenAccountsByOwner",
          params: [
            walletAddress2,
            {
              mint: tokenMintAddress2,
            },
            {
              encoding: "jsonParsed",
            },
          ],
        },
    ]
});