0

I am testing a smart contract but I have troubles accessing the balance of the contract in my javascript test file. For simplicity assume this is my smart contract:

contract Donation{
  function donate() external payable{}

  function getBalance() external view returns(uint)
  {
    return address(this).balance;
  }
}

In remix I called the donate() function with value = 1 ether, and afterwards when I called the getBalance() function it returned the correct value for the balance.

However, when I use Ganache in combination with javascript I only get 0 as value for the balance of the contract. This is how my test looks like:

it( 'Test contract', async() => {
  instance = await Donation.deployed();

  let balance = await web3.eth.getBalance(instance.address);
  console.log("balance = ", balance);

  user1 = accounts[0];
  instance.donate({value:400000000});

  balance = await web3.eth.getBalance(instance.address);
  console.log("balance = ", balance);
});

The first console.log returns 0 as balance for the smart contract which is fine. However, after calling the donate() function with a value of 400000000, I expected the second console.log() to return that value as the balance of the contract.

I have no idea why the donate() function doesn't increase the contract balance. Anyone has any idea what is wrong here ?

0

You just need to replace instance.donate({value:400000000}); by await instance.donate({value:400000000}); to get the desired behavior.

Indeed, always use await in your asynchronous tests for each transaction to be sure that they are executed in the correct order.

1
  • 1
    That did the trick. Thanks a lot :-)
    – JohnyB
    Jun 2 at 8:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.