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

# instructions の実行

> テストで Solana プログラムの instruction を呼び出す方法を学びます

## 概要

LiteSVM にプログラムをデプロイした後は、デプロイしたプログラムとやり取りするために
instructions を実行する必要があります。

<Note>
  このページのスニペットでは、以下のクレートを使用します。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 は、Solana のトランザクションモデルと完全な互換性を持つ、トランザクションの作成・送信・シミュレーション用のシンプルな API を提供します。

## 基本的なトランザクションフロー

instruction を実行する一般的な流れは次のとおりです:

1. **instruction を作成** - 呼び出すプログラムと渡すデータを定義します
2. **Message を構築** - 1 つ以上の instructions を組み合わせます
3. **トランザクションを作成** - 必要な署名者でメッセージに署名します
4. **送信またはシミュレーション** - トランザクションを実行し、結果を処理します

## instructions の作成

### instruction の基本構造

```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` の動作:**

- instructions から Message を自動的に構築します
- 指定されたすべての keypair でトランザクションに自動的に署名します
- 完全に署名済みで、すぐに送信できるトランザクションを返します

### 方法 2: カスタム Message トランザクション

```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)
- 部分署名/マルチシグのワークフロー
- Durable 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 の instructions

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 での instructions の実行は、Solana 標準のトランザクションモデルに従います:

1. プログラム ID、アカウント、データを指定して `Instruction` オブジェクトを作成します
2. instruction と必要な署名者を指定して `Transaction` を構築します
3. 実行には `send_transaction()`、テストには `simulate_transaction()` を使用します
4. `TransactionMetadata` またはエラーの詳細を確認して、結果を処理します

LiteSVM は、詳細なログとデバッグ情報とともに即時実行を提供するため、
Solana プログラムを効率的にテストするのに最適です。
