Skip to main content

anchor_lang/accounts/
boxed.rs

1//! `Box<T>` type to save stack space.
2//!
3//! Sometimes accounts are too large for the stack,
4//! leading to stack violations.
5//!
6//! Boxing the account can help.
7//!
8//! # Example
9//! ```ignore
10//! #[derive(Accounts)]
11//! pub struct Example {
12//!     pub my_acc: Box<Account<'info, MyData>>
13//! }
14//! ```
15
16use {
17    crate::{
18        solana_program::{account_info::AccountInfo, instruction::AccountMeta, pubkey::Pubkey},
19        Accounts, AccountsClose, AccountsExit, Result, ToAccountInfos, ToAccountMetas,
20    },
21    std::{collections::BTreeSet, ops::Deref},
22};
23
24impl<'info, B, T: Accounts<'info, B>> Accounts<'info, B> for Box<T> {
25    fn try_accounts(
26        program_id: &Pubkey,
27        accounts: &mut &'info [AccountInfo<'info>],
28        ix_data: &[u8],
29        bumps: &mut B,
30        reallocs: &mut BTreeSet<Pubkey>,
31    ) -> Result<Self> {
32        T::try_accounts(program_id, accounts, ix_data, bumps, reallocs).map(Box::new)
33    }
34}
35
36impl<'info, T: AccountsExit<'info>> AccountsExit<'info> for Box<T> {
37    fn exit(&self, program_id: &Pubkey) -> Result<()> {
38        T::exit(Deref::deref(self), program_id)
39    }
40}
41
42impl<'info, T: ToAccountInfos<'info>> ToAccountInfos<'info> for Box<T> {
43    fn to_account_infos(&self) -> Vec<AccountInfo<'info>> {
44        T::to_account_infos(self)
45    }
46}
47
48impl<T: ToAccountMetas> ToAccountMetas for Box<T> {
49    fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta> {
50        T::to_account_metas(self, is_signer)
51    }
52}
53
54impl<'info, T: AccountsClose<'info>> AccountsClose<'info> for Box<T> {
55    fn close(&self, sol_destination: AccountInfo<'info>) -> Result<()> {
56        T::close(self, sol_destination)
57    }
58}