reactjsmetamaskethers.js

Listening for changes in wallet balance (Metamask / ethers.js)


So I know we can listen for account changes, but what about balance changes?
For example if an account is topped up, I want my React app to reflect that change in balance.

Is there an event for this? I couldn't find any, but maybe I'm looking in the wrong place.
Or am I stuck with using a setInterval to periodically and inefficiently update the balance?


Solution

  • While I couldn't find a way to specifically listen to balance changes, what I did was checking the balance whenever there's a new block event:

    import { ethers } from "ethers";
    
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    
    function refreshBalance() {
     // handle getting an updated balance and do something with it
    }
    
    provider.on("block", refreshBalance);
    

    Where refreshBalance handles the logic to get the updated balance.