How to watch Ether balance changes - Hideyoshi Moriya - Medium

Testing import from medium

  • 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!