@gainsnetwork/sdk 0.0.0-v10.rc3 → 0.0.0-v10.rc4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/lib/backend/index.d.ts +1 -0
  2. package/lib/backend/index.js +10 -0
  3. package/lib/backend/tradingVariables/converter.d.ts +2 -1
  4. package/lib/backend/tradingVariables/converter.js +2 -1
  5. package/lib/backend/tradingVariables/index.d.ts +2 -0
  6. package/lib/backend/tradingVariables/index.js +17 -0
  7. package/lib/constants.d.ts +10 -0
  8. package/lib/constants.js +11 -1
  9. package/lib/contracts/utils/pairs.js +10 -0
  10. package/lib/index.d.ts +1 -0
  11. package/lib/index.js +4 -0
  12. package/lib/trade/fees/borrowing/builder.d.ts +14 -0
  13. package/lib/trade/fees/borrowing/builder.js +33 -0
  14. package/lib/trade/fees/borrowing/index.d.ts +3 -2
  15. package/lib/trade/fees/borrowing/index.js +13 -4
  16. package/lib/trade/fees/borrowingV2/builder.d.ts +6 -0
  17. package/lib/trade/fees/borrowingV2/builder.js +24 -0
  18. package/lib/trade/fees/borrowingV2/converter.d.ts +12 -3
  19. package/lib/trade/fees/borrowingV2/converter.js +29 -18
  20. package/lib/trade/fees/borrowingV2/fetcher.js +5 -13
  21. package/lib/trade/fees/borrowingV2/index.d.ts +5 -17
  22. package/lib/trade/fees/borrowingV2/index.js +9 -37
  23. package/lib/trade/fees/borrowingV2/types.d.ts +22 -6
  24. package/lib/trade/fees/fundingFees/builder.d.ts +9 -0
  25. package/lib/trade/fees/fundingFees/builder.js +35 -0
  26. package/lib/trade/fees/fundingFees/index.d.ts +12 -2
  27. package/lib/trade/fees/fundingFees/index.js +23 -3
  28. package/lib/trade/fees/fundingFees/pairContext.d.ts +33 -0
  29. package/lib/trade/fees/fundingFees/pairContext.js +17 -0
  30. package/lib/trade/fees/index.d.ts +1 -1
  31. package/lib/trade/fees/index.js +2 -3
  32. package/lib/trade/fees/trading/builder.d.ts +18 -0
  33. package/lib/trade/fees/trading/builder.js +20 -0
  34. package/lib/trade/fees/trading/holdingFees.d.ts +28 -0
  35. package/lib/trade/fees/trading/holdingFees.js +66 -0
  36. package/lib/trade/fees/trading/holdingFeesStructured.d.ts +28 -0
  37. package/lib/trade/fees/trading/holdingFeesStructured.js +66 -0
  38. package/lib/trade/fees/trading/index.d.ts +19 -11
  39. package/lib/trade/fees/trading/index.js +29 -21
  40. package/lib/trade/liquidation/builder.d.ts +25 -0
  41. package/lib/trade/liquidation/builder.js +59 -0
  42. package/lib/trade/liquidation/index.d.ts +8 -13
  43. package/lib/trade/liquidation/index.js +43 -88
  44. package/lib/trade/liquidation/types.d.ts +36 -21
  45. package/lib/trade/pnl/builder.d.ts +16 -0
  46. package/lib/trade/pnl/builder.js +44 -0
  47. package/lib/trade/pnl/index.d.ts +21 -30
  48. package/lib/trade/pnl/index.js +119 -50
  49. package/lib/trade/pnl/types.d.ts +29 -1
  50. package/lib/trade/types.d.ts +11 -1
  51. package/lib/trade/types.js +10 -0
  52. package/package.json +1 -1
  53. package/lib/contracts/fetch/fees/borrowingFeesV2.d.ts +0 -75
  54. package/lib/contracts/fetch/fees/borrowingFeesV2.js +0 -193
  55. package/lib/contracts/fetch/fees/fundingFees.d.ts +0 -66
  56. package/lib/contracts/fetch/fees/fundingFees.js +0 -150
  57. package/lib/contracts/fetch/priceImpact/skew.d.ts +0 -63
  58. package/lib/contracts/fetch/priceImpact/skew.js +0 -168
  59. package/lib/trade/liquidation.d.ts +0 -12
  60. package/lib/trade/liquidation.js +0 -55
  61. package/lib/trade/pnl.d.ts +0 -10
  62. package/lib/trade/pnl.js +0 -33
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Liquidation price context builder module
4
+ * @dev Provides builder functions for creating liquidation price contexts
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.buildLiquidationPriceContext = void 0;
8
+ const builder_1 = require("../fees/borrowing/builder");
9
+ const builder_2 = require("../fees/borrowingV2/builder");
10
+ const builder_3 = require("../fees/fundingFees/builder");
11
+ const builder_4 = require("../fees/trading/builder");
12
+ /**
13
+ * @dev Builds a complete context for liquidation price calculations
14
+ * @param globalTradingVariables The transformed global trading variables from backend
15
+ * @param tradeContainer Full trade container with trade, tradeInfo, fees data and liquidation params
16
+ * @param additionalParams Additional parameters not available in trading variables
17
+ * @returns Complete context ready for getLiquidationPrice
18
+ */
19
+ const buildLiquidationPriceContext = (globalTradingVariables, tradeContainer, additionalParams) => {
20
+ var _a;
21
+ const { trade, tradeInfo } = tradeContainer;
22
+ const collateralIndex = trade.collateralIndex || 1;
23
+ const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
24
+ if (!tradeContainer.liquidationParams) {
25
+ throw new Error("Liquidation params are required for liquidation price calculation");
26
+ }
27
+ return {
28
+ // Core shared context
29
+ core: {
30
+ currentBlock: additionalParams.currentBlock,
31
+ currentTimestamp: additionalParams.currentTimestamp,
32
+ collateralPriceUsd: ((_a = collateral.prices) === null || _a === void 0 ? void 0 : _a.collateralPriceUsd) || 1,
33
+ contractsVersion: tradeInfo.contractsVersion,
34
+ spreadP: additionalParams.spreadP,
35
+ },
36
+ // Build sub-contexts using dedicated builders
37
+ borrowingV1: (0, builder_1.buildBorrowingV1Context)(globalTradingVariables, collateralIndex, additionalParams.currentBlock),
38
+ borrowingV2: (0, builder_2.buildBorrowingV2Context)(globalTradingVariables, collateralIndex, trade.pairIndex, additionalParams.currentTimestamp),
39
+ funding: (0, builder_3.buildFundingContext)(globalTradingVariables, collateralIndex, trade.pairIndex, additionalParams.currentTimestamp),
40
+ trading: (0, builder_4.buildTradingFeesContext)(globalTradingVariables, trade.pairIndex, additionalParams.traderFeeMultiplier),
41
+ // Trade-specific data
42
+ tradeData: {
43
+ tradeInfo,
44
+ tradeFeesData: tradeContainer.tradeFeesData,
45
+ liquidationParams: tradeContainer.liquidationParams,
46
+ initialAccFeesV1: tradeContainer.initialAccFees,
47
+ },
48
+ // Additional parameters for liquidation calculation
49
+ liquidationSpecific: {
50
+ currentPairPrice: additionalParams.currentPairPrice,
51
+ additionalFeeCollateral: additionalParams.additionalFeeCollateral || 0,
52
+ partialCloseMultiplier: additionalParams.partialCloseMultiplier || 1,
53
+ beforeOpened: additionalParams.beforeOpened || false,
54
+ isCounterTrade: trade.isCounterTrade || false,
55
+ userPriceImpact: additionalParams.userPriceImpact,
56
+ },
57
+ };
58
+ };
59
+ exports.buildLiquidationPriceContext = buildLiquidationPriceContext;
@@ -1,19 +1,15 @@
1
1
  /**
2
2
  * @dev Main export file for liquidation module
3
3
  */
4
- import { Trade, Fee, BorrowingFee, LiquidationParams } from "..";
5
- import { GetLiquidationPriceContext, LiqPriceInput } from "./types";
4
+ import { Trade, LiquidationParams } from "..";
5
+ import { GetLiquidationPriceContext } from "./types";
6
6
  /**
7
- * @dev Wrapper function that mirrors the contract's getTradeLiquidationPrice signature
8
- * @dev This is the main entry point matching the contract interface
9
- * @param input Liquidation price input parameters
10
- * @param context Additional context for SDK calculations
7
+ * @dev Calculate liquidation price with structured context
8
+ * @param trade The trade to calculate liquidation price for
9
+ * @param context Structured context with all required data
11
10
  * @returns Liquidation price
12
11
  */
13
- export declare const getTradeLiquidationPrice: (input: LiqPriceInput, context: Omit<GetLiquidationPriceContext, "currentPairPrice" | "isCounterTrade" | "partialCloseMultiplier" | "additionalFeeCollateral" | "beforeOpened" | "liquidationParams"> & {
14
- fee: Fee;
15
- }) => number;
16
- export declare const getLiquidationPrice: (trade: Trade, fee: Fee, initialAccFees: BorrowingFee.InitialAccFees, context: GetLiquidationPriceContext) => number;
12
+ export declare const getLiquidationPrice: (trade: Trade, context: GetLiquidationPriceContext) => number;
17
13
  export declare const getLiqPnlThresholdP: (liquidationParams: LiquidationParams | undefined, leverage: number | undefined) => number;
