# Exchange Module

The Exchange Module is the core trading engine of the Uniocean protocol, implementing on-chain orderbook storage, matching, and settlement across Spot, Derivative (Perpetual and Expiry Futures), and Binary Options markets. To balance high-frequency trading demands with MEV resistance, the module utilizes a hybrid execution model: immediate transaction-time execution for market orders, and deterministic batch matching for resting limit orders during the block lifecycle.

## Immediate Execution (Transaction-Time)

To accommodate smart contracts and traders requiring instant fill feedback, specific order flows are executed immediately against the resting limit orderbook during the standard transaction processing phase (prior to the `EndBlocker`):

* **Market Orders:** Spot market orders execute instantly, utilizing a balance-hold model where the protocol reserves the required assets, matches the order, and immediately refunds any unused reserve. Derivative market orders execute similarly, incorporating a `WorstPrice` parameter to enforce strict slippage protection, debiting margin upfront and refunding it if the execution fails.
* **Fill-or-Kill (FOK) Atomicity:** Spot limit orders submitted with FOK semantics are executed within a cached state context. If the order cannot be entirely filled against the resting liquidity, the cached state is immediately discarded, and the transaction fails, ensuring strict all-or-nothing execution.

## Deterministic Batch Matching (EndBlocker)

To mitigate front-running and ensure fair execution pricing, all resting limit orders are processed deterministically during the `EndBlocker` phase.

Unlike continuous matching engines, Uniocean performs batch clearing sequentially per market. For both Spot and Derivative limit orders, the protocol evaluates crossing liquidity (where the best bid is greater than or equal to the best ask). It then computes a single, uniform clearing price — typically derived from the mid-price of the crossing bid/ask spread. All matched quantities in that batch are settled at this uniform clearing price, mathematically eliminating the profitability of transaction reordering within the block.

## Dynamic Fee Discounts

Uniocean incentivizes deep liquidity via an automated fee discount schedule applied at execution time. The tier calculation is based on two primary metrics:

* **Rolling Volume:** Trading volume is aggregated across a rolling window of chronological buckets to determine active participation.
* **Staked Capital:** The total amount of native tokens directly delegated to validators by the account.

To optimize state machine performance, the computed discount tier is cached with a Time-To-Live (TTL) keyed to the current bucket boundary, preventing redundant calculations on every individual fill.

## Perpetual Funding Mechanics

For Perpetual Futures, the protocol aligns the contract price with the underlying asset via a funding rate, updated at fixed intervals (e.g., every 8 hours). The funding rate is derived from the premium between the Mark Price and the Index Price, plus a fixed interest component:

$$\text{premium} = \frac{MarkPrice - IndexPrice}{IndexPrice}$$

$$\text{fundingRate} = \text{premium} + \text{interest}$$

This calculated `fundingRate` is strictly clamped to predefined protocol bounds and applied to active positions during relevant execution paths.

## Expiring Futures Settlement and Deficit Accounting

For expiring futures, settlement is triggered during the `BeginBlocker` of the matured market using an Oracle Time-Weighted Average Price (TWAP) calculated over the settlement window.

If extreme volatility causes a position to settle with a negative payout (bankruptcy), the module attempts to cover the shortfall by drawing down the specific market's Insurance Fund balance. If the Insurance Fund is exhausted, the protocol does not arbitrarily penalize winning traders via socialized loss; instead, it records the remaining shortfall as an *uncovered deficit* for strict protocol accounting and monitoring.

## Block Lifecycle Maintenance

The Exchange Module meticulously segregates operations to optimize block times:

* **BeginBlocker:** Executes protocol maintenance before user transactions. This includes fee bucket rotation, trading reward distributions, conditional order triggers, funding updates, expiry and binary market settlements, and invariant validations (such as open interest checks).
* **EndBlocker:** Executes the heavy computational loads after user transactions. This includes the sequential batch matching for all active Spot and Derivative markets, fill persistence, event emission, and (if configured) periodic auto-liquidation sweeps.


---

# 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://uniocean.gitbook.io/uniocean-docs/core-platform-modules/exchange-module.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.
