@gainsnetwork/sdk 1.0.6-rc3 → 1.1.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 (147) hide show
  1. package/lib/backend/globalTrades/index.js +10 -10
  2. package/lib/backend/tradingVariables/backend.types.d.ts +11 -4
  3. package/lib/backend/tradingVariables/converter.d.ts +7 -3
  4. package/lib/backend/tradingVariables/converter.js +70 -63
  5. package/lib/backend/tradingVariables/index.js +11 -7
  6. package/lib/backend/tradingVariables/types.d.ts +4 -2
  7. package/lib/contracts/addresses.js +1 -4
  8. package/lib/contracts/index.d.ts +1 -1
  9. package/lib/contracts/index.js +3 -3
  10. package/lib/contracts/types/generated/GFarmTradingStorageV5.d.ts +1911 -0
  11. package/lib/contracts/types/generated/GFarmTradingStorageV5.js +2 -0
  12. package/lib/contracts/types/generated/GNSBorrowingFees.d.ts +1067 -0
  13. package/lib/contracts/types/generated/GNSBorrowingFees.js +2 -0
  14. package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.d.ts +979 -0
  15. package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.js +2 -0
  16. package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.d.ts +1058 -0
  17. package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.js +2 -0
  18. package/lib/contracts/types/generated/GNSMultiCollatDiamond.d.ts +223 -40
  19. package/lib/contracts/types/generated/GNSNftRewardsV6.d.ts +533 -0
  20. package/lib/contracts/types/generated/GNSNftRewardsV6.js +2 -0
  21. package/lib/contracts/types/generated/GNSNftRewardsV6_3_1.d.ts +613 -0
  22. package/lib/contracts/types/generated/GNSNftRewardsV6_3_1.js +2 -0
  23. package/lib/contracts/types/generated/GNSPairInfosV6_1.d.ts +911 -0
  24. package/lib/contracts/types/generated/GNSPairInfosV6_1.js +2 -0
  25. package/lib/contracts/types/generated/GNSPairsStorageV6.d.ts +660 -0
  26. package/lib/contracts/types/generated/GNSPairsStorageV6.js +2 -0
  27. package/lib/contracts/types/generated/GNSTrading.d.ts +758 -0
  28. package/lib/contracts/types/generated/GNSTrading.js +2 -0
  29. package/lib/contracts/types/generated/GNSTradingCallbacks.d.ts +875 -0
  30. package/lib/contracts/types/generated/GNSTradingCallbacks.js +2 -0
  31. package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.d.ts +806 -0
  32. package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.js +2 -0
  33. package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.d.ts +821 -0
  34. package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.js +2 -0
  35. package/lib/contracts/types/generated/GNSTradingStorage.d.ts +1387 -0
  36. package/lib/contracts/types/generated/GNSTradingStorage.js +2 -0
  37. package/lib/contracts/types/generated/GTokenV6_3_2.d.ts +1838 -0
  38. package/lib/contracts/types/generated/GTokenV6_3_2.js +2 -0
  39. package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.d.ts +83 -0
  40. package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.js +2691 -0
  41. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.d.ts +88 -0
  42. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.js +1654 -0
  43. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.d.ts +113 -0
  44. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.js +1742 -0
  45. package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.d.ts +124 -0
  46. package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.js +1784 -0
  47. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.d.ts +10 -2
  48. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.js +317 -36
  49. package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.d.ts +100 -0
  50. package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.js +1116 -0
  51. package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.d.ts +100 -0
  52. package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.js +1003 -0
  53. package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.d.ts +98 -0
  54. package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.js +1485 -0
  55. package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.d.ts +117 -0
  56. package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.js +1265 -0
  57. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.d.ts +82 -0
  58. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.js +1273 -0
  59. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.d.ts +82 -0
  60. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.js +1326 -0
  61. package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.d.ts +113 -0
  62. package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.js +1428 -0
  63. package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.d.ts +96 -0
  64. package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.js +2241 -0
  65. package/lib/contracts/types/generated/factories/GNSTrading__factory.d.ts +95 -0
  66. package/lib/contracts/types/generated/factories/GNSTrading__factory.js +1071 -0
  67. package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.d.ts +110 -0
  68. package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.js +2682 -0
  69. package/lib/contracts/utils/borrowingFees.js +20 -9
  70. package/lib/contracts/utils/openTrades.js +20 -11
  71. package/lib/contracts/utils/pairs.d.ts +13 -2
  72. package/lib/contracts/utils/pairs.js +89 -21
  73. package/lib/index.d.ts +1 -0
  74. package/lib/index.js +1 -0
  75. package/lib/markets/forex.js +1 -1
  76. package/lib/markets/leverage/builder.js +2 -2
  77. package/lib/markets/oi/fetcher.d.ts +58 -0
  78. package/lib/markets/oi/fetcher.js +181 -0
  79. package/lib/markets/oi/validation.d.ts +80 -0
  80. package/lib/markets/oi/validation.js +172 -0
  81. package/lib/markets/price/index.d.ts +0 -1
  82. package/lib/markets/price/index.js +0 -1
  83. package/lib/markets/price/signedPrices.d.ts +7 -0
  84. package/lib/markets/price/signedPrices.js +55 -2
  85. package/lib/markets/price/types.d.ts +0 -27
  86. package/lib/pricing/depthBands/converter.d.ts +65 -0
  87. package/lib/pricing/depthBands/converter.js +155 -0
  88. package/lib/pricing/depthBands/decoder.d.ts +32 -0
  89. package/lib/pricing/depthBands/decoder.js +109 -0
  90. package/lib/pricing/depthBands/encoder.d.ts +19 -0
  91. package/lib/pricing/depthBands/encoder.js +105 -0
  92. package/lib/pricing/depthBands/index.d.ts +8 -0
  93. package/lib/pricing/depthBands/index.js +26 -0
  94. package/lib/pricing/depthBands/types.d.ts +49 -0
  95. package/lib/pricing/depthBands/types.js +10 -0
  96. package/lib/pricing/depthBands/validator.d.ts +22 -0
  97. package/lib/pricing/depthBands/validator.js +113 -0
  98. package/lib/pricing/depthBands.d.ts +39 -0
  99. package/lib/pricing/depthBands.js +92 -0
  100. package/lib/pricing/index.d.ts +4 -0
  101. package/lib/pricing/index.js +20 -0
  102. package/lib/trade/effectiveLeverage/builder.d.ts +23 -0
  103. package/lib/trade/effectiveLeverage/builder.js +30 -0
  104. package/lib/trade/fees/borrowing/builder.js +3 -2
  105. package/lib/trade/fees/borrowing/converter.js +1 -5
  106. package/lib/trade/fees/borrowing/index.js +5 -5
  107. package/lib/trade/fees/borrowingV2/builder.js +4 -3
  108. package/lib/trade/fees/borrowingV2/converter.js +1 -1
  109. package/lib/trade/fees/borrowingV2/fetcher.d.ts +0 -1
  110. package/lib/trade/fees/borrowingV2/fetcher.js +32 -26
  111. package/lib/trade/fees/borrowingV2/index.js +3 -3
  112. package/lib/trade/fees/converter.js +22 -22
  113. package/lib/trade/fees/fundingFees/builder.js +7 -6
  114. package/lib/trade/fees/fundingFees/converter.js +1 -1
  115. package/lib/trade/fees/fundingFees/fetcher.js +25 -16
  116. package/lib/trade/fees/fundingFees/index.js +3 -2
  117. package/lib/trade/fees/holdingFees/index.d.ts +46 -0
  118. package/lib/trade/fees/holdingFees/index.js +105 -0
  119. package/lib/trade/fees/holdingFees/types.d.ts +23 -0
  120. package/lib/trade/fees/holdingFees/types.js +5 -0
  121. package/lib/trade/fees/tiers/index.js +2 -1
  122. package/lib/trade/fees/trading/holdingFees.d.ts +28 -0
  123. package/lib/trade/fees/trading/holdingFees.js +66 -0
  124. package/lib/trade/fees/trading/holdingFeesStructured.d.ts +28 -0
  125. package/lib/trade/fees/trading/holdingFeesStructured.js +66 -0
  126. package/lib/trade/fees/trading/index.js +3 -5
  127. package/lib/trade/liquidation/builder.js +3 -6
  128. package/lib/trade/liquidation/index.js +6 -4
  129. package/lib/trade/oiWindows.js +2 -1
  130. package/lib/trade/pnl/builder.js +2 -1
  131. package/lib/trade/pnl/converter.js +1 -1
  132. package/lib/trade/pnl/index.js +7 -4
  133. package/lib/trade/priceImpact/close/builder.js +2 -1
  134. package/lib/trade/priceImpact/close/index.js +1 -4
  135. package/lib/trade/priceImpact/cumulVol/builder.js +11 -18
  136. package/lib/trade/priceImpact/cumulVol/converter.d.ts +63 -0
  137. package/lib/trade/priceImpact/cumulVol/converter.js +97 -1
  138. package/lib/trade/priceImpact/cumulVol/index.d.ts +3 -0
  139. package/lib/trade/priceImpact/cumulVol/index.js +123 -25
  140. package/lib/trade/priceImpact/cumulVol/types.d.ts +11 -0
  141. package/lib/trade/priceImpact/cumulVol/types.js +2 -0
  142. package/lib/trade/priceImpact/open/builder.js +2 -1
  143. package/lib/trade/priceImpact/open/index.js +1 -4
  144. package/lib/trade/priceImpact/skew/builder.js +3 -2
  145. package/lib/trade/priceImpact/skew/converter.js +1 -1
  146. package/lib/trade/priceImpact/skew/fetcher.js +33 -24
  147. package/package.json +2 -2
