@gainsnetwork/sdk 1.0.6-rc4 → 1.1.0

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 (92) hide show
  1. package/lib/backend/globalTrades/index.js +10 -10
  2. package/lib/backend/tradingVariables/converter.js +57 -57
  3. package/lib/backend/tradingVariables/index.js +7 -6
  4. package/lib/contracts/addresses.js +1 -4
  5. package/lib/contracts/index.d.ts +1 -1
  6. package/lib/contracts/index.js +3 -3
  7. package/lib/contracts/types/generated/GNSMultiCollatDiamond.d.ts +20 -7
  8. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.js +16 -7
  9. package/lib/contracts/types/generated/factories/GToken__factory.d.ts +0 -7
  10. package/lib/contracts/types/generated/factories/GToken__factory.js +0 -4
  11. package/lib/contracts/utils/borrowingFees.js +20 -9
  12. package/lib/contracts/utils/openTrades.js +20 -11
  13. package/lib/contracts/utils/pairs.js +21 -12
  14. package/lib/markets/forex.js +1 -1
  15. package/lib/markets/leverage/builder.js +2 -2
  16. package/lib/markets/price/index.d.ts +0 -1
  17. package/lib/markets/price/index.js +0 -1
  18. package/lib/markets/price/types.d.ts +0 -27
  19. package/lib/trade/fees/borrowing/builder.js +3 -2
  20. package/lib/trade/fees/borrowing/converter.js +1 -5
  21. package/lib/trade/fees/borrowing/index.js +5 -5
  22. package/lib/trade/fees/borrowingV2/builder.js +4 -3
  23. package/lib/trade/fees/borrowingV2/converter.js +1 -1
  24. package/lib/trade/fees/borrowingV2/fetcher.js +32 -26
  25. package/lib/trade/fees/borrowingV2/index.js +3 -3
  26. package/lib/trade/fees/converter.js +22 -22
  27. package/lib/trade/fees/fundingFees/builder.js +7 -6
  28. package/lib/trade/fees/fundingFees/converter.js +1 -1
  29. package/lib/trade/fees/fundingFees/fetcher.js +25 -16
  30. package/lib/trade/fees/fundingFees/index.js +3 -2
  31. package/lib/trade/fees/tiers/index.js +2 -1
  32. package/lib/trade/fees/trading/builder.d.ts +2 -1
  33. package/lib/trade/fees/trading/builder.js +2 -1
  34. package/lib/trade/fees/trading/index.js +3 -5
  35. package/lib/trade/fees/trading/types.d.ts +1 -3
  36. package/lib/trade/liquidation/builder.js +3 -6
  37. package/lib/trade/liquidation/index.js +6 -4
  38. package/lib/trade/liquidation/types.d.ts +2 -7
  39. package/lib/trade/oiWindows.js +2 -1
  40. package/lib/trade/pnl/builder.js +2 -1
  41. package/lib/trade/pnl/converter.js +1 -1
  42. package/lib/trade/pnl/index.js +9 -4
  43. package/lib/trade/priceImpact/close/builder.js +2 -1
  44. package/lib/trade/priceImpact/close/index.js +1 -4
  45. package/lib/trade/priceImpact/cumulVol/builder.js +10 -18
  46. package/lib/trade/priceImpact/cumulVol/index.js +16 -21
  47. package/lib/trade/priceImpact/open/builder.js +2 -1
  48. package/lib/trade/priceImpact/open/index.js +1 -4
  49. package/lib/trade/priceImpact/skew/builder.js +3 -2
  50. package/lib/trade/priceImpact/skew/converter.js +1 -1
  51. package/lib/trade/priceImpact/skew/fetcher.js +33 -24
  52. package/package.json +2 -2
  53. package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.d.ts +0 -979
  54. package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.js +0 -2
  55. package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.d.ts +0 -1058
  56. package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.js +0 -2
  57. package/lib/contracts/types/generated/GNSPairInfosV6_1.d.ts +0 -911
  58. package/lib/contracts/types/generated/GNSPairInfosV6_1.js +0 -2
  59. package/lib/contracts/types/generated/GNSPairsStorageV6.d.ts +0 -660
  60. package/lib/contracts/types/generated/GNSPairsStorageV6.js +0 -2
  61. package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.d.ts +0 -806
  62. package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.js +0 -2
  63. package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.d.ts +0 -821
  64. package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.js +0 -2
  65. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.d.ts +0 -88
  66. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.js +0 -1654
  67. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.d.ts +0 -113
  68. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.js +0 -1742
  69. package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.d.ts +0 -98
  70. package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.js +0 -1485
  71. package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.d.ts +0 -117
  72. package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.js +0 -1265
  73. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.d.ts +0 -82
  74. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.js +0 -1273
  75. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.d.ts +0 -82
  76. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.js +0 -1326
  77. package/lib/markets/oi/fetcher.d.ts +0 -58
  78. package/lib/markets/oi/fetcher.js +0 -181
  79. package/lib/markets/oi/validation.d.ts +0 -80
  80. package/lib/markets/oi/validation.js +0 -172
  81. package/lib/markets/price/signedPrices.d.ts +0 -36
  82. package/lib/markets/price/signedPrices.js +0 -181
  83. package/lib/trade/effectiveLeverage/builder.d.ts +0 -23
  84. package/lib/trade/effectiveLeverage/builder.js +0 -30
  85. package/lib/trade/fees/holdingFees/index.d.ts +0 -46
  86. package/lib/trade/fees/holdingFees/index.js +0 -105
  87. package/lib/trade/fees/holdingFees/types.d.ts +0 -23
  88. package/lib/trade/fees/holdingFees/types.js +0 -5
  89. package/lib/trade/fees/trading/holdingFees.d.ts +0 -28
  90. package/lib/trade/fees/trading/holdingFees.js +0 -66
  91. package/lib/trade/fees/trading/holdingFeesStructured.d.ts +0 -28
  92. package/lib/trade/fees/trading/holdingFeesStructured.js +0 -66
