[Ethereum] Automatically update account balance with web3.js without polling

accountsbalancesdapp-developmentjavascriptweb3js

I've made a user interface in JavaScript with web3.js where the user can select an account to use. The accounts are displayed together with their current balance for convenience.

I load the account addresses like this:

web3.eth.accounts

and I load the balances using this function:

web3.eth.getBalance(account, callback)

Obviously, while using my DApp the user's account balance can change. Whenever the use of my DApp changes the balance, I update it by calling getBalance(…). However, this is not a complete solution because the balance may change if the user does anything outside my DApp.

Right now I'm polling the getBalance function every x seconds to keep the account balance reasonably up-to-date. Polling is not the cleanest solution because it constantly takes some power and some CPU cycles. If I save some power by only polling once a minute, it's very slow. Is there a way to avoid polling and just receive a callback when the account balance changes?

Best Answer

You can install a block filter and only update balances when a new block arrives.

const Web3 = require('web3');

const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

const address = "0x9b....";

let balance = web3.eth.getBalance(address);

const filter = web3.eth.filter('latest');
filter.watch((err, res) => {
  if (err) {
    console.log(`Watch error: ${err}`);
  } else {
    // Update balance
    web3.eth.getBalance(address, (err, bal) => {
      if (err) {
        console.log(`getBalance error: ${err}`);
      } else {
        balance = bal;
        console.log(`Balance [${address}]: ${web3.fromWei(balance, "ether")}`);
      }
    });
  }
});
Related Topic