Skip to main content
Anchor provides several powerful macros that reduce boilerplate and enforce security best practices.

Program macros

#[program]

Defines the module containing instruction handlers.
#[program]
pub mod my_program {
    use super::*;
    
    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        // Instruction logic
        Ok(())
    }
}

declare_id!

Declares the program’s on-chain address.
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
See Program Structure for more details.

Account macros

#[derive(Accounts)]

Validates and deserializes accounts for an instruction.
#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(init, payer = user, space = 8 + 8)]
    pub data: Account<'info, Data>,
    #[account(mut)]
    pub user: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[account]

Creates a custom account type with automatic serialization.
#[account]
pub struct Data {
    pub value: u64,
}

Event macros

#[event]

Defines an event that can be emitted.
#[event]
pub struct DataUpdated {
    pub old_value: u64,
    pub new_value: u64,
}

emit!

Emits an event from your program.
emit!(DataUpdated {
    old_value: 0,
    new_value: 42,
});

Error macros

#[error_code]

Defines custom error codes.
#[error_code]
pub enum ErrorCode {
    #[msg("Invalid authority")]
    InvalidAuthority,
    #[msg("Insufficient funds")]
    InsufficientFunds,
}
See Errors for more details.

Constraint macros

require!

Assert a condition is true.
require!(ctx.accounts.user.key() == ctx.accounts.data.authority, ErrorCode::InvalidAuthority);

require_keys_eq!

Assert two public keys are equal.
require_keys_eq!(ctx.accounts.user.key(), ctx.accounts.data.authority);
See Account Constraints for all constraints.

Build docs developers (and LLMs) love