@@ -10,14 +10,16 @@ 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;
13
14
  const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
14
15
  if (!collateral) {
15
16
  return undefined;
16
17
  }
17
18
  // Get pair-specific data from global variables
18
- const pairDepth = globalTradingVariables.pairDepths?.[pairIndex];
19
- const pairFactor = globalTradingVariables.pairFactors?.[pairIndex];
20
- const oiWindows = globalTradingVariables.oiWindows?.[pairIndex];
19
+ // TODO: Update to use pairDepthBands for v10.2
20
+ const pairDepth = undefined; // globalTradingVariables.pairDepths?.[pairIndex];
21
+ const pairFactor = (_a = globalTradingVariables.pairFactors) === null || _a === void 0 ? void 0 : _a[pairIndex];
22
+ const oiWindows = (_b = globalTradingVariables.oiWindows) === null || _b === void 0 ? void 0 : _b[pairIndex];
21
23
  // Get OI windows settings (same for all pairs)
22
24
  // OI windows settings from global trading variables are already in SDK format
23
25
  const oiWindowsSettings = globalTradingVariables.oiWindowsSettings;
@@ -25,27 +27,18 @@ const buildCumulVolContext = (globalTradingVariables, collateralIndex, pairIndex
25
27
  const userPriceImpact = additionalParams.userPriceImpact;
26
28
  const protectionCloseFactorWhitelist = additionalParams.protectionCloseFactorWhitelist;
27
29
  // Get liquidation params - check both pair and group level
28
- const liquidationParams = globalTradingVariables.liquidationParams?.pairs?.[pairIndex] ||
29
- globalTradingVariables.liquidationParams?.groups?.[0]; // fallback to first group
30
- return {
30
+ const liquidationParams = ((_d = (_c = globalTradingVariables.liquidationParams) === null || _c === void 0 ? void 0 : _c.pairs) === null || _d === void 0 ? void 0 : _d[pairIndex]) ||
31
+ ((_f = (_e = globalTradingVariables.liquidationParams) === null || _e === void 0 ? void 0 : _e.groups) === null || _f === void 0 ? void 0 : _f[0]); // fallback to first group
32
+ return Object.assign({
31
33
  // Trade state
32
- isOpen: additionalParams.isOpen,
33
- isPnlPositive: additionalParams.isPnlPositive,
34
- createdBlock: additionalParams.createdBlock,
34
+ isOpen: additionalParams.isOpen, isPnlPositive: additionalParams.isPnlPositive, createdBlock: additionalParams.createdBlock,
35
35
  // Protection factors
36
- liquidationParams,
37
- currentBlock: additionalParams.currentBlock,
38
- contractsVersion: additionalParams.contractsVersion,
39
- protectionCloseFactorWhitelist,
36
+ liquidationParams, currentBlock: additionalParams.currentBlock, contractsVersion: additionalParams.contractsVersion, protectionCloseFactorWhitelist,
40
37
  // Price impact data
41
38
  pairDepth,
42
39
  oiWindowsSettings,
43
40
  oiWindows,
44
41
  // User/collateral specific
45
- userPriceImpact,
46
- collateralPriceUsd: collateral.prices?.collateralPriceUsd || 1,
47
- // Pair factors (spread across the context)
48
- ...pairFactor,
49
- };
42
+ userPriceImpact, collateralPriceUsd: ((_g = collateral.prices) === null || _g === void 0 ? void 0 : _g.collateralPriceUsd) || 1 }, pairFactor);
50
43
  };
