> ## Documentation Index
> Fetch the complete documentation index at: https://docs.raydium.io/llms.txt
> Use this file to discover all available pages before exploring further.

# 部署 CLMM 池

> 即插即用的 Node 脚本，用于创建新的 CLMM 池，然后开启初始集中头寸。模拟官方 raydium-sdk-V2-demo 流程。

<Info>
  **本页内容由 AI 自动翻译，所有内容以英文版本为准。**

  [查看英文版 →](/quick-start/deploy-clmm-pool)
</Info>

<Info>
  **这段代码做什么。** 在你选择的费用层级创建新的 CLMM 池，然后开启初始集中头寸。两笔交易，一个脚本。代码来自 [`raydium-sdk-V2-demo/src/clmm`](https://github.com/raydium-io/raydium-sdk-V2-demo/tree/master/src/clmm) 中的官方演示，并适配为单个 Node 可运行的文件。
</Info>

## 准备工作

确保你已阅读 [快速入门先决条件](/zh/quick-start)，拥有 `RPC_URL`、`KEYPAIR` 和安装好的依赖项。

CLMM 池创建需要一次性费用，加上初始头寸的按 tick 数组租金。你还需要在钱包中拥有两种种子币种——当价格落在选择的范围内开启头寸时，需要两边都有流动性。

## 步骤 1 — `config.ts`

保存为 `config.ts`。形式与演示仓库的 [`src/config.ts.template`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/config.ts.template) 相同——`disableFeatureCheck` 被强制设置为 `true`（对于任何非平凡的集成都推荐这样做，这样 SDK 就不会在启动功能检测调用时阻塞）：

```ts theme={null}
// config.ts
import { Raydium, TxVersion, parseTokenAccountResp } from "@raydium-io/raydium-sdk-v2";
import { Connection, Keypair, clusterApiUrl } from "@solana/web3.js";
import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } from "@solana/spl-token";
import bs58 from "bs58";
import fs from "node:fs";

export const owner: Keypair = Keypair.fromSecretKey(
  // accept either a JSON-array keypair file (same shape Solana CLI writes) or a bs58 secret in env
  process.env.KEYPAIR_BS58
    ? bs58.decode(process.env.KEYPAIR_BS58)
    : new Uint8Array(JSON.parse(fs.readFileSync(process.env.KEYPAIR!, "utf8"))),
);

export const connection = new Connection(
  process.env.RPC_URL ?? clusterApiUrl("mainnet-beta"),
  "confirmed",
);
export const txVersion = TxVersion.V0;
const cluster = "mainnet" as "mainnet" | "devnet";

let raydium: Raydium | undefined;
export const initSdk = async (params?: { loadToken?: boolean }) => {
  if (raydium) return raydium;
  raydium = await Raydium.load({
    owner,
    connection,
    cluster,
    disableFeatureCheck: true,
    disableLoadToken: !params?.loadToken,
    blockhashCommitment: "finalized",
  });
  return raydium;
};

export const fetchTokenAccountData = async () => {
  const solAccountResp = await connection.getAccountInfo(owner.publicKey);
  const tokenAccountResp = await connection.getTokenAccountsByOwner(owner.publicKey, {
    programId: TOKEN_PROGRAM_ID,
  });
  const token2022Req = await connection.getTokenAccountsByOwner(owner.publicKey, {
    programId: TOKEN_2022_PROGRAM_ID,
  });
  return parseTokenAccountResp({
    owner: owner.publicKey,
    solAccountResp,
    tokenAccountResp: {
      context: tokenAccountResp.context,
      value: [...tokenAccountResp.value, ...token2022Req.value],
    },
  });
};
```

## 步骤 2 — `createPool.ts`

与 `config.ts` 并排保存。源代码：[`src/clmm/createPool.ts`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/clmm/createPool.ts)。

```ts theme={null}
// createPool.ts
import { CLMM_PROGRAM_ID, DEVNET_PROGRAM_ID } from "@raydium-io/raydium-sdk-v2";
import { PublicKey } from "@solana/web3.js";
import Decimal from "decimal.js";
import { initSdk, txVersion } from "./config";

export const createPool = async () => {
  const raydium = await initSdk({ loadToken: true });

  // RAY
  const mint1 = await raydium.token.getTokenInfo("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R");
  // USDT
  const mint2 = await raydium.token.getTokenInfo("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB");

  // Fee tiers come from the live API. On devnet the published `id` field is wrong;
  // re-derive the PDA before passing it to the SDK.
  const clmmConfigs = await raydium.api.getClmmConfigs();

  const { execute } = await raydium.clmm.createPool({
    programId: CLMM_PROGRAM_ID,
    // programId: DEVNET_PROGRAM_ID.CLMM_PROGRAM_ID,
    mint1,
    mint2,
    ammConfig: {
      ...clmmConfigs[0],
      id: new PublicKey(clmmConfigs[0].id),
      fundOwner: "",
      description: "",
    },
    initialPrice: new Decimal(1),
    txVersion,
    // optional: set up priority fee here
    // computeBudgetConfig: { units: 600000, microLamports: 46591500 },
  });

  const { txId } = await execute({ sendAndConfirm: true });
  console.log("clmm pool created:", { txId: `https://explorer.solana.com/tx/${txId}` });
  process.exit();
};

createPool();
```

## 步骤 3 — `createPosition.ts`

源代码：[`src/clmm/createPosition.ts`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/clmm/createPosition.ts)。

```ts theme={null}
// createPosition.ts
import {
  ApiV3PoolInfoConcentratedItem,
  TickUtils,
  PoolUtils,
  ClmmKeys,
} from "@raydium-io/raydium-sdk-v2";
import BN from "bn.js";
import Decimal from "decimal.js";
import { initSdk, txVersion } from "./config";
import { isValidClmm } from "./utils";

export const createPosition = async () => {
  const raydium = await initSdk();

  let poolInfo: ApiV3PoolInfoConcentratedItem;
  // RAY-USDC pool
  const poolId = "61R1ndXxvsWXXkWSyNkCxnzwd3zUNB8Q2ibmkiLPC8ht";
  let poolKeys: ClmmKeys | undefined;

  if (raydium.cluster === "mainnet") {
    const data = await raydium.api.fetchPoolById({ ids: poolId });
    poolInfo = data[0] as ApiV3PoolInfoConcentratedItem;
    if (!isValidClmm(poolInfo.programId)) throw new Error("target pool is not CLMM pool");
  } else {
    const data = await raydium.clmm.getPoolInfoFromRpc(poolId);
    poolInfo = data.poolInfo;
    poolKeys = data.poolKeys;
  }

  // Optional: pull on-chain real-time price to avoid slippage errors from a stale API quote.
  // const rpcData = await raydium.clmm.getRpcClmmPoolInfo({ poolId: poolInfo.id });
  // poolInfo.price = rpcData.currentPrice;

  const inputAmount = 0.000001; // RAY amount
  const [startPrice, endPrice] = [0.000001, 100000];

  const { tick: lowerTick } = TickUtils.getPriceAndTick({
    poolInfo,
    price: new Decimal(startPrice),
    baseIn: true,
  });
  const { tick: upperTick } = TickUtils.getPriceAndTick({
    poolInfo,
    price: new Decimal(endPrice),
    baseIn: true,
  });

  const epochInfo = await raydium.fetchEpochInfo();
  const res = await PoolUtils.getLiquidityAmountOutFromAmountIn({
    poolInfo,
    slippage: 0,
    inputA: true,
    tickUpper: Math.max(lowerTick, upperTick),
    tickLower: Math.min(lowerTick, upperTick),
    amount: new BN(new Decimal(inputAmount || "0").mul(10 ** poolInfo.mintA.decimals).toFixed(0)),
    add: true,
    amountHasFee: true,
    epochInfo,
  });

  const { execute, extInfo } = await raydium.clmm.openPositionFromBase({
    poolInfo,
    poolKeys,
    tickUpper: Math.max(lowerTick, upperTick),
    tickLower: Math.min(lowerTick, upperTick),
    base: "MintA",
    ownerInfo: { useSOLBalance: true },
    baseAmount: new BN(new Decimal(inputAmount || "0").mul(10 ** poolInfo.mintA.decimals).toFixed(0)),
    otherAmountMax: res.amountSlippageB.amount,
    txVersion,
    computeBudgetConfig: { units: 600000, microLamports: 100000 },
  });

  const { txId } = await execute({ sendAndConfirm: true });
  console.log("clmm position opened:", { txId, nft: extInfo.nftMint.toBase58() });
  process.exit();
};

createPosition();
```

## 步骤 4 — `utils.ts`

源代码：[`src/clmm/utils.ts`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/clmm/utils.ts)。

```ts theme={null}
// utils.ts
import { CLMM_PROGRAM_ID, DEVNET_PROGRAM_ID } from "@raydium-io/raydium-sdk-v2";

const VALID_PROGRAM_IDS = new Set<string>([
  CLMM_PROGRAM_ID.toBase58(),
  DEVNET_PROGRAM_ID.CLMM_PROGRAM_ID.toBase58(),
]);

export const isValidClmm = (programId: string) => VALID_PROGRAM_IDS.has(programId);
```

## 运行

```bash theme={null}
# create the pool first
RPC_URL="https://api.mainnet-beta.solana.com" \
KEYPAIR="$HOME/.config/solana/id.json" \
npx tsx createPool.ts

# then open an initial position against the new pool id
# (edit poolId at the top of createPosition.ts to point at your new pool)
RPC_URL="https://api.mainnet-beta.solana.com" \
KEYPAIR="$HOME/.config/solana/id.json" \
npx tsx createPosition.ts
```

## 刚才发生了什么

**交易 1 — `raydium.clmm.createPool`** 初始化了：

* 位于 `(mint1, mint2, ammConfig)` 的规范 PDA 处的池状态，
* `token_0_vault` 和 `token_1_vault`（按 mint 字节顺序排序），
* `observation` 环形缓冲区，
* 内联 tick 数组位图，

并从你的 `initialPrice` 设置初始 `sqrt_price_x64`。

**交易 2 — `raydium.clmm.openPositionFromBase`** 开启了一个集中头寸：

* 向你的钱包铸造了头寸 NFT（NFT *就是* 头寸；转移它就转移头寸），
* 在下界和上界分配了 tick 数组（首个头寸在这些范围内时需一次租金；tick 数组不会被程序关闭，所以后续头寸在同一数组中无额外租金），
* 存入了 `mint1` 的 `inputAmount` 和匹配的 `mint2` 对应金额（由 `PoolUtils.getLiquidityAmountOutFromAmountIn` 计算），
* 根据范围宽度赋予头寸相应流动性。

范围越窄，每美元 TVL 的资本效率越高——同时当价格漂离范围时无常损失越大。上面使用的范围（`[0.000001, 100000]`）实际上是全范围；收紧范围来浓缩当前现货附近的手续费。

## 选择费用层级

`clmmConfigs[0]` 是最低费用层级。完整集合在 `GET https://api-v3.raydium.io/main/clmm-config` 发布：

| 索引 | `tradeFeeRate`  | Tick 间距 | 用途                     |
| -- | --------------- | ------- | ---------------------- |
| 0  | `100`（1bp）      | 1       | 稳定币对稳定币，预期极低的无常损失      |
| 1  | `500`（5bp）      | 10      | 高度相关的资产（如流动性质押币对其基础资产） |
| 2  | `2_500`（25bp）   | 60      | 标准代币对，蓝筹币加稳定币          |
| 3  | `10_000`（1.00%） | 120     | 高波动或薄流动性对，IL 风险高       |

详见 [`user-flows/choosing-a-pool-type`](/zh/user-flows/choosing-a-pool-type) 了解完整决策矩阵。

## 常见错误

* **`Pool already exists for this config`** — 此 `(mint1, mint2, ammConfig)` 组合已存在 CLMM 池。查找现有池 ID 并跳过第 2 步。
* **`Insufficient funds for amount B`** — 你的钱包有请求的 `mintA` 数量，但没有匹配的 `mintB`。当价格在范围内开启头寸时需要两边都有流动性。
* **`Tick out of range`** — 你的 `lowerPrice` 或 `upperPrice` 超出了可表示的价格范围。相对于当前价格使用更合理的范围。
* **价格过时** — API 的报价可能落后 5-60 秒。如果 `executePosition` 因滑点失败，在 `createPosition.ts` 中取消注释 `getRpcClmmPoolInfo` 代码块，在签署前重新获取实时价格。

## 注意事项

* **头寸 NFT 是你的唯一句柄。** 丢失 NFT 或转移它就会失去对头寸的访问权限。把它当作钥匙对待。
* **范围外头寸赚不了手续费。** 如果价格移动到 `[lowerPrice, upperPrice]` 之外，你的头寸完全停留在一种资产中，直到你重新平衡前一分钱也赚不到。
* **Tick 数组租金是单向的。** 首个接触从未初始化的 tick 数组的头寸需支付租金；程序不提供关闭 tick 数组的路径，所以租金是永久的。后续在同一数组中的头寸是免费的。

## 下一步

* [`products/clmm/overview`](/zh/products/clmm/overview) — 完整 CLMM 机制。
* [`products/clmm/ticks-and-positions`](/zh/products/clmm/ticks-and-positions) — tick 的数学原理。
* [`algorithms/impermanent-loss`](/zh/algorithms/impermanent-loss) — 量化 CLMM IL 放大。
* [`user-flows/create-clmm-pool`](/zh/user-flows/create-clmm-pool) — 通过 Raydium UI 的同一流程。

源代码：

* [`raydium-sdk-V2-demo/src/clmm/createPool.ts`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/clmm/createPool.ts)
* [`raydium-sdk-V2-demo/src/clmm/createPosition.ts`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/clmm/createPosition.ts)
* [`raydium-sdk-V2-demo/src/clmm/utils.ts`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/clmm/utils.ts)
* [`raydium-sdk-V2-demo/src/config.ts.template`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/config.ts.template)
