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, ICfdEngineAdminHost, 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;

State Variables

vault

ICfdVault public vault;

planner

ICfdEnginePlanner public planner;

settlementModule

ICfdEngineSettlementModule public settlementModule;

admin

address public admin;

sides

SideState[2] public sides;

lastMarkPrice

uint256 public lastMarkPrice;

lastMarkTime

uint64 public lastMarkTime;

accumulatedFeesUsdc

uint256 public accumulatedFeesUsdc;

accumulatedBadDebtUsdc

uint256 public accumulatedBadDebtUsdc;

unsettledCarryUsdc

mapping(bytes32 => uint256) public unsettledCarryUsdc;

degradedMode

bool public degradedMode;

riskParams

CfdTypes.RiskParams public riskParams;

_positions

mapping(bytes32 => StoredPosition) internal _positions;

deferredTraderCreditUsdc

mapping(bytes32 => uint256) public deferredTraderCreditUsdc;

totalDeferredTraderCreditUsdc

uint256 public totalDeferredTraderCreditUsdc;

deferredKeeperCreditUsdc

mapping(address => uint256) public deferredKeeperCreditUsdc;

totalDeferredKeeperCreditUsdc

uint256 public totalDeferredKeeperCreditUsdc;

orderRouter

address public orderRouter;

fadDayOverrides

mapping(uint256 => bool) public fadDayOverrides;

_fadOverrideDays

uint256[] private _fadOverrideDays;

fadMaxStaleness

uint256 public fadMaxStaleness = 3 days;

fadRunwaySeconds

uint256 public fadRunwaySeconds = 3 hours;

engineMarkStalenessLimit

uint256 public engineMarkStalenessLimit = 60;

executionFeeBps

uint256 public executionFeeBps = 4;

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

_checkpointDeferredClaimCarryIfPossible

function _checkpointDeferredClaimCarryIfPossible(
    bytes32 accountId,
    StoredPosition storage pos
) internal;

_claimDeferredBalance

function _claimDeferredBalance(
    uint256 amount,
    bytes32 accountId
) internal returns (uint256 claimAmountUsdc);

_increaseDeferredLiability

function _increaseDeferredLiability(
    uint256 currentAmountUsdc,
    uint256 currentTotalUsdc,
    uint256 amountUsdc
) internal pure returns (uint256 updatedAmountUsdc, uint256 updatedTotalUsdc);

_decreaseDeferredLiability

function _decreaseDeferredLiability(
    uint256 currentAmountUsdc,
    uint256 currentTotalUsdc,
    uint256 amountUsdc
) internal pure returns (uint256 updatedAmountUsdc, uint256 updatedTotalUsdc);

onlyRouter

modifier onlyRouter();

onlySettlementModule

modifier onlySettlementModule();

onlyAdmin

modifier onlyAdmin();

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, carry rate, bounty config)

setDependencies

One-time setter for planner, settlement module, and admin sidecars.

function setDependencies(
    address planner_,
    address settlementModule_,
    address admin_
) external onlyOwner;

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;

withdrawFees

Withdraws accumulated execution fees from the vault to a recipient.

function withdrawFees(
    address recipient
) external onlyOwner;

withdrawFees

Withdraws up to amountUsdc of accumulated execution fees from the vault to a recipient.

function withdrawFees(
    address recipient,
    uint256 amountUsdc
) public 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 funded the vault.

function recordRouterProtocolFee(
    uint256 amountUsdc
) external onlyRouter;

creditKeeperExecutionBounty

Credits a router-collected execution bounty into the beneficiary’s clearinghouse account.

Realizes carry first when the beneficiary currently has an open position because the clearinghouse settlement credit changes the carry basis. Router execution already validates the oracle publish time, so this helper only enforces monotonic publish ordering before checkpointing against the validated cached mark.

function creditKeeperExecutionBounty(
    address beneficiary,
    uint256 amountUsdc,
    uint256 price,
    uint64 publishTime
) external onlyRouter nonReentrant;

addMargin

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

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

realizeCarryBeforeMarginChange

Realizes accrued carry before a user-level clearinghouse balance mutation changes the carry basis.

Called only by the clearinghouse before user deposits and withdrawals.

function realizeCarryBeforeMarginChange(
    bytes32 accountId,
    uint256 reachableCollateralBasisUsdc
) external nonReentrant;

checkpointCarryUsingStoredMark

Checkpoints carry against the cached stored mark when fresh-mark liveness is unavailable.

Restricted to the clearinghouse stale-deposit path so deposits preserve pre-mutation carry basis.

function checkpointCarryUsingStoredMark(
    bytes32 accountId,
    uint256 reachableCollateralBasisUsdc
) external nonReentrant;

claimDeferredTraderCredit

Claims deferred trader credit balance into the clearinghouse.

The claim can be partial if current vault cash is insufficient. Funds are credited to the clearinghouse first, so beneficiaries access them through the normal account-balance path. Carry is checkpointed before the settlement-basis change using a fresh mark when available, otherwise the cached stored mark is used.

function claimDeferredTraderCredit(
    bytes32 accountId
) external nonReentrant;

claimDeferredKeeperCredit

Claims previously deferred keeper credit when the vault has replenished cash.

Deferred keeper value always settles to clearinghouse credit for the recorded keeper address-derived account.

function claimDeferredKeeperCredit() external nonReentrant;

recordDeferredKeeperCredit

Records keeper credit that could not be serviced immediately because vault cash was unavailable.

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

reserveCloseOrderExecutionBounty

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

sweepToken

function sweepToken(
    address token,
    address to,
    uint256 amount
) external onlyOwner;

clearDegradedMode

function clearDegradedMode() external onlyOwner;

applyRiskConfig

function applyRiskConfig(
    ICfdEngineAdminHost.EngineRiskConfig calldata config
) external onlyAdmin;

applyCalendarConfig

function applyCalendarConfig(
    ICfdEngineAdminHost.EngineCalendarConfig calldata config
) external onlyAdmin;

applyFreshnessConfig

function applyFreshnessConfig(
    ICfdEngineAdminHost.EngineFreshnessConfig calldata config
) external onlyAdmin;

checkWithdraw

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

function checkWithdraw(
    bytes32 accountId
) external override nonReentrant;

Parameters

NameTypeDescription
accountIdbytes32Clearinghouse account to check

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

_enqueueOrAccrueDeferredKeeperCredit

function _enqueueOrAccrueDeferredKeeperCredit(
    address keeper,
    uint256 amountUsdc
) 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);

_freshVaultReservation

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

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

positions

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

getPositionLastCarryTimestamp

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

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 for post-op solvency checks and payout affordability
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);

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

_tryGetFreshLiveMarkPrice

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

_revertIfOpenInvalidTyped

function _revertIfOpenInvalidTyped(
    CfdEnginePlanTypes.OpenRevertCode code
) internal view;

_revertIfCloseInvalidTyped

function _revertIfCloseInvalidTyped(
    CfdEnginePlanTypes.CloseRevertCode code
) internal view;

_applyFundingAndMark

function _applyFundingAndMark(
    uint256 newMarkPrice,
    uint64 newMarkTime
) internal;

settlementApplyFundingAndMark

function settlementApplyFundingAndMark(
    uint256 newMarkPrice,
    uint64 newMarkTime
) external onlySettlementModule;

settlementSyncTotalSideMargin

function settlementSyncTotalSideMargin(
    CfdTypes.Side side,
    uint256 marginBefore,
    uint256 marginAfter
) external onlySettlementModule;

settlementApplySideDelta

function settlementApplySideDelta(
    CfdTypes.Side side,
    int256 maxProfitDelta,
    int256 openInterestDelta,
    int256 entryNotionalDelta
) external onlySettlementModule;

settlementConsumeDeferredTraderPayout

function settlementConsumeDeferredTraderPayout(
    bytes32 accountId,
    uint256 amountUsdc
) external onlySettlementModule;

settlementRecordDeferredTraderPayout

function settlementRecordDeferredTraderPayout(
    bytes32 accountId,
    uint256 amountUsdc
) external onlySettlementModule;

settlementAccumulateFees

function settlementAccumulateFees(
    uint256 amountUsdc
) external onlySettlementModule;

settlementAccumulateBadDebt

function settlementAccumulateBadDebt(
    uint256 amountUsdc
) external onlySettlementModule;

settlementWritePosition

function settlementWritePosition(
    bytes32 accountId,
    CfdEngineSettlementTypes.PositionState calldata position
) external onlySettlementModule;

settlementDeletePosition

function settlementDeletePosition(
    bytes32 accountId
) external onlySettlementModule;

_applyOpen

function _applyOpen(
    CfdEnginePlanTypes.OpenDelta memory delta,
    uint64 publishTime
) internal;

_applyClose

function _applyClose(
    CfdEnginePlanTypes.CloseDelta memory delta,
    uint64 publishTime
) internal;

_applyLiquidation

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

_enterDegradedModeIfInsolvent

function _enterDegradedModeIfInsolvent(
    bytes32 accountId,
    uint256 pendingVaultPayoutUsdc
) internal;

_genericReachableCollateralUsdc

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

_terminalReachableCollateralUsdc

function _terminalReachableCollateralUsdc(
    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);

_elapsedCarryUsdc

function _elapsedCarryUsdc(
    CfdTypes.Position memory pos,
    uint256 price,
    uint256 reachableCollateralUsdc,
    uint256 timestampNow
) internal view returns (uint256);

_totalPendingCarryUsdc

function _totalPendingCarryUsdc(
    bytes32 accountId,
    CfdTypes.Position memory pos,
    uint256 price,
    uint256 reachableCollateralUsdc,
    uint256 timestampNow
) internal view returns (uint256);

_canFullyRealizeCarryFromSettlement

function _canFullyRealizeCarryFromSettlement(
    bytes32 accountId,
    CfdTypes.Position memory pos,
    uint256 price
) internal view returns (bool);

_checkpointCarryBeforeBasisChange

function _checkpointCarryBeforeBasisChange(
    bytes32 accountId,
    StoredPosition storage pos,
    uint256 price,
    uint256 reachableCollateralUsdc
) internal;

_realizeCarryFromSettlement

function _realizeCarryFromSettlement(
    bytes32 accountId,
    StoredPosition storage pos,
    uint256 price,
    uint256 reachableCollateralUsdc
) internal returns (uint256 realizedCarryUsdc);

_liveMarkStalenessLimit

function _liveMarkStalenessLimit() internal view returns (uint256);

_consumeDeferredTraderPayout

function _consumeDeferredTraderPayout(
    bytes32 accountId,
    uint256 amountUsdc
) internal;

_validateRiskParams

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

updateMarkPrice

Updates the cached mark price without processing a trade or liquidation.

This does not itself realize carry; carry realization happens on execution and margin-mutating paths.

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

Parameters

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

_getVaultMtmLiability

function _getVaultMtmLiability() internal view returns (uint256);

_getProtocolPhase

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

getProtocolStatus

function getProtocolStatus() external view returns (EngineStatusViewTypes.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);

EngineMarkStalenessLimitUpdated

event EngineMarkStalenessLimitUpdated(uint256 newStaleness);

BadDebtCleared

event BadDebtCleared(uint256 amount, uint256 remaining);

DegradedModeEntered

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

DegradedModeCleared

event DegradedModeCleared();

DeferredTraderCreditRecorded

event DeferredTraderCreditRecorded(bytes32 indexed accountId, uint256 amountUsdc);

DeferredTraderCreditClaimed

event DeferredTraderCreditClaimed(bytes32 indexed accountId, uint256 amountUsdc);

DeferredKeeperCreditRecorded

event DeferredKeeperCreditRecorded(address indexed keeper, uint256 amountUsdc);

DeferredKeeperCreditClaimed

event DeferredKeeperCreditClaimed(address indexed keeper, uint256 amountUsdc);

CarryCheckpointed

event CarryCheckpointed(
    bytes32 indexed accountId, uint256 addedUnsettledCarryUsdc, uint256 totalUnsettledCarryUsdc
);

CarryRealized

event CarryRealized(
    bytes32 indexed accountId,
    uint256 realizedCarryUsdc,
    uint256 freeSettlementConsumedUsdc,
    uint256 marginConsumedUsdc,
    uint256 remainingUnsettledCarryUsdc
);

TokenSwept

event TokenSwept(address indexed token, address indexed to, uint256 amount);

Errors

CfdEngine__Unauthorized

error CfdEngine__Unauthorized();

CfdEngine__VaultAlreadySet

error CfdEngine__VaultAlreadySet();

CfdEngine__RouterAlreadySet

error CfdEngine__RouterAlreadySet();

CfdEngine__DependenciesAlreadySet

error CfdEngine__DependenciesAlreadySet();

CfdEngine__NoFeesToWithdraw

error CfdEngine__NoFeesToWithdraw();

CfdEngine__NoDeferredTraderCredit

error CfdEngine__NoDeferredTraderCredit();

CfdEngine__InsufficientVaultLiquidity

error CfdEngine__InsufficientVaultLiquidity();

CfdEngine__NoDeferredKeeperCredit

error CfdEngine__NoDeferredKeeperCredit();

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__ZeroAmount

error CfdEngine__ZeroAmount();

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__NotClearinghouse

error CfdEngine__NotClearinghouse();

CfdEngine__NotAccountOwner

error CfdEngine__NotAccountOwner();

CfdEngine__NoOpenPosition

error CfdEngine__NoOpenPosition();

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

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

PositionView

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

ProtocolAccountingView

struct ProtocolAccountingView {
    uint256 vaultAssetsUsdc;
    uint256 maxLiabilityUsdc;
    uint256 withdrawalReservedUsdc;
    uint256 freeUsdc;
    uint256 accumulatedFeesUsdc;
    uint256 totalDeferredTraderCreditUsdc;
    uint256 totalDeferredKeeperCreditUsdc;
    bool degradedMode;
    bool hasLiveLiability;
}

ClosePreview

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

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

DeferredCreditStatus

struct DeferredCreditStatus {
    uint256 deferredTraderCreditUsdc;
    bool traderPayoutClaimableNow;
    uint256 deferredKeeperCreditUsdc;
    bool keeperCreditClaimableNow;
}

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

StoredPosition

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