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?
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?
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:
somePubkey
and putting it into the explorerprogram.account.myAccountType
and not program.account.someOtherAccountType
.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.
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.