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

# TypeScript SDK

> @alephium/powfi-sdk: installation, initialization, module facades, transaction results, and common pitfalls.

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', 'clmm', 'staking']} lang="en" />

<Info>
  This page targets `@alephium/powfi-sdk@1.0.2`. Pin exact versions in production and read the release notes before upgrading.
</Info>

## Install

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

Toolchain requirements:

* **Node.js 20+** or **Bun 1.0+** (declared in `engines`).
* **TypeScript 5.x**. The package ships CommonJS (`lib/index.js`), ESM (`lib/index.mjs`), and type declarations (`lib/index.d.ts`).
* Native `bigint` support. All on-chain amounts are `bigint`.

`@alephium/web3` is a **peer dependency** (`^3.0.3`): install it yourself, as in the command above, so the SDK and your app share one copy. Pulled in automatically: `@alephium/token-list`, `bignumber.js`, `decimal.js`.

## Initialize

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

const powfi = Powfi.load({
  networkId: 'mainnet', // 'mainnet' | 'testnet' | 'devnet'
  signer, // optional: any @alephium/web3 SignerProvider
  networkOverrides: {
    // optional: override any field of the built-in network config
    nodeUrl: 'https://my-node.example.com',
    nodeApiKey: process.env.NODE_API_KEY
  }
})
```

`Powfi.load` is **synchronous**. It:

1. Resolves the network from the built-in list (`mainnet`, `testnet`, `devnet`) and applies `networkOverrides`.
2. Creates a `NodeProvider` and an `ExplorerProvider` for that network.
3. Instantiates every module and loads its contract IDs from the deployment files bundled in the package.
4. Registers its providers as the global `@alephium/web3` defaults (`setCurrentProviders()`), so generated contract helpers work right away.

It does **not** make any network calls. The token list is fetched lazily on first use and cached for one day.

<Tip>
  Many generated contract helpers from `@alephium/web3` use the *global* node provider. `Powfi.load` sets it for you, and the most recent `load` wins. If you run several SDK instances, call `powfi.setCurrentProviders()` to make a given instance's providers global again.
</Tip>

See [Networks & configuration](/concepts/networks) for the default endpoints and how to point at your own node.

## The module facades

```ts theme={null}
powfi.cpmm    // CpmmModule: constant-product pools. Pool state, quotes, swap, add/remove liquidity, create pool
powfi.clmm    // ClmmModule: concentrated liquidity. Fee tiers, pool state, simulateSwap, swap, positions, rewards
powfi.staking // StakingModule: xALPH liquid staking. Stake, unstake, claim, fee-collector vaults
powfi.token   // TokenModule: token metadata from the Alephium token list (cached)
```

Stateless helpers are exported alongside the modules:

```ts theme={null}
import {
  CpmmModule,          // static quote helpers: computeSwapAmount, computeLiquidityAmounts, ...
  TickUtils,           // tick <-> sqrtPriceX96 <-> price
  ClmmLiquidityUtils,  // liquidity <-> token amounts
  PoolUtils,           // position IDs, offline swap simulation
  MathUtil,            // bigint math (sqrt, mulDiv with rounding)
  NumericUtils,        // bigint/Decimal/string conversion and decimal scaling
  sortTokens,          // canonical token ordering used for pool IDs
} from '@alephium/powfi-sdk'
```

Every module extends `ModuleBase`, which gives it access to the parent `Powfi` instance (`scope`: providers, signer, network) and a named logger. See [Logging](/utilities/math#logging) to turn on debug output.

## Transaction results

Write methods sign **and submit** the transaction through `powfi.signer`. They return the `@alephium/web3` result type of the underlying call:

| Method style | Return type | Key fields |
| - | - | - |
| Script execution (CPMM swap/liquidity, CLMM `createPool`, staking fee ops) | `ExecuteScriptResult` | `txId`, `unsignedTx`, `signature`, `gasAmount`, `gasPrice` |
| Contract method call (CLMM swap/positions, staking) | `SignExecuteScriptTxResult` | same fields as above |
| Methods that create something | `{ poolId, result }` or `{ positionId, result }` | the derived ID plus the tx result |

```ts theme={null}
const { positionId, result } = await powfi.clmm.addLiquidity({ /* ... */ })
console.log(positionId, result.txId)
```

The SDK does **not** wait for confirmation. Poll `powfi.nodeProvider.transactions.getTransactionsStatus({ txId })` until `type === 'Confirmed'` (see step 5 of the [Quickstart](/quickstart)).

<Note>
  There is no "build only" mode for most methods. The exception is CLMM add-liquidity: `getAddLiquidityParams` returns the prepared call parameters, and `addLiquidityFromParams` executes them. For everything else, if you need an unsigned transaction, call the underlying script's or contract's `.execute` / `.transact` with a custom `SignerProvider` that captures the request instead of submitting it.
</Note>

## Common pitfalls

<AccordionGroup>
  <Accordion title="1. Network mismatch">
    Contract IDs come from the deployment file for `networkId`. A mainnet signer with `networkId: 'testnet'` (or the reverse) builds transactions against contracts that don't exist on the signer's network. Always derive `networkId` from the same place as your wallet's network.
  </Accordion>

  <Accordion title="2. Token ordering">
    Pools are keyed by the **lexicographically sorted** pair (`token0 < token1`). Getters such as `getPoolId(tokenA, tokenB)` sort for you. Reserves, prices, and `sqrtPriceX96` are always expressed in sorted order (price = token1 per token0). Use `sortTokens(a, b)` whenever you map UI "base/quote" onto pool fields.
  </Accordion>

  <Accordion title="3. CLMM swap uses token0/token1 for direction, not pool order">
    In `ClmmSwapRequest`, `token0` is the **input** token and `token1` is the **output** token. In `ClmmSimulateSwapParams`, the direction is set by `zeroForOne` instead. See [Swap on CLMM](/guides/clmm-swap).
  </Accordion>

  <Accordion title="4. Stale state">
    Quotes computed from a `CpmmPoolContractState` or a `ClmmSimulateSwapQuote` go stale as soon as another trade lands. `cpmm.swap` re-fetches state before sending. For CLMM, re-run `simulateSwap` right before submitting, and always set a non-zero slippage.
  </Accordion>

  <Accordion title="5. Slippage is in basis points, and applied differently per pool type">
    `slippageBps: 50n` means 0.5%. CPMM applies it to **amounts** (`minimalAmount` / `maximalAmount`). CLMM applies it to the **price** (a `sqrtPriceLimitX96` bound). See [Amounts & slippage](/concepts/amounts-and-slippage).
  </Accordion>

  <Accordion title="6. Groupless addresses">
    Alephium groupless addresses (no `:group` suffix) are normalized to the protocol group internally for owner/recipient arguments. When you derive IDs yourself (for example `clmm.getPositionId`), pass the normalized form: `normalizeAddress(address, powfi.clmm.getClmmConfig().groupIndex)`.
  </Accordion>

  <Accordion title="7. CPMM price impact cap">
    `cpmm.swap` throws `PriceImpactTooHighError` when the quote's price impact is **≥ 5%** (`MAX_PRICE_IMPACT`). Split the trade or use `swapTo` (which skips the check) if you really mean it.
  </Accordion>
</AccordionGroup>

## Versioning policy

* Stable releases are published on npm as `@alephium/powfi-sdk` under the `latest` tag. Release candidates use the `rc` tag.
* Contract bindings (`clmm/`, `cpmm/`, `staking/`) are regenerated from the contracts repository and **bundled in the package**. A contract upgrade that changes addresses or ABIs ships as a new SDK version.
* Pin exact versions and read the release notes before upgrading.

## Upgrading

1. Read the release notes on GitHub.
2. Bump `@alephium/powfi-sdk` and make sure your `@alephium/web3` satisfies the SDK's peer dependency (`^3.0.3` today) and that only one copy is installed (`npm ls @alephium/web3`). Duplicate `@alephium/web3` copies cause `instanceof` and provider-registration bugs.
3. Run `tsc --noEmit`. Most breaking changes surface as type errors.
4. Re-run your quote tests against testnet before switching mainnet traffic.

## Getting help

* **Bugs and feature requests:** [GitHub issues](https://github.com/alephium/powfi-sdk/issues).
* **Security issues:** do not open a public issue. Contact the Powfi team privately.

## Pointers

* [Module reference: CPMM](/modules/cpmm) · [CLMM](/modules/clmm) · [Staking](/modules/staking) · [Token](/modules/token)
* [Contract artifacts & deployments](/reference/contracts)
* [Developer CLI](/reference/cli)
* Source: [github.com/alephium/powfi-sdk](https://github.com/alephium/powfi-sdk)


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