fetch_account_balance.ts 1.5 KB

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