@gainsnetwork/sdk 1.2.0 → 1.3.0-rc1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/lib/backend/tradingVariables/backend.types.d.ts +11 -4
  2. package/lib/backend/tradingVariables/converter.d.ts +7 -3
  3. package/lib/backend/tradingVariables/converter.js +14 -7
  4. package/lib/backend/tradingVariables/index.js +5 -2
  5. package/lib/backend/tradingVariables/types.d.ts +4 -2
  6. package/lib/contracts/addresses.d.ts +1 -1
  7. package/lib/contracts/addresses.js +5 -4
  8. package/lib/contracts/addresses.json +29 -0
  9. package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.d.ts +979 -0
  10. package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.js +2 -0
  11. package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.d.ts +1058 -0
  12. package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.js +2 -0
  13. package/lib/contracts/types/generated/GNSMultiCollatDiamond.d.ts +608 -299
  14. package/lib/contracts/types/generated/GNSPairInfosV6_1.d.ts +911 -0
  15. package/lib/contracts/types/generated/GNSPairInfosV6_1.js +2 -0
  16. package/lib/contracts/types/generated/GNSPairsStorageV6.d.ts +660 -0
  17. package/lib/contracts/types/generated/GNSPairsStorageV6.js +2 -0
  18. package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.d.ts +806 -0
  19. package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.js +2 -0
  20. package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.d.ts +821 -0
  21. package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.js +2 -0
  22. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.d.ts +88 -0
  23. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.js +1654 -0
  24. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.d.ts +113 -0
  25. package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.js +1742 -0
  26. package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.js +1933 -250
  27. package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.d.ts +98 -0
  28. package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.js +1485 -0
  29. package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.d.ts +117 -0
  30. package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.js +1265 -0
  31. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.d.ts +82 -0
  32. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.js +1273 -0
  33. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.d.ts +82 -0
  34. package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.js +1326 -0
  35. package/lib/contracts/utils/pairs.d.ts +13 -2
  36. package/lib/contracts/utils/pairs.js +70 -11
  37. package/lib/index.d.ts +1 -0
  38. package/lib/index.js +1 -0
  39. package/lib/markets/oi/fetcher.d.ts +58 -0
  40. package/lib/markets/oi/fetcher.js +181 -0
  41. package/lib/markets/oi/validation.d.ts +80 -0
  42. package/lib/markets/oi/validation.js +172 -0
  43. package/lib/markets/price/signedPrices.d.ts +36 -0
  44. package/lib/markets/price/signedPrices.js +181 -0
  45. package/lib/pricing/depthBands/converter.d.ts +65 -0
  46. package/lib/pricing/depthBands/converter.js +155 -0
  47. package/lib/pricing/depthBands/decoder.d.ts +32 -0
  48. package/lib/pricing/depthBands/decoder.js +109 -0
  49. package/lib/pricing/depthBands/encoder.d.ts +19 -0
  50. package/lib/pricing/depthBands/encoder.js +105 -0
  51. package/lib/pricing/depthBands/index.d.ts +8 -0
  52. package/lib/pricing/depthBands/index.js +26 -0
  53. package/lib/pricing/depthBands/types.d.ts +49 -0
  54. package/lib/pricing/depthBands/types.js +10 -0
  55. package/lib/pricing/depthBands/validator.d.ts +22 -0
  56. package/lib/pricing/depthBands/validator.js +113 -0
  57. package/lib/pricing/depthBands.d.ts +39 -0
  58. package/lib/pricing/depthBands.js +92 -0
  59. package/lib/pricing/index.d.ts +4 -0
  60. package/lib/pricing/index.js +20 -0
  61. package/lib/trade/effectiveLeverage/builder.d.ts +23 -0
  62. package/lib/trade/effectiveLeverage/builder.js +30 -0
  63. package/lib/trade/fees/holdingFees/index.d.ts +46 -0
  64. package/lib/trade/fees/holdingFees/index.js +105 -0
  65. package/lib/trade/fees/holdingFees/types.d.ts +23 -0
  66. package/lib/trade/fees/holdingFees/types.js +5 -0
  67. package/lib/trade/fees/trading/holdingFees.d.ts +28 -0
  68. package/lib/trade/fees/trading/holdingFees.js +66 -0
  69. package/lib/trade/fees/trading/holdingFeesStructured.d.ts +28 -0
  70. package/lib/trade/fees/trading/holdingFeesStructured.js +66 -0
  71. package/lib/trade/priceImpact/cumulVol/builder.js +8 -7
  72. package/lib/trade/priceImpact/cumulVol/converter.d.ts +63 -0
  73. package/lib/trade/priceImpact/cumulVol/converter.js +97 -1
  74. package/lib/trade/priceImpact/cumulVol/index.d.ts +3 -0
  75. package/lib/trade/priceImpact/cumulVol/index.js +107 -4
  76. package/lib/trade/priceImpact/cumulVol/types.d.ts +11 -0
  77. package/lib/trade/priceImpact/cumulVol/types.js +2 -0
  78. package/package.json +1 -1
@@ -1,7 +1,18 @@
1
- import { Pair, Fee, OpenInterest, PairDepth, PairIndex } from "../../trade/types";
1
+ import { Pair, Fee, OpenInterest, PairIndex } from "../../trade/types";
2
2
  import { Contracts } from "../../contracts/types";
3
3
  export declare const fetchPairs: (contracts: Contracts, pairIxs: PairIndex[]) => Promise<Pair[]>;
4
- export declare const fetchPairDepths: (contracts: Contracts, pairIxs: number[]) => Promise<PairDepth[]>;
4
+ export declare const fetchPairDepthBands: (contracts: Contracts, pairIxs: number[]) => Promise<any[]>;
5
+ export declare const fetchPairDepthBandsDecoded: (contracts: Contracts, pairIxs: number[]) => Promise<{
6
+ totalDepthAboveUsd: number[];
7
+ totalDepthBelowUsd: number[];
8
+ bandsAbove: number[][];
9
+ bandsBelow: number[][];
10
+ }>;
11
+ export declare const fetchDepthBandsMapping: (contracts: Contracts) => Promise<{
12
+ slot1: string;
13
+ slot2: string;
14
+ }>;
15
+ export declare const fetchDepthBandsMappingDecoded: (contracts: Contracts) => Promise<number[]>;
5
16
  export declare const fetchFees: (contracts: Contracts, feeIxs: PairIndex[]) => Promise<Fee[]>;
6
17
  export declare const fetchOpenInterest: (contracts: Contracts, collateralIndex: number, pairIxs: number[]) => Promise<OpenInterest[]>;
7
18
  export declare const getPairDescription: (pairIndex: PairIndex) => string;
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.getPairDescription = exports.fetchOpenInterest = exports.fetchFees = exports.fetchPairDepths = exports.fetchPairs = void 0;
12
+ exports.getPairDescription = exports.fetchOpenInterest = exports.fetchFees = exports.fetchDepthBandsMappingDecoded = exports.fetchDepthBandsMapping = exports.fetchPairDepthBandsDecoded = exports.fetchPairDepthBands = exports.fetchPairs = void 0;
13
13
  /* eslint-disable @typescript-eslint/no-unsafe-call */
14
14
  /* eslint-disable @typescript-eslint/no-unsafe-return */
15
15
  /* eslint-disable @typescript-eslint/no-unsafe-member-access */
@@ -40,26 +40,85 @@ const fetchPairs = (contracts, pairIxs) => __awaiter(void 0, void 0, void 0, fun
40
40
  }
41
41
  });
42
42
  exports.fetchPairs = fetchPairs;
