Accounts & Constraints Best Practices
Fail-closed, minimal-trust account structs for production Anchor programs.
How to Use This List
- Review every new
#[derive(Accounts)]against this list. - Treat UncheckedAccount as a security exception requiring comment.
- Re-run review when adding
init_if_neededor token CPIs.
A - Type hygiene
- Use Signer for authorities not UncheckedAccount with manual is_signer.
- Prefer Account<T> over UncheckedAccount for program-owned state.
- Include Program<Token/System> explicitly for every CPI target.
- Use Interface types for Token-2022 when supporting extensions.
B - Constraints
- Validate PDAs with seeds + stored bump on every instruction.
- Add has_one for authority relationships instead of handler-only checks.
- Map constraint failures to #[error_code] with
@syntax. - Avoid init_if_needed without authority checks on existing accounts.
C - Sizing and lifecycle
- Use InitSpace + max_len for variable-length fields.
- Close accounts to a defined recipient to reclaim rent.
- Document migrations when space grows with realloc or new accounts.
- Never trust client-provided account order without type constraints.
FAQs
What Anchor version does this site use?
0.32.1 for anchor-lang, Anchor CLI, and examples in this section.
Do I need Solana CLI alongside Anchor?
Yes. Solana CLI 3.0.10 handles keypairs, airdrops, and solana program inspection.
Where does the IDL live after build?
target/idl/<program>.json in your workspace.
Can I mix UncheckedAccount with Signer?
Yes, but every unchecked field needs explicit constraints or handler checks.
How do I test without devnet?
Use anchor test with Surfpool 0.12.0 or LiteSVM 0.6.x in CI.
What is the 8-byte prefix on account data?
Anchor account discriminator; do not strip it when sizing space.
Should I commit generated IDL?
Yes, or publish on-chain IDL so clients have a canonical source.
How do I debug constraint failures?
Run with logs; Anchor prints constraint name and account index.
Does Anchor work on Agave 4.1.1?
Yes. This stack targets Agave validators with Solana CLI 3.0.10.
What should I read next in this section?
See sibling articles linked in Related for deeper accounts bp topics.
Related
- Account Types - wrappers
- Custom Constraints - invariants
- Anchor Basics Best Practices - workspace habits
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.