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

CfdEngine

Git Source

Inherits: IWithdrawGuard, Ownable2Step, ReentrancyGuardTransient

Title: CfdEngine

The core mathematical ledger for Plether CFDs.

Settles all funds through the MarginClearinghouse and CfdVault.

Note: security-contact: contact@plether.com

Constants

CAP_PRICE

uint256 public immutable CAP_PRICE

USDC

IERC20 public immutable USDC

clearinghouse

IMarginClearinghouse public immutable clearinghouse

EXECUTION_FEE_BPS

uint256 public constant EXECUTION_FEE_BPS = 4

TIMELOCK_DELAY

uint256 public constant TIMELOCK_DELAY = 48 hours

State Variables

vault

ICfdVault public vault

sides

SideState[2] public sides

lastMarkPrice

uint256 public lastMarkPrice

lastMarkTime

uint64 public lastMarkTime

accumulatedFeesUsdc

uint256 public accumulatedFeesUsdc

accumulatedBadDebtUsdc

uint256 public accumulatedBadDebtUsdc

degradedMode

bool public degradedMode

lastFundingTime

uint64 public lastFundingTime

riskParams

CfdTypes.RiskParams public riskParams

_positions

mapping(bytes32 => StoredPosition) internal _positions

deferredPayoutUsdc

mapping(bytes32 => uint256) public deferredPayoutUsdc

totalDeferredPayoutUsdc

uint256 public totalDeferredPayoutUsdc

deferredClearerBountyUsdc

mapping(address => uint256) public deferredClearerBountyUsdc

totalDeferredClearerBountyUsdc

uint256 public totalDeferredClearerBountyUsdc

deferredClaims

mapping(uint64 => ICfdEngine.DeferredClaim) public deferredClaims

nextDeferredClaimId

uint64 public nextDeferredClaimId = 1

deferredClaimHeadId

uint64 public deferredClaimHeadId

deferredClaimTailId

uint64 public deferredClaimTailId

traderDeferredClaimIdByAccount

mapping(bytes32 => uint64) public traderDeferredClaimIdByAccount

clearerDeferredClaimIdByKeeper

mapping(address => uint64) public clearerDeferredClaimIdByKeeper

orderRouter

address public orderRouter

fadDayOverrides

mapping(uint256 => bool) public fadDayOverrides

fadMaxStaleness

uint256 public fadMaxStaleness = 3 days

fadRunwaySeconds

uint256 public fadRunwaySeconds = 3 hours

engineMarkStalenessLimit

uint256 public engineMarkStalenessLimit = 60

pendingRiskParams

CfdTypes.RiskParams public pendingRiskParams

riskParamsActivationTime

uint256 public riskParamsActivationTime

_pendingAddFadDays

uint256[] private _pendingAddFadDays

addFadDaysActivationTime

uint256 public addFadDaysActivationTime

_pendingRemoveFadDays

uint256[] private _pendingRemoveFadDays

removeFadDaysActivationTime

uint256 public removeFadDaysActivationTime

pendingFadMaxStaleness

uint256 public pendingFadMaxStaleness

fadMaxStalenessActivationTime

uint256 public fadMaxStalenessActivationTime

pendingFadRunway

uint256 public pendingFadRunway

fadRunwayActivationTime

uint256 public fadRunwayActivationTime

pendingEngineMarkStalenessLimit

uint256 public pendingEngineMarkStalenessLimit

engineMarkStalenessActivationTime

uint256 public engineMarkStalenessActivationTime

Functions

_sideIndex

function _sideIndex(
    CfdTypes.Side side
) internal pure returns (uint256);

_sideState

function _sideState(
    CfdTypes.Side side
) internal view returns (SideState storage state);

_oppositeSide

function _oppositeSide(
    CfdTypes.Side side
) internal pure returns (CfdTypes.Side);

_sideAndOppositeStates

function _sideAndOppositeStates(
    CfdTypes.Side side
) internal view returns (SideState storage selected, SideState storage opposite);

_bullAndBearStates

function _bullAndBearStates() internal view returns (SideState storage bullState, SideState storage bearState);

getSideState

function getSideState(
    CfdTypes.Side side
) public view returns (ICfdEngine.SideState memory state);

_requireTimelockReady

function _requireTimelockReady(
    uint256 activationTime
) internal view;

onlyRouter

modifier onlyRouter() ;

constructor

constructor(
    address _usdc,
    address _clearinghouse,
    uint256 _capPrice,
    CfdTypes.RiskParams memory _riskParams
) Ownable(msg.sender);

Parameters

NameTypeDescription
_usdcaddressUSDC token used as margin and settlement currency
_clearinghouseaddressMargin clearinghouse that custodies trader balances
_capPriceuint256Maximum oracle price — positions are clamped here (also determines BULL max profit)
_riskParamsCfdTypes.RiskParamsInitial risk parameters (margin requirements, funding curve, bounty config)

setVault

