|
| 1 | +import inquirer from "inquirer"; |
| 2 | + |
| 3 | +import Program from "./command.js"; |
| 4 | +import { accountOption, chainOption, zeekOption } from "../../common/options.js"; |
| 5 | +import { l2Chains } from "../../data/chains.js"; |
| 6 | +import { bigNumberToDecimal } from "../../utils/formatters.js"; |
| 7 | +import { getL2Provider, optionNameToParam } from "../../utils/helpers.js"; |
| 8 | +import Logger from "../../utils/logger.js"; |
| 9 | +import { isAddress } from "../../utils/validators.js"; |
| 10 | +import zeek from "../../utils/zeek.js"; |
| 11 | + |
| 12 | +import type { DefaultOptions } from "../../common/options.js"; |
| 13 | + |
| 14 | +type BalanceOptions = DefaultOptions & { |
| 15 | + chain?: string; |
| 16 | + l2RpcUrl?: string; |
| 17 | + address?: string; |
| 18 | +}; |
| 19 | + |
| 20 | +export const handler = async (options: BalanceOptions) => { |
| 21 | + try { |
| 22 | + const answers: BalanceOptions = await inquirer.prompt( |
| 23 | + [ |
| 24 | + { |
| 25 | + message: chainOption.description, |
| 26 | + name: optionNameToParam(chainOption.long!), |
| 27 | + type: "list", |
| 28 | + choices: l2Chains.filter((e) => e.l1Chain).map((e) => ({ name: e.name, value: e.network })), |
| 29 | + required: true, |
| 30 | + when(answers: BalanceOptions) { |
| 31 | + if (answers.l2RpcUrl) { |
| 32 | + return false; |
| 33 | + } |
| 34 | + return true; |
| 35 | + }, |
| 36 | + }, |
| 37 | + { |
| 38 | + message: accountOption.description, |
| 39 | + name: optionNameToParam(accountOption.long!), |
| 40 | + type: "input", |
| 41 | + required: true, |
| 42 | + validate: (input: string) => isAddress(input), |
| 43 | + }, |
| 44 | + ], |
| 45 | + options |
| 46 | + ); |
| 47 | + |
| 48 | + options = { |
| 49 | + ...options, |
| 50 | + ...answers, |
| 51 | + }; |
| 52 | + |
| 53 | + const selectedChain = l2Chains.find((e) => e.network === options.chain); |
| 54 | + const l2Provider = getL2Provider(options.l2RpcUrl ?? selectedChain!.rpcUrl); |
| 55 | + const balance = await l2Provider.getBalance(options.address!); |
| 56 | + |
| 57 | + Logger.info(`\n${selectedChain?.name} Balance: ${bigNumberToDecimal(balance)} ETH`); |
| 58 | + |
| 59 | + if (options.zeek) { |
| 60 | + zeek(); |
| 61 | + } |
| 62 | + } catch (error) { |
| 63 | + Logger.error("There was an error while fetching balance for the specified address:"); |
| 64 | + Logger.error(error); |
| 65 | + } |
| 66 | +}; |
| 67 | + |
| 68 | +Program.command("balance") |
| 69 | + .description("Get balance of an L2 account") |
| 70 | + .addOption(chainOption) |
| 71 | + .addOption(accountOption) |
| 72 | + .addOption(zeekOption) |
| 73 | + .action(handler); |
0 commit comments