[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 와 같이 한다.

[ethers.js] ERC20 balance 체크

hardhat task로 만든 ERC20 잔액 확인 태스크

task("balanceERC20", "Check the balance of ERC20 token")
  .addPositionalParam("tokenAddress", "ERC20 Token contract address")
  .addPositionalParam("address", "Address to be checked")
  .setAction(async (taskArgs) => {
    const ERC20 = await ethers.getContractFactory("@openzeppelin/contracts/token/ERC20/ERC20.sol:ERC20");
    const erc20 = await ERC20.attach(taskArgs.tokenAddress);
    console.log(ethers.formatEther(await erc20.balanceOf(taskArgs.address)), await erc20.symbol());
  });

[ethers.js] Transaction details 얻기 및 ERC20 Transfer 정보 얻기

hardhat task로 만든 txHash로 transaction details 얻어서 ERC20 Transfer() 이면 정보 출력.

task("trasactionDetails", "Get the transaction deatils")
  .addPositionalParam("txHash", "Transaction Hash")
  .setAction(async (taskArgs, hre) => {
    const provider = ethers.provider;
    const transaction = await provider.getTransaction(taskArgs.txHash);
    console.log(transaction);
    if (transaction.value === 0n) {
      if (transaction.data.slice(0, 10) === "0xa9059cbb") {
        console.log("---- ERC20 Transfer -------------------------");
        await hre.run("parseERC20TransferData", { data: transaction.data });
      }
    }
  });

task("parseERC20TransferData", "Parsing")
  .addPositionalParam("data", "Transacton Data")
  .setAction(async (taskArgs) => {
    const abiCoder = new ethers.AbiCoder();
    const decodedData = abiCoder.decode(['address', 'uint256'], "0x" + taskArgs.data.slice(10));
    const to = decodedData[0];
    const value = decodedData[1].toString();

    console.log('To Address:', to);
    console.log('Token Amount:', ethers.formatEther(value));
  });