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

## 基础程序部署

### 方法一：从字节数据部署

直接从字节数组部署程序，可获得最快的测试执行速度：

```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>

### 方法二：从文件 (.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 拉取）
  - 程序在开发期间频繁变更（无需重新编译即可重新运行测试）
  - 你的 CI/CD 环境中 .so 文件属于构建产物

### 理解程序 keypair

构建 Solana 程序时：

1. **Anchor** 会创建 `target/deploy/program-keypair.json`
2. **原生**构建会在 `.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. 指令中使用了错误的程序 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)。

### 部署所需的 Lamports 不足

**注意**：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>

## 后续步骤

在下一节中，我们将学习如何执行程序指令并处理复杂的交易模式。
