0

When an account is closed (on-chain), the account.subscribe listener try to decode the account, and it throws an error. How can I handle the error, to execute a callback when the error happens. It's an expected event.

Currently, I'm getting: "Error: Invalid account discriminator". Probably because the account doesn't exist anymore.

The account.subscribe method uses Solana Web3's onAccountChange and EventEmitter.

patriciobcs
  • 161
  • 5

1 Answers1

2

The account.subscribe listener decodes the account whenever an update for it is received:

const account = this._coder.accounts.decode(this._idlAccount.name, acc.data);

If the account is deleted, then it will fail to decode as the expected type. It looks like the code you linked could use a PR to fix this behavior!

In other places, it returns null if the account data is incorrect, so perhaps the event emitter should return null if the account fails to decode.

In the meantime, you can implement your own version of this which adds that check, ie:

    const listener = this._provider.connection.onAccountChange(
      address,
      (acc) => {
        if (acc == null) {
          ee.emit("change", null);
        } else {
          const account = this._coder.accounts.decode(
            this._idlAccount.name,
            acc.data
          );
          ee.emit("change", account);
        }
      },
      commitment
    );
Jon C
  • 7,019
  • 10
  • 17
  • Hello, I did something similar but with some changes, because when an account is deleted, "acc" is not going to be null. Instead, it is going to be an account object with the field called data as a buffer with length zero. I'll submit a PR soon – patriciobcs Mar 12 '22 at 15:20