# Liquidation System

The **Symmio Options Protocol** includes a robust liquidation system, designed to manage counterparty risk and maintain systemic solvency. Liquidation processes are orchestrated by the **Symmio Clearing House**, which acts as the protocol's enforcement and settlement authority.

## Liquidation Workflow

The liquidation process is composed of three core stages:

### **Step 1: Flagging**

* The **Clearing House** can flag accounts that appear insolvent based on external solvency checks.
* Flagging creates a `LiquidationDetail` entry with status `FLAGGED`.
* The protocol provides distinct flagging functions for different margin types (e.g., isolated, cross) and parties (Party A or Party B).
* Once flagged, the account enters a **grace period** during which it may recover solvency before liquidation is enforced.

### **Step 2: Liquidation Execution**

* After the grace period, if the account remains insolvent, the Clearing House may **execute liquidation**.
* Upon execution, the liquidation status is updated from `FLAGGED` to `IN_PROGRESS`.
* The **collateral price** and **unrealized PnL (UPNL)** at the time of liquidation are recorded to determine accurate settlement amounts.
* Relevant **cross-margin balances** are zeroed out and redistributed or seized as required.

### **Step 3: Cancel Intents, Close Trades, and Adjust Balances**

* After execution, the Clearing House finalizes **balance adjustments** for all affected parties.
* Some balance changes may already occur during Step 2 (e.g., during cross balance resets), but this step ensures all final deltas are correctly applied.
* The liquidated party must not retain any **open intents** or **open trades**:
  * The Clearing House forcibly cancels any remaining **intents**.
  * It also **closes all active trades** associated with the liquidated party.
  * This guarantees a clean state for system integrity.

### **Liquidation States**

| State            | Description                                   | Next Actions                                           |
| ---------------- | --------------------------------------------- | ------------------------------------------------------ |
| **FLAGGED**      | Account flagged as insolvent                  | Execute liquidation or unflag if recovered             |
| **IN\_PROGRESS** | Liquidation actively being processed          | Close trades, confiscate assets, distribute collateral |
| **CANCELLED**    | Flagged liquidation cancelled due to recovery | Return to normal operation                             |

## **Liquidation Types**

### **1. Isolated Party B Liquidation**

Used when Party B becomes insolvent in isolated margin mode when Party A buys option from Party B :

```solidity
// Flagging
flagIsolatedPartyBLiquidation(address partyB, address collateral)

// Execution
liquidateIsolatedPartyB(address partyB, address collateral, int256 upnl, uint256 collateralPrice)

// Unflagging (if Party B recovers)
unflagIsolatedPartyBLiquidation(address partyB, address collateral)
```

**Trigger Conditions:**

* When total loss of open positions exceeded from loss coverage of isolated balance.
* `isolatedBalance + (effectiveUpnl * 1e18) / collateralPrice < 0`
* Where `effectiveUpnl = upnl > 0 ? upnl : (upnl * lossCoverage) / 1e18`
* There is no balance changes in this liquidate function

### **2. Cross Party B Liquidation**

Used when Party B becomes insolvent in cross margin mode:

```solidity
// Flagging
flagCrossPartyBLiquidation(address partyB, address partyA, address collateral)

// Execution
liquidateCrossPartyB(address partyB, address partyA, address collateral, int256 upnl, uint256 collateralPrice)

// Unflagging
unflagCrossPartyBLiquidation(address partyB, address partyA, address collateral)
```

**Trigger Conditions:**

* When Party B’s cross loss of open trades with an specific Party A exceeded from loss coverage of cross balance.
* `crossBalance.balance + (effectiveUpnl * 1e18) / collateralPrice < 0`
* Where `effectiveUpnl = upnl > 0 ? upnl : (upnl * lossCoverage) / 1e18`

**Liquidation Process:**

* Remaining cross balance transferred to Party A via scheduled release
* All cross margin entries (balance, locked, totalMM) reset to zero
* Liquidation status advanced to `IN_PROGRESS`

### **3. Cross Party A Liquidation**

Used when Party A becomes insolvent in cross margin mode:

```solidity
// Flagging
flagPartyALiquidation(address partyA, address partyB, address collateral)

// Execution
liquidateCrossPartyA(uint256 liquidationId, int256 upnl, uint256 collateralPrice)

// Unflagging
unflagPartyALiquidation(address partyA, address partyB, address collateral)
```

**Trigger Conditions:**

* `(crossBalance.balance - totalMM) + (upnl * 1e18) / collateralPrice < 0`
* Party A's available balance insufficient to cover maintenance margin plus losses

**Liquidation Process:**

* Remaining cross balance transferred to Party B via scheduled release
* All cross margin entries reset to zero
* Liquidation proceeds to position closure phase

## Clearing House Operations

Clearing House also has some shared methods for closing, cancelling and balance changing.

### **Trade Closure During Liquidation**

```solidity
closeTrades(uint256 liquidationId, uint256[] memory tradeIds, uint256[] memory prices)
```

**Process:**

* All specified trades must belong to the liquidated parties
* Trades are closed at liquidator-provided prices
* Trade status changed to `LIQUIDATED`
* Associated close intents cancelled

### **Asset Confiscation**

```solidity
confiscatePartyA(uint256 liquidationId, uint256 amount)
confiscatePartyBWithdrawal(uint256 withdrawId)
```

**Party A Confiscation:**

* Removes specified amount from Party A's cross balance
* Used to cover liquidation costs and losses
* Requires sufficient available balance

**Party B Withdrawal Confiscation:**

* Cancels pending Party B withdrawals during liquidation
* Returns withdrawn amount to Party B's isolated balance
* Prevents capital flight during liquidation process

### **Collateral Distribution**

```solidity
distributeCollateral(
    address partyB,
    address collateral,
    MarginType marginType,
    address[] memory partyAs,
    uint256[] memory amounts
)
```

**Process:**

* Distributes Party B's remaining collateral among affected Party A accounts
* Uses scheduled release system for secure transfers
* Proportional distribution based on losses and exposure
* Ensures total distribution doesn't exceed available balance

### **Intent Cancellation During Liquidation**

#### **Open Intent Cancellation:**

```solidity
cancelOpenIntents(uint256[] memory intentIds)
```

#### **Close Intent Cancellation:**

```solidity
cancelCloseIntents(uint256[] memory intentIds)
```

**Cancellation Logic:**

* Only cancels intents involving insolvent parties
* Handles fees and premium refunds appropriately
* Expired intents processed through normal expiration flow
* Prevents further trading by liquidated accounts
