> ## 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-program/token과 LiteSVM으로 SPL 토큰 테스트하기

Solana에서 토큰 로직을 테스트하려면, 정작 확인하고 싶은 전송 로직을 테스트하기 전에 먼저 민트, token account, 권한(authority)을 설정해야 합니다.
`@solana-program/token`의 `tokenProgram()` 플러그인은 이 설정 과정을 몇 번의 메서드 호출로 줄여 주며, ATA 생성도 자동으로 처리합니다.

[npm에서 `@solana-program/token` 보기](https://www.npmjs.com/package/@solana-program/token)

## 설치

```bash
npm install @solana/kit @solana/kit-plugin-litesvm @solana/kit-plugin-signer @solana-program/token
```

## 민트 생성

```typescript
import { createClient, generateKeyPairSigner, lamports } from "@solana/kit";
import { litesvm } from "@solana/kit-plugin-litesvm";
import { signer } from "@solana/kit-plugin-signer";
import { tokenProgram } from "@solana-program/token";

const mySigner = await generateKeyPairSigner();
const client = createClient()
  .use(signer(mySigner))
  .use(litesvm())
  .use(tokenProgram());

client.svm.airdrop(client.payer.address, lamports(10_000_000_000n));

const mintAuthority = await generateKeyPairSigner();
const newMint = await generateKeyPairSigner();

await client.token.instructions
  .createMint({
    newMint,
    decimals: 9,
    mintAuthority: mintAuthority.address
  })
  .sendTransaction();

// Verify
const mintAccount = await client.token.accounts.mint.fetch(newMint.address);
console.log(mintAccount.data.supply); // 0n
console.log(mintAccount.data.decimals); // 9
```

## 토큰 발행

`mintToATA`는 소유자의 Associated Token Account로 토큰을 발행합니다. ATA가 존재하지 않으면 동일한 트랜잭션에서 생성됩니다.

```typescript
await client.token.instructions
  .mintToATA({
    mint: newMint.address,
    owner: client.payer.address,
    mintAuthority,
    amount: 1_000_000_000_000n, // 1000 tokens (9 decimals)
    decimals: 9
  })
  .sendTransaction();
```

`decimals` 매개변수는 안전 장치입니다. 민트의 decimals와 정확히 일치해야 하며, 일치하지 않으면 Token Program이 `Custom program error: #18` (`0x12`, `MintDecimalsMismatch`) 오류와 함께 트랜잭션을 거부합니다. 이를 통해 실수로 1000배나 많은 토큰이 발행되는 것을 방지합니다.

## 토큰 전송

`transferToATA`는 사용자 간에 토큰을 이동합니다. 수신자의 ATA는 필요한 경우 자동으로 생성됩니다.

```typescript
const alice = await generateKeyPairSigner();
const bob = await generateKeyPairSigner();

// Mint to Alice
await client.token.instructions
  .mintToATA({
    mint: newMint.address,
    owner: alice.address,
    mintAuthority,
    amount: 1_000_000_000_000n,
    decimals: 9
  })
  .sendTransaction();

// Transfer 400 tokens from Alice to Bob
await client.token.instructions
  .transferToATA({
    mint: newMint.address,
    authority: alice,
    recipient: bob.address,
    amount: 400_000_000_000n,
    decimals: 9
  })
  .sendTransaction();
```

`authority`는 소스 토큰을 소유한 서명자입니다. 플러그인은 각 주소와 민트를 이용해 소스 ATA와 대상 ATA를 모두 파생합니다.

## 잔액 확인

토큰 잔액을 조회하려면 `findAssociatedTokenPda`로 ATA 주소를 파생한 다음, 디코딩된 계정을 가져옵니다.

```typescript
import {
  findAssociatedTokenPda,
  TOKEN_PROGRAM_ADDRESS
} from "@solana-program/token";

const [aliceAta] = await findAssociatedTokenPda({
  owner: alice.address,
  mint: newMint.address,
  tokenProgram: TOKEN_PROGRAM_ADDRESS
});

const aliceAccount = await client.token.accounts.token.fetch(aliceAta);
console.log(aliceAccount.data.amount); // 600_000_000_000n
console.log(aliceAccount.data.mint); // newMint.address
console.log(aliceAccount.data.owner); // alice.address
```

## 소수 자릿수(Decimals)

토큰 수량은 항상 원시 단위로 표현됩니다. decimals가 9인 토큰 1000개는 `1000n`이 아니라 `1_000_000_000_000n`입니다.

```typescript
// USDC has 6 decimals
const oneUSDC = 10n ** 6n; // 1_000_000n

// SOL has 9 decimals
const oneSOL = 10n ** 9n; // 1_000_000_000n
```

<Warning>
  토큰 수량에는 항상 `BigInt`를 사용하세요. JavaScript의 `Number`는 2^53을 초과하면 정밀도를 잃습니다.
</Warning>

## 플러그인 레퍼런스

| 메서드                                      | 설명                                                  |
| ------------------------------------------- | ------------------------------------------------------------ |
| `client.token.instructions.createMint()`    | 새 SPL 토큰 민트 생성                                  |
| `client.token.instructions.mintToATA()`     | 소유자의 ATA로 토큰 발행 (필요 시 ATA 생성)        |
| `client.token.instructions.transferToATA()` | 수신자의 ATA로 토큰 전송 (필요 시 ATA 생성) |
| `client.token.accounts.mint.fetch()`        | mint account를 가져와 디코딩                              |
| `client.token.accounts.token.fetch()`       | token account를 가져와 디코딩                             |

## 자주 발생하는 오류

| 오류                                                               | 원인                             | 해결 방법                                                    |
| ------------------------------------------------------------------- | --------------------------------- | ------------------------------------------------------ |
| `Custom program error: #18` (`0x12`, `MintDecimalsMismatch`)        | `decimals`가 민트와 일치하지 않음 | `createMint`에 전달한 것과 동일한 decimals 값을 사용하세요 |
| `Account not found at address: ...`                                 | 계정이 아직 존재하지 않음         | 가져오거나 발행하기 전에 민트가 생성되었는지 확인하세요  |
| `Attempt to debit an account but found no record of a prior credit` | 수수료를 지불할 SOL이 payer에게 없음  | 먼저 payer에게 SOL을 에어드롭하세요                         |
| `Custom program error: #4` (`OwnerMismatch`)                       | 서명하는 `authority`가 소스 token account의 소유자가 아님 | 실제 소유자를 `authority`로 전달하세요     |
