摘要
对于所有所需签名者已在原始交易中签名的 CPI,使用 invoke 即可。无需 PDA
签名。签名者和可写权限会从调用方传递到被调用方。
无需 PDA 签名者的 CPI
当 CPI 不需要 PDA 签名者时,会使用
invoke
函数。invoke 函数会调用 invoke_signed 函数,并传入一个空的
signers_seeds 数组。空的 signers 数组表示不需要任何 PDA 进行签名。
Invoke function
pub fn invoke(instruction: &Instruction, account_infos: &[AccountInfo]) -> ProgramResult {invoke_signed(instruction, account_infos, &[])}
下面的示例展示了如何使用 Anchor 和原生 Rust 进行 CPI。示例包含一个将 SOL 从一个账户转账到另一个账户的指令。
Anchor
以下示例展示了在 Anchor 程序中实现 CPI 的两种方法。这些示例在功能上等价,但展示了不同的抽象层级。
- 示例 1:使用 Anchor 的
CpiContext及辅助函数。 - 示例 2:使用
system_instruction::transfer函数,来自solana_programcrate。 - 示例 3:手动构造 CPI 指令。当没有现成 crate 可用时,这种方式很有用。
use anchor_lang::prelude::*;use anchor_lang::system_program::{transfer, Transfer};declare_id!("9AvUNHjxscdkiKQ8tUn12QCMXtcnbR9BVGq3ULNzFMRi");#[program]pub mod cpi {use super::*;pub fn sol_transfer(ctx: Context<SolTransfer>, amount: u64) -> Result<()> {let from_pubkey = ctx.accounts.sender.to_account_info();let to_pubkey = ctx.accounts.recipient.to_account_info();let program_id = ctx.accounts.system_program.to_account_info();let cpi_context = CpiContext::new(program_id,Transfer {from: from_pubkey,to: to_pubkey,},);transfer(cpi_context, amount)?;Ok(())}}#[derive(Accounts)]pub struct SolTransfer<'info> {#[account(mut)]sender: Signer<'info>,#[account(mut)]recipient: SystemAccount<'info>,system_program: Program<'info, System>,}
Rust
以下示例展示了如何在原生 Rust 编写的程序中进行 CPI。示例包含一个将 SOL 从一个账户转账到另一个账户的指令。(测试文件使用 LiteSVM 对程序进行测试。)
use borsh::BorshDeserialize;use solana_program::{account_info::AccountInfo,entrypoint,entrypoint::ProgramResult,program::invoke,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 [sender_info, recipient_info, system_program_info] = accounts else {return Err(ProgramError::NotEnoughAccountKeys);};// Verify the sender is a signerif !sender_info.is_signer {return Err(ProgramError::MissingRequiredSignature);}// Create and invoke the transfer instructionlet transfer_ix = system_instruction::transfer(sender_info.key,recipient_info.key,amount,);invoke(&transfer_ix,&[sender_info.clone(),recipient_info.clone(),system_program_info.clone(),],)?;Ok(())}}}
Is this page helpful?