5

For getting balance I use connetion.getBalance(publicKey). Is exists way to get balance of keys list in one call, something like getBalances(publicKeys)?

2 Answers 2

3

You can use connection.getMultipleAccountsInfo([pubkey1, pubkey2, pubkey3, etc]) to load several accounts in a single RPC call, but you'll get AccountInfo instead of balance, so you need to parse the balance manually from the AccountInfo.

Once you have the accountInfo, you can get the bal with something like:

  let data: RawAccount = AccountLayout.decode(accountInfo.data);
  if (data == undefined || data.amount == undefined) {
    return 0;
  }
  let amount: BigInt = data.amount;
  return Number(amount);
3

You can loop through an array of public keys to get all balances.

Code snippet:

import { Connection, PublicKey, clusterApiUrl } from "@solana/web3.js";

const network = clusterApiUrl("devnet");

const getAllBalances = async () => {
  const publicKeys = [
    "43UyB1TMHeo4PUBodYcDXimcAsyU5gWgB6tChypeL2vC",
    "HZXnGd16Knjq2a8hLWCA2u4kXA3SQUfbwx3DPdAyCNEG",
  ];

  const connection = new Connection(clusterApiUrl("devnet"));
  
  let netBalance = 0;
  for (let index = 0; index < publicKeys.length; index++) {
    const pk = new PublicKey(publicKeys[index]);
    console.log(pk);
    const balance = await connection.getBalance(pk);
    netBalance += balance;
  }
  console.log(` netBalance = ${netBalance/LAMPORTS_PER_SOL}`);
};

If you need sum of all balances then you can use a variable to store the sum.

2
  • I searching way to request balance in one call, like connection.getBalances(keys). I know that I can multiple call for each account, I do that, but it slowly
    – Oksana
    Commented Oct 27, 2022 at 11:05
  • Note that this approach may result in being rate-limited, depending on which RPC service provider are you connecting to. Commented Nov 27, 2023 at 8:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.