1

Can anyone please explain the following issue? I have a pretty simple code to fetch ETH balance using the web3 JS library. It's something like the following:

import Web3 form 'web3';

const web3 = new Web3(new Web3.providers.HttpProvider('https://api.myetherapi.com/eth'));
const batch = new web3.eth.BatchRequest();

batch.add(api.eth.getBalance.request('0x...', 'latest', (err, balance) => {
    if (err) {
        console.error(err);
    } else {
        console.log(web3.utils.fromWei(balance, 'ether');
    }
}));

...

batch.execute();

I call this code every N seconds, and it works fine most of the time. However, when some transaction changes the balance, a weird thing happens: getBalance may return either new balance or old one. I mean, one call will return a new value, the next call - old value, then new value again and so on.

Is there any kind of a workaround for this?

1

This behavior can happen due to forks in the chain. The best practice is to wait for a transaction until you have 12 confirmations (blocks). See "What number of confirmations is considered secure in Ethereum?"

EDIT Ethereum just like Bitcoin implements probabilistic BFT. This means that there is no point in time where you can be 100,0% sure about what you're getting from the chain. For this reason, if you want stable values, you should query these from currentBlock-12.. you can do this via eth.getBalance(addr, eth.blockNumber-12)

  • Thank you for the answer. But all I want is to get the current balance; I don't see a way to check that all affecting transactions have already been confirmed 12 times. – Alex Kiselev Jun 4 '18 at 7:33
  • 1
    Ethereum just like Bitcoin implements probabilistic BFT. This means that there is no point in time where you can be 100,0% sure about what you're getting from the chain. For this reason, if you want stable values, you should query these from currentBlock-12.. you can do this via eth.getBalance(addr, eth.blockNumber-12) – ivicaa Jun 4 '18 at 7:38

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.