1

Basically I need to use DAI stablecoin in my contract. I want to test it out so I have copied the DAI smart contract code and deployed it on my localhost. Everything works fine, but I can't write Hardhat tests to my code, because it doesn't know about the contract deployed on my localhost. How should I write the tests when using another contract in my contract?

    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
    }
5
  • This isn't really a hardhat question. This is about your testing framework. Are you using web3js or ethers - for example? In any case, you can simply reference an existing contract in your tests - with ethers it's factory.at(addr) if I remember right Aug 15, 2021 at 19:26
  • @LauriPeltonen Yes, I am using ethers. I am not quite sure how to use the code you sent, could you provide some documentation for this, please? I can update my question with my hardhat code if that helps?
    – David
    Aug 15, 2021 at 19:44
  • docs.ethers.io/v5/api/contract/contract/#Contract-attach But you would probably be better off deploying the DAI in your tests in beforeEach cycle Aug 15, 2021 at 19:50
  • @LauriPeltonen You mean deploying it in beforeEach and then passing it into the original contract constructor?
    – David
    Aug 15, 2021 at 20:21
  • For example, yes Aug 16, 2021 at 4:09

1 Answer 1

3

Final solution with help of @LauriPeltonen: I am just deploying my dai contract in beforeEach and then taking its address and passing it to the contract constructor.

Solidity:

address public daiContractAddress; 

constructor(address _daiContractAddress ) {
    daiContractAddress = _daiContractAddress;
}


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

EthersJS test:

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");
    });
  });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.