摘要
当调用程序需要代表其拥有的 PDA 进行签名时,请使用
invoke_signed。运行时会根据提供的 signer seeds 派生 PDA
公钥,并在权限检查前将其加入有效签名者集合。
带有 PDA 签名者的 CPI
当 CPI 需要 PDA 签名者时,请使用
invoke_signed
并传入用于派生 PDA 的
signer seeds。关于运行时如何验证 PDA 签名的详细信息,请参见
PDA 签名。
Invoke signed
pub fn invoke_signed(instruction: &Instruction,account_infos: &[AccountInfo],signers_seeds: &[&[&[u8]]],) -> ProgramResult {// --snip--invoke_signed_unchecked(instruction, account_infos, signers_seeds)}
下面的示例展示了如何使用 Anchor 和原生 Rust 进行带有 PDA 签名者的 CPI。每个示例都包含一个将 SOL 从 PDA 转账到收款账户的指令,并由 PDA 进行 CPI 签名。
Anchor
以下示例展示了在 Anchor 程序中实现 CPI 的两种方法。这些示例在功能上等价,但展示了不同的抽象层级。
- 示例 1:使用 Anchor 的
CpiContext及其辅助函数。 - 示例 2:使用
system_instruction::transfer函数,来自solana_programcrate。(示例 1 是该实现的抽象。) - 示例 3:手动构造 CPI 指令。当没有可用 crate 帮助构建你想要调用的指令时,这种方式非常有用。
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.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 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>,}
Rust
下面的示例展示了如何在原生 Rust 编写的程序中,使用 PDA 签名者进行 CPI 操作。该示例包含一个指令,用于将 SOL 从一个 PDA 账户转账到另一个账户。CPI 操作由 PDA 账户签名。(测试文件使用 LiteSVM 对该程序进行测试。)
use borsh::BorshDeserialize;use solana_program::{account_info::AccountInfo,entrypoint,entrypoint::ProgramResult,program::invoke_signed,program_error::ProgramError,pubkey::Pubkey,system_instruction,};// Declare program entrypointentrypoint!(process_instruction);// Define program instructions#[derive(BorshDeserialize)]enum ProgramInstruction {SolTransfer { amount: u64 },}impl ProgramInstruction {fn unpack(input: &[u8]) -> Result<Self, ProgramError> {Self::try_from_slice(input).map_err(|_| ProgramError::InvalidInstructionData)}}pub fn process_instruction(program_id: &Pubkey,accounts: &[AccountInfo],instruction_data: &[u8],) -> ProgramResult {// Deserialize instruction datalet instruction = ProgramInstruction::unpack(instruction_data)?;// Process instructionmatch instruction {ProgramInstruction::SolTransfer { amount } => {// Parse accountslet [pda_account_info, recipient_info, system_program_info] = accounts else {return Err(ProgramError::NotEnoughAccountKeys);};// Derive PDA and verify it matches the account provided by clientlet recipient_pubkey = recipient_info.key;let seeds = &[b"pda", recipient_pubkey.as_ref()];let (expected_pda, bump_seed) = Pubkey::find_program_address(seeds, program_id);if expected_pda != *pda_account_info.key {return Err(ProgramError::InvalidArgument);}// Create the transfer instructionlet transfer_ix = system_instruction::transfer(pda_account_info.key,recipient_info.key,amount,);// Create signer seeds for PDAlet signer_seeds: &[&[&[u8]]] = &[&[b"pda", recipient_pubkey.as_ref(), &[bump_seed]]];// Invoke the transfer instruction with PDA as signerinvoke_signed(&transfer_ix,&[pda_account_info.clone(),recipient_info.clone(),system_program_info.clone(),],signer_seeds,)?;Ok(())}}}
Is this page helpful?