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

# Market maker operations

> A control framework for quoting, range management, fee reconciliation, and deployment cutovers.

Market makers need current public pool state and controlled custody of confidential ownership records. The contract provides deterministic position accounting. Range selection, inventory limits, rebalancing policy, custody, and reconciliation remain operator responsibilities.

## Operating state

Maintain a deployment-scoped state record for each market:

* Program ID and checksum
* Pool key
* Canonical token0 and token1
* Token display decimals and wrapper relationships
* Fee tier in fee pips
* Current `fee_protocol` numerator
* Tick spacing
* Current tick and square-root price
* Active liquidity
* Nearest initialized ticks above and below
* Pause and enable controls
* Open position token IDs
* Latest unspent `PositionNFT` record for each position

Do not key the state store only by pool key. Pool keys are mapping keys inside a program. A fresh deployment can use the same logical pair and fee values while holding entirely separate liquidity and records.

## Quote construction

Before quoting:

1. Read the slot and pool state at a known height.
2. Confirm token order, decimals, and wrapper relationships.
3. Walk the initialized-tick index in the proposed direction.
4. Apply the fixed iteration limit used by the selected swap path.
5. Apply fee and protocol-share rounding per step.
6. Keep final output and any refund in native token base units.
7. Enforce a nonzero minimum output appropriate to the instruction.

The pool fee is in parts per million. For example, 3000 fee pips is 0.30 percent. The protocol share is a fraction of that integer fee:

```text theme={"languages":{"custom":["/languages/leo.tmLanguage.json"]}}
protocol_fee = floor(step_fee * fee_protocol / 16)
lp_fee = step_fee - protocol_fee
```

The current setting is public and administrator-controlled. A fee forecast that assumes a static protocol share should state the observation height and update policy.

## Tiny inputs

After fee adjustment, a small input can have zero amount available for price movement. The bounded partial path returns the full input without moving price or charging a fee. Routers and market makers should still reject quote sizes whose expected output is zero.

## Range and inventory management

Each position is active over:

```text theme={"languages":{"custom":["/languages/leo.tmLanguage.json"]}}
tick_lower <= current_tick < tick_upper
```

The position moves toward token1 as price rises through the range and toward token0 as price falls. A range manager should track:

* Distance to each boundary
* Inventory by token
* Active liquidity share
* Realized and pending fees by input token
* Expected proving and confirmation time for a rebalance
* Available token records for the next mint or increase
* Current predecessor hints if a boundary must be inserted

Position ranges and liquidity are public, so an LP's strategy remains observable even when ownership is confidential.

Read [Choosing a range](./choosing-a-range).

## Exact-limit tick behavior

Reaching an initialized tick completes the crossing even when the tick price equals the user's square-root-price limit.

At the boundary, the contract:

1. Charges the step fee.
2. Adds LP growth using pre-crossing active liquidity.
3. Flips both token outside-growth counters.
4. Applies `liquidity_net`.
5. Stops if no further price movement is allowed.

The post-swap slot can therefore hold post-crossing liquidity while its price equals the limit. A simulator that leaves liquidity unchanged at an exact limit will misquote the next transaction and misclassify which ranges are active.

Tests and monitors should include exact lower and upper boundary cases in both swap directions.

## Rebalancing workflow

A range cannot be changed in place. A controlled rebalance normally uses:

1. Decrease liquidity in the old range.
2. Confirm the resulting principal and settled fees in `tokens_owed`.
3. Collect the required amounts into token records.
4. Select and align the new range.
5. Refresh initialized-tick insertion hints.
6. Mint the new position with unspent records.
7. Verify public position and slot changes.
8. Burn the old position after its liquidity and owed balances are zero.

An increase is appropriate when the range stays the same. It settles fees at old liquidity before adding new liquidity. A partial decrease similarly settles at full old liquidity before reducing it.

These settlement points define liquidity epochs. They prevent new capital from sharing in old fee growth, but each settlement also floors the position's fractional entitlement to an integer native base unit.

## Settlement cadence

Pending fees do not need to be collected for the position to keep earning. They remain represented by Q128.128 growth until increase, decrease, collect, or freeze settles them.

More frequent settlement can:

* Improve treasury availability
* Simplify period-end realization
* Increase proof and custody operations
* Discard more sub-unit fee dust

The floor is less than one native base unit per token and position settlement. Use token decimals only to express that threshold in display units.

Read [Fee entitlements](./fee-entitlements) and [Rounding, overflow, and invariants](../math/rounding-overflow-and-invariants).

## Fee reconciliation

Track at least four fee categories:

| Category          | State source                                              |
| ----------------- | --------------------------------------------------------- |
| Gross step fee    | Swap execution model                                      |
| Protocol fee      | `Slot.protocol_fees0` and `protocol_fees1`                |
| Settled LP amount | Position `tokens_owed` changes and collect                |
| Pending LP amount | Global, tick outside, and position checkpoint calculation |

There is also a rounding surplus:

* Fee growth floors once per step.
* Position entitlement floors at settlement.
* The contract does not carry a pool-level residual across liquidity epochs.
* The contract has no generic sweep for the resulting surplus.

Do not force reconciliation by assigning unexplained public token balance to protocol revenue. Protocol collection is limited to recorded protocol-fee fields.

## Public and confidential records

Publicly observable data includes:

* Pool fee and protocol share
* Slot price, tick, liquidity, and fee growth
* Initialized ticks and outside growth
* Position range, liquidity, checkpoints, and owed amounts
* Public amounts requested by collect

Confidential data includes the ownership and payout information held in Aleo records, subject to investigator-owned compliance records and ordinary transaction metadata.

Market surveillance can calculate pool and position economics without knowing the public owner address because no owner address is stored in `Position`. Amount and timing correlation remain possible.

## Controls and incident response

Monitor:

* Global, token, pair, and pool pause state
* Position freeze mappings
* Program checksum changes
* Protocol fee setting changes
* Boundary-list consistency
* Active liquidity versus boundary net changes
* Unexpected fee-growth wraps
* Settlement amounts approaching `u128` limits
* Persistent contract balance not explained by principal, protocol fees, or LP claims

Pool disable and broad pause controls block entry and trading paths, but decrease and collect remain available. Position freeze is stricter. It removes live liquidity, settles value into owed accounting, and blocks the holder until unfreeze.

An incident runbook should distinguish stopping new risk from blocking a specific position.

## Fresh-deployment cutover

The current schema uses two-limb Q128.128 fee-growth values and no residual state. It is incompatible with deployments that use scalar growth fields in the same mapping structures. Aleo program upgrades freeze existing mapping and struct interfaces, so adopting the current schema requires a fresh deployment.

For a cutover:

1. Stop routing new flow to the old deployment.
2. Disable old pools while preserving LP decrease and collect access.
3. Reconcile and collect recorded protocol fees.
4. Deploy and bootstrap the new program.
5. Establish new pools and approvals.
6. Update simulators, decoders, routers, and custody systems together.
7. Exit and remint liquidity rather than copying old fee checkpoints.
8. Keep old and new histories under separate schema versions.

A residual from an earlier deployment cannot be fairly attached to a new active-liquidity set. Transplanting that state would violate the current rule that prevents fee fractions from crossing liquidity epochs.

## Daily control checklist

* Confirm deployment checksum and configuration.
* Reconcile token metadata, wrapper relationships, and canonical order.
* Refresh slots and initialized ticks.
* Review exact-limit boundary exposure.
* Compare pending and settled fees.
* Confirm the current protocol share.
* Check unspent ownership and token records.
* Review pause and freeze state.
* Investigate unexplained surplus without assuming it is withdrawable.
* Preserve evidence for each range, quote, settlement, and rebalance decision.