One-time setter for the HousePool vault backing all positions

function setVault(
    address _vault
) external onlyOwner;

setOrderRouter

One-time setter for the authorized OrderRouter

function setOrderRouter(
    address _router
) external onlyOwner;

proposeRiskParams

Proposes new risk parameters (margin BPS, funding curve, bounty config) subject to timelock

function proposeRiskParams(
    CfdTypes.RiskParams memory _riskParams
) external onlyOwner;

finalizeRiskParams

Applies proposed risk parameters after timelock expires; settles funding first

function finalizeRiskParams() external onlyOwner;

cancelRiskParamsProposal

Cancels a pending risk parameters proposal

function cancelRiskParamsProposal() external onlyOwner;

proposeAddFadDays

Proposes adding FAD (Friday Afternoon Deleverage) override days — elevated margin on those dates

function proposeAddFadDays(
    uint256[] calldata timestamps
) external onlyOwner;

finalizeAddFadDays

Applies proposed FAD day additions after timelock expires

function finalizeAddFadDays() external onlyOwner;

cancelAddFadDaysProposal

Cancels a pending add-FAD-days proposal

function cancelAddFadDaysProposal() external onlyOwner;

proposeRemoveFadDays

Proposes removing FAD override days (restores normal margin on those dates)

function proposeRemoveFadDays(
    uint256[] calldata timestamps
) external onlyOwner;

finalizeRemoveFadDays

Applies proposed FAD day removals after timelock expires

function finalizeRemoveFadDays() external onlyOwner;

cancelRemoveFadDaysProposal

Cancels a pending remove-FAD-days proposal

function cancelRemoveFadDaysProposal() external onlyOwner;

proposeFadMaxStaleness

Proposes a new fadMaxStaleness — max age of the last mark price before FAD kicks in

function proposeFadMaxStaleness(
    uint256 _seconds
) external onlyOwner;

finalizeFadMaxStaleness

Applies proposed fadMaxStaleness after timelock expires

function finalizeFadMaxStaleness() external onlyOwner;

cancelFadMaxStalenessProposal

Cancels a pending fadMaxStaleness proposal

function cancelFadMaxStalenessProposal() external onlyOwner;

proposeFadRunway

Proposes a new fadRunway — how many seconds before an FAD day the elevated margin activates

function proposeFadRunway(
    uint256 _seconds
) external onlyOwner;

finalizeFadRunway

Applies proposed fadRunway after timelock expires

function finalizeFadRunway() external onlyOwner;

cancelFadRunwayProposal

Cancels a pending fadRunway proposal

function cancelFadRunwayProposal() external onlyOwner;

proposeEngineMarkStalenessLimit

function proposeEngineMarkStalenessLimit(
    uint256 newStaleness
) external onlyOwner;

finalizeEngineMarkStalenessLimit

function finalizeEngineMarkStalenessLimit() external onlyOwner;

cancelEngineMarkStalenessLimitProposal

function cancelEngineMarkStalenessLimitProposal() external onlyOwner;

withdrawFees

Withdraws accumulated execution fees from the vault to a recipient

function withdrawFees(
    address recipient
) external onlyOwner;

absorbRouterCancellationFee

Pulls router-custodied cancellation fees into the vault and books them as protocol revenue.

function absorbRouterCancellationFee(
    uint256 amountUsdc
) external onlyRouter;

recordRouterProtocolFee

Books router-delivered protocol-owned inflow as protocol fees after the router has already synced funding and funded the vault.

function recordRouterProtocolFee(
    uint256 amountUsdc
) external onlyRouter;

addMargin

Adds isolated margin to an existing open position without changing size.

function addMargin(
    bytes32 accountId,
    uint256 amount
) external nonReentrant;

claimDeferredPayout

Claims a previously deferred profitable close payout into the clearinghouse.

The payout remains subject to current vault cash availability. Funds are credited to the clearinghouse first, so traders access them through the normal account-balance path.

function claimDeferredPayout(
    bytes32 accountId
) external nonReentrant;

claimDeferredClearerBounty

Claims a previously deferred clearer bounty when the vault has replenished cash.

Deferred keeper bounties settle to clearinghouse credit for the recorded keeper address-derived account, rather than attempting a direct USDC wallet transfer.

function claimDeferredClearerBounty() external nonReentrant;

recordDeferredClearerBounty

Records a liquidation bounty that could not be paid immediately because vault cash was unavailable.

function recordDeferredClearerBounty(
    address keeper,
    uint256 amountUsdc
) external onlyRouter;

reserveCloseOrderExecutionBounty

function reserveCloseOrderExecutionBounty(
    bytes32 accountId,
    uint256 amountUsdc,
    address recipient
) external onlyRouter;

clearBadDebt

Reduces accumulated bad debt after governance-confirmed recapitalization

function clearBadDebt(
    uint256 amount
) external onlyOwner;

Parameters

NameTypeDescription
amountuint256USDC amount of bad debt to clear (6 decimals)

clearDegradedMode

function clearDegradedMode() external onlyOwner;

checkWithdraw

Reverts if the account has an open position that would be undercollateralized after withdrawal

function checkWithdraw(
    bytes32 accountId
) external view override;

Parameters

NameTypeDescription
accountIdbytes32Clearinghouse account to check

syncFunding

Materializes accrued funding into storage so subsequent reads reflect current state. O(1) gas, idempotent (no-op if called twice in the same block).

function syncFunding() external;

_syncFunding

Canonical internal funding sync. Every function that changes vault cash or reads funding-dependent state must call this first. Using a dedicated helper instead of inline _updateFunding(lastMarkPrice, vault.totalAssets()) ensures new call sites cannot silently skip the sync.

function _syncFunding() internal;

_syncFundingForMarkUpdate

function _syncFundingForMarkUpdate() internal;

_updateFunding

function _updateFunding(
    uint256 currentOraclePrice,
    uint256 vaultDepthUsdc
) internal;

getPendingFunding

Returns unsettled funding owed to (+) or by (-) a position in USDC (6 decimals)

function getPendingFunding(
    CfdTypes.Position memory pos
) public view returns (int256 fundingUsdc);

Parameters

NameTypeDescription
posCfdTypes.PositionThe position to compute pending funding for

Returns

NameTypeDescription
fundingUsdcint256Positive if the position is owed funding, negative if it owes

processOrder

Executes an order: settles funding, then increases or decreases the position. Called exclusively by OrderRouter after MEV and slippage checks pass.

function processOrder(
    CfdTypes.Order memory order,
    uint256 currentOraclePrice,
    uint256 vaultDepthUsdc,
    uint64 publishTime
) external onlyRouter nonReentrant;

Parameters

NameTypeDescription
orderCfdTypes.OrderThe order to execute (account, side, size delta, margin delta, isClose)
currentOraclePriceuint256Pyth oracle price (8 decimals), clamped to CAP_PRICE
vaultDepthUsdcuint256HousePool total assets — used to scale funding rate
publishTimeuint64Pyth publish timestamp, stored as lastMarkTime

processOrderTyped

Router-facing order execution entrypoint with typed business-rule failures.

function processOrderTyped(
    CfdTypes.Order memory order,
    uint256 currentOraclePrice,
    uint256 vaultDepthUsdc,
    uint64 publishTime
) external onlyRouter nonReentrant;

_processOrder

function _processOrder(
    CfdTypes.Order memory order,
    uint256 currentOraclePrice,
    uint256 vaultDepthUsdc,
    uint64 publishTime,
    bool typedFailures
) internal;

_syncTotalSideMargin

function _syncTotalSideMargin(
    CfdTypes.Side side,
    uint256 marginBefore,
    uint256 marginAfter
) internal;

_syncMarginQueue

function _syncMarginQueue(
    bytes32 accountId,
    uint256 consumedCommittedReservationUsdc
) internal;

_payOrRecordDeferredTraderPayout

function _payOrRecordDeferredTraderPayout(
    bytes32 accountId,
    uint256 amountUsdc
) internal;

_enqueueOrAccrueDeferredTraderPayout

function _enqueueOrAccrueDeferredTraderPayout(
    bytes32 accountId,
    uint256 amountUsdc
) internal;

_enqueueOrAccrueDeferredClearerBounty

function _enqueueOrAccrueDeferredClearerBounty(
    address keeper,
    uint256 amountUsdc
) internal;

_accountVaultCashInflow

function _accountVaultCashInflow(
    VaultCashInflow memory inflow
) internal;

_canPayFreshVaultPayout

function _canPayFreshVaultPayout(
    uint256 amountUsdc
) internal view returns (bool);

_canWithdrawProtocolFees

function _canWithdrawProtocolFees(
    uint256 amountUsdc
) internal view returns (bool);

_availableCashForFreshVaultPayouts

function _availableCashForFreshVaultPayouts() internal view returns (uint256);

_claimableHeadAmountUsdc

function _claimableHeadAmountUsdc() internal view returns (uint256);

_freshVaultReservation

function _freshVaultReservation() internal view returns (CashPriorityLib.SeniorCashReservation memory reservation);

_headDeferredClaimReservation

function _headDeferredClaimReservation(
    uint256 headClaimAmountUsdc
) internal view returns (CashPriorityLib.SeniorCashReservation memory reservation);

_enqueueDeferredClaim

function _enqueueDeferredClaim(
    ICfdEngine.DeferredClaimType claimType,
    bytes32 accountId,
    address keeper,
    uint256 amountUsdc
) internal returns (uint64 claimId);

_popDeferredClaimHead

function _popDeferredClaimHead() internal;

_unlinkDeferredClaim

function _unlinkDeferredClaim(
    uint64 claimId
) internal;

isFadWindow

