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

# 执行指令

> 了解如何在测试中调用 Solana 程序的指令

## 概述

将程序部署到 LiteSVM 后,您需要执行指令来
与已部署的程序进行交互。

<Note>
  本页的代码片段使用了以下 crate。请固定所示的版本,以便
  与 LiteSVM 使用的类型保持一致:

  ```bash
  cargo add --dev litesvm solana-keypair@3 solana-signer@3 solana-transaction@4 solana-message@4 solana-instruction@3 solana-pubkey@3 solana-transaction-error@3 solana-compute-budget@4 solana-compute-budget-interface@3
  cargo add --dev solana-system-interface --features bincode
  ```
</Note>

LiteSVM 提供了简单的 API 用于创建、发送和模拟交易,
并与 Solana 的交易模型完全兼容。

## 基本交易流程

执行指令的典型流程如下:

1. **创建指令** - 定义要调用的程序以及传入的数据
2. **构建消息** - 组合一个或多个指令
3. **创建交易** - 使用所需的签名者对消息进行签名
4. **发送或模拟** - 执行交易并处理结果

## 创建指令

### 基本指令结构

```rust
use solana_instruction::{Instruction, AccountMeta};
use solana_pubkey::Pubkey;

let instruction = Instruction {
    program_id: Pubkey::new_unique(),  // The program to call
    accounts: vec![                     // Accounts the program needs
        AccountMeta::new(account_pubkey, false),        // Writable, not signer
        AccountMeta::new_readonly(readonly_pubkey, false), // Read-only, not signer
        AccountMeta::new(signer_pubkey, true),          // Writable, signer
    ],
    data: vec![0, 1, 2, 3],             // Instruction data (program-specific)
};
```

## 构建并发送交易

### 方法 1:基本交易

```rust
use litesvm::LiteSVM;
use solana_keypair::Keypair;
use solana_transaction::Transaction;
use solana_signer::Signer;

let mut svm = LiteSVM::new();
let payer = Keypair::new();

// Airdrop SOL for fees
svm.airdrop(&payer.pubkey(), 1_000_000_000).unwrap();

// Create instruction
let instruction = /* your instruction */;

// Create and sign transaction
let tx = Transaction::new_signed_with_payer(
    &[instruction],                 // Your instructions
    Some(&payer.pubkey()),          // Who pays transaction fees
    &[&payer],                      // All required signers
    svm.latest_blockhash(),         // Recent blockhash
);


// Send transaction
let result = svm.send_transaction(tx);
```

**`new_signed_with_payer` 的作用:**

- 根据您的指令自动构建 Message
- 使用所有提供的 keypair 自动对交易签名
- 返回已完全签名、可直接发送的交易

### 方法 2:自定义消息交易

```rust
let payer = Keypair::new();

// Manually construct message
let message = Message::new(&[instruction], Some(&payer.pubkey()));

// Create transaction with signers, message, and blockhash
let tx = Transaction::new(
    &[&payer],
    message,
    svm.latest_blockhash(),
);

let result = svm.send_transaction(tx);
```

**当您需要控制 `Message` 时,请使用此方法,例如:**

- 版本化交易(使用查找表的 v0)
- 部分签名/多签工作流
- 持久 nonce
- 签名前的模拟或检查
- 自定义手续费支付者逻辑
- 交易大小优化

## 版本化交易

LiteSVM 同时支持传统交易和版本化交易:

```rust
use solana_transaction::versioned::VersionedTransaction;
use solana_message::{Message, VersionedMessage};

// Legacy transaction (most common).
// `Message::new` leaves the blockhash zeroed, so use `new_with_blockhash`.
let legacy_msg = Message::new_with_blockhash(
    &[instruction],
    Some(&payer.pubkey()),
    &svm.latest_blockhash(),
);
let versioned_tx = VersionedTransaction::try_new(
    VersionedMessage::Legacy(legacy_msg),
    &[&payer]
).unwrap();

// Send versioned transaction
let result = svm.send_transaction(versioned_tx);
```

## 交易结果

### 交易成功

```rust
match svm.send_transaction(tx) {
    Ok(meta) => {
        println!("Signature: {}", meta.signature);
        println!("Compute units: {}", meta.compute_units_consumed);
        println!("Logs:");
        for log in &meta.logs {
            println!("  {}", log);
        }
    }
    Err(err) => {
        println!("Transaction failed: {:?}", err.err);
        // Logs are still available on failure
        println!("Failure logs: {:?}", err.meta.logs);
    }
}
```

