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

# 빠른 시작

> 간소화된 문법으로 Anchor 프로그램을 테스트하기 위해 anchor-litesvm을 사용하는 방법을 알아보세요

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

## 설치

`anchor init`은 LiteSVM 테스트인 `programs/<program-name>/tests/test_initialize.rs`를
생성하며, 이 테스트에는 자체 `litesvm` dev-dependency가 포함되어 있습니다. `anchor-litesvm`은
자체 버전의 `litesvm`을 함께 제공하는데, 두 개의 크레이트 사본에서 가져온 타입은 서로 호환되지 않습니다
(Anchor 1.2.2에서는 두 의존성 집합이 함께 컴파일조차 되지 않습니다).
프로그램 폴더인 `programs/<program-name>`에서 생성된 테스트와 해당 의존성을 제거한 다음,
`anchor-litesvm`을 추가하세요:

```bash
rm tests/test_initialize.rs
cargo remove --dev litesvm solana-message solana-transaction solana-signer solana-keypair
cargo add --dev anchor-litesvm litesvm-utils anchor-lang@1 solana-sdk@3
```

별도의 `litesvm` 의존성을 추가하지 말고
`anchor_litesvm`에서 `LiteSVM`, `Keypair`, `Pubkey`, `Signer`를 가져오세요.

<Warning>
**`build_with_program`이 `Failed to add program: Instruction(InvalidAccountData)` 오류와 함께 패닉이 발생하나요?**
`anchor-litesvm` 0.4와 `litesvm-utils` 0.4는 LiteSVM 0.11을 사용하며, 이 버전은
SBPF v3 프로그램을 로드할 수 없습니다. Anchor 1.2 이상과 Solana CLI 4.3 이상은 기본적으로 SBPF
v3로 빌드합니다. 이러한 크레이트가 더 새로운 LiteSVM으로 이동하기 전까지는, 프로그램을
SBPF v0용으로 빌드하고 다시 빌드하지 않은 채 테스트를 실행하세요:

- **Anchor 1.2 이상:**

  ```bash
  anchor build --arch v0
  anchor test --skip-build
  ```

- **Solana CLI 4.3 이상 환경의 Anchor 1.1.x**: 일반 `anchor build`가
  `Platform tools v1.52 is incompatible with SBPFv3` 오류로 실패하는 경우, IDL 없이 프로그램을
  빌드한 다음 IDL을 별도로 빌드하세요.

  ```bash
  anchor build --no-idl -- --arch v0
  anchor idl build -p my_program -o target/idl/my_program.json
  anchor test --skip-build
  ```

Solana 설치 프로그램이 설정하는 방식대로 AVM으로 설치한 Anchor 1.1.2는 SBPF v0를 빌드하는 Solana
CLI 3.1.10을 사용하므로 별도의 해결 방법이 필요하지 않습니다.
</Warning>

## 프로젝트 설정

1. 프로그램을 빌드(위에서 설명한 대로 SBPF v0용)한 다음, `target/idl/`에 있는 IDL을 워크스페이스 루트의
   `idls/` 폴더로 복사하세요.
   `declare_program!(my_program)`은 컴파일 시점에 `idls/my_program.json`을 읽어
   클라이언트 타입과 프로그램 ID인 `my_program::ID`를 생성합니다.

   ```bash
   mkdir -p idls && cp target/idl/my_program.json idls/
   ```

   `declare_program!`을 호출하는 테스트를 작성하기 전에 이 작업을 먼저 수행하세요. `anchor build`는
   IDL을 빌드하는 동안 테스트도 컴파일하므로, IDL을 찾지 못하는 테스트가 있으면 빌드가 실패합니다.
   프로그램의 instruction, 계정 또는 이벤트를 변경한 후에는 IDL을 다시 복사하세요.

