0

the function in the contract is

    function withdraw() external onlyOwner {
        payable(msg.sender).transfer(address(this).balance);
    }

the test I've started is

  it('Should withdraw all funds', async () => {
    const balance = await provider.getBalance(owner.address);
    expect(ethers.utils.formatEther(await balance.toString())).to.equal(
      '9999.982579589843532242'
    );
    const setWithdrawTx = await greeter.withdraw();
    await setWithdrawTx.wait();
    expect(ethers.utils.formatEther(await balance.toString())).to.equal(
      '19999.9651591797'
    );
  });

and this is how I'm launching the contract

  beforeEach(async () => {
    provider = ethers.provider;
    [owner, addr1, addr2, ...addresses] = await ethers.getSigners();
    const baseFactory = (await ethers.getContractFactory(
      'Greeter',
      owner
    )) as Greeter__factory;
    greeter = await baseFactory.deploy('hello');
    await greeter.deployed();
  });

The error is

AssertionError: expected '9999.982579589843532242' to equal '19999.9651591797'

Will the contract initially have no funds? hence the balance doesn't change? If so I guess I need a way to send some funds then try to withdraw it? How do I get the address of the balance?

2 Answers 2

0

Inside the test balance remains constant. It isn't updated after the call to withdraw. It is likely you want to update the balance.

let balance = await provider.getBalance(owner.address);

expect(ethers.utils.formatEther(await balance.toString())).to.equal(
  '9999.982579589843532242'
);

const setWithdrawTx = await greeter.withdraw();
await setWithdrawTx.wait();

balance = await provider.getBalance(owner.address); 

expect(ethers.utils.formatEther(await balance.toString())).to.equal(
  '19999.9651591797'
);
0

You can calculate the transaction gas fee.

  const balance = await ethers.provider.getBalance(owner.address); // owner balance
  const amount = await ethers.provider.getBalance(greeter.target); // contract balance

  const txReceipt = await greeter.withdraw();

  const receipt = await txReceipt.wait();
  const gasUsed = receipt.cumulativeGasUsed * receipt.gasPrice; // transaction gas fee

  // test balance of owner account after transaction
  expect(await ethers.provider.getBalance(owner.address)).to.equal(
    balance - gasUsed + amount
  );

  // test balance of the contract after transaction
  expect(await ethers.provider.getBalance(greeter.target)).to.equal(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.