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?

vadersfather
  • 243
  • 1
  • 2
  • 8

3 Answers3

26

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.

Karl Taylor
  • 103
  • 2
trizin
  • 914
  • 5
  • 11
3

you can try this

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

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

jsina
  • 111
  • 3