Skip to main content
Instruction handlers are the core functions that execute when your program receives an instruction. In Anchor, these handlers are defined as public functions within a module annotated with the #[program] attribute.

Basic Structure

Every instruction handler follows this pattern:
The first parameter is always a Context<T> type where T is a struct that defines the accounts required by the instruction.

The Context Type

The Context type provides access to non-argument inputs needed by the instruction:

Accessing Context Fields

program_id: The currently executing program’s address
accounts: Access to the deserialized and validated accounts
remaining_accounts: Accounts passed to the instruction but not specified in the Accounts struct
bumps: PDA bump seeds automatically discovered during validation

Complete Example

Here’s a complete example demonstrating instruction handlers with various parameter types:

Instruction Arguments

You can pass additional arguments to instruction handlers after the Context parameter:

Supported Argument Types

  • Primitive types: u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, bool
  • String and Vec<T>
  • Pubkey
  • Custom structs that implement AnchorSerialize and AnchorDeserialize

Return Values

All instruction handlers must return Result<()>. To return an error, use the err! macro or require! macro:

Best Practices

  1. Keep handlers focused: Each instruction should have a single, clear purpose
  2. Validate early: Perform validation checks at the start of the handler
  3. Use descriptive names: Choose clear, action-oriented names for your handlers
  4. Log important events: Use msg! to log important state changes
  5. Handle errors gracefully: Use custom errors to provide clear feedback

CPI Context

For cross-program invocations, use CpiContext instead of Context:
For CPIs with PDA signers: