# Block Lifecycle & Trade Execution

## BeginBlock Operations

The `BeginBlocker` executes at the absolute start of the block, before any user transactions from the mempool are processed:

| Operation                        | Description                                                         |
| -------------------------------- | ------------------------------------------------------------------- |
| **Fee Discount Bucket Rotation** | Advances rolling volume windows for fee discount tiers              |
| **Trading Rewards Processing**   | Manages the algorithmic reward lifecycle                            |
| **Conditional Order Triggers**   | Evaluates resting conditional orders (Stop-Loss, Take-Profit)       |
| **Expiry Futures Settlement**    | Settles non-perpetual derivative markets at expiry                  |
| **Funding Rate Updates**         | Recalculates funding rates for active Perpetual markets             |
| **Binary Options Lifecycle**     | Evaluates binary markets against their time-locks                   |
| **Risk & Solvency Monitoring**   | Evaluates the balance health of derivative markets                  |
| **Open Interest Invariants**     | Validates *OI\_long ≈ OI\_short* across all derivative markets      |
| **Expired Order Cleanup**        | Deletes resting orders that have reached their `ExpiryBlock` height |

## EndBlock Operations

The `EndBlocker` executes at the very end of the block, after all user transactions have been finalized:

| Operation                              | Description                                                                      |
| -------------------------------------- | -------------------------------------------------------------------------------- |
| **Spot Batch Matching**                | Processes resting limit orderbooks and settles at a uniform block clearing price |
| **Derivatives Batch Auction Matching** | Executes limit order batch auction across all Derivative markets                 |
| **Automated Liquidation Engine**       | Sweeps for undercollateralized positions within a strict per-block budget        |

## Trade Execution Lifecycle

Every trade on Uniocean undergoes a highly structured verification, matching, and settlement process embedded directly into the Cosmos SDK state machine.

### Execution Steps

{% stepper %}
{% step %}

### Broadcast (Transaction Submission)

The user formulates, signs, and broadcasts a transaction containing a specific exchange payload (e.g., `MsgCreateSpotLimitOrder`, `MsgCreateDerivativeLimitOrder`). The network authenticates the cryptographic signature before routing the message to the Exchange module's message server handlers.
{% endstep %}

{% step %}

### Validation (Market, Risk, and Funds)

Before an order is accepted, it undergoes rigorous multi-layered validation:

* **Circuit Breakers:** The protocol verifies that trading is globally enabled and that the specific market is flagged as tradable.
* **Constraints & Risk Limits:** Orders are checked for invalid flag combinations, hash uniqueness, and `reduce_only` invariants.
* **Margin & Fund Reservation:** For Spot markets, the protocol utilizes a hold model, moving the required assets from `AvailableBalance` to a locked `HoldBalance`. For Derivative markets, the required margin is instantly deducted from the subaccount's available balance.
  {% endstep %}

{% step %}

### Order Matching (Immediate vs. Batch)

* **Immediate Execution (In-Tx):** Spot Market orders, as well as IOC and FOK Limit orders, execute immediately against the active orderbook utilizing a cached context to ensure strict atomicity.
* **End-Block Batch Matching:** Standard GTC Limit orders are stored in the module's orderbook state. At the end of each block, the Keeper executes market-wide batch matching using a price-time priority loop.
  {% endstep %}

{% step %}

### Settlement and Event Processing

Following a successful match, the chain atomically settles subaccount balances and positions. The module emits strongly typed protobuf events including `EventBatchSpotExecution` and `EventBatchDerivativeExecution`.
{% endstep %}

{% step %}

### Frontend Update (Off-Chain Consumption)

Off-chain infrastructure — including indexers, market data APIs, and WebSocket relays — subscribes to the Tendermint RPC to capture emitted block and transaction events, serving aggregated data to the Frontend DEX UI for near real-time rendering.
{% endstep %}
{% endstepper %}

### Implementation References

| Component                             | File                       |
| ------------------------------------- | -------------------------- |
| Transaction Schemas & Events          | `tx.proto`, `events.proto` |
| Message Entrypoints                   | `msg_server.go`            |
| Spot Limit Matching Engine            | `spot_matching_engine.go`  |
| End-Block Batch Matching & Settlement | `abci.go`                  |
| Event Emission Logic                  | `event_emission.go`        |


---

# 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/block-lifecycle-and-trade-execution.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.
