CPI Basics
10 examples to get you started with CPIs - 7 basic and 3 intermediate.
Search across all documentation pages
10 examples to get you started with CPIs - 7 basic and 3 intermediate.
Call System Program transfer from your program.
use solana_program::program::invoke;
use solana_program::system_instruction;
invoke(
&system_instruction::transfer(from.key, to.key, lamports),
&[from.clone(), to.clone()],
)?;? to bubble CPI errors.Build Instruction with program id, accounts, data.
use solana_program::instruction::{AccountMeta, Instruction};
let ix = Instruction {
program_id: *token_program.key, // Pubkey by value; `key` is a field on AccountInfo
accounts: vec![/* AccountMeta */],
data: vec![/* opcode */],
};Instruction.program_id is a Pubkey, so dereference AccountInfo::key (&Pubkey). In Anchor, token_program.key() resolves instead via the Key trait.spl-token) for encoding.Invoke needs owned AccountInfo references in slice.
&[payer.clone(), vault.clone(), system_program.clone()]clone on AccountInfo is cheap ref clone.Failed CPI fails your instruction.
invoke(&ix, accounts).map_err(|e| {
solana_program::msg!("cpi failed");
e
})?;Pass token/system program account readonly.
let system_program = next_account_info(iter)?;
if system_program.key != &system_program::ID {
return Err(ProgramError::IncorrectProgramId);
}CPI cannot add signatures wallets did not provide.
if !payer.is_signer {
return Err(ProgramError::MissingRequiredSignature);
}invoke_signed.Some CPIs only read callee state.
// e.g. reading oracle - still passes accountsProgram signs CPI on behalf of PDA.
invoke_signed(&ix, accounts, &[&[b"vault", &[bump]]])?;Related: invoke vs invoke_signed
Transfer tokens with token program.
use spl_token::instruction as token_ix;
let ix = token_ix::transfer(
token_program.key,
source.key,
dest.key,
authority.key,
&[],
amount,
)?;
invoke(&ix, &[source.clone(), dest.clone(), authority.clone(), token_program.clone()])?;Related: CPI to SPL Token
CPIs can call programs that CPI again - max depth 4.
// Your program -> Token -> ... depth budgetRelated: CPI Depth & Limits
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