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

# CPMM

> Constant-product (x·y=k) pools: pool state, quotes, swaps, liquidity, and pool creation.

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="mainnet" products={['cpmm']} lang="en" />

```ts theme={null}
powfi.cpmm              // CpmmModule instance (network-bound)
import { CpmmModule } from '@alephium/powfi-sdk' // static quote helpers
```

CPMM pools hold two tokens and price them by the constant-product invariant `reserve0 × reserve1 = k`. Each swap pays a **0.3%** fee to liquidity providers. Liquidity is represented by a fungible **LP token whose token ID equals the pool ID**.

<CardGroup cols={2}>
  <Card title="Guide: swap on CPMM" icon="arrow-right-arrow-left" href="/guides/cpmm-swap" />

  <Card title="Guide: provide CPMM liquidity" icon="droplet" href="/guides/cpmm-liquidity" />
</CardGroup>

## Pool lookups

### `getPoolId(tokenA, tokenB)`

```ts theme={null}
getPoolId(tokenA: string, tokenB: string): string
```

Derives the pair's contract ID offline (tokens are sorted first, so the order doesn't matter). This is also the **LP token ID**.

### `getPoolAddress(tokenA, tokenB)`

Returns the pair's contract address (`addressFromContractId(getPoolId(...))`).

### `poolExists(tokenA, tokenB)`

```ts theme={null}
poolExists(tokenA: string, tokenB: string): Promise<boolean>
```

### `getPoolState(tokenA, tokenB)`

```ts theme={null}
getPoolState(tokenA: string, tokenB: string): Promise<CpmmPoolContractState>
```

Fetches reserves and LP supply, and resolves both tokens through the token list. Throws `PoolNotFoundError` if the pair doesn't exist. Both tokens must be in the token list.

<ResponseField name="CpmmPoolContractState" type="object">
  <Expandable title="fields" defaultOpen>
    <ResponseField name="poolId" type="string">Pair contract ID (= LP token ID).</ResponseField>
    <ResponseField name="reserve0" type="bigint">Reserve of `token0` (sorted order).</ResponseField>
    <ResponseField name="reserve1" type="bigint">Reserve of `token1`.</ResponseField>
    <ResponseField name="token0Info" type="TokenInfo">Metadata of the lexicographically smaller token ID.</ResponseField>
    <ResponseField name="token1Info" type="TokenInfo">Metadata of the larger token ID.</ResponseField>
    <ResponseField name="totalSupply" type="bigint">Total LP tokens outstanding.</ResponseField>
    <ResponseField name="dexRoot" type="string">DEX root contract ID recorded in the pair.</ResponseField>
  </Expandable>
</ResponseField>

### `getPoolProtocolFees(poolAddress)`

```ts theme={null}
getPoolProtocolFees(poolAddress: string): Promise<bigint>
```

Protocol fees accrued in the pair and not yet collected. Takes the pool **address**, not token IDs.

## Quotes (static, offline)

All quote helpers are **static** and pure. Pass a `CpmmPoolContractState` you already fetched.

### `CpmmModule.computeSwapAmount(params)`

```ts theme={null}
static computeSwapAmount(params: CpmmSwapQuoteParams): CpmmSwapQuote
```

<ParamField path="state" type="CpmmPoolContractState" required />

<ParamField path="tokenInId" type="string" required />

<ParamField path="tokenOutId" type="string" required />

<ParamField path="amountIn" type="bigint">Set for an **exact-in** quote.</ParamField>
<ParamField path="amountOut" type="bigint">Set for an **exact-out** quote (used only when `amountIn` is undefined).</ParamField>
<ParamField path="slippageBps" type="bigint" required>Slippage tolerance in basis points.</ParamField>

