fetch_account_balance.ts 1.5 KB

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