2. 테스트는 `programs/my_program/tests/`에 두세요. 이 페이지들의 예제는 그곳에서 세 단계 위 폴더에 있는
   프로그램을 로드합니다:
   `include_bytes!("../../../target/deploy/my_program.so")`. 테스트가
   다른 크레이트에 있다면 워크스페이스의 어느 크레이트에서든 동작하는 경로를 사용하세요:
   `include_bytes!(concat!(env!("CARGO_TARGET_TMPDIR"), "/../deploy/my_program.so"))`.

## anchor-litesvm이란?

`anchor-litesvm` 크레이트는 **anchor-client와 유사한 간소화된 문법**을 제공하면서도
RPC 오버헤드가 없습니다. Anchor 타입의 타입 안전성을 유지하면서 순수 LiteSVM 대비
**코드량을 78% 줄일 수 있습니다**.

<Steps>
<Step title="AnchorContext">
- 프로덕션과 호환되는 테스트 컨텍스트
- anchor-client와 동일한 API 패턴
- LiteSVM 인스턴스, payer, 프로그램 관리
- RPC 오버헤드 없이 instruction 실행
</Step>

<Step title="Program API">
- Fluent 방식의 instruction 빌드
- 타입 안전한 계정 및 인자 처리
- 익숙한 anchor-client 문법
</Step>

<Step title="계정 역직렬화">
- Anchor 계정 조회 및 역직렬화
- 자동 discriminator 처리
- PDA 및 커스텀 레이아웃 지원
</Step>

<Step title="이벤트 파싱">
- 트랜잭션 로그에서 이벤트 파싱
- 이벤트 발생 검증
- 타입 안전한 이벤트 역직렬화
</Step>
</Steps>

## 간단한 예제

Anchor 1.0에서는 `declare_program!`을 사용해 프로그램의 IDL로부터 클라이언트 타입을 생성하세요.
이 매크로는 타입 안전한 instruction 빌드를 위한 `client::accounts::*` 및 `client::args::*`
모듈과 프로그램 ID를 생성합니다:

```rust
use anchor_lang::prelude::*;
use anchor_lang::system_program;
use anchor_litesvm::{AnchorLiteSVM, Signer, TestHelpers};

// Generate client types and the program ID from your program's IDL
anchor_lang::declare_program!(my_program);

#[test]
fn test_anchor_program() {
    // One-line setup with the program ID from the IDL
    let mut ctx = AnchorLiteSVM::build_with_program(
        my_program::ID,
        include_bytes!("../../../target/deploy/my_program.so"),
    );

    // Create a funded account via TestHelpers on ctx.svm
    let user = ctx.svm.create_funded_account(10_000_000_000).unwrap();

    // Derive PDA
    let seed: u64 = 42;
    let pda = ctx.svm.get_pda(
        &[b"user", user.pubkey().as_ref(), &seed.to_le_bytes()],
        &my_program::ID,
    );

    // Build instruction using generated client types
    let ix = ctx.program()
        .accounts(my_program::client::accounts::Initialize {
            user: user.pubkey(),
            user_account: pda,
            system_program: system_program::ID,
        })
        .args(my_program::client::args::Initialize {
            seed,
            name: "test".to_string(),
        })
        .instruction()
        .unwrap();

    // Execute and assert in one chain
    ctx.execute_instruction(ix, &[&user])
        .unwrap()
        .assert_success();

    // Fetch and deserialize the account
    let account: my_program::accounts::MyAccount = ctx.get_account(&pda).unwrap();
    assert_eq!(account.name, "test");
}
```

<Info>
  `declare_program!(my_program)`은 컴파일 시점에 `idls/my_program.json`에서 IDL을 읽습니다
  (크레이트 디렉터리와 그 상위 디렉터리에서 `idls` 디렉터리를 검색합니다).
  `my_program::ID`는 IDL에 있는 주소로, 프로그램의 `declare_id!`와 같습니다.
  매크로를 호출하는 위치에서 `anchor_lang`도 스코프에 있어야 하므로,
  그 위에 `use anchor_lang::prelude::*;`를 추가하세요.
