Collateral Engine V1

TL;DR: The Collateral Engine is XCCY's central bank — it holds all user funds, manages positions, calculates margin requirements, handles settlements, and executes liquidations.

Collateral Engine — Overview

The Collateral Engine is the protocol’s custodian and the enforcement point for account-level safety. It is the single source of truth for user funds and positions, and it coordinates settlement and liquidations.

At a high level, it covers six responsibilities:

  • Custody: holds all user collateral and applies deposits/withdrawals.

  • Positions: tracks all open positions (trader and LP) and their balances.

  • Risk enforcement: triggers margin requirement checks and blocks unsafe state changes.

  • Settlement: finalizes positions at maturity (realizes PnL and closes exposure).

  • Liquidation: force-closes or transfers positions when an account becomes liquidatable.

  • Oracle integration: consumes validated price/rate inputs (typically via OracleHub) for valuation and risk checks.

We can come up with the following mental model:

  • The vAMM decides “what the price/rate is” and outputs deltas.

  • The Collateral Engine decides “can the user afford it” and applies deltas only if the account remains collateralized.

Account Structure

Account ID

Users are identified by a composite key:

Sub-Accounts

A single wallet can create multiple isolated sub-accounts, each with independent collateral and independent risk.

Example:

  • Sub-account 0 (Cross margin): can hold multiple collateral types; positions share a common margin pool.

  • Sub-account 1 (USDC isolated): only USDC counts as margin; risk is isolated from other sub-accounts.

  • Sub-account 2 (ETH isolated): only ETH counts as margin; risk is isolated from other sub-accounts.

Why sub-accounts exist

  • Risk isolation between strategies (one strategy blowing up does not drain everything).

  • Different collateral policies per sub-account (cross vs isolated).

  • Independent margin and liquidation boundaries per sub-account.

Margin Management

Depositing Margin

Example:

Collateral Valuation

Not all collateral is valued equally. Each collateral asset is assigned a discount factor (haircut) to account for volatility and liquidation risk.

Collateral value (USD):

collateralValue = balance * priceUsd * discountFactor

Discount factors (example)

Asset
Discount factor
Interpretation

USDC

1.00

Full value

USDT

0.99

Minor haircut

ETH

0.95

Volatility haircut

WBTC

0.8

Higher volatility haircut

Why discount factors exist

Volatile assets can lose value quickly during stress. Haircuts create a buffer so liquidators have enough room to repay obligations without taking loss from fast-moving collateral.

Position Tracking

Position Structure

Position updates

Whenever a trader swaps or an LP mints/burns liquidity, the Collateral Engine updates the position and enforces safety.

Execution flow (conceptual):

  1. VAMMManager.swap() / mint() / burn() computes deltas (pricing side)

  2. CollateralEngine.updatePositionPostVAMMAction() applies deltas (custody side)

  3. Risk check runs and either accepts or reverts the update

CollateralEngine.updatePositionPostVAMMAction() typically performs:

  • Update fixed/variable token balances

  • Deduct trading fees from margin (if applicable)

  • Update LP fee growth / accumulated fees (if applicable)

  • Trigger a margin requirement check (worst-case)

spinner

Margin Requirements

Calculation

The protocol calculates how much margin each account needs by simulating the worst-case loss at maturity.

Conceptual formula:

marginRequiredUsd = worstCaseLoss * priceUsd

Where:

  • worstCaseLoss is the maximum potential loss under conservative assumptions

  • Inputs include notional, term length, fixed yield locked, and bounds on variable yield

Worst Case Variable Factor

The protocol maintains two conservative variable-yield assumptions per pool:

  • worstCaseVariableFactorPositive: used when the position is receiving VY (variableTokenBalance > 0)

    Worst case: VY drops (receiver earns less than expected)

  • worstCaseVariableFactorNegative: used when the position is paying VY (variableTokenBalance < 0)

    Worst case: VY rises (payer pays more than expected)

This makes margin requirements depend on position direction, not on a single “expected” rate.

Health Check

Health factor:

health = collateralValue / marginRequired

  • health > 1.0 → safe

  • health = 1.0 → at threshold

  • health < 1.0 → liquidatable

Settlement

At Maturity

When a pool's term ends, positions can be settled:

