Testing

安全帽測試:使用 ERC20 代幣的基金合約

  • February 24, 2022

我有一份正在使用安全帽測試的契約。

使用任意 ERC20 代幣(在本例中為 WETH)為該合約提供資金的好方法是什麼?

我正在使用安全帽主網分叉進行測試,我的方法是模擬一個擁有大量該令牌的帳戶並從該帳戶發送到我的合約;這不起作用,似乎我沒有成功模擬該帳戶。此外,似乎有更好的方法。

MyTest.js

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

const IERC20_SOURCE = "@openzeppelin/contracts/token/ERC20/IERC20.sol:IERC20";

const WETH_WHALE = "0xF04a5cC80B1E94C69B48f5ee68a08CD2F09A7c3E";
const WETH_ADDRESS = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";


describe("Test Contract", async () => {

 let contractToTest, wethContract;
 let admin;

 beforeEach(async () => {
       ([admin] = await ethers.getSigners());

       // Deploy contract
       const MyContract = await ethers.getContractFactory("MyContract");
       contractToTest = await MyContract.deploy();
       await contractToTest.deployed();
      
       // ~~~~~~~~~~~~~ HERE LIES THE ISSUE ~~~~~~~~~~~~

       // Send some ERC20 to my contract
       // by trying to impersonate a whale and sending stuff from their accounts
       await hre.network.provider.request({
           method: "hardhat_impersonateAccount",
           params: [WETH_WHALE],
       });
       const signer = await ethers.provider.getSigner(WETH_WHALE);
       signer.address = signer._address;
       wethContract = await hre.ethers.getContractAt(IERC20_SOURCE, WETH_ADDRESS, signer);
       wethContract = wethContract.connect(signer);

       console.log("Signer WETH balance", await wethContract.balanceOf(signer.address))
       // Signer WETH balance BigNumber { value: "480881976480357719815777" }

       // ~~~~~~~~~~~~~~~ ERROR AFTER THIS LINE :
       await wethContract.transfer(contractToTest.address, ethers.utils.parseEther("10"));
       //  InvalidInputError: sender doesn't have enough funds to send tx. 
       // The max upfront cost is: 3311216806566865328 and the sender's account only has: 0

       // WE DON'T GET HERE: 
       // check that contractToTest actually holds the 10 WETH
       expect(await wethContract.balanceOf(contractToTest.address)).to.equal(
           ethers.utils.parseEther("10"), 
           "Contract to test should hold 10 WETH!");
 });

});

hardhat.config.js


require("@nomiclabs/hardhat-waffle");
require('dotenv').config();
require("@nomiclabs/hardhat-ethers");

/**
* @type import('hardhat/config').HardhatUserConfig
*/
const { ALCHEMY_MAINNET_URL, PRIVATE_KEY } = process.env;
module.exports = {
 solidity: "0.6.12",
 defaultNetwork: "hardhat",
 networks: {
     hardhat: {
       forking: {
         url: `https://eth-mainnet.alchemyapi.io/v2/${ALCHEMY_MAINNET_URL}`,
         // accounts: [`0x${PRIVATE_KEY}`]
       }
     }
 },
};

我認為您的問題不在於您沒有將代幣發送到合約中,而是您的合約中沒有足夠的 gas 來支付交易成本。部署時,value使用此交易發送一些,以便您的合約可以為自己的交易支付費用。

引用自:https://ethereum.stackexchange.com/questions/122443