Account Constraints
Anchor Account Constraints Examples
Minimal reference examples for Anchor account constraints.
See the account constraints source code for implementation details.
Normal Constraints
#[account(signer)]
Description: Checks the given account signed the transaction. Consider using the
Signer type if you would only have this constraint on the account.
Examples: Github
|
Solpg
#[account(mut)]
Description: Checks the given account is mutable. Makes anchor persist any state
changes.
Examples: Github
|
Solpg
#[account(init)]
Description: Creates the account via a CPI to the system program and initializes
it (sets its account discriminator).
Examples: Github
|
Solpg
#[account(init_if_needed)]
Description: Same as init but only runs if the account does not exist yet.
Requires init-if-needed cargo feature.
Examples: Github
|
Solpg
#[account(seeds, bump)]
Description: Checks that given account is a PDA derived from the currently
executing program, the seeds, and if provided, the bump.
Examples: Github
|
Solpg
#[account(has_one = target)]
Description: Checks the target field on the account matches the key of the
target field in the Accounts struct.
Examples: Github
|
Solpg
#[account(address = expr)]
Description: Checks the account key matches the pubkey.
Examples: Github
|
Solpg
#[account(owner = expr)]
Description: Checks the account owner matches expr.
Examples: Github
|
Solpg
#[account(executable)]
Description: Checks the account is executable (i.e. the account is a program).
Examples: Github
|
Solpg
#[account(zero)]
Description: Checks the account discriminator is zero. Use for accounts larger
than 10 Kibibyte.
Examples: Github
|
Solpg
#[account(close = target)]
Description: Closes the account by sending lamports to target and resetting
data.
Examples: Github
|
Solpg
#[account(constraint = expr)]
Description: Custom constraint that checks whether the given expression
evaluates to true.
Examples: Github
|
Solpg
#[account(realloc)]
Description: Used to realloc program account space at the beginning of an
instruction.
Examples: Github
|
Solpg
SPL Constraints
#[account(token::*)]
Description: Create or validate token accounts with specified mint and
authority.
Examples: Github
|
Solpg
#[account(mint::*)]
Description: Create or validate mint accounts with specified parameters.
Examples: Github
|
Solpg
#[account(associated_token::*)]
Description: Create or validate associated token accounts.
Examples: Github
|
Solpg
#[account(*::token_program = expr)]
Description: The token_program can optionally be overridden.
Examples: Github
|
Solpg
Instruction Attribute
#[instruction(...)]
Description: You can access the instruction's arguments with the
#[instruction(..)]
attribute. You must list them in the same order as in the
instruction handler but you can omit all arguments after the last one you need.
Skipping arguments will result in an error.
Valid Usage:
Invalid Usage, will result in an error: