@gainsnetwork/sdk 1.3.0-rc3 → 1.3.0-rc6

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 (47) hide show
  1. package/lib/backend/globalTrades/index.js +10 -10
  2. package/lib/backend/tradingVariables/converter.js +58 -57
  3. package/lib/backend/tradingVariables/index.js +6 -7
  4. package/lib/contracts/addresses.js +4 -1
  5. package/lib/contracts/index.d.ts +1 -1
  6. package/lib/contracts/index.js +3 -3
  7. package/lib/contracts/utils/borrowingFees.js +9 -20
  8. package/lib/contracts/utils/openTrades.js +11 -20
  9. package/lib/contracts/utils/pairs.js +21 -30
  10. package/lib/markets/forex.js +1 -1
  11. package/lib/markets/leverage/builder.js +2 -2
  12. package/lib/markets/price/index.d.ts +1 -0
  13. package/lib/markets/price/index.js +1 -0
  14. package/lib/markets/price/types.d.ts +27 -0
  15. package/lib/pricing/depthBands.d.ts +1 -1
  16. package/lib/pricing/depthBands.js +7 -5
  17. package/lib/trade/fees/borrowing/builder.js +2 -3
  18. package/lib/trade/fees/borrowing/converter.js +5 -1
  19. package/lib/trade/fees/borrowing/index.js +5 -5
  20. package/lib/trade/fees/borrowingV2/builder.js +3 -4
  21. package/lib/trade/fees/borrowingV2/converter.js +1 -1
  22. package/lib/trade/fees/borrowingV2/fetcher.js +26 -32
  23. package/lib/trade/fees/borrowingV2/index.js +3 -3
  24. package/lib/trade/fees/converter.js +22 -22
  25. package/lib/trade/fees/fundingFees/builder.js +6 -7
  26. package/lib/trade/fees/fundingFees/converter.js +1 -1
  27. package/lib/trade/fees/fundingFees/fetcher.js +16 -25
  28. package/lib/trade/fees/fundingFees/index.js +2 -3
  29. package/lib/trade/fees/tiers/index.js +1 -2
  30. package/lib/trade/fees/trading/index.js +5 -3
  31. package/lib/trade/liquidation/builder.js +1 -2
  32. package/lib/trade/liquidation/index.js +4 -6
  33. package/lib/trade/oiWindows.js +1 -2
  34. package/lib/trade/pnl/builder.js +1 -2
  35. package/lib/trade/pnl/converter.js +1 -1
  36. package/lib/trade/pnl/index.js +4 -7
  37. package/lib/trade/priceImpact/close/builder.js +1 -2
  38. package/lib/trade/priceImpact/close/index.js +4 -1
  39. package/lib/trade/priceImpact/cumulVol/builder.js +20 -10
  40. package/lib/trade/priceImpact/cumulVol/index.d.ts +3 -3
  41. package/lib/trade/priceImpact/cumulVol/index.js +47 -20
  42. package/lib/trade/priceImpact/open/builder.js +1 -2
  43. package/lib/trade/priceImpact/open/index.js +7 -1
  44. package/lib/trade/priceImpact/skew/builder.js +2 -3
  45. package/lib/trade/priceImpact/skew/converter.js +1 -1
  46. package/lib/trade/priceImpact/skew/fetcher.js +24 -33
  47. package/package.json +2 -2
@@ -9,14 +9,13 @@ const index_1 = require("../../../markets/oi/index");
9
9
  * @dev Builds funding fees sub-context for a specific pair
10
10
  */
11
11
  const buildFundingContext = (globalTradingVariables, collateralIndex, pairIndex, currentTimestamp) => {
12
- var _a, _b, _c, _d, _e;
13
12
  const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
14
- if (!(collateral === null || collateral === void 0 ? void 0 : collateral.pairFundingFees)) {
13
+ if (!collateral?.pairFundingFees) {
15
14
  return undefined;
16
15
  }
17
- const params = (_a = collateral.pairFundingFees.params) === null || _a === void 0 ? void 0 : _a[pairIndex];
18
- const data = (_b = collateral.pairFundingFees.data) === null || _b === void 0 ? void 0 : _b[pairIndex];
19
- const pairOi = (_c = collateral.pairOis) === null || _c === void 0 ? void 0 : _c[pairIndex];
16
+ const params = collateral.pairFundingFees.params?.[pairIndex];
17
+ const data = collateral.pairFundingFees.data?.[pairIndex];
18
+ const pairOi = collateral.pairOis?.[pairIndex];
20
19
  const netExposureToken = (0, index_1.getPairV10OiTokenSkewCollateral)(pairIndex, {
21
20
  pairOis: collateral.pairOis,
22
21
  });
@@ -28,8 +27,8 @@ const buildFundingContext = (globalTradingVariables, collateralIndex, pairIndex,
28
27
  data,
29
28
  pairOi: pairOi
30
29
  ? {
31
- oiLongToken: ((_d = pairOi.token) === null || _d === void 0 ? void 0 : _d.long) || 0,
32
- oiShortToken: ((_e = pairOi.token) === null || _e === void 0 ? void 0 : _e.short) || 0,
30
+ oiLongToken: pairOi.token?.long || 0,
31
+ oiShortToken: pairOi.token?.short || 0,
33
32
  }
34
33
  : undefined,
35
34
  currentTimestamp,
@@ -111,7 +111,7 @@ exports.convertTradeInitialAccFundingFees = convertTradeInitialAccFundingFees;
111
111
  */
112
112
  const createFundingFeeContext = (collateralIndices, pairIndices, params, data, globalParams, currentTimestamp) => {
113
113
  const context = {
114
- currentTimestamp: currentTimestamp !== null && currentTimestamp !== void 0 ? currentTimestamp : Math.floor(Date.now() / 1000),
114
+ currentTimestamp: currentTimestamp ?? Math.floor(Date.now() / 1000),
115
115
  fundingParams: {},
116
116
  fundingData: {},
117
117
  globalParams: globalParams ? {} : undefined,
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.collateralToContractFormat = exports.priceToContractFormat = exports.fetchPairPendingAccFundingFeesBatch = exports.fetchTradeFeesDataBatch = exports.fetchTradeFeesData = exports.fetchTradeFundingFeesCollateral = exports.fetchPairPendingAccFundingFees = void 0;
13
4
  /**
@@ -18,9 +9,9 @@ exports.collateralToContractFormat = exports.priceToContractFormat = exports.fet
18
9
  * @param currentPairPrice Current pair price (1e10)
19
10
  * @returns Promise resolving to accumulated funding fees and current rate
20
11
  */
21
- const fetchPairPendingAccFundingFees = (contract, collateralIndex, pairIndex, currentPairPrice) => __awaiter(void 0, void 0, void 0, function* () {
12
+ const fetchPairPendingAccFundingFees = async (contract, collateralIndex, pairIndex, currentPairPrice) => {
22
13
  try {
23
- const result = yield contract.getPairPendingAccFundingFees(collateralIndex, pairIndex, currentPairPrice);
14
+ const result = await contract.getPairPendingAccFundingFees(collateralIndex, pairIndex, currentPairPrice);
24
15
  return {
25
16
  accFundingFeeLongP: Number(result.accFundingFeeLongP) / 1e20,
26
17
  accFundingFeeShortP: Number(result.accFundingFeeShortP) / 1e20,
@@ -31,7 +22,7 @@ const fetchPairPendingAccFundingFees = (contract, collateralIndex, pairIndex, cu
31
22
  console.error("Error fetching pair pending acc funding fees:", error);
32
23
  throw error;
33
24
  }
34
- });
25
+ };
35
26
  exports.fetchPairPendingAccFundingFees = fetchPairPendingAccFundingFees;
36
27
  /**
37
28
  * @dev Fetches funding fees for a specific trade in collateral tokens
@@ -41,9 +32,9 @@ exports.fetchPairPendingAccFundingFees = fetchPairPendingAccFundingFees;
41
32
  * @param currentPairPrice Current pair price (1e10)
42
33
  * @returns Promise resolving to funding fee in collateral tokens
43
34
  */
44
- const fetchTradeFundingFeesCollateral = (contract, trader, index, currentPairPrice) => __awaiter(void 0, void 0, void 0, function* () {
35
+ const fetchTradeFundingFeesCollateral = async (contract, trader, index, currentPairPrice) => {
45
36
  try {
46
- const fundingFeeCollateral = yield contract.getTradeFundingFeesCollateral(trader, index, currentPairPrice);
37
+ const fundingFeeCollateral = await contract.getTradeFundingFeesCollateral(trader, index, currentPairPrice);
47
38
  // Convert from BigNumber to number (collateral precision already applied)
48
39
  return Number(fundingFeeCollateral);
49
40
  }
@@ -51,7 +42,7 @@ const fetchTradeFundingFeesCollateral = (contract, trader, index, currentPairPri
51
42
  console.error("Error fetching trade funding fees:", error);
52
43
  throw error;
53
44
  }
54
- });
45
+ };
55
46
  exports.fetchTradeFundingFeesCollateral = fetchTradeFundingFeesCollateral;
56
47
  /**
57
48
  * @dev Fetches trade fees data for a specific trade
@@ -60,9 +51,9 @@ exports.fetchTradeFundingFeesCollateral = fetchTradeFundingFeesCollateral;
60
51
  * @param index Trade index
61
52
  * @returns Promise resolving to trade fees data
62
53
  */
63
- const fetchTradeFeesData = (contract, trader, index) => __awaiter(void 0, void 0, void 0, function* () {
54
+ const fetchTradeFeesData = async (contract, trader, index) => {
64
55
  try {
65
- const feesData = yield contract.getTradeFeesData(trader, index);
56
+ const feesData = await contract.getTradeFeesData(trader, index);
66
57
  return {
67
58
  accPerOiLong: Number(feesData.initialAccFundingFeeP) / 1e20,
68
59
  accPerOiShort: Number(feesData.initialAccFundingFeeP) / 1e20,
@@ -73,7 +64,7 @@ const fetchTradeFeesData = (contract, trader, index) => __awaiter(void 0, void 0
73
64
  console.error("Error fetching trade fees data:", error);
74
65
  throw error;
75
66
  }
76
- });
67
+ };
77
68
  exports.fetchTradeFeesData = fetchTradeFeesData;
78
69
  /**
79
70
  * @dev Fetches trade fees data for multiple trades
@@ -82,12 +73,12 @@ exports.fetchTradeFeesData = fetchTradeFeesData;
82
73
  * @param indices Array of trade indices
83
74
  * @returns Promise resolving to array of trade fees data
84
75
  */
85
- const fetchTradeFeesDataBatch = (contract, traders, indices) => __awaiter(void 0, void 0, void 0, function* () {
76
+ const fetchTradeFeesDataBatch = async (contract, traders, indices) => {
86
77
  if (traders.length !== indices.length) {
87
78
  throw new Error("Traders and indices arrays must have the same length");
88
79
  }
89
80
  try {
90
- const feesDatas = yield contract.getTradeFeesDataArray(traders, indices);
81
+ const feesDatas = await contract.getTradeFeesDataArray(traders, indices);
91
82
  return feesDatas.map(feesData => ({
92
83
  accPerOiLong: Number(feesData.initialAccFundingFeeP) / 1e20,
93
84
  accPerOiShort: Number(feesData.initialAccFundingFeeP) / 1e20,
@@ -98,7 +89,7 @@ const fetchTradeFeesDataBatch = (contract, traders, indices) => __awaiter(void 0
98
89
  console.error("Error fetching trade fees data batch:", error);
99
90
  throw error;
100
91
  }
101
- });
92
+ };
102
93
  exports.fetchTradeFeesDataBatch = fetchTradeFeesDataBatch;
103
94
  /**
104
95
  * @dev Fetches pending accumulated funding fees for multiple pairs
@@ -108,7 +99,7 @@ exports.fetchTradeFeesDataBatch = fetchTradeFeesDataBatch;
108
99
  * @param currentPairPrices Array of current pair prices (1e10)
109
100
  * @returns Promise resolving to array of accumulated funding fees
110
101
  */
111
- const fetchPairPendingAccFundingFeesBatch = (contract, collateralIndices, pairIndices, currentPairPrices) => __awaiter(void 0, void 0, void 0, function* () {
102
+ const fetchPairPendingAccFundingFeesBatch = async (contract, collateralIndices, pairIndices, currentPairPrices) => {
112
103
  if (collateralIndices.length !== pairIndices.length ||
113
104
  pairIndices.length !== currentPairPrices.length) {
114
105
  throw new Error("All input arrays must have the same length");
@@ -116,7 +107,7 @@ const fetchPairPendingAccFundingFeesBatch = (contract, collateralIndices, pairIn
116
107
  try {
117
108
  // Fetch all in parallel
118
109
  const promises = collateralIndices.map((collateralIndex, i) => contract.getPairPendingAccFundingFees(collateralIndex, pairIndices[i], currentPairPrices[i]));
119
- const results = yield Promise.all(promises);
110
+ const results = await Promise.all(promises);
120
111
  return results.map(result => ({
121
112
  accFundingFeeLongP: Number(result.accFundingFeeLongP) / 1e20,
122
113
  accFundingFeeShortP: Number(result.accFundingFeeShortP) / 1e20,
@@ -127,7 +118,7 @@ const fetchPairPendingAccFundingFeesBatch = (contract, collateralIndices, pairIn
127
118
  console.error("Error fetching pair pending acc funding fees batch:", error);
128
119
  throw error;
129
120
  }
130
- });
121
+ };
131
122
  exports.fetchPairPendingAccFundingFeesBatch = fetchPairPendingAccFundingFeesBatch;
132
123
  /**
133
124
  * @dev Helper to convert price from number to contract format
@@ -145,6 +136,6 @@ exports.priceToContractFormat = priceToContractFormat;
145
136
  * @returns Amount in contract format
146
137
  */
147
138
  const collateralToContractFormat = (amount, decimals) => {
148
- return BigInt(Math.round(amount * Math.pow(10, decimals)));
139
+ return BigInt(Math.round(amount * 10 ** decimals));
149
140
  };
150
141
  exports.collateralToContractFormat = collateralToContractFormat;
@@ -259,10 +259,9 @@ exports.getTradeFundingFeesCollateral = getTradeFundingFeesCollateral;
259
259
  * @returns Complete funding fee calculation result
260
260
  */
261
261
  const getTradeFundingFees = (input, context) => {
262
- var _a, _b;
263
262
  // Get params and data from context
264
- const params = (_a = context.fundingParams[input.collateralIndex]) === null || _a === void 0 ? void 0 : _a[input.pairIndex];
265
- const data = (_b = context.fundingData[input.collateralIndex]) === null || _b === void 0 ? void 0 : _b[input.pairIndex];
263
+ const params = context.fundingParams[input.collateralIndex]?.[input.pairIndex];
264
+ const data = context.fundingData[input.collateralIndex]?.[input.pairIndex];
266
265
  if (!params || !data) {
267
266
  throw new Error(`Missing funding fee data for collateral ${input.collateralIndex} pair ${input.pairIndex}`);
268
267
  }
@@ -24,9 +24,8 @@ exports.MAX_FEE_TIERS = 8;
24
24
  const getCurrentDay = () => Math.floor(Date.now() / 1000 / 60 / 60 / 24);
25
25
  exports.getCurrentDay = getCurrentDay;
26
26
  const getFeeTiersCount = (feeTiers) => {
27
- var _a;
28
27
  for (let i = exports.MAX_FEE_TIERS; i > 0; --i) {
29
- if (((_a = feeTiers[i - 1]) === null || _a === void 0 ? void 0 : _a.feeMultiplier) > 0) {
28
+ if (feeTiers[i - 1]?.feeMultiplier > 0) {
30
29
  return i;
31
30
  }
32
31
  }
@@ -35,11 +35,10 @@ const types_1 = require("../../../contracts/types");
35
35
  * @returns Total fee in collateral tokens
36
36
  */
37
37
  const getTotalTradeFeesCollateral = (collateralIndex, trader, pairIndex, positionSizeCollateral, isCounterTrade, context) => {
38
- var _a;
39
38
  const { fee, collateralPriceUsd } = context;
40
39
  const { totalPositionSizeFeeP, minPositionSizeUsd } = fee;
41
40
  // Get counter trade fee rate multiplier (default 1 = 1x)
42
- const counterTradeFeeRateMultiplier = isCounterTrade && ((_a = context.counterTradeSettings) === null || _a === void 0 ? void 0 : _a[pairIndex])
41
+ const counterTradeFeeRateMultiplier = isCounterTrade && context.counterTradeSettings?.[pairIndex]
43
42
  ? context.counterTradeSettings[pairIndex].feeRateMultiplier
44
43
  : 1;
45
44
  // Apply counter trade multiplier to position size
@@ -119,7 +118,10 @@ const getTradePendingHoldingFeesCollateral = (trade, tradeInfo, tradeFeesData, c
119
118
  if (context.contractsVersion >= types_1.ContractsVersion.V10 &&
120
119
  context.funding &&
121
120
  tradeFeesData.initialAccFundingFeeP !== undefined) {
122
- fundingFeeCollateral = (0, fundingFees_1.getTradeFundingFeesCollateral)(trade, tradeInfo, tradeFeesData, currentPairPrice, Object.assign(Object.assign({}, context.funding), { currentTimestamp: context.currentTimestamp }));
121
+ fundingFeeCollateral = (0, fundingFees_1.getTradeFundingFeesCollateral)(trade, tradeInfo, tradeFeesData, currentPairPrice, {
122
+ ...context.funding,
123
+ currentTimestamp: context.currentTimestamp,
124
+ });
123
125
  }
124
126
  // Calculate borrowing fees v2 (v10+ only)
125
127
  let borrowingFeeCollateral = 0;
@@ -17,7 +17,6 @@ const builder_4 = require("../fees/trading/builder");
17
17
  * @returns Complete context ready for getLiquidationPrice
18
18
  */
19
19
  const buildLiquidationPriceContext = (globalTradingVariables, tradeContainer, additionalParams) => {
20
- var _a;
21
20
  const { trade, tradeInfo } = tradeContainer;
22
21
  const collateralIndex = trade.collateralIndex || 1;
23
22
  const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
@@ -29,7 +28,7 @@ const buildLiquidationPriceContext = (globalTradingVariables, tradeContainer, ad
29
28
  core: {
30
29
  currentBlock: additionalParams.currentBlock,
31
30
  currentTimestamp: additionalParams.currentTimestamp,
32
- collateralPriceUsd: ((_a = collateral.prices) === null || _a === void 0 ? void 0 : _a.collateralPriceUsd) || 1,
31
+ collateralPriceUsd: collateral.prices?.collateralPriceUsd || 1,
33
32
  contractsVersion: tradeInfo.contractsVersion,
34
33
  spreadP: additionalParams.spreadP,
35
34
  },
@@ -27,7 +27,6 @@ const __1 = require("..");
27
27
  * @returns Liquidation price
28
28
  */
29
29
  const getLiquidationPrice = (trade, context) => {
30
- var _a, _b;
31
30
  // Extract parameters from structured context
32
31
  const { currentPairPrice, additionalFeeCollateral = 0, partialCloseMultiplier = 1, beforeOpened = false, isCounterTrade = false, } = context.liquidationSpecific;
33
32
  // 1. Calculate closing fees
@@ -72,9 +71,9 @@ const getLiquidationPrice = (trade, context) => {
72
71
  trade.leverage;
73
72
  // 6. Apply closing spread for v9.2+
74
73
  if (context.core.contractsVersion >= types_1.ContractsVersion.V9_2 &&
75
- ((((_a = context.tradeData.liquidationParams) === null || _a === void 0 ? void 0 : _a.maxLiqSpreadP) !== undefined &&
74
+ ((context.tradeData.liquidationParams?.maxLiqSpreadP !== undefined &&
76
75
  context.tradeData.liquidationParams.maxLiqSpreadP > 0) ||
77
- (((_b = context.liquidationSpecific.userPriceImpact) === null || _b === void 0 ? void 0 : _b.fixedSpreadP) !==
76
+ (context.liquidationSpecific.userPriceImpact?.fixedSpreadP !==
78
77
  undefined &&
79
78
  context.liquidationSpecific.userPriceImpact.fixedSpreadP > 0))) {
80
79
  const closingSpreadP = (0, __1.getSpreadP)(context.core.spreadP, true, context.tradeData.liquidationParams, context.liquidationSpecific.userPriceImpact);
@@ -99,7 +98,6 @@ exports.getLiquidationPrice = getLiquidationPrice;
99
98
  * @returns New liquidation price after the update
100
99
  */
101
100
  const getLiquidationPriceAfterPositionUpdate = (existingTrade, newCollateralAmount, newLeverage, isLeverageUpdate, positionSizeCollateralDelta, pnlToRealizeCollateral, context) => {
102
- var _a, _b;
103
101
  const { currentPairPrice, isCounterTrade = false } = context.liquidationSpecific;
104
102
  // 1. Calculate closing fees on the new position size
105
103
  const closingFeeCollateral = (0, __1.getTotalTradeFeesCollateral)(existingTrade.collateralIndex, "", // No fee tiers applied for liquidation calculation
@@ -167,9 +165,9 @@ const getLiquidationPriceAfterPositionUpdate = (existingTrade, newCollateralAmou
167
165
  newLeverage;
168
166
  // 9. Apply closing spread for v9.2+
169
167
  if (context.core.contractsVersion >= types_1.ContractsVersion.V9_2 &&
170
- ((((_a = context.tradeData.liquidationParams) === null || _a === void 0 ? void 0 : _a.maxLiqSpreadP) !== undefined &&
168
+ ((context.tradeData.liquidationParams?.maxLiqSpreadP !== undefined &&
171
169
  context.tradeData.liquidationParams.maxLiqSpreadP > 0) ||
172
- (((_b = context.liquidationSpecific.userPriceImpact) === null || _b === void 0 ? void 0 : _b.fixedSpreadP) !==
170
+ (context.liquidationSpecific.userPriceImpact?.fixedSpreadP !==
173
171
  undefined &&
174
172
  context.liquidationSpecific.userPriceImpact.fixedSpreadP > 0))) {
175
173
  const closingSpreadP = (0, __1.getSpreadP)(context.core.spreadP, true, context.tradeData.liquidationParams, context.liquidationSpecific.userPriceImpact);
@@ -7,13 +7,12 @@ const getCurrentOiWindowId = (oiWindowSettings) => {
7
7
  };
8
8
  exports.getCurrentOiWindowId = getCurrentOiWindowId;
9
9
  const getActiveOi = (currentOiWindowId, windowsCount, oiWindows, buy) => {
10
- var _a, _b;
11
10
  if (oiWindows === undefined || windowsCount === 0)
12
11
  return 0;
13
12
  let activeOi = 0;
14
13
  for (let id = currentOiWindowId - (windowsCount - 1); id <= currentOiWindowId; id++) {
15
14
  activeOi +=
16
- (buy ? (_a = oiWindows === null || oiWindows === void 0 ? void 0 : oiWindows[id]) === null || _a === void 0 ? void 0 : _a.oiLongUsd : (_b = oiWindows === null || oiWindows === void 0 ? void 0 : oiWindows[id]) === null || _b === void 0 ? void 0 : _b.oiShortUsd) || 0;
15
+ (buy ? oiWindows?.[id]?.oiLongUsd : oiWindows?.[id]?.oiShortUsd) || 0;
17
16
  }
18
17
  return activeOi;
19
18
  };
@@ -14,7 +14,6 @@ const builder_4 = require("../fees/trading/builder");
14
14
  * @returns Complete context ready for getComprehensivePnl
15
15
  */
16
16
  const buildComprehensivePnlContext = (globalTradingVariables, tradeContainer, additionalParams) => {
17
- var _a;
18
17
  const { trade, tradeInfo } = tradeContainer;
19
18
  const collateralIndex = trade.collateralIndex || 1;
20
19
  const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
@@ -23,7 +22,7 @@ const buildComprehensivePnlContext = (globalTradingVariables, tradeContainer, ad
23
22
  core: {
24
23
  currentBlock: additionalParams.currentBlock,
25
24
  currentTimestamp: additionalParams.currentTimestamp,
26
- collateralPriceUsd: ((_a = collateral.prices) === null || _a === void 0 ? void 0 : _a.collateralPriceUsd) || 1,
25
+ collateralPriceUsd: collateral.prices?.collateralPriceUsd || 1,
27
26
  contractsVersion: tradeInfo.contractsVersion,
28
27
  },
29
28
  // Build sub-contexts using dedicated builders
@@ -34,7 +34,7 @@ exports.encodePnlPercent = encodePnlPercent;
34
34
  */
35
35
  const convertCollateralAmount = (amount, collateralDecimals) => {
36
36
  const value = typeof amount === "bigint" ? Number(amount) : amount;
37
- return value / Math.pow(10, collateralDecimals);
37
+ return value / 10 ** collateralDecimals;
38
38
  };
39
39
  exports.convertCollateralAmount = convertCollateralAmount;
40
40
  /**
@@ -81,7 +81,6 @@ exports.getTradeValue = getTradeValue;
81
81
  * @returns Detailed PnL breakdown
82
82
  */
83
83
  const getComprehensivePnl = (trade, marketPrice, executionPrice, tradeInfo, context) => {
84
- var _a;
85
84
  // Calculate both raw PnL (market price) and impact-adjusted PnL (execution price)
86
85
  let rawPnlPercent = (0, exports.getPnlPercent)(trade.openPrice, marketPrice, trade.long, trade.leverage);
87
86
  let impactPnlPercent = (0, exports.getPnlPercent)(trade.openPrice, executionPrice, trade.long, trade.leverage);
@@ -115,7 +114,7 @@ const getComprehensivePnl = (trade, marketPrice, executionPrice, tradeInfo, cont
115
114
  const totalHoldingFees = borrowingFeeV1 + borrowingFeeV2 + fundingFee;
116
115
  const totalFees = totalHoldingFees + closingFee;
117
116
  // Check liquidation (using raw PnL for liquidation check)
118
- const liquidationThreshold = ((_a = context.tradeData) === null || _a === void 0 ? void 0 : _a.liquidationParams)
117
+ const liquidationThreshold = context.tradeData?.liquidationParams
119
118
  ? (0, liquidation_1.getLiqPnlThresholdP)(context.tradeData.liquidationParams, trade.leverage) *
120
119
  -100
121
120
  : -90; // Default 90% loss
@@ -192,7 +191,6 @@ exports.getComprehensivePnl = getComprehensivePnl;
192
191
  * @returns [pnlCollateral, pnlPercentage] or undefined if no price
193
192
  */
194
193
  const getPnl = (price, trade, _tradeInfo, initialAccFees, liquidationParams, useFees, context) => {
195
- var _a;
196
194
  if (!price) {
197
195
  return;
198
196
  }
@@ -224,7 +222,7 @@ const getPnl = (price, trade, _tradeInfo, initialAccFees, liquidationParams, use
224
222
  // Calculate closing fee using the same function as opening fees
225
223
  const positionSizeCollateral = posCollat * trade.leverage;
226
224
  const closingFee = (0, trading_1.getTotalTradeFeesCollateral)(0, // collateralIndex not used
227
- trade.user, trade.pairIndex, positionSizeCollateral, (_a = trade.isCounterTrade) !== null && _a !== void 0 ? _a : false, {
225
+ trade.user, trade.pairIndex, positionSizeCollateral, trade.isCounterTrade ?? false, {
228
226
  fee: context.fee,
229
227
  globalTradeFeeParams: context.globalTradeFeeParams,
230
228
  collateralPriceUsd: context.collateralPriceUsd || 1,
@@ -248,12 +246,11 @@ exports.getPnl = getPnl;
248
246
  * @returns The price that would result in the target PnL percentage
249
247
  */
250
248
  const getPriceForTargetPnlPercentage = (targetPnlPercent, trade, tradeInfo, context, netPnl = false) => {
251
- var _a, _b;
252
249
  const { leverage, openPrice, long, collateralAmount } = trade;
253
250
  const positionSizeCollateral = collateralAmount * leverage;
254
251
  // Calculate holding fees - always use getTradePendingHoldingFeesCollateral
255
252
  // This mirrors the contract's getTradeValueCollateral which always calls this function
256
- const fees = (0, trading_1.getTradePendingHoldingFeesCollateral)(trade, tradeInfo, ((_a = context.tradeData) === null || _a === void 0 ? void 0 : _a.tradeFeesData) || {
253
+ const fees = (0, trading_1.getTradePendingHoldingFeesCollateral)(trade, tradeInfo, context.tradeData?.tradeFeesData || {
257
254
  realizedTradingFeesCollateral: 0,
258
255
  realizedPnlCollateral: 0,
259
256
  manuallyRealizedNegativePnlCollateral: 0,
@@ -269,7 +266,7 @@ const getPriceForTargetPnlPercentage = (targetPnlPercent, trade, tradeInfo, cont
269
266
  borrowingV1: context.borrowingV1,
270
267
  borrowingV2: context.borrowingV2,
271
268
  funding: context.funding,
272
- initialAccFees: (_b = context.tradeData) === null || _b === void 0 ? void 0 : _b.initialAccFees,
269
+ initialAccFees: context.tradeData?.initialAccFees,
273
270
  });
274
271
  const totalHoldingFees = fees.fundingFeeCollateral +
275
272
  fees.borrowingFeeCollateral +
@@ -14,7 +14,6 @@ const builder_2 = require("../skew/builder");
14
14
  * @returns Complete context ready for getTradeClosingPriceImpact
15
15
  */
16
16
  const buildTradeClosingPriceImpactContext = (globalTradingVariables, collateralIndex, pairIndex, tradeInfo, additionalParams) => {
17
- var _a;
18
17
  const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
19
18
  if (!collateral) {
20
19
  return undefined;
@@ -36,7 +35,7 @@ const buildTradeClosingPriceImpactContext = (globalTradingVariables, collateralI
36
35
  }
37
36
  // Return structured context with proper subcontexts
38
37
  return {
39
- collateralPriceUsd: ((_a = collateral.prices) === null || _a === void 0 ? void 0 : _a.collateralPriceUsd) || 1,
38
+ collateralPriceUsd: collateral.prices?.collateralPriceUsd || 1,
40
39
  cumulVolContext,
41
40
  skewContext,
42
41
  tradeInfo,
@@ -129,6 +129,9 @@ exports.getTradeClosingPriceImpact = getTradeClosingPriceImpact;
129
129
  * @returns Price impact breakdown and trade value
130
130
  */
131
131
  const getTradeClosingPriceImpactAtOracle = (input, context) => {
132
- return (0, exports.getTradeClosingPriceImpact)(Object.assign(Object.assign({}, input), { currentPairPrice: input.oraclePrice }), context);
132
+ return (0, exports.getTradeClosingPriceImpact)({
133
+ ...input,
134
+ currentPairPrice: input.oraclePrice,
135
+ }, context);
133
136
  };
134
137
  exports.getTradeClosingPriceImpactAtOracle = getTradeClosingPriceImpactAtOracle;
@@ -10,15 +10,15 @@ exports.buildCumulVolContext = void 0;
10
10
  * @returns Cumulative volume context ready for getTradeCumulVolPriceImpactP
11
11
  */
12
12
  const buildCumulVolContext = (globalTradingVariables, collateralIndex, pairIndex, additionalParams) => {
13
- var _a, _b, _c, _d, _e, _f, _g, _h;
14
13
  const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
15
14
  if (!collateral) {
16
15
  return undefined;
17
16
  }
18
17
  // Get pair-specific data from global variables
19
- const pairDepthBands = (_a = globalTradingVariables.pairDepthBands) === null || _a === void 0 ? void 0 : _a[pairIndex];
20
- const pairFactor = (_b = globalTradingVariables.pairFactors) === null || _b === void 0 ? void 0 : _b[pairIndex];
21
- const oiWindows = (_c = globalTradingVariables.oiWindows) === null || _c === void 0 ? void 0 : _c[pairIndex];
18
+ const pairDepthBands = globalTradingVariables.pairDepthBands?.[pairIndex];
19
+ const depthBandsMapping = globalTradingVariables.depthBandsMapping;
20
+ const pairFactor = globalTradingVariables.pairFactors?.[pairIndex];
21
+ const oiWindows = globalTradingVariables.oiWindows?.[pairIndex];
22
22
  // Get OI windows settings (same for all pairs)
23
23
  // OI windows settings from global trading variables are already in SDK format
24
24
  const oiWindowsSettings = globalTradingVariables.oiWindowsSettings;
@@ -26,18 +26,28 @@ const buildCumulVolContext = (globalTradingVariables, collateralIndex, pairIndex
26
26
  const userPriceImpact = additionalParams.userPriceImpact;
27
27
  const protectionCloseFactorWhitelist = additionalParams.protectionCloseFactorWhitelist;
28
28
  // Get liquidation params - check both pair and group level
29
- const liquidationParams = ((_e = (_d = globalTradingVariables.liquidationParams) === null || _d === void 0 ? void 0 : _d.pairs) === null || _e === void 0 ? void 0 : _e[pairIndex]) ||
30
- ((_g = (_f = globalTradingVariables.liquidationParams) === null || _f === void 0 ? void 0 : _f.groups) === null || _g === void 0 ? void 0 : _g[0]); // fallback to first group
31
- return Object.assign({
29
+ const liquidationParams = globalTradingVariables.liquidationParams?.pairs?.[pairIndex] ||
30
+ globalTradingVariables.liquidationParams?.groups?.[0]; // fallback to first group
31
+ return {
32
32
  // Trade state
33
- isOpen: additionalParams.isOpen, isPnlPositive: additionalParams.isPnlPositive, createdBlock: additionalParams.createdBlock,
33
+ isOpen: additionalParams.isOpen,
34
+ isPnlPositive: additionalParams.isPnlPositive,
35
+ createdBlock: additionalParams.createdBlock,
34
36
  // Protection factors
35
- liquidationParams, currentBlock: additionalParams.currentBlock, contractsVersion: additionalParams.contractsVersion, protectionCloseFactorWhitelist,
37
+ liquidationParams,
38
+ currentBlock: additionalParams.currentBlock,
39
+ contractsVersion: additionalParams.contractsVersion,
40
+ protectionCloseFactorWhitelist,
36
41
  // Price impact data
37
42
  pairDepthBands,
43
+ depthBandsMapping,
38
44
  oiWindowsSettings,
39
45
  oiWindows,
40
46
  // User/collateral specific
41
- userPriceImpact, collateralPriceUsd: ((_h = collateral.prices) === null || _h === void 0 ? void 0 : _h.collateralPriceUsd) || 1 }, pairFactor);
47
+ userPriceImpact,
48
+ collateralPriceUsd: collateral.prices?.collateralPriceUsd || 1,
49
+ // Pair factors (spread across the context)
50
+ ...pairFactor,
51
+ };
42
52
  };
43
53
  exports.buildCumulVolContext = buildCumulVolContext;
@@ -57,7 +57,7 @@ export declare const getLegacyFactor: (context: CumulVolContext | undefined) =>
57
57
  * @param context Additional context with depths, OI data, and factors
58
58
  * @returns Cumulative volume price impact percentage (not including spread)
59
59
  */
60
- export declare const getTradeCumulVolPriceImpactP: (trader: string, pairIndex: number, long: boolean, tradeOpenInterestUsd: number, isPnlPositive: boolean, open: boolean, lastPosIncreaseBlock: number, context: CumulVolContext) => number;
60
+ export declare const getTradeCumulVolPriceImpactP: (_trader: string, _pairIndex: number, long: boolean, tradeOpenInterestUsd: number, isPnlPositive: boolean, open: boolean, lastPosIncreaseBlock: number, context: CumulVolContext) => number;
61
61
  /**
62
62
  * @dev Gets the fixed spread percentage with direction
63
63
  * @dev Mirrors contract's getFixedSpreadP function
@@ -90,7 +90,7 @@ export declare const getSpreadP: (pairSpreadP: number | undefined, isLiquidation
90
90
  * @param context Additional context for the calculation
91
91
  * @returns Total spread + cumulative volume price impact percentage
92
92
  */
93
- export declare const getSpreadWithCumulVolPriceImpactP: (pairSpreadP: number, buy: boolean, collateral: number, leverage: number, oiWindowsSettings?: OiWindowsSettings | undefined, oiWindows?: OiWindows | undefined, context?: CumulVolContext | undefined) => number;
93
+ export declare const getSpreadWithCumulVolPriceImpactP: (pairSpreadP: number, buy: boolean, collateral: number, leverage: number, context: CumulVolContext) => number;
94
94
  /**
95
95
  * @dev Convenience function for calculating cumulative volume price impact
96
96
  * @dev Uses collateral and leverage instead of USD position size
@@ -104,6 +104,6 @@ export declare const getSpreadWithCumulVolPriceImpactP: (pairSpreadP: number, bu
104
104
  export declare const getCumulVolPriceImpact: (buy: boolean, collateral: number, leverage: number, open: boolean, context: CumulVolContext & {
105
105
  collateralPriceUsd: number;
106
106
  }) => number;
107
- export declare const getSpreadWithPriceImpactP: (pairSpreadP: number, buy: boolean, collateral: number, leverage: number, oiWindowsSettings?: OiWindowsSettings | undefined, oiWindows?: OiWindows | undefined, context?: CumulVolContext | undefined) => number;
107
+ export declare const getSpreadWithPriceImpactP: (pairSpreadP: number, buy: boolean, collateral: number, leverage: number, context: CumulVolContext) => number;
108
108
  export { convertOiWindowsSettings, convertOiWindow, convertOiWindows, convertOiWindowsSettingsArray, } from "./converter";
109
109
  export { buildCumulVolContext } from "./builder";