> ## 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-utils crate를 사용하여 Solana 프로그램 테스트를 간소화하는 방법을 알아보세요

[crates.io에서 `litesvm-utils` 보기](https://crates.io/crates/litesvm-utils)

## 설치

필요한 의존성이 모두 설치되어 있는지 확인하세요:

```bash
cargo add --dev litesvm-utils solana-sdk@3 spl-token
cargo add --dev solana-system-interface@2 --features bincode
```

<Warning>
  `litesvm-utils`는 자체 `litesvm` 버전을 고정하여 다시 내보냅니다(re-export). 아래 예제처럼
  `litesvm_utils`에서 `LiteSVM`을 import하고, 별도의 `litesvm` 의존성은 추가하지 마세요.
  그렇지 않으면 호환되지 않는 두 개의 crate 사본이 생기게 됩니다.
</Warning>

## litesvm-utils란?

`litesvm-utils` crate는 Solana 프로그램 테스트를 간소화하는 핵심 헬퍼 trait과 유틸리티를 제공합니다. 사용하기 편한 API를 통해 일반적인 테스트 보일러플레이트를 30줄 이상에서 읽기 쉬운 최소한의 코드로 줄여 줍니다.

<Steps>
<Step title="TestHelpers Trait">
- 메서드 호출 한 번으로 자금이 충전된 계정 생성
- 토큰 민트와 token account를 간편하게 설정
- 보일러플레이트 없이 PDA 파생
- 시간 기반 테스트를 위한 slot 관리
</Step>

<Step title="AssertionHelpers Trait">
- 계정 상태 검증(존재 여부, 폐쇄 여부, 소유자)
- 토큰 잔액 및 민트 공급량 검증
- SOL 잔액 확인
- 계정 데이터 길이 검증
</Step>

<Step title="TransactionHelpers Trait">
- 풍부한 결과 처리와 함께 instruction 실행
- 트랜잭션 성공 또는 실패 검증
- 특정 오류 확인
- 트랜잭션 로그 및 컴퓨트 유닛 확인
</Step>

<Step title="LiteSVMBuilder">
- 테스트 환경 설정을 위한 Fluent 빌더 패턴
- 메서드 체이닝으로 프로그램 배포
- 편리한 정적 팩토리 메서드
</Step>
</Steps>

## 간단한 예제

다음은 litesvm-utils의 강력한 기능을 보여 주는 전체 예제입니다:

```rust
use litesvm_utils::{AssertionHelpers, LiteSVM, Signer, TestHelpers, TransactionHelpers};
use solana_sdk::native_token::LAMPORTS_PER_SOL;
use solana_system_interface::instruction as system_instruction;

#[test]
fn test_with_utils() {
    let mut svm = LiteSVM::new();

    // Create funded accounts in one line
    let alice = svm.create_funded_account(10 * LAMPORTS_PER_SOL).unwrap();
    let bob = svm.create_funded_account(0).unwrap();

    // Create a token mint easily
    let mint = svm.create_token_mint(&alice, 9).unwrap();

    // Create an associated token account (returns Pubkey)
    let alice_ata = svm.create_associated_token_account(&mint.pubkey(), &alice).unwrap();

    // Mint tokens
    svm.mint_to(&mint.pubkey(), &alice_ata, &alice, 1000).unwrap();

    // Assert balances
    svm.assert_token_balance(&alice_ata, 1000);

    // Execute a SOL transfer with rich result handling
    let transfer_ix = system_instruction::transfer(
        &alice.pubkey(),
        &bob.pubkey(),
        LAMPORTS_PER_SOL,
    );

    let result = svm.send_instruction(transfer_ix, &[&alice]).unwrap();
    result.assert_success();

    // Verify the transfer
    svm.assert_sol_balance(&bob.pubkey(), LAMPORTS_PER_SOL);

    // Bob now has SOL, so he can pay for his own associated token account
    let bob_ata = svm.create_associated_token_account(&mint.pubkey(), &bob).unwrap();
    svm.assert_token_balance(&bob_ata, 0);
}
```

## 주요 이점

### litesvm-utils 사용 전

```rust
// Creating a funded account manually
let keypair = Keypair::new();
let airdrop_tx = Transaction::new_signed_with_payer(
    &[system_instruction::transfer(
        &payer.pubkey(),
        &keypair.pubkey(),
        lamports,
    )],
    Some(&payer.pubkey()),
    &[&payer],
    svm.latest_blockhash(),
);
svm.send_transaction(airdrop_tx).unwrap();
```

### litesvm-utils 사용 후

```rust
// One line to create a funded account
let keypair = svm.create_funded_account(lamports).unwrap();
```

## Trait 개요

### TestHelpers

| 메서드                                         | 반환값                | 설명                         |
| ---------------------------------------------- | ---------------------- | ----------------------------------- |
| `create_funded_account(lamports)`              | `Result<Keypair>`      | keypair를 생성하고 자금을 충전합니다      |
| `create_funded_accounts(count, lamports)`      | `Result<Vec<Keypair>>` | 자금이 충전된 keypair를 여러 개 생성합니다    |
| `create_token_mint(authority, decimals)`       | `Result<Keypair>`      | SPL 토큰 민트를 생성합니다           |
| `create_token_account(mint, owner)`            | `Result<Keypair>`      | 일반 token account를 생성합니다     |
| `create_associated_token_account(mint, owner)` | `Result<Pubkey>`       | ATA를 생성하고 해당 주소를 반환합니다 |
| `mint_to(mint, account, authority, amount)`    | `Result<()>`           | 계정에 토큰을 발행합니다          |
| `derive_pda(seeds, program_id)`                | `(Pubkey, u8)`         | bump seed와 함께 PDA를 파생합니다        |
| `get_pda(seeds, program_id)`                   | `Pubkey`               | PDA 주소만 가져옵니다           |
| `get_pda_with_bump(seeds, program_id)`         | `(Pubkey, u8)`         | `derive_pda`의 별칭입니다              |
| `get_current_slot()`                           | `u64`                  | 현재 slot을 반환합니다                |
| `advance_slot(slots)`                          | `()`                   | N개의 slot만큼 시간을 진행시킵니다            |

### AssertionHelpers

| 메서드                                  | 설명                                                            |
| --------------------------------------- | ---------------------------------------------------------------------- |
| `assert_account_exists(pubkey)`         | 계정이 존재하지 않으면 panic이 발생합니다                                       |
| `assert_account_closed(pubkey)`         | 계정이 없거나, lamports가 0이면서 데이터가 없는 경우가 아니면 panic이 발생합니다 |
| `assert_token_balance(account, amount)` | 토큰 잔액을 검증합니다                                                 |
| `assert_sol_balance(pubkey, lamports)`  | SOL 잔액을 검증합니다                                                   |
| `assert_mint_supply(mint, supply)`      | 민트의 총 공급량을 검증합니다                                             |
| `assert_account_owner(pubkey, owner)`   | 계정 소유자를 검증합니다                                                 |
| `assert_account_data_len(pubkey, len)`  | 데이터 길이를 검증합니다                                                   |

### TransactionHelpers

| 메서드                            | 반환값                                       | 설명                           |
| --------------------------------- | --------------------------------------------- | ------------------------------------- |
| `send_instruction(ix, signers)`   | `Result<TransactionResult, TransactionError>` | 단일 instruction을 전송합니다            |
| `send_instructions(ixs, signers)` | `Result<TransactionResult, TransactionError>` | 하나의 트랜잭션으로 여러 instruction을 전송합니다 |
| `send_transaction_result(tx)`     | `Result<TransactionResult, TransactionError>` | 원시 `Transaction`을 전송합니다             |

## 문제 해결

### 일반적인 오류

| 오류               | 원인                                       | 해결 방법                          |
| ------------------- | ------------------------------------------- | --------------------------------- |
| `AccountNotFound`   | 존재하지 않는 계정을 사용하려고 했습니다 | 먼저 `create_funded_account`를 사용하세요 |
| `InsufficientFunds` | 트랜잭션에 필요한 lamports가 부족합니다         | 초기 충전 금액을 늘리세요   |
| `OwnerMismatch`     | 계정이 잘못된 프로그램에 의해 소유되고 있습니다              | 올바른 프로그램 ID인지 확인하세요         |
| `AssertionFailed`   | 잔액 또는 상태가 예상 값과 일치하지 않습니다     | 테스트 로직을 확인하세요             |