18
14
  /**
19
15
  * @dev Simplified wrapper for getTradeLiquidationPrice
@@ -24,8 +20,7 @@ export declare const getLiqPnlThresholdP: (liquidationParams: LiquidationParams
24
20
  * @param context Context with all required data
25
21
  * @returns Liquidation price
26
22
  */
27
- export declare const getTradeLiquidationPriceSimple: (trade: Trade, additionalFeeCollateral: number, currentPairPrice: number, context: Omit<GetLiquidationPriceContext, "currentPairPrice" | "additionalFeeCollateral"> & {
28
- fee: Fee;
29
- }) => number;
23
+ export declare const getTradeLiquidationPriceSimple: (trade: Trade, additionalFeeCollateral: number, currentPairPrice: number, context: GetLiquidationPriceContext) => number;
30
24
  export { convertLiquidationParams, convertLiquidationParamsArray, encodeLiquidationParams, } from "./converter";
31
25
  export * from "./types";
26
+ export * from "./builder";
@@ -17,98 +17,70 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
17
17
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.encodeLiquidationParams = exports.convertLiquidationParamsArray = exports.convertLiquidationParams = exports.getTradeLiquidationPriceSimple = exports.getLiqPnlThresholdP = exports.getLiquidationPrice = exports.getTradeLiquidationPrice = void 0;
20
+ exports.encodeLiquidationParams = exports.convertLiquidationParamsArray = exports.convertLiquidationParams = exports.getTradeLiquidationPriceSimple = exports.getLiqPnlThresholdP = exports.getLiquidationPrice = void 0;
21
21
  const types_1 = require("../../contracts/types");
22
22
  const __1 = require("..");
23
23
  /**
24
- * @dev Wrapper function that mirrors the contract's getTradeLiquidationPrice signature
25
- * @dev This is the main entry point matching the contract interface
26
- * @param input Liquidation price input parameters
27
- * @param context Additional context for SDK calculations
24
+ * @dev Calculate liquidation price with structured context
25
+ * @param trade The trade to calculate liquidation price for
26
+ * @param context Structured context with all required data
28
27
  * @returns Liquidation price
29
28
  */
