7

I'm trying to fetch an account from a public key:

await program.account.myAccountType.fetch(somePubkey);

But then Anchor throws an error saying:

Invalid account discriminator

What is an account discriminator?

Evan Conrad
  • 3,993
  • 4
  • 28
  • 46

4 Answers4

11

An account discriminator is few bytes that Anchor puts at the front of an account, like a header. It lets anchor know what type of account it should deserialize the data as.

This error happens if you try to to fetch something as myAccountType, but it's actually a pubkey for some other account, like a Token Account, or another account within your program.

Here's some things you could try:

  • console logging somePubkey and putting it into the explorer
  • making extra double sure that you meant program.account.myAccountType and not program.account.someOtherAccountType.
Evan Conrad
  • 3,993
  • 4
  • 28
  • 46
1

In my case this problem occurred after I did anchor idl init [OPTIONS] --filepath <FILEPATH> <PROGRAM_ID>.

Once I ran this command the frontend started to throw Error: Invalid account discriminator every time I tried to run await connection.getProgramAccounts().

I wanted to do the anchor idl init because I wanted to fetch the idl using Program.fetchIdl() instead of passing idl as a json object, which requires me to copy it from target/idl/<program-name>.json into my React frontend and then import the json into my project...

To fix the issue I had to rebuild and redeploy anchor program by running anchor build and then anchor deploy. Once I did this then I had to pass the idl as a json object into the Program.getProgramAccounts() function.

Yuivae
  • 91
  • 5
-1

I had the same error come up when I had put my accounts in the wrong order. As a result the discriminator didn't match up with what it expected.

Slae
  • 335
  • 5
  • 18
-1

In my case, I am using a Non-camelcase type for account struct.

Previous

enter image description here

After Fix enter image description here

Swaroop Maddu
  • 4,289
  • 2
  • 26
  • 38