@gainsnetwork/sdk 1.3.0-rc7 → 1.4.0-rc1

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 (153) hide show
  1. package/lib/backend/globalTrades/index.js +10 -10
  2. package/lib/backend/tradingVariables/backend.types.d.ts +4 -11
  3. package/lib/backend/tradingVariables/converter.d.ts +3 -7
  4. package/lib/backend/tradingVariables/converter.js +63 -71
  5. package/lib/backend/tradingVariables/index.js +8 -10
  6. package/lib/backend/tradingVariables/types.d.ts +2 -4
  7. package/lib/constants.js +1 -1
  8. package/lib/contracts/addresses.d.ts +1 -1
  9. package/lib/contracts/addresses.js +4 -8
  10. package/lib/contracts/addresses.json +0 -29
  11. package/lib/contracts/index.d.ts +1 -1
  12. package/lib/contracts/index.js +3 -3
  13. package/lib/contracts/types/generated/GNSMultiCollatDiamond.d.ts +299 -608
  14. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.d.ts +10 -2
  15. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.js +317 -1995
  16. package/lib/contracts/utils/borrowingFees.js +20 -9
  17. package/lib/contracts/utils/openTrades.js +20 -11
  18. package/lib/contracts/utils/pairs.d.ts +2 -13
  19. package/lib/contracts/utils/pairs.js +30 -80
  20. package/lib/index.d.ts +0 -1
  21. package/lib/index.js +0 -1
  22. package/lib/markets/forex.js +1 -1
  23. package/lib/markets/leverage/builder.js +2 -2
  24. package/lib/markets/price/index.d.ts +0 -1
  25. package/lib/markets/price/index.js +0 -1
  26. package/lib/markets/price/types.d.ts +0 -27
  27. package/lib/trade/fees/borrowing/builder.js +3 -2
  28. package/lib/trade/fees/borrowing/converter.js +1 -5
  29. package/lib/trade/fees/borrowing/index.js +5 -5
  30. package/lib/trade/fees/borrowingV2/builder.js +4 -3
  31. package/lib/trade/fees/borrowingV2/converter.js +1 -1
  32. package/lib/trade/fees/borrowingV2/fetcher.js +32 -26
  33. package/lib/trade/fees/borrowingV2/index.js +3 -3
  34. package/lib/trade/fees/converter.js +22 -22
  35. package/lib/trade/fees/fundingFees/builder.js +7 -6
  36. package/lib/trade/fees/fundingFees/converter.js +1 -1
  37. package/lib/trade/fees/fundingFees/fetcher.js +25 -16
  38. package/lib/trade/fees/fundingFees/index.js +3 -2
  39. package/lib/trade/fees/tiers/index.js +2 -1
  40. package/lib/trade/fees/trading/index.js +3 -5
  41. package/lib/trade/liquidation/builder.js +2 -1
  42. package/lib/trade/liquidation/index.js +6 -4
  43. package/lib/trade/liquidation.d.ts +12 -0
  44. package/lib/trade/liquidation.js +55 -0
  45. package/lib/trade/oiWindows.js +2 -1
  46. package/lib/trade/pnl/builder.js +2 -1
  47. package/lib/trade/pnl/converter.js +1 -1
  48. package/lib/trade/pnl/index.js +7 -4
  49. package/lib/trade/pnl.d.ts +10 -0
  50. package/lib/trade/pnl.js +33 -0
  51. package/lib/trade/priceImpact/close/builder.js +2 -1
  52. package/lib/trade/priceImpact/close/index.js +1 -4
  53. package/lib/trade/priceImpact/cumulVol/builder.js +11 -21
  54. package/lib/trade/priceImpact/cumulVol/converter.d.ts +0 -63
  55. package/lib/trade/priceImpact/cumulVol/converter.js +1 -97
  56. package/lib/trade/priceImpact/cumulVol/index.d.ts +6 -7
  57. package/lib/trade/priceImpact/cumulVol/index.js +41 -149
  58. package/lib/trade/priceImpact/open/builder.js +2 -1
  59. package/lib/trade/priceImpact/open/index.js +1 -7
  60. package/lib/trade/priceImpact/skew/builder.js +3 -2
  61. package/lib/trade/priceImpact/skew/converter.js +1 -1
  62. package/lib/trade/priceImpact/skew/fetcher.js +33 -24
  63. package/package.json +2 -2
  64. package/lib/contracts/types/generated/GFarmTradingStorageV5.d.ts +0 -1911
  65. package/lib/contracts/types/generated/GFarmTradingStorageV5.js +0 -2
  66. package/lib/contracts/types/generated/GNSBorrowingFees.d.ts +0 -1067
  67. package/lib/contracts/types/generated/GNSBorrowingFees.js +0 -2
  68. package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.d.ts +0 -979
  69. package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.js +0 -2
  70. package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.d.ts +0 -1058
  71. package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.js +0 -2
  72. package/lib/contracts/types/generated/GNSNftRewardsV6.d.ts +0 -533
  73. package/lib/contracts/types/generated/GNSNftRewardsV6.js +0 -2
  74. package/lib/contracts/types/generated/GNSNftRewardsV6_3_1.d.ts +0 -613
  75. package/lib/contracts/types/generated/GNSNftRewardsV6_3_1.js +0 -2
  76. package/lib/contracts/types/generated/GNSPairInfosV6_1.d.ts +0 -911
  77. package/lib/contracts/types/generated/GNSPairInfosV6_1.js +0 -2
  78. package/lib/contracts/types/generated/GNSPairsStorageV6.d.ts +0 -660
  79. package/lib/contracts/types/generated/GNSPairsStorageV6.js +0 -2
  80. package/lib/contracts/types/generated/GNSTrading.d.ts +0 -758
  81. package/lib/contracts/types/generated/GNSTrading.js +0 -2
  82. package/lib/contracts/types/generated/GNSTradingCallbacks.d.ts +0 -875
  83. package/lib/contracts/types/generated/GNSTradingCallbacks.js +0 -2
  84. package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.d.ts +0 -806
  85. package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.js +0 -2
  86. package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.d.ts +0 -821
  87. package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.js +0 -2
  88. package/lib/contracts/types/generated/GNSTradingStorage.d.ts +0 -1387
  89. package/lib/contracts/types/generated/GNSTradingStorage.js +0 -2
  90. package/lib/contracts/types/generated/GTokenV6_3_2.d.ts +0 -1838
  91. package/lib/contracts/types/generated/GTokenV6_3_2.js +0 -2
  92. package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.d.ts +0 -83
  93. package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.js +0 -2691
  94. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.d.ts +0 -88
  95. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.js +0 -1654
  96. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.d.ts +0 -113
  97. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.js +0 -1742
  98. package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.d.ts +0 -124
  99. package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.js +0 -1784
  100. package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.d.ts +0 -100
  101. package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.js +0 -1116
  102. package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.d.ts +0 -100
  103. package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.js +0 -1003
  104. package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.d.ts +0 -98
  105. package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.js +0 -1485
  106. package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.d.ts +0 -117
  107. package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.js +0 -1265
  108. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.d.ts +0 -82
  109. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.js +0 -1273
  110. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.d.ts +0 -82
  111. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.js +0 -1326
  112. package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.d.ts +0 -113
  113. package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.js +0 -1428
  114. package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.d.ts +0 -96
  115. package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.js +0 -2241
  116. package/lib/contracts/types/generated/factories/GNSTrading__factory.d.ts +0 -95
  117. package/lib/contracts/types/generated/factories/GNSTrading__factory.js +0 -1071
  118. package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.d.ts +0 -110
  119. package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.js +0 -2682
  120. package/lib/markets/oi/fetcher.d.ts +0 -58
  121. package/lib/markets/oi/fetcher.js +0 -181
  122. package/lib/markets/oi/validation.d.ts +0 -80
  123. package/lib/markets/oi/validation.js +0 -172
  124. package/lib/markets/price/signedPrices.d.ts +0 -36
  125. package/lib/markets/price/signedPrices.js +0 -181
  126. package/lib/pricing/depthBands/converter.d.ts +0 -65
  127. package/lib/pricing/depthBands/converter.js +0 -155
  128. package/lib/pricing/depthBands/decoder.d.ts +0 -32
  129. package/lib/pricing/depthBands/decoder.js +0 -109
  130. package/lib/pricing/depthBands/encoder.d.ts +0 -19
  131. package/lib/pricing/depthBands/encoder.js +0 -105
  132. package/lib/pricing/depthBands/index.d.ts +0 -8
  133. package/lib/pricing/depthBands/index.js +0 -26
  134. package/lib/pricing/depthBands/types.d.ts +0 -49
  135. package/lib/pricing/depthBands/types.js +0 -10
  136. package/lib/pricing/depthBands/validator.d.ts +0 -22
  137. package/lib/pricing/depthBands/validator.js +0 -113
  138. package/lib/pricing/depthBands.d.ts +0 -39
  139. package/lib/pricing/depthBands.js +0 -94
  140. package/lib/pricing/index.d.ts +0 -4
  141. package/lib/pricing/index.js +0 -20
  142. package/lib/trade/effectiveLeverage/builder.d.ts +0 -23
  143. package/lib/trade/effectiveLeverage/builder.js +0 -30
  144. package/lib/trade/fees/holdingFees/index.d.ts +0 -46
  145. package/lib/trade/fees/holdingFees/index.js +0 -105
  146. package/lib/trade/fees/holdingFees/types.d.ts +0 -23
  147. package/lib/trade/fees/holdingFees/types.js +0 -5
  148. package/lib/trade/fees/trading/holdingFees.d.ts +0 -28
  149. package/lib/trade/fees/trading/holdingFees.js +0 -66
  150. package/lib/trade/fees/trading/holdingFeesStructured.d.ts +0 -28
  151. package/lib/trade/fees/trading/holdingFeesStructured.js +0 -66
  152. package/lib/trade/priceImpact/cumulVol/types.d.ts +0 -11
  153. package/lib/trade/priceImpact/cumulVol/types.js +0 -2
@@ -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,111 +71,9 @@ 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
- * @dev Mirrors contract's _calculateDepthBandsPriceImpact function
78
- * @param tradeSizeUsd Trade size in USD (always positive here)
79
- * @param depthBandParams Depth band parameters
80
- * @returns Price impact percentage
81
- */
82
- const _calculateDepthBandsPriceImpact = (tradeSizeUsd, depthBandParams) => {
83
- console.log("tradeSizeUsd", tradeSizeUsd);
84
- console.log("depthBandParams", depthBandParams);
85
- const totalDepthUsd = depthBandParams.depthBands.totalDepthUsd;
86
- if (totalDepthUsd === 0 || tradeSizeUsd === 0)
87
- return 0;
88
- let remainingSizeUsd = tradeSizeUsd;
89
- let totalWeightedPriceImpactP = 0;
90
- let prevBandDepthUsd = 0;
91
- let topOfPrevBandOffsetPpm = 0;
92
- for (let i = 0; i < 30 && remainingSizeUsd !== 0; i++) {
93
- const bandLiquidityPercentageBps = depthBandParams.depthBands.bands[i]; // Already in 0-1 format
94
- const topOfBandOffsetPpm = depthBandParams.depthBandsMapping.bands[i]; // Already in 0-1 format
95
- const bandDepthUsd = bandLiquidityPercentageBps * totalDepthUsd;
96
- console.log("bandDepthUsd", bandDepthUsd);
97
- // Skip if band has same depth as previous (would cause division by zero)
98
- if (bandDepthUsd <= prevBandDepthUsd) {
99
- console.log("Skipping band");
100
- prevBandDepthUsd = bandDepthUsd;
101
- topOfPrevBandOffsetPpm = topOfBandOffsetPpm;
102
- continue;
103
- }
104
- // Since bandDepthUsd represents liquidity from mid price to top of band, we need to subtract previous band depth
105
- const bandAvailableDepthUsd = bandDepthUsd - prevBandDepthUsd;
106
- console.log("bandAvailableDepthUsd", bandAvailableDepthUsd);
107
- let depthConsumedUsd;
108
- // At 100% band always consume all remaining size, even if more than band available depth
109
- if (bandLiquidityPercentageBps === 1 ||
110
- remainingSizeUsd <= bandAvailableDepthUsd) {
111
- depthConsumedUsd = remainingSizeUsd;
112
- remainingSizeUsd = 0;
113
- console.log("Consumed all remaining size");
114
- }
115
- else {
116
- // Normal case: consume entire band and continue to next
117
- depthConsumedUsd = bandAvailableDepthUsd;
118
- remainingSizeUsd -= bandAvailableDepthUsd;
119
- console.log("Consumed entire band");
120
- }
121
- // Calculate impact contribution from this band using trapezoidal rule
122
- // Low = previous band's price offset, High = current band's price offset
123
- const lowOffsetP = topOfPrevBandOffsetPpm;
124
- const offsetRangeP = topOfBandOffsetPpm - topOfPrevBandOffsetPpm;
125
- console.log("lowOffsetP", lowOffsetP);
126
- console.log("offsetRangeP", offsetRangeP);
127
- console.log("depthConsumedUsd", depthConsumedUsd);
128
- console.log("bandAvailableDepthUsd", bandAvailableDepthUsd);
129
- // Calculate average impact using trapezoidal rule: low + (range * fraction / 2)
130
- const avgImpactP = lowOffsetP +
131
- (offsetRangeP * depthConsumedUsd) / bandAvailableDepthUsd / 2;
132
- console.log("avgImpactP", avgImpactP);
133
- totalWeightedPriceImpactP += avgImpactP * depthConsumedUsd;
134
- console.log("totalWeightedPriceImpactP", totalWeightedPriceImpactP);
135
- // Update previous values for next iteration
136
- topOfPrevBandOffsetPpm = topOfBandOffsetPpm;
137
- prevBandDepthUsd = bandDepthUsd;
138
- }
139
- console.log("totalWeightedPriceImpactP", totalWeightedPriceImpactP);
140
- console.log("tradeSizeUsd", tradeSizeUsd);
141
- return totalWeightedPriceImpactP / tradeSizeUsd;
142
- };
143
- /**
144
- * @dev Mirrors contract's _getDepthBandsPriceImpactP function
145
- * @param cumulativeVolumeUsd Cumulative volume in USD (can be negative)
146
- * @param tradeSizeUsd Trade size in USD (can be negative)
147
- * @param depthBandParams Depth band parameters (contains both pair bands and global mapping)
148
- * @param priceImpactFactor Price impact factor (protection close factor)
149
- * @param cumulativeFactor Cumulative factor for volume impact
150
- * @returns Price impact percentage (can be negative)
151
- */
152
- const _getDepthBandsPriceImpactP = (cumulativeVolumeUsd, tradeSizeUsd, depthBandParams, priceImpactFactor, cumulativeFactor) => {
153
- // Check for opposite signs
154
- if ((cumulativeVolumeUsd > 0 && tradeSizeUsd < 0) ||
155
- (cumulativeVolumeUsd < 0 && tradeSizeUsd > 0)) {
156
- throw new Error("Wrong params: cumulative volume and trade size have opposite signs");
157
- }
158
- const effectiveCumulativeVolumeUsd = cumulativeVolumeUsd * cumulativeFactor;
159
- const totalSizeLookupUsd = effectiveCumulativeVolumeUsd + tradeSizeUsd;
160
- const isNegative = totalSizeLookupUsd < 0;
161
- const effectiveCumulativeVolumeUsdUint = isNegative
162
- ? -effectiveCumulativeVolumeUsd
163
- : effectiveCumulativeVolumeUsd;
164
- const totalSizeLookupUsdUint = isNegative
165
- ? -totalSizeLookupUsd
166
- : totalSizeLookupUsd;
167
- console.log("effectiveCumulativeVolumeUsdUint", effectiveCumulativeVolumeUsdUint);
168
- console.log("totalSizeLookupUsdUint", totalSizeLookupUsdUint);
169
- const cumulativeVolPriceImpactP = _calculateDepthBandsPriceImpact(effectiveCumulativeVolumeUsdUint, depthBandParams);
170
- const totalSizePriceImpactP = _calculateDepthBandsPriceImpact(totalSizeLookupUsdUint, depthBandParams);
171
- console.log("cumulativeVolPriceImpactP", cumulativeVolPriceImpactP);
172
- console.log("totalSizePriceImpactP", totalSizePriceImpactP);
173
- const unscaledPriceImpactP = cumulativeVolPriceImpactP +
174
- (totalSizePriceImpactP - cumulativeVolPriceImpactP) / 2;
175
- const scaledPriceImpactP = unscaledPriceImpactP * priceImpactFactor;
176
- return isNegative ? -scaledPriceImpactP : scaledPriceImpactP;
177
- };
178
77
  /**
179
78
  * @dev Calculates cumulative volume price impact percentage
180
79
  * @dev Mirrors contract's getTradeCumulVolPriceImpactP function
@@ -188,63 +87,48 @@ const _getDepthBandsPriceImpactP = (cumulativeVolumeUsd, tradeSizeUsd, depthBand
188
87
  * @param context Additional context with depths, OI data, and factors
189
88
  * @returns Cumulative volume price impact percentage (not including spread)
190
89
  */
