Serialization Basics
10 examples to get you started with Account Serialization - 7 basic and 3 intermediate.
Search across all documentation pages
10 examples to get you started with Account Serialization - 7 basic and 3 intermediate.
Serialize structured state into account data.
#[derive(BorshSerialize, BorshDeserialize)]
pub struct Config { pub fee_bps: u16 }Predeclare space for create_account.
impl Config { pub const LEN: usize = 2; }InitSpace calculates automatically.Tag account type to prevent confusion.
pub const DISCRIMINATOR: [u8; 8] = [0xC0, 0xFF, 0xEE, 0x00, 0x00, 0x00, 0x00, 0x01];Validate length and discriminator first.
if data.len() < Config::LEN { return Err(ProgramError::InvalidAccountData); }Use Pod for big fixed arrays.
#[repr(C)]
#[derive(Pod, Zeroable, Clone, Copy)]
pub struct Book { pub bids: [u64; 256] }Instructions often Borsh; accounts may be hybrid.
// ix: enum Instruction { Update { val: u64 } }Larger accounts need more lamports.
let rent = Rent::get()?.minimum_balance(Config::LEN);First byte indicates schema version.
pub enum Version { V1 = 1, V2 = 2 }Related: Data Versioning & Migration
Expand account when schema grows.
// CPI realloc + rent transfer then new fieldsRelated: realloc & Growing Accounts
Sum discriminator + fields + padding.
pub const SPACE: usize = 8 + Config::LEN;Related: Space Calculation
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.
Reviewed by Chris St. John·Last updated Jul 19, 2026