30
- const getTradeLiquidationPrice = (input, context) => {
31
- // Create trade object from input
32
- const trade = {
33
- user: input.trader,
34
- index: input.index,
35
- pairIndex: input.pairIndex,
36
- leverage: input.leverage,
37
- long: input.long,
38
- isOpen: true,
39
- collateralIndex: input.collateralIndex,
40
- tradeType: 0,
41
- collateralAmount: input.collateral,
42
- openPrice: input.openPrice,
43
- sl: 0,
44
- tp: 0,
45
- isCounterTrade: input.isCounterTrade,
46
- };
47
- // Merge input params into context
48
- const fullContext = Object.assign(Object.assign({}, context), { currentPairPrice: input.currentPairPrice, isCounterTrade: input.isCounterTrade, partialCloseMultiplier: input.partialCloseMultiplier, additionalFeeCollateral: input.additionalFeeCollateral, beforeOpened: input.beforeOpened, liquidationParams: input.liquidationParams });
49
- // Call the existing implementation
50
- return (0, exports.getLiquidationPrice)(trade, context.fee, context.initialAccFees || { accPairFee: 0, accGroupFee: 0, block: 0 }, fullContext);
51
- };
52
- exports.getTradeLiquidationPrice = getTradeLiquidationPrice;
53
- const getLiquidationPrice = (trade, fee, initialAccFees, context) => {
54
- var _a, _b, _c, _d, _e, _f;
55
- // Ensure initialAccFees is in context
56
- if (!context.initialAccFees) {
57
- context = Object.assign(Object.assign({}, context), { initialAccFees });
58
- }
29
+ const getLiquidationPrice = (trade, context) => {
30
+ var _a, _b, _c;
31
+ // Extract legacy parameters from structured context
32
+ const { currentPairPrice, additionalFeeCollateral, partialCloseMultiplier, beforeOpened, } = context.liquidationSpecific;
59
33
  // 1. Calculate liquidation fees
60
- const closingFee = (0, __1.getTotalTradeLiqFeesCollateral)(0, // collateralIndex not used in calculation
61
- trade.user, trade.pairIndex, trade.collateralAmount, context);
34
+ const closingFee = (0, __1.getTotalTradeLiqFeesCollateral)(trade.collateralIndex, trade.user, trade.pairIndex, trade.collateralAmount, {
35
+ totalLiqCollateralFeeP: ((_a = context.tradeData.liquidationParams) === null || _a === void 0 ? void 0 : _a.endLiqThresholdP) || 0.9,
36
+ globalTradeFeeParams: context.trading.globalTradeFeeParams,
37
+ traderFeeMultiplier: context.trading.traderFeeMultiplier,
38
+ });
62
39
  // 2. Calculate holding fees and realized PnL
63
40
  let holdingFeesTotal = 0;
64
41
  let totalRealizedPnlCollateral = 0;
65
- if (!context.beforeOpened &&
66
- context.tradeFeesData &&
67
- context.currentPairPrice) {
42
+ if (!beforeOpened && context.tradeData.tradeFeesData && currentPairPrice) {
68
43
  // V10 data available - calculate full holding fees
69
- // Create a minimal tradeInfo from context
70
- const tradeInfo = {
71
- contractsVersion: (_a = context.contractsVersion) !== null && _a !== void 0 ? _a : types_1.ContractsVersion.V10,
72
- createdBlock: 0,
73
- tpLastUpdatedBlock: 0,
74
- slLastUpdatedBlock: 0,
75
- maxSlippageP: 0,
76
- lastOiUpdateTs: 0,
77
- collateralPriceUsd: (_b = context.collateralPriceUsd) !== null && _b !== void 0 ? _b : 0,
78
- lastPosIncreaseBlock: 0,
79
- };
80
- const holdingFees = (0, __1.getTradePendingHoldingFeesCollateral)(trade, tradeInfo, context.tradeFeesData, context.currentPairPrice, context);
44
+ const holdingFees = (0, __1.getTradePendingHoldingFeesCollateral)(trade, context.tradeData.tradeInfo, context.tradeData.tradeFeesData, currentPairPrice, {
45
+ contractsVersion: context.core.contractsVersion,
46
+ currentTimestamp: context.core.currentTimestamp,
47
+ collateralPriceUsd: context.core.collateralPriceUsd,
48
+ borrowingV1: context.borrowingV1,
49
+ borrowingV2: context.borrowingV2,
50
+ funding: context.funding,
51
+ initialAccFeesV1: context.tradeData.initialAccFeesV1,
52
+ });
81
53
  holdingFeesTotal = holdingFees.totalFeeCollateral;
82
54
  // Calculate total realized PnL (realized PnL minus realized trading fees)
83
55
  totalRealizedPnlCollateral =
84
- context.tradeFeesData.realizedPnlCollateral -
85
- context.tradeFeesData.realizedTradingFeesCollateral;
56
+ context.tradeData.tradeFeesData.realizedPnlCollateral -
57
+ context.tradeData.tradeFeesData.realizedTradingFeesCollateral;
86
58
  }
87
- else if (!context.beforeOpened) {
59
+ else if (!beforeOpened &&
60
+ context.borrowingV1 &&
61
+ context.tradeData.initialAccFeesV1) {
88
62
  // Markets using v1 borrowing fees model
89
- holdingFeesTotal = (0, __1.getBorrowingFee)(trade.collateralAmount * trade.leverage, trade.pairIndex, trade.long, initialAccFees, context);
63
+ holdingFeesTotal = (0, __1.getBorrowingFee)(trade.collateralAmount * trade.leverage, trade.pairIndex, trade.long, context.tradeData.initialAccFeesV1, context.borrowingV1);
90
64
  }
91
65
  // 3. Apply unified formula for all trades
92
- const partialCloseMultiplier = (_c = context.partialCloseMultiplier) !== null && _c !== void 0 ? _c : 1;
93
- const additionalFeeCollateral = (_d = context.additionalFeeCollateral) !== null && _d !== void 0 ? _d : 0;
94
66
  const totalFeesCollateral = closingFee +
95
67
  (holdingFeesTotal - totalRealizedPnlCollateral) * partialCloseMultiplier +
96
68
  additionalFeeCollateral;
97
69
  // 4. Calculate liquidation threshold
98
- const liqThresholdP = (0, exports.getLiqPnlThresholdP)(context.liquidationParams, trade.leverage);
70
+ const liqThresholdP = (0, exports.getLiqPnlThresholdP)(context.tradeData.liquidationParams, trade.leverage);
99
71
  // 5. Calculate liquidation price distance
100
72
  const collateralLiqNegativePnl = trade.collateralAmount * liqThresholdP;
101
73
  let liqPriceDistance = (trade.openPrice * (collateralLiqNegativePnl - totalFeesCollateral)) /
102
74
  trade.collateralAmount /
103
75
  trade.leverage;
104
76
  // 6. Apply closing spread for v9.2+
105
- if ((context === null || context === void 0 ? void 0 : context.contractsVersion) !== undefined &&
106
- context.contractsVersion >= types_1.ContractsVersion.V9_2 &&
107
- ((((_e = context === null || context === void 0 ? void 0 : context.liquidationParams) === null || _e === void 0 ? void 0 : _e.maxLiqSpreadP) !== undefined &&
108
- context.liquidationParams.maxLiqSpreadP > 0) ||
109
- (((_f = context === null || context === void 0 ? void 0 : context.userPriceImpact) === null || _f === void 0 ? void 0 : _f.fixedSpreadP) !== undefined &&
110
- context.userPriceImpact.fixedSpreadP > 0))) {
111
- const closingSpreadP = (0, __1.getSpreadP)(context.pairSpreadP, true, context.liquidationParams, context.userPriceImpact);
77
+ if (context.core.contractsVersion >= types_1.ContractsVersion.V9_2 &&
78
+ ((((_b = context.tradeData.liquidationParams) === null || _b === void 0 ? void 0 : _b.maxLiqSpreadP) !== undefined &&
79
+ context.tradeData.liquidationParams.maxLiqSpreadP > 0) ||
80
+ (((_c = context.liquidationSpecific.userPriceImpact) === null || _c === void 0 ? void 0 : _c.fixedSpreadP) !==
81
+ undefined &&
82
+ context.liquidationSpecific.userPriceImpact.fixedSpreadP > 0))) {
83
+ const closingSpreadP = (0, __1.getSpreadP)(context.core.spreadP, true, context.tradeData.liquidationParams, context.liquidationSpecific.userPriceImpact);
112
84
  liqPriceDistance -= trade.openPrice * closingSpreadP;
113
85
  }
114
86
  // 7. Calculate final liquidation price
@@ -153,29 +125,10 @@ exports.getLiqPnlThresholdP = getLiqPnlThresholdP;
153
125
  * @returns Liquidation price
154
126
  */
155
127
  const getTradeLiquidationPriceSimple = (trade, additionalFeeCollateral, currentPairPrice, context) => {
156
- const input = {
157
- collateralIndex: trade.collateralIndex,
158
- trader: trade.user,
159
- pairIndex: trade.pairIndex,
160
- index: trade.index,
161
- openPrice: trade.openPrice,
162
- long: trade.long,
163
- collateral: trade.collateralAmount,
164
- leverage: trade.leverage,
165
- additionalFeeCollateral,
166
- liquidationParams: context.liquidationParams || {
167
- maxLiqSpreadP: 0,
168
- startLiqThresholdP: 0.9,
169
- endLiqThresholdP: 0.9,
170
- startLeverage: 0,
171
- endLeverage: 0,
172
- },
173
- currentPairPrice,
174
- isCounterTrade: trade.isCounterTrade || false,
175
- partialCloseMultiplier: 1,
176
- beforeOpened: false,
177
- };
178
- return (0, exports.getTradeLiquidationPrice)(input, context);
128
+ // Build complete context with additional parameters
129
+ const fullContext = Object.assign(Object.assign({}, context), { liquidationSpecific: Object.assign(Object.assign({}, context.liquidationSpecific), { currentPairPrice,
130
+ additionalFeeCollateral, partialCloseMultiplier: 1, beforeOpened: false, isCounterTrade: trade.isCounterTrade || false }) });
131
+ return (0, exports.getLiquidationPrice)(trade, fullContext);
179
132
  };
180
133
  exports.getTradeLiquidationPriceSimple = getTradeLiquidationPriceSimple;
181
134
  // Converters
@@ -185,3 +138,5 @@ Object.defineProperty(exports, "convertLiquidationParamsArray", { enumerable: tr
185
138
  Object.defineProperty(exports, "encodeLiquidationParams", { enumerable: true, get: function () { return converter_1.encodeLiquidationParams; } });
186
139
  // Types
187
140
  __exportStar(require("./types"), exports);
141
+ // Builder
142
+ __exportStar(require("./builder"), exports);
@@ -1,8 +1,9 @@
1
1
  import { GetBorrowingFeeContext, BorrowingFee } from "./../fees";
2
- import { GetLiquidationFeesContext } from "./../fees/trading";
3
- import { BorrowingFeeV2 } from "./../fees/borrowingV2";
4
- import { LiquidationParams, UserPriceImpact, TradeFeesData } from "./../types";
2
+ import { LiquidationParams, UserPriceImpact, TradeFeesData, TradeInfo } from "./../types";
5
3
  import { ContractsVersion } from "../../contracts/types";
4
+ import { GetPairBorrowingFeeV2Context } from "../fees/borrowingV2";
5
+ import { GetPairFundingFeeContext } from "../fees/fundingFees";
6
+ import { TradingFeesSubContext } from "../fees/trading/builder";
6
7
  /**
7
8
  * @dev Input parameters for getTradeLiquidationPrice
8
9
  * @dev Mirrors the contract's LiqPriceInput struct
@@ -23,22 +24,36 @@ export type LiqPriceInput = {
23
24
  partialCloseMultiplier: number;
24
25
  beforeOpened: boolean;
25
26
  };
26
- export type GetLiquidationPriceContext = GetBorrowingFeeContext & BorrowingFeeV2.GetBorrowingFeeV2Context & GetLiquidationFeesContext & {
27
- liquidationParams: LiquidationParams | undefined;
28
- pairSpreadP: number | undefined;
29
- collateralPriceUsd: number | undefined;
30
- contractsVersion: ContractsVersion | undefined;
31
- userPriceImpact?: UserPriceImpact | undefined;
32
- currentPairPrice?: number;
33
- isCounterTrade?: boolean;
34
- tradeFeesData?: TradeFeesData;
35
- partialCloseMultiplier?: number;
36
- additionalFeeCollateral?: number;
37
- beforeOpened?: boolean;
38
- initialAccFees?: BorrowingFee.InitialAccFees;
39
- fundingParams?: Record<number, Record<number, any>>;
40
- fundingData?: Record<number, Record<number, any>>;
41
- pairOiAfterV10?: Record<number, Record<number, any>>;
42
- netExposureToken?: Record<number, Record<number, number>>;
43
- netExposureUsd?: Record<number, Record<number, number>>;
27
+ /**
28
+ * @dev Structured context for liquidation price calculations
29
+ * @dev Follows the same pattern as GetComprehensivePnlContext
30
+ */
31
+ export type GetLiquidationPriceContext = {
32
+ core: {
33
+ currentBlock: number;
34
+ currentTimestamp: number;
35
+ collateralPriceUsd: number;
36
+ contractsVersion: ContractsVersion;
37
+ spreadP: number;
38
+ };
39
+ borrowingV1?: GetBorrowingFeeContext;
40
+ borrowingV2?: GetPairBorrowingFeeV2Context;
41
+ funding?: GetPairFundingFeeContext;
42
+ trading: TradingFeesSubContext & {
43
+ userPriceImpact?: UserPriceImpact;
44
+ };
45
+ tradeData: {
46
+ tradeInfo: TradeInfo;
47
+ tradeFeesData: TradeFeesData;
48
+ liquidationParams: LiquidationParams;
49
+ initialAccFeesV1?: BorrowingFee.InitialAccFees;
50
+ };
51
+ liquidationSpecific: {
52
+ currentPairPrice: number;
53
+ additionalFeeCollateral: number;
54
+ partialCloseMultiplier: number;
55
+ beforeOpened: boolean;
56
+ isCounterTrade: boolean;
57
+ userPriceImpact?: UserPriceImpact;
58
+ };
44
59
  };
@@ -0,0 +1,16 @@
1
+ import { TradeContainer } from "../types";
2
+ import { GlobalTradingVariablesType } from "src/backend/tradingVariables/types";
3
+ import { GetComprehensivePnlContext } from "./types";
4
+ /**
5
+ * @dev Builds a complete context for comprehensive PnL calculations
6
+ * @dev Uses sub-context builders to create properly scoped contexts
7
+ * @param globalTradingVariables The transformed global trading variables from backend
8
+ * @param tradeContainer Full trade container with trade, tradeInfo, fees data and liquidation params
9
+ * @param additionalParams Additional parameters not available in trading variables
10
+ * @returns Complete context ready for getComprehensivePnl
11
+ */
12
+ export declare const buildComprehensivePnlContext: (globalTradingVariables: GlobalTradingVariablesType, tradeContainer: TradeContainer, additionalParams: {
13
+ currentBlock: number;
14
+ currentTimestamp: number;
15
+ traderFeeMultiplier?: number;
16
+ }) => GetComprehensivePnlContext;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildComprehensivePnlContext = void 0;
4
+ const builder_1 = require("../fees/borrowingV2/builder");
5
+ const builder_2 = require("../fees/fundingFees/builder");
6
+ const builder_3 = require("../fees/borrowing/builder");
7
+ const builder_4 = require("../fees/trading/builder");
8
+ /**
9
+ * @dev Builds a complete context for comprehensive PnL calculations
10
+ * @dev Uses sub-context builders to create properly scoped contexts
11
+ * @param globalTradingVariables The transformed global trading variables from backend
12
+ * @param tradeContainer Full trade container with trade, tradeInfo, fees data and liquidation params
13
+ * @param additionalParams Additional parameters not available in trading variables
14
+ * @returns Complete context ready for getComprehensivePnl
15
+ */
16
+ const buildComprehensivePnlContext = (globalTradingVariables, tradeContainer, additionalParams) => {
17
+ var _a;
18
+ const { trade, tradeInfo } = tradeContainer;
19
+ const collateralIndex = trade.collateralIndex || 1;
20
+ const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
21
+ return {
22
+ // Core shared context
23
+ core: {
24
+ currentBlock: additionalParams.currentBlock,
25
+ currentTimestamp: additionalParams.currentTimestamp,
26
+ collateralPriceUsd: ((_a = collateral.prices) === null || _a === void 0 ? void 0 : _a.collateralPriceUsd) || 1,
27
+ contractsVersion: tradeInfo.contractsVersion,
28
+ },
29
+ // Build sub-contexts using dedicated builders
30
+ borrowingV1: (0, builder_3.buildBorrowingV1Context)(globalTradingVariables, collateralIndex, additionalParams.currentBlock),
31
+ borrowingV2: (0, builder_1.buildBorrowingV2Context)(globalTradingVariables, collateralIndex, trade.pairIndex, additionalParams.currentTimestamp),
32
+ funding: (0, builder_2.buildFundingContext)(globalTradingVariables, collateralIndex, trade.pairIndex, additionalParams.currentTimestamp),
33
+ trading: (0, builder_4.buildTradingFeesContext)(globalTradingVariables, trade.pairIndex, additionalParams.traderFeeMultiplier),
34
+ // Trade-specific data
35
+ tradeData: tradeContainer.tradeFeesData && tradeContainer.liquidationParams
36
+ ? {
37
+ tradeFeesData: tradeContainer.tradeFeesData,
38
+ liquidationParams: tradeContainer.liquidationParams,
39
+ initialAccFeesV1: tradeContainer.initialAccFees,
40
+ }
41
+ : undefined,
42
+ };
43
+ };
44
+ exports.buildComprehensivePnlContext = buildComprehensivePnlContext;
@@ -2,10 +2,9 @@
2
2
  * @dev PnL calculation module
3
3
  * @dev Provides functions matching v10 contract implementations
4
4
  */
5
- import { Trade, TradeInfo, LiquidationParams } from "../types";
6
- import { ComprehensivePnlResult } from "./types";
7
- import { GetBorrowingFeeContext, BorrowingFee } from "../fees";
8
- import { GetTradeFeesContext } from "../fees/trading";
5
+ import { Trade, TradeInfo, LiquidationParams, Fee, GlobalTradeFeeParams } from "../types";
6
+ import { ComprehensivePnlResult, GetComprehensivePnlContext } from "./types";
7
+ import { BorrowingFee } from "../fees/borrowing";
9
8
  import { ContractsVersion } from "../../contracts/types";
10
9
  /**
11
10
  * @dev Calculates PnL percentage for a position
@@ -26,31 +25,6 @@ export declare const getPnlPercent: (openPrice: number, currentPrice: number, lo
26
25
  * @returns Trade value after PnL and fees
27
26
  */
28
27
  export declare const getTradeValue: (collateral: number, pnlPercent: number, totalFees: number) => number;
29
- /**
30
- * @dev Context for comprehensive PnL calculations
31
- */
32
- export type GetComprehensivePnlContext = GetBorrowingFeeContext & GetTradeFeesContext & {
33
- collateralPriceUsd: number;
34
- contractsVersion: ContractsVersion;
35
- currentTimestamp: number;
36
- initialAccFees?: BorrowingFee.InitialAccFees;
37
- borrowingProviderContext?: any;
38
- fundingParams?: any;
39
- fundingData?: any;
40
- pairOiAfterV10?: any;
41
- netExposureToken?: any;
42
- netExposureUsd?: any;
43
- tradeFeesData?: {
44
- initialAccFundingFeeP: number;
45
- initialAccBorrowingFeeP: number;
46
- realizedPnlCollateral: number;
47
- realizedTradingFeesCollateral: number;
48
- manuallyRealizedNegativePnlCollateral?: number;
49
- alreadyTransferredNegativePnlCollateral?: number;
50
- virtualAvailableCollateralInDiamond?: number;
51
- };
52
- liquidationParams?: LiquidationParams;
53
- };
54
28
  /**
55
29
  * @dev Comprehensive PnL calculation including all fees
56
30
  * @param trade The trade to calculate PnL for
@@ -64,10 +38,16 @@ export declare const getComprehensivePnl: (trade: Trade, currentPrice: number, t
64
38
  * @dev Legacy getPnl function for backward compatibility
65
39
  * @deprecated Use getComprehensivePnl for new implementations
66
40
  */
67
- export type GetPnlContext = GetBorrowingFeeContext & GetTradeFeesContext & {
41
+ export type GetPnlContext = {
42
+ currentBlock: number;
43
+ groups: BorrowingFee.Group[];
44
+ pairs: BorrowingFee.Pair[];
68
45
  collateralPriceUsd: number | undefined;
69
46
  contractsVersion: ContractsVersion | undefined;
70
47
  feeMultiplier: number | undefined;
48
+ fee: Fee;
49
+ globalTradeFeeParams: GlobalTradeFeeParams;
50
+ traderFeeMultiplier?: number;
71
51
  };
72
52
  /**
73
53
  * @dev Legacy PnL calculation function
@@ -82,5 +62,16 @@ export type GetPnlContext = GetBorrowingFeeContext & GetTradeFeesContext & {
82
62
  * @returns [pnlCollateral, pnlPercentage] or undefined if no price
83
63
  */
84
64
  export declare const getPnl: (price: number | undefined, trade: Trade, _tradeInfo: TradeInfo, initialAccFees: BorrowingFee.InitialAccFees, liquidationParams: LiquidationParams, useFees: boolean, context: GetPnlContext) => number[] | undefined;
65
+ /**
66
+ * @dev Calculates the price needed to achieve a target PnL percentage
67
+ * @param targetPnlPercent The target PnL percentage (e.g., 50 for 50% profit, -25 for 25% loss)
68
+ * @param trade The trade to calculate for
69
+ * @param tradeInfo Trade info with timestamps
70
+ * @param context Context with fee calculation parameters
71
+ * @param netPnl Whether to include closing fees in the calculation
72
+ * @returns The price that would result in the target PnL percentage
73
+ */
74
+ export declare const getPriceForTargetPnlPercentage: (targetPnlPercent: number, trade: Trade, tradeInfo: TradeInfo, context: GetComprehensivePnlContext, netPnl?: boolean) => number;
85
75
  export * from "./types";
86
76
  export * from "./converter";
77
+ export * from "./builder";