14

I've written Hardhat tests for a Solidity contract that contains a receive() external payable { ... } function.

How can I call it within the test with an Ether amount?

3 Answers 3

28

You can make a transaction and send ether to the contract address

const [owner] = await ethers.getSigners();

const transactionHash = await owner.sendTransaction({
  to: "contract address",
  value: ethers.utils.parseEther("1.0"), // Sends exactly 1.0 ether
});

Making a transaction should call the receive function.

4
  • The BigNumber type from ethers.utils.parseEther("1") is an invalid type for the params. Using toHexString() also isn't working at the moment Commented Jun 30, 2021 at 6:22
  • 1
    Thanks for letting me know, please see my updated answer.
    – trizin
    Commented Jun 30, 2021 at 12:57
  • Excellent that worked! Commented Jun 30, 2021 at 18:04
  • 2
    What method of the contract are you calling in the above answer? Commented Aug 18, 2021 at 9:48
3

you can try this

await contract.connect(account).receive({ value: ethers.utils.parseEther("1") })
2

Here's a workaround for this issue, based on Ether's version 6:


    import { ethers } from "hardhat";
    import { expect } from "chai";
    import { parseEther } from "ethers";
            
    it("Should be deployed and have a balance of 1000000000000000000.", async function () {
      const faucet = await ethers.deployContract("Faucet");
      await faucet.waitForDeployment();
        
      const deployedAddress = await faucet.getAddress();
      const [owner] = await ethers.getSigners();
        
      const tx = {
        to: deployedAddress,
        value: parseEther("1.0"),
      };
      await owner.sendTransaction(tx);
        
      const contractBalance = await ethers.provider.getBalance(deployedAddress);
      expect(contractBalance).to.equal(parseEther("1.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.