Contract-Deployment

為呼叫另一個合約的合約編寫安全帽測試

  • August 16, 2021

基本上我需要在我的契約中使用 DAI 穩定幣。我想對其進行測試,因此我複制了 DAI 智能合約程式碼並將其部署在我的本地主機上。一切正常,但我無法為我的程式碼編寫安全帽測試,因為它不知道部署在我的本地主機上的合約。在我的合約中使用另一個合約時,我應該如何編寫測試?

   address daiContractAddress = 0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0; // HOW TO GET THIS TO HARDHAT TESTS?

   function getDaiBalanceForOwner() external view returns(uint){
       IERC20 dai = IERC20(address(daiContractAddress ));
       return dai.balanceOf(msg.sender); //Error: Transaction reverted: function call to a non-contract account
   }

在@LauriPeltonen 的幫助下的最終解決方案:我只是在部署我的 dai 合約beforeEach,然後獲取它的地址並將其傳遞給合約constructor

堅固性:

address public daiContractAddress; 

constructor(address _daiContractAddress ) {
   daiContractAddress = _erc20TokenAddress;
}


function getDaiBalanceForOwner() external view returns(uint){
   IERC20 dai = IERC20(address(daiContractAddress));
   return dai.balanceOf(msg.sender);
}

EthersJS 測試:

beforeEach(async function () {
   dai = await ethers.getContractFactory("Dai"); 
   myContract= await ethers.getContractFactory("MyContract"); 
    
   dai = await dai.deploy(1); //deploying dai contract first
   
   myContract = await myContract.deploy(dai.address); //deploying my contract later using dai.address in constructor
 });

 describe("Deployment", function() {
   it("Should be able to implement usd dai stablecoin", async function() {
     expect(ethers.utils.formatEther(await myContract.getDaiBalanceForOwner())).to.equal("0.0");
   });
 });

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