</Info>

## 비교: 순수 LiteSVM vs anchor-litesvm

### 이전 (순수 LiteSVM)

```rust
use litesvm::LiteSVM;
use solana_keypair::Keypair;
use solana_signer::Signer;
use solana_program::instruction::{AccountMeta, Instruction};
use solana_message::Message;
use solana_transaction::Transaction;

let mut svm = LiteSVM::new();
svm.add_program(program_id, program_bytes).unwrap();

let payer = Keypair::new();
svm.airdrop(&payer.pubkey(), 10_000_000_000).unwrap();

// Manually compute 8-byte discriminator
let discriminator = {
    let mut hasher = sha2::Sha256::new();
    hasher.update(b"global:initialize");
    let result = hasher.finalize();
    result[..8].to_vec()
};

// Manually serialize args and build instruction
let mut data = discriminator;
data.extend_from_slice(&borsh::to_vec(&args).unwrap());

let accounts = vec![
    AccountMeta::new(user.pubkey(), true),
    AccountMeta::new(user_pda, false),
    AccountMeta::new_readonly(system_program::id(), false),
];

let ix = Instruction::new_with_bytes(program_id, &data, accounts);
let tx = Transaction::new_signed_with_payer(
    &[ix],
    Some(&payer.pubkey()),
    &[&payer],
    svm.latest_blockhash(),
);
svm.send_transaction(tx).unwrap();

// Manually deserialize with discriminator skip
let account_data = svm.get_account(&pda).unwrap().data;
let account: MyAccount = MyAccount::try_deserialize(
    &mut &account_data[8..]
).unwrap();
```

### 이후 (anchor-litesvm)

```rust
use anchor_lang::prelude::*;
use anchor_litesvm::{AnchorLiteSVM, Signer, TestHelpers};

anchor_lang::declare_program!(my_program);

let mut ctx = AnchorLiteSVM::build_with_program(my_program::ID, program_bytes);
let user = ctx.svm.create_funded_account(10_000_000_000).unwrap();

let ix = ctx.program()
    .accounts(my_program::client::accounts::Initialize {
        user: user.pubkey(),
        user_account: user_pda,
        system_program: anchor_lang::system_program::ID,
    })
    .args(my_program::client::args::Initialize { seed, name: "test".to_string() })
    .instruction()
    .unwrap();

ctx.execute_instruction(ix, &[&user]).unwrap().assert_success();

let account: my_program::accounts::MyAccount = ctx.get_account(&user_pda).unwrap();
```

## 주요 구성 요소

### AnchorLiteSVM Builder

| 메서드                          | 설명                    |
| ------------------------------- | ------------------------------ |
| `new()`                         | 새 빌더 인스턴스를 생성합니다 |
| `with_payer(keypair)`           | 커스텀 payer keypair를 설정합니다    |
| `deploy_program(id, bytes)`     | 배포할 프로그램을 추가합니다       |
| `build()`                       | AnchorContext를 빌드합니다       |
| `build_with_program(id, bytes)` | 단일 프로그램용 편의 메서드 |
| `build_with_programs(programs)` | 여러 프로그램을 배포합니다       |

### AnchorContext

