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