# View Facet

## View Facet (0.8.5)

The View Facet provides read-only functions for querying protocol state. It exposes balance information, configuration parameters, liquidation details, pause states, withdrawal requests, and various status checks. All functions are `view` and do not modify state.

***

### Overview

The View Facet is organized into the following categories:

* **Ownership:** Diamond owner and pending owner.
* **Balances & Allocation:** User balances, PartyA/PartyB allocated balances, locked values, and cross-mode balances.
* **Nonces & Cooldowns:** Party nonces, deallocation timestamps, withdrawal cooldowns, and various protocol cooldown parameters.
* **Liquidation:** Liquidation status, details, settlement states, insurance vault parameters, cross liquidation details, and PartyA takeover details.
* **Pause State:** Global and per-subsystem pause states, emergency mode, PartyB emergency status.
* **Roles & Access:** Role checks, role admin checks, role hash computation.
* **Protocol Configuration:** Collateral address, fee collectors, Muon configuration, balance limits, signature verifier, and various protocol parameters.
* **Quotes & Positions:** Force close details, pending quotes length.
* **Symbols & Affiliates:** Affiliate fees (with full resolution priority), affiliate hooks, minimum fees, ADL status.
* **Withdrawal System:** Withdraw requests (single, batch, pending-only), provider registration, speed-up eligibility, cooldown end times, locked balance.
* **Cross PartyB:** Cross-mode status, cross balance info, migration status.
* **Binding & Instant Layer:** Bind state, instant layer call detection, bindable PartyB status.
* **External Transfers:** Virtual external transfer requests.
* **Bridge:** Bridge transactions, next transaction ID.
* **Funding:** Legacy funding deprecation status, accumulated funding activation status.
* **Solvency Previews:** `getMaxCloseAmountToLiquidation` for previewing partial close amounts.

***

### Ownership

| Function         | Returns                                                 |
| ---------------- | ------------------------------------------------------- |
| `owner()`        | Diamond contract owner address                          |
| `pendingOwner()` | Pending owner address (for two-step ownership transfer) |

***

### Balances & Allocation

| Function                                                       | Parameters               | Returns                                                                                                    |
| -------------------------------------------------------------- | ------------------------ | ---------------------------------------------------------------------------------------------------------- |
| `balanceOf(address user)`                                      | User address             | User's free (unallocated) balance                                                                          |
| `allocatedBalanceOfPartyA(address partyA)`                     | PartyA address           | PartyA's allocated balance                                                                                 |
| `allocatedBalanceOfPartyB(address partyB, address partyA)`     | PartyB, PartyA           | PartyB's allocated balance for a specific PartyA                                                           |
| `allocatedBalanceOfPartyBs(address partyA, address[] partyBs)` | PartyA, array of PartyBs | Array of allocated balances for each PartyB                                                                |
| `balanceOfCrossPartyB(address partyB)`                         | PartyB address           | Cross-mode aggregated allocated balance (`address(0)` bucket)                                              |
| `balanceInfoOfPartyA(address partyA)`                          | PartyA address           | Allocated balance, locked values (cva, lf, partyAmm, partyBmm), and pending locked values                  |
| `balanceInfoOfPartyB(address partyB, address partyA)`          | PartyB, PartyA           | Same as above but for a PartyB-PartyA pair                                                                 |
| `balanceInfoOfCrossPartyB(address partyB)`                     | PartyB address           | Same as above but for the cross bucket (`address(0)`)                                                      |
| `partyAStats(address partyA)`                                  | PartyA address           | Comprehensive stats: liquidation status, balances, locked values, position counts, nonces, quote IDs count |
| `partyAReimbursement(address partyA)`                          | PartyA address           | Reimbursement amount escrowed during ClearingHouse liquidation                                             |

***

### Nonces & Cooldowns

| Function                                                                                  | Parameters      | Returns                                                                                           |
| ----------------------------------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------- |
| `nonceOfPartyA(address partyA)`                                                           | PartyA address  | PartyA's current nonce                                                                            |
| `nonceOfPartyB(address partyB, address partyA)`                                           | PartyB, PartyA  | PartyB's nonce (per-PartyA or cross)                                                              |
| `withdrawCooldownOf(address user)`                                                        | User address    | Timestamp of user's most recent deallocation                                                      |
| `getWithdrawableTime(address user)`                                                       | User address    | Earliest time a withdrawal initiated now could be finalized                                       |
| `coolDownsOfMA()`                                                                         | —               | Withdraw cooldown, force cancel cooldown, force cancel close cooldown, force close first cooldown |
| `forceCloseCooldowns()`                                                                   | —               | Force close first and second cooldowns                                                            |
| `deallocateCooldown()`                                                                    | —               | Withdraw cooldown period                                                                          |
| `settlementCooldown()`                                                                    | —               | Settlement cooldown                                                                               |
| `unbindCooldown()`                                                                        | —               | Unbind cooldown for oracle-less trading                                                           |
| `getDeallocateDebounceTime()`                                                             | —               | Debounce time between deallocations                                                               |
| `lastUpnlSettlementTimestamp(address senderPartyB, address targetPartyB, address partyA)` | Three addresses | Last settlement timestamp for the given combination                                               |

***

### Liquidation

| Function                                                     | Parameters               | Returns                                                   |
| ------------------------------------------------------------ | ------------------------ | --------------------------------------------------------- |
| `isPartyALiquidated(address partyA)`                         | PartyA address           | Whether PartyA is in liquidation                          |
| `isPartyBLiquidated(address partyB, address partyA)`         | PartyB, PartyA           | Whether PartyB is in liquidation for this PartyA          |
| `getLiquidatedStateOfPartyA(address partyA)`                 | PartyA address           | Full `LiquidationDetail` struct                           |
| `getSettlementStates(address partyA, address[] partyBs)`     | PartyA, array of PartyBs | Settlement states for each PartyB                         |
| `getLiquidationInsuranceVaultParams()`                       | —                        | Insurance vault address and max profit per position       |
| `getPartyBCrossLiquidationStatus(address partyB)`            | PartyB address           | Whether PartyB is in cross liquidation                    |
| `getCrossLiquidationDetails(address partyB)`                 | PartyB address           | Full `CrossLiquidationDetail` struct                      |
| `getPartyATakeoverDetails(address partyA)`                   | PartyA address           | `PartyATakeoverDetail` struct for ClearingHouse takeovers |
| `liquidatorShare()`                                          | —                        | Liquidator share percentage                               |
| `liquidationTimeout()`                                       | —                        | Liquidation timeout period                                |
| `partyBLiquidationTimestamp(address partyB, address partyA)` | PartyB, PartyA           | When PartyB liquidation was initiated                     |

***

### Pause State

| Function                                   | Returns                                                                                                                                                                |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pauseState()`                             | Tuple of all pause flags: global, liquidation, accounting, partyB actions, partyA actions, internal transfer, external transfer, emergency mode, partyB open positions |
| `getPartyBEmergencyStatus(address partyB)` | Whether PartyB has emergency status                                                                                                                                    |

***

### Roles & Access

| Function                                  | Parameters       | Returns                               |
| ----------------------------------------- | ---------------- | ------------------------------------- |
| `hasRole(address user, bytes32 role)`     | User, role hash  | Whether user has the role             |
| `isRoleAdmin(address user, bytes32 role)` | User, role hash  | Whether user is an admin for the role |
| `getRoleHash(string str)`                 | Role name string | `keccak256` hash of the role name     |

***

### Protocol Configuration

| Function                               | Returns                                        |
| -------------------------------------- | ---------------------------------------------- |
| `getCollateral()`                      | Collateral token address                       |
| `getFeeCollector(address affiliate)`   | Fee collector address for a specific affiliate |
| `getDefaultFeeCollector()`             | Default fee collector address                  |
| `getBalanceLimitPerUser()`             | Maximum balance allowed per user               |
| `getSignatureVerifier()`               | Muon signature verifier contract address       |
| `getMuonConfig()`                      | UPNL validity time and price validity time     |
| `getMuonIds()`                         | Muon application ID                            |
| `pendingQuotesValidLength()`           | Maximum number of valid pending quotes         |
| `forceClosePricePenalty()`             | Price penalty applied during force close       |
| `forceCloseMinSigPeriod()`             | Minimum signature period for force close       |
| `maxConnectedCounterParty()`           | Maximum PartyA-to-PartyB connection count      |
| `getSoftLiquidationPenaltyCollector()` | Address receiving soft liquidation penalties   |
| `getInvalidBridgedAmountsPool()`       | Address receiving invalid bridged amounts      |

***

### Symbols & Affiliates

| Function                                                                    | Parameters              | Returns                                                                                                                 |
| --------------------------------------------------------------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `getFeeForUser(address affiliate, address user, uint256 symbolId)`          | Affiliate, user, symbol | Resolved `Fee` struct using the full priority chain (user+symbol → user default → symbol → default → symbol tradingFee) |
| `getAffiliateFeeForUser(address affiliate, address user, uint256 symbolId)` | Affiliate, user, symbol | Fee struct for user-specific level only                                                                                 |
| `getAffiliateFee(address affiliate, uint256 symbolId)`                      | Affiliate, symbol       | Fee struct for affiliate-level only                                                                                     |
| `getMinAffiliateFee()`                                                      | —                       | Minimum affiliate fee threshold                                                                                         |
| `getAffiliateHook(address affiliate)`                                       | Affiliate address       | Hook contract address                                                                                                   |
| `isAffiliate(address affiliate)`                                            | Address                 | Whether the address is a registered affiliate                                                                           |
| `isADLEnabled(address partyB)`                                              | PartyB address          | Whether ADL is enabled for the PartyB                                                                                   |

***

### Withdrawal System

| Function                                                                | Parameters                 | Returns                                                                                |
| ----------------------------------------------------------------------- | -------------------------- | -------------------------------------------------------------------------------------- |
| `getWithdrawRequests(address user, uint256 requestId)`                  | User, request ID           | Single `WithdrawRequest` struct                                                        |
| `getLastWithdrawRequestId(address user)`                                | User address               | Last assigned request ID (0 = no requests)                                             |
| `getWithdrawRequestsBatch(address user, uint256 start, uint256 size)`   | User, start ID, batch size | Array of all requests in range (any status)                                            |
| `getPendingWithdrawRequests(address user, uint256 start, uint256 size)` | User, start ID, scan size  | Only non-terminal requests (PENDING, PROVIDER\_ACCEPTED, CANCEL\_REQUESTED, SUSPENDED) |
| `isExpressProviderRegistered(address provider)`                         | Provider address           | Whether the address is a registered express provider                                   |
| `isVirtualProviderRegistered(address provider)`                         | Provider address           | Whether the address is a registered virtual provider                                   |
| `isSpeedUpEligible(address user)`                                       | User address               | Whether the user is on the speed-up whitelist                                          |
| `getModifiedCooldownEndTime(address user, uint256 requestId)`           | User, request ID           | Modified cooldown end time (reverts if not modified)                                   |
| `getWithdrawLockedBalance()`                                            | —                          | Total collateral locked for pending withdrawals                                        |

***

### Cross PartyB

| Function                                         | Parameters     | Returns                                          |
| ------------------------------------------------ | -------------- | ------------------------------------------------ |
| `isCrossPartyB(address partyB)`                  | PartyB address | Whether cross mode is enabled                    |
| `isCrossPartyBModeActivated()`                   | —              | Whether the global cross mode feature flag is on |
| `isCrossPartyBMigrationComplete(address partyB)` | PartyB address | Whether locked-values migration is complete      |

***

### Binding & Instant Layer

| Function                     | Parameters     | Returns                                                           |
| ---------------------------- | -------------- | ----------------------------------------------------------------- |
| `getBindState(address user)` | User address   | `BindState` struct (status, bound PartyB, timestamps)             |
| `isBindable(address partyB)` | PartyB address | Whether PartyB is bindable for oracle-less trading                |
| `isCallFromInstantLayer()`   | —              | Whether the current call originates from the Instant Layer        |
| `getSigner()`                | —              | Effective signer address (falls back to `msg.sender` if none set) |

***

### External Transfers & Bridge

| Function                                                             | Parameters                 | Returns                                 |
| -------------------------------------------------------------------- | -------------------------- | --------------------------------------- |
| `getVirtualExternalTransfer(uint256 id)`                             | Transfer ID                | `VirtualExternalTransferRequest` struct |
| `getBridgeTransaction(uint256 transactionId)`                        | Transaction ID             | `BridgeTransaction` struct              |
| `getBridgeTransactions(address bridge, uint256 start, uint256 size)` | Bridge address, pagination | Array of `BridgeTransaction` structs    |
| `getNextBridgeTransactionId()`                                       | —                          | Next bridge transaction ID              |

***

### Funding

| Function                          | Returns                                                           |
| --------------------------------- | ----------------------------------------------------------------- |
| `isLegacyFundingDeprecated()`     | Whether legacy per-quote funding is deprecated                    |
| `isAccumulatedFundingActivated()` | Whether accumulated funding mode is active                        |
| `isLegacyDeallocateDeprecated()`  | Whether legacy deallocate is deprecated (must use safeDeallocate) |

***

### Solvency Previews

#### getMaxCloseAmountToLiquidation()

Preview function for `fillCloseRequestToLiquidation`. Calculates the maximum close amount that keeps PartyA at the liquidation threshold without submitting a transaction.

**Function Signature:**

```solidity
function getMaxCloseAmountToLiquidation(
    uint256 quoteId,
    uint256 closedPrice,
    uint256 marketPrice,
    int256 upnlPartyA
) external view returns (uint256 maxCloseAmount, bool canCloseAll);
```

**Parameters:**

* `quoteId`: The quote with a pending close request.
* `closedPrice`: The price at which the position would be closed.
* `marketPrice`: The current market price.
* `upnlPartyA`: PartyA's unrealized PnL.

**Returns:**

* `maxCloseAmount`: The maximum amount that can be closed while keeping PartyA solvent.
* `canCloseAll`: Whether the full `quantityToClose` can be closed without insolvency.

***

### Muon Verification

#### verifyMuonTSSAndGateway()

Utility function to verify a Muon TSS and gateway signature against a hash. Reverts if verification fails.

```solidity
function verifyMuonTSSAndGateway(bytes32 hash, SchnorrSign memory sign, bytes memory gatewaySignature) external view;
```
