> ## 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.

# 프로그램 배포하기

> LiteSVM 테스트 인스턴스에 프로그램을 배포하는 방법을 알아봅니다

## 시작하기

```rust
let mut svm = LiteSVM::new();
```

이 코드는 기본 litesvm 테스트 인스턴스를 생성하며, 현재 mainnet-beta에서 활성화된 런타임
기능, 기본 sysvar, spl 프로그램, sigverify, 그리고 system program과 같은 모든 내장 프로그램을
활성화합니다. `litesvm`의 `precompiles` 기능이 활성화되어 있으면 프리컴파일
(ed25519, secp256k1, secp256r1)도 포함됩니다. `FeatureSet::all_enabled()`와 같은 다른 기능 세트로
테스트하려면 [빠른 시작](/developers/docs/tools/litesvm/testing-your-program)에서 보여 드린 것처럼 `LiteSVM::default()`로 환경을 구성하세요.

테스트에서 다른 프로그램과 상호작용하려면 해당 프로그램을 테스트 환경에 배포해야 합니다.

1. 테스트할 프로그램을 빌드하고 배포합니다

2. 위 프로그램이 CPI 호출을 하는 모든 프로그램을 찾아 함께 배포합니다

<Info>
  **예시:** 프로그램에서 Pyth의 데이터 피드를 사용한다면, Pyth 프로그램을 테스트 인스턴스에
  배포해야 합니다.
</Info>

## 기본 프로그램 배포

### 방법 1: 바이트에서 배포

바이트 배열에서 직접 프로그램을 배포하면 테스트를 가장 빠르게 실행할 수 있습니다:

```rust
use litesvm::LiteSVM;
use solana_sdk::signature::{read_keypair_file, Signer};

let mut svm = LiteSVM::new();

// Read the program's keypair to get correct ID
let program_keypair = read_keypair_file("target/deploy/my_program-keypair.json")
    .expect("Program keypair file not found");
let program_id = program_keypair.pubkey();

// Include bytes at compile time
let program_bytes = include_bytes!("../target/deploy/my_program.so");

// Deploy from bytes
svm.add_program(program_id, program_bytes)
    .expect("Failed to deploy program");

// Verify deployment
assert!(svm.get_account(&program_id).is_some(), "Program account not created");
assert!(svm.get_account(&program_id).unwrap().executable, "Program not executable");
```

`include_bytes!`는 컴파일 시점에 바이너리를 테스트 실행 파일에 직접 포함하므로, 테스트 실행 중
I/O가 발생하지 않습니다.

<Columns cols={2}>
  <Card title="장점" icon="check">
    - 런타임에 더 빠름(디스크 읽기 없음)
    - 독립적으로 실행 가능한 테스트 바이너리
    - 컴파일 후 .so 파일을 삭제해도 동작
  </Card>

  <Card title="단점" icon="x">
    - 테스트 바이너리 크기가 커짐
    - .so가 변경되면 테스트를 다시 컴파일해야 함
  </Card>
</Columns>

### 방법 2: 파일(.so)에서 배포

프로그램이 자주 변경되는 경우 파일 시스템에서 프로그램을 불러옵니다:

```rust
use litesvm::LiteSVM;
use solana_sdk::signature::{read_keypair_file, Signer};

let mut svm = LiteSVM::new();

// Read keypair for correct program ID
let program_keypair = read_keypair_file("target/deploy/program-keypair.json").unwrap();
let program_id = program_keypair.pubkey();

// Deploy from file
svm.add_program_from_file(program_id, "target/deploy/program.so")
    .expect("Failed to deploy program from file");

// Always verify
assert!(svm.get_account(&program_id).unwrap().executable);
```

<Columns cols={2}>
  <Card title="장점" icon="check">
    - 테스트 바이너리가 더 작음
    - 테스트를 다시 컴파일하지 않고도 .so 변경 사항을 반영할 수 있음
    - CI/CD 파이프라인에서 더 유연함
  </Card>

  <Card title="단점" icon="x">
    - 더 느림(런타임에 디스크 I/O 발생)
    - 테스트 실행 시점에 .so 파일이 존재해야 함
    - 파일 경로가 테스트 실행 디렉터리 기준으로 올바라야 함
  </Card>
</Columns>

## Mainnet/Devnet에서 프로그램 가져오기

코드를 가지고 있지 않은 프로그램이 필요한 경우, Solana CLI를 사용해 라이브 클러스터에서
프로그램을 덤프한 뒤 테스트에서 사용하세요:

```bash
# Dump a program from mainnet
solana program dump gSbePebfvPy7tRqimPoVecS2UsBvYv46ynrzWocc92s pyth.so --url mainnet-beta

# Dump from devnet
solana program dump YourProgramID program.so --url devnet
```

그런 다음 테스트에서 불러옵니다:

```rust
use solana_sdk::pubkey;

svm.add_program_from_file(
    pubkey!("gSbePebfvPy7tRqimPoVecS2UsBvYv46ynrzWocc92s"),
    "pyth.so"
).unwrap();
```

## 모범 사례

### 1. 올바른 배포 방법 선택하기

- 다음과 같은 경우 **`add_program()`을 사용하세요**:
  - 프로그램이 컴파일 시점에 테스트 바이너리에 포함되는 경우
  - 테스트를 더 빠르게 실행하고 싶은 경우(런타임 I/O 없음)
  - 독립적으로 실행 가능한 테스트

- 다음과 같은 경우 **`add_program_from_file()`을 사용하세요**:
  - 프로그램이 별도로 빌드되는 경우(예: devnet에서 가져오는 경우)
  - 개발 중 프로그램이 자주 변경되는 경우(다시 컴파일하지 않고 테스트를
    재실행할 수 있음)
  - .so 파일이 아티팩트로 관리되는 CI/CD 환경을 사용하는 경우

### 프로그램 keypair 이해하기

Solana 프로그램을 빌드하면 다음과 같이 됩니다:

1. **Anchor**는 `target/deploy/program-keypair.json`을 생성합니다
2. **Native** 빌드는 `.so` 파일과 같은 위치에 keypair 파일을 생성합니다
3. 프로그램의 **온체인 주소**는 이 keypair의 공개 키이며, 프로그램 ID라고도 합니다.
4. **PDA**의 경우, `find_program_address()`는 프로그램 ID를 seed로 요구합니다
5. **CPI**의 경우, 프로그램 ID는 다른 프로그램을 호출하는 데 사용됩니다

## 자주 발생하는 문제와 해결 방법

### 조용히 발생하는 배포 실패

**문제**: 프로그램이 배포된 것처럼 보이지만 트랜잭션이
"InvalidProgramForExecution" 오류로 실패합니다.

**원인**: 프로그램 ID가 keypair와 일치하지 않습니다.

**해결 방법**:

```rust
// Always use the keypair-derived ID
let keypair = read_keypair_file("target/deploy/program-keypair.json").unwrap();
let program_id = keypair.pubkey();

svm.add_program(program_id, &program_bytes).unwrap();

// Verify with detailed checks
let account = svm.get_account(&program_id)
    .expect("Program account doesn't exist");

assert!(account.executable, "Program not executable");
// LiteSVM deploys programs through the upgradeable loader
// (add it with `cargo add --dev solana-sdk-ids`)
assert_eq!(
    account.owner,
    solana_sdk_ids::bpf_loader_upgradeable::id(),
    "Wrong owner"
);
assert!(!account.data.is_empty(), "Program data is empty");

println!("✅ Program verified at {}", program_id);
```

### 프로그램을 찾을 수 없음 오류

**오류**: `TransactionError::InvalidProgramForExecution`

**일반적인 원인**:

1. 프로그램이 배포되지 않음
2. instruction에 잘못된 프로그램 ID를 사용함
3. 프로그램 ID가 keypair와 일치하지 않음

**디버깅 단계**:

```rust
// Step 1: Check if program exists
if let Some(account) = svm.get_account(&program_id) {
    println!("Program exists");
    println!("  Executable: {}", account.executable);
    println!("  Owner: {}", account.owner);
    println!("  Data length: {}", account.data.len());
} else {
    println!("Program does not exist at {}", program_id);
}

// Step 2: Verify the ID matches keypair
let expected_keypair = read_keypair_file("target/deploy/program-keypair.json").unwrap();
let expected_id = expected_keypair.pubkey();

if program_id != expected_id {
    println!("  ID mismatch!");
    println!("  Used: {}", program_id);
    println!("  Expected: {}", expected_id);
}

// Step 3: Check instruction program ID
println!("Instruction program_id: {}", instruction.program_id);
assert_eq!(instruction.program_id, program_id, "Instruction uses wrong program ID");
```

### 배포되지 않은 프로그램에 대한 CPI

**문제**: 프로그램이 배포되지 않은 프로그램에 CPI 호출을 합니다.

**해결 방법**: 의존하는 모든 프로그램을 배포하세요:

```rust
use solana_sdk::pubkey;

// Find all dependency programs and make sure they are deployed
svm.add_program_from_file(
    pubkey!("gSbePebfvPy7tRqimPoVecS2UsBvYv46ynrzWocc92s"),
    "pyth.so"
).unwrap();

```

클러스터에서 프로그램을 가져와야 한다면
[이 섹션](#pulling-programs-from-mainnet/devnet)을 참고하세요.

### 배포를 위한 Lamport 부족

**참고**: LiteSVM은 프로그램의 렌트 면제 잔액을 자동으로 처리합니다.

```rust
// No need to manually fund - LiteSVM handles this
svm.add_program(program_id, &program_bytes).unwrap();

// But you can check the rent if needed
let program_len = program_bytes.len();
let required_lamports = svm.minimum_balance_for_rent_exemption(program_len);
println!("Program requires {} lamports for rent exemption", required_lamports);
```

## 배포 확인 체크리스트

<Steps>
<Step title="프로그램 keypair 읽기">
```rust
let keypair = read_keypair_file("target/deploy/program-keypair.json").unwrap();
let program_id = keypair.pubkey();
```

</Step>

<Step title="일치하는 ID로 배포">
```rust
svm.add_program(program_id, &program_bytes).unwrap();
```

</Step>

<Step title="배포 확인">
```rust
assert!(svm.get_account(&program_id).unwrap().executable);
```

</Step>

<Step>
프로그램이 CPI로 호출하는 모든 프로그램을 litesvm 테스트 인스턴스에 배포하세요

</Step>
</Steps>

## 다음 단계

다음 섹션에서는 프로그램 instruction을 실행하는 방법과 복잡한 트랜잭션 패턴을 처리하는 방법을 알아봅니다.
