Lesson content
Constraint Macros
Anchor validates accounts before your instruction logic runs. If any constraint fails, the transaction reverts.
Common Constraints
#[derive(Accounts)]
pub struct Enroll<'info> {
// PDA derivation + initialization
#[account(
init,
payer = learner,
space = 8 + Enrollment::INIT_SPACE,
seeds = [b"enrollment", course.course_id.as_bytes(), learner.key().as_ref()],
bump,
)]
pub enrollment: Account<'info, Enrollment>,
// Read-only, validate it's active
#[account(constraint = course.is_active @ ErrorCode::CourseNotActive)]
pub course: Account<'info, Course>,
// Must be a signer and mutable (pays rent)
#[account(mut)]
pub learner: Signer<'info>,
pub system_program: Program<'info, System>,
}Constraint Types
• `init` — create and initialize the account
• `mut` — account must be writable
• `seeds` + `bump` — PDA derivation and verification
• `has_one` — field must match another account's key
• `constraint` — arbitrary boolean expression
• `close` — close account and return lamports
• `realloc` — resize account data