1

What if we want to pass arbitrary number of accounts to the function(as part of accounts).

Expectation :-

If we have a program and there is a function named as transferMultiple (Which is responsible for extracting multiple accounts and pay them a constant amount of tokens).

pub fn transferMultiple(ctx:Context<TransferMultiple>, amt:uint8) -> Result<()> {

//extract the arbitrary number of accounts from ctx 
//transfer "amt" number of tokens to every account extracted.

}


#[derive(Accounts)]
pub struct TransferMultiple<'info> {
    #[account(mut)]
    pub from: Signer<'info>, 
    
    pub input_accounts: **Here I need to specify array of AccountInfo**,
}

How to achieve the above operation ?

2 Answers 2

3

You can use remaining_accounts to pass in an arbitrary number of unchecked accounts, up to the transaction size limit.

In the instruction you can access the accounts using ctx.remaining_accounts.iter()

Pass them in using .remainingAccounts

  const transactionSignature = await program.methods
      .instruction()
      .accounts({})
      .remainingAccounts([
        {
          pubkey: address1,
          isSigner: false,
          isWritable: true,
        },
        {
          pubkey: address2,
          isSigner: false,
          isWritable: true,
        },
      ])
      .rpc({ skipPreflight: true });
1

You could have a struct with a Vec. That way you could access all the accounts, but in solana you would need to pass in all the accounts you want to interact with into the transaction. So that would not work. You have multiple options. You could hard code keys 1-10 for example or you could use an address lookup table in case you have more accounts you want to pass in.

What that does is it creates a new account and saves pubkeys in there which can then be accessed in the transaction via an index.

Read more about it here: https://solana.com/de/docs/advanced/lookup-tables

2

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.