Detecting on the browser when user switches Phantom wallet accounts

Viewed 809

So I have a react app with nextjs where I'd need to get an event trigger when the user uses the Phantom wallet extension and switches accounts. I cannot find anything relevant on their docs: https://docs.phantom.app/

I was wondering if anyone encounter this issue. Basically I have the window.solana object but it does not have a trigger for when the user siwtches accounts

2 Answers

So Phantom itself does not expose any account switching specific API on their window.solana object.

There are some tricks you can do to find out when the account switches though.

You can continuously poll for the currently connected account and set the publicKey to some variable. When the publicKey changes, you can trigger your event.

Example psuedocode:

let currentKey = '';

poll(() => {
  if (/* wallet available and connected */) {
    await /* Action that updates publicKey */
    if (currentKey !== wallet.publicKey.toBase58()) {
      currentKey = wallet.publicKey.toBase58();
      this.publicKey = wallet.publicKey;
      this.emit('change')
    }
  }
})

You can find a writeup and PR we currently have on wallet-adapter going over this flow here

Related