Returns true during the Friday Afternoon Deleverage (FAD) window (Friday 19:00 UTC → Sunday 22:00 UTC), on admin-configured FAD days, or within fadRunwaySeconds before an admin FAD day (deleverage runway).

function isFadWindow() public view returns (bool);

isOracleFrozen

Returns true only when FX markets are closed and oracle freshness can be relaxed. Distinct from FAD, which starts earlier for deleveraging risk controls.

function isOracleFrozen() public view returns (bool);

hasOpenPosition

function hasOpenPosition(
    bytes32 accountId
) external view returns (bool);

positions

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

getPositionSize

function getPositionSize(
    bytes32 accountId
) external view returns (uint256);

getAccountCollateralView

function getAccountCollateralView(
    bytes32 accountId
) external view returns (AccountCollateralView memory viewData);

getAccountLedgerView

function getAccountLedgerView(
    bytes32 accountId
) external view returns (ICfdEngine.AccountLedgerView memory viewData);

getAccountLedgerSnapshot

function getAccountLedgerSnapshot(
    bytes32 accountId
) external view returns (ICfdEngine.AccountLedgerSnapshot memory snapshot);

_buildAccountLedgerSnapshot

function _buildAccountLedgerSnapshot(
    bytes32 accountId
) internal view returns (ICfdEngine.AccountLedgerSnapshot memory snapshot);

getPositionView

function getPositionView(
    bytes32 accountId
) external view returns (PositionView memory viewData);

getProtocolAccountingView

function getProtocolAccountingView() external view returns (ProtocolAccountingView memory viewData);

getProtocolAccountingSnapshot

function getProtocolAccountingSnapshot()
    external
    view
    returns (ICfdEngine.ProtocolAccountingSnapshot memory snapshot);

_buildProtocolAccountingSnapshot

function _buildProtocolAccountingSnapshot()
    internal
    view
    returns (ICfdEngine.ProtocolAccountingSnapshot memory snapshot);

previewOpenRevertCode

function previewOpenRevertCode(
    bytes32 accountId,
    CfdTypes.Side side,
    uint256 sizeDelta,
    uint256 marginDelta,
    uint256 oraclePrice,
    uint64 publishTime
) external view returns (uint8 code);

previewOpenFailurePolicyCategory

function previewOpenFailurePolicyCategory(
    bytes32 accountId,
    CfdTypes.Side side,
    uint256 sizeDelta,
    uint256 marginDelta,
    uint256 oraclePrice,
    uint64 publishTime
) external view returns (CfdEnginePlanTypes.OpenFailurePolicyCategory category);

getDeferredPayoutStatus

function getDeferredPayoutStatus(
    bytes32 accountId,
    address keeper
) external view returns (DeferredPayoutStatus memory status);

getDeferredClaimHead

function getDeferredClaimHead() external view returns (ICfdEngine.DeferredClaim memory claim);

getDeferredTraderStatus

function getDeferredTraderStatus(
    bytes32 accountId
) public view returns (ICfdEngine.DeferredTraderStatus memory status);

getDeferredClearerStatus

function getDeferredClearerStatus(
    address keeper
) public view returns (ICfdEngine.DeferredClearerStatus memory status);

previewClose

Canonical close preview using the vault’s current accounted depth.

function previewClose(
    bytes32 accountId,
    uint256 sizeDelta,
    uint256 oraclePrice
) external view returns (ClosePreview memory preview);

simulateClose

Hypothetical close simulation at a caller-supplied vault depth.

function simulateClose(
    bytes32 accountId,
    uint256 sizeDelta,
    uint256 oraclePrice,
    uint256 vaultDepthUsdc
) external view returns (ClosePreview memory preview);

_previewClose

function _previewClose(
    bytes32 accountId,
    uint256 sizeDelta,
    uint256 oraclePrice,
    uint256 vaultDepthUsdc
) internal view returns (ClosePreview memory preview);

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

_previewLiquidation

function _previewLiquidation(
    bytes32 accountId,
    uint256 oraclePrice,
    uint256 vaultDepthUsdc
) internal view returns (LiquidationPreview memory preview);

_applyLiquidationPreviewForfeiture

function _applyLiquidationPreviewForfeiture(
    bytes32 accountId,
    CfdEnginePlanTypes.RawSnapshot memory snap
) internal view;

getPositionSide

function getPositionSide(
    bytes32 accountId
) external view returns (CfdTypes.Side);

getMaintenanceMarginUsdc

Returns the maintenance margin requirement in USDC (6 decimals). Uses fadMarginBps during the FAD window, maintMarginBps otherwise.

function getMaintenanceMarginUsdc(
    uint256 size,
    uint256 currentOraclePrice
) public view returns (uint256);

Parameters

NameTypeDescription
sizeuint256Position size in tokens (18 decimals)
currentOraclePriceuint256Oracle price (8 decimals)

liquidatePosition

Liquidates an undercollateralized position. Surplus equity (after bounty) is returned to the user. In bad-debt cases (equity < bounty), all remaining margin is seized by the vault.

function liquidatePosition(
    bytes32 accountId,
    uint256 currentOraclePrice,
    uint256 vaultDepthUsdc,
    uint64 publishTime
) external onlyRouter nonReentrant returns (uint256 keeperBountyUsdc);

Parameters

NameTypeDescription
accountIdbytes32Clearinghouse account that owns the position
currentOraclePriceuint256Pyth oracle price (8 decimals), clamped to CAP_PRICE
vaultDepthUsdcuint256HousePool total assets — used to scale funding rate
publishTimeuint64Pyth publish timestamp, stored as lastMarkTime

Returns

NameTypeDescription
keeperBountyUsdcuint256Bounty paid to the liquidation keeper (USDC, 6 decimals)

_assertPostSolvency

function _assertPostSolvency() internal view;

_maxLiability

function _maxLiability() internal view returns (uint256);

_getWithdrawalReservedUsdc

function _getWithdrawalReservedUsdc() internal view returns (uint256 reservedUsdc);

_buildHousePoolInputSnapshot

function _buildHousePoolInputSnapshot(
    uint256 markStalenessLimit
) internal view returns (ICfdEngine.HousePoolInputSnapshot memory snapshot);

_buildHousePoolStatusSnapshot

function _buildHousePoolStatusSnapshot()
    internal
    view
    returns (ICfdEngine.HousePoolStatusSnapshot memory snapshot);

_buildAdjustedSolvencyState

function _buildAdjustedSolvencyState() internal view returns (SolvencyAccountingLib.SolvencyState memory);

_buildAdjustedSolvencySnapshot

function _buildAdjustedSolvencySnapshot()
    internal
    view
    returns (CfdEngineSnapshotsLib.SolvencySnapshot memory snapshot);

_buildRawSnapshot

function _buildRawSnapshot(
    bytes32 accountId,
    uint256,
    uint256 vaultDepthUsdc,
    uint64
) internal view returns (CfdEnginePlanTypes.RawSnapshot memory snap);

_copySideSnapshot

function _copySideSnapshot(
    SideState storage state
) internal view returns (CfdEnginePlanTypes.SideSnapshot memory snap);

_getProjectedPendingFunding

function _getProjectedPendingFunding(
    bytes32 accountId,
    CfdTypes.Position memory pos
) internal view returns (int256 fundingUsdc);

_buildProjectedPositionRiskState

function _buildProjectedPositionRiskState(
    bytes32 accountId,
    CfdTypes.Position memory pos,
    uint256 price,
    uint256 reachableUsdc,
    uint256 riskBps
) internal view returns (PositionRiskAccountingLib.PositionRiskState memory riskState);

_tryGetFreshLiveMarkPrice

function _tryGetFreshLiveMarkPrice() internal view returns (bool fresh, uint256 price);

_revertIfOpenInvalid

function _revertIfOpenInvalid(
    CfdEnginePlanTypes.OpenRevertCode code
) internal pure;

_revertIfOpenInvalidTyped

function _revertIfOpenInvalidTyped(
    CfdEnginePlanTypes.OpenRevertCode code
) internal pure;

_revertIfCloseInvalid

function _revertIfCloseInvalid(
    CfdEnginePlanTypes.CloseRevertCode code
) internal pure;

_revertIfCloseInvalidTyped

function _revertIfCloseInvalidTyped(
    CfdEnginePlanTypes.CloseRevertCode code
) internal pure;

_applyFundingAndMark

function _applyFundingAndMark(
    int256 bullDelta,
    int256 bearDelta,
    uint256 absSkew,
    uint64 newFundingTime,
    uint256 newMarkPrice,
    uint64 newMarkTime
) internal;

_applyFundingSettlement

function _applyFundingSettlement(
    CfdEnginePlanTypes.FundingDelta memory fd,
    bytes32 accountId,
    StoredPosition storage pos,
    CfdTypes.Side marginSide
) internal returns (uint256 marginAfterFunding);

_applyOpen

function _applyOpen(
    CfdEnginePlanTypes.OpenDelta memory delta
) internal;

_applyClose

function _applyClose(
    CfdEnginePlanTypes.CloseDelta memory delta
) internal;

_applyLiquidation

function _applyLiquidation(
    CfdEnginePlanTypes.LiquidationDelta memory delta
) internal returns (uint256 keeperBountyUsdc);

_enterDegradedModeIfInsolvent

function _enterDegradedModeIfInsolvent(
    bytes32 accountId,
    uint256 pendingVaultPayoutUsdc
) internal;

_physicalReachableCollateralUsdc

function _physicalReachableCollateralUsdc(
    bytes32 accountId
) internal view returns (uint256);

_positionMarginBucketUsdc

function _positionMarginBucketUsdc(
    bytes32 accountId
) internal view returns (uint256);

_loadPosition

