Learn ANCHOR with Real Code Examples
Updated Nov 24, 2025
Code Sample Descriptions
1
Anchor Simple Counter Program
#[program]
mod counter {
use super::*;
#[state]
pub struct Counter {
pub value: u64,
}
impl Counter {
pub fn new(ctx: Context<New>) -> Result<Self> {
Ok(Counter { value: 0 })
}
pub fn increment(&mut self, ctx: Context<Increment>) -> Result<()> {
self.value += 1;
Ok(())
}
pub fn reset(&mut self, ctx: Context<Reset>) -> Result<()> {
self.value = 0;
Ok(())
}
}
}
A minimal Anchor program defining a counter with increment and reset functionality, demonstrating the use of Anchor macros and client interaction.
2
Anchor Token Mint Example
#[program]
mod token_mint {
use super::*;
pub fn mint_tokens(ctx: Context<MintTokens>, amount: u64) -> Result<()> {
let cpi_accounts = token::MintTo {
mint: ctx.accounts.mint.to_account_info(),
to: ctx.accounts.receiver.to_account_info(),
authority: ctx.accounts.authority.to_account_info(),
};
let cpi_program = ctx.accounts.token_program.to_account_info();
token::mint_to(CpiContext::new(cpi_program, cpi_accounts), amount)?;
Ok(())
}
}
Defines a simple Anchor program to mint SPL tokens to a user.
3
Anchor Initialize Account Example
#[program]
mod init_account {
use super::*;
#[derive(Accounts)]
pub struct Init<'info> {
#[account(init, payer=user, space=8+8)]
pub my_account: ProgramAccount<'info, MyAccount>,
#[account(signer)]
pub user: AccountInfo<'info>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct MyAccount {
pub data: u64,
}
pub fn create(ctx: Context<Init>) -> Result<()> {
ctx.accounts.my_account.data = 0;
Ok(())
}
}
Initializes a new account using Anchor with default values.
4
Anchor Transfer SOL Example
#[program]
mod sol_transfer {
use super::*;
pub fn transfer(ctx: Context<Transfer>, amount: u64) -> Result<()> {
**ctx.accounts.from.try_borrow_mut_lamports()? -= amount;
**ctx.accounts.to.try_borrow_mut_lamports()? += amount;
Ok(())
}
#[derive(Accounts)]
pub struct Transfer<'info> {
#[account(mut)]
pub from: Signer<'info>,
#[account(mut)]
pub to: AccountInfo<'info>,
}
}
Transfers SOL from one account to another using Anchor.
5
Anchor PDA Example
#[program]
mod pda_example {
use super::*;
pub fn store_data(ctx: Context<StoreData>, value: u64) -> Result<()> {
let my_account = &mut ctx.accounts.my_account;
my_account.value = value;
Ok(())
}
#[derive(Accounts)]
pub struct StoreData<'info> {
#[account(mut, seeds=[b"my_seed".as_ref()], bump)]
pub my_account: ProgramAccount<'info, MyAccount>,
}
#[account]
pub struct MyAccount {
pub value: u64,
}
}
Uses a program-derived address (PDA) to store data securely.
6
Anchor Multisig Example
#[program]
mod multisig {
use super::*;
#[account]
pub struct MultiSig {
pub approvals: u8,
pub threshold: u8,
}
pub fn approve(ctx: Context<Approve>) -> Result<()> {
let multisig = &mut ctx.accounts.multisig;
multisig.approvals += 1;
if multisig.approvals >= multisig.threshold {
// Execute transaction
}
Ok(())
}
#[derive(Accounts)]
pub struct Approve<'info> {
#[account(mut)]
pub multisig: ProgramAccount<'info, MultiSig>,
pub signer: Signer<'info>,
}
}
A minimal multisig contract where multiple signatures are required to execute a function.
7
Anchor Escrow Example
#[program]
mod escrow {
use super::*;
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
ctx.accounts.escrow.amount = 0;
Ok(())
}
#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(init, payer=user, space=8+8)]
pub escrow: ProgramAccount<'info, Escrow>,
#[account(signer)]
pub user: AccountInfo<'info>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct Escrow {
pub amount: u64,
}
}
Implements a basic escrow contract for token exchange.
8
Anchor Event Emission Example
#[program]
mod events {
use super::*;
pub fn trigger_event(ctx: Context<Trigger>, value: u64) -> Result<()> {
emit!(MyEvent { value });
Ok(())
}
#[event]
pub struct MyEvent {
pub value: u64,
}
#[derive(Accounts)]
pub struct Trigger<'info> {}
}
Emits an event when a function is called in an Anchor program.
9
Anchor Custom Error Example
#[program]
mod custom_error {
use super::*;
pub fn check_value(ctx: Context<Check>, value: u64) -> Result<()> {
if value > 100 {
return Err(ErrorCode::ValueTooHigh.into());
}
Ok(())
}
#[error_code]
pub enum ErrorCode {
#[msg("Value exceeds the allowed limit")]
ValueTooHigh,
}
#[derive(Accounts)]
pub struct Check<'info> {}
}
Demonstrates defining and using custom errors in Anchor.
10
Anchor Program With Seeds Example
#[program]
mod seeds_example {
use super::*;
pub fn create_account(ctx: Context<Create>, seed: u64) -> Result<()> {
let account = &mut ctx.accounts.my_account;
account.data = seed;
Ok(())
}
#[derive(Accounts)]
pub struct Create<'info> {
#[account(init, seeds=[b"seed", &seed.to_le_bytes()], bump, payer=user, space=8+8)]
pub my_account: ProgramAccount<'info, MyAccount>,
#[account(signer)]
pub user: AccountInfo<'info>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct MyAccount {
pub data: u64,
}
}
Uses seeds to deterministically create program accounts.