Cross-Program Invocation

Kiểm Thử Hoàn Chỉnh

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);
}
}
}

Các Điểm Chính

  1. Nhiều Chương Trình: Triển khai tất cả các chương trình liên quan trong chuỗi CPI
  2. ID Chương Trình: Truyền ID chương trình được gọi như một tài khoản trong lệnh
  3. System Program: Thường cần thiết cho các hoạt động CPI (chuyển tiền, tạo tài khoản, v.v.)
  4. Xác Minh Nhật Ký: Kiểm tra nhật ký để xác nhận tất cả các chương trình trong chuỗi gọi đã thực thi

Để biết thêm thông tin triển khai chi tiết, hãy đọc phần này.

Hiểu Nhật Ký CPI

Khi một Cross Program Invocation xảy ra, bạn sẽ thấy các nhật ký như:

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

Các số trong ngoặc vuông cho biết độ sâu của lời gọi.

Is this page helpful?

Mục lục

Chỉnh sửa trang