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)
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):
VAMMManager.swap() / mint() / burn()computes deltas (pricing side)CollateralEngine.updatePositionPostVAMMAction()applies deltas (custody side)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)
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:
worstCaseLossis the maximum potential loss under conservative assumptionsInputs 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→ safehealth = 1.0→ at thresholdhealth < 1.0→ liquidatable
Settlement
At Maturity
When a pool's term ends, positions can be settled:
Settlement Flow
Verify the pool has matured
block.timestamp >= termEndTimestampFetch the final variable factor from the APR oracle (accumulated VY over the term)
Compute settlement cashflow:
cashflow = fixedTokens * fixedFactor + variableTokens * variableFactor
Apply cashflow to margin:
If
cashflow > 0: credit the user’s margin balanceIf
cashflow < 0: debit the user’s margin balance (or trigger forced handling if margin is insufficient)
Clear the position state (reset balances, keep remaining margin)
Settlement Example
Position:
Notional:
100,000 USDCfixedTokenBalance = +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.01235variableFactor = 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
Check the account is liquidatable:
collateralValue < marginRequired(i.e.,health < 1.0)Close all LP positions (burn liquidity): for each position where
liquidity > 0, burn to remove in-range exposure and realize balances/fees.Transfer positions to the liquidator: the liquidator inherits the account’s fixed/variable balances (and any remaining position state, depending on design).
Transfer remaining margin collateral to the liquidator: move the remaining collateral out of the liquidated account (protocol rules may apply: penalties, fees, dust handling).
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
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:
Update position growth / mark-to-market (bring accounting current).
Recompute margin requirement.
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:
Verify the pool is not expired.
Enforce isolated margin mode constraints (if the account is isolated).
Apply position updates (fixed/variable deltas, fees, LP accounting).
Verify the margin requirement (revert if insufficient).
Key Takeaways
Central custody — All funds held by CollateralEngine
Sub-accounts — Isolate risk between strategies
Discount factors — Volatile collateral has haircuts
Worst case VY — Conservative margin calculations
Automatic settlement — At maturity, positions settle
Next Steps
Margin System — Detailed margin mechanics
Liquidations — Liquidation deep dive
API Reference — Full function reference
Last updated