@gainsnetwork/sdk 1.3.0-rc3 → 1.3.0-rc6

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 (47) hide show
  1. package/lib/backend/globalTrades/index.js +10 -10
  2. package/lib/backend/tradingVariables/converter.js +58 -57
  3. package/lib/backend/tradingVariables/index.js +6 -7
  4. package/lib/contracts/addresses.js +4 -1
  5. package/lib/contracts/index.d.ts +1 -1
  6. package/lib/contracts/index.js +3 -3
  7. package/lib/contracts/utils/borrowingFees.js +9 -20
  8. package/lib/contracts/utils/openTrades.js +11 -20
  9. package/lib/contracts/utils/pairs.js +21 -30
  10. package/lib/markets/forex.js +1 -1
  11. package/lib/markets/leverage/builder.js +2 -2
  12. package/lib/markets/price/index.d.ts +1 -0
  13. package/lib/markets/price/index.js +1 -0
  14. package/lib/markets/price/types.d.ts +27 -0
  15. package/lib/pricing/depthBands.d.ts +1 -1
  16. package/lib/pricing/depthBands.js +7 -5
  17. package/lib/trade/fees/borrowing/builder.js +2 -3
  18. package/lib/trade/fees/borrowing/converter.js +5 -1
  19. package/lib/trade/fees/borrowing/index.js +5 -5
  20. package/lib/trade/fees/borrowingV2/builder.js +3 -4
  21. package/lib/trade/fees/borrowingV2/converter.js +1 -1
  22. package/lib/trade/fees/borrowingV2/fetcher.js +26 -32
  23. package/lib/trade/fees/borrowingV2/index.js +3 -3
  24. package/lib/trade/fees/converter.js +22 -22
  25. package/lib/trade/fees/fundingFees/builder.js +6 -7
  26. package/lib/trade/fees/fundingFees/converter.js +1 -1
  27. package/lib/trade/fees/fundingFees/fetcher.js +16 -25
  28. package/lib/trade/fees/fundingFees/index.js +2 -3
  29. package/lib/trade/fees/tiers/index.js +1 -2
  30. package/lib/trade/fees/trading/index.js +5 -3
  31. package/lib/trade/liquidation/builder.js +1 -2
  32. package/lib/trade/liquidation/index.js +4 -6
  33. package/lib/trade/oiWindows.js +1 -2
  34. package/lib/trade/pnl/builder.js +1 -2
  35. package/lib/trade/pnl/converter.js +1 -1
  36. package/lib/trade/pnl/index.js +4 -7
  37. package/lib/trade/priceImpact/close/builder.js +1 -2
  38. package/lib/trade/priceImpact/close/index.js +4 -1
  39. package/lib/trade/priceImpact/cumulVol/builder.js +20 -10
  40. package/lib/trade/priceImpact/cumulVol/index.d.ts +3 -3
  41. package/lib/trade/priceImpact/cumulVol/index.js +47 -20
  42. package/lib/trade/priceImpact/open/builder.js +1 -2
  43. package/lib/trade/priceImpact/open/index.js +7 -1
  44. package/lib/trade/priceImpact/skew/builder.js +2 -3
  45. package/lib/trade/priceImpact/skew/converter.js +1 -1
  46. package/lib/trade/priceImpact/skew/fetcher.js +24 -33
  47. package/package.json +2 -2
@@ -1,26 +1,17 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.getPairDescription = exports.fetchOpenInterest = exports.fetchFees = exports.fetchDepthBandsMappingDecoded = exports.fetchDepthBandsMapping = exports.fetchPairDepthBandsDecoded = exports.fetchPairDepthBands = exports.fetchPairs = void 0;
13
4
  /* eslint-disable @typescript-eslint/no-unsafe-call */
14
5
  /* eslint-disable @typescript-eslint/no-unsafe-return */
15
6
  /* eslint-disable @typescript-eslint/no-unsafe-member-access */
16
7
  const types_1 = require("../../trade/types");
17
- const fetchPairs = (contracts, pairIxs) => __awaiter(void 0, void 0, void 0, function* () {
8
+ const fetchPairs = async (contracts, pairIxs) => {
18
9
  if (!contracts) {
19
10
  return [];
20
11
  }
21
12
  const { gnsMultiCollatDiamond: multiCollatContract } = contracts;
22
13
  try {
23
- const pairs = yield Promise.all(pairIxs.map(pairIndex => multiCollatContract.pairs(pairIndex)));
14
+ const pairs = await Promise.all(pairIxs.map(pairIndex => multiCollatContract.pairs(pairIndex)));
24
15
  return pairs.map((pair, index) => {
25
16
  return {
26
17
  name: pair.from + "/" + pair.to,
@@ -38,9 +29,9 @@ const fetchPairs = (contracts, pairIxs) => __awaiter(void 0, void 0, void 0, fun
38
29
  console.error(`Unexpected error while fetching pairs!`);
39
30
  throw error;
40
31
  }
41
- });
32
+ };
42
33
  exports.fetchPairs = fetchPairs;
43
- const fetchPairDepthBands = (contracts, pairIxs) => __awaiter(void 0, void 0, void 0, function* () {
34
+ const fetchPairDepthBands = async (contracts, pairIxs) => {
44
35
  if (!contracts || pairIxs.length === 0) {
45
36
  return [];
46
37
  }
@@ -48,16 +39,16 @@ const fetchPairDepthBands = (contracts, pairIxs) => __awaiter(void 0, void 0, vo
48
39
  try {
49
40
  // Returns array of PairDepthBands structs (encoded slots)
50
41
  // Using quoted signature for overloaded function
51
- const depthBands = yield multiCollatContract["getPairDepthBands(uint256[])"](pairIxs);
42
+ const depthBands = await multiCollatContract["getPairDepthBands(uint256[])"](pairIxs);
52
43
  return depthBands;
53
44
  }
54
45
  catch (error) {
55
46
  console.error(`Unexpected error while fetching pair depth bands!`);
56
47
  throw error;
57
48
  }
58
- });
49
+ };
59
50
  exports.fetchPairDepthBands = fetchPairDepthBands;
60
- const fetchPairDepthBandsDecoded = (contracts, pairIxs) => __awaiter(void 0, void 0, void 0, function* () {
51
+ const fetchPairDepthBandsDecoded = async (contracts, pairIxs) => {
61
52
  if (!contracts || pairIxs.length === 0) {
62
53
  return {
63
54
  totalDepthAboveUsd: [],
@@ -70,7 +61,7 @@ const fetchPairDepthBandsDecoded = (contracts, pairIxs) => __awaiter(void 0, voi
70
61
  try {
71
62
  // Returns decoded values
72
63
  // Using quoted signature for overloaded function
73
- const [totalDepthAboveUsd, totalDepthBelowUsd, bandsAbove, bandsBelow] = yield multiCollatContract["getPairDepthBandsDecoded(uint256[])"](pairIxs);
64
+ const [totalDepthAboveUsd, totalDepthBelowUsd, bandsAbove, bandsBelow] = await multiCollatContract["getPairDepthBandsDecoded(uint256[])"](pairIxs);
74
65
  return {
75
66
  totalDepthAboveUsd: totalDepthAboveUsd.map((v) => parseFloat(v.toString())),
76
67
  totalDepthBelowUsd: totalDepthBelowUsd.map((v) => parseFloat(v.toString())),
@@ -82,16 +73,16 @@ const fetchPairDepthBandsDecoded = (contracts, pairIxs) => __awaiter(void 0, voi
82
73
  console.error(`Unexpected error while fetching decoded pair depth bands!`);
83
74
  throw error;
84
75
  }
85
- });
76
+ };
86
77
  exports.fetchPairDepthBandsDecoded = fetchPairDepthBandsDecoded;
87
- const fetchDepthBandsMapping = (contracts) => __awaiter(void 0, void 0, void 0, function* () {
78
+ const fetchDepthBandsMapping = async (contracts) => {
88
79
  if (!contracts) {
89
80
  return { slot1: "0", slot2: "0" };
90
81
  }
91
82
  const { gnsMultiCollatDiamond: multiCollatContract } = contracts;
92
83
  try {
93
84
  // Returns two uint256 slots
94
- const [slot1, slot2] = yield multiCollatContract.getDepthBandsMapping();
85
+ const [slot1, slot2] = await multiCollatContract.getDepthBandsMapping();
95
86
  return {
96
87
  slot1: slot1.toString(),
97
88
  slot2: slot2.toString(),
@@ -101,31 +92,31 @@ const fetchDepthBandsMapping = (contracts) => __awaiter(void 0, void 0, void 0,
101
92
  console.error(`Unexpected error while fetching depth bands mapping!`);
102
93
  throw error;
103
94
  }
104
- });
95
+ };
105
96
  exports.fetchDepthBandsMapping = fetchDepthBandsMapping;
106
- const fetchDepthBandsMappingDecoded = (contracts) => __awaiter(void 0, void 0, void 0, function* () {
97
+ const fetchDepthBandsMappingDecoded = async (contracts) => {
107
98
  if (!contracts) {
108
99
  return [];
109
100
  }
110
101
  const { gnsMultiCollatDiamond: multiCollatContract } = contracts;
111
102
  try {
112
103
  // Returns array of 30 uint16 values
113
- const bands = yield multiCollatContract.getDepthBandsMappingDecoded();
104
+ const bands = await multiCollatContract.getDepthBandsMappingDecoded();
114
105
  return bands.map((b) => parseInt(b.toString()));
115
106
  }
116
107
  catch (error) {
117
108
  console.error(`Unexpected error while fetching decoded depth bands mapping!`);
118
109
  throw error;
119
110
  }
120
- });
111
+ };
121
112
  exports.fetchDepthBandsMappingDecoded = fetchDepthBandsMappingDecoded;
122
- const fetchFees = (contracts, feeIxs) => __awaiter(void 0, void 0, void 0, function* () {
113
+ const fetchFees = async (contracts, feeIxs) => {
123
114
  if (!contracts) {
124
115
  return [];
125
116
  }
126
117
  const { gnsMultiCollatDiamond: multiCollatContract } = contracts;
127
118
  try {
128
- const fees = yield Promise.all(feeIxs.map(pairIndex => multiCollatContract.fees(pairIndex)));
119
+ const fees = await Promise.all(feeIxs.map(pairIndex => multiCollatContract.fees(pairIndex)));
129
120
  return fees.map(fee => {
130
121
  return {
131
122
  totalPositionSizeFeeP: parseFloat(fee.totalPositionSizeFeeP.toString()) / 1e12,
@@ -139,13 +130,13 @@ const fetchFees = (contracts, feeIxs) => __awaiter(void 0, void 0, void 0, funct
139
130
  console.error(`Unexpected error while fetching pairs!`);
140
131
  throw error;
141
132
  }
142
- });
133
+ };
143
134
  exports.fetchFees = fetchFees;
144
- const fetchOpenInterest = (contracts, collateralIndex, pairIxs) => __awaiter(void 0, void 0, void 0, function* () {
135
+ const fetchOpenInterest = async (contracts, collateralIndex, pairIxs) => {
145
136
  if (pairIxs.length === 0) {
146
137
  return [];
147
138
  }
148
- const openInterests = (yield contracts.gnsMultiCollatDiamond.getAllBorrowingPairs(collateralIndex))[1];
139
+ const openInterests = (await contracts.gnsMultiCollatDiamond.getAllBorrowingPairs(collateralIndex))[1];
149
140
  return pairIxs.map(pairIndex => {
150
141
  const openInterest = openInterests[pairIndex];
151
142
  if (!openInterest) {
@@ -157,7 +148,7 @@ const fetchOpenInterest = (contracts, collateralIndex, pairIxs) => __awaiter(voi
157
148
  max: parseFloat(openInterest[2].toString()) / 1e10,
158
149
  };
159
150
  });
160
- });
151
+ };
161
152
  exports.fetchOpenInterest = fetchOpenInterest;
162
153
  const getPairDescription = (pairIndex) => {
163
154
  return PAIR_INDEX_TO_DESCRIPTION[pairIndex] || "";
@@ -33,7 +33,7 @@ const isForexLowLiquidity = (timestampToCheck, pair) => {
33
33
  const hour = now.hour;
34
34
  const minute = now.minute;
35
35
  const isInDST = now.isInDST;
36
- const groupIndex = pair === null || pair === void 0 ? void 0 : pair.groupIndex;
36
+ const groupIndex = pair?.groupIndex;
37
37
  if (groupIndex && extendedLowLiqGroupIds.includes(+groupIndex)) {
38
38
  return ((isInDST &&
39
39
  ((hour == 14 && minute >= 45) || (hour >= 15 && hour < 21))) ||
@@ -18,8 +18,8 @@ const buildMarketLeverageRestrictionsContext = (globalTradingVariables, pairInde
18
18
  return {
19
19
  groupMinLeverage: group.minLeverage,
20
20
  groupMaxLeverage: group.maxLeverage,
21
- pairMaxLeverage: pairMaxLeverages === null || pairMaxLeverages === void 0 ? void 0 : pairMaxLeverages[pairIndex],
22
- counterTradeSettings: counterTradeSettings === null || counterTradeSettings === void 0 ? void 0 : counterTradeSettings[pairIndex],
21
+ pairMaxLeverage: pairMaxLeverages?.[pairIndex],
22
+ counterTradeSettings: counterTradeSettings?.[pairIndex],
23
23
  };
24
24
  };
25
25
  exports.buildMarketLeverageRestrictionsContext = buildMarketLeverageRestrictionsContext;
@@ -4,3 +4,4 @@
4
4
  export * from "./types";
5
5
  export * from "./marketPrice";
6
6
  export * from "./builder";
7
+ export * from "./signedPrices";
@@ -20,3 +20,4 @@ Object.defineProperty(exports, "__esModule", { value: true });
20
20
  __exportStar(require("./types"), exports);
21
21
  __exportStar(require("./marketPrice"), exports);
22
22
  __exportStar(require("./builder"), exports);
23
+ __exportStar(require("./signedPrices"), exports);
@@ -21,3 +21,30 @@ export type MarketPriceContext = {
21
21
  oiShortToken: number;
22
22
  };
23
23
  };
24
+ /**
25
+ * @dev Types for signed prices data structure
26
+ */
27
+ export type SignedPricesResponse = {
28
+ signedData: SignedPrices;
29
+ missingPrices: number[];
30
+ };
31
+ export type SignedPrices = {
32
+ signerId: number;
33
+ expiryTs: number;
34
+ fromBlock: number;
35
+ isLookback: boolean;
36
+ pairIndices: number[];
37
+ prices: Price[];
38
+ signature: string;
39
+ };
40
+ export type Price = {
41
+ open: string;
42
+ high: string;
43
+ low: string;
44
+ current: string;
45
+ ts: number;
46
+ };
47
+ export type Oracle = {
48
+ url: string;
49
+ key?: string;
50
+ };
@@ -32,7 +32,7 @@ export declare function encodeDepthBandsMapping(bands: number[]): {
32
32
  };
33
33
  /**
34
34
  * Decode depth bands mapping from two uint256 slots
35
- * @param slot1 First slot containing bands 0-13
35
+ * @param slot1 First slot containing bands 0-13 (starting at bit 32, first 32 bits unused)
36
36
  * @param slot2 Second slot containing bands 14-29
37
37
  * @returns Array of band offset values in ppm
38
38
  */
@@ -56,10 +56,11 @@ exports.decodeDepthBands = decodeDepthBands;
56
56
  * @returns Two slots as bigints
57
57
  */
58
58
  function encodeDepthBandsMapping(bands) {
59
- // Pack slot1: bands 0-13 (14 * 16 bits)
59
+ // Pack slot1: bands 0-13 (starting at bit 32, first 32 bits unused)
60
60
  let slot1 = BigInt(0);
61
61
  for (let i = 0; i < DEPTH_BANDS_PER_SLOT1; i++) {
62
- slot1 |= BigInt(bands[i]) << BigInt(i * 16);
62
+ const shift = 32 + i * 16; // Start at bit 32 to match contract
63
+ slot1 |= BigInt(bands[i]) << BigInt(shift);
63
64
  }
64
65
  // Pack slot2: bands 14-29 (16 * 16 bits)
65
66
  let slot2 = BigInt(0);
@@ -72,15 +73,16 @@ function encodeDepthBandsMapping(bands) {
72
73
  exports.encodeDepthBandsMapping = encodeDepthBandsMapping;
73
74
  /**
74
75
  * Decode depth bands mapping from two uint256 slots
75
- * @param slot1 First slot containing bands 0-13
76
+ * @param slot1 First slot containing bands 0-13 (starting at bit 32, first 32 bits unused)
76
77
  * @param slot2 Second slot containing bands 14-29
77
78
  * @returns Array of band offset values in ppm
78
79
  */
79
80
  function decodeDepthBandsMapping(slot1, slot2) {
80
81
  const bands = [];
81
- // Extract bands 0-13 from slot1
82
+ // Extract bands 0-13 from slot1 (skip first 32 bits which are unused for mappings)
82
83
  for (let i = 0; i < DEPTH_BANDS_PER_SLOT1; i++) {
83
- bands.push(Number((slot1 >> BigInt(i * 16)) & BigInt(0xffff)));
84
+ const shift = 32 + i * 16; // Start at bit 32, not bit 0
85
+ bands.push(Number((slot1 >> BigInt(shift)) & BigInt(0xffff)));
84
86
  }
85
87
  // Extract bands 14-29 from slot2
86
88
  for (let i = DEPTH_BANDS_PER_SLOT1; i < DEPTH_BANDS_COUNT; i++) {
@@ -13,9 +13,8 @@ exports.buildBorrowingV1Context = void 0;
13
13
  * @returns Full borrowing context with all pairs and groups or undefined if data not available
14
14
  */
15
15
  const buildBorrowingV1Context = (globalTradingVariables, collateralIndex, currentBlock) => {
16
- var _a;
17
16
  const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
18
- if (!(collateral === null || collateral === void 0 ? void 0 : collateral.pairBorrowingFees) || !(collateral === null || collateral === void 0 ? void 0 : collateral.groupBorrowingFees)) {
17
+ if (!collateral?.pairBorrowingFees || !collateral?.groupBorrowingFees) {
19
18
  return undefined;
20
19
  }
21
20
  const pairs = collateral.pairBorrowingFees;
@@ -27,7 +26,7 @@ const buildBorrowingV1Context = (globalTradingVariables, collateralIndex, curren
27
26
  currentBlock,
28
27
  pairs,
29
28
  groups,
30
- collateralPriceUsd: ((_a = collateral.prices) === null || _a === void 0 ? void 0 : _a.collateralPriceUsd) || 1,
29
+ collateralPriceUsd: collateral.prices?.collateralPriceUsd || 1,
31
30
  pairOis: collateral.pairOis,
32
31
  };
33
32
  };
@@ -14,7 +14,11 @@ const convertPairGroupBorrowingFee = (pairGroup) => ({
14
14
  block: pairGroup.block,
15
15
  });
16
16
  exports.convertPairGroupBorrowingFee = convertPairGroupBorrowingFee;
17
- const convertPairBorrowingFee = (pair, pairOi, pairGroup, feeCap) => (Object.assign(Object.assign({}, (0, exports.convertGroupBorrowingData)(pair, pairOi)), { groups: pairGroup.map(value => (0, exports.convertPairGroupBorrowingFee)(value)), feePerBlockCap: (0, exports.convertFeePerBlockCap)(feeCap) }));
17
+ const convertPairBorrowingFee = (pair, pairOi, pairGroup, feeCap) => ({
18
+ ...(0, exports.convertGroupBorrowingData)(pair, pairOi),
19
+ groups: pairGroup.map(value => (0, exports.convertPairGroupBorrowingFee)(value)),
20
+ feePerBlockCap: (0, exports.convertFeePerBlockCap)(feeCap),
21
+ });
18
22
  exports.convertPairBorrowingFee = convertPairBorrowingFee;
19
23
  const convertPairBorrowingFees = ([pairs, pairOi, pairGroups, feeCaps]) => pairs.map((value, ix) => (0, exports.convertPairBorrowingFee)(value, pairOi[ix], pairGroups[ix], feeCaps[ix]));
20
24
  exports.convertPairBorrowingFees = convertPairBorrowingFees;
@@ -48,7 +48,7 @@ const getBorrowingFee = (posDai, pairIndex, long, initialAccFees, currentPairPri
48
48
  return 0;
49
49
  }
50
50
  const pairGroups = pairs[pairIndex].groups;
51
- const firstPairGroup = (pairGroups === null || pairGroups === void 0 ? void 0 : pairGroups.length) > 0 ? pairGroups[0] : undefined;
51
+ const firstPairGroup = pairGroups?.length > 0 ? pairGroups[0] : undefined;
52
52
  let fee = 0;
53
53
  if (!firstPairGroup || firstPairGroup.block > initialAccFees.block) {
54
54
  const openInterest = (0, __1.getPairTotalOisDynamicCollateral)(pairIndex, {
@@ -215,13 +215,13 @@ collateralPriceUsd) => {
215
215
  };
216
216
  const getPendingAccFeesDelta = (blockDistance, feePerBlock, netOi, maxOi, feeExponent) => {
217
217
  return maxOi > 0 && feeExponent > 0
218
- ? feePerBlock * blockDistance * Math.pow((netOi / maxOi), feeExponent)
218
+ ? feePerBlock * blockDistance * (netOi / maxOi) ** feeExponent
219
219
  : 0;
220
220
  };
221
221
  const getFeePerBlockCaps = (cap) => {
222
222
  return {
223
- minP: (cap === null || cap === void 0 ? void 0 : cap.minP) || 0,
224
- maxP: (cap === null || cap === void 0 ? void 0 : cap.maxP) && cap.maxP > 0 ? cap.maxP : 1,
223
+ minP: cap?.minP || 0,
224
+ maxP: cap?.maxP && cap.maxP > 0 ? cap.maxP : 1,
225
225
  };
226
226
  };
227
227
  const getBorrowingDataActiveFeePerBlock = (val) => {
@@ -231,7 +231,7 @@ const getBorrowingDataActiveFeePerBlock = (val) => {
231
231
  // If minP > 0 then netOi has to be at least minP * maxOi
232
232
  // If maxP > 0 then netOi cannot be more than maxP * maxOi
233
233
  const effectiveOi = Math.min(Math.max(Math.abs(long - short), max * minP), max * maxP);
234
- return val.feePerBlock * Math.pow((effectiveOi / max), val.feeExponent);
234
+ return val.feePerBlock * (effectiveOi / max) ** val.feeExponent;
235
235
  };
236
236
  const getActiveFeePerBlock = (pair, group) => {
237
237
  const pairFeePerBlock = getBorrowingDataActiveFeePerBlock(pair);
@@ -5,13 +5,12 @@ exports.buildBorrowingV2Context = void 0;
5
5
  * @dev Builds borrowing v2 sub-context for a specific pair
6
6
  */
7
7
  const buildBorrowingV2Context = (globalTradingVariables, collateralIndex, pairIndex, currentTimestamp) => {
8
- var _a, _b;
9
8
  const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
10
- if (!(collateral === null || collateral === void 0 ? void 0 : collateral.pairBorrowingFeesV2)) {
9
+ if (!collateral?.pairBorrowingFeesV2) {
11
10
  return undefined;
12
11
  }
13
- const params = (_a = collateral.pairBorrowingFeesV2.params) === null || _a === void 0 ? void 0 : _a[pairIndex];
14
- const data = (_b = collateral.pairBorrowingFeesV2.data) === null || _b === void 0 ? void 0 : _b[pairIndex];
12
+ const params = collateral.pairBorrowingFeesV2.params?.[pairIndex];
13
+ const data = collateral.pairBorrowingFeesV2.data?.[pairIndex];
15
14
  if (!params || !data) {
16
15
  return undefined;
17
16
  }
@@ -116,7 +116,7 @@ exports.aprToBorrowingRate = aprToBorrowingRate;
116
116
  */
117
117
  const createCollateralScopedBorrowingContext = (collateralBorrowingData, currentTimestamp) => {
118
118
  const context = {
119
- currentTimestamp: currentTimestamp !== null && currentTimestamp !== void 0 ? currentTimestamp : Math.floor(Date.now() / 1000),
119
+ currentTimestamp: currentTimestamp ?? Math.floor(Date.now() / 1000),
120
120
  borrowingParams: {},
121
121
  borrowingData: {},
122
122
  };
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.fetchBorrowingV2DataForPairs = exports.createBorrowingV2ContextFromArrays = exports.createBorrowingV2ContextFromContract = exports.fetchAllBorrowingV2Data = exports.fetchPairPendingAccBorrowingFeesV2 = exports.fetchTradeBorrowingFeesCollateralV2 = exports.fetchPairBorrowingFeeDataV2 = exports.fetchBorrowingFeeParamsV2 = void 0;
13
4
  const converter_1 = require("./converter");
@@ -18,19 +9,19 @@ const converter_1 = require("./converter");
18
9
  * @param pairIndices Array of pair indices
19
10
  * @returns Promise resolving to array of borrowing fee parameters
20
11
  */
21
- const fetchBorrowingFeeParamsV2 = (contract, collateralIndices, pairIndices) => __awaiter(void 0, void 0, void 0, function* () {
12
+ const fetchBorrowingFeeParamsV2 = async (contract, collateralIndices, pairIndices) => {
22
13
  if (collateralIndices.length !== pairIndices.length) {
23
14
  throw new Error("Collateral indices and pair indices arrays must have the same length");
24
15
  }
25
16
  try {
26
- const contractParams = yield contract.getPairBorrowingFeeParams(collateralIndices, pairIndices);
17
+ const contractParams = await contract.getPairBorrowingFeeParams(collateralIndices, pairIndices);
27
18
  return (0, converter_1.convertBorrowingFeeParamsArray)(contractParams);
28
19
  }
29
20
  catch (error) {
30
21
  console.error("Error fetching borrowing fee params v2:", error);
31
22
  throw error;
32
23
  }
33
- });
24
+ };
34
25
  exports.fetchBorrowingFeeParamsV2 = fetchBorrowingFeeParamsV2;
35
26
  /**
36
27
  * @dev Fetches pair borrowing fee data v2 for specific pairs
@@ -39,19 +30,19 @@ exports.fetchBorrowingFeeParamsV2 = fetchBorrowingFeeParamsV2;
39
30
  * @param pairIndices Array of pair indices
40
31
  * @returns Promise resolving to array of pair borrowing fee data
41
32
  */
42
- const fetchPairBorrowingFeeDataV2 = (contract, collateralIndices, pairIndices) => __awaiter(void 0, void 0, void 0, function* () {
33
+ const fetchPairBorrowingFeeDataV2 = async (contract, collateralIndices, pairIndices) => {
43
34
  if (collateralIndices.length !== pairIndices.length) {
44
35
  throw new Error("Collateral indices and pair indices arrays must have the same length");
45
36
  }
46
37
  try {
47
- const contractData = yield contract.getPairBorrowingFeeData(collateralIndices, pairIndices);
38
+ const contractData = await contract.getPairBorrowingFeeData(collateralIndices, pairIndices);
48
39
  return (0, converter_1.convertPairBorrowingFeeDataArray)(contractData);
49
40
  }
50
41
  catch (error) {
51
42
  console.error("Error fetching pair borrowing fee data v2:", error);
52
43
  throw error;
53
44
  }
54
- });
45
+ };
55
46
  exports.fetchPairBorrowingFeeDataV2 = fetchPairBorrowingFeeDataV2;
56
47
  /**
57
48
  * @dev Fetches borrowing fees in collateral tokens for a specific trade
@@ -61,9 +52,9 @@ exports.fetchPairBorrowingFeeDataV2 = fetchPairBorrowingFeeDataV2;
61
52
  * @param currentPairPrice Current price of the trading pair (1e6 precision)
62
53
  * @returns Promise resolving to borrowing fees in collateral tokens
63
54
  */
64
- const fetchTradeBorrowingFeesCollateralV2 = (contract, trader, index, currentPairPrice) => __awaiter(void 0, void 0, void 0, function* () {
55
+ const fetchTradeBorrowingFeesCollateralV2 = async (contract, trader, index, currentPairPrice) => {
65
56
  try {
66
- const feesCollateral = yield contract.getTradeBorrowingFeesCollateral(trader, index, currentPairPrice);
57
+ const feesCollateral = await contract.getTradeBorrowingFeesCollateral(trader, index, currentPairPrice);
67
58
  // Convert BigNumber to normalized float
68
59
  // Note: Collateral precision varies by chain, but contract returns proper precision
69
60
  return parseFloat(feesCollateral.toString());
@@ -72,7 +63,7 @@ const fetchTradeBorrowingFeesCollateralV2 = (contract, trader, index, currentPai
72
63
  console.error("Error fetching trade borrowing fees collateral v2:", error);
73
64
  throw error;
74
65
  }
75
- });
66
+ };
76
67
  exports.fetchTradeBorrowingFeesCollateralV2 = fetchTradeBorrowingFeesCollateralV2;
77
68
  /**
78
69
  * @dev Fetches pending accumulated borrowing fees for a specific pair
@@ -82,9 +73,9 @@ exports.fetchTradeBorrowingFeesCollateralV2 = fetchTradeBorrowingFeesCollateralV
82
73
  * @param currentPairPrice Current price of the trading pair (1e6 precision)
83
74
  * @returns Promise resolving to pending accumulated borrowing fee
84
75
  */
85
- const fetchPairPendingAccBorrowingFeesV2 = (contract, collateralIndex, pairIndex, currentPairPrice) => __awaiter(void 0, void 0, void 0, function* () {
76
+ const fetchPairPendingAccBorrowingFeesV2 = async (contract, collateralIndex, pairIndex, currentPairPrice) => {
86
77
  try {
87
- const accBorrowingFeeP = yield contract.getPairPendingAccBorrowingFees(collateralIndex, pairIndex, currentPairPrice);
78
+ const accBorrowingFeeP = await contract.getPairPendingAccBorrowingFees(collateralIndex, pairIndex, currentPairPrice);
88
79
  // Convert BigNumber to normalized float
89
80
  return parseFloat(accBorrowingFeeP.toString()) / 1e20;
90
81
  }
@@ -92,7 +83,7 @@ const fetchPairPendingAccBorrowingFeesV2 = (contract, collateralIndex, pairIndex
92
83
  console.error("Error fetching pair pending acc borrowing fees v2:", error);
93
84
  throw error;
94
85
  }
95
- });
86
+ };
96
87
  exports.fetchPairPendingAccBorrowingFeesV2 = fetchPairPendingAccBorrowingFeesV2;
97
88
  /**
98
89
  * @dev Convenience function to fetch all borrowing v2 data for specific pairs
@@ -101,11 +92,11 @@ exports.fetchPairPendingAccBorrowingFeesV2 = fetchPairPendingAccBorrowingFeesV2;
101
92
  * @param pairIndices Array of pair indices
102
93
  * @returns Promise resolving to complete borrowing v2 data set
103
94
  */
104
- const fetchAllBorrowingV2Data = (contract, collateralIndex, pairIndices) => __awaiter(void 0, void 0, void 0, function* () {
95
+ const fetchAllBorrowingV2Data = async (contract, collateralIndex, pairIndices) => {
105
96
  const collateralIndices = new Array(pairIndices.length).fill(collateralIndex);
106
97
  try {
107
98
  // Fetch both parameters and data in parallel
108
- const [params, data] = yield Promise.all([
99
+ const [params, data] = await Promise.all([
109
100
  (0, exports.fetchBorrowingFeeParamsV2)(contract, collateralIndices, pairIndices),
110
101
  (0, exports.fetchPairBorrowingFeeDataV2)(contract, collateralIndices, pairIndices),
111
102
  ]);
@@ -117,7 +108,7 @@ const fetchAllBorrowingV2Data = (contract, collateralIndex, pairIndices) => __aw
117
108
  console.error("Error fetching all borrowing v2 data:", error);
118
109
  throw error;
119
110
  }
120
- });
111
+ };
121
112
  exports.fetchAllBorrowingV2Data = fetchAllBorrowingV2Data;
122
113
  /**
123
114
  * @dev Creates a complete borrowing v2 context from contract data
@@ -127,10 +118,13 @@ exports.fetchAllBorrowingV2Data = fetchAllBorrowingV2Data;
127
118
  * @param currentTimestamp Optional current timestamp for calculations
128
119
  * @returns Promise resolving to complete borrowing v2 context
129
120
  */
130
- const createBorrowingV2ContextFromContract = (contract, collateralIndex, pairIndices, currentTimestamp) => __awaiter(void 0, void 0, void 0, function* () {
131
- const { context } = yield (0, exports.fetchAllBorrowingV2Data)(contract, collateralIndex, pairIndices);
132
- return Object.assign(Object.assign({}, context), { currentTimestamp: currentTimestamp !== null && currentTimestamp !== void 0 ? currentTimestamp : Math.floor(Date.now() / 1000) });
133
- });
121
+ const createBorrowingV2ContextFromContract = async (contract, collateralIndex, pairIndices, currentTimestamp) => {
122
+ const { context } = await (0, exports.fetchAllBorrowingV2Data)(contract, collateralIndex, pairIndices);
123
+ return {
124
+ ...context,
125
+ currentTimestamp: currentTimestamp ?? Math.floor(Date.now() / 1000),
126
+ };
127
+ };
134
128
  exports.createBorrowingV2ContextFromContract = createBorrowingV2ContextFromContract;
135
129
  /**
136
130
  * @dev Helper function to create context from already fetched arrays
@@ -143,7 +137,7 @@ exports.createBorrowingV2ContextFromContract = createBorrowingV2ContextFromContr
143
137
  */
144
138
  const createBorrowingV2ContextFromArrays = (collateralIndices, pairIndices, params, data, currentTimestamp) => {
145
139
  const context = {
146
- currentTimestamp: currentTimestamp !== null && currentTimestamp !== void 0 ? currentTimestamp : Math.floor(Date.now() / 1000),
140
+ currentTimestamp: currentTimestamp ?? Math.floor(Date.now() / 1000),
147
141
  borrowingParams: {},
148
142
  borrowingData: {},
149
143
  };
@@ -164,13 +158,13 @@ exports.createBorrowingV2ContextFromArrays = createBorrowingV2ContextFromArrays;
164
158
  * @param pairIndices Array of pair indices (must match collateralIndices length)
165
159
  * @returns Promise resolving to complete borrowing v2 context
166
160
  */
167
- const fetchBorrowingV2DataForPairs = (contract, collateralIndices, pairIndices) => __awaiter(void 0, void 0, void 0, function* () {
161
+ const fetchBorrowingV2DataForPairs = async (contract, collateralIndices, pairIndices) => {
168
162
  if (collateralIndices.length !== pairIndices.length) {
169
163
  throw new Error("Collateral indices and pair indices arrays must have the same length");
170
164
  }
171
165
  try {
172
166
  // Fetch both parameters and data in parallel
173
- const [params, data] = yield Promise.all([
167
+ const [params, data] = await Promise.all([
174
168
  (0, exports.fetchBorrowingFeeParamsV2)(contract, collateralIndices, pairIndices),
175
169
  (0, exports.fetchPairBorrowingFeeDataV2)(contract, collateralIndices, pairIndices),
176
170
  ]);
@@ -181,5 +175,5 @@ const fetchBorrowingV2DataForPairs = (contract, collateralIndices, pairIndices)
181
175
  console.error("Error fetching borrowing v2 data for pairs:", error);
182
176
  throw error;
183
177
  }
184
- });
178
+ };
185
179
  exports.fetchBorrowingV2DataForPairs = fetchBorrowingV2DataForPairs;
@@ -48,7 +48,7 @@ exports.BORROWING_V2_PRECISION = {
48
48
  * @returns Updated accumulated borrowing fee (1e20 precision)
49
49
  */
50
50
  const getPairPendingAccBorrowingFees = (params, data, currentPairPrice, currentTimestamp) => {
51
- const timestamp = currentTimestamp !== null && currentTimestamp !== void 0 ? currentTimestamp : Math.floor(Date.now() / 1000);
51
+ const timestamp = currentTimestamp ?? Math.floor(Date.now() / 1000);
52
52
  // Calculate time elapsed since last update
53
53
  const timeElapsed = Math.max(0, timestamp - data.lastBorrowingUpdateTs);
54
54
  // If no time elapsed, return current accumulated fee
@@ -74,7 +74,7 @@ const getTradeBorrowingFeesCollateral = (input, context) => {
74
74
  return 0;
75
75
  }
76
76
  // Calculate current accumulated borrowing fees
77
- const currentAccBorrowingFeeP = (0, exports.getPairPendingAccBorrowingFees)(params, data, currentPairPrice, currentTimestamp !== null && currentTimestamp !== void 0 ? currentTimestamp : context.currentTimestamp);
77
+ const currentAccBorrowingFeeP = (0, exports.getPairPendingAccBorrowingFees)(params, data, currentPairPrice, currentTimestamp ?? context.currentTimestamp);
78
78
  // Calculate borrowing fees for this trade
79
79
  // Formula: (positionSizeCollateral * (currentAccFee - initialAccFee)) / openPrice / 100
80
80
  const feeDeltaP = currentAccBorrowingFeeP - initialAccBorrowingFeeP;
@@ -96,7 +96,7 @@ const getPairBorrowingFees = (input, context) => {
96
96
  if (!params || !data) {
97
97
  return 0;
98
98
  }
99
- return (0, exports.getPairPendingAccBorrowingFees)(params, data, currentPairPrice, currentTimestamp !== null && currentTimestamp !== void 0 ? currentTimestamp : context.currentTimestamp);
99
+ return (0, exports.getPairPendingAccBorrowingFees)(params, data, currentPairPrice, currentTimestamp ?? context.currentTimestamp);
100
100
  };
101
101
  exports.getPairBorrowingFees = getPairBorrowingFees;
102
102
  /**
@@ -16,14 +16,14 @@ const convertTradeFeesData = (data, collateralConfig) => {
16
16
  const decimals = collateralConfig.decimals || 18;
17
17
  return {
18
18
  realizedTradingFeesCollateral: parseFloat(data.realizedTradingFeesCollateral.toString()) /
19
- Math.pow(10, decimals),
20
- realizedPnlCollateral: parseFloat(data.realizedPnlCollateral.toString()) / Math.pow(10, decimals),
19
+ 10 ** decimals,
20
+ realizedPnlCollateral: parseFloat(data.realizedPnlCollateral.toString()) / 10 ** decimals,
21
21
  manuallyRealizedNegativePnlCollateral: parseFloat(data.manuallyRealizedNegativePnlCollateral.toString()) /
22
- Math.pow(10, decimals),
22
+ 10 ** decimals,
23
23
  alreadyTransferredNegativePnlCollateral: parseFloat(data.alreadyTransferredNegativePnlCollateral.toString()) /
24
- Math.pow(10, decimals),
24
+ 10 ** decimals,
25
25
  virtualAvailableCollateralInDiamond: parseFloat(data.virtualAvailableCollateralInDiamond.toString()) /
26
- Math.pow(10, decimals),
26
+ 10 ** decimals,
27
27
  initialAccFundingFeeP: parseFloat(data.initialAccFundingFeeP.toString()) /
28
28
  converter_1.FUNDING_FEES_PRECISION.ACC_FUNDING_FEE_P,
29
29
  initialAccBorrowingFeeP: parseFloat(data.initialAccBorrowingFeeP.toString()) /
@@ -51,16 +51,16 @@ const convertUiRealizedPnlData = (data, collateralConfig) => {
51
51
  const decimals = collateralConfig.decimals || 18;
52
52
  return {
53
53
  realizedTradingFeesCollateral: parseFloat(data.realizedTradingFeesCollateral.toString()) /
54
- Math.pow(10, decimals),
54
+ 10 ** decimals,
55
55
  realizedOldBorrowingFeesCollateral: parseFloat(data.realizedOldBorrowingFeesCollateral.toString()) /
56
- Math.pow(10, decimals),
56
+ 10 ** decimals,
57
57
  realizedNewBorrowingFeesCollateral: parseFloat(data.realizedNewBorrowingFeesCollateral.toString()) /
58
- Math.pow(10, decimals),
58
+ 10 ** decimals,
59
59
  realizedFundingFeesCollateral: parseFloat(data.realizedFundingFeesCollateral.toString()) /
60
- Math.pow(10, decimals),
60
+ 10 ** decimals,
61
61
  realizedPnlPartialCloseCollateral: parseFloat(data.realizedPnlPartialCloseCollateral.toString()) /
62
- Math.pow(10, decimals),
63
- pnlWithdrawnCollateral: parseFloat(data.pnlWithdrawnCollateral.toString()) / Math.pow(10, decimals),
62
+ 10 ** decimals,
63
+ pnlWithdrawnCollateral: parseFloat(data.pnlWithdrawnCollateral.toString()) / 10 ** decimals,
64
64
  };
65
65
  };
66
66
  exports.convertUiRealizedPnlData = convertUiRealizedPnlData;
@@ -83,11 +83,11 @@ exports.convertUiRealizedPnlDataArray = convertUiRealizedPnlDataArray;
83
83
  const encodeTradeFeesData = (data, collateralConfig) => {
84
84
  const decimals = collateralConfig.decimals || 18;
85
85
  return {
86
- realizedTradingFeesCollateral: Math.round(data.realizedTradingFeesCollateral * Math.pow(10, decimals)),
87
- realizedPnlCollateral: Math.round(data.realizedPnlCollateral * Math.pow(10, decimals)),
88
- manuallyRealizedNegativePnlCollateral: Math.round(data.manuallyRealizedNegativePnlCollateral * Math.pow(10, decimals)),
89
- alreadyTransferredNegativePnlCollateral: Math.round(data.alreadyTransferredNegativePnlCollateral * Math.pow(10, decimals)),
90
- virtualAvailableCollateralInDiamond: Math.round(data.virtualAvailableCollateralInDiamond * Math.pow(10, decimals)),
86
+ realizedTradingFeesCollateral: Math.round(data.realizedTradingFeesCollateral * 10 ** decimals),
87
+ realizedPnlCollateral: Math.round(data.realizedPnlCollateral * 10 ** decimals),
88
+ manuallyRealizedNegativePnlCollateral: Math.round(data.manuallyRealizedNegativePnlCollateral * 10 ** decimals),
89
+ alreadyTransferredNegativePnlCollateral: Math.round(data.alreadyTransferredNegativePnlCollateral * 10 ** decimals),
90
+ virtualAvailableCollateralInDiamond: Math.round(data.virtualAvailableCollateralInDiamond * 10 ** decimals),
91
91
  __placeholder: 0,
92
92
  initialAccFundingFeeP: Math.round(data.initialAccFundingFeeP * converter_1.FUNDING_FEES_PRECISION.ACC_FUNDING_FEE_P),
93
93
  initialAccBorrowingFeeP: Math.round(data.initialAccBorrowingFeeP * borrowingV2_1.BORROWING_V2_PRECISION.ACC_FEE),
@@ -103,12 +103,12 @@ exports.encodeTradeFeesData = encodeTradeFeesData;
103
103
  const encodeUiRealizedPnlData = (data, collateralConfig) => {
104
104
  const decimals = collateralConfig.decimals || 18;
105
105
  return {
106
- realizedTradingFeesCollateral: Math.round(data.realizedTradingFeesCollateral * Math.pow(10, decimals)),
107
- realizedOldBorrowingFeesCollateral: Math.round(data.realizedOldBorrowingFeesCollateral * Math.pow(10, decimals)),
108
- realizedNewBorrowingFeesCollateral: Math.round(data.realizedNewBorrowingFeesCollateral * Math.pow(10, decimals)),
109
- realizedFundingFeesCollateral: Math.round(data.realizedFundingFeesCollateral * Math.pow(10, decimals)),
110
- realizedPnlPartialCloseCollateral: Math.round(data.realizedPnlPartialCloseCollateral * Math.pow(10, decimals)),
111
- pnlWithdrawnCollateral: Math.round(data.pnlWithdrawnCollateral * Math.pow(10, decimals)),
106
+ realizedTradingFeesCollateral: Math.round(data.realizedTradingFeesCollateral * 10 ** decimals),
107
+ realizedOldBorrowingFeesCollateral: Math.round(data.realizedOldBorrowingFeesCollateral * 10 ** decimals),
108
+ realizedNewBorrowingFeesCollateral: Math.round(data.realizedNewBorrowingFeesCollateral * 10 ** decimals),
109
+ realizedFundingFeesCollateral: Math.round(data.realizedFundingFeesCollateral * 10 ** decimals),
110
+ realizedPnlPartialCloseCollateral: Math.round(data.realizedPnlPartialCloseCollateral * 10 ** decimals),
111
+ pnlWithdrawnCollateral: Math.round(data.pnlWithdrawnCollateral * 10 ** decimals),
112
112
  };
113
113
  };
114
114
  exports.encodeUiRealizedPnlData = encodeUiRealizedPnlData;