How does Metamask keep the updated balances of my ERC20 tokens?
What happens in the background that as soon as I receive an ERC20 transfer, the balance gets updated? Who calls balanceOf()
?
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityMetamask relies on external data indexers - last time I checked it used Infura.
Whenever a new block arrives, its data is stored in database in various, queryable, formats. One of the formats is used to query "which tokens does address X own". Metamask then queries for that data whenever new blocks are received.
Metamask could also analyze its transactions to see token balance changes, but I doubt it actually does this, since it would only show part of token changes (for example one may transact with the same account outside Metamask).
For tokens, the logic of monitoring token account updates is in assets-controller, TokenBalancesController to be more specific.
The token balance is updated when
A typical token state looks like this:
const tokenState = {
metamask: {
addressBook: {},
identities: {},
blockGasLimit: '',
selectedAddress: '',
provider: {
chainId: '0x1',
},
},
send: {
account: {
balance: '',
},
asset: {
type: AssetType.token,
details: {},
},
gas: {
gasPrice: '',
},
recipient: {
address: '',
},
amount: {
value: '',
},
userInputHexData: '',
},
};
Token state change can be triggered in several events. For example:
Metamask monitors state changes and query blockchain information via Infura's RPC endpoint.
balanceOf()
? Metamask? If so, where do the files that do the call live? In which server? Or in the browser?