Search code examples
next.js13web3jsmetamaskdecentralized-applications

Can Web3 be used to switch between accounts on Metamask programmatically?


If my currently active account on Metamask is Acc1, and I want to pass the address of Acc2 from a webpage and programmatically switch the active account on Metamask to Acc2, how can this be achieved?

I have explored the Metamask documentation and attempted various approaches, but I haven't found a solution for programmatically switching the active account using web3 and passing the account address from a webpage.


Solution

  • Not possible to do programmatically.

    MetaMask only reflects the user selected address in the eth_requestAccounts method and selectedAddress property for security reasons.

    Having said that, your app can react to changes by listening to the accountsChanged event (docs).


    Possible scenario how it could be misused if the switch was allowed programmatically: A user wants to send a transaction from Address 1. Just before opening the MetaMask popup requesting signature, the web app switches the active address to Address 2 along with changing the value of the transaction to total balance of Address 2. User overlooks the change and signs the transaction - effectively stealing their Address 2 balance.