[hardhat/ethers.js] getLedgerSigner

import { subtask } from "hardhat/config";
import { LedgerSigner } from "@ethers-ext/signer-ledger";
import HIDTransport from "@ledgerhq/hw-transport-node-hid";

const USE_LEDGER = {
  "61331819613419": true,
  "2022": true
};

subtask("getLedgerSigner", "Get LedgerSigner")
  .addOptionalPositionalParam("accountNumber", "Account number of the Ledger", "0")
  .setAction(async (taskArgs) => {
    const accountNumber = taskArgs.accountNumber;
    const chainId = (await ethers.provider.getNetwork()).chainId;
    const ledgerNeeded = USE_LEDGER[chainId] ?? false;
    console.log("ChainID:", chainId, "LedgerNeeded:", ledgerNeeded);
    if (ledgerNeeded) {
      const _master = new LedgerSigner(HIDTransport, ethers.provider, `m/44'/60'/${accountNumber}'/0/0`);
      _master.getFeeData = async () => {
        return {
            gasPrice: ethers.BigNumber.from(0),
            lastBaseFeePerGas: ethers.BigNumber.from(0),
            maxFeePerGas: ethers.utils.parseUnits("800", "gwei"),
            maxPriorityFeePerGas: ethers.utils.parseUnits("800", "gwei"),
        };
      };
      console.log(`LedgerSinger: m/44'/60'/${accountNumber}'/0/0:`, await _master.getAddress());
      _master.getBalance = async function() {
        return await this.provider.getBalance(this.getAddress());
      };

      return _master;
    }

    const accounts = await ethers.getSigners();
    return accounts[accountNumber];
  });

사용할 때는 hre를 이용해서 다음과 같이 하면 된다.

import { task } from "hardhat/config";
import './subtasks/getLedgerSigner';

task("ledgerBalance", "Prints an account's balance")
  .addOptionalPositionalParam("accountNumber", "The account number of the ledger", "0")
  .setAction(async (taskArgs) => {
    const signer = await hre.run("getLedgerSigner", { accountNumber: taskArgs.accountNumber });
    console.log("Signer Address:", await signer.getAddress());
    const balance = await signer.getBalance();

    console.log(ethers.utils.formatEther(balance), "ETH");
  });

[hardhat/ethers.js] HW Ledger 체크

ethers.js v5 기준 hardhat 태스크

import { LedgerSigner } from "@anders-t/ethers-ledger";
import { task } from "hardhat/config";

task("checkHW", "Check HW Wallet")
  .addOptionalPositionalParam("accountNumber", "Index of the address of the HW wallet")
  .setAction(async (taskArgs) => {
  const accountNumber = taskArgs.accountNumber;
    const _master = new LedgerSigner(ethers.provider, `m/44'/60'/${accountNumber}'/0/0`);
  _master.getFeeData = async () => {
    return {
      gasPrice: ethers.BigNumber.from(0),
      lastBaseFeePerGas: ethers.BigNumber.from(0),
      maxFeePerGas: ethers.utils.parseUnits("800", "gwei"),
      maxPriorityFeePerGas: ethers.utils.parseUnits("800", "gwei"),
    };
  };
  const master = _master;

  console.log(`HW Ledger: [${accountNumber}]:${await master.getAddress()}: ${ethers.utils.formatEther(await master.getBalance())} ETH`);
});

사용은 hh checkHW 0 와 같이 한다.