Lesson content
Anchor Overview
Anchor is a framework that reduces Solana program boilerplate. It provides:
• **Macros** for account validation (`#[account]`, `#[derive(Accounts)]`)
• **Auto-generated IDL** — interface definition for clients
• **Built-in serialization** via Borsh
• **Error handling** with custom error codes
Program Structure
use anchor_lang::prelude::*;
declare_id!("YourProgramIdHere");
#[program]
pub mod my_program {
use super::*;
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
let config = &mut ctx.accounts.config;
config.authority = ctx.accounts.authority.key();
Ok(())
}
}
#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(init, payer = authority, space = 8 + Config::INIT_SPACE)]
pub config: Account<'info, Config>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[account]
#[derive(InitSpace)]
pub struct Config {
pub authority: Pubkey,
}Key Components
• `declare_id!` — sets the program's public key
• `#[program]` — marks the instruction handler module
• `Context<T>` — provides validated accounts to each handler
• `#[account]` — marks a struct as a Solana account (auto-adds 8-byte discriminator)