4

Anchor has the concept of "remaining accounts", which allows me to pass in an array of unvalidated accounts of an arbitrary size. This is great if I need accounts for inner instructions and the number of them may vary.

From the Anchor source:

pub struct Context<'a, 'b, 'c, 'info, T: Bumps> {
    /// Currently executing program id.
    pub program_id: &'a Pubkey,
    /// Deserialized accounts.
    pub accounts: &'b mut T,
    /// Remaining accounts given but not deserialized or validated.
    /// Be very careful when using this directly.
    pub remaining_accounts: &'c [AccountInfo<'info>],
    /// Bump seeds found during constraint validation. This is provided as a
    /// convenience so that handlers don't have to recalculate bump seeds or
    /// pass them in as arguments.
    /// Type is the bumps struct generated by #[derive(Accounts)]
    pub bumps: T::Bumps,
}

How can a pattern like this be replicated with native Rust programs? I haven't been able to find a way to pass an arbitrary array of accounts like Anchor handles, and I'm wondering if anyone has methods they've used.

1 Answer 1

6

When you define an accounts struct in Anchor, it assigns indexes in the accounts array that the program receives. However, that array can be longer than specified by the accounts struct (i.e you specify 10 accounts the ix needs, but 12 are supplied)

Those extra two accounts aren't just thrown out, but rather pushed to "remaining accounts". Anchor abstracts this since most programs will not need this, so better to have the builder specify only the accounts they need unless explicitly opted-in.

So, to answer the question, I can do something like this:

// I know upfront I've specified 10 accounts that I need in my base case
let remaining_accounts = &accounts[10..];

// Expanding to the use-case mentioned in the question
let account_metas: Vec<AccountMeta> = remaining_accounts
     .iter()
     .map(|acc| AccountMeta::new(*acc.key, false))
     .collect();
            
let ix = Instruction::new_with_bytes(
     program_id, 
     &data, 
     account_metas
);
2
  • This is helpful, thanks! Commented Jun 7 at 6:23
  • That was helpful, Congrats Arihant! Commented Jul 3 at 10:51

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.