@gainsnetwork/sdk 0.2.67-rc6 → 0.2.67-rc8

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.d.ts +11 -0
  2. package/lib/backend/globalTrades/index.js +69 -0
  3. package/lib/backend/index.d.ts +3 -0
  4. package/lib/backend/index.js +28 -0
  5. package/lib/backend/tradingVariables/backend.types.d.ts +312 -0
  6. package/lib/backend/tradingVariables/backend.types.js +2 -0
  7. package/lib/backend/tradingVariables/converter.d.ts +31 -0
  8. package/lib/backend/tradingVariables/converter.js +330 -0
  9. package/lib/backend/tradingVariables/index.d.ts +5 -0
  10. package/lib/backend/tradingVariables/index.js +95 -0
  11. package/lib/backend/tradingVariables/types.d.ts +109 -0
  12. package/lib/backend/tradingVariables/types.js +14 -0
  13. package/lib/constants.js +2 -3
  14. package/lib/contracts/types/generated/GFarmTradingStorageV5.d.ts +1911 -0
  15. package/lib/contracts/types/generated/GFarmTradingStorageV5.js +2 -0
  16. package/lib/contracts/types/generated/GNSBorrowingFees.d.ts +1067 -0
  17. package/lib/contracts/types/generated/GNSBorrowingFees.js +2 -0
  18. package/lib/contracts/types/generated/GNSMultiCollatDiamond.d.ts +2140 -286
  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/GNSTrading.d.ts +758 -0
  24. package/lib/contracts/types/generated/GNSTrading.js +2 -0
  25. package/lib/contracts/types/generated/GNSTradingCallbacks.d.ts +875 -0
  26. package/lib/contracts/types/generated/GNSTradingCallbacks.js +2 -0
  27. package/lib/contracts/types/generated/GNSTradingStorage.d.ts +1387 -0
  28. package/lib/contracts/types/generated/GNSTradingStorage.js +2 -0
  29. package/lib/contracts/types/generated/GToken.d.ts +78 -107
  30. package/lib/contracts/types/generated/GTokenV6_3_2.d.ts +1838 -0
  31. package/lib/contracts/types/generated/GTokenV6_3_2.js +2 -0
  32. package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.d.ts +83 -0
  33. package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.js +2691 -0
  34. package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.d.ts +124 -0
  35. package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.js +1784 -0
  36. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.d.ts +90 -53
  37. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.js +4502 -427
  38. package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.d.ts +100 -0
  39. package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.js +1116 -0
  40. package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.d.ts +100 -0
  41. package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.js +1003 -0
  42. package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.d.ts +113 -0
  43. package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.js +1428 -0
  44. package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.d.ts +96 -0
  45. package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.js +2241 -0
  46. package/lib/contracts/types/generated/factories/GNSTrading__factory.d.ts +95 -0
  47. package/lib/contracts/types/generated/factories/GNSTrading__factory.js +1071 -0
  48. package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.d.ts +110 -0
  49. package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.js +2682 -0
  50. package/lib/contracts/types/generated/factories/GToken__factory.js +65 -142
  51. package/lib/contracts/utils/openLimitOrders.d.ts +8 -0
  52. package/lib/contracts/utils/openLimitOrders.js +88 -0
  53. package/lib/markets/collateral/converter.d.ts +5 -0
  54. package/lib/markets/collateral/converter.js +11 -0
  55. package/lib/markets/collateral/index.d.ts +1 -0
  56. package/lib/markets/collateral/index.js +17 -0
  57. package/lib/markets/collateral/types.d.ts +7 -0
  58. package/lib/markets/collateral/types.js +2 -0
  59. package/lib/markets/oi/converter.d.ts +63 -0
  60. package/lib/markets/oi/converter.js +103 -0
  61. package/lib/markets/oi/fetcher.d.ts +58 -0
  62. package/lib/markets/oi/fetcher.js +181 -0
  63. package/lib/markets/oi/index.d.ts +10 -0
  64. package/lib/markets/oi/index.js +37 -0
  65. package/lib/markets/oi/types.d.ts +82 -0
  66. package/lib/markets/oi/types.js +6 -0
  67. package/lib/markets/oi/validation.d.ts +80 -0
  68. package/lib/markets/oi/validation.js +172 -0
  69. package/lib/trade/fees/borrowing/builder.d.ts +14 -0
  70. package/lib/trade/fees/borrowing/builder.js +33 -0
  71. package/lib/trade/fees/borrowingV2/builder.d.ts +6 -0
  72. package/lib/trade/fees/borrowingV2/builder.js +24 -0
  73. package/lib/trade/fees/borrowingV2/converter.d.ts +75 -0
  74. package/lib/trade/fees/borrowingV2/converter.js +132 -0
  75. package/lib/trade/fees/borrowingV2/fetcher.d.ts +75 -0
  76. package/lib/trade/fees/borrowingV2/fetcher.js +185 -0
  77. package/lib/trade/fees/borrowingV2/index.d.ts +48 -0
  78. package/lib/trade/fees/borrowingV2/index.js +112 -0
  79. package/lib/trade/fees/borrowingV2/types.d.ts +95 -0
  80. package/lib/trade/fees/borrowingV2/types.js +5 -0
  81. package/lib/trade/fees/converter.d.ts +48 -0
  82. package/lib/trade/fees/converter.js +110 -0
  83. package/lib/trade/fees/fundingFees/builder.d.ts +9 -0
  84. package/lib/trade/fees/fundingFees/builder.js +35 -0
  85. package/lib/trade/fees/fundingFees/converter.d.ts +102 -0
  86. package/lib/trade/fees/fundingFees/converter.js +196 -0
  87. package/lib/trade/fees/fundingFees/fetcher.d.ts +66 -0
  88. package/lib/trade/fees/fundingFees/fetcher.js +150 -0
  89. package/lib/trade/fees/fundingFees/index.d.ts +146 -0
  90. package/lib/trade/fees/fundingFees/index.js +346 -0
  91. package/lib/trade/fees/fundingFees/pairContext.d.ts +33 -0
  92. package/lib/trade/fees/fundingFees/pairContext.js +17 -0
  93. package/lib/trade/fees/fundingFees/types.d.ts +77 -0
  94. package/lib/trade/fees/fundingFees/types.js +5 -0
  95. package/lib/trade/fees/tiers/converter.d.ts +54 -0
  96. package/lib/trade/fees/tiers/converter.js +81 -0
  97. package/lib/trade/fees/trading/builder.d.ts +18 -0
  98. package/lib/trade/fees/trading/builder.js +20 -0
  99. package/lib/trade/fees/trading/converter.d.ts +30 -0
  100. package/lib/trade/fees/trading/converter.js +43 -0
  101. package/lib/trade/fees/trading/index.d.ts +62 -0
  102. package/lib/trade/fees/trading/index.js +155 -0
  103. package/lib/trade/fees/trading/types.d.ts +48 -0
  104. package/lib/trade/fees/trading/types.js +5 -0
  105. package/lib/trade/liquidation/builder.d.ts +25 -0
  106. package/lib/trade/liquidation/builder.js +59 -0
  107. package/lib/trade/liquidation/converter.d.ts +23 -0
  108. package/lib/trade/liquidation/converter.js +46 -0
  109. package/lib/trade/liquidation/index.d.ts +26 -0
  110. package/lib/trade/liquidation/index.js +142 -0
  111. package/lib/trade/liquidation/types.d.ts +59 -0
  112. package/lib/trade/liquidation/types.js +2 -0
  113. package/lib/trade/openLimitOrder.d.ts +2 -0
  114. package/lib/trade/openLimitOrder.js +23 -0
  115. package/lib/trade/pnl/builder.d.ts +16 -0
  116. package/lib/trade/pnl/builder.js +44 -0
  117. package/lib/trade/pnl/converter.d.ts +47 -0
  118. package/lib/trade/pnl/converter.js +72 -0
  119. package/lib/trade/pnl/index.d.ts +77 -0
  120. package/lib/trade/pnl/index.js +270 -0
  121. package/lib/trade/pnl/types.d.ts +114 -0
  122. package/lib/trade/pnl/types.js +5 -0
  123. package/lib/trade/priceImpact/close/index.d.ts +21 -0
  124. package/lib/trade/priceImpact/close/index.js +131 -0
  125. package/lib/trade/priceImpact/close/types.d.ts +43 -0
  126. package/lib/trade/priceImpact/close/types.js +5 -0
  127. package/lib/trade/priceImpact/cumulVol/converter.d.ts +31 -0
  128. package/lib/trade/priceImpact/cumulVol/converter.js +59 -0
  129. package/lib/trade/priceImpact/cumulVol/index.d.ts +107 -0
  130. package/lib/trade/priceImpact/cumulVol/index.js +228 -0
  131. package/lib/trade/priceImpact/index.d.ts +12 -0
  132. package/lib/trade/priceImpact/index.js +59 -0
  133. package/lib/trade/priceImpact/open/index.d.ts +22 -0
  134. package/lib/trade/priceImpact/open/index.js +76 -0
  135. package/lib/trade/priceImpact/open/types.d.ts +41 -0
  136. package/lib/trade/priceImpact/open/types.js +5 -0
  137. package/lib/trade/priceImpact/skew/converter.d.ts +77 -0
  138. package/lib/trade/priceImpact/skew/converter.js +171 -0
  139. package/lib/trade/priceImpact/skew/fetcher.d.ts +63 -0
  140. package/lib/trade/priceImpact/skew/fetcher.js +168 -0
  141. package/lib/trade/priceImpact/skew/index.d.ts +58 -0
  142. package/lib/trade/priceImpact/skew/index.js +179 -0
  143. package/lib/trade/priceImpact/skew/types.d.ts +55 -0
  144. package/lib/trade/priceImpact/skew/types.js +5 -0
  145. package/lib/trade/utils.d.ts +18 -0
  146. package/lib/trade/utils.js +30 -0
  147. package/package.json +1 -1
