@gainsnetwork/sdk 0.2.67-rc7 → 0.2.68

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 (39) hide show
  1. package/lib/contracts/addresses.json +20 -0
  2. package/lib/contracts/fetch/fees/borrowingFeesV2.d.ts +76 -0
  3. package/lib/contracts/fetch/fees/borrowingFeesV2.js +193 -0
  4. package/lib/contracts/fetch/fees/fundingFees.d.ts +66 -0
  5. package/lib/contracts/fetch/fees/fundingFees.js +150 -0
  6. package/lib/contracts/fetch/priceImpact/skew.d.ts +63 -0
  7. package/lib/contracts/fetch/priceImpact/skew.js +168 -0
  8. package/lib/contracts/index.js +3 -1
  9. package/lib/contracts/types/index.d.ts +2 -1
  10. package/lib/contracts/types/index.js +1 -0
  11. package/lib/trade/fees/borrowingV2/converter.d.ts +66 -0
  12. package/lib/trade/fees/borrowingV2/converter.js +121 -0
  13. package/lib/trade/fees/borrowingV2/index.d.ts +59 -0
  14. package/lib/trade/fees/borrowingV2/index.js +139 -0
  15. package/lib/trade/fees/borrowingV2/types.d.ts +79 -0
  16. package/lib/trade/fees/borrowingV2/types.js +5 -0
  17. package/lib/trade/fees/fundingFees/converter.d.ts +102 -0
  18. package/lib/trade/fees/fundingFees/converter.js +196 -0
  19. package/lib/trade/fees/fundingFees/index.d.ts +135 -0
  20. package/lib/trade/fees/fundingFees/index.js +322 -0
  21. package/lib/trade/fees/fundingFees/types.d.ts +77 -0
  22. package/lib/trade/fees/fundingFees/types.js +5 -0
  23. package/lib/trade/fees/trading/converter.d.ts +30 -0
  24. package/lib/trade/fees/trading/converter.js +43 -0
  25. package/lib/trade/fees/trading/index.d.ts +34 -0
  26. package/lib/trade/fees/trading/index.js +104 -0
  27. package/lib/trade/fees/trading/types.d.ts +39 -0
  28. package/lib/trade/fees/trading/types.js +5 -0
  29. package/lib/trade/priceImpact/index.d.ts +8 -0
  30. package/lib/trade/priceImpact/index.js +32 -0
  31. package/lib/trade/priceImpact/skew/converter.d.ts +77 -0
  32. package/lib/trade/priceImpact/skew/converter.js +171 -0
  33. package/lib/trade/priceImpact/skew/index.d.ts +57 -0
  34. package/lib/trade/priceImpact/skew/index.js +175 -0
  35. package/lib/trade/priceImpact/skew/types.d.ts +55 -0
  36. package/lib/trade/priceImpact/skew/types.js +5 -0
  37. package/lib/trade/utils.d.ts +18 -0
  38. package/lib/trade/utils.js +30 -0
  39. package/package.json +1 -1
