Know when MetaMask wallet has switched

is there a way to call a function when the user switches there metamask wallet to another wallet.

Im trying to achieve the same thing as 1Inch where if you switch wallets the data on the page is automatically reloaded.

I have found this in the Moralis documentation

Moralis.onAccountsChanged(async function (accounts) {

// DO SOMETHING

});



But this function is only called if the user disconnects or connects their wallet and is not called on a simple switch.

You mean that this doesnโ€™t work for you?

Moralis.onAccountsChanged(function(accounts) {

    console.log("x", accounts);
// your code to run when "accountsChanged" happens

});

For me I get that console.log output every time I change an account in MetaMask.

Just retested it and it does work when you switch accounts.

The problem iโ€™m having is when i use this code to get the nativeBalance

const balance = await Moralis.Web3API.account.getNativeBalance(options)

It returns the native balance of the previously connect wallet as opposed to the one which the user just switched too.

1 Like

Currently Web3API takes ethAddress from user object.
If you want to work with Moralis.onAccountsChanged without linking address to account you can get addresses dynamically:

const web3 = await Moralis.enable();
const address = (await web3.eth.getAccounts())[0];
Moralis.Web3API.account.getNativeBalance({address})

I get Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'getAccounts').
How can I avoid this error, please?

Moralis (moralis-v1) doesnโ€™t use web3.js anymore, it uses ethers.js. Also it is enableWeb3() now, not enable(). You can use this:

const web3 = await Moralis.enableWeb3();
const address = (await web3.listAccounts())[0];

Or you can get the address from the authenticated user (if you use Moralis.authenticate()):

Moralis.User.current().get('ethAddress');