43
- const fetchPairDepths = (contracts, pairIxs) => __awaiter(void 0, void 0, void 0, function* () {
43
+ const fetchPairDepthBands = (contracts, pairIxs) => __awaiter(void 0, void 0, void 0, function* () {
44
+ if (!contracts || pairIxs.length === 0) {
45
+ return [];
46
+ }
47
+ const { gnsMultiCollatDiamond: multiCollatContract } = contracts;
48
+ try {
49
+ // Returns array of PairDepthBands structs (encoded slots)
50
+ // Using quoted signature for overloaded function
51
+ const depthBands = yield multiCollatContract["getPairDepthBands(uint256[])"](pairIxs);
52
+ return depthBands;
53
+ }
54
+ catch (error) {
55
+ console.error(`Unexpected error while fetching pair depth bands!`);
56
+ throw error;
57
+ }
58
+ });
59
+ exports.fetchPairDepthBands = fetchPairDepthBands;
60
+ const fetchPairDepthBandsDecoded = (contracts, pairIxs) => __awaiter(void 0, void 0, void 0, function* () {
61
+ if (!contracts || pairIxs.length === 0) {
62
+ return {
63
+ totalDepthAboveUsd: [],
64
+ totalDepthBelowUsd: [],
65
+ bandsAbove: [],
66
+ bandsBelow: [],
67
+ };
68
+ }
69
+ const { gnsMultiCollatDiamond: multiCollatContract } = contracts;
70
+ try {
71
+ // Returns decoded values
72
+ // Using quoted signature for overloaded function
73
+ const [totalDepthAboveUsd, totalDepthBelowUsd, bandsAbove, bandsBelow] = yield multiCollatContract["getPairDepthBandsDecoded(uint256[])"](pairIxs);
74
+ return {
75
+ totalDepthAboveUsd: totalDepthAboveUsd.map((v) => parseFloat(v.toString())),
76
+ totalDepthBelowUsd: totalDepthBelowUsd.map((v) => parseFloat(v.toString())),
77
+ bandsAbove: bandsAbove.map((bands) => bands.map((b) => parseInt(b.toString()))),
78
+ bandsBelow: bandsBelow.map((bands) => bands.map((b) => parseInt(b.toString()))),
79
+ };
80
+ }
81
+ catch (error) {
82
+ console.error(`Unexpected error while fetching decoded pair depth bands!`);
83
+ throw error;
84
+ }
85
+ });
86
+ exports.fetchPairDepthBandsDecoded = fetchPairDepthBandsDecoded;
87
+ const fetchDepthBandsMapping = (contracts) => __awaiter(void 0, void 0, void 0, function* () {
88
+ if (!contracts) {
89
+ return { slot1: "0", slot2: "0" };
90
+ }
91
+ const { gnsMultiCollatDiamond: multiCollatContract } = contracts;
92
+ try {
93
+ // Returns two uint256 slots
94
+ const [slot1, slot2] = yield multiCollatContract.getDepthBandsMapping();
95
+ return {
96
+ slot1: slot1.toString(),
97
+ slot2: slot2.toString(),
98
+ };
99
+ }
100
+ catch (error) {
101
+ console.error(`Unexpected error while fetching depth bands mapping!`);
102
+ throw error;
103
+ }
104
+ });
105
+ exports.fetchDepthBandsMapping = fetchDepthBandsMapping;
106
+ const fetchDepthBandsMappingDecoded = (contracts) => __awaiter(void 0, void 0, void 0, function* () {
44
107
  if (!contracts) {
45
108
  return [];
46
109
  }
47
110
  const { gnsMultiCollatDiamond: multiCollatContract } = contracts;
48
111
  try {
49
- const pairParams = yield multiCollatContract.getPairDepths(pairIxs);
50
- return pairParams.map(pair => {
51
- return {
52
- onePercentDepthAboveUsd: parseFloat(pair.onePercentDepthAboveUsd.toString()),
53
- onePercentDepthBelowUsd: parseFloat(pair.onePercentDepthBelowUsd.toString()),
54
- };
55
- });
112
+ // Returns array of 30 uint16 values
113
+ const bands = yield multiCollatContract.getDepthBandsMappingDecoded();
114
+ return bands.map((b) => parseInt(b.toString()));
56
115
  }
57
116
  catch (error) {
58
- console.error(`Unexpected error while fetching pairs!`);
117
+ console.error(`Unexpected error while fetching decoded depth bands mapping!`);
59
118
  throw error;
60
119
  }
61
120
  });
62
- exports.fetchPairDepths = fetchPairDepths;
121
+ exports.fetchDepthBandsMappingDecoded = fetchDepthBandsMappingDecoded;
63
122
  const fetchFees = (contracts, feeIxs) => __awaiter(void 0, void 0, void 0, function* () {
64
123
  if (!contracts) {
65
124
  return [];
package/lib/index.d.ts CHANGED
@@ -5,5 +5,6 @@ export * from "./constants";
5
5
  export * from "./utils";
6
6
  export * from "./vault";
7
7
  export * from "./backend";
8
+ export * from "./pricing";
8
9
  export * from "./trade/fees/borrowing/index";
9
10
  export { ContractsVersion } from "./contracts/types";
package/lib/index.js CHANGED
@@ -22,6 +22,7 @@ __exportStar(require("./constants"), exports);
22
22
  __exportStar(require("./utils"), exports);
23
23
  __exportStar(require("./vault"), exports);
24
24
  __exportStar(require("./backend"), exports);
25
+ __exportStar(require("./pricing"), exports);
25
26
  // Not sure why this is needed, but it is. Barrel imports are not working.
26
27
  __exportStar(require("./trade/fees/borrowing/index"), exports);
27
28
  // Export ContractsVersion for frontend usage
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @dev Fetchers for retrieving OI data from contracts
3
+ * @dev Consolidates the three OI storage systems into unified format
4
+ */
5
+ import { ethers } from "ethers";
6
+ import { ChainId } from "../../contracts/types";
7
+ import { UnifiedPairOi } from "./types";
8
+ /**
9
+ * @dev Fetches all OI data for a single pair
10
+ * @param chainId Target chain
11
+ * @param collateralIndex Collateral type
12
+ * @param pairIndex Trading pair
13
+ * @param signer Ethers signer
14
+ * @returns Unified PairOi structure with all OI data
15
+ */
16
+ export declare function fetchPairOi(chainId: ChainId, collateralIndex: number, pairIndex: number, signer: ethers.Signer): Promise<UnifiedPairOi>;
17
+ /**
18
+ * @dev Fetches OI data for multiple pairs efficiently
19
+ * @param chainId Target chain
20
+ * @param collateralIndex Collateral type
21
+ * @param pairIndices Array of trading pairs
22
+ * @param signer Ethers signer
23
+ * @returns Array of unified PairOi structures
24
+ */
25
+ export declare function fetchMultiplePairOi(chainId: ChainId, collateralIndex: number, pairIndices: number[], signer: ethers.Signer): Promise<UnifiedPairOi[]>;
26
+ /**
27
+ * @dev Creates OI context for fee calculations
28
+ * @param chainId Target chain
29
+ * @param collateralIndex Collateral type
30
+ * @param pairIndex Trading pair
31
+ * @param signer Ethers signer
32
+ * @returns OI data formatted for SDK calculations
33
+ */
34
+ export declare function createOiContext(chainId: ChainId, collateralIndex: number, pairIndex: number, signer: ethers.Signer): Promise<{
35
+ pairOi: UnifiedPairOi;
36
+ currentPrice: number;
37
+ computed: {
38
+ totalDynamicOi: {
39
+ long: number;
40
+ short: number;
41
+ };
42
+ totalStaticOi: {
43
+ long: number;
44
+ short: number;
45
+ };
46
+ skew: number;
47
+ };
48
+ }>;
49
+ /**
50
+ * @dev Fetches only the OI data needed for specific use cases
51
+ * @param chainId Target chain
52
+ * @param collateralIndex Collateral type
53
+ * @param pairIndex Trading pair
54
+ * @param useCase Which OI systems to fetch
55
+ * @param signer Ethers signer
56
+ * @returns Partial OI data based on use case
57
+ */
58
+ export declare function fetchOiForUseCase(chainId: ChainId, collateralIndex: number, pairIndex: number, useCase: "skew" | "funding" | "borrowingV1" | "limits", signer: ethers.Signer): Promise<Partial<UnifiedPairOi>>;
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ /**
3
+ * @dev Fetchers for retrieving OI data from contracts
4
+ * @dev Consolidates the three OI storage systems into unified format
5
+ */
6
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
+ return new (P || (P = Promise))(function (resolve, reject) {
9
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ });
14
+ };
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.fetchOiForUseCase = exports.createOiContext = exports.fetchMultiplePairOi = exports.fetchPairOi = void 0;
17
+ const ethers_1 = require("ethers");
18
+ const contracts_1 = require("../../contracts");
19
+ const generated_1 = require("../../contracts/types/generated");
20
+ const converter_1 = require("./converter");
21
+ /**
22
+ * @dev Fetches all OI data for a single pair
23
+ * @param chainId Target chain
24
+ * @param collateralIndex Collateral type
25
+ * @param pairIndex Trading pair
26
+ * @param signer Ethers signer
27
+ * @returns Unified PairOi structure with all OI data
28
+ */
29
+ function fetchPairOi(chainId, collateralIndex, pairIndex, signer) {
30
+ return __awaiter(this, void 0, void 0, function* () {
31
+ const addresses = (0, contracts_1.getContractAddressesForChain)(chainId);
32
+ const diamond = generated_1.GNSMultiCollatDiamond__factory.connect(addresses.gnsMultiCollatDiamond, signer);
33
+ // Fetch all three OI types in parallel
34
+ const [beforeV10Raw, afterV10Collateral, afterV10Token, maxOi, collateral] = yield Promise.all([
35
+ diamond.getPairOisBeforeV10Collateral(collateralIndex, pairIndex),
36
+ diamond.getPairOiAfterV10Collateral(collateralIndex, pairIndex),
37
+ diamond.getPairOiAfterV10Token(collateralIndex, pairIndex),
38
+ diamond.getPairMaxOi(collateralIndex, pairIndex),
39
+ diamond.getCollateral(collateralIndex),
40
+ ]);
41
+ // Convert the beforeV10 format to match expected structure
42
+ const beforeV10 = {
43
+ long: beforeV10Raw.longOi,
44
+ short: beforeV10Raw.shortOi,
45
+ max: maxOi,
46
+ __placeholder: ethers_1.ethers.BigNumber.from(0),
47
+ };
48
+ return (0, converter_1.convertPairOi)(beforeV10, afterV10Collateral, afterV10Token, Number(collateral.precision));
49
+ });
50
+ }
51
+ exports.fetchPairOi = fetchPairOi;
52
+ /**
53
+ * @dev Fetches OI data for multiple pairs efficiently
54
+ * @param chainId Target chain
55
+ * @param collateralIndex Collateral type
56
+ * @param pairIndices Array of trading pairs
57
+ * @param signer Ethers signer
58
+ * @returns Array of unified PairOi structures
59
+ */
60
+ function fetchMultiplePairOi(chainId, collateralIndex, pairIndices, signer) {
61
+ return __awaiter(this, void 0, void 0, function* () {
62
+ const addresses = (0, contracts_1.getContractAddressesForChain)(chainId);
63
+ const diamond = generated_1.GNSMultiCollatDiamond__factory.connect(addresses.gnsMultiCollatDiamond, signer);
64
+ // Get collateral precision once
65
+ const collateral = yield diamond.getCollateral(collateralIndex);
66
+ const precision = Number(collateral.precision);
67
+ // Batch fetch all OI data
68
+ const promises = pairIndices.map((pairIndex) => __awaiter(this, void 0, void 0, function* () {
69
+ const [beforeV10Raw, afterV10Collateral, afterV10Token, maxOi] = yield Promise.all([
70
+ diamond.getPairOisBeforeV10Collateral(collateralIndex, pairIndex),
71
+ diamond.getPairOiAfterV10Collateral(collateralIndex, pairIndex),
72
+ diamond.getPairOiAfterV10Token(collateralIndex, pairIndex),
73
+ diamond.getPairMaxOi(collateralIndex, pairIndex),
74
+ ]);
75
+ // Convert the beforeV10 format to match expected structure
76
+ const beforeV10 = {
77
+ long: beforeV10Raw.longOi,
78
+ short: beforeV10Raw.shortOi,
79
+ max: maxOi,
80
+ __placeholder: ethers_1.ethers.BigNumber.from(0),
81
+ };
82
+ return {
83
+ beforeV10: beforeV10,
84
+ collateral: afterV10Collateral,
85
+ token: afterV10Token,
86
+ };
87
+ }));
88
+ const results = yield Promise.all(promises);
89
+ return (0, converter_1.convertPairOiArray)(results, precision);
90
+ });
91
+ }
92
+ exports.fetchMultiplePairOi = fetchMultiplePairOi;
93
+ /**
94
+ * @dev Creates OI context for fee calculations
95
+ * @param chainId Target chain
96
+ * @param collateralIndex Collateral type
97
+ * @param pairIndex Trading pair
98
+ * @param signer Ethers signer
99
+ * @returns OI data formatted for SDK calculations
100
+ */
101
+ function createOiContext(chainId, collateralIndex, pairIndex, signer) {
102
+ return __awaiter(this, void 0, void 0, function* () {
103
+ // Fetch OI data
104
+ const pairOi = yield fetchPairOi(chainId, collateralIndex, pairIndex, signer);
105
+ // For now, use a placeholder price - in real usage, this would come from price feeds
106
+ // The actual price should be fetched from the price aggregator or oracle
107
+ const currentPrice = 1; // Placeholder - replace with actual price fetching
108
+ // Compute derived values
109
+ const totalDynamicOi = {
110
+ long: pairOi.beforeV10Collateral.long + pairOi.token.long * currentPrice,
111
+ short: pairOi.beforeV10Collateral.short + pairOi.token.short * currentPrice,
112
+ };
113
+ const totalStaticOi = {
114
+ long: pairOi.beforeV10Collateral.long + pairOi.collateral.long,
115
+ short: pairOi.beforeV10Collateral.short + pairOi.collateral.short,
116
+ };
117
+ const skew = pairOi.token.long - pairOi.token.short;
118
+ return {
119
+ pairOi,
120
+ currentPrice,
121
+ computed: {
122
+ totalDynamicOi,
123
+ totalStaticOi,
124
+ skew,
125
+ },
126
+ };
127
+ });
128
+ }
129
+ exports.createOiContext = createOiContext;
130
+ /**
131
+ * @dev Fetches only the OI data needed for specific use cases
132
+ * @param chainId Target chain
133
+ * @param collateralIndex Collateral type
134
+ * @param pairIndex Trading pair
135
+ * @param useCase Which OI systems to fetch
136
+ * @param signer Ethers signer
137
+ * @returns Partial OI data based on use case
138
+ */
139
+ function fetchOiForUseCase(chainId, collateralIndex, pairIndex, useCase, signer) {
140
+ return __awaiter(this, void 0, void 0, function* () {
141
+ const addresses = (0, contracts_1.getContractAddressesForChain)(chainId);
142
+ const diamond = generated_1.GNSMultiCollatDiamond__factory.connect(addresses.gnsMultiCollatDiamond, signer);
143
+ switch (useCase) {
144
+ case "skew":
145
+ case "funding": {
146
+ // Only need token OI
147
+ const tokenOi = yield diamond.getPairOiAfterV10Token(collateralIndex, pairIndex);
148
+ return {
149
+ token: (0, converter_1.convertTokenOi)(tokenOi),
150
+ };
151
+ }
152
+ case "borrowingV1": {
153
+ // Need beforeV10 and token (for dynamic calculation)
154
+ const [beforeV10Raw, tokenOi, collateral, maxOi] = yield Promise.all([
155
+ diamond.getPairOisBeforeV10Collateral(collateralIndex, pairIndex),
156
+ diamond.getPairOiAfterV10Token(collateralIndex, pairIndex),
157
+ diamond.getCollateral(collateralIndex),
158
+ diamond.getPairMaxOi(collateralIndex, pairIndex),
159
+ ]);
160
+ // Convert the beforeV10 format to match expected structure
161
+ const beforeV10 = {
162
+ long: beforeV10Raw.longOi,
163
+ short: beforeV10Raw.shortOi,
164
+ max: maxOi,
165
+ __placeholder: ethers_1.ethers.BigNumber.from(0),
166
+ };
167
+ return {
168
+ beforeV10Collateral: (0, converter_1.convertBeforeV10Collateral)(beforeV10, Number(collateral.precision)),
169
+ token: (0, converter_1.convertTokenOi)(tokenOi),
170
+ };
171
+ }
172
+ case "limits": {
173
+ // Need all OI for limit checks
174
+ return fetchPairOi(chainId, collateralIndex, pairIndex, signer);
175
+ }
176
+ default:
177
+ throw new Error(`Unknown use case: ${String(useCase)}`);
178
+ }
179
+ });
180
+ }
181
+ exports.fetchOiForUseCase = fetchOiForUseCase;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * @dev OI Validation module
3
+ * @dev Provides validation functions for Open Interest limits
4
+ */
5
+ import { UnifiedPairOi } from "./types";
6
+ import * as BorrowingFee from "../../trade/fees/borrowing/types";
7
+ import { PairIndex } from "../../trade/types";
8
+ /**
9
+ * @dev Check if a position would exceed per-pair OI limits
10
+ * @param pairOi Current OI data for the pair
11
+ * @param long Whether the position is long
12
+ * @param positionSizeCollateral Position size in collateral
13
+ * @param currentPrice Current collateral price in USD (required for dynamic OI)
14
+ * @returns true if within limits, false if would exceed
15
+ */
16
+ export declare const withinMaxPairOi: (pairOi: UnifiedPairOi, long: boolean, positionSizeCollateral: number, currentPrice: number) => boolean;
17
+ /**
18
+ * @dev Calculate dynamic OI for a specific side
19
+ * @param pairOi OI data for the pair
20
+ * @param currentPrice Current collateral price in USD
21
+ * @param long Whether to calculate for long side
22
+ * @returns Dynamic OI in collateral value
23
+ */
24
+ export declare const calculateDynamicOi: (pairOi: UnifiedPairOi, currentPrice: number, long: boolean) => number;
25
+ /**
26
+ * @dev Calculate remaining OI capacity for a side
27
+ * @param pairOi OI data for the pair
28
+ * @param currentPrice Current collateral price in USD
29
+ * @param long Whether to calculate for long side
30
+ * @returns Remaining capacity in collateral (0 if unlimited)
31
+ */
32
+ export declare const getRemainingOiCapacity: (pairOi: UnifiedPairOi, currentPrice: number, long: boolean) => number;
33
+ /**
34
+ * @dev Updated group OI validation using dynamic OI
35
+ * @param pairIndex Index of the trading pair
36
+ * @param long Whether the position is long
37
+ * @param positionSizeCollateral Position size in collateral
38
+ * @param currentPrice Current collateral price in USD
39
+ * @param context Context with groups, pairs, and OI data
40
+ * @returns true if within group limits, false if would exceed
41
+ */
42
+ export declare const withinMaxGroupOiDynamic: (pairIndex: PairIndex, long: boolean, positionSizeCollateral: number, currentPrice: number, context: {
43
+ groups: BorrowingFee.Group[];
44
+ pairs: BorrowingFee.Pair[];
45
+ pairOis: UnifiedPairOi[];
46
+ }) => boolean;
47
+ /**
48
+ * @dev Calculate total dynamic OI for a group
49
+ * @param groupIndex Index of the group
50
+ * @param currentPrice Current collateral price in USD
51
+ * @param context Context with pairs and OI data
52
+ * @returns Total dynamic OI for the group
53
+ */
54
+ export declare const getGroupDynamicOi: (groupIndex: number, currentPrice: number, context: {
55
+ pairs: BorrowingFee.Pair[];
56
+ pairOis: UnifiedPairOi[];
57
+ }) => {
58
+ long: number;
59
+ short: number;
60
+ total: number;
61
+ };
62
+ /**
63
+ * @dev Check both pair and group OI limits
64
+ * @param pairIndex Index of the trading pair
65
+ * @param long Whether the position is long
66
+ * @param positionSizeCollateral Position size in collateral
67
+ * @param currentPrice Current collateral price in USD
68
+ * @param context Full context with all required data
69
+ * @returns Object with validation results
70
+ */
71
+ export declare const validateOiLimits: (pairIndex: PairIndex, long: boolean, positionSizeCollateral: number, currentPrice: number, context: {
72
+ groups: BorrowingFee.Group[];
73
+ pairs: BorrowingFee.Pair[];
74
+ pairOis: UnifiedPairOi[];
75
+ }) => {
76
+ withinPairLimit: boolean;
77
+ withinGroupLimit: boolean;
78
+ pairRemainingCapacity: number;
79
+ groupRemainingCapacity: number;
80
+ };
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ /**
3
+ * @dev OI Validation module
4
+ * @dev Provides validation functions for Open Interest limits
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.validateOiLimits = exports.getGroupDynamicOi = exports.withinMaxGroupOiDynamic = exports.getRemainingOiCapacity = exports.calculateDynamicOi = exports.withinMaxPairOi = void 0;
8
+ const converter_1 = require("./converter");
9
+ /**
10
+ * @dev Check if a position would exceed per-pair OI limits
11
+ * @param pairOi Current OI data for the pair
12
+ * @param long Whether the position is long
13
+ * @param positionSizeCollateral Position size in collateral
14
+ * @param currentPrice Current collateral price in USD (required for dynamic OI)
15
+ * @returns true if within limits, false if would exceed
16
+ */
17
+ const withinMaxPairOi = (pairOi, long, positionSizeCollateral, currentPrice) => {
18
+ // If maxCollateral is 0, unlimited OI allowed
19
+ if (pairOi.maxCollateral === 0) {
20
+ return true;
21
+ }
22
+ // Calculate current dynamic OI
23
+ const computed = (0, converter_1.computeOiValues)(pairOi, currentPrice);
24
+ const currentOi = long
25
+ ? computed.totalDynamicCollateral.long
26
+ : computed.totalDynamicCollateral.short;
27
+ // Check if adding position would exceed max
28
+ const newOi = currentOi + positionSizeCollateral;
29
+ return newOi <= pairOi.maxCollateral;
30
+ };
31
+ exports.withinMaxPairOi = withinMaxPairOi;
32
+ /**
33
+ * @dev Calculate dynamic OI for a specific side
34
+ * @param pairOi OI data for the pair
35
+ * @param currentPrice Current collateral price in USD
36
+ * @param long Whether to calculate for long side
37
+ * @returns Dynamic OI in collateral value
38
+ */
39
+ const calculateDynamicOi = (pairOi, currentPrice, long) => {
40
+ const computed = (0, converter_1.computeOiValues)(pairOi, currentPrice);
41
+ return long
42
+ ? computed.totalDynamicCollateral.long
43
+ : computed.totalDynamicCollateral.short;
44
+ };
45
+ exports.calculateDynamicOi = calculateDynamicOi;
46
+ /**
47
+ * @dev Calculate remaining OI capacity for a side
48
+ * @param pairOi OI data for the pair
49
+ * @param currentPrice Current collateral price in USD
50
+ * @param long Whether to calculate for long side
51
+ * @returns Remaining capacity in collateral (0 if unlimited)
52
+ */
53
+ const getRemainingOiCapacity = (pairOi, currentPrice, long) => {
54
+ // If maxCollateral is 0, unlimited capacity
55
+ if (pairOi.maxCollateral === 0) {
56
+ return 0; // Indicates unlimited
57
+ }
58
+ const dynamicOi = (0, exports.calculateDynamicOi)(pairOi, currentPrice, long);
59
+ const remaining = pairOi.maxCollateral - dynamicOi;
60
+ // Return 0 if already at or over capacity
61
+ return Math.max(0, remaining);
62
+ };
63
+ exports.getRemainingOiCapacity = getRemainingOiCapacity;
64
+ /**
65
+ * @dev Updated group OI validation using dynamic OI
66
+ * @param pairIndex Index of the trading pair
67
+ * @param long Whether the position is long
68
+ * @param positionSizeCollateral Position size in collateral
69
+ * @param currentPrice Current collateral price in USD
70
+ * @param context Context with groups, pairs, and OI data
71
+ * @returns true if within group limits, false if would exceed
72
+ */
73
+ const withinMaxGroupOiDynamic = (pairIndex, long, positionSizeCollateral, currentPrice, context) => {
74
+ const pair = context.pairs[pairIndex];
75
+ if (!pair)
76
+ return false;
77
+ // Get group index from first group in pair's groups array
78
+ const groupIndex = pair.groups.length > 0 ? pair.groups[0].groupIndex : 0;
79
+ const group = context.groups[groupIndex];
80
+ if (!group)
81
+ return false;
82
+ // If maxOi is 0, unlimited OI allowed
83
+ if (group.oi.max === 0) {
84
+ return true;
85
+ }
86
+ // Calculate total dynamic OI for all pairs in group
87
+ let totalGroupOi = 0;
88
+ context.pairs.forEach((p, idx) => {
89
+ const pGroupIndex = p.groups.length > 0 ? p.groups[0].groupIndex : 0;
90
+ if (pGroupIndex === groupIndex && context.pairOis[idx]) {
91
+ const pairOi = context.pairOis[idx];
92
+ const computed = (0, converter_1.computeOiValues)(pairOi, currentPrice);
93
+ // Add both long and short OI for the pair
94
+ totalGroupOi +=
95
+ computed.totalDynamicCollateral.long +
96
+ computed.totalDynamicCollateral.short;
97
+ }
98
+ });
99
+ // Check if adding position would exceed group max
100
+ const newTotalOi = totalGroupOi + positionSizeCollateral;
101
+ return newTotalOi <= group.oi.max;
102
+ };
103
+ exports.withinMaxGroupOiDynamic = withinMaxGroupOiDynamic;
104
+ /**
105
+ * @dev Calculate total dynamic OI for a group
106
+ * @param groupIndex Index of the group
107
+ * @param currentPrice Current collateral price in USD
108
+ * @param context Context with pairs and OI data
109
+ * @returns Total dynamic OI for the group
110
+ */
111
+ const getGroupDynamicOi = (groupIndex, currentPrice, context) => {
112
+ let longOi = 0;
113
+ let shortOi = 0;
114
+ context.pairs.forEach((p, idx) => {
115
+ const pGroupIndex = p.groups.length > 0 ? p.groups[0].groupIndex : 0;
116
+ if (pGroupIndex === groupIndex && context.pairOis[idx]) {
117
+ const pairOi = context.pairOis[idx];
118
+ const computed = (0, converter_1.computeOiValues)(pairOi, currentPrice);
119
+ longOi += computed.totalDynamicCollateral.long;
120
+ shortOi += computed.totalDynamicCollateral.short;
121
+ }
122
+ });
123
+ return {
124
+ long: longOi,
125
+ short: shortOi,
126
+ total: longOi + shortOi,
127
+ };
128
+ };
129
+ exports.getGroupDynamicOi = getGroupDynamicOi;
130
+ /**
131
+ * @dev Check both pair and group OI limits
132
+ * @param pairIndex Index of the trading pair
133
+ * @param long Whether the position is long
134
+ * @param positionSizeCollateral Position size in collateral
135
+ * @param currentPrice Current collateral price in USD
136
+ * @param context Full context with all required data
137
+ * @returns Object with validation results
138
+ */
139
+ const validateOiLimits = (pairIndex, long, positionSizeCollateral, currentPrice, context) => {
140
+ const pairOi = context.pairOis[pairIndex];
141
+ if (!pairOi) {
142
+ return {
143
+ withinPairLimit: false,
144
+ withinGroupLimit: false,
145
+ pairRemainingCapacity: 0,
146
+ groupRemainingCapacity: 0,
147
+ };
148
+ }
149
+ // Check pair limits
150
+ const withinPairLimit = (0, exports.withinMaxPairOi)(pairOi, long, positionSizeCollateral, currentPrice);
151
+ const pairRemainingCapacity = (0, exports.getRemainingOiCapacity)(pairOi, currentPrice, long);
152
+ // Check group limits
153
+ const withinGroupLimit = (0, exports.withinMaxGroupOiDynamic)(pairIndex, long, positionSizeCollateral, currentPrice, context);
154
+ // Calculate group remaining capacity
155
+ const pair = context.pairs[pairIndex];
156
+ let groupRemainingCapacity = 0;
157
+ if (pair) {
158
+ const groupIndex = pair.groups.length > 0 ? pair.groups[0].groupIndex : 0;
159
+ const group = context.groups[groupIndex];
160
+ if (group && group.oi.max > 0) {
161
+ const groupOi = (0, exports.getGroupDynamicOi)(groupIndex, currentPrice, context);
162
+ groupRemainingCapacity = Math.max(0, group.oi.max - groupOi.total);
163
+ }
164
+ }
165
+ return {
166
+ withinPairLimit,
167
+ withinGroupLimit,
168
+ pairRemainingCapacity,
169
+ groupRemainingCapacity,
170
+ };
171
+ };
172
+ exports.validateOiLimits = validateOiLimits;
@@ -0,0 +1,36 @@
1
+ import { Oracle, SignedPricesResponse } from "./types";
2
+ import { PendingOrderType } from "../../trade";
3
+ export interface FetchSignedPricesInput {
4
+ oracles: Oracle[];
5
+ pairs: number[];
6
+ chain: number;
7
+ minAnswer?: number;
8
+ timeoutMs?: number;
9
+ }
10
+ export declare const fetchSignedPrices: (input: FetchSignedPricesInput) => Promise<SignedPricesResponse[] | null>;
11
+ export interface FetchSignedLookbackPricesInput {
12
+ oracles: Oracle[];
13
+ trader: string;
14
+ tradeIndex: number;
15
+ pair: number;
16
+ orderType: PendingOrderType;
17
+ currentBlock: number;
18
+ fromBlock: number;
19
+ chain: number;
20
+ minAnswer?: number;
21
+ timeoutMs?: number;
22
+ }
23
+ export declare const fetchSignedLookbackPrices: (input: FetchSignedLookbackPricesInput) => Promise<SignedPricesResponse[] | null>;
24
+ export interface RetryOptions {
25
+ maxRetries?: number;
26
+ retryDelayMs?: number;
27
+ backoffMultiplier?: number;
28
+ }
29
+ export declare const fetchSignedPricesWithRetry: (input: FetchSignedPricesInput, retryOptions?: RetryOptions) => Promise<SignedPricesResponse[] | null>;
30
+ export declare const fetchSignedLookbackPricesWithRetry: (input: FetchSignedLookbackPricesInput, retryOptions?: RetryOptions) => Promise<SignedPricesResponse[] | null>;
31
+ export declare const validateSignedPricesPairs: (pairs: number[]) => {
32
+ valid: boolean;
33
+ pairs: number[];
34
+ };
35
+ export declare const isValidSignedPricesChain: (chainId: number) => boolean;
36
+ export declare const isValidSignedPricesOrderType: (orderType: PendingOrderType) => boolean;