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

# TickUtils

> Convert between ticks, sqrtPriceX96, and human-readable prices for CLMM pools.

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 { TickUtils } from '@alephium/powfi-sdk'
```

CLMM prices live in three representations:

| Representation | Type | Example | Used by |
| - | - | - | - |
| Human price | `number` / `Decimal` | `0.25` (token1 per token0, decimal-adjusted) | UIs |
| `sqrtPriceX96` | `bigint` | `sqrt(rawPrice) × 2^96` | pool state, swap limits |
| Tick | `bigint` | `price = 1.0001^tick` | position ranges |

All raw prices are **token1 per token0** in sorted order. The base/quote helpers below handle UI pairs in either orientation.

## Tick ↔ sqrtPriceX96

### `getSqrtRatioAtTick(tick)`

```ts theme={null}
static getSqrtRatioAtTick(tick: bigint): bigint
```

Exact port of the on-chain tick math. Throws `TickOutOfBounds` if `|tick| > MAX_TICK` (887272).

### `getTickAtSqrtRatio(sqrtPriceX96)`

```ts theme={null}
static getTickAtSqrtRatio(sqrtPriceX96: bigint): bigint
```

The greatest tick whose sqrt ratio is ≤ the input. Throws `SqrtPriceX96OutOfBounds` outside `[MIN_SQRT_RATIO, MAX_SQRT_RATIO)`.

## Price ↔ sqrtPriceX96

### `priceToSqrtPriceX96(price, token0Decimals, token1Decimals)`

```ts theme={null}
static priceToSqrtPriceX96(price: Decimal.Value, token0Decimal: number, token1Decimal: number): bigint
```

`price` is the human price of token0 in token1. Throws on non-finite or non-positive prices.

### `sqrtPriceX96ToPrice(sqrtPriceX96, token0Decimals, token1Decimals)`

```ts theme={null}
static sqrtPriceX96ToPrice(sqrtPriceX96: bigint, token0Decimal: number, token1Decimal: number): number
```

```ts theme={null}
const state = await powfi.clmm.getPoolState(poolId)
const price = TickUtils.sqrtPriceX96ToPrice(state.sqrtPriceX96, state.token0Info.decimals, state.token1Info.decimals)
// price of 1 token0 in token1
```

## Aligning to tick spacing

Position bounds must be multiples of the fee tier's `tickSpacing`.

### `getAlignedTick(price, token0Decimals, token1Decimals, tickSpacing)`

Converts a human price to the nearest valid tick (rounded up to a multiple of `tickSpacing`).

```ts theme={null}
const { tickSpacing } = (await powfi.clmm.getPoolConfig(configIndex))!
const tickLower = TickUtils.getAlignedTick(0.2, d0, d1, tickSpacing)
const tickUpper = TickUtils.getAlignedTick(0.3, d0, d1, tickSpacing)
```

## Base/quote helpers for UIs

These take the tokens as the **user sees them** (`tokenBase`, `tokenQuote`) plus `baseIn`, and flip to sorted order internally. With `baseIn = true` the price is quoted as "1 base = X quote".

| Method | Returns | Use |
| - | - | - |
| `getAlignedPrice(price, tokenBase, tokenQuote, tickSpacing, baseIn)` | `{ tick, price }` | Snap a typed price to a valid tick and show the snapped price |
| `getPriceFromTick(tick, tokenBase, tokenQuote, baseIn)` | `{ tick, price }` | Display a range bound |
| `getNextTick(tick, tickSpacing, tokenBase, tokenQuote, baseIn, isAdd)` | `bigint` | `+` / `−` buttons next to a price input |
| `getMinPriceFromTick(tokenBase, tokenQuote, tickSpacing, baseIn)` | `{ tick, price }` | "Full range" lower bound |
| `getMaxPriceFromTick(tokenBase, tokenQuote, tickSpacing, baseIn)` | `{ tick, price }` | "Full range" upper bound |

```ts theme={null}
// user types "1 ALPH = 0.25 USDT" as the lower bound
const lower = TickUtils.getAlignedPrice(0.25, alphInfo, usdtInfo, tickSpacing, true)
// lower.tick -> pass to addLiquidity; lower.price -> show "0.2499…" in the input
```

## Swap math

| Method | Description |
| - | - |
| `getNextSqrtPrice(sqrtPX96, liquidity, amount, zeroForOne)` | Price after swapping `amount` within one liquidity range |
| `getNextSqrtPriceFromAmount0(...)` / `getNextSqrtPriceFromAmount1(...)` | Direction-specific versions |
| `getSqrtPriceX96Bounds(sqrtPriceX96, slippageBps)` | `[min, max]` = `sqrtPrice × sqrt(1 ∓ s)` |
| `getSqrtPriceLimitX96(sqrtPriceX96, slippageBps, zeroForOne)` | The limit passed to swaps. Always strictly past the current price and inside the valid range. |

## Constants

Exported from the package root: `MIN_TICK = -887272n`, `MAX_TICK = 887272n`, `U256_MAX`, `UNLIMITED_AMOUNT`, and `MAX_PIPS`. The package root does **not** export `MIN_SQRT_RATIO` (`4295128739n`), `MAX_SQRT_RATIO`, or `Q96` (`2n ** 96n`). Define them locally if you need them.


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