@@ -1,5 +1,5 @@
1
1
  import { GetBorrowingFeeContext, BorrowingFee } from "./../fees";
2
- import { LiquidationParams, UserPriceImpact, TradeFeesData, TradeInfo, CounterTradeSettings } from "./../types";
2
+ import { LiquidationParams, UserPriceImpact, TradeFeesData, TradeInfo } from "./../types";
3
3
  import { ContractsVersion } from "../../contracts/types";
4
4
  import { GetPairBorrowingFeeV2Context } from "../fees/borrowingV2";
5
5
  import { GetPairFundingFeeContext } from "../fees/fundingFees";
@@ -19,12 +19,7 @@ export type GetLiquidationPriceContext = {
19
19
  borrowingV1?: GetBorrowingFeeContext;
20
20
  borrowingV2?: GetPairBorrowingFeeV2Context;
21
21
  funding?: GetPairFundingFeeContext;
22
- trading: TradingFeesSubContext & {
23
- userPriceImpact?: UserPriceImpact;
24
- counterTradeSettings?: {
25
- [pairIndex: number]: CounterTradeSettings;
26
- };
27
- };
22
+ trading: TradingFeesSubContext;
28
23
  tradeData: {
29
24
  tradeInfo: TradeInfo;
30
25
  tradeFeesData: TradeFeesData;
@@ -7,12 +7,13 @@ const getCurrentOiWindowId = (oiWindowSettings) => {
7
7
  };
8
8
  exports.getCurrentOiWindowId = getCurrentOiWindowId;
9
9
  const getActiveOi = (currentOiWindowId, windowsCount, oiWindows, buy) => {
10
+ var _a, _b;
10
11
  if (oiWindows === undefined || windowsCount === 0)
11
12
  return 0;
12
13
  let activeOi = 0;
13
14
  for (let id = currentOiWindowId - (windowsCount - 1); id <= currentOiWindowId; id++) {
14
15
  activeOi +=
15
- (buy ? oiWindows?.[id]?.oiLongUsd : oiWindows?.[id]?.oiShortUsd) || 0;
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;
16
17
  }
17
18
  return activeOi;
18
19
  };
@@ -14,6 +14,7 @@ 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;
17
18
  const { trade, tradeInfo } = tradeContainer;
18
19
  const collateralIndex = trade.collateralIndex || 1;
19
20
  const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
@@ -22,7 +23,7 @@ const buildComprehensivePnlContext = (globalTradingVariables, tradeContainer, ad
22
23
  core: {
23
24
  currentBlock: additionalParams.currentBlock,
24
25
  currentTimestamp: additionalParams.currentTimestamp,
25
- collateralPriceUsd: collateral.prices?.collateralPriceUsd || 1,
26
+ collateralPriceUsd: ((_a = collateral.prices) === null || _a === void 0 ? void 0 : _a.collateralPriceUsd) || 1,
26
27
  contractsVersion: tradeInfo.contractsVersion,
27
28
  },
28
29
  // 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 / 10 ** collateralDecimals;
37
+ return value / Math.pow(10, collateralDecimals);
38
38
  };
39
39
  exports.convertCollateralAmount = convertCollateralAmount;
40
40
  /**
@@ -81,6 +81,7 @@ exports.getTradeValue = getTradeValue;
81
81
  * @returns Detailed PnL breakdown
82
82
  */
83
83
  const getComprehensivePnl = (trade, marketPrice, executionPrice, tradeInfo, context) => {
84
+ var _a;
84
85
  // Calculate both raw PnL (market price) and impact-adjusted PnL (execution price)
85
86
  let rawPnlPercent = (0, exports.getPnlPercent)(trade.openPrice, marketPrice, trade.long, trade.leverage);
86
87
  let impactPnlPercent = (0, exports.getPnlPercent)(trade.openPrice, executionPrice, trade.long, trade.leverage);
@@ -107,13 +108,14 @@ const getComprehensivePnl = (trade, marketPrice, executionPrice, tradeInfo, cont
107
108
  fee: context.trading.fee,
108
109
  globalTradeFeeParams: context.trading.globalTradeFeeParams,
109
110
  collateralPriceUsd: context.core.collateralPriceUsd,
111
+ counterTradeSettings: context.trading.counterTradeSettings,
110
112
  traderFeeMultiplier: context.trading.traderFeeMultiplier,
111
113
  });
112
114
  // Total fees
113
115
  const totalHoldingFees = borrowingFeeV1 + borrowingFeeV2 + fundingFee;
114
116
  const totalFees = totalHoldingFees + closingFee;
115
117
  // Check liquidation (using raw PnL for liquidation check)
116
- const liquidationThreshold = context.tradeData?.liquidationParams
118
+ const liquidationThreshold = ((_a = context.tradeData) === null || _a === void 0 ? void 0 : _a.liquidationParams)
117
119
  ? (0, liquidation_1.getLiqPnlThresholdP)(context.tradeData.liquidationParams, trade.leverage) *
118
120
  -100
119
121
  : -90; // Default 90% loss
@@ -190,6 +192,7 @@ exports.getComprehensivePnl = getComprehensivePnl;
190
192
  * @returns [pnlCollateral, pnlPercentage] or undefined if no price
191
193
  */
192
194
  const getPnl = (price, trade, _tradeInfo, initialAccFees, liquidationParams, useFees, context) => {
195
+ var _a;
193
196
  if (!price) {
194
197
  return;
195
198
  }
@@ -221,7 +224,7 @@ const getPnl = (price, trade, _tradeInfo, initialAccFees, liquidationParams, use
221
224
  // Calculate closing fee using the same function as opening fees
222
225
  const positionSizeCollateral = posCollat * trade.leverage;
223
226
  const closingFee = (0, trading_1.getTotalTradeFeesCollateral)(0, // collateralIndex not used
224
- trade.user, trade.pairIndex, positionSizeCollateral, trade.isCounterTrade ?? false, {
227
+ trade.user, trade.pairIndex, positionSizeCollateral, (_a = trade.isCounterTrade) !== null && _a !== void 0 ? _a : false, {
225
228
  fee: context.fee,
226
229
  globalTradeFeeParams: context.globalTradeFeeParams,
227
230
  collateralPriceUsd: context.collateralPriceUsd || 1,
@@ -245,11 +248,12 @@ exports.getPnl = getPnl;
245
248
  * @returns The price that would result in the target PnL percentage
246
249
  */
247
250
  const getPriceForTargetPnlPercentage = (targetPnlPercent, trade, tradeInfo, context, netPnl = false) => {
251
+ var _a, _b;
248
252
  const { leverage, openPrice, long, collateralAmount } = trade;
249
253
  const positionSizeCollateral = collateralAmount * leverage;
250
254
  // Calculate holding fees - always use getTradePendingHoldingFeesCollateral
251
255
  // This mirrors the contract's getTradeValueCollateral which always calls this function
252
- const fees = (0, trading_1.getTradePendingHoldingFeesCollateral)(trade, tradeInfo, context.tradeData?.tradeFeesData || {
256
+ const fees = (0, trading_1.getTradePendingHoldingFeesCollateral)(trade, tradeInfo, ((_a = context.tradeData) === null || _a === void 0 ? void 0 : _a.tradeFeesData) || {
253
257
  realizedTradingFeesCollateral: 0,
254
258
  realizedPnlCollateral: 0,
255
259
  manuallyRealizedNegativePnlCollateral: 0,
@@ -265,7 +269,7 @@ const getPriceForTargetPnlPercentage = (targetPnlPercent, trade, tradeInfo, cont
265
269
  borrowingV1: context.borrowingV1,
266
270
  borrowingV2: context.borrowingV2,
267
271
  funding: context.funding,
268
- initialAccFees: context.tradeData?.initialAccFees,
272
+ initialAccFees: (_b = context.tradeData) === null || _b === void 0 ? void 0 : _b.initialAccFees,
269
273
  });
270
274
  const totalHoldingFees = fees.fundingFeeCollateral +
271
275
  fees.borrowingFeeCollateral +
@@ -279,6 +283,7 @@ const getPriceForTargetPnlPercentage = (targetPnlPercent, trade, tradeInfo, cont
279
283
  globalTradeFeeParams: context.trading.globalTradeFeeParams,
280
284
  collateralPriceUsd: context.core.collateralPriceUsd,
281
285
  traderFeeMultiplier: context.trading.traderFeeMultiplier,
286
+ counterTradeSettings: context.trading.counterTradeSettings,
282
287
  });
283
288
  targetPnlGross += closingFee;
284
289
  }
@@ -14,6 +14,7 @@ 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;
17
18
  const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
18
19
  if (!collateral) {
19
20
  return undefined;
@@ -35,7 +36,7 @@ const buildTradeClosingPriceImpactContext = (globalTradingVariables, collateralI
35
36
  }
36
37
  // Return structured context with proper subcontexts
37
38
  return {
38
- collateralPriceUsd: collateral.prices?.collateralPriceUsd || 1,
39
+ collateralPriceUsd: ((_a = collateral.prices) === null || _a === void 0 ? void 0 : _a.collateralPriceUsd) || 1,
39
40
  cumulVolContext,
40
41
  skewContext,
41
42
  tradeInfo,
@@ -129,9 +129,6 @@ 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)({
133
- ...input,
134
- currentPairPrice: input.oraclePrice,
135
- }, context);
132
+ return (0, exports.getTradeClosingPriceImpact)(Object.assign(Object.assign({}, input), { currentPairPrice: input.oraclePrice }), context);
136
133
  };
137
134
  exports.getTradeClosingPriceImpactAtOracle = getTradeClosingPriceImpactAtOracle;
@@ -10,14 +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;
13
14
  const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
14
15
  if (!collateral) {
15
16
  return undefined;
16
17
  }
17
18
  // Get pair-specific data from global variables
18
- const pairDepth = globalTradingVariables.pairDepths?.[pairIndex];
19
- const pairFactor = globalTradingVariables.pairFactors?.[pairIndex];
20
- const oiWindows = globalTradingVariables.oiWindows?.[pairIndex];
19
+ const pairDepth = (_a = globalTradingVariables.pairDepths) === 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];
21
22
  // Get OI windows settings (same for all pairs)
22
23
  // OI windows settings from global trading variables are already in SDK format
23
24
  const oiWindowsSettings = globalTradingVariables.oiWindowsSettings;
@@ -25,27 +26,18 @@ const buildCumulVolContext = (globalTradingVariables, collateralIndex, pairIndex
25
26
  const userPriceImpact = additionalParams.userPriceImpact;
26
27
  const protectionCloseFactorWhitelist = additionalParams.protectionCloseFactorWhitelist;
27
28
  // Get liquidation params - check both pair and group level
28
- const liquidationParams = globalTradingVariables.liquidationParams?.pairs?.[pairIndex] ||
29
- globalTradingVariables.liquidationParams?.groups?.[0]; // fallback to first group
30
- return {
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({
31
32
  // Trade state
32
- isOpen: additionalParams.isOpen,
33
- isPnlPositive: additionalParams.isPnlPositive,
34
- createdBlock: additionalParams.createdBlock,
33
+ isOpen: additionalParams.isOpen, isPnlPositive: additionalParams.isPnlPositive, createdBlock: additionalParams.createdBlock,
35
34
  // Protection factors
36
- liquidationParams,
37
- currentBlock: additionalParams.currentBlock,
38
- contractsVersion: additionalParams.contractsVersion,
39
- protectionCloseFactorWhitelist,
35
+ liquidationParams, currentBlock: additionalParams.currentBlock, contractsVersion: additionalParams.contractsVersion, protectionCloseFactorWhitelist,
40
36
  // Price impact data
41
37
  pairDepth,
42
38
  oiWindowsSettings,
43
39
  oiWindows,
44
40
  // User/collateral specific
45
- userPriceImpact,
46
- collateralPriceUsd: collateral.prices?.collateralPriceUsd || 1,
47
- // Pair factors (spread across the context)
48
- ...pairFactor,
49
- };
41
+ userPriceImpact, collateralPriceUsd: ((_h = collateral.prices) === null || _h === void 0 ? void 0 : _h.collateralPriceUsd) || 1 }, pairFactor);
50
42
  };
51
43
  exports.buildCumulVolContext = buildCumulVolContext;
@@ -14,6 +14,7 @@ const types_1 = require("../../../contracts/types");
14
14
  * @returns Protection close factor (1 = 100%)
15
15
  */
16
16
  const getProtectionCloseFactor = (context) => {
17
+ var _a;
17
18
  const protectionCloseFactor = context === undefined ||
18
19
  context.contractsVersion === types_1.ContractsVersion.BEFORE_V9_2 ||
19
20
  context.isOpen === undefined ||
@@ -22,7 +23,7 @@ const getProtectionCloseFactor = (context) => {
22
23
  (0, exports.isProtectionCloseFactorActive)(context) !== true
23
24
  ? constants_1.DEFAULT_PROTECTION_CLOSE_FACTOR
24
25
  : context.protectionCloseFactor;
25
- const protectionCloseFactorMultiplier = context?.userPriceImpact?.cumulVolPriceImpactMultiplier !== undefined &&
26
+ const protectionCloseFactorMultiplier = ((_a = context === null || context === void 0 ? void 0 : context.userPriceImpact) === null || _a === void 0 ? void 0 : _a.cumulVolPriceImpactMultiplier) !== undefined &&
26
27
  context.userPriceImpact.cumulVolPriceImpactMultiplier > 0
27
28
  ? context.userPriceImpact.cumulVolPriceImpactMultiplier
28
29
  : 1;
@@ -70,7 +71,7 @@ exports.getCumulativeFactor = getCumulativeFactor;
70
71
  * @returns 1 for pre-v9.2, 2 for v9.2+
71
72
  */
72
73
  const getLegacyFactor = (context) => {
73
- return context?.contractsVersion === types_1.ContractsVersion.BEFORE_V9_2 ? 1 : 2;
74
+ return (context === null || context === void 0 ? void 0 : context.contractsVersion) === types_1.ContractsVersion.BEFORE_V9_2 ? 1 : 2;
74
75
  };
75
76
  exports.getLegacyFactor = getLegacyFactor;
76
77
  /**
@@ -87,22 +88,18 @@ exports.getLegacyFactor = getLegacyFactor;
87
88
  * @returns Cumulative volume price impact percentage (not including spread)
88
89
  */
89
90
  const getTradeCumulVolPriceImpactP = (trader, pairIndex, long, tradeOpenInterestUsd, isPnlPositive, open, lastPosIncreaseBlock, context) => {
91
+ var _a, _b;
90
92
  // Update context with passed parameters
91
- const updatedContext = {
92
- ...context,
93
- isOpen: open,
94
- isPnlPositive: isPnlPositive,
95
- createdBlock: context.createdBlock || lastPosIncreaseBlock,
96
- };
93
+ const updatedContext = Object.assign(Object.assign({}, context), { isOpen: open, isPnlPositive: isPnlPositive, createdBlock: context.createdBlock || lastPosIncreaseBlock });
97
94
  if (
98
95
  // No price impact when closing pre-v9.2 trades
99
- (!open && context?.contractsVersion === types_1.ContractsVersion.BEFORE_V9_2) ||
96
+ (!open && (context === null || context === void 0 ? void 0 : context.contractsVersion) === types_1.ContractsVersion.BEFORE_V9_2) ||
100
97
  // No price impact for opens when `pair.exemptOnOpen` is true
101
- (open && context?.exemptOnOpen === true) ||
98
+ (open && (context === null || context === void 0 ? void 0 : context.exemptOnOpen) === true) ||
102
99
  // No price impact for closes after `protectionCloseFactor` has expired
103
100
  // when `pair.exemptAfterProtectionCloseFactor` is true
104
101
  (!open &&
105
- context?.exemptAfterProtectionCloseFactor === true &&
102
+ (context === null || context === void 0 ? void 0 : context.exemptAfterProtectionCloseFactor) === true &&
106
103
  (0, exports.isProtectionCloseFactorActive)(updatedContext) !== true)) {
107
104
  return 0;
108
105
  }
@@ -113,8 +110,8 @@ const getTradeCumulVolPriceImpactP = (trader, pairIndex, long, tradeOpenInterest
113
110
  // For positive skew (long open or short close), use depth above
114
111
  // For negative skew (short open or long close), use depth below
115
112
  const onePercentDepth = tradePositiveSkew
116
- ? context.pairDepth?.onePercentDepthAboveUsd
117
- : context.pairDepth?.onePercentDepthBelowUsd;
113
+ ? (_a = context.pairDepth) === null || _a === void 0 ? void 0 : _a.onePercentDepthAboveUsd
114
+ : (_b = context.pairDepth) === null || _b === void 0 ? void 0 : _b.onePercentDepthBelowUsd;
118
115
  let activeOi = undefined;
119
116
  if (context.oiWindowsSettings !== undefined) {
120
117
  activeOi = (0, oiWindows_1.getActiveOi)((0, oiWindows_1.getCurrentOiWindowId)(context.oiWindowsSettings), context.oiWindowsSettings.windowsCount, context.oiWindows, open ? long : !long);
@@ -162,7 +159,8 @@ exports.getFixedSpreadP = getFixedSpreadP;
162
159
  * Currently it may double-count user fixed spread if pairSpreadP already includes it
163
160
  */
164
161
  const getSpreadP = (pairSpreadP, isLiquidation, liquidationParams, userPriceImpact) => {
165
- const fixedSpreadP = userPriceImpact?.fixedSpreadP ?? 0;
162
+ var _a;
163
+ const fixedSpreadP = (_a = userPriceImpact === null || userPriceImpact === void 0 ? void 0 : userPriceImpact.fixedSpreadP) !== null && _a !== void 0 ? _a : 0;
166
164
  if (pairSpreadP === undefined || (pairSpreadP === 0 && fixedSpreadP === 0)) {
167
165
  return 0;
168
166
  }
@@ -192,17 +190,14 @@ const getSpreadWithCumulVolPriceImpactP = (pairSpreadP, buy, collateral, leverag
192
190
  if (pairSpreadP === undefined) {
193
191
  return 0;
194
192
  }
195
- const baseSpread = (0, exports.getSpreadP)(pairSpreadP, undefined, undefined, context?.userPriceImpact);
193
+ const baseSpread = (0, exports.getSpreadP)(pairSpreadP, undefined, undefined, context === null || context === void 0 ? void 0 : context.userPriceImpact);
196
194
  // Calculate position size in USD
197
- const positionSizeUsd = collateral * leverage * (context?.collateralPriceUsd || 1);
195
+ const positionSizeUsd = collateral * leverage * ((context === null || context === void 0 ? void 0 : context.collateralPriceUsd) || 1);
198
196
  const cumulVolImpact = (0, exports.getTradeCumulVolPriceImpactP)("", // trader - not used in calculation
199
197
  0, // pairIndex - not used in calculation
200
- buy, positionSizeUsd, context?.isPnlPositive || false, context?.isOpen !== false, context?.createdBlock || 0, {
201
- ...context,
202
- pairDepth,
198
+ buy, positionSizeUsd, (context === null || context === void 0 ? void 0 : context.isPnlPositive) || false, (context === null || context === void 0 ? void 0 : context.isOpen) !== false, (context === null || context === void 0 ? void 0 : context.createdBlock) || 0, Object.assign(Object.assign({}, context), { pairDepth,
203
199
  oiWindowsSettings,
204
- oiWindows,
205
- });
200
+ oiWindows }));
206
201
  // If no depth or OI data, return just half spread
207
202
  if (cumulVolImpact === 0 && (!pairDepth || !oiWindowsSettings)) {
208
203
  return pairSpreadP / 2;
@@ -13,6 +13,7 @@ const builder_2 = require("../skew/builder");
13
13
  * @returns Complete context ready for getTradeOpeningPriceImpact
14
14
  */
15
15
  const buildTradeOpeningPriceImpactContext = (globalTradingVariables, collateralIndex, pairIndex, additionalParams) => {
16
+ var _a;
16
17
  const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
17
18
  if (!collateral) {
18
19
  return undefined;
@@ -34,7 +35,7 @@ const buildTradeOpeningPriceImpactContext = (globalTradingVariables, collateralI
34
35
  }
35
36
  // Return structured context with proper subcontexts
36
37
  return {
37
- collateralPriceUsd: collateral.prices?.collateralPriceUsd || 1,
38
+ collateralPriceUsd: ((_a = collateral.prices) === null || _a === void 0 ? void 0 : _a.collateralPriceUsd) || 1,
38
39
  cumulVolContext,
39
40
  skewContext,
40
41
  };
@@ -74,9 +74,6 @@ exports.getTradeOpeningPriceImpact = getTradeOpeningPriceImpact;
74
74
  * @returns Price impact breakdown and final price
75
75
  */
76
76
  const getTradeOpeningPriceImpactAtMarket = (input, context, currentMarketPrice) => {
77
- return (0, exports.getTradeOpeningPriceImpact)({
78
- ...input,
79
- openPrice: currentMarketPrice,
80
- }, context);
77
+ return (0, exports.getTradeOpeningPriceImpact)(Object.assign(Object.assign({}, input), { openPrice: currentMarketPrice }), context);
81
78
  };
82
79
  exports.getTradeOpeningPriceImpactAtMarket = getTradeOpeningPriceImpactAtMarket;
@@ -11,8 +11,9 @@ exports.buildSkewPriceImpactContext = void 0;
11
11
  * @returns Skew price impact context for the pair
12
12
  */
13
13
  const buildSkewPriceImpactContext = (tradingVariables, pairIndex) => {
14
- const skewDepth = tradingVariables.pairSkewDepths?.[pairIndex] ?? 0;
15
- const pairOi = tradingVariables.pairOis?.[pairIndex];
14
+ var _a, _b, _c;
15
+ const skewDepth = (_b = (_a = tradingVariables.pairSkewDepths) === null || _a === void 0 ? void 0 : _a[pairIndex]) !== null && _b !== void 0 ? _b : 0;
16
+ const pairOi = (_c = tradingVariables.pairOis) === null || _c === void 0 ? void 0 : _c[pairIndex];
16
17
  if (!pairOi) {
17
18
  throw new Error(`Pair OI data not found for pair index ${pairIndex}`);
18
19
  }
@@ -34,7 +34,7 @@ exports.convertPairOiTokenArray = convertPairOiTokenArray;
34
34
  * @returns Normalized pair OI collateral data
35
35
  */
36
36
  const convertPairOiCollateral = (contractData, collateralDecimals) => {
37
- const divisor = 10 ** collateralDecimals;
37
+ const divisor = Math.pow(10, collateralDecimals);
38
38
  return {
39
39
  oiLongCollateral: Number(contractData.oiLongCollateral) / divisor,
40
40
  oiShortCollateral: Number(contractData.oiShortCollateral) / divisor,
@@ -1,4 +1,13 @@
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
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
12
  exports.calculateTradeSkewPriceImpact = exports.fetchCollateralDecimals = exports.fetchSkewPriceImpactContext = exports.fetchPairSkewDepths = exports.fetchPairSkewDepth = exports.fetchPairOisAfterV10Token = exports.fetchPairOiAfterV10Token = void 0;
4
13
  const converter_1 = require("./converter");
@@ -9,16 +18,16 @@ const converter_1 = require("./converter");
9
18
  * @param pairIndex Pair index
10
19
  * @returns Promise resolving to pair OI in tokens
11
20
  */
12
- const fetchPairOiAfterV10Token = async (contract, collateralIndex, pairIndex) => {
21
+ const fetchPairOiAfterV10Token = (contract, collateralIndex, pairIndex) => __awaiter(void 0, void 0, void 0, function* () {
13
22
  try {
14
- const contractData = await contract.getPairOiAfterV10Token(collateralIndex, pairIndex);
23
+ const contractData = yield contract.getPairOiAfterV10Token(collateralIndex, pairIndex);
15
24
  return (0, converter_1.convertPairOiToken)(contractData);
16
25
  }
17
26
  catch (error) {
18
27
  console.error("Error fetching pair OI token:", error);
19
28
  throw error;
20
29
  }
21
- };
30
+ });
22
31
  exports.fetchPairOiAfterV10Token = fetchPairOiAfterV10Token;
23
32
  /**
24
33
  * @dev Fetches pair open interest in tokens for multiple pairs
@@ -27,19 +36,19 @@ exports.fetchPairOiAfterV10Token = fetchPairOiAfterV10Token;
27
36
  * @param pairIndices Array of pair indices
28
37
  * @returns Promise resolving to array of pair OI in tokens
29
38
  */
30
- const fetchPairOisAfterV10Token = async (contract, collateralIndices, pairIndices) => {
39
+ const fetchPairOisAfterV10Token = (contract, collateralIndices, pairIndices) => __awaiter(void 0, void 0, void 0, function* () {
31
40
  if (collateralIndices.length !== pairIndices.length) {
32
41
  throw new Error("Collateral indices and pair indices arrays must have the same length");
33
42
  }
34
43
  try {
35
- const contractDataArray = await contract.getPairOisAfterV10Token(collateralIndices, pairIndices);
44
+ const contractDataArray = yield contract.getPairOisAfterV10Token(collateralIndices, pairIndices);
36
45
  return contractDataArray.map(converter_1.convertPairOiToken);
37
46
  }
38
47
  catch (error) {
39
48
  console.error("Error fetching pair OIs token:", error);
40
49
  throw error;
41
50
  }
42
- };
51
+ });
43
52
  exports.fetchPairOisAfterV10Token = fetchPairOisAfterV10Token;
44
53
  /**
45
54
  * @dev Fetches skew depth for a specific pair
@@ -48,9 +57,9 @@ exports.fetchPairOisAfterV10Token = fetchPairOisAfterV10Token;
48
57
  * @param pairIndex Pair index
49
58
  * @returns Promise resolving to normalized skew depth
50
59
  */
51
- const fetchPairSkewDepth = async (contract, collateralIndex, pairIndex) => {
60
+ const fetchPairSkewDepth = (contract, collateralIndex, pairIndex) => __awaiter(void 0, void 0, void 0, function* () {
52
61
  try {
53
- const contractDepth = await contract.getPairSkewDepth(collateralIndex, pairIndex);
62
+ const contractDepth = yield contract.getPairSkewDepth(collateralIndex, pairIndex);
54
63
  // Token depths are always 1e18 precision
55
64
  return (0, converter_1.convertSkewDepth)(contractDepth.toString());
56
65
  }
@@ -58,7 +67,7 @@ const fetchPairSkewDepth = async (contract, collateralIndex, pairIndex) => {
58
67
  console.error("Error fetching skew depth:", error);
59
68
  throw error;
60
69
  }
61
- };
70
+ });
62
71
  exports.fetchPairSkewDepth = fetchPairSkewDepth;
63
72
  /**
64
73
  * @dev Fetches skew depths for multiple pairs
@@ -67,12 +76,12 @@ exports.fetchPairSkewDepth = fetchPairSkewDepth;
67
76
  * @param pairIndices Array of pair indices
68
77
  * @returns Promise resolving to array of normalized skew depths
69
78
  */
70
- const fetchPairSkewDepths = async (contract, collateralIndices, pairIndices) => {
79
+ const fetchPairSkewDepths = (contract, collateralIndices, pairIndices) => __awaiter(void 0, void 0, void 0, function* () {
71
80
  if (collateralIndices.length !== pairIndices.length) {
72
81
  throw new Error("All input arrays must have the same length");
73
82
  }
74
83
  try {
75
- const contractDepths = await contract.getPairSkewDepths(collateralIndices, pairIndices);
84
+ const contractDepths = yield contract.getPairSkewDepths(collateralIndices, pairIndices);
76
85
  // Token depths are always 1e18 precision
77
86
  return contractDepths.map(depth => (0, converter_1.convertSkewDepth)(depth.toString()));
78
87
  }
@@ -80,7 +89,7 @@ const fetchPairSkewDepths = async (contract, collateralIndices, pairIndices) =>
80
89
  console.error("Error fetching skew depths:", error);
81
90
  throw error;
82
91
  }
83
- };
92
+ });
84
93
  exports.fetchPairSkewDepths = fetchPairSkewDepths;
85
94
  /**
86
95
  * @dev Fetches skew price impact context for a single pair
@@ -89,10 +98,10 @@ exports.fetchPairSkewDepths = fetchPairSkewDepths;
89
98
  * @param pairIndex Pair index
90
99
  * @returns Promise resolving to skew price impact context
91
100
  */
92
- const fetchSkewPriceImpactContext = async (contract, collateralIndex, pairIndex) => {
101
+ const fetchSkewPriceImpactContext = (contract, collateralIndex, pairIndex) => __awaiter(void 0, void 0, void 0, function* () {
93
102
  try {
94
103
  // Fetch OI data and skew depth in parallel
95
- const [pairOiToken, skewDepth] = await Promise.all([
104
+ const [pairOiToken, skewDepth] = yield Promise.all([
96
105
  (0, exports.fetchPairOiAfterV10Token)(contract, collateralIndex, pairIndex),
97
106
  (0, exports.fetchPairSkewDepth)(contract, collateralIndex, pairIndex),
98
107
  ]);
@@ -105,7 +114,7 @@ const fetchSkewPriceImpactContext = async (contract, collateralIndex, pairIndex)
105
114
  console.error("Error fetching skew price impact context:", error);
106
115
  throw error;
107
116
  }
108
- };
117
+ });
109
118
  exports.fetchSkewPriceImpactContext = fetchSkewPriceImpactContext;
110
119
  /**
111
120
  * @dev Fetches collateral decimals for given collateral indices
@@ -113,16 +122,16 @@ exports.fetchSkewPriceImpactContext = fetchSkewPriceImpactContext;
113
122
  * @param collateralIndices Array of collateral indices
114
123
  * @returns Promise resolving to array of decimals
115
124
  */
116
- const fetchCollateralDecimals = async (contract, collateralIndices) => {
125
+ const fetchCollateralDecimals = (contract, collateralIndices) => __awaiter(void 0, void 0, void 0, function* () {
117
126
  try {
118
127
  // Get unique collateral indices to minimize calls
119
128
  const uniqueIndices = [...new Set(collateralIndices)];
120
129
  // Fetch collateral info for unique indices
121
- const promises = uniqueIndices.map(async (index) => {
122
- const collateral = await contract.getCollateral(index);
130
+ const promises = uniqueIndices.map((index) => __awaiter(void 0, void 0, void 0, function* () {
131
+ const collateral = yield contract.getCollateral(index);
123
132
  return { index, decimals: Number(collateral.precision) };
124
- });
125
- const collateralData = await Promise.all(promises);
133
+ }));
134
+ const collateralData = yield Promise.all(promises);
126
135
  // Create a map for quick lookup
127
136
  const decimalsMap = new Map(collateralData.map(data => [data.index, data.decimals]));
128
137
  // Return decimals in the same order as input
@@ -133,7 +142,7 @@ const fetchCollateralDecimals = async (contract, collateralIndices) => {
133
142
  console.error("Error fetching collateral decimals:", error);
134
143
  throw error;
135
144
  }
136
- };
145
+ });
137
146
  exports.fetchCollateralDecimals = fetchCollateralDecimals;
138
147
  /**
139
148
  * @dev Calculates skew price impact for a trade using contract call
@@ -145,9 +154,9 @@ exports.fetchCollateralDecimals = fetchCollateralDecimals;
145
154
  * @param open Whether trade is opening
146
155
  * @returns Promise resolving to price impact percentage (1e10)
147
156
  */
148
- const calculateTradeSkewPriceImpact = async (contract, collateralIndex, pairIndex, long, positionSizeToken, open) => {
157
+ const calculateTradeSkewPriceImpact = (contract, collateralIndex, pairIndex, long, positionSizeToken, open) => __awaiter(void 0, void 0, void 0, function* () {
149
158
  try {
150
- const priceImpactP = await contract.getTradeSkewPriceImpactP(collateralIndex, pairIndex, long, BigInt(Math.round(positionSizeToken * 1e18)), // Convert to 1e18 precision
159
+ const priceImpactP = yield contract.getTradeSkewPriceImpactP(collateralIndex, pairIndex, long, BigInt(Math.round(positionSizeToken * 1e18)), // Convert to 1e18 precision
151
160
  open);
152
161
  // Convert from int256 1e10 to percentage
153
162
  return Number(priceImpactP) / 1e10;
@@ -156,5 +165,5 @@ const calculateTradeSkewPriceImpact = async (contract, collateralIndex, pairInde
156
165
  console.error("Error calculating trade skew price impact:", error);
157
166
  throw error;
158
167
  }
159
- };
168
+ });
160
169
  exports.calculateTradeSkewPriceImpact = calculateTradeSkewPriceImpact;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gainsnetwork/sdk",
3
- "version": "1.0.6-rc4",
3
+ "version": "1.1.0",
4
4
  "description": "Gains Network SDK",
5
5
  "main": "./lib/index.js",
6
6
  "files": [
@@ -24,7 +24,7 @@
24
24
  "url": "git+git@github.com:GainsNetwork-org/sdk.git"
25
25
  },
26
26
  "engines": {
27
- "node": ">=14.0"
27
+ "node": ">=12.0"
28
28
  },
29
29
  "devDependencies": {
30
30
  "@typechain/ethers-v5": "^10.1.1",