Writing On-Chain Programs with Anchor Framework

10 min read


1. Anchor Framework Setup and Project Structure πŸ› οΈ

Definition & The Problem

In vanilla (native) Solana development, writing a program feels like performing open-heart surgery with oven mitts:

  • You must manually deserialize raw byte arrays (&[u8]) using Borsh.
  • You have to manually inspect every single account in an array to verify that it is a signer, that its owner matches your program, and that it isn't an impostor account.
  • If you miss a single condition, someone drains your liquidity pool.
smali
Raw Transaction Bytes ➑️ [Manual Slice / Borsh Deserialization] ➑️ [15 lines of if/else security checks] ➑️ Logic

The Anchor Framework is an opinionated framework for Solana's Sealevel runtime. It provides Rust procedural macros to automate account serialization, validation checks, instruction routing, and Interface Definition Language (IDL) generation.


What is Possible vs. What is NOT Possible 🚧

What You CAN Do What You CANNOT Do Why the Boundary Exists
Generate strongly-typed client SDKs automatically via Anchor's generated IDL JSON. Use dynamic memory allocations (Vec, heap growth) carelessly. Solana programs compile to eBPF/SBF (Solana Bytecode Format). You are restricted to a tiny 32 KB heap and 4 KB stack frame.
Declare security rules declaratively using struct tags. Run continuous loops or listen for external network HTTP calls. On-chain code is deterministic. Programs only execute when an external transaction sends an instruction and lamports to cover Compute Units (CU).
Standardize instruction dispatching and routing with zero boilerplate. Bypass Solana's account ownership rules. The runtime enforces that only the program marked as an account's owner can write data to it or deduct lamports from it. Anchor cannot override runtime consensus rules.

Environment Setup

Anchor relies on Rust, the Solana CLI suite, Node.js/Yarn (for client tests), and the Anchor Version Manager (avm).

bash
# 1. Install avm (Anchor Version Manager)
cargo install --git https://github.com/coral-xyz/anchor avm --locked --force

# 2. Install the latest stable anchor-cli
avm install latest
avm use latest

# Verify installation (Ensure anchor-cli version matches your workspace anchor-lang version)
anchor --version

(Fun fact: Forgetting to match your CLI version with your Cargo dependencies is responsible for an estimated 73% of all developer keyboard smashes on Discord.)


Project Scaffolding & Anatomy

Run:

bash
anchor init vault_system
cd vault_system

Anchor generates this directory layout:

text
vault_system/
β”œβ”€β”€ Anchor.toml           <-- Workspace configuration (clusters, provider wallet, program IDs)
β”œβ”€β”€ Cargo.toml            <-- Rust workspace root
β”œβ”€β”€ programs/
β”‚   └── vault_system/
β”‚       β”œβ”€β”€ Cargo.toml    <-- Program dependencies (anchor-lang)
β”‚       └── src/
β”‚           └── lib.rs    <-- On-chain entrypoint & instruction logic
β”œβ”€β”€ tests/
β”‚   └── vault_system.ts   <-- Mocha/TypeScript integration tests
└── target/
    β”œβ”€β”€ idl/              <-- Generated IDL JSON (your contract's "ABI")
    └── deploy/           <-- Compiled program .so files and program keypairs

Anatomy of lib.rs

Open programs/vault_system/src/lib.rs. It contains three essential zones:

rust
use anchor_lang::prelude::*;

// 1. Program ID declaration (must match the keypair generated in target/deploy)
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");

// 2. Program module: holds your business logic functions
#[program]
pub mod vault_system {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        msg!("Vault initialized! Greetings from program: {:?}", ctx.program_id);
        Ok(())
    }
}

// 3. Validation struct: validates accounts BEFORE logic executes
#[derive(Accounts)]
pub struct Initialize {}

2. Account Validation Structs and Context Constraints πŸ›‘οΈ

Definition & The Problem

On Solana, programs are stateless, while accounts hold state. When an instruction is called, the caller passes an array of account public keys.

Without validation, an attacker could:

  1. Pass their own account pretending it is an admin account.
  2. Pass an account owned by a different program with malicious data layout.
  3. Pass a read-only account when your code expects a signer.

Anchor solves this by decoupling Account Validation (structural assertions) from Business Logic (instruction code).


The 8-Byte Account Discriminator

Whenever Anchor creates an account with #[account], it prepends an 8-byte discriminator to the beginning of the account data:

Discriminator=SHA256("account:<AccountStructName>")[0..8]\text{Discriminator} = \text{SHA256}(\text{"account:<AccountStructName>"})[0..8]

When an instruction deserializes an account, Anchor compares the first 8 bytes in storage against this hash. If someone passes an account of type UserStats into an instruction expecting VaultConfig, Anchor rejects the transaction immediately before your code runs, preventing type-confusion attacks.


Core Account Constraints

rust
#[derive(Accounts)]
#[instruction(vault_id: u64)] // Allows accessing instruction parameters inside constraints
pub struct InitializeVault<'info> {
    // 1. Initialize a new account via the System Program
    #[account(
        init,
        payer = authority,
        space = 8 + Vault::INIT_SPACE,
        seeds = [b"vault", authority.key().as_ref(), &vault_id.to_le_bytes()],
        bump
    )]
    pub vault: Account<'info, Vault>,

    // 2. Mutable signer (paying for space allocation)
    #[account(mut)]
    pub authority: Signer<'info>,

    // 3. System Program reference required for account creation
    pub system_program: Program<'info, System>,
}

#[account]
#[derive(InitSpace)] // Automatically calculates field byte sizes
pub struct Vault {
    pub authority: Pubkey, // 32 bytes
    pub vault_id: u64,     // 8 bytes
    pub balance: u64,      // 8 bytes
    pub bump: u8,          // 1 byte
}

Constraint Breakdown:

  • init: Tells Anchor to invoke the System Program to create an account, allocate its space, and assign its owner to your program.
  • payer = authority: Specifies who provides the lamports to fund the rent-exempt minimum balance.
  • space = 8 + Vault::INIT_SPACE: Total storage reserved (8-byte discriminator + fields).
  • seeds = [...] & bump: Derives a Program Derived Address (PDA). Anchor verifies that vault is the deterministic PDA derived from those seeds.
  • has_one = authority: Ensures vault.authority == authority.key(). If mismatched, it throws an error without manual if/else checks.

3. Instruction Handlers, State Mutation, and Custom Errors ⚑

Definition & The Problem

In bare-metal Solana, instructions return cryptic exit codes (e.g., InstructionError::Custom(0)). Finding bugs feels like deciphering ancient runes. Moreover, modifying data requires writing changes back into memory using raw slices.

Anchor provides:

  1. The Context<T> wrapper to access validated accounts.
  2. Automatic data serialization at the end of the instruction scope.
  3. The #[error_code] macro to return descriptive human-readable error messages on-chain.

Real Scenario: Implementing the Vault System

Let's write a vault that tracks deposited amounts, allows owner updates, and enforces safety bounds.

rust
use anchor_lang::prelude::*;

declare_id!("Vau1t11111111111111111111111111111111111111");

#[program]
pub mod vault_system {
    use super::*;

    pub fn initialize(ctx: Context<InitializeVault>, vault_id: u64) -> Result<()> {
        let vault = &mut ctx.accounts.vault;
        vault.authority = ctx.accounts.authority.key();
        vault.vault_id = vault_id;
        vault.balance = 0;
        vault.bump = ctx.bumps.vault; // Anchor 0.30+ provides bumps directly in ctx.bumps

        msg!("Vault {} created by {}", vault_id, vault.authority);
        Ok(())
    }

    pub fn deposit_record(ctx: Context<UpdateVault>, amount: u64) -> Result<()> {
        // Enforce conditions declaratively or imperatively
        require!(amount > 0, VaultError::ZeroDeposit);
        require!(amount <= 1_000_000_000, VaultError::DepositTooLarge); // Cap at 1,000 SOL

        let vault = &mut ctx.accounts.vault;

        // Checked math to prevent overflow panics
        vault.balance = vault.balance
            .checked_add(amount)
            .ok_or(VaultError::MathOverflow)?;

        msg!("Deposit recorded. New virtual balance: {}", vault.balance);
        Ok(())
    }
}

#[derive(Accounts)]
pub struct UpdateVault<'info> {
    #[account(
        mut,
        has_one = authority @ VaultError::Unauthorized,
        seeds = [b"vault", authority.key().as_ref(), &vault.vault_id.to_le_bytes()],
        bump = vault.bump
    )]
    pub vault: Account<'info, Vault>,

    pub authority: Signer<'info>,
}

#[account]
#[derive(InitSpace)]
pub struct Vault {
    pub authority: Pubkey,
    pub vault_id: u64,
    pub balance: u64,
    pub bump: u8,
}

// Custom On-Chain Errors
#[error_code]
pub enum VaultError {
    #[msg("Deposit amount must be strictly greater than 0.")]
    ZeroDeposit,
    #[msg("Deposit exceeds single-transaction safety threshold.")]
    DepositTooLarge,
    #[msg("You do not have permission to modify this vault.")]
    Unauthorized,
    #[msg("Arithmetic overflow detected.")]
    MathOverflow,
}

What Happens Behind the Curtain?

When deposit_record terminates:

  1. vault.balance is updated in memory.
  2. The #[account] macro's drop implementation re-serializes the Vault struct back into the raw account buffer (ctx.accounts.vault.to_account_info().data).
  3. If an error is returned via require!, the entire transaction rolls back, burning the compute units consumed up to that point.

4. Cross-Program Invocations (CPI) and PDA Signing 🀝

Definition & The Problem

Smart contracts rarely live in isolation. Your vault needs to move actual native SOL or SPL tokens.

  • To move native SOL out of an account, you must invoke the System Program.
  • To move SPL tokens, you must invoke the SPL Token Program.

The Problem: Calling another on-chain program is called a Cross-Program Invocation (CPI). But if funds are locked inside a Program Derived Address (PDA), who signs the CPI? PDAs have no private keysβ€”they lie off the Ed25519 elliptic curve.

The Solution: PDA Signing

A program can sign on behalf of a PDA if it proves to the runtime that it owns the derivation seeds.
Anchor provides CpiContext and CpiContext::new_with_signer to handle both standard and PDA-signed CPIs.

gherkin
+------------------+         CPI via CpiContext          +------------------+
|   Your Program   | ----------------------------------> |  System Program  |
|  (with PDA seed) | <---------------------------------- | (Transfers SOL)  |
+------------------+           Transfer Success          +------------------+

CPI Example: Depositing and Withdrawing Native SOL

Here is how a user deposits SOL into the PDA vault, and how the program signs with PDA seeds to refund or transfer it back out.

rust
use anchor_lang::prelude::*;
use anchor_lang::system_program::{transfer, Transfer};

#[program]
pub mod sol_vault {
    use super::*;

    // 1. User deposits native SOL into the PDA vault (User is the signer)
    pub fn deposit_sol(ctx: Context<DepositSol>, amount: u64) -> Result<()> {
        let cpi_program = ctx.accounts.system_program.to_account_info();
        let cpi_accounts = Transfer {
            from: ctx.accounts.user.to_account_info(),
            to: ctx.accounts.vault.to_account_info(),
        };

        let cpi_ctx = CpiContext::new(cpi_program, cpi_accounts);
        transfer(cpi_ctx, amount)?;

        ctx.accounts.vault.balance += amount;
        Ok(())
    }

