When initializing accounts, you must specify the space (size in bytes) required.
space = 8 (discriminator) + account_data_size
Type sizes
| Type | Size (bytes) |
|---|
| bool | 1 |
| u8/i8 | 1 |
| u16/i16 | 2 |
| u32/i32 | 4 |
| u64/i64 | 8 |
| u128/i128 | 16 |
| Pubkey | 32 |
| String | 4 + length |
| Vec<T> | 4 + (size_of(T) * length) |
| Option<T> | 1 + size_of(T) |
InitSpace derive
Use InitSpace for automatic calculation:
#[account]
#[derive(InitSpace)]
pub struct Data {
pub value: u64, // 8
pub owner: Pubkey, // 32
pub name: String, // 4 + len
}
// Usage
#[account(init, payer = user, space = 8 + Data::INIT_SPACE)]
pub data: Account<'info, Data>
String and Vec lengths
Specify max lengths with attributes:
#[account]
#[derive(InitSpace)]
pub struct Data {
#[max_len(50)]
pub name: String,
#[max_len(10)]
pub items: Vec<u64>,
}
Manual calculation
#[account(init, payer = user, space = 8 + 32 + 8)]
pub data: Account<'info, Data>
#[account]
pub struct Data {
pub owner: Pubkey, // 32
pub count: u64, // 8
}
// Total: 8 (discriminator) + 32 + 8 = 48 bytes
Best practices
Always use InitSpace derive to avoid calculation errors.
Allocate enough space for dynamic types (String, Vec) based on expected max size.