How to use the invoke_signed function for Cross-Program Invocations on Solana when the calling program needs to sign as a PDA, with Anchor CpiContext and Native Rust examples.
SummaryUse invoke_signed when the calling program needs to sign on behalf of a
PDA it owns. The runtime derives PDA pubkeys from the provided signer seeds
and adds them to the set of valid signers before privilege checking.
When a CPI requires a PDA signer, use
invoke_signed
with the signer seeds used to derive the
PDA. For details on how the runtime verifies PDA signatures,
see PDA Signing.
Security: Your program decides what its PDAs signinvoke_signed signs for any PDA your program can derive from the seeds
you pass. Build signers_seeds from accounts you’ve validated and from
values stored in program state, such as the stored bump. If the seeds come
from instruction data, the caller chooses which of your PDAs signs, and
can move funds out of a vault that isn’t theirs. See
Control what a PDA signature authorizes.
The examples below make a CPI with PDA signers using Anchor and Native Rust.
Each example includes a single instruction to transfer SOL from a PDA to a
recipient account, using a CPI signed by the PDA.
The following examples show two approaches to implementing CPIs in an
Anchor program. The examples are
functionally equivalent, but demonstrate different levels of abstraction.
Example 1: Uses Anchor’s CpiContext and helper function.
Example 2: Uses the system_instruction::transfer function from
solana_program crate. (Example 1 is an abstraction of this
implementation.)
Example 3: Constructs the CPI instruction manually. This approach is
useful when there is no crate available to help build the instruction you want
to invoke.
To run one of these examples locally with the Anchor CLI:
Create a project with a single-file program and a Mocha test:
Terminal
anchor init cpi --template single --test-template mochacd cpi
Replace programs/cpi/src/lib.rs with the program below and
tests/cpi.ts with the test.
Point the program’s declare_id! at your project’s program ID:
Terminal
anchor keys sync
Without this step, anchor build only warns
Program ID mismatch detected, and anchor test fails with an error such
as DeclaredProgramIdMismatch (Anchor 1.1.2) or
This program may not be used for executing instructions.
Build the program and run the test:
Terminal
anchor test
use anchor_lang::prelude::*;use anchor_lang::system_program::{transfer, Transfer};declare_id!("BrcdB9sV7z9DvF9rDHG263HUxXgJM3iCQdF36TcxbFEn");#[program]pub mod cpi { use super::*; pub fn sol_transfer(ctx: Context<SolTransfer>, amount: u64) -> Result<()> { let from_pubkey = ctx.accounts.pda_account.to_account_info(); let to_pubkey = ctx.accounts.recipient.to_account_info(); let program_id = ctx.accounts.system_program.key(); let seed = to_pubkey.key(); let bump_seed = ctx.bumps.pda_account; let signer_seeds: &[&[&[u8]]] = &[&[b"pda", seed.as_ref(), &[bump_seed]]]; let cpi_context = CpiContext::new( program_id, Transfer { from: from_pubkey, to: to_pubkey, }, ) .with_signer(signer_seeds); transfer(cpi_context, amount)?; Ok(()) }}#[derive(Accounts)]pub struct SolTransfer<'info> { #[account( mut, seeds = [b"pda", recipient.key().as_ref()], bump, )] pda_account: SystemAccount<'info>, #[account(mut)] recipient: SystemAccount<'info>, system_program: Program<'info, System>,}
use anchor_lang::prelude::*;use anchor_lang::solana_program::{program::invoke_signed, system_instruction};declare_id!("BrcdB9sV7z9DvF9rDHG263HUxXgJM3iCQdF36TcxbFEn");#[program]pub mod cpi { use super::*; pub fn sol_transfer(ctx: Context<SolTransfer>, amount: u64) -> Result<()> { let from_pubkey = ctx.accounts.pda_account.to_account_info(); let to_pubkey = ctx.accounts.recipient.to_account_info(); let program_id = ctx.accounts.system_program.to_account_info(); let seed = to_pubkey.key(); let bump_seed = ctx.bumps.pda_account; let signer_seeds: &[&[&[u8]]] = &[&[b"pda", seed.as_ref(), &[bump_seed]]]; let instruction = &system_instruction::transfer(&from_pubkey.key(), &to_pubkey.key(), amount); invoke_signed(instruction, &[from_pubkey, to_pubkey, program_id], signer_seeds)?; Ok(()) }}#[derive(Accounts)]pub struct SolTransfer<'info> { #[account( mut, seeds = [b"pda", recipient.key().as_ref()], bump, )] pda_account: SystemAccount<'info>, #[account(mut)] recipient: SystemAccount<'info>, system_program: Program<'info, System>,}
use anchor_lang::prelude::*;use anchor_lang::solana_program::{program::invoke_signed, instruction::{Instruction, AccountMeta}};declare_id!("BrcdB9sV7z9DvF9rDHG263HUxXgJM3iCQdF36TcxbFEn");#[program]pub mod cpi { use super::*; pub fn sol_transfer(ctx: Context<SolTransfer>, amount: u64) -> Result<()> { let from_pubkey = ctx.accounts.pda_account.to_account_info(); let to_pubkey = ctx.accounts.recipient.to_account_info(); let program_id = ctx.accounts.system_program.to_account_info(); // Get PDA signer seeds let seed = to_pubkey.key(); let bump_seed = ctx.bumps.pda_account; let signer_seeds: &[&[&[u8]]] = &[&[b"pda", seed.as_ref(), &[bump_seed]]]; // Prepare instruction AccountMetas let account_metas = vec![ AccountMeta::new(from_pubkey.key(), true), AccountMeta::new(to_pubkey.key(), false), ]; // SOL transfer instruction discriminator let instruction_discriminator: u32 = 2; // Prepare instruction data let mut instruction_data = Vec::with_capacity(4 + 8); instruction_data.extend_from_slice(&instruction_discriminator.to_le_bytes()); instruction_data.extend_from_slice(&amount.to_le_bytes()); // Create instruction let instruction = Instruction { program_id: program_id.key(), accounts: account_metas, data: instruction_data, }; // Invoke instruction with PDA signer invoke_signed(&instruction, &[from_pubkey, to_pubkey, program_id], signer_seeds)?; Ok(()) }}#[derive(Accounts)]pub struct SolTransfer<'info> { #[account( mut, seeds = [b"pda", recipient.key().as_ref()], bump, )] pda_account: SystemAccount<'info>, #[account(mut)] recipient: SystemAccount<'info>, system_program: Program<'info, System>,}
import * as anchor from "@anchor-lang/core";import { BN, Program } from "@anchor-lang/core";import { LAMPORTS_PER_SOL, PublicKey } from "@solana/web3.js";import { Cpi } from "../target/types/cpi";describe("cpi", () => { const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); const program = anchor.workspace.Cpi as Program<Cpi>; const connection = program.provider.connection; const wallet = provider.wallet as anchor.Wallet; const [PDA] = PublicKey.findProgramAddressSync( [Buffer.from("pda"), wallet.publicKey.toBuffer()], program.programId ); const transferAmount = 0.1 * LAMPORTS_PER_SOL; before(async () => { // Request airdrop to fund PDA const signature = await connection.requestAirdrop(PDA, transferAmount); const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash(); await connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight }); }); it("SOL Transfer with PDA signer", async () => { const transactionSignature = await program.methods .solTransfer(new BN(transferAmount)) .accounts({ recipient: wallet.publicKey }) .rpc(); console.log(`\nTransaction Signature: ${transactionSignature}`); });});
The example below makes a CPI with PDA signers from a program written in Native
Rust. It includes a single instruction that transfers SOL from a PDA account to
another. The CPI is signed by the PDA account. (The test file uses
LiteSVM to test the program.)
The test uses litesvm with the Kit API and runs with
Vitest. Install the test dependencies with
npm i -D vitest litesvm @solana/kit @solana-program/system. Build the program
with cargo build-sbf, copy the .so file from target/deploy next to the
test file as program.so, then run the test with npx vitest run. The
program’s Cargo.toml needs these dependencies: