# Vault Contract

`contracts/Vault.sol` is a non-custodial, non-transferable LP share vault that runs a market-making strategy directly against the canonical OrderBook. It keeps accounting oracle-free for deposits and withdrawals, reconstructs inventory from live order book state, and relies on roles to separate operator flow from governance controls.

## Scope & Surface

* Dual-asset vault: holds `baseToken` and `quoteToken`, mints ERC20-like shares that cannot be transferred (`_update` reverts on transfers; only mint/burn are allowed).
* Market making only: optionally `makerOnly`, which forces post-only, standard creates and rejects any immediate fills when ID is zeroed.
* Hard cap of `MAX_ACTIVE_ORDERS = 80` tracked locally via `activeOrderIds`. Orders outside this list are ignored unless they belong to the vault.
* Order plumbing works with the core `IOrderBook` and, when deployed, the optional `IOrderBookExtended` for atomic cancel-and-create.
* Assets must be non-rebasing / non-fee-on-transfer; deposits revert if fewer tokens are received than requested.

## Roles & Access

* `DEFAULT_ADMIN_ROLE` – governs fees, deposit gates, pausing, and performance fee settings. Also inherits whitelist administration via role admin.
* `OPERATOR_ROLE` – runs `executeBatch` / `executeBatchExtended`, cancels orders, claims/prunes, closes deposits, and handles emergency exits.
* `WHITELIST_ADMIN_ROLE` – toggles the whitelist feature and individual addresses. Defaults to the admin if an explicit address is not provided at deploy.
* Constructor wires immutable references (OrderBook, tokens, maker-only flag, optional oracles) and pre-approves the OrderBook for max token spend.

## Deposits & Withdrawals

* `depositDual(baseAmountDesired, quoteAmountDesired, baseMin, quoteMin)` mints shares in the current vault ratio without any oracle lookups. Transfers must be exact (no fee-on-transfer tokens) or the call reverts. The first LP mints `sqrt(base * quote) - MINIMUM_LIQUIDITY` shares after a product sanity check; `MINIMUM_LIQUIDITY` stays locked to avoid inflation.
* Every deposit syncs filled orders, accrues performance fees if enabled, and optionally seeds `highWaterMark` the first time a priceable NAV is available.
* `withdrawDual(shares)` burns shares for proportional base+quote, waiving the withdrawal fee for the final LP (leaving only `MINIMUM_LIQUIDITY`). `_ensureLiquidity` first pulls withdrawables, then cancels tracked orders as needed, and reverts with `LiquidityCrunch` if inventory is still insufficient.
* Withdrawal fee is paid in shares (`withdrawalFeeBps`, capped by `MAX_WITHDRAWAL_FEE_BPS`) and burned to benefit remaining LPs. Deposits can be closed independently of pausing via `depositsOpen`.

## Order Management

* `executeBatch(...)` and `executeBatchExtended(...)` let operators cancel and/or place orders in one call. Inputs are length-checked, capped (32 creates, 128 cancels), and may revert with `PostOnlyFill` if maker-only is violated.
* `cancelOrders(orderIds)` is a cancel-only helper; `_cancelAndAccount` tolerates untracked IDs and prunes dead entries when cancellations fail due to prior fills.
* `claimAndPrune(claimIds, pruneIds)` batches claims (no withdraw) and drops inactive IDs from `activeOrderIds`.
* `_claimAllFilled` and `_pruneCancelledIds` keep `activeOrderIds` aligned with on-chain state; all helper paths are non-reentrant and respect pause guards where applicable.

## Accounting & NAV

* `_getRealtimeBalances` rebuilds total base/quote by combining free balances, withdrawables, unfilled resting orders, and unclaimed fills reconstructed from packed order data.
* Performance fee (optional) uses `oracleA` (and an optional `oracleB` ratio) to compute quote-denominated NAV. `_accruePerformanceFee` mints shares to `performanceFeeRecipient` when NAV exceeds `highWaterMark`, capped by `MAX_PERFORMANCE_FEE_BPS`. Manual trigger: `accruePerformanceFeeNow()`.
* NAV computation is skipped if fees are disabled, oracles are unset/zeroed, or precision is invalid; `highWaterMark` initializes lazily on the first priceable deposit.

## Whitelisting, Pausing, and Emergencies

* Whitelisting is optional (`whitelistEnabled`). When on, deposits require `isWhitelisted[msg.sender]`.
* Pausing (`pause`/`unpause`) is admin-gated. Withdrawals remain available while paused; deposits are blocked by `whenNotPaused`.
* `exitAndWithdrawAll` is the emergency off-ramp: claims fills, cancels all tracked orders (bounded by the 80-order cap), withdraws refunds, and pauses the vault (deposits are blocked while paused).
* Operators can close deposits without pausing via `closeDepositsFromOperator` and can call `manualWithdrawTokens` to sweep OrderBook refunds without touching order state.

## Events & View Helpers

* Lifecycle and fee events: `DepositDual`, `WithdrawalDual`, `WithdrawalFeeSharesBurned`, `PerformanceFeeAccrued`, `HighWaterMarkUpdated`, `DepositsOpenUpdated`, and updates for fee rates/recipient.
* Order ops: `BatchExecuted`, `OrderCancelled`, `ExitInitiated`, plus whitelist toggles.
* Views: `getActiveOrderIds()` returns the locally tracked IDs; `getRealtimeBalances()` mirrors `_getRealtimeBalances` for front ends and monitoring.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dbookio.gitbook.io/dbook/technical-documentation/vault-contract.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
