> ## 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 上测试代币逻辑，意味着在测试你真正关心的转账逻辑之前，必须先设置 mint、token account 和授权方。`@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
```

## 创建 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
```

## 铸造代币

`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` 参数是一项安全检查——它必须与 mint 的小数位数完全一致，否则 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` 是持有源代币的签名者。插件会根据双方的地址以及 mint 推导出源 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
```

## 小数位数

代币数量始终以原始单位表示。9 位小数的 1000 个代币应为 `1_000_000_000_000n`，而不是 `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>
  代币数量请始终使用 `BigInt`。JavaScript 的 `Number` 在超过 2^53 时会丢失精度。
</Warning>

## 插件参考

| 方法                                      | 说明                                                  |
| ------------------------------------------- | ------------------------------------------------------------ |
| `client.token.instructions.createMint()`    | 创建新的 SPL 代币 mint                                  |
| `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` 与 mint 不匹配 | 使用与传给 `createMint` 时相同的 decimals 值 |
| `Account not found at address: ...`                                 | 账户尚不存在         | 确保在获取或铸造之前已创建 mint  |
| `Attempt to debit an account but found no record of a prior credit` | 付款方没有用于支付手续费的 SOL  | 先向付款方空投 SOL                         |
| `Custom program error: #4`（`OwnerMismatch`）                       | 签名的 `authority` 不是源 token account 的所有者 | 将真正的所有者作为 `authority` 传入     |
