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

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 (66) hide show
  1. package/lib/backend/index.d.ts +1 -0
  2. package/lib/backend/index.js +10 -0
  3. package/lib/backend/tradingVariables/backend.types.d.ts +5 -0
  4. package/lib/backend/tradingVariables/converter.d.ts +2 -1
  5. package/lib/backend/tradingVariables/converter.js +2 -1
  6. package/lib/backend/tradingVariables/index.d.ts +2 -0
  7. package/lib/backend/tradingVariables/index.js +18 -0
  8. package/lib/backend/tradingVariables/types.d.ts +2 -1
  9. package/lib/constants.d.ts +10 -0
  10. package/lib/constants.js +11 -1
  11. package/lib/contracts/utils/pairs.js +10 -0
  12. package/lib/index.d.ts +1 -0
  13. package/lib/index.js +4 -0
  14. package/lib/trade/fees/borrowing/builder.d.ts +14 -0
  15. package/lib/trade/fees/borrowing/builder.js +33 -0
  16. package/lib/trade/fees/borrowing/index.d.ts +3 -2
  17. package/lib/trade/fees/borrowing/index.js +13 -4
  18. package/lib/trade/fees/borrowingV2/builder.d.ts +6 -0
  19. package/lib/trade/fees/borrowingV2/builder.js +24 -0
  20. package/lib/trade/fees/borrowingV2/converter.d.ts +12 -3
  21. package/lib/trade/fees/borrowingV2/converter.js +29 -18
  22. package/lib/trade/fees/borrowingV2/fetcher.js +5 -13
  23. package/lib/trade/fees/borrowingV2/index.d.ts +5 -17
  24. package/lib/trade/fees/borrowingV2/index.js +9 -37
  25. package/lib/trade/fees/borrowingV2/types.d.ts +22 -6
  26. package/lib/trade/fees/fundingFees/builder.d.ts +9 -0
  27. package/lib/trade/fees/fundingFees/builder.js +35 -0
  28. package/lib/trade/fees/fundingFees/index.d.ts +12 -2
  29. package/lib/trade/fees/fundingFees/index.js +23 -3
  30. package/lib/trade/fees/fundingFees/pairContext.d.ts +33 -0
  31. package/lib/trade/fees/fundingFees/pairContext.js +17 -0
  32. package/lib/trade/fees/index.d.ts +1 -1
  33. package/lib/trade/fees/index.js +2 -3
  34. package/lib/trade/fees/trading/builder.d.ts +18 -0
  35. package/lib/trade/fees/trading/builder.js +20 -0
  36. package/lib/trade/fees/trading/converter.d.ts +2 -0
  37. package/lib/trade/fees/trading/converter.js +5 -1
  38. package/lib/trade/fees/trading/holdingFees.d.ts +28 -0
  39. package/lib/trade/fees/trading/holdingFees.js +66 -0
  40. package/lib/trade/fees/trading/holdingFeesStructured.d.ts +28 -0
  41. package/lib/trade/fees/trading/holdingFeesStructured.js +66 -0
  42. package/lib/trade/fees/trading/index.d.ts +19 -11
  43. package/lib/trade/fees/trading/index.js +29 -21
  44. package/lib/trade/liquidation/builder.d.ts +25 -0
  45. package/lib/trade/liquidation/builder.js +59 -0
  46. package/lib/trade/liquidation/index.d.ts +7 -22
  47. package/lib/trade/liquidation/index.js +41 -105
  48. package/lib/trade/liquidation/types.d.ts +37 -39
  49. package/lib/trade/pnl/builder.d.ts +16 -0
  50. package/lib/trade/pnl/builder.js +44 -0
  51. package/lib/trade/pnl/index.d.ts +21 -30
  52. package/lib/trade/pnl/index.js +119 -50
  53. package/lib/trade/pnl/types.d.ts +26 -36
  54. package/lib/trade/types.d.ts +11 -1
  55. package/lib/trade/types.js +10 -0
  56. package/package.json +1 -1
  57. package/lib/contracts/fetch/fees/borrowingFeesV2.d.ts +0 -75
  58. package/lib/contracts/fetch/fees/borrowingFeesV2.js +0 -193
  59. package/lib/contracts/fetch/fees/fundingFees.d.ts +0 -66
  60. package/lib/contracts/fetch/fees/fundingFees.js +0 -150
  61. package/lib/contracts/fetch/priceImpact/skew.d.ts +0 -63
  62. package/lib/contracts/fetch/priceImpact/skew.js +0 -168
  63. package/lib/trade/liquidation.d.ts +0 -12
  64. package/lib/trade/liquidation.js +0 -55
  65. package/lib/trade/pnl.d.ts +0 -10
  66. package/lib/trade/pnl.js +0 -33
