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

# Triển khai chương trình

> Tìm hiểu cách triển khai chương trình lên một instance kiểm thử LiteSVM

## Bắt đầu

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

Lệnh này tạo instance kiểm thử litesvm cơ bản, với các tính năng runtime
hiện đang hoạt động trên mainnet-beta, sysvar mặc định, các chương trình spl,
sigverify và tất cả chương trình tích hợp sẵn như system program. Các
precompile (ed25519, secp256k1, secp256r1) được đưa vào khi bật tính năng
`precompiles` của `litesvm`. Để kiểm thử với một bộ tính năng khác, chẳng hạn
`FeatureSet::all_enabled()`, hãy xây dựng môi trường từ `LiteSVM::default()`
như trình bày trong phần [Bắt đầu nhanh](/developers/docs/tools/litesvm/testing-your-program).

Để tương tác với bất kỳ chương trình nào khác trong các bài kiểm thử, bạn phải
triển khai chương trình đó lên môi trường kiểm thử của mình.

1. Xây dựng và triển khai chương trình bạn muốn kiểm thử

2. Tìm tất cả các chương trình mà chương trình trên thực hiện lệnh gọi CPI tới và
   triển khai các chương trình đó

<Info>
  **Ví dụ:** Nếu chương trình của bạn sử dụng nguồn dữ liệu từ Pyth, bạn sẽ cần
  triển khai chương trình Pyth lên instance kiểm thử của mình.
</Info>

## Triển khai chương trình cơ bản

### Cách 1: Triển khai từ byte

Triển khai chương trình trực tiếp từ mảng byte để chạy kiểm thử nhanh nhất:

```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!` nhúng trực tiếp tệp nhị phân vào tệp thực thi kiểm thử tại thời
điểm biên dịch, loại bỏ I/O trong quá trình chạy kiểm thử.

<Columns cols={2}>
  <Card title="Ưu điểm" icon="check">
    - Nhanh hơn khi chạy (không đọc đĩa)
    - Tệp nhị phân kiểm thử độc lập
    - Vẫn hoạt động ngay cả khi tệp .so bị xóa sau khi biên dịch
  </Card>

  <Card title="Nhược điểm" icon="x">
    - Kích thước tệp nhị phân kiểm thử lớn hơn
    - Phải biên dịch lại các bài kiểm thử khi .so thay đổi
  </Card>
</Columns>

### Cách 2: Triển khai từ tệp (.so)

Tải chương trình từ hệ thống tệp khi chúng thay đổi thường xuyên:

```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="Ưu điểm" icon="check">
    - Tệp nhị phân kiểm thử nhỏ hơn
    - Có thể nhận các thay đổi của .so mà không cần biên dịch lại bài kiểm thử
    - Linh hoạt hơn cho các pipeline CI/CD
  </Card>

  <Card title="Nhược điểm" icon="x">
    - Chậm hơn (I/O đĩa khi chạy)
    - Yêu cầu tệp .so phải tồn tại tại thời điểm chạy kiểm thử
    - Đường dẫn tệp phải chính xác so với thư mục chạy kiểm thử
  </Card>
</Columns>

## Lấy chương trình từ Mainnet/Devnet

Khi bạn cần một chương trình mà bạn không có mã nguồn, hãy dùng Solana CLI để
trích xuất chương trình từ các cluster đang hoạt động và sử dụng chúng trong
các bài kiểm thử:

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

Sau đó tải nó trong các bài kiểm thử của bạn:

```rust
use solana_sdk::pubkey;

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

## Thực hành tốt nhất

### 1. Chọn đúng phương thức triển khai

- **Dùng `add_program()`** khi:
  - Chương trình được nhúng vào tệp nhị phân kiểm thử tại thời điểm biên dịch
  - Bạn muốn chạy kiểm thử nhanh hơn (không có I/O khi chạy)
  - Các bài kiểm thử độc lập

- **Dùng `add_program_from_file()`** khi:
  - Chương trình được xây dựng riêng (ví dụ: lấy từ devnet)
  - Chương trình thay đổi thường xuyên trong quá trình phát triển (có thể chạy lại
    kiểm thử mà không cần biên dịch lại)
  - Bạn có các môi trường CI/CD nơi các tệp .so là artifact

### Tìm hiểu về keypair của chương trình

Khi bạn xây dựng một chương trình Solana:

1. **Anchor** tạo `target/deploy/program-keypair.json`
2. Các bản build **Native** tạo một tệp keypair cùng với tệp `.so`
3. **Địa chỉ onchain** của chương trình chính là khóa công khai của keypair này,
   còn được gọi là program ID.
4. Với **PDA**, `find_program_address()` yêu cầu program ID làm seed
5. Với **CPI**, program ID được dùng để gọi các chương trình khác

## Các vấn đề thường gặp và giải pháp

### Lỗi triển khai âm thầm

**Vấn đề**: Chương trình có vẻ đã được triển khai nhưng các giao dịch thất bại
với lỗi "InvalidProgramForExecution".

**Nguyên nhân**: Program ID không khớp với keypair.

**Giải pháp**:

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

### Lỗi không tìm thấy chương trình

**Lỗi**: `TransactionError::InvalidProgramForExecution`

**Nguyên nhân thường gặp**:

1. Chương trình chưa được triển khai
2. Sử dụng sai program ID trong instruction
3. Program ID không khớp với keypair

**Các bước gỡ lỗi**:

```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 tới các chương trình chưa được triển khai

**Vấn đề**: Chương trình của bạn thực hiện lệnh gọi CPI tới một chương trình
chưa được triển khai.

**Giải pháp**: Triển khai tất cả các chương trình phụ thuộc:

```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();

```

Nếu bạn cần lấy chương trình từ một cluster, hãy xem lại
[phần này](#pulling-programs-from-mainnet/devnet).

### Không đủ Lamports để triển khai

**Lưu ý**: LiteSVM tự động xử lý số dư miễn phí thuê (rent-exempt) cho các chương trình.

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

## Danh sách kiểm tra xác minh triển khai

<Steps>
<Step title="Đọc keypair của chương trình">
```rust
let keypair = read_keypair_file("target/deploy/program-keypair.json").unwrap();
let program_id = keypair.pubkey();
```

</Step>

<Step title="Triển khai với ID khớp">
```rust
svm.add_program(program_id, &program_bytes).unwrap();
```

</Step>

<Step title="Xác minh việc triển khai">
```rust
assert!(svm.get_account(&program_id).unwrap().executable);
```

</Step>

<Step>
Triển khai mọi chương trình mà chương trình của bạn gọi qua CPI lên instance kiểm thử litesvm

</Step>
</Steps>

## Bước tiếp theo

Trong phần tiếp theo, chúng ta sẽ tìm hiểu cách thực thi các instruction của
chương trình và xử lý các mẫu giao dịch phức tạp.
