Serialization Best Practices
Account bytes are your database schema. These practices keep layouts auditable, migration-friendly, and resistant to type confusion.
How to Use This List
- Document SPACE formula next to every account struct.
- Add deserialize tests with corrupt fixtures.
- Review discriminator uniqueness table.
A - Layout
- Prefix every account type with a unique discriminator. Stops type confusion attacks.
- Store
LENorSPACEconstants; assert at runtime on access. Prevents partial read/write bugs. - Append fields for upgrades; never reorder or remove fields in place. Preserves live account compatibility.
- Cap variable-length fields with explicit max sizes. Controls rent and CU griefing.
- Prefer fixed layouts on hot paths; document hybrid zero-copy + Borsh splits. Predictable performance.
B - Migration
- Ship a dedicated migration instruction before enforcing new schema. Avoids bricking users.
- Dual-read old and new versions during transition. Smooth rollout.
- Zero new bytes after realloc. Prevents stale data leaks.
- Log migration events for indexers. Operational visibility.
- Freeze schema when program is made immutable. Plan headroom early.
C - Testing
- Roundtrip serialize/deserialize tests on host. Catches LEN mistakes.
- Fuzz deserialize with random bytes. Finds panic paths.
- Snapshot account bytes in LiteSVM integration tests. Regression safety.
- Verify rent calculation matches SPACE. User funding correctness.
- Align Anchor
spaceattributes with native constants. Single source of truth.
FAQs
Borsh vs zero-copy default?
Borsh unless profiled need.
Discriminator length?
8 bytes Anchor style common.
String in account?
Rare - prefer pubkey keys.
InitSpace enough?
Review generated size.
IMutable deploy?
No migrations possible - plan space.
Compression?
Not native on-chain.
Account JSON?
Off-chain only.
Schema registry?
In repo docs.
Codama?
Client decode alignment.
Rent spikes?
From unbounded Vec.
Agave 4.1.1?
Rent rules via SDK.
Audit focus?
Disc + LEN + migration.
Related
- Serialization Basics - Intro
- Account Discriminators - Tagging
- Rust for Solana Best Practices - General Rust
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.