5

I'm getting the following error using Anchor 0.25.0 Stack offset of 11792 exceeded max offset of 4096 by 7696 bytes, please minimize large stack variables initializing my accounts on local testing.

I'm initializing a boxed account (Board) that represents a 10x10 optional board, where each cell contains a public key and some values.

pub struct Create<'info> {
    #[account(mut)]
    pub user: Signer<'info>,
    #[account(
        init,
        payer = user,
        space = 8 + board::MAXIMUM_SIZE,
        seeds = [b"board"],
        bump
    )]
    pub board: Box<Account<'info, Board>>,
   ... etc

pub const MAXIMUM_SIZE: usize = 32 + 8 + 1 + (100 * (32 + 1 + 1 + 1 + 1 + 1));

public initializer function that is failing

pub fn create(ctx: Context<Create>) -> Result<()> {
    let pixel_board = &mut ctx.accounts.board;
    pixel_board.bump = *ctx.bumps.get("board").unwrap();
    pixel_board.count = 0;
    pixel_board.gov = *ctx.accounts.gov.key;

    Ok(())
}
```

any tips / pointers on how to reduce this the stack variables here? I'd like to scale beyond 10x10 at some point if possible. Thank you in advance

2 Answers 2

3

This will be a bit tough if you're using Anchor, since it automatically deserializes and reserializes variables for you, which means it will try to put the whole type on the stack.

I'm not sure if this will work, but you can try to have it as an unchecked account, then allocate it on the heap using a Box, ie let boxed = Box<Board>::try_from_slice(account_info.borrow_data()).unwrap();

4
1

Quote from Program Architecture https://solana.com/developers/courses/program-optimization/program-architecture:

  • If your data accounts are too large for the Stack, wrap them in Box to allocate them to the Heap
  • Use Zero-Copy to deal with accounts that are too large for Box (< 10MB)
  • The size and the order of fields in an account matter; put variable length fields at the end
  • Solana can process in parallel, but you can still run into bottlenecks; be mindful of "shared" accounts that all users interacting with the program have to write to

Use Box to fix it

#[account]
pub struct SomeBigDataStruct {
    pub big_data: [u8; 5000],
}
 
#[derive(Accounts)]
pub struct SomeFunctionContext<'info> {
    pub some_big_data: Box<Account<'info, SomeBigDataStruct>>, // <- Box Added!
}

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.