Programs Basics
9 examples to get you started with Solana programs on the Sealevel runtime - 6 basic and 3 intermediate.
Prerequisites
cargo install --git https://github.com/coral-xyz/anchor --tag v0.32.1 anchor-cli
anchor --versionBasic Examples
1. Minimal Anchor Program
use anchor_lang::prelude::*;
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
#[program]
pub mod hello {
use super::*;
pub fn initialize(_ctx: Context<Initialize>) -> Result<()> {
msg!("Hello from Agave 4.1.1");
Ok(())
}
}
#[derive(Accounts)]
pub struct Initialize {}- Programs are compiled to sBPF bytecode deployed to executable accounts
#[program]generates the instruction dispatcher and entrypoint
Related: The Program Entrypoint
2. Deploy to Devnet
anchor build
anchor deploy --provider.cluster devnet
solana program show <PROGRAM_ID>- Deploy uploads bytecode via BPF Upgradeable Loader
- Program ID comes from
declare_id!keypair
Related: Program Loaders & Upgradeability
3. Invoke a Program from CLI
anchor run test
# Or: solana program invoke <PROGRAM_ID> --data <BYTES>- Clients send transactions with instructions targeting your program ID
- Instruction data selects which handler runs
4. Programs Are Stateless
#[account]
pub struct Counter { pub value: u64 }
// State in Counter account, not in program binary- Logic in executable account; data in separate owned accounts
Related: Stateless Programs
5. Pass Accounts to Instructions
#[derive(Accounts)]
pub struct Increment<'info> {
#[account(mut)]
pub counter: Account<'info, Counter>,
}- Every account the program reads/writes must appear in the transaction
6. Read Compute Units in Logs
solana confirm -v <SIG> | grep "consumed"- Each instruction consumes CU from the transaction budget
Related: Compute Units & Budgets
Intermediate Examples
7. Cross-Program Invocation (CPI)
use anchor_lang::system_program;
pub fn fund(ctx: Context<Fund>, lamports: u64) -> Result<()> {
system_program::transfer(
CpiContext::new(ctx.accounts.system_program.to_account_info(), /* ... */),
lamports,
)?;
Ok(())
}- Programs call other programs via CPI with declared accounts
8. Parallel-Safe Account Design
#[account(seeds = [b"user", user.key().as_ref()], bump)]
pub position: Account<'info, Position>,- Non-overlapping accounts let Sealevel execute txs in parallel
Related: Sealevel Parallel Execution
9. Test with Surfpool
npx surfpool@0.12.0 run anchor test- Surfpool 0.12.0 provides fast local Agave-compatible testing
Stack versions: This page was written for Agave 4.1.1, Solana CLI 3.0.10, Anchor 0.32.1, anchor-lang 0.32.1, Rust 1.91.1, @solana/kit 7.0.0, Surfpool 0.12.0, and LiteSVM 0.6.x.