CfdMath
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
| Name | Type | Description |
|---|---|---|
pos | CfdTypes.Position | The position to evaluate |
currentOraclePrice | uint256 | Current oracle price (8 decimals) |
capPrice | uint256 | Protocol cap price (8 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
isProfit | bool | True if the position is in profit |
pnlUsdc | uint256 | Absolute 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
| Name | Type | Description |
|---|---|---|
size | uint256 | Notional size (18 decimals) |
entryPrice | uint256 | Entry oracle price (8 decimals) |
side | CfdTypes.Side | BULL or BEAR |
capPrice | uint256 | Protocol cap price (8 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
maxProfitUsdc | uint256 | Maximum 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
| Name | Type | Description |
|---|---|---|
skewUsdc | uint256 | The absolute directional imbalance in USDC (6 decimals) |
depthUsdc | uint256 | The total free USDC in the House Pool (6 decimals) |
vpiFactorWad | uint256 | The ‘k’ impact parameter (18 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
costUsdc | uint256 | The 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);