> ## 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 프로그램과,
계정으로 전달받은 프로그램 ID를 사용해 callee를 호출하는 caller 프로그램입니다. 두 프로그램을
하나의 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가
테스트 의존성의 feature를 프로그램 빌드에 적용하여, 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**: callee 프로그램 ID를 instruction의 계정으로 전달합니다
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
```

대괄호 안의 숫자는 호출 깊이를 나타냅니다.
