@gainsnetwork/sdk 0.0.0-me-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 (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -0
  3. package/lib/backend/globalTrades/index.d.ts +11 -0
  4. package/lib/backend/globalTrades/index.js +69 -0
  5. package/lib/backend/index.d.ts +3 -0
  6. package/lib/backend/index.js +28 -0
  7. package/lib/backend/tradingVariables/backend.types.d.ts +337 -0
  8. package/lib/backend/tradingVariables/backend.types.js +2 -0
  9. package/lib/backend/tradingVariables/converter.d.ts +38 -0
  10. package/lib/backend/tradingVariables/converter.js +359 -0
  11. package/lib/backend/tradingVariables/index.d.ts +5 -0
  12. package/lib/backend/tradingVariables/index.js +98 -0
  13. package/lib/backend/tradingVariables/types.d.ts +115 -0
  14. package/lib/backend/tradingVariables/types.js +14 -0
  15. package/lib/constants.d.ts +483 -0
  16. package/lib/constants.js +516 -0
  17. package/lib/contracts/addresses.d.ts +3 -0
  18. package/lib/contracts/addresses.js +35 -0
  19. package/lib/contracts/addresses.json +266 -0
  20. package/lib/contracts/index.d.ts +14 -0
  21. package/lib/contracts/index.js +92 -0
  22. package/lib/contracts/types/generated/GNSMultiCollatDiamond.d.ts +9327 -0
  23. package/lib/contracts/types/generated/GNSMultiCollatDiamond.js +2 -0
  24. package/lib/contracts/types/generated/GToken.d.ts +1917 -0
  25. package/lib/contracts/types/generated/GToken.js +2 -0
  26. package/lib/contracts/types/generated/GTokenOpenPnlFeed.d.ts +557 -0
  27. package/lib/contracts/types/generated/GTokenOpenPnlFeed.js +2 -0
  28. package/lib/contracts/types/generated/common.d.ts +22 -0
  29. package/lib/contracts/types/generated/common.js +2 -0
  30. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.d.ts +276 -0
  31. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.js +21557 -0
  32. package/lib/contracts/types/generated/factories/GTokenOpenPnlFeed__factory.d.ts +59 -0
  33. package/lib/contracts/types/generated/factories/GTokenOpenPnlFeed__factory.js +765 -0
  34. package/lib/contracts/types/generated/factories/GToken__factory.d.ts +121 -0
  35. package/lib/contracts/types/generated/factories/GToken__factory.js +2867 -0
  36. package/lib/contracts/types/generated/factories/index.d.ts +3 -0
  37. package/lib/contracts/types/generated/factories/index.js +12 -0
  38. package/lib/contracts/types/generated/index.d.ts +7 -0
  39. package/lib/contracts/types/generated/index.js +33 -0
  40. package/lib/contracts/types/index.d.ts +37 -0
  41. package/lib/contracts/types/index.js +30 -0
  42. package/lib/contracts/utils/borrowingFees.d.ts +9 -0
  43. package/lib/contracts/utils/borrowingFees.js +43 -0
  44. package/lib/contracts/utils/index.d.ts +3 -0
  45. package/lib/contracts/utils/index.js +19 -0
  46. package/lib/contracts/utils/openTrades.d.ts +12 -0
  47. package/lib/contracts/utils/openTrades.js +172 -0
  48. package/lib/contracts/utils/pairs.d.ts +18 -0
  49. package/lib/contracts/utils/pairs.js +602 -0
  50. package/lib/index.d.ts +10 -0
  51. package/lib/index.js +30 -0
  52. package/lib/markets/collateral/converter.d.ts +5 -0
  53. package/lib/markets/collateral/converter.js +11 -0
  54. package/lib/markets/collateral/index.d.ts +1 -0
  55. package/lib/markets/collateral/index.js +17 -0
  56. package/lib/markets/collateral/types.d.ts +7 -0
  57. package/lib/markets/collateral/types.js +2 -0
  58. package/lib/markets/commodities.d.ts +1 -0
  59. package/lib/markets/commodities.js +7 -0
  60. package/lib/markets/crypto.d.ts +1 -0
  61. package/lib/markets/crypto.js +6 -0
  62. package/lib/markets/forex.d.ts +3 -0
  63. package/lib/markets/forex.js +8 -0
  64. package/lib/markets/holdingFees/index.d.ts +46 -0
  65. package/lib/markets/holdingFees/index.js +104 -0
  66. package/lib/markets/holdingFees/types.d.ts +23 -0
  67. package/lib/markets/holdingFees/types.js +5 -0
  68. package/lib/markets/index.d.ts +11 -0
  69. package/lib/markets/index.js +27 -0
  70. package/lib/markets/indices.d.ts +1 -0
  71. package/lib/markets/indices.js +6 -0
  72. package/lib/markets/leverage/builder.d.ts +12 -0
  73. package/lib/markets/leverage/builder.js +25 -0
  74. package/lib/markets/leverage/getMarketLeverageRestrictions.d.ts +7 -0
  75. package/lib/markets/leverage/getMarketLeverageRestrictions.js +38 -0
  76. package/lib/markets/leverage/index.d.ts +3 -0
  77. package/lib/markets/leverage/index.js +19 -0
  78. package/lib/markets/leverage/types.d.ts +15 -0
  79. package/lib/markets/leverage/types.js +2 -0
  80. package/lib/markets/oi/converter.d.ts +62 -0
  81. package/lib/markets/oi/converter.js +111 -0
  82. package/lib/markets/oi/index.d.ts +49 -0
  83. package/lib/markets/oi/index.js +77 -0
  84. package/lib/markets/oi/types.d.ts +89 -0
  85. package/lib/markets/oi/types.js +6 -0
  86. package/lib/markets/price/builder.d.ts +25 -0
  87. package/lib/markets/price/builder.js +69 -0
  88. package/lib/markets/price/index.d.ts +7 -0
  89. package/lib/markets/price/index.js +23 -0
  90. package/lib/markets/price/marketPrice.d.ts +13 -0
  91. package/lib/markets/price/marketPrice.js +35 -0
  92. package/lib/markets/price/signedPrices.d.ts +36 -0
  93. package/lib/markets/price/signedPrices.js +181 -0
  94. package/lib/markets/price/types.d.ts +50 -0
  95. package/lib/markets/price/types.js +5 -0
  96. package/lib/markets/schedules/builders.d.ts +7 -0
  97. package/lib/markets/schedules/builders.js +81 -0
  98. package/lib/markets/schedules/checkers.d.ts +7 -0
  99. package/lib/markets/schedules/checkers.js +36 -0
  100. package/lib/markets/schedules/holidays.d.ts +4 -0
  101. package/lib/markets/schedules/holidays.js +77 -0
  102. package/lib/markets/schedules/index.d.ts +9 -0
  103. package/lib/markets/schedules/index.js +45 -0
  104. package/lib/markets/schedules/types.d.ts +43 -0
  105. package/lib/markets/schedules/types.js +37 -0
  106. package/lib/markets/stocks.d.ts +3 -0
  107. package/lib/markets/stocks.js +15 -0
  108. package/lib/pricing/depthBands.d.ts +39 -0
  109. package/lib/pricing/depthBands.js +94 -0
  110. package/lib/pricing/index.d.ts +4 -0
  111. package/lib/pricing/index.js +20 -0
  112. package/lib/trade/counterTrade/index.d.ts +2 -0
  113. package/lib/trade/counterTrade/index.js +18 -0
  114. package/lib/trade/counterTrade/types.d.ts +7 -0
  115. package/lib/trade/counterTrade/types.js +2 -0
  116. package/lib/trade/counterTrade/validateCounterTrade.d.ts +10 -0
  117. package/lib/trade/counterTrade/validateCounterTrade.js +29 -0
  118. package/lib/trade/effectiveLeverage/getTradeNewEffectiveLeverage.d.ts +20 -0
  119. package/lib/trade/effectiveLeverage/getTradeNewEffectiveLeverage.js +42 -0
  120. package/lib/trade/effectiveLeverage/index.d.ts +2 -0
  121. package/lib/trade/effectiveLeverage/index.js +21 -0
  122. package/lib/trade/effectiveLeverage/types.d.ts +30 -0
  123. package/lib/trade/effectiveLeverage/types.js +2 -0
  124. package/lib/trade/fees/borrowing/builder.d.ts +14 -0
  125. package/lib/trade/fees/borrowing/builder.js +33 -0
  126. package/lib/trade/fees/borrowing/converter.d.ts +17 -0
  127. package/lib/trade/fees/borrowing/converter.js +46 -0
  128. package/lib/trade/fees/borrowing/index.d.ts +81 -0
  129. package/lib/trade/fees/borrowing/index.js +259 -0
  130. package/lib/trade/fees/borrowing/types.d.ts +36 -0
  131. package/lib/trade/fees/borrowing/types.js +2 -0
  132. package/lib/trade/fees/borrowingV2/builder.d.ts +6 -0
  133. package/lib/trade/fees/borrowingV2/builder.js +23 -0
  134. package/lib/trade/fees/borrowingV2/converter.d.ts +75 -0
  135. package/lib/trade/fees/borrowingV2/converter.js +132 -0
  136. package/lib/trade/fees/borrowingV2/fetcher.d.ts +76 -0
  137. package/lib/trade/fees/borrowingV2/fetcher.js +179 -0
  138. package/lib/trade/fees/borrowingV2/index.d.ts +48 -0
  139. package/lib/trade/fees/borrowingV2/index.js +112 -0
  140. package/lib/trade/fees/borrowingV2/types.d.ts +95 -0
  141. package/lib/trade/fees/borrowingV2/types.js +5 -0
  142. package/lib/trade/fees/converter.d.ts +48 -0
  143. package/lib/trade/fees/converter.js +114 -0
  144. package/lib/trade/fees/fundingFees/builder.d.ts +9 -0
  145. package/lib/trade/fees/fundingFees/builder.js +38 -0
  146. package/lib/trade/fees/fundingFees/converter.d.ts +102 -0
  147. package/lib/trade/fees/fundingFees/converter.js +196 -0
  148. package/lib/trade/fees/fundingFees/fetcher.d.ts +66 -0
  149. package/lib/trade/fees/fundingFees/fetcher.js +141 -0
  150. package/lib/trade/fees/fundingFees/index.d.ts +124 -0
  151. package/lib/trade/fees/fundingFees/index.js +309 -0
  152. package/lib/trade/fees/fundingFees/pairContext.d.ts +33 -0
  153. package/lib/trade/fees/fundingFees/pairContext.js +17 -0
  154. package/lib/trade/fees/fundingFees/types.d.ts +77 -0
  155. package/lib/trade/fees/fundingFees/types.js +5 -0
  156. package/lib/trade/fees/index.d.ts +11 -0
  157. package/lib/trade/fees/index.js +87 -0
  158. package/lib/trade/fees/tiers/converter.d.ts +64 -0
  159. package/lib/trade/fees/tiers/converter.js +100 -0
  160. package/lib/trade/fees/tiers/index.d.ts +46 -0
  161. package/lib/trade/fees/tiers/index.js +135 -0
  162. package/lib/trade/fees/tiers/types.d.ts +22 -0
  163. package/lib/trade/fees/tiers/types.js +8 -0
  164. package/lib/trade/fees/trading/builder.d.ts +19 -0
  165. package/lib/trade/fees/trading/builder.js +21 -0
  166. package/lib/trade/fees/trading/converter.d.ts +32 -0
  167. package/lib/trade/fees/trading/converter.js +47 -0
  168. package/lib/trade/fees/trading/index.d.ts +62 -0
  169. package/lib/trade/fees/trading/index.js +157 -0
  170. package/lib/trade/fees/trading/types.d.ts +46 -0
  171. package/lib/trade/fees/trading/types.js +5 -0
  172. package/lib/trade/index.d.ts +10 -0
  173. package/lib/trade/index.js +26 -0
  174. package/lib/trade/liquidation/builder.d.ts +25 -0
  175. package/lib/trade/liquidation/builder.js +58 -0
  176. package/lib/trade/liquidation/converter.d.ts +23 -0
  177. package/lib/trade/liquidation/converter.js +46 -0
  178. package/lib/trade/liquidation/index.d.ts +29 -0
  179. package/lib/trade/liquidation/index.js +216 -0
  180. package/lib/trade/liquidation/types.d.ts +38 -0
  181. package/lib/trade/liquidation/types.js +2 -0
  182. package/lib/trade/oiWindows.d.ts +3 -0
  183. package/lib/trade/oiWindows.js +19 -0
  184. package/lib/trade/pnl/builder.d.ts +16 -0
  185. package/lib/trade/pnl/builder.js +43 -0
  186. package/lib/trade/pnl/converter.d.ts +47 -0
  187. package/lib/trade/pnl/converter.js +72 -0
  188. package/lib/trade/pnl/index.d.ts +91 -0
  189. package/lib/trade/pnl/index.js +301 -0
  190. package/lib/trade/pnl/types.d.ts +79 -0
  191. package/lib/trade/pnl/types.js +5 -0
  192. package/lib/trade/priceImpact/close/builder.d.ts +23 -0
  193. package/lib/trade/priceImpact/close/builder.js +44 -0
  194. package/lib/trade/priceImpact/close/index.d.ts +22 -0
  195. package/lib/trade/priceImpact/close/index.js +137 -0
  196. package/lib/trade/priceImpact/close/types.d.ts +47 -0
  197. package/lib/trade/priceImpact/close/types.js +5 -0
  198. package/lib/trade/priceImpact/cumulVol/builder.d.ts +22 -0
  199. package/lib/trade/priceImpact/cumulVol/builder.js +53 -0
  200. package/lib/trade/priceImpact/cumulVol/converter.d.ts +94 -0
  201. package/lib/trade/priceImpact/cumulVol/converter.js +155 -0
  202. package/lib/trade/priceImpact/cumulVol/index.d.ts +109 -0
  203. package/lib/trade/priceImpact/cumulVol/index.js +316 -0
  204. package/lib/trade/priceImpact/cumulVol/types.d.ts +11 -0
  205. package/lib/trade/priceImpact/cumulVol/types.js +2 -0
  206. package/lib/trade/priceImpact/index.d.ts +21 -0
  207. package/lib/trade/priceImpact/index.js +79 -0
  208. package/lib/trade/priceImpact/open/builder.d.ts +21 -0
  209. package/lib/trade/priceImpact/open/builder.js +42 -0
  210. package/lib/trade/priceImpact/open/index.d.ts +23 -0
  211. package/lib/trade/priceImpact/open/index.js +82 -0
  212. package/lib/trade/priceImpact/open/types.d.ts +45 -0
  213. package/lib/trade/priceImpact/open/types.js +5 -0
  214. package/lib/trade/priceImpact/skew/builder.d.ts +12 -0
  215. package/lib/trade/priceImpact/skew/builder.js +27 -0
  216. package/lib/trade/priceImpact/skew/converter.d.ts +46 -0
  217. package/lib/trade/priceImpact/skew/converter.js +81 -0
  218. package/lib/trade/priceImpact/skew/fetcher.d.ts +60 -0
  219. package/lib/trade/priceImpact/skew/fetcher.js +160 -0
  220. package/lib/trade/priceImpact/skew/index.d.ts +53 -0
  221. package/lib/trade/priceImpact/skew/index.js +148 -0
  222. package/lib/trade/priceImpact/skew/types.d.ts +44 -0
  223. package/lib/trade/priceImpact/skew/types.js +5 -0
  224. package/lib/trade/spread.d.ts +5 -0
  225. package/lib/trade/spread.js +19 -0
  226. package/lib/trade/types.d.ts +777 -0
  227. package/lib/trade/types.js +478 -0
  228. package/lib/trade/utils.d.ts +18 -0
  229. package/lib/trade/utils.js +30 -0
  230. package/lib/utils/index.d.ts +1 -0
  231. package/lib/utils/index.js +17 -0
  232. package/lib/utils/packing.d.ts +2 -0
  233. package/lib/utils/packing.js +39 -0
  234. package/lib/vault/index.d.ts +10 -0
  235. package/lib/vault/index.js +10 -0
  236. package/package.json +106 -0
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @dev Main export file for OI module
3
+ * @dev Provides unified Open Interest management functionality
4
+ */
5
+ import { GenericPairOiContext } from "./types";
6
+ export declare const getPairTotalOisCollateral: (pairIndex: number, context: GenericPairOiContext) => {
7
+ long: number;
8
+ short: number;
9
+ };
10
+ /**
11
+ * @dev Returns pair total dynamic open interest (before v10 + after v10) in collateral tokens
12
+ * @param pairIndex index of pair
13
+ * @param context contains UnifiedPairOi array and current pair price
14
+ * @returns dynamic OI for long and short sides in collateral precision
15
+ */
16
+ export declare const getPairTotalOisDynamicCollateral: (pairIndex: number, context: GenericPairOiContext & {
17
+ currentPairPrice: number;
18
+ }) => {
19
+ long: number;
20
+ short: number;
21
+ };
22
+ /**
23
+ * @dev Returns pair total dynamic open interest (before v10 + after v10) in collateral tokens on one side only
24
+ * @param pairIndex index of pair
25
+ * @param long true if long, false if short
26
+ * @param context contains UnifiedPairOi array and current pair price
27
+ * @returns dynamic OI for the specified side in collateral precision
28
+ */
29
+ export declare const getPairTotalOiDynamicCollateral: (pairIndex: number, long: boolean, context: GenericPairOiContext & {
30
+ currentPairPrice: number;
31
+ }) => number;
32
+ /**
33
+ * @dev Returns pair open interest skew (v10 only) in tokens
34
+ * @param pairIndex index of pair
35
+ * @param context contains UnifiedPairOi array
36
+ * @returns skew in token amount (positive = more longs, negative = more shorts)
37
+ */
38
+ export declare const getPairV10OiTokenSkewCollateral: (pairIndex: number, context: GenericPairOiContext) => number;
39
+ /**
40
+ * @dev Returns pair dynamic skew (v10 only) in collateral tokens
41
+ * @param pairIndex index of pair
42
+ * @param context contains UnifiedPairOi array and current pair price
43
+ * @returns dynamic skew in collateral precision
44
+ */
45
+ export declare const getPairV10OiDynamicSkewCollateral: (pairIndex: number, context: GenericPairOiContext & {
46
+ currentPairPrice: number;
47
+ }) => number;
48
+ export { UnifiedPairOi, GroupOi, ComputedOi } from "./types";
49
+ export { convertBeforeV10Collateral, convertCollateralOi, convertTokenOi, convertPairOi, convertPairOiArray, computeOiValues, } from "./converter";
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Main export file for OI module
4
+ * @dev Provides unified Open Interest management functionality
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.computeOiValues = exports.convertPairOiArray = exports.convertPairOi = exports.convertTokenOi = exports.convertCollateralOi = exports.convertBeforeV10Collateral = exports.getPairV10OiDynamicSkewCollateral = exports.getPairV10OiTokenSkewCollateral = exports.getPairTotalOiDynamicCollateral = exports.getPairTotalOisDynamicCollateral = exports.getPairTotalOisCollateral = void 0;
8
+ const getPairTotalOisCollateral = (pairIndex, context) => {
9
+ return {
10
+ long: context.pairOis[pairIndex].beforeV10Collateral.long +
11
+ context.pairOis[pairIndex].collateral.long,
12
+ short: context.pairOis[pairIndex].beforeV10Collateral.short +
13
+ context.pairOis[pairIndex].collateral.short,
14
+ };
15
+ };
16
+ exports.getPairTotalOisCollateral = getPairTotalOisCollateral;
17
+ /**
18
+ * @dev Returns pair total dynamic open interest (before v10 + after v10) in collateral tokens
19
+ * @param pairIndex index of pair
20
+ * @param context contains UnifiedPairOi array and current pair price
21
+ * @returns dynamic OI for long and short sides in collateral precision
22
+ */
23
+ const getPairTotalOisDynamicCollateral = (pairIndex, context) => {
24
+ const pairOi = context.pairOis[pairIndex];
25
+ // We have to use the initial collateral OIs for pre-v10 trades because we don't have OIs in token amount
26
+ const oiLongCollateralDynamicAfterV10 = pairOi.beforeV10Collateral.long +
27
+ pairOi.token.long * context.currentPairPrice;
28
+ const oiShortCollateralDynamicAfterV10 = pairOi.beforeV10Collateral.short +
29
+ pairOi.token.short * context.currentPairPrice;
30
+ return {
31
+ long: oiLongCollateralDynamicAfterV10,
32
+ short: oiShortCollateralDynamicAfterV10,
33
+ };
34
+ };
35
+ exports.getPairTotalOisDynamicCollateral = getPairTotalOisDynamicCollateral;
36
+ /**
37
+ * @dev Returns pair total dynamic open interest (before v10 + after v10) in collateral tokens on one side only
38
+ * @param pairIndex index of pair
39
+ * @param long true if long, false if short
40
+ * @param context contains UnifiedPairOi array and current pair price
41
+ * @returns dynamic OI for the specified side in collateral precision
42
+ */
43
+ const getPairTotalOiDynamicCollateral = (pairIndex, long, context) => {
44
+ const dynamicOis = (0, exports.getPairTotalOisDynamicCollateral)(pairIndex, context);
45
+ return long ? dynamicOis.long : dynamicOis.short;
46
+ };
47
+ exports.getPairTotalOiDynamicCollateral = getPairTotalOiDynamicCollateral;
48
+ /**
49
+ * @dev Returns pair open interest skew (v10 only) in tokens
50
+ * @param pairIndex index of pair
51
+ * @param context contains UnifiedPairOi array
52
+ * @returns skew in token amount (positive = more longs, negative = more shorts)
53
+ */
54
+ const getPairV10OiTokenSkewCollateral = (pairIndex, context) => {
55
+ const pairOi = context.pairOis[pairIndex];
56
+ return pairOi.token.long - pairOi.token.short;
57
+ };
58
+ exports.getPairV10OiTokenSkewCollateral = getPairV10OiTokenSkewCollateral;
59
+ /**
60
+ * @dev Returns pair dynamic skew (v10 only) in collateral tokens
61
+ * @param pairIndex index of pair
62
+ * @param context contains UnifiedPairOi array and current pair price
63
+ * @returns dynamic skew in collateral precision
64
+ */
65
+ const getPairV10OiDynamicSkewCollateral = (pairIndex, context) => {
66
+ return ((0, exports.getPairV10OiTokenSkewCollateral)(pairIndex, context) *
67
+ context.currentPairPrice);
68
+ };
69
+ exports.getPairV10OiDynamicSkewCollateral = getPairV10OiDynamicSkewCollateral;
70
+ // Converters
71
+ var converter_1 = require("./converter");
72
+ Object.defineProperty(exports, "convertBeforeV10Collateral", { enumerable: true, get: function () { return converter_1.convertBeforeV10Collateral; } });
73
+ Object.defineProperty(exports, "convertCollateralOi", { enumerable: true, get: function () { return converter_1.convertCollateralOi; } });
74
+ Object.defineProperty(exports, "convertTokenOi", { enumerable: true, get: function () { return converter_1.convertTokenOi; } });
75
+ Object.defineProperty(exports, "convertPairOi", { enumerable: true, get: function () { return converter_1.convertPairOi; } });
76
+ Object.defineProperty(exports, "convertPairOiArray", { enumerable: true, get: function () { return converter_1.convertPairOiArray; } });
77
+ Object.defineProperty(exports, "computeOiValues", { enumerable: true, get: function () { return converter_1.computeOiValues; } });
@@ -0,0 +1,89 @@
1
+ /**
2
+ * @dev Consolidated OI types for unified Open Interest management
3
+ * @dev Represents the three OI storage systems in Gains Network v10
4
+ */
5
+ /**
6
+ * @dev Unified pair OI structure combining all storage systems
7
+ */
8
+ export interface UnifiedPairOi {
9
+ /**
10
+ * @dev Maximum allowed OI in collateral (applies to combined OI)
11
+ */
12
+ maxCollateral: number;
13
+ /**
14
+ * @dev Pre-v10 trades OI stored in collateral amounts
15
+ * @dev Static values from when positions were opened
16
+ */
17
+ beforeV10Collateral: {
18
+ long: number;
19
+ short: number;
20
+ };
21
+ /**
22
+ * @dev Post-v10 trades OI stored in collateral amounts
23
+ * @dev Initial collateral values when positions were opened
24
+ * @dev Used for administrative operations and static calculations
25
+ */
26
+ collateral: {
27
+ long: number;
28
+ short: number;
29
+ };
30
+ /**
31
+ * @dev Post-v10 trades OI stored in token amounts
32
+ * @dev Used for dynamic calculations (multiply by current price)
33
+ * @dev Powers skew impact and funding fees
34
+ */
35
+ token: {
36
+ long: number;
37
+ short: number;
38
+ };
39
+ }
40
+ export type GenericPairOiContext = {
41
+ pairOis: UnifiedPairOi[];
42
+ };
43
+ /**
44
+ * @dev Group OI remains unchanged - only used by borrowing v1
45
+ * @dev Re-export existing type for consistency
46
+ */
47
+ export { OpenInterest as GroupOi } from "../../trade/types";
48
+ /**
49
+ * @dev Helper type for computed OI values
50
+ */
51
+ export interface ComputedOi {
52
+ /**
53
+ * @dev Total OI using static values: beforeV10Collateral + collateral
54
+ * @dev Used for administrative operations
55
+ */
56
+ totalStaticCollateral: {
57
+ long: number;
58
+ short: number;
59
+ };
60
+ /**
61
+ * @dev Total OI using dynamic values: beforeV10Collateral + (token * price)
62
+ * @dev Used for real-time calculations like fees
63
+ */
64
+ totalDynamicCollateral: {
65
+ long: number;
66
+ short: number;
67
+ };
68
+ /**
69
+ * @dev v10-only OI using static collateral values
70
+ * @dev Used for funding fee markets display
71
+ */
72
+ v10StaticCollateral: {
73
+ long: number;
74
+ short: number;
75
+ };
76
+ /**
77
+ * @dev v10-only OI using dynamic values: token * price
78
+ * @dev Used for funding fee markets real-time display
79
+ */
80
+ v10DynamicCollateral: {
81
+ long: number;
82
+ short: number;
83
+ };
84
+ /**
85
+ * @dev Net skew in tokens (v10+ only)
86
+ * @dev Positive = more longs, negative = more shorts
87
+ */
88
+ skewToken: number;
89
+ }
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Consolidated OI types for unified Open Interest management
4
+ * @dev Represents the three OI storage systems in Gains Network v10
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @dev Builder functions for creating market price contexts
3
+ */
4
+ import { MarketPriceContext } from "./types";
5
+ import { TradingVariablesCollateral } from "../../backend/tradingVariables/types";
6
+ /**
7
+ * @dev Builds a market price context for a specific pair from trading variables
8
+ * @param tradingVariables Trading variables for a specific collateral
9
+ * @param pairIndex Pair index to create context for
10
+ * @returns Market price context for the pair
11
+ */
12
+ export declare const buildMarketPriceContext: (tradingVariables: TradingVariablesCollateral, pairIndex: number) => MarketPriceContext;
13
+ /**
14
+ * @dev Creates an empty market price context
15
+ * @returns Empty market price context
16
+ */
17
+ export declare const createEmptyMarketPriceContext: () => MarketPriceContext;
18
+ /**
19
+ * @dev Creates a market price context with custom values
20
+ * @param skewDepth Skew depth in tokens
21
+ * @param oiLongToken Long OI in tokens
22
+ * @param oiShortToken Short OI in tokens
23
+ * @returns Market price context
24
+ */
25
+ export declare const createMarketPriceContext: (skewDepth: number, oiLongToken: number, oiShortToken: number) => MarketPriceContext;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Builder functions for creating market price contexts
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createMarketPriceContext = exports.createEmptyMarketPriceContext = exports.buildMarketPriceContext = void 0;
7
+ /**
8
+ * @dev Builds a market price context for a specific pair from trading variables
9
+ * @param tradingVariables Trading variables for a specific collateral
10
+ * @param pairIndex Pair index to create context for
11
+ * @returns Market price context for the pair
12
+ */
13
+ const buildMarketPriceContext = (tradingVariables, pairIndex) => {
14
+ // Get skew depth for the pair, default to 0 if not set
15
+ const skewDepth = tradingVariables.pairSkewDepths[pairIndex] || 0;
16
+ // Get pair OI data
17
+ const pairOi = tradingVariables.pairOis[pairIndex];
18
+ if (!pairOi) {
19
+ // Return default context if no OI data
20
+ return {
21
+ skewDepth,
22
+ pairOiToken: {
23
+ oiLongToken: 0,
24
+ oiShortToken: 0,
25
+ },
26
+ };
27
+ }
28
+ // Extract token OI from unified pair OI
29
+ const pairOiToken = {
30
+ oiLongToken: pairOi.token.long,
31
+ oiShortToken: pairOi.token.short,
32
+ };
33
+ return {
34
+ skewDepth,
35
+ pairOiToken,
36
+ };
37
+ };
38
+ exports.buildMarketPriceContext = buildMarketPriceContext;
39
+ /**
40
+ * @dev Creates an empty market price context
41
+ * @returns Empty market price context
42
+ */
43
+ const createEmptyMarketPriceContext = () => {
44
+ return {
45
+ skewDepth: 0,
46
+ pairOiToken: {
47
+ oiLongToken: 0,
48
+ oiShortToken: 0,
49
+ },
50
+ };
51
+ };
52
+ exports.createEmptyMarketPriceContext = createEmptyMarketPriceContext;
53
+ /**
54
+ * @dev Creates a market price context with custom values
55
+ * @param skewDepth Skew depth in tokens
56
+ * @param oiLongToken Long OI in tokens
57
+ * @param oiShortToken Short OI in tokens
58
+ * @returns Market price context
59
+ */
60
+ const createMarketPriceContext = (skewDepth, oiLongToken, oiShortToken) => {
61
+ return {
62
+ skewDepth,
63
+ pairOiToken: {
64
+ oiLongToken,
65
+ oiShortToken,
66
+ },
67
+ };
68
+ };
69
+ exports.createMarketPriceContext = createMarketPriceContext;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @dev Market price module exports
3
+ */
4
+ export * from "./types";
5
+ export * from "./marketPrice";
6
+ export * from "./builder";
7
+ export * from "./signedPrices";
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Market price module exports
4
+ */
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
17
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ __exportStar(require("./types"), exports);
21
+ __exportStar(require("./marketPrice"), exports);
22
+ __exportStar(require("./builder"), exports);
23
+ __exportStar(require("./signedPrices"), exports);
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @dev Current market price calculation with skew impact
3
+ */
4
+ import { MarketPriceResult, MarketPriceContext } from "./types";
5
+ /**
6
+ * @dev Calculates the current market price adjusted for skew impact
7
+ * @dev Please always provide oracle price to this and other functions in the sdk. Market price is displayed in the UI.
8
+ * @param pairIndex Trading pair index
9
+ * @param oraclePrice Oracle price for the pair
10
+ * @param context Market price context with depths and OI data
11
+ * @returns Current market price with skew impact applied
12
+ */
13
+ export declare const getCurrentMarketPrice: (pairIndex: number, oraclePrice: number, context: MarketPriceContext) => MarketPriceResult;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Current market price calculation with skew impact
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getCurrentMarketPrice = void 0;
7
+ const skew_1 = require("../../trade/priceImpact/skew");
8
+ /**
9
+ * @dev Calculates the current market price adjusted for skew impact
10
+ * @dev Please always provide oracle price to this and other functions in the sdk. Market price is displayed in the UI.
11
+ * @param pairIndex Trading pair index
12
+ * @param oraclePrice Oracle price for the pair
13
+ * @param context Market price context with depths and OI data
14
+ * @returns Current market price with skew impact applied
15
+ */
16
+ const getCurrentMarketPrice = (pairIndex, oraclePrice, context) => {
17
+ let skewImpactP = 0;
18
+ if (context.skewDepth > 0) {
19
+ const skewResult = (0, skew_1.getTradeSkewPriceImpact)({
20
+ collateralIndex: 0,
21
+ pairIndex,
22
+ long: true,
23
+ open: true,
24
+ positionSizeToken: 0, // Size 0 for current market price
25
+ }, context);
26
+ skewImpactP = skewResult.basePriceImpactP;
27
+ }
28
+ const marketPrice = oraclePrice * (1 + skewImpactP / 100);
29
+ return {
30
+ marketPrice,
31
+ skewImpactP,
32
+ oraclePrice,
33
+ };
34
+ };
35
+ exports.getCurrentMarketPrice = getCurrentMarketPrice;
@@ -0,0 +1,36 @@
1
+ import { Oracle, SignedPricesResponse } from "./types";
2
+ import { PendingOrderType } from "../../trade";
3
+ export interface FetchSignedPricesInput {
4
+ oracles: Oracle[];
5
+ pairs: number[];
6
+ chain: number;
7
+ minAnswer?: number;
8
+ timeoutMs?: number;
9
+ }
10
+ export declare const fetchSignedPrices: (input: FetchSignedPricesInput) => Promise<SignedPricesResponse[] | null>;
11
+ export interface FetchSignedLookbackPricesInput {
12
+ oracles: Oracle[];
13
+ trader: string;
14
+ tradeIndex: number;
15
+ pair: number;
16
+ orderType: PendingOrderType;
17
+ currentBlock: number;
18
+ fromBlock: number;
19
+ chain: number;
20
+ minAnswer?: number;
21
+ timeoutMs?: number;
22
+ }
23
+ export declare const fetchSignedLookbackPrices: (input: FetchSignedLookbackPricesInput) => Promise<SignedPricesResponse[] | null>;
24
+ export interface RetryOptions {
25
+ maxRetries?: number;
26
+ retryDelayMs?: number;
27
+ backoffMultiplier?: number;
28
+ }
29
+ export declare const fetchSignedPricesWithRetry: (input: FetchSignedPricesInput, retryOptions?: RetryOptions) => Promise<SignedPricesResponse[] | null>;
30
+ export declare const fetchSignedLookbackPricesWithRetry: (input: FetchSignedLookbackPricesInput, retryOptions?: RetryOptions) => Promise<SignedPricesResponse[] | null>;
31
+ export declare const validateSignedPricesPairs: (pairs: number[]) => {
32
+ valid: boolean;
33
+ pairs: number[];
34
+ };
35
+ export declare const isValidSignedPricesChain: (chainId: number) => boolean;
36
+ export declare const isValidSignedPricesOrderType: (orderType: PendingOrderType) => boolean;
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isValidSignedPricesOrderType = exports.isValidSignedPricesChain = exports.validateSignedPricesPairs = exports.fetchSignedLookbackPricesWithRetry = exports.fetchSignedPricesWithRetry = exports.fetchSignedLookbackPrices = exports.fetchSignedPrices = void 0;
4
+ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
5
+ const types_1 = require("../../contracts/types");
6
+ const trade_1 = require("../../trade");
7
+ const fetchSignedPrices = async (input) => {
8
+ const { minAnswers, timeoutMs, oracles, chain } = {
9
+ minAnswers: input.chain === types_1.ChainId.ARBITRUM_SEPOLIA ? 2 : 3,
10
+ timeoutMs: 1000,
11
+ ...input,
12
+ };
13
+ if (!(0, exports.isValidSignedPricesChain)(chain))
14
+ throw new Error(`Invalid chain ${chain}`);
15
+ const { valid, pairs } = (0, exports.validateSignedPricesPairs)(input.pairs);
16
+ if (!valid)
17
+ throw new Error(`Invalid pairs array`);
18
+ return await initiateSignedPricesRequest(oracles, "signPrices", JSON.stringify({ pairs, chain }), minAnswers, timeoutMs);
19
+ };
20
+ exports.fetchSignedPrices = fetchSignedPrices;
21
+ const fetchSignedLookbackPrices = async (input) => {
22
+ const { minAnswers, timeoutMs, oracles, trader, tradeIndex, pair, orderType, currentBlock, fromBlock, chain, } = {
23
+ minAnswers: input.chain === types_1.ChainId.ARBITRUM_SEPOLIA ? 2 : 3,
24
+ timeoutMs: 6000,
25
+ ...input,
26
+ };
27
+ if (!(0, exports.isValidSignedPricesChain)(chain))
28
+ throw new Error(`Invalid chain ${chain}`);
29
+ if (!(0, exports.isValidSignedPricesOrderType)(orderType))
30
+ throw new Error(`Invalid orderType ${orderType}`);
31
+ if (isNaN(pair))
32
+ throw new Error(`Invalid pair ${pair}`);
33
+ if (isNaN(tradeIndex) || tradeIndex < 0)
34
+ throw new Error(`Invalid tradeIndex ${tradeIndex}`);
35
+ if (!currentBlock || !fromBlock)
36
+ throw new Error(`Invalid block numbers`);
37
+ return await initiateSignedPricesRequest(oracles, "signLookbackPrices", JSON.stringify({
38
+ trader,
39
+ tradeIndex,
40
+ pair,
41
+ orderType,
42
+ currentBlock,
43
+ fromBlock,
44
+ chain,
45
+ }), minAnswers, timeoutMs);
46
+ };
47
+ exports.fetchSignedLookbackPrices = fetchSignedLookbackPrices;
48
+ // Helper to determine if an error is likely transient
49
+ const isTransientError = (error) => {
50
+ const message = (error instanceof Error ? error.message : String(error))?.toLowerCase() ||
51
+ "";
52
+ return (message.includes("timeout") ||
53
+ message.includes("aborted") ||
54
+ message.includes("not enough valid signed prices") ||
55
+ message.includes("network") ||
56
+ message.includes("fetch failed"));
57
+ };
58
+ // Fetch signed prices with retry logic for transient failures
59
+ const fetchSignedPricesWithRetry = async (input, retryOptions) => {
60
+ const { maxRetries = 2, retryDelayMs = 500, backoffMultiplier = 1.5, } = retryOptions || {};
61
+ let lastError;
62
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
63
+ try {
64
+ return await (0, exports.fetchSignedPrices)(input);
65
+ }
66
+ catch (error) {
67
+ lastError = error;
68
+ // Don't retry non-transient errors or if we're out of retries
69
+ if (attempt === maxRetries || !isTransientError(error)) {
70
+ throw error;
71
+ }
72
+ // Wait with exponential backoff before retry
73
+ const delay = Math.floor(retryDelayMs * Math.pow(backoffMultiplier, attempt));
74
+ await new Promise(resolve => setTimeout(resolve, delay));
75
+ }
76
+ }
77
+ throw lastError;
78
+ };
79
+ exports.fetchSignedPricesWithRetry = fetchSignedPricesWithRetry;
80
+ // Fetch lookback prices with retry logic
81
+ const fetchSignedLookbackPricesWithRetry = async (input, retryOptions) => {
82
+ const { maxRetries = 2, retryDelayMs = 1000, backoffMultiplier = 2, } = retryOptions || {};
83
+ let lastError;
84
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
85
+ try {
86
+ return await (0, exports.fetchSignedLookbackPrices)(input);
87
+ }
88
+ catch (error) {
89
+ lastError = error;
90
+ // Don't retry non-transient errors or if we're out of retries
91
+ if (attempt === maxRetries || !isTransientError(error)) {
92
+ throw error;
93
+ }
94
+ // Wait with exponential backoff before retry
95
+ const delay = Math.floor(retryDelayMs * Math.pow(backoffMultiplier, attempt));
96
+ await new Promise(resolve => setTimeout(resolve, delay));
97
+ }
98
+ }
99
+ throw lastError;
100
+ };
101
+ exports.fetchSignedLookbackPricesWithRetry = fetchSignedLookbackPricesWithRetry;
102
+ // @todo optional filtering to minAnswers best responses
103
+ const initiateSignedPricesRequest = async (oracles, request, requestBody, minAnswers, timeoutMs) => {
104
+ try {
105
+ // Fetch signed prices from all oracles in parallel
106
+ const signedPrices = await Promise.allSettled(oracles.map(oracle => _getSignedPricesFromSigner(`${oracle.url}/${request}`, requestBody, oracle?.key, timeoutMs)));
107
+ // Filter out failed requests and null responses, then sort by signerId
108
+ const successfulResponses = signedPrices.filter(res => res.status === "fulfilled" && res.value !== null // Filter out failed or null responses
109
+ )
110
+ // Extract `value`
111
+ .map((res) => res.value)
112
+ // Sort by signerId, contracts expect signerId ascending
113
+ .sort((a, b) => a.signedData.signerId - b.signedData.signerId);
114
+ // Ensure we have at least `minAnswers` valid responses
115
+ if (successfulResponses.length < minAnswers) {
116
+ throw new Error(`Not enough valid signed prices. Wanted ${minAnswers} but got ${successfulResponses.length}`);
117
+ }
118
+ return successfulResponses;
119
+ }
120
+ catch (e) {
121
+ console.error("Error processing signed prices", e);
122
+ throw e;
123
+ }
124
+ };
125
+ const _getSignedPricesFromSigner = async (url, requestBody, authKey, timeoutMs) => {
126
+ try {
127
+ const controller = new AbortController();
128
+ const timeout = setTimeout(() => {
129
+ controller.abort();
130
+ }, timeoutMs || 2000);
131
+ const response = await fetch(`${url}`, {
132
+ method: "POST",
133
+ headers: {
134
+ "Content-Type": "application/json",
135
+ "x-api-key": authKey || "",
136
+ },
137
+ body: requestBody,
138
+ signal: controller.signal,
139
+ });
140
+ clearTimeout(timeout);
141
+ if (!response.ok) {
142
+ throw new Error(`Failed to fetch signed prices from ${url}: ${response.statusText}`);
143
+ }
144
+ return (await response.json());
145
+ }
146
+ catch (error) {
147
+ console.error(`Error fetching signed prices from ${url}:`, {
148
+ error: error?.message,
149
+ });
150
+ return null;
151
+ }
152
+ };
153
+ const validateSignedPricesPairs = (pairs) => {
154
+ if (!Array.isArray(pairs) || pairs?.length === 0 || pairs.some(p => isNaN(p)))
155
+ return { valid: false, pairs: [] };
156
+ // Pairs must always be in ascending order
157
+ return { valid: true, pairs: [...new Set(pairs)].sort((a, b) => a - b) };
158
+ };
159
+ exports.validateSignedPricesPairs = validateSignedPricesPairs;
160
+ const isValidSignedPricesChain = (chainId) => {
161
+ return (!isNaN(chainId) &&
162
+ [
163
+ types_1.ChainId.POLYGON,
164
+ types_1.ChainId.BASE,
165
+ types_1.ChainId.ARBITRUM,
166
+ types_1.ChainId.ARBITRUM_SEPOLIA,
167
+ types_1.ChainId.APECHAIN,
168
+ ].includes(chainId));
169
+ };
170
+ exports.isValidSignedPricesChain = isValidSignedPricesChain;
171
+ const isValidSignedPricesOrderType = (orderType) => {
172
+ return (!isNaN(orderType) &&
173
+ [
174
+ trade_1.PendingOrderType.LIMIT_OPEN,
175
+ trade_1.PendingOrderType.STOP_OPEN,
176
+ trade_1.PendingOrderType.TP_CLOSE,
177
+ trade_1.PendingOrderType.SL_CLOSE,
178
+ trade_1.PendingOrderType.LIQ_CLOSE,
179
+ ].includes(orderType));
180
+ };
181
+ exports.isValidSignedPricesOrderType = isValidSignedPricesOrderType;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @dev Market price types for calculating price with skew impact
3
+ */
4
+ export type MarketPriceInput = {
5
+ collateralIndex: number;
6
+ pairIndex: number;
7
+ oraclePrice: number;
8
+ long: boolean;
9
+ open: boolean;
10
+ positionSizeCollateral: number;
11
+ };
12
+ export type MarketPriceResult = {
13
+ marketPrice: number;
14
+ skewImpactP: number;
15
+ oraclePrice: number;
16
+ };
17
+ export type MarketPriceContext = {
18
+ skewDepth: number;
19
+ pairOiToken: {
20
+ oiLongToken: number;
21
+ oiShortToken: number;
22
+ };
23
+ };
24
+ /**
25
+ * @dev Types for signed prices data structure
26
+ */
27
+ export type SignedPricesResponse = {
28
+ signedData: SignedPrices;
29
+ missingPrices: number[];
30
+ };
31
+ export type SignedPrices = {
32
+ signerId: number;
33
+ expiryTs: number;
34
+ fromBlock: number;
35
+ isLookback: boolean;
36
+ pairIndices: number[];
37
+ prices: Price[];
38
+ signature: string;
39
+ };
40
+ export type Price = {
41
+ open: string;
42
+ high: string;
43
+ low: string;
44
+ current: string;
45
+ ts: number;
46
+ };
47
+ export type Oracle = {
48
+ url: string;
49
+ key?: string;
50
+ };
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Market price types for calculating price with skew impact
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });