Web3 Event Callback – Notify Account Balance Change

web3js

The app below is to send the eth value to the account and refresh the account balance. however the balance doesn't show immediately.

   // send the eth to the contract 
   contract.methods.create(model)
                     .send({from: account,value:value })
                     .on('transactionHash', function(hash){
                               console.log('hash',hash);
                      })

   // refresh the account to see the balance
    web3.eth.getBalance(address, function (error, result) {
      if (error) {
      } else {

        }
    })

I am just wondering is there a event callback on web3 to notify the account balance change?

Best Answer

Are you using web3 v1? In v1 you can use .then() from the result of send to chain getBalance after the transaction was mined.

// send the eth to the contract 
contract.methods.create(model)
    .send({from: account,value:value })
    .on('transactionHash', function(hash){
        console.log('hash',hash);
    })
    .then(function () {
        // refresh the account to see the balance
        web3.eth.getBalance(address, function (error, result) {
            if (error) {
            } else {
            }
        })
    })

There's no event for balance changes that I'm aware of, but installing a block filter and checking for balance chanes should work.

Related Topic