coral-xyz / anchor

⚓ Solana Sealevel Framework
https://anchor-lang.com
Apache License 2.0
3.56k stars 1.32k forks source link

[FEATURE] Support for dynamic number of account inputs for `Accounts` structs #1325

Closed enzoampil closed 2 years ago

enzoampil commented 2 years ago

For a specific instruction, is it possible for it to take a dynamic number of accounts - e.g. for a "create_vault" instruction where you allow users to specify the number of assets (token mints) they want to have in the vault that they create.

E.g. Single asset vault creation for create_vault

create_vault(
   authority,
   token1_mint,
   token1_account,
   1, // Specified number of assets
)

2 asset vault creation

create_vault(
   authority,
   token1_mint,
   token1_account,
   token2_mint,
   token2_account,
   2, // Specified number of assets
)

In the instruction invocations above, there is support for a dynamic number of accounts depending on the specified number of assets (n_assets) for the same instruction.

Is this dynamic number of account inputs for an instruction possible for Anchor? If not, it would be great if there existed something like an AccountInfos type that is essentially a vector of AccountInfo (calling next_accounts_infos underneath) , which allows an instruction to process a dynamic number of accounts of the same type.

The idea is that if the Accounts structs can take a Vec<AccountInfo> (in addition to singular AccountInfo), then at account validation, Anchor should be able to validate through the vector, and then store the vector in the context's self to be used during instruction handling.

For context, I recall being able to implement this flow in a fairly straightforward way from raw Solana code, but I notice that Anchor contexts have to have strict lengths (with all account names specified).

This is an example from Serum Pool of how you can support a vault with a dynamic number of assets via the next_account_infos function.

Thanks

fanatid commented 2 years ago

Is Context.remaining_accounts solve you problem?

enzoampil commented 2 years ago

@fanatid yes, this looks like it solves me problem quite nicely! Thanks.

enzoampil commented 2 years ago

Closing now as above seems to be exactly what I'm looking for