4

I was writing test script for a contract. I am stuck at a point where there is a claim function. whenever a user calls it, he gets the claimable ether, whatever available. The problem is when I compare the balance before and after calling the claim function, it doesn't match. One reason I can think of is the gas price that is being deducted. If this is the reason then how can I include the gas price amount in the calculation? What can be other reasons?

This is the test case.

      it("user1 can withdraw their funds", async () => {
      let balance1 = await ethers.provider.getBalance(participant1.address);
      await expect(bounty.connect(participant1).claimPrize()).to.be.fulfilled;
      expect(await ethers.provider.getBalance(participant1.address)).to.be.equal(balance1.add(ethers.utils.parseEther("2")));

    })
4
  • You can configure hardhat with 0 gas price if it can help
    – Adam Boudj
    Commented Mar 22, 2023 at 13:02
  • For now I used Talha's solution. Would love to know more about this 0 gas approach. Can you share some resources? Thanks Commented Mar 22, 2023 at 13:36
  • 1
    You can set the gasPrice on the network to 0 in your hardhat.config.js file. Simply specify the network that you're using and set the gasPrice configuration to 0. You can find more information on this configuration in Hardhat documentation here: hardhat.org/hardhat-runner/docs/config/#network-config"
    – Adam Boudj
    Commented Mar 22, 2023 at 15:37
  • Will try it out Thank you Commented Mar 22, 2023 at 16:05

1 Answer 1

0

The gas price is the reason for the balance mismatch. When a user calls a function that requires gas, the gas is deducted from their account balance. This means that the amount of ether they receive after calling the function will be less than the amount they had before the function call.

Here try this updated code

it("user1 can withdraw their funds", async () => {
  let balance1 = await ethers.provider.getBalance(participant1.address);
  let tx = await bounty.connect(participant1).claimPrize();
  let receipt = await tx.wait();
  let gasCost = receipt.gasUsed.mul(receipt.gasPrice);
  expect(await ethers.provider.getBalance(participant1.address)).to.be.equal(balance1.add(ethers.utils.parseEther("2")).sub(gasCost));
})
2
  • Thank you Talha it worked. Just a small correction. The gasPrice should be effectiveGasPrice. That's it Commented Mar 22, 2023 at 13:33
  • Thanks and Happy to help Commented Mar 23, 2023 at 5:48

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.