51
44
  exports.buildCumulVolContext = buildCumulVolContext;
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { IPriceImpact } from "../../../contracts/types/generated/GNSMultiCollatDiamond";
6
6
  import { OiWindowsSettings, OiWindow, OiWindows } from "../../types";
7
+ import { DepthBands, PairDepthBands, DepthBandsMapping } from "./types";
7
8
  /**
8
9
  * @dev Converts contract OI windows settings to SDK format
9
10
  * @param contractData Contract OiWindowsSettings struct
@@ -29,3 +30,65 @@ export declare const convertOiWindows: (windowIds: string[], contractWindows: IP
29
30
  * @returns Array of normalized OI windows settings
30
31
  */
31
32
  export declare const convertOiWindowsSettingsArray: (contractDataArray: IPriceImpact.OiWindowsSettingsStructOutput[]) => OiWindowsSettings[];
33
+ /**
34
+ * @dev Converts decoded depth bands from contract to SDK format
35
+ * @param totalDepthUsd Total depth in USD (already decoded from contract)
36
+ * @param bandsBps Array of 30 band percentages in basis points from contract
37
+ * @returns Normalized depth bands with bands in 0-1 range
38
+ */
39
+ export declare const convertDepthBands: (totalDepthUsd: number, bandsBps: number[]) => DepthBands;
40
+ /**
41
+ * @dev Converts decoded pair depth bands from contract to SDK format
42
+ * @param aboveDepth Decoded above depth bands from getPairDepthBandsDecoded
43
+ * @param belowDepth Decoded below depth bands from getPairDepthBandsDecoded
44
+ * @returns Normalized pair depth bands with above/below
45
+ */
46
+ export declare const convertPairDepthBands: (aboveDepth: {
47
+ totalDepthUsd: number;
48
+ bands: number[];
49
+ } | undefined, belowDepth: {
50
+ totalDepthUsd: number;
51
+ bands: number[];
52
+ } | undefined) => PairDepthBands;
53
+ /**
54
+ * @dev Converts decoded depth bands mapping from contract to SDK format
55
+ * @param bandsBps Array of 30 band offset values in basis points from getDepthBandsMappingDecoded
56
+ * @returns Normalized depth bands mapping with offset values in 0-1 range
57
+ */
58
+ export declare const convertDepthBandsMapping: (bandsBps: number[]) => DepthBandsMapping;
59
+ /**
60
+ * @dev Validates depth bands have correct number of bands
61
+ * @param depthBands Depth bands to validate
62
+ * @returns True if valid (30 bands)
63
+ */
64
+ export declare const validateDepthBands: (depthBands: DepthBands) => boolean;
65
+ /**
66
+ * @dev Validates depth bands mapping has correct number of bands
67
+ * @param mapping Depth bands mapping to validate
68
+ * @returns True if valid (30 bands)
69
+ */
70
+ export declare const validateDepthBandsMapping: (mapping: DepthBandsMapping) => boolean;
71
+ /**
72
+ * @dev Alternative converter for decoded pair depth bands from contract
73
+ * @param contractData Decoded pair depth bands from getPairDepthBandsDecoded
74
+ * @returns Normalized pair depth bands
75
+ */
76
+ export declare const convertPairDepthBandsDecoded: (contractData: {
77
+ above: {
78
+ totalDepthUsd: number;
79
+ bands: number[];
80
+ };
81
+ below: {
82
+ totalDepthUsd: number;
83
+ bands: number[];
84
+ };
85
+ }) => PairDepthBands;
86
+ /**
87
+ * @dev Alternative converter for raw slot-based pair depth bands (if needed for legacy)
88
+ * @param aboveSlot1 First slot for above bands
89
+ * @param aboveSlot2 Second slot for above bands
90
+ * @param belowSlot1 First slot for below bands
91
+ * @param belowSlot2 Second slot for below bands
92
+ * @returns Normalized pair depth bands
93
+ */
94
+ export declare const convertPairDepthBandsFromSlots: (aboveSlot1: bigint, aboveSlot2: bigint, belowSlot1: bigint, belowSlot2: bigint) => PairDepthBands;
@@ -4,7 +4,8 @@
4
4
  * @dev All BigNumber values are normalized to floats with appropriate precision
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.convertOiWindowsSettingsArray = exports.convertOiWindows = exports.convertOiWindow = exports.convertOiWindowsSettings = void 0;
7
+ exports.convertPairDepthBandsFromSlots = exports.convertPairDepthBandsDecoded = exports.validateDepthBandsMapping = exports.validateDepthBands = exports.convertDepthBandsMapping = exports.convertPairDepthBands = exports.convertDepthBands = exports.convertOiWindowsSettingsArray = exports.convertOiWindows = exports.convertOiWindow = exports.convertOiWindowsSettings = void 0;
8
+ const depthBands_1 = require("../../../pricing/depthBands");
8
9
  /**
9
10
  * @dev Converts contract OI windows settings to SDK format
10
11
  * @param contractData Contract OiWindowsSettings struct
@@ -57,3 +58,98 @@ const convertOiWindowsSettingsArray = (contractDataArray) => {
57
58
  return contractDataArray.map(exports.convertOiWindowsSettings);
58
59
  };
59
60
  exports.convertOiWindowsSettingsArray = convertOiWindowsSettingsArray;
61
+ /**
62
+ * @dev Converts decoded depth bands from contract to SDK format
63
+ * @param totalDepthUsd Total depth in USD (already decoded from contract)
64
+ * @param bandsBps Array of 30 band percentages in basis points from contract
65
+ * @returns Normalized depth bands with bands in 0-1 range
66
+ */
67
+ const convertDepthBands = (totalDepthUsd, bandsBps) => {
68
+ // Convert bands from basis points to 0-1 range
69
+ const bands = bandsBps.map(bps => bps / 10000);
70
+ return {
71
+ totalDepthUsd,
72
+ bands,
73
+ };
74
+ };
75
+ exports.convertDepthBands = convertDepthBands;
76
+ /**
77
+ * @dev Converts decoded pair depth bands from contract to SDK format
78
+ * @param aboveDepth Decoded above depth bands from getPairDepthBandsDecoded
79
+ * @param belowDepth Decoded below depth bands from getPairDepthBandsDecoded
80
+ * @returns Normalized pair depth bands with above/below
81
+ */
82
+ const convertPairDepthBands = (aboveDepth, belowDepth) => {
83
+ // Convert above bands if configured
84
+ const above = aboveDepth && aboveDepth.totalDepthUsd > 0
85
+ ? (0, exports.convertDepthBands)(aboveDepth.totalDepthUsd, aboveDepth.bands)
86
+ : undefined;
87
+ // Convert below bands if configured
88
+ const below = belowDepth && belowDepth.totalDepthUsd > 0
89
+ ? (0, exports.convertDepthBands)(belowDepth.totalDepthUsd, belowDepth.bands)
90
+ : undefined;
91
+ return {
92
+ above,
93
+ below,
94
+ };
95
+ };
96
+ exports.convertPairDepthBands = convertPairDepthBands;
97
+ /**
98
+ * @dev Converts decoded depth bands mapping from contract to SDK format
99
+ * @param bandsBps Array of 30 band offset values in basis points from getDepthBandsMappingDecoded
100
+ * @returns Normalized depth bands mapping with offset values in 0-1 range
101
+ */
102
+ const convertDepthBandsMapping = (bandsBps) => {
103
+ // Convert bands from basis points to 0-1 range
104
+ const bands = bandsBps.map(bps => bps / 10000);
105
+ return {
106
+ bands,
107
+ };
108
+ };
109
+ exports.convertDepthBandsMapping = convertDepthBandsMapping;
110
+ /**
111
+ * @dev Validates depth bands have correct number of bands
112
+ * @param depthBands Depth bands to validate
113
+ * @returns True if valid (30 bands)
114
+ */
115
+ const validateDepthBands = (depthBands) => {
116
+ return depthBands.bands.length === 30;
117
+ };
118
+ exports.validateDepthBands = validateDepthBands;
119
+ /**
120
+ * @dev Validates depth bands mapping has correct number of bands
121
+ * @param mapping Depth bands mapping to validate
122
+ * @returns True if valid (30 bands)
123
+ */
124
+ const validateDepthBandsMapping = (mapping) => {
125
+ return mapping.bands.length === 30;
126
+ };
127
+ exports.validateDepthBandsMapping = validateDepthBandsMapping;
128
+ /**
129
+ * @dev Alternative converter for decoded pair depth bands from contract
130
+ * @param contractData Decoded pair depth bands from getPairDepthBandsDecoded
131
+ * @returns Normalized pair depth bands
132
+ */
133
+ const convertPairDepthBandsDecoded = (contractData) => {
134
+ return (0, exports.convertPairDepthBands)(contractData.above, contractData.below);
135
+ };
136
+ exports.convertPairDepthBandsDecoded = convertPairDepthBandsDecoded;
137
+ /**
138
+ * @dev Alternative converter for raw slot-based pair depth bands (if needed for legacy)
139
+ * @param aboveSlot1 First slot for above bands
140
+ * @param aboveSlot2 Second slot for above bands
141
+ * @param belowSlot1 First slot for below bands
142
+ * @param belowSlot2 Second slot for below bands
143
+ * @returns Normalized pair depth bands
144
+ */
145
+ const convertPairDepthBandsFromSlots = (aboveSlot1, aboveSlot2, belowSlot1, belowSlot2) => {
146
+ // Use the decoding functions from pricing module if raw slots are provided
147
+ const above = aboveSlot1 !== BigInt(0) || aboveSlot2 !== BigInt(0)
148
+ ? (0, depthBands_1.decodeDepthBands)(aboveSlot1, aboveSlot2)
149
+ : undefined;
150
+ const below = belowSlot1 !== BigInt(0) || belowSlot2 !== BigInt(0)
151
+ ? (0, depthBands_1.decodeDepthBands)(belowSlot1, belowSlot2)
152
+ : undefined;
153
+ return (0, exports.convertPairDepthBands)(above, below);
154
+ };
155
+ exports.convertPairDepthBandsFromSlots = convertPairDepthBandsFromSlots;
@@ -2,6 +2,7 @@
2
2
  * @dev Cumulative volume price impact calculations
