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

> Conversion entre ticks, sqrtPriceX96 et prix lisibles pour les pools CLMM.

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="fr" />

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

Les prix CLMM existent sous trois représentations :

| Représentation | Type | Exemple | Utilisée par |
| - | - | - | - |
| Prix lisible | `number` / `Decimal` | `0.25` (token1 par token0, ajusté des décimales) | Interfaces |
| `sqrtPriceX96` | `bigint` | `sqrt(prixBrut) × 2^96` | état du pool, limites de swap |
| Tick | `bigint` | `prix = 1.0001^tick` | plages de positions |

Tous les prix bruts sont exprimés en **token1 par token0** dans l'ordre trié. Les helpers base/cotation ci-dessous gèrent les paires d'interface dans les deux sens.

## Tick ↔ sqrtPriceX96

### `getSqrtRatioAtTick(tick)`

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

Portage exact des calculs de ticks on-chain. Lève `TickOutOfBounds` si `|tick| > MAX_TICK` (887272).

### `getTickAtSqrtRatio(sqrtPriceX96)`

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

Le plus grand tick dont le ratio en racine carrée est ≤ à l'entrée. Lève `SqrtPriceX96OutOfBounds` hors de `[MIN_SQRT_RATIO, MAX_SQRT_RATIO)`.

## Prix ↔ sqrtPriceX96

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

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

`price` est le prix lisible du token0 exprimé en token1. Lève une erreur si le prix n'est pas fini ou pas strictement positif.

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

## Alignement sur l'espacement des ticks

Les bornes de position doivent être des multiples du `tickSpacing` du palier de frais.

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

Convertit un prix lisible en tick valide le plus proche (arrondi au multiple de `tickSpacing` supérieur).

```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)
```

## Helpers base/cotation pour les interfaces

Ces fonctions prennent les jetons **tels que l'utilisateur les voit** (`tokenBase`, `tokenQuote`) ainsi que `baseIn`, et passent à l'ordre trié en interne. Avec `baseIn = true`, le prix s'exprime comme « 1 base = X cotation ».

| Méthode | Renvoie | Usage |
| - | - | - |
| `getAlignedPrice(price, tokenBase, tokenQuote, tickSpacing, baseIn)` | `{ tick, price }` | Aligner un prix saisi sur un tick valide et afficher le prix aligné |
| `getPriceFromTick(tick, tokenBase, tokenQuote, baseIn)` | `{ tick, price }` | Afficher une borne de plage |
| `getNextTick(tick, tickSpacing, tokenBase, tokenQuote, baseIn, isAdd)` | `bigint` | Boutons `+` / `−` à côté d'un champ de prix |
| `getMinPriceFromTick(tokenBase, tokenQuote, tickSpacing, baseIn)` | `{ tick, price }` | Borne inférieure « plage complète » |
| `getMaxPriceFromTick(tokenBase, tokenQuote, tickSpacing, baseIn)` | `{ tick, price }` | Borne supérieure « plage complète » |

```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
```

## Calculs de swap

| Méthode | Description |
| - | - |
| `getNextSqrtPrice(sqrtPX96, liquidity, amount, zeroForOne)` | Prix après un swap de `amount` dans une plage de liquidité |
| `getNextSqrtPriceFromAmount0(...)` / `getNextSqrtPriceFromAmount1(...)` | Versions spécifiques à chaque direction |
| `getSqrtPriceX96Bounds(sqrtPriceX96, slippageBps)` | `[min, max]` = `sqrtPrice × sqrt(1 ∓ s)` |
| `getSqrtPriceLimitX96(sqrtPriceX96, slippageBps, zeroForOne)` | La limite passée aux swaps. Toujours strictement au-delà du prix actuel et dans la plage valide. |

## Constantes

Exportées depuis la racine du package : `MIN_TICK = -887272n`, `MAX_TICK = 887272n`, `U256_MAX`, `UNLIMITED_AMOUNT` et `MAX_PIPS`. La racine du package n'exporte **pas** `MIN_SQRT_RATIO` (`4295128739n`), `MAX_SQRT_RATIO` ni `Q96` (`2n ** 96n`). Définissez-les localement si vous en avez besoin.


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