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

# Staking

> xALPH liquid staking: stake ALPH, unstake with linear unlocking, and the protocol fee-collector vaults.

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

```ts theme={null}
powfi.staking // StakingModule
```

Staking ALPH mints **xALPH**, a liquid token whose value in ALPH grows as protocol rewards are deposited. Unstaking burns xALPH and opens an **unstake vault** that releases the ALPH linearly over `unstakeDuration`.

<Card title="Guide: stake and unstake ALPH" icon="coins" href="/guides/xalph-staking" horizontal />

## Settings

```ts theme={null}
powfi.staking.getSettings()
// { unstakeDuration, maxActiveUnstakeRequestsPerUser }
```

| Network | `unstakeDuration` | `maxActiveUnstakeRequestsPerUser` |
| - | - | - |
| mainnet | 30 days (`2_592_000_000n` ms) | `16n` |
| testnet | 30 days | `16n` |
| devnet | 1 minute (`60_000n` ms) | `16n` |

These values mirror the contract parameters. The live values are in `getXAlphTokenState()` (`fields.unstakeDuration`, `fields.maxActiveUnstakeRequestsPerUser`).

## xALPH token

### `getXAlphTokenState()`

```ts theme={null}
getXAlphTokenState(): Promise<XAlphTokenTypes.State>
```

Useful fields:

| Field | Meaning |
| - | - |
| `totalDepositedAlph` | ALPH backing all xALPH |
| `totalXAlphSupply` | xALPH outstanding |
| `unstakeDuration` | Unlock period in ms (ALPH unlocks linearly over it) |
| `lastUnstakeVaultIndex` | Global counter of unstake vaults |

Exchange rate: **1 xALPH = `totalDepositedAlph / totalXAlphSupply` ALPH**.

```ts theme={null}
const { fields } = await powfi.staking.getXAlphTokenState()
const alphPerXAlph = new Decimal(fields.totalDepositedAlph.toString()).div(fields.totalXAlphSupply.toString())
```

`getXAlphToken()` returns the typed `XAlphTokenInstance`. `getConfig().xAlphTokenId` is the xALPH token ID.

## Stake

### `stakeAlph(amount)`

```ts theme={null}
stakeAlph(amount: bigint): Promise<XAlphTokenTypes.SignExecuteMethodResult<'stake'>>
```

Stakes `amount` attoALPH and mints xALPH to the signer at the current rate. Attaches `amount + MINIMAL_CONTRACT_DEPOSIT` ALPH. The xALPH token contract is recorded as the referral.

### `stakeAlphWithReferral(amount, referral)`

Same as above, with a custom `referral` address. The contract does not validate the referral or send it anything. It only records it in the `Staked(to, referral, alphAmount, xAlphAmount)` event. Partners who want commission on referred stakes must [contact the team first](/guides/referral-staking).

### `donateReward(amount)`

Deposits `amount` ALPH as a reward to all xALPH holders **without minting xALPH**, which raises the exchange rate.

## Unstake

Unstaking unlocks linearly. After `startUnstake`, the claimable ALPH grows with elapsed time, and the full amount is available after `unstakeDuration`. Call `claimUnstaked` at any time to withdraw what has unlocked so far.

### `startUnstake(amount)`

```ts theme={null}
startUnstake(amount: bigint): Promise<XAlphTokenTypes.SignExecuteMethodResult<'startUnstake'>>
```

Burns `amount` xALPH and creates a new unstake vault for the signer, holding the equivalent ALPH. Each user can hold at most `maxActiveUnstakeRequestsPerUser` active vaults.

### `getActiveUnstakeVaultIndexes(address)`

Returns `bigint[]` with the vault indexes of the user's pending or claimable requests.

### `getAlphUnstakeVaultState(address, vaultIndex)`

```ts theme={null}
// fields: { unstakerAddress, totalUnstakeAmount, unstakeStartTime, unstakeDuration, withdrawnAmount, xalphToken }
```

Claimable ALPH is `totalUnstakeAmount × min(elapsed, unstakeDuration) / unstakeDuration − withdrawnAmount`, so a request is fully unlocked at `unstakeStartTime + unstakeDuration`. `getAlphUnstakeVault(address, vaultIndex)` returns the typed contract instance.

### `getClaimableAmount(address, vaultIndex)`

ALPH currently claimable from a vault. It grows linearly from `0n` when the request starts.

### `claimUnstaked(vaultIndex, amount)`

Withdraws `amount` ALPH from the vault to the signer. `amount` must be greater than 0 and at most the claimable amount.

### `cancelUnstake(vaultIndex)`

Closes a request. ALPH that has already unlocked is sent to the signer, and the rest is re-staked and returned as xALPH at the current rate. The `UnstakeCancelled` event reports `xAlphAmount`, `claimedAlphAmount`, and `restakedAlphAmount`.

## How rewards reach xALPH

Protocol fees from CPMM and CLMM pools flow into the `RewardFeeCollector`. The Powfi team collects them and converts them to ALPH. Then `distributeRewards` pays out `totalDepositedAlph × rewardRate / 10000 × elapsed / 1 year` (an annual rate), capped by the ALPH the collector holds. The treasury share is taken first, a burn share is taken from what remains, and the rest is deposited into xALPH, which raises the exchange rate.

`distributeRewards` is not restricted, and nothing calls it automatically. Apart from `donateReward`, which raises the rate immediately, the xALPH rate only rises when someone calls it.

| Method | Description |
| - | - |
| `distributeRewards(contractId)` | Distribute pending rewards. Pass `getConfig().feeCollectorId`. |
| `getVault(token)` / `getDistributorVaultId(token)` | Fee collector's vault for a token (for CPMM, key by LP token ID = pool ID) |
| `getVaultState(token)` | `{ address, id, state, balances }` |

## Other accessors

| Method | Returns |
| - | - |
| `getConfig()` / `setConfig(config)` | `StakingConfig` |
| `getRewardFeeCollector(contractId)` | `RewardFeeCollectorInstance` |

```ts theme={null}
interface StakingConfig {
  groupIndex: number
  alphUnstakeVaultTemplateId: string
  xAlphTokenId: string
  xAlphTokenAddress: string
  feeCollectorId: string
}
```

## Helpers

`decodeU256List(hex)` and `decodeContractIdList(hex)` decode the packed byte-vector returns used by the staking contracts (32-byte chunks).


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