Learn Anchor - 10 Code Examples & CST Typing Practice Test
Anchor is a Rust-based framework for Solana smart contract (program) development, testing, and deployment. It simplifies building Solana dApps by providing a high-level abstraction over Solana programs and client interactions.
View all 10 Anchor code examples →
Learn ANCHOR with Real Code Examples
Updated Nov 24, 2025
Code Sample Descriptions
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Frequently Asked Questions about Anchor
What is Anchor?
Anchor is a Rust-based framework for Solana smart contract (program) development, testing, and deployment. It simplifies building Solana dApps by providing a high-level abstraction over Solana programs and client interactions.
What are the primary use cases for Anchor?
Writing Solana smart contracts in Rust. Generating client interfaces (IDL) for programs. Testing programs with simulated Solana clusters. Deploying Solana programs to devnet/testnet/mainnet. Automating transactions and client-side interactions
What are the strengths of Anchor?
Reduces boilerplate and enforces best practices. Simplifies account and PDA management. Strong testing support with local validator. IDL provides type-safe client interaction. Large adoption in Solana DeFi and NFT projects
What are the limitations of Anchor?
Only for Solana blockchain. Requires familiarity with Rust programming. Program size limitations dictated by Solana. Learning curve for Anchor-specific macros and patterns. Smaller ecosystem compared to Ethereum tooling like Hardhat/Brownie
How can I practice Anchor typing speed?
CodeSpeedTest offers 10+ real Anchor code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.