5

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?

9

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")}`);
      }
    });
  }
});
1

Unfortunately, a push approach is just in the making rught now in web3, as far as I heard from a developer involved. Web3, in this case, represents a connection to an Ethereum node. You can ask it for information, but it, as for now, has no way of "telling" you something proactively. You need to continue polling for now.

  • Is this answer still true? – Lee Han Kyeol Jan 9 '18 at 8:49
  • 1
    Partially. Web3js 1.0.0 supports websockets HOWEVER you can not use it in production as it is not compatible with metamask which is the main way users will interact with a dApp. – Nico Mar 3 '18 at 2:30
0

Is seems like not working in Web3js 1.0 above.

is there any solution for the beta beside using filter. I found out that some people are using subscribe but not sure how to do that.

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.