191
- const getTradeCumulVolPriceImpactP = (_trader, // Unused - kept for compatibility
192
- _pairIndex, // Unused - kept for compatibility
193
- long, tradeOpenInterestUsd, isPnlPositive, open, lastPosIncreaseBlock, context) => {
90
+ const getTradeCumulVolPriceImpactP = (trader, pairIndex, long, tradeOpenInterestUsd, isPnlPositive, open, lastPosIncreaseBlock, context) => {
91
+ var _a, _b;
194
92
  // Update context with passed parameters
195
- const updatedContext = {
196
- ...context,
197
- isOpen: open,
198
- isPnlPositive: isPnlPositive,
199
- createdBlock: context.createdBlock || lastPosIncreaseBlock,
200
- };
93
+ const updatedContext = Object.assign(Object.assign({}, context), { isOpen: open, isPnlPositive: isPnlPositive, createdBlock: context.createdBlock || lastPosIncreaseBlock });
201
94
  if (
202
95
  // No price impact when closing pre-v9.2 trades
203
- (!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) ||
204
97
  // No price impact for opens when `pair.exemptOnOpen` is true
205
- (open && context?.exemptOnOpen === true) ||
98
+ (open && (context === null || context === void 0 ? void 0 : context.exemptOnOpen) === true) ||
206
99
  // No price impact for closes after `protectionCloseFactor` has expired
207
100
  // when `pair.exemptAfterProtectionCloseFactor` is true
208
101
  (!open &&
209
- context?.exemptAfterProtectionCloseFactor === true &&
102
+ (context === null || context === void 0 ? void 0 : context.exemptAfterProtectionCloseFactor) === true &&
210
103
  (0, exports.isProtectionCloseFactorActive)(updatedContext) !== true)) {
211
- console.log("No price impact, protection close factor");
212
104
  return 0;
213
105
  }
106
+ // Calculate trade skew direction (matches Solidity logic)
214
107
  const tradePositiveSkew = (long && open) || (!long && !open);
215
108
  const tradeSkewMultiplier = tradePositiveSkew ? 1 : -1;
216
- console.log("bands", context.pairDepthBands);
217
- console.log("mapping", context.depthBandsMapping);
218
- if (!context.pairDepthBands || !context.depthBandsMapping) {
219
- console.log("No price impact, bands");
220
- return 0;
109
+ // Select depth based on trade direction
110
+ // For positive skew (long open or short close), use depth above
111
+ // For negative skew (short open or long close), use depth below
112
+ const onePercentDepth = tradePositiveSkew
113
+ ? (_a = context.pairDepth) === null || _a === void 0 ? void 0 : _a.onePercentDepthAboveUsd
114
+ : (_b = context.pairDepth) === null || _b === void 0 ? void 0 : _b.onePercentDepthBelowUsd;
115
+ let activeOi = undefined;
116
+ if (context.oiWindowsSettings !== undefined) {
117
+ activeOi = (0, oiWindows_1.getActiveOi)((0, oiWindows_1.getCurrentOiWindowId)(context.oiWindowsSettings), context.oiWindowsSettings.windowsCount, context.oiWindows, open ? long : !long);
221
118
  }
222
- // Select depth bands based on trade direction
223
- const depthBands = tradePositiveSkew
224
- ? context.pairDepthBands.above
225
- : context.pairDepthBands.below;
226
- // Return 0 if no depth bands configured (matching contract lines 588-590)
227
- if (!depthBands || depthBands.totalDepthUsd === 0) {
228
- console.log("No price impact, depth bands");
119
+ if (!onePercentDepth || activeOi === undefined) {
229
120
  return 0;
230
121
  }
231
- // Get active OI for cumulative volume calculation
232
- let activeOi = 0;
233
- if (context.oiWindowsSettings !== undefined) {
234
- activeOi =
235
- (0, oiWindows_1.getActiveOi)((0, oiWindows_1.getCurrentOiWindowId)(context.oiWindowsSettings), context.oiWindowsSettings.windowsCount, context.oiWindows, open ? long : !long) || 0;
236
- }
237
- console.log("activeOi", activeOi);
122
+ // Apply trade skew multiplier to match Solidity's signed calculation
238
123
  const signedActiveOi = activeOi * tradeSkewMultiplier;
239
124
  const signedTradeOi = tradeOpenInterestUsd * tradeSkewMultiplier;
240
- console.log("signedActiveOi", signedActiveOi);
241
- console.log("signedTradeOi", signedTradeOi);
242
- // Calculate price impact using depth bands
243
- const priceImpactP = _getDepthBandsPriceImpactP(signedActiveOi, signedTradeOi, {
244
- depthBands: depthBands,
245
- depthBandsMapping: context.depthBandsMapping,
246
- }, (0, exports.getProtectionCloseFactor)(updatedContext), (0, exports.getCumulativeFactor)(updatedContext));
247
- return priceImpactP;
125
+ // Calculate impact with proper signs (matching Solidity's _getTradePriceImpactP)
126
+ const finalPriceImpactP = ((signedActiveOi * (0, exports.getCumulativeFactor)(updatedContext) +
127
+ signedTradeOi / 2) /
128
+ onePercentDepth /
129
+ (0, exports.getLegacyFactor)(updatedContext)) *
130
+ (0, exports.getProtectionCloseFactor)(updatedContext);
131
+ return finalPriceImpactP;
248
132
  };
249
133
  exports.getTradeCumulVolPriceImpactP = getTradeCumulVolPriceImpactP;
250
134
  /**
@@ -275,7 +159,8 @@ exports.getFixedSpreadP = getFixedSpreadP;
275
159
  * Currently it may double-count user fixed spread if pairSpreadP already includes it
276
160
  */
277
161
  const getSpreadP = (pairSpreadP, isLiquidation, liquidationParams, userPriceImpact) => {
278
- 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;
279
164
  if (pairSpreadP === undefined || (pairSpreadP === 0 && fixedSpreadP === 0)) {
280
165
  return 0;
281
166
  }
@@ -295,21 +180,28 @@ exports.getSpreadP = getSpreadP;
295
180
  * @param buy True for long, false for short
296
181
  * @param collateral Collateral amount
297
182
  * @param leverage Position leverage
183
+ * @param pairDepth 1% depth values for the pair
298
184
  * @param oiWindowsSettings OI windows configuration
299
185
  * @param oiWindows Current OI windows data
300
186
  * @param context Additional context for the calculation
301
187
  * @returns Total spread + cumulative volume price impact percentage
302
188
  */
303
- const getSpreadWithCumulVolPriceImpactP = (pairSpreadP, buy, collateral, leverage, context) => {
189
+ const getSpreadWithCumulVolPriceImpactP = (pairSpreadP, buy, collateral, leverage, pairDepth, oiWindowsSettings, oiWindows, context) => {
304
190
  if (pairSpreadP === undefined) {
305
191
  return 0;
306
192
  }
307
- 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);
308
194
  // Calculate position size in USD
309
- const positionSizeUsd = collateral * leverage * (context?.collateralPriceUsd || 1);
195
+ const positionSizeUsd = collateral * leverage * ((context === null || context === void 0 ? void 0 : context.collateralPriceUsd) || 1);
310
196
  const cumulVolImpact = (0, exports.getTradeCumulVolPriceImpactP)("", // trader - not used in calculation
311
197
  0, // pairIndex - not used in calculation
312
- buy, positionSizeUsd, context?.isPnlPositive || false, context?.isOpen !== false, context?.createdBlock || 0, context);
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,
199
+ oiWindowsSettings,
200
+ oiWindows }));
201
+ // If no depth or OI data, return just half spread
202
+ if (cumulVolImpact === 0 && (!pairDepth || !oiWindowsSettings)) {
203
+ return pairSpreadP / 2;
204
+ }
313
205
  return baseSpread + cumulVolImpact;
314
206
  };
315
207
  exports.getSpreadWithCumulVolPriceImpactP = getSpreadWithCumulVolPriceImpactP;
@@ -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
  };
