@gainsnetwork/sdk 0.0.0-v10.rc1 → 0.0.0-v10.rc11

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 (210) hide show
  1. package/lib/backend/globalTrades/index.d.ts +11 -0
  2. package/lib/backend/globalTrades/index.js +69 -0
  3. package/lib/backend/index.d.ts +3 -0
  4. package/lib/backend/index.js +28 -0
  5. package/lib/backend/tradingVariables/backend.types.d.ts +318 -0
  6. package/lib/backend/tradingVariables/backend.types.js +2 -0
  7. package/lib/backend/tradingVariables/converter.d.ts +34 -0
  8. package/lib/backend/tradingVariables/converter.js +338 -0
  9. package/lib/backend/tradingVariables/index.d.ts +5 -0
  10. package/lib/backend/tradingVariables/index.js +96 -0
  11. package/lib/backend/tradingVariables/types.d.ts +113 -0
  12. package/lib/backend/tradingVariables/types.js +14 -0
  13. package/lib/constants.d.ts +18 -1
  14. package/lib/constants.js +19 -2
  15. package/lib/contracts/types/generated/GFarmTradingStorageV5.d.ts +1911 -0
  16. package/lib/contracts/types/generated/GFarmTradingStorageV5.js +2 -0
  17. package/lib/contracts/types/generated/GNSBorrowingFees.d.ts +1067 -0
  18. package/lib/contracts/types/generated/GNSBorrowingFees.js +2 -0
  19. package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.d.ts +979 -0
  20. package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.js +2 -0
  21. package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.d.ts +1058 -0
  22. package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.js +2 -0
  23. package/lib/contracts/types/generated/GNSNftRewardsV6.d.ts +533 -0
  24. package/lib/contracts/types/generated/GNSNftRewardsV6.js +2 -0
  25. package/lib/contracts/types/generated/GNSNftRewardsV6_3_1.d.ts +613 -0
  26. package/lib/contracts/types/generated/GNSNftRewardsV6_3_1.js +2 -0
  27. package/lib/contracts/types/generated/GNSPairInfosV6_1.d.ts +911 -0
  28. package/lib/contracts/types/generated/GNSPairInfosV6_1.js +2 -0
  29. package/lib/contracts/types/generated/GNSPairsStorageV6.d.ts +660 -0
  30. package/lib/contracts/types/generated/GNSPairsStorageV6.js +2 -0
  31. package/lib/contracts/types/generated/GNSTrading.d.ts +758 -0
  32. package/lib/contracts/types/generated/GNSTrading.js +2 -0
  33. package/lib/contracts/types/generated/GNSTradingCallbacks.d.ts +875 -0
  34. package/lib/contracts/types/generated/GNSTradingCallbacks.js +2 -0
  35. package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.d.ts +806 -0
  36. package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.js +2 -0
  37. package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.d.ts +821 -0
  38. package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.js +2 -0
  39. package/lib/contracts/types/generated/GNSTradingStorage.d.ts +1387 -0
  40. package/lib/contracts/types/generated/GNSTradingStorage.js +2 -0
  41. package/lib/contracts/types/generated/GTokenV6_3_2.d.ts +1838 -0
  42. package/lib/contracts/types/generated/GTokenV6_3_2.js +2 -0
  43. package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.d.ts +83 -0
  44. package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.js +2691 -0
  45. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.d.ts +88 -0
  46. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.js +1654 -0
  47. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.d.ts +113 -0
  48. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.js +1742 -0
  49. package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.d.ts +124 -0
  50. package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.js +1784 -0
  51. package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.d.ts +100 -0
  52. package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.js +1116 -0
  53. package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.d.ts +100 -0
  54. package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.js +1003 -0
  55. package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.d.ts +98 -0
  56. package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.js +1485 -0
  57. package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.d.ts +117 -0
  58. package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.js +1265 -0
  59. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.d.ts +82 -0
  60. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.js +1273 -0
  61. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.d.ts +82 -0
  62. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.js +1326 -0
  63. package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.d.ts +113 -0
  64. package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.js +1428 -0
  65. package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.d.ts +96 -0
  66. package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.js +2241 -0
  67. package/lib/contracts/types/generated/factories/GNSTrading__factory.d.ts +95 -0
  68. package/lib/contracts/types/generated/factories/GNSTrading__factory.js +1071 -0
  69. package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.d.ts +110 -0
  70. package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.js +2682 -0
  71. package/lib/contracts/types/index.d.ts +2 -1
  72. package/lib/contracts/types/index.js +1 -0
  73. package/lib/contracts/utils/openTrades.d.ts +1 -0
  74. package/lib/contracts/utils/openTrades.js +94 -56
  75. package/lib/contracts/utils/pairs.js +17 -0
  76. package/lib/index.d.ts +2 -0
  77. package/lib/index.js +5 -0
  78. package/lib/markets/collateral/converter.d.ts +5 -0
  79. package/lib/markets/collateral/converter.js +11 -0
  80. package/lib/markets/collateral/index.d.ts +1 -0
  81. package/lib/markets/collateral/index.js +17 -0
  82. package/lib/markets/collateral/types.d.ts +7 -0
  83. package/lib/markets/collateral/types.js +2 -0
  84. package/lib/markets/index.d.ts +3 -0
  85. package/lib/markets/index.js +3 -0
  86. package/lib/markets/oi/converter.d.ts +63 -0
  87. package/lib/markets/oi/converter.js +103 -0
  88. package/lib/markets/oi/fetcher.d.ts +58 -0
  89. package/lib/markets/oi/fetcher.js +181 -0
  90. package/lib/markets/oi/index.d.ts +10 -0
  91. package/lib/markets/oi/index.js +37 -0
  92. package/lib/markets/oi/types.d.ts +82 -0
  93. package/lib/markets/oi/types.js +6 -0
  94. package/lib/markets/oi/validation.d.ts +80 -0
  95. package/lib/markets/oi/validation.js +172 -0
  96. package/lib/markets/price/builder.d.ts +25 -0
  97. package/lib/markets/price/builder.js +69 -0
  98. package/lib/markets/price/index.d.ts +6 -0
  99. package/lib/markets/price/index.js +22 -0
  100. package/lib/markets/price/marketPrice.d.ts +12 -0
  101. package/lib/markets/price/marketPrice.js +34 -0
  102. package/lib/markets/price/types.d.ts +23 -0
  103. package/lib/markets/price/types.js +5 -0
  104. package/lib/trade/fees/borrowing/builder.d.ts +14 -0
  105. package/lib/trade/fees/borrowing/builder.js +33 -0
  106. package/lib/trade/fees/borrowing/index.d.ts +24 -2
  107. package/lib/trade/fees/borrowing/index.js +51 -16
  108. package/lib/trade/fees/borrowingV2/builder.d.ts +6 -0
  109. package/lib/trade/fees/borrowingV2/builder.js +24 -0
  110. package/lib/trade/fees/borrowingV2/converter.d.ts +75 -0
  111. package/lib/trade/fees/borrowingV2/converter.js +132 -0
  112. package/lib/trade/fees/borrowingV2/fetcher.d.ts +75 -0
  113. package/lib/trade/fees/borrowingV2/fetcher.js +185 -0
  114. package/lib/trade/fees/borrowingV2/index.d.ts +48 -0
  115. package/lib/trade/fees/borrowingV2/index.js +112 -0
  116. package/lib/trade/fees/borrowingV2/types.d.ts +95 -0
  117. package/lib/trade/fees/borrowingV2/types.js +5 -0
  118. package/lib/trade/fees/converter.d.ts +48 -0
  119. package/lib/trade/fees/converter.js +114 -0
  120. package/lib/trade/fees/fundingFees/builder.d.ts +9 -0
  121. package/lib/trade/fees/fundingFees/builder.js +35 -0
  122. package/lib/trade/fees/fundingFees/converter.d.ts +102 -0
  123. package/lib/trade/fees/fundingFees/converter.js +196 -0
  124. package/lib/trade/fees/fundingFees/fetcher.d.ts +66 -0
  125. package/lib/trade/fees/fundingFees/fetcher.js +150 -0
  126. package/lib/trade/fees/fundingFees/index.d.ts +124 -0
  127. package/lib/trade/fees/fundingFees/index.js +309 -0
  128. package/lib/trade/fees/fundingFees/pairContext.d.ts +33 -0
  129. package/lib/trade/fees/fundingFees/pairContext.js +17 -0
  130. package/lib/trade/fees/fundingFees/types.d.ts +77 -0
  131. package/lib/trade/fees/fundingFees/types.js +5 -0
  132. package/lib/trade/fees/index.d.ts +7 -2
  133. package/lib/trade/fees/index.js +66 -16
  134. package/lib/trade/fees/tiers/converter.d.ts +54 -0
  135. package/lib/trade/fees/tiers/converter.js +81 -0
  136. package/lib/trade/fees/tiers/index.d.ts +18 -0
  137. package/lib/trade/fees/tiers/index.js +45 -1
  138. package/lib/trade/fees/trading/builder.d.ts +18 -0
  139. package/lib/trade/fees/trading/builder.js +20 -0
  140. package/lib/trade/fees/trading/converter.d.ts +32 -0
  141. package/lib/trade/fees/trading/converter.js +47 -0
  142. package/lib/trade/fees/trading/holdingFees.d.ts +28 -0
  143. package/lib/trade/fees/trading/holdingFees.js +66 -0
  144. package/lib/trade/fees/trading/holdingFeesStructured.d.ts +28 -0
  145. package/lib/trade/fees/trading/holdingFeesStructured.js +66 -0
  146. package/lib/trade/fees/trading/index.d.ts +62 -0
  147. package/lib/trade/fees/trading/index.js +155 -0
  148. package/lib/trade/fees/trading/types.d.ts +48 -0
  149. package/lib/trade/fees/trading/types.js +5 -0
  150. package/lib/trade/index.d.ts +3 -2
  151. package/lib/trade/index.js +3 -2
  152. package/lib/trade/liquidation/builder.d.ts +25 -0
  153. package/lib/trade/liquidation/builder.js +59 -0
  154. package/lib/trade/liquidation/converter.d.ts +23 -0
  155. package/lib/trade/liquidation/converter.js +46 -0
  156. package/lib/trade/liquidation/index.d.ts +16 -0
  157. package/lib/trade/liquidation/index.js +123 -0
  158. package/lib/trade/liquidation/types.d.ts +42 -0
  159. package/lib/trade/liquidation/types.js +2 -0
  160. package/lib/trade/pnl/builder.d.ts +16 -0
  161. package/lib/trade/pnl/builder.js +44 -0
  162. package/lib/trade/pnl/converter.d.ts +47 -0
  163. package/lib/trade/pnl/converter.js +72 -0
  164. package/lib/trade/pnl/index.d.ts +88 -0
  165. package/lib/trade/pnl/index.js +286 -0
  166. package/lib/trade/pnl/types.d.ts +75 -0
  167. package/lib/trade/pnl/types.js +5 -0
  168. package/lib/trade/priceImpact/close/builder.d.ts +23 -0
  169. package/lib/trade/priceImpact/close/builder.js +45 -0
  170. package/lib/trade/priceImpact/close/index.d.ts +22 -0
  171. package/lib/trade/priceImpact/close/index.js +137 -0
  172. package/lib/trade/priceImpact/close/types.d.ts +44 -0
  173. package/lib/trade/priceImpact/close/types.js +5 -0
  174. package/lib/trade/priceImpact/cumulVol/builder.d.ts +22 -0
  175. package/lib/trade/priceImpact/cumulVol/builder.js +43 -0
  176. package/lib/trade/priceImpact/cumulVol/converter.d.ts +31 -0
  177. package/lib/trade/priceImpact/cumulVol/converter.js +59 -0
  178. package/lib/trade/priceImpact/cumulVol/index.d.ts +108 -0
  179. package/lib/trade/priceImpact/cumulVol/index.js +231 -0
  180. package/lib/trade/priceImpact/index.d.ts +13 -0
  181. package/lib/trade/priceImpact/index.js +64 -0
  182. package/lib/trade/priceImpact/open/builder.d.ts +21 -0
  183. package/lib/trade/priceImpact/open/builder.js +43 -0
  184. package/lib/trade/priceImpact/open/index.d.ts +23 -0
  185. package/lib/trade/priceImpact/open/index.js +79 -0
  186. package/lib/trade/priceImpact/open/types.d.ts +42 -0
  187. package/lib/trade/priceImpact/open/types.js +5 -0
  188. package/lib/trade/priceImpact/skew/builder.d.ts +12 -0
  189. package/lib/trade/priceImpact/skew/builder.js +28 -0
  190. package/lib/trade/priceImpact/skew/converter.d.ts +46 -0
  191. package/lib/trade/priceImpact/skew/converter.js +81 -0
  192. package/lib/trade/priceImpact/skew/fetcher.d.ts +60 -0
  193. package/lib/trade/priceImpact/skew/fetcher.js +169 -0
  194. package/lib/trade/priceImpact/skew/index.d.ts +60 -0
  195. package/lib/trade/priceImpact/skew/index.js +173 -0
  196. package/lib/trade/priceImpact/skew/types.d.ts +42 -0
  197. package/lib/trade/priceImpact/skew/types.js +5 -0
  198. package/lib/trade/spread.d.ts +5 -18
  199. package/lib/trade/spread.js +17 -106
  200. package/lib/trade/types.d.ts +44 -9
  201. package/lib/trade/types.js +17 -0
  202. package/lib/trade/utils.d.ts +18 -0
  203. package/lib/trade/utils.js +30 -0
  204. package/lib/vault/index.d.ts +3 -1
  205. package/lib/vault/index.js +2 -2
  206. package/package.json +2 -1
  207. package/lib/trade/liquidation.d.ts +0 -12
  208. package/lib/trade/liquidation.js +0 -55
  209. package/lib/trade/pnl.d.ts +0 -10
  210. package/lib/trade/pnl.js +0 -33
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildTradeClosingPriceImpactContext = void 0;
4
+ const builder_1 = require("../cumulVol/builder");
5
+ const builder_2 = require("../skew/builder");
6
+ /**
7
+ * @dev Builds a complete context for trade closing price impact calculations
8
+ * @dev Uses sub-context builders to create properly scoped contexts
9
+ * @param globalTradingVariables The transformed global trading variables from backend
10
+ * @param collateralIndex The collateral index (1-based)
11
+ * @param pairIndex The pair index
12
+ * @param tradeInfo Trade information including createdBlock
13
+ * @param additionalParams Additional parameters not available in trading variables
14
+ * @returns Complete context ready for getTradeClosingPriceImpact
15
+ */
16
+ const buildTradeClosingPriceImpactContext = (globalTradingVariables, collateralIndex, pairIndex, tradeInfo, additionalParams) => {
17
+ var _a;
18
+ const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
19
+ if (!collateral) {
20
+ return undefined;
21
+ }
22
+ // Build cumulative volume subcontext for closing
23
+ const cumulVolContext = (0, builder_1.buildCumulVolContext)(globalTradingVariables, collateralIndex, pairIndex, {
24
+ currentBlock: additionalParams.currentBlock,
25
+ contractsVersion: additionalParams.contractsVersion || tradeInfo.contractsVersion,
26
+ isPnlPositive: additionalParams.isPnlPositive,
27
+ isOpen: false,
28
+ createdBlock: tradeInfo.createdBlock,
29
+ userPriceImpact: additionalParams.userPriceImpact,
30
+ protectionCloseFactorWhitelist: additionalParams.protectionCloseFactorWhitelist,
31
+ });
32
+ // Build skew price impact subcontext
33
+ const skewContext = (0, builder_2.buildSkewPriceImpactContext)(collateral, pairIndex);
34
+ if (!cumulVolContext || !skewContext) {
35
+ return undefined;
36
+ }
37
+ // Return structured context with proper subcontexts
38
+ return {
39
+ collateralPriceUsd: ((_a = collateral.prices) === null || _a === void 0 ? void 0 : _a.collateralPriceUsd) || 1,
40
+ cumulVolContext,
41
+ skewContext,
42
+ tradeInfo,
43
+ };
44
+ };
45
+ exports.buildTradeClosingPriceImpactContext = buildTradeClosingPriceImpactContext;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @dev Trade closing price impact calculations
3
+ * @dev Mirrors contract's TradingCommonUtils.getTradeClosingPriceImpact
4
+ */
5
+ import { TradeClosingPriceImpactInput, TradeClosingPriceImpactContext, TradeClosingPriceImpactResult } from "./types";
6
+ export type { TradeClosingPriceImpactInput, TradeClosingPriceImpactContext, TradeClosingPriceImpactResult, };
7
+ export { buildTradeClosingPriceImpactContext } from "./builder";
8
+ /**
9
+ * @dev Calculates all price impacts for trade closing
10
+ * @dev Mirrors contract's getTradeClosingPriceImpact function
11
+ * @param input Trade parameters
12
+ * @param context Combined context for calculations
13
+ * @returns Price impact breakdown and trade value
14
+ */
15
+ export declare const getTradeClosingPriceImpact: (input: TradeClosingPriceImpactInput, context: TradeClosingPriceImpactContext) => TradeClosingPriceImpactResult;
16
+ /**
17
+ * @dev Simplified version using oracle price as current price
18
+ * @param input Trade parameters (without currentPairPrice)
19
+ * @param context Combined context
20
+ * @returns Price impact breakdown and trade value
21
+ */
22
+ export declare const getTradeClosingPriceImpactAtOracle: (input: Omit<TradeClosingPriceImpactInput, "currentPairPrice">, context: TradeClosingPriceImpactContext) => TradeClosingPriceImpactResult;
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Trade closing price impact calculations
4
+ * @dev Mirrors contract's TradingCommonUtils.getTradeClosingPriceImpact
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.getTradeClosingPriceImpactAtOracle = exports.getTradeClosingPriceImpact = exports.buildTradeClosingPriceImpactContext = void 0;
8
+ const cumulVol_1 = require("../cumulVol");
9
+ const skew_1 = require("../skew");
10
+ const types_1 = require("../../../contracts/types");
11
+ // Export builder
12
+ var builder_1 = require("./builder");
13
+ Object.defineProperty(exports, "buildTradeClosingPriceImpactContext", { enumerable: true, get: function () { return builder_1.buildTradeClosingPriceImpactContext; } });
14
+ /**
15
+ * @dev Calculates position size in tokens for the portion being closed
16
+ * @param positionSizeCollateral Position size in collateral units being closed
17
+ * @param originalPositionSizeToken Original total position size in tokens
18
+ * @param originalCollateral Original collateral amount
19
+ * @param originalLeverage Original leverage
20
+ * @returns Position size in tokens for the closing portion
21
+ */
22
+ const calculateClosingPositionSizeToken = (positionSizeCollateral, originalPositionSizeToken, originalCollateral, originalLeverage) => {
23
+ const totalPositionSizeCollateral = originalCollateral * originalLeverage;
24
+ if (totalPositionSizeCollateral === 0)
25
+ return 0;
26
+ // Match contract logic: (positionSizeCollateral * originalPositionSizeToken) / totalPositionSizeCollateral
27
+ return ((positionSizeCollateral * originalPositionSizeToken) /
28
+ totalPositionSizeCollateral);
29
+ };
30
+ /**
31
+ * @dev Calculates all price impacts for trade closing
32
+ * @dev Mirrors contract's getTradeClosingPriceImpact function
33
+ * @param input Trade parameters
34
+ * @param context Combined context for calculations
35
+ * @returns Price impact breakdown and trade value
36
+ */
37
+ const getTradeClosingPriceImpact = (input, context) => {
38
+ // For trades before V9.2, return oracle price without any impact
39
+ if (input.contractsVersion === types_1.ContractsVersion.BEFORE_V9_2) {
40
+ return {
41
+ positionSizeToken: 0,
42
+ fixedSpreadP: 0,
43
+ cumulVolPriceImpactP: 0,
44
+ skewPriceImpactP: 0,
45
+ totalPriceImpactP: 0,
46
+ priceAfterImpact: input.oraclePrice,
47
+ tradeValueCollateralNoFactor: 0,
48
+ };
49
+ }
50
+ // Calculate position size in tokens (proportional to collateral being closed)
51
+ const positionSizeToken = input.trade.positionSizeToken
52
+ ? calculateClosingPositionSizeToken(input.positionSizeCollateral, input.trade.positionSizeToken, input.trade.collateralAmount, input.trade.leverage)
53
+ : 0;
54
+ // Calculate fixed spread (reversed for closing)
55
+ const fixedSpreadP = (0, cumulVol_1.getFixedSpreadP)(input.pairSpreadP, input.trade.long, false // closing
56
+ );
57
+ let cumulVolPriceImpactP = 0;
58
+ let tradeValueCollateralNoFactor = 0;
59
+ if (input.useCumulativeVolPriceImpact) {
60
+ // First pass: Calculate with negative PnL assumption
61
+ const positionSizeUsd = input.positionSizeCollateral * context.collateralPriceUsd;
62
+ cumulVolPriceImpactP = (0, cumulVol_1.getTradeCumulVolPriceImpactP)(input.trade.user, input.pairIndex, input.trade.long, positionSizeUsd, false, // Assume negative PnL initially
63
+ false, // closing
64
+ context.tradeInfo.lastPosIncreaseBlock || context.tradeInfo.createdBlock, context.cumulVolContext);
65
+ // Calculate price with conservative impact
66
+ const priceWithImpact = input.trade.long
67
+ ? input.currentPairPrice *
68
+ (1 - (fixedSpreadP + cumulVolPriceImpactP) / 100)
69
+ : input.currentPairPrice /
70
+ (1 - (fixedSpreadP + cumulVolPriceImpactP) / 100);
71
+ // Calculate trade value in collateral
72
+ // For long: value = positionSizeToken * priceWithImpact
73
+ // For short: value = positionSizeToken / priceWithImpact * openPrice^2 / currentPrice
74
+ if (positionSizeToken > 0) {
75
+ if (input.trade.long) {
76
+ tradeValueCollateralNoFactor = positionSizeToken * priceWithImpact;
77
+ }
78
+ else {
79
+ // Short calculation: profit from price decrease
80
+ const pnlFactor = (2 * input.trade.openPrice - priceWithImpact) / input.trade.openPrice;
81
+ tradeValueCollateralNoFactor = input.positionSizeCollateral * pnlFactor;
82
+ }
83
+ }
84
+ else {
85
+ tradeValueCollateralNoFactor = input.positionSizeCollateral;
86
+ }
87
+ // Determine actual PnL
88
+ const isPnlPositive = tradeValueCollateralNoFactor > input.trade.collateralAmount;
89
+ // Second pass: Recalculate with actual PnL if positive
90
+ if (isPnlPositive) {
91
+ cumulVolPriceImpactP = (0, cumulVol_1.getTradeCumulVolPriceImpactP)(input.trade.user, input.pairIndex, input.trade.long, positionSizeUsd, true, // Positive PnL
92
+ false, // closing
93
+ context.tradeInfo.lastPosIncreaseBlock ||
94
+ context.tradeInfo.createdBlock, context.cumulVolContext);
95
+ }
96
+ }
97
+ // Calculate skew price impact (v10+ only)
98
+ const skewPriceImpactP = input.contractsVersion === types_1.ContractsVersion.V10
99
+ ? (0, skew_1.getTradeSkewPriceImpactWithChecks)({
100
+ collateralIndex: input.collateralIndex,
101
+ pairIndex: input.pairIndex,
102
+ long: input.trade.long,
103
+ open: false,
104
+ positionSizeCollateral: input.positionSizeCollateral,
105
+ currentPrice: input.currentPairPrice,
106
+ contractsVersion: input.contractsVersion,
107
+ isCounterTrade: input.trade.isCounterTrade,
108
+ }, context.skewContext)
109
+ : 0;
110
+ // Total price impact (all components)
111
+ const totalPriceImpactP = fixedSpreadP + cumulVolPriceImpactP + skewPriceImpactP;
112
+ // Calculate final price after all impacts
113
+ // For closing: longs get worse price when impact is positive, shorts get better
114
+ const priceAfterImpact = input.trade.long
115
+ ? input.currentPairPrice * (1 - totalPriceImpactP / 100)
116
+ : input.currentPairPrice / (1 - totalPriceImpactP / 100);
117
+ return {
118
+ positionSizeToken,
119
+ fixedSpreadP,
120
+ cumulVolPriceImpactP,
121
+ skewPriceImpactP,
122
+ totalPriceImpactP,
123
+ priceAfterImpact,
124
+ tradeValueCollateralNoFactor,
125
+ };
126
+ };
127
+ exports.getTradeClosingPriceImpact = getTradeClosingPriceImpact;
128
+ /**
129
+ * @dev Simplified version using oracle price as current price
130
+ * @param input Trade parameters (without currentPairPrice)
131
+ * @param context Combined context
132
+ * @returns Price impact breakdown and trade value
133
+ */
134
+ const getTradeClosingPriceImpactAtOracle = (input, context) => {
135
+ return (0, exports.getTradeClosingPriceImpact)(Object.assign(Object.assign({}, input), { currentPairPrice: input.oraclePrice }), context);
136
+ };
137
+ exports.getTradeClosingPriceImpactAtOracle = getTradeClosingPriceImpactAtOracle;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @dev Types for trade closing price impact calculations
3
+ */
4
+ import { CumulVolContext } from "../cumulVol";
5
+ import { SkewPriceImpactContext } from "../skew/types";
6
+ import { Trade, TradeInfo, PairIndex } from "../../types";
7
+ /**
8
+ * @dev Input parameters for trade closing price impact
9
+ * @dev Mirrors contract's TradePriceImpactInput struct
10
+ */
11
+ export type TradeClosingPriceImpactInput = {
12
+ trade: Trade;
13
+ oraclePrice: number;
14
+ positionSizeCollateral: number;
15
+ currentPairPrice: number;
16
+ useCumulativeVolPriceImpact: boolean;
17
+ collateralIndex: number;
18
+ pairIndex: PairIndex;
19
+ pairSpreadP: number;
20
+ contractsVersion: number;
21
+ };
22
+ /**
23
+ * @dev Context for trade closing price impact calculation
24
+ * Combines contexts from spread, cumul vol, and skew
25
+ */
26
+ export type TradeClosingPriceImpactContext = {
27
+ collateralPriceUsd: number;
28
+ cumulVolContext: CumulVolContext;
29
+ skewContext: SkewPriceImpactContext;
30
+ tradeInfo: TradeInfo;
31
+ };
32
+ /**
33
+ * @dev Result of trade closing price impact calculation
34
+ * @dev Mirrors contract's TradePriceImpact struct with additional return value
35
+ */
36
+ export type TradeClosingPriceImpactResult = {
37
+ positionSizeToken: number;
38
+ fixedSpreadP: number;
39
+ cumulVolPriceImpactP: number;
40
+ skewPriceImpactP: number;
41
+ totalPriceImpactP: number;
42
+ priceAfterImpact: number;
43
+ tradeValueCollateralNoFactor: number;
44
+ };
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Types for trade closing price impact calculations
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,22 @@
1
+ import { GlobalTradingVariablesType } from "../../../backend/tradingVariables/types";
2
+ import { CumulVolContext } from "./index";
3
+ /**
4
+ * @dev Builds cumulative volume price impact sub-context for a specific pair
5
+ * @param globalTradingVariables The transformed global trading variables from backend
6
+ * @param collateralIndex The collateral index (1-based)
7
+ * @param pairIndex The pair index
8
+ * @param additionalParams Additional parameters not available in trading variables
9
+ * @returns Cumulative volume context ready for getTradeCumulVolPriceImpactP
10
+ */
11
+ export declare const buildCumulVolContext: (globalTradingVariables: GlobalTradingVariablesType, collateralIndex: number, pairIndex: number, additionalParams: {
12
+ currentBlock: number;
13
+ contractsVersion?: number;
14
+ isPnlPositive?: boolean;
15
+ isOpen?: boolean;
16
+ createdBlock?: number;
17
+ userPriceImpact?: {
18
+ cumulVolPriceImpactMultiplier: number;
19
+ fixedSpreadP: number;
20
+ };
21
+ protectionCloseFactorWhitelist?: boolean;
22
+ }) => CumulVolContext | undefined;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildCumulVolContext = void 0;
4
+ /**
5
+ * @dev Builds cumulative volume price impact sub-context for a specific pair
6
+ * @param globalTradingVariables The transformed global trading variables from backend
7
+ * @param collateralIndex The collateral index (1-based)
8
+ * @param pairIndex The pair index
9
+ * @param additionalParams Additional parameters not available in trading variables
10
+ * @returns Cumulative volume context ready for getTradeCumulVolPriceImpactP
11
+ */
12
+ const buildCumulVolContext = (globalTradingVariables, collateralIndex, pairIndex, additionalParams) => {
13
+ var _a, _b, _c, _d, _e, _f, _g, _h;
14
+ const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
15
+ if (!collateral) {
16
+ return undefined;
17
+ }
18
+ // 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];
22
+ // Get OI windows settings (same for all pairs)
23
+ // OI windows settings from global trading variables are already in SDK format
24
+ const oiWindowsSettings = globalTradingVariables.oiWindowsSettings;
25
+ // Get user-specific parameters from additionalParams
26
+ const userPriceImpact = additionalParams.userPriceImpact;
27
+ const protectionCloseFactorWhitelist = additionalParams.protectionCloseFactorWhitelist;
28
+ // Get liquidation params - check both pair and group level
29
+ const liquidationParams = ((_e = (_d = globalTradingVariables.liquidationParams) === null || _d === void 0 ? void 0 : _d.pairs) === null || _e === void 0 ? void 0 : _e[pairIndex]) ||
30
+ ((_g = (_f = globalTradingVariables.liquidationParams) === null || _f === void 0 ? void 0 : _f.groups) === null || _g === void 0 ? void 0 : _g[0]); // fallback to first group
31
+ return Object.assign({
32
+ // Trade state
33
+ isOpen: additionalParams.isOpen, isPnlPositive: additionalParams.isPnlPositive, createdBlock: additionalParams.createdBlock,
34
+ // Protection factors
35
+ liquidationParams, currentBlock: additionalParams.currentBlock, contractsVersion: additionalParams.contractsVersion, protectionCloseFactorWhitelist,
36
+ // Price impact data
37
+ pairDepth,
38
+ oiWindowsSettings,
39
+ oiWindows,
40
+ // User/collateral specific
41
+ userPriceImpact, collateralPriceUsd: ((_h = collateral.prices) === null || _h === void 0 ? void 0 : _h.collateralPriceUsd) || 1 }, pairFactor);
42
+ };
43
+ exports.buildCumulVolContext = buildCumulVolContext;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @dev Converters for cumulative volume price impact data between contract and SDK formats
3
+ * @dev All BigNumber values are normalized to floats with appropriate precision
4
+ */
5
+ import { IPriceImpact } from "../../../contracts/types/generated/GNSMultiCollatDiamond";
6
+ import { OiWindowsSettings, OiWindow, OiWindows } from "../../types";
7
+ /**
8
+ * @dev Converts contract OI windows settings to SDK format
9
+ * @param contractData Contract OiWindowsSettings struct
10
+ * @returns Normalized OI windows settings
11
+ */
12
+ export declare const convertOiWindowsSettings: (contractData: IPriceImpact.OiWindowsSettingsStructOutput) => OiWindowsSettings;
13
+ /**
14
+ * @dev Converts contract PairOi data to SDK OiWindow format
15
+ * @param contractData Contract PairOi struct with USD values
16
+ * @returns Normalized OI window data
17
+ */
18
+ export declare const convertOiWindow: (contractData: IPriceImpact.PairOiStructOutput) => OiWindow;
19
+ /**
20
+ * @dev Converts array of OI windows from contract format
21
+ * @param windowIds Array of window IDs (as strings for mapping)
22
+ * @param contractWindows Array of PairOi data from contract
23
+ * @returns Normalized OI windows mapping
24
+ */
25
+ export declare const convertOiWindows: (windowIds: string[], contractWindows: IPriceImpact.PairOiStructOutput[]) => OiWindows;
26
+ /**
27
+ * @dev Batch converter for multiple OI windows settings
28
+ * @param contractDataArray Array of contract OiWindowsSettings
29
+ * @returns Array of normalized OI windows settings
30
+ */
31
+ export declare const convertOiWindowsSettingsArray: (contractDataArray: IPriceImpact.OiWindowsSettingsStructOutput[]) => OiWindowsSettings[];
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Converters for cumulative volume price impact data between contract and SDK formats
4
+ * @dev All BigNumber values are normalized to floats with appropriate precision
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.convertOiWindowsSettingsArray = exports.convertOiWindows = exports.convertOiWindow = exports.convertOiWindowsSettings = void 0;
8
+ /**
9
+ * @dev Converts contract OI windows settings to SDK format
10
+ * @param contractData Contract OiWindowsSettings struct
11
+ * @returns Normalized OI windows settings
12
+ */
13
+ const convertOiWindowsSettings = (contractData) => {
14
+ return {
15
+ startTs: Number(contractData.startTs),
16
+ windowsDuration: Number(contractData.windowsDuration),
17
+ windowsCount: Number(contractData.windowsCount),
18
+ };
19
+ };
20
+ exports.convertOiWindowsSettings = convertOiWindowsSettings;
21
+ /**
22
+ * @dev Converts contract PairOi data to SDK OiWindow format
23
+ * @param contractData Contract PairOi struct with USD values
24
+ * @returns Normalized OI window data
25
+ */
26
+ const convertOiWindow = (contractData) => {
27
+ // USD values are stored as 1e18 in contract
28
+ return {
29
+ oiLongUsd: Number(contractData.oiLongUsd) / 1e18,
30
+ oiShortUsd: Number(contractData.oiShortUsd) / 1e18,
31
+ };
32
+ };
33
+ exports.convertOiWindow = convertOiWindow;
34
+ /**
35
+ * @dev Converts array of OI windows from contract format
36
+ * @param windowIds Array of window IDs (as strings for mapping)
37
+ * @param contractWindows Array of PairOi data from contract
38
+ * @returns Normalized OI windows mapping
39
+ */
40
+ const convertOiWindows = (windowIds, contractWindows) => {
41
+ if (windowIds.length !== contractWindows.length) {
42
+ throw new Error("Window IDs and data arrays must have the same length");
43
+ }
44
+ const windows = {};
45
+ windowIds.forEach((id, index) => {
46
+ windows[id] = (0, exports.convertOiWindow)(contractWindows[index]);
47
+ });
48
+ return windows;
49
+ };
50
+ exports.convertOiWindows = convertOiWindows;
51
+ /**
52
+ * @dev Batch converter for multiple OI windows settings
53
+ * @param contractDataArray Array of contract OiWindowsSettings
54
+ * @returns Array of normalized OI windows settings
55
+ */
56
+ const convertOiWindowsSettingsArray = (contractDataArray) => {
57
+ return contractDataArray.map(exports.convertOiWindowsSettings);
58
+ };
59
+ exports.convertOiWindowsSettingsArray = convertOiWindowsSettingsArray;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * @dev Cumulative volume price impact calculations
3
+ * @dev Mirrors contract's getTradeCumulVolPriceImpactP functionality
4
+ */
5
+ import { LiquidationParams, OiWindows, OiWindowsSettings, PairDepth, PairFactor, UserPriceImpact } from "../../types";
6
+ import { ContractsVersion } from "../../../contracts/types";
7
+ export type CumulVolContext = {
8
+ isOpen?: boolean;
9
+ isPnlPositive?: boolean;
10
+ createdBlock?: number;
11
+ liquidationParams?: LiquidationParams | undefined;
12
+ currentBlock?: number | undefined;
13
+ contractsVersion?: ContractsVersion | undefined;
14
+ protectionCloseFactorWhitelist?: boolean;
15
+ pairDepth?: PairDepth | undefined;
16
+ oiWindowsSettings?: OiWindowsSettings | undefined;
17
+ oiWindows?: OiWindows | undefined;
18
+ userPriceImpact?: UserPriceImpact | undefined;
19
+ collateralPriceUsd?: number;
20
+ } & Partial<PairFactor>;
21
+ /**
22
+ * @dev Gets the protection close factor with user multiplier
23
+ * @param context Cumulative volume context
24
+ * @returns Protection close factor (1 = 100%)
25
+ */
26
+ export declare const getProtectionCloseFactor: (context: CumulVolContext | undefined) => number;
27
+ /**
28
+ * @dev Checks if protection close factor is active
29
+ * @param context Cumulative volume context
30
+ * @returns True if protection close factor should be applied
31
+ */
32
+ export declare const isProtectionCloseFactorActive: (context: CumulVolContext | undefined) => boolean | undefined;
33
+ /**
34
+ * @dev Gets the cumulative factor for price impact calculation
35
+ * @param context Cumulative volume context
36
+ * @returns Cumulative factor (default 1)
37
+ */
38
+ export declare const getCumulativeFactor: (context: CumulVolContext | undefined) => number;
39
+ /**
40
+ * @dev Gets the legacy factor for v9.2 compatibility
41
+ * @param context Cumulative volume context
42
+ * @returns 1 for pre-v9.2, 2 for v9.2+
43
+ */
44
+ export declare const getLegacyFactor: (context: CumulVolContext | undefined) => number;
45
+ /**
46
+ * @dev Calculates cumulative volume price impact percentage
47
+ * @dev Mirrors contract's getTradeCumulVolPriceImpactP function
48
+ * @param trader Trader address
49
+ * @param pairIndex Trading pair index
50
+ * @param long True for long, false for short
51
+ * @param tradeOpenInterestUsd Position size in USD
52
+ * @param isPnlPositive Whether PnL is positive (only relevant when closing)
53
+ * @param open True for opening, false for closing
54
+ * @param lastPosIncreaseBlock Last block when position was increased (only relevant when closing)
55
+ * @param context Additional context with depths, OI data, and factors
56
+ * @returns Cumulative volume price impact percentage (not including spread)
57
+ */
58
+ export declare const getTradeCumulVolPriceImpactP: (trader: string, pairIndex: number, long: boolean, tradeOpenInterestUsd: number, isPnlPositive: boolean, open: boolean, lastPosIncreaseBlock: number, context: CumulVolContext) => number;
59
+ /**
60
+ * @dev Gets the fixed spread percentage with direction
61
+ * @dev Mirrors contract's getFixedSpreadP function
62
+ * @param spreadP Total spread percentage (includes base + user spread)
63
+ * @param long True for long position
64
+ * @param open True for opening, false for closing
65
+ * @returns Signed spread percentage (positive or negative based on direction)
66
+ */
67
+ export declare const getFixedSpreadP: (spreadP: number, long: boolean, open: boolean) => number;
68
+ /**
69
+ * @dev Gets the base spread percentage
70
+ * @param pairSpreadP Pair spread percentage
71
+ * @param isLiquidation True if liquidation
72
+ * @param liquidationParams Liquidation parameters
73
+ * @param userPriceImpact User-specific price impact settings
74
+ * @returns Base spread percentage
75
+ * @todo Review if this function still makes sense or should use getFixedSpreadP pattern
76
+ * Currently it may double-count user fixed spread if pairSpreadP already includes it
77
+ */
78
+ export declare const getSpreadP: (pairSpreadP: number | undefined, isLiquidation?: boolean | undefined, liquidationParams?: LiquidationParams | undefined, userPriceImpact?: UserPriceImpact | undefined) => number;
79
+ /**
80
+ * @dev Gets spread with cumulative volume price impact
81
+ * @dev This combines base spread + cumulative volume impact
82
+ * @param pairSpreadP Base pair spread percentage
83
+ * @param buy True for long, false for short
84
+ * @param collateral Collateral amount
85
+ * @param leverage Position leverage
86
+ * @param pairDepth 1% depth values for the pair
87
+ * @param oiWindowsSettings OI windows configuration
88
+ * @param oiWindows Current OI windows data
89
+ * @param context Additional context for the calculation
90
+ * @returns Total spread + cumulative volume price impact percentage
91
+ */
92
+ export declare const getSpreadWithCumulVolPriceImpactP: (pairSpreadP: number, buy: boolean, collateral: number, leverage: number, pairDepth: PairDepth | undefined, oiWindowsSettings?: OiWindowsSettings | undefined, oiWindows?: OiWindows | undefined, context?: CumulVolContext | undefined) => number;
93
+ /**
94
+ * @dev Convenience function for calculating cumulative volume price impact
95
+ * @dev Uses collateral and leverage instead of USD position size
96
+ * @param buy True for long, false for short
97
+ * @param collateral Collateral amount
98
+ * @param leverage Position leverage
99
+ * @param open True for opening, false for closing
100
+ * @param context Full context including depths, OI data, and collateral price
101
+ * @returns Cumulative volume price impact percentage
102
+ */
103
+ export declare const getCumulVolPriceImpact: (buy: boolean, collateral: number, leverage: number, open: boolean, context: CumulVolContext & {
104
+ collateralPriceUsd: number;
105
+ }) => number;
106
+ export declare const getSpreadWithPriceImpactP: (pairSpreadP: number, buy: boolean, collateral: number, leverage: number, pairDepth: PairDepth | undefined, oiWindowsSettings?: OiWindowsSettings | undefined, oiWindows?: OiWindows | undefined, context?: CumulVolContext | undefined) => number;
107
+ export { convertOiWindowsSettings, convertOiWindow, convertOiWindows, convertOiWindowsSettingsArray, } from "./converter";
108
+ export { buildCumulVolContext } from "./builder";