Anchor Space Allocation Remediation
How to fix incorrect Anchor space allocation.
Anchor Space Allocation Remediation
Overview
Related Detector: Anchor Space Allocation
Incorrect space allocation causes initialization failures. The fix is to use Anchor’s InitSpace derive macro and always add the 8-byte discriminator prefix.
Recommended Fix
#[account]
#[derive(InitSpace)]
pub struct MyData {
pub owner: Pubkey, // 32
pub amount: u64, // 8
#[max_len(100)]
pub name: String, // 4 + 100
}
#[derive(Accounts)]
pub struct Init<'info> {
#[account(init, payer = user, space = 8 + MyData::INIT_SPACE)]
pub data: Account<'info, MyData>,
}
Alternative Mitigations
Manual Calculation Reference
If not using InitSpace, calculate manually with this reference:
| Type | Size |
|---|---|
| bool | 1 |
| u8/i8 | 1 |
| u16/i16 | 2 |
| u32/i32 | 4 |
| u64/i64 | 8 |
| u128/i128 | 16 |
| Pubkey | 32 |
| Vec<T> | 4 + (len * sizeof(T)) |
| String | 4 + len |
| Option<T> | 1 + sizeof(T) |
Always add 8 bytes for the Anchor discriminator.
Common Mistakes
Mistake: Forgetting the Discriminator
// WRONG: missing 8-byte discriminator
#[account(init, payer = user, space = 32 + 8)] // Should be 8 + 32 + 8
Mistake: Forgetting Vec/String Length Prefix
// WRONG: String needs 4 bytes for Borsh length prefix
// space = 8 + 32 + 100 -- should be 8 + 32 + (4 + 100)