> For the complete documentation index, see [llms.txt](https://docs.uniocean.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.uniocean.io/protocol-and-infrastructure/protocol/block-lifecycle.md).

# 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

1. **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.
2. **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.
3. **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.
4. **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`.
5. **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.

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