Open this lesson in your favourite AI. It'll walk you through the why, explain the demo, and quiz you on the try-it list.
Anchor is the framework for writing Solana programs. It generates account validation, serialisation, and the IDL automatically. Most production Solana protocols are written in Anchor — understanding how it maps Rust to Solana's runtime is essential for reading and writing protocol code.
Anchor's macros do four things: define account types (#[account]), define instructions (#[derive(Accounts)] structs), generate clients via IDL, and validate account constraints at runtime.
cargo install --git https://github.com/coral-xyz/anchor anchor-cli). Run anchor init for a new project.anchor build. Deploy to localnet with anchor deploy.Use these three in order. Each builds on the one before.
In one paragraph, explain what Anchor does.
Walk me through how Anchor's macros transform Rust code into the runtime form.
Design an Anchor program with a non-trivial account constraint (e.g., 'recipient must have a token account for this mint').
use anchor_lang::prelude::*;
declare_id!("HelloAnchor1111111111111111111111111111111111");
#[program]
pub mod hello {
use super::*;
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
ctx.accounts.greeting.message = "hello".to_string();
Ok(())
}
}
#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(init, payer = user, space = 8 + 64)]
pub greeting: Account<'info, Greeting>,
#[account(mut)]
pub user: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct Greeting {
pub message: String,
}