[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");
  });

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다