I am looking to use zero account (Anchor) for the first time in my program. I have read the example and from the look of it, it doesn't require the space constraint like init does. I wanted to use a vector field in my struct whose initial length will be zero but will increase eventually. How do I let the program know how much space should it reserve for the vector without space constraint?
1 Answer
You can initialize it like this:
#[account(init, payer=payer, space = 40 , seeds = [b"seeds".as_ref()], bump)]
account_pda: Account<'info, AccountStruct>
#[account]
#[derive(Default)]
pub struct AccountStruct{
pub addresses: Vec<Pubkey>,
pub bump: u8,
}
impl AccountStruct{
pub fn space(len: usize) -> usize {
8 + (4 + ((len + 1) * 32)) + 1
}
}
Then use like this. I realloc 32 bytes each time because I add a new Pubkey to the Vec, which uses 32 bytes.
#[account(mut, seeds = [b"seeds".as_ref()], bump = account_pda.bump,
realloc = AccountStruct::space(account_pda.addresses.len() as usize) , realloc::payer = payer, realloc::zero = false,)]
account_pda: Account<'info, AccountStruct>,
Hope it helps.
realloc
.