Anchor account constraints: what each one checks

Anchor's account types and #[account(...)] constraints read as the if statements they generate: what each one checks, the attack it stops, and what it leaves to you.

On this page
  1. Constraints are if statements
  2. Account types
  3. Constraints
  4. What constraints don't check

Constraints are if statements

A Solana instruction receives whatever accounts the transaction builder chose. Every one is untrusted input. A raw program checks each account by hand, and a forgotten check is the most common way programs get drained.

Anchor moves those checks into the #[derive(Accounts)] struct. Each field's type and #[account(...)] attribute generate validation code that runs before the handler. Anchor got easier for me once I read constraints as the if statements they compile to rather than as configuration. This is the list.

Account types

The field type sets the first checks:

Type Checks
Signer<'info> The account signed the transaction
Account<'info, T> Owner is this program (or T's program), first 8 bytes match T's discriminator, data deserialises as T
Program<'info, T> The account is the expected program and is executable
SystemAccount<'info> Owner is the System Program
InterfaceAccount<'info, T> Like Account, but accepts several owners, such as SPL Token and Token-2022
AccountLoader<'info, T> Owner and discriminator, with zero-copy access for large accounts
UncheckedAccount<'info> Nothing

The discriminator is what stops type confusion. It is 8 bytes derived from the struct name, written at the start of the account when it's created. Without it, an attacker could pass a Profile where a Vault was expected, as long as the bytes deserialised. It is also why account space starts with 8 +.

UncheckedAccount only compiles with a /// CHECK: comment explaining why it is safe. In review, each of those comments is a place to look.

Constraints

mut

Checks the account was marked writable in the transaction, and writes changed data back when the handler returns. Mark every account you modify, including ones whose lamports change.

has_one = field

#[account(mut, has_one = authority)]
pub vault: Account<'info, Vault>,
pub authority: Signer<'info>,

Checks vault.authority == authority.key(). Without it, any signer could pass someone else's vault next to their own signature. has_one with a Signer is the standard owner-only check. has_one alone does not require a signature; the Signer type does.

constraint = expression @ Error

#[account(constraint = pool.open @ PoolError::Closed)]
pub pool: Account<'info, Pool>,

Any boolean expression, with an optional custom error. For business rules the other constraints don't cover.

address = key and owner = program

Check the address or owner directly. address suits fixed accounts such as a known admin or oracle. owner matters most on UncheckedAccount, where nothing else checks it.

seeds = [...], bump

Derives a program derived address from the seeds and checks the account sits at it. A bare bump searches for the canonical bump and puts it in ctx.bumps. bump = account.bump uses the stored value and checks with one hash, which costs less compute.

init, payer, space

#[account(
    init,
    payer = user,
    space = 8 + Vault::INIT_SPACE,
    seeds = [b"vault", user.key().as_ref()],
    bump,
)]
pub vault: Account<'info, Vault>,

Creates the account through the System Program, funds it to rent exemption from payer, assigns it to the program and writes the discriminator. Creation fails if an account already exists at the address, so init also prevents reinitialisation: calling the create instruction again can't reset an existing vault.

#[derive(InitSpace)] computes INIT_SPACE. Strings and vectors need #[max_len(n)].

init_if_needed

Creates the account if missing, otherwise loads it. It sits behind a feature flag because it brings reinitialisation back: the handler now runs on new and existing accounts and must not overwrite state the second time. I'd only use it when the alternative is a much worse experience for users, with a test that calls the instruction twice.

close = destination

Runs after the handler. Moves all lamports to destination, returns the account to the System Program and shrinks its data to zero. Closing by hand is easy to get wrong: moving only the lamports leaves the account usable until the end of the transaction, and a later instruction in the same transaction can top it back up to rent exemption and revive it.

realloc = size, realloc::payer, realloc::zero

Resizes the account and charges or refunds rent through the payer. Growth is capped at 10 KiB per instruction.

What constraints don't check

Anchor checks what you ask for. These stay with you:

  • Arithmetic. Use checked_add and friends, or set overflow-checks = true for release builds in Cargo.toml.
  • Aliased accounts. If an instruction takes from and to, add constraint = from.key() != to.key(), or a transfer to yourself can double-count.
  • remaining_accounts. Nothing passed this way is checked.
  • CPI targets. Type the target as Program<'info, T>, not UncheckedAccount, or a caller can swap in their own program.
  • Business logic. Constraints prove the accounts are the right ones. They can't prove the instruction does the right thing with them.

Next I want numbers on what these checks cost in compute.