Settlement Flow

  1. Verify the pool has matured block.timestamp >= termEndTimestamp

  2. Fetch the final variable factor from the APR oracle (accumulated VY over the term)

  3. Compute settlement cashflow:

cashflow = fixedTokens * fixedFactor + variableTokens * variableFactor

  1. Apply cashflow to margin:

  • If cashflow > 0: credit the user’s margin balance

  • If cashflow < 0: debit the user’s margin balance (or trigger forced handling if margin is insufficient)

  1. Clear the position state (reset balances, keep remaining margin)

spinner

Settlement Example

Position:

  • Notional: 100,000 USDC

  • fixedTokenBalance = +100,000 (receiving 5% FY)

  • variableTokenBalance = -100,000 (paying VY)

  • Term: 90 days

Time factor:

timeFactor = 90 / 365 = 0.247

Assume at maturity:

  • FY = 5%

  • VY averaged = 3%

Compute factors:

  • fixedFactor = timeFactor * FY = 0.247 * 0.05 = 0.01235

  • variableFactor = timeFactor * VY = 0.247 * 0.03 = 0.00741

Cashflow:

cashflow = fixedTokens * fixedFactor + variableTokens * variableFactor

cashflow = 100,000 * 0.01235 + (-100,000) * 0.00741 cashflow = 1,235 - 741 cashflow = +494 USDC

Result: the user realizes +494 USDC profit, which is credited to their margin balance.

Liquidation

When Liquidation Occurs

Accounts are liquidatable when Collateral Value < Margin Requirement

Liquidation Process

Flow

  1. Check the account is liquidatable: collateralValue < marginRequired (i.e., health < 1.0)

  2. Close all LP positions (burn liquidity): for each position where liquidity > 0, burn to remove in-range exposure and realize balances/fees.

  3. Transfer positions to the liquidator: the liquidator inherits the account’s fixed/variable balances (and any remaining position state, depending on design).

  4. Transfer remaining margin collateral to the liquidator: move the remaining collateral out of the liquidated account (protocol rules may apply: penalties, fees, dust handling).

  5. Clear the original account: reset balances and positions to zero to finalize liquidation.

Liquidator Incentive

Liquidators receive:

  • All remaining margin from liquidated account

  • All positions (which may have value)

  • Opportunity to profit if positions are profitable

Oracle Integration

Price Oracle (OracleHub)

Used for:

  • Collateral valuation

  • Cross-asset margin calculations

Rate Oracle (AprOracle)

Used for:

  • Settlement calculations (final VY)

  • Margin requirement estimation

Key Functions

Function
Purpose

updateAccountMargin()

Deposit/withdraw collateral

updatePositionPostVAMMAction()

Update positions after trades

checkMarginRequirement()

Verify margin sufficiency

settlePosition()

Process maturity settlement

liquidateAccount()

Force close underwater accounts

setMarginTokenWhitelist()

Admin: configure collateral

setWorstCaseVariableFactor()

Admin: set VY bounds

Storage Layout

Security Considerations

Access Control

  • updateAccountMargin(): only the account owner can deposit/withdraw collateral.

  • updatePositionPostVAMMAction(): only VAMMManager can call (prevents arbitrary position mutation).

  • liquidateAccount(): permissionless — anyone can liquidate an account only if it is underwater.

  • Admin functions: restricted to the contract owner (or governance), for parameter/config changes.

Safety Checks

Withdrawal

On withdrawal, the system must ensure the account remains safe after funds are removed:

  1. Update position growth / mark-to-market (bring accounting current).

  2. Recompute margin requirement.

  3. Revert if margin would be insufficient post-withdrawal.

Trade (swap / mint / burn)

On any position-changing action, the system enforces preconditions and a final safety check:

  1. Verify the pool is not expired.

  2. Enforce isolated margin mode constraints (if the account is isolated).

  3. Apply position updates (fixed/variable deltas, fees, LP accounting).

  4. Verify the margin requirement (revert if insufficient).

Key Takeaways

  1. Central custody — All funds held by CollateralEngine

  2. Sub-accounts — Isolate risk between strategies

  3. Discount factors — Volatile collateral has haircuts

  4. Worst case VY — Conservative margin calculations

  5. Automatic settlement — At maturity, positions settle

Next Steps

  • Margin System — Detailed margin mechanics

  • Liquidations — Liquidation deep dive

  • API Reference — Full function reference

Last updated