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

# Bắt đầu nhanh

> Tìm hiểu cách sử dụng crate litesvm-token để kiểm thử với SPL token

[Xem `litesvm-token` trên crates.io](https://crates.io/crates/litesvm-token)

## Cài đặt

Hãy đảm bảo bạn đã có đầy đủ các dependency cần thiết:

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

## Kiến thức cơ bản về SPL Token

Trên Solana, việc tạo một token account gồm hai bước.

<Steps>
<Step title="Tạo một Mint Account">
- Không có số dư token 
- Lưu trữ toàn bộ thông tin chung của token, như tổng cung, số thập phân (decimals), authority, v.v.
- Mỗi token có một Mint Account
- Owner là Token Program (Tokenkeg hoặc Token-2022)
</Step>

<Step title="Tạo một Token Account">
- Lưu trữ số dư của một SPL token cụ thể 
- Giữ Mint Account để xác định SPL token nào nằm trong account này 
- Một Mint Account có thể có nhiều token account 
- Owner là bên có quyền kiểm soát số token trong account này 
</Step>
</Steps>

## Các loại Token Account

### Token Account thông thường

Một token account lưu trữ số dư của bạn cho một SPL token cụ thể:

```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="Ưu điểm" icon="check">
    - Có thể tạo nhiều account cho cùng một mint/owner
    - Linh hoạt - có thể dùng bất kỳ địa chỉ nào
  </Card>

  <Card title="Nhược điểm" icon="x">
    - Không mang tính xác định - cần theo dõi địa chỉ thủ công
    - Người nhận phải cho bạn biết account nào để gửi đến
    - Gây nhầm lẫn khi có nhiều account
  </Card>
</Columns>

<Info>
  **Khi nào nên dùng:** Account tạm thời/escrow, account do chương trình sở hữu với logic tùy chỉnh, khi bạn cần nhiều account cho cùng một token, các chiến lược DeFi nâng cao.
</Info>

### Associated Token Account (ATA)

ATA là một token account nằm tại một địa chỉ PDA mang tính xác định:

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

Cách địa chỉ ATA được dẫn xuất:

```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="Ưu điểm" icon="check">
    - Một account chuẩn duy nhất cho mỗi cặp owner/mint
    - Mang tính xác định - ai cũng có thể tính ra địa chỉ
    - Đơn giản hóa thanh toán - chỉ cần địa chỉ ví + mint
    - Quy ước tiêu chuẩn trên mọi ứng dụng Solana
  </Card>

  <Card title="Nhược điểm" icon="x">
    - Chỉ có thể có MỘT ATA cho mỗi cặp owner/mint (theo thiết kế)
  </Card>
</Columns>

<Info>
  **Khuyến nghị cho hầu hết trường hợp:** Ứng dụng ví, giao thức DeFi, nắm giữ NFT, hệ thống thanh toán và mọi giao dịch chuyển token hướng đến người dùng.
</Info>

## Ví dụ nhanh

Dưới đây là ví dụ hoàn chỉnh về việc tạo một token mint và mint token:

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

## Khái niệm chính

### Số thập phân của token

Hầu hết token sử dụng số thập phân để biểu diễn các giá trị phân số:

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

### Mối quan hệ giữa các account

Việc hiểu mối quan hệ giữa các account là rất quan trọng:

- **Mint Account**: Định nghĩa token (nguồn cung, số thập phân, các authority)
- **Token Account**: Giữ token cho một owner cụ thể
- **Associated Token Account**: Token account mang tính xác định cho một cặp owner+mint
- **Mint Authority**: Có thể tạo token mới
- **Freeze Authority**: Có thể đóng băng các token account (tùy chọn)

## Khắc phục sự cố

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

| Lỗi                       | Nguyên nhân                                               | Giải pháp                                |
| --------------------------- | --------------------------------------------------- | --------------------------------------- |
| `AccountNotFound`           | Cố gắng sử dụng một account không tồn tại         | Đảm bảo account đã được tạo trước khi sử dụng    |
| `AccountAlreadyInitialized` | Cố gắng khởi tạo một account đã được khởi tạo | Kiểm tra account đã tồn tại chưa trước khi tạo |
| `InsufficientFunds`         | Không đủ lamport để trả rent hoặc không đủ token để chuyển | Đảm bảo đã nạp đủ tiền/mint đủ token       |
| `OwnerMismatch`             | Account thuộc sở hữu của chương trình sai                      | Xác minh đúng program ID khi tạo |
