如何使用 Ether.js 转移 ERC20 代币?

Jas*_*ran 1 blockchain ethereum erc20 ethers.js hardhat

我正在尝试在 Hardhat 中测试我的智能合约,但为了做到这一点,我首先需要向我的合约发送一些 ERC20 代币(对于此测试,我使用 USDC)。

在我的测试中,我模拟了 USDC 鲸鱼,但如何实际将 USDC 转移到我的合约中?

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
});
Run Code Online (Sandbox Code Playgroud)

Jas*_*ran 12

要转移 ERC20 代币,您首先需要部署代币的主合约。您将需要代币合约地址以及ERC20 ABI

const USDC_ADDRESS = "0x6262998ced04146fa42253a5c0af90ca02dfd2a3";
const ERC20ABI = require('./ERC20ABI.json');

const provider = ethers.provider;
const USDC = new ethers.Contract(USDC_ADDRESS, ERC20ABI, provider);
Run Code Online (Sandbox Code Playgroud)

然后从usdcWhaleto转入 100 USDC testContract

await USDC.connect(usdcWhale).transfer(testContract.address, 100);
Run Code Online (Sandbox Code Playgroud)