Native Program Basics
10 examples to get you started with Native Programs - 7 basic and 3 intermediate.
Search across all documentation pages
10 examples to get you started with Native Programs - 7 basic and 3 intermediate.
cargo build-sbf.solana-program dependency.Native programs target SBF with cdylib crate type.
[lib]
crate-type = ["cdylib"]
[dependencies]
solana-program = "2.2"
borsh = "1.5"cdylib produces the deployable .so.solana-program to match Agave 4.1.1 SDK.Crate root wires modules and entrypoint.
#![no_std]
extern crate alloc;
mod error;
mod instruction;
mod processor;
use solana_program::entrypoint;
entrypoint!(processor::process_instruction);entrypoint! per crate.instruction.rs.Tag instructions with a Borsh enum.
use borsh::{BorshDeserialize, BorshSerialize};
#[derive(BorshSerialize, BorshDeserialize)]
pub enum HelloInstruction {
Greet { name: String },
}Related: Instruction Data (de)Serialization - parsing
Route parsed instructions to handlers.
pub fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
data: &[u8],
) -> ProgramResult {
let ix = HelloInstruction::deserialize(&mut &data[..])?;
match ix {
HelloInstruction::Greet { name } => greet(accounts, name),
}
}program_id into handlers that derive PDAs.? for error propagation.Related: The Entrypoint & Dispatch - patterns
Consume accounts in a fixed order.
let iter = &mut accounts.iter();
let payer = next_account_info(iter)?;
let state = next_account_info(iter)?;AccountMeta list.NotEnoughAccountKeys if iterator empty.Centralize domain errors.
#[repr(u32)]
pub enum MyError { BadName = 0 }
impl From<MyError> for ProgramError {
fn from(e: MyError) -> Self { ProgramError::Custom(e as u32) }
}ProgramError::Custom for clients.Define account size constant.
#[derive(BorshSerialize, BorshDeserialize)]
pub struct State { pub counter: u64 }
impl State {
pub const LEN: usize = 8;
}create_account.InitSpace is the macro equivalent.System Program allocates space and assigns owner.
invoke(
&system_instruction::create_account(
payer.key, state.key, rent, State::LEN as u64, program_id,
),
&[payer.clone(), state.clone(), system_program.clone()],
)?;Rent sysvar.Related: Creating Accounts via CPI - full flow
Borrow data, mutate, serialize back.
let mut state = State::deserialize(&mut &account.data.borrow()[..])?;
state.counter = state.counter.saturating_add(1);
state.serialize(&mut &mut account.data.borrow_mut()[..])?;Related: Reading & Writing Account Data - patterns
Debug with msg! during development.
solana_program::msg!("greet: {}", name);Related: Emitting Logs - logging guide
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.
Reviewed by Chris St. John·Last updated Jul 16, 2026