@gainsnetwork/sdk 0.2.67-rc8 → 0.2.69

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 (136) hide show
  1. package/lib/contracts/addresses.json +20 -0
  2. package/lib/{trade/fees/borrowingV2/fetcher.d.ts → contracts/fetch/fees/borrowingFeesV2.d.ts} +3 -2
  3. package/lib/{trade/fees/borrowingV2/fetcher.js → contracts/fetch/fees/borrowingFeesV2.js} +14 -6
  4. package/lib/{trade/fees/fundingFees/fetcher.d.ts → contracts/fetch/fees/fundingFees.d.ts} +2 -2
  5. package/lib/{trade/priceImpact/skew/fetcher.d.ts → contracts/fetch/priceImpact/skew.d.ts} +2 -2
  6. package/lib/{trade/priceImpact/skew/fetcher.js → contracts/fetch/priceImpact/skew.js} +6 -6
  7. package/lib/contracts/index.js +3 -1
  8. package/lib/contracts/types/generated/GNSMultiCollatDiamond.d.ts +258 -2112
  9. package/lib/contracts/types/generated/GToken.d.ts +107 -78
  10. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.d.ts +53 -90
  11. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.js +421 -4496
  12. package/lib/contracts/types/generated/factories/GToken__factory.js +142 -65
  13. package/lib/contracts/types/index.d.ts +2 -1
  14. package/lib/contracts/types/index.js +1 -0
  15. package/lib/trade/fees/borrowingV2/converter.d.ts +3 -12
  16. package/lib/trade/fees/borrowingV2/converter.js +18 -29
  17. package/lib/trade/fees/borrowingV2/index.d.ts +17 -6
  18. package/lib/trade/fees/borrowingV2/index.js +37 -10
  19. package/lib/trade/fees/borrowingV2/types.d.ts +6 -22
  20. package/lib/trade/fees/fundingFees/index.d.ts +2 -13
  21. package/lib/trade/fees/fundingFees/index.js +3 -27
  22. package/lib/trade/fees/trading/index.d.ts +2 -30
  23. package/lib/trade/fees/trading/index.js +1 -52
  24. package/lib/trade/fees/trading/types.d.ts +0 -9
  25. package/lib/trade/priceImpact/index.d.ts +2 -6
  26. package/lib/trade/priceImpact/index.js +3 -30
  27. package/lib/trade/priceImpact/skew/index.d.ts +0 -1
  28. package/lib/trade/priceImpact/skew/index.js +0 -4
  29. package/package.json +1 -1
  30. package/lib/backend/globalTrades/index.d.ts +0 -11
  31. package/lib/backend/globalTrades/index.js +0 -69
  32. package/lib/backend/index.d.ts +0 -3
  33. package/lib/backend/index.js +0 -28
  34. package/lib/backend/tradingVariables/backend.types.d.ts +0 -312
  35. package/lib/backend/tradingVariables/backend.types.js +0 -2
  36. package/lib/backend/tradingVariables/converter.d.ts +0 -31
  37. package/lib/backend/tradingVariables/converter.js +0 -330
  38. package/lib/backend/tradingVariables/index.d.ts +0 -5
  39. package/lib/backend/tradingVariables/index.js +0 -95
  40. package/lib/backend/tradingVariables/types.d.ts +0 -109
  41. package/lib/backend/tradingVariables/types.js +0 -14
  42. package/lib/contracts/types/generated/GFarmTradingStorageV5.d.ts +0 -1911
  43. package/lib/contracts/types/generated/GFarmTradingStorageV5.js +0 -2
  44. package/lib/contracts/types/generated/GNSBorrowingFees.d.ts +0 -1067
  45. package/lib/contracts/types/generated/GNSBorrowingFees.js +0 -2
  46. package/lib/contracts/types/generated/GNSNftRewardsV6.d.ts +0 -533
  47. package/lib/contracts/types/generated/GNSNftRewardsV6.js +0 -2
  48. package/lib/contracts/types/generated/GNSNftRewardsV6_3_1.d.ts +0 -613
  49. package/lib/contracts/types/generated/GNSNftRewardsV6_3_1.js +0 -2
  50. package/lib/contracts/types/generated/GNSTrading.d.ts +0 -758
  51. package/lib/contracts/types/generated/GNSTrading.js +0 -2
  52. package/lib/contracts/types/generated/GNSTradingCallbacks.d.ts +0 -875
  53. package/lib/contracts/types/generated/GNSTradingCallbacks.js +0 -2
  54. package/lib/contracts/types/generated/GNSTradingStorage.d.ts +0 -1387
  55. package/lib/contracts/types/generated/GNSTradingStorage.js +0 -2
  56. package/lib/contracts/types/generated/GTokenV6_3_2.d.ts +0 -1838
  57. package/lib/contracts/types/generated/GTokenV6_3_2.js +0 -2
  58. package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.d.ts +0 -83
  59. package/lib/contracts/types/generated/factories/GFarmTradingStorageV5__factory.js +0 -2691
  60. package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.d.ts +0 -124
  61. package/lib/contracts/types/generated/factories/GNSBorrowingFees__factory.js +0 -1784
  62. package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.d.ts +0 -100
  63. package/lib/contracts/types/generated/factories/GNSNftRewardsV6_3_1__factory.js +0 -1116
  64. package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.d.ts +0 -100
  65. package/lib/contracts/types/generated/factories/GNSNftRewardsV6__factory.js +0 -1003
  66. package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.d.ts +0 -113
  67. package/lib/contracts/types/generated/factories/GNSTradingCallbacks__factory.js +0 -1428
  68. package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.d.ts +0 -96
  69. package/lib/contracts/types/generated/factories/GNSTradingStorage__factory.js +0 -2241
  70. package/lib/contracts/types/generated/factories/GNSTrading__factory.d.ts +0 -95
  71. package/lib/contracts/types/generated/factories/GNSTrading__factory.js +0 -1071
  72. package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.d.ts +0 -110
  73. package/lib/contracts/types/generated/factories/GTokenV6_3_2__factory.js +0 -2682
  74. package/lib/contracts/utils/openLimitOrders.d.ts +0 -8
  75. package/lib/contracts/utils/openLimitOrders.js +0 -88
  76. package/lib/markets/collateral/converter.d.ts +0 -5
  77. package/lib/markets/collateral/converter.js +0 -11
  78. package/lib/markets/collateral/index.d.ts +0 -1
  79. package/lib/markets/collateral/index.js +0 -17
  80. package/lib/markets/collateral/types.d.ts +0 -7
  81. package/lib/markets/collateral/types.js +0 -2
  82. package/lib/markets/oi/converter.d.ts +0 -63
  83. package/lib/markets/oi/converter.js +0 -103
  84. package/lib/markets/oi/fetcher.d.ts +0 -58
  85. package/lib/markets/oi/fetcher.js +0 -181
  86. package/lib/markets/oi/index.d.ts +0 -10
  87. package/lib/markets/oi/index.js +0 -37
  88. package/lib/markets/oi/types.d.ts +0 -82
  89. package/lib/markets/oi/types.js +0 -6
  90. package/lib/markets/oi/validation.d.ts +0 -80
  91. package/lib/markets/oi/validation.js +0 -172
  92. package/lib/trade/fees/borrowing/builder.d.ts +0 -14
  93. package/lib/trade/fees/borrowing/builder.js +0 -33
  94. package/lib/trade/fees/borrowingV2/builder.d.ts +0 -6
  95. package/lib/trade/fees/borrowingV2/builder.js +0 -24
  96. package/lib/trade/fees/converter.d.ts +0 -48
  97. package/lib/trade/fees/converter.js +0 -110
  98. package/lib/trade/fees/fundingFees/builder.d.ts +0 -9
  99. package/lib/trade/fees/fundingFees/builder.js +0 -35
  100. package/lib/trade/fees/fundingFees/pairContext.d.ts +0 -33
  101. package/lib/trade/fees/fundingFees/pairContext.js +0 -17
  102. package/lib/trade/fees/tiers/converter.d.ts +0 -54
  103. package/lib/trade/fees/tiers/converter.js +0 -81
  104. package/lib/trade/fees/trading/builder.d.ts +0 -18
  105. package/lib/trade/fees/trading/builder.js +0 -20
  106. package/lib/trade/liquidation/builder.d.ts +0 -25
  107. package/lib/trade/liquidation/builder.js +0 -59
  108. package/lib/trade/liquidation/converter.d.ts +0 -23
  109. package/lib/trade/liquidation/converter.js +0 -46
  110. package/lib/trade/liquidation/index.d.ts +0 -26
  111. package/lib/trade/liquidation/index.js +0 -142
  112. package/lib/trade/liquidation/types.d.ts +0 -59
  113. package/lib/trade/liquidation/types.js +0 -2
  114. package/lib/trade/openLimitOrder.d.ts +0 -2
  115. package/lib/trade/openLimitOrder.js +0 -23
  116. package/lib/trade/pnl/builder.d.ts +0 -16
  117. package/lib/trade/pnl/builder.js +0 -44
  118. package/lib/trade/pnl/converter.d.ts +0 -47
  119. package/lib/trade/pnl/converter.js +0 -72
  120. package/lib/trade/pnl/index.d.ts +0 -77
  121. package/lib/trade/pnl/index.js +0 -270
  122. package/lib/trade/pnl/types.d.ts +0 -114
  123. package/lib/trade/pnl/types.js +0 -5
  124. package/lib/trade/priceImpact/close/index.d.ts +0 -21
  125. package/lib/trade/priceImpact/close/index.js +0 -131
  126. package/lib/trade/priceImpact/close/types.d.ts +0 -43
  127. package/lib/trade/priceImpact/close/types.js +0 -5
  128. package/lib/trade/priceImpact/cumulVol/converter.d.ts +0 -31
  129. package/lib/trade/priceImpact/cumulVol/converter.js +0 -59
  130. package/lib/trade/priceImpact/cumulVol/index.d.ts +0 -107
  131. package/lib/trade/priceImpact/cumulVol/index.js +0 -228
  132. package/lib/trade/priceImpact/open/index.d.ts +0 -22
  133. package/lib/trade/priceImpact/open/index.js +0 -76
  134. package/lib/trade/priceImpact/open/types.d.ts +0 -41
  135. package/lib/trade/priceImpact/open/types.js +0 -5
  136. /package/lib/{trade/fees/fundingFees/fetcher.js → contracts/fetch/fees/fundingFees.js} +0 -0
