How to watch Ether balance changes

--

  • The example code below listens to Ether balance changes.
  • It gets Ether balance when a new block mined.
  • Strictly speaking, a fork can be happened. So you will need to count confirmation numbers depending on your application.
const ethers = require('ethers')const network = 'rinkeby'
const provider = ethers.getDefaultProvider(network)
const address = '0xF02c1c8e6114b1Dbe8937a39260b5b0a374432bB'// Listen Ether balance changes
let lastBalance = ethers.constants.Zero
provider.on('block', () => {
provider.getBalance(address).then((balance) => {
if (!balance.eq(lastBalance)) {
lastBalance = balance
// convert a currency unit from wei to ether
const balanceInEth = ethers.utils.formatEther(balance)
console.log(`balance: ${balanceInEth} ETH`)
}
})
})

Support

If you find this article is helpful, it would be greatly appreciated if you could tip Ether to the address below. Thank you!

0x0089d53F703f7E0843953D48133f74cE247184c2

--

--