Cross Program Invocation

完全なテスト

tests/cpi_test.rs
use litesvm::LiteSVM;
use solana_sdk::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
signature::{Keypair, Signer},
transaction::Transaction,
system_program,
};
#[test]
fn test_cross_program_invocation() {
let mut svm = LiteSVM::new();
// Deploy both programs
let caller_program = Pubkey::new_unique();
let callee_program = Pubkey::new_unique();
svm.add_program(
caller_program,
include_bytes!("../target/deploy/caller.so")
).unwrap();
svm.add_program(
callee_program,
include_bytes!("../target/deploy/callee.so")
).unwrap();
// Setup accounts
let payer = Keypair::new();
svm.airdrop(&payer.pubkey(), 10_000_000_000).unwrap();
// Create instruction that will trigger CPI
let instruction = Instruction {
program_id: caller_program,
accounts: vec![
AccountMeta::new(payer.pubkey(), true),
AccountMeta::new_readonly(callee_program, false),
AccountMeta::new_readonly(system_program::id(), false),
],
data: vec![1], // Instruction to trigger CPI
};
let tx = Transaction::new_signed_with_payer(
&[instruction],
Some(&payer.pubkey()),
&[&payer],
svm.latest_blockhash(),
);
let result = svm.send_transaction(tx).unwrap();
// Verify both programs were invoked
assert!(result.logs.iter().any(|log|
log.contains(&format!("Program {} invoke", caller_program))
));
assert!(result.logs.iter().any(|log|
log.contains(&format!("Program {} invoke", callee_program))
));
println!("CPI successful!");
println!("Logs showing both programs:");
for log in &result.logs {
if log.contains("invoke") {
println!(" {}", log);
}
}
}

重要なポイント

  1. 複数のプログラム: CPIチェーンに関わるすべてのプログラムをデプロイする
  2. プログラムID: 呼び出し先のプログラムIDをinstructionsのアカウントとして渡す
  3. System Program: CPI操作(転送、アカウント作成など)に頻繁に必要となる
  4. ログの検証: 呼び出しチェーン内のすべてのプログラムが実行されたことをログで確認する

デプロイに関する詳細情報は、 このセクションをご参照ください。

CPIログの理解

CPIが発生すると、次のようなログが表示されます:

Program A invoke [1]
Program B invoke [2]
Program B success
Program A success

括弧内の数字は呼び出しの深さを示しています。

Is this page helpful?

目次

ページを編集
© 2026 Solana Foundation. 無断転載を禁じます。