Account Space
Reference guide for calculating account data size (bytes) requirements by Rust type
This reference tells you how much space you should allocate for an account.
This only applies to accounts that don't use zero-copy
. zero-copy
uses
repr(C)
with a pointer cast, so there the C
layout applies.
In addition to the space for the account data, you have to add 8
to the
space
constraint for Anchor's internal discriminator (see the example).
Type chart
Types | Space in bytes | Details/Example |
---|---|---|
bool | 1 | would only require 1 bit but still uses 1 byte |
u8/i8 | 1 | |
u16/i16 | 2 | |
u32/i32 | 4 | |
u64/i64 | 8 | |
u128/i128 | 16 | |
[T;amount] | space(T) * amount | e.g. space([u16;32]) = 2 * 32 = 64 |
Pubkey | 32 | |
Vec<T> | 4 + (space(T) * amount) | |
String | 4 + length of string in bytes | |
Option<T> | 1 + (space(T)) | |
Enum | 1 + Largest Variant Size | e.g. Enum { A, B { val: u8 }, C { val: u16 } } -> 1 + space(u16) = 3 |
f32 | 4 | serialization will fail for NaN |
f64 | 8 | serialization will fail for NaN |
Example
The InitSpace macro
Sometimes it can be difficult to calculate the initial space of an account. This
macro will add an INIT_SPACE
constant to the structure. It is not necessary
for the structure to contain the #[account]
macro to generate the constant.
Here's an example:
A few important things to know:
- Don't forget the discriminator when defining
space
- The
max_len
attribute specifies the maximum number of elements in a Vec, not the total size in bytes. For example, if you specify#[max_len(10)]
for aVec<u32>
, it means:- Maximum 10 elements
- Each element (u32) takes 4 bytes
- The Vec itself has a 4-byte length prefix
- Total space = 4 + (10 * 4) = 44 bytes