4

How can I fetch empty optional accounts in Anchor? For instance I have a simple account in rust with the following optional account:

#[account]
pub struct MyApp {
    pub my_optional_account: Option<Pubkey>,
}

How could I fetch in JS the accounts whose my_optional_accountare empty?

// Javascript:
myProgram.account.myAccount.all([
    {
      memcmp: {
        offset: 8,
        bytes: "", // What should I add here to search for empty Pubkeys?
      },
    },
])

2 Answers 2

3

Anchor generated client is using getProgramAccounts underneath to fetch corresponding program accounts. The default encoding for bytes is base58

So your code would look something like this if you're using base58 utility shipped with Anchor.

import { utils } from "@coral-xyz/anchor";

const OPTION_NONE = 0;
// Javascript:
myProgram.account.myAccount.all([
    {
      memcmp: {
        offset: 8,
        bytes: utils.bytes.bs58.encode([OPTION_NONE])
      },
    },
])
1

Seems like using just "1" does the job:

// Javascript:
myProgram.account.myAccount.all([
    {
      memcmp: {
        offset: 8,
        bytes: "1",
      },
    },
])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.