ICfdEngine
Stateful CFD trading engine: processes orders, settles funding, and liquidates positions.
Functions
clearinghouse
Margin clearinghouse address used for account margin locking/unlocking
function clearinghouse() external view returns (address);
orderRouter
Current order router allowed to execute orders through the engine.
function orderRouter() external view returns (address);
USDC
Settlement token used for fees, margin, and payouts
function USDC() external view returns (IERC20);
lastMarkPrice
Last mark price observed by the engine (8 decimals)
function lastMarkPrice() external view returns (uint256);
processOrder
Settles funding and processes an open/close order at the given oracle price
function processOrder(
CfdTypes.Order memory order,
uint256 currentOraclePrice,
uint256 vaultDepthUsdc,
uint64 publishTime
) external;
Parameters
| Name | Type | Description |
|---|---|---|
order | CfdTypes.Order | Order to execute (contains accountId, market, direction, size) |
currentOraclePrice | uint256 | Mark price from the oracle (8 decimals) |
vaultDepthUsdc | uint256 | Available vault liquidity, used for open-interest caps (6 decimals) |
publishTime | uint64 | Oracle publish timestamp, used for funding rate accrual |
processOrderTyped
Router-facing order execution entrypoint with typed business-rule failures.
Reverts with CfdEngine__TypedOrderFailure for expected order invalidations so the
router can apply deterministic failed-order bounty policy without selector matching.
function processOrderTyped(
CfdTypes.Order memory order,
uint256 currentOraclePrice,
uint256 vaultDepthUsdc,
uint64 publishTime
) external;
previewOpenRevertCode
Returns the current open-path revert code using canonical vault depth and a caller-supplied oracle snapshot.
function previewOpenRevertCode(
bytes32 accountId,
CfdTypes.Side side,
uint256 sizeDelta,
uint256 marginDelta,
uint256 oraclePrice,
uint64 publishTime
) external view returns (uint8 code);
previewOpenFailurePolicyCategory
Returns the semantic commit-time policy category for the current open-path invalidation, if any.
function previewOpenFailurePolicyCategory(
bytes32 accountId,
CfdTypes.Side side,
uint256 sizeDelta,
uint256 marginDelta,
uint256 oraclePrice,
uint64 publishTime
) external view returns (CfdEnginePlanTypes.OpenFailurePolicyCategory category);
recordDeferredClearerBounty
Records a deferred clearer bounty when immediate vault payment is unavailable.
Deferred keeper bounties are later claimed as clearinghouse credit, not direct wallet transfer.
function recordDeferredClearerBounty(
address keeper,
uint256 amountUsdc
) external;
getDeferredClaimHead
function getDeferredClaimHead() external view returns (DeferredClaim memory claim);
getDeferredTraderStatus
function getDeferredTraderStatus(
bytes32 accountId
) external view returns (DeferredTraderStatus memory status);
getDeferredClearerStatus
function getDeferredClearerStatus(
address keeper
) external view returns (DeferredClearerStatus memory status);
reserveCloseOrderExecutionBounty
Reserves close-order execution bounty from free settlement first, then active position margin.
function reserveCloseOrderExecutionBounty(
bytes32 accountId,
uint256 amountUsdc,
address recipient
) external;
absorbRouterCancellationFee
Pulls router-custodied cancellation fees into protocol revenue.
function absorbRouterCancellationFee(
uint256 amountUsdc
) external;
recordRouterProtocolFee
Books router-delivered protocol-owned inflow as accumulated fees after the router has already paid the vault.
function recordRouterProtocolFee(
uint256 amountUsdc
) external;
liquidatePosition
Liquidates an undercollateralized position, returns keeper bounty in USDC
function liquidatePosition(
bytes32 accountId,
uint256 currentOraclePrice,
uint256 vaultDepthUsdc,
uint64 publishTime
) external returns (uint256 keeperBountyUsdc);
Parameters
| Name | Type | Description |
|---|---|---|
accountId | bytes32 | Account holding the position to liquidate |
currentOraclePrice | uint256 | Mark price from the oracle (8 decimals) |
vaultDepthUsdc | uint256 | Available vault liquidity (6 decimals) |
publishTime | uint64 | Oracle publish timestamp |
Returns
| Name | Type | Description |
|---|---|---|
keeperBountyUsdc | uint256 | Bounty paid to the liquidation keeper (6 decimals) |
previewLiquidation
Canonical liquidation preview using the vault’s current accounted depth.
function previewLiquidation(
bytes32 accountId,
uint256 oraclePrice
) external view returns (LiquidationPreview memory preview);
simulateLiquidation
Hypothetical liquidation simulation at a caller-supplied vault depth.
function simulateLiquidation(
bytes32 accountId,
uint256 oraclePrice,
uint256 vaultDepthUsdc
) external view returns (LiquidationPreview memory preview);
getSideState
Returns the accounting state for a given side.
function getSideState(
CfdTypes.Side side
) external view returns (SideState memory);
getMaxLiability
Worst-case directional liability after taking the max of bull/bear payout bounds.
function getMaxLiability() external view returns (uint256);
getAccountLedgerView
Compact per-account ledger view spanning clearinghouse, router escrow, and deferred trader payout state.
function getAccountLedgerView(
bytes32 accountId
) external view returns (AccountLedgerView memory viewData);
getAccountLedgerSnapshot
Expanded per-account ledger snapshot for debugging account health and settlement reachability across protocol components.
function getAccountLedgerSnapshot(
bytes32 accountId
) external view returns (AccountLedgerSnapshot memory snapshot);
getProtocolAccountingSnapshot
Canonical protocol-wide accounting snapshot across physical assets, liabilities, fees, bad debt, and deferred obligations.
function getProtocolAccountingSnapshot() external view returns (ProtocolAccountingSnapshot memory snapshot);
accumulatedFeesUsdc
Accumulated execution fees awaiting withdrawal (6 decimals)
function accumulatedFeesUsdc() external view returns (uint256);
getWithdrawalReservedUsdc
Total withdrawal reserve required by current protocol liabilities.
function getWithdrawalReservedUsdc() external view returns (uint256);
getHousePoolInputSnapshot
Canonical accounting snapshot consumed by HousePool.
function getHousePoolInputSnapshot(
uint256 markStalenessLimit
) external view returns (HousePoolInputSnapshot memory snapshot);
Parameters
| Name | Type | Description |
|---|---|---|
markStalenessLimit | uint256 | Normal live-market staleness limit configured by HousePool. |
getHousePoolStatusSnapshot
Canonical non-accounting market/status snapshot consumed by HousePool.
function getHousePoolStatusSnapshot() external view returns (HousePoolStatusSnapshot memory snapshot);
totalDeferredPayoutUsdc
Deferred profitable-close payouts still owed to traders.
function totalDeferredPayoutUsdc() external view returns (uint256);
totalDeferredClearerBountyUsdc
Deferred liquidation bounties still owed after failed immediate payout.
function totalDeferredClearerBountyUsdc() external view returns (uint256);
deferredClaimHeadId
function deferredClaimHeadId() external view returns (uint64);
getUnrealizedTraderPnl
Aggregate unrealized PnL of all open positions at lastMarkPrice. Positive = traders winning (house liability). Negative = traders losing (house asset).
function getUnrealizedTraderPnl() external view returns (int256);
getUnrealizedFundingPnl
Aggregate unrealized funding PnL across all open positions. Positive = traders are net funding receivers (vault liability).
function getUnrealizedFundingPnl() external view returns (int256);
getCappedFundingPnl
Aggregate unrealized funding PnL with negative per-side funding capped by backing margin. Positive = traders are net funding receivers after clipping uncollectible debts.
function getCappedFundingPnl() external view returns (int256);
getLiabilityOnlyFundingPnl
Aggregate funding liabilities only, excluding any trader debts owed to the vault. Used by withdrawal firewalls that must assume funding receivables are uncollectible until physically seized.
function getLiabilityOnlyFundingPnl() external view returns (uint256);
getVaultMtmAdjustment
Combined MtM liability: per-side (PnL + funding), clamped at zero. Positive = vault owes traders (unrealized liability). Zero = traders losing or neutral. Unrealized trader losses are not counted as vault assets.
function getVaultMtmAdjustment() external view returns (uint256);
lastMarkTime
Timestamp of the last mark price update
function lastMarkTime() external view returns (uint64);
hasLiveLiability
Returns true when the engine currently has open bounded liability that depends on mark freshness.
function hasLiveLiability() external view returns (bool);
syncFunding
Materializes accrued funding into storage so subsequent reads reflect current state.
function syncFunding() external;
updateMarkPrice
Push a fresh mark price without processing an order
function updateMarkPrice(
uint256 price,
uint64 publishTime
) external;
Parameters
| Name | Type | Description |
|---|---|---|
price | uint256 | New mark price (8 decimals) |
publishTime | uint64 | Oracle publish timestamp for the price update |
CAP_PRICE
Protocol cap price (8 decimals). Oracle prices are clamped to this.
function CAP_PRICE() external view returns (uint256);
isFadWindow
True during weekend FX closure or admin-configured FAD days
function isFadWindow() external view returns (bool);
fadMaxStaleness
Maximum oracle staleness allowed during FAD windows
function fadMaxStaleness() external view returns (uint256);
isOracleFrozen
True only when FX markets are actually closed and oracle freshness can be relaxed.
function isOracleFrozen() external view returns (bool);
hasOpenPosition
Returns true when the account currently has an open position.
function hasOpenPosition(
bytes32 accountId
) external view returns (bool);
getPositionSize
Returns the current position size for an account (18 decimals).
function getPositionSize(
bytes32 accountId
) external view returns (uint256);
getPositionSide
Returns the stored side for an open position.
function getPositionSide(
bytes32 accountId
) external view returns (CfdTypes.Side);
degradedMode
True when the engine has latched degraded mode after a close revealed insolvency.
function degradedMode() external view returns (bool);
fadDayOverrides
Whether a given day number is an admin-configured FAD override
function fadDayOverrides(
uint256 dayNumber
) external view returns (bool);
getProtocolPhase
function getProtocolPhase() external view returns (ProtocolPhase);
getProtocolStatus
function getProtocolStatus() external view returns (ProtocolStatus memory);
Errors
CfdEngine__TypedOrderFailure
error CfdEngine__TypedOrderFailure(
CfdEnginePlanTypes.ExecutionFailurePolicyCategory failureCategory, uint8 failureCode, bool isClose
);
CfdEngine__MarkPriceOutOfOrder
error CfdEngine__MarkPriceOutOfOrder();
Structs
AccountLedgerView
Compact per-account ledger view spanning trader-owned settlement buckets and router-reserved order state.
settlementBalanceUsdc, freeSettlementUsdc, activePositionMarginUsdc, otherLockedMarginUsdc, and
deferredPayoutUsdc are trader-owned value or obligations recorded by the protocol.
activePositionMarginUsdc is the canonical clearinghouse custody bucket for live position backing, while
engine economic position margin is exposed separately on AccountLedgerSnapshot.margin.
executionEscrowUsdc is router-custodied order bounty escrow attributed to the account.
committedMarginUsdc remains trader-owned settlement reserved for queued orders inside the clearinghouse.
struct AccountLedgerView {
uint256 settlementBalanceUsdc;
uint256 freeSettlementUsdc;
uint256 activePositionMarginUsdc;
uint256 otherLockedMarginUsdc;
uint256 executionEscrowUsdc;
uint256 committedMarginUsdc;
uint256 deferredPayoutUsdc;
uint256 pendingOrderCount;
}
AccountLedgerSnapshot
Expanded per-account ledger snapshot for debugging account health, reachability, and queued-order state.
Extends AccountLedgerView with typed clearinghouse locked-margin buckets, terminal settlement reachability,
equity, buying power, and live position risk.
margin is the engine’s economic position margin, while positionMarginBucketUsdc is the clearinghouse
custody bucket that should back it.
struct AccountLedgerSnapshot {
uint256 settlementBalanceUsdc;
uint256 freeSettlementUsdc;
uint256 activePositionMarginUsdc;
uint256 otherLockedMarginUsdc;
uint256 positionMarginBucketUsdc;
uint256 committedOrderMarginBucketUsdc;
uint256 reservedSettlementBucketUsdc;
uint256 executionEscrowUsdc;
uint256 committedMarginUsdc;
uint256 deferredPayoutUsdc;
uint256 pendingOrderCount;
uint256 closeReachableUsdc;
uint256 terminalReachableUsdc;
uint256 accountEquityUsdc;
uint256 freeBuyingPowerUsdc;
bool hasPosition;
CfdTypes.Side side;
uint256 size;
uint256 margin;
uint256 entryPrice;
int256 unrealizedPnlUsdc;
int256 pendingFundingUsdc;
int256 netEquityUsdc;
bool liquidatable;
}
ProtocolAccountingSnapshot
struct ProtocolAccountingSnapshot {
uint256 vaultAssetsUsdc;
uint256 netPhysicalAssetsUsdc;
uint256 maxLiabilityUsdc;
uint256 effectiveSolvencyAssetsUsdc;
uint256 withdrawalReservedUsdc;
uint256 freeUsdc;
uint256 accumulatedFeesUsdc;
uint256 accumulatedBadDebtUsdc;
int256 cappedFundingPnlUsdc;
uint256 liabilityOnlyFundingPnlUsdc;
uint256 totalDeferredPayoutUsdc;
uint256 totalDeferredClearerBountyUsdc;
bool degradedMode;
bool hasLiveLiability;
}
HousePoolInputSnapshot
struct HousePoolInputSnapshot {
uint256 physicalAssetsUsdc;
uint256 netPhysicalAssetsUsdc;
uint256 maxLiabilityUsdc;
uint256 withdrawalFundingLiabilityUsdc;
uint256 unrealizedMtmLiabilityUsdc;
uint256 deferredTraderPayoutUsdc;
uint256 deferredClearerBountyUsdc;
uint256 protocolFeesUsdc;
bool markFreshnessRequired;
uint256 maxMarkStaleness;
}
HousePoolStatusSnapshot
struct HousePoolStatusSnapshot {
uint64 lastMarkTime;
bool oracleFrozen;
bool degradedMode;
}
SideState
struct SideState {
uint256 maxProfitUsdc;
uint256 openInterest;
uint256 entryNotional;
uint256 totalMargin;
int256 fundingIndex;
int256 entryFunding;
}
LiquidationPreview
struct LiquidationPreview {
bool liquidatable;
uint256 oraclePrice;
int256 equityUsdc;
int256 pnlUsdc;
int256 fundingUsdc;
uint256 reachableCollateralUsdc;
uint256 keeperBountyUsdc;
uint256 seizedCollateralUsdc;
uint256 settlementRetainedUsdc;
uint256 freshTraderPayoutUsdc;
uint256 existingDeferredConsumedUsdc;
uint256 existingDeferredRemainingUsdc;
uint256 immediatePayoutUsdc;
uint256 deferredPayoutUsdc;
uint256 badDebtUsdc;
bool triggersDegradedMode;
bool postOpDegradedMode;
uint256 effectiveAssetsAfterUsdc;
uint256 maxLiabilityAfterUsdc;
int256 solvencyFundingPnlUsdc;
}
DeferredClaim
struct DeferredClaim {
DeferredClaimType claimType;
bytes32 accountId;
address keeper;
uint256 remainingUsdc;
uint64 prevClaimId;
uint64 nextClaimId;
}
DeferredTraderStatus
struct DeferredTraderStatus {
uint64 claimId;
uint256 deferredPayoutUsdc;
bool isHead;
bool claimableNow;
}
DeferredClearerStatus
struct DeferredClearerStatus {
uint64 claimId;
uint256 deferredBountyUsdc;
bool isHead;
bool claimableNow;
}
ProtocolStatus
struct ProtocolStatus {
ProtocolPhase phase;
uint64 lastMarkTime;
uint256 lastMarkPrice;
bool oracleFrozen;
bool fadWindow;
uint256 fadMaxStaleness;
}
Enums
DeferredClaimType
enum DeferredClaimType {
TraderPayout,
ClearerBounty
}
ProtocolPhase
High-level protocol lifecycle used by external status consumers.
Active means the engine is wired and the vault has enabled live risk-taking.
enum ProtocolPhase {
Configuring,
Active,
Degraded
}