Anchor Space Allocation
Detects incorrect space allocation in Anchor account initialization.
Anchor Space Allocation
Overview
The Anchor space allocation detector identifies incorrect space calculations in #[account(init)] operations. Common issues include insufficient space for the data structure, missing the 8-byte discriminator in the calculation, wrong size for dynamic data types (Vec, String), missing MAX_SIZE for variable-length fields, and calculations that do not account for all fields.
For remediation guidance, see Anchor Space Allocation Remediation.
Why This Is an Issue
Anchor accounts require exactly the right amount of space: 8 bytes for the discriminator plus the serialized size of the data structure. Under-allocating causes serialization failures when writing data. Over-allocating wastes rent. Dynamic types (Vec, String) require Borsh’s 4-byte length prefix in the calculation. Incorrect space allocation is a common source of initialization failures in production.
How to Resolve
Before (Vulnerable)
// Vulnerable: missing discriminator, no room for Vec length prefix
#[derive(Accounts)]
pub struct Init<'info> {
#[account(init, payer = user, space = 32 + 200)] // Missing 8 + 4
pub data: Account<'info, MyData>,
// ...
}
After (Fixed)
// Fixed: correct space with discriminator and Borsh overhead
#[derive(Accounts)]
pub struct Init<'info> {
#[account(init, payer = user, space = 8 + MyData::INIT_SPACE)]
pub data: Account<'info, MyData>,
// ...
}
#[account]
#[derive(InitSpace)]
pub struct MyData {
pub owner: Pubkey, // 32 bytes
#[max_len(200)]
pub uri: String, // 4 + 200 bytes (Borsh prefix + data)
}
Example JSON Finding
{
"detector": "anchor-space-allocation",
"severity": "medium",
"confidence": 0.6,
"message": "Account initialization with space calculation missing discriminator offset",
"location": { "function": "initialize", "block": 0, "statement": 1 }
}
Detection Methodology
- Init function detection: Identifies functions related to account initialization.
- Space allocation extraction: Extracts the allocated space from init operations.
- Data store size comparison: Compares allocated space against data write sizes.
- Discriminator accounting: Checks whether space includes the 8-byte discriminator.
Limitations
False positives: Dynamic space calculations using runtime variables may appear incorrect at static analysis time. False negatives: Space issues that only manifest with specific data sizes are not detected.
Related Detectors
- Account Size Violation — general account size issues
- Anchor Init/Close Patterns — init/close vulnerabilities