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

# 快速入门

> 了解如何使用 litesvm-token crate 测试 SPL 代币

[在 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 代币的余额 
- 保存 Mint Account,以确定该账户中是哪种 SPL 代币 
- 一个 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`         | lamports 不足以支付 rent,或代币不足以完成转账 | 确保有足够的资金/铸造数量       |
| `OwnerMismatch`             | 账户由错误的程序拥有                      | 创建时请验证程序 ID 是否正确 |