    // 2. Vault refunds SOL to user (PDA must sign because vault has no private key!)
    pub fn withdraw_sol(ctx: Context<WithdrawSol>, amount: u64) -> Result<()> {
        require!(ctx.accounts.vault.balance >= amount, VaultError::InsufficientFunds);

        let user_key = ctx.accounts.authority.key();
        let vault_id_bytes = ctx.accounts.vault.vault_id.to_le_bytes();

        // Construct the signer seeds: &[ &[ &[u8] ] ]
        let seeds: &[&[&[u8]]] = &[&[
            b"vault",
            user_key.as_ref(),
            vault_id_bytes.as_ref(),
            &[ctx.accounts.vault.bump], // The bump seed calculated during initialization
        ]];

        let cpi_program = ctx.accounts.system_program.to_account_info();
        let cpi_accounts = Transfer {
            from: ctx.accounts.vault.to_account_info(),
            to: ctx.accounts.authority.to_account_info(),
        };

        // Pass signer seeds to CPI context
        let cpi_ctx = CpiContext::new_with_signer(cpi_program, cpi_accounts, seeds);
        transfer(cpi_ctx, amount)?;

        ctx.accounts.vault.balance -= amount;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct DepositSol<'info> {
    #[account(
        mut,
        seeds = [b"vault", authority.key().as_ref(), &vault.vault_id.to_le_bytes()],
        bump = vault.bump
    )]
    pub vault: Account<'info, Vault>,
    #[account(mut)]
    pub user: Signer<'info>,
    /// CHECK: The authority who owns the vault
    pub authority: AccountInfo<'info>,
    pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct WithdrawSol<'info> {
    #[account(
        mut,
        has_one = authority @ VaultError::Unauthorized,
        seeds = [b"vault", authority.key().as_ref(), &vault.vault_id.to_le_bytes()],
        bump = vault.bump
    )]
    pub vault: Account<'info, Vault>,
    #[account(mut)]
    pub authority: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[account]
#[derive(InitSpace)]
pub struct Vault {
    pub authority: Pubkey,
    pub vault_id: u64,
    pub balance: u64,
    pub bump: u8,
}

#[error_code]
pub enum VaultError {
    #[msg("Unauthorized access.")]
    Unauthorized,
    #[msg("Insufficient balance in vault.")]
    InsufficientFunds,
}

CPI Scope, Limits, and Boundaries βš™οΈ

  1. Max Call Depth: CPIs have a maximum depth limit of 4 calls (A→B→C→DA \rightarrow B \rightarrow C \rightarrow D). Attempting a fifth re-entrant invocation immediately halts execution with an error.
  2. Compute Unit (CU) Inheritance: The child program shares the same Compute Budget pool as the parent program. If your caller program has 25,000 CU remaining and calls an SPL token transfer that costs 30,000 CU, the entire transaction fails due to Compute Budget exhaustion.
  3. Seed Length Constraints: Individual seeds cannot exceed 32 bytes, and there can be at most 16 seeds used to derive a single PDA.
  4. Re-entrancy Protection: Solana prevents direct re-entrancy on the exact same instruction without privilege validation; an account cannot be borrowed mutably twice in the same scope.

5. Mental Model Checklist & Summary 🧠

When developing in Anchor, follow this sequence:

  1. Derive State Layout: Define your #[account] data structures, calculate space using #[derive(InitSpace)], and remember the 8-byte discriminator.
  2. Lock Down the Perimeter: Use #[derive(Accounts)] to define security boundaries (signer, mut, has_one, seeds, bump) before writing any logic.
  3. Execute Logic: Keep instruction handlers focused purely on math and business rules. Use checked arithmetic (checked_add, checked_sub).
  4. Invoke External Programs: If transferring tokens or interacting with other contracts, use CpiContext::new (user-signed) or CpiContext::new_with_signer (PDA-signed).

References & Further Reading πŸ“š

Challenge

You are implementing a token swap function within an Anchor Solana program. This function needs to execute a CPI (Cross-Program Invocation) to transfer tokens from a source account to a destination account.

Your task is to complete the execute_token_transfer function. You must correctly define the CpiContext for the Solana Token Program (using a placeholder instruction transfer) and call the transfer logic.

  • Assume token_program is the globally initialized CpiContext handle for the Token Program.
  • The method token_program.transfer() requires the following arguments:
    1. The CpiAccount handle for the source token account.
    2. The CpiAccount handle for the destination token account.
    3. The CpiAccount handle for the system program (which often acts as the payer in token transfers).
    4. The amount to transfer (u64).

Complete the function call using the provided variables.

Expected result

The execute_token_transfer function must be completed to correctly call the self.token_program.transfer() method, passing the source_account, destination_account, payer_system_account, and the amount parameter in the correct sequence. The function must return the result of the CPI call wrapped in a Result.

rust

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.