> ## Documentation Index
> Fetch the complete documentation index at: https://shield.fi/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Minting a position

> Open a liquidity position in a Shield Swap pool, in the app or with the Typescript SDK, Python SDK, or CLI.

Developers
Web App

This page helps you open a liquidity position, called minting, in the Shield Swap app or with the Typescript SDK, Python SDK, or CLI.

## Your deposit and withdrawal address

Your chosen range and the current pool price determine how much of each deposited asset becomes liquidity. Any amount the range does not use stays with the position until you [collect it](https://shield.fi/docs/liquidity/collecting-and-burning.md). If you deposit 100 units of an asset and the range uses 80, the remaining 20 are position funds you can collect. Those unused funds do not earn trading fees.

Choose who manages the position and where its payouts go before you mint. The recipient address owns the position and can manage its liquidity. The withdrawal address receives every payout and is fixed for the life of the position, including after a rebalance. Both default to your connected wallet.

The pool, the range, the liquidity, and the amounts in a position are public. Who owns the position is confidential. See [Public data](https://shield.fi/docs/confidentiality/public-data.md).

## In the app

**Before you start**

You'll need:

* Shield Wallet connected to Shield Swap, with a confidential balance of at least one of the pool's two assets. See [Fund](https://shield.fi/docs/trading/fund-and-bridge.md#web-app).
* A range in mind. See [Choosing a liquidity range](https://shield.fi/docs/liquidity/choosing-a-range.md).

### Open the position

1. Open **Pools**, then select the pool.
2. In the panel on the right, keep **New Position** selected.
3. Enter an amount for either asset. The app fills in the other amount for the current price and range. **Private Balance** above each field shows what you can deposit.
4. Keep **Full Range**, or select **Custom** and choose a range. A custom range changes the second amount.
5. Open **Advanced Addresses** and check **Recipient address** and **Withdrawal address**.

> [!WARNING]
>
> **Check the withdrawal address before you continue.** Every payout from this position goes to that address, and it cannot be changed after the position is created.

6. Select **Add Liquidity**.
7. In **Review deposit**, check both deposit amounts, the **Selected price range** with its lower, current, and upper prices, and both addresses. Select **Confirm**.
8. In the **Transaction request** in Shield Wallet, check that the request is from swap.shield.fi and that the amounts match, then select **Confirm**. The network fee shows **Covered by Shield**.

The app shows **Adding liquidity** with a progress circle, then **Liquidity added** with the transaction marked **Confirmed**. Select **Done**. The position appears under **Your Positions** with its status, amounts, **Position Funds**, and range, and **Recent Activity** lists a **Mint** row for it.

### Troubleshooting

| What you see | Why it happens | What to do |
| - | - | - |
| **The current price is outside your range. The position will be 100% in one token and won't earn fees until the price moves back into the range.** | Your custom range does not include the current price. | Widen the range to include the current price, or continue if you intend to wait for the price to reach the range. |
| **Add Liquidity** is unavailable after entering an amount | The amount is larger than your **Private Balance** for that asset, or the second asset's balance is too small for the calculated amount. | Lower the amount, or move more of the asset into your confidential balance. See [Fund](https://shield.fi/docs/trading/fund-and-bridge.md#web-app). |
| The position has not appeared under **Your Positions** after **Done** | The app is still reading the new position from the network. | Wait a moment and refresh the page. The **Recent Activity** tab shows the **Mint** row first. |

## Next steps

* [Increasing liquidity](https://shield.fi/docs/liquidity/increasing-liquidity.md) to add funds to the position.
* [Collecting and burning](https://shield.fi/docs/liquidity/collecting-and-burning.md) to collect the fees it earns.
* [Rebalancing positions](https://shield.fi/docs/liquidity/rebalance-position.md) to move it to a new range.

## Preview and mint

**Prerequisites:** Your authenticated mainnet `client` for Typescript, `dex` for Python, or CLI profile from [Setup](https://shield.fi/docs/trading/configure.md), funded with a confidential balance of both pool assets. See [Fund a trading account](https://shield.fi/docs/trading/fund-and-bridge.md).

Choose the pool before submitting. Replace `POOL_KEY` with its key from the [pool list](https://shield.fi/docs/api-reference/pools/list-pools.md). For Typescript, replace `AMOUNT0_BASE_UNITS` and `AMOUNT1_BASE_UNITS` with `bigint` deposit budgets in the pool's token order. The Python example converts decimal strings to integer base units using each token's `decimals`.

For Typescript, define the [confirmation helper](#wait-between-sdk-operations) before running the examples. Python includes its confirmation checks below.

> [tab] Typescript
>
> ### Step 1: Choose the pool, amounts, and range
>
> `previewMint` aligns the range to the pool's tick spacing, calculates the liquidity the budget supports, and reports the amounts the range will consume. Nothing is spent.
>
> ```typescript theme={"languages":{"custom":["/languages/leo.tmLanguage.json"]}}
> import { formatUnits } from "@provablehq/shield-swap-sdk"
>
> const { data: pool } = await client.api.getPool(POOL_KEY)
>
> const [token0, token1] = await Promise.all([
>   client.tokenData(pool.token0),
>   client.tokenData(pool.token1),
> ])
>
> const preview = await client.previewMint({
>   poolKey: pool.key,
>   amount0Desired: AMOUNT0_BASE_UNITS,
>   amount1Desired: AMOUNT1_BASE_UNITS,
>   rangePercent: 5,
> })
>
> if (preview.liquidity === 0n) throw new Error("this budget backs no liquidity at this range")
>
> console.log(`range ticks ${preview.tickLower} to ${preview.tickUpper}, current ${preview.tickCurrent}`)
> console.log(`consumes ${formatUnits(preview.amount0, token0.decimals)} ${token0.symbol}`)
> console.log(`         ${formatUnits(preview.amount1, token1.decimals)} ${token1.symbol}`)
> if (!preview.inRange) console.log("opens out of range, so it earns nothing yet")
> ```
>
> Pass `tickLower` and `tickUpper` instead of `rangePercent` to set exact bounds. `preview.inRange` is `false` when the range does not include the current price. Zero liquidity means one side of the budget is empty or the amounts are too small for the range; a mint would still cost a fee and open nothing.
>
> ### Step 2: Mint the position
>
> Pass the amounts the preview reported, not the budget. That caps the mint at what the preview showed even if the price moves before the transaction finalizes.
>
> ```typescript theme={"languages":{"custom":["/languages/leo.tmLanguage.json"]}}
> const imports = await client.resolveDexImports({
>   tokenPrograms: [token0.ammTokenProgram!, token1.ammTokenProgram!],
> })
>
> const minted = await client.mint({
>   poolKey: pool.key,
>   tickLower: preview.tickLower,
>   tickUpper: preview.tickUpper,
>   amount0Desired: preview.amount0,
>   amount1Desired: preview.amount1,
>   recipient: account.address,
>   withdrawal: account.address, // fixed for the life of the position
>   imports,
> })
>
> console.log(`minted ${minted.positionTokenId}`)
> ```
>
> `minted.positionTokenId` identifies the position for every later operation. `withdrawal` is where every collect pays, and it cannot be changed afterwards.
>
> ### Step 3: Check the position
>
> Save the transaction ID before waiting. The helper checks acceptance and waits for both the position state and its spendable record.
>
> ```typescript theme={"languages":{"custom":["/languages/leo.tmLanguage.json"]}}
> console.log(`submitted ${minted.transactionId}`)
> if (!minted.positionTokenId) throw new Error("recover the position ID from the confirmed mint")
> const position = await waitForPosition(minted.transactionId, minted.positionTokenId)
> if (position.state.liquidity === 0n) throw new Error("mint opened with no liquidity")
> console.log(`confirmed: liquidity ${position.state.liquidity}`)
> ```
>
> `position.state.liquidity` is the position's share of the range. `position.state.tokensOwed0` and `tokensOwed1` can be nonzero right after a mint: any part of the desired amounts the range did not use is credited to the position for you to collect.

> [tab] Python
>
> Run these steps in order with `dex` and `account` from [Setup](https://shield.fi/docs/trading/configure.md). The Python SDK has no mint preview. Size your chosen range with the CLI plan or Typescript preview before submitting.
>
> ### Step 1: Choose the pool, amounts, and range
>
> Replace `AMOUNT0_TOKEN_UNITS` and `AMOUNT1_TOKEN_UNITS` with decimal strings for the deposit budgets, in token0/token1 order. For example, `"1.25"` converts to `1_250_000` base units for a token with six decimals. Use strings to avoid floating-point rounding.
>
> ```python theme={"languages":{"custom":["/languages/leo.tmLanguage.json"]}}
> from decimal import Decimal
>
> def to_base_units(amount: str, decimals: int) -> int:
>     value = Decimal(amount)
>     if not value.is_finite() or value < 0:
>         raise ValueError("amount must be finite and nonnegative")
>     numerator, denominator = value.as_integer_ratio()
>     units, remainder = divmod(numerator * 10**decimals, denominator)
>     if remainder:
>         raise ValueError(f"amount exceeds the token's {decimals} decimal places")
>     if units >= 2**128:
>         raise ValueError("amount exceeds the contract's u128 limit")
>     return units
>
> pool = dex.api.get_pool(POOL_KEY)
> tokens_by_id = {token.address: token for token in dex.api.get_tokens()}
> token0 = tokens_by_id[pool.token0]
> token1 = tokens_by_id[pool.token1]
>
> amount0_desired = to_base_units("AMOUNT0_TOKEN_UNITS", token0.decimals)
> amount1_desired = to_base_units("AMOUNT1_TOKEN_UNITS", token1.decimals)
> print(f"deposit budget: {amount0_desired} base units of {token0.symbol}")
> print(f"deposit budget: {amount1_desired} base units of {token1.symbol}")
>
> slot = dex.get_slot(pool.key)
> tick_lower, tick_upper = slot.tick_range(10)
> print(f"range ticks: {tick_lower} to {tick_upper}")
> ```
>
> `slot.tick_range(10)` selects ten tick spacings on either side of the current tick. Replace these bounds with your own spacing-aligned ticks to match a different planned range. The conversion rejects fractional base units instead of rounding your budget.
>
> ### Step 2: Mint the position
>
> ```python theme={"languages":{"custom":["/languages/leo.tmLanguage.json"]}}
> recipient = str(account.address)  # Owns the PositionNFT and manages the position.
> withdrawal = str(account.address)  # Receives payouts; fixed even after a rebalance.
>
> result = dex.mint(
>     pool_key=pool.key,
>     tick_lower=tick_lower,
>     tick_upper=tick_upper,
>     amount0_desired=amount0_desired,
>     amount1_desired=amount1_desired,
>     recipient=recipient,
>     withdrawal=withdrawal,
>     account=account,
> ).delegate(wait=True)
>
> print(f"transaction: {result.transaction_id}")
> print(f"position: {result.position_token_id}")
> ```
>
> `recipient` controls the position; `withdrawal` receives every collect payout and nonzero rebalance refund. You cannot change the withdrawal address after minting, including during a rebalance. Setting a separate withdrawal address does not give it control of the position.
>
> The addresses can differ from each other and from the signer. If omitted, `recipient` defaults to the signer and `withdrawal` defaults to the recipient.
>
> `.delegate(wait=True)` submits through the configured proving service and waits for transaction confirmation. Save the transaction and position IDs before checking the record scanner.
>
> ### Step 3: Check the position
>
> The example mints to the signing account. If you choose another recipient, run the ownership check with that recipient's configured account and record scanner. The signer cannot scan another account's position record.
>
> ```python theme={"languages":{"custom":["/languages/leo.tmLanguage.json"]}}
> import time
>
> if not result.position_token_id:
>     raise RuntimeError(f"inspect transaction {result.transaction_id} to recover the position ID")
> if str(account.address) != recipient:
>     raise ValueError("configure the recipient's account before scanning this position")
>
> deadline = time.monotonic() + 180
> while time.monotonic() < deadline:
>     position = dex.get_owned_position(result.position_token_id, account=account)
>     if position is not None and position.state is not None:
>         break
>     time.sleep(3)
> else:
>     raise TimeoutError(
>         f"position not readable; check transaction {result.transaction_id} before resubmitting"
>     )
>
> if (position.pool_key, position.tick_lower, position.tick_upper, position.withdrawal) != (
>     pool.key, tick_lower, tick_upper, withdrawal,
> ):
>     raise RuntimeError("position does not match the mint request")
> state = position.state
> if state.liquidity <= 0:
>     raise RuntimeError("minted position has no liquidity")
>
> def format_units(amount: int, decimals: int) -> str:
>     whole, fraction = divmod(amount, 10**decimals)
>     return str(whole) if decimals == 0 else f"{whole}.{fraction:0{decimals}d}"
>
> print(f"confirmed liquidity: {state.liquidity}")
> for token, backing, owed in (
>     (token0, state.amount0, state.tokens_owed0),
>     (token1, state.amount1, state.tokens_owed1),
> ):
>     print(f"{token.symbol}: {format_units(backing, token.decimals)} backing liquidity")
>     print(f"{token.symbol}: {format_units(owed, token.decimals)} owed")
> ```
>
> This waits for both the ownership record and readable state. A timeout does not mean the mint failed. The backing amounts reflect the price when you read the position; owed balances include any unused deposit and remain available to [collect](https://shield.fi/docs/liquidity/collecting-and-burning.md).

> [tab] CLI
>
> ### Step 1: Choose the pool, amounts, and range
>
> Without `--execute`, the command prints the plan and stops: the aligned range, the amounts it consumes, and whether it opens in range.
>
> ```bash theme={"languages":{"custom":["/languages/leo.tmLanguage.json"]}}
> shield-swap mint --pair USDCx:ETH --amount USDCx:1 --range-pct 5 --network mainnet
> ```
>
> Name the amount by symbol with `--amount`; a side left unnamed commits its whole confidential balance as a ceiling, and the plan shows what the range uses.
>
> ### Step 2: Mint the position
>
> Add `--execute` to submit the command from step 1.
>
> ```bash theme={"languages":{"custom":["/languages/leo.tmLanguage.json"]}}
> shield-swap mint --pair USDCx:ETH --amount USDCx:1 --range-pct 5 --network mainnet --execute
> ```
>
> Save the position token ID and transaction ID printed by the command.
>
> ### Step 3: Check the position
>
> List your positions and find the ID printed in step 2:
>
> ```bash theme={"languages":{"custom":["/languages/leo.tmLanguage.json"]}}
> shield-swap positions --network mainnet
> ```
>
> The list shows live liquidity and owed balances once the position is readable. A position still finalizing appears only with `--all`; check its transaction before submitting another mint.

## Wait between SDK operations

Continue with the authenticated mainnet client from [Setup](https://shield.fi/docs/trading/configure.md). Define the helper for your SDK before running the liquidity examples on this page and the pages that follow. Submit operations on a position one at a time.

> [tab] Typescript
>
> `waitForPosition` checks transaction acceptance, then waits for the scanner to return the position. After an increase, decrease, or collect, pass the previous record's `tag` so a stale record cannot satisfy the wait.
>
> ```typescript theme={"languages":{"custom":["/languages/leo.tmLanguage.json"]}}
> async function waitForTransaction(transactionId: string) {
>   const deadline = Date.now() + 180_000
>   while (Date.now() < deadline) {
>     const { status } = await walletClient.transactionStatus({ transactionId })
>     if (status === "accepted") return
>     if (status === "rejected") throw new Error(`transaction rejected: ${transactionId}`)
>     await new Promise((resolve) => setTimeout(resolve, 3_000))
>   }
>   throw new Error(`confirmation timed out; check transaction ${transactionId} before retrying`)
> }
>
> async function waitForPosition(
>   transactionId: string,
>   positionTokenId: string,
>   previousTag?: string,
> ) {
>   await waitForTransaction(transactionId)
>   const deadline = Date.now() + 180_000
>   while (Date.now() < deadline) {
>     const positions = await client.getOwnedPositions()
>     const position = positions.find((p) => p.positionTokenId === positionTokenId)
>     if (position?.state && position.record.tag !== previousTag) {
>       return { ...position, state: position.state }
>     }
>     await new Promise((resolve) => setTimeout(resolve, 3_000))
>   }
>   throw new Error(`position not ready; check transaction ${transactionId} before retrying`)
> }
> ```

> [tab] Python
>
> `.delegate(wait=True)` waits for transaction confirmation. Call `wait_for_position` afterwards to wait for the scanner, passing the previous record after an operation that replaces it.
>
> ```python theme={"languages":{"custom":["/languages/leo.tmLanguage.json"]}}
> import time
> from aleo.codegen.runtime import parse_plaintext
>
> def wait_for_position(position_token_id, previous_record=None):
>     deadline = time.monotonic() + 180
>     while time.monotonic() < deadline:
>         position = dex.get_owned_position(position_token_id)
>         if position and position.record != previous_record:
>             return position
>         time.sleep(3)
>     raise TimeoutError("position record not ready; check the original transaction before retrying")
>
> def read_position_state(position_token_id):
>     raw = aleo.network.get_program_mapping_value(dex.program, "positions", position_token_id)
>     if not raw or raw == "null":
>         raise RuntimeError("position mapping not readable")
>     return parse_plaintext(raw)
> ```
>
> In the Python SDK, `position.state` can be `None` after a full decrease removes the range's boundary ticks. The position can still hold collectible funds. Use `read_position_state` to read its settled balances directly when its liquidity is zero.

A timeout does not prove the transaction failed. Check the saved transaction ID before submitting another operation. Burn returns no replacement record; confirm its transaction and the removal of the public position row instead.

## How it works on chain

`mint` transfers your desired token0 and token1 amounts into the AMM and creates a position. The amount used backs liquidity; any excess stays owed to the position until you collect it.

### What mint creates

| Item | After a successful mint |
| - | - |
| `token_id` | A new public position ID. |
| `PositionNFT` | A record owned by the recipient, binding the position ID, pool, range, and fixed withdrawal address. |
| Token change records | One per input token, holding the input-record amount above the desired amount. |
| Public position state | Liquidity and fee checkpoints, with each token's `desired - used` credited to its owed balance (`tokens_owed0` or `tokens_owed1`). |

### How liquidity is recorded

1. The contract calculates liquidity and the amounts used at the current square-root price. Liquidity must be nonzero, and each used amount must meet its token minimum.
2. It updates the boundary ticks, inserting any new boundaries with your supplied hints.
3. It records the liquidity, owed balances, and current fee-growth checkpoints. Your position earns only subsequent [fee growth](https://shield.fi/docs/liquidity/fee-entitlements.md).

Use spacing-aligned ticks with `MIN_TICK <= tick_lower < tick_upper <= MAX_TICK`. Fetch [insertion hints](https://shield.fi/docs/concepts/initialized-tick-index.md#inserting-a-boundary) immediately before submission; another accepted transaction can make a hint stale and cause your mint to be rejected.

After acceptance, save the transaction ID, `PositionNFT` ciphertext, and change records before marking the input records spent. Live liquidity and owed balances are read from `positions[token_id]`.

## Next steps

* [Increasing liquidity](https://shield.fi/docs/liquidity/increasing-liquidity.md) to add funds to the position.
* [Collecting and burning](https://shield.fi/docs/liquidity/collecting-and-burning.md) to collect fees and close the position.
* [Rebalancing positions](https://shield.fi/docs/liquidity/rebalance-position.md) to move it to a new range, or [Tracking position fills](https://shield.fi/docs/liquidity/position-fills.md) to inspect inventory changes.
* The [Typescript mint example](https://github.com/ProvableHQ/veil/blob/main/examples/shield-swap/mint.ts) is the runnable version of the steps above.


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