@@ -18,10 +18,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
20
  exports.getTradePendingHoldingFeesCollateral = exports.getClosingFee = exports.getTotalTradeLiqFeesCollateral = exports.getTradeFeesCollateral = exports.getTotalTradeFeesCollateral = void 0;
21
- const tiers_1 = require("../tiers");
22
- const fundingFees_1 = require("../fundingFees");
23
- const borrowingV2_1 = require("../borrowingV2");
24
21
  const borrowing_1 = require("../borrowing");
22
+ const borrowingV2_1 = require("../borrowingV2");
23
+ const fundingFees_1 = require("../fundingFees");
24
+ const tiers_1 = require("../tiers");
25
25
  const types_1 = require("../../../contracts/types");
26
26
  /**
27
27
  * @dev Returns the total fee for a trade in collateral tokens
@@ -109,29 +109,36 @@ exports.getClosingFee = getClosingFee;
109
109
  * @param tradeInfo Trade info containing contracts version
110
110
  * @param tradeFeesData Trade fees data containing initial acc fees
111
111
  * @param currentPairPrice Current pair price
112
- * @param context Context with fee parameters
112
+ * @param context Structured context with sub-contexts for each fee type
113
113
  * @returns Object containing all holding fee components
114
114
  */
115
115
  const getTradePendingHoldingFeesCollateral = (trade, tradeInfo, tradeFeesData, currentPairPrice, context) => {
116
- var _a;
116
+ const positionSizeCollateral = trade.collateralAmount * trade.leverage;
117
117
  // Calculate funding fees (v10+ only)
118
- const fundingFeeCollateral = ((_a = context.contractsVersion) !== null && _a !== void 0 ? _a : tradeInfo.contractsVersion) >=
119
- types_1.ContractsVersion.V10
120
- ? (0, fundingFees_1.getTradeFundingFeesCollateral)(trade, tradeInfo, tradeFeesData, currentPairPrice, context)
121
- : 0;
122
- // Calculate borrowing fees v2
123
- const borrowingFeeCollateral = (0, borrowingV2_1.getTradeBorrowingFeesCollateral)({
124
- positionSizeCollateral: trade.collateralAmount * trade.leverage,
125
- openPrice: trade.openPrice,
126
- collateralIndex: trade.collateralIndex,
127
- pairIndex: trade.pairIndex,
128
- currentPairPrice,
129
- initialAccBorrowingFeeP: tradeFeesData.initialAccBorrowingFeeP,
130
- currentTimestamp: context.currentTimestamp,
131
- }, context);
118
+ let fundingFeeCollateral = 0;
119
+ if (context.contractsVersion >= types_1.ContractsVersion.V10 &&
120
+ context.funding &&
121
+ tradeFeesData.initialAccFundingFeeP !== undefined) {
122
+ fundingFeeCollateral = (0, fundingFees_1.getTradeFundingFeesCollateral)(trade, tradeInfo, tradeFeesData, currentPairPrice, Object.assign(Object.assign({}, context.funding), { currentTimestamp: context.currentTimestamp }));
123
+ }
124
+ // Calculate borrowing fees v2 (v10+ only)
125
+ let borrowingFeeCollateral = 0;
126
+ if (context.contractsVersion >= types_1.ContractsVersion.V10 &&
127
+ context.borrowingV2 &&
128
+ tradeFeesData.initialAccBorrowingFeeP !== undefined) {
129
+ borrowingFeeCollateral = (0, borrowingV2_1.getTradeBorrowingFeesCollateral)({
130
+ positionSizeCollateral,
131
+ openPrice: trade.openPrice,
132
+ currentPairPrice,
133
+ initialAccBorrowingFeeP: tradeFeesData.initialAccBorrowingFeeP,
134
+ currentTimestamp: context.currentTimestamp,
135
+ }, context.borrowingV2);
136
+ }
132
137
  // Calculate v1 borrowing fees (some markets use v1 indefinitely)
133
- const borrowingFeeCollateral_old = (0, borrowing_1.getBorrowingFee)(trade.collateralAmount * trade.leverage, trade.pairIndex, trade.long, context.initialAccFees || { accPairFee: 0, accGroupFee: 0, block: 0 }, // Use context initial fees or empty
134
- context);
138
+ let borrowingFeeCollateral_old = 0;
139
+ if (context.borrowingV1 && context.initialAccFees) {
140
+ borrowingFeeCollateral_old = (0, borrowing_1.getBorrowingFee)(positionSizeCollateral, trade.pairIndex, trade.long, context.initialAccFees, context.borrowingV1);
141
+ }
135
142
  return {
136
143
  fundingFeeCollateral,
137
144
  borrowingFeeCollateral,
@@ -145,3 +152,4 @@ exports.getTradePendingHoldingFeesCollateral = getTradePendingHoldingFeesCollate
145
152
  // Export types
146
153
  __exportStar(require("./types"), exports);
147
154
  __exportStar(require("./converter"), exports);
155
+ __exportStar(require("./builder"), exports);
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @dev Liquidation price context builder module
3
+ * @dev Provides builder functions for creating liquidation price contexts
4
+ */
5
+ import { GlobalTradingVariablesType } from "../../backend/tradingVariables/types";
6
+ import { TradeContainer, UserPriceImpact } from "../types";
7
+ import { GetLiquidationPriceContext } from "./types";
8
+ /**
9
+ * @dev Builds a complete context for liquidation price calculations
10
+ * @param globalTradingVariables The transformed global trading variables from backend
11
+ * @param tradeContainer Full trade container with trade, tradeInfo, fees data and liquidation params
12
+ * @param additionalParams Additional parameters not available in trading variables
13
+ * @returns Complete context ready for getLiquidationPrice
14
+ */
15
+ export declare const buildLiquidationPriceContext: (globalTradingVariables: GlobalTradingVariablesType, tradeContainer: TradeContainer, additionalParams: {
16
+ currentBlock: number;
17
+ currentTimestamp: number;
18
+ currentPairPrice: number;
19
+ spreadP: number;
20
+ traderFeeMultiplier?: number;
21
+ additionalFeeCollateral?: number;
22
+ partialCloseMultiplier?: number;
23
+ beforeOpened?: boolean;
24
+ userPriceImpact?: UserPriceImpact;
25
+ }) => GetLiquidationPriceContext;
@@ -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: Object.assign(Object.assign({}, (0, builder_4.buildTradingFeesContext)(globalTradingVariables, trade.pairIndex, additionalParams.traderFeeMultiplier)), { counterTradeSettings: globalTradingVariables.counterTradeSettings, userPriceImpact: additionalParams.userPriceImpact }),
41
+ // Trade-specific data
42
+ tradeData: {
43
+ tradeInfo,
44
+ tradeFeesData: tradeContainer.tradeFeesData,
45
+ liquidationParams: tradeContainer.liquidationParams,
46
+ initialAccFees: 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,31 +1,16 @@
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
11
- * @returns Liquidation price
12
- */
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;
17
- export declare const getLiqPnlThresholdP: (liquidationParams: LiquidationParams | undefined, leverage: number | undefined) => number;
18
- /**
19
- * @dev Simplified wrapper for getTradeLiquidationPrice
20
- * @dev Mirrors the contract's simplified overload
7
+ * @dev Calculate liquidation price with structured context
21
8
  * @param trade The trade to calculate liquidation price for
22
- * @param additionalFeeCollateral Additional fees to consider
23
- * @param currentPairPrice Current pair price
24
- * @param context Context with all required data
9
+ * @param context Structured context with all required data
25
10
  * @returns Liquidation price
26
11
  */
27
- export declare const getTradeLiquidationPriceSimple: (trade: Trade, additionalFeeCollateral: number, currentPairPrice: number, context: Omit<GetLiquidationPriceContext, "currentPairPrice" | "additionalFeeCollateral"> & {
28
- fee: Fee;
29
- }) => number;
12
+ export declare const getLiquidationPrice: (trade: Trade, context: GetLiquidationPriceContext) => number;
13
+ export declare const getLiqPnlThresholdP: (liquidationParams: LiquidationParams | undefined, leverage: number | undefined) => number;
30
14
  export { convertLiquidationParams, convertLiquidationParamsArray, encodeLiquidationParams, } from "./converter";
31
15
  export * from "./types";
16
+ export * from "./builder";
@@ -17,98 +17,67 @@ 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.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
- }
59
- // 1. Calculate liquidation fees
60
- const closingFee = (0, __1.getTotalTradeLiqFeesCollateral)(0, // collateralIndex not used in calculation
61
- trade.user, trade.pairIndex, trade.collateralAmount, context);
62
- // 2. Calculate holding fees and realized PnL
29
+ const getLiquidationPrice = (trade, context) => {
30
+ var _a, _b;
31
+ // Extract parameters from structured context
32
+ const { currentPairPrice, additionalFeeCollateral = 0, partialCloseMultiplier = 1, beforeOpened = false, isCounterTrade = false, } = context.liquidationSpecific;
33
+ // 1. Calculate closing fees
34
+ const closingFee = (0, __1.getTotalTradeFeesCollateral)(trade.collateralIndex, "", // No fee tiers applied for liquidation calculation
35
+ trade.pairIndex, trade.collateralAmount * trade.leverage, isCounterTrade, {
36
+ fee: context.trading.fee,
37
+ collateralPriceUsd: context.core.collateralPriceUsd,
38
+ globalTradeFeeParams: context.trading.globalTradeFeeParams,
39
+ traderFeeMultiplier: 1,
40
+ counterTradeSettings: context.trading.counterTradeSettings,
41
+ });
42
+ // 2. Calculate holding fees and realized PnL for opened trades
63
43
  let holdingFeesTotal = 0;
64
44
  let totalRealizedPnlCollateral = 0;
65
- if (!context.beforeOpened &&
66
- context.tradeFeesData &&
67
- context.currentPairPrice) {
68
- // 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);
45
+ if (!beforeOpened) {
46
+ // Calculate holding fees
47
+ const holdingFees = (0, __1.getTradePendingHoldingFeesCollateral)(trade, context.tradeData.tradeInfo, context.tradeData.tradeFeesData, currentPairPrice, {
48
+ contractsVersion: context.core.contractsVersion,
49
+ currentTimestamp: context.core.currentTimestamp,
50
+ collateralPriceUsd: context.core.collateralPriceUsd,
51
+ borrowingV1: context.borrowingV1,
52
+ borrowingV2: context.borrowingV2,
53
+ funding: context.funding,
54
+ initialAccFees: context.tradeData.initialAccFees,
55
+ });
81
56
  holdingFeesTotal = holdingFees.totalFeeCollateral;
82
57
  // Calculate total realized PnL (realized PnL minus realized trading fees)
83
58
  totalRealizedPnlCollateral =
84
- context.tradeFeesData.realizedPnlCollateral -
85
- context.tradeFeesData.realizedTradingFeesCollateral;
86
- }
87
- else if (!context.beforeOpened) {
88
- // Markets using v1 borrowing fees model
89
- holdingFeesTotal = (0, __1.getBorrowingFee)(trade.collateralAmount * trade.leverage, trade.pairIndex, trade.long, initialAccFees, context);
59
+ context.tradeData.tradeFeesData.realizedPnlCollateral -
60
+ context.tradeData.tradeFeesData.realizedTradingFeesCollateral;
90
61
  }
91
62
  // 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
63
  const totalFeesCollateral = closingFee +
95
64
  (holdingFeesTotal - totalRealizedPnlCollateral) * partialCloseMultiplier +
96
65
  additionalFeeCollateral;
97
66
  // 4. Calculate liquidation threshold
98
- const liqThresholdP = (0, exports.getLiqPnlThresholdP)(context.liquidationParams, trade.leverage);
67
+ const liqThresholdP = (0, exports.getLiqPnlThresholdP)(context.tradeData.liquidationParams, trade.leverage);
99
68
  // 5. Calculate liquidation price distance
100
69
  const collateralLiqNegativePnl = trade.collateralAmount * liqThresholdP;
101
70
  let liqPriceDistance = (trade.openPrice * (collateralLiqNegativePnl - totalFeesCollateral)) /
102
71
  trade.collateralAmount /
103
72
  trade.leverage;
104
73
  // 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);
74
+ if (context.core.contractsVersion >= types_1.ContractsVersion.V9_2 &&
75
+ ((((_a = context.tradeData.liquidationParams) === null || _a === void 0 ? void 0 : _a.maxLiqSpreadP) !== undefined &&
76
+ context.tradeData.liquidationParams.maxLiqSpreadP > 0) ||
77
+ (((_b = context.liquidationSpecific.userPriceImpact) === null || _b === void 0 ? void 0 : _b.fixedSpreadP) !==
78
+ undefined &&
79
+ context.liquidationSpecific.userPriceImpact.fixedSpreadP > 0))) {
80
+ const closingSpreadP = (0, __1.getSpreadP)(context.core.spreadP, true, context.tradeData.liquidationParams, context.liquidationSpecific.userPriceImpact);
112
81
  liqPriceDistance -= trade.openPrice * closingSpreadP;
113
82
  }
114
83
  // 7. Calculate final liquidation price
@@ -143,41 +112,6 @@ const getLiqPnlThresholdP = (liquidationParams, leverage) => {
143
112
  (liquidationParams.endLeverage - liquidationParams.startLeverage));
144
113
  };
145
114
  exports.getLiqPnlThresholdP = getLiqPnlThresholdP;
146
- /**
147
- * @dev Simplified wrapper for getTradeLiquidationPrice
148
- * @dev Mirrors the contract's simplified overload
149
- * @param trade The trade to calculate liquidation price for
150
- * @param additionalFeeCollateral Additional fees to consider
151
- * @param currentPairPrice Current pair price
152
- * @param context Context with all required data
153
- * @returns Liquidation price
154
- */
155
- 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);
179
- };
180
- exports.getTradeLiquidationPriceSimple = getTradeLiquidationPriceSimple;
181
115
  // Converters
182
116
  var converter_1 = require("./converter");
183
117
  Object.defineProperty(exports, "convertLiquidationParams", { enumerable: true, get: function () { return converter_1.convertLiquidationParams; } });
@@ -185,3 +119,5 @@ Object.defineProperty(exports, "convertLiquidationParamsArray", { enumerable: tr
185
119
  Object.defineProperty(exports, "encodeLiquidationParams", { enumerable: true, get: function () { return converter_1.encodeLiquidationParams; } });
186
120
  // Types
187
121
  __exportStar(require("./types"), exports);
122
+ // Builder
123
+ __exportStar(require("./builder"), exports);
@@ -1,44 +1,42 @@
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, CounterTradeSettings } 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
- * @dev Input parameters for getTradeLiquidationPrice
8
- * @dev Mirrors the contract's LiqPriceInput struct
8
+ * @dev Structured context for liquidation price calculations
9
+ * @dev Follows the same pattern as GetComprehensivePnlContext
9
10
  */
10
- export type LiqPriceInput = {
11
- collateralIndex: number;
12
- trader: string;
13
- pairIndex: number;
14
- index: number;
15
- openPrice: number;
16
- long: boolean;
17
- collateral: number;
18
- leverage: number;
19
- additionalFeeCollateral: number;
20
- liquidationParams: LiquidationParams;
21
- currentPairPrice: number;
22
- isCounterTrade: boolean;
23
- partialCloseMultiplier: number;
24
- beforeOpened: boolean;
25
- };
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>>;
11
+ export type GetLiquidationPriceContext = {
12
+ core: {
13
+ currentBlock: number;
14
+ currentTimestamp: number;
15
+ collateralPriceUsd: number;
16
+ contractsVersion: ContractsVersion;
17
+ spreadP: number;
18
+ };
19
+ borrowingV1?: GetBorrowingFeeContext;
20
+ borrowingV2?: GetPairBorrowingFeeV2Context;
21
+ funding?: GetPairFundingFeeContext;
22
+ trading: TradingFeesSubContext & {
23
+ userPriceImpact?: UserPriceImpact;
24
+ counterTradeSettings?: {
25
+ [pairIndex: number]: CounterTradeSettings;
26
+ };
27
+ };
28
+ tradeData: {
29
+ tradeInfo: TradeInfo;
30
+ tradeFeesData: TradeFeesData;
31
+ liquidationParams: LiquidationParams;
32
+ initialAccFees?: BorrowingFee.InitialAccFees;
33
+ };
34
+ liquidationSpecific: {
35
+ currentPairPrice: number;
36
+ additionalFeeCollateral: number;
37
+ partialCloseMultiplier: number;
38
+ beforeOpened: boolean;
39
+ isCounterTrade: boolean;
40
+ userPriceImpact?: UserPriceImpact;
41
+ };
44
42
  };
@@ -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
+ initialAccFees: 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";