<ResponseField name="CpmmSwapQuote" type="object">
  <Expandable title="fields" defaultOpen>
    <ResponseField name="swapType" type="'ExactIn' | 'ExactOut'" />

    <ResponseField name="tokenInInfo / tokenOutInfo" type="TokenInfo" />

    <ResponseField name="tokenInAmount" type="bigint">Input amount (given, or computed for exact-out).</ResponseField>
    <ResponseField name="tokenOutAmount" type="bigint">Output amount (computed, or given for exact-out).</ResponseField>
    <ResponseField name="minimalTokenOutAmount" type="bigint | undefined">Exact-in only: output after slippage.</ResponseField>
    <ResponseField name="maximalTokenInAmount" type="bigint | undefined">Exact-out only: input after slippage.</ResponseField>
    <ResponseField name="priceImpact" type="number">Percent, for example `0.42` = 0.42%.</ResponseField>
    <ResponseField name="state" type="CpmmPoolContractState">The state the quote was computed from.</ResponseField>
  </Expandable>
</ResponseField>

Throws `InsufficientLiquidityError` for exact-out when `amountOut >= reserveOut`.

### `CpmmModule.getAmountOut(state, tokenInId, amountIn)` / `getAmountIn(state, tokenOutId, amountOut)`

The raw x·y=k formulas with the 0.3% fee:

```ts theme={null}
amountOut = (amountIn * 997 * reserveOut) / (reserveIn * 1000 + amountIn * 997)
amountIn  = (reserveIn * amountOut * 1000) / ((reserveOut - amountOut) * 997) + 1
```

### `CpmmModule.calcPriceImpact(reserve0, reserve1, tokenInId, token0Id, amountIn, amountOut)`

Returns the price impact in percent.

### `CpmmModule.computeLiquidityAmounts(params)`

```ts theme={null}
static computeLiquidityAmounts(params: CpmmAddLiquidityQuoteParams): CpmmAddLiquidityQuote
```

* **Existing pool** (`poolState` set): give the amount of one side (`inputType: 'TokenA'` uses `amountA`, `'TokenB'` uses `amountB`) and it derives the other side from the reserves, plus the LP tokens you'd mint.
* **New pool** (`poolState` undefined): both `amountA` and `amountB` are required. LP minted = `sqrt(amountA × amountB) − MINIMUM_LIQUIDITY` (1000 units are locked forever). Throws `InsufficientLiquidityError` if `sqrt(amountA × amountB) <= 1000`.

Returns `{ tokenAId, tokenBId, amountA, amountB, shareAmount, sharePercentage, state? }`, where `sharePercentage` is your share of the pool after the deposit, in percent.

### `CpmmModule.computeRemoveLiquidityAmounts(state, totalLiquidity, liquidityToRemove)`

Token amounts returned for burning `liquidityToRemove` LP tokens, plus your remaining share. `totalLiquidity` is **your** LP balance. Throws if `liquidityToRemove > totalLiquidity`.

### `CpmmModule.computeClaimableAmounts(state, liquidityBalance)`

The full underlying value of an LP balance: `{ token0, amount0, token1, amount1, ... }`.

### `CpmmModule.minimalAmount(amount, slippage)` / `maximalAmount(amount, slippage)`