function _loadPosition(
    bytes32 accountId
) internal view returns (CfdTypes.Position memory pos);

_liveMarkStalenessLimit

function _liveMarkStalenessLimit() internal view returns (uint256);

_consumeDeferredTraderPayout

function _consumeDeferredTraderPayout(
    bytes32 accountId,
    uint256 amountUsdc
) internal;

_computeGlobalFundingPnl

function _computeGlobalFundingPnl() internal view returns (int256 bullFunding, int256 bearFunding);

_getProjectedFundingIndices

function _getProjectedFundingIndices() internal view returns (int256 bullFundingIndex, int256 bearFundingIndex);

_buildFundingSnapshot

function _buildFundingSnapshot() internal view returns (CfdEngineSnapshotsLib.FundingSnapshot memory snapshot);

_getSolvencyCappedFundingPnl

function _getSolvencyCappedFundingPnl() internal view returns (int256);

_canProjectFundingStep

function _canProjectFundingStep() internal view returns (bool);

_buildFundingStep

function _buildFundingStep(
    uint256 price,
    uint256 vaultDepthUsdc
) internal view returns (PositionRiskAccountingLib.FundingStepResult memory step);

_getLiabilityOnlyFundingPnl

function _getLiabilityOnlyFundingPnl() internal view returns (uint256);

_validateRiskParams

function _validateRiskParams(
    CfdTypes.RiskParams memory _riskParams
) internal pure;

_getUnrealizedFundingPnl

function _getUnrealizedFundingPnl() internal view returns (int256);

getUnrealizedFundingPnl

Aggregate unsettled funding across all positions (uncapped, for reporting only)

function getUnrealizedFundingPnl() external view returns (int256);

Returns

NameTypeDescription
<none>int256Net funding PnL in USDC (6 decimals), positive = traders are owed funding

getCappedFundingPnl

Aggregate unsettled funding across all positions with uncollectible debts capped by margin.

function getCappedFundingPnl() external view returns (int256);

Returns

NameTypeDescription
<none>int256Net funding PnL in USDC (6 decimals), positive = traders are owed funding

getLiabilityOnlyFundingPnl

Aggregate unsettled funding liabilities only, ignoring trader debts owed to the vault.

function getLiabilityOnlyFundingPnl() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256Funding liabilities the vault should conservatively reserve for withdrawals (6 decimals)

getMaxLiability

Returns the protocol’s worst-case directional liability.

function getMaxLiability() external view returns (uint256);

getWithdrawalReservedUsdc

Returns the total USDC reserve required for withdrawals.

function getWithdrawalReservedUsdc() external view returns (uint256);

getHousePoolInputSnapshot

function getHousePoolInputSnapshot(
    uint256 markStalenessLimit
) external view returns (ICfdEngine.HousePoolInputSnapshot memory snapshot);

getHousePoolStatusSnapshot

function getHousePoolStatusSnapshot() external view returns (ICfdEngine.HousePoolStatusSnapshot memory snapshot);

updateMarkPrice

Updates the cached mark price without settling funding or processing trades

function updateMarkPrice(
    uint256 price,
    uint64 publishTime
) external onlyRouter;

Parameters

NameTypeDescription
priceuint256Oracle price (8 decimals), clamped to CAP_PRICE
publishTimeuint64Pyth publish timestamp

hasLiveLiability

Returns true when the protocol still has live bounded directional liability.

function hasLiveLiability() external view returns (bool);

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

Returns

NameTypeDescription
<none>int256Net trader PnL in USDC (6 decimals), sign from the traders’ perspective

getVaultMtmAdjustment

Combined MtM: per-side (PnL + funding), clamped at zero per side then summed. Positive = vault owes traders (unrealized liability). Zero = traders losing or neutral.

function getVaultMtmAdjustment() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256Net MtM liability the vault must reserve, in USDC (6 decimals). Non-negative by construction.

_getVaultMtmLiability

function _getVaultMtmLiability() internal view returns (uint256);

_getProtocolPhase

function _getProtocolPhase() internal view returns (ICfdEngine.ProtocolPhase);

getProtocolPhase

function getProtocolPhase() external view returns (ICfdEngine.ProtocolPhase);

getProtocolStatus

function getProtocolStatus() external view returns (ICfdEngine.ProtocolStatus memory status);

Events

FundingUpdated

event FundingUpdated(int256 bullIndex, int256 bearIndex, uint256 absSkewUsdc);

PositionOpened

event PositionOpened(
    bytes32 indexed accountId, CfdTypes.Side side, uint256 sizeDelta, uint256 price, uint256 marginDelta
);

PositionClosed

event PositionClosed(bytes32 indexed accountId, CfdTypes.Side side, uint256 sizeDelta, uint256 price, int256 pnl);

PositionLiquidated

event PositionLiquidated(
    bytes32 indexed accountId, CfdTypes.Side side, uint256 size, uint256 price, uint256 keeperBounty
);