3
3
  * @dev Mirrors contract's getTradeCumulVolPriceImpactP functionality
4
4
  */
5
+ import { PairDepthBands, DepthBandsMapping } from "./types";
5
6
  import { LiquidationParams, OiWindows, OiWindowsSettings, PairDepth, PairFactor, UserPriceImpact } from "../../types";
6
7
  import { ContractsVersion } from "../../../contracts/types";
7
8
  export type CumulVolContext = {
@@ -15,6 +16,8 @@ export type CumulVolContext = {
15
16
  pairDepth?: PairDepth | undefined;
16
17
  oiWindowsSettings?: OiWindowsSettings | undefined;
17
18
  oiWindows?: OiWindows | undefined;
19
+ pairDepthBands?: PairDepthBands | undefined;
20
+ depthBandsMapping?: DepthBandsMapping | undefined;
18
21
  userPriceImpact?: UserPriceImpact | undefined;
19
22
  collateralPriceUsd?: number;
20
23
  } & Partial<PairFactor>;
@@ -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,9 +71,92 @@ 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;
77
+ /**
78
+ * @dev Mirrors contract's _calculateDepthBandsPriceImpact function
79
+ * @param tradeSizeUsd Trade size in USD (always positive here)
80
+ * @param depthBandParams Depth band parameters
81
+ * @returns Price impact percentage
82
+ */
83
+ const _calculateDepthBandsPriceImpact = (tradeSizeUsd, depthBandParams) => {
84
+ const totalDepthUsd = depthBandParams.pairSlot1.totalDepthUsd;
85
+ if (totalDepthUsd === 0 || tradeSizeUsd === 0)
86
+ return 0;
87
+ let remainingSizeUsd = tradeSizeUsd;
88
+ let totalWeightedPriceImpactP = 0;
89
+ let prevBandDepthUsd = 0;
90
+ let topOfPrevBandOffsetPpm = 0;
91
+ for (let i = 0; i < 30 && remainingSizeUsd !== 0; i++) {
92
+ const bandLiquidityPercentageBps = depthBandParams.pairSlot1.bands[i]; // Already in 0-1 format
93
+ const topOfBandOffsetPpm = depthBandParams.mappingSlot1.bands[i]; // Already in 0-1 format
94
+ const bandDepthUsd = bandLiquidityPercentageBps * totalDepthUsd;
95
+ // Skip if band has same depth as previous (would cause division by zero)
96
+ if (bandDepthUsd <= prevBandDepthUsd) {
97
+ prevBandDepthUsd = bandDepthUsd;
98
+ topOfPrevBandOffsetPpm = topOfBandOffsetPpm;
99
+ continue;
100
+ }
101
+ // Since bandDepthUsd represents liquidity from mid price to top of band, we need to subtract previous band depth
102
+ const bandAvailableDepthUsd = bandDepthUsd - prevBandDepthUsd;
103
+ let depthConsumedUsd;
104
+ // At 100% band always consume all remaining size, even if more than band available depth
105
+ if (bandLiquidityPercentageBps === 1 ||
106
+ remainingSizeUsd <= bandAvailableDepthUsd) {
107
+ depthConsumedUsd = remainingSizeUsd;
108
+ remainingSizeUsd = 0;
109
+ }
110
+ else {
111
+ // Normal case: consume entire band and continue to next
112
+ depthConsumedUsd = bandAvailableDepthUsd;
113
+ remainingSizeUsd -= bandAvailableDepthUsd;
114
+ }
115
+ // Calculate impact contribution from this band using trapezoidal rule
116
+ // Low = previous band's price offset, High = current band's price offset
117
+ const lowOffsetP = topOfPrevBandOffsetPpm;
118
+ const offsetRangeP = topOfBandOffsetPpm - topOfPrevBandOffsetPpm;
119
+ // Calculate average impact using trapezoidal rule: low + (range * fraction / 2)
120
+ const avgImpactP = lowOffsetP +
121
+ (offsetRangeP * depthConsumedUsd) / bandAvailableDepthUsd / 2;
122
+ totalWeightedPriceImpactP += avgImpactP * depthConsumedUsd;
123
+ // Update previous values for next iteration
124
+ topOfPrevBandOffsetPpm = topOfBandOffsetPpm;
125
+ prevBandDepthUsd = bandDepthUsd;
126
+ }
127
+ return totalWeightedPriceImpactP / tradeSizeUsd;
128
+ };
129
+ /**
130
+ * @dev Mirrors contract's _getDepthBandsPriceImpactP function
131
+ * @param cumulativeVolumeUsd Cumulative volume in USD (can be negative)
132
+ * @param tradeSizeUsd Trade size in USD (can be negative)
133
+ * @param depthBandParams Depth band parameters (contains both pair bands and global mapping)
134
+ * @param priceImpactFactor Price impact factor (protection close factor)
135
+ * @param cumulativeFactor Cumulative factor for volume impact
136
+ * @returns Price impact percentage (can be negative)
137
+ */
138
+ const _getDepthBandsPriceImpactP = (cumulativeVolumeUsd, tradeSizeUsd, depthBandParams, priceImpactFactor, cumulativeFactor) => {
139
+ // Check for opposite signs (would revert in contract)
140
+ if ((cumulativeVolumeUsd > 0 && tradeSizeUsd < 0) ||
141
+ (cumulativeVolumeUsd < 0 && tradeSizeUsd > 0)) {
142
+ throw new Error("Wrong params: cumulative volume and trade size have opposite signs");
143
+ }
144
+ const effectiveCumulativeVolumeUsd = cumulativeVolumeUsd * cumulativeFactor;
145
+ const totalSizeLookupUsd = effectiveCumulativeVolumeUsd + tradeSizeUsd;
146
+ const isNegative = totalSizeLookupUsd < 0;
147
+ const effectiveCumulativeVolumeUsdUint = isNegative
148
+ ? -effectiveCumulativeVolumeUsd
149
+ : effectiveCumulativeVolumeUsd;
150
+ const totalSizeLookupUsdUint = isNegative
151
+ ? -totalSizeLookupUsd
152
+ : totalSizeLookupUsd;
153
+ const cumulativeVolPriceImpactP = _calculateDepthBandsPriceImpact(effectiveCumulativeVolumeUsdUint, depthBandParams);
154
+ const totalSizePriceImpactP = _calculateDepthBandsPriceImpact(totalSizeLookupUsdUint, depthBandParams);
155
+ const unscaledPriceImpactP = cumulativeVolPriceImpactP +
156
+ (totalSizePriceImpactP - cumulativeVolPriceImpactP) / 2;
157
+ const scaledPriceImpactP = unscaledPriceImpactP * priceImpactFactor;
158
+ return isNegative ? -scaledPriceImpactP : scaledPriceImpactP;
159
+ };
76
160
  /**
77
161
  * @dev Calculates cumulative volume price impact percentage
78
162
  * @dev Mirrors contract's getTradeCumulVolPriceImpactP function
@@ -87,34 +171,50 @@ exports.getLegacyFactor = getLegacyFactor;
87
171
  * @returns Cumulative volume price impact percentage (not including spread)
88
172
  */
89
173
  const getTradeCumulVolPriceImpactP = (trader, pairIndex, long, tradeOpenInterestUsd, isPnlPositive, open, lastPosIncreaseBlock, context) => {
174
+ var _a, _b;
90
175
  // Update context with passed parameters
91
- const updatedContext = {
92
- ...context,
93
- isOpen: open,
94
- isPnlPositive: isPnlPositive,
95
- createdBlock: context.createdBlock || lastPosIncreaseBlock,
96
- };
176
+ const updatedContext = Object.assign(Object.assign({}, context), { isOpen: open, isPnlPositive: isPnlPositive, createdBlock: context.createdBlock || lastPosIncreaseBlock });
97
177
  if (
98
178
  // No price impact when closing pre-v9.2 trades
99
- (!open && context?.contractsVersion === types_1.ContractsVersion.BEFORE_V9_2) ||
179
+ (!open && (context === null || context === void 0 ? void 0 : context.contractsVersion) === types_1.ContractsVersion.BEFORE_V9_2) ||
100
180
  // No price impact for opens when `pair.exemptOnOpen` is true
101
- (open && context?.exemptOnOpen === true) ||
181
+ (open && (context === null || context === void 0 ? void 0 : context.exemptOnOpen) === true) ||
102
182
  // No price impact for closes after `protectionCloseFactor` has expired
103
183
  // when `pair.exemptAfterProtectionCloseFactor` is true
104
184
  (!open &&
105
- context?.exemptAfterProtectionCloseFactor === true &&
185
+ (context === null || context === void 0 ? void 0 : context.exemptAfterProtectionCloseFactor) === true &&
106
186
  (0, exports.isProtectionCloseFactorActive)(updatedContext) !== true)) {
107
187
  return 0;
108
188
  }
109
- // Calculate trade skew direction (matches Solidity logic)
110
189
  const tradePositiveSkew = (long && open) || (!long && !open);
111
190
  const tradeSkewMultiplier = tradePositiveSkew ? 1 : -1;
112
- // Select depth based on trade direction
113
- // For positive skew (long open or short close), use depth above
114
- // For negative skew (short open or long close), use depth below
191
+ if (context.pairDepthBands && context.depthBandsMapping) {
192
+ // Select depth bands based on trade direction
193
+ const depthBands = tradePositiveSkew
194
+ ? context.pairDepthBands.above
195
+ : context.pairDepthBands.below;
196
+ if (depthBands && depthBands.totalDepthUsd > 0) {
197
+ // Get active OI for cumulative volume calculation
198
+ let activeOi = 0;
199
+ if (context.oiWindowsSettings !== undefined) {
200
+ activeOi =
201
+ (0, oiWindows_1.getActiveOi)((0, oiWindows_1.getCurrentOiWindowId)(context.oiWindowsSettings), context.oiWindowsSettings.windowsCount, context.oiWindows, open ? long : !long) || 0;
202
+ }
203
+ const signedActiveOi = activeOi * tradeSkewMultiplier;
204
+ const signedTradeOi = tradeOpenInterestUsd * tradeSkewMultiplier;
205
+ // Calculate price impact using depth bands
206
+ const priceImpactP = _getDepthBandsPriceImpactP(signedActiveOi, signedTradeOi, {
207
+ pairSlot1: depthBands,
208
+ mappingSlot1: context.depthBandsMapping,
209
+ }, (0, exports.getProtectionCloseFactor)(updatedContext), (0, exports.getCumulativeFactor)(updatedContext));
210
+ return priceImpactP;
211
+ }
212
+ return 0;
213
+ }
214
+ // Fall back to legacy calculation for pre-v10.2 contracts
115
215
  const onePercentDepth = tradePositiveSkew
116
- ? context.pairDepth?.onePercentDepthAboveUsd
117
- : context.pairDepth?.onePercentDepthBelowUsd;
216
+ ? (_a = context.pairDepth) === null || _a === void 0 ? void 0 : _a.onePercentDepthAboveUsd
217
+ : (_b = context.pairDepth) === null || _b === void 0 ? void 0 : _b.onePercentDepthBelowUsd;
118
218
  let activeOi = undefined;
119
219
  if (context.oiWindowsSettings !== undefined) {
120
220
  activeOi = (0, oiWindows_1.getActiveOi)((0, oiWindows_1.getCurrentOiWindowId)(context.oiWindowsSettings), context.oiWindowsSettings.windowsCount, context.oiWindows, open ? long : !long);
@@ -162,7 +262,8 @@ exports.getFixedSpreadP = getFixedSpreadP;
162
262
  * Currently it may double-count user fixed spread if pairSpreadP already includes it
163
263
  */
164
264
  const getSpreadP = (pairSpreadP, isLiquidation, liquidationParams, userPriceImpact) => {
165
- const fixedSpreadP = userPriceImpact?.fixedSpreadP ?? 0;
265
+ var _a;
266
+ const fixedSpreadP = (_a = userPriceImpact === null || userPriceImpact === void 0 ? void 0 : userPriceImpact.fixedSpreadP) !== null && _a !== void 0 ? _a : 0;
166
267
  if (pairSpreadP === undefined || (pairSpreadP === 0 && fixedSpreadP === 0)) {
167
268
  return 0;
168
269
  }
@@ -192,17 +293,14 @@ const getSpreadWithCumulVolPriceImpactP = (pairSpreadP, buy, collateral, leverag
192
293
  if (pairSpreadP === undefined) {
193
294
  return 0;
194
295
  }
195
- const baseSpread = (0, exports.getSpreadP)(pairSpreadP, undefined, undefined, context?.userPriceImpact);
296
+ const baseSpread = (0, exports.getSpreadP)(pairSpreadP, undefined, undefined, context === null || context === void 0 ? void 0 : context.userPriceImpact);
196
297
  // Calculate position size in USD
197
- const positionSizeUsd = collateral * leverage * (context?.collateralPriceUsd || 1);
298
+ const positionSizeUsd = collateral * leverage * ((context === null || context === void 0 ? void 0 : context.collateralPriceUsd) || 1);
198
299
  const cumulVolImpact = (0, exports.getTradeCumulVolPriceImpactP)("", // trader - not used in calculation
199
300
  0, // pairIndex - not used in calculation
200
- buy, positionSizeUsd, context?.isPnlPositive || false, context?.isOpen !== false, context?.createdBlock || 0, {
201
- ...context,
202
- pairDepth,
301
+ buy, positionSizeUsd, (context === null || context === void 0 ? void 0 : context.isPnlPositive) || false, (context === null || context === void 0 ? void 0 : context.isOpen) !== false, (context === null || context === void 0 ? void 0 : context.createdBlock) || 0, Object.assign(Object.assign({}, context), { pairDepth,
203
302
  oiWindowsSettings,
204
- oiWindows,
205
- });
303
+ oiWindows }));
206
304
  // If no depth or OI data, return just half spread
207
305
  if (cumulVolImpact === 0 && (!pairDepth || !oiWindowsSettings)) {
208
306
  return pairSpreadP / 2;
@@ -0,0 +1,11 @@
1
+ export type DepthBands = {
2
+ totalDepthUsd: number;
3
+ bands: number[];
4
+ };
5
+ export type PairDepthBands = {
6
+ above: DepthBands | undefined;
7
+ below: DepthBands | undefined;
8
+ };
9
+ export type DepthBandsMapping = {
10
+ bands: number[];
11
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -13,6 +13,7 @@ const builder_2 = require("../skew/builder");
13
13
  * @returns Complete context ready for getTradeOpeningPriceImpact
14
14
  */
15
15
  const buildTradeOpeningPriceImpactContext = (globalTradingVariables, collateralIndex, pairIndex, additionalParams) => {
16
+ var _a;
16
17
  const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
17
18
  if (!collateral) {
18
19
  return undefined;
@@ -34,7 +35,7 @@ const buildTradeOpeningPriceImpactContext = (globalTradingVariables, collateralI
34
35
  }
35
36
  // Return structured context with proper subcontexts
36
37
  return {
37
- collateralPriceUsd: collateral.prices?.collateralPriceUsd || 1,
38
+ collateralPriceUsd: ((_a = collateral.prices) === null || _a === void 0 ? void 0 : _a.collateralPriceUsd) || 1,
38
39
  cumulVolContext,
39
40
  skewContext,
40
41
  };
@@ -74,9 +74,6 @@ exports.getTradeOpeningPriceImpact = getTradeOpeningPriceImpact;
74
74
  * @returns Price impact breakdown and final price
75
75
  */
76
76
  const getTradeOpeningPriceImpactAtMarket = (input, context, currentMarketPrice) => {
77
- return (0, exports.getTradeOpeningPriceImpact)({
78
- ...input,
79
- openPrice: currentMarketPrice,
80
- }, context);
77
+ return (0, exports.getTradeOpeningPriceImpact)(Object.assign(Object.assign({}, input), { openPrice: currentMarketPrice }), context);
81
78
  };
82
79
  exports.getTradeOpeningPriceImpactAtMarket = getTradeOpeningPriceImpactAtMarket;
@@ -11,8 +11,9 @@ exports.buildSkewPriceImpactContext = void 0;
11
11
  * @returns Skew price impact context for the pair
12
12
  */
13
13
  const buildSkewPriceImpactContext = (tradingVariables, pairIndex) => {
14
- const skewDepth = tradingVariables.pairSkewDepths?.[pairIndex] ?? 0;
15
- const pairOi = tradingVariables.pairOis?.[pairIndex];
14
+ var _a, _b, _c;
15
+ const skewDepth = (_b = (_a = tradingVariables.pairSkewDepths) === null || _a === void 0 ? void 0 : _a[pairIndex]) !== null && _b !== void 0 ? _b : 0;
16
+ const pairOi = (_c = tradingVariables.pairOis) === null || _c === void 0 ? void 0 : _c[pairIndex];
16
17
  if (!pairOi) {
17
18
  throw new Error(`Pair OI data not found for pair index ${pairIndex}`);
18
19
  }
@@ -34,7 +34,7 @@ exports.convertPairOiTokenArray = convertPairOiTokenArray;
34
34
  * @returns Normalized pair OI collateral data
35
35
  */
36
36
  const convertPairOiCollateral = (contractData, collateralDecimals) => {
37
- const divisor = 10 ** collateralDecimals;
37
+ const divisor = Math.pow(10, collateralDecimals);
38
38
  return {
39
39
  oiLongCollateral: Number(contractData.oiLongCollateral) / divisor,
40
40
  oiShortCollateral: Number(contractData.oiShortCollateral) / divisor,