Check balance of ERC20 token in Hardhat using Ethers.js
Asked Answered
R

1

7

I'm writing unit tests using Hardhat's mainnet fork, and for a test I want to check the owner account's initial balance of an ERC20 token, in particular DAI. Here's my test so far:

const { ethers } = require("hardhat");

describe("Simple Test", function () {
    it("Check balance of DAI", async function () {
        const provider = ethers.provider;
        const [owner] = await ethers.getSigners();

        // Want to get initial DAI balance here so it can be compared later
    });
});

What's a simple way to do this?

Runnel answered 14/2, 2022 at 3:24 Comment(0)
R
15

Found what I was looking for. First thing I did was save the DAI contract address at the top:

const DAI_ADDRESS = "0x6b175474e89094c44da98b954eedeac495271d0f";

Then I had to use the ERC20 token ABI, which I placed in the same folder as my test:

const ERC20ABI = require('./ERC20.json');

Then to get the owner account's DAI balance I just called balanceOf() from the DAI contract:

const DAI = new ethers.Contract(DAI_ADDRESS, ERC20ABI, provider);
DAIBalance = await DAI.balanceOf(owner.address);

This should work for any ERC20 token as well.

Runnel answered 14/2, 2022 at 3:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.