MarginAdded

event MarginAdded(bytes32 indexed accountId, uint256 amount);

FadDaysAdded

event FadDaysAdded(uint256[] timestamps);

FadDaysRemoved

event FadDaysRemoved(uint256[] timestamps);

FadMaxStalenessUpdated

event FadMaxStalenessUpdated(uint256 newStaleness);

FadRunwayUpdated

event FadRunwayUpdated(uint256 newRunway);

EngineMarkStalenessLimitProposed

event EngineMarkStalenessLimitProposed(uint256 newStaleness, uint256 activationTime);

EngineMarkStalenessLimitUpdated

event EngineMarkStalenessLimitUpdated(uint256 newStaleness);

RiskParamsProposed

event RiskParamsProposed(uint256 activationTime);

RiskParamsFinalized

event RiskParamsFinalized();

AddFadDaysProposed

event AddFadDaysProposed(uint256[] timestamps, uint256 activationTime);

AddFadDaysFinalized

event AddFadDaysFinalized();

RemoveFadDaysProposed

event RemoveFadDaysProposed(uint256[] timestamps, uint256 activationTime);

RemoveFadDaysFinalized

event RemoveFadDaysFinalized();

FadMaxStalenessProposed

event FadMaxStalenessProposed(uint256 newStaleness, uint256 activationTime);

FadMaxStalenessFinalized

event FadMaxStalenessFinalized();

FadRunwayProposed

event FadRunwayProposed(uint256 newRunway, uint256 activationTime);

FadRunwayFinalized

event FadRunwayFinalized();

BadDebtCleared

event BadDebtCleared(uint256 amount, uint256 remaining);

DegradedModeEntered

event DegradedModeEntered(uint256 effectiveAssets, uint256 maxLiability, bytes32 indexed triggeringAccount);

DegradedModeCleared

event DegradedModeCleared();

DeferredPayoutRecorded

event DeferredPayoutRecorded(bytes32 indexed accountId, uint256 amountUsdc);

DeferredPayoutClaimed

event DeferredPayoutClaimed(bytes32 indexed accountId, uint256 amountUsdc);

DeferredClearerBountyRecorded

event DeferredClearerBountyRecorded(address indexed keeper, uint256 amountUsdc);

DeferredClearerBountyClaimed

event DeferredClearerBountyClaimed(address indexed keeper, uint256 amountUsdc);

Errors

CfdEngine__Unauthorized

error CfdEngine__Unauthorized();

CfdEngine__VaultAlreadySet

error CfdEngine__VaultAlreadySet();

CfdEngine__RouterAlreadySet

error CfdEngine__RouterAlreadySet();

CfdEngine__NoFeesToWithdraw

error CfdEngine__NoFeesToWithdraw();

CfdEngine__NoDeferredPayout

error CfdEngine__NoDeferredPayout();

CfdEngine__InsufficientVaultLiquidity

error CfdEngine__InsufficientVaultLiquidity();

CfdEngine__NoDeferredClearerBounty

error CfdEngine__NoDeferredClearerBounty();

CfdEngine__DeferredClaimNotAtHead

error CfdEngine__DeferredClaimNotAtHead();

CfdEngine__MustCloseOpposingPosition

error CfdEngine__MustCloseOpposingPosition();

CfdEngine__FundingExceedsMargin

error CfdEngine__FundingExceedsMargin();

CfdEngine__VaultSolvencyExceeded

error CfdEngine__VaultSolvencyExceeded();

CfdEngine__MarginDrainedByFees

error CfdEngine__MarginDrainedByFees();

CfdEngine__CloseSizeExceedsPosition

error CfdEngine__CloseSizeExceedsPosition();

CfdEngine__NoPositionToLiquidate

error CfdEngine__NoPositionToLiquidate();

CfdEngine__PositionIsSolvent

error CfdEngine__PositionIsSolvent();

CfdEngine__PostOpSolvencyBreach

error CfdEngine__PostOpSolvencyBreach();

CfdEngine__InsufficientInitialMargin

error CfdEngine__InsufficientInitialMargin();

CfdEngine__PositionTooSmall

error CfdEngine__PositionTooSmall();

CfdEngine__WithdrawBlockedByOpenPosition

error CfdEngine__WithdrawBlockedByOpenPosition();

CfdEngine__EmptyDays

error CfdEngine__EmptyDays();

CfdEngine__ZeroStaleness

error CfdEngine__ZeroStaleness();

CfdEngine__RunwayTooLong

error CfdEngine__RunwayTooLong();

CfdEngine__PartialCloseUnderwaterFunding

error CfdEngine__PartialCloseUnderwaterFunding();

CfdEngine__DustPosition

error CfdEngine__DustPosition();

CfdEngine__MarkPriceStale

error CfdEngine__MarkPriceStale();

CfdEngine__MarkPriceOutOfOrder

error CfdEngine__MarkPriceOutOfOrder();

CfdEngine__NotAccountOwner

error CfdEngine__NotAccountOwner();

CfdEngine__NoOpenPosition

error CfdEngine__NoOpenPosition();

CfdEngine__TimelockNotReady

error CfdEngine__TimelockNotReady();

CfdEngine__NoProposal

error CfdEngine__NoProposal();

CfdEngine__BadDebtTooLarge

error CfdEngine__BadDebtTooLarge();

CfdEngine__InvalidRiskParams

error CfdEngine__InvalidRiskParams();

CfdEngine__SkewTooHigh

error CfdEngine__SkewTooHigh();

CfdEngine__DegradedMode

error CfdEngine__DegradedMode();

CfdEngine__NotDegraded

error CfdEngine__NotDegraded();

CfdEngine__StillInsolvent

error CfdEngine__StillInsolvent();

CfdEngine__ZeroAddress

error CfdEngine__ZeroAddress();

CfdEngine__InsufficientCloseOrderBountyBacking

error CfdEngine__InsufficientCloseOrderBountyBacking();

CfdEngine__InvalidVaultCashInflow

error CfdEngine__InvalidVaultCashInflow();

Structs

AccountCollateralView

struct AccountCollateralView {
    uint256 settlementBalanceUsdc;
    uint256 lockedMarginUsdc;
    // Clearinghouse custody bucket for currently locked live position backing.
    uint256 activePositionMarginUsdc;
    uint256 otherLockedMarginUsdc;
    uint256 freeSettlementUsdc;
    // Current UI helper only; this does not include terminally reachable queued committed margin.
    uint256 closeReachableUsdc;
    uint256 terminalReachableUsdc;
    uint256 accountEquityUsdc;
    uint256 freeBuyingPowerUsdc;
    uint256 deferredPayoutUsdc;
}

PositionView

struct PositionView {
    bool exists;
    CfdTypes.Side side;
    uint256 size;
    uint256 margin;
    uint256 entryPrice;
    uint256 entryNotionalUsdc;
    uint256 physicalReachableCollateralUsdc;
    uint256 nettableDeferredPayoutUsdc;
    int256 unrealizedPnlUsdc;
    int256 pendingFundingUsdc;
    int256 netEquityUsdc;
    uint256 maxProfitUsdc;
    bool liquidatable;
}

ProtocolAccountingView

struct ProtocolAccountingView {
    uint256 vaultAssetsUsdc;
    uint256 maxLiabilityUsdc;
    uint256 withdrawalReservedUsdc;
    uint256 freeUsdc;
    uint256 accumulatedFeesUsdc;
    int256 cappedFundingPnlUsdc;
    uint256 liabilityOnlyFundingPnlUsdc;
    uint256 totalDeferredPayoutUsdc;
    uint256 totalDeferredClearerBountyUsdc;
    bool degradedMode;
    bool hasLiveLiability;
}

ClosePreview

struct ClosePreview {
    bool valid;
    CfdTypes.CloseInvalidReason invalidReason;
    uint256 executionPrice;
    uint256 sizeDelta;
    int256 realizedPnlUsdc;
    int256 fundingUsdc;
    int256 vpiDeltaUsdc;
    uint256 vpiUsdc;
    uint256 executionFeeUsdc;
    uint256 freshTraderPayoutUsdc;
    uint256 existingDeferredConsumedUsdc;
    uint256 existingDeferredRemainingUsdc;
    uint256 immediatePayoutUsdc;
    uint256 deferredPayoutUsdc;
    uint256 seizedCollateralUsdc;
    uint256 badDebtUsdc;
    uint256 remainingSize;
    uint256 remainingMargin;
    bool triggersDegradedMode;
    bool postOpDegradedMode;
    uint256 effectiveAssetsAfterUsdc;
    uint256 maxLiabilityAfterUsdc;
    int256 solvencyFundingPnlUsdc;
}

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

DeferredPayoutStatus

struct DeferredPayoutStatus {
    uint256 deferredTraderPayoutUsdc;
    bool traderPayoutClaimableNow;
    uint256 deferredClearerBountyUsdc;
    bool liquidationBountyClaimableNow;
}

SideState

struct SideState {
    uint256 maxProfitUsdc;
    uint256 openInterest;
    uint256 entryNotional;
    // Cached aggregate of engine economic position margins for this side; not a custody bucket.
    uint256 totalMargin;
    int256 fundingIndex;
    int256 entryFunding;
}

VaultCashInflow

struct VaultCashInflow {
    uint256 physicalCashReceivedUsdc;
    uint256 protocolOwnedUsdc;
    uint256 lpOwnedUsdc;
}

StoredPosition

struct StoredPosition {
    uint256 size;
    uint256 entryPrice;
    uint256 maxProfitUsdc;
    int256 entryFundingIndex;
    CfdTypes.Side side;
    uint64 lastUpdateTime;
    int256 vpiAccrued;
}