### 交易元数据字段

```rust
pub struct TransactionMetadata {
    pub signature: Signature,
    pub logs: Vec<String>,
    pub inner_instructions: InnerInstructionsList,
    pub compute_units_consumed: u64,
    pub return_data: TransactionReturnData,
    pub fee: u64,
    pub loaded_accounts_data_size: u32,
}
```

## 模拟交易

模拟交易可让您在不改变状态的情况下测试交易:

```rust
// Simulate instead of sending
match svm.simulate_transaction(tx) {
    Ok(sim_result) => {
        println!("Simulation successful!");
        println!("Logs: {:?}", sim_result.meta.logs);
        println!("Compute units: {}", sim_result.meta.compute_units_consumed);
    }
    Err(err) => {
        println!("Simulation failed: {:?}", err.err);
    }
}
```

## 错误处理

### 常见交易错误

```rust
use solana_transaction_error::TransactionError;
use solana_instruction::error::InstructionError;

match svm.send_transaction(tx) {
    Err(failed_tx) => {
        match failed_tx.err {
            TransactionError::InsufficientFundsForFee => {
                println!("Not enough SOL for fees");
            }
            TransactionError::AccountNotFound => {
                println!("Fee payer doesn't exist");
            }
            TransactionError::InvalidProgramForExecution => {
                println!("Program doesn't exist or isn't executable");
            }
            TransactionError::InstructionError(index, err) => {
                println!("Instruction {} failed: {:?}", index, err);
                match err {
                    InstructionError::Custom(code) => {
                        println!("Custom error code: {}", code);
                    }
                    InstructionError::MissingAccount => {
                        println!("An account required by the instruction is missing");
                    }
                    _ => {}
                }
            }
            TransactionError::BlockhashNotFound => {
                println!("Blockhash expired or invalid");
            }
            _ => println!("Other error: {:?}", failed_tx.err),
        }
    }
    Ok(_) => {}
}
```

## 使用程序日志

### 访问日志

```rust
let result = svm.send_transaction(tx).unwrap();

// All logs (including system logs)
for log in &result.logs {
    println!("{}", log);
}

// Pretty-printed logs (formatted)
println!("{}", result.pretty_logs());
```

### 日志输出示例

```
Program <PROGRAM_ID> invoke [1]
Program log: Processing instruction
Program <PROGRAM_ID> consumed 2000 of 200000 compute units
Program <PROGRAM_ID> success
```

## 计算预算配置

### 设置全局计算预算

```rust
use solana_compute_budget::compute_budget::ComputeBudget;

let mut svm = LiteSVM::new()
    .with_compute_budget(ComputeBudget {
        compute_unit_limit: 200_000,
        ..ComputeBudget::new_with_defaults(true)
    });
```

### 单笔交易的计算预算

```rust
use solana_compute_budget_interface::ComputeBudgetInstruction;

let instructions = vec![
    // Set compute budget for this transaction
    ComputeBudgetInstruction::set_compute_unit_limit(400_000),
    ComputeBudgetInstruction::set_compute_unit_price(1),

    // Your actual instruction
    your_instruction,
];
```

## System Program 指令

LiteSVM 内置了对 System Program 的支持:

```rust
use solana_keypair::Keypair;
use solana_signer::Signer;
use solana_system_interface::instruction as system_instruction;
use solana_transaction::Transaction;


// Transfer SOL
let transfer_ix = system_instruction::transfer(
    &alice.pubkey(),
    &bob.pubkey(),
    1_000_000_000, // 1 SOL
);

// Create new account
let create_ix = system_instruction::create_account(
    &payer_pubkey,
    &new_account_pubkey,
    lamports,
    space as u64,
    &owner_program_id,
);
```

## 总结

在 LiteSVM 中执行指令遵循标准的 Solana 交易模型:

1. 使用程序 ID、账户和数据创建 `Instruction` 对象
2. 使用该指令和所需的签名者构建 `Transaction`
3. 使用 `send_transaction()` 执行交易,或使用 `simulate_transaction()` 进行测试
4. 通过检查 `TransactionMetadata` 或错误详情来处理结果

LiteSVM 可即时执行并提供详细的日志和调试信息,
是高效测试 Solana 程序的理想选择。
