2

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
  • I think you need to clarify what "zero account" is. Maybe with a link? The general wisdom is to allocate maximum forecasted size to an account from the get-go, rather than trying to realloc.
    – sohrab
    Commented Sep 2, 2022 at 11:08

1 Answer 1

1

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.

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.