Understanding Metamask Balance Updates

In this article, we’ll explore how Metamask, a popular Ethereum wallet and decentralized application builder, keeps track of the updated balances of your ERC20 tokens (Ethereum-based tokens).

The Magic of Balance Updates in Metamask

When you create an account on a blockchain platform like MetaMask or Truffle Suite, you’re essentially signing up for a user interface that interacts with various smart contracts, including those that manage your digital assets. One of these contracts is the ERC20 standard, which allows developers to build applications based on tokens.

The Backend Process: Balances

When an ERC20 transfer happens, it’s not just a “move from one wallet to another.” Rather, it’s an update of the balances of both parties involved in the transaction. In Metamask, this process is handled by a background thread that runs periodically on your device.

Here’s what happens:

  • Event listeners: When an ERC20 transfer occurs, you will receive notifications from Metamask via event listeners (e.g. the “onTransfer” event). These event listeners are attached to the smart contract that manages your tokens.
  • Balance update

    : When the event listener detects a new transfer, it triggers a balance update for both parties involved in the transaction. This is done by querying the internal state of the contract and updating the “totalSupply” property accordingly.

  • Update in background thread: The updated value is then sent to Metamask’s background thread using WebSockets or IPC (Inter-Process Communication) mechanisms.

Who Calls BalanceOf()

To understand what’s going on behind the scenes, we need to look at another crucial function: balanceOf(). This method is called by the smart contract on behalf of your wallet when you query its balance:

  • Balance Updates: When you call balanceOf() from Metamask, it triggers a request to the contract’s internal state. The contract responds with the current balance value.
  • WebSockets or IPC: If you’re using WebSockets or IPC (e.g. Web3.js), you’ll send a request to the contract’s endpoint and receive the response immediately.

In a Nutshell

Metamask keeps track of your ERC20 token balances by:

  • Running periodic background threads that update the balance values ​​for each token transferred.
  • Attaching event listeners to the smart contracts that manage your tokens, which trigger updates when an event occurs (e.g. the onTransfer event).
  • Using WebSockets or IPC mechanisms to send requests from Metamask to the contract’s internal state and receive responses.

By understanding how balances are updated in Metamask, you can better appreciate the complexity of managing your digital assets on a blockchain platform like Ethereum.