@gainsnetwork/sdk 1.4.5 → 1.5.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 (110) hide show
  1. package/lib/backend/tradingVariables/backend.types.d.ts +11 -4
  2. package/lib/backend/tradingVariables/converter.d.ts +7 -3
  3. package/lib/backend/tradingVariables/converter.js +15 -7
  4. package/lib/backend/tradingVariables/index.js +5 -2
  5. package/lib/backend/tradingVariables/types.d.ts +4 -2
  6. package/lib/contracts/addresses.d.ts +1 -1
  7. package/lib/contracts/addresses.js +6 -5
  8. package/lib/contracts/addresses.json +29 -0
  9. package/lib/contracts/types/generated/GFarmTradingStorageV5.d.ts +1911 -0
  10. package/lib/contracts/types/generated/GFarmTradingStorageV5.js +2 -0
  11. package/lib/contracts/types/generated/GNSBorrowingFees.d.ts +1067 -0
  12. package/lib/contracts/types/generated/GNSBorrowingFees.js +2 -0
  13. package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.d.ts +979 -0
  14. package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.js +2 -0
  15. package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.d.ts +1058 -0
  16. package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.js +2 -0
  17. package/lib/contracts/types/generated/GNSMultiCollatDiamond.d.ts +223 -40
  18. package/lib/contracts/types/generated/GNSNftRewardsV6.d.ts +533 -0
  19. package/lib/contracts/types/generated/GNSNftRewardsV6.js +2 -0
  20. package/lib/contracts/types/generated/GNSNftRewardsV6_3_1.d.ts +613 -0
  21. package/lib/contracts/types/generated/GNSNftRewardsV6_3_1.js +2 -0
  22. package/lib/contracts/types/generated/GNSPairInfosV6_1.d.ts +911 -0
  23. package/lib/contracts/types/generated/GNSPairInfosV6_1.js +2 -0
  24. package/lib/contracts/types/generated/GNSPairsStorageV6.d.ts +660 -0
  25. package/lib/contracts/types/generated/GNSPairsStorageV6.js +2 -0
  26. package/lib/contracts/types/generated/GNSTrading.d.ts +758 -0
  27. package/lib/contracts/types/generated/GNSTrading.js +2 -0
  28. package/lib/contracts/types/generated/GNSTradingCallbacks.d.ts +875 -0
  29. package/lib/contracts/types/generated/GNSTradingCallbacks.js +2 -0
  30. package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.d.ts +806 -0
  31. package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.js +2 -0
  32. package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.d.ts +821 -0
  33. package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.js +2 -0
  34. package/lib/contracts/types/generated/GNSTradingStorage.d.ts +1387 -0
  35. package/lib/contracts/types/generated/GNSTradingStorage.js +2 -0
  36. package/lib/contracts/types/generated/GTokenV6_3_2.d.ts +1838 -0
  37. package/lib/contracts/types/generated/GTokenV6_3_2.js +2 -0
  38. package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.d.ts +83 -0
  39. package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.js +2691 -0
  40. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.d.ts +88 -0
  41. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.js +1654 -0
  42. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.d.ts +113 -0
  43. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.js +1742 -0
  44. package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.d.ts +124 -0
  45. package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.js +1784 -0
  46. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.js +312 -36
  47. package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.d.ts +100 -0
  48. package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.js +1116 -0
  49. package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.d.ts +100 -0
  50. package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.js +1003 -0
  51. package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.d.ts +98 -0
  52. package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.js +1485 -0
  53. package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.d.ts +117 -0
  54. package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.js +1265 -0
  55. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.d.ts +82 -0
  56. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.js +1273 -0
  57. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.d.ts +82 -0
  58. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.js +1326 -0
  59. package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.d.ts +113 -0
  60. package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.js +1428 -0
  61. package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.d.ts +96 -0
  62. package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.js +2241 -0
  63. package/lib/contracts/types/generated/factories/GNSTrading__factory.d.ts +95 -0
  64. package/lib/contracts/types/generated/factories/GNSTrading__factory.js +1071 -0
  65. package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.d.ts +110 -0
  66. package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.js +2682 -0
  67. package/lib/contracts/utils/pairs.d.ts +13 -2
  68. package/lib/contracts/utils/pairs.js +70 -11
  69. package/lib/index.d.ts +1 -0
  70. package/lib/index.js +1 -0
  71. package/lib/markets/oi/fetcher.d.ts +58 -0
  72. package/lib/markets/oi/fetcher.js +181 -0
  73. package/lib/markets/oi/validation.d.ts +80 -0
  74. package/lib/markets/oi/validation.js +172 -0
  75. package/lib/pricing/depthBands/converter.d.ts +65 -0
  76. package/lib/pricing/depthBands/converter.js +155 -0
  77. package/lib/pricing/depthBands/decoder.d.ts +32 -0
  78. package/lib/pricing/depthBands/decoder.js +109 -0
  79. package/lib/pricing/depthBands/encoder.d.ts +19 -0
  80. package/lib/pricing/depthBands/encoder.js +105 -0
  81. package/lib/pricing/depthBands/index.d.ts +8 -0
  82. package/lib/pricing/depthBands/index.js +26 -0
  83. package/lib/pricing/depthBands/types.d.ts +49 -0
  84. package/lib/pricing/depthBands/types.js +10 -0
  85. package/lib/pricing/depthBands/validator.d.ts +22 -0
  86. package/lib/pricing/depthBands/validator.js +113 -0
  87. package/lib/pricing/depthBands.d.ts +39 -0
  88. package/lib/pricing/depthBands.js +94 -0
  89. package/lib/pricing/index.d.ts +4 -0
  90. package/lib/pricing/index.js +20 -0
  91. package/lib/trade/effectiveLeverage/builder.d.ts +23 -0
  92. package/lib/trade/effectiveLeverage/builder.js +30 -0
  93. package/lib/trade/fees/borrowingV2/fetcher.d.ts +0 -1
  94. package/lib/trade/fees/holdingFees/index.d.ts +46 -0
  95. package/lib/trade/fees/holdingFees/index.js +105 -0
  96. package/lib/trade/fees/holdingFees/types.d.ts +23 -0
  97. package/lib/trade/fees/holdingFees/types.js +5 -0
  98. package/lib/trade/fees/trading/holdingFees.d.ts +28 -0
  99. package/lib/trade/fees/trading/holdingFees.js +66 -0
  100. package/lib/trade/fees/trading/holdingFeesStructured.d.ts +28 -0
  101. package/lib/trade/fees/trading/holdingFeesStructured.js +66 -0
  102. package/lib/trade/priceImpact/cumulVol/builder.js +4 -2
  103. package/lib/trade/priceImpact/cumulVol/converter.d.ts +63 -0
  104. package/lib/trade/priceImpact/cumulVol/converter.js +97 -1
  105. package/lib/trade/priceImpact/cumulVol/index.d.ts +7 -6
  106. package/lib/trade/priceImpact/cumulVol/index.js +135 -32
  107. package/lib/trade/priceImpact/cumulVol/types.d.ts +11 -0
  108. package/lib/trade/priceImpact/cumulVol/types.js +2 -0
  109. package/lib/trade/priceImpact/open/index.js +3 -0
  110. package/package.json +1 -1
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Holding fees calculation for structured contexts
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getTradePendingHoldingFeesCollateralStructured = void 0;
7
+ const types_1 = require("../../../contracts/types");
8
+ const borrowing_1 = require("../borrowing");
9
+ const borrowingV2_1 = require("../borrowingV2");
10
+ const fundingFees_1 = require("../fundingFees");
11
+ /**
12
+ * @dev Calculates total holding fees using structured context
13
+ * @param trade The trade to calculate fees for
14
+ * @param tradeInfo Trade info containing contracts version
15
+ * @param tradeFeesData Trade fees data containing initial acc fees
16
+ * @param currentPairPrice Current pair price
17
+ * @param context Structured context with sub-contexts for each fee type
18
+ * @returns Object containing all holding fee components
19
+ */
20
+ const getTradePendingHoldingFeesCollateralStructured = (trade, tradeInfo, tradeFeesData, currentPairPrice, context) => {
21
+ const positionSizeCollateral = trade.collateralAmount * trade.leverage;
22
+ // Calculate funding fees (v10+ only)
23
+ let fundingFeeCollateral = 0;
24
+ if (context.contractsVersion >= types_1.ContractsVersion.V10 &&
25
+ context.funding &&
26
+ tradeFeesData.initialAccFundingFeeP !== undefined) {
27
+ fundingFeeCollateral = (0, fundingFees_1.getTradeFundingFeesCollateral)(trade, tradeInfo, tradeFeesData, currentPairPrice, Object.assign(Object.assign({}, context.funding), { currentTimestamp: context.currentTimestamp }) // TODO: Fix types once funding types are properly imported
28
+ );
29
+ }
30
+ // Calculate borrowing fees v2
31
+ let borrowingFeeCollateral = 0;
32
+ if (context.borrowingV2 &&
33
+ tradeFeesData.initialAccBorrowingFeeP !== undefined) {
34
+ borrowingFeeCollateral = (0, borrowingV2_1.getTradeBorrowingFeesCollateral)({
35
+ positionSizeCollateral,
36
+ openPrice: trade.openPrice,
37
+ currentPairPrice,
38
+ initialAccBorrowingFeeP: tradeFeesData.initialAccBorrowingFeeP,
39
+ currentTimestamp: context.currentTimestamp,
40
+ }, context.borrowingV2);
41
+ }
42
+ // Calculate v1 borrowing fees (some markets use v1 indefinitely)
43
+ let borrowingFeeCollateral_old = 0;
44
+ if (context.borrowingV1) {
45
+ borrowingFeeCollateral_old = (0, borrowing_1.getBorrowingFee)(positionSizeCollateral, undefined, // pairIndex not needed for pair-specific context
46
+ trade.long, context.borrowingV1.initialAccFees || {
47
+ accPairFee: 0,
48
+ accGroupFee: 0,
49
+ block: 0,
50
+ }, {
51
+ currentBlock: context.borrowingV1.currentBlock,
52
+ group: context.borrowingV1.group,
53
+ pair: context.borrowingV1.pair,
54
+ collateralPriceUsd: context.collateralPriceUsd,
55
+ });
56
+ }
57
+ return {
58
+ fundingFeeCollateral,
59
+ borrowingFeeCollateral,
60
+ borrowingFeeCollateral_old,
61
+ totalFeeCollateral: fundingFeeCollateral +
62
+ borrowingFeeCollateral +
63
+ borrowingFeeCollateral_old,
64
+ };
65
+ };
66
+ exports.getTradePendingHoldingFeesCollateralStructured = getTradePendingHoldingFeesCollateralStructured;
@@ -15,7 +15,8 @@ const buildCumulVolContext = (globalTradingVariables, collateralIndex, pairIndex
15
15
  return undefined;
16
16
  }
17
17
  // Get pair-specific data from global variables
18
- const pairDepth = globalTradingVariables.pairDepths?.[pairIndex];
18
+ const pairDepthBands = globalTradingVariables.pairDepthBands?.[pairIndex];
19
+ const depthBandsMapping = globalTradingVariables.depthBandsMapping;
19
20
  const pairFactor = globalTradingVariables.pairFactors?.[pairIndex];
20
21
  const oiWindows = globalTradingVariables.oiWindows?.[pairIndex];
21
22
  // Get OI windows settings (same for all pairs)
@@ -38,7 +39,8 @@ const buildCumulVolContext = (globalTradingVariables, collateralIndex, pairIndex
38
39
  contractsVersion: additionalParams.contractsVersion,
39
40
  protectionCloseFactorWhitelist,
40
41
  // Price impact data
41
- pairDepth,
42
+ pairDepthBands,
43
+ depthBandsMapping,
42
44
  oiWindowsSettings,
43
45
  oiWindows,
44
46
  // User/collateral specific
@@ -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,7 +2,8 @@
2
2
  * @dev Cumulative volume price impact calculations
3
3
  * @dev Mirrors contract's getTradeCumulVolPriceImpactP functionality
4
4
  */
5
- import { LiquidationParams, OiWindows, OiWindowsSettings, PairDepth, PairFactor, UserPriceImpact } from "../../types";
5
+ import { PairDepthBands, DepthBandsMapping } from "./types";
6
+ import { LiquidationParams, OiWindows, OiWindowsSettings, PairFactor, UserPriceImpact } from "../../types";
6
7
  import { ContractsVersion } from "../../../contracts/types";
7
8
  export type CumulVolContext = {
8
9
  isOpen?: boolean;
@@ -12,9 +13,10 @@ export type CumulVolContext = {
12
13
  currentBlock?: number | undefined;
13
14
  contractsVersion?: ContractsVersion | undefined;
14
15
  protectionCloseFactorWhitelist?: boolean;
15
- pairDepth?: PairDepth | undefined;
16
16
  oiWindowsSettings?: OiWindowsSettings | undefined;
17
17
  oiWindows?: OiWindows | undefined;
18
+ pairDepthBands?: PairDepthBands | undefined;
19
+ depthBandsMapping?: DepthBandsMapping | undefined;
18
20
  userPriceImpact?: UserPriceImpact | undefined;
19
21
  collateralPriceUsd?: number;
20
22
  } & Partial<PairFactor>;
@@ -55,7 +57,7 @@ export declare const getLegacyFactor: (context: CumulVolContext | undefined) =>
55
57
  * @param context Additional context with depths, OI data, and factors
56
58
  * @returns Cumulative volume price impact percentage (not including spread)
57
59
  */
58
- export declare const getTradeCumulVolPriceImpactP: (trader: string, pairIndex: number, long: boolean, tradeOpenInterestUsd: number, isPnlPositive: boolean, open: boolean, lastPosIncreaseBlock: number, context: CumulVolContext) => number;
60
+ export declare const getTradeCumulVolPriceImpactP: (_trader: string, _pairIndex: number, long: boolean, tradeOpenInterestUsd: number, isPnlPositive: boolean, open: boolean, lastPosIncreaseBlock: number, context: CumulVolContext) => number;
59
61
  /**
60
62
  * @dev Gets the fixed spread percentage with direction
61
63
  * @dev Mirrors contract's getFixedSpreadP function
@@ -83,13 +85,12 @@ export declare const getSpreadP: (pairSpreadP: number | undefined, isLiquidation
83
85
  * @param buy True for long, false for short
84
86
  * @param collateral Collateral amount
85
87
  * @param leverage Position leverage
86
- * @param pairDepth 1% depth values for the pair
87
88
  * @param oiWindowsSettings OI windows configuration
88
89
  * @param oiWindows Current OI windows data
89
90
  * @param context Additional context for the calculation
90
91
  * @returns Total spread + cumulative volume price impact percentage
91
92
  */
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
+ export declare const getSpreadWithCumulVolPriceImpactP: (pairSpreadP: number, buy: boolean, collateral: number, leverage: number, context: CumulVolContext) => number;
93
94
  /**
94
95
  * @dev Convenience function for calculating cumulative volume price impact
95
96
  * @dev Uses collateral and leverage instead of USD position size
@@ -103,6 +104,6 @@ export declare const getSpreadWithCumulVolPriceImpactP: (pairSpreadP: number, bu
103
104
  export declare const getCumulVolPriceImpact: (buy: boolean, collateral: number, leverage: number, open: boolean, context: CumulVolContext & {
104
105
  collateralPriceUsd: number;
105
106
  }) => 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 declare const getSpreadWithPriceImpactP: (pairSpreadP: number, buy: boolean, collateral: number, leverage: number, context: CumulVolContext) => number;
107
108
  export { convertOiWindowsSettings, convertOiWindow, convertOiWindows, convertOiWindowsSettingsArray, } from "./converter";
108
109
  export { buildCumulVolContext } from "./builder";
@@ -73,6 +73,108 @@ const getLegacyFactor = (context) => {
73
73
  return context?.contractsVersion === types_1.ContractsVersion.BEFORE_V9_2 ? 1 : 2;
74
74
  };
75
75
  exports.getLegacyFactor = getLegacyFactor;
76
+ /**
77
+ * @dev Mirrors contract's _calculateDepthBandsPriceImpact function
78
+ * @param tradeSizeUsd Trade size in USD (always positive here)
79
+ * @param depthBandParams Depth band parameters
80
+ * @returns Price impact percentage
81
+ */
82
+ const _calculateDepthBandsPriceImpact = (tradeSizeUsd, depthBandParams) => {
83
+ console.log("tradeSizeUsd", tradeSizeUsd);
84
+ console.log("depthBandParams", depthBandParams);
85
+ const totalDepthUsd = depthBandParams.depthBands.totalDepthUsd;
86
+ if (totalDepthUsd === 0 || tradeSizeUsd === 0)
87
+ return 0;
88
+ let remainingSizeUsd = tradeSizeUsd;
89
+ let totalWeightedPriceImpactP = 0;
90
+ let prevBandDepthUsd = 0;
91
+ let topOfPrevBandOffsetPpm = 0;
92
+ for (let i = 0; i < 30 && remainingSizeUsd !== 0; i++) {
93
+ const bandLiquidityPercentageBps = depthBandParams.depthBands.bands[i]; // Already in 0-1 format
94
+ const topOfBandOffsetPpm = depthBandParams.depthBandsMapping.bands[i]; // Already in 0-1 format
95
+ const bandDepthUsd = bandLiquidityPercentageBps * totalDepthUsd;
96
+ console.log("bandDepthUsd", bandDepthUsd);
97
+ // Skip if band has same depth as previous (would cause division by zero)
98
+ if (bandDepthUsd <= prevBandDepthUsd) {
99
+ console.log("Skipping band");
100
+ prevBandDepthUsd = bandDepthUsd;
101
+ topOfPrevBandOffsetPpm = topOfBandOffsetPpm;
102
+ continue;
103
+ }
104
+ // Since bandDepthUsd represents liquidity from mid price to top of band, we need to subtract previous band depth
105
+ const bandAvailableDepthUsd = bandDepthUsd - prevBandDepthUsd;
106
+ console.log("bandAvailableDepthUsd", bandAvailableDepthUsd);
107
+ let depthConsumedUsd;
108
+ // At 100% band always consume all remaining size, even if more than band available depth
109
+ if (bandLiquidityPercentageBps === 1 ||
110
+ remainingSizeUsd <= bandAvailableDepthUsd) {
111
+ depthConsumedUsd = remainingSizeUsd;
112
+ remainingSizeUsd = 0;
113
+ console.log("Consumed all remaining size");
114
+ }
115
+ else {
116
+ // Normal case: consume entire band and continue to next
117
+ depthConsumedUsd = bandAvailableDepthUsd;
118
+ remainingSizeUsd -= bandAvailableDepthUsd;
119
+ console.log("Consumed entire band");
120
+ }
121
+ // Calculate impact contribution from this band using trapezoidal rule
122
+ // Low = previous band's price offset, High = current band's price offset
123
+ const lowOffsetP = topOfPrevBandOffsetPpm;
124
+ const offsetRangeP = topOfBandOffsetPpm - topOfPrevBandOffsetPpm;
125
+ console.log("lowOffsetP", lowOffsetP);
126
+ console.log("offsetRangeP", offsetRangeP);
127
+ console.log("depthConsumedUsd", depthConsumedUsd);
128
+ console.log("bandAvailableDepthUsd", bandAvailableDepthUsd);
129
+ // Calculate average impact using trapezoidal rule: low + (range * fraction / 2)
130
+ const avgImpactP = lowOffsetP +
131
+ (offsetRangeP * depthConsumedUsd) / bandAvailableDepthUsd / 2;
132
+ console.log("avgImpactP", avgImpactP);
133
+ totalWeightedPriceImpactP += avgImpactP * depthConsumedUsd;
134
+ console.log("totalWeightedPriceImpactP", totalWeightedPriceImpactP);
135
+ // Update previous values for next iteration
136
+ topOfPrevBandOffsetPpm = topOfBandOffsetPpm;
137
+ prevBandDepthUsd = bandDepthUsd;
138
+ }
139
+ console.log("totalWeightedPriceImpactP", totalWeightedPriceImpactP);
140
+ console.log("tradeSizeUsd", tradeSizeUsd);
141
+ return totalWeightedPriceImpactP / tradeSizeUsd;
142
+ };
143
+ /**
144
+ * @dev Mirrors contract's _getDepthBandsPriceImpactP function
145
+ * @param cumulativeVolumeUsd Cumulative volume in USD (can be negative)
146
+ * @param tradeSizeUsd Trade size in USD (can be negative)
147
+ * @param depthBandParams Depth band parameters (contains both pair bands and global mapping)
148
+ * @param priceImpactFactor Price impact factor (protection close factor)
149
+ * @param cumulativeFactor Cumulative factor for volume impact
150
+ * @returns Price impact percentage (can be negative)
151
+ */
152
+ const _getDepthBandsPriceImpactP = (cumulativeVolumeUsd, tradeSizeUsd, depthBandParams, priceImpactFactor, cumulativeFactor) => {
153
+ // Check for opposite signs
154
+ if ((cumulativeVolumeUsd > 0 && tradeSizeUsd < 0) ||
155
+ (cumulativeVolumeUsd < 0 && tradeSizeUsd > 0)) {
156
+ throw new Error("Wrong params: cumulative volume and trade size have opposite signs");
157
+ }
158
+ const effectiveCumulativeVolumeUsd = cumulativeVolumeUsd * cumulativeFactor;
159
+ const totalSizeLookupUsd = effectiveCumulativeVolumeUsd + tradeSizeUsd;
160
+ const isNegative = totalSizeLookupUsd < 0;
161
+ const effectiveCumulativeVolumeUsdUint = isNegative
162
+ ? -effectiveCumulativeVolumeUsd
163
+ : effectiveCumulativeVolumeUsd;
164
+ const totalSizeLookupUsdUint = isNegative
165
+ ? -totalSizeLookupUsd
166
+ : totalSizeLookupUsd;
167
+ console.log("effectiveCumulativeVolumeUsdUint", effectiveCumulativeVolumeUsdUint);
168
+ console.log("totalSizeLookupUsdUint", totalSizeLookupUsdUint);
169
+ const cumulativeVolPriceImpactP = _calculateDepthBandsPriceImpact(effectiveCumulativeVolumeUsdUint, depthBandParams);
170
+ const totalSizePriceImpactP = _calculateDepthBandsPriceImpact(totalSizeLookupUsdUint, depthBandParams);
171
+ console.log("cumulativeVolPriceImpactP", cumulativeVolPriceImpactP);
172
+ console.log("totalSizePriceImpactP", totalSizePriceImpactP);
173
+ const unscaledPriceImpactP = cumulativeVolPriceImpactP +
174
+ (totalSizePriceImpactP - cumulativeVolPriceImpactP) / 2;
175
+ const scaledPriceImpactP = unscaledPriceImpactP * priceImpactFactor;
176
+ return isNegative ? -scaledPriceImpactP : scaledPriceImpactP;
177
+ };
76
178
  /**
77
179
  * @dev Calculates cumulative volume price impact percentage
78
180
  * @dev Mirrors contract's getTradeCumulVolPriceImpactP function
@@ -86,7 +188,9 @@ exports.getLegacyFactor = getLegacyFactor;
86
188
  * @param context Additional context with depths, OI data, and factors
87
189
  * @returns Cumulative volume price impact percentage (not including spread)
88
190
  */
89
- const getTradeCumulVolPriceImpactP = (trader, pairIndex, long, tradeOpenInterestUsd, isPnlPositive, open, lastPosIncreaseBlock, context) => {
191
+ const getTradeCumulVolPriceImpactP = (_trader, // Unused - kept for compatibility
192
+ _pairIndex, // Unused - kept for compatibility
193
+ long, tradeOpenInterestUsd, isPnlPositive, open, lastPosIncreaseBlock, context) => {
90
194
  // Update context with passed parameters
91
195
  const updatedContext = {
92
196
  ...context,
@@ -104,34 +208,43 @@ const getTradeCumulVolPriceImpactP = (trader, pairIndex, long, tradeOpenInterest
104
208
  (!open &&
105
209
  context?.exemptAfterProtectionCloseFactor === true &&
106
210
  (0, exports.isProtectionCloseFactorActive)(updatedContext) !== true)) {
211
+ console.log("No price impact, protection close factor");
107
212
  return 0;
108
213
  }
109
- // Calculate trade skew direction (matches Solidity logic)
110
214
  const tradePositiveSkew = (long && open) || (!long && !open);
111
215
  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
115
- const onePercentDepth = tradePositiveSkew
116
- ? context.pairDepth?.onePercentDepthAboveUsd
117
- : context.pairDepth?.onePercentDepthBelowUsd;
118
- let activeOi = undefined;
119
- if (context.oiWindowsSettings !== undefined) {
120
- activeOi = (0, oiWindows_1.getActiveOi)((0, oiWindows_1.getCurrentOiWindowId)(context.oiWindowsSettings), context.oiWindowsSettings.windowsCount, context.oiWindows, open ? long : !long);
216
+ console.log("bands", context.pairDepthBands);
217
+ console.log("mapping", context.depthBandsMapping);
218
+ if (!context.pairDepthBands || !context.depthBandsMapping) {
219
+ console.log("No price impact, bands");
220
+ return 0;
121
221
  }
122
- if (!onePercentDepth || activeOi === undefined) {
222
+ // Select depth bands based on trade direction
223
+ const depthBands = tradePositiveSkew
224
+ ? context.pairDepthBands.above
225
+ : context.pairDepthBands.below;
226
+ // Return 0 if no depth bands configured (matching contract lines 588-590)
227
+ if (!depthBands || depthBands.totalDepthUsd === 0) {
228
+ console.log("No price impact, depth bands");
123
229
  return 0;
124
230
  }
125
- // Apply trade skew multiplier to match Solidity's signed calculation
231
+ // Get active OI for cumulative volume calculation
232
+ let activeOi = 0;
233
+ if (context.oiWindowsSettings !== undefined) {
234
+ activeOi =
235
+ (0, oiWindows_1.getActiveOi)((0, oiWindows_1.getCurrentOiWindowId)(context.oiWindowsSettings), context.oiWindowsSettings.windowsCount, context.oiWindows, open ? long : !long) || 0;
236
+ }
237
+ console.log("activeOi", activeOi);
126
238
  const signedActiveOi = activeOi * tradeSkewMultiplier;
127
239
  const signedTradeOi = tradeOpenInterestUsd * tradeSkewMultiplier;
128
- // Calculate impact with proper signs (matching Solidity's _getTradePriceImpactP)
129
- const finalPriceImpactP = ((signedActiveOi * (0, exports.getCumulativeFactor)(updatedContext) +
130
- signedTradeOi / 2) /
131
- onePercentDepth /
132
- (0, exports.getLegacyFactor)(updatedContext)) *
133
- (0, exports.getProtectionCloseFactor)(updatedContext);
134
- return finalPriceImpactP;
240
+ console.log("signedActiveOi", signedActiveOi);
241
+ console.log("signedTradeOi", signedTradeOi);
242
+ // Calculate price impact using depth bands
243
+ const priceImpactP = _getDepthBandsPriceImpactP(signedActiveOi, signedTradeOi, {
244
+ depthBands: depthBands,
245
+ depthBandsMapping: context.depthBandsMapping,
246
+ }, (0, exports.getProtectionCloseFactor)(updatedContext), (0, exports.getCumulativeFactor)(updatedContext));
247
+ return priceImpactP;
135
248
  };
136
249
  exports.getTradeCumulVolPriceImpactP = getTradeCumulVolPriceImpactP;
137
250
  /**
@@ -182,13 +295,12 @@ exports.getSpreadP = getSpreadP;
182
295
  * @param buy True for long, false for short
183
296
  * @param collateral Collateral amount
184
297
  * @param leverage Position leverage
185
- * @param pairDepth 1% depth values for the pair
186
298
  * @param oiWindowsSettings OI windows configuration
187
299
  * @param oiWindows Current OI windows data
188
300
  * @param context Additional context for the calculation
189
301
  * @returns Total spread + cumulative volume price impact percentage
190
302
  */
191
- const getSpreadWithCumulVolPriceImpactP = (pairSpreadP, buy, collateral, leverage, pairDepth, oiWindowsSettings, oiWindows, context) => {
303
+ const getSpreadWithCumulVolPriceImpactP = (pairSpreadP, buy, collateral, leverage, context) => {
192
304
  if (pairSpreadP === undefined) {
193
305
  return 0;
194
306
  }
@@ -197,16 +309,7 @@ const getSpreadWithCumulVolPriceImpactP = (pairSpreadP, buy, collateral, leverag
197
309
  const positionSizeUsd = collateral * leverage * (context?.collateralPriceUsd || 1);
198
310
  const cumulVolImpact = (0, exports.getTradeCumulVolPriceImpactP)("", // trader - not used in calculation
199
311
  0, // pairIndex - not used in calculation
200
- buy, positionSizeUsd, context?.isPnlPositive || false, context?.isOpen !== false, context?.createdBlock || 0, {
201
- ...context,
202
- pairDepth,
203
- oiWindowsSettings,
204
- oiWindows,
205
- });
206
- // If no depth or OI data, return just half spread
207
- if (cumulVolImpact === 0 && (!pairDepth || !oiWindowsSettings)) {
208
- return pairSpreadP / 2;
209
- }
312
+ buy, positionSizeUsd, context?.isPnlPositive || false, context?.isOpen !== false, context?.createdBlock || 0, context);
210
313
  return baseSpread + cumulVolImpact;
211
314
  };
212
315
  exports.getSpreadWithCumulVolPriceImpactP = getSpreadWithCumulVolPriceImpactP;
@@ -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 });
@@ -23,14 +23,17 @@ const getTradeOpeningPriceImpact = (input, context) => {
23
23
  // Calculate fixed spread
24
24
  const spreadP = (0, cumulVol_1.getFixedSpreadP)(input.pairSpreadP, input.long, true // opening
25
25
  );
26
+ console.log("spreadP", spreadP);
26
27
  // Calculate position size in USD
27
28
  const positionSizeUsd = positionSizeCollateral * context.collateralPriceUsd;
29
+ console.log("positionSizeUsd", positionSizeUsd);
28
30
  // Calculate cumulative volume price impact
29
31
  const cumulVolPriceImpactP = (0, cumulVol_1.getTradeCumulVolPriceImpactP)("", // trader - not needed for calculation
30
32
  input.pairIndex, input.long, positionSizeUsd, false, // isPnlPositive - not relevant for opening
31
33
  true, // open
32
34
  0, // lastPosIncreaseBlock - not relevant for opening
33
35
  context.cumulVolContext);
36
+ console.log("cumulVolPriceImpactP", cumulVolPriceImpactP);
34
37
  // Calculate price after spread and cumulative volume impact (before skew)
35
38
  const priceAfterSpreadAndCumulVolPriceImpact = (0, __1.getPriceAfterImpact)(input.openPrice, spreadP + cumulVolPriceImpactP);
36
39
  // Calculate position size in tokens using the price after fixed spread and cumul vol impact
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gainsnetwork/sdk",
3
- "version": "1.4.5",
3
+ "version": "1.5.0-rc1",
4
4
  "description": "Gains Network SDK",
5
5
  "main": "./lib/index.js",
6
6
  "files": [