Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

ICfdEngine

Git Source

Stateful CFD trading engine: processes orders and liquidates positions.

This remains a rich internal/admin integration interface. Product-facing consumers should prefer the slim public surfaces in IPerpsTraderActions, IPerpsTraderViews, IPerpsLPActions, IPerpsLPViews, IPerpsKeeper, IProtocolViews, and IMarginAccount. Live protocol contracts should prefer smaller role-specific interfaces like ICfdEngineCore.

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);

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;

recordDeferredKeeperCredit

Records deferred keeper credit when immediate clearinghouse settlement is unavailable.

Deferred keeper value is always later claimed as clearinghouse credit.

function recordDeferredKeeperCredit(
    address keeper,
    uint256 amountUsdc
) external;

reserveCloseOrderExecutionBounty

Reserves close-order execution bounty from free settlement first, then active position margin.

function reserveCloseOrderExecutionBounty(
    bytes32 accountId,
    uint256 sizeDelta,
    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;

creditKeeperExecutionBounty

Credits a keeper execution bounty into the beneficiary’s clearinghouse account.

Realizes carry first when the beneficiary account currently has an open position so the settlement-balance credit cannot retroactively dilute carry owed over the elapsed interval.

function creditKeeperExecutionBounty(
    address beneficiary,
    uint256 amountUsdc,
    uint256 price,
    uint64 publishTime
) 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

NameTypeDescription
accountIdbytes32Account holding the position to liquidate
currentOraclePriceuint256Mark price from the oracle (8 decimals)
vaultDepthUsdcuint256Available vault liquidity (6 decimals)
publishTimeuint64Oracle publish timestamp

Returns

NameTypeDescription
keeperBountyUsdcuint256Bounty paid to the liquidation keeper (6 decimals)

realizeCarryBeforeMarginChange

Realizes accrued carry against the current reachable collateral before a user-level settlement balance mutation changes the carry basis.

function realizeCarryBeforeMarginChange(
    bytes32 accountId,
    uint256 reachableCollateralBasisUsdc
) external;

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);

accumulatedFeesUsdc

Accumulated execution fees awaiting withdrawal (6 decimals)

function accumulatedFeesUsdc() external view returns (uint256);

totalDeferredTraderCreditUsdc

Deferred trader credit still owed to beneficiaries.

function totalDeferredTraderCreditUsdc() external view returns (uint256);

totalDeferredKeeperCreditUsdc

Deferred keeper credit still owed after failed immediate settlement.

function totalDeferredKeeperCreditUsdc() external view returns (uint256);

lastMarkTime

Timestamp of the last mark price update

function lastMarkTime() external view returns (uint64);

updateMarkPrice

Pushes a fresh mark price without processing an order.

This updates the cached mark only; carry is realized on execution and margin-mutating paths.

function updateMarkPrice(
    uint256 price,
    uint64 publishTime
) external;

Parameters

NameTypeDescription
priceuint256New mark price (8 decimals)
publishTimeuint64Oracle 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);

positions

Returns the current position tuple for an account.

function positions(
    bytes32 accountId
)
    external
    view
    returns (
        uint256 size,
        uint256 margin,
        uint256 entryPrice,
        uint256 maxProfitUsdc,
        CfdTypes.Side side,
        uint64 lastUpdateTime,
        int256 vpiAccrued
    );

getPositionLastCarryTimestamp

Returns the timestamp through which carry has been realized for the position.

function getPositionLastCarryTimestamp(
    bytes32 accountId
) external view returns (uint64);

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);

getProtocolStatus

function getProtocolStatus() external view returns (EngineStatusViewTypes.ProtocolStatus memory);

Errors

CfdEngine__TypedOrderFailure

error CfdEngine__TypedOrderFailure(
    CfdEnginePlanTypes.ExecutionFailurePolicyCategory failureCategory, uint8 failureCode, bool isClose
);

CfdEngine__MarkPriceOutOfOrder

error CfdEngine__MarkPriceOutOfOrder();

Structs

SideState

struct SideState {
    uint256 maxProfitUsdc;
    uint256 openInterest;
    uint256 entryNotional;
    uint256 totalMargin;
}

LiquidationPreview

struct LiquidationPreview {
    bool liquidatable;
    uint256 oraclePrice;
    int256 equityUsdc;
    int256 pnlUsdc;
    uint256 reachableCollateralUsdc;
    uint256 keeperBountyUsdc;
    uint256 seizedCollateralUsdc;
    uint256 settlementRetainedUsdc;
    uint256 freshTraderPayoutUsdc;
    uint256 existingDeferredConsumedUsdc;
    uint256 existingDeferredRemainingUsdc;
    uint256 immediatePayoutUsdc;
    uint256 deferredTraderCreditUsdc;
    uint256 badDebtUsdc;
    bool triggersDegradedMode;
    bool postOpDegradedMode;
    uint256 effectiveAssetsAfterUsdc;
    uint256 maxLiabilityAfterUsdc;
}

Enums

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
}