> ## Documentation Index
> Fetch the complete documentation index at: https://docs.xentfi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Liquidity & Settlement

> How matched trades settle on-chain, how markets stay funded, and what protects a market from thin liquidity, MEV, and stale prices.

<Note>
  This page explains the **concepts** behind liquidity and settlement on XentFi Pro. For the full request/response schema of every endpoint, see the [XentFi Pro API Reference](/xentfi-pro/overview).
</Note>

## Overview

Matched trades on XentFi Pro don't settle one-by-one on-chain, and they don't net arbitrary wallet pairs against each other directly either — every wallet is a real, independent on-chain account, so two different owners' balances can't be merged into a single transaction without a shared contract. Instead, settlement routes through each market's **settlement master wallet**, in a hub-and-spoke pattern, batched every 2 seconds.

```mermaid theme={null}
sequenceDiagram
    participant Payer as Wallets that owe (IN)
    participant Master as Market's settlement master wallet
    participant Payee as Wallets that are owed (OUT)

    Note over Payer,Payee: Every 2s: net all trades per (wallet, asset)

    Payer->>Master: Phase 1 — one transaction per payer wallet,<br/>bundling every asset it owes this cycle
    Note over Master: Confirmation gate:<br/>wait for every IN leg to confirm
    Master->>Payee: Phase 2 — one transaction from the master wallet,<br/>paying every wallet owed funds this cycle
```

This means **N** trades in a market during one settlement window collapse to at most `(number of distinct payer wallets) + 1` on-chain transactions — not N — and a payout is never broadcast against funds that haven't actually landed yet.

## Settlement batches

Every settlement batch tracks its legs individually, so a partial failure (e.g. one payer's IN leg reverts) is visible per-wallet rather than collapsing the whole batch into one opaque status.

```bash theme={null}
curl -X GET https://api.pro.xentfi.com/v1/orderbook/settlement-batches/{batchId} \
  -H "apiKey: your-api-key" \
  -H "orgId: your-org-id"
```

| Field       | Description                                                                                                         |
| ----------- | ------------------------------------------------------------------------------------------------------------------- |
| `netDeltas` | `walletId → assetId → signed net delta` for the batch — negative means the wallet owed, positive means it was owed. |
| `legs`      | One entry per `(walletId, assetId, direction)`, each with its own `txHash`, `status`, and `failureReason`.          |
| `status`    | Batch-level `SettlementStatus`: `QUEUED`, `BATCHED`, `SUBMITTED`, `CONFIRMED`, `FAILED`, `REORGED`, or `REPLACED`.  |

Once a batch reaches `CONFIRMED`, its trades are marked settled and the affected wallets' cached balances are immediately re-synced against on-chain state.

## Funding a market's liquidity

Every market needs a real `settlementMasterWalletId` — an existing XentFi master wallet — with enough working capital on the market's `settlementBlockchainId` to cover Phase 2 payouts between settlement cycles.

<Warning>
  This is real custody. Monitor a market's settlement master wallet balance the same way you'd monitor any other hot wallet — if it can't cover a settlement cycle's payouts, that cycle's OUT legs fail even though the matching trades already executed off-chain.
</Warning>

Because a `Market` is scoped to a single chain (`settlementBlockchainId`), plan working capital per chain per market rather than assuming one wallet covers multiple markets across chains.

## Price oracle & market-order protection

An external reference price feed protects two situations the order book's own trade history can't cover on its own:

* **Empty or thin books** — before a book has a mid price of its own, a price-band check falls back to the oracle so a brand-new market's first order can't set an arbitrary opening price for everyone after it.
* **MARKET orders** — before a `MARKET` order is allowed to walk the book, its expected execution price is checked against the oracle, rejecting execution against a stale or thinly-manipulated book independent of the order book's own recent trades.

If no oracle is configured for a pair, both checks **fail open** — price discovery proceeds unconstrained rather than blocking trading on long-tail markets. This is a deliberate default, not a gap: configure an oracle for any market where you want that protection active.

## Anti-MEV & fair matching

* **Batch auctions** (`batchAuctionIntervalMs`, default 250ms) remove intra-batch latency races — orders within the same window are matched on price-time priority rather than rewarding whoever's request lands microseconds earlier.
* **Private relay routing** is used for settlement transactions where available, reducing exposure to public-mempool front-running on the settlement leg itself.
* **Price bands** (`maxDeviationFromMidBps`) and rate limiting reject spoofing and fat-finger orders before they ever reach the book.

## Gas & fee volatility

Settlement legs are quoted and submitted using a rolling EMA base-fee estimate per chain, with a volatility-scaled buffer. If live gas exceeds a hard multiple of that baseline, a circuit breaker **holds and requeues** affected trades rather than dropping them or settling at an unpredictable cost — they settle once conditions normalize.

## Reconciliation

Off-chain cached balances are reconciled against actual on-chain state in two ways:

1. **Event-driven** — immediately after every confirmed settlement batch.
2. **Real-time on external activity** — a deposit or withdrawal that happens outside the order book (e.g. your business moving funds directly) is detected via the platform's existing webhook pipeline and immediately reconciles that wallet's balance if it has open orders, unwinding any now-under-collateralized resting orders within seconds.

A downward discrepancy freezes the affected wallet and unwinds excess resting-order reservations, rather than allowing it to trade on a balance that no longer exists.

## API Reference

| Endpoint                                     | Method | Description                                            |
| -------------------------------------------- | ------ | ------------------------------------------------------ |
| `/v1/orderbook/settlement-batches`           | GET    | List settlement batches                                |
| `/v1/orderbook/settlement-batches/{batchId}` | GET    | Get settlement batch status, including per-wallet legs |
| `/v1/orderbook/status`                       | GET    | Engine node health and shard leadership                |

Full request/response schemas: [XentFi Pro API Reference](/xentfi-pro/overview).

## Related

<CardGroup cols={3}>
  <Card title="Order Book" icon="list-ordered" href="/essentials/orderbook">
    Markets, order types, and the order/trade lifecycle.
  </Card>

  <Card title="XentFi Pro Quickstart" icon="rocket" href="/xentfi-pro/quickstart">
    Place your first order end to end.
  </Card>

  <Card title="Master Wallets" icon="wallet" href="/essentials/master-wallets">
    How settlement master wallets fit into XentFi's wallet hierarchy.
  </Card>
</CardGroup>
