Space Calculation
Correct space calculation prevents failed inits and rent surprises. Sum discriminators, Borsh fields, or size_of::<Pod>(), then query Rent for lamports.
Recipe
pub const SPACE: usize = 8 + User::LEN;
let lamports = Rent::get()?.minimum_balance(SPACE);When to reach for this:
- Creating accounts in program or client.
- Estimating protocol rent costs.
- Reviewing Anchor
space =attributes.
Working Example
#[derive(BorshSerialize, BorshDeserialize)]
pub struct User { pub authority: Pubkey, pub points: u64 }
impl User { pub const LEN: usize = 32 + 8; }
pub const USER_SPACE: usize = 8 + User::LEN; // disc + bodyWhat this demonstrates:
- 8-byte discriminator plus body.
- LEN constant documented.
- Rent from SPACE constant.
Deep Dive
Formula
SPACE = disc + sum(field sizes) + variable length caps.
Variable Vec
4 + max_entries * entry_size.
Rust Notes
// Host test: assert_eq!(serialized.len(), USER_SPACE - 8);Gotchas
- Forgot discriminator - Off-by 8.. Fix: Always add disc.
- String unbounded - Cannot precompute.. Fix: Use max UTF-8 bytes.
- Option fields - 1 + inner size each.. Fix: Include in sum.
- Wrong Pubkey size - Must be 32.. Fix: Use constants.
- Padding in Pod - Use size_of not manual guess.. Fix: Compile-time assert.
Alternatives
| Alternative | Use When | Don't Use When |
|---|---|---|
| Anchor InitSpace | Auto | Manual native |
| Host serialize measure | Ground truth | Runtime only |
| Excel rent calculator | Planning | Not code substitute |
FAQs
Rent exempt min?
Rent::minimum_balance.
Grow later?
realloc pays delta.
Token acct size?
165 bytes classic SPL.
Account overhead?
On-chain only data len.
Max space?
10 MB.
Zero space?
Only lamports holder.
InitSpace anchor 0.32?
Macro expands at compile time.
Pubkey array?
32 * n.
C string?
Avoid - use fixed bytes.
Test LEN?
Unit test host.
Rent calculator CLI?
solana rent.
Surfpool?
Verify create with SPACE.
Related
- Borsh Structs - Field sizes
- Rent & Rent Exemption - Economics
- Creating Accounts via CPI - Allocate
Stack versions: This page was written for Agave 4.1.1, Solana CLI 3.0.10, Anchor 0.32.1, anchor-lang 0.32.1, Rust 1.91.1, @solana/kit 7.0.0, Surfpool 0.12.0, and LiteSVM 0.6.x.