> ## 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>
  이 페이지의 스니펫은 다음 크레이트를 사용합니다. 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를 제공합니다.

## 기본 트랜잭션 흐름

명령어를 실행하는 일반적인 흐름은 다음과 같습니다:

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)
- 부분 서명/멀티시그 워크플로
- 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 명령어

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 프로그램을 효율적으로 테스트하기에 이상적입니다.