@@ -1,44 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildComprehensivePnlContext = void 0;
4
- const builder_1 = require("../fees/borrowingV2/builder");
5
- const builder_2 = require("../fees/fundingFees/builder");
6
- const builder_3 = require("../fees/borrowing/builder");
7
- const builder_4 = require("../fees/trading/builder");
8
- /**
9
- * @dev Builds a complete context for comprehensive PnL calculations
10
- * @dev Uses sub-context builders to create properly scoped contexts
11
- * @param globalTradingVariables The transformed global trading variables from backend
12
- * @param tradeContainer Full trade container with trade, tradeInfo, fees data and liquidation params
13
- * @param additionalParams Additional parameters not available in trading variables
14
- * @returns Complete context ready for getComprehensivePnl
15
- */
16
- const buildComprehensivePnlContext = (globalTradingVariables, tradeContainer, additionalParams) => {
17
- var _a;
18
- const { trade, tradeInfo } = tradeContainer;
19
- const collateralIndex = trade.collateralIndex || 1;
20
- const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
21
- return {
22
- // Core shared context
23
- core: {
24
- currentBlock: additionalParams.currentBlock,
25
- currentTimestamp: additionalParams.currentTimestamp,
26
- collateralPriceUsd: ((_a = collateral.prices) === null || _a === void 0 ? void 0 : _a.collateralPriceUsd) || 1,
27
- contractsVersion: tradeInfo.contractsVersion,
28
- },
29
- // Build sub-contexts using dedicated builders
30
- borrowingV1: (0, builder_3.buildBorrowingV1Context)(globalTradingVariables, collateralIndex, additionalParams.currentBlock),
31
- borrowingV2: (0, builder_1.buildBorrowingV2Context)(globalTradingVariables, collateralIndex, trade.pairIndex, additionalParams.currentTimestamp),
32
- funding: (0, builder_2.buildFundingContext)(globalTradingVariables, collateralIndex, trade.pairIndex, additionalParams.currentTimestamp),
33
- trading: (0, builder_4.buildTradingFeesContext)(globalTradingVariables, trade.pairIndex, additionalParams.traderFeeMultiplier),
34
- // Trade-specific data
35
- tradeData: tradeContainer.tradeFeesData && tradeContainer.liquidationParams
36
- ? {
37
- tradeFeesData: tradeContainer.tradeFeesData,
38
- liquidationParams: tradeContainer.liquidationParams,
39
- initialAccFeesV1: tradeContainer.initialAccFees,
40
- }
41
- : undefined,
42
- };
43
- };
44
- exports.buildComprehensivePnlContext = buildComprehensivePnlContext;
@@ -1,47 +0,0 @@
1
- /**
2
- * @dev Converters for PnL data between contract and SDK formats
3
- */
4
- /**
5
- * @dev Convert PnL percentage from contract precision to SDK format
6
- * @param pnlPercentContract PnL percentage with 1e10 precision
7
- * @returns PnL percentage as regular number (e.g., 10 = 10%)
8
- */
9
- export declare const convertPnlPercent: (pnlPercentContract: bigint | number) => number;
10
- /**
11
- * @dev Convert PnL percentage from SDK format to contract precision
12
- * @param pnlPercent PnL percentage as regular number
13
- * @returns PnL percentage with 1e10 precision
14
- */
15
- export declare const encodePnlPercent: (pnlPercent: number) => bigint;
16
- /**
17
- * @dev Convert collateral amount considering precision
18
- * @param amount Amount in contract format
19
- * @param collateralDecimals Collateral token decimals (6 or 18)
20
- * @returns Amount as SDK float
21
- */
22
- export declare const convertCollateralAmount: (amount: bigint | number, collateralDecimals: number) => number;
23
- /**
24
- * @dev Convert price from contract format to SDK format
25
- * @param price Price with 1e10 precision
26
- * @returns Price as SDK float
27
- */
28
- export declare const convertPrice: (price: bigint | number) => number;
29
- /**
30
- * @dev Convert leverage from contract format to SDK format
31
- * @param leverage Leverage with 1e3 precision
32
- * @returns Leverage as SDK float (e.g., 10 = 10x)
33
- */
34
- export declare const convertLeverage: (leverage: bigint | number) => number;
35
- /**
36
- * @dev Batch convert PnL results from contract format
37
- * @param results Array of PnL results from contract
38
- * @param collateralDecimals Collateral token decimals
39
- * @returns Array of converted PnL results
40
- */
41
- export declare const convertPnlResults: (results: Array<{
42
- pnlCollateral: bigint;
43
- pnlPercent: bigint;
44
- }>, collateralDecimals: number) => Array<{
45
- pnlCollateral: number;
46
- pnlPercent: number;
47
- }>;
@@ -1,72 +0,0 @@
1
- "use strict";
2
- /**
3
- * @dev Converters for PnL data between contract and SDK formats
4
- */
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.convertPnlResults = exports.convertLeverage = exports.convertPrice = exports.convertCollateralAmount = exports.encodePnlPercent = exports.convertPnlPercent = void 0;
7
- /**
8
- * @dev Convert PnL percentage from contract precision to SDK format
9
- * @param pnlPercentContract PnL percentage with 1e10 precision
10
- * @returns PnL percentage as regular number (e.g., 10 = 10%)
11
- */
12
- const convertPnlPercent = (pnlPercentContract) => {
13
- const value = typeof pnlPercentContract === "bigint"
14
- ? Number(pnlPercentContract)
15
- : pnlPercentContract;
16
- // Contract uses 1e10 precision for percentages
17
- return value / 1e10;
18
- };
19
- exports.convertPnlPercent = convertPnlPercent;
20
- /**
21
- * @dev Convert PnL percentage from SDK format to contract precision
22
- * @param pnlPercent PnL percentage as regular number
23
- * @returns PnL percentage with 1e10 precision
24
- */
25
- const encodePnlPercent = (pnlPercent) => {
26
- return BigInt(Math.round(pnlPercent * 1e10));
27
- };
28
- exports.encodePnlPercent = encodePnlPercent;
29
- /**
30
- * @dev Convert collateral amount considering precision
31
- * @param amount Amount in contract format
32
- * @param collateralDecimals Collateral token decimals (6 or 18)
33
- * @returns Amount as SDK float
34
- */
35
- const convertCollateralAmount = (amount, collateralDecimals) => {
36
- const value = typeof amount === "bigint" ? Number(amount) : amount;
37
- return value / Math.pow(10, collateralDecimals);
38
- };
39
- exports.convertCollateralAmount = convertCollateralAmount;
40
- /**
41
- * @dev Convert price from contract format to SDK format
42
- * @param price Price with 1e10 precision
43
- * @returns Price as SDK float
44
- */
45
- const convertPrice = (price) => {
46
- const value = typeof price === "bigint" ? Number(price) : price;
47
- return value / 1e10;
48
- };
49
- exports.convertPrice = convertPrice;
50
- /**
51
- * @dev Convert leverage from contract format to SDK format
52
- * @param leverage Leverage with 1e3 precision
53
- * @returns Leverage as SDK float (e.g., 10 = 10x)
54
- */
55
- const convertLeverage = (leverage) => {
56
- const value = typeof leverage === "bigint" ? Number(leverage) : leverage;
57
- return value / 1e3;
58
- };
59
- exports.convertLeverage = convertLeverage;
60
- /**
61
- * @dev Batch convert PnL results from contract format
62
- * @param results Array of PnL results from contract
63
- * @param collateralDecimals Collateral token decimals
64
- * @returns Array of converted PnL results
65
- */
66
- const convertPnlResults = (results, collateralDecimals) => {
67
- return results.map(result => ({
68
- pnlCollateral: (0, exports.convertCollateralAmount)(result.pnlCollateral, collateralDecimals),
69
- pnlPercent: (0, exports.convertPnlPercent)(result.pnlPercent),
70
- }));
71
- };
72
- exports.convertPnlResults = convertPnlResults;
@@ -1,77 +0,0 @@
1
- /**
2
- * @dev PnL calculation module
3
- * @dev Provides functions matching v10 contract implementations
4
- */
5
- import { Trade, TradeInfo, LiquidationParams, Fee, GlobalTradeFeeParams } from "../types";
6
- import { ComprehensivePnlResult, GetComprehensivePnlContext } from "./types";
7
- import { BorrowingFee } from "../fees/borrowing";
8
- import { ContractsVersion } from "../../contracts/types";
9
- /**
10
- * @dev Calculates PnL percentage for a position
11
- * @dev Mirrors contract's getPnlPercent function
12
- * @param openPrice Trade open price
13
- * @param currentPrice Current market price
14
- * @param long Whether position is long
15
- * @param leverage Position leverage
16
- * @returns PnL percentage (e.g., 10 = 10% profit, -50 = 50% loss)
17
- */
18
- export declare const getPnlPercent: (openPrice: number, currentPrice: number, long: boolean, leverage: number) => number;
19
- /**
20
- * @dev Calculates trade value from collateral and PnL
21
- * @dev Mirrors contract's getTradeValuePure function
22
- * @param collateral Trade collateral amount
23
- * @param pnlPercent PnL percentage
24
- * @param totalFees Total fees to deduct
25
- * @returns Trade value after PnL and fees
26
- */
27
- export declare const getTradeValue: (collateral: number, pnlPercent: number, totalFees: number) => number;
28
- /**
29
- * @dev Comprehensive PnL calculation including all fees
30
- * @param trade The trade to calculate PnL for
31
- * @param currentPrice Current market price
32
- * @param tradeInfo Trade info with version and timestamps
33
- * @param context Context with all fee parameters
34
- * @returns Detailed PnL breakdown
35
- */
36
- export declare const getComprehensivePnl: (trade: Trade, currentPrice: number, tradeInfo: TradeInfo, context: GetComprehensivePnlContext) => ComprehensivePnlResult;
37
- /**
38
- * @dev Legacy getPnl function for backward compatibility
39
- * @deprecated Use getComprehensivePnl for new implementations
40
- */
41
- export type GetPnlContext = {
42
- currentBlock: number;
43
- groups: BorrowingFee.Group[];
44
- pairs: BorrowingFee.Pair[];
45
- collateralPriceUsd: number | undefined;
46
- contractsVersion: ContractsVersion | undefined;
47
- feeMultiplier: number | undefined;
48
- fee: Fee;
49
- globalTradeFeeParams: GlobalTradeFeeParams;
50
- traderFeeMultiplier?: number;
51
- };
52
- /**
53
- * @dev Legacy PnL calculation function
54
- * @deprecated Use getComprehensivePnl for more comprehensive calculations
55
- * @param price Current price
56
- * @param trade Trade object
57
- * @param tradeInfo Trade info (not used in legacy implementation)
58
- * @param initialAccFees Initial accumulated fees
59
- * @param liquidationParams Liquidation parameters
60
- * @param useFees Whether to include fees
61
- * @param context Context with fee calculation parameters
62
- * @returns [pnlCollateral, pnlPercentage] or undefined if no price
63
- */
64
- export declare const getPnl: (price: number | undefined, trade: Trade, _tradeInfo: TradeInfo, initialAccFees: BorrowingFee.InitialAccFees, liquidationParams: LiquidationParams, useFees: boolean, context: GetPnlContext) => number[] | undefined;
65
- /**
66
- * @dev Calculates the price needed to achieve a target PnL percentage
67
- * @param targetPnlPercent The target PnL percentage (e.g., 50 for 50% profit, -25 for 25% loss)
68
- * @param trade The trade to calculate for
69
- * @param tradeInfo Trade info with timestamps
70
- * @param context Context with fee calculation parameters
71
- * @param netPnl Whether to include closing fees in the calculation
72
- * @returns The price that would result in the target PnL percentage
73
- */
74
- export declare const getPriceForTargetPnlPercentage: (targetPnlPercent: number, trade: Trade, tradeInfo: TradeInfo, context: GetComprehensivePnlContext, netPnl?: boolean) => number;
75
- export * from "./types";
76
- export * from "./converter";
77
- export * from "./builder";
@@ -1,270 +0,0 @@
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);
@@ -1,114 +0,0 @@
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
- };
@@ -1,5 +0,0 @@
1
- "use strict";
2
- /**
3
- * @dev Types for PnL calculations
4
- */
5
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,21 +0,0 @@
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;