accountChange event not trigring when switch phantom wallet account

126 Views Asked by At

I am trying to get the key of phantom account when the user switches to new account. It work fine when multi chain is on but when I turn it off the event doesn't gets triggered.

Here is the code

provider.on('accountChanged', (publicKey: PublicKey) => {
      if (publicKey) {
        console.log('publicKey: ', publicKey.toString())
      }
    })

I have tried the documentation of Phantom but the don't have an answer to my problem. I have also opened a issue but haven't recieeved any response yet.

1

There are 1 best solutions below

1
Orelsanpls On

If you look at the code of the wallet adapter when the account change, phantom emit a connect event.

private _accountChanged = (newPublicKey: PublicKey) => {
    const publicKey = this._publicKey;
    if (!publicKey) return;

    try {
        newPublicKey = new PublicKey(newPublicKey.toBytes());
    } catch (error: any) {
        this.emit('error', new WalletPublicKeyError(error?.message, error));
        return;
    }

    if (publicKey.equals(newPublicKey)) return;

    this._publicKey = newPublicKey;
    this.emit('connect', newPublicKey);
};