> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Cross-Program Invocation

> 如何测试调用其他程序的程序

## 待测程序

下面的测试会加载两个程序:一个是记录消息的被调用程序(callee),另一个是调用它的
调用程序(caller),被调用程序的程序 ID 会作为账户传入。请将两者放在同一个 Cargo 工作区中,
这样 `cargo build-sbf` 就会把 `caller.so` 和
`callee.so` 写入共享的 `target/deploy/` 文件夹:

```
cpi-example/
├── Cargo.toml
├── callee/
│   ├── Cargo.toml
│   └── src/lib.rs
└── caller/
    ├── Cargo.toml
    ├── src/lib.rs
    └── tests/cpi_test.rs
```

工作区的 `Cargo.toml` 设置了 `resolver = "2"`。如果没有这项设置,Cargo 会把
测试依赖项的 features 应用到程序构建中,一旦 LiteSVM 成为 dev-dependency,
`cargo build-sbf` 就会失败:

```toml Cargo.toml
[workspace]
members = ["callee", "caller"]
resolver = "2"
```

除包名外,两个程序的 `Cargo.toml` 完全相同:

```toml caller/Cargo.toml
[package]
name = "caller"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib", "lib"]

[dependencies]
solana-program = "2.2.0"
```

```rust callee/src/lib.rs
use solana_program::{
    account_info::AccountInfo, entrypoint, entrypoint::ProgramResult, msg, pubkey::Pubkey,
};

entrypoint!(process_instruction);

pub fn process_instruction(
    _program_id: &Pubkey,
    _accounts: &[AccountInfo],
    _instruction_data: &[u8],
) -> ProgramResult {
    msg!("Callee invoked");
    Ok(())
}
```

```rust caller/src/lib.rs
use solana_program::{
    account_info::{next_account_info, AccountInfo},
    entrypoint,
    entrypoint::ProgramResult,
    instruction::Instruction,
    msg,
    program::invoke,
    pubkey::Pubkey,
};

entrypoint!(process_instruction);

pub fn process_instruction(
    _program_id: &Pubkey,
    accounts: &[AccountInfo],
    _instruction_data: &[u8],
) -> ProgramResult {
    let accounts_iter = &mut accounts.iter();
    let _payer = next_account_info(accounts_iter)?;
    let callee_program = next_account_info(accounts_iter)?;

    msg!("Caller invoking callee");
    // Invoke the callee program, whose ID arrives as the second account
    invoke(
        &Instruction::new_with_bytes(*callee_program.key, &[], vec![]),
        &[callee_program.clone()],
    )?;
    Ok(())
}
```

将测试依赖项添加到 caller,然后在工作区根目录构建这两个程序。在首次构建之前添加这些依赖项,
可以让 Cargo 同时解析程序依赖项和测试依赖项:

```bash
cd caller
cargo add --dev litesvm solana-sdk@4
cargo add --dev solana-system-interface --features bincode
cd ..
cargo build-sbf
```

## 完整测试

```rust caller/tests/cpi_test.rs
use litesvm::LiteSVM;
use solana_sdk::{
    instruction::{AccountMeta, Instruction},
    pubkey::Pubkey,
    signature::{Keypair, Signer},
    transaction::Transaction,
};
use solana_system_interface::program as 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![], // The caller ignores instruction data
    };

    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 作为账户传入
3. **System Program**: 在执行 CPI 操作(转账、创建
   账户等)时通常需要用到
4. **日志验证**:检查日志,确认调用链中的所有程序
   均已执行

如需了解更详细的部署信息,请阅读
[本节](/developers/docs/tools/litesvm/testing-your-program/deploy)。

## 理解 CPI 日志

发生 CPI 时,你会看到如下日志:

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

括号中的数字表示调用深度。