@@ -23,17 +23,14 @@ const getTradeOpeningPriceImpact = (input, context) => {
23
23
  // Calculate fixed spread
24
24
  const spreadP = (0, cumulVol_1.getFixedSpreadP)(input.pairSpreadP, input.long, true // opening
25
25
  );
26
- console.log("spreadP", spreadP);
27
26
  // Calculate position size in USD
28
27
  const positionSizeUsd = positionSizeCollateral * context.collateralPriceUsd;
29
- console.log("positionSizeUsd", positionSizeUsd);
30
28
  // Calculate cumulative volume price impact
31
29
  const cumulVolPriceImpactP = (0, cumulVol_1.getTradeCumulVolPriceImpactP)("", // trader - not needed for calculation
32
30
  input.pairIndex, input.long, positionSizeUsd, false, // isPnlPositive - not relevant for opening
33
31
  true, // open
34
32
  0, // lastPosIncreaseBlock - not relevant for opening
35
33
  context.cumulVolContext);
36
- console.log("cumulVolPriceImpactP", cumulVolPriceImpactP);
37
34
  // Calculate price after spread and cumulative volume impact (before skew)
38
35
  const priceAfterSpreadAndCumulVolPriceImpact = (0, __1.getPriceAfterImpact)(input.openPrice, spreadP + cumulVolPriceImpactP);
39
36
  // Calculate position size in tokens using the price after fixed spread and cumul vol impact
@@ -77,9 +74,6 @@ exports.getTradeOpeningPriceImpact = getTradeOpeningPriceImpact;
77
74
  * @returns Price impact breakdown and final price
78
75
  */
79
76
  const getTradeOpeningPriceImpactAtMarket = (input, context, currentMarketPrice) => {
80
- return (0, exports.getTradeOpeningPriceImpact)({
81
- ...input,
82
- openPrice: currentMarketPrice,
83
- }, context);
77
+ return (0, exports.getTradeOpeningPriceImpact)(Object.assign(Object.assign({}, input), { openPrice: currentMarketPrice }), context);
84
78
  };
85
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.3.0-rc7",
3
+ "version": "1.4.0-rc1",
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",