3

Let's imagine I have this account and I want to filter all the Program Accounts by the author:

pub struct EntryBook {
    title: String,
    author: String
}

How would be the offset to target the author property?

const filteringBooks = await program.account.entryBook.all([
      {
          memcmp: {
              offset: 8 +    // Discriminator.
                      4 +    // Title string prefix.
                      ?????  // Title String 
                      4,     // Author string prefix.
              bytes: bs58.encode(Buffer.from('<author name>')),
          }
      }
    ]);

2 Answers 2

3

You need to pack them into fixed lengths byte arrays. This is the downside of memcmp: you can't have variable length fields. The following is an easy way to do so:

pub fn pack_string_in_32_bytes(string: String) -> Result<[u8; 32]> {
    let string_in_bytes = string.as_bytes();

    if string_in_bytes.len() > 32 {
        return Err(error!(CustomProgramError::StringTooLong));
    }

    let mut bytes: [u8; 32] = [0; 32];
    bytes[..string_in_bytes.len()].copy_from_slice(string_in_bytes);

    Ok(bytes)
}
1

You would have to make title a fixed length in order for the offset to work in this way. e.g. title: [u8; 10] Then just pad the end of the title string with empty space if it doesn't fill up the full fixed length.

0

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.