我正在尝试在 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
});
要转移 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);
然后要将 100 USDC 从
usdcWhale
转至 testContract
,请执行以下操作:
await USDC.connect(usdcWhale).transfer(testContract.address, 100);
如您所知,ether.js 的最新版本是“6.7.1”。 也许,使用最新版本和旧版本之间有点不同。
现在,我将使用 ether.js _v6.7.1 推荐我的代码库。 我在React项目中使用ether.js实现了USDT代币转账。
import { ethers, Signer } from "ethers";
const usdtContractAddress = "0xdac17f958d2ee523a2206206994597c13d831ec7";
const transferABI = [
{
name: "transfer",
type: "function",
inputs: [
{
name: "_to",
type: "address",
},
{
type: "uint256",
name: "_tokens",
},
],
constant: false,
outputs: [],
payable: false,
},
];
const signer: Signer = await provider.getSigner();
const token = new ethers.Contract(usdtContractAddress, transferABI, signer);
const amount = ethers.parseUnits(usdtAmount, 18);
await token
.transfer("Recipient_Wallet_Address", amount)
.then((transferResult: any) => {
console.log("transferResult", transferResult);
})
.catch((error: any) => {
console.error("Error", error);
});
希望这对您有帮助。
最好的。