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

# Liquidity & pool utils

> ClmmLiquidityUtils for position math and PoolUtils for position IDs and offline swap simulation.

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

```ts theme={null}
import { ClmmLiquidityUtils, PoolUtils } from '@alephium/powfi-sdk'
```

These are stateless ports of the on-chain math, using Alephium's rounding (`MathUtil.alphDiv`), so results match the contracts to the unit.

## ClmmLiquidityUtils

Conventions: `sqrtRatioX96` is the current price. `sqrtRatioAX96` and `sqrtRatioBX96` are the range bounds (`getSqrtRatioAtTick(tickLower/Upper)`). Amounts are in sorted token0/token1 order.

### `getLiquidityFromAmounts(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1)`

The maximum liquidity mintable from the given amounts:

* price at or below the lower bound → only `amount0` counts
* price inside the range → `min(L from amount0, L from amount1)`
* price above the range → only `amount1` counts

### `getAmountsForLiquidity(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, liquidity)`

`[amount0, amount1]` for a signed liquidity delta. Contract convention: pass `-liquidity` to get the (negated) amounts required to **add** liquidity, and `+liquidity` for amounts received when removing.

### `getAmountsAndLiquidityAtSqrtPrice(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1)`

Returns `[amount0Used, amount1Used, liquidity]`: the balanced amounts actually deposited for the desired `amount0` and `amount1`. This is the usual call for a "you will deposit" preview.

### `getAmountsAndLiquidityAtPrice(price, token0, token1, lowerTick, upperTick, amount0, amount1)`

Same as above, taking a human price and `TokenInfo`s.

### `getPositionAmountsFromPrice(props)`

UI-oriented variant that works in base/quote terms and accepts ticks in any order:

```ts theme={null}
const { newAmountBase, newAmountQuote, liquidity } = ClmmLiquidityUtils.getPositionAmountsFromPrice({
  sqrtRatioX96: state.sqrtPriceX96,
  tokenBaseId: alph,
  tokenQuoteId: usdt,
  lowerTick,
  upperTick,
  amountBase: 100n * 10n ** 18n,
  amountQuote: UNLIMITED_AMOUNT // let the base amount decide
})
```

Returns zeros if either input amount is `0n`. To size a position from one side, pass `UNLIMITED_AMOUNT` (`2^128 − 1`) for the other side.

### Lower-level

| Method | Description |
| - | - |
| `getLiquidityFromToken0(sqrtA, sqrtB, amount0)` | L from token0 only |
| `getLiquidityFromToken1(sqrtA, sqrtB, amount1)` | L from token1 only |
| `getToken0Delta(sqrtA, sqrtB, liquidity)` | Δtoken0 between two prices |
| `getToken1Delta(sqrtA, sqrtB, liquidity)` | Δtoken1 between two prices |
| `getAmountDelta(sqrtA, sqrtB, liquidity, zeroForOne)` | Dispatches to the above |

## PoolUtils

### `getPositionId(poolAddress, owner, tickLower, tickUpper)`

Derives the position contract ID from the pool **address**. Unlike `clmm.getPositionId`, it normalizes groupless `owner` addresses for you.

### `offlineSwap`

```ts theme={null}
static offlineSwap(liqDist: ClmmSimulateSwapQuote, amountSpecified: bigint, sqrtPriceX96: bigint): bigint
```

Replays a swap locally over the liquidity curve returned by [`clmm.simulateSwap`](/modules/clmm#simulateswap-params), and returns the other side's amount as a **signed** value:

* **exact-in** (`amountSpecified > 0`): returns the output as a **negative** number (`-offlineSwap(...)` is what you receive)
* **exact-out** (`amountSpecified < 0`): returns the input required (take the absolute value)

```ts theme={null}
const quote = await powfi.clmm.simulateSwap({ configIndex, token0, token1, zeroForOne: true, amount: amountIn })
const out = -PoolUtils.offlineSwap(quote, amountIn, quote.sqrtPriceX96)
```

The integration tests check that this matches the pool's on-chain `simulateSwap` return value exactly.

### `computeSwapStep(sqrtPriceX96, sqrtPriceTargetX96, liquidity, amount, feePips)`

A single swap step within one liquidity range. Returns `[sqrtPriceNextX96, amountIn, amountOut, feeAmount]`. `offlineSwap` calls this once per row.


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