Slippage helpers. See [Amounts & slippage](/concepts/amounts-and-slippage#cpmm-slippage-on-amounts).

## Swaps

### `swap(params, balances?)`

```ts theme={null}
swap(params: CpmmSwapRequest, balances?: Map<string, bigint>): Promise<ExecuteScriptResult>
```

Fetches fresh pool state, quotes, checks price impact, and executes `SwapMinOut` (exact-in) or `SwapMaxIn` (exact-out) through the router. Requires a signer.

<ParamField path="tokenInId" type="string" required />

<ParamField path="tokenOutId" type="string" required />

<ParamField path="amountIn" type="bigint">Exact-in amount.</ParamField>
<ParamField path="amountOut" type="bigint">Exact-out amount (used when `amountIn` is undefined).</ParamField>
<ParamField path="slippageBps" type="bigint" required>Basis points.</ParamField>
<ParamField path="sender" type="string" required>Address that pays and receives. Usually the signer's address.</ParamField>
<ParamField path="ttlMinutes" type="number" default="60">Deadline.</ParamField>
<ParamField path="fee" type="bigint">Optional [integrator fee](/guides/integrator-fees), in the input token.</ParamField>
<ParamField path="feeRecipient" type="string">Required together with `fee`.</ParamField>

<ParamField path="balances" type="Map<tokenId, bigint>">
  Optional pre-flight check: if provided and `balances.get(tokenIn) < input + fee`, throws `InsufficientBalanceError` before signing. For ALPH, key the map by `ALPH_TOKEN_ID`.
</ParamField>

Throws `PriceImpactTooHighError` if `priceImpact >= 5`.

### `simSwap(params)`

```ts theme={null}
simSwap(params: CpmmSwapRequest): Promise<CpmmSwapQuote>
```

Fetches pool state and returns the quote `swap` would use, without sending anything. `slippageBps` defaults to `100n` if nullish.

### `swapTo(params)`

```ts theme={null}
swapTo(params: {
  tokenA: string
  tokenB: string
  targetPrice: number | BigNumber // human price: token1 per token0 (sorted order)
  sender: string
  slippageBps?: bigint            // default 50n
}): Promise<ExecuteScriptResult>
```

Computes the exact-in trade that moves the pool price to `targetPrice` and executes it. Direction is inferred automatically. **Skips the price-impact check.** Throws if the target equals the current price. Useful for arbitrage and for re-pegging test pools.

## Liquidity

### `addLiquidity(params, balances?)`

```ts theme={null}
addLiquidity(params: CpmmAddLiquidityRequest, balances?: Map<string, bigint>): Promise<ExecuteScriptResult>
```

<ParamField path="poolState" type="CpmmPoolContractState" required>Fresh state from `getPoolState`.</ParamField>
<ParamField path="tokenAId / tokenBId" type="string" required>Must both be pool tokens (any order).</ParamField>
<ParamField path="amountA / amountB" type="bigint" required>Desired amounts. Both must be greater than 0. Use `computeLiquidityAmounts` to get a balanced pair.</ParamField>
<ParamField path="slippageBps" type="bigint" required>Applied to both amounts as minimums. Ignored when the pool is empty.</ParamField>

<ParamField path="sender" type="string" required />

<ParamField path="ttlMinutes" type="number" default="60" />

The router deposits the optimal ratio and mints LP tokens to `sender`.

### `removeLiquidity(params)`

```ts theme={null}
removeLiquidity(params: CpmmRemoveLiquidityRequest): Promise<ExecuteScriptResult>
```

<ParamField path="poolState" type="CpmmPoolContractState" required />

<ParamField path="liquidity" type="bigint" required>LP tokens to burn.</ParamField>
<ParamField path="totalLiquidityAmount" type="bigint">Your LP balance (used for share math). Defaults to `poolState.totalSupply`.</ParamField>
<ParamField path="slippageBps" type="bigint" required>Applied to both output amounts as minimums.</ParamField>

<ParamField path="sender" type="string" required />

<ParamField path="ttlMinutes" type="number" default="60" />

### `computeClaimableAmounts(tokenAId, tokenBId, liquidityBalance)`

Instance version: fetches pool state, then returns `{ token0, amount0, token1, amount1 }` for an LP balance.

## Pool creation

### `createPool(params)`

```ts theme={null}
createPool(params: CpmmCreatePoolRequest): Promise<{ poolId: string; result: ExecuteScriptResult }>
```

<ParamField path="tokenAId / tokenBId" type="string" required />

<ParamField path="sender" type="string" required>Pays the 1 ALPH contract deposit.</ParamField>

<ParamField path="initialLiquidity" type="{ tokenAAmount: bigint; tokenBAmount: bigint }">
  If set, creates the pair and deposits initial liquidity in one transaction (`CreatePairAndAddLiquidity`). The ratio sets the starting price. If omitted, only the pair is created (`CreatePair`, which attaches 1 base unit of each token).
</ParamField>

## Configuration

`getConfig()` returns the active `CpmmConfig` (`groupIndex`, `factoryId`, `routerId`). `setConfig(config)` overrides it. `getCpmmConfig()` re-reads the bundled deployment.

## Constants

| Name | Value | Meaning |
| - | - | - |
| `MAX_PRICE_IMPACT` | `5` | Percent. `swap` rejects quotes at or above this. |
| `MINIMUM_LIQUIDITY` | `1000n` | LP units locked on the first deposit. |
| `BPS` | `10_000n` | Basis-point denominator. |


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