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

# Kiểm thử Token

> Kiểm thử với SPL token bằng @solana-program/token và LiteSVM

Kiểm thử logic token trên Solana đồng nghĩa với việc phải thiết lập mint, token account và
các authority trước khi bạn có thể kiểm thử logic chuyển token mà bạn thực sự quan tâm. Plugin
`tokenProgram()` từ `@solana-program/token` rút gọn quá trình thiết lập đó xuống
chỉ còn vài lệnh gọi phương thức — và tự động xử lý việc tạo ATA.

[Xem `@solana-program/token` trên npm](https://www.npmjs.com/package/@solana-program/token)

## Cài đặt

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

## Tạo Mint

```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
```

## Mint Token

`mintToATA` phát hành token cho Associated Token Account của chủ sở hữu. Nếu ATA
chưa tồn tại, nó sẽ được tạo trong cùng một giao dịch.

```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();
```

Tham số `decimals` là một bước kiểm tra an toàn — giá trị này phải khớp chính xác với decimals của mint,
nếu không Token Program sẽ từ chối giao dịch với lỗi `Custom program error: #18` (`0x12`,
`MintDecimalsMismatch`). Điều này
giúp tránh việc vô tình mint dư gấp 1000 lần số token.

## Chuyển Token

`transferToATA` chuyển token giữa những người dùng. ATA của người nhận sẽ được tạo
tự động nếu cần.

```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` là bên ký sở hữu số token nguồn. Plugin sẽ suy ra
cả ATA nguồn và ATA đích từ địa chỉ của chúng + mint.

## Xác minh số dư

Để đọc lại số dư token, hãy suy ra địa chỉ ATA bằng
`findAssociatedTokenPda` và lấy account đã được giải mã:

```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

Số lượng token luôn được tính theo đơn vị thô. 1000 token với 9 decimals là
`1_000_000_000_000n`, chứ không phải `1000n`.

```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>
  Luôn sử dụng `BigInt` cho số lượng token. `Number` của JavaScript bị mất độ chính xác
  khi vượt quá 2^53.
</Warning>

## Tham chiếu Plugin

| Phương thức                                      | Mô tả                                                  |
| ------------------------------------------- | ------------------------------------------------------------ |
| `client.token.instructions.createMint()`    | Tạo một SPL token mint mới                                  |
| `client.token.instructions.mintToATA()`     | Mint token vào ATA của chủ sở hữu (tạo ATA nếu cần)        |
| `client.token.instructions.transferToATA()` | Chuyển token vào ATA của người nhận (tạo ATA nếu cần) |
| `client.token.accounts.mint.fetch()`        | Lấy và giải mã một mint account                              |
| `client.token.accounts.token.fetch()`       | Lấy và giải mã một token account                             |

## Các lỗi thường gặp

| Lỗi                                                               | Nguyên nhân                             | Cách khắc phục                                                    |
| ------------------------------------------------------------------- | --------------------------------- | ------------------------------------------------------ |
| `Custom program error: #18` (`0x12`, `MintDecimalsMismatch`)        | `decimals` không khớp với mint | Sử dụng cùng giá trị decimals mà bạn đã truyền vào `createMint` |
| `Account not found at address: ...`                                 | Account chưa tồn tại         | Đảm bảo mint đã được tạo trước khi fetch hoặc mint  |
| `Attempt to debit an account but found no record of a prior credit` | Người trả phí không có SOL để trả phí  | Airdrop SOL cho người trả phí trước                         |
| `Custom program error: #4` (`OwnerMismatch`)                       | `authority` ký không phải là chủ sở hữu của token account nguồn | Truyền chủ sở hữu thực sự làm `authority`     |
