Search code examples
ethereumblockchainethers.jshardhaterc20

How do I transfer ERC20 tokens using Ether.js?


I'm trying to test my smart contract in Hardhat, but in order to do so I first need to send some ERC20 tokens to my contract (for this test I'm using USDC).

In my test I've impersonated a USDC whale, but how do I actually transfer the USDC to my contract?

it("USDC test", async function () {
    const testContract =
        await ethers.getContractFactory("TestContract")
            .then(contract => contract.deploy());
    await testContract.deployed();

    // Impersonate USDC whale
    await network.provider.request({
        method: "hardhat_impersonateAccount",
        params: [USDC_WHALE_ADDRESS],
    });
    const usdcWhale = await ethers.provider.getSigner(USDC_WHALE_ADDRESS);

    // Need to transfer USDC from usdcWhale to testContract
});

Solution

  • To transfer an ERC20 token you first need to deploy the token's main contract. You'll need the tokens contract address as well as the ERC20 ABI.

    const USDC_ADDRESS = "0x6262998ced04146fa42253a5c0af90ca02dfd2a3";
    const ERC20ABI = require('./ERC20ABI.json');
    
    const provider = ethers.provider;
    const USDC = new ethers.Contract(USDC_ADDRESS, ERC20ABI, provider);
    

    Then to transfer 100 USDC from usdcWhale to testContract do:

    await USDC.connect(usdcWhale).transfer(testContract.address, 100);