| 메서드                               | 설명                                                       |
| ------------------------------------ | ----------------------------------------------------------------- |
| `svm`                                | 내부 `LiteSVM` 인스턴스에 직접 접근 (public 필드) |
| `program_id`                         | 프로그램 ID (public 필드)                                     |
| `program()`                          | instruction 빌드를 위한 `Program`을 반환합니다                        |
| `payer()`                            | payer `Keypair`를 가져옵니다                                           |
| `execute_instruction(ix, signers)`   | 단일 instruction을 실행합니다                                      |
| `execute_instructions(ixs, signers)` | 하나의 트랜잭션에서 여러 instruction을 실행합니다                           |
| `send_and_confirm_transaction(&tx)`  | 원시 트랜잭션을 전송합니다                                            |
| `get_account<T>(pubkey)`             | Anchor 계정을 조회하고 역직렬화합니다                           |
| `get_account_unchecked<T>(pubkey)`   | discriminator 검사 없이 조회합니다                                 |
| `create_funded_account(lamports)`    | 새 keypair를 생성하고 자금을 충전합니다                                     |
| `airdrop(pubkey, lamports)`          | 주소로 SOL을 에어드롭합니다                                         |
| `latest_blockhash()`                 | 현재 blockhash를 가져옵니다                                         |
| `account_exists(pubkey)`             | 계정이 존재하는지 확인합니다                                        |
| `deploy_program(id, bytes)`          | 추가 프로그램을 배포합니다 (`ProgramTestExt` 사용)               |

### Program

| 메서드               | 설명                                            |
| -------------------- | ------------------------------------------------------ |
| `accounts(accounts)` | instruction 계정을 설정합니다 (모든 `ToAccountMetas` 타입)   |
| `args(args)`         | instruction 인자를 설정합니다 (모든 `InstructionData` 타입) |
| `instruction()`      | 최종 `Instruction`을 빌드합니다                          |
| `id()`               | 프로그램 ID를 가져옵니다                                     |

### ctx.svm — TestHelpers & AssertionHelpers

`ctx.svm`은 public `LiteSVM` 필드이며, `litesvm-utils`를 통해 `TestHelpers` 및
`AssertionHelpers` 트레이트를 사용할 수 있습니다:

| 메서드                                                    | 설명               |
| --------------------------------------------------------- | ------------------------- |
| `ctx.svm.create_funded_account(lamports)`                 | keypair를 생성하고 자금을 충전합니다 |
| `ctx.svm.create_token_mint(authority, decimals)`          | SPL 토큰 mint를 생성합니다  |
| `ctx.svm.create_associated_token_account(mint, owner)`    | ATA를 생성합니다             |
| `ctx.svm.mint_to(mint, token_account, authority, amount)` | 토큰을 발행합니다               |
| `ctx.svm.get_pda(seeds, program_id)`                      | PDA 주소를 파생합니다      |
| `ctx.svm.get_pda_with_bump(seeds, program_id)`            | bump seed와 함께 PDA를 파생합니다 |
| `ctx.svm.assert_token_balance(token_account, expected)`   | 토큰 잔액을 검증합니다      |
| `ctx.svm.assert_account_closed(pubkey)`                   | 계정이 닫혔는지 검증합니다 |
| `ctx.svm.assert_sol_balance(pubkey, expected)`            | SOL 잔액을 검증합니다        |

## 문제 해결

### 일반적인 오류

| 오류                                                    | 원인                                       | 해결 방법                                                                 |
| -------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------ |
| `Failed to add program: Instruction(InvalidAccountData)` | 프로그램이 SBPF v3로 빌드되었습니다            | [설치](#installation)에서 설명한 대로 SBPF v0용으로 빌드하세요      |
| `AccountNotFound`                                        | 계정이 존재하지 않습니다                       | 조회하기 전에 계정이 생성되었는지 확인하세요                                |
| `DiscriminatorMismatch`                                  | 잘못된 계정 타입                          | 올바른 계정 구조체를 사용하고 있는지 확인하세요                           |
| `DeserializationError`                                   | 잘못된 계정 데이터                        | 계정이 올바르게 초기화되었는지 확인하세요                                  |
| 추가된 프로그램 없음                                        | `deploy_program()` 없이 `build()`를 호출했습니다 | 빌드하기 전에 프로그램을 하나 이상 추가하세요                                 |
| 클라이언트 타입 누락                                     | `declare_program!`이 호출되지 않았습니다               | `target/idl/`의 IDL을 `idls/`로 복사한 다음 `declare_program!`을 호출하세요 |
