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

# 빠른 시작

> SPL 토큰 테스트에 litesvm-token 크레이트를 사용하는 방법을 알아보세요

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

## 설치

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

```bash
cargo add --dev litesvm litesvm-token solana-sdk@4 spl-token spl-associated-token-account
cargo add --dev solana-system-interface --features bincode
```

## SPL 토큰 기초

Solana에서 token account를 생성하는 과정은 두 단계로 이루어집니다.

<Steps>
<Step title="Mint Account 생성">
- 토큰 잔액이 없습니다 
- 총 공급량, 소수점 자릿수, 권한 등 토큰의 모든 전역 정보를 보관합니다
- 토큰당 Mint Account가 하나씩 존재합니다
- 소유자는 Token Program입니다(Tokenkeg 또는 Token-2022)
</Step>

<Step title="Token Account 생성">
- 특정 SPL 토큰의 잔액을 저장합니다 
- 이 계정에 어떤 SPL 토큰이 담기는지 정의하는 Mint Account를 가리킵니다 
- 하나의 Mint Account에 대해 여러 개의 token account가 존재할 수 있습니다 
- 소유자는 이 계정 안의 토큰을 제어할 수 있는 주체입니다 
</Step>
</Steps>

## Token Account의 유형

### 일반 Token Account

token account는 특정 SPL 토큰에 대한 잔액을 저장합니다:

```rust
// Can create token accounts at ANY address
let token_account = Keypair::new();  // Random address
let create_ix = system_instruction::create_account(
    &payer.pubkey(),
    &token_account.pubkey(),  // Any address you want
    rent,
    165,  // Token account size
    &spl_token::id(),
);
let init_ix = spl_token::instruction::initialize_account(
    &spl_token::id(),
    &token_account.pubkey(),
    &mint,
    &owner.pubkey(),
)?;
```

<Columns cols={2}>
  <Card title="장점" icon="check">
    - 같은 mint/소유자에 대해 여러 계정을 만들 수 있음
    - 유연함 - 어떤 주소든 사용 가능
  </Card>

  <Card title="단점" icon="x">
    - 결정적이지 않음 - 주소를 수동으로 추적해야 함
    - 수신자가 어느 계정으로 보내야 하는지 알려줘야 함
    - 여러 계정으로 인해 혼란이 발생함
  </Card>
</Columns>

<Info>
  **사용 시점:** 임시/에스크로 계정, 커스텀 로직이 있는 프로그램 소유 계정, 같은 토큰에 대해
  여러 계정이 필요한 경우, 고급 DeFi 전략.
</Info>

### Associated Token Account (ATA)

ATA는 결정적 PDA 주소에 있는 token account입니다:

```rust
// ATA address is ALWAYS the same for owner + mint
let ata = get_associated_token_address(&owner.pubkey(), &mint);
// Address derived from: [owner_pubkey, token_program_id, mint]
```

ATA 주소가 도출되는 방식:

```rust
// The ATA address is a PDA of the Associated Token Program;
// the account itself is owned by the Token Program
let (ata, bump) = Pubkey::find_program_address(
    &[
        owner.as_ref(),
        spl_token::id().as_ref(),
        mint.as_ref(),
    ],
    &spl_associated_token_account::id(),  // ATA program
);
```

<Columns cols={2}>
  <Card title="장점" icon="check">
    - 소유자/mint 쌍당 하나의 표준 계정
    - 결정적 - 누구나 주소를 계산할 수 있음
    - 결제 간소화 - 지갑 주소 + mint만 있으면 됨
    - 모든 Solana 앱에서 통용되는 표준 규칙
  </Card>

  <Card title="단점" icon="x">
    - 소유자/mint당 ATA를 하나만 가질 수 있음(설계상)
  </Card>
</Columns>

<Info>
  **대부분의 경우 권장:** 지갑 애플리케이션, DeFi 프로토콜, NFT 보유,
  결제 시스템 및 사용자 대상 토큰 전송 전반.
</Info>

## 간단한 예제

토큰 mint를 생성하고 토큰을 발행하는 전체 예제입니다:

```rust
use litesvm::LiteSVM;
use litesvm_token::{
    get_spl_account,
    spl_token::{native_mint::DECIMALS, state::Account as TokenAccount},
    CreateAccount, CreateMint, MintTo, Transfer,
};
use solana_sdk::{
    native_token::LAMPORTS_PER_SOL,
    signature::{Keypair, Signer},
};

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

    // Create payer account and fund it
    let payer = Keypair::new();
    svm.airdrop(&payer.pubkey(), 10 * LAMPORTS_PER_SOL).unwrap();

    // Create a new SPL token mint with the payer as the mint authority
    let mint = CreateMint::new(&mut svm, &payer)
        .authority(&payer.pubkey())
        .decimals(DECIMALS)
        .send()
        .unwrap();

    // Create a token account for the payer
    let token_account = CreateAccount::new(&mut svm, &payer, &mint)
        .owner(&payer.pubkey())
        .send()
        .unwrap();

    // Mint tokens into the payer's token account
    MintTo::new(&mut svm, &payer, &mint, &token_account, 1000)
        .owner(&payer)
        .send()
        .unwrap();

    // Verify balance
    let token_account: TokenAccount = get_spl_account(&svm, &token_account).unwrap();
    let account_balance = token_account.amount;
    assert_eq!(account_balance, 1000)
}
```

## 핵심 개념

### 토큰 소수점 자릿수

대부분의 토큰은 소수 단위 금액을 표현하기 위해 소수점 자릿수를 사용합니다:

```rust
// SOL has 9 decimals
let one_sol = 10_u64.pow(9);  // 1_000_000_000 lamports

// USDC has 6 decimals
let one_usdc = 10_u64.pow(6); // 1_000_000 micro-USDC

// Always account for decimals in calculations
let amount_tokens = 100;
let amount_raw = amount_tokens * 10_u64.pow(decimals as u32);
```

### 계정 간 관계

계정 간의 관계를 이해하는 것이 중요합니다:

- **Mint Account**: 토큰을 정의합니다(공급량, 소수점 자릿수, 권한)
- **Token Account**: 특정 소유자의 토큰을 보관합니다
- **Associated Token Account**: 소유자+mint 쌍에 대한 결정적
  token account
- **Mint Authority**: 새 토큰을 생성할 수 있음
- **Freeze Authority**: token account를 동결할 수 있음(선택 사항)

## 문제 해결

### 자주 발생하는 오류

| 오류                       | 원인                                               | 해결 방법                                |
| --------------------------- | --------------------------------------------------- | --------------------------------------- |
| `AccountNotFound`           | 존재하지 않는 계정을 사용하려고 함         | 사용하기 전에 계정이 생성되었는지 확인    |
| `AccountAlreadyInitialized` | 이미 초기화된 계정을 다시 초기화하려고 함 | 생성하기 전에 계정이 존재하는지 확인 |
| `InsufficientFunds`         | rent에 필요한 lamports 또는 전송에 필요한 토큰이 부족함 | 충분한 자금 충전 및 토큰 발행 확인       |
| `OwnerMismatch`             | 잘못된 프로그램이 소유한 계정                      | 생성 시 올바른 프로그램 ID인지 확인 |