@@ -0,0 +1,168 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.calculateTradeSkewPriceImpact = exports.fetchCollateralDecimals = exports.fetchSkewPriceImpactContext = exports.fetchPairSkewDepths = exports.fetchPairSkewDepth = exports.fetchPairOisAfterV10Token = exports.fetchPairOiAfterV10Token = void 0;
13
+ const priceImpact_1 = require("../../../trade/priceImpact");
14
+ /**
15
+ * @dev Fetches pair open interest in tokens for a specific pair
16
+ * @param contract GNSMultiCollatDiamond contract instance
17
+ * @param collateralIndex Collateral index
18
+ * @param pairIndex Pair index
19
+ * @returns Promise resolving to pair OI in tokens
20
+ */
21
+ const fetchPairOiAfterV10Token = (contract, collateralIndex, pairIndex) => __awaiter(void 0, void 0, void 0, function* () {
22
+ try {
23
+ const contractData = yield contract.getPairOiAfterV10Token(collateralIndex, pairIndex);
24
+ return (0, priceImpact_1.convertPairOiToken)(contractData);
25
+ }
26
+ catch (error) {
27
+ console.error("Error fetching pair OI token:", error);
28
+ throw error;
29
+ }
30
+ });
31
+ exports.fetchPairOiAfterV10Token = fetchPairOiAfterV10Token;
32
+ /**
33
+ * @dev Fetches pair open interest in tokens for multiple pairs
34
+ * @param contract GNSMultiCollatDiamond contract instance
35
+ * @param collateralIndices Array of collateral indices
36
+ * @param pairIndices Array of pair indices
37
+ * @returns Promise resolving to array of pair OI in tokens
38
+ */
39
+ const fetchPairOisAfterV10Token = (contract, collateralIndices, pairIndices) => __awaiter(void 0, void 0, void 0, function* () {
40
+ if (collateralIndices.length !== pairIndices.length) {
41
+ throw new Error("Collateral indices and pair indices arrays must have the same length");
42
+ }
43
+ try {
44
+ const contractDataArray = yield contract.getPairOisAfterV10Token(collateralIndices, pairIndices);
45
+ return contractDataArray.map(priceImpact_1.convertPairOiToken);
46
+ }
47
+ catch (error) {
48
+ console.error("Error fetching pair OIs token:", error);
49
+ throw error;
50
+ }
51
+ });
52
+ exports.fetchPairOisAfterV10Token = fetchPairOisAfterV10Token;
53
+ /**
54
+ * @dev Fetches skew depth for a specific pair
55
+ * @param contract GNSMultiCollatDiamond contract instance
56
+ * @param collateralIndex Collateral index
57
+ * @param pairIndex Pair index
58
+ * @param collateralDecimals Number of decimals for the collateral
59
+ * @returns Promise resolving to normalized skew depth
60
+ */
61
+ const fetchPairSkewDepth = (contract, collateralIndex, pairIndex, collateralDecimals) => __awaiter(void 0, void 0, void 0, function* () {
62
+ try {
63
+ const contractDepth = yield contract.getPairSkewDepth(collateralIndex, pairIndex);
64
+ return (0, priceImpact_1.normalizeSkewDepth)(contractDepth.toBigInt(), collateralDecimals);
65
+ }
66
+ catch (error) {
67
+ console.error("Error fetching skew depth:", error);
68
+ throw error;
69
+ }
70
+ });
71
+ exports.fetchPairSkewDepth = fetchPairSkewDepth;
72
+ /**
73
+ * @dev Fetches skew depths for multiple pairs
74
+ * @param contract GNSMultiCollatDiamond contract instance
75
+ * @param collateralIndices Array of collateral indices
76
+ * @param pairIndices Array of pair indices
77
+ * @param collateralDecimals Array of collateral decimals for each pair
78
+ * @returns Promise resolving to array of normalized skew depths
79
+ */
80
+ const fetchPairSkewDepths = (contract, collateralIndices, pairIndices, collateralDecimals) => __awaiter(void 0, void 0, void 0, function* () {
81
+ if (collateralIndices.length !== pairIndices.length ||
82
+ pairIndices.length !== collateralDecimals.length) {
83
+ throw new Error("All input arrays must have the same length");
84
+ }
85
+ try {
86
+ const contractDepths = yield contract.getPairSkewDepths(collateralIndices, pairIndices);
87
+ return contractDepths.map((depth, i) => (0, priceImpact_1.normalizeSkewDepth)(depth.toBigInt(), collateralDecimals[i]));
88
+ }
89
+ catch (error) {
90
+ console.error("Error fetching skew depths:", error);
91
+ throw error;
92
+ }
93
+ });
94
+ exports.fetchPairSkewDepths = fetchPairSkewDepths;
95
+ /**
96
+ * @dev Fetches complete skew price impact context for multiple pairs
97
+ * @param contract GNSMultiCollatDiamond contract instance
98
+ * @param collateralIndices Array of collateral indices
99
+ * @param pairIndices Array of pair indices
100
+ * @param collateralDecimals Array of collateral decimals for each pair
101
+ * @returns Promise resolving to complete skew price impact context
102
+ */
103
+ const fetchSkewPriceImpactContext = (contract, collateralIndices, pairIndices, collateralDecimals) => __awaiter(void 0, void 0, void 0, function* () {
104
+ try {
105
+ // Fetch OI data and skew depths in parallel
106
+ const [pairOiTokens, skewDepths] = yield Promise.all([
107
+ (0, exports.fetchPairOisAfterV10Token)(contract, collateralIndices, pairIndices),
108
+ (0, exports.fetchPairSkewDepths)(contract, collateralIndices, pairIndices, collateralDecimals),
109
+ ]);
110
+ return (0, priceImpact_1.createSkewPriceImpactContext)(collateralIndices, pairIndices, skewDepths, pairOiTokens);
111
+ }
112
+ catch (error) {
113
+ console.error("Error fetching skew price impact context:", error);
114
+ throw error;
115
+ }
116
+ });
117
+ exports.fetchSkewPriceImpactContext = fetchSkewPriceImpactContext;
118
+ /**
119
+ * @dev Fetches collateral decimals for given collateral indices
120
+ * @param contract GNSMultiCollatDiamond contract instance
121
+ * @param collateralIndices Array of collateral indices
122
+ * @returns Promise resolving to array of decimals
123
+ */
124
+ const fetchCollateralDecimals = (contract, collateralIndices) => __awaiter(void 0, void 0, void 0, function* () {
125
+ try {
126
+ // Get unique collateral indices to minimize calls
127
+ const uniqueIndices = [...new Set(collateralIndices)];
128
+ // Fetch collateral info for unique indices
129
+ const promises = uniqueIndices.map((index) => __awaiter(void 0, void 0, void 0, function* () {
130
+ const collateral = yield contract.getCollateral(index);
131
+ return { index, decimals: Number(collateral.precision) };
132
+ }));
133
+ const collateralData = yield Promise.all(promises);
134
+ // Create a map for quick lookup
135
+ const decimalsMap = new Map(collateralData.map(data => [data.index, data.decimals]));
136
+ // Return decimals in the same order as input
137
+ return collateralIndices.map(index => decimalsMap.get(index) || 18 // Default to 18 if not found
138
+ );
139
+ }
140
+ catch (error) {
141
+ console.error("Error fetching collateral decimals:", error);
142
+ throw error;
143
+ }
144
+ });
145
+ exports.fetchCollateralDecimals = fetchCollateralDecimals;
146
+ /**
147
+ * @dev Calculates skew price impact for a trade using contract call
148
+ * @param contract GNSMultiCollatDiamond contract instance
149
+ * @param collateralIndex Collateral index
150
+ * @param pairIndex Pair index
151
+ * @param long Whether trade is long
152
+ * @param positionSizeToken Position size in tokens
153
+ * @param open Whether trade is opening
154
+ * @returns Promise resolving to price impact percentage (1e10)
155
+ */
156
+ const calculateTradeSkewPriceImpact = (contract, collateralIndex, pairIndex, long, positionSizeToken, open) => __awaiter(void 0, void 0, void 0, function* () {
157
+ try {
158
+ const priceImpactP = yield contract.getTradeSkewPriceImpactP(collateralIndex, pairIndex, long, BigInt(Math.round(positionSizeToken * 1e18)), // Convert to 1e18 precision
159
+ open);
160
+ // Convert from int256 1e10 to percentage
161
+ return Number(priceImpactP) / 1e10;
162
+ }
163
+ catch (error) {
164
+ console.error("Error calculating trade skew price impact:", error);
165
+ throw error;
166
+ }
167
+ });
168
+ exports.calculateTradeSkewPriceImpact = calculateTradeSkewPriceImpact;
@@ -63,6 +63,7 @@ exports.COLLATERAL_TO_CHAIN_COLLATERAL_INDEX = {
63
63
  },
64
64
  [types_1.ChainId.BASE]: {
65
65
  [types_1.CollateralTypes.USDC]: 1,
66
+ [types_1.CollateralTypes.BTCUSD]: 2,
66
67
  },
67
68
  [types_1.ChainId.APECHAIN]: {
68
69
  [types_1.CollateralTypes.APE]: 1,
@@ -75,7 +76,8 @@ exports.COLLATERAL_TO_COLLATERAL_INDEX = {
75
76
  [types_1.CollateralTypes.USDC]: 3,
76
77
  [types_1.CollateralTypes.ARB]: 0,
77
78
  [types_1.CollateralTypes.APE]: 0,
78
- [types_1.CollateralTypes.GNS]: 0, // not in use
79
+ [types_1.CollateralTypes.GNS]: 0,
80
+ [types_1.CollateralTypes.BTCUSD]: 0,
79
81
  };
80
82
  __exportStar(require("./utils"), exports);
81
83
  __exportStar(require("./addresses"), exports);
@@ -16,7 +16,8 @@ export declare enum CollateralTypes {
16
16
  ARB = "ARB",
17
17
  USDC = "USDC",
18
18
  APE = "APE",
19
- GNS = "GNS"
19
+ GNS = "GNS",
20
+ BTCUSD = "BTCUSD"
20
21
  }
21
22
  export declare enum ContractsVersion {
22
23
  BEFORE_V9_2 = 0,
@@ -9,6 +9,7 @@ var CollateralTypes;
9
9
  CollateralTypes["USDC"] = "USDC";
10
10
  CollateralTypes["APE"] = "APE";
11
11
  CollateralTypes["GNS"] = "GNS";
12
+ CollateralTypes["BTCUSD"] = "BTCUSD";
12
13
  })(CollateralTypes = exports.CollateralTypes || (exports.CollateralTypes = {}));
13
14
  var ContractsVersion;
14
15
  (function (ContractsVersion) {
@@ -0,0 +1,66 @@
1
+ import type { IFundingFees } from "../../../contracts/types/generated/GNSMultiCollatDiamond";
2
+ import { BorrowingFeeV2 } from ".";
3
+ /**
4
+ * @dev Converts contract BorrowingFeeParams to SDK type
5
+ * @param contractParams Contract borrowing fee params from IFundingFees.BorrowingFeeParams
6
+ * @returns SDK BorrowingFeeParams
7
+ */
8
+ export declare const convertBorrowingFeeParams: (contractParams: IFundingFees.BorrowingFeeParamsStructOutput) => BorrowingFeeV2.BorrowingFeeParams;
9
+ /**
10
+ * @dev Converts array of contract BorrowingFeeParams to SDK types
11
+ * @param contractParamsArray Array of contract borrowing fee params
12
+ * @returns Array of SDK BorrowingFeeParams
13
+ */
14
+ export declare const convertBorrowingFeeParamsArray: (contractParamsArray: IFundingFees.BorrowingFeeParamsStructOutput[]) => BorrowingFeeV2.BorrowingFeeParams[];
15
+ /**
16
+ * @dev Converts contract PairBorrowingFeeData to SDK type
17
+ * @param contractData Contract pair borrowing fee data from IFundingFees.PairBorrowingFeeData
18
+ * @returns SDK PairBorrowingFeeData
19
+ */
20
+ export declare const convertPairBorrowingFeeData: (contractData: IFundingFees.PairBorrowingFeeDataStructOutput) => BorrowingFeeV2.PairBorrowingFeeData;
21
+ /**
22
+ * @dev Converts array of contract PairBorrowingFeeData to SDK types
23
+ * @param contractDataArray Array of contract pair borrowing fee data
24
+ * @returns Array of SDK PairBorrowingFeeData
25
+ */
26
+ export declare const convertPairBorrowingFeeDataArray: (contractDataArray: IFundingFees.PairBorrowingFeeDataStructOutput[]) => BorrowingFeeV2.PairBorrowingFeeData[];
27
+ /**
28
+ * @dev Converts contract TradeFeesData to SDK TradeInitialAccFees
29
+ * @param contractTradeData Contract trade fees data from IFundingFees.TradeFeesData
30
+ * @returns SDK TradeInitialAccFees
31
+ */
32
+ export declare const convertTradeInitialAccFees: (contractTradeData: IFundingFees.TradeFeesDataStructOutput) => BorrowingFeeV2.TradeInitialAccFees;
33
+ /**
34
+ * @dev Converts array of contract TradeFeesData to SDK TradeInitialAccFees
35
+ * @param contractTradeDataArray Array of contract trade fees data
36
+ * @returns Array of SDK TradeInitialAccFees
37
+ */
38
+ export declare const convertTradeInitialAccFeesArray: (contractTradeDataArray: IFundingFees.TradeFeesDataStructOutput[]) => BorrowingFeeV2.TradeInitialAccFees[];
39
+ /**
40
+ * @dev Creates a context object from contract data arrays
41
+ * @param collateralIndices Array of collateral indices
42
+ * @param pairIndices Array of pair indices
43
+ * @param borrowingParams Array of borrowing fee params from contract
44
+ * @param borrowingData Array of pair borrowing fee data from contract
45
+ * @param currentTimestamp Optional current timestamp
46
+ * @returns Complete SDK context for borrowing v2 calculations
47
+ */
48
+ export declare const createBorrowingV2Context: (collateralIndices: number[], pairIndices: number[], borrowingParams: IFundingFees.BorrowingFeeParamsStructOutput[], borrowingData: IFundingFees.PairBorrowingFeeDataStructOutput[], currentTimestamp?: number) => BorrowingFeeV2.GetBorrowingFeeV2Context;
49
+ /**
50
+ * @dev Helper function to validate borrowing rate per second
51
+ * @param borrowingRatePerSecondP Borrowing rate per second (normalized float)
52
+ * @returns True if rate is within valid bounds
53
+ */
54
+ export declare const isValidBorrowingRate: (borrowingRatePerSecondP: number) => boolean;
55
+ /**
56
+ * @dev Helper function to convert borrowing rate to APR percentage
57
+ * @param borrowingRatePerSecondP Borrowing rate per second (normalized float)
58
+ * @returns APR as percentage (e.g., 10.5 for 10.5% APR)
59
+ */
60
+ export declare const borrowingRateToAPR: (borrowingRatePerSecondP: number) => number;
61
+ /**
62
+ * @dev Helper function to convert APR percentage to borrowing rate per second
63
+ * @param aprPercentage APR as percentage (e.g., 10.5 for 10.5% APR)
64
+ * @returns Borrowing rate per second (normalized float)
65
+ */
66
+ export declare const aprToBorrowingRate: (aprPercentage: number) => number;
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.aprToBorrowingRate = exports.borrowingRateToAPR = exports.isValidBorrowingRate = exports.createBorrowingV2Context = exports.convertTradeInitialAccFeesArray = exports.convertTradeInitialAccFees = exports.convertPairBorrowingFeeDataArray = exports.convertPairBorrowingFeeData = exports.convertBorrowingFeeParamsArray = exports.convertBorrowingFeeParams = void 0;
4
+ const index_1 = require("./index");
5
+ /**
6
+ * @dev Converts contract BorrowingFeeParams to SDK type
7
+ * @param contractParams Contract borrowing fee params from IFundingFees.BorrowingFeeParams
8
+ * @returns SDK BorrowingFeeParams
9
+ */
10
+ const convertBorrowingFeeParams = (contractParams) => ({
11
+ borrowingRatePerSecondP: contractParams.borrowingRatePerSecondP /
12
+ index_1.BORROWING_V2_PRECISION.RATE_PER_SECOND,
13
+ });
14
+ exports.convertBorrowingFeeParams = convertBorrowingFeeParams;
15
+ /**
16
+ * @dev Converts array of contract BorrowingFeeParams to SDK types
17
+ * @param contractParamsArray Array of contract borrowing fee params
18
+ * @returns Array of SDK BorrowingFeeParams
19
+ */
20
+ const convertBorrowingFeeParamsArray = (contractParamsArray) => contractParamsArray.map(params => (0, exports.convertBorrowingFeeParams)(params));
21
+ exports.convertBorrowingFeeParamsArray = convertBorrowingFeeParamsArray;
22
+ /**
23
+ * @dev Converts contract PairBorrowingFeeData to SDK type
24
+ * @param contractData Contract pair borrowing fee data from IFundingFees.PairBorrowingFeeData
25
+ * @returns SDK PairBorrowingFeeData
26
+ */
27
+ const convertPairBorrowingFeeData = (contractData) => ({
28
+ accBorrowingFeeP: parseFloat(contractData.accBorrowingFeeP.toString()) /
29
+ index_1.BORROWING_V2_PRECISION.ACC_FEE,
30
+ lastBorrowingUpdateTs: contractData.lastBorrowingUpdateTs,
31
+ });
32
+ exports.convertPairBorrowingFeeData = convertPairBorrowingFeeData;
33
+ /**
34
+ * @dev Converts array of contract PairBorrowingFeeData to SDK types
35
+ * @param contractDataArray Array of contract pair borrowing fee data
36
+ * @returns Array of SDK PairBorrowingFeeData
37
+ */
38
+ const convertPairBorrowingFeeDataArray = (contractDataArray) => contractDataArray.map(data => (0, exports.convertPairBorrowingFeeData)(data));
39
+ exports.convertPairBorrowingFeeDataArray = convertPairBorrowingFeeDataArray;
40
+ /**
41
+ * @dev Converts contract TradeFeesData to SDK TradeInitialAccFees
42
+ * @param contractTradeData Contract trade fees data from IFundingFees.TradeFeesData
43
+ * @returns SDK TradeInitialAccFees
44
+ */
45
+ const convertTradeInitialAccFees = (contractTradeData) => ({
46
+ initialAccBorrowingFeeP: parseFloat(contractTradeData.initialAccBorrowingFeeP.toString()) /
47
+ index_1.BORROWING_V2_PRECISION.ACC_FEE,
48
+ });
49
+ exports.convertTradeInitialAccFees = convertTradeInitialAccFees;
50
+ /**
51
+ * @dev Converts array of contract TradeFeesData to SDK TradeInitialAccFees
52
+ * @param contractTradeDataArray Array of contract trade fees data
53
+ * @returns Array of SDK TradeInitialAccFees
54
+ */
55
+ const convertTradeInitialAccFeesArray = (contractTradeDataArray) => contractTradeDataArray.map(data => (0, exports.convertTradeInitialAccFees)(data));
56
+ exports.convertTradeInitialAccFeesArray = convertTradeInitialAccFeesArray;
57
+ /**
58
+ * @dev Creates a context object from contract data arrays
59
+ * @param collateralIndices Array of collateral indices
60
+ * @param pairIndices Array of pair indices
61
+ * @param borrowingParams Array of borrowing fee params from contract
62
+ * @param borrowingData Array of pair borrowing fee data from contract
63
+ * @param currentTimestamp Optional current timestamp
64
+ * @returns Complete SDK context for borrowing v2 calculations
65
+ */
66
+ const createBorrowingV2Context = (collateralIndices, pairIndices, borrowingParams, borrowingData, currentTimestamp) => {
67
+ const context = {
68
+ currentTimestamp,
69
+ borrowingParams: {},
70
+ borrowingData: {},
71
+ };
72
+ // Build nested objects indexed by collateralIndex and pairIndex
73
+ for (let i = 0; i < collateralIndices.length; i++) {
74
+ const collateralIndex = collateralIndices[i];
75
+ const pairIndex = pairIndices[i];
76
+ // Initialize collateral index objects if they don't exist
77
+ if (!context.borrowingParams[collateralIndex]) {
78
+ context.borrowingParams[collateralIndex] = {};
79
+ }
80
+ if (!context.borrowingData[collateralIndex]) {
81
+ context.borrowingData[collateralIndex] = {};
82
+ }
83
+ // Store converted data
84
+ context.borrowingParams[collateralIndex][pairIndex] =
85
+ (0, exports.convertBorrowingFeeParams)(borrowingParams[i]);
86
+ context.borrowingData[collateralIndex][pairIndex] =
87
+ (0, exports.convertPairBorrowingFeeData)(borrowingData[i]);
88
+ }
89
+ return context;
90
+ };
91
+ exports.createBorrowingV2Context = createBorrowingV2Context;
92
+ /**
93
+ * @dev Helper function to validate borrowing rate per second
94
+ * @param borrowingRatePerSecondP Borrowing rate per second (normalized float)
95
+ * @returns True if rate is within valid bounds
96
+ */
97
+ const isValidBorrowingRate = (borrowingRatePerSecondP) => {
98
+ return (borrowingRatePerSecondP >= 0 &&
99
+ borrowingRatePerSecondP <= 317097 / index_1.BORROWING_V2_PRECISION.RATE_PER_SECOND); // Max 1,000% APR
100
+ };
101
+ exports.isValidBorrowingRate = isValidBorrowingRate;
102
+ /**
103
+ * @dev Helper function to convert borrowing rate to APR percentage
104
+ * @param borrowingRatePerSecondP Borrowing rate per second (normalized float)
105
+ * @returns APR as percentage (e.g., 10.5 for 10.5% APR)
106
+ */
107
+ const borrowingRateToAPR = (borrowingRatePerSecondP) => {
108
+ const SECONDS_PER_YEAR = 365 * 24 * 60 * 60; // 31,536,000
109
+ return borrowingRatePerSecondP * SECONDS_PER_YEAR;
110
+ };
111
+ exports.borrowingRateToAPR = borrowingRateToAPR;
112
+ /**
113
+ * @dev Helper function to convert APR percentage to borrowing rate per second
114
+ * @param aprPercentage APR as percentage (e.g., 10.5 for 10.5% APR)
115
+ * @returns Borrowing rate per second (normalized float)
116
+ */
117
+ const aprToBorrowingRate = (aprPercentage) => {
118
+ const SECONDS_PER_YEAR = 365 * 24 * 60 * 60; // 31,536,000
119
+ return aprPercentage / SECONDS_PER_YEAR;
120
+ };
121
+ exports.aprToBorrowingRate = aprToBorrowingRate;
@@ -0,0 +1,59 @@
1
+ import * as BorrowingFeeV2 from "./types";
2
+ /**
3
+ * @dev Maximum borrowing rate per second (1,000% APR)
4
+ */
5
+ export declare const MAX_BORROWING_RATE_PER_SECOND = 0.0317097;
6
+ /**
7
+ * @dev Precision constants for borrowing v2 calculations
8
+ */
9
+ export declare const BORROWING_V2_PRECISION: {
10
+ readonly RATE_PER_SECOND: 10000000000;
11
+ readonly ACC_FEE: 100000000000000000000;
12
+ readonly PERCENTAGE: 100;
13
+ };
14
+ /**
15
+ * @dev Calculates pending accumulated borrowing fees for a pair
16
+ * @param params Borrowing fee parameters for the pair
17
+ * @param data Current borrowing fee data for the pair
18
+ * @param currentPairPrice Current price of the trading pair
19
+ * @param currentTimestamp Current timestamp (defaults to now)
20
+ * @returns Updated accumulated borrowing fee (1e20 precision)
21
+ */
22
+ export declare const getPairPendingAccBorrowingFees: (params: BorrowingFeeV2.BorrowingFeeParams, data: BorrowingFeeV2.PairBorrowingFeeData, currentPairPrice: number, currentTimestamp?: number) => number;
23
+ /**
24
+ * @dev Calculates borrowing fees owed by a specific trade
25
+ * @param input Trade borrowing fee calculation input
26
+ * @param context Context containing borrowing parameters and data
27
+ * @returns Borrowing fees in collateral tokens
28
+ */
29
+ export declare const getTradeBorrowingFeesCollateral: (input: BorrowingFeeV2.TradeBorrowingFeeInput, context: BorrowingFeeV2.GetBorrowingFeeV2Context) => number;
30
+ /**
31
+ * @dev Convenience function to calculate borrowing fees for a trade using individual parameters
32
+ * @param positionSizeCollateral Position size in collateral tokens
33
+ * @param pairIndex Index of the trading pair
34
+ * @param collateralIndex Index of the collateral
35
+ * @param openPrice Price at which the trade was opened
36
+ * @param currentPairPrice Current price of the trading pair
37
+ * @param initialAccBorrowingFeeP Initial accumulated borrowing fee when trade was opened
38
+ * @param context Context containing borrowing parameters and data
39
+ * @returns Borrowing fees in collateral tokens
40
+ */
41
+ export declare const getBorrowingFee: (positionSizeCollateral: number, pairIndex: number, collateralIndex: number, openPrice: number, currentPairPrice: number, initialAccBorrowingFeeP: number, context: BorrowingFeeV2.GetBorrowingFeeV2Context) => number;
42
+ /**
43
+ * @dev Utility function to get pending accumulated borrowing fees for a pair using context
44
+ * @param input Pair borrowing fee calculation input
45
+ * @param context Context containing borrowing parameters and data
46
+ * @returns Updated accumulated borrowing fee (1e20 precision)
47
+ */
48
+ export declare const getPairBorrowingFees: (input: BorrowingFeeV2.PairBorrowingFeeInput, context: BorrowingFeeV2.GetBorrowingFeeV2Context) => number;
49
+ /**
50
+ * @dev Utility functions for working with borrowing v2 fees
51
+ */
52
+ export declare const borrowingFeeV2Utils: {
53
+ getPairPendingAccBorrowingFees: (params: BorrowingFeeV2.BorrowingFeeParams, data: BorrowingFeeV2.PairBorrowingFeeData, currentPairPrice: number, currentTimestamp?: number) => number;
54
+ getTradeBorrowingFeesCollateral: (input: BorrowingFeeV2.TradeBorrowingFeeInput, context: BorrowingFeeV2.GetBorrowingFeeV2Context) => number;
55
+ getPairBorrowingFees: (input: BorrowingFeeV2.PairBorrowingFeeInput, context: BorrowingFeeV2.GetBorrowingFeeV2Context) => number;
56
+ getBorrowingFee: (positionSizeCollateral: number, pairIndex: number, collateralIndex: number, openPrice: number, currentPairPrice: number, initialAccBorrowingFeeP: number, context: BorrowingFeeV2.GetBorrowingFeeV2Context) => number;
57
+ };
58
+ export * as BorrowingFeeV2 from "./types";
59
+ export * from "./converter";
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
26
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.BorrowingFeeV2 = exports.borrowingFeeV2Utils = exports.getPairBorrowingFees = exports.getBorrowingFee = exports.getTradeBorrowingFeesCollateral = exports.getPairPendingAccBorrowingFees = exports.BORROWING_V2_PRECISION = exports.MAX_BORROWING_RATE_PER_SECOND = void 0;
30
+ /**
31
+ * @dev Maximum borrowing rate per second (1,000% APR)
32
+ */
33
+ exports.MAX_BORROWING_RATE_PER_SECOND = 0.0317097; // 317097 / 1e10
34
+ /**
35
+ * @dev Precision constants for borrowing v2 calculations
36
+ */
37
+ exports.BORROWING_V2_PRECISION = {
38
+ RATE_PER_SECOND: 1e10,
39
+ ACC_FEE: 1e20,
40
+ PERCENTAGE: 100,
41
+ };
42
+ /**
43
+ * @dev Calculates pending accumulated borrowing fees for a pair
44
+ * @param params Borrowing fee parameters for the pair
45
+ * @param data Current borrowing fee data for the pair
46
+ * @param currentPairPrice Current price of the trading pair
47
+ * @param currentTimestamp Current timestamp (defaults to now)
48
+ * @returns Updated accumulated borrowing fee (1e20 precision)
49
+ */
50
+ const getPairPendingAccBorrowingFees = (params, data, currentPairPrice, currentTimestamp) => {
51
+ const timestamp = currentTimestamp !== null && currentTimestamp !== void 0 ? currentTimestamp : Math.floor(Date.now() / 1000);
52
+ // Calculate time elapsed since last update
53
+ const timeElapsed = Math.max(0, timestamp - data.lastBorrowingUpdateTs);
54
+ // If no time elapsed, return current accumulated fee
55
+ if (timeElapsed === 0) {
56
+ return data.accBorrowingFeeP;
57
+ }
58
+ // Calculate accumulated borrowing fee delta
59
+ // Formula: borrowingRatePerSecondP * timeElapsed * currentPairPrice
60
+ const accBorrowingFeeDeltaP = params.borrowingRatePerSecondP * timeElapsed * currentPairPrice;
61
+ return data.accBorrowingFeeP + accBorrowingFeeDeltaP;
62
+ };
63
+ exports.getPairPendingAccBorrowingFees = getPairPendingAccBorrowingFees;
64
+ /**
65
+ * @dev Calculates borrowing fees owed by a specific trade
66
+ * @param input Trade borrowing fee calculation input
67
+ * @param context Context containing borrowing parameters and data
68
+ * @returns Borrowing fees in collateral tokens
69
+ */
70
+ const getTradeBorrowingFeesCollateral = (input, context) => {
71
+ var _a, _b;
72
+ const { positionSizeCollateral, openPrice, collateralIndex, pairIndex, currentPairPrice, initialAccBorrowingFeeP, currentTimestamp, } = input;
73
+ // Get borrowing parameters and data for the pair
74
+ const params = (_a = context.borrowingParams[collateralIndex]) === null || _a === void 0 ? void 0 : _a[pairIndex];
75
+ const data = (_b = context.borrowingData[collateralIndex]) === null || _b === void 0 ? void 0 : _b[pairIndex];
76
+ if (!params || !data) {
77
+ return 0;
78
+ }
79
+ // Calculate current accumulated borrowing fees
80
+ const currentAccBorrowingFeeP = (0, exports.getPairPendingAccBorrowingFees)(params, data, currentPairPrice, currentTimestamp);
81
+ // Calculate borrowing fees for this trade
82
+ // Formula: (positionSizeCollateral * (currentAccFee - initialAccFee)) / openPrice / 100
83
+ const feeDeltaP = currentAccBorrowingFeeP - initialAccBorrowingFeeP;
84
+ return ((positionSizeCollateral * feeDeltaP) /
85
+ openPrice /
86
+ exports.BORROWING_V2_PRECISION.PERCENTAGE);
87
+ };
88
+ exports.getTradeBorrowingFeesCollateral = getTradeBorrowingFeesCollateral;
89
+ /**
90
+ * @dev Convenience function to calculate borrowing fees for a trade using individual parameters
91
+ * @param positionSizeCollateral Position size in collateral tokens
92
+ * @param pairIndex Index of the trading pair
93
+ * @param collateralIndex Index of the collateral
94
+ * @param openPrice Price at which the trade was opened
95
+ * @param currentPairPrice Current price of the trading pair
96
+ * @param initialAccBorrowingFeeP Initial accumulated borrowing fee when trade was opened
97
+ * @param context Context containing borrowing parameters and data
98
+ * @returns Borrowing fees in collateral tokens
99
+ */
100
+ const getBorrowingFee = (positionSizeCollateral, pairIndex, collateralIndex, openPrice, currentPairPrice, initialAccBorrowingFeeP, context) => {
101
+ return (0, exports.getTradeBorrowingFeesCollateral)({
102
+ positionSizeCollateral,
103
+ openPrice,
104
+ collateralIndex,
105
+ pairIndex,
106
+ currentPairPrice,
107
+ initialAccBorrowingFeeP,
108
+ currentTimestamp: context.currentTimestamp,
109
+ }, context);
110
+ };
111
+ exports.getBorrowingFee = getBorrowingFee;
112
+ /**
113
+ * @dev Utility function to get pending accumulated borrowing fees for a pair using context
114
+ * @param input Pair borrowing fee calculation input
115
+ * @param context Context containing borrowing parameters and data
116
+ * @returns Updated accumulated borrowing fee (1e20 precision)
117
+ */
118
+ const getPairBorrowingFees = (input, context) => {
119
+ var _a, _b;
120
+ const { collateralIndex, pairIndex, currentPairPrice, currentTimestamp } = input;
121
+ const params = (_a = context.borrowingParams[collateralIndex]) === null || _a === void 0 ? void 0 : _a[pairIndex];
122
+ const data = (_b = context.borrowingData[collateralIndex]) === null || _b === void 0 ? void 0 : _b[pairIndex];
123
+ if (!params || !data) {
124
+ return 0;
125
+ }
126
+ return (0, exports.getPairPendingAccBorrowingFees)(params, data, currentPairPrice, currentTimestamp !== null && currentTimestamp !== void 0 ? currentTimestamp : context.currentTimestamp);
127
+ };
128
+ exports.getPairBorrowingFees = getPairBorrowingFees;
129
+ /**
130
+ * @dev Utility functions for working with borrowing v2 fees
131
+ */
132
+ exports.borrowingFeeV2Utils = {
133
+ getPairPendingAccBorrowingFees: exports.getPairPendingAccBorrowingFees,
134
+ getTradeBorrowingFeesCollateral: exports.getTradeBorrowingFeesCollateral,
135
+ getPairBorrowingFees: exports.getPairBorrowingFees,
136
+ getBorrowingFee: exports.getBorrowingFee,
137
+ };
138
+ exports.BorrowingFeeV2 = __importStar(require("./types"));
139
+ __exportStar(require("./converter"), exports);
@@ -0,0 +1,79 @@
1
+ /**
2
+ * @dev Types for borrowing v2 fees system (simplified rate-based model)
3
+ */
4
+ /**
5
+ * @dev Borrowing fee parameters for a specific pair/collateral combination
6
+ */
7
+ export type BorrowingFeeParams = {
8
+ /**
9
+ * @dev Borrowing rate % per second
10
+ * @dev Raw contract value divided by 1e10
11
+ * @dev Max: ~0.0000317097 => 1,000% APR
12
+ */
13
+ borrowingRatePerSecondP: number;
14
+ };
15
+ /**
16
+ * @dev Accumulated borrowing fee data for a specific pair/collateral combination
17
+ */
18
+ export type PairBorrowingFeeData = {
19
+ /**
20
+ * @dev Accumulated borrowing fees % weighted by pair price
21
+ * @dev Unit: fee collateral per 100 units of OI in pair amount
22
+ */
23
+ accBorrowingFeeP: number;
24
+ /**
25
+ * @dev Timestamp of last accumulated borrowing fees update
26
+ */
27
+ lastBorrowingUpdateTs: number;
28
+ };
29
+ /**
30
+ * @dev Trade-specific borrowing fee data stored when position is opened
31
+ */
32
+ export type TradeInitialAccFees = {
33
+ /**
34
+ * @dev Initial accumulated borrowing fee when trade was opened (normalized float)
35
+ * @dev Raw contract value divided by 1e20
36
+ * @dev Used to calculate how much borrowing fees the trade owes
37
+ */
38
+ initialAccBorrowingFeeP: number;
39
+ };
40
+ /**
41
+ * @dev Context required for borrowing v2 fee calculations
42
+ */
43
+ export type GetBorrowingFeeV2Context = {
44
+ /**
45
+ * @dev Current timestamp (defaults to Date.now() / 1000)
46
+ */
47
+ currentTimestamp?: number;
48
+ /**
49
+ * @dev Borrowing fee parameters for pairs
50
+ * @dev Indexed by: params[collateralIndex][pairIndex]
51
+ */
52
+ borrowingParams: Record<number, Record<number, BorrowingFeeParams>>;
53
+ /**
54
+ * @dev Borrowing fee data for pairs
55
+ * @dev Indexed by: data[collateralIndex][pairIndex]
56
+ */
57
+ borrowingData: Record<number, Record<number, PairBorrowingFeeData>>;
58
+ };
59
+ /**
60
+ * @dev Input for calculating pending borrowing fees for a pair
61
+ */
62
+ export type PairBorrowingFeeInput = {
63
+ collateralIndex: number;
64
+ pairIndex: number;
65
+ currentPairPrice: number;
66
+ currentTimestamp?: number;
67
+ };
68
+ /**
69
+ * @dev Input for calculating borrowing fees for a specific trade
70
+ */
71
+ export type TradeBorrowingFeeInput = {
72
+ positionSizeCollateral: number;
73
+ openPrice: number;
74
+ collateralIndex: number;
75
+ pairIndex: number;
76
+ currentPairPrice: number;
77
+ initialAccBorrowingFeeP: number;
78
+ currentTimestamp?: number;
79
+ };