fetch_account_balance.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* eslint-disable @typescript-eslint/no-floating-promises */
  2. /* eslint-disable unicorn/prefer-top-level-await */
  3. /* eslint-disable no-console */
  4. import yargs from "yargs";
  5. import { hideBin } from "yargs/helpers";
  6. import type { PrivateKey } from "../src/core/base";
  7. import { toPrivateKey } from "../src/core/base";
  8. import { DefaultStore } from "../src/node/utils/store";
  9. const parser = yargs(hideBin(process.argv))
  10. .usage("Usage: $0 --private-key <private-key> [--chain <chain>]")
  11. .options({
  12. "private-key": {
  13. type: "string",
  14. demandOption: true,
  15. desc: "Private key to use to sign transaction",
  16. },
  17. chain: {
  18. type: "array",
  19. string: true,
  20. desc: "Chain to get the balance for. If not provided the balance for all chains is returned.",
  21. },
  22. });
  23. type AccountBalance = {
  24. chain: string;
  25. address: string | undefined;
  26. balance: number | undefined;
  27. };
  28. async function getBalance(
  29. chain: string,
  30. privateKey: PrivateKey,
  31. ): Promise<AccountBalance | undefined> {
  32. const address =
  33. await DefaultStore.chains[chain]?.getAccountAddress(privateKey);
  34. try {
  35. const balance =
  36. await DefaultStore.chains[chain]?.getAccountBalance(privateKey);
  37. return { chain, address, balance };
  38. } catch (error) {
  39. console.error(`Error fetching balance for ${chain}`, error);
  40. }
  41. return { chain, address, balance: undefined };
  42. }
  43. async function main() {
  44. const argv = await parser.argv;
  45. const chains =
  46. argv.chain ??
  47. Object.keys(DefaultStore.chains).filter((chain) => chain !== "global");
  48. const privateKey = toPrivateKey(argv["private-key"]);
  49. const balances = await Promise.all(
  50. chains.map((chain) => getBalance(chain, privateKey)),
  51. );
  52. console.table(balances);
  53. }
  54. main();