@@ -0,0 +1,270 @@
1
+ "use strict";
2
+ /**
3
+ * @dev PnL calculation module
4
+ * @dev Provides functions matching v10 contract implementations
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
18
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.getPriceForTargetPnlPercentage = exports.getPnl = exports.getComprehensivePnl = exports.getTradeValue = exports.getPnlPercent = void 0;
22
+ const borrowing_1 = require("../fees/borrowing");
23
+ const trading_1 = require("../fees/trading");
24
+ const liquidation_1 = require("../liquidation");
25
+ /**
26
+ * @dev Calculates PnL percentage for a position
27
+ * @dev Mirrors contract's getPnlPercent function
28
+ * @param openPrice Trade open price
29
+ * @param currentPrice Current market price
30
+ * @param long Whether position is long
31
+ * @param leverage Position leverage
32
+ * @returns PnL percentage (e.g., 10 = 10% profit, -50 = 50% loss)
33
+ */
34
+ const getPnlPercent = (openPrice, currentPrice, long, leverage) => {
35
+ if (openPrice === 0)
36
+ return -100;
37
+ const priceDiff = long ? currentPrice - openPrice : openPrice - currentPrice;
38
+ const pnlPercent = (priceDiff / openPrice) * 100 * leverage;
39
+ // Cap at -100% loss
40
+ return Math.max(pnlPercent, -100);
41
+ };
42
+ exports.getPnlPercent = getPnlPercent;
43
+ /**
44
+ * @dev Calculates trade value from collateral and PnL
45
+ * @dev Mirrors contract's getTradeValuePure function
46
+ * @param collateral Trade collateral amount
47
+ * @param pnlPercent PnL percentage
48
+ * @param totalFees Total fees to deduct
49
+ * @returns Trade value after PnL and fees
50
+ */
51
+ const getTradeValue = (collateral, pnlPercent, totalFees) => {
52
+ const pnlCollateral = collateral * (pnlPercent / 100);
53
+ const value = collateral + pnlCollateral - totalFees;
54
+ return Math.max(0, value);
55
+ };
56
+ exports.getTradeValue = getTradeValue;
57
+ /**
58
+ * @dev Comprehensive PnL calculation including all fees
59
+ * @param trade The trade to calculate PnL for
60
+ * @param currentPrice Current market price
61
+ * @param tradeInfo Trade info with version and timestamps
62
+ * @param context Context with all fee parameters
63
+ * @returns Detailed PnL breakdown
64
+ */
65
+ const getComprehensivePnl = (trade, currentPrice, tradeInfo, context) => {
66
+ var _a;
67
+ // Calculate base PnL percentage
68
+ let pnlPercent = (0, exports.getPnlPercent)(trade.openPrice, currentPrice, trade.long, trade.leverage);
69
+ if (!context.tradeData) {
70
+ throw new Error("Trade data is undefined");
71
+ }
72
+ // Calculate position size
73
+ const positionSizeCollateral = trade.collateralAmount * trade.leverage;
74
+ // Calculate holding fees - always use getTradePendingHoldingFeesCollateral
75
+ // This mirrors the contract's getTradeValueCollateral which always calls this function
76
+ const pendingHoldingFees = (0, trading_1.getTradePendingHoldingFeesCollateral)(trade, tradeInfo, context.tradeData.tradeFeesData, currentPrice, {
77
+ contractsVersion: context.core.contractsVersion,
78
+ currentTimestamp: context.core.currentTimestamp,
79
+ collateralPriceUsd: context.core.collateralPriceUsd,
80
+ borrowingV1: context.borrowingV1,
81
+ borrowingV2: context.borrowingV2,
82
+ funding: context.funding,
83
+ initialAccFeesV1: context.tradeData.initialAccFeesV1,
84
+ });
85
+ const borrowingFeeV1 = pendingHoldingFees.borrowingFeeCollateral_old;
86
+ const borrowingFeeV2 = pendingHoldingFees.borrowingFeeCollateral;
87
+ const fundingFee = pendingHoldingFees.fundingFeeCollateral;
88
+ // Calculate closing fees
89
+ const closingFee = (0, trading_1.getTotalTradeFeesCollateral)(trade.collateralIndex, trade.user, trade.pairIndex, positionSizeCollateral, trade.isCounterTrade || false, {
90
+ fee: context.trading.fee,
91
+ globalTradeFeeParams: context.trading.globalTradeFeeParams,
92
+ collateralPriceUsd: context.core.collateralPriceUsd,
93
+ traderFeeMultiplier: context.trading.traderFeeMultiplier,
94
+ });
95
+ // Total fees
96
+ const totalFees = borrowingFeeV1 + borrowingFeeV2 + fundingFee + closingFee;
97
+ // Check liquidation
98
+ const liquidationThreshold = ((_a = context.tradeData) === null || _a === void 0 ? void 0 : _a.liquidationParams)
99
+ ? (0, liquidation_1.getLiqPnlThresholdP)(context.tradeData.liquidationParams, trade.leverage) *
100
+ -100
101
+ : -90; // Default 90% loss
102
+ const isLiquidated = pnlPercent <= liquidationThreshold;
103
+ // If liquidated, set PnL to -100%
104
+ if (isLiquidated) {
105
+ pnlPercent = -100;
106
+ }
107
+ // Calculate final trade value
108
+ const tradeValue = (0, exports.getTradeValue)(trade.collateralAmount, pnlPercent, totalFees);
109
+ // Calculate PnL in collateral
110
+ const pnlCollateral = trade.collateralAmount * (pnlPercent / 100);
111
+ // Calculate leveraged position size
112
+ const leveragedPositionSize = trade.collateralAmount * trade.leverage;
113
+ // Calculate net PnL after fees
114
+ const netPnlAfterFees = pnlCollateral - totalFees;
115
+ // Calculate unrealized PnL (before closing fee, after holding fees)
116
+ const totalHoldingFees = borrowingFeeV1 + borrowingFeeV2 + fundingFee;
117
+ const uPnlCollateral = pnlCollateral - totalHoldingFees;
118
+ const uPnlPercent = (uPnlCollateral / trade.collateralAmount) * 100;
119
+ // Realized PnL (after all fees including closing)
120
+ const realizedPnlCollateral = pnlCollateral - totalFees;
121
+ const realizedPnlPercent = (realizedPnlCollateral / trade.collateralAmount) * 100;
122
+ return {
123
+ // Core PnL values
124
+ pnlPercent,
125
+ pnlCollateral,
126
+ tradeValue,
127
+ // Unrealized PnL (after holding fees, before closing fee)
128
+ uPnlCollateral,
129
+ uPnlPercent,
130
+ // Realized PnL (after all fees)
131
+ realizedPnlCollateral,
132
+ realizedPnlPercent,
133
+ // Fee breakdown
134
+ fees: {
135
+ borrowingV1: borrowingFeeV1,
136
+ borrowingV2: borrowingFeeV2,
137
+ funding: fundingFee,
138
+ closing: closingFee,
139
+ total: totalFees,
140
+ },
141
+ // Status flags
142
+ isLiquidated,
143
+ isProfitable: pnlPercent > 0,
144
+ // Additional info
145
+ leveragedPositionSize,
146
+ netPnlAfterFees,
147
+ };
148
+ };
149
+ exports.getComprehensivePnl = getComprehensivePnl;
150
+ /**
151
+ * @dev Legacy PnL calculation function
152
+ * @deprecated Use getComprehensivePnl for more comprehensive calculations
153
+ * @param price Current price
154
+ * @param trade Trade object
155
+ * @param tradeInfo Trade info (not used in legacy implementation)
156
+ * @param initialAccFees Initial accumulated fees
157
+ * @param liquidationParams Liquidation parameters
158
+ * @param useFees Whether to include fees
159
+ * @param context Context with fee calculation parameters
160
+ * @returns [pnlCollateral, pnlPercentage] or undefined if no price
161
+ */
162
+ const getPnl = (price, trade, _tradeInfo, initialAccFees, liquidationParams, useFees, context) => {
163
+ var _a;
164
+ if (!price) {
165
+ return;
166
+ }
167
+ const posCollat = trade.collateralAmount;
168
+ const { openPrice, leverage } = trade;
169
+ let pnlCollat = trade.long
170
+ ? ((price - openPrice) / openPrice) * leverage * posCollat
171
+ : ((openPrice - price) / openPrice) * leverage * posCollat;
172
+ if (useFees &&
173
+ context.pairs &&
174
+ context.groups &&
175
+ context.currentBlock !== undefined &&
176
+ context.collateralPriceUsd !== undefined) {
177
+ pnlCollat -= (0, borrowing_1.getBorrowingFee)(posCollat * trade.leverage, trade.pairIndex, trade.long, initialAccFees, {
178
+ currentBlock: context.currentBlock,
179
+ groups: context.groups,
180
+ pairs: context.pairs,
181
+ collateralPriceUsd: context.collateralPriceUsd,
182
+ });
183
+ }
184
+ let pnlPercentage = (pnlCollat / posCollat) * 100;
185
+ // Can be liquidated
186
+ if (pnlPercentage <=
187
+ (0, liquidation_1.getLiqPnlThresholdP)(liquidationParams, leverage) * -100) {
188
+ pnlPercentage = -100;
189
+ }
190
+ else {
191
+ // Calculate closing fee using the same function as opening fees
192
+ const positionSizeCollateral = posCollat * trade.leverage;
193
+ const closingFee = (0, trading_1.getTotalTradeFeesCollateral)(0, // collateralIndex not used
194
+ trade.user, trade.pairIndex, positionSizeCollateral, (_a = trade.isCounterTrade) !== null && _a !== void 0 ? _a : false, {
195
+ fee: context.fee,
196
+ globalTradeFeeParams: context.globalTradeFeeParams,
197
+ collateralPriceUsd: context.collateralPriceUsd || 1,
198
+ traderFeeMultiplier: context.traderFeeMultiplier,
199
+ });
200
+ pnlCollat -= closingFee;
201
+ pnlPercentage = (pnlCollat / posCollat) * 100;
202
+ }
203
+ pnlPercentage = pnlPercentage < -100 ? -100 : pnlPercentage;
204
+ pnlCollat = (posCollat * pnlPercentage) / 100;
205
+ return [pnlCollat, pnlPercentage];
206
+ };
207
+ exports.getPnl = getPnl;
208
+ /**
209
+ * @dev Calculates the price needed to achieve a target PnL percentage
210
+ * @param targetPnlPercent The target PnL percentage (e.g., 50 for 50% profit, -25 for 25% loss)
211
+ * @param trade The trade to calculate for
212
+ * @param tradeInfo Trade info with timestamps
213
+ * @param context Context with fee calculation parameters
214
+ * @param netPnl Whether to include closing fees in the calculation
215
+ * @returns The price that would result in the target PnL percentage
216
+ */
217
+ const getPriceForTargetPnlPercentage = (targetPnlPercent, trade, tradeInfo, context, netPnl = false) => {
218
+ var _a, _b;
219
+ const { leverage, openPrice, long, collateralAmount } = trade;
220
+ const positionSizeCollateral = collateralAmount * leverage;
221
+ // Calculate holding fees - always use getTradePendingHoldingFeesCollateral
222
+ // This mirrors the contract's getTradeValueCollateral which always calls this function
223
+ const fees = (0, trading_1.getTradePendingHoldingFeesCollateral)(trade, tradeInfo, ((_a = context.tradeData) === null || _a === void 0 ? void 0 : _a.tradeFeesData) || {
224
+ realizedTradingFeesCollateral: 0,
225
+ realizedPnlCollateral: 0,
226
+ manuallyRealizedNegativePnlCollateral: 0,
227
+ alreadyTransferredNegativePnlCollateral: 0,
228
+ virtualAvailableCollateralInDiamond: 0,
229
+ initialAccFundingFeeP: 0,
230
+ initialAccBorrowingFeeP: 0,
231
+ }, openPrice, // Use open price as a baseline
232
+ {
233
+ contractsVersion: context.core.contractsVersion,
234
+ currentTimestamp: context.core.currentTimestamp,
235
+ collateralPriceUsd: context.core.collateralPriceUsd,
236
+ borrowingV1: context.borrowingV1,
237
+ borrowingV2: context.borrowingV2,
238
+ funding: context.funding,
239
+ initialAccFeesV1: (_b = context.tradeData) === null || _b === void 0 ? void 0 : _b.initialAccFeesV1,
240
+ });
241
+ const totalHoldingFees = fees.fundingFeeCollateral +
242
+ fees.borrowingFeeCollateral +
243
+ fees.borrowingFeeCollateral_old;
244
+ const targetPnlInCollateral = (collateralAmount * targetPnlPercent) / 100;
245
+ let targetPnlGross = targetPnlInCollateral + totalHoldingFees;
246
+ if (netPnl) {
247
+ // Include closing fees
248
+ const closingFee = (0, trading_1.getTotalTradeFeesCollateral)(trade.collateralIndex, trade.user, trade.pairIndex, positionSizeCollateral, trade.isCounterTrade || false, {
249
+ fee: context.trading.fee,
250
+ globalTradeFeeParams: context.trading.globalTradeFeeParams,
251
+ collateralPriceUsd: context.core.collateralPriceUsd,
252
+ traderFeeMultiplier: context.trading.traderFeeMultiplier,
253
+ });
254
+ targetPnlGross += closingFee;
255
+ }
256
+ // Calculate the price
257
+ let price;
258
+ if (long) {
259
+ price = openPrice + (targetPnlGross * openPrice) / positionSizeCollateral;
260
+ }
261
+ else {
262
+ price = openPrice - (targetPnlGross * openPrice) / positionSizeCollateral;
263
+ }
264
+ return price;
265
+ };
266
+ exports.getPriceForTargetPnlPercentage = getPriceForTargetPnlPercentage;
267
+ // Re-export types
268
+ __exportStar(require("./types"), exports);
269
+ __exportStar(require("./converter"), exports);
270
+ __exportStar(require("./builder"), exports);
@@ -0,0 +1,114 @@
1
+ /**
2
+ * @dev Types for PnL calculations
3
+ */
4
+ import { ContractsVersion } from "src/contracts/types";
5
+ import { BorrowingFee, GetBorrowingFeeContext, TradingFeesSubContext } from "../fees";
6
+ import { GetPairBorrowingFeeV2Context } from "../fees/borrowingV2";
7
+ import { GetPairFundingFeeContext } from "../fees/fundingFees";
8
+ import { Trade, TradeInfo, TradeFeesData, LiquidationParams } from "../types";
9
+ /**
10
+ * @dev Input for trade value calculation with all fees
11
+ * @dev Mirrors contract's TradeValueInput struct
12
+ */
13
+ export type TradeValueInput = {
14
+ trade: Trade;
15
+ currentPrice: number;
16
+ collateralPriceUsd: number;
17
+ fees: {
18
+ openingFeeCollateral: number;
19
+ closingFeeCollateral: number;
20
+ holdingFeesCollateral: number;
21
+ };
22
+ };
23
+ /**
24
+ * @dev Result of trade value calculation
25
+ */
26
+ export type TradeValueResult = {
27
+ tradeValue: number;
28
+ pnlPercent: number;
29
+ pnlCollateral: number;
30
+ totalFees: number;
31
+ };
32
+ /**
33
+ * @dev Detailed fee breakdown
34
+ */
35
+ export type FeeBreakdown = {
36
+ borrowingV1: number;
37
+ borrowingV2: number;
38
+ funding: number;
39
+ closing: number;
40
+ opening?: number;
41
+ total: number;
42
+ };
43
+ /**
44
+ * @dev Price impact breakdown for v10
45
+ */
46
+ export type PriceImpactBreakdown = {
47
+ fixedSpread: number;
48
+ skewImpact: number;
49
+ cumulVolImpact: number;
50
+ total: number;
51
+ priceAfterImpact: number;
52
+ };
53
+ /**
54
+ * @dev Comprehensive PnL result with all details
55
+ */
56
+ export type ComprehensivePnlResult = {
57
+ pnlPercent: number;
58
+ pnlCollateral: number;
59
+ tradeValue: number;
60
+ uPnlCollateral: number;
61
+ uPnlPercent: number;
62
+ realizedPnlCollateral: number;
63
+ realizedPnlPercent: number;
64
+ fees: FeeBreakdown;
65
+ priceImpact?: PriceImpactBreakdown;
66
+ isLiquidated: boolean;
67
+ isProfitable: boolean;
68
+ leveragedPositionSize: number;
69
+ netPnlAfterFees: number;
70
+ };
71
+ /**
72
+ * @dev Simple PnL result for backward compatibility
73
+ */
74
+ export type SimplePnlResult = [pnlCollateral: number, pnlPercent: number];
75
+ /**
76
+ * @dev Input for PnL calculation with price impact
77
+ */
78
+ export type PnlWithPriceImpactInput = {
79
+ trade: Trade;
80
+ tradeInfo: TradeInfo;
81
+ oraclePrice: number;
82
+ currentPairPrice: number;
83
+ usePriceImpact: boolean;
84
+ includeOpeningFees?: boolean;
85
+ };
86
+ /**
87
+ * @dev Context for v10 PnL calculations
88
+ */
89
+ export type V10PnlContext = {
90
+ tradeFeesData: TradeFeesData;
91
+ priceImpactContext?: any;
92
+ skewContext?: any;
93
+ cumulVolContext?: any;
94
+ };
95
+ /**
96
+ * @dev Context for comprehensive PnL calculations with nested sub-contexts
97
+ */
98
+ export type GetComprehensivePnlContext = {
99
+ core: {
100
+ currentBlock: number;
101
+ currentTimestamp: number;
102
+ collateralPriceUsd: number;
103
+ contractsVersion: ContractsVersion;
104
+ };
105
+ borrowingV1?: GetBorrowingFeeContext;
106
+ borrowingV2?: GetPairBorrowingFeeV2Context;
107
+ funding?: GetPairFundingFeeContext;
108
+ trading: TradingFeesSubContext;
109
+ tradeData?: {
110
+ tradeFeesData: TradeFeesData;
111
+ liquidationParams: LiquidationParams;
112
+ initialAccFeesV1?: BorrowingFee.InitialAccFees;
113
+ };
114
+ };
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Types for PnL calculations
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,21 @@
1
+ /**
2
+ * @dev Trade closing price impact calculations
3
+ * @dev Mirrors contract's TradingCommonUtils.getTradeClosingPriceImpact
4
+ */
5
+ import { TradeClosingPriceImpactInput, TradeClosingPriceImpactContext, TradeClosingPriceImpactResult } from "./types";
6
+ export type { TradeClosingPriceImpactInput, TradeClosingPriceImpactContext, TradeClosingPriceImpactResult, };
7
+ /**
8
+ * @dev Calculates all price impacts for trade closing
9
+ * @dev Mirrors contract's getTradeClosingPriceImpact function
10
+ * @param input Trade parameters
11
+ * @param context Combined context for calculations
12
+ * @returns Price impact breakdown and trade value
13
+ */
14
+ export declare const getTradeClosingPriceImpact: (input: TradeClosingPriceImpactInput, context: TradeClosingPriceImpactContext) => TradeClosingPriceImpactResult;
15
+ /**
16
+ * @dev Simplified version using oracle price as current price
17
+ * @param input Trade parameters (without currentPairPrice)
18
+ * @param context Combined context
19
+ * @returns Price impact breakdown and trade value
20
+ */
21
+ export declare const getTradeClosingPriceImpactAtOracle: (input: Omit<TradeClosingPriceImpactInput, "currentPairPrice">, context: TradeClosingPriceImpactContext) => TradeClosingPriceImpactResult;
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Trade closing price impact calculations
4
+ * @dev Mirrors contract's TradingCommonUtils.getTradeClosingPriceImpact
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.getTradeClosingPriceImpactAtOracle = exports.getTradeClosingPriceImpact = void 0;
8
+ const cumulVol_1 = require("../cumulVol");
9
+ const skew_1 = require("../skew");
10
+ const types_1 = require("../../../contracts/types");
11
+ /**
12
+ * @dev Calculates position size in tokens for partial close
13
+ * @param originalPositionSizeToken Original position size in tokens
14
+ * @param originalCollateral Original collateral amount
15
+ * @param closingCollateral Collateral amount being closed
16
+ * @returns Proportional position size in tokens
17
+ */
18
+ const calculateClosingPositionSizeToken = (originalPositionSizeToken, originalCollateral, closingCollateral) => {
19
+ if (originalCollateral === 0)
20
+ return 0;
21
+ // Proportional calculation: (closingCollateral / originalCollateral) * originalPositionSizeToken
22
+ return (closingCollateral * originalPositionSizeToken) / originalCollateral;
23
+ };
24
+ /**
25
+ * @dev Calculates all price impacts for trade closing
26
+ * @dev Mirrors contract's getTradeClosingPriceImpact function
27
+ * @param input Trade parameters
28
+ * @param context Combined context for calculations
29
+ * @returns Price impact breakdown and trade value
30
+ */
31
+ const getTradeClosingPriceImpact = (input, context) => {
32
+ // For trades before V9.2, return oracle price without any impact
33
+ if (input.contractsVersion === types_1.ContractsVersion.BEFORE_V9_2) {
34
+ return {
35
+ positionSizeToken: 0,
36
+ fixedSpreadP: 0,
37
+ cumulVolPriceImpactP: 0,
38
+ skewPriceImpactP: 0,
39
+ totalPriceImpactP: 0,
40
+ priceAfterImpact: input.oraclePrice,
41
+ tradeValueCollateralNoFactor: 0,
42
+ };
43
+ }
44
+ // Calculate position size in tokens (proportional to collateral being closed)
45
+ const positionSizeToken = input.trade.positionSizeToken
46
+ ? calculateClosingPositionSizeToken(input.trade.positionSizeToken, input.trade.collateralAmount, input.positionSizeCollateral)
47
+ : 0;
48
+ // Calculate fixed spread (reversed for closing)
49
+ const fixedSpreadP = (0, cumulVol_1.getFixedSpreadP)(input.pairSpreadP, input.trade.long, false // closing
50
+ );
51
+ let cumulVolPriceImpactP = 0;
52
+ let tradeValueCollateralNoFactor = 0;
53
+ if (input.useCumulativeVolPriceImpact) {
54
+ // First pass: Calculate with negative PnL assumption
55
+ const positionSizeUsd = input.positionSizeCollateral * context.collateralPriceUsd;
56
+ cumulVolPriceImpactP = (0, cumulVol_1.getTradeCumulVolPriceImpactP)(input.trade.user, input.pairIndex, input.trade.long, positionSizeUsd, false, // Assume negative PnL initially
57
+ false, // closing
58
+ context.tradeInfo.lastPosIncreaseBlock || context.tradeInfo.createdBlock, Object.assign(Object.assign({}, context), { isOpen: false, isPnlPositive: false, contractsVersion: input.contractsVersion, createdBlock: context.tradeInfo.createdBlock }));
59
+ // Calculate price with conservative impact
60
+ const priceWithImpact = input.trade.long
61
+ ? input.currentPairPrice *
62
+ (1 - (fixedSpreadP + cumulVolPriceImpactP) / 100)
63
+ : input.currentPairPrice /
64
+ (1 - (fixedSpreadP + cumulVolPriceImpactP) / 100);
65
+ // Calculate trade value in collateral
66
+ // For long: value = positionSizeToken * priceWithImpact
67
+ // For short: value = positionSizeToken / priceWithImpact * openPrice^2 / currentPrice
68
+ if (positionSizeToken > 0) {
69
+ if (input.trade.long) {
70
+ tradeValueCollateralNoFactor = positionSizeToken * priceWithImpact;
71
+ }
72
+ else {
73
+ // Short calculation: profit from price decrease
74
+ const pnlFactor = (2 * input.trade.openPrice - priceWithImpact) / input.trade.openPrice;
75
+ tradeValueCollateralNoFactor = input.positionSizeCollateral * pnlFactor;
76
+ }
77
+ }
78
+ else {
79
+ tradeValueCollateralNoFactor = input.positionSizeCollateral;
80
+ }
81
+ // Determine actual PnL
82
+ const isPnlPositive = tradeValueCollateralNoFactor > input.trade.collateralAmount;
83
+ // Second pass: Recalculate with actual PnL if positive
84
+ if (isPnlPositive) {
85
+ cumulVolPriceImpactP = (0, cumulVol_1.getTradeCumulVolPriceImpactP)(input.trade.user, input.pairIndex, input.trade.long, positionSizeUsd, true, // Positive PnL
86
+ false, // closing
87
+ context.tradeInfo.lastPosIncreaseBlock ||
88
+ context.tradeInfo.createdBlock, Object.assign(Object.assign({}, context), { isOpen: false, isPnlPositive: true, contractsVersion: input.contractsVersion, createdBlock: context.tradeInfo.createdBlock }));
89
+ }
90
+ }
91
+ // Calculate skew price impact (v10+ only)
92
+ const skewPriceImpactP = input.contractsVersion === types_1.ContractsVersion.V10
93
+ ? (0, skew_1.getTradeSkewPriceImpactWithChecks)({
94
+ collateralIndex: input.collateralIndex,
95
+ pairIndex: input.pairIndex,
96
+ long: input.trade.long,
97
+ open: false,
98
+ positionSizeCollateral: input.positionSizeCollateral,
99
+ currentPrice: input.currentPairPrice,
100
+ contractsVersion: input.contractsVersion,
101
+ isCounterTrade: input.trade.isCounterTrade,
102
+ }, context.skewContext)
103
+ : 0;
104
+ // Total price impact (all components)
105
+ const totalPriceImpactP = fixedSpreadP + cumulVolPriceImpactP + skewPriceImpactP;
106
+ // Calculate final price after all impacts
107
+ // For closing: longs get worse price when impact is positive, shorts get better
108
+ const priceAfterImpact = input.trade.long
109
+ ? input.currentPairPrice * (1 - totalPriceImpactP / 100)
110
+ : input.currentPairPrice / (1 - totalPriceImpactP / 100);
111
+ return {
112
+ positionSizeToken,
113
+ fixedSpreadP,
114
+ cumulVolPriceImpactP,
115
+ skewPriceImpactP,
116
+ totalPriceImpactP,
117
+ priceAfterImpact,
118
+ tradeValueCollateralNoFactor,
119
+ };
120
+ };
121
+ exports.getTradeClosingPriceImpact = getTradeClosingPriceImpact;
122
+ /**
123
+ * @dev Simplified version using oracle price as current price
124
+ * @param input Trade parameters (without currentPairPrice)
125
+ * @param context Combined context
126
+ * @returns Price impact breakdown and trade value
127
+ */
128
+ const getTradeClosingPriceImpactAtOracle = (input, context) => {
129
+ return (0, exports.getTradeClosingPriceImpact)(Object.assign(Object.assign({}, input), { currentPairPrice: input.oraclePrice }), context);
130
+ };
131
+ exports.getTradeClosingPriceImpactAtOracle = getTradeClosingPriceImpactAtOracle;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @dev Types for trade closing price impact calculations
3
+ */
4
+ import { CumulVolContext } from "../cumulVol";
5
+ import { SkewPriceImpactContext } from "../skew/types";
6
+ import { Trade, TradeInfo, PairIndex } from "../../types";
7
+ /**
8
+ * @dev Input parameters for trade closing price impact
9
+ * @dev Mirrors contract's TradePriceImpactInput struct
10
+ */
11
+ export type TradeClosingPriceImpactInput = {
12
+ trade: Trade;
13
+ oraclePrice: number;
14
+ positionSizeCollateral: number;
15
+ currentPairPrice: number;
16
+ useCumulativeVolPriceImpact: boolean;
17
+ collateralIndex: number;
18
+ pairIndex: PairIndex;
19
+ pairSpreadP: number;
20
+ contractsVersion: number;
21
+ };
22
+ /**
23
+ * @dev Context for trade closing price impact calculation
24
+ * Combines contexts from spread, cumul vol, and skew
25
+ */
26
+ export type TradeClosingPriceImpactContext = CumulVolContext & {
27
+ skewContext: SkewPriceImpactContext;
28
+ collateralPriceUsd: number;
29
+ tradeInfo: TradeInfo;
30
+ };
31
+ /**
32
+ * @dev Result of trade closing price impact calculation
33
+ * @dev Mirrors contract's TradePriceImpact struct with additional return value
34
+ */
35
+ export type TradeClosingPriceImpactResult = {
36
+ positionSizeToken: number;
37
+ fixedSpreadP: number;
38
+ cumulVolPriceImpactP: number;
39
+ skewPriceImpactP: number;
40
+ totalPriceImpactP: number;
41
+ priceAfterImpact: number;
42
+ tradeValueCollateralNoFactor: number;
43
+ };
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Types for trade closing price impact calculations
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @dev Converters for cumulative volume price impact data between contract and SDK formats
3
+ * @dev All BigNumber values are normalized to floats with appropriate precision
4
+ */
5
+ import { IPriceImpact } from "../../../contracts/types/generated/GNSMultiCollatDiamond";
6
+ import { OiWindowsSettings, OiWindow, OiWindows } from "../../types";
7
+ /**
8
+ * @dev Converts contract OI windows settings to SDK format
9
+ * @param contractData Contract OiWindowsSettings struct
10
+ * @returns Normalized OI windows settings
11
+ */
12
+ export declare const convertOiWindowsSettings: (contractData: IPriceImpact.OiWindowsSettingsStructOutput) => OiWindowsSettings;
13
+ /**
14
+ * @dev Converts contract PairOi data to SDK OiWindow format
15
+ * @param contractData Contract PairOi struct with USD values
16
+ * @returns Normalized OI window data
17
+ */
18
+ export declare const convertOiWindow: (contractData: IPriceImpact.PairOiStructOutput) => OiWindow;
19
+ /**
20
+ * @dev Converts array of OI windows from contract format
21
+ * @param windowIds Array of window IDs (as strings for mapping)
22
+ * @param contractWindows Array of PairOi data from contract
23
+ * @returns Normalized OI windows mapping
24
+ */
25
+ export declare const convertOiWindows: (windowIds: string[], contractWindows: IPriceImpact.PairOiStructOutput[]) => OiWindows;
26
+ /**
27
+ * @dev Batch converter for multiple OI windows settings
28
+ * @param contractDataArray Array of contract OiWindowsSettings
29
+ * @returns Array of normalized OI windows settings
30
+ */
31
+ export declare const convertOiWindowsSettingsArray: (contractDataArray: IPriceImpact.OiWindowsSettingsStructOutput[]) => OiWindowsSettings[];