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

# 快速开始

> 安装 SDK、读取池、获取兑换报价，并发送第一笔交易。

export const VersionBanner = ({network = 'mainnet', products = [], lang = 'en'}) => {
  const SDK_VERSION = '1.0.2';
  const ADDRESSES = {
    mainnet: {
      cpmm: {
        Router: 'ze15rnAwTyVCPnDhN7J8An3SvNeWBsZHAVMeBx1ehXeP',
        TokenPairFactory: '24CXRLvj1QiDH6riwr1EPERG7BcduHKZtktygbq97MfYb'
      },
      clmm: {
        PoolFactory: '24gqd4DMQXVzjm5QDAGxUtYupx3WM2PSu3vZUseuBCV9h',
        PositionManager: 'vFyKSqnJHS9MicrojBcLgztyRFqhS4hB349Ci3LJCELw'
      },
      staking: {
        XAlphToken: '225WevmFp5ZgzPsyVJTvyp2v2uyKrvp329HfrVmzffnWj',
        RewardFeeCollector: '22CE7vG6u64zjjsLZLxeJqQuPDydjPvbP9iG1d861j2G7'
      }
    },
    testnet: {
      cpmm: {
        Router: 'xaueT8kPMvpnaFJEfHv6CJLgqsSPpoNmHjF1QgTxoF9R',
        TokenPairFactory: '29hdd9b9Gp7oXuamwHKfUqBaRXP487HoeTcutS3RhZJEj'
      },
      clmm: {
        PoolFactory: 'z2QFT7qBQrfm8UwAYG3VHWoHs7B56ZDFNdSCcDu5j53m',
        PositionManager: '21p6egW8d6FEyVVuH17WqvHCARsCsD61GcBmeCr75XdGT'
      },
      staking: {
        XAlphToken: '23psDicimC5VdpM56wrgqgCzQzcyXWGCkQGSYWbtZAPRq',
        RewardFeeCollector: '29qQ1LPJ5uqawRviXLVDMeo19JUygRrNNTQy5RUBh817D'
      }
    }
  };
  const EXPLORERS = {
    mainnet: 'https://explorer.alephium.org/addresses/',
    testnet: 'https://testnet.alephium.org/addresses/'
  };
  const LABELS = {
    en: {
      sdk: 'SDK',
      network: 'Network',
      contracts: 'Contracts',
      all: 'All addresses',
      allNetworks: 'mainnet · testnet · devnet',
      devnet: 'Local deployment (addresses vary per devnet)'
    },
    zh: {
      sdk: 'SDK 版本',
      network: '网络',
      contracts: '合约',
      all: '全部地址',
      allNetworks: 'mainnet · testnet · devnet',
      devnet: '本地部署（每个 devnet 的地址不同）'
    },
    fr: {
      sdk: 'SDK',
      network: 'Réseau',
      contracts: 'Contrats',
      all: 'Toutes les adresses',
      allNetworks: 'mainnet · testnet · devnet',
      devnet: 'Déploiement local (adresses propres à chaque devnet)'
    }
  };
  const t = LABELS[lang] ?? LABELS.en;
  const contractsPage = lang === 'en' ? '/reference/contracts' : `/${lang}/reference/contracts`;
  const short = a => `${a.slice(0, 6)}…${a.slice(-4)}`;
  const entries = [];
  const addrs = ADDRESSES[network];
  if (addrs) {
    for (const p of products) {
      for (const [name, address] of Object.entries(addrs[p] ?? ({}))) entries.push({
        name,
        address
      });
    }
  }
  let contractsCell;
  if (network === 'devnet' && products.length > 0) {
    contractsCell = <span>{t.devnet}</span>;
  } else if (entries.length > 0) {
    contractsCell = entries.map(({name, address}, i) => <span key={name}>
        {i > 0 && <span className="mx-1 opacity-50">·</span>}
        {name}{' '}
        <a href={EXPLORERS[network] + address} target="_blank" rel="noreferrer" title={address}>
          <code>{short(address)}</code>
        </a>
      </span>);
  }
  const row = (label, value) => <div className="flex flex-wrap gap-x-2">
      <span className="font-semibold min-w-[5.5rem]">{label}</span>
      <span className="flex-1 min-w-0 break-words">{value}</span>
    </div>;
  return <div className="not-prose mb-6 rounded-xl border border-zinc-950/10 dark:border-white/10 bg-zinc-50 dark:bg-white/5 px-4 py-3 text-sm leading-6 text-zinc-700 dark:text-zinc-300">
      {row(t.sdk, <code>@alephium/powfi-sdk@{SDK_VERSION}</code>)}
      {row(t.network, network === 'all' ? t.allNetworks : network)}
      {contractsCell && row(t.contracts, <span>
            {contractsCell}
            <span className="mx-1 opacity-50">·</span>
            <a href={contractsPage}>{t.all} →</a>
          </span>)}
    </div>;
};

<VersionBanner network="testnet" products={['cpmm']} lang="zh" />

<Note>
  本指南使用 **testnet**，第一笔兑换不会花费真实资产。从水龙头领取免费的测试网 ALPH：

  ```bash theme={null}
  curl -X POST -d '<你的地址>' https://faucet.testnet.alephium.org/send
  ```

  正式使用时，把 `networkId` 改为 `'mainnet'`，并换成在主网上有池子的代币。主网兑换会花费真实资金。
</Note>

<Info>
  需要 Node.js 20+（或 Bun 1.0+）。
</Info>

<Steps>
  <Step title="安装">
    以 ES module 方式新建项目（示例代码使用了顶层 `await`）：

    ```bash theme={null}
    mkdir powfi-quickstart && cd powfi-quickstart
    npm init -y && npm pkg set type=module
    ```

    <CodeGroup>
      ```bash npm theme={null}
      npm install @alephium/powfi-sdk @alephium/web3
      ```

      ```bash pnpm theme={null}
      pnpm add @alephium/powfi-sdk @alephium/web3
      ```

      ```bash bun theme={null}
      bun add @alephium/powfi-sdk @alephium/web3
      ```
    </CodeGroup>

    如果要在后端用私钥签名，还需安装 `@alephium/web3-wallet`。

    把下面各步的代码按顺序写进同一个 `index.ts`，用 `npx tsx index.ts`（或 `bun index.ts`）运行。
  </Step>

  <Step title="加载 SDK（只读）">
    ```ts theme={null}
    import { Powfi } from '@alephium/powfi-sdk'

    const powfi = Powfi.load({ networkId: 'testnet' })
    ```

    读取池和计算报价不需要签名器。`mainnet`、`testnet` 和 `devnet` 的合约地址已打包在 SDK 中。
  </Step>

  <Step title="读取 CPMM 池并获取兑换报价">
    ```ts theme={null}
    import { ALPH_TOKEN_ID } from '@alephium/web3'
    import { CpmmModule, NumericUtils } from '@alephium/powfi-sdk'

    const alph = ALPH_TOKEN_ID
    const baal = (await powfi.token.getTokenBySymbol('BAAL')).id // ALPH/BAAL has a CPMM pool on testnet

    const pool = await powfi.cpmm.getPoolState(alph, baal)

    const quote = CpmmModule.computeSwapAmount({
      state: pool,
      tokenInId: alph,
      tokenOutId: baal,
      amountIn: 10n * 10n ** 18n, // 10 ALPH (18 decimals)
      slippageBps: 50n // 0.5%
    })

    console.log({
      out: NumericUtils.scaleToString(quote.tokenOutAmount, quote.tokenOutInfo.decimals),
      minOut: NumericUtils.scaleToString(quote.minimalTokenOutAmount!, quote.tokenOutInfo.decimals),
      priceImpactPct: quote.priceImpact
    })
    ```

    `computeSwapAmount` 是纯函数：调用一次 `getPoolState` 之后，每次按键都可以重新报价，而无需访问网络。
  </Step>

  <Step title="设置签名器并兑换">
    ```ts theme={null}
    import { PrivateKeyWallet } from '@alephium/web3-wallet'

    const signer = new PrivateKeyWallet({
      privateKey: process.env.PRIVATE_KEY!,
      keyType: 'gl-secp256k1'
    })
    powfi.signer = signer
    const { address } = await signer.getSelectedAccount()

    const result = await powfi.cpmm.swap({
      tokenInId: alph,
      tokenOutId: baal,
      amountIn: 10n * 10n ** 18n,
      slippageBps: 50n,
      sender: address
    })

    console.log('txId', result.txId)
    ```

    在浏览器中，请传入钱包的 `SignerProvider`（例如来自 `@alephium/web3-react`），而不是 `PrivateKeyWallet`。
  </Step>

  <Step title="等待确认">
    ```ts theme={null}
    async function waitForTx(txId: string) {
      for (;;) {
        const status = await powfi.nodeProvider.transactions.getTransactionsStatus({ txId })
        if (status.type === 'Confirmed') return status
        await new Promise((r) => setTimeout(r, 2000))
      }
    }

    await waitForTx(result.txId)
    ```
  </Step>
</Steps>

## 下一步

<CardGroup cols={2}>
  <Card title="TypeScript SDK" icon="code" href="/zh/typescript-sdk">
    SDK 如何初始化、各模块的作用，以及常见陷阱。
  </Card>

  <Card title="在 CLMM 上兑换" icon="chart-area" href="/zh/guides/clmm-swap">
    用模拟得到的流动性曲线报价，再带价格限制执行。
  </Card>

  <Card title="数量与滑点" icon="percent" href="/zh/concepts/amounts-and-slippage">
    bigint 单位、精度，以及基点滑点的计算方式。
  </Card>

  <Card title="质押 ALPH" icon="coins" href="/zh/guides/xalph-staking">
    铸造 xALPH 并管理解除质押请求。
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.