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

CfdMath

Git Source

Title: CfdMath

Pure stateless math library for PnL and price impact

Note: security-contact: contact@plether.com

Constants

WAD

uint256 internal constant WAD = 1e18;

SECONDS_PER_YEAR

uint256 internal constant SECONDS_PER_YEAR = 31_536_000;

USDC_TO_TOKEN_SCALE

uint256 internal constant USDC_TO_TOKEN_SCALE = 1e20;

Functions

calculatePnL

Calculates Unrealized PnL strictly bounded by the protocol CAP

function calculatePnL(
    CfdTypes.Position memory pos,
    uint256 currentOraclePrice,
    uint256 capPrice
) internal pure returns (bool isProfit, uint256 pnlUsdc);

Parameters

NameTypeDescription
posCfdTypes.PositionThe position to evaluate
currentOraclePriceuint256Current oracle price (8 decimals)
capPriceuint256Protocol cap price (8 decimals)

Returns

NameTypeDescription
isProfitboolTrue if the position is in profit
pnlUsdcuint256Absolute PnL value in USDC (6 decimals)

calculateMaxProfit

Calculates the absolute maximum payout a trade can ever achieve

function calculateMaxProfit(
    uint256 size,
    uint256 entryPrice,
    CfdTypes.Side side,
    uint256 capPrice
) internal pure returns (uint256 maxProfitUsdc);

Parameters

NameTypeDescription
sizeuint256Notional size (18 decimals)
entryPriceuint256Entry oracle price (8 decimals)
sideCfdTypes.SideBULL or BEAR
capPriceuint256Protocol cap price (8 decimals)

Returns

NameTypeDescription
maxProfitUsdcuint256Maximum possible profit in USDC (6 decimals)

conservativeMtmLiability

Conservative upper bound for a side’s current gross winning-trader MtM liability.

Uses each position’s max-profit envelope so same-side losing positions cannot net down winning positions before their losses are physically realized.

function conservativeMtmLiability(
    uint256 maxProfitUsdc,
    CfdTypes.Side side,
    uint256 price,
    uint256 capPrice
) internal pure returns (uint256);

_getSkewCost

Calculates the cost of a specific skew state. C(S) = 0.5 * k * (S^2 / D)

function _getSkewCost(
    uint256 skewUsdc,
    uint256 depthUsdc,
    uint256 vpiFactorWad
) private pure returns (uint256 costUsdc);

Parameters

NameTypeDescription
skewUsdcuint256The absolute directional imbalance in USDC (6 decimals)
depthUsdcuint256The total free USDC in the House Pool (6 decimals)
vpiFactorWaduint256The ‘k’ impact parameter (18 decimals)

Returns

NameTypeDescription
costUsdcuint256The theoretical cost to reach this skew (6 decimals)

calculateVPI

Calculates the VPI charge/rebate for a trade.

If postCost > preCost, result is positive (Charge Trader). If postCost < preCost, result is negative (Rebate Trader / MM Incentive).

function calculateVPI(
    uint256 preSkewUsdc,
    uint256 postSkewUsdc,
    uint256 depthUsdc,
    uint256 vpiFactorWad
) internal pure returns (int256 vpiUsdc);