1

Hardhat testing

1) stakeEther
       should transfer ether and update balances correctly:
     TypeError: receipt.gasUsed.mul is not a function
      at Context.<anonymous> (test\Test.js:53:37)
      at processTicksAndRejections (node:internal/process/task_queues:96:5)
describe("stakeEther", function () {
  it("should transfer ether and update balances correctly", async function () {
    let contractBalance = await ethers.provider.getBalance(
      stakingContract.getAddress()
    );

    let signerBalance = await ethers.provider.getBalance(deployer.getAddress()); // Use 'address' property instead of 'getAddress()'
    const transferAmount = ethers.parseEther("2.0");

    const data = { value: transferAmount };
    const transaction = await stakingContract
      .connect(deployer)
      .stakeEther(30, data);

    const receipt = await transaction.wait();

    const gasUsed = receipt.gasUsed.mul(receipt.effectiveGasPrice);

    // test the change in deployer ether balance
    expect(await deployer.getBalance()).to.equal(
      signerBalance.sub(transferAmount).sub(gasUsed)
    );

    // test the change in contract ether balance
    expect(
      await ethers.provider.getBalance(stakingContract.getAddress())
    ).to.equal(contractBalance.add(transferAmount));
  });
});

I am trying to calculate the gas cost through transaction.wait().

I don't understand why this function is not working.

Hence I am using latest ethers and hardhat versions.

Please provide solutions.

1
  • You can try const gasUsed = BigNumber.from(receipt.gasUsed).mul(receipt.effectiveGasPrice);. See if the error changes at least
    – 0xSanson
    Commented Jul 20, 2023 at 20:53

2 Answers 2

2

Things have changed in ethers v6 as compared to ethers v5.

In ethers version 5, we have to use these functions such as add() , mul(),div() etc , but in ethers version 6, javascript takes cares of all the things, you don't need to use these function inseted just use regulat + ,- ,* ,/

Replace the code where these functions have been used

//first change
const gasUsed = receipt.gasUsed * receipt.effectiveGasPrice ; 

//2nd change
    expect(await deployer.getBalance()).to.equal((
      signerBalance-transferAmount)-gasUsed
    );

    // test the change in contract ether balance
    expect(
      await ethers.provider.getBalance(stakingContract.getAddress())
    ).to.equal(contractBalance + transferAmount);

0

It came to me while debugging receipt that u should make following changes :

const gasUsed = receipt.gasUsed * receipt.gasPrice;

Since, receipt provides gasPrice instead of effectiveGasPrice. Also, gasPrice is of type